YoutubeDL.py 191 KB

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