YoutubeDL.py 207 KB

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