Source: lib/media/transmuxer.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.Transmuxer');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.util.BufferUtils');
  9. goog.require('shaka.util.Error');
  10. goog.require('shaka.util.IDestroyable');
  11. goog.require('shaka.util.ManifestParserUtils');
  12. goog.require('shaka.util.PublicPromise');
  13. goog.require('shaka.util.Uint8ArrayUtils');
  14. goog.require('shaka.dependencies');
  15. /**
  16. * Transmuxer provides all operations for transmuxing from Transport
  17. * Stream to MP4.
  18. *
  19. * @implements {shaka.util.IDestroyable}
  20. */
  21. shaka.media.Transmuxer = class {
  22. /** */
  23. constructor() {
  24. /** @private {?muxjs} */
  25. this.muxjs_ = shaka.dependencies.muxjs();
  26. /** @private {muxjs.mp4.Transmuxer} */
  27. this.muxTransmuxer_ = new this.muxjs_.mp4.Transmuxer({
  28. 'keepOriginalTimestamps': true,
  29. });
  30. /** @private {shaka.util.PublicPromise} */
  31. this.transmuxPromise_ = null;
  32. /** @private {!Array.<!Uint8Array>} */
  33. this.transmuxedData_ = [];
  34. /** @private {!Array.<muxjs.mp4.ClosedCaption>} */
  35. this.captions_ = [];
  36. /** @private {!Array.<muxjs.mp4.Metadata>} */
  37. this.metadata_ = [];
  38. /** @private {boolean} */
  39. this.isTransmuxing_ = false;
  40. this.muxTransmuxer_.on('data', (segment) => this.onTransmuxed_(segment));
  41. this.muxTransmuxer_.on('done', () => this.onTransmuxDone_());
  42. }
  43. /**
  44. * @override
  45. */
  46. destroy() {
  47. this.muxTransmuxer_.dispose();
  48. this.muxTransmuxer_ = null;
  49. return Promise.resolve();
  50. }
  51. /**
  52. * Check if the content type is Transport Stream, and if muxjs is loaded.
  53. * @param {string} mimeType
  54. * @param {string=} contentType
  55. * @return {boolean}
  56. */
  57. static isSupported(mimeType, contentType) {
  58. const Transmuxer = shaka.media.Transmuxer;
  59. if (!shaka.dependencies.muxjs() || !Transmuxer.isTsContainer(mimeType)) {
  60. return false;
  61. }
  62. if (contentType) {
  63. return MediaSource.isTypeSupported(
  64. Transmuxer.convertTsCodecs(contentType, mimeType));
  65. }
  66. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  67. const audioMime = Transmuxer.convertTsCodecs(ContentType.AUDIO, mimeType);
  68. const videoMime = Transmuxer.convertTsCodecs(ContentType.VIDEO, mimeType);
  69. return MediaSource.isTypeSupported(audioMime) ||
  70. MediaSource.isTypeSupported(videoMime);
  71. }
  72. /**
  73. * Check if the mimetype contains 'mp2t'.
  74. * @param {string} mimeType
  75. * @return {boolean}
  76. */
  77. static isTsContainer(mimeType) {
  78. return mimeType.toLowerCase().split(';')[0].split('/')[1] == 'mp2t';
  79. }
  80. /**
  81. * For transport stream, convert its codecs to MP4 codecs.
  82. * @param {string} contentType
  83. * @param {string} tsMimeType
  84. * @return {string}
  85. */
  86. static convertTsCodecs(contentType, tsMimeType) {
  87. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  88. let mp4MimeType = tsMimeType.replace(/mp2t/i, 'mp4');
  89. if (contentType == ContentType.AUDIO) {
  90. mp4MimeType = mp4MimeType.replace('video', 'audio');
  91. }
  92. // Handle legacy AVC1 codec strings (pre-RFC 6381).
  93. // Look for "avc1.<profile>.<level>", where profile is:
  94. // 66 (baseline => 0x42)
  95. // 77 (main => 0x4d)
  96. // 100 (high => 0x64)
  97. // Reference: https://bit.ly/2K9JI3x
  98. const match = /avc1\.(66|77|100)\.(\d+)/.exec(mp4MimeType);
  99. if (match) {
  100. let newCodecString = 'avc1.';
  101. const profile = match[1];
  102. if (profile == '66') {
  103. newCodecString += '4200';
  104. } else if (profile == '77') {
  105. newCodecString += '4d00';
  106. } else {
  107. goog.asserts.assert(profile == '100',
  108. 'Legacy avc1 parsing code out of sync with regex!');
  109. newCodecString += '6400';
  110. }
  111. // Convert the level to hex and append to the codec string.
  112. const level = Number(match[2]);
  113. goog.asserts.assert(level < 256,
  114. 'Invalid legacy avc1 level number!');
  115. newCodecString += (level >> 4).toString(16);
  116. newCodecString += (level & 0xf).toString(16);
  117. mp4MimeType = mp4MimeType.replace(match[0], newCodecString);
  118. }
  119. return mp4MimeType;
  120. }
  121. /**
  122. * Transmux from Transport stream to MP4, using the mux.js library.
  123. * @param {BufferSource} data
  124. * @return {!Promise.<{data: !Uint8Array,
  125. * captions: !Array.<!muxjs.mp4.ClosedCaption>,
  126. * metadata: !Array.<!Object>}>}
  127. */
  128. transmux(data) {
  129. goog.asserts.assert(!this.isTransmuxing_,
  130. 'No transmuxing should be in progress.');
  131. this.isTransmuxing_ = true;
  132. this.transmuxPromise_ = new shaka.util.PublicPromise();
  133. this.transmuxedData_ = [];
  134. this.captions_ = [];
  135. this.metadata_ = [];
  136. const dataArray = shaka.util.BufferUtils.toUint8(data);
  137. this.muxTransmuxer_.push(dataArray);
  138. this.muxTransmuxer_.flush();
  139. // Workaround for https://bit.ly/Shaka1449 mux.js not
  140. // emitting 'data' and 'done' events.
  141. // mux.js code is synchronous, so if onTransmuxDone_ has
  142. // not been called by now, it's not going to be.
  143. // Treat it as a transmuxing failure and reject the promise.
  144. if (this.isTransmuxing_) {
  145. this.transmuxPromise_.reject(new shaka.util.Error(
  146. shaka.util.Error.Severity.CRITICAL,
  147. shaka.util.Error.Category.MEDIA,
  148. shaka.util.Error.Code.TRANSMUXING_FAILED));
  149. }
  150. return this.transmuxPromise_;
  151. }
  152. /**
  153. * Handles the 'data' event of the transmuxer.
  154. * Extracts the cues from the transmuxed segment, and adds them to an array.
  155. * Stores the transmuxed data in another array, to pass it back to
  156. * MediaSourceEngine, and append to the source buffer.
  157. *
  158. * @param {muxjs.mp4.Transmuxer.Segment} segment
  159. * @private
  160. */
  161. onTransmuxed_(segment) {
  162. this.captions_ = segment.captions;
  163. this.metadata_ = segment.metadata;
  164. this.transmuxedData_.push(
  165. shaka.util.Uint8ArrayUtils.concat(segment.initSegment, segment.data));
  166. }
  167. /**
  168. * Handles the 'done' event of the transmuxer.
  169. * Resolves the transmux Promise, and returns the transmuxed data.
  170. * @private
  171. */
  172. onTransmuxDone_() {
  173. const output = {
  174. data: shaka.util.Uint8ArrayUtils.concat(...this.transmuxedData_),
  175. captions: this.captions_,
  176. metadata: this.metadata_,
  177. };
  178. this.transmuxPromise_.resolve(output);
  179. this.isTransmuxing_ = false;
  180. }
  181. };