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. try {
  1026. await mediaState.stream.createSegmentIndex();
  1027. } catch (error) {
  1028. await this.handleStreamingError_(mediaState, error);
  1029. return;
  1030. }
  1031. if (thisStream != mediaState.stream) {
  1032. // We switched streams while in the middle of this async call to
  1033. // createSegmentIndex. Abandon this update and schedule a new one if
  1034. // there's not already one pending.
  1035. // Releases the segmentIndex of the old stream.
  1036. if (thisStream.closeSegmentIndex) {
  1037. goog.asserts.assert(!mediaState.stream.segmentIndex,
  1038. 'mediastate.stream should not have segmentIndex yet.');
  1039. thisStream.closeSegmentIndex();
  1040. }
  1041. if (!mediaState.performingUpdate && !mediaState.updateTimer) {
  1042. this.scheduleUpdate_(mediaState, 0);
  1043. }
  1044. return;
  1045. }
  1046. }
  1047. // Update the MediaState.
  1048. try {
  1049. const delay = this.update_(mediaState);
  1050. if (delay != null) {
  1051. this.scheduleUpdate_(mediaState, delay);
  1052. mediaState.hasError = false;
  1053. }
  1054. } catch (error) {
  1055. await this.handleStreamingError_(mediaState, error);
  1056. return;
  1057. }
  1058. const mediaStates = Array.from(this.mediaStates_.values());
  1059. // Check if we've buffered to the end of the presentation. We delay adding
  1060. // the audio and video media states, so it is possible for the text stream
  1061. // to be the only state and buffer to the end. So we need to wait until we
  1062. // have completed startup to determine if we have reached the end.
  1063. if (this.startupComplete_ &&
  1064. mediaStates.every((ms) => ms.endOfStream)) {
  1065. shaka.log.v1(logPrefix, 'calling endOfStream()...');
  1066. await this.playerInterface_.mediaSourceEngine.endOfStream();
  1067. this.destroyer_.ensureNotDestroyed();
  1068. // If the media segments don't reach the end, then we need to update the
  1069. // timeline duration to match the final media duration to avoid
  1070. // buffering forever at the end.
  1071. // We should only do this if the duration needs to shrink.
  1072. // Growing it by less than 1ms can actually cause buffering on
  1073. // replay, as in https://github.com/shaka-project/shaka-player/issues/979
  1074. // On some platforms, this can spuriously be 0, so ignore this case.
  1075. // https://github.com/shaka-project/shaka-player/issues/1967,
  1076. const duration = this.playerInterface_.mediaSourceEngine.getDuration();
  1077. if (duration != 0 &&
  1078. duration < this.manifest_.presentationTimeline.getDuration()) {
  1079. this.manifest_.presentationTimeline.setDuration(duration);
  1080. }
  1081. }
  1082. }
  1083. /**
  1084. * Updates the given MediaState.
  1085. *
  1086. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1087. * @return {?number} The number of seconds to wait until updating again or
  1088. * null if another update does not need to be scheduled.
  1089. * @private
  1090. */
  1091. update_(mediaState) {
  1092. goog.asserts.assert(this.manifest_, 'manifest_ should not be null');
  1093. goog.asserts.assert(this.config_, 'config_ should not be null');
  1094. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1095. // Do not schedule update for closed captions text mediastate, since closed
  1096. // captions are embedded in video streams.
  1097. if (shaka.media.StreamingEngine.isEmbeddedText_(mediaState)) {
  1098. this.playerInterface_.mediaSourceEngine.setSelectedClosedCaptionId(
  1099. mediaState.stream.originalId || '');
  1100. return null;
  1101. } else if (mediaState.type == ContentType.TEXT) {
  1102. // Disable embedded captions if not desired (e.g. if transitioning from
  1103. // embedded to not-embedded captions).
  1104. this.playerInterface_.mediaSourceEngine.clearSelectedClosedCaptionId();
  1105. }
  1106. if (!this.playerInterface_.mediaSourceEngine.isStreamingAllowed() &&
  1107. mediaState.type != ContentType.TEXT) {
  1108. // It is not allowed to add segments yet, so we schedule an update to
  1109. // check again later. So any prediction we make now could be terribly
  1110. // invalid soon.
  1111. return this.config_.updateIntervalSeconds / 2;
  1112. }
  1113. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1114. // Compute how far we've buffered ahead of the playhead.
  1115. const presentationTime = this.playerInterface_.getPresentationTime();
  1116. if (mediaState.type === ContentType.AUDIO) {
  1117. // evict all prefetched segments that are before the presentationTime
  1118. for (const stream of this.audioPrefetchMap_.keys()) {
  1119. const prefetch = this.audioPrefetchMap_.get(stream);
  1120. prefetch.evict(presentationTime, /* clearInitSegments= */ true);
  1121. prefetch.prefetchSegmentsByTime(presentationTime);
  1122. }
  1123. }
  1124. // Get the next timestamp we need.
  1125. const timeNeeded = this.getTimeNeeded_(mediaState, presentationTime);
  1126. shaka.log.v2(logPrefix, 'timeNeeded=' + timeNeeded);
  1127. // Get the amount of content we have buffered, accounting for drift. This
  1128. // is only used to determine if we have meet the buffering goal. This
  1129. // should be the same method that PlayheadObserver uses.
  1130. const bufferedAhead =
  1131. this.playerInterface_.mediaSourceEngine.bufferedAheadOf(
  1132. mediaState.type, presentationTime);
  1133. shaka.log.v2(logPrefix,
  1134. 'update_:',
  1135. 'presentationTime=' + presentationTime,
  1136. 'bufferedAhead=' + bufferedAhead);
  1137. const unscaledBufferingGoal = Math.max(
  1138. this.manifest_.minBufferTime || 0,
  1139. this.config_.rebufferingGoal,
  1140. this.config_.bufferingGoal);
  1141. const scaledBufferingGoal = Math.max(1,
  1142. unscaledBufferingGoal * this.bufferingGoalScale_);
  1143. // Check if we've buffered to the end of the presentation.
  1144. const timeUntilEnd =
  1145. this.manifest_.presentationTimeline.getDuration() - timeNeeded;
  1146. const oneMicrosecond = 1e-6;
  1147. const bufferEnd =
  1148. this.playerInterface_.mediaSourceEngine.bufferEnd(mediaState.type);
  1149. if (timeUntilEnd < oneMicrosecond && !!bufferEnd) {
  1150. // We shouldn't rebuffer if the playhead is close to the end of the
  1151. // presentation.
  1152. shaka.log.debug(logPrefix, 'buffered to end of presentation');
  1153. mediaState.endOfStream = true;
  1154. if (mediaState.type == ContentType.VIDEO) {
  1155. // Since the text stream of CEA closed captions doesn't have update
  1156. // timer, we have to set the text endOfStream based on the video
  1157. // stream's endOfStream state.
  1158. const textState = this.mediaStates_.get(ContentType.TEXT);
  1159. if (textState &&
  1160. shaka.media.StreamingEngine.isEmbeddedText_(textState)) {
  1161. textState.endOfStream = true;
  1162. }
  1163. }
  1164. return null;
  1165. }
  1166. mediaState.endOfStream = false;
  1167. // If we've buffered to the buffering goal then schedule an update.
  1168. if (bufferedAhead >= scaledBufferingGoal) {
  1169. shaka.log.v2(logPrefix, 'buffering goal met');
  1170. // Do not try to predict the next update. Just poll according to
  1171. // configuration (seconds). The playback rate can change at any time, so
  1172. // any prediction we make now could be terribly invalid soon.
  1173. return this.config_.updateIntervalSeconds / 2;
  1174. }
  1175. const reference = this.getSegmentReferenceNeeded_(
  1176. mediaState, presentationTime, bufferEnd);
  1177. if (!reference) {
  1178. // The segment could not be found, does not exist, or is not available.
  1179. // In any case just try again... if the manifest is incomplete or is not
  1180. // being updated then we'll idle forever; otherwise, we'll end up getting
  1181. // a SegmentReference eventually.
  1182. return this.config_.updateIntervalSeconds;
  1183. }
  1184. // Do not let any one stream get far ahead of any other.
  1185. let minTimeNeeded = Infinity;
  1186. const mediaStates = Array.from(this.mediaStates_.values());
  1187. for (const otherState of mediaStates) {
  1188. // Do not consider embedded captions in this calculation. It could lead
  1189. // to hangs in streaming.
  1190. if (shaka.media.StreamingEngine.isEmbeddedText_(otherState)) {
  1191. continue;
  1192. }
  1193. // If there is no next segment, ignore this stream. This happens with
  1194. // text when there's a Period with no text in it.
  1195. if (otherState.segmentIterator && !otherState.segmentIterator.current()) {
  1196. continue;
  1197. }
  1198. const timeNeeded = this.getTimeNeeded_(otherState, presentationTime);
  1199. minTimeNeeded = Math.min(minTimeNeeded, timeNeeded);
  1200. }
  1201. const maxSegmentDuration =
  1202. this.manifest_.presentationTimeline.getMaxSegmentDuration();
  1203. const maxRunAhead = maxSegmentDuration *
  1204. shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_;
  1205. if (timeNeeded >= minTimeNeeded + maxRunAhead) {
  1206. // Wait and give other media types time to catch up to this one.
  1207. // For example, let video buffering catch up to audio buffering before
  1208. // fetching another audio segment.
  1209. shaka.log.v2(logPrefix, 'waiting for other streams to buffer');
  1210. return this.config_.updateIntervalSeconds;
  1211. }
  1212. if (mediaState.segmentPrefetch && mediaState.segmentIterator &&
  1213. !this.audioPrefetchMap_.has(mediaState.stream)) {
  1214. mediaState.segmentPrefetch.evict(presentationTime);
  1215. mediaState.segmentPrefetch.prefetchSegmentsByTime(reference.startTime);
  1216. }
  1217. const p = this.fetchAndAppend_(mediaState, presentationTime, reference);
  1218. p.catch(() => {}); // TODO(#1993): Handle asynchronous errors.
  1219. return null;
  1220. }
  1221. /**
  1222. * Gets the next timestamp needed. Returns the playhead's position if the
  1223. * buffer is empty; otherwise, returns the time at which the last segment
  1224. * appended ends.
  1225. *
  1226. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1227. * @param {number} presentationTime
  1228. * @return {number} The next timestamp needed.
  1229. * @private
  1230. */
  1231. getTimeNeeded_(mediaState, presentationTime) {
  1232. // Get the next timestamp we need. We must use |lastSegmentReference|
  1233. // to determine this and not the actual buffer for two reasons:
  1234. // 1. Actual segments end slightly before their advertised end times, so
  1235. // the next timestamp we need is actually larger than |bufferEnd|.
  1236. // 2. There may be drift (the timestamps in the segments are ahead/behind
  1237. // of the timestamps in the manifest), but we need drift-free times
  1238. // when comparing times against the presentation timeline.
  1239. if (!mediaState.lastSegmentReference) {
  1240. return presentationTime;
  1241. }
  1242. return mediaState.lastSegmentReference.endTime;
  1243. }
  1244. /**
  1245. * Gets the SegmentReference of the next segment needed.
  1246. *
  1247. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1248. * @param {number} presentationTime
  1249. * @param {?number} bufferEnd
  1250. * @return {shaka.media.SegmentReference} The SegmentReference of the
  1251. * next segment needed. Returns null if a segment could not be found, does
  1252. * not exist, or is not available.
  1253. * @private
  1254. */
  1255. getSegmentReferenceNeeded_(mediaState, presentationTime, bufferEnd) {
  1256. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1257. goog.asserts.assert(
  1258. mediaState.stream.segmentIndex,
  1259. 'segment index should have been generated already');
  1260. if (mediaState.segmentIterator) {
  1261. // Something is buffered from the same Stream. Use the current position
  1262. // in the segment index. This is updated via next() after each segment is
  1263. // appended.
  1264. return mediaState.segmentIterator.current();
  1265. } else if (mediaState.lastSegmentReference || bufferEnd) {
  1266. // Something is buffered from another Stream.
  1267. const time = mediaState.lastSegmentReference ?
  1268. mediaState.lastSegmentReference.endTime :
  1269. bufferEnd;
  1270. goog.asserts.assert(time != null, 'Should have a time to search');
  1271. shaka.log.v1(
  1272. logPrefix, 'looking up segment from new stream endTime:', time);
  1273. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  1274. mediaState.segmentIterator =
  1275. mediaState.stream.segmentIndex.getIteratorForTime(
  1276. time, /* allowNonIndepedent= */ false, reverse);
  1277. const ref = mediaState.segmentIterator &&
  1278. mediaState.segmentIterator.next().value;
  1279. if (ref == null) {
  1280. shaka.log.warning(logPrefix, 'cannot find segment', 'endTime:', time);
  1281. }
  1282. return ref;
  1283. } else {
  1284. // Nothing is buffered. Start at the playhead time.
  1285. // If there's positive drift then we need to adjust the lookup time, and
  1286. // may wind up requesting the previous segment to be safe.
  1287. // inaccurateManifestTolerance should be 0 for low latency streaming.
  1288. const inaccurateTolerance = this.config_.inaccurateManifestTolerance;
  1289. const lookupTime = Math.max(presentationTime - inaccurateTolerance, 0);
  1290. shaka.log.v1(logPrefix, 'looking up segment',
  1291. 'lookupTime:', lookupTime,
  1292. 'presentationTime:', presentationTime);
  1293. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  1294. let ref = null;
  1295. if (inaccurateTolerance) {
  1296. mediaState.segmentIterator =
  1297. mediaState.stream.segmentIndex.getIteratorForTime(
  1298. lookupTime, /* allowNonIndepedent= */ false, reverse);
  1299. ref = mediaState.segmentIterator &&
  1300. mediaState.segmentIterator.next().value;
  1301. }
  1302. if (!ref) {
  1303. // If we can't find a valid segment with the drifted time, look for a
  1304. // segment with the presentation time.
  1305. mediaState.segmentIterator =
  1306. mediaState.stream.segmentIndex.getIteratorForTime(
  1307. presentationTime, /* allowNonIndepedent= */ false, reverse);
  1308. ref = mediaState.segmentIterator &&
  1309. mediaState.segmentIterator.next().value;
  1310. }
  1311. if (ref == null) {
  1312. shaka.log.warning(logPrefix, 'cannot find segment',
  1313. 'lookupTime:', lookupTime,
  1314. 'presentationTime:', presentationTime);
  1315. }
  1316. return ref;
  1317. }
  1318. }
  1319. /**
  1320. * Fetches and appends the given segment. Sets up the given MediaState's
  1321. * associated SourceBuffer and evicts segments if either are required
  1322. * beforehand. Schedules another update after completing successfully.
  1323. *
  1324. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  1325. * @param {number} presentationTime
  1326. * @param {!shaka.media.SegmentReference} reference
  1327. * @private
  1328. */
  1329. async fetchAndAppend_(mediaState, presentationTime, reference) {
  1330. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1331. const StreamingEngine = shaka.media.StreamingEngine;
  1332. const logPrefix = StreamingEngine.logPrefix_(mediaState);
  1333. shaka.log.v1(logPrefix,
  1334. 'fetchAndAppend_:',
  1335. 'presentationTime=' + presentationTime,
  1336. 'reference.startTime=' + reference.startTime,
  1337. 'reference.endTime=' + reference.endTime);
  1338. // Subtlety: The playhead may move while asynchronous update operations are
  1339. // in progress, so we should avoid calling playhead.getTime() in any
  1340. // callbacks. Furthermore, switch() or seeked() may be called at any time,
  1341. // so we store the old iterator. This allows the mediaState to change and
  1342. // we'll update the old iterator.
  1343. const stream = mediaState.stream;
  1344. const iter = mediaState.segmentIterator;
  1345. mediaState.performingUpdate = true;
  1346. try {
  1347. if (reference.getStatus() ==
  1348. shaka.media.SegmentReference.Status.MISSING) {
  1349. throw new shaka.util.Error(
  1350. shaka.util.Error.Severity.RECOVERABLE,
  1351. shaka.util.Error.Category.NETWORK,
  1352. shaka.util.Error.Code.SEGMENT_MISSING);
  1353. }
  1354. await this.initSourceBuffer_(mediaState, reference);
  1355. this.destroyer_.ensureNotDestroyed();
  1356. if (this.fatalError_) {
  1357. return;
  1358. }
  1359. shaka.log.v2(logPrefix, 'fetching segment');
  1360. const isMP4 = stream.mimeType == 'video/mp4' ||
  1361. stream.mimeType == 'audio/mp4';
  1362. const isReadableStreamSupported = window.ReadableStream;
  1363. const lowLatencyMode = this.config_.lowLatencyMode &&
  1364. this.manifest_.isLowLatency;
  1365. // Enable MP4 low latency streaming with ReadableStream chunked data.
  1366. // And only for DASH and HLS with byterange optimization.
  1367. if (lowLatencyMode && isReadableStreamSupported && isMP4 &&
  1368. (this.manifest_.type != shaka.media.ManifestParser.HLS ||
  1369. reference.hasByterangeOptimization())) {
  1370. let remaining = new Uint8Array(0);
  1371. let processingResult = false;
  1372. let callbackCalled = false;
  1373. let streamDataCallbackError;
  1374. const streamDataCallback = async (data) => {
  1375. if (processingResult) {
  1376. // If the fallback result processing was triggered, don't also
  1377. // append the buffer here. In theory this should never happen,
  1378. // but it does on some older TVs.
  1379. return;
  1380. }
  1381. callbackCalled = true;
  1382. this.destroyer_.ensureNotDestroyed();
  1383. if (this.fatalError_) {
  1384. return;
  1385. }
  1386. try {
  1387. // Append the data with complete boxes.
  1388. // Every time streamDataCallback gets called, append the new data
  1389. // to the remaining data.
  1390. // Find the last fully completed Mdat box, and slice the data into
  1391. // two parts: the first part with completed Mdat boxes, and the
  1392. // second part with an incomplete box.
  1393. // Append the first part, and save the second part as remaining
  1394. // data, and handle it with the next streamDataCallback call.
  1395. remaining = this.concatArray_(remaining, data);
  1396. let sawMDAT = false;
  1397. let offset = 0;
  1398. new shaka.util.Mp4Parser()
  1399. .box('mdat', (box) => {
  1400. offset = box.size + box.start;
  1401. sawMDAT = true;
  1402. })
  1403. .parse(remaining, /* partialOkay= */ false,
  1404. /* isChunkedData= */ true);
  1405. if (sawMDAT) {
  1406. const dataToAppend = remaining.subarray(0, offset);
  1407. remaining = remaining.subarray(offset);
  1408. await this.append_(
  1409. mediaState, presentationTime, stream, reference, dataToAppend,
  1410. /* isChunkedData= */ true);
  1411. if (mediaState.segmentPrefetch && mediaState.segmentIterator) {
  1412. mediaState.segmentPrefetch.prefetchSegmentsByTime(
  1413. reference.startTime, /* skipFirst= */ true);
  1414. }
  1415. }
  1416. } catch (error) {
  1417. streamDataCallbackError = error;
  1418. }
  1419. };
  1420. const result =
  1421. await this.fetch_(mediaState, reference, streamDataCallback);
  1422. if (streamDataCallbackError) {
  1423. throw streamDataCallbackError;
  1424. }
  1425. if (!callbackCalled) {
  1426. // In some environments, we might be forced to use network plugins
  1427. // that don't support streamDataCallback. In those cases, as a
  1428. // fallback, append the buffer here.
  1429. processingResult = true;
  1430. this.destroyer_.ensureNotDestroyed();
  1431. if (this.fatalError_) {
  1432. return;
  1433. }
  1434. // If the text stream gets switched between fetch_() and append_(),
  1435. // the new text parser is initialized, but the new init segment is
  1436. // not fetched yet. That would cause an error in
  1437. // TextParser.parseMedia().
  1438. // See http://b/168253400
  1439. if (mediaState.waitingToClearBuffer) {
  1440. shaka.log.info(logPrefix, 'waitingToClearBuffer, skip append');
  1441. mediaState.performingUpdate = false;
  1442. this.scheduleUpdate_(mediaState, 0);
  1443. return;
  1444. }
  1445. await this.append_(
  1446. mediaState, presentationTime, stream, reference, result);
  1447. }
  1448. if (mediaState.segmentPrefetch && mediaState.segmentIterator) {
  1449. mediaState.segmentPrefetch.prefetchSegmentsByTime(
  1450. reference.startTime, /* skipFirst= */ true);
  1451. }
  1452. } else {
  1453. if (lowLatencyMode && !isReadableStreamSupported) {
  1454. shaka.log.warning('Low latency streaming mode is enabled, but ' +
  1455. 'ReadableStream is not supported by the browser.');
  1456. }
  1457. const fetchSegment = this.fetch_(mediaState, reference);
  1458. const result = await fetchSegment;
  1459. this.destroyer_.ensureNotDestroyed();
  1460. if (this.fatalError_) {
  1461. return;
  1462. }
  1463. this.destroyer_.ensureNotDestroyed();
  1464. // If the text stream gets switched between fetch_() and append_(), the
  1465. // new text parser is initialized, but the new init segment is not
  1466. // fetched yet. That would cause an error in TextParser.parseMedia().
  1467. // See http://b/168253400
  1468. if (mediaState.waitingToClearBuffer) {
  1469. shaka.log.info(logPrefix, 'waitingToClearBuffer, skip append');
  1470. mediaState.performingUpdate = false;
  1471. this.scheduleUpdate_(mediaState, 0);
  1472. return;
  1473. }
  1474. await this.append_(
  1475. mediaState, presentationTime, stream, reference, result);
  1476. }
  1477. this.destroyer_.ensureNotDestroyed();
  1478. if (this.fatalError_) {
  1479. return;
  1480. }
  1481. // move to next segment after appending the current segment.
  1482. mediaState.lastSegmentReference = reference;
  1483. const newRef = iter.next().value;
  1484. shaka.log.v2(logPrefix, 'advancing to next segment', newRef);
  1485. mediaState.performingUpdate = false;
  1486. mediaState.recovering = false;
  1487. const info = this.playerInterface_.mediaSourceEngine.getBufferedInfo();
  1488. const buffered = info[mediaState.type];
  1489. // Convert the buffered object to a string capture its properties on
  1490. // WebOS.
  1491. shaka.log.v1(logPrefix, 'finished fetch and append',
  1492. JSON.stringify(buffered));
  1493. if (!mediaState.waitingToClearBuffer) {
  1494. this.playerInterface_.onSegmentAppended(reference, mediaState.stream);
  1495. }
  1496. // Update right away.
  1497. this.scheduleUpdate_(mediaState, 0);
  1498. } catch (error) {
  1499. this.destroyer_.ensureNotDestroyed(error);
  1500. if (this.fatalError_) {
  1501. return;
  1502. }
  1503. goog.asserts.assert(error instanceof shaka.util.Error,
  1504. 'Should only receive a Shaka error');
  1505. mediaState.performingUpdate = false;
  1506. if (error.code == shaka.util.Error.Code.OPERATION_ABORTED) {
  1507. // If the network slows down, abort the current fetch request and start
  1508. // a new one, and ignore the error message.
  1509. mediaState.performingUpdate = false;
  1510. this.cancelUpdate_(mediaState);
  1511. this.scheduleUpdate_(mediaState, 0);
  1512. } else if (mediaState.type == ContentType.TEXT &&
  1513. this.config_.ignoreTextStreamFailures) {
  1514. if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS) {
  1515. shaka.log.warning(logPrefix,
  1516. 'Text stream failed to download. Proceeding without it.');
  1517. } else {
  1518. shaka.log.warning(logPrefix,
  1519. 'Text stream failed to parse. Proceeding without it.');
  1520. }
  1521. this.mediaStates_.delete(ContentType.TEXT);
  1522. } else if (error.code == shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR) {
  1523. this.handleQuotaExceeded_(mediaState, error);
  1524. } else {
  1525. shaka.log.error(logPrefix, 'failed fetch and append: code=' +
  1526. error.code);
  1527. mediaState.hasError = true;
  1528. if (error.category == shaka.util.Error.Category.NETWORK &&
  1529. mediaState.segmentPrefetch) {
  1530. mediaState.segmentPrefetch.removeReference(reference);
  1531. }
  1532. error.severity = shaka.util.Error.Severity.CRITICAL;
  1533. await this.handleStreamingError_(mediaState, error);
  1534. }
  1535. }
  1536. }
  1537. /**
  1538. * @param {!BufferSource} rawResult
  1539. * @param {shaka.extern.aesKey} aesKey
  1540. * @param {number} position
  1541. * @return {!Promise.<!BufferSource>} finalResult
  1542. * @private
  1543. */
  1544. async aesDecrypt_(rawResult, aesKey, position) {
  1545. const key = aesKey;
  1546. if (!key.cryptoKey) {
  1547. goog.asserts.assert(key.fetchKey, 'If AES cryptoKey was not ' +
  1548. 'preloaded, fetchKey function should be provided');
  1549. await key.fetchKey();
  1550. goog.asserts.assert(key.cryptoKey, 'AES cryptoKey should now be set');
  1551. }
  1552. let iv = key.iv;
  1553. if (!iv) {
  1554. iv = shaka.util.BufferUtils.toUint8(new ArrayBuffer(16));
  1555. let sequence = key.firstMediaSequenceNumber + position;
  1556. for (let i = iv.byteLength - 1; i >= 0; i--) {
  1557. iv[i] = sequence & 0xff;
  1558. sequence >>= 8;
  1559. }
  1560. }
  1561. let algorithm;
  1562. if (aesKey.blockCipherMode == 'CBC') {
  1563. algorithm = {
  1564. name: 'AES-CBC',
  1565. iv,
  1566. };
  1567. } else {
  1568. algorithm = {
  1569. name: 'AES-CTR',
  1570. counter: iv,
  1571. // NIST SP800-38A standard suggests that the counter should occupy half
  1572. // of the counter block
  1573. length: 64,
  1574. };
  1575. }
  1576. return window.crypto.subtle.decrypt(algorithm, key.cryptoKey, rawResult);
  1577. }
  1578. /**
  1579. * Clear per-stream error states and retry any failed streams.
  1580. * @param {number} delaySeconds
  1581. * @return {boolean} False if unable to retry.
  1582. */
  1583. retry(delaySeconds) {
  1584. if (this.destroyer_.destroyed()) {
  1585. shaka.log.error('Unable to retry after StreamingEngine is destroyed!');
  1586. return false;
  1587. }
  1588. if (this.fatalError_) {
  1589. shaka.log.error('Unable to retry after StreamingEngine encountered a ' +
  1590. 'fatal error!');
  1591. return false;
  1592. }
  1593. for (const mediaState of this.mediaStates_.values()) {
  1594. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1595. // Only schedule an update if it has an error, but it's not mid-update
  1596. // and there is not already an update scheduled.
  1597. if (mediaState.hasError && !mediaState.performingUpdate &&
  1598. !mediaState.updateTimer) {
  1599. shaka.log.info(logPrefix, 'Retrying after failure...');
  1600. mediaState.hasError = false;
  1601. this.scheduleUpdate_(mediaState, delaySeconds);
  1602. }
  1603. }
  1604. return true;
  1605. }
  1606. /**
  1607. * Append the data to the remaining data.
  1608. * @param {!Uint8Array} remaining
  1609. * @param {!Uint8Array} data
  1610. * @return {!Uint8Array}
  1611. * @private
  1612. */
  1613. concatArray_(remaining, data) {
  1614. const result = new Uint8Array(remaining.length + data.length);
  1615. result.set(remaining);
  1616. result.set(data, remaining.length);
  1617. return result;
  1618. }
  1619. /**
  1620. * Handles a QUOTA_EXCEEDED_ERROR.
  1621. *
  1622. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1623. * @param {!shaka.util.Error} error
  1624. * @private
  1625. */
  1626. handleQuotaExceeded_(mediaState, error) {
  1627. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1628. // The segment cannot fit into the SourceBuffer. Ideally, MediaSource would
  1629. // have evicted old data to accommodate the segment; however, it may have
  1630. // failed to do this if the segment is very large, or if it could not find
  1631. // a suitable time range to remove.
  1632. //
  1633. // We can overcome the latter by trying to append the segment again;
  1634. // however, to avoid continuous QuotaExceededErrors we must reduce the size
  1635. // of the buffer going forward.
  1636. //
  1637. // If we've recently reduced the buffering goals, wait until the stream
  1638. // which caused the first QuotaExceededError recovers. Doing this ensures
  1639. // we don't reduce the buffering goals too quickly.
  1640. const mediaStates = Array.from(this.mediaStates_.values());
  1641. const waitingForAnotherStreamToRecover = mediaStates.some((ms) => {
  1642. return ms != mediaState && ms.recovering;
  1643. });
  1644. if (!waitingForAnotherStreamToRecover) {
  1645. if (this.config_.maxDisabledTime > 0) {
  1646. const handled = this.playerInterface_.disableStream(
  1647. mediaState.stream, this.config_.maxDisabledTime);
  1648. if (handled) {
  1649. return;
  1650. }
  1651. }
  1652. // Reduction schedule: 80%, 60%, 40%, 20%, 16%, 12%, 8%, 4%, fail.
  1653. // Note: percentages are used for comparisons to avoid rounding errors.
  1654. const percentBefore = Math.round(100 * this.bufferingGoalScale_);
  1655. if (percentBefore > 20) {
  1656. this.bufferingGoalScale_ -= 0.2;
  1657. } else if (percentBefore > 4) {
  1658. this.bufferingGoalScale_ -= 0.04;
  1659. } else {
  1660. shaka.log.error(
  1661. logPrefix, 'MediaSource threw QuotaExceededError too many times');
  1662. mediaState.hasError = true;
  1663. this.fatalError_ = true;
  1664. this.playerInterface_.onError(error);
  1665. return;
  1666. }
  1667. const percentAfter = Math.round(100 * this.bufferingGoalScale_);
  1668. shaka.log.warning(
  1669. logPrefix,
  1670. 'MediaSource threw QuotaExceededError:',
  1671. 'reducing buffering goals by ' + (100 - percentAfter) + '%');
  1672. mediaState.recovering = true;
  1673. } else {
  1674. shaka.log.debug(
  1675. logPrefix,
  1676. 'MediaSource threw QuotaExceededError:',
  1677. 'waiting for another stream to recover...');
  1678. }
  1679. // QuotaExceededError gets thrown if eviction didn't help to make room
  1680. // for a segment. We want to wait for a while (4 seconds is just an
  1681. // arbitrary number) before updating to give the playhead a chance to
  1682. // advance, so we don't immediately throw again.
  1683. this.scheduleUpdate_(mediaState, 4);
  1684. }
  1685. /**
  1686. * Sets the given MediaState's associated SourceBuffer's timestamp offset,
  1687. * append window, and init segment if they have changed. If an error occurs
  1688. * then neither the timestamp offset or init segment are unset, since another
  1689. * call to switch() will end up superseding them.
  1690. *
  1691. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  1692. * @param {!shaka.media.SegmentReference} reference
  1693. * @return {!Promise}
  1694. * @private
  1695. */
  1696. async initSourceBuffer_(mediaState, reference) {
  1697. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1698. const MimeUtils = shaka.util.MimeUtils;
  1699. const StreamingEngine = shaka.media.StreamingEngine;
  1700. const logPrefix = StreamingEngine.logPrefix_(mediaState);
  1701. /** @type {!Array.<!Promise>} */
  1702. const operations = [];
  1703. // Rounding issues can cause us to remove the first frame of a Period, so
  1704. // reduce the window start time slightly.
  1705. const appendWindowStart = Math.max(0,
  1706. Math.max(reference.appendWindowStart, this.playRangeStart_) -
  1707. StreamingEngine.APPEND_WINDOW_START_FUDGE_);
  1708. const appendWindowEnd =
  1709. Math.min(reference.appendWindowEnd, this.playRangeEnd_) +
  1710. StreamingEngine.APPEND_WINDOW_END_FUDGE_;
  1711. goog.asserts.assert(
  1712. reference.startTime <= appendWindowEnd,
  1713. logPrefix + ' segment should start before append window end');
  1714. const codecs = MimeUtils.getCodecBase(mediaState.stream.codecs);
  1715. const mimeType = MimeUtils.getBasicType(mediaState.stream.mimeType);
  1716. const timestampOffset = reference.timestampOffset;
  1717. if (timestampOffset != mediaState.lastTimestampOffset ||
  1718. appendWindowStart != mediaState.lastAppendWindowStart ||
  1719. appendWindowEnd != mediaState.lastAppendWindowEnd ||
  1720. codecs != mediaState.lastCodecs ||
  1721. mimeType != mediaState.lastMimeType) {
  1722. shaka.log.v1(logPrefix, 'setting timestamp offset to ' + timestampOffset);
  1723. shaka.log.v1(logPrefix,
  1724. 'setting append window start to ' + appendWindowStart);
  1725. shaka.log.v1(logPrefix,
  1726. 'setting append window end to ' + appendWindowEnd);
  1727. const isResetMediaSourceNecessary =
  1728. mediaState.lastCodecs && mediaState.lastMimeType &&
  1729. this.playerInterface_.mediaSourceEngine.isResetMediaSourceNecessary(
  1730. mediaState.type, mediaState.stream, mimeType, codecs);
  1731. if (isResetMediaSourceNecessary) {
  1732. let otherState = null;
  1733. if (mediaState.type === ContentType.VIDEO) {
  1734. otherState = this.mediaStates_.get(ContentType.AUDIO);
  1735. } else if (mediaState.type === ContentType.AUDIO) {
  1736. otherState = this.mediaStates_.get(ContentType.VIDEO);
  1737. }
  1738. if (otherState) {
  1739. // First, abort all operations in progress on the other stream.
  1740. await this.abortOperations_(otherState).catch(() => {});
  1741. // Then clear our cache of the last init segment, since MSE will be
  1742. // reloaded and no init segment will be there post-reload.
  1743. otherState.lastInitSegmentReference = null;
  1744. // Now force the existing buffer to be cleared. It is not necessary
  1745. // to perform the MSE clear operation, but this has the side-effect
  1746. // that our state for that stream will then match MSE's post-reload
  1747. // state.
  1748. this.forceClearBuffer_(otherState);
  1749. }
  1750. }
  1751. // Dispatching init asynchronously causes the sourceBuffers in
  1752. // the MediaSourceEngine to become detached do to race conditions
  1753. // with mediaSource and sourceBuffers being created simultaneously.
  1754. await this.setProperties_(mediaState, timestampOffset, appendWindowStart,
  1755. appendWindowEnd, reference, codecs, mimeType);
  1756. }
  1757. if (!shaka.media.InitSegmentReference.equal(
  1758. reference.initSegmentReference, mediaState.lastInitSegmentReference)) {
  1759. mediaState.lastInitSegmentReference = reference.initSegmentReference;
  1760. if (reference.isIndependent() && reference.initSegmentReference) {
  1761. shaka.log.v1(logPrefix, 'fetching init segment');
  1762. const fetchInit =
  1763. this.fetch_(mediaState, reference.initSegmentReference);
  1764. const append = async () => {
  1765. try {
  1766. const initSegment = await fetchInit;
  1767. this.destroyer_.ensureNotDestroyed();
  1768. let lastTimescale = null;
  1769. const timescaleMap = new Map();
  1770. /** @type {!shaka.extern.SpatialVideoInfo} */
  1771. const spatialVideoInfo = {
  1772. projection: null,
  1773. hfov: null,
  1774. };
  1775. const parser = new shaka.util.Mp4Parser();
  1776. const Mp4Parser = shaka.util.Mp4Parser;
  1777. const Mp4BoxParsers = shaka.util.Mp4BoxParsers;
  1778. parser.box('moov', Mp4Parser.children)
  1779. .box('trak', Mp4Parser.children)
  1780. .box('mdia', Mp4Parser.children)
  1781. .fullBox('mdhd', (box) => {
  1782. goog.asserts.assert(
  1783. box.version != null,
  1784. 'MDHD is a full box and should have a valid version.');
  1785. const parsedMDHDBox = Mp4BoxParsers.parseMDHD(
  1786. box.reader, box.version);
  1787. lastTimescale = parsedMDHDBox.timescale;
  1788. })
  1789. .box('hdlr', (box) => {
  1790. const parsedHDLR = Mp4BoxParsers.parseHDLR(box.reader);
  1791. switch (parsedHDLR.handlerType) {
  1792. case 'soun':
  1793. timescaleMap.set(ContentType.AUDIO, lastTimescale);
  1794. break;
  1795. case 'vide':
  1796. timescaleMap.set(ContentType.VIDEO, lastTimescale);
  1797. break;
  1798. }
  1799. lastTimescale = null;
  1800. })
  1801. .box('minf', Mp4Parser.children)
  1802. .box('stbl', Mp4Parser.children)
  1803. .fullBox('stsd', Mp4Parser.sampleDescription)
  1804. .box('encv', Mp4Parser.visualSampleEntry)
  1805. .box('avc1', Mp4Parser.visualSampleEntry)
  1806. .box('avc3', Mp4Parser.visualSampleEntry)
  1807. .box('hev1', Mp4Parser.visualSampleEntry)
  1808. .box('hvc1', Mp4Parser.visualSampleEntry)
  1809. .box('dvav', Mp4Parser.visualSampleEntry)
  1810. .box('dva1', Mp4Parser.visualSampleEntry)
  1811. .box('dvh1', Mp4Parser.visualSampleEntry)
  1812. .box('dvhe', Mp4Parser.visualSampleEntry)
  1813. .box('vexu', Mp4Parser.children)
  1814. .box('proj', Mp4Parser.children)
  1815. .fullBox('prji', (box) => {
  1816. const parsedPRJIBox = Mp4BoxParsers.parsePRJI(box.reader);
  1817. spatialVideoInfo.projection = parsedPRJIBox.projection;
  1818. })
  1819. .box('hfov', (box) => {
  1820. const parsedHFOVBox = Mp4BoxParsers.parseHFOV(box.reader);
  1821. spatialVideoInfo.hfov = parsedHFOVBox.hfov;
  1822. })
  1823. .parse(initSegment);
  1824. this.updateSpatialVideoInfo_(spatialVideoInfo);
  1825. if (timescaleMap.has(mediaState.type)) {
  1826. reference.initSegmentReference.timescale =
  1827. timescaleMap.get(mediaState.type);
  1828. } else if (lastTimescale != null) {
  1829. // Fallback for segments without HDLR box
  1830. reference.initSegmentReference.timescale = lastTimescale;
  1831. }
  1832. shaka.log.v1(logPrefix, 'appending init segment');
  1833. const hasClosedCaptions = mediaState.stream.closedCaptions &&
  1834. mediaState.stream.closedCaptions.size > 0;
  1835. await this.playerInterface_.beforeAppendSegment(
  1836. mediaState.type, initSegment);
  1837. await this.playerInterface_.mediaSourceEngine.appendBuffer(
  1838. mediaState.type, initSegment, /* reference= */ null,
  1839. mediaState.stream, hasClosedCaptions);
  1840. } catch (error) {
  1841. mediaState.lastInitSegmentReference = null;
  1842. throw error;
  1843. }
  1844. };
  1845. this.playerInterface_.onInitSegmentAppended(
  1846. reference.startTime, reference.initSegmentReference);
  1847. operations.push(append());
  1848. }
  1849. }
  1850. if (this.manifest_.sequenceMode) {
  1851. const lastDiscontinuitySequence =
  1852. mediaState.lastSegmentReference ?
  1853. mediaState.lastSegmentReference.discontinuitySequence : null;
  1854. // Across discontinuity bounds, we should resync timestamps for
  1855. // sequence mode playbacks. The next segment appended should
  1856. // land at its theoretical timestamp from the segment index.
  1857. if (reference.discontinuitySequence != lastDiscontinuitySequence) {
  1858. operations.push(this.playerInterface_.mediaSourceEngine.resync(
  1859. mediaState.type, reference.startTime));
  1860. }
  1861. }
  1862. await Promise.all(operations);
  1863. }
  1864. /**
  1865. *
  1866. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  1867. * @param {number} timestampOffset
  1868. * @param {number} appendWindowStart
  1869. * @param {number} appendWindowEnd
  1870. * @param {!shaka.media.SegmentReference} reference
  1871. * @param {?string=} codecs
  1872. * @param {?string=} mimeType
  1873. * @private
  1874. */
  1875. async setProperties_(mediaState, timestampOffset, appendWindowStart,
  1876. appendWindowEnd, reference, codecs, mimeType) {
  1877. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1878. /**
  1879. * @type {!Map.<shaka.util.ManifestParserUtils.ContentType,
  1880. * shaka.extern.Stream>}
  1881. */
  1882. const streamsByType = new Map();
  1883. if (this.currentVariant_.audio) {
  1884. streamsByType.set(ContentType.AUDIO, this.currentVariant_.audio);
  1885. }
  1886. if (this.currentVariant_.video) {
  1887. streamsByType.set(ContentType.VIDEO, this.currentVariant_.video);
  1888. }
  1889. try {
  1890. mediaState.lastAppendWindowStart = appendWindowStart;
  1891. mediaState.lastAppendWindowEnd = appendWindowEnd;
  1892. if (codecs) {
  1893. mediaState.lastCodecs = codecs;
  1894. }
  1895. if (mimeType) {
  1896. mediaState.lastMimeType = mimeType;
  1897. }
  1898. mediaState.lastTimestampOffset = timestampOffset;
  1899. const ignoreTimestampOffset = this.manifest_.sequenceMode ||
  1900. this.manifest_.type == shaka.media.ManifestParser.HLS;
  1901. await this.playerInterface_.mediaSourceEngine.setStreamProperties(
  1902. mediaState.type, timestampOffset, appendWindowStart,
  1903. appendWindowEnd, ignoreTimestampOffset,
  1904. reference.mimeType || mediaState.stream.mimeType,
  1905. reference.codecs || mediaState.stream.codecs, streamsByType);
  1906. } catch (error) {
  1907. mediaState.lastAppendWindowStart = null;
  1908. mediaState.lastAppendWindowEnd = null;
  1909. mediaState.lastCodecs = null;
  1910. mediaState.lastMimeType = null;
  1911. mediaState.lastTimestampOffset = null;
  1912. throw error;
  1913. }
  1914. }
  1915. /**
  1916. * Appends the given segment and evicts content if required to append.
  1917. *
  1918. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  1919. * @param {number} presentationTime
  1920. * @param {shaka.extern.Stream} stream
  1921. * @param {!shaka.media.SegmentReference} reference
  1922. * @param {BufferSource} segment
  1923. * @param {boolean=} isChunkedData
  1924. * @return {!Promise}
  1925. * @private
  1926. */
  1927. async append_(mediaState, presentationTime, stream, reference, segment,
  1928. isChunkedData = false) {
  1929. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  1930. const hasClosedCaptions = stream.closedCaptions &&
  1931. stream.closedCaptions.size > 0;
  1932. let parser;
  1933. const hasEmsg = ((stream.emsgSchemeIdUris != null &&
  1934. stream.emsgSchemeIdUris.length > 0) ||
  1935. this.config_.dispatchAllEmsgBoxes);
  1936. const shouldParsePrftBox =
  1937. (this.config_.parsePrftBox && !this.parsedPrftEventRaised_);
  1938. const isMP4 = stream.mimeType == 'video/mp4' ||
  1939. stream.mimeType == 'audio/mp4';
  1940. let timescale = null;
  1941. if (reference.initSegmentReference) {
  1942. timescale = reference.initSegmentReference.timescale;
  1943. }
  1944. const shouldFixTimestampOffset = isMP4 && timescale &&
  1945. stream.type === shaka.util.ManifestParserUtils.ContentType.VIDEO &&
  1946. this.manifest_.type == shaka.media.ManifestParser.DASH &&
  1947. this.config_.shouldFixTimestampOffset;
  1948. if (hasEmsg || shouldParsePrftBox || shouldFixTimestampOffset) {
  1949. parser = new shaka.util.Mp4Parser();
  1950. }
  1951. if (hasEmsg) {
  1952. parser
  1953. .fullBox(
  1954. 'emsg',
  1955. (box) => this.parseEMSG_(
  1956. reference, stream.emsgSchemeIdUris, box));
  1957. }
  1958. if (shouldParsePrftBox) {
  1959. parser
  1960. .fullBox(
  1961. 'prft',
  1962. (box) => this.parsePrft_(
  1963. reference, box));
  1964. }
  1965. if (shouldFixTimestampOffset) {
  1966. parser
  1967. .box('moof', shaka.util.Mp4Parser.children)
  1968. .box('traf', shaka.util.Mp4Parser.children)
  1969. .fullBox('tfdt', async (box) => {
  1970. goog.asserts.assert(
  1971. box.version != null,
  1972. 'TFDT is a full box and should have a valid version.');
  1973. const parsedTFDT = shaka.util.Mp4BoxParsers.parseTFDTInaccurate(
  1974. box.reader, box.version);
  1975. const baseMediaDecodeTime = parsedTFDT.baseMediaDecodeTime;
  1976. // In case the time is 0, it is not updated
  1977. if (!baseMediaDecodeTime) {
  1978. return;
  1979. }
  1980. goog.asserts.assert(typeof(timescale) == 'number',
  1981. 'Should be an number!');
  1982. const scaledMediaDecodeTime = -baseMediaDecodeTime / timescale;
  1983. const comparison1 = Number(mediaState.lastTimestampOffset) || 0;
  1984. if (comparison1 < scaledMediaDecodeTime) {
  1985. const lastAppendWindowStart = mediaState.lastAppendWindowStart;
  1986. const lastAppendWindowEnd = mediaState.lastAppendWindowEnd;
  1987. goog.asserts.assert(typeof(lastAppendWindowStart) == 'number',
  1988. 'Should be an number!');
  1989. goog.asserts.assert(typeof(lastAppendWindowEnd) == 'number',
  1990. 'Should be an number!');
  1991. await this.setProperties_(mediaState, scaledMediaDecodeTime,
  1992. lastAppendWindowStart, lastAppendWindowEnd, reference);
  1993. }
  1994. });
  1995. }
  1996. if (hasEmsg || shouldParsePrftBox || shouldFixTimestampOffset) {
  1997. parser.parse(segment, /* partialOkay= */ false, isChunkedData);
  1998. }
  1999. await this.evict_(mediaState, presentationTime);
  2000. this.destroyer_.ensureNotDestroyed();
  2001. // 'seeked' or 'adaptation' triggered logic applies only to this
  2002. // appendBuffer() call.
  2003. const seeked = mediaState.seeked;
  2004. mediaState.seeked = false;
  2005. const adaptation = mediaState.adaptation;
  2006. mediaState.adaptation = false;
  2007. await this.playerInterface_.beforeAppendSegment(mediaState.type, segment);
  2008. await this.playerInterface_.mediaSourceEngine.appendBuffer(
  2009. mediaState.type,
  2010. segment,
  2011. reference,
  2012. stream,
  2013. hasClosedCaptions,
  2014. seeked,
  2015. adaptation,
  2016. isChunkedData);
  2017. this.destroyer_.ensureNotDestroyed();
  2018. shaka.log.v2(logPrefix, 'appended media segment');
  2019. }
  2020. /**
  2021. * Parse the EMSG box from a MP4 container.
  2022. *
  2023. * @param {!shaka.media.SegmentReference} reference
  2024. * @param {?Array.<string>} emsgSchemeIdUris Array of emsg
  2025. * scheme_id_uri for which emsg boxes should be parsed.
  2026. * @param {!shaka.extern.ParsedBox} box
  2027. * @private
  2028. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  2029. * aligned(8) class DASHEventMessageBox
  2030. * extends FullBox(‘emsg’, version, flags = 0){
  2031. * if (version==0) {
  2032. * string scheme_id_uri;
  2033. * string value;
  2034. * unsigned int(32) timescale;
  2035. * unsigned int(32) presentation_time_delta;
  2036. * unsigned int(32) event_duration;
  2037. * unsigned int(32) id;
  2038. * } else if (version==1) {
  2039. * unsigned int(32) timescale;
  2040. * unsigned int(64) presentation_time;
  2041. * unsigned int(32) event_duration;
  2042. * unsigned int(32) id;
  2043. * string scheme_id_uri;
  2044. * string value;
  2045. * }
  2046. * unsigned int(8) message_data[];
  2047. */
  2048. parseEMSG_(reference, emsgSchemeIdUris, box) {
  2049. let timescale;
  2050. let id;
  2051. let eventDuration;
  2052. let schemeId;
  2053. let startTime;
  2054. let presentationTimeDelta;
  2055. let value;
  2056. if (box.version === 0) {
  2057. schemeId = box.reader.readTerminatedString();
  2058. value = box.reader.readTerminatedString();
  2059. timescale = box.reader.readUint32();
  2060. presentationTimeDelta = box.reader.readUint32();
  2061. eventDuration = box.reader.readUint32();
  2062. id = box.reader.readUint32();
  2063. startTime = reference.startTime + (presentationTimeDelta / timescale);
  2064. } else {
  2065. timescale = box.reader.readUint32();
  2066. const pts = box.reader.readUint64();
  2067. startTime = (pts / timescale) + reference.timestampOffset;
  2068. presentationTimeDelta = startTime - reference.startTime;
  2069. eventDuration = box.reader.readUint32();
  2070. id = box.reader.readUint32();
  2071. schemeId = box.reader.readTerminatedString();
  2072. value = box.reader.readTerminatedString();
  2073. }
  2074. const messageData = box.reader.readBytes(
  2075. box.reader.getLength() - box.reader.getPosition());
  2076. // See DASH sec. 5.10.3.3.1
  2077. // If a DASH client detects an event message box with a scheme that is not
  2078. // defined in MPD, the client is expected to ignore it.
  2079. if ((emsgSchemeIdUris && emsgSchemeIdUris.includes(schemeId)) ||
  2080. this.config_.dispatchAllEmsgBoxes) {
  2081. // See DASH sec. 5.10.4.1
  2082. // A special scheme in DASH used to signal manifest updates.
  2083. if (schemeId == 'urn:mpeg:dash:event:2012') {
  2084. this.playerInterface_.onManifestUpdate();
  2085. } else {
  2086. // All other schemes are dispatched as a general 'emsg' event.
  2087. /** @type {shaka.extern.EmsgInfo} */
  2088. const emsg = {
  2089. startTime: startTime,
  2090. endTime: startTime + (eventDuration / timescale),
  2091. schemeIdUri: schemeId,
  2092. value: value,
  2093. timescale: timescale,
  2094. presentationTimeDelta: presentationTimeDelta,
  2095. eventDuration: eventDuration,
  2096. id: id,
  2097. messageData: messageData,
  2098. };
  2099. // Dispatch an event to notify the application about the emsg box.
  2100. const eventName = shaka.util.FakeEvent.EventName.Emsg;
  2101. const data = (new Map()).set('detail', emsg);
  2102. const event = new shaka.util.FakeEvent(eventName, data);
  2103. // A user can call preventDefault() on a cancelable event.
  2104. event.cancelable = true;
  2105. this.playerInterface_.onEvent(event);
  2106. if (event.defaultPrevented) {
  2107. // If the caller uses preventDefault() on the 'emsg' event, don't
  2108. // process any further, and don't generate an ID3 'metadata' event
  2109. // for the same data.
  2110. return;
  2111. }
  2112. // Additionally, ID3 events generate a 'metadata' event. This is a
  2113. // pre-parsed version of the metadata blob already dispatched in the
  2114. // 'emsg' event.
  2115. if (schemeId == 'https://aomedia.org/emsg/ID3' ||
  2116. schemeId == 'https://developer.apple.com/streaming/emsg-id3') {
  2117. // See https://aomediacodec.github.io/id3-emsg/
  2118. const frames = shaka.util.Id3Utils.getID3Frames(messageData);
  2119. if (frames.length && reference) {
  2120. /** @private {shaka.extern.ID3Metadata} */
  2121. const metadata = {
  2122. cueTime: reference.startTime,
  2123. data: messageData,
  2124. frames: frames,
  2125. dts: reference.startTime,
  2126. pts: reference.startTime,
  2127. };
  2128. this.playerInterface_.onMetadata(
  2129. [metadata], /* offset= */ 0, reference.endTime);
  2130. }
  2131. }
  2132. }
  2133. }
  2134. }
  2135. /**
  2136. * Parse PRFT box.
  2137. * @param {!shaka.media.SegmentReference} reference
  2138. * @param {!shaka.extern.ParsedBox} box
  2139. * @private
  2140. */
  2141. parsePrft_(reference, box) {
  2142. if (this.parsedPrftEventRaised_ ||
  2143. !reference.initSegmentReference.timescale) {
  2144. return;
  2145. }
  2146. goog.asserts.assert(
  2147. box.version == 0 || box.version == 1,
  2148. 'PRFT version can only be 0 or 1');
  2149. const parsed = shaka.util.Mp4BoxParsers.parsePRFTInaccurate(
  2150. box.reader, box.version);
  2151. const timescale = reference.initSegmentReference.timescale;
  2152. const wallClockTime = this.convertNtp(parsed.ntpTimestamp);
  2153. const programStartDate = new Date(wallClockTime -
  2154. (parsed.mediaTime / timescale) * 1000);
  2155. const prftInfo = {
  2156. wallClockTime,
  2157. programStartDate,
  2158. };
  2159. const eventName = shaka.util.FakeEvent.EventName.Prft;
  2160. const data = (new Map()).set('detail', prftInfo);
  2161. const event = new shaka.util.FakeEvent(
  2162. eventName, data);
  2163. this.playerInterface_.onEvent(event);
  2164. this.parsedPrftEventRaised_ = true;
  2165. }
  2166. /**
  2167. * Convert Ntp ntpTimeStamp to UTC Time
  2168. *
  2169. * @param {number} ntpTimeStamp
  2170. * @return {number} utcTime
  2171. */
  2172. convertNtp(ntpTimeStamp) {
  2173. const start = new Date(Date.UTC(1900, 0, 1, 0, 0, 0));
  2174. return new Date(start.getTime() + ntpTimeStamp).getTime();
  2175. }
  2176. /**
  2177. * Evicts media to meet the max buffer behind limit.
  2178. *
  2179. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2180. * @param {number} presentationTime
  2181. * @private
  2182. */
  2183. async evict_(mediaState, presentationTime) {
  2184. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2185. shaka.log.v2(logPrefix, 'checking buffer length');
  2186. // Use the max segment duration, if it is longer than the bufferBehind, to
  2187. // avoid accidentally clearing too much data when dealing with a manifest
  2188. // with a long keyframe interval.
  2189. const bufferBehind = Math.max(this.config_.bufferBehind,
  2190. this.manifest_.presentationTimeline.getMaxSegmentDuration());
  2191. const startTime =
  2192. this.playerInterface_.mediaSourceEngine.bufferStart(mediaState.type);
  2193. if (startTime == null) {
  2194. shaka.log.v2(logPrefix,
  2195. 'buffer behind okay because nothing buffered:',
  2196. 'presentationTime=' + presentationTime,
  2197. 'bufferBehind=' + bufferBehind);
  2198. return;
  2199. }
  2200. const bufferedBehind = presentationTime - startTime;
  2201. const overflow = bufferedBehind - bufferBehind;
  2202. // See: https://github.com/shaka-project/shaka-player/issues/6240
  2203. if (overflow <= this.config_.evictionGoal) {
  2204. shaka.log.v2(logPrefix,
  2205. 'buffer behind okay:',
  2206. 'presentationTime=' + presentationTime,
  2207. 'bufferedBehind=' + bufferedBehind,
  2208. 'bufferBehind=' + bufferBehind,
  2209. 'evictionGoal=' + this.config_.evictionGoal,
  2210. 'underflow=' + Math.abs(overflow));
  2211. return;
  2212. }
  2213. shaka.log.v1(logPrefix,
  2214. 'buffer behind too large:',
  2215. 'presentationTime=' + presentationTime,
  2216. 'bufferedBehind=' + bufferedBehind,
  2217. 'bufferBehind=' + bufferBehind,
  2218. 'evictionGoal=' + this.config_.evictionGoal,
  2219. 'overflow=' + overflow);
  2220. await this.playerInterface_.mediaSourceEngine.remove(mediaState.type,
  2221. startTime, startTime + overflow);
  2222. this.destroyer_.ensureNotDestroyed();
  2223. shaka.log.v1(logPrefix, 'evicted ' + overflow + ' seconds');
  2224. }
  2225. /**
  2226. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2227. * @return {boolean}
  2228. * @private
  2229. */
  2230. static isEmbeddedText_(mediaState) {
  2231. const MimeUtils = shaka.util.MimeUtils;
  2232. const CEA608_MIME = MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE;
  2233. const CEA708_MIME = MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE;
  2234. return mediaState &&
  2235. mediaState.type == shaka.util.ManifestParserUtils.ContentType.TEXT &&
  2236. (mediaState.stream.mimeType == CEA608_MIME ||
  2237. mediaState.stream.mimeType == CEA708_MIME);
  2238. }
  2239. /**
  2240. * Fetches the given segment.
  2241. *
  2242. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2243. * @param {(!shaka.media.InitSegmentReference|!shaka.media.SegmentReference)}
  2244. * reference
  2245. * @param {?function(BufferSource):!Promise=} streamDataCallback
  2246. *
  2247. * @return {!Promise.<BufferSource>}
  2248. * @private
  2249. */
  2250. async fetch_(mediaState, reference, streamDataCallback) {
  2251. const segmentData = reference.getSegmentData();
  2252. if (segmentData) {
  2253. return segmentData;
  2254. }
  2255. let op = null;
  2256. if (mediaState.segmentPrefetch) {
  2257. op = mediaState.segmentPrefetch.getPrefetchedSegment(
  2258. reference, streamDataCallback);
  2259. }
  2260. if (!op) {
  2261. op = this.dispatchFetch_(
  2262. reference, mediaState.stream, streamDataCallback);
  2263. }
  2264. let position = 0;
  2265. if (mediaState.segmentIterator) {
  2266. position = mediaState.segmentIterator.currentPosition();
  2267. }
  2268. mediaState.operation = op;
  2269. const response = await op.promise;
  2270. mediaState.operation = null;
  2271. let result = response.data;
  2272. if (reference.aesKey) {
  2273. result = await this.aesDecrypt_(result, reference.aesKey, position);
  2274. }
  2275. return result;
  2276. }
  2277. /**
  2278. * Fetches the given segment.
  2279. *
  2280. * @param {!shaka.extern.Stream} stream
  2281. * @param {(!shaka.media.InitSegmentReference|!shaka.media.SegmentReference)}
  2282. * reference
  2283. * @param {?function(BufferSource):!Promise=} streamDataCallback
  2284. *
  2285. * @return {!shaka.net.NetworkingEngine.PendingRequest}
  2286. * @private
  2287. */
  2288. dispatchFetch_(reference, stream, streamDataCallback) {
  2289. goog.asserts.assert(
  2290. this.playerInterface_.netEngine, 'Must have net engine');
  2291. return shaka.media.StreamingEngine.dispatchFetch(
  2292. reference, stream, streamDataCallback || null,
  2293. this.config_.retryParameters, this.playerInterface_.netEngine);
  2294. }
  2295. /**
  2296. * Fetches the given segment.
  2297. *
  2298. * @param {!shaka.extern.Stream} stream
  2299. * @param {(!shaka.media.InitSegmentReference|!shaka.media.SegmentReference)}
  2300. * reference
  2301. * @param {?function(BufferSource):!Promise} streamDataCallback
  2302. * @param {shaka.extern.RetryParameters} retryParameters
  2303. * @param {!shaka.net.NetworkingEngine} netEngine
  2304. *
  2305. * @return {!shaka.net.NetworkingEngine.PendingRequest}
  2306. */
  2307. static dispatchFetch(
  2308. reference, stream, streamDataCallback, retryParameters, netEngine) {
  2309. const requestType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  2310. const segment = reference instanceof shaka.media.SegmentReference ?
  2311. reference : undefined;
  2312. const type = segment ?
  2313. shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT :
  2314. shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT;
  2315. const request = shaka.util.Networking.createSegmentRequest(
  2316. reference.getUris(),
  2317. reference.startByte,
  2318. reference.endByte,
  2319. retryParameters,
  2320. streamDataCallback);
  2321. request.contentType = stream.type;
  2322. shaka.log.v2('fetching: reference=', reference);
  2323. return netEngine.request(requestType, request, {type, stream, segment});
  2324. }
  2325. /**
  2326. * Clears the buffer and schedules another update.
  2327. * The optional parameter safeMargin allows to retain a certain amount
  2328. * of buffer, which can help avoiding rebuffering events.
  2329. * The value of the safe margin should be provided by the ABR manager.
  2330. *
  2331. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2332. * @param {boolean} flush
  2333. * @param {number} safeMargin
  2334. * @private
  2335. */
  2336. async clearBuffer_(mediaState, flush, safeMargin) {
  2337. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2338. goog.asserts.assert(
  2339. !mediaState.performingUpdate && (mediaState.updateTimer == null),
  2340. logPrefix + ' unexpected call to clearBuffer_()');
  2341. mediaState.waitingToClearBuffer = false;
  2342. mediaState.waitingToFlushBuffer = false;
  2343. mediaState.clearBufferSafeMargin = 0;
  2344. mediaState.clearingBuffer = true;
  2345. mediaState.lastSegmentReference = null;
  2346. mediaState.segmentIterator = null;
  2347. shaka.log.debug(logPrefix, 'clearing buffer');
  2348. if (mediaState.segmentPrefetch &&
  2349. !this.audioPrefetchMap_.has(mediaState.stream)) {
  2350. mediaState.segmentPrefetch.clearAll();
  2351. }
  2352. if (safeMargin) {
  2353. const presentationTime = this.playerInterface_.getPresentationTime();
  2354. const duration = this.playerInterface_.mediaSourceEngine.getDuration();
  2355. await this.playerInterface_.mediaSourceEngine.remove(
  2356. mediaState.type, presentationTime + safeMargin, duration);
  2357. } else {
  2358. await this.playerInterface_.mediaSourceEngine.clear(mediaState.type);
  2359. this.destroyer_.ensureNotDestroyed();
  2360. if (flush) {
  2361. await this.playerInterface_.mediaSourceEngine.flush(
  2362. mediaState.type);
  2363. }
  2364. }
  2365. this.destroyer_.ensureNotDestroyed();
  2366. shaka.log.debug(logPrefix, 'cleared buffer');
  2367. mediaState.clearingBuffer = false;
  2368. mediaState.endOfStream = false;
  2369. // Since the clear operation was async, check to make sure we're not doing
  2370. // another update and we don't have one scheduled yet.
  2371. if (!mediaState.performingUpdate && !mediaState.updateTimer) {
  2372. this.scheduleUpdate_(mediaState, 0);
  2373. }
  2374. }
  2375. /**
  2376. * Schedules |mediaState|'s next update.
  2377. *
  2378. * @param {!shaka.media.StreamingEngine.MediaState_} mediaState
  2379. * @param {number} delay The delay in seconds.
  2380. * @private
  2381. */
  2382. scheduleUpdate_(mediaState, delay) {
  2383. const logPrefix = shaka.media.StreamingEngine.logPrefix_(mediaState);
  2384. // If the text's update is canceled and its mediaState is deleted, stop
  2385. // scheduling another update.
  2386. const type = mediaState.type;
  2387. if (type == shaka.util.ManifestParserUtils.ContentType.TEXT &&
  2388. !this.mediaStates_.has(type)) {
  2389. shaka.log.v1(logPrefix, 'Text stream is unloaded. No update is needed.');
  2390. return;
  2391. }
  2392. shaka.log.v2(logPrefix, 'updating in ' + delay + ' seconds');
  2393. goog.asserts.assert(mediaState.updateTimer == null,
  2394. logPrefix + ' did not expect update to be scheduled');
  2395. mediaState.updateTimer = new shaka.util.DelayedTick(async () => {
  2396. try {
  2397. await this.onUpdate_(mediaState);
  2398. } catch (error) {
  2399. if (this.playerInterface_) {
  2400. this.playerInterface_.onError(error);
  2401. }
  2402. }
  2403. }).tickAfter(delay);
  2404. }
  2405. /**
  2406. * If |mediaState| is scheduled to update, stop it.
  2407. *
  2408. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2409. * @private
  2410. */
  2411. cancelUpdate_(mediaState) {
  2412. if (mediaState.updateTimer == null) {
  2413. return;
  2414. }
  2415. mediaState.updateTimer.stop();
  2416. mediaState.updateTimer = null;
  2417. }
  2418. /**
  2419. * If |mediaState| holds any in-progress operations, abort them.
  2420. *
  2421. * @return {!Promise}
  2422. * @private
  2423. */
  2424. async abortOperations_(mediaState) {
  2425. if (mediaState.operation) {
  2426. await mediaState.operation.abort();
  2427. }
  2428. }
  2429. /**
  2430. * Handle streaming errors by delaying, then notifying the application by
  2431. * error callback and by streaming failure callback.
  2432. *
  2433. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2434. * @param {!shaka.util.Error} error
  2435. * @return {!Promise}
  2436. * @private
  2437. */
  2438. async handleStreamingError_(mediaState, error) {
  2439. // If we invoke the callback right away, the application could trigger a
  2440. // rapid retry cycle that could be very unkind to the server. Instead,
  2441. // use the backoff system to delay and backoff the error handling.
  2442. await this.failureCallbackBackoff_.attempt();
  2443. this.destroyer_.ensureNotDestroyed();
  2444. const maxDisabledTime = this.getDisabledTime_(error);
  2445. // Try to recover from network errors
  2446. if (error.category === shaka.util.Error.Category.NETWORK &&
  2447. maxDisabledTime > 0) {
  2448. error.handled = this.playerInterface_.disableStream(
  2449. mediaState.stream, maxDisabledTime);
  2450. // Decrease the error severity to recoverable
  2451. if (error.handled) {
  2452. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  2453. }
  2454. }
  2455. // First fire an error event.
  2456. if (!error.handled ||
  2457. error.code != shaka.util.Error.Code.SEGMENT_MISSING) {
  2458. this.playerInterface_.onError(error);
  2459. }
  2460. // If the error was not handled by the application, call the failure
  2461. // callback.
  2462. if (!error.handled) {
  2463. this.config_.failureCallback(error);
  2464. }
  2465. }
  2466. /**
  2467. * @param {!shaka.util.Error} error
  2468. * @private
  2469. */
  2470. getDisabledTime_(error) {
  2471. if (this.config_.maxDisabledTime === 0 &&
  2472. error.code == shaka.util.Error.Code.SEGMENT_MISSING) {
  2473. // Spec: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.3
  2474. // The client SHOULD NOT attempt to load Media Segments that have been
  2475. // marked with an EXT-X-GAP tag, or to load Partial Segments with a
  2476. // GAP=YES attribute. Instead, clients are encouraged to look for
  2477. // another Variant Stream of the same Rendition which does not have the
  2478. // same gap, and play that instead.
  2479. return 1;
  2480. }
  2481. return this.config_.maxDisabledTime;
  2482. }
  2483. /**
  2484. * Reset Media Source
  2485. *
  2486. * @return {!Promise.<boolean>}
  2487. */
  2488. async resetMediaSource() {
  2489. const now = (Date.now() / 1000);
  2490. const minTimeBetweenRecoveries = this.config_.minTimeBetweenRecoveries;
  2491. if (!this.config_.allowMediaSourceRecoveries ||
  2492. (now - this.lastMediaSourceReset_) < minTimeBetweenRecoveries) {
  2493. return false;
  2494. }
  2495. this.lastMediaSourceReset_ = now;
  2496. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2497. const audioMediaState = this.mediaStates_.get(ContentType.AUDIO);
  2498. if (audioMediaState) {
  2499. audioMediaState.lastInitSegmentReference = null;
  2500. this.forceClearBuffer_(audioMediaState);
  2501. this.abortOperations_(audioMediaState).catch(() => {});
  2502. }
  2503. const videoMediaState = this.mediaStates_.get(ContentType.VIDEO);
  2504. if (videoMediaState) {
  2505. videoMediaState.lastInitSegmentReference = null;
  2506. this.forceClearBuffer_(videoMediaState);
  2507. this.abortOperations_(videoMediaState).catch(() => {});
  2508. }
  2509. /**
  2510. * @type {!Map.<shaka.util.ManifestParserUtils.ContentType,
  2511. * shaka.extern.Stream>}
  2512. */
  2513. const streamsByType = new Map();
  2514. if (this.currentVariant_.audio) {
  2515. streamsByType.set(ContentType.AUDIO, this.currentVariant_.audio);
  2516. }
  2517. if (this.currentVariant_.video) {
  2518. streamsByType.set(ContentType.VIDEO, this.currentVariant_.video);
  2519. }
  2520. await this.playerInterface_.mediaSourceEngine.reset(streamsByType);
  2521. return true;
  2522. }
  2523. /**
  2524. * Update the spatial video info and notify to the app.
  2525. *
  2526. * @param {shaka.extern.SpatialVideoInfo} info
  2527. * @private
  2528. */
  2529. updateSpatialVideoInfo_(info) {
  2530. if (this.spatialVideoInfo_.projection != info.projection ||
  2531. this.spatialVideoInfo_.hfov != info.hfov) {
  2532. const EventName = shaka.util.FakeEvent.EventName;
  2533. let event;
  2534. if (info.projection != null || info.hfov != null) {
  2535. const eventName = EventName.SpatialVideoInfoEvent;
  2536. const data = (new Map()).set('detail', info);
  2537. event = new shaka.util.FakeEvent(eventName, data);
  2538. } else {
  2539. const eventName = EventName.NoSpatialVideoInfoEvent;
  2540. event = new shaka.util.FakeEvent(eventName);
  2541. }
  2542. event.cancelable = true;
  2543. this.playerInterface_.onEvent(event);
  2544. this.spatialVideoInfo_ = info;
  2545. }
  2546. }
  2547. /**
  2548. * Update the segment iterator direction.
  2549. *
  2550. * @private
  2551. */
  2552. updateSegmentIteratorReverse_() {
  2553. const reverse = this.playerInterface_.getPlaybackRate() < 0;
  2554. for (const mediaState of this.mediaStates_.values()) {
  2555. if (mediaState.segmentIterator) {
  2556. mediaState.segmentIterator.setReverse(reverse);
  2557. }
  2558. if (mediaState.segmentPrefetch) {
  2559. mediaState.segmentPrefetch.setReverse(reverse);
  2560. }
  2561. }
  2562. for (const prefetch of this.audioPrefetchMap_.values()) {
  2563. prefetch.setReverse(reverse);
  2564. }
  2565. }
  2566. /**
  2567. * @param {shaka.media.StreamingEngine.MediaState_} mediaState
  2568. * @return {string} A log prefix of the form ($CONTENT_TYPE:$STREAM_ID), e.g.,
  2569. * "(audio:5)" or "(video:hd)".
  2570. * @private
  2571. */
  2572. static logPrefix_(mediaState) {
  2573. return '(' + mediaState.type + ':' + mediaState.stream.id + ')';
  2574. }
  2575. };
  2576. /**
  2577. * @typedef {{
  2578. * getPresentationTime: function():number,
  2579. * getBandwidthEstimate: function():number,
  2580. * getPlaybackRate: function():number,
  2581. * mediaSourceEngine: !shaka.media.MediaSourceEngine,
  2582. * netEngine: shaka.net.NetworkingEngine,
  2583. * onError: function(!shaka.util.Error),
  2584. * onEvent: function(!Event),
  2585. * onManifestUpdate: function(),
  2586. * onSegmentAppended: function(!shaka.media.SegmentReference,
  2587. * !shaka.extern.Stream),
  2588. * onInitSegmentAppended: function(!number,!shaka.media.InitSegmentReference),
  2589. * beforeAppendSegment: function(
  2590. * shaka.util.ManifestParserUtils.ContentType,!BufferSource):Promise,
  2591. * onMetadata: !function(!Array.<shaka.extern.ID3Metadata>, number, ?number),
  2592. * disableStream: function(!shaka.extern.Stream, number):boolean
  2593. * }}
  2594. *
  2595. * @property {function():number} getPresentationTime
  2596. * Get the position in the presentation (in seconds) of the content that the
  2597. * viewer is seeing on screen right now.
  2598. * @property {function():number} getBandwidthEstimate
  2599. * Get the estimated bandwidth in bits per second.
  2600. * @property {function():number} getPlaybackRate
  2601. * Get the playback rate
  2602. * @property {!shaka.media.MediaSourceEngine} mediaSourceEngine
  2603. * The MediaSourceEngine. The caller retains ownership.
  2604. * @property {shaka.net.NetworkingEngine} netEngine
  2605. * The NetworkingEngine instance to use. The caller retains ownership.
  2606. * @property {function(!shaka.util.Error)} onError
  2607. * Called when an error occurs. If the error is recoverable (see
  2608. * {@link shaka.util.Error}) then the caller may invoke either
  2609. * StreamingEngine.switch*() or StreamingEngine.seeked() to attempt recovery.
  2610. * @property {function(!Event)} onEvent
  2611. * Called when an event occurs that should be sent to the app.
  2612. * @property {function()} onManifestUpdate
  2613. * Called when an embedded 'emsg' box should trigger a manifest update.
  2614. * @property {function(!shaka.media.SegmentReference,
  2615. * !shaka.extern.Stream)} onSegmentAppended
  2616. * Called after a segment is successfully appended to a MediaSource.
  2617. * @property
  2618. * {function(!number, !shaka.media.InitSegmentReference)} onInitSegmentAppended
  2619. * Called when an init segment is appended to a MediaSource.
  2620. * @property {!function(shaka.util.ManifestParserUtils.ContentType,
  2621. * !BufferSource):Promise} beforeAppendSegment
  2622. * A function called just before appending to the source buffer.
  2623. * @property
  2624. * {!function(!Array.<shaka.extern.ID3Metadata>, number, ?number)} onMetadata
  2625. * Called when an ID3 is found in a EMSG.
  2626. * @property {function(!shaka.extern.Stream, number):boolean} disableStream
  2627. * Called to temporarily disable a stream i.e. disabling all variant
  2628. * containing said stream.
  2629. */
  2630. shaka.media.StreamingEngine.PlayerInterface;
  2631. /**
  2632. * @typedef {{
  2633. * type: shaka.util.ManifestParserUtils.ContentType,
  2634. * stream: shaka.extern.Stream,
  2635. * segmentIterator: shaka.media.SegmentIterator,
  2636. * lastSegmentReference: shaka.media.SegmentReference,
  2637. * lastInitSegmentReference: shaka.media.InitSegmentReference,
  2638. * lastTimestampOffset: ?number,
  2639. * lastAppendWindowStart: ?number,
  2640. * lastAppendWindowEnd: ?number,
  2641. * lastCodecs: ?string,
  2642. * lastMimeType: ?string,
  2643. * restoreStreamAfterTrickPlay: ?shaka.extern.Stream,
  2644. * endOfStream: boolean,
  2645. * performingUpdate: boolean,
  2646. * updateTimer: shaka.util.DelayedTick,
  2647. * waitingToClearBuffer: boolean,
  2648. * waitingToFlushBuffer: boolean,
  2649. * clearBufferSafeMargin: number,
  2650. * clearingBuffer: boolean,
  2651. * seeked: boolean,
  2652. * adaptation: boolean,
  2653. * recovering: boolean,
  2654. * hasError: boolean,
  2655. * operation: shaka.net.NetworkingEngine.PendingRequest,
  2656. * segmentPrefetch: shaka.media.SegmentPrefetch
  2657. * }}
  2658. *
  2659. * @description
  2660. * Contains the state of a logical stream, i.e., a sequence of segmented data
  2661. * for a particular content type. At any given time there is a Stream object
  2662. * associated with the state of the logical stream.
  2663. *
  2664. * @property {shaka.util.ManifestParserUtils.ContentType} type
  2665. * The stream's content type, e.g., 'audio', 'video', or 'text'.
  2666. * @property {shaka.extern.Stream} stream
  2667. * The current Stream.
  2668. * @property {shaka.media.SegmentIndexIterator} segmentIterator
  2669. * An iterator through the segments of |stream|.
  2670. * @property {shaka.media.SegmentReference} lastSegmentReference
  2671. * The SegmentReference of the last segment that was appended.
  2672. * @property {shaka.media.InitSegmentReference} lastInitSegmentReference
  2673. * The InitSegmentReference of the last init segment that was appended.
  2674. * @property {?number} lastTimestampOffset
  2675. * The last timestamp offset given to MediaSourceEngine for this type.
  2676. * @property {?number} lastAppendWindowStart
  2677. * The last append window start given to MediaSourceEngine for this type.
  2678. * @property {?number} lastAppendWindowEnd
  2679. * The last append window end given to MediaSourceEngine for this type.
  2680. * @property {?string} lastCodecs
  2681. * The last append codecs given to MediaSourceEngine for this type.
  2682. * @property {?string} lastMimeType
  2683. * The last append mime type given to MediaSourceEngine for this type.
  2684. * @property {?shaka.extern.Stream} restoreStreamAfterTrickPlay
  2685. * The Stream to restore after trick play mode is turned off.
  2686. * @property {boolean} endOfStream
  2687. * True indicates that the end of the buffer has hit the end of the
  2688. * presentation.
  2689. * @property {boolean} performingUpdate
  2690. * True indicates that an update is in progress.
  2691. * @property {shaka.util.DelayedTick} updateTimer
  2692. * A timer used to update the media state.
  2693. * @property {boolean} waitingToClearBuffer
  2694. * True indicates that the buffer must be cleared after the current update
  2695. * finishes.
  2696. * @property {boolean} waitingToFlushBuffer
  2697. * True indicates that the buffer must be flushed after it is cleared.
  2698. * @property {number} clearBufferSafeMargin
  2699. * The amount of buffer to retain when clearing the buffer after the update.
  2700. * @property {boolean} clearingBuffer
  2701. * True indicates that the buffer is being cleared.
  2702. * @property {boolean} seeked
  2703. * True indicates that the presentation just seeked.
  2704. * @property {boolean} adaptation
  2705. * True indicates that the presentation just automatically switched variants.
  2706. * @property {boolean} recovering
  2707. * True indicates that the last segment was not appended because it could not
  2708. * fit in the buffer.
  2709. * @property {boolean} hasError
  2710. * True indicates that the stream has encountered an error and has stopped
  2711. * updating.
  2712. * @property {shaka.net.NetworkingEngine.PendingRequest} operation
  2713. * Operation with the number of bytes to be downloaded.
  2714. * @property {?shaka.media.SegmentPrefetch} segmentPrefetch
  2715. * A prefetch object for managing prefetching. Null if unneeded
  2716. * (if prefetching is disabled, etc).
  2717. */
  2718. shaka.media.StreamingEngine.MediaState_;
  2719. /**
  2720. * The fudge factor for appendWindowStart. By adjusting the window backward, we
  2721. * avoid rounding errors that could cause us to remove the keyframe at the start
  2722. * of the Period.
  2723. *
  2724. * NOTE: This was increased as part of the solution to
  2725. * https://github.com/shaka-project/shaka-player/issues/1281
  2726. *
  2727. * @const {number}
  2728. * @private
  2729. */
  2730. shaka.media.StreamingEngine.APPEND_WINDOW_START_FUDGE_ = 0.1;
  2731. /**
  2732. * The fudge factor for appendWindowEnd. By adjusting the window backward, we
  2733. * avoid rounding errors that could cause us to remove the last few samples of
  2734. * the Period. This rounding error could then create an artificial gap and a
  2735. * stutter when the gap-jumping logic takes over.
  2736. *
  2737. * https://github.com/shaka-project/shaka-player/issues/1597
  2738. *
  2739. * @const {number}
  2740. * @private
  2741. */
  2742. shaka.media.StreamingEngine.APPEND_WINDOW_END_FUDGE_ = 0.01;
  2743. /**
  2744. * The maximum number of segments by which a stream can get ahead of other
  2745. * streams.
  2746. *
  2747. * Introduced to keep StreamingEngine from letting one media type get too far
  2748. * ahead of another. For example, audio segments are typically much smaller
  2749. * than video segments, so in the time it takes to fetch one video segment, we
  2750. * could fetch many audio segments. This doesn't help with buffering, though,
  2751. * since the intersection of the two buffered ranges is what counts.
  2752. *
  2753. * @const {number}
  2754. * @private
  2755. */
  2756. shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_ = 1;