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. **kwargs,
  1768. }
  1769. if strict:
  1770. return info
  1771. if ie_result.get('webpage_url'):
  1772. info.update({
  1773. 'webpage_url': ie_result['webpage_url'],
  1774. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1775. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1776. })
  1777. return {
  1778. **info,
  1779. 'playlist_index': 0,
  1780. '__last_playlist_index': max(ie_result.get('requested_entries') or (0, 0)),
  1781. 'extractor': ie_result['extractor'],
  1782. 'extractor_key': ie_result['extractor_key'],
  1783. }
  1784. def __process_playlist(self, ie_result, download):
  1785. """Process each entry in the playlist"""
  1786. assert ie_result['_type'] in ('playlist', 'multi_video')
  1787. common_info = self._playlist_infodict(ie_result, strict=True)
  1788. title = common_info.get('playlist') or '<Untitled>'
  1789. if self._match_entry(common_info, incomplete=True) is not None:
  1790. return
  1791. self.to_screen(f'[download] Downloading {ie_result["_type"]}: {title}')
  1792. all_entries = PlaylistEntries(self, ie_result)
  1793. entries = orderedSet(all_entries.get_requested_items(), lazy=True)
  1794. lazy = self.params.get('lazy_playlist')
  1795. if lazy:
  1796. resolved_entries, n_entries = [], 'N/A'
  1797. ie_result['requested_entries'], ie_result['entries'] = None, None
  1798. else:
  1799. entries = resolved_entries = list(entries)
  1800. n_entries = len(resolved_entries)
  1801. ie_result['requested_entries'], ie_result['entries'] = tuple(zip(*resolved_entries)) or ([], [])
  1802. if not ie_result.get('playlist_count'):
  1803. # Better to do this after potentially exhausting entries
  1804. ie_result['playlist_count'] = all_entries.get_full_count()
  1805. extra = self._playlist_infodict(ie_result, n_entries=int_or_none(n_entries))
  1806. ie_copy = collections.ChainMap(ie_result, extra)
  1807. _infojson_written = False
  1808. write_playlist_files = self.params.get('allow_playlist_files', True)
  1809. if write_playlist_files and self.params.get('list_thumbnails'):
  1810. self.list_thumbnails(ie_result)
  1811. if write_playlist_files and not self.params.get('simulate'):
  1812. _infojson_written = self._write_info_json(
  1813. 'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
  1814. if _infojson_written is None:
  1815. return
  1816. if self._write_description('playlist', ie_result,
  1817. self.prepare_filename(ie_copy, 'pl_description')) is None:
  1818. return
  1819. # TODO: This should be passed to ThumbnailsConvertor if necessary
  1820. self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail'))
  1821. if lazy:
  1822. if self.params.get('playlistreverse') or self.params.get('playlistrandom'):
  1823. self.report_warning('playlistreverse and playlistrandom are not supported with lazy_playlist', only_once=True)
  1824. elif self.params.get('playlistreverse'):
  1825. entries.reverse()
  1826. elif self.params.get('playlistrandom'):
  1827. random.shuffle(entries)
  1828. self.to_screen(f'[{ie_result["extractor"]}] Playlist {title}: Downloading {n_entries} items'
  1829. f'{format_field(ie_result, "playlist_count", " of %s")}')
  1830. keep_resolved_entries = self.params.get('extract_flat') != 'discard'
  1831. if self.params.get('extract_flat') == 'discard_in_playlist':
  1832. keep_resolved_entries = ie_result['_type'] != 'playlist'
  1833. if keep_resolved_entries:
  1834. self.write_debug('The information of all playlist entries will be held in memory')
  1835. failures = 0
  1836. max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
  1837. for i, (playlist_index, entry) in enumerate(entries):
  1838. if lazy:
  1839. resolved_entries.append((playlist_index, entry))
  1840. if not entry:
  1841. continue
  1842. entry['__x_forwarded_for_ip'] = ie_result.get('__x_forwarded_for_ip')
  1843. if not lazy and 'playlist-index' in self.params['compat_opts']:
  1844. playlist_index = ie_result['requested_entries'][i]
  1845. entry_copy = collections.ChainMap(entry, {
  1846. **common_info,
  1847. 'n_entries': int_or_none(n_entries),
  1848. 'playlist_index': playlist_index,
  1849. 'playlist_autonumber': i + 1,
  1850. })
  1851. if self._match_entry(entry_copy, incomplete=True) is not None:
  1852. # For compatabilty with youtube-dl. See https://github.com/yt-dlp/yt-dlp/issues/4369
  1853. resolved_entries[i] = (playlist_index, NO_DEFAULT)
  1854. continue
  1855. self.to_screen(
  1856. f'[download] Downloading item {self._format_screen(i + 1, self.Styles.ID)} '
  1857. f'of {self._format_screen(n_entries, self.Styles.EMPHASIS)}')
  1858. entry_result = self.__process_iterable_entry(entry, download, collections.ChainMap({
  1859. 'playlist_index': playlist_index,
  1860. 'playlist_autonumber': i + 1,
  1861. }, extra))
  1862. if not entry_result:
  1863. failures += 1
  1864. if failures >= max_failures:
  1865. self.report_error(
  1866. f'Skipping the remaining entries in playlist "{title}" since {failures} items failed extraction')
  1867. break
  1868. if keep_resolved_entries:
  1869. resolved_entries[i] = (playlist_index, entry_result)
  1870. # Update with processed data
  1871. ie_result['entries'] = [e for _, e in resolved_entries if e is not NO_DEFAULT]
  1872. ie_result['requested_entries'] = [i for i, e in resolved_entries if e is not NO_DEFAULT]
  1873. if ie_result['requested_entries'] == try_call(lambda: list(range(1, ie_result['playlist_count'] + 1))):
  1874. # Do not set for full playlist
  1875. ie_result.pop('requested_entries')
  1876. # Write the updated info to json
  1877. if _infojson_written is True and self._write_info_json(
  1878. 'updated playlist', ie_result,
  1879. self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
  1880. return
  1881. ie_result = self.run_all_pps('playlist', ie_result)
  1882. self.to_screen(f'[download] Finished downloading playlist: {title}')
  1883. return ie_result
  1884. @_handle_extraction_exceptions
  1885. def __process_iterable_entry(self, entry, download, extra_info):
  1886. return self.process_ie_result(
  1887. entry, download=download, extra_info=extra_info)
  1888. def _build_format_filter(self, filter_spec):
  1889. " Returns a function to filter the formats according to the filter_spec "
  1890. OPERATORS = {
  1891. '<': operator.lt,
  1892. '<=': operator.le,
  1893. '>': operator.gt,
  1894. '>=': operator.ge,
  1895. '=': operator.eq,
  1896. '!=': operator.ne,
  1897. }
  1898. operator_rex = re.compile(r'''(?x)\s*
  1899. (?P<key>[\w.-]+)\s*
  1900. (?P<op>{})(?P<none_inclusive>\s*\?)?\s*
  1901. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
  1902. '''.format('|'.join(map(re.escape, OPERATORS.keys()))))
  1903. m = operator_rex.fullmatch(filter_spec)
  1904. if m:
  1905. try:
  1906. comparison_value = int(m.group('value'))
  1907. except ValueError:
  1908. comparison_value = parse_filesize(m.group('value'))
  1909. if comparison_value is None:
  1910. comparison_value = parse_filesize(m.group('value') + 'B')
  1911. if comparison_value is None:
  1912. raise ValueError(
  1913. 'Invalid value {!r} in format specification {!r}'.format(
  1914. m.group('value'), filter_spec))
  1915. op = OPERATORS[m.group('op')]
  1916. if not m:
  1917. STR_OPERATORS = {
  1918. '=': operator.eq,
  1919. '^=': lambda attr, value: attr.startswith(value),
  1920. '$=': lambda attr, value: attr.endswith(value),
  1921. '*=': lambda attr, value: value in attr,
  1922. '~=': lambda attr, value: value.search(attr) is not None,
  1923. }
  1924. str_operator_rex = re.compile(r'''(?x)\s*
  1925. (?P<key>[a-zA-Z0-9._-]+)\s*
  1926. (?P<negation>!\s*)?(?P<op>{})\s*(?P<none_inclusive>\?\s*)?
  1927. (?P<quote>["'])?
  1928. (?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
  1929. (?(quote)(?P=quote))\s*
  1930. '''.format('|'.join(map(re.escape, STR_OPERATORS.keys()))))
  1931. m = str_operator_rex.fullmatch(filter_spec)
  1932. if m:
  1933. if m.group('op') == '~=':
  1934. comparison_value = re.compile(m.group('value'))
  1935. else:
  1936. comparison_value = re.sub(r'''\\([\\"'])''', r'\1', m.group('value'))
  1937. str_op = STR_OPERATORS[m.group('op')]
  1938. if m.group('negation'):
  1939. op = lambda attr, value: not str_op(attr, value)
  1940. else:
  1941. op = str_op
  1942. if not m:
  1943. raise SyntaxError(f'Invalid filter specification {filter_spec!r}')
  1944. def _filter(f):
  1945. actual_value = f.get(m.group('key'))
  1946. if actual_value is None:
  1947. return m.group('none_inclusive')
  1948. return op(actual_value, comparison_value)
  1949. return _filter
  1950. def _check_formats(self, formats):
  1951. for f in formats:
  1952. working = f.get('__working')
  1953. if working is not None:
  1954. if working:
  1955. yield f
  1956. continue
  1957. self.to_screen('[info] Testing format {}'.format(f['format_id']))
  1958. path = self.get_output_path('temp')
  1959. if not self._ensure_dir_exists(f'{path}/'):
  1960. continue
  1961. temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path or None)
  1962. temp_file.close()
  1963. try:
  1964. success, _ = self.dl(temp_file.name, f, test=True)
  1965. except (DownloadError, OSError, ValueError, *network_exceptions):
  1966. success = False
  1967. finally:
  1968. if os.path.exists(temp_file.name):
  1969. try:
  1970. os.remove(temp_file.name)
  1971. except OSError:
  1972. self.report_warning(f'Unable to delete temporary file "{temp_file.name}"')
  1973. f['__working'] = success
  1974. if success:
  1975. yield f
  1976. else:
  1977. self.to_screen('[info] Unable to download format {}. Skipping...'.format(f['format_id']))
  1978. def _select_formats(self, formats, selector):
  1979. return list(selector({
  1980. 'formats': formats,
  1981. 'has_merged_format': any('none' not in (f.get('acodec'), f.get('vcodec')) for f in formats),
  1982. 'incomplete_formats': (all(f.get('vcodec') == 'none' for f in formats) # No formats with video
  1983. or all(f.get('acodec') == 'none' for f in formats)), # OR, No formats with audio
  1984. }))
  1985. def _default_format_spec(self, info_dict):
  1986. prefer_best = (
  1987. self.params['outtmpl']['default'] == '-'
  1988. or info_dict.get('is_live') and not self.params.get('live_from_start'))
  1989. def can_merge():
  1990. merger = FFmpegMergerPP(self)
  1991. return merger.available and merger.can_merge()
  1992. if not prefer_best and not can_merge():
  1993. prefer_best = True
  1994. formats = self._get_formats(info_dict)
  1995. evaluate_formats = lambda spec: self._select_formats(formats, self.build_format_selector(spec))
  1996. if evaluate_formats('b/bv+ba') != evaluate_formats('bv*+ba/b'):
  1997. self.report_warning('ffmpeg not found. The downloaded format may not be the best available. '
  1998. 'Installing ffmpeg is strongly recommended: https://github.com/yt-dlp/yt-dlp#dependencies')
  1999. compat = (self.params.get('allow_multiple_audio_streams')
  2000. or 'format-spec' in self.params['compat_opts'])
  2001. return ('best/bestvideo+bestaudio' if prefer_best
  2002. else 'bestvideo+bestaudio/best' if compat
  2003. else 'bestvideo*+bestaudio/best')
  2004. def build_format_selector(self, format_spec):
  2005. def syntax_error(note, start):
  2006. message = (
  2007. 'Invalid format specification: '
  2008. '{}\n\t{}\n\t{}^'.format(note, format_spec, ' ' * start[1]))
  2009. return SyntaxError(message)
  2010. PICKFIRST = 'PICKFIRST'
  2011. MERGE = 'MERGE'
  2012. SINGLE = 'SINGLE'
  2013. GROUP = 'GROUP'
  2014. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  2015. allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
  2016. 'video': self.params.get('allow_multiple_video_streams', False)}
  2017. def _parse_filter(tokens):
  2018. filter_parts = []
  2019. for type_, string_, _start, _, _ in tokens:
  2020. if type_ == tokenize.OP and string_ == ']':
  2021. return ''.join(filter_parts)
  2022. else:
  2023. filter_parts.append(string_)
  2024. def _remove_unused_ops(tokens):
  2025. # Remove operators that we don't use and join them with the surrounding strings.
  2026. # E.g. 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  2027. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  2028. last_string, last_start, last_end, last_line = None, None, None, None
  2029. for type_, string_, start, end, line in tokens:
  2030. if type_ == tokenize.OP and string_ == '[':
  2031. if last_string:
  2032. yield tokenize.NAME, last_string, last_start, last_end, last_line
  2033. last_string = None
  2034. yield type_, string_, start, end, line
  2035. # everything inside brackets will be handled by _parse_filter
  2036. for type_, string_, start, end, line in tokens:
  2037. yield type_, string_, start, end, line
  2038. if type_ == tokenize.OP and string_ == ']':
  2039. break
  2040. elif type_ == tokenize.OP and string_ in ALLOWED_OPS:
  2041. if last_string:
  2042. yield tokenize.NAME, last_string, last_start, last_end, last_line
  2043. last_string = None
  2044. yield type_, string_, start, end, line
  2045. elif type_ in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  2046. if not last_string:
  2047. last_string = string_
  2048. last_start = start
  2049. last_end = end
  2050. else:
  2051. last_string += string_
  2052. if last_string:
  2053. yield tokenize.NAME, last_string, last_start, last_end, last_line
  2054. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  2055. selectors = []
  2056. current_selector = None
  2057. for type_, string_, start, _, _ in tokens:
  2058. # ENCODING is only defined in Python 3.x
  2059. if type_ == getattr(tokenize, 'ENCODING', None):
  2060. continue
  2061. elif type_ in [tokenize.NAME, tokenize.NUMBER]:
  2062. current_selector = FormatSelector(SINGLE, string_, [])
  2063. elif type_ == tokenize.OP:
  2064. if string_ == ')':
  2065. if not inside_group:
  2066. # ')' will be handled by the parentheses group
  2067. tokens.restore_last_token()
  2068. break
  2069. elif inside_merge and string_ in ['/', ',']:
  2070. tokens.restore_last_token()
  2071. break
  2072. elif inside_choice and string_ == ',':
  2073. tokens.restore_last_token()
  2074. break
  2075. elif string_ == ',':
  2076. if not current_selector:
  2077. raise syntax_error('"," must follow a format selector', start)
  2078. selectors.append(current_selector)
  2079. current_selector = None
  2080. elif string_ == '/':
  2081. if not current_selector:
  2082. raise syntax_error('"/" must follow a format selector', start)
  2083. first_choice = current_selector
  2084. second_choice = _parse_format_selection(tokens, inside_choice=True)
  2085. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  2086. elif string_ == '[':
  2087. if not current_selector:
  2088. current_selector = FormatSelector(SINGLE, 'best', [])
  2089. format_filter = _parse_filter(tokens)
  2090. current_selector.filters.append(format_filter)
  2091. elif string_ == '(':
  2092. if current_selector:
  2093. raise syntax_error('Unexpected "("', start)
  2094. group = _parse_format_selection(tokens, inside_group=True)
  2095. current_selector = FormatSelector(GROUP, group, [])
  2096. elif string_ == '+':
  2097. if not current_selector:
  2098. raise syntax_error('Unexpected "+"', start)
  2099. selector_1 = current_selector
  2100. selector_2 = _parse_format_selection(tokens, inside_merge=True)
  2101. if not selector_2:
  2102. raise syntax_error('Expected a selector', start)
  2103. current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
  2104. else:
  2105. raise syntax_error(f'Operator not recognized: "{string_}"', start)
  2106. elif type_ == tokenize.ENDMARKER:
  2107. break
  2108. if current_selector:
  2109. selectors.append(current_selector)
  2110. return selectors
  2111. def _merge(formats_pair):
  2112. format_1, format_2 = formats_pair
  2113. formats_info = []
  2114. formats_info.extend(format_1.get('requested_formats', (format_1,)))
  2115. formats_info.extend(format_2.get('requested_formats', (format_2,)))
  2116. if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
  2117. get_no_more = {'video': False, 'audio': False}
  2118. for (i, fmt_info) in enumerate(formats_info):
  2119. if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
  2120. formats_info.pop(i)
  2121. continue
  2122. for aud_vid in ['audio', 'video']:
  2123. if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
  2124. if get_no_more[aud_vid]:
  2125. formats_info.pop(i)
  2126. break
  2127. get_no_more[aud_vid] = True
  2128. if len(formats_info) == 1:
  2129. return formats_info[0]
  2130. video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
  2131. audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
  2132. the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
  2133. the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
  2134. output_ext = get_compatible_ext(
  2135. vcodecs=[f.get('vcodec') for f in video_fmts],
  2136. acodecs=[f.get('acodec') for f in audio_fmts],
  2137. vexts=[f['ext'] for f in video_fmts],
  2138. aexts=[f['ext'] for f in audio_fmts],
  2139. preferences=(try_call(lambda: self.params['merge_output_format'].split('/'))
  2140. or self.params.get('prefer_free_formats') and ('webm', 'mkv')))
  2141. filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
  2142. new_dict = {
  2143. 'requested_formats': formats_info,
  2144. 'format': '+'.join(filtered('format')),
  2145. 'format_id': '+'.join(filtered('format_id')),
  2146. 'ext': output_ext,
  2147. 'protocol': '+'.join(map(determine_protocol, formats_info)),
  2148. 'language': '+'.join(orderedSet(filtered('language'))) or None,
  2149. 'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
  2150. 'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
  2151. 'tbr': sum(filtered('tbr', 'vbr', 'abr')),
  2152. }
  2153. if the_only_video:
  2154. new_dict.update({
  2155. 'width': the_only_video.get('width'),
  2156. 'height': the_only_video.get('height'),
  2157. 'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
  2158. 'fps': the_only_video.get('fps'),
  2159. 'dynamic_range': the_only_video.get('dynamic_range'),
  2160. 'vcodec': the_only_video.get('vcodec'),
  2161. 'vbr': the_only_video.get('vbr'),
  2162. 'stretched_ratio': the_only_video.get('stretched_ratio'),
  2163. 'aspect_ratio': the_only_video.get('aspect_ratio'),
  2164. })
  2165. if the_only_audio:
  2166. new_dict.update({
  2167. 'acodec': the_only_audio.get('acodec'),
  2168. 'abr': the_only_audio.get('abr'),
  2169. 'asr': the_only_audio.get('asr'),
  2170. 'audio_channels': the_only_audio.get('audio_channels'),
  2171. })
  2172. return new_dict
  2173. def _check_formats(formats):
  2174. if self.params.get('check_formats') == 'selected':
  2175. yield from self._check_formats(formats)
  2176. return
  2177. elif (self.params.get('check_formats') is not None
  2178. or self.params.get('allow_unplayable_formats')):
  2179. yield from formats
  2180. return
  2181. for f in formats:
  2182. if f.get('has_drm') or f.get('__needs_testing'):
  2183. yield from self._check_formats([f])
  2184. else:
  2185. yield f
  2186. def _build_selector_function(selector):
  2187. if isinstance(selector, list): # ,
  2188. fs = [_build_selector_function(s) for s in selector]
  2189. def selector_function(ctx):
  2190. for f in fs:
  2191. yield from f(ctx)
  2192. return selector_function
  2193. elif selector.type == GROUP: # ()
  2194. selector_function = _build_selector_function(selector.selector)
  2195. elif selector.type == PICKFIRST: # /
  2196. fs = [_build_selector_function(s) for s in selector.selector]
  2197. def selector_function(ctx):
  2198. for f in fs:
  2199. picked_formats = list(f(ctx))
  2200. if picked_formats:
  2201. return picked_formats
  2202. return []
  2203. elif selector.type == MERGE: # +
  2204. selector_1, selector_2 = map(_build_selector_function, selector.selector)
  2205. def selector_function(ctx):
  2206. for pair in itertools.product(selector_1(ctx), selector_2(ctx)):
  2207. yield _merge(pair)
  2208. elif selector.type == SINGLE: # atom
  2209. format_spec = selector.selector or 'best'
  2210. # TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
  2211. if format_spec == 'all':
  2212. def selector_function(ctx):
  2213. yield from _check_formats(ctx['formats'][::-1])
  2214. elif format_spec == 'mergeall':
  2215. def selector_function(ctx):
  2216. formats = list(_check_formats(
  2217. f for f in ctx['formats'] if f.get('vcodec') != 'none' or f.get('acodec') != 'none'))
  2218. if not formats:
  2219. return
  2220. merged_format = formats[-1]
  2221. for f in formats[-2::-1]:
  2222. merged_format = _merge((merged_format, f))
  2223. yield merged_format
  2224. else:
  2225. format_fallback, seperate_fallback, format_reverse, format_idx = False, None, True, 1
  2226. mobj = re.match(
  2227. r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
  2228. format_spec)
  2229. if mobj is not None:
  2230. format_idx = int_or_none(mobj.group('n'), default=1)
  2231. format_reverse = mobj.group('bw')[0] == 'b'
  2232. format_type = (mobj.group('type') or [None])[0]
  2233. not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
  2234. format_modified = mobj.group('mod') is not None
  2235. format_fallback = not format_type and not format_modified # for b, w
  2236. _filter_f = (
  2237. (lambda f: f.get(f'{format_type}codec') != 'none')
  2238. if format_type and format_modified # bv*, ba*, wv*, wa*
  2239. else (lambda f: f.get(f'{not_format_type}codec') == 'none')
  2240. if format_type # bv, ba, wv, wa
  2241. else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
  2242. if not format_modified # b, w
  2243. else lambda f: True) # b*, w*
  2244. filter_f = lambda f: _filter_f(f) and (
  2245. f.get('vcodec') != 'none' or f.get('acodec') != 'none')
  2246. else:
  2247. if format_spec in self._format_selection_exts['audio']:
  2248. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
  2249. elif format_spec in self._format_selection_exts['video']:
  2250. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
  2251. seperate_fallback = lambda f: f.get('ext') == format_spec and f.get('vcodec') != 'none'
  2252. elif format_spec in self._format_selection_exts['storyboards']:
  2253. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
  2254. else:
  2255. filter_f = lambda f: f.get('format_id') == format_spec # id
  2256. def selector_function(ctx):
  2257. formats = list(ctx['formats'])
  2258. matches = list(filter(filter_f, formats)) if filter_f is not None else formats
  2259. if not matches:
  2260. if format_fallback and ctx['incomplete_formats']:
  2261. # for extractors with incomplete formats (audio only (soundcloud)
  2262. # or video only (imgur)) best/worst will fallback to
  2263. # best/worst {video,audio}-only format
  2264. matches = list(filter(lambda f: f.get('vcodec') != 'none' or f.get('acodec') != 'none', formats))
  2265. elif seperate_fallback and not ctx['has_merged_format']:
  2266. # for compatibility with youtube-dl when there is no pre-merged format
  2267. matches = list(filter(seperate_fallback, formats))
  2268. matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
  2269. try:
  2270. yield matches[format_idx - 1]
  2271. except LazyList.IndexError:
  2272. return
  2273. filters = [self._build_format_filter(f) for f in selector.filters]
  2274. def final_selector(ctx):
  2275. ctx_copy = dict(ctx)
  2276. for _filter in filters:
  2277. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  2278. return selector_function(ctx_copy)
  2279. return final_selector
  2280. # HACK: Python 3.12 changed the underlying parser, rendering '7_a' invalid
  2281. # Prefix numbers with random letters to avoid it being classified as a number
  2282. # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
  2283. # TODO: Implement parser not reliant on tokenize.tokenize
  2284. prefix = ''.join(random.choices(string.ascii_letters, k=32))
  2285. stream = io.BytesIO(re.sub(r'\d[_\d]*', rf'{prefix}\g<0>', format_spec).encode())
  2286. try:
  2287. tokens = list(_remove_unused_ops(
  2288. token._replace(string=token.string.replace(prefix, ''))
  2289. for token in tokenize.tokenize(stream.readline)))
  2290. except tokenize.TokenError:
  2291. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  2292. class TokenIterator:
  2293. def __init__(self, tokens):
  2294. self.tokens = tokens
  2295. self.counter = 0
  2296. def __iter__(self):
  2297. return self
  2298. def __next__(self):
  2299. if self.counter >= len(self.tokens):
  2300. raise StopIteration
  2301. value = self.tokens[self.counter]
  2302. self.counter += 1
  2303. return value
  2304. next = __next__
  2305. def restore_last_token(self):
  2306. self.counter -= 1
  2307. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  2308. return _build_selector_function(parsed_selector)
  2309. def _calc_headers(self, info_dict, load_cookies=False):
  2310. res = HTTPHeaderDict(self.params['http_headers'], info_dict.get('http_headers'))
  2311. clean_headers(res)
  2312. if load_cookies: # For --load-info-json
  2313. self._load_cookies(res.get('Cookie'), autoscope=info_dict['url']) # compat
  2314. self._load_cookies(info_dict.get('cookies'), autoscope=False)
  2315. # The `Cookie` header is removed to prevent leaks and unscoped cookies.
  2316. # See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  2317. res.pop('Cookie', None)
  2318. cookies = self.cookiejar.get_cookies_for_url(info_dict['url'])
  2319. if cookies:
  2320. encoder = LenientSimpleCookie()
  2321. values = []
  2322. for cookie in cookies:
  2323. _, value = encoder.value_encode(cookie.value)
  2324. values.append(f'{cookie.name}={value}')
  2325. if cookie.domain:
  2326. values.append(f'Domain={cookie.domain}')
  2327. if cookie.path:
  2328. values.append(f'Path={cookie.path}')
  2329. if cookie.secure:
  2330. values.append('Secure')
  2331. if cookie.expires:
  2332. values.append(f'Expires={cookie.expires}')
  2333. if cookie.version:
  2334. values.append(f'Version={cookie.version}')
  2335. info_dict['cookies'] = '; '.join(values)
  2336. if 'X-Forwarded-For' not in res:
  2337. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  2338. if x_forwarded_for_ip:
  2339. res['X-Forwarded-For'] = x_forwarded_for_ip
  2340. return res
  2341. def _calc_cookies(self, url):
  2342. self.deprecation_warning('"YoutubeDL._calc_cookies" is deprecated and may be removed in a future version')
  2343. return self.cookiejar.get_cookie_header(url)
  2344. def _sort_thumbnails(self, thumbnails):
  2345. thumbnails.sort(key=lambda t: (
  2346. t.get('preference') if t.get('preference') is not None else -1,
  2347. t.get('width') if t.get('width') is not None else -1,
  2348. t.get('height') if t.get('height') is not None else -1,
  2349. t.get('id') if t.get('id') is not None else '',
  2350. t.get('url')))
  2351. def _sanitize_thumbnails(self, info_dict):
  2352. thumbnails = info_dict.get('thumbnails')
  2353. if thumbnails is None:
  2354. thumbnail = info_dict.get('thumbnail')
  2355. if thumbnail:
  2356. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  2357. if not thumbnails:
  2358. return
  2359. def check_thumbnails(thumbnails):
  2360. for t in thumbnails:
  2361. self.to_screen(f'[info] Testing thumbnail {t["id"]}')
  2362. try:
  2363. self.urlopen(HEADRequest(t['url']))
  2364. except network_exceptions as err:
  2365. self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...')
  2366. continue
  2367. yield t
  2368. self._sort_thumbnails(thumbnails)
  2369. for i, t in enumerate(thumbnails):
  2370. if t.get('id') is None:
  2371. t['id'] = str(i)
  2372. if t.get('width') and t.get('height'):
  2373. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  2374. t['url'] = sanitize_url(t['url'])
  2375. if self.params.get('check_formats') is True:
  2376. info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
  2377. else:
  2378. info_dict['thumbnails'] = thumbnails
  2379. def _fill_common_fields(self, info_dict, final=True):
  2380. # TODO: move sanitization here
  2381. if final:
  2382. title = info_dict['fulltitle'] = info_dict.get('title')
  2383. if not title:
  2384. if title == '':
  2385. self.write_debug('Extractor gave empty title. Creating a generic title')
  2386. else:
  2387. self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
  2388. info_dict['title'] = f'{info_dict["extractor"].replace(":", "-")} video #{info_dict["id"]}'
  2389. if info_dict.get('duration') is not None:
  2390. info_dict['duration_string'] = formatSeconds(info_dict['duration'])
  2391. for ts_key, date_key in (
  2392. ('timestamp', 'upload_date'),
  2393. ('release_timestamp', 'release_date'),
  2394. ('modified_timestamp', 'modified_date'),
  2395. ):
  2396. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  2397. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  2398. # see http://bugs.python.org/issue1646728)
  2399. with contextlib.suppress(ValueError, OverflowError, OSError):
  2400. upload_date = dt.datetime.fromtimestamp(info_dict[ts_key], dt.timezone.utc)
  2401. info_dict[date_key] = upload_date.strftime('%Y%m%d')
  2402. if not info_dict.get('release_year'):
  2403. info_dict['release_year'] = traverse_obj(info_dict, ('release_date', {lambda x: int(x[:4])}))
  2404. live_keys = ('is_live', 'was_live')
  2405. live_status = info_dict.get('live_status')
  2406. if live_status is None:
  2407. for key in live_keys:
  2408. if info_dict.get(key) is False:
  2409. continue
  2410. if info_dict.get(key):
  2411. live_status = key
  2412. break
  2413. if all(info_dict.get(key) is False for key in live_keys):
  2414. live_status = 'not_live'
  2415. if live_status:
  2416. info_dict['live_status'] = live_status
  2417. for key in live_keys:
  2418. if info_dict.get(key) is None:
  2419. info_dict[key] = (live_status == key)
  2420. if live_status == 'post_live':
  2421. info_dict['was_live'] = True
  2422. # Auto generate title fields corresponding to the *_number fields when missing
  2423. # in order to always have clean titles. This is very common for TV series.
  2424. for field in ('chapter', 'season', 'episode'):
  2425. if final and info_dict.get(f'{field}_number') is not None and not info_dict.get(field):
  2426. info_dict[field] = '%s %d' % (field.capitalize(), info_dict[f'{field}_number'])
  2427. for old_key, new_key in self._deprecated_multivalue_fields.items():
  2428. if new_key in info_dict and old_key in info_dict:
  2429. if '_version' not in info_dict: # HACK: Do not warn when using --load-info-json
  2430. self.deprecation_warning(f'Do not return {old_key!r} when {new_key!r} is present')
  2431. elif old_value := info_dict.get(old_key):
  2432. info_dict[new_key] = old_value.split(', ')
  2433. elif new_value := info_dict.get(new_key):
  2434. info_dict[old_key] = ', '.join(v.replace(',', '\N{FULLWIDTH COMMA}') for v in new_value)
  2435. def _raise_pending_errors(self, info):
  2436. err = info.pop('__pending_error', None)
  2437. if err:
  2438. self.report_error(err, tb=False)
  2439. def sort_formats(self, info_dict):
  2440. formats = self._get_formats(info_dict)
  2441. formats.sort(key=FormatSorter(
  2442. self, info_dict.get('_format_sort_fields') or []).calculate_preference)
  2443. def process_video_result(self, info_dict, download=True):
  2444. assert info_dict.get('_type', 'video') == 'video'
  2445. self._num_videos += 1
  2446. if 'id' not in info_dict:
  2447. raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
  2448. elif not info_dict.get('id'):
  2449. raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
  2450. def report_force_conversion(field, field_not, conversion):
  2451. self.report_warning(
  2452. f'"{field}" field is not {field_not} - forcing {conversion} conversion, '
  2453. 'there is an error in extractor')
  2454. def sanitize_string_field(info, string_field):
  2455. field = info.get(string_field)
  2456. if field is None or isinstance(field, str):
  2457. return
  2458. report_force_conversion(string_field, 'a string', 'string')
  2459. info[string_field] = str(field)
  2460. def sanitize_numeric_fields(info):
  2461. for numeric_field in self._NUMERIC_FIELDS:
  2462. field = info.get(numeric_field)
  2463. if field is None or isinstance(field, (int, float)):
  2464. continue
  2465. report_force_conversion(numeric_field, 'numeric', 'int')
  2466. info[numeric_field] = int_or_none(field)
  2467. sanitize_string_field(info_dict, 'id')
  2468. sanitize_numeric_fields(info_dict)
  2469. if info_dict.get('section_end') and info_dict.get('section_start') is not None:
  2470. info_dict['duration'] = round(info_dict['section_end'] - info_dict['section_start'], 3)
  2471. if (info_dict.get('duration') or 0) <= 0 and info_dict.pop('duration', None):
  2472. self.report_warning('"duration" field is negative, there is an error in extractor')
  2473. chapters = info_dict.get('chapters') or []
  2474. if chapters and chapters[0].get('start_time'):
  2475. chapters.insert(0, {'start_time': 0})
  2476. dummy_chapter = {'end_time': 0, 'start_time': info_dict.get('duration')}
  2477. for idx, (prev, current, next_) in enumerate(zip(
  2478. (dummy_chapter, *chapters), chapters, (*chapters[1:], dummy_chapter)), 1):
  2479. if current.get('start_time') is None:
  2480. current['start_time'] = prev.get('end_time')
  2481. if not current.get('end_time'):
  2482. current['end_time'] = next_.get('start_time')
  2483. if not current.get('title'):
  2484. current['title'] = f'<Untitled Chapter {idx}>'
  2485. if 'playlist' not in info_dict:
  2486. # It isn't part of a playlist
  2487. info_dict['playlist'] = None
  2488. info_dict['playlist_index'] = None
  2489. self._sanitize_thumbnails(info_dict)
  2490. thumbnail = info_dict.get('thumbnail')
  2491. thumbnails = info_dict.get('thumbnails')
  2492. if thumbnail:
  2493. info_dict['thumbnail'] = sanitize_url(thumbnail)
  2494. elif thumbnails:
  2495. info_dict['thumbnail'] = thumbnails[-1]['url']
  2496. if info_dict.get('display_id') is None and 'id' in info_dict:
  2497. info_dict['display_id'] = info_dict['id']
  2498. self._fill_common_fields(info_dict)
  2499. for cc_kind in ('subtitles', 'automatic_captions'):
  2500. cc = info_dict.get(cc_kind)
  2501. if cc:
  2502. for _, subtitle in cc.items():
  2503. for subtitle_format in subtitle:
  2504. if subtitle_format.get('url'):
  2505. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  2506. if subtitle_format.get('ext') is None:
  2507. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  2508. automatic_captions = info_dict.get('automatic_captions')
  2509. subtitles = info_dict.get('subtitles')
  2510. info_dict['requested_subtitles'] = self.process_subtitles(
  2511. info_dict['id'], subtitles, automatic_captions)
  2512. formats = self._get_formats(info_dict)
  2513. # Backward compatibility with InfoExtractor._sort_formats
  2514. field_preference = (formats or [{}])[0].pop('__sort_fields', None)
  2515. if field_preference:
  2516. info_dict['_format_sort_fields'] = field_preference
  2517. info_dict['_has_drm'] = any( # or None ensures --clean-infojson removes it
  2518. f.get('has_drm') and f['has_drm'] != 'maybe' for f in formats) or None
  2519. if not self.params.get('allow_unplayable_formats'):
  2520. formats = [f for f in formats if not f.get('has_drm') or f['has_drm'] == 'maybe']
  2521. if formats and all(f.get('acodec') == f.get('vcodec') == 'none' for f in formats):
  2522. self.report_warning(
  2523. f'{"This video is DRM protected and " if info_dict["_has_drm"] else ""}'
  2524. 'only images are available for download. Use --list-formats to see them'.capitalize())
  2525. get_from_start = not info_dict.get('is_live') or bool(self.params.get('live_from_start'))
  2526. if not get_from_start:
  2527. info_dict['title'] += ' ' + dt.datetime.now().strftime('%Y-%m-%d %H:%M')
  2528. if info_dict.get('is_live') and formats:
  2529. formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
  2530. if get_from_start and not formats:
  2531. self.raise_no_formats(info_dict, msg=(
  2532. '--live-from-start is passed, but there are no formats that can be downloaded from the start. '
  2533. 'If you want to download from the current time, use --no-live-from-start'))
  2534. def is_wellformed(f):
  2535. url = f.get('url')
  2536. if not url:
  2537. self.report_warning(
  2538. '"url" field is missing or empty - skipping format, '
  2539. 'there is an error in extractor')
  2540. return False
  2541. if isinstance(url, bytes):
  2542. sanitize_string_field(f, 'url')
  2543. return True
  2544. # Filter out malformed formats for better extraction robustness
  2545. formats = list(filter(is_wellformed, formats or []))
  2546. if not formats:
  2547. self.raise_no_formats(info_dict)
  2548. for fmt in formats:
  2549. sanitize_string_field(fmt, 'format_id')
  2550. sanitize_numeric_fields(fmt)
  2551. fmt['url'] = sanitize_url(fmt['url'])
  2552. FormatSorter._fill_sorting_fields(fmt)
  2553. if fmt['ext'] in ('aac', 'opus', 'mp3', 'flac', 'vorbis'):
  2554. if fmt.get('acodec') is None:
  2555. fmt['acodec'] = fmt['ext']
  2556. if fmt.get('resolution') is None:
  2557. fmt['resolution'] = self.format_resolution(fmt, default=None)
  2558. if fmt.get('dynamic_range') is None and fmt.get('vcodec') != 'none':
  2559. fmt['dynamic_range'] = 'SDR'
  2560. if fmt.get('aspect_ratio') is None:
  2561. fmt['aspect_ratio'] = try_call(lambda: round(fmt['width'] / fmt['height'], 2))
  2562. # For fragmented formats, "tbr" is often max bitrate and not average
  2563. if (('manifest-filesize-approx' in self.params['compat_opts'] or not fmt.get('manifest_url'))
  2564. and not fmt.get('filesize') and not fmt.get('filesize_approx')):
  2565. fmt['filesize_approx'] = filesize_from_tbr(fmt.get('tbr'), info_dict.get('duration'))
  2566. fmt['http_headers'] = self._calc_headers(collections.ChainMap(fmt, info_dict), load_cookies=True)
  2567. # Safeguard against old/insecure infojson when using --load-info-json
  2568. if info_dict.get('http_headers'):
  2569. info_dict['http_headers'] = HTTPHeaderDict(info_dict['http_headers'])
  2570. info_dict['http_headers'].pop('Cookie', None)
  2571. # This is copied to http_headers by the above _calc_headers and can now be removed
  2572. if '__x_forwarded_for_ip' in info_dict:
  2573. del info_dict['__x_forwarded_for_ip']
  2574. self.sort_formats({
  2575. 'formats': formats,
  2576. '_format_sort_fields': info_dict.get('_format_sort_fields'),
  2577. })
  2578. # Sanitize and group by format_id
  2579. formats_dict = {}
  2580. for i, fmt in enumerate(formats):
  2581. if not fmt.get('format_id'):
  2582. fmt['format_id'] = str(i)
  2583. else:
  2584. # Sanitize format_id from characters used in format selector expression
  2585. fmt['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', fmt['format_id'])
  2586. formats_dict.setdefault(fmt['format_id'], []).append(fmt)
  2587. # Make sure all formats have unique format_id
  2588. common_exts = set(itertools.chain(*self._format_selection_exts.values()))
  2589. for format_id, ambiguous_formats in formats_dict.items():
  2590. ambigious_id = len(ambiguous_formats) > 1
  2591. for i, fmt in enumerate(ambiguous_formats):
  2592. if ambigious_id:
  2593. fmt['format_id'] = f'{format_id}-{i}'
  2594. # Ensure there is no conflict between id and ext in format selection
  2595. # See https://github.com/yt-dlp/yt-dlp/issues/1282
  2596. if fmt['format_id'] != fmt['ext'] and fmt['format_id'] in common_exts:
  2597. fmt['format_id'] = 'f{}'.format(fmt['format_id'])
  2598. if fmt.get('format') is None:
  2599. fmt['format'] = '{id} - {res}{note}'.format(
  2600. id=fmt['format_id'],
  2601. res=self.format_resolution(fmt),
  2602. note=format_field(fmt, 'format_note', ' (%s)'),
  2603. )
  2604. if self.params.get('check_formats') is True:
  2605. formats = LazyList(self._check_formats(formats[::-1]), reverse=True)
  2606. if not formats or formats[0] is not info_dict:
  2607. # only set the 'formats' fields if the original info_dict list them
  2608. # otherwise we end up with a circular reference, the first (and unique)
  2609. # element in the 'formats' field in info_dict is info_dict itself,
  2610. # which can't be exported to json
  2611. info_dict['formats'] = formats
  2612. info_dict, _ = self.pre_process(info_dict)
  2613. if self._match_entry(info_dict, incomplete=self._format_fields) is not None:
  2614. return info_dict
  2615. self.post_extract(info_dict)
  2616. info_dict, _ = self.pre_process(info_dict, 'after_filter')
  2617. # The pre-processors may have modified the formats
  2618. formats = self._get_formats(info_dict)
  2619. list_only = self.params.get('simulate') == 'list_only'
  2620. interactive_format_selection = not list_only and self.format_selector == '-'
  2621. if self.params.get('list_thumbnails'):
  2622. self.list_thumbnails(info_dict)
  2623. if self.params.get('listsubtitles'):
  2624. if 'automatic_captions' in info_dict:
  2625. self.list_subtitles(
  2626. info_dict['id'], automatic_captions, 'automatic captions')
  2627. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  2628. if self.params.get('listformats') or interactive_format_selection:
  2629. self.list_formats(info_dict)
  2630. if list_only:
  2631. # Without this printing, -F --print-json will not work
  2632. self.__forced_printings(info_dict)
  2633. return info_dict
  2634. format_selector = self.format_selector
  2635. while True:
  2636. if interactive_format_selection:
  2637. req_format = input(self._format_screen('\nEnter format selector ', self.Styles.EMPHASIS)
  2638. + '(Press ENTER for default, or Ctrl+C to quit)'
  2639. + self._format_screen(': ', self.Styles.EMPHASIS))
  2640. try:
  2641. format_selector = self.build_format_selector(req_format) if req_format else None
  2642. except SyntaxError as err:
  2643. self.report_error(err, tb=False, is_error=False)
  2644. continue
  2645. if format_selector is None:
  2646. req_format = self._default_format_spec(info_dict)
  2647. self.write_debug(f'Default format spec: {req_format}')
  2648. format_selector = self.build_format_selector(req_format)
  2649. formats_to_download = self._select_formats(formats, format_selector)
  2650. if interactive_format_selection and not formats_to_download:
  2651. self.report_error('Requested format is not available', tb=False, is_error=False)
  2652. continue
  2653. break
  2654. if not formats_to_download:
  2655. if not self.params.get('ignore_no_formats_error'):
  2656. raise ExtractorError(
  2657. 'Requested format is not available. Use --list-formats for a list of available formats',
  2658. expected=True, video_id=info_dict['id'], ie=info_dict['extractor'])
  2659. self.report_warning('Requested format is not available')
  2660. # Process what we can, even without any available formats.
  2661. formats_to_download = [{}]
  2662. requested_ranges = tuple(self.params.get('download_ranges', lambda *_: [{}])(info_dict, self))
  2663. best_format, downloaded_formats = formats_to_download[-1], []
  2664. if download:
  2665. if best_format and requested_ranges:
  2666. def to_screen(*msg):
  2667. self.to_screen(f'[info] {info_dict["id"]}: {" ".join(", ".join(variadic(m)) for m in msg)}')
  2668. to_screen(f'Downloading {len(formats_to_download)} format(s):',
  2669. (f['format_id'] for f in formats_to_download))
  2670. if requested_ranges != ({}, ):
  2671. to_screen(f'Downloading {len(requested_ranges)} time ranges:',
  2672. (f'{c["start_time"]:.1f}-{c["end_time"]:.1f}' for c in requested_ranges))
  2673. max_downloads_reached = False
  2674. for fmt, chapter in itertools.product(formats_to_download, requested_ranges):
  2675. new_info = self._copy_infodict(info_dict)
  2676. new_info.update(fmt)
  2677. offset, duration = info_dict.get('section_start') or 0, info_dict.get('duration') or float('inf')
  2678. end_time = offset + min(chapter.get('end_time', duration), duration)
  2679. # duration may not be accurate. So allow deviations <1sec
  2680. if end_time == float('inf') or end_time > offset + duration + 1:
  2681. end_time = None
  2682. if chapter or offset:
  2683. new_info.update({
  2684. 'section_start': offset + chapter.get('start_time', 0),
  2685. 'section_end': end_time,
  2686. 'section_title': chapter.get('title'),
  2687. 'section_number': chapter.get('index'),
  2688. })
  2689. downloaded_formats.append(new_info)
  2690. try:
  2691. self.process_info(new_info)
  2692. except MaxDownloadsReached:
  2693. max_downloads_reached = True
  2694. self._raise_pending_errors(new_info)
  2695. # Remove copied info
  2696. for key, val in tuple(new_info.items()):
  2697. if info_dict.get(key) == val:
  2698. new_info.pop(key)
  2699. if max_downloads_reached:
  2700. break
  2701. write_archive = {f.get('__write_download_archive', False) for f in downloaded_formats}
  2702. assert write_archive.issubset({True, False, 'ignore'})
  2703. if True in write_archive and False not in write_archive:
  2704. self.record_download_archive(info_dict)
  2705. info_dict['requested_downloads'] = downloaded_formats
  2706. info_dict = self.run_all_pps('after_video', info_dict)
  2707. if max_downloads_reached:
  2708. raise MaxDownloadsReached
  2709. # We update the info dict with the selected best quality format (backwards compatibility)
  2710. info_dict.update(best_format)
  2711. return info_dict
  2712. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  2713. """Select the requested subtitles and their format"""
  2714. available_subs, normal_sub_langs = {}, []
  2715. if normal_subtitles and self.params.get('writesubtitles'):
  2716. available_subs.update(normal_subtitles)
  2717. normal_sub_langs = tuple(normal_subtitles.keys())
  2718. if automatic_captions and self.params.get('writeautomaticsub'):
  2719. for lang, cap_info in automatic_captions.items():
  2720. if lang not in available_subs:
  2721. available_subs[lang] = cap_info
  2722. if not available_subs or (
  2723. not self.params.get('writesubtitles')
  2724. and not self.params.get('writeautomaticsub')):
  2725. return None
  2726. all_sub_langs = tuple(available_subs.keys())
  2727. if self.params.get('allsubtitles', False):
  2728. requested_langs = all_sub_langs
  2729. elif self.params.get('subtitleslangs', False):
  2730. try:
  2731. requested_langs = orderedSet_from_options(
  2732. self.params.get('subtitleslangs'), {'all': all_sub_langs}, use_regex=True)
  2733. except re.error as e:
  2734. raise ValueError(f'Wrong regex for subtitlelangs: {e.pattern}')
  2735. else:
  2736. requested_langs = LazyList(itertools.chain(
  2737. ['en'] if 'en' in normal_sub_langs else [],
  2738. filter(lambda f: f.startswith('en'), normal_sub_langs),
  2739. ['en'] if 'en' in all_sub_langs else [],
  2740. filter(lambda f: f.startswith('en'), all_sub_langs),
  2741. normal_sub_langs, all_sub_langs,
  2742. ))[:1]
  2743. if requested_langs:
  2744. self.to_screen(f'[info] {video_id}: Downloading subtitles: {", ".join(requested_langs)}')
  2745. formats_query = self.params.get('subtitlesformat', 'best')
  2746. formats_preference = formats_query.split('/') if formats_query else []
  2747. subs = {}
  2748. for lang in requested_langs:
  2749. formats = available_subs.get(lang)
  2750. if formats is None:
  2751. self.report_warning(f'{lang} subtitles not available for {video_id}')
  2752. continue
  2753. for ext in formats_preference:
  2754. if ext == 'best':
  2755. f = formats[-1]
  2756. break
  2757. matches = list(filter(lambda f: f['ext'] == ext, formats))
  2758. if matches:
  2759. f = matches[-1]
  2760. break
  2761. else:
  2762. f = formats[-1]
  2763. self.report_warning(
  2764. 'No subtitle format found matching "{}" for language {}, '
  2765. 'using {}. Use --list-subs for a list of available subtitles'.format(formats_query, lang, f['ext']))
  2766. subs[lang] = f
  2767. return subs
  2768. def _forceprint(self, key, info_dict):
  2769. if info_dict is None:
  2770. return
  2771. info_copy = info_dict.copy()
  2772. info_copy.setdefault('filename', self.prepare_filename(info_dict))
  2773. if info_dict.get('requested_formats') is not None:
  2774. # For RTMP URLs, also include the playpath
  2775. info_copy['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
  2776. elif info_dict.get('url'):
  2777. info_copy['urls'] = info_dict['url'] + info_dict.get('play_path', '')
  2778. info_copy['formats_table'] = self.render_formats_table(info_dict)
  2779. info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
  2780. info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
  2781. info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
  2782. def format_tmpl(tmpl):
  2783. mobj = re.fullmatch(r'([\w.:,]|-\d|(?P<dict>{([\w.:,]|-\d)+}))+=?', tmpl)
  2784. if not mobj:
  2785. return tmpl
  2786. fmt = '%({})s'
  2787. if tmpl.startswith('{'):
  2788. tmpl, fmt = f'.{tmpl}', '%({})j'
  2789. if tmpl.endswith('='):
  2790. tmpl, fmt = tmpl[:-1], '{0} = %({0})#j'
  2791. return '\n'.join(map(fmt.format, [tmpl] if mobj.group('dict') else tmpl.split(',')))
  2792. for tmpl in self.params['forceprint'].get(key, []):
  2793. self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
  2794. for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
  2795. filename = self.prepare_filename(info_dict, outtmpl=file_tmpl)
  2796. tmpl = format_tmpl(tmpl)
  2797. self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
  2798. if self._ensure_dir_exists(filename):
  2799. with open(filename, 'a', encoding='utf-8', newline='') as f:
  2800. f.write(self.evaluate_outtmpl(tmpl, info_copy) + os.linesep)
  2801. return info_copy
  2802. def __forced_printings(self, info_dict, filename=None, incomplete=True):
  2803. if (self.params.get('forcejson')
  2804. or self.params['forceprint'].get('video')
  2805. or self.params['print_to_file'].get('video')):
  2806. self.post_extract(info_dict)
  2807. if filename:
  2808. info_dict['filename'] = filename
  2809. info_copy = self._forceprint('video', info_dict)
  2810. def print_field(field, actual_field=None, optional=False):
  2811. if actual_field is None:
  2812. actual_field = field
  2813. if self.params.get(f'force{field}') and (
  2814. info_copy.get(field) is not None or (not optional and not incomplete)):
  2815. self.to_stdout(info_copy[actual_field])
  2816. print_field('title')
  2817. print_field('id')
  2818. print_field('url', 'urls')
  2819. print_field('thumbnail', optional=True)
  2820. print_field('description', optional=True)
  2821. print_field('filename')
  2822. if self.params.get('forceduration') and info_copy.get('duration') is not None:
  2823. self.to_stdout(formatSeconds(info_copy['duration']))
  2824. print_field('format')
  2825. if self.params.get('forcejson'):
  2826. self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
  2827. def dl(self, name, info, subtitle=False, test=False):
  2828. if not info.get('url'):
  2829. self.raise_no_formats(info, True)
  2830. if test:
  2831. verbose = self.params.get('verbose')
  2832. quiet = self.params.get('quiet') or not verbose
  2833. params = {
  2834. 'test': True,
  2835. 'quiet': quiet,
  2836. 'verbose': verbose,
  2837. 'noprogress': quiet,
  2838. 'nopart': True,
  2839. 'skip_unavailable_fragments': False,
  2840. 'keep_fragments': False,
  2841. 'overwrites': True,
  2842. '_no_ytdl_file': True,
  2843. }
  2844. else:
  2845. params = self.params
  2846. fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
  2847. if not test:
  2848. for ph in self._progress_hooks:
  2849. fd.add_progress_hook(ph)
  2850. urls = '", "'.join(
  2851. (f['url'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
  2852. for f in info.get('requested_formats', []) or [info])
  2853. self.write_debug(f'Invoking {fd.FD_NAME} downloader on "{urls}"')
  2854. # Note: Ideally info should be a deep-copied so that hooks cannot modify it.
  2855. # But it may contain objects that are not deep-copyable
  2856. new_info = self._copy_infodict(info)
  2857. if new_info.get('http_headers') is None:
  2858. new_info['http_headers'] = self._calc_headers(new_info)
  2859. return fd.download(name, new_info, subtitle)
  2860. def existing_file(self, filepaths, *, default_overwrite=True):
  2861. existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
  2862. if existing_files and not self.params.get('overwrites', default_overwrite):
  2863. return existing_files[0]
  2864. for file in existing_files:
  2865. self.report_file_delete(file)
  2866. os.remove(file)
  2867. return None
  2868. @_catch_unsafe_extension_error
  2869. def process_info(self, info_dict):
  2870. """Process a single resolved IE result. (Modifies it in-place)"""
  2871. assert info_dict.get('_type', 'video') == 'video'
  2872. original_infodict = info_dict
  2873. if 'format' not in info_dict and 'ext' in info_dict:
  2874. info_dict['format'] = info_dict['ext']
  2875. if self._match_entry(info_dict) is not None:
  2876. info_dict['__write_download_archive'] = 'ignore'
  2877. return
  2878. # Does nothing under normal operation - for backward compatibility of process_info
  2879. self.post_extract(info_dict)
  2880. def replace_info_dict(new_info):
  2881. nonlocal info_dict
  2882. if new_info == info_dict:
  2883. return
  2884. info_dict.clear()
  2885. info_dict.update(new_info)
  2886. new_info, _ = self.pre_process(info_dict, 'video')
  2887. replace_info_dict(new_info)
  2888. self._num_downloads += 1
  2889. # info_dict['_filename'] needs to be set for backward compatibility
  2890. info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
  2891. temp_filename = self.prepare_filename(info_dict, 'temp')
  2892. files_to_move = {}
  2893. # Forced printings
  2894. self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
  2895. def check_max_downloads():
  2896. if self._num_downloads >= float(self.params.get('max_downloads') or 'inf'):
  2897. raise MaxDownloadsReached
  2898. if self.params.get('simulate'):
  2899. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2900. check_max_downloads()
  2901. return
  2902. if full_filename is None:
  2903. return
  2904. if not self._ensure_dir_exists(full_filename):
  2905. return
  2906. if not self._ensure_dir_exists(temp_filename):
  2907. return
  2908. if self._write_description('video', info_dict,
  2909. self.prepare_filename(info_dict, 'description')) is None:
  2910. return
  2911. sub_files = self._write_subtitles(info_dict, temp_filename)
  2912. if sub_files is None:
  2913. return
  2914. files_to_move.update(dict(sub_files))
  2915. thumb_files = self._write_thumbnails(
  2916. 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
  2917. if thumb_files is None:
  2918. return
  2919. files_to_move.update(dict(thumb_files))
  2920. infofn = self.prepare_filename(info_dict, 'infojson')
  2921. _infojson_written = self._write_info_json('video', info_dict, infofn)
  2922. if _infojson_written:
  2923. info_dict['infojson_filename'] = infofn
  2924. # For backward compatibility, even though it was a private field
  2925. info_dict['__infojson_filename'] = infofn
  2926. elif _infojson_written is None:
  2927. return
  2928. # Note: Annotations are deprecated
  2929. annofn = None
  2930. if self.params.get('writeannotations', False):
  2931. annofn = self.prepare_filename(info_dict, 'annotation')
  2932. if annofn:
  2933. if not self._ensure_dir_exists(annofn):
  2934. return
  2935. if not self.params.get('overwrites', True) and os.path.exists(annofn):
  2936. self.to_screen('[info] Video annotations are already present')
  2937. elif not info_dict.get('annotations'):
  2938. self.report_warning('There are no annotations to write.')
  2939. else:
  2940. try:
  2941. self.to_screen('[info] Writing video annotations to: ' + annofn)
  2942. with open(annofn, 'w', encoding='utf-8') as annofile:
  2943. annofile.write(info_dict['annotations'])
  2944. except (KeyError, TypeError):
  2945. self.report_warning('There are no annotations to write.')
  2946. except OSError:
  2947. self.report_error('Cannot write annotations file: ' + annofn)
  2948. return
  2949. # Write internet shortcut files
  2950. def _write_link_file(link_type):
  2951. url = try_get(info_dict['webpage_url'], iri_to_uri)
  2952. if not url:
  2953. self.report_warning(
  2954. f'Cannot write internet shortcut file because the actual URL of "{info_dict["webpage_url"]}" is unknown')
  2955. return True
  2956. linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext'))
  2957. if not self._ensure_dir_exists(linkfn):
  2958. return False
  2959. if self.params.get('overwrites', True) and os.path.exists(linkfn):
  2960. self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
  2961. return True
  2962. try:
  2963. self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
  2964. with open(to_high_limit_path(linkfn), 'w', encoding='utf-8',
  2965. newline='\r\n' if link_type == 'url' else '\n') as linkfile:
  2966. template_vars = {'url': url}
  2967. if link_type == 'desktop':
  2968. template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
  2969. linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
  2970. except OSError:
  2971. self.report_error(f'Cannot write internet shortcut {linkfn}')
  2972. return False
  2973. return True
  2974. write_links = {
  2975. 'url': self.params.get('writeurllink'),
  2976. 'webloc': self.params.get('writewebloclink'),
  2977. 'desktop': self.params.get('writedesktoplink'),
  2978. }
  2979. if self.params.get('writelink'):
  2980. link_type = ('webloc' if sys.platform == 'darwin'
  2981. else 'desktop' if sys.platform.startswith('linux')
  2982. else 'url')
  2983. write_links[link_type] = True
  2984. if any(should_write and not _write_link_file(link_type)
  2985. for link_type, should_write in write_links.items()):
  2986. return
  2987. new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
  2988. replace_info_dict(new_info)
  2989. if self.params.get('skip_download'):
  2990. info_dict['filepath'] = temp_filename
  2991. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename))
  2992. info_dict['__files_to_move'] = files_to_move
  2993. replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
  2994. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2995. else:
  2996. # Download
  2997. info_dict.setdefault('__postprocessors', [])
  2998. try:
  2999. def existing_video_file(*filepaths):
  3000. ext = info_dict.get('ext')
  3001. converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
  3002. file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths)),
  3003. default_overwrite=False)
  3004. if file:
  3005. info_dict['ext'] = os.path.splitext(file)[1][1:]
  3006. return file
  3007. fd, success = None, True
  3008. if info_dict.get('protocol') or info_dict.get('url'):
  3009. fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
  3010. if fd != FFmpegFD and 'no-direct-merge' not in self.params['compat_opts'] and (
  3011. info_dict.get('section_start') or info_dict.get('section_end')):
  3012. msg = ('This format cannot be partially downloaded' if FFmpegFD.available()
  3013. else 'You have requested downloading the video partially, but ffmpeg is not installed')
  3014. self.report_error(f'{msg}. Aborting')
  3015. return
  3016. if info_dict.get('requested_formats') is not None:
  3017. old_ext = info_dict['ext']
  3018. if self.params.get('merge_output_format') is None:
  3019. if (info_dict['ext'] == 'webm'
  3020. and info_dict.get('thumbnails')
  3021. # check with type instead of pp_key, __name__, or isinstance
  3022. # since we dont want any custom PPs to trigger this
  3023. and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])): # noqa: E721
  3024. info_dict['ext'] = 'mkv'
  3025. self.report_warning(
  3026. 'webm doesn\'t support embedding a thumbnail, mkv will be used')
  3027. new_ext = info_dict['ext']
  3028. def correct_ext(filename, ext=new_ext):
  3029. if filename == '-':
  3030. return filename
  3031. filename_real_ext = os.path.splitext(filename)[1][1:]
  3032. filename_wo_ext = (
  3033. os.path.splitext(filename)[0]
  3034. if filename_real_ext in (old_ext, new_ext)
  3035. else filename)
  3036. return f'{filename_wo_ext}.{ext}'
  3037. # Ensure filename always has a correct extension for successful merge
  3038. full_filename = correct_ext(full_filename)
  3039. temp_filename = correct_ext(temp_filename)
  3040. dl_filename = existing_video_file(full_filename, temp_filename)
  3041. info_dict['__real_download'] = False
  3042. # NOTE: Copy so that original format dicts are not modified
  3043. info_dict['requested_formats'] = list(map(dict, info_dict['requested_formats']))
  3044. merger = FFmpegMergerPP(self)
  3045. downloaded = []
  3046. if dl_filename is not None:
  3047. self.report_file_already_downloaded(dl_filename)
  3048. elif fd:
  3049. for f in info_dict['requested_formats'] if fd != FFmpegFD else []:
  3050. f['filepath'] = fname = prepend_extension(
  3051. correct_ext(temp_filename, info_dict['ext']),
  3052. 'f{}'.format(f['format_id']), info_dict['ext'])
  3053. downloaded.append(fname)
  3054. info_dict['url'] = '\n'.join(f['url'] for f in info_dict['requested_formats'])
  3055. success, real_download = self.dl(temp_filename, info_dict)
  3056. info_dict['__real_download'] = real_download
  3057. else:
  3058. if self.params.get('allow_unplayable_formats'):
  3059. self.report_warning(
  3060. 'You have requested merging of multiple formats '
  3061. 'while also allowing unplayable formats to be downloaded. '
  3062. 'The formats won\'t be merged to prevent data corruption.')
  3063. elif not merger.available:
  3064. msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
  3065. if not self.params.get('ignoreerrors'):
  3066. self.report_error(f'{msg}. Aborting due to --abort-on-error')
  3067. return
  3068. self.report_warning(f'{msg}. The formats won\'t be merged')
  3069. if temp_filename == '-':
  3070. reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
  3071. else 'but the formats are incompatible for simultaneous download' if merger.available
  3072. else 'but ffmpeg is not installed')
  3073. self.report_warning(
  3074. f'You have requested downloading multiple formats to stdout {reason}. '
  3075. 'The formats will be streamed one after the other')
  3076. fname = temp_filename
  3077. for f in info_dict['requested_formats']:
  3078. new_info = dict(info_dict)
  3079. del new_info['requested_formats']
  3080. new_info.update(f)
  3081. if temp_filename != '-':
  3082. fname = prepend_extension(
  3083. correct_ext(temp_filename, new_info['ext']),
  3084. 'f{}'.format(f['format_id']), new_info['ext'])
  3085. if not self._ensure_dir_exists(fname):
  3086. return
  3087. f['filepath'] = fname
  3088. downloaded.append(fname)
  3089. partial_success, real_download = self.dl(fname, new_info)
  3090. info_dict['__real_download'] = info_dict['__real_download'] or real_download
  3091. success = success and partial_success
  3092. if downloaded and merger.available and not self.params.get('allow_unplayable_formats'):
  3093. info_dict['__postprocessors'].append(merger)
  3094. info_dict['__files_to_merge'] = downloaded
  3095. # Even if there were no downloads, it is being merged only now
  3096. info_dict['__real_download'] = True
  3097. else:
  3098. for file in downloaded:
  3099. files_to_move[file] = None
  3100. else:
  3101. # Just a single file
  3102. dl_filename = existing_video_file(full_filename, temp_filename)
  3103. if dl_filename is None or dl_filename == temp_filename:
  3104. # dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
  3105. # So we should try to resume the download
  3106. success, real_download = self.dl(temp_filename, info_dict)
  3107. info_dict['__real_download'] = real_download
  3108. else:
  3109. self.report_file_already_downloaded(dl_filename)
  3110. dl_filename = dl_filename or temp_filename
  3111. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename))
  3112. except network_exceptions as err:
  3113. self.report_error(f'unable to download video data: {err}')
  3114. return
  3115. except OSError as err:
  3116. raise UnavailableVideoError(err)
  3117. except ContentTooShortError as err:
  3118. self.report_error(f'content too short (expected {err.expected} bytes and served {err.downloaded})')
  3119. return
  3120. self._raise_pending_errors(info_dict)
  3121. if success and full_filename != '-':
  3122. def fixup():
  3123. do_fixup = True
  3124. fixup_policy = self.params.get('fixup')
  3125. vid = info_dict['id']
  3126. if fixup_policy in ('ignore', 'never'):
  3127. return
  3128. elif fixup_policy == 'warn':
  3129. do_fixup = 'warn'
  3130. elif fixup_policy != 'force':
  3131. assert fixup_policy in ('detect_or_warn', None)
  3132. if not info_dict.get('__real_download'):
  3133. do_fixup = False
  3134. def ffmpeg_fixup(cndn, msg, cls):
  3135. if not (do_fixup and cndn):
  3136. return
  3137. elif do_fixup == 'warn':
  3138. self.report_warning(f'{vid}: {msg}')
  3139. return
  3140. pp = cls(self)
  3141. if pp.available:
  3142. info_dict['__postprocessors'].append(pp)
  3143. else:
  3144. self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
  3145. stretched_ratio = info_dict.get('stretched_ratio')
  3146. ffmpeg_fixup(stretched_ratio not in (1, None),
  3147. f'Non-uniform pixel ratio {stretched_ratio}',
  3148. FFmpegFixupStretchedPP)
  3149. downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
  3150. downloader = downloader.FD_NAME if downloader else None
  3151. ext = info_dict.get('ext')
  3152. postprocessed_by_ffmpeg = info_dict.get('requested_formats') or any((
  3153. isinstance(pp, FFmpegVideoConvertorPP)
  3154. and resolve_recode_mapping(ext, pp.mapping)[0] not in (ext, None)
  3155. ) for pp in self._pps['post_process'])
  3156. if not postprocessed_by_ffmpeg:
  3157. ffmpeg_fixup(fd != FFmpegFD and ext == 'm4a'
  3158. and info_dict.get('container') == 'm4a_dash',
  3159. 'writing DASH m4a. Only some players support this container',
  3160. FFmpegFixupM4aPP)
  3161. ffmpeg_fixup(downloader == 'hlsnative' and not self.params.get('hls_use_mpegts')
  3162. or info_dict.get('is_live') and self.params.get('hls_use_mpegts') is None,
  3163. 'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
  3164. FFmpegFixupM3u8PP)
  3165. ffmpeg_fixup(downloader == 'dashsegments'
  3166. and (info_dict.get('is_live') or info_dict.get('is_dash_periods')),
  3167. 'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
  3168. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
  3169. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed duration detected', FFmpegFixupDurationPP)
  3170. fixup()
  3171. try:
  3172. replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
  3173. except PostProcessingError as err:
  3174. self.report_error(f'Postprocessing: {err}')
  3175. return
  3176. try:
  3177. for ph in self._post_hooks:
  3178. ph(info_dict['filepath'])
  3179. except Exception as err:
  3180. self.report_error(f'post hooks: {err}')
  3181. return
  3182. info_dict['__write_download_archive'] = True
  3183. assert info_dict is original_infodict # Make sure the info_dict was modified in-place
  3184. if self.params.get('force_write_download_archive'):
  3185. info_dict['__write_download_archive'] = True
  3186. check_max_downloads()
  3187. def __download_wrapper(self, func):
  3188. @functools.wraps(func)
  3189. def wrapper(*args, **kwargs):
  3190. try:
  3191. res = func(*args, **kwargs)
  3192. except CookieLoadError:
  3193. raise
  3194. except UnavailableVideoError as e:
  3195. self.report_error(e)
  3196. except DownloadCancelled as e:
  3197. self.to_screen(f'[info] {e}')
  3198. if not self.params.get('break_per_url'):
  3199. raise
  3200. self._num_downloads = 0
  3201. else:
  3202. if self.params.get('dump_single_json', False):
  3203. self.post_extract(res)
  3204. self.to_stdout(json.dumps(self.sanitize_info(res)))
  3205. return wrapper
  3206. def download(self, url_list):
  3207. """Download a given list of URLs."""
  3208. url_list = variadic(url_list) # Passing a single URL is a common mistake
  3209. outtmpl = self.params['outtmpl']['default']
  3210. if (len(url_list) > 1
  3211. and outtmpl != '-'
  3212. and '%' not in outtmpl
  3213. and self.params.get('max_downloads') != 1):
  3214. raise SameFileError(outtmpl)
  3215. for url in url_list:
  3216. self.__download_wrapper(self.extract_info)(
  3217. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  3218. return self._download_retcode
  3219. def download_with_info_file(self, info_filename):
  3220. with contextlib.closing(fileinput.FileInput(
  3221. [info_filename], mode='r',
  3222. openhook=fileinput.hook_encoded('utf-8'))) as f:
  3223. # FileInput doesn't have a read method, we can't call json.load
  3224. infos = [self.sanitize_info(info, self.params.get('clean_infojson', True))
  3225. for info in variadic(json.loads('\n'.join(f)))]
  3226. for info in infos:
  3227. try:
  3228. self.__download_wrapper(self.process_ie_result)(info, download=True)
  3229. except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
  3230. if not isinstance(e, EntryNotInPlaylist):
  3231. self.to_stderr('\r')
  3232. webpage_url = info.get('webpage_url')
  3233. if webpage_url is None:
  3234. raise
  3235. self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}')
  3236. self.download([webpage_url])
  3237. except ExtractorError as e:
  3238. self.report_error(e)
  3239. return self._download_retcode
  3240. @staticmethod
  3241. def sanitize_info(info_dict, remove_private_keys=False):
  3242. """ Sanitize the infodict for converting to json """
  3243. if info_dict is None:
  3244. return info_dict
  3245. info_dict.setdefault('epoch', int(time.time()))
  3246. info_dict.setdefault('_type', 'video')
  3247. info_dict.setdefault('_version', {
  3248. 'version': __version__,
  3249. 'current_git_head': current_git_head(),
  3250. 'release_git_head': RELEASE_GIT_HEAD,
  3251. 'repository': ORIGIN,
  3252. })
  3253. if remove_private_keys:
  3254. reject = lambda k, v: v is None or k.startswith('__') or k in {
  3255. 'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
  3256. 'entries', 'filepath', '_filename', 'filename', 'infojson_filename', 'original_url',
  3257. 'playlist_autonumber',
  3258. }
  3259. else:
  3260. reject = lambda k, v: False
  3261. def filter_fn(obj):
  3262. if isinstance(obj, dict):
  3263. return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
  3264. elif isinstance(obj, (list, tuple, set, LazyList)):
  3265. return list(map(filter_fn, obj))
  3266. elif obj is None or isinstance(obj, (str, int, float, bool)):
  3267. return obj
  3268. else:
  3269. return repr(obj)
  3270. return filter_fn(info_dict)
  3271. @staticmethod
  3272. def filter_requested_info(info_dict, actually_filter=True):
  3273. """ Alias of sanitize_info for backward compatibility """
  3274. return YoutubeDL.sanitize_info(info_dict, actually_filter)
  3275. def _delete_downloaded_files(self, *files_to_delete, info={}, msg=None):
  3276. for filename in set(filter(None, files_to_delete)):
  3277. if msg:
  3278. self.to_screen(msg % filename)
  3279. try:
  3280. os.remove(filename)
  3281. except OSError:
  3282. self.report_warning(f'Unable to delete file {filename}')
  3283. if filename in info.get('__files_to_move', []): # NB: Delete even if None
  3284. del info['__files_to_move'][filename]
  3285. @staticmethod
  3286. def post_extract(info_dict):
  3287. def actual_post_extract(info_dict):
  3288. if info_dict.get('_type') in ('playlist', 'multi_video'):
  3289. for video_dict in info_dict.get('entries', {}):
  3290. actual_post_extract(video_dict or {})
  3291. return
  3292. post_extractor = info_dict.pop('__post_extractor', None) or dict
  3293. info_dict.update(post_extractor())
  3294. actual_post_extract(info_dict or {})
  3295. def run_pp(self, pp, infodict):
  3296. files_to_delete = []
  3297. if '__files_to_move' not in infodict:
  3298. infodict['__files_to_move'] = {}
  3299. try:
  3300. files_to_delete, infodict = pp.run(infodict)
  3301. except PostProcessingError as e:
  3302. # Must be True and not 'only_download'
  3303. if self.params.get('ignoreerrors') is True:
  3304. self.report_error(e)
  3305. return infodict
  3306. raise
  3307. if not files_to_delete:
  3308. return infodict
  3309. if self.params.get('keepvideo', False):
  3310. for f in files_to_delete:
  3311. infodict['__files_to_move'].setdefault(f, '')
  3312. else:
  3313. self._delete_downloaded_files(
  3314. *files_to_delete, info=infodict, msg='Deleting original file %s (pass -k to keep)')
  3315. return infodict
  3316. def run_all_pps(self, key, info, *, additional_pps=None):
  3317. if key != 'video':
  3318. self._forceprint(key, info)
  3319. for pp in (additional_pps or []) + self._pps[key]:
  3320. info = self.run_pp(pp, info)
  3321. return info
  3322. def pre_process(self, ie_info, key='pre_process', files_to_move=None):
  3323. info = dict(ie_info)
  3324. info['__files_to_move'] = files_to_move or {}
  3325. try:
  3326. info = self.run_all_pps(key, info)
  3327. except PostProcessingError as err:
  3328. msg = f'Preprocessing: {err}'
  3329. info.setdefault('__pending_error', msg)
  3330. self.report_error(msg, is_error=False)
  3331. return info, info.pop('__files_to_move', None)
  3332. def post_process(self, filename, info, files_to_move=None):
  3333. """Run all the postprocessors on the given file."""
  3334. info['filepath'] = filename
  3335. info['__files_to_move'] = files_to_move or {}
  3336. info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
  3337. info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
  3338. del info['__files_to_move']
  3339. return self.run_all_pps('after_move', info)
  3340. def _make_archive_id(self, info_dict):
  3341. video_id = info_dict.get('id')
  3342. if not video_id:
  3343. return
  3344. # Future-proof against any change in case
  3345. # and backwards compatibility with prior versions
  3346. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  3347. if extractor is None:
  3348. url = str_or_none(info_dict.get('url'))
  3349. if not url:
  3350. return
  3351. # Try to find matching extractor for the URL and take its ie_key
  3352. for ie_key, ie in self._ies.items():
  3353. if ie.suitable(url):
  3354. extractor = ie_key
  3355. break
  3356. else:
  3357. return
  3358. return make_archive_id(extractor, video_id)
  3359. def in_download_archive(self, info_dict):
  3360. if not self.archive:
  3361. return False
  3362. vid_ids = [self._make_archive_id(info_dict)]
  3363. vid_ids.extend(info_dict.get('_old_archive_ids') or [])
  3364. return any(id_ in self.archive for id_ in vid_ids)
  3365. def record_download_archive(self, info_dict):
  3366. fn = self.params.get('download_archive')
  3367. if fn is None:
  3368. return
  3369. vid_id = self._make_archive_id(info_dict)
  3370. assert vid_id
  3371. self.write_debug(f'Adding to archive: {vid_id}')
  3372. if is_path_like(fn):
  3373. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  3374. archive_file.write(vid_id + '\n')
  3375. self.archive.add(vid_id)
  3376. @staticmethod
  3377. def format_resolution(format, default='unknown'):
  3378. if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
  3379. return 'audio only'
  3380. if format.get('resolution') is not None:
  3381. return format['resolution']
  3382. if format.get('width') and format.get('height'):
  3383. return '%dx%d' % (format['width'], format['height'])
  3384. elif format.get('height'):
  3385. return '{}p'.format(format['height'])
  3386. elif format.get('width'):
  3387. return '%dx?' % format['width']
  3388. return default
  3389. def _list_format_headers(self, *headers):
  3390. if self.params.get('listformats_table', True) is not False:
  3391. return [self._format_out(header, self.Styles.HEADERS) for header in headers]
  3392. return headers
  3393. def _format_note(self, fdict):
  3394. res = ''
  3395. if fdict.get('ext') in ['f4f', 'f4m']:
  3396. res += '(unsupported)'
  3397. if fdict.get('language'):
  3398. if res:
  3399. res += ' '
  3400. res += '[{}]'.format(fdict['language'])
  3401. if fdict.get('format_note') is not None:
  3402. if res:
  3403. res += ' '
  3404. res += fdict['format_note']
  3405. if fdict.get('tbr') is not None:
  3406. if res:
  3407. res += ', '
  3408. res += '%4dk' % fdict['tbr']
  3409. if fdict.get('container') is not None:
  3410. if res:
  3411. res += ', '
  3412. res += '{} container'.format(fdict['container'])
  3413. if (fdict.get('vcodec') is not None
  3414. and fdict.get('vcodec') != 'none'):
  3415. if res:
  3416. res += ', '
  3417. res += fdict['vcodec']
  3418. if fdict.get('vbr') is not None:
  3419. res += '@'
  3420. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  3421. res += 'video@'
  3422. if fdict.get('vbr') is not None:
  3423. res += '%4dk' % fdict['vbr']
  3424. if fdict.get('fps') is not None:
  3425. if res:
  3426. res += ', '
  3427. res += '{}fps'.format(fdict['fps'])
  3428. if fdict.get('acodec') is not None:
  3429. if res:
  3430. res += ', '
  3431. if fdict['acodec'] == 'none':
  3432. res += 'video only'
  3433. else:
  3434. res += '%-5s' % fdict['acodec']
  3435. elif fdict.get('abr') is not None:
  3436. if res:
  3437. res += ', '
  3438. res += 'audio'
  3439. if fdict.get('abr') is not None:
  3440. res += '@%3dk' % fdict['abr']
  3441. if fdict.get('asr') is not None:
  3442. res += ' (%5dHz)' % fdict['asr']
  3443. if fdict.get('filesize') is not None:
  3444. if res:
  3445. res += ', '
  3446. res += format_bytes(fdict['filesize'])
  3447. elif fdict.get('filesize_approx') is not None:
  3448. if res:
  3449. res += ', '
  3450. res += '~' + format_bytes(fdict['filesize_approx'])
  3451. return res
  3452. def _get_formats(self, info_dict):
  3453. if info_dict.get('formats') is None:
  3454. if info_dict.get('url') and info_dict.get('_type', 'video') == 'video':
  3455. return [info_dict]
  3456. return []
  3457. return info_dict['formats']
  3458. def render_formats_table(self, info_dict):
  3459. formats = self._get_formats(info_dict)
  3460. if not formats:
  3461. return
  3462. if not self.params.get('listformats_table', True) is not False:
  3463. table = [
  3464. [
  3465. format_field(f, 'format_id'),
  3466. format_field(f, 'ext'),
  3467. self.format_resolution(f),
  3468. self._format_note(f),
  3469. ] for f in formats if (f.get('preference') or 0) >= -1000]
  3470. return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
  3471. def simplified_codec(f, field):
  3472. assert field in ('acodec', 'vcodec')
  3473. codec = f.get(field)
  3474. if not codec:
  3475. return 'unknown'
  3476. elif codec != 'none':
  3477. return '.'.join(codec.split('.')[:4])
  3478. if field == 'vcodec' and f.get('acodec') == 'none':
  3479. return 'images'
  3480. elif field == 'acodec' and f.get('vcodec') == 'none':
  3481. return ''
  3482. return self._format_out('audio only' if field == 'vcodec' else 'video only',
  3483. self.Styles.SUPPRESS)
  3484. delim = self._format_out('\u2502', self.Styles.DELIM, '|', test_encoding=True)
  3485. table = [
  3486. [
  3487. self._format_out(format_field(f, 'format_id'), self.Styles.ID),
  3488. format_field(f, 'ext'),
  3489. format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
  3490. format_field(f, 'fps', '\t%d', func=round),
  3491. format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
  3492. format_field(f, 'audio_channels', '\t%s'),
  3493. delim, (
  3494. format_field(f, 'filesize', ' \t%s', func=format_bytes)
  3495. or format_field(f, 'filesize_approx', '≈\t%s', func=format_bytes)
  3496. or format_field(filesize_from_tbr(f.get('tbr'), info_dict.get('duration')), None,
  3497. self._format_out('~\t%s', self.Styles.SUPPRESS), func=format_bytes)),
  3498. format_field(f, 'tbr', '\t%dk', func=round),
  3499. shorten_protocol_name(f.get('protocol', '')),
  3500. delim,
  3501. simplified_codec(f, 'vcodec'),
  3502. format_field(f, 'vbr', '\t%dk', func=round),
  3503. simplified_codec(f, 'acodec'),
  3504. format_field(f, 'abr', '\t%dk', func=round),
  3505. format_field(f, 'asr', '\t%s', func=format_decimal_suffix),
  3506. join_nonempty(format_field(f, 'language', '[%s]'), join_nonempty(
  3507. self._format_out('UNSUPPORTED', self.Styles.BAD_FORMAT) if f.get('ext') in ('f4f', 'f4m') else None,
  3508. (self._format_out('Maybe DRM', self.Styles.WARNING) if f.get('has_drm') == 'maybe'
  3509. else self._format_out('DRM', self.Styles.BAD_FORMAT) if f.get('has_drm') else None),
  3510. format_field(f, 'format_note'),
  3511. format_field(f, 'container', ignore=(None, f.get('ext'))),
  3512. delim=', '), delim=' '),
  3513. ] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
  3514. header_line = self._list_format_headers(
  3515. 'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', 'CH', delim, '\tFILESIZE', '\tTBR', 'PROTO',
  3516. delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
  3517. return render_table(
  3518. header_line, table, hide_empty=True,
  3519. delim=self._format_out('\u2500', self.Styles.DELIM, '-', test_encoding=True))
  3520. def render_thumbnails_table(self, info_dict):
  3521. thumbnails = list(info_dict.get('thumbnails') or [])
  3522. if not thumbnails:
  3523. return None
  3524. return render_table(
  3525. self._list_format_headers('ID', 'Width', 'Height', 'URL'),
  3526. [[t.get('id'), t.get('width') or 'unknown', t.get('height') or 'unknown', t['url']] for t in thumbnails])
  3527. def render_subtitles_table(self, video_id, subtitles):
  3528. def _row(lang, formats):
  3529. exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)))
  3530. if len(set(names)) == 1:
  3531. names = [] if names[0] == 'unknown' else names[:1]
  3532. return [lang, ', '.join(names), ', '.join(exts)]
  3533. if not subtitles:
  3534. return None
  3535. return render_table(
  3536. self._list_format_headers('Language', 'Name', 'Formats'),
  3537. [_row(lang, formats) for lang, formats in subtitles.items()],
  3538. hide_empty=True)
  3539. def __list_table(self, video_id, name, func, *args):
  3540. table = func(*args)
  3541. if not table:
  3542. self.to_screen(f'{video_id} has no {name}')
  3543. return
  3544. self.to_screen(f'[info] Available {name} for {video_id}:')
  3545. self.to_stdout(table)
  3546. def list_formats(self, info_dict):
  3547. self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
  3548. def list_thumbnails(self, info_dict):
  3549. self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
  3550. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  3551. self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
  3552. def print_debug_header(self):
  3553. if not self.params.get('verbose'):
  3554. return
  3555. from . import _IN_CLI # Must be delayed import
  3556. # These imports can be slow. So import them only as needed
  3557. from .extractor.extractors import _LAZY_LOADER
  3558. from .extractor.extractors import (
  3559. _PLUGIN_CLASSES as plugin_ies,
  3560. _PLUGIN_OVERRIDES as plugin_ie_overrides,
  3561. )
  3562. def get_encoding(stream):
  3563. ret = str(getattr(stream, 'encoding', f'missing ({type(stream).__name__})'))
  3564. additional_info = []
  3565. if os.environ.get('TERM', '').lower() == 'dumb':
  3566. additional_info.append('dumb')
  3567. if not supports_terminal_sequences(stream):
  3568. from .utils import WINDOWS_VT_MODE # Must be imported locally
  3569. additional_info.append('No VT' if WINDOWS_VT_MODE is False else 'No ANSI')
  3570. if additional_info:
  3571. ret = f'{ret} ({",".join(additional_info)})'
  3572. return ret
  3573. encoding_str = 'Encodings: locale {}, fs {}, pref {}, {}'.format(
  3574. locale.getpreferredencoding(),
  3575. sys.getfilesystemencoding(),
  3576. self.get_encoding(),
  3577. ', '.join(
  3578. f'{key} {get_encoding(stream)}' for key, stream in self._out_files.items_
  3579. if stream is not None and key != 'console'),
  3580. )
  3581. logger = self.params.get('logger')
  3582. if logger:
  3583. write_debug = lambda msg: logger.debug(f'[debug] {msg}')
  3584. write_debug(encoding_str)
  3585. else:
  3586. write_string(f'[debug] {encoding_str}\n', encoding=None)
  3587. write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
  3588. source = detect_variant()
  3589. if VARIANT not in (None, 'pip'):
  3590. source += '*'
  3591. klass = type(self)
  3592. write_debug(join_nonempty(
  3593. f'{REPOSITORY.rpartition("/")[2]} version',
  3594. _make_label(ORIGIN, CHANNEL.partition('@')[2] or __version__, __version__),
  3595. f'[{RELEASE_GIT_HEAD[:9]}]' if RELEASE_GIT_HEAD else '',
  3596. '' if source == 'unknown' else f'({source})',
  3597. '' if _IN_CLI else 'API' if klass == YoutubeDL else f'API:{self.__module__}.{klass.__qualname__}',
  3598. delim=' '))
  3599. if not _IN_CLI:
  3600. write_debug(f'params: {self.params}')
  3601. if not _LAZY_LOADER:
  3602. if os.environ.get('YTDLP_NO_LAZY_EXTRACTORS'):
  3603. write_debug('Lazy loading extractors is forcibly disabled')
  3604. else:
  3605. write_debug('Lazy loading extractors is disabled')
  3606. if self.params['compat_opts']:
  3607. write_debug('Compatibility options: {}'.format(', '.join(self.params['compat_opts'])))
  3608. if current_git_head():
  3609. write_debug(f'Git HEAD: {current_git_head()}')
  3610. write_debug(system_identifier())
  3611. exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
  3612. ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
  3613. if ffmpeg_features:
  3614. exe_versions['ffmpeg'] += ' ({})'.format(','.join(sorted(ffmpeg_features)))
  3615. exe_versions['rtmpdump'] = rtmpdump_version()
  3616. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  3617. exe_str = ', '.join(
  3618. f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
  3619. ) or 'none'
  3620. write_debug(f'exe versions: {exe_str}')
  3621. from .compat.compat_utils import get_package_info
  3622. from .dependencies import available_dependencies
  3623. write_debug('Optional libraries: %s' % (', '.join(sorted({
  3624. join_nonempty(*get_package_info(m)) for m in available_dependencies.values()
  3625. })) or 'none'))
  3626. write_debug(f'Proxy map: {self.proxies}')
  3627. write_debug(f'Request Handlers: {", ".join(rh.RH_NAME for rh in self._request_director.handlers.values())}')
  3628. if os.environ.get('YTDLP_NO_PLUGINS'):
  3629. write_debug('Plugins are forcibly disabled')
  3630. return
  3631. for plugin_type, plugins in {'Extractor': plugin_ies, 'Post-Processor': plugin_pps}.items():
  3632. display_list = ['{}{}'.format(
  3633. klass.__name__, '' if klass.__name__ == name else f' as {name}')
  3634. for name, klass in plugins.items()]
  3635. if plugin_type == 'Extractor':
  3636. display_list.extend(f'{plugins[-1].IE_NAME.partition("+")[2]} ({parent.__name__})'
  3637. for parent, plugins in plugin_ie_overrides.items())
  3638. if not display_list:
  3639. continue
  3640. write_debug(f'{plugin_type} Plugins: {", ".join(sorted(display_list))}')
  3641. plugin_dirs = plugin_directories()
  3642. if plugin_dirs:
  3643. write_debug(f'Plugin directories: {plugin_dirs}')
  3644. @functools.cached_property
  3645. def proxies(self):
  3646. """Global proxy configuration"""
  3647. opts_proxy = self.params.get('proxy')
  3648. if opts_proxy is not None:
  3649. if opts_proxy == '':
  3650. opts_proxy = '__noproxy__'
  3651. proxies = {'all': opts_proxy}
  3652. else:
  3653. proxies = urllib.request.getproxies()
  3654. # compat. Set HTTPS_PROXY to __noproxy__ to revert
  3655. if 'http' in proxies and 'https' not in proxies:
  3656. proxies['https'] = proxies['http']
  3657. return proxies
  3658. @functools.cached_property
  3659. def cookiejar(self):
  3660. """Global cookiejar instance"""
  3661. try:
  3662. return load_cookies(
  3663. self.params.get('cookiefile'), self.params.get('cookiesfrombrowser'), self)
  3664. except CookieLoadError as error:
  3665. cause = error.__context__
  3666. # compat: <=py3.9: `traceback.format_exception` has a different signature
  3667. self.report_error(str(cause), tb=''.join(traceback.format_exception(None, cause, cause.__traceback__)))
  3668. raise
  3669. @property
  3670. def _opener(self):
  3671. """
  3672. Get a urllib OpenerDirector from the Urllib handler (deprecated).
  3673. """
  3674. self.deprecation_warning('YoutubeDL._opener is deprecated, use YoutubeDL.urlopen()')
  3675. handler = self._request_director.handlers['Urllib']
  3676. return handler._get_instance(cookiejar=self.cookiejar, proxies=self.proxies)
  3677. def _get_available_impersonate_targets(self):
  3678. # TODO(future): make available as public API
  3679. return [
  3680. (target, rh.RH_NAME)
  3681. for rh in self._request_director.handlers.values()
  3682. if isinstance(rh, ImpersonateRequestHandler)
  3683. for target in rh.supported_targets
  3684. ]
  3685. def _impersonate_target_available(self, target):
  3686. # TODO(future): make available as public API
  3687. return any(
  3688. rh.is_supported_target(target)
  3689. for rh in self._request_director.handlers.values()
  3690. if isinstance(rh, ImpersonateRequestHandler))
  3691. def urlopen(self, req):
  3692. """ Start an HTTP download """
  3693. if isinstance(req, str):
  3694. req = Request(req)
  3695. elif isinstance(req, urllib.request.Request):
  3696. self.deprecation_warning(
  3697. 'Passing a urllib.request.Request object to YoutubeDL.urlopen() is deprecated. '
  3698. 'Use yt_dlp.networking.common.Request instead.')
  3699. req = urllib_req_to_req(req)
  3700. assert isinstance(req, Request)
  3701. # compat: Assume user:pass url params are basic auth
  3702. url, basic_auth_header = extract_basic_auth(req.url)
  3703. if basic_auth_header:
  3704. req.headers['Authorization'] = basic_auth_header
  3705. req.url = sanitize_url(url)
  3706. clean_proxies(proxies=req.proxies, headers=req.headers)
  3707. clean_headers(req.headers)
  3708. try:
  3709. return self._request_director.send(req)
  3710. except NoSupportingHandlers as e:
  3711. for ue in e.unsupported_errors:
  3712. # FIXME: This depends on the order of errors.
  3713. if not (ue.handler and ue.msg):
  3714. continue
  3715. if ue.handler.RH_KEY == 'Urllib' and 'unsupported url scheme: "file"' in ue.msg.lower():
  3716. raise RequestError(
  3717. 'file:// URLs are disabled by default in yt-dlp for security reasons. '
  3718. 'Use --enable-file-urls to enable at your own risk.', cause=ue) from ue
  3719. if (
  3720. 'unsupported proxy type: "https"' in ue.msg.lower()
  3721. and 'requests' not in self._request_director.handlers
  3722. and 'curl_cffi' not in self._request_director.handlers
  3723. ):
  3724. raise RequestError(
  3725. 'To use an HTTPS proxy for this request, one of the following dependencies needs to be installed: requests, curl_cffi')
  3726. elif (
  3727. re.match(r'unsupported url scheme: "wss?"', ue.msg.lower())
  3728. and 'websockets' not in self._request_director.handlers
  3729. ):
  3730. raise RequestError(
  3731. 'This request requires WebSocket support. '
  3732. 'Ensure one of the following dependencies are installed: websockets',
  3733. cause=ue) from ue
  3734. elif re.match(r'unsupported (?:extensions: impersonate|impersonate target)', ue.msg.lower()):
  3735. raise RequestError(
  3736. f'Impersonate target "{req.extensions["impersonate"]}" is not available.'
  3737. f' See --list-impersonate-targets for available targets.'
  3738. f' This request requires browser impersonation, however you may be missing dependencies'
  3739. f' required to support this target.')
  3740. raise
  3741. except SSLError as e:
  3742. if 'UNSAFE_LEGACY_RENEGOTIATION_DISABLED' in str(e):
  3743. raise RequestError('UNSAFE_LEGACY_RENEGOTIATION_DISABLED: Try using --legacy-server-connect', cause=e) from e
  3744. elif 'SSLV3_ALERT_HANDSHAKE_FAILURE' in str(e):
  3745. raise RequestError(
  3746. 'SSLV3_ALERT_HANDSHAKE_FAILURE: The server may not support the current cipher list. '
  3747. 'Try using --legacy-server-connect', cause=e) from e
  3748. raise
  3749. def build_request_director(self, handlers, preferences=None):
  3750. logger = _YDLLogger(self)
  3751. headers = self.params['http_headers'].copy()
  3752. proxies = self.proxies.copy()
  3753. clean_headers(headers)
  3754. clean_proxies(proxies, headers)
  3755. director = RequestDirector(logger=logger, verbose=self.params.get('debug_printtraffic'))
  3756. for handler in handlers:
  3757. director.add_handler(handler(
  3758. logger=logger,
  3759. headers=headers,
  3760. cookiejar=self.cookiejar,
  3761. proxies=proxies,
  3762. prefer_system_certs='no-certifi' in self.params['compat_opts'],
  3763. verify=not self.params.get('nocheckcertificate'),
  3764. **traverse_obj(self.params, {
  3765. 'verbose': 'debug_printtraffic',
  3766. 'source_address': 'source_address',
  3767. 'timeout': 'socket_timeout',
  3768. 'legacy_ssl_support': 'legacyserverconnect',
  3769. 'enable_file_urls': 'enable_file_urls',
  3770. 'impersonate': 'impersonate',
  3771. 'client_cert': {
  3772. 'client_certificate': 'client_certificate',
  3773. 'client_certificate_key': 'client_certificate_key',
  3774. 'client_certificate_password': 'client_certificate_password',
  3775. },
  3776. }),
  3777. ))
  3778. director.preferences.update(preferences or [])
  3779. if 'prefer-legacy-http-handler' in self.params['compat_opts']:
  3780. director.preferences.add(lambda rh, _: 500 if rh.RH_KEY == 'Urllib' else 0)
  3781. return director
  3782. @functools.cached_property
  3783. def _request_director(self):
  3784. return self.build_request_director(_REQUEST_HANDLERS.values(), _RH_PREFERENCES)
  3785. def encode(self, s):
  3786. if isinstance(s, bytes):
  3787. return s # Already encoded
  3788. try:
  3789. return s.encode(self.get_encoding())
  3790. except UnicodeEncodeError as err:
  3791. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  3792. raise
  3793. def get_encoding(self):
  3794. encoding = self.params.get('encoding')
  3795. if encoding is None:
  3796. encoding = preferredencoding()
  3797. return encoding
  3798. def _write_info_json(self, label, ie_result, infofn, overwrite=None):
  3799. """ Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error """
  3800. if overwrite is None:
  3801. overwrite = self.params.get('overwrites', True)
  3802. if not self.params.get('writeinfojson'):
  3803. return False
  3804. elif not infofn:
  3805. self.write_debug(f'Skipping writing {label} infojson')
  3806. return False
  3807. elif not self._ensure_dir_exists(infofn):
  3808. return None
  3809. elif not overwrite and os.path.exists(infofn):
  3810. self.to_screen(f'[info] {label.title()} metadata is already present')
  3811. return 'exists'
  3812. self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
  3813. try:
  3814. write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
  3815. return True
  3816. except OSError:
  3817. self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
  3818. return None
  3819. def _write_description(self, label, ie_result, descfn):
  3820. """ Write description and returns True = written, False = skip, None = error """
  3821. if not self.params.get('writedescription'):
  3822. return False
  3823. elif not descfn:
  3824. self.write_debug(f'Skipping writing {label} description')
  3825. return False
  3826. elif not self._ensure_dir_exists(descfn):
  3827. return None
  3828. elif not self.params.get('overwrites', True) and os.path.exists(descfn):
  3829. self.to_screen(f'[info] {label.title()} description is already present')
  3830. elif ie_result.get('description') is None:
  3831. self.to_screen(f'[info] There\'s no {label} description to write')
  3832. return False
  3833. else:
  3834. try:
  3835. self.to_screen(f'[info] Writing {label} description to: {descfn}')
  3836. with open(descfn, 'w', encoding='utf-8') as descfile:
  3837. descfile.write(ie_result['description'])
  3838. except OSError:
  3839. self.report_error(f'Cannot write {label} description file {descfn}')
  3840. return None
  3841. return True
  3842. def _write_subtitles(self, info_dict, filename):
  3843. """ Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error"""
  3844. ret = []
  3845. subtitles = info_dict.get('requested_subtitles')
  3846. if not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
  3847. # subtitles download errors are already managed as troubles in relevant IE
  3848. # that way it will silently go on when used with unsupporting IE
  3849. return ret
  3850. elif not subtitles:
  3851. self.to_screen('[info] There are no subtitles for the requested languages')
  3852. return ret
  3853. sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
  3854. if not sub_filename_base:
  3855. self.to_screen('[info] Skipping writing video subtitles')
  3856. return ret
  3857. for sub_lang, sub_info in subtitles.items():
  3858. sub_format = sub_info['ext']
  3859. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  3860. sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
  3861. existing_sub = self.existing_file((sub_filename_final, sub_filename))
  3862. if existing_sub:
  3863. self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
  3864. sub_info['filepath'] = existing_sub
  3865. ret.append((existing_sub, sub_filename_final))
  3866. continue
  3867. self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
  3868. if sub_info.get('data') is not None:
  3869. try:
  3870. # Use newline='' to prevent conversion of newline characters
  3871. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  3872. with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
  3873. subfile.write(sub_info['data'])
  3874. sub_info['filepath'] = sub_filename
  3875. ret.append((sub_filename, sub_filename_final))
  3876. continue
  3877. except OSError:
  3878. self.report_error(f'Cannot write video subtitles file {sub_filename}')
  3879. return None
  3880. try:
  3881. sub_copy = sub_info.copy()
  3882. sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
  3883. self.dl(sub_filename, sub_copy, subtitle=True)
  3884. sub_info['filepath'] = sub_filename
  3885. ret.append((sub_filename, sub_filename_final))
  3886. except (DownloadError, ExtractorError, OSError, ValueError, *network_exceptions) as err:
  3887. msg = f'Unable to download video subtitles for {sub_lang!r}: {err}'
  3888. if self.params.get('ignoreerrors') is not True: # False or 'only_download'
  3889. if not self.params.get('ignoreerrors'):
  3890. self.report_error(msg)
  3891. raise DownloadError(msg)
  3892. self.report_warning(msg)
  3893. return ret
  3894. def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
  3895. """ Write thumbnails to file and return list of (thumb_filename, final_thumb_filename); or None if error """
  3896. write_all = self.params.get('write_all_thumbnails', False)
  3897. thumbnails, ret = [], []
  3898. if write_all or self.params.get('writethumbnail', False):
  3899. thumbnails = info_dict.get('thumbnails') or []
  3900. if not thumbnails:
  3901. self.to_screen(f'[info] There are no {label} thumbnails to download')
  3902. return ret
  3903. multiple = write_all and len(thumbnails) > 1
  3904. if thumb_filename_base is None:
  3905. thumb_filename_base = filename
  3906. if thumbnails and not thumb_filename_base:
  3907. self.write_debug(f'Skipping writing {label} thumbnail')
  3908. return ret
  3909. if thumbnails and not self._ensure_dir_exists(filename):
  3910. return None
  3911. for idx, t in list(enumerate(thumbnails))[::-1]:
  3912. thumb_ext = t.get('ext') or determine_ext(t['url'], 'jpg')
  3913. if multiple:
  3914. thumb_ext = f'{t["id"]}.{thumb_ext}'
  3915. thumb_display_id = f'{label} thumbnail {t["id"]}'
  3916. thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
  3917. thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
  3918. existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
  3919. if existing_thumb:
  3920. self.to_screen('[info] {} is already present'.format((
  3921. thumb_display_id if multiple else f'{label} thumbnail').capitalize()))
  3922. t['filepath'] = existing_thumb
  3923. ret.append((existing_thumb, thumb_filename_final))
  3924. else:
  3925. self.to_screen(f'[info] Downloading {thumb_display_id} ...')
  3926. try:
  3927. uf = self.urlopen(Request(t['url'], headers=t.get('http_headers', {})))
  3928. self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
  3929. with open(thumb_filename, 'wb') as thumbf:
  3930. shutil.copyfileobj(uf, thumbf)
  3931. ret.append((thumb_filename, thumb_filename_final))
  3932. t['filepath'] = thumb_filename
  3933. except network_exceptions as err:
  3934. if isinstance(err, HTTPError) and err.status == 404:
  3935. self.to_screen(f'[info] {thumb_display_id.title()} does not exist')
  3936. else:
  3937. self.report_warning(f'Unable to download {thumb_display_id}: {err}')
  3938. thumbnails.pop(idx)
  3939. if ret and not write_all:
  3940. break
  3941. return ret