Source: lib/media/transmuxer.js

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