Source: lib/media/streaming_engine.js

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