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