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