Source: lib/ads/interstitial_ad_manager.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.ads.InterstitialAdManager');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.Player');
  9. goog.require('shaka.ads.InterstitialAd');
  10. goog.require('shaka.ads.Utils');
  11. goog.require('shaka.log');
  12. goog.require('shaka.media.PreloadManager');
  13. goog.require('shaka.net.NetworkingEngine');
  14. goog.require('shaka.util.Dom');
  15. goog.require('shaka.util.Error');
  16. goog.require('shaka.util.EventManager');
  17. goog.require('shaka.util.FakeEvent');
  18. goog.require('shaka.util.IReleasable');
  19. goog.require('shaka.util.Platform');
  20. goog.require('shaka.util.PublicPromise');
  21. goog.require('shaka.util.StringUtils');
  22. goog.require('shaka.util.Timer');
  23. goog.require('shaka.util.TXml');
  24. /**
  25. * A class responsible for Interstitial ad interactions.
  26. *
  27. * @implements {shaka.util.IReleasable}
  28. */
  29. shaka.ads.InterstitialAdManager = class {
  30. /**
  31. * @param {HTMLElement} adContainer
  32. * @param {shaka.Player} basePlayer
  33. * @param {HTMLMediaElement} baseVideo
  34. * @param {function(!shaka.util.FakeEvent)} onEvent
  35. */
  36. constructor(adContainer, basePlayer, baseVideo, onEvent) {
  37. /** @private {?shaka.extern.AdsConfiguration} */
  38. this.config_ = null;
  39. /** @private {HTMLElement} */
  40. this.adContainer_ = adContainer;
  41. /** @private {shaka.Player} */
  42. this.basePlayer_ = basePlayer;
  43. /** @private {HTMLMediaElement} */
  44. this.baseVideo_ = baseVideo;
  45. /** @private {?HTMLMediaElement} */
  46. this.adVideo_ = null;
  47. /** @private {boolean} */
  48. this.usingBaseVideo_ = true;
  49. /** @private {HTMLMediaElement} */
  50. this.video_ = this.baseVideo_;
  51. /** @private {function(!shaka.util.FakeEvent)} */
  52. this.onEvent_ = onEvent;
  53. /** @private {!Set.<string>} */
  54. this.interstitialIds_ = new Set();
  55. /** @private {!Set.<shaka.extern.AdInterstitial>} */
  56. this.interstitials_ = new Set();
  57. /**
  58. * @private {!Map.<shaka.extern.AdInterstitial,
  59. * Promise<?shaka.media.PreloadManager>>}
  60. */
  61. this.preloadManagerInterstitials_ = new Map();
  62. /** @private {shaka.Player} */
  63. this.player_ = new shaka.Player();
  64. this.updatePlayerConfig_();
  65. /** @private {shaka.util.EventManager} */
  66. this.eventManager_ = new shaka.util.EventManager();
  67. /** @private {shaka.util.EventManager} */
  68. this.adEventManager_ = new shaka.util.EventManager();
  69. /** @private {boolean} */
  70. this.playingAd_ = false;
  71. /** @private {?number} */
  72. this.lastTime_ = null;
  73. /** @private {?shaka.extern.AdInterstitial} */
  74. this.lastPlayedAd_ = null;
  75. this.eventManager_.listen(this.baseVideo_, 'timeupdate', () => {
  76. if (this.playingAd_ || this.lastTime_ ||
  77. this.basePlayer_.isRemotePlayback()) {
  78. return;
  79. }
  80. this.lastTime_ = this.baseVideo_.currentTime;
  81. const currentInterstitial = this.getCurrentInterstitial_(
  82. /* needPreRoll= */ true);
  83. if (currentInterstitial) {
  84. this.setupAd_(currentInterstitial, /* sequenceLength= */ 1,
  85. /* adPosition= */ 1, /* initialTime= */ Date.now());
  86. }
  87. });
  88. const checkForInterstitials = () => {
  89. if (this.playingAd_ || !this.lastTime_ ||
  90. this.basePlayer_.isRemotePlayback()) {
  91. return;
  92. }
  93. this.lastTime_ = this.baseVideo_.currentTime;
  94. // Remove last played add when the new time is before to the ad time.
  95. if (this.lastPlayedAd_ &&
  96. !this.lastPlayedAd_.pre && !this.lastPlayedAd_.post &&
  97. this.lastTime_ < this.lastPlayedAd_.startTime) {
  98. this.lastPlayedAd_ = null;
  99. }
  100. const currentInterstitial = this.getCurrentInterstitial_();
  101. if (currentInterstitial) {
  102. this.setupAd_(currentInterstitial, /* sequenceLength= */ 1,
  103. /* adPosition= */ 1, /* initialTime= */ Date.now());
  104. }
  105. };
  106. this.eventManager_.listen(this.baseVideo_, 'ended', () => {
  107. checkForInterstitials();
  108. });
  109. /** @private {shaka.util.Timer} */
  110. this.timeUpdateTimer_ = new shaka.util.Timer(checkForInterstitials);
  111. if ('requestVideoFrameCallback' in this.baseVideo_ &&
  112. !shaka.util.Platform.isSmartTV()) {
  113. const baseVideo = /** @type {!HTMLVideoElement} */ (this.baseVideo_);
  114. const videoFrameCallback = () => {
  115. checkForInterstitials();
  116. baseVideo.requestVideoFrameCallback(videoFrameCallback);
  117. };
  118. baseVideo.requestVideoFrameCallback(videoFrameCallback);
  119. } else {
  120. this.timeUpdateTimer_.tickEvery(/* seconds= */ 0.025);
  121. }
  122. /** @private {shaka.util.Timer} */
  123. this.pollTimer_ = new shaka.util.Timer(async () => {
  124. if (this.interstitials_.size && this.lastTime_ != null) {
  125. const currentLoadMode = this.basePlayer_.getLoadMode();
  126. if (currentLoadMode == shaka.Player.LoadMode.DESTROYED ||
  127. currentLoadMode == shaka.Player.LoadMode.NOT_LOADED) {
  128. return;
  129. }
  130. let cuepointsChanged = false;
  131. const interstitials = Array.from(this.interstitials_);
  132. const seekRange = this.basePlayer_.seekRange();
  133. for (const interstitial of interstitials) {
  134. if (interstitial == this.lastPlayedAd_) {
  135. continue;
  136. }
  137. const comparisonTime = interstitial.endTime || interstitial.startTime;
  138. if ((seekRange.start - comparisonTime) >= 1) {
  139. if (this.preloadManagerInterstitials_.has(interstitial)) {
  140. const preloadManager =
  141. // eslint-disable-next-line no-await-in-loop
  142. await this.preloadManagerInterstitials_.get(interstitial);
  143. if (preloadManager) {
  144. preloadManager.destroy();
  145. }
  146. this.preloadManagerInterstitials_.delete(interstitial);
  147. }
  148. const interstitialId = JSON.stringify(interstitial);
  149. if (this.interstitialIds_.has(interstitialId)) {
  150. this.interstitialIds_.delete(interstitialId);
  151. }
  152. this.interstitials_.delete(interstitial);
  153. cuepointsChanged = true;
  154. } else {
  155. const difference = interstitial.startTime - this.lastTime_;
  156. if (difference > 0 && difference <= 10) {
  157. if (!this.preloadManagerInterstitials_.has(interstitial)) {
  158. this.preloadManagerInterstitials_.set(
  159. interstitial, this.player_.preload(interstitial.uri));
  160. }
  161. }
  162. }
  163. }
  164. if (cuepointsChanged) {
  165. this.cuepointsChanged_();
  166. }
  167. }
  168. }).tickEvery(/* seconds= */ 1);
  169. }
  170. /**
  171. * Called by the AdManager to provide an updated configuration any time it
  172. * changes.
  173. *
  174. * @param {shaka.extern.AdsConfiguration} config
  175. */
  176. configure(config) {
  177. this.config_ = config;
  178. this.determineIfUsingBaseVideo_();
  179. }
  180. /**
  181. * @private
  182. */
  183. determineIfUsingBaseVideo_() {
  184. if (!this.adContainer_ || !this.config_ || this.playingAd_) {
  185. return;
  186. }
  187. let supportsMultipleMediaElements =
  188. this.config_.supportsMultipleMediaElements;
  189. const video = /** @type {HTMLVideoElement} */(this.baseVideo_);
  190. if (video.webkitSupportsFullscreen && video.webkitDisplayingFullscreen) {
  191. supportsMultipleMediaElements = false;
  192. }
  193. if (this.usingBaseVideo_ != supportsMultipleMediaElements) {
  194. return;
  195. }
  196. this.usingBaseVideo_ = !supportsMultipleMediaElements;
  197. if (this.usingBaseVideo_) {
  198. this.video_ = this.baseVideo_;
  199. if (this.adVideo_) {
  200. if (this.adVideo_.parentElement) {
  201. this.adContainer_.removeChild(this.adVideo_);
  202. }
  203. this.adVideo_ = null;
  204. }
  205. } else {
  206. if (!this.adVideo_) {
  207. this.adVideo_ = this.createMediaElement_();
  208. }
  209. this.video_ = this.adVideo_;
  210. }
  211. }
  212. /**
  213. * Resets the Interstitial manager and removes any continuous polling.
  214. */
  215. stop() {
  216. if (this.adEventManager_) {
  217. this.adEventManager_.removeAll();
  218. }
  219. this.interstitialIds_.clear();
  220. this.interstitials_.clear();
  221. this.player_.destroyAllPreloads();
  222. this.preloadManagerInterstitials_.clear();
  223. this.player_.detach();
  224. this.playingAd_ = false;
  225. this.lastTime_ = null;
  226. this.lastPlayedAd_ = null;
  227. }
  228. /** @override */
  229. release() {
  230. this.stop();
  231. if (this.eventManager_) {
  232. this.eventManager_.release();
  233. }
  234. if (this.adEventManager_) {
  235. this.adEventManager_.release();
  236. }
  237. if (this.adContainer_) {
  238. shaka.util.Dom.removeAllChildren(this.adContainer_);
  239. }
  240. if (this.timeUpdateTimer_) {
  241. this.timeUpdateTimer_.stop();
  242. this.timeUpdateTimer_ = null;
  243. }
  244. if (this.pollTimer_) {
  245. this.pollTimer_.stop();
  246. this.pollTimer_ = null;
  247. }
  248. this.player_.destroy();
  249. }
  250. /**
  251. * @param {shaka.extern.HLSInterstitial} hlsInterstitial
  252. */
  253. async addMetadata(hlsInterstitial) {
  254. this.updatePlayerConfig_();
  255. const adInterstitials = await this.getInterstitialsInfo_(hlsInterstitial);
  256. if (adInterstitials.length) {
  257. this.addInterstitials(adInterstitials);
  258. } else {
  259. shaka.log.alwaysWarn('Unsupported HLS interstitial', hlsInterstitial);
  260. }
  261. }
  262. /**
  263. * @param {shaka.extern.TimelineRegionInfo} region
  264. */
  265. addRegion(region) {
  266. let alternativeMPDUri;
  267. let alternativeMPDmode;
  268. for (const node of region.eventNode.children) {
  269. if (node.tagName == 'AlternativeMPD') {
  270. const uri = node.attributes['uri'];
  271. const mode = node.attributes['mode'];
  272. if (uri) {
  273. alternativeMPDUri = uri;
  274. alternativeMPDmode = mode;
  275. break;
  276. }
  277. }
  278. }
  279. if (!alternativeMPDUri) {
  280. shaka.log.alwaysWarn('Unsupported MPD alternate', region);
  281. return;
  282. }
  283. const isReplace = alternativeMPDmode == 'replace';
  284. const isInsert = alternativeMPDmode == 'insert';
  285. if (!isReplace && !isInsert) {
  286. shaka.log.warning('Unsupported MPD alternate', region);
  287. return;
  288. }
  289. const interstitial = {
  290. id: region.id,
  291. startTime: region.startTime,
  292. endTime: region.endTime,
  293. uri: alternativeMPDUri,
  294. isSkippable: false,
  295. skipOffset: null,
  296. canJump: true,
  297. resumeOffset: isInsert ? 0 : null,
  298. playoutLimit: null,
  299. once: false,
  300. pre: false,
  301. post: false,
  302. timelineRange: isReplace && !isInsert,
  303. };
  304. this.addInterstitials([interstitial]);
  305. }
  306. /**
  307. * @param {string} url
  308. * @return {!Promise}
  309. */
  310. async addAdUrlInterstitial(url) {
  311. const NetworkingEngine = shaka.net.NetworkingEngine;
  312. const context = {
  313. type: NetworkingEngine.AdvancedRequestType.INTERSTITIAL_AD_URL,
  314. };
  315. const responseData = await this.makeAdRequest_(url, context);
  316. const data = shaka.util.TXml.parseXml(responseData, 'VAST,vmap:VMAP');
  317. if (!data) {
  318. throw new shaka.util.Error(
  319. shaka.util.Error.Severity.CRITICAL,
  320. shaka.util.Error.Category.ADS,
  321. shaka.util.Error.Code.VAST_INVALID_XML);
  322. }
  323. let interstitials = [];
  324. if (data.tagName == 'VAST') {
  325. interstitials = shaka.ads.Utils.parseVastToInterstitials(
  326. data, this.lastTime_);
  327. } else if (data.tagName == 'vmap:VMAP') {
  328. for (const ad of shaka.ads.Utils.parseVMAP(data)) {
  329. // eslint-disable-next-line no-await-in-loop
  330. const vastResponseData = await this.makeAdRequest_(ad.uri, context);
  331. const vast = shaka.util.TXml.parseXml(vastResponseData, 'VAST');
  332. if (!vast) {
  333. throw new shaka.util.Error(
  334. shaka.util.Error.Severity.CRITICAL,
  335. shaka.util.Error.Category.ADS,
  336. shaka.util.Error.Code.VAST_INVALID_XML);
  337. }
  338. interstitials.push(...shaka.ads.Utils.parseVastToInterstitials(
  339. vast, ad.time));
  340. }
  341. }
  342. this.addInterstitials(interstitials);
  343. }
  344. /**
  345. * @param {!Array.<shaka.extern.AdInterstitial>} interstitials
  346. */
  347. addInterstitials(interstitials) {
  348. let cuepointsChanged = false;
  349. for (const interstitial of interstitials) {
  350. const interstitialId = interstitial.id || JSON.stringify(interstitial);
  351. if (this.interstitialIds_.has(interstitialId)) {
  352. continue;
  353. }
  354. cuepointsChanged = true;
  355. this.interstitialIds_.add(interstitialId);
  356. this.interstitials_.add(interstitial);
  357. let shouldPreload = false;
  358. if (interstitial.pre && this.lastTime_ == null) {
  359. shouldPreload = true;
  360. } else if (interstitial.startTime == 0 && !interstitial.canJump) {
  361. shouldPreload = true;
  362. } else if (this.lastTime_ != null) {
  363. const difference = interstitial.startTime - this.lastTime_;
  364. if (difference > 0 && difference <= 10) {
  365. shouldPreload = true;
  366. }
  367. }
  368. if (shouldPreload) {
  369. if (!this.preloadManagerInterstitials_.has(interstitial)) {
  370. this.preloadManagerInterstitials_.set(
  371. interstitial, this.player_.preload(interstitial.uri));
  372. }
  373. }
  374. }
  375. if (cuepointsChanged) {
  376. this.cuepointsChanged_();
  377. }
  378. }
  379. /**
  380. * @return {!HTMLMediaElement}
  381. * @private
  382. */
  383. createMediaElement_() {
  384. const video = /** @type {!HTMLMediaElement} */(
  385. document.createElement(this.baseVideo_.tagName));
  386. video.autoplay = true;
  387. video.style.position = 'absolute';
  388. video.style.top = '0';
  389. video.style.left = '0';
  390. video.style.width = '100%';
  391. video.style.height = '100%';
  392. video.style.backgroundColor = 'rgb(0, 0, 0)';
  393. video.setAttribute('playsinline', '');
  394. return video;
  395. }
  396. /**
  397. * @param {boolean=} needPreRoll
  398. * @param {?number=} numberToSkip
  399. * @return {?shaka.extern.AdInterstitial}
  400. * @private
  401. */
  402. getCurrentInterstitial_(needPreRoll = false, numberToSkip = null) {
  403. let skipped = 0;
  404. let currentInterstitial = null;
  405. if (this.interstitials_.size && this.lastTime_ != null) {
  406. const isEnded = this.baseVideo_.ended;
  407. const interstitials = Array.from(this.interstitials_).sort((a, b) => {
  408. return b.startTime - a.startTime;
  409. });
  410. const roundDecimals = (number) => {
  411. return Math.round(number * 1000) / 1000;
  412. };
  413. let interstitialsToCheck = interstitials;
  414. if (needPreRoll) {
  415. interstitialsToCheck = interstitials.filter((i) => i.pre);
  416. } else if (isEnded) {
  417. interstitialsToCheck = interstitials.filter((i) => i.post);
  418. } else {
  419. interstitialsToCheck = interstitials.filter((i) => !i.pre && !i.post);
  420. }
  421. for (const interstitial of interstitialsToCheck) {
  422. let isValid = false;
  423. if (needPreRoll) {
  424. isValid = interstitial.pre;
  425. } else if (isEnded) {
  426. isValid = interstitial.post;
  427. } else if (!interstitial.pre && !interstitial.post) {
  428. const difference =
  429. this.lastTime_ - roundDecimals(interstitial.startTime);
  430. if (difference > 0 &&
  431. (difference <= 1 || !interstitial.canJump)) {
  432. if (numberToSkip == null && this.lastPlayedAd_ &&
  433. !this.lastPlayedAd_.pre && !this.lastPlayedAd_.post &&
  434. this.lastPlayedAd_.startTime >= interstitial.startTime) {
  435. isValid = false;
  436. } else {
  437. isValid = true;
  438. }
  439. }
  440. }
  441. if (isValid && (!this.lastPlayedAd_ ||
  442. interstitial.startTime >= this.lastPlayedAd_.startTime)) {
  443. if (skipped == (numberToSkip || 0)) {
  444. currentInterstitial = interstitial;
  445. } else if (currentInterstitial && !interstitial.canJump) {
  446. const currentStartTime =
  447. roundDecimals(currentInterstitial.startTime);
  448. const newStartTime =
  449. roundDecimals(interstitial.startTime);
  450. if (newStartTime - currentStartTime > 0.001) {
  451. currentInterstitial = interstitial;
  452. skipped = 0;
  453. }
  454. }
  455. skipped++;
  456. }
  457. }
  458. }
  459. return currentInterstitial;
  460. }
  461. /**
  462. * @param {shaka.extern.AdInterstitial} interstitial
  463. * @param {number} sequenceLength
  464. * @param {number} adPosition
  465. * @param {number} initialTime the clock time the ad started at
  466. * @param {number=} oncePlayed
  467. * @private
  468. */
  469. async setupAd_(interstitial, sequenceLength, adPosition, initialTime,
  470. oncePlayed = 0) {
  471. this.determineIfUsingBaseVideo_();
  472. goog.asserts.assert(this.video_, 'Must have video');
  473. this.lastPlayedAd_ = interstitial;
  474. shaka.log.info('Starting interstitial',
  475. interstitial.startTime, 'at', this.lastTime_);
  476. const startTime = Date.now();
  477. if (!this.video_.parentElement && this.adContainer_) {
  478. this.adContainer_.appendChild(this.video_);
  479. }
  480. if (adPosition == 1 && sequenceLength == 1) {
  481. sequenceLength = Array.from(this.interstitials_).filter((i) => {
  482. if (interstitial.pre) {
  483. return i.pre == interstitial.pre;
  484. } else if (interstitial.post) {
  485. return i.post == interstitial.post;
  486. }
  487. return Math.abs(i.startTime - interstitial.startTime) < 0.001;
  488. }).length;
  489. }
  490. if (interstitial.once) {
  491. oncePlayed++;
  492. this.interstitials_.delete(interstitial);
  493. this.cuepointsChanged_();
  494. }
  495. this.playingAd_ = true;
  496. if (this.usingBaseVideo_ && adPosition == 1) {
  497. this.onEvent_(new shaka.util.FakeEvent(
  498. shaka.ads.Utils.AD_CONTENT_PAUSE_REQUESTED,
  499. (new Map()).set('saveLivePosition', true)));
  500. const detachBasePlayerPromise = new shaka.util.PublicPromise();
  501. const checkState = async (e) => {
  502. if (e['state'] == 'detach') {
  503. if (shaka.util.Platform.isSmartTV()) {
  504. await new Promise(
  505. (resolve) => new shaka.util.Timer(resolve).tickAfter(0.1));
  506. }
  507. detachBasePlayerPromise.resolve();
  508. this.adEventManager_.unlisten(
  509. this.basePlayer_, 'onstatechange', checkState);
  510. }
  511. };
  512. this.adEventManager_.listen(
  513. this.basePlayer_, 'onstatechange', checkState);
  514. await detachBasePlayerPromise;
  515. }
  516. if (!this.usingBaseVideo_) {
  517. this.baseVideo_.pause();
  518. if (interstitial.resumeOffset != null &&
  519. interstitial.resumeOffset != 0) {
  520. this.baseVideo_.currentTime += interstitial.resumeOffset;
  521. }
  522. }
  523. let unloadingInterstitial = false;
  524. /** @type {?shaka.util.Timer} */
  525. let playoutLimitTimer = null;
  526. const updateBaseVideoTime = () => {
  527. if (!this.usingBaseVideo_) {
  528. if (interstitial.resumeOffset == null) {
  529. if (interstitial.timelineRange && interstitial.endTime &&
  530. interstitial.endTime != Infinity) {
  531. if (this.baseVideo_.currentTime != interstitial.endTime) {
  532. this.baseVideo_.currentTime = interstitial.endTime;
  533. }
  534. } else {
  535. const now = Date.now();
  536. this.baseVideo_.currentTime += (now - initialTime) / 1000;
  537. initialTime = now;
  538. }
  539. }
  540. }
  541. };
  542. const basicTask = async () => {
  543. updateBaseVideoTime();
  544. if (playoutLimitTimer) {
  545. playoutLimitTimer.stop();
  546. }
  547. goog.asserts.assert(typeof(oncePlayed) == 'number',
  548. 'Should be an number!');
  549. // Optimization to avoid returning to main content when there is another
  550. // interstitial below.
  551. const nextCurrentInterstitial = this.getCurrentInterstitial_(
  552. interstitial.pre, adPosition - oncePlayed);
  553. if (nextCurrentInterstitial) {
  554. this.onEvent_(
  555. new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED));
  556. this.adEventManager_.removeAll();
  557. this.setupAd_(nextCurrentInterstitial, sequenceLength,
  558. ++adPosition, initialTime, oncePlayed);
  559. } else {
  560. if (interstitial.post) {
  561. this.lastTime_ = null;
  562. this.lastPlayedAd_ = null;
  563. }
  564. if (this.usingBaseVideo_) {
  565. await this.player_.detach();
  566. } else {
  567. await this.player_.unload();
  568. }
  569. if (this.usingBaseVideo_) {
  570. let offset = interstitial.resumeOffset;
  571. if (offset == null) {
  572. if (interstitial.timelineRange && interstitial.endTime &&
  573. interstitial.endTime != Infinity) {
  574. offset = interstitial.endTime - (this.lastTime_ || 0);
  575. } else {
  576. offset = (Date.now() - initialTime) / 1000;
  577. }
  578. }
  579. this.onEvent_(new shaka.util.FakeEvent(
  580. shaka.ads.Utils.AD_CONTENT_RESUME_REQUESTED,
  581. (new Map()).set('offset', offset)));
  582. }
  583. this.onEvent_(
  584. new shaka.util.FakeEvent(shaka.ads.Utils.AD_STOPPED));
  585. this.adEventManager_.removeAll();
  586. this.playingAd_ = false;
  587. if (!this.usingBaseVideo_) {
  588. updateBaseVideoTime();
  589. if (!this.baseVideo_.ended) {
  590. this.baseVideo_.play();
  591. }
  592. } else {
  593. this.cuepointsChanged_();
  594. }
  595. this.determineIfUsingBaseVideo_();
  596. }
  597. };
  598. const error = async (e) => {
  599. if (unloadingInterstitial) {
  600. return;
  601. }
  602. unloadingInterstitial = true;
  603. this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_ERROR,
  604. (new Map()).set('originalEvent', e)));
  605. await basicTask();
  606. };
  607. const complete = async () => {
  608. if (unloadingInterstitial) {
  609. return;
  610. }
  611. unloadingInterstitial = true;
  612. await basicTask();
  613. this.onEvent_(
  614. new shaka.util.FakeEvent(shaka.ads.Utils.AD_COMPLETE));
  615. };
  616. const onSkip = async () => {
  617. if (unloadingInterstitial) {
  618. return;
  619. }
  620. unloadingInterstitial = true;
  621. this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.AD_SKIPPED));
  622. await basicTask();
  623. };
  624. const ad = new shaka.ads.InterstitialAd(this.video_,
  625. interstitial.isSkippable, interstitial.skipOffset,
  626. onSkip, sequenceLength, adPosition);
  627. if (!this.usingBaseVideo_) {
  628. ad.setMuted(this.baseVideo_.muted);
  629. ad.setVolume(this.baseVideo_.volume);
  630. }
  631. this.onEvent_(
  632. new shaka.util.FakeEvent(shaka.ads.Utils.AD_STARTED,
  633. (new Map()).set('ad', ad)));
  634. if (ad.canSkipNow()) {
  635. this.onEvent_(new shaka.util.FakeEvent(
  636. shaka.ads.Utils.AD_SKIP_STATE_CHANGED));
  637. }
  638. const eventsSent = new Set();
  639. this.adEventManager_.listenOnce(this.player_, 'error', error);
  640. this.adEventManager_.listen(this.video_, 'timeupdate', () => {
  641. const duration = this.video_.duration;
  642. if (!duration) {
  643. return;
  644. }
  645. if (interstitial.isSkippable && interstitial.skipOffset &&
  646. ad.canSkipNow() && ad.getRemainingTime() > 0 &&
  647. ad.getDuration() > 0) {
  648. this.onEvent_(
  649. new shaka.util.FakeEvent(shaka.ads.Utils.AD_SKIP_STATE_CHANGED));
  650. }
  651. const currentPercent = 100 * this.video_.currentTime / duration;
  652. if (currentPercent >= 25 && !eventsSent.has('firstquartile')) {
  653. updateBaseVideoTime();
  654. this.onEvent_(
  655. new shaka.util.FakeEvent(shaka.ads.Utils.AD_FIRST_QUARTILE));
  656. eventsSent.add('firstquartile');
  657. } else if (currentPercent >= 50 && !eventsSent.has('midpoint')) {
  658. updateBaseVideoTime();
  659. this.onEvent_(
  660. new shaka.util.FakeEvent(shaka.ads.Utils.AD_MIDPOINT));
  661. eventsSent.add('midpoint');
  662. } else if (currentPercent >= 75 && !eventsSent.has('thirdquartile')) {
  663. updateBaseVideoTime();
  664. this.onEvent_(
  665. new shaka.util.FakeEvent(shaka.ads.Utils.AD_THIRD_QUARTILE));
  666. eventsSent.add('thirdquartile');
  667. }
  668. });
  669. this.adEventManager_.listenOnce(this.player_, 'complete', complete);
  670. this.adEventManager_.listen(this.video_, 'play', () => {
  671. this.onEvent_(
  672. new shaka.util.FakeEvent(shaka.ads.Utils.AD_RESUMED));
  673. });
  674. this.adEventManager_.listen(this.video_, 'pause', () => {
  675. // playRangeEnd in src= causes the ended event not to be fired when that
  676. // position is reached, instead pause event is fired.
  677. const currentConfig = this.player_.getConfiguration();
  678. if (this.video_.currentTime >= currentConfig.playRangeEnd) {
  679. complete();
  680. return;
  681. }
  682. this.onEvent_(
  683. new shaka.util.FakeEvent(shaka.ads.Utils.AD_PAUSED));
  684. });
  685. this.adEventManager_.listen(this.video_, 'volumechange', () => {
  686. if (this.video_.muted) {
  687. this.onEvent_(
  688. new shaka.util.FakeEvent(shaka.ads.Utils.AD_MUTED));
  689. } else {
  690. this.onEvent_(
  691. new shaka.util.FakeEvent(shaka.ads.Utils.AD_VOLUME_CHANGED));
  692. }
  693. });
  694. try {
  695. this.updatePlayerConfig_();
  696. if (interstitial.startTime && interstitial.endTime &&
  697. interstitial.endTime != Infinity &&
  698. interstitial.startTime != interstitial.endTime) {
  699. const duration = interstitial.endTime - interstitial.startTime;
  700. if (duration > 0) {
  701. this.player_.configure('playRangeEnd', duration);
  702. }
  703. }
  704. if (interstitial.playoutLimit) {
  705. playoutLimitTimer = new shaka.util.Timer(() => {
  706. ad.skip();
  707. }).tickAfter(interstitial.playoutLimit);
  708. this.player_.configure('playRangeEnd', interstitial.playoutLimit);
  709. }
  710. await this.player_.attach(this.video_);
  711. if (this.preloadManagerInterstitials_.has(interstitial)) {
  712. const preloadManager =
  713. await this.preloadManagerInterstitials_.get(interstitial);
  714. this.preloadManagerInterstitials_.delete(interstitial);
  715. if (preloadManager) {
  716. await this.player_.load(preloadManager);
  717. } else {
  718. await this.player_.load(interstitial.uri);
  719. }
  720. } else {
  721. await this.player_.load(interstitial.uri);
  722. }
  723. if (interstitial.playoutLimit) {
  724. if (playoutLimitTimer) {
  725. playoutLimitTimer.stop();
  726. }
  727. playoutLimitTimer = new shaka.util.Timer(() => {
  728. ad.skip();
  729. }).tickAfter(interstitial.playoutLimit);
  730. }
  731. const loadTime = (Date.now() - startTime) / 1000;
  732. this.onEvent_(new shaka.util.FakeEvent(shaka.ads.Utils.ADS_LOADED,
  733. (new Map()).set('loadTime', loadTime)));
  734. if (this.usingBaseVideo_) {
  735. this.baseVideo_.play();
  736. }
  737. } catch (e) {
  738. error(e);
  739. }
  740. }
  741. /**
  742. * @param {shaka.extern.HLSInterstitial} hlsInterstitial
  743. * @return {!Promise.<!Array.<shaka.extern.AdInterstitial>>}
  744. * @private
  745. */
  746. async getInterstitialsInfo_(hlsInterstitial) {
  747. const interstitialsAd = [];
  748. if (!hlsInterstitial) {
  749. return interstitialsAd;
  750. }
  751. const assetUri = hlsInterstitial.values.find((v) => v.key == 'X-ASSET-URI');
  752. const assetList =
  753. hlsInterstitial.values.find((v) => v.key == 'X-ASSET-LIST');
  754. if (!assetUri && !assetList) {
  755. return interstitialsAd;
  756. }
  757. let id = null;
  758. const hlsInterstitialId = hlsInterstitial.values.find((v) => v.key == 'ID');
  759. if (hlsInterstitialId) {
  760. id = /** @type {string} */(hlsInterstitialId.data);
  761. }
  762. const startTime = id == null ?
  763. Math.floor(hlsInterstitial.startTime * 10) / 10:
  764. hlsInterstitial.startTime;
  765. let endTime = hlsInterstitial.endTime;
  766. if (hlsInterstitial.endTime && hlsInterstitial.endTime != Infinity &&
  767. typeof(hlsInterstitial.endTime) == 'number') {
  768. endTime = id == null ?
  769. Math.floor(hlsInterstitial.endTime * 10) / 10:
  770. hlsInterstitial.endTime;
  771. }
  772. const restrict = hlsInterstitial.values.find((v) => v.key == 'X-RESTRICT');
  773. let isSkippable = true;
  774. let canJump = true;
  775. if (restrict && restrict.data) {
  776. const data = /** @type {string} */(restrict.data);
  777. isSkippable = !data.includes('SKIP');
  778. canJump = !data.includes('JUMP');
  779. }
  780. let resumeOffset = null;
  781. const resume =
  782. hlsInterstitial.values.find((v) => v.key == 'X-RESUME-OFFSET');
  783. if (resume) {
  784. const resumeOffsetString = /** @type {string} */(resume.data);
  785. resumeOffset = parseFloat(resumeOffsetString);
  786. if (isNaN(resumeOffset)) {
  787. resumeOffset = null;
  788. }
  789. }
  790. let playoutLimit = null;
  791. const playout =
  792. hlsInterstitial.values.find((v) => v.key == 'X-PLAYOUT-LIMIT');
  793. if (playout) {
  794. const playoutLimitString = /** @type {string} */(playout.data);
  795. playoutLimit = parseFloat(playoutLimitString);
  796. if (isNaN(playoutLimit)) {
  797. playoutLimit = null;
  798. }
  799. }
  800. let once = false;
  801. let pre = false;
  802. let post = false;
  803. const cue = hlsInterstitial.values.find((v) => v.key == 'CUE');
  804. if (cue) {
  805. const data = /** @type {string} */(cue.data);
  806. once = data.includes('ONCE');
  807. pre = data.includes('PRE');
  808. post = data.includes('POST');
  809. }
  810. let timelineRange = false;
  811. const timelineOccupies =
  812. hlsInterstitial.values.find((v) => v.key == 'X-TIMELINE-OCCUPIES');
  813. if (timelineOccupies) {
  814. const data = /** @type {string} */(timelineOccupies.data);
  815. timelineRange = data.includes('RANGE');
  816. } else if (!resume && this.basePlayer_.isLive()) {
  817. timelineRange = !pre && !post;
  818. }
  819. if (assetUri) {
  820. const uri = /** @type {string} */(assetUri.data);
  821. if (!uri) {
  822. return interstitialsAd;
  823. }
  824. interstitialsAd.push({
  825. id,
  826. startTime,
  827. endTime,
  828. uri,
  829. isSkippable,
  830. skipOffset: isSkippable ? 0 : null,
  831. canJump,
  832. resumeOffset,
  833. playoutLimit,
  834. once,
  835. pre,
  836. post,
  837. timelineRange,
  838. });
  839. } else if (assetList) {
  840. const uri = /** @type {string} */(assetList.data);
  841. if (!uri) {
  842. return interstitialsAd;
  843. }
  844. try {
  845. const NetworkingEngine = shaka.net.NetworkingEngine;
  846. const context = {
  847. type: NetworkingEngine.AdvancedRequestType.INTERSTITIAL_ASSET_LIST,
  848. };
  849. const responseData = await this.makeAdRequest_(uri, context);
  850. const data = shaka.util.StringUtils.fromUTF8(responseData);
  851. const dataAsJson =
  852. /** @type {!shaka.ads.InterstitialAdManager.AssetsList} */ (
  853. JSON.parse(data));
  854. for (const asset of dataAsJson['ASSETS']) {
  855. if (asset['URI']) {
  856. interstitialsAd.push({
  857. id,
  858. startTime,
  859. endTime,
  860. uri: asset['URI'],
  861. isSkippable,
  862. skipOffset: isSkippable ? 0 : null,
  863. canJump,
  864. resumeOffset,
  865. playoutLimit,
  866. once,
  867. pre,
  868. post,
  869. timelineRange,
  870. });
  871. }
  872. }
  873. } catch (e) {
  874. // Ignore errors
  875. }
  876. }
  877. return interstitialsAd;
  878. }
  879. /**
  880. * @private
  881. */
  882. cuepointsChanged_() {
  883. /** @type {!Array.<!shaka.extern.AdCuePoint>} */
  884. const cuePoints = [];
  885. for (const interstitial of this.interstitials_) {
  886. /** @type {shaka.extern.AdCuePoint} */
  887. const shakaCuePoint = {
  888. start: interstitial.startTime,
  889. end: null,
  890. };
  891. if (interstitial.pre) {
  892. shakaCuePoint.start = 0;
  893. shakaCuePoint.end = null;
  894. } else if (interstitial.post) {
  895. shakaCuePoint.start = -1;
  896. shakaCuePoint.end = null;
  897. } else if (interstitial.timelineRange) {
  898. shakaCuePoint.end = interstitial.endTime;
  899. }
  900. const isValid = !cuePoints.find((c) => {
  901. return shakaCuePoint.start == c.start && shakaCuePoint.end == c.end;
  902. });
  903. if (isValid) {
  904. cuePoints.push(shakaCuePoint);
  905. }
  906. }
  907. this.onEvent_(new shaka.util.FakeEvent(
  908. shaka.ads.Utils.CUEPOINTS_CHANGED,
  909. (new Map()).set('cuepoints', cuePoints)));
  910. }
  911. /**
  912. * @private
  913. */
  914. updatePlayerConfig_() {
  915. goog.asserts.assert(this.player_, 'Must have player');
  916. goog.asserts.assert(this.basePlayer_, 'Must have base player');
  917. this.player_.configure(this.basePlayer_.getNonDefaultConfiguration());
  918. this.player_.configure('ads.disableHLSInterstitial', true);
  919. this.player_.configure('ads.disableDASHInterstitial', true);
  920. const netEngine = this.player_.getNetworkingEngine();
  921. goog.asserts.assert(netEngine, 'Need networking engine');
  922. netEngine.clearAllRequestFilters();
  923. netEngine.clearAllResponseFilters();
  924. this.basePlayer_.getNetworkingEngine().copyFiltersInto(netEngine);
  925. }
  926. /**
  927. * @param {string} url
  928. * @param {shaka.extern.RequestContext=} context
  929. * @return {!Promise.<BufferSource>}
  930. * @private
  931. */
  932. async makeAdRequest_(url, context) {
  933. const type = shaka.net.NetworkingEngine.RequestType.ADS;
  934. const request = shaka.net.NetworkingEngine.makeRequest(
  935. [url],
  936. shaka.net.NetworkingEngine.defaultRetryParameters());
  937. const op = this.basePlayer_.getNetworkingEngine()
  938. .request(type, request, context);
  939. const response = await op.promise;
  940. return response.data;
  941. }
  942. };
  943. /**
  944. * @typedef {{
  945. * ASSETS: !Array.<shaka.ads.InterstitialAdManager.Asset>
  946. * }}
  947. *
  948. * @property {!Array.<shaka.ads.InterstitialAdManager.Asset>} ASSETS
  949. */
  950. shaka.ads.InterstitialAdManager.AssetsList;
  951. /**
  952. * @typedef {{
  953. * URI: string
  954. * }}
  955. *
  956. * @property {string} URI
  957. */
  958. shaka.ads.InterstitialAdManager.Asset;