Source: lib/media/streaming_engine.js

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