YoutubeDL.py 207 KB

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