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.

601 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. publisher_id = video_info.get('publisherId')
  279. info = {
  280. 'id': compat_str(video_info['id']),
  281. 'title': video_info['displayName'].strip(),
  282. 'description': video_info.get('shortDescription'),
  283. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  284. 'uploader': video_info.get('publisherName'),
  285. 'uploader_id': compat_str(publisher_id) if publisher_id else None,
  286. 'duration': float_or_none(video_info.get('length'), 1000),
  287. 'timestamp': int_or_none(video_info.get('creationDate'), 1000),
  288. }
  289. renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
  290. if renditions:
  291. formats = []
  292. for rend in renditions:
  293. url = rend['defaultURL']
  294. if not url:
  295. continue
  296. ext = None
  297. if rend['remote']:
  298. url_comp = compat_urllib_parse_urlparse(url)
  299. if url_comp.path.endswith('.m3u8'):
  300. formats.extend(
  301. self._extract_m3u8_formats(url, info['id'], 'mp4'))
  302. continue
  303. elif 'akamaihd.net' in url_comp.netloc:
  304. # This type of renditions are served through
  305. # akamaihd.net, but they don't use f4m manifests
  306. url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
  307. ext = 'flv'
  308. if ext is None:
  309. ext = determine_ext(url)
  310. tbr = int_or_none(rend.get('encodingRate'), 1000),
  311. a_format = {
  312. 'format_id': 'http%s' % ('-%s' % tbr if tbr else ''),
  313. 'url': url,
  314. 'ext': ext,
  315. 'filesize': int_or_none(rend.get('size')) or None,
  316. 'tbr': tbr,
  317. }
  318. if rend.get('audioOnly'):
  319. a_format.update({
  320. 'vcodec': 'none',
  321. })
  322. else:
  323. a_format.update({
  324. 'height': int_or_none(rend.get('frameHeight')),
  325. 'width': int_or_none(rend.get('frameWidth')),
  326. 'vcodec': rend.get('videoCodec'),
  327. })
  328. # m3u8 manifests with remote == false are media playlists
  329. # Not calling _extract_m3u8_formats here to save network traffic
  330. if ext == 'm3u8':
  331. a_format.update({
  332. 'format_id': 'hls%s' % ('-%s' % tbr if tbr else ''),
  333. 'ext': 'mp4',
  334. 'protocol': 'm3u8',
  335. })
  336. formats.append(a_format)
  337. self._sort_formats(formats)
  338. info['formats'] = formats
  339. elif video_info.get('FLVFullLengthURL') is not None:
  340. info.update({
  341. 'url': video_info['FLVFullLengthURL'],
  342. 'vcodec': self.FLV_VCODECS.get(video_info.get('FLVFullCodec')),
  343. 'filesize': int_or_none(video_info.get('FLVFullSize')),
  344. })
  345. if self._downloader.params.get('include_ads', False):
  346. adServerURL = video_info.get('_youtubedl_adServerURL')
  347. if adServerURL:
  348. ad_info = {
  349. '_type': 'url',
  350. 'url': adServerURL,
  351. }
  352. if 'url' in info:
  353. return {
  354. '_type': 'playlist',
  355. 'title': info['title'],
  356. 'entries': [ad_info, info],
  357. }
  358. else:
  359. return ad_info
  360. if 'url' not in info and not info.get('formats'):
  361. raise ExtractorError('Unable to extract video url for %s' % info['id'])
  362. return info
  363. class BrightcoveNewIE(InfoExtractor):
  364. IE_NAME = 'brightcove:new'
  365. _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
  366. _TESTS = [{
  367. 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
  368. 'md5': 'c8100925723840d4b0d243f7025703be',
  369. 'info_dict': {
  370. 'id': '4463358922001',
  371. 'ext': 'mp4',
  372. 'title': 'Meet the man behind Popcorn Time',
  373. 'description': 'md5:eac376a4fe366edc70279bfb681aea16',
  374. 'duration': 165.768,
  375. 'timestamp': 1441391203,
  376. 'upload_date': '20150904',
  377. 'uploader_id': '929656772001',
  378. 'formats': 'mincount:22',
  379. },
  380. }, {
  381. # with rtmp streams
  382. 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
  383. 'info_dict': {
  384. 'id': '4279049078001',
  385. 'ext': 'mp4',
  386. 'title': 'Titansgrave: Chapter 0',
  387. 'description': 'Titansgrave: Chapter 0',
  388. 'duration': 1242.058,
  389. 'timestamp': 1433556729,
  390. 'upload_date': '20150606',
  391. 'uploader_id': '4036320279001',
  392. 'formats': 'mincount:41',
  393. },
  394. 'params': {
  395. # m3u8 download
  396. 'skip_download': True,
  397. }
  398. }, {
  399. # ref: prefixed video id
  400. 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
  401. 'only_matching': True,
  402. }, {
  403. # non numeric ref: prefixed video id
  404. 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
  405. 'only_matching': True,
  406. }]
  407. @staticmethod
  408. def _extract_url(webpage):
  409. urls = BrightcoveNewIE._extract_urls(webpage)
  410. return urls[0] if urls else None
  411. @staticmethod
  412. def _extract_urls(webpage):
  413. # Reference:
  414. # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
  415. # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
  416. # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
  417. # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
  418. entries = []
  419. # Look for iframe embeds [1]
  420. for _, url in re.findall(
  421. r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
  422. entries.append(url if url.startswith('http') else 'http:' + url)
  423. # Look for embed_in_page embeds [2]
  424. for video_id, account_id, player_id, embed in re.findall(
  425. # According to examples from [3] it's unclear whether video id
  426. # may be optional and what to do when it is
  427. # According to [4] data-video-id may be prefixed with ref:
  428. r'''(?sx)
  429. <video[^>]+
  430. data-video-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
  431. </video>.*?
  432. <script[^>]+
  433. src=["\'](?:https?:)?//players\.brightcove\.net/
  434. (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
  435. ''', webpage):
  436. entries.append(
  437. 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
  438. % (account_id, player_id, embed, video_id))
  439. return entries
  440. def _real_extract(self, url):
  441. account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
  442. webpage = self._download_webpage(
  443. 'http://players.brightcove.net/%s/%s_%s/index.min.js'
  444. % (account_id, player_id, embed), video_id)
  445. policy_key = None
  446. catalog = self._search_regex(
  447. r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
  448. if catalog:
  449. catalog = self._parse_json(
  450. js_to_json(catalog), video_id, fatal=False)
  451. if catalog:
  452. policy_key = catalog.get('policyKey')
  453. if not policy_key:
  454. policy_key = self._search_regex(
  455. r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
  456. webpage, 'policy key', group='pk')
  457. api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
  458. try:
  459. json_data = self._download_json(api_url, video_id, headers={
  460. 'Accept': 'application/json;pk=%s' % policy_key
  461. })
  462. except ExtractorError as e:
  463. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
  464. json_data = self._parse_json(e.cause.read().decode(), video_id)
  465. raise ExtractorError(json_data[0]['message'], expected=True)
  466. raise
  467. title = json_data['name'].strip()
  468. formats = []
  469. for source in json_data.get('sources', []):
  470. container = source.get('container')
  471. source_type = source.get('type')
  472. src = source.get('src')
  473. if source_type == 'application/x-mpegURL' or container == 'M2TS':
  474. if not src:
  475. continue
  476. formats.extend(self._extract_m3u8_formats(
  477. src, video_id, 'mp4', m3u8_id='hls', fatal=False))
  478. elif source_type == 'application/dash+xml':
  479. if not src:
  480. continue
  481. formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
  482. else:
  483. streaming_src = source.get('streaming_src')
  484. stream_name, app_name = source.get('stream_name'), source.get('app_name')
  485. if not src and not streaming_src and (not stream_name or not app_name):
  486. continue
  487. tbr = float_or_none(source.get('avg_bitrate'), 1000)
  488. height = int_or_none(source.get('height'))
  489. width = int_or_none(source.get('width'))
  490. f = {
  491. 'tbr': tbr,
  492. 'filesize': int_or_none(source.get('size')),
  493. 'container': container,
  494. 'ext': container.lower(),
  495. }
  496. if width == 0 and height == 0:
  497. f.update({
  498. 'vcodec': 'none',
  499. })
  500. else:
  501. f.update({
  502. 'width': width,
  503. 'height': height,
  504. 'vcodec': source.get('codec'),
  505. })
  506. def build_format_id(kind):
  507. format_id = kind
  508. if tbr:
  509. format_id += '-%dk' % int(tbr)
  510. if height:
  511. format_id += '-%dp' % height
  512. return format_id
  513. if src or streaming_src:
  514. f.update({
  515. 'url': src or streaming_src,
  516. 'format_id': build_format_id('http' if src else 'http-streaming'),
  517. 'source_preference': 0 if src else -1,
  518. })
  519. else:
  520. f.update({
  521. 'url': app_name,
  522. 'play_path': stream_name,
  523. 'format_id': build_format_id('rtmp'),
  524. })
  525. formats.append(f)
  526. self._sort_formats(formats)
  527. subtitles = {}
  528. for text_track in json_data.get('text_tracks', []):
  529. if text_track.get('src'):
  530. subtitles.setdefault(text_track.get('srclang'), []).append({
  531. 'url': text_track['src'],
  532. })
  533. return {
  534. 'id': video_id,
  535. 'title': title,
  536. 'description': json_data.get('description'),
  537. 'thumbnail': json_data.get('thumbnail') or json_data.get('poster'),
  538. 'duration': float_or_none(json_data.get('duration'), 1000),
  539. 'timestamp': parse_iso8601(json_data.get('published_at')),
  540. 'uploader_id': account_id,
  541. 'formats': formats,
  542. 'subtitles': subtitles,
  543. 'tags': json_data.get('tags', []),
  544. }