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