bf858c39d32e8a5a93183464ef0c860e7cf3f6e4
[ytdl] / youtube_dl / extractor / youtube.py
1 # coding: utf-8
2
3 from __future__ import unicode_literals
4
5 import itertools
6 import json
7 import os.path
8 import random
9 import re
10 import traceback
11
12 from .common import InfoExtractor, SearchInfoExtractor
13 from ..compat import (
14     compat_chr,
15     compat_HTTPError,
16     compat_parse_qs,
17     compat_str,
18     compat_urllib_parse_unquote_plus,
19     compat_urllib_parse_urlencode,
20     compat_urllib_parse_urlparse,
21     compat_urlparse,
22 )
23 from ..jsinterp import JSInterpreter
24 from ..utils import (
25     ExtractorError,
26     clean_html,
27     dict_get,
28     float_or_none,
29     int_or_none,
30     mimetype2ext,
31     parse_codecs,
32     parse_duration,
33     qualities,
34     remove_start,
35     smuggle_url,
36     str_or_none,
37     str_to_int,
38     try_get,
39     unescapeHTML,
40     unified_strdate,
41     unsmuggle_url,
42     update_url_query,
43     url_or_none,
44     urlencode_postdata,
45     urljoin,
46 )
47
48
49 def parse_qs(url):
50     return compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
51
52
53 class YoutubeBaseInfoExtractor(InfoExtractor):
54     """Provide base functions for Youtube extractors"""
55     _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
56     _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
57
58     _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
59     _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
60     _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
61
62     _NETRC_MACHINE = 'youtube'
63     # If True it will raise an error if no login info is provided
64     _LOGIN_REQUIRED = False
65
66     _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM)'
67
68     def _login(self):
69         """
70         Attempt to log in to YouTube.
71         True is returned if successful or skipped.
72         False is returned if login failed.
73
74         If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
75         """
76         username, password = self._get_login_info()
77         # No authentication to be performed
78         if username is None:
79             if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
80                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
81             return True
82
83         login_page = self._download_webpage(
84             self._LOGIN_URL, None,
85             note='Downloading login page',
86             errnote='unable to fetch login page', fatal=False)
87         if login_page is False:
88             return
89
90         login_form = self._hidden_inputs(login_page)
91
92         def req(url, f_req, note, errnote):
93             data = login_form.copy()
94             data.update({
95                 'pstMsg': 1,
96                 'checkConnection': 'youtube',
97                 'checkedDomains': 'youtube',
98                 'hl': 'en',
99                 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
100                 'f.req': json.dumps(f_req),
101                 'flowName': 'GlifWebSignIn',
102                 'flowEntry': 'ServiceLogin',
103                 # TODO: reverse actual botguard identifier generation algo
104                 'bgRequest': '["identifier",""]',
105             })
106             return self._download_json(
107                 url, None, note=note, errnote=errnote,
108                 transform_source=lambda s: re.sub(r'^[^[]*', '', s),
109                 fatal=False,
110                 data=urlencode_postdata(data), headers={
111                     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
112                     'Google-Accounts-XSRF': 1,
113                 })
114
115         def warn(message):
116             self._downloader.report_warning(message)
117
118         lookup_req = [
119             username,
120             None, [], None, 'US', None, None, 2, False, True,
121             [
122                 None, None,
123                 [2, 1, None, 1,
124                  'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',
125                  None, [], 4],
126                 1, [None, None, []], None, None, None, True
127             ],
128             username,
129         ]
130
131         lookup_results = req(
132             self._LOOKUP_URL, lookup_req,
133             'Looking up account info', 'Unable to look up account info')
134
135         if lookup_results is False:
136             return False
137
138         user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
139         if not user_hash:
140             warn('Unable to extract user hash')
141             return False
142
143         challenge_req = [
144             user_hash,
145             None, 1, None, [1, None, None, None, [password, None, True]],
146             [
147                 None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],
148                 1, [None, None, []], None, None, None, True
149             ]]
150
151         challenge_results = req(
152             self._CHALLENGE_URL, challenge_req,
153             'Logging in', 'Unable to log in')
154
155         if challenge_results is False:
156             return
157
158         login_res = try_get(challenge_results, lambda x: x[0][5], list)
159         if login_res:
160             login_msg = try_get(login_res, lambda x: x[5], compat_str)
161             warn(
162                 'Unable to login: %s' % 'Invalid password'
163                 if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
164             return False
165
166         res = try_get(challenge_results, lambda x: x[0][-1], list)
167         if not res:
168             warn('Unable to extract result entry')
169             return False
170
171         login_challenge = try_get(res, lambda x: x[0][0], list)
172         if login_challenge:
173             challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
174             if challenge_str == 'TWO_STEP_VERIFICATION':
175                 # SEND_SUCCESS - TFA code has been successfully sent to phone
176                 # QUOTA_EXCEEDED - reached the limit of TFA codes
177                 status = try_get(login_challenge, lambda x: x[5], compat_str)
178                 if status == 'QUOTA_EXCEEDED':
179                     warn('Exceeded the limit of TFA codes, try later')
180                     return False
181
182                 tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
183                 if not tl:
184                     warn('Unable to extract TL')
185                     return False
186
187                 tfa_code = self._get_tfa_info('2-step verification code')
188
189                 if not tfa_code:
190                     warn(
191                         'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
192                         '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
193                     return False
194
195                 tfa_code = remove_start(tfa_code, 'G-')
196
197                 tfa_req = [
198                     user_hash, None, 2, None,
199                     [
200                         9, None, None, None, None, None, None, None,
201                         [None, tfa_code, True, 2]
202                     ]]
203
204                 tfa_results = req(
205                     self._TFA_URL.format(tl), tfa_req,
206                     'Submitting TFA code', 'Unable to submit TFA code')
207
208                 if tfa_results is False:
209                     return False
210
211                 tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
212                 if tfa_res:
213                     tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
214                     warn(
215                         'Unable to finish TFA: %s' % 'Invalid TFA code'
216                         if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
217                     return False
218
219                 check_cookie_url = try_get(
220                     tfa_results, lambda x: x[0][-1][2], compat_str)
221             else:
222                 CHALLENGES = {
223                     'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
224                     'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
225                     'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
226                 }
227                 challenge = CHALLENGES.get(
228                     challenge_str,
229                     '%s returned error %s.' % (self.IE_NAME, challenge_str))
230                 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
231                 return False
232         else:
233             check_cookie_url = try_get(res, lambda x: x[2], compat_str)
234
235         if not check_cookie_url:
236             warn('Unable to extract CheckCookie URL')
237             return False
238
239         check_cookie_results = self._download_webpage(
240             check_cookie_url, None, 'Checking cookie', fatal=False)
241
242         if check_cookie_results is False:
243             return False
244
245         if 'https://myaccount.google.com/' not in check_cookie_results:
246             warn('Unable to log in')
247             return False
248
249         return True
250
251     def _initialize_consent(self):
252         cookies = self._get_cookies('https://www.youtube.com/')
253         if cookies.get('__Secure-3PSID'):
254             return
255         consent_id = None
256         consent = cookies.get('CONSENT')
257         if consent:
258             if 'YES' in consent.value:
259                 return
260             consent_id = self._search_regex(
261                 r'PENDING\+(\d+)', consent.value, 'consent', default=None)
262         if not consent_id:
263             consent_id = random.randint(100, 999)
264         self._set_cookie('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id)
265
266     def _real_initialize(self):
267         self._initialize_consent()
268         if self._downloader is None:
269             return
270         if not self._login():
271             return
272
273     _DEFAULT_API_DATA = {
274         'context': {
275             'client': {
276                 'clientName': 'WEB',
277                 'clientVersion': '2.20201021.03.00',
278             }
279         },
280     }
281
282     _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
283     _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
284     _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
285
286     def _call_api(self, ep, query, video_id, fatal=True):
287         data = self._DEFAULT_API_DATA.copy()
288         data.update(query)
289
290         return self._download_json(
291             'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
292             note='Downloading API JSON', errnote='Unable to download API page',
293             data=json.dumps(data).encode('utf8'), fatal=fatal,
294             headers={'content-type': 'application/json'},
295             query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
296
297     def _extract_yt_initial_data(self, video_id, webpage):
298         return self._parse_json(
299             self._search_regex(
300                 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
301                  self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
302             video_id)
303
304     def _extract_ytcfg(self, video_id, webpage):
305         return self._parse_json(
306             self._search_regex(
307                 r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
308                 default='{}'), video_id, fatal=False) or {}
309
310     def _extract_video(self, renderer):
311         video_id = renderer['videoId']
312         title = try_get(
313             renderer,
314             (lambda x: x['title']['runs'][0]['text'],
315              lambda x: x['title']['simpleText']), compat_str)
316         description = try_get(
317             renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
318             compat_str)
319         duration = parse_duration(try_get(
320             renderer, lambda x: x['lengthText']['simpleText'], compat_str))
321         view_count_text = try_get(
322             renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
323         view_count = str_to_int(self._search_regex(
324             r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
325             'view count', default=None))
326         uploader = try_get(
327             renderer,
328             (lambda x: x['ownerText']['runs'][0]['text'],
329              lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
330         return {
331             '_type': 'url',
332             'ie_key': YoutubeIE.ie_key(),
333             'id': video_id,
334             'url': video_id,
335             'title': title,
336             'description': description,
337             'duration': duration,
338             'view_count': view_count,
339             'uploader': uploader,
340         }
341
342
343 class YoutubeIE(YoutubeBaseInfoExtractor):
344     IE_DESC = 'YouTube.com'
345     _INVIDIOUS_SITES = (
346         # invidious-redirect websites
347         r'(?:www\.)?redirect\.invidious\.io',
348         r'(?:(?:www|dev)\.)?invidio\.us',
349         # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
350         r'(?:(?:www|no)\.)?invidiou\.sh',
351         r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
352         r'(?:www\.)?invidious\.kabi\.tk',
353         r'(?:www\.)?invidious\.13ad\.de',
354         r'(?:www\.)?invidious\.mastodon\.host',
355         r'(?:www\.)?invidious\.zapashcanon\.fr',
356         r'(?:www\.)?invidious\.kavin\.rocks',
357         r'(?:www\.)?invidious\.tinfoil-hat\.net',
358         r'(?:www\.)?invidious\.himiko\.cloud',
359         r'(?:www\.)?invidious\.reallyancient\.tech',
360         r'(?:www\.)?invidious\.tube',
361         r'(?:www\.)?invidiou\.site',
362         r'(?:www\.)?invidious\.site',
363         r'(?:www\.)?invidious\.xyz',
364         r'(?:www\.)?invidious\.nixnet\.xyz',
365         r'(?:www\.)?invidious\.048596\.xyz',
366         r'(?:www\.)?invidious\.drycat\.fr',
367         r'(?:www\.)?inv\.skyn3t\.in',
368         r'(?:www\.)?tube\.poal\.co',
369         r'(?:www\.)?tube\.connect\.cafe',
370         r'(?:www\.)?vid\.wxzm\.sx',
371         r'(?:www\.)?vid\.mint\.lgbt',
372         r'(?:www\.)?vid\.puffyan\.us',
373         r'(?:www\.)?yewtu\.be',
374         r'(?:www\.)?yt\.elukerio\.org',
375         r'(?:www\.)?yt\.lelux\.fi',
376         r'(?:www\.)?invidious\.ggc-project\.de',
377         r'(?:www\.)?yt\.maisputain\.ovh',
378         r'(?:www\.)?ytprivate\.com',
379         r'(?:www\.)?invidious\.13ad\.de',
380         r'(?:www\.)?invidious\.toot\.koeln',
381         r'(?:www\.)?invidious\.fdn\.fr',
382         r'(?:www\.)?watch\.nettohikari\.com',
383         r'(?:www\.)?kgg2m7yk5aybusll\.onion',
384         r'(?:www\.)?qklhadlycap4cnod\.onion',
385         r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
386         r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
387         r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
388         r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
389         r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
390         r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
391     )
392     _VALID_URL = r"""(?x)^
393                      (
394                          (?:https?://|//)                                    # http(s):// or protocol-independent URL
395                          (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
396                             (?:www\.)?deturl\.com/www\.youtube\.com|
397                             (?:www\.)?pwnyoutube\.com|
398                             (?:www\.)?hooktube\.com|
399                             (?:www\.)?yourepeat\.com|
400                             tube\.majestyc\.net|
401                             %(invidious)s|
402                             youtube\.googleapis\.com)/                        # the various hostnames, with wildcard subdomains
403                          (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
404                          (?:                                                  # the various things that can precede the ID:
405                              (?:(?:v|embed|e)/(?!videoseries))                # v/ or embed/ or e/
406                              |(?:                                             # or the v= param in all its forms
407                                  (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)?  # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
408                                  (?:\?|\#!?)                                  # the params delimiter ? or # or #!
409                                  (?:.*?[&;])??                                # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
410                                  v=
411                              )
412                          ))
413                          |(?:
414                             youtu\.be|                                        # just youtu.be/xxxx
415                             vid\.plus|                                        # or vid.plus/xxxx
416                             zwearz\.com/watch|                                # or zwearz.com/watch/xxxx
417                             %(invidious)s
418                          )/
419                          |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
420                          )
421                      )?                                                       # all until now is optional -> you can pass the naked ID
422                      (?P<id>[0-9A-Za-z_-]{11})                                # here is it! the YouTube video ID
423                      (?(1).+)?                                                # if we found the ID, everything can follow
424                      $""" % {
425         'invidious': '|'.join(_INVIDIOUS_SITES),
426     }
427     _PLAYER_INFO_RE = (
428         r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
429         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$',
430         r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
431     )
432     _SUBTITLE_FORMATS = ('srv1', 'srv2', 'srv3', 'ttml', 'vtt')
433
434     _GEO_BYPASS = False
435
436     IE_NAME = 'youtube'
437     _TESTS = [
438         {
439             'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
440             'info_dict': {
441                 'id': 'BaW_jenozKc',
442                 'ext': 'mp4',
443                 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
444                 'uploader': 'Philipp Hagemeister',
445                 'uploader_id': 'phihag',
446                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
447                 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
448                 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
449                 'upload_date': '20121002',
450                 'description': 'test chars:  "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
451                 'categories': ['Science & Technology'],
452                 'tags': ['youtube-dl'],
453                 'duration': 10,
454                 'view_count': int,
455                 'like_count': int,
456                 'dislike_count': int,
457                 'start_time': 1,
458                 'end_time': 9,
459             }
460         },
461         {
462             'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
463             'note': 'Embed-only video (#1746)',
464             'info_dict': {
465                 'id': 'yZIXLfi8CZQ',
466                 'ext': 'mp4',
467                 'upload_date': '20120608',
468                 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
469                 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
470                 'uploader': 'SET India',
471                 'uploader_id': 'setindia',
472                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
473                 'age_limit': 18,
474             },
475             'skip': 'Private video',
476         },
477         {
478             'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
479             'note': 'Use the first video ID in the URL',
480             'info_dict': {
481                 'id': 'BaW_jenozKc',
482                 'ext': 'mp4',
483                 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
484                 'uploader': 'Philipp Hagemeister',
485                 'uploader_id': 'phihag',
486                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
487                 'upload_date': '20121002',
488                 'description': 'test chars:  "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
489                 'categories': ['Science & Technology'],
490                 'tags': ['youtube-dl'],
491                 'duration': 10,
492                 'view_count': int,
493                 'like_count': int,
494                 'dislike_count': int,
495             },
496             'params': {
497                 'skip_download': True,
498             },
499         },
500         {
501             'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
502             'note': '256k DASH audio (format 141) via DASH manifest',
503             'info_dict': {
504                 'id': 'a9LDPn-MO4I',
505                 'ext': 'm4a',
506                 'upload_date': '20121002',
507                 'uploader_id': '8KVIDEO',
508                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
509                 'description': '',
510                 'uploader': '8KVIDEO',
511                 'title': 'UHDTV TEST 8K VIDEO.mp4'
512             },
513             'params': {
514                 'youtube_include_dash_manifest': True,
515                 'format': '141',
516             },
517             'skip': 'format 141 not served anymore',
518         },
519         # DASH manifest with encrypted signature
520         {
521             'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
522             'info_dict': {
523                 'id': 'IB3lcPjvWLA',
524                 'ext': 'm4a',
525                 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
526                 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
527                 'duration': 244,
528                 'uploader': 'AfrojackVEVO',
529                 'uploader_id': 'AfrojackVEVO',
530                 'upload_date': '20131011',
531                 'abr': 129.495,
532             },
533             'params': {
534                 'youtube_include_dash_manifest': True,
535                 'format': '141/bestaudio[ext=m4a]',
536             },
537         },
538         # Controversy video
539         {
540             'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
541             'info_dict': {
542                 'id': 'T4XJQO3qol8',
543                 'ext': 'mp4',
544                 'duration': 219,
545                 'upload_date': '20100909',
546                 'uploader': 'Amazing Atheist',
547                 'uploader_id': 'TheAmazingAtheist',
548                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
549                 'title': 'Burning Everyone\'s Koran',
550                 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms \r\n\r\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
551             }
552         },
553         # Normal age-gate video (No vevo, embed allowed), available via embed page
554         {
555             'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
556             'info_dict': {
557                 'id': 'HtVdAasjOgU',
558                 'ext': 'mp4',
559                 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
560                 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
561                 'duration': 142,
562                 'uploader': 'The Witcher',
563                 'uploader_id': 'WitcherGame',
564                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
565                 'upload_date': '20140605',
566                 'age_limit': 18,
567             },
568         },
569         {
570             # Age-gated video only available with authentication (unavailable
571             # via embed page workaround)
572             'url': 'XgnwCQzjau8',
573             'only_matching': True,
574         },
575         # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
576         # YouTube Red ad is not captured for creator
577         {
578             'url': '__2ABJjxzNo',
579             'info_dict': {
580                 'id': '__2ABJjxzNo',
581                 'ext': 'mp4',
582                 'duration': 266,
583                 'upload_date': '20100430',
584                 'uploader_id': 'deadmau5',
585                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
586                 'creator': 'deadmau5',
587                 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
588                 'uploader': 'deadmau5',
589                 'title': 'Deadmau5 - Some Chords (HD)',
590                 'alt_title': 'Some Chords',
591             },
592             'expected_warnings': [
593                 'DASH manifest missing',
594             ]
595         },
596         # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
597         {
598             'url': 'lqQg6PlCWgI',
599             'info_dict': {
600                 'id': 'lqQg6PlCWgI',
601                 'ext': 'mp4',
602                 'duration': 6085,
603                 'upload_date': '20150827',
604                 'uploader_id': 'olympic',
605                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
606                 'description': 'HO09  - Women -  GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
607                 'uploader': 'Olympic',
608                 'title': 'Hockey - Women -  GER-AUS - London 2012 Olympic Games',
609             },
610             'params': {
611                 'skip_download': 'requires avconv',
612             }
613         },
614         # Non-square pixels
615         {
616             'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
617             'info_dict': {
618                 'id': '_b-2C3KPAM0',
619                 'ext': 'mp4',
620                 'stretched_ratio': 16 / 9.,
621                 'duration': 85,
622                 'upload_date': '20110310',
623                 'uploader_id': 'AllenMeow',
624                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
625                 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
626                 'uploader': '孫ᄋᄅ',
627                 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
628             },
629         },
630         # url_encoded_fmt_stream_map is empty string
631         {
632             'url': 'qEJwOuvDf7I',
633             'info_dict': {
634                 'id': 'qEJwOuvDf7I',
635                 'ext': 'webm',
636                 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
637                 'description': '',
638                 'upload_date': '20150404',
639                 'uploader_id': 'spbelect',
640                 'uploader': 'Наблюдатели Петербурга',
641             },
642             'params': {
643                 'skip_download': 'requires avconv',
644             },
645             'skip': 'This live event has ended.',
646         },
647         # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
648         {
649             'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
650             'info_dict': {
651                 'id': 'FIl7x6_3R5Y',
652                 'ext': 'webm',
653                 'title': 'md5:7b81415841e02ecd4313668cde88737a',
654                 'description': 'md5:116377fd2963b81ec4ce64b542173306',
655                 'duration': 220,
656                 'upload_date': '20150625',
657                 'uploader_id': 'dorappi2000',
658                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
659                 'uploader': 'dorappi2000',
660                 'formats': 'mincount:31',
661             },
662             'skip': 'not actual anymore',
663         },
664         # DASH manifest with segment_list
665         {
666             'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
667             'md5': '8ce563a1d667b599d21064e982ab9e31',
668             'info_dict': {
669                 'id': 'CsmdDsKjzN8',
670                 'ext': 'mp4',
671                 'upload_date': '20150501',  # According to '<meta itemprop="datePublished"', but in other places it's 20150510
672                 'uploader': 'Airtek',
673                 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
674                 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
675                 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
676             },
677             'params': {
678                 'youtube_include_dash_manifest': True,
679                 'format': '135',  # bestvideo
680             },
681             'skip': 'This live event has ended.',
682         },
683         {
684             # Multifeed videos (multiple cameras), URL is for Main Camera
685             'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
686             'info_dict': {
687                 'id': 'jvGDaLqkpTg',
688                 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
689                 'description': 'md5:e03b909557865076822aa169218d6a5d',
690             },
691             'playlist': [{
692                 'info_dict': {
693                     'id': 'jvGDaLqkpTg',
694                     'ext': 'mp4',
695                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
696                     'description': 'md5:e03b909557865076822aa169218d6a5d',
697                     'duration': 10643,
698                     'upload_date': '20161111',
699                     'uploader': 'Team PGP',
700                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
701                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
702                 },
703             }, {
704                 'info_dict': {
705                     'id': '3AKt1R1aDnw',
706                     'ext': 'mp4',
707                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
708                     'description': 'md5:e03b909557865076822aa169218d6a5d',
709                     'duration': 10991,
710                     'upload_date': '20161111',
711                     'uploader': 'Team PGP',
712                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
713                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
714                 },
715             }, {
716                 'info_dict': {
717                     'id': 'RtAMM00gpVc',
718                     'ext': 'mp4',
719                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
720                     'description': 'md5:e03b909557865076822aa169218d6a5d',
721                     'duration': 10995,
722                     'upload_date': '20161111',
723                     'uploader': 'Team PGP',
724                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
725                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
726                 },
727             }, {
728                 'info_dict': {
729                     'id': '6N2fdlP3C5U',
730                     'ext': 'mp4',
731                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
732                     'description': 'md5:e03b909557865076822aa169218d6a5d',
733                     'duration': 10990,
734                     'upload_date': '20161111',
735                     'uploader': 'Team PGP',
736                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
737                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
738                 },
739             }],
740             'params': {
741                 'skip_download': True,
742             },
743         },
744         {
745             # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
746             'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
747             'info_dict': {
748                 'id': 'gVfLd0zydlo',
749                 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
750             },
751             'playlist_count': 2,
752             'skip': 'Not multifeed anymore',
753         },
754         {
755             'url': 'https://vid.plus/FlRa-iH7PGw',
756             'only_matching': True,
757         },
758         {
759             'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
760             'only_matching': True,
761         },
762         {
763             # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
764             # Also tests cut-off URL expansion in video description (see
765             # https://github.com/ytdl-org/youtube-dl/issues/1892,
766             # https://github.com/ytdl-org/youtube-dl/issues/8164)
767             'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
768             'info_dict': {
769                 'id': 'lsguqyKfVQg',
770                 'ext': 'mp4',
771                 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
772                 'alt_title': 'Dark Walk - Position Music',
773                 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
774                 'duration': 133,
775                 'upload_date': '20151119',
776                 'uploader_id': 'IronSoulElf',
777                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
778                 'uploader': 'IronSoulElf',
779                 'creator': 'Todd Haberman,  Daniel Law Heath and Aaron Kaplan',
780                 'track': 'Dark Walk - Position Music',
781                 'artist': 'Todd Haberman,  Daniel Law Heath and Aaron Kaplan',
782                 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
783             },
784             'params': {
785                 'skip_download': True,
786             },
787         },
788         {
789             # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
790             'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
791             'only_matching': True,
792         },
793         {
794             # Video with yt:stretch=17:0
795             'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
796             'info_dict': {
797                 'id': 'Q39EVAstoRM',
798                 'ext': 'mp4',
799                 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
800                 'description': 'md5:ee18a25c350637c8faff806845bddee9',
801                 'upload_date': '20151107',
802                 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
803                 'uploader': 'CH GAMER DROID',
804             },
805             'params': {
806                 'skip_download': True,
807             },
808             'skip': 'This video does not exist.',
809         },
810         {
811             # Video with incomplete 'yt:stretch=16:'
812             'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
813             'only_matching': True,
814         },
815         {
816             # Video licensed under Creative Commons
817             'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
818             'info_dict': {
819                 'id': 'M4gD1WSo5mA',
820                 'ext': 'mp4',
821                 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
822                 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
823                 'duration': 721,
824                 'upload_date': '20150127',
825                 'uploader_id': 'BerkmanCenter',
826                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
827                 'uploader': 'The Berkman Klein Center for Internet & Society',
828                 'license': 'Creative Commons Attribution license (reuse allowed)',
829             },
830             'params': {
831                 'skip_download': True,
832             },
833         },
834         {
835             # Channel-like uploader_url
836             'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
837             'info_dict': {
838                 'id': 'eQcmzGIKrzg',
839                 'ext': 'mp4',
840                 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
841                 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
842                 'duration': 4060,
843                 'upload_date': '20151119',
844                 'uploader': 'Bernie Sanders',
845                 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
846                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
847                 'license': 'Creative Commons Attribution license (reuse allowed)',
848             },
849             'params': {
850                 'skip_download': True,
851             },
852         },
853         {
854             'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
855             'only_matching': True,
856         },
857         {
858             # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
859             'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
860             'only_matching': True,
861         },
862         {
863             # Rental video preview
864             'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
865             'info_dict': {
866                 'id': 'uGpuVWrhIzE',
867                 'ext': 'mp4',
868                 'title': 'Piku - Trailer',
869                 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
870                 'upload_date': '20150811',
871                 'uploader': 'FlixMatrix',
872                 'uploader_id': 'FlixMatrixKaravan',
873                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
874                 'license': 'Standard YouTube License',
875             },
876             'params': {
877                 'skip_download': True,
878             },
879             'skip': 'This video is not available.',
880         },
881         {
882             # YouTube Red video with episode data
883             'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
884             'info_dict': {
885                 'id': 'iqKdEhx-dD4',
886                 'ext': 'mp4',
887                 'title': 'Isolation - Mind Field (Ep 1)',
888                 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
889                 'duration': 2085,
890                 'upload_date': '20170118',
891                 'uploader': 'Vsauce',
892                 'uploader_id': 'Vsauce',
893                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
894                 'series': 'Mind Field',
895                 'season_number': 1,
896                 'episode_number': 1,
897             },
898             'params': {
899                 'skip_download': True,
900             },
901             'expected_warnings': [
902                 'Skipping DASH manifest',
903             ],
904         },
905         {
906             # The following content has been identified by the YouTube community
907             # as inappropriate or offensive to some audiences.
908             'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
909             'info_dict': {
910                 'id': '6SJNVb0GnPI',
911                 'ext': 'mp4',
912                 'title': 'Race Differences in Intelligence',
913                 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
914                 'duration': 965,
915                 'upload_date': '20140124',
916                 'uploader': 'New Century Foundation',
917                 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
918                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
919             },
920             'params': {
921                 'skip_download': True,
922             },
923             'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
924         },
925         {
926             # itag 212
927             'url': '1t24XAntNCY',
928             'only_matching': True,
929         },
930         {
931             # geo restricted to JP
932             'url': 'sJL6WA-aGkQ',
933             'only_matching': True,
934         },
935         {
936             'url': 'https://invidio.us/watch?v=BaW_jenozKc',
937             'only_matching': True,
938         },
939         {
940             'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
941             'only_matching': True,
942         },
943         {
944             # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
945             'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
946             'only_matching': True,
947         },
948         {
949             # DRM protected
950             'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
951             'only_matching': True,
952         },
953         {
954             # Video with unsupported adaptive stream type formats
955             'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
956             'info_dict': {
957                 'id': 'Z4Vy8R84T1U',
958                 'ext': 'mp4',
959                 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
960                 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
961                 'duration': 433,
962                 'upload_date': '20130923',
963                 'uploader': 'Amelia Putri Harwita',
964                 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
965                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
966                 'formats': 'maxcount:10',
967             },
968             'params': {
969                 'skip_download': True,
970                 'youtube_include_dash_manifest': False,
971             },
972             'skip': 'not actual anymore',
973         },
974         {
975             # Youtube Music Auto-generated description
976             'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
977             'info_dict': {
978                 'id': 'MgNrAu2pzNs',
979                 'ext': 'mp4',
980                 'title': 'Voyeur Girl',
981                 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
982                 'upload_date': '20190312',
983                 'uploader': 'Stephen - Topic',
984                 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
985                 'artist': 'Stephen',
986                 'track': 'Voyeur Girl',
987                 'album': 'it\'s too much love to know my dear',
988                 'release_date': '20190313',
989                 'release_year': 2019,
990             },
991             'params': {
992                 'skip_download': True,
993             },
994         },
995         {
996             'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
997             'only_matching': True,
998         },
999         {
1000             # invalid -> valid video id redirection
1001             'url': 'DJztXj2GPfl',
1002             'info_dict': {
1003                 'id': 'DJztXj2GPfk',
1004                 'ext': 'mp4',
1005                 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1006                 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1007                 'upload_date': '20090125',
1008                 'uploader': 'Prochorowka',
1009                 'uploader_id': 'Prochorowka',
1010                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1011                 'artist': 'Panjabi MC',
1012                 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1013                 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1014             },
1015             'params': {
1016                 'skip_download': True,
1017             },
1018             'skip': 'Video unavailable',
1019         },
1020         {
1021             # empty description results in an empty string
1022             'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1023             'info_dict': {
1024                 'id': 'x41yOUIvK2k',
1025                 'ext': 'mp4',
1026                 'title': 'IMG 3456',
1027                 'description': '',
1028                 'upload_date': '20170613',
1029                 'uploader_id': 'ElevageOrVert',
1030                 'uploader': 'ElevageOrVert',
1031             },
1032             'params': {
1033                 'skip_download': True,
1034             },
1035         },
1036         {
1037             # with '};' inside yt initial data (see [1])
1038             # see [2] for an example with '};' inside ytInitialPlayerResponse
1039             # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1040             # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1041             'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1042             'info_dict': {
1043                 'id': 'CHqg6qOn4no',
1044                 'ext': 'mp4',
1045                 'title': 'Part 77   Sort a list of simple types in c#',
1046                 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1047                 'upload_date': '20130831',
1048                 'uploader_id': 'kudvenkat',
1049                 'uploader': 'kudvenkat',
1050             },
1051             'params': {
1052                 'skip_download': True,
1053             },
1054         },
1055         {
1056             # another example of '};' in ytInitialData
1057             'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1058             'only_matching': True,
1059         },
1060         {
1061             'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1062             'only_matching': True,
1063         },
1064         {
1065             # https://github.com/ytdl-org/youtube-dl/pull/28094
1066             'url': 'OtqTfy26tG0',
1067             'info_dict': {
1068                 'id': 'OtqTfy26tG0',
1069                 'ext': 'mp4',
1070                 'title': 'Burn Out',
1071                 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1072                 'upload_date': '20141120',
1073                 'uploader': 'The Cinematic Orchestra - Topic',
1074                 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1075                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1076                 'artist': 'The Cinematic Orchestra',
1077                 'track': 'Burn Out',
1078                 'album': 'Every Day',
1079                 'release_data': None,
1080                 'release_year': None,
1081             },
1082             'params': {
1083                 'skip_download': True,
1084             },
1085         },
1086         {
1087             # controversial video, only works with bpctr when authenticated with cookies
1088             'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1089             'only_matching': True,
1090         },
1091         {
1092             # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
1093             'url': 'cBvYw8_A0vQ',
1094             'info_dict': {
1095                 'id': 'cBvYw8_A0vQ',
1096                 'ext': 'mp4',
1097                 'title': '4K Ueno Okachimachi  Street  Scenes  上野御徒町歩き',
1098                 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
1099                 'upload_date': '20201120',
1100                 'uploader': 'Walk around Japan',
1101                 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
1102                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
1103             },
1104             'params': {
1105                 'skip_download': True,
1106             },
1107         },
1108     ]
1109     _formats = {
1110         '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1111         '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1112         '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
1113         '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
1114         '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
1115         '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1116         '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1117         '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1118         # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
1119         '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
1120         '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1121         '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1122         '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1123         '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1124         '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
1125         '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
1126         '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1127         '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1128
1129
1130         # 3D videos
1131         '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1132         '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1133         '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1134         '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1135         '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
1136         '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1137         '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1138
1139         # Apple HTTP Live Streaming
1140         '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1141         '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1142         '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1143         '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1144         '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1145         '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1146         '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1147         '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
1148
1149         # DASH mp4 video
1150         '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
1151         '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
1152         '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1153         '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
1154         '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
1155         '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'},  # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
1156         '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
1157         '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1158         '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
1159         '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1160         '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1161         '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
1162
1163         # Dash mp4 audio
1164         '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
1165         '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
1166         '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
1167         '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1168         '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1169         '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
1170         '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
1171
1172         # Dash webm
1173         '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1174         '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1175         '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1176         '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1177         '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1178         '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1179         '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
1180         '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1181         '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1182         '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1183         '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1184         '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1185         '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1186         '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1187         '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1188         # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
1189         '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1190         '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1191         '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1192         '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1193         '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1194         '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1195
1196         # Dash webm audio
1197         '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
1198         '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
1199
1200         # Dash webm audio with opus inside
1201         '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
1202         '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
1203         '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
1204
1205         # RTMP (unnamed)
1206         '_rtmp': {'protocol': 'rtmp'},
1207
1208         # av01 video only formats sometimes served with "unknown" codecs
1209         '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1210         '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1211         '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1212         '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1213     }
1214
1215     @classmethod
1216     def suitable(cls, url):
1217         # Hack for lazy extractors until more generic solution is implemented
1218         # (see #28780)
1219         from .youtube import parse_qs
1220         qs = parse_qs(url)
1221         if qs.get('list', [None])[0]:
1222             return False
1223         return super(YoutubeIE, cls).suitable(url)
1224
1225     def __init__(self, *args, **kwargs):
1226         super(YoutubeIE, self).__init__(*args, **kwargs)
1227         self._code_cache = {}
1228         self._player_cache = {}
1229
1230     def _signature_cache_id(self, example_sig):
1231         """ Return a string representation of a signature """
1232         return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
1233
1234     @classmethod
1235     def _extract_player_info(cls, player_url):
1236         for player_re in cls._PLAYER_INFO_RE:
1237             id_m = re.search(player_re, player_url)
1238             if id_m:
1239                 break
1240         else:
1241             raise ExtractorError('Cannot identify player %r' % player_url)
1242         return id_m.group('id')
1243
1244     def _extract_signature_function(self, video_id, player_url, example_sig):
1245         player_id = self._extract_player_info(player_url)
1246
1247         # Read from filesystem cache
1248         func_id = 'js_%s_%s' % (
1249             player_id, self._signature_cache_id(example_sig))
1250         assert os.path.basename(func_id) == func_id
1251
1252         cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
1253         if cache_spec is not None:
1254             return lambda s: ''.join(s[i] for i in cache_spec)
1255
1256         if player_id not in self._code_cache:
1257             self._code_cache[player_id] = self._download_webpage(
1258                 player_url, video_id,
1259                 note='Downloading player ' + player_id,
1260                 errnote='Download of %s failed' % player_url)
1261         code = self._code_cache[player_id]
1262         res = self._parse_sig_js(code)
1263
1264         test_string = ''.join(map(compat_chr, range(len(example_sig))))
1265         cache_res = res(test_string)
1266         cache_spec = [ord(c) for c in cache_res]
1267
1268         self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
1269         return res
1270
1271     def _print_sig_code(self, func, example_sig):
1272         def gen_sig_code(idxs):
1273             def _genslice(start, end, step):
1274                 starts = '' if start == 0 else str(start)
1275                 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
1276                 steps = '' if step == 1 else (':%d' % step)
1277                 return 's[%s%s%s]' % (starts, ends, steps)
1278
1279             step = None
1280             # Quelch pyflakes warnings - start will be set when step is set
1281             start = '(Never used)'
1282             for i, prev in zip(idxs[1:], idxs[:-1]):
1283                 if step is not None:
1284                     if i - prev == step:
1285                         continue
1286                     yield _genslice(start, prev, step)
1287                     step = None
1288                     continue
1289                 if i - prev in [-1, 1]:
1290                     step = i - prev
1291                     start = prev
1292                     continue
1293                 else:
1294                     yield 's[%d]' % prev
1295             if step is None:
1296                 yield 's[%d]' % i
1297             else:
1298                 yield _genslice(start, i, step)
1299
1300         test_string = ''.join(map(compat_chr, range(len(example_sig))))
1301         cache_res = func(test_string)
1302         cache_spec = [ord(c) for c in cache_res]
1303         expr_code = ' + '.join(gen_sig_code(cache_spec))
1304         signature_id_tuple = '(%s)' % (
1305             ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
1306         code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1307                 '    return %s\n') % (signature_id_tuple, expr_code)
1308         self.to_screen('Extracted signature function:\n' + code)
1309
1310     def _parse_sig_js(self, jscode):
1311         funcname = self._search_regex(
1312             (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1313              r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1314              r'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1315              r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1316              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+\)',
1317              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*\)',
1318              r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1319              # Obsolete patterns
1320              r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1321              r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
1322              r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1323              r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1324              r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1325              r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1326              r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1327              r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
1328             jscode, 'Initial JS player signature function name', group='sig')
1329
1330         jsi = JSInterpreter(jscode)
1331         initial_function = jsi.extract_function(funcname)
1332         return lambda s: initial_function([s])
1333
1334     def _decrypt_signature(self, s, video_id, player_url):
1335         """Turn the encrypted s field into a working signature"""
1336
1337         if player_url is None:
1338             raise ExtractorError('Cannot decrypt signature without player_url')
1339
1340         if player_url.startswith('//'):
1341             player_url = 'https:' + player_url
1342         elif not re.match(r'https?://', player_url):
1343             player_url = compat_urlparse.urljoin(
1344                 'https://www.youtube.com', player_url)
1345         try:
1346             player_id = (player_url, self._signature_cache_id(s))
1347             if player_id not in self._player_cache:
1348                 func = self._extract_signature_function(
1349                     video_id, player_url, s
1350                 )
1351                 self._player_cache[player_id] = func
1352             func = self._player_cache[player_id]
1353             if self._downloader.params.get('youtube_print_sig_code'):
1354                 self._print_sig_code(func, s)
1355             return func(s)
1356         except Exception as e:
1357             tb = traceback.format_exc()
1358             raise ExtractorError(
1359                 'Signature extraction failed: ' + tb, cause=e)
1360
1361     def _mark_watched(self, video_id, player_response):
1362         playback_url = url_or_none(try_get(
1363             player_response,
1364             lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']))
1365         if not playback_url:
1366             return
1367         parsed_playback_url = compat_urlparse.urlparse(playback_url)
1368         qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1369
1370         # cpn generation algorithm is reverse engineered from base.js.
1371         # In fact it works even with dummy cpn.
1372         CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
1373         cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1374
1375         qs.update({
1376             'ver': ['2'],
1377             'cpn': [cpn],
1378         })
1379         playback_url = compat_urlparse.urlunparse(
1380             parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1381
1382         self._download_webpage(
1383             playback_url, video_id, 'Marking watched',
1384             'Unable to mark watched', fatal=False)
1385
1386     @staticmethod
1387     def _extract_urls(webpage):
1388         # Embedded YouTube player
1389         entries = [
1390             unescapeHTML(mobj.group('url'))
1391             for mobj in re.finditer(r'''(?x)
1392             (?:
1393                 <iframe[^>]+?src=|
1394                 data-video-url=|
1395                 <embed[^>]+?src=|
1396                 embedSWF\(?:\s*|
1397                 <object[^>]+data=|
1398                 new\s+SWFObject\(
1399             )
1400             (["\'])
1401                 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1402                 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1403             \1''', webpage)]
1404
1405         # lazyYT YouTube embed
1406         entries.extend(list(map(
1407             unescapeHTML,
1408             re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
1409
1410         # Wordpress "YouTube Video Importer" plugin
1411         matches = re.findall(r'''(?x)<div[^>]+
1412             class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
1413             data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
1414         entries.extend(m[-1] for m in matches)
1415
1416         return entries
1417
1418     @staticmethod
1419     def _extract_url(webpage):
1420         urls = YoutubeIE._extract_urls(webpage)
1421         return urls[0] if urls else None
1422
1423     @classmethod
1424     def extract_id(cls, url):
1425         mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1426         if mobj is None:
1427             raise ExtractorError('Invalid URL: %s' % url)
1428         video_id = mobj.group(2)
1429         return video_id
1430
1431     def _extract_chapters_from_json(self, data, video_id, duration):
1432         chapters_list = try_get(
1433             data,
1434             lambda x: x['playerOverlays']
1435                        ['playerOverlayRenderer']
1436                        ['decoratedPlayerBarRenderer']
1437                        ['decoratedPlayerBarRenderer']
1438                        ['playerBar']
1439                        ['chapteredPlayerBarRenderer']
1440                        ['chapters'],
1441             list)
1442         if not chapters_list:
1443             return
1444
1445         def chapter_time(chapter):
1446             return float_or_none(
1447                 try_get(
1448                     chapter,
1449                     lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1450                     int),
1451                 scale=1000)
1452         chapters = []
1453         for next_num, chapter in enumerate(chapters_list, start=1):
1454             start_time = chapter_time(chapter)
1455             if start_time is None:
1456                 continue
1457             end_time = (chapter_time(chapters_list[next_num])
1458                         if next_num < len(chapters_list) else duration)
1459             if end_time is None:
1460                 continue
1461             title = try_get(
1462                 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1463                 compat_str)
1464             chapters.append({
1465                 'start_time': start_time,
1466                 'end_time': end_time,
1467                 'title': title,
1468             })
1469         return chapters
1470
1471     def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1472         return self._parse_json(self._search_regex(
1473             (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1474              regex), webpage, name, default='{}'), video_id, fatal=False)
1475
1476     def _real_extract(self, url):
1477         url, smuggled_data = unsmuggle_url(url, {})
1478         video_id = self._match_id(url)
1479         base_url = self.http_scheme() + '//www.youtube.com/'
1480         webpage_url = base_url + 'watch?v=' + video_id
1481         webpage = self._download_webpage(
1482             webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1483
1484         player_response = None
1485         if webpage:
1486             player_response = self._extract_yt_initial_variable(
1487                 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1488                 video_id, 'initial player response')
1489         if not player_response:
1490             player_response = self._call_api(
1491                 'player', {'videoId': video_id}, video_id)
1492
1493         playability_status = player_response.get('playabilityStatus') or {}
1494         if playability_status.get('reason') == 'Sign in to confirm your age':
1495             pr = self._parse_json(try_get(compat_parse_qs(
1496                 self._download_webpage(
1497                     base_url + 'get_video_info', video_id,
1498                     'Refetching age-gated info webpage',
1499                     'unable to download video info webpage', query={
1500                         'video_id': video_id,
1501                         'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1502                         'html5': 1,
1503                     }, fatal=False)),
1504                 lambda x: x['player_response'][0],
1505                 compat_str) or '{}', video_id)
1506             if pr:
1507                 player_response = pr
1508
1509         trailer_video_id = try_get(
1510             playability_status,
1511             lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1512             compat_str)
1513         if trailer_video_id:
1514             return self.url_result(
1515                 trailer_video_id, self.ie_key(), trailer_video_id)
1516
1517         def get_text(x):
1518             if not x:
1519                 return
1520             text = x.get('simpleText')
1521             if text and isinstance(text, compat_str):
1522                 return text
1523             runs = x.get('runs')
1524             if not isinstance(runs, list):
1525                 return
1526             return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
1527
1528         search_meta = (
1529             lambda x: self._html_search_meta(x, webpage, default=None)) \
1530             if webpage else lambda x: None
1531
1532         video_details = player_response.get('videoDetails') or {}
1533         microformat = try_get(
1534             player_response,
1535             lambda x: x['microformat']['playerMicroformatRenderer'],
1536             dict) or {}
1537         video_title = video_details.get('title') \
1538             or get_text(microformat.get('title')) \
1539             or search_meta(['og:title', 'twitter:title', 'title'])
1540         video_description = video_details.get('shortDescription')
1541
1542         if not smuggled_data.get('force_singlefeed', False):
1543             if not self._downloader.params.get('noplaylist'):
1544                 multifeed_metadata_list = try_get(
1545                     player_response,
1546                     lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1547                     compat_str)
1548                 if multifeed_metadata_list:
1549                     entries = []
1550                     feed_ids = []
1551                     for feed in multifeed_metadata_list.split(','):
1552                         # Unquote should take place before split on comma (,) since textual
1553                         # fields may contain comma as well (see
1554                         # https://github.com/ytdl-org/youtube-dl/issues/8536)
1555                         feed_data = compat_parse_qs(
1556                             compat_urllib_parse_unquote_plus(feed))
1557
1558                         def feed_entry(name):
1559                             return try_get(
1560                                 feed_data, lambda x: x[name][0], compat_str)
1561
1562                         feed_id = feed_entry('id')
1563                         if not feed_id:
1564                             continue
1565                         feed_title = feed_entry('title')
1566                         title = video_title
1567                         if feed_title:
1568                             title += ' (%s)' % feed_title
1569                         entries.append({
1570                             '_type': 'url_transparent',
1571                             'ie_key': 'Youtube',
1572                             'url': smuggle_url(
1573                                 base_url + 'watch?v=' + feed_data['id'][0],
1574                                 {'force_singlefeed': True}),
1575                             'title': title,
1576                         })
1577                         feed_ids.append(feed_id)
1578                     self.to_screen(
1579                         'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1580                         % (', '.join(feed_ids), video_id))
1581                     return self.playlist_result(
1582                         entries, video_id, video_title, video_description)
1583             else:
1584                 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1585
1586         formats = []
1587         itags = []
1588         itag_qualities = {}
1589         player_url = None
1590         q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1591         streaming_data = player_response.get('streamingData') or {}
1592         streaming_formats = streaming_data.get('formats') or []
1593         streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1594         for fmt in streaming_formats:
1595             if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1596                 continue
1597
1598             itag = str_or_none(fmt.get('itag'))
1599             quality = fmt.get('quality')
1600             if itag and quality:
1601                 itag_qualities[itag] = quality
1602             # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
1603             # (adding `&sq=0` to the URL) and parsing emsg box to determine the
1604             # number of fragment that would subsequently requested with (`&sq=N`)
1605             if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
1606                 continue
1607
1608             fmt_url = fmt.get('url')
1609             if not fmt_url:
1610                 sc = compat_parse_qs(fmt.get('signatureCipher'))
1611                 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1612                 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1613                 if not (sc and fmt_url and encrypted_sig):
1614                     continue
1615                 if not player_url:
1616                     if not webpage:
1617                         continue
1618                     player_url = self._search_regex(
1619                         r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1620                         webpage, 'player URL', fatal=False)
1621                 if not player_url:
1622                     continue
1623                 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1624                 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1625                 fmt_url += '&' + sp + '=' + signature
1626
1627             if itag:
1628                 itags.append(itag)
1629             tbr = float_or_none(
1630                 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
1631             dct = {
1632                 'asr': int_or_none(fmt.get('audioSampleRate')),
1633                 'filesize': int_or_none(fmt.get('contentLength')),
1634                 'format_id': itag,
1635                 'format_note': fmt.get('qualityLabel') or quality,
1636                 'fps': int_or_none(fmt.get('fps')),
1637                 'height': int_or_none(fmt.get('height')),
1638                 'quality': q(quality),
1639                 'tbr': tbr,
1640                 'url': fmt_url,
1641                 'width': fmt.get('width'),
1642             }
1643             mimetype = fmt.get('mimeType')
1644             if mimetype:
1645                 mobj = re.match(
1646                     r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
1647                 if mobj:
1648                     dct['ext'] = mimetype2ext(mobj.group(1))
1649                     dct.update(parse_codecs(mobj.group(2)))
1650             no_audio = dct.get('acodec') == 'none'
1651             no_video = dct.get('vcodec') == 'none'
1652             if no_audio:
1653                 dct['vbr'] = tbr
1654             if no_video:
1655                 dct['abr'] = tbr
1656             if no_audio or no_video:
1657                 dct['downloader_options'] = {
1658                     # Youtube throttles chunks >~10M
1659                     'http_chunk_size': 10485760,
1660                 }
1661                 if dct.get('ext'):
1662                     dct['container'] = dct['ext'] + '_dash'
1663             formats.append(dct)
1664
1665         hls_manifest_url = streaming_data.get('hlsManifestUrl')
1666         if hls_manifest_url:
1667             for f in self._extract_m3u8_formats(
1668                     hls_manifest_url, video_id, 'mp4', fatal=False):
1669                 itag = self._search_regex(
1670                     r'/itag/(\d+)', f['url'], 'itag', default=None)
1671                 if itag:
1672                     f['format_id'] = itag
1673                 formats.append(f)
1674
1675         if self._downloader.params.get('youtube_include_dash_manifest', True):
1676             dash_manifest_url = streaming_data.get('dashManifestUrl')
1677             if dash_manifest_url:
1678                 for f in self._extract_mpd_formats(
1679                         dash_manifest_url, video_id, fatal=False):
1680                     itag = f['format_id']
1681                     if itag in itags:
1682                         continue
1683                     if itag in itag_qualities:
1684                         f['quality'] = q(itag_qualities[itag])
1685                     filesize = int_or_none(self._search_regex(
1686                         r'/clen/(\d+)', f.get('fragment_base_url')
1687                         or f['url'], 'file size', default=None))
1688                     if filesize:
1689                         f['filesize'] = filesize
1690                     formats.append(f)
1691
1692         if not formats:
1693             if streaming_data.get('licenseInfos'):
1694                 raise ExtractorError(
1695                     'This video is DRM protected.', expected=True)
1696             pemr = try_get(
1697                 playability_status,
1698                 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
1699                 dict) or {}
1700             reason = get_text(pemr.get('reason')) or playability_status.get('reason')
1701             subreason = pemr.get('subreason')
1702             if subreason:
1703                 subreason = clean_html(get_text(subreason))
1704                 if subreason == 'The uploader has not made this video available in your country.':
1705                     countries = microformat.get('availableCountries')
1706                     if not countries:
1707                         regions_allowed = search_meta('regionsAllowed')
1708                         countries = regions_allowed.split(',') if regions_allowed else None
1709                     self.raise_geo_restricted(
1710                         subreason, countries)
1711                 reason += '\n' + subreason
1712             if reason:
1713                 raise ExtractorError(reason, expected=True)
1714
1715         self._sort_formats(formats)
1716
1717         keywords = video_details.get('keywords') or []
1718         if not keywords and webpage:
1719             keywords = [
1720                 unescapeHTML(m.group('content'))
1721                 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
1722         for keyword in keywords:
1723             if keyword.startswith('yt:stretch='):
1724                 mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
1725                 if mobj:
1726                     # NB: float is intentional for forcing float division
1727                     w, h = (float(v) for v in mobj.groups())
1728                     if w > 0 and h > 0:
1729                         ratio = w / h
1730                         for f in formats:
1731                             if f.get('vcodec') != 'none':
1732                                 f['stretched_ratio'] = ratio
1733                         break
1734
1735         thumbnails = []
1736         for container in (video_details, microformat):
1737             for thumbnail in (try_get(
1738                     container,
1739                     lambda x: x['thumbnail']['thumbnails'], list) or []):
1740                 thumbnail_url = thumbnail.get('url')
1741                 if not thumbnail_url:
1742                     continue
1743                 thumbnails.append({
1744                     'height': int_or_none(thumbnail.get('height')),
1745                     'url': thumbnail_url,
1746                     'width': int_or_none(thumbnail.get('width')),
1747                 })
1748             if thumbnails:
1749                 break
1750         else:
1751             thumbnail = search_meta(['og:image', 'twitter:image'])
1752             if thumbnail:
1753                 thumbnails = [{'url': thumbnail}]
1754
1755         category = microformat.get('category') or search_meta('genre')
1756         channel_id = video_details.get('channelId') \
1757             or microformat.get('externalChannelId') \
1758             or search_meta('channelId')
1759         duration = int_or_none(
1760             video_details.get('lengthSeconds')
1761             or microformat.get('lengthSeconds')) \
1762             or parse_duration(search_meta('duration'))
1763         is_live = video_details.get('isLive')
1764         owner_profile_url = microformat.get('ownerProfileUrl')
1765
1766         info = {
1767             'id': video_id,
1768             'title': self._live_title(video_title) if is_live else video_title,
1769             'formats': formats,
1770             'thumbnails': thumbnails,
1771             'description': video_description,
1772             'upload_date': unified_strdate(
1773                 microformat.get('uploadDate')
1774                 or search_meta('uploadDate')),
1775             'uploader': video_details['author'],
1776             'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
1777             'uploader_url': owner_profile_url,
1778             'channel_id': channel_id,
1779             'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
1780             'duration': duration,
1781             'view_count': int_or_none(
1782                 video_details.get('viewCount')
1783                 or microformat.get('viewCount')
1784                 or search_meta('interactionCount')),
1785             'average_rating': float_or_none(video_details.get('averageRating')),
1786             'age_limit': 18 if (
1787                 microformat.get('isFamilySafe') is False
1788                 or search_meta('isFamilyFriendly') == 'false'
1789                 or search_meta('og:restrictions:age') == '18+') else 0,
1790             'webpage_url': webpage_url,
1791             'categories': [category] if category else None,
1792             'tags': keywords,
1793             'is_live': is_live,
1794         }
1795
1796         pctr = try_get(
1797             player_response,
1798             lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
1799         if pctr:
1800             def process_language(container, base_url, lang_code, query):
1801                 lang_subs = []
1802                 for fmt in self._SUBTITLE_FORMATS:
1803                     query.update({
1804                         'fmt': fmt,
1805                     })
1806                     lang_subs.append({
1807                         'ext': fmt,
1808                         'url': update_url_query(base_url, query),
1809                     })
1810                 container[lang_code] = lang_subs
1811
1812             subtitles = {}
1813             for caption_track in (pctr.get('captionTracks') or []):
1814                 base_url = caption_track.get('baseUrl')
1815                 if not base_url:
1816                     continue
1817                 if caption_track.get('kind') != 'asr':
1818                     lang_code = caption_track.get('languageCode')
1819                     if not lang_code:
1820                         continue
1821                     process_language(
1822                         subtitles, base_url, lang_code, {})
1823                     continue
1824                 automatic_captions = {}
1825                 for translation_language in (pctr.get('translationLanguages') or []):
1826                     translation_language_code = translation_language.get('languageCode')
1827                     if not translation_language_code:
1828                         continue
1829                     process_language(
1830                         automatic_captions, base_url, translation_language_code,
1831                         {'tlang': translation_language_code})
1832                 info['automatic_captions'] = automatic_captions
1833             info['subtitles'] = subtitles
1834
1835         parsed_url = compat_urllib_parse_urlparse(url)
1836         for component in [parsed_url.fragment, parsed_url.query]:
1837             query = compat_parse_qs(component)
1838             for k, v in query.items():
1839                 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
1840                     d_k += '_time'
1841                     if d_k not in info and k in s_ks:
1842                         info[d_k] = parse_duration(query[k][0])
1843
1844         if video_description:
1845             mobj = re.search(r'(?s)(?P<track>[^·\n]+)·(?P<artist>[^\n]+)\n+(?P<album>[^\n]+)(?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?(?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?(.+?\nArtist\s*:\s*(?P<clean_artist>[^\n]+))?.+\nAuto-generated by YouTube\.\s*$', video_description)
1846             if mobj:
1847                 release_year = mobj.group('release_year')
1848                 release_date = mobj.group('release_date')
1849                 if release_date:
1850                     release_date = release_date.replace('-', '')
1851                     if not release_year:
1852                         release_year = release_date[:4]
1853                 info.update({
1854                     'album': mobj.group('album'.strip()),
1855                     'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
1856                     'track': mobj.group('track').strip(),
1857                     'release_date': release_date,
1858                     'release_year': int_or_none(release_year),
1859                 })
1860
1861         initial_data = None
1862         if webpage:
1863             initial_data = self._extract_yt_initial_variable(
1864                 webpage, self._YT_INITIAL_DATA_RE, video_id,
1865                 'yt initial data')
1866         if not initial_data:
1867             initial_data = self._call_api(
1868                 'next', {'videoId': video_id}, video_id, fatal=False)
1869
1870         if initial_data:
1871             chapters = self._extract_chapters_from_json(
1872                 initial_data, video_id, duration)
1873             if not chapters:
1874                 for engagment_pannel in (initial_data.get('engagementPanels') or []):
1875                     contents = try_get(
1876                         engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
1877                         list)
1878                     if not contents:
1879                         continue
1880
1881                     def chapter_time(mmlir):
1882                         return parse_duration(
1883                             get_text(mmlir.get('timeDescription')))
1884
1885                     chapters = []
1886                     for next_num, content in enumerate(contents, start=1):
1887                         mmlir = content.get('macroMarkersListItemRenderer') or {}
1888                         start_time = chapter_time(mmlir)
1889                         end_time = chapter_time(try_get(
1890                             contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
1891                             if next_num < len(contents) else duration
1892                         if start_time is None or end_time is None:
1893                             continue
1894                         chapters.append({
1895                             'start_time': start_time,
1896                             'end_time': end_time,
1897                             'title': get_text(mmlir.get('title')),
1898                         })
1899                     if chapters:
1900                         break
1901             if chapters:
1902                 info['chapters'] = chapters
1903
1904             contents = try_get(
1905                 initial_data,
1906                 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
1907                 list) or []
1908             for content in contents:
1909                 vpir = content.get('videoPrimaryInfoRenderer')
1910                 if vpir:
1911                     stl = vpir.get('superTitleLink')
1912                     if stl:
1913                         stl = get_text(stl)
1914                         if try_get(
1915                                 vpir,
1916                                 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
1917                             info['location'] = stl
1918                         else:
1919                             mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
1920                             if mobj:
1921                                 info.update({
1922                                     'series': mobj.group(1),
1923                                     'season_number': int(mobj.group(2)),
1924                                     'episode_number': int(mobj.group(3)),
1925                                 })
1926                     for tlb in (try_get(
1927                             vpir,
1928                             lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
1929                             list) or []):
1930                         tbr = tlb.get('toggleButtonRenderer') or {}
1931                         for getter, regex in [(
1932                                 lambda x: x['defaultText']['accessibility']['accessibilityData'],
1933                                 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
1934                                     lambda x: x['accessibility'],
1935                                     lambda x: x['accessibilityData']['accessibilityData'],
1936                                 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
1937                             label = (try_get(tbr, getter, dict) or {}).get('label')
1938                             if label:
1939                                 mobj = re.match(regex, label)
1940                                 if mobj:
1941                                     info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
1942                                     break
1943                     sbr_tooltip = try_get(
1944                         vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
1945                     if sbr_tooltip:
1946                         like_count, dislike_count = sbr_tooltip.split(' / ')
1947                         info.update({
1948                             'like_count': str_to_int(like_count),
1949                             'dislike_count': str_to_int(dislike_count),
1950                         })
1951                 vsir = content.get('videoSecondaryInfoRenderer')
1952                 if vsir:
1953                     info['channel'] = get_text(try_get(
1954                         vsir,
1955                         lambda x: x['owner']['videoOwnerRenderer']['title'],
1956                         dict))
1957                     rows = try_get(
1958                         vsir,
1959                         lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
1960                         list) or []
1961                     multiple_songs = False
1962                     for row in rows:
1963                         if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
1964                             multiple_songs = True
1965                             break
1966                     for row in rows:
1967                         mrr = row.get('metadataRowRenderer') or {}
1968                         mrr_title = mrr.get('title')
1969                         if not mrr_title:
1970                             continue
1971                         mrr_title = get_text(mrr['title'])
1972                         mrr_contents_text = get_text(mrr['contents'][0])
1973                         if mrr_title == 'License':
1974                             info['license'] = mrr_contents_text
1975                         elif not multiple_songs:
1976                             if mrr_title == 'Album':
1977                                 info['album'] = mrr_contents_text
1978                             elif mrr_title == 'Artist':
1979                                 info['artist'] = mrr_contents_text
1980                             elif mrr_title == 'Song':
1981                                 info['track'] = mrr_contents_text
1982
1983         for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
1984             v = info.get(s_k)
1985             if v:
1986                 info[d_k] = v
1987
1988         self.mark_watched(video_id, player_response)
1989
1990         return info
1991
1992
1993 class YoutubeTabIE(YoutubeBaseInfoExtractor):
1994     IE_DESC = 'YouTube.com tab'
1995     _VALID_URL = r'''(?x)
1996                     https?://
1997                         (?:\w+\.)?
1998                         (?:
1999                             youtube(?:kids)?\.com|
2000                             invidio\.us
2001                         )/
2002                         (?:
2003                             (?:channel|c|user|feed|hashtag)/|
2004                             (?:playlist|watch)\?.*?\blist=|
2005                             (?!(?:watch|embed|v|e)\b)
2006                         )
2007                         (?P<id>[^/?\#&]+)
2008                     '''
2009     IE_NAME = 'youtube:tab'
2010
2011     _TESTS = [{
2012         # playlists, multipage
2013         'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2014         'playlist_mincount': 94,
2015         'info_dict': {
2016             'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2017             'title': 'Игорь Клейнер - Playlists',
2018             'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2019         },
2020     }, {
2021         # playlists, multipage, different order
2022         'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2023         'playlist_mincount': 94,
2024         'info_dict': {
2025             'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2026             'title': 'Игорь Клейнер - Playlists',
2027             'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2028         },
2029     }, {
2030         # playlists, series
2031         'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
2032         'playlist_mincount': 5,
2033         'info_dict': {
2034             'id': 'UCYO_jab_esuFRV4b17AJtAw',
2035             'title': '3Blue1Brown - Playlists',
2036             'description': 'md5:e1384e8a133307dd10edee76e875d62f',
2037         },
2038     }, {
2039         # playlists, singlepage
2040         'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2041         'playlist_mincount': 4,
2042         'info_dict': {
2043             'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2044             'title': 'ThirstForScience - Playlists',
2045             'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2046         }
2047     }, {
2048         'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2049         'only_matching': True,
2050     }, {
2051         # basic, single video playlist
2052         'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2053         'info_dict': {
2054             'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2055             'uploader': 'Sergey M.',
2056             'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2057             'title': 'youtube-dl public playlist',
2058         },
2059         'playlist_count': 1,
2060     }, {
2061         # empty playlist
2062         'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2063         'info_dict': {
2064             'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2065             'uploader': 'Sergey M.',
2066             'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2067             'title': 'youtube-dl empty playlist',
2068         },
2069         'playlist_count': 0,
2070     }, {
2071         # Home tab
2072         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2073         'info_dict': {
2074             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2075             'title': 'lex will - Home',
2076             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2077         },
2078         'playlist_mincount': 2,
2079     }, {
2080         # Videos tab
2081         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2082         'info_dict': {
2083             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2084             'title': 'lex will - Videos',
2085             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2086         },
2087         'playlist_mincount': 975,
2088     }, {
2089         # Videos tab, sorted by popular
2090         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2091         'info_dict': {
2092             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2093             'title': 'lex will - Videos',
2094             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2095         },
2096         'playlist_mincount': 199,
2097     }, {
2098         # Playlists tab
2099         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2100         'info_dict': {
2101             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2102             'title': 'lex will - Playlists',
2103             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2104         },
2105         'playlist_mincount': 17,
2106     }, {
2107         # Community tab
2108         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2109         'info_dict': {
2110             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2111             'title': 'lex will - Community',
2112             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2113         },
2114         'playlist_mincount': 18,
2115     }, {
2116         # Channels tab
2117         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2118         'info_dict': {
2119             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2120             'title': 'lex will - Channels',
2121             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2122         },
2123         'playlist_mincount': 138,
2124     }, {
2125         'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2126         'only_matching': True,
2127     }, {
2128         'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2129         'only_matching': True,
2130     }, {
2131         'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2132         'only_matching': True,
2133     }, {
2134         'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2135         'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2136         'info_dict': {
2137             'title': '29C3: Not my department',
2138             'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2139             'uploader': 'Christiaan008',
2140             'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2141         },
2142         'playlist_count': 96,
2143     }, {
2144         'note': 'Large playlist',
2145         'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2146         'info_dict': {
2147             'title': 'Uploads from Cauchemar',
2148             'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2149             'uploader': 'Cauchemar',
2150             'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2151         },
2152         'playlist_mincount': 1123,
2153     }, {
2154         # even larger playlist, 8832 videos
2155         'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2156         'only_matching': True,
2157     }, {
2158         'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2159         'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2160         'info_dict': {
2161             'title': 'Uploads from Interstellar Movie',
2162             'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2163             'uploader': 'Interstellar Movie',
2164             'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2165         },
2166         'playlist_mincount': 21,
2167     }, {
2168         # https://github.com/ytdl-org/youtube-dl/issues/21844
2169         'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2170         'info_dict': {
2171             'title': 'Data Analysis with Dr Mike Pound',
2172             'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2173             'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2174             'uploader': 'Computerphile',
2175         },
2176         'playlist_mincount': 11,
2177     }, {
2178         'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2179         'only_matching': True,
2180     }, {
2181         # Playlist URL that does not actually serve a playlist
2182         'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2183         'info_dict': {
2184             'id': 'FqZTN594JQw',
2185             'ext': 'webm',
2186             'title': "Smiley's People 01 detective, Adventure Series, Action",
2187             'uploader': 'STREEM',
2188             'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2189             'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2190             'upload_date': '20150526',
2191             'license': 'Standard YouTube License',
2192             'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2193             'categories': ['People & Blogs'],
2194             'tags': list,
2195             'view_count': int,
2196             'like_count': int,
2197             'dislike_count': int,
2198         },
2199         'params': {
2200             'skip_download': True,
2201         },
2202         'skip': 'This video is not available.',
2203         'add_ie': [YoutubeIE.ie_key()],
2204     }, {
2205         'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2206         'only_matching': True,
2207     }, {
2208         'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2209         'only_matching': True,
2210     }, {
2211         'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2212         'info_dict': {
2213             'id': '9Auq9mYxFEE',
2214             'ext': 'mp4',
2215             'title': 'Watch Sky News live',
2216             'uploader': 'Sky News',
2217             'uploader_id': 'skynews',
2218             'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2219             'upload_date': '20191102',
2220             'description': 'md5:78de4e1c2359d0ea3ed829678e38b662',
2221             'categories': ['News & Politics'],
2222             'tags': list,
2223             'like_count': int,
2224             'dislike_count': int,
2225         },
2226         'params': {
2227             'skip_download': True,
2228         },
2229     }, {
2230         'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2231         'info_dict': {
2232             'id': 'a48o2S1cPoo',
2233             'ext': 'mp4',
2234             'title': 'The Young Turks - Live Main Show',
2235             'uploader': 'The Young Turks',
2236             'uploader_id': 'TheYoungTurks',
2237             'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2238             'upload_date': '20150715',
2239             'license': 'Standard YouTube License',
2240             'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2241             'categories': ['News & Politics'],
2242             'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2243             'like_count': int,
2244             'dislike_count': int,
2245         },
2246         'params': {
2247             'skip_download': True,
2248         },
2249         'only_matching': True,
2250     }, {
2251         'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2252         'only_matching': True,
2253     }, {
2254         'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2255         'only_matching': True,
2256     }, {
2257         'url': 'https://www.youtube.com/feed/trending',
2258         'only_matching': True,
2259     }, {
2260         # needs auth
2261         'url': 'https://www.youtube.com/feed/library',
2262         'only_matching': True,
2263     }, {
2264         # needs auth
2265         'url': 'https://www.youtube.com/feed/history',
2266         'only_matching': True,
2267     }, {
2268         # needs auth
2269         'url': 'https://www.youtube.com/feed/subscriptions',
2270         'only_matching': True,
2271     }, {
2272         # needs auth
2273         'url': 'https://www.youtube.com/feed/watch_later',
2274         'only_matching': True,
2275     }, {
2276         # no longer available?
2277         'url': 'https://www.youtube.com/feed/recommended',
2278         'only_matching': True,
2279     }, {
2280         # inline playlist with not always working continuations
2281         'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2282         'only_matching': True,
2283     }, {
2284         'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2285         'only_matching': True,
2286     }, {
2287         'url': 'https://www.youtube.com/course',
2288         'only_matching': True,
2289     }, {
2290         'url': 'https://www.youtube.com/zsecurity',
2291         'only_matching': True,
2292     }, {
2293         'url': 'http://www.youtube.com/NASAgovVideo/videos',
2294         'only_matching': True,
2295     }, {
2296         'url': 'https://www.youtube.com/TheYoungTurks/live',
2297         'only_matching': True,
2298     }, {
2299         'url': 'https://www.youtube.com/hashtag/cctv9',
2300         'info_dict': {
2301             'id': 'cctv9',
2302             'title': '#cctv9',
2303         },
2304         'playlist_mincount': 350,
2305     }, {
2306         'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
2307         'only_matching': True,
2308     }]
2309
2310     @classmethod
2311     def suitable(cls, url):
2312         return False if YoutubeIE.suitable(url) else super(
2313             YoutubeTabIE, cls).suitable(url)
2314
2315     def _extract_channel_id(self, webpage):
2316         channel_id = self._html_search_meta(
2317             'channelId', webpage, 'channel id', default=None)
2318         if channel_id:
2319             return channel_id
2320         channel_url = self._html_search_meta(
2321             ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2322              'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2323              'twitter:app:url:googleplay'), webpage, 'channel url')
2324         return self._search_regex(
2325             r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2326             channel_url, 'channel id')
2327
2328     @staticmethod
2329     def _extract_grid_item_renderer(item):
2330         assert isinstance(item, dict)
2331         for key, renderer in item.items():
2332             if not key.startswith('grid') or not key.endswith('Renderer'):
2333                 continue
2334             if not isinstance(renderer, dict):
2335                 continue
2336             return renderer
2337
2338     def _grid_entries(self, grid_renderer):
2339         for item in grid_renderer['items']:
2340             if not isinstance(item, dict):
2341                 continue
2342             renderer = self._extract_grid_item_renderer(item)
2343             if not isinstance(renderer, dict):
2344                 continue
2345             title = try_get(
2346                 renderer, (lambda x: x['title']['runs'][0]['text'],
2347                            lambda x: x['title']['simpleText']), compat_str)
2348             # playlist
2349             playlist_id = renderer.get('playlistId')
2350             if playlist_id:
2351                 yield self.url_result(
2352                     'https://www.youtube.com/playlist?list=%s' % playlist_id,
2353                     ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2354                     video_title=title)
2355                 continue
2356             # video
2357             video_id = renderer.get('videoId')
2358             if video_id:
2359                 yield self._extract_video(renderer)
2360                 continue
2361             # channel
2362             channel_id = renderer.get('channelId')
2363             if channel_id:
2364                 title = try_get(
2365                     renderer, lambda x: x['title']['simpleText'], compat_str)
2366                 yield self.url_result(
2367                     'https://www.youtube.com/channel/%s' % channel_id,
2368                     ie=YoutubeTabIE.ie_key(), video_title=title)
2369                 continue
2370             # generic endpoint URL support
2371             ep_url = urljoin('https://www.youtube.com/', try_get(
2372                 renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
2373                 compat_str))
2374             if ep_url:
2375                 for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
2376                     if ie.suitable(ep_url):
2377                         yield self.url_result(
2378                             ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
2379                         break
2380
2381     def _shelf_entries_from_content(self, shelf_renderer):
2382         content = shelf_renderer.get('content')
2383         if not isinstance(content, dict):
2384             return
2385         renderer = content.get('gridRenderer')
2386         if renderer:
2387             # TODO: add support for nested playlists so each shelf is processed
2388             # as separate playlist
2389             # TODO: this includes only first N items
2390             for entry in self._grid_entries(renderer):
2391                 yield entry
2392         renderer = content.get('horizontalListRenderer')
2393         if renderer:
2394             # TODO
2395             pass
2396
2397     def _shelf_entries(self, shelf_renderer, skip_channels=False):
2398         ep = try_get(
2399             shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2400             compat_str)
2401         shelf_url = urljoin('https://www.youtube.com', ep)
2402         if shelf_url:
2403             # Skipping links to another channels, note that checking for
2404             # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2405             # will not work
2406             if skip_channels and '/channels?' in shelf_url:
2407                 return
2408             title = try_get(
2409                 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2410             yield self.url_result(shelf_url, video_title=title)
2411         # Shelf may not contain shelf URL, fallback to extraction from content
2412         for entry in self._shelf_entries_from_content(shelf_renderer):
2413             yield entry
2414
2415     def _playlist_entries(self, video_list_renderer):
2416         for content in video_list_renderer['contents']:
2417             if not isinstance(content, dict):
2418                 continue
2419             renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2420             if not isinstance(renderer, dict):
2421                 continue
2422             video_id = renderer.get('videoId')
2423             if not video_id:
2424                 continue
2425             yield self._extract_video(renderer)
2426
2427     def _video_entry(self, video_renderer):
2428         video_id = video_renderer.get('videoId')
2429         if video_id:
2430             return self._extract_video(video_renderer)
2431
2432     def _post_thread_entries(self, post_thread_renderer):
2433         post_renderer = try_get(
2434             post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2435         if not post_renderer:
2436             return
2437         # video attachment
2438         video_renderer = try_get(
2439             post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2440         video_id = None
2441         if video_renderer:
2442             entry = self._video_entry(video_renderer)
2443             if entry:
2444                 yield entry
2445         # inline video links
2446         runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2447         for run in runs:
2448             if not isinstance(run, dict):
2449                 continue
2450             ep_url = try_get(
2451                 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2452             if not ep_url:
2453                 continue
2454             if not YoutubeIE.suitable(ep_url):
2455                 continue
2456             ep_video_id = YoutubeIE._match_id(ep_url)
2457             if video_id == ep_video_id:
2458                 continue
2459             yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2460
2461     def _post_thread_continuation_entries(self, post_thread_continuation):
2462         contents = post_thread_continuation.get('contents')
2463         if not isinstance(contents, list):
2464             return
2465         for content in contents:
2466             renderer = content.get('backstagePostThreadRenderer')
2467             if not isinstance(renderer, dict):
2468                 continue
2469             for entry in self._post_thread_entries(renderer):
2470                 yield entry
2471
2472     def _rich_grid_entries(self, contents):
2473         for content in contents:
2474             video_renderer = try_get(content, lambda x: x['richItemRenderer']['content']['videoRenderer'], dict)
2475             if video_renderer:
2476                 entry = self._video_entry(video_renderer)
2477                 if entry:
2478                     yield entry
2479
2480     @staticmethod
2481     def _build_continuation_query(continuation, ctp=None):
2482         query = {
2483             'ctoken': continuation,
2484             'continuation': continuation,
2485         }
2486         if ctp:
2487             query['itct'] = ctp
2488         return query
2489
2490     @staticmethod
2491     def _extract_next_continuation_data(renderer):
2492         next_continuation = try_get(
2493             renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2494         if not next_continuation:
2495             return
2496         continuation = next_continuation.get('continuation')
2497         if not continuation:
2498             return
2499         ctp = next_continuation.get('clickTrackingParams')
2500         return YoutubeTabIE._build_continuation_query(continuation, ctp)
2501
2502     @classmethod
2503     def _extract_continuation(cls, renderer):
2504         next_continuation = cls._extract_next_continuation_data(renderer)
2505         if next_continuation:
2506             return next_continuation
2507         contents = []
2508         for key in ('contents', 'items'):
2509             contents.extend(try_get(renderer, lambda x: x[key], list) or [])
2510         for content in contents:
2511             if not isinstance(content, dict):
2512                 continue
2513             continuation_ep = try_get(
2514                 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2515                 dict)
2516             if not continuation_ep:
2517                 continue
2518             continuation = try_get(
2519                 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2520             if not continuation:
2521                 continue
2522             ctp = continuation_ep.get('clickTrackingParams')
2523             return YoutubeTabIE._build_continuation_query(continuation, ctp)
2524
2525     def _entries(self, tab, item_id, webpage):
2526         tab_content = try_get(tab, lambda x: x['content'], dict)
2527         if not tab_content:
2528             return
2529         slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
2530         if slr_renderer:
2531             is_channels_tab = tab.get('title') == 'Channels'
2532             continuation = None
2533             slr_contents = try_get(slr_renderer, lambda x: x['contents'], list) or []
2534             for slr_content in slr_contents:
2535                 if not isinstance(slr_content, dict):
2536                     continue
2537                 is_renderer = try_get(slr_content, lambda x: x['itemSectionRenderer'], dict)
2538                 if not is_renderer:
2539                     continue
2540                 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
2541                 for isr_content in isr_contents:
2542                     if not isinstance(isr_content, dict):
2543                         continue
2544                     renderer = isr_content.get('playlistVideoListRenderer')
2545                     if renderer:
2546                         for entry in self._playlist_entries(renderer):
2547                             yield entry
2548                         continuation = self._extract_continuation(renderer)
2549                         continue
2550                     renderer = isr_content.get('gridRenderer')
2551                     if renderer:
2552                         for entry in self._grid_entries(renderer):
2553                             yield entry
2554                         continuation = self._extract_continuation(renderer)
2555                         continue
2556                     renderer = isr_content.get('shelfRenderer')
2557                     if renderer:
2558                         for entry in self._shelf_entries(renderer, not is_channels_tab):
2559                             yield entry
2560                         continue
2561                     renderer = isr_content.get('backstagePostThreadRenderer')
2562                     if renderer:
2563                         for entry in self._post_thread_entries(renderer):
2564                             yield entry
2565                         continuation = self._extract_continuation(renderer)
2566                         continue
2567                     renderer = isr_content.get('videoRenderer')
2568                     if renderer:
2569                         entry = self._video_entry(renderer)
2570                         if entry:
2571                             yield entry
2572
2573                 if not continuation:
2574                     continuation = self._extract_continuation(is_renderer)
2575             if not continuation:
2576                 continuation = self._extract_continuation(slr_renderer)
2577         else:
2578             rich_grid_renderer = tab_content.get('richGridRenderer')
2579             if not rich_grid_renderer:
2580                 return
2581             for entry in self._rich_grid_entries(rich_grid_renderer.get('contents') or []):
2582                 yield entry
2583             continuation = self._extract_continuation(rich_grid_renderer)
2584
2585         ytcfg = self._extract_ytcfg(item_id, webpage)
2586         client_version = try_get(
2587             ytcfg, lambda x: x['INNERTUBE_CLIENT_VERSION'], compat_str) or '2.20210407.08.00'
2588
2589         headers = {
2590             'x-youtube-client-name': '1',
2591             'x-youtube-client-version': client_version,
2592             'content-type': 'application/json',
2593         }
2594
2595         context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'], dict) or {
2596             'client': {
2597                 'clientName': 'WEB',
2598                 'clientVersion': client_version,
2599             }
2600         }
2601         visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
2602
2603         identity_token = self._extract_identity_token(ytcfg, webpage)
2604         if identity_token:
2605             headers['x-youtube-identity-token'] = identity_token
2606
2607         data = {
2608             'context': context,
2609         }
2610
2611         for page_num in itertools.count(1):
2612             if not continuation:
2613                 break
2614             if visitor_data:
2615                 headers['x-goog-visitor-id'] = visitor_data
2616             data['continuation'] = continuation['continuation']
2617             data['clickTracking'] = {
2618                 'clickTrackingParams': continuation['itct']
2619             }
2620             count = 0
2621             retries = 3
2622             while count <= retries:
2623                 try:
2624                     # Downloading page may result in intermittent 5xx HTTP error
2625                     # that is usually worked around with a retry
2626                     response = self._download_json(
2627                         'https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
2628                         None, 'Downloading page %d%s' % (page_num, ' (retry #%d)' % count if count else ''),
2629                         headers=headers, data=json.dumps(data).encode('utf8'))
2630                     break
2631                 except ExtractorError as e:
2632                     if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
2633                         count += 1
2634                         if count <= retries:
2635                             continue
2636                     raise
2637             if not response:
2638                 break
2639
2640             visitor_data = try_get(
2641                 response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
2642
2643             continuation_contents = try_get(
2644                 response, lambda x: x['continuationContents'], dict)
2645             if continuation_contents:
2646                 continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
2647                 if continuation_renderer:
2648                     for entry in self._playlist_entries(continuation_renderer):
2649                         yield entry
2650                     continuation = self._extract_continuation(continuation_renderer)
2651                     continue
2652                 continuation_renderer = continuation_contents.get('gridContinuation')
2653                 if continuation_renderer:
2654                     for entry in self._grid_entries(continuation_renderer):
2655                         yield entry
2656                     continuation = self._extract_continuation(continuation_renderer)
2657                     continue
2658                 continuation_renderer = continuation_contents.get('itemSectionContinuation')
2659                 if continuation_renderer:
2660                     for entry in self._post_thread_continuation_entries(continuation_renderer):
2661                         yield entry
2662                     continuation = self._extract_continuation(continuation_renderer)
2663                     continue
2664
2665             on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
2666             continuation_items = try_get(
2667                 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
2668             if continuation_items:
2669                 continuation_item = continuation_items[0]
2670                 if not isinstance(continuation_item, dict):
2671                     continue
2672                 renderer = self._extract_grid_item_renderer(continuation_item)
2673                 if renderer:
2674                     grid_renderer = {'items': continuation_items}
2675                     for entry in self._grid_entries(grid_renderer):
2676                         yield entry
2677                     continuation = self._extract_continuation(grid_renderer)
2678                     continue
2679                 renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
2680                 if renderer:
2681                     video_list_renderer = {'contents': continuation_items}
2682                     for entry in self._playlist_entries(video_list_renderer):
2683                         yield entry
2684                     continuation = self._extract_continuation(video_list_renderer)
2685                     continue
2686                 renderer = continuation_item.get('backstagePostThreadRenderer')
2687                 if renderer:
2688                     continuation_renderer = {'contents': continuation_items}
2689                     for entry in self._post_thread_continuation_entries(continuation_renderer):
2690                         yield entry
2691                     continuation = self._extract_continuation(continuation_renderer)
2692                     continue
2693                 renderer = continuation_item.get('richItemRenderer')
2694                 if renderer:
2695                     for entry in self._rich_grid_entries(continuation_items):
2696                         yield entry
2697                     continuation = self._extract_continuation({'contents': continuation_items})
2698                     continue
2699
2700             break
2701
2702     @staticmethod
2703     def _extract_selected_tab(tabs):
2704         for tab in tabs:
2705             if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
2706                 return tab['tabRenderer']
2707         else:
2708             raise ExtractorError('Unable to find selected tab')
2709
2710     @staticmethod
2711     def _extract_uploader(data):
2712         uploader = {}
2713         sidebar_renderer = try_get(
2714             data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
2715         if sidebar_renderer:
2716             for item in sidebar_renderer:
2717                 if not isinstance(item, dict):
2718                     continue
2719                 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
2720                 if not isinstance(renderer, dict):
2721                     continue
2722                 owner = try_get(
2723                     renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
2724                 if owner:
2725                     uploader['uploader'] = owner.get('text')
2726                     uploader['uploader_id'] = try_get(
2727                         owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
2728                     uploader['uploader_url'] = urljoin(
2729                         'https://www.youtube.com/',
2730                         try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
2731         return uploader
2732
2733     @staticmethod
2734     def _extract_alert(data):
2735         alerts = []
2736         for alert in try_get(data, lambda x: x['alerts'], list) or []:
2737             if not isinstance(alert, dict):
2738                 continue
2739             alert_text = try_get(
2740                 alert, lambda x: x['alertRenderer']['text'], dict)
2741             if not alert_text:
2742                 continue
2743             text = try_get(
2744                 alert_text,
2745                 (lambda x: x['simpleText'], lambda x: x['runs'][0]['text']),
2746                 compat_str)
2747             if text:
2748                 alerts.append(text)
2749         return '\n'.join(alerts)
2750
2751     def _extract_from_tabs(self, item_id, webpage, data, tabs):
2752         selected_tab = self._extract_selected_tab(tabs)
2753         renderer = try_get(
2754             data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
2755         playlist_id = item_id
2756         title = description = None
2757         if renderer:
2758             channel_title = renderer.get('title') or item_id
2759             tab_title = selected_tab.get('title')
2760             title = channel_title or item_id
2761             if tab_title:
2762                 title += ' - %s' % tab_title
2763             description = renderer.get('description')
2764             playlist_id = renderer.get('externalId')
2765         else:
2766             renderer = try_get(
2767                 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
2768             if renderer:
2769                 title = renderer.get('title')
2770             else:
2771                 renderer = try_get(
2772                     data, lambda x: x['header']['hashtagHeaderRenderer'], dict)
2773                 if renderer:
2774                     title = try_get(renderer, lambda x: x['hashtag']['simpleText'])
2775         playlist = self.playlist_result(
2776             self._entries(selected_tab, item_id, webpage),
2777             playlist_id=playlist_id, playlist_title=title,
2778             playlist_description=description)
2779         playlist.update(self._extract_uploader(data))
2780         return playlist
2781
2782     def _extract_from_playlist(self, item_id, url, data, playlist):
2783         title = playlist.get('title') or try_get(
2784             data, lambda x: x['titleText']['simpleText'], compat_str)
2785         playlist_id = playlist.get('playlistId') or item_id
2786         # Inline playlist rendition continuation does not always work
2787         # at Youtube side, so delegating regular tab-based playlist URL
2788         # processing whenever possible.
2789         playlist_url = urljoin(url, try_get(
2790             playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2791             compat_str))
2792         if playlist_url and playlist_url != url:
2793             return self.url_result(
2794                 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2795                 video_title=title)
2796         return self.playlist_result(
2797             self._playlist_entries(playlist), playlist_id=playlist_id,
2798             playlist_title=title)
2799
2800     def _extract_identity_token(self, ytcfg, webpage):
2801         if ytcfg:
2802             token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
2803             if token:
2804                 return token
2805         return self._search_regex(
2806             r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
2807             'identity token', default=None)
2808
2809     def _real_extract(self, url):
2810         item_id = self._match_id(url)
2811         url = compat_urlparse.urlunparse(
2812             compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
2813         # Handle both video/playlist URLs
2814         qs = parse_qs(url)
2815         video_id = qs.get('v', [None])[0]
2816         playlist_id = qs.get('list', [None])[0]
2817         if video_id and playlist_id:
2818             if self._downloader.params.get('noplaylist'):
2819                 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
2820                 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
2821             self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
2822         webpage = self._download_webpage(url, item_id)
2823         data = self._extract_yt_initial_data(item_id, webpage)
2824         tabs = try_get(
2825             data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
2826         if tabs:
2827             return self._extract_from_tabs(item_id, webpage, data, tabs)
2828         playlist = try_get(
2829             data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
2830         if playlist:
2831             return self._extract_from_playlist(item_id, url, data, playlist)
2832         # Fallback to video extraction if no playlist alike page is recognized.
2833         # First check for the current video then try the v attribute of URL query.
2834         video_id = try_get(
2835             data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
2836             compat_str) or video_id
2837         if video_id:
2838             return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
2839         # Capture and output alerts
2840         alert = self._extract_alert(data)
2841         if alert:
2842             raise ExtractorError(alert, expected=True)
2843         # Failed to recognize
2844         raise ExtractorError('Unable to recognize tab page')
2845
2846
2847 class YoutubePlaylistIE(InfoExtractor):
2848     IE_DESC = 'YouTube.com playlists'
2849     _VALID_URL = r'''(?x)(?:
2850                         (?:https?://)?
2851                         (?:\w+\.)?
2852                         (?:
2853                             (?:
2854                                 youtube(?:kids)?\.com|
2855                                 invidio\.us
2856                             )
2857                             /.*?\?.*?\blist=
2858                         )?
2859                         (?P<id>%(playlist_id)s)
2860                      )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
2861     IE_NAME = 'youtube:playlist'
2862     _TESTS = [{
2863         'note': 'issue #673',
2864         'url': 'PLBB231211A4F62143',
2865         'info_dict': {
2866             'title': '[OLD]Team Fortress 2 (Class-based LP)',
2867             'id': 'PLBB231211A4F62143',
2868             'uploader': 'Wickydoo',
2869             'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
2870         },
2871         'playlist_mincount': 29,
2872     }, {
2873         'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
2874         'info_dict': {
2875             'title': 'YDL_safe_search',
2876             'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
2877         },
2878         'playlist_count': 2,
2879         'skip': 'This playlist is private',
2880     }, {
2881         'note': 'embedded',
2882         'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
2883         'playlist_count': 4,
2884         'info_dict': {
2885             'title': 'JODA15',
2886             'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
2887             'uploader': 'milan',
2888             'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
2889         }
2890     }, {
2891         'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
2892         'playlist_mincount': 982,
2893         'info_dict': {
2894             'title': '2018 Chinese New Singles (11/6 updated)',
2895             'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
2896             'uploader': 'LBK',
2897             'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
2898         }
2899     }, {
2900         'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
2901         'only_matching': True,
2902     }, {
2903         # music album playlist
2904         'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
2905         'only_matching': True,
2906     }]
2907
2908     @classmethod
2909     def suitable(cls, url):
2910         if YoutubeTabIE.suitable(url):
2911             return False
2912         # Hack for lazy extractors until more generic solution is implemented
2913         # (see #28780)
2914         from .youtube import parse_qs
2915         qs = parse_qs(url)
2916         if qs.get('v', [None])[0]:
2917             return False
2918         return super(YoutubePlaylistIE, cls).suitable(url)
2919
2920     def _real_extract(self, url):
2921         playlist_id = self._match_id(url)
2922         qs = parse_qs(url)
2923         if not qs:
2924             qs = {'list': playlist_id}
2925         return self.url_result(
2926             update_url_query('https://www.youtube.com/playlist', qs),
2927             ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
2928
2929
2930 class YoutubeYtBeIE(InfoExtractor):
2931     _VALID_URL = r'https?://youtu\.be/(?P<id>[0-9A-Za-z_-]{11})/*?.*?\blist=(?P<playlist_id>%(playlist_id)s)' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
2932     _TESTS = [{
2933         'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
2934         'info_dict': {
2935             'id': 'yeWKywCrFtk',
2936             'ext': 'mp4',
2937             'title': 'Small Scale Baler and Braiding Rugs',
2938             'uploader': 'Backus-Page House Museum',
2939             'uploader_id': 'backuspagemuseum',
2940             'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
2941             'upload_date': '20161008',
2942             'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
2943             'categories': ['Nonprofits & Activism'],
2944             'tags': list,
2945             'like_count': int,
2946             'dislike_count': int,
2947         },
2948         'params': {
2949             'noplaylist': True,
2950             'skip_download': True,
2951         },
2952     }, {
2953         'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
2954         'only_matching': True,
2955     }]
2956
2957     def _real_extract(self, url):
2958         mobj = re.match(self._VALID_URL, url)
2959         video_id = mobj.group('id')
2960         playlist_id = mobj.group('playlist_id')
2961         return self.url_result(
2962             update_url_query('https://www.youtube.com/watch', {
2963                 'v': video_id,
2964                 'list': playlist_id,
2965                 'feature': 'youtu.be',
2966             }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
2967
2968
2969 class YoutubeYtUserIE(InfoExtractor):
2970     _VALID_URL = r'ytuser:(?P<id>.+)'
2971     _TESTS = [{
2972         'url': 'ytuser:phihag',
2973         'only_matching': True,
2974     }]
2975
2976     def _real_extract(self, url):
2977         user_id = self._match_id(url)
2978         return self.url_result(
2979             'https://www.youtube.com/user/%s' % user_id,
2980             ie=YoutubeTabIE.ie_key(), video_id=user_id)
2981
2982
2983 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
2984     IE_NAME = 'youtube:favorites'
2985     IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
2986     _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
2987     _LOGIN_REQUIRED = True
2988     _TESTS = [{
2989         'url': ':ytfav',
2990         'only_matching': True,
2991     }, {
2992         'url': ':ytfavorites',
2993         'only_matching': True,
2994     }]
2995
2996     def _real_extract(self, url):
2997         return self.url_result(
2998             'https://www.youtube.com/playlist?list=LL',
2999             ie=YoutubeTabIE.ie_key())
3000
3001
3002 class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
3003     IE_DESC = 'YouTube.com searches'
3004     # there doesn't appear to be a real limit, for example if you search for
3005     # 'python' you get more than 8.000.000 results
3006     _MAX_RESULTS = float('inf')
3007     IE_NAME = 'youtube:search'
3008     _SEARCH_KEY = 'ytsearch'
3009     _SEARCH_PARAMS = None
3010     _TESTS = []
3011
3012     def _entries(self, query, n):
3013         data = {
3014             'context': {
3015                 'client': {
3016                     'clientName': 'WEB',
3017                     'clientVersion': '2.20201021.03.00',
3018                 }
3019             },
3020             'query': query,
3021         }
3022         if self._SEARCH_PARAMS:
3023             data['params'] = self._SEARCH_PARAMS
3024         total = 0
3025         for page_num in itertools.count(1):
3026             search = self._download_json(
3027                 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
3028                 video_id='query "%s"' % query,
3029                 note='Downloading page %s' % page_num,
3030                 errnote='Unable to download API page', fatal=False,
3031                 data=json.dumps(data).encode('utf8'),
3032                 headers={'content-type': 'application/json'})
3033             if not search:
3034                 break
3035             slr_contents = try_get(
3036                 search,
3037                 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3038                  lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3039                 list)
3040             if not slr_contents:
3041                 break
3042             for slr_content in slr_contents:
3043                 isr_contents = try_get(
3044                     slr_content,
3045                     lambda x: x['itemSectionRenderer']['contents'],
3046                     list)
3047                 if not isr_contents:
3048                     continue
3049                 for content in isr_contents:
3050                     if not isinstance(content, dict):
3051                         continue
3052                     video = content.get('videoRenderer')
3053                     if not isinstance(video, dict):
3054                         continue
3055                     video_id = video.get('videoId')
3056                     if not video_id: