YoutubeDL.py 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439
  1. import collections
  2. import contextlib
  3. import copy
  4. import datetime as dt
  5. import errno
  6. import fileinput
  7. import functools
  8. import http.cookiejar
  9. import io
  10. import itertools
  11. import json
  12. import locale
  13. import operator
  14. import os
  15. import random
  16. import re
  17. import shutil
  18. import string
  19. import subprocess
  20. import sys
  21. import tempfile
  22. import time
  23. import tokenize
  24. import traceback
  25. import unicodedata
  26. from .cache import Cache
  27. from .compat import urllib # isort: split
  28. from .compat import urllib_req_to_req
  29. from .cookies import CookieLoadError, LenientSimpleCookie, load_cookies
  30. from .downloader import FFmpegFD, get_suitable_downloader, shorten_protocol_name
  31. from .downloader.rtmp import rtmpdump_version
  32. from .extractor import gen_extractor_classes, get_info_extractor, import_extractors
  33. from .extractor.common import UnsupportedURLIE
  34. from .extractor.openload import PhantomJSwrapper
  35. from .globals import (
  36. IN_CLI,
  37. LAZY_EXTRACTORS,
  38. plugin_ies,
  39. plugin_ies_overrides,
  40. plugin_pps,
  41. all_plugins_loaded,
  42. plugin_dirs,
  43. )
  44. from .minicurses import format_text
  45. from .networking import HEADRequest, Request, RequestDirector
  46. from .networking.common import _REQUEST_HANDLERS, _RH_PREFERENCES
  47. from .networking.exceptions import (
  48. HTTPError,
  49. NoSupportingHandlers,
  50. RequestError,
  51. SSLError,
  52. network_exceptions,
  53. )
  54. from .networking.impersonate import ImpersonateRequestHandler
  55. from .plugins import directories as plugin_directories, load_all_plugins
  56. from .postprocessor import (
  57. EmbedThumbnailPP,
  58. FFmpegFixupDuplicateMoovPP,
  59. FFmpegFixupDurationPP,
  60. FFmpegFixupM3u8PP,
  61. FFmpegFixupM4aPP,
  62. FFmpegFixupStretchedPP,
  63. FFmpegFixupTimestampPP,
  64. FFmpegMergerPP,
  65. FFmpegPostProcessor,
  66. FFmpegVideoConvertorPP,
  67. MoveFilesAfterDownloadPP,
  68. get_postprocessor,
  69. )
  70. from .postprocessor.ffmpeg import resolve_mapping as resolve_recode_mapping
  71. from .update import (
  72. REPOSITORY,
  73. _get_system_deprecation,
  74. _make_label,
  75. current_git_head,
  76. detect_variant,
  77. )
  78. from .utils import (
  79. DEFAULT_OUTTMPL,
  80. IDENTITY,
  81. LINK_TEMPLATES,
  82. MEDIA_EXTENSIONS,
  83. NO_DEFAULT,
  84. NUMBER_RE,
  85. OUTTMPL_TYPES,
  86. POSTPROCESS_WHEN,
  87. STR_FORMAT_RE_TMPL,
  88. STR_FORMAT_TYPES,
  89. ContentTooShortError,
  90. DateRange,
  91. DownloadCancelled,
  92. DownloadError,
  93. EntryNotInPlaylist,
  94. ExistingVideoReached,
  95. ExtractorError,
  96. FormatSorter,
  97. GeoRestrictedError,
  98. ISO3166Utils,
  99. LazyList,
  100. MaxDownloadsReached,
  101. Namespace,
  102. PagedList,
  103. PlaylistEntries,
  104. Popen,
  105. PostProcessingError,
  106. ReExtractInfo,
  107. RejectedVideoReached,
  108. SameFileError,
  109. UnavailableVideoError,
  110. UserNotLive,
  111. YoutubeDLError,
  112. age_restricted,
  113. bug_reports_message,
  114. date_from_str,
  115. deprecation_warning,
  116. determine_ext,
  117. determine_protocol,
  118. encode_compat_str,
  119. escapeHTML,
  120. expand_path,
  121. extract_basic_auth,
  122. filter_dict,
  123. float_or_none,
  124. format_bytes,
  125. format_decimal_suffix,
  126. format_field,
  127. formatSeconds,
  128. get_compatible_ext,
  129. get_domain,
  130. int_or_none,
  131. iri_to_uri,
  132. is_path_like,
  133. join_nonempty,
  134. locked_file,
  135. make_archive_id,
  136. make_dir,
  137. number_of_digits,
  138. orderedSet,
  139. orderedSet_from_options,
  140. parse_filesize,
  141. preferredencoding,
  142. prepend_extension,
  143. remove_terminal_sequences,
  144. render_table,
  145. replace_extension,
  146. sanitize_filename,
  147. sanitize_path,
  148. sanitize_url,
  149. shell_quote,
  150. str_or_none,
  151. strftime_or_none,
  152. subtitles_filename,
  153. supports_terminal_sequences,
  154. system_identifier,
  155. filesize_from_tbr,
  156. timetuple_from_msec,
  157. to_high_limit_path,
  158. traverse_obj,
  159. try_call,
  160. try_get,
  161. url_basename,
  162. variadic,
  163. windows_enable_vt_mode,
  164. write_json_file,
  165. write_string,
  166. )
  167. from .utils._utils import _UnsafeExtensionError, _YDLLogger, _ProgressState
  168. from .utils.networking import (
  169. HTTPHeaderDict,
  170. clean_headers,
  171. clean_proxies,
  172. std_headers,
  173. )
  174. from .version import CHANNEL, ORIGIN, RELEASE_GIT_HEAD, VARIANT, __version__
  175. if os.name == 'nt':
  176. import ctypes
  177. def _catch_unsafe_extension_error(func):
  178. @functools.wraps(func)
  179. def wrapper(self, *args, **kwargs):
  180. try:
  181. return func(self, *args, **kwargs)
  182. except _UnsafeExtensionError as error:
  183. self.report_error(
  184. f'The extracted extension ({error.extension!r}) is unusual '
  185. 'and will be skipped for safety reasons. '
  186. f'If you believe this is an error{bug_reports_message(",")}')
  187. return wrapper
  188. class YoutubeDL:
  189. """YoutubeDL class.
  190. YoutubeDL objects are the ones responsible of downloading the
  191. actual video file and writing it to disk if the user has requested
  192. it, among some other tasks. In most cases there should be one per
  193. program. As, given a video URL, the downloader doesn't know how to
  194. extract all the needed information, task that InfoExtractors do, it
  195. has to pass the URL to one of them.
  196. For this, YoutubeDL objects have a method that allows
  197. InfoExtractors to be registered in a given order. When it is passed
  198. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  199. finds that reports being able to handle it. The InfoExtractor extracts
  200. all the information about the video or videos the URL refers to, and
  201. YoutubeDL process the extracted information, possibly using a File
  202. Downloader to download the video.
  203. YoutubeDL objects accept a lot of parameters. In order not to saturate
  204. the object constructor with arguments, it receives a dictionary of
  205. options instead. These options are available through the params
  206. attribute for the InfoExtractors to use. The YoutubeDL also
  207. registers itself as the downloader in charge for the InfoExtractors
  208. that are added to it, so this is a "mutual registration".
  209. Available options:
  210. username: Username for authentication purposes.
  211. password: Password for authentication purposes.
  212. videopassword: Password for accessing a video.
  213. ap_mso: Adobe Pass multiple-system operator identifier.
  214. ap_username: Multiple-system operator account username.
  215. ap_password: Multiple-system operator account password.
  216. usenetrc: Use netrc for authentication instead.
  217. netrc_location: Location of the netrc file. Defaults to ~/.netrc.
  218. netrc_cmd: Use a shell command to get credentials
  219. verbose: Print additional info to stdout.
  220. quiet: Do not print messages to stdout.
  221. no_warnings: Do not print out anything for warnings.
  222. forceprint: A dict with keys WHEN mapped to a list of templates to
  223. print to stdout. The allowed keys are video or any of the
  224. items in utils.POSTPROCESS_WHEN.
  225. For compatibility, a single list is also accepted
  226. print_to_file: A dict with keys WHEN (same as forceprint) mapped to
  227. a list of tuples with (template, filename)
  228. forcejson: Force printing info_dict as JSON.
  229. dump_single_json: Force printing the info_dict of the whole playlist
  230. (or video) as a single JSON line.
  231. force_write_download_archive: Force writing download archive regardless
  232. of 'skip_download' or 'simulate'.
  233. simulate: Do not download the video files. If unset (or None),
  234. simulate only if listsubtitles, listformats or list_thumbnails is used
  235. format: Video format code. see "FORMAT SELECTION" for more details.
  236. You can also pass a function. The function takes 'ctx' as
  237. argument and returns the formats to download.
  238. See "build_format_selector" for an implementation
  239. allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded.
  240. ignore_no_formats_error: Ignore "No video formats" error. Usefull for
  241. extracting metadata even if the video is not actually
  242. available for download (experimental)
  243. format_sort: A list of fields by which to sort the video formats.
  244. See "Sorting Formats" for more details.
  245. format_sort_force: Force the given format_sort. see "Sorting Formats"
  246. for more details.
  247. prefer_free_formats: Whether to prefer video formats with free containers
  248. over non-free ones of the same quality.
  249. allow_multiple_video_streams: Allow multiple video streams to be merged
  250. into a single file
  251. allow_multiple_audio_streams: Allow multiple audio streams to be merged
  252. into a single file
  253. check_formats Whether to test if the formats are downloadable.
  254. Can be True (check all), False (check none),
  255. 'selected' (check selected formats),
  256. or None (check only if requested by extractor)
  257. paths: Dictionary of output paths. The allowed keys are 'home'
  258. 'temp' and the keys of OUTTMPL_TYPES (in utils/_utils.py)
  259. outtmpl: Dictionary of templates for output names. Allowed keys
  260. are 'default' and the keys of OUTTMPL_TYPES (in utils/_utils.py).
  261. For compatibility with youtube-dl, a single string can also be used
  262. outtmpl_na_placeholder: Placeholder for unavailable meta fields.
  263. restrictfilenames: Do not allow "&" and spaces in file names
  264. trim_file_name: Limit length of filename (extension excluded)
  265. windowsfilenames: True: Force filenames to be Windows compatible
  266. False: Sanitize filenames only minimally
  267. This option has no effect when running on Windows
  268. ignoreerrors: Do not stop on download/postprocessing errors.
  269. Can be 'only_download' to ignore only download errors.
  270. Default is 'only_download' for CLI, but False for API
  271. skip_playlist_after_errors: Number of allowed failures until the rest of
  272. the playlist is skipped
  273. allowed_extractors: List of regexes to match against extractor names that are allowed
  274. overwrites: Overwrite all video and metadata files if True,
  275. overwrite only non-video files if None
  276. and don't overwrite any file if False
  277. playlist_items: Specific indices of playlist to download.
  278. playlistrandom: Download playlist items in random order.
  279. lazy_playlist: Process playlist entries as they are received.
  280. matchtitle: Download only matching titles.
  281. rejecttitle: Reject downloads for matching titles.
  282. logger: A class having a `debug`, `warning` and `error` function where
  283. each has a single string parameter, the message to be logged.
  284. For compatibility reasons, both debug and info messages are passed to `debug`.
  285. A debug message will have a prefix of `[debug] ` to discern it from info messages.
  286. logtostderr: Print everything to stderr instead of stdout.
  287. consoletitle: Display progress in the console window's titlebar.
  288. writedescription: Write the video description to a .description file
  289. writeinfojson: Write the video description to a .info.json file
  290. clean_infojson: Remove internal metadata from the infojson
  291. getcomments: Extract video comments. This will not be written to disk
  292. unless writeinfojson is also given
  293. writeannotations: Write the video annotations to a .annotations.xml file
  294. writethumbnail: Write the thumbnail image to a file
  295. allow_playlist_files: Whether to write playlists' description, infojson etc
  296. also to disk when using the 'write*' options
  297. write_all_thumbnails: Write all thumbnail formats to files
  298. writelink: Write an internet shortcut file, depending on the
  299. current platform (.url/.webloc/.desktop)
  300. writeurllink: Write a Windows internet shortcut file (.url)
  301. writewebloclink: Write a macOS internet shortcut file (.webloc)
  302. writedesktoplink: Write a Linux internet shortcut file (.desktop)
  303. writesubtitles: Write the video subtitles to a file
  304. writeautomaticsub: Write the automatically generated subtitles to a file
  305. listsubtitles: Lists all available subtitles for the video
  306. subtitlesformat: The format code for subtitles
  307. subtitleslangs: List of languages of the subtitles to download (can be regex).
  308. The list may contain "all" to refer to all the available
  309. subtitles. The language can be prefixed with a "-" to
  310. exclude it from the requested languages, e.g. ['all', '-live_chat']
  311. keepvideo: Keep the video file after post-processing
  312. daterange: A utils.DateRange object, download only if the upload_date is in the range.
  313. skip_download: Skip the actual download of the video file
  314. cachedir: Location of the cache files in the filesystem.
  315. False to disable filesystem cache.
  316. noplaylist: Download single video instead of a playlist if in doubt.
  317. age_limit: An integer representing the user's age in years.
  318. Unsuitable videos for the given age are skipped.
  319. min_views: An integer representing the minimum view count the video
  320. must have in order to not be skipped.
  321. Videos without view count information are always
  322. downloaded. None for no limit.
  323. max_views: An integer representing the maximum view count.
  324. Videos that are more popular than that are not
  325. downloaded.
  326. Videos without view count information are always
  327. downloaded. None for no limit.
  328. download_archive: A set, or the name of a file where all downloads are recorded.
  329. Videos already present in the file are not downloaded again.
  330. break_on_existing: Stop the download process after attempting to download a
  331. file that is in the archive.
  332. break_per_url: Whether break_on_reject and break_on_existing
  333. should act on each input URL as opposed to for the entire queue
  334. cookiefile: File name or text stream from where cookies should be read and dumped to
  335. cookiesfrombrowser: A tuple containing the name of the browser, the profile
  336. name/path from where cookies are loaded, the name of the keyring,
  337. and the container name, e.g. ('chrome', ) or
  338. ('vivaldi', 'default', 'BASICTEXT') or ('firefox', 'default', None, 'Meta')
  339. legacyserverconnect: Explicitly allow HTTPS connection to servers that do not
  340. support RFC 5746 secure renegotiation
  341. nocheckcertificate: Do not verify SSL certificates
  342. client_certificate: Path to client certificate file in PEM format. May include the private key
  343. client_certificate_key: Path to private key file for client certificate
  344. client_certificate_password: Password for client certificate private key, if encrypted.
  345. If not provided and the key is encrypted, yt-dlp will ask interactively
  346. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  347. (Only supported by some extractors)
  348. enable_file_urls: Enable file:// URLs. This is disabled by default for security reasons.
  349. http_headers: A dictionary of custom headers to be used for all requests
  350. proxy: URL of the proxy server to use
  351. geo_verification_proxy: URL of the proxy to use for IP address verification
  352. on geo-restricted sites.
  353. socket_timeout: Time to wait for unresponsive hosts, in seconds
  354. bidi_workaround: Work around buggy terminals without bidirectional text
  355. support, using fridibi
  356. debug_printtraffic:Print out sent and received HTTP traffic
  357. default_search: Prepend this string if an input url is not valid.
  358. 'auto' for elaborate guessing
  359. encoding: Use this encoding instead of the system-specified.
  360. extract_flat: Whether to resolve and process url_results further
  361. * False: Always process. Default for API
  362. * True: Never process
  363. * 'in_playlist': Do not process inside playlist/multi_video
  364. * 'discard': Always process, but don't return the result
  365. from inside playlist/multi_video
  366. * 'discard_in_playlist': Same as "discard", but only for
  367. playlists (not multi_video). Default for CLI
  368. wait_for_video: If given, wait for scheduled streams to become available.
  369. The value should be a tuple containing the range
  370. (min_secs, max_secs) to wait between retries
  371. postprocessors: A list of dictionaries, each with an entry
  372. * key: The name of the postprocessor. See
  373. yt_dlp/postprocessor/__init__.py for a list.
  374. * when: When to run the postprocessor. Allowed values are
  375. the entries of utils.POSTPROCESS_WHEN
  376. Assumed to be 'post_process' if not given
  377. progress_hooks: A list of functions that get called on download
  378. progress, with a dictionary with the entries
  379. * status: One of "downloading", "error", or "finished".
  380. Check this first and ignore unknown values.
  381. * info_dict: The extracted info_dict
  382. If status is one of "downloading", or "finished", the
  383. following properties may also be present:
  384. * filename: The final filename (always present)
  385. * tmpfilename: The filename we're currently writing to
  386. * downloaded_bytes: Bytes on disk
  387. * total_bytes: Size of the whole file, None if unknown
  388. * total_bytes_estimate: Guess of the eventual file size,
  389. None if unavailable.
  390. * elapsed: The number of seconds since download started.
  391. * eta: The estimated time in seconds, None if unknown
  392. * speed: The download speed in bytes/second, None if
  393. unknown
  394. * fragment_index: The counter of the currently
  395. downloaded video fragment.
  396. * fragment_count: The number of fragments (= individual
  397. files that will be merged)
  398. Progress hooks are guaranteed to be called at least once
  399. (with status "finished") if the download is successful.
  400. postprocessor_hooks: A list of functions that get called on postprocessing
  401. progress, with a dictionary with the entries
  402. * status: One of "started", "processing", or "finished".
  403. Check this first and ignore unknown values.
  404. * postprocessor: Name of the postprocessor
  405. * info_dict: The extracted info_dict
  406. Progress hooks are guaranteed to be called at least twice
  407. (with status "started" and "finished") if the processing is successful.
  408. merge_output_format: "/" separated list of extensions to use when merging formats.
  409. final_ext: Expected final extension; used to detect when the file was
  410. already downloaded and converted
  411. fixup: Automatically correct known faults of the file.
  412. One of:
  413. - "never": do nothing
  414. - "warn": only emit a warning
  415. - "detect_or_warn": check whether we can do anything
  416. about it, warn otherwise (default)
  417. source_address: Client-side IP address to bind to.
  418. impersonate: Client to impersonate for requests.
  419. An ImpersonateTarget (from yt_dlp.networking.impersonate)
  420. sleep_interval_requests: Number of seconds to sleep between requests
  421. during extraction
  422. sleep_interval: Number of seconds to sleep before each download when
  423. used alone or a lower bound of a range for randomized
  424. sleep before each download (minimum possible number
  425. of seconds to sleep) when used along with
  426. max_sleep_interval.
  427. max_sleep_interval:Upper bound of a range for randomized sleep before each
  428. download (maximum possible number of seconds to sleep).
  429. Must only be used along with sleep_interval.
  430. Actual sleep time will be a random float from range
  431. [sleep_interval; max_sleep_interval].
  432. sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
  433. listformats: Print an overview of available video formats and exit.
  434. list_thumbnails: Print a table of all thumbnails and exit.
  435. match_filter: A function that gets called for every video with the signature
  436. (info_dict, *, incomplete: bool) -> Optional[str]
  437. For backward compatibility with youtube-dl, the signature
  438. (info_dict) -> Optional[str] is also allowed.
  439. - If it returns a message, the video is ignored.
  440. - If it returns None, the video is downloaded.
  441. - If it returns utils.NO_DEFAULT, the user is interactively
  442. asked whether to download the video.
  443. - Raise utils.DownloadCancelled(msg) to abort remaining
  444. downloads when a video is rejected.
  445. match_filter_func in utils/_utils.py is one example for this.
  446. color: A Dictionary with output stream names as keys
  447. and their respective color policy as values.
  448. Can also just be a single color policy,
  449. in which case it applies to all outputs.
  450. Valid stream names are 'stdout' and 'stderr'.
  451. Valid color policies are one of 'always', 'auto',
  452. 'no_color', 'never', 'auto-tty' or 'no_color-tty'.
  453. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
  454. HTTP header
  455. geo_bypass_country:
  456. Two-letter ISO 3166-2 country code that will be used for
  457. explicit geographic restriction bypassing via faking
  458. X-Forwarded-For HTTP header
  459. geo_bypass_ip_block:
  460. IP range in CIDR notation that will be used similarly to
  461. geo_bypass_country
  462. external_downloader: A dictionary of protocol keys and the executable of the
  463. external downloader to use for it. The allowed protocols
  464. are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
  465. Set the value to 'native' to use the native downloader
  466. compat_opts: Compatibility options. See "Differences in default behavior".
  467. The following options do not work when used through the API:
  468. filename, abort-on-error, multistreams, no-live-chat,
  469. format-sort, no-clean-infojson, no-playlist-metafiles,
  470. no-keep-subs, no-attach-info-json, allow-unsafe-ext, prefer-vp9-sort.
  471. Refer __init__.py for their implementation
  472. progress_template: Dictionary of templates for progress outputs.
  473. Allowed keys are 'download', 'postprocess',
  474. 'download-title' (console title) and 'postprocess-title'.
  475. The template is mapped on a dictionary with keys 'progress' and 'info'
  476. retry_sleep_functions: Dictionary of functions that takes the number of attempts
  477. as argument and returns the time to sleep in seconds.
  478. Allowed keys are 'http', 'fragment', 'file_access'
  479. download_ranges: A callback function that gets called for every video with
  480. the signature (info_dict, ydl) -> Iterable[Section].
  481. Only the returned sections will be downloaded.
  482. Each Section is a dict with the following keys:
  483. * start_time: Start time of the section in seconds
  484. * end_time: End time of the section in seconds
  485. * title: Section title (Optional)
  486. * index: Section number (Optional)
  487. force_keyframes_at_cuts: Re-encode the video when downloading ranges to get precise cuts
  488. noprogress: Do not print the progress bar
  489. live_from_start: Whether to download livestreams videos from the start
  490. The following parameters are not used by YoutubeDL itself, they are used by
  491. the downloader (see yt_dlp/downloader/common.py):
  492. nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
  493. max_filesize, test, noresizebuffer, retries, file_access_retries, fragment_retries,
  494. continuedl, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
  495. external_downloader_args, concurrent_fragment_downloads, progress_delta.
  496. The following options are used by the post processors:
  497. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
  498. to the binary or its containing directory.
  499. postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
  500. and a list of additional command-line arguments for the
  501. postprocessor/executable. The dict can also have "PP+EXE" keys
  502. which are used when the given exe is used by the given PP.
  503. Use 'default' as the name for arguments to passed to all PP
  504. For compatibility with youtube-dl, a single list of args
  505. can also be used
  506. The following options are used by the extractors:
  507. extractor_retries: Number of times to retry for known errors (default: 3)
  508. dynamic_mpd: Whether to process dynamic DASH manifests (default: True)
  509. hls_split_discontinuity: Split HLS playlists into different formats at
  510. discontinuities such as ad breaks (default: False)
  511. extractor_args: A dictionary of arguments to be passed to the extractors.
  512. See "EXTRACTOR ARGUMENTS" for details.
  513. E.g. {'youtube': {'skip': ['dash', 'hls']}}
  514. mark_watched: Mark videos watched (even with --simulate). Only for YouTube
  515. The following options are deprecated and may be removed in the future:
  516. break_on_reject: Stop the download process when encountering a video that
  517. has been filtered out.
  518. - `raise DownloadCancelled(msg)` in match_filter instead
  519. force_generic_extractor: Force downloader to use the generic extractor
  520. - Use allowed_extractors = ['generic', 'default']
  521. playliststart: - Use playlist_items
  522. Playlist item to start at.
  523. playlistend: - Use playlist_items
  524. Playlist item to end at.
  525. playlistreverse: - Use playlist_items
  526. Download playlist items in reverse order.
  527. forceurl: - Use forceprint
  528. Force printing final URL.
  529. forcetitle: - Use forceprint
  530. Force printing title.
  531. forceid: - Use forceprint
  532. Force printing ID.
  533. forcethumbnail: - Use forceprint
  534. Force printing thumbnail URL.
  535. forcedescription: - Use forceprint
  536. Force printing description.
  537. forcefilename: - Use forceprint
  538. Force printing final filename.
  539. forceduration: - Use forceprint
  540. Force printing duration.
  541. allsubtitles: - Use subtitleslangs = ['all']
  542. Downloads all the subtitles of the video
  543. (requires writesubtitles or writeautomaticsub)
  544. include_ads: - Doesn't work
  545. Download ads as well
  546. call_home: - Not implemented
  547. Boolean, true if we are allowed to contact the
  548. yt-dlp servers for debugging.
  549. post_hooks: - Register a custom postprocessor
  550. A list of functions that get called as the final step
  551. for each video file, after all postprocessors have been
  552. called. The filename will be passed as the only argument.
  553. hls_prefer_native: - Use external_downloader = {'m3u8': 'native'} or {'m3u8': 'ffmpeg'}.
  554. Use the native HLS downloader instead of ffmpeg/avconv
  555. if True, otherwise use ffmpeg/avconv if False, otherwise
  556. use downloader suggested by extractor if None.
  557. prefer_ffmpeg: - avconv support is deprecated
  558. If False, use avconv instead of ffmpeg if both are available,
  559. otherwise prefer ffmpeg.
  560. youtube_include_dash_manifest: - Use extractor_args
  561. If True (default), DASH manifests and related
  562. data will be downloaded and processed by extractor.
  563. You can reduce network I/O by disabling it if you don't
  564. care about DASH. (only for youtube)
  565. youtube_include_hls_manifest: - Use extractor_args
  566. If True (default), HLS manifests and related
  567. data will be downloaded and processed by extractor.
  568. You can reduce network I/O by disabling it if you don't
  569. care about HLS. (only for youtube)
  570. no_color: Same as `color='no_color'`
  571. no_overwrites: Same as `overwrites=False`
  572. """
  573. _NUMERIC_FIELDS = {
  574. 'width', 'height', 'asr', 'audio_channels', 'fps',
  575. 'tbr', 'abr', 'vbr', 'filesize', 'filesize_approx',
  576. 'timestamp', 'release_timestamp',
  577. 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
  578. 'average_rating', 'comment_count', 'age_limit',
  579. 'start_time', 'end_time',
  580. 'chapter_number', 'season_number', 'episode_number',
  581. 'track_number', 'disc_number', 'release_year',
  582. }
  583. _format_fields = {
  584. # NB: Keep in sync with the docstring of extractor/common.py
  585. 'url', 'manifest_url', 'manifest_stream_number', 'ext', 'format', 'format_id', 'format_note',
  586. 'width', 'height', 'aspect_ratio', 'resolution', 'dynamic_range', 'tbr', 'abr', 'acodec', 'asr', 'audio_channels',
  587. 'vbr', 'fps', 'vcodec', 'container', 'filesize', 'filesize_approx', 'rows', 'columns', 'hls_media_playlist_data',
  588. 'player_url', 'protocol', 'fragment_base_url', 'fragments', 'is_from_start', 'is_dash_periods', 'request_data',
  589. 'preference', 'language', 'language_preference', 'quality', 'source_preference', 'cookies',
  590. 'http_headers', 'stretched_ratio', 'no_resume', 'has_drm', 'extra_param_to_segment_url', 'extra_param_to_key_url',
  591. 'hls_aes', 'downloader_options', 'page_url', 'app', 'play_path', 'tc_url', 'flash_version',
  592. 'rtmp_live', 'rtmp_conn', 'rtmp_protocol', 'rtmp_real_time',
  593. }
  594. _deprecated_multivalue_fields = {
  595. 'album_artist': 'album_artists',
  596. 'artist': 'artists',
  597. 'composer': 'composers',
  598. 'creator': 'creators',
  599. 'genre': 'genres',
  600. }
  601. _format_selection_exts = {
  602. 'audio': set(MEDIA_EXTENSIONS.common_audio),
  603. 'video': {*MEDIA_EXTENSIONS.common_video, '3gp'},
  604. 'storyboards': set(MEDIA_EXTENSIONS.storyboards),
  605. }
  606. def __init__(self, params=None, auto_init=True):
  607. """Create a FileDownloader object with the given options.
  608. @param auto_init Whether to load the default extractors and print header (if verbose).
  609. Set to 'no_verbose_header' to not print the header
  610. """
  611. if params is None:
  612. params = {}
  613. self.params = params
  614. self._ies = {}
  615. self._ies_instances = {}
  616. self._pps = {k: [] for k in POSTPROCESS_WHEN}
  617. self._printed_messages = set()
  618. self._first_webpage_request = True
  619. self._post_hooks = []
  620. self._progress_hooks = []
  621. self._postprocessor_hooks = []
  622. self._download_retcode = 0
  623. self._num_downloads = 0
  624. self._num_videos = 0
  625. self._playlist_level = 0
  626. self._playlist_urls = set()
  627. self.cache = Cache(self)
  628. self.__header_cookies = []
  629. # compat for API: load plugins if they have not already
  630. if not all_plugins_loaded.value:
  631. load_all_plugins()
  632. stdout = sys.stderr if self.params.get('logtostderr') else sys.stdout
  633. self._out_files = Namespace(
  634. out=stdout,
  635. error=sys.stderr,
  636. screen=sys.stderr if self.params.get('quiet') else stdout,
  637. )
  638. try:
  639. windows_enable_vt_mode()
  640. except Exception as e:
  641. self.write_debug(f'Failed to enable VT mode: {e}')
  642. # hehe "immutable" namespace
  643. self._out_files.console = next(filter(supports_terminal_sequences, (sys.stderr, sys.stdout)), None)
  644. if self.params.get('no_color'):
  645. if self.params.get('color') is not None:
  646. self.params.setdefault('_warnings', []).append(
  647. 'Overwriting params from "color" with "no_color"')
  648. self.params['color'] = 'no_color'
  649. term_allow_color = os.getenv('TERM', '').lower() != 'dumb'
  650. base_no_color = bool(os.getenv('NO_COLOR'))
  651. def process_color_policy(stream):
  652. stream_name = {sys.stdout: 'stdout', sys.stderr: 'stderr'}[stream]
  653. policy = traverse_obj(self.params, ('color', (stream_name, None), {str}, any)) or 'auto'
  654. if policy in ('auto', 'auto-tty', 'no_color-tty'):
  655. no_color = base_no_color
  656. if policy.endswith('tty'):
  657. no_color = policy.startswith('no_color')
  658. if term_allow_color and supports_terminal_sequences(stream):
  659. return 'no_color' if no_color else True
  660. return False
  661. assert policy in ('always', 'never', 'no_color'), policy
  662. return {'always': True, 'never': False}.get(policy, policy)
  663. self._allow_colors = Namespace(**{
  664. name: process_color_policy(stream)
  665. for name, stream in self._out_files.items_ if name != 'console'
  666. })
  667. system_deprecation = _get_system_deprecation()
  668. if system_deprecation:
  669. self.deprecated_feature(system_deprecation.replace('\n', '\n '))
  670. if self.params.get('allow_unplayable_formats'):
  671. self.report_warning(
  672. f'You have asked for {self._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. '
  673. 'This is a developer option intended for debugging. \n'
  674. ' If you experience any issues while using this option, '
  675. f'{self._format_err("DO NOT", self.Styles.ERROR)} open a bug report')
  676. if self.params.get('bidi_workaround', False):
  677. try:
  678. import pty
  679. master, slave = pty.openpty()
  680. width = shutil.get_terminal_size().columns
  681. width_args = [] if width is None else ['-w', str(width)]
  682. sp_kwargs = {'stdin': subprocess.PIPE, 'stdout': slave, 'stderr': self._out_files.error}
  683. try:
  684. self._output_process = Popen(['bidiv', *width_args], **sp_kwargs)
  685. except OSError:
  686. self._output_process = Popen(['fribidi', '-c', 'UTF-8', *width_args], **sp_kwargs)
  687. self._output_channel = os.fdopen(master, 'rb')
  688. except OSError as ose:
  689. if ose.errno == errno.ENOENT:
  690. self.report_warning(
  691. 'Could not find fribidi executable, ignoring --bidi-workaround. '
  692. 'Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  693. else:
  694. raise
  695. self.params['compat_opts'] = set(self.params.get('compat_opts', ()))
  696. self.params['http_headers'] = HTTPHeaderDict(std_headers, self.params.get('http_headers'))
  697. self._load_cookies(self.params['http_headers'].get('Cookie')) # compat
  698. self.params['http_headers'].pop('Cookie', None)
  699. if auto_init and auto_init != 'no_verbose_header':
  700. self.print_debug_header()
  701. def check_deprecated(param, option, suggestion):
  702. if self.params.get(param) is not None:
  703. self.report_warning(f'{option} is deprecated. Use {suggestion} instead')
  704. return True
  705. return False
  706. if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
  707. if self.params.get('geo_verification_proxy') is None:
  708. self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
  709. check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
  710. check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
  711. check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"')
  712. for msg in self.params.get('_warnings', []):
  713. self.report_warning(msg)
  714. for msg in self.params.get('_deprecation_warnings', []):
  715. self.deprecated_feature(msg)
  716. if impersonate_target := self.params.get('impersonate'):
  717. if not self._impersonate_target_available(impersonate_target):
  718. raise YoutubeDLError(
  719. f'Impersonate target "{impersonate_target}" is not available. '
  720. f'Use --list-impersonate-targets to see available targets. '
  721. f'You may be missing dependencies required to support this target.')
  722. if 'list-formats' in self.params['compat_opts']:
  723. self.params['listformats_table'] = False
  724. if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
  725. # nooverwrites was unnecessarily changed to overwrites
  726. # in 0c3d0f51778b153f65c21906031c2e091fcfb641
  727. # This ensures compatibility with both keys
  728. self.params['overwrites'] = not self.params['nooverwrites']
  729. elif self.params.get('overwrites') is None:
  730. self.params.pop('overwrites', None)
  731. else:
  732. self.params['nooverwrites'] = not self.params['overwrites']
  733. if self.params.get('simulate') is None and any((
  734. self.params.get('list_thumbnails'),
  735. self.params.get('listformats'),
  736. self.params.get('listsubtitles'),
  737. )):
  738. self.params['simulate'] = 'list_only'
  739. self.params.setdefault('forceprint', {})
  740. self.params.setdefault('print_to_file', {})
  741. # Compatibility with older syntax
  742. if not isinstance(params['forceprint'], dict):
  743. self.params['forceprint'] = {'video': params['forceprint']}
  744. if auto_init:
  745. self.add_default_info_extractors()
  746. if (sys.platform != 'win32'
  747. and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  748. and not self.params.get('restrictfilenames', False)):
  749. # Unicode filesystem API will throw errors (#1474, #13027)
  750. self.report_warning(
  751. 'Assuming --restrict-filenames since file system encoding '
  752. 'cannot encode all characters. '
  753. 'Set the LC_ALL environment variable to fix this.')
  754. self.params['restrictfilenames'] = True
  755. self._parse_outtmpl()
  756. # Creating format selector here allows us to catch syntax errors before the extraction
  757. self.format_selector = (
  758. self.params.get('format') if self.params.get('format') in (None, '-')
  759. else self.params['format'] if callable(self.params['format'])
  760. else self.build_format_selector(self.params['format']))
  761. hooks = {
  762. 'post_hooks': self.add_post_hook,
  763. 'progress_hooks': self.add_progress_hook,
  764. 'postprocessor_hooks': self.add_postprocessor_hook,
  765. }
  766. for opt, fn in hooks.items():
  767. for ph in self.params.get(opt, []):
  768. fn(ph)
  769. for pp_def_raw in self.params.get('postprocessors', []):
  770. pp_def = dict(pp_def_raw)
  771. when = pp_def.pop('when', 'post_process')
  772. self.add_post_processor(
  773. get_postprocessor(pp_def.pop('key'))(self, **pp_def),
  774. when=when)
  775. def preload_download_archive(fn):
  776. """Preload the archive, if any is specified"""
  777. archive = set()
  778. if fn is None:
  779. return archive
  780. elif not is_path_like(fn):
  781. return fn
  782. self.write_debug(f'Loading archive file {fn!r}')
  783. try:
  784. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  785. for line in archive_file:
  786. archive.add(line.strip())
  787. except OSError as ioe:
  788. if ioe.errno != errno.ENOENT:
  789. raise
  790. return archive
  791. self.archive = preload_download_archive(self.params.get('download_archive'))
  792. def warn_if_short_id(self, argv):
  793. # short YouTube ID starting with dash?
  794. idxs = [
  795. i for i, a in enumerate(argv)
  796. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  797. if idxs:
  798. correct_argv = (
  799. ['yt-dlp']
  800. + [a for i, a in enumerate(argv) if i not in idxs]
  801. + ['--'] + [argv[i] for i in idxs]
  802. )
  803. self.report_warning(
  804. 'Long argument string detected. '
  805. f'Use -- to separate parameters and URLs, like this:\n{shell_quote(correct_argv)}')
  806. def add_info_extractor(self, ie):
  807. """Add an InfoExtractor object to the end of the list."""
  808. ie_key = ie.ie_key()
  809. self._ies[ie_key] = ie
  810. if not isinstance(ie, type):
  811. self._ies_instances[ie_key] = ie
  812. ie.set_downloader(self)
  813. def get_info_extractor(self, ie_key):
  814. """
  815. Get an instance of an IE with name ie_key, it will try to get one from
  816. the _ies list, if there's no instance it will create a new one and add
  817. it to the extractor list.
  818. """
  819. ie = self._ies_instances.get(ie_key)
  820. if ie is None:
  821. ie = get_info_extractor(ie_key)()
  822. self.add_info_extractor(ie)
  823. return ie
  824. def add_default_info_extractors(self):
  825. """
  826. Add the InfoExtractors returned by gen_extractors to the end of the list
  827. """
  828. all_ies = {ie.IE_NAME.lower(): ie for ie in gen_extractor_classes()}
  829. all_ies['end'] = UnsupportedURLIE()
  830. try:
  831. ie_names = orderedSet_from_options(
  832. self.params.get('allowed_extractors', ['default']), {
  833. 'all': list(all_ies),
  834. 'default': [name for name, ie in all_ies.items() if ie._ENABLED],
  835. }, use_regex=True)
  836. except re.error as e:
  837. raise ValueError(f'Wrong regex for allowed_extractors: {e.pattern}')
  838. for name in ie_names:
  839. self.add_info_extractor(all_ies[name])
  840. self.write_debug(f'Loaded {len(ie_names)} extractors')
  841. def add_post_processor(self, pp, when='post_process'):
  842. """Add a PostProcessor object to the end of the chain."""
  843. assert when in POSTPROCESS_WHEN, f'Invalid when={when}'
  844. self._pps[when].append(pp)
  845. pp.set_downloader(self)
  846. def add_post_hook(self, ph):
  847. """Add the post hook"""
  848. self._post_hooks.append(ph)
  849. def add_progress_hook(self, ph):
  850. """Add the download progress hook"""
  851. self._progress_hooks.append(ph)
  852. def add_postprocessor_hook(self, ph):
  853. """Add the postprocessing progress hook"""
  854. self._postprocessor_hooks.append(ph)
  855. for pps in self._pps.values():
  856. for pp in pps:
  857. pp.add_progress_hook(ph)
  858. def _bidi_workaround(self, message):
  859. if not hasattr(self, '_output_channel'):
  860. return message
  861. assert hasattr(self, '_output_process')
  862. assert isinstance(message, str)
  863. line_count = message.count('\n') + 1
  864. self._output_process.stdin.write((message + '\n').encode())
  865. self._output_process.stdin.flush()
  866. res = ''.join(self._output_channel.readline().decode()
  867. for _ in range(line_count))
  868. return res[:-len('\n')]
  869. def _write_string(self, message, out=None, only_once=False):
  870. if only_once:
  871. if message in self._printed_messages:
  872. return
  873. self._printed_messages.add(message)
  874. write_string(message, out=out, encoding=self.params.get('encoding'))
  875. def to_stdout(self, message, skip_eol=False, quiet=None):
  876. """Print message to stdout"""
  877. if quiet is not None:
  878. self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. '
  879. 'Use "YoutubeDL.to_screen" instead')
  880. if skip_eol is not False:
  881. self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. '
  882. 'Use "YoutubeDL.to_screen" instead')
  883. self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out)
  884. def to_screen(self, message, skip_eol=False, quiet=None, only_once=False):
  885. """Print message to screen if not in quiet mode"""
  886. if self.params.get('logger'):
  887. self.params['logger'].debug(message)
  888. return
  889. if (self.params.get('quiet') if quiet is None else quiet) and not self.params.get('verbose'):
  890. return
  891. self._write_string(
  892. '{}{}'.format(self._bidi_workaround(message), ('' if skip_eol else '\n')),
  893. self._out_files.screen, only_once=only_once)
  894. def to_stderr(self, message, only_once=False):
  895. """Print message to stderr"""
  896. assert isinstance(message, str)
  897. if self.params.get('logger'):
  898. self.params['logger'].error(message)
  899. else:
  900. self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.error, only_once=only_once)
  901. def _send_console_code(self, code):
  902. if not supports_terminal_sequences(self._out_files.console):
  903. return False
  904. self._write_string(code, self._out_files.console)
  905. return True
  906. def to_console_title(self, message=None, progress_state=None, percent=None):
  907. if not self.params.get('consoletitle'):
  908. return
  909. if message:
  910. success = self._send_console_code(f'\033]0;{remove_terminal_sequences(message)}\007')
  911. if not success and os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  912. ctypes.windll.kernel32.SetConsoleTitleW(message)
  913. if isinstance(progress_state, _ProgressState):
  914. self._send_console_code(progress_state.get_ansi_escape(percent))
  915. def save_console_title(self):
  916. if not self.params.get('consoletitle') or self.params.get('simulate'):
  917. return
  918. self._send_console_code('\033[22;0t') # Save the title on stack
  919. def restore_console_title(self):
  920. if not self.params.get('consoletitle') or self.params.get('simulate'):
  921. return
  922. self._send_console_code('\033[23;0t') # Restore the title from stack
  923. def __enter__(self):
  924. self.save_console_title()
  925. self.to_console_title(progress_state=_ProgressState.INDETERMINATE)
  926. return self
  927. def save_cookies(self):
  928. if self.params.get('cookiefile') is not None:
  929. self.cookiejar.save()
  930. def __exit__(self, *args):
  931. self.restore_console_title()
  932. self.to_console_title(progress_state=_ProgressState.HIDDEN)
  933. self.close()
  934. def close(self):
  935. self.save_cookies()
  936. if '_request_director' in self.__dict__:
  937. self._request_director.close()
  938. del self._request_director
  939. def trouble(self, message=None, tb=None, is_error=True):
  940. """Determine action to take when a download problem appears.
  941. Depending on if the downloader has been configured to ignore
  942. download errors or not, this method may throw an exception or
  943. not when errors are found, after printing the message.
  944. @param tb If given, is additional traceback information
  945. @param is_error Whether to raise error according to ignorerrors
  946. """
  947. if message is not None:
  948. self.to_stderr(message)
  949. if self.params.get('verbose'):
  950. if tb is None:
  951. if sys.exc_info()[0]: # if .trouble has been called from an except block
  952. tb = ''
  953. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  954. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  955. tb += encode_compat_str(traceback.format_exc())
  956. else:
  957. tb_data = traceback.format_list(traceback.extract_stack())
  958. tb = ''.join(tb_data)
  959. if tb:
  960. self.to_stderr(tb)
  961. if not is_error:
  962. return
  963. if not self.params.get('ignoreerrors'):
  964. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  965. exc_info = sys.exc_info()[1].exc_info
  966. else:
  967. exc_info = sys.exc_info()
  968. raise DownloadError(message, exc_info)
  969. self._download_retcode = 1
  970. Styles = Namespace(
  971. HEADERS='yellow',
  972. EMPHASIS='light blue',
  973. FILENAME='green',
  974. ID='green',
  975. DELIM='blue',
  976. ERROR='red',
  977. BAD_FORMAT='light red',
  978. WARNING='yellow',
  979. SUPPRESS='light black',
  980. )
  981. def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False):
  982. text = str(text)
  983. if test_encoding:
  984. original_text = text
  985. # handle.encoding can be None. See https://github.com/yt-dlp/yt-dlp/issues/2711
  986. encoding = self.params.get('encoding') or getattr(handle, 'encoding', None) or 'ascii'
  987. text = text.encode(encoding, 'ignore').decode(encoding)
  988. if fallback is not None and text != original_text:
  989. text = fallback
  990. return format_text(text, f) if allow_colors is True else text if fallback is None else fallback
  991. def _format_out(self, *args, **kwargs):
  992. return self._format_text(self._out_files.out, self._allow_colors.out, *args, **kwargs)
  993. def _format_screen(self, *args, **kwargs):
  994. return self._format_text(self._out_files.screen, self._allow_colors.screen, *args, **kwargs)
  995. def _format_err(self, *args, **kwargs):
  996. return self._format_text(self._out_files.error, self._allow_colors.error, *args, **kwargs)
  997. def report_warning(self, message, only_once=False):
  998. """
  999. Print the message to stderr, it will be prefixed with 'WARNING:'
  1000. If stderr is a tty file the 'WARNING:' will be colored
  1001. """
  1002. if self.params.get('logger') is not None:
  1003. self.params['logger'].warning(message)
  1004. else:
  1005. if self.params.get('no_warnings'):
  1006. return
  1007. self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
  1008. def deprecation_warning(self, message, *, stacklevel=0):
  1009. deprecation_warning(
  1010. message, stacklevel=stacklevel + 1, printer=self.report_error, is_error=False)
  1011. def deprecated_feature(self, message):
  1012. if self.params.get('logger') is not None:
  1013. self.params['logger'].warning(f'Deprecated Feature: {message}')
  1014. self.to_stderr(f'{self._format_err("Deprecated Feature:", self.Styles.ERROR)} {message}', True)
  1015. def report_error(self, message, *args, **kwargs):
  1016. """
  1017. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  1018. in red if stderr is a tty file.
  1019. """
  1020. self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
  1021. def write_debug(self, message, only_once=False):
  1022. """Log debug message or Print message to stderr"""
  1023. if not self.params.get('verbose', False):
  1024. return
  1025. message = f'[debug] {message}'
  1026. if self.params.get('logger'):
  1027. self.params['logger'].debug(message)
  1028. else:
  1029. self.to_stderr(message, only_once)
  1030. def report_file_already_downloaded(self, file_name):
  1031. """Report file has already been fully downloaded."""
  1032. try:
  1033. self.to_screen(f'[download] {file_name} has already been downloaded')
  1034. except UnicodeEncodeError:
  1035. self.to_screen('[download] The file has already been downloaded')
  1036. def report_file_delete(self, file_name):
  1037. """Report that existing file will be deleted."""
  1038. try:
  1039. self.to_screen(f'Deleting existing file {file_name}')
  1040. except UnicodeEncodeError:
  1041. self.to_screen('Deleting existing file')
  1042. def raise_no_formats(self, info, forced=False, *, msg=None):
  1043. has_drm = info.get('_has_drm')
  1044. ignored, expected = self.params.get('ignore_no_formats_error'), bool(msg)
  1045. msg = msg or (has_drm and 'This video is DRM protected') or 'No video formats found!'
  1046. if forced or not ignored:
  1047. raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'],
  1048. expected=has_drm or ignored or expected)
  1049. else:
  1050. self.report_warning(msg)
  1051. def parse_outtmpl(self):
  1052. self.deprecation_warning('"YoutubeDL.parse_outtmpl" is deprecated and may be removed in a future version')
  1053. self._parse_outtmpl()
  1054. return self.params['outtmpl']
  1055. def _parse_outtmpl(self):
  1056. sanitize = IDENTITY
  1057. if self.params.get('restrictfilenames'): # Remove spaces in the default template
  1058. sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-')
  1059. outtmpl = self.params.setdefault('outtmpl', {})
  1060. if not isinstance(outtmpl, dict):
  1061. self.params['outtmpl'] = outtmpl = {'default': outtmpl}
  1062. outtmpl.update({k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items() if outtmpl.get(k) is None})
  1063. def get_output_path(self, dir_type='', filename=None):
  1064. paths = self.params.get('paths', {})
  1065. assert isinstance(paths, dict), '"paths" parameter must be a dictionary'
  1066. path = os.path.join(
  1067. expand_path(paths.get('home', '').strip()),
  1068. expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
  1069. filename or '')
  1070. return sanitize_path(path, force=self.params.get('windowsfilenames'))
  1071. @staticmethod
  1072. def _outtmpl_expandpath(outtmpl):
  1073. # expand_path translates '%%' into '%' and '$$' into '$'
  1074. # correspondingly that is not what we want since we need to keep
  1075. # '%%' intact for template dict substitution step. Working around
  1076. # with boundary-alike separator hack.
  1077. sep = ''.join(random.choices(string.ascii_letters, k=32))
  1078. outtmpl = outtmpl.replace('%%', f'%{sep}%').replace('$$', f'${sep}$')
  1079. # outtmpl should be expand_path'ed before template dict substitution
  1080. # because meta fields may contain env variables we don't want to
  1081. # be expanded. E.g. for outtmpl "%(title)s.%(ext)s" and
  1082. # title "Hello $PATH", we don't want `$PATH` to be expanded.
  1083. return expand_path(outtmpl).replace(sep, '')
  1084. @staticmethod
  1085. def escape_outtmpl(outtmpl):
  1086. """ Escape any remaining strings like %s, %abc% etc. """
  1087. return re.sub(
  1088. STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'),
  1089. lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0),
  1090. outtmpl)
  1091. @classmethod
  1092. def validate_outtmpl(cls, outtmpl):
  1093. """ @return None or Exception object """
  1094. outtmpl = re.sub(
  1095. STR_FORMAT_RE_TMPL.format('[^)]*', '[ljhqBUDS]'),
  1096. lambda mobj: f'{mobj.group(0)[:-1]}s',
  1097. cls._outtmpl_expandpath(outtmpl))
  1098. try:
  1099. cls.escape_outtmpl(outtmpl) % collections.defaultdict(int)
  1100. return None
  1101. except ValueError as err:
  1102. return err
  1103. @staticmethod
  1104. def _copy_infodict(info_dict):
  1105. info_dict = dict(info_dict)
  1106. info_dict.pop('__postprocessors', None)
  1107. info_dict.pop('__pending_error', None)
  1108. return info_dict
  1109. def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False):
  1110. """ Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict
  1111. @param sanitize Whether to sanitize the output as a filename
  1112. """
  1113. info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set
  1114. info_dict = self._copy_infodict(info_dict)
  1115. info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs
  1116. formatSeconds(info_dict['duration'], '-' if sanitize else ':')
  1117. if info_dict.get('duration', None) is not None
  1118. else None)
  1119. info_dict['autonumber'] = int(self.params.get('autonumber_start', 1) - 1 + self._num_downloads)
  1120. info_dict['video_autonumber'] = self._num_videos
  1121. if info_dict.get('resolution') is None:
  1122. info_dict['resolution'] = self.format_resolution(info_dict, default=None)
  1123. # For fields playlist_index, playlist_autonumber and autonumber convert all occurrences
  1124. # of %(field)s to %(field)0Nd for backward compatibility
  1125. field_size_compat_map = {
  1126. 'playlist_index': number_of_digits(info_dict.get('__last_playlist_index') or 0),
  1127. 'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0),
  1128. 'autonumber': self.params.get('autonumber_size') or 5,
  1129. }
  1130. TMPL_DICT = {}
  1131. EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljhqBUDS]'))
  1132. MATH_FUNCTIONS = {
  1133. '+': float.__add__,
  1134. '-': float.__sub__,
  1135. '*': float.__mul__,
  1136. }
  1137. # Field is of the form key1.key2...
  1138. # where keys (except first) can be string, int, slice or "{field, ...}"
  1139. FIELD_INNER_RE = r'(?:\w+|%(num)s|%(num)s?(?::%(num)s?){1,2})' % {'num': r'(?:-?\d+)'} # noqa: UP031
  1140. FIELD_RE = r'\w*(?:\.(?:%(inner)s|{%(field)s(?:,%(field)s)*}))*' % { # noqa: UP031
  1141. 'inner': FIELD_INNER_RE,
  1142. 'field': rf'\w*(?:\.{FIELD_INNER_RE})*',
  1143. }
  1144. MATH_FIELD_RE = rf'(?:{FIELD_RE}|-?{NUMBER_RE})'
  1145. MATH_OPERATORS_RE = r'(?:{})'.format('|'.join(map(re.escape, MATH_FUNCTIONS.keys())))
  1146. INTERNAL_FORMAT_RE = re.compile(rf'''(?xs)
  1147. (?P<negate>-)?
  1148. (?P<fields>{FIELD_RE})
  1149. (?P<maths>(?:{MATH_OPERATORS_RE}{MATH_FIELD_RE})*)
  1150. (?:>(?P<strf_format>.+?))?
  1151. (?P<remaining>
  1152. (?P<alternate>(?<!\\),[^|&)]+)?
  1153. (?:&(?P<replacement>.*?))?
  1154. (?:\|(?P<default>.*?))?
  1155. )$''')
  1156. def _from_user_input(field):
  1157. if field == ':':
  1158. return ...
  1159. elif ':' in field:
  1160. return slice(*map(int_or_none, field.split(':')))
  1161. elif int_or_none(field) is not None:
  1162. return int(field)
  1163. return field
  1164. def _traverse_infodict(fields):
  1165. fields = [f for x in re.split(r'\.({.+?})\.?', fields)
  1166. for f in ([x] if x.startswith('{') else x.split('.'))]
  1167. for i in (0, -1):
  1168. if fields and not fields[i]:
  1169. fields.pop(i)
  1170. for i, f in enumerate(fields):
  1171. if not f.startswith('{'):
  1172. fields[i] = _from_user_input(f)
  1173. continue
  1174. assert f.endswith('}'), f'No closing brace for {f} in {fields}'
  1175. fields[i] = {k: list(map(_from_user_input, k.split('.'))) for k in f[1:-1].split(',')}
  1176. return traverse_obj(info_dict, fields, traverse_string=True)
  1177. def get_value(mdict):
  1178. # Object traversal
  1179. value = _traverse_infodict(mdict['fields'])
  1180. # Negative
  1181. if mdict['negate']:
  1182. value = float_or_none(value)
  1183. if value is not None:
  1184. value *= -1
  1185. # Do maths
  1186. offset_key = mdict['maths']
  1187. if offset_key:
  1188. value = float_or_none(value)
  1189. operator = None
  1190. while offset_key:
  1191. item = re.match(
  1192. MATH_FIELD_RE if operator else MATH_OPERATORS_RE,
  1193. offset_key).group(0)
  1194. offset_key = offset_key[len(item):]
  1195. if operator is None:
  1196. operator = MATH_FUNCTIONS[item]
  1197. continue
  1198. item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1)
  1199. offset = float_or_none(item)
  1200. if offset is None:
  1201. offset = float_or_none(_traverse_infodict(item))
  1202. try:
  1203. value = operator(value, multiplier * offset)
  1204. except (TypeError, ZeroDivisionError):
  1205. return None
  1206. operator = None
  1207. # Datetime formatting
  1208. if mdict['strf_format']:
  1209. value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ','))
  1210. # XXX: Workaround for https://github.com/yt-dlp/yt-dlp/issues/4485
  1211. if sanitize and value == '':
  1212. value = None
  1213. return value
  1214. na = self.params.get('outtmpl_na_placeholder', 'NA')
  1215. def filename_sanitizer(key, value, restricted):
  1216. return sanitize_filename(str(value), restricted=restricted, is_id=(
  1217. bool(re.search(r'(^|[_.])id(\.|$)', key))
  1218. if 'filename-sanitization' in self.params['compat_opts']
  1219. else NO_DEFAULT))
  1220. if callable(sanitize):
  1221. self.deprecation_warning('Passing a callable "sanitize" to YoutubeDL.prepare_outtmpl is deprecated')
  1222. elif not sanitize:
  1223. pass
  1224. elif (sys.platform != 'win32' and not self.params.get('restrictfilenames')
  1225. and self.params.get('windowsfilenames') is False):
  1226. def sanitize(key, value):
  1227. return str(value).replace('/', '\u29F8').replace('\0', '')
  1228. else:
  1229. def sanitize(key, value):
  1230. return filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames'))
  1231. def _dumpjson_default(obj):
  1232. if isinstance(obj, (set, LazyList)):
  1233. return list(obj)
  1234. return repr(obj)
  1235. class _ReplacementFormatter(string.Formatter):
  1236. def get_field(self, field_name, args, kwargs):
  1237. if field_name.isdigit():
  1238. return args[0], -1
  1239. raise ValueError('Unsupported field')
  1240. replacement_formatter = _ReplacementFormatter()
  1241. def create_key(outer_mobj):
  1242. if not outer_mobj.group('has_key'):
  1243. return outer_mobj.group(0)
  1244. key = outer_mobj.group('key')
  1245. mobj = re.match(INTERNAL_FORMAT_RE, key)
  1246. value, replacement, default, last_field = None, None, na, ''
  1247. while mobj:
  1248. mobj = mobj.groupdict()
  1249. default = mobj['default'] if mobj['default'] is not None else default
  1250. value = get_value(mobj)
  1251. last_field, replacement = mobj['fields'], mobj['replacement']
  1252. if value is None and mobj['alternate']:
  1253. mobj = re.match(INTERNAL_FORMAT_RE, mobj['remaining'][1:])
  1254. else:
  1255. break
  1256. if None not in (value, replacement):
  1257. try:
  1258. value = replacement_formatter.format(replacement, value)
  1259. except ValueError:
  1260. value, default = None, na
  1261. fmt = outer_mobj.group('format')
  1262. if fmt == 's' and last_field in field_size_compat_map and isinstance(value, int):
  1263. fmt = f'0{field_size_compat_map[last_field]:d}d'
  1264. flags = outer_mobj.group('conversion') or ''
  1265. str_fmt = f'{fmt[:-1]}s'
  1266. if value is None:
  1267. value, fmt = default, 's'
  1268. elif fmt[-1] == 'l': # list
  1269. delim = '\n' if '#' in flags else ', '
  1270. value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt
  1271. elif fmt[-1] == 'j': # json
  1272. value, fmt = json.dumps(
  1273. value, default=_dumpjson_default,
  1274. indent=4 if '#' in flags else None, ensure_ascii='+' not in flags), str_fmt
  1275. elif fmt[-1] == 'h': # html
  1276. value, fmt = escapeHTML(str(value)), str_fmt
  1277. elif fmt[-1] == 'q': # quoted
  1278. value = map(str, variadic(value) if '#' in flags else [value])
  1279. value, fmt = shell_quote(value, shell=True), str_fmt
  1280. elif fmt[-1] == 'B': # bytes
  1281. value = f'%{str_fmt}'.encode() % str(value).encode()
  1282. value, fmt = value.decode('utf-8', 'ignore'), 's'
  1283. elif fmt[-1] == 'U': # unicode normalized
  1284. value, fmt = unicodedata.normalize(
  1285. # "+" = compatibility equivalence, "#" = NFD
  1286. 'NF{}{}'.format('K' if '+' in flags else '', 'D' if '#' in flags else 'C'),
  1287. value), str_fmt
  1288. elif fmt[-1] == 'D': # decimal suffix
  1289. num_fmt, fmt = fmt[:-1].replace('#', ''), 's'
  1290. value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s',
  1291. factor=1024 if '#' in flags else 1000)
  1292. elif fmt[-1] == 'S': # filename sanitization
  1293. value, fmt = filename_sanitizer(last_field, value, restricted='#' in flags), str_fmt
  1294. elif fmt[-1] == 'c':
  1295. if value:
  1296. value = str(value)[0]
  1297. else:
  1298. fmt = str_fmt
  1299. elif fmt[-1] not in 'rsa': # numeric
  1300. value = float_or_none(value)
  1301. if value is None:
  1302. value, fmt = default, 's'
  1303. if sanitize:
  1304. # If value is an object, sanitize might convert it to a string
  1305. # So we manually convert it before sanitizing
  1306. if fmt[-1] == 'r':
  1307. value, fmt = repr(value), str_fmt
  1308. elif fmt[-1] == 'a':
  1309. value, fmt = ascii(value), str_fmt
  1310. if fmt[-1] in 'csra':
  1311. value = sanitize(last_field, value)
  1312. key = '{}\0{}'.format(key.replace('%', '%\0'), outer_mobj.group('format'))
  1313. TMPL_DICT[key] = value
  1314. return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix'))
  1315. return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT
  1316. def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs):
  1317. outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs)
  1318. return self.escape_outtmpl(outtmpl) % info_dict
  1319. @_catch_unsafe_extension_error
  1320. def _prepare_filename(self, info_dict, *, outtmpl=None, tmpl_type=None):
  1321. assert None in (outtmpl, tmpl_type), 'outtmpl and tmpl_type are mutually exclusive'
  1322. if outtmpl is None:
  1323. outtmpl = self.params['outtmpl'].get(tmpl_type or 'default', self.params['outtmpl']['default'])
  1324. try:
  1325. outtmpl = self._outtmpl_expandpath(outtmpl)
  1326. filename = self.evaluate_outtmpl(outtmpl, info_dict, True)
  1327. if not filename:
  1328. return None
  1329. if tmpl_type in ('', 'temp'):
  1330. final_ext, ext = self.params.get('final_ext'), info_dict.get('ext')
  1331. if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'):
  1332. filename = replace_extension(filename, ext, final_ext)
  1333. elif tmpl_type:
  1334. force_ext = OUTTMPL_TYPES[tmpl_type]
  1335. if force_ext:
  1336. filename = replace_extension(filename, force_ext, info_dict.get('ext'))
  1337. # https://github.com/blackjack4494/youtube-dlc/issues/85
  1338. trim_file_name = self.params.get('trim_file_name', False)
  1339. if trim_file_name:
  1340. no_ext, *ext = filename.rsplit('.', 2)
  1341. filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.')
  1342. return filename
  1343. except ValueError as err:
  1344. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  1345. return None
  1346. def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False):
  1347. """Generate the output filename"""
  1348. if outtmpl:
  1349. assert not dir_type, 'outtmpl and dir_type are mutually exclusive'
  1350. dir_type = None
  1351. filename = self._prepare_filename(info_dict, tmpl_type=dir_type, outtmpl=outtmpl)
  1352. if not filename and dir_type not in ('', 'temp'):
  1353. return ''
  1354. if warn:
  1355. if not self.params.get('paths'):
  1356. pass
  1357. elif filename == '-':
  1358. self.report_warning('--paths is ignored when an outputting to stdout', only_once=True)
  1359. elif os.path.isabs(filename):
  1360. self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True)
  1361. if filename == '-' or not filename:
  1362. return filename
  1363. return self.get_output_path(dir_type, filename)
  1364. def _match_entry(self, info_dict, incomplete=False, silent=False):
  1365. """Returns None if the file should be downloaded"""
  1366. _type = 'video' if 'playlist-match-filter' in self.params['compat_opts'] else info_dict.get('_type', 'video')
  1367. assert incomplete or _type == 'video', 'Only video result can be considered complete'
  1368. video_title = info_dict.get('title', info_dict.get('id', 'entry'))
  1369. def check_filter():
  1370. if _type in ('playlist', 'multi_video'):
  1371. return
  1372. elif _type in ('url', 'url_transparent') and not try_call(
  1373. lambda: self.get_info_extractor(info_dict['ie_key']).is_single_video(info_dict['url'])):
  1374. return
  1375. if 'title' in info_dict:
  1376. # This can happen when we're just evaluating the playlist
  1377. title = info_dict['title']
  1378. matchtitle = self.params.get('matchtitle', False)
  1379. if matchtitle:
  1380. if not re.search(matchtitle, title, re.IGNORECASE):
  1381. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  1382. rejecttitle = self.params.get('rejecttitle', False)
  1383. if rejecttitle:
  1384. if re.search(rejecttitle, title, re.IGNORECASE):
  1385. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  1386. date = info_dict.get('upload_date')
  1387. if date is not None:
  1388. date_range = self.params.get('daterange', DateRange())
  1389. if date not in date_range:
  1390. return f'{date_from_str(date).isoformat()} upload date is not in range {date_range}'
  1391. view_count = info_dict.get('view_count')
  1392. if view_count is not None:
  1393. min_views = self.params.get('min_views')
  1394. if min_views is not None and view_count < min_views:
  1395. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  1396. max_views = self.params.get('max_views')
  1397. if max_views is not None and view_count > max_views:
  1398. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  1399. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  1400. return f'Skipping "{video_title}" because it is age restricted'
  1401. match_filter = self.params.get('match_filter')
  1402. if match_filter is None:
  1403. return None
  1404. cancelled = None
  1405. try:
  1406. try:
  1407. ret = match_filter(info_dict, incomplete=incomplete)
  1408. except TypeError:
  1409. # For backward compatibility
  1410. ret = None if incomplete else match_filter(info_dict)
  1411. except DownloadCancelled as err:
  1412. if err.msg is not NO_DEFAULT:
  1413. raise
  1414. ret, cancelled = err.msg, err
  1415. if ret is NO_DEFAULT:
  1416. while True:
  1417. filename = self._format_screen(self.prepare_filename(info_dict), self.Styles.FILENAME)
  1418. reply = input(self._format_screen(
  1419. f'Download "{filename}"? (Y/n): ', self.Styles.EMPHASIS)).lower().strip()
  1420. if reply in {'y', ''}:
  1421. return None
  1422. elif reply == 'n':
  1423. if cancelled:
  1424. raise type(cancelled)(f'Skipping {video_title}')
  1425. return f'Skipping {video_title}'
  1426. return ret
  1427. if self.in_download_archive(info_dict):
  1428. reason = ''.join((
  1429. format_field(info_dict, 'id', f'{self._format_screen("%s", self.Styles.ID)}: '),
  1430. format_field(info_dict, 'title', f'{self._format_screen("%s", self.Styles.EMPHASIS)} '),
  1431. 'has already been recorded in the archive'))
  1432. break_opt, break_err = 'break_on_existing', ExistingVideoReached
  1433. else:
  1434. try:
  1435. reason = check_filter()
  1436. except DownloadCancelled as e:
  1437. reason, break_opt, break_err = e.msg, 'match_filter', type(e)
  1438. else:
  1439. break_opt, break_err = 'break_on_reject', RejectedVideoReached
  1440. if reason is not None:
  1441. if not silent:
  1442. self.to_screen('[download] ' + reason)
  1443. if self.params.get(break_opt, False):
  1444. raise break_err()
  1445. return reason
  1446. @staticmethod
  1447. def add_extra_info(info_dict, extra_info):
  1448. """Set the keys from extra_info in info dict if they are missing"""
  1449. for key, value in extra_info.items():
  1450. info_dict.setdefault(key, value)
  1451. def extract_info(self, url, download=True, ie_key=None, extra_info=None,
  1452. process=True, force_generic_extractor=False):
  1453. """
  1454. Extract and return the information dictionary of the URL
  1455. Arguments:
  1456. @param url URL to extract
  1457. Keyword arguments:
  1458. @param download Whether to download videos
  1459. @param process Whether to resolve all unresolved references (URLs, playlist items).
  1460. Must be True for download to work
  1461. @param ie_key Use only the extractor with this key
  1462. @param extra_info Dictionary containing the extra values to add to the info (For internal use only)
  1463. @force_generic_extractor Force using the generic extractor (Deprecated; use ie_key='Generic')
  1464. """
  1465. if extra_info is None:
  1466. extra_info = {}
  1467. if not ie_key and force_generic_extractor:
  1468. ie_key = 'Generic'
  1469. if ie_key:
  1470. ies = {ie_key: self._ies[ie_key]} if ie_key in self._ies else {}
  1471. else:
  1472. ies = self._ies
  1473. for key, ie in ies.items():
  1474. if not ie.suitable(url):
  1475. continue
  1476. if not ie.working():
  1477. self.report_warning('The program functionality for this site has been marked as broken, '
  1478. 'and will probably not work.')
  1479. temp_id = ie.get_temp_id(url)
  1480. if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': key}):
  1481. self.to_screen(f'[download] {self._format_screen(temp_id, self.Styles.ID)}: '
  1482. 'has already been recorded in the archive')
  1483. if self.params.get('break_on_existing', False):
  1484. raise ExistingVideoReached
  1485. break
  1486. return self.__extract_info(url, self.get_info_extractor(key), download, extra_info, process)
  1487. else:
  1488. extractors_restricted = self.params.get('allowed_extractors') not in (None, ['default'])
  1489. self.report_error(f'No suitable extractor{format_field(ie_key, None, " (%s)")} found for URL {url}',
  1490. tb=False if extractors_restricted else None)
  1491. def _handle_extraction_exceptions(func):
  1492. @functools.wraps(func)
  1493. def wrapper(self, *args, **kwargs):
  1494. while True:
  1495. try:
  1496. return func(self, *args, **kwargs)
  1497. except (CookieLoadError, DownloadCancelled, LazyList.IndexError, PagedList.IndexError):
  1498. raise
  1499. except ReExtractInfo as e:
  1500. if e.expected:
  1501. self.to_screen(f'{e}; Re-extracting data')
  1502. else:
  1503. self.to_stderr('\r')
  1504. self.report_warning(f'{e}; Re-extracting data')
  1505. continue
  1506. except GeoRestrictedError as e:
  1507. msg = e.msg
  1508. if e.countries:
  1509. msg += '\nThis video is available in {}.'.format(', '.join(
  1510. map(ISO3166Utils.short2full, e.countries)))
  1511. msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
  1512. self.report_error(msg)
  1513. except ExtractorError as e: # An error we somewhat expected
  1514. self.report_error(str(e), e.format_traceback())
  1515. except Exception as e:
  1516. if self.params.get('ignoreerrors'):
  1517. self.report_error(str(e), tb=encode_compat_str(traceback.format_exc()))
  1518. else:
  1519. raise
  1520. break
  1521. return wrapper
  1522. def _wait_for_video(self, ie_result={}):
  1523. if (not self.params.get('wait_for_video')
  1524. or ie_result.get('_type', 'video') != 'video'
  1525. or ie_result.get('formats') or ie_result.get('url')):
  1526. return
  1527. format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1]
  1528. last_msg = ''
  1529. def progress(msg):
  1530. nonlocal last_msg
  1531. full_msg = f'{msg}\n'
  1532. if not self.params.get('noprogress'):
  1533. full_msg = msg + ' ' * (len(last_msg) - len(msg)) + '\r'
  1534. elif last_msg:
  1535. return
  1536. self.to_screen(full_msg, skip_eol=True)
  1537. last_msg = msg
  1538. min_wait, max_wait = self.params.get('wait_for_video')
  1539. diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time())
  1540. if diff is None and ie_result.get('live_status') == 'is_upcoming':
  1541. diff = round(random.uniform(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait), 0)
  1542. self.report_warning('Release time of video is not known')
  1543. elif ie_result and (diff or 0) <= 0:
  1544. self.report_warning('Video should already be available according to extracted info')
  1545. diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf'))
  1546. self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now')
  1547. wait_till = time.time() + diff
  1548. try:
  1549. while True:
  1550. diff = wait_till - time.time()
  1551. if diff <= 0:
  1552. progress('')
  1553. raise ReExtractInfo('[wait] Wait period ended', expected=True)
  1554. progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}')
  1555. time.sleep(1)
  1556. except KeyboardInterrupt:
  1557. progress('')
  1558. raise ReExtractInfo('[wait] Interrupted by user', expected=True)
  1559. except BaseException as e:
  1560. if not isinstance(e, ReExtractInfo):
  1561. self.to_screen('')
  1562. raise
  1563. def _load_cookies(self, data, *, autoscope=True):
  1564. """Loads cookies from a `Cookie` header
  1565. This tries to work around the security vulnerability of passing cookies to every domain.
  1566. See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  1567. @param data The Cookie header as string to load the cookies from
  1568. @param autoscope If `False`, scope cookies using Set-Cookie syntax and error for cookie without domains
  1569. If `True`, save cookies for later to be stored in the jar with a limited scope
  1570. If a URL, save cookies in the jar with the domain of the URL
  1571. """
  1572. for cookie in LenientSimpleCookie(data).values():
  1573. if autoscope and any(cookie.values()):
  1574. raise ValueError('Invalid syntax in Cookie Header')
  1575. domain = cookie.get('domain') or ''
  1576. expiry = cookie.get('expires')
  1577. if expiry == '': # 0 is valid
  1578. expiry = None
  1579. prepared_cookie = http.cookiejar.Cookie(
  1580. cookie.get('version') or 0, cookie.key, cookie.value, None, False,
  1581. domain, True, True, cookie.get('path') or '', bool(cookie.get('path')),
  1582. cookie.get('secure') or False, expiry, False, None, None, {})
  1583. if domain:
  1584. self.cookiejar.set_cookie(prepared_cookie)
  1585. elif autoscope is True:
  1586. self.deprecated_feature(
  1587. 'Passing cookies as a header is a potential security risk; '
  1588. 'they will be scoped to the domain of the downloaded urls. '
  1589. 'Please consider loading cookies from a file or browser instead.')
  1590. self.__header_cookies.append(prepared_cookie)
  1591. elif autoscope:
  1592. self.report_warning(
  1593. 'The extractor result contains an unscoped cookie as an HTTP header. '
  1594. f'If you are using yt-dlp with an input URL{bug_reports_message(before=",")}',
  1595. only_once=True)
  1596. self._apply_header_cookies(autoscope, [prepared_cookie])
  1597. else:
  1598. self.report_error('Unscoped cookies are not allowed; please specify some sort of scoping',
  1599. tb=False, is_error=False)
  1600. def _apply_header_cookies(self, url, cookies=None):
  1601. """Applies stray header cookies to the provided url
  1602. This loads header cookies and scopes them to the domain provided in `url`.
  1603. While this is not ideal, it helps reduce the risk of them being sent
  1604. to an unintended destination while mostly maintaining compatibility.
  1605. """
  1606. parsed = urllib.parse.urlparse(url)
  1607. if not parsed.hostname:
  1608. return
  1609. for cookie in map(copy.copy, cookies or self.__header_cookies):
  1610. cookie.domain = f'.{parsed.hostname}'
  1611. self.cookiejar.set_cookie(cookie)
  1612. @_handle_extraction_exceptions
  1613. def __extract_info(self, url, ie, download, extra_info, process):
  1614. self._apply_header_cookies(url)
  1615. try:
  1616. ie_result = ie.extract(url)
  1617. except UserNotLive as e:
  1618. if process:
  1619. if self.params.get('wait_for_video'):
  1620. self.report_warning(e)
  1621. self._wait_for_video()
  1622. raise
  1623. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  1624. self.report_warning(f'Extractor {ie.IE_NAME} returned nothing{bug_reports_message()}')
  1625. return
  1626. if isinstance(ie_result, list):
  1627. # Backwards compatibility: old IE result format
  1628. ie_result = {
  1629. '_type': 'compat_list',
  1630. 'entries': ie_result,
  1631. }
  1632. if extra_info.get('original_url'):
  1633. ie_result.setdefault('original_url', extra_info['original_url'])
  1634. self.add_default_extra_info(ie_result, ie, url)
  1635. if process:
  1636. self._wait_for_video(ie_result)
  1637. return self.process_ie_result(ie_result, download, extra_info)
  1638. else:
  1639. return ie_result
  1640. def add_default_extra_info(self, ie_result, ie, url):
  1641. if url is not None:
  1642. self.add_extra_info(ie_result, {
  1643. 'webpage_url': url,
  1644. 'original_url': url,
  1645. })
  1646. webpage_url = ie_result.get('webpage_url')
  1647. if webpage_url:
  1648. self.add_extra_info(ie_result, {
  1649. 'webpage_url_basename': url_basename(webpage_url),
  1650. 'webpage_url_domain': get_domain(webpage_url),
  1651. })
  1652. if ie is not None:
  1653. self.add_extra_info(ie_result, {
  1654. 'extractor': ie.IE_NAME,
  1655. 'extractor_key': ie.ie_key(),
  1656. })
  1657. def process_ie_result(self, ie_result, download=True, extra_info=None):
  1658. """
  1659. Take the result of the ie(may be modified) and resolve all unresolved
  1660. references (URLs, playlist items).
  1661. It will also download the videos if 'download'.
  1662. Returns the resolved ie_result.
  1663. """
  1664. if extra_info is None:
  1665. extra_info = {}
  1666. result_type = ie_result.get('_type', 'video')
  1667. if result_type in ('url', 'url_transparent'):
  1668. ie_result['url'] = sanitize_url(
  1669. ie_result['url'], scheme='http' if self.params.get('prefer_insecure') else 'https')
  1670. if ie_result.get('original_url') and not extra_info.get('original_url'):
  1671. extra_info = {'original_url': ie_result['original_url'], **extra_info}
  1672. extract_flat = self.params.get('extract_flat', False)
  1673. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
  1674. or extract_flat is True):
  1675. info_copy = ie_result.copy()
  1676. ie = try_get(ie_result.get('ie_key'), self.get_info_extractor)
  1677. if ie and not ie_result.get('id'):
  1678. info_copy['id'] = ie.get_temp_id(ie_result['url'])
  1679. self.add_default_extra_info(info_copy, ie, ie_result['url'])
  1680. self.add_extra_info(info_copy, extra_info)
  1681. info_copy, _ = self.pre_process(info_copy)
  1682. self._fill_common_fields(info_copy, False)
  1683. self.__forced_printings(info_copy)
  1684. self._raise_pending_errors(info_copy)
  1685. if self.params.get('force_write_download_archive', False):
  1686. self.record_download_archive(info_copy)
  1687. return ie_result
  1688. if result_type == 'video':
  1689. self.add_extra_info(ie_result, extra_info)
  1690. ie_result = self.process_video_result(ie_result, download=download)
  1691. self._raise_pending_errors(ie_result)
  1692. additional_urls = (ie_result or {}).get('additional_urls')
  1693. if additional_urls:
  1694. # TODO: Improve MetadataParserPP to allow setting a list
  1695. if isinstance(additional_urls, str):
  1696. additional_urls = [additional_urls]
  1697. self.to_screen(
  1698. '[info] {}: {} additional URL(s) requested'.format(ie_result['id'], len(additional_urls)))
  1699. self.write_debug('Additional URLs: "{}"'.format('", "'.join(additional_urls)))
  1700. ie_result['additional_entries'] = [
  1701. self.extract_info(
  1702. url, download, extra_info=extra_info,
  1703. force_generic_extractor=self.params.get('force_generic_extractor'))
  1704. for url in additional_urls
  1705. ]
  1706. return ie_result
  1707. elif result_type == 'url':
  1708. # We have to add extra_info to the results because it may be
  1709. # contained in a playlist
  1710. return self.extract_info(
  1711. ie_result['url'], download,
  1712. ie_key=ie_result.get('ie_key'),
  1713. extra_info=extra_info)
  1714. elif result_type == 'url_transparent':
  1715. # Use the information from the embedding page
  1716. info = self.extract_info(
  1717. ie_result['url'], ie_key=ie_result.get('ie_key'),
  1718. extra_info=extra_info, download=False, process=False)
  1719. # extract_info may return None when ignoreerrors is enabled and
  1720. # extraction failed with an error, don't crash and return early
  1721. # in this case
  1722. if not info:
  1723. return info
  1724. exempted_fields = {'_type', 'url', 'ie_key'}
  1725. if not ie_result.get('section_end') and ie_result.get('section_start') is None:
  1726. # For video clips, the id etc of the clip extractor should be used
  1727. exempted_fields |= {'id', 'extractor', 'extractor_key'}
  1728. new_result = info.copy()
  1729. new_result.update(filter_dict(ie_result, lambda k, v: v is not None and k not in exempted_fields))
  1730. # Extracted info may not be a video result (i.e.
  1731. # info.get('_type', 'video') != video) but rather an url or
  1732. # url_transparent. In such cases outer metadata (from ie_result)
  1733. # should be propagated to inner one (info). For this to happen
  1734. # _type of info should be overridden with url_transparent. This
  1735. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  1736. if new_result.get('_type') == 'url':
  1737. new_result['_type'] = 'url_transparent'
  1738. return self.process_ie_result(
  1739. new_result, download=download, extra_info=extra_info)
  1740. elif result_type in ('playlist', 'multi_video'):
  1741. # Protect from infinite recursion due to recursively nested playlists
  1742. # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
  1743. webpage_url = ie_result.get('webpage_url') # Playlists maynot have webpage_url
  1744. if webpage_url and webpage_url in self._playlist_urls:
  1745. self.to_screen(
  1746. '[download] Skipping already downloaded playlist: {}'.format(
  1747. ie_result.get('title')) or ie_result.get('id'))
  1748. return
  1749. self._playlist_level += 1
  1750. self._playlist_urls.add(webpage_url)
  1751. self._fill_common_fields(ie_result, False)
  1752. self._sanitize_thumbnails(ie_result)
  1753. try:
  1754. return self.__process_playlist(ie_result, download)
  1755. finally:
  1756. self._playlist_level -= 1
  1757. if not self._playlist_level:
  1758. self._playlist_urls.clear()
  1759. elif result_type == 'compat_list':
  1760. self.report_warning(
  1761. 'Extractor {} returned a compat_list result. '
  1762. 'It needs to be updated.'.format(ie_result.get('extractor')))
  1763. def _fixup(r):
  1764. self.add_extra_info(r, {
  1765. 'extractor': ie_result['extractor'],
  1766. 'webpage_url': ie_result['webpage_url'],
  1767. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1768. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1769. 'extractor_key': ie_result['extractor_key'],
  1770. })
  1771. return r
  1772. ie_result['entries'] = [
  1773. self.process_ie_result(_fixup(r), download, extra_info)
  1774. for r in ie_result['entries']
  1775. ]
  1776. return ie_result
  1777. else:
  1778. raise Exception(f'Invalid result type: {result_type}')
  1779. def _ensure_dir_exists(self, path):
  1780. return make_dir(path, self.report_error)
  1781. @staticmethod
  1782. def _playlist_infodict(ie_result, strict=False, **kwargs):
  1783. info = {
  1784. 'playlist_count': ie_result.get('playlist_count'),
  1785. 'playlist': ie_result.get('title') or ie_result.get('id'),
  1786. 'playlist_id': ie_result.get('id'),
  1787. 'playlist_title': ie_result.get('title'),
  1788. 'playlist_uploader': ie_result.get('uploader'),
  1789. 'playlist_uploader_id': ie_result.get('uploader_id'),
  1790. 'playlist_channel': ie_result.get('channel'),
  1791. 'playlist_channel_id': ie_result.get('channel_id'),
  1792. 'playlist_webpage_url': ie_result.get('webpage_url'),
  1793. **kwargs,
  1794. }
  1795. if strict:
  1796. return info
  1797. if ie_result.get('webpage_url'):
  1798. info.update({
  1799. 'webpage_url': ie_result['webpage_url'],
  1800. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1801. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1802. })
  1803. return {
  1804. **info,
  1805. 'playlist_index': 0,
  1806. '__last_playlist_index': max(ie_result.get('requested_entries') or (0, 0)),
  1807. 'extractor': ie_result['extractor'],
  1808. 'extractor_key': ie_result['extractor_key'],
  1809. }
  1810. def __process_playlist(self, ie_result, download):
  1811. """Process each entry in the playlist"""
  1812. assert ie_result['_type'] in ('playlist', 'multi_video')
  1813. common_info = self._playlist_infodict(ie_result, strict=True)
  1814. title = common_info.get('playlist') or '<Untitled>'
  1815. if self._match_entry(common_info, incomplete=True) is not None:
  1816. return
  1817. self.to_screen(f'[download] Downloading {ie_result["_type"]}: {title}')
  1818. all_entries = PlaylistEntries(self, ie_result)
  1819. entries = orderedSet(all_entries.get_requested_items(), lazy=True)
  1820. lazy = self.params.get('lazy_playlist')
  1821. if lazy:
  1822. resolved_entries, n_entries = [], 'N/A'
  1823. ie_result['requested_entries'], ie_result['entries'] = None, None
  1824. else:
  1825. entries = resolved_entries = list(entries)
  1826. n_entries = len(resolved_entries)
  1827. ie_result['requested_entries'], ie_result['entries'] = tuple(zip(*resolved_entries)) or ([], [])
  1828. if not ie_result.get('playlist_count'):
  1829. # Better to do this after potentially exhausting entries
  1830. ie_result['playlist_count'] = all_entries.get_full_count()
  1831. extra = self._playlist_infodict(ie_result, n_entries=int_or_none(n_entries))
  1832. ie_copy = collections.ChainMap(ie_result, extra)
  1833. _infojson_written = False
  1834. write_playlist_files = self.params.get('allow_playlist_files', True)
  1835. if write_playlist_files and self.params.get('list_thumbnails'):
  1836. self.list_thumbnails(ie_result)
  1837. if write_playlist_files and not self.params.get('simulate'):
  1838. _infojson_written = self._write_info_json(
  1839. 'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
  1840. if _infojson_written is None:
  1841. return
  1842. if self._write_description('playlist', ie_result,
  1843. self.prepare_filename(ie_copy, 'pl_description')) is None:
  1844. return
  1845. # TODO: This should be passed to ThumbnailsConvertor if necessary
  1846. self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail'))
  1847. if lazy:
  1848. if self.params.get('playlistreverse') or self.params.get('playlistrandom'):
  1849. self.report_warning('playlistreverse and playlistrandom are not supported with lazy_playlist', only_once=True)
  1850. elif self.params.get('playlistreverse'):
  1851. entries.reverse()
  1852. elif self.params.get('playlistrandom'):
  1853. random.shuffle(entries)
  1854. self.to_screen(f'[{ie_result["extractor"]}] Playlist {title}: Downloading {n_entries} items'
  1855. f'{format_field(ie_result, "playlist_count", " of %s")}')
  1856. keep_resolved_entries = self.params.get('extract_flat') != 'discard'
  1857. if self.params.get('extract_flat') == 'discard_in_playlist':
  1858. keep_resolved_entries = ie_result['_type'] != 'playlist'
  1859. if keep_resolved_entries:
  1860. self.write_debug('The information of all playlist entries will be held in memory')
  1861. failures = 0
  1862. max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
  1863. for i, (playlist_index, entry) in enumerate(entries):
  1864. if lazy:
  1865. resolved_entries.append((playlist_index, entry))
  1866. if not entry:
  1867. continue
  1868. entry['__x_forwarded_for_ip'] = ie_result.get('__x_forwarded_for_ip')
  1869. if not lazy and 'playlist-index' in self.params['compat_opts']:
  1870. playlist_index = ie_result['requested_entries'][i]
  1871. entry_copy = collections.ChainMap(entry, {
  1872. **common_info,
  1873. 'n_entries': int_or_none(n_entries),
  1874. 'playlist_index': playlist_index,
  1875. 'playlist_autonumber': i + 1,
  1876. })
  1877. if self._match_entry(entry_copy, incomplete=True) is not None:
  1878. # For compatabilty with youtube-dl. See https://github.com/yt-dlp/yt-dlp/issues/4369
  1879. resolved_entries[i] = (playlist_index, NO_DEFAULT)
  1880. continue
  1881. self.to_screen(
  1882. f'[download] Downloading item {self._format_screen(i + 1, self.Styles.ID)} '
  1883. f'of {self._format_screen(n_entries, self.Styles.EMPHASIS)}')
  1884. entry_result = self.__process_iterable_entry(entry, download, collections.ChainMap({
  1885. 'playlist_index': playlist_index,
  1886. 'playlist_autonumber': i + 1,
  1887. }, extra))
  1888. if not entry_result:
  1889. failures += 1
  1890. if failures >= max_failures:
  1891. self.report_error(
  1892. f'Skipping the remaining entries in playlist "{title}" since {failures} items failed extraction')
  1893. break
  1894. if keep_resolved_entries:
  1895. resolved_entries[i] = (playlist_index, entry_result)
  1896. # Update with processed data
  1897. ie_result['entries'] = [e for _, e in resolved_entries if e is not NO_DEFAULT]
  1898. ie_result['requested_entries'] = [i for i, e in resolved_entries if e is not NO_DEFAULT]
  1899. if ie_result['requested_entries'] == try_call(lambda: list(range(1, ie_result['playlist_count'] + 1))):
  1900. # Do not set for full playlist
  1901. ie_result.pop('requested_entries')
  1902. # Write the updated info to json
  1903. if _infojson_written is True and self._write_info_json(
  1904. 'updated playlist', ie_result,
  1905. self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
  1906. return
  1907. ie_result = self.run_all_pps('playlist', ie_result)
  1908. self.to_screen(f'[download] Finished downloading playlist: {title}')
  1909. return ie_result
  1910. @_handle_extraction_exceptions
  1911. def __process_iterable_entry(self, entry, download, extra_info):
  1912. return self.process_ie_result(
  1913. entry, download=download, extra_info=extra_info)
  1914. def _build_format_filter(self, filter_spec):
  1915. " Returns a function to filter the formats according to the filter_spec "
  1916. OPERATORS = {
  1917. '<': operator.lt,
  1918. '<=': operator.le,
  1919. '>': operator.gt,
  1920. '>=': operator.ge,
  1921. '=': operator.eq,
  1922. '!=': operator.ne,
  1923. }
  1924. operator_rex = re.compile(r'''(?x)\s*
  1925. (?P<key>[\w.-]+)\s*
  1926. (?P<op>{})(?P<none_inclusive>\s*\?)?\s*
  1927. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
  1928. '''.format('|'.join(map(re.escape, OPERATORS.keys()))))
  1929. m = operator_rex.fullmatch(filter_spec)
  1930. if m:
  1931. try:
  1932. comparison_value = float(m.group('value'))
  1933. except ValueError:
  1934. comparison_value = parse_filesize(m.group('value'))
  1935. if comparison_value is None:
  1936. comparison_value = parse_filesize(m.group('value') + 'B')
  1937. if comparison_value is None:
  1938. raise ValueError(
  1939. 'Invalid value {!r} in format specification {!r}'.format(
  1940. m.group('value'), filter_spec))
  1941. op = OPERATORS[m.group('op')]
  1942. if not m:
  1943. STR_OPERATORS = {
  1944. '=': operator.eq,
  1945. '^=': lambda attr, value: attr.startswith(value),
  1946. '$=': lambda attr, value: attr.endswith(value),
  1947. '*=': lambda attr, value: value in attr,
  1948. '~=': lambda attr, value: value.search(attr) is not None,
  1949. }
  1950. str_operator_rex = re.compile(r'''(?x)\s*
  1951. (?P<key>[a-zA-Z0-9._-]+)\s*
  1952. (?P<negation>!\s*)?(?P<op>{})\s*(?P<none_inclusive>\?\s*)?
  1953. (?P<quote>["'])?
  1954. (?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
  1955. (?(quote)(?P=quote))\s*
  1956. '''.format('|'.join(map(re.escape, STR_OPERATORS.keys()))))
  1957. m = str_operator_rex.fullmatch(filter_spec)
  1958. if m:
  1959. if m.group('op') == '~=':
  1960. comparison_value = re.compile(m.group('value'))
  1961. else:
  1962. comparison_value = re.sub(r'''\\([\\"'])''', r'\1', m.group('value'))
  1963. str_op = STR_OPERATORS[m.group('op')]
  1964. if m.group('negation'):
  1965. op = lambda attr, value: not str_op(attr, value)
  1966. else:
  1967. op = str_op
  1968. if not m:
  1969. raise SyntaxError(f'Invalid filter specification {filter_spec!r}')
  1970. def _filter(f):
  1971. actual_value = f.get(m.group('key'))
  1972. if actual_value is None:
  1973. return m.group('none_inclusive')
  1974. return op(actual_value, comparison_value)
  1975. return _filter
  1976. def _check_formats(self, formats):
  1977. for f in formats:
  1978. working = f.get('__working')
  1979. if working is not None:
  1980. if working:
  1981. yield f
  1982. continue
  1983. self.to_screen('[info] Testing format {}'.format(f['format_id']))
  1984. path = self.get_output_path('temp')
  1985. if not self._ensure_dir_exists(f'{path}/'):
  1986. continue
  1987. temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path or None)
  1988. temp_file.close()
  1989. try:
  1990. success, _ = self.dl(temp_file.name, f, test=True)
  1991. except (DownloadError, OSError, ValueError, *network_exceptions):
  1992. success = False
  1993. finally:
  1994. if os.path.exists(temp_file.name):
  1995. try:
  1996. os.remove(temp_file.name)
  1997. except OSError:
  1998. self.report_warning(f'Unable to delete temporary file "{temp_file.name}"')
  1999. f['__working'] = success
  2000. if success:
  2001. yield f
  2002. else:
  2003. self.to_screen('[info] Unable to download format {}. Skipping...'.format(f['format_id']))
  2004. def _select_formats(self, formats, selector):
  2005. return list(selector({
  2006. 'formats': formats,
  2007. 'has_merged_format': any('none' not in (f.get('acodec'), f.get('vcodec')) for f in formats),
  2008. 'incomplete_formats': (all(f.get('vcodec') == 'none' for f in formats) # No formats with video
  2009. or all(f.get('acodec') == 'none' for f in formats)), # OR, No formats with audio
  2010. }))
  2011. def _default_format_spec(self, info_dict):
  2012. prefer_best = (
  2013. self.params['outtmpl']['default'] == '-'
  2014. or (info_dict.get('is_live') and not self.params.get('live_from_start')))
  2015. def can_merge():
  2016. merger = FFmpegMergerPP(self)
  2017. return merger.available and merger.can_merge()
  2018. if not prefer_best and not can_merge():
  2019. prefer_best = True
  2020. formats = self._get_formats(info_dict)
  2021. evaluate_formats = lambda spec: self._select_formats(formats, self.build_format_selector(spec))
  2022. if evaluate_formats('b/bv+ba') != evaluate_formats('bv*+ba/b'):
  2023. self.report_warning('ffmpeg not found. The downloaded format may not be the best available. '
  2024. 'Installing ffmpeg is strongly recommended: https://github.com/yt-dlp/yt-dlp#dependencies')
  2025. compat = (self.params.get('allow_multiple_audio_streams')
  2026. or 'format-spec' in self.params['compat_opts'])
  2027. return ('best/bestvideo+bestaudio' if prefer_best
  2028. else 'bestvideo+bestaudio/best' if compat
  2029. else 'bestvideo*+bestaudio/best')
  2030. def build_format_selector(self, format_spec):
  2031. def syntax_error(note, start):
  2032. message = (
  2033. 'Invalid format specification: '
  2034. '{}\n\t{}\n\t{}^'.format(note, format_spec, ' ' * start[1]))
  2035. return SyntaxError(message)
  2036. PICKFIRST = 'PICKFIRST'
  2037. MERGE = 'MERGE'
  2038. SINGLE = 'SINGLE'
  2039. GROUP = 'GROUP'
  2040. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  2041. allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
  2042. 'video': self.params.get('allow_multiple_video_streams', False)}
  2043. def _parse_filter(tokens):
  2044. filter_parts = []
  2045. for type_, string_, _start, _, _ in tokens:
  2046. if type_ == tokenize.OP and string_ == ']':
  2047. return ''.join(filter_parts)
  2048. else:
  2049. filter_parts.append(string_)
  2050. def _remove_unused_ops(tokens):
  2051. # Remove operators that we don't use and join them with the surrounding strings.
  2052. # E.g. 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  2053. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  2054. last_string, last_start, last_end, last_line = None, None, None, None
  2055. for type_, string_, start, end, line in tokens:
  2056. if type_ == tokenize.OP and string_ == '[':
  2057. if last_string:
  2058. yield tokenize.NAME, last_string, last_start, last_end, last_line
  2059. last_string = None
  2060. yield type_, string_, start, end, line
  2061. # everything inside brackets will be handled by _parse_filter
  2062. for type_, string_, start, end, line in tokens:
  2063. yield type_, string_, start, end, line
  2064. if type_ == tokenize.OP and string_ == ']':
  2065. break
  2066. elif type_ == tokenize.OP and string_ in ALLOWED_OPS:
  2067. if last_string:
  2068. yield tokenize.NAME, last_string, last_start, last_end, last_line
  2069. last_string = None
  2070. yield type_, string_, start, end, line
  2071. elif type_ in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  2072. if not last_string:
  2073. last_string = string_
  2074. last_start = start
  2075. last_end = end
  2076. else:
  2077. last_string += string_
  2078. if last_string:
  2079. yield tokenize.NAME, last_string, last_start, last_end, last_line
  2080. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  2081. selectors = []
  2082. current_selector = None
  2083. for type_, string_, start, _, _ in tokens:
  2084. # ENCODING is only defined in Python 3.x
  2085. if type_ == getattr(tokenize, 'ENCODING', None):
  2086. continue
  2087. elif type_ in [tokenize.NAME, tokenize.NUMBER]:
  2088. current_selector = FormatSelector(SINGLE, string_, [])
  2089. elif type_ == tokenize.OP:
  2090. if string_ == ')':
  2091. if not inside_group:
  2092. # ')' will be handled by the parentheses group
  2093. tokens.restore_last_token()
  2094. break
  2095. elif inside_merge and string_ in ['/', ',']:
  2096. tokens.restore_last_token()
  2097. break
  2098. elif inside_choice and string_ == ',':
  2099. tokens.restore_last_token()
  2100. break
  2101. elif string_ == ',':
  2102. if not current_selector:
  2103. raise syntax_error('"," must follow a format selector', start)
  2104. selectors.append(current_selector)
  2105. current_selector = None
  2106. elif string_ == '/':
  2107. if not current_selector:
  2108. raise syntax_error('"/" must follow a format selector', start)
  2109. first_choice = current_selector
  2110. second_choice = _parse_format_selection(tokens, inside_choice=True)
  2111. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  2112. elif string_ == '[':
  2113. if not current_selector:
  2114. current_selector = FormatSelector(SINGLE, 'best', [])
  2115. format_filter = _parse_filter(tokens)
  2116. current_selector.filters.append(format_filter)
  2117. elif string_ == '(':
  2118. if current_selector:
  2119. raise syntax_error('Unexpected "("', start)
  2120. group = _parse_format_selection(tokens, inside_group=True)
  2121. current_selector = FormatSelector(GROUP, group, [])
  2122. elif string_ == '+':
  2123. if not current_selector:
  2124. raise syntax_error('Unexpected "+"', start)
  2125. selector_1 = current_selector
  2126. selector_2 = _parse_format_selection(tokens, inside_merge=True)
  2127. if not selector_2:
  2128. raise syntax_error('Expected a selector', start)
  2129. current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
  2130. else:
  2131. raise syntax_error(f'Operator not recognized: "{string_}"', start)
  2132. elif type_ == tokenize.ENDMARKER:
  2133. break
  2134. if current_selector:
  2135. selectors.append(current_selector)
  2136. return selectors
  2137. def _merge(formats_pair):
  2138. format_1, format_2 = formats_pair
  2139. formats_info = []
  2140. formats_info.extend(format_1.get('requested_formats', (format_1,)))
  2141. formats_info.extend(format_2.get('requested_formats', (format_2,)))
  2142. if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
  2143. get_no_more = {'video': False, 'audio': False}
  2144. for (i, fmt_info) in enumerate(formats_info):
  2145. if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
  2146. formats_info.pop(i)
  2147. continue
  2148. for aud_vid in ['audio', 'video']:
  2149. if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
  2150. if get_no_more[aud_vid]:
  2151. formats_info.pop(i)
  2152. break
  2153. get_no_more[aud_vid] = True
  2154. if len(formats_info) == 1:
  2155. return formats_info[0]
  2156. video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
  2157. audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
  2158. the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
  2159. the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
  2160. output_ext = get_compatible_ext(
  2161. vcodecs=[f.get('vcodec') for f in video_fmts],
  2162. acodecs=[f.get('acodec') for f in audio_fmts],
  2163. vexts=[f['ext'] for f in video_fmts],
  2164. aexts=[f['ext'] for f in audio_fmts],
  2165. preferences=(try_call(lambda: self.params['merge_output_format'].split('/'))
  2166. or (self.params.get('prefer_free_formats') and ('webm', 'mkv'))))
  2167. filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
  2168. new_dict = {
  2169. 'requested_formats': formats_info,
  2170. 'format': '+'.join(filtered('format')),
  2171. 'format_id': '+'.join(filtered('format_id')),
  2172. 'ext': output_ext,
  2173. 'protocol': '+'.join(map(determine_protocol, formats_info)),
  2174. 'language': '+'.join(orderedSet(filtered('language'))) or None,
  2175. 'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
  2176. 'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
  2177. 'tbr': sum(filtered('tbr', 'vbr', 'abr')),
  2178. }
  2179. if the_only_video:
  2180. new_dict.update({
  2181. 'width': the_only_video.get('width'),
  2182. 'height': the_only_video.get('height'),
  2183. 'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
  2184. 'fps': the_only_video.get('fps'),
  2185. 'dynamic_range': the_only_video.get('dynamic_range'),
  2186. 'vcodec': the_only_video.get('vcodec'),
  2187. 'vbr': the_only_video.get('vbr'),
  2188. 'stretched_ratio': the_only_video.get('stretched_ratio'),
  2189. 'aspect_ratio': the_only_video.get('aspect_ratio'),
  2190. })
  2191. if the_only_audio:
  2192. new_dict.update({
  2193. 'acodec': the_only_audio.get('acodec'),
  2194. 'abr': the_only_audio.get('abr'),
  2195. 'asr': the_only_audio.get('asr'),
  2196. 'audio_channels': the_only_audio.get('audio_channels'),
  2197. })
  2198. return new_dict
  2199. def _check_formats(formats):
  2200. if self.params.get('check_formats') == 'selected':
  2201. yield from self._check_formats(formats)
  2202. return
  2203. elif (self.params.get('check_formats') is not None
  2204. or self.params.get('allow_unplayable_formats')):
  2205. yield from formats
  2206. return
  2207. for f in formats:
  2208. if f.get('has_drm') or f.get('__needs_testing'):
  2209. yield from self._check_formats([f])
  2210. else:
  2211. yield f
  2212. def _build_selector_function(selector):
  2213. if isinstance(selector, list): # ,
  2214. fs = [_build_selector_function(s) for s in selector]
  2215. def selector_function(ctx):
  2216. for f in fs:
  2217. yield from f(ctx)
  2218. return selector_function
  2219. elif selector.type == GROUP: # ()
  2220. selector_function = _build_selector_function(selector.selector)
  2221. elif selector.type == PICKFIRST: # /
  2222. fs = [_build_selector_function(s) for s in selector.selector]
  2223. def selector_function(ctx):
  2224. for f in fs:
  2225. picked_formats = list(f(ctx))
  2226. if picked_formats:
  2227. return picked_formats
  2228. return []
  2229. elif selector.type == MERGE: # +
  2230. selector_1, selector_2 = map(_build_selector_function, selector.selector)
  2231. def selector_function(ctx):
  2232. for pair in itertools.product(selector_1(ctx), selector_2(ctx)):
  2233. yield _merge(pair)
  2234. elif selector.type == SINGLE: # atom
  2235. format_spec = selector.selector or 'best'
  2236. # TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
  2237. if format_spec == 'all':
  2238. def selector_function(ctx):
  2239. yield from _check_formats(ctx['formats'][::-1])
  2240. elif format_spec == 'mergeall':
  2241. def selector_function(ctx):
  2242. formats = list(_check_formats(
  2243. f for f in ctx['formats'] if f.get('vcodec') != 'none' or f.get('acodec') != 'none'))
  2244. if not formats:
  2245. return
  2246. merged_format = formats[-1]
  2247. for f in formats[-2::-1]:
  2248. merged_format = _merge((merged_format, f))
  2249. yield merged_format
  2250. else:
  2251. format_fallback, seperate_fallback, format_reverse, format_idx = False, None, True, 1
  2252. mobj = re.match(
  2253. r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
  2254. format_spec)
  2255. if mobj is not None:
  2256. format_idx = int_or_none(mobj.group('n'), default=1)
  2257. format_reverse = mobj.group('bw')[0] == 'b'
  2258. format_type = (mobj.group('type') or [None])[0]
  2259. not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
  2260. format_modified = mobj.group('mod') is not None
  2261. format_fallback = not format_type and not format_modified # for b, w
  2262. _filter_f = (
  2263. (lambda f: f.get(f'{format_type}codec') != 'none')
  2264. if format_type and format_modified # bv*, ba*, wv*, wa*
  2265. else (lambda f: f.get(f'{not_format_type}codec') == 'none')
  2266. if format_type # bv, ba, wv, wa
  2267. else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
  2268. if not format_modified # b, w
  2269. else lambda f: True) # b*, w*
  2270. filter_f = lambda f: _filter_f(f) and (
  2271. f.get('vcodec') != 'none' or f.get('acodec') != 'none')
  2272. else:
  2273. if format_spec in self._format_selection_exts['audio']:
  2274. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
  2275. elif format_spec in self._format_selection_exts['video']:
  2276. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
  2277. seperate_fallback = lambda f: f.get('ext') == format_spec and f.get('vcodec') != 'none'
  2278. elif format_spec in self._format_selection_exts['storyboards']:
  2279. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
  2280. else:
  2281. filter_f = lambda f: f.get('format_id') == format_spec # id
  2282. def selector_function(ctx):
  2283. formats = list(ctx['formats'])
  2284. matches = list(filter(filter_f, formats)) if filter_f is not None else formats
  2285. if not matches:
  2286. if format_fallback and ctx['incomplete_formats']:
  2287. # for extractors with incomplete formats (audio only (soundcloud)
  2288. # or video only (imgur)) best/worst will fallback to
  2289. # best/worst {video,audio}-only format
  2290. matches = list(filter(lambda f: f.get('vcodec') != 'none' or f.get('acodec') != 'none', formats))
  2291. elif seperate_fallback and not ctx['has_merged_format']:
  2292. # for compatibility with youtube-dl when there is no pre-merged format
  2293. matches = list(filter(seperate_fallback, formats))
  2294. matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
  2295. try:
  2296. yield matches[format_idx - 1]
  2297. except LazyList.IndexError:
  2298. return
  2299. filters = [self._build_format_filter(f) for f in selector.filters]
  2300. def final_selector(ctx):
  2301. ctx_copy = dict(ctx)
  2302. for _filter in filters:
  2303. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  2304. return selector_function(ctx_copy)
  2305. return final_selector
  2306. # HACK: Python 3.12 changed the underlying parser, rendering '7_a' invalid
  2307. # Prefix numbers with random letters to avoid it being classified as a number
  2308. # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
  2309. # TODO: Implement parser not reliant on tokenize.tokenize
  2310. prefix = ''.join(random.choices(string.ascii_letters, k=32))
  2311. stream = io.BytesIO(re.sub(r'\d[_\d]*', rf'{prefix}\g<0>', format_spec).encode())
  2312. try:
  2313. tokens = list(_remove_unused_ops(
  2314. token._replace(string=token.string.replace(prefix, ''))
  2315. for token in tokenize.tokenize(stream.readline)))
  2316. except tokenize.TokenError:
  2317. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  2318. class TokenIterator:
  2319. def __init__(self, tokens):
  2320. self.tokens = tokens
  2321. self.counter = 0
  2322. def __iter__(self):
  2323. return self
  2324. def __next__(self):
  2325. if self.counter >= len(self.tokens):
  2326. raise StopIteration
  2327. value = self.tokens[self.counter]
  2328. self.counter += 1
  2329. return value
  2330. next = __next__
  2331. def restore_last_token(self):
  2332. self.counter -= 1
  2333. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  2334. return _build_selector_function(parsed_selector)
  2335. def _calc_headers(self, info_dict, load_cookies=False):
  2336. res = HTTPHeaderDict(self.params['http_headers'], info_dict.get('http_headers'))
  2337. clean_headers(res)
  2338. if load_cookies: # For --load-info-json
  2339. self._load_cookies(res.get('Cookie'), autoscope=info_dict['url']) # compat
  2340. self._load_cookies(info_dict.get('cookies'), autoscope=False)
  2341. # The `Cookie` header is removed to prevent leaks and unscoped cookies.
  2342. # See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  2343. res.pop('Cookie', None)
  2344. cookies = self.cookiejar.get_cookies_for_url(info_dict['url'])
  2345. if cookies:
  2346. encoder = LenientSimpleCookie()
  2347. values = []
  2348. for cookie in cookies:
  2349. _, value = encoder.value_encode(cookie.value)
  2350. values.append(f'{cookie.name}={value}')
  2351. if cookie.domain:
  2352. values.append(f'Domain={cookie.domain}')
  2353. if cookie.path:
  2354. values.append(f'Path={cookie.path}')
  2355. if cookie.secure:
  2356. values.append('Secure')
  2357. if cookie.expires:
  2358. values.append(f'Expires={cookie.expires}')
  2359. if cookie.version:
  2360. values.append(f'Version={cookie.version}')
  2361. info_dict['cookies'] = '; '.join(values)
  2362. if 'X-Forwarded-For' not in res:
  2363. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  2364. if x_forwarded_for_ip:
  2365. res['X-Forwarded-For'] = x_forwarded_for_ip
  2366. return res
  2367. def _calc_cookies(self, url):
  2368. self.deprecation_warning('"YoutubeDL._calc_cookies" is deprecated and may be removed in a future version')
  2369. return self.cookiejar.get_cookie_header(url)
  2370. def _sort_thumbnails(self, thumbnails):
  2371. thumbnails.sort(key=lambda t: (
  2372. t.get('preference') if t.get('preference') is not None else -1,
  2373. t.get('width') if t.get('width') is not None else -1,
  2374. t.get('height') if t.get('height') is not None else -1,
  2375. t.get('id') if t.get('id') is not None else '',
  2376. t.get('url')))
  2377. def _sanitize_thumbnails(self, info_dict):
  2378. thumbnails = info_dict.get('thumbnails')
  2379. if thumbnails is None:
  2380. thumbnail = info_dict.get('thumbnail')
  2381. if thumbnail:
  2382. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  2383. if not thumbnails:
  2384. return
  2385. def check_thumbnails(thumbnails):
  2386. for t in thumbnails:
  2387. self.to_screen(f'[info] Testing thumbnail {t["id"]}')
  2388. try:
  2389. self.urlopen(HEADRequest(t['url']))
  2390. except network_exceptions as err:
  2391. self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...')
  2392. continue
  2393. yield t
  2394. self._sort_thumbnails(thumbnails)
  2395. for i, t in enumerate(thumbnails):
  2396. if t.get('id') is None:
  2397. t['id'] = str(i)
  2398. if t.get('width') and t.get('height'):
  2399. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  2400. t['url'] = sanitize_url(t['url'])
  2401. if self.params.get('check_formats') is True:
  2402. info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
  2403. else:
  2404. info_dict['thumbnails'] = thumbnails
  2405. def _fill_common_fields(self, info_dict, final=True):
  2406. # TODO: move sanitization here
  2407. if final:
  2408. title = info_dict['fulltitle'] = info_dict.get('title')
  2409. if not title:
  2410. if title == '':
  2411. self.write_debug('Extractor gave empty title. Creating a generic title')
  2412. else:
  2413. self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
  2414. info_dict['title'] = f'{info_dict["extractor"].replace(":", "-")} video #{info_dict["id"]}'
  2415. if info_dict.get('duration') is not None:
  2416. info_dict['duration_string'] = formatSeconds(info_dict['duration'])
  2417. for ts_key, date_key in (
  2418. ('timestamp', 'upload_date'),
  2419. ('release_timestamp', 'release_date'),
  2420. ('modified_timestamp', 'modified_date'),
  2421. ):
  2422. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  2423. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  2424. # see http://bugs.python.org/issue1646728)
  2425. with contextlib.suppress(ValueError, OverflowError, OSError):
  2426. upload_date = dt.datetime.fromtimestamp(info_dict[ts_key], dt.timezone.utc)
  2427. info_dict[date_key] = upload_date.strftime('%Y%m%d')
  2428. if not info_dict.get('release_year'):
  2429. info_dict['release_year'] = traverse_obj(info_dict, ('release_date', {lambda x: int(x[:4])}))
  2430. live_keys = ('is_live', 'was_live')
  2431. live_status = info_dict.get('live_status')
  2432. if live_status is None:
  2433. for key in live_keys:
  2434. if info_dict.get(key) is False:
  2435. continue
  2436. if info_dict.get(key):
  2437. live_status = key
  2438. break
  2439. if all(info_dict.get(key) is False for key in live_keys):
  2440. live_status = 'not_live'
  2441. if live_status:
  2442. info_dict['live_status'] = live_status
  2443. for key in live_keys:
  2444. if info_dict.get(key) is None:
  2445. info_dict[key] = (live_status == key)
  2446. if live_status == 'post_live':
  2447. info_dict['was_live'] = True
  2448. # Auto generate title fields corresponding to the *_number fields when missing
  2449. # in order to always have clean titles. This is very common for TV series.
  2450. for field in ('chapter', 'season', 'episode'):
  2451. if final and info_dict.get(f'{field}_number') is not None and not info_dict.get(field):
  2452. info_dict[field] = '%s %d' % (field.capitalize(), info_dict[f'{field}_number'])
  2453. for old_key, new_key in self._deprecated_multivalue_fields.items():
  2454. if new_key in info_dict and old_key in info_dict:
  2455. if '_version' not in info_dict: # HACK: Do not warn when using --load-info-json
  2456. self.deprecation_warning(f'Do not return {old_key!r} when {new_key!r} is present')
  2457. elif old_value := info_dict.get(old_key):
  2458. info_dict[new_key] = old_value.split(', ')
  2459. elif new_value := info_dict.get(new_key):
  2460. info_dict[old_key] = ', '.join(v.replace(',', '\N{FULLWIDTH COMMA}') for v in new_value)
  2461. def _raise_pending_errors(self, info):
  2462. err = info.pop('__pending_error', None)
  2463. if err:
  2464. self.report_error(err, tb=False)
  2465. def sort_formats(self, info_dict):
  2466. formats = self._get_formats(info_dict)
  2467. formats.sort(key=FormatSorter(
  2468. self, info_dict.get('_format_sort_fields') or []).calculate_preference)
  2469. def process_video_result(self, info_dict, download=True):
  2470. assert info_dict.get('_type', 'video') == 'video'
  2471. self._num_videos += 1
  2472. if 'id' not in info_dict:
  2473. raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
  2474. elif not info_dict.get('id'):
  2475. raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
  2476. def report_force_conversion(field, field_not, conversion):
  2477. self.report_warning(
  2478. f'"{field}" field is not {field_not} - forcing {conversion} conversion, '
  2479. 'there is an error in extractor')
  2480. def sanitize_string_field(info, string_field):
  2481. field = info.get(string_field)
  2482. if field is None or isinstance(field, str):
  2483. return
  2484. report_force_conversion(string_field, 'a string', 'string')
  2485. info[string_field] = str(field)
  2486. def sanitize_numeric_fields(info):
  2487. for numeric_field in self._NUMERIC_FIELDS:
  2488. field = info.get(numeric_field)
  2489. if field is None or isinstance(field, (int, float)):
  2490. continue
  2491. report_force_conversion(numeric_field, 'numeric', 'int')
  2492. info[numeric_field] = int_or_none(field)
  2493. sanitize_string_field(info_dict, 'id')
  2494. sanitize_numeric_fields(info_dict)
  2495. if info_dict.get('section_end') and info_dict.get('section_start') is not None:
  2496. info_dict['duration'] = round(info_dict['section_end'] - info_dict['section_start'], 3)
  2497. if (info_dict.get('duration') or 0) <= 0 and info_dict.pop('duration', None):
  2498. self.report_warning('"duration" field is negative, there is an error in extractor')
  2499. chapters = info_dict.get('chapters') or []
  2500. if chapters and chapters[0].get('start_time'):
  2501. chapters.insert(0, {'start_time': 0})
  2502. dummy_chapter = {'end_time': 0, 'start_time': info_dict.get('duration')}
  2503. for idx, (prev, current, next_) in enumerate(zip(
  2504. (dummy_chapter, *chapters), chapters, (*chapters[1:], dummy_chapter)), 1):
  2505. if current.get('start_time') is None:
  2506. current['start_time'] = prev.get('end_time')
  2507. if not current.get('end_time'):
  2508. current['end_time'] = next_.get('start_time')
  2509. if not current.get('title'):
  2510. current['title'] = f'<Untitled Chapter {idx}>'
  2511. if 'playlist' not in info_dict:
  2512. # It isn't part of a playlist
  2513. info_dict['playlist'] = None
  2514. info_dict['playlist_index'] = None
  2515. self._sanitize_thumbnails(info_dict)
  2516. thumbnail = info_dict.get('thumbnail')
  2517. thumbnails = info_dict.get('thumbnails')
  2518. if thumbnail:
  2519. info_dict['thumbnail'] = sanitize_url(thumbnail)
  2520. elif thumbnails:
  2521. info_dict['thumbnail'] = thumbnails[-1]['url']
  2522. if info_dict.get('display_id') is None and 'id' in info_dict:
  2523. info_dict['display_id'] = info_dict['id']
  2524. self._fill_common_fields(info_dict)
  2525. for cc_kind in ('subtitles', 'automatic_captions'):
  2526. cc = info_dict.get(cc_kind)
  2527. if cc:
  2528. for _, subtitle in cc.items():
  2529. for subtitle_format in subtitle:
  2530. if subtitle_format.get('url'):
  2531. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  2532. if subtitle_format.get('ext') is None:
  2533. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  2534. automatic_captions = info_dict.get('automatic_captions')
  2535. subtitles = info_dict.get('subtitles')
  2536. info_dict['requested_subtitles'] = self.process_subtitles(
  2537. info_dict['id'], subtitles, automatic_captions)
  2538. formats = self._get_formats(info_dict)
  2539. # Backward compatibility with InfoExtractor._sort_formats
  2540. field_preference = (formats or [{}])[0].pop('__sort_fields', None)
  2541. if field_preference:
  2542. info_dict['_format_sort_fields'] = field_preference
  2543. info_dict['_has_drm'] = any( # or None ensures --clean-infojson removes it
  2544. f.get('has_drm') and f['has_drm'] != 'maybe' for f in formats) or None
  2545. if not self.params.get('allow_unplayable_formats'):
  2546. formats = [f for f in formats if not f.get('has_drm') or f['has_drm'] == 'maybe']
  2547. if formats and all(f.get('acodec') == f.get('vcodec') == 'none' for f in formats):
  2548. self.report_warning(
  2549. f'{"This video is DRM protected and " if info_dict["_has_drm"] else ""}'
  2550. 'only images are available for download. Use --list-formats to see them'.capitalize())
  2551. get_from_start = not info_dict.get('is_live') or bool(self.params.get('live_from_start'))
  2552. if not get_from_start:
  2553. info_dict['title'] += ' ' + dt.datetime.now().strftime('%Y-%m-%d %H:%M')
  2554. if info_dict.get('is_live') and formats:
  2555. formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
  2556. if get_from_start and not formats:
  2557. self.raise_no_formats(info_dict, msg=(
  2558. '--live-from-start is passed, but there are no formats that can be downloaded from the start. '
  2559. 'If you want to download from the current time, use --no-live-from-start'))
  2560. def is_wellformed(f):
  2561. url = f.get('url')
  2562. if not url:
  2563. self.report_warning(
  2564. '"url" field is missing or empty - skipping format, '
  2565. 'there is an error in extractor')
  2566. return False
  2567. if isinstance(url, bytes):
  2568. sanitize_string_field(f, 'url')
  2569. return True
  2570. # Filter out malformed formats for better extraction robustness
  2571. formats = list(filter(is_wellformed, formats or []))
  2572. if not formats:
  2573. self.raise_no_formats(info_dict)
  2574. for fmt in formats:
  2575. sanitize_string_field(fmt, 'format_id')
  2576. sanitize_numeric_fields(fmt)
  2577. fmt['url'] = sanitize_url(fmt['url'])
  2578. FormatSorter._fill_sorting_fields(fmt)
  2579. if fmt['ext'] in ('aac', 'opus', 'mp3', 'flac', 'vorbis'):
  2580. if fmt.get('acodec') is None:
  2581. fmt['acodec'] = fmt['ext']
  2582. if fmt.get('resolution') is None:
  2583. fmt['resolution'] = self.format_resolution(fmt, default=None)
  2584. if fmt.get('dynamic_range') is None and fmt.get('vcodec') != 'none':
  2585. fmt['dynamic_range'] = 'SDR'
  2586. if fmt.get('aspect_ratio') is None:
  2587. fmt['aspect_ratio'] = try_call(lambda: round(fmt['width'] / fmt['height'], 2))
  2588. # For fragmented formats, "tbr" is often max bitrate and not average
  2589. if (('manifest-filesize-approx' in self.params['compat_opts'] or not fmt.get('manifest_url'))
  2590. and not fmt.get('filesize') and not fmt.get('filesize_approx')):
  2591. fmt['filesize_approx'] = filesize_from_tbr(fmt.get('tbr'), info_dict.get('duration'))
  2592. fmt['http_headers'] = self._calc_headers(collections.ChainMap(fmt, info_dict), load_cookies=True)
  2593. # Safeguard against old/insecure infojson when using --load-info-json
  2594. if info_dict.get('http_headers'):
  2595. info_dict['http_headers'] = HTTPHeaderDict(info_dict['http_headers'])
  2596. info_dict['http_headers'].pop('Cookie', None)
  2597. # This is copied to http_headers by the above _calc_headers and can now be removed
  2598. if '__x_forwarded_for_ip' in info_dict:
  2599. del info_dict['__x_forwarded_for_ip']
  2600. self.sort_formats({
  2601. 'formats': formats,
  2602. '_format_sort_fields': info_dict.get('_format_sort_fields'),
  2603. })
  2604. # Sanitize and group by format_id
  2605. formats_dict = {}
  2606. for i, fmt in enumerate(formats):
  2607. if not fmt.get('format_id'):
  2608. fmt['format_id'] = str(i)
  2609. else:
  2610. # Sanitize format_id from characters used in format selector expression
  2611. fmt['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', fmt['format_id'])
  2612. formats_dict.setdefault(fmt['format_id'], []).append(fmt)
  2613. # Make sure all formats have unique format_id
  2614. common_exts = set(itertools.chain(*self._format_selection_exts.values()))
  2615. for format_id, ambiguous_formats in formats_dict.items():
  2616. ambigious_id = len(ambiguous_formats) > 1
  2617. for i, fmt in enumerate(ambiguous_formats):
  2618. if ambigious_id:
  2619. fmt['format_id'] = f'{format_id}-{i}'
  2620. # Ensure there is no conflict between id and ext in format selection
  2621. # See https://github.com/yt-dlp/yt-dlp/issues/1282
  2622. if fmt['format_id'] != fmt['ext'] and fmt['format_id'] in common_exts:
  2623. fmt['format_id'] = 'f{}'.format(fmt['format_id'])
  2624. if fmt.get('format') is None:
  2625. fmt['format'] = '{id} - {res}{note}'.format(
  2626. id=fmt['format_id'],
  2627. res=self.format_resolution(fmt),
  2628. note=format_field(fmt, 'format_note', ' (%s)'),
  2629. )
  2630. if self.params.get('check_formats') is True:
  2631. formats = LazyList(self._check_formats(formats[::-1]), reverse=True)
  2632. if not formats or formats[0] is not info_dict:
  2633. # only set the 'formats' fields if the original info_dict list them
  2634. # otherwise we end up with a circular reference, the first (and unique)
  2635. # element in the 'formats' field in info_dict is info_dict itself,
  2636. # which can't be exported to json
  2637. info_dict['formats'] = formats
  2638. info_dict, _ = self.pre_process(info_dict)
  2639. if self._match_entry(info_dict, incomplete=self._format_fields) is not None:
  2640. return info_dict
  2641. self.post_extract(info_dict)
  2642. info_dict, _ = self.pre_process(info_dict, 'after_filter')
  2643. # The pre-processors may have modified the formats
  2644. formats = self._get_formats(info_dict)
  2645. list_only = self.params.get('simulate') == 'list_only'
  2646. interactive_format_selection = not list_only and self.format_selector == '-'
  2647. if self.params.get('list_thumbnails'):
  2648. self.list_thumbnails(info_dict)
  2649. if self.params.get('listsubtitles'):
  2650. if 'automatic_captions' in info_dict:
  2651. self.list_subtitles(
  2652. info_dict['id'], automatic_captions, 'automatic captions')
  2653. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  2654. if self.params.get('listformats') or interactive_format_selection:
  2655. self.list_formats(info_dict)
  2656. if list_only:
  2657. # Without this printing, -F --print-json will not work
  2658. self.__forced_printings(info_dict)
  2659. return info_dict
  2660. format_selector = self.format_selector
  2661. while True:
  2662. if interactive_format_selection:
  2663. req_format = input(self._format_screen('\nEnter format selector ', self.Styles.EMPHASIS)
  2664. + '(Press ENTER for default, or Ctrl+C to quit)'
  2665. + self._format_screen(': ', self.Styles.EMPHASIS))
  2666. try:
  2667. format_selector = self.build_format_selector(req_format) if req_format else None
  2668. except SyntaxError as err:
  2669. self.report_error(err, tb=False, is_error=False)
  2670. continue
  2671. if format_selector is None:
  2672. req_format = self._default_format_spec(info_dict)
  2673. self.write_debug(f'Default format spec: {req_format}')
  2674. format_selector = self.build_format_selector(req_format)
  2675. formats_to_download = self._select_formats(formats, format_selector)
  2676. if interactive_format_selection and not formats_to_download:
  2677. self.report_error('Requested format is not available', tb=False, is_error=False)
  2678. continue
  2679. break
  2680. if not formats_to_download:
  2681. if not self.params.get('ignore_no_formats_error'):
  2682. raise ExtractorError(
  2683. 'Requested format is not available. Use --list-formats for a list of available formats',
  2684. expected=True, video_id=info_dict['id'], ie=info_dict['extractor'])
  2685. self.report_warning('Requested format is not available')
  2686. # Process what we can, even without any available formats.
  2687. formats_to_download = [{}]
  2688. requested_ranges = tuple(self.params.get('download_ranges', lambda *_: [{}])(info_dict, self))
  2689. best_format, downloaded_formats = formats_to_download[-1], []
  2690. if download:
  2691. if best_format and requested_ranges:
  2692. def to_screen(*msg):
  2693. self.to_screen(f'[info] {info_dict["id"]}: {" ".join(", ".join(variadic(m)) for m in msg)}')
  2694. to_screen(f'Downloading {len(formats_to_download)} format(s):',
  2695. (f['format_id'] for f in formats_to_download))
  2696. if requested_ranges != ({}, ):
  2697. to_screen(f'Downloading {len(requested_ranges)} time ranges:',
  2698. (f'{c["start_time"]:.1f}-{c["end_time"]:.1f}' for c in requested_ranges))
  2699. max_downloads_reached = False
  2700. for fmt, chapter in itertools.product(formats_to_download, requested_ranges):
  2701. new_info = self._copy_infodict(info_dict)
  2702. new_info.update(fmt)
  2703. offset, duration = info_dict.get('section_start') or 0, info_dict.get('duration') or float('inf')
  2704. end_time = offset + min(chapter.get('end_time', duration), duration)
  2705. # duration may not be accurate. So allow deviations <1sec
  2706. if end_time == float('inf') or end_time > offset + duration + 1:
  2707. end_time = None
  2708. if chapter or offset:
  2709. new_info.update({
  2710. 'section_start': offset + chapter.get('start_time', 0),
  2711. 'section_end': end_time,
  2712. 'section_title': chapter.get('title'),
  2713. 'section_number': chapter.get('index'),
  2714. })
  2715. downloaded_formats.append(new_info)
  2716. try:
  2717. self.process_info(new_info)
  2718. except MaxDownloadsReached:
  2719. max_downloads_reached = True
  2720. self._raise_pending_errors(new_info)
  2721. # Remove copied info
  2722. for key, val in tuple(new_info.items()):
  2723. if info_dict.get(key) == val:
  2724. new_info.pop(key)
  2725. if max_downloads_reached:
  2726. break
  2727. write_archive = {f.get('__write_download_archive', False) for f in downloaded_formats}
  2728. assert write_archive.issubset({True, False, 'ignore'})
  2729. if True in write_archive and False not in write_archive:
  2730. self.record_download_archive(info_dict)
  2731. info_dict['requested_downloads'] = downloaded_formats
  2732. info_dict = self.run_all_pps('after_video', info_dict)
  2733. if max_downloads_reached:
  2734. raise MaxDownloadsReached
  2735. # We update the info dict with the selected best quality format (backwards compatibility)
  2736. info_dict.update(best_format)
  2737. return info_dict
  2738. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  2739. """Select the requested subtitles and their format"""
  2740. available_subs, normal_sub_langs = {}, []
  2741. if normal_subtitles and self.params.get('writesubtitles'):
  2742. available_subs.update(normal_subtitles)
  2743. normal_sub_langs = tuple(normal_subtitles.keys())
  2744. if automatic_captions and self.params.get('writeautomaticsub'):
  2745. for lang, cap_info in automatic_captions.items():
  2746. if lang not in available_subs:
  2747. available_subs[lang] = cap_info
  2748. if not available_subs or (
  2749. not self.params.get('writesubtitles')
  2750. and not self.params.get('writeautomaticsub')):
  2751. return None
  2752. all_sub_langs = tuple(available_subs.keys())
  2753. if self.params.get('allsubtitles', False):
  2754. requested_langs = all_sub_langs
  2755. elif self.params.get('subtitleslangs', False):
  2756. try:
  2757. requested_langs = orderedSet_from_options(
  2758. self.params.get('subtitleslangs'), {'all': all_sub_langs}, use_regex=True)
  2759. except re.error as e:
  2760. raise ValueError(f'Wrong regex for subtitlelangs: {e.pattern}')
  2761. else:
  2762. requested_langs = LazyList(itertools.chain(
  2763. ['en'] if 'en' in normal_sub_langs else [],
  2764. filter(lambda f: f.startswith('en'), normal_sub_langs),
  2765. ['en'] if 'en' in all_sub_langs else [],
  2766. filter(lambda f: f.startswith('en'), all_sub_langs),
  2767. normal_sub_langs, all_sub_langs,
  2768. ))[:1]
  2769. if requested_langs:
  2770. self.to_screen(f'[info] {video_id}: Downloading subtitles: {", ".join(requested_langs)}')
  2771. formats_query = self.params.get('subtitlesformat', 'best')
  2772. formats_preference = formats_query.split('/') if formats_query else []
  2773. subs = {}
  2774. for lang in requested_langs:
  2775. formats = available_subs.get(lang)
  2776. if formats is None:
  2777. self.report_warning(f'{lang} subtitles not available for {video_id}')
  2778. continue
  2779. for ext in formats_preference:
  2780. if ext == 'best':
  2781. f = formats[-1]
  2782. break
  2783. matches = list(filter(lambda f: f['ext'] == ext, formats))
  2784. if matches:
  2785. f = matches[-1]
  2786. break
  2787. else:
  2788. f = formats[-1]
  2789. self.report_warning(
  2790. 'No subtitle format found matching "{}" for language {}, '
  2791. 'using {}. Use --list-subs for a list of available subtitles'.format(formats_query, lang, f['ext']))
  2792. subs[lang] = f
  2793. return subs
  2794. def _forceprint(self, key, info_dict):
  2795. if info_dict is None:
  2796. return
  2797. info_copy = info_dict.copy()
  2798. info_copy.setdefault('filename', self.prepare_filename(info_dict))
  2799. if info_dict.get('requested_formats') is not None:
  2800. # For RTMP URLs, also include the playpath
  2801. info_copy['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
  2802. elif info_dict.get('url'):
  2803. info_copy['urls'] = info_dict['url'] + info_dict.get('play_path', '')
  2804. info_copy['formats_table'] = self.render_formats_table(info_dict)
  2805. info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
  2806. info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
  2807. info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
  2808. def format_tmpl(tmpl):
  2809. mobj = re.fullmatch(r'([\w.:,]|-\d|(?P<dict>{([\w.:,]|-\d)+}))+=?', tmpl)
  2810. if not mobj:
  2811. return tmpl
  2812. fmt = '%({})s'
  2813. if tmpl.startswith('{'):
  2814. tmpl, fmt = f'.{tmpl}', '%({})j'
  2815. if tmpl.endswith('='):
  2816. tmpl, fmt = tmpl[:-1], '{0} = %({0})#j'
  2817. return '\n'.join(map(fmt.format, [tmpl] if mobj.group('dict') else tmpl.split(',')))
  2818. for tmpl in self.params['forceprint'].get(key, []):
  2819. self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
  2820. for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
  2821. filename = self.prepare_filename(info_dict, outtmpl=file_tmpl)
  2822. tmpl = format_tmpl(tmpl)
  2823. self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
  2824. if self._ensure_dir_exists(filename):
  2825. with open(filename, 'a', encoding='utf-8', newline='') as f:
  2826. f.write(self.evaluate_outtmpl(tmpl, info_copy) + os.linesep)
  2827. return info_copy
  2828. def __forced_printings(self, info_dict, filename=None, incomplete=True):
  2829. if (self.params.get('forcejson')
  2830. or self.params['forceprint'].get('video')
  2831. or self.params['print_to_file'].get('video')):
  2832. self.post_extract(info_dict)
  2833. if filename:
  2834. info_dict['filename'] = filename
  2835. info_copy = self._forceprint('video', info_dict)
  2836. def print_field(field, actual_field=None, optional=False):
  2837. if actual_field is None:
  2838. actual_field = field
  2839. if self.params.get(f'force{field}') and (
  2840. info_copy.get(field) is not None or (not optional and not incomplete)):
  2841. self.to_stdout(info_copy[actual_field])
  2842. print_field('title')
  2843. print_field('id')
  2844. print_field('url', 'urls')
  2845. print_field('thumbnail', optional=True)
  2846. print_field('description', optional=True)
  2847. print_field('filename')
  2848. if self.params.get('forceduration') and info_copy.get('duration') is not None:
  2849. self.to_stdout(formatSeconds(info_copy['duration']))
  2850. print_field('format')
  2851. if self.params.get('forcejson'):
  2852. self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
  2853. def dl(self, name, info, subtitle=False, test=False):
  2854. if not info.get('url'):
  2855. self.raise_no_formats(info, True)
  2856. if test:
  2857. verbose = self.params.get('verbose')
  2858. quiet = self.params.get('quiet') or not verbose
  2859. params = {
  2860. 'test': True,
  2861. 'quiet': quiet,
  2862. 'verbose': verbose,
  2863. 'noprogress': quiet,
  2864. 'nopart': True,
  2865. 'skip_unavailable_fragments': False,
  2866. 'keep_fragments': False,
  2867. 'overwrites': True,
  2868. '_no_ytdl_file': True,
  2869. }
  2870. else:
  2871. params = self.params
  2872. fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
  2873. if not test:
  2874. for ph in self._progress_hooks:
  2875. fd.add_progress_hook(ph)
  2876. urls = '", "'.join(
  2877. (f['url'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
  2878. for f in info.get('requested_formats', []) or [info])
  2879. self.write_debug(f'Invoking {fd.FD_NAME} downloader on "{urls}"')
  2880. # Note: Ideally info should be a deep-copied so that hooks cannot modify it.
  2881. # But it may contain objects that are not deep-copyable
  2882. new_info = self._copy_infodict(info)
  2883. if new_info.get('http_headers') is None:
  2884. new_info['http_headers'] = self._calc_headers(new_info)
  2885. return fd.download(name, new_info, subtitle)
  2886. def existing_file(self, filepaths, *, default_overwrite=True):
  2887. existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
  2888. if existing_files and not self.params.get('overwrites', default_overwrite):
  2889. return existing_files[0]
  2890. for file in existing_files:
  2891. self.report_file_delete(file)
  2892. os.remove(file)
  2893. return None
  2894. @_catch_unsafe_extension_error
  2895. def process_info(self, info_dict):
  2896. """Process a single resolved IE result. (Modifies it in-place)"""
  2897. assert info_dict.get('_type', 'video') == 'video'
  2898. original_infodict = info_dict
  2899. if 'format' not in info_dict and 'ext' in info_dict:
  2900. info_dict['format'] = info_dict['ext']
  2901. if self._match_entry(info_dict) is not None:
  2902. info_dict['__write_download_archive'] = 'ignore'
  2903. return
  2904. # Does nothing under normal operation - for backward compatibility of process_info
  2905. self.post_extract(info_dict)
  2906. def replace_info_dict(new_info):
  2907. nonlocal info_dict
  2908. if new_info == info_dict:
  2909. return
  2910. info_dict.clear()
  2911. info_dict.update(new_info)
  2912. new_info, _ = self.pre_process(info_dict, 'video')
  2913. replace_info_dict(new_info)
  2914. self._num_downloads += 1
  2915. # info_dict['_filename'] needs to be set for backward compatibility
  2916. info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
  2917. temp_filename = self.prepare_filename(info_dict, 'temp')
  2918. files_to_move = {}
  2919. # Forced printings
  2920. self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
  2921. def check_max_downloads():
  2922. if self._num_downloads >= float(self.params.get('max_downloads') or 'inf'):
  2923. raise MaxDownloadsReached
  2924. if self.params.get('simulate'):
  2925. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2926. check_max_downloads()
  2927. return
  2928. if full_filename is None:
  2929. return
  2930. if not self._ensure_dir_exists(full_filename):
  2931. return
  2932. if not self._ensure_dir_exists(temp_filename):
  2933. return
  2934. if self._write_description('video', info_dict,
  2935. self.prepare_filename(info_dict, 'description')) is None:
  2936. return
  2937. sub_files = self._write_subtitles(info_dict, temp_filename)
  2938. if sub_files is None:
  2939. return
  2940. files_to_move.update(dict(sub_files))
  2941. thumb_files = self._write_thumbnails(
  2942. 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
  2943. if thumb_files is None:
  2944. return
  2945. files_to_move.update(dict(thumb_files))
  2946. infofn = self.prepare_filename(info_dict, 'infojson')
  2947. _infojson_written = self._write_info_json('video', info_dict, infofn)
  2948. if _infojson_written:
  2949. info_dict['infojson_filename'] = infofn
  2950. # For backward compatibility, even though it was a private field
  2951. info_dict['__infojson_filename'] = infofn
  2952. elif _infojson_written is None:
  2953. return
  2954. # Note: Annotations are deprecated
  2955. annofn = None
  2956. if self.params.get('writeannotations', False):
  2957. annofn = self.prepare_filename(info_dict, 'annotation')
  2958. if annofn:
  2959. if not self._ensure_dir_exists(annofn):
  2960. return
  2961. if not self.params.get('overwrites', True) and os.path.exists(annofn):
  2962. self.to_screen('[info] Video annotations are already present')
  2963. elif not info_dict.get('annotations'):
  2964. self.report_warning('There are no annotations to write.')
  2965. else:
  2966. try:
  2967. self.to_screen('[info] Writing video annotations to: ' + annofn)
  2968. with open(annofn, 'w', encoding='utf-8') as annofile:
  2969. annofile.write(info_dict['annotations'])
  2970. except (KeyError, TypeError):
  2971. self.report_warning('There are no annotations to write.')
  2972. except OSError:
  2973. self.report_error('Cannot write annotations file: ' + annofn)
  2974. return
  2975. # Write internet shortcut files
  2976. def _write_link_file(link_type):
  2977. url = try_get(info_dict['webpage_url'], iri_to_uri)
  2978. if not url:
  2979. self.report_warning(
  2980. f'Cannot write internet shortcut file because the actual URL of "{info_dict["webpage_url"]}" is unknown')
  2981. return True
  2982. linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext'))
  2983. if not self._ensure_dir_exists(linkfn):
  2984. return False
  2985. if self.params.get('overwrites', True) and os.path.exists(linkfn):
  2986. self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
  2987. return True
  2988. try:
  2989. self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
  2990. with open(to_high_limit_path(linkfn), 'w', encoding='utf-8',
  2991. newline='\r\n' if link_type == 'url' else '\n') as linkfile:
  2992. template_vars = {'url': url}
  2993. if link_type == 'desktop':
  2994. template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
  2995. linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
  2996. except OSError:
  2997. self.report_error(f'Cannot write internet shortcut {linkfn}')
  2998. return False
  2999. return True
  3000. write_links = {
  3001. 'url': self.params.get('writeurllink'),
  3002. 'webloc': self.params.get('writewebloclink'),
  3003. 'desktop': self.params.get('writedesktoplink'),
  3004. }
  3005. if self.params.get('writelink'):
  3006. link_type = ('webloc' if sys.platform == 'darwin'
  3007. else 'desktop' if sys.platform.startswith('linux')
  3008. else 'url')
  3009. write_links[link_type] = True
  3010. if any(should_write and not _write_link_file(link_type)
  3011. for link_type, should_write in write_links.items()):
  3012. return
  3013. new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
  3014. replace_info_dict(new_info)
  3015. if self.params.get('skip_download'):
  3016. info_dict['filepath'] = temp_filename
  3017. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename))
  3018. info_dict['__files_to_move'] = files_to_move
  3019. replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
  3020. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  3021. else:
  3022. # Download
  3023. info_dict.setdefault('__postprocessors', [])
  3024. try:
  3025. def existing_video_file(*filepaths):
  3026. ext = info_dict.get('ext')
  3027. converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
  3028. file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths)),
  3029. default_overwrite=False)
  3030. if file:
  3031. info_dict['ext'] = os.path.splitext(file)[1][1:]
  3032. return file
  3033. fd, success = None, True
  3034. if info_dict.get('protocol') or info_dict.get('url'):
  3035. fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
  3036. if fd != FFmpegFD and 'no-direct-merge' not in self.params['compat_opts'] and (
  3037. info_dict.get('section_start') or info_dict.get('section_end')):
  3038. msg = ('This format cannot be partially downloaded' if FFmpegFD.available()
  3039. else 'You have requested downloading the video partially, but ffmpeg is not installed')
  3040. self.report_error(f'{msg}. Aborting')
  3041. return
  3042. if info_dict.get('requested_formats') is not None:
  3043. old_ext = info_dict['ext']
  3044. if self.params.get('merge_output_format') is None:
  3045. if (info_dict['ext'] == 'webm'
  3046. and info_dict.get('thumbnails')
  3047. # check with type instead of pp_key, __name__, or isinstance
  3048. # since we dont want any custom PPs to trigger this
  3049. and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])): # noqa: E721
  3050. info_dict['ext'] = 'mkv'
  3051. self.report_warning(
  3052. 'webm doesn\'t support embedding a thumbnail, mkv will be used')
  3053. new_ext = info_dict['ext']
  3054. def correct_ext(filename, ext=new_ext):
  3055. if filename == '-':
  3056. return filename
  3057. filename_real_ext = os.path.splitext(filename)[1][1:]
  3058. filename_wo_ext = (
  3059. os.path.splitext(filename)[0]
  3060. if filename_real_ext in (old_ext, new_ext)
  3061. else filename)
  3062. return f'{filename_wo_ext}.{ext}'
  3063. # Ensure filename always has a correct extension for successful merge
  3064. full_filename = correct_ext(full_filename)
  3065. temp_filename = correct_ext(temp_filename)
  3066. dl_filename = existing_video_file(full_filename, temp_filename)
  3067. info_dict['__real_download'] = False
  3068. # NOTE: Copy so that original format dicts are not modified
  3069. info_dict['requested_formats'] = list(map(dict, info_dict['requested_formats']))
  3070. merger = FFmpegMergerPP(self)
  3071. downloaded = []
  3072. if dl_filename is not None:
  3073. self.report_file_already_downloaded(dl_filename)
  3074. elif fd:
  3075. for f in info_dict['requested_formats'] if fd != FFmpegFD else []:
  3076. f['filepath'] = fname = prepend_extension(
  3077. correct_ext(temp_filename, info_dict['ext']),
  3078. 'f{}'.format(f['format_id']), info_dict['ext'])
  3079. downloaded.append(fname)
  3080. info_dict['url'] = '\n'.join(f['url'] for f in info_dict['requested_formats'])
  3081. success, real_download = self.dl(temp_filename, info_dict)
  3082. info_dict['__real_download'] = real_download
  3083. else:
  3084. if self.params.get('allow_unplayable_formats'):
  3085. self.report_warning(
  3086. 'You have requested merging of multiple formats '
  3087. 'while also allowing unplayable formats to be downloaded. '
  3088. 'The formats won\'t be merged to prevent data corruption.')
  3089. elif not merger.available:
  3090. msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
  3091. if not self.params.get('ignoreerrors'):
  3092. self.report_error(f'{msg}. Aborting due to --abort-on-error')
  3093. return
  3094. self.report_warning(f'{msg}. The formats won\'t be merged')
  3095. if temp_filename == '-':
  3096. reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
  3097. else 'but the formats are incompatible for simultaneous download' if merger.available
  3098. else 'but ffmpeg is not installed')
  3099. self.report_warning(
  3100. f'You have requested downloading multiple formats to stdout {reason}. '
  3101. 'The formats will be streamed one after the other')
  3102. fname = temp_filename
  3103. for f in info_dict['requested_formats']:
  3104. new_info = dict(info_dict)
  3105. del new_info['requested_formats']
  3106. new_info.update(f)
  3107. if temp_filename != '-':
  3108. fname = prepend_extension(
  3109. correct_ext(temp_filename, new_info['ext']),
  3110. 'f{}'.format(f['format_id']), new_info['ext'])
  3111. if not self._ensure_dir_exists(fname):
  3112. return
  3113. f['filepath'] = fname
  3114. downloaded.append(fname)
  3115. partial_success, real_download = self.dl(fname, new_info)
  3116. info_dict['__real_download'] = info_dict['__real_download'] or real_download
  3117. success = success and partial_success
  3118. if downloaded and merger.available and not self.params.get('allow_unplayable_formats'):
  3119. info_dict['__postprocessors'].append(merger)
  3120. info_dict['__files_to_merge'] = downloaded
  3121. # Even if there were no downloads, it is being merged only now
  3122. info_dict['__real_download'] = True
  3123. else:
  3124. for file in downloaded:
  3125. files_to_move[file] = None
  3126. else:
  3127. # Just a single file
  3128. dl_filename = existing_video_file(full_filename, temp_filename)
  3129. if dl_filename is None or dl_filename == temp_filename:
  3130. # dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
  3131. # So we should try to resume the download
  3132. success, real_download = self.dl(temp_filename, info_dict)
  3133. info_dict['__real_download'] = real_download
  3134. else:
  3135. self.report_file_already_downloaded(dl_filename)
  3136. dl_filename = dl_filename or temp_filename
  3137. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename))
  3138. except network_exceptions as err:
  3139. self.report_error(f'unable to download video data: {err}')
  3140. return
  3141. except OSError as err:
  3142. raise UnavailableVideoError(err)
  3143. except ContentTooShortError as err:
  3144. self.report_error(f'content too short (expected {err.expected} bytes and served {err.downloaded})')
  3145. return
  3146. self._raise_pending_errors(info_dict)
  3147. if success and full_filename != '-':
  3148. def fixup():
  3149. do_fixup = True
  3150. fixup_policy = self.params.get('fixup')
  3151. vid = info_dict['id']
  3152. if fixup_policy in ('ignore', 'never'):
  3153. return
  3154. elif fixup_policy == 'warn':
  3155. do_fixup = 'warn'
  3156. elif fixup_policy != 'force':
  3157. assert fixup_policy in ('detect_or_warn', None)
  3158. if not info_dict.get('__real_download'):
  3159. do_fixup = False
  3160. def ffmpeg_fixup(cndn, msg, cls):
  3161. if not (do_fixup and cndn):
  3162. return
  3163. elif do_fixup == 'warn':
  3164. self.report_warning(f'{vid}: {msg}')
  3165. return
  3166. pp = cls(self)
  3167. if pp.available:
  3168. info_dict['__postprocessors'].append(pp)
  3169. else:
  3170. self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
  3171. stretched_ratio = info_dict.get('stretched_ratio')
  3172. ffmpeg_fixup(stretched_ratio not in (1, None),
  3173. f'Non-uniform pixel ratio {stretched_ratio}',
  3174. FFmpegFixupStretchedPP)
  3175. downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
  3176. downloader = downloader.FD_NAME if downloader else None
  3177. ext = info_dict.get('ext')
  3178. postprocessed_by_ffmpeg = info_dict.get('requested_formats') or any((
  3179. isinstance(pp, FFmpegVideoConvertorPP)
  3180. and resolve_recode_mapping(ext, pp.mapping)[0] not in (ext, None)
  3181. ) for pp in self._pps['post_process'])
  3182. if not postprocessed_by_ffmpeg:
  3183. ffmpeg_fixup(fd != FFmpegFD and ext == 'm4a'
  3184. and info_dict.get('container') == 'm4a_dash',
  3185. 'writing DASH m4a. Only some players support this container',
  3186. FFmpegFixupM4aPP)
  3187. ffmpeg_fixup((downloader == 'hlsnative' and not self.params.get('hls_use_mpegts'))
  3188. or (info_dict.get('is_live') and self.params.get('hls_use_mpegts') is None),
  3189. 'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
  3190. FFmpegFixupM3u8PP)
  3191. ffmpeg_fixup(downloader == 'dashsegments'
  3192. and (info_dict.get('is_live') or info_dict.get('is_dash_periods')),
  3193. 'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
  3194. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
  3195. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed duration detected', FFmpegFixupDurationPP)
  3196. fixup()
  3197. try:
  3198. replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
  3199. except PostProcessingError as err:
  3200. self.report_error(f'Postprocessing: {err}')
  3201. return
  3202. try:
  3203. for ph in self._post_hooks:
  3204. ph(info_dict['filepath'])
  3205. except Exception as err:
  3206. self.report_error(f'post hooks: {err}')
  3207. return
  3208. info_dict['__write_download_archive'] = True
  3209. assert info_dict is original_infodict # Make sure the info_dict was modified in-place
  3210. if self.params.get('force_write_download_archive'):
  3211. info_dict['__write_download_archive'] = True
  3212. check_max_downloads()
  3213. def __download_wrapper(self, func):
  3214. @functools.wraps(func)
  3215. def wrapper(*args, **kwargs):
  3216. try:
  3217. res = func(*args, **kwargs)
  3218. except CookieLoadError:
  3219. raise
  3220. except UnavailableVideoError as e:
  3221. self.report_error(e)
  3222. except DownloadCancelled as e:
  3223. self.to_screen(f'[info] {e}')
  3224. if not self.params.get('break_per_url'):
  3225. raise
  3226. self._num_downloads = 0
  3227. else:
  3228. if self.params.get('dump_single_json', False):
  3229. self.post_extract(res)
  3230. self.to_stdout(json.dumps(self.sanitize_info(res)))
  3231. return wrapper
  3232. def download(self, url_list):
  3233. """Download a given list of URLs."""
  3234. url_list = variadic(url_list) # Passing a single URL is a common mistake
  3235. outtmpl = self.params['outtmpl']['default']
  3236. if (len(url_list) > 1
  3237. and outtmpl != '-'
  3238. and '%' not in outtmpl
  3239. and self.params.get('max_downloads') != 1):
  3240. raise SameFileError(outtmpl)
  3241. for url in url_list:
  3242. self.__download_wrapper(self.extract_info)(
  3243. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  3244. return self._download_retcode
  3245. def download_with_info_file(self, info_filename):
  3246. with contextlib.closing(fileinput.FileInput(
  3247. [info_filename], mode='r',
  3248. openhook=fileinput.hook_encoded('utf-8'))) as f:
  3249. # FileInput doesn't have a read method, we can't call json.load
  3250. infos = [self.sanitize_info(info, self.params.get('clean_infojson', True))
  3251. for info in variadic(json.loads('\n'.join(f)))]
  3252. for info in infos:
  3253. try:
  3254. self.__download_wrapper(self.process_ie_result)(info, download=True)
  3255. except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
  3256. if not isinstance(e, EntryNotInPlaylist):
  3257. self.to_stderr('\r')
  3258. webpage_url = info.get('webpage_url')
  3259. if webpage_url is None:
  3260. raise
  3261. self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}')
  3262. self.download([webpage_url])
  3263. except ExtractorError as e:
  3264. self.report_error(e)
  3265. return self._download_retcode
  3266. @staticmethod
  3267. def sanitize_info(info_dict, remove_private_keys=False):
  3268. """ Sanitize the infodict for converting to json """
  3269. if info_dict is None:
  3270. return info_dict
  3271. info_dict.setdefault('epoch', int(time.time()))
  3272. info_dict.setdefault('_type', 'video')
  3273. info_dict.setdefault('_version', {
  3274. 'version': __version__,
  3275. 'current_git_head': current_git_head(),
  3276. 'release_git_head': RELEASE_GIT_HEAD,
  3277. 'repository': ORIGIN,
  3278. })
  3279. if remove_private_keys:
  3280. reject = lambda k, v: v is None or k.startswith('__') or k in {
  3281. 'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
  3282. 'entries', 'filepath', '_filename', 'filename', 'infojson_filename', 'original_url',
  3283. 'playlist_autonumber',
  3284. }
  3285. else:
  3286. reject = lambda k, v: False
  3287. def filter_fn(obj):
  3288. if isinstance(obj, dict):
  3289. return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
  3290. elif isinstance(obj, (list, tuple, set, LazyList)):
  3291. return list(map(filter_fn, obj))
  3292. elif obj is None or isinstance(obj, (str, int, float, bool)):
  3293. return obj
  3294. else:
  3295. return repr(obj)
  3296. return filter_fn(info_dict)
  3297. @staticmethod
  3298. def filter_requested_info(info_dict, actually_filter=True):
  3299. """ Alias of sanitize_info for backward compatibility """
  3300. return YoutubeDL.sanitize_info(info_dict, actually_filter)
  3301. def _delete_downloaded_files(self, *files_to_delete, info={}, msg=None):
  3302. for filename in set(filter(None, files_to_delete)):
  3303. if msg:
  3304. self.to_screen(msg % filename)
  3305. try:
  3306. os.remove(filename)
  3307. except OSError:
  3308. self.report_warning(f'Unable to delete file {filename}')
  3309. if filename in info.get('__files_to_move', []): # NB: Delete even if None
  3310. del info['__files_to_move'][filename]
  3311. @staticmethod
  3312. def post_extract(info_dict):
  3313. def actual_post_extract(info_dict):
  3314. if info_dict.get('_type') in ('playlist', 'multi_video'):
  3315. for video_dict in info_dict.get('entries', {}):
  3316. actual_post_extract(video_dict or {})
  3317. return
  3318. post_extractor = info_dict.pop('__post_extractor', None) or dict
  3319. info_dict.update(post_extractor())
  3320. actual_post_extract(info_dict or {})
  3321. def run_pp(self, pp, infodict):
  3322. files_to_delete = []
  3323. if '__files_to_move' not in infodict:
  3324. infodict['__files_to_move'] = {}
  3325. try:
  3326. files_to_delete, infodict = pp.run(infodict)
  3327. except PostProcessingError as e:
  3328. # Must be True and not 'only_download'
  3329. if self.params.get('ignoreerrors') is True:
  3330. self.report_error(e)
  3331. return infodict
  3332. raise
  3333. if not files_to_delete:
  3334. return infodict
  3335. if self.params.get('keepvideo', False):
  3336. for f in files_to_delete:
  3337. infodict['__files_to_move'].setdefault(f, '')
  3338. else:
  3339. self._delete_downloaded_files(
  3340. *files_to_delete, info=infodict, msg='Deleting original file %s (pass -k to keep)')
  3341. return infodict
  3342. def run_all_pps(self, key, info, *, additional_pps=None):
  3343. if key != 'video':
  3344. self._forceprint(key, info)
  3345. for pp in (additional_pps or []) + self._pps[key]:
  3346. info = self.run_pp(pp, info)
  3347. return info
  3348. def pre_process(self, ie_info, key='pre_process', files_to_move=None):
  3349. info = dict(ie_info)
  3350. info['__files_to_move'] = files_to_move or {}
  3351. try:
  3352. info = self.run_all_pps(key, info)
  3353. except PostProcessingError as err:
  3354. msg = f'Preprocessing: {err}'
  3355. info.setdefault('__pending_error', msg)
  3356. self.report_error(msg, is_error=False)
  3357. return info, info.pop('__files_to_move', None)
  3358. def post_process(self, filename, info, files_to_move=None):
  3359. """Run all the postprocessors on the given file."""
  3360. info['filepath'] = filename
  3361. info['__files_to_move'] = files_to_move or {}
  3362. info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
  3363. info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
  3364. del info['__files_to_move']
  3365. return self.run_all_pps('after_move', info)
  3366. def _make_archive_id(self, info_dict):
  3367. video_id = info_dict.get('id')
  3368. if not video_id:
  3369. return
  3370. # Future-proof against any change in case
  3371. # and backwards compatibility with prior versions
  3372. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  3373. if extractor is None:
  3374. url = str_or_none(info_dict.get('url'))
  3375. if not url:
  3376. return
  3377. # Try to find matching extractor for the URL and take its ie_key
  3378. for ie_key, ie in self._ies.items():
  3379. if ie.suitable(url):
  3380. extractor = ie_key
  3381. break
  3382. else:
  3383. return
  3384. return make_archive_id(extractor, video_id)
  3385. def in_download_archive(self, info_dict):
  3386. if not self.archive:
  3387. return False
  3388. vid_ids = [self._make_archive_id(info_dict)]
  3389. vid_ids.extend(info_dict.get('_old_archive_ids') or [])
  3390. return any(id_ in self.archive for id_ in vid_ids)
  3391. def record_download_archive(self, info_dict):
  3392. fn = self.params.get('download_archive')
  3393. if fn is None:
  3394. return
  3395. vid_id = self._make_archive_id(info_dict)
  3396. assert vid_id
  3397. self.write_debug(f'Adding to archive: {vid_id}')
  3398. if is_path_like(fn):
  3399. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  3400. archive_file.write(vid_id + '\n')
  3401. self.archive.add(vid_id)
  3402. @staticmethod
  3403. def format_resolution(format, default='unknown'):
  3404. if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
  3405. return 'audio only'
  3406. if format.get('resolution') is not None:
  3407. return format['resolution']
  3408. if format.get('width') and format.get('height'):
  3409. return '%dx%d' % (format['width'], format['height'])
  3410. elif format.get('height'):
  3411. return '{}p'.format(format['height'])
  3412. elif format.get('width'):
  3413. return '%dx?' % format['width']
  3414. return default
  3415. def _list_format_headers(self, *headers):
  3416. if self.params.get('listformats_table', True) is not False:
  3417. return [self._format_out(header, self.Styles.HEADERS) for header in headers]
  3418. return headers
  3419. def _format_note(self, fdict):
  3420. res = ''
  3421. if fdict.get('ext') in ['f4f', 'f4m']:
  3422. res += '(unsupported)'
  3423. if fdict.get('language'):
  3424. if res:
  3425. res += ' '
  3426. res += '[{}]'.format(fdict['language'])
  3427. if fdict.get('format_note') is not None:
  3428. if res:
  3429. res += ' '
  3430. res += fdict['format_note']
  3431. if fdict.get('tbr') is not None:
  3432. if res:
  3433. res += ', '
  3434. res += '%4dk' % fdict['tbr']
  3435. if fdict.get('container') is not None:
  3436. if res:
  3437. res += ', '
  3438. res += '{} container'.format(fdict['container'])
  3439. if (fdict.get('vcodec') is not None
  3440. and fdict.get('vcodec') != 'none'):
  3441. if res:
  3442. res += ', '
  3443. res += fdict['vcodec']
  3444. if fdict.get('vbr') is not None:
  3445. res += '@'
  3446. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  3447. res += 'video@'
  3448. if fdict.get('vbr') is not None:
  3449. res += '%4dk' % fdict['vbr']
  3450. if fdict.get('fps') is not None:
  3451. if res:
  3452. res += ', '
  3453. res += '{}fps'.format(fdict['fps'])
  3454. if fdict.get('acodec') is not None:
  3455. if res:
  3456. res += ', '
  3457. if fdict['acodec'] == 'none':
  3458. res += 'video only'
  3459. else:
  3460. res += '%-5s' % fdict['acodec']
  3461. elif fdict.get('abr') is not None:
  3462. if res:
  3463. res += ', '
  3464. res += 'audio'
  3465. if fdict.get('abr') is not None:
  3466. res += '@%3dk' % fdict['abr']
  3467. if fdict.get('asr') is not None:
  3468. res += ' (%5dHz)' % fdict['asr']
  3469. if fdict.get('filesize') is not None:
  3470. if res:
  3471. res += ', '
  3472. res += format_bytes(fdict['filesize'])
  3473. elif fdict.get('filesize_approx') is not None:
  3474. if res:
  3475. res += ', '
  3476. res += '~' + format_bytes(fdict['filesize_approx'])
  3477. return res
  3478. def _get_formats(self, info_dict):
  3479. if info_dict.get('formats') is None:
  3480. if info_dict.get('url') and info_dict.get('_type', 'video') == 'video':
  3481. return [info_dict]
  3482. return []
  3483. return info_dict['formats']
  3484. def render_formats_table(self, info_dict):
  3485. formats = self._get_formats(info_dict)
  3486. if not formats:
  3487. return
  3488. if not self.params.get('listformats_table', True) is not False:
  3489. table = [
  3490. [
  3491. format_field(f, 'format_id'),
  3492. format_field(f, 'ext'),
  3493. self.format_resolution(f),
  3494. self._format_note(f),
  3495. ] for f in formats if (f.get('preference') or 0) >= -1000]
  3496. return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
  3497. def simplified_codec(f, field):
  3498. assert field in ('acodec', 'vcodec')
  3499. codec = f.get(field)
  3500. if not codec:
  3501. return 'unknown'
  3502. elif codec != 'none':
  3503. return '.'.join(codec.split('.')[:4])
  3504. if field == 'vcodec' and f.get('acodec') == 'none':
  3505. return 'images'
  3506. elif field == 'acodec' and f.get('vcodec') == 'none':
  3507. return ''
  3508. return self._format_out('audio only' if field == 'vcodec' else 'video only',
  3509. self.Styles.SUPPRESS)
  3510. delim = self._format_out('\u2502', self.Styles.DELIM, '|', test_encoding=True)
  3511. table = [
  3512. [
  3513. self._format_out(format_field(f, 'format_id'), self.Styles.ID),
  3514. format_field(f, 'ext'),
  3515. format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
  3516. format_field(f, 'fps', '\t%d', func=round),
  3517. format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
  3518. format_field(f, 'audio_channels', '\t%s'),
  3519. delim, (
  3520. format_field(f, 'filesize', ' \t%s', func=format_bytes)
  3521. or format_field(f, 'filesize_approx', '≈\t%s', func=format_bytes)
  3522. or format_field(filesize_from_tbr(f.get('tbr'), info_dict.get('duration')), None,
  3523. self._format_out('~\t%s', self.Styles.SUPPRESS), func=format_bytes)),
  3524. format_field(f, 'tbr', '\t%dk', func=round),
  3525. shorten_protocol_name(f.get('protocol', '')),
  3526. delim,
  3527. simplified_codec(f, 'vcodec'),
  3528. format_field(f, 'vbr', '\t%dk', func=round),
  3529. simplified_codec(f, 'acodec'),
  3530. format_field(f, 'abr', '\t%dk', func=round),
  3531. format_field(f, 'asr', '\t%s', func=format_decimal_suffix),
  3532. join_nonempty(format_field(f, 'language', '[%s]'), join_nonempty(
  3533. self._format_out('UNSUPPORTED', self.Styles.BAD_FORMAT) if f.get('ext') in ('f4f', 'f4m') else None,
  3534. (self._format_out('Maybe DRM', self.Styles.WARNING) if f.get('has_drm') == 'maybe'
  3535. else self._format_out('DRM', self.Styles.BAD_FORMAT) if f.get('has_drm') else None),
  3536. format_field(f, 'format_note'),
  3537. format_field(f, 'container', ignore=(None, f.get('ext'))),
  3538. delim=', '), delim=' '),
  3539. ] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
  3540. header_line = self._list_format_headers(
  3541. 'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', 'CH', delim, '\tFILESIZE', '\tTBR', 'PROTO',
  3542. delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
  3543. return render_table(
  3544. header_line, table, hide_empty=True,
  3545. delim=self._format_out('\u2500', self.Styles.DELIM, '-', test_encoding=True))
  3546. def render_thumbnails_table(self, info_dict):
  3547. thumbnails = list(info_dict.get('thumbnails') or [])
  3548. if not thumbnails:
  3549. return None
  3550. return render_table(
  3551. self._list_format_headers('ID', 'Width', 'Height', 'URL'),
  3552. [[t.get('id'), t.get('width') or 'unknown', t.get('height') or 'unknown', t['url']] for t in thumbnails])
  3553. def render_subtitles_table(self, video_id, subtitles):
  3554. def _row(lang, formats):
  3555. exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)))
  3556. if len(set(names)) == 1:
  3557. names = [] if names[0] == 'unknown' else names[:1]
  3558. return [lang, ', '.join(names), ', '.join(exts)]
  3559. if not subtitles:
  3560. return None
  3561. return render_table(
  3562. self._list_format_headers('Language', 'Name', 'Formats'),
  3563. [_row(lang, formats) for lang, formats in subtitles.items()],
  3564. hide_empty=True)
  3565. def __list_table(self, video_id, name, func, *args):
  3566. table = func(*args)
  3567. if not table:
  3568. self.to_screen(f'{video_id} has no {name}')
  3569. return
  3570. self.to_screen(f'[info] Available {name} for {video_id}:')
  3571. self.to_stdout(table)
  3572. def list_formats(self, info_dict):
  3573. self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
  3574. def list_thumbnails(self, info_dict):
  3575. self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
  3576. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  3577. self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
  3578. def print_debug_header(self):
  3579. if not self.params.get('verbose'):
  3580. return
  3581. def get_encoding(stream):
  3582. ret = str(getattr(stream, 'encoding', f'missing ({type(stream).__name__})'))
  3583. additional_info = []
  3584. if os.environ.get('TERM', '').lower() == 'dumb':
  3585. additional_info.append('dumb')
  3586. if not supports_terminal_sequences(stream):
  3587. from .utils import WINDOWS_VT_MODE # Must be imported locally
  3588. additional_info.append('No VT' if WINDOWS_VT_MODE is False else 'No ANSI')
  3589. if additional_info:
  3590. ret = f'{ret} ({",".join(additional_info)})'
  3591. return ret
  3592. encoding_str = 'Encodings: locale {}, fs {}, pref {}, {}'.format(
  3593. locale.getpreferredencoding(),
  3594. sys.getfilesystemencoding(),
  3595. self.get_encoding(),
  3596. ', '.join(
  3597. f'{key} {get_encoding(stream)}' for key, stream in self._out_files.items_
  3598. if stream is not None and key != 'console'),
  3599. )
  3600. logger = self.params.get('logger')
  3601. if logger:
  3602. write_debug = lambda msg: logger.debug(f'[debug] {msg}')
  3603. write_debug(encoding_str)
  3604. else:
  3605. write_string(f'[debug] {encoding_str}\n', encoding=None)
  3606. write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
  3607. source = detect_variant()
  3608. if VARIANT not in (None, 'pip'):
  3609. source += '*'
  3610. klass = type(self)
  3611. write_debug(join_nonempty(
  3612. f'{REPOSITORY.rpartition("/")[2]} version',
  3613. _make_label(ORIGIN, CHANNEL.partition('@')[2] or __version__, __version__),
  3614. f'[{RELEASE_GIT_HEAD[:9]}]' if RELEASE_GIT_HEAD else '',
  3615. '' if source == 'unknown' else f'({source})',
  3616. '' if IN_CLI.value else 'API' if klass == YoutubeDL else f'API:{self.__module__}.{klass.__qualname__}',
  3617. delim=' '))
  3618. if not IN_CLI.value:
  3619. write_debug(f'params: {self.params}')
  3620. import_extractors()
  3621. lazy_extractors = LAZY_EXTRACTORS.value
  3622. if lazy_extractors is None:
  3623. write_debug('Lazy loading extractors is disabled')
  3624. elif not lazy_extractors:
  3625. write_debug('Lazy loading extractors is forcibly disabled')
  3626. if self.params['compat_opts']:
  3627. write_debug('Compatibility options: {}'.format(', '.join(self.params['compat_opts'])))
  3628. if current_git_head():
  3629. write_debug(f'Git HEAD: {current_git_head()}')
  3630. write_debug(system_identifier())
  3631. exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
  3632. ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
  3633. if ffmpeg_features:
  3634. exe_versions['ffmpeg'] += ' ({})'.format(','.join(sorted(ffmpeg_features)))
  3635. exe_versions['rtmpdump'] = rtmpdump_version()
  3636. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  3637. exe_str = ', '.join(
  3638. f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
  3639. ) or 'none'
  3640. write_debug(f'exe versions: {exe_str}')
  3641. from .compat.compat_utils import get_package_info
  3642. from .dependencies import available_dependencies
  3643. write_debug('Optional libraries: %s' % (', '.join(sorted({
  3644. join_nonempty(*get_package_info(m)) for m in available_dependencies.values()
  3645. })) or 'none'))
  3646. write_debug(f'Proxy map: {self.proxies}')
  3647. write_debug(f'Request Handlers: {", ".join(rh.RH_NAME for rh in self._request_director.handlers.values())}')
  3648. for plugin_type, plugins in (('Extractor', plugin_ies), ('Post-Processor', plugin_pps)):
  3649. display_list = [
  3650. klass.__name__ if klass.__name__ == name else f'{klass.__name__} as {name}'
  3651. for name, klass in plugins.value.items()]
  3652. if plugin_type == 'Extractor':
  3653. display_list.extend(f'{plugins[-1].IE_NAME.partition("+")[2]} ({parent.__name__})'
  3654. for parent, plugins in plugin_ies_overrides.value.items())
  3655. if not display_list:
  3656. continue
  3657. write_debug(f'{plugin_type} Plugins: {", ".join(sorted(display_list))}')
  3658. plugin_dirs_msg = 'none'
  3659. if not plugin_dirs.value:
  3660. plugin_dirs_msg = 'none (disabled)'
  3661. else:
  3662. found_plugin_directories = plugin_directories()
  3663. if found_plugin_directories:
  3664. plugin_dirs_msg = ', '.join(found_plugin_directories)
  3665. write_debug(f'Plugin directories: {plugin_dirs_msg}')
  3666. @functools.cached_property
  3667. def proxies(self):
  3668. """Global proxy configuration"""
  3669. opts_proxy = self.params.get('proxy')
  3670. if opts_proxy is not None:
  3671. if opts_proxy == '':
  3672. opts_proxy = '__noproxy__'
  3673. proxies = {'all': opts_proxy}
  3674. else:
  3675. proxies = urllib.request.getproxies()
  3676. # compat. Set HTTPS_PROXY to __noproxy__ to revert
  3677. if 'http' in proxies and 'https' not in proxies:
  3678. proxies['https'] = proxies['http']
  3679. return proxies
  3680. @functools.cached_property
  3681. def cookiejar(self):
  3682. """Global cookiejar instance"""
  3683. try:
  3684. return load_cookies(
  3685. self.params.get('cookiefile'), self.params.get('cookiesfrombrowser'), self)
  3686. except CookieLoadError as error:
  3687. cause = error.__context__
  3688. # compat: <=py3.9: `traceback.format_exception` has a different signature
  3689. self.report_error(str(cause), tb=''.join(traceback.format_exception(None, cause, cause.__traceback__)))
  3690. raise
  3691. @property
  3692. def _opener(self):
  3693. """
  3694. Get a urllib OpenerDirector from the Urllib handler (deprecated).
  3695. """
  3696. self.deprecation_warning('YoutubeDL._opener is deprecated, use YoutubeDL.urlopen()')
  3697. handler = self._request_director.handlers['Urllib']
  3698. return handler._get_instance(cookiejar=self.cookiejar, proxies=self.proxies)
  3699. def _get_available_impersonate_targets(self):
  3700. # TODO(future): make available as public API
  3701. return [
  3702. (target, rh.RH_NAME)
  3703. for rh in self._request_director.handlers.values()
  3704. if isinstance(rh, ImpersonateRequestHandler)
  3705. for target in reversed(rh.supported_targets)
  3706. ]
  3707. def _impersonate_target_available(self, target):
  3708. # TODO(future): make available as public API
  3709. return any(
  3710. rh.is_supported_target(target)
  3711. for rh in self._request_director.handlers.values()
  3712. if isinstance(rh, ImpersonateRequestHandler))
  3713. def urlopen(self, req):
  3714. """ Start an HTTP download """
  3715. if isinstance(req, str):
  3716. req = Request(req)
  3717. elif isinstance(req, urllib.request.Request):
  3718. self.deprecation_warning(
  3719. 'Passing a urllib.request.Request object to YoutubeDL.urlopen() is deprecated. '
  3720. 'Use yt_dlp.networking.common.Request instead.')
  3721. req = urllib_req_to_req(req)
  3722. assert isinstance(req, Request)
  3723. # compat: Assume user:pass url params are basic auth
  3724. url, basic_auth_header = extract_basic_auth(req.url)
  3725. if basic_auth_header:
  3726. req.headers['Authorization'] = basic_auth_header
  3727. req.url = sanitize_url(url)
  3728. clean_proxies(proxies=req.proxies, headers=req.headers)
  3729. clean_headers(req.headers)
  3730. try:
  3731. return self._request_director.send(req)
  3732. except NoSupportingHandlers as e:
  3733. for ue in e.unsupported_errors:
  3734. # FIXME: This depends on the order of errors.
  3735. if not (ue.handler and ue.msg):
  3736. continue
  3737. if ue.handler.RH_KEY == 'Urllib' and 'unsupported url scheme: "file"' in ue.msg.lower():
  3738. raise RequestError(
  3739. 'file:// URLs are disabled by default in yt-dlp for security reasons. '
  3740. 'Use --enable-file-urls to enable at your own risk.', cause=ue) from ue
  3741. if (
  3742. 'unsupported proxy type: "https"' in ue.msg.lower()
  3743. and 'requests' not in self._request_director.handlers
  3744. and 'curl_cffi' not in self._request_director.handlers
  3745. ):
  3746. raise RequestError(
  3747. 'To use an HTTPS proxy for this request, one of the following dependencies needs to be installed: requests, curl_cffi')
  3748. elif (
  3749. re.match(r'unsupported url scheme: "wss?"', ue.msg.lower())
  3750. and 'websockets' not in self._request_director.handlers
  3751. ):
  3752. raise RequestError(
  3753. 'This request requires WebSocket support. '
  3754. 'Ensure one of the following dependencies are installed: websockets',
  3755. cause=ue) from ue
  3756. elif re.match(r'unsupported (?:extensions: impersonate|impersonate target)', ue.msg.lower()):
  3757. raise RequestError(
  3758. f'Impersonate target "{req.extensions["impersonate"]}" is not available.'
  3759. f' See --list-impersonate-targets for available targets.'
  3760. f' This request requires browser impersonation, however you may be missing dependencies'
  3761. f' required to support this target.')
  3762. raise
  3763. except SSLError as e:
  3764. if 'UNSAFE_LEGACY_RENEGOTIATION_DISABLED' in str(e):
  3765. raise RequestError('UNSAFE_LEGACY_RENEGOTIATION_DISABLED: Try using --legacy-server-connect', cause=e) from e
  3766. elif 'SSLV3_ALERT_HANDSHAKE_FAILURE' in str(e):
  3767. raise RequestError(
  3768. 'SSLV3_ALERT_HANDSHAKE_FAILURE: The server may not support the current cipher list. '
  3769. 'Try using --legacy-server-connect', cause=e) from e
  3770. raise
  3771. def build_request_director(self, handlers, preferences=None):
  3772. logger = _YDLLogger(self)
  3773. headers = self.params['http_headers'].copy()
  3774. proxies = self.proxies.copy()
  3775. clean_headers(headers)
  3776. clean_proxies(proxies, headers)
  3777. director = RequestDirector(logger=logger, verbose=self.params.get('debug_printtraffic'))
  3778. for handler in handlers:
  3779. director.add_handler(handler(
  3780. logger=logger,
  3781. headers=headers,
  3782. cookiejar=self.cookiejar,
  3783. proxies=proxies,
  3784. prefer_system_certs='no-certifi' in self.params['compat_opts'],
  3785. verify=not self.params.get('nocheckcertificate'),
  3786. **traverse_obj(self.params, {
  3787. 'verbose': 'debug_printtraffic',
  3788. 'source_address': 'source_address',
  3789. 'timeout': 'socket_timeout',
  3790. 'legacy_ssl_support': 'legacyserverconnect',
  3791. 'enable_file_urls': 'enable_file_urls',
  3792. 'impersonate': 'impersonate',
  3793. 'client_cert': {
  3794. 'client_certificate': 'client_certificate',
  3795. 'client_certificate_key': 'client_certificate_key',
  3796. 'client_certificate_password': 'client_certificate_password',
  3797. },
  3798. }),
  3799. ))
  3800. director.preferences.update(preferences or [])
  3801. if 'prefer-legacy-http-handler' in self.params['compat_opts']:
  3802. director.preferences.add(lambda rh, _: 500 if rh.RH_KEY == 'Urllib' else 0)
  3803. return director
  3804. @functools.cached_property
  3805. def _request_director(self):
  3806. return self.build_request_director(_REQUEST_HANDLERS.values(), _RH_PREFERENCES)
  3807. def encode(self, s):
  3808. if isinstance(s, bytes):
  3809. return s # Already encoded
  3810. try:
  3811. return s.encode(self.get_encoding())
  3812. except UnicodeEncodeError as err:
  3813. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  3814. raise
  3815. def get_encoding(self):
  3816. encoding = self.params.get('encoding')
  3817. if encoding is None:
  3818. encoding = preferredencoding()
  3819. return encoding
  3820. def _write_info_json(self, label, ie_result, infofn, overwrite=None):
  3821. """ Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error """
  3822. if overwrite is None:
  3823. overwrite = self.params.get('overwrites', True)
  3824. if not self.params.get('writeinfojson'):
  3825. return False
  3826. elif not infofn:
  3827. self.write_debug(f'Skipping writing {label} infojson')
  3828. return False
  3829. elif not self._ensure_dir_exists(infofn):
  3830. return None
  3831. elif not overwrite and os.path.exists(infofn):
  3832. self.to_screen(f'[info] {label.title()} metadata is already present')
  3833. return 'exists'
  3834. self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
  3835. try:
  3836. write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
  3837. return True
  3838. except OSError:
  3839. self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
  3840. return None
  3841. def _write_description(self, label, ie_result, descfn):
  3842. """ Write description and returns True = written, False = skip, None = error """
  3843. if not self.params.get('writedescription'):
  3844. return False
  3845. elif not descfn:
  3846. self.write_debug(f'Skipping writing {label} description')
  3847. return False
  3848. elif not self._ensure_dir_exists(descfn):
  3849. return None
  3850. elif not self.params.get('overwrites', True) and os.path.exists(descfn):
  3851. self.to_screen(f'[info] {label.title()} description is already present')
  3852. elif ie_result.get('description') is None:
  3853. self.to_screen(f'[info] There\'s no {label} description to write')
  3854. return False
  3855. else:
  3856. try:
  3857. self.to_screen(f'[info] Writing {label} description to: {descfn}')
  3858. with open(descfn, 'w', encoding='utf-8') as descfile:
  3859. descfile.write(ie_result['description'])
  3860. except OSError:
  3861. self.report_error(f'Cannot write {label} description file {descfn}')
  3862. return None
  3863. return True
  3864. def _write_subtitles(self, info_dict, filename):
  3865. """ Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error"""
  3866. ret = []
  3867. subtitles = info_dict.get('requested_subtitles')
  3868. if not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
  3869. # subtitles download errors are already managed as troubles in relevant IE
  3870. # that way it will silently go on when used with unsupporting IE
  3871. return ret
  3872. elif not subtitles:
  3873. self.to_screen('[info] There are no subtitles for the requested languages')
  3874. return ret
  3875. sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
  3876. if not sub_filename_base:
  3877. self.to_screen('[info] Skipping writing video subtitles')
  3878. return ret
  3879. for sub_lang, sub_info in subtitles.items():
  3880. sub_format = sub_info['ext']
  3881. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  3882. sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
  3883. existing_sub = self.existing_file((sub_filename_final, sub_filename))
  3884. if existing_sub:
  3885. self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
  3886. sub_info['filepath'] = existing_sub
  3887. ret.append((existing_sub, sub_filename_final))
  3888. continue
  3889. self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
  3890. if sub_info.get('data') is not None:
  3891. try:
  3892. # Use newline='' to prevent conversion of newline characters
  3893. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  3894. with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
  3895. subfile.write(sub_info['data'])
  3896. sub_info['filepath'] = sub_filename
  3897. ret.append((sub_filename, sub_filename_final))
  3898. continue
  3899. except OSError:
  3900. self.report_error(f'Cannot write video subtitles file {sub_filename}')
  3901. return None
  3902. try:
  3903. sub_copy = sub_info.copy()
  3904. sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
  3905. self.dl(sub_filename, sub_copy, subtitle=True)
  3906. sub_info['filepath'] = sub_filename
  3907. ret.append((sub_filename, sub_filename_final))
  3908. except (DownloadError, ExtractorError, OSError, ValueError, *network_exceptions) as err:
  3909. msg = f'Unable to download video subtitles for {sub_lang!r}: {err}'
  3910. if self.params.get('ignoreerrors') is not True: # False or 'only_download'
  3911. if not self.params.get('ignoreerrors'):
  3912. self.report_error(msg)
  3913. raise DownloadError(msg)
  3914. self.report_warning(msg)
  3915. return ret
  3916. def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
  3917. """ Write thumbnails to file and return list of (thumb_filename, final_thumb_filename); or None if error """
  3918. write_all = self.params.get('write_all_thumbnails', False)
  3919. thumbnails, ret = [], []
  3920. if write_all or self.params.get('writethumbnail', False):
  3921. thumbnails = info_dict.get('thumbnails') or []
  3922. if not thumbnails:
  3923. self.to_screen(f'[info] There are no {label} thumbnails to download')
  3924. return ret
  3925. multiple = write_all and len(thumbnails) > 1
  3926. if thumb_filename_base is None:
  3927. thumb_filename_base = filename
  3928. if thumbnails and not thumb_filename_base:
  3929. self.write_debug(f'Skipping writing {label} thumbnail')
  3930. return ret
  3931. if thumbnails and not self._ensure_dir_exists(filename):
  3932. return None
  3933. for idx, t in list(enumerate(thumbnails))[::-1]:
  3934. thumb_ext = t.get('ext') or determine_ext(t['url'], 'jpg')
  3935. if multiple:
  3936. thumb_ext = f'{t["id"]}.{thumb_ext}'
  3937. thumb_display_id = f'{label} thumbnail {t["id"]}'
  3938. thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
  3939. thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
  3940. existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
  3941. if existing_thumb:
  3942. self.to_screen('[info] {} is already present'.format((
  3943. thumb_display_id if multiple else f'{label} thumbnail').capitalize()))
  3944. t['filepath'] = existing_thumb
  3945. ret.append((existing_thumb, thumb_filename_final))
  3946. else:
  3947. self.to_screen(f'[info] Downloading {thumb_display_id} ...')
  3948. try:
  3949. uf = self.urlopen(Request(t['url'], headers=t.get('http_headers', {})))
  3950. self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
  3951. with open(thumb_filename, 'wb') as thumbf:
  3952. shutil.copyfileobj(uf, thumbf)
  3953. ret.append((thumb_filename, thumb_filename_final))
  3954. t['filepath'] = thumb_filename
  3955. except network_exceptions as err:
  3956. if isinstance(err, HTTPError) and err.status == 404:
  3957. self.to_screen(f'[info] {thumb_display_id.title()} does not exist')
  3958. else:
  3959. self.report_warning(f'Unable to download {thumb_display_id}: {err}')
  3960. thumbnails.pop(idx)
  3961. if ret and not write_all:
  3962. break
  3963. return ret