You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

608 lines
26 KiB

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