common.py 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055
  1. import base64
  2. import collections
  3. import functools
  4. import getpass
  5. import http.client
  6. import http.cookiejar
  7. import http.cookies
  8. import inspect
  9. import itertools
  10. import json
  11. import math
  12. import netrc
  13. import os
  14. import random
  15. import re
  16. import subprocess
  17. import sys
  18. import time
  19. import types
  20. import urllib.parse
  21. import urllib.request
  22. import xml.etree.ElementTree
  23. from ..compat import (
  24. compat_etree_fromstring,
  25. compat_expanduser,
  26. urllib_req_to_req,
  27. )
  28. from ..cookies import LenientSimpleCookie
  29. from ..downloader.f4m import get_base_url, remove_encrypted_media
  30. from ..downloader.hls import HlsFD
  31. from ..globals import plugin_ies_overrides
  32. from ..networking import HEADRequest, Request
  33. from ..networking.exceptions import (
  34. HTTPError,
  35. IncompleteRead,
  36. TransportError,
  37. network_exceptions,
  38. )
  39. from ..networking.impersonate import ImpersonateTarget
  40. from ..utils import (
  41. IDENTITY,
  42. JSON_LD_RE,
  43. NO_DEFAULT,
  44. ExtractorError,
  45. FormatSorter,
  46. GeoRestrictedError,
  47. GeoUtils,
  48. ISO639Utils,
  49. LenientJSONDecoder,
  50. Popen,
  51. RegexNotFoundError,
  52. RetryManager,
  53. UnsupportedError,
  54. age_restricted,
  55. base_url,
  56. bug_reports_message,
  57. classproperty,
  58. clean_html,
  59. deprecation_warning,
  60. determine_ext,
  61. dict_get,
  62. encode_data_uri,
  63. extract_attributes,
  64. filter_dict,
  65. fix_xml_ampersands,
  66. float_or_none,
  67. format_field,
  68. int_or_none,
  69. join_nonempty,
  70. js_to_json,
  71. mimetype2ext,
  72. netrc_from_content,
  73. orderedSet,
  74. parse_bitrate,
  75. parse_codecs,
  76. parse_duration,
  77. parse_iso8601,
  78. parse_m3u8_attributes,
  79. parse_resolution,
  80. qualities,
  81. sanitize_url,
  82. smuggle_url,
  83. str_or_none,
  84. str_to_int,
  85. strip_or_none,
  86. traverse_obj,
  87. truncate_string,
  88. try_call,
  89. try_get,
  90. unescapeHTML,
  91. unified_strdate,
  92. unified_timestamp,
  93. url_basename,
  94. url_or_none,
  95. urlhandle_detect_ext,
  96. urljoin,
  97. variadic,
  98. xpath_element,
  99. xpath_text,
  100. xpath_with_ns,
  101. )
  102. from ..utils._utils import _request_dump_filename
  103. class InfoExtractor:
  104. """Information Extractor class.
  105. Information extractors are the classes that, given a URL, extract
  106. information about the video (or videos) the URL refers to. This
  107. information includes the real video URL, the video title, author and
  108. others. The information is stored in a dictionary which is then
  109. passed to the YoutubeDL. The YoutubeDL processes this
  110. information possibly downloading the video to the file system, among
  111. other possible outcomes.
  112. The type field determines the type of the result.
  113. By far the most common value (and the default if _type is missing) is
  114. "video", which indicates a single video.
  115. For a video, the dictionaries must include the following fields:
  116. id: Video identifier.
  117. title: Video title, unescaped. Set to an empty string if video has
  118. no title as opposed to "None" which signifies that the
  119. extractor failed to obtain a title
  120. Additionally, it must contain either a formats entry or a url one:
  121. formats: A list of dictionaries for each format available, ordered
  122. from worst to best quality.
  123. Potential fields:
  124. * url The mandatory URL representing the media:
  125. for plain file media - HTTP URL of this file,
  126. for RTMP - RTMP URL,
  127. for HLS - URL of the M3U8 media playlist,
  128. for HDS - URL of the F4M manifest,
  129. for DASH
  130. - HTTP URL to plain file media (in case of
  131. unfragmented media)
  132. - URL of the MPD manifest or base URL
  133. representing the media if MPD manifest
  134. is parsed from a string (in case of
  135. fragmented media)
  136. for MSS - URL of the ISM manifest.
  137. * request_data Data to send in POST request to the URL
  138. * manifest_url
  139. The URL of the manifest file in case of
  140. fragmented media:
  141. for HLS - URL of the M3U8 master playlist,
  142. for HDS - URL of the F4M manifest,
  143. for DASH - URL of the MPD manifest,
  144. for MSS - URL of the ISM manifest.
  145. * manifest_stream_number (For internal use only)
  146. The index of the stream in the manifest file
  147. * ext Will be calculated from URL if missing
  148. * format A human-readable description of the format
  149. ("mp4 container with h264/opus").
  150. Calculated from the format_id, width, height.
  151. and format_note fields if missing.
  152. * format_id A short description of the format
  153. ("mp4_h264_opus" or "19").
  154. Technically optional, but strongly recommended.
  155. * format_note Additional info about the format
  156. ("3D" or "DASH video")
  157. * width Width of the video, if known
  158. * height Height of the video, if known
  159. * aspect_ratio Aspect ratio of the video, if known
  160. Automatically calculated from width and height
  161. * resolution Textual description of width and height
  162. Automatically calculated from width and height
  163. * dynamic_range The dynamic range of the video. One of:
  164. "SDR" (None), "HDR10", "HDR10+, "HDR12", "HLG, "DV"
  165. * tbr Average bitrate of audio and video in kbps (1000 bits/sec)
  166. * abr Average audio bitrate in kbps (1000 bits/sec)
  167. * acodec Name of the audio codec in use
  168. * asr Audio sampling rate in Hertz
  169. * audio_channels Number of audio channels
  170. * vbr Average video bitrate in kbps (1000 bits/sec)
  171. * fps Frame rate
  172. * vcodec Name of the video codec in use
  173. * container Name of the container format
  174. * filesize The number of bytes, if known in advance
  175. * filesize_approx An estimate for the number of bytes
  176. * player_url SWF Player URL (used for rtmpdump).
  177. * protocol The protocol that will be used for the actual
  178. download, lower-case. One of "http", "https" or
  179. one of the protocols defined in downloader.PROTOCOL_MAP
  180. * fragment_base_url
  181. Base URL for fragments. Each fragment's path
  182. value (if present) will be relative to
  183. this URL.
  184. * fragments A list of fragments of a fragmented media.
  185. Each fragment entry must contain either an url
  186. or a path. If an url is present it should be
  187. considered by a client. Otherwise both path and
  188. fragment_base_url must be present. Here is
  189. the list of all potential fields:
  190. * "url" - fragment's URL
  191. * "path" - fragment's path relative to
  192. fragment_base_url
  193. * "duration" (optional, int or float)
  194. * "filesize" (optional, int)
  195. * hls_media_playlist_data
  196. The M3U8 media playlist data as a string.
  197. Only use if the data must be modified during extraction and
  198. the native HLS downloader should bypass requesting the URL.
  199. Does not apply if ffmpeg is used as external downloader
  200. * is_from_start Is a live format that can be downloaded
  201. from the start. Boolean
  202. * preference Order number of this format. If this field is
  203. present and not None, the formats get sorted
  204. by this field, regardless of all other values.
  205. -1 for default (order by other properties),
  206. -2 or smaller for less than default.
  207. < -1000 to hide the format (if there is
  208. another one which is strictly better)
  209. * language Language code, e.g. "de" or "en-US".
  210. * language_preference Is this in the language mentioned in
  211. the URL?
  212. 10 if it's what the URL is about,
  213. -1 for default (don't know),
  214. -10 otherwise, other values reserved for now.
  215. * quality Order number of the video quality of this
  216. format, irrespective of the file format.
  217. -1 for default (order by other properties),
  218. -2 or smaller for less than default.
  219. * source_preference Order number for this video source
  220. (quality takes higher priority)
  221. -1 for default (order by other properties),
  222. -2 or smaller for less than default.
  223. * http_headers A dictionary of additional HTTP headers
  224. to add to the request.
  225. * stretched_ratio If given and not 1, indicates that the
  226. video's pixels are not square.
  227. width : height ratio as float.
  228. * no_resume The server does not support resuming the
  229. (HTTP or RTMP) download. Boolean.
  230. * has_drm True if the format has DRM and cannot be downloaded.
  231. 'maybe' if the format may have DRM and has to be tested before download.
  232. * extra_param_to_segment_url A query string to append to each
  233. fragment's URL, or to update each existing query string
  234. with. If it is an HLS stream with an AES-128 decryption key,
  235. the query paramaters will be passed to the key URI as well,
  236. unless there is an `extra_param_to_key_url` given,
  237. or unless an external key URI is provided via `hls_aes`.
  238. Only applied by the native HLS/DASH downloaders.
  239. * extra_param_to_key_url A query string to append to the URL
  240. of the format's HLS AES-128 decryption key.
  241. Only applied by the native HLS downloader.
  242. * hls_aes A dictionary of HLS AES-128 decryption information
  243. used by the native HLS downloader to override the
  244. values in the media playlist when an '#EXT-X-KEY' tag
  245. is present in the playlist:
  246. * uri The URI from which the key will be downloaded
  247. * key The key (as hex) used to decrypt fragments.
  248. If `key` is given, any key URI will be ignored
  249. * iv The IV (as hex) used to decrypt fragments
  250. * downloader_options A dictionary of downloader options
  251. (For internal use only)
  252. * http_chunk_size Chunk size for HTTP downloads
  253. * ffmpeg_args Extra arguments for ffmpeg downloader (input)
  254. * ffmpeg_args_out Extra arguments for ffmpeg downloader (output)
  255. * is_dash_periods Whether the format is a result of merging
  256. multiple DASH periods.
  257. RTMP formats can also have the additional fields: page_url,
  258. app, play_path, tc_url, flash_version, rtmp_live, rtmp_conn,
  259. rtmp_protocol, rtmp_real_time
  260. url: Final video URL.
  261. ext: Video filename extension.
  262. format: The video format, defaults to ext (used for --get-format)
  263. player_url: SWF Player URL (used for rtmpdump).
  264. The following fields are optional:
  265. direct: True if a direct video file was given (must only be set by GenericIE)
  266. alt_title: A secondary title of the video.
  267. display_id: An alternative identifier for the video, not necessarily
  268. unique, but available before title. Typically, id is
  269. something like "4234987", title "Dancing naked mole rats",
  270. and display_id "dancing-naked-mole-rats"
  271. thumbnails: A list of dictionaries, with the following entries:
  272. * "id" (optional, string) - Thumbnail format ID
  273. * "url"
  274. * "ext" (optional, string) - actual image extension if not given in URL
  275. * "preference" (optional, int) - quality of the image
  276. * "width" (optional, int)
  277. * "height" (optional, int)
  278. * "resolution" (optional, string "{width}x{height}",
  279. deprecated)
  280. * "filesize" (optional, int)
  281. * "http_headers" (dict) - HTTP headers for the request
  282. thumbnail: Full URL to a video thumbnail image.
  283. description: Full video description.
  284. uploader: Full name of the video uploader.
  285. license: License name the video is licensed under.
  286. creators: List of creators of the video.
  287. timestamp: UNIX timestamp of the moment the video was uploaded
  288. upload_date: Video upload date in UTC (YYYYMMDD).
  289. If not explicitly set, calculated from timestamp
  290. release_timestamp: UNIX timestamp of the moment the video was released.
  291. If it is not clear whether to use timestamp or this, use the former
  292. release_date: The date (YYYYMMDD) when the video was released in UTC.
  293. If not explicitly set, calculated from release_timestamp
  294. release_year: Year (YYYY) as integer when the video or album was released.
  295. To be used if no exact release date is known.
  296. If not explicitly set, calculated from release_date.
  297. modified_timestamp: UNIX timestamp of the moment the video was last modified.
  298. modified_date: The date (YYYYMMDD) when the video was last modified in UTC.
  299. If not explicitly set, calculated from modified_timestamp
  300. uploader_id: Nickname or id of the video uploader.
  301. uploader_url: Full URL to a personal webpage of the video uploader.
  302. channel: Full name of the channel the video is uploaded on.
  303. Note that channel fields may or may not repeat uploader
  304. fields. This depends on a particular extractor.
  305. channel_id: Id of the channel.
  306. channel_url: Full URL to a channel webpage.
  307. channel_follower_count: Number of followers of the channel.
  308. channel_is_verified: Whether the channel is verified on the platform.
  309. location: Physical location where the video was filmed.
  310. subtitles: The available subtitles as a dictionary in the format
  311. {tag: subformats}. "tag" is usually a language code, and
  312. "subformats" is a list sorted from lower to higher
  313. preference, each element is a dictionary with the "ext"
  314. entry and one of:
  315. * "data": The subtitles file contents
  316. * "url": A URL pointing to the subtitles file
  317. It can optionally also have:
  318. * "name": Name or description of the subtitles
  319. * "http_headers": A dictionary of additional HTTP headers
  320. to add to the request.
  321. "ext" will be calculated from URL if missing
  322. automatic_captions: Like 'subtitles'; contains automatically generated
  323. captions instead of normal subtitles
  324. duration: Length of the video in seconds, as an integer or float.
  325. view_count: How many users have watched the video on the platform.
  326. concurrent_view_count: How many users are currently watching the video on the platform.
  327. like_count: Number of positive ratings of the video
  328. dislike_count: Number of negative ratings of the video
  329. repost_count: Number of reposts of the video
  330. average_rating: Average rating given by users, the scale used depends on the webpage
  331. comment_count: Number of comments on the video
  332. comments: A list of comments, each with one or more of the following
  333. properties (all but one of text or html optional):
  334. * "author" - human-readable name of the comment author
  335. * "author_id" - user ID of the comment author
  336. * "author_thumbnail" - The thumbnail of the comment author
  337. * "author_url" - The url to the comment author's page
  338. * "author_is_verified" - Whether the author is verified
  339. on the platform
  340. * "author_is_uploader" - Whether the comment is made by
  341. the video uploader
  342. * "id" - Comment ID
  343. * "html" - Comment as HTML
  344. * "text" - Plain text of the comment
  345. * "timestamp" - UNIX timestamp of comment
  346. * "parent" - ID of the comment this one is replying to.
  347. Set to "root" to indicate that this is a
  348. comment to the original video.
  349. * "like_count" - Number of positive ratings of the comment
  350. * "dislike_count" - Number of negative ratings of the comment
  351. * "is_favorited" - Whether the comment is marked as
  352. favorite by the video uploader
  353. * "is_pinned" - Whether the comment is pinned to
  354. the top of the comments
  355. age_limit: Age restriction for the video, as an integer (years)
  356. webpage_url: The URL to the video webpage, if given to yt-dlp it
  357. should allow to get the same result again. (It will be set
  358. by YoutubeDL if it's missing)
  359. categories: A list of categories that the video falls in, for example
  360. ["Sports", "Berlin"]
  361. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  362. cast: A list of the video cast
  363. is_live: True, False, or None (=unknown). Whether this video is a
  364. live stream that goes on instead of a fixed-length video.
  365. was_live: True, False, or None (=unknown). Whether this video was
  366. originally a live stream.
  367. live_status: None (=unknown), 'is_live', 'is_upcoming', 'was_live', 'not_live',
  368. or 'post_live' (was live, but VOD is not yet processed)
  369. If absent, automatically set from is_live, was_live
  370. start_time: Time in seconds where the reproduction should start, as
  371. specified in the URL.
  372. end_time: Time in seconds where the reproduction should end, as
  373. specified in the URL.
  374. chapters: A list of dictionaries, with the following entries:
  375. * "start_time" - The start time of the chapter in seconds
  376. * "end_time" - The end time of the chapter in seconds
  377. * "title" (optional, string)
  378. heatmap: A list of dictionaries, with the following entries:
  379. * "start_time" - The start time of the data point in seconds
  380. * "end_time" - The end time of the data point in seconds
  381. * "value" - The normalized value of the data point (float between 0 and 1)
  382. playable_in_embed: Whether this video is allowed to play in embedded
  383. players on other sites. Can be True (=always allowed),
  384. False (=never allowed), None (=unknown), or a string
  385. specifying the criteria for embedability; e.g. 'whitelist'
  386. availability: Under what condition the video is available. One of
  387. 'private', 'premium_only', 'subscriber_only', 'needs_auth',
  388. 'unlisted' or 'public'. Use 'InfoExtractor._availability'
  389. to set it
  390. media_type: The type of media as classified by the site, e.g. "episode", "clip", "trailer"
  391. _old_archive_ids: A list of old archive ids needed for backward compatibility
  392. _format_sort_fields: A list of fields to use for sorting formats
  393. __post_extractor: A function to be called just before the metadata is
  394. written to either disk, logger or console. The function
  395. must return a dict which will be added to the info_dict.
  396. This is usefull for additional information that is
  397. time-consuming to extract. Note that the fields thus
  398. extracted will not be available to output template and
  399. match_filter. So, only "comments" and "comment_count" are
  400. currently allowed to be extracted via this method.
  401. The following fields should only be used when the video belongs to some logical
  402. chapter or section:
  403. chapter: Name or title of the chapter the video belongs to.
  404. chapter_number: Number of the chapter the video belongs to, as an integer.
  405. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  406. The following fields should only be used when the video is an episode of some
  407. series, programme or podcast:
  408. series: Title of the series or programme the video episode belongs to.
  409. series_id: Id of the series or programme the video episode belongs to, as a unicode string.
  410. season: Title of the season the video episode belongs to.
  411. season_number: Number of the season the video episode belongs to, as an integer.
  412. season_id: Id of the season the video episode belongs to, as a unicode string.
  413. episode: Title of the video episode. Unlike mandatory video title field,
  414. this field should denote the exact title of the video episode
  415. without any kind of decoration.
  416. episode_number: Number of the video episode within a season, as an integer.
  417. episode_id: Id of the video episode, as a unicode string.
  418. The following fields should only be used when the media is a track or a part of
  419. a music album:
  420. track: Title of the track.
  421. track_number: Number of the track within an album or a disc, as an integer.
  422. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  423. as a unicode string.
  424. artists: List of artists of the track.
  425. composers: List of composers of the piece.
  426. genres: List of genres of the track.
  427. album: Title of the album the track belongs to.
  428. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  429. album_artists: List of all artists appeared on the album.
  430. E.g. ["Ash Borer", "Fell Voices"] or ["Various Artists"].
  431. Useful for splits and compilations.
  432. disc_number: Number of the disc or other physical medium the track belongs to,
  433. as an integer.
  434. The following fields should only be set for clips that should be cut from the original video:
  435. section_start: Start time of the section in seconds
  436. section_end: End time of the section in seconds
  437. The following fields should only be set for storyboards:
  438. rows: Number of rows in each storyboard fragment, as an integer
  439. columns: Number of columns in each storyboard fragment, as an integer
  440. The following fields are deprecated and should not be set by new code:
  441. composer: Use "composers" instead.
  442. Composer(s) of the piece, comma-separated.
  443. artist: Use "artists" instead.
  444. Artist(s) of the track, comma-separated.
  445. genre: Use "genres" instead.
  446. Genre(s) of the track, comma-separated.
  447. album_artist: Use "album_artists" instead.
  448. All artists appeared on the album, comma-separated.
  449. creator: Use "creators" instead.
  450. The creator of the video.
  451. Unless mentioned otherwise, the fields should be Unicode strings.
  452. Unless mentioned otherwise, None is equivalent to absence of information.
  453. _type "playlist" indicates multiple videos.
  454. There must be a key "entries", which is a list, an iterable, or a PagedList
  455. object, each element of which is a valid dictionary by this specification.
  456. Additionally, playlists can have "id", "title", and any other relevant
  457. attributes with the same semantics as videos (see above).
  458. It can also have the following optional fields:
  459. playlist_count: The total number of videos in a playlist. If not given,
  460. YoutubeDL tries to calculate it from "entries"
  461. _type "multi_video" indicates that there are multiple videos that
  462. form a single show, for examples multiple acts of an opera or TV episode.
  463. It must have an entries key like a playlist and contain all the keys
  464. required for a video at the same time.
  465. _type "url" indicates that the video must be extracted from another
  466. location, possibly by a different extractor. Its only required key is:
  467. "url" - the next URL to extract.
  468. The key "ie_key" can be set to the class name (minus the trailing "IE",
  469. e.g. "Youtube") if the extractor class is known in advance.
  470. Additionally, the dictionary may have any properties of the resolved entity
  471. known in advance, for example "title" if the title of the referred video is
  472. known ahead of time.
  473. _type "url_transparent" entities have the same specification as "url", but
  474. indicate that the given additional information is more precise than the one
  475. associated with the resolved URL.
  476. This is useful when a site employs a video service that hosts the video and
  477. its technical metadata, but that video service does not embed a useful
  478. title, description etc.
  479. Subclasses of this should also be added to the list of extractors and
  480. should define _VALID_URL as a regexp or a Sequence of regexps, and
  481. re-define the _real_extract() and (optionally) _real_initialize() methods.
  482. Subclasses may also override suitable() if necessary, but ensure the function
  483. signature is preserved and that this function imports everything it needs
  484. (except other extractors), so that lazy_extractors works correctly.
  485. Subclasses can define a list of _EMBED_REGEX, which will be searched for in
  486. the HTML of Generic webpages. It may also override _extract_embed_urls
  487. or _extract_from_webpage as necessary. While these are normally classmethods,
  488. _extract_from_webpage is allowed to be an instance method.
  489. _extract_from_webpage may raise self.StopExtraction to stop further
  490. processing of the webpage and obtain exclusive rights to it. This is useful
  491. when the extractor cannot reliably be matched using just the URL,
  492. e.g. invidious/peertube instances
  493. Embed-only extractors can be defined by setting _VALID_URL = False.
  494. To support username + password (or netrc) login, the extractor must define a
  495. _NETRC_MACHINE and re-define _perform_login(username, password) and
  496. (optionally) _initialize_pre_login() methods. The _perform_login method will
  497. be called between _initialize_pre_login and _real_initialize if credentials
  498. are passed by the user. In cases where it is necessary to have the login
  499. process as part of the extraction rather than initialization, _perform_login
  500. can be left undefined.
  501. _GEO_BYPASS attribute may be set to False in order to disable
  502. geo restriction bypass mechanisms for a particular extractor.
  503. Though it won't disable explicit geo restriction bypass based on
  504. country code provided with geo_bypass_country.
  505. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  506. countries for this extractor. One of these countries will be used by
  507. geo restriction bypass mechanism right away in order to bypass
  508. geo restriction, of course, if the mechanism is not disabled.
  509. _GEO_IP_BLOCKS attribute may contain a list of presumably geo unrestricted
  510. IP blocks in CIDR notation for this extractor. One of these IP blocks
  511. will be used by geo restriction bypass mechanism similarly
  512. to _GEO_COUNTRIES.
  513. The _ENABLED attribute should be set to False for IEs that
  514. are disabled by default and must be explicitly enabled.
  515. The _WORKING attribute should be set to False for broken IEs
  516. in order to warn the users and skip the tests.
  517. """
  518. _ready = False
  519. _downloader = None
  520. _x_forwarded_for_ip = None
  521. _GEO_BYPASS = True
  522. _GEO_COUNTRIES = None
  523. _GEO_IP_BLOCKS = None
  524. _WORKING = True
  525. _ENABLED = True
  526. _NETRC_MACHINE = None
  527. IE_DESC = None
  528. SEARCH_KEY = None
  529. _VALID_URL = None
  530. _EMBED_REGEX = []
  531. def _login_hint(self, method=NO_DEFAULT, netrc=None):
  532. password_hint = f'--username and --password, --netrc-cmd, or --netrc ({netrc or self._NETRC_MACHINE}) to provide account credentials'
  533. cookies_hint = 'See https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp for how to manually pass cookies'
  534. return {
  535. None: '',
  536. 'any': f'Use --cookies, --cookies-from-browser, {password_hint}. {cookies_hint}',
  537. 'password': f'Use {password_hint}',
  538. 'cookies': f'Use --cookies-from-browser or --cookies for the authentication. {cookies_hint}',
  539. 'session_cookies': f'Use --cookies for the authentication (--cookies-from-browser might not work). {cookies_hint}',
  540. }[method if method is not NO_DEFAULT else 'any' if self.supports_login() else 'cookies']
  541. def __init__(self, downloader=None):
  542. """Constructor. Receives an optional downloader (a YoutubeDL instance).
  543. If a downloader is not passed during initialization,
  544. it must be set using "set_downloader()" before "extract()" is called"""
  545. self._ready = False
  546. self._x_forwarded_for_ip = None
  547. self._printed_messages = set()
  548. self.set_downloader(downloader)
  549. @classmethod
  550. def _match_valid_url(cls, url):
  551. if cls._VALID_URL is False:
  552. return None
  553. # This does not use has/getattr intentionally - we want to know whether
  554. # we have cached the regexp for *this* class, whereas getattr would also
  555. # match the superclass
  556. if '_VALID_URL_RE' not in cls.__dict__:
  557. cls._VALID_URL_RE = tuple(map(re.compile, variadic(cls._VALID_URL)))
  558. return next(filter(None, (regex.match(url) for regex in cls._VALID_URL_RE)), None)
  559. @classmethod
  560. def suitable(cls, url):
  561. """Receives a URL and returns True if suitable for this IE."""
  562. # This function must import everything it needs (except other extractors),
  563. # so that lazy_extractors works correctly
  564. return cls._match_valid_url(url) is not None
  565. @classmethod
  566. def _match_id(cls, url):
  567. return cls._match_valid_url(url).group('id')
  568. @classmethod
  569. def get_temp_id(cls, url):
  570. try:
  571. return cls._match_id(url)
  572. except (IndexError, AttributeError):
  573. return None
  574. @classmethod
  575. def working(cls):
  576. """Getter method for _WORKING."""
  577. return cls._WORKING
  578. @classmethod
  579. def supports_login(cls):
  580. return bool(cls._NETRC_MACHINE)
  581. def initialize(self):
  582. """Initializes an instance (authentication, etc)."""
  583. self._printed_messages = set()
  584. self._initialize_geo_bypass({
  585. 'countries': self._GEO_COUNTRIES,
  586. 'ip_blocks': self._GEO_IP_BLOCKS,
  587. })
  588. if not self._ready:
  589. self._initialize_pre_login()
  590. if self.supports_login():
  591. username, password = self._get_login_info()
  592. if username:
  593. self._perform_login(username, password)
  594. elif self.get_param('username') and False not in (self.IE_DESC, self._NETRC_MACHINE):
  595. self.report_warning(f'Login with password is not supported for this website. {self._login_hint("cookies")}')
  596. self._real_initialize()
  597. self._ready = True
  598. def _initialize_geo_bypass(self, geo_bypass_context):
  599. """
  600. Initialize geo restriction bypass mechanism.
  601. This method is used to initialize geo bypass mechanism based on faking
  602. X-Forwarded-For HTTP header. A random country from provided country list
  603. is selected and a random IP belonging to this country is generated. This
  604. IP will be passed as X-Forwarded-For HTTP header in all subsequent
  605. HTTP requests.
  606. This method will be used for initial geo bypass mechanism initialization
  607. during the instance initialization with _GEO_COUNTRIES and
  608. _GEO_IP_BLOCKS.
  609. You may also manually call it from extractor's code if geo bypass
  610. information is not available beforehand (e.g. obtained during
  611. extraction) or due to some other reason. In this case you should pass
  612. this information in geo bypass context passed as first argument. It may
  613. contain following fields:
  614. countries: List of geo unrestricted countries (similar
  615. to _GEO_COUNTRIES)
  616. ip_blocks: List of geo unrestricted IP blocks in CIDR notation
  617. (similar to _GEO_IP_BLOCKS)
  618. """
  619. if not self._x_forwarded_for_ip:
  620. # Geo bypass mechanism is explicitly disabled by user
  621. if not self.get_param('geo_bypass', True):
  622. return
  623. if not geo_bypass_context:
  624. geo_bypass_context = {}
  625. # Backward compatibility: previously _initialize_geo_bypass
  626. # expected a list of countries, some 3rd party code may still use
  627. # it this way
  628. if isinstance(geo_bypass_context, (list, tuple)):
  629. geo_bypass_context = {
  630. 'countries': geo_bypass_context,
  631. }
  632. # The whole point of geo bypass mechanism is to fake IP
  633. # as X-Forwarded-For HTTP header based on some IP block or
  634. # country code.
  635. # Path 1: bypassing based on IP block in CIDR notation
  636. # Explicit IP block specified by user, use it right away
  637. # regardless of whether extractor is geo bypassable or not
  638. ip_block = self.get_param('geo_bypass_ip_block', None)
  639. # Otherwise use random IP block from geo bypass context but only
  640. # if extractor is known as geo bypassable
  641. if not ip_block:
  642. ip_blocks = geo_bypass_context.get('ip_blocks')
  643. if self._GEO_BYPASS and ip_blocks:
  644. ip_block = random.choice(ip_blocks)
  645. if ip_block:
  646. self._x_forwarded_for_ip = GeoUtils.random_ipv4(ip_block)
  647. self.write_debug(f'Using fake IP {self._x_forwarded_for_ip} as X-Forwarded-For')
  648. return
  649. # Path 2: bypassing based on country code
  650. # Explicit country code specified by user, use it right away
  651. # regardless of whether extractor is geo bypassable or not
  652. country = self.get_param('geo_bypass_country', None)
  653. # Otherwise use random country code from geo bypass context but
  654. # only if extractor is known as geo bypassable
  655. if not country:
  656. countries = geo_bypass_context.get('countries')
  657. if self._GEO_BYPASS and countries:
  658. country = random.choice(countries)
  659. if country:
  660. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country)
  661. self._downloader.write_debug(
  662. f'Using fake IP {self._x_forwarded_for_ip} ({country.upper()}) as X-Forwarded-For')
  663. def extract(self, url):
  664. """Extracts URL information and returns it in list of dicts."""
  665. try:
  666. for _ in range(2):
  667. try:
  668. self.initialize()
  669. self.to_screen('Extracting URL: %s' % (
  670. url if self.get_param('verbose') else truncate_string(url, 100, 20)))
  671. ie_result = self._real_extract(url)
  672. if ie_result is None:
  673. return None
  674. if self._x_forwarded_for_ip:
  675. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  676. subtitles = ie_result.get('subtitles') or {}
  677. if 'no-live-chat' in self.get_param('compat_opts'):
  678. for lang in ('live_chat', 'comments', 'danmaku'):
  679. subtitles.pop(lang, None)
  680. return ie_result
  681. except GeoRestrictedError as e:
  682. if self.__maybe_fake_ip_and_retry(e.countries):
  683. continue
  684. raise
  685. except UnsupportedError:
  686. raise
  687. except ExtractorError as e:
  688. e.video_id = e.video_id or self.get_temp_id(url)
  689. e.ie = e.ie or self.IE_NAME
  690. e.traceback = e.traceback or sys.exc_info()[2]
  691. raise
  692. except IncompleteRead as e:
  693. raise ExtractorError('A network error has occurred.', cause=e, expected=True, video_id=self.get_temp_id(url))
  694. except (KeyError, StopIteration) as e:
  695. raise ExtractorError('An extractor error has occurred.', cause=e, video_id=self.get_temp_id(url))
  696. def __maybe_fake_ip_and_retry(self, countries):
  697. if (not self.get_param('geo_bypass_country', None)
  698. and self._GEO_BYPASS
  699. and self.get_param('geo_bypass', True)
  700. and not self._x_forwarded_for_ip
  701. and countries):
  702. country_code = random.choice(countries)
  703. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  704. if self._x_forwarded_for_ip:
  705. self.report_warning(
  706. 'Video is geo restricted. Retrying extraction with fake IP '
  707. f'{self._x_forwarded_for_ip} ({country_code.upper()}) as X-Forwarded-For.')
  708. return True
  709. return False
  710. def set_downloader(self, downloader):
  711. """Sets a YoutubeDL instance as the downloader for this IE."""
  712. self._downloader = downloader
  713. @property
  714. def cache(self):
  715. return self._downloader.cache
  716. @property
  717. def cookiejar(self):
  718. return self._downloader.cookiejar
  719. def _initialize_pre_login(self):
  720. """ Initialization before login. Redefine in subclasses."""
  721. pass
  722. def _perform_login(self, username, password):
  723. """ Login with username and password. Redefine in subclasses."""
  724. pass
  725. def _real_initialize(self):
  726. """Real initialization process. Redefine in subclasses."""
  727. pass
  728. def _real_extract(self, url):
  729. """Real extraction process. Redefine in subclasses."""
  730. raise NotImplementedError('This method must be implemented by subclasses')
  731. @classmethod
  732. def ie_key(cls):
  733. """A string for getting the InfoExtractor with get_info_extractor"""
  734. return cls.__name__[:-2]
  735. @classproperty
  736. def IE_NAME(cls):
  737. return cls.__name__[:-2]
  738. @staticmethod
  739. def __can_accept_status_code(err, expected_status):
  740. assert isinstance(err, HTTPError)
  741. if expected_status is None:
  742. return False
  743. elif callable(expected_status):
  744. return expected_status(err.status) is True
  745. else:
  746. return err.status in variadic(expected_status)
  747. def _create_request(self, url_or_request, data=None, headers=None, query=None, extensions=None):
  748. if isinstance(url_or_request, urllib.request.Request):
  749. self._downloader.deprecation_warning(
  750. 'Passing a urllib.request.Request to _create_request() is deprecated. '
  751. 'Use yt_dlp.networking.common.Request instead.')
  752. url_or_request = urllib_req_to_req(url_or_request)
  753. elif not isinstance(url_or_request, Request):
  754. url_or_request = Request(url_or_request)
  755. url_or_request.update(data=data, headers=headers, query=query, extensions=extensions)
  756. return url_or_request
  757. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None,
  758. headers=None, query=None, expected_status=None, impersonate=None, require_impersonation=False):
  759. """
  760. Return the response handle.
  761. See _download_webpage docstring for arguments specification.
  762. """
  763. if not self._downloader._first_webpage_request:
  764. sleep_interval = self.get_param('sleep_interval_requests') or 0
  765. if sleep_interval > 0:
  766. self.to_screen(f'Sleeping {sleep_interval} seconds ...')
  767. time.sleep(sleep_interval)
  768. else:
  769. self._downloader._first_webpage_request = False
  770. if note is None:
  771. self.report_download_webpage(video_id)
  772. elif note is not False:
  773. if video_id is None:
  774. self.to_screen(str(note))
  775. else:
  776. self.to_screen(f'{video_id}: {note}')
  777. # Some sites check X-Forwarded-For HTTP header in order to figure out
  778. # the origin of the client behind proxy. This allows bypassing geo
  779. # restriction by faking this header's value to IP that belongs to some
  780. # geo unrestricted country. We will do so once we encounter any
  781. # geo restriction error.
  782. if self._x_forwarded_for_ip:
  783. headers = (headers or {}).copy()
  784. headers.setdefault('X-Forwarded-For', self._x_forwarded_for_ip)
  785. extensions = {}
  786. if impersonate in (True, ''):
  787. impersonate = ImpersonateTarget()
  788. requested_targets = [
  789. t if isinstance(t, ImpersonateTarget) else ImpersonateTarget.from_str(t)
  790. for t in variadic(impersonate)
  791. ] if impersonate else []
  792. available_target = next(filter(self._downloader._impersonate_target_available, requested_targets), None)
  793. if available_target:
  794. extensions['impersonate'] = available_target
  795. elif requested_targets:
  796. message = 'The extractor is attempting impersonation, but '
  797. message += (
  798. 'no impersonate target is available' if not str(impersonate)
  799. else f'none of these impersonate targets are available: "{", ".join(map(str, requested_targets))}"')
  800. info_msg = ('see https://github.com/yt-dlp/yt-dlp#impersonation '
  801. 'for information on installing the required dependencies')
  802. if require_impersonation:
  803. raise ExtractorError(f'{message}; {info_msg}', expected=True)
  804. self.report_warning(f'{message}; if you encounter errors, then {info_msg}', only_once=True)
  805. try:
  806. return self._downloader.urlopen(self._create_request(url_or_request, data, headers, query, extensions))
  807. except network_exceptions as err:
  808. if isinstance(err, HTTPError):
  809. if self.__can_accept_status_code(err, expected_status):
  810. return err.response
  811. if errnote is False:
  812. return False
  813. if errnote is None:
  814. errnote = 'Unable to download webpage'
  815. errmsg = f'{errnote}: {err}'
  816. if fatal:
  817. raise ExtractorError(errmsg, cause=err)
  818. else:
  819. self.report_warning(errmsg)
  820. return False
  821. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True,
  822. encoding=None, data=None, headers={}, query={}, expected_status=None,
  823. impersonate=None, require_impersonation=False):
  824. """
  825. Return a tuple (page content as string, URL handle).
  826. Arguments:
  827. url_or_request -- plain text URL as a string or
  828. a yt_dlp.networking.Request object
  829. video_id -- Video/playlist/item identifier (string)
  830. Keyword arguments:
  831. note -- note printed before downloading (string)
  832. errnote -- note printed in case of an error (string)
  833. fatal -- flag denoting whether error should be considered fatal,
  834. i.e. whether it should cause ExtractionError to be raised,
  835. otherwise a warning will be reported and extraction continued
  836. encoding -- encoding for a page content decoding, guessed automatically
  837. when not explicitly specified
  838. data -- POST data (bytes)
  839. headers -- HTTP headers (dict)
  840. query -- URL query (dict)
  841. expected_status -- allows to accept failed HTTP requests (non 2xx
  842. status code) by explicitly specifying a set of accepted status
  843. codes. Can be any of the following entities:
  844. - an integer type specifying an exact failed status code to
  845. accept
  846. - a list or a tuple of integer types specifying a list of
  847. failed status codes to accept
  848. - a callable accepting an actual failed status code and
  849. returning True if it should be accepted
  850. Note that this argument does not affect success status codes (2xx)
  851. which are always accepted.
  852. impersonate -- the impersonate target. Can be any of the following entities:
  853. - an instance of yt_dlp.networking.impersonate.ImpersonateTarget
  854. - a string in the format of CLIENT[:OS]
  855. - a list or a tuple of CLIENT[:OS] strings or ImpersonateTarget instances
  856. - a boolean value; True means any impersonate target is sufficient
  857. require_impersonation -- flag to toggle whether the request should raise an error
  858. if impersonation is not possible (bool, default: False)
  859. """
  860. # Strip hashes from the URL (#1038)
  861. if isinstance(url_or_request, str):
  862. url_or_request = url_or_request.partition('#')[0]
  863. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data,
  864. headers=headers, query=query, expected_status=expected_status,
  865. impersonate=impersonate, require_impersonation=require_impersonation)
  866. if urlh is False:
  867. assert not fatal
  868. return False
  869. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal,
  870. encoding=encoding, data=data)
  871. if content is False:
  872. assert not fatal
  873. return False
  874. return (content, urlh)
  875. @staticmethod
  876. def _guess_encoding_from_content(content_type, webpage_bytes):
  877. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  878. if m:
  879. encoding = m.group(1)
  880. else:
  881. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  882. webpage_bytes[:1024])
  883. if m:
  884. encoding = m.group(1).decode('ascii')
  885. elif webpage_bytes.startswith(b'\xff\xfe'):
  886. encoding = 'utf-16'
  887. else:
  888. encoding = 'utf-8'
  889. return encoding
  890. def __check_blocked(self, content):
  891. first_block = content[:512]
  892. if ('<title>Access to this site is blocked</title>' in content
  893. and 'Websense' in first_block):
  894. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  895. blocked_iframe = self._html_search_regex(
  896. r'<iframe src="([^"]+)"', content,
  897. 'Websense information URL', default=None)
  898. if blocked_iframe:
  899. msg += f' Visit {blocked_iframe} for more details'
  900. raise ExtractorError(msg, expected=True)
  901. if '<title>The URL you requested has been blocked</title>' in first_block:
  902. msg = (
  903. 'Access to this webpage has been blocked by Indian censorship. '
  904. 'Use a VPN or proxy server (with --proxy) to route around it.')
  905. block_msg = self._html_search_regex(
  906. r'</h1><p>(.*?)</p>',
  907. content, 'block message', default=None)
  908. if block_msg:
  909. msg += ' (Message: "{}")'.format(block_msg.replace('\n', ' '))
  910. raise ExtractorError(msg, expected=True)
  911. if ('<title>TTK :: Доступ к ресурсу ограничен</title>' in content
  912. and 'blocklist.rkn.gov.ru' in content):
  913. raise ExtractorError(
  914. 'Access to this webpage has been blocked by decision of the Russian government. '
  915. 'Visit http://blocklist.rkn.gov.ru/ for a block reason.',
  916. expected=True)
  917. def __decode_webpage(self, webpage_bytes, encoding, headers):
  918. if not encoding:
  919. encoding = self._guess_encoding_from_content(headers.get('Content-Type', ''), webpage_bytes)
  920. try:
  921. return webpage_bytes.decode(encoding, 'replace')
  922. except LookupError:
  923. return webpage_bytes.decode('utf-8', 'replace')
  924. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True,
  925. prefix=None, encoding=None, data=None):
  926. try:
  927. webpage_bytes = urlh.read()
  928. except TransportError as err:
  929. errmsg = f'{video_id}: Error reading response: {err.msg}'
  930. if fatal:
  931. raise ExtractorError(errmsg, cause=err)
  932. self.report_warning(errmsg)
  933. return False
  934. if prefix is not None:
  935. webpage_bytes = prefix + webpage_bytes
  936. if self.get_param('dump_intermediate_pages', False):
  937. self.to_screen('Dumping request to ' + urlh.url)
  938. dump = base64.b64encode(webpage_bytes).decode('ascii')
  939. self._downloader.to_screen(dump)
  940. if self.get_param('write_pages'):
  941. if isinstance(url_or_request, Request):
  942. data = self._create_request(url_or_request, data).data
  943. filename = _request_dump_filename(
  944. urlh.url, video_id, data,
  945. trim_length=self.get_param('trim_file_name'))
  946. self.to_screen(f'Saving request to {filename}')
  947. with open(filename, 'wb') as outf:
  948. outf.write(webpage_bytes)
  949. content = self.__decode_webpage(webpage_bytes, encoding, urlh.headers)
  950. self.__check_blocked(content)
  951. return content
  952. def __print_error(self, errnote, fatal, video_id, err):
  953. if fatal:
  954. raise ExtractorError(f'{video_id}: {errnote}', cause=err)
  955. elif errnote:
  956. self.report_warning(f'{video_id}: {errnote}: {err}')
  957. def _parse_xml(self, xml_string, video_id, transform_source=None, fatal=True, errnote=None):
  958. if transform_source:
  959. xml_string = transform_source(xml_string)
  960. try:
  961. return compat_etree_fromstring(xml_string.encode())
  962. except xml.etree.ElementTree.ParseError as ve:
  963. self.__print_error('Failed to parse XML' if errnote is None else errnote, fatal, video_id, ve)
  964. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True, errnote=None, **parser_kwargs):
  965. try:
  966. return json.loads(
  967. json_string, cls=LenientJSONDecoder, strict=False, transform_source=transform_source, **parser_kwargs)
  968. except ValueError as ve:
  969. self.__print_error('Failed to parse JSON' if errnote is None else errnote, fatal, video_id, ve)
  970. def _parse_socket_response_as_json(self, data, *args, **kwargs):
  971. return self._parse_json(data[data.find('{'):data.rfind('}') + 1], *args, **kwargs)
  972. def __create_download_methods(name, parser, note, errnote, return_value):
  973. def parse(ie, content, *args, errnote=errnote, **kwargs):
  974. if parser is None:
  975. return content
  976. if errnote is False:
  977. kwargs['errnote'] = errnote
  978. # parser is fetched by name so subclasses can override it
  979. return getattr(ie, parser)(content, *args, **kwargs)
  980. def download_handle(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  981. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  982. impersonate=None, require_impersonation=False):
  983. res = self._download_webpage_handle(
  984. url_or_request, video_id, note=note, errnote=errnote, fatal=fatal, encoding=encoding,
  985. data=data, headers=headers, query=query, expected_status=expected_status,
  986. impersonate=impersonate, require_impersonation=require_impersonation)
  987. if res is False:
  988. return res
  989. content, urlh = res
  990. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote), urlh
  991. def download_content(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  992. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  993. impersonate=None, require_impersonation=False):
  994. if self.get_param('load_pages'):
  995. url_or_request = self._create_request(url_or_request, data, headers, query)
  996. filename = _request_dump_filename(
  997. url_or_request.url, video_id, url_or_request.data,
  998. trim_length=self.get_param('trim_file_name'))
  999. self.to_screen(f'Loading request from {filename}')
  1000. try:
  1001. with open(filename, 'rb') as dumpf:
  1002. webpage_bytes = dumpf.read()
  1003. except OSError as e:
  1004. self.report_warning(f'Unable to load request from disk: {e}')
  1005. else:
  1006. content = self.__decode_webpage(webpage_bytes, encoding, url_or_request.headers)
  1007. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote)
  1008. kwargs = {
  1009. 'note': note,
  1010. 'errnote': errnote,
  1011. 'transform_source': transform_source,
  1012. 'fatal': fatal,
  1013. 'encoding': encoding,
  1014. 'data': data,
  1015. 'headers': headers,
  1016. 'query': query,
  1017. 'expected_status': expected_status,
  1018. 'impersonate': impersonate,
  1019. 'require_impersonation': require_impersonation,
  1020. }
  1021. if parser is None:
  1022. kwargs.pop('transform_source')
  1023. # The method is fetched by name so subclasses can override _download_..._handle
  1024. res = getattr(self, download_handle.__name__)(url_or_request, video_id, **kwargs)
  1025. return res if res is False else res[0]
  1026. def impersonate(func, name, return_value):
  1027. func.__name__, func.__qualname__ = name, f'InfoExtractor.{name}'
  1028. func.__doc__ = f'''
  1029. @param transform_source Apply this transformation before parsing
  1030. @returns {return_value}
  1031. See _download_webpage_handle docstring for other arguments specification
  1032. '''
  1033. impersonate(download_handle, f'_download_{name}_handle', f'({return_value}, URL handle)')
  1034. impersonate(download_content, f'_download_{name}', f'{return_value}')
  1035. return download_handle, download_content
  1036. _download_xml_handle, _download_xml = __create_download_methods(
  1037. 'xml', '_parse_xml', 'Downloading XML', 'Unable to download XML', 'xml as an xml.etree.ElementTree.Element')
  1038. _download_json_handle, _download_json = __create_download_methods(
  1039. 'json', '_parse_json', 'Downloading JSON metadata', 'Unable to download JSON metadata', 'JSON object as a dict')
  1040. _download_socket_json_handle, _download_socket_json = __create_download_methods(
  1041. 'socket_json', '_parse_socket_response_as_json', 'Polling socket', 'Unable to poll socket', 'JSON object as a dict')
  1042. __download_webpage = __create_download_methods('webpage', None, None, None, 'data of the page as a string')[1]
  1043. def _download_webpage(
  1044. self, url_or_request, video_id, note=None, errnote=None,
  1045. fatal=True, tries=1, timeout=NO_DEFAULT, *args, **kwargs):
  1046. """
  1047. Return the data of the page as a string.
  1048. Keyword arguments:
  1049. tries -- number of tries
  1050. timeout -- sleep interval between tries
  1051. See _download_webpage_handle docstring for other arguments specification.
  1052. """
  1053. R''' # NB: These are unused; should they be deprecated?
  1054. if tries != 1:
  1055. self._downloader.deprecation_warning('tries argument is deprecated in InfoExtractor._download_webpage')
  1056. if timeout is NO_DEFAULT:
  1057. timeout = 5
  1058. else:
  1059. self._downloader.deprecation_warning('timeout argument is deprecated in InfoExtractor._download_webpage')
  1060. '''
  1061. try_count = 0
  1062. while True:
  1063. try:
  1064. return self.__download_webpage(url_or_request, video_id, note, errnote, None, fatal, *args, **kwargs)
  1065. except IncompleteRead as e:
  1066. try_count += 1
  1067. if try_count >= tries:
  1068. raise e
  1069. self._sleep(timeout, video_id)
  1070. def report_warning(self, msg, video_id=None, *args, only_once=False, **kwargs):
  1071. idstr = format_field(video_id, None, '%s: ')
  1072. msg = f'[{self.IE_NAME}] {idstr}{msg}'
  1073. if only_once:
  1074. if f'WARNING: {msg}' in self._printed_messages:
  1075. return
  1076. self._printed_messages.add(f'WARNING: {msg}')
  1077. self._downloader.report_warning(msg, *args, **kwargs)
  1078. def to_screen(self, msg, *args, **kwargs):
  1079. """Print msg to screen, prefixing it with '[ie_name]'"""
  1080. self._downloader.to_screen(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1081. def write_debug(self, msg, *args, **kwargs):
  1082. self._downloader.write_debug(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1083. def get_param(self, name, default=None, *args, **kwargs):
  1084. if self._downloader:
  1085. return self._downloader.params.get(name, default, *args, **kwargs)
  1086. return default
  1087. def report_drm(self, video_id, partial=NO_DEFAULT):
  1088. if partial is not NO_DEFAULT:
  1089. self._downloader.deprecation_warning('InfoExtractor.report_drm no longer accepts the argument partial')
  1090. self.raise_no_formats('This video is DRM protected', expected=True, video_id=video_id)
  1091. def report_extraction(self, id_or_name):
  1092. """Report information extraction."""
  1093. self.to_screen(f'{id_or_name}: Extracting information')
  1094. def report_download_webpage(self, video_id):
  1095. """Report webpage download."""
  1096. self.to_screen(f'{video_id}: Downloading webpage')
  1097. def report_age_confirmation(self):
  1098. """Report attempt to confirm age."""
  1099. self.to_screen('Confirming age')
  1100. def report_login(self):
  1101. """Report attempt to log in."""
  1102. self.to_screen('Logging in')
  1103. def raise_login_required(
  1104. self, msg='This video is only available for registered users',
  1105. metadata_available=False, method=NO_DEFAULT):
  1106. if metadata_available and (
  1107. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1108. self.report_warning(msg)
  1109. return
  1110. msg += format_field(self._login_hint(method), None, '. %s')
  1111. raise ExtractorError(msg, expected=True)
  1112. def raise_geo_restricted(
  1113. self, msg='This video is not available from your location due to geo restriction',
  1114. countries=None, metadata_available=False):
  1115. if metadata_available and (
  1116. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1117. self.report_warning(msg)
  1118. else:
  1119. raise GeoRestrictedError(msg, countries=countries)
  1120. def raise_no_formats(self, msg, expected=False, video_id=None):
  1121. if expected and (
  1122. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1123. self.report_warning(msg, video_id)
  1124. elif isinstance(msg, ExtractorError):
  1125. raise msg
  1126. else:
  1127. raise ExtractorError(msg, expected=expected, video_id=video_id)
  1128. # Methods for following #608
  1129. @staticmethod
  1130. def url_result(url, ie=None, video_id=None, video_title=None, *, url_transparent=False, **kwargs):
  1131. """Returns a URL that points to a page that should be processed"""
  1132. if ie is not None:
  1133. kwargs['ie_key'] = ie if isinstance(ie, str) else ie.ie_key()
  1134. if video_id is not None:
  1135. kwargs['id'] = video_id
  1136. if video_title is not None:
  1137. kwargs['title'] = video_title
  1138. return {
  1139. **kwargs,
  1140. '_type': 'url_transparent' if url_transparent else 'url',
  1141. 'url': url,
  1142. }
  1143. @classmethod
  1144. def playlist_from_matches(cls, matches, playlist_id=None, playlist_title=None,
  1145. getter=IDENTITY, ie=None, video_kwargs=None, **kwargs):
  1146. return cls.playlist_result(
  1147. (cls.url_result(m, ie, **(video_kwargs or {})) for m in orderedSet(map(getter, matches), lazy=True)),
  1148. playlist_id, playlist_title, **kwargs)
  1149. @staticmethod
  1150. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None, *, multi_video=False, **kwargs):
  1151. """Returns a playlist"""
  1152. if playlist_id:
  1153. kwargs['id'] = playlist_id
  1154. if playlist_title:
  1155. kwargs['title'] = playlist_title
  1156. if playlist_description is not None:
  1157. kwargs['description'] = playlist_description
  1158. return {
  1159. **kwargs,
  1160. '_type': 'multi_video' if multi_video else 'playlist',
  1161. 'entries': entries,
  1162. }
  1163. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1164. """
  1165. Perform a regex search on the given string, using a single or a list of
  1166. patterns returning the first matching group.
  1167. In case of failure return a default value or raise a WARNING or a
  1168. RegexNotFoundError, depending on fatal, specifying the field name.
  1169. """
  1170. if string is None:
  1171. mobj = None
  1172. elif isinstance(pattern, (str, re.Pattern)):
  1173. mobj = re.search(pattern, string, flags)
  1174. else:
  1175. for p in pattern:
  1176. mobj = re.search(p, string, flags)
  1177. if mobj:
  1178. break
  1179. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1180. if mobj:
  1181. if group is None:
  1182. # return the first matching group
  1183. return next(g for g in mobj.groups() if g is not None)
  1184. elif isinstance(group, (list, tuple)):
  1185. return tuple(mobj.group(g) for g in group)
  1186. else:
  1187. return mobj.group(group)
  1188. elif default is not NO_DEFAULT:
  1189. return default
  1190. elif fatal:
  1191. raise RegexNotFoundError(f'Unable to extract {_name}')
  1192. else:
  1193. self.report_warning(f'unable to extract {_name}' + bug_reports_message())
  1194. return None
  1195. def _search_json(self, start_pattern, string, name, video_id, *, end_pattern='',
  1196. contains_pattern=r'{(?s:.+)}', fatal=True, default=NO_DEFAULT, **kwargs):
  1197. """Searches string for the JSON object specified by start_pattern"""
  1198. # NB: end_pattern is only used to reduce the size of the initial match
  1199. if default is NO_DEFAULT:
  1200. default, has_default = {}, False
  1201. else:
  1202. fatal, has_default = False, True
  1203. json_string = self._search_regex(
  1204. rf'(?:{start_pattern})\s*(?P<json>{contains_pattern})\s*(?:{end_pattern})',
  1205. string, name, group='json', fatal=fatal, default=None if has_default else NO_DEFAULT)
  1206. if not json_string:
  1207. return default
  1208. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1209. try:
  1210. return self._parse_json(json_string, video_id, ignore_extra=True, **kwargs)
  1211. except ExtractorError as e:
  1212. if fatal:
  1213. raise ExtractorError(
  1214. f'Unable to extract {_name} - Failed to parse JSON', cause=e.cause, video_id=video_id)
  1215. elif not has_default:
  1216. self.report_warning(
  1217. f'Unable to extract {_name} - Failed to parse JSON: {e}', video_id=video_id)
  1218. return default
  1219. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1220. """
  1221. Like _search_regex, but strips HTML tags and unescapes entities.
  1222. """
  1223. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  1224. if isinstance(res, tuple):
  1225. return tuple(map(clean_html, res))
  1226. return clean_html(res)
  1227. def _get_netrc_login_info(self, netrc_machine=None):
  1228. netrc_machine = netrc_machine or self._NETRC_MACHINE
  1229. cmd = self.get_param('netrc_cmd')
  1230. if cmd:
  1231. cmd = cmd.replace('{}', netrc_machine)
  1232. self.to_screen(f'Executing command: {cmd}')
  1233. stdout, _, ret = Popen.run(cmd, text=True, shell=True, stdout=subprocess.PIPE)
  1234. if ret != 0:
  1235. raise OSError(f'Command returned error code {ret}')
  1236. info = netrc_from_content(stdout).authenticators(netrc_machine)
  1237. elif self.get_param('usenetrc', False):
  1238. netrc_file = compat_expanduser(self.get_param('netrc_location') or '~')
  1239. if os.path.isdir(netrc_file):
  1240. netrc_file = os.path.join(netrc_file, '.netrc')
  1241. info = netrc.netrc(netrc_file).authenticators(netrc_machine)
  1242. else:
  1243. return None, None
  1244. if not info:
  1245. self.to_screen(f'No authenticators for {netrc_machine}')
  1246. return None, None
  1247. self.write_debug(f'Using netrc for {netrc_machine} authentication')
  1248. # compat: <=py3.10: netrc cannot parse tokens as empty strings, will return `""` instead
  1249. # Ref: https://github.com/yt-dlp/yt-dlp/issues/11413
  1250. # https://github.com/python/cpython/commit/15409c720be0503131713e3d3abc1acd0da07378
  1251. if sys.version_info < (3, 11):
  1252. return tuple(x if x != '""' else '' for x in info[::2])
  1253. return info[0], info[2]
  1254. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  1255. """
  1256. Get the login info as (username, password)
  1257. First look for the manually specified credentials using username_option
  1258. and password_option as keys in params dictionary. If no such credentials
  1259. are available try the netrc_cmd if it is defined or look in the
  1260. netrc file using the netrc_machine or _NETRC_MACHINE value.
  1261. If there's no info available, return (None, None)
  1262. """
  1263. username = self.get_param(username_option)
  1264. if username is not None:
  1265. password = self.get_param(password_option)
  1266. else:
  1267. try:
  1268. username, password = self._get_netrc_login_info(netrc_machine)
  1269. except (OSError, netrc.NetrcParseError) as err:
  1270. self.report_warning(f'Failed to parse .netrc: {err}')
  1271. return None, None
  1272. return username, password
  1273. def _get_tfa_info(self, note='two-factor verification code'):
  1274. """
  1275. Get the two-factor authentication info
  1276. TODO - asking the user will be required for sms/phone verify
  1277. currently just uses the command line option
  1278. If there's no info available, return None
  1279. """
  1280. tfa = self.get_param('twofactor')
  1281. if tfa is not None:
  1282. return tfa
  1283. return getpass.getpass(f'Type {note} and press [Return]: ')
  1284. # Helper functions for extracting OpenGraph info
  1285. @staticmethod
  1286. def _og_regexes(prop):
  1287. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?)(?=\s|/?>))'
  1288. property_re = r'(?:name|property)=(?:\'og{sep}{prop}\'|"og{sep}{prop}"|\s*og{sep}{prop}\b)'.format(
  1289. prop=re.escape(prop), sep='(?:&#x3A;|[:-])')
  1290. template = r'<meta[^>]+?%s[^>]+?%s'
  1291. return [
  1292. template % (property_re, content_re),
  1293. template % (content_re, property_re),
  1294. ]
  1295. @staticmethod
  1296. def _meta_regex(prop):
  1297. return rf'''(?isx)<meta
  1298. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?){re.escape(prop)}\1)
  1299. [^>]+?content=(["\'])(?P<content>.*?)\2'''
  1300. def _og_search_property(self, prop, html, name=None, **kargs):
  1301. prop = variadic(prop)
  1302. if name is None:
  1303. name = f'OpenGraph {prop[0]}'
  1304. og_regexes = []
  1305. for p in prop:
  1306. og_regexes.extend(self._og_regexes(p))
  1307. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  1308. if escaped is None:
  1309. return None
  1310. return unescapeHTML(escaped)
  1311. def _og_search_thumbnail(self, html, **kargs):
  1312. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  1313. def _og_search_description(self, html, **kargs):
  1314. return self._og_search_property('description', html, fatal=False, **kargs)
  1315. def _og_search_title(self, html, *, fatal=False, **kargs):
  1316. return self._og_search_property('title', html, fatal=fatal, **kargs)
  1317. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  1318. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  1319. if secure:
  1320. regexes = self._og_regexes('video:secure_url') + regexes
  1321. return self._html_search_regex(regexes, html, name, **kargs)
  1322. def _og_search_url(self, html, **kargs):
  1323. return self._og_search_property('url', html, **kargs)
  1324. def _html_extract_title(self, html, name='title', *, fatal=False, **kwargs):
  1325. return self._html_search_regex(r'(?s)<title\b[^>]*>([^<]+)</title>', html, name, fatal=fatal, **kwargs)
  1326. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  1327. name = variadic(name)
  1328. if display_name is None:
  1329. display_name = name[0]
  1330. return self._html_search_regex(
  1331. [self._meta_regex(n) for n in name],
  1332. html, display_name, fatal=fatal, group='content', **kwargs)
  1333. def _dc_search_uploader(self, html):
  1334. return self._html_search_meta('dc.creator', html, 'uploader')
  1335. @staticmethod
  1336. def _rta_search(html):
  1337. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  1338. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  1339. r' content="RTA-5042-1996-1400-1577-RTA"',
  1340. html):
  1341. return 18
  1342. # And then there are the jokers who advertise that they use RTA, but actually don't.
  1343. AGE_LIMIT_MARKERS = [
  1344. r'Proudly Labeled <a href="http://www\.rtalabel\.org/" title="Restricted to Adults">RTA</a>',
  1345. r'>[^<]*you acknowledge you are at least (\d+) years old',
  1346. r'>\s*(?:18\s+U(?:\.S\.C\.|SC)\s+)?(?:§+\s*)?2257\b',
  1347. ]
  1348. age_limit = 0
  1349. for marker in AGE_LIMIT_MARKERS:
  1350. mobj = re.search(marker, html)
  1351. if mobj:
  1352. age_limit = max(age_limit, int(traverse_obj(mobj, 1, default=18)))
  1353. return age_limit
  1354. def _media_rating_search(self, html):
  1355. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  1356. rating = self._html_search_meta('rating', html)
  1357. if not rating:
  1358. return None
  1359. RATING_TABLE = {
  1360. 'safe for kids': 0,
  1361. 'general': 8,
  1362. '14 years': 14,
  1363. 'mature': 17,
  1364. 'restricted': 19,
  1365. }
  1366. return RATING_TABLE.get(rating.lower())
  1367. def _family_friendly_search(self, html):
  1368. # See http://schema.org/VideoObject
  1369. family_friendly = self._html_search_meta(
  1370. 'isFamilyFriendly', html, default=None)
  1371. if not family_friendly:
  1372. return None
  1373. RATING_TABLE = {
  1374. '1': 0,
  1375. 'true': 0,
  1376. '0': 18,
  1377. 'false': 18,
  1378. }
  1379. return RATING_TABLE.get(family_friendly.lower())
  1380. def _twitter_search_player(self, html):
  1381. return self._html_search_meta('twitter:player', html,
  1382. 'twitter card player')
  1383. def _yield_json_ld(self, html, video_id, *, fatal=True, default=NO_DEFAULT):
  1384. """Yield all json ld objects in the html"""
  1385. if default is not NO_DEFAULT:
  1386. fatal = False
  1387. for mobj in re.finditer(JSON_LD_RE, html):
  1388. json_ld_item = self._parse_json(
  1389. mobj.group('json_ld'), video_id, fatal=fatal,
  1390. errnote=False if default is not NO_DEFAULT else None)
  1391. for json_ld in variadic(json_ld_item):
  1392. if isinstance(json_ld, dict):
  1393. yield json_ld
  1394. def _search_json_ld(self, html, video_id, expected_type=None, *, fatal=True, default=NO_DEFAULT):
  1395. """Search for a video in any json ld in the html"""
  1396. if default is not NO_DEFAULT:
  1397. fatal = False
  1398. info = self._json_ld(
  1399. list(self._yield_json_ld(html, video_id, fatal=fatal, default=default)),
  1400. video_id, fatal=fatal, expected_type=expected_type)
  1401. if info:
  1402. return info
  1403. if default is not NO_DEFAULT:
  1404. return default
  1405. elif fatal:
  1406. raise RegexNotFoundError('Unable to extract JSON-LD')
  1407. else:
  1408. self.report_warning(f'unable to extract JSON-LD {bug_reports_message()}')
  1409. return {}
  1410. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  1411. if isinstance(json_ld, str):
  1412. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  1413. if not json_ld:
  1414. return {}
  1415. info = {}
  1416. INTERACTION_TYPE_MAP = {
  1417. 'CommentAction': 'comment',
  1418. 'AgreeAction': 'like',
  1419. 'DisagreeAction': 'dislike',
  1420. 'LikeAction': 'like',
  1421. 'DislikeAction': 'dislike',
  1422. 'ListenAction': 'view',
  1423. 'WatchAction': 'view',
  1424. 'ViewAction': 'view',
  1425. }
  1426. def is_type(e, *expected_types):
  1427. type_ = variadic(traverse_obj(e, '@type'))
  1428. return any(x in type_ for x in expected_types)
  1429. def extract_interaction_type(e):
  1430. interaction_type = e.get('interactionType')
  1431. if isinstance(interaction_type, dict):
  1432. interaction_type = interaction_type.get('@type')
  1433. return str_or_none(interaction_type)
  1434. def extract_interaction_statistic(e):
  1435. interaction_statistic = e.get('interactionStatistic')
  1436. if isinstance(interaction_statistic, dict):
  1437. interaction_statistic = [interaction_statistic]
  1438. if not isinstance(interaction_statistic, list):
  1439. return
  1440. for is_e in interaction_statistic:
  1441. if not is_type(is_e, 'InteractionCounter'):
  1442. continue
  1443. interaction_type = extract_interaction_type(is_e)
  1444. if not interaction_type:
  1445. continue
  1446. # For interaction count some sites provide string instead of
  1447. # an integer (as per spec) with non digit characters (e.g. ",")
  1448. # so extracting count with more relaxed str_to_int
  1449. interaction_count = str_to_int(is_e.get('userInteractionCount'))
  1450. if interaction_count is None:
  1451. continue
  1452. count_kind = INTERACTION_TYPE_MAP.get(interaction_type.split('/')[-1])
  1453. if not count_kind:
  1454. continue
  1455. count_key = f'{count_kind}_count'
  1456. if info.get(count_key) is not None:
  1457. continue
  1458. info[count_key] = interaction_count
  1459. def extract_chapter_information(e):
  1460. chapters = [{
  1461. 'title': part.get('name'),
  1462. 'start_time': part.get('startOffset'),
  1463. 'end_time': part.get('endOffset'),
  1464. } for part in variadic(e.get('hasPart') or []) if part.get('@type') == 'Clip']
  1465. for idx, (last_c, current_c, next_c) in enumerate(zip(
  1466. [{'end_time': 0}, *chapters], chapters, chapters[1:])):
  1467. current_c['end_time'] = current_c['end_time'] or next_c['start_time']
  1468. current_c['start_time'] = current_c['start_time'] or last_c['end_time']
  1469. if None in current_c.values():
  1470. self.report_warning(f'Chapter {idx} contains broken data. Not extracting chapters')
  1471. return
  1472. if chapters:
  1473. chapters[-1]['end_time'] = chapters[-1]['end_time'] or info['duration']
  1474. info['chapters'] = chapters
  1475. def extract_video_object(e):
  1476. author = e.get('author')
  1477. info.update({
  1478. 'url': url_or_none(e.get('contentUrl')),
  1479. 'ext': mimetype2ext(e.get('encodingFormat')),
  1480. 'title': unescapeHTML(e.get('name')),
  1481. 'description': unescapeHTML(e.get('description')),
  1482. 'thumbnails': [{'url': unescapeHTML(url)}
  1483. for url in variadic(traverse_obj(e, 'thumbnailUrl', 'thumbnailURL'))
  1484. if url_or_none(url)],
  1485. 'duration': parse_duration(e.get('duration')),
  1486. 'timestamp': unified_timestamp(e.get('uploadDate')),
  1487. # author can be an instance of 'Organization' or 'Person' types.
  1488. # both types can have 'name' property(inherited from 'Thing' type). [1]
  1489. # however some websites are using 'Text' type instead.
  1490. # 1. https://schema.org/VideoObject
  1491. 'uploader': author.get('name') if isinstance(author, dict) else author if isinstance(author, str) else None,
  1492. 'artist': traverse_obj(e, ('byArtist', 'name'), expected_type=str),
  1493. 'filesize': int_or_none(float_or_none(e.get('contentSize'))),
  1494. 'tbr': int_or_none(e.get('bitrate')),
  1495. 'width': int_or_none(e.get('width')),
  1496. 'height': int_or_none(e.get('height')),
  1497. 'view_count': int_or_none(e.get('interactionCount')),
  1498. 'tags': try_call(lambda: e.get('keywords').split(',')),
  1499. })
  1500. if is_type(e, 'AudioObject'):
  1501. info.update({
  1502. 'vcodec': 'none',
  1503. 'abr': int_or_none(e.get('bitrate')),
  1504. })
  1505. extract_interaction_statistic(e)
  1506. extract_chapter_information(e)
  1507. def traverse_json_ld(json_ld, at_top_level=True):
  1508. for e in variadic(json_ld):
  1509. if not isinstance(e, dict):
  1510. continue
  1511. if at_top_level and '@context' not in e:
  1512. continue
  1513. if at_top_level and set(e.keys()) == {'@context', '@graph'}:
  1514. traverse_json_ld(e['@graph'], at_top_level=False)
  1515. continue
  1516. if expected_type is not None and not is_type(e, expected_type):
  1517. continue
  1518. rating = traverse_obj(e, ('aggregateRating', 'ratingValue'), expected_type=float_or_none)
  1519. if rating is not None:
  1520. info['average_rating'] = rating
  1521. if is_type(e, 'TVEpisode', 'Episode', 'PodcastEpisode'):
  1522. episode_name = unescapeHTML(e.get('name'))
  1523. info.update({
  1524. 'episode': episode_name,
  1525. 'episode_number': int_or_none(e.get('episodeNumber')),
  1526. 'description': unescapeHTML(e.get('description')),
  1527. })
  1528. if not info.get('title') and episode_name:
  1529. info['title'] = episode_name
  1530. part_of_season = e.get('partOfSeason')
  1531. if is_type(part_of_season, 'TVSeason', 'Season', 'CreativeWorkSeason'):
  1532. info.update({
  1533. 'season': unescapeHTML(part_of_season.get('name')),
  1534. 'season_number': int_or_none(part_of_season.get('seasonNumber')),
  1535. })
  1536. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  1537. if is_type(part_of_series, 'TVSeries', 'Series', 'CreativeWorkSeries'):
  1538. info['series'] = unescapeHTML(part_of_series.get('name'))
  1539. elif is_type(e, 'Movie'):
  1540. info.update({
  1541. 'title': unescapeHTML(e.get('name')),
  1542. 'description': unescapeHTML(e.get('description')),
  1543. 'duration': parse_duration(e.get('duration')),
  1544. 'timestamp': unified_timestamp(e.get('dateCreated')),
  1545. })
  1546. elif is_type(e, 'Article', 'NewsArticle'):
  1547. info.update({
  1548. 'timestamp': parse_iso8601(e.get('datePublished')),
  1549. 'title': unescapeHTML(e.get('headline')),
  1550. 'description': unescapeHTML(e.get('articleBody') or e.get('description')),
  1551. })
  1552. if is_type(traverse_obj(e, ('video', 0)), 'VideoObject'):
  1553. extract_video_object(e['video'][0])
  1554. elif is_type(traverse_obj(e, ('subjectOf', 0)), 'VideoObject'):
  1555. extract_video_object(e['subjectOf'][0])
  1556. elif is_type(e, 'VideoObject', 'AudioObject'):
  1557. extract_video_object(e)
  1558. if expected_type is None:
  1559. continue
  1560. else:
  1561. break
  1562. video = e.get('video')
  1563. if is_type(video, 'VideoObject'):
  1564. extract_video_object(video)
  1565. if expected_type is None:
  1566. continue
  1567. else:
  1568. break
  1569. traverse_json_ld(json_ld)
  1570. return filter_dict(info)
  1571. def _search_nextjs_data(self, webpage, video_id, *, fatal=True, default=NO_DEFAULT, **kw):
  1572. if default == '{}':
  1573. self._downloader.deprecation_warning('using `default=\'{}\'` is deprecated, use `default={}` instead')
  1574. default = {}
  1575. if default is not NO_DEFAULT:
  1576. fatal = False
  1577. return self._search_json(
  1578. r'<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>', webpage, 'next.js data',
  1579. video_id, end_pattern='</script>', fatal=fatal, default=default, **kw)
  1580. def _search_nuxt_data(self, webpage, video_id, context_name='__NUXT__', *, fatal=True, traverse=('data', 0)):
  1581. """Parses Nuxt.js metadata. This works as long as the function __NUXT__ invokes is a pure function"""
  1582. rectx = re.escape(context_name)
  1583. FUNCTION_RE = r'\(function\((?P<arg_keys>.*?)\){.*?\breturn\s+(?P<js>{.*?})\s*;?\s*}\((?P<arg_vals>.*?)\)'
  1584. js, arg_keys, arg_vals = self._search_regex(
  1585. (rf'<script>\s*window\.{rectx}={FUNCTION_RE}\s*\)\s*;?\s*</script>', rf'{rectx}\(.*?{FUNCTION_RE}'),
  1586. webpage, context_name, group=('js', 'arg_keys', 'arg_vals'),
  1587. default=NO_DEFAULT if fatal else (None, None, None))
  1588. if js is None:
  1589. return {}
  1590. args = dict(zip(arg_keys.split(','), map(json.dumps, self._parse_json(
  1591. f'[{arg_vals}]', video_id, transform_source=js_to_json, fatal=fatal) or ())))
  1592. ret = self._parse_json(js, video_id, transform_source=functools.partial(js_to_json, vars=args), fatal=fatal)
  1593. return traverse_obj(ret, traverse) or {}
  1594. @staticmethod
  1595. def _hidden_inputs(html):
  1596. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  1597. hidden_inputs = {}
  1598. for input_el in re.findall(r'(?i)(<input[^>]+>)', html):
  1599. attrs = extract_attributes(input_el)
  1600. if not input_el:
  1601. continue
  1602. if attrs.get('type') not in ('hidden', 'submit'):
  1603. continue
  1604. name = attrs.get('name') or attrs.get('id')
  1605. value = attrs.get('value')
  1606. if name and value is not None:
  1607. hidden_inputs[name] = value
  1608. return hidden_inputs
  1609. def _form_hidden_inputs(self, form_id, html):
  1610. form = self._search_regex(
  1611. rf'(?is)<form[^>]+?id=(["\']){form_id}\1[^>]*>(?P<form>.+?)</form>',
  1612. html, f'{form_id} form', group='form')
  1613. return self._hidden_inputs(form)
  1614. @classproperty(cache=True)
  1615. def FormatSort(cls):
  1616. class FormatSort(FormatSorter):
  1617. def __init__(ie, *args, **kwargs):
  1618. super().__init__(ie._downloader, *args, **kwargs)
  1619. deprecation_warning(
  1620. 'yt_dlp.InfoExtractor.FormatSort is deprecated and may be removed in the future. '
  1621. 'Use yt_dlp.utils.FormatSorter instead')
  1622. return FormatSort
  1623. def _sort_formats(self, formats, field_preference=[]):
  1624. if not field_preference:
  1625. self._downloader.deprecation_warning(
  1626. 'yt_dlp.InfoExtractor._sort_formats is deprecated and is no longer required')
  1627. return
  1628. self._downloader.deprecation_warning(
  1629. 'yt_dlp.InfoExtractor._sort_formats is deprecated and no longer works as expected. '
  1630. 'Return _format_sort_fields in the info_dict instead')
  1631. if formats:
  1632. formats[0]['__sort_fields'] = field_preference
  1633. def _check_formats(self, formats, video_id):
  1634. if formats:
  1635. formats[:] = filter(
  1636. lambda f: self._is_valid_url(
  1637. f['url'], video_id,
  1638. item='{} video format'.format(f.get('format_id')) if f.get('format_id') else 'video'),
  1639. formats)
  1640. @staticmethod
  1641. def _remove_duplicate_formats(formats):
  1642. seen_urls = set()
  1643. seen_fragment_urls = set()
  1644. unique_formats = []
  1645. for f in formats:
  1646. fragments = f.get('fragments')
  1647. if callable(fragments):
  1648. unique_formats.append(f)
  1649. elif fragments:
  1650. fragment_urls = frozenset(
  1651. fragment.get('url') or urljoin(f['fragment_base_url'], fragment['path'])
  1652. for fragment in fragments)
  1653. if fragment_urls not in seen_fragment_urls:
  1654. seen_fragment_urls.add(fragment_urls)
  1655. unique_formats.append(f)
  1656. elif f['url'] not in seen_urls:
  1657. seen_urls.add(f['url'])
  1658. unique_formats.append(f)
  1659. formats[:] = unique_formats
  1660. def _is_valid_url(self, url, video_id, item='video', headers={}):
  1661. url = self._proto_relative_url(url, scheme='http:')
  1662. # For now assume non HTTP(S) URLs always valid
  1663. if not url.startswith(('http://', 'https://')):
  1664. return True
  1665. try:
  1666. self._request_webpage(url, video_id, f'Checking {item} URL', headers=headers)
  1667. return True
  1668. except ExtractorError as e:
  1669. self.to_screen(
  1670. f'{video_id}: {item} URL is invalid, skipping: {e.cause!s}')
  1671. return False
  1672. def http_scheme(self):
  1673. """ Either "http:" or "https:", depending on the user's preferences """
  1674. return (
  1675. 'http:'
  1676. if self.get_param('prefer_insecure', False)
  1677. else 'https:')
  1678. def _proto_relative_url(self, url, scheme=None):
  1679. scheme = scheme or self.http_scheme()
  1680. assert scheme.endswith(':')
  1681. return sanitize_url(url, scheme=scheme[:-1])
  1682. def _sleep(self, timeout, video_id, msg_template=None):
  1683. if msg_template is None:
  1684. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1685. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1686. self.to_screen(msg)
  1687. time.sleep(timeout)
  1688. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1689. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1690. fatal=True, m3u8_id=None, data=None, headers={}, query={}):
  1691. if self.get_param('ignore_no_formats_error'):
  1692. fatal = False
  1693. res = self._download_xml_handle(
  1694. manifest_url, video_id, 'Downloading f4m manifest',
  1695. 'Unable to download f4m manifest',
  1696. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1697. # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244)
  1698. transform_source=transform_source,
  1699. fatal=fatal, data=data, headers=headers, query=query)
  1700. if res is False:
  1701. return []
  1702. manifest, urlh = res
  1703. manifest_url = urlh.url
  1704. return self._parse_f4m_formats(
  1705. manifest, manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1706. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1707. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1708. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1709. fatal=True, m3u8_id=None):
  1710. if not isinstance(manifest, xml.etree.ElementTree.Element) and not fatal:
  1711. return []
  1712. # currently yt-dlp cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1713. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1714. if akamai_pv is not None and ';' in akamai_pv.text:
  1715. player_verification_challenge = akamai_pv.text.split(';')[0]
  1716. if player_verification_challenge.strip() != '':
  1717. return []
  1718. formats = []
  1719. manifest_version = '1.0'
  1720. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1721. if not media_nodes:
  1722. manifest_version = '2.0'
  1723. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1724. # Remove unsupported DRM protected media from final formats
  1725. # rendition (see https://github.com/ytdl-org/youtube-dl/issues/8573).
  1726. media_nodes = remove_encrypted_media(media_nodes)
  1727. if not media_nodes:
  1728. return formats
  1729. manifest_base_url = get_base_url(manifest)
  1730. bootstrap_info = xpath_element(
  1731. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1732. 'bootstrap info', default=None)
  1733. vcodec = None
  1734. mime_type = xpath_text(
  1735. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1736. 'base URL', default=None)
  1737. if mime_type and mime_type.startswith('audio/'):
  1738. vcodec = 'none'
  1739. for i, media_el in enumerate(media_nodes):
  1740. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1741. width = int_or_none(media_el.attrib.get('width'))
  1742. height = int_or_none(media_el.attrib.get('height'))
  1743. format_id = join_nonempty(f4m_id, tbr or i)
  1744. # If <bootstrapInfo> is present, the specified f4m is a
  1745. # stream-level manifest, and only set-level manifests may refer to
  1746. # external resources. See section 11.4 and section 4 of F4M spec
  1747. if bootstrap_info is None:
  1748. media_url = None
  1749. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1750. if manifest_version == '2.0':
  1751. media_url = media_el.attrib.get('href')
  1752. if media_url is None:
  1753. media_url = media_el.attrib.get('url')
  1754. if not media_url:
  1755. continue
  1756. manifest_url = (
  1757. media_url if media_url.startswith(('http://', 'https://'))
  1758. else ((manifest_base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1759. # If media_url is itself a f4m manifest do the recursive extraction
  1760. # since bitrates in parent manifest (this one) and media_url manifest
  1761. # may differ leading to inability to resolve the format by requested
  1762. # bitrate in f4m downloader
  1763. ext = determine_ext(manifest_url)
  1764. if ext == 'f4m':
  1765. f4m_formats = self._extract_f4m_formats(
  1766. manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1767. transform_source=transform_source, fatal=fatal)
  1768. # Sometimes stream-level manifest contains single media entry that
  1769. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1770. # At the same time parent's media entry in set-level manifest may
  1771. # contain it. We will copy it from parent in such cases.
  1772. if len(f4m_formats) == 1:
  1773. f = f4m_formats[0]
  1774. f.update({
  1775. 'tbr': f.get('tbr') or tbr,
  1776. 'width': f.get('width') or width,
  1777. 'height': f.get('height') or height,
  1778. 'format_id': f.get('format_id') if not tbr else format_id,
  1779. 'vcodec': vcodec,
  1780. })
  1781. formats.extend(f4m_formats)
  1782. continue
  1783. elif ext == 'm3u8':
  1784. formats.extend(self._extract_m3u8_formats(
  1785. manifest_url, video_id, 'mp4', preference=preference,
  1786. quality=quality, m3u8_id=m3u8_id, fatal=fatal))
  1787. continue
  1788. formats.append({
  1789. 'format_id': format_id,
  1790. 'url': manifest_url,
  1791. 'manifest_url': manifest_url,
  1792. 'ext': 'flv' if bootstrap_info is not None else None,
  1793. 'protocol': 'f4m',
  1794. 'tbr': tbr,
  1795. 'width': width,
  1796. 'height': height,
  1797. 'vcodec': vcodec,
  1798. 'preference': preference,
  1799. 'quality': quality,
  1800. })
  1801. return formats
  1802. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, quality=None, m3u8_id=None):
  1803. return {
  1804. 'format_id': join_nonempty(m3u8_id, 'meta'),
  1805. 'url': m3u8_url,
  1806. 'ext': ext,
  1807. 'protocol': 'm3u8',
  1808. 'preference': preference - 100 if preference else -100,
  1809. 'quality': quality,
  1810. 'resolution': 'multiple',
  1811. 'format_note': 'Quality selection URL',
  1812. }
  1813. def _report_ignoring_subs(self, name):
  1814. self.report_warning(bug_reports_message(
  1815. f'Ignoring subtitle tracks found in the {name} manifest; '
  1816. 'if any subtitle tracks are missing,',
  1817. ), only_once=True)
  1818. def _extract_m3u8_formats(self, *args, **kwargs):
  1819. fmts, subs = self._extract_m3u8_formats_and_subtitles(*args, **kwargs)
  1820. if subs:
  1821. self._report_ignoring_subs('HLS')
  1822. return fmts
  1823. def _extract_m3u8_formats_and_subtitles(
  1824. self, m3u8_url, video_id, ext=None, entry_protocol='m3u8_native',
  1825. preference=None, quality=None, m3u8_id=None, note=None,
  1826. errnote=None, fatal=True, live=False, data=None, headers={},
  1827. query={}):
  1828. if self.get_param('ignore_no_formats_error'):
  1829. fatal = False
  1830. if not m3u8_url:
  1831. if errnote is not False:
  1832. errnote = errnote or 'Failed to obtain m3u8 URL'
  1833. if fatal:
  1834. raise ExtractorError(errnote, video_id=video_id)
  1835. self.report_warning(f'{errnote}{bug_reports_message()}')
  1836. return [], {}
  1837. res = self._download_webpage_handle(
  1838. m3u8_url, video_id,
  1839. note='Downloading m3u8 information' if note is None else note,
  1840. errnote='Failed to download m3u8 information' if errnote is None else errnote,
  1841. fatal=fatal, data=data, headers=headers, query=query)
  1842. if res is False:
  1843. return [], {}
  1844. m3u8_doc, urlh = res
  1845. m3u8_url = urlh.url
  1846. return self._parse_m3u8_formats_and_subtitles(
  1847. m3u8_doc, m3u8_url, ext=ext, entry_protocol=entry_protocol,
  1848. preference=preference, quality=quality, m3u8_id=m3u8_id,
  1849. note=note, errnote=errnote, fatal=fatal, live=live, data=data,
  1850. headers=headers, query=query, video_id=video_id)
  1851. def _parse_m3u8_formats_and_subtitles(
  1852. self, m3u8_doc, m3u8_url=None, ext=None, entry_protocol='m3u8_native',
  1853. preference=None, quality=None, m3u8_id=None, live=False, note=None,
  1854. errnote=None, fatal=True, data=None, headers={}, query={},
  1855. video_id=None):
  1856. formats, subtitles = [], {}
  1857. has_drm = HlsFD._has_drm(m3u8_doc)
  1858. def format_url(url):
  1859. return url if re.match(r'https?://', url) else urllib.parse.urljoin(m3u8_url, url)
  1860. if self.get_param('hls_split_discontinuity', False):
  1861. def _extract_m3u8_playlist_indices(manifest_url=None, m3u8_doc=None):
  1862. if not m3u8_doc:
  1863. if not manifest_url:
  1864. return []
  1865. m3u8_doc = self._download_webpage(
  1866. manifest_url, video_id, fatal=fatal, data=data, headers=headers,
  1867. note=False, errnote='Failed to download m3u8 playlist information')
  1868. if m3u8_doc is False:
  1869. return []
  1870. return range(1 + sum(line.startswith('#EXT-X-DISCONTINUITY') for line in m3u8_doc.splitlines()))
  1871. else:
  1872. def _extract_m3u8_playlist_indices(*args, **kwargs):
  1873. return [None]
  1874. # References:
  1875. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-21
  1876. # 2. https://github.com/ytdl-org/youtube-dl/issues/12211
  1877. # 3. https://github.com/ytdl-org/youtube-dl/issues/18923
  1878. # We should try extracting formats only from master playlists [1, 4.3.4],
  1879. # i.e. playlists that describe available qualities. On the other hand
  1880. # media playlists [1, 4.3.3] should be returned as is since they contain
  1881. # just the media without qualities renditions.
  1882. # Fortunately, master playlist can be easily distinguished from media
  1883. # playlist based on particular tags availability. As of [1, 4.3.3, 4.3.4]
  1884. # master playlist tags MUST NOT appear in a media playlist and vice versa.
  1885. # As of [1, 4.3.3.1] #EXT-X-TARGETDURATION tag is REQUIRED for every
  1886. # media playlist and MUST NOT appear in master playlist thus we can
  1887. # clearly detect media playlist with this criterion.
  1888. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1889. formats = [{
  1890. 'format_id': join_nonempty(m3u8_id, idx),
  1891. 'format_index': idx,
  1892. 'url': m3u8_url or encode_data_uri(m3u8_doc.encode(), 'application/x-mpegurl'),
  1893. 'ext': ext,
  1894. 'protocol': entry_protocol,
  1895. 'preference': preference,
  1896. 'quality': quality,
  1897. 'has_drm': has_drm,
  1898. } for idx in _extract_m3u8_playlist_indices(m3u8_doc=m3u8_doc)]
  1899. return formats, subtitles
  1900. groups = {}
  1901. last_stream_inf = {}
  1902. def extract_media(x_media_line):
  1903. media = parse_m3u8_attributes(x_media_line)
  1904. # As per [1, 4.3.4.1] TYPE, GROUP-ID and NAME are REQUIRED
  1905. media_type, group_id, name = media.get('TYPE'), media.get('GROUP-ID'), media.get('NAME')
  1906. if not (media_type and group_id and name):
  1907. return
  1908. groups.setdefault(group_id, []).append(media)
  1909. # <https://tools.ietf.org/html/rfc8216#section-4.3.4.1>
  1910. if media_type == 'SUBTITLES':
  1911. # According to RFC 8216 §4.3.4.2.1, URI is REQUIRED in the
  1912. # EXT-X-MEDIA tag if the media type is SUBTITLES.
  1913. # However, lack of URI has been spotted in the wild.
  1914. # e.g. NebulaIE; see https://github.com/yt-dlp/yt-dlp/issues/339
  1915. if not media.get('URI'):
  1916. return
  1917. url = format_url(media['URI'])
  1918. sub_info = {
  1919. 'url': url,
  1920. 'ext': determine_ext(url),
  1921. }
  1922. if sub_info['ext'] == 'm3u8':
  1923. # Per RFC 8216 §3.1, the only possible subtitle format m3u8
  1924. # files may contain is WebVTT:
  1925. # <https://tools.ietf.org/html/rfc8216#section-3.1>
  1926. sub_info['ext'] = 'vtt'
  1927. sub_info['protocol'] = 'm3u8_native'
  1928. lang = media.get('LANGUAGE') or 'und'
  1929. subtitles.setdefault(lang, []).append(sub_info)
  1930. if media_type not in ('VIDEO', 'AUDIO'):
  1931. return
  1932. media_url = media.get('URI')
  1933. if media_url:
  1934. manifest_url = format_url(media_url)
  1935. is_audio = media_type == 'AUDIO'
  1936. is_alternate = media.get('DEFAULT') == 'NO' or media.get('AUTOSELECT') == 'NO'
  1937. formats.extend({
  1938. 'format_id': join_nonempty(m3u8_id, group_id, name, idx),
  1939. 'format_note': name,
  1940. 'format_index': idx,
  1941. 'url': manifest_url,
  1942. 'manifest_url': m3u8_url,
  1943. 'language': media.get('LANGUAGE'),
  1944. 'ext': ext,
  1945. 'protocol': entry_protocol,
  1946. 'preference': preference,
  1947. 'quality': quality,
  1948. 'has_drm': has_drm,
  1949. 'vcodec': 'none' if is_audio else None,
  1950. # Alternate audio formats (e.g. audio description) should be deprioritized
  1951. 'source_preference': -2 if is_audio and is_alternate else None,
  1952. # Save this to assign source_preference based on associated video stream
  1953. '_audio_group_id': group_id if is_audio and not is_alternate else None,
  1954. } for idx in _extract_m3u8_playlist_indices(manifest_url))
  1955. def build_stream_name():
  1956. # Despite specification does not mention NAME attribute for
  1957. # EXT-X-STREAM-INF tag it still sometimes may be present (see [1]
  1958. # or vidio test in TestInfoExtractor.test_parse_m3u8_formats)
  1959. # 1. http://www.vidio.com/watch/165683-dj_ambred-booyah-live-2015
  1960. stream_name = last_stream_inf.get('NAME')
  1961. if stream_name:
  1962. return stream_name
  1963. # If there is no NAME in EXT-X-STREAM-INF it will be obtained
  1964. # from corresponding rendition group
  1965. stream_group_id = last_stream_inf.get('VIDEO')
  1966. if not stream_group_id:
  1967. return
  1968. stream_group = groups.get(stream_group_id)
  1969. if not stream_group:
  1970. return stream_group_id
  1971. rendition = stream_group[0]
  1972. return rendition.get('NAME') or stream_group_id
  1973. # parse EXT-X-MEDIA tags before EXT-X-STREAM-INF in order to have the
  1974. # chance to detect video only formats when EXT-X-STREAM-INF tags
  1975. # precede EXT-X-MEDIA tags in HLS manifest such as [3].
  1976. for line in m3u8_doc.splitlines():
  1977. if line.startswith('#EXT-X-MEDIA:'):
  1978. extract_media(line)
  1979. for line in m3u8_doc.splitlines():
  1980. if line.startswith('#EXT-X-STREAM-INF:'):
  1981. last_stream_inf = parse_m3u8_attributes(line)
  1982. elif line.startswith('#') or not line.strip():
  1983. continue
  1984. else:
  1985. tbr = float_or_none(
  1986. last_stream_inf.get('AVERAGE-BANDWIDTH')
  1987. or last_stream_inf.get('BANDWIDTH'), scale=1000)
  1988. manifest_url = format_url(line.strip())
  1989. for idx in _extract_m3u8_playlist_indices(manifest_url):
  1990. format_id = [m3u8_id, None, idx]
  1991. # Bandwidth of live streams may differ over time thus making
  1992. # format_id unpredictable. So it's better to keep provided
  1993. # format_id intact.
  1994. if not live:
  1995. stream_name = build_stream_name()
  1996. format_id[1] = stream_name or '%d' % (tbr or len(formats))
  1997. f = {
  1998. 'format_id': join_nonempty(*format_id),
  1999. 'format_index': idx,
  2000. 'url': manifest_url,
  2001. 'manifest_url': m3u8_url,
  2002. 'tbr': tbr,
  2003. 'ext': ext,
  2004. 'fps': float_or_none(last_stream_inf.get('FRAME-RATE')),
  2005. 'protocol': entry_protocol,
  2006. 'preference': preference,
  2007. 'quality': quality,
  2008. 'has_drm': has_drm,
  2009. }
  2010. # YouTube-specific
  2011. if yt_audio_content_id := last_stream_inf.get('YT-EXT-AUDIO-CONTENT-ID'):
  2012. f['language'] = yt_audio_content_id.split('.')[0]
  2013. resolution = last_stream_inf.get('RESOLUTION')
  2014. if resolution:
  2015. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  2016. if mobj:
  2017. f['width'] = int(mobj.group('width'))
  2018. f['height'] = int(mobj.group('height'))
  2019. # Unified Streaming Platform
  2020. mobj = re.search(
  2021. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  2022. if mobj:
  2023. abr, vbr = mobj.groups()
  2024. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  2025. f.update({
  2026. 'vbr': vbr,
  2027. 'abr': abr,
  2028. })
  2029. codecs = parse_codecs(last_stream_inf.get('CODECS'))
  2030. f.update(codecs)
  2031. audio_group_id = last_stream_inf.get('AUDIO')
  2032. # As per [1, 4.3.4.1.1] any EXT-X-STREAM-INF tag which
  2033. # references a rendition group MUST have a CODECS attribute.
  2034. # However, this is not always respected. E.g. [2]
  2035. # contains EXT-X-STREAM-INF tag which references AUDIO
  2036. # rendition group but does not have CODECS and despite
  2037. # referencing an audio group it represents a complete
  2038. # (with audio and video) format. So, for such cases we will
  2039. # ignore references to rendition groups and treat them
  2040. # as complete formats.
  2041. if audio_group_id and codecs and f.get('vcodec') != 'none':
  2042. # Save this to determine quality of audio formats that only have a GROUP-ID
  2043. f['_audio_group_id'] = audio_group_id
  2044. audio_group = groups.get(audio_group_id)
  2045. if audio_group and audio_group[0].get('URI'):
  2046. # TODO: update acodec for audio only formats with
  2047. # the same GROUP-ID
  2048. f['acodec'] = 'none'
  2049. if not f.get('ext'):
  2050. f['ext'] = 'm4a' if f.get('vcodec') == 'none' else 'mp4'
  2051. formats.append(f)
  2052. # for DailyMotion
  2053. progressive_uri = last_stream_inf.get('PROGRESSIVE-URI')
  2054. if progressive_uri:
  2055. http_f = f.copy()
  2056. del http_f['manifest_url']
  2057. http_f.update({
  2058. 'format_id': f['format_id'].replace('hls-', 'http-'),
  2059. 'protocol': 'http',
  2060. 'url': progressive_uri,
  2061. })
  2062. formats.append(http_f)
  2063. last_stream_inf = {}
  2064. # Some audio-only formats only have a GROUP-ID without any other quality/bitrate/codec info
  2065. # Each audio GROUP-ID corresponds with one or more video formats' AUDIO attribute
  2066. # For sorting purposes, set source_preference based on the quality of the video formats they are grouped with
  2067. # See https://github.com/yt-dlp/yt-dlp/issues/11178
  2068. audio_groups_by_quality = orderedSet(f['_audio_group_id'] for f in sorted(
  2069. traverse_obj(formats, lambda _, v: v.get('vcodec') != 'none' and v['_audio_group_id']),
  2070. key=lambda x: (x.get('tbr') or 0, x.get('width') or 0)))
  2071. audio_quality_map = {
  2072. audio_groups_by_quality[0]: 'low',
  2073. audio_groups_by_quality[-1]: 'high',
  2074. } if len(audio_groups_by_quality) > 1 else None
  2075. audio_preference = qualities(audio_groups_by_quality)
  2076. for fmt in formats:
  2077. audio_group_id = fmt.pop('_audio_group_id', None)
  2078. if not audio_quality_map or not audio_group_id or fmt.get('vcodec') != 'none':
  2079. continue
  2080. # Use source_preference since quality and preference are set by params
  2081. fmt['source_preference'] = audio_preference(audio_group_id)
  2082. fmt['format_note'] = join_nonempty(
  2083. fmt.get('format_note'), audio_quality_map.get(audio_group_id), delim=', ')
  2084. return formats, subtitles
  2085. def _extract_m3u8_vod_duration(
  2086. self, m3u8_vod_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2087. m3u8_vod = self._download_webpage(
  2088. m3u8_vod_url, video_id,
  2089. note='Downloading m3u8 VOD manifest' if note is None else note,
  2090. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2091. fatal=False, data=data, headers=headers, query=query)
  2092. return self._parse_m3u8_vod_duration(m3u8_vod or '', video_id)
  2093. def _parse_m3u8_vod_duration(self, m3u8_vod, video_id):
  2094. if '#EXT-X-ENDLIST' not in m3u8_vod:
  2095. return None
  2096. return int(sum(
  2097. float(line[len('#EXTINF:'):].split(',')[0])
  2098. for line in m3u8_vod.splitlines() if line.startswith('#EXTINF:'))) or None
  2099. def _extract_mpd_vod_duration(
  2100. self, mpd_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2101. mpd_doc = self._download_xml(
  2102. mpd_url, video_id,
  2103. note='Downloading MPD VOD manifest' if note is None else note,
  2104. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2105. fatal=False, data=data, headers=headers, query=query)
  2106. if not isinstance(mpd_doc, xml.etree.ElementTree.Element):
  2107. return None
  2108. return int_or_none(parse_duration(mpd_doc.get('mediaPresentationDuration')))
  2109. @staticmethod
  2110. def _xpath_ns(path, namespace=None):
  2111. if not namespace:
  2112. return path
  2113. out = []
  2114. for c in path.split('/'):
  2115. if not c or c == '.':
  2116. out.append(c)
  2117. else:
  2118. out.append(f'{{{namespace}}}{c}')
  2119. return '/'.join(out)
  2120. def _extract_smil_formats_and_subtitles(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  2121. if self.get_param('ignore_no_formats_error'):
  2122. fatal = False
  2123. res = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  2124. if res is False:
  2125. assert not fatal
  2126. return [], {}
  2127. smil, urlh = res
  2128. return self._parse_smil_formats_and_subtitles(smil, urlh.url, video_id, f4m_params=f4m_params,
  2129. namespace=self._parse_smil_namespace(smil))
  2130. def _extract_smil_formats(self, *args, **kwargs):
  2131. fmts, subs = self._extract_smil_formats_and_subtitles(*args, **kwargs)
  2132. if subs:
  2133. self._report_ignoring_subs('SMIL')
  2134. return fmts
  2135. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  2136. res = self._download_smil(smil_url, video_id, fatal=fatal)
  2137. if res is False:
  2138. return {}
  2139. smil, urlh = res
  2140. smil_url = urlh.url
  2141. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  2142. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  2143. return self._download_xml_handle(
  2144. smil_url, video_id, 'Downloading SMIL file',
  2145. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  2146. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  2147. namespace = self._parse_smil_namespace(smil)
  2148. formats, subtitles = self._parse_smil_formats_and_subtitles(
  2149. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  2150. video_id = os.path.splitext(url_basename(smil_url))[0]
  2151. title = None
  2152. description = None
  2153. upload_date = None
  2154. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2155. name = meta.attrib.get('name')
  2156. content = meta.attrib.get('content')
  2157. if not name or not content:
  2158. continue
  2159. if not title and name == 'title':
  2160. title = content
  2161. elif not description and name in ('description', 'abstract'):
  2162. description = content
  2163. elif not upload_date and name == 'date':
  2164. upload_date = unified_strdate(content)
  2165. thumbnails = [{
  2166. 'id': image.get('type'),
  2167. 'url': image.get('src'),
  2168. 'width': int_or_none(image.get('width')),
  2169. 'height': int_or_none(image.get('height')),
  2170. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  2171. return {
  2172. 'id': video_id,
  2173. 'title': title or video_id,
  2174. 'description': description,
  2175. 'upload_date': upload_date,
  2176. 'thumbnails': thumbnails,
  2177. 'formats': formats,
  2178. 'subtitles': subtitles,
  2179. }
  2180. def _parse_smil_namespace(self, smil):
  2181. return self._search_regex(
  2182. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  2183. def _parse_smil_formats(self, *args, **kwargs):
  2184. fmts, subs = self._parse_smil_formats_and_subtitles(*args, **kwargs)
  2185. if subs:
  2186. self._report_ignoring_subs('SMIL')
  2187. return fmts
  2188. def _parse_smil_formats_and_subtitles(
  2189. self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  2190. base = smil_url
  2191. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2192. b = meta.get('base') or meta.get('httpBase')
  2193. if b:
  2194. base = b
  2195. break
  2196. formats, subtitles = [], {}
  2197. rtmp_count = 0
  2198. http_count = 0
  2199. m3u8_count = 0
  2200. imgs_count = 0
  2201. srcs = set()
  2202. media = itertools.chain.from_iterable(
  2203. smil.findall(self._xpath_ns(arg, namespace))
  2204. for arg in ['.//video', './/audio', './/media'])
  2205. for medium in media:
  2206. src = medium.get('src')
  2207. if not src or src in srcs:
  2208. continue
  2209. srcs.add(src)
  2210. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  2211. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  2212. width = int_or_none(medium.get('width'))
  2213. height = int_or_none(medium.get('height'))
  2214. proto = medium.get('proto')
  2215. ext = medium.get('ext')
  2216. src_ext = determine_ext(src, default_ext=None) or ext or urlhandle_detect_ext(
  2217. self._request_webpage(HEADRequest(src), video_id, note='Requesting extension info', fatal=False))
  2218. streamer = medium.get('streamer') or base
  2219. if proto == 'rtmp' or streamer.startswith('rtmp'):
  2220. rtmp_count += 1
  2221. formats.append({
  2222. 'url': streamer,
  2223. 'play_path': src,
  2224. 'ext': 'flv',
  2225. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  2226. 'tbr': bitrate,
  2227. 'filesize': filesize,
  2228. 'width': width,
  2229. 'height': height,
  2230. })
  2231. if transform_rtmp_url:
  2232. streamer, src = transform_rtmp_url(streamer, src)
  2233. formats[-1].update({
  2234. 'url': streamer,
  2235. 'play_path': src,
  2236. })
  2237. continue
  2238. src_url = src if src.startswith('http') else urllib.parse.urljoin(f'{base}/', src)
  2239. src_url = src_url.strip()
  2240. if proto == 'm3u8' or src_ext == 'm3u8':
  2241. m3u8_formats, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
  2242. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  2243. self._merge_subtitles(m3u8_subs, target=subtitles)
  2244. if len(m3u8_formats) == 1:
  2245. m3u8_count += 1
  2246. m3u8_formats[0].update({
  2247. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  2248. 'tbr': bitrate,
  2249. 'width': width,
  2250. 'height': height,
  2251. })
  2252. formats.extend(m3u8_formats)
  2253. elif src_ext == 'f4m':
  2254. f4m_url = src_url
  2255. if not f4m_params:
  2256. f4m_params = {
  2257. 'hdcore': '3.2.0',
  2258. 'plugin': 'flowplayer-3.2.0.1',
  2259. }
  2260. f4m_url += '&' if '?' in f4m_url else '?'
  2261. f4m_url += urllib.parse.urlencode(f4m_params)
  2262. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  2263. elif src_ext == 'mpd':
  2264. mpd_formats, mpd_subs = self._extract_mpd_formats_and_subtitles(
  2265. src_url, video_id, mpd_id='dash', fatal=False)
  2266. formats.extend(mpd_formats)
  2267. self._merge_subtitles(mpd_subs, target=subtitles)
  2268. elif re.search(r'\.ism/[Mm]anifest', src_url):
  2269. ism_formats, ism_subs = self._extract_ism_formats_and_subtitles(
  2270. src_url, video_id, ism_id='mss', fatal=False)
  2271. formats.extend(ism_formats)
  2272. self._merge_subtitles(ism_subs, target=subtitles)
  2273. elif src_url.startswith('http') and self._is_valid_url(src, video_id):
  2274. http_count += 1
  2275. formats.append({
  2276. 'url': src_url,
  2277. 'ext': ext or src_ext or 'flv',
  2278. 'format_id': 'http-%d' % (bitrate or http_count),
  2279. 'tbr': bitrate,
  2280. 'filesize': filesize,
  2281. 'width': width,
  2282. 'height': height,
  2283. })
  2284. for medium in smil.findall(self._xpath_ns('.//imagestream', namespace)):
  2285. src = medium.get('src')
  2286. if not src or src in srcs:
  2287. continue
  2288. srcs.add(src)
  2289. imgs_count += 1
  2290. formats.append({
  2291. 'format_id': f'imagestream-{imgs_count}',
  2292. 'url': src,
  2293. 'ext': mimetype2ext(medium.get('type')),
  2294. 'acodec': 'none',
  2295. 'vcodec': 'none',
  2296. 'width': int_or_none(medium.get('width')),
  2297. 'height': int_or_none(medium.get('height')),
  2298. 'format_note': 'SMIL storyboards',
  2299. })
  2300. smil_subs = self._parse_smil_subtitles(smil, namespace=namespace)
  2301. self._merge_subtitles(smil_subs, target=subtitles)
  2302. return formats, subtitles
  2303. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  2304. urls = []
  2305. subtitles = {}
  2306. for textstream in smil.findall(self._xpath_ns('.//textstream', namespace)):
  2307. src = textstream.get('src')
  2308. if not src or src in urls:
  2309. continue
  2310. urls.append(src)
  2311. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  2312. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  2313. subtitles.setdefault(lang, []).append({
  2314. 'url': src,
  2315. 'ext': ext,
  2316. })
  2317. return subtitles
  2318. def _extract_xspf_playlist(self, xspf_url, playlist_id, fatal=True):
  2319. res = self._download_xml_handle(
  2320. xspf_url, playlist_id, 'Downloading xpsf playlist',
  2321. 'Unable to download xspf manifest', fatal=fatal)
  2322. if res is False:
  2323. return []
  2324. xspf, urlh = res
  2325. xspf_url = urlh.url
  2326. return self._parse_xspf(
  2327. xspf, playlist_id, xspf_url=xspf_url,
  2328. xspf_base_url=base_url(xspf_url))
  2329. def _parse_xspf(self, xspf_doc, playlist_id, xspf_url=None, xspf_base_url=None):
  2330. NS_MAP = {
  2331. 'xspf': 'http://xspf.org/ns/0/',
  2332. 's1': 'http://static.streamone.nl/player/ns/0',
  2333. }
  2334. entries = []
  2335. for track in xspf_doc.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  2336. title = xpath_text(
  2337. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  2338. description = xpath_text(
  2339. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  2340. thumbnail = xpath_text(
  2341. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  2342. duration = float_or_none(
  2343. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  2344. formats = []
  2345. for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP)):
  2346. format_url = urljoin(xspf_base_url, location.text)
  2347. if not format_url:
  2348. continue
  2349. formats.append({
  2350. 'url': format_url,
  2351. 'manifest_url': xspf_url,
  2352. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  2353. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  2354. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  2355. })
  2356. entries.append({
  2357. 'id': playlist_id,
  2358. 'title': title,
  2359. 'description': description,
  2360. 'thumbnail': thumbnail,
  2361. 'duration': duration,
  2362. 'formats': formats,
  2363. })
  2364. return entries
  2365. def _extract_mpd_formats(self, *args, **kwargs):
  2366. fmts, subs = self._extract_mpd_formats_and_subtitles(*args, **kwargs)
  2367. if subs:
  2368. self._report_ignoring_subs('DASH')
  2369. return fmts
  2370. def _extract_mpd_formats_and_subtitles(self, *args, **kwargs):
  2371. periods = self._extract_mpd_periods(*args, **kwargs)
  2372. return self._merge_mpd_periods(periods)
  2373. def _extract_mpd_periods(
  2374. self, mpd_url, video_id, mpd_id=None, note=None, errnote=None,
  2375. fatal=True, data=None, headers={}, query={}):
  2376. if self.get_param('ignore_no_formats_error'):
  2377. fatal = False
  2378. res = self._download_xml_handle(
  2379. mpd_url, video_id,
  2380. note='Downloading MPD manifest' if note is None else note,
  2381. errnote='Failed to download MPD manifest' if errnote is None else errnote,
  2382. fatal=fatal, data=data, headers=headers, query=query)
  2383. if res is False:
  2384. return []
  2385. mpd_doc, urlh = res
  2386. if mpd_doc is None:
  2387. return []
  2388. # We could have been redirected to a new url when we retrieved our mpd file.
  2389. mpd_url = urlh.url
  2390. mpd_base_url = base_url(mpd_url)
  2391. return self._parse_mpd_periods(mpd_doc, mpd_id, mpd_base_url, mpd_url)
  2392. def _parse_mpd_formats(self, *args, **kwargs):
  2393. fmts, subs = self._parse_mpd_formats_and_subtitles(*args, **kwargs)
  2394. if subs:
  2395. self._report_ignoring_subs('DASH')
  2396. return fmts
  2397. def _parse_mpd_formats_and_subtitles(self, *args, **kwargs):
  2398. periods = self._parse_mpd_periods(*args, **kwargs)
  2399. return self._merge_mpd_periods(periods)
  2400. def _merge_mpd_periods(self, periods):
  2401. """
  2402. Combine all formats and subtitles from an MPD manifest into a single list,
  2403. by concatenate streams with similar formats.
  2404. """
  2405. formats, subtitles = {}, {}
  2406. for period in periods:
  2407. for f in period['formats']:
  2408. assert 'is_dash_periods' not in f, 'format already processed'
  2409. f['is_dash_periods'] = True
  2410. format_key = tuple(v for k, v in f.items() if k not in (
  2411. ('format_id', 'fragments', 'manifest_stream_number')))
  2412. if format_key not in formats:
  2413. formats[format_key] = f
  2414. elif 'fragments' in f:
  2415. formats[format_key].setdefault('fragments', []).extend(f['fragments'])
  2416. if subtitles and period['subtitles']:
  2417. self.report_warning(bug_reports_message(
  2418. 'Found subtitles in multiple periods in the DASH manifest; '
  2419. 'if part of the subtitles are missing,',
  2420. ), only_once=True)
  2421. for sub_lang, sub_info in period['subtitles'].items():
  2422. subtitles.setdefault(sub_lang, []).extend(sub_info)
  2423. return list(formats.values()), subtitles
  2424. def _parse_mpd_periods(self, mpd_doc, mpd_id=None, mpd_base_url='', mpd_url=None):
  2425. """
  2426. Parse formats from MPD manifest.
  2427. References:
  2428. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  2429. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  2430. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  2431. """
  2432. if not self.get_param('dynamic_mpd', True):
  2433. if mpd_doc.get('type') == 'dynamic':
  2434. return [], {}
  2435. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  2436. def _add_ns(path):
  2437. return self._xpath_ns(path, namespace)
  2438. def is_drm_protected(element):
  2439. return element.find(_add_ns('ContentProtection')) is not None
  2440. def extract_multisegment_info(element, ms_parent_info):
  2441. ms_info = ms_parent_info.copy()
  2442. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  2443. # common attributes and elements. We will only extract relevant
  2444. # for us.
  2445. def extract_common(source):
  2446. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  2447. if segment_timeline is not None:
  2448. s_e = segment_timeline.findall(_add_ns('S'))
  2449. if s_e:
  2450. ms_info['total_number'] = 0
  2451. ms_info['s'] = []
  2452. for s in s_e:
  2453. r = int(s.get('r', 0))
  2454. ms_info['total_number'] += 1 + r
  2455. ms_info['s'].append({
  2456. 't': int(s.get('t', 0)),
  2457. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  2458. 'd': int(s.attrib['d']),
  2459. 'r': r,
  2460. })
  2461. start_number = source.get('startNumber')
  2462. if start_number:
  2463. ms_info['start_number'] = int(start_number)
  2464. timescale = source.get('timescale')
  2465. if timescale:
  2466. ms_info['timescale'] = int(timescale)
  2467. segment_duration = source.get('duration')
  2468. if segment_duration:
  2469. ms_info['segment_duration'] = float(segment_duration)
  2470. def extract_Initialization(source):
  2471. initialization = source.find(_add_ns('Initialization'))
  2472. if initialization is not None:
  2473. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  2474. segment_list = element.find(_add_ns('SegmentList'))
  2475. if segment_list is not None:
  2476. extract_common(segment_list)
  2477. extract_Initialization(segment_list)
  2478. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  2479. if segment_urls_e:
  2480. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  2481. else:
  2482. segment_template = element.find(_add_ns('SegmentTemplate'))
  2483. if segment_template is not None:
  2484. extract_common(segment_template)
  2485. media = segment_template.get('media')
  2486. if media:
  2487. ms_info['media'] = media
  2488. initialization = segment_template.get('initialization')
  2489. if initialization:
  2490. ms_info['initialization'] = initialization
  2491. else:
  2492. extract_Initialization(segment_template)
  2493. return ms_info
  2494. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  2495. stream_numbers = collections.defaultdict(int)
  2496. for period_idx, period in enumerate(mpd_doc.findall(_add_ns('Period'))):
  2497. period_entry = {
  2498. 'id': period.get('id', f'period-{period_idx}'),
  2499. 'formats': [],
  2500. 'subtitles': collections.defaultdict(list),
  2501. }
  2502. period_duration = parse_duration(period.get('duration')) or mpd_duration
  2503. period_ms_info = extract_multisegment_info(period, {
  2504. 'start_number': 1,
  2505. 'timescale': 1,
  2506. })
  2507. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  2508. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  2509. for representation in adaptation_set.findall(_add_ns('Representation')):
  2510. representation_attrib = adaptation_set.attrib.copy()
  2511. representation_attrib.update(representation.attrib)
  2512. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  2513. mime_type = representation_attrib['mimeType']
  2514. content_type = representation_attrib.get('contentType', mime_type.split('/')[0])
  2515. codec_str = representation_attrib.get('codecs', '')
  2516. # Some kind of binary subtitle found in some youtube livestreams
  2517. if mime_type == 'application/x-rawcc':
  2518. codecs = {'scodec': codec_str}
  2519. else:
  2520. codecs = parse_codecs(codec_str)
  2521. if content_type not in ('video', 'audio', 'text'):
  2522. if mime_type == 'image/jpeg':
  2523. content_type = mime_type
  2524. elif codecs.get('vcodec', 'none') != 'none':
  2525. content_type = 'video'
  2526. elif codecs.get('acodec', 'none') != 'none':
  2527. content_type = 'audio'
  2528. elif codecs.get('scodec', 'none') != 'none':
  2529. content_type = 'text'
  2530. elif mimetype2ext(mime_type) in ('tt', 'dfxp', 'ttml', 'xml', 'json'):
  2531. content_type = 'text'
  2532. else:
  2533. self.report_warning(f'Unknown MIME type {mime_type} in DASH manifest')
  2534. continue
  2535. base_url = ''
  2536. for element in (representation, adaptation_set, period, mpd_doc):
  2537. base_url_e = element.find(_add_ns('BaseURL'))
  2538. if try_call(lambda: base_url_e.text) is not None:
  2539. base_url = base_url_e.text + base_url
  2540. if re.match(r'https?://', base_url):
  2541. break
  2542. if mpd_base_url and base_url.startswith('/'):
  2543. base_url = urllib.parse.urljoin(mpd_base_url, base_url)
  2544. elif mpd_base_url and not re.match(r'https?://', base_url):
  2545. if not mpd_base_url.endswith('/'):
  2546. mpd_base_url += '/'
  2547. base_url = mpd_base_url + base_url
  2548. representation_id = representation_attrib.get('id')
  2549. lang = representation_attrib.get('lang')
  2550. url_el = representation.find(_add_ns('BaseURL'))
  2551. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  2552. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  2553. if representation_id is not None:
  2554. format_id = representation_id
  2555. else:
  2556. format_id = content_type
  2557. if mpd_id:
  2558. format_id = mpd_id + '-' + format_id
  2559. if content_type in ('video', 'audio'):
  2560. f = {
  2561. 'format_id': format_id,
  2562. 'manifest_url': mpd_url,
  2563. 'ext': mimetype2ext(mime_type),
  2564. 'width': int_or_none(representation_attrib.get('width')),
  2565. 'height': int_or_none(representation_attrib.get('height')),
  2566. 'tbr': float_or_none(bandwidth, 1000),
  2567. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  2568. 'fps': int_or_none(representation_attrib.get('frameRate')),
  2569. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  2570. 'format_note': f'DASH {content_type}',
  2571. 'filesize': filesize,
  2572. 'container': mimetype2ext(mime_type) + '_dash',
  2573. **codecs,
  2574. }
  2575. elif content_type == 'text':
  2576. f = {
  2577. 'ext': mimetype2ext(mime_type),
  2578. 'manifest_url': mpd_url,
  2579. 'filesize': filesize,
  2580. }
  2581. elif content_type == 'image/jpeg':
  2582. # See test case in VikiIE
  2583. # https://www.viki.com/videos/1175236v-choosing-spouse-by-lottery-episode-1
  2584. f = {
  2585. 'format_id': format_id,
  2586. 'ext': 'mhtml',
  2587. 'manifest_url': mpd_url,
  2588. 'format_note': 'DASH storyboards (jpeg)',
  2589. 'acodec': 'none',
  2590. 'vcodec': 'none',
  2591. }
  2592. if is_drm_protected(adaptation_set) or is_drm_protected(representation):
  2593. f['has_drm'] = True
  2594. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  2595. def prepare_template(template_name, identifiers):
  2596. tmpl = representation_ms_info[template_name]
  2597. if representation_id is not None:
  2598. tmpl = tmpl.replace('$RepresentationID$', representation_id)
  2599. # First of, % characters outside $...$ templates
  2600. # must be escaped by doubling for proper processing
  2601. # by % operator string formatting used further (see
  2602. # https://github.com/ytdl-org/youtube-dl/issues/16867).
  2603. t = ''
  2604. in_template = False
  2605. for c in tmpl:
  2606. t += c
  2607. if c == '$':
  2608. in_template = not in_template
  2609. elif c == '%' and not in_template:
  2610. t += c
  2611. # Next, $...$ templates are translated to their
  2612. # %(...) counterparts to be used with % operator
  2613. t = re.sub(r'\$({})\$'.format('|'.join(identifiers)), r'%(\1)d', t)
  2614. t = re.sub(r'\$({})%([^$]+)\$'.format('|'.join(identifiers)), r'%(\1)\2', t)
  2615. t.replace('$$', '$')
  2616. return t
  2617. # @initialization is a regular template like @media one
  2618. # so it should be handled just the same way (see
  2619. # https://github.com/ytdl-org/youtube-dl/issues/11605)
  2620. if 'initialization' in representation_ms_info:
  2621. initialization_template = prepare_template(
  2622. 'initialization',
  2623. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  2624. # $Time$ shall not be included for @initialization thus
  2625. # only $Bandwidth$ remains
  2626. ('Bandwidth', ))
  2627. representation_ms_info['initialization_url'] = initialization_template % {
  2628. 'Bandwidth': bandwidth,
  2629. }
  2630. def location_key(location):
  2631. return 'url' if re.match(r'https?://', location) else 'path'
  2632. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  2633. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  2634. media_location_key = location_key(media_template)
  2635. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  2636. # can't be used at the same time
  2637. if '%(Number' in media_template and 's' not in representation_ms_info:
  2638. segment_duration = None
  2639. if 'total_number' not in representation_ms_info and 'segment_duration' in representation_ms_info:
  2640. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  2641. representation_ms_info['total_number'] = math.ceil(float_or_none(period_duration, segment_duration, default=0))
  2642. representation_ms_info['fragments'] = [{
  2643. media_location_key: media_template % {
  2644. 'Number': segment_number,
  2645. 'Bandwidth': bandwidth,
  2646. },
  2647. 'duration': segment_duration,
  2648. } for segment_number in range(
  2649. representation_ms_info['start_number'],
  2650. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  2651. else:
  2652. # $Number*$ or $Time$ in media template with S list available
  2653. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  2654. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  2655. representation_ms_info['fragments'] = []
  2656. segment_time = 0
  2657. segment_d = None
  2658. segment_number = representation_ms_info['start_number']
  2659. def add_segment_url():
  2660. segment_url = media_template % {
  2661. 'Time': segment_time,
  2662. 'Bandwidth': bandwidth,
  2663. 'Number': segment_number,
  2664. }
  2665. representation_ms_info['fragments'].append({
  2666. media_location_key: segment_url,
  2667. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  2668. })
  2669. for s in representation_ms_info['s']:
  2670. segment_time = s.get('t') or segment_time
  2671. segment_d = s['d']
  2672. add_segment_url()
  2673. segment_number += 1
  2674. for _ in range(s.get('r', 0)):
  2675. segment_time += segment_d
  2676. add_segment_url()
  2677. segment_number += 1
  2678. segment_time += segment_d
  2679. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  2680. # No media template,
  2681. # e.g. https://www.youtube.com/watch?v=iXZV5uAYMJI
  2682. # or any YouTube dashsegments video
  2683. fragments = []
  2684. segment_index = 0
  2685. timescale = representation_ms_info['timescale']
  2686. for s in representation_ms_info['s']:
  2687. duration = float_or_none(s['d'], timescale)
  2688. for _ in range(s.get('r', 0) + 1):
  2689. segment_uri = representation_ms_info['segment_urls'][segment_index]
  2690. fragments.append({
  2691. location_key(segment_uri): segment_uri,
  2692. 'duration': duration,
  2693. })
  2694. segment_index += 1
  2695. representation_ms_info['fragments'] = fragments
  2696. elif 'segment_urls' in representation_ms_info:
  2697. # Segment URLs with no SegmentTimeline
  2698. # E.g. https://www.seznam.cz/zpravy/clanek/cesko-zasahne-vitr-o-sile-vichrice-muze-byt-i-zivotu-nebezpecny-39091
  2699. # https://github.com/ytdl-org/youtube-dl/pull/14844
  2700. fragments = []
  2701. segment_duration = float_or_none(
  2702. representation_ms_info['segment_duration'],
  2703. representation_ms_info['timescale']) if 'segment_duration' in representation_ms_info else None
  2704. for segment_url in representation_ms_info['segment_urls']:
  2705. fragment = {
  2706. location_key(segment_url): segment_url,
  2707. }
  2708. if segment_duration:
  2709. fragment['duration'] = segment_duration
  2710. fragments.append(fragment)
  2711. representation_ms_info['fragments'] = fragments
  2712. # If there is a fragments key available then we correctly recognized fragmented media.
  2713. # Otherwise we will assume unfragmented media with direct access. Technically, such
  2714. # assumption is not necessarily correct since we may simply have no support for
  2715. # some forms of fragmented media renditions yet, but for now we'll use this fallback.
  2716. if 'fragments' in representation_ms_info:
  2717. f.update({
  2718. # NB: mpd_url may be empty when MPD manifest is parsed from a string
  2719. 'url': mpd_url or base_url,
  2720. 'fragment_base_url': base_url,
  2721. 'fragments': [],
  2722. 'protocol': 'http_dash_segments' if mime_type != 'image/jpeg' else 'mhtml',
  2723. })
  2724. if 'initialization_url' in representation_ms_info:
  2725. initialization_url = representation_ms_info['initialization_url']
  2726. if not f.get('url'):
  2727. f['url'] = initialization_url
  2728. f['fragments'].append({location_key(initialization_url): initialization_url})
  2729. f['fragments'].extend(representation_ms_info['fragments'])
  2730. if not period_duration:
  2731. period_duration = try_get(
  2732. representation_ms_info,
  2733. lambda r: sum(frag['duration'] for frag in r['fragments']), float)
  2734. else:
  2735. # Assuming direct URL to unfragmented media.
  2736. f['url'] = base_url
  2737. if content_type in ('video', 'audio', 'image/jpeg'):
  2738. f['manifest_stream_number'] = stream_numbers[f['url']]
  2739. stream_numbers[f['url']] += 1
  2740. period_entry['formats'].append(f)
  2741. elif content_type == 'text':
  2742. period_entry['subtitles'][lang or 'und'].append(f)
  2743. yield period_entry
  2744. def _extract_ism_formats(self, *args, **kwargs):
  2745. fmts, subs = self._extract_ism_formats_and_subtitles(*args, **kwargs)
  2746. if subs:
  2747. self._report_ignoring_subs('ISM')
  2748. return fmts
  2749. def _extract_ism_formats_and_subtitles(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  2750. if self.get_param('ignore_no_formats_error'):
  2751. fatal = False
  2752. res = self._download_xml_handle(
  2753. ism_url, video_id,
  2754. note='Downloading ISM manifest' if note is None else note,
  2755. errnote='Failed to download ISM manifest' if errnote is None else errnote,
  2756. fatal=fatal, data=data, headers=headers, query=query)
  2757. if res is False:
  2758. return [], {}
  2759. ism_doc, urlh = res
  2760. if ism_doc is None:
  2761. return [], {}
  2762. return self._parse_ism_formats_and_subtitles(ism_doc, urlh.url, ism_id)
  2763. def _parse_ism_formats_and_subtitles(self, ism_doc, ism_url, ism_id=None):
  2764. """
  2765. Parse formats from ISM manifest.
  2766. References:
  2767. 1. [MS-SSTR]: Smooth Streaming Protocol,
  2768. https://msdn.microsoft.com/en-us/library/ff469518.aspx
  2769. """
  2770. if ism_doc.get('IsLive') == 'TRUE':
  2771. return [], {}
  2772. duration = int(ism_doc.attrib['Duration'])
  2773. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  2774. formats = []
  2775. subtitles = {}
  2776. for stream in ism_doc.findall('StreamIndex'):
  2777. stream_type = stream.get('Type')
  2778. if stream_type not in ('video', 'audio', 'text'):
  2779. continue
  2780. url_pattern = stream.attrib['Url']
  2781. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  2782. stream_name = stream.get('Name')
  2783. # IsmFD expects ISO 639 Set 2 language codes (3-character length)
  2784. # See: https://github.com/yt-dlp/yt-dlp/issues/11356
  2785. stream_language = stream.get('Language') or 'und'
  2786. if len(stream_language) != 3:
  2787. stream_language = ISO639Utils.short2long(stream_language) or 'und'
  2788. for track in stream.findall('QualityLevel'):
  2789. KNOWN_TAGS = {'255': 'AACL', '65534': 'EC-3'}
  2790. fourcc = track.get('FourCC') or KNOWN_TAGS.get(track.get('AudioTag'))
  2791. # TODO: add support for WVC1 and WMAP
  2792. if fourcc not in ('H264', 'AVC1', 'AACL', 'TTML', 'EC-3'):
  2793. self.report_warning(f'{fourcc} is not a supported codec')
  2794. continue
  2795. tbr = int(track.attrib['Bitrate']) // 1000
  2796. # [1] does not mention Width and Height attributes. However,
  2797. # they're often present while MaxWidth and MaxHeight are
  2798. # missing, so should be used as fallbacks
  2799. width = int_or_none(track.get('MaxWidth') or track.get('Width'))
  2800. height = int_or_none(track.get('MaxHeight') or track.get('Height'))
  2801. sampling_rate = int_or_none(track.get('SamplingRate'))
  2802. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  2803. track_url_pattern = urllib.parse.urljoin(ism_url, track_url_pattern)
  2804. fragments = []
  2805. fragment_ctx = {
  2806. 'time': 0,
  2807. }
  2808. stream_fragments = stream.findall('c')
  2809. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  2810. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  2811. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  2812. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  2813. if not fragment_ctx['duration']:
  2814. try:
  2815. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  2816. except IndexError:
  2817. next_fragment_time = duration
  2818. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  2819. for _ in range(fragment_repeat):
  2820. fragments.append({
  2821. 'url': re.sub(r'{start[ _]time}', str(fragment_ctx['time']), track_url_pattern),
  2822. 'duration': fragment_ctx['duration'] / stream_timescale,
  2823. })
  2824. fragment_ctx['time'] += fragment_ctx['duration']
  2825. if stream_type == 'text':
  2826. subtitles.setdefault(stream_language, []).append({
  2827. 'ext': 'ismt',
  2828. 'protocol': 'ism',
  2829. 'url': ism_url,
  2830. 'manifest_url': ism_url,
  2831. 'fragments': fragments,
  2832. '_download_params': {
  2833. 'stream_type': stream_type,
  2834. 'duration': duration,
  2835. 'timescale': stream_timescale,
  2836. 'fourcc': fourcc,
  2837. 'language': stream_language,
  2838. 'codec_private_data': track.get('CodecPrivateData'),
  2839. },
  2840. })
  2841. elif stream_type in ('video', 'audio'):
  2842. formats.append({
  2843. 'format_id': join_nonempty(ism_id, stream_name, tbr),
  2844. 'url': ism_url,
  2845. 'manifest_url': ism_url,
  2846. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  2847. 'width': width,
  2848. 'height': height,
  2849. 'tbr': tbr,
  2850. 'asr': sampling_rate,
  2851. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  2852. 'acodec': 'none' if stream_type == 'video' else fourcc,
  2853. 'protocol': 'ism',
  2854. 'fragments': fragments,
  2855. 'has_drm': ism_doc.find('Protection') is not None,
  2856. 'language': stream_language,
  2857. 'audio_channels': int_or_none(track.get('Channels')),
  2858. '_download_params': {
  2859. 'stream_type': stream_type,
  2860. 'duration': duration,
  2861. 'timescale': stream_timescale,
  2862. 'width': width or 0,
  2863. 'height': height or 0,
  2864. 'fourcc': fourcc,
  2865. 'language': stream_language,
  2866. 'codec_private_data': track.get('CodecPrivateData'),
  2867. 'sampling_rate': sampling_rate,
  2868. 'channels': int_or_none(track.get('Channels', 2)),
  2869. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  2870. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  2871. },
  2872. })
  2873. return formats, subtitles
  2874. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8_native', mpd_id=None, preference=None, quality=None, _headers=None):
  2875. def absolute_url(item_url):
  2876. return urljoin(base_url, item_url)
  2877. def parse_content_type(content_type):
  2878. if not content_type:
  2879. return {}
  2880. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  2881. if ctr:
  2882. mimetype, codecs = ctr.groups()
  2883. f = parse_codecs(codecs)
  2884. f['ext'] = mimetype2ext(mimetype)
  2885. return f
  2886. return {}
  2887. def _media_formats(src, cur_media_type, type_info=None):
  2888. type_info = type_info or {}
  2889. full_url = absolute_url(src)
  2890. ext = type_info.get('ext') or determine_ext(full_url)
  2891. if ext == 'm3u8':
  2892. is_plain_url = False
  2893. formats = self._extract_m3u8_formats(
  2894. full_url, video_id, ext='mp4',
  2895. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  2896. preference=preference, quality=quality, fatal=False, headers=_headers)
  2897. elif ext == 'mpd':
  2898. is_plain_url = False
  2899. formats = self._extract_mpd_formats(
  2900. full_url, video_id, mpd_id=mpd_id, fatal=False, headers=_headers)
  2901. else:
  2902. is_plain_url = True
  2903. formats = [{
  2904. 'url': full_url,
  2905. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  2906. 'ext': ext,
  2907. }]
  2908. return is_plain_url, formats
  2909. entries = []
  2910. # amp-video and amp-audio are very similar to their HTML5 counterparts
  2911. # so we will include them right here (see
  2912. # https://www.ampproject.org/docs/reference/components/amp-video)
  2913. # For dl8-* tags see https://delight-vr.com/documentation/dl8-video/
  2914. _MEDIA_TAG_NAME_RE = r'(?:(?:amp|dl8(?:-live)?)-)?(video|audio)'
  2915. media_tags = [(media_tag, media_tag_name, media_type, '')
  2916. for media_tag, media_tag_name, media_type
  2917. in re.findall(rf'(?s)(<({_MEDIA_TAG_NAME_RE})[^>]*/>)', webpage)]
  2918. media_tags.extend(re.findall(
  2919. # We only allow video|audio followed by a whitespace or '>'.
  2920. # Allowing more characters may end up in significant slow down (see
  2921. # https://github.com/ytdl-org/youtube-dl/issues/11979,
  2922. # e.g. http://www.porntrex.com/maps/videositemap.xml).
  2923. rf'(?s)(<(?P<tag>{_MEDIA_TAG_NAME_RE})(?:\s+[^>]*)?>)(.*?)</(?P=tag)>', webpage))
  2924. for media_tag, _, media_type, media_content in media_tags:
  2925. media_info = {
  2926. 'formats': [],
  2927. 'subtitles': {},
  2928. }
  2929. media_attributes = extract_attributes(media_tag)
  2930. src = strip_or_none(dict_get(media_attributes, ('src', 'data-video-src', 'data-src', 'data-source')))
  2931. if src:
  2932. f = parse_content_type(media_attributes.get('type'))
  2933. _, formats = _media_formats(src, media_type, f)
  2934. media_info['formats'].extend(formats)
  2935. media_info['thumbnail'] = absolute_url(media_attributes.get('poster'))
  2936. if media_content:
  2937. for source_tag in re.findall(r'<source[^>]+>', media_content):
  2938. s_attr = extract_attributes(source_tag)
  2939. # data-video-src and data-src are non standard but seen
  2940. # several times in the wild
  2941. src = strip_or_none(dict_get(s_attr, ('src', 'data-video-src', 'data-src', 'data-source')))
  2942. if not src:
  2943. continue
  2944. f = parse_content_type(s_attr.get('type'))
  2945. is_plain_url, formats = _media_formats(src, media_type, f)
  2946. if is_plain_url:
  2947. # width, height, res, label and title attributes are
  2948. # all not standard but seen several times in the wild
  2949. labels = [
  2950. s_attr.get(lbl)
  2951. for lbl in ('label', 'title')
  2952. if str_or_none(s_attr.get(lbl))
  2953. ]
  2954. width = int_or_none(s_attr.get('width'))
  2955. height = (int_or_none(s_attr.get('height'))
  2956. or int_or_none(s_attr.get('res')))
  2957. if not width or not height:
  2958. for lbl in labels:
  2959. resolution = parse_resolution(lbl)
  2960. if not resolution:
  2961. continue
  2962. width = width or resolution.get('width')
  2963. height = height or resolution.get('height')
  2964. for lbl in labels:
  2965. tbr = parse_bitrate(lbl)
  2966. if tbr:
  2967. break
  2968. else:
  2969. tbr = None
  2970. f.update({
  2971. 'width': width,
  2972. 'height': height,
  2973. 'tbr': tbr,
  2974. 'format_id': s_attr.get('label') or s_attr.get('title'),
  2975. })
  2976. f.update(formats[0])
  2977. media_info['formats'].append(f)
  2978. else:
  2979. media_info['formats'].extend(formats)
  2980. for track_tag in re.findall(r'<track[^>]+>', media_content):
  2981. track_attributes = extract_attributes(track_tag)
  2982. kind = track_attributes.get('kind')
  2983. if not kind or kind in ('subtitles', 'captions'):
  2984. src = strip_or_none(track_attributes.get('src'))
  2985. if not src:
  2986. continue
  2987. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  2988. media_info['subtitles'].setdefault(lang, []).append({
  2989. 'url': absolute_url(src),
  2990. })
  2991. for f in media_info['formats']:
  2992. f.setdefault('http_headers', {})['Referer'] = base_url
  2993. if _headers:
  2994. f['http_headers'].update(_headers)
  2995. if media_info['formats'] or media_info['subtitles']:
  2996. entries.append(media_info)
  2997. return entries
  2998. def _extract_akamai_formats(self, *args, **kwargs):
  2999. fmts, subs = self._extract_akamai_formats_and_subtitles(*args, **kwargs)
  3000. if subs:
  3001. self._report_ignoring_subs('akamai')
  3002. return fmts
  3003. def _extract_akamai_formats_and_subtitles(self, manifest_url, video_id, hosts={}):
  3004. signed = 'hdnea=' in manifest_url
  3005. if not signed:
  3006. # https://learn.akamai.com/en-us/webhelp/media-services-on-demand/stream-packaging-user-guide/GUID-BE6C0F73-1E06-483B-B0EA-57984B91B7F9.html
  3007. manifest_url = re.sub(
  3008. r'(?:b=[\d,-]+|(?:__a__|attributes)=off|__b__=\d+)&?',
  3009. '', manifest_url).strip('?')
  3010. formats = []
  3011. subtitles = {}
  3012. hdcore_sign = 'hdcore=3.7.0'
  3013. f4m_url = re.sub(r'(https?://[^/]+)/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  3014. hds_host = hosts.get('hds')
  3015. if hds_host:
  3016. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  3017. if 'hdcore=' not in f4m_url:
  3018. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  3019. f4m_formats = self._extract_f4m_formats(
  3020. f4m_url, video_id, f4m_id='hds', fatal=False)
  3021. for entry in f4m_formats:
  3022. entry.update({'extra_param_to_segment_url': hdcore_sign})
  3023. formats.extend(f4m_formats)
  3024. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  3025. hls_host = hosts.get('hls')
  3026. if hls_host:
  3027. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  3028. m3u8_formats, m3u8_subtitles = self._extract_m3u8_formats_and_subtitles(
  3029. m3u8_url, video_id, 'mp4', 'm3u8_native',
  3030. m3u8_id='hls', fatal=False)
  3031. formats.extend(m3u8_formats)
  3032. subtitles = self._merge_subtitles(subtitles, m3u8_subtitles)
  3033. http_host = hosts.get('http')
  3034. if http_host and m3u8_formats and not signed:
  3035. REPL_REGEX = r'https?://[^/]+/i/([^,]+),([^/]+),([^/]+)\.csmil/.+'
  3036. qualities = re.match(REPL_REGEX, m3u8_url).group(2).split(',')
  3037. qualities_length = len(qualities)
  3038. if len(m3u8_formats) in (qualities_length, qualities_length + 1):
  3039. i = 0
  3040. for f in m3u8_formats:
  3041. if f['vcodec'] != 'none':
  3042. for protocol in ('http', 'https'):
  3043. http_f = f.copy()
  3044. del http_f['manifest_url']
  3045. http_url = re.sub(
  3046. REPL_REGEX, protocol + fr'://{http_host}/\g<1>{qualities[i]}\3', f['url'])
  3047. http_f.update({
  3048. 'format_id': http_f['format_id'].replace('hls-', protocol + '-'),
  3049. 'url': http_url,
  3050. 'protocol': protocol,
  3051. })
  3052. formats.append(http_f)
  3053. i += 1
  3054. return formats, subtitles
  3055. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  3056. query = urllib.parse.urlparse(url).query
  3057. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  3058. mobj = re.search(
  3059. r'(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)', url)
  3060. url_base = mobj.group('url')
  3061. http_base_url = '{}{}:{}'.format('http', mobj.group('s') or '', url_base)
  3062. formats = []
  3063. def manifest_url(manifest):
  3064. m_url = f'{http_base_url}/{manifest}'
  3065. if query:
  3066. m_url += f'?{query}'
  3067. return m_url
  3068. if 'm3u8' not in skip_protocols:
  3069. formats.extend(self._extract_m3u8_formats(
  3070. manifest_url('playlist.m3u8'), video_id, 'mp4',
  3071. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  3072. if 'f4m' not in skip_protocols:
  3073. formats.extend(self._extract_f4m_formats(
  3074. manifest_url('manifest.f4m'),
  3075. video_id, f4m_id='hds', fatal=False))
  3076. if 'dash' not in skip_protocols:
  3077. formats.extend(self._extract_mpd_formats(
  3078. manifest_url('manifest.mpd'),
  3079. video_id, mpd_id='dash', fatal=False))
  3080. if re.search(r'(?:/smil:|\.smil)', url_base):
  3081. if 'smil' not in skip_protocols:
  3082. rtmp_formats = self._extract_smil_formats(
  3083. manifest_url('jwplayer.smil'),
  3084. video_id, fatal=False)
  3085. for rtmp_format in rtmp_formats:
  3086. rtsp_format = rtmp_format.copy()
  3087. rtsp_format['url'] = '{}/{}'.format(rtmp_format['url'], rtmp_format['play_path'])
  3088. del rtsp_format['play_path']
  3089. del rtsp_format['ext']
  3090. rtsp_format.update({
  3091. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  3092. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  3093. 'protocol': 'rtsp',
  3094. })
  3095. formats.extend([rtmp_format, rtsp_format])
  3096. else:
  3097. for protocol in ('rtmp', 'rtsp'):
  3098. if protocol not in skip_protocols:
  3099. formats.append({
  3100. 'url': f'{protocol}:{url_base}',
  3101. 'format_id': protocol,
  3102. 'protocol': protocol,
  3103. })
  3104. return formats
  3105. def _find_jwplayer_data(self, webpage, video_id=None, transform_source=js_to_json):
  3106. return self._search_json(
  3107. r'''(?<!-)\bjwplayer\s*\(\s*(?P<q>'|")(?!(?P=q)).+(?P=q)\s*\)(?:(?!</script>).)*?\.\s*(?:setup\s*\(|(?P<load>load)\s*\(\s*\[)''',
  3108. webpage, 'JWPlayer data', video_id,
  3109. # must be a {...} or sequence, ending
  3110. contains_pattern=r'\{(?s:.*)}(?(load)(?:\s*,\s*\{(?s:.*)})*)', end_pattern=r'(?(load)\]|\))',
  3111. transform_source=transform_source, default=None)
  3112. def _extract_jwplayer_data(self, webpage, video_id, *args, transform_source=js_to_json, **kwargs):
  3113. jwplayer_data = self._find_jwplayer_data(
  3114. webpage, video_id, transform_source=transform_source)
  3115. return self._parse_jwplayer_data(
  3116. jwplayer_data, video_id, *args, **kwargs)
  3117. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  3118. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3119. entries = []
  3120. if not isinstance(jwplayer_data, dict):
  3121. return entries
  3122. playlist_items = jwplayer_data.get('playlist')
  3123. # JWPlayer backward compatibility: single playlist item/flattened playlists
  3124. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  3125. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  3126. if not isinstance(playlist_items, list):
  3127. playlist_items = (playlist_items or jwplayer_data, )
  3128. for video_data in playlist_items:
  3129. if not isinstance(video_data, dict):
  3130. continue
  3131. # JWPlayer backward compatibility: flattened sources
  3132. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  3133. if 'sources' not in video_data:
  3134. video_data['sources'] = [video_data]
  3135. this_video_id = video_id or video_data['mediaid']
  3136. formats = self._parse_jwplayer_formats(
  3137. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  3138. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  3139. subtitles = {}
  3140. for track in traverse_obj(video_data, (
  3141. 'tracks', lambda _, v: v['kind'].lower() in ('captions', 'subtitles'))):
  3142. track_url = urljoin(base_url, track.get('file'))
  3143. if not track_url:
  3144. continue
  3145. subtitles.setdefault(track.get('label') or 'en', []).append({
  3146. 'url': self._proto_relative_url(track_url),
  3147. })
  3148. entry = {
  3149. 'id': this_video_id,
  3150. 'title': unescapeHTML(video_data['title'] if require_title else video_data.get('title')),
  3151. 'description': clean_html(video_data.get('description')),
  3152. 'thumbnail': urljoin(base_url, self._proto_relative_url(video_data.get('image'))),
  3153. 'timestamp': int_or_none(video_data.get('pubdate')),
  3154. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  3155. 'subtitles': subtitles,
  3156. 'alt_title': clean_html(video_data.get('subtitle')), # attributes used e.g. by Tele5 ...
  3157. 'genre': clean_html(video_data.get('genre')),
  3158. 'channel': clean_html(dict_get(video_data, ('category', 'channel'))),
  3159. 'season_number': int_or_none(video_data.get('season')),
  3160. 'episode_number': int_or_none(video_data.get('episode')),
  3161. 'release_year': int_or_none(video_data.get('releasedate')),
  3162. 'age_limit': int_or_none(video_data.get('age_restriction')),
  3163. }
  3164. # https://github.com/jwplayer/jwplayer/blob/master/src/js/utils/validator.js#L32
  3165. if len(formats) == 1 and re.search(r'^(?:http|//).*(?:youtube\.com|youtu\.be)/.+', formats[0]['url']):
  3166. entry.update({
  3167. '_type': 'url_transparent',
  3168. 'url': formats[0]['url'],
  3169. })
  3170. else:
  3171. entry['formats'] = formats
  3172. entries.append(entry)
  3173. if len(entries) == 1:
  3174. return entries[0]
  3175. else:
  3176. return self.playlist_result(entries)
  3177. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  3178. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3179. urls = set()
  3180. formats = []
  3181. for source in jwplayer_sources_data:
  3182. if not isinstance(source, dict):
  3183. continue
  3184. source_url = urljoin(
  3185. base_url, self._proto_relative_url(source.get('file')))
  3186. if not source_url or source_url in urls:
  3187. continue
  3188. urls.add(source_url)
  3189. source_type = source.get('type') or ''
  3190. ext = determine_ext(source_url, default_ext=mimetype2ext(source_type))
  3191. if source_type == 'hls' or ext == 'm3u8' or 'format=m3u8-aapl' in source_url:
  3192. formats.extend(self._extract_m3u8_formats(
  3193. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  3194. m3u8_id=m3u8_id, fatal=False))
  3195. elif source_type == 'dash' or ext == 'mpd' or 'format=mpd-time-csf' in source_url:
  3196. formats.extend(self._extract_mpd_formats(
  3197. source_url, video_id, mpd_id=mpd_id, fatal=False))
  3198. elif ext == 'smil':
  3199. formats.extend(self._extract_smil_formats(
  3200. source_url, video_id, fatal=False))
  3201. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  3202. elif source_type.startswith('audio') or ext in (
  3203. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  3204. formats.append({
  3205. 'url': source_url,
  3206. 'vcodec': 'none',
  3207. 'ext': ext,
  3208. })
  3209. else:
  3210. format_id = str_or_none(source.get('label'))
  3211. height = int_or_none(source.get('height'))
  3212. if height is None and format_id:
  3213. # Often no height is provided but there is a label in
  3214. # format like "1080p", "720p SD", or 1080.
  3215. height = parse_resolution(format_id).get('height')
  3216. a_format = {
  3217. 'url': source_url,
  3218. 'width': int_or_none(source.get('width')),
  3219. 'height': height,
  3220. 'tbr': int_or_none(source.get('bitrate'), scale=1000),
  3221. 'filesize': int_or_none(source.get('filesize')),
  3222. 'ext': ext,
  3223. 'format_id': format_id,
  3224. }
  3225. if source_url.startswith('rtmp'):
  3226. a_format['ext'] = 'flv'
  3227. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  3228. # of jwplayer.flash.swf
  3229. rtmp_url_parts = re.split(
  3230. r'((?:mp4|mp3|flv):)', source_url, maxsplit=1)
  3231. if len(rtmp_url_parts) == 3:
  3232. rtmp_url, prefix, play_path = rtmp_url_parts
  3233. a_format.update({
  3234. 'url': rtmp_url,
  3235. 'play_path': prefix + play_path,
  3236. })
  3237. if rtmp_params:
  3238. a_format.update(rtmp_params)
  3239. formats.append(a_format)
  3240. return formats
  3241. def _live_title(self, name):
  3242. self._downloader.deprecation_warning('yt_dlp.InfoExtractor._live_title is deprecated and does not work as expected')
  3243. return name
  3244. def _int(self, v, name, fatal=False, **kwargs):
  3245. res = int_or_none(v, **kwargs)
  3246. if res is None:
  3247. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3248. if fatal:
  3249. raise ExtractorError(msg)
  3250. else:
  3251. self.report_warning(msg)
  3252. return res
  3253. def _float(self, v, name, fatal=False, **kwargs):
  3254. res = float_or_none(v, **kwargs)
  3255. if res is None:
  3256. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3257. if fatal:
  3258. raise ExtractorError(msg)
  3259. else:
  3260. self.report_warning(msg)
  3261. return res
  3262. def _set_cookie(self, domain, name, value, expire_time=None, port=None,
  3263. path='/', secure=False, discard=False, rest={}, **kwargs):
  3264. cookie = http.cookiejar.Cookie(
  3265. 0, name, value, port, port is not None, domain, True,
  3266. domain.startswith('.'), path, True, secure, expire_time,
  3267. discard, None, None, rest)
  3268. self.cookiejar.set_cookie(cookie)
  3269. def _get_cookies(self, url):
  3270. """ Return a http.cookies.SimpleCookie with the cookies for the url """
  3271. return LenientSimpleCookie(self._downloader.cookiejar.get_cookie_header(url))
  3272. def _apply_first_set_cookie_header(self, url_handle, cookie):
  3273. """
  3274. Apply first Set-Cookie header instead of the last. Experimental.
  3275. Some sites (e.g. [1-3]) may serve two cookies under the same name
  3276. in Set-Cookie header and expect the first (old) one to be set rather
  3277. than second (new). However, as of RFC6265 the newer one cookie
  3278. should be set into cookie store what actually happens.
  3279. We will workaround this issue by resetting the cookie to
  3280. the first one manually.
  3281. 1. https://new.vk.com/
  3282. 2. https://github.com/ytdl-org/youtube-dl/issues/9841#issuecomment-227871201
  3283. 3. https://learning.oreilly.com/
  3284. """
  3285. for header, cookies in url_handle.headers.items():
  3286. if header.lower() != 'set-cookie':
  3287. continue
  3288. cookies = cookies.encode('iso-8859-1').decode('utf-8')
  3289. cookie_value = re.search(
  3290. rf'{cookie}=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)', cookies)
  3291. if cookie_value:
  3292. value, domain = cookie_value.groups()
  3293. self._set_cookie(domain, cookie, value)
  3294. break
  3295. @classmethod
  3296. def get_testcases(cls, include_onlymatching=False):
  3297. # Do not look in super classes
  3298. t = vars(cls).get('_TEST')
  3299. if t:
  3300. assert not hasattr(cls, '_TESTS'), f'{cls.ie_key()}IE has _TEST and _TESTS'
  3301. tests = [t]
  3302. else:
  3303. tests = vars(cls).get('_TESTS', [])
  3304. for t in tests:
  3305. if not include_onlymatching and t.get('only_matching', False):
  3306. continue
  3307. t['name'] = cls.ie_key()
  3308. yield t
  3309. if getattr(cls, '__wrapped__', None):
  3310. yield from cls.__wrapped__.get_testcases(include_onlymatching)
  3311. @classmethod
  3312. def get_webpage_testcases(cls):
  3313. tests = vars(cls).get('_WEBPAGE_TESTS', [])
  3314. for t in tests:
  3315. t['name'] = cls.ie_key()
  3316. yield t
  3317. if getattr(cls, '__wrapped__', None):
  3318. yield from cls.__wrapped__.get_webpage_testcases()
  3319. @classproperty(cache=True)
  3320. def age_limit(cls):
  3321. """Get age limit from the testcases"""
  3322. return max(traverse_obj(
  3323. (*cls.get_testcases(include_onlymatching=False), *cls.get_webpage_testcases()),
  3324. (..., (('playlist', 0), None), 'info_dict', 'age_limit')) or [0])
  3325. @classproperty(cache=True)
  3326. def _RETURN_TYPE(cls):
  3327. """What the extractor returns: "video", "playlist", "any", or None (Unknown)"""
  3328. tests = tuple(cls.get_testcases(include_onlymatching=False))
  3329. if not tests:
  3330. return None
  3331. elif not any(k.startswith('playlist') for test in tests for k in test):
  3332. return 'video'
  3333. elif all(any(k.startswith('playlist') for k in test) for test in tests):
  3334. return 'playlist'
  3335. return 'any'
  3336. @classmethod
  3337. def is_single_video(cls, url):
  3338. """Returns whether the URL is of a single video, None if unknown"""
  3339. if cls.suitable(url):
  3340. return {'video': True, 'playlist': False}.get(cls._RETURN_TYPE)
  3341. @classmethod
  3342. def is_suitable(cls, age_limit):
  3343. """Test whether the extractor is generally suitable for the given age limit"""
  3344. return not age_restricted(cls.age_limit, age_limit)
  3345. @classmethod
  3346. def description(cls, *, markdown=True, search_examples=None):
  3347. """Description of the extractor"""
  3348. desc = ''
  3349. if cls._NETRC_MACHINE:
  3350. if markdown:
  3351. desc += f' [*{cls._NETRC_MACHINE}*](## "netrc machine")'
  3352. else:
  3353. desc += f' [{cls._NETRC_MACHINE}]'
  3354. if cls.IE_DESC is False:
  3355. desc += ' [HIDDEN]'
  3356. elif cls.IE_DESC:
  3357. desc += f' {cls.IE_DESC}'
  3358. if cls.SEARCH_KEY:
  3359. desc += f'{";" if cls.IE_DESC else ""} "{cls.SEARCH_KEY}:" prefix'
  3360. if search_examples:
  3361. _COUNTS = ('', '5', '10', 'all')
  3362. desc += f' (e.g. "{cls.SEARCH_KEY}{random.choice(_COUNTS)}:{random.choice(search_examples)}")'
  3363. if not cls.working():
  3364. desc += ' (**Currently broken**)' if markdown else ' (Currently broken)'
  3365. # Escape emojis. Ref: https://github.com/github/markup/issues/1153
  3366. name = (' - **{}**'.format(re.sub(r':(\w+:)', ':\u200B\\g<1>', cls.IE_NAME))) if markdown else cls.IE_NAME
  3367. return f'{name}:{desc}' if desc else name
  3368. def extract_subtitles(self, *args, **kwargs):
  3369. if (self.get_param('writesubtitles', False)
  3370. or self.get_param('listsubtitles')):
  3371. return self._get_subtitles(*args, **kwargs)
  3372. return {}
  3373. def _get_subtitles(self, *args, **kwargs):
  3374. raise NotImplementedError('This method must be implemented by subclasses')
  3375. class CommentsDisabled(Exception):
  3376. """Raise in _get_comments if comments are disabled for the video"""
  3377. def extract_comments(self, *args, **kwargs):
  3378. if not self.get_param('getcomments'):
  3379. return None
  3380. generator = self._get_comments(*args, **kwargs)
  3381. def extractor():
  3382. comments = []
  3383. interrupted = True
  3384. try:
  3385. while True:
  3386. comments.append(next(generator))
  3387. except StopIteration:
  3388. interrupted = False
  3389. except KeyboardInterrupt:
  3390. self.to_screen('Interrupted by user')
  3391. except self.CommentsDisabled:
  3392. return {'comments': None, 'comment_count': None}
  3393. except Exception as e:
  3394. if self.get_param('ignoreerrors') is not True:
  3395. raise
  3396. self._downloader.report_error(e)
  3397. comment_count = len(comments)
  3398. self.to_screen(f'Extracted {comment_count} comments')
  3399. return {
  3400. 'comments': comments,
  3401. 'comment_count': None if interrupted else comment_count,
  3402. }
  3403. return extractor
  3404. def _get_comments(self, *args, **kwargs):
  3405. raise NotImplementedError('This method must be implemented by subclasses')
  3406. @staticmethod
  3407. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  3408. """ Merge subtitle items for one language. Items with duplicated URLs/data
  3409. will be dropped. """
  3410. list1_data = {(item.get('url'), item.get('data')) for item in subtitle_list1}
  3411. ret = list(subtitle_list1)
  3412. ret.extend(item for item in subtitle_list2 if (item.get('url'), item.get('data')) not in list1_data)
  3413. return ret
  3414. @classmethod
  3415. def _merge_subtitles(cls, *dicts, target=None):
  3416. """ Merge subtitle dictionaries, language by language. """
  3417. if target is None:
  3418. target = {}
  3419. for d in filter(None, dicts):
  3420. for lang, subs in d.items():
  3421. target[lang] = cls._merge_subtitle_items(target.get(lang, []), subs)
  3422. return target
  3423. def extract_automatic_captions(self, *args, **kwargs):
  3424. if (self.get_param('writeautomaticsub', False)
  3425. or self.get_param('listsubtitles')):
  3426. return self._get_automatic_captions(*args, **kwargs)
  3427. return {}
  3428. def _get_automatic_captions(self, *args, **kwargs):
  3429. raise NotImplementedError('This method must be implemented by subclasses')
  3430. @functools.cached_property
  3431. def _cookies_passed(self):
  3432. """Whether cookies have been passed to YoutubeDL"""
  3433. return self.get_param('cookiefile') is not None or self.get_param('cookiesfrombrowser') is not None
  3434. def mark_watched(self, *args, **kwargs):
  3435. if not self.get_param('mark_watched', False):
  3436. return
  3437. if (self.supports_login() and self._get_login_info()[0] is not None) or self._cookies_passed:
  3438. self._mark_watched(*args, **kwargs)
  3439. def _mark_watched(self, *args, **kwargs):
  3440. raise NotImplementedError('This method must be implemented by subclasses')
  3441. def geo_verification_headers(self):
  3442. headers = {}
  3443. geo_verification_proxy = self.get_param('geo_verification_proxy')
  3444. if geo_verification_proxy:
  3445. headers['Ytdl-request-proxy'] = geo_verification_proxy
  3446. return headers
  3447. @staticmethod
  3448. def _generic_id(url):
  3449. return urllib.parse.unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  3450. def _generic_title(self, url='', webpage='', *, default=None):
  3451. return (self._og_search_title(webpage, default=None)
  3452. or self._html_extract_title(webpage, default=None)
  3453. or urllib.parse.unquote(os.path.splitext(url_basename(url))[0])
  3454. or default)
  3455. def _extract_chapters_helper(self, chapter_list, start_function, title_function, duration, strict=True):
  3456. if not duration:
  3457. return
  3458. chapter_list = [{
  3459. 'start_time': start_function(chapter),
  3460. 'title': title_function(chapter),
  3461. } for chapter in chapter_list or []]
  3462. if strict:
  3463. warn = self.report_warning
  3464. else:
  3465. warn = self.write_debug
  3466. chapter_list.sort(key=lambda c: c['start_time'] or 0)
  3467. chapters = [{'start_time': 0}]
  3468. for idx, chapter in enumerate(chapter_list):
  3469. if chapter['start_time'] is None:
  3470. warn(f'Incomplete chapter {idx}')
  3471. elif chapters[-1]['start_time'] <= chapter['start_time'] <= duration:
  3472. chapters.append(chapter)
  3473. elif chapter not in chapters:
  3474. issue = (f'{chapter["start_time"]} > {duration}' if chapter['start_time'] > duration
  3475. else f'{chapter["start_time"]} < {chapters[-1]["start_time"]}')
  3476. warn(f'Invalid start time ({issue}) for chapter "{chapter["title"]}"')
  3477. return chapters[1:]
  3478. def _extract_chapters_from_description(self, description, duration):
  3479. duration_re = r'(?:\d+:)?\d{1,2}:\d{2}'
  3480. sep_re = r'(?m)^\s*(%s)\b\W*\s(%s)\s*$'
  3481. return self._extract_chapters_helper(
  3482. re.findall(sep_re % (duration_re, r'.+?'), description or ''),
  3483. start_function=lambda x: parse_duration(x[0]), title_function=lambda x: x[1],
  3484. duration=duration, strict=False) or self._extract_chapters_helper(
  3485. re.findall(sep_re % (r'.+?', duration_re), description or ''),
  3486. start_function=lambda x: parse_duration(x[1]), title_function=lambda x: x[0],
  3487. duration=duration, strict=False)
  3488. @staticmethod
  3489. def _availability(is_private=None, needs_premium=None, needs_subscription=None, needs_auth=None, is_unlisted=None):
  3490. all_known = all(
  3491. x is not None for x in
  3492. (is_private, needs_premium, needs_subscription, needs_auth, is_unlisted))
  3493. return (
  3494. 'private' if is_private
  3495. else 'premium_only' if needs_premium
  3496. else 'subscriber_only' if needs_subscription
  3497. else 'needs_auth' if needs_auth
  3498. else 'unlisted' if is_unlisted
  3499. else 'public' if all_known
  3500. else None)
  3501. def _configuration_arg(self, key, default=NO_DEFAULT, *, ie_key=None, casesense=False):
  3502. '''
  3503. @returns A list of values for the extractor argument given by "key"
  3504. or "default" if no such key is present
  3505. @param default The default value to return when the key is not present (default: [])
  3506. @param casesense When false, the values are converted to lower case
  3507. '''
  3508. ie_key = ie_key if isinstance(ie_key, str) else (ie_key or self).ie_key()
  3509. val = traverse_obj(self._downloader.params, ('extractor_args', ie_key.lower(), key))
  3510. if val is None:
  3511. return [] if default is NO_DEFAULT else default
  3512. return list(val) if casesense else [x.lower() for x in val]
  3513. def _yes_playlist(self, playlist_id, video_id, smuggled_data=None, *, playlist_label='playlist', video_label='video'):
  3514. if not playlist_id or not video_id:
  3515. return not video_id
  3516. no_playlist = (smuggled_data or {}).get('force_noplaylist')
  3517. if no_playlist is not None:
  3518. return not no_playlist
  3519. video_id = '' if video_id is True else f' {video_id}'
  3520. playlist_id = '' if playlist_id is True else f' {playlist_id}'
  3521. if self.get_param('noplaylist'):
  3522. self.to_screen(f'Downloading just the {video_label}{video_id} because of --no-playlist')
  3523. return False
  3524. self.to_screen(f'Downloading {playlist_label}{playlist_id} - add --no-playlist to download just the {video_label}{video_id}')
  3525. return True
  3526. def _error_or_warning(self, err, _count=None, _retries=0, *, fatal=True):
  3527. RetryManager.report_retry(
  3528. err, _count or int(fatal), _retries,
  3529. info=self.to_screen, warn=self.report_warning, error=None if fatal else self.report_warning,
  3530. sleep_func=self.get_param('retry_sleep_functions', {}).get('extractor'))
  3531. def RetryManager(self, **kwargs):
  3532. return RetryManager(self.get_param('extractor_retries', 3), self._error_or_warning, **kwargs)
  3533. def _extract_generic_embeds(self, url, *args, info_dict={}, note='Extracting generic embeds', **kwargs):
  3534. display_id = traverse_obj(info_dict, 'display_id', 'id')
  3535. self.to_screen(f'{format_field(display_id, None, "%s: ")}{note}')
  3536. return self._downloader.get_info_extractor('Generic')._extract_embeds(
  3537. smuggle_url(url, {'block_ies': [self.ie_key()]}), *args, **kwargs)
  3538. @classmethod
  3539. def extract_from_webpage(cls, ydl, url, webpage):
  3540. ie = (cls if isinstance(cls._extract_from_webpage, types.MethodType)
  3541. else ydl.get_info_extractor(cls.ie_key()))
  3542. for info in ie._extract_from_webpage(url, webpage) or []:
  3543. # url = None since we do not want to set (webpage/original)_url
  3544. ydl.add_default_extra_info(info, ie, None)
  3545. yield info
  3546. @classmethod
  3547. def _extract_from_webpage(cls, url, webpage):
  3548. for embed_url in orderedSet(
  3549. cls._extract_embed_urls(url, webpage) or [], lazy=True):
  3550. yield cls.url_result(embed_url, None if cls._VALID_URL is False else cls)
  3551. @classmethod
  3552. def _extract_embed_urls(cls, url, webpage):
  3553. """@returns all the embed urls on the webpage"""
  3554. if '_EMBED_URL_RE' not in cls.__dict__:
  3555. assert isinstance(cls._EMBED_REGEX, (list, tuple))
  3556. for idx, regex in enumerate(cls._EMBED_REGEX):
  3557. assert regex.count('(?P<url>') == 1, \
  3558. f'{cls.__name__}._EMBED_REGEX[{idx}] must have exactly 1 url group\n\t{regex}'
  3559. cls._EMBED_URL_RE = tuple(map(re.compile, cls._EMBED_REGEX))
  3560. for regex in cls._EMBED_URL_RE:
  3561. for mobj in regex.finditer(webpage):
  3562. embed_url = urllib.parse.urljoin(url, unescapeHTML(mobj.group('url')))
  3563. if cls._VALID_URL is False or cls.suitable(embed_url):
  3564. yield embed_url
  3565. class StopExtraction(Exception):
  3566. pass
  3567. @classmethod
  3568. def _extract_url(cls, webpage): # TODO: Remove
  3569. """Only for compatibility with some older extractors"""
  3570. return next(iter(cls._extract_embed_urls(None, webpage) or []), None)
  3571. @classmethod
  3572. def __init_subclass__(cls, *, plugin_name=None, **kwargs):
  3573. if plugin_name:
  3574. mro = inspect.getmro(cls)
  3575. next_mro_class = super_class = mro[mro.index(cls) + 1]
  3576. while getattr(super_class, '__wrapped__', None):
  3577. super_class = super_class.__wrapped__
  3578. if not any(override.PLUGIN_NAME == plugin_name for override in plugin_ies_overrides.value[super_class]):
  3579. cls.__wrapped__ = next_mro_class
  3580. cls.PLUGIN_NAME, cls.ie_key = plugin_name, next_mro_class.ie_key
  3581. cls.IE_NAME = f'{next_mro_class.IE_NAME}+{plugin_name}'
  3582. setattr(sys.modules[super_class.__module__], super_class.__name__, cls)
  3583. plugin_ies_overrides.value[super_class].append(cls)
  3584. return super().__init_subclass__(**kwargs)
  3585. class SearchInfoExtractor(InfoExtractor):
  3586. """
  3587. Base class for paged search queries extractors.
  3588. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  3589. Instances should define _SEARCH_KEY and optionally _MAX_RESULTS
  3590. """
  3591. _MAX_RESULTS = float('inf')
  3592. _RETURN_TYPE = 'playlist'
  3593. @classproperty
  3594. def _VALID_URL(cls):
  3595. return rf'{cls._SEARCH_KEY}(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)'
  3596. def _real_extract(self, query):
  3597. prefix, query = self._match_valid_url(query).group('prefix', 'query')
  3598. if prefix == '':
  3599. return self._get_n_results(query, 1)
  3600. elif prefix == 'all':
  3601. return self._get_n_results(query, self._MAX_RESULTS)
  3602. else:
  3603. n = int(prefix)
  3604. if n <= 0:
  3605. raise ExtractorError(f'invalid download number {n} for query "{query}"')
  3606. elif n > self._MAX_RESULTS:
  3607. self.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  3608. n = self._MAX_RESULTS
  3609. return self._get_n_results(query, n)
  3610. def _get_n_results(self, query, n):
  3611. """Get a specified number of results for a query.
  3612. Either this function or _search_results must be overridden by subclasses """
  3613. return self.playlist_result(
  3614. itertools.islice(self._search_results(query), 0, None if n == float('inf') else n),
  3615. query, query)
  3616. def _search_results(self, query):
  3617. """Returns an iterator of search results"""
  3618. raise NotImplementedError('This method must be implemented by subclasses')
  3619. @classproperty
  3620. def SEARCH_KEY(cls):
  3621. return cls._SEARCH_KEY
  3622. class UnsupportedURLIE(InfoExtractor):
  3623. _VALID_URL = '.*'
  3624. _ENABLED = False
  3625. IE_DESC = False
  3626. def _real_extract(self, url):
  3627. raise UnsupportedError(url)