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