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. */
  29. constructor(player, videoContainer, video) {
  30. /** @private {shaka.Player} */
  31. this.player_ = player;
  32. /** @private {!shaka.extern.UIConfiguration} */
  33. this.config_ = this.defaultConfig_();
  34. // Make sure this container is discoverable and that the UI can be reached
  35. // through it.
  36. videoContainer['dataset']['shakaPlayerContainer'] = '';
  37. videoContainer['ui'] = this;
  38. // Tag the container for mobile platforms, to allow different styles.
  39. if (this.isMobile()) {
  40. videoContainer.classList.add('shaka-mobile');
  41. }
  42. /** @private {shaka.ui.Controls} */
  43. this.controls_ = new shaka.ui.Controls(
  44. player, videoContainer, video, this.config_);
  45. // Run the initial setup so that no configure() call is required for default
  46. // settings.
  47. this.configure({});
  48. // If the browser's native controls are disabled, use UI TextDisplayer.
  49. if (!video.controls) {
  50. player.setVideoContainer(videoContainer);
  51. }
  52. videoContainer['ui'] = this;
  53. video['ui'] = this;
  54. }
  55. /**
  56. * @override
  57. * @export
  58. */
  59. async destroy() {
  60. if (this.controls_) {
  61. await this.controls_.destroy();
  62. }
  63. this.controls_ = null;
  64. if (this.player_) {
  65. await this.player_.destroy();
  66. }
  67. this.player_ = null;
  68. }
  69. /**
  70. * Detects if this is a mobile platform, in case you want to choose a
  71. * different UI configuration on mobile devices.
  72. *
  73. * @return {boolean}
  74. * @export
  75. */
  76. isMobile() {
  77. return shaka.util.Platform.isMobile();
  78. }
  79. /**
  80. * @return {!shaka.extern.UIConfiguration}
  81. * @export
  82. */
  83. getConfiguration() {
  84. const ret = this.defaultConfig_();
  85. shaka.util.ConfigUtils.mergeConfigObjects(
  86. ret, this.config_, this.defaultConfig_(),
  87. /* overrides= */ {}, /* path= */ '');
  88. return ret;
  89. }
  90. /**
  91. * @param {string|!Object} config This should either be a field name or an
  92. * object following the form of {@link shaka.extern.UIConfiguration}, where
  93. * you may omit any field you do not wish to change.
  94. * @param {*=} value This should be provided if the previous parameter
  95. * was a string field name.
  96. * @export
  97. */
  98. configure(config, value) {
  99. goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
  100. 'String configs should have values!');
  101. // ('fieldName', value) format
  102. if (arguments.length == 2 && typeof(config) == 'string') {
  103. config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
  104. }
  105. goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
  106. shaka.util.ConfigUtils.mergeConfigObjects(
  107. this.config_, config, this.defaultConfig_(),
  108. /* overrides= */ {}, /* path= */ '');
  109. // If a cast receiver app id has been given, add a cast button to the UI
  110. if (this.config_.castReceiverAppId &&
  111. !this.config_.overflowMenuButtons.includes('cast')) {
  112. this.config_.overflowMenuButtons.push('cast');
  113. }
  114. goog.asserts.assert(this.player_ != null, 'Should have a player!');
  115. this.controls_.configure(this.config_);
  116. this.controls_.dispatchEvent(new shaka.util.FakeEvent('uiupdated'));
  117. }
  118. /**
  119. * @return {shaka.ui.Controls}
  120. * @export
  121. */
  122. getControls() {
  123. return this.controls_;
  124. }
  125. /**
  126. * Enable or disable the custom controls.
  127. *
  128. * @param {boolean} enabled
  129. * @export
  130. */
  131. setEnabled(enabled) {
  132. this.controls_.setEnabledShakaControls(enabled);
  133. }
  134. /**
  135. * @return {!shaka.extern.UIConfiguration}
  136. * @private
  137. */
  138. defaultConfig_() {
  139. const config = {
  140. controlPanelElements: [
  141. 'play_pause',
  142. 'time_and_duration',
  143. 'spacer',
  144. 'mute',
  145. 'volume',
  146. 'fullscreen',
  147. 'overflow_menu',
  148. ],
  149. overflowMenuButtons: [
  150. 'captions',
  151. 'quality',
  152. 'language',
  153. 'picture_in_picture',
  154. 'cast',
  155. 'playback_rate',
  156. ],
  157. addSeekBar: true,
  158. addBigPlayButton: false,
  159. castReceiverAppId: '',
  160. clearBufferOnQualityChange: true,
  161. showUnbufferedStart: false,
  162. seekBarColors: {
  163. base: 'rgba(255, 255, 255, 0.3)',
  164. buffered: 'rgba(255, 255, 255, 0.54)',
  165. played: 'rgb(255, 255, 255)',
  166. adBreaks: 'rgb(255, 204, 0)',
  167. },
  168. volumeBarColors: {
  169. base: 'rgba(255, 255, 255, 0.54)',
  170. level: 'rgb(255, 255, 255)',
  171. },
  172. trackLabelFormat: shaka.ui.Overlay.TrackLabelFormat.LANGUAGE,
  173. fadeDelay: 0,
  174. doubleClickForFullscreen: true,
  175. enableKeyboardPlaybackControls: true,
  176. enableFullscreenOnRotation: true,
  177. forceLandscapeOnFullscreen: true,
  178. };
  179. // Check AirPlay support
  180. if (window.WebKitPlaybackTargetAvailabilityEvent) {
  181. config.overflowMenuButtons.push('airplay');
  182. }
  183. // On mobile, by default, hide the volume slide and the small play/pause
  184. // button and show the big play/pause button in the center.
  185. // This is in line with default styles in Chrome.
  186. if (this.isMobile()) {
  187. config.addBigPlayButton = true;
  188. config.controlPanelElements = config.controlPanelElements.filter(
  189. (name) => name != 'play_pause' && name != 'volume');
  190. }
  191. return config;
  192. }
  193. /**
  194. * @private
  195. */
  196. static async scanPageForShakaElements_() {
  197. // Install built-in polyfills to patch browser incompatibilities.
  198. shaka.polyfill.installAll();
  199. // Check to see if the browser supports the basic APIs Shaka needs.
  200. if (!shaka.Player.isBrowserSupported()) {
  201. shaka.log.error('Shaka Player does not support this browser. ' +
  202. 'Please see https://tinyurl.com/y7s4j9tr for the list of ' +
  203. 'supported browsers.');
  204. // After scanning the page for elements, fire a special "loaded" event for
  205. // when the load fails. This will allow the page to react to the failure.
  206. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-load-failed',
  207. shaka.ui.Overlay.FailReasonCode.NO_BROWSER_SUPPORT);
  208. return;
  209. }
  210. // Look for elements marked 'data-shaka-player-container'
  211. // on the page. These will be used to create our default
  212. // UI.
  213. const containers = document.querySelectorAll(
  214. '[data-shaka-player-container]');
  215. // Look for elements marked 'data-shaka-player'. They will
  216. // either be used in our default UI or with native browser
  217. // controls.
  218. const videos = document.querySelectorAll(
  219. '[data-shaka-player]');
  220. if (!videos.length && !containers.length) {
  221. // No elements have been tagged with shaka attributes.
  222. } else if (videos.length && !containers.length) {
  223. // Just the video elements were provided.
  224. for (const video of videos) {
  225. // If the app has already manually created a UI for this element,
  226. // don't create another one.
  227. if (video['ui']) {
  228. continue;
  229. }
  230. goog.asserts.assert(video.tagName.toLowerCase() == 'video',
  231. 'Should be a video element!');
  232. const container = document.createElement('div');
  233. const videoParent = video.parentElement;
  234. videoParent.replaceChild(container, video);
  235. container.appendChild(video);
  236. shaka.ui.Overlay.setupUIandAutoLoad_(container, video);
  237. }
  238. } else {
  239. for (const container of containers) {
  240. // If the app has already manually created a UI for this element,
  241. // don't create another one.
  242. if (container['ui']) {
  243. continue;
  244. }
  245. goog.asserts.assert(container.tagName.toLowerCase() == 'div',
  246. 'Container should be a div!');
  247. let currentVideo = null;
  248. for (const video of videos) {
  249. goog.asserts.assert(video.tagName.toLowerCase() == 'video',
  250. 'Should be a video element!');
  251. if (video.parentElement == container) {
  252. currentVideo = video;
  253. break;
  254. }
  255. }
  256. if (!currentVideo) {
  257. currentVideo = document.createElement('video');
  258. currentVideo.setAttribute('playsinline', '');
  259. container.appendChild(currentVideo);
  260. }
  261. try {
  262. // eslint-disable-next-line no-await-in-loop
  263. await shaka.ui.Overlay.setupUIandAutoLoad_(container, currentVideo);
  264. } catch (e) {
  265. // This can fail if, for example, not every player file has loaded.
  266. // Ad-block is a likely cause for this sort of failure.
  267. shaka.log.error('Error setting up Shaka Player', e);
  268. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-load-failed',
  269. shaka.ui.Overlay.FailReasonCode.PLAYER_FAILED_TO_LOAD);
  270. return;
  271. }
  272. }
  273. }
  274. // After scanning the page for elements, fire the "loaded" event. This will
  275. // let apps know they can use the UI library programmatically now, even if
  276. // they didn't have any Shaka-related elements declared in their HTML.
  277. shaka.ui.Overlay.dispatchLoadedEvent_('shaka-ui-loaded');
  278. }
  279. /**
  280. * @param {string} eventName
  281. * @param {shaka.ui.Overlay.FailReasonCode=} reasonCode
  282. * @private
  283. */
  284. static dispatchLoadedEvent_(eventName, reasonCode) {
  285. let detail = null;
  286. if (reasonCode != undefined) {
  287. detail = {
  288. 'reasonCode': reasonCode,
  289. };
  290. }
  291. const uiLoadedEvent = new CustomEvent(eventName, {detail});
  292. document.dispatchEvent(uiLoadedEvent);
  293. }
  294. /**
  295. * @param {!Element} container
  296. * @param {!Element} video
  297. * @private
  298. */
  299. static async setupUIandAutoLoad_(container, video) {
  300. // Create the UI
  301. const player = new shaka.Player(
  302. shaka.util.Dom.asHTMLMediaElement(video));
  303. const ui = new shaka.ui.Overlay(player,
  304. shaka.util.Dom.asHTMLElement(container),
  305. shaka.util.Dom.asHTMLMediaElement(video));
  306. // Get and configure cast app id.
  307. let castAppId = '';
  308. // Cast receiver id can be specified on either container or video.
  309. // It should not be provided on both. If it was, we will use the last
  310. // one we saw.
  311. if (container['dataset'] &&
  312. container['dataset']['shakaPlayerCastReceiverId']) {
  313. castAppId = container['dataset']['shakaPlayerCastReceiverId'];
  314. } else if (video['dataset'] &&
  315. video['dataset']['shakaPlayerCastReceiverId']) {
  316. castAppId = video['dataset']['shakaPlayerCastReceiverId'];
  317. }
  318. if (castAppId.length) {
  319. ui.configure({castReceiverAppId: castAppId});
  320. }
  321. if (shaka.util.Dom.asHTMLMediaElement(video).controls) {
  322. ui.getControls().setEnabledNativeControls(true);
  323. }
  324. // Get the source and load it
  325. // Source can be specified either on the video element:
  326. // <video src='foo.m2u8'></video>
  327. // or as a separate element inside the video element:
  328. // <video>
  329. // <source src='foo.m2u8'/>
  330. // </video>
  331. // It should not be specified on both.
  332. const src = video.getAttribute('src');
  333. if (src) {
  334. const sourceElem = document.createElement('source');
  335. sourceElem.setAttribute('src', src);
  336. video.appendChild(sourceElem);
  337. video.removeAttribute('src');
  338. }
  339. for (const elem of video.querySelectorAll('source')) {
  340. try { // eslint-disable-next-line no-await-in-loop
  341. await ui.getControls().getPlayer().load(elem.getAttribute('src'));
  342. break;
  343. } catch (e) {
  344. shaka.log.error('Error auto-loading asset', e);
  345. }
  346. }
  347. }
  348. };
  349. /**
  350. * Describes what information should show up in labels for selecting audio
  351. * variants and text tracks.
  352. *
  353. * @enum {number}
  354. * @export
  355. */
  356. shaka.ui.Overlay.TrackLabelFormat = {
  357. 'LANGUAGE': 0,
  358. 'ROLE': 1,
  359. 'LANGUAGE_ROLE': 2,
  360. 'LABEL': 3,
  361. };
  362. /*
  363. * "shaka.ui.TrackLabelFormat" is deprecated and will be removed in v4.
  364. *
  365. * @deprecated
  366. * @enum {number}
  367. */
  368. shaka.ui.TrackLabelFormat = shaka.ui.Overlay.TrackLabelFormat;
  369. /**
  370. * Describes the possible reasons that the UI might fail to load.
  371. *
  372. * @enum {number}
  373. * @export
  374. */
  375. shaka.ui.Overlay.FailReasonCode = {
  376. 'NO_BROWSER_SUPPORT': 0,
  377. 'PLAYER_FAILED_TO_LOAD': 1,
  378. };
  379. /**
  380. * "shaka.ui.FailReasonCode" is deprecated and will be removed in v4.
  381. *
  382. * @deprecated
  383. * @enum {number}
  384. */
  385. shaka.ui.FailReasonCode = shaka.ui.Overlay.FailReasonCode;
  386. if (document.readyState == 'complete') {
  387. // Don't fire this event synchronously. In a compiled bundle, the "shaka"
  388. // namespace might not be exported to the window until after this point.
  389. (async () => {
  390. await Promise.resolve();
  391. shaka.ui.Overlay.scanPageForShakaElements_();
  392. })();
  393. } else {
  394. window.addEventListener('load', shaka.ui.Overlay.scanPageForShakaElements_);
  395. }