22 from .common
import InfoExtractor
, SearchInfoExtractor
23 from .openload
import PhantomJSwrapper
24 from ..jsinterp
import JSInterpreter
25 from ..networking
.exceptions
import HTTPError
, network_exceptions
72 STREAMING_DATA_CLIENT_NAME
= '__yt_dlp_client'
73 STREAMING_DATA_PO_TOKEN
= '__yt_dlp_po_token'
75 # any clients starting with _ cannot be explicitly requested by the user
78 'INNERTUBE_CONTEXT': {
81 'clientVersion': '2.20241126.01.00',
84 'INNERTUBE_CONTEXT_CLIENT_NAME': 1,
85 'REQUIRE_PO_TOKEN': True,
86 'SUPPORTS_COOKIES': True,
88 # Safari UA returns pre-merged video+audio 144p/240p/360p/720p/1080p HLS formats
90 'INNERTUBE_CONTEXT': {
93 'clientVersion': '2.20241126.01.00',
94 'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15,gzip(gfe)',
97 'INNERTUBE_CONTEXT_CLIENT_NAME': 1,
98 'REQUIRE_PO_TOKEN': True,
99 'SUPPORTS_COOKIES': True,
102 'INNERTUBE_CONTEXT': {
104 'clientName': 'WEB_EMBEDDED_PLAYER',
105 'clientVersion': '1.20241201.00.00',
108 'INNERTUBE_CONTEXT_CLIENT_NAME': 56,
109 'SUPPORTS_COOKIES': True,
112 'INNERTUBE_HOST': 'music.youtube.com',
113 'INNERTUBE_CONTEXT': {
115 'clientName': 'WEB_REMIX',
116 'clientVersion': '1.20241127.01.00',
119 'INNERTUBE_CONTEXT_CLIENT_NAME': 67,
120 'SUPPORTS_COOKIES': True,
122 # This client now requires sign-in for every video
124 'INNERTUBE_CONTEXT': {
126 'clientName': 'WEB_CREATOR',
127 'clientVersion': '1.20241203.01.00',
130 'INNERTUBE_CONTEXT_CLIENT_NAME': 62,
131 'REQUIRE_AUTH': True,
132 'SUPPORTS_COOKIES': True,
135 'INNERTUBE_CONTEXT': {
137 'clientName': 'ANDROID',
138 'clientVersion': '19.44.38',
139 'androidSdkVersion': 30,
140 'userAgent': 'com.google.android.youtube/19.44.38 (Linux; U; Android 11) gzip',
145 'INNERTUBE_CONTEXT_CLIENT_NAME': 3,
146 'REQUIRE_JS_PLAYER': False,
147 'REQUIRE_PO_TOKEN': True,
149 # This client now requires sign-in for every video
151 'INNERTUBE_CONTEXT': {
153 'clientName': 'ANDROID_MUSIC',
154 'clientVersion': '7.27.52',
155 'androidSdkVersion': 30,
156 'userAgent': 'com.google.android.apps.youtube.music/7.27.52 (Linux; U; Android 11) gzip',
161 'INNERTUBE_CONTEXT_CLIENT_NAME': 21,
162 'REQUIRE_JS_PLAYER': False,
163 'REQUIRE_PO_TOKEN': True,
164 'REQUIRE_AUTH': True,
165 'SUPPORTS_COOKIES': True,
167 # This client now requires sign-in for every video
169 'INNERTUBE_CONTEXT': {
171 'clientName': 'ANDROID_CREATOR',
172 'clientVersion': '24.45.100',
173 'androidSdkVersion': 30,
174 'userAgent': 'com.google.android.apps.youtube.creator/24.45.100 (Linux; U; Android 11) gzip',
179 'INNERTUBE_CONTEXT_CLIENT_NAME': 14,
180 'REQUIRE_JS_PLAYER': False,
181 'REQUIRE_PO_TOKEN': True,
182 'REQUIRE_AUTH': True,
184 # YouTube Kids videos aren't returned on this client for some reason
186 'INNERTUBE_CONTEXT': {
188 'clientName': 'ANDROID_VR',
189 'clientVersion': '1.60.19',
190 'deviceMake': 'Oculus',
191 'deviceModel': 'Quest 3',
192 'androidSdkVersion': 32,
193 'userAgent': 'com.google.android.apps.youtube.vr.oculus/1.60.19 (Linux; U; Android 12L; eureka-user Build/SQ3A.220605.009.A1) gzip',
198 'INNERTUBE_CONTEXT_CLIENT_NAME': 28,
199 'REQUIRE_JS_PLAYER': False,
200 'SUPPORTS_COOKIES': True,
202 # iOS clients have HLS live streams. Setting device model to get 60fps formats.
203 # See: https://github.com/TeamNewPipe/NewPipeExtractor/issues/680#issuecomment-1002724558
205 'INNERTUBE_CONTEXT': {
208 'clientVersion': '19.45.4',
209 'deviceMake': 'Apple',
210 'deviceModel': 'iPhone16,2',
211 'userAgent': 'com.google.ios.youtube/19.45.4 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)',
213 'osVersion': '18.1.0.22B83',
216 'INNERTUBE_CONTEXT_CLIENT_NAME': 5,
217 'REQUIRE_JS_PLAYER': False,
219 # This client now requires sign-in for every video
221 'INNERTUBE_CONTEXT': {
223 'clientName': 'IOS_MUSIC',
224 'clientVersion': '7.27.0',
225 'deviceMake': 'Apple',
226 'deviceModel': 'iPhone16,2',
227 'userAgent': 'com.google.ios.youtubemusic/7.27.0 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)',
229 'osVersion': '18.1.0.22B83',
232 'INNERTUBE_CONTEXT_CLIENT_NAME': 26,
233 'REQUIRE_JS_PLAYER': False,
234 'REQUIRE_AUTH': True,
235 'SUPPORTS_COOKIES': True,
237 # This client now requires sign-in for every video
239 'INNERTUBE_CONTEXT': {
241 'clientName': 'IOS_CREATOR',
242 'clientVersion': '24.45.100',
243 'deviceMake': 'Apple',
244 'deviceModel': 'iPhone16,2',
245 'userAgent': 'com.google.ios.ytcreator/24.45.100 (iPhone16,2; U; CPU iOS 18_1_0 like Mac OS X;)',
247 'osVersion': '18.1.0.22B83',
250 'INNERTUBE_CONTEXT_CLIENT_NAME': 15,
251 'REQUIRE_JS_PLAYER': False,
252 'REQUIRE_AUTH': True,
254 # mweb has 'ultralow' formats
255 # See: https://github.com/yt-dlp/yt-dlp/pull/557
257 'INNERTUBE_CONTEXT': {
259 'clientName': 'MWEB',
260 'clientVersion': '2.20241202.07.00',
261 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 16_7_10 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1,gzip(gfe)',
264 'INNERTUBE_CONTEXT_CLIENT_NAME': 2,
265 'SUPPORTS_COOKIES': True,
268 'INNERTUBE_CONTEXT': {
270 'clientName': 'TVHTML5',
271 'clientVersion': '7.20241201.18.00',
274 'INNERTUBE_CONTEXT_CLIENT_NAME': 7,
275 'SUPPORTS_COOKIES': True,
277 # This client now requires sign-in for every video
278 # It was previously an age-gate workaround for videos that were `playable_in_embed`
279 # It may still be useful if signed into an EU account that is not age-verified
281 'INNERTUBE_CONTEXT': {
283 'clientName': 'TVHTML5_SIMPLY_EMBEDDED_PLAYER',
284 'clientVersion': '2.0',
287 'INNERTUBE_CONTEXT_CLIENT_NAME': 85,
288 'REQUIRE_AUTH': True,
289 'SUPPORTS_COOKIES': True,
294 def _split_innertube_client(client_name
):
295 variant
, *base
= client_name
.rsplit('.', 1)
297 return variant
, base
[0], variant
298 base
, *variant
= client_name
.split('_', 1)
299 return client_name
, base
, variant
[0] if variant
else None
302 def short_client_name(client_name
):
303 main
, *parts
= _split_innertube_client(client_name
)[0].split('_')
304 return join_nonempty(main
[:4], ''.join(x
[0] for x
in parts
)).upper()
307 def build_innertube_clients():
309 'embedUrl': 'https://www.youtube.com/', # Can be any valid URL
311 BASE_CLIENTS
= ('ios', 'web', 'tv', 'mweb', 'android')
312 priority
= qualities(BASE_CLIENTS
[::-1])
314 for client
, ytcfg
in tuple(INNERTUBE_CLIENTS
.items()):
315 ytcfg
.setdefault('INNERTUBE_HOST', 'www.youtube.com')
316 ytcfg
.setdefault('REQUIRE_JS_PLAYER', True)
317 ytcfg
.setdefault('REQUIRE_PO_TOKEN', False)
318 ytcfg
.setdefault('REQUIRE_AUTH', False)
319 ytcfg
.setdefault('SUPPORTS_COOKIES', False)
320 ytcfg
.setdefault('PLAYER_PARAMS', None)
321 ytcfg
['INNERTUBE_CONTEXT']['client'].setdefault('hl', 'en')
323 _
, base_client
, variant
= _split_innertube_client(client
)
324 ytcfg
['priority'] = 10 * priority(base_client
)
326 if variant
== 'embedded':
327 ytcfg
['INNERTUBE_CONTEXT']['thirdParty'] = THIRD_PARTY
328 ytcfg
['priority'] -= 2
330 ytcfg
['priority'] -= 3
333 build_innertube_clients()
336 class BadgeType(enum
.Enum
):
337 AVAILABILITY_UNLISTED
= enum
.auto()
338 AVAILABILITY_PRIVATE
= enum
.auto()
339 AVAILABILITY_PUBLIC
= enum
.auto()
340 AVAILABILITY_PREMIUM
= enum
.auto()
341 AVAILABILITY_SUBSCRIPTION
= enum
.auto()
342 LIVE_NOW
= enum
.auto()
343 VERIFIED
= enum
.auto()
346 class YoutubeBaseInfoExtractor(InfoExtractor
):
347 """Provide base functions for Youtube extractors"""
350 r
'channel|c|user|playlist|watch|w|v|embed|e|live|watch_popup|clip|'
351 r
'shorts|movies|results|search|shared|hashtag|trending|explore|feed|feeds|'
352 r
'browse|oembed|get_video_info|iframe_api|s/player|source|'
353 r
'storefront|oops|index|account|t/terms|about|upload|signin|logout')
355 _PLAYLIST_ID_RE
= r
'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
357 # _NETRC_MACHINE = 'youtube'
359 # If True it will raise an error if no login info is provided
360 _LOGIN_REQUIRED
= False
363 # invidious-redirect websites
364 r
'(?:www\.)?redirect\.invidious\.io',
365 r
'(?:(?:www|dev)\.)?invidio\.us',
366 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/docs/instances.md
367 r
'(?:www\.)?invidious\.pussthecat\.org',
368 r
'(?:www\.)?invidious\.zee\.li',
369 r
'(?:www\.)?invidious\.ethibox\.fr',
370 r
'(?:www\.)?iv\.ggtyler\.dev',
371 r
'(?:www\.)?inv\.vern\.i2p',
372 r
'(?:www\.)?am74vkcrjp2d5v36lcdqgsj2m6x36tbrkhsruoegwfcizzabnfgf5zyd\.onion',
373 r
'(?:www\.)?inv\.riverside\.rocks',
374 r
'(?:www\.)?invidious\.silur\.me',
375 r
'(?:www\.)?inv\.bp\.projectsegfau\.lt',
376 r
'(?:www\.)?invidious\.g4c3eya4clenolymqbpgwz3q3tawoxw56yhzk4vugqrl6dtu3ejvhjid\.onion',
377 r
'(?:www\.)?invidious\.slipfox\.xyz',
378 r
'(?:www\.)?invidious\.esmail5pdn24shtvieloeedh7ehz3nrwcdivnfhfcedl7gf4kwddhkqd\.onion',
379 r
'(?:www\.)?inv\.vernccvbvyi5qhfzyqengccj7lkove6bjot2xhh5kajhwvidqafczrad\.onion',
380 r
'(?:www\.)?invidious\.tiekoetter\.com',
381 r
'(?:www\.)?iv\.odysfvr23q5wgt7i456o5t3trw2cw5dgn56vbjfbq2m7xsc5vqbqpcyd\.onion',
382 r
'(?:www\.)?invidious\.nerdvpn\.de',
383 r
'(?:www\.)?invidious\.weblibre\.org',
384 r
'(?:www\.)?inv\.odyssey346\.dev',
385 r
'(?:www\.)?invidious\.dhusch\.de',
386 r
'(?:www\.)?iv\.melmac\.space',
387 r
'(?:www\.)?watch\.thekitty\.zone',
388 r
'(?:www\.)?invidious\.privacydev\.net',
389 r
'(?:www\.)?ng27owmagn5amdm7l5s3rsqxwscl5ynppnis5dqcasogkyxcfqn7psid\.onion',
390 r
'(?:www\.)?invidious\.drivet\.xyz',
391 r
'(?:www\.)?vid\.priv\.au',
392 r
'(?:www\.)?euxxcnhsynwmfidvhjf6uzptsmh4dipkmgdmcmxxuo7tunp3ad2jrwyd\.onion',
393 r
'(?:www\.)?inv\.vern\.cc',
394 r
'(?:www\.)?invidious\.esmailelbob\.xyz',
395 r
'(?:www\.)?invidious\.sethforprivacy\.com',
396 r
'(?:www\.)?yt\.oelrichsgarcia\.de',
397 r
'(?:www\.)?yt\.artemislena\.eu',
398 r
'(?:www\.)?invidious\.flokinet\.to',
399 r
'(?:www\.)?invidious\.baczek\.me',
400 r
'(?:www\.)?y\.com\.sb',
401 r
'(?:www\.)?invidious\.epicsite\.xyz',
402 r
'(?:www\.)?invidious\.lidarshield\.cloud',
403 r
'(?:www\.)?yt\.funami\.tech',
404 r
'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
405 r
'(?:www\.)?osbivz6guyeahrwp2lnwyjk2xos342h4ocsxyqrlaopqjuhwn2djiiyd\.onion',
406 r
'(?:www\.)?u2cvlit75owumwpy4dj2hsmvkq7nvrclkpht7xgyye2pyoxhpmclkrad\.onion',
407 # youtube-dl invidious instances list
408 r
'(?:(?:www|no)\.)?invidiou\.sh',
409 r
'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
410 r
'(?:www\.)?invidious\.kabi\.tk',
411 r
'(?:www\.)?invidious\.mastodon\.host',
412 r
'(?:www\.)?invidious\.zapashcanon\.fr',
413 r
'(?:www\.)?(?:invidious(?:-us)?|piped)\.kavin\.rocks',
414 r
'(?:www\.)?invidious\.tinfoil-hat\.net',
415 r
'(?:www\.)?invidious\.himiko\.cloud',
416 r
'(?:www\.)?invidious\.reallyancient\.tech',
417 r
'(?:www\.)?invidious\.tube',
418 r
'(?:www\.)?invidiou\.site',
419 r
'(?:www\.)?invidious\.site',
420 r
'(?:www\.)?invidious\.xyz',
421 r
'(?:www\.)?invidious\.nixnet\.xyz',
422 r
'(?:www\.)?invidious\.048596\.xyz',
423 r
'(?:www\.)?invidious\.drycat\.fr',
424 r
'(?:www\.)?inv\.skyn3t\.in',
425 r
'(?:www\.)?tube\.poal\.co',
426 r
'(?:www\.)?tube\.connect\.cafe',
427 r
'(?:www\.)?vid\.wxzm\.sx',
428 r
'(?:www\.)?vid\.mint\.lgbt',
429 r
'(?:www\.)?vid\.puffyan\.us',
430 r
'(?:www\.)?yewtu\.be',
431 r
'(?:www\.)?yt\.elukerio\.org',
432 r
'(?:www\.)?yt\.lelux\.fi',
433 r
'(?:www\.)?invidious\.ggc-project\.de',
434 r
'(?:www\.)?yt\.maisputain\.ovh',
435 r
'(?:www\.)?ytprivate\.com',
436 r
'(?:www\.)?invidious\.13ad\.de',
437 r
'(?:www\.)?invidious\.toot\.koeln',
438 r
'(?:www\.)?invidious\.fdn\.fr',
439 r
'(?:www\.)?watch\.nettohikari\.com',
440 r
'(?:www\.)?invidious\.namazso\.eu',
441 r
'(?:www\.)?invidious\.silkky\.cloud',
442 r
'(?:www\.)?invidious\.exonip\.de',
443 r
'(?:www\.)?invidious\.riverside\.rocks',
444 r
'(?:www\.)?invidious\.blamefran\.net',
445 r
'(?:www\.)?invidious\.moomoo\.de',
446 r
'(?:www\.)?ytb\.trom\.tf',
447 r
'(?:www\.)?yt\.cyberhost\.uk',
448 r
'(?:www\.)?kgg2m7yk5aybusll\.onion',
449 r
'(?:www\.)?qklhadlycap4cnod\.onion',
450 r
'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
451 r
'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
452 r
'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
453 r
'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
454 r
'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
455 r
'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
456 r
'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
457 r
'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
458 r
'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
459 r
'(?:www\.)?hpniueoejy4opn7bc4ftgazyqjoeqwlvh2uiku2xqku6zpoa4bf5ruid\.onion',
460 # piped instances from https://github.com/TeamPiped/Piped/wiki/Instances
461 r
'(?:www\.)?piped\.kavin\.rocks',
462 r
'(?:www\.)?piped\.tokhmi\.xyz',
463 r
'(?:www\.)?piped\.syncpundit\.io',
464 r
'(?:www\.)?piped\.mha\.fi',
465 r
'(?:www\.)?watch\.whatever\.social',
466 r
'(?:www\.)?piped\.garudalinux\.org',
467 r
'(?:www\.)?piped\.rivo\.lol',
468 r
'(?:www\.)?piped-libre\.kavin\.rocks',
469 r
'(?:www\.)?yt\.jae\.fi',
470 r
'(?:www\.)?piped\.mint\.lgbt',
472 r
'(?:www\.)?piped\.esmailelbob\.xyz',
473 r
'(?:www\.)?piped\.projectsegfau\.lt',
474 r
'(?:www\.)?piped\.privacydev\.net',
475 r
'(?:www\.)?piped\.palveluntarjoaja\.eu',
476 r
'(?:www\.)?piped\.smnz\.de',
477 r
'(?:www\.)?piped\.adminforge\.de',
478 r
'(?:www\.)?watch\.whatevertinfoil\.de',
479 r
'(?:www\.)?piped\.qdi\.fi',
480 r
'(?:(?:www|cf)\.)?piped\.video',
481 r
'(?:www\.)?piped\.aeong\.one',
482 r
'(?:www\.)?piped\.moomoo\.me',
483 r
'(?:www\.)?piped\.chauvet\.pro',
484 r
'(?:www\.)?watch\.leptons\.xyz',
485 r
'(?:www\.)?pd\.vern\.cc',
486 r
'(?:www\.)?piped\.hostux\.net',
487 r
'(?:www\.)?piped\.lunar\.icu',
488 # Hyperpipe instances from https://hyperpipe.codeberg.page/
489 r
'(?:www\.)?hyperpipe\.surge\.sh',
490 r
'(?:www\.)?hyperpipe\.esmailelbob\.xyz',
491 r
'(?:www\.)?listen\.whatever\.social',
492 r
'(?:www\.)?music\.adminforge\.de',
495 # extracted from account/account_menu ep
496 # XXX: These are the supported YouTube UI and API languages,
497 # which is slightly different from languages supported for translation in YouTube studio
498 _SUPPORTED_LANG_CODES
= [
499 'af', 'az', 'id', 'ms', 'bs', 'ca', 'cs', 'da', 'de', 'et', 'en-IN', 'en-GB', 'en', 'es',
500 'es-419', 'es-US', 'eu', 'fil', 'fr', 'fr-CA', 'gl', 'hr', 'zu', 'is', 'it', 'sw', 'lv',
501 'lt', 'hu', 'nl', 'no', 'uz', 'pl', 'pt-PT', 'pt', 'ro', 'sq', 'sk', 'sl', 'sr-Latn', 'fi',
502 'sv', 'vi', 'tr', 'be', 'bg', 'ky', 'kk', 'mk', 'mn', 'ru', 'sr', 'uk', 'el', 'hy', 'iw',
503 'ur', 'ar', 'fa', 'ne', 'mr', 'hi', 'as', 'bn', 'pa', 'gu', 'or', 'ta', 'te', 'kn', 'ml',
504 'si', 'th', 'lo', 'my', 'ka', 'am', 'km', 'zh-CN', 'zh-TW', 'zh-HK', 'ja', 'ko',
507 _IGNORED_WARNINGS
= {
508 'Unavailable videos will be hidden during playback',
509 'Unavailable videos are hidden',
512 _YT_HANDLE_RE
= r
'@[\w.-]{3,30}' # https://support.google.com/youtube/answer/11585688?hl=en
513 _YT_CHANNEL_UCID_RE
= r
'UC[\w-]{22}'
515 _NETRC_MACHINE
= 'youtube'
517 def ucid_or_none(self
, ucid
):
518 return self
._search
_regex
(rf
'^({self._YT_CHANNEL_UCID_RE})$', ucid
, 'UC-id', default
=None)
520 def handle_or_none(self
, handle
):
521 return self
._search
_regex
(rf
'^({self._YT_HANDLE_RE})$', urllib
.parse
.unquote(handle
or ''),
522 '@-handle', default
=None)
524 def handle_from_url(self
, url
):
525 return self
._search
_regex
(rf
'^(?:https?://(?:www\.)?youtube\.com)?/({self._YT_HANDLE_RE})',
526 urllib
.parse
.unquote(url
or ''), 'channel handle', default
=None)
528 def ucid_from_url(self
, url
):
529 return self
._search
_regex
(rf
'^(?:https?://(?:www\.)?youtube\.com)?/({self._YT_CHANNEL_UCID_RE})',
530 url
, 'channel id', default
=None)
532 @functools.cached_property
533 def _preferred_lang(self
):
535 Returns a language code supported by YouTube for the user preferred language.
536 Returns None if no preferred language set.
538 preferred_lang
= self
._configuration
_arg
('lang', ie_key
='Youtube', casesense
=True, default
=[''])[0]
539 if not preferred_lang
:
541 if preferred_lang
not in self
._SUPPORTED
_LANG
_CODES
:
542 raise ExtractorError(
543 f
'Unsupported language code: {preferred_lang}. Supported language codes (case-sensitive): {join_nonempty(*self._SUPPORTED_LANG_CODES, delim=", ")}.',
545 elif preferred_lang
!= 'en':
547 f
'Preferring "{preferred_lang}" translated fields. Note that some metadata extraction may fail or be incorrect.')
548 return preferred_lang
550 def _initialize_consent(self
):
551 cookies
= self
._get
_cookies
('https://www.youtube.com/')
552 if cookies
.get('__Secure-3PSID'):
554 socs
= cookies
.get('SOCS')
555 if socs
and not socs
.value
.startswith('CAA'): # not consented
557 self
._set
_cookie
('.youtube.com', 'SOCS', 'CAI', secure
=True) # accept all (required for mixes)
559 def _initialize_pref(self
):
560 cookies
= self
._get
_cookies
('https://www.youtube.com/')
561 pref_cookie
= cookies
.get('PREF')
565 pref
= dict(urllib
.parse
.parse_qsl(pref_cookie
.value
))
567 self
.report_warning('Failed to parse user PREF cookie' + bug_reports_message())
568 pref
.update({'hl': self
._preferred
_lang
or 'en', 'tz': 'UTC'})
569 self
._set
_cookie
('.youtube.com', name
='PREF', value
=urllib
.parse
.urlencode(pref
))
571 def _real_initialize(self
):
572 self
._initialize
_pref
()
573 self
._initialize
_consent
()
574 self
._check
_login
_required
()
576 def _perform_login(self
, username
, password
):
577 if username
.startswith('oauth'):
578 raise ExtractorError(
579 f
'Login with OAuth is no longer supported. {self._youtube_login_hint}', expected
=True)
582 f
'Login with password is not supported for YouTube. {self._youtube_login_hint}')
585 def _youtube_login_hint(self
):
586 return (f
'{self._login_hint(method="cookies")}. Also see '
587 'https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies '
588 'for tips on effectively exporting YouTube cookies')
590 def _check_login_required(self
):
591 if self
._LOGIN
_REQUIRED
and not self
.is_authenticated
:
592 self
.raise_login_required(
593 f
'Login details are needed to download this content. {self._youtube_login_hint}', method
=None)
595 _YT_INITIAL_DATA_RE
= r
'(?:window\s*\[\s*["\']ytInitialData
["\']\s*\]|ytInitialData)\s*='
596 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*='
598 def _get_default_ytcfg(self, client='web'):
599 return copy.deepcopy(INNERTUBE_CLIENTS[client])
601 def _get_innertube_host(self, client='web'):
602 return INNERTUBE_CLIENTS[client]['INNERTUBE_HOST']
604 def _ytcfg_get_safe(self, ytcfg, getter, expected_type=None, default_client='web'):
605 # try_get but with fallback to default ytcfg client values when present
606 _func = lambda y: try_get(y, getter, expected_type)
607 return _func(ytcfg) or _func(self._get_default_ytcfg(default_client))
609 def _extract_client_name(self, ytcfg, default_client='web'):
610 return self._ytcfg_get_safe(
611 ytcfg, (lambda x: x['INNERTUBE_CLIENT_NAME'],
612 lambda x: x['INNERTUBE_CONTEXT']['client']['clientName']), str, default_client)
614 def _extract_client_version(self, ytcfg, default_client='web'):
615 return self._ytcfg_get_safe(
616 ytcfg, (lambda x: x['INNERTUBE_CLIENT_VERSION'],
617 lambda x: x['INNERTUBE_CONTEXT']['client']['clientVersion']), str, default_client)
619 def _select_api_hostname(self, req_api_hostname, default_client=None):
620 return (self._configuration_arg('innertube_host', [''], ie_key=YoutubeIE.ie_key())[0]
621 or req_api_hostname or self._get_innertube_host(default_client or 'web'))
623 def _extract_context(self, ytcfg=None, default_client='web'):
625 (ytcfg, self._get_default_ytcfg(default_client)), 'INNERTUBE_CONTEXT', expected_type=dict)
626 # Enforce language and tz for extraction
627 client_context = traverse_obj(context, 'client', expected_type=dict, default={})
628 client_context.update({'hl': self._preferred_lang or 'en', 'timeZone': 'UTC', 'utcOffsetMinutes': 0})
633 def _generate_sapisidhash_header(self, origin='https://www.youtube.com'):
634 time_now = round(time.time())
635 if self._SAPISID is None:
636 yt_cookies = self._get_cookies('https://www.youtube.com')
637 # Sometimes SAPISID cookie isn't present but __Secure-3PAPISID is.
638 # See: https://github.com/yt-dlp/yt-dlp/issues/393
639 sapisid_cookie = dict_get(
640 yt_cookies, ('__Secure-3PAPISID', 'SAPISID'))
641 if sapisid_cookie and sapisid_cookie.value:
642 self._SAPISID = sapisid_cookie.value
643 self.write_debug('Extracted SAPISID cookie')
644 # SAPISID cookie is required if not already present
645 if not yt_cookies.get('SAPISID'):
646 self.write_debug('Copying __Secure-3PAPISID cookie to SAPISID cookie')
648 '.youtube.com', 'SAPISID', self._SAPISID, secure=True, expire_time=time_now + 3600)
650 self._SAPISID = False
651 if not self._SAPISID:
653 # SAPISIDHASH algorithm from https://stackoverflow.com/a/32065323
654 sapisidhash = hashlib.sha1(
655 f'{time_now} {self._SAPISID} {origin}'.encode()).hexdigest()
656 return f'SAPISIDHASH {time_now}_{sapisidhash}'
658 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
659 note='Downloading API JSON', errnote='Unable to download API page',
660 context=None, api_key=None, api_hostname=None, default_client='web'):
662 data = {'context': context} if context else {'context': self._extract_context(default_client=default_client)}
664 real_headers = self.generate_api_headers(default_client=default_client)
665 real_headers.update({'content-type': 'application/json'})
667 real_headers.update(headers)
668 return self._download_json(
669 f'https://{self._select_api_hostname(api_hostname, default_client)}/youtubei/v1/{ep}',
670 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
671 data=json.dumps(data).encode('utf8'), headers=real_headers,
673 'key': self._configuration_arg(
674 'innertube_key', [api_key], ie_key=YoutubeIE.ie_key(), casesense=True)[0],
675 'prettyPrint': 'false',
676 }, cndn=lambda _, v: v))
678 def extract_yt_initial_data(self, item_id, webpage, fatal=True):
679 return self._search_json(self._YT_INITIAL_DATA_RE, webpage, 'yt initial data', item_id, fatal=fatal)
682 def _extract_session_index(*data):
684 Index of current account in account list.
685 See: https://github.com/yt-dlp/yt-dlp/pull/519
688 session_index = int_or_none(try_get(ytcfg, lambda x: x['SESSION_INDEX']))
689 if session_index is not None:
692 def _data_sync_id_to_delegated_session_id(self, data_sync_id):
695 # datasyncid is of the form "channel_syncid||user_syncid
" for secondary channel
696 # and just "user_syncid||
" for primary channel. We only want the channel_syncid
697 channel_syncid, _, user_syncid = data_sync_id.partition('||')
699 return channel_syncid
701 def _extract_account_syncid(self, *args):
703 Extract current session ID required to download private playlists of secondary channels
704 @params response and/or ytcfg
706 # ytcfg includes channel_syncid if on secondary channel
707 if delegated_sid := traverse_obj(args, (..., 'DELEGATED_SESSION_ID', {str}, any)):
710 data_sync_id = self._extract_data_sync_id(*args)
711 return self._data_sync_id_to_delegated_session_id(data_sync_id)
713 def _extract_data_sync_id(self, *args):
715 Extract current account dataSyncId.
716 In the format DELEGATED_SESSION_ID||USER_SESSION_ID or USER_SESSION_ID||
717 @params response and/or ytcfg
719 if data_sync_id := self._configuration_arg('data_sync_id', [None], ie_key=YoutubeIE, casesense=True)[0]:
723 args, (..., ('DATASYNC_ID', ('responseContext', 'mainAppWebResponseContext', 'datasyncId')), {str}, any))
725 def _extract_visitor_data(self, *args):
727 Extracts visitorData from an API response or ytcfg
728 Appears to be used to track session state
730 if visitor_data := self._configuration_arg('visitor_data', [None], ie_key=YoutubeIE, casesense=True)[0]:
733 args, [('VISITOR_DATA', ('INNERTUBE_CONTEXT', 'client', 'visitorData'), ('responseContext', 'visitorData'))],
736 @functools.cached_property
737 def is_authenticated(self):
738 return bool(self._generate_sapisidhash_header())
740 def extract_ytcfg(self, video_id, webpage):
743 return self._parse_json(
745 r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
746 default='{}'), video_id, fatal=False) or {}
748 def _generate_cookie_auth_headers(self, *, ytcfg=None, account_syncid=None, session_index=None, origin=None, **kwargs):
750 account_syncid = account_syncid or self._extract_account_syncid(ytcfg)
752 headers['X-Goog-PageId'] = account_syncid
753 if session_index is None:
754 session_index = self._extract_session_index(ytcfg)
755 if account_syncid or session_index is not None:
756 headers['X-Goog-AuthUser'] = session_index if session_index is not None else 0
758 auth = self._generate_sapisidhash_header(origin)
760 headers['Authorization'] = auth
761 headers['X-Origin'] = origin
765 def generate_api_headers(
766 self, *, ytcfg=None, account_syncid=None, session_index=None,
767 visitor_data=None, api_hostname=None, default_client='web', **kwargs):
769 origin = 'https://' + (self._select_api_hostname(api_hostname, default_client))
771 'X-YouTube-Client-Name': str(
772 self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_CONTEXT_CLIENT_NAME'], default_client=default_client)),
773 'X-YouTube-Client-Version': self._extract_client_version(ytcfg, default_client),
775 'X-Goog-Visitor-Id': visitor_data or self._extract_visitor_data(ytcfg),
776 'User-Agent': self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_CONTEXT']['client']['userAgent'], default_client=default_client),
777 **self._generate_cookie_auth_headers(ytcfg=ytcfg, account_syncid=account_syncid, session_index=session_index, origin=origin),
779 return filter_dict(headers)
781 def _download_ytcfg(self, client, video_id):
783 'web': 'https://www.youtube.com',
784 'web_music': 'https://music.youtube.com',
785 'web_embedded': f'https://www.youtube.com/embed/{video_id}?html5=1',
789 webpage = self._download_webpage(
790 url, video_id, fatal=False, note=f'Downloading {client.replace("_
", " ").strip()} client config')
791 return self.extract_ytcfg(video_id, webpage) or {}
794 def _build_api_continuation_query(continuation, ctp=None):
796 'continuation': continuation,
798 # TODO: Inconsistency with clickTrackingParams.
799 # Currently we have a fixed ctp contained within context (from ytcfg)
800 # and a ctp in root query for continuation.
802 query['clickTracking'] = {'clickTrackingParams': ctp}
806 def _extract_next_continuation_data(cls, renderer):
807 next_continuation = try_get(
808 renderer, (lambda x: x['continuations'][0]['nextContinuationData'],
809 lambda x: x['continuation']['reloadContinuationData']), dict)
810 if not next_continuation:
812 continuation = next_continuation.get('continuation')
815 ctp = next_continuation.get('clickTrackingParams')
816 return cls._build_api_continuation_query(continuation, ctp)
819 def _extract_continuation_ep_data(cls, continuation_ep: dict):
820 if isinstance(continuation_ep, dict):
821 continuation = try_get(
822 continuation_ep, lambda x: x['continuationCommand']['token'], str)
825 ctp = continuation_ep.get('clickTrackingParams')
826 return cls._build_api_continuation_query(continuation, ctp)
829 def _extract_continuation(cls, renderer):
830 next_continuation = cls._extract_next_continuation_data(renderer)
831 if next_continuation:
832 return next_continuation
834 return traverse_obj(renderer, (
835 ('contents', 'items', 'rows'), ..., 'continuationItemRenderer',
836 ('continuationEndpoint', ('button', 'buttonRenderer', 'command')),
837 ), get_all=False, expected_type=cls._extract_continuation_ep_data)
840 def _extract_alerts(cls, data):
841 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
842 if not isinstance(alert_dict, dict):
844 for alert in alert_dict.values():
845 alert_type = alert.get('type')
848 message = cls._get_text(alert, 'text')
850 yield alert_type, message
852 def _report_alerts(self, alerts, expected=True, fatal=True, only_once=False):
853 errors, warnings = [], []
854 for alert_type, alert_message in alerts:
855 if alert_type.lower() == 'error' and fatal:
856 errors.append([alert_type, alert_message])
857 elif alert_message not in self._IGNORED_WARNINGS:
858 warnings.append([alert_type, alert_message])
860 for alert_type, alert_message in (warnings + errors[:-1]):
861 self.report_warning(f'YouTube said: {alert_type} - {alert_message}', only_once=only_once)
863 raise ExtractorError(f'YouTube said: {errors[-1][1]}', expected=expected)
865 def _extract_and_report_alerts(self, data, *args, **kwargs):
866 return self._report_alerts(self._extract_alerts(data), *args, **kwargs)
868 def _extract_badges(self, badge_list: list):
870 Extract known BadgeType's from a list of badge renderers.
871 @returns [{'type': BadgeType}]
874 'PRIVACY_UNLISTED': BadgeType.AVAILABILITY_UNLISTED,
875 'PRIVACY_PRIVATE': BadgeType.AVAILABILITY_PRIVATE,
876 'PRIVACY_PUBLIC': BadgeType.AVAILABILITY_PUBLIC,
877 'CHECK_CIRCLE_THICK': BadgeType.VERIFIED,
878 'OFFICIAL_ARTIST_BADGE': BadgeType.VERIFIED,
879 'CHECK': BadgeType.VERIFIED,
883 'BADGE_STYLE_TYPE_MEMBERS_ONLY': BadgeType.AVAILABILITY_SUBSCRIPTION,
884 'BADGE_STYLE_TYPE_PREMIUM': BadgeType.AVAILABILITY_PREMIUM,
885 'BADGE_STYLE_TYPE_LIVE_NOW': BadgeType.LIVE_NOW,
886 'BADGE_STYLE_TYPE_VERIFIED': BadgeType.VERIFIED,
887 'BADGE_STYLE_TYPE_VERIFIED_ARTIST': BadgeType.VERIFIED,
891 'unlisted': BadgeType.AVAILABILITY_UNLISTED,
892 'private': BadgeType.AVAILABILITY_PRIVATE,
893 'members only': BadgeType.AVAILABILITY_SUBSCRIPTION,
894 'live': BadgeType.LIVE_NOW,
895 'premium': BadgeType.AVAILABILITY_PREMIUM,
896 'verified': BadgeType.VERIFIED,
897 'official artist channel': BadgeType.VERIFIED,
901 for badge in traverse_obj(badge_list, (..., lambda key, _: re.search(r'[bB]adgeRenderer$', key))):
903 icon_type_map.get(traverse_obj(badge, ('icon', 'iconType'), expected_type=str))
904 or badge_style_map.get(traverse_obj(badge, 'style'))
907 badges.append({'type': badge_type})
910 # fallback, won't work in some languages
911 label = traverse_obj(
912 badge, 'label', ('accessibilityData', 'label'), 'tooltip', 'iconTooltip', get_all=False, expected_type=str, default='')
913 for match, label_badge_type in label_map.items():
914 if match in label.lower():
915 badges.append({'type': label_badge_type})
921 def _has_badge(badges, badge_type):
922 return bool(traverse_obj(badges, lambda _, v: v['type'] == badge_type))
925 def _get_text(data, *path_list, max_runs=None):
926 for path in path_list or [None]:
930 obj = traverse_obj(data, path, default=[])
931 if not any(key is ... or isinstance(key, (list, tuple)) for key in variadic(path)):
934 text = try_get(item, lambda x: x['simpleText'], str)
937 runs = try_get(item, lambda x: x['runs'], list) or []
938 if not runs and isinstance(item, list):
941 runs = runs[:min(len(runs), max_runs or len(runs))]
942 text = ''.join(traverse_obj(runs, (..., 'text'), expected_type=str))
946 def _get_count(self, data, *path_list):
947 count_text = self._get_text(data, *path_list) or ''
948 count = parse_count(count_text)
951 self._search_regex(r'^([\d,]+)', re.sub(r'\s', '', count_text), 'count', default=None))
955 def _extract_thumbnails(data, *path_list, final_key='thumbnails'):
957 Extract thumbnails from thumbnails dict
958 @param path_list: path list to level that contains 'thumbnails' key
961 for path in path_list or [()]:
962 for thumbnail in traverse_obj(data, (*variadic(path), final_key, ...)):
963 thumbnail_url = url_or_none(thumbnail.get('url'))
964 if not thumbnail_url:
966 # Sometimes youtube gives a wrong thumbnail URL. See:
967 # https://github.com/yt-dlp/yt-dlp/issues/233
968 # https://github.com/ytdl-org/youtube-dl/issues/28023
969 if 'maxresdefault' in thumbnail_url:
970 thumbnail_url = thumbnail_url.split('?')[0]
972 'url': thumbnail_url,
973 'height': int_or_none(thumbnail.get('height')),
974 'width': int_or_none(thumbnail.get('width')),
979 def extract_relative_time(relative_time_text):
981 Extracts a relative time from string and converts to dt object
982 e.g. 'streamed 6 days ago', '5 seconds ago (edited)', 'updated today', '8 yr ago'
985 # XXX: this could be moved to a general function in utils/_utils.py
986 # The relative time text strings are roughly the same as what
987 # Javascript's Intl.RelativeTimeFormat function generates.
988 # See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
990 r'(?P<start>today|yesterday|now)|(?P<time>\d+)\s*(?P<unit>sec(?:ond)?|s|min(?:ute)?|h(?:our|r)?|d(?:ay)?|w(?:eek|k)?|mo(?:nth)?|y(?:ear|r)?)s?\s*ago',
993 start = mobj.group('start')
995 return datetime_from_str(start)
997 return datetime_from_str('now-{}{}'.format(mobj.group('time'), mobj.group('unit')))
1001 def _parse_time_text(self, text):
1004 dt_ = self.extract_relative_time(text)
1006 if isinstance(dt_, dt.datetime):
1007 timestamp = calendar.timegm(dt_.timetuple())
1009 if timestamp is None:
1011 unified_timestamp(text) or unified_timestamp(
1013 (r'([a-z]+\s*\d{1,2},?\s*20\d{2})', r'(?:.+|^)(?:live|premieres|ed|ing)(?:\s*(?:on|for))?\s*(.+\d)'),
1014 text.lower(), 'time text', default=None)))
1016 if text and timestamp is None and self._preferred_lang in (None, 'en'):
1017 self.report_warning(
1018 f'Cannot parse localized time text "{text}
"', only_once=True)
1021 def _extract_response(self, item_id, query, note='Downloading API JSON', headers=None,
1022 ytcfg=None, check_get_keys=None, ep='browse', fatal=True, api_hostname=None,
1023 default_client='web'):
1024 raise_for_incomplete = bool(self._configuration_arg('raise_incomplete_data', ie_key=YoutubeIE))
1025 # Incomplete Data should be a warning by default when retries are exhausted, while other errors should be fatal.
1026 icd_retries = iter(self.RetryManager(fatal=raise_for_incomplete))
1027 icd_rm = next(icd_retries)
1028 main_retries = iter(self.RetryManager())
1029 main_rm = next(main_retries)
1030 # Manual retry loop for multiple RetryManagers
1031 # The proper RetryManager MUST be advanced after an error
1032 # and its result MUST be checked if the manager is non fatal
1035 response = self._call_api(
1036 ep=ep, fatal=True, headers=headers,
1037 video_id=item_id, query=query, note=note,
1038 context=self._extract_context(ytcfg, default_client),
1039 api_hostname=api_hostname, default_client=default_client)
1040 except ExtractorError as e:
1041 if not isinstance(e.cause, network_exceptions):
1042 return self._error_or_warning(e, fatal=fatal)
1043 elif not isinstance(e.cause, HTTPError):
1048 first_bytes = e.cause.response.read(512)
1049 if not is_html(first_bytes):
1052 self._webpage_read_content(e.cause.response, None, item_id, prefix=first_bytes) or '{}', item_id, fatal=False),
1053 lambda x: x['error']['message'], str)
1055 self._report_alerts([('ERROR', yt_error)], fatal=False)
1056 # Downloading page may result in intermittent 5xx HTTP error
1057 # Sometimes a 404 is also received. See: https://github.com/ytdl-org/youtube-dl/issues/28289
1058 # We also want to catch all other network exceptions since errors in later pages can be troublesome
1059 # See https://github.com/yt-dlp/yt-dlp/issues/507#issuecomment-880188210
1060 if e.cause.status not in (403, 429):
1064 return self._error_or_warning(e, fatal=fatal)
1067 self._extract_and_report_alerts(response, only_once=True)
1068 except ExtractorError as e:
1069 # YouTube's servers may return errors we want to retry on in a 200 OK response
1070 # See: https://github.com/yt-dlp/yt-dlp/issues/839
1071 if 'unknown error' in e.msg.lower():
1075 return self._error_or_warning(e, fatal=fatal)
1076 # Youtube sometimes sends incomplete data
1077 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
1078 if not traverse_obj(response, *variadic(check_get_keys)):
1079 icd_rm.error = ExtractorError('Incomplete data received', expected=True)
1080 should_retry = next(icd_retries, None)
1081 if not should_retry:
1088 def is_music_url(url):
1089 return re.match(r'(https?://)?music\.youtube\.com/', url) is not None
1091 def _extract_video(self, renderer):
1092 video_id = renderer.get('videoId')
1094 reel_header_renderer = traverse_obj(renderer, (
1095 'navigationEndpoint', 'reelWatchEndpoint', 'overlay', 'reelPlayerOverlayRenderer',
1096 'reelPlayerHeaderSupportedRenderers', 'reelPlayerHeaderRenderer'))
1098 title = self._get_text(renderer, 'title', 'headline') or self._get_text(reel_header_renderer, 'reelTitleText')
1099 description = self._get_text(renderer, 'descriptionSnippet')
1101 duration = int_or_none(renderer.get('lengthSeconds'))
1102 if duration is None:
1103 duration = parse_duration(self._get_text(
1104 renderer, 'lengthText', ('thumbnailOverlays', ..., 'thumbnailOverlayTimeStatusRenderer', 'text')))
1105 if duration is None:
1106 # XXX: should write a parser to be more general to support more cases (e.g. shorts in shorts tab)
1107 duration = parse_duration(self._search_regex(
1108 r'(?i)(ago)(?!.*\1)\s+(?P<duration>[a-z0-9 ,]+?)(?:\s+[\d,]+\s+views)?(?:\s+-\s+play\s+short)?$',
1109 traverse_obj(renderer, ('title', 'accessibility', 'accessibilityData', 'label'), default='', expected_type=str),
1110 video_id, default=None, group='duration'))
1112 channel_id = traverse_obj(
1113 renderer, ('shortBylineText', 'runs', ..., 'navigationEndpoint', 'browseEndpoint', 'browseId'),
1114 expected_type=str, get_all=False)
1116 channel_id = traverse_obj(reel_header_renderer, ('channelNavigationEndpoint', 'browseEndpoint', 'browseId'))
1118 channel_id = self.ucid_or_none(channel_id)
1120 overlay_style = traverse_obj(
1121 renderer, ('thumbnailOverlays', ..., 'thumbnailOverlayTimeStatusRenderer', 'style'),
1122 get_all=False, expected_type=str)
1123 badges = self._extract_badges(traverse_obj(renderer, 'badges'))
1124 owner_badges = self._extract_badges(traverse_obj(renderer, 'ownerBadges'))
1125 navigation_url = urljoin('https://www.youtube.com/', traverse_obj(
1126 renderer, ('navigationEndpoint', 'commandMetadata', 'webCommandMetadata', 'url'),
1127 expected_type=str)) or ''
1128 url = f'https://www.youtube.com/watch?v={video_id}'
1129 if overlay_style == 'SHORTS' or '/shorts/' in navigation_url:
1130 url = f'https://www.youtube.com/shorts/{video_id}'
1132 time_text = (self._get_text(renderer, 'publishedTimeText', 'videoInfo')
1133 or self._get_text(reel_header_renderer, 'timestampText') or '')
1134 scheduled_timestamp = str_to_int(traverse_obj(renderer, ('upcomingEventData', 'startTime'), get_all=False))
1137 'is_upcoming' if scheduled_timestamp is not None
1138 else 'was_live' if 'streamed' in time_text.lower()
1139 else 'is_live' if overlay_style == 'LIVE' or self._has_badge(badges, BadgeType.LIVE_NOW)
1142 # videoInfo is a string like '50K views • 10 years ago'.
1143 view_count_text = self._get_text(renderer, 'viewCountText', 'shortViewCountText', 'videoInfo') or ''
1144 view_count = (0 if 'no views' in view_count_text.lower()
1145 else self._get_count({'simpleText': view_count_text}))
1146 view_count_field = 'concurrent_view_count' if live_status in ('is_live', 'is_upcoming') else 'view_count'
1148 channel = (self._get_text(renderer, 'ownerText', 'shortBylineText')
1149 or self._get_text(reel_header_renderer, 'channelTitleText'))
1151 channel_handle = traverse_obj(renderer, (
1152 'shortBylineText', 'runs', ..., 'navigationEndpoint',
1153 (('commandMetadata', 'webCommandMetadata', 'url'), ('browseEndpoint', 'canonicalBaseUrl'))),
1154 expected_type=self.handle_from_url, get_all=False)
1157 'ie_key': YoutubeIE.ie_key(),
1161 'description': description,
1162 'duration': duration,
1163 'channel_id': channel_id,
1165 'channel_url': f'https://www.youtube.com/channel/{channel_id}' if channel_id else None,
1166 'uploader': channel,
1167 'uploader_id': channel_handle,
1168 'uploader_url': format_field(channel_handle, None, 'https://www.youtube.com/%s', default=None),
1169 'thumbnails': self._extract_thumbnails(renderer, 'thumbnail'),
1170 'timestamp': (self._parse_time_text(time_text)
1171 if self._configuration_arg('approximate_date', ie_key=YoutubeTabIE)
1173 'release_timestamp': scheduled_timestamp,
1175 'public' if self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
1176 else self._availability(
1177 is_private=self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE) or None,
1178 needs_premium=self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM) or None,
1179 needs_subscription=self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION) or None,
1180 is_unlisted=self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED) or None),
1181 view_count_field: view_count,
1182 'live_status': live_status,
1183 'channel_is_verified': True if self._has_badge(owner_badges, BadgeType.VERIFIED) else None,
1187 class YoutubeIE(YoutubeBaseInfoExtractor):
1189 _VALID_URL = r'''(?x)^
1191 (?:https?://|//) # http(s):// or protocol-independent URL
1192 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
1193 (?:www\.)?deturl\.com/www\.youtube\.com|
1194 (?:www\.)?pwnyoutube\.com|
1195 (?:www\.)?hooktube\.com|
1196 (?:www\.)?yourepeat\.com|
1197 tube\.majestyc\.net|
1199 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
1200 (?:.*?\#/)? # handle anchor (#/) redirect urls
1201 (?: # the various things that can precede the ID:
1202 (?:(?:v|embed|e|shorts|live)/(?!videoseries|live_stream)) # v/ or embed/ or e/ or shorts/
1203 |(?: # or the v= param in all its forms
1204 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
1205 (?:\?|\#!?) # the params delimiter ? or # or #!
1206 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
1211 youtu\.be| # just youtu.be/xxxx
1212 vid\.plus| # or vid.plus/xxxx
1213 zwearz\.com/watch| # or zwearz.com/watch/xxxx
1216 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
1218 )? # all until now is optional -> you can pass the naked ID
1219 (?P<id>[0-9A-Za-z_-]{{11}}) # here is it! the YouTube video ID
1220 (?(1).+)? # if we found the ID, everything can follow
1222 invidious='|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
1227 <(?:[0-9A-Za-z-]+?)?iframe[^>]+?src=|
1235 (?P
<url
>(?
:https?
:)?
//(?
:www\
.)?
youtube(?
:-nocookie
)?\
.com
/
1236 (?
:embed|v|p
)/[0-9A
-Za
-z_
-]{11}
.*?
)
1238 # https://wordpress.org/plugins/lazy-load-for-videos/
1240 <a\s
[^
>]*\bhref
="(?P<url>https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"
1241 \s
[^
>]*\bclass
="[^"]*\blazy
-load
-youtube
''',
1243 _RETURN_TYPE = 'video' # XXX: How to handle multifeed?
1246 r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
1247 r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
1248 r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
1250 _formats = { # NB: Used in YoutubeWebArchiveIE and GoogleDriveIE
1251 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1252 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1253 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
1254 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
1255 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
1256 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1257 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1258 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1259 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
1260 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
1261 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1262 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1263 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1264 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1265 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
1266 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
1267 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1268 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1272 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1273 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1274 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1275 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1276 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
1277 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1278 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1280 # Apple HTTP Live Streaming
1281 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1282 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1283 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1284 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1285 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1286 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1287 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1288 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
1291 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
1292 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
1293 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1294 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
1295 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
1296 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
1297 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
1298 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1299 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
1300 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1301 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1302 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
1305 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
1306 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
1307 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
1308 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1309 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1310 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
1311 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
1314 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1315 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1316 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1317 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1318 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1319 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1320 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
1321 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1322 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1323 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1324 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1325 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1326 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1327 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1328 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1329 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
1330 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1331 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1332 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1333 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1334 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1335 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1338 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
1339 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
1341 # Dash webm audio with opus inside
1342 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
1343 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
1344 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
1347 '_rtmp': {'protocol': 'rtmp'},
1349 # av01 video only formats sometimes served with "unknown" codecs
1350 '394': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'av01.0.00M.08'},
1351 '395': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'av01.0.00M.08'},
1352 '396': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'av01.0.01M.08'},
1353 '397': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'av01.0.04M.08'},
1354 '398': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'av01.0.05M.08'},
1355 '399': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'av01.0.08M.08'},
1356 '400': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'av01.0.12M.08'},
1357 '401': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'av01.0.12M.08'},
1359 _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
1360 _DEFAULT_CLIENTS = ('ios', 'mweb')
1361 _DEFAULT_AUTHED_CLIENTS = ('web_creator', 'mweb')
1368 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
1370 'id': 'BaW_jenozKc',
1372 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
1373 'channel': 'Philipp Hagemeister',
1374 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
1375 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
1376 'upload_date': '20121002',
1377 'description': 'md5:8fb536f4877b8a7455c2ec23794dbc22',
1378 'categories': ['Science & Technology'],
1379 'tags': ['youtube-dl'],
1383 'availability': 'public',
1384 'playable_in_embed': True,
1385 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
1386 'live_status': 'not_live',
1390 'comment_count': int,
1391 'channel_follower_count': int,
1392 'uploader': 'Philipp Hagemeister',
1393 'uploader_url': 'https://www.youtube.com/@PhilippHagemeister',
1394 'uploader_id': '@PhilippHagemeister',
1395 'heatmap': 'count:100',
1396 'timestamp': 1349198244,
1400 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
1401 'note': 'Embed-only video (#1746)',
1403 'id': 'yZIXLfi8CZQ',
1405 'upload_date': '20120608',
1406 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
1407 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
1410 'skip': 'Private video',
1413 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
1414 'note': 'Use the first video ID in the URL',
1416 'id': 'BaW_jenozKc',
1418 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
1419 'channel': 'Philipp Hagemeister',
1420 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
1421 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
1422 'upload_date': '20121002',
1423 'description': 'md5:8fb536f4877b8a7455c2ec23794dbc22',
1424 'categories': ['Science & Technology'],
1425 'tags': ['youtube-dl'],
1429 'availability': 'public',
1430 'playable_in_embed': True,
1431 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
1432 'live_status': 'not_live',
1434 'comment_count': int,
1435 'channel_follower_count': int,
1436 'uploader': 'Philipp Hagemeister',
1437 'uploader_url': 'https://www.youtube.com/@PhilippHagemeister',
1438 'uploader_id': '@PhilippHagemeister',
1439 'heatmap': 'count:100',
1440 'timestamp': 1349198244,
1443 'skip_download': True,
1447 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
1448 'note': '256k DASH audio (format 141) via DASH manifest',
1450 'id': 'a9LDPn-MO4I',
1452 'upload_date': '20121002',
1454 'title': 'UHDTV TEST 8K VIDEO.mp4',
1457 'youtube_include_dash_manifest': True,
1460 'skip': 'format 141 not served anymore',
1462 # DASH manifest with encrypted signature
1464 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
1466 'id': 'IB3lcPjvWLA',
1468 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
1469 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
1471 'upload_date': '20131011',
1474 'channel_id': 'UChuZAo1RKL85gev3Eal9_zg',
1475 'playable_in_embed': True,
1476 'channel_url': 'https://www.youtube.com/channel/UChuZAo1RKL85gev3Eal9_zg',
1478 'track': 'The Spark',
1479 'live_status': 'not_live',
1480 'thumbnail': 'https://i.ytimg.com/vi_webp/IB3lcPjvWLA/maxresdefault.webp',
1481 'channel': 'Afrojack',
1483 'availability': 'public',
1484 'categories': ['Music'],
1486 'alt_title': 'The Spark',
1487 'channel_follower_count': int,
1488 'uploader': 'Afrojack',
1489 'uploader_url': 'https://www.youtube.com/@Afrojack',
1490 'uploader_id': '@Afrojack',
1493 'youtube_include_dash_manifest': True,
1494 'format': '141/bestaudio[ext=m4a]',
1497 # Age-gate videos. See https://github.com/yt-dlp/yt-dlp/pull/575#issuecomment-888837000
1499 'note': 'Embed allowed age-gate video; works with web_embedded',
1500 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
1502 'id': 'HtVdAasjOgU',
1504 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
1505 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
1507 'upload_date': '20140605',
1509 'categories': ['Gaming'],
1510 'thumbnail': 'https://i.ytimg.com/vi_webp/HtVdAasjOgU/maxresdefault.webp',
1511 'availability': 'needs_auth',
1512 'channel_url': 'https://www.youtube.com/channel/UCzybXLxv08IApdjdN0mJhEg',
1514 'channel': 'The Witcher',
1515 'live_status': 'not_live',
1517 'channel_id': 'UCzybXLxv08IApdjdN0mJhEg',
1518 'playable_in_embed': True,
1520 'channel_follower_count': int,
1521 'uploader': 'The Witcher',
1522 'uploader_url': 'https://www.youtube.com/@thewitcher',
1523 'uploader_id': '@thewitcher',
1524 'comment_count': int,
1525 'channel_is_verified': True,
1526 'heatmap': 'count:100',
1527 'timestamp': 1401991663,
1531 'note': 'Age-gate video with embed allowed in public site',
1532 'url': 'https://youtube.com/watch?v=HsUATh_Nc2U',
1534 'id': 'HsUATh_Nc2U',
1536 'title': 'Godzilla 2 (Official Video)',
1537 'description': 'md5:bf77e03fcae5529475e500129b05668a',
1538 'upload_date': '20200408',
1540 'availability': 'needs_auth',
1541 'channel_id': 'UCYQT13AtrJC0gsM1far_zJg',
1542 'channel': 'FlyingKitty',
1543 'channel_url': 'https://www.youtube.com/channel/UCYQT13AtrJC0gsM1far_zJg',
1545 'categories': ['Entertainment'],
1546 'live_status': 'not_live',
1547 'tags': ['Flyingkitty', 'godzilla 2'],
1548 'thumbnail': 'https://i.ytimg.com/vi/HsUATh_Nc2U/maxresdefault.jpg',
1551 'playable_in_embed': True,
1552 'channel_follower_count': int,
1553 'uploader': 'FlyingKitty',
1554 'uploader_url': 'https://www.youtube.com/@FlyingKitty900',
1555 'uploader_id': '@FlyingKitty900',
1556 'comment_count': int,
1557 'channel_is_verified': True,
1559 'skip': 'Age-restricted; requires authentication',
1562 'note': 'Age-gate video embedable only with clientScreen=EMBED',
1563 'url': 'https://youtube.com/watch?v=Tq92D6wQ1mg',
1565 'id': 'Tq92D6wQ1mg',
1566 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
1568 'upload_date': '20191228',
1569 'description': 'md5:17eccca93a786d51bc67646756894066',
1572 'availability': 'needs_auth',
1573 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
1575 'thumbnail': 'https://i.ytimg.com/vi_webp/Tq92D6wQ1mg/sddefault.webp',
1576 'channel': 'Projekt Melody',
1577 'live_status': 'not_live',
1578 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
1579 'playable_in_embed': True,
1580 'categories': ['Entertainment'],
1582 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
1583 'comment_count': int,
1584 'channel_follower_count': int,
1585 'uploader': 'Projekt Melody',
1586 'uploader_url': 'https://www.youtube.com/@ProjektMelody',
1587 'uploader_id': '@ProjektMelody',
1588 'timestamp': 1577508724,
1590 'skip': 'Age-restricted; requires authentication',
1593 'note': 'Non-Agegated non-embeddable video',
1594 'url': 'https://youtube.com/watch?v=MeJVWBSsPAY',
1596 'id': 'MeJVWBSsPAY',
1598 'title': 'OOMPH! - Such Mich Find Mich (Lyrics)',
1599 'description': 'Fan Video. Music & Lyrics by OOMPH!.',
1600 'upload_date': '20130730',
1601 'track': 'Such mich find mich',
1603 'tags': ['oomph', 'such mich find mich', 'lyrics', 'german industrial', 'musica industrial'],
1605 'playable_in_embed': False,
1606 'creator': 'OOMPH!',
1607 'thumbnail': 'https://i.ytimg.com/vi/MeJVWBSsPAY/sddefault.jpg',
1609 'alt_title': 'Such mich find mich',
1611 'channel': 'Herr Lurik',
1612 'channel_id': 'UCdR3RSDPqub28LjZx0v9-aA',
1613 'categories': ['Music'],
1614 'availability': 'public',
1615 'channel_url': 'https://www.youtube.com/channel/UCdR3RSDPqub28LjZx0v9-aA',
1616 'live_status': 'not_live',
1618 'channel_follower_count': int,
1619 'uploader': 'Herr Lurik',
1620 'uploader_url': 'https://www.youtube.com/@HerrLurik',
1621 'uploader_id': '@HerrLurik',
1625 'note': 'Non-bypassable age-gated video',
1626 'url': 'https://youtube.com/watch?v=Cr381pDsSsA',
1627 'only_matching': True,
1629 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
1630 # YouTube Red ad is not captured for creator
1632 'url': '__2ABJjxzNo',
1634 'id': '__2ABJjxzNo',
1637 'upload_date': '20100430',
1638 'creator': 'deadmau5',
1639 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
1640 'title': 'Deadmau5 - Some Chords (HD)',
1641 'alt_title': 'Some Chords',
1642 'availability': 'public',
1644 'channel_id': 'UCYEK6xds6eo-3tr4xRdflmQ',
1646 'live_status': 'not_live',
1647 'channel': 'deadmau5',
1648 'thumbnail': 'https://i.ytimg.com/vi_webp/__2ABJjxzNo/maxresdefault.webp',
1650 'track': 'Some Chords',
1651 'artist': 'deadmau5',
1652 'playable_in_embed': True,
1654 'channel_url': 'https://www.youtube.com/channel/UCYEK6xds6eo-3tr4xRdflmQ',
1655 'categories': ['Music'],
1656 'album': 'Some Chords',
1657 'channel_follower_count': int,
1658 'uploader': 'deadmau5',
1659 'uploader_url': 'https://www.youtube.com/@deadmau5',
1660 'uploader_id': '@deadmau5',
1662 'expected_warnings': [
1663 'DASH manifest missing',
1666 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
1668 'url': 'lqQg6PlCWgI',
1670 'id': 'lqQg6PlCWgI',
1673 'upload_date': '20150827',
1674 'description': 'md5:04bbbf3ccceb6795947572ca36f45904',
1675 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
1677 'release_timestamp': 1343767800,
1678 'playable_in_embed': True,
1679 'categories': ['Sports'],
1680 'release_date': '20120731',
1681 'channel': 'Olympics',
1682 'tags': ['Hockey', '2012-07-31', '31 July 2012', 'Riverbank Arena', 'Session', 'Olympics', 'Olympic Games', 'London 2012', '2012 Summer Olympics', 'Summer Games'],
1683 'channel_id': 'UCTl3QQTvqHFjurroKxexy2Q',
1684 'thumbnail': 'https://i.ytimg.com/vi/lqQg6PlCWgI/maxresdefault.jpg',
1686 'availability': 'public',
1687 'live_status': 'was_live',
1689 'channel_url': 'https://www.youtube.com/channel/UCTl3QQTvqHFjurroKxexy2Q',
1690 'channel_follower_count': int,
1691 'uploader': 'Olympics',
1692 'uploader_url': 'https://www.youtube.com/@Olympics',
1693 'uploader_id': '@Olympics',
1694 'channel_is_verified': True,
1695 'timestamp': 1440707674,
1698 'skip_download': 'requires avconv',
1703 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
1705 'id': '_b-2C3KPAM0',
1707 'stretched_ratio': 16 / 9.,
1709 'upload_date': '20110310',
1710 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
1711 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
1712 'playable_in_embed': True,
1716 'channel_url': 'https://www.youtube.com/channel/UCS-xxCmRaA6BFdmgDPA_BIw',
1717 'channel_id': 'UCS-xxCmRaA6BFdmgDPA_BIw',
1718 'thumbnail': 'https://i.ytimg.com/vi/_b-2C3KPAM0/maxresdefault.jpg',
1720 'categories': ['People & Blogs'],
1722 'live_status': 'not_live',
1723 'availability': 'unlisted',
1724 'comment_count': int,
1725 'channel_follower_count': int,
1727 'uploader_url': 'https://www.youtube.com/@AllenMeow',
1728 'uploader_id': '@AllenMeow',
1729 'timestamp': 1299776999,
1732 # url_encoded_fmt_stream_map is empty string
1734 'url': 'qEJwOuvDf7I',
1736 'id': 'qEJwOuvDf7I',
1738 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
1740 'upload_date': '20150404',
1743 'skip_download': 'requires avconv',
1745 'skip': 'This live event has ended.',
1747 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
1749 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
1751 'id': 'FIl7x6_3R5Y',
1753 'title': 'md5:7b81415841e02ecd4313668cde88737a',
1754 'description': 'md5:116377fd2963b81ec4ce64b542173306',
1756 'upload_date': '20150625',
1757 'formats': 'mincount:31',
1759 'skip': 'not actual anymore',
1761 # DASH manifest with segment_list
1763 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
1764 'md5': '8ce563a1d667b599d21064e982ab9e31',
1766 'id': 'CsmdDsKjzN8',
1768 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
1769 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
1770 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
1773 'youtube_include_dash_manifest': True,
1774 'format': '135', # bestvideo
1776 'skip': 'This live event has ended.',
1779 # Multifeed videos (multiple cameras), URL can be of any Camera
1780 # TODO: fix multifeed titles
1781 'url': 'https://www.youtube.com/watch?v=zaPI8MvL8pg',
1783 'id': 'zaPI8MvL8pg',
1784 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04',
1785 'description': 'md5:563ccbc698b39298481ca3c571169519',
1789 'id': 'j5yGuxZ8lLU',
1791 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04 (Chris)',
1792 'description': 'md5:563ccbc698b39298481ca3c571169519',
1794 'channel_follower_count': int,
1795 'channel_url': 'https://www.youtube.com/channel/UCN2XePorRokPB9TEgRZpddg',
1796 'availability': 'public',
1797 'playable_in_embed': True,
1798 'upload_date': '20131105',
1799 'categories': ['Gaming'],
1800 'live_status': 'was_live',
1802 'release_timestamp': 1383701910,
1803 'thumbnail': 'https://i.ytimg.com/vi/j5yGuxZ8lLU/maxresdefault.jpg',
1804 'comment_count': int,
1807 'channel_id': 'UCN2XePorRokPB9TEgRZpddg',
1808 'channel': 'WiiLikeToPlay',
1810 'release_date': '20131106',
1811 'uploader': 'WiiLikeToPlay',
1812 'uploader_id': '@WLTP',
1813 'uploader_url': 'https://www.youtube.com/@WLTP',
1817 'id': 'zaPI8MvL8pg',
1819 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04 (Tyson)',
1820 'availability': 'public',
1821 'channel_url': 'https://www.youtube.com/channel/UCN2XePorRokPB9TEgRZpddg',
1822 'channel': 'WiiLikeToPlay',
1823 'channel_follower_count': int,
1824 'description': 'md5:563ccbc698b39298481ca3c571169519',
1829 'channel_id': 'UCN2XePorRokPB9TEgRZpddg',
1830 'release_timestamp': 1383701915,
1831 'comment_count': int,
1832 'upload_date': '20131105',
1833 'thumbnail': 'https://i.ytimg.com/vi/zaPI8MvL8pg/maxresdefault.jpg',
1834 'release_date': '20131106',
1835 'playable_in_embed': True,
1836 'live_status': 'was_live',
1837 'categories': ['Gaming'],
1839 'uploader': 'WiiLikeToPlay',
1840 'uploader_id': '@WLTP',
1841 'uploader_url': 'https://www.youtube.com/@WLTP',
1845 'id': 'R7r3vfO7Hao',
1847 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04 (Spencer)',
1848 'thumbnail': 'https://i.ytimg.com/vi/R7r3vfO7Hao/maxresdefault.jpg',
1849 'channel_id': 'UCN2XePorRokPB9TEgRZpddg',
1851 'availability': 'public',
1852 'playable_in_embed': True,
1853 'upload_date': '20131105',
1854 'description': 'md5:563ccbc698b39298481ca3c571169519',
1855 'channel_follower_count': int,
1857 'release_date': '20131106',
1858 'comment_count': int,
1859 'channel_url': 'https://www.youtube.com/channel/UCN2XePorRokPB9TEgRZpddg',
1860 'channel': 'WiiLikeToPlay',
1861 'categories': ['Gaming'],
1862 'release_timestamp': 1383701914,
1863 'live_status': 'was_live',
1867 'uploader': 'WiiLikeToPlay',
1868 'uploader_id': '@WLTP',
1869 'uploader_url': 'https://www.youtube.com/@WLTP',
1872 'params': {'skip_download': True},
1873 'skip': 'Not multifeed anymore',
1876 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
1877 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
1879 'id': 'gVfLd0zydlo',
1880 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
1882 'playlist_count': 2,
1883 'skip': 'Not multifeed anymore',
1886 'url': 'https://vid.plus/FlRa-iH7PGw',
1887 'only_matching': True,
1890 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
1891 'only_matching': True,
1894 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
1895 # Also tests cut-off URL expansion in video description (see
1896 # https://github.com/ytdl-org/youtube-dl/issues/1892,
1897 # https://github.com/ytdl-org/youtube-dl/issues/8164)
1898 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
1900 'id': 'lsguqyKfVQg',
1902 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
1903 'alt_title': 'Dark Walk',
1904 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
1906 'upload_date': '20151119',
1907 'creator': 'Todd Haberman;\nDaniel Law Heath and Aaron Kaplan',
1908 'track': 'Dark Walk',
1909 'artist': 'Todd Haberman;\nDaniel Law Heath and Aaron Kaplan',
1910 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
1911 'thumbnail': 'https://i.ytimg.com/vi_webp/lsguqyKfVQg/maxresdefault.webp',
1912 'categories': ['Film & Animation'],
1914 'live_status': 'not_live',
1915 'channel_url': 'https://www.youtube.com/channel/UCTSRgz5jylBvFt_S7wnsqLQ',
1916 'channel_id': 'UCTSRgz5jylBvFt_S7wnsqLQ',
1918 'availability': 'public',
1919 'channel': 'IronSoulElf',
1920 'playable_in_embed': True,
1923 'channel_follower_count': int,
1926 'skip_download': True,
1930 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
1931 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
1932 'only_matching': True,
1935 # Video with yt:stretch=17:0
1936 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
1938 'id': 'Q39EVAstoRM',
1940 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
1941 'description': 'md5:ee18a25c350637c8faff806845bddee9',
1942 'upload_date': '20151107',
1945 'skip_download': True,
1947 'skip': 'This video does not exist.',
1950 # Video with incomplete 'yt:stretch=16:'
1951 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
1952 'only_matching': True,
1955 # Video licensed under Creative Commons
1956 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
1958 'id': 'M4gD1WSo5mA',
1960 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
1961 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
1963 'upload_date': '20150128',
1964 'license': 'Creative Commons Attribution license (reuse allowed)',
1965 'channel_id': 'UCuLGmD72gJDBwmLw06X58SA',
1966 'channel_url': 'https://www.youtube.com/channel/UCuLGmD72gJDBwmLw06X58SA',
1969 'tags': ['Copyright (Legal Subject)', 'Law (Industry)', 'William W. Fisher (Author)'],
1970 'channel': 'The Berkman Klein Center for Internet & Society',
1971 'availability': 'public',
1973 'categories': ['Education'],
1974 'thumbnail': 'https://i.ytimg.com/vi_webp/M4gD1WSo5mA/maxresdefault.webp',
1975 'live_status': 'not_live',
1976 'playable_in_embed': True,
1977 'channel_follower_count': int,
1979 'uploader': 'The Berkman Klein Center for Internet & Society',
1980 'uploader_id': '@BKCHarvard',
1981 'uploader_url': 'https://www.youtube.com/@BKCHarvard',
1982 'timestamp': 1422422076,
1985 'skip_download': True,
1989 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
1991 'id': 'eQcmzGIKrzg',
1993 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
1994 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
1996 'upload_date': '20151120',
1997 'license': 'Creative Commons Attribution license (reuse allowed)',
1998 'playable_in_embed': True,
2001 'channel_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
2003 'availability': 'public',
2004 'categories': ['News & Politics'],
2005 'channel': 'Bernie Sanders',
2006 'thumbnail': 'https://i.ytimg.com/vi_webp/eQcmzGIKrzg/maxresdefault.webp',
2008 'live_status': 'not_live',
2009 'channel_url': 'https://www.youtube.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
2010 'comment_count': int,
2011 'channel_follower_count': int,
2013 'uploader': 'Bernie Sanders',
2014 'uploader_url': 'https://www.youtube.com/@BernieSanders',
2015 'uploader_id': '@BernieSanders',
2016 'channel_is_verified': True,
2017 'heatmap': 'count:100',
2018 'timestamp': 1447987198,
2021 'skip_download': True,
2025 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
2026 'only_matching': True,
2029 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
2030 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
2031 'only_matching': True,
2034 # Rental video preview
2035 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
2037 'id': 'uGpuVWrhIzE',
2039 'title': 'Piku - Trailer',
2040 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
2041 'upload_date': '20150811',
2042 'license': 'Standard YouTube License',
2045 'skip_download': True,
2047 'skip': 'This video is not available.',
2050 # YouTube Red video with episode data
2051 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
2053 'id': 'iqKdEhx-dD4',
2055 'title': 'Isolation - Mind Field (Ep 1)',
2056 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
2058 'upload_date': '20170118',
2059 'series': 'Mind Field',
2061 'episode_number': 1,
2062 'thumbnail': 'https://i.ytimg.com/vi_webp/iqKdEhx-dD4/maxresdefault.webp',
2065 'availability': 'public',
2067 'channel': 'Vsauce',
2068 'episode': 'Episode 1',
2069 'categories': ['Entertainment'],
2070 'season': 'Season 1',
2071 'channel_id': 'UC6nSFpj9HTCZ5t-N3Rm3-HA',
2072 'channel_url': 'https://www.youtube.com/channel/UC6nSFpj9HTCZ5t-N3Rm3-HA',
2074 'playable_in_embed': True,
2075 'live_status': 'not_live',
2076 'channel_follower_count': int,
2077 'uploader': 'Vsauce',
2078 'uploader_url': 'https://www.youtube.com/@Vsauce',
2079 'uploader_id': '@Vsauce',
2080 'comment_count': int,
2081 'channel_is_verified': True,
2082 'timestamp': 1484761047,
2085 'skip_download': True,
2087 'expected_warnings': [
2088 'Skipping DASH manifest',
2092 # The following content has been identified by the YouTube community
2093 # as inappropriate or offensive to some audiences.
2094 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
2096 'id': '6SJNVb0GnPI',
2098 'title': 'Race Differences in Intelligence',
2099 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
2101 'upload_date': '20140124',
2104 'skip_download': True,
2106 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
2110 'url': '1t24XAntNCY',
2111 'only_matching': True,
2114 # geo restricted to JP
2115 'url': 'sJL6WA-aGkQ',
2116 'only_matching': True,
2119 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
2120 'only_matching': True,
2123 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
2124 'only_matching': True,
2127 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
2128 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
2129 'only_matching': True,
2133 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
2134 'only_matching': True,
2137 # Video with unsupported adaptive stream type formats
2138 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
2140 'id': 'Z4Vy8R84T1U',
2142 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
2143 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
2145 'upload_date': '20130923',
2146 'formats': 'maxcount:10',
2149 'skip_download': True,
2150 'youtube_include_dash_manifest': False,
2152 'skip': 'not actual anymore',
2155 # Youtube Music Auto-generated description
2156 # TODO: fix metadata extraction
2157 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
2159 'id': 'MgNrAu2pzNs',
2161 'title': 'Voyeur Girl',
2162 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
2163 'upload_date': '20190312',
2164 'artists': ['Stephen'],
2165 'creators': ['Stephen'],
2166 'track': 'Voyeur Girl',
2167 'album': 'it\'s too much love to know my dear',
2168 'release_date': '20190313',
2169 'alt_title': 'Voyeur Girl',
2171 'playable_in_embed': True,
2173 'categories': ['Music'],
2174 'channel_url': 'https://www.youtube.com/channel/UC-pWHpBjdGG69N9mM2auIAA',
2175 'channel': 'Stephen', # TODO: should be "Stephen - Topic"
2176 'uploader': 'Stephen',
2177 'availability': 'public',
2179 'thumbnail': 'https://i.ytimg.com/vi_webp/MgNrAu2pzNs/maxresdefault.webp',
2181 'channel_id': 'UC-pWHpBjdGG69N9mM2auIAA',
2183 'live_status': 'not_live',
2184 'channel_follower_count': int,
2187 'skip_download': True,
2191 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
2192 'only_matching': True,
2195 # invalid -> valid video id redirection
2196 'url': 'DJztXj2GPfl',
2198 'id': 'DJztXj2GPfk',
2200 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
2201 'description': 'md5:bf577a41da97918e94fa9798d9228825',
2202 'upload_date': '20090125',
2203 'artist': 'Panjabi MC',
2204 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
2205 'album': 'Beware of the Boys (Mundian To Bach Ke)',
2208 'skip_download': True,
2210 'skip': 'Video unavailable',
2213 # empty description results in an empty string
2214 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
2216 'id': 'x41yOUIvK2k',
2218 'title': 'IMG 3456',
2220 'upload_date': '20170613',
2222 'thumbnail': 'https://i.ytimg.com/vi_webp/x41yOUIvK2k/maxresdefault.webp',
2224 'channel_id': 'UCo03ZQPBW5U4UC3regpt1nw',
2226 'channel_url': 'https://www.youtube.com/channel/UCo03ZQPBW5U4UC3regpt1nw',
2227 'availability': 'public',
2229 'categories': ['Pets & Animals'],
2231 'playable_in_embed': True,
2232 'live_status': 'not_live',
2233 'channel': 'l\'Or Vert asbl',
2234 'channel_follower_count': int,
2235 'uploader': 'l\'Or Vert asbl',
2236 'uploader_url': 'https://www.youtube.com/@ElevageOrVert',
2237 'uploader_id': '@ElevageOrVert',
2238 'timestamp': 1497343210,
2241 'skip_download': True,
2245 # with '};' inside yt initial data (see [1])
2246 # see [2] for an example with '};' inside ytInitialPlayerResponse
2247 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
2248 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
2249 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
2251 'id': 'CHqg6qOn4no',
2253 'title': 'Part 77 Sort a list of simple types in c#',
2254 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
2255 'upload_date': '20130831',
2256 'channel_id': 'UCCTVrRB5KpIiK6V2GGVsR1Q',
2258 'channel_url': 'https://www.youtube.com/channel/UCCTVrRB5KpIiK6V2GGVsR1Q',
2259 'live_status': 'not_live',
2260 'categories': ['Education'],
2261 'availability': 'public',
2262 'thumbnail': 'https://i.ytimg.com/vi/CHqg6qOn4no/sddefault.jpg',
2264 'playable_in_embed': True,
2268 'channel': 'kudvenkat',
2269 'comment_count': int,
2270 'channel_follower_count': int,
2272 'uploader': 'kudvenkat',
2273 'uploader_url': 'https://www.youtube.com/@Csharp-video-tutorialsBlogspot',
2274 'uploader_id': '@Csharp-video-tutorialsBlogspot',
2275 'channel_is_verified': True,
2276 'heatmap': 'count:100',
2277 'timestamp': 1377976349,
2280 'skip_download': True,
2284 # another example of '};' in ytInitialData
2285 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
2286 'only_matching': True,
2289 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
2290 'only_matching': True,
2293 # https://github.com/ytdl-org/youtube-dl/pull/28094
2294 'url': 'OtqTfy26tG0',
2296 'id': 'OtqTfy26tG0',
2298 'title': 'Burn Out',
2299 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
2300 'upload_date': '20141120',
2301 'artist': 'The Cinematic Orchestra',
2302 'track': 'Burn Out',
2303 'album': 'Every Day',
2305 'live_status': 'not_live',
2306 'alt_title': 'Burn Out',
2310 'channel_url': 'https://www.youtube.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
2311 'creator': 'The Cinematic Orchestra',
2312 'channel': 'The Cinematic Orchestra',
2313 'tags': ['The Cinematic Orchestra', 'Every Day', 'Burn Out'],
2314 'channel_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
2315 'availability': 'public',
2316 'thumbnail': 'https://i.ytimg.com/vi/OtqTfy26tG0/maxresdefault.jpg',
2317 'categories': ['Music'],
2318 'playable_in_embed': True,
2319 'channel_follower_count': int,
2320 'uploader': 'The Cinematic Orchestra',
2321 'comment_count': int,
2324 'skip_download': True,
2328 # controversial video, only works with bpctr when authenticated with cookies
2329 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
2330 'only_matching': True,
2333 # controversial video, requires bpctr/contentCheckOk
2334 'url': 'https://www.youtube.com/watch?v=SZJvDhaSDnc',
2336 'id': 'SZJvDhaSDnc',
2338 'title': 'San Diego teen commits suicide after bullying over embarrassing video',
2339 'channel_id': 'UC-SJ6nODDmufqBzPBwCvYvQ',
2340 'upload_date': '20140716',
2341 'description': 'md5:acde3a73d3f133fc97e837a9f76b53b7',
2343 'categories': ['News & Politics'],
2345 'channel': 'CBS Mornings',
2346 'tags': ['suicide', 'bullying', 'video', 'cbs', 'news'],
2347 'thumbnail': 'https://i.ytimg.com/vi/SZJvDhaSDnc/hqdefault.jpg',
2349 'availability': 'needs_auth',
2350 'channel_url': 'https://www.youtube.com/channel/UC-SJ6nODDmufqBzPBwCvYvQ',
2352 'live_status': 'not_live',
2353 'playable_in_embed': True,
2354 'channel_follower_count': int,
2355 'uploader': 'CBS Mornings',
2356 'uploader_url': 'https://www.youtube.com/@CBSMornings',
2357 'uploader_id': '@CBSMornings',
2358 'comment_count': int,
2359 'channel_is_verified': True,
2360 'timestamp': 1405513526,
2362 'skip': 'Age-restricted; requires authentication',
2365 # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
2366 'url': 'cBvYw8_A0vQ',
2368 'id': 'cBvYw8_A0vQ',
2370 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
2371 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
2372 'upload_date': '20201120',
2374 'categories': ['Travel & Events'],
2375 'channel_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
2377 'channel': 'Walk around Japan',
2378 'tags': ['Ueno Tokyo', 'Okachimachi Tokyo', 'Ameyoko Street', 'Tokyo attraction', 'Travel in Tokyo'],
2379 'thumbnail': 'https://i.ytimg.com/vi/cBvYw8_A0vQ/hqdefault.jpg',
2381 'availability': 'public',
2382 'channel_url': 'https://www.youtube.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
2383 'live_status': 'not_live',
2384 'playable_in_embed': True,
2385 'channel_follower_count': int,
2386 'uploader': 'Walk around Japan',
2387 'uploader_url': 'https://www.youtube.com/@walkaroundjapan7124',
2388 'uploader_id': '@walkaroundjapan7124',
2389 'timestamp': 1605884416,
2392 'skip_download': True,
2395 # Has multiple audio streams
2396 'url': 'WaOKSUlf4TM',
2397 'only_matching': True,
2399 # Requires Premium: has format 141 when requested using YTM url
2400 'url': 'https://music.youtube.com/watch?v=XclachpHxis',
2401 'only_matching': True,
2403 # multiple subtitles with same lang_code
2404 'url': 'https://www.youtube.com/watch?v=wsQiKKfKxug',
2405 'only_matching': True,
2407 # Force use android client fallback
2408 'url': 'https://www.youtube.com/watch?v=YOelRv7fMxY',
2410 'id': 'YOelRv7fMxY',
2411 'title': 'DIGGING A SECRET TUNNEL Part 1',
2413 'upload_date': '20210624',
2414 'channel_id': 'UCp68_FLety0O-n9QU6phsgw',
2415 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCp68_FLety0O-n9QU6phsgw',
2416 'description': 'md5:5d5991195d599b56cd0c4148907eec50',
2418 'categories': ['Entertainment'],
2420 'channel': 'colinfurze',
2421 'tags': ['Colin', 'furze', 'Terry', 'tunnel', 'underground', 'bunker'],
2422 'thumbnail': 'https://i.ytimg.com/vi/YOelRv7fMxY/maxresdefault.jpg',
2424 'availability': 'public',
2426 'live_status': 'not_live',
2427 'playable_in_embed': True,
2428 'channel_follower_count': int,
2430 'uploader': 'colinfurze',
2431 'uploader_url': 'https://www.youtube.com/@colinfurze',
2432 'uploader_id': '@colinfurze',
2433 'comment_count': int,
2434 'channel_is_verified': True,
2435 'heatmap': 'count:100',
2438 'format': '17', # 3gp format available on android
2439 'extractor_args': {'youtube': {'player_client': ['android']}},
2441 'skip': 'android client broken',
2444 # Skip download of additional client configs (remix client config in this case)
2445 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
2446 'only_matching': True,
2448 'extractor_args': {'youtube': {'player_skip': ['configs']}},
2452 'url': 'https://www.youtube.com/shorts/BGQWPY4IigY',
2453 'only_matching': True,
2455 'note': 'Storyboards',
2456 'url': 'https://www.youtube.com/watch?v=5KLPxDtMqe8',
2458 'id': '5KLPxDtMqe8',
2461 'title': 'Your Brain is Plastic',
2462 'description': 'md5:89cd86034bdb5466cd87c6ba206cd2bc',
2463 'upload_date': '20140324',
2465 'channel_id': 'UCZYTClx2T1of7BRZ86-8fow',
2466 'channel_url': 'https://www.youtube.com/channel/UCZYTClx2T1of7BRZ86-8fow',
2468 'thumbnail': 'https://i.ytimg.com/vi/5KLPxDtMqe8/maxresdefault.jpg',
2469 'playable_in_embed': True,
2471 'availability': 'public',
2472 'channel': 'SciShow',
2473 'live_status': 'not_live',
2475 'categories': ['Education'],
2477 'channel_follower_count': int,
2479 'uploader': 'SciShow',
2480 'uploader_url': 'https://www.youtube.com/@SciShow',
2481 'uploader_id': '@SciShow',
2482 'comment_count': int,
2483 'channel_is_verified': True,
2484 'heatmap': 'count:100',
2485 'timestamp': 1395685455,
2486 }, 'params': {'format': 'mhtml', 'skip_download': True},
2488 # Ensure video upload_date is in UTC timezone (video was uploaded 1641170939)
2489 'url': 'https://www.youtube.com/watch?v=2NUZ8W2llS4',
2491 'id': '2NUZ8W2llS4',
2493 'title': 'The NP that test your phone performance 🙂',
2494 'description': 'md5:144494b24d4f9dfacb97c1bbef5de84d',
2495 'channel_id': 'UCRqNBSOHgilHfAczlUmlWHA',
2496 'channel_url': 'https://www.youtube.com/channel/UCRqNBSOHgilHfAczlUmlWHA',
2500 'categories': ['Gaming'],
2502 'playable_in_embed': True,
2503 'live_status': 'not_live',
2504 'upload_date': '20220103',
2506 'availability': 'public',
2507 'channel': 'Leon Nguyen',
2508 'thumbnail': 'https://i.ytimg.com/vi_webp/2NUZ8W2llS4/maxresdefault.webp',
2509 'comment_count': int,
2510 'channel_follower_count': int,
2511 'uploader': 'Leon Nguyen',
2512 'uploader_url': 'https://www.youtube.com/@LeonNguyen',
2513 'uploader_id': '@LeonNguyen',
2514 'heatmap': 'count:100',
2515 'timestamp': 1641170939,
2518 # date text is premiered video, ensure upload date in UTC (published 1641172509)
2519 'url': 'https://www.youtube.com/watch?v=mzZzzBU6lrM',
2521 'id': 'mzZzzBU6lrM',
2523 'title': 'I Met GeorgeNotFound In Real Life...',
2524 'description': 'md5:978296ec9783a031738b684d4ebf302d',
2525 'channel_id': 'UC_8NknAFiyhOUaZqHR3lq3Q',
2526 'channel_url': 'https://www.youtube.com/channel/UC_8NknAFiyhOUaZqHR3lq3Q',
2530 'categories': ['Entertainment'],
2532 'playable_in_embed': True,
2533 'live_status': 'not_live',
2534 'release_timestamp': 1641172509,
2535 'release_date': '20220103',
2536 'upload_date': '20220103',
2538 'availability': 'public',
2539 'channel': 'Quackity',
2540 'thumbnail': 'https://i.ytimg.com/vi/mzZzzBU6lrM/maxresdefault.jpg',
2541 'channel_follower_count': int,
2542 'uploader': 'Quackity',
2543 'uploader_id': '@Quackity',
2544 'uploader_url': 'https://www.youtube.com/@Quackity',
2545 'comment_count': int,
2546 'channel_is_verified': True,
2547 'heatmap': 'count:100',
2548 'timestamp': 1641172509,
2551 { # continuous livestream.
2552 # Upload date was 2022-07-12T05:12:29-07:00, while stream start is 2022-07-12T15:59:30+00:00
2553 'url': 'https://www.youtube.com/watch?v=jfKfPfyJRdk',
2555 'id': 'jfKfPfyJRdk',
2557 'channel_id': 'UCSJ4gkVC6NrvII8umztf0Ow',
2559 'uploader': 'Lofi Girl',
2560 'categories': ['Music'],
2561 'concurrent_view_count': int,
2562 'playable_in_embed': True,
2563 'timestamp': 1657627949,
2564 'release_date': '20220712',
2565 'channel_url': 'https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow',
2566 'description': 'md5:13a6f76df898f5674f9127139f3df6f7',
2568 'thumbnail': 'https://i.ytimg.com/vi/jfKfPfyJRdk/maxresdefault.jpg',
2569 'release_timestamp': 1657641570,
2570 'uploader_url': 'https://www.youtube.com/@LofiGirl',
2571 'channel_follower_count': int,
2572 'channel_is_verified': True,
2573 'title': r're:^lofi hip hop radio 📚 - beats to relax/study to',
2575 'live_status': 'is_live',
2577 'channel': 'Lofi Girl',
2578 'availability': 'public',
2579 'upload_date': '20220712',
2580 'uploader_id': '@LofiGirl',
2582 'params': {'skip_download': True},
2584 'url': 'https://www.youtube.com/watch?v=tjjjtzRLHvA',
2586 'id': 'tjjjtzRLHvA',
2588 'title': 'ハッシュタグ無し };if window.ytcsi',
2589 'upload_date': '20220323',
2591 'availability': 'unlisted',
2592 'channel': 'Lesmiscore',
2593 'thumbnail': r're:^https?://.*\.jpg',
2595 'categories': ['Music'],
2598 'channel_url': 'https://www.youtube.com/channel/UCdqltm_7iv1Vs6kp6Syke5A',
2599 'channel_id': 'UCdqltm_7iv1Vs6kp6Syke5A',
2600 'live_status': 'not_live',
2601 'playable_in_embed': True,
2602 'channel_follower_count': int,
2605 'uploader_id': '@lesmiscore',
2606 'uploader': 'Lesmiscore',
2607 'uploader_url': 'https://www.youtube.com/@lesmiscore',
2608 'timestamp': 1648005313,
2611 # Prefer primary title+description language metadata by default
2612 # Do not prefer translated description if primary is empty
2613 'url': 'https://www.youtube.com/watch?v=el3E4MbxRqQ',
2615 'id': 'el3E4MbxRqQ',
2617 'title': 'dlp test video 2 - primary sv no desc',
2619 'channel': 'cole-dlp-test-acc',
2622 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
2624 'playable_in_embed': True,
2625 'availability': 'unlisted',
2626 'thumbnail': r're:^https?://.*\.jpg',
2629 'live_status': 'not_live',
2630 'upload_date': '20220908',
2631 'categories': ['People & Blogs'],
2632 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
2633 'uploader_url': 'https://www.youtube.com/@coletdjnz',
2634 'uploader_id': '@coletdjnz',
2635 'uploader': 'cole-dlp-test-acc',
2636 'timestamp': 1662677394,
2638 'params': {'skip_download': True},
2640 # Extractor argument: prefer translated title+description
2641 'url': 'https://www.youtube.com/watch?v=gHKT4uU8Zng',
2643 'id': 'gHKT4uU8Zng',
2645 'channel': 'cole-dlp-test-acc',
2648 'live_status': 'not_live',
2649 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
2650 'upload_date': '20220729',
2652 'categories': ['People & Blogs'],
2653 'thumbnail': r're:^https?://.*\.jpg',
2654 'title': 'dlp test video title translated (fr)',
2655 'availability': 'public',
2657 'description': 'dlp test video description translated (fr)',
2658 'playable_in_embed': True,
2659 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
2660 'uploader_url': 'https://www.youtube.com/@coletdjnz',
2661 'uploader_id': '@coletdjnz',
2662 'uploader': 'cole-dlp-test-acc',
2663 'timestamp': 1659073275,
2666 'params': {'skip_download': True, 'extractor_args': {'youtube': {'lang': ['fr']}}},
2667 'expected_warnings': [r'Preferring "fr" translated fields'],
2669 'note': '6 channel audio',
2670 'url': 'https://www.youtube.com/watch?v=zgdo7-RRjgo',
2671 'only_matching': True,
2673 'note': 'Multiple HLS formats with same itag',
2674 'url': 'https://www.youtube.com/watch?v=kX3nB4PpJko',
2676 'id': 'kX3nB4PpJko',
2678 'categories': ['Entertainment'],
2679 'description': 'md5:e8031ff6e426cdb6a77670c9b81f6fa6',
2680 'live_status': 'not_live',
2682 'channel_follower_count': int,
2683 'thumbnail': 'https://i.ytimg.com/vi_webp/kX3nB4PpJko/maxresdefault.webp',
2684 'title': 'Last To Take Hand Off Jet, Keeps It!',
2685 'channel': 'MrBeast',
2686 'playable_in_embed': True,
2688 'upload_date': '20221112',
2689 'channel_url': 'https://www.youtube.com/channel/UCX6OQ3DkcsbYNE6H8uQQuVA',
2691 'availability': 'public',
2692 'channel_id': 'UCX6OQ3DkcsbYNE6H8uQQuVA',
2695 'uploader': 'MrBeast',
2696 'uploader_url': 'https://www.youtube.com/@MrBeast',
2697 'uploader_id': '@MrBeast',
2698 'comment_count': int,
2699 'channel_is_verified': True,
2700 'heatmap': 'count:100',
2702 'params': {'extractor_args': {'youtube': {'player_client': ['ios']}}, 'format': '233-1'},
2704 'note': 'Audio formats with Dynamic Range Compression',
2705 'url': 'https://www.youtube.com/watch?v=Tq92D6wQ1mg',
2707 'id': 'Tq92D6wQ1mg',
2709 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
2710 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
2711 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
2712 'channel_follower_count': int,
2713 'description': 'md5:17eccca93a786d51bc67646756894066',
2714 'upload_date': '20191228',
2715 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
2716 'playable_in_embed': True,
2718 'categories': ['Entertainment'],
2719 'thumbnail': 'https://i.ytimg.com/vi/Tq92D6wQ1mg/sddefault.jpg',
2721 'channel': 'Projekt Melody',
2723 'availability': 'needs_auth',
2724 'comment_count': int,
2725 'live_status': 'not_live',
2727 'uploader': 'Projekt Melody',
2728 'uploader_id': '@ProjektMelody',
2729 'uploader_url': 'https://www.youtube.com/@ProjektMelody',
2730 'timestamp': 1577508724,
2732 'params': {'extractor_args': {'youtube': {'player_client': ['tv_embedded']}}, 'format': '251-drc'},
2733 'skip': 'Age-restricted; requires authentication',
2736 'url': 'https://www.youtube.com/live/qVv6vCqciTM',
2738 'id': 'qVv6vCqciTM',
2741 'comment_count': int,
2742 'chapters': 'count:13',
2743 'upload_date': '20221223',
2744 'thumbnail': 'https://i.ytimg.com/vi/qVv6vCqciTM/maxresdefault.jpg',
2745 'channel_url': 'https://www.youtube.com/channel/UCIdEIHpS0TdkqRkHL5OkLtA',
2747 'release_date': '20221223',
2748 'tags': ['Vtuber', '月ノ美兎', '名取さな', 'にじさんじ', 'クリスマス', '3D配信'],
2749 'title': '【 #インターネット女クリスマス 】3Dで歌ってはしゃぐインターネットの女たち【月ノ美兎/名取さな】',
2751 'playable_in_embed': True,
2753 'availability': 'public',
2754 'channel_follower_count': int,
2755 'channel_id': 'UCIdEIHpS0TdkqRkHL5OkLtA',
2756 'categories': ['Entertainment'],
2757 'live_status': 'was_live',
2758 'release_timestamp': 1671793345,
2759 'channel': 'さなちゃんねる',
2760 'description': 'md5:6aebf95cc4a1d731aebc01ad6cc9806d',
2761 'uploader': 'さなちゃんねる',
2762 'uploader_url': 'https://www.youtube.com/@sana_natori',
2763 'uploader_id': '@sana_natori',
2764 'channel_is_verified': True,
2765 'heatmap': 'count:100',
2766 'timestamp': 1671798112,
2770 # Fallbacks when webpage and web client is unavailable
2771 'url': 'https://www.youtube.com/watch?v=wSSmNUl9Snw',
2773 'id': 'wSSmNUl9Snw',
2775 # 'categories': ['Science & Technology'],
2777 'chapters': 'count:2',
2778 'channel': 'Scott Manley',
2781 # 'availability': 'public',
2782 'channel_follower_count': int,
2783 'live_status': 'not_live',
2784 'upload_date': '20170831',
2787 'uploader_url': 'https://www.youtube.com/@scottmanley',
2788 'description': 'md5:f4bed7b200404b72a394c2f97b782c02',
2789 'uploader': 'Scott Manley',
2790 'uploader_id': '@scottmanley',
2791 'title': 'The Computer Hack That Saved Apollo 14',
2792 'channel_id': 'UCxzC4EngIsMrPmbm6Nxvb-A',
2793 'thumbnail': r're:^https?://.*\.webp',
2794 'channel_url': 'https://www.youtube.com/channel/UCxzC4EngIsMrPmbm6Nxvb-A',
2795 'playable_in_embed': True,
2796 'comment_count': int,
2797 'channel_is_verified': True,
2798 'heatmap': 'count:100',
2801 'extractor_args': {'youtube': {'player_client': ['ios'], 'player_skip': ['webpage']}},
2805 # uploader_id has non-ASCII characters that are percent-encoded in YT's JSON
2806 'url': 'https://www.youtube.com/shorts/18NGQq7p3LY',
2808 'id': '18NGQq7p3LY',
2810 'title': '아이브 이서 장원영 리즈 삐끼삐끼 챌린지',
2813 'uploader_id': '@으아-v1k',
2814 'uploader_url': 'https://www.youtube.com/@으아-v1k',
2816 'channel_id': 'UCC25oTm2J7ZVoi5TngOHg9g',
2817 'channel_url': 'https://www.youtube.com/channel/UCC25oTm2J7ZVoi5TngOHg9g',
2818 'thumbnail': r're:https?://.+/.+\.jpg',
2819 'playable_in_embed': True,
2822 'timestamp': 1724306170,
2823 'upload_date': '20240822',
2824 'availability': 'public',
2825 'live_status': 'not_live',
2828 'channel_follower_count': int,
2829 'categories': ['People & Blogs'],
2836 # YouTube <object> embed
2838 'url': 'http://www.improbable.com/2017/04/03/untrained-modern-youths-and-ancient-masters-in-selfie-portraits/',
2839 'md5': '873c81d308b979f0e23ee7e620b312a3',
2841 'id': 'msN87y-iEx0',
2843 'title': 'Feynman: Mirrors FUN TO IMAGINE 6',
2844 'upload_date': '20080526',
2845 'description': 'md5:873c81d308b979f0e23ee7e620b312a3',
2847 'tags': ['feynman', 'mirror', 'science', 'physics', 'imagination', 'fun', 'cool', 'puzzle'],
2848 'channel_id': 'UCCeo--lls1vna5YJABWAcVA',
2849 'playable_in_embed': True,
2850 'thumbnail': 'https://i.ytimg.com/vi/msN87y-iEx0/hqdefault.jpg',
2852 'comment_count': int,
2853 'channel': 'Christopher Sykes',
2854 'live_status': 'not_live',
2855 'channel_url': 'https://www.youtube.com/channel/UCCeo--lls1vna5YJABWAcVA',
2856 'availability': 'public',
2859 'categories': ['Science & Technology'],
2860 'channel_follower_count': int,
2861 'uploader': 'Christopher Sykes',
2862 'uploader_url': 'https://www.youtube.com/@ChristopherSykesDocumentaries',
2863 'uploader_id': '@ChristopherSykesDocumentaries',
2864 'heatmap': 'count:100',
2865 'timestamp': 1211825920,
2868 'skip_download': True,
2874 def suitable(cls, url):
2875 from ..utils import parse_qs
2878 if qs.get('list', [None])[0]:
2880 return super().suitable(url)
2882 def __init__(self, *args, **kwargs):
2883 super().__init__(*args, **kwargs)
2884 self._code_cache = {}
2885 self._player_cache = {}
2887 def _prepare_live_from_start_formats(self, formats, video_id, live_start_time, url, webpage_url, smuggled_data, is_live):
2888 lock = threading.Lock()
2889 start_time = time.time()
2890 formats = [f for f in formats if f.get('is_from_start')]
2892 def refetch_manifest(format_id, delay):
2893 nonlocal formats, start_time, is_live
2894 if time.time() <= start_time + delay:
2897 _, _, prs, player_url = self._download_player_responses(url, smuggled_data, video_id, webpage_url)
2898 video_details = traverse_obj(prs, (..., 'videoDetails'), expected_type=dict)
2899 microformats = traverse_obj(
2900 prs, (..., 'microformat', 'playerMicroformatRenderer'),
2902 _, live_status, _, formats, _ = self._list_formats(video_id, microformats, video_details, prs, player_url)
2903 is_live = live_status == 'is_live'
2904 start_time = time.time()
2906 def mpd_feed(format_id, delay):
2908 @returns (manifest_url, manifest_stream_number, is_live) or None
2910 for retry in self.RetryManager(fatal=False):
2912 refetch_manifest(format_id, delay)
2914 f = next((f for f in formats if f['format_id'] == format_id), None)
2917 retry.error = f'{video_id}: Video is no longer live'
2919 retry.error = f'Cannot find refreshed manifest for format {format_id}{bug_reports_message()}'
2921 return f['manifest_url'], f['manifest_stream_number'], is_live
2925 f['is_live'] = is_live
2926 gen = functools.partial(self._live_dash_fragments, video_id, f['format_id'],
2927 live_start_time, mpd_feed, not is_live and f.copy())
2929 f['fragments'] = gen
2930 f['protocol'] = 'http_dash_segments_generator'
2932 f['fragments'] = LazyList(gen({}))
2933 del f['is_from_start']
2935 def _live_dash_fragments(self, video_id, format_id, live_start_time, mpd_feed, manifestless_orig_fmt, ctx):
2936 FETCH_SPAN, MAX_DURATION = 5, 432000
2938 mpd_url, stream_number, is_live = None, None, True
2941 download_start_time = ctx.get('start') or time.time()
2943 lack_early_segments = download_start_time - (live_start_time or download_start_time) > MAX_DURATION
2944 if lack_early_segments:
2945 self.report_warning(bug_reports_message(
2946 'Starting download from the last 120 hours of the live stream since '
2947 'YouTube does not have data before that. If you think this is wrong,'), only_once=True)
2948 lack_early_segments = True
2950 known_idx, no_fragment_score, last_segment_url = begin_index, 0, None
2951 fragments, fragment_base_url = None, None
2953 def _extract_sequence_from_mpd(refresh_sequence, immediate):
2954 nonlocal mpd_url, stream_number, is_live, no_fragment_score, fragments, fragment_base_url
2955 # Obtain from MPD's maximum seq value
2956 old_mpd_url = mpd_url
2957 last_error = ctx.pop('last_error', None)
2958 expire_fast = immediate or (last_error and isinstance(last_error, HTTPError) and last_error.status == 403)
2959 mpd_url, stream_number, is_live = (mpd_feed(format_id, 5 if expire_fast else 18000)
2960 or (mpd_url, stream_number, False))
2961 if not refresh_sequence:
2962 if expire_fast and not is_live:
2963 return False, last_seq
2964 elif old_mpd_url == mpd_url:
2965 return True, last_seq
2966 if manifestless_orig_fmt:
2967 fmt_info = manifestless_orig_fmt
2970 fmts, _ = self._extract_mpd_formats_and_subtitles(
2971 mpd_url, None, note=False, errnote=False, fatal=False)
2972 except ExtractorError:
2975 no_fragment_score += 2
2976 return False, last_seq
2977 fmt_info = next(x for x in fmts if x['manifest_stream_number'] == stream_number)
2978 fragments = fmt_info['fragments']
2979 fragment_base_url = fmt_info['fragment_base_url']
2980 assert fragment_base_url
2982 _last_seq = int(re.search(r'(?:/|^)sq/(\d+)', fragments[-1]['path']).group(1))
2983 return True, _last_seq
2985 self.write_debug(f'[{video_id}] Generating fragments for format {format_id}')
2987 fetch_time = time.time()
2988 if no_fragment_score > 30:
2990 if last_segment_url:
2991 # Obtain from "X-Head-Seqnum" header value from each segment
2993 urlh = self._request_webpage(
2994 last_segment_url, None, note=False, errnote=False, fatal=False)
2995 except ExtractorError:
2997 last_seq = try_get(urlh, lambda x: int_or_none(x.headers['X-Head-Seqnum']))
2998 if last_seq is None:
2999 no_fragment_score += 2
3000 last_segment_url = None
3003 should_continue, last_seq = _extract_sequence_from_mpd(True, no_fragment_score > 15)
3004 no_fragment_score += 2
3005 if not should_continue:
3008 if known_idx > last_seq:
3009 last_segment_url = None
3014 if begin_index < 0 and known_idx < 0:
3015 # skip from the start when it's negative value
3016 known_idx = last_seq + begin_index
3017 if lack_early_segments:
3018 known_idx = max(known_idx, last_seq - int(MAX_DURATION // fragments[-1]['duration']))
3020 for idx in range(known_idx, last_seq):
3021 # do not update sequence here or you'll get skipped some part of it
3022 should_continue, _ = _extract_sequence_from_mpd(False, False)
3023 if not should_continue:
3025 raise ExtractorError('breaking out of outer loop')
3026 last_segment_url = urljoin(fragment_base_url, f'sq/{idx}')
3028 'url': last_segment_url,
3029 'fragment_count': last_seq,
3031 if known_idx == last_seq:
3032 no_fragment_score += 5
3034 no_fragment_score = 0
3035 known_idx = last_seq
3036 except ExtractorError:
3039 if manifestless_orig_fmt:
3040 # Stop at the first iteration if running for post-live manifestless;
3041 # fragment count no longer increase since it starts
3044 time.sleep(max(0, FETCH_SPAN + fetch_time - time.time()))
3046 def _extract_player_url(self, *ytcfgs, webpage=None):
3047 player_url = traverse_obj(
3048 ytcfgs, (..., 'PLAYER_JS_URL'), (..., 'WEB_PLAYER_CONTEXT_CONFIGS', ..., 'jsUrl'),
3049 get_all=False, expected_type=str)
3052 return urljoin('https://www.youtube.com', player_url)
3054 def _download_player_url(self, video_id, fatal=False):
3055 res = self._download_webpage(
3056 'https://www.youtube.com/iframe_api',
3057 note='Downloading iframe API JS', video_id=video_id, fatal=fatal)
3059 player_version = self._search_regex(
3060 r'player\\?/([0-9a-fA-F]{8})\\?/', res, 'player version', fatal=fatal)
3062 return f'https://www.youtube.com/s/player/{player_version}/player_ias.vflset/en_US/base.js'
3064 def _signature_cache_id(self, example_sig):
3065 """ Return a string representation of a signature """
3066 return '.'.join(str(len(part)) for part in example_sig.split('.'))
3069 def _extract_player_info(cls, player_url):
3070 for player_re in cls._PLAYER_INFO_RE:
3071 id_m = re.search(player_re, player_url)
3075 raise ExtractorError(f'Cannot identify player {player_url!r}')
3076 return id_m.group('id')
3078 def _load_player(self, video_id, player_url, fatal=True):
3079 player_id = self._extract_player_info(player_url)
3080 if player_id not in self._code_cache:
3081 code = self._download_webpage(
3082 player_url, video_id, fatal=fatal,
3083 note='Downloading player ' + player_id,
3084 errnote=f'Download of {player_url} failed')
3086 self._code_cache[player_id] = code
3087 return self._code_cache.get(player_id)
3089 def _extract_signature_function(self, video_id, player_url, example_sig):
3090 player_id = self._extract_player_info(player_url)
3092 # Read from filesystem cache
3093 func_id = f'js_{player_id}_{self._signature_cache_id(example_sig)}'
3094 assert os.path.basename(func_id) == func_id
3096 self.write_debug(f'Extracting signature function {func_id}')
3097 cache_spec, code = self.cache.load('youtube-sigfuncs', func_id), None
3100 code = self._load_player(video_id, player_url)
3102 res = self._parse_sig_js(code)
3103 test_string = ''.join(map(chr, range(len(example_sig))))
3104 cache_spec = [ord(c) for c in res(test_string)]
3105 self.cache.store('youtube-sigfuncs', func_id, cache_spec)
3107 return lambda s: ''.join(s[i] for i in cache_spec)
3109 def _print_sig_code(self, func, example_sig):
3110 if not self.get_param('youtube_print_sig_code'):
3113 def gen_sig_code(idxs):
3114 def _genslice(start, end, step):
3115 starts = '' if start == 0 else str(start)
3116 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
3117 steps = '' if step == 1 else (':%d' % step)
3118 return f's[{starts}{ends}{steps}]'
3121 # Quelch pyflakes warnings - start will be set when step is set
3122 start = '(Never used)'
3123 for i, prev in zip(idxs[1:], idxs[:-1]):
3124 if step is not None:
3125 if i - prev == step:
3127 yield _genslice(start, prev, step)
3130 if i - prev in [-1, 1]:
3135 yield 's[%d]' % prev
3139 yield _genslice(start, i, step)
3141 test_string = ''.join(map(chr, range(len(example_sig))))
3142 cache_res = func(test_string)
3143 cache_spec = [ord(c) for c in cache_res]
3144 expr_code = ' + '.join(gen_sig_code(cache_spec))
3145 signature_id_tuple = '({})'.format(', '.join(str(len(p)) for p in example_sig.split('.')))
3146 code = (f'if tuple(len(p) for p in s.split(\'.\')) == {signature_id_tuple}:\n'
3147 f' return {expr_code}\n')
3148 self.to_screen('Extracted signature function:\n' + code)
3150 def _parse_sig_js(self, jscode):
3151 # Examples where `sig` is funcname:
3152 # sig=function(a){a=a.split(""); ... ;return a.join("")};
3153 # ;c&&(c=sig(decodeURIComponent(c)),a.set(b,encodeURIComponent(c)));return a};
3154 # {var l=f,m=h.sp,n=sig(decodeURIComponent(h.s));l.set(m,encodeURIComponent(n))}
3155 # sig=function(J){J=J.split(""); ... ;return J.join("")};
3156 # ;N&&(N=sig(decodeURIComponent(N)),J.set(R,encodeURIComponent(N)));return J};
3157 # {var H=u,k=f.sp,v=sig(decodeURIComponent(f.s));H.set(k,encodeURIComponent(v))}
3158 funcname = self._search_regex(
3159 (r'\b(?P<var>[a-zA-Z0-9_$]+)&&\((?P=var)=(?P<sig>[a-zA-Z0-9_$]{2,})\(decodeURIComponent\((?P=var)\)\)',
3160 r'(?P<sig>[a-zA-Z0-9_$]+)\s*=\s*function\(\s*(?P<arg>[a-zA-Z0-9_$]+)\s*\)\s*{\s*(?P=arg)\s*=\s*(?P=arg)\.split\(\s*""\s*\)\s*;\s*[^}]+;\s*return\s+(?P=arg)\.join\(\s*""\s*\)',
3161 r'(?:\b|[^a-zA-Z0-9_$])(?P<sig>[a-zA-Z0-9_$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)(?:;[a-zA-Z0-9_$]{2}\.[a-zA-Z0-9_$]{2}\(a,\d+\))?',
3163 r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
3164 r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
3165 r'\bm=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(h\.s\)\)',
3167 r'("|\')signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
3168 r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
3169 r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
3170 r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
3171 r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
3172 jscode, 'Initial JS player signature function name', group='sig')
3174 jsi = JSInterpreter(jscode)
3175 initial_function = jsi.extract_function(funcname)
3176 return lambda s: initial_function([s])
3178 def _cached(self, func, *cache_id):
3179 def inner(*args, **kwargs):
3180 if cache_id not in self._player_cache:
3182 self._player_cache[cache_id] = func(*args, **kwargs)
3183 except ExtractorError as e:
3184 self._player_cache[cache_id] = e
3185 except Exception as e:
3186 self._player_cache[cache_id] = ExtractorError(traceback.format_exc(), cause=e)
3188 ret = self._player_cache[cache_id]
3189 if isinstance(ret, Exception):
3194 def _decrypt_signature(self, s, video_id, player_url):
3195 """Turn the encrypted s field into a working signature"""
3196 extract_sig = self._cached(
3197 self._extract_signature_function, 'sig', player_url, self._signature_cache_id(s))
3198 func = extract_sig(video_id, player_url, s)
3199 self._print_sig_code(func, s)
3202 def _decrypt_nsig(self, s, video_id, player_url):
3203 """Turn the encrypted n field into a working signature"""
3204 if player_url is None:
3205 raise ExtractorError('Cannot decrypt nsig without player_url')
3206 player_url = urljoin('https://www.youtube.com', player_url)
3209 jsi, player_id, func_code = self._extract_n_function_code(video_id, player_url)
3210 except ExtractorError as e:
3211 raise ExtractorError('Unable to extract nsig function code', cause=e)
3212 if self.get_param('youtube_print_sig_code'):
3213 self.to_screen(f'Extracted nsig function from {player_id}:\n{func_code[1]}\n')
3216 extract_nsig = self._cached(self._extract_n_function_from_code, 'nsig func', player_url)
3217 ret = extract_nsig(jsi, func_code)(s)
3218 except JSInterpreter.Exception as e:
3220 jsi = PhantomJSwrapper(self, timeout=5000)
3221 except ExtractorError:
3223 self.report_warning(
3224 f'Native nsig extraction failed: Trying with PhantomJS\n'
3225 f' n = {s} ; player = {player_url}', video_id)
3226 self.write_debug(e, only_once=True)
3228 args, func_body = func_code
3230 f'console.log(function({", ".join(args)}) {{ {func_body} }}({s!r}));',
3231 video_id=video_id, note='Executing signature code').strip()
3233 self.write_debug(f'Decrypted nsig {s} => {ret}')
3236 def _extract_n_function_name(self, jscode, player_url=None):
3237 # Examples (with placeholders nfunc, narray, idx):
3238 # * .get("n"))&&(b=nfunc(b)
3239 # * .get("n"))&&(b=narray[idx](b)
3240 # * b=String.fromCharCode(110),c=a.get(b))&&c=narray[idx](c)
3241 # * a.D&&(b="nn"[+a.D],c=a.get(b))&&(c=narray[idx](c),a.set(b,c),narray.length||nfunc("")
3242 # * a.D&&(PL(a),b=a.j.n||null)&&(b=narray[0](b),a.set("n",b),narray.length||nfunc("")
3243 # * a.D&&(b="nn"[+a.D],vL(a),c=a.j[b]||null)&&(c=narray[idx](c),a.set(b,c),narray.length||nfunc("")
3244 # * J.J="";J.url="";J.Z&&(R="nn"[+J.Z],mW(J),N=J.K[R]||null)&&(N=narray[idx](N),J.set(R,N))}};
3245 funcname, idx = self._search_regex(
3248 \
.get\
("n"\
)\
)&&\
(b
=|
3250 b
=String\
.fromCharCode\
(110\
)|
3251 (?P
<str_idx
>[a
-zA
-Z0
-9_$
.]+)&&\
(b
="nn"\
[\
+(?P
=str_idx
)\
]
3254 ,[a
-zA
-Z0
-9_$
]+\
(a\
))?
,c
=a\
.
3257 [a
-zA
-Z0
-9_$
]+\
[b\
]\|\|null
3259 \b(?P
<var
>[a
-zA
-Z0
-9_$
]+)=
3260 )(?P
<nfunc
>[a
-zA
-Z0
-9_$
]+)(?
:\
[(?P
<idx
>\d
+)\
])?\
([a
-zA
-Z
]\
)
3261 (?
(var
),[a
-zA
-Z0
-9_$
]+\
.set\
((?
:"n+"|
[a
-zA
-Z0
-9_$
]+)\
,(?P
=var
)\
))''',
3262 jscode, 'n function name', group=('nfunc', 'idx'), default=(None, None))
3264 self.report_warning(join_nonempty(
3265 'Falling back to generic n function search',
3266 player_url and f' player = {player_url}', delim='\n'))
3267 return self._search_regex(
3269 ;\s
*(?P
<name
>[a
-zA
-Z0
-9_$
]+)\s
*=\s
*function\
([a
-zA
-Z0
-9_$
]+\
)
3270 \s
*\
{(?
:(?
!};).)+?
return\s
*(?P
<q
>["'])[\w-]+_w8_(?P=q)\s*\+\s*[a-zA-Z0-9_$]+''',
3271 jscode, 'Initial JS player n function name', group='name')
3275 return json.loads(js_to_json(self._search_regex(
3276 rf'var {re.escape(funcname)}\s*=\s*(\[.+?\])\s*[,;]', jscode,
3277 f'Initial JS player n function list ({funcname}.{idx})')))[int(idx)]
3279 def _fixup_n_function_code(self, argnames, code):
3280 return argnames, re.sub(
3281 rf';\s*if\s*\(\s*typeof\s+[a-zA-Z0-9_$]+\s*===?\s*(["\'])undefined\
1\s
*\
)\s
*return\s
+{argnames
[0]};',
3284 def _extract_n_function_code(self, video_id, player_url):
3285 player_id = self._extract_player_info(player_url)
3286 func_code = self.cache.load('youtube
-nsig
', player_id, min_ver='2024.07.09')
3287 jscode = func_code or self._load_player(video_id, player_url)
3288 jsi = JSInterpreter(jscode)
3291 return jsi, player_id, func_code
3293 func_name = self._extract_n_function_name(jscode, player_url=player_url)
3295 # XXX: Workaround for the `typeof` gotcha
3296 func_code = self._fixup_n_function_code(*jsi.extract_function_code(func_name))
3298 self.cache.store('youtube
-nsig
', player_id, func_code)
3299 return jsi, player_id, func_code
3301 def _extract_n_function_from_code(self, jsi, func_code):
3302 func = jsi.extract_function_from_code(*func_code)
3304 def extract_nsig(s):
3307 except JSInterpreter.Exception:
3309 except Exception as e:
3310 raise JSInterpreter.Exception(traceback.format_exc(), cause=e)
3312 if ret.startswith('enhanced_except_
') or ret.endswith(s):
3313 raise JSInterpreter.Exception('Signature function returned an exception
')
3318 def _extract_signature_timestamp(self, video_id, player_url, ytcfg=None, fatal=False):
3320 Extract signatureTimestamp (sts)
3321 Required to tell API what sig/player version is in use.
3324 if isinstance(ytcfg, dict):
3325 sts = int_or_none(ytcfg.get('STS
'))
3328 # Attempt to extract from player
3329 if player_url is None:
3330 error_msg = 'Cannot extract signature timestamp without player_url
.'
3332 raise ExtractorError(error_msg)
3333 self.report_warning(error_msg)
3335 code = self._load_player(video_id, player_url, fatal=fatal)
3337 sts = int_or_none(self._search_regex(
3338 r'(?
:signatureTimestamp|sts
)\s
*:\s
*(?P
<sts
>[0-9]{5}
)', code,
3339 'JS player signature timestamp
', group='sts
', fatal=fatal))
3342 def _mark_watched(self, video_id, player_responses):
3343 for is_full, key in enumerate(('videostatsPlaybackUrl
', 'videostatsWatchtimeUrl
')):
3344 label = 'fully
' if is_full else ''
3345 url = get_first(player_responses, ('playbackTracking
', key, 'baseUrl
'),
3346 expected_type=url_or_none)
3348 self.report_warning(f'Unable to mark {label}watched
')
3350 parsed_url = urllib.parse.urlparse(url)
3351 qs = urllib.parse.parse_qs(parsed_url.query)
3353 # cpn generation algorithm is reverse engineered from base.js.
3354 # In fact it works even with dummy cpn.
3355 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
3356 cpn = ''.join(CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(16))
3358 # # more consistent results setting it to right before the end
3359 video_length = [str(float((qs.get('len') or ['1.5'])[0]) - 1)]
3364 'cmt
': video_length,
3365 'el
': 'detailpage
', # otherwise defaults to "shorts"
3369 # these seem to mark watchtime "history" in the real world
3370 # they're required
, so send
in a single value
3376 url
= urllib
.parse
.urlunparse(
3377 parsed_url
._replace
(query
=urllib
.parse
.urlencode(qs
, True)))
3379 self
._download
_webpage
(
3380 url
, video_id
, f
'Marking {label}watched',
3381 'Unable to mark watched', fatal
=False)
3384 def _extract_from_webpage(cls
, url
, webpage
):
3385 # Invidious Instances
3386 # https://github.com/yt-dlp/yt-dlp/issues/195
3387 # https://github.com/iv-org/invidious/pull/1730
3389 r
'<link rel="alternate" href="(?P<url>https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"',
3392 yield cls
.url_result(mobj
.group('url'), cls
)
3393 raise cls
.StopExtraction
3395 yield from super()._extract
_from
_webpage
(url
, webpage
)
3397 # lazyYT YouTube embed
3398 for id_
in re
.findall(r
'class="lazyYT" data-youtube-id="([^"]+)"', webpage
):
3399 yield cls
.url_result(unescapeHTML(id_
), cls
, id_
)
3401 # Wordpress "YouTube Video Importer" plugin
3402 for m
in re
.findall(r
'''(?x)<div[^>]+
3403 class=(?P<q1>[\'"])[^\'"]*\byvii
_single
_video
_player
\b[^
\'"]*(?P=q1)[^>]+
3404 data-video_id=(?P<q2>[\'"])([^
\'"]+)(?P=q2)''', webpage):
3405 yield cls.url_result(m[-1], cls, m[-1])
3408 def extract_id(cls, url):
3409 video_id = cls.get_temp_id(url)
3411 raise ExtractorError(f'Invalid URL: {url}')
3414 def _extract_chapters_from_json(self, data, duration):
3415 chapter_list = traverse_obj(
3417 'playerOverlays', 'playerOverlayRenderer', 'decoratedPlayerBarRenderer',
3418 'decoratedPlayerBarRenderer', 'playerBar', 'chapteredPlayerBarRenderer', 'chapters',
3419 ), expected_type=list)
3421 return self._extract_chapters_helper(
3423 start_function=lambda chapter: float_or_none(
3424 traverse_obj(chapter, ('chapterRenderer', 'timeRangeStartMillis')), scale=1000),
3425 title_function=lambda chapter: traverse_obj(
3426 chapter, ('chapterRenderer', 'title', 'simpleText'), expected_type=str),
3429 def _extract_chapters_from_engagement_panel(self, data, duration):
3430 content_list = traverse_obj(
3432 ('engagementPanels', ..., 'engagementPanelSectionListRenderer', 'content', 'macroMarkersListRenderer', 'contents'),
3434 chapter_time = lambda chapter: parse_duration(self._get_text(chapter, 'timeDescription'))
3435 chapter_title = lambda chapter: self._get_text(chapter, 'title')
3437 return next(filter(None, (
3438 self._extract_chapters_helper(traverse_obj(contents, (..., 'macroMarkersListItemRenderer')),
3439 chapter_time, chapter_title, duration)
3440 for contents in content_list)), [])
3442 def _extract_heatmap(self, data):
3443 return traverse_obj(data, (
3444 'frameworkUpdates', 'entityBatchUpdate', 'mutations',
3445 lambda _, v: v['payload']['macroMarkersListEntity']['markersList']['markerType'] == 'MARKER_TYPE_HEATMAP',
3446 'payload', 'macroMarkersListEntity', 'markersList', 'markers', ..., {
3447 'start_time': ('startMillis', {float_or_none(scale=1000)}),
3448 'end_time': {lambda x: (int(x['startMillis']) + int(x['durationMillis'])) / 1000},
3449 'value': ('intensityScoreNormalized', {float_or_none}),
3452 def _extract_comment(self, entities, parent=None):
3453 comment_entity_payload = get_first(entities, ('payload', 'commentEntityPayload', {dict}))
3454 if not (comment_id := traverse_obj(comment_entity_payload, ('properties', 'commentId', {str}))):
3457 toolbar_entity_payload = get_first(entities, ('payload', 'engagementToolbarStateEntityPayload', {dict}))
3458 time_text = traverse_obj(comment_entity_payload, ('properties', 'publishedTime', {str})) or ''
3462 'parent': parent or 'root',
3463 **traverse_obj(comment_entity_payload, {
3464 'text': ('properties', 'content', 'content', {str}),
3465 'like_count': ('toolbar', 'likeCountA11y', {parse_count}),
3466 'author_id': ('author', 'channelId', {self.ucid_or_none}),
3467 'author': ('author', 'displayName', {str}),
3468 'author_thumbnail': ('author', 'avatarThumbnailUrl', {url_or_none}),
3469 'author_is_uploader': ('author', 'isCreator', {bool}),
3470 'author_is_verified': ('author', 'isVerified', {bool}),
3471 'author_url': ('author', 'channelCommand', 'innertubeCommand', (
3472 ('browseEndpoint', 'canonicalBaseUrl'), ('commandMetadata', 'webCommandMetadata', 'url'),
3473 ), {urljoin('https://www.youtube.com')}),
3475 'is_favorited': (None if toolbar_entity_payload is None else
3476 toolbar_entity_payload.get('heartState') == 'TOOLBAR_HEART_STATE_HEARTED'),
3477 '_time_text': time_text, # FIXME: non-standard, but we need a way of showing that it is an estimate.
3478 'timestamp': self._parse_time_text(time_text),
3481 def _extract_comment_old(self, comment_renderer, parent=None):
3482 comment_id = comment_renderer.get('commentId')
3488 'text': self._get_text(comment_renderer, 'contentText'),
3489 'like_count': self._get_count(comment_renderer, 'voteCount'),
3490 'author_id': traverse_obj(comment_renderer, ('authorEndpoint', 'browseEndpoint', 'browseId', {self.ucid_or_none})),
3491 'author': self._get_text(comment_renderer, 'authorText'),
3492 'author_thumbnail': traverse_obj(comment_renderer, ('authorThumbnail', 'thumbnails', -1, 'url', {url_or_none})),
3493 'parent': parent or 'root',
3496 # Timestamp is an estimate calculated from the current time and time_text
3497 time_text = self._get_text(comment_renderer, 'publishedTimeText') or ''
3498 timestamp = self._parse_time_text(time_text)
3501 # FIXME: non-standard, but we need a way of showing that it is an estimate.
3502 '_time_text': time_text,
3503 'timestamp': timestamp,
3506 info['author_url'] = urljoin(
3507 'https://www.youtube.com', traverse_obj(comment_renderer, ('authorEndpoint', (
3508 ('browseEndpoint', 'canonicalBaseUrl'), ('commandMetadata', 'webCommandMetadata', 'url'))),
3509 expected_type=str, get_all=False))
3511 author_is_uploader = traverse_obj(comment_renderer, 'authorIsChannelOwner')
3512 if author_is_uploader is not None:
3513 info['author_is_uploader'] = author_is_uploader
3515 comment_abr = traverse_obj(
3516 comment_renderer, ('actionButtons', 'commentActionButtonsRenderer'), expected_type=dict)
3517 if comment_abr is not None:
3518 info['is_favorited'] = 'creatorHeart' in comment_abr
3520 badges = self._extract_badges([traverse_obj(comment_renderer, 'authorCommentBadge')])
3521 if self._has_badge(badges, BadgeType.VERIFIED):
3522 info['author_is_verified'] = True
3524 is_pinned = traverse_obj(comment_renderer, 'pinnedCommentBadge')
3526 info['is_pinned'] = True
3530 def _comment_entries(self, root_continuation_data, ytcfg, video_id, parent=None, tracker=None):
3532 get_single_config_arg = lambda c: self._configuration_arg(c, [''])[0]
3534 def extract_header(contents):
3535 _continuation = None
3536 for content in contents:
3537 comments_header_renderer = traverse_obj(content, 'commentsHeaderRenderer')
3538 expected_comment_count = self._get_count(
3539 comments_header_renderer, 'countText', 'commentsCount')
3541 if expected_comment_count is not None:
3542 tracker['est_total'] = expected_comment_count
3543 self.to_screen(f'Downloading ~{expected_comment_count} comments')
3544 comment_sort_index = int(get_single_config_arg('comment_sort') != 'top') # 1 = new, 0 = top
3546 sort_menu_item = try_get(
3547 comments_header_renderer,
3548 lambda x: x['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems'][comment_sort_index], dict) or {}
3549 sort_continuation_ep = sort_menu_item.get('serviceEndpoint') or {}
3551 _continuation = self._extract_continuation_ep_data(sort_continuation_ep) or self._extract_continuation(sort_menu_item)
3552 if not _continuation:
3555 sort_text = str_or_none(sort_menu_item.get('title'))
3557 sort_text = 'top comments' if comment_sort_index == 0 else 'newest first'
3558 self.to_screen(f'Sorting comments by {sort_text.lower()}')
3560 return _continuation
3562 def extract_thread(contents, entity_payloads):
3564 tracker['current_page_thread'] = 0
3565 for content in contents:
3566 if not parent and tracker['total_parent_comments'] >= max_parents:
3568 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
3570 # old comment format
3571 if not entity_payloads:
3572 comment_renderer = get_first(
3573 (comment_thread_renderer, content), [['commentRenderer', ('comment', 'commentRenderer')]],
3574 expected_type=dict, default={})
3576 comment = self._extract_comment_old(comment_renderer, parent)
3578 # new comment format
3581 traverse_obj(comment_thread_renderer, ('commentViewModel', 'commentViewModel', {dict}))
3582 or traverse_obj(content, ('commentViewModel', {dict})))
3583 comment_keys = traverse_obj(view_model, (('commentKey', 'toolbarStateKey'), {str}))
3584 if not comment_keys:
3586 entities = traverse_obj(entity_payloads, lambda _, v: v['entityKey'] in comment_keys)
3587 comment = self._extract_comment(entities, parent)
3589 comment['is_pinned'] = traverse_obj(view_model, ('pinnedText', {str})) is not None
3593 comment_id = comment['id']
3595 if comment.get('is_pinned'):
3596 tracker['pinned_comment_ids'].add(comment_id)
3597 # Sometimes YouTube may break and give us infinite looping comments.
3598 # See: https://github.com/yt-dlp/yt-dlp/issues/6290
3599 if comment_id in tracker['seen_comment_ids']:
3600 if comment_id in tracker['pinned_comment_ids'] and not comment.get('is_pinned'):
3601 # Pinned comments may appear a second time in newest first sort
3602 # See: https://github.com/yt-dlp/yt-dlp/issues/6712
3604 self.report_warning(
3605 'Detected YouTube comments looping. Stopping comment extraction '
3606 f'{"for this thread
" if parent else ""} as we probably cannot get any more.')
3609 tracker['seen_comment_ids'].add(comment['id'])
3611 tracker['running_total'] += 1
3612 tracker['total_reply_comments' if parent else 'total_parent_comments'] += 1
3615 # Attempt to get the replies
3616 comment_replies_renderer = try_get(
3617 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
3619 if comment_replies_renderer:
3620 tracker['current_page_thread'] += 1
3621 comment_entries_iter = self._comment_entries(
3622 comment_replies_renderer, ytcfg, video_id,
3623 parent=comment.get('id'), tracker=tracker)
3624 yield from itertools.islice(comment_entries_iter, min(
3625 max_replies_per_thread, max(0, max_replies - tracker['total_reply_comments'])))
3627 # Keeps track of counts across recursive calls
3632 'current_page_thread': 0,
3633 'total_parent_comments': 0,
3634 'total_reply_comments': 0,
3635 'seen_comment_ids': set(),
3636 'pinned_comment_ids': set(),
3640 # YouTube comments have a max depth of 2
3641 max_depth = int_or_none(get_single_config_arg('max_comment_depth'))
3643 self._downloader.deprecated_feature('[youtube] max_comment_depth extractor argument is deprecated. '
3644 'Set max replies in the max-comments extractor argument instead')
3645 if max_depth == 1 and parent:
3648 max_comments, max_parents, max_replies, max_replies_per_thread, *_ = (
3649 int_or_none(p, default=sys.maxsize) for p in self._configuration_arg('max_comments') + [''] * 4)
3651 continuation = self._extract_continuation(root_continuation_data)
3654 is_forced_continuation = False
3655 is_first_continuation = parent is None
3656 if is_first_continuation and not continuation:
3657 # Sometimes you can get comments by generating the continuation yourself,
3658 # even if YouTube initially reports them being disabled - e.g. stories comments.
3659 # Note: if the comment section is actually disabled, YouTube may return a response with
3660 # required check_get_keys missing. So we will disable that check initially in this case.
3661 continuation = self._build_api_continuation_query(self._generate_comment_continuation(video_id))
3662 is_forced_continuation = True
3664 continuation_items_path = (
3665 'onResponseReceivedEndpoints', ..., ('reloadContinuationItemsCommand', 'appendContinuationItemsAction'), 'continuationItems')
3666 for page_num in itertools.count(0):
3667 if not continuation:
3669 headers = self.generate_api_headers(ytcfg=ytcfg, visitor_data=self._extract_visitor_data(response))
3670 comment_prog_str = f"({tracker
['running_total']}/~
{tracker
['est_total']})"
3672 if is_first_continuation:
3673 note_prefix = 'Downloading comment section API JSON'
3675 note_prefix = ' Downloading comment API JSON reply thread %d %s' % (
3676 tracker['current_page_thread'], comment_prog_str)
3678 note_prefix = '{}Downloading comment{} API JSON page {} {}'.format(
3679 ' ' if parent else '', ' replies' if parent else '',
3680 page_num, comment_prog_str)
3682 # Do a deep check for incomplete data as sometimes YouTube may return no comments for a continuation
3683 # Ignore check if YouTube says the comment count is 0.
3684 check_get_keys = None
3685 if not is_forced_continuation and not (tracker['est_total'] == 0 and tracker['running_total'] == 0):
3686 check_get_keys = [[*continuation_items_path, ..., (
3687 'commentsHeaderRenderer' if is_first_continuation else ('commentThreadRenderer', 'commentViewModel', 'commentRenderer'))]]
3689 response = self._extract_response(
3690 item_id=None, query=continuation,
3691 ep='next', ytcfg=ytcfg, headers=headers, note=note_prefix,
3692 check_get_keys=check_get_keys)
3693 except ExtractorError as e:
3694 # Ignore incomplete data error for replies if retries didn't work.
3695 # This is to allow any other parent comments and comment threads to be downloaded.
3696 # See: https://github.com/yt-dlp/yt-dlp/issues/4669
3697 if 'incomplete data' in str(e).lower() and parent:
3698 if self.get_param('ignoreerrors') in (True, 'only_download'):
3699 self.report_warning(
3700 'Received incomplete data for a comment reply thread and retrying did not help. '
3701 'Ignoring to let other comments be downloaded. Pass --no-ignore-errors to not ignore.')
3704 raise ExtractorError(
3705 'Incomplete data received for comment reply thread. '
3706 'Pass --ignore-errors to ignore and allow rest of comments to download.',
3709 is_forced_continuation = False
3711 mutations = traverse_obj(response, ('frameworkUpdates', 'entityBatchUpdate', 'mutations', ..., {dict}))
3712 for continuation_items in traverse_obj(response, continuation_items_path, expected_type=list, default=[]):
3713 if is_first_continuation:
3714 continuation = extract_header(continuation_items)
3715 is_first_continuation = False
3720 for entry in extract_thread(continuation_items, mutations):
3724 continuation = self._extract_continuation({'contents': continuation_items})
3728 message = self._get_text(root_continuation_data, ('contents', ..., 'messageRenderer', 'text'), max_runs=1)
3729 if message and not parent and tracker['running_total'] == 0:
3730 self.report_warning(f'Youtube said: {message}', video_id=video_id, only_once=True)
3731 raise self.CommentsDisabled
3734 def _generate_comment_continuation(video_id):
3736 Generates initial comment section continuation token from given video id
3738 token = f'\x12\r\x12\x0b{video_id}\x18\x062\'"\x11"\x0b{video_id}0\x00x\x020\x00B\x10comments-section'
3739 return base64.b64encode(token.encode()).decode()
3741 def _get_comments(self, ytcfg, video_id, contents, webpage):
3742 """Entry for comment extraction"""
3743 def _real_comment_extract(contents):
3745 item for item in traverse_obj(contents, (..., 'itemSectionRenderer'), default={})
3746 if item.get('sectionIdentifier') == 'comment-item-section'), None)
3747 yield from self._comment_entries(renderer, ytcfg, video_id)
3749 max_comments = int_or_none(self._configuration_arg('max_comments', [''])[0])
3750 return itertools.islice(_real_comment_extract(contents), 0, max_comments)
3753 def _get_checkok_params():
3754 return {'contentCheckOk': True, 'racyCheckOk': True}
3757 def _generate_player_context(cls, sts=None):
3759 'html5Preference': 'HTML5_PREF_WANTS',
3762 context['signatureTimestamp'] = sts
3764 'playbackContext': {
3765 'contentPlaybackContext': context,
3767 **cls._get_checkok_params(),
3770 def _get_config_po_token(self, client):
3771 po_token_strs = self._configuration_arg('po_token', [], ie_key=YoutubeIE, casesense=True)
3772 for token_str in po_token_strs:
3773 po_token_client, sep, po_token = token_str.partition('+')
3775 self.report_warning(
3776 f'Invalid po_token configuration format. Expected "client
+po_token
", got "{token_str}
"', only_once=True)
3778 if po_token_client == client:
3781 def fetch_po_token(self, client='web', visitor_data=None, data_sync_id=None, player_url=None, **kwargs):
3782 # PO Token is bound to visitor_data / Visitor ID when logged out. Must have visitor_data for it to function.
3783 if not visitor_data and not self.is_authenticated and player_url:
3784 self.report_warning(
3785 f'Unable to fetch PO Token for {client} client: Missing required Visitor Data. '
3786 f'You may need to pass Visitor Data with --extractor-args "youtube
:visitor_data
=XXX
"')
3789 config_po_token = self._get_config_po_token(client)
3791 # PO token is bound to data_sync_id / account Session ID when logged in. However, for the config po_token,
3792 # if using first channel in an account then we don't need the data_sync_id anymore...
3793 if not data_sync_id and self.is_authenticated and player_url:
3794 self.report_warning(
3795 f'Got a PO Token for {client} client, but missing Data Sync ID for account. Formats may not work.'
3796 f'You may need to pass a Data Sync ID with --extractor-args "youtube
:data_sync_id
=XXX
"')
3798 return config_po_token
3800 # Require PO Token if logged in for external fetching
3801 if not data_sync_id and self.is_authenticated and player_url:
3802 self.report_warning(
3803 f'Unable to fetch PO Token for {client} client: Missing required Data Sync ID for account. '
3804 f'You may need to pass a Data Sync ID with --extractor-args "youtube
:data_sync_id
=XXX
"')
3807 return self._fetch_po_token(
3809 visitor_data=visitor_data,
3810 data_sync_id=data_sync_id,
3811 player_url=player_url,
3815 def _fetch_po_token(self, client, visitor_data=None, data_sync_id=None, player_url=None, **kwargs):
3816 """External PO Token fetch stub"""
3819 def _is_agegated(player_response):
3820 if traverse_obj(player_response, ('playabilityStatus', 'desktopLegacyAgeGateReason')):
3823 reasons = traverse_obj(player_response, ('playabilityStatus', ('status', 'reason')))
3824 AGE_GATE_REASONS = (
3825 'confirm your age', 'age-restricted', 'inappropriate', # reason
3826 'age_verification_required', 'age_check_required', # status
3828 return any(expected in reason for expected in AGE_GATE_REASONS for reason in reasons)
3831 def _is_unplayable(player_response):
3832 return traverse_obj(player_response, ('playabilityStatus', 'status')) == 'UNPLAYABLE'
3834 def _extract_player_response(self, client, video_id, master_ytcfg, player_ytcfg, player_url, initial_pr, visitor_data, data_sync_id, po_token):
3835 headers = self.generate_api_headers(
3837 default_client=client,
3838 visitor_data=visitor_data,
3839 session_index=self._extract_session_index(master_ytcfg, player_ytcfg),
3841 self._data_sync_id_to_delegated_session_id(data_sync_id)
3842 or self._extract_account_syncid(master_ytcfg, initial_pr, player_ytcfg)
3847 'videoId': video_id,
3850 default_pp = traverse_obj(
3851 INNERTUBE_CLIENTS, (_split_innertube_client(client)[0], 'PLAYER_PARAMS', {str}))
3852 if player_params := self._configuration_arg('player_params', [default_pp], casesense=True)[0]:
3853 yt_query['params'] = player_params
3856 yt_query['serviceIntegrityDimensions'] = {'poToken': po_token}
3858 sts = self._extract_signature_timestamp(video_id, player_url, master_ytcfg, fatal=False) if player_url else None
3859 yt_query.update(self._generate_player_context(sts))
3860 return self._extract_response(
3861 item_id=video_id, ep='player', query=yt_query,
3862 ytcfg=player_ytcfg, headers=headers, fatal=True,
3863 default_client=client,
3864 note='Downloading {} player API JSON'.format(client.replace('_', ' ').strip()),
3867 def _get_requested_clients(self, url, smuggled_data):
3868 requested_clients = []
3869 excluded_clients = []
3870 default_clients = self._DEFAULT_AUTHED_CLIENTS if self.is_authenticated else self._DEFAULT_CLIENTS
3871 allowed_clients = sorted(
3872 (client for client in INNERTUBE_CLIENTS if client[:1] != '_'),
3873 key=lambda client: INNERTUBE_CLIENTS[client]['priority'], reverse=True)
3874 for client in self._configuration_arg('player_client'):
3875 if client == 'default':
3876 requested_clients.extend(default_clients)
3877 elif client == 'all':
3878 requested_clients.extend(allowed_clients)
3879 elif client.startswith('-'):
3880 excluded_clients.append(client[1:])
3881 elif client not in allowed_clients:
3882 self.report_warning(f'Skipping unsupported client "{client}
"')
3884 requested_clients.append(client)
3885 if not requested_clients:
3886 requested_clients.extend(default_clients)
3887 for excluded_client in excluded_clients:
3888 if excluded_client in requested_clients:
3889 requested_clients.remove(excluded_client)
3890 if not requested_clients:
3891 raise ExtractorError('No player clients have been requested', expected=True)
3893 if smuggled_data.get('is_music_url') or self.is_music_url(url):
3894 for requested_client in requested_clients:
3895 _, base_client, variant = _split_innertube_client(requested_client)
3896 music_client = f'{base_client}_music' if base_client != 'mweb' else 'web_music'
3897 if variant != 'music' and music_client in INNERTUBE_CLIENTS:
3898 client_info = INNERTUBE_CLIENTS[music_client]
3899 if not client_info['REQUIRE_AUTH'] or (self.is_authenticated and client_info['SUPPORTS_COOKIES']):
3900 requested_clients.append(music_client)
3902 if self.is_authenticated:
3903 unsupported_clients = [
3904 client for client in requested_clients if not INNERTUBE_CLIENTS[client]['SUPPORTS_COOKIES']
3906 for client in unsupported_clients:
3907 self.report_warning(f'Skipping client "{client}
" since it does not support cookies', only_once=True)
3908 requested_clients.remove(client)
3910 return orderedSet(requested_clients)
3912 def _invalid_player_response(self, pr, video_id):
3913 # YouTube may return a different video player response than expected.
3914 # See: https://github.com/TeamNewPipe/NewPipe/issues/8713
3915 if (pr_id := traverse_obj(pr, ('videoDetails', 'videoId'))) != video_id:
3918 def _extract_player_responses(self, clients, video_id, webpage, master_ytcfg, smuggled_data):
3921 initial_pr = self._search_json(
3922 self._YT_INITIAL_PLAYER_RESPONSE_RE, webpage, 'initial player response', video_id, fatal=False)
3925 deprioritized_prs = []
3927 if initial_pr and not self._invalid_player_response(initial_pr, video_id):
3928 # Android player_response does not have microFormats which are needed for
3929 # extraction of some data. So we return the initial_pr with formats
3930 # stripped out even if not requested by the user
3931 # See: https://github.com/yt-dlp/yt-dlp/issues/501
3932 prs.append({**initial_pr, 'streamingData': None})
3934 all_clients = set(clients)
3935 clients = clients[::-1]
3937 def append_client(*client_names):
3938 """ Append the first client name that exists but not already used """
3939 for client_name in client_names:
3940 actual_client = _split_innertube_client(client_name)[0]
3941 if actual_client in INNERTUBE_CLIENTS:
3942 if actual_client not in all_clients:
3943 clients.append(client_name)
3944 all_clients.add(actual_client)
3947 tried_iframe_fallback = False
3948 player_url = visitor_data = data_sync_id = None
3949 skipped_clients = {}
3951 deprioritize_pr = False
3952 client, base_client, variant = _split_innertube_client(clients.pop())
3953 player_ytcfg = master_ytcfg if client == 'web' else {}
3954 if 'configs' not in self._configuration_arg('player_skip') and client != 'web':
3955 player_ytcfg = self._download_ytcfg(client, video_id) or player_ytcfg
3957 player_url = player_url or self._extract_player_url(master_ytcfg, player_ytcfg, webpage=webpage)
3958 require_js_player = self._get_default_ytcfg(client).get('REQUIRE_JS_PLAYER')
3959 if 'js' in self._configuration_arg('player_skip'):
3960 require_js_player = False
3963 if not player_url and not tried_iframe_fallback and require_js_player:
3964 player_url = self._download_player_url(video_id)
3965 tried_iframe_fallback = True
3967 visitor_data = visitor_data or self._extract_visitor_data(master_ytcfg, initial_pr, player_ytcfg)
3968 data_sync_id = data_sync_id or self._extract_data_sync_id(master_ytcfg, initial_pr, player_ytcfg)
3969 po_token = self.fetch_po_token(
3970 client=client, visitor_data=visitor_data,
3971 data_sync_id=data_sync_id if self.is_authenticated else None,
3972 player_url=player_url if require_js_player else None,
3975 require_po_token = self._get_default_ytcfg(client).get('REQUIRE_PO_TOKEN')
3976 if not po_token and require_po_token:
3977 self.report_warning(
3978 f'No PO Token provided for {client} client, '
3979 f'which is required for working {client} formats. '
3980 f'You can manually pass a PO Token for this client with '
3981 f'--extractor-args "youtube
:po_token
={client}
+XXX
"',
3983 deprioritize_pr = True
3985 pr = initial_pr if client == 'web' else None
3987 pr = pr or self._extract_player_response(
3989 master_ytcfg=player_ytcfg or master_ytcfg,
3990 player_ytcfg=player_ytcfg,
3991 player_url=player_url,
3992 initial_pr=initial_pr,
3993 visitor_data=visitor_data,
3994 data_sync_id=data_sync_id,
3996 except ExtractorError as e:
3997 self.report_warning(e)
4000 if pr_id := self._invalid_player_response(pr, video_id):
4001 skipped_clients[client] = pr_id
4003 # Save client name for introspection later
4004 sd = traverse_obj(pr, ('streamingData', {dict})) or {}
4005 sd[STREAMING_DATA_CLIENT_NAME] = client
4006 sd[STREAMING_DATA_PO_TOKEN] = po_token
4007 for f in traverse_obj(sd, (('formats', 'adaptiveFormats'), ..., {dict})):
4008 f[STREAMING_DATA_CLIENT_NAME] = client
4009 f[STREAMING_DATA_PO_TOKEN] = po_token
4011 deprioritized_prs.append(pr)
4015 # web_embedded can work around age-gate and age-verification for some embeddable videos
4016 if self._is_agegated(pr) and variant != 'web_embedded':
4017 append_client(f'web_embedded.{base_client}')
4018 # Unauthenticated users will only get web_embedded client formats if age-gated
4019 if self._is_agegated(pr) and not self.is_authenticated:
4021 f'{video_id}: This video is age-restricted; some formats may be missing '
4022 f'without authentication. {self._login_hint()}', only_once=True)
4024 ''' This code is pointless while web_creator is in _DEFAULT_AUTHED_CLIENTS
4025 # EU countries require age-verification for accounts to access age-restricted videos
4026 # If account is not age-verified, _is_agegated() will be truthy for non-embedded clients
4027 embedding_is_disabled = variant == 'web_embedded' and self._is_unplayable(pr)
4028 if self.is_authenticated and (self._is_agegated(pr) or embedding_is_disabled):
4030 f'{video_id}: This video is age-restricted and YouTube is requiring '
4031 'account age-verification; some formats may be missing', only_once=True)
4032 # web_creator can work around the age-verification requirement
4033 # android_vr may also be able to work around age-verification
4034 # tv_embedded may(?) still work around age-verification if the video is embeddable
4035 append_client('web_creator')
4038 prs.extend(deprioritized_prs)
4041 self.report_warning(
4042 f'Skipping player responses from {"/".join(skipped_clients)} clients '
4043 f'(got player responses for video "{"/".join(set(skipped_clients
.values()))}" instead of "{video_id}
")')
4045 raise ExtractorError(
4046 'All player responses are invalid. Your IP is likely being blocked by Youtube', expected=True)
4048 raise ExtractorError('Failed to extract any player response')
4049 return prs, player_url
4051 def _needs_live_processing(self, live_status, duration):
4052 if ((live_status == 'is_live' and self.get_param('live_from_start'))
4053 or (live_status == 'post_live' and (duration or 0) > 2 * 3600)):
4056 def _extract_formats_and_subtitles(self, streaming_data, video_id, player_url, live_status, duration):
4057 CHUNK_SIZE = 10 << 20
4058 PREFERRED_LANG_VALUE = 10
4059 original_language = None
4060 itags, stream_ids = collections.defaultdict(set), []
4061 itag_qualities, res_qualities = {}, {0: None}
4063 # Normally tiny is the smallest video-only formats. But
4064 # audio-only formats with unknown quality may get tagged as tiny
4066 'audio_quality_ultralow', 'audio_quality_low', 'audio_quality_medium', 'audio_quality_high', # Audio only formats
4067 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres',
4069 streaming_formats = traverse_obj(streaming_data, (..., ('formats', 'adaptiveFormats'), ...))
4070 format_types = self._configuration_arg('formats')
4071 all_formats = 'duplicate' in format_types
4072 if self._configuration_arg('include_duplicate_formats'):
4074 self._downloader.deprecated_feature('[youtube] include_duplicate_formats extractor argument is deprecated. '
4075 'Use formats=duplicate extractor argument instead')
4077 def build_fragments(f):
4079 'url': update_url_query(f['url'], {
4080 'range': f'{range_start}-{min(range_start + CHUNK_SIZE - 1, f["filesize
"])}',
4082 } for range_start in range(0, f['filesize'], CHUNK_SIZE))
4084 for fmt in streaming_formats:
4085 if fmt.get('targetDurationSec'):
4088 itag = str_or_none(fmt.get('itag'))
4089 audio_track = fmt.get('audioTrack') or {}
4090 stream_id = (itag, audio_track.get('id'), fmt.get('isDrc'))
4092 if stream_id in stream_ids:
4095 quality = fmt.get('quality')
4096 height = int_or_none(fmt.get('height'))
4097 if quality == 'tiny' or not quality:
4098 quality = fmt.get('audioQuality', '').lower() or quality
4099 # The 3gp format (17) in android client has a quality of "small
",
4100 # but is actually worse than other formats
4105 itag_qualities[itag] = quality
4107 res_qualities[height] = quality
4109 display_name = audio_track.get('displayName') or ''
4110 is_original = 'original' in display_name.lower()
4111 is_descriptive = 'descriptive' in display_name.lower()
4112 is_default = audio_track.get('audioIsDefault')
4113 language_code = audio_track.get('id', '').split('.')[0]
4114 if language_code and (is_original or (is_default and not original_language)):
4115 original_language = language_code
4117 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
4118 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
4119 # number of fragment that would subsequently requested with (`&sq=N`)
4120 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
4123 fmt_url = fmt.get('url')
4125 sc = urllib.parse.parse_qs(fmt.get('signatureCipher'))
4126 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
4127 encrypted_sig = try_get(sc, lambda x: x['s'][0])
4128 if not all((sc, fmt_url, player_url, encrypted_sig)):
4131 fmt_url += '&{}={}'.format(
4132 traverse_obj(sc, ('sp', -1)) or 'signature',
4133 self._decrypt_signature(encrypted_sig, video_id, player_url),
4135 except ExtractorError as e:
4136 self.report_warning('Signature extraction failed: Some formats may be missing',
4137 video_id=video_id, only_once=True)
4138 self.write_debug(e, only_once=True)
4141 query = parse_qs(fmt_url)
4144 decrypt_nsig = self._cached(self._decrypt_nsig, 'nsig', query['n'][0])
4145 fmt_url = update_url_query(fmt_url, {
4146 'n': decrypt_nsig(query['n'][0], video_id, player_url),
4148 except ExtractorError as e:
4150 if isinstance(e, JSInterpreter.Exception):
4151 phantomjs_hint = (f' Install {self._downloader._format_err("PhantomJS
", self._downloader.Styles.EMPHASIS)} '
4152 f'to workaround the issue. {PhantomJSwrapper.INSTALL_HINT}\n')
4154 self.report_warning(
4155 f'nsig extraction failed: Some formats may be missing\n{phantomjs_hint}'
4156 f' n = {query["n
"][0]} ; player = {player_url}', video_id=video_id, only_once=True)
4157 self.write_debug(e, only_once=True)
4159 self.report_warning(
4160 'Cannot decrypt nsig without player_url: Some formats may be missing',
4161 video_id=video_id, only_once=True)
4164 tbr = float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
4165 format_duration = traverse_obj(fmt, ('approxDurationMs', {float_or_none(scale=1000)}))
4166 # Some formats may have much smaller duration than others (possibly damaged during encoding)
4167 # E.g. 2-nOtRESiUc Ref: https://github.com/yt-dlp/yt-dlp/issues/2823
4168 # Make sure to avoid false positives with small duration differences.
4169 # E.g. __2ABJjxzNo, ySuUZEjARPY
4170 is_damaged = try_call(lambda: format_duration < duration // 2)
4172 self.report_warning(
4173 f'{video_id}: Some formats are possibly damaged. They will be deprioritized', only_once=True)
4175 client_name = fmt[STREAMING_DATA_CLIENT_NAME]
4176 po_token = fmt.get(STREAMING_DATA_PO_TOKEN)
4179 fmt_url = update_url_query(fmt_url, {'pot': po_token})
4181 # Clients that require PO Token return videoplayback URLs that may return 403
4182 is_broken = (not po_token and self._get_default_ytcfg(client_name).get('REQUIRE_PO_TOKEN'))
4184 self.report_warning(
4185 f'{video_id}: {client_name} client formats require a PO Token which was not provided. '
4186 'They will be deprioritized as they may yield HTTP Error 403', only_once=True)
4188 name = fmt.get('qualityLabel') or quality.replace('audio_quality_', '') or ''
4189 fps = int_or_none(fmt.get('fps')) or 0
4191 'asr': int_or_none(fmt.get('audioSampleRate')),
4192 'filesize': int_or_none(fmt.get('contentLength')),
4193 'format_id': f'{itag}{"-drc
" if fmt.get("isDrc
") else ""}',
4194 'format_note': join_nonempty(
4195 join_nonempty(display_name, is_default and ' (default)', delim=''),
4196 name, fmt.get('isDrc') and 'DRC',
4197 try_get(fmt, lambda x: x['projectionType'].replace('RECTANGULAR', '').lower()),
4198 try_get(fmt, lambda x: x['spatialAudioType'].replace('SPATIAL_AUDIO_TYPE_', '').lower()),
4199 is_damaged and 'DAMAGED', is_broken and 'BROKEN',
4200 (self.get_param('verbose') or all_formats) and short_client_name(client_name),
4202 # Format 22 is likely to be damaged. See https://github.com/yt-dlp/yt-dlp/issues/3372
4203 'source_preference': (-5 if itag == '22' else -1) + (100 if 'Premium' in name else 0),
4204 'fps': fps if fps > 1 else None, # For some formats, fps is wrongly returned as 1
4205 'audio_channels': fmt.get('audioChannels'),
4207 'quality': q(quality) - bool(fmt.get('isDrc')) / 2,
4208 'has_drm': bool(fmt.get('drmFamilies')),
4210 'filesize_approx': filesize_from_tbr(tbr, format_duration),
4212 'width': int_or_none(fmt.get('width')),
4213 'language': join_nonempty(language_code, 'desc' if is_descriptive else '') or None,
4214 'language_preference': PREFERRED_LANG_VALUE if is_original else 5 if is_default else -10 if is_descriptive else -1,
4215 # Strictly de-prioritize broken, damaged and 3gp formats
4216 'preference': -20 if is_broken else -10 if is_damaged else -2 if itag == '17' else None,
4218 mime_mobj = re.match(
4219 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^
"]+)")?
', fmt.get('mimeType
') or '')
4221 dct['ext
'] = mimetype2ext(mime_mobj.group(1))
4222 dct.update(parse_codecs(mime_mobj.group(2)))
4224 itags[itag].add(('https
', dct.get('language
')))
4225 stream_ids.append(stream_id)
4226 single_stream = 'none
' in (dct.get('acodec
'), dct.get('vcodec
'))
4227 if single_stream and dct.get('ext
'):
4228 dct['container
'] = dct['ext
'] + '_dash
'
4230 if (all_formats or 'dashy
' in format_types) and dct['filesize
']:
4233 'format_id
': f'{dct
["format_id"]}-dashy
' if all_formats else dct['format_id
'],
4234 'protocol
': 'http_dash_segments
',
4235 'fragments
': build_fragments(dct),
4237 if all_formats or 'dashy
' not in format_types:
4238 dct['downloader_options
'] = {'http_chunk_size
': CHUNK_SIZE}
4241 needs_live_processing = self._needs_live_processing(live_status, duration)
4242 skip_bad_formats = 'incomplete
' not in format_types
4243 if self._configuration_arg('include_incomplete_formats
'):
4244 skip_bad_formats = False
4245 self._downloader.deprecated_feature('[youtube
] include_incomplete_formats extractor argument
is deprecated
. '
4246 'Use formats
=incomplete extractor argument instead
')
4248 skip_manifests = set(self._configuration_arg('skip
'))
4249 if (not self.get_param('youtube_include_hls_manifest
', True)
4250 or needs_live_processing == 'is_live
' # These will be filtered out by YoutubeDL anyway
4251 or (needs_live_processing and skip_bad_formats)):
4252 skip_manifests.add('hls
')
4254 if not self.get_param('youtube_include_dash_manifest
', True):
4255 skip_manifests.add('dash
')
4256 if self._configuration_arg('include_live_dash
'):
4257 self._downloader.deprecated_feature('[youtube
] include_live_dash extractor argument
is deprecated
. '
4258 'Use formats
=incomplete extractor argument instead
')
4259 elif skip_bad_formats and live_status == 'is_live
' and needs_live_processing != 'is_live
':
4260 skip_manifests.add('dash
')
4262 def process_manifest_format(f, proto, client_name, itag, po_token):
4263 key = (proto, f.get('language
'))
4264 if not all_formats and key in itags[itag]:
4266 itags[itag].add(key)
4268 if f.get('source_preference
') is None:
4269 f['source_preference
'] = -1
4271 # Clients that require PO Token return videoplayback URLs that may return 403
4272 # hls does not currently require PO Token
4273 if (not po_token and self._get_default_ytcfg(client_name).get('REQUIRE_PO_TOKEN
')) and proto != 'hls
':
4274 self.report_warning(
4275 f'{video_id}
: {client_name} client {proto} formats require a PO Token which was
not provided
. '
4276 'They will be deprioritized
as they may
yield HTTP Error
403', only_once=True)
4277 f['format_note
'] = join_nonempty(f.get('format_note
'), 'BROKEN
', delim=' ')
4278 f['source_preference
'] -= 20
4280 if itag and all_formats:
4281 f['format_id
'] = f'{itag}
-{proto}
'
4282 elif any(p != proto for p, _ in itags[itag]):
4283 f['format_id
'] = f'{itag}
-{proto}
'
4285 f['format_id
'] = itag
4287 if original_language and f.get('language
') == original_language:
4288 f['format_note
'] = join_nonempty(f.get('format_note
'), '(default
)', delim=' ')
4289 f['language_preference
'] = PREFERRED_LANG_VALUE
4291 if itag in ('616', '235'):
4292 f['format_note
'] = join_nonempty(f.get('format_note
'), 'Premium
', delim=' ')
4293 f['source_preference
'] += 100
4295 f['quality
'] = q(itag_qualities.get(try_get(f, lambda f: f['format_id
'].split('-')[0]), -1))
4296 if f['quality
'] == -1 and f.get('height
'):
4297 f['quality
'] = q(res_qualities[min(res_qualities, key=lambda x: abs(x - f['height
']))])
4298 if self.get_param('verbose
') or all_formats:
4299 f['format_note
'] = join_nonempty(
4300 f.get('format_note
'), short_client_name(client_name), delim=', ')
4301 if f.get('fps
') and f['fps
'] <= 1:
4304 if proto == 'hls
' and f.get('has_drm
'):
4305 f['has_drm
'] = 'maybe
'
4306 f['source_preference
'] -= 5
4310 for sd in streaming_data:
4311 client_name = sd[STREAMING_DATA_CLIENT_NAME]
4312 po_token = sd.get(STREAMING_DATA_PO_TOKEN)
4313 hls_manifest_url = 'hls
' not in skip_manifests and sd.get('hlsManifestUrl
')
4314 if hls_manifest_url:
4316 hls_manifest_url = hls_manifest_url.rstrip('/') + f'/pot
/{po_token}
'
4317 fmts, subs = self._extract_m3u8_formats_and_subtitles(
4318 hls_manifest_url, video_id, 'mp4
', fatal=False, live=live_status == 'is_live
')
4319 subtitles = self._merge_subtitles(subs, subtitles)
4321 if process_manifest_format(f, 'hls
', client_name, self._search_regex(
4322 r'/itag
/(\d
+)', f['url
'], 'itag
', default=None), po_token):
4325 dash_manifest_url = 'dash
' not in skip_manifests and sd.get('dashManifestUrl
')
4326 if dash_manifest_url:
4328 dash_manifest_url = dash_manifest_url.rstrip('/') + f'/pot
/{po_token}
'
4329 formats, subs = self._extract_mpd_formats_and_subtitles(dash_manifest_url, video_id, fatal=False)
4330 subtitles = self._merge_subtitles(subs, subtitles) # Prioritize HLS subs over DASH
4332 if process_manifest_format(f, 'dash
', client_name, f['format_id
'], po_token):
4333 f['filesize
'] = int_or_none(self._search_regex(
4334 r'/clen
/(\d
+)', f.get('fragment_base_url
') or f['url
'], 'file size
', default=None))
4335 if needs_live_processing:
4336 f['is_from_start
'] = True
4341 def _extract_storyboard(self, player_responses, duration):
4343 player_responses, ('storyboards
', 'playerStoryboardSpecRenderer
', 'spec
'), default='').split('|
')[::-1]
4344 base_url = url_or_none(urljoin('https
://i
.ytimg
.com
/', spec.pop() or None))
4348 for i, args in enumerate(spec):
4349 args = args.split('#')
4350 counts
= list(map(int_or_none
, args
[:5]))
4351 if len(args
) != 8 or not all(counts
):
4352 self
.report_warning(f
'Malformed storyboard {i}: {"#".join(args)}{bug_reports_message()}')
4354 width
, height
, frame_count
, cols
, rows
= counts
4357 url
= base_url
.replace('$L', str(L
- i
)).replace('$N', N
) + f
'&sigh={sigh}'
4358 fragment_count
= frame_count
/ (cols
* rows
)
4359 fragment_duration
= duration
/ fragment_count
4361 'format_id': f
'sb{i}',
4362 'format_note': 'storyboard',
4364 'protocol': 'mhtml',
4370 'fps': frame_count
/ duration
,
4374 'url': url
.replace('$M', str(j
)),
4375 'duration': min(fragment_duration
, duration
- (j
* fragment_duration
)),
4376 } for j
in range(math
.ceil(fragment_count
))],
4379 def _download_player_responses(self
, url
, smuggled_data
, video_id
, webpage_url
):
4381 if 'webpage' not in self
._configuration
_arg
('player_skip'):
4382 query
= {'bpctr': '9999999999', 'has_verified': '1'}
4383 pp
= self
._configuration
_arg
('player_params', [None], casesense
=True)[0]
4386 webpage
= self
._download
_webpage
(
4387 webpage_url
, video_id
, fatal
=False, query
=query
)
4389 master_ytcfg
= self
.extract_ytcfg(video_id
, webpage
) or self
._get
_default
_ytcfg
()
4391 player_responses
, player_url
= self
._extract
_player
_responses
(
4392 self
._get
_requested
_clients
(url
, smuggled_data
),
4393 video_id
, webpage
, master_ytcfg
, smuggled_data
)
4395 return webpage
, master_ytcfg
, player_responses
, player_url
4397 def _list_formats(self
, video_id
, microformats
, video_details
, player_responses
, player_url
, duration
=None):
4398 live_broadcast_details
= traverse_obj(microformats
, (..., 'liveBroadcastDetails'))
4399 is_live
= get_first(video_details
, 'isLive')
4401 is_live
= get_first(live_broadcast_details
, 'isLiveNow')
4402 live_content
= get_first(video_details
, 'isLiveContent')
4403 is_upcoming
= get_first(video_details
, 'isUpcoming')
4404 post_live
= get_first(video_details
, 'isPostLiveDvr')
4405 live_status
= ('post_live' if post_live
4406 else 'is_live' if is_live
4407 else 'is_upcoming' if is_upcoming
4408 else 'was_live' if live_content
4409 else 'not_live' if False in (is_live
, live_content
)
4411 streaming_data
= traverse_obj(player_responses
, (..., 'streamingData'))
4412 *formats
, subtitles
= self
._extract
_formats
_and
_subtitles
(streaming_data
, video_id
, player_url
, live_status
, duration
)
4413 if all(f
.get('has_drm') for f
in formats
):
4414 # If there are no formats that definitely don't have DRM, all have DRM
4418 return live_broadcast_details
, live_status
, streaming_data
, formats
, subtitles
4420 def _real_extract(self
, url
):
4421 url
, smuggled_data
= unsmuggle_url(url
, {})
4422 video_id
= self
._match
_id
(url
)
4424 base_url
= self
.http_scheme() + '//www.youtube.com/'
4425 webpage_url
= base_url
+ 'watch?v=' + video_id
4427 webpage
, master_ytcfg
, player_responses
, player_url
= self
._download
_player
_responses
(url
, smuggled_data
, video_id
, webpage_url
)
4429 playability_statuses
= traverse_obj(
4430 player_responses
, (..., 'playabilityStatus'), expected_type
=dict)
4432 trailer_video_id
= get_first(
4433 playability_statuses
,
4434 ('errorScreen', 'playerLegacyDesktopYpcTrailerRenderer', 'trailerVideoId'),
4436 if trailer_video_id
:
4437 return self
.url_result(
4438 trailer_video_id
, self
.ie_key(), trailer_video_id
)
4440 search_meta
= ((lambda x
: self
._html
_search
_meta
(x
, webpage
, default
=None))
4441 if webpage
else (lambda x
: None))
4443 video_details
= traverse_obj(player_responses
, (..., 'videoDetails'), expected_type
=dict)
4444 microformats
= traverse_obj(
4445 player_responses
, (..., 'microformat', 'playerMicroformatRenderer'),
4448 translated_title
= self
._get
_text
(microformats
, (..., 'title'))
4449 video_title
= ((self
._preferred
_lang
and translated_title
)
4450 or get_first(video_details
, 'title') # primary
4452 or search_meta(['og:title', 'twitter:title', 'title']))
4453 translated_description
= self
._get
_text
(microformats
, (..., 'description'))
4454 original_description
= get_first(video_details
, 'shortDescription')
4455 video_description
= (
4456 (self
._preferred
_lang
and translated_description
)
4457 # If original description is blank, it will be an empty string.
4458 # Do not prefer translated description in this case.
4459 or original_description
if original_description
is not None else translated_description
)
4461 multifeed_metadata_list
= get_first(
4463 ('multicamera', 'playerLegacyMulticameraRenderer', 'metadataList'),
4465 if multifeed_metadata_list
and not smuggled_data
.get('force_singlefeed'):
4466 if self
.get_param('noplaylist'):
4467 self
.to_screen(f
'Downloading just video {video_id} because of --no-playlist')
4471 for feed
in multifeed_metadata_list
.split(','):
4472 # Unquote should take place before split on comma (,) since textual
4473 # fields may contain comma as well (see
4474 # https://github.com/ytdl-org/youtube-dl/issues/8536)
4475 feed_data
= urllib
.parse
.parse_qs(
4476 urllib
.parse
.unquote_plus(feed
))
4478 def feed_entry(name
):
4480 feed_data
, lambda x
: x
[name
][0], str)
4482 feed_id
= feed_entry('id')
4485 feed_title
= feed_entry('title')
4488 title
+= f
' ({feed_title})'
4490 '_type': 'url_transparent',
4491 'ie_key': 'Youtube',
4493 '{}watch?v={}'.format(base_url
, feed_data
['id'][0]),
4494 {'force_singlefeed': True}),
4497 feed_ids
.append(feed_id
)
4499 'Downloading multifeed video ({}) - add --no-playlist to just download video {}'.format(
4500 ', '.join(feed_ids
), video_id
))
4501 return self
.playlist_result(
4502 entries
, video_id
, video_title
, video_description
)
4504 duration
= (int_or_none(get_first(video_details
, 'lengthSeconds'))
4505 or int_or_none(get_first(microformats
, 'lengthSeconds'))
4506 or parse_duration(search_meta('duration')) or None)
4508 live_broadcast_details
, live_status
, streaming_data
, formats
, automatic_captions
= \
4509 self
._list
_formats
(video_id
, microformats
, video_details
, player_responses
, player_url
, duration
)
4510 if live_status
== 'post_live':
4511 self
.write_debug(f
'{video_id}: Video is in Post-Live Manifestless mode')
4514 if not self
.get_param('allow_unplayable_formats') and traverse_obj(streaming_data
, (..., 'licenseInfos')):
4515 self
.report_drm(video_id
)
4517 playability_statuses
,
4518 ('errorScreen', 'playerErrorMessageRenderer'), expected_type
=dict) or {}
4519 reason
= self
._get
_text
(pemr
, 'reason') or get_first(playability_statuses
, 'reason')
4520 subreason
= clean_html(self
._get
_text
(pemr
, 'subreason') or '')
4522 if subreason
== 'The uploader has not made this video available in your country.':
4523 countries
= get_first(microformats
, 'availableCountries')
4525 regions_allowed
= search_meta('regionsAllowed')
4526 countries
= regions_allowed
.split(',') if regions_allowed
else None
4527 self
.raise_geo_restricted(subreason
, countries
, metadata_available
=True)
4528 reason
+= f
'. {subreason}'
4530 if 'sign in' in reason
.lower():
4531 reason
= remove_end(reason
, 'This helps protect our community. Learn more')
4532 reason
= f
'{remove_end(reason.strip(), ".")}. {self._youtube_login_hint}'
4533 self
.raise_no_formats(reason
, expected
=True)
4535 keywords
= get_first(video_details
, 'keywords', expected_type
=list) or []
4536 if not keywords
and webpage
:
4538 unescapeHTML(m
.group('content'))
4539 for m
in re
.finditer(self
._meta
_regex
('og:video:tag'), webpage
)]
4540 for keyword
in keywords
:
4541 if keyword
.startswith('yt:stretch='):
4542 mobj
= re
.search(r
'(\d+)\s*:\s*(\d+)', keyword
)
4544 # NB: float is intentional for forcing float division
4545 w
, h
= (float(v
) for v
in mobj
.groups())
4549 if f
.get('vcodec') != 'none':
4550 f
['stretched_ratio'] = ratio
4552 thumbnails
= self
._extract
_thumbnails
((video_details
, microformats
), (..., ..., 'thumbnail'))
4553 thumbnail_url
= search_meta(['og:image', 'twitter:image'])
4556 'url': thumbnail_url
,
4558 original_thumbnails
= thumbnails
.copy()
4560 # The best resolution thumbnails sometimes does not appear in the webpage
4561 # See: https://github.com/yt-dlp/yt-dlp/issues/340
4562 # List of possible thumbnails - Ref: <https://stackoverflow.com/a/20542029>
4564 # While the *1,*2,*3 thumbnails are just below their corresponding "*default" variants
4565 # in resolution, these are not the custom thumbnail. So de-prioritize them
4566 'maxresdefault', 'hq720', 'sddefault', 'hqdefault', '0', 'mqdefault', 'default',
4567 'sd1', 'sd2', 'sd3', 'hq1', 'hq2', 'hq3', 'mq1', 'mq2', 'mq3', '1', '2', '3',
4569 n_thumbnail_names
= len(thumbnail_names
)
4571 'url': 'https://i.ytimg.com/vi{webp}/{video_id}/{name}{live}.{ext}'.format(
4572 video_id
=video_id
, name
=name
, ext
=ext
,
4573 webp
='_webp' if ext
== 'webp' else '', live
='_live' if live_status
== 'is_live' else ''),
4574 } for name
in thumbnail_names
for ext
in ('webp', 'jpg'))
4575 for thumb
in thumbnails
:
4576 i
= next((i
for i
, t
in enumerate(thumbnail_names
) if f
'/{video_id}/{t}' in thumb
['url']), n_thumbnail_names
)
4577 thumb
['preference'] = (0 if '.webp' in thumb
['url'] else -1) - (2 * i
)
4578 self
._remove
_duplicate
_formats
(thumbnails
)
4579 self
._downloader
._sort
_thumbnails
(original_thumbnails
)
4581 category
= get_first(microformats
, 'category') or search_meta('genre')
4582 channel_id
= self
.ucid_or_none(str_or_none(
4583 get_first(video_details
, 'channelId')
4584 or get_first(microformats
, 'externalChannelId')
4585 or search_meta('channelId')))
4586 owner_profile_url
= get_first(microformats
, 'ownerProfileUrl')
4588 live_start_time
= parse_iso8601(get_first(live_broadcast_details
, 'startTimestamp'))
4589 live_end_time
= parse_iso8601(get_first(live_broadcast_details
, 'endTimestamp'))
4590 if not duration
and live_end_time
and live_start_time
:
4591 duration
= live_end_time
- live_start_time
4593 needs_live_processing
= self
._needs
_live
_processing
(live_status
, duration
)
4595 def is_bad_format(fmt
):
4596 if needs_live_processing
and not fmt
.get('is_from_start'):
4598 elif (live_status
== 'is_live' and needs_live_processing
!= 'is_live'
4599 and fmt
.get('protocol') == 'http_dash_segments'):
4602 for fmt
in filter(is_bad_format
, formats
):
4603 fmt
['preference'] = (fmt
.get('preference') or -1) - 10
4604 fmt
['format_note'] = join_nonempty(fmt
.get('format_note'), '(Last 2 hours)', delim
=' ')
4606 if needs_live_processing
:
4607 self
._prepare
_live
_from
_start
_formats
(
4608 formats
, video_id
, live_start_time
, url
, webpage_url
, smuggled_data
, live_status
== 'is_live')
4610 formats
.extend(self
._extract
_storyboard
(player_responses
, duration
))
4612 channel_handle
= self
.handle_from_url(owner_profile_url
)
4616 'title': video_title
,
4618 'thumbnails': thumbnails
,
4619 # The best thumbnail that we are sure exists. Prevents unnecessary
4620 # URL checking if user don't care about getting the best possible thumbnail
4621 'thumbnail': traverse_obj(original_thumbnails
, (-1, 'url')),
4622 'description': video_description
,
4623 'channel_id': channel_id
,
4624 'channel_url': format_field(channel_id
, None, 'https://www.youtube.com/channel/%s', default
=None),
4625 'duration': duration
,
4626 'view_count': int_or_none(
4627 get_first((video_details
, microformats
), (..., 'viewCount'))
4628 or search_meta('interactionCount')),
4629 'average_rating': float_or_none(get_first(video_details
, 'averageRating')),
4630 'age_limit': 18 if (
4631 get_first(microformats
, 'isFamilySafe') is False
4632 or search_meta('isFamilyFriendly') == 'false'
4633 or search_meta('og:restrictions:age') == '18+') else 0,
4634 'webpage_url': webpage_url
,
4635 'categories': [category
] if category
else None,
4637 'playable_in_embed': get_first(playability_statuses
, 'playableInEmbed'),
4638 'live_status': live_status
,
4639 'release_timestamp': live_start_time
,
4640 '_format_sort_fields': ( # source_preference is lower for potentially damaged formats
4641 'quality', 'res', 'fps', 'hdr:12', 'source', 'vcodec', 'channels', 'acodec', 'lang', 'proto'),
4645 pctr
= traverse_obj(player_responses
, (..., 'captions', 'playerCaptionsTracklistRenderer'), expected_type
=dict)
4647 def get_lang_code(track
):
4648 return (remove_start(track
.get('vssId') or '', '.').replace('.', '-')
4649 or track
.get('languageCode'))
4651 # Converted into dicts to remove duplicates
4653 get_lang_code(sub
): sub
4654 for sub
in traverse_obj(pctr
, (..., 'captionTracks', ...))}
4655 translation_languages
= {
4656 lang
.get('languageCode'): self
._get
_text
(lang
.get('languageName'), max_runs
=1)
4657 for lang
in traverse_obj(pctr
, (..., 'translationLanguages', ...))}
4659 def process_language(container
, base_url
, lang_code
, sub_name
, query
):
4660 lang_subs
= container
.setdefault(lang_code
, [])
4661 for fmt
in self
._SUBTITLE
_FORMATS
:
4667 'url': urljoin('https://www.youtube.com', update_url_query(base_url
, query
)),
4671 # NB: Constructing the full subtitle dictionary is slow
4672 get_translated_subs
= 'translated_subs' not in self
._configuration
_arg
('skip') and (
4673 self
.get_param('writeautomaticsub', False) or self
.get_param('listsubtitles'))
4674 for lang_code
, caption_track
in captions
.items():
4675 base_url
= caption_track
.get('baseUrl')
4676 orig_lang
= parse_qs(base_url
).get('lang', [None])[-1]
4679 lang_name
= self
._get
_text
(caption_track
, 'name', max_runs
=1)
4680 if caption_track
.get('kind') != 'asr':
4684 subtitles
, base_url
, lang_code
, lang_name
, {})
4685 if not caption_track
.get('isTranslatable'):
4687 for trans_code
, trans_name
in translation_languages
.items():
4690 orig_trans_code
= trans_code
4691 if caption_track
.get('kind') != 'asr' and trans_code
!= 'und':
4692 if not get_translated_subs
:
4694 trans_code
+= f
'-{lang_code}'
4695 trans_name
+= format_field(lang_name
, None, ' from %s')
4696 if lang_code
== f
'a-{orig_trans_code}':
4697 # Set audio language based on original subtitles
4699 if f
.get('acodec') != 'none' and not f
.get('language'):
4700 f
['language'] = orig_trans_code
4701 # Add an "-orig" label to the original language so that it can be distinguished.
4702 # The subs are returned without "-orig" as well for compatibility
4704 automatic_captions
, base_url
, f
'{trans_code}-orig', f
'{trans_name} (Original)', {})
4705 # Setting tlang=lang returns damaged subtitles.
4706 process_language(automatic_captions
, base_url
, trans_code
, trans_name
,
4707 {} if orig_lang
== orig_trans_code
else {'tlang': trans_code
})
4709 info
['automatic_captions'] = automatic_captions
4710 info
['subtitles'] = subtitles
4712 parsed_url
= urllib
.parse
.urlparse(url
)
4713 for component
in [parsed_url
.fragment
, parsed_url
.query
]:
4714 query
= urllib
.parse
.parse_qs(component
)
4715 for k
, v
in query
.items():
4716 for d_k
, s_ks
in [('start', ('start', 't')), ('end', ('end',))]:
4718 if d_k
not in info
and k
in s_ks
:
4719 info
[d_k
] = parse_duration(v
[0])
4721 # Youtube Music Auto-generated description
4722 if (video_description
or '').strip().endswith('\nAuto-generated by YouTube.'):
4723 # XXX: Causes catastrophic backtracking if description has "·"
4724 # E.g. https://www.youtube.com/watch?v=DoPaAxMQoiI
4725 # Simulating atomic groups: (?P<a>[^xy]+)x => (?=(?P<a>[^xy]+))(?P=a)x
4726 # reduces it, but does not fully fix it. https://regex101.com/r/8Ssf2h/2
4729 (?=(?P<track>[^\n·]+))(?P=track)·
4730 (?=(?P<artist>[^\n]+))(?P=artist)\n+
4731 (?=(?P<album>[^\n]+))(?P=album)\n
4732 (?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?
4733 (?:.+?Released\ on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?
4735 (?=(?P<clean_artist>[^\n]+))(?P=clean_artist)\n
4736 )?.+\nAuto-generated\ by\ YouTube\.\s*$
4737 ''', video_description
)
4739 release_year
= mobj
.group('release_year')
4740 release_date
= mobj
.group('release_date')
4742 release_date
= release_date
.replace('-', '')
4743 if not release_year
:
4744 release_year
= release_date
[:4]
4746 'album': mobj
.group('album'.strip()),
4747 'artists': ([a
] if (a
:= mobj
.group('clean_artist'))
4748 else [a
.strip() for a
in mobj
.group('artist').split('·')]),
4749 'track': mobj
.group('track').strip(),
4750 'release_date': release_date
,
4751 'release_year': int_or_none(release_year
),
4756 initial_data
= self
.extract_yt_initial_data(video_id
, webpage
, fatal
=False)
4757 if not traverse_obj(initial_data
, 'contents'):
4758 self
.report_warning('Incomplete data received in embedded initial data; re-fetching using API.')
4760 if not initial_data
:
4761 query
= {'videoId': video_id
}
4762 query
.update(self
._get
_checkok
_params
())
4763 initial_data
= self
._extract
_response
(
4764 item_id
=video_id
, ep
='next', fatal
=False,
4765 ytcfg
=master_ytcfg
, query
=query
, check_get_keys
='contents',
4766 headers
=self
.generate_api_headers(ytcfg
=master_ytcfg
),
4767 note
='Downloading initial data API JSON')
4769 COMMENTS_SECTION_IDS
= ('comment-item-section', 'engagement-panel-comments-section')
4770 info
['comment_count'] = traverse_obj(initial_data
, (
4771 'contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'itemSectionRenderer',
4772 'contents', ..., 'commentsEntryPointHeaderRenderer', 'commentCount',
4774 'engagementPanels', lambda _
, v
: v
['engagementPanelSectionListRenderer']['panelIdentifier'] in COMMENTS_SECTION_IDS
,
4775 'engagementPanelSectionListRenderer', 'header', 'engagementPanelTitleHeaderRenderer', 'contextualInfo',
4776 ), expected_type
=self
._get
_count
, get_all
=False)
4778 try: # This will error if there is no livechat
4779 initial_data
['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
4780 except (KeyError, IndexError, TypeError):
4783 info
.setdefault('subtitles', {})['live_chat'] = [{
4784 # url is needed to set cookies
4785 'url': f
'https://www.youtube.com/watch?v={video_id}&bpctr=9999999999&has_verified=1',
4786 'video_id': video_id
,
4788 'protocol': ('youtube_live_chat' if live_status
in ('is_live', 'is_upcoming')
4789 else 'youtube_live_chat_replay'),
4793 info
['chapters'] = (
4794 self
._extract
_chapters
_from
_json
(initial_data
, duration
)
4795 or self
._extract
_chapters
_from
_engagement
_panel
(initial_data
, duration
)
4796 or self
._extract
_chapters
_from
_description
(video_description
, duration
)
4799 info
['heatmap'] = self
._extract
_heatmap
(initial_data
)
4801 contents
= traverse_obj(
4802 initial_data
, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents'),
4803 expected_type
=list, default
=[])
4805 vpir
= get_first(contents
, 'videoPrimaryInfoRenderer')
4807 stl
= vpir
.get('superTitleLink')
4809 stl
= self
._get
_text
(stl
)
4812 lambda x
: x
['superTitleIcon']['iconType']) == 'LOCATION_PIN':
4813 info
['location'] = stl
4815 mobj
= re
.search(r
'(.+?)\s*S(\d+)\s*•?\s*E(\d+)', stl
)
4818 'series': mobj
.group(1),
4819 'season_number': int(mobj
.group(2)),
4820 'episode_number': int(mobj
.group(3)),
4822 for tlb
in (try_get(
4824 lambda x
: x
['videoActions']['menuRenderer']['topLevelButtons'],
4828 tlb
, ('toggleButtonRenderer', ...),
4829 ('segmentedLikeDislikeButtonRenderer', ..., 'toggleButtonRenderer')))
4831 for getter
, regex
in [(
4832 lambda x
: x
['defaultText']['accessibility']['accessibilityData'],
4833 r
'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
4834 lambda x
: x
['accessibility'],
4835 lambda x
: x
['accessibilityData']['accessibilityData'],
4836 ], r
'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
4837 label
= (try_get(tbr
, getter
, dict) or {}).get('label')
4839 mobj
= re
.match(regex
, label
)
4841 info
[mobj
.group('type') + '_count'] = str_to_int(mobj
.group('count'))
4844 info
['like_count'] = traverse_obj(vpir
, (
4845 'videoActions', 'menuRenderer', 'topLevelButtons', ...,
4846 'segmentedLikeDislikeButtonViewModel', 'likeButtonViewModel', 'likeButtonViewModel',
4847 'toggleButtonViewModel', 'toggleButtonViewModel', 'defaultButtonViewModel',
4848 'buttonViewModel', 'accessibilityText', {parse_count}
), get_all
=False)
4850 vcr
= traverse_obj(vpir
, ('viewCount', 'videoViewCountRenderer'))
4852 vc
= self
._get
_count
(vcr
, 'viewCount')
4853 # Upcoming premieres with waiting count are treated as live here
4854 if vcr
.get('isLive'):
4855 info
['concurrent_view_count'] = vc
4856 elif info
.get('view_count') is None:
4857 info
['view_count'] = vc
4859 vsir
= get_first(contents
, 'videoSecondaryInfoRenderer')
4861 vor
= traverse_obj(vsir
, ('owner', 'videoOwnerRenderer'))
4863 'channel': self
._get
_text
(vor
, 'title'),
4864 'channel_follower_count': self
._get
_count
(vor
, 'subscriberCountText')})
4866 if not channel_handle
:
4867 channel_handle
= self
.handle_from_url(
4869 ('navigationEndpoint', ('title', 'runs', ..., 'navigationEndpoint')),
4870 (('commandMetadata', 'webCommandMetadata', 'url'), ('browseEndpoint', 'canonicalBaseUrl')),
4871 {str}
), get_all
=False))
4875 lambda x
: x
['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
4877 multiple_songs
= False
4879 if try_get(row
, lambda x
: x
['metadataRowRenderer']['hasDividerLine']) is True:
4880 multiple_songs
= True
4883 mrr
= row
.get('metadataRowRenderer') or {}
4884 mrr_title
= mrr
.get('title')
4887 mrr_title
= self
._get
_text
(mrr
, 'title')
4888 mrr_contents_text
= self
._get
_text
(mrr
, ('contents', 0))
4889 if mrr_title
== 'License':
4890 info
['license'] = mrr_contents_text
4891 elif not multiple_songs
:
4892 if mrr_title
== 'Album':
4893 info
['album'] = mrr_contents_text
4894 elif mrr_title
== 'Artist':
4895 info
['artists'] = [mrr_contents_text
] if mrr_contents_text
else None
4896 elif mrr_title
== 'Song':
4897 info
['track'] = mrr_contents_text
4898 owner_badges
= self
._extract
_badges
(traverse_obj(vsir
, ('owner', 'videoOwnerRenderer', 'badges')))
4899 if self
._has
_badge
(owner_badges
, BadgeType
.VERIFIED
):
4900 info
['channel_is_verified'] = True
4903 'uploader': info
.get('channel'),
4904 'uploader_id': channel_handle
,
4905 'uploader_url': format_field(channel_handle
, None, 'https://www.youtube.com/%s', default
=None),
4908 # We only want timestamp IF it has time precision AND a timezone
4909 # Currently the uploadDate in microformats appears to be in US/Pacific timezone.
4911 parse_iso8601(get_first(microformats
, 'uploadDate'), timezone
=NO_DEFAULT
)
4912 or parse_iso8601(search_meta('uploadDate'), timezone
=NO_DEFAULT
)
4915 dt
.datetime
.fromtimestamp(timestamp
, dt
.timezone
.utc
).strftime('%Y%m%d') if timestamp
else
4917 unified_strdate(get_first(microformats
, 'uploadDate'))
4918 or unified_strdate(search_meta('uploadDate'))
4921 # In the case we cannot get the timestamp:
4922 # The upload date for scheduled, live and past live streams / premieres in microformats
4923 # may be different from the stream date. Although not in UTC, we will prefer it in this case.
4924 # See: https://github.com/yt-dlp/yt-dlp/pull/2223#issuecomment-1008485139
4925 if not upload_date
or (not timestamp
and live_status
in ('not_live', None)):
4926 # this should be in UTC, as configured in the cookie/client context
4927 upload_date
= strftime_or_none(
4928 self
._parse
_time
_text
(self
._get
_text
(vpir
, 'dateText'))) or upload_date
4930 info
['upload_date'] = upload_date
4931 info
['timestamp'] = timestamp
4933 if upload_date
and live_status
not in ('is_live', 'post_live', 'is_upcoming'):
4934 # Newly uploaded videos' HLS formats are potentially problematic and need to be checked
4935 upload_datetime
= datetime_from_str(upload_date
).replace(tzinfo
=dt
.timezone
.utc
)
4936 if upload_datetime
>= datetime_from_str('today-2days'):
4937 for fmt
in info
['formats']:
4938 if fmt
.get('protocol') == 'm3u8_native':
4939 fmt
['__needs_testing'] = True
4941 for s_k
, d_k
in [('artists', 'creators'), ('track', 'alt_title')]:
4946 badges
= self
._extract
_badges
(traverse_obj(vpir
, 'badges'))
4948 is_private
= (self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_PRIVATE
)
4949 or get_first(video_details
, 'isPrivate', expected_type
=bool))
4951 info
['availability'] = (
4952 'public' if self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_PUBLIC
)
4953 else self
._availability
(
4954 is_private
=is_private
,
4956 self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_PREMIUM
)
4957 or False if initial_data
and is_private
is not None else None),
4958 needs_subscription
=(
4959 self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_SUBSCRIPTION
)
4960 or False if initial_data
and is_private
is not None else None),
4961 needs_auth
=info
['age_limit'] >= 18,
4962 is_unlisted
=None if is_private
is None else (
4963 self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_UNLISTED
)
4964 or get_first(microformats
, 'isUnlisted', expected_type
=bool))))
4966 info
['__post_extractor'] = self
.extract_comments(master_ytcfg
, video_id
, contents
, webpage
)
4968 self
.mark_watched(video_id
, player_responses
)
4973 class YoutubeTabBaseInfoExtractor(YoutubeBaseInfoExtractor
):
4975 def passthrough_smuggled_data(func
):
4976 def _smuggle(info
, smuggled_data
):
4977 if info
.get('_type') not in ('url', 'url_transparent'):
4979 if smuggled_data
.get('is_music_url'):
4980 parsed_url
= urllib
.parse
.urlparse(info
['url'])
4981 if parsed_url
.netloc
in ('www.youtube.com', 'music.youtube.com'):
4982 smuggled_data
.pop('is_music_url')
4983 info
['url'] = urllib
.parse
.urlunparse(parsed_url
._replace
(netloc
='music.youtube.com'))
4985 info
['url'] = smuggle_url(info
['url'], smuggled_data
)
4988 @functools.wraps(func
)
4989 def wrapper(self
, url
):
4990 url
, smuggled_data
= unsmuggle_url(url
, {})
4991 if self
.is_music_url(url
):
4992 smuggled_data
['is_music_url'] = True
4993 info_dict
= func(self
, url
, smuggled_data
)
4995 _smuggle(info_dict
, smuggled_data
)
4996 if info_dict
.get('entries'):
4997 info_dict
['entries'] = (_smuggle(i
, smuggled_data
.copy()) for i
in info_dict
['entries'])
5002 def _extract_basic_item_renderer(item
):
5003 # Modified from _extract_grid_item_renderer
5004 known_basic_renderers
= (
5005 'playlistRenderer', 'videoRenderer', 'channelRenderer', 'showRenderer', 'reelItemRenderer',
5007 for key
, renderer
in item
.items():
5008 if not isinstance(renderer
, dict):
5010 elif key
in known_basic_renderers
:
5012 elif key
.startswith('grid') and key
.endswith('Renderer'):
5015 def _extract_channel_renderer(self
, renderer
):
5016 channel_id
= self
.ucid_or_none(renderer
['channelId'])
5017 title
= self
._get
_text
(renderer
, 'title')
5018 channel_url
= format_field(channel_id
, None, 'https://www.youtube.com/channel/%s', default
=None)
5019 channel_handle
= self
.handle_from_url(
5020 traverse_obj(renderer
, (
5021 'navigationEndpoint', (('commandMetadata', 'webCommandMetadata', 'url'),
5022 ('browseEndpoint', 'canonicalBaseUrl')),
5023 {str}
), get_all
=False))
5024 if not channel_handle
:
5025 # As of 2023-06-01, YouTube sets subscriberCountText to the handle in search
5026 channel_handle
= self
.handle_or_none(self
._get
_text
(renderer
, 'subscriberCountText'))
5031 'ie_key': YoutubeTabIE
.ie_key(),
5034 'channel_id': channel_id
,
5035 'channel_url': channel_url
,
5037 'uploader_id': channel_handle
,
5038 'uploader_url': format_field(channel_handle
, None, 'https://www.youtube.com/%s', default
=None),
5039 # See above. YouTube sets videoCountText to the subscriber text in search channel renderers.
5040 # However, in feed/channels this is set correctly to the subscriber count
5041 'channel_follower_count': traverse_obj(
5042 renderer
, 'subscriberCountText', 'videoCountText', expected_type
=self
._get
_count
),
5043 'thumbnails': self
._extract
_thumbnails
(renderer
, 'thumbnail'),
5045 # videoCountText may be the subscriber count
5046 self
._get
_count
(renderer
, 'videoCountText')
5047 if self
._get
_count
(renderer
, 'subscriberCountText') is not None else None),
5048 'description': self
._get
_text
(renderer
, 'descriptionSnippet'),
5049 'channel_is_verified': True if self
._has
_badge
(
5050 self
._extract
_badges
(traverse_obj(renderer
, 'ownerBadges')), BadgeType
.VERIFIED
) else None,
5053 def _grid_entries(self
, grid_renderer
):
5054 for item
in grid_renderer
['items']:
5055 if not isinstance(item
, dict):
5057 if lockup_view_model
:= traverse_obj(item
, ('lockupViewModel', {dict}
)):
5058 if entry
:= self
._extract
_lockup
_view
_model
(lockup_view_model
):
5061 renderer
= self
._extract
_basic
_item
_renderer
(item
)
5062 if not isinstance(renderer
, dict):
5064 title
= self
._get
_text
(renderer
, 'title')
5067 playlist_id
= renderer
.get('playlistId')
5069 yield self
.url_result(
5070 f
'https://www.youtube.com/playlist?list={playlist_id}',
5071 ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
,
5075 video_id
= renderer
.get('videoId')
5077 yield self
._extract
_video
(renderer
)
5080 channel_id
= renderer
.get('channelId')
5082 yield self
._extract
_channel
_renderer
(renderer
)
5084 # generic endpoint URL support
5085 ep_url
= urljoin('https://www.youtube.com/', try_get(
5086 renderer
, lambda x
: x
['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
5089 for ie
in (YoutubeTabIE
, YoutubePlaylistIE
, YoutubeIE
):
5090 if ie
.suitable(ep_url
):
5091 yield self
.url_result(
5092 ep_url
, ie
=ie
.ie_key(), video_id
=ie
._match
_id
(ep_url
), video_title
=title
)
5095 def _music_reponsive_list_entry(self
, renderer
):
5096 video_id
= traverse_obj(renderer
, ('playlistItemData', 'videoId'))
5098 title
= traverse_obj(renderer
, (
5099 'flexColumns', 0, 'musicResponsiveListItemFlexColumnRenderer',
5100 'text', 'runs', 0, 'text'))
5101 return self
.url_result(f
'https://music.youtube.com/watch?v={video_id}',
5102 ie
=YoutubeIE
.ie_key(), video_id
=video_id
, title
=title
)
5103 playlist_id
= traverse_obj(renderer
, ('navigationEndpoint', 'watchEndpoint', 'playlistId'))
5105 video_id
= traverse_obj(renderer
, ('navigationEndpoint', 'watchEndpoint', 'videoId'))
5107 return self
.url_result(f
'https://music.youtube.com/watch?v={video_id}&list={playlist_id}',
5108 ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
)
5109 return self
.url_result(f
'https://music.youtube.com/playlist?list={playlist_id}',
5110 ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
)
5111 browse_id
= traverse_obj(renderer
, ('navigationEndpoint', 'browseEndpoint', 'browseId'))
5113 return self
.url_result(f
'https://music.youtube.com/browse/{browse_id}',
5114 ie
=YoutubeTabIE
.ie_key(), video_id
=browse_id
)
5116 def _shelf_entries_from_content(self
, shelf_renderer
):
5117 content
= shelf_renderer
.get('content')
5118 if not isinstance(content
, dict):
5120 renderer
= content
.get('gridRenderer') or content
.get('expandedShelfContentsRenderer')
5122 # TODO: add support for nested playlists so each shelf is processed
5123 # as separate playlist
5124 # TODO: this includes only first N items
5125 yield from self
._grid
_entries
(renderer
)
5126 renderer
= content
.get('horizontalListRenderer')
5131 def _shelf_entries(self
, shelf_renderer
, skip_channels
=False):
5133 shelf_renderer
, lambda x
: x
['endpoint']['commandMetadata']['webCommandMetadata']['url'],
5135 shelf_url
= urljoin('https://www.youtube.com', ep
)
5137 # Skipping links to another channels, note that checking for
5138 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
5140 if skip_channels
and '/channels?' in shelf_url
:
5142 title
= self
._get
_text
(shelf_renderer
, 'title')
5143 yield self
.url_result(shelf_url
, video_title
=title
)
5144 # Shelf may not contain shelf URL, fallback to extraction from content
5145 yield from self
._shelf
_entries
_from
_content
(shelf_renderer
)
5147 def _playlist_entries(self
, video_list_renderer
):
5148 for content
in video_list_renderer
['contents']:
5149 if not isinstance(content
, dict):
5151 renderer
= content
.get('playlistVideoRenderer') or content
.get('playlistPanelVideoRenderer')
5152 if not isinstance(renderer
, dict):
5154 video_id
= renderer
.get('videoId')
5157 yield self
._extract
_video
(renderer
)
5159 def _extract_lockup_view_model(self
, view_model
):
5160 content_id
= view_model
.get('contentId')
5163 content_type
= view_model
.get('contentType')
5164 if content_type
not in ('LOCKUP_CONTENT_TYPE_PLAYLIST', 'LOCKUP_CONTENT_TYPE_PODCAST'):
5165 self
.report_warning(
5166 f
'Unsupported lockup view model content type "{content_type}"{bug_reports_message()}', only_once
=True)
5168 return self
.url_result(
5169 f
'https://www.youtube.com/playlist?list={content_id}', ie
=YoutubeTabIE
, video_id
=content_id
,
5170 title
=traverse_obj(view_model
, (
5171 'metadata', 'lockupMetadataViewModel', 'title', 'content', {str}
)),
5172 thumbnails
=self
._extract
_thumbnails
(view_model
, (
5173 'contentImage', 'collectionThumbnailViewModel', 'primaryThumbnail', 'thumbnailViewModel', 'image'), final_key
='sources'))
5175 def _rich_entries(self
, rich_grid_renderer
):
5176 if lockup_view_model
:= traverse_obj(rich_grid_renderer
, ('content', 'lockupViewModel', {dict}
)):
5177 if entry
:= self
._extract
_lockup
_view
_model
(lockup_view_model
):
5180 renderer
= traverse_obj(
5182 ('content', ('videoRenderer', 'reelItemRenderer', 'playlistRenderer', 'shortsLockupViewModel'), any
)) or {}
5183 video_id
= renderer
.get('videoId')
5185 yield self
._extract
_video
(renderer
)
5187 playlist_id
= renderer
.get('playlistId')
5189 yield self
.url_result(
5190 f
'https://www.youtube.com/playlist?list={playlist_id}',
5191 ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
,
5192 video_title
=self
._get
_text
(renderer
, 'title'))
5194 # shortsLockupViewModel extraction
5195 entity_id
= renderer
.get('entityId')
5197 video_id
= traverse_obj(renderer
, ('onTap', 'innertubeCommand', 'reelWatchEndpoint', 'videoId', {str}
))
5200 yield self
.url_result(
5201 f
'https://www.youtube.com/shorts/{video_id}',
5202 ie
=YoutubeIE
, video_id
=video_id
,
5203 **traverse_obj(renderer
, ('overlayMetadata', {
5204 'title': ('primaryText', 'content', {str}
),
5205 'view_count': ('secondaryText', 'content', {parse_count}
),
5207 thumbnails
=self
._extract
_thumbnails
(renderer
, 'thumbnail', final_key
='sources'))
5210 def _video_entry(self
, video_renderer
):
5211 video_id
= video_renderer
.get('videoId')
5213 return self
._extract
_video
(video_renderer
)
5215 def _hashtag_tile_entry(self
, hashtag_tile_renderer
):
5216 url
= urljoin('https://youtube.com', traverse_obj(
5217 hashtag_tile_renderer
, ('onTapCommand', 'commandMetadata', 'webCommandMetadata', 'url')))
5219 return self
.url_result(
5220 url
, ie
=YoutubeTabIE
.ie_key(), title
=self
._get
_text
(hashtag_tile_renderer
, 'hashtag'))
5222 def _post_thread_entries(self
, post_thread_renderer
):
5223 post_renderer
= try_get(
5224 post_thread_renderer
, lambda x
: x
['post']['backstagePostRenderer'], dict)
5225 if not post_renderer
:
5228 video_renderer
= try_get(
5229 post_renderer
, lambda x
: x
['backstageAttachment']['videoRenderer'], dict) or {}
5230 video_id
= video_renderer
.get('videoId')
5232 entry
= self
._extract
_video
(video_renderer
)
5235 # playlist attachment
5236 playlist_id
= try_get(
5237 post_renderer
, lambda x
: x
['backstageAttachment']['playlistRenderer']['playlistId'], str)
5239 yield self
.url_result(
5240 f
'https://www.youtube.com/playlist?list={playlist_id}',
5241 ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
)
5242 # inline video links
5243 runs
= try_get(post_renderer
, lambda x
: x
['contentText']['runs'], list) or []
5245 if not isinstance(run
, dict):
5248 run
, lambda x
: x
['navigationEndpoint']['urlEndpoint']['url'], str)
5251 if not YoutubeIE
.suitable(ep_url
):
5253 ep_video_id
= YoutubeIE
._match
_id
(ep_url
)
5254 if video_id
== ep_video_id
:
5256 yield self
.url_result(ep_url
, ie
=YoutubeIE
.ie_key(), video_id
=ep_video_id
)
5258 def _post_thread_continuation_entries(self
, post_thread_continuation
):
5259 contents
= post_thread_continuation
.get('contents')
5260 if not isinstance(contents
, list):
5262 for content
in contents
:
5263 renderer
= content
.get('backstagePostThreadRenderer')
5264 if isinstance(renderer
, dict):
5265 yield from self
._post
_thread
_entries
(renderer
)
5267 renderer
= content
.get('videoRenderer')
5268 if isinstance(renderer
, dict):
5269 yield self
._video
_entry
(renderer
)
5272 def _rich_grid_entries(self, contents):
5273 for content in contents:
5274 video_renderer = try_get(content, lambda x: x['richItemRenderer']['content']['videoRenderer'], dict)
5276 entry = self._video_entry(video_renderer)
5281 def _report_history_entries(self
, renderer
):
5282 for url
in traverse_obj(renderer
, (
5283 'rows', ..., 'reportHistoryTableRowRenderer', 'cells', ...,
5284 'reportHistoryTableCellRenderer', 'cell', 'reportHistoryTableTextCellRenderer', 'text', 'runs', ...,
5285 'navigationEndpoint', 'commandMetadata', 'webCommandMetadata', 'url')):
5286 yield self
.url_result(urljoin('https://www.youtube.com', url
), YoutubeIE
)
5288 def _extract_entries(self
, parent_renderer
, continuation_list
):
5289 # continuation_list is modified in-place with continuation_list = [continuation_token]
5290 continuation_list
[:] = [None]
5291 contents
= try_get(parent_renderer
, lambda x
: x
['contents'], list) or []
5292 for content
in contents
:
5293 if not isinstance(content
, dict):
5295 is_renderer
= traverse_obj(
5296 content
, 'itemSectionRenderer', 'musicShelfRenderer', 'musicShelfContinuation',
5299 if content
.get('richItemRenderer'):
5300 for entry
in self
._rich
_entries
(content
['richItemRenderer']):
5302 continuation_list
[0] = self
._extract
_continuation
(parent_renderer
)
5303 elif content
.get('reportHistorySectionRenderer'): # https://www.youtube.com/reporthistory
5304 table
= traverse_obj(content
, ('reportHistorySectionRenderer', 'table', 'tableRenderer'))
5305 yield from self
._report
_history
_entries
(table
)
5306 continuation_list
[0] = self
._extract
_continuation
(table
)
5309 isr_contents
= try_get(is_renderer
, lambda x
: x
['contents'], list) or []
5310 for isr_content
in isr_contents
:
5311 if not isinstance(isr_content
, dict):
5315 'playlistVideoListRenderer': self
._playlist
_entries
,
5316 'gridRenderer': self
._grid
_entries
,
5317 'reelShelfRenderer': self
._grid
_entries
,
5318 'shelfRenderer': self
._shelf
_entries
,
5319 'musicResponsiveListItemRenderer': lambda x
: [self
._music
_reponsive
_list
_entry
(x
)],
5320 'backstagePostThreadRenderer': self
._post
_thread
_entries
,
5321 'videoRenderer': lambda x
: [self
._video
_entry
(x
)],
5322 'playlistRenderer': lambda x
: self
._grid
_entries
({'items': [{'playlistRenderer': x
}]}),
5323 'channelRenderer': lambda x
: self
._grid
_entries
({'items': [{'channelRenderer': x
}]}),
5324 'hashtagTileRenderer': lambda x
: [self
._hashtag
_tile
_entry
(x
)],
5325 'richGridRenderer': lambda x
: self
._extract
_entries
(x
, continuation_list
),
5326 'lockupViewModel': lambda x
: [self
._extract
_lockup
_view
_model
(x
)],
5328 for key
, renderer
in isr_content
.items():
5329 if key
not in known_renderers
:
5331 for entry
in known_renderers
[key
](renderer
):
5334 continuation_list
[0] = self
._extract
_continuation
(renderer
)
5337 if not continuation_list
[0]:
5338 continuation_list
[0] = self
._extract
_continuation
(is_renderer
)
5340 if not continuation_list
[0]:
5341 continuation_list
[0] = self
._extract
_continuation
(parent_renderer
)
5343 def _entries(self
, tab
, item_id
, ytcfg
, account_syncid
, visitor_data
):
5344 continuation_list
= [None]
5345 extract_entries
= lambda x
: self
._extract
_entries
(x
, continuation_list
)
5346 tab_content
= try_get(tab
, lambda x
: x
['content'], dict)
5350 try_get(tab_content
, lambda x
: x
['sectionListRenderer'], dict)
5351 or try_get(tab_content
, lambda x
: x
['richGridRenderer'], dict) or {})
5352 yield from extract_entries(parent_renderer
)
5353 continuation
= continuation_list
[0]
5354 seen_continuations
= set()
5355 for page_num
in itertools
.count(1):
5356 if not continuation
:
5358 continuation_token
= continuation
.get('continuation')
5359 if continuation_token
is not None and continuation_token
in seen_continuations
:
5360 self
.write_debug('Detected YouTube feed looping - assuming end of feed.')
5362 seen_continuations
.add(continuation_token
)
5363 headers
= self
.generate_api_headers(
5364 ytcfg
=ytcfg
, account_syncid
=account_syncid
, visitor_data
=visitor_data
)
5365 response
= self
._extract
_response
(
5366 item_id
=f
'{item_id} page {page_num}',
5367 query
=continuation
, headers
=headers
, ytcfg
=ytcfg
,
5368 check_get_keys
=('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints'))
5372 # Extracting updated visitor data is required to prevent an infinite extraction loop in some cases
5373 # See: https://github.com/ytdl-org/youtube-dl/issues/28702
5374 visitor_data
= self
._extract
_visitor
_data
(response
) or visitor_data
5377 'videoRenderer': (self
._grid
_entries
, 'items'), # for membership tab
5378 'gridPlaylistRenderer': (self
._grid
_entries
, 'items'),
5379 'gridVideoRenderer': (self
._grid
_entries
, 'items'),
5380 'gridChannelRenderer': (self
._grid
_entries
, 'items'),
5381 'playlistVideoRenderer': (self
._playlist
_entries
, 'contents'),
5382 'itemSectionRenderer': (extract_entries
, 'contents'), # for feeds
5383 'richItemRenderer': (extract_entries
, 'contents'), # for hashtag
5384 'backstagePostThreadRenderer': (self
._post
_thread
_continuation
_entries
, 'contents'),
5385 'reportHistoryTableRowRenderer': (self
._report
_history
_entries
, 'rows'),
5386 'playlistVideoListContinuation': (self
._playlist
_entries
, None),
5387 'gridContinuation': (self
._grid
_entries
, None),
5388 'itemSectionContinuation': (self
._post
_thread
_continuation
_entries
, None),
5389 'sectionListContinuation': (extract_entries
, None), # for feeds
5392 continuation_items
= traverse_obj(response
, (
5393 ('onResponseReceivedActions', 'onResponseReceivedEndpoints'), ...,
5394 'appendContinuationItemsAction', 'continuationItems',
5395 ), 'continuationContents', get_all
=False)
5396 continuation_item
= traverse_obj(continuation_items
, 0, None, expected_type
=dict, default
={})
5398 video_items_renderer
= None
5399 for key
in continuation_item
:
5400 if key
not in known_renderers
:
5402 func
, parent_key
= known_renderers
[key
]
5403 video_items_renderer
= {parent_key
: continuation_items
} if parent_key
else continuation_items
5404 continuation_list
= [None]
5405 yield from func(video_items_renderer
)
5406 continuation
= continuation_list
[0] or self
._extract
_continuation
(video_items_renderer
)
5408 if not video_items_renderer
:
5412 def _extract_selected_tab(tabs
, fatal
=True):
5413 for tab_renderer
in tabs
:
5414 if tab_renderer
.get('selected'):
5417 raise ExtractorError('Unable to find selected tab')
5420 def _extract_tab_renderers(response
):
5421 return traverse_obj(
5422 response
, ('contents', 'twoColumnBrowseResultsRenderer', 'tabs', ..., ('tabRenderer', 'expandableTabRenderer')), expected_type
=dict)
5424 def _extract_from_tabs(self
, item_id
, ytcfg
, data
, tabs
):
5425 metadata
= self
._extract
_metadata
_from
_tabs
(item_id
, data
)
5427 selected_tab
= self
._extract
_selected
_tab
(tabs
)
5428 metadata
['title'] += format_field(selected_tab
, 'title', ' - %s')
5429 metadata
['title'] += format_field(selected_tab
, 'expandedText', ' - %s')
5431 return self
.playlist_result(
5433 selected_tab
, metadata
['id'], ytcfg
,
5434 self
._extract
_account
_syncid
(ytcfg
, data
),
5435 self
._extract
_visitor
_data
(data
, ytcfg
)),
5438 def _extract_metadata_from_tabs(self
, item_id
, data
):
5439 info
= {'id': item_id
}
5441 metadata_renderer
= traverse_obj(data
, ('metadata', 'channelMetadataRenderer'), expected_type
=dict)
5442 if metadata_renderer
:
5443 channel_id
= traverse_obj(metadata_renderer
, ('externalId', {self
.ucid_or_none
}),
5444 ('channelUrl', {self
.ucid_from_url
}))
5446 'channel': metadata_renderer
.get('title'),
5447 'channel_id': channel_id
,
5449 if info
['channel_id']:
5450 info
['id'] = info
['channel_id']
5452 metadata_renderer
= traverse_obj(data
, ('metadata', 'playlistMetadataRenderer'), expected_type
=dict)
5454 # pageHeaderViewModel slow rollout began April 2024
5455 page_header_view_model
= traverse_obj(data
, (
5456 'header', 'pageHeaderRenderer', 'content', 'pageHeaderViewModel', {dict}
))
5458 # We can get the uncropped banner/avatar by replacing the crop params with '=s0'
5459 # See: https://github.com/yt-dlp/yt-dlp/issues/2237#issuecomment-1013694714
5460 def _get_uncropped(url
):
5461 return url_or_none((url
or '').split('=')[0] + '=s0')
5463 avatar_thumbnails
= self
._extract
_thumbnails
(metadata_renderer
, 'avatar')
5464 if avatar_thumbnails
:
5465 uncropped_avatar
= _get_uncropped(avatar_thumbnails
[0]['url'])
5466 if uncropped_avatar
:
5467 avatar_thumbnails
.append({
5468 'url': uncropped_avatar
,
5469 'id': 'avatar_uncropped',
5474 self
._extract
_thumbnails
(data
, ('header', ..., ('banner', 'mobileBanner', 'tvBanner')))
5475 or self
._extract
_thumbnails
(
5476 page_header_view_model
, ('banner', 'imageBannerViewModel', 'image'), final_key
='sources'))
5477 for banner
in channel_banners
:
5478 banner
['preference'] = -10
5481 uncropped_banner
= _get_uncropped(channel_banners
[0]['url'])
5482 if uncropped_banner
:
5483 channel_banners
.append({
5484 'url': uncropped_banner
,
5485 'id': 'banner_uncropped',
5489 # Deprecated - remove primary_sidebar_renderer when layout discontinued
5490 primary_sidebar_renderer
= self
._extract
_sidebar
_info
_renderer
(data
, 'playlistSidebarPrimaryInfoRenderer')
5491 playlist_header_renderer
= traverse_obj(data
, ('header', 'playlistHeaderRenderer'), expected_type
=dict)
5493 primary_thumbnails
= self
._extract
_thumbnails
(
5494 primary_sidebar_renderer
, ('thumbnailRenderer', ('playlistVideoThumbnailRenderer', 'playlistCustomThumbnailRenderer'), 'thumbnail'))
5495 playlist_thumbnails
= self
._extract
_thumbnails
(
5496 playlist_header_renderer
, ('playlistHeaderBanner', 'heroPlaylistThumbnailRenderer', 'thumbnail'))
5499 'title': (traverse_obj(metadata_renderer
, 'title')
5500 or self
._get
_text
(data
, ('header', 'hashtagHeaderRenderer', 'hashtag'))
5502 'availability': self
._extract
_availability
(data
),
5503 'channel_follower_count': (
5504 self
._get
_count
(data
, ('header', ..., 'subscriberCountText'))
5505 or traverse_obj(page_header_view_model
, (
5506 'metadata', 'contentMetadataViewModel', 'metadataRows', ..., 'metadataParts',
5507 lambda _
, v
: 'subscribers' in v
['text']['content'], 'text', 'content', {parse_count}
, any
))),
5508 'description': try_get(metadata_renderer
, lambda x
: x
.get('description', '')),
5509 'tags': (traverse_obj(data
, ('microformat', 'microformatDataRenderer', 'tags', ..., {str}
))
5510 or traverse_obj(metadata_renderer
, ('keywords', {lambda x
: x
and shlex
.split(x
)}, ...))),
5511 'thumbnails': (primary_thumbnails
or playlist_thumbnails
) + avatar_thumbnails
+ channel_banners
,
5515 traverse_obj(metadata_renderer
, (('vanityChannelUrl', ('ownerUrls', ...)), {self
.handle_from_url
}), get_all
=False)
5516 or traverse_obj(data
, ('header', ..., 'channelHandleText', {self
.handle_or_none
}), get_all
=False))
5520 'uploader_id': channel_handle
,
5521 'uploader_url': format_field(channel_handle
, None, 'https://www.youtube.com/%s', default
=None),
5524 channel_badges
= self
._extract
_badges
(traverse_obj(data
, ('header', ..., 'badges'), get_all
=False))
5525 if self
._has
_badge
(channel_badges
, BadgeType
.VERIFIED
):
5526 info
['channel_is_verified'] = True
5527 # Playlist stats is a text runs array containing [video count, view count, last updated].
5528 # last updated or (view count and last updated) may be missing.
5529 playlist_stats
= get_first(
5530 (primary_sidebar_renderer
, playlist_header_renderer
), (('stats', 'briefStats', 'numVideosText'), ))
5532 last_updated_unix
= self
._parse
_time
_text
(
5533 self
._get
_text
(playlist_stats
, 2) # deprecated, remove when old layout discontinued
5534 or self
._get
_text
(playlist_header_renderer
, ('byline', 1, 'playlistBylineRenderer', 'text')))
5535 info
['modified_date'] = strftime_or_none(last_updated_unix
)
5537 info
['view_count'] = self
._get
_count
(playlist_stats
, 1)
5538 if info
['view_count'] is None: # 0 is allowed
5539 info
['view_count'] = self
._get
_count
(playlist_header_renderer
, 'viewCountText')
5540 if info
['view_count'] is None:
5541 info
['view_count'] = self
._get
_count
(data
, (
5542 'contents', 'twoColumnBrowseResultsRenderer', 'tabs', ..., 'tabRenderer', 'content', 'sectionListRenderer',
5543 'contents', ..., 'itemSectionRenderer', 'contents', ..., 'channelAboutFullMetadataRenderer', 'viewCountText'))
5545 info
['playlist_count'] = self
._get
_count
(playlist_stats
, 0)
5546 if info
['playlist_count'] is None: # 0 is allowed
5547 info
['playlist_count'] = self
._get
_count
(playlist_header_renderer
, ('byline', 0, 'playlistBylineRenderer', 'text'))
5549 if not info
.get('channel_id'):
5550 owner
= traverse_obj(playlist_header_renderer
, 'ownerText')
5551 if not owner
: # Deprecated
5552 owner
= traverse_obj(
5553 self
._extract
_sidebar
_info
_renderer
(data
, 'playlistSidebarSecondaryInfoRenderer'),
5554 ('videoOwner', 'videoOwnerRenderer', 'title'))
5555 owner_text
= self
._get
_text
(owner
)
5556 browse_ep
= traverse_obj(owner
, ('runs', 0, 'navigationEndpoint', 'browseEndpoint')) or {}
5558 'channel': self
._search
_regex
(r
'^by (.+) and \d+ others?$', owner_text
, 'uploader', default
=owner_text
),
5559 'channel_id': self
.ucid_or_none(browse_ep
.get('browseId')),
5560 'uploader_id': self
.handle_from_url(urljoin('https://www.youtube.com', browse_ep
.get('canonicalBaseUrl'))),
5564 'uploader': info
['channel'],
5565 'channel_url': format_field(info
.get('channel_id'), None, 'https://www.youtube.com/channel/%s', default
=None),
5566 'uploader_url': format_field(info
.get('uploader_id'), None, 'https://www.youtube.com/%s', default
=None),
5571 def _extract_inline_playlist(self
, playlist
, playlist_id
, data
, ytcfg
):
5572 first_id
= last_id
= response
= None
5573 for page_num
in itertools
.count(1):
5574 videos
= list(self
._playlist
_entries
(playlist
))
5577 start
= next((i
for i
, v
in enumerate(videos
) if v
['id'] == last_id
), -1) + 1
5578 if start
>= len(videos
):
5580 yield from videos
[start
:]
5581 first_id
= first_id
or videos
[0]['id']
5582 last_id
= videos
[-1]['id']
5583 watch_endpoint
= try_get(
5584 playlist
, lambda x
: x
['contents'][-1]['playlistPanelVideoRenderer']['navigationEndpoint']['watchEndpoint'])
5585 headers
= self
.generate_api_headers(
5586 ytcfg
=ytcfg
, account_syncid
=self
._extract
_account
_syncid
(ytcfg
, data
),
5587 visitor_data
=self
._extract
_visitor
_data
(response
, data
, ytcfg
))
5589 'playlistId': playlist_id
,
5590 'videoId': watch_endpoint
.get('videoId') or last_id
,
5591 'index': watch_endpoint
.get('index') or len(videos
),
5592 'params': watch_endpoint
.get('params') or 'OAE%3D',
5594 response
= self
._extract
_response
(
5595 item_id
=f
'{playlist_id} page {page_num}',
5596 query
=query
, ep
='next', headers
=headers
, ytcfg
=ytcfg
,
5597 check_get_keys
='contents',
5600 response
, lambda x
: x
['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
5602 def _extract_from_playlist(self
, item_id
, url
, data
, playlist
, ytcfg
):
5603 title
= playlist
.get('title') or try_get(
5604 data
, lambda x
: x
['titleText']['simpleText'], str)
5605 playlist_id
= playlist
.get('playlistId') or item_id
5607 # Delegating everything except mix playlists to regular tab-based playlist URL
5608 playlist_url
= urljoin(url
, try_get(
5609 playlist
, lambda x
: x
['endpoint']['commandMetadata']['webCommandMetadata']['url'],
5612 # Some playlists are unviewable but YouTube still provides a link to the (broken) playlist page [1]
5613 # [1] MLCT, RLTDwFCb4jeqaKWnciAYM-ZVHg
5614 is_known_unviewable
= re
.fullmatch(r
'MLCT|RLTD[\w-]{22}', playlist_id
)
5616 if playlist_url
and playlist_url
!= url
and not is_known_unviewable
:
5617 return self
.url_result(
5618 playlist_url
, ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
,
5621 return self
.playlist_result(
5622 self
._extract
_inline
_playlist
(playlist
, playlist_id
, data
, ytcfg
),
5623 playlist_id
=playlist_id
, playlist_title
=title
)
5625 def _extract_availability(self
, data
):
5627 Gets the availability of a given playlist/tab.
5628 Note: Unless YouTube tells us explicitly, we do not assume it is public
5629 @param data: response
5631 sidebar_renderer
= self
._extract
_sidebar
_info
_renderer
(data
, 'playlistSidebarPrimaryInfoRenderer') or {}
5632 playlist_header_renderer
= traverse_obj(data
, ('header', 'playlistHeaderRenderer')) or {}
5633 player_header_privacy
= playlist_header_renderer
.get('privacy')
5635 badges
= self
._extract
_badges
(traverse_obj(sidebar_renderer
, 'badges'))
5637 # Personal playlists, when authenticated, have a dropdown visibility selector instead of a badge
5638 privacy_setting_icon
= get_first(
5639 (playlist_header_renderer
, sidebar_renderer
),
5640 ('privacyForm', 'dropdownFormFieldRenderer', 'dropdown', 'dropdownRenderer', 'entries',
5641 lambda _
, v
: v
['privacyDropdownItemRenderer']['isSelected'], 'privacyDropdownItemRenderer', 'icon', 'iconType'),
5644 microformats_is_unlisted
= traverse_obj(
5645 data
, ('microformat', 'microformatDataRenderer', 'unlisted'), expected_type
=bool)
5649 self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_PUBLIC
)
5650 or player_header_privacy
== 'PUBLIC'
5651 or privacy_setting_icon
== 'PRIVACY_PUBLIC')
5652 else self
._availability
(
5654 self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_PRIVATE
)
5655 or player_header_privacy
== 'PRIVATE' if player_header_privacy
is not None
5656 else privacy_setting_icon
== 'PRIVACY_PRIVATE' if privacy_setting_icon
is not None else None),
5658 self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_UNLISTED
)
5659 or player_header_privacy
== 'UNLISTED' if player_header_privacy
is not None
5660 else privacy_setting_icon
== 'PRIVACY_UNLISTED' if privacy_setting_icon
is not None
5661 else microformats_is_unlisted
if microformats_is_unlisted
is not None else None),
5662 needs_subscription
=self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_SUBSCRIPTION
) or None,
5663 needs_premium
=self
._has
_badge
(badges
, BadgeType
.AVAILABILITY_PREMIUM
) or None,
5667 def _extract_sidebar_info_renderer(data
, info_renderer
, expected_type
=dict):
5668 sidebar_renderer
= try_get(
5669 data
, lambda x
: x
['sidebar']['playlistSidebarRenderer']['items'], list) or []
5670 for item
in sidebar_renderer
:
5671 renderer
= try_get(item
, lambda x
: x
[info_renderer
], expected_type
)
5675 def _reload_with_unavailable_videos(self
, item_id
, data
, ytcfg
):
5677 Reload playlists with unavailable videos (e.g. private videos, region blocked, etc.)
5679 is_playlist
= bool(traverse_obj(
5680 data
, ('metadata', 'playlistMetadataRenderer'), ('header', 'playlistHeaderRenderer')))
5683 headers
= self
.generate_api_headers(
5684 ytcfg
=ytcfg
, account_syncid
=self
._extract
_account
_syncid
(ytcfg
, data
),
5685 visitor_data
=self
._extract
_visitor
_data
(data
, ytcfg
))
5687 'params': 'wgYCCAA=',
5688 'browseId': f
'VL{item_id}',
5690 return self
._extract
_response
(
5691 item_id
=item_id
, headers
=headers
, query
=query
,
5692 check_get_keys
='contents', fatal
=False, ytcfg
=ytcfg
,
5693 note
='Redownloading playlist API JSON with unavailable videos')
5695 @functools.cached_property
5696 def skip_webpage(self
):
5697 return 'webpage' in self
._configuration
_arg
('skip', ie_key
=YoutubeTabIE
.ie_key())
5699 def _extract_webpage(self
, url
, item_id
, fatal
=True):
5700 webpage
, data
= None, None
5701 for retry
in self
.RetryManager(fatal
=fatal
):
5703 webpage
= self
._download
_webpage
(url
, item_id
, note
='Downloading webpage')
5704 data
= self
.extract_yt_initial_data(item_id
, webpage
or '', fatal
=fatal
) or {}
5705 except ExtractorError
as e
:
5706 if isinstance(e
.cause
, network_exceptions
):
5707 if not isinstance(e
.cause
, HTTPError
) or e
.cause
.status
not in (403, 429):
5710 self
._error
_or
_warning
(e
, fatal
=fatal
)
5714 self
._extract
_and
_report
_alerts
(data
)
5715 except ExtractorError
as e
:
5716 self
._error
_or
_warning
(e
, fatal
=fatal
)
5719 # Sometimes youtube returns a webpage with incomplete ytInitialData
5720 # See: https://github.com/yt-dlp/yt-dlp/issues/116
5721 if not traverse_obj(data
, 'contents', 'currentVideoEndpoint', 'onResponseReceivedActions'):
5722 retry
.error
= ExtractorError('Incomplete yt initial data received')
5726 return webpage
, data
5728 def _report_playlist_authcheck(self
, ytcfg
, fatal
=True):
5729 """Use if failed to extract ytcfg (and data) from initial webpage"""
5730 if not ytcfg
and self
.is_authenticated
:
5731 msg
= 'Playlists that require authentication may not extract correctly without a successful webpage download'
5732 if 'authcheck' not in self
._configuration
_arg
('skip', ie_key
=YoutubeTabIE
.ie_key()) and fatal
:
5733 raise ExtractorError(
5734 f
'{msg}. If you are not downloading private content, or '
5735 'your cookies are only for the first account and channel,'
5736 ' pass "--extractor-args youtubetab:skip=authcheck" to skip this check',
5738 self
.report_warning(msg
, only_once
=True)
5740 def _extract_data(self
, url
, item_id
, ytcfg
=None, fatal
=True, webpage_fatal
=False, default_client
='web'):
5742 if not self
.skip_webpage
:
5743 webpage
, data
= self
._extract
_webpage
(url
, item_id
, fatal
=webpage_fatal
)
5744 ytcfg
= ytcfg
or self
.extract_ytcfg(item_id
, webpage
)
5745 # Reject webpage data if redirected to home page without explicitly requesting
5746 selected_tab
= self
._extract
_selected
_tab
(self
._extract
_tab
_renderers
(data
), fatal
=False) or {}
5747 if (url
!= 'https://www.youtube.com/feed/recommended'
5748 and selected_tab
.get('tabIdentifier') == 'FEwhat_to_watch' # Home page
5749 and 'no-youtube-channel-redirect' not in self
.get_param('compat_opts', [])):
5750 msg
= 'The channel/playlist does not exist and the URL redirected to youtube.com home page'
5752 raise ExtractorError(msg
, expected
=True)
5753 self
.report_warning(msg
, only_once
=True)
5755 self
._report
_playlist
_authcheck
(ytcfg
, fatal
=fatal
)
5756 data
= self
._extract
_tab
_endpoint
(url
, item_id
, ytcfg
, fatal
=fatal
, default_client
=default_client
)
5759 def _extract_tab_endpoint(self
, url
, item_id
, ytcfg
=None, fatal
=True, default_client
='web'):
5760 headers
= self
.generate_api_headers(ytcfg
=ytcfg
, default_client
=default_client
)
5761 resolve_response
= self
._extract
_response
(
5762 item_id
=item_id
, query
={'url': url
}, check_get_keys
='endpoint', headers
=headers
, ytcfg
=ytcfg
, fatal
=fatal
,
5763 ep
='navigation/resolve_url', note
='Downloading API parameters API JSON', default_client
=default_client
)
5764 endpoints
= {'browseEndpoint': 'browse', 'watchEndpoint': 'next'}
5765 for ep_key
, ep
in endpoints
.items():
5766 params
= try_get(resolve_response
, lambda x
: x
['endpoint'][ep_key
], dict)
5768 return self
._extract
_response
(
5769 item_id
=item_id
, query
=params
, ep
=ep
, headers
=headers
,
5770 ytcfg
=ytcfg
, fatal
=fatal
, default_client
=default_client
,
5771 check_get_keys
=('contents', 'currentVideoEndpoint', 'onResponseReceivedActions'))
5772 err_note
= 'Failed to resolve url (does the playlist exist?)'
5774 raise ExtractorError(err_note
, expected
=True)
5775 self
.report_warning(err_note
, item_id
)
5777 _SEARCH_PARAMS
= None
5779 def _search_results(self
, query
, params
=NO_DEFAULT
, default_client
='web'):
5780 data
= {'query': query
}
5781 if params
is NO_DEFAULT
:
5782 params
= self
._SEARCH
_PARAMS
5784 data
['params'] = params
5787 ('contents', 'twoColumnSearchResultsRenderer', 'primaryContents', 'sectionListRenderer', 'contents'),
5788 ('onResponseReceivedCommands', 0, 'appendContinuationItemsAction', 'continuationItems'),
5790 ('contents', 'tabbedSearchResultsRenderer', 'tabs', 0, 'tabRenderer', 'content', 'sectionListRenderer', 'contents'),
5791 ('continuationContents', ),
5793 display_id
= f
'query "{query}"'
5794 check_get_keys
= tuple({keys
[0] for keys
in content_keys
})
5795 ytcfg
= self
._download
_ytcfg
(default_client
, display_id
) if not self
.skip_webpage
else {}
5796 self
._report
_playlist
_authcheck
(ytcfg
, fatal
=False)
5798 continuation_list
= [None]
5800 for page_num
in itertools
.count(1):
5801 data
.update(continuation_list
[0] or {})
5802 headers
= self
.generate_api_headers(
5803 ytcfg
=ytcfg
, visitor_data
=self
._extract
_visitor
_data
(search
), default_client
=default_client
)
5804 search
= self
._extract
_response
(
5805 item_id
=f
'{display_id} page {page_num}', ep
='search', query
=data
,
5806 default_client
=default_client
, check_get_keys
=check_get_keys
, ytcfg
=ytcfg
, headers
=headers
)
5807 slr_contents
= traverse_obj(search
, *content_keys
)
5808 yield from self
._extract
_entries
({'contents': list(variadic(slr_contents
))}, continuation_list
)
5809 if not continuation_list
[0]:
5813 class YoutubeTabIE(YoutubeTabBaseInfoExtractor
):
5814 IE_DESC
= 'YouTube Tabs'
5815 _VALID_URL
= r
'''(?x:
5817 (?!consent\.)(?:\w+\.)?
5819 youtube(?:kids)?\.com|
5823 (?P<channel_type>channel|c|user|browse)/|
5826 (?:playlist|watch)\?.*?\blist=
5828 (?!(?:{reserved_names})\b) # Direct URLs
5832 reserved_names
=YoutubeBaseInfoExtractor
._RESERVED
_NAMES
,
5833 invidious
='|'.join(YoutubeBaseInfoExtractor
._INVIDIOUS
_SITES
),
5835 IE_NAME
= 'youtube:tab'
5838 'note': 'playlists, multipage',
5839 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
5840 'playlist_mincount': 94,
5842 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
5843 'title': 'Igor Kleiner Ph.D. - Playlists',
5844 'description': 'md5:15d7dd9e333cb987907fcb0d604b233a',
5845 'uploader': 'Igor Kleiner Ph.D.',
5846 'uploader_id': '@IgorDataScience',
5847 'uploader_url': 'https://www.youtube.com/@IgorDataScience',
5848 'channel': 'Igor Kleiner Ph.D.',
5849 'channel_id': 'UCqj7Cz7revf5maW9g5pgNcg',
5850 'tags': ['критическое мышление', 'наука просто', 'математика', 'анализ данных'],
5851 'channel_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
5852 'channel_follower_count': int,
5855 'note': 'playlists, multipage, different order',
5856 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
5857 'playlist_mincount': 94,
5859 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
5860 'title': 'Igor Kleiner Ph.D. - Playlists',
5861 'description': 'md5:15d7dd9e333cb987907fcb0d604b233a',
5862 'uploader': 'Igor Kleiner Ph.D.',
5863 'uploader_id': '@IgorDataScience',
5864 'uploader_url': 'https://www.youtube.com/@IgorDataScience',
5865 'tags': ['критическое мышление', 'наука просто', 'математика', 'анализ данных'],
5866 'channel_id': 'UCqj7Cz7revf5maW9g5pgNcg',
5867 'channel': 'Igor Kleiner Ph.D.',
5868 'channel_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
5869 'channel_follower_count': int,
5872 'note': 'playlists, series',
5873 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
5874 'playlist_mincount': 5,
5876 'id': 'UCYO_jab_esuFRV4b17AJtAw',
5877 'title': '3Blue1Brown - Playlists',
5878 'description': 'md5:602e3789e6a0cb7d9d352186b720e395',
5879 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
5880 'channel': '3Blue1Brown',
5881 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
5882 'uploader_id': '@3blue1brown',
5883 'uploader_url': 'https://www.youtube.com/@3blue1brown',
5884 'uploader': '3Blue1Brown',
5885 'tags': ['Mathematics'],
5886 'channel_follower_count': int,
5887 'channel_is_verified': True,
5890 'note': 'playlists, singlepage',
5891 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
5892 'playlist_mincount': 4,
5894 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
5895 'title': 'ThirstForScience - Playlists',
5896 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
5897 'uploader': 'ThirstForScience',
5898 'uploader_url': 'https://www.youtube.com/@ThirstForScience',
5899 'uploader_id': '@ThirstForScience',
5900 'channel_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
5901 'channel_url': 'https://www.youtube.com/channel/UCAEtajcuhQ6an9WEzY9LEMQ',
5903 'channel': 'ThirstForScience',
5904 'channel_follower_count': int,
5907 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
5908 'only_matching': True,
5910 'note': 'basic, single video playlist',
5911 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
5913 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
5914 'title': 'youtube-dl public playlist',
5918 'modified_date': '20201130',
5919 'channel': 'Sergey M.',
5920 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
5921 'channel_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5922 'availability': 'public',
5923 'uploader': 'Sergey M.',
5924 'uploader_url': 'https://www.youtube.com/@sergeym.6173',
5925 'uploader_id': '@sergeym.6173',
5927 'playlist_count': 1,
5929 'note': 'empty playlist',
5930 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
5932 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
5933 'title': 'youtube-dl empty playlist',
5935 'channel': 'Sergey M.',
5937 'modified_date': '20230921',
5938 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
5939 'channel_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5940 'availability': 'unlisted',
5941 'uploader_url': 'https://www.youtube.com/@sergeym.6173',
5942 'uploader_id': '@sergeym.6173',
5943 'uploader': 'Sergey M.',
5945 'playlist_count': 0,
5948 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
5950 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5951 'title': 'lex will - Home',
5952 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5953 'uploader': 'lex will',
5954 'uploader_id': '@lexwill718',
5955 'channel': 'lex will',
5956 'tags': ['bible', 'history', 'prophesy'],
5957 'uploader_url': 'https://www.youtube.com/@lexwill718',
5958 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5959 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5960 'channel_follower_count': int,
5962 'playlist_mincount': 2,
5964 'note': 'Videos tab',
5965 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
5967 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5968 'title': 'lex will - Videos',
5969 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5970 'uploader': 'lex will',
5971 'uploader_id': '@lexwill718',
5972 'tags': ['bible', 'history', 'prophesy'],
5973 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5974 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5975 'uploader_url': 'https://www.youtube.com/@lexwill718',
5976 'channel': 'lex will',
5977 'channel_follower_count': int,
5979 'playlist_mincount': 975,
5981 'note': 'Videos tab, sorted by popular',
5982 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
5984 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5985 'title': 'lex will - Videos',
5986 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5987 'uploader': 'lex will',
5988 'uploader_id': '@lexwill718',
5989 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5990 'uploader_url': 'https://www.youtube.com/@lexwill718',
5991 'channel': 'lex will',
5992 'tags': ['bible', 'history', 'prophesy'],
5993 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5994 'channel_follower_count': int,
5996 'playlist_mincount': 199,
5998 'note': 'Playlists tab',
5999 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
6001 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6002 'title': 'lex will - Playlists',
6003 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
6004 'uploader': 'lex will',
6005 'uploader_id': '@lexwill718',
6006 'uploader_url': 'https://www.youtube.com/@lexwill718',
6007 'channel': 'lex will',
6008 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
6009 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6010 'tags': ['bible', 'history', 'prophesy'],
6011 'channel_follower_count': int,
6013 'playlist_mincount': 17,
6015 'note': 'Community tab',
6016 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
6018 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6019 'title': 'lex will - Community',
6020 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
6021 'channel': 'lex will',
6022 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
6023 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6024 'tags': ['bible', 'history', 'prophesy'],
6025 'channel_follower_count': int,
6026 'uploader_url': 'https://www.youtube.com/@lexwill718',
6027 'uploader_id': '@lexwill718',
6028 'uploader': 'lex will',
6030 'playlist_mincount': 18,
6032 'note': 'Channels tab',
6033 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
6035 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6036 'title': 'lex will - Channels',
6037 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
6038 'channel': 'lex will',
6039 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
6040 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6041 'tags': ['bible', 'history', 'prophesy'],
6042 'channel_follower_count': int,
6043 'uploader_url': 'https://www.youtube.com/@lexwill718',
6044 'uploader_id': '@lexwill718',
6045 'uploader': 'lex will',
6047 'playlist_mincount': 12,
6049 'note': 'Search tab',
6050 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
6051 'playlist_mincount': 40,
6053 'id': 'UCYO_jab_esuFRV4b17AJtAw',
6054 'title': '3Blue1Brown - Search - linear algebra',
6055 'description': 'md5:4d1da95432004b7ba840ebc895b6b4c9',
6056 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
6057 'tags': ['Mathematics'],
6058 'channel': '3Blue1Brown',
6059 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
6060 'channel_follower_count': int,
6061 'uploader_url': 'https://www.youtube.com/@3blue1brown',
6062 'uploader_id': '@3blue1brown',
6063 'uploader': '3Blue1Brown',
6064 'channel_is_verified': True,
6067 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
6068 'only_matching': True,
6070 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
6071 'only_matching': True,
6073 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
6074 'only_matching': True,
6076 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
6077 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
6079 'title': '29C3: Not my department',
6080 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
6081 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
6084 'modified_date': '20150605',
6085 'channel_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
6086 'channel_url': 'https://www.youtube.com/channel/UCEPzS1rYsrkqzSLNp76nrcg',
6087 'channel': 'Christiaan008',
6088 'availability': 'public',
6089 'uploader_id': '@ChRiStIaAn008',
6090 'uploader': 'Christiaan008',
6091 'uploader_url': 'https://www.youtube.com/@ChRiStIaAn008',
6093 'playlist_count': 96,
6095 'note': 'Large playlist',
6096 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
6098 'title': 'Uploads from Cauchemar',
6099 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
6100 'channel_url': 'https://www.youtube.com/channel/UCBABnxM4Ar9ten8Mdjj1j0Q',
6102 'modified_date': r
're:\d{8}',
6103 'channel': 'Cauchemar',
6106 'channel_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
6107 'availability': 'public',
6108 'uploader_id': '@Cauchemar89',
6109 'uploader': 'Cauchemar',
6110 'uploader_url': 'https://www.youtube.com/@Cauchemar89',
6112 'playlist_mincount': 1123,
6113 'expected_warnings': [r
'[Uu]navailable videos (are|will be) hidden'],
6115 'note': 'even larger playlist, 8832 videos',
6116 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
6117 'only_matching': True,
6119 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
6120 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
6122 'title': 'Uploads from Interstellar Movie',
6123 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
6126 'channel_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
6127 'channel_url': 'https://www.youtube.com/channel/UCXw-G3eDE9trcvY2sBMM_aA',
6128 'channel': 'Interstellar Movie',
6130 'modified_date': r
're:\d{8}',
6131 'availability': 'public',
6132 'uploader_id': '@InterstellarMovie',
6133 'uploader': 'Interstellar Movie',
6134 'uploader_url': 'https://www.youtube.com/@InterstellarMovie',
6136 'playlist_mincount': 21,
6138 'note': 'Playlist with "show unavailable videos" button',
6139 'url': 'https://www.youtube.com/playlist?list=UUTYLiWFZy8xtPwxFwX9rV7Q',
6141 'title': 'Uploads from Phim Siêu Nhân Nhật Bản',
6142 'id': 'UUTYLiWFZy8xtPwxFwX9rV7Q',
6144 'channel': 'Phim Siêu Nhân Nhật Bản',
6147 'channel_url': 'https://www.youtube.com/channel/UCTYLiWFZy8xtPwxFwX9rV7Q',
6148 'channel_id': 'UCTYLiWFZy8xtPwxFwX9rV7Q',
6149 'modified_date': r
're:\d{8}',
6150 'availability': 'public',
6151 'uploader_url': 'https://www.youtube.com/@phimsieunhannhatban',
6152 'uploader_id': '@phimsieunhannhatban',
6153 'uploader': 'Phim Siêu Nhân Nhật Bản',
6155 'playlist_mincount': 200,
6156 'expected_warnings': [r
'[Uu]navailable videos (are|will be) hidden'],
6158 'note': 'Playlist with unavailable videos in page 7',
6159 'url': 'https://www.youtube.com/playlist?list=UU8l9frL61Yl5KFOl87nIm2w',
6161 'title': 'Uploads from BlankTV',
6162 'id': 'UU8l9frL61Yl5KFOl87nIm2w',
6163 'channel': 'BlankTV',
6164 'channel_url': 'https://www.youtube.com/channel/UC8l9frL61Yl5KFOl87nIm2w',
6165 'channel_id': 'UC8l9frL61Yl5KFOl87nIm2w',
6168 'modified_date': r
're:\d{8}',
6170 'availability': 'public',
6171 'uploader_id': '@blanktv',
6172 'uploader': 'BlankTV',
6173 'uploader_url': 'https://www.youtube.com/@blanktv',
6175 'playlist_mincount': 1000,
6176 'expected_warnings': [r
'[Uu]navailable videos (are|will be) hidden'],
6178 'note': 'https://github.com/ytdl-org/youtube-dl/issues/21844',
6179 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
6181 'title': 'Data Analysis with Dr Mike Pound',
6182 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
6183 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
6186 'channel_id': 'UC9-y-6csu5WGm29I7JiwpnA',
6187 'channel_url': 'https://www.youtube.com/channel/UC9-y-6csu5WGm29I7JiwpnA',
6188 'channel': 'Computerphile',
6189 'availability': 'public',
6190 'modified_date': '20190712',
6191 'uploader_id': '@Computerphile',
6192 'uploader': 'Computerphile',
6193 'uploader_url': 'https://www.youtube.com/@Computerphile',
6195 'playlist_mincount': 11,
6197 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
6198 'only_matching': True,
6200 'note': 'Playlist URL that does not actually serve a playlist',
6201 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
6203 'id': 'FqZTN594JQw',
6205 'title': "Smiley's People 01 detective, Adventure Series, Action",
6206 'upload_date': '20150526',
6207 'license': 'Standard YouTube License',
6208 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
6209 'categories': ['People & Blogs'],
6215 'skip_download': True,
6217 'skip': 'This video is not available.',
6218 'add_ie': [YoutubeIE
.ie_key()],
6220 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
6221 'only_matching': True,
6223 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
6224 'only_matching': True,
6226 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
6228 'id': 'hGkQjiJLjWQ', # This will keep changing
6231 'upload_date': r
're:\d{8}',
6233 'categories': ['News & Politics'],
6236 'release_timestamp': int,
6237 'channel': 'Sky News',
6238 'channel_id': 'UCoMdktPbSTixAyNGwb-UYkQ',
6241 'thumbnail': r
're:https?://i\.ytimg\.com/vi/[^/]+/maxresdefault(?:_live)?\.jpg',
6242 'playable_in_embed': True,
6243 'release_date': r
're:\d+',
6244 'availability': 'public',
6245 'live_status': 'is_live',
6246 'channel_url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ',
6247 'channel_follower_count': int,
6248 'concurrent_view_count': int,
6249 'uploader_url': 'https://www.youtube.com/@SkyNews',
6250 'uploader_id': '@SkyNews',
6251 'uploader': 'Sky News',
6252 'channel_is_verified': True,
6255 'skip_download': True,
6257 'expected_warnings': ['Ignoring subtitle tracks found in '],
6259 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
6261 'id': 'a48o2S1cPoo',
6263 'title': 'The Young Turks - Live Main Show',
6264 'upload_date': '20150715',
6265 'license': 'Standard YouTube License',
6266 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
6267 'categories': ['News & Politics'],
6268 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
6272 'skip_download': True,
6274 'only_matching': True,
6276 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
6277 'only_matching': True,
6279 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
6280 'only_matching': True,
6282 'note': 'A channel that is not live. Should raise error',
6283 'url': 'https://www.youtube.com/user/numberphile/live',
6284 'only_matching': True,
6286 'url': 'https://www.youtube.com/feed/trending',
6287 'only_matching': True,
6289 'url': 'https://www.youtube.com/feed/library',
6290 'only_matching': True,
6292 'url': 'https://www.youtube.com/feed/history',
6293 'only_matching': True,
6295 'url': 'https://www.youtube.com/feed/subscriptions',
6296 'only_matching': True,
6298 'url': 'https://www.youtube.com/feed/watch_later',
6299 'only_matching': True,
6301 'note': 'Recommended - redirects to home page.',
6302 'url': 'https://www.youtube.com/feed/recommended',
6303 'only_matching': True,
6305 'note': 'inline playlist with not always working continuations',
6306 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
6307 'only_matching': True,
6309 'url': 'https://www.youtube.com/course',
6310 'only_matching': True,
6312 'url': 'https://www.youtube.com/zsecurity',
6313 'only_matching': True,
6315 'url': 'http://www.youtube.com/NASAgovVideo/videos',
6316 'only_matching': True,
6318 'url': 'https://www.youtube.com/TheYoungTurks/live',
6319 'only_matching': True,
6321 'url': 'https://www.youtube.com/hashtag/cctv9',
6324 'title': 'cctv9 - All',
6327 'playlist_mincount': 300, # not consistent but should be over 300
6329 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
6330 'only_matching': True,
6332 'note': 'Requires Premium: should request additional YTM-info webpage (and have format 141) for videos in playlist',
6333 'url': 'https://music.youtube.com/playlist?list=PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
6334 'only_matching': True,
6336 'note': '/browse/ should redirect to /channel/',
6337 'url': 'https://music.youtube.com/browse/UC1a8OFewdjuLq6KlF8M_8Ng',
6338 'only_matching': True,
6340 'note': 'VLPL, should redirect to playlist?list=PL...',
6341 'url': 'https://music.youtube.com/browse/VLPLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
6343 'id': 'PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
6344 'description': 'Providing you with copyright free / safe music for gaming, live streaming, studying and more!',
6345 'title': 'NCS : All Releases 💿',
6346 'channel_url': 'https://www.youtube.com/channel/UC_aEa8K-EOJ3D6gOs7HcyNg',
6347 'modified_date': r
're:\d{8}',
6349 'channel_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg',
6351 'channel': 'NoCopyrightSounds',
6352 'availability': 'public',
6353 'uploader_url': 'https://www.youtube.com/@NoCopyrightSounds',
6354 'uploader': 'NoCopyrightSounds',
6355 'uploader_id': '@NoCopyrightSounds',
6357 'playlist_mincount': 166,
6358 'expected_warnings': [r
'[Uu]navailable videos (are|will be) hidden', 'YouTube Music is not directly supported'],
6360 # TODO: fix 'unviewable' issue with this playlist when reloading with unavailable videos
6361 'note': 'Topic, should redirect to playlist?list=UU...',
6362 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
6364 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
6365 'title': 'Uploads from Royalty Free Music - Topic',
6367 'channel_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
6368 'channel': 'Royalty Free Music - Topic',
6370 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
6371 'modified_date': r
're:\d{8}',
6373 'availability': 'public',
6374 'uploader': 'Royalty Free Music - Topic',
6376 'playlist_mincount': 101,
6377 'expected_warnings': ['YouTube Music is not directly supported', r
'[Uu]navailable videos (are|will be) hidden'],
6379 # Destination channel with only a hidden self tab (tab id is UCtFRv9O2AHqOZjjynzrv-xg)
6380 # Treat as a general feed
6381 'url': 'https://www.youtube.com/channel/UCtFRv9O2AHqOZjjynzrv-xg',
6383 'id': 'UCtFRv9O2AHqOZjjynzrv-xg',
6384 'title': 'UCtFRv9O2AHqOZjjynzrv-xg',
6387 'playlist_mincount': 9,
6389 'note': 'Youtube music Album',
6390 'url': 'https://music.youtube.com/browse/MPREb_gTAcphH99wE',
6392 'id': 'OLAK5uy_l1m0thk3g31NmIIz_vMIbWtyv7eZixlH0',
6393 'title': 'Album - Royalty Free Music Library V2 (50 Songs)',
6397 'availability': 'unlisted',
6398 'modified_date': r
're:\d{8}',
6400 'playlist_count': 50,
6401 'expected_warnings': ['YouTube Music is not directly supported'],
6403 'note': 'unlisted single video playlist',
6404 'url': 'https://www.youtube.com/playlist?list=PLwL24UFy54GrB3s2KMMfjZscDi1x5Dajf',
6406 'id': 'PLwL24UFy54GrB3s2KMMfjZscDi1x5Dajf',
6407 'title': 'yt-dlp unlisted playlist test',
6408 'availability': 'unlisted',
6410 'modified_date': '20220418',
6411 'channel': 'colethedj',
6414 'channel_id': 'UC9zHu_mHU96r19o-wV5Qs1Q',
6415 'channel_url': 'https://www.youtube.com/channel/UC9zHu_mHU96r19o-wV5Qs1Q',
6416 'uploader_url': 'https://www.youtube.com/@colethedj1894',
6417 'uploader_id': '@colethedj1894',
6418 'uploader': 'colethedj',
6422 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
6423 'id': 'BaW_jenozKc',
6425 'ie_key': 'Youtube',
6427 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
6428 'channel_url': 'https://www.youtube.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
6430 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc',
6431 'channel': 'Philipp Hagemeister',
6432 'uploader_id': '@PhilippHagemeister',
6433 'uploader_url': 'https://www.youtube.com/@PhilippHagemeister',
6434 'uploader': 'Philipp Hagemeister',
6437 'playlist_count': 1,
6438 'params': {'extract_flat': True},
6440 'note': 'API Fallback: Recommended - redirects to home page. Requires visitorData',
6441 'url': 'https://www.youtube.com/feed/recommended',
6443 'id': 'recommended',
6444 'title': 'recommended',
6447 'playlist_mincount': 50,
6449 'skip_download': True,
6450 'extractor_args': {'youtubetab': {'skip': ['webpage']}},
6453 'note': 'API Fallback: /videos tab, sorted by oldest first',
6454 'url': 'https://www.youtube.com/user/theCodyReeder/videos?view=0&sort=da&flow=grid',
6456 'id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
6457 'title': 'Cody\'sLab - Videos',
6458 'description': 'md5:d083b7c2f0c67ee7a6c74c3e9b4243fa',
6459 'channel': 'Cody\'sLab',
6460 'channel_id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
6462 'channel_url': 'https://www.youtube.com/channel/UCu6mSoMNzHQiBIOCkHUa2Aw',
6463 'channel_follower_count': int,
6465 'playlist_mincount': 650,
6467 'skip_download': True,
6468 'extractor_args': {'youtubetab': {'skip': ['webpage']}},
6470 'skip': 'Query for sorting no longer works',
6472 'note': 'API Fallback: Topic, should redirect to playlist?list=UU...',
6473 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
6475 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
6476 'title': 'Uploads from Royalty Free Music - Topic',
6477 'modified_date': r
're:\d{8}',
6478 'channel_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
6480 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
6482 'channel': 'Royalty Free Music - Topic',
6484 'availability': 'public',
6485 'uploader': 'Royalty Free Music - Topic',
6487 'playlist_mincount': 101,
6489 'skip_download': True,
6490 'extractor_args': {'youtubetab': {'skip': ['webpage']}},
6492 'expected_warnings': ['YouTube Music is not directly supported', r
'[Uu]navailable videos (are|will be) hidden'],
6494 'note': 'non-standard redirect to regional channel',
6495 'url': 'https://www.youtube.com/channel/UCwVVpHQ2Cs9iGJfpdFngePQ',
6496 'only_matching': True,
6498 'note': 'collaborative playlist (uploader name in the form "by <uploader> and x other(s)")',
6499 'url': 'https://www.youtube.com/playlist?list=PLx-_-Kk4c89oOHEDQAojOXzEzemXxoqx6',
6501 'id': 'PLx-_-Kk4c89oOHEDQAojOXzEzemXxoqx6',
6502 'modified_date': '20220407',
6503 'channel_url': 'https://www.youtube.com/channel/UCKcqXmCcyqnhgpA5P0oHH_Q',
6505 'availability': 'unlisted',
6506 'channel_id': 'UCKcqXmCcyqnhgpA5P0oHH_Q',
6507 'channel': 'pukkandan',
6508 'description': 'Test for collaborative playlist',
6509 'title': 'yt-dlp test - collaborative playlist',
6511 'uploader_url': 'https://www.youtube.com/@pukkandan',
6512 'uploader_id': '@pukkandan',
6513 'uploader': 'pukkandan',
6515 'playlist_mincount': 2,
6517 'note': 'translated tab name',
6518 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/playlists',
6520 'id': 'UCiu-3thuViMebBjw_5nWYrA',
6522 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
6523 'description': 'test description',
6524 'title': 'cole-dlp-test-acc - 再生リスト',
6525 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
6526 'channel': 'cole-dlp-test-acc',
6527 'uploader_url': 'https://www.youtube.com/@coletdjnz',
6528 'uploader_id': '@coletdjnz',
6529 'uploader': 'cole-dlp-test-acc',
6531 'playlist_mincount': 1,
6532 'params': {'extractor_args': {'youtube': {'lang': ['ja']}}},
6533 'expected_warnings': ['Preferring "ja"'],
6535 # XXX: this should really check flat playlist entries, but the test suite doesn't support that
6536 'note': 'preferred lang set with playlist with translated video titles',
6537 'url': 'https://www.youtube.com/playlist?list=PLt5yu3-wZAlQAaPZ5Z-rJoTdbT-45Q7c0',
6539 'id': 'PLt5yu3-wZAlQAaPZ5Z-rJoTdbT-45Q7c0',
6542 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
6543 'channel': 'cole-dlp-test-acc',
6544 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
6545 'description': 'test',
6546 'title': 'dlp test playlist',
6547 'availability': 'public',
6548 'uploader_url': 'https://www.youtube.com/@coletdjnz',
6549 'uploader_id': '@coletdjnz',
6550 'uploader': 'cole-dlp-test-acc',
6552 'playlist_mincount': 1,
6553 'params': {'extractor_args': {'youtube': {'lang': ['ja']}}},
6554 'expected_warnings': ['Preferring "ja"'],
6556 # shorts audio pivot for 2GtVksBMYFM.
6557 'url': 'https://www.youtube.com/feed/sfv_audio_pivot?bp=8gUrCikSJwoLMkd0VmtzQk1ZRk0SCzJHdFZrc0JNWUZNGgsyR3RWa3NCTVlGTQ==',
6559 'id': 'sfv_audio_pivot',
6560 'title': 'sfv_audio_pivot',
6563 'playlist_mincount': 50,
6566 # Channel with a real live tab (not to be mistaken with streams tab)
6567 # Do not treat like it should redirect to live stream
6568 'url': 'https://www.youtube.com/channel/UCEH7P7kyJIkS_gJf93VYbmg/live',
6570 'id': 'UCEH7P7kyJIkS_gJf93VYbmg',
6571 'title': 'UCEH7P7kyJIkS_gJf93VYbmg - Live',
6574 'playlist_mincount': 20,
6576 # Tab name is not the same as tab id
6577 'url': 'https://www.youtube.com/channel/UCQvWX73GQygcwXOTSf_VDVg/letsplay',
6579 'id': 'UCQvWX73GQygcwXOTSf_VDVg',
6580 'title': 'UCQvWX73GQygcwXOTSf_VDVg - Let\'s play',
6583 'playlist_mincount': 8,
6585 # Home tab id is literally home. Not to get mistaken with featured
6586 'url': 'https://www.youtube.com/channel/UCQvWX73GQygcwXOTSf_VDVg/home',
6588 'id': 'UCQvWX73GQygcwXOTSf_VDVg',
6589 'title': 'UCQvWX73GQygcwXOTSf_VDVg - Home',
6592 'playlist_mincount': 8,
6594 # Should get three playlists for videos, shorts and streams tabs
6595 'url': 'https://www.youtube.com/channel/UCK9V2B22uJYu3N7eR_BT9QA',
6597 'id': 'UCK9V2B22uJYu3N7eR_BT9QA',
6598 'title': 'Polka Ch. 尾丸ポルカ',
6599 'channel_follower_count': int,
6600 'channel_id': 'UCK9V2B22uJYu3N7eR_BT9QA',
6601 'channel_url': 'https://www.youtube.com/channel/UCK9V2B22uJYu3N7eR_BT9QA',
6602 'description': 'md5:49809d8bf9da539bc48ed5d1f83c33f2',
6603 'channel': 'Polka Ch. 尾丸ポルカ',
6605 'uploader_url': 'https://www.youtube.com/@OmaruPolka',
6606 'uploader': 'Polka Ch. 尾丸ポルカ',
6607 'uploader_id': '@OmaruPolka',
6608 'channel_is_verified': True,
6610 'playlist_count': 3,
6612 # Shorts tab with channel with handle
6613 # TODO: fix channel description
6614 'url': 'https://www.youtube.com/@NotJustBikes/shorts',
6616 'id': 'UC0intLFzLaudFG-xAvUEO-A',
6617 'title': 'Not Just Bikes - Shorts',
6619 'channel_url': 'https://www.youtube.com/channel/UC0intLFzLaudFG-xAvUEO-A',
6620 'description': 'md5:5e82545b3a041345927a92d0585df247',
6621 'channel_follower_count': int,
6622 'channel_id': 'UC0intLFzLaudFG-xAvUEO-A',
6623 'channel': 'Not Just Bikes',
6624 'uploader_url': 'https://www.youtube.com/@NotJustBikes',
6625 'uploader': 'Not Just Bikes',
6626 'uploader_id': '@NotJustBikes',
6627 'channel_is_verified': True,
6629 'playlist_mincount': 10,
6632 'url': 'https://www.youtube.com/channel/UC3eYAvjCVwNHgkaGbXX3sig/streams',
6634 'id': 'UC3eYAvjCVwNHgkaGbXX3sig',
6635 'title': '中村悠一 - Live',
6637 'channel_id': 'UC3eYAvjCVwNHgkaGbXX3sig',
6638 'channel_url': 'https://www.youtube.com/channel/UC3eYAvjCVwNHgkaGbXX3sig',
6640 'channel_follower_count': int,
6641 'description': 'md5:e744f6c93dafa7a03c0c6deecb157300',
6642 'uploader_url': 'https://www.youtube.com/@Yuichi-Nakamura',
6643 'uploader_id': '@Yuichi-Nakamura',
6646 'playlist_mincount': 60,
6648 # Channel with no uploads and hence no videos, streams, shorts tabs or uploads playlist. This should fail.
6649 # See test_youtube_lists
6650 'url': 'https://www.youtube.com/channel/UC2yXPzFejc422buOIzn_0CA',
6651 'only_matching': True,
6653 # No uploads and no UCID given. Should fail with no uploads error
6654 # See test_youtube_lists
6655 'url': 'https://www.youtube.com/news',
6656 'only_matching': True,
6658 # No videos tab but has a shorts tab
6659 'url': 'https://www.youtube.com/c/TKFShorts',
6661 'id': 'UCgJ5_1F6yJhYLnyMszUdmUg',
6662 'title': 'Shorts Break - Shorts',
6664 'channel_id': 'UCgJ5_1F6yJhYLnyMszUdmUg',
6665 'channel': 'Shorts Break',
6666 'description': 'md5:6de33c5e7ba686e5f3efd4e19c7ef499',
6667 'channel_follower_count': int,
6668 'channel_url': 'https://www.youtube.com/channel/UCgJ5_1F6yJhYLnyMszUdmUg',
6669 'uploader_url': 'https://www.youtube.com/@ShortsBreak_Official',
6670 'uploader': 'Shorts Break',
6671 'uploader_id': '@ShortsBreak_Official',
6673 'playlist_mincount': 30,
6675 # Trending Now Tab. tab id is empty
6676 'url': 'https://www.youtube.com/feed/trending',
6679 'title': 'trending - Now',
6682 'playlist_mincount': 30,
6684 # Trending Gaming Tab. tab id is empty
6685 'url': 'https://www.youtube.com/feed/trending?bp=4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D',
6688 'title': 'trending - Gaming',
6691 'playlist_mincount': 30,
6693 # Shorts url result in shorts tab
6694 # TODO: Fix channel id extraction
6695 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/shorts',
6697 'id': 'UCiu-3thuViMebBjw_5nWYrA',
6698 'title': 'cole-dlp-test-acc - Shorts',
6699 'channel': 'cole-dlp-test-acc',
6700 'description': 'test description',
6701 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
6702 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
6704 'uploader_url': 'https://www.youtube.com/@coletdjnz',
6705 'uploader_id': '@coletdjnz',
6706 'uploader': 'cole-dlp-test-acc',
6710 # Channel data is not currently available for short renderers (as of 2023-03-01)
6712 'ie_key': 'Youtube',
6713 'url': 'https://www.youtube.com/shorts/sSM9J5YH_60',
6714 'id': 'sSM9J5YH_60',
6715 'title': 'SHORT short',
6720 'params': {'extract_flat': True},
6722 # Live video status should be extracted
6723 'url': 'https://www.youtube.com/channel/UCQvWX73GQygcwXOTSf_VDVg/live',
6725 'id': 'UCQvWX73GQygcwXOTSf_VDVg',
6726 'title': 'UCQvWX73GQygcwXOTSf_VDVg - Live', # TODO: should be Minecraft - Live or Minecraft - Topic - Live
6732 'ie_key': 'Youtube',
6733 'url': 'startswith:https://www.youtube.com/watch?v=',
6736 'live_status': 'is_live',
6739 'concurrent_view_count': int,
6742 'uploader_url': str,
6744 'channel_is_verified': bool, # this will keep changing
6747 'params': {'extract_flat': True, 'playlist_items': '1'},
6748 'playlist_mincount': 1,
6750 # Channel renderer metadata. Contains number of videos on the channel
6751 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/channels',
6753 'id': 'UCiu-3thuViMebBjw_5nWYrA',
6754 'title': 'cole-dlp-test-acc - Channels',
6755 'channel': 'cole-dlp-test-acc',
6756 'description': 'test description',
6757 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
6758 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
6760 'uploader_url': 'https://www.youtube.com/@coletdjnz',
6761 'uploader_id': '@coletdjnz',
6762 'uploader': 'cole-dlp-test-acc',
6767 'ie_key': 'YoutubeTab',
6768 'url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
6769 'id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
6770 'channel_id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
6771 'title': 'PewDiePie',
6772 'channel': 'PewDiePie',
6773 'channel_url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
6775 'channel_follower_count': int,
6776 'playlist_count': int,
6777 'uploader': 'PewDiePie',
6778 'uploader_url': 'https://www.youtube.com/@PewDiePie',
6779 'uploader_id': '@PewDiePie',
6780 'channel_is_verified': True,
6783 'params': {'extract_flat': True},
6785 'url': 'https://www.youtube.com/@3blue1brown/about',
6787 'id': '@3blue1brown',
6788 'tags': ['Mathematics'],
6789 'title': '3Blue1Brown',
6790 'channel_follower_count': int,
6791 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
6792 'channel': '3Blue1Brown',
6793 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
6794 'description': 'md5:4d1da95432004b7ba840ebc895b6b4c9',
6795 'uploader_url': 'https://www.youtube.com/@3blue1brown',
6796 'uploader_id': '@3blue1brown',
6797 'uploader': '3Blue1Brown',
6798 'channel_is_verified': True,
6800 'playlist_count': 0,
6802 # Podcasts tab, with rich entry lockupViewModel
6803 'url': 'https://www.youtube.com/@99percentinvisiblepodcast/podcasts',
6805 'id': 'UCVMF2HD4ZgC0QHpU9Yq5Xrw',
6806 'channel_id': 'UCVMF2HD4ZgC0QHpU9Yq5Xrw',
6807 'uploader_url': 'https://www.youtube.com/@99percentinvisiblepodcast',
6808 'description': 'md5:3a0ed38f1ad42a68ef0428c04a15695c',
6809 'title': '99% Invisible - Podcasts',
6810 'uploader': '99% Invisible',
6811 'channel_follower_count': int,
6812 'channel_url': 'https://www.youtube.com/channel/UCVMF2HD4ZgC0QHpU9Yq5Xrw',
6814 'channel': '99% Invisible',
6815 'uploader_id': '@99percentinvisiblepodcast',
6817 'playlist_count': 5,
6819 # Releases tab, with rich entry playlistRenderers (same as Podcasts tab)
6820 'url': 'https://www.youtube.com/@AHimitsu/releases',
6822 'id': 'UCgFwu-j5-xNJml2FtTrrB3A',
6823 'channel': 'A Himitsu',
6824 'uploader_url': 'https://www.youtube.com/@AHimitsu',
6825 'title': 'A Himitsu - Releases',
6826 'uploader_id': '@AHimitsu',
6827 'uploader': 'A Himitsu',
6828 'channel_id': 'UCgFwu-j5-xNJml2FtTrrB3A',
6830 'description': 'I make music',
6831 'channel_url': 'https://www.youtube.com/channel/UCgFwu-j5-xNJml2FtTrrB3A',
6832 'channel_follower_count': int,
6833 'channel_is_verified': True,
6835 'playlist_mincount': 10,
6837 # Playlist with only shorts, shown as reel renderers
6838 # FIXME: future: YouTube currently doesn't give continuation for this,
6840 'url': 'https://www.youtube.com/playlist?list=UUxqPAgubo4coVn9Lx1FuKcg',
6842 'id': 'UUxqPAgubo4coVn9Lx1FuKcg',
6843 'channel_url': 'https://www.youtube.com/channel/UCxqPAgubo4coVn9Lx1FuKcg',
6845 'uploader_id': '@BangyShorts',
6847 'uploader_url': 'https://www.youtube.com/@BangyShorts',
6848 'channel_id': 'UCxqPAgubo4coVn9Lx1FuKcg',
6849 'channel': 'Bangy Shorts',
6850 'uploader': 'Bangy Shorts',
6852 'availability': 'public',
6853 'modified_date': r
're:\d{8}',
6854 'title': 'Uploads from Bangy Shorts',
6856 'playlist_mincount': 100,
6857 'expected_warnings': [r
'[Uu]navailable videos (are|will be) hidden'],
6859 'note': 'Tags containing spaces',
6860 'url': 'https://www.youtube.com/channel/UC7_YxT-KID8kRbqZo7MyscQ',
6861 'playlist_count': 3,
6863 'id': 'UC7_YxT-KID8kRbqZo7MyscQ',
6864 'channel': 'Markiplier',
6865 'channel_id': 'UC7_YxT-KID8kRbqZo7MyscQ',
6866 'title': 'Markiplier',
6867 'channel_follower_count': int,
6868 'description': 'md5:0c010910558658824402809750dc5d97',
6869 'uploader_id': '@markiplier',
6870 'uploader_url': 'https://www.youtube.com/@markiplier',
6871 'uploader': 'Markiplier',
6872 'channel_url': 'https://www.youtube.com/channel/UC7_YxT-KID8kRbqZo7MyscQ',
6873 'channel_is_verified': True,
6874 'tags': ['markiplier', 'comedy', 'gaming', 'funny videos', 'funny moments',
6875 'sketch comedy', 'laughing', 'lets play', 'challenge videos', 'hilarious',
6876 'challenges', 'sketches', 'scary games', 'funny games', 'rage games',
6882 def suitable(cls
, url
):
6883 return False if YoutubeIE
.suitable(url
) else super().suitable(url
)
6885 _URL_RE
= re
.compile(rf
'(?P<pre>{_VALID_URL})(?(not_channel)|(?P<tab>/[^?#/]+))?(?P<post>.*)$')
6887 def _get_url_mobj(self
, url
):
6888 mobj
= self
._URL
_RE
.match(url
).groupdict()
6889 mobj
.update((k
, '') for k
, v
in mobj
.items() if v
is None)
6892 def _extract_tab_id_and_name(self
, tab
, base_url
='https://www.youtube.com'):
6893 tab_name
= (tab
.get('title') or '').lower()
6894 tab_url
= urljoin(base_url
, traverse_obj(
6895 tab
, ('endpoint', 'commandMetadata', 'webCommandMetadata', 'url')))
6897 tab_id
= ((tab_url
and self
._get
_url
_mobj
(tab_url
)['tab'][1:])
6898 or traverse_obj(tab
, 'tabIdentifier', expected_type
=str))
6901 'TAB_ID_SPONSORSHIPS': 'membership',
6902 }.get(tab_id
, tab_id
), tab_name
6904 # Fallback to tab name if we cannot get the tab id.
6905 # XXX: should we strip non-ascii letters? e.g. in case of 'let's play' tab example on special gaming channel
6906 # Note that in the case of translated tab name this may result in an empty string, which we don't want.
6908 self
.write_debug(f
'Falling back to selected tab name: {tab_name}')
6912 }.get(tab_name
, tab_name
), tab_name
6914 def _has_tab(self
, tabs
, tab_id
):
6915 return any(self
._extract
_tab
_id
_and
_name
(tab
)[0] == tab_id
for tab
in tabs
)
6917 def _empty_playlist(self
, item_id
, data
):
6918 return self
.playlist_result([], item_id
, **self
._extract
_metadata
_from
_tabs
(item_id
, data
))
6920 @YoutubeTabBaseInfoExtractor.passthrough_smuggled_data
6921 def _real_extract(self
, url
, smuggled_data
):
6922 item_id
= self
._match
_id
(url
)
6923 url
= urllib
.parse
.urlunparse(
6924 urllib
.parse
.urlparse(url
)._replace
(netloc
='www.youtube.com'))
6925 compat_opts
= self
.get_param('compat_opts', [])
6927 mobj
= self
._get
_url
_mobj
(url
)
6928 pre
, tab
, post
, is_channel
= mobj
['pre'], mobj
['tab'], mobj
['post'], not mobj
['not_channel']
6929 if is_channel
and smuggled_data
.get('is_music_url'):
6930 if item_id
[:2] == 'VL': # Youtube music VL channels have an equivalent playlist
6931 return self
.url_result(
6932 f
'https://music.youtube.com/playlist?list={item_id[2:]}', YoutubeTabIE
, item_id
[2:])
6933 elif item_id
[:2] == 'MP': # Resolve albums (/[channel/browse]/MP...) to their equivalent playlist
6934 mdata
= self
._extract
_tab
_endpoint
(
6935 f
'https://music.youtube.com/channel/{item_id}', item_id
, default_client
='web_music')
6936 murl
= traverse_obj(mdata
, ('microformat', 'microformatDataRenderer', 'urlCanonical'),
6937 get_all
=False, expected_type
=str)
6939 raise ExtractorError('Failed to resolve album to playlist')
6940 return self
.url_result(murl
, YoutubeTabIE
)
6941 elif mobj
['channel_type'] == 'browse': # Youtube music /browse/ should be changed to /channel/
6942 return self
.url_result(
6943 f
'https://music.youtube.com/channel/{item_id}{tab}{post}', YoutubeTabIE
, item_id
)
6945 original_tab_id
, display_id
= tab
[1:], f
'{item_id}{tab}'
6946 if is_channel
and not tab
and 'no-youtube-channel-redirect' not in compat_opts
:
6947 url
= f
'{pre}/videos{post}'
6948 if smuggled_data
.get('is_music_url'):
6949 self
.report_warning(f
'YouTube Music is not directly supported. Redirecting to {url}')
6951 # Handle both video/playlist URLs
6953 video_id
, playlist_id
= (traverse_obj(qs
, (key
, 0)) for key
in ('v', 'list'))
6954 if not video_id
and mobj
['not_channel'].startswith('watch'):
6956 # If there is neither video or playlist ids, youtube redirects to home page, which is undesirable
6957 raise ExtractorError('A video URL was given without video ID', expected
=True)
6958 # Common mistake: https://www.youtube.com/watch?list=playlist_id
6959 self
.report_warning(f
'A video URL was given without video ID. Trying to download playlist {playlist_id}')
6960 return self
.url_result(
6961 f
'https://www.youtube.com/playlist?list={playlist_id}', YoutubeTabIE
, playlist_id
)
6963 if not self
._yes
_playlist
(playlist_id
, video_id
):
6964 return self
.url_result(
6965 f
'https://www.youtube.com/watch?v={video_id}', YoutubeIE
, video_id
)
6967 data
, ytcfg
= self
._extract
_data
(url
, display_id
)
6969 # YouTube may provide a non-standard redirect to the regional channel
6970 # See: https://github.com/yt-dlp/yt-dlp/issues/2694
6971 # https://support.google.com/youtube/answer/2976814#zippy=,conditional-redirects
6972 redirect_url
= traverse_obj(
6973 data
, ('onResponseReceivedActions', ..., 'navigateAction', 'endpoint', 'commandMetadata', 'webCommandMetadata', 'url'), get_all
=False)
6974 if redirect_url
and 'no-youtube-channel-redirect' not in compat_opts
:
6975 redirect_url
= ''.join((urljoin('https://www.youtube.com', redirect_url
), tab
, post
))
6976 self
.to_screen(f
'This playlist is likely not available in your region. Following conditional redirect to {redirect_url}')
6977 return self
.url_result(redirect_url
, YoutubeTabIE
)
6979 tabs
, extra_tabs
= self
._extract
_tab
_renderers
(data
), []
6980 if is_channel
and tabs
and 'no-youtube-channel-redirect' not in compat_opts
:
6981 selected_tab
= self
._extract
_selected
_tab
(tabs
)
6982 selected_tab_id
, selected_tab_name
= self
._extract
_tab
_id
_and
_name
(selected_tab
, url
) # NB: Name may be translated
6983 self
.write_debug(f
'Selected tab: {selected_tab_id!r} ({selected_tab_name}), Requested tab: {original_tab_id!r}')
6985 # /about is no longer a tab
6986 if original_tab_id
== 'about':
6987 return self
._empty
_playlist
(item_id
, data
)
6989 if not original_tab_id
and selected_tab_name
:
6990 self
.to_screen('Downloading all uploads of the channel. '
6991 'To download only the videos in a specific tab, pass the tab\'s URL')
6992 if self
._has
_tab
(tabs
, 'streams'):
6993 extra_tabs
.append(''.join((pre
, '/streams', post
)))
6994 if self
._has
_tab
(tabs
, 'shorts'):
6995 extra_tabs
.append(''.join((pre
, '/shorts', post
)))
6996 # XXX: Members-only tab should also be extracted
6998 if not extra_tabs
and selected_tab_id
!= 'videos':
6999 # Channel does not have streams, shorts or videos tabs
7000 if item_id
[:2] != 'UC':
7001 return self
._empty
_playlist
(item_id
, data
)
7003 # Topic channels don't have /videos. Use the equivalent playlist instead
7004 pl_id
= f
'UU{item_id[2:]}'
7005 pl_url
= f
'https://www.youtube.com/playlist?list={pl_id}'
7007 data
, ytcfg
= self
._extract
_data
(pl_url
, pl_id
, ytcfg
=ytcfg
, fatal
=True, webpage_fatal
=True)
7008 except ExtractorError
:
7009 return self
._empty
_playlist
(item_id
, data
)
7011 item_id
, url
= pl_id
, pl_url
7013 f
'The channel does not have a videos, shorts, or live tab. Redirecting to playlist {pl_id} instead')
7015 elif extra_tabs
and selected_tab_id
!= 'videos':
7016 # When there are shorts/live tabs but not videos tab
7017 url
, data
= f
'{pre}{post}', None
7019 elif (original_tab_id
or 'videos') != selected_tab_id
:
7020 if original_tab_id
== 'live':
7021 # Live tab should have redirected to the video
7022 # Except in the case the channel has an actual live tab
7023 # Example: https://www.youtube.com/channel/UCEH7P7kyJIkS_gJf93VYbmg/live
7024 raise UserNotLive(video_id
=item_id
)
7025 elif selected_tab_name
:
7026 raise ExtractorError(f
'This channel does not have a {original_tab_id} tab', expected
=True)
7028 # For channels such as https://www.youtube.com/channel/UCtFRv9O2AHqOZjjynzrv-xg
7029 url
= f
'{pre}{post}'
7031 # YouTube sometimes provides a button to reload playlist with unavailable videos.
7032 if 'no-youtube-unavailable-videos' not in compat_opts
:
7033 data
= self
._reload
_with
_unavailable
_videos
(display_id
, data
, ytcfg
) or data
7034 self
._extract
_and
_report
_alerts
(data
, only_once
=True)
7036 tabs
, entries
= self
._extract
_tab
_renderers
(data
), []
7038 entries
= [self
._extract
_from
_tabs
(item_id
, ytcfg
, data
, tabs
)]
7040 'extractor_key': YoutubeTabIE
.ie_key(),
7041 'extractor': YoutubeTabIE
.IE_NAME
,
7044 if self
.get_param('playlist_items') == '0':
7045 entries
.extend(self
.url_result(u
, YoutubeTabIE
) for u
in extra_tabs
)
7046 else: # Users expect to get all `video_id`s even with `--flat-playlist`. So don't return `url_result`
7047 entries
.extend(map(self
._real
_extract
, extra_tabs
))
7049 if len(entries
) == 1:
7052 metadata
= self
._extract
_metadata
_from
_tabs
(item_id
, data
)
7053 uploads_url
= 'the Uploads (UU) playlist URL'
7054 if try_get(metadata
, lambda x
: x
['channel_id'].startswith('UC')):
7055 uploads_url
= f
'https://www.youtube.com/playlist?list=UU{metadata["channel_id"][2:]}'
7057 'Downloading as multiple playlists, separated by tabs. '
7058 f
'To download as a single playlist instead, pass {uploads_url}')
7059 return self
.playlist_result(entries
, item_id
, **metadata
)
7062 playlist
= traverse_obj(
7063 data
, ('contents', 'twoColumnWatchNextResults', 'playlist', 'playlist'), expected_type
=dict)
7065 return self
._extract
_from
_playlist
(item_id
, url
, data
, playlist
, ytcfg
)
7067 video_id
= traverse_obj(
7068 data
, ('currentVideoEndpoint', 'watchEndpoint', 'videoId'), expected_type
=str) or video_id
7070 if tab
!= '/live': # live tab is expected to redirect to video
7071 self
.report_warning(f
'Unable to recognize playlist. Downloading just video {video_id}')
7072 return self
.url_result(f
'https://www.youtube.com/watch?v={video_id}', YoutubeIE
, video_id
)
7074 raise ExtractorError('Unable to recognize tab page')
7077 class YoutubePlaylistIE(YoutubeBaseInfoExtractor
):
7078 IE_DESC
= 'YouTube playlists'
7079 _VALID_URL
= r
'''(?x)(?:
7084 youtube(?:kids)?\.com|
7089 (?P<id>{playlist_id})
7091 playlist_id
=YoutubeBaseInfoExtractor
._PLAYLIST
_ID
_RE
,
7092 invidious
='|'.join(YoutubeBaseInfoExtractor
._INVIDIOUS
_SITES
),
7094 IE_NAME
= 'youtube:playlist'
7096 'note': 'issue #673',
7097 'url': 'PLBB231211A4F62143',
7099 'title': '[OLD]Team Fortress 2 (Class-based LP)',
7100 'id': 'PLBB231211A4F62143',
7101 'uploader': 'Wickman',
7102 'uploader_id': '@WickmanVT',
7103 'description': 'md5:8fa6f52abb47a9552002fa3ddfc57fc2',
7105 'uploader_url': 'https://www.youtube.com/@WickmanVT',
7106 'modified_date': r
're:\d{8}',
7107 'channel_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
7108 'channel': 'Wickman',
7110 'channel_url': 'https://www.youtube.com/channel/UCKSpbfbl5kRQpTdL7kMc-1Q',
7111 'availability': 'public',
7113 'playlist_mincount': 29,
7115 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
7117 'title': 'YDL_safe_search',
7118 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
7120 'playlist_count': 2,
7121 'skip': 'This playlist is private',
7124 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
7125 'playlist_count': 4,
7128 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
7129 'uploader': 'milan',
7130 'uploader_id': '@milan5503',
7132 'channel_url': 'https://www.youtube.com/channel/UCEI1-PVPcYXjB73Hfelbmaw',
7134 'modified_date': '20140919',
7137 'channel_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
7138 'uploader_url': 'https://www.youtube.com/@milan5503',
7139 'availability': 'public',
7141 'expected_warnings': [r
'[Uu]navailable videos? (is|are|will be) hidden', 'Retrying', 'Giving up'],
7143 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
7144 'playlist_mincount': 455,
7146 'title': '2018 Chinese New Singles (11/6 updated)',
7147 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
7149 'uploader_id': '@music_king',
7150 'description': 'md5:da521864744d60a198e3a88af4db0d9d',
7153 'channel_url': 'https://www.youtube.com/channel/UC21nz3_MesPLqtDqwdvnoxA',
7155 'uploader_url': 'https://www.youtube.com/@music_king',
7156 'channel_id': 'UC21nz3_MesPLqtDqwdvnoxA',
7157 'modified_date': r
're:\d{8}',
7158 'availability': 'public',
7160 'expected_warnings': [r
'[Uu]navailable videos (are|will be) hidden'],
7162 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
7163 'only_matching': True,
7165 # music album playlist
7166 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
7167 'only_matching': True,
7171 def suitable(cls
, url
):
7172 if YoutubeTabIE
.suitable(url
):
7174 from ..utils
import parse_qs
7176 if qs
.get('v', [None])[0]:
7178 return super().suitable(url
)
7180 def _real_extract(self
, url
):
7181 playlist_id
= self
._match
_id
(url
)
7182 is_music_url
= YoutubeBaseInfoExtractor
.is_music_url(url
)
7183 url
= update_url_query(
7184 'https://www.youtube.com/playlist',
7185 parse_qs(url
) or {'list': playlist_id
})
7187 url
= smuggle_url(url
, {'is_music_url': True})
7188 return self
.url_result(url
, ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
)
7191 class YoutubeYtBeIE(YoutubeBaseInfoExtractor
):
7192 IE_DESC
= 'youtu.be'
7193 _VALID_URL
= rf
'https?://youtu\.be/(?P<id>[0-9A-Za-z_-]{{11}})/*?.*?\blist=(?P<playlist_id>{YoutubeBaseInfoExtractor._PLAYLIST_ID_RE})'
7195 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
7197 'id': 'yeWKywCrFtk',
7199 'title': 'Small Scale Baler and Braiding Rugs',
7200 'uploader': 'Backus-Page House Museum',
7201 'uploader_id': '@backuspagemuseum',
7202 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/@backuspagemuseum',
7203 'upload_date': '20161008',
7204 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
7205 'categories': ['Nonprofits & Activism'],
7209 'playable_in_embed': True,
7210 'thumbnail': r
're:^https?://.*\.webp',
7211 'channel': 'Backus-Page House Museum',
7212 'channel_id': 'UCEfMCQ9bs3tjvjy1s451zaw',
7213 'live_status': 'not_live',
7215 'channel_url': 'https://www.youtube.com/channel/UCEfMCQ9bs3tjvjy1s451zaw',
7216 'availability': 'public',
7218 'comment_count': int,
7219 'channel_follower_count': int,
7223 'skip_download': True,
7226 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
7227 'only_matching': True,
7230 def _real_extract(self
, url
):
7231 mobj
= self
._match
_valid
_url
(url
)
7232 video_id
= mobj
.group('id')
7233 playlist_id
= mobj
.group('playlist_id')
7234 return self
.url_result(
7235 update_url_query('https://www.youtube.com/watch', {
7237 'list': playlist_id
,
7238 'feature': 'youtu.be',
7239 }), ie
=YoutubeTabIE
.ie_key(), video_id
=playlist_id
)
7242 class YoutubeLivestreamEmbedIE(YoutubeBaseInfoExtractor
):
7243 IE_DESC
= 'YouTube livestream embeds'
7244 _VALID_URL
= r
'https?://(?:\w+\.)?youtube\.com/embed/live_stream/?\?(?:[^#]+&)?channel=(?P<id>[^&#]+)'
7246 'url': 'https://www.youtube.com/embed/live_stream?channel=UC2_KI6RB__jGdlnK6dvFEZA',
7247 'only_matching': True,
7250 def _real_extract(self
, url
):
7251 channel_id
= self
._match
_id
(url
)
7252 return self
.url_result(
7253 f
'https://www.youtube.com/channel/{channel_id}/live',
7254 ie
=YoutubeTabIE
.ie_key(), video_id
=channel_id
)
7257 class YoutubeYtUserIE(YoutubeBaseInfoExtractor
):
7258 IE_DESC
= 'YouTube user videos; "ytuser:" prefix'
7259 IE_NAME
= 'youtube:user'
7260 _VALID_URL
= r
'ytuser:(?P<id>.+)'
7262 'url': 'ytuser:phihag',
7263 'only_matching': True,
7266 def _real_extract(self
, url
):
7267 user_id
= self
._match
_id
(url
)
7268 return self
.url_result(f
'https://www.youtube.com/user/{user_id}', YoutubeTabIE
, user_id
)
7271 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor
):
7272 IE_NAME
= 'youtube:favorites'
7273 IE_DESC
= 'YouTube liked videos; ":ytfav" keyword (requires cookies)'
7274 _VALID_URL
= r
':ytfav(?:ou?rite)?s?'
7275 _LOGIN_REQUIRED
= True
7278 'only_matching': True,
7280 'url': ':ytfavorites',
7281 'only_matching': True,
7284 def _real_extract(self
, url
):
7285 return self
.url_result(
7286 'https://www.youtube.com/playlist?list=LL',
7287 ie
=YoutubeTabIE
.ie_key())
7290 class YoutubeNotificationsIE(YoutubeTabBaseInfoExtractor
):
7291 IE_NAME
= 'youtube:notif'
7292 IE_DESC
= 'YouTube notifications; ":ytnotif" keyword (requires cookies)'
7293 _VALID_URL
= r
':ytnotif(?:ication)?s?'
7294 _LOGIN_REQUIRED
= True
7297 'only_matching': True,
7299 'url': ':ytnotifications',
7300 'only_matching': True,
7303 def _extract_notification_menu(self
, response
, continuation_list
):
7304 notification_list
= traverse_obj(
7306 ('actions', 0, 'openPopupAction', 'popup', 'multiPageMenuRenderer', 'sections', 0, 'multiPageMenuNotificationSectionRenderer', 'items'),
7307 ('actions', 0, 'appendContinuationItemsAction', 'continuationItems'),
7308 expected_type
=list) or []
7309 continuation_list
[0] = None
7310 for item
in notification_list
:
7311 entry
= self
._extract
_notification
_renderer
(item
.get('notificationRenderer'))
7314 continuation
= item
.get('continuationItemRenderer')
7316 continuation_list
[0] = continuation
7318 def _extract_notification_renderer(self
, notification
):
7319 video_id
= traverse_obj(
7320 notification
, ('navigationEndpoint', 'watchEndpoint', 'videoId'), expected_type
=str)
7321 url
= f
'https://www.youtube.com/watch?v={video_id}'
7324 browse_ep
= traverse_obj(
7325 notification
, ('navigationEndpoint', 'browseEndpoint'), expected_type
=dict)
7326 channel_id
= self
.ucid_or_none(traverse_obj(browse_ep
, 'browseId', expected_type
=str))
7327 post_id
= self
._search
_regex
(
7328 r
'/post/(.+)', traverse_obj(browse_ep
, 'canonicalBaseUrl', expected_type
=str),
7329 'post id', default
=None)
7330 if not channel_id
or not post_id
:
7332 # The direct /post url redirects to this in the browser
7333 url
= f
'https://www.youtube.com/channel/{channel_id}/community?lb={post_id}'
7335 channel
= traverse_obj(
7336 notification
, ('contextualMenu', 'menuRenderer', 'items', 1, 'menuServiceItemRenderer', 'text', 'runs', 1, 'text'),
7338 notification_title
= self
._get
_text
(notification
, 'shortMessage')
7339 if notification_title
:
7340 notification_title
= notification_title
.replace('\xad', '') # remove soft hyphens
7341 # TODO: handle recommended videos
7342 title
= self
._search
_regex
(
7343 rf
'{re.escape(channel or "")}[^:]+: (.+)', notification_title
,
7344 'video title', default
=None)
7345 timestamp
= (self
._parse
_time
_text
(self
._get
_text
(notification
, 'sentTimeText'))
7346 if self
._configuration
_arg
('approximate_date', ie_key
=YoutubeTabIE
)
7351 'ie_key': (YoutubeIE
if video_id
else YoutubeTabIE
).ie_key(),
7352 'video_id': video_id
,
7354 'channel_id': channel_id
,
7356 'uploader': channel
,
7357 'thumbnails': self
._extract
_thumbnails
(notification
, 'videoThumbnail'),
7358 'timestamp': timestamp
,
7361 def _notification_menu_entries(self
, ytcfg
):
7362 continuation_list
= [None]
7364 for page
in itertools
.count(1):
7365 ctoken
= traverse_obj(
7366 continuation_list
, (0, 'continuationEndpoint', 'getNotificationMenuEndpoint', 'ctoken'), expected_type
=str)
7367 response
= self
._extract
_response
(
7368 item_id
=f
'page {page}', query
={'ctoken': ctoken
} if ctoken
else {}, ytcfg
=ytcfg
,
7369 ep
='notification/get_notification_menu', check_get_keys
='actions',
7370 headers
=self
.generate_api_headers(ytcfg
=ytcfg
, visitor_data
=self
._extract
_visitor
_data
(response
)))
7371 yield from self
._extract
_notification
_menu
(response
, continuation_list
)
7372 if not continuation_list
[0]:
7375 def _real_extract(self
, url
):
7376 display_id
= 'notifications'
7377 ytcfg
= self
._download
_ytcfg
('web', display_id
) if not self
.skip_webpage
else {}
7378 self
._report
_playlist
_authcheck
(ytcfg
)
7379 return self
.playlist_result(self
._notification
_menu
_entries
(ytcfg
), display_id
, display_id
)
7382 class YoutubeSearchIE(YoutubeTabBaseInfoExtractor
, SearchInfoExtractor
):
7383 IE_DESC
= 'YouTube search'
7384 IE_NAME
= 'youtube:search'
7385 _SEARCH_KEY
= 'ytsearch'
7386 _SEARCH_PARAMS
= 'EgIQAfABAQ==' # Videos only
7388 'url': 'ytsearch5:youtube-dl test video',
7389 'playlist_count': 5,
7391 'id': 'youtube-dl test video',
7392 'title': 'youtube-dl test video',
7395 'note': 'Suicide/self-harm search warning',
7396 'url': 'ytsearch1:i hate myself and i wanna die',
7397 'playlist_count': 1,
7399 'id': 'i hate myself and i wanna die',
7400 'title': 'i hate myself and i wanna die',
7405 class YoutubeSearchDateIE(YoutubeTabBaseInfoExtractor
, SearchInfoExtractor
):
7406 IE_NAME
= YoutubeSearchIE
.IE_NAME
+ ':date'
7407 _SEARCH_KEY
= 'ytsearchdate'
7408 IE_DESC
= 'YouTube search, newest videos first'
7409 _SEARCH_PARAMS
= 'CAISAhAB8AEB' # Videos only, sorted by date
7411 'url': 'ytsearchdate5:youtube-dl test video',
7412 'playlist_count': 5,
7414 'id': 'youtube-dl test video',
7415 'title': 'youtube-dl test video',
7420 class YoutubeSearchURLIE(YoutubeTabBaseInfoExtractor
):
7421 IE_DESC
= 'YouTube search URLs with sorting and filter support'
7422 IE_NAME
= YoutubeSearchIE
.IE_NAME
+ '_url'
7423 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/(?:results|search)\?([^#]+&)?(?:search_query|q)=(?:[^&]+)(?:[&#]|$)'
7425 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
7426 'playlist_mincount': 5,
7428 'id': 'youtube-dl test video',
7429 'title': 'youtube-dl test video',
7432 'url': 'https://www.youtube.com/results?search_query=python&sp=EgIQAg%253D%253D',
7433 'playlist_mincount': 5,
7439 'url': 'https://www.youtube.com/results?search_query=%23cats',
7440 'playlist_mincount': 1,
7444 # The test suite does not have support for nested playlists
7446 # 'url': r're:https://(www\.)?youtube\.com/hashtag/cats',
7452 'url': 'https://www.youtube.com/results?search_query=kurzgesagt&sp=EgIQAg%253D%253D',
7455 'title': 'kurzgesagt',
7460 'id': 'UCsXVk37bltHxD1rDPwtNM8Q',
7461 'url': 'https://www.youtube.com/channel/UCsXVk37bltHxD1rDPwtNM8Q',
7462 'ie_key': 'YoutubeTab',
7463 'channel': 'Kurzgesagt – In a Nutshell',
7464 'description': 'md5:4ae48dfa9505ffc307dad26342d06bfc',
7465 'title': 'Kurzgesagt – In a Nutshell',
7466 'channel_id': 'UCsXVk37bltHxD1rDPwtNM8Q',
7467 # No longer available for search as it is set to the handle.
7468 # 'playlist_count': int,
7469 'channel_url': 'https://www.youtube.com/channel/UCsXVk37bltHxD1rDPwtNM8Q',
7471 'uploader_id': '@kurzgesagt',
7472 'uploader_url': 'https://www.youtube.com/@kurzgesagt',
7473 'uploader': 'Kurzgesagt – In a Nutshell',
7474 'channel_is_verified': True,
7475 'channel_follower_count': int,
7478 'params': {'extract_flat': True, 'playlist_items': '1'},
7479 'playlist_mincount': 1,
7481 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
7482 'only_matching': True,
7485 def _real_extract(self
, url
):
7487 query
= (qs
.get('search_query') or qs
.get('q'))[0]
7488 return self
.playlist_result(self
._search
_results
(query
, qs
.get('sp', (None,))[0]), query
, query
)
7491 class YoutubeMusicSearchURLIE(YoutubeTabBaseInfoExtractor
):
7492 IE_DESC
= 'YouTube music search URLs with selectable sections, e.g. #songs'
7493 IE_NAME
= 'youtube:music:search_url'
7494 _VALID_URL
= r
'https?://music\.youtube\.com/search\?([^#]+&)?(?:search_query|q)=(?:[^&]+)(?:[&#]|$)'
7496 'url': 'https://music.youtube.com/search?q=royalty+free+music',
7497 'playlist_count': 16,
7499 'id': 'royalty free music',
7500 'title': 'royalty free music',
7503 'url': 'https://music.youtube.com/search?q=royalty+free+music&sp=EgWKAQIIAWoKEAoQAxAEEAkQBQ%3D%3D',
7504 'playlist_mincount': 30,
7506 'id': 'royalty free music - songs',
7507 'title': 'royalty free music - songs',
7509 'params': {'extract_flat': 'in_playlist'},
7511 'url': 'https://music.youtube.com/search?q=royalty+free+music#community+playlists',
7512 'playlist_mincount': 30,
7514 'id': 'royalty free music - community playlists',
7515 'title': 'royalty free music - community playlists',
7517 'params': {'extract_flat': 'in_playlist'},
7521 'albums': 'EgWKAQIYAWoKEAoQAxAEEAkQBQ==',
7522 'artists': 'EgWKAQIgAWoKEAoQAxAEEAkQBQ==',
7523 'community playlists': 'EgeKAQQoAEABagoQChADEAQQCRAF',
7524 'featured playlists': 'EgeKAQQoADgBagwQAxAJEAQQDhAKEAU==',
7525 'songs': 'EgWKAQIIAWoKEAoQAxAEEAkQBQ==',
7526 'videos': 'EgWKAQIQAWoKEAoQAxAEEAkQBQ==',
7529 def _real_extract(self
, url
):
7531 query
= (qs
.get('search_query') or qs
.get('q'))[0]
7532 params
= qs
.get('sp', (None,))[0]
7534 section
= next((k
for k
, v
in self
._SECTIONS
.items() if v
== params
), params
)
7536 section
= urllib
.parse
.unquote_plus(([*url
.split('#'), ''])[1]).lower()
7537 params
= self
._SECTIONS
.get(section
)
7540 title
= join_nonempty(query
, section
, delim
=' - ')
7541 return self
.playlist_result(self
._search
_results
(query
, params
, default_client
='web_music'), title
, title
)
7544 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor
):
7546 Base class for feed extractors
7547 Subclasses must re-define the _FEED_NAME property.
7549 _LOGIN_REQUIRED
= True
7550 _FEED_NAME
= 'feeds'
7554 return f
'youtube:{cls._FEED_NAME}'
7556 def _real_extract(self
, url
):
7557 return self
.url_result(
7558 f
'https://www.youtube.com/feed/{self._FEED_NAME}', ie
=YoutubeTabIE
.ie_key())
7561 class YoutubeWatchLaterIE(YoutubeBaseInfoExtractor
):
7562 IE_NAME
= 'youtube:watchlater'
7563 IE_DESC
= 'Youtube watch later list; ":ytwatchlater" keyword (requires cookies)'
7564 _VALID_URL
= r
':ytwatchlater'
7566 'url': ':ytwatchlater',
7567 'only_matching': True,
7570 def _real_extract(self
, url
):
7571 return self
.url_result(
7572 'https://www.youtube.com/playlist?list=WL', ie
=YoutubeTabIE
.ie_key())
7575 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor
):
7576 IE_DESC
= 'YouTube recommended videos; ":ytrec" keyword'
7577 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
7578 _FEED_NAME
= 'recommended'
7579 _LOGIN_REQUIRED
= False
7582 'only_matching': True,
7584 'url': ':ytrecommended',
7585 'only_matching': True,
7587 'url': 'https://youtube.com',
7588 'only_matching': True,
7592 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor
):
7593 IE_DESC
= 'YouTube subscriptions feed; ":ytsubs" keyword (requires cookies)'
7594 _VALID_URL
= r
':ytsub(?:scription)?s?'
7595 _FEED_NAME
= 'subscriptions'
7598 'only_matching': True,
7600 'url': ':ytsubscriptions',
7601 'only_matching': True,
7605 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor
):
7606 IE_DESC
= 'Youtube watch history; ":ythis" keyword (requires cookies)'
7607 _VALID_URL
= r
':ythis(?:tory)?'
7608 _FEED_NAME
= 'history'
7610 'url': ':ythistory',
7611 'only_matching': True,
7615 class YoutubeShortsAudioPivotIE(YoutubeBaseInfoExtractor
):
7616 IE_DESC
= 'YouTube Shorts audio pivot (Shorts using audio of a given video)'
7617 IE_NAME
= 'youtube:shorts:pivot:audio'
7618 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/source/(?P<id>[\w-]{11})/shorts'
7620 'url': 'https://www.youtube.com/source/Lyj-MZSAA9o/shorts',
7621 'only_matching': True,
7625 def _generate_audio_pivot_params(video_id
):
7627 Generates sfv_audio_pivot browse params for this video id
7629 pb_params
= b
'\xf2\x05+\n)\x12\'\n\x0b%b\x12\x0b%b\x1a\x0b%b' % ((video_id
.encode(),) * 3)
7630 return urllib
.parse
.quote(base64
.b64encode(pb_params
).decode())
7632 def _real_extract(self
, url
):
7633 video_id
= self
._match
_id
(url
)
7634 return self
.url_result(
7635 f
'https://www.youtube.com/feed/sfv_audio_pivot?bp={self._generate_audio_pivot_params(video_id)}',
7639 class YoutubeTruncatedURLIE(YoutubeBaseInfoExtractor
):
7640 IE_NAME
= 'youtube:truncated_url'
7641 IE_DESC
= False # Do not list
7642 _VALID_URL
= r
'''(?x)
7644 (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
7647 annotation_id=annotation_[^&]+|
7653 attribution_link\?a=[^&]+
7659 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
7660 'only_matching': True,
7662 'url': 'https://www.youtube.com/watch?',
7663 'only_matching': True,
7665 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
7666 'only_matching': True,
7668 'url': 'https://www.youtube.com/watch?feature=foo',
7669 'only_matching': True,
7671 'url': 'https://www.youtube.com/watch?hl=en-GB',
7672 'only_matching': True,
7674 'url': 'https://www.youtube.com/watch?t=2372',
7675 'only_matching': True,
7678 def _real_extract(self
, url
):
7679 raise ExtractorError(
7680 'Did you forget to quote the URL? Remember that & is a meta '
7681 'character in most shells, so you want to put the URL in quotes, '
7683 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
7684 ' or simply yt-dlp BaW_jenozKc .',
7688 class YoutubeClipIE(YoutubeTabBaseInfoExtractor
):
7689 IE_NAME
= 'youtube:clip'
7690 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/clip/(?P<id>[^/?#]+)'
7692 # FIXME: Other metadata should be extracted from the clip, not from the base video
7693 'url': 'https://www.youtube.com/clip/UgytZKpehg-hEMBSn3F4AaABCQ',
7695 'id': 'UgytZKpehg-hEMBSn3F4AaABCQ',
7697 'section_start': 29.0,
7698 'section_end': 39.7,
7701 'availability': 'public',
7702 'categories': ['Gaming'],
7703 'channel': 'Scott The Woz',
7704 'channel_id': 'UC4rqhyiTs7XyuODcECvuiiQ',
7705 'channel_url': 'https://www.youtube.com/channel/UC4rqhyiTs7XyuODcECvuiiQ',
7706 'description': 'md5:7a4517a17ea9b4bd98996399d8bb36e7',
7708 'playable_in_embed': True,
7710 'thumbnail': 'https://i.ytimg.com/vi_webp/ScPX26pdQik/maxresdefault.webp',
7711 'title': 'Mobile Games on Console - Scott The Woz',
7712 'upload_date': '20210920',
7713 'uploader': 'Scott The Woz',
7714 'uploader_id': '@ScottTheWoz',
7715 'uploader_url': 'https://www.youtube.com/@ScottTheWoz',
7717 'live_status': 'not_live',
7718 'channel_follower_count': int,
7719 'chapters': 'count:20',
7720 'comment_count': int,
7721 'heatmap': 'count:100',
7725 def _real_extract(self
, url
):
7726 clip_id
= self
._match
_id
(url
)
7727 _
, data
= self
._extract
_webpage
(url
, clip_id
)
7729 video_id
= traverse_obj(data
, ('currentVideoEndpoint', 'watchEndpoint', 'videoId'))
7731 raise ExtractorError('Unable to find video ID')
7733 clip_data
= traverse_obj(data
, (
7734 'engagementPanels', ..., 'engagementPanelSectionListRenderer', 'content', 'clipSectionRenderer',
7735 'contents', ..., 'clipAttributionRenderer', 'onScrubExit', 'commandExecutorCommand', 'commands', ...,
7736 'openPopupAction', 'popup', 'notificationActionRenderer', 'actionButton', 'buttonRenderer', 'command',
7737 'commandExecutorCommand', 'commands', ..., 'loopCommand'), get_all
=False)
7740 '_type': 'url_transparent',
7741 'url': f
'https://www.youtube.com/watch?v={video_id}',
7742 'ie_key': YoutubeIE
.ie_key(),
7744 'section_start': int(clip_data
['startTimeMs']) / 1000,
7745 'section_end': int(clip_data
['endTimeMs']) / 1000,
7746 '_format_sort_fields': ( # https protocol is prioritized for ffmpeg compatibility
7747 'proto:https', 'quality', 'res', 'fps', 'hdr:12', 'source', 'vcodec', 'channels', 'acodec', 'lang'),
7751 class YoutubeConsentRedirectIE(YoutubeBaseInfoExtractor
):
7752 IE_NAME
= 'youtube:consent'
7753 IE_DESC
= False # Do not list
7754 _VALID_URL
= r
'https?://consent\.youtube\.com/m\?'
7756 'url': 'https://consent.youtube.com/m?continue=https%3A%2F%2Fwww.youtube.com%2Flive%2FqVv6vCqciTM%3Fcbrd%3D1&gl=NL&m=0&pc=yt&hl=en&src=1',
7758 'id': 'qVv6vCqciTM',
7761 'uploader_id': '@sana_natori',
7762 'comment_count': int,
7763 'chapters': 'count:13',
7764 'upload_date': '20221223',
7765 'thumbnail': 'https://i.ytimg.com/vi/qVv6vCqciTM/maxresdefault.jpg',
7766 'channel_url': 'https://www.youtube.com/channel/UCIdEIHpS0TdkqRkHL5OkLtA',
7767 'uploader_url': 'https://www.youtube.com/@sana_natori',
7769 'release_date': '20221223',
7770 'tags': ['Vtuber', '月ノ美兎', '名取さな', 'にじさんじ', 'クリスマス', '3D配信'],
7771 'title': '【 #インターネット女クリスマス 】3Dで歌ってはしゃぐインターネットの女たち【月ノ美兎/名取さな】',
7773 'playable_in_embed': True,
7775 'availability': 'public',
7776 'channel_follower_count': int,
7777 'channel_id': 'UCIdEIHpS0TdkqRkHL5OkLtA',
7778 'categories': ['Entertainment'],
7779 'live_status': 'was_live',
7780 'release_timestamp': 1671793345,
7781 'channel': 'さなちゃんねる',
7782 'description': 'md5:6aebf95cc4a1d731aebc01ad6cc9806d',
7783 'uploader': 'さなちゃんねる',
7784 'channel_is_verified': True,
7785 'heatmap': 'count:100',
7787 'add_ie': ['Youtube'],
7788 'params': {'skip_download': 'Youtube'},
7791 def _real_extract(self
, url
):
7792 redirect_url
= url_or_none(parse_qs(url
).get('continue', [None])[-1])
7793 if not redirect_url
:
7794 raise ExtractorError('Invalid cookie consent redirect URL', expected
=True)
7795 return self
.url_result(redirect_url
)
7798 class YoutubeTruncatedIDIE(YoutubeBaseInfoExtractor
):
7799 IE_NAME
= 'youtube:truncated_id'
7800 IE_DESC
= False # Do not list
7801 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
7804 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
7805 'only_matching': True,
7808 def _real_extract(self
, url
):
7809 video_id
= self
._match
_id
(url
)
7810 raise ExtractorError(
7811 f
'Incomplete YouTube ID {video_id}. URL {url} looks truncated.',