YoutubeDL.py 183 KB

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