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