Repository: yt-dlp/yt-dlp

Issue:
New Player 20dfca59 has broken YouTube extractor
### DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

- [X] I understand that I will be **blocked** if I *intentionally* remove or skip any mandatory\* field

### Checklist

- [X] I'm reporting that yt-dlp is broken on a **supported** site
- [X] I've verified that I have **updated yt-dlp to nightly or master** ([update instructions](https://github.com/yt-dlp/yt-dlp#update-channels))
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [X] I've checked that all URLs and arguments with special characters are [properly quoted or escaped](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#video-url-contains-an-ampersand--and-im-getting-some-strange-output-1-2839-or-v-is-not-recognized-as-an-internal-or-external-command)
- [X] I've searched [known issues](https://github.com/yt-dlp/yt-dlp/issues/3766) and the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues **including closed ones**. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)
- [X] I've read about [sharing account credentials](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#are-you-willing-to-share-account-details-if-needed) and I'm willing to share it if required

### Region

_No response_

### Provide a description that is worded well enough to be understood

A new player (20dfca59) has broken the YouTube extractor

### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [X] If using API, add `'verbose': True` to `YoutubeDL` params instead
- [X] Copy the WHOLE output (starting with `[debug] Command-line config`) and insert it below

### Complete Verbose Output

```shell
[debug] Encodings: locale cp1252, fs utf-8, pref cp1252, out utf-8, error utf-8, screen utf-8
[debug] yt-dlp version stable@2024.07.25 from yt-dlp/yt-dlp [f0993391e] (pip)
[debug] Python 3.12.3 (CPython AMD64 64bit) - Windows-11-10.0.22631-SP0 (OpenSSL 3.0.13 30 Jan 2024)
[debug] exe versions: ffmpeg N-116328-gfa5a605542-20240718 (setts), ffprobe N-116328-gfa5a605542-20240718
[debug] Optional libraries: Cryptodome-3.20.0, brotli-1.1.0, certifi-2024.07.04, mutagen-1.47.0, requests-2.32.3, sqlite3-3.45.1, urllib3-2.2.2, websockets-12.0
[debug] Proxy map: {}
[debug] Request Handlers: urllib, requests, websockets
[debug] Loaded 1829 extractors
[debug] Fetching release info: https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest
Latest version: stable@2024.07.25 from yt-dlp/yt-dlp
yt-dlp is up to date (stable@2024.07.25 from yt-dlp/yt-dlp)
[youtube:tab] Extracting URL: https://music.youtube.com/playlist?list=OLAK5uy_kOExsg4A5Wc7X3_DhtK4GB0YqdeFIIjhs
WARNING: [youtube:tab] YouTube Music is not directly supported. Redirecting to https://www.youtube.com/playlist?list=OLAK5uy_kOExsg4A5Wc7X3_DhtK4GB0YqdeFIIjhs
[youtube:tab] OLAK5uy_kOExsg4A5Wc7X3_DhtK4GB0YqdeFIIjhs: Downloading webpage
[debug] [youtube:tab] Extracted SAPISID cookie
[youtube:tab] OLAK5uy_kOExsg4A5Wc7X3_DhtK4GB0YqdeFIIjhs: Redownloading playlist API JSON with unavailable videos
[download] Downloading playlist: Album - Meteora 20th Anniversary Edition
[youtube:tab] Playlist Album - Meteora 20th Anniversary Edition: Downloading 89 items of 89
[download] Downloading item 1 of 89
[youtube] Extracting URL: https://music.youtube.com/watch?v=d_iv0n9ZpAg
[youtube] d_iv0n9ZpAg: Downloading webpage
[debug] [youtube] Extracted SAPISID cookie
[youtube] d_iv0n9ZpAg: Downloading ios player API JSON
[youtube] d_iv0n9ZpAg: Downloading ios music player API JSON
[youtube] d_iv0n9ZpAg: Downloading web music client config
[youtube] d_iv0n9ZpAg: Downloading player 20dfca59
[youtube] d_iv0n9ZpAg: Downloading web music player API JSON
[debug] [youtube] Extracting signature function js_20dfca59_107
[debug] Loading youtube-sigfuncs.js_20dfca59_107 from cache
WARNING: [youtube] d_iv0n9ZpAg: nsig extraction failed: Some formats may be missing
         n = A1Ou24bVhXz1jIVy ; player = https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js
[debug] [youtube] Unable to extract nsig function code (caused by RegexNotFoundError('Unable to extract \x1b[0;94mInitial JS player n function name\x1b[0m; please report this issue on  https://github.com/yt-dlp/yt-dlp/issues?q= , filling out the appropriate issue template. Confirm you are on the latest version using  yt-dlp -U')); please report this issue on  https://github.com/yt-dlp/yt-dlp/issues?q= , filling out the appropriate issue template. Confirm you are on the latest version using  yt-dlp -U
WARNING: [youtube] d_iv0n9ZpAg: nsig extraction failed: Some formats may be missing
         n = -fLCxedkAk4LUTK2 ; player = https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js
[debug] [youtube] Extracting signature function js_20dfca59_103
[debug] Loading youtube-sigfuncs.js_20dfca59_103 from cache
WARNING: [youtube] d_iv0n9ZpAg: nsig extraction failed: Some formats may be missing
         n = lfFDQouqFm1Pmkfk ; player = https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js
WARNING: [youtube] d_iv0n9ZpAg: nsig extraction failed: Some formats may be missing
         n = N6FLr39qpAOmT5Ak ; player = https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js
```


Discussion:

Patch:
diff --git a/yt_dlp/extractor/mediaklikk.py b/yt_dlp/extractor/mediaklikk.py
index bd1a27fcc..f51342060 100644
--- a/yt_dlp/extractor/mediaklikk.py
+++ b/yt_dlp/extractor/mediaklikk.py
@@ -133,7 +133,9 @@ def _real_extract(self, url):
                 r'<p+\b[^>]+\bclass="article_date">([^<]+)<', webpage, 'upload date', default=None))
 
         player_data['video'] = player_data.pop('token')
-        player_page = self._download_webpage('https://player.mediaklikk.hu/playernew/player.php', video_id, query=player_data)
+        player_page = self._download_webpage(
+            'https://player.mediaklikk.hu/playernew/player.php', video_id,
+            query=player_data, headers={'Referer': url})
         player_json = self._search_json(
             r'\bpl\.setup\s*\(', player_page, 'player json', video_id, end_pattern=r'\);')
         playlist_url = traverse_obj(
diff --git a/yt_dlp/extractor/olympics.py b/yt_dlp/extractor/olympics.py
index becf052f6..a50c510cb 100644
--- a/yt_dlp/extractor/olympics.py
+++ b/yt_dlp/extractor/olympics.py
@@ -1,9 +1,17 @@
 from .common import InfoExtractor
-from ..utils import int_or_none, try_get
+from ..networking.exceptions import HTTPError
+from ..utils import (
+    ExtractorError,
+    int_or_none,
+    parse_iso8601,
+    try_get,
+    url_or_none,
+)
+from ..utils.traversal import traverse_obj
 
 
 class OlympicsReplayIE(InfoExtractor):
-    _VALID_URL = r'https?://(?:www\.)?olympics\.com(?:/tokyo-2020)?/[a-z]{2}/(?:replay|video)/(?P<id>[^/#&?]+)'
+    _VALID_URL = r'https?://(?:www\.)?olympics\.com/[a-z]{2}/(?:paris-2024/)?(?:replay|videos?|original-series/episode)/(?P<id>[\w-]+)'
     _TESTS = [{
         'url': 'https://olympics.com/fr/video/men-s-109kg-group-a-weightlifting-tokyo-2020-replays',
         'info_dict': {
@@ -11,26 +19,98 @@ class OlympicsReplayIE(InfoExtractor):
             'ext': 'mp4',
             'title': '+109kg (H) Groupe A - Haltérophilie | Replay de Tokyo 2020',
             'upload_date': '20210801',
-            'timestamp': 1627783200,
+            'timestamp': 1627797600,
             'description': 'md5:c66af4a5bc7429dbcc43d15845ff03b3',
-            'uploader': 'International Olympic Committee',
+            'thumbnail': 'https://img.olympics.com/images/image/private/t_1-1_1280/primary/nua4o7zwyaznoaejpbk2',
+            'duration': 7017.0,
         },
         'params': {
             'skip_download': True,
         },
     }, {
-        'url': 'https://olympics.com/tokyo-2020/en/replay/bd242924-4b22-49a5-a846-f1d4c809250d/mens-bronze-medal-match-hun-esp',
-        'only_matching': True,
+        'url': 'https://olympics.com/en/original-series/episode/b-boys-and-b-girls-take-the-spotlight-breaking-life-road-to-paris-2024',
+        'info_dict': {
+            'id': '32633650-c5ee-4280-8b94-fb6defb6a9b5',
+            'ext': 'mp4',
+            'title': 'B-girl Nicka - Breaking Life, Road to Paris 2024 | Episode 1',
+            'upload_date': '20240517',
+            'timestamp': 1715948200,
+            'description': 'md5:f63d728a41270ec628f6ac33ce471bb1',
+            'thumbnail': 'https://img.olympics.com/images/image/private/t_1-1_1280/primary/a3j96l7j6so3vyfijby1',
+            'duration': 1321.0,
+        },
+    }, {
+        'url': 'https://olympics.com/en/paris-2024/videos/men-s-preliminaries-gbr-esp-ned-rsa-hockey-olympic-games-paris-2024',
+        'info_dict': {
+            'id': '3d96db23-8eee-4b7c-8ef5-488a0361026c',
+            'ext': 'mp4',
+            'title': 'Men\'s Preliminaries GBR-ESP & NED-RSA | Hockey | Olympic Games Paris 2024',
+            'upload_date': '20240727',
+            'timestamp': 1722066600,
+        },
+        'skip': 'Geo-restricted to RU, BR, BT, NP, TM, BD, TL',
+    }, {
+        'url': 'https://olympics.com/en/paris-2024/videos/dnp-suni-lee-i-have-goals-and-i-have-expectations-for-myself-but-i-also-am-trying-to-give-myself-grace',
+        'info_dict': {
+            'id': 'a42f37ab-8a74-41d0-a7d9-af27b7b02a90',
+            'ext': 'mp4',
+            'title': 'md5:c7cfbc9918636a98e66400a812e4d407',
+            'upload_date': '20240729',
+            'timestamp': 1722288600,
+        },
     }]
+    _GEO_BYPASS = False
+
+    def _extract_from_nextjs_data(self, webpage, video_id):
+        data = traverse_obj(self._search_nextjs_data(webpage, video_id, default={}), (
+            'props', 'pageProps', 'page', 'items',
+            lambda _, v: v['name'] == 'videoPlaylist', 'data', 'currentVideo', {dict}, any))
+        if not data:
+            return None
+
+        geo_countries = traverse_obj(data, ('countries', ..., {str}))
+        if traverse_obj(data, ('geoRestrictedVideo', {bool})):
+            self.raise_geo_restricted(countries=geo_countries)
+
+        is_live = traverse_obj(data, ('streamingStatus', {str})) == 'LIVE'
+        m3u8_url = traverse_obj(data, ('videoUrl', {url_or_none})) or data['streamUrl']
+        tokenized_url = m3u8_url if is_live else self._tokenize_url(m3u8_url, video_id)
+
+        try:
+            formats, subtitles = self._extract_m3u8_formats_and_subtitles(
+                tokenized_url, video_id, 'mp4', m3u8_id='hls')
+        except ExtractorError as e:
+            if isinstance(e.cause, HTTPError) and 'georestricted' in e.cause.msg:
+                self.raise_geo_restricted(countries=geo_countries)
+            raise
+
+        return {
+            'formats': formats,
+            'subtitles': subtitles,
+            'is_live': is_live,
+            **traverse_obj(data, {
+                'id': ('videoID', {str}),
+                'title': ('title', {str}),
+                'timestamp': ('contentDate', {parse_iso8601}),
+            }),
+        }
+
+    def _tokenize_url(self, url, video_id):
+        return self._download_json(
+            'https://olympics.com/tokenGenerator', video_id,
+            'Downloading tokenized m3u8 url', query={'url': url})
 
     def _real_extract(self, url):
         video_id = self._match_id(url)
-
         webpage = self._download_webpage(url, video_id)
+
+        if info := self._extract_from_nextjs_data(webpage, video_id):
+            return info
+
         title = self._html_search_meta(('title', 'og:title', 'twitter:title'), webpage)
-        uuid = self._html_search_meta('episode_uid', webpage)
+        video_uuid = self._html_search_meta('episode_uid', webpage)
         m3u8_url = self._html_search_meta('video_url', webpage)
-        json_ld = self._search_json_ld(webpage, uuid)
+        json_ld = self._search_json_ld(webpage, video_uuid)
         thumbnails_list = json_ld.get('image')
         if not thumbnails_list:
             thumbnails_list = self._html_search_regex(
@@ -48,12 +128,12 @@ def _real_extract(self, url):
                 'width': width,
                 'height': int_or_none(try_get(width, lambda x: x * height_a / width_a)),
             })
-        m3u8_url = self._download_json(
-            f'https://olympics.com/tokenGenerator?url={m3u8_url}', uuid, note='Downloading m3u8 url')
-        formats, subtitles = self._extract_m3u8_formats_and_subtitles(m3u8_url, uuid, 'mp4', m3u8_id='hls')
+
+        formats, subtitles = self._extract_m3u8_formats_and_subtitles(
+            self._tokenize_url(m3u8_url, video_uuid), video_uuid, 'mp4', m3u8_id='hls')
 
         return {
-            'id': uuid,
+            'id': video_uuid,
             'title': title,
             'thumbnails': thumbnails,
             'formats': formats,
diff --git a/yt_dlp/extractor/tver.py b/yt_dlp/extractor/tver.py
index 8105db41c..c13832c6f 100644
--- a/yt_dlp/extractor/tver.py
+++ b/yt_dlp/extractor/tver.py
@@ -10,7 +10,7 @@
 
 
 class TVerIE(InfoExtractor):
-    _VALID_URL = r'https?://(?:www\.)?tver\.jp/(?:(?P<type>lp|corner|series|episodes?|feature|tokyo2020/video)/)+(?P<id>[a-zA-Z0-9]+)'
+    _VALID_URL = r'https?://(?:www\.)?tver\.jp/(?:(?P<type>lp|corner|series|episodes?|feature|tokyo2020/video|olympic/paris2024/video)/)+(?P<id>[a-zA-Z0-9]+)'
     _TESTS = [{
         'skip': 'videos are only available for 7 days',
         'url': 'https://tver.jp/episodes/ep83nf3w4p',
@@ -23,6 +23,20 @@ class TVerIE(InfoExtractor):
             'channel': 'テレビ朝日',
         },
         'add_ie': ['BrightcoveNew'],
+    }, {
+        'url': 'https://tver.jp/olympic/paris2024/video/6359578055112/',
+        'info_dict': {
+            'id': '6359578055112',
+            'ext': 'mp4',
+            'title': '堀米雄斗 金メダルで五輪連覇！「みんなの応援が最後に乗れたカギ」',
+            'timestamp': 1722279928,
+            'upload_date': '20240729',
+            'tags': ['20240729', 'japanese', 'japanmedal', 'paris'],
+            'uploader_id': '4774017240001',
+            'thumbnail': r're:https?://[^/?#]+boltdns\.net/[^?#]+/1920x1080/match/image\.jpg',
+            'duration': 670.571,
+        },
+        'params': {'skip_download': 'm3u8'},
     }, {
         'url': 'https://tver.jp/corner/f0103888',
         'only_matching': True,
@@ -47,7 +61,15 @@ def _real_initialize(self):
 
     def _real_extract(self, url):
         video_id, video_type = self._match_valid_url(url).group('id', 'type')
-        if video_type not in {'series', 'episodes'}:
+
+        if video_type == 'olympic/paris2024/video':
+            # Player ID is taken from .content.brightcove.E200.pro.pc.account_id:
+            # https://tver.jp/olympic/paris2024/req/api/hook?q=https%3A%2F%2Folympic-assets.tver.jp%2Fweb-static%2Fjson%2Fconfig.json&d=
+            return self.url_result(smuggle_url(
+                self.BRIGHTCOVE_URL_TEMPLATE % ('4774017240001', video_id),
+                {'geo_countries': ['JP']}), 'BrightcoveNew')
+
+        elif video_type not in {'series', 'episodes'}:
             webpage = self._download_webpage(url, video_id, note='Resolving to new URL')
             video_id = self._match_id(self._search_regex(
                 (r'canonical"\s*href="(https?://tver\.jp/[^"]+)"', r'&link=(https?://tver\.jp/[^?&]+)[?&]'),
diff --git a/yt_dlp/extractor/youtube.py b/yt_dlp/extractor/youtube.py
index 1a3e286c6..4993ce397 100644
--- a/yt_dlp/extractor/youtube.py
+++ b/yt_dlp/extractor/youtube.py
@@ -3174,18 +3174,32 @@ def _decrypt_nsig(self, s, video_id, player_url):
         return ret
 
     def _extract_n_function_name(self, jscode):
+        # Examples (with placeholders nfunc, narray, idx):
+        # *  .get("n"))&&(b=nfunc(b)
+        # *  .get("n"))&&(b=narray[idx](b)
+        # *  b=String.fromCharCode(110),c=a.get(b))&&c=narray[idx](c)
+        # *  a.D&&(b="nn"[+a.D],c=a.get(b))&&(c=narray[idx](c),a.set(b,c),narray.length||nfunc("")
+        # *  a.D&&(PL(a),b=a.j.n||null)&&(b=narray[0](b),a.set("n",b),narray.length||nfunc("")
         funcname, idx = self._search_regex(
             r'''(?x)
             (?:
                 \.get\("n"\)\)&&\(b=|
                 (?:
                     b=String\.fromCharCode\(110\)|
-                    ([a-zA-Z0-9$.]+)&&\(b="nn"\[\+\1\]
-                ),c=a\.get\(b\)\)&&\(c=
-            )
-            (?P<nfunc>[a-zA-Z0-9$]+)(?:\[(?P<idx>\d+)\])?\([a-zA-Z0-9]\)''',
-            jscode, 'Initial JS player n function name', group=('nfunc', 'idx'))
-        if not idx:
+                    (?P<str_idx>[a-zA-Z0-9_$.]+)&&\(b="nn"\[\+(?P=str_idx)\]
+                ),c=a\.get\(b\)\)&&\(c=|
+                \b(?P<var>[a-zA-Z0-9_$]+)=
+            )(?P<nfunc>[a-zA-Z0-9_$]+)(?:\[(?P<idx>\d+)\])?\([a-zA-Z]\)
+            (?(var),[a-zA-Z0-9_$]+\.set\("n"\,(?P=var)\),(?P=nfunc)\.length)''',
+            jscode, 'n function name', group=('nfunc', 'idx'), default=(None, None))
+        if not funcname:
+            self.report_warning('Falling back to generic n function search')
+            return self._search_regex(
+                r'''(?xs)
+                ;\s*(?P<name>[a-zA-Z0-9_$]+)\s*=\s*function\([a-zA-Z0-9_$]+\)
+                \s*\{(?:(?!};).)+?["']enhanced_except_''',
+                jscode, 'Initial JS player n function name', group='name')
+        elif not idx:
             return funcname
 
         return json.loads(js_to_json(self._search_regex(


Test patch:
diff --git a/test/test_youtube_signature.py b/test/test_youtube_signature.py
index ae167d16d..d37df7a2e 100644
--- a/test/test_youtube_signature.py
+++ b/test/test_youtube_signature.py
@@ -175,6 +175,10 @@
         'https://www.youtube.com/s/player/3400486c/player_ias.vflset/en_US/base.js',
         'lL46g3XifCKUZn1Xfw', 'z767lhet6V2Skl',
     ),
+    (
+        'https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js',
+        '-fLCxedkAk4LUTK2', 'O8kfRq1y1eyHGw',
+    ),
 ]