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