common.py 188 KB

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