YoutubeDL.py 208 KB

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