YoutubeDL.py 208 KB

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