YoutubeDL.py 185 KB

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