Source: lib/media/streaming_engine.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. /**
  7. * @fileoverview
  8. */
  9. goog.provide('shaka.media.StreamingEngine');
  10. goog.require('goog.asserts');
  11. goog.require('shaka.config.CrossBoundaryStrategy');
  12. goog.require('shaka.log');
  13. goog.require('shaka.media.Capabilities');
  14. goog.require('shaka.media.InitSegmentReference');
  15. goog.require('shaka.media.ManifestParser');
  16. goog.require('shaka.media.MediaSourceEngine');
  17. goog.require('shaka.media.MetaSegmentIndex');
  18. goog.require('shaka.media.SegmentIterator');
  19. goog.require('shaka.media.SegmentReference');
  20. goog.require('shaka.media.SegmentPrefetch');
  21. goog.require('shaka.media.SegmentUtils');
  22. goog.require('shaka.net.Backoff');
  23. goog.require('shaka.net.NetworkingEngine');
  24. goog.require('shaka.util.DelayedTick');
  25. goog.require('shaka.util.Destroyer');
  26. goog.require('shaka.util.Error');
  27. goog.require('shaka.util.FakeEvent');
  28. goog.require('shaka.util.IDestroyable');
  29. goog.require('shaka.util.LanguageUtils');
  30. goog.require('shaka.util.ManifestParserUtils');
  31. goog.require('shaka.util.MimeUtils');
  32. goog.require('shaka.util.Mp4BoxParsers');
  33. goog.require('shaka.util.Mp4Parser');
  34. goog.require('shaka.util.Networking');
  35. goog.require('shaka.util.Timer');
  36. /**
  37. * @summary Creates a Streaming Engine.
  38. * The StreamingEngine is responsible for setting up the Manifest's Streams
  39. * (i.e., for calling each Stream's createSegmentIndex() function), for
  40. * downloading segments, for co-ordinating audio, video, and text buffering.
  41. * The StreamingEngine provides an interface to switch between Streams, but it
  42. * does not choose which Streams to switch to.
  43. *
  44. * The StreamingEngine does not need to be notified about changes to the
  45. * Manifest's SegmentIndexes; however, it does need to be notified when new
  46. * Variants are added to the Manifest.
  47. *
  48. * To start the StreamingEngine the owner must first call configure(), followed
  49. * by one call to switchVariant(), one optional call to switchTextStream(), and
  50. * finally a call to start(). After start() resolves, switch*() can be used
  51. * freely.
  52. *
  53. * The owner must call seeked() each time the playhead moves to a new location
  54. * within the presentation timeline; however, the owner may forego calling
  55. * seeked() when the playhead moves outside the presentation timeline.
  56. *
  57. * @implements {shaka.util.IDestroyable}
  58. */
  59. shaka.media.StreamingEngine = class {
  60. /**
  61. * @param {shaka.extern.Manifest} manifest
  62. * @param {shaka.media.StreamingEngine.PlayerInterface} playerInterface
  63. */
  64. constructor(manifest, playerInterface) {
  65. /** @private {?shaka.media.StreamingEngine.PlayerInterface} */
  66. this.playerInterface_ = playerInterface;
  67. /** @private {?shaka.extern.Manifest} */
  68. this.manifest_ = manifest;
  69. /** @private {?shaka.extern.StreamingConfiguration} */
  70. this.config_ = null;
  71. /**
  72. * Retains a reference to the function used to close SegmentIndex objects
  73. * for streams which were switched away from during an ongoing update_().
  74. * @private {!Map<string, !function()>}
  75. */
  76. this.deferredCloseSegmentIndex_ = new Map();
  77. /** @private {number} */
  78. this.bufferingScale_ = 1;
  79. /** @private {?shaka.extern.Variant} */
  80. this.currentVariant_ = null;
  81. /** @private {?shaka.extern.Stream} */
  82. this.currentTextStream_ = null;
  83. /** @private {number} */
  84. this.textStreamSequenceId_ = 0;
  85. /**
  86. * Maps a content type, e.g., 'audio', 'video', or 'text', to a MediaState.
  87. *
  88. * @private {!Map<shaka.util.ManifestParserUtils.ContentType,
  89. * !shaka.media.StreamingEngine.MediaState_>}
  90. */
  91. this.mediaStates_ = new Map();
  92. /**
  93. * Set to true once the initial media states have been created.
  94. *
  95. * @private {boolean}
  96. */
  97. this.startupComplete_ = false;
  98. /**
  99. * Used for delay and backoff of failure callbacks, so that apps do not
  100. * retry instantly.
  101. *
  102. * @private {shaka.net.Backoff}
  103. */
  104. this.failureCallbackBackoff_ = null;
  105. /**
  106. * Set to true on fatal error. Interrupts fetchAndAppend_().
  107. *
  108. * @private {boolean}
  109. */
  110. this.fatalError_ = false;
  111. /** @private {!shaka.util.Destroyer} */
  112. this.destroyer_ = new shaka.util.Destroyer(() => this.doDestroy_());
  113. /** @private {number} */
  114. this.lastMediaSourceReset_ = Date.now() / 1000;
  115. /**
  116. * @private {!Map<shaka.extern.Stream, !shaka.media.SegmentPrefetch>}
  117. */
  118. this.audioPrefetchMap_ = new Map();
  119. /** @private {!shaka.extern.SpatialVideoInfo} */
  120. this.spatialVideoInfo_ = {
  121. projection: null,
  122. hfov: null,
  123. };
  124. /** @private {number} */
  125. this.playRangeStart_ = 0;
  126. /** @private {number} */
  127. this.playRangeEnd_ = Infinity;
  128. /** @private {?shaka.media.StreamingEngine.MediaState_} */
  129. this.lastTextMediaStateBeforeUnload_ = null;
  130. /** @private {?shaka.util.Timer} */
  131. this.updateLiveSeekableRangeTime_ = new shaka.util.Timer(() => {
  132. if (!this.manifest_ || !this.playerInterface_) {
  133. return;
  134. }
  135. if (!this.manifest_.presentationTimeline.isLive()) {
  136. this.playerInterface_.mediaSourceEngine.clearLiveSeekableRange();
  137. if (this.updateLiveSeekableRangeTime_) {
  138. this.updateLiveSeekableRangeTime_.stop();
  139. }
  140. return;
  141. }
  142. const startTime = this.manifest_.presentationTimeline.getSeekRangeStart();
  143. const endTime = this.manifest_.presentationTimeline.getSeekRangeEnd();
  144. // Some older devices require the range to be greater than 1 or exceptions
  145. // are thrown, due to an old and buggy implementation.
  146. if (endTime - startTime > 1) {
  147. this.playerInterface_.mediaSourceEngine.setLiveSeekableRange(
  148. startTime, endTime);
  149. } else {
  150. this.playerInterface_.mediaSourceEngine.clearLiveSeekableRange();
  151. }
  152. });
  153. /** @private {?number} */
  154. this.boundaryTime_ = null;
  155. /** @private {?shaka.util.Timer} */
  156. this.crossBoundaryTimer_ = new shaka.util.Timer(() => {
  157. const video = this.playerInterface_.video;
  158. if (video.ended) {
  159. return;
  160. }
  161. if (this.boundaryTime_) {
  162. shaka.log.info('Crossing boundary at', this.boundaryTime_);
  163. video.currentTime = this.boundaryTime_;
  164. this.boundaryTime_ = null;
  165. }
  166. });
  167. }
  168. /** @override */
  169. destroy() {
  170. return this.destroyer_.destroy();
  171. }
  172. /**
  173. * @return {!Promise}
  174. * @private
  175. */
  176. async doDestroy_() {
  177. const aborts = [];
  178. for (const state of this.mediaStates_.values()) {
  179. this.cancelUpdate_(state);
  180. aborts.push(this.abortOperations_(state));
  181. if (state.segmentPrefetch) {
  182. state.segmentPrefetch.clearAll();
  183. state.segmentPrefetch = null;
  184. }
  185. }
  186. for (const prefetch of this.audioPrefetchMap_.values()) {
  187. prefetch.clearAll();
  188. }
  189. await Promise.all(aborts);
  190. this.mediaStates_.clear();
  191. this.audioPrefetchMap_.clear();
  192. this.playerInterface_ = null;
  193. this.manifest_ = null;
  194. this.config_ = null;
  195. if (this.updateLiveSeekableRangeTime_) {
  196. this.updateLiveSeekableRangeTime_.stop();
  197. }
  198. this.updateLiveSeekableRangeTime_ = null;
  199. if (this.crossBoundaryTimer_) {
  200. this.crossBoundaryTimer_.stop();
  201. }
  202. this.crossBoundaryTimer_ = null;
  203. }
  204. /**
  205. * Called by the Player to provide an updated configuration any time it
  206. * changes. Must be called at least once before start().
  207. *
  208. * @param {shaka.extern.StreamingConfiguration} config
  209. */
  210. configure(config) {
  211. this.config_ = config;
  212. // Create separate parameters for backoff during streaming failure.
  213. /** @type {shaka.extern.RetryParameters} */
  214. const failureRetryParams = {
  215. // The term "attempts" includes the initial attempt, plus all retries.
  216. // In order to see a delay, there would have to be at least 2 attempts.
  217. maxAttempts: Math.max(config.retryParameters.maxAttempts, 2),
  218. baseDelay: config.retryParameters.baseDelay,
  219. backoffFactor: config.retryParameters.backoffFactor,
  220. fuzzFactor: config.retryParameters.fuzzFactor,
  221. timeout: 0, // irrelevant
  222. stallTimeout: 0, // irrelevant
  223. connectionTimeout: 0, // irrelevant
  224. };
  225. // We don't want to ever run out of attempts. The application should be
  226. // allowed to retry streaming infinitely if it wishes.
  227. const autoReset = true;
  228. this.failureCallbackBackoff_ =
  229. new shaka.net.Backoff(failureRetryParams, autoReset);
  230. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  231. // disable audio segment prefetch if this is now set
  232. if (config.disableAudioPrefetch) {
  233. const state = this.mediaStates_.get(ContentType.AUDIO);
  234. if (state && state.segmentPrefetch) {
  235. state.segmentPrefetch.clearAll();
  236. state.segmentPrefetch = null;
  237. }
  238. for (const stream of this.audioPrefetchMap_.keys()) {
  239. const prefetch = this.audioPrefetchMap_.get(stream);
  240. prefetch.clearAll();
  241. this.audioPrefetchMap_.delete(stream);
  242. }
  243. }
  244. // disable text segment prefetch if this is now set
  245. if (config.disableTextPrefetch) {
  246. const state = this.mediaStates_.get(ContentType.TEXT);
  247. if (state && state.segmentPrefetch) {
  248. state.segmentPrefetch.clearAll();
  249. state.segmentPrefetch = null;
  250. }
  251. }
  252. // disable video segment prefetch if this is now set
  253. if (config.disableVideoPrefetch) {
  254. const state = this.mediaStates_.get(ContentType.VIDEO);
  255. if (state && state.segmentPrefetch) {
  256. state.segmentPrefetch.clearAll();
  257. state.segmentPrefetch = null;
  258. }
  259. }
  260. // Allow configuring the segment prefetch in middle of the playback.
  261. for (const type of this.mediaStates_.keys()) {
  262. const state = this.mediaStates_.get(type);
  263. if (state.segmentPrefetch) {
  264. state.segmentPrefetch.resetLimit(config.segmentPrefetchLimit);
  265. if (!(config.segmentPrefetchLimit > 0)) {
  266. // ResetLimit is still needed in this case,
  267. // to abort existing prefetch operations.
  268. state.segmentPrefetch.clearAll();
  269. state.segmentPrefetch = null;
  270. }
  271. } else if (config.segmentPrefetchLimit > 0) {
  272. state.segmentPrefetch = this.createSegmentPrefetch_(state.stream);
  273. }
  274. }
  275. if (!config.disableAudioPrefetch) {
  276. this.updatePrefetchMapForAudio_();
  277. }
  278. }
  279. /**
  280. * Applies a playback range. This will only affect non-live content.
  281. *
  282. * @param {number} playRangeStart
  283. * @param {number} playRangeEnd
  284. */
  285. applyPlayRange(playRangeStart, playRangeEnd) {
  286. if (!this.manifest_.presentationTimeline.isLive()) {
  287. this.playRangeStart_ = playRangeStart;
  288. this.playRangeEnd_ = playRangeEnd;
  289. }
  290. }
  291. /**
  292. * Initialize and start streaming.
  293. *
  294. * By calling this method, StreamingEngine will start streaming the variant
  295. * chosen by a prior call to switchVariant(), and optionally, the text stream
  296. * chosen by a prior call to switchTextStream(). Once the Promise resolves,
  297. * switch*() may be called freely.
  298. *
  299. * @param {!Map<number, shaka.media.SegmentPrefetch>=} segmentPrefetchById
  300. * If provided, segments prefetched for these streams will be used as needed
  301. * during playback.
  302. * @return {!Promise}
  303. */
  304. async start(segmentPrefetchById) {
  305. goog.asserts.assert(this.config_,
  306. 'StreamingEngine configure() must be called before init()!');
  307. // Setup the initial set of Streams and then begin each update cycle.
  308. await this.initStreams_(segmentPrefetchById || (new Map()));
  309. this.destroyer_.ensureNotDestroyed();
  310. shaka.log.debug('init: completed initial Stream setup');
  311. this.startupComplete_ = true;
  312. }
  313. /**
  314. * Get the current variant we are streaming. Returns null if nothing is
  315. * streaming.
  316. * @return {?shaka.extern.Variant}
  317. */
  318. getCurrentVariant() {
  319. return this.currentVariant_;
  320. }
  321. /**
  322. * Get the text stream we are streaming. Returns null if there is no text
  323. * streaming.
  324. * @return {?shaka.extern.Stream}
  325. */
  326. getCurrentTextStream() {
  327. return this.currentTextStream_;
  328. }
  329. /**
  330. * Start streaming text, creating a new media state.
  331. *
  332. * @param {shaka.extern.Stream} stream
  333. * @return {!Promise}
  334. * @private
  335. */
  336. async loadNewTextStream_(stream) {
  337. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  338. goog.asserts.assert(!this.mediaStates_.has(ContentType.TEXT),
  339. 'Should not call loadNewTextStream_ while streaming text!');
  340. this.textStreamSequenceId_++;
  341. const currentSequenceId = this.textStreamSequenceId_;
  342. try {
  343. // Clear MediaSource's buffered text, so that the new text stream will
  344. // properly replace the old buffered text.
  345. // TODO: Should this happen in unloadTextStream() instead?
  346. await this.playerInterface_.mediaSourceEngine.clear(ContentType.TEXT);
  347. } catch (error) {
  348. if (this.playerInterface_) {
  349. this.playerInterface_.onError(error);
  350. }
  351. }
  352. const mimeType = shaka.util.MimeUtils.getFullType(
  353. stream.mimeType, stream.codecs);
  354. this.playerInterface_.mediaSourceEngine.reinitText(
  355. mimeType, this.manifest_.sequenceMode, stream.external);
  356. const textDisplayer =
  357. this.playerInterface_.mediaSourceEngine.getTextDisplayer();
  358. const streamText =
  359. textDisplayer.isTextVisible() || this.config_.alwaysStreamText;
  360. if (streamText && (this.textStreamSequenceId_ == currentSequenceId)) {
  361. const state = this.createMediaState_(stream);
  362. this.mediaStates_.set(ContentType.TEXT, state);
  363. this.scheduleUpdate_(state, 0);
  364. }
  365. }
  366. /**
  367. * Stop fetching text stream when the user chooses to hide the captions.
  368. */
  369. unloadTextStream() {
  370. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  371. const state = this.mediaStates_.get(ContentType.TEXT);
  372. if (state) {
  373. this.cancelUpdate_(state);
  374. this.abortOperations_(state).catch(() => {});
  375. this.lastTextMediaStateBeforeUnload_ =
  376. this.mediaStates_.get(ContentType.TEXT);
  377. this.mediaStates_.delete(ContentType.TEXT);
  378. }
  379. this.currentTextStream_ = null;
  380. }
  381. /**
  382. * Set trick play on or off.
  383. * If trick play is on, related trick play streams will be used when possible.
  384. * @param {boolean} on
  385. */
  386. setTrickPlay(on) {
  387. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  388. this.updateSegmentIteratorReverse_();
  389. const mediaState = this.mediaStates_.get(ContentType.VIDEO);
  390. if (!mediaState) {
  391. return;
  392. }
  393. const stream = mediaState.stream;
  394. if (!stream) {
  395. return;
  396. }
  397. shaka.log.debug('setTrickPlay', on);
  398. if (on) {
  399. const trickModeVideo = stream.trickModeVideo;
  400. if (!trickModeVideo) {
  401. return; // Can't engage trick play.
  402. }
  403. const normalVideo = mediaState.restoreStreamAfterTrickPlay;
  404. if (normalVideo) {
  405. return; // Already in trick play.
  406. }
  407. shaka.log.debug('Engaging trick mode stream', trickModeVideo);
  408. this.switchInternal_(trickModeVideo, /* clearBuffer= */ false,
  409. /* safeMargin= */ 0, /* force= */ false);
  410. mediaState.restoreStreamAfterTrickPlay = stream;
  411. } else {
  412. const normalVideo = mediaState.restoreStreamAfterTrickPlay;
  413. if (!normalVideo) {
  414. return;
  415. }
  416. shaka.log.debug('Restoring non-trick-mode stream', normalVideo);
  417. mediaState.restoreStreamAfterTrickPlay = null;
  418. this.switchInternal_(normalVideo, /* clearBuffer= */ true,
  419. /* safeMargin= */ 0, /* force= */ false);
  420. }
  421. }
  422. /**
  423. * @param {shaka.extern.Variant} variant
  424. * @param {boolean=} clearBuffer
  425. * @param {number=} safeMargin
  426. * @param {boolean=} force
  427. * If true, reload the variant even if it did not change.
  428. * @param {boolean=} adaptation
  429. * If true, update the media state to indicate MediaSourceEngine should
  430. * reset the timestamp offset to ensure the new track segments are correctly
  431. * placed on the timeline.
  432. */
  433. switchVariant(
  434. variant, clearBuffer = false, safeMargin = 0, force = false,
  435. adaptation = false) {
  436. this.currentVariant_ = variant;
  437. if (!this.startupComplete_) {
  438. // The selected variant will be used in start().
  439. return;
  440. }
  441. if (variant.video) {
  442. this.switchInternal_(
  443. variant.video, /* clearBuffer= */ clearBuffer,
  444. /* safeMargin= */ safeMargin, /* force= */ force,
  445. /* adaptation= */ adaptation);
  446. }
  447. if (variant.audio) {
  448. this.switchInternal_(
  449. variant.audio, /* clearBuffer= */ clearBuffer,
  450. /* safeMargin= */ safeMargin, /* force= */ force,
  451. /* adaptation= */ adaptation);
  452. }
  453. }
  454. /**
  455. * @param {shaka.extern.Stream} textStream
  456. */
  457. async switchTextStream(textStream) {
  458. this.lastTextMediaStateBeforeUnload_ = null;
  459. this.currentTextStream_ = textStream;
  460. if (!this.startupComplete_) {
  461. // The selected text stream will be used in start().
  462. return;
  463. }
  464. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  465. goog.asserts.assert(textStream && textStream.type == ContentType.TEXT,
  466. 'Wrong stream type passed to switchTextStream!');
  467. // In HLS it is possible that the mimetype changes when the media
  468. // playlist is downloaded, so it is necessary to have the updated data
  469. // here.
  470. if (!textStream.segmentIndex) {
  471. await textStream.createSegmentIndex();
  472. }
  473. this.switchInternal_(
  474. textStream, /* clearBuffer= */ true,
  475. /* safeMargin= */ 0, /* force= */ false);
  476. }
  477. /** Reload the current text stream. */
  478. reloadTextStream() {
  479. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  480. const mediaState = this.mediaStates_.get(ContentType.TEXT);
  481. if (mediaState) { // Don't reload if there's no text to begin with.
  482. this.switchInternal_(
  483. mediaState.stream, /* clearBuffer= */ true,
  484. /* safeMargin= */ 0, /* force= */ true);
  485. }
  486. }
  487. /**
  488. * Handles deferred releases of old SegmentIndexes for the mediaState's
  489. * content type from a previous update.
  490. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  491. * @private
  492. */
  493. handleDeferredCloseSegmentIndexes_(mediaState) {
  494. for (const [key, value] of this.deferredCloseSegmentIndex_.entries()) {
  495. const streamId = /** @type {string} */ (key);
  496. const closeSegmentIndex = /** @type {!function()} */ (value);
  497. if (streamId.includes(mediaState.type)) {
  498. closeSegmentIndex();
  499. this.deferredCloseSegmentIndex_.delete(streamId);
  500. }
  501. }
  502. }
  503. /**
  504. * Switches to the given Stream. |stream| may be from any Variant.
  505. *
  506. * @param {shaka.extern.Stream} stream
  507. * @param {boolean} clearBuffer
  508. * @param {number} safeMargin
  509. * @param {boolean} force
  510. * If true, reload the text stream even if it did not change.
  511. * @param {boolean=} adaptation
  512. * If true, update the media state to indicate MediaSourceEngine should
  513. * reset the timestamp offset to ensure the new track segments are correctly
  514. * placed on the timeline.
  515. * @private
  516. */
  517. switchInternal_(stream, clearBuffer, safeMargin, force, adaptation) {
  518. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  519. const type = /** @type {!ContentType} */(stream.type);
  520. const mediaState = this.mediaStates_.get(type);
  521. if (!mediaState && stream.type == ContentType.TEXT) {
  522. this.loadNewTextStream_(stream);
  523. return;
  524. }
  525. goog.asserts.assert(mediaState, 'switch: expected mediaState to exist');
  526. if (!mediaState) {
  527. return;
  528. }
  529. if (mediaState.restoreStreamAfterTrickPlay) {
  530. shaka.log.debug('switch during trick play mode', stream);
  531. // Already in trick play mode, so stick with trick mode tracks if
  532. // possible.
  533. if (stream.trickModeVideo) {
  534. // Use the trick mode stream, but revert to the new selection later.
  535. mediaState.restoreStreamAfterTrickPlay = stream;
  536. stream = stream.trickModeVideo;
  537. shaka.log.debug('switch found trick play stream', stream);
  538. } else {
  539. // There is no special trick mode video for this stream!
  540. mediaState.restoreStreamAfterTrickPlay = null;
  541. shaka.log.debug('switch found no special trick play stream');
  542. }
  543. }
  544. if (mediaState.stream == stream && !force) {
  545. const streamTag = shaka.media.StreamingEngine.logPrefix_(mediaState);
  546. shaka.log.debug('switch: Stream ' + streamTag + ' already active');
  547. return;
  548. }
  549. if (this.audioPrefetchMap_.has(stream)) {
  550. mediaState.segmentPrefetch = this.audioPrefetchMap_.get(stream);
  551. } else if (mediaState.segmentPrefetch) {
  552. mediaState.segmentPrefetch.switchStream(stream);
  553. }
  554. if (stream.type == ContentType.TEXT) {
  555. // Mime types are allowed to change for text streams.
  556. // Reinitialize the text parser, but only if we are going to fetch the
  557. // init segment again.
  558. const fullMimeType = shaka.util.MimeUtils.getFullType(
  559. stream.mimeType, stream.codecs);
  560. this.playerInterface_.mediaSourceEngine.reinitText(
  561. fullMimeType, this.manifest_.sequenceMode, stream.external);
  562. }
  563. // Releases the segmentIndex of the old stream.
  564. // Do not close segment indexes we are prefetching.
  565. if (!this.audioPrefetchMap_.has(mediaState.stream)) {
  566. if (mediaState.stream.closeSegmentIndex) {
  567. if (mediaState.performingUpdate) {
  568. const oldStreamTag =
  569. shaka.media.StreamingEngine.logPrefix_(mediaState);
  570. if (!this.deferredCloseSegmentIndex_.has(oldStreamTag)) {
  571. // The ongoing update is still using the old stream's segment
  572. // reference information.
  573. // If we close the old stream now, the update will not complete
  574. // correctly.
  575. // The next onUpdate_() for this content type will resume the
  576. // closeSegmentIndex() operation for the old stream once the ongoing
  577. // update has finished, then immediately create a new segment index.
  578. this.deferredCloseSegmentIndex_.set(
  579. oldStreamTag, mediaState.stream.closeSegmentIndex);
  580. }
  581. } else {
  582. mediaState.stream.closeSegmentIndex();
  583. }
  584. }
  585. }
  586. const shouldResetMediaSource =
  587. mediaState.stream.isAudioMuxedInVideo != stream.isAudioMuxedInVideo;
  588. mediaState.stream = stream;
  589. mediaState.segmentIterator = null;
  590. mediaState.adaptation = !!adaptation;
  591. if (stream.dependencyStream) {
  592. mediaState.dependencyMediaState =
  593. this.createMediaState_(stream.dependencyStream);
  594. } else {
  595. mediaState.dependencyMediaState = null;
  596. }
  597. const streamTag = shaka.media.StreamingEngine.logPrefix_(mediaState);
  598. shaka.log.debug('switch: switching to Stream ' + streamTag);
  599. if (shouldResetMediaSource) {
  600. this.resetMediaSource(/* force= */ true, /* clearBuffer= */ false);
  601. return;
  602. }
  603. if (clearBuffer) {
  604. if (mediaState.clearingBuffer) {
  605. // We are already going to clear the buffer, but make sure it is also
  606. // flushed.
  607. mediaState.waitingToFlushBuffer = true;
  608. } else if (mediaState.performingUpdate) {
  609. // We are performing an update, so we have to wait until it's finished.
  610. // onUpdate_() will call clearBuffer_() when the update has finished.
  611. // We need to save the safe margin because its value will be needed when
  612. // clearing the buffer after the update.
  613. mediaState.waitingToClearBuffer = true;
  614. mediaState.clearBufferSafeMargin = safeMargin;
  615. mediaState.waitingToFlushBuffer = true;
  616. } else {
  617. // Cancel the update timer, if any.
  618. this.cancelUpdate_(mediaState);
  619. // Clear right away.
  620. this.clearBuffer_(mediaState, /* flush= */ true, safeMargin)
  621. .catch((error) => {
  622. if (this.playerInterface_) {
  623. goog.asserts.assert(error instanceof shaka.util.Error,
  624. 'Wrong error type!');
  625. this.playerInterface_.onError(error);
  626. }
  627. });
  628. }
  629. } else {
  630. if (!mediaState.performingUpdate && !mediaState.updateTimer) {
  631. this.scheduleUpdate_(mediaState, 0);
  632. }
  633. }
  634. this.makeAbortDecision_(mediaState).catch((error) => {
  635. if (this.playerInterface_) {
  636. goog.asserts.assert(error instanceof shaka.util.Error,
  637. 'Wrong error type!');
  638. this.playerInterface_.onError(error);
  639. }
  640. });
  641. }
  642. /**
  643. * Decide if it makes sense to abort the current operation, and abort it if
  644. * so.
  645. *
  646. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  647. * @private
  648. */
  649. async makeAbortDecision_(mediaState) {
  650. // If the operation is completed, it will be set to null, and there's no
  651. // need to abort the request.
  652. if (!mediaState.operation) {
  653. return;
  654. }
  655. const originalStream = mediaState.stream;
  656. const originalOperation = mediaState.operation;
  657. if (!originalStream.segmentIndex) {
  658. // Create the new segment index so the time taken is accounted for when
  659. // deciding whether to abort.
  660. await originalStream.createSegmentIndex();
  661. }
  662. if (mediaState.operation != originalOperation) {
  663. // The original operation completed while we were getting a segment index,
  664. // so there's nothing to do now.
  665. return;
  666. }
  667. if (mediaState.stream != originalStream) {
  668. // The stream changed again while we were getting a segment index. We
  669. // can't carry out this check, since another one might be in progress by
  670. // now.
  671. return;
  672. }
  673. goog.asserts.assert(mediaState.stream.segmentIndex,
  674. 'Segment index should exist by now!');
  675. if (this.shouldAbortCurrentRequest_(mediaState)) {
  676. shaka.log.info('Aborting current segment request.');
  677. mediaState.operation.abort();
  678. }
  679. }
  680. /**
  681. * Returns whether we should abort the current request.
  682. *
  683. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  684. * @return {boolean}
  685. * @private
  686. */
  687. shouldAbortCurrentRequest_(mediaState) {
  688. goog.asserts.assert(mediaState.operation,
  689. 'Abort logic requires an ongoing operation!');
  690. goog.asserts.assert(mediaState.stream && mediaState.stream.segmentIndex,
  691. 'Abort logic requires a segment index');
  692. const presentationTime = this.playerInterface_.getPresentationTime();
  693. const bufferEnd =
  694. this.playerInterface_.mediaSourceEngine.bufferEnd(mediaState.type);
  695. // The next segment to append from the current stream. This doesn't
  696. // account for a pending network request and will likely be different from
  697. // that since we just switched.
  698. const timeNeeded = this.getTimeNeeded_(mediaState, presentationTime);
  699. const index = mediaState.stream.segmentIndex.find(timeNeeded);
  700. const newSegment =
  701. index == null ? null : mediaState.stream.segmentIndex.get(index);
  702. let newSegmentSize = newSegment ? newSegment.getSize() : null;
  703. if (newSegment && !newSegmentSize) {
  704. // compute approximate segment size using stream bandwidth
  705. const duration = newSegment.getEndTime() - newSegment.getStartTime();
  706. const bandwidth = mediaState.stream.bandwidth || 0;
  707. // bandwidth is in bits per second, and the size is in bytes
  708. newSegmentSize = duration * bandwidth / 8;
  709. }
  710. if (!newSegmentSize) {
  711. return false;
  712. }
  713. // When switching, we'll need to download the init segment.
  714. const init = newSegment.initSegmentReference;
  715. if (init) {
  716. newSegmentSize += init.getSize() || 0;
  717. }
  718. const bandwidthEstimate = this.playerInterface_.getBandwidthEstimate();
  719. // The estimate is in bits per second, and the size is in bytes. The time
  720. // remaining is in seconds after this calculation.
  721. const timeToFetchNewSegment = (newSegmentSize * 8) / bandwidthEstimate;
  722. // If the new segment can be finished in time without risking a buffer
  723. // underflow, we should abort the old one and switch.
  724. const bufferedAhead = (bufferEnd || 0) - presentationTime;
  725. const safetyBuffer = this.config_.rebufferingGoal;
  726. const safeBufferedAhead = bufferedAhead - safetyBuffer;
  727. if (timeToFetchNewSegment < safeBufferedAhead) {
  728. return true;
  729. }
  730. // If the thing we want to switch to will be done more quickly than what
  731. // we've got in progress, we should abort the old one and switch.
  732. const bytesRemaining = mediaState.operation.getBytesRemaining();
  733. if (bytesRemaining > newSegmentSize) {
  734. return true;
  735. }
  736. // Otherwise, complete the operation in progress.
  737. return false;
  738. }
  739. /**
  740. * Notifies the StreamingEngine that the playhead has moved to a valid time
  741. * within the presentation timeline.
  742. */
  743. seeked() {
  744. if (!this.playerInterface_) {
  745. // Already destroyed.
  746. return;
  747. }
  748. const presentationTime = this.playerInterface_.getPresentationTime();
  749. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  750. const newTimeIsBuffered = (type) => {
  751. return this.playerInterface_.mediaSourceEngine.isBuffered(
  752. type, presentationTime);
  753. };
  754. let streamCleared = false;
  755. for (const type of this.mediaStates_.keys()) {
  756. const mediaState = this.mediaStates_.get(type);
  757. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  758. if (!newTimeIsBuffered(type)) {
  759. if (mediaState.segmentPrefetch) {
  760. mediaState.segmentPrefetch.resetPosition();
  761. }
  762. if (mediaState.type === ContentType.AUDIO) {
  763. for (const prefetch of this.audioPrefetchMap_.values()) {
  764. prefetch.resetPosition();
  765. }
  766. }
  767. mediaState.segmentIterator = null;
  768. const bufferEnd =
  769. this.playerInterface_.mediaSourceEngine.bufferEnd(type);
  770. const somethingBuffered = bufferEnd != null;
  771. // Don't clear the buffer unless something is buffered. This extra
  772. // check prevents extra, useless calls to clear the buffer.
  773. if (somethingBuffered || mediaState.performingUpdate) {
  774. this.forceClearBuffer_(mediaState);
  775. streamCleared = true;
  776. }
  777. // If there is an operation in progress, stop it now.
  778. if (mediaState.operation) {
  779. mediaState.operation.abort();
  780. shaka.log.debug(logPrefix, 'Aborting operation due to seek');
  781. mediaState.operation = null;
  782. }
  783. // The pts has shifted from the seek, invalidating captions currently
  784. // in the text buffer. Thus, clear and reset the caption parser.
  785. if (type === ContentType.TEXT) {
  786. this.playerInterface_.mediaSourceEngine.resetCaptionParser();
  787. }
  788. // Mark the media state as having seeked, so that the new buffers know
  789. // that they will need to be at a new position (for sequence mode).
  790. mediaState.seeked = true;
  791. }
  792. }
  793. if (!streamCleared) {
  794. shaka.log.debug(
  795. '(all): seeked: buffered seek: presentationTime=' + presentationTime);
  796. }
  797. }
  798. /**
  799. * Clear the buffer for a given stream. Unlike clearBuffer_, this will handle
  800. * cases where a MediaState is performing an update. After this runs, the
  801. * MediaState will have a pending update.
  802. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  803. * @private
  804. */
  805. forceClearBuffer_(mediaState) {
  806. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  807. if (mediaState.clearingBuffer) {
  808. // We're already clearing the buffer, so we don't need to clear the
  809. // buffer again.
  810. shaka.log.debug(logPrefix, 'clear: already clearing the buffer');
  811. return;
  812. }
  813. if (mediaState.waitingToClearBuffer) {
  814. // May not be performing an update, but an update will still happen.
  815. // See: https://github.com/shaka-project/shaka-player/issues/334
  816. shaka.log.debug(logPrefix, 'clear: already waiting');
  817. return;
  818. }
  819. if (mediaState.performingUpdate) {
  820. // We are performing an update, so we have to wait until it's finished.
  821. // onUpdate_() will call clearBuffer_() when the update has finished.
  822. shaka.log.debug(logPrefix, 'clear: currently updating');
  823. mediaState.waitingToClearBuffer = true;
  824. // We can set the offset to zero to remember that this was a call to
  825. // clearAllBuffers.
  826. mediaState.clearBufferSafeMargin = 0;
  827. return;
  828. }
  829. const type = mediaState.type;
  830. if (this.playerInterface_.mediaSourceEngine.bufferStart(type) == null) {
  831. // Nothing buffered.
  832. shaka.log.debug(logPrefix, 'clear: nothing buffered');
  833. if (mediaState.updateTimer == null) {
  834. // Note: an update cycle stops when we buffer to the end of the
  835. // presentation, or when we raise an error.
  836. this.scheduleUpdate_(mediaState, 0);
  837. }
  838. return;
  839. }
  840. // An update may be scheduled, but we can just cancel it and clear the
  841. // buffer right away. Note: clearBuffer_() will schedule the next update.
  842. shaka.log.debug(logPrefix, 'clear: handling right now');
  843. this.cancelUpdate_(mediaState);
  844. this.clearBuffer_(mediaState, /* flush= */ false, 0).catch((error) => {
  845. if (this.playerInterface_) {
  846. goog.asserts.assert(error instanceof shaka.util.Error,
  847. 'Wrong error type!');
  848. this.playerInterface_.onError(error);
  849. }
  850. });
  851. }
  852. /**
  853. * Initializes the initial streams and media states. This will schedule
  854. * updates for the given types.
  855. *
  856. * @param {!Map<number, shaka.media.SegmentPrefetch>} segmentPrefetchById
  857. * @return {!Promise}
  858. * @private
  859. */
  860. async initStreams_(segmentPrefetchById) {
  861. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  862. goog.asserts.assert(this.config_,
  863. 'StreamingEngine configure() must be called before init()!');
  864. if (!this.currentVariant_) {
  865. shaka.log.error('init: no Streams chosen');
  866. throw new shaka.util.Error(
  867. shaka.util.Error.Severity.CRITICAL,
  868. shaka.util.Error.Category.STREAMING,
  869. shaka.util.Error.Code.STREAMING_ENGINE_STARTUP_INVALID_STATE);
  870. }
  871. /**
  872. * @type {!Map<shaka.util.ManifestParserUtils.ContentType,
  873. * shaka.extern.Stream>}
  874. */
  875. const streamsByType = new Map();
  876. /** @type {!Set<shaka.extern.Stream>} */
  877. const streams = new Set();
  878. if (this.currentVariant_.audio) {
  879. streamsByType.set(ContentType.AUDIO, this.currentVariant_.audio);
  880. streams.add(this.currentVariant_.audio);
  881. }
  882. if (this.currentVariant_.video) {
  883. streamsByType.set(ContentType.VIDEO, this.currentVariant_.video);
  884. streams.add(this.currentVariant_.video);
  885. }
  886. if (this.currentTextStream_) {
  887. streamsByType.set(ContentType.TEXT, this.currentTextStream_);
  888. streams.add(this.currentTextStream_);
  889. }
  890. // Init MediaSourceEngine.
  891. const mediaSourceEngine = this.playerInterface_.mediaSourceEngine;
  892. await mediaSourceEngine.init(streamsByType,
  893. this.manifest_.sequenceMode,
  894. this.manifest_.type,
  895. this.manifest_.ignoreManifestTimestampsInSegmentsMode,
  896. );
  897. this.destroyer_.ensureNotDestroyed();
  898. this.updateDuration();
  899. for (const type of streamsByType.keys()) {
  900. const stream = streamsByType.get(type);
  901. if (!this.mediaStates_.has(type)) {
  902. const mediaState = this.createMediaState_(stream);
  903. if (segmentPrefetchById.has(stream.id)) {
  904. const segmentPrefetch = segmentPrefetchById.get(stream.id);
  905. segmentPrefetch.replaceFetchDispatcher(
  906. (reference, stream, streamDataCallback) => {
  907. return this.dispatchFetch_(
  908. reference, stream, streamDataCallback);
  909. });
  910. mediaState.segmentPrefetch = segmentPrefetch;
  911. }
  912. this.mediaStates_.set(type, mediaState);
  913. this.scheduleUpdate_(mediaState, 0);
  914. }
  915. }
  916. }
  917. /**
  918. * Creates a media state.
  919. *
  920. * @param {shaka.extern.Stream} stream
  921. * @return {shaka.media.StreamingEngine.MediaState_}
  922. * @private
  923. */
  924. createMediaState_(stream) {
  925. /** @type {!shaka.media.StreamingEngine.MediaState_} */
  926. const mediaState = {
  927. stream,
  928. type: /** @type {shaka.util.ManifestParserUtils.ContentType} */(
  929. stream.type),
  930. segmentIterator: null,
  931. segmentPrefetch: this.createSegmentPrefetch_(stream),
  932. lastSegmentReference: null,
  933. lastInitSegmentReference: null,
  934. lastTimestampOffset: null,
  935. lastAppendWindowStart: null,
  936. lastAppendWindowEnd: null,
  937. lastCodecs: null,
  938. lastMimeType: null,
  939. restoreStreamAfterTrickPlay: null,
  940. endOfStream: false,
  941. performingUpdate: false,
  942. updateTimer: null,
  943. waitingToClearBuffer: false,
  944. clearBufferSafeMargin: 0,
  945. waitingToFlushBuffer: false,
  946. clearingBuffer: false,
  947. // The playhead might be seeking on startup, if a start time is set, so
  948. // start "seeked" as true.
  949. seeked: true,
  950. adaptation: false,
  951. recovering: false,
  952. hasError: false,
  953. operation: null,
  954. dependencyMediaState: null,
  955. };
  956. if (stream.dependencyStream) {
  957. mediaState.dependencyMediaState =
  958. this.createMediaState_(stream.dependencyStream);
  959. }
  960. return mediaState;
  961. }
  962. /**
  963. * Creates a media state.
  964. *
  965. * @param {shaka.extern.Stream} stream
  966. * @return {shaka.media.SegmentPrefetch | null}
  967. * @private
  968. */
  969. createSegmentPrefetch_(stream) {
  970. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  971. if (stream.type === ContentType.VIDEO &&
  972. this.config_.disableVideoPrefetch) {
  973. return null;
  974. }
  975. if (stream.type === ContentType.AUDIO &&
  976. this.config_.disableAudioPrefetch) {
  977. return null;
  978. }
  979. const MimeUtils = shaka.util.MimeUtils;
  980. const CEA608_MIME = MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE;
  981. const CEA708_MIME = MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE;
  982. if (stream.type === ContentType.TEXT &&
  983. (stream.mimeType == CEA608_MIME || stream.mimeType == CEA708_MIME)) {
  984. return null;
  985. }
  986. if (stream.type === ContentType.TEXT &&
  987. this.config_.disableTextPrefetch) {
  988. return null;
  989. }
  990. if (this.audioPrefetchMap_.has(stream)) {
  991. return this.audioPrefetchMap_.get(stream);
  992. }
  993. const type = /** @type {!shaka.util.ManifestParserUtils.ContentType} */
  994. (stream.type);
  995. const mediaState = this.mediaStates_.get(type);
  996. const currentSegmentPrefetch = mediaState && mediaState.segmentPrefetch;
  997. if (currentSegmentPrefetch &&
  998. stream === currentSegmentPrefetch.getStream()) {
  999. return currentSegmentPrefetch;
  1000. }
  1001. if (this.config_.segmentPrefetchLimit > 0) {
  1002. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  1003. return new shaka.media.SegmentPrefetch(
  1004. this.config_.segmentPrefetchLimit,
  1005. stream,
  1006. (reference, stream, streamDataCallback) => {
  1007. return this.dispatchFetch_(reference, stream, streamDataCallback);
  1008. },
  1009. reverse);
  1010. }
  1011. return null;
  1012. }
  1013. /**
  1014. * Populates the prefetch map depending on the configuration
  1015. * @private
  1016. */
  1017. updatePrefetchMapForAudio_() {
  1018. const prefetchLimit = this.config_.segmentPrefetchLimit;
  1019. const prefetchLanguages = this.config_.prefetchAudioLanguages;
  1020. const LanguageUtils = shaka.util.LanguageUtils;
  1021. for (const variant of this.manifest_.variants) {
  1022. if (!variant.audio) {
  1023. continue;
  1024. }
  1025. if (this.audioPrefetchMap_.has(variant.audio)) {
  1026. // if we already have a segment prefetch,
  1027. // update it's prefetch limit and if the new limit isn't positive,
  1028. // remove the segment prefetch from our prefetch map.
  1029. const prefetch = this.audioPrefetchMap_.get(variant.audio);
  1030. prefetch.resetLimit(prefetchLimit);
  1031. if (!(prefetchLimit > 0) ||
  1032. !prefetchLanguages.some(
  1033. (lang) => LanguageUtils.areLanguageCompatible(
  1034. variant.audio.language, lang))
  1035. ) {
  1036. const type = /** @type {!shaka.util.ManifestParserUtils.ContentType}*/
  1037. (variant.audio.type);
  1038. const mediaState = this.mediaStates_.get(type);
  1039. const currentSegmentPrefetch = mediaState &&
  1040. mediaState.segmentPrefetch;
  1041. // if this prefetch isn't the current one, we want to clear it
  1042. if (prefetch !== currentSegmentPrefetch) {
  1043. prefetch.clearAll();
  1044. }
  1045. this.audioPrefetchMap_.delete(variant.audio);
  1046. }
  1047. continue;
  1048. }
  1049. // don't try to create a new segment prefetch if the limit isn't positive.
  1050. if (prefetchLimit <= 0) {
  1051. continue;
  1052. }
  1053. // only create a segment prefetch if its language is configured
  1054. // to be prefetched
  1055. if (!prefetchLanguages.some(
  1056. (lang) => LanguageUtils.areLanguageCompatible(
  1057. variant.audio.language, lang))) {
  1058. continue;
  1059. }
  1060. // use the helper to create a segment prefetch to ensure that existing
  1061. // objects are reused.
  1062. const segmentPrefetch = this.createSegmentPrefetch_(variant.audio);
  1063. // if a segment prefetch wasn't created, skip the rest
  1064. if (!segmentPrefetch) {
  1065. continue;
  1066. }
  1067. if (!variant.audio.segmentIndex) {
  1068. variant.audio.createSegmentIndex();
  1069. }
  1070. this.audioPrefetchMap_.set(variant.audio, segmentPrefetch);
  1071. }
  1072. }
  1073. /**
  1074. * Sets the MediaSource's duration.
  1075. */
  1076. updateDuration() {
  1077. const isInfiniteLiveStreamDurationSupported =
  1078. shaka.media.Capabilities.isInfiniteLiveStreamDurationSupported();
  1079. const duration = this.manifest_.presentationTimeline.getDuration();
  1080. if (duration < Infinity) {
  1081. if (isInfiniteLiveStreamDurationSupported) {
  1082. if (this.updateLiveSeekableRangeTime_) {
  1083. this.updateLiveSeekableRangeTime_.stop();
  1084. }
  1085. this.playerInterface_.mediaSourceEngine.clearLiveSeekableRange();
  1086. }
  1087. this.playerInterface_.mediaSourceEngine.setDuration(duration);
  1088. } else {
  1089. // Set the media source live duration as Infinity if the platform supports
  1090. // it.
  1091. if (isInfiniteLiveStreamDurationSupported) {
  1092. if (this.updateLiveSeekableRangeTime_) {
  1093. this.updateLiveSeekableRangeTime_.tickEvery(/* seconds= */ 0.5);
  1094. }
  1095. this.playerInterface_.mediaSourceEngine.setDuration(Infinity);
  1096. } else {
  1097. // Not all platforms support infinite durations, so set a finite
  1098. // duration so we can append segments and so the user agent can seek.
  1099. this.playerInterface_.mediaSourceEngine.setDuration(Math.pow(2, 32));
  1100. }
  1101. }
  1102. }
  1103. /**
  1104. * Called when |mediaState|'s update timer has expired.
  1105. *
  1106. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  1107. * @suppress {suspiciousCode} The compiler assumes that updateTimer can't
  1108. * change during the await, and so complains about the null check.
  1109. * @private
  1110. */
  1111. async onUpdate_(mediaState) {
  1112. this.destroyer_.ensureNotDestroyed();
  1113. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1114. // Sanity check.
  1115. goog.asserts.assert(
  1116. !mediaState.performingUpdate && (mediaState.updateTimer != null),
  1117. logPrefix + ' unexpected call to onUpdate_()');
  1118. if (mediaState.performingUpdate || (mediaState.updateTimer == null)) {
  1119. return;
  1120. }
  1121. goog.asserts.assert(
  1122. !mediaState.clearingBuffer, logPrefix +
  1123. ' onUpdate_() should not be called when clearing the buffer');
  1124. if (mediaState.clearingBuffer) {
  1125. return;
  1126. }
  1127. mediaState.updateTimer = null;
  1128. // Handle pending buffer clears.
  1129. if (mediaState.waitingToClearBuffer) {
  1130. // Note: clearBuffer_() will schedule the next update.
  1131. shaka.log.debug(logPrefix, 'skipping update and clearing the buffer');
  1132. await this.clearBuffer_(
  1133. mediaState, mediaState.waitingToFlushBuffer,
  1134. mediaState.clearBufferSafeMargin);
  1135. return;
  1136. }
  1137. // If stream switches happened during the previous update_() for this
  1138. // content type, close out the old streams that were switched away from.
  1139. // Even if we had switched away from the active stream 'A' during the
  1140. // update_(), e.g. (A -> B -> A), closing 'A' is permissible here since we
  1141. // will immediately re-create it in the logic below.
  1142. this.handleDeferredCloseSegmentIndexes_(mediaState);
  1143. // Make sure the segment index exists. If not, create the segment index.
  1144. if (!mediaState.stream.segmentIndex) {
  1145. const thisStream = mediaState.stream;
  1146. try {
  1147. await mediaState.stream.createSegmentIndex();
  1148. } catch (error) {
  1149. await this.handleStreamingError_(mediaState, error);
  1150. return;
  1151. }
  1152. if (thisStream != mediaState.stream) {
  1153. // We switched streams while in the middle of this async call to
  1154. // createSegmentIndex. Abandon this update and schedule a new one if
  1155. // there's not already one pending.
  1156. // Releases the segmentIndex of the old stream.
  1157. if (thisStream.closeSegmentIndex) {
  1158. goog.asserts.assert(!mediaState.stream.segmentIndex,
  1159. 'mediaState.stream should not have segmentIndex yet.');
  1160. thisStream.closeSegmentIndex();
  1161. }
  1162. if (!mediaState.performingUpdate && !mediaState.updateTimer) {
  1163. this.scheduleUpdate_(mediaState, 0);
  1164. }
  1165. return;
  1166. }
  1167. }
  1168. // Update the MediaState.
  1169. try {
  1170. const delay = this.update_(mediaState);
  1171. if (delay != null) {
  1172. this.scheduleUpdate_(mediaState, delay);
  1173. mediaState.hasError = false;
  1174. }
  1175. } catch (error) {
  1176. await this.handleStreamingError_(mediaState, error);
  1177. return;
  1178. }
  1179. const mediaStates = Array.from(this.mediaStates_.values());
  1180. // Check if we've buffered to the end of the presentation. We delay adding
  1181. // the audio and video media states, so it is possible for the text stream
  1182. // to be the only state and buffer to the end. So we need to wait until we
  1183. // have completed startup to determine if we have reached the end.
  1184. if (this.startupComplete_ &&
  1185. mediaStates.every((ms) => ms.endOfStream)) {
  1186. shaka.log.v1(logPrefix, 'calling endOfStream()...');
  1187. await this.playerInterface_.mediaSourceEngine.endOfStream();
  1188. this.destroyer_.ensureNotDestroyed();
  1189. // If the media segments don't reach the end, then we need to update the
  1190. // timeline duration to match the final media duration to avoid
  1191. // buffering forever at the end.
  1192. // We should only do this if the duration needs to shrink.
  1193. // Growing it by less than 1ms can actually cause buffering on
  1194. // replay, as in https://github.com/shaka-project/shaka-player/issues/979
  1195. // On some platforms, this can spuriously be 0, so ignore this case.
  1196. // https://github.com/shaka-project/shaka-player/issues/1967,
  1197. const duration = this.playerInterface_.mediaSourceEngine.getDuration();
  1198. if (duration != 0 &&
  1199. duration < this.manifest_.presentationTimeline.getDuration()) {
  1200. this.manifest_.presentationTimeline.setDuration(duration);
  1201. }
  1202. }
  1203. }
  1204. /**
  1205. * Updates the given MediaState.
  1206. *
  1207. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1208. * @return {?number} The number of seconds to wait until updating again or
  1209. * null if another update does not need to be scheduled.
  1210. * @private
  1211. */
  1212. update_(mediaState) {
  1213. goog.asserts.assert(this.manifest_, 'manifest_ should not be null');
  1214. goog.asserts.assert(this.config_, 'config_ should not be null');
  1215. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1216. // Do not schedule update for closed captions text mediaState, since closed
  1217. // captions are embedded in video streams.
  1218. if (shaka.media.StreamingEngine.isEmbeddedText_(mediaState)) {
  1219. this.playerInterface_.mediaSourceEngine.setSelectedClosedCaptionId(
  1220. mediaState.stream.originalId || '');
  1221. return null;
  1222. } else if (mediaState.type == ContentType.TEXT) {
  1223. // Disable embedded captions if not desired (e.g. if transitioning from
  1224. // embedded to not-embedded captions).
  1225. this.playerInterface_.mediaSourceEngine.clearSelectedClosedCaptionId();
  1226. }
  1227. if (mediaState.stream.isAudioMuxedInVideo) {
  1228. return null;
  1229. }
  1230. // Update updateIntervalSeconds according to our current playbackrate,
  1231. // and always considering a minimum of 1.
  1232. const updateIntervalSeconds = this.config_.updateIntervalSeconds /
  1233. Math.max(1, Math.abs(this.playerInterface_.getPlaybackRate()));
  1234. if (!this.playerInterface_.mediaSourceEngine.isStreamingAllowed() &&
  1235. mediaState.type != ContentType.TEXT) {
  1236. // It is not allowed to add segments yet, so we schedule an update to
  1237. // check again later. So any prediction we make now could be terribly
  1238. // invalid soon.
  1239. return updateIntervalSeconds / 2;
  1240. }
  1241. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1242. // Compute how far we've buffered ahead of the playhead.
  1243. const presentationTime = this.playerInterface_.getPresentationTime();
  1244. if (mediaState.type === ContentType.AUDIO) {
  1245. // evict all prefetched segments that are before the presentationTime
  1246. for (const stream of this.audioPrefetchMap_.keys()) {
  1247. const prefetch = this.audioPrefetchMap_.get(stream);
  1248. prefetch.evict(presentationTime, /* clearInitSegments= */ true);
  1249. prefetch.prefetchSegmentsByTime(presentationTime);
  1250. }
  1251. }
  1252. // Get the next timestamp we need.
  1253. const timeNeeded = this.getTimeNeeded_(mediaState, presentationTime);
  1254. shaka.log.v2(logPrefix, 'timeNeeded=' + timeNeeded);
  1255. // Get the amount of content we have buffered, accounting for drift. This
  1256. // is only used to determine if we have meet the buffering goal. This
  1257. // should be the same method that PlayheadObserver uses.
  1258. const bufferedAhead =
  1259. this.playerInterface_.mediaSourceEngine.bufferedAheadOf(
  1260. mediaState.type, presentationTime);
  1261. shaka.log.v2(logPrefix,
  1262. 'update_:',
  1263. 'presentationTime=' + presentationTime,
  1264. 'bufferedAhead=' + bufferedAhead);
  1265. const unscaledBufferingGoal = Math.max(
  1266. this.config_.rebufferingGoal, this.config_.bufferingGoal);
  1267. const scaledBufferingGoal = Math.max(1,
  1268. unscaledBufferingGoal * this.bufferingScale_);
  1269. // Check if we've buffered to the end of the presentation.
  1270. const timeUntilEnd =
  1271. this.manifest_.presentationTimeline.getDuration() - timeNeeded;
  1272. const oneMicrosecond = 1e-6;
  1273. const bufferEnd =
  1274. this.playerInterface_.mediaSourceEngine.bufferEnd(mediaState.type);
  1275. if (timeUntilEnd < oneMicrosecond && !!bufferEnd) {
  1276. // We shouldn't rebuffer if the playhead is close to the end of the
  1277. // presentation.
  1278. shaka.log.debug(logPrefix, 'buffered to end of presentation');
  1279. mediaState.endOfStream = true;
  1280. if (mediaState.type == ContentType.VIDEO) {
  1281. // Since the text stream of CEA closed captions doesn't have update
  1282. // timer, we have to set the text endOfStream based on the video
  1283. // stream's endOfStream state.
  1284. const textState = this.mediaStates_.get(ContentType.TEXT);
  1285. if (textState &&
  1286. shaka.media.StreamingEngine.isEmbeddedText_(textState)) {
  1287. textState.endOfStream = true;
  1288. }
  1289. }
  1290. return null;
  1291. }
  1292. mediaState.endOfStream = false;
  1293. // If we've buffered to the buffering goal then schedule an update.
  1294. if (bufferedAhead >= scaledBufferingGoal) {
  1295. shaka.log.v2(logPrefix, 'buffering goal met');
  1296. // Do not try to predict the next update. Just poll according to
  1297. // configuration (seconds).
  1298. return updateIntervalSeconds / 2;
  1299. }
  1300. // Lack of segment iterator is the best indicator stream has changed.
  1301. const streamChanged = !mediaState.segmentIterator;
  1302. const reference = this.getSegmentReferenceNeeded_(
  1303. mediaState, presentationTime, bufferEnd);
  1304. if (!reference) {
  1305. // The segment could not be found, does not exist, or is not available.
  1306. // In any case just try again... if the manifest is incomplete or is not
  1307. // being updated then we'll idle forever; otherwise, we'll end up getting
  1308. // a SegmentReference eventually.
  1309. return updateIntervalSeconds;
  1310. }
  1311. // Get media state adaptation and reset this value. By guarding it during
  1312. // actual stream change we ensure it won't be cleaned by accident on regular
  1313. // append.
  1314. let adaptation = false;
  1315. if (streamChanged && mediaState.adaptation) {
  1316. adaptation = true;
  1317. mediaState.adaptation = false;
  1318. }
  1319. // Do not let any one stream get far ahead of any other.
  1320. let minTimeNeeded = Infinity;
  1321. const mediaStates = Array.from(this.mediaStates_.values());
  1322. for (const otherState of mediaStates) {
  1323. // Do not consider embedded captions in this calculation. It could lead
  1324. // to hangs in streaming.
  1325. if (shaka.media.StreamingEngine.isEmbeddedText_(otherState)) {
  1326. continue;
  1327. }
  1328. // If there is no next segment, ignore this stream. This happens with
  1329. // text when there's a Period with no text in it.
  1330. if (otherState.segmentIterator && !otherState.segmentIterator.current()) {
  1331. continue;
  1332. }
  1333. const timeNeeded = this.getTimeNeeded_(otherState, presentationTime);
  1334. minTimeNeeded = Math.min(minTimeNeeded, timeNeeded);
  1335. }
  1336. const maxSegmentDuration =
  1337. this.manifest_.presentationTimeline.getMaxSegmentDuration();
  1338. const maxRunAhead = maxSegmentDuration *
  1339. shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_;
  1340. if (timeNeeded >= minTimeNeeded + maxRunAhead) {
  1341. // Wait and give other media types time to catch up to this one.
  1342. // For example, let video buffering catch up to audio buffering before
  1343. // fetching another audio segment.
  1344. shaka.log.v2(logPrefix, 'waiting for other streams to buffer');
  1345. return updateIntervalSeconds;
  1346. }
  1347. const CrossBoundaryStrategy = shaka.config.CrossBoundaryStrategy;
  1348. if (this.config_.crossBoundaryStrategy !== CrossBoundaryStrategy.KEEP &&
  1349. this.discardReferenceByBoundary_(mediaState, reference)) {
  1350. // Return null as we do not want to fetch and append segments outside
  1351. // of the current boundary.
  1352. return null;
  1353. }
  1354. if (mediaState.segmentPrefetch && mediaState.segmentIterator &&
  1355. !this.audioPrefetchMap_.has(mediaState.stream)) {
  1356. mediaState.segmentPrefetch.evict(reference.startTime);
  1357. mediaState.segmentPrefetch.prefetchSegmentsByTime(reference.startTime);
  1358. }
  1359. const p = this.fetchAndAppend_(mediaState, presentationTime, reference,
  1360. adaptation);
  1361. p.catch(() => {}); // TODO(#1993): Handle asynchronous errors.
  1362. if (mediaState.dependencyMediaState) {
  1363. this.fetchAndAppendDependency_(
  1364. mediaState.dependencyMediaState, presentationTime);
  1365. }
  1366. return null;
  1367. }
  1368. /**
  1369. * Gets the next timestamp needed. Returns the playhead's position if the
  1370. * buffer is empty; otherwise, returns the time at which the last segment
  1371. * appended ends.
  1372. *
  1373. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1374. * @param {number} presentationTime
  1375. * @return {number} The next timestamp needed.
  1376. * @private
  1377. */
  1378. getTimeNeeded_(mediaState, presentationTime) {
  1379. // Get the next timestamp we need. We must use |lastSegmentReference|
  1380. // to determine this and not the actual buffer for two reasons:
  1381. // 1. Actual segments end slightly before their advertised end times, so
  1382. // the next timestamp we need is actually larger than |bufferEnd|.
  1383. // 2. There may be drift (the timestamps in the segments are ahead/behind
  1384. // of the timestamps in the manifest), but we need drift-free times
  1385. // when comparing times against the presentation timeline.
  1386. if (!mediaState.lastSegmentReference) {
  1387. return presentationTime;
  1388. }
  1389. return mediaState.lastSegmentReference.endTime;
  1390. }
  1391. /**
  1392. * Gets the SegmentReference of the next segment needed.
  1393. *
  1394. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1395. * @param {number} presentationTime
  1396. * @param {?number} bufferEnd
  1397. * @return {shaka.media.SegmentReference} The SegmentReference of the
  1398. * next segment needed. Returns null if a segment could not be found, does
  1399. * not exist, or is not available.
  1400. * @private
  1401. */
  1402. getSegmentReferenceNeeded_(mediaState, presentationTime, bufferEnd) {
  1403. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1404. goog.asserts.assert(
  1405. mediaState.stream.segmentIndex,
  1406. 'segment index should have been generated already');
  1407. if (mediaState.segmentIterator) {
  1408. // Something is buffered from the same Stream. Use the current position
  1409. // in the segment index. This is updated via next() after each segment is
  1410. // appended.
  1411. let ref = mediaState.segmentIterator.current();
  1412. if (ref && mediaState.lastSegmentReference) {
  1413. // In HLS sometimes the segment iterator adds or removes segments very
  1414. // quickly, so we have to be sure that we do not add the last segment
  1415. // again, tolerating a difference of 1ms.
  1416. const isDiffNegligible = (a, b) => Math.abs(a - b) < 0.001;
  1417. const lastStartTime = mediaState.lastSegmentReference.startTime;
  1418. if (isDiffNegligible(lastStartTime, ref.startTime)) {
  1419. ref = mediaState.segmentIterator.next().value;
  1420. }
  1421. }
  1422. return ref;
  1423. } else if (mediaState.lastSegmentReference || bufferEnd) {
  1424. // Something is buffered from another Stream.
  1425. const time = mediaState.lastSegmentReference ?
  1426. mediaState.lastSegmentReference.endTime :
  1427. bufferEnd;
  1428. goog.asserts.assert(time != null, 'Should have a time to search');
  1429. shaka.log.v1(
  1430. logPrefix, 'looking up segment from new stream endTime:', time);
  1431. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  1432. if (mediaState.stream.segmentIndex) {
  1433. mediaState.segmentIterator =
  1434. mediaState.stream.segmentIndex.getIteratorForTime(
  1435. time, /* allowNonIndependent= */ false, reverse);
  1436. }
  1437. const ref = mediaState.segmentIterator &&
  1438. mediaState.segmentIterator.next().value;
  1439. if (ref == null) {
  1440. shaka.log.warning(logPrefix, 'cannot find segment', 'endTime:', time);
  1441. }
  1442. return ref;
  1443. } else {
  1444. // Nothing is buffered. Start at the playhead time.
  1445. // If there's positive drift then we need to adjust the lookup time, and
  1446. // may wind up requesting the previous segment to be safe.
  1447. // inaccurateManifestTolerance should be 0 for low latency streaming.
  1448. const inaccurateTolerance = this.manifest_.sequenceMode ?
  1449. 0 : this.config_.inaccurateManifestTolerance;
  1450. const lookupTime = Math.max(presentationTime - inaccurateTolerance, 0);
  1451. shaka.log.v1(logPrefix, 'looking up segment',
  1452. 'lookupTime:', lookupTime,
  1453. 'presentationTime:', presentationTime);
  1454. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  1455. let ref = null;
  1456. if (inaccurateTolerance) {
  1457. if (mediaState.stream.segmentIndex) {
  1458. mediaState.segmentIterator =
  1459. mediaState.stream.segmentIndex.getIteratorForTime(
  1460. lookupTime, /* allowNonIndependent= */ false, reverse);
  1461. }
  1462. ref = mediaState.segmentIterator &&
  1463. mediaState.segmentIterator.next().value;
  1464. }
  1465. if (!ref) {
  1466. // If we can't find a valid segment with the drifted time, look for a
  1467. // segment with the presentation time.
  1468. if (mediaState.stream.segmentIndex) {
  1469. mediaState.segmentIterator =
  1470. mediaState.stream.segmentIndex.getIteratorForTime(
  1471. presentationTime, /* allowNonIndependent= */ false, reverse);
  1472. }
  1473. ref = mediaState.segmentIterator &&
  1474. mediaState.segmentIterator.next().value;
  1475. }
  1476. if (ref == null) {
  1477. shaka.log.warning(logPrefix, 'cannot find segment',
  1478. 'lookupTime:', lookupTime,
  1479. 'presentationTime:', presentationTime);
  1480. }
  1481. return ref;
  1482. }
  1483. }
  1484. /**
  1485. * Fetches and appends the given segment. Sets up the given MediaState's
  1486. * associated SourceBuffer and evicts segments if either are required
  1487. * beforehand. Schedules another update after completing successfully.
  1488. *
  1489. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  1490. * @param {number} presentationTime
  1491. * @param {!shaka.media.SegmentReference} reference
  1492. * @param {boolean} adaptation
  1493. * @private
  1494. */
  1495. async fetchAndAppend_(mediaState, presentationTime, reference, adaptation) {
  1496. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1497. const StreamingEngine = shaka.media.StreamingEngine;
  1498. const logPrefix = StreamingEngine.logPrefix_(mediaState);
  1499. shaka.log.v1(logPrefix,
  1500. 'fetchAndAppend_:',
  1501. 'presentationTime=' + presentationTime,
  1502. 'reference.startTime=' + reference.startTime,
  1503. 'reference.endTime=' + reference.endTime);
  1504. // Subtlety: The playhead may move while asynchronous update operations are
  1505. // in progress, so we should avoid calling playhead.getTime() in any
  1506. // callbacks. Furthermore, switch() or seeked() may be called at any time,
  1507. // so we store the old iterator. This allows the mediaState to change and
  1508. // we'll update the old iterator.
  1509. const stream = mediaState.stream;
  1510. const iter = mediaState.segmentIterator;
  1511. mediaState.performingUpdate = true;
  1512. try {
  1513. if (reference.getStatus() ==
  1514. shaka.media.SegmentReference.Status.MISSING) {
  1515. throw new shaka.util.Error(
  1516. shaka.util.Error.Severity.RECOVERABLE,
  1517. shaka.util.Error.Category.NETWORK,
  1518. shaka.util.Error.Code.SEGMENT_MISSING);
  1519. }
  1520. await this.initSourceBuffer_(mediaState, reference, adaptation);
  1521. this.destroyer_.ensureNotDestroyed();
  1522. if (this.fatalError_) {
  1523. return;
  1524. }
  1525. shaka.log.v2(logPrefix, 'fetching segment');
  1526. const isMP4 = stream.mimeType == 'video/mp4' ||
  1527. stream.mimeType == 'audio/mp4';
  1528. const isReadableStreamSupported = window.ReadableStream;
  1529. const lowLatencyMode = this.config_.lowLatencyMode &&
  1530. this.manifest_.isLowLatency;
  1531. // Enable MP4 low latency streaming with ReadableStream chunked data.
  1532. // And only for DASH and HLS with byterange optimization.
  1533. if (lowLatencyMode && isReadableStreamSupported && isMP4 &&
  1534. (this.manifest_.type != shaka.media.ManifestParser.HLS ||
  1535. reference.hasByterangeOptimization())) {
  1536. let remaining = new Uint8Array(0);
  1537. let processingResult = false;
  1538. let callbackCalled = false;
  1539. let streamDataCallbackError;
  1540. const streamDataCallback = async (data) => {
  1541. if (processingResult) {
  1542. // If the fallback result processing was triggered, don't also
  1543. // append the buffer here. In theory this should never happen,
  1544. // but it does on some older TVs.
  1545. return;
  1546. }
  1547. callbackCalled = true;
  1548. this.destroyer_.ensureNotDestroyed();
  1549. if (this.fatalError_) {
  1550. return;
  1551. }
  1552. try {
  1553. // Append the data with complete boxes.
  1554. // Every time streamDataCallback gets called, append the new data
  1555. // to the remaining data.
  1556. // Find the last fully completed Mdat box, and slice the data into
  1557. // two parts: the first part with completed Mdat boxes, and the
  1558. // second part with an incomplete box.
  1559. // Append the first part, and save the second part as remaining
  1560. // data, and handle it with the next streamDataCallback call.
  1561. remaining = this.concatArray_(remaining, data);
  1562. let sawMDAT = false;
  1563. let offset = 0;
  1564. new shaka.util.Mp4Parser()
  1565. .box('mdat', (box) => {
  1566. offset = box.size + box.start;
  1567. sawMDAT = true;
  1568. })
  1569. .parse(remaining, /* partialOkay= */ false,
  1570. /* isChunkedData= */ true);
  1571. if (sawMDAT) {
  1572. const dataToAppend = remaining.subarray(0, offset);
  1573. remaining = remaining.subarray(offset);
  1574. await this.append_(
  1575. mediaState, presentationTime, stream, reference, dataToAppend,
  1576. /* isChunkedData= */ true, adaptation);
  1577. if (mediaState.segmentPrefetch && mediaState.segmentIterator) {
  1578. mediaState.segmentPrefetch.prefetchSegmentsByTime(
  1579. reference.startTime, /* skipFirst= */ true);
  1580. }
  1581. }
  1582. } catch (error) {
  1583. streamDataCallbackError = error;
  1584. }
  1585. };
  1586. const result =
  1587. await this.fetch_(mediaState, reference, streamDataCallback);
  1588. if (streamDataCallbackError) {
  1589. throw streamDataCallbackError;
  1590. }
  1591. if (!callbackCalled) {
  1592. // In some environments, we might be forced to use network plugins
  1593. // that don't support streamDataCallback. In those cases, as a
  1594. // fallback, append the buffer here.
  1595. processingResult = true;
  1596. this.destroyer_.ensureNotDestroyed();
  1597. if (this.fatalError_) {
  1598. return;
  1599. }
  1600. // If the text stream gets switched between fetch_() and append_(),
  1601. // the new text parser is initialized, but the new init segment is
  1602. // not fetched yet. That would cause an error in
  1603. // TextParser.parseMedia().
  1604. // See http://b/168253400
  1605. if (mediaState.waitingToClearBuffer) {
  1606. shaka.log.info(logPrefix, 'waitingToClearBuffer, skip append');
  1607. mediaState.performingUpdate = false;
  1608. this.scheduleUpdate_(mediaState, 0);
  1609. return;
  1610. }
  1611. await this.append_(mediaState, presentationTime, stream, reference,
  1612. result, /* chunkedData= */ false, adaptation);
  1613. }
  1614. if (mediaState.segmentPrefetch && mediaState.segmentIterator) {
  1615. mediaState.segmentPrefetch.prefetchSegmentsByTime(
  1616. reference.startTime, /* skipFirst= */ true);
  1617. }
  1618. } else {
  1619. if (lowLatencyMode && !isReadableStreamSupported) {
  1620. shaka.log.warning('Low latency streaming mode is enabled, but ' +
  1621. 'ReadableStream is not supported by the browser.');
  1622. }
  1623. const fetchSegment = this.fetch_(mediaState, reference);
  1624. const result = await fetchSegment;
  1625. this.destroyer_.ensureNotDestroyed();
  1626. if (this.fatalError_) {
  1627. return;
  1628. }
  1629. this.destroyer_.ensureNotDestroyed();
  1630. // If the text stream gets switched between fetch_() and append_(), the
  1631. // new text parser is initialized, but the new init segment is not
  1632. // fetched yet. That would cause an error in TextParser.parseMedia().
  1633. // See http://b/168253400
  1634. if (mediaState.waitingToClearBuffer) {
  1635. shaka.log.info(logPrefix, 'waitingToClearBuffer, skip append');
  1636. mediaState.performingUpdate = false;
  1637. this.scheduleUpdate_(mediaState, 0);
  1638. return;
  1639. }
  1640. await this.append_(mediaState, presentationTime, stream, reference,
  1641. result, /* chunkedData= */ false, adaptation);
  1642. }
  1643. this.destroyer_.ensureNotDestroyed();
  1644. if (this.fatalError_) {
  1645. return;
  1646. }
  1647. // move to next segment after appending the current segment.
  1648. mediaState.lastSegmentReference = reference;
  1649. const newRef = iter.next().value;
  1650. shaka.log.v2(logPrefix, 'advancing to next segment', newRef);
  1651. mediaState.performingUpdate = false;
  1652. mediaState.recovering = false;
  1653. const info = this.playerInterface_.mediaSourceEngine.getBufferedInfo();
  1654. const buffered = info[mediaState.type];
  1655. // Convert the buffered object to a string capture its properties on
  1656. // WebOS.
  1657. shaka.log.v1(logPrefix, 'finished fetch and append',
  1658. JSON.stringify(buffered));
  1659. if (!mediaState.waitingToClearBuffer) {
  1660. let otherState = null;
  1661. if (mediaState.type === ContentType.VIDEO) {
  1662. otherState = this.mediaStates_.get(ContentType.AUDIO);
  1663. } else if (mediaState.type === ContentType.AUDIO) {
  1664. otherState = this.mediaStates_.get(ContentType.VIDEO);
  1665. }
  1666. if (otherState && otherState.type == ContentType.AUDIO) {
  1667. this.playerInterface_.onSegmentAppended(reference, mediaState.stream,
  1668. otherState.stream.isAudioMuxedInVideo);
  1669. } else {
  1670. this.playerInterface_.onSegmentAppended(reference, mediaState.stream,
  1671. mediaState.stream.codecs.includes(','));
  1672. }
  1673. }
  1674. // Update right away.
  1675. this.scheduleUpdate_(mediaState, 0);
  1676. } catch (error) {
  1677. this.destroyer_.ensureNotDestroyed(error);
  1678. if (this.fatalError_) {
  1679. return;
  1680. }
  1681. goog.asserts.assert(error instanceof shaka.util.Error,
  1682. 'Should only receive a Shaka error');
  1683. mediaState.performingUpdate = false;
  1684. if (error.code == shaka.util.Error.Code.OPERATION_ABORTED) {
  1685. // If the network slows down, abort the current fetch request and start
  1686. // a new one, and ignore the error message.
  1687. mediaState.performingUpdate = false;
  1688. this.cancelUpdate_(mediaState);
  1689. this.scheduleUpdate_(mediaState, 0);
  1690. } else if (mediaState.type == ContentType.TEXT &&
  1691. this.config_.ignoreTextStreamFailures) {
  1692. if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS) {
  1693. shaka.log.warning(logPrefix,
  1694. 'Text stream failed to download. Proceeding without it.');
  1695. } else {
  1696. shaka.log.warning(logPrefix,
  1697. 'Text stream failed to parse. Proceeding without it.');
  1698. }
  1699. this.mediaStates_.delete(ContentType.TEXT);
  1700. } else if (error.code == shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR) {
  1701. await this.handleQuotaExceeded_(mediaState, error);
  1702. } else {
  1703. shaka.log.error(logPrefix, 'failed fetch and append: code=' +
  1704. error.code);
  1705. mediaState.hasError = true;
  1706. if (error.category == shaka.util.Error.Category.NETWORK &&
  1707. mediaState.segmentPrefetch) {
  1708. mediaState.segmentPrefetch.removeReference(reference);
  1709. }
  1710. error.severity = shaka.util.Error.Severity.CRITICAL;
  1711. await this.handleStreamingError_(mediaState, error);
  1712. }
  1713. }
  1714. }
  1715. /**
  1716. * Fetches and appends a dependency media state
  1717. *
  1718. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  1719. * @param {number} presentationTime
  1720. * @private
  1721. */
  1722. async fetchAndAppendDependency_(mediaState, presentationTime) {
  1723. const dependencyStream = mediaState.stream;
  1724. const iterator =
  1725. dependencyStream.segmentIndex.getIteratorForTime(presentationTime);
  1726. const reference = iterator && iterator.next().value;
  1727. if (reference) {
  1728. const initSegmentReference = reference.initSegmentReference;
  1729. if (initSegmentReference && !shaka.media.InitSegmentReference.equal(
  1730. initSegmentReference, mediaState.lastInitSegmentReference)) {
  1731. mediaState.lastInitSegmentReference = initSegmentReference;
  1732. try {
  1733. const init = await this.fetch_(mediaState, initSegmentReference);
  1734. this.playerInterface_.mediaSourceEngine.appendDependency(
  1735. init, 0, dependencyStream);
  1736. } catch (e) {
  1737. mediaState.lastInitSegmentReference = null;
  1738. throw e;
  1739. }
  1740. }
  1741. if (!mediaState.lastSegmentReference ||
  1742. mediaState.lastSegmentReference != reference) {
  1743. mediaState.lastSegmentReference = reference;
  1744. try {
  1745. const result = await this.fetch_(mediaState, reference);
  1746. this.playerInterface_.mediaSourceEngine.appendDependency(
  1747. result, 0, dependencyStream);
  1748. } catch (e) {
  1749. mediaState.lastSegmentReference = null;
  1750. throw e;
  1751. }
  1752. }
  1753. }
  1754. }
  1755. /**
  1756. * Clear per-stream error states and retry any failed streams.
  1757. * @param {number} delaySeconds
  1758. * @return {boolean} False if unable to retry.
  1759. */
  1760. retry(delaySeconds) {
  1761. if (this.destroyer_.destroyed()) {
  1762. shaka.log.error('Unable to retry after StreamingEngine is destroyed!');
  1763. return false;
  1764. }
  1765. if (this.fatalError_) {
  1766. shaka.log.error('Unable to retry after StreamingEngine encountered a ' +
  1767. 'fatal error!');
  1768. return false;
  1769. }
  1770. for (const mediaState of this.mediaStates_.values()) {
  1771. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1772. // Only schedule an update if it has an error, but it's not mid-update
  1773. // and there is not already an update scheduled.
  1774. if (mediaState.hasError && !mediaState.performingUpdate &&
  1775. !mediaState.updateTimer) {
  1776. shaka.log.info(logPrefix, 'Retrying after failure...');
  1777. mediaState.hasError = false;
  1778. this.scheduleUpdate_(mediaState, delaySeconds);
  1779. }
  1780. }
  1781. return true;
  1782. }
  1783. /**
  1784. * Append the data to the remaining data.
  1785. * @param {!Uint8Array} remaining
  1786. * @param {!Uint8Array} data
  1787. * @return {!Uint8Array}
  1788. * @private
  1789. */
  1790. concatArray_(remaining, data) {
  1791. const result = new Uint8Array(remaining.length + data.length);
  1792. result.set(remaining);
  1793. result.set(data, remaining.length);
  1794. return result;
  1795. }
  1796. /**
  1797. * Handles a QUOTA_EXCEEDED_ERROR.
  1798. *
  1799. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1800. * @param {!shaka.util.Error} error
  1801. * @return {!Promise}
  1802. * @private
  1803. */
  1804. async handleQuotaExceeded_(mediaState, error) {
  1805. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1806. // The segment cannot fit into the SourceBuffer. Ideally, MediaSource would
  1807. // have evicted old data to accommodate the segment; however, it may have
  1808. // failed to do this if the segment is very large, or if it could not find
  1809. // a suitable time range to remove.
  1810. //
  1811. // We can overcome the latter by trying to append the segment again;
  1812. // however, to avoid continuous QuotaExceededErrors we must reduce the size
  1813. // of the buffer going forward.
  1814. //
  1815. // If we've recently reduced the buffering goals, wait until the stream
  1816. // which caused the first QuotaExceededError recovers. Doing this ensures
  1817. // we don't reduce the buffering goals too quickly.
  1818. const mediaStates = Array.from(this.mediaStates_.values());
  1819. const waitingForAnotherStreamToRecover = mediaStates.some((ms) => {
  1820. return ms != mediaState && ms.recovering;
  1821. });
  1822. if (!waitingForAnotherStreamToRecover) {
  1823. const maxDisabledTime = this.getDisabledTime_(error);
  1824. if (maxDisabledTime) {
  1825. shaka.log.debug(logPrefix, 'Disabling stream due to quota', error);
  1826. }
  1827. const handled = this.playerInterface_.disableStream(
  1828. mediaState.stream, maxDisabledTime);
  1829. if (handled) {
  1830. return;
  1831. }
  1832. if (this.config_.avoidEvictionOnQuotaExceededError) {
  1833. // QuotaExceededError gets thrown if eviction didn't help to make room
  1834. // for a segment. We want to wait for a while (4 seconds is just an
  1835. // arbitrary number) before updating to give the playhead a chance to
  1836. // advance, so we don't immediately throw again.
  1837. this.scheduleUpdate_(mediaState, 4);
  1838. return;
  1839. }
  1840. // Reduction schedule: 80%, 60%, 40%, 20%, 16%, 12%, 8%, 4%, fail.
  1841. // Note: percentages are used for comparisons to avoid rounding errors.
  1842. const percentBefore = Math.round(100 * this.bufferingScale_);
  1843. if (percentBefore > 20) {
  1844. this.bufferingScale_ -= 0.2;
  1845. } else if (percentBefore > 4) {
  1846. this.bufferingScale_ -= 0.04;
  1847. } else {
  1848. shaka.log.error(
  1849. logPrefix, 'MediaSource threw QuotaExceededError too many times');
  1850. mediaState.hasError = true;
  1851. this.fatalError_ = true;
  1852. this.playerInterface_.onError(error);
  1853. return;
  1854. }
  1855. const percentAfter = Math.round(100 * this.bufferingScale_);
  1856. shaka.log.warning(
  1857. logPrefix,
  1858. 'MediaSource threw QuotaExceededError:',
  1859. 'reducing buffering goals by ' + (100 - percentAfter) + '%');
  1860. mediaState.recovering = true;
  1861. const presentationTime = this.playerInterface_.getPresentationTime();
  1862. await this.evict_(mediaState, presentationTime);
  1863. } else {
  1864. shaka.log.debug(
  1865. logPrefix,
  1866. 'MediaSource threw QuotaExceededError:',
  1867. 'waiting for another stream to recover...');
  1868. }
  1869. // QuotaExceededError gets thrown if eviction didn't help to make room
  1870. // for a segment. We want to wait for a while (4 seconds is just an
  1871. // arbitrary number) before updating to give the playhead a chance to
  1872. // advance, so we don't immediately throw again.
  1873. this.scheduleUpdate_(mediaState, 4);
  1874. }
  1875. /**
  1876. * Sets the given MediaState's associated SourceBuffer's timestamp offset,
  1877. * append window, and init segment if they have changed. If an error occurs
  1878. * then neither the timestamp offset or init segment are unset, since another
  1879. * call to switch() will end up superseding them.
  1880. *
  1881. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1882. * @param {!shaka.media.SegmentReference} reference
  1883. * @param {boolean} adaptation
  1884. * @return {!Promise}
  1885. * @private
  1886. */
  1887. async initSourceBuffer_(mediaState, reference, adaptation) {
  1888. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1889. const MimeUtils = shaka.util.MimeUtils;
  1890. const StreamingEngine = shaka.media.StreamingEngine;
  1891. const logPrefix = StreamingEngine.logPrefix_(mediaState);
  1892. const nullLastReferences = mediaState.lastSegmentReference == null;
  1893. /** @type {!Array<!Promise>} */
  1894. const operations = [];
  1895. // Rounding issues can cause us to remove the first frame of a Period, so
  1896. // reduce the window start time slightly.
  1897. const appendWindowStart = Math.max(0,
  1898. Math.max(reference.appendWindowStart, this.playRangeStart_) -
  1899. StreamingEngine.APPEND_WINDOW_START_FUDGE_);
  1900. const appendWindowEnd =
  1901. Math.min(reference.appendWindowEnd, this.playRangeEnd_) +
  1902. StreamingEngine.APPEND_WINDOW_END_FUDGE_;
  1903. goog.asserts.assert(
  1904. reference.startTime <= appendWindowEnd,
  1905. logPrefix + ' segment should start before append window end');
  1906. const fullCodecs = (reference.codecs || mediaState.stream.codecs);
  1907. const codecs = MimeUtils.getCodecBase(fullCodecs);
  1908. const mimeType = MimeUtils.getBasicType(
  1909. reference.mimeType || mediaState.stream.mimeType);
  1910. const timestampOffset = reference.timestampOffset;
  1911. if (timestampOffset != mediaState.lastTimestampOffset ||
  1912. appendWindowStart != mediaState.lastAppendWindowStart ||
  1913. appendWindowEnd != mediaState.lastAppendWindowEnd ||
  1914. codecs != mediaState.lastCodecs ||
  1915. mimeType != mediaState.lastMimeType) {
  1916. shaka.log.v1(logPrefix, 'setting timestamp offset to ' + timestampOffset);
  1917. shaka.log.v1(logPrefix,
  1918. 'setting append window start to ' + appendWindowStart);
  1919. shaka.log.v1(logPrefix,
  1920. 'setting append window end to ' + appendWindowEnd);
  1921. const isResetMediaSourceNecessary =
  1922. mediaState.lastCodecs && mediaState.lastMimeType &&
  1923. this.playerInterface_.mediaSourceEngine.isResetMediaSourceNecessary(
  1924. mediaState.type, mimeType, fullCodecs);
  1925. if (isResetMediaSourceNecessary) {
  1926. let otherState = null;
  1927. if (mediaState.type === ContentType.VIDEO) {
  1928. otherState = this.mediaStates_.get(ContentType.AUDIO);
  1929. } else if (mediaState.type === ContentType.AUDIO) {
  1930. otherState = this.mediaStates_.get(ContentType.VIDEO);
  1931. }
  1932. if (otherState) {
  1933. // First, abort all operations in progress on the other stream.
  1934. await this.abortOperations_(otherState).catch(() => {});
  1935. // Then clear our cache of the last init segment, since MSE will be
  1936. // reloaded and no init segment will be there post-reload.
  1937. otherState.lastInitSegmentReference = null;
  1938. // Clear cache of append window start and end, since they will need
  1939. // to be reapplied post-reload by streaming engine.
  1940. otherState.lastAppendWindowStart = null;
  1941. otherState.lastAppendWindowEnd = null;
  1942. // Now force the existing buffer to be cleared. It is not necessary
  1943. // to perform the MSE clear operation, but this has the side-effect
  1944. // that our state for that stream will then match MSE's post-reload
  1945. // state.
  1946. this.forceClearBuffer_(otherState);
  1947. }
  1948. }
  1949. // Dispatching init asynchronously causes the sourceBuffers in
  1950. // the MediaSourceEngine to become detached do to race conditions
  1951. // with mediaSource and sourceBuffers being created simultaneously.
  1952. await this.setProperties_(mediaState, timestampOffset, appendWindowStart,
  1953. appendWindowEnd, reference, codecs, mimeType);
  1954. }
  1955. if (!shaka.media.InitSegmentReference.equal(
  1956. reference.initSegmentReference, mediaState.lastInitSegmentReference)) {
  1957. mediaState.lastInitSegmentReference = reference.initSegmentReference;
  1958. if (reference.isIndependent() && reference.initSegmentReference) {
  1959. shaka.log.v1(logPrefix, 'fetching init segment');
  1960. const fetchInit =
  1961. this.fetch_(mediaState, reference.initSegmentReference);
  1962. const append = async () => {
  1963. try {
  1964. const initSegment = await fetchInit;
  1965. this.destroyer_.ensureNotDestroyed();
  1966. let lastTimescale = null;
  1967. const timescaleMap = new Map();
  1968. /** @type {!shaka.extern.SpatialVideoInfo} */
  1969. const spatialVideoInfo = {
  1970. projection: null,
  1971. hfov: null,
  1972. };
  1973. const parser = new shaka.util.Mp4Parser();
  1974. const Mp4Parser = shaka.util.Mp4Parser;
  1975. const Mp4BoxParsers = shaka.util.Mp4BoxParsers;
  1976. parser.box('moov', Mp4Parser.children)
  1977. .box('trak', Mp4Parser.children)
  1978. .box('mdia', Mp4Parser.children)
  1979. .fullBox('mdhd', (box) => {
  1980. goog.asserts.assert(
  1981. box.version != null,
  1982. 'MDHD is a full box and should have a valid version.');
  1983. const parsedMDHDBox = Mp4BoxParsers.parseMDHD(
  1984. box.reader, box.version);
  1985. lastTimescale = parsedMDHDBox.timescale;
  1986. })
  1987. .box('hdlr', (box) => {
  1988. const parsedHDLR = Mp4BoxParsers.parseHDLR(box.reader);
  1989. switch (parsedHDLR.handlerType) {
  1990. case 'soun':
  1991. timescaleMap.set(ContentType.AUDIO, lastTimescale);
  1992. break;
  1993. case 'vide':
  1994. timescaleMap.set(ContentType.VIDEO, lastTimescale);
  1995. break;
  1996. }
  1997. lastTimescale = null;
  1998. })
  1999. .box('minf', Mp4Parser.children)
  2000. .box('stbl', Mp4Parser.children)
  2001. .fullBox('stsd', Mp4Parser.sampleDescription)
  2002. .box('encv', Mp4Parser.visualSampleEntry)
  2003. .box('avc1', Mp4Parser.visualSampleEntry)
  2004. .box('avc3', Mp4Parser.visualSampleEntry)
  2005. .box('hev1', Mp4Parser.visualSampleEntry)
  2006. .box('hvc1', Mp4Parser.visualSampleEntry)
  2007. .box('dvav', Mp4Parser.visualSampleEntry)
  2008. .box('dva1', Mp4Parser.visualSampleEntry)
  2009. .box('dvh1', Mp4Parser.visualSampleEntry)
  2010. .box('dvhe', Mp4Parser.visualSampleEntry)
  2011. .box('dvc1', Mp4Parser.visualSampleEntry)
  2012. .box('dvi1', Mp4Parser.visualSampleEntry)
  2013. .box('vexu', Mp4Parser.children)
  2014. .box('proj', Mp4Parser.children)
  2015. .fullBox('prji', (box) => {
  2016. const parsedPRJIBox = Mp4BoxParsers.parsePRJI(box.reader);
  2017. spatialVideoInfo.projection = parsedPRJIBox.projection;
  2018. })
  2019. .box('hfov', (box) => {
  2020. const parsedHFOVBox = Mp4BoxParsers.parseHFOV(box.reader);
  2021. spatialVideoInfo.hfov = parsedHFOVBox.hfov;
  2022. })
  2023. .parse(initSegment);
  2024. if (mediaState.type === ContentType.VIDEO) {
  2025. this.updateSpatialVideoInfo_(spatialVideoInfo);
  2026. }
  2027. if (timescaleMap.has(mediaState.type)) {
  2028. reference.initSegmentReference.timescale =
  2029. timescaleMap.get(mediaState.type);
  2030. } else if (lastTimescale != null) {
  2031. // Fallback for segments without HDLR box
  2032. reference.initSegmentReference.timescale = lastTimescale;
  2033. }
  2034. shaka.log.v1(logPrefix, 'appending init segment');
  2035. const hasClosedCaptions = mediaState.stream.closedCaptions &&
  2036. mediaState.stream.closedCaptions.size > 0;
  2037. await this.playerInterface_.beforeAppendSegment(
  2038. mediaState.type, initSegment);
  2039. await this.playerInterface_.mediaSourceEngine.appendBuffer(
  2040. mediaState.type, initSegment, /* reference= */ null,
  2041. mediaState.stream, hasClosedCaptions, mediaState.seeked,
  2042. adaptation);
  2043. } catch (error) {
  2044. mediaState.lastInitSegmentReference = null;
  2045. throw error;
  2046. }
  2047. };
  2048. let initSegmentTime = reference.startTime;
  2049. if (nullLastReferences) {
  2050. const bufferEnd =
  2051. this.playerInterface_.mediaSourceEngine.bufferEnd(mediaState.type);
  2052. if (bufferEnd != null) {
  2053. // Adjust init segment append time if we have something in
  2054. // a buffer, i.e. due to running switchVariant() with non zero
  2055. // safe margin value.
  2056. initSegmentTime = bufferEnd;
  2057. }
  2058. }
  2059. this.playerInterface_.onInitSegmentAppended(
  2060. initSegmentTime, reference.initSegmentReference);
  2061. operations.push(append());
  2062. }
  2063. }
  2064. const lastDiscontinuitySequence =
  2065. mediaState.lastSegmentReference ?
  2066. mediaState.lastSegmentReference.discontinuitySequence : null;
  2067. // Across discontinuity bounds, we should resync timestamps. The next
  2068. // segment appended should land at its theoretical timestamp from the
  2069. // segment index.
  2070. if (reference.discontinuitySequence != lastDiscontinuitySequence) {
  2071. operations.push(this.playerInterface_.mediaSourceEngine.resync(
  2072. mediaState.type, reference.startTime));
  2073. }
  2074. await Promise.all(operations);
  2075. }
  2076. /**
  2077. *
  2078. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2079. * @param {number} timestampOffset
  2080. * @param {number} appendWindowStart
  2081. * @param {number} appendWindowEnd
  2082. * @param {!shaka.media.SegmentReference} reference
  2083. * @param {?string=} codecs
  2084. * @param {?string=} mimeType
  2085. * @private
  2086. */
  2087. async setProperties_(mediaState, timestampOffset, appendWindowStart,
  2088. appendWindowEnd, reference, codecs, mimeType) {
  2089. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2090. /**
  2091. * @type {!Map<shaka.util.ManifestParserUtils.ContentType,
  2092. * shaka.extern.Stream>}
  2093. */
  2094. const streamsByType = new Map();
  2095. if (this.currentVariant_.audio) {
  2096. streamsByType.set(ContentType.AUDIO, this.currentVariant_.audio);
  2097. }
  2098. if (this.currentVariant_.video) {
  2099. streamsByType.set(ContentType.VIDEO, this.currentVariant_.video);
  2100. }
  2101. try {
  2102. mediaState.lastAppendWindowStart = appendWindowStart;
  2103. mediaState.lastAppendWindowEnd = appendWindowEnd;
  2104. if (codecs) {
  2105. mediaState.lastCodecs = codecs;
  2106. }
  2107. if (mimeType) {
  2108. mediaState.lastMimeType = mimeType;
  2109. }
  2110. mediaState.lastTimestampOffset = timestampOffset;
  2111. const ignoreTimestampOffset = this.manifest_.sequenceMode ||
  2112. this.manifest_.type == shaka.media.ManifestParser.HLS;
  2113. await this.playerInterface_.mediaSourceEngine.setStreamProperties(
  2114. mediaState.type, timestampOffset, appendWindowStart,
  2115. appendWindowEnd, ignoreTimestampOffset,
  2116. reference.mimeType || mediaState.stream.mimeType,
  2117. reference.codecs || mediaState.stream.codecs, streamsByType);
  2118. } catch (error) {
  2119. mediaState.lastAppendWindowStart = null;
  2120. mediaState.lastAppendWindowEnd = null;
  2121. mediaState.lastCodecs = null;
  2122. mediaState.lastMimeType = null;
  2123. mediaState.lastTimestampOffset = null;
  2124. throw error;
  2125. }
  2126. }
  2127. /**
  2128. * Appends the given segment and evicts content if required to append.
  2129. *
  2130. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2131. * @param {number} presentationTime
  2132. * @param {shaka.extern.Stream} stream
  2133. * @param {!shaka.media.SegmentReference} reference
  2134. * @param {BufferSource} segment
  2135. * @param {boolean=} isChunkedData
  2136. * @param {boolean=} adaptation
  2137. * @return {!Promise}
  2138. * @private
  2139. */
  2140. async append_(mediaState, presentationTime, stream, reference, segment,
  2141. isChunkedData = false, adaptation = false) {
  2142. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2143. const hasClosedCaptions = stream.closedCaptions &&
  2144. stream.closedCaptions.size > 0;
  2145. if (this.config_.shouldFixTimestampOffset) {
  2146. let parser;
  2147. const isMP4 = stream.mimeType == 'video/mp4' ||
  2148. stream.mimeType == 'audio/mp4';
  2149. let timescale = null;
  2150. if (reference.initSegmentReference) {
  2151. timescale = reference.initSegmentReference.timescale;
  2152. }
  2153. const shouldFixTimestampOffset = isMP4 && timescale &&
  2154. stream.type === shaka.util.ManifestParserUtils.ContentType.VIDEO &&
  2155. this.manifest_.type == shaka.media.ManifestParser.DASH;
  2156. if (shouldFixTimestampOffset) {
  2157. parser = new shaka.util.Mp4Parser();
  2158. }
  2159. if (shouldFixTimestampOffset) {
  2160. parser
  2161. .box('moof', shaka.util.Mp4Parser.children)
  2162. .box('traf', shaka.util.Mp4Parser.children)
  2163. .fullBox('tfdt', async (box) => {
  2164. goog.asserts.assert(
  2165. box.version != null,
  2166. 'TFDT is a full box and should have a valid version.');
  2167. const parsedTFDT = shaka.util.Mp4BoxParsers.parseTFDTInaccurate(
  2168. box.reader, box.version);
  2169. const baseMediaDecodeTime = parsedTFDT.baseMediaDecodeTime;
  2170. // In case the time is 0, it is not updated
  2171. if (!baseMediaDecodeTime) {
  2172. return;
  2173. }
  2174. goog.asserts.assert(typeof(timescale) == 'number',
  2175. 'Should be an number!');
  2176. const scaledMediaDecodeTime = -baseMediaDecodeTime / timescale;
  2177. const comparison1 = Number(mediaState.lastTimestampOffset) || 0;
  2178. if (comparison1 < scaledMediaDecodeTime) {
  2179. const lastAppendWindowStart = mediaState.lastAppendWindowStart;
  2180. const lastAppendWindowEnd = mediaState.lastAppendWindowEnd;
  2181. goog.asserts.assert(typeof(lastAppendWindowStart) == 'number',
  2182. 'Should be an number!');
  2183. goog.asserts.assert(typeof(lastAppendWindowEnd) == 'number',
  2184. 'Should be an number!');
  2185. await this.setProperties_(mediaState, scaledMediaDecodeTime,
  2186. lastAppendWindowStart, lastAppendWindowEnd, reference);
  2187. }
  2188. });
  2189. }
  2190. if (shouldFixTimestampOffset) {
  2191. parser.parse(segment, /* partialOkay= */ false, isChunkedData);
  2192. }
  2193. }
  2194. await this.evict_(mediaState, presentationTime);
  2195. this.destroyer_.ensureNotDestroyed();
  2196. // 'seeked' or 'adaptation' triggered logic applies only to this
  2197. // appendBuffer() call.
  2198. const seeked = mediaState.seeked;
  2199. mediaState.seeked = false;
  2200. await this.playerInterface_.beforeAppendSegment(mediaState.type, segment);
  2201. await this.playerInterface_.mediaSourceEngine.appendBuffer(
  2202. mediaState.type,
  2203. segment,
  2204. reference,
  2205. stream,
  2206. hasClosedCaptions,
  2207. seeked,
  2208. adaptation,
  2209. isChunkedData);
  2210. this.destroyer_.ensureNotDestroyed();
  2211. shaka.log.v2(logPrefix, 'appended media segment');
  2212. }
  2213. /**
  2214. * Evicts media to meet the max buffer behind limit.
  2215. *
  2216. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2217. * @param {number} presentationTime
  2218. * @private
  2219. */
  2220. async evict_(mediaState, presentationTime) {
  2221. const segmentIndex = mediaState.stream.segmentIndex;
  2222. if (segmentIndex instanceof shaka.media.MetaSegmentIndex) {
  2223. segmentIndex.evict(
  2224. this.manifest_.presentationTimeline.getSegmentAvailabilityStart());
  2225. }
  2226. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2227. shaka.log.v2(logPrefix, 'checking buffer length');
  2228. // Use the max segment duration, if it is longer than the bufferBehind, to
  2229. // avoid accidentally clearing too much data when dealing with a manifest
  2230. // with a long keyframe interval.
  2231. const bufferBehind = Math.max(
  2232. this.config_.bufferBehind * this.bufferingScale_,
  2233. this.manifest_.presentationTimeline.getMaxSegmentDuration());
  2234. const startTime =
  2235. this.playerInterface_.mediaSourceEngine.bufferStart(mediaState.type);
  2236. if (startTime == null) {
  2237. if (this.lastTextMediaStateBeforeUnload_ == mediaState) {
  2238. this.lastTextMediaStateBeforeUnload_ = null;
  2239. }
  2240. shaka.log.v2(logPrefix,
  2241. 'buffer behind okay because nothing buffered:',
  2242. 'presentationTime=' + presentationTime,
  2243. 'bufferBehind=' + bufferBehind);
  2244. return;
  2245. }
  2246. const bufferedBehind = presentationTime - startTime;
  2247. const evictionGoal = this.config_.evictionGoal;
  2248. const seekRangeStart =
  2249. this.manifest_.presentationTimeline.getSeekRangeStart();
  2250. const seekRangeEnd =
  2251. this.manifest_.presentationTimeline.getSeekRangeEnd();
  2252. let overflow = bufferedBehind - bufferBehind;
  2253. if (seekRangeEnd - seekRangeStart > evictionGoal) {
  2254. overflow = Math.max(bufferedBehind - bufferBehind,
  2255. seekRangeStart - evictionGoal - startTime);
  2256. }
  2257. // See: https://github.com/shaka-project/shaka-player/issues/6240
  2258. if (overflow <= evictionGoal) {
  2259. shaka.log.v2(logPrefix,
  2260. 'buffer behind okay:',
  2261. 'presentationTime=' + presentationTime,
  2262. 'bufferedBehind=' + bufferedBehind,
  2263. 'bufferBehind=' + bufferBehind,
  2264. 'evictionGoal=' + evictionGoal,
  2265. 'underflow=' + Math.abs(overflow));
  2266. return;
  2267. }
  2268. shaka.log.v1(logPrefix,
  2269. 'buffer behind too large:',
  2270. 'presentationTime=' + presentationTime,
  2271. 'bufferedBehind=' + bufferedBehind,
  2272. 'bufferBehind=' + bufferBehind,
  2273. 'evictionGoal=' + evictionGoal,
  2274. 'overflow=' + overflow);
  2275. await this.playerInterface_.mediaSourceEngine.remove(mediaState.type,
  2276. startTime, startTime + overflow);
  2277. this.destroyer_.ensureNotDestroyed();
  2278. shaka.log.v1(logPrefix, 'evicted ' + overflow + ' seconds');
  2279. if (this.lastTextMediaStateBeforeUnload_) {
  2280. await this.evict_(this.lastTextMediaStateBeforeUnload_, presentationTime);
  2281. this.destroyer_.ensureNotDestroyed();
  2282. }
  2283. }
  2284. /**
  2285. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2286. * @return {boolean}
  2287. * @private
  2288. */
  2289. static isEmbeddedText_(mediaState) {
  2290. const MimeUtils = shaka.util.MimeUtils;
  2291. const CEA608_MIME = MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE;
  2292. const CEA708_MIME = MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE;
  2293. return mediaState &&
  2294. mediaState.type == shaka.util.ManifestParserUtils.ContentType.TEXT &&
  2295. (mediaState.stream.mimeType == CEA608_MIME ||
  2296. mediaState.stream.mimeType == CEA708_MIME);
  2297. }
  2298. /**
  2299. * Fetches the given segment.
  2300. *
  2301. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2302. * @param {(!shaka.media.InitSegmentReference|
  2303. * !shaka.media.SegmentReference)} reference
  2304. * @param {?function(BufferSource):!Promise=} streamDataCallback
  2305. *
  2306. * @return {!Promise<BufferSource>}
  2307. * @private
  2308. */
  2309. async fetch_(mediaState, reference, streamDataCallback) {
  2310. const segmentData = reference.getSegmentData();
  2311. if (segmentData) {
  2312. return segmentData;
  2313. }
  2314. let op = null;
  2315. if (mediaState.segmentPrefetch) {
  2316. op = mediaState.segmentPrefetch.getPrefetchedSegment(
  2317. reference, streamDataCallback);
  2318. }
  2319. if (!op) {
  2320. op = this.dispatchFetch_(
  2321. reference, mediaState.stream, streamDataCallback);
  2322. }
  2323. let position = 0;
  2324. if (mediaState.segmentIterator) {
  2325. position = mediaState.segmentIterator.currentPosition();
  2326. }
  2327. mediaState.operation = op;
  2328. const response = await op.promise;
  2329. mediaState.operation = null;
  2330. let result = response.data;
  2331. if (reference.aesKey) {
  2332. result = await shaka.media.SegmentUtils.aesDecrypt(
  2333. result, reference.aesKey, position);
  2334. }
  2335. return result;
  2336. }
  2337. /**
  2338. * Fetches the given segment.
  2339. *
  2340. * @param {(!shaka.media.InitSegmentReference|
  2341. * !shaka.media.SegmentReference)} reference
  2342. * @param {!shaka.extern.Stream} stream
  2343. * @param {?function(BufferSource):!Promise=} streamDataCallback
  2344. * @param {boolean=} isPreload
  2345. *
  2346. * @return {!shaka.net.NetworkingEngine.PendingRequest}
  2347. * @private
  2348. */
  2349. dispatchFetch_(reference, stream, streamDataCallback, isPreload = false) {
  2350. goog.asserts.assert(
  2351. this.playerInterface_.netEngine, 'Must have net engine');
  2352. return shaka.media.StreamingEngine.dispatchFetch(
  2353. reference, stream, streamDataCallback || null,
  2354. this.config_.retryParameters, this.playerInterface_.netEngine);
  2355. }
  2356. /**
  2357. * Fetches the given segment.
  2358. *
  2359. * @param {(!shaka.media.InitSegmentReference|
  2360. * !shaka.media.SegmentReference)} reference
  2361. * @param {!shaka.extern.Stream} stream
  2362. * @param {?function(BufferSource):!Promise} streamDataCallback
  2363. * @param {shaka.extern.RetryParameters} retryParameters
  2364. * @param {!shaka.net.NetworkingEngine} netEngine
  2365. * @param {boolean=} isPreload
  2366. *
  2367. * @return {!shaka.net.NetworkingEngine.PendingRequest}
  2368. */
  2369. static dispatchFetch(
  2370. reference, stream, streamDataCallback, retryParameters, netEngine,
  2371. isPreload = false) {
  2372. const requestType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  2373. const segment = reference instanceof shaka.media.SegmentReference ?
  2374. reference : undefined;
  2375. const type = segment ?
  2376. shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT :
  2377. shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT;
  2378. const request = shaka.util.Networking.createSegmentRequest(
  2379. reference.getUris(),
  2380. reference.startByte,
  2381. reference.endByte,
  2382. retryParameters,
  2383. streamDataCallback);
  2384. request.contentType = stream.type;
  2385. shaka.log.v2('fetching: reference=', reference);
  2386. return netEngine.request(
  2387. requestType, request, {type, stream, segment, isPreload});
  2388. }
  2389. /**
  2390. * Clears the buffer and schedules another update.
  2391. * The optional parameter safeMargin allows to retain a certain amount
  2392. * of buffer, which can help avoiding rebuffering events.
  2393. * The value of the safe margin should be provided by the ABR manager.
  2394. *
  2395. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2396. * @param {boolean} flush
  2397. * @param {number} safeMargin
  2398. * @private
  2399. */
  2400. async clearBuffer_(mediaState, flush, safeMargin) {
  2401. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2402. goog.asserts.assert(
  2403. !mediaState.performingUpdate && (mediaState.updateTimer == null),
  2404. logPrefix + ' unexpected call to clearBuffer_()');
  2405. mediaState.waitingToClearBuffer = false;
  2406. mediaState.waitingToFlushBuffer = false;
  2407. mediaState.clearBufferSafeMargin = 0;
  2408. mediaState.clearingBuffer = true;
  2409. mediaState.lastSegmentReference = null;
  2410. mediaState.segmentIterator = null;
  2411. shaka.log.debug(logPrefix, 'clearing buffer');
  2412. if (mediaState.segmentPrefetch &&
  2413. !this.audioPrefetchMap_.has(mediaState.stream)) {
  2414. mediaState.segmentPrefetch.clearAll();
  2415. }
  2416. if (safeMargin) {
  2417. const presentationTime = this.playerInterface_.getPresentationTime();
  2418. const duration = this.playerInterface_.mediaSourceEngine.getDuration();
  2419. await this.playerInterface_.mediaSourceEngine.remove(
  2420. mediaState.type, presentationTime + safeMargin, duration);
  2421. } else {
  2422. await this.playerInterface_.mediaSourceEngine.clear(mediaState.type);
  2423. this.destroyer_.ensureNotDestroyed();
  2424. if (flush) {
  2425. await this.playerInterface_.mediaSourceEngine.flush(
  2426. mediaState.type);
  2427. }
  2428. }
  2429. this.destroyer_.ensureNotDestroyed();
  2430. shaka.log.debug(logPrefix, 'cleared buffer');
  2431. mediaState.clearingBuffer = false;
  2432. mediaState.endOfStream = false;
  2433. // Since the clear operation was async, check to make sure we're not doing
  2434. // another update and we don't have one scheduled yet.
  2435. if (!mediaState.performingUpdate && !mediaState.updateTimer) {
  2436. this.scheduleUpdate_(mediaState, 0);
  2437. }
  2438. }
  2439. /**
  2440. * Schedules |mediaState|'s next update.
  2441. *
  2442. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2443. * @param {number} delay The delay in seconds.
  2444. * @private
  2445. */
  2446. scheduleUpdate_(mediaState, delay) {
  2447. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2448. // If the text's update is canceled and its mediaState is deleted, stop
  2449. // scheduling another update.
  2450. const type = mediaState.type;
  2451. if (type == shaka.util.ManifestParserUtils.ContentType.TEXT &&
  2452. !this.mediaStates_.has(type)) {
  2453. shaka.log.v1(logPrefix, 'Text stream is unloaded. No update is needed.');
  2454. return;
  2455. }
  2456. shaka.log.v2(logPrefix, 'updating in ' + delay + ' seconds');
  2457. goog.asserts.assert(mediaState.updateTimer == null,
  2458. logPrefix + ' did not expect update to be scheduled');
  2459. mediaState.updateTimer = new shaka.util.DelayedTick(async () => {
  2460. try {
  2461. await this.onUpdate_(mediaState);
  2462. } catch (error) {
  2463. if (this.playerInterface_) {
  2464. this.playerInterface_.onError(error);
  2465. }
  2466. }
  2467. }).tickAfter(delay);
  2468. }
  2469. /**
  2470. * If |mediaState| is scheduled to update, stop it.
  2471. *
  2472. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2473. * @private
  2474. */
  2475. cancelUpdate_(mediaState) {
  2476. if (mediaState.updateTimer == null) {
  2477. return;
  2478. }
  2479. mediaState.updateTimer.stop();
  2480. mediaState.updateTimer = null;
  2481. }
  2482. /**
  2483. * If |mediaState| holds any in-progress operations, abort them.
  2484. *
  2485. * @return {!Promise}
  2486. * @private
  2487. */
  2488. async abortOperations_(mediaState) {
  2489. if (mediaState.operation) {
  2490. await mediaState.operation.abort();
  2491. }
  2492. }
  2493. /**
  2494. * Handle streaming errors by delaying, then notifying the application by
  2495. * error callback and by streaming failure callback.
  2496. *
  2497. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2498. * @param {!shaka.util.Error} error
  2499. * @return {!Promise}
  2500. * @private
  2501. */
  2502. async handleStreamingError_(mediaState, error) {
  2503. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2504. if (error.code == shaka.util.Error.Code.STREAMING_NOT_ALLOWED) {
  2505. mediaState.performingUpdate = false;
  2506. this.cancelUpdate_(mediaState);
  2507. this.scheduleUpdate_(mediaState, 0);
  2508. return;
  2509. }
  2510. // If we invoke the callback right away, the application could trigger a
  2511. // rapid retry cycle that could be very unkind to the server. Instead,
  2512. // use the backoff system to delay and backoff the error handling.
  2513. await this.failureCallbackBackoff_.attempt();
  2514. this.destroyer_.ensureNotDestroyed();
  2515. // Try to recover from network errors, but not timeouts.
  2516. // See https://github.com/shaka-project/shaka-player/issues/7368
  2517. if (error.category === shaka.util.Error.Category.NETWORK &&
  2518. error.code != shaka.util.Error.Code.TIMEOUT) {
  2519. if (mediaState.restoreStreamAfterTrickPlay) {
  2520. this.setTrickPlay(/* on= */ false);
  2521. return;
  2522. }
  2523. const maxDisabledTime = this.getDisabledTime_(error);
  2524. if (maxDisabledTime) {
  2525. shaka.log.debug(logPrefix, 'Disabling stream due to error', error);
  2526. }
  2527. error.handled = this.playerInterface_.disableStream(
  2528. mediaState.stream, maxDisabledTime);
  2529. // Decrease the error severity to recoverable
  2530. if (error.handled) {
  2531. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  2532. }
  2533. }
  2534. // First fire an error event.
  2535. if (!error.handled ||
  2536. error.code != shaka.util.Error.Code.SEGMENT_MISSING) {
  2537. this.playerInterface_.onError(error);
  2538. }
  2539. // If the error was not handled by the application, call the failure
  2540. // callback.
  2541. if (!error.handled) {
  2542. this.config_.failureCallback(error);
  2543. }
  2544. }
  2545. /**
  2546. * @param {!shaka.util.Error} error
  2547. * @return {number}
  2548. * @private
  2549. */
  2550. getDisabledTime_(error) {
  2551. if (this.config_.maxDisabledTime === 0 &&
  2552. error.code == shaka.util.Error.Code.SEGMENT_MISSING) {
  2553. // Spec: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.3
  2554. // The client SHOULD NOT attempt to load Media Segments that have been
  2555. // marked with an EXT-X-GAP tag, or to load Partial Segments with a
  2556. // GAP=YES attribute. Instead, clients are encouraged to look for
  2557. // another Variant Stream of the same Rendition which does not have the
  2558. // same gap, and play that instead.
  2559. return 1;
  2560. }
  2561. return this.config_.maxDisabledTime;
  2562. }
  2563. /**
  2564. * Reset Media Source
  2565. *
  2566. * @param {boolean=} force
  2567. * @return {!Promise<boolean>}
  2568. */
  2569. async resetMediaSource(force = false, clearBuffer = true) {
  2570. const now = (Date.now() / 1000);
  2571. const minTimeBetweenRecoveries = this.config_.minTimeBetweenRecoveries;
  2572. if (!force) {
  2573. if (!this.config_.allowMediaSourceRecoveries ||
  2574. (now - this.lastMediaSourceReset_) < minTimeBetweenRecoveries) {
  2575. return false;
  2576. }
  2577. this.lastMediaSourceReset_ = now;
  2578. }
  2579. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2580. const audioMediaState = this.mediaStates_.get(ContentType.AUDIO);
  2581. if (audioMediaState) {
  2582. audioMediaState.lastInitSegmentReference = null;
  2583. audioMediaState.lastAppendWindowStart = null;
  2584. audioMediaState.lastAppendWindowEnd = null;
  2585. if (clearBuffer) {
  2586. this.forceClearBuffer_(audioMediaState);
  2587. }
  2588. this.abortOperations_(audioMediaState).catch(() => {});
  2589. if (audioMediaState.segmentIterator) {
  2590. audioMediaState.segmentIterator.resetToLastIndependent();
  2591. }
  2592. }
  2593. const videoMediaState = this.mediaStates_.get(ContentType.VIDEO);
  2594. if (videoMediaState) {
  2595. videoMediaState.lastInitSegmentReference = null;
  2596. videoMediaState.lastAppendWindowStart = null;
  2597. videoMediaState.lastAppendWindowEnd = null;
  2598. if (clearBuffer) {
  2599. this.forceClearBuffer_(videoMediaState);
  2600. }
  2601. this.abortOperations_(videoMediaState).catch(() => {});
  2602. if (videoMediaState.segmentIterator) {
  2603. videoMediaState.segmentIterator.resetToLastIndependent();
  2604. }
  2605. }
  2606. /**
  2607. * @type {!Map<shaka.util.ManifestParserUtils.ContentType,
  2608. * shaka.extern.Stream>}
  2609. */
  2610. const streamsByType = new Map();
  2611. if (this.currentVariant_.audio) {
  2612. streamsByType.set(ContentType.AUDIO, this.currentVariant_.audio);
  2613. }
  2614. if (this.currentVariant_.video) {
  2615. streamsByType.set(ContentType.VIDEO, this.currentVariant_.video);
  2616. }
  2617. await this.playerInterface_.mediaSourceEngine.reset(streamsByType);
  2618. if (videoMediaState &&
  2619. !videoMediaState.performingUpdate && !videoMediaState.updateTimer) {
  2620. this.scheduleUpdate_(videoMediaState, 0);
  2621. }
  2622. if (audioMediaState &&
  2623. !audioMediaState.performingUpdate && !audioMediaState.updateTimer) {
  2624. this.scheduleUpdate_(audioMediaState, 0);
  2625. }
  2626. return true;
  2627. }
  2628. /**
  2629. * Update the spatial video info and notify to the app.
  2630. *
  2631. * @param {shaka.extern.SpatialVideoInfo} info
  2632. * @private
  2633. */
  2634. updateSpatialVideoInfo_(info) {
  2635. if (this.spatialVideoInfo_.projection != info.projection ||
  2636. this.spatialVideoInfo_.hfov != info.hfov) {
  2637. const EventName = shaka.util.FakeEvent.EventName;
  2638. let event;
  2639. if (info.projection != null || info.hfov != null) {
  2640. const eventName = EventName.SpatialVideoInfoEvent;
  2641. const data = (new Map()).set('detail', info);
  2642. event = new shaka.util.FakeEvent(eventName, data);
  2643. } else {
  2644. const eventName = EventName.NoSpatialVideoInfoEvent;
  2645. event = new shaka.util.FakeEvent(eventName);
  2646. }
  2647. event.cancelable = true;
  2648. this.playerInterface_.onEvent(event);
  2649. this.spatialVideoInfo_ = info;
  2650. }
  2651. }
  2652. /**
  2653. * Update the segment iterator direction.
  2654. *
  2655. * @private
  2656. */
  2657. updateSegmentIteratorReverse_() {
  2658. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  2659. for (const mediaState of this.mediaStates_.values()) {
  2660. if (mediaState.segmentIterator) {
  2661. mediaState.segmentIterator.setReverse(reverse);
  2662. }
  2663. if (mediaState.segmentPrefetch) {
  2664. mediaState.segmentPrefetch.setReverse(reverse);
  2665. }
  2666. }
  2667. for (const prefetch of this.audioPrefetchMap_.values()) {
  2668. prefetch.setReverse(reverse);
  2669. }
  2670. }
  2671. /**
  2672. * Checks if need to push time forward to cross a boundary. If so,
  2673. * an MSE reset will happen. If the strategy is KEEP, this logic is skipped.
  2674. * Called on timeupdate to schedule a theoretical, future, offset or on
  2675. * waiting, which is another indicator we might need to cross a boundary.
  2676. * @param {boolean=} immediate
  2677. */
  2678. forwardTimeForCrossBoundary(immediate = false) {
  2679. if (this.config_.crossBoundaryStrategy ===
  2680. shaka.config.CrossBoundaryStrategy.KEEP) {
  2681. // When crossBoundaryStrategy changed to keep mid stream, we can bail
  2682. // out early.
  2683. return;
  2684. }
  2685. const video = this.playerInterface_.video;
  2686. if (video.seeking) {
  2687. // When seeking, close to a boundary, we can reset too early due to
  2688. // a subsequent waiting event. Schedule a theoretical delay.
  2689. immediate = false;
  2690. }
  2691. // Stop timer first, in case someone seeked back during the time a timer
  2692. // was scheduled.
  2693. this.crossBoundaryTimer_.stop();
  2694. const presentationTime = this.playerInterface_.getPresentationTime();
  2695. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2696. const mediaState = this.mediaStates_.get(ContentType.VIDEO) ||
  2697. this.mediaStates_.get(ContentType.AUDIO);
  2698. if (!mediaState || !mediaState.lastAppendWindowEnd ||
  2699. mediaState.clearingBuffer) {
  2700. return;
  2701. }
  2702. const threshold = shaka.media.StreamingEngine.CROSS_BOUNDARY_END_THRESHOLD_;
  2703. const fromEnd = mediaState.lastAppendWindowEnd - presentationTime;
  2704. // Check if greater than 0 to eliminate a backwards seek.
  2705. if (fromEnd > 0 && fromEnd < threshold) {
  2706. // Set the intended time to seek to in order to cross the boundary.
  2707. this.boundaryTime_ = mediaState.lastAppendWindowEnd;
  2708. if (immediate) {
  2709. this.crossBoundaryTimer_.tickNow();
  2710. } else {
  2711. // When not immediate, we schedule a time tick when the boundary
  2712. // theoretically should be reached, else we'd be stalled when
  2713. // a waiting event doesn't come (due to segment misalignment).
  2714. this.crossBoundaryTimer_.tickAfter(fromEnd);
  2715. }
  2716. }
  2717. }
  2718. /**
  2719. * Returns whether the reference should be discarded. If the segment crosses
  2720. * a boundary, we'll discard it based on the crossBoundaryStrategy.
  2721. *
  2722. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2723. * @param {!shaka.media.SegmentReference} reference
  2724. * @private
  2725. */
  2726. discardReferenceByBoundary_(mediaState, reference) {
  2727. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2728. if (mediaState.type === ContentType.TEXT) {
  2729. return false;
  2730. }
  2731. const lastInitRef = mediaState.lastInitSegmentReference;
  2732. if (!lastInitRef) {
  2733. return false;
  2734. }
  2735. const CrossBoundaryStrategy = shaka.config.CrossBoundaryStrategy;
  2736. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2737. const initRef = reference.initSegmentReference;
  2738. let discard = lastInitRef.boundaryEnd !== initRef.boundaryEnd;
  2739. // Some devices can play plain data when initialized with an encrypted
  2740. // init segment. We can keep the MediaSource in this case.
  2741. if (this.config_.crossBoundaryStrategy ===
  2742. CrossBoundaryStrategy.RESET_TO_ENCRYPTED) {
  2743. if (!lastInitRef.encrypted && !initRef.encrypted) {
  2744. // We're crossing a plain to plain boundary, allow the reference.
  2745. discard = false;
  2746. }
  2747. if (lastInitRef.encrypted) {
  2748. // We initialized MediaSource with an encrypted init segment, from
  2749. // now on, we can keep the buffer.
  2750. shaka.log.debug(logPrefix, 'stream is encrypted, ' +
  2751. 'discard crossBoundaryStrategy');
  2752. this.config_.crossBoundaryStrategy = CrossBoundaryStrategy.KEEP;
  2753. }
  2754. }
  2755. // If discarded & seeked across a boundary, reset MediaSource.
  2756. if (discard && mediaState.seeked) {
  2757. shaka.log.debug(logPrefix, 'reset mediaSource',
  2758. 'from=', mediaState.lastInitSegmentReference,
  2759. 'to=', reference.initSegmentReference);
  2760. this.resetMediaSource(/* force= */ true).then(() => {
  2761. const eventName = shaka.util.FakeEvent.EventName.BoundaryCrossed;
  2762. this.playerInterface_.onEvent(new shaka.util.FakeEvent(eventName));
  2763. });
  2764. }
  2765. return discard;
  2766. }
  2767. /**
  2768. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2769. * @return {string} A log prefix of the form ($CONTENT_TYPE:$STREAM_ID), e.g.,
  2770. * "(audio:5)" or "(video:hd)".
  2771. * @private
  2772. */
  2773. static logPrefix_(mediaState) {
  2774. return '(' + mediaState.type + ':' + mediaState.stream.id + ')';
  2775. }
  2776. };
  2777. /**
  2778. * @typedef {{
  2779. * getPresentationTime: function():number,
  2780. * getBandwidthEstimate: function():number,
  2781. * getPlaybackRate: function():number,
  2782. * video: !HTMLMediaElement,
  2783. * mediaSourceEngine: !shaka.media.MediaSourceEngine,
  2784. * netEngine: shaka.net.NetworkingEngine,
  2785. * onError: function(!shaka.util.Error),
  2786. * onEvent: function(!Event),
  2787. * onSegmentAppended: function(!shaka.media.SegmentReference,
  2788. * !shaka.extern.Stream, boolean),
  2789. * onInitSegmentAppended: function(!number,!shaka.media.InitSegmentReference),
  2790. * beforeAppendSegment: function(
  2791. * shaka.util.ManifestParserUtils.ContentType,!BufferSource):Promise,
  2792. * disableStream: function(!shaka.extern.Stream, number):boolean
  2793. * }}
  2794. *
  2795. * @property {function():number} getPresentationTime
  2796. * Get the position in the presentation (in seconds) of the content that the
  2797. * viewer is seeing on screen right now.
  2798. * @property {function():number} getBandwidthEstimate
  2799. * Get the estimated bandwidth in bits per second.
  2800. * @property {function():number} getPlaybackRate
  2801. * Get the playback rate.
  2802. * @property {!HTMLVideoElement} video
  2803. * Get the video element.
  2804. * @property {!shaka.media.MediaSourceEngine} mediaSourceEngine
  2805. * The MediaSourceEngine. The caller retains ownership.
  2806. * @property {shaka.net.NetworkingEngine} netEngine
  2807. * The NetworkingEngine instance to use. The caller retains ownership.
  2808. * @property {function(!shaka.util.Error)} onError
  2809. * Called when an error occurs. If the error is recoverable (see
  2810. * {@link shaka.util.Error}) then the caller may invoke either
  2811. * StreamingEngine.switch*() or StreamingEngine.seeked() to attempt recovery.
  2812. * @property {function(!Event)} onEvent
  2813. * Called when an event occurs that should be sent to the app.
  2814. * @property {function(!shaka.media.SegmentReference,
  2815. * !shaka.extern.Stream, boolean)} onSegmentAppended
  2816. * Called after a segment is successfully appended to a MediaSource.
  2817. * @property {function(!number,
  2818. * !shaka.media.InitSegmentReference)} onInitSegmentAppended
  2819. * Called when an init segment is appended to a MediaSource.
  2820. * @property {!function(shaka.util.ManifestParserUtils.ContentType,
  2821. * !BufferSource):Promise} beforeAppendSegment
  2822. * A function called just before appending to the source buffer.
  2823. * @property {function(!shaka.extern.Stream, number):boolean} disableStream
  2824. * Called to temporarily disable a stream i.e. disabling all variant
  2825. * containing said stream.
  2826. */
  2827. shaka.media.StreamingEngine.PlayerInterface;
  2828. /**
  2829. * @typedef {{
  2830. * type: shaka.util.ManifestParserUtils.ContentType,
  2831. * stream: shaka.extern.Stream,
  2832. * segmentIterator: shaka.media.SegmentIterator,
  2833. * lastSegmentReference: shaka.media.SegmentReference,
  2834. * lastInitSegmentReference: shaka.media.InitSegmentReference,
  2835. * lastTimestampOffset: ?number,
  2836. * lastAppendWindowStart: ?number,
  2837. * lastAppendWindowEnd: ?number,
  2838. * lastCodecs: ?string,
  2839. * lastMimeType: ?string,
  2840. * restoreStreamAfterTrickPlay: ?shaka.extern.Stream,
  2841. * endOfStream: boolean,
  2842. * performingUpdate: boolean,
  2843. * updateTimer: shaka.util.DelayedTick,
  2844. * waitingToClearBuffer: boolean,
  2845. * waitingToFlushBuffer: boolean,
  2846. * clearBufferSafeMargin: number,
  2847. * clearingBuffer: boolean,
  2848. * seeked: boolean,
  2849. * adaptation: boolean,
  2850. * recovering: boolean,
  2851. * hasError: boolean,
  2852. * operation: shaka.net.NetworkingEngine.PendingRequest,
  2853. * segmentPrefetch: shaka.media.SegmentPrefetch,
  2854. * dependencyMediaState: ?shaka.media.StreamingEngine.MediaState_
  2855. * }}
  2856. *
  2857. * @description
  2858. * Contains the state of a logical stream, i.e., a sequence of segmented data
  2859. * for a particular content type. At any given time there is a Stream object
  2860. * associated with the state of the logical stream.
  2861. *
  2862. * @property {shaka.util.ManifestParserUtils.ContentType} type
  2863. * The stream's content type, e.g., 'audio', 'video', or 'text'.
  2864. * @property {shaka.extern.Stream} stream
  2865. * The current Stream.
  2866. * @property {shaka.media.SegmentIndexIterator} segmentIterator
  2867. * An iterator through the segments of |stream|.
  2868. * @property {shaka.media.SegmentReference} lastSegmentReference
  2869. * The SegmentReference of the last segment that was appended.
  2870. * @property {shaka.media.InitSegmentReference} lastInitSegmentReference
  2871. * The InitSegmentReference of the last init segment that was appended.
  2872. * @property {?number} lastTimestampOffset
  2873. * The last timestamp offset given to MediaSourceEngine for this type.
  2874. * @property {?number} lastAppendWindowStart
  2875. * The last append window start given to MediaSourceEngine for this type.
  2876. * @property {?number} lastAppendWindowEnd
  2877. * The last append window end given to MediaSourceEngine for this type.
  2878. * @property {?string} lastCodecs
  2879. * The last append codecs given to MediaSourceEngine for this type.
  2880. * @property {?string} lastMimeType
  2881. * The last append mime type given to MediaSourceEngine for this type.
  2882. * @property {?shaka.extern.Stream} restoreStreamAfterTrickPlay
  2883. * The Stream to restore after trick play mode is turned off.
  2884. * @property {boolean} endOfStream
  2885. * True indicates that the end of the buffer has hit the end of the
  2886. * presentation.
  2887. * @property {boolean} performingUpdate
  2888. * True indicates that an update is in progress.
  2889. * @property {shaka.util.DelayedTick} updateTimer
  2890. * A timer used to update the media state.
  2891. * @property {boolean} waitingToClearBuffer
  2892. * True indicates that the buffer must be cleared after the current update
  2893. * finishes.
  2894. * @property {boolean} waitingToFlushBuffer
  2895. * True indicates that the buffer must be flushed after it is cleared.
  2896. * @property {number} clearBufferSafeMargin
  2897. * The amount of buffer to retain when clearing the buffer after the update.
  2898. * @property {boolean} clearingBuffer
  2899. * True indicates that the buffer is being cleared.
  2900. * @property {boolean} seeked
  2901. * True indicates that the presentation just seeked.
  2902. * @property {boolean} adaptation
  2903. * True indicates that the presentation just automatically switched variants.
  2904. * @property {boolean} recovering
  2905. * True indicates that the last segment was not appended because it could not
  2906. * fit in the buffer.
  2907. * @property {boolean} hasError
  2908. * True indicates that the stream has encountered an error and has stopped
  2909. * updating.
  2910. * @property {shaka.net.NetworkingEngine.PendingRequest} operation
  2911. * Operation with the number of bytes to be downloaded.
  2912. * @property {?shaka.media.SegmentPrefetch} segmentPrefetch
  2913. * A prefetch object for managing prefetching. Null if unneeded
  2914. * (if prefetching is disabled, etc).
  2915. * @property {?shaka.media.StreamingEngine.MediaState_} dependencyMediaState
  2916. * A dependency media state.
  2917. */
  2918. shaka.media.StreamingEngine.MediaState_;
  2919. /**
  2920. * The fudge factor for appendWindowStart. By adjusting the window backward, we
  2921. * avoid rounding errors that could cause us to remove the keyframe at the start
  2922. * of the Period.
  2923. *
  2924. * NOTE: This was increased as part of the solution to
  2925. * https://github.com/shaka-project/shaka-player/issues/1281
  2926. *
  2927. * @const {number}
  2928. * @private
  2929. */
  2930. shaka.media.StreamingEngine.APPEND_WINDOW_START_FUDGE_ = 0.1;
  2931. /**
  2932. * The fudge factor for appendWindowEnd. By adjusting the window backward, we
  2933. * avoid rounding errors that could cause us to remove the last few samples of
  2934. * the Period. This rounding error could then create an artificial gap and a
  2935. * stutter when the gap-jumping logic takes over.
  2936. *
  2937. * https://github.com/shaka-project/shaka-player/issues/1597
  2938. *
  2939. * @const {number}
  2940. * @private
  2941. */
  2942. shaka.media.StreamingEngine.APPEND_WINDOW_END_FUDGE_ = 0.01;
  2943. /**
  2944. * The maximum number of segments by which a stream can get ahead of other
  2945. * streams.
  2946. *
  2947. * Introduced to keep StreamingEngine from letting one media type get too far
  2948. * ahead of another. For example, audio segments are typically much smaller
  2949. * than video segments, so in the time it takes to fetch one video segment, we
  2950. * could fetch many audio segments. This doesn't help with buffering, though,
  2951. * since the intersection of the two buffered ranges is what counts.
  2952. *
  2953. * @const {number}
  2954. * @private
  2955. */
  2956. shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_ = 1;
  2957. /**
  2958. * The threshold to decide if we're close to a boundary. If presentation time
  2959. * is before this offset, boundary crossing logic will be skipped.
  2960. *
  2961. * @const {number}
  2962. * @private
  2963. */
  2964. shaka.media.StreamingEngine.CROSS_BOUNDARY_END_THRESHOLD_ = 1;