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