Source: lib/media/content_workarounds.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.ContentWorkarounds');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.util.BufferUtils');
  10. goog.require('shaka.util.Error');
  11. goog.require('shaka.util.Lazy');
  12. goog.require('shaka.util.Mp4Parser');
  13. goog.require('shaka.util.Platform');
  14. goog.require('shaka.util.Uint8ArrayUtils');
  15. /**
  16. * @summary
  17. * A collection of methods to work around content issues on various platforms.
  18. */
  19. shaka.media.ContentWorkarounds = class {
  20. /**
  21. * Transform the init segment into a new init segment buffer that indicates
  22. * encryption. If the init segment already indicates encryption, return the
  23. * original init segment.
  24. *
  25. * Should only be called for MP4 init segments, and only on platforms that
  26. * need this workaround.
  27. *
  28. * @param {!BufferSource} initSegmentBuffer
  29. * @param {?string} uri
  30. * @return {!Uint8Array}
  31. * @see https://github.com/shaka-project/shaka-player/issues/2759
  32. */
  33. static fakeEncryption(initSegmentBuffer, uri) {
  34. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  35. const initSegment = shaka.util.BufferUtils.toUint8(initSegmentBuffer);
  36. let modifiedInitSegment = initSegment;
  37. let isEncrypted = false;
  38. /** @type {shaka.extern.ParsedBox} */
  39. let stsdBox;
  40. const ancestorBoxes = [];
  41. const onSimpleAncestorBox = (box) => {
  42. ancestorBoxes.push(box);
  43. shaka.util.Mp4Parser.children(box);
  44. };
  45. const onEncryptionMetadataBox = (box) => {
  46. isEncrypted = true;
  47. };
  48. // Multiplexed content could have multiple boxes that we need to modify.
  49. // Add to this array in order of box offset. This will be important later,
  50. // when we process the boxes.
  51. /** @type {!Array.<{box: shaka.extern.ParsedBox, newType: number}>} */
  52. const boxesToModify = [];
  53. new shaka.util.Mp4Parser()
  54. .box('moov', onSimpleAncestorBox)
  55. .box('trak', onSimpleAncestorBox)
  56. .box('mdia', onSimpleAncestorBox)
  57. .box('minf', onSimpleAncestorBox)
  58. .box('stbl', onSimpleAncestorBox)
  59. .fullBox('stsd', (box) => {
  60. stsdBox = box;
  61. ancestorBoxes.push(box);
  62. shaka.util.Mp4Parser.sampleDescription(box);
  63. })
  64. .fullBox('encv', onEncryptionMetadataBox)
  65. .fullBox('enca', onEncryptionMetadataBox)
  66. .fullBox('dvav', (box) => {
  67. boxesToModify.push({
  68. box,
  69. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  70. });
  71. })
  72. .fullBox('dva1', (box) => {
  73. boxesToModify.push({
  74. box,
  75. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  76. });
  77. })
  78. .fullBox('dvh1', (box) => {
  79. boxesToModify.push({
  80. box,
  81. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  82. });
  83. })
  84. .fullBox('dvhe', (box) => {
  85. boxesToModify.push({
  86. box,
  87. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  88. });
  89. })
  90. .fullBox('hev1', (box) => {
  91. boxesToModify.push({
  92. box,
  93. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  94. });
  95. })
  96. .fullBox('hvc1', (box) => {
  97. boxesToModify.push({
  98. box,
  99. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  100. });
  101. })
  102. .fullBox('avc1', (box) => {
  103. boxesToModify.push({
  104. box,
  105. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  106. });
  107. })
  108. .fullBox('avc3', (box) => {
  109. boxesToModify.push({
  110. box,
  111. newType: ContentWorkarounds.BOX_TYPE_ENCV_,
  112. });
  113. })
  114. .fullBox('ac-3', (box) => {
  115. boxesToModify.push({
  116. box,
  117. newType: ContentWorkarounds.BOX_TYPE_ENCA_,
  118. });
  119. })
  120. .fullBox('ec-3', (box) => {
  121. boxesToModify.push({
  122. box,
  123. newType: ContentWorkarounds.BOX_TYPE_ENCA_,
  124. });
  125. })
  126. .fullBox('ac-4', (box) => {
  127. boxesToModify.push({
  128. box,
  129. newType: ContentWorkarounds.BOX_TYPE_ENCA_,
  130. });
  131. })
  132. .fullBox('mp4a', (box) => {
  133. boxesToModify.push({
  134. box,
  135. newType: ContentWorkarounds.BOX_TYPE_ENCA_,
  136. });
  137. }).parse(initSegment);
  138. if (isEncrypted) {
  139. shaka.log.debug('Init segment already indicates encryption.');
  140. return initSegment;
  141. }
  142. if (boxesToModify.length == 0 || !stsdBox) {
  143. shaka.log.error('Failed to find boxes needed to fake encryption!');
  144. shaka.log.v2('Failed init segment (hex):',
  145. shaka.util.Uint8ArrayUtils.toHex(initSegment));
  146. throw new shaka.util.Error(
  147. shaka.util.Error.Severity.CRITICAL,
  148. shaka.util.Error.Category.MEDIA,
  149. shaka.util.Error.Code.CONTENT_TRANSFORMATION_FAILED,
  150. uri);
  151. }
  152. // Modify boxes in order from largest offset to smallest, so that earlier
  153. // boxes don't have their offsets changed before we process them.
  154. boxesToModify.reverse(); // in place!
  155. for (const workItem of boxesToModify) {
  156. const insertedBoxType =
  157. shaka.util.Mp4Parser.typeToString(workItem.newType);
  158. shaka.log.debug(`Inserting "${insertedBoxType}" box into init segment.`);
  159. modifiedInitSegment = ContentWorkarounds.insertEncryptionMetadata_(
  160. modifiedInitSegment, stsdBox, workItem.box, ancestorBoxes,
  161. workItem.newType);
  162. }
  163. // Edge Windows needs the unmodified init segment to be appended after the
  164. // patched one, otherwise video element throws following error:
  165. // CHUNK_DEMUXER_ERROR_APPEND_FAILED: Sample encryption info is not
  166. // available.
  167. if (shaka.util.Platform.isEdge() && shaka.util.Platform.isWindows() &&
  168. !shaka.util.Platform.isXboxOne()) {
  169. const doubleInitSegment = new Uint8Array(initSegment.byteLength +
  170. modifiedInitSegment.byteLength);
  171. doubleInitSegment.set(modifiedInitSegment);
  172. doubleInitSegment.set(initSegment, modifiedInitSegment.byteLength);
  173. return doubleInitSegment;
  174. }
  175. return modifiedInitSegment;
  176. }
  177. /**
  178. * Insert an encryption metadata box ("encv" or "enca" box) into the MP4 init
  179. * segment, based on the source box ("mp4a", "avc1", etc). Returns a new
  180. * buffer containing the modified init segment.
  181. *
  182. * @param {!Uint8Array} initSegment
  183. * @param {shaka.extern.ParsedBox} stsdBox
  184. * @param {shaka.extern.ParsedBox} sourceBox
  185. * @param {!Array.<shaka.extern.ParsedBox>} ancestorBoxes
  186. * @param {number} metadataBoxType
  187. * @return {!Uint8Array}
  188. * @private
  189. */
  190. static insertEncryptionMetadata_(
  191. initSegment, stsdBox, sourceBox, ancestorBoxes, metadataBoxType) {
  192. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  193. const metadataBoxArray = ContentWorkarounds.createEncryptionMetadata_(
  194. initSegment, sourceBox, metadataBoxType);
  195. // Construct a new init segment array with room for the encryption metadata
  196. // box we're adding.
  197. const newInitSegment =
  198. new Uint8Array(initSegment.byteLength + metadataBoxArray.byteLength);
  199. // For Xbox One & Edge, we cut and insert at the start of the source box.
  200. // For other platforms, we cut and insert at the end of the source box. It's
  201. // not clear why this is necessary on Xbox One, but it seems to be evidence
  202. // of another bug in the firmware implementation of MediaSource & EME.
  203. const cutPoint =
  204. (shaka.util.Platform.isXboxOne() || shaka.util.Platform.isEdge()) ?
  205. sourceBox.start :
  206. sourceBox.start + sourceBox.size;
  207. // The data before the cut point will be copied to the same location as
  208. // before. The data after that will be appended after the added metadata
  209. // box.
  210. const beforeData = initSegment.subarray(0, cutPoint);
  211. const afterData = initSegment.subarray(cutPoint);
  212. newInitSegment.set(beforeData);
  213. newInitSegment.set(metadataBoxArray, cutPoint);
  214. newInitSegment.set(afterData, cutPoint + metadataBoxArray.byteLength);
  215. // The parents up the chain from the encryption metadata box need their
  216. // sizes adjusted to account for the added box. These offsets should not be
  217. // changed, because they should all be within the first section we copy.
  218. for (const box of ancestorBoxes) {
  219. goog.asserts.assert(box.start < cutPoint,
  220. 'Ancestor MP4 box found in the wrong location! ' +
  221. 'Modified init segment will not make sense!');
  222. ContentWorkarounds.updateBoxSize_(
  223. newInitSegment, box.start, box.size + metadataBoxArray.byteLength);
  224. }
  225. // Add one to the sample entries field of the "stsd" box. This is a 4-byte
  226. // field just past the box header.
  227. const stsdBoxView = shaka.util.BufferUtils.toDataView(
  228. newInitSegment, stsdBox.start);
  229. const stsdBoxHeaderSize = shaka.util.Mp4Parser.headerSize(stsdBox);
  230. const numEntries = stsdBoxView.getUint32(stsdBoxHeaderSize);
  231. stsdBoxView.setUint32(stsdBoxHeaderSize, numEntries + 1);
  232. return newInitSegment;
  233. }
  234. /**
  235. * Create an encryption metadata box ("encv" or "enca" box), based on the
  236. * source box ("mp4a", "avc1", etc). Returns a new buffer containing the
  237. * encryption metadata box.
  238. *
  239. * @param {!Uint8Array} initSegment
  240. * @param {shaka.extern.ParsedBox} sourceBox
  241. * @param {number} metadataBoxType
  242. * @return {!Uint8Array}
  243. * @private
  244. */
  245. static createEncryptionMetadata_(initSegment, sourceBox, metadataBoxType) {
  246. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  247. const sinfBoxArray = ContentWorkarounds.CANNED_SINF_BOX_.value();
  248. // Create a subarray which points to the source box data.
  249. const sourceBoxArray = initSegment.subarray(
  250. /* start= */ sourceBox.start,
  251. /* end= */ sourceBox.start + sourceBox.size);
  252. // Create a view on the source box array.
  253. const sourceBoxView = shaka.util.BufferUtils.toDataView(sourceBoxArray);
  254. // Create an array to hold the new encryption metadata box, which is based
  255. // on the source box.
  256. const metadataBoxArray = new Uint8Array(
  257. sourceBox.size + sinfBoxArray.byteLength);
  258. // Copy the source box into the new array.
  259. metadataBoxArray.set(sourceBoxArray, /* targetOffset= */ 0);
  260. // Change the box type.
  261. const metadataBoxView = shaka.util.BufferUtils.toDataView(metadataBoxArray);
  262. metadataBoxView.setUint32(
  263. ContentWorkarounds.BOX_TYPE_OFFSET_, metadataBoxType);
  264. // Append the "sinf" box to the encryption metadata box.
  265. metadataBoxArray.set(sinfBoxArray, /* targetOffset= */ sourceBox.size);
  266. // Update the "sinf" box's format field (in the child "frma" box) to reflect
  267. // the format of the original source box.
  268. const sourceBoxType = sourceBoxView.getUint32(
  269. ContentWorkarounds.BOX_TYPE_OFFSET_);
  270. metadataBoxView.setUint32(
  271. sourceBox.size + ContentWorkarounds.CANNED_SINF_BOX_FORMAT_OFFSET_,
  272. sourceBoxType);
  273. // Now update the encryption metadata box size.
  274. ContentWorkarounds.updateBoxSize_(
  275. metadataBoxArray, /* boxStart= */ 0, metadataBoxArray.byteLength);
  276. return metadataBoxArray;
  277. }
  278. /**
  279. * Modify an MP4 box's size field in-place.
  280. *
  281. * @param {!Uint8Array} dataArray
  282. * @param {number} boxStart The start position of the box in dataArray.
  283. * @param {number} newBoxSize The new size of the box.
  284. * @private
  285. */
  286. static updateBoxSize_(dataArray, boxStart, newBoxSize) {
  287. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  288. const boxView = shaka.util.BufferUtils.toDataView(dataArray, boxStart);
  289. const sizeField = boxView.getUint32(ContentWorkarounds.BOX_SIZE_OFFSET_);
  290. if (sizeField == 0) { // Means "the rest of the box".
  291. // No adjustment needed for this box.
  292. } else if (sizeField == 1) { // Means "use 64-bit size box".
  293. // Set the 64-bit int in two 32-bit parts.
  294. // The high bits should definitely be 0 in practice, but we're being
  295. // thorough here.
  296. boxView.setUint32(ContentWorkarounds.BOX_SIZE_64_OFFSET_,
  297. newBoxSize >> 32);
  298. boxView.setUint32(ContentWorkarounds.BOX_SIZE_64_OFFSET_ + 4,
  299. newBoxSize & 0xffffffff);
  300. } else { // Normal 32-bit size field.
  301. // Not checking the size of the value here, since a box larger than 4GB is
  302. // unrealistic.
  303. boxView.setUint32(ContentWorkarounds.BOX_SIZE_OFFSET_, newBoxSize);
  304. }
  305. }
  306. };
  307. /**
  308. * A canned "sinf" box for use when adding fake encryption metadata to init
  309. * segments.
  310. *
  311. * @const {!shaka.util.Lazy.<!Uint8Array>}
  312. * @private
  313. * @see https://github.com/shaka-project/shaka-player/issues/2759
  314. */
  315. shaka.media.ContentWorkarounds.CANNED_SINF_BOX_ =
  316. new shaka.util.Lazy(() => new Uint8Array([
  317. // sinf box
  318. // Size: 0x50 = 80
  319. 0x00, 0x00, 0x00, 0x50,
  320. // Type: sinf
  321. 0x73, 0x69, 0x6e, 0x66,
  322. // Children of sinf...
  323. // frma box
  324. // Size: 0x0c = 12
  325. 0x00, 0x00, 0x00, 0x0c,
  326. // Type: frma (child of sinf)
  327. 0x66, 0x72, 0x6d, 0x61,
  328. // Format: filled in later based on the source box ("avc1", "mp4a", etc)
  329. 0x00, 0x00, 0x00, 0x00,
  330. // end of frma box
  331. // schm box
  332. // Size: 0x14 = 20
  333. 0x00, 0x00, 0x00, 0x14,
  334. // Type: schm (child of sinf)
  335. 0x73, 0x63, 0x68, 0x6d,
  336. // Version: 0, Flags: 0
  337. 0x00, 0x00, 0x00, 0x00,
  338. // Scheme: cenc
  339. 0x63, 0x65, 0x6e, 0x63,
  340. // Scheme version: 1.0
  341. 0x00, 0x01, 0x00, 0x00,
  342. // end of schm box
  343. // schi box
  344. // Size: 0x28 = 40
  345. 0x00, 0x00, 0x00, 0x28,
  346. // Type: schi (child of sinf)
  347. 0x73, 0x63, 0x68, 0x69,
  348. // Children of schi...
  349. // tenc box
  350. // Size: 0x20 = 32
  351. 0x00, 0x00, 0x00, 0x20,
  352. // Type: tenc (child of schi)
  353. 0x74, 0x65, 0x6e, 0x63,
  354. // Version: 0, Flags: 0
  355. 0x00, 0x00, 0x00, 0x00,
  356. // Reserved fields
  357. 0x00, 0x00,
  358. // Default protected: true
  359. 0x01,
  360. // Default per-sample IV size: 8
  361. 0x08,
  362. // Default key ID: all zeros (dummy)
  363. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  364. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  365. // end of tenc box
  366. // end of schi box
  367. // end of sinf box
  368. ]));
  369. /**
  370. * The location of the format field in the "frma" box inside the canned "sinf"
  371. * box above.
  372. *
  373. * @const {number}
  374. * @private
  375. */
  376. shaka.media.ContentWorkarounds.CANNED_SINF_BOX_FORMAT_OFFSET_ = 0x10;
  377. /**
  378. * Offset to a box's size field.
  379. *
  380. * @const {number}
  381. * @private
  382. */
  383. shaka.media.ContentWorkarounds.BOX_SIZE_OFFSET_ = 0;
  384. /**
  385. * Offset to a box's type field.
  386. *
  387. * @const {number}
  388. * @private
  389. */
  390. shaka.media.ContentWorkarounds.BOX_TYPE_OFFSET_ = 4;
  391. /**
  392. * Offset to a box's 64-bit size field, if it has one.
  393. *
  394. * @const {number}
  395. * @private
  396. */
  397. shaka.media.ContentWorkarounds.BOX_SIZE_64_OFFSET_ = 8;
  398. /**
  399. * Box type for "encv".
  400. *
  401. * @const {number}
  402. * @private
  403. */
  404. shaka.media.ContentWorkarounds.BOX_TYPE_ENCV_ = 0x656e6376;
  405. /**
  406. * Box type for "enca".
  407. *
  408. * @const {number}
  409. * @private
  410. */
  411. shaka.media.ContentWorkarounds.BOX_TYPE_ENCA_ = 0x656e6361;