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