Source: ui/controls.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.ui.Controls');
  7. goog.provide('shaka.ui.ControlsPanel');
  8. goog.require('goog.asserts');
  9. goog.require('shaka.ads.Utils');
  10. goog.require('shaka.cast.CastProxy');
  11. goog.require('shaka.log');
  12. goog.require('shaka.ui.AdCounter');
  13. goog.require('shaka.ui.AdPosition');
  14. goog.require('shaka.ui.BigPlayButton');
  15. goog.require('shaka.ui.ContextMenu');
  16. goog.require('shaka.ui.HiddenFastForwardButton');
  17. goog.require('shaka.ui.HiddenRewindButton');
  18. goog.require('shaka.ui.Locales');
  19. goog.require('shaka.ui.Localization');
  20. goog.require('shaka.ui.SeekBar');
  21. goog.require('shaka.ui.SkipAdButton');
  22. goog.require('shaka.ui.Utils');
  23. goog.require('shaka.ui.VRManager');
  24. goog.require('shaka.util.Dom');
  25. goog.require('shaka.util.EventManager');
  26. goog.require('shaka.util.FakeEvent');
  27. goog.require('shaka.util.FakeEventTarget');
  28. goog.require('shaka.util.IDestroyable');
  29. goog.require('shaka.util.Timer');
  30. goog.requireType('shaka.Player');
  31. /**
  32. * A container for custom video controls.
  33. * @implements {shaka.util.IDestroyable}
  34. * @export
  35. */
  36. shaka.ui.Controls = class extends shaka.util.FakeEventTarget {
  37. /**
  38. * @param {!shaka.Player} player
  39. * @param {!HTMLElement} videoContainer
  40. * @param {!HTMLMediaElement} video
  41. * @param {?HTMLCanvasElement} vrCanvas
  42. * @param {shaka.extern.UIConfiguration} config
  43. */
  44. constructor(player, videoContainer, video, vrCanvas, config) {
  45. super();
  46. /** @private {boolean} */
  47. this.enabled_ = true;
  48. /** @private {shaka.extern.UIConfiguration} */
  49. this.config_ = config;
  50. /** @private {shaka.cast.CastProxy} */
  51. this.castProxy_ = new shaka.cast.CastProxy(
  52. video, player, this.config_.castReceiverAppId,
  53. this.config_.castAndroidReceiverCompatible);
  54. /** @private {boolean} */
  55. this.castAllowed_ = true;
  56. /** @private {HTMLMediaElement} */
  57. this.video_ = this.castProxy_.getVideo();
  58. /** @private {HTMLMediaElement} */
  59. this.localVideo_ = video;
  60. /** @private {shaka.Player} */
  61. this.player_ = this.castProxy_.getPlayer();
  62. /** @private {shaka.Player} */
  63. this.localPlayer_ = player;
  64. /** @private {!HTMLElement} */
  65. this.videoContainer_ = videoContainer;
  66. /** @private {?HTMLCanvasElement} */
  67. this.vrCanvas_ = vrCanvas;
  68. /** @private {shaka.extern.IAdManager} */
  69. this.adManager_ = this.player_.getAdManager();
  70. /** @private {?shaka.extern.IAd} */
  71. this.ad_ = null;
  72. /** @private {?shaka.extern.IUISeekBar} */
  73. this.seekBar_ = null;
  74. /** @private {boolean} */
  75. this.isSeeking_ = false;
  76. /** @private {!Array.<!HTMLElement>} */
  77. this.menus_ = [];
  78. /**
  79. * Individual controls which, when hovered or tab-focused, will force the
  80. * controls to be shown.
  81. * @private {!Array.<!Element>}
  82. */
  83. this.showOnHoverControls_ = [];
  84. /** @private {boolean} */
  85. this.recentMouseMovement_ = false;
  86. /**
  87. * This timer is used to detect when the user has stopped moving the mouse
  88. * and we should fade out the ui.
  89. *
  90. * @private {shaka.util.Timer}
  91. */
  92. this.mouseStillTimer_ = new shaka.util.Timer(() => {
  93. this.onMouseStill_();
  94. });
  95. /**
  96. * This timer is used to delay the fading of the UI.
  97. *
  98. * @private {shaka.util.Timer}
  99. */
  100. this.fadeControlsTimer_ = new shaka.util.Timer(() => {
  101. this.controlsContainer_.removeAttribute('shown');
  102. // If there's an overflow menu open, keep it this way for a couple of
  103. // seconds in case a user immediately initiates another mouse move to
  104. // interact with the menus. If that didn't happen, go ahead and hide
  105. // the menus.
  106. this.hideSettingsMenusTimer_.tickAfter(/* seconds= */ 2);
  107. });
  108. /**
  109. * This timer will be used to hide all settings menus. When the timer ticks
  110. * it will force all controls to invisible.
  111. *
  112. * Rather than calling the callback directly, |Controls| will always call it
  113. * through the timer to avoid conflicts.
  114. *
  115. * @private {shaka.util.Timer}
  116. */
  117. this.hideSettingsMenusTimer_ = new shaka.util.Timer(() => {
  118. for (const menu of this.menus_) {
  119. shaka.ui.Utils.setDisplay(menu, /* visible= */ false);
  120. }
  121. });
  122. /**
  123. * This timer is used to regularly update the time and seek range elements
  124. * so that we are communicating the current state as accurately as possibly.
  125. *
  126. * Unlike the other timers, this timer does not "own" the callback because
  127. * this timer is acting like a heartbeat.
  128. *
  129. * @private {shaka.util.Timer}
  130. */
  131. this.timeAndSeekRangeTimer_ = new shaka.util.Timer(() => {
  132. // Suppress timer-based updates if the controls are hidden.
  133. if (this.isOpaque()) {
  134. this.updateTimeAndSeekRange_();
  135. }
  136. });
  137. /** @private {?number} */
  138. this.lastTouchEventTime_ = null;
  139. /** @private {!Array.<!shaka.extern.IUIElement>} */
  140. this.elements_ = [];
  141. /** @private {shaka.ui.Localization} */
  142. this.localization_ = shaka.ui.Controls.createLocalization_();
  143. /** @private {shaka.util.EventManager} */
  144. this.eventManager_ = new shaka.util.EventManager();
  145. /** @private {?shaka.ui.VRManager} */
  146. this.vr_ = null;
  147. // Configure and create the layout of the controls
  148. this.configure(this.config_);
  149. this.addEventListeners_();
  150. this.setupMediaSession_();
  151. /**
  152. * The pressed keys set is used to record which keys are currently pressed
  153. * down, so we can know what keys are pressed at the same time.
  154. * Used by the focusInsideOverflowMenu_() function.
  155. * @private {!Set.<string>}
  156. */
  157. this.pressedKeys_ = new Set();
  158. // We might've missed a caststatuschanged event from the proxy between
  159. // the controls creation and initializing. Run onCastStatusChange_()
  160. // to ensure we have the casting state right.
  161. this.onCastStatusChange_();
  162. // Start this timer after we are finished initializing everything,
  163. this.timeAndSeekRangeTimer_.tickEvery(this.config_.refreshTickInSeconds);
  164. this.eventManager_.listen(this.localization_,
  165. shaka.ui.Localization.LOCALE_CHANGED, (e) => {
  166. const locale = e['locales'][0];
  167. this.adManager_.setLocale(locale);
  168. });
  169. this.adManager_.initInterstitial(
  170. this.getClientSideAdContainer(), this.localPlayer_, this.localVideo_);
  171. }
  172. /**
  173. * @override
  174. * @export
  175. */
  176. async destroy() {
  177. if (document.pictureInPictureElement == this.localVideo_) {
  178. await document.exitPictureInPicture();
  179. }
  180. if (this.eventManager_) {
  181. this.eventManager_.release();
  182. this.eventManager_ = null;
  183. }
  184. if (this.mouseStillTimer_) {
  185. this.mouseStillTimer_.stop();
  186. this.mouseStillTimer_ = null;
  187. }
  188. if (this.fadeControlsTimer_) {
  189. this.fadeControlsTimer_.stop();
  190. this.fadeControlsTimer_ = null;
  191. }
  192. if (this.hideSettingsMenusTimer_) {
  193. this.hideSettingsMenusTimer_.stop();
  194. this.hideSettingsMenusTimer_ = null;
  195. }
  196. if (this.timeAndSeekRangeTimer_) {
  197. this.timeAndSeekRangeTimer_.stop();
  198. this.timeAndSeekRangeTimer_ = null;
  199. }
  200. if (this.vr_) {
  201. this.vr_.release();
  202. this.vr_ = null;
  203. }
  204. // Important! Release all child elements before destroying the cast proxy
  205. // or player. This makes sure those destructions will not trigger event
  206. // listeners in the UI which would then invoke the cast proxy or player.
  207. this.releaseChildElements_();
  208. if (this.controlsContainer_) {
  209. this.videoContainer_.removeChild(this.controlsContainer_);
  210. this.controlsContainer_ = null;
  211. }
  212. if (this.castProxy_) {
  213. await this.castProxy_.destroy();
  214. this.castProxy_ = null;
  215. }
  216. if (this.spinnerContainer_) {
  217. this.videoContainer_.removeChild(this.spinnerContainer_);
  218. this.spinnerContainer_ = null;
  219. }
  220. if (this.clientAdContainer_) {
  221. this.videoContainer_.removeChild(this.clientAdContainer_);
  222. this.clientAdContainer_ = null;
  223. }
  224. if (this.localPlayer_) {
  225. await this.localPlayer_.destroy();
  226. this.localPlayer_ = null;
  227. }
  228. this.player_ = null;
  229. this.localVideo_ = null;
  230. this.video_ = null;
  231. this.localization_ = null;
  232. this.pressedKeys_.clear();
  233. this.removeMediaSession_();
  234. // FakeEventTarget implements IReleasable
  235. super.release();
  236. }
  237. /** @private */
  238. releaseChildElements_() {
  239. for (const element of this.elements_) {
  240. element.release();
  241. }
  242. this.elements_ = [];
  243. }
  244. /**
  245. * @param {string} name
  246. * @param {!shaka.extern.IUIElement.Factory} factory
  247. * @export
  248. */
  249. static registerElement(name, factory) {
  250. shaka.ui.ControlsPanel.elementNamesToFactories_.set(name, factory);
  251. }
  252. /**
  253. * @param {!shaka.extern.IUISeekBar.Factory} factory
  254. * @export
  255. */
  256. static registerSeekBar(factory) {
  257. shaka.ui.ControlsPanel.seekBarFactory_ = factory;
  258. }
  259. /**
  260. * This allows the application to inhibit casting.
  261. *
  262. * @param {boolean} allow
  263. * @export
  264. */
  265. allowCast(allow) {
  266. this.castAllowed_ = allow;
  267. this.onCastStatusChange_();
  268. }
  269. /**
  270. * Used by the application to notify the controls that a load operation is
  271. * complete. This allows the controls to recalculate play/paused state, which
  272. * is important for platforms like Android where autoplay is disabled.
  273. * @export
  274. */
  275. loadComplete() {
  276. // If we are on Android or if autoplay is false, video.paused should be
  277. // true. Otherwise, video.paused is false and the content is autoplaying.
  278. this.onPlayStateChange_();
  279. }
  280. /**
  281. * @param {!shaka.extern.UIConfiguration} config
  282. * @export
  283. */
  284. configure(config) {
  285. this.config_ = config;
  286. this.castProxy_.changeReceiverId(config.castReceiverAppId,
  287. config.castAndroidReceiverCompatible);
  288. // Deconstruct the old layout if applicable
  289. if (this.seekBar_) {
  290. this.seekBar_ = null;
  291. }
  292. if (this.playButton_) {
  293. this.playButton_ = null;
  294. }
  295. if (this.contextMenu_) {
  296. this.contextMenu_ = null;
  297. }
  298. if (this.vr_) {
  299. this.vr_.configure(config);
  300. }
  301. if (this.controlsContainer_) {
  302. shaka.util.Dom.removeAllChildren(this.controlsContainer_);
  303. this.releaseChildElements_();
  304. } else {
  305. this.addControlsContainer_();
  306. // The client-side ad container is only created once, and is never
  307. // re-created or uprooted in the DOM, even when the DOM is re-created,
  308. // since that seemingly breaks the IMA SDK.
  309. this.addClientAdContainer_();
  310. goog.asserts.assert(
  311. this.controlsContainer_, 'Should have a controlsContainer_!');
  312. goog.asserts.assert(this.localVideo_, 'Should have a localVideo_!');
  313. goog.asserts.assert(this.player_, 'Should have a player_!');
  314. this.vr_ = new shaka.ui.VRManager(this.controlsContainer_, this.vrCanvas_,
  315. this.localVideo_, this.player_, this.config_);
  316. }
  317. // Create the new layout
  318. this.createDOM_();
  319. // Init the play state
  320. this.onPlayStateChange_();
  321. // Elements that should not propagate clicks (controls panel, menus)
  322. const noPropagationElements = this.videoContainer_.getElementsByClassName(
  323. 'shaka-no-propagation');
  324. for (const element of noPropagationElements) {
  325. const cb = (event) => event.stopPropagation();
  326. this.eventManager_.listen(element, 'click', cb);
  327. this.eventManager_.listen(element, 'dblclick', cb);
  328. }
  329. }
  330. /**
  331. * Enable or disable the custom controls. Enabling disables native
  332. * browser controls.
  333. *
  334. * @param {boolean} enabled
  335. * @export
  336. */
  337. setEnabledShakaControls(enabled) {
  338. this.enabled_ = enabled;
  339. if (enabled) {
  340. this.videoContainer_.setAttribute('shaka-controls', 'true');
  341. // If we're hiding native controls, make sure the video element itself is
  342. // not tab-navigable. Our custom controls will still be tab-navigable.
  343. this.localVideo_.tabIndex = -1;
  344. this.localVideo_.controls = false;
  345. } else {
  346. this.videoContainer_.removeAttribute('shaka-controls');
  347. }
  348. // The effects of play state changes are inhibited while showing native
  349. // browser controls. Recalculate that state now.
  350. this.onPlayStateChange_();
  351. }
  352. /**
  353. * Enable or disable native browser controls. Enabling disables shaka
  354. * controls.
  355. *
  356. * @param {boolean} enabled
  357. * @export
  358. */
  359. setEnabledNativeControls(enabled) {
  360. // If we enable the native controls, the element must be tab-navigable.
  361. // If we disable the native controls, we want to make sure that the video
  362. // element itself is not tab-navigable, so that the element is skipped over
  363. // when tabbing through the page.
  364. this.localVideo_.controls = enabled;
  365. this.localVideo_.tabIndex = enabled ? 0 : -1;
  366. if (enabled) {
  367. this.setEnabledShakaControls(false);
  368. }
  369. }
  370. /**
  371. * @export
  372. * @return {?shaka.extern.IAd}
  373. */
  374. getAd() {
  375. return this.ad_;
  376. }
  377. /**
  378. * @export
  379. * @return {shaka.cast.CastProxy}
  380. */
  381. getCastProxy() {
  382. return this.castProxy_;
  383. }
  384. /**
  385. * @return {shaka.ui.Localization}
  386. * @export
  387. */
  388. getLocalization() {
  389. return this.localization_;
  390. }
  391. /**
  392. * @return {!HTMLElement}
  393. * @export
  394. */
  395. getVideoContainer() {
  396. return this.videoContainer_;
  397. }
  398. /**
  399. * @return {HTMLMediaElement}
  400. * @export
  401. */
  402. getVideo() {
  403. return this.video_;
  404. }
  405. /**
  406. * @return {HTMLMediaElement}
  407. * @export
  408. */
  409. getLocalVideo() {
  410. return this.localVideo_;
  411. }
  412. /**
  413. * @return {shaka.Player}
  414. * @export
  415. */
  416. getPlayer() {
  417. return this.player_;
  418. }
  419. /**
  420. * @return {shaka.Player}
  421. * @export
  422. */
  423. getLocalPlayer() {
  424. return this.localPlayer_;
  425. }
  426. /**
  427. * @return {!HTMLElement}
  428. * @export
  429. */
  430. getControlsContainer() {
  431. goog.asserts.assert(
  432. this.controlsContainer_, 'No controls container after destruction!');
  433. return this.controlsContainer_;
  434. }
  435. /**
  436. * @return {!HTMLElement}
  437. * @export
  438. */
  439. getServerSideAdContainer() {
  440. return this.daiAdContainer_;
  441. }
  442. /**
  443. * @return {!HTMLElement}
  444. * @export
  445. */
  446. getClientSideAdContainer() {
  447. goog.asserts.assert(
  448. this.clientAdContainer_, 'No client ad container after destruction!');
  449. return this.clientAdContainer_;
  450. }
  451. /**
  452. * @return {!shaka.extern.UIConfiguration}
  453. * @export
  454. */
  455. getConfig() {
  456. return this.config_;
  457. }
  458. /**
  459. * @return {boolean}
  460. * @export
  461. */
  462. isSeeking() {
  463. return this.isSeeking_;
  464. }
  465. /**
  466. * @param {boolean} seeking
  467. * @export
  468. */
  469. setSeeking(seeking) {
  470. this.isSeeking_ = seeking;
  471. }
  472. /**
  473. * @return {boolean}
  474. * @export
  475. */
  476. isCastAllowed() {
  477. return this.castAllowed_;
  478. }
  479. /**
  480. * @return {number}
  481. * @export
  482. */
  483. getDisplayTime() {
  484. return this.seekBar_ ? this.seekBar_.getValue() : this.video_.currentTime;
  485. }
  486. /**
  487. * @param {?number} time
  488. * @export
  489. */
  490. setLastTouchEventTime(time) {
  491. this.lastTouchEventTime_ = time;
  492. }
  493. /**
  494. * @return {boolean}
  495. * @export
  496. */
  497. anySettingsMenusAreOpen() {
  498. return this.menus_.some(
  499. (menu) => !menu.classList.contains('shaka-hidden'));
  500. }
  501. /** @export */
  502. hideSettingsMenus() {
  503. this.hideSettingsMenusTimer_.tickNow();
  504. }
  505. /**
  506. * @return {boolean}
  507. * @export
  508. */
  509. isFullScreenSupported() {
  510. if (document.fullscreenEnabled) {
  511. return true;
  512. }
  513. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  514. if (video.webkitSupportsFullscreen) {
  515. return true;
  516. }
  517. return false;
  518. }
  519. /**
  520. * @return {boolean}
  521. * @export
  522. */
  523. isFullScreenEnabled() {
  524. if (document.fullscreenEnabled) {
  525. return !!document.fullscreenElement;
  526. }
  527. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  528. if (video.webkitSupportsFullscreen) {
  529. return video.webkitDisplayingFullscreen;
  530. }
  531. return false;
  532. }
  533. /** @private */
  534. async enterFullScreen_() {
  535. try {
  536. if (document.fullscreenEnabled) {
  537. if (document.pictureInPictureElement) {
  538. await document.exitPictureInPicture();
  539. }
  540. const fullScreenElement = this.config_.fullScreenElement;
  541. await fullScreenElement.requestFullscreen({navigationUI: 'hide'});
  542. if (this.config_.forceLandscapeOnFullscreen && screen.orientation) {
  543. // Locking to 'landscape' should let it be either
  544. // 'landscape-primary' or 'landscape-secondary' as appropriate.
  545. // We ignore errors from this specific call, since it creates noise
  546. // on desktop otherwise.
  547. try {
  548. await screen.orientation.lock('landscape');
  549. } catch (error) {}
  550. }
  551. } else {
  552. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  553. if (video.webkitSupportsFullscreen) {
  554. video.webkitEnterFullscreen();
  555. }
  556. }
  557. } catch (error) {
  558. // Entering fullscreen can fail without user interaction.
  559. this.dispatchEvent(new shaka.util.FakeEvent(
  560. 'error', (new Map()).set('detail', error)));
  561. }
  562. }
  563. /** @private */
  564. async exitFullScreen_() {
  565. if (document.fullscreenEnabled) {
  566. if (screen.orientation) {
  567. screen.orientation.unlock();
  568. }
  569. await document.exitFullscreen();
  570. } else {
  571. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  572. if (video.webkitSupportsFullscreen) {
  573. video.webkitExitFullscreen();
  574. }
  575. }
  576. }
  577. /** @export */
  578. async toggleFullScreen() {
  579. if (this.isFullScreenEnabled()) {
  580. await this.exitFullScreen_();
  581. } else {
  582. await this.enterFullScreen_();
  583. }
  584. }
  585. /**
  586. * @return {boolean}
  587. * @export
  588. */
  589. isPiPAllowed() {
  590. if (this.castProxy_.isCasting()) {
  591. return false;
  592. }
  593. if ('documentPictureInPicture' in window &&
  594. this.config_.preferDocumentPictureInPicture) {
  595. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  596. return !video.disablePictureInPicture;
  597. }
  598. if (document.pictureInPictureEnabled) {
  599. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  600. return !video.disablePictureInPicture;
  601. }
  602. return false;
  603. }
  604. /**
  605. * @return {boolean}
  606. * @export
  607. */
  608. isPiPEnabled() {
  609. if ('documentPictureInPicture' in window &&
  610. this.config_.preferDocumentPictureInPicture) {
  611. return !!window.documentPictureInPicture.window;
  612. } else {
  613. return !!document.pictureInPictureElement;
  614. }
  615. }
  616. /** @export */
  617. async togglePiP() {
  618. try {
  619. if ('documentPictureInPicture' in window &&
  620. this.config_.preferDocumentPictureInPicture) {
  621. await this.toggleDocumentPictureInPicture_();
  622. } else if (!document.pictureInPictureElement) {
  623. // If you were fullscreen, leave fullscreen first.
  624. if (document.fullscreenElement) {
  625. document.exitFullscreen();
  626. }
  627. const video = /** @type {HTMLVideoElement} */(this.localVideo_);
  628. await video.requestPictureInPicture();
  629. } else {
  630. await document.exitPictureInPicture();
  631. }
  632. } catch (error) {
  633. this.dispatchEvent(new shaka.util.FakeEvent(
  634. 'error', (new Map()).set('detail', error)));
  635. }
  636. }
  637. /**
  638. * The Document Picture-in-Picture API makes it possible to open an
  639. * always-on-top window that can be populated with arbitrary HTML content.
  640. * https://developer.chrome.com/docs/web-platform/document-picture-in-picture
  641. * @private
  642. */
  643. async toggleDocumentPictureInPicture_() {
  644. // Close Picture-in-Picture window if any.
  645. if (window.documentPictureInPicture.window) {
  646. window.documentPictureInPicture.window.close();
  647. return;
  648. }
  649. // Open a Picture-in-Picture window.
  650. const pipPlayer = this.videoContainer_;
  651. const rectPipPlayer = pipPlayer.getBoundingClientRect();
  652. const pipWindow = await window.documentPictureInPicture.requestWindow({
  653. width: rectPipPlayer.width,
  654. height: rectPipPlayer.height,
  655. });
  656. // Copy style sheets to the Picture-in-Picture window.
  657. this.copyStyleSheetsToWindow_(pipWindow);
  658. // Add placeholder for the player.
  659. const parentPlayer = pipPlayer.parentNode || document.body;
  660. const placeholder = this.videoContainer_.cloneNode(true);
  661. placeholder.style.visibility = 'hidden';
  662. placeholder.style.height = getComputedStyle(pipPlayer).height;
  663. parentPlayer.appendChild(placeholder);
  664. // Make sure player fits in the Picture-in-Picture window.
  665. const styles = document.createElement('style');
  666. styles.append(`[data-shaka-player-container] {
  667. width: 100% !important; max-height: 100%}`);
  668. pipWindow.document.head.append(styles);
  669. // Move player to the Picture-in-Picture window.
  670. pipWindow.document.body.append(pipPlayer);
  671. // Listen for the PiP closing event to move the player back.
  672. this.eventManager_.listenOnce(pipWindow, 'pagehide', () => {
  673. placeholder.replaceWith(/** @type {!Node} */(pipPlayer));
  674. });
  675. }
  676. /** @private */
  677. copyStyleSheetsToWindow_(win) {
  678. const styleSheets = /** @type {!Iterable<*>} */(document.styleSheets);
  679. const allCSS = [...styleSheets]
  680. .map((sheet) => {
  681. try {
  682. return [...sheet.cssRules].map((rule) => rule.cssText).join('');
  683. } catch (e) {
  684. const link = /** @type {!HTMLLinkElement} */(
  685. document.createElement('link'));
  686. link.rel = 'stylesheet';
  687. link.type = sheet.type;
  688. link.media = sheet.media;
  689. link.href = sheet.href;
  690. win.document.head.appendChild(link);
  691. }
  692. return '';
  693. })
  694. .filter(Boolean)
  695. .join('\n');
  696. const style = document.createElement('style');
  697. style.textContent = allCSS;
  698. win.document.head.appendChild(style);
  699. }
  700. /** @export */
  701. showAdUI() {
  702. shaka.ui.Utils.setDisplay(this.adPanel_, true);
  703. shaka.ui.Utils.setDisplay(this.clientAdContainer_, true);
  704. this.controlsContainer_.setAttribute('ad-active', 'true');
  705. }
  706. /** @export */
  707. hideAdUI() {
  708. shaka.ui.Utils.setDisplay(this.adPanel_, false);
  709. shaka.ui.Utils.setDisplay(this.clientAdContainer_, false);
  710. this.controlsContainer_.removeAttribute('ad-active');
  711. }
  712. /**
  713. * Play or pause the current presentation.
  714. */
  715. playPausePresentation() {
  716. if (!this.enabled_) {
  717. return;
  718. }
  719. if (!this.video_.duration) {
  720. // Can't play yet. Ignore.
  721. return;
  722. }
  723. this.player_.cancelTrickPlay();
  724. if (this.presentationIsPaused()) {
  725. this.video_.play();
  726. } else {
  727. this.video_.pause();
  728. }
  729. }
  730. /**
  731. * Play or pause the current ad.
  732. */
  733. playPauseAd() {
  734. if (this.ad_ && this.ad_.isPaused()) {
  735. this.ad_.play();
  736. } else if (this.ad_) {
  737. this.ad_.pause();
  738. }
  739. }
  740. /**
  741. * Return true if the presentation is paused.
  742. *
  743. * @return {boolean}
  744. */
  745. presentationIsPaused() {
  746. // The video element is in a paused state while seeking, but we don't count
  747. // that.
  748. return this.video_.paused && !this.isSeeking();
  749. }
  750. /** @private */
  751. createDOM_() {
  752. this.videoContainer_.classList.add('shaka-video-container');
  753. this.localVideo_.classList.add('shaka-video');
  754. this.addScrimContainer_();
  755. if (this.config_.addBigPlayButton) {
  756. this.addPlayButton_();
  757. }
  758. if (this.config_.customContextMenu) {
  759. this.addContextMenu_();
  760. }
  761. if (!this.spinnerContainer_) {
  762. this.addBufferingSpinner_();
  763. }
  764. if (this.config_.seekOnTaps) {
  765. this.addFastForwardButtonOnControlsContainer_();
  766. this.addRewindButtonOnControlsContainer_();
  767. }
  768. this.addDaiAdContainer_();
  769. this.addControlsButtonPanel_();
  770. this.menus_ = Array.from(
  771. this.videoContainer_.getElementsByClassName('shaka-settings-menu'));
  772. this.menus_.push(...Array.from(
  773. this.videoContainer_.getElementsByClassName('shaka-overflow-menu')));
  774. this.addSeekBar_();
  775. this.showOnHoverControls_ = Array.from(
  776. this.videoContainer_.getElementsByClassName(
  777. 'shaka-show-controls-on-mouse-over'));
  778. }
  779. /** @private */
  780. addControlsContainer_() {
  781. /** @private {HTMLElement} */
  782. this.controlsContainer_ = shaka.util.Dom.createHTMLElement('div');
  783. this.controlsContainer_.classList.add('shaka-controls-container');
  784. this.videoContainer_.appendChild(this.controlsContainer_);
  785. // Use our controls by default, without anyone calling
  786. // setEnabledShakaControls:
  787. this.videoContainer_.setAttribute('shaka-controls', 'true');
  788. this.eventManager_.listen(this.controlsContainer_, 'touchstart', (e) => {
  789. this.onContainerTouch_(e);
  790. }, {passive: false});
  791. this.eventManager_.listen(this.controlsContainer_, 'click', () => {
  792. this.onContainerClick_();
  793. });
  794. this.eventManager_.listen(this.controlsContainer_, 'dblclick', () => {
  795. if (this.config_.doubleClickForFullscreen &&
  796. this.isFullScreenSupported()) {
  797. this.toggleFullScreen();
  798. }
  799. });
  800. }
  801. /** @private */
  802. addPlayButton_() {
  803. const playButtonContainer = shaka.util.Dom.createHTMLElement('div');
  804. playButtonContainer.classList.add('shaka-play-button-container');
  805. this.controlsContainer_.appendChild(playButtonContainer);
  806. /** @private {shaka.ui.BigPlayButton} */
  807. this.playButton_ =
  808. new shaka.ui.BigPlayButton(playButtonContainer, this);
  809. this.elements_.push(this.playButton_);
  810. }
  811. /** @private */
  812. addContextMenu_() {
  813. /** @private {shaka.ui.ContextMenu} */
  814. this.contextMenu_ =
  815. new shaka.ui.ContextMenu(this.controlsButtonPanel_, this);
  816. this.elements_.push(this.contextMenu_);
  817. }
  818. /** @private */
  819. addScrimContainer_() {
  820. // This is the container that gets styled by CSS to have the
  821. // black gradient scrim at the end of the controls.
  822. const scrimContainer = shaka.util.Dom.createHTMLElement('div');
  823. scrimContainer.classList.add('shaka-scrim-container');
  824. this.controlsContainer_.appendChild(scrimContainer);
  825. }
  826. /** @private */
  827. addAdControls_() {
  828. /** @private {!HTMLElement} */
  829. this.adPanel_ = shaka.util.Dom.createHTMLElement('div');
  830. this.adPanel_.classList.add('shaka-ad-controls');
  831. const showAdPanel = this.ad_ != null && this.ad_.isLinear();
  832. shaka.ui.Utils.setDisplay(this.adPanel_, showAdPanel);
  833. this.bottomControls_.appendChild(this.adPanel_);
  834. const adPosition = new shaka.ui.AdPosition(this.adPanel_, this);
  835. this.elements_.push(adPosition);
  836. const adCounter = new shaka.ui.AdCounter(this.adPanel_, this);
  837. this.elements_.push(adCounter);
  838. const skipButton = new shaka.ui.SkipAdButton(this.adPanel_, this);
  839. this.elements_.push(skipButton);
  840. }
  841. /** @private */
  842. addBufferingSpinner_() {
  843. /** @private {HTMLElement} */
  844. this.spinnerContainer_ = shaka.util.Dom.createHTMLElement('div');
  845. this.spinnerContainer_.classList.add('shaka-spinner-container');
  846. this.videoContainer_.appendChild(this.spinnerContainer_);
  847. const spinner = shaka.util.Dom.createHTMLElement('div');
  848. spinner.classList.add('shaka-spinner');
  849. this.spinnerContainer_.appendChild(spinner);
  850. // Svg elements have to be created with the svg xml namespace.
  851. const xmlns = 'http://www.w3.org/2000/svg';
  852. const svg =
  853. /** @type {!HTMLElement} */(document.createElementNS(xmlns, 'svg'));
  854. svg.classList.add('shaka-spinner-svg');
  855. svg.setAttribute('viewBox', '0 0 30 30');
  856. spinner.appendChild(svg);
  857. // These coordinates are relative to the SVG viewBox above. This is
  858. // distinct from the actual display size in the page, since the "S" is for
  859. // "Scalable." The radius of 14.5 is so that the edges of the 1-px-wide
  860. // stroke will touch the edges of the viewBox.
  861. const spinnerCircle = document.createElementNS(xmlns, 'circle');
  862. spinnerCircle.classList.add('shaka-spinner-path');
  863. spinnerCircle.setAttribute('cx', '15');
  864. spinnerCircle.setAttribute('cy', '15');
  865. spinnerCircle.setAttribute('r', '14.5');
  866. spinnerCircle.setAttribute('fill', 'none');
  867. spinnerCircle.setAttribute('stroke-width', '1');
  868. spinnerCircle.setAttribute('stroke-miterlimit', '10');
  869. svg.appendChild(spinnerCircle);
  870. }
  871. /**
  872. * Add fast-forward button on Controls container for moving video some
  873. * seconds ahead when the video is tapped more than once, video seeks ahead
  874. * some seconds for every extra tap.
  875. * @private
  876. */
  877. addFastForwardButtonOnControlsContainer_() {
  878. const hiddenFastForwardContainer = shaka.util.Dom.createHTMLElement('div');
  879. hiddenFastForwardContainer.classList.add(
  880. 'shaka-hidden-fast-forward-container');
  881. this.controlsContainer_.appendChild(hiddenFastForwardContainer);
  882. /** @private {shaka.ui.HiddenFastForwardButton} */
  883. this.hiddenFastForwardButton_ =
  884. new shaka.ui.HiddenFastForwardButton(hiddenFastForwardContainer, this);
  885. this.elements_.push(this.hiddenFastForwardButton_);
  886. }
  887. /**
  888. * Add Rewind button on Controls container for moving video some seconds
  889. * behind when the video is tapped more than once, video seeks behind some
  890. * seconds for every extra tap.
  891. * @private
  892. */
  893. addRewindButtonOnControlsContainer_() {
  894. const hiddenRewindContainer = shaka.util.Dom.createHTMLElement('div');
  895. hiddenRewindContainer.classList.add(
  896. 'shaka-hidden-rewind-container');
  897. this.controlsContainer_.appendChild(hiddenRewindContainer);
  898. /** @private {shaka.ui.HiddenRewindButton} */
  899. this.hiddenRewindButton_ =
  900. new shaka.ui.HiddenRewindButton(hiddenRewindContainer, this);
  901. this.elements_.push(this.hiddenRewindButton_);
  902. }
  903. /** @private */
  904. addControlsButtonPanel_() {
  905. /** @private {!HTMLElement} */
  906. this.bottomControls_ = shaka.util.Dom.createHTMLElement('div');
  907. this.bottomControls_.classList.add('shaka-bottom-controls');
  908. this.bottomControls_.classList.add('shaka-no-propagation');
  909. this.controlsContainer_.appendChild(this.bottomControls_);
  910. // Overflow menus are supposed to hide once you click elsewhere
  911. // on the page. The click event listener on window ensures that.
  912. // However, clicks on the bottom controls don't propagate to the container,
  913. // so we have to explicitly hide the menus onclick here.
  914. this.eventManager_.listen(this.bottomControls_, 'click', (e) => {
  915. // We explicitly deny this measure when clicking on buttons that
  916. // open submenus in the control panel.
  917. if (!e.target['closest']('.shaka-overflow-button')) {
  918. this.hideSettingsMenus();
  919. }
  920. });
  921. this.addAdControls_();
  922. /** @private {!HTMLElement} */
  923. this.controlsButtonPanel_ = shaka.util.Dom.createHTMLElement('div');
  924. this.controlsButtonPanel_.classList.add('shaka-controls-button-panel');
  925. this.controlsButtonPanel_.classList.add(
  926. 'shaka-show-controls-on-mouse-over');
  927. if (this.config_.enableTooltips) {
  928. this.controlsButtonPanel_.classList.add('shaka-tooltips-on');
  929. }
  930. this.bottomControls_.appendChild(this.controlsButtonPanel_);
  931. // Create the elements specified by controlPanelElements
  932. for (const name of this.config_.controlPanelElements) {
  933. if (shaka.ui.ControlsPanel.elementNamesToFactories_.get(name)) {
  934. const factory =
  935. shaka.ui.ControlsPanel.elementNamesToFactories_.get(name);
  936. const element = factory.create(this.controlsButtonPanel_, this);
  937. this.elements_.push(element);
  938. } else {
  939. shaka.log.alwaysWarn('Unrecognized control panel element requested:',
  940. name);
  941. }
  942. }
  943. }
  944. /**
  945. * Adds a container for server side ad UI with IMA SDK.
  946. *
  947. * @private
  948. */
  949. addDaiAdContainer_() {
  950. /** @private {!HTMLElement} */
  951. this.daiAdContainer_ = shaka.util.Dom.createHTMLElement('div');
  952. this.daiAdContainer_.classList.add('shaka-server-side-ad-container');
  953. this.controlsContainer_.appendChild(this.daiAdContainer_);
  954. }
  955. /**
  956. * Adds a seekbar depending on the configuration.
  957. * By default an instance of shaka.ui.SeekBar is created
  958. * This behaviour can be overriden by providing a SeekBar factory using the
  959. * registerSeekBarFactory function.
  960. *
  961. * @private
  962. */
  963. addSeekBar_() {
  964. if (this.config_.addSeekBar) {
  965. this.seekBar_ = shaka.ui.ControlsPanel.seekBarFactory_.create(
  966. this.bottomControls_, this);
  967. this.elements_.push(this.seekBar_);
  968. } else {
  969. // Settings menus need to be positioned lower if the seekbar is absent.
  970. for (const menu of this.menus_) {
  971. menu.classList.add('shaka-low-position');
  972. }
  973. }
  974. }
  975. /**
  976. * Adds a container for client side ad UI with IMA SDK.
  977. *
  978. * @private
  979. */
  980. addClientAdContainer_() {
  981. /** @private {HTMLElement} */
  982. this.clientAdContainer_ = shaka.util.Dom.createHTMLElement('div');
  983. this.clientAdContainer_.classList.add('shaka-client-side-ad-container');
  984. shaka.ui.Utils.setDisplay(this.clientAdContainer_, false);
  985. this.eventManager_.listen(this.clientAdContainer_, 'click', () => {
  986. this.onContainerClick_();
  987. });
  988. this.videoContainer_.appendChild(this.clientAdContainer_);
  989. }
  990. /**
  991. * Adds static event listeners. This should only add event listeners to
  992. * things that don't change (e.g. Player). Dynamic elements (e.g. controls)
  993. * should have their event listeners added when they are created.
  994. *
  995. * @private
  996. */
  997. addEventListeners_() {
  998. this.eventManager_.listen(this.player_, 'buffering', () => {
  999. this.onBufferingStateChange_();
  1000. });
  1001. // Set the initial state, as well.
  1002. this.onBufferingStateChange_();
  1003. // Listen for key down events to detect tab and enable outline
  1004. // for focused elements.
  1005. this.eventManager_.listen(window, 'keydown', (e) => {
  1006. this.onWindowKeyDown_(/** @type {!KeyboardEvent} */(e));
  1007. });
  1008. // Listen for click events to dismiss the settings menus.
  1009. this.eventManager_.listen(window, 'click', () => this.hideSettingsMenus());
  1010. // Avoid having multiple submenus open at the same time.
  1011. this.eventManager_.listen(
  1012. this, 'submenuopen', () => {
  1013. this.hideSettingsMenus();
  1014. });
  1015. this.eventManager_.listen(this.video_, 'play', () => {
  1016. this.onPlayStateChange_();
  1017. });
  1018. this.eventManager_.listen(this.video_, 'pause', () => {
  1019. this.onPlayStateChange_();
  1020. });
  1021. this.eventManager_.listen(this.videoContainer_, 'mousemove', (e) => {
  1022. this.onMouseMove_(e);
  1023. });
  1024. this.eventManager_.listen(this.videoContainer_, 'touchmove', (e) => {
  1025. this.onMouseMove_(e);
  1026. }, {passive: true});
  1027. this.eventManager_.listen(this.videoContainer_, 'touchend', (e) => {
  1028. this.onMouseMove_(e);
  1029. }, {passive: true});
  1030. this.eventManager_.listen(this.videoContainer_, 'mouseleave', () => {
  1031. this.onMouseLeave_();
  1032. });
  1033. this.eventManager_.listen(this.castProxy_, 'caststatuschanged', () => {
  1034. this.onCastStatusChange_();
  1035. });
  1036. this.eventManager_.listen(this.vr_, 'vrstatuschanged', () => {
  1037. this.dispatchEvent(new shaka.util.FakeEvent('vrstatuschanged'));
  1038. });
  1039. this.eventManager_.listen(this.videoContainer_, 'keydown', (e) => {
  1040. this.onControlsKeyDown_(/** @type {!KeyboardEvent} */(e));
  1041. });
  1042. this.eventManager_.listen(this.videoContainer_, 'keyup', (e) => {
  1043. this.onControlsKeyUp_(/** @type {!KeyboardEvent} */(e));
  1044. });
  1045. this.eventManager_.listen(
  1046. this.adManager_, shaka.ads.Utils.AD_STARTED, (e) => {
  1047. this.ad_ = (/** @type {!Object} */ (e))['ad'];
  1048. this.showAdUI();
  1049. });
  1050. this.eventManager_.listen(
  1051. this.adManager_, shaka.ads.Utils.AD_STOPPED, () => {
  1052. this.ad_ = null;
  1053. this.hideAdUI();
  1054. });
  1055. if (screen.orientation) {
  1056. this.eventManager_.listen(screen.orientation, 'change', async () => {
  1057. await this.onScreenRotation_();
  1058. });
  1059. }
  1060. }
  1061. /**
  1062. * @private
  1063. */
  1064. setupMediaSession_() {
  1065. if (!this.config_.setupMediaSession || !navigator.mediaSession) {
  1066. return;
  1067. }
  1068. const addMediaSessionHandler = (type, callback) => {
  1069. try {
  1070. navigator.mediaSession.setActionHandler(type, (details) => {
  1071. callback(details);
  1072. });
  1073. } catch (error) {
  1074. shaka.log.warning(
  1075. `The "${type}" media session action is not supported.`);
  1076. }
  1077. };
  1078. const updatePositionState = () => {
  1079. const seekRange = this.player_.seekRange();
  1080. let duration = seekRange.end - seekRange.start;
  1081. const position = parseFloat(
  1082. (this.video_.currentTime - seekRange.start).toFixed(2));
  1083. if (this.player_.isLive() && Math.abs(duration - position) < 1) {
  1084. // Positive infinity indicates media without a defined end, such as a
  1085. // live stream.
  1086. duration = Infinity;
  1087. }
  1088. try {
  1089. if ((this.ad_ && this.ad_.isLinear())) {
  1090. navigator.mediaSession.setPositionState();
  1091. } else {
  1092. navigator.mediaSession.setPositionState({
  1093. duration: Math.max(0, duration),
  1094. playbackRate: this.video_.playbackRate,
  1095. position: Math.max(0, position),
  1096. });
  1097. }
  1098. } catch (error) {
  1099. shaka.log.warning(
  1100. 'setPositionState in media session is not supported.');
  1101. }
  1102. };
  1103. const commonHandler = (details) => {
  1104. const keyboardSeekDistance = this.config_.keyboardSeekDistance;
  1105. const seekRange = this.player_.seekRange();
  1106. switch (details.action) {
  1107. case 'pause':
  1108. this.onPlayPauseClick_();
  1109. break;
  1110. case 'play':
  1111. this.onPlayPauseClick_();
  1112. break;
  1113. case 'seekbackward':
  1114. if (!this.ad_ || !this.ad_.isLinear()) {
  1115. this.seek_(this.seekBar_.getValue() -
  1116. (details.seekOffset || keyboardSeekDistance));
  1117. }
  1118. break;
  1119. case 'seekforward':
  1120. if (!this.ad_ || !this.ad_.isLinear()) {
  1121. this.seek_(this.seekBar_.getValue() +
  1122. (details.seekOffset || keyboardSeekDistance));
  1123. }
  1124. break;
  1125. case 'seekto':
  1126. if (!this.ad_ || !this.ad_.isLinear()) {
  1127. this.seek_(seekRange.start + details.seekTime);
  1128. }
  1129. break;
  1130. case 'stop':
  1131. this.player_.unload();
  1132. break;
  1133. case 'enterpictureinpicture':
  1134. if (!this.ad_ || !this.ad_.isLinear()) {
  1135. this.togglePiP();
  1136. }
  1137. break;
  1138. }
  1139. };
  1140. addMediaSessionHandler('pause', commonHandler);
  1141. addMediaSessionHandler('play', commonHandler);
  1142. addMediaSessionHandler('seekbackward', commonHandler);
  1143. addMediaSessionHandler('seekforward', commonHandler);
  1144. addMediaSessionHandler('seekto', commonHandler);
  1145. addMediaSessionHandler('stop', commonHandler);
  1146. if ('documentPictureInPicture' in window ||
  1147. document.pictureInPictureEnabled) {
  1148. addMediaSessionHandler('enterpictureinpicture', commonHandler);
  1149. }
  1150. this.eventManager_.listen(this.video_, 'timeupdate', () => {
  1151. updatePositionState();
  1152. });
  1153. this.eventManager_.listen(this.player_, 'metadata', (event) => {
  1154. const payload = event['payload'];
  1155. if (!payload) {
  1156. return;
  1157. }
  1158. let title;
  1159. if (payload['key'] == 'TIT2' && payload['data']) {
  1160. title = payload['data'];
  1161. }
  1162. let imageUrl;
  1163. if (payload['key'] == 'APIC' && payload['mimeType'] == '-->') {
  1164. imageUrl = payload['data'];
  1165. }
  1166. if (navigator.mediaSession.metadata && title) {
  1167. const metadata = navigator.mediaSession.metadata;
  1168. metadata.title = title;
  1169. navigator.mediaSession.metadata = new MediaMetadata(metadata);
  1170. }
  1171. if (imageUrl) {
  1172. const video = /** @type {HTMLVideoElement} */ (this.localVideo_);
  1173. if (imageUrl != video.poster) {
  1174. video.poster = imageUrl;
  1175. }
  1176. if (navigator.mediaSession.metadata) {
  1177. const metadata = navigator.mediaSession.metadata;
  1178. metadata.artwork = [{src: imageUrl}];
  1179. navigator.mediaSession.metadata = new MediaMetadata(metadata);
  1180. }
  1181. }
  1182. });
  1183. }
  1184. /**
  1185. * @private
  1186. */
  1187. removeMediaSession_() {
  1188. if (!this.config_.setupMediaSession || !navigator.mediaSession) {
  1189. return;
  1190. }
  1191. try {
  1192. navigator.mediaSession.setPositionState();
  1193. } catch (error) {}
  1194. const disableMediaSessionHandler = (type) => {
  1195. try {
  1196. navigator.mediaSession.setActionHandler(type, null);
  1197. } catch (error) {}
  1198. };
  1199. disableMediaSessionHandler('pause');
  1200. disableMediaSessionHandler('play');
  1201. disableMediaSessionHandler('seekbackward');
  1202. disableMediaSessionHandler('seekforward');
  1203. disableMediaSessionHandler('seekto');
  1204. disableMediaSessionHandler('stop');
  1205. disableMediaSessionHandler('enterpictureinpicture');
  1206. }
  1207. /**
  1208. * When a mobile device is rotated to landscape layout, and the video is
  1209. * loaded, make the demo app go into fullscreen.
  1210. * Similarly, exit fullscreen when the device is rotated to portrait layout.
  1211. * @private
  1212. */
  1213. async onScreenRotation_() {
  1214. if (!this.video_ ||
  1215. this.video_.readyState == 0 ||
  1216. this.castProxy_.isCasting() ||
  1217. !this.config_.enableFullscreenOnRotation ||
  1218. !this.isFullScreenSupported()) {
  1219. return;
  1220. }
  1221. if (screen.orientation.type.includes('landscape') &&
  1222. !this.isFullScreenEnabled()) {
  1223. await this.enterFullScreen_();
  1224. } else if (screen.orientation.type.includes('portrait') &&
  1225. this.isFullScreenEnabled()) {
  1226. await this.exitFullScreen_();
  1227. }
  1228. }
  1229. /**
  1230. * Hiding the cursor when the mouse stops moving seems to be the only
  1231. * decent UX in fullscreen mode. Since we can't use pure CSS for that,
  1232. * we use events both in and out of fullscreen mode.
  1233. * Showing the control bar when a key is pressed, and hiding it after some
  1234. * time.
  1235. * @param {!Event} event
  1236. * @private
  1237. */
  1238. onMouseMove_(event) {
  1239. // Disable blue outline for focused elements for mouse navigation.
  1240. if (event.type == 'mousemove') {
  1241. this.controlsContainer_.classList.remove('shaka-keyboard-navigation');
  1242. this.computeOpacity();
  1243. }
  1244. if (event.type == 'touchstart' || event.type == 'touchmove' ||
  1245. event.type == 'touchend' || event.type == 'keyup') {
  1246. this.lastTouchEventTime_ = Date.now();
  1247. } else if (this.lastTouchEventTime_ + 1000 < Date.now()) {
  1248. // It has been a while since the last touch event, this is probably a real
  1249. // mouse moving, so treat it like a mouse.
  1250. this.lastTouchEventTime_ = null;
  1251. }
  1252. // When there is a touch, we can get a 'mousemove' event after touch events.
  1253. // This should be treated as part of the touch, which has already been
  1254. // handled.
  1255. if (this.lastTouchEventTime_ && event.type == 'mousemove') {
  1256. return;
  1257. }
  1258. // Use the cursor specified in the CSS file.
  1259. this.videoContainer_.style.cursor = '';
  1260. this.recentMouseMovement_ = true;
  1261. // Make sure we are not about to hide the settings menus and then force them
  1262. // open.
  1263. this.hideSettingsMenusTimer_.stop();
  1264. if (!this.isOpaque()) {
  1265. // Only update the time and seek range on mouse movement if it's the very
  1266. // first movement and we're about to show the controls. Otherwise, the
  1267. // seek bar will be updated much more rapidly during mouse movement. Do
  1268. // this right before making it visible.
  1269. this.updateTimeAndSeekRange_();
  1270. this.computeOpacity();
  1271. }
  1272. // Hide the cursor when the mouse stops moving.
  1273. // Only applies while the cursor is over the video container.
  1274. this.mouseStillTimer_.stop();
  1275. // Only start a timeout on 'touchend' or for 'mousemove' with no touch
  1276. // events.
  1277. if (event.type == 'touchend' ||
  1278. event.type == 'keyup'|| !this.lastTouchEventTime_) {
  1279. this.mouseStillTimer_.tickAfter(/* seconds= */ 3);
  1280. }
  1281. }
  1282. /** @private */
  1283. onMouseLeave_() {
  1284. // We sometimes get 'mouseout' events with touches. Since we can never
  1285. // leave the video element when touching, ignore.
  1286. if (this.lastTouchEventTime_) {
  1287. return;
  1288. }
  1289. // Stop the timer and invoke the callback now to hide the controls. If we
  1290. // don't, the opacity style we set in onMouseMove_ will continue to override
  1291. // the opacity in CSS and force the controls to stay visible.
  1292. this.mouseStillTimer_.tickNow();
  1293. }
  1294. /**
  1295. * This callback is for when we are pretty sure that the mouse has stopped
  1296. * moving (aka the mouse is still). This method should only be called via
  1297. * |mouseStillTimer_|. If this behaviour needs to be invoked directly, use
  1298. * |mouseStillTimer_.tickNow()|.
  1299. *
  1300. * @private
  1301. */
  1302. onMouseStill_() {
  1303. // Hide the cursor.
  1304. this.videoContainer_.style.cursor = 'none';
  1305. this.recentMouseMovement_ = false;
  1306. this.computeOpacity();
  1307. }
  1308. /**
  1309. * @return {boolean} true if any relevant elements are hovered.
  1310. * @private
  1311. */
  1312. isHovered_() {
  1313. if (!window.matchMedia('hover: hover').matches) {
  1314. // This is primarily a touch-screen device, so the :hover query below
  1315. // doesn't make sense. In spite of this, the :hover query on an element
  1316. // can still return true on such a device after a touch ends.
  1317. // See https://bit.ly/34dBORX for details.
  1318. return false;
  1319. }
  1320. return this.showOnHoverControls_.some((element) => {
  1321. return element.matches(':hover');
  1322. });
  1323. }
  1324. /**
  1325. * Recompute whether the controls should be shown or hidden.
  1326. */
  1327. computeOpacity() {
  1328. const adIsPaused = this.ad_ ? this.ad_.isPaused() : false;
  1329. const videoIsPaused = this.video_.paused && !this.isSeeking_;
  1330. const keyboardNavigationMode = this.controlsContainer_.classList.contains(
  1331. 'shaka-keyboard-navigation');
  1332. // Keep showing the controls if the ad or video is paused, there has been
  1333. // recent mouse movement, we're in keyboard navigation, or one of a special
  1334. // class of elements is hovered.
  1335. if (adIsPaused ||
  1336. ((!this.ad_ || !this.ad_.isLinear()) && videoIsPaused) ||
  1337. this.recentMouseMovement_ ||
  1338. keyboardNavigationMode ||
  1339. this.isHovered_()) {
  1340. // Make sure the state is up-to-date before showing it.
  1341. this.updateTimeAndSeekRange_();
  1342. this.controlsContainer_.setAttribute('shown', 'true');
  1343. this.fadeControlsTimer_.stop();
  1344. } else {
  1345. this.fadeControlsTimer_.tickAfter(/* seconds= */ this.config_.fadeDelay);
  1346. }
  1347. }
  1348. /**
  1349. * @param {!Event} event
  1350. * @private
  1351. */
  1352. onContainerTouch_(event) {
  1353. if (!this.video_.duration) {
  1354. // Can't play yet. Ignore.
  1355. return;
  1356. }
  1357. if (this.isOpaque()) {
  1358. this.lastTouchEventTime_ = Date.now();
  1359. // The controls are showing.
  1360. // Let this event continue and become a click.
  1361. } else {
  1362. // The controls are hidden, so show them.
  1363. this.onMouseMove_(event);
  1364. // Stop this event from becoming a click event.
  1365. event.cancelable && event.preventDefault();
  1366. }
  1367. }
  1368. /** @private */
  1369. onContainerClick_() {
  1370. if (!this.enabled_ || this.isPlayingVR()) {
  1371. return;
  1372. }
  1373. if (this.anySettingsMenusAreOpen()) {
  1374. this.hideSettingsMenusTimer_.tickNow();
  1375. } else if (this.config_.singleClickForPlayAndPause) {
  1376. this.onPlayPauseClick_();
  1377. }
  1378. }
  1379. /** @private */
  1380. onPlayPauseClick_() {
  1381. if (this.ad_ && this.ad_.isLinear()) {
  1382. this.playPauseAd();
  1383. } else {
  1384. this.playPausePresentation();
  1385. }
  1386. }
  1387. /** @private */
  1388. onCastStatusChange_() {
  1389. const isCasting = this.castProxy_.isCasting();
  1390. this.dispatchEvent(new shaka.util.FakeEvent(
  1391. 'caststatuschanged', (new Map()).set('newStatus', isCasting)));
  1392. if (isCasting) {
  1393. this.controlsContainer_.setAttribute('casting', 'true');
  1394. } else {
  1395. this.controlsContainer_.removeAttribute('casting');
  1396. }
  1397. }
  1398. /** @private */
  1399. onPlayStateChange_() {
  1400. this.computeOpacity();
  1401. }
  1402. /**
  1403. * Support controls with keyboard inputs.
  1404. * @param {!KeyboardEvent} event
  1405. * @private
  1406. */
  1407. onControlsKeyDown_(event) {
  1408. const activeElement = document.activeElement;
  1409. const isVolumeBar = activeElement && activeElement.classList ?
  1410. activeElement.classList.contains('shaka-volume-bar') : false;
  1411. const isSeekBar = activeElement && activeElement.classList &&
  1412. activeElement.classList.contains('shaka-seek-bar');
  1413. // Show the control panel if it is on focus or any button is pressed.
  1414. if (this.controlsContainer_.contains(activeElement)) {
  1415. this.onMouseMove_(event);
  1416. }
  1417. if (!this.config_.enableKeyboardPlaybackControls) {
  1418. return;
  1419. }
  1420. const keyboardSeekDistance = this.config_.keyboardSeekDistance;
  1421. const keyboardLargeSeekDistance = this.config_.keyboardLargeSeekDistance;
  1422. switch (event.key) {
  1423. case 'ArrowLeft':
  1424. // If it's not focused on the volume bar, move the seek time backward
  1425. // for a few sec. Otherwise, the volume will be adjusted automatically.
  1426. if (this.seekBar_ && isSeekBar && !isVolumeBar &&
  1427. keyboardSeekDistance > 0) {
  1428. event.preventDefault();
  1429. this.seek_(this.seekBar_.getValue() - keyboardSeekDistance);
  1430. }
  1431. break;
  1432. case 'ArrowRight':
  1433. // If it's not focused on the volume bar, move the seek time forward
  1434. // for a few sec. Otherwise, the volume will be adjusted automatically.
  1435. if (this.seekBar_ && isSeekBar && !isVolumeBar &&
  1436. keyboardSeekDistance > 0) {
  1437. event.preventDefault();
  1438. this.seek_(this.seekBar_.getValue() + keyboardSeekDistance);
  1439. }
  1440. break;
  1441. case 'PageDown':
  1442. // PageDown is like ArrowLeft, but has a larger jump distance, and does
  1443. // nothing to volume.
  1444. if (this.seekBar_ && isSeekBar && keyboardSeekDistance > 0) {
  1445. event.preventDefault();
  1446. this.seek_(this.seekBar_.getValue() - keyboardLargeSeekDistance);
  1447. }
  1448. break;
  1449. case 'PageUp':
  1450. // PageDown is like ArrowRight, but has a larger jump distance, and does
  1451. // nothing to volume.
  1452. if (this.seekBar_ && isSeekBar && keyboardSeekDistance > 0) {
  1453. event.preventDefault();
  1454. this.seek_(this.seekBar_.getValue() + keyboardLargeSeekDistance);
  1455. }
  1456. break;
  1457. // Jump to the beginning of the video's seek range.
  1458. case 'Home':
  1459. if (this.seekBar_) {
  1460. this.seek_(this.player_.seekRange().start);
  1461. }
  1462. break;
  1463. // Jump to the end of the video's seek range.
  1464. case 'End':
  1465. if (this.seekBar_) {
  1466. this.seek_(this.player_.seekRange().end);
  1467. }
  1468. break;
  1469. case 'f':
  1470. if (this.isFullScreenSupported()) {
  1471. this.toggleFullScreen();
  1472. }
  1473. break;
  1474. case 'm':
  1475. if (this.ad_ && this.ad_.isLinear()) {
  1476. this.ad_.setMuted(!this.ad_.isMuted());
  1477. } else {
  1478. this.localVideo_.muted = !this.localVideo_.muted;
  1479. }
  1480. break;
  1481. case 'p':
  1482. if (this.isPiPAllowed()) {
  1483. this.togglePiP();
  1484. }
  1485. break;
  1486. // Pause or play by pressing space on the seek bar.
  1487. case ' ':
  1488. if (isSeekBar) {
  1489. this.onPlayPauseClick_();
  1490. }
  1491. break;
  1492. }
  1493. }
  1494. /**
  1495. * Support controls with keyboard inputs.
  1496. * @param {!KeyboardEvent} event
  1497. * @private
  1498. */
  1499. onControlsKeyUp_(event) {
  1500. // When the key is released, remove it from the pressed keys set.
  1501. this.pressedKeys_.delete(event.key);
  1502. }
  1503. /**
  1504. * Called both as an event listener and directly by the controls to initialize
  1505. * the buffering state.
  1506. * @private
  1507. */
  1508. onBufferingStateChange_() {
  1509. if (!this.enabled_) {
  1510. return;
  1511. }
  1512. shaka.ui.Utils.setDisplay(
  1513. this.spinnerContainer_, this.player_.isBuffering());
  1514. }
  1515. /**
  1516. * @return {boolean}
  1517. * @export
  1518. */
  1519. isOpaque() {
  1520. if (!this.enabled_) {
  1521. return false;
  1522. }
  1523. return this.controlsContainer_.getAttribute('shown') != null ||
  1524. this.controlsContainer_.getAttribute('casting') != null;
  1525. }
  1526. /**
  1527. * Update the video's current time based on the keyboard operations.
  1528. *
  1529. * @param {number} currentTime
  1530. * @private
  1531. */
  1532. seek_(currentTime) {
  1533. goog.asserts.assert(
  1534. this.seekBar_, 'Caller of seek_ must check for seekBar_ first!');
  1535. this.seekBar_.changeTo(currentTime);
  1536. if (this.isOpaque()) {
  1537. // Only update the time and seek range if it's visible.
  1538. this.updateTimeAndSeekRange_();
  1539. }
  1540. }
  1541. /**
  1542. * Called when the seek range or current time need to be updated.
  1543. * @private
  1544. */
  1545. updateTimeAndSeekRange_() {
  1546. if (this.seekBar_) {
  1547. this.seekBar_.setValue(this.video_.currentTime);
  1548. this.seekBar_.update();
  1549. if (this.seekBar_.isShowing()) {
  1550. for (const menu of this.menus_) {
  1551. menu.classList.remove('shaka-low-position');
  1552. }
  1553. } else {
  1554. for (const menu of this.menus_) {
  1555. menu.classList.add('shaka-low-position');
  1556. }
  1557. }
  1558. }
  1559. this.dispatchEvent(new shaka.util.FakeEvent('timeandseekrangeupdated'));
  1560. }
  1561. /**
  1562. * Add behaviors for keyboard navigation.
  1563. * 1. Add blue outline for focused elements.
  1564. * 2. Allow exiting overflow settings menus by pressing Esc key.
  1565. * 3. When navigating on overflow settings menu by pressing Tab
  1566. * key or Shift+Tab keys keep the focus inside overflow menu.
  1567. *
  1568. * @param {!KeyboardEvent} event
  1569. * @private
  1570. */
  1571. onWindowKeyDown_(event) {
  1572. // Add the key to the pressed keys set when it's pressed.
  1573. this.pressedKeys_.add(event.key);
  1574. const anySettingsMenusAreOpen = this.anySettingsMenusAreOpen();
  1575. if (event.key == 'Tab') {
  1576. // Enable blue outline for focused elements for keyboard
  1577. // navigation.
  1578. this.controlsContainer_.classList.add('shaka-keyboard-navigation');
  1579. this.computeOpacity();
  1580. this.eventManager_.listen(window, 'mousedown', () => this.onMouseDown_());
  1581. }
  1582. // If escape key was pressed, close any open settings menus.
  1583. if (event.key == 'Escape') {
  1584. this.hideSettingsMenusTimer_.tickNow();
  1585. }
  1586. if (anySettingsMenusAreOpen && this.pressedKeys_.has('Tab')) {
  1587. // If Tab key or Shift+Tab keys are pressed when navigating through
  1588. // an overflow settings menu, keep the focus to loop inside the
  1589. // overflow menu.
  1590. this.keepFocusInMenu_(event);
  1591. }
  1592. }
  1593. /**
  1594. * When the user is using keyboard to navigate inside the overflow settings
  1595. * menu (pressing Tab key to go forward, or pressing Shift + Tab keys to go
  1596. * backward), make sure it's focused only on the elements of the overflow
  1597. * panel.
  1598. *
  1599. * This is called by onWindowKeyDown_() function, when there's a settings
  1600. * overflow menu open, and the Tab key / Shift+Tab keys are pressed.
  1601. *
  1602. * @param {!Event} event
  1603. * @private
  1604. */
  1605. keepFocusInMenu_(event) {
  1606. const openSettingsMenus = this.menus_.filter(
  1607. (menu) => !menu.classList.contains('shaka-hidden'));
  1608. if (!openSettingsMenus.length) {
  1609. // For example, this occurs when you hit escape to close the menu.
  1610. return;
  1611. }
  1612. const settingsMenu = openSettingsMenus[0];
  1613. if (settingsMenu.childNodes.length) {
  1614. // Get the first and the last displaying child element from the overflow
  1615. // menu.
  1616. let firstShownChild = settingsMenu.firstElementChild;
  1617. while (firstShownChild &&
  1618. firstShownChild.classList.contains('shaka-hidden')) {
  1619. firstShownChild = firstShownChild.nextElementSibling;
  1620. }
  1621. let lastShownChild = settingsMenu.lastElementChild;
  1622. while (lastShownChild &&
  1623. lastShownChild.classList.contains('shaka-hidden')) {
  1624. lastShownChild = lastShownChild.previousElementSibling;
  1625. }
  1626. const activeElement = document.activeElement;
  1627. // When only Tab key is pressed, navigate to the next elememnt.
  1628. // If it's currently focused on the last shown child element of the
  1629. // overflow menu, let the focus move to the first child element of the
  1630. // menu.
  1631. // When Tab + Shift keys are pressed at the same time, navigate to the
  1632. // previous element. If it's currently focused on the first shown child
  1633. // element of the overflow menu, let the focus move to the last child
  1634. // element of the menu.
  1635. if (this.pressedKeys_.has('Shift')) {
  1636. if (activeElement == firstShownChild) {
  1637. event.preventDefault();
  1638. lastShownChild.focus();
  1639. }
  1640. } else {
  1641. if (activeElement == lastShownChild) {
  1642. event.preventDefault();
  1643. firstShownChild.focus();
  1644. }
  1645. }
  1646. }
  1647. }
  1648. /**
  1649. * For keyboard navigation, we use blue borders to highlight the active
  1650. * element. If we detect that a mouse is being used, remove the blue border
  1651. * from the active element.
  1652. * @private
  1653. */
  1654. onMouseDown_() {
  1655. this.eventManager_.unlisten(window, 'mousedown');
  1656. }
  1657. /**
  1658. * @export
  1659. */
  1660. showUI() {
  1661. const event = new Event('mousemove', {bubbles: false, cancelable: false});
  1662. this.onMouseMove_(event);
  1663. }
  1664. /**
  1665. * @export
  1666. */
  1667. hideUI() {
  1668. this.onMouseLeave_();
  1669. }
  1670. /**
  1671. * @return {shaka.ui.VRManager}
  1672. */
  1673. getVR() {
  1674. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1675. return this.vr_;
  1676. }
  1677. /**
  1678. * Returns if a VR is capable.
  1679. *
  1680. * @return {boolean}
  1681. * @export
  1682. */
  1683. canPlayVR() {
  1684. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1685. return this.vr_.canPlayVR();
  1686. }
  1687. /**
  1688. * Returns if a VR is supported.
  1689. *
  1690. * @return {boolean}
  1691. * @export
  1692. */
  1693. isPlayingVR() {
  1694. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1695. return this.vr_.isPlayingVR();
  1696. }
  1697. /**
  1698. * Reset VR view.
  1699. */
  1700. resetVR() {
  1701. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1702. this.vr_.reset();
  1703. }
  1704. /**
  1705. * Get the angle of the north.
  1706. *
  1707. * @return {?number}
  1708. * @export
  1709. */
  1710. getVRNorth() {
  1711. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1712. return this.vr_.getNorth();
  1713. }
  1714. /**
  1715. * Returns the angle of the current field of view displayed in degrees.
  1716. *
  1717. * @return {?number}
  1718. * @export
  1719. */
  1720. getVRFieldOfView() {
  1721. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1722. return this.vr_.getFieldOfView();
  1723. }
  1724. /**
  1725. * Changing the field of view increases or decreases the portion of the video
  1726. * that is viewed at one time. If the field of view is decreased, a small
  1727. * part of the video will be seen, but with more detail. If the field of view
  1728. * is increased, a larger part of the video will be seen, but with less
  1729. * detail.
  1730. *
  1731. * @param {number} fieldOfView In degrees
  1732. * @export
  1733. */
  1734. setVRFieldOfView(fieldOfView) {
  1735. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1736. this.vr_.setFieldOfView(fieldOfView);
  1737. }
  1738. /**
  1739. * Toggle stereoscopic mode.
  1740. *
  1741. * @export
  1742. */
  1743. toggleStereoscopicMode() {
  1744. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1745. this.vr_.toggleStereoscopicMode();
  1746. }
  1747. /**
  1748. * Returns true if stereoscopic mode is enabled.
  1749. *
  1750. * @return {boolean}
  1751. */
  1752. isStereoscopicModeEnabled() {
  1753. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1754. return this.vr_.isStereoscopicModeEnabled();
  1755. }
  1756. /**
  1757. * Increment the yaw in X angle in degrees.
  1758. *
  1759. * @param {number} angle In degrees
  1760. * @export
  1761. */
  1762. incrementYaw(angle) {
  1763. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1764. this.vr_.incrementYaw(angle);
  1765. }
  1766. /**
  1767. * Increment the pitch in X angle in degrees.
  1768. *
  1769. * @param {number} angle In degrees
  1770. * @export
  1771. */
  1772. incrementPitch(angle) {
  1773. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1774. this.vr_.incrementPitch(angle);
  1775. }
  1776. /**
  1777. * Increment the roll in X angle in degrees.
  1778. *
  1779. * @param {number} angle In degrees
  1780. * @export
  1781. */
  1782. incrementRoll(angle) {
  1783. goog.asserts.assert(this.vr_ != null, 'Should have a VR manager!');
  1784. this.vr_.incrementRoll(angle);
  1785. }
  1786. /**
  1787. * Create a localization instance already pre-loaded with all the locales that
  1788. * we support.
  1789. *
  1790. * @return {!shaka.ui.Localization}
  1791. * @private
  1792. */
  1793. static createLocalization_() {
  1794. /** @type {string} */
  1795. const fallbackLocale = 'en';
  1796. /** @type {!shaka.ui.Localization} */
  1797. const localization = new shaka.ui.Localization(fallbackLocale);
  1798. shaka.ui.Locales.addTo(localization);
  1799. localization.changeLocale(navigator.languages || []);
  1800. return localization;
  1801. }
  1802. };
  1803. /**
  1804. * @event shaka.ui.Controls#CastStatusChangedEvent
  1805. * @description Fired upon receiving a 'caststatuschanged' event from
  1806. * the cast proxy.
  1807. * @property {string} type
  1808. * 'caststatuschanged'
  1809. * @property {boolean} newStatus
  1810. * The new status of the application. True for 'is casting' and
  1811. * false otherwise.
  1812. * @exportDoc
  1813. */
  1814. /**
  1815. * @event shaka.ui.Controls#VRStatusChangedEvent
  1816. * @description Fired when VR status change
  1817. * @property {string} type
  1818. * 'vrstatuschanged'
  1819. * @exportDoc
  1820. */
  1821. /**
  1822. * @event shaka.ui.Controls#SubMenuOpenEvent
  1823. * @description Fired when one of the overflow submenus is opened
  1824. * (e. g. language/resolution/subtitle selection).
  1825. * @property {string} type
  1826. * 'submenuopen'
  1827. * @exportDoc
  1828. */
  1829. /**
  1830. * @event shaka.ui.Controls#CaptionSelectionUpdatedEvent
  1831. * @description Fired when the captions/subtitles menu has finished updating.
  1832. * @property {string} type
  1833. * 'captionselectionupdated'
  1834. * @exportDoc
  1835. */
  1836. /**
  1837. * @event shaka.ui.Controls#ResolutionSelectionUpdatedEvent
  1838. * @description Fired when the resolution menu has finished updating.
  1839. * @property {string} type
  1840. * 'resolutionselectionupdated'
  1841. * @exportDoc
  1842. */
  1843. /**
  1844. * @event shaka.ui.Controls#LanguageSelectionUpdatedEvent
  1845. * @description Fired when the audio language menu has finished updating.
  1846. * @property {string} type
  1847. * 'languageselectionupdated'
  1848. * @exportDoc
  1849. */
  1850. /**
  1851. * @event shaka.ui.Controls#ErrorEvent
  1852. * @description Fired when something went wrong with the controls.
  1853. * @property {string} type
  1854. * 'error'
  1855. * @property {!shaka.util.Error} detail
  1856. * An object which contains details on the error. The error's 'category'
  1857. * and 'code' properties will identify the specific error that occurred.
  1858. * In an uncompiled build, you can also use the 'message' and 'stack'
  1859. * properties to debug.
  1860. * @exportDoc
  1861. */
  1862. /**
  1863. * @event shaka.ui.Controls#TimeAndSeekRangeUpdatedEvent
  1864. * @description Fired when the time and seek range elements have finished
  1865. * updating.
  1866. * @property {string} type
  1867. * 'timeandseekrangeupdated'
  1868. * @exportDoc
  1869. */
  1870. /**
  1871. * @event shaka.ui.Controls#UIUpdatedEvent
  1872. * @description Fired after a call to ui.configure() once the UI has finished
  1873. * updating.
  1874. * @property {string} type
  1875. * 'uiupdated'
  1876. * @exportDoc
  1877. */
  1878. /** @private {!Map.<string, !shaka.extern.IUIElement.Factory>} */
  1879. shaka.ui.ControlsPanel.elementNamesToFactories_ = new Map();
  1880. /** @private {?shaka.extern.IUISeekBar.Factory} */
  1881. shaka.ui.ControlsPanel.seekBarFactory_ = new shaka.ui.SeekBar.Factory();