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