Source: lib/media/streaming_engine.js

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