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