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