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. 'save_video_frame',
  162. ],
  163. statisticsList: [
  164. 'width',
  165. 'height',
  166. 'corruptedFrames',
  167. 'decodedFrames',
  168. 'droppedFrames',
  169. 'drmTimeSeconds',
  170. 'licenseTime',
  171. 'liveLatency',
  172. 'loadLatency',
  173. 'bufferingTime',
  174. 'manifestTimeSeconds',
  175. 'estimatedBandwidth',
  176. 'streamBandwidth',
  177. 'maxSegmentDuration',
  178. 'pauseTime',
  179. 'playTime',
  180. 'completionPercent',
  181. 'manifestSizeBytes',
  182. 'bytesDownloaded',
  183. 'nonFatalErrorCount',
  184. 'manifestPeriodCount',
  185. 'manifestGapCount',
  186. ],
  187. adStatisticsList: [
  188. 'loadTimes',
  189. 'averageLoadTime',
  190. 'started',
  191. 'playedCompletely',
  192. 'skipped',
  193. 'errors',
  194. ],
  195. contextMenuElements: [
  196. 'loop',
  197. 'picture_in_picture',
  198. 'save_video_frame',
  199. 'statistics',
  200. 'ad_statistics',
  201. ],
  202. playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
  203. fastForwardRates: [2, 4, 8, 1],
  204. rewindRates: [-1, -2, -4, -8],
  205. addSeekBar: true,
  206. addBigPlayButton: false,
  207. customContextMenu: false,
  208. castReceiverAppId: '',
  209. castAndroidReceiverCompatible: false,
  210. clearBufferOnQualityChange: true,
  211. showUnbufferedStart: false,
  212. seekBarColors: {
  213. base: 'rgba(255, 255, 255, 0.3)',
  214. buffered: 'rgba(255, 255, 255, 0.54)',
  215. played: 'rgb(255, 255, 255)',
  216. adBreaks: 'rgb(255, 204, 0)',
  217. },
  218. volumeBarColors: {
  219. base: 'rgba(255, 255, 255, 0.54)',
  220. level: 'rgb(255, 255, 255)',
  221. },
  222. trackLabelFormat: shaka.ui.Overlay.TrackLabelFormat.LANGUAGE,
  223. textTrackLabelFormat: shaka.ui.Overlay.TrackLabelFormat.LANGUAGE,
  224. fadeDelay: 0,
  225. doubleClickForFullscreen: true,
  226. singleClickForPlayAndPause: true,
  227. enableKeyboardPlaybackControls: true,
  228. enableFullscreenOnRotation: true,
  229. forceLandscapeOnFullscreen: true,
  230. enableTooltips: false,
  231. keyboardSeekDistance: 5,
  232. keyboardLargeSeekDistance: 60,
  233. fullScreenElement: this.videoContainer_,
  234. preferDocumentPictureInPicture: true,
  235. showAudioChannelCountVariants: true,
  236. seekOnTaps: true,
  237. tapSeekDistance: 10,
  238. refreshTickInSeconds: 0.125,
  239. displayInVrMode: false,
  240. defaultVrProjectionMode: 'equirectangular',
  241. };
  242. // eslint-disable-next-line no-restricted-syntax
  243. if ('remote' in HTMLMediaElement.prototype) {
  244. config.overflowMenuButtons.push('remote');
  245. } else if (window.WebKitPlaybackTargetAvailabilityEvent) {
  246. config.overflowMenuButtons.push('airplay');
  247. }
  248. // On mobile, by default, hide the volume slide and the small play/pause
  249. // button and show the big play/pause button in the center.
  250. // This is in line with default styles in Chrome.
  251. if (this.isMobile()) {
  252. config.addBigPlayButton = true;
  253. config.controlPanelElements = config.controlPanelElements.filter(
  254. (name) => name != 'play_pause' && name != 'volume');
  255. }
  256. return config;
  257. }
  258. /**
  259. * @private
  260. */
  261. static async scanPageForShakaElements_() {
  262. // Install built-in polyfills to patch browser incompatibilities.
  263. shaka.polyfill.installAll();
  264. // Check to see if the browser supports the basic APIs Shaka needs.
  265. if (!shaka.Player.isBrowserSupported()) {
  266. shaka.log.error('Shaka Player does not support this browser. ' +
  267. 'Please see https://tinyurl.com/y7s4j9tr for the list of ' +
  268. 'supported browsers.');
  269. // After scanning the page for elements, fire a special "loaded" event for
  270. // when the load fails. This will allow the page to react to the failure.
  271. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-load-failed',
  272. shaka.ui.Overlay.FailReasonCode.NO_BROWSER_SUPPORT);
  273. return;
  274. }
  275. // Look for elements marked 'data-shaka-player-container'
  276. // on the page. These will be used to create our default
  277. // UI.
  278. const containers = document.querySelectorAll(
  279. '[data-shaka-player-container]');
  280. // Look for elements marked 'data-shaka-player'. They will
  281. // either be used in our default UI or with native browser
  282. // controls.
  283. const videos = document.querySelectorAll(
  284. '[data-shaka-player]');
  285. // Look for elements marked 'data-shaka-player-canvas'
  286. // on the page. These will be used to create our default
  287. // UI.
  288. const canvases = document.querySelectorAll(
  289. '[data-shaka-player-canvas]');
  290. // Look for elements marked 'data-shaka-player-vr-canvas'
  291. // on the page. These will be used to create our default
  292. // UI.
  293. const vrCanvases = document.querySelectorAll(
  294. '[data-shaka-player-vr-canvas]');
  295. if (!videos.length && !containers.length) {
  296. // No elements have been tagged with shaka attributes.
  297. } else if (videos.length && !containers.length) {
  298. // Just the video elements were provided.
  299. for (const video of videos) {
  300. // If the app has already manually created a UI for this element,
  301. // don't create another one.
  302. if (video['ui']) {
  303. continue;
  304. }
  305. goog.asserts.assert(video.tagName.toLowerCase() == 'video',
  306. 'Should be a video element!');
  307. const container = document.createElement('div');
  308. const videoParent = video.parentElement;
  309. videoParent.replaceChild(container, video);
  310. container.appendChild(video);
  311. const {lcevcCanvas, vrCanvas} =
  312. shaka.ui.Overlay.findOrMakeSpecialCanvases_(
  313. container, canvases, vrCanvases);
  314. shaka.ui.Overlay.setupUIandAutoLoad_(
  315. container, video, lcevcCanvas, vrCanvas);
  316. }
  317. } else {
  318. for (const container of containers) {
  319. // If the app has already manually created a UI for this element,
  320. // don't create another one.
  321. if (container['ui']) {
  322. continue;
  323. }
  324. goog.asserts.assert(container.tagName.toLowerCase() == 'div',
  325. 'Container should be a div!');
  326. let currentVideo = null;
  327. for (const video of videos) {
  328. goog.asserts.assert(video.tagName.toLowerCase() == 'video',
  329. 'Should be a video element!');
  330. if (video.parentElement == container) {
  331. currentVideo = video;
  332. break;
  333. }
  334. }
  335. if (!currentVideo) {
  336. currentVideo = document.createElement('video');
  337. currentVideo.setAttribute('playsinline', '');
  338. container.appendChild(currentVideo);
  339. }
  340. const {lcevcCanvas, vrCanvas} =
  341. shaka.ui.Overlay.findOrMakeSpecialCanvases_(
  342. container, canvases, vrCanvases);
  343. try {
  344. // eslint-disable-next-line no-await-in-loop
  345. await shaka.ui.Overlay.setupUIandAutoLoad_(
  346. container, currentVideo, lcevcCanvas, vrCanvas);
  347. } catch (e) {
  348. // This can fail if, for example, not every player file has loaded.
  349. // Ad-block is a likely cause for this sort of failure.
  350. shaka.log.error('Error setting up Shaka Player', e);
  351. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-load-failed',
  352. shaka.ui.Overlay.FailReasonCode.PLAYER_FAILED_TO_LOAD);
  353. return;
  354. }
  355. }
  356. }
  357. // After scanning the page for elements, fire the "loaded" event. This will
  358. // let apps know they can use the UI library programmatically now, even if
  359. // they didn't have any Shaka-related elements declared in their HTML.
  360. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-loaded');
  361. }
  362. /**
  363. * @param {string} eventName
  364. * @param {shaka.ui.Overlay.FailReasonCode=} reasonCode
  365. * @private
  366. */
  367. static dispatchLoadedEvent_(eventName, reasonCode) {
  368. let detail = null;
  369. if (reasonCode != undefined) {
  370. detail = {
  371. 'reasonCode': reasonCode,
  372. };
  373. }
  374. const uiLoadedEvent = new CustomEvent(eventName, {detail});
  375. document.dispatchEvent(uiLoadedEvent);
  376. }
  377. /**
  378. * @param {!Element} container
  379. * @param {!Element} video
  380. * @param {!Element} lcevcCanvas
  381. * @param {!Element} vrCanvas
  382. * @private
  383. */
  384. static async setupUIandAutoLoad_(container, video, lcevcCanvas, vrCanvas) {
  385. // Create the UI
  386. const player = new shaka.Player();
  387. const ui = new shaka.ui.Overlay(player,
  388. shaka.util.Dom.asHTMLElement(container),
  389. shaka.util.Dom.asHTMLMediaElement(video),
  390. shaka.util.Dom.asHTMLCanvasElement(vrCanvas));
  391. // Attach Canvas used for LCEVC Decoding
  392. player.attachCanvas(/** @type {HTMLCanvasElement} */(lcevcCanvas));
  393. // Get and configure cast app id.
  394. let castAppId = '';
  395. // Get and configure cast Android Receiver Compatibility
  396. let castAndroidReceiverCompatible = false;
  397. // Cast receiver id can be specified on either container or video.
  398. // It should not be provided on both. If it was, we will use the last
  399. // one we saw.
  400. if (container['dataset'] &&
  401. container['dataset']['shakaPlayerCastReceiverId']) {
  402. castAppId = container['dataset']['shakaPlayerCastReceiverId'];
  403. castAndroidReceiverCompatible =
  404. container['dataset']['shakaPlayerCastAndroidReceiverCompatible'] ===
  405. 'true';
  406. } else if (video['dataset'] &&
  407. video['dataset']['shakaPlayerCastReceiverId']) {
  408. castAppId = video['dataset']['shakaPlayerCastReceiverId'];
  409. castAndroidReceiverCompatible =
  410. video['dataset']['shakaPlayerCastAndroidReceiverCompatible'] === 'true';
  411. }
  412. if (castAppId.length) {
  413. ui.configure({castReceiverAppId: castAppId,
  414. castAndroidReceiverCompatible: castAndroidReceiverCompatible});
  415. }
  416. if (shaka.util.Dom.asHTMLMediaElement(video).controls) {
  417. ui.getControls().setEnabledNativeControls(true);
  418. }
  419. // Get the source and load it
  420. // Source can be specified either on the video element:
  421. // <video src='foo.m2u8'></video>
  422. // or as a separate element inside the video element:
  423. // <video>
  424. // <source src='foo.m2u8'/>
  425. // </video>
  426. // It should not be specified on both.
  427. const src = video.getAttribute('src');
  428. if (src) {
  429. const sourceElem = document.createElement('source');
  430. sourceElem.setAttribute('src', src);
  431. video.appendChild(sourceElem);
  432. video.removeAttribute('src');
  433. }
  434. for (const elem of video.querySelectorAll('source')) {
  435. try { // eslint-disable-next-line no-await-in-loop
  436. await ui.getControls().getPlayer().load(elem.getAttribute('src'));
  437. break;
  438. } catch (e) {
  439. shaka.log.error('Error auto-loading asset', e);
  440. }
  441. }
  442. await player.attach(shaka.util.Dom.asHTMLMediaElement(video));
  443. }
  444. /**
  445. * @param {!Element} container
  446. * @param {!NodeList.<!Element>} canvases
  447. * @param {!NodeList.<!Element>} vrCanvases
  448. * @return {{lcevcCanvas: !Element, vrCanvas: !Element}}
  449. * @private
  450. */
  451. static findOrMakeSpecialCanvases_(container, canvases, vrCanvases) {
  452. let lcevcCanvas = null;
  453. for (const canvas of canvases) {
  454. goog.asserts.assert(canvas.tagName.toLowerCase() == 'canvas',
  455. 'Should be a canvas element!');
  456. if (canvas.parentElement == container) {
  457. lcevcCanvas = canvas;
  458. break;
  459. }
  460. }
  461. if (!lcevcCanvas) {
  462. lcevcCanvas = document.createElement('canvas');
  463. lcevcCanvas.classList.add('shaka-canvas-container');
  464. container.appendChild(lcevcCanvas);
  465. }
  466. let vrCanvas = null;
  467. for (const canvas of vrCanvases) {
  468. goog.asserts.assert(canvas.tagName.toLowerCase() == 'canvas',
  469. 'Should be a canvas element!');
  470. if (canvas.parentElement == container) {
  471. vrCanvas = canvas;
  472. break;
  473. }
  474. }
  475. if (!vrCanvas) {
  476. vrCanvas = document.createElement('canvas');
  477. vrCanvas.classList.add('shaka-vr-canvas-container');
  478. container.appendChild(vrCanvas);
  479. }
  480. return {
  481. lcevcCanvas,
  482. vrCanvas,
  483. };
  484. }
  485. };
  486. /**
  487. * Describes what information should show up in labels for selecting audio
  488. * variants and text tracks.
  489. *
  490. * @enum {number}
  491. * @export
  492. */
  493. shaka.ui.Overlay.TrackLabelFormat = {
  494. 'LANGUAGE': 0,
  495. 'ROLE': 1,
  496. 'LANGUAGE_ROLE': 2,
  497. 'LABEL': 3,
  498. };
  499. /**
  500. * Describes the possible reasons that the UI might fail to load.
  501. *
  502. * @enum {number}
  503. * @export
  504. */
  505. shaka.ui.Overlay.FailReasonCode = {
  506. 'NO_BROWSER_SUPPORT': 0,
  507. 'PLAYER_FAILED_TO_LOAD': 1,
  508. };
  509. if (document.readyState == 'complete') {
  510. // Don't fire this event synchronously. In a compiled bundle, the "shaka"
  511. // namespace might not be exported to the window until after this point.
  512. (async () => {
  513. await Promise.resolve();
  514. shaka.ui.Overlay.scanPageForShakaElements_();
  515. })();
  516. } else {
  517. window.addEventListener('load', shaka.ui.Overlay.scanPageForShakaElements_);
  518. }