YoutubeDL.py 207 KB

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