brightcove.py 34 KB

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