Source: lib/media/streaming_engine.js

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