Repository: yt-dlp/yt-dlp

Issue:
[AfreecaTV] Ability to switch between servers with options
### 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 requesting a site-specific feature
- [X] I've verified that I'm running yt-dlp version **2023.03.04** ([update instructions](https://github.com/yt-dlp/yt-dlp#update)) or later (specify commit)
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [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

Most parts of the world

### Example URLs

https://play.afreecatv.com/m0m099/live

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

AfreecaTV has more than one server/CDN and I would like to have the ability to use options in the command line to switch between them.

To what I know, yt-dlp uses "gcp_cdn" and streamlink uses "gs_cdn_pc_web".

The reason why I want this feature is that gcp is giving me some issues where it would be very unstable at a certain day/time and streamlink doesn't have the --no-hls-use-mpegts command that I use with yt-dlp.

### 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] Command-line config: ['-vU', 'https://play.afreecatv.com/m0m099/live']
[debug] Encodings: locale cp950, fs utf-8, pref cp950, out utf-8, error utf-8, screen utf-8
[debug] yt-dlp version stable@2023.03.04 [392389b7d] (win_exe)
[debug] Python 3.8.10 (CPython AMD64 64bit) - Windows-10-10.0.22621-SP0 (OpenSSL 1.1.1k  25 Mar 2021)
[debug] exe versions: ffmpeg N-107944-g4fce3bab64-20220830 (setts), ffprobe N-107944-g4fce3bab64-20220830
[debug] Optional libraries: Cryptodome-3.17, brotli-1.0.9, certifi-2022.12.07, mutagen-1.46.0, sqlite3-2.6.0, websockets-10.4
[debug] Proxy map: {}
[debug] Loaded 1786 extractors
[debug] Fetching release info: https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest
Available version: stable@2023.03.04, Current version: stable@2023.03.04
Current Build Hash: 5590c57bd0433ed239a2deaaf92e2ad6f37fe50f53664c821575cafe106a9421
yt-dlp is up to date (stable@2023.03.04)
[afreecatv:live] Extracting URL: https://play.afreecatv.com/m0m099/live
[afreecatv:live] m0m099: Downloading JSON metadata
[afreecatv:live] 245401012: Downloading access token for sd stream
[afreecatv:live] 245401012: Downloading metadata for sd stream
[afreecatv:live] 245401012: Downloading access token for hd stream
[afreecatv:live] 245401012: Downloading metadata for hd stream
[afreecatv:live] 245401012: Downloading access token for hd2k stream
[afreecatv:live] 245401012: Downloading metadata for hd2k stream
[afreecatv:live] 245401012: Downloading access token for original stream
[afreecatv:live] 245401012: Downloading metadata for original stream
[afreecatv:live] 245401012: Downloading channel metadata
[debug] Formats sorted by: hasvid, ie_pref, lang, quality, res, fps, hdr:12(7), vcodec:vp9.2(10), channels, acodec, filesize, fs_approx, tbr, vbr, abr, asr, proto, vext, aext, hasaud, source, id
[debug] Default format spec: best/bestvideo+bestaudio
[info] 245401012: Downloading 1 format(s): original
[debug] Invoking ffmpeg downloader on "https://live-global-cdn-v02.afreecatv.com/live-stm-01/auth_playlist.m3u8?aid=.A32.7bbT56vyHM9fKZk.Jd0P35RgmksLW32apUsJiTT30jbEaCSkVevKEMukEgl4XtdqRQ2jltIS4uxOnlUy-k3UtdZAj3AnSYmvOp8VNzG9hTskKMuLvgSww_QBvWE"
[download] Destination: 항공캠 궁금하지않앙？..ㅎ♥ 2023-03-09 20_08 [245401012].mp4
[debug] ffmpeg command line: ffmpeg -y -loglevel verbose -headers "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.17 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Sec-Fetch-Mode: navigate
```



Discussion:
As of 9073ae6458f4c6a832aa832c67174c61852869be, yt-dlp is using `gs_cdn_pc_app`

This could easily be added as an extractor-arg though

Resolving patch:
diff --git a/yt_dlp/extractor/afreecatv.py b/yt_dlp/extractor/afreecatv.py
--- a/yt_dlp/extractor/afreecatv.py
+++ b/yt_dlp/extractor/afreecatv.py
@@ -8,9 +8,11 @@
     determine_ext,
     filter_dict,
     int_or_none,
+    orderedSet,
     unified_timestamp,
     url_or_none,
     urlencode_postdata,
+    urljoin,
 )
 from ..utils.traversal import traverse_obj
 
@@ -276,6 +278,47 @@ class AfreecaTVLiveIE(AfreecaTVBaseIE):
     }]
 
     _LIVE_API_URL = 'https://live.afreecatv.com/afreeca/player_live_api.php'
+    _WORKING_CDNS = [
+        'gcp_cdn',  # live-global-cdn-v02.afreecatv.com
+        'gs_cdn_pc_app',  # pc-app.stream.afreecatv.com
+        'gs_cdn_mobile_web',  # mobile-web.stream.afreecatv.com
+        'gs_cdn_pc_web',  # pc-web.stream.afreecatv.com
+    ]
+    _BAD_CDNS = [
+        'gs_cdn',  # chromecast.afreeca.gscdn.com (cannot resolve)
+        'gs_cdn_chromecast',  # chromecast.stream.afreecatv.com (HTTP Error 400)
+        'azure_cdn',  # live-global-cdn-v01.afreecatv.com (cannot resolve)
+        'aws_cf',  # live-global-cdn-v03.afreecatv.com (cannot resolve)
+        'kt_cdn',  # kt.stream.afreecatv.com (HTTP Error 400)
+    ]
+
+    def _extract_formats(self, channel_info, broadcast_no, aid):
+        stream_base_url = channel_info.get('RMD') or 'https://livestream-manager.afreecatv.com'
+
+        # If user has not passed CDN IDs, try API-provided CDN ID followed by other working CDN IDs
+        default_cdn_ids = orderedSet([
+            *traverse_obj(channel_info, ('CDN', {str}, all, lambda _, v: v not in self._BAD_CDNS)),
+            *self._WORKING_CDNS,
+        ])
+        cdn_ids = self._configuration_arg('cdn', default_cdn_ids)
+
+        for attempt, cdn_id in enumerate(cdn_ids, start=1):
+            m3u8_url = traverse_obj(self._download_json(
+                urljoin(stream_base_url, 'broad_stream_assign.html'), broadcast_no,
+                f'Downloading {cdn_id} stream info', f'Unable to download {cdn_id} stream info',
+                fatal=False, query={
+                    'return_type': cdn_id,
+                    'broad_key': f'{broadcast_no}-common-master-hls',
+                }), ('view_url', {url_or_none}))
+            try:
+                return self._extract_m3u8_formats(
+                    m3u8_url, broadcast_no, 'mp4', m3u8_id='hls', query={'aid': aid},
+                    headers={'Referer': 'https://play.afreecatv.com/'})
+            except ExtractorError as e:
+                if attempt == len(cdn_ids):
+                    raise
+                self.report_warning(
+                    f'{e.cause or e.msg}. Retrying... (attempt {attempt} of {len(cdn_ids)})')
 
     def _real_extract(self, url):
         broadcaster_id, broadcast_no = self._match_valid_url(url).group('id', 'bno')
@@ -294,7 +337,7 @@ def _real_extract(self, url):
                 'This livestream is protected by a password, use the --video-password option',
                 expected=True)
 
-        aid = self._download_json(
+        token_info = traverse_obj(self._download_json(
             self._LIVE_API_URL, broadcast_no, 'Downloading access token for stream',
             'Unable to download access token for stream', data=urlencode_postdata(filter_dict({
                 'bno': broadcast_no,
@@ -302,18 +345,17 @@ def _real_extract(self, url):
                 'type': 'aid',
                 'quality': 'master',
                 'pwd': password,
-            })))['CHANNEL']['AID']
-
-        stream_base_url = channel_info.get('RMD') or 'https://livestream-manager.afreecatv.com'
-        stream_info = self._download_json(f'{stream_base_url}/broad_stream_assign.html', broadcast_no, query={
-            # works: gs_cdn_pc_app, gs_cdn_mobile_web, gs_cdn_pc_web
-            'return_type': 'gs_cdn_pc_app',
-            'broad_key': f'{broadcast_no}-common-master-hls',
-        }, note='Downloading metadata for stream', errnote='Unable to download metadata for stream')
-
-        formats = self._extract_m3u8_formats(
-            stream_info['view_url'], broadcast_no, 'mp4', m3u8_id='hls',
-            query={'aid': aid}, headers={'Referer': url})
+            }))), ('CHANNEL', {dict})) or {}
+        aid = token_info.get('AID')
+        if not aid:
+            result = token_info.get('RESULT')
+            if result == 0:
+                raise ExtractorError('This livestream has ended', expected=True)
+            elif result == -6:
+                self.raise_login_required('This livestream is for subscribers only', method='password')
+            raise ExtractorError('Unable to extract access token')
+
+        formats = self._extract_formats(channel_info, broadcast_no, aid)
 
         station_info = traverse_obj(self._download_json(
             'https://st.afreecatv.com/api/get_station_status.php', broadcast_no,


Test patch: