YoutubeDL.py 181 KB

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