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