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