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