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