]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/bilibili.py
[extractor/youtube] Fix bug in format sorting
[yt-dlp.git] / yt_dlp / extractor / bilibili.py
CommitLineData
cfcf60ea 1import base64
04b32c8f 2import hashlib
6efb0711 3import itertools
c34f505b 4import functools
520e7533 5import re
c34f505b 6import math
28746fbd 7
06167fbb 8from .common import InfoExtractor, SearchInfoExtractor
bd8f48c7
YCH
9from ..compat import (
10 compat_parse_qs,
11 compat_urlparse,
c34f505b 12 compat_urllib_parse_urlparse
bd8f48c7 13)
28746fbd 14from ..utils import (
bd8f48c7 15 ExtractorError,
f5f15c99 16 filter_dict,
6461f2b7
YCH
17 int_or_none,
18 float_or_none,
f8580bf0 19 mimetype2ext,
bd8f48c7 20 parse_iso8601,
b4f53662 21 qualities,
e88d44c6 22 traverse_obj,
c62ecf0d 23 parse_count,
bd8f48c7 24 smuggle_url,
efc947fb 25 srt_subtitles_timecode,
4bc15a68 26 str_or_none,
bd8f48c7 27 strip_jsonp,
04b32c8f 28 unified_timestamp,
bd8f48c7 29 unsmuggle_url,
1f85029d 30 urlencode_postdata,
c62ecf0d 31 url_or_none,
c34f505b 32 OnDemandPagedList
28746fbd
PH
33)
34
35
36class BiliBiliIE(InfoExtractor):
b4eb08bb
S
37 _VALID_URL = r'''(?x)
38 https?://
39 (?:(?:www|bangumi)\.)?
40 bilibili\.(?:tv|com)/
41 (?:
42 (?:
43 video/[aA][vV]|
44 anime/(?P<anime_id>\d+)/play\#
06167fbb 45 )(?P<id>\d+)|
9536bc07 46 (s/)?video/[bB][vV](?P<id_bv>[^/?#&]+)
b4eb08bb 47 )
06167fbb 48 (?:/?\?p=(?P<page>\d+))?
b4eb08bb 49 '''
28746fbd 50
bd8f48c7 51 _TESTS = [{
06167fbb 52 'url': 'http://www.bilibili.com/video/av1074402/',
89fabf11 53 'md5': '7ac275ec84a99a6552c5d229659a0fe1',
28746fbd 54 'info_dict': {
54bb3906 55 'id': '1074402_part1',
f8580bf0 56 'ext': 'mp4',
28746fbd 57 'title': '【金坷垃】金泡沫',
f8580bf0 58 'uploader_id': '156160',
59 'uploader': '菊子桑',
60 'upload_date': '20140420',
6461f2b7 61 'description': 'md5:ce18c2a2d2193f0df2917d270f2e5923',
3526c304 62 'timestamp': 1398012678,
89fabf11
JN
63 'tags': ['顶上去报复社会', '该来的总会来的', '金克拉是检验歌曲的唯一标准', '坷垃教主', '金坷垃', '邓紫棋', '治愈系坷垃'],
64 'bv_id': 'BV11x411K7CN',
65 'cid': '1554319',
66 'thumbnail': 'http://i2.hdslb.com/bfs/archive/c79a8cf0347cd7a897c53a2f756e96aead128e8c.jpg',
67 'duration': 308.36,
28746fbd 68 },
bd8f48c7
YCH
69 }, {
70 # Tested in BiliBiliBangumiIE
71 'url': 'http://bangumi.bilibili.com/anime/1869/play#40062',
72 'only_matching': True,
06167fbb 73 }, {
74 # bilibili.tv
75 'url': 'http://www.bilibili.tv/video/av1074402/',
76 'only_matching': True,
bd8f48c7
YCH
77 }, {
78 'url': 'http://bangumi.bilibili.com/anime/5802/play#100643',
79 'md5': '3f721ad1e75030cc06faf73587cfec57',
80 'info_dict': {
54bb3906 81 'id': '100643_part1',
bd8f48c7
YCH
82 'ext': 'mp4',
83 'title': 'CHAOS;CHILD',
84 'description': '如果你是神明,并且能够让妄想成为现实。那你会进行怎么样的妄想?是淫靡的世界?独裁社会?毁灭性的制裁?还是……2015年,涩谷。从6年前发生的大灾害“涩谷地震”之后复兴了的这个街区里新设立的私立高中...',
85 },
86 'skip': 'Geo-restricted to China',
ca270371 87 }, {
ca270371
YCH
88 'url': 'http://www.bilibili.com/video/av8903802/',
89 'info_dict': {
54bb3906 90 'id': '8903802_part1',
f8580bf0 91 'ext': 'mp4',
ca270371 92 'title': '阿滴英文|英文歌分享#6 "Closer',
f8580bf0 93 'upload_date': '20170301',
ca270371 94 'description': '滴妹今天唱Closer給你聽! 有史以来,被推最多次也是最久的歌曲,其实歌词跟我原本想像差蛮多的,不过还是好听! 微博@阿滴英文',
f8580bf0 95 'timestamp': 1488382634,
96 'uploader_id': '65880958',
97 'uploader': '阿滴英文',
89fabf11
JN
98 'thumbnail': 'http://i2.hdslb.com/bfs/archive/49267ce20bc246be6304bf369a3ded0256854c23.jpg',
99 'cid': '14694589',
100 'duration': 554.117,
101 'bv_id': 'BV13x41117TL',
102 'tags': ['人文', '英语', '文化', '公开课', '阿滴英文'],
f8580bf0 103 },
104 'params': {
105 'skip_download': True,
ca270371 106 },
b4eb08bb
S
107 }, {
108 # new BV video id format
109 'url': 'https://www.bilibili.com/video/BV1JE411F741',
110 'only_matching': True,
adc74b3c 111 }, {
112 # Anthology
113 'url': 'https://www.bilibili.com/video/BV1bK411W797',
114 'info_dict': {
115 'id': 'BV1bK411W797',
7e60c069 116 'title': '物语中的人物是如何吐槽自己的OP的'
adc74b3c 117 },
118 'playlist_count': 17,
89fabf11
JN
119 }, {
120 # Correct matching of single and double quotes in title
121 'url': 'https://www.bilibili.com/video/BV1NY411E7Rx/',
122 'info_dict': {
123 'id': '255513412_part1',
124 'ext': 'mp4',
125 'title': 'Vid"eo" Te\'st',
126 'cid': '570602418',
127 'thumbnail': 'http://i2.hdslb.com/bfs/archive/0c0de5a90b6d5b991b8dcc6cde0afbf71d564791.jpg',
128 'upload_date': '20220408',
129 'timestamp': 1649436552,
130 'description': 'Vid"eo" Te\'st',
131 'uploader_id': '1630758804',
132 'bv_id': 'BV1NY411E7Rx',
133 'duration': 60.394,
134 'uploader': 'bili_31244483705',
135 'tags': ['VLOG'],
136 },
137 'params': {
138 'skip_download': True,
139 },
bd8f48c7 140 }]
28746fbd 141
c9a0ea6e
S
142 _APP_KEY = 'iVGUTjsxvpLeuDCf'
143 _BILIBILI_KEY = 'aHRmhWMLkdeMuILqORnYZocwMBpMEOdt'
6461f2b7 144
bd8f48c7
YCH
145 def _report_error(self, result):
146 if 'message' in result:
147 raise ExtractorError('%s said: %s' % (self.IE_NAME, result['message']), expected=True)
148 elif 'code' in result:
149 raise ExtractorError('%s returns error %d' % (self.IE_NAME, result['code']), expected=True)
150 else:
151 raise ExtractorError('Can\'t extract Bangumi episode ID')
152
520e7533 153 def _real_extract(self, url):
bd8f48c7
YCH
154 url, smuggled_data = unsmuggle_url(url, {})
155
5ad28e7f 156 mobj = self._match_valid_url(url)
06167fbb 157 video_id = mobj.group('id_bv') or mobj.group('id')
158
159 av_id, bv_id = self._get_video_id_set(video_id, mobj.group('id_bv') is not None)
160 video_id = av_id
161
f8580bf0 162 info = {}
bd8f48c7 163 anime_id = mobj.group('anime_id')
06167fbb 164 page_id = mobj.group('page')
6461f2b7
YCH
165 webpage = self._download_webpage(url, video_id)
166
adc74b3c 167 # Bilibili anthologies are similar to playlists but all videos share the same video ID as the anthology itself.
168 # If the video has no page argument, check to see if it's an anthology
169 if page_id is None:
a06916d9 170 if not self.get_param('noplaylist'):
adc74b3c 171 r = self._extract_anthology_entries(bv_id, video_id, webpage)
172 if r is not None:
173 self.to_screen('Downloading anthology %s - add --no-playlist to just download video' % video_id)
174 return r
7e60c069 175 else:
176 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
adc74b3c 177
bd8f48c7 178 if 'anime/' not in url:
3526c304 179 cid = self._search_regex(
e88d44c6 180 r'\bcid(?:["\']:|=)(\d+),["\']page(?:["\']:|=)' + str(page_id), webpage, 'cid',
06167fbb 181 default=None
182 ) or self._search_regex(
61cb6683 183 r'\bcid(?:["\']:|=)(\d+)', webpage, 'cid',
3526c304
S
184 default=None
185 ) or compat_parse_qs(self._search_regex(
95a1322b
S
186 [r'EmbedPlayer\([^)]+,\s*"([^"]+)"\)',
187 r'EmbedPlayer\([^)]+,\s*\\"([^"]+)\\"\)',
188 r'<iframe[^>]+src="https://secure\.bilibili\.com/secure,([^"]+)"'],
7be15d40
P
189 webpage, 'player parameters'))['cid'][0]
190 else:
bd8f48c7 191 if 'no_bangumi_tip' not in smuggled_data:
7a5c1cfe 192 self.to_screen('Downloading episode %s. To download all videos in anime %s, re-run yt-dlp with %s' % (
bd8f48c7 193 video_id, anime_id, compat_urlparse.urljoin(url, '//bangumi.bilibili.com/anime/%s' % anime_id)))
10db0d2f 194 headers = {
195 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
196 'Referer': url
197 }
198 headers.update(self.geo_verification_headers())
bd8f48c7 199
1f85029d
YCH
200 js = self._download_json(
201 'http://bangumi.bilibili.com/web_api/get_source', video_id,
202 data=urlencode_postdata({'episode_id': video_id}),
bd8f48c7
YCH
203 headers=headers)
204 if 'result' not in js:
205 self._report_error(js)
7be15d40 206 cid = js['result']['cid']
04b32c8f 207
10db0d2f 208 headers = {
209 'Accept': 'application/json',
210 'Referer': url
211 }
212 headers.update(self.geo_verification_headers())
213
f8580bf0 214 video_info = self._parse_json(
54bb3906 215 self._search_regex(r'window.__playinfo__\s*=\s*({.+?})</script>', webpage, 'video info', default=None) or '{}',
216 video_id, fatal=False)
f8580bf0 217 video_info = video_info.get('data') or {}
218
219 durl = traverse_obj(video_info, ('dash', 'video'))
220 audios = traverse_obj(video_info, ('dash', 'audio')) or []
d90e4030 221 entries = []
c4a21bc9 222
3526c304
S
223 RENDITIONS = ('qn=80&quality=80&type=', 'quality=2&type=mp4')
224 for num, rendition in enumerate(RENDITIONS, start=1):
225 payload = 'appkey=%s&cid=%s&otype=json&%s' % (self._APP_KEY, cid, rendition)
226 sign = hashlib.md5((payload + self._BILIBILI_KEY).encode('utf-8')).hexdigest()
3526c304 227 if not video_info:
f8580bf0 228 video_info = self._download_json(
229 'http://interface.bilibili.com/v2/playurl?%s&sign=%s' % (payload, sign),
230 video_id, note='Downloading video info page',
231 headers=headers, fatal=num == len(RENDITIONS))
232 if not video_info:
233 continue
3526c304 234
f8580bf0 235 if not durl and 'durl' not in video_info:
3526c304
S
236 if num < len(RENDITIONS):
237 continue
238 self._report_error(video_info)
239
f8580bf0 240 formats = []
241 for idx, durl in enumerate(durl or video_info['durl']):
242 formats.append({
243 'url': durl.get('baseUrl') or durl.get('base_url') or durl.get('url'),
244 'ext': mimetype2ext(durl.get('mimeType') or durl.get('mime_type')),
245 'fps': int_or_none(durl.get('frameRate') or durl.get('frame_rate')),
246 'width': int_or_none(durl.get('width')),
247 'height': int_or_none(durl.get('height')),
248 'vcodec': durl.get('codecs'),
249 'acodec': 'none' if audios else None,
250 'tbr': float_or_none(durl.get('bandwidth'), scale=1000),
251 'filesize': int_or_none(durl.get('size')),
252 })
253 for backup_url in traverse_obj(durl, 'backup_url', expected_type=list) or []:
3526c304
S
254 formats.append({
255 'url': backup_url,
f983b875 256 'quality': -2 if 'hd.mp4' in backup_url else -3,
3526c304
S
257 })
258
f8580bf0 259 for audio in audios:
260 formats.append({
261 'url': audio.get('baseUrl') or audio.get('base_url') or audio.get('url'),
262 'ext': mimetype2ext(audio.get('mimeType') or audio.get('mime_type')),
263 'fps': int_or_none(audio.get('frameRate') or audio.get('frame_rate')),
264 'width': int_or_none(audio.get('width')),
265 'height': int_or_none(audio.get('height')),
266 'acodec': audio.get('codecs'),
267 'vcodec': 'none',
268 'tbr': float_or_none(audio.get('bandwidth'), scale=1000),
269 'filesize': int_or_none(audio.get('size'))
6461f2b7 270 })
f8580bf0 271 for backup_url in traverse_obj(audio, 'backup_url', expected_type=list) or []:
272 formats.append({
273 'url': backup_url,
274 # backup URLs have lower priorities
275 'quality': -3,
276 })
277
278 info.update({
279 'id': video_id,
280 'duration': float_or_none(durl.get('length'), 1000),
281 'formats': formats,
be8d6234
DZ
282 'http_headers': {
283 'Referer': url,
284 },
f8580bf0 285 })
3526c304 286 break
6461f2b7 287
f8580bf0 288 self._sort_formats(formats)
289
54bb3906 290 title = self._html_search_regex((
89fabf11
JN
291 r'<h1[^>]+title=(["])(?P<content>[^"]+)',
292 r'<h1[^>]+title=([\'])(?P<content>[^\']+)',
54bb3906 293 r'(?s)<h1[^>]*>(?P<content>.+?)</h1>',
294 self._meta_regex('title')
295 ), webpage, 'title', group='content', fatal=False)
adc74b3c 296
297 # Get part title for anthologies
298 if page_id is not None:
f8580bf0 299 # TODO: The json is already downloaded by _extract_anthology_entries. Don't redownload for each video.
300 part_info = traverse_obj(self._download_json(
301 f'https://api.bilibili.com/x/player/pagelist?bvid={bv_id}&jsonp=jsonp',
302 video_id, note='Extracting videos in anthology'), 'data', expected_type=list)
303 title = title if len(part_info) == 1 else traverse_obj(part_info, (int(page_id) - 1, 'part')) or title
adc74b3c 304
6461f2b7 305 description = self._html_search_meta('description', webpage)
04b32c8f 306 timestamp = unified_timestamp(self._html_search_regex(
3526c304
S
307 r'<time[^>]+datetime="([^"]+)"', webpage, 'upload time',
308 default=None) or self._html_search_meta(
309 'uploadDate', webpage, 'timestamp', default=None))
1f85029d 310 thumbnail = self._html_search_meta(['og:image', 'thumbnailUrl'], webpage)
6461f2b7
YCH
311
312 # TODO 'view_count' requires deobfuscating Javascript
f8580bf0 313 info.update({
54bb3906 314 'id': f'{video_id}_part{page_id or 1}',
06167fbb 315 'cid': cid,
d90e4030 316 'title': title,
6461f2b7
YCH
317 'description': description,
318 'timestamp': timestamp,
7be15d40 319 'thumbnail': thumbnail,
04b32c8f 320 'duration': float_or_none(video_info.get('timelength'), scale=1000),
f8580bf0 321 })
d90e4030 322
6461f2b7 323 uploader_mobj = re.search(
7e60c069 324 r'<a[^>]+href="(?:https?:)?//space\.bilibili\.com/(?P<id>\d+)"[^>]*>\s*(?P<name>[^<]+?)\s*<',
6461f2b7
YCH
325 webpage)
326 if uploader_mobj:
327 info.update({
ed807c18 328 'uploader': uploader_mobj.group('name').strip(),
6461f2b7
YCH
329 'uploader_id': uploader_mobj.group('id'),
330 })
06167fbb 331
3526c304
S
332 if not info.get('uploader'):
333 info['uploader'] = self._html_search_meta(
334 'author', webpage, 'uploader', default=None)
6461f2b7 335
06167fbb 336 top_level_info = {
e88d44c6 337 'tags': traverse_obj(self._download_json(
338 f'https://api.bilibili.com/x/tag/archive/tags?aid={video_id}',
339 video_id, fatal=False, note='Downloading tags'), ('data', ..., 'tag_name')),
06167fbb 340 }
277d6ff5 341
f8580bf0 342 info['subtitles'] = {
e88d44c6 343 'danmaku': [{
344 'ext': 'xml',
345 'url': f'https://comment.bilibili.com/{cid}.xml',
346 }]
347 }
06167fbb 348
e88d44c6 349 r'''
06167fbb 350 # Requires https://github.com/m13253/danmaku2ass which is licenced under GPL3
351 # See https://github.com/animelover1984/youtube-dl
e88d44c6 352
353 raw_danmaku = self._download_webpage(
354 f'https://comment.bilibili.com/{cid}.xml', video_id, fatal=False, note='Downloading danmaku comments')
06167fbb 355 danmaku = NiconicoIE.CreateDanmaku(raw_danmaku, commentType='Bilibili', x=1024, y=576)
356 entries[0]['subtitles'] = {
357 'danmaku': [{
358 'ext': 'ass',
359 'data': danmaku
360 }]
361 }
362 '''
363
e88d44c6 364 top_level_info['__post_extractor'] = self.extract_comments(video_id)
365
6461f2b7
YCH
366 for entry in entries:
367 entry.update(info)
368
d90e4030 369 if len(entries) == 1:
06167fbb 370 entries[0].update(top_level_info)
d90e4030 371 return entries[0]
bd8f48c7 372
e88d44c6 373 for idx, entry in enumerate(entries):
374 entry['id'] = '%s_part%d' % (video_id, (idx + 1))
06167fbb 375
e88d44c6 376 return {
e88d44c6 377 'id': str(video_id),
378 'bv_id': bv_id,
379 'title': title,
380 'description': description,
e88d44c6 381 **info, **top_level_info
382 }
06167fbb 383
adc74b3c 384 def _extract_anthology_entries(self, bv_id, video_id, webpage):
385 title = self._html_search_regex(
386 (r'<h1[^>]+\btitle=(["\'])(?P<title>(?:(?!\1).)+)\1',
ac0efabf 387 r'(?s)<h1[^>]*>(?P<title>.+?)</h1>',
388 r'<title>(?P<title>.+?)</title>'), webpage, 'title',
adc74b3c 389 group='title')
390 json_data = self._download_json(
e88d44c6 391 f'https://api.bilibili.com/x/player/pagelist?bvid={bv_id}&jsonp=jsonp',
adc74b3c 392 video_id, note='Extracting videos in anthology')
393
e88d44c6 394 if json_data['data']:
adc74b3c 395 return self.playlist_from_matches(
396 json_data['data'], bv_id, title, ie=BiliBiliIE.ie_key(),
397 getter=lambda entry: 'https://www.bilibili.com/video/%s?p=%d' % (bv_id, entry['page']))
398
06167fbb 399 def _get_video_id_set(self, id, is_bv):
400 query = {'bvid': id} if is_bv else {'aid': id}
401 response = self._download_json(
402 "http://api.bilibili.cn/x/web-interface/view",
403 id, query=query,
404 note='Grabbing original ID via API')
405
406 if response['code'] == -400:
407 raise ExtractorError('Video ID does not exist', expected=True, video_id=id)
408 elif response['code'] != 0:
e88d44c6 409 raise ExtractorError(f'Unknown error occurred during API check (code {response["code"]})',
410 expected=True, video_id=id)
411 return response['data']['aid'], response['data']['bvid']
06167fbb 412
e88d44c6 413 def _get_comments(self, video_id, commentPageNumber=0):
414 for idx in itertools.count(1):
415 replies = traverse_obj(
416 self._download_json(
417 f'https://api.bilibili.com/x/v2/reply?pn={idx}&oid={video_id}&type=1&jsonp=jsonp&sort=2&_=1567227301685',
8e7ab2cf 418 video_id, note=f'Extracting comments from page {idx}', fatal=False),
419 ('data', 'replies'))
420 if not replies:
421 return
e88d44c6 422 for children in map(self._get_all_children, replies):
423 yield from children
424
425 def _get_all_children(self, reply):
426 yield {
427 'author': traverse_obj(reply, ('member', 'uname')),
428 'author_id': traverse_obj(reply, ('member', 'mid')),
429 'id': reply.get('rpid'),
430 'text': traverse_obj(reply, ('content', 'message')),
431 'timestamp': reply.get('ctime'),
432 'parent': reply.get('parent') or 'root',
433 }
434 for children in map(self._get_all_children, reply.get('replies') or []):
435 yield from children
06167fbb 436
bd8f48c7
YCH
437
438class BiliBiliBangumiIE(InfoExtractor):
439 _VALID_URL = r'https?://bangumi\.bilibili\.com/anime/(?P<id>\d+)'
440
441 IE_NAME = 'bangumi.bilibili.com'
442 IE_DESC = 'BiliBili番剧'
443
444 _TESTS = [{
445 'url': 'http://bangumi.bilibili.com/anime/1869',
446 'info_dict': {
447 'id': '1869',
448 'title': '混沌武士',
449 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
450 },
451 'playlist_count': 26,
452 }, {
453 'url': 'http://bangumi.bilibili.com/anime/1869',
454 'info_dict': {
455 'id': '1869',
456 'title': '混沌武士',
457 'description': 'md5:6a9622b911565794c11f25f81d6a97d2',
458 },
459 'playlist': [{
460 'md5': '91da8621454dd58316851c27c68b0c13',
461 'info_dict': {
462 'id': '40062',
463 'ext': 'mp4',
464 'title': '混沌武士',
465 'description': '故事发生在日本的江户时代。风是一个小酒馆的打工女。一日,酒馆里来了一群恶霸,虽然他们的举动令风十分不满,但是毕竟风只是一届女流,无法对他们采取什么行动,只能在心里嘟哝。这时,酒家里又进来了个“不良份子...',
466 'timestamp': 1414538739,
467 'upload_date': '20141028',
468 'episode': '疾风怒涛 Tempestuous Temperaments',
469 'episode_number': 1,
470 },
471 }],
472 'params': {
473 'playlist_items': '1',
474 },
475 }]
476
477 @classmethod
478 def suitable(cls, url):
479 return False if BiliBiliIE.suitable(url) else super(BiliBiliBangumiIE, cls).suitable(url)
480
481 def _real_extract(self, url):
482 bangumi_id = self._match_id(url)
483
484 # Sometimes this API returns a JSONP response
485 season_info = self._download_json(
486 'http://bangumi.bilibili.com/jsonp/seasoninfo/%s.ver' % bangumi_id,
487 bangumi_id, transform_source=strip_jsonp)['result']
488
489 entries = [{
490 '_type': 'url_transparent',
491 'url': smuggle_url(episode['webplay_url'], {'no_bangumi_tip': 1}),
492 'ie_key': BiliBiliIE.ie_key(),
493 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '),
494 'episode': episode.get('index_title'),
495 'episode_number': int_or_none(episode.get('index')),
496 } for episode in season_info['episodes']]
497
498 entries = sorted(entries, key=lambda entry: entry.get('episode_number'))
499
500 return self.playlist_result(
501 entries, bangumi_id,
502 season_info.get('bangumi_title'), season_info.get('evaluate'))
4bc15a68
RA
503
504
06167fbb 505class BilibiliChannelIE(InfoExtractor):
506 _VALID_URL = r'https?://space.bilibili\.com/(?P<id>\d+)'
6efb0711 507 _API_URL = "https://api.bilibili.com/x/space/arc/search?mid=%s&pn=%d&jsonp=jsonp"
508 _TESTS = [{
509 'url': 'https://space.bilibili.com/3985676/video',
510 'info_dict': {},
511 'playlist_mincount': 112,
512 }]
513
514 def _entries(self, list_id):
515 count, max_count = 0, None
516
517 for page_num in itertools.count(1):
e88d44c6 518 data = self._download_json(
519 self._API_URL % (list_id, page_num), list_id, note=f'Downloading page {page_num}')['data']
6efb0711 520
f8580bf0 521 max_count = max_count or traverse_obj(data, ('page', 'count'))
6efb0711 522
f8580bf0 523 entries = traverse_obj(data, ('list', 'vlist'))
6efb0711 524 if not entries:
525 return
526 for entry in entries:
527 yield self.url_result(
528 'https://www.bilibili.com/video/%s' % entry['bvid'],
529 BiliBiliIE.ie_key(), entry['bvid'])
530
531 count += len(entries)
532 if max_count and count >= max_count:
533 return
06167fbb 534
535 def _real_extract(self, url):
536 list_id = self._match_id(url)
6efb0711 537 return self.playlist_result(self._entries(list_id), list_id)
06167fbb 538
539
c34f505b 540class BilibiliCategoryIE(InfoExtractor):
541 IE_NAME = 'Bilibili category extractor'
542 _MAX_RESULTS = 1000000
543 _VALID_URL = r'https?://www\.bilibili\.com/v/[a-zA-Z]+\/[a-zA-Z]+'
544 _TESTS = [{
545 'url': 'https://www.bilibili.com/v/kichiku/mad',
546 'info_dict': {
547 'id': 'kichiku: mad',
548 'title': 'kichiku: mad'
549 },
550 'playlist_mincount': 45,
551 'params': {
552 'playlistend': 45
553 }
554 }]
555
556 def _fetch_page(self, api_url, num_pages, query, page_num):
557 parsed_json = self._download_json(
558 api_url, query, query={'Search_key': query, 'pn': page_num},
559 note='Extracting results from page %s of %s' % (page_num, num_pages))
560
f8580bf0 561 video_list = traverse_obj(parsed_json, ('data', 'archives'), expected_type=list)
c34f505b 562 if not video_list:
563 raise ExtractorError('Failed to retrieve video list for page %d' % page_num)
564
565 for video in video_list:
566 yield self.url_result(
567 'https://www.bilibili.com/video/%s' % video['bvid'], 'BiliBili', video['bvid'])
568
569 def _entries(self, category, subcategory, query):
570 # map of categories : subcategories : RIDs
571 rid_map = {
572 'kichiku': {
573 'mad': 26,
574 'manual_vocaloid': 126,
575 'guide': 22,
576 'theatre': 216,
577 'course': 127
578 },
579 }
580
581 if category not in rid_map:
e88d44c6 582 raise ExtractorError(
583 f'The category {category} isn\'t supported. Supported categories: {list(rid_map.keys())}')
c34f505b 584 if subcategory not in rid_map[category]:
e88d44c6 585 raise ExtractorError(
586 f'The subcategory {subcategory} isn\'t supported for this category. Supported subcategories: {list(rid_map[category].keys())}')
c34f505b 587 rid_value = rid_map[category][subcategory]
588
589 api_url = 'https://api.bilibili.com/x/web-interface/newlist?rid=%d&type=1&ps=20&jsonp=jsonp' % rid_value
590 page_json = self._download_json(api_url, query, query={'Search_key': query, 'pn': '1'})
f8580bf0 591 page_data = traverse_obj(page_json, ('data', 'page'), expected_type=dict)
c34f505b 592 count, size = int_or_none(page_data.get('count')), int_or_none(page_data.get('size'))
593 if count is None or not size:
594 raise ExtractorError('Failed to calculate either page count or size')
595
596 num_pages = math.ceil(count / size)
597
598 return OnDemandPagedList(functools.partial(
599 self._fetch_page, api_url, num_pages, query), size)
600
601 def _real_extract(self, url):
602 u = compat_urllib_parse_urlparse(url)
603 category, subcategory = u.path.split('/')[2:4]
604 query = '%s: %s' % (category, subcategory)
605
606 return self.playlist_result(self._entries(category, subcategory, query), query, query)
607
608
06167fbb 609class BiliBiliSearchIE(SearchInfoExtractor):
96565c7e 610 IE_DESC = 'Bilibili video search'
06167fbb 611 _MAX_RESULTS = 100000
612 _SEARCH_KEY = 'bilisearch'
06167fbb 613
e88d44c6 614 def _search_results(self, query):
615 for page_num in itertools.count(1):
616 videos = self._download_json(
617 'https://api.bilibili.com/x/web-interface/search/type', query,
618 note=f'Extracting results from page {page_num}', query={
619 'Search_key': query,
620 'keyword': query,
621 'page': page_num,
622 'context': '',
623 'order': 'pubdate',
624 'duration': 0,
625 'tids_2': '',
626 '__refresh__': 'true',
627 'search_type': 'video',
628 'tids': 0,
629 'highlight': 1,
630 })['data'].get('result') or []
06167fbb 631 for video in videos:
e88d44c6 632 yield self.url_result(video['arcurl'], 'BiliBili', str(video['aid']))
06167fbb 633
634
4bc15a68
RA
635class BilibiliAudioBaseIE(InfoExtractor):
636 def _call_api(self, path, sid, query=None):
637 if not query:
638 query = {'sid': sid}
639 return self._download_json(
640 'https://www.bilibili.com/audio/music-service-c/web/' + path,
641 sid, query=query)['data']
642
643
644class BilibiliAudioIE(BilibiliAudioBaseIE):
645 _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/au(?P<id>\d+)'
646 _TEST = {
647 'url': 'https://www.bilibili.com/audio/au1003142',
648 'md5': 'fec4987014ec94ef9e666d4d158ad03b',
649 'info_dict': {
650 'id': '1003142',
651 'ext': 'm4a',
652 'title': '【tsukimi】YELLOW / 神山羊',
653 'artist': 'tsukimi',
654 'comment_count': int,
655 'description': 'YELLOW的mp3版!',
656 'duration': 183,
657 'subtitles': {
658 'origin': [{
659 'ext': 'lrc',
660 }],
661 },
662 'thumbnail': r're:^https?://.+\.jpg',
663 'timestamp': 1564836614,
664 'upload_date': '20190803',
665 'uploader': 'tsukimi-つきみぐー',
666 'view_count': int,
667 },
668 }
669
670 def _real_extract(self, url):
671 au_id = self._match_id(url)
672
673 play_data = self._call_api('url', au_id)
674 formats = [{
675 'url': play_data['cdns'][0],
676 'filesize': int_or_none(play_data.get('size')),
f0884c8b 677 'vcodec': 'none'
4bc15a68
RA
678 }]
679
6d1b3489 680 for a_format in formats:
681 a_format.setdefault('http_headers', {}).update({
682 'Referer': url,
683 })
684
4bc15a68
RA
685 song = self._call_api('song/info', au_id)
686 title = song['title']
687 statistic = song.get('statistic') or {}
688
689 subtitles = None
690 lyric = song.get('lyric')
691 if lyric:
692 subtitles = {
693 'origin': [{
694 'url': lyric,
695 }]
696 }
697
698 return {
699 'id': au_id,
700 'title': title,
701 'formats': formats,
702 'artist': song.get('author'),
703 'comment_count': int_or_none(statistic.get('comment')),
704 'description': song.get('intro'),
705 'duration': int_or_none(song.get('duration')),
706 'subtitles': subtitles,
707 'thumbnail': song.get('cover'),
708 'timestamp': int_or_none(song.get('passtime')),
709 'uploader': song.get('uname'),
710 'view_count': int_or_none(statistic.get('play')),
711 }
712
713
714class BilibiliAudioAlbumIE(BilibiliAudioBaseIE):
715 _VALID_URL = r'https?://(?:www\.)?bilibili\.com/audio/am(?P<id>\d+)'
716 _TEST = {
717 'url': 'https://www.bilibili.com/audio/am10624',
718 'info_dict': {
719 'id': '10624',
720 'title': '每日新曲推荐(每日11:00更新)',
721 'description': '每天11:00更新,为你推送最新音乐',
722 },
723 'playlist_count': 19,
724 }
725
726 def _real_extract(self, url):
727 am_id = self._match_id(url)
728
729 songs = self._call_api(
730 'song/of-menu', am_id, {'sid': am_id, 'pn': 1, 'ps': 100})['data']
731
732 entries = []
733 for song in songs:
734 sid = str_or_none(song.get('id'))
735 if not sid:
736 continue
737 entries.append(self.url_result(
738 'https://www.bilibili.com/audio/au' + sid,
739 BilibiliAudioIE.ie_key(), sid))
740
741 if entries:
742 album_data = self._call_api('menu/info', am_id) or {}
743 album_title = album_data.get('title')
744 if album_title:
745 for entry in entries:
746 entry['album'] = album_title
747 return self.playlist_result(
748 entries, am_id, album_title, album_data.get('intro'))
749
750 return self.playlist_result(entries, am_id)
63dce309
S
751
752
753class BiliBiliPlayerIE(InfoExtractor):
754 _VALID_URL = r'https?://player\.bilibili\.com/player\.html\?.*?\baid=(?P<id>\d+)'
755 _TEST = {
756 'url': 'http://player.bilibili.com/player.html?aid=92494333&cid=157926707&page=1',
757 'only_matching': True,
758 }
759
760 def _real_extract(self, url):
761 video_id = self._match_id(url)
762 return self.url_result(
763 'http://www.bilibili.tv/video/av%s/' % video_id,
764 ie=BiliBiliIE.ie_key(), video_id=video_id)
16f7e6be
AG
765
766
767class BiliIntlBaseIE(InfoExtractor):
c62ecf0d 768 _API_URL = 'https://api.bilibili.tv/intl/gateway'
cfcf60ea 769 _NETRC_MACHINE = 'biliintl'
16f7e6be 770
c62ecf0d 771 def _call_api(self, endpoint, *args, **kwargs):
cfcf60ea
M
772 json = self._download_json(self._API_URL + endpoint, *args, **kwargs)
773 if json.get('code'):
774 if json['code'] in (10004004, 10004005, 10023006):
775 self.raise_login_required()
776 elif json['code'] == 10004001:
777 self.raise_geo_restricted()
778 else:
779 if json.get('message') and str(json['code']) != json['message']:
780 errmsg = f'{kwargs.get("errnote", "Unable to download JSON metadata")}: {self.IE_NAME} said: {json["message"]}'
781 else:
782 errmsg = kwargs.get('errnote', 'Unable to download JSON metadata')
783 if kwargs.get('fatal'):
784 raise ExtractorError(errmsg)
785 else:
786 self.report_warning(errmsg)
787 return json.get('data')
16f7e6be 788
efc947fb 789 def json2srt(self, json):
790 data = '\n\n'.join(
791 f'{i + 1}\n{srt_subtitles_timecode(line["from"])} --> {srt_subtitles_timecode(line["to"])}\n{line["content"]}'
dfb855b4 792 for i, line in enumerate(traverse_obj(json, (
793 'body', lambda _, l: l['content'] and l['from'] and l['to']))))
efc947fb 794 return data
795
f5f15c99
LR
796 def _get_subtitles(self, *, ep_id=None, aid=None):
797 sub_json = self._call_api(
fbb888a3 798 '/web/v2/subtitle', ep_id or aid, fatal=False,
799 note='Downloading subtitles list', errnote='Unable to download subtitles list',
800 query=filter_dict({
f5f15c99 801 'platform': 'web',
fbb888a3 802 's_locale': 'en_US',
f5f15c99
LR
803 'episode_id': ep_id,
804 'aid': aid,
fbb888a3 805 })) or {}
16f7e6be 806 subtitles = {}
c62ecf0d 807 for sub in sub_json.get('subtitles') or []:
16f7e6be
AG
808 sub_url = sub.get('url')
809 if not sub_url:
810 continue
c62ecf0d 811 sub_data = self._download_json(
f5f15c99 812 sub_url, ep_id or aid, errnote='Unable to download subtitles', fatal=False,
c62ecf0d 813 note='Downloading subtitles%s' % f' for {sub["lang"]}' if sub.get('lang') else '')
efc947fb 814 if not sub_data:
815 continue
c62ecf0d 816 subtitles.setdefault(sub.get('lang_key', 'en'), []).append({
efc947fb 817 'ext': 'srt',
818 'data': self.json2srt(sub_data)
16f7e6be
AG
819 })
820 return subtitles
821
f5f15c99
LR
822 def _get_formats(self, *, ep_id=None, aid=None):
823 video_json = self._call_api(
824 '/web/playurl', ep_id or aid, note='Downloading video formats',
825 errnote='Unable to download video formats', query=filter_dict({
826 'platform': 'web',
827 'ep_id': ep_id,
828 'aid': aid,
829 }))
16f7e6be
AG
830 video_json = video_json['playurl']
831 formats = []
c62ecf0d 832 for vid in video_json.get('video') or []:
16f7e6be
AG
833 video_res = vid.get('video_resource') or {}
834 video_info = vid.get('stream_info') or {}
835 if not video_res.get('url'):
836 continue
837 formats.append({
838 'url': video_res['url'],
839 'ext': 'mp4',
840 'format_note': video_info.get('desc_words'),
841 'width': video_res.get('width'),
842 'height': video_res.get('height'),
843 'vbr': video_res.get('bandwidth'),
844 'acodec': 'none',
845 'vcodec': video_res.get('codecs'),
846 'filesize': video_res.get('size'),
847 })
c62ecf0d 848 for aud in video_json.get('audio_resource') or []:
16f7e6be
AG
849 if not aud.get('url'):
850 continue
851 formats.append({
852 'url': aud['url'],
853 'ext': 'mp4',
854 'abr': aud.get('bandwidth'),
855 'acodec': aud.get('codecs'),
856 'vcodec': 'none',
857 'filesize': aud.get('size'),
858 })
859
860 self._sort_formats(formats)
861 return formats
862
f5f15c99 863 def _extract_video_info(self, video_data, *, ep_id=None, aid=None):
16f7e6be 864 return {
f5f15c99
LR
865 'id': ep_id or aid,
866 'title': video_data.get('title_display') or video_data.get('title'),
867 'thumbnail': video_data.get('cover'),
c62ecf0d 868 'episode_number': int_or_none(self._search_regex(
f5f15c99
LR
869 r'^E(\d+)(?:$| - )', video_data.get('title_display') or '', 'episode number', default=None)),
870 'formats': self._get_formats(ep_id=ep_id, aid=aid),
871 'subtitles': self._get_subtitles(ep_id=ep_id, aid=aid),
16f7e6be
AG
872 'extractor_key': BiliIntlIE.ie_key(),
873 }
874
52efa4b3 875 def _perform_login(self, username, password):
cfcf60ea
M
876 try:
877 from Cryptodome.PublicKey import RSA
878 from Cryptodome.Cipher import PKCS1_v1_5
879 except ImportError:
880 try:
881 from Crypto.PublicKey import RSA
882 from Crypto.Cipher import PKCS1_v1_5
883 except ImportError:
884 raise ExtractorError('pycryptodomex not found. Please install', expected=True)
885
886 key_data = self._download_json(
887 'https://passport.bilibili.tv/x/intl/passport-login/web/key?lang=en-US', None,
888 note='Downloading login key', errnote='Unable to download login key')['data']
889
890 public_key = RSA.importKey(key_data['key'])
891 password_hash = PKCS1_v1_5.new(public_key).encrypt((key_data['hash'] + password).encode('utf-8'))
892 login_post = self._download_json(
893 'https://passport.bilibili.tv/x/intl/passport-login/web/login/password?lang=en-US', None, data=urlencode_postdata({
894 'username': username,
895 'password': base64.b64encode(password_hash).decode('ascii'),
896 'keep_me': 'true',
897 's_locale': 'en_US',
898 'isTrusted': 'true'
899 }), note='Logging in', errnote='Unable to log in')
900 if login_post.get('code'):
901 if login_post.get('message'):
902 raise ExtractorError(f'Unable to log in: {self.IE_NAME} said: {login_post["message"]}', expected=True)
903 else:
904 raise ExtractorError('Unable to log in')
905
16f7e6be
AG
906
907class BiliIntlIE(BiliIntlBaseIE):
f5f15c99 908 _VALID_URL = r'https?://(?:www\.)?bili(?:bili\.tv|intl\.com)/(?:[a-z]{2}/)?(play/(?P<season_id>\d+)/(?P<ep_id>\d+)|video/(?P<aid>\d+))'
16f7e6be 909 _TESTS = [{
cfcf60ea 910 # Bstation page
16f7e6be
AG
911 'url': 'https://www.bilibili.tv/en/play/34613/341736',
912 'info_dict': {
913 'id': '341736',
914 'ext': 'mp4',
c62ecf0d
M
915 'title': 'E2 - The First Night',
916 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$',
16f7e6be 917 'episode_number': 2,
c62ecf0d 918 }
16f7e6be 919 }, {
cfcf60ea 920 # Non-Bstation page
c62ecf0d 921 'url': 'https://www.bilibili.tv/en/play/1033760/11005006',
16f7e6be 922 'info_dict': {
c62ecf0d 923 'id': '11005006',
16f7e6be 924 'ext': 'mp4',
c62ecf0d
M
925 'title': 'E3 - Who?',
926 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$',
927 'episode_number': 3,
928 }
cfcf60ea
M
929 }, {
930 # Subtitle with empty content
931 'url': 'https://www.bilibili.tv/en/play/1005144/10131790',
932 'info_dict': {
933 'id': '10131790',
934 'ext': 'mp4',
935 'title': 'E140 - Two Heartbeats: Kabuto\'s Trap',
936 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$',
937 'episode_number': 140,
938 },
939 'skip': 'According to the copyright owner\'s request, you may only watch the video after you log in.'
c62ecf0d
M
940 }, {
941 'url': 'https://www.biliintl.com/en/play/34613/341736',
942 'only_matching': True,
f5f15c99
LR
943 }, {
944 # User-generated content (as opposed to a series licensed from a studio)
945 'url': 'https://bilibili.tv/en/video/2019955076',
946 'only_matching': True,
947 }, {
948 # No language in URL
949 'url': 'https://www.bilibili.tv/video/2019955076',
950 'only_matching': True,
16f7e6be
AG
951 }]
952
953 def _real_extract(self, url):
f5f15c99
LR
954 season_id, ep_id, aid = self._match_valid_url(url).group('season_id', 'ep_id', 'aid')
955 video_id = ep_id or aid
c62ecf0d
M
956 webpage = self._download_webpage(url, video_id)
957 # Bstation layout
8072ef2b 958 initial_data = (
959 self._search_json(r'window\.__INITIAL_(?:DATA|STATE)__\s*=', webpage, 'preload state', video_id, default={})
960 or self._search_nuxt_data(webpage, video_id, '__initialState', fatal=False, traverse=None))
961 video_data = traverse_obj(
962 initial_data, ('OgvVideo', 'epDetail'), ('UgcVideo', 'videoData'), ('ugc', 'archive'), expected_type=dict)
c62ecf0d 963
f5f15c99 964 if season_id and not video_data:
c62ecf0d
M
965 # Non-Bstation layout, read through episode list
966 season_json = self._call_api(f'/web/v2/ogv/play/episodes?season_id={season_id}&platform=web', video_id)
a44ca5a4 967 video_data = traverse_obj(season_json,
968 ('sections', ..., 'episodes', lambda _, v: str(v['episode_id']) == ep_id),
969 expected_type=dict, get_all=False)
8072ef2b 970 return self._extract_video_info(video_data or {}, ep_id=ep_id, aid=aid)
16f7e6be
AG
971
972
973class BiliIntlSeriesIE(BiliIntlBaseIE):
c62ecf0d 974 _VALID_URL = r'https?://(?:www\.)?bili(?:bili\.tv|intl\.com)/(?:[a-z]{2}/)?play/(?P<id>\d+)$'
16f7e6be
AG
975 _TESTS = [{
976 'url': 'https://www.bilibili.tv/en/play/34613',
977 'playlist_mincount': 15,
978 'info_dict': {
979 'id': '34613',
c62ecf0d
M
980 'title': 'Fly Me to the Moon',
981 'description': 'md5:a861ee1c4dc0acfad85f557cc42ac627',
982 'categories': ['Romance', 'Comedy', 'Slice of life'],
983 'thumbnail': r're:^https://pic\.bstarstatic\.com/ogv/.+\.png$',
984 'view_count': int,
16f7e6be
AG
985 },
986 'params': {
987 'skip_download': True,
16f7e6be
AG
988 },
989 }, {
990 'url': 'https://www.biliintl.com/en/play/34613',
c62ecf0d 991 'only_matching': True,
16f7e6be
AG
992 }]
993
c62ecf0d
M
994 def _entries(self, series_id):
995 series_json = self._call_api(f'/web/v2/ogv/play/episodes?season_id={series_id}&platform=web', series_id)
996 for episode in traverse_obj(series_json, ('sections', ..., 'episodes', ...), expected_type=dict, default=[]):
997 episode_id = str(episode.get('episode_id'))
f5f15c99 998 yield self._extract_video_info(episode, ep_id=episode_id)
16f7e6be
AG
999
1000 def _real_extract(self, url):
c62ecf0d
M
1001 series_id = self._match_id(url)
1002 series_info = self._call_api(f'/web/v2/ogv/play/season_info?season_id={series_id}&platform=web', series_id).get('season') or {}
1003 return self.playlist_result(
1004 self._entries(series_id), series_id, series_info.get('title'), series_info.get('description'),
1005 categories=traverse_obj(series_info, ('styles', ..., 'title'), expected_type=str_or_none),
1006 thumbnail=url_or_none(series_info.get('horizontal_cover')), view_count=parse_count(series_info.get('view')))
b4f53662
H
1007
1008
1009class BiliLiveIE(InfoExtractor):
1010 _VALID_URL = r'https?://live.bilibili.com/(?P<id>\d+)'
1011
1012 _TESTS = [{
1013 'url': 'https://live.bilibili.com/196',
1014 'info_dict': {
1015 'id': '33989',
1016 'description': "周六杂谈回,其他时候随机游戏。 | \n录播:@下播型泛式录播组。 | \n直播通知群(全员禁言):666906670,902092584,59971⑧481 (功能一样,别多加)",
1017 'ext': 'flv',
1018 'title': "太空狼人杀联动,不被爆杀就算赢",
1019 'thumbnail': "https://i0.hdslb.com/bfs/live/new_room_cover/e607bc1529057ef4b332e1026e62cf46984c314d.jpg",
1020 'timestamp': 1650802769,
1021 },
1022 'skip': 'not live'
1023 }, {
1024 'url': 'https://live.bilibili.com/196?broadcast_type=0&is_room_feed=1?spm_id_from=333.999.space_home.strengthen_live_card.click',
1025 'only_matching': True
1026 }]
1027
1028 _FORMATS = {
1029 80: {'format_id': 'low', 'format_note': '流畅'},
1030 150: {'format_id': 'high_res', 'format_note': '高清'},
1031 250: {'format_id': 'ultra_high_res', 'format_note': '超清'},
1032 400: {'format_id': 'blue_ray', 'format_note': '蓝光'},
1033 10000: {'format_id': 'source', 'format_note': '原画'},
1034 20000: {'format_id': '4K', 'format_note': '4K'},
1035 30000: {'format_id': 'dolby', 'format_note': '杜比'},
1036 }
1037
1038 _quality = staticmethod(qualities(list(_FORMATS)))
1039
1040 def _call_api(self, path, room_id, query):
1041 api_result = self._download_json(f'https://api.live.bilibili.com/{path}', room_id, query=query)
1042 if api_result.get('code') != 0:
1043 raise ExtractorError(api_result.get('message') or 'Unable to download JSON metadata')
1044 return api_result.get('data') or {}
1045
1046 def _parse_formats(self, qn, fmt):
1047 for codec in fmt.get('codec') or []:
1048 if codec.get('current_qn') != qn:
1049 continue
1050 for url_info in codec['url_info']:
1051 yield {
1052 'url': f'{url_info["host"]}{codec["base_url"]}{url_info["extra"]}',
1053 'ext': fmt.get('format_name'),
1054 'vcodec': codec.get('codec_name'),
1055 'quality': self._quality(qn),
1056 **self._FORMATS[qn],
1057 }
1058
1059 def _real_extract(self, url):
1060 room_id = self._match_id(url)
1061 room_data = self._call_api('room/v1/Room/get_info', room_id, {'id': room_id})
1062 if room_data.get('live_status') == 0:
1063 raise ExtractorError('Streamer is not live', expected=True)
1064
1065 formats = []
1066 for qn in self._FORMATS.keys():
1067 stream_data = self._call_api('xlive/web-room/v2/index/getRoomPlayInfo', room_id, {
1068 'room_id': room_id,
1069 'qn': qn,
1070 'codec': '0,1',
1071 'format': '0,2',
1072 'mask': '0',
1073 'no_playurl': '0',
1074 'platform': 'web',
1075 'protocol': '0,1',
1076 })
1077 for fmt in traverse_obj(stream_data, ('playurl_info', 'playurl', 'stream', ..., 'format', ...)) or []:
1078 formats.extend(self._parse_formats(qn, fmt))
1079 self._sort_formats(formats)
1080
1081 return {
1082 'id': room_id,
1083 'title': room_data.get('title'),
1084 'description': room_data.get('description'),
1085 'thumbnail': room_data.get('user_cover'),
1086 'timestamp': stream_data.get('live_time'),
1087 'formats': formats,
1088 'http_headers': {
1089 'Referer': url,
1090 },
1091 }