Source: lib/media/media_source_engine.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.MediaSourceEngine');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.config.CodecSwitchingStrategy');
  10. goog.require('shaka.media.Capabilities');
  11. goog.require('shaka.media.ContentWorkarounds');
  12. goog.require('shaka.media.ClosedCaptionParser');
  13. goog.require('shaka.media.IClosedCaptionParser');
  14. goog.require('shaka.media.ManifestParser');
  15. goog.require('shaka.media.SegmentReference');
  16. goog.require('shaka.media.TimeRangesUtils');
  17. goog.require('shaka.text.TextEngine');
  18. goog.require('shaka.transmuxer.TransmuxerEngine');
  19. goog.require('shaka.util.BufferUtils');
  20. goog.require('shaka.util.Destroyer');
  21. goog.require('shaka.util.Error');
  22. goog.require('shaka.util.EventManager');
  23. goog.require('shaka.util.Functional');
  24. goog.require('shaka.util.IDestroyable');
  25. goog.require('shaka.util.Id3Utils');
  26. goog.require('shaka.util.ManifestParserUtils');
  27. goog.require('shaka.util.MimeUtils');
  28. goog.require('shaka.util.Mp4BoxParsers');
  29. goog.require('shaka.util.Mp4Parser');
  30. goog.require('shaka.util.Platform');
  31. goog.require('shaka.util.PublicPromise');
  32. goog.require('shaka.util.StreamUtils');
  33. goog.require('shaka.util.TsParser');
  34. goog.require('shaka.lcevc.Dec');
  35. /**
  36. * @summary
  37. * MediaSourceEngine wraps all operations on MediaSource and SourceBuffers.
  38. * All asynchronous operations return a Promise, and all operations are
  39. * internally synchronized and serialized as needed. Operations that can
  40. * be done in parallel will be done in parallel.
  41. *
  42. * @implements {shaka.util.IDestroyable}
  43. */
  44. shaka.media.MediaSourceEngine = class {
  45. /**
  46. * @param {HTMLMediaElement} video The video element, whose source is tied to
  47. * MediaSource during the lifetime of the MediaSourceEngine.
  48. * @param {!shaka.extern.TextDisplayer} textDisplayer
  49. * The text displayer that will be used with the text engine.
  50. * MediaSourceEngine takes ownership of the displayer. When
  51. * MediaSourceEngine is destroyed, it will destroy the displayer.
  52. * @param {!function(!Array.<shaka.extern.ID3Metadata>, number, ?number)=}
  53. * onMetadata
  54. * @param {?shaka.lcevc.Dec} [lcevcDec] Optional - LCEVC Decoder Object
  55. *
  56. */
  57. constructor(video, textDisplayer, onMetadata, lcevcDec) {
  58. /** @private {HTMLMediaElement} */
  59. this.video_ = video;
  60. /** @private {?shaka.extern.MediaSourceConfiguration} */
  61. this.config_ = null;
  62. /** @private {shaka.extern.TextDisplayer} */
  63. this.textDisplayer_ = textDisplayer;
  64. /** @private {!Object.<shaka.util.ManifestParserUtils.ContentType,
  65. SourceBuffer>} */
  66. this.sourceBuffers_ = {};
  67. /** @private {!Object.<shaka.util.ManifestParserUtils.ContentType,
  68. string>} */
  69. this.sourceBufferTypes_ = {};
  70. /** @private {!Object.<shaka.util.ManifestParserUtils.ContentType,
  71. boolean>} */
  72. this.expectedEncryption_ = {};
  73. /** @private {shaka.text.TextEngine} */
  74. this.textEngine_ = null;
  75. /** @private {boolean} */
  76. this.segmentRelativeVttTiming_ = false;
  77. const onMetadataNoOp = (metadata, timestampOffset, segmentEnd) => {};
  78. /** @private {!function(!Array.<shaka.extern.ID3Metadata>,
  79. number, ?number)} */
  80. this.onMetadata_ = onMetadata || onMetadataNoOp;
  81. /** @private {?shaka.lcevc.Dec} */
  82. this.lcevcDec_ = lcevcDec || null;
  83. /**
  84. * @private {!Object.<string,
  85. * !Array.<shaka.media.MediaSourceEngine.Operation>>}
  86. */
  87. this.queues_ = {};
  88. /** @private {shaka.util.EventManager} */
  89. this.eventManager_ = new shaka.util.EventManager();
  90. /** @private {!Object.<string, !shaka.extern.Transmuxer>} */
  91. this.transmuxers_ = {};
  92. /** @private {?shaka.media.IClosedCaptionParser} */
  93. this.captionParser_ = null;
  94. /** @private {!shaka.util.PublicPromise} */
  95. this.mediaSourceOpen_ = new shaka.util.PublicPromise();
  96. /** @private {string} */
  97. this.url_ = '';
  98. /** @private {boolean} */
  99. this.playbackHasBegun_ = false;
  100. /** @private {(MediaSource|ManagedMediaSource)} */
  101. this.mediaSource_ = this.createMediaSource(this.mediaSourceOpen_);
  102. /** @private {boolean} */
  103. this.reloadingMediaSource_ = false;
  104. /** @type {!shaka.util.Destroyer} */
  105. this.destroyer_ = new shaka.util.Destroyer(() => this.doDestroy_());
  106. /** @private {boolean} */
  107. this.sequenceMode_ = false;
  108. /** @private {string} */
  109. this.manifestType_ = shaka.media.ManifestParser.UNKNOWN;
  110. /** @private {boolean} */
  111. this.ignoreManifestTimestampsInSegmentsMode_ = false;
  112. /** @private {boolean} */
  113. this.attemptTimestampOffsetCalculation_ = false;
  114. /** @private {!shaka.util.PublicPromise.<number>} */
  115. this.textSequenceModeOffset_ = new shaka.util.PublicPromise();
  116. /** @private {boolean} */
  117. this.needSplitMuxedContent_ = false;
  118. /** @private {boolean} */
  119. this.streamingAllowed_ = true;
  120. /** @private {?number} */
  121. this.lastDuration_ = null;
  122. /** @private {?shaka.util.TsParser} */
  123. this.tsParser_ = null;
  124. }
  125. /**
  126. * Create a MediaSource object, attach it to the video element, and return it.
  127. * Resolves the given promise when the MediaSource is ready.
  128. *
  129. * Replaced by unit tests.
  130. *
  131. * @param {!shaka.util.PublicPromise} p
  132. * @return {!(MediaSource|ManagedMediaSource)}
  133. */
  134. createMediaSource(p) {
  135. if (window.ManagedMediaSource) {
  136. this.video_.disableRemotePlayback = true;
  137. const mediaSource = new ManagedMediaSource();
  138. this.eventManager_.listen(
  139. mediaSource, 'startstreaming', () => {
  140. this.streamingAllowed_ = true;
  141. });
  142. this.eventManager_.listen(
  143. mediaSource, 'endstreaming', () => {
  144. this.streamingAllowed_ = false;
  145. });
  146. this.eventManager_.listenOnce(
  147. mediaSource, 'sourceopen', () => this.onSourceOpen_(p));
  148. // Correctly set when playback has begun.
  149. this.eventManager_.listenOnce(this.video_, 'playing', () => {
  150. this.playbackHasBegun_ = true;
  151. });
  152. this.url_ = shaka.media.MediaSourceEngine.createObjectURL(mediaSource);
  153. this.video_.src = this.url_;
  154. return mediaSource;
  155. } else {
  156. const mediaSource = new MediaSource();
  157. // Set up MediaSource on the video element.
  158. this.eventManager_.listenOnce(
  159. mediaSource, 'sourceopen', () => this.onSourceOpen_(p));
  160. // Correctly set when playback has begun.
  161. this.eventManager_.listenOnce(this.video_, 'playing', () => {
  162. this.playbackHasBegun_ = true;
  163. });
  164. // Store the object URL for releasing it later.
  165. this.url_ = shaka.media.MediaSourceEngine.createObjectURL(mediaSource);
  166. this.video_.src = this.url_;
  167. return mediaSource;
  168. }
  169. }
  170. /**
  171. * @param {shaka.util.PublicPromise} p
  172. * @private
  173. */
  174. onSourceOpen_(p) {
  175. goog.asserts.assert(this.url_, 'Must have object URL');
  176. // Release the object URL that was previously created, to prevent memory
  177. // leak.
  178. // createObjectURL creates a strong reference to the MediaSource object
  179. // inside the browser. Setting the src of the video then creates another
  180. // reference within the video element. revokeObjectURL will remove the
  181. // strong reference to the MediaSource object, and allow it to be
  182. // garbage-collected later.
  183. URL.revokeObjectURL(this.url_);
  184. p.resolve();
  185. }
  186. /**
  187. * Checks if a certain type is supported.
  188. *
  189. * @param {shaka.extern.Stream} stream
  190. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  191. * @return {!Promise.<boolean>}
  192. */
  193. static async isStreamSupported(stream, contentType) {
  194. if (stream.createSegmentIndex) {
  195. await stream.createSegmentIndex();
  196. }
  197. if (!stream.segmentIndex) {
  198. return false;
  199. }
  200. if (stream.segmentIndex.isEmpty()) {
  201. return true;
  202. }
  203. const MimeUtils = shaka.util.MimeUtils;
  204. const TransmuxerEngine = shaka.transmuxer.TransmuxerEngine;
  205. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  206. const StreamUtils = shaka.util.StreamUtils;
  207. const seenCombos = new Set();
  208. // Check each combination of mimeType and codecs within the segment index.
  209. // Unfortunately we cannot use fullMimeTypes, as we ALSO need to check the
  210. // getFullTypeWithAllCodecs (for the sake of the transmuxer) and we have no
  211. // way of going from a full mimeType to a full mimeType with all codecs.
  212. // As this function is only called in debug mode, a little inefficiency is
  213. // acceptable.
  214. for (const ref of stream.segmentIndex) {
  215. const mimeType = ref.mimeType || stream.mimeType || '';
  216. let codecs = ref.codecs || stream.codecs || '';
  217. // Don't check the same combination of mimetype + codecs twice.
  218. const combo = mimeType + ':' + codecs;
  219. if (seenCombos.has(combo)) {
  220. continue;
  221. }
  222. seenCombos.add(combo);
  223. if (contentType == ContentType.TEXT) {
  224. const fullMimeType = MimeUtils.getFullType(mimeType, codecs);
  225. if (!shaka.text.TextEngine.isTypeSupported(fullMimeType)) {
  226. return false;
  227. }
  228. } else {
  229. if (contentType == ContentType.VIDEO) {
  230. codecs = StreamUtils.getCorrectVideoCodecs(codecs);
  231. } else if (contentType == ContentType.AUDIO) {
  232. codecs = StreamUtils.getCorrectAudioCodecs(codecs, mimeType);
  233. }
  234. const extendedMimeType = MimeUtils.getExtendedType(
  235. stream, mimeType, codecs);
  236. const fullMimeType = MimeUtils.getFullTypeWithAllCodecs(
  237. mimeType, codecs);
  238. if (!shaka.media.Capabilities.isTypeSupported(extendedMimeType) &&
  239. !TransmuxerEngine.isSupported(fullMimeType, stream.type)) {
  240. return false;
  241. }
  242. }
  243. }
  244. return true;
  245. }
  246. /**
  247. * Returns a map of MediaSource support for well-known types.
  248. *
  249. * @return {!Object.<string, boolean>}
  250. */
  251. static probeSupport() {
  252. const testMimeTypes = [
  253. // MP4 types
  254. 'video/mp4; codecs="avc1.42E01E"',
  255. 'video/mp4; codecs="avc3.42E01E"',
  256. 'video/mp4; codecs="hev1.1.6.L93.90"',
  257. 'video/mp4; codecs="hvc1.1.6.L93.90"',
  258. 'video/mp4; codecs="hev1.2.4.L153.B0"; eotf="smpte2084"', // HDR HEVC
  259. 'video/mp4; codecs="hvc1.2.4.L153.B0"; eotf="smpte2084"', // HDR HEVC
  260. 'video/mp4; codecs="vp9"',
  261. 'video/mp4; codecs="vp09.00.10.08"',
  262. 'video/mp4; codecs="av01.0.01M.08"',
  263. 'video/mp4; codecs="dvh1.20.01"',
  264. 'audio/mp4; codecs="mp4a.40.2"',
  265. 'audio/mp4; codecs="ac-3"',
  266. 'audio/mp4; codecs="ec-3"',
  267. 'audio/mp4; codecs="ac-4.02.01.01"',
  268. 'audio/mp4; codecs="opus"',
  269. 'audio/mp4; codecs="flac"',
  270. 'audio/mp4; codecs="dtsc"', // DTS Digital Surround
  271. 'audio/mp4; codecs="dtse"', // DTS Express
  272. 'audio/mp4; codecs="dtsx"', // DTS:X
  273. // WebM types
  274. 'video/webm; codecs="vp8"',
  275. 'video/webm; codecs="vp9"',
  276. 'video/webm; codecs="vp09.00.10.08"',
  277. 'audio/webm; codecs="vorbis"',
  278. 'audio/webm; codecs="opus"',
  279. // MPEG2 TS types (video/ is also used for audio: https://bit.ly/TsMse)
  280. 'video/mp2t; codecs="avc1.42E01E"',
  281. 'video/mp2t; codecs="avc3.42E01E"',
  282. 'video/mp2t; codecs="hvc1.1.6.L93.90"',
  283. 'video/mp2t; codecs="mp4a.40.2"',
  284. 'video/mp2t; codecs="ac-3"',
  285. 'video/mp2t; codecs="ec-3"',
  286. // WebVTT types
  287. 'text/vtt',
  288. 'application/mp4; codecs="wvtt"',
  289. // TTML types
  290. 'application/ttml+xml',
  291. 'application/mp4; codecs="stpp"',
  292. // Containerless types
  293. ...shaka.util.MimeUtils.RAW_FORMATS,
  294. ];
  295. const support = {};
  296. for (const type of testMimeTypes) {
  297. if (shaka.text.TextEngine.isTypeSupported(type)) {
  298. support[type] = true;
  299. } else if (shaka.util.Platform.supportsMediaSource()) {
  300. support[type] = shaka.media.Capabilities.isTypeSupported(type) ||
  301. shaka.transmuxer.TransmuxerEngine.isSupported(type);
  302. } else {
  303. support[type] = shaka.util.Platform.supportsMediaType(type);
  304. }
  305. const basicType = type.split(';')[0];
  306. support[basicType] = support[basicType] || support[type];
  307. }
  308. return support;
  309. }
  310. /** @override */
  311. destroy() {
  312. return this.destroyer_.destroy();
  313. }
  314. /** @private */
  315. async doDestroy_() {
  316. const Functional = shaka.util.Functional;
  317. const cleanup = [];
  318. for (const contentType in this.queues_) {
  319. // Make a local copy of the queue and the first item.
  320. const q = this.queues_[contentType];
  321. const inProgress = q[0];
  322. // Drop everything else out of the original queue.
  323. this.queues_[contentType] = q.slice(0, 1);
  324. // We will wait for this item to complete/fail.
  325. if (inProgress) {
  326. cleanup.push(inProgress.p.catch(Functional.noop));
  327. }
  328. // The rest will be rejected silently if possible.
  329. for (const item of q.slice(1)) {
  330. item.p.reject(shaka.util.Destroyer.destroyedError());
  331. }
  332. }
  333. if (this.textEngine_) {
  334. cleanup.push(this.textEngine_.destroy());
  335. }
  336. if (this.textDisplayer_) {
  337. cleanup.push(this.textDisplayer_.destroy());
  338. }
  339. for (const contentType in this.transmuxers_) {
  340. cleanup.push(this.transmuxers_[contentType].destroy());
  341. }
  342. await Promise.all(cleanup);
  343. if (this.eventManager_) {
  344. this.eventManager_.release();
  345. this.eventManager_ = null;
  346. }
  347. if (this.video_) {
  348. // "unload" the video element.
  349. this.video_.removeAttribute('src');
  350. this.video_.load();
  351. this.video_ = null;
  352. }
  353. this.config_ = null;
  354. this.mediaSource_ = null;
  355. this.textEngine_ = null;
  356. this.textDisplayer_ = null;
  357. this.sourceBuffers_ = {};
  358. this.transmuxers_ = {};
  359. this.captionParser_ = null;
  360. if (goog.DEBUG) {
  361. for (const contentType in this.queues_) {
  362. goog.asserts.assert(
  363. this.queues_[contentType].length == 0,
  364. contentType + ' queue should be empty after destroy!');
  365. }
  366. }
  367. this.queues_ = {};
  368. // This object is owned by Player
  369. this.lcevcDec_ = null;
  370. this.tsParser_ = null;
  371. }
  372. /**
  373. * @return {!Promise} Resolved when MediaSource is open and attached to the
  374. * media element. This process is actually initiated by the constructor.
  375. */
  376. open() {
  377. return this.mediaSourceOpen_;
  378. }
  379. /**
  380. * Initialize MediaSourceEngine.
  381. *
  382. * Note that it is not valid to call this multiple times, except to add or
  383. * reinitialize text streams.
  384. *
  385. * @param {!Map.<shaka.util.ManifestParserUtils.ContentType,
  386. * shaka.extern.Stream>} streamsByType
  387. * A map of content types to streams. All streams must be supported
  388. * according to MediaSourceEngine.isStreamSupported.
  389. * @param {boolean=} sequenceMode
  390. * If true, the media segments are appended to the SourceBuffer in strict
  391. * sequence.
  392. * @param {string=} manifestType
  393. * Indicates the type of the manifest.
  394. * @param {boolean=} ignoreManifestTimestampsInSegmentsMode
  395. * If true, don't adjust the timestamp offset to account for manifest
  396. * segment durations being out of sync with segment durations. In other
  397. * words, assume that there are no gaps in the segments when appending
  398. * to the SourceBuffer, even if the manifest and segment times disagree.
  399. * Indicates if the manifest has text streams.
  400. *
  401. * @return {!Promise}
  402. */
  403. async init(streamsByType, sequenceMode=false,
  404. manifestType=shaka.media.ManifestParser.UNKNOWN,
  405. ignoreManifestTimestampsInSegmentsMode=false) {
  406. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  407. await this.mediaSourceOpen_;
  408. this.sequenceMode_ = sequenceMode;
  409. this.manifestType_ = manifestType;
  410. this.ignoreManifestTimestampsInSegmentsMode_ =
  411. ignoreManifestTimestampsInSegmentsMode;
  412. this.attemptTimestampOffsetCalculation_ = !this.sequenceMode_ &&
  413. this.manifestType_ == shaka.media.ManifestParser.HLS &&
  414. !this.ignoreManifestTimestampsInSegmentsMode_;
  415. this.tsParser_ = null;
  416. for (const contentType of streamsByType.keys()) {
  417. const stream = streamsByType.get(contentType);
  418. // eslint-disable-next-line no-await-in-loop
  419. await this.initSourceBuffer_(contentType, stream, stream.codecs);
  420. if (this.needSplitMuxedContent_) {
  421. this.queues_[ContentType.AUDIO] = [];
  422. this.queues_[ContentType.VIDEO] = [];
  423. } else {
  424. this.queues_[contentType] = [];
  425. }
  426. }
  427. }
  428. /**
  429. * Initialize a specific SourceBuffer.
  430. *
  431. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  432. * @param {shaka.extern.Stream} stream
  433. * @param {string} codecs
  434. * @return {!Promise}
  435. * @private
  436. */
  437. async initSourceBuffer_(contentType, stream, codecs) {
  438. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  439. goog.asserts.assert(
  440. await shaka.media.MediaSourceEngine.isStreamSupported(
  441. stream, contentType),
  442. 'Type negotiation should happen before MediaSourceEngine.init!');
  443. let mimeType = shaka.util.MimeUtils.getFullType(
  444. stream.mimeType, codecs);
  445. if (contentType == ContentType.TEXT) {
  446. this.reinitText(mimeType, this.sequenceMode_, stream.external);
  447. } else {
  448. let needTransmux = this.config_.forceTransmux;
  449. if (!shaka.media.Capabilities.isTypeSupported(mimeType) ||
  450. (!this.sequenceMode_ &&
  451. shaka.util.MimeUtils.RAW_FORMATS.includes(mimeType))) {
  452. needTransmux = true;
  453. }
  454. const mimeTypeWithAllCodecs =
  455. shaka.util.MimeUtils.getFullTypeWithAllCodecs(
  456. stream.mimeType, codecs);
  457. if (needTransmux) {
  458. const audioCodec = shaka.util.ManifestParserUtils.guessCodecsSafe(
  459. ContentType.AUDIO, (codecs || '').split(','));
  460. const videoCodec = shaka.util.ManifestParserUtils.guessCodecsSafe(
  461. ContentType.VIDEO, (codecs || '').split(','));
  462. if (audioCodec && videoCodec) {
  463. this.needSplitMuxedContent_ = true;
  464. await this.initSourceBuffer_(ContentType.AUDIO, stream, audioCodec);
  465. await this.initSourceBuffer_(ContentType.VIDEO, stream, videoCodec);
  466. return;
  467. }
  468. const transmuxerPlugin = shaka.transmuxer.TransmuxerEngine
  469. .findTransmuxer(mimeTypeWithAllCodecs);
  470. if (transmuxerPlugin) {
  471. const transmuxer = transmuxerPlugin();
  472. this.transmuxers_[contentType] = transmuxer;
  473. mimeType =
  474. transmuxer.convertCodecs(contentType, mimeTypeWithAllCodecs);
  475. }
  476. }
  477. const type = this.addExtraFeaturesToMimeType_(mimeType);
  478. this.destroyer_.ensureNotDestroyed();
  479. let sourceBuffer;
  480. try {
  481. sourceBuffer = this.mediaSource_.addSourceBuffer(type);
  482. } catch (exception) {
  483. throw new shaka.util.Error(
  484. shaka.util.Error.Severity.CRITICAL,
  485. shaka.util.Error.Category.MEDIA,
  486. shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,
  487. exception,
  488. 'The mediaSource_ status was ' + this.mediaSource_.readyState +
  489. ' expected \'open\'');
  490. }
  491. if (this.sequenceMode_) {
  492. sourceBuffer.mode =
  493. shaka.media.MediaSourceEngine.SourceBufferMode_.SEQUENCE;
  494. }
  495. this.eventManager_.listen(
  496. sourceBuffer, 'error',
  497. () => this.onError_(contentType));
  498. this.eventManager_.listen(
  499. sourceBuffer, 'updateend',
  500. () => this.onUpdateEnd_(contentType));
  501. this.sourceBuffers_[contentType] = sourceBuffer;
  502. this.sourceBufferTypes_[contentType] = mimeType;
  503. this.expectedEncryption_[contentType] = !!stream.drmInfos.length;
  504. }
  505. }
  506. /**
  507. * Called by the Player to provide an updated configuration any time it
  508. * changes. Must be called at least once before init().
  509. *
  510. * @param {shaka.extern.MediaSourceConfiguration} config
  511. */
  512. configure(config) {
  513. this.config_ = config;
  514. if (this.textEngine_) {
  515. this.textEngine_.setModifyCueCallback(config.modifyCueCallback);
  516. }
  517. }
  518. /**
  519. * Indicate if the streaming is allowed by MediaSourceEngine.
  520. * If we using MediaSource we allways returns true.
  521. *
  522. * @return {boolean}
  523. */
  524. isStreamingAllowed() {
  525. return this.streamingAllowed_;
  526. }
  527. /**
  528. * Reinitialize the TextEngine for a new text type.
  529. * @param {string} mimeType
  530. * @param {boolean} sequenceMode
  531. * @param {boolean} external
  532. */
  533. reinitText(mimeType, sequenceMode, external) {
  534. if (!this.textEngine_) {
  535. this.textEngine_ = new shaka.text.TextEngine(this.textDisplayer_);
  536. if (this.textEngine_) {
  537. this.textEngine_.setModifyCueCallback(this.config_.modifyCueCallback);
  538. }
  539. }
  540. this.textEngine_.initParser(mimeType, sequenceMode,
  541. external || this.segmentRelativeVttTiming_, this.manifestType_);
  542. }
  543. /**
  544. * @return {boolean} True if the MediaSource is in an "ended" state, or if the
  545. * object has been destroyed.
  546. */
  547. ended() {
  548. if (this.reloadingMediaSource_) {
  549. return false;
  550. }
  551. return this.mediaSource_ ? this.mediaSource_.readyState == 'ended' : true;
  552. }
  553. /**
  554. * Gets the first timestamp in buffer for the given content type.
  555. *
  556. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  557. * @return {?number} The timestamp in seconds, or null if nothing is buffered.
  558. */
  559. bufferStart(contentType) {
  560. if (this.reloadingMediaSource_ ||
  561. !Object.keys(this.sourceBuffers_).length) {
  562. return null;
  563. }
  564. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  565. if (contentType == ContentType.TEXT) {
  566. return this.textEngine_.bufferStart();
  567. }
  568. return shaka.media.TimeRangesUtils.bufferStart(
  569. this.getBuffered_(contentType));
  570. }
  571. /**
  572. * Gets the last timestamp in buffer for the given content type.
  573. *
  574. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  575. * @return {?number} The timestamp in seconds, or null if nothing is buffered.
  576. */
  577. bufferEnd(contentType) {
  578. if (this.reloadingMediaSource_) {
  579. return null;
  580. }
  581. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  582. if (contentType == ContentType.TEXT) {
  583. return this.textEngine_.bufferEnd();
  584. }
  585. return shaka.media.TimeRangesUtils.bufferEnd(
  586. this.getBuffered_(contentType));
  587. }
  588. /**
  589. * Determines if the given time is inside the buffered range of the given
  590. * content type.
  591. *
  592. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  593. * @param {number} time Playhead time
  594. * @return {boolean}
  595. */
  596. isBuffered(contentType, time) {
  597. if (this.reloadingMediaSource_) {
  598. return false;
  599. }
  600. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  601. if (contentType == ContentType.TEXT) {
  602. return this.textEngine_.isBuffered(time);
  603. } else {
  604. const buffered = this.getBuffered_(contentType);
  605. return shaka.media.TimeRangesUtils.isBuffered(buffered, time);
  606. }
  607. }
  608. /**
  609. * Computes how far ahead of the given timestamp is buffered for the given
  610. * content type.
  611. *
  612. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  613. * @param {number} time
  614. * @return {number} The amount of time buffered ahead in seconds.
  615. */
  616. bufferedAheadOf(contentType, time) {
  617. if (this.reloadingMediaSource_) {
  618. return 0;
  619. }
  620. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  621. if (contentType == ContentType.TEXT) {
  622. return this.textEngine_.bufferedAheadOf(time);
  623. } else {
  624. const buffered = this.getBuffered_(contentType);
  625. return shaka.media.TimeRangesUtils.bufferedAheadOf(buffered, time);
  626. }
  627. }
  628. /**
  629. * Returns info about what is currently buffered.
  630. * @return {shaka.extern.BufferedInfo}
  631. */
  632. getBufferedInfo() {
  633. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  634. const TimeRangesUtils = shaka.media.TimeRangesUtils;
  635. const info = {
  636. total: this.reloadingMediaSource_ ? [] :
  637. TimeRangesUtils.getBufferedInfo(this.video_.buffered),
  638. audio: this.reloadingMediaSource_ ? [] :
  639. TimeRangesUtils.getBufferedInfo(this.getBuffered_(ContentType.AUDIO)),
  640. video: this.reloadingMediaSource_ ? [] :
  641. TimeRangesUtils.getBufferedInfo(this.getBuffered_(ContentType.VIDEO)),
  642. text: [],
  643. };
  644. if (this.textEngine_) {
  645. const start = this.textEngine_.bufferStart();
  646. const end = this.textEngine_.bufferEnd();
  647. if (start != null && end != null) {
  648. info.text.push({start: start, end: end});
  649. }
  650. }
  651. return info;
  652. }
  653. /**
  654. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  655. * @return {TimeRanges} The buffered ranges for the given content type, or
  656. * null if the buffered ranges could not be obtained.
  657. * @private
  658. */
  659. getBuffered_(contentType) {
  660. try {
  661. return this.sourceBuffers_[contentType].buffered;
  662. } catch (exception) {
  663. if (contentType in this.sourceBuffers_) {
  664. // Note: previous MediaSource errors may cause access to |buffered| to
  665. // throw.
  666. shaka.log.error('failed to get buffered range for ' + contentType,
  667. exception);
  668. }
  669. return null;
  670. }
  671. }
  672. /**
  673. * Create a new closed caption parser. This will ONLY be replaced by tests as
  674. * a way to inject fake closed caption parser instances.
  675. *
  676. * @param {string} mimeType
  677. * @return {!shaka.media.IClosedCaptionParser}
  678. */
  679. getCaptionParser(mimeType) {
  680. return new shaka.media.ClosedCaptionParser(mimeType);
  681. }
  682. /**
  683. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  684. * @param {!BufferSource} data
  685. * @param {?shaka.media.SegmentReference} reference The segment reference
  686. * we are appending, or null for init segments
  687. * @param {!string} mimeType
  688. * @param {!number} timestampOffset
  689. * @return {?number}
  690. * @private
  691. */
  692. getTimestampAndDispatchMetadata_(contentType, data, reference, mimeType,
  693. timestampOffset) {
  694. let timestamp = null;
  695. const uint8ArrayData = shaka.util.BufferUtils.toUint8(data);
  696. if (shaka.util.MimeUtils.RAW_FORMATS.includes(mimeType)) {
  697. const frames = shaka.util.Id3Utils.getID3Frames(uint8ArrayData);
  698. if (frames.length && reference) {
  699. const metadataTimestamp = frames.find((frame) => {
  700. return frame.description ===
  701. 'com.apple.streaming.transportStreamTimestamp';
  702. });
  703. if (metadataTimestamp && metadataTimestamp.data) {
  704. timestamp = Math.round(metadataTimestamp.data) / 1000;
  705. }
  706. /** @private {shaka.extern.ID3Metadata} */
  707. const metadata = {
  708. cueTime: reference.startTime,
  709. data: uint8ArrayData,
  710. frames: frames,
  711. dts: reference.startTime,
  712. pts: reference.startTime,
  713. };
  714. this.onMetadata_([metadata], /* offset= */ 0, reference.endTime);
  715. }
  716. } else if (mimeType.includes('/mp4') &&
  717. reference && reference.timestampOffset == 0 &&
  718. reference.initSegmentReference &&
  719. reference.initSegmentReference.timescale) {
  720. const timescale = reference.initSegmentReference.timescale;
  721. if (!isNaN(timescale)) {
  722. const Mp4Parser = shaka.util.Mp4Parser;
  723. let startTime = 0;
  724. let parsedMedia = false;
  725. new Mp4Parser()
  726. .box('moof', Mp4Parser.children)
  727. .box('traf', Mp4Parser.children)
  728. .fullBox('tfdt', (box) => {
  729. goog.asserts.assert(
  730. box.version == 0 || box.version == 1,
  731. 'TFDT version can only be 0 or 1');
  732. const parsed = shaka.util.Mp4BoxParsers.parseTFDTInaccurate(
  733. box.reader, box.version);
  734. startTime = parsed.baseMediaDecodeTime / timescale;
  735. parsedMedia = true;
  736. box.parser.stop();
  737. }).parse(data, /* partialOkay= */ true);
  738. if (parsedMedia) {
  739. timestamp = startTime;
  740. }
  741. }
  742. } else if (!mimeType.includes('/mp4') && !mimeType.includes('/webm') &&
  743. shaka.util.TsParser.probe(uint8ArrayData)) {
  744. if (!this.tsParser_) {
  745. this.tsParser_ = new shaka.util.TsParser();
  746. } else {
  747. this.tsParser_.clearData();
  748. }
  749. const tsParser = this.tsParser_.parse(uint8ArrayData);
  750. const startTime = tsParser.getStartTime(contentType);
  751. if (startTime != null) {
  752. timestamp = startTime;
  753. }
  754. const metadata = tsParser.getMetadata();
  755. if (metadata.length) {
  756. this.onMetadata_(metadata, timestampOffset,
  757. reference ? reference.endTime : null);
  758. }
  759. }
  760. return timestamp;
  761. }
  762. /**
  763. * Enqueue an operation to append data to the SourceBuffer.
  764. * Start and end times are needed for TextEngine, but not for MediaSource.
  765. * Start and end times may be null for initialization segments; if present
  766. * they are relative to the presentation timeline.
  767. *
  768. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  769. * @param {!BufferSource} data
  770. * @param {?shaka.media.SegmentReference} reference The segment reference
  771. * we are appending, or null for init segments
  772. * @param {shaka.extern.Stream} stream
  773. * @param {?boolean} hasClosedCaptions True if the buffer contains CEA closed
  774. * captions
  775. * @param {boolean=} seeked True if we just seeked
  776. * @param {boolean=} adaptation True if we just automatically switched active
  777. * variant(s).
  778. * @param {boolean=} isChunkedData True if we add to the buffer from the
  779. * partial read of the segment.
  780. * @return {!Promise}
  781. */
  782. async appendBuffer(
  783. contentType, data, reference, stream, hasClosedCaptions, seeked = false,
  784. adaptation = false, isChunkedData = false, fromSplit = false) {
  785. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  786. if (contentType == ContentType.TEXT) {
  787. if (this.sequenceMode_) {
  788. // This won't be known until the first video segment is appended.
  789. const offset = await this.textSequenceModeOffset_;
  790. this.textEngine_.setTimestampOffset(offset);
  791. }
  792. await this.textEngine_.appendBuffer(
  793. data,
  794. reference ? reference.startTime : null,
  795. reference ? reference.endTime : null,
  796. reference ? reference.getUris()[0] : null);
  797. return;
  798. }
  799. if (!fromSplit && this.needSplitMuxedContent_) {
  800. await this.appendBuffer(ContentType.AUDIO, data, reference, stream,
  801. hasClosedCaptions, seeked, adaptation, isChunkedData,
  802. /* fromSplit= */ true);
  803. await this.appendBuffer(ContentType.VIDEO, data, reference, stream,
  804. hasClosedCaptions, seeked, adaptation, isChunkedData,
  805. /* fromSplit= */ true);
  806. return;
  807. }
  808. if (!this.sourceBuffers_[contentType]) {
  809. shaka.log.warning('Attempted to restore a non-existent source buffer');
  810. return;
  811. }
  812. let timestampOffset = this.sourceBuffers_[contentType].timestampOffset;
  813. let mimeType = this.sourceBufferTypes_[contentType];
  814. if (this.transmuxers_[contentType]) {
  815. mimeType = this.transmuxers_[contentType].getOriginalMimeType();
  816. }
  817. if (reference) {
  818. const timestamp = this.getTimestampAndDispatchMetadata_(
  819. contentType, data, reference, mimeType, timestampOffset);
  820. if (timestamp != null) {
  821. const calculatedTimestampOffset = reference.startTime - timestamp;
  822. const timestampOffsetDifference =
  823. Math.abs(timestampOffset - calculatedTimestampOffset);
  824. if ((timestampOffsetDifference >= 0.001 || seeked || adaptation) &&
  825. (!isChunkedData || calculatedTimestampOffset > 0 ||
  826. !timestampOffset)) {
  827. timestampOffset = calculatedTimestampOffset;
  828. if (this.attemptTimestampOffsetCalculation_) {
  829. this.enqueueOperation_(
  830. contentType,
  831. () => this.abort_(contentType));
  832. this.enqueueOperation_(
  833. contentType,
  834. () => this.setTimestampOffset_(contentType, timestampOffset));
  835. }
  836. }
  837. // Timestamps can only be reliably extracted from video, not audio.
  838. // Packed audio formats do not have internal timestamps at all.
  839. // Prefer video for this when available.
  840. const isBestSourceBufferForTimestamps =
  841. contentType == ContentType.VIDEO ||
  842. !(ContentType.VIDEO in this.sourceBuffers_);
  843. if (this.sequenceMode_ && isBestSourceBufferForTimestamps) {
  844. this.textSequenceModeOffset_.resolve(timestampOffset);
  845. }
  846. }
  847. }
  848. if (hasClosedCaptions && contentType == ContentType.VIDEO) {
  849. if (!this.textEngine_) {
  850. this.reinitText(shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE,
  851. this.sequenceMode_, /* external= */ false);
  852. }
  853. if (!this.captionParser_) {
  854. const basicType = mimeType.split(';', 1)[0];
  855. this.captionParser_ = this.getCaptionParser(basicType);
  856. }
  857. // If it is the init segment for closed captions, initialize the closed
  858. // caption parser.
  859. if (!reference) {
  860. this.captionParser_.init(data, adaptation);
  861. } else {
  862. const closedCaptions = this.captionParser_.parseFrom(data);
  863. if (closedCaptions.length) {
  864. this.textEngine_.storeAndAppendClosedCaptions(
  865. closedCaptions,
  866. reference.startTime,
  867. reference.endTime,
  868. timestampOffset);
  869. }
  870. }
  871. }
  872. if (this.transmuxers_[contentType]) {
  873. data = await this.transmuxers_[contentType].transmux(
  874. data, stream, reference, this.mediaSource_.duration, contentType);
  875. }
  876. data = this.workAroundBrokenPlatforms_(
  877. data, reference ? reference.startTime : null, contentType);
  878. if (reference && this.sequenceMode_ && contentType != ContentType.TEXT) {
  879. // In sequence mode, for non-text streams, if we just cleared the buffer
  880. // and are either performing an unbuffered seek or handling an automatic
  881. // adaptation, we need to set a new timestampOffset on the sourceBuffer.
  882. if (seeked || adaptation) {
  883. const timestampOffset = reference.startTime;
  884. // The logic to call abort() before setting the timestampOffset is
  885. // extended during unbuffered seeks or automatic adaptations; it is
  886. // possible for the append state to be PARSING_MEDIA_SEGMENT from the
  887. // previous SourceBuffer#appendBuffer() call.
  888. this.enqueueOperation_(contentType, () => this.abort_(contentType));
  889. this.enqueueOperation_(
  890. contentType,
  891. () => this.setTimestampOffset_(contentType, timestampOffset));
  892. }
  893. }
  894. let bufferedBefore = null;
  895. await this.enqueueOperation_(contentType, () => {
  896. if (goog.DEBUG && reference && !reference.isPreload() && !isChunkedData) {
  897. bufferedBefore = this.getBuffered_(contentType);
  898. }
  899. this.append_(contentType, data, timestampOffset);
  900. });
  901. if (goog.DEBUG && reference && !reference.isPreload() && !isChunkedData) {
  902. const bufferedAfter = this.getBuffered_(contentType);
  903. const newBuffered = shaka.media.TimeRangesUtils.computeAddedRange(
  904. bufferedBefore, bufferedAfter);
  905. if (newBuffered) {
  906. const segmentDuration = reference.endTime - reference.startTime;
  907. // Check end times instead of start times. We may be overwriting a
  908. // buffer and only the end changes, and that would be fine.
  909. // Also, exclude tiny segments. Sometimes alignment segments as small
  910. // as 33ms are seen in Google DAI content. For such tiny segments,
  911. // half a segment duration would be no issue.
  912. const offset = Math.abs(newBuffered.end - reference.endTime);
  913. if (segmentDuration > 0.100 && offset > segmentDuration / 2) {
  914. shaka.log.error('Possible encoding problem detected!',
  915. 'Unexpected buffered range for reference', reference,
  916. 'from URIs', reference.getUris(),
  917. 'should be', {start: reference.startTime, end: reference.endTime},
  918. 'but got', newBuffered);
  919. }
  920. }
  921. }
  922. }
  923. /**
  924. * Set the selected closed captions Id and language.
  925. *
  926. * @param {string} id
  927. */
  928. setSelectedClosedCaptionId(id) {
  929. const VIDEO = shaka.util.ManifestParserUtils.ContentType.VIDEO;
  930. const videoBufferEndTime = this.bufferEnd(VIDEO) || 0;
  931. this.textEngine_.setSelectedClosedCaptionId(id, videoBufferEndTime);
  932. }
  933. /** Disable embedded closed captions. */
  934. clearSelectedClosedCaptionId() {
  935. if (this.textEngine_) {
  936. this.textEngine_.setSelectedClosedCaptionId('', 0);
  937. }
  938. }
  939. /**
  940. * Enqueue an operation to remove data from the SourceBuffer.
  941. *
  942. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  943. * @param {number} startTime relative to the start of the presentation
  944. * @param {number} endTime relative to the start of the presentation
  945. * @return {!Promise}
  946. */
  947. async remove(contentType, startTime, endTime) {
  948. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  949. if (contentType == ContentType.TEXT) {
  950. await this.textEngine_.remove(startTime, endTime);
  951. } else {
  952. await this.enqueueOperation_(
  953. contentType,
  954. () => this.remove_(contentType, startTime, endTime));
  955. if (this.needSplitMuxedContent_) {
  956. await this.enqueueOperation_(
  957. ContentType.AUDIO,
  958. () => this.remove_(ContentType.AUDIO, startTime, endTime));
  959. }
  960. }
  961. }
  962. /**
  963. * Enqueue an operation to clear the SourceBuffer.
  964. *
  965. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  966. * @return {!Promise}
  967. */
  968. async clear(contentType) {
  969. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  970. if (contentType == ContentType.TEXT) {
  971. if (!this.textEngine_) {
  972. return;
  973. }
  974. await this.textEngine_.remove(0, Infinity);
  975. } else {
  976. // Note that not all platforms allow clearing to Infinity.
  977. await this.enqueueOperation_(
  978. contentType,
  979. () => this.remove_(contentType, 0, this.mediaSource_.duration));
  980. if (this.needSplitMuxedContent_) {
  981. await this.enqueueOperation_(
  982. ContentType.AUDIO,
  983. () => this.remove_(
  984. ContentType.AUDIO, 0, this.mediaSource_.duration));
  985. }
  986. }
  987. }
  988. /**
  989. * Fully reset the state of the caption parser owned by MediaSourceEngine.
  990. */
  991. resetCaptionParser() {
  992. if (this.captionParser_) {
  993. this.captionParser_.reset();
  994. }
  995. }
  996. /**
  997. * Enqueue an operation to flush the SourceBuffer.
  998. * This is a workaround for what we believe is a Chromecast bug.
  999. *
  1000. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1001. * @return {!Promise}
  1002. */
  1003. async flush(contentType) {
  1004. // Flush the pipeline. Necessary on Chromecast, even though we have removed
  1005. // everything.
  1006. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1007. if (contentType == ContentType.TEXT) {
  1008. // Nothing to flush for text.
  1009. return;
  1010. }
  1011. await this.enqueueOperation_(
  1012. contentType,
  1013. () => this.flush_(contentType));
  1014. if (this.needSplitMuxedContent_) {
  1015. await this.enqueueOperation_(
  1016. ContentType.AUDIO,
  1017. () => this.flush_(ContentType.AUDIO));
  1018. }
  1019. }
  1020. /**
  1021. * Sets the timestamp offset and append window end for the given content type.
  1022. *
  1023. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1024. * @param {number} timestampOffset The timestamp offset. Segments which start
  1025. * at time t will be inserted at time t + timestampOffset instead. This
  1026. * value does not affect segments which have already been inserted.
  1027. * @param {number} appendWindowStart The timestamp to set the append window
  1028. * start to. For future appends, frames/samples with timestamps less than
  1029. * this value will be dropped.
  1030. * @param {number} appendWindowEnd The timestamp to set the append window end
  1031. * to. For future appends, frames/samples with timestamps greater than this
  1032. * value will be dropped.
  1033. * @param {boolean} ignoreTimestampOffset If true, the timestampOffset will
  1034. * not be applied in this step.
  1035. * @param {string} mimeType
  1036. * @param {string} codecs
  1037. * @param {!Map.<shaka.util.ManifestParserUtils.ContentType,
  1038. * shaka.extern.Stream>} streamsByType
  1039. * A map of content types to streams. All streams must be supported
  1040. * according to MediaSourceEngine.isStreamSupported.
  1041. *
  1042. * @return {!Promise}
  1043. */
  1044. async setStreamProperties(
  1045. contentType, timestampOffset, appendWindowStart, appendWindowEnd,
  1046. ignoreTimestampOffset, mimeType, codecs, streamsByType) {
  1047. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1048. if (contentType == ContentType.TEXT) {
  1049. if (!ignoreTimestampOffset) {
  1050. this.textEngine_.setTimestampOffset(timestampOffset);
  1051. }
  1052. this.textEngine_.setAppendWindow(appendWindowStart, appendWindowEnd);
  1053. return;
  1054. }
  1055. const operations = [];
  1056. const hasChangedCodecs = await this.codecSwitchIfNecessary_(
  1057. contentType, mimeType, codecs, streamsByType);
  1058. if (!hasChangedCodecs) {
  1059. // Queue an abort() to help MSE splice together overlapping segments.
  1060. // We set appendWindowEnd when we change periods in DASH content, and the
  1061. // period transition may result in overlap.
  1062. //
  1063. // An abort() also helps with MPEG2-TS. When we append a TS segment, we
  1064. // always enter a PARSING_MEDIA_SEGMENT state and we can't change the
  1065. // timestamp offset. By calling abort(), we reset the state so we can
  1066. // set it.
  1067. operations.push(this.enqueueOperation_(
  1068. contentType,
  1069. () => this.abort_(contentType)));
  1070. if (this.needSplitMuxedContent_) {
  1071. operations.push(this.enqueueOperation_(
  1072. ContentType.AUDIO,
  1073. () => this.abort_(ContentType.AUDIO)));
  1074. }
  1075. }
  1076. if (!ignoreTimestampOffset) {
  1077. operations.push(this.enqueueOperation_(
  1078. contentType,
  1079. () => this.setTimestampOffset_(contentType, timestampOffset)));
  1080. if (this.needSplitMuxedContent_) {
  1081. operations.push(this.enqueueOperation_(
  1082. ContentType.AUDIO,
  1083. () => this.setTimestampOffset_(
  1084. ContentType.AUDIO, timestampOffset)));
  1085. }
  1086. }
  1087. operations.push(this.enqueueOperation_(
  1088. contentType,
  1089. () => this.setAppendWindow_(
  1090. contentType, appendWindowStart, appendWindowEnd)));
  1091. if (this.needSplitMuxedContent_) {
  1092. operations.push(this.enqueueOperation_(
  1093. ContentType.AUDIO,
  1094. () => this.setAppendWindow_(
  1095. ContentType.AUDIO, appendWindowStart, appendWindowEnd)));
  1096. }
  1097. await Promise.all(operations);
  1098. }
  1099. /**
  1100. * Adjust timestamp offset to maintain AV sync across discontinuities.
  1101. *
  1102. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1103. * @param {number} timestampOffset
  1104. * @return {!Promise}
  1105. */
  1106. async resync(contentType, timestampOffset) {
  1107. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1108. if (contentType == ContentType.TEXT) {
  1109. // This operation is for audio and video only.
  1110. return;
  1111. }
  1112. // Reset the promise in case the timestamp offset changed during
  1113. // a period/discontinuity transition.
  1114. if (contentType == ContentType.VIDEO) {
  1115. this.textSequenceModeOffset_ = new shaka.util.PublicPromise();
  1116. }
  1117. // Queue an abort() to help MSE splice together overlapping segments.
  1118. // We set appendWindowEnd when we change periods in DASH content, and the
  1119. // period transition may result in overlap.
  1120. //
  1121. // An abort() also helps with MPEG2-TS. When we append a TS segment, we
  1122. // always enter a PARSING_MEDIA_SEGMENT state and we can't change the
  1123. // timestamp offset. By calling abort(), we reset the state so we can
  1124. // set it.
  1125. this.enqueueOperation_(
  1126. contentType,
  1127. () => this.abort_(contentType));
  1128. if (this.needSplitMuxedContent_) {
  1129. this.enqueueOperation_(
  1130. ContentType.AUDIO,
  1131. () => this.abort_(ContentType.AUDIO));
  1132. }
  1133. await this.enqueueOperation_(
  1134. contentType,
  1135. () => this.setTimestampOffset_(contentType, timestampOffset));
  1136. if (this.needSplitMuxedContent_) {
  1137. await this.enqueueOperation_(
  1138. ContentType.AUDIO,
  1139. () => this.setTimestampOffset_(ContentType.AUDIO, timestampOffset));
  1140. }
  1141. }
  1142. /**
  1143. * @param {string=} reason Valid reasons are 'network' and 'decode'.
  1144. * @return {!Promise}
  1145. * @see http://w3c.github.io/media-source/#idl-def-EndOfStreamError
  1146. */
  1147. async endOfStream(reason) {
  1148. await this.enqueueBlockingOperation_(() => {
  1149. // If endOfStream() has already been called on the media source,
  1150. // don't call it again. Also do not call if readyState is
  1151. // 'closed' (not attached to video element) since it is not a
  1152. // valid operation.
  1153. if (this.ended() || this.mediaSource_.readyState === 'closed') {
  1154. return;
  1155. }
  1156. // Tizen won't let us pass undefined, but it will let us omit the
  1157. // argument.
  1158. if (reason) {
  1159. this.mediaSource_.endOfStream(reason);
  1160. } else {
  1161. this.mediaSource_.endOfStream();
  1162. }
  1163. });
  1164. }
  1165. /**
  1166. * @param {number} duration
  1167. * @return {!Promise}
  1168. */
  1169. async setDuration(duration) {
  1170. await this.enqueueBlockingOperation_(() => {
  1171. // Reducing the duration causes the MSE removal algorithm to run, which
  1172. // triggers an 'updateend' event to fire. To handle this scenario, we
  1173. // have to insert a dummy operation into the beginning of each queue,
  1174. // which the 'updateend' handler will remove.
  1175. if (duration < this.mediaSource_.duration) {
  1176. for (const contentType in this.sourceBuffers_) {
  1177. const dummyOperation = {
  1178. start: () => {},
  1179. p: new shaka.util.PublicPromise(),
  1180. };
  1181. this.queues_[contentType].unshift(dummyOperation);
  1182. }
  1183. }
  1184. this.mediaSource_.duration = duration;
  1185. this.lastDuration_ = duration;
  1186. });
  1187. }
  1188. /**
  1189. * Get the current MediaSource duration.
  1190. *
  1191. * @return {number}
  1192. */
  1193. getDuration() {
  1194. return this.mediaSource_.duration;
  1195. }
  1196. /**
  1197. * Append data to the SourceBuffer.
  1198. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1199. * @param {BufferSource} data
  1200. * @param {number} timestampOffset
  1201. * @private
  1202. */
  1203. append_(contentType, data, timestampOffset) {
  1204. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1205. // Append only video data to the LCEVC Dec.
  1206. if (contentType == ContentType.VIDEO && this.lcevcDec_) {
  1207. // Append video buffers to the LCEVC Dec for parsing and storing
  1208. // of LCEVC data.
  1209. this.lcevcDec_.appendBuffer(data, timestampOffset);
  1210. }
  1211. // This will trigger an 'updateend' event.
  1212. this.sourceBuffers_[contentType].appendBuffer(data);
  1213. }
  1214. /**
  1215. * Remove data from the SourceBuffer.
  1216. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1217. * @param {number} startTime relative to the start of the presentation
  1218. * @param {number} endTime relative to the start of the presentation
  1219. * @private
  1220. */
  1221. remove_(contentType, startTime, endTime) {
  1222. if (endTime <= startTime) {
  1223. // Ignore removal of inverted or empty ranges.
  1224. // Fake 'updateend' event to resolve the operation.
  1225. this.onUpdateEnd_(contentType);
  1226. return;
  1227. }
  1228. // This will trigger an 'updateend' event.
  1229. this.sourceBuffers_[contentType].remove(startTime, endTime);
  1230. }
  1231. /**
  1232. * Call abort() on the SourceBuffer.
  1233. * This resets MSE's last_decode_timestamp on all track buffers, which should
  1234. * trigger the splicing logic for overlapping segments.
  1235. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1236. * @private
  1237. */
  1238. abort_(contentType) {
  1239. // Save the append window, which is reset on abort().
  1240. const appendWindowStart =
  1241. this.sourceBuffers_[contentType].appendWindowStart;
  1242. const appendWindowEnd = this.sourceBuffers_[contentType].appendWindowEnd;
  1243. // This will not trigger an 'updateend' event, since nothing is happening.
  1244. // This is only to reset MSE internals, not to abort an actual operation.
  1245. this.sourceBuffers_[contentType].abort();
  1246. // Restore the append window.
  1247. this.sourceBuffers_[contentType].appendWindowStart = appendWindowStart;
  1248. this.sourceBuffers_[contentType].appendWindowEnd = appendWindowEnd;
  1249. // Fake an 'updateend' event to resolve the operation.
  1250. this.onUpdateEnd_(contentType);
  1251. }
  1252. /**
  1253. * Nudge the playhead to force the media pipeline to be flushed.
  1254. * This seems to be necessary on Chromecast to get new content to replace old
  1255. * content.
  1256. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1257. * @private
  1258. */
  1259. flush_(contentType) {
  1260. // Never use flush_ if there's data. It causes a hiccup in playback.
  1261. goog.asserts.assert(
  1262. this.video_.buffered.length == 0, 'MediaSourceEngine.flush_ should ' +
  1263. 'only be used after clearing all data!');
  1264. // Seeking forces the pipeline to be flushed.
  1265. this.video_.currentTime -= 0.001;
  1266. // Fake an 'updateend' event to resolve the operation.
  1267. this.onUpdateEnd_(contentType);
  1268. }
  1269. /**
  1270. * Set the SourceBuffer's timestamp offset.
  1271. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1272. * @param {number} timestampOffset
  1273. * @private
  1274. */
  1275. setTimestampOffset_(contentType, timestampOffset) {
  1276. // Work around for
  1277. // https://github.com/shaka-project/shaka-player/issues/1281:
  1278. // TODO(https://bit.ly/2ttKiBU): follow up when this is fixed in Edge
  1279. if (timestampOffset < 0) {
  1280. // Try to prevent rounding errors in Edge from removing the first
  1281. // keyframe.
  1282. timestampOffset += 0.001;
  1283. }
  1284. this.sourceBuffers_[contentType].timestampOffset = timestampOffset;
  1285. // Fake an 'updateend' event to resolve the operation.
  1286. this.onUpdateEnd_(contentType);
  1287. }
  1288. /**
  1289. * Set the SourceBuffer's append window end.
  1290. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1291. * @param {number} appendWindowStart
  1292. * @param {number} appendWindowEnd
  1293. * @private
  1294. */
  1295. setAppendWindow_(contentType, appendWindowStart, appendWindowEnd) {
  1296. // You can't set start > end, so first set start to 0, then set the new
  1297. // end, then set the new start. That way, there are no intermediate
  1298. // states which are invalid.
  1299. this.sourceBuffers_[contentType].appendWindowStart = 0;
  1300. this.sourceBuffers_[contentType].appendWindowEnd = appendWindowEnd;
  1301. this.sourceBuffers_[contentType].appendWindowStart = appendWindowStart;
  1302. // Fake an 'updateend' event to resolve the operation.
  1303. this.onUpdateEnd_(contentType);
  1304. }
  1305. /**
  1306. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1307. * @private
  1308. */
  1309. onError_(contentType) {
  1310. const operation = this.queues_[contentType][0];
  1311. goog.asserts.assert(operation, 'Spurious error event!');
  1312. goog.asserts.assert(!this.sourceBuffers_[contentType].updating,
  1313. 'SourceBuffer should not be updating on error!');
  1314. const code = this.video_.error ? this.video_.error.code : 0;
  1315. operation.p.reject(new shaka.util.Error(
  1316. shaka.util.Error.Severity.CRITICAL,
  1317. shaka.util.Error.Category.MEDIA,
  1318. shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED,
  1319. code));
  1320. // Do not pop from queue. An 'updateend' event will fire next, and to
  1321. // avoid synchronizing these two event handlers, we will allow that one to
  1322. // pop from the queue as normal. Note that because the operation has
  1323. // already been rejected, the call to resolve() in the 'updateend' handler
  1324. // will have no effect.
  1325. }
  1326. /**
  1327. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1328. * @private
  1329. */
  1330. onUpdateEnd_(contentType) {
  1331. if (this.reloadingMediaSource_) {
  1332. return;
  1333. }
  1334. const operation = this.queues_[contentType][0];
  1335. goog.asserts.assert(operation, 'Spurious updateend event!');
  1336. if (!operation) {
  1337. return;
  1338. }
  1339. goog.asserts.assert(!this.sourceBuffers_[contentType].updating,
  1340. 'SourceBuffer should not be updating on updateend!');
  1341. operation.p.resolve();
  1342. this.popFromQueue_(contentType);
  1343. }
  1344. /**
  1345. * Enqueue an operation and start it if appropriate.
  1346. *
  1347. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1348. * @param {function()} start
  1349. * @return {!Promise}
  1350. * @private
  1351. */
  1352. enqueueOperation_(contentType, start) {
  1353. this.destroyer_.ensureNotDestroyed();
  1354. const operation = {
  1355. start: start,
  1356. p: new shaka.util.PublicPromise(),
  1357. };
  1358. this.queues_[contentType].push(operation);
  1359. if (this.queues_[contentType].length == 1) {
  1360. this.startOperation_(contentType);
  1361. }
  1362. return operation.p;
  1363. }
  1364. /**
  1365. * Enqueue an operation which must block all other operations on all
  1366. * SourceBuffers.
  1367. *
  1368. * @param {function():(Promise|undefined)} run
  1369. * @return {!Promise}
  1370. * @private
  1371. */
  1372. async enqueueBlockingOperation_(run) {
  1373. this.destroyer_.ensureNotDestroyed();
  1374. /** @type {!Array.<!shaka.util.PublicPromise>} */
  1375. const allWaiters = [];
  1376. // Enqueue a 'wait' operation onto each queue.
  1377. // This operation signals its readiness when it starts.
  1378. // When all wait operations are ready, the real operation takes place.
  1379. for (const contentType in this.sourceBuffers_) {
  1380. const ready = new shaka.util.PublicPromise();
  1381. const operation = {
  1382. start: () => ready.resolve(),
  1383. p: ready,
  1384. };
  1385. this.queues_[contentType].push(operation);
  1386. allWaiters.push(ready);
  1387. if (this.queues_[contentType].length == 1) {
  1388. operation.start();
  1389. }
  1390. }
  1391. // Return a Promise to the real operation, which waits to begin until
  1392. // there are no other in-progress operations on any SourceBuffers.
  1393. try {
  1394. await Promise.all(allWaiters);
  1395. } catch (error) {
  1396. // One of the waiters failed, which means we've been destroyed.
  1397. goog.asserts.assert(
  1398. this.destroyer_.destroyed(), 'Should be destroyed by now');
  1399. // We haven't popped from the queue. Canceled waiters have been removed
  1400. // by destroy. What's left now should just be resolved waiters. In
  1401. // uncompiled mode, we will maintain good hygiene and make sure the
  1402. // assert at the end of destroy passes. In compiled mode, the queues
  1403. // are wiped in destroy.
  1404. if (goog.DEBUG) {
  1405. for (const contentType in this.sourceBuffers_) {
  1406. if (this.queues_[contentType].length) {
  1407. goog.asserts.assert(
  1408. this.queues_[contentType].length == 1,
  1409. 'Should be at most one item in queue!');
  1410. goog.asserts.assert(
  1411. allWaiters.includes(this.queues_[contentType][0].p),
  1412. 'The item in queue should be one of our waiters!');
  1413. this.queues_[contentType].shift();
  1414. }
  1415. }
  1416. }
  1417. throw error;
  1418. }
  1419. if (goog.DEBUG) {
  1420. // If we did it correctly, nothing is updating.
  1421. for (const contentType in this.sourceBuffers_) {
  1422. goog.asserts.assert(
  1423. this.sourceBuffers_[contentType].updating == false,
  1424. 'SourceBuffers should not be updating after a blocking op!');
  1425. }
  1426. }
  1427. // Run the real operation, which can be asynchronous.
  1428. try {
  1429. await run();
  1430. } catch (exception) {
  1431. throw new shaka.util.Error(
  1432. shaka.util.Error.Severity.CRITICAL,
  1433. shaka.util.Error.Category.MEDIA,
  1434. shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,
  1435. exception,
  1436. this.video_.error || 'No error in the media element');
  1437. } finally {
  1438. // Unblock the queues.
  1439. for (const contentType in this.sourceBuffers_) {
  1440. this.popFromQueue_(contentType);
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * Pop from the front of the queue and start a new operation.
  1446. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1447. * @private
  1448. */
  1449. popFromQueue_(contentType) {
  1450. // Remove the in-progress operation, which is now complete.
  1451. this.queues_[contentType].shift();
  1452. this.startOperation_(contentType);
  1453. }
  1454. /**
  1455. * Starts the next operation in the queue.
  1456. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1457. * @private
  1458. */
  1459. startOperation_(contentType) {
  1460. // Retrieve the next operation, if any, from the queue and start it.
  1461. const next = this.queues_[contentType][0];
  1462. if (next) {
  1463. try {
  1464. next.start();
  1465. } catch (exception) {
  1466. if (exception.name == 'QuotaExceededError') {
  1467. next.p.reject(new shaka.util.Error(
  1468. shaka.util.Error.Severity.CRITICAL,
  1469. shaka.util.Error.Category.MEDIA,
  1470. shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR,
  1471. contentType));
  1472. } else {
  1473. next.p.reject(new shaka.util.Error(
  1474. shaka.util.Error.Severity.CRITICAL,
  1475. shaka.util.Error.Category.MEDIA,
  1476. shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,
  1477. exception,
  1478. this.video_.error || 'No error in the media element'));
  1479. }
  1480. this.popFromQueue_(contentType);
  1481. }
  1482. }
  1483. }
  1484. /**
  1485. * @return {!shaka.extern.TextDisplayer}
  1486. */
  1487. getTextDisplayer() {
  1488. goog.asserts.assert(
  1489. this.textDisplayer_,
  1490. 'TextDisplayer should only be null when this is destroyed');
  1491. return this.textDisplayer_;
  1492. }
  1493. /**
  1494. * @param {!shaka.extern.TextDisplayer} textDisplayer
  1495. */
  1496. setTextDisplayer(textDisplayer) {
  1497. const oldTextDisplayer = this.textDisplayer_;
  1498. this.textDisplayer_ = textDisplayer;
  1499. if (oldTextDisplayer) {
  1500. textDisplayer.setTextVisibility(oldTextDisplayer.isTextVisible());
  1501. oldTextDisplayer.destroy();
  1502. }
  1503. if (this.textEngine_) {
  1504. this.textEngine_.setDisplayer(textDisplayer);
  1505. }
  1506. }
  1507. /**
  1508. * @param {boolean} segmentRelativeVttTiming
  1509. */
  1510. setSegmentRelativeVttTiming(segmentRelativeVttTiming) {
  1511. this.segmentRelativeVttTiming_ = segmentRelativeVttTiming;
  1512. }
  1513. /**
  1514. * Apply platform-specific transformations to this segment to work around
  1515. * issues in the platform.
  1516. *
  1517. * @param {!BufferSource} segment
  1518. * @param {?number} startTime
  1519. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1520. * @return {!BufferSource}
  1521. * @private
  1522. */
  1523. workAroundBrokenPlatforms_(segment, startTime, contentType) {
  1524. const isInitSegment = startTime == null;
  1525. const encryptionExpected = this.expectedEncryption_[contentType];
  1526. // If:
  1527. // 1. the configuration tells to insert fake encryption,
  1528. // 2. and this is an init segment,
  1529. // 3. and encryption is expected,
  1530. // 4. and the platform requires encryption in all init segments,
  1531. // 5. and the content is MP4 (mimeType == "video/mp4" or "audio/mp4"),
  1532. // then insert fake encryption metadata for init segments that lack it.
  1533. // The MP4 requirement is because we can currently only do this
  1534. // transformation on MP4 containers.
  1535. // See: https://github.com/shaka-project/shaka-player/issues/2759
  1536. if (this.config_.insertFakeEncryptionInInit &&
  1537. isInitSegment &&
  1538. encryptionExpected &&
  1539. shaka.util.Platform.requiresEncryptionInfoInAllInitSegments() &&
  1540. shaka.util.MimeUtils.getContainerType(
  1541. this.sourceBufferTypes_[contentType]) == 'mp4') {
  1542. shaka.log.debug('Forcing fake encryption information in init segment.');
  1543. segment = shaka.media.ContentWorkarounds.fakeEncryption(segment);
  1544. }
  1545. return segment;
  1546. }
  1547. /**
  1548. * Prepare the SourceBuffer to parse a potentially new type or codec.
  1549. *
  1550. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1551. * @param {string} mimeType
  1552. * @param {?shaka.extern.Transmuxer} transmuxer
  1553. * @private
  1554. */
  1555. change_(contentType, mimeType, transmuxer) {
  1556. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1557. if (contentType === ContentType.TEXT) {
  1558. shaka.log.debug(`Change not supported for ${contentType}`);
  1559. return;
  1560. }
  1561. shaka.log.debug(
  1562. `Change Type: ${this.sourceBufferTypes_[contentType]} -> ${mimeType}`);
  1563. if (shaka.media.Capabilities.isChangeTypeSupported()) {
  1564. if (this.transmuxers_[contentType]) {
  1565. this.transmuxers_[contentType].destroy();
  1566. delete this.transmuxers_[contentType];
  1567. }
  1568. if (transmuxer) {
  1569. this.transmuxers_[contentType] = transmuxer;
  1570. }
  1571. const type = this.addExtraFeaturesToMimeType_(mimeType);
  1572. this.sourceBuffers_[contentType].changeType(type);
  1573. this.sourceBufferTypes_[contentType] = mimeType;
  1574. } else {
  1575. shaka.log.debug('Change Type not supported');
  1576. }
  1577. // Fake an 'updateend' event to resolve the operation.
  1578. this.onUpdateEnd_(contentType);
  1579. }
  1580. /**
  1581. * Enqueue an operation to prepare the SourceBuffer to parse a potentially new
  1582. * type or codec.
  1583. *
  1584. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1585. * @param {string} mimeType
  1586. * @param {?shaka.extern.Transmuxer} transmuxer
  1587. * @return {!Promise}
  1588. */
  1589. changeType(contentType, mimeType, transmuxer) {
  1590. return this.enqueueOperation_(
  1591. contentType,
  1592. () => this.change_(contentType, mimeType, transmuxer));
  1593. }
  1594. /**
  1595. * Resets the MediaSource and re-adds source buffers due to codec mismatch
  1596. *
  1597. * @param {!Map.<shaka.util.ManifestParserUtils.ContentType,
  1598. * shaka.extern.Stream>} streamsByType
  1599. * @private
  1600. */
  1601. async reset_(streamsByType) {
  1602. const Functional = shaka.util.Functional;
  1603. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1604. this.reloadingMediaSource_ = true;
  1605. this.needSplitMuxedContent_ = false;
  1606. const currentTime = this.video_.currentTime;
  1607. // When codec switching if the user is currently paused we don't want
  1608. // to trigger a play when switching codec.
  1609. // Playing can also end up in a paused state after a codec switch
  1610. // so we need to remember the current states.
  1611. const previousAutoPlayState = this.video_.autoplay;
  1612. const previousPausedState = this.video_.paused;
  1613. if (this.playbackHasBegun_) {
  1614. // Only set autoplay to false if the video playback has already begun.
  1615. // When a codec switch happens before playback has begun this can cause
  1616. // autoplay not to work as expected.
  1617. this.video_.autoplay = false;
  1618. }
  1619. try {
  1620. this.eventManager_.removeAll();
  1621. const cleanup = [];
  1622. for (const contentType in this.transmuxers_) {
  1623. cleanup.push(this.transmuxers_[contentType].destroy());
  1624. }
  1625. for (const contentType in this.queues_) {
  1626. // Make a local copy of the queue and the first item.
  1627. const q = this.queues_[contentType];
  1628. const inProgress = q[0];
  1629. // Drop everything else out of the original queue.
  1630. this.queues_[contentType] = q.slice(0, 1);
  1631. // We will wait for this item to complete/fail.
  1632. if (inProgress) {
  1633. cleanup.push(inProgress.p.catch(Functional.noop));
  1634. }
  1635. // The rest will be rejected silently if possible.
  1636. for (const item of q.slice(1)) {
  1637. item.p.reject(shaka.util.Destroyer.destroyedError());
  1638. }
  1639. }
  1640. for (const contentType in this.sourceBuffers_) {
  1641. const sourceBuffer = this.sourceBuffers_[contentType];
  1642. try {
  1643. this.mediaSource_.removeSourceBuffer(sourceBuffer);
  1644. } catch (e) {}
  1645. }
  1646. await Promise.all(cleanup);
  1647. this.transmuxers_ = {};
  1648. this.sourceBuffers_ = {};
  1649. const previousDuration = this.mediaSource_.duration;
  1650. this.mediaSourceOpen_ = new shaka.util.PublicPromise();
  1651. this.mediaSource_ = this.createMediaSource(this.mediaSourceOpen_);
  1652. await this.mediaSourceOpen_;
  1653. if (!isNaN(previousDuration) && previousDuration) {
  1654. this.mediaSource_.duration = previousDuration;
  1655. } else if (!isNaN(this.lastDuration_) && this.lastDuration_) {
  1656. this.mediaSource_.duration = this.lastDuration_;
  1657. }
  1658. const sourceBufferAdded = new shaka.util.PublicPromise();
  1659. const sourceBuffers =
  1660. /** @type {EventTarget} */(this.mediaSource_.sourceBuffers);
  1661. const totalOfBuffers = streamsByType.size;
  1662. let numberOfSourceBufferAdded = 0;
  1663. const onSourceBufferAdded = () => {
  1664. numberOfSourceBufferAdded++;
  1665. if (numberOfSourceBufferAdded === totalOfBuffers) {
  1666. sourceBufferAdded.resolve();
  1667. this.eventManager_.unlisten(sourceBuffers, 'addsourcebuffer',
  1668. onSourceBufferAdded);
  1669. }
  1670. };
  1671. this.eventManager_.listen(sourceBuffers, 'addsourcebuffer',
  1672. onSourceBufferAdded);
  1673. for (const contentType of streamsByType.keys()) {
  1674. const stream = streamsByType.get(contentType);
  1675. // eslint-disable-next-line no-await-in-loop
  1676. await this.initSourceBuffer_(contentType, stream, stream.codecs);
  1677. if (this.needSplitMuxedContent_) {
  1678. this.queues_[ContentType.AUDIO] = [];
  1679. this.queues_[ContentType.VIDEO] = [];
  1680. } else {
  1681. this.queues_[contentType] = [];
  1682. }
  1683. }
  1684. // Fake a seek to catchup the playhead.
  1685. this.video_.currentTime = currentTime;
  1686. await sourceBufferAdded;
  1687. } finally {
  1688. this.reloadingMediaSource_ = false;
  1689. this.destroyer_.ensureNotDestroyed();
  1690. this.eventManager_.listenOnce(this.video_, 'canplaythrough', () => {
  1691. // Don't use ensureNotDestroyed() from this event listener, because
  1692. // that results in an uncaught exception. Instead, just check the
  1693. // flag.
  1694. if (this.destroyer_.destroyed()) {
  1695. return;
  1696. }
  1697. this.video_.autoplay = previousAutoPlayState;
  1698. if (!previousPausedState) {
  1699. this.video_.play();
  1700. }
  1701. });
  1702. }
  1703. }
  1704. /**
  1705. * Resets the Media Source
  1706. * @param {!Map.<shaka.util.ManifestParserUtils.ContentType,
  1707. * shaka.extern.Stream>} streamsByType
  1708. * @return {!Promise}
  1709. */
  1710. reset(streamsByType) {
  1711. return this.enqueueBlockingOperation_(
  1712. () => this.reset_(streamsByType));
  1713. }
  1714. /**
  1715. * Codec switch if necessary, this will not resolve until the codec
  1716. * switch is over.
  1717. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1718. * @param {string} mimeType
  1719. * @param {string} codecs
  1720. * @param {!Map.<shaka.util.ManifestParserUtils.ContentType,
  1721. * shaka.extern.Stream>} streamsByType
  1722. * @return {!Promise.<boolean>} true if there was a codec switch,
  1723. * false otherwise.
  1724. * @private
  1725. */
  1726. async codecSwitchIfNecessary_(contentType, mimeType, codecs, streamsByType) {
  1727. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1728. if (contentType == ContentType.TEXT) {
  1729. return false;
  1730. }
  1731. const MimeUtils = shaka.util.MimeUtils;
  1732. const currentCodec = MimeUtils.getCodecBase(
  1733. MimeUtils.getCodecs(this.sourceBufferTypes_[contentType]));
  1734. const currentBasicType = MimeUtils.getBasicType(
  1735. this.sourceBufferTypes_[contentType]);
  1736. /** @type {?shaka.extern.Transmuxer} */
  1737. let transmuxer;
  1738. let transmuxerMuxed = false;
  1739. let newMimeType = shaka.util.MimeUtils.getFullType(mimeType, codecs);
  1740. let needTransmux = this.config_.forceTransmux;
  1741. if (!shaka.media.Capabilities.isTypeSupported(newMimeType) ||
  1742. (!this.sequenceMode_ &&
  1743. shaka.util.MimeUtils.RAW_FORMATS.includes(newMimeType))) {
  1744. needTransmux = true;
  1745. }
  1746. const TransmuxerEngine = shaka.transmuxer.TransmuxerEngine;
  1747. if (needTransmux) {
  1748. const newMimeTypeWithAllCodecs =
  1749. shaka.util.MimeUtils.getFullTypeWithAllCodecs(mimeType, codecs);
  1750. const transmuxerPlugin =
  1751. TransmuxerEngine.findTransmuxer(newMimeTypeWithAllCodecs);
  1752. if (transmuxerPlugin) {
  1753. transmuxer = transmuxerPlugin();
  1754. const audioCodec = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1755. ContentType.AUDIO, (codecs || '').split(','));
  1756. const videoCodec = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1757. ContentType.VIDEO, (codecs || '').split(','));
  1758. if (audioCodec && videoCodec) {
  1759. transmuxerMuxed = true;
  1760. let codec = videoCodec;
  1761. if (contentType == ContentType.AUDIO) {
  1762. codec = audioCodec;
  1763. }
  1764. newMimeType = transmuxer.convertCodecs(contentType,
  1765. shaka.util.MimeUtils.getFullTypeWithAllCodecs(mimeType, codec));
  1766. } else {
  1767. newMimeType =
  1768. transmuxer.convertCodecs(contentType, newMimeTypeWithAllCodecs);
  1769. }
  1770. }
  1771. }
  1772. const newCodec = MimeUtils.getCodecBase(
  1773. MimeUtils.getCodecs(newMimeType));
  1774. const newBasicType = MimeUtils.getBasicType(newMimeType);
  1775. // Current/new codecs base and basic type match then no need to switch
  1776. if (currentCodec === newCodec && currentBasicType === newBasicType) {
  1777. return false;
  1778. }
  1779. let allowChangeType = true;
  1780. if (this.needSplitMuxedContent_ || (transmuxerMuxed &&
  1781. transmuxer && !this.transmuxers_[contentType])) {
  1782. allowChangeType = false;
  1783. }
  1784. if (allowChangeType && this.config_.codecSwitchingStrategy ===
  1785. shaka.config.CodecSwitchingStrategy.SMOOTH &&
  1786. shaka.media.Capabilities.isChangeTypeSupported()) {
  1787. await this.changeType(contentType, newMimeType, transmuxer);
  1788. } else {
  1789. if (transmuxer) {
  1790. transmuxer.destroy();
  1791. }
  1792. await this.reset(streamsByType);
  1793. }
  1794. return true;
  1795. }
  1796. /**
  1797. * Returns true if it's necessary codec switch to load the new stream.
  1798. *
  1799. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1800. * @param {shaka.extern.Stream} stream
  1801. * @param {string} refMimeType
  1802. * @param {string} refCodecs
  1803. * @return {boolean}
  1804. * @private
  1805. */
  1806. isCodecSwitchNecessary_(contentType, stream, refMimeType, refCodecs) {
  1807. if (contentType == shaka.util.ManifestParserUtils.ContentType.TEXT) {
  1808. return false;
  1809. }
  1810. const MimeUtils = shaka.util.MimeUtils;
  1811. const currentCodec = MimeUtils.getCodecBase(
  1812. MimeUtils.getCodecs(this.sourceBufferTypes_[contentType]));
  1813. const currentBasicType = MimeUtils.getBasicType(
  1814. this.sourceBufferTypes_[contentType]);
  1815. let newMimeType = shaka.util.MimeUtils.getFullType(refMimeType, refCodecs);
  1816. let needTransmux = this.config_.forceTransmux;
  1817. if (!shaka.media.Capabilities.isTypeSupported(newMimeType) ||
  1818. (!this.sequenceMode_ &&
  1819. shaka.util.MimeUtils.RAW_FORMATS.includes(newMimeType))) {
  1820. needTransmux = true;
  1821. }
  1822. const newMimeTypeWithAllCodecs =
  1823. shaka.util.MimeUtils.getFullTypeWithAllCodecs(
  1824. refMimeType, refCodecs);
  1825. const TransmuxerEngine = shaka.transmuxer.TransmuxerEngine;
  1826. if (needTransmux) {
  1827. const transmuxerPlugin =
  1828. TransmuxerEngine.findTransmuxer(newMimeTypeWithAllCodecs);
  1829. if (transmuxerPlugin) {
  1830. const transmuxer = transmuxerPlugin();
  1831. newMimeType =
  1832. transmuxer.convertCodecs(contentType, newMimeTypeWithAllCodecs);
  1833. transmuxer.destroy();
  1834. }
  1835. }
  1836. const newCodec = MimeUtils.getCodecBase(
  1837. MimeUtils.getCodecs(newMimeType));
  1838. const newBasicType = MimeUtils.getBasicType(newMimeType);
  1839. return currentCodec !== newCodec || currentBasicType !== newBasicType;
  1840. }
  1841. /**
  1842. * Returns true if it's necessary reset the media source to load the
  1843. * new stream.
  1844. *
  1845. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  1846. * @param {shaka.extern.Stream} stream
  1847. * @param {string} mimeType
  1848. * @param {string} codecs
  1849. * @return {boolean}
  1850. */
  1851. isResetMediaSourceNecessary(contentType, stream, mimeType, codecs) {
  1852. if (!this.isCodecSwitchNecessary_(contentType, stream, mimeType, codecs)) {
  1853. return false;
  1854. }
  1855. return this.config_.codecSwitchingStrategy !==
  1856. shaka.config.CodecSwitchingStrategy.SMOOTH ||
  1857. !shaka.media.Capabilities.isChangeTypeSupported() ||
  1858. this.needSplitMuxedContent_;
  1859. }
  1860. /**
  1861. * Update LCEVC Decoder object when ready for LCEVC Decode.
  1862. * @param {?shaka.lcevc.Dec} lcevcDec
  1863. */
  1864. updateLcevcDec(lcevcDec) {
  1865. this.lcevcDec_ = lcevcDec;
  1866. }
  1867. /**
  1868. * @param {string} mimeType
  1869. * @return {string}
  1870. * @private
  1871. */
  1872. addExtraFeaturesToMimeType_(mimeType) {
  1873. const extraFeatures = this.config_.addExtraFeaturesToSourceBuffer(mimeType);
  1874. const extendedType = mimeType + extraFeatures;
  1875. shaka.log.debug('Using full mime type', extendedType);
  1876. return extendedType;
  1877. }
  1878. };
  1879. /**
  1880. * Internal reference to window.URL.createObjectURL function to avoid
  1881. * compatibility issues with other libraries and frameworks such as React
  1882. * Native. For use in unit tests only, not meant for external use.
  1883. *
  1884. * @type {function(?):string}
  1885. */
  1886. shaka.media.MediaSourceEngine.createObjectURL = window.URL.createObjectURL;
  1887. /**
  1888. * @typedef {{
  1889. * start: function(),
  1890. * p: !shaka.util.PublicPromise
  1891. * }}
  1892. *
  1893. * @summary An operation in queue.
  1894. * @property {function()} start
  1895. * The function which starts the operation.
  1896. * @property {!shaka.util.PublicPromise} p
  1897. * The PublicPromise which is associated with this operation.
  1898. */
  1899. shaka.media.MediaSourceEngine.Operation;
  1900. /**
  1901. * @enum {string}
  1902. * @private
  1903. */
  1904. shaka.media.MediaSourceEngine.SourceBufferMode_ = {
  1905. SEQUENCE: 'sequence',
  1906. SEGMENTS: 'segments',
  1907. };