]> jfr.im git - yt-dlp.git/blobdiff - youtube_dlc/extractor/youtube.py
[youtube] Show if video was a live stream in info
[yt-dlp.git] / youtube_dlc / extractor / youtube.py
index a9b591125f13c15fe4a08b323bb038e7e9131716..2f02f3afc2708883a92a0e11c9ad3c3cb0e1a6cb 100644 (file)
@@ -2,7 +2,6 @@
 
 from __future__ import unicode_literals
 
-
 import itertools
 import json
 import os.path
 import traceback
 
 from .common import InfoExtractor, SearchInfoExtractor
-from ..jsinterp import JSInterpreter
-from ..swfinterp import SWFInterpreter
 from ..compat import (
     compat_chr,
     compat_HTTPError,
     compat_kwargs,
     compat_parse_qs,
-    compat_urllib_parse_unquote,
+    compat_str,
     compat_urllib_parse_unquote_plus,
     compat_urllib_parse_urlencode,
     compat_urllib_parse_urlparse,
     compat_urlparse,
-    compat_str,
 )
+from ..jsinterp import JSInterpreter
 from ..utils import (
-    bool_or_none,
     clean_html,
-    error_to_compat_str,
-    extract_attributes,
     ExtractorError,
+    format_field,
     float_or_none,
-    get_element_by_attribute,
-    get_element_by_id,
     int_or_none,
-    js_to_json,
     mimetype2ext,
-    orderedSet,
     parse_codecs,
-    parse_count,
     parse_duration,
-    remove_quotes,
+    qualities,
     remove_start,
     smuggle_url,
     str_or_none,
     unescapeHTML,
     unified_strdate,
     unsmuggle_url,
-    uppercase_escape,
+    update_url_query,
     url_or_none,
     urlencode_postdata,
+    urljoin,
 )
 
 
@@ -66,24 +57,16 @@ class YoutubeBaseInfoExtractor(InfoExtractor):
     _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
     _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
 
+    _RESERVED_NAMES = (
+        r'embed|e|watch_popup|channel|c|user|playlist|watch|w|v|movies|results|shared|hashtag|'
+        r'storefront|oops|index|account|reporthistory|t/terms|about|upload|signin|logout|'
+        r'feed/(?:watch_later|history|subscriptions|library|trending|recommended)')
+
     _NETRC_MACHINE = 'youtube'
     # If True it will raise an error if no login info is provided
     _LOGIN_REQUIRED = False
 
-    _PLAYLIST_ID_RE = r'(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}'
-    _INITIAL_DATA_RE = r'(?:window\["ytInitialData"\]|ytInitialData)\W?=\W?({.*?});'
-    _YTCFG_DATA_RE = r"ytcfg.set\(({.*?})\)"
-
-    _YOUTUBE_CLIENT_HEADERS = {
-        'x-youtube-client-name': '1',
-        'x-youtube-client-version': '1.20200609.04.02',
-    }
-
-    def _set_language(self):
-        self._set_cookie(
-            '.youtube.com', 'PREF', 'f1=50000000&f6=8&hl=en',
-            # YouTube sets the expire time to about two months
-            expire_time=time.time() + 2 * 30 * 24 * 3600)
+    _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
 
     def _ids_to_results(self, ids):
         return [
@@ -103,8 +86,8 @@ def _login(self):
         if username is None:
             if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
-            if self._downloader.params.get('cookiefile') and False:  # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
-                self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
+            # if self._downloader.params.get('cookiefile'):  # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
+                self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
             return True
 
         login_page = self._download_webpage(
@@ -281,205 +264,148 @@ def _download_webpage_handle(self, *args, **kwargs):
         return super(YoutubeBaseInfoExtractor, self)._download_webpage_handle(
             *args, **compat_kwargs(kwargs))
 
-    def _get_yt_initial_data(self, video_id, webpage):
-        config = self._search_regex(
-            (r'window\["ytInitialData"\]\s*=\s*(.*?)(?<=});',
-             r'var\s+ytInitialData\s*=\s*(.*?)(?<=});'),
-            webpage, 'ytInitialData', default=None)
-        if config:
-            return self._parse_json(
-                uppercase_escape(config), video_id, fatal=False)
-
     def _real_initialize(self):
         if self._downloader is None:
             return
-        self._set_language()
         if not self._login():
             return
 
+    _DEFAULT_API_DATA = {
+        'context': {
+            'client': {
+                'clientName': 'WEB',
+                'clientVersion': '2.20201021.03.00',
+            }
+        },
+    }
 
-class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
-
-    def _find_entries_in_json(self, extracted):
-        entries = []
-        c = {}
-
-        def _real_find(obj):
-            if obj is None or isinstance(obj, str):
-                return
-
-            if type(obj) is list:
-                for elem in obj:
-                    _real_find(elem)
-
-            if type(obj) is dict:
-                if self._is_entry(obj):
-                    entries.append(obj)
-                    return
-
-                if 'continuationCommand' in obj:
-                    c['continuation'] = obj
-                    return
-
-                for _, o in obj.items():
-                    _real_find(o)
-
-        _real_find(extracted)
-
-        return entries, try_get(c, lambda x: x["continuation"])
-
-    def _entries(self, page, playlist_id, max_pages=None):
-        seen = []
-
-        yt_conf = {}
-        for m in re.finditer(self._YTCFG_DATA_RE, page):
-            parsed = self._parse_json(m.group(1), playlist_id,
-                                      transform_source=js_to_json, fatal=False)
-            if parsed:
-                yt_conf.update(parsed)
-
-        data_json = self._parse_json(self._search_regex(self._INITIAL_DATA_RE, page, 'ytInitialData'), None)
-
-        for page_num in range(1, max_pages + 1) if max_pages is not None else itertools.count(1):
-            entries, continuation = self._find_entries_in_json(data_json)
-            processed = self._process_entries(entries, seen)
-
-            if not processed:
-                break
-            for entry in processed:
-                yield entry
-
-            if not continuation or not yt_conf:
-                break
-            continuation_token = try_get(continuation, lambda x: x['continuationCommand']['token'])
-            continuation_url = try_get(continuation, lambda x: x['commandMetadata']['webCommandMetadata']['apiUrl'])
-            if not continuation_token or not continuation_url:
-                break
-
-            count = 0
-            retries = 3
-            while count <= retries:
-                try:
-                    # Downloading page may result in intermittent 5xx HTTP error
-                    # that is usually worked around with a retry
-                    data_json = self._download_json(
-                        'https://www.youtube.com%s' % continuation_url,
-                        playlist_id,
-                        'Downloading continuation page #%s%s' % (page_num, ' (retry #%d)' % count if count else ''),
-
-                        transform_source=uppercase_escape,
-                        query={
-                            'key': try_get(yt_conf, lambda x: x['INNERTUBE_API_KEY'])
-                        },
-                        data=str(json.dumps({
-                            'context': try_get(yt_conf, lambda x: x['INNERTUBE_CONTEXT']),
-                            'continuation': continuation_token
-                        })).encode(encoding='UTF-8', errors='strict'),
-                        headers={
-                            'Content-Type': 'application/json'
-                        }
-                    )
-                    break
-                except ExtractorError as e:
-                    if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
-                        count += 1
-                        if count <= retries:
-                            continue
-                    raise
-
-    def _extract_title(self, renderer):
-        title = try_get(renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
-        if title:
-            return title
-        return try_get(renderer, lambda x: x['title']['simpleText'], compat_str)
-
-
-class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
-    def _is_entry(self, obj):
-        return 'videoId' in obj
-
-    def _process_entries(self, entries, seen):
-        ids_in_page = []
-        titles_in_page = []
-        for renderer in entries:
-            video_id = try_get(renderer, lambda x: x['videoId'])
-            video_title = self._extract_title(renderer)
-
-            if video_id is None or video_title is None:
-                # we do not have a videoRenderer or title extraction broke
-                continue
-
-            video_title = video_title.strip()
-
-            try:
-                idx = ids_in_page.index(video_id)
-                if video_title and not titles_in_page[idx]:
-                    titles_in_page[idx] = video_title
-            except ValueError:
-                ids_in_page.append(video_id)
-                titles_in_page.append(video_title)
-
-        for video_id, video_title in zip(ids_in_page, titles_in_page):
-            yield self.url_result(video_id, 'Youtube', video_id, video_title)
-
+    _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
+    _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
+    _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
 
-class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
-    def _is_entry(self, obj):
-        return 'playlistId' in obj
+    def _call_api(self, ep, query, video_id, fatal=True):
+        data = self._DEFAULT_API_DATA.copy()
+        data.update(query)
 
-    def _process_entries(self, entries, seen):
-        for playlist_id in orderedSet(try_get(r, lambda x: x['playlistId']) for r in entries):
+        return self._download_json(
+            'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
+            note='Downloading API JSON', errnote='Unable to download API page',
+            data=json.dumps(data).encode('utf8'), fatal=fatal,
+            headers={'content-type': 'application/json'},
+            query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
 
-            yield self.url_result(
-                'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
+    def _extract_yt_initial_data(self, video_id, webpage):
+        return self._parse_json(
+            self._search_regex(
+                (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
+                 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
+            video_id)
 
-    def _real_extract(self, url):
-        playlist_id = self._match_id(url)
-        webpage = self._download_webpage(url, playlist_id)
-        title = self._og_search_title(webpage, fatal=False)
-        return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
+    def _extract_ytcfg(self, video_id, webpage):
+        return self._parse_json(
+            self._search_regex(
+                r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
+                default='{}'), video_id, fatal=False)
+
+    def _extract_video(self, renderer):
+        video_id = renderer.get('videoId')
+        title = try_get(
+            renderer,
+            (lambda x: x['title']['runs'][0]['text'],
+             lambda x: x['title']['simpleText']), compat_str)
+        description = try_get(
+            renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
+            compat_str)
+        duration = parse_duration(try_get(
+            renderer, lambda x: x['lengthText']['simpleText'], compat_str))
+        view_count_text = try_get(
+            renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
+        view_count = str_to_int(self._search_regex(
+            r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
+            'view count', default=None))
+        uploader = try_get(
+            renderer,
+            (lambda x: x['ownerText']['runs'][0]['text'],
+             lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
+        return {
+            '_type': 'url_transparent',
+            'ie_key': YoutubeIE.ie_key(),
+            'id': video_id,
+            'url': video_id,
+            'title': title,
+            'description': description,
+            'duration': duration,
+            'view_count': view_count,
+            'uploader': uploader,
+        }
 
 
 class YoutubeIE(YoutubeBaseInfoExtractor):
     IE_DESC = 'YouTube.com'
+    _INVIDIOUS_SITES = (
+        # invidious-redirect websites
+        r'(?:www\.)?redirect\.invidious\.io',
+        r'(?:(?:www|dev)\.)?invidio\.us',
+        # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
+        r'(?:www\.)?invidious\.pussthecat\.org',
+        r'(?:www\.)?invidious\.048596\.xyz',
+        r'(?:www\.)?invidious\.zee\.li',
+        r'(?:www\.)?vid\.puffyan\.us',
+        r'(?:(?:www|au)\.)?ytprivate\.com',
+        r'(?:www\.)?invidious\.namazso\.eu',
+        r'(?:www\.)?invidious\.ethibox\.fr',
+        r'(?:www\.)?inv\.skyn3t\.in',
+        r'(?:www\.)?invidious\.himiko\.cloud',
+        r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
+        r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
+        r'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
+        r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
+        # youtube-dl invidious instances list
+        r'(?:(?:www|no)\.)?invidiou\.sh',
+        r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
+        r'(?:www\.)?invidious\.kabi\.tk',
+        r'(?:www\.)?invidious\.13ad\.de',
+        r'(?:www\.)?invidious\.mastodon\.host',
+        r'(?:www\.)?invidious\.zapashcanon\.fr',
+        r'(?:www\.)?invidious\.kavin\.rocks',
+        r'(?:www\.)?invidious\.tube',
+        r'(?:www\.)?invidiou\.site',
+        r'(?:www\.)?invidious\.site',
+        r'(?:www\.)?invidious\.xyz',
+        r'(?:www\.)?invidious\.nixnet\.xyz',
+        r'(?:www\.)?invidious\.drycat\.fr',
+        r'(?:www\.)?tube\.poal\.co',
+        r'(?:www\.)?tube\.connect\.cafe',
+        r'(?:www\.)?vid\.wxzm\.sx',
+        r'(?:www\.)?vid\.mint\.lgbt',
+        r'(?:www\.)?yewtu\.be',
+        r'(?:www\.)?yt\.elukerio\.org',
+        r'(?:www\.)?yt\.lelux\.fi',
+        r'(?:www\.)?invidious\.ggc-project\.de',
+        r'(?:www\.)?yt\.maisputain\.ovh',
+        r'(?:www\.)?invidious\.toot\.koeln',
+        r'(?:www\.)?invidious\.fdn\.fr',
+        r'(?:www\.)?watch\.nettohikari\.com',
+        r'(?:www\.)?kgg2m7yk5aybusll\.onion',
+        r'(?:www\.)?qklhadlycap4cnod\.onion',
+        r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
+        r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
+        r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
+        r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
+        r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
+        r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
+    )
     _VALID_URL = r"""(?x)^
                      (
                          (?:https?://|//)                                    # http(s):// or protocol-independent URL
-                         (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com/|
-                            (?:www\.)?deturl\.com/www\.youtube\.com/|
-                            (?:www\.)?pwnyoutube\.com/|
-                            (?:www\.)?hooktube\.com/|
-                            (?:www\.)?yourepeat\.com/|
-                            tube\.majestyc\.net/|
-                            # Invidious instances taken from https://github.com/omarroth/invidious/wiki/Invidious-Instances
-                            (?:(?:www|dev)\.)?invidio\.us/|
-                            (?:(?:www|no)\.)?invidiou\.sh/|
-                            (?:(?:www|fi|de)\.)?invidious\.snopyta\.org/|
-                            (?:www\.)?invidious\.kabi\.tk/|
-                            (?:www\.)?invidious\.13ad\.de/|
-                            (?:www\.)?invidious\.mastodon\.host/|
-                            (?:www\.)?invidious\.nixnet\.xyz/|
-                            (?:www\.)?invidious\.drycat\.fr/|
-                            (?:www\.)?tube\.poal\.co/|
-                            (?:www\.)?vid\.wxzm\.sx/|
-                            (?:www\.)?yewtu\.be/|
-                            (?:www\.)?yt\.elukerio\.org/|
-                            (?:www\.)?yt\.lelux\.fi/|
-                            (?:www\.)?invidious\.ggc-project\.de/|
-                            (?:www\.)?yt\.maisputain\.ovh/|
-                            (?:www\.)?invidious\.13ad\.de/|
-                            (?:www\.)?invidious\.toot\.koeln/|
-                            (?:www\.)?invidious\.fdn\.fr/|
-                            (?:www\.)?watch\.nettohikari\.com/|
-                            (?:www\.)?kgg2m7yk5aybusll\.onion/|
-                            (?:www\.)?qklhadlycap4cnod\.onion/|
-                            (?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion/|
-                            (?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion/|
-                            (?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion/|
-                            (?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion/|
-                            (?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p/|
-                            (?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion/|
-                            youtube\.googleapis\.com/)                        # the various hostnames, with wildcard subdomains
+                         (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
+                            (?:www\.)?deturl\.com/www\.youtube\.com|
+                            (?:www\.)?pwnyoutube\.com|
+                            (?:www\.)?hooktube\.com|
+                            (?:www\.)?yourepeat\.com|
+                            tube\.majestyc\.net|
+                            %(invidious)s|
+                            youtube\.googleapis\.com)/                        # the various hostnames, with wildcard subdomains
                          (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
                          (?:                                                  # the various things that can precede the ID:
                              (?:(?:v|embed|e)/(?!videoseries))                # v/ or embed/ or e/
@@ -494,11 +420,12 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                             youtu\.be|                                        # just youtu.be/xxxx
                             vid\.plus|                                        # or vid.plus/xxxx
                             zwearz\.com/watch|                                # or zwearz.com/watch/xxxx
+                            %(invidious)s
                          )/
                          |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
                          )
                      )?                                                       # all until now is optional -> you can pass the naked ID
-                     ([0-9A-Za-z_-]{11})                                      # here is it! the YouTube video ID
+                     (?P<id>[0-9A-Za-z_-]{11})                                      # here is it! the YouTube video ID
                      (?!.*?\blist=
                         (?:
                             %(playlist_id)s|                                  # combined list/video URLs are handled by the playlist IE
@@ -506,11 +433,14 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                         )
                      )
                      (?(1).+)?                                                # if we found the ID, everything can follow
-                     $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
-    _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
+                     $""" % {
+        'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE,
+        'invidious': '|'.join(_INVIDIOUS_SITES),
+    }
     _PLAYER_INFO_RE = (
-        r'/(?P<id>[a-zA-Z0-9_-]{8,})/player_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?/base\.(?P<ext>[a-z]+)$',
-        r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.(?P<ext>[a-z]+)$',
+        r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
+        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$',
+        r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
     )
     _formats = {
         '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
@@ -659,10 +589,11 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'uploader_id': 'setindia',
                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
                 'age_limit': 18,
-            }
+            },
+            'skip': 'Private video',
         },
         {
-            'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
+            'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
             'note': 'Use the first video ID in the URL',
             'info_dict': {
                 'id': 'BaW_jenozKc',
@@ -703,6 +634,25 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
             },
             'skip': 'format 141 not served anymore',
         },
+        # DASH manifest with encrypted signature
+        {
+            'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
+            'info_dict': {
+                'id': 'IB3lcPjvWLA',
+                'ext': 'm4a',
+                'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
+                'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
+                'duration': 244,
+                'uploader': 'AfrojackVEVO',
+                'uploader_id': 'AfrojackVEVO',
+                'upload_date': '20131011',
+                'abr': 129.495,
+            },
+            'params': {
+                'youtube_include_dash_manifest': True,
+                'format': '141/bestaudio[ext=m4a]',
+            },
+        },
         # Controversy video
         {
             'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
@@ -715,7 +665,7 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'uploader_id': 'TheAmazingAtheist',
                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
                 'title': 'Burning Everyone\'s Koran',
-                'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms\n\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',
+                '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',
             }
         },
         # Normal age-gate video (embed allowed)
@@ -734,6 +684,27 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'age_limit': 18,
             },
         },
+        # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
+        # YouTube Red ad is not captured for creator
+        {
+            'url': '__2ABJjxzNo',
+            'info_dict': {
+                'id': '__2ABJjxzNo',
+                'ext': 'mp4',
+                'duration': 266,
+                'upload_date': '20100430',
+                'uploader_id': 'deadmau5',
+                'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
+                'creator': 'deadmau5',
+                'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
+                'uploader': 'deadmau5',
+                'title': 'Deadmau5 - Some Chords (HD)',
+                'alt_title': 'Some Chords',
+            },
+            'expected_warnings': [
+                'DASH manifest missing',
+            ]
+        },
         # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
         {
             'url': 'lqQg6PlCWgI',
@@ -823,69 +794,64 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
         },
         {
             # Multifeed videos (multiple cameras), URL is for Main Camera
-            'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
+            'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
             'info_dict': {
-                'id': 'jqWvoWXjCVs',
-                'title': 'teamPGP: Rocket League Noob Stream',
-                'description': 'md5:dc7872fb300e143831327f1bae3af010',
+                'id': 'jvGDaLqkpTg',
+                'title': 'Tom Clancy Free Weekend Rainbow Whatever',
+                'description': 'md5:e03b909557865076822aa169218d6a5d',
             },
             'playlist': [{
                 'info_dict': {
-                    'id': 'jqWvoWXjCVs',
+                    'id': 'jvGDaLqkpTg',
                     'ext': 'mp4',
-                    'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
-                    'description': 'md5:dc7872fb300e143831327f1bae3af010',
-                    'duration': 7335,
-                    'upload_date': '20150721',
-                    'uploader': 'Beer Games Beer',
-                    'uploader_id': 'beergamesbeer',
-                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
-                    'license': 'Standard YouTube License',
+                    'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
+                    'description': 'md5:e03b909557865076822aa169218d6a5d',
+                    'duration': 10643,
+                    'upload_date': '20161111',
+                    'uploader': 'Team PGP',
+                    'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
+                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
                 },
             }, {
                 'info_dict': {
-                    'id': '6h8e8xoXJzg',
+                    'id': '3AKt1R1aDnw',
                     'ext': 'mp4',
-                    'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
-                    'description': 'md5:dc7872fb300e143831327f1bae3af010',
-                    'duration': 7337,
-                    'upload_date': '20150721',
-                    'uploader': 'Beer Games Beer',
-                    'uploader_id': 'beergamesbeer',
-                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
-                    'license': 'Standard YouTube License',
+                    'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
+                    'description': 'md5:e03b909557865076822aa169218d6a5d',
+                    'duration': 10991,
+                    'upload_date': '20161111',
+                    'uploader': 'Team PGP',
+                    'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
+                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
                 },
             }, {
                 'info_dict': {
-                    'id': 'PUOgX5z9xZw',
+                    'id': 'RtAMM00gpVc',
                     'ext': 'mp4',
-                    'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
-                    'description': 'md5:dc7872fb300e143831327f1bae3af010',
-                    'duration': 7337,
-                    'upload_date': '20150721',
-                    'uploader': 'Beer Games Beer',
-                    'uploader_id': 'beergamesbeer',
-                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
-                    'license': 'Standard YouTube License',
+                    'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
+                    'description': 'md5:e03b909557865076822aa169218d6a5d',
+                    'duration': 10995,
+                    'upload_date': '20161111',
+                    'uploader': 'Team PGP',
+                    'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
+                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
                 },
             }, {
                 'info_dict': {
-                    'id': 'teuwxikvS5k',
+                    'id': '6N2fdlP3C5U',
                     'ext': 'mp4',
-                    'title': 'teamPGP: Rocket League Noob Stream (zim)',
-                    'description': 'md5:dc7872fb300e143831327f1bae3af010',
-                    'duration': 7334,
-                    'upload_date': '20150721',
-                    'uploader': 'Beer Games Beer',
-                    'uploader_id': 'beergamesbeer',
-                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
-                    'license': 'Standard YouTube License',
+                    'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
+                    'description': 'md5:e03b909557865076822aa169218d6a5d',
+                    'duration': 10990,
+                    'upload_date': '20161111',
+                    'uploader': 'Team PGP',
+                    'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
+                    'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
                 },
             }],
             'params': {
                 'skip_download': True,
             },
-            'skip': 'This video is not available.',
         },
         {
             # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
@@ -979,7 +945,7 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'id': 'eQcmzGIKrzg',
                 'ext': 'mp4',
                 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
-                'description': 'md5:dda0d780d5a6e120758d1711d062a867',
+                'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
                 'duration': 4060,
                 'upload_date': '20151119',
                 'uploader': 'Bernie Sanders',
@@ -1026,7 +992,7 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'id': 'iqKdEhx-dD4',
                 'ext': 'mp4',
                 'title': 'Isolation - Mind Field (Ep 1)',
-                'description': 'md5:46a29be4ceffa65b92d277b93f463c0f',
+                'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
                 'duration': 2085,
                 'upload_date': '20170118',
                 'uploader': 'Vsauce',
@@ -1061,6 +1027,7 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
             'params': {
                 'skip_download': True,
             },
+            'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
         },
         {
             # itag 212
@@ -1073,11 +1040,16 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
             'only_matching': True,
         },
         {
-            'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
+            'url': 'https://invidio.us/watch?v=BaW_jenozKc',
             'only_matching': True,
         },
         {
-            'url': 'https://invidio.us/watch?v=BaW_jenozKc',
+            'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
+            'only_matching': True,
+        },
+        {
+            # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
+            'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
             'only_matching': True,
         },
         {
@@ -1127,73 +1099,6 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'skip_download': True,
             },
         },
-        {
-            # Youtube Music Auto-generated description
-            # Retrieve 'artist' field from 'Artist:' in video description
-            # when it is present on youtube music video
-            'url': 'https://www.youtube.com/watch?v=k0jLE7tTwjY',
-            'info_dict': {
-                'id': 'k0jLE7tTwjY',
-                'ext': 'mp4',
-                'title': 'Latch Feat. Sam Smith',
-                'description': 'md5:3cb1e8101a7c85fcba9b4fb41b951335',
-                'upload_date': '20150110',
-                'uploader': 'Various Artists - Topic',
-                'uploader_id': 'UCNkEcmYdjrH4RqtNgh7BZ9w',
-                'artist': 'Disclosure',
-                'track': 'Latch Feat. Sam Smith',
-                'album': 'Latch Featuring Sam Smith',
-                'release_date': '20121008',
-                'release_year': 2012,
-            },
-            'params': {
-                'skip_download': True,
-            },
-        },
-        {
-            # Youtube Music Auto-generated description
-            # handle multiple artists on youtube music video
-            'url': 'https://www.youtube.com/watch?v=74qn0eJSjpA',
-            'info_dict': {
-                'id': '74qn0eJSjpA',
-                'ext': 'mp4',
-                'title': 'Eastside',
-                'description': 'md5:290516bb73dcbfab0dcc4efe6c3de5f2',
-                'upload_date': '20180710',
-                'uploader': 'Benny Blanco - Topic',
-                'uploader_id': 'UCzqz_ksRu_WkIzmivMdIS7A',
-                'artist': 'benny blanco, Halsey, Khalid',
-                'track': 'Eastside',
-                'album': 'Eastside',
-                'release_date': '20180713',
-                'release_year': 2018,
-            },
-            'params': {
-                'skip_download': True,
-            },
-        },
-        {
-            # Youtube Music Auto-generated description
-            # handle youtube music video with release_year and no release_date
-            'url': 'https://www.youtube.com/watch?v=-hcAI0g-f5M',
-            'info_dict': {
-                'id': '-hcAI0g-f5M',
-                'ext': 'mp4',
-                'title': 'Put It On Me',
-                'description': 'md5:f6422397c07c4c907c6638e1fee380a5',
-                'upload_date': '20180426',
-                'uploader': 'Matt Maeson - Topic',
-                'uploader_id': 'UCnEkIGqtGcQMLk73Kp-Q5LQ',
-                'artist': 'Matt Maeson',
-                'track': 'Put It On Me',
-                'album': 'The Hearse',
-                'release_date': None,
-                'release_year': 2018,
-            },
-            'params': {
-                'skip_download': True,
-            },
-        },
         {
             'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
             'only_matching': True,
@@ -1217,6 +1122,7 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
             'params': {
                 'skip_download': True,
             },
+            'skip': 'Video unavailable',
         },
         {
             # empty description results in an empty string
@@ -1234,28 +1140,68 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
                 'skip_download': True,
             },
         },
+        {
+            # with '};' inside yt initial data (see [1])
+            # see [2] for an example with '};' inside ytInitialPlayerResponse
+            # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
+            # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
+            'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
+            'info_dict': {
+                'id': 'CHqg6qOn4no',
+                'ext': 'mp4',
+                'title': 'Part 77   Sort a list of simple types in c#',
+                'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
+                'upload_date': '20130831',
+                'uploader_id': 'kudvenkat',
+                'uploader': 'kudvenkat',
+            },
+            'params': {
+                'skip_download': True,
+            },
+        },
+        {
+            # another example of '};' in ytInitialData
+            'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
+            'only_matching': True,
+        },
+        {
+            'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
+            'only_matching': True,
+        },
+        {
+            # https://github.com/ytdl-org/youtube-dl/pull/28094
+            'url': 'OtqTfy26tG0',
+            'info_dict': {
+                'id': 'OtqTfy26tG0',
+                'ext': 'mp4',
+                'title': 'Burn Out',
+                'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
+                'upload_date': '20141120',
+                'uploader': 'The Cinematic Orchestra - Topic',
+                'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
+                'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
+                'artist': 'The Cinematic Orchestra',
+                'track': 'Burn Out',
+                'album': 'Every Day',
+                'release_data': None,
+                'release_year': None,
+            },
+            'params': {
+                'skip_download': True,
+            },
+        },
+        {
+            # controversial video, only works with bpctr when authenticated with cookies
+            'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
+            'only_matching': True,
+        },
     ]
 
     def __init__(self, *args, **kwargs):
         super(YoutubeIE, self).__init__(*args, **kwargs)
+        self._code_cache = {}
         self._player_cache = {}
 
-    def report_video_info_webpage_download(self, video_id):
-        """Report attempt to download video info webpage."""
-        self.to_screen('%s: Downloading video info webpage' % video_id)
-
-    def report_information_extraction(self, video_id):
-        """Report attempt to extract video information."""
-        self.to_screen('%s: Extracting video information' % video_id)
-
-    def report_unavailable_format(self, video_id, format):
-        """Report extracted video URL."""
-        self.to_screen('%s: Format %s not available' % (video_id, format))
-
-    def report_rtmp_download(self):
-        """Indicate the download will use the RTMP protocol."""
-        self.to_screen('RTMP download detected')
-
     def _signature_cache_id(self, example_sig):
         """ Return a string representation of a signature """
         return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
@@ -1268,40 +1214,27 @@ def _extract_player_info(cls, player_url):
                 break
         else:
             raise ExtractorError('Cannot identify player %r' % player_url)
-        return id_m.group('ext'), id_m.group('id')
+        return id_m.group('id')
 
     def _extract_signature_function(self, video_id, player_url, example_sig):
-        player_type, player_id = self._extract_player_info(player_url)
+        player_id = self._extract_player_info(player_url)
 
         # Read from filesystem cache
-        func_id = '%s_%s_%s' % (
-            player_type, player_id, self._signature_cache_id(example_sig))
+        func_id = 'js_%s_%s' % (
+            player_id, self._signature_cache_id(example_sig))
         assert os.path.basename(func_id) == func_id
 
         cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
         if cache_spec is not None:
             return lambda s: ''.join(s[i] for i in cache_spec)
 
-        download_note = (
-            'Downloading player %s' % player_url
-            if self._downloader.params.get('verbose') else
-            'Downloading %s player %s' % (player_type, player_id)
-        )
-        if player_type == 'js':
-            code = self._download_webpage(
-                player_url, video_id,
-                note=download_note,
-                errnote='Download of %s failed' % player_url)
-            res = self._parse_sig_js(code)
-        elif player_type == 'swf':
-            urlh = self._request_webpage(
+        if player_id not in self._code_cache:
+            self._code_cache[player_id] = self._download_webpage(
                 player_url, video_id,
-                note=download_note,
+                note='Downloading player ' + player_id,
                 errnote='Download of %s failed' % player_url)
-            code = urlh.read()
-            res = self._parse_sig_swf(code)
-        else:
-            assert False, 'Invalid player type %r' % player_type
+        code = self._code_cache[player_id]
+        res = self._parse_sig_js(code)
 
         test_string = ''.join(map(compat_chr, range(len(example_sig))))
         cache_res = res(test_string)
@@ -1353,6 +1286,9 @@ def _parse_sig_js(self, jscode):
         funcname = self._search_regex(
             (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
              r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
+             r'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
+             r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
+             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+\)',
              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*\)',
              r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
              # Obsolete patterns
@@ -1370,14 +1306,7 @@ def _parse_sig_js(self, jscode):
         initial_function = jsi.extract_function(funcname)
         return lambda s: initial_function([s])
 
-    def _parse_sig_swf(self, file_contents):
-        swfi = SWFInterpreter(file_contents)
-        TARGET_CLASSNAME = 'SignatureDecipher'
-        searched_class = swfi.extract_class(TARGET_CLASSNAME)
-        initial_function = swfi.extract_function(searched_class, 'decipher')
-        return lambda s: initial_function([s])
-
-    def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
+    def _decrypt_signature(self, s, video_id, player_url):
         """Turn the encrypted s field into a working signature"""
 
         if player_url is None:
@@ -1404,228 +1333,10 @@ def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
             raise ExtractorError(
                 'Signature extraction failed: ' + tb, cause=e)
 
-    def _get_subtitles(self, video_id, webpage, has_live_chat_replay):
-        try:
-            subs_doc = self._download_xml(
-                'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
-                video_id, note=False)
-        except ExtractorError as err:
-            self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
-            return {}
-
-        sub_lang_list = {}
-        for track in subs_doc.findall('track'):
-            lang = track.attrib['lang_code']
-            if lang in sub_lang_list:
-                continue
-            sub_formats = []
-            for ext in self._SUBTITLE_FORMATS:
-                params = compat_urllib_parse_urlencode({
-                    'lang': lang,
-                    'v': video_id,
-                    'fmt': ext,
-                    'name': track.attrib['name'].encode('utf-8'),
-                })
-                sub_formats.append({
-                    'url': 'https://www.youtube.com/api/timedtext?' + params,
-                    'ext': ext,
-                })
-            sub_lang_list[lang] = sub_formats
-        if has_live_chat_replay:
-            sub_lang_list['live_chat'] = [
-                {
-                    'video_id': video_id,
-                    'ext': 'json',
-                    'protocol': 'youtube_live_chat_replay',
-                },
-            ]
-        if not sub_lang_list:
-            self._downloader.report_warning('video doesn\'t have subtitles')
-            return {}
-        return sub_lang_list
-
-    def _get_ytplayer_config(self, video_id, webpage):
-        patterns = (
-            # User data may contain arbitrary character sequences that may affect
-            # JSON extraction with regex, e.g. when '};' is contained the second
-            # regex won't capture the whole JSON. Yet working around by trying more
-            # concrete regex first keeping in mind proper quoted string handling
-            # to be implemented in future that will replace this workaround (see
-            # https://github.com/ytdl-org/youtube-dl/issues/7468,
-            # https://github.com/ytdl-org/youtube-dl/pull/7599)
-            r';ytplayer\.config\s*=\s*({.+?});ytplayer',
-            r';ytplayer\.config\s*=\s*({.+?});',
-            r'ytInitialPlayerResponse\s*=\s*({.+?});var meta'
-        )
-        config = self._search_regex(
-            patterns, webpage, 'ytplayer.config', default=None)
-        if config:
-            return self._parse_json(
-                uppercase_escape(config), video_id, fatal=False)
-
-    def _get_music_metadata_from_yt_initial(self, yt_initial):
-        music_metadata = []
-        key_map = {
-            'Album': 'album',
-            'Artist': 'artist',
-            'Song': 'track'
-        }
-        contents = try_get(yt_initial, lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'])
-        if type(contents) is list:
-            for content in contents:
-                music_track = {}
-                if type(content) is not dict:
-                    continue
-                videoSecondaryInfoRenderer = try_get(content, lambda x: x['videoSecondaryInfoRenderer'])
-                if type(videoSecondaryInfoRenderer) is not dict:
-                    continue
-                rows = try_get(videoSecondaryInfoRenderer, lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'])
-                if type(rows) is not list:
-                    continue
-                for row in rows:
-                    metadataRowRenderer = try_get(row, lambda x: x['metadataRowRenderer'])
-                    if type(metadataRowRenderer) is not dict:
-                        continue
-                    key = try_get(metadataRowRenderer, lambda x: x['title']['simpleText'])
-                    value = try_get(metadataRowRenderer, lambda x: x['contents'][0]['simpleText']) or \
-                        try_get(metadataRowRenderer, lambda x: x['contents'][0]['runs'][0]['text'])
-                    if type(key) is not str or type(value) is not str:
-                        continue
-                    if key in key_map:
-                        if key_map[key] in music_track:
-                            # we've started on a new track
-                            music_metadata.append(music_track)
-                            music_track = {}
-                        music_track[key_map[key]] = value
-                if len(music_track.keys()):
-                    music_metadata.append(music_track)
-        return music_metadata
-
-    def _get_automatic_captions(self, video_id, webpage):
-        """We need the webpage for getting the captions url, pass it as an
-           argument to speed up the process."""
-        self.to_screen('%s: Looking for automatic captions' % video_id)
-        player_config = self._get_ytplayer_config(video_id, webpage)
-        err_msg = 'Couldn\'t find automatic captions for %s' % video_id
-        if not player_config:
-            self._downloader.report_warning(err_msg)
-            return {}
-        try:
-            if "args" in player_config and "ttsurl" in player_config["args"]:
-                args = player_config['args']
-                caption_url = args['ttsurl']
-                timestamp = args['timestamp']
-
-                # We get the available subtitles
-                list_params = compat_urllib_parse_urlencode({
-                    'type': 'list',
-                    'tlangs': 1,
-                    'asrs': 1,
-                })
-                list_url = caption_url + '&' + list_params
-                caption_list = self._download_xml(list_url, video_id)
-                original_lang_node = caption_list.find('track')
-                if original_lang_node is None:
-                    self._downloader.report_warning('Video doesn\'t have automatic captions')
-                    return {}
-                original_lang = original_lang_node.attrib['lang_code']
-                caption_kind = original_lang_node.attrib.get('kind', '')
-
-                sub_lang_list = {}
-                for lang_node in caption_list.findall('target'):
-                    sub_lang = lang_node.attrib['lang_code']
-                    sub_formats = []
-                    for ext in self._SUBTITLE_FORMATS:
-                        params = compat_urllib_parse_urlencode({
-                            'lang': original_lang,
-                            'tlang': sub_lang,
-                            'fmt': ext,
-                            'ts': timestamp,
-                            'kind': caption_kind,
-                        })
-                        sub_formats.append({
-                            'url': caption_url + '&' + params,
-                            'ext': ext,
-                        })
-                    sub_lang_list[sub_lang] = sub_formats
-                return sub_lang_list
-
-            def make_captions(sub_url, sub_langs):
-                parsed_sub_url = compat_urllib_parse_urlparse(sub_url)
-                caption_qs = compat_parse_qs(parsed_sub_url.query)
-                captions = {}
-                for sub_lang in sub_langs:
-                    sub_formats = []
-                    for ext in self._SUBTITLE_FORMATS:
-                        caption_qs.update({
-                            'tlang': [sub_lang],
-                            'fmt': [ext],
-                        })
-                        sub_url = compat_urlparse.urlunparse(parsed_sub_url._replace(
-                            query=compat_urllib_parse_urlencode(caption_qs, True)))
-                        sub_formats.append({
-                            'url': sub_url,
-                            'ext': ext,
-                        })
-                    captions[sub_lang] = sub_formats
-                return captions
-
-            # New captions format as of 22.06.2017
-            if "args" in player_config:
-                player_response = player_config["args"].get('player_response')
-            else:
-                # New player system (ytInitialPlayerResponse) as of October 2020
-                player_response = player_config
-
-            if player_response:
-                if isinstance(player_response, compat_str):
-                    player_response = self._parse_json(
-                        player_response, video_id, fatal=False)
-
-                renderer = player_response['captions']['playerCaptionsTracklistRenderer']
-                caption_tracks = renderer['captionTracks']
-                for caption_track in caption_tracks:
-                    if 'kind' not in caption_track:
-                        # not an automatic transcription
-                        continue
-                    base_url = caption_track['baseUrl']
-                    sub_lang_list = []
-                    for lang in renderer['translationLanguages']:
-                        lang_code = lang.get('languageCode')
-                        if lang_code:
-                            sub_lang_list.append(lang_code)
-                    return make_captions(base_url, sub_lang_list)
-
-                self._downloader.report_warning("Couldn't find automatic captions for %s" % video_id)
-                return {}
-
-            if "args" in player_config:
-                args = player_config["args"]
-
-                # Some videos don't provide ttsurl but rather caption_tracks and
-                # caption_translation_languages (e.g. 20LmZk1hakA)
-                # Does not used anymore as of 22.06.2017
-                caption_tracks = args['caption_tracks']
-                caption_translation_languages = args['caption_translation_languages']
-                caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
-                sub_lang_list = []
-                for lang in caption_translation_languages.split(','):
-                    lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
-                    sub_lang = lang_qs.get('lc', [None])[0]
-                    if sub_lang:
-                        sub_lang_list.append(sub_lang)
-                return make_captions(caption_url, sub_lang_list)
-        # An extractor error can be raise by the download process if there are
-        # no automatic captions but there are subtitles
-        except (KeyError, IndexError, ExtractorError):
-            self._downloader.report_warning(err_msg)
-            return {}
-
-    def _mark_watched(self, video_id, video_info, player_response):
+    def _mark_watched(self, video_id, player_response):
         playback_url = url_or_none(try_get(
             player_response,
-            lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']) or try_get(
-            video_info, lambda x: x['videostats_playback_base_url'][0]))
+            lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']))
         if not playback_url:
             return
         parsed_playback_url = compat_urlparse.urlparse(playback_url)
@@ -1692,18 +1403,9 @@ def extract_id(cls, url):
         video_id = mobj.group(2)
         return video_id
 
-    def _extract_chapters_from_json(self, webpage, video_id, duration):
-        if not webpage:
-            return
-        initial_data = self._parse_json(
-            self._search_regex(
-                r'window\["ytInitialData"\] = (.+);\n', webpage,
-                'player args', default='{}'),
-            video_id, fatal=False)
-        if not initial_data or not isinstance(initial_data, dict):
-            return
+    def _extract_chapters_from_json(self, data, video_id, duration):
         chapters_list = try_get(
-            initial_data,
+            data,
             lambda x: x['playerOverlays']
                        ['playerOverlayRenderer']
                        ['decoratedPlayerBarRenderer']
@@ -1741,290 +1443,75 @@ def chapter_time(chapter):
             })
         return chapters
 
-    @staticmethod
-    def _extract_chapters_from_description(description, duration):
-        if not description:
-            return None
-        chapter_lines = re.findall(
-            r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
-            description)
-        if not chapter_lines:
-            return None
-        chapters = []
-        for next_num, (chapter_line, time_point) in enumerate(
-                chapter_lines, start=1):
-            start_time = parse_duration(time_point)
-            if start_time is None:
-                continue
-            if start_time > duration:
-                break
-            end_time = (duration if next_num == len(chapter_lines)
-                        else parse_duration(chapter_lines[next_num][1]))
-            if end_time is None:
-                continue
-            if end_time > duration:
-                end_time = duration
-            if start_time > end_time:
-                break
-            chapter_title = re.sub(
-                r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
-            chapter_title = re.sub(r'\s+', ' ', chapter_title)
-            chapters.append({
-                'start_time': start_time,
-                'end_time': end_time,
-                'title': chapter_title,
-            })
-        return chapters
-
-    def _extract_chapters(self, webpage, description, video_id, duration):
-        return (self._extract_chapters_from_json(webpage, video_id, duration)
-                or self._extract_chapters_from_description(description, duration))
+    def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
+        return self._parse_json(self._search_regex(
+            (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
+             regex), webpage, name, default='{}'), video_id, fatal=False)
 
     def _real_extract(self, url):
         url, smuggled_data = unsmuggle_url(url, {})
+        video_id = self._match_id(url)
+        base_url = self.http_scheme() + '//www.youtube.com/'
+        webpage_url = base_url + 'watch?v=' + video_id + '&has_verified=1&bpctr=9999999999'
+        webpage = self._download_webpage(webpage_url, video_id, fatal=False)
 
-        proto = (
-            'http' if self._downloader.params.get('prefer_insecure', False)
-            else 'https')
-
-        start_time = None
-        end_time = None
-        parsed_url = compat_urllib_parse_urlparse(url)
-        for component in [parsed_url.fragment, parsed_url.query]:
-            query = compat_parse_qs(component)
-            if start_time is None and 't' in query:
-                start_time = parse_duration(query['t'][0])
-            if start_time is None and 'start' in query:
-                start_time = parse_duration(query['start'][0])
-            if end_time is None and 'end' in query:
-                end_time = parse_duration(query['end'][0])
-
-        # Extract original video URL from URL with redirection, like age verification, using next_url parameter
-        mobj = re.search(self._NEXT_URL_RE, url)
-        if mobj:
-            url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
-        video_id = self.extract_id(url)
-
-        # Get video webpage
-        url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
-        video_webpage, urlh = self._download_webpage_handle(url, video_id)
-
-        qs = compat_parse_qs(compat_urllib_parse_urlparse(urlh.geturl()).query)
-        video_id = qs.get('v', [None])[0] or video_id
-
-        # Attempt to extract SWF player URL
-        mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
-        if mobj is not None:
-            player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
-        else:
-            player_url = None
-
-        dash_mpds = []
-
-        def add_dash_mpd(video_info):
-            dash_mpd = video_info.get('dashmpd')
-            if dash_mpd and dash_mpd[0] not in dash_mpds:
-                dash_mpds.append(dash_mpd[0])
-
-        def add_dash_mpd_pr(pl_response):
-            dash_mpd = url_or_none(try_get(
-                pl_response, lambda x: x['streamingData']['dashManifestUrl'],
-                compat_str))
-            if dash_mpd and dash_mpd not in dash_mpds:
-                dash_mpds.append(dash_mpd)
-
-        is_live = None
-        view_count = None
-
-        def extract_view_count(v_info):
-            return int_or_none(try_get(v_info, lambda x: x['view_count'][0]))
+        player_response = None
+        if webpage:
+            player_response = self._extract_yt_initial_variable(
+                webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
+                video_id, 'initial player response')
+        if not player_response:
+            player_response = self._call_api(
+                'player', {'videoId': video_id}, video_id)
+
+        playability_status = player_response.get('playabilityStatus') or {}
+        if playability_status.get('reason') == 'Sign in to confirm your age':
+            pr = self._parse_json(try_get(compat_parse_qs(
+                self._download_webpage(
+                    base_url + 'get_video_info', video_id,
+                    'Refetching age-gated info webpage',
+                    'unable to download video info webpage', query={
+                        'video_id': video_id,
+                        'eurl': 'https://www.youtube.com/embed/' + video_id,
+                    }, fatal=False)),
+                lambda x: x['player_response'][0],
+                compat_str) or '{}', video_id)
+            if pr:
+                player_response = pr
+
+        trailer_video_id = try_get(
+            playability_status,
+            lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
+            compat_str)
+        if trailer_video_id:
+            return self.url_result(
+                trailer_video_id, self.ie_key(), trailer_video_id)
 
-        def extract_player_response(player_response, video_id):
-            pl_response = str_or_none(player_response)
-            if not pl_response:
+        def get_text(x):
+            if not x:
                 return
-            pl_response = self._parse_json(pl_response, video_id, fatal=False)
-            if isinstance(pl_response, dict):
-                add_dash_mpd_pr(pl_response)
-                return pl_response
-
-        def extract_embedded_config(embed_webpage, video_id):
-            embedded_config = self._search_regex(
-                r'setConfig\(({.*})\);',
-                embed_webpage, 'ytInitialData', default=None)
-            if embedded_config:
-                return embedded_config
-
-        player_response = {}
-
-        # Get video info
-        video_info = {}
-        embed_webpage = None
-        if (self._og_search_property('restrictions:age', video_webpage, default=None) == '18+'
-                or re.search(r'player-age-gate-content">', video_webpage) is not None):
-            cookie_keys = self._get_cookies('https://www.youtube.com').keys()
-            age_gate = True
-            # We simulate the access to the video from www.youtube.com/v/{video_id}
-            # this can be viewed without login into Youtube
-            url = proto + '://www.youtube.com/embed/%s' % video_id
-            embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
-            ext = extract_embedded_config(embed_webpage, video_id)
-            # playabilityStatus = re.search(r'{\\\"status\\\":\\\"(?P<playabilityStatus>[^\"]+)\\\"', ext)
-            playable_in_embed = re.search(r'{\\\"playableInEmbed\\\":(?P<playableinEmbed>[^\,]+)', ext)
-            if not playable_in_embed:
-                self.to_screen('Could not determine whether playabale in embed for video %s' % video_id)
-                playable_in_embed = ''
-            else:
-                playable_in_embed = playable_in_embed.group('playableinEmbed')
-            # check if video is only playable on youtube in other words not playable in embed - if so it requires auth (cookies)
-            # if re.search(r'player-unavailable">', embed_webpage) is not None:
-            if playable_in_embed == 'false':
-                '''
-                # TODO apply this patch when Support for Python 2.6(!) and above drops
-                if ({'VISITOR_INFO1_LIVE', 'HSID', 'SSID', 'SID'} <= cookie_keys
-                        or {'VISITOR_INFO1_LIVE', '__Secure-3PSID', 'LOGIN_INFO'} <= cookie_keys):
-                '''
-                if (set(('VISITOR_INFO1_LIVE', 'HSID', 'SSID', 'SID')) <= set(cookie_keys)
-                        or set(('VISITOR_INFO1_LIVE', '__Secure-3PSID', 'LOGIN_INFO')) <= set(cookie_keys)):
-                    age_gate = False
-                    # Try looking directly into the video webpage
-                    ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
-                    if ytplayer_config:
-                        args = ytplayer_config.get("args")
-                        if args is not None:
-                            if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
-                                # Convert to the same format returned by compat_parse_qs
-                                video_info = dict((k, [v]) for k, v in args.items())
-                                add_dash_mpd(video_info)
-                            # Rental video is not rented but preview is available (e.g.
-                            # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
-                            # https://github.com/ytdl-org/youtube-dl/issues/10532)
-                            if not video_info and args.get('ypc_vid'):
-                                return self.url_result(
-                                    args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
-                            if args.get('livestream') == '1' or args.get('live_playback') == 1:
-                                is_live = True
-                            if not player_response:
-                                player_response = extract_player_response(args.get('player_response'), video_id)
-                        elif not player_response:
-                            player_response = ytplayer_config
-                    if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
-                        add_dash_mpd_pr(player_response)
-                else:
-                    raise ExtractorError('Video is age restricted and only playable on Youtube. Requires cookies!', expected=True)
-            else:
-                data = compat_urllib_parse_urlencode({
-                    'video_id': video_id,
-                    'eurl': 'https://youtube.googleapis.com/v/' + video_id,
-                    'sts': self._search_regex(
-                        r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
-                })
-                video_info_url = proto + '://www.youtube.com/get_video_info?' + data
-                try:
-                    video_info_webpage = self._download_webpage(
-                        video_info_url, video_id,
-                        note='Refetching age-gated info webpage',
-                        errnote='unable to download video info webpage')
-                except ExtractorError:
-                    video_info_webpage = None
-                if video_info_webpage:
-                    video_info = compat_parse_qs(video_info_webpage)
-                    pl_response = video_info.get('player_response', [None])[0]
-                    player_response = extract_player_response(pl_response, video_id)
-                    add_dash_mpd(video_info)
-                    view_count = extract_view_count(video_info)
-        else:
-            age_gate = False
-            # Try looking directly into the video webpage
-            ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
-            args = ytplayer_config.get("args")
-            if args is not None:
-                if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
-                    # Convert to the same format returned by compat_parse_qs
-                    video_info = dict((k, [v]) for k, v in args.items())
-                    add_dash_mpd(video_info)
-                # Rental video is not rented but preview is available (e.g.
-                # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
-                # https://github.com/ytdl-org/youtube-dl/issues/10532)
-                if not video_info and args.get('ypc_vid'):
-                    return self.url_result(
-                        args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
-                if args.get('livestream') == '1' or args.get('live_playback') == 1:
-                    is_live = True
-                if not player_response:
-                    player_response = extract_player_response(args.get('player_response'), video_id)
-            elif not player_response:
-                player_response = ytplayer_config
-            if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
-                add_dash_mpd_pr(player_response)
-
-        def extract_unavailable_message():
-            messages = []
-            for tag, kind in (('h1', 'message'), ('div', 'submessage')):
-                msg = self._html_search_regex(
-                    r'(?s)<{tag}[^>]+id=["\']unavailable-{kind}["\'][^>]*>(.+?)</{tag}>'.format(tag=tag, kind=kind),
-                    video_webpage, 'unavailable %s' % kind, default=None)
-                if msg:
-                    messages.append(msg)
-            if messages:
-                return '\n'.join(messages)
-
-        if not video_info and not player_response:
-            unavailable_message = extract_unavailable_message()
-            if not unavailable_message:
-                unavailable_message = 'Unable to extract video data'
-            raise ExtractorError(
-                'YouTube said: %s' % unavailable_message, expected=True, video_id=video_id)
+            return x.get('simpleText') or ''.join([r['text'] for r in x['runs']])
 
-        if not isinstance(video_info, dict):
-            video_info = {}
-
-        video_details = try_get(
-            player_response, lambda x: x['videoDetails'], dict) or {}
+        search_meta = (
+            lambda x: self._html_search_meta(x, webpage, default=None)) \
+            if webpage else lambda x: None
 
+        video_details = player_response.get('videoDetails') or {}
         microformat = try_get(
-            player_response, lambda x: x['microformat']['playerMicroformatRenderer'], dict) or {}
-
-        video_title = video_info.get('title', [None])[0] or video_details.get('title')
-        if not video_title:
-            self._downloader.report_warning('Unable to extract video title')
-            video_title = '_'
-
-        description_original = video_description = get_element_by_id("eow-description", video_webpage)
-        if video_description:
-
-            def replace_url(m):
-                redir_url = compat_urlparse.urljoin(url, m.group(1))
-                parsed_redir_url = compat_urllib_parse_urlparse(redir_url)
-                if re.search(r'^(?:www\.)?(?:youtube(?:-nocookie)?\.com|youtu\.be)$', parsed_redir_url.netloc) and parsed_redir_url.path == '/redirect':
-                    qs = compat_parse_qs(parsed_redir_url.query)
-                    q = qs.get('q')
-                    if q and q[0]:
-                        return q[0]
-                return redir_url
-
-            description_original = video_description = re.sub(r'''(?x)
-                <a\s+
-                    (?:[a-zA-Z-]+="[^"]*"\s+)*?
-                    (?:title|href)="([^"]+)"\s+
-                    (?:[a-zA-Z-]+="[^"]*"\s+)*?
-                    class="[^"]*"[^>]*>
-                [^<]+\.{3}\s*
-                </a>
-            ''', replace_url, video_description)
-            video_description = clean_html(video_description)
-        else:
-            video_description = video_details.get('shortDescription')
-            if video_description is None:
-                video_description = self._html_search_meta('description', video_webpage)
+            player_response,
+            lambda x: x['microformat']['playerMicroformatRenderer'],
+            dict) or {}
+        video_title = video_details.get('title') \
+            or get_text(microformat.get('title')) \
+            or search_meta(['og:title', 'twitter:title', 'title'])
+        video_description = video_details.get('shortDescription')
 
         if not smuggled_data.get('force_singlefeed', False):
             if not self._downloader.params.get('noplaylist'):
                 multifeed_metadata_list = try_get(
                     player_response,
                     lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
-                    compat_str) or try_get(
-                    video_info, lambda x: x['multifeed_metadata_list'][0], compat_str)
+                    compat_str)
                 if multifeed_metadata_list:
                     entries = []
                     feed_ids = []
@@ -2032,10 +1519,12 @@ def replace_url(m):
                         # Unquote should take place before split on comma (,) since textual
                         # fields may contain comma as well (see
                         # https://github.com/ytdl-org/youtube-dl/issues/8536)
-                        feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
+                        feed_data = compat_parse_qs(
+                            compat_urllib_parse_unquote_plus(feed))
 
                         def feed_entry(name):
-                            return try_get(feed_data, lambda x: x[name][0], compat_str)
+                            return try_get(
+                                feed_data, lambda x: x[name][0], compat_str)
 
                         feed_id = feed_entry('id')
                         if not feed_id:
@@ -2048,7 +1537,7 @@ def feed_entry(name):
                             '_type': 'url_transparent',
                             'ie_key': 'Youtube',
                             'url': smuggle_url(
-                                '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
+                                base_url + 'watch?v=' + feed_data['id'][0],
                                 {'force_singlefeed': True}),
                             'title': title,
                         })
@@ -2056,644 +1545,678 @@ def feed_entry(name):
                     self.to_screen(
                         'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
                         % (', '.join(feed_ids), video_id))
-                    return self.playlist_result(entries, video_id, video_title, video_description)
+                    return self.playlist_result(
+                        entries, video_id, video_title, video_description)
             else:
                 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
 
-        if view_count is None:
-            view_count = extract_view_count(video_info)
-        if view_count is None and video_details:
-            view_count = int_or_none(video_details.get('viewCount'))
-        if view_count is None and microformat:
-            view_count = int_or_none(microformat.get('viewCount'))
-
-        if is_live is None:
-            is_live = bool_or_none(video_details.get('isLive'))
+        formats = []
+        itags = []
+        itag_qualities = {}
+        player_url = None
+        q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
+        streaming_data = player_response.get('streamingData') or {}
+        streaming_formats = streaming_data.get('formats') or []
+        streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
+        for fmt in streaming_formats:
+            if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
+                continue
 
-        has_live_chat_replay = False
-        if not is_live:
-            yt_initial_data = self._get_yt_initial_data(video_id, video_webpage)
-            try:
-                yt_initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
-                has_live_chat_replay = True
-            except (KeyError, IndexError, TypeError):
-                pass
+            itag = str_or_none(fmt.get('itag'))
+            quality = fmt.get('quality')
+            if itag and quality:
+                itag_qualities[itag] = quality
+            # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
+            # (adding `&sq=0` to the URL) and parsing emsg box to determine the
+            # number of fragment that would subsequently requested with (`&sq=N`)
+            if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
+                continue
 
-        # Check for "rental" videos
-        if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
-            raise ExtractorError('"rental" videos not supported. See https://github.com/ytdl-org/youtube-dl/issues/359 for more information.', expected=True)
-
-        def _extract_filesize(media_url):
-            return int_or_none(self._search_regex(
-                r'\bclen[=/](\d+)', media_url, 'filesize', default=None))
-
-        streaming_formats = try_get(player_response, lambda x: x['streamingData']['formats'], list) or []
-        streaming_formats.extend(try_get(player_response, lambda x: x['streamingData']['adaptiveFormats'], list) or [])
-
-        if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
-            self.report_rtmp_download()
-            formats = [{
-                'format_id': '_rtmp',
-                'protocol': 'rtmp',
-                'url': video_info['conn'][0],
-                'player_url': player_url,
-            }]
-        elif not is_live and (streaming_formats or len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1):
-            encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
-            if 'rtmpe%3Dyes' in encoded_url_map:
-                raise ExtractorError('rtmpe downloads are not supported, see https://github.com/ytdl-org/youtube-dl/issues/343 for more information.', expected=True)
-            formats = []
-            formats_spec = {}
-            fmt_list = video_info.get('fmt_list', [''])[0]
-            if fmt_list:
-                for fmt in fmt_list.split(','):
-                    spec = fmt.split('/')
-                    if len(spec) > 1:
-                        width_height = spec[1].split('x')
-                        if len(width_height) == 2:
-                            formats_spec[spec[0]] = {
-                                'resolution': spec[1],
-                                'width': int_or_none(width_height[0]),
-                                'height': int_or_none(width_height[1]),
-                            }
-            for fmt in streaming_formats:
-                itag = str_or_none(fmt.get('itag'))
-                if not itag:
+            fmt_url = fmt.get('url')
+            if not fmt_url:
+                sc = compat_parse_qs(fmt.get('signatureCipher'))
+                fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
+                encrypted_sig = try_get(sc, lambda x: x['s'][0])
+                if not (sc and fmt_url and encrypted_sig):
+                    continue
+                if not player_url:
+                    if not webpage:
+                        continue
+                    player_url = self._search_regex(
+                        r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
+                        webpage, 'player URL', fatal=False)
+                if not player_url:
                     continue
-                quality = fmt.get('quality')
-                quality_label = fmt.get('qualityLabel') or quality
-                formats_spec[itag] = {
-                    'asr': int_or_none(fmt.get('audioSampleRate')),
-                    'filesize': int_or_none(fmt.get('contentLength')),
-                    'format_note': quality_label,
-                    'fps': int_or_none(fmt.get('fps')),
-                    'height': int_or_none(fmt.get('height')),
-                    # bitrate for itag 43 is always 2147483647
-                    'tbr': float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000) if itag != '43' else None,
-                    'width': int_or_none(fmt.get('width')),
+                signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
+                sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
+                fmt_url += '&' + sp + '=' + signature
+
+            if itag:
+                itags.append(itag)
+            tbr = float_or_none(
+                fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
+            dct = {
+                'asr': int_or_none(fmt.get('audioSampleRate')),
+                'filesize': int_or_none(fmt.get('contentLength')),
+                'format_id': itag,
+                'format_note': fmt.get('qualityLabel') or quality,
+                'fps': int_or_none(fmt.get('fps')),
+                'height': int_or_none(fmt.get('height')),
+                'quality': q(quality),
+                'tbr': tbr,
+                'url': fmt_url,
+                'width': fmt.get('width'),
+            }
+            mimetype = fmt.get('mimeType')
+            if mimetype:
+                mobj = re.match(
+                    r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
+                if mobj:
+                    dct['ext'] = mimetype2ext(mobj.group(1))
+                    dct.update(parse_codecs(mobj.group(2)))
+            no_audio = dct.get('acodec') == 'none'
+            no_video = dct.get('vcodec') == 'none'
+            if no_audio:
+                dct['vbr'] = tbr
+            if no_video:
+                dct['abr'] = tbr
+            if no_audio or no_video:
+                dct['downloader_options'] = {
+                    # Youtube throttles chunks >~10M
+                    'http_chunk_size': 10485760,
                 }
+            formats.append(dct)
+
+        hls_manifest_url = streaming_data.get('hlsManifestUrl')
+        if hls_manifest_url:
+            for f in self._extract_m3u8_formats(
+                    hls_manifest_url, video_id, 'mp4', fatal=False):
+                itag = self._search_regex(
+                    r'/itag/(\d+)', f['url'], 'itag', default=None)
+                if itag:
+                    f['format_id'] = itag
+                formats.append(f)
+
+        if self._downloader.params.get('youtube_include_dash_manifest'):
+            dash_manifest_url = streaming_data.get('dashManifestUrl')
+            if dash_manifest_url:
+                for f in self._extract_mpd_formats(
+                        dash_manifest_url, video_id, fatal=False):
+                    itag = f['format_id']
+                    if itag in itags:
+                        continue
+                    if itag in itag_qualities:
+                        # Not actually usefull since the sorting is already done with "quality,res,fps,codec"
+                        # but kept to maintain feature parity (and code similarity) with youtube-dl
+                        # Remove if this causes any issues with sorting in future
+                        f['quality'] = q(itag_qualities[itag])
+                    filesize = int_or_none(self._search_regex(
+                        r'/clen/(\d+)', f.get('fragment_base_url')
+                        or f['url'], 'file size', default=None))
+                    if filesize:
+                        f['filesize'] = filesize
+                    formats.append(f)
 
-            for fmt in streaming_formats:
-                if fmt.get('drmFamilies') or fmt.get('drm_families'):
-                    continue
-                url = url_or_none(fmt.get('url'))
+        if not formats:
+            if not self._downloader.params.get('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
+                raise ExtractorError(
+                    'This video is DRM protected.', expected=True)
+            pemr = try_get(
+                playability_status,
+                lambda x: x['errorScreen']['playerErrorMessageRenderer'],
+                dict) or {}
+            reason = get_text(pemr.get('reason')) or playability_status.get('reason')
+            subreason = pemr.get('subreason')
+            if subreason:
+                subreason = clean_html(get_text(subreason))
+                if subreason == 'The uploader has not made this video available in your country.':
+                    countries = microformat.get('availableCountries')
+                    if not countries:
+                        regions_allowed = search_meta('regionsAllowed')
+                        countries = regions_allowed.split(',') if regions_allowed else None
+                    self.raise_geo_restricted(
+                        subreason, countries)
+                reason += '\n' + subreason
+            if reason:
+                raise ExtractorError(reason, expected=True)
 
-                if not url:
-                    cipher = fmt.get('cipher') or fmt.get('signatureCipher')
-                    if not cipher:
-                        continue
-                    url_data = compat_parse_qs(cipher)
-                    url = url_or_none(try_get(url_data, lambda x: x['url'][0], compat_str))
-                    if not url:
-                        continue
-                else:
-                    cipher = None
-                    url_data = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
+        self._sort_formats(formats)
 
-                stream_type = int_or_none(try_get(url_data, lambda x: x['stream_type'][0]))
-                # Unsupported FORMAT_STREAM_TYPE_OTF
-                if stream_type == 3:
-                    continue
+        keywords = video_details.get('keywords') or []
+        if not keywords and webpage:
+            keywords = [
+                unescapeHTML(m.group('content'))
+                for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
+        for keyword in keywords:
+            if keyword.startswith('yt:stretch='):
+                w, h = keyword.split('=')[1].split(':')
+                w, h = int(w), int(h)
+                if w > 0 and h > 0:
+                    ratio = w / h
+                    for f in formats:
+                        if f.get('vcodec') != 'none':
+                            f['stretched_ratio'] = ratio
 
-                format_id = fmt.get('itag') or url_data['itag'][0]
-                if not format_id:
+        thumbnails = []
+        for container in (video_details, microformat):
+            for thumbnail in (try_get(
+                    container,
+                    lambda x: x['thumbnail']['thumbnails'], list) or []):
+                thumbnail_url = thumbnail.get('url')
+                if not thumbnail_url:
                     continue
-                format_id = compat_str(format_id)
-
-                if cipher:
-                    if 's' in url_data or self._downloader.params.get('youtube_include_dash_manifest', True):
-                        ASSETS_RE = r'(?:"assets":.+?"js":\s*("[^"]+"))|(?:"jsUrl":\s*("[^"]+"))'
-                        jsplayer_url_json = self._search_regex(
-                            ASSETS_RE,
-                            embed_webpage if age_gate else video_webpage,
-                            'JS player URL (1)', default=None)
-                        if not jsplayer_url_json and not age_gate:
-                            # We need the embed website after all
-                            if embed_webpage is None:
-                                embed_url = proto + '://www.youtube.com/embed/%s' % video_id
-                                embed_webpage = self._download_webpage(
-                                    embed_url, video_id, 'Downloading embed webpage')
-                            jsplayer_url_json = self._search_regex(
-                                ASSETS_RE, embed_webpage, 'JS player URL')
-
-                        player_url = json.loads(jsplayer_url_json)
-                        if player_url is None:
-                            player_url_json = self._search_regex(
-                                r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
-                                video_webpage, 'age gate player URL')
-                            player_url = json.loads(player_url_json)
-
-                    if 'sig' in url_data:
-                        url += '&signature=' + url_data['sig'][0]
-                    elif 's' in url_data:
-                        encrypted_sig = url_data['s'][0]
-
-                        if self._downloader.params.get('verbose'):
-                            if player_url is None:
-                                player_desc = 'unknown'
-                            else:
-                                player_type, player_version = self._extract_player_info(player_url)
-                                player_desc = '%s player %s' % ('flash' if player_type == 'swf' else 'html5', player_version)
-                            parts_sizes = self._signature_cache_id(encrypted_sig)
-                            self.to_screen('{%s} signature length %s, %s' %
-                                           (format_id, parts_sizes, player_desc))
-
-                        signature = self._decrypt_signature(
-                            encrypted_sig, video_id, player_url, age_gate)
-                        sp = try_get(url_data, lambda x: x['sp'][0], compat_str) or 'signature'
-                        url += '&%s=%s' % (sp, signature)
-                if 'ratebypass' not in url:
-                    url += '&ratebypass=yes'
-
-                dct = {
-                    'format_id': format_id,
-                    'url': url,
-                    'player_url': player_url,
-                }
-                if format_id in self._formats:
-                    dct.update(self._formats[format_id])
-                if format_id in formats_spec:
-                    dct.update(formats_spec[format_id])
-
-                # Some itags are not included in DASH manifest thus corresponding formats will
-                # lack metadata (see https://github.com/ytdl-org/youtube-dl/pull/5993).
-                # Trying to extract metadata from url_encoded_fmt_stream_map entry.
-                mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
-                width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
-
-                if width is None:
-                    width = int_or_none(fmt.get('width'))
-                if height is None:
-                    height = int_or_none(fmt.get('height'))
-
-                filesize = int_or_none(url_data.get(
-                    'clen', [None])[0]) or _extract_filesize(url)
-
-                quality = url_data.get('quality', [None])[0] or fmt.get('quality')
-                quality_label = url_data.get('quality_label', [None])[0] or fmt.get('qualityLabel')
-
-                tbr = (float_or_none(url_data.get('bitrate', [None])[0], 1000)
-                       or float_or_none(fmt.get('bitrate'), 1000)) if format_id != '43' else None
-                fps = int_or_none(url_data.get('fps', [None])[0]) or int_or_none(fmt.get('fps'))
-
-                more_fields = {
-                    'filesize': filesize,
-                    'tbr': tbr,
-                    'width': width,
-                    'height': height,
-                    'fps': fps,
-                    'format_note': quality_label or quality,
-                }
-                for key, value in more_fields.items():
-                    if value:
-                        dct[key] = value
-                type_ = url_data.get('type', [None])[0] or fmt.get('mimeType')
-                if type_:
-                    type_split = type_.split(';')
-                    kind_ext = type_split[0].split('/')
-                    if len(kind_ext) == 2:
-                        kind, _ = kind_ext
-                        dct['ext'] = mimetype2ext(type_split[0])
-                        if kind in ('audio', 'video'):
-                            codecs = None
-                            for mobj in re.finditer(
-                                    r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
-                                if mobj.group('key') == 'codecs':
-                                    codecs = mobj.group('val')
-                                    break
-                            if codecs:
-                                dct.update(parse_codecs(codecs))
-                if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
-                    dct['downloader_options'] = {
-                        # Youtube throttles chunks >~10M
-                        'http_chunk_size': 10485760,
-                    }
-                formats.append(dct)
+                thumbnails.append({
+                    'height': int_or_none(thumbnail.get('height')),
+                    'url': thumbnail_url,
+                    'width': int_or_none(thumbnail.get('width')),
+                })
+            if thumbnails:
+                break
         else:
-            manifest_url = (
-                url_or_none(try_get(
-                    player_response,
-                    lambda x: x['streamingData']['hlsManifestUrl'],
-                    compat_str))
-                or url_or_none(try_get(
-                    video_info, lambda x: x['hlsvp'][0], compat_str)))
-            if manifest_url:
-                formats = []
-                m3u8_formats = self._extract_m3u8_formats(
-                    manifest_url, video_id, 'mp4', fatal=False)
-                for a_format in m3u8_formats:
-                    itag = self._search_regex(
-                        r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
-                    if itag:
-                        a_format['format_id'] = itag
-                        if itag in self._formats:
-                            dct = self._formats[itag].copy()
-                            dct.update(a_format)
-                            a_format = dct
-                    a_format['player_url'] = player_url
-                    # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
-                    a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
-                    if self._downloader.params.get('youtube_include_hls_manifest', True):
-                        formats.append(a_format)
-            else:
-                error_message = extract_unavailable_message()
-                if not error_message:
-                    error_message = clean_html(try_get(
-                        player_response, lambda x: x['playabilityStatus']['reason'],
-                        compat_str))
-                if not error_message:
-                    error_message = clean_html(
-                        try_get(video_info, lambda x: x['reason'][0], compat_str))
-                if error_message:
-                    raise ExtractorError(error_message, expected=True)
-                raise ExtractorError('no conn, hlsvp, hlsManifestUrl or url_encoded_fmt_stream_map information found in video info')
-
-        # uploader
-        video_uploader = try_get(
-            video_info, lambda x: x['author'][0],
-            compat_str) or str_or_none(video_details.get('author'))
-        if video_uploader:
-            video_uploader = compat_urllib_parse_unquote_plus(video_uploader)
-        else:
-            self._downloader.report_warning('unable to extract uploader name')
-
-        # uploader_id
-        video_uploader_id = None
-        video_uploader_url = None
-        mobj = re.search(
-            r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
-            video_webpage)
-        if mobj is not None:
-            video_uploader_id = mobj.group('uploader_id')
-            video_uploader_url = mobj.group('uploader_url')
-        else:
-            owner_profile_url = url_or_none(microformat.get('ownerProfileUrl'))
-            if owner_profile_url:
-                video_uploader_id = self._search_regex(
-                    r'(?:user|channel)/([^/]+)', owner_profile_url, 'uploader id',
-                    default=None)
-                video_uploader_url = owner_profile_url
-
-        channel_id = (
-            str_or_none(video_details.get('channelId'))
-            or self._html_search_meta(
-                'channelId', video_webpage, 'channel id', default=None)
-            or self._search_regex(
-                r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
-                video_webpage, 'channel id', default=None, group='id'))
-        channel_url = 'http://www.youtube.com/channel/%s' % channel_id if channel_id else None
-
-        thumbnails = []
-        thumbnails_list = try_get(
-            video_details, lambda x: x['thumbnail']['thumbnails'], list) or []
-        for t in thumbnails_list:
-            if not isinstance(t, dict):
-                continue
-            thumbnail_url = url_or_none(t.get('url'))
-            if not thumbnail_url:
-                continue
-            thumbnails.append({
-                'url': thumbnail_url,
-                'width': int_or_none(t.get('width')),
-                'height': int_or_none(t.get('height')),
-            })
-
-        if not thumbnails:
-            video_thumbnail = None
-            # We try first to get a high quality image:
-            m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
-                                video_webpage, re.DOTALL)
-            if m_thumb is not None:
-                video_thumbnail = m_thumb.group(1)
-            thumbnail_url = try_get(video_info, lambda x: x['thumbnail_url'][0], compat_str)
-            if thumbnail_url:
-                video_thumbnail = compat_urllib_parse_unquote_plus(thumbnail_url)
-            if video_thumbnail:
-                thumbnails.append({'url': video_thumbnail})
-
-        # upload date
-        upload_date = self._html_search_meta(
-            'datePublished', video_webpage, 'upload date', default=None)
-        if not upload_date:
-            upload_date = self._search_regex(
-                [r'(?s)id="eow-date.*?>(.*?)</span>',
-                 r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'],
-                video_webpage, 'upload date', default=None)
-        if not upload_date:
-            upload_date = microformat.get('publishDate') or microformat.get('uploadDate')
-        upload_date = unified_strdate(upload_date)
-
-        video_license = self._html_search_regex(
-            r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
-            video_webpage, 'license', default=None)
-
-        m_music = re.search(
-            r'''(?x)
-                <h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*
-                <ul[^>]*>\s*
-                <li>(?P<title>.+?)
-                by (?P<creator>.+?)
-                (?:
-                    \(.+?\)|
-                    <a[^>]*
-                        (?:
-                            \bhref=["\']/red[^>]*>|             # drop possible
-                            >\s*Listen ad-free with YouTube Red # YouTube Red ad
-                        )
-                    .*?
-                )?</li
-            ''',
-            video_webpage)
-        if m_music:
-            video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
-            video_creator = clean_html(m_music.group('creator'))
-        else:
-            video_alt_title = video_creator = None
+            thumbnail = search_meta(['og:image', 'twitter:image'])
+            if thumbnail:
+                thumbnails = [{'url': thumbnail}]
+
+        category = microformat.get('category') or search_meta('genre')
+        channel_id = video_details.get('channelId') \
+            or microformat.get('externalChannelId') \
+            or search_meta('channelId')
+        duration = int_or_none(
+            video_details.get('lengthSeconds')
+            or microformat.get('lengthSeconds')) \
+            or parse_duration(search_meta('duration'))
+        is_live = video_details.get('isLive')
+        owner_profile_url = microformat.get('ownerProfileUrl')
+
+        info = {
+            'id': video_id,
+            'title': self._live_title(video_title) if is_live else video_title,
+            'formats': formats,
+            'thumbnails': thumbnails,
+            'description': video_description,
+            'upload_date': unified_strdate(
+                microformat.get('uploadDate')
+                or search_meta('uploadDate')),
+            'uploader': video_details['author'],
+            'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
+            'uploader_url': owner_profile_url,
+            'channel_id': channel_id,
+            'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
+            'duration': duration,
+            'view_count': int_or_none(
+                video_details.get('viewCount')
+                or microformat.get('viewCount')
+                or search_meta('interactionCount')),
+            'average_rating': float_or_none(video_details.get('averageRating')),
+            'age_limit': 18 if (
+                microformat.get('isFamilySafe') is False
+                or search_meta('isFamilyFriendly') == 'false'
+                or search_meta('og:restrictions:age') == '18+') else 0,
+            'webpage_url': webpage_url,
+            'categories': [category] if category else None,
+            'tags': keywords,
+            'is_live': is_live,
+            'playable_in_embed': playability_status.get('playableInEmbed'),
+            'was_live': video_details.get('isLiveContent')
+        }
 
-        def extract_meta(field):
-            return self._html_search_regex(
-                r'<h4[^>]+class="title"[^>]*>\s*%s\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li>\s*' % field,
-                video_webpage, field, default=None)
+        pctr = try_get(
+            player_response,
+            lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
+        subtitles = {}
+        if pctr:
+            def process_language(container, base_url, lang_code, query):
+                lang_subs = []
+                for fmt in self._SUBTITLE_FORMATS:
+                    query.update({
+                        'fmt': fmt,
+                    })
+                    lang_subs.append({
+                        'ext': fmt,
+                        'url': update_url_query(base_url, query),
+                    })
+                container[lang_code] = lang_subs
+
+            for caption_track in (pctr.get('captionTracks') or []):
+                base_url = caption_track.get('baseUrl')
+                if not base_url:
+                    continue
+                if caption_track.get('kind') != 'asr':
+                    lang_code = caption_track.get('languageCode')
+                    if not lang_code:
+                        continue
+                    process_language(
+                        subtitles, base_url, lang_code, {})
+                    continue
+                automatic_captions = {}
+                for translation_language in (pctr.get('translationLanguages') or []):
+                    translation_language_code = translation_language.get('languageCode')
+                    if not translation_language_code:
+                        continue
+                    process_language(
+                        automatic_captions, base_url, translation_language_code,
+                        {'tlang': translation_language_code})
+                info['automatic_captions'] = automatic_captions
+        info['subtitles'] = subtitles
 
-        track = extract_meta('Song')
-        artist = extract_meta('Artist')
-        album = extract_meta('Album')
+        parsed_url = compat_urllib_parse_urlparse(url)
+        for component in [parsed_url.fragment, parsed_url.query]:
+            query = compat_parse_qs(component)
+            for k, v in query.items():
+                for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
+                    d_k += '_time'
+                    if d_k not in info and k in s_ks:
+                        info[d_k] = parse_duration(query[k][0])
 
         # Youtube Music Auto-generated description
-        release_date = release_year = None
         if video_description:
-            mobj = re.search(r'(?s)Provided to YouTube by [^\n]+\n+(?P<track>[^·]+)·(?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]+))?', video_description)
+            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)
             if mobj:
-                if not track:
-                    track = mobj.group('track').strip()
-                if not artist:
-                    artist = mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·'))
-                if not album:
-                    album = mobj.group('album'.strip())
                 release_year = mobj.group('release_year')
                 release_date = mobj.group('release_date')
                 if release_date:
                     release_date = release_date.replace('-', '')
                     if not release_year:
-                        release_year = int(release_date[:4])
-                if release_year:
-                    release_year = int(release_year)
-
-        yt_initial = self._get_yt_initial_data(video_id, video_webpage)
-        if yt_initial:
-            music_metadata = self._get_music_metadata_from_yt_initial(yt_initial)
-            if len(music_metadata):
-                album = music_metadata[0].get('album')
-                artist = music_metadata[0].get('artist')
-                track = music_metadata[0].get('track')
-
-        m_episode = re.search(
-            r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
-            video_webpage)
-        if m_episode:
-            series = unescapeHTML(m_episode.group('series'))
-            season_number = int(m_episode.group('season'))
-            episode_number = int(m_episode.group('episode'))
-        else:
-            series = season_number = episode_number = None
-
-        m_cat_container = self._search_regex(
-            r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
-            video_webpage, 'categories', default=None)
-        category = None
-        if m_cat_container:
-            category = self._html_search_regex(
-                r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
-                default=None)
-        if not category:
-            category = try_get(
-                microformat, lambda x: x['category'], compat_str)
-        video_categories = None if category is None else [category]
-
-        video_tags = [
-            unescapeHTML(m.group('content'))
-            for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
-        if not video_tags:
-            video_tags = try_get(video_details, lambda x: x['keywords'], list)
-
-        def _extract_count(count_name):
-            return str_to_int(self._search_regex(
-                r'"accessibilityData":\{"label":"([\d,\w]+) %ss"\}'
-                % re.escape(count_name),
-                video_webpage, count_name, default=None))
-
-        like_count = _extract_count('like')
-        dislike_count = _extract_count('dislike')
-
-        if view_count is None:
-            view_count = str_to_int(self._search_regex(
-                r'<[^>]+class=["\']watch-view-count[^>]+>\s*([\d,\s]+)', video_webpage,
-                'view count', default=None))
-
-        average_rating = (
-            float_or_none(video_details.get('averageRating'))
-            or try_get(video_info, lambda x: float_or_none(x['avg_rating'][0])))
-
-        # subtitles
-        video_subtitles = self.extract_subtitles(
-            video_id, video_webpage, has_live_chat_replay)
-        automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
-
-        video_duration = try_get(
-            video_info, lambda x: int_or_none(x['length_seconds'][0]))
-        if not video_duration:
-            video_duration = int_or_none(video_details.get('lengthSeconds'))
-        if not video_duration:
-            video_duration = parse_duration(self._html_search_meta(
-                'duration', video_webpage, 'video duration'))
-
-        # Get Subscriber Count of channel
-        subscriber_count = parse_count(self._search_regex(
-            r'"text":"([\d\.]+\w?) subscribers"',
-            video_webpage,
-            'subscriber count',
-            default=None
-        ))
+                        release_year = release_date[:4]
+                info.update({
+                    'album': mobj.group('album'.strip()),
+                    'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
+                    'track': mobj.group('track').strip(),
+                    'release_date': release_date,
+                    'release_year': int_or_none(release_year),
+                })
+
+        initial_data = None
+        if webpage:
+            initial_data = self._extract_yt_initial_variable(
+                webpage, self._YT_INITIAL_DATA_RE, video_id,
+                'yt initial data')
+        if not initial_data:
+            initial_data = self._call_api(
+                'next', {'videoId': video_id}, video_id, fatal=False)
+
+        if not is_live:
+            try:
+                # This will error if there is no livechat
+                initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
+                info['subtitles']['live_chat'] = [{
+                    'video_id': video_id,
+                    'ext': 'json',
+                    'protocol': 'youtube_live_chat_replay',
+                }]
+            except (KeyError, IndexError, TypeError):
+                pass
+
+        if initial_data:
+            chapters = self._extract_chapters_from_json(
+                initial_data, video_id, duration)
+            if not chapters:
+                for engagment_pannel in (initial_data.get('engagementPanels') or []):
+                    contents = try_get(
+                        engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
+                        list)
+                    if not contents:
+                        continue
+
+                    def chapter_time(mmlir):
+                        return parse_duration(
+                            get_text(mmlir.get('timeDescription')))
+
+                    chapters = []
+                    for next_num, content in enumerate(contents, start=1):
+                        mmlir = content.get('macroMarkersListItemRenderer') or {}
+                        start_time = chapter_time(mmlir)
+                        end_time = chapter_time(try_get(
+                            contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
+                            if next_num < len(contents) else duration
+                        if start_time is None or end_time is None:
+                            continue
+                        chapters.append({
+                            'start_time': start_time,
+                            'end_time': end_time,
+                            'title': get_text(mmlir.get('title')),
+                        })
+                    if chapters:
+                        break
+            if chapters:
+                info['chapters'] = chapters
+
+            contents = try_get(
+                initial_data,
+                lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
+                list) or []
+            for content in contents:
+                vpir = content.get('videoPrimaryInfoRenderer')
+                if vpir:
+                    stl = vpir.get('superTitleLink')
+                    if stl:
+                        stl = get_text(stl)
+                        if try_get(
+                                vpir,
+                                lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
+                            info['location'] = stl
+                        else:
+                            mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
+                            if mobj:
+                                info.update({
+                                    'series': mobj.group(1),
+                                    'season_number': int(mobj.group(2)),
+                                    'episode_number': int(mobj.group(3)),
+                                })
+                    for tlb in (try_get(
+                            vpir,
+                            lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
+                            list) or []):
+                        tbr = tlb.get('toggleButtonRenderer') or {}
+                        for getter, regex in [(
+                                lambda x: x['defaultText']['accessibility']['accessibilityData'],
+                                r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
+                                    lambda x: x['accessibility'],
+                                    lambda x: x['accessibilityData']['accessibilityData'],
+                                ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
+                            label = (try_get(tbr, getter, dict) or {}).get('label')
+                            if label:
+                                mobj = re.match(regex, label)
+                                if mobj:
+                                    info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
+                                    break
+                    sbr_tooltip = try_get(
+                        vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
+                    if sbr_tooltip:
+                        like_count, dislike_count = sbr_tooltip.split(' / ')
+                        info.update({
+                            'like_count': str_to_int(like_count),
+                            'dislike_count': str_to_int(dislike_count),
+                        })
+                vsir = content.get('videoSecondaryInfoRenderer')
+                if vsir:
+                    info['channel'] = get_text(try_get(
+                        vsir,
+                        lambda x: x['owner']['videoOwnerRenderer']['title'],
+                        compat_str))
+                    rows = try_get(
+                        vsir,
+                        lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
+                        list) or []
+                    multiple_songs = False
+                    for row in rows:
+                        if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
+                            multiple_songs = True
+                            break
+                    for row in rows:
+                        mrr = row.get('metadataRowRenderer') or {}
+                        mrr_title = mrr.get('title')
+                        if not mrr_title:
+                            continue
+                        mrr_title = get_text(mrr['title'])
+                        mrr_contents_text = get_text(mrr['contents'][0])
+                        if mrr_title == 'License':
+                            info['license'] = mrr_contents_text
+                        elif not multiple_songs:
+                            if mrr_title == 'Album':
+                                info['album'] = mrr_contents_text
+                            elif mrr_title == 'Artist':
+                                info['artist'] = mrr_contents_text
+                            elif mrr_title == 'Song':
+                                info['track'] = mrr_contents_text
+
+        fallbacks = {
+            'channel': 'uploader',
+            'channel_id': 'uploader_id',
+            'channel_url': 'uploader_url',
+        }
+        for to, frm in fallbacks.items():
+            if not info.get(to):
+                info[to] = info.get(frm)
+
+        for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
+            v = info.get(s_k)
+            if v:
+                info[d_k] = v
+
+        # get xsrf for annotations or comments
+        get_annotations = self._downloader.params.get('writeannotations', False)
+        get_comments = self._downloader.params.get('getcomments', False)
+        if get_annotations or get_comments:
+            xsrf_token = None
+            ytcfg = self._extract_ytcfg(video_id, webpage)
+            if ytcfg:
+                xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
+            if not xsrf_token:
+                xsrf_token = self._search_regex(
+                    r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
+                    webpage, 'xsrf token', group='xsrf_token', fatal=False)
 
         # annotations
-        video_annotations = None
-        if self._downloader.params.get('writeannotations', False):
-            xsrf_token = self._search_regex(
-                r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>[A-Za-z0-9+/=]+)\2',
-                video_webpage, 'xsrf token', group='xsrf_token', fatal=False)
+        if get_annotations:
             invideo_url = try_get(
                 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
             if xsrf_token and invideo_url:
-                xsrf_field_name = self._search_regex(
-                    r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
-                    video_webpage, 'xsrf field name',
-                    group='xsrf_field_name', default='session_token')
-                video_annotations = self._download_webpage(
+                xsrf_field_name = None
+                if ytcfg:
+                    xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
+                if not xsrf_field_name:
+                    xsrf_field_name = self._search_regex(
+                        r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
+                        webpage, 'xsrf field name',
+                        group='xsrf_field_name', default='session_token')
+                info['annotations'] = self._download_webpage(
                     self._proto_relative_url(invideo_url),
                     video_id, note='Downloading annotations',
                     errnote='Unable to download video annotations', fatal=False,
                     data=urlencode_postdata({xsrf_field_name: xsrf_token}))
 
-        chapters = self._extract_chapters(video_webpage, description_original, video_id, video_duration)
-
-        # Look for the DASH manifest
-        if self._downloader.params.get('youtube_include_dash_manifest', True):
-            dash_mpd_fatal = True
-            for mpd_url in dash_mpds:
-                dash_formats = {}
+        # Get comments
+        # TODO: Refactor and move to seperate function
+        if get_comments:
+            expected_video_comment_count = 0
+            video_comments = []
+
+            def find_value(html, key, num_chars=2, separator='"'):
+                pos_begin = html.find(key) + len(key) + num_chars
+                pos_end = html.find(separator, pos_begin)
+                return html[pos_begin: pos_end]
+
+            def search_dict(partial, key):
+                if isinstance(partial, dict):
+                    for k, v in partial.items():
+                        if k == key:
+                            yield v
+                        else:
+                            for o in search_dict(v, key):
+                                yield o
+                elif isinstance(partial, list):
+                    for i in partial:
+                        for o in search_dict(i, key):
+                            yield o
+
+            continuations = []
+            if initial_data:
                 try:
-                    def decrypt_sig(mobj):
-                        s = mobj.group(1)
-                        dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
-                        return '/signature/%s' % dec_s
-
-                    mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
-
-                    for df in self._extract_mpd_formats(
-                            mpd_url, video_id, fatal=dash_mpd_fatal,
-                            formats_dict=self._formats):
-                        if not df.get('filesize'):
-                            df['filesize'] = _extract_filesize(df['url'])
-                        # Do not overwrite DASH format found in some previous DASH manifest
-                        if df['format_id'] not in dash_formats:
-                            dash_formats[df['format_id']] = df
-                        # Additional DASH manifests may end up in HTTP Error 403 therefore
-                        # allow them to fail without bug report message if we already have
-                        # some DASH manifest succeeded. This is temporary workaround to reduce
-                        # burst of bug reports until we figure out the reason and whether it
-                        # can be fixed at all.
-                        dash_mpd_fatal = False
-                except (ExtractorError, KeyError) as e:
-                    self.report_warning(
-                        'Skipping DASH manifest: %r' % e, video_id)
-                if dash_formats:
-                    # Remove the formats we found through non-DASH, they
-                    # contain less info and it can be wrong, because we use
-                    # fixed values (for example the resolution). See
-                    # https://github.com/ytdl-org/youtube-dl/issues/5774 for an
-                    # example.
-                    formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
-                    formats.extend(dash_formats.values())
-
-        # Check for malformed aspect ratio
-        stretched_m = re.search(
-            r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
-            video_webpage)
-        if stretched_m:
-            w = float(stretched_m.group('w'))
-            h = float(stretched_m.group('h'))
-            # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
-            # We will only process correct ratios.
-            if w > 0 and h > 0:
-                ratio = w / h
-                for f in formats:
-                    if f.get('vcodec') != 'none':
-                        f['stretched_ratio'] = ratio
+                    ncd = next(search_dict(initial_data, 'nextContinuationData'))
+                    continuations = [ncd['continuation']]
+                # Handle videos where comments have been disabled entirely
+                except StopIteration:
+                    pass
+
+            def get_continuation(continuation, session_token, replies=False):
+                query = {
+                    'pbj': 1,
+                    'ctoken': continuation,
+                }
+                if replies:
+                    query['action_get_comment_replies'] = 1
+                else:
+                    query['action_get_comments'] = 1
+
+                while True:
+                    content, handle = self._download_webpage_handle(
+                        'https://www.youtube.com/comment_service_ajax',
+                        video_id,
+                        note=False,
+                        expected_status=[413],
+                        data=urlencode_postdata({
+                            'session_token': session_token
+                        }),
+                        query=query,
+                        headers={
+                            'Accept': '*/*',
+                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
+                            'X-YouTube-Client-Name': '1',
+                            'X-YouTube-Client-Version': '2.20201202.06.01'
+                        }
+                    )
 
-        if not formats:
-            if 'reason' in video_info:
-                if 'The uploader has not made this video available in your country.' in video_info['reason']:
-                    regions_allowed = self._html_search_meta(
-                        'regionsAllowed', video_webpage, default=None)
-                    countries = regions_allowed.split(',') if regions_allowed else None
-                    self.raise_geo_restricted(
-                        msg=video_info['reason'][0], countries=countries)
-                reason = video_info['reason'][0]
-                if 'Invalid parameters' in reason:
-                    unavailable_message = extract_unavailable_message()
-                    if unavailable_message:
-                        reason = unavailable_message
-                raise ExtractorError(
-                    'YouTube said: %s' % reason,
-                    expected=True, video_id=video_id)
-            if video_info.get('license_info') or try_get(player_response, lambda x: x['streamingData']['licenseInfos']):
-                raise ExtractorError('This video is DRM protected.', expected=True)
+                    response_code = handle.getcode()
+                    if (response_code == 200):
+                        return self._parse_json(content, video_id)
+                    if (response_code == 413):
+                        return None
+                    raise ExtractorError('Unexpected HTTP error code: %s' % response_code)
+
+            first_continuation = True
+            chain_msg = ''
+            self.to_screen('Downloading comments')
+            while continuations:
+                continuation = continuations.pop()
+                comment_response = get_continuation(continuation, xsrf_token)
+                if not comment_response:
+                    continue
+                if list(search_dict(comment_response, 'externalErrorMessage')):
+                    raise ExtractorError('Error returned from server: ' + next(search_dict(comment_response, 'externalErrorMessage')))
 
-        self._sort_formats(formats)
+                if 'continuationContents' not in comment_response['response']:
+                    # Something is wrong here. Youtube won't accept this continuation token for some reason and responds with a user satisfaction dialog (error?)
+                    continue
+                # not sure if this actually helps
+                if 'xsrf_token' in comment_response:
+                    xsrf_token = comment_response['xsrf_token']
+
+                item_section = comment_response['response']['continuationContents']['itemSectionContinuation']
+                if first_continuation:
+                    expected_video_comment_count = int(item_section['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'].replace(' Comments', '').replace('1 Comment', '1').replace(',', ''))
+                    first_continuation = False
+                if 'contents' not in item_section:
+                    # continuation returned no comments?
+                    # set an empty array as to not break the for loop
+                    item_section['contents'] = []
+
+                for meta_comment in item_section['contents']:
+                    comment = meta_comment['commentThreadRenderer']['comment']['commentRenderer']
+                    video_comments.append({
+                        'id': comment['commentId'],
+                        'text': ''.join([c['text'] for c in try_get(comment, lambda x: x['contentText']['runs'], list) or []]),
+                        'time_text': ''.join([c['text'] for c in comment['publishedTimeText']['runs']]),
+                        'author': comment.get('authorText', {}).get('simpleText', ''),
+                        'votes': comment.get('voteCount', {}).get('simpleText', '0'),
+                        'author_thumbnail': comment['authorThumbnail']['thumbnails'][-1]['url'],
+                        'parent': 'root'
+                    })
+                    if 'replies' not in meta_comment['commentThreadRenderer']:
+                        continue
 
-        self.mark_watched(video_id, video_info, player_response)
+                    reply_continuations = [rcn['nextContinuationData']['continuation'] for rcn in meta_comment['commentThreadRenderer']['replies']['commentRepliesRenderer']['continuations']]
+                    while reply_continuations:
+                        time.sleep(1)
+                        continuation = reply_continuations.pop()
+                        replies_data = get_continuation(continuation, xsrf_token, True)
+                        if not replies_data or 'continuationContents' not in replies_data[1]['response']:
+                            continue
 
-        return {
-            'id': video_id,
-            'uploader': video_uploader,
-            'uploader_id': video_uploader_id,
-            'uploader_url': video_uploader_url,
-            'channel_id': channel_id,
-            'channel_url': channel_url,
-            'upload_date': upload_date,
-            'license': video_license,
-            'creator': video_creator or artist,
-            'title': video_title,
-            'alt_title': video_alt_title or track,
-            'thumbnails': thumbnails,
-            'description': video_description,
-            'categories': video_categories,
-            'tags': video_tags,
-            'subtitles': video_subtitles,
-            'automatic_captions': automatic_captions,
-            'duration': video_duration,
-            'age_limit': 18 if age_gate else 0,
-            'annotations': video_annotations,
-            'chapters': chapters,
-            'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
-            'view_count': view_count,
-            'like_count': like_count,
-            'dislike_count': dislike_count,
-            'average_rating': average_rating,
-            'formats': formats,
-            'is_live': is_live,
-            'start_time': start_time,
-            'end_time': end_time,
-            'series': series,
-            'season_number': season_number,
-            'episode_number': episode_number,
-            'track': track,
-            'artist': artist,
-            'album': album,
-            'release_date': release_date,
-            'release_year': release_year,
-            'subscriber_count': subscriber_count,
-        }
+                        if self._downloader.params.get('verbose', False):
+                            chain_msg = ' (chain %s)' % comment['commentId']
+                        self.to_screen('Comments downloaded: %d of ~%d%s' % (len(video_comments), expected_video_comment_count, chain_msg))
+                        reply_comment_meta = replies_data[1]['response']['continuationContents']['commentRepliesContinuation']
+                        for reply_meta in reply_comment_meta.get('contents', {}):
+                            reply_comment = reply_meta['commentRenderer']
+                            video_comments.append({
+                                'id': reply_comment['commentId'],
+                                'text': ''.join([c['text'] for c in reply_comment['contentText']['runs']]),
+                                'time_text': ''.join([c['text'] for c in reply_comment['publishedTimeText']['runs']]),
+                                'author': reply_comment.get('authorText', {}).get('simpleText', ''),
+                                'votes': reply_comment.get('voteCount', {}).get('simpleText', '0'),
+                                'author_thumbnail': reply_comment['authorThumbnail']['thumbnails'][-1]['url'],
+                                'parent': comment['commentId']
+                            })
+                        if 'continuations' not in reply_comment_meta or len(reply_comment_meta['continuations']) == 0:
+                            continue
+                        reply_continuations += [rcn['nextContinuationData']['continuation'] for rcn in reply_comment_meta['continuations']]
 
+                self.to_screen('Comments downloaded: %d of ~%d' % (len(video_comments), expected_video_comment_count))
+                if 'continuations' in item_section:
+                    continuations += [ncd['nextContinuationData']['continuation'] for ncd in item_section['continuations']]
+                time.sleep(1)
 
-class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
-    IE_DESC = 'YouTube.com playlists'
-    _VALID_URL = r"""(?x)(?:
-                        (?:https?://)?
+            self.to_screen('Total comments downloaded: %d of ~%d' % (len(video_comments), expected_video_comment_count))
+            info.update({
+                'comments': video_comments,
+                'comment_count': expected_video_comment_count
+            })
+
+        self.mark_watched(video_id, player_response)
+
+        return info
+
+
+class YoutubeTabIE(YoutubeBaseInfoExtractor):
+    IE_DESC = 'YouTube.com tab'
+    _VALID_URL = r'''(?x)
+                    https?://
                         (?:\w+\.)?
                         (?:
-                            (?:
-                                youtube(?:kids)?\.com|
-                                invidio\.us
-                            )
-                            /
-                            (?:
-                               (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
-                               \? (?:.*?[&;])*? (?:p|a|list)=
-                            |  p/
+                            youtube(?:kids)?\.com|
+                            invidio\.us
+                        )/
+                        (?:
+                            (?:channel|c|user)/|
+                            (?P<not_channel>
+                                feed/|hashtag/|
+                                (?:playlist|watch)\?.*?\blist=
                             )|
-                            youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
-                        )
-                        (
-                            (?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)?[0-9A-Za-z-_]{10,}
-                            # Top tracks, they can also include dots
-                            |(?:MC)[\w\.]*
+                            (?!(?:%s)\b)  # Direct URLs
                         )
-                        .*
-                     |
-                        (%(playlist_id)s)
-                     )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
-    _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
-    _VIDEO_RE_TPL = r'href="\s*/watch\?v=%s(?:&amp;(?:[^"]*?index=(?P<index>\d+))?(?:[^>]+>(?P<title>[^<]+))?)?'
-    _VIDEO_RE = _VIDEO_RE_TPL % r'(?P<id>[0-9A-Za-z_-]{11})'
-    IE_NAME = 'youtube:playlist'
-    _YTM_PLAYLIST_PREFIX = 'RDCLAK5uy_'
-    _YTM_CHANNEL_INFO = {
-        'uploader': 'Youtube Music',
-        'uploader_id': 'music',  # or "UC-9-kyTW8ZkZNDHQJ6FgpwQ"
-        'uploader_url': 'https://www.youtube.com/music'
-    }
+                        (?P<id>[^/?\#&]+)
+                    ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
+    IE_NAME = 'youtube:tab'
+
     _TESTS = [{
+        # playlists, multipage
+        'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
+        'playlist_mincount': 94,
+        'info_dict': {
+            'id': 'UCqj7Cz7revf5maW9g5pgNcg',
+            'title': 'Игорь Клейнер - Playlists',
+            'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
+            'uploader': 'Игорь Клейнер',
+            'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
+        },
+    }, {
+        # playlists, multipage, different order
+        'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
+        'playlist_mincount': 94,
+        'info_dict': {
+            'id': 'UCqj7Cz7revf5maW9g5pgNcg',
+            'title': 'Игорь Клейнер - Playlists',
+            'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
+            'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
+            'uploader': 'Игорь Клейнер',
+        },
+    }, {
+        # playlists, singlepage
+        'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
+        'playlist_mincount': 4,
+        'info_dict': {
+            'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
+            'title': 'ThirstForScience - Playlists',
+            'description': 'md5:609399d937ea957b0f53cbffb747a14c',
+            'uploader': 'ThirstForScience',
+            'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
+        }
+    }, {
+        'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
+        'only_matching': True,
+    }, {
+        # basic, single video playlist
         'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
         'info_dict': {
             'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
@@ -2703,6 +2226,7 @@ class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
         },
         'playlist_count': 1,
     }, {
+        # empty playlist
         'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
         'info_dict': {
             'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
@@ -2712,71 +2236,105 @@ class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
         },
         'playlist_count': 0,
     }, {
-        'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
-        'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
+        # Home tab
+        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
         'info_dict': {
-            'title': '29C3: Not my department',
-            'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
-            'uploader': 'Christiaan008',
-            'uploader_id': 'ChRiStIaAn008',
+            'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+            'title': 'lex will - Home',
+            'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
+            'uploader': 'lex will',
+            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
         },
-        'playlist_count': 96,
+        'playlist_mincount': 2,
     }, {
-        'note': 'issue #673',
-        'url': 'PLBB231211A4F62143',
+        # Videos tab
+        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
         'info_dict': {
-            'title': '[OLD]Team Fortress 2 (Class-based LP)',
-            'id': 'PLBB231211A4F62143',
-            'uploader': 'Wickydoo',
-            'uploader_id': 'Wickydoo',
+            'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+            'title': 'lex will - Videos',
+            'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
+            'uploader': 'lex will',
+            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
         },
-        'playlist_mincount': 26,
+        'playlist_mincount': 975,
     }, {
-        'note': 'Large playlist',
-        'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
+        # Videos tab, sorted by popular
+        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
         'info_dict': {
-            'title': 'Uploads from Cauchemar',
-            'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
-            'uploader': 'Cauchemar',
-            'uploader_id': 'Cauchemar89',
+            'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+            'title': 'lex will - Videos',
+            'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
+            'uploader': 'lex will',
+            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
         },
-        'playlist_mincount': 799,
+        'playlist_mincount': 199,
     }, {
-        'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
+        # Playlists tab
+        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
         'info_dict': {
-            'title': 'YDL_safe_search',
-            'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
+            'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+            'title': 'lex will - Playlists',
+            'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
+            'uploader': 'lex will',
+            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
         },
-        'playlist_count': 2,
-        'skip': 'This playlist is private',
+        'playlist_mincount': 17,
     }, {
-        'note': 'embedded',
-        'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
-        'playlist_count': 4,
+        # Community tab
+        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
         'info_dict': {
-            'title': 'JODA15',
-            'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
-            'uploader': 'milan',
-            'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
-        }
+            'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+            'title': 'lex will - Community',
+            'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
+            'uploader': 'lex will',
+            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+        },
+        'playlist_mincount': 18,
     }, {
-        'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
-        'playlist_mincount': 485,
+        # Channels tab
+        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
         'info_dict': {
-            'title': '2018 Chinese New Singles (11/6 updated)',
-            'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
-            'uploader': 'LBK',
-            'uploader_id': 'sdragonfang',
-        }
+            'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+            'title': 'lex will - Channels',
+            'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
+            'uploader': 'lex will',
+            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
+        },
+        'playlist_mincount': 12,
     }, {
-        'note': 'Embedded SWF player',
-        'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
-        'playlist_count': 4,
+        'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
+        'only_matching': True,
+    }, {
+        'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
+        'only_matching': True,
+    }, {
+        'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
+        'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
         'info_dict': {
-            'title': 'JODA7',
-            'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
+            'title': '29C3: Not my department',
+            'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
+            'uploader': 'Christiaan008',
+            'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
+            'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
         },
-        'skip': 'This playlist does not exist',
+        'playlist_count': 96,
+    }, {
+        'note': 'Large playlist',
+        'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
+        'info_dict': {
+            'title': 'Uploads from Cauchemar',
+            'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
+            'uploader': 'Cauchemar',
+            'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
+        },
+        'playlist_mincount': 1123,
+    }, {
+        # even larger playlist, 8832 videos
+        'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
+        'only_matching': True,
     }, {
         'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
         'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
@@ -2784,9 +2342,23 @@ class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
             'title': 'Uploads from Interstellar Movie',
             'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
             'uploader': 'Interstellar Movie',
-            'uploader_id': 'InterstellarMovie1',
+            'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
         },
         'playlist_mincount': 21,
+    }, {
+        # https://github.com/ytdl-org/youtube-dl/issues/21844
+        'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
+        'info_dict': {
+            'title': 'Data Analysis with Dr Mike Pound',
+            'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
+            'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
+            'uploader': 'Computerphile',
+            'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
+        },
+        'playlist_mincount': 11,
+    }, {
+        'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
+        'only_matching': True,
     }, {
         # Playlist URL that does not actually serve a playlist
         'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
@@ -2812,492 +2384,802 @@ class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
         'skip': 'This video is not available.',
         'add_ie': [YoutubeIE.ie_key()],
     }, {
-        'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
+        'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
         'info_dict': {
-            'id': 'yeWKywCrFtk',
+            'id': '9Auq9mYxFEE',
             'ext': 'mp4',
-            'title': 'Small Scale Baler and Braiding Rugs',
-            'uploader': 'Backus-Page House Museum',
-            'uploader_id': 'backuspagemuseum',
-            'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
-            'upload_date': '20161008',
-            'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
-            'categories': ['Nonprofits & Activism'],
+            'title': compat_str,
+            'uploader': 'Sky News',
+            'uploader_id': 'skynews',
+            'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
+            'upload_date': '20191102',
+            'description': 'md5:85ddd75d888674631aaf9599a9a0b0ae',
+            'categories': ['News & Politics'],
             'tags': list,
             'like_count': int,
             'dislike_count': int,
         },
         'params': {
-            'noplaylist': True,
             'skip_download': True,
         },
     }, {
-        # https://github.com/ytdl-org/youtube-dl/issues/21844
-        'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
+        'url': 'https://www.youtube.com/user/TheYoungTurks/live',
         'info_dict': {
-            'title': 'Data Analysis with Dr Mike Pound',
-            'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
-            'uploader_id': 'Computerphile',
-            'uploader': 'Computerphile',
+            'id': 'a48o2S1cPoo',
+            'ext': 'mp4',
+            'title': 'The Young Turks - Live Main Show',
+            'uploader': 'The Young Turks',
+            'uploader_id': 'TheYoungTurks',
+            'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
+            'upload_date': '20150715',
+            'license': 'Standard YouTube License',
+            'description': 'md5:438179573adcdff3c97ebb1ee632b891',
+            'categories': ['News & Politics'],
+            'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
+            'like_count': int,
+            'dislike_count': int,
         },
-        'playlist_mincount': 11,
+        'params': {
+            'skip_download': True,
+        },
+        'only_matching': True,
     }, {
-        'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
+        'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
         'only_matching': True,
     }, {
-        'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
+        'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
         'only_matching': True,
     }, {
-        # music album playlist
-        'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
+        'url': 'https://www.youtube.com/feed/trending',
         'only_matching': True,
     }, {
-        'url': 'https://invidio.us/playlist?list=PLDIoUOhQQPlXr63I_vwF9GD8sAKh77dWU',
+        # needs auth
+        'url': 'https://www.youtube.com/feed/library',
         'only_matching': True,
     }, {
-        'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
+        # needs auth
+        'url': 'https://www.youtube.com/feed/history',
+        'only_matching': True,
+    }, {
+        # needs auth
+        'url': 'https://www.youtube.com/feed/subscriptions',
+        'only_matching': True,
+    }, {
+        # needs auth
+        'url': 'https://www.youtube.com/feed/watch_later',
+        'only_matching': True,
+    }, {
+        # no longer available?
+        'url': 'https://www.youtube.com/feed/recommended',
+        'only_matching': True,
+    }, {
+        # inline playlist with not always working continuations
+        'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtube.com/course',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtube.com/zsecurity',
+        'only_matching': True,
+    }, {
+        'url': 'http://www.youtube.com/NASAgovVideo/videos',
+        'only_matching': True,
+    }, {
+        'url': 'https://www.youtube.com/TheYoungTurks/live',
         'only_matching': True,
     }]
 
-    def _real_initialize(self):
-        self._login()
+    @classmethod
+    def suitable(cls, url):
+        return False if YoutubeIE.suitable(url) else super(
+            YoutubeTabIE, cls).suitable(url)
+
+    def _extract_channel_id(self, webpage):
+        channel_id = self._html_search_meta(
+            'channelId', webpage, 'channel id', default=None)
+        if channel_id:
+            return channel_id
+        channel_url = self._html_search_meta(
+            ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
+             'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
+             'twitter:app:url:googleplay'), webpage, 'channel url')
+        return self._search_regex(
+            r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
+            channel_url, 'channel id')
 
-    def extract_videos_from_page(self, page):
-        ids_in_page = []
-        titles_in_page = []
-
-        for item in re.findall(
-                r'(<[^>]*\bdata-video-id\s*=\s*["\'][0-9A-Za-z_-]{11}[^>]+>)', page):
-            attrs = extract_attributes(item)
-            video_id = attrs['data-video-id']
-            video_title = unescapeHTML(attrs.get('data-title'))
-            if video_title:
-                video_title = video_title.strip()
-            ids_in_page.append(video_id)
-            titles_in_page.append(video_title)
-
-        # Fallback with old _VIDEO_RE
-        self.extract_videos_from_page_impl(
-            self._VIDEO_RE, page, ids_in_page, titles_in_page)
-
-        # Relaxed fallbacks
-        self.extract_videos_from_page_impl(
-            r'href="\s*/watch\?v\s*=\s*(?P<id>[0-9A-Za-z_-]{11})', page,
-            ids_in_page, titles_in_page)
-        self.extract_videos_from_page_impl(
-            r'data-video-ids\s*=\s*["\'](?P<id>[0-9A-Za-z_-]{11})', page,
-            ids_in_page, titles_in_page)
-
-        return zip(ids_in_page, titles_in_page)
-
-    def _extract_mix_ids_from_yt_initial(self, yt_initial):
-        ids = []
-        playlist_contents = try_get(yt_initial, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist']['contents'], list)
-        if playlist_contents:
-            for item in playlist_contents:
-                videoId = try_get(item, lambda x: x['playlistPanelVideoRenderer']['videoId'], compat_str)
-                if videoId:
-                    ids.append(videoId)
-        return ids
-
-    def _extract_mix(self, playlist_id):
-        # The mixes are generated from a single video
-        # the id of the playlist is just 'RD' + video_id
-        ids = []
-        yt_initial = None
-        last_id = playlist_id[-11:]
-        for n in itertools.count(1):
-            url = 'https://www.youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
-            webpage = self._download_webpage(
-                url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
-            new_ids = orderedSet(re.findall(
-                r'''(?xs)data-video-username=".*?".*?
-                           href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
-                webpage))
-
-            # if no ids in html of page, try using embedded json
-            if (len(new_ids) == 0):
-                yt_initial = self._get_yt_initial_data(playlist_id, webpage)
-                if yt_initial:
-                    new_ids = self._extract_mix_ids_from_yt_initial(yt_initial)
-
-            # Fetch new pages until all the videos are repeated, it seems that
-            # there are always 51 unique videos.
-            new_ids = [_id for _id in new_ids if _id not in ids]
-            if not new_ids:
-                break
-            ids.extend(new_ids)
-            last_id = ids[-1]
+    @staticmethod
+    def _extract_grid_item_renderer(item):
+        for item_kind in ('Playlist', 'Video', 'Channel'):
+            renderer = item.get('grid%sRenderer' % item_kind)
+            if renderer:
+                return renderer
+
+    def _grid_entries(self, grid_renderer):
+        for item in grid_renderer['items']:
+            if not isinstance(item, dict):
+                continue
+            renderer = self._extract_grid_item_renderer(item)
+            if not isinstance(renderer, dict):
+                continue
+            title = try_get(
+                renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
+            # playlist
+            playlist_id = renderer.get('playlistId')
+            if playlist_id:
+                yield self.url_result(
+                    'https://www.youtube.com/playlist?list=%s' % playlist_id,
+                    ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
+                    video_title=title)
+            # video
+            video_id = renderer.get('videoId')
+            if video_id:
+                yield self._extract_video(renderer)
+            # channel
+            channel_id = renderer.get('channelId')
+            if channel_id:
+                title = try_get(
+                    renderer, lambda x: x['title']['simpleText'], compat_str)
+                yield self.url_result(
+                    'https://www.youtube.com/channel/%s' % channel_id,
+                    ie=YoutubeTabIE.ie_key(), video_title=title)
+
+    def _shelf_entries_from_content(self, shelf_renderer):
+        content = shelf_renderer.get('content')
+        if not isinstance(content, dict):
+            return
+        renderer = content.get('gridRenderer')
+        if renderer:
+            # TODO: add support for nested playlists so each shelf is processed
+            # as separate playlist
+            # TODO: this includes only first N items
+            for entry in self._grid_entries(renderer):
+                yield entry
+        renderer = content.get('horizontalListRenderer')
+        if renderer:
+            # TODO
+            pass
+
+    def _shelf_entries(self, shelf_renderer, skip_channels=False):
+        ep = try_get(
+            shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
+            compat_str)
+        shelf_url = urljoin('https://www.youtube.com', ep)
+        if shelf_url:
+            # Skipping links to another channels, note that checking for
+            # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
+            # will not work
+            if skip_channels and '/channels?' in shelf_url:
+                return
+            title = try_get(
+                shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
+            yield self.url_result(shelf_url, video_title=title)
+        # Shelf may not contain shelf URL, fallback to extraction from content
+        for entry in self._shelf_entries_from_content(shelf_renderer):
+            yield entry
+
+    def _playlist_entries(self, video_list_renderer):
+        for content in video_list_renderer['contents']:
+            if not isinstance(content, dict):
+                continue
+            renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
+            if not isinstance(renderer, dict):
+                continue
+            video_id = renderer.get('videoId')
+            if not video_id:
+                continue
+            yield self._extract_video(renderer)
+
+    r""" # Not needed in the new implementation
+    def _itemSection_entries(self, item_sect_renderer):
+        for content in item_sect_renderer['contents']:
+            if not isinstance(content, dict):
+                continue
+            renderer = content.get('videoRenderer', {})
+            if not isinstance(renderer, dict):
+                continue
+            video_id = renderer.get('videoId')
+            if not video_id:
+                continue
+            yield self._extract_video(renderer)
+    """
+
+    def _rich_entries(self, rich_grid_renderer):
+        renderer = try_get(
+            rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
+        video_id = renderer.get('videoId')
+        if not video_id:
+            return
+        yield self._extract_video(renderer)
+
+    def _video_entry(self, video_renderer):
+        video_id = video_renderer.get('videoId')
+        if video_id:
+            return self._extract_video(video_renderer)
+
+    def _post_thread_entries(self, post_thread_renderer):
+        post_renderer = try_get(
+            post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
+        if not post_renderer:
+            return
+        # video attachment
+        video_renderer = try_get(
+            post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
+        video_id = None
+        if video_renderer:
+            entry = self._video_entry(video_renderer)
+            if entry:
+                yield entry
+        # inline video links
+        runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
+        for run in runs:
+            if not isinstance(run, dict):
+                continue
+            ep_url = try_get(
+                run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
+            if not ep_url:
+                continue
+            if not YoutubeIE.suitable(ep_url):
+                continue
+            ep_video_id = YoutubeIE._match_id(ep_url)
+            if video_id == ep_video_id:
+                continue
+            yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
+
+    def _post_thread_continuation_entries(self, post_thread_continuation):
+        contents = post_thread_continuation.get('contents')
+        if not isinstance(contents, list):
+            return
+        for content in contents:
+            renderer = content.get('backstagePostThreadRenderer')
+            if not isinstance(renderer, dict):
+                continue
+            for entry in self._post_thread_entries(renderer):
+                yield entry
+
+    @staticmethod
+    def _build_continuation_query(continuation, ctp=None):
+        query = {
+            'ctoken': continuation,
+            'continuation': continuation,
+        }
+        if ctp:
+            query['itct'] = ctp
+        return query
+
+    @staticmethod
+    def _extract_next_continuation_data(renderer):
+        next_continuation = try_get(
+            renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
+        if not next_continuation:
+            return
+        continuation = next_continuation.get('continuation')
+        if not continuation:
+            return
+        ctp = next_continuation.get('clickTrackingParams')
+        return YoutubeTabIE._build_continuation_query(continuation, ctp)
+
+    @classmethod
+    def _extract_continuation(cls, renderer):
+        next_continuation = cls._extract_next_continuation_data(renderer)
+        if next_continuation:
+            return next_continuation
+        contents = []
+        for key in ('contents', 'items'):
+            contents.extend(try_get(renderer, lambda x: x[key], list) or [])
+        for content in contents:
+            if not isinstance(content, dict):
+                continue
+            continuation_ep = try_get(
+                content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
+                dict)
+            if not continuation_ep:
+                continue
+            continuation = try_get(
+                continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
+            if not continuation:
+                continue
+            ctp = continuation_ep.get('clickTrackingParams')
+            return YoutubeTabIE._build_continuation_query(continuation, ctp)
+
+    def _entries(self, tab, identity_token):
+
+        def extract_entries(parent_renderer):  # this needs to called again for continuation to work with feeds
+            contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
+            for content in contents:
+                if not isinstance(content, dict):
+                    continue
+                is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
+                if not is_renderer:
+                    renderer = content.get('richItemRenderer')
+                    if renderer:
+                        for entry in self._rich_entries(renderer):
+                            yield entry
+                        continuation_list[0] = self._extract_continuation(parent_renderer)
+                    continue
+                isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
+                for isr_content in isr_contents:
+                    if not isinstance(isr_content, dict):
+                        continue
+
+                    known_renderers = {
+                        'playlistVideoListRenderer': self._playlist_entries,
+                        'gridRenderer': self._grid_entries,
+                        'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
+                        'backstagePostThreadRenderer': self._post_thread_entries,
+                        'videoRenderer': lambda x: [self._video_entry(x)],
+                    }
+                    for key, renderer in isr_content.items():
+                        if key not in known_renderers:
+                            continue
+                        for entry in known_renderers[key](renderer):
+                            if entry:
+                                yield entry
+                        continuation_list[0] = self._extract_continuation(renderer)
+                        break
 
-        url_results = self._ids_to_results(ids)
+                if not continuation_list[0]:
+                    continuation_list[0] = self._extract_continuation(is_renderer)
 
-        search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
-        title_span = (
-            search_title('playlist-title')
-            or search_title('title long-title')
-            or search_title('title'))
-        title = clean_html(title_span)
+            if not continuation_list[0]:
+                continuation_list[0] = self._extract_continuation(parent_renderer)
 
-        if not title:
-            title = try_get(yt_initial, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist']['title'], compat_str)
+        continuation_list = [None]  # Python 2 doesnot support nonlocal
+        tab_content = try_get(tab, lambda x: x['content'], dict)
+        if not tab_content:
+            return
+        parent_renderer = (
+            try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
+            or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
+        for entry in extract_entries(parent_renderer):
+            yield entry
+        continuation = continuation_list[0]
+
+        headers = {
+            'x-youtube-client-name': '1',
+            'x-youtube-client-version': '2.20201112.04.01',
+        }
+        if identity_token:
+            headers['x-youtube-identity-token'] = identity_token
 
-        return self.playlist_result(url_results, playlist_id, title)
+        for page_num in itertools.count(1):
+            if not continuation:
+                break
+            count = 0
+            retries = 3
+            while count <= retries:
+                try:
+                    # Downloading page may result in intermittent 5xx HTTP error
+                    # that is usually worked around with a retry
+                    browse = self._download_json(
+                        'https://www.youtube.com/browse_ajax', None,
+                        'Downloading page %d%s'
+                        % (page_num, ' (retry #%d)' % count if count else ''),
+                        headers=headers, query=continuation)
+                    break
+                except ExtractorError as e:
+                    if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
+                        count += 1
+                        if count <= retries:
+                            continue
+                    raise
+            if not browse:
+                break
+            response = try_get(browse, lambda x: x[1]['response'], dict)
+            if not response:
+                break
 
-    def _extract_playlist(self, playlist_id):
-        url = self._TEMPLATE_URL % playlist_id
-        page = self._download_webpage(url, playlist_id)
+            known_continuation_renderers = {
+                'playlistVideoListContinuation': self._playlist_entries,
+                'gridContinuation': self._grid_entries,
+                'itemSectionContinuation': self._post_thread_continuation_entries,
+                'sectionListContinuation': extract_entries,  # for feeds
+            }
+            continuation_contents = try_get(
+                response, lambda x: x['continuationContents'], dict) or {}
+            continuation_renderer = None
+            for key, value in continuation_contents.items():
+                if key not in known_continuation_renderers:
+                    continue
+                continuation_renderer = value
+                continuation_list = [None]
+                for entry in known_continuation_renderers[key](continuation_renderer):
+                    yield entry
+                continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
+                break
+            if continuation_renderer:
+                continue
 
-        # the yt-alert-message now has tabindex attribute (see https://github.com/ytdl-org/youtube-dl/issues/11604)
-        for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
-            match = match.strip()
-            # Check if the playlist exists or is private
-            mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
-            if mobj:
-                reason = mobj.group('reason')
-                message = 'This playlist %s' % reason
-                if 'private' in reason:
-                    message += ', use --username or --netrc to access it'
-                message += '.'
-                raise ExtractorError(message, expected=True)
-            elif re.match(r'[^<]*Invalid parameters[^<]*', match):
-                raise ExtractorError(
-                    'Invalid parameters. Maybe URL is incorrect.',
-                    expected=True)
-            elif re.match(r'[^<]*Choose your language[^<]*', match):
+            known_renderers = {
+                'gridPlaylistRenderer': (self._grid_entries, 'items'),
+                'gridVideoRenderer': (self._grid_entries, 'items'),
+                'playlistVideoRenderer': (self._playlist_entries, 'contents'),
+                'itemSectionRenderer': (self._playlist_entries, 'contents'),
+                'richItemRenderer': (extract_entries, 'contents'),  # for hashtag
+            }
+            continuation_items = try_get(
+                response, lambda x: x['onResponseReceivedActions'][0]['appendContinuationItemsAction']['continuationItems'], list)
+            continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
+            video_items_renderer = None
+            for key, value in continuation_item.items():
+                if key not in known_renderers:
+                    continue
+                video_items_renderer = {known_renderers[key][1]: continuation_items}
+                continuation_list = [None]
+                for entry in known_renderers[key][0](video_items_renderer):
+                    yield entry
+                continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
+                break
+            if video_items_renderer:
                 continue
-            else:
-                self.report_warning('Youtube gives an alert message: ' + match)
-
-        playlist_title = self._html_search_regex(
-            r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
-            page, 'title', default=None)
-
-        _UPLOADER_BASE = r'class=["\']pl-header-details[^>]+>\s*<li>\s*<a[^>]+\bhref='
-        uploader = self._html_search_regex(
-            r'%s["\']/(?:user|channel)/[^>]+>([^<]+)' % _UPLOADER_BASE,
-            page, 'uploader', default=None)
-        mobj = re.search(
-            r'%s(["\'])(?P<path>/(?:user|channel)/(?P<uploader_id>.+?))\1' % _UPLOADER_BASE,
-            page)
-        if mobj:
-            uploader_id = mobj.group('uploader_id')
-            uploader_url = compat_urlparse.urljoin(url, mobj.group('path'))
+            break
+
+    @staticmethod
+    def _extract_selected_tab(tabs):
+        for tab in tabs:
+            if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
+                return tab['tabRenderer']
         else:
-            uploader_id = uploader_url = None
+            raise ExtractorError('Unable to find selected tab')
+
+    @staticmethod
+    def _extract_uploader(data):
+        uploader = {}
+        sidebar_renderer = try_get(
+            data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
+        if sidebar_renderer:
+            for item in sidebar_renderer:
+                if not isinstance(item, dict):
+                    continue
+                renderer = item.get('playlistSidebarSecondaryInfoRenderer')
+                if not isinstance(renderer, dict):
+                    continue
+                owner = try_get(
+                    renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
+                if owner:
+                    uploader['uploader'] = owner.get('text')
+                    uploader['uploader_id'] = try_get(
+                        owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
+                    uploader['uploader_url'] = urljoin(
+                        'https://www.youtube.com/',
+                        try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
+        return {k: v for k, v in uploader.items() if v is not None}
+
+    def _extract_from_tabs(self, item_id, webpage, data, tabs, identity_token):
+        playlist_id = title = description = channel_url = channel_name = channel_id = None
+        thumbnails_list = tags = []
+
+        selected_tab = self._extract_selected_tab(tabs)
+        renderer = try_get(
+            data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
+        if renderer:
+            channel_name = renderer.get('title')
+            channel_url = renderer.get('channelUrl')
+            channel_id = renderer.get('externalId')
+
+        if not renderer:
+            renderer = try_get(
+                data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
+        if renderer:
+            title = renderer.get('title')
+            description = renderer.get('description', '')
+            playlist_id = channel_id
+            tags = renderer.get('keywords', '').split()
+            thumbnails_list = (
+                try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
+                or try_get(
+                    data,
+                    lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
+                    list)
+                or [])
 
-        has_videos = True
+        thumbnails = []
+        for t in thumbnails_list:
+            if not isinstance(t, dict):
+                continue
+            thumbnail_url = url_or_none(t.get('url'))
+            if not thumbnail_url:
+                continue
+            thumbnails.append({
+                'url': thumbnail_url,
+                'width': int_or_none(t.get('width')),
+                'height': int_or_none(t.get('height')),
+            })
 
-        if not playlist_title:
-            try:
-                # Some playlist URLs don't actually serve a playlist (e.g.
-                # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
-                next(self._entries(page, playlist_id))
-            except StopIteration:
-                has_videos = False
-
-        playlist = self.playlist_result(
-            self._entries(page, playlist_id), playlist_id, playlist_title)
-        playlist.update({
-            'uploader': uploader,
-            'uploader_id': uploader_id,
-            'uploader_url': uploader_url,
-        })
-        if playlist_id.startswith(self._YTM_PLAYLIST_PREFIX):
-            playlist.update(self._YTM_CHANNEL_INFO)
+        if playlist_id is None:
+            playlist_id = item_id
+        if title is None:
+            title = playlist_id
+        title += format_field(selected_tab, 'title', ' - %s')
+
+        metadata = {
+            'playlist_id': playlist_id,
+            'playlist_title': title,
+            'playlist_description': description,
+            'uploader': channel_name,
+            'uploader_id': channel_id,
+            'uploader_url': channel_url,
+            'thumbnails': thumbnails,
+            'tags': tags,
+        }
+        if not channel_id:
+            metadata.update(self._extract_uploader(data))
+        metadata.update({
+            'channel': metadata['uploader'],
+            'channel_id': metadata['uploader_id'],
+            'channel_url': metadata['uploader_url']})
+        return self.playlist_result(
+            self._entries(selected_tab, identity_token),
+            **metadata)
+
+    def _extract_from_playlist(self, item_id, url, data, playlist):
+        title = playlist.get('title') or try_get(
+            data, lambda x: x['titleText']['simpleText'], compat_str)
+        playlist_id = playlist.get('playlistId') or item_id
+        # Inline playlist rendition continuation does not always work
+        # at Youtube side, so delegating regular tab-based playlist URL
+        # processing whenever possible.
+        playlist_url = urljoin(url, try_get(
+            playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
+            compat_str))
+        if playlist_url and playlist_url != url:
+            return self.url_result(
+                playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
+                video_title=title)
+        return self.playlist_result(
+            self._playlist_entries(playlist), playlist_id=playlist_id,
+            playlist_title=title)
 
-        return has_videos, playlist
+    @staticmethod
+    def _extract_alerts(data):
+        for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
+            if not isinstance(alert_dict, dict):
+                continue
+            for renderer in alert_dict:
+                alert = alert_dict[renderer]
+                alert_type = alert.get('type')
+                if not alert_type:
+                    continue
+                message = try_get(alert, lambda x: x['text']['simpleText'], compat_str)
+                if message:
+                    yield alert_type, message
+                for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
+                    message = try_get(run, lambda x: x['text'], compat_str)
+                    if message:
+                        yield alert_type, message
+
+    def _extract_identity_token(self, webpage, item_id):
+        ytcfg = self._extract_ytcfg(item_id, webpage)
+        if ytcfg:
+            token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
+            if token:
+                return token
+        return self._search_regex(
+            r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
+            'identity token', default=None)
 
-    def _check_download_just_video(self, url, playlist_id):
-        # Check if it's a video-specific URL
-        query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
-        video_id = query_dict.get('v', [None])[0] or self._search_regex(
-            r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
-            'video id', default=None)
-        if video_id:
+    def _real_extract(self, url):
+        item_id = self._match_id(url)
+        url = compat_urlparse.urlunparse(
+            compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
+        is_home = re.match(r'(?P<pre>%s)(?P<post>/?(?![^#?]).*$)' % self._VALID_URL, url)
+        if is_home is not None and is_home.group('not_channel') is None and item_id != 'feed':
+            self._downloader.report_warning(
+                'A channel/user page was given. All the channel\'s videos will be downloaded. '
+                'To download only the videos in the home page, add a "/featured" to the URL')
+            url = '%s/videos%s' % (is_home.group('pre'), is_home.group('post') or '')
+
+        # Handle both video/playlist URLs
+        qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
+        video_id = qs.get('v', [None])[0]
+        playlist_id = qs.get('list', [None])[0]
+
+        if is_home is not None and is_home.group('not_channel') is not None and is_home.group('not_channel').startswith('watch') and not video_id:
+            if playlist_id:
+                self._downloader.report_warning('%s is not a valid Youtube URL. Trying to download playlist %s' % (url, playlist_id))
+                url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
+                # return self.url_result(playlist_id, ie=YoutubePlaylistIE.ie_key())
+            else:
+                raise ExtractorError('Unable to recognize tab page')
+        if video_id and playlist_id:
             if self._downloader.params.get('noplaylist'):
                 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
-                return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
+                return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
+            self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
+
+        webpage = self._download_webpage(url, item_id)
+        identity_token = self._extract_identity_token(webpage, item_id)
+        data = self._extract_yt_initial_data(item_id, webpage)
+        err_msg = None
+        for alert_type, alert_message in self._extract_alerts(data):
+            if alert_type.lower() == 'error':
+                if err_msg:
+                    self._downloader.report_warning('YouTube said: %s - %s' % ('ERROR', err_msg))
+                err_msg = alert_message
             else:
-                self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
-                return video_id, None
-        return None, None
+                self._downloader.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
+        if err_msg:
+            raise ExtractorError('YouTube said: %s' % err_msg, expected=True)
+        tabs = try_get(
+            data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
+        if tabs:
+            return self._extract_from_tabs(item_id, webpage, data, tabs, identity_token)
+        playlist = try_get(
+            data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
+        if playlist:
+            return self._extract_from_playlist(item_id, url, data, playlist)
+        # Fallback to video extraction if no playlist alike page is recognized.
+        # First check for the current video then try the v attribute of URL query.
+        video_id = try_get(
+            data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
+            compat_str) or video_id
+        if video_id:
+            return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
+        # Failed to recognize
+        raise ExtractorError('Unable to recognize tab page')
 
-    def _real_extract(self, url):
-        # Extract playlist id
-        mobj = re.match(self._VALID_URL, url)
-        if mobj is None:
-            raise ExtractorError('Invalid URL: %s' % url)
-        playlist_id = mobj.group(1) or mobj.group(2)
-
-        video_id, video = self._check_download_just_video(url, playlist_id)
-        if video:
-            return video
-
-        if playlist_id.startswith(('RD', 'UL', 'PU')):
-            if not playlist_id.startswith(self._YTM_PLAYLIST_PREFIX):
-                # Mixes require a custom extraction process,
-                # Youtube Music playlists act like normal playlists (with randomized order)
-                return self._extract_mix(playlist_id)
-
-        has_videos, playlist = self._extract_playlist(playlist_id)
-        if has_videos or not video_id:
-            return playlist
-
-        # Some playlist URLs don't actually serve a playlist (see
-        # https://github.com/ytdl-org/youtube-dl/issues/10537).
-        # Fallback to plain video extraction if there is a video id
-        # along with playlist id.
-        return self.url_result(video_id, 'Youtube', video_id=video_id)
-
-
-class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
-    IE_DESC = 'YouTube.com channels'
-    _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie|kids)?\.com|(?:www\.)?invidio\.us)/channel/(?P<id>[0-9A-Za-z_-]+)'
-    _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
-    _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
-    IE_NAME = 'youtube:channel'
+
+class YoutubePlaylistIE(InfoExtractor):
+    IE_DESC = 'YouTube.com playlists'
+    _VALID_URL = r'''(?x)(?:
+                        (?:https?://)?
+                        (?:\w+\.)?
+                        (?:
+                            (?:
+                                youtube(?:kids)?\.com|
+                                invidio\.us
+                            )
+                            /.*?\?.*?\blist=
+                        )?
+                        (?P<id>%(playlist_id)s)
+                     )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
+    IE_NAME = 'youtube:playlist'
     _TESTS = [{
-        'note': 'paginated channel',
-        'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
-        'playlist_mincount': 91,
+        'note': 'issue #673',
+        'url': 'PLBB231211A4F62143',
         'info_dict': {
-            'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
-            'title': 'Uploads from lex will',
-            'uploader': 'lex will',
-            'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
-        }
+            'title': '[OLD]Team Fortress 2 (Class-based LP)',
+            'id': 'PLBB231211A4F62143',
+            'uploader': 'Wickydoo',
+            'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
+        },
+        'playlist_mincount': 29,
     }, {
-        'note': 'Age restricted channel',
-        # from https://www.youtube.com/user/DeusExOfficial
-        'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
-        'playlist_mincount': 64,
+        'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
         'info_dict': {
-            'id': 'UUs0ifCMCm1icqRbqhUINa0w',
-            'title': 'Uploads from Deus Ex',
-            'uploader': 'Deus Ex',
-            'uploader_id': 'DeusExOfficial',
+            'title': 'YDL_safe_search',
+            'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
         },
+        'playlist_count': 2,
+        'skip': 'This playlist is private',
     }, {
-        'url': 'https://invidio.us/channel/UC23qupoDRn9YOAVzeoxjOQA',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtubekids.com/channel/UCyu8StPfZWapR6rfW_JgqcA',
-        'only_matching': True,
-    }]
-
-    @classmethod
-    def suitable(cls, url):
-        return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
-                else super(YoutubeChannelIE, cls).suitable(url))
-
-    def _build_template_url(self, url, channel_id):
-        return self._TEMPLATE_URL % channel_id
-
-    def _real_extract(self, url):
-        channel_id = self._match_id(url)
-
-        url = self._build_template_url(url, channel_id)
-
-        # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
-        # Workaround by extracting as a playlist if managed to obtain channel playlist URL
-        # otherwise fallback on channel by page extraction
-        channel_page = self._download_webpage(
-            url + '?view=57', channel_id,
-            'Downloading channel page', fatal=False)
-        if channel_page is False:
-            channel_playlist_id = False
-        else:
-            channel_playlist_id = self._html_search_meta(
-                'channelId', channel_page, 'channel id', default=None)
-            if not channel_playlist_id:
-                channel_url = self._html_search_meta(
-                    ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
-                    channel_page, 'channel url', default=None)
-                if channel_url:
-                    channel_playlist_id = self._search_regex(
-                        r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
-                        channel_url, 'channel id', default=None)
-        if channel_playlist_id and channel_playlist_id.startswith('UC'):
-            playlist_id = 'UU' + channel_playlist_id[2:]
-            return self.url_result(
-                compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
-
-        channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
-        autogenerated = re.search(r'''(?x)
-                class="[^"]*?(?:
-                    channel-header-autogenerated-label|
-                    yt-channel-title-autogenerated
-                )[^"]*"''', channel_page) is not None
-
-        if autogenerated:
-            # The videos are contained in a single page
-            # the ajax pages can't be used, they are empty
-            entries = [
-                self.url_result(
-                    video_id, 'Youtube', video_id=video_id,
-                    video_title=video_title)
-                for video_id, video_title in self.extract_videos_from_page(channel_page)]
-            return self.playlist_result(entries, channel_id)
-
-        try:
-            next(self._entries(channel_page, channel_id))
-        except StopIteration:
-            alert_message = self._html_search_regex(
-                r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
-                channel_page, 'alert', default=None, group='alert')
-            if alert_message:
-                raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
-
-        return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
-
-
-class YoutubeUserIE(YoutubeChannelIE):
-    IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
-    _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:(?P<user>user|c)/)?(?!(?:attribution_link|watch|results|shared)(?:$|[^a-z_A-Z0-9%-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_%-]+)'
-    _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
-    IE_NAME = 'youtube:user'
-
-    _TESTS = [{
-        'url': 'https://www.youtube.com/user/TheLinuxFoundation',
-        'playlist_mincount': 320,
+        'note': 'embedded',
+        'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
+        'playlist_count': 4,
         'info_dict': {
-            'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
-            'title': 'Uploads from The Linux Foundation',
-            'uploader': 'The Linux Foundation',
-            'uploader_id': 'TheLinuxFoundation',
+            'title': 'JODA15',
+            'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
+            'uploader': 'milan',
+            'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
         }
     }, {
-        # Only available via https://www.youtube.com/c/12minuteathlete/videos
-        # but not https://www.youtube.com/user/12minuteathlete/videos
-        'url': 'https://www.youtube.com/c/12minuteathlete/videos',
-        'playlist_mincount': 249,
+        'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
+        'playlist_mincount': 982,
         'info_dict': {
-            'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
-            'title': 'Uploads from 12 Minute Athlete',
-            'uploader': '12 Minute Athlete',
-            'uploader_id': 'the12minuteathlete',
+            'title': '2018 Chinese New Singles (11/6 updated)',
+            'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
+            'uploader': 'LBK',
+            'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
         }
     }, {
-        'url': 'ytuser:phihag',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtube.com/c/gametrailers',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtube.com/c/Pawe%C5%82Zadro%C5%BCniak',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtube.com/gametrailers',
+        'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
         'only_matching': True,
     }, {
-        # This channel is not available, geo restricted to JP
-        'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
+        # music album playlist
+        'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
         'only_matching': True,
     }]
 
     @classmethod
     def suitable(cls, url):
-        # Don't return True if the url can be extracted with other youtube
-        # extractor, the regex would is too permissive and it would match.
-        other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
-        if any(ie.suitable(url) for ie in other_yt_ies):
-            return False
-        else:
-            return super(YoutubeUserIE, cls).suitable(url)
-
-    def _build_template_url(self, url, channel_id):
-        mobj = re.match(self._VALID_URL, url)
-        return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
+        return False if YoutubeTabIE.suitable(url) else super(
+            YoutubePlaylistIE, cls).suitable(url)
 
+    def _real_extract(self, url):
+        playlist_id = self._match_id(url)
+        qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
+        if not qs:
+            qs = {'list': playlist_id}
+        return self.url_result(
+            update_url_query('https://www.youtube.com/playlist', qs),
+            ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
 
-class YoutubeLiveIE(YoutubeBaseInfoExtractor):
-    IE_DESC = 'YouTube.com live streams'
-    _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
-    IE_NAME = 'youtube:live'
 
+class YoutubeYtBeIE(InfoExtractor):
+    IE_DESC = 'youtu.be'
+    _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}
     _TESTS = [{
-        'url': 'https://www.youtube.com/user/TheYoungTurks/live',
+        'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
         'info_dict': {
-            'id': 'a48o2S1cPoo',
+            'id': 'yeWKywCrFtk',
             'ext': 'mp4',
-            'title': 'The Young Turks - Live Main Show',
-            'uploader': 'The Young Turks',
-            'uploader_id': 'TheYoungTurks',
-            'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
-            'upload_date': '20150715',
-            'license': 'Standard YouTube License',
-            'description': 'md5:438179573adcdff3c97ebb1ee632b891',
-            'categories': ['News & Politics'],
-            'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
+            'title': 'Small Scale Baler and Braiding Rugs',
+            'uploader': 'Backus-Page House Museum',
+            'uploader_id': 'backuspagemuseum',
+            'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
+            'upload_date': '20161008',
+            'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
+            'categories': ['Nonprofits & Activism'],
+            'tags': list,
             'like_count': int,
             'dislike_count': int,
         },
         'params': {
+            'noplaylist': True,
             'skip_download': True,
         },
     }, {
-        'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtube.com/TheYoungTurks/live',
+        'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
         'only_matching': True,
     }]
 
     def _real_extract(self, url):
         mobj = re.match(self._VALID_URL, url)
-        channel_id = mobj.group('id')
-        base_url = mobj.group('base_url')
-        webpage = self._download_webpage(url, channel_id, fatal=False)
-        if webpage:
-            page_type = self._og_search_property(
-                'type', webpage, 'page type', default='')
-            video_id = self._html_search_meta(
-                'videoId', webpage, 'video id', default=None)
-            if page_type.startswith('video') and video_id and re.match(
-                    r'^[0-9A-Za-z_-]{11}$', video_id):
-                return self.url_result(video_id, YoutubeIE.ie_key())
-        return self.url_result(base_url)
+        video_id = mobj.group('id')
+        playlist_id = mobj.group('playlist_id')
+        return self.url_result(
+            update_url_query('https://www.youtube.com/watch', {
+                'v': video_id,
+                'list': playlist_id,
+                'feature': 'youtu.be',
+            }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
+
+
+class YoutubeYtUserIE(InfoExtractor):
+    IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
+    _VALID_URL = r'ytuser:(?P<id>.+)'
+    _TESTS = [{
+        'url': 'ytuser:phihag',
+        'only_matching': True,
+    }]
 
+    def _real_extract(self, url):
+        user_id = self._match_id(url)
+        return self.url_result(
+            'https://www.youtube.com/user/%s' % user_id,
+            ie=YoutubeTabIE.ie_key(), video_id=user_id)
 
-class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
-    IE_DESC = 'YouTube.com user/channel playlists'
-    _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel|c)/(?P<id>[^/]+)/playlists'
-    IE_NAME = 'youtube:playlists'
 
+class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
+    IE_NAME = 'youtube:favorites'
+    IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
+    _VALID_URL = r':ytfav(?:ou?rite)?s?'
+    _LOGIN_REQUIRED = True
     _TESTS = [{
-        'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
-        'playlist_mincount': 4,
-        'info_dict': {
-            'id': 'ThirstForScience',
-            'title': 'ThirstForScience',
-        },
-    }, {
-        # with "Load more" button
-        'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
-        'playlist_mincount': 70,
-        'info_dict': {
-            'id': 'igorkle1',
-            'title': 'Игорь Клейнер',
-        },
-    }, {
-        'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
-        'playlist_mincount': 17,
-        'info_dict': {
-            'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
-            'title': 'Chem Player',
-        },
-        'skip': 'Blocked',
+        'url': ':ytfav',
+        'only_matching': True,
     }, {
-        'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
+        'url': ':ytfavorites',
         'only_matching': True,
     }]
 
+    def _real_extract(self, url):
+        return self.url_result(
+            'https://www.youtube.com/playlist?list=LL',
+            ie=YoutubeTabIE.ie_key())
+
 
-class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistBaseInfoExtractor):
-    IE_DESC = 'YouTube.com searches'
+class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
+    IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
     # there doesn't appear to be a real limit, for example if you search for
     # 'python' you get more than 8.000.000 results
     _MAX_RESULTS = float('inf')
@@ -3337,65 +3219,38 @@ def _entries(self, query, n):
             if not slr_contents:
                 break
 
-            isr_contents = []
-            continuation_token = None
             # Youtube sometimes adds promoted content to searches,
             # changing the index location of videos and token.
             # So we search through all entries till we find them.
-            for index, isr in enumerate(slr_contents):
-                if not isr_contents:
-                    isr_contents = try_get(
-                        slr_contents,
-                        (lambda x: x[index]['itemSectionRenderer']['contents']),
-                        list)
-                    for content in isr_contents:
-                        if content.get('videoRenderer') is not None:
-                            break
-                    else:
-                        isr_contents = []
-
+            continuation_token = None
+            for slr_content in slr_contents:
                 if continuation_token is None:
                     continuation_token = try_get(
-                        slr_contents,
-                        lambda x: x[index]['continuationItemRenderer']['continuationEndpoint']['continuationCommand'][
-                            'token'],
+                        slr_content,
+                        lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
                         compat_str)
-                if continuation_token is not None and isr_contents:
-                    break
 
-            if not isr_contents:
-                break
-            for content in isr_contents:
-                if not isinstance(content, dict):
-                    continue
-                video = content.get('videoRenderer')
-                if not isinstance(video, dict):
-                    continue
-                video_id = video.get('videoId')
-                if not video_id:
+                isr_contents = try_get(
+                    slr_content,
+                    lambda x: x['itemSectionRenderer']['contents'],
+                    list)
+                if not isr_contents:
                     continue
-                title = try_get(video, lambda x: x['title']['runs'][0]['text'], compat_str)
-                description = try_get(video, lambda x: x['descriptionSnippet']['runs'][0]['text'], compat_str)
-                duration = parse_duration(try_get(video, lambda x: x['lengthText']['simpleText'], compat_str))
-                view_count_text = try_get(video, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
-                view_count = int_or_none(self._search_regex(
-                    r'^(\d+)', re.sub(r'\s', '', view_count_text),
-                    'view count', default=None))
-                uploader = try_get(video, lambda x: x['ownerText']['runs'][0]['text'], compat_str)
-                total += 1
-                yield {
-                    '_type': 'url_transparent',
-                    'ie_key': YoutubeIE.ie_key(),
-                    'id': video_id,
-                    'url': video_id,
-                    'title': title,
-                    'description': description,
-                    'duration': duration,
-                    'view_count': view_count,
-                    'uploader': uploader,
-                }
-                if total == n:
-                    return
+                for content in isr_contents:
+                    if not isinstance(content, dict):
+                        continue
+                    video = content.get('videoRenderer')
+                    if not isinstance(video, dict):
+                        continue
+                    video_id = video.get('videoId')
+                    if not video_id:
+                        continue
+
+                    yield self._extract_video(video)
+                    total += 1
+                    if total == n:
+                        return
+
             if not continuation_token:
                 break
             data['continuation'] = continuation_token
@@ -3408,14 +3263,15 @@ def _get_n_results(self, query, n):
 class YoutubeSearchDateIE(YoutubeSearchIE):
     IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
     _SEARCH_KEY = 'ytsearchdate'
-    IE_DESC = 'YouTube.com searches, newest videos first'
+    IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
     _SEARCH_PARAMS = 'CAI%3D'
 
 
-class YoutubeSearchURLIE(YoutubePlaylistBaseInfoExtractor):
+class YoutubeSearchURLIE(YoutubeSearchIE):
     IE_DESC = 'YouTube.com search URLs'
-    IE_NAME = 'youtube:search_url'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
+    IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
+    _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
+    # _MAX_RESULTS = 100
     _TESTS = [{
         'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
         'playlist_mincount': 5,
@@ -3427,47 +3283,25 @@ class YoutubeSearchURLIE(YoutubePlaylistBaseInfoExtractor):
         'only_matching': True,
     }]
 
-    def _process_json_dict(self, obj, videos, c):
-        if "videoId" in obj:
-            videos.append(obj)
-            return
-
-        if "nextContinuationData" in obj:
-            c["continuation"] = obj["nextContinuationData"]
-            return
-
-    def _real_extract(self, url):
-        mobj = re.match(self._VALID_URL, url)
-        query = compat_urllib_parse_unquote_plus(mobj.group('query'))
-        webpage = self._download_webpage(url, query)
-        return self.playlist_result(self._entries(webpage, query, max_pages=5), playlist_title=query)
-
-
-class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
-    IE_DESC = 'YouTube.com (multi-season) shows'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
-    IE_NAME = 'youtube:show'
-    _TESTS = [{
-        'url': 'https://www.youtube.com/show/airdisasters',
-        'playlist_mincount': 5,
-        'info_dict': {
-            'id': 'airdisasters',
-            'title': 'Air Disasters',
-        }
-    }]
+    @classmethod
+    def _make_valid_url(cls):
+        return cls._VALID_URL
 
     def _real_extract(self, url):
-        playlist_id = self._match_id(url)
-        return super(YoutubeShowIE, self)._real_extract(
-            'https://www.youtube.com/show/%s/playlists' % playlist_id)
+        qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
+        query = (qs.get('search_query') or qs.get('q'))[0]
+        self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
+        return self._get_n_results(query, self._MAX_RESULTS)
 
 
-class YoutubeFeedsInfoExtractor(YoutubePlaylistBaseInfoExtractor):
+class YoutubeFeedsInfoExtractor(YoutubeTabIE):
     """
     Base class for feed extractors
-    Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
+    Subclasses must define the _FEED_NAME property.
     """
     _LOGIN_REQUIRED = True
+    # _MAX_PAGES = 5
+    _TESTS = []
 
     @property
     def IE_NAME(self):
@@ -3476,89 +3310,63 @@ def IE_NAME(self):
     def _real_initialize(self):
         self._login()
 
-    def _process_entries(self, entries, seen):
-        new_info = []
-        for v in entries:
-            v_id = try_get(v, lambda x: x['videoId'])
-            if not v_id:
-                continue
-
-            have_video = False
-            for old in seen:
-                if old['videoId'] == v_id:
-                    have_video = True
-                    break
-
-            if not have_video:
-                new_info.append(v)
-
-        if not new_info:
-            return
-
-        seen.extend(new_info)
-        for video in new_info:
-            yield self.url_result(try_get(video, lambda x: x['videoId']), YoutubeIE.ie_key(), video_title=self._extract_title(video))
-
     def _real_extract(self, url):
-        page = self._download_webpage(
+        return self.url_result(
             'https://www.youtube.com/feed/%s' % self._FEED_NAME,
-            self._PLAYLIST_TITLE)
-        return self.playlist_result(self._entries(page, self._PLAYLIST_TITLE),
-                                    playlist_title=self._PLAYLIST_TITLE)
+            ie=YoutubeTabIE.ie_key())
 
 
-class YoutubeWatchLaterIE(YoutubePlaylistIE):
+class YoutubeWatchLaterIE(InfoExtractor):
     IE_NAME = 'youtube:watchlater'
     IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
-
+    _VALID_URL = r':ytwatchlater'
     _TESTS = [{
-        'url': 'https://www.youtube.com/playlist?list=WL',
-        'only_matching': True,
-    }, {
-        'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
+        'url': ':ytwatchlater',
         'only_matching': True,
     }]
 
     def _real_extract(self, url):
-        _, video = self._check_download_just_video(url, 'WL')
-        if video:
-            return video
-        _, playlist = self._extract_playlist('WL')
-        return playlist
-
-
-class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
-    IE_NAME = 'youtube:favorites'
-    IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
-    _LOGIN_REQUIRED = True
-
-    def _real_extract(self, url):
-        webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
-        playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
-        return self.url_result(playlist_id, 'YoutubePlaylist')
+        return self.url_result(
+            'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
 
 
 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
     IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
+    _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
     _FEED_NAME = 'recommended'
-    _PLAYLIST_TITLE = 'Youtube Recommended videos'
+    _TESTS = [{
+        'url': ':ytrec',
+        'only_matching': True,
+    }, {
+        'url': ':ytrecommended',
+        'only_matching': True,
+    }, {
+        'url': 'https://youtube.com',
+        'only_matching': True,
+    }]
 
 
 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
-    IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
+    IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
+    _VALID_URL = r':ytsub(?:scription)?s?'
     _FEED_NAME = 'subscriptions'
-    _PLAYLIST_TITLE = 'Youtube Subscriptions'
+    _TESTS = [{
+        'url': ':ytsubs',
+        'only_matching': True,
+    }, {
+        'url': ':ytsubscriptions',
+        'only_matching': True,
+    }]
 
 
 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
     IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
-    _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
+    _VALID_URL = r':ythistory'
     _FEED_NAME = 'history'
-    _PLAYLIST_TITLE = 'Youtube History'
+    _TESTS = [{
+        'url': ':ythistory',
+        'only_matching': True,
+    }]
 
 
 class YoutubeTruncatedURLIE(InfoExtractor):