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