Repository: yt-dlp/yt-dlp
Issue category: Feature Request

Issue:
[Chaturbate] Consider using the API
### 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 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 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)
- [ ] 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_

### Example URLs

https://chaturbate.com/kira_censori/

### Provide a description that is worded well enough to be understood

Currently yt-dlp loads the entire page to find the m3u8 stream URL, but another way is to use the API:

```sh
$ curl -X POST "https://chaturbate.com/get_edge_hls_url_ajax/" -H "X-Requested-With: XMLHttpRequest" -d "room_slug=kira_censori"
```

```json
{
    "success": true,
    "url": "https://edge17-hel.live.mmcdn.com/live-hls/amlst:kira_censori-sd-203fe4e99b463f0b5013d75b7f491286d7f8cbdad109cef79db409bfc80e33d0_trns_h264/playlist.m3u8",
    "room_status": "public",
    "hidden_message": ""
}
```

This endpoint provides the same m3u8 stream URL that is embedded in HTML (specifically in `window.initialRoomDossier`). The advantage is that this is ~500 times smaller in size compared to downloading the entire HTML page and simplifies error handling.

Here is a rough sequence of actions:

```
if "success":
  - true:
    if "room_status":
      - "public":
        if "url":
          - [m3u8 stream url]
          - "": [room is geo-blocked]
      - something else: [room is private or offline]
  - false: [room doesn't exist]
```

All possible `room_status` values can be found [here](https://devportal.cb.dev/wiki/api/$room#roomstatus-string). Not sure what we need to tell the user in non-`public` cases, above is just an example.

Maybe someday I'll do a PR if I have time. What do you think about that?

### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [ ] 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

_No response_



Hints:

Patch:
diff --git a/yt_dlp/extractor/chaturbate.py b/yt_dlp/extractor/chaturbate.py
index 864d61f9c2b8..aa70f26a1bcb 100644
--- a/yt_dlp/extractor/chaturbate.py
+++ b/yt_dlp/extractor/chaturbate.py
@@ -5,6 +5,7 @@
     ExtractorError,
     lowercase_escape,
     url_or_none,
+    urlencode_postdata,
 )
 
 
@@ -40,14 +41,48 @@ class ChaturbateIE(InfoExtractor):
         'only_matching': True,
     }]
 
-    _ROOM_OFFLINE = 'Room is currently offline'
+    _ERROR_MAP = {
+        'offline': 'Room is currently offline',
+        'private': 'Room is currently in a private show',
+        'away': 'Performer is currently away',
+        'password protected': 'Room is password protected',
+        'hidden': 'Hidden session in progress',
+    }
 
-    def _real_extract(self, url):
-        video_id, tld = self._match_valid_url(url).group('id', 'tld')
+    def _extract_from_api(self, video_id, tld):
+        response = self._download_json(
+            f'https://chaturbate.{tld}/get_edge_hls_url_ajax/', video_id,
+            data=urlencode_postdata({'room_slug': video_id}),
+            headers={
+                **self.geo_verification_headers(),
+                'X-Requested-With': 'XMLHttpRequest',
+                'Accept': 'application/json',
+            }, fatal=False, impersonate=True) or {}
+
+        status = response.get('room_status')
+        if status != 'public':
+            if error := self._ERROR_MAP.get(status):
+                raise ExtractorError(error, expected=True)
+            self.report_warning('Falling back to webpage extraction')
+            return None
+
+        m3u8_url = response.get('url')
+        if not m3u8_url:
+            self.raise_geo_restricted()
+
+        return {
+            'id': video_id,
+            'title': video_id,
+            'thumbnail': f'https://roomimg.stream.highwebmedia.com/ri/{video_id}.jpg',
+            'is_live': True,
+            'age_limit': 18,
+            'formats': self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4', live=True),
+        }
 
+    def _extract_from_webpage(self, video_id, tld):
         webpage = self._download_webpage(
             f'https://chaturbate.{tld}/{video_id}/', video_id,
-            headers=self.geo_verification_headers())
+            headers=self.geo_verification_headers(), impersonate=True)
 
         found_m3u8_urls = []
 
@@ -85,8 +120,8 @@ def _real_extract(self, url):
                 webpage, 'error', group='error', default=None)
             if not error:
                 if any(p in webpage for p in (
-                        self._ROOM_OFFLINE, 'offline_tipping', 'tip_offline')):
-                    error = self._ROOM_OFFLINE
+                        self._ERROR_MAP['offline'], 'offline_tipping', 'tip_offline')):
+                    error = self._ERROR_MAP['offline']
             if error:
                 raise ExtractorError(error, expected=True)
             raise ExtractorError('Unable to find stream URL')
@@ -113,3 +148,7 @@ def _real_extract(self, url):
             'is_live': True,
             'formats': formats,
         }
+
+    def _real_extract(self, url):
+        video_id, tld = self._match_valid_url(url).group('id', 'tld')
+        return self._extract_from_api(video_id, tld) or self._extract_from_webpage(video_id, tld)


Test patch: