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