]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/brightcove.py
[dbtv] delegate extraction to BrightcoveNewIE
[yt-dlp.git] / youtube_dl / extractor / brightcove.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_etree_fromstring,
10 compat_parse_qs,
11 compat_str,
12 compat_urllib_parse_urlparse,
13 compat_urlparse,
14 compat_xml_parse_error,
15 compat_HTTPError,
16 )
17 from ..utils import (
18 determine_ext,
19 ExtractorError,
20 find_xpath_attr,
21 fix_xml_ampersands,
22 float_or_none,
23 js_to_json,
24 int_or_none,
25 parse_iso8601,
26 unescapeHTML,
27 unsmuggle_url,
28 update_url_query,
29 )
30
31
32 class BrightcoveLegacyIE(InfoExtractor):
33 IE_NAME = 'brightcove:legacy'
34 _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
35 _FEDERATED_URL = 'http://c.brightcove.com/services/viewer/htmlFederated'
36
37 _TESTS = [
38 {
39 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
40 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
41 'md5': '5423e113865d26e40624dce2e4b45d95',
42 'note': 'Test Brightcove downloads and detection in GenericIE',
43 'info_dict': {
44 'id': '2371591881001',
45 'ext': 'mp4',
46 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
47 'uploader': '8TV',
48 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
49 'timestamp': 1368213670,
50 'upload_date': '20130510',
51 'uploader_id': '1589608506001',
52 }
53 },
54 {
55 # From http://medianetwork.oracle.com/video/player/1785452137001
56 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
57 'info_dict': {
58 'id': '1785452137001',
59 'ext': 'flv',
60 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
61 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
62 'uploader': 'Oracle',
63 'timestamp': 1344975024,
64 'upload_date': '20120814',
65 'uploader_id': '1460825906',
66 },
67 },
68 {
69 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
70 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
71 'info_dict': {
72 'id': '2750934548001',
73 'ext': 'mp4',
74 'title': 'This Bracelet Acts as a Personal Thermostat',
75 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
76 'uploader': 'Mashable',
77 'timestamp': 1382041798,
78 'upload_date': '20131017',
79 'uploader_id': '1130468786001',
80 },
81 },
82 {
83 # test that the default referer works
84 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
85 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
86 'info_dict': {
87 'id': '2878862109001',
88 'ext': 'mp4',
89 'title': 'Lost in Motion II',
90 'description': 'md5:363109c02998fee92ec02211bd8000df',
91 'uploader': 'National Ballet of Canada',
92 },
93 'skip': 'Video gone',
94 },
95 {
96 # test flv videos served by akamaihd.net
97 # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
98 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?%40videoPlayer=ref%3Aevent-stream-356&linkBaseURL=http%3A%2F%2Fwww.redbull.com%2Fen%2Fbike%2Fvideos%2F1331655630249%2Freplay-uci-fort-william-2014-dh&playerKey=AQ%7E%7E%2CAAAApYJ7UqE%7E%2Cxqr_zXk0I-zzNndy8NlHogrCb5QdyZRf&playerID=1398061561001#__youtubedl_smuggle=%7B%22Referer%22%3A+%22http%3A%2F%2Fwww.redbull.com%2Fen%2Fbike%2Fstories%2F1331655643987%2Freplay-uci-dh-world-cup-2014-from-fort-william%22%7D',
99 # The md5 checksum changes on each download
100 'info_dict': {
101 'id': '3750436379001',
102 'ext': 'flv',
103 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
104 'uploader': 'RBTV Old (do not use)',
105 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
106 'timestamp': 1409122195,
107 'upload_date': '20140827',
108 'uploader_id': '710858724001',
109 },
110 },
111 {
112 # playlist with 'videoList'
113 # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
114 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
115 'info_dict': {
116 'title': 'Sealife',
117 'id': '3550319591001',
118 },
119 'playlist_mincount': 7,
120 },
121 {
122 # playlist with 'playlistTab' (https://github.com/rg3/youtube-dl/issues/9965)
123 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg',
124 'info_dict': {
125 'id': '1522758701001',
126 'title': 'Lesson 08',
127 },
128 'playlist_mincount': 10,
129 },
130 ]
131 FLV_VCODECS = {
132 1: 'SORENSON',
133 2: 'ON2',
134 3: 'H264',
135 4: 'VP8',
136 }
137
138 @classmethod
139 def _build_brighcove_url(cls, object_str):
140 """
141 Build a Brightcove url from a xml string containing
142 <object class="BrightcoveExperience">{params}</object>
143 """
144
145 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
146 object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
147 lambda m: m.group(1) + '/>', object_str)
148 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
149 object_str = object_str.replace('<--', '<!--')
150 # remove namespace to simplify extraction
151 object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
152 object_str = fix_xml_ampersands(object_str)
153
154 try:
155 object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
156 except compat_xml_parse_error:
157 return
158
159 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
160 if fv_el is not None:
161 flashvars = dict(
162 (k, v[0])
163 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
164 else:
165 flashvars = {}
166
167 data_url = object_doc.attrib.get('data', '')
168 data_url_params = compat_parse_qs(compat_urllib_parse_urlparse(data_url).query)
169
170 def find_param(name):
171 if name in flashvars:
172 return flashvars[name]
173 node = find_xpath_attr(object_doc, './param', 'name', name)
174 if node is not None:
175 return node.attrib['value']
176 return data_url_params.get(name)
177
178 params = {}
179
180 playerID = find_param('playerID')
181 if playerID is None:
182 raise ExtractorError('Cannot find player ID')
183 params['playerID'] = playerID
184
185 playerKey = find_param('playerKey')
186 # Not all pages define this value
187 if playerKey is not None:
188 params['playerKey'] = playerKey
189 # These fields hold the id of the video
190 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
191 if videoPlayer is not None:
192 params['@videoPlayer'] = videoPlayer
193 linkBase = find_param('linkBaseURL')
194 if linkBase is not None:
195 params['linkBaseURL'] = linkBase
196 return cls._make_brightcove_url(params)
197
198 @classmethod
199 def _build_brighcove_url_from_js(cls, object_js):
200 # The layout of JS is as follows:
201 # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
202 # // build Brightcove <object /> XML
203 # }
204 m = re.search(
205 r'''(?x)customBC.\createVideo\(
206 .*? # skipping width and height
207 ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID
208 ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters
209 # in length, however it's appended to itself
210 # in places, so truncate
211 ["\'](?P<videoID>\d+)["\'] # @videoPlayer
212 ''', object_js)
213 if m:
214 return cls._make_brightcove_url(m.groupdict())
215
216 @classmethod
217 def _make_brightcove_url(cls, params):
218 return update_url_query(cls._FEDERATED_URL, params)
219
220 @classmethod
221 def _extract_brightcove_url(cls, webpage):
222 """Try to extract the brightcove url from the webpage, returns None
223 if it can't be found
224 """
225 urls = cls._extract_brightcove_urls(webpage)
226 return urls[0] if urls else None
227
228 @classmethod
229 def _extract_brightcove_urls(cls, webpage):
230 """Return a list of all Brightcove URLs from the webpage """
231
232 url_m = re.search(
233 r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
234 webpage)
235 if url_m:
236 url = unescapeHTML(url_m.group(1))
237 # Some sites don't add it, we can't download with this url, for example:
238 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
239 if 'playerKey' in url or 'videoId' in url:
240 return [url]
241
242 matches = re.findall(
243 r'''(?sx)<object
244 (?:
245 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
246 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
247 ).+?>\s*</object>''',
248 webpage)
249 if matches:
250 return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
251
252 return list(filter(None, [
253 cls._build_brighcove_url_from_js(custom_bc)
254 for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
255
256 def _real_extract(self, url):
257 url, smuggled_data = unsmuggle_url(url, {})
258
259 # Change the 'videoId' and others field to '@videoPlayer'
260 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
261 # Change bckey (used by bcove.me urls) to playerKey
262 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
263 mobj = re.match(self._VALID_URL, url)
264 query_str = mobj.group('query')
265 query = compat_urlparse.parse_qs(query_str)
266
267 videoPlayer = query.get('@videoPlayer')
268 if videoPlayer:
269 # We set the original url as the default 'Referer' header
270 referer = smuggled_data.get('Referer', url)
271 return self._get_video_info(
272 videoPlayer[0], query, referer=referer)
273 elif 'playerKey' in query:
274 player_key = query['playerKey']
275 return self._get_playlist_info(player_key[0])
276 else:
277 raise ExtractorError(
278 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
279 expected=True)
280
281 def _get_video_info(self, video_id, query, referer=None):
282 headers = {}
283 linkBase = query.get('linkBaseURL')
284 if linkBase is not None:
285 referer = linkBase[0]
286 if referer is not None:
287 headers['Referer'] = referer
288 webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
289
290 error_msg = self._html_search_regex(
291 r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
292 'error message', default=None)
293 if error_msg is not None:
294 raise ExtractorError(
295 'brightcove said: %s' % error_msg, expected=True)
296
297 self.report_extraction(video_id)
298 info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
299 info = json.loads(info)['data']
300 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
301 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
302
303 return self._extract_video_info(video_info)
304
305 def _get_playlist_info(self, player_key):
306 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
307 playlist_info = self._download_webpage(
308 info_url, player_key, 'Downloading playlist information')
309
310 json_data = json.loads(playlist_info)
311 if 'videoList' in json_data:
312 playlist_info = json_data['videoList']
313 playlist_dto = playlist_info['mediaCollectionDTO']
314 elif 'playlistTabs' in json_data:
315 playlist_info = json_data['playlistTabs']
316 playlist_dto = playlist_info['lineupListDTO']['playlistDTOs'][0]
317 else:
318 raise ExtractorError('Empty playlist')
319
320 videos = [self._extract_video_info(video_info) for video_info in playlist_dto['videoDTOs']]
321
322 return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
323 playlist_title=playlist_dto['displayName'])
324
325 def _extract_video_info(self, video_info):
326 video_id = compat_str(video_info['id'])
327 publisher_id = video_info.get('publisherId')
328 info = {
329 'id': video_id,
330 'title': video_info['displayName'].strip(),
331 'description': video_info.get('shortDescription'),
332 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
333 'uploader': video_info.get('publisherName'),
334 'uploader_id': compat_str(publisher_id) if publisher_id else None,
335 'duration': float_or_none(video_info.get('length'), 1000),
336 'timestamp': int_or_none(video_info.get('creationDate'), 1000),
337 }
338
339 renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
340 if renditions:
341 formats = []
342 for rend in renditions:
343 url = rend['defaultURL']
344 if not url:
345 continue
346 ext = None
347 if rend['remote']:
348 url_comp = compat_urllib_parse_urlparse(url)
349 if url_comp.path.endswith('.m3u8'):
350 formats.extend(
351 self._extract_m3u8_formats(
352 url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
353 continue
354 elif 'akamaihd.net' in url_comp.netloc:
355 # This type of renditions are served through
356 # akamaihd.net, but they don't use f4m manifests
357 url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
358 ext = 'flv'
359 if ext is None:
360 ext = determine_ext(url)
361 tbr = int_or_none(rend.get('encodingRate'), 1000)
362 a_format = {
363 'format_id': 'http%s' % ('-%s' % tbr if tbr else ''),
364 'url': url,
365 'ext': ext,
366 'filesize': int_or_none(rend.get('size')) or None,
367 'tbr': tbr,
368 }
369 if rend.get('audioOnly'):
370 a_format.update({
371 'vcodec': 'none',
372 })
373 else:
374 a_format.update({
375 'height': int_or_none(rend.get('frameHeight')),
376 'width': int_or_none(rend.get('frameWidth')),
377 'vcodec': rend.get('videoCodec'),
378 })
379
380 # m3u8 manifests with remote == false are media playlists
381 # Not calling _extract_m3u8_formats here to save network traffic
382 if ext == 'm3u8':
383 a_format.update({
384 'format_id': 'hls%s' % ('-%s' % tbr if tbr else ''),
385 'ext': 'mp4',
386 'protocol': 'm3u8_native',
387 })
388
389 formats.append(a_format)
390 self._sort_formats(formats)
391 info['formats'] = formats
392 elif video_info.get('FLVFullLengthURL') is not None:
393 info.update({
394 'url': video_info['FLVFullLengthURL'],
395 'vcodec': self.FLV_VCODECS.get(video_info.get('FLVFullCodec')),
396 'filesize': int_or_none(video_info.get('FLVFullSize')),
397 })
398
399 if self._downloader.params.get('include_ads', False):
400 adServerURL = video_info.get('_youtubedl_adServerURL')
401 if adServerURL:
402 ad_info = {
403 '_type': 'url',
404 'url': adServerURL,
405 }
406 if 'url' in info:
407 return {
408 '_type': 'playlist',
409 'title': info['title'],
410 'entries': [ad_info, info],
411 }
412 else:
413 return ad_info
414
415 if 'url' not in info and not info.get('formats'):
416 raise ExtractorError('Unable to extract video url for %s' % video_id)
417 return info
418
419
420 class BrightcoveNewIE(InfoExtractor):
421 IE_NAME = 'brightcove:new'
422 _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
423 _TESTS = [{
424 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
425 'md5': 'c8100925723840d4b0d243f7025703be',
426 'info_dict': {
427 'id': '4463358922001',
428 'ext': 'mp4',
429 'title': 'Meet the man behind Popcorn Time',
430 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
431 'duration': 165.768,
432 'timestamp': 1441391203,
433 'upload_date': '20150904',
434 'uploader_id': '929656772001',
435 'formats': 'mincount:22',
436 },
437 }, {
438 # with rtmp streams
439 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
440 'info_dict': {
441 'id': '4279049078001',
442 'ext': 'mp4',
443 'title': 'Titansgrave: Chapter 0',
444 'description': 'Titansgrave: Chapter 0',
445 'duration': 1242.058,
446 'timestamp': 1433556729,
447 'upload_date': '20150606',
448 'uploader_id': '4036320279001',
449 'formats': 'mincount:41',
450 },
451 'params': {
452 # m3u8 download
453 'skip_download': True,
454 }
455 }, {
456 # ref: prefixed video id
457 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
458 'only_matching': True,
459 }, {
460 # non numeric ref: prefixed video id
461 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
462 'only_matching': True,
463 }, {
464 # unavailable video without message but with error_code
465 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001',
466 'only_matching': True,
467 }]
468
469 @staticmethod
470 def _extract_url(webpage):
471 urls = BrightcoveNewIE._extract_urls(webpage)
472 return urls[0] if urls else None
473
474 @staticmethod
475 def _extract_urls(webpage):
476 # Reference:
477 # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
478 # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
479 # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
480 # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
481
482 entries = []
483
484 # Look for iframe embeds [1]
485 for _, url in re.findall(
486 r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
487 entries.append(url if url.startswith('http') else 'http:' + url)
488
489 # Look for embed_in_page embeds [2]
490 for video_id, account_id, player_id, embed in re.findall(
491 # According to examples from [3] it's unclear whether video id
492 # may be optional and what to do when it is
493 # According to [4] data-video-id may be prefixed with ref:
494 r'''(?sx)
495 <video[^>]+
496 data-video-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
497 </video>.*?
498 <script[^>]+
499 src=["\'](?:https?:)?//players\.brightcove\.net/
500 (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
501 ''', webpage):
502 entries.append(
503 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
504 % (account_id, player_id, embed, video_id))
505
506 return entries
507
508 def _real_extract(self, url):
509 account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
510
511 webpage = self._download_webpage(
512 'http://players.brightcove.net/%s/%s_%s/index.min.js'
513 % (account_id, player_id, embed), video_id)
514
515 policy_key = None
516
517 catalog = self._search_regex(
518 r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
519 if catalog:
520 catalog = self._parse_json(
521 js_to_json(catalog), video_id, fatal=False)
522 if catalog:
523 policy_key = catalog.get('policyKey')
524
525 if not policy_key:
526 policy_key = self._search_regex(
527 r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
528 webpage, 'policy key', group='pk')
529
530 api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
531 try:
532 json_data = self._download_json(api_url, video_id, headers={
533 'Accept': 'application/json;pk=%s' % policy_key
534 })
535 except ExtractorError as e:
536 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
537 json_data = self._parse_json(e.cause.read().decode(), video_id)[0]
538 raise ExtractorError(
539 json_data.get('message') or json_data['error_code'], expected=True)
540 raise
541
542 title = json_data['name'].strip()
543
544 formats = []
545 for source in json_data.get('sources', []):
546 container = source.get('container')
547 source_type = source.get('type')
548 src = source.get('src')
549 if source_type == 'application/x-mpegURL' or container == 'M2TS':
550 if not src:
551 continue
552 formats.extend(self._extract_m3u8_formats(
553 src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
554 elif source_type == 'application/dash+xml':
555 if not src:
556 continue
557 formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
558 else:
559 streaming_src = source.get('streaming_src')
560 stream_name, app_name = source.get('stream_name'), source.get('app_name')
561 if not src and not streaming_src and (not stream_name or not app_name):
562 continue
563 tbr = float_or_none(source.get('avg_bitrate'), 1000)
564 height = int_or_none(source.get('height'))
565 width = int_or_none(source.get('width'))
566 f = {
567 'tbr': tbr,
568 'filesize': int_or_none(source.get('size')),
569 'container': container,
570 'ext': container.lower(),
571 }
572 if width == 0 and height == 0:
573 f.update({
574 'vcodec': 'none',
575 })
576 else:
577 f.update({
578 'width': width,
579 'height': height,
580 'vcodec': source.get('codec'),
581 })
582
583 def build_format_id(kind):
584 format_id = kind
585 if tbr:
586 format_id += '-%dk' % int(tbr)
587 if height:
588 format_id += '-%dp' % height
589 return format_id
590
591 if src or streaming_src:
592 f.update({
593 'url': src or streaming_src,
594 'format_id': build_format_id('http' if src else 'http-streaming'),
595 'source_preference': 0 if src else -1,
596 })
597 else:
598 f.update({
599 'url': app_name,
600 'play_path': stream_name,
601 'format_id': build_format_id('rtmp'),
602 })
603 formats.append(f)
604
605 errors = json_data.get('errors')
606 if not formats and errors:
607 error = errors[0]
608 raise ExtractorError(
609 error.get('message') or error.get('error_subcode') or error['error_code'], expected=True)
610
611 self._sort_formats(formats)
612
613 subtitles = {}
614 for text_track in json_data.get('text_tracks', []):
615 if text_track.get('src'):
616 subtitles.setdefault(text_track.get('srclang'), []).append({
617 'url': text_track['src'],
618 })
619
620 return {
621 'id': video_id,
622 'title': title,
623 'description': json_data.get('description'),
624 'thumbnail': json_data.get('thumbnail') or json_data.get('poster'),
625 'duration': float_or_none(json_data.get('duration'), 1000),
626 'timestamp': parse_iso8601(json_data.get('published_at')),
627 'uploader_id': account_id,
628 'formats': formats,
629 'subtitles': subtitles,
630 'tags': json_data.get('tags', []),
631 }