Source: ui/ui.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.ui.Overlay');
  7. goog.provide('shaka.ui.Overlay.FailReasonCode');
  8. goog.provide('shaka.ui.Overlay.TrackLabelFormat');
  9. goog.require('goog.asserts');
  10. goog.require('shaka.Player');
  11. goog.require('shaka.log');
  12. goog.require('shaka.polyfill');
  13. goog.require('shaka.ui.Controls');
  14. goog.require('shaka.util.ConfigUtils');
  15. goog.require('shaka.util.Dom');
  16. goog.require('shaka.util.FakeEvent');
  17. goog.require('shaka.util.IDestroyable');
  18. goog.require('shaka.util.Platform');
  19. /**
  20. * @implements {shaka.util.IDestroyable}
  21. * @export
  22. */
  23. shaka.ui.Overlay = class {
  24. /**
  25. * @param {!shaka.Player} player
  26. * @param {!HTMLElement} videoContainer
  27. * @param {!HTMLMediaElement} video
  28. * @param {?HTMLCanvasElement=} vrCanvas
  29. */
  30. constructor(player, videoContainer, video, vrCanvas = null) {
  31. /** @private {shaka.Player} */
  32. this.player_ = player;
  33. /** @private {HTMLElement} */
  34. this.videoContainer_ = videoContainer;
  35. /** @private {!shaka.extern.UIConfiguration} */
  36. this.config_ = this.defaultConfig_();
  37. // Make sure this container is discoverable and that the UI can be reached
  38. // through it.
  39. videoContainer['dataset']['shakaPlayerContainer'] = '';
  40. videoContainer['ui'] = this;
  41. // Tag the container for mobile platforms, to allow different styles.
  42. if (this.isMobile()) {
  43. videoContainer.classList.add('shaka-mobile');
  44. }
  45. /** @private {shaka.ui.Controls} */
  46. this.controls_ = new shaka.ui.Controls(
  47. player, videoContainer, video, vrCanvas, this.config_);
  48. // Run the initial setup so that no configure() call is required for default
  49. // settings.
  50. this.configure({});
  51. // If the browser's native controls are disabled, use UI TextDisplayer.
  52. if (!video.controls) {
  53. player.setVideoContainer(videoContainer);
  54. }
  55. videoContainer['ui'] = this;
  56. video['ui'] = this;
  57. }
  58. /**
  59. * @override
  60. * @export
  61. */
  62. async destroy() {
  63. if (this.controls_) {
  64. await this.controls_.destroy();
  65. }
  66. this.controls_ = null;
  67. if (this.player_) {
  68. await this.player_.destroy();
  69. }
  70. this.player_ = null;
  71. }
  72. /**
  73. * Detects if this is a mobile platform, in case you want to choose a
  74. * different UI configuration on mobile devices.
  75. *
  76. * @return {boolean}
  77. * @export
  78. */
  79. isMobile() {
  80. return shaka.util.Platform.isMobile();
  81. }
  82. /**
  83. * @return {!shaka.extern.UIConfiguration}
  84. * @export
  85. */
  86. getConfiguration() {
  87. const ret = this.defaultConfig_();
  88. shaka.util.ConfigUtils.mergeConfigObjects(
  89. ret, this.config_, this.defaultConfig_(),
  90. /* overrides= */ {}, /* path= */ '');
  91. return ret;
  92. }
  93. /**
  94. * @param {string|!Object} config This should either be a field name or an
  95. * object following the form of {@link shaka.extern.UIConfiguration}, where
  96. * you may omit any field you do not wish to change.
  97. * @param {*=} value This should be provided if the previous parameter
  98. * was a string field name.
  99. * @export
  100. */
  101. configure(config, value) {
  102. goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
  103. 'String configs should have values!');
  104. // ('fieldName', value) format
  105. if (arguments.length == 2 && typeof(config) == 'string') {
  106. config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
  107. }
  108. goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
  109. shaka.util.ConfigUtils.mergeConfigObjects(
  110. this.config_, config, this.defaultConfig_(),
  111. /* overrides= */ {}, /* path= */ '');
  112. // If a cast receiver app id has been given, add a cast button to the UI
  113. if (this.config_.castReceiverAppId &&
  114. !this.config_.overflowMenuButtons.includes('cast')) {
  115. this.config_.overflowMenuButtons.push('cast');
  116. }
  117. goog.asserts.assert(this.player_ != null, 'Should have a player!');
  118. this.controls_.configure(this.config_);
  119. this.controls_.dispatchEvent(new shaka.util.FakeEvent('uiupdated'));
  120. }
  121. /**
  122. * @return {shaka.ui.Controls}
  123. * @export
  124. */
  125. getControls() {
  126. return this.controls_;
  127. }
  128. /**
  129. * Enable or disable the custom controls.
  130. *
  131. * @param {boolean} enabled
  132. * @export
  133. */
  134. setEnabled(enabled) {
  135. this.controls_.setEnabledShakaControls(enabled);
  136. }
  137. /**
  138. * @return {!shaka.extern.UIConfiguration}
  139. * @private
  140. */
  141. defaultConfig_() {
  142. const config = {
  143. controlPanelElements: [
  144. 'play_pause',
  145. 'time_and_duration',
  146. 'spacer',
  147. 'mute',
  148. 'volume',
  149. 'fullscreen',
  150. 'overflow_menu',
  151. ],
  152. overflowMenuButtons: [
  153. 'captions',
  154. 'quality',
  155. 'language',
  156. 'picture_in_picture',
  157. 'cast',
  158. 'playback_rate',
  159. 'recenter_vr',
  160. 'toggle_stereoscopic',
  161. ],
  162. statisticsList: [
  163. 'width',
  164. 'height',
  165. 'corruptedFrames',
  166. 'decodedFrames',
  167. 'droppedFrames',
  168. 'drmTimeSeconds',
  169. 'licenseTime',
  170. 'liveLatency',
  171. 'loadLatency',
  172. 'bufferingTime',
  173. 'manifestTimeSeconds',
  174. 'estimatedBandwidth',
  175. 'streamBandwidth',
  176. 'maxSegmentDuration',
  177. 'pauseTime',
  178. 'playTime',
  179. 'completionPercent',
  180. 'bytesDownloaded',
  181. ],
  182. contextMenuElements: [
  183. 'loop',
  184. 'picture_in_picture',
  185. 'statistics',
  186. ],
  187. playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
  188. fastForwardRates: [2, 4, 8, 1],
  189. rewindRates: [-1, -2, -4, -8],
  190. addSeekBar: true,
  191. addBigPlayButton: false,
  192. customContextMenu: false,
  193. castReceiverAppId: '',
  194. castAndroidReceiverCompatible: false,
  195. clearBufferOnQualityChange: true,
  196. showUnbufferedStart: false,
  197. seekBarColors: {
  198. base: 'rgba(255, 255, 255, 0.3)',
  199. buffered: 'rgba(255, 255, 255, 0.54)',
  200. played: 'rgb(255, 255, 255)',
  201. adBreaks: 'rgb(255, 204, 0)',
  202. },
  203. volumeBarColors: {
  204. base: 'rgba(255, 255, 255, 0.54)',
  205. level: 'rgb(255, 255, 255)',
  206. },
  207. trackLabelFormat: shaka.ui.Overlay.TrackLabelFormat.LANGUAGE,
  208. textTrackLabelFormat: shaka.ui.Overlay.TrackLabelFormat.LANGUAGE,
  209. fadeDelay: 0,
  210. doubleClickForFullscreen: true,
  211. singleClickForPlayAndPause: true,
  212. enableKeyboardPlaybackControls: true,
  213. enableFullscreenOnRotation: true,
  214. forceLandscapeOnFullscreen: true,
  215. enableTooltips: false,
  216. keyboardSeekDistance: 5,
  217. keyboardLargeSeekDistance: 60,
  218. fullScreenElement: this.videoContainer_,
  219. preferDocumentPictureInPicture: true,
  220. showAudioChannelCountVariants: true,
  221. seekOnTaps: true,
  222. tapSeekDistance: 10,
  223. refreshTickInSeconds: 0.125,
  224. displayInVrMode: false,
  225. defaultVrProjectionMode: 'equirectangular',
  226. };
  227. // eslint-disable-next-line no-restricted-syntax
  228. if ('remote' in HTMLMediaElement.prototype) {
  229. config.overflowMenuButtons.push('remote');
  230. } else if (window.WebKitPlaybackTargetAvailabilityEvent) {
  231. config.overflowMenuButtons.push('airplay');
  232. }
  233. // On mobile, by default, hide the volume slide and the small play/pause
  234. // button and show the big play/pause button in the center.
  235. // This is in line with default styles in Chrome.
  236. if (this.isMobile()) {
  237. config.addBigPlayButton = true;
  238. config.controlPanelElements = config.controlPanelElements.filter(
  239. (name) => name != 'play_pause' && name != 'volume');
  240. }
  241. return config;
  242. }
  243. /**
  244. * @private
  245. */
  246. static async scanPageForShakaElements_() {
  247. // Install built-in polyfills to patch browser incompatibilities.
  248. shaka.polyfill.installAll();
  249. // Check to see if the browser supports the basic APIs Shaka needs.
  250. if (!shaka.Player.isBrowserSupported()) {
  251. shaka.log.error('Shaka Player does not support this browser. ' +
  252. 'Please see https://tinyurl.com/y7s4j9tr for the list of ' +
  253. 'supported browsers.');
  254. // After scanning the page for elements, fire a special "loaded" event for
  255. // when the load fails. This will allow the page to react to the failure.
  256. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-load-failed',
  257. shaka.ui.Overlay.FailReasonCode.NO_BROWSER_SUPPORT);
  258. return;
  259. }
  260. // Look for elements marked 'data-shaka-player-container'
  261. // on the page. These will be used to create our default
  262. // UI.
  263. const containers = document.querySelectorAll(
  264. '[data-shaka-player-container]');
  265. // Look for elements marked 'data-shaka-player'. They will
  266. // either be used in our default UI or with native browser
  267. // controls.
  268. const videos = document.querySelectorAll(
  269. '[data-shaka-player]');
  270. // Look for elements marked 'data-shaka-player-canvas'
  271. // on the page. These will be used to create our default
  272. // UI.
  273. const canvases = document.querySelectorAll(
  274. '[data-shaka-player-canvas]');
  275. // Look for elements marked 'data-shaka-player-vr-canvas'
  276. // on the page. These will be used to create our default
  277. // UI.
  278. const vrCanvases = document.querySelectorAll(
  279. '[data-shaka-player-vr-canvas]');
  280. if (!videos.length && !containers.length) {
  281. // No elements have been tagged with shaka attributes.
  282. } else if (videos.length && !containers.length) {
  283. // Just the video elements were provided.
  284. for (const video of videos) {
  285. // If the app has already manually created a UI for this element,
  286. // don't create another one.
  287. if (video['ui']) {
  288. continue;
  289. }
  290. goog.asserts.assert(video.tagName.toLowerCase() == 'video',
  291. 'Should be a video element!');
  292. const container = document.createElement('div');
  293. const videoParent = video.parentElement;
  294. videoParent.replaceChild(container, video);
  295. container.appendChild(video);
  296. const {lcevcCanvas, vrCanvas} =
  297. shaka.ui.Overlay.findOrMakeSpecialCanvases_(
  298. container, canvases, vrCanvases);
  299. shaka.ui.Overlay.setupUIandAutoLoad_(
  300. container, video, lcevcCanvas, vrCanvas);
  301. }
  302. } else {
  303. for (const container of containers) {
  304. // If the app has already manually created a UI for this element,
  305. // don't create another one.
  306. if (container['ui']) {
  307. continue;
  308. }
  309. goog.asserts.assert(container.tagName.toLowerCase() == 'div',
  310. 'Container should be a div!');
  311. let currentVideo = null;
  312. for (const video of videos) {
  313. goog.asserts.assert(video.tagName.toLowerCase() == 'video',
  314. 'Should be a video element!');
  315. if (video.parentElement == container) {
  316. currentVideo = video;
  317. break;
  318. }
  319. }
  320. if (!currentVideo) {
  321. currentVideo = document.createElement('video');
  322. currentVideo.setAttribute('playsinline', '');
  323. container.appendChild(currentVideo);
  324. }
  325. const {lcevcCanvas, vrCanvas} =
  326. shaka.ui.Overlay.findOrMakeSpecialCanvases_(
  327. container, canvases, vrCanvases);
  328. try {
  329. // eslint-disable-next-line no-await-in-loop
  330. await shaka.ui.Overlay.setupUIandAutoLoad_(
  331. container, currentVideo, lcevcCanvas, vrCanvas);
  332. } catch (e) {
  333. // This can fail if, for example, not every player file has loaded.
  334. // Ad-block is a likely cause for this sort of failure.
  335. shaka.log.error('Error setting up Shaka Player', e);
  336. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-load-failed',
  337. shaka.ui.Overlay.FailReasonCode.PLAYER_FAILED_TO_LOAD);
  338. return;
  339. }
  340. }
  341. }
  342. // After scanning the page for elements, fire the "loaded" event. This will
  343. // let apps know they can use the UI library programmatically now, even if
  344. // they didn't have any Shaka-related elements declared in their HTML.
  345. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-loaded');
  346. }
  347. /**
  348. * @param {string} eventName
  349. * @param {shaka.ui.Overlay.FailReasonCode=} reasonCode
  350. * @private
  351. */
  352. static dispatchLoadedEvent_(eventName, reasonCode) {
  353. let detail = null;
  354. if (reasonCode != undefined) {
  355. detail = {
  356. 'reasonCode': reasonCode,
  357. };
  358. }
  359. const uiLoadedEvent = new CustomEvent(eventName, {detail});
  360. document.dispatchEvent(uiLoadedEvent);
  361. }
  362. /**
  363. * @param {!Element} container
  364. * @param {!Element} video
  365. * @param {!Element} lcevcCanvas
  366. * @param {!Element} vrCanvas
  367. * @private
  368. */
  369. static async setupUIandAutoLoad_(container, video, lcevcCanvas, vrCanvas) {
  370. // Create the UI
  371. const player = new shaka.Player();
  372. const ui = new shaka.ui.Overlay(player,
  373. shaka.util.Dom.asHTMLElement(container),
  374. shaka.util.Dom.asHTMLMediaElement(video),
  375. shaka.util.Dom.asHTMLCanvasElement(vrCanvas));
  376. // Attach Canvas used for LCEVC Decoding
  377. player.attachCanvas(/** @type {HTMLCanvasElement} */(lcevcCanvas));
  378. // Get and configure cast app id.
  379. let castAppId = '';
  380. // Get and configure cast Android Receiver Compatibility
  381. let castAndroidReceiverCompatible = false;
  382. // Cast receiver id can be specified on either container or video.
  383. // It should not be provided on both. If it was, we will use the last
  384. // one we saw.
  385. if (container['dataset'] &&
  386. container['dataset']['shakaPlayerCastReceiverId']) {
  387. castAppId = container['dataset']['shakaPlayerCastReceiverId'];
  388. castAndroidReceiverCompatible =
  389. container['dataset']['shakaPlayerCastAndroidReceiverCompatible'] ===
  390. 'true';
  391. } else if (video['dataset'] &&
  392. video['dataset']['shakaPlayerCastReceiverId']) {
  393. castAppId = video['dataset']['shakaPlayerCastReceiverId'];
  394. castAndroidReceiverCompatible =
  395. video['dataset']['shakaPlayerCastAndroidReceiverCompatible'] === 'true';
  396. }
  397. if (castAppId.length) {
  398. ui.configure({castReceiverAppId: castAppId,
  399. castAndroidReceiverCompatible: castAndroidReceiverCompatible});
  400. }
  401. if (shaka.util.Dom.asHTMLMediaElement(video).controls) {
  402. ui.getControls().setEnabledNativeControls(true);
  403. }
  404. // Get the source and load it
  405. // Source can be specified either on the video element:
  406. // <video src='foo.m2u8'></video>
  407. // or as a separate element inside the video element:
  408. // <video>
  409. // <source src='foo.m2u8'/>
  410. // </video>
  411. // It should not be specified on both.
  412. const src = video.getAttribute('src');
  413. if (src) {
  414. const sourceElem = document.createElement('source');
  415. sourceElem.setAttribute('src', src);
  416. video.appendChild(sourceElem);
  417. video.removeAttribute('src');
  418. }
  419. for (const elem of video.querySelectorAll('source')) {
  420. try { // eslint-disable-next-line no-await-in-loop
  421. await ui.getControls().getPlayer().load(elem.getAttribute('src'));
  422. break;
  423. } catch (e) {
  424. shaka.log.error('Error auto-loading asset', e);
  425. }
  426. }
  427. await player.attach(shaka.util.Dom.asHTMLMediaElement(video));
  428. }
  429. /**
  430. * @param {!Element} container
  431. * @param {!NodeList.<!Element>} canvases
  432. * @param {!NodeList.<!Element>} vrCanvases
  433. * @return {{lcevcCanvas: !Element, vrCanvas: !Element}}
  434. * @private
  435. */
  436. static findOrMakeSpecialCanvases_(container, canvases, vrCanvases) {
  437. let lcevcCanvas = null;
  438. for (const canvas of canvases) {
  439. goog.asserts.assert(canvas.tagName.toLowerCase() == 'canvas',
  440. 'Should be a canvas element!');
  441. if (canvas.parentElement == container) {
  442. lcevcCanvas = canvas;
  443. break;
  444. }
  445. }
  446. if (!lcevcCanvas) {
  447. lcevcCanvas = document.createElement('canvas');
  448. lcevcCanvas.classList.add('shaka-canvas-container');
  449. container.appendChild(lcevcCanvas);
  450. }
  451. let vrCanvas = null;
  452. for (const canvas of vrCanvases) {
  453. goog.asserts.assert(canvas.tagName.toLowerCase() == 'canvas',
  454. 'Should be a canvas element!');
  455. if (canvas.parentElement == container) {
  456. vrCanvas = canvas;
  457. break;
  458. }
  459. }
  460. if (!vrCanvas) {
  461. vrCanvas = document.createElement('canvas');
  462. vrCanvas.classList.add('shaka-vr-canvas-container');
  463. container.appendChild(vrCanvas);
  464. }
  465. return {
  466. lcevcCanvas,
  467. vrCanvas,
  468. };
  469. }
  470. };
  471. /**
  472. * Describes what information should show up in labels for selecting audio
  473. * variants and text tracks.
  474. *
  475. * @enum {number}
  476. * @export
  477. */
  478. shaka.ui.Overlay.TrackLabelFormat = {
  479. 'LANGUAGE': 0,
  480. 'ROLE': 1,
  481. 'LANGUAGE_ROLE': 2,
  482. 'LABEL': 3,
  483. };
  484. /**
  485. * Describes the possible reasons that the UI might fail to load.
  486. *
  487. * @enum {number}
  488. * @export
  489. */
  490. shaka.ui.Overlay.FailReasonCode = {
  491. 'NO_BROWSER_SUPPORT': 0,
  492. 'PLAYER_FAILED_TO_LOAD': 1,
  493. };
  494. if (document.readyState == 'complete') {
  495. // Don't fire this event synchronously. In a compiled bundle, the "shaka"
  496. // namespace might not be exported to the window until after this point.
  497. (async () => {
  498. await Promise.resolve();
  499. shaka.ui.Overlay.scanPageForShakaElements_();
  500. })();
  501. } else {
  502. window.addEventListener('load', shaka.ui.Overlay.scanPageForShakaElements_);
  503. }