Source: lib/media/streaming_engine.js

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