Source: lib/media/streaming_engine.js

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