YoutubeDL.py 191 KB

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