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