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. const doubleInitSegment = new Uint8Array(initSegment.byteLength +
  169. modifiedInitSegment.byteLength);
  170. doubleInitSegment.set(modifiedInitSegment);
  171. doubleInitSegment.set(initSegment, modifiedInitSegment.byteLength);
  172. return doubleInitSegment;
  173. }
  174. return modifiedInitSegment;
  175. }
  176. /**
  177. * Insert an encryption metadata box ("encv" or "enca" box) into the MP4 init
  178. * segment, based on the source box ("mp4a", "avc1", etc). Returns a new
  179. * buffer containing the modified init segment.
  180. *
  181. * @param {!Uint8Array} initSegment
  182. * @param {shaka.extern.ParsedBox} stsdBox
  183. * @param {shaka.extern.ParsedBox} sourceBox
  184. * @param {!Array.<shaka.extern.ParsedBox>} ancestorBoxes
  185. * @param {number} metadataBoxType
  186. * @return {!Uint8Array}
  187. * @private
  188. */
  189. static insertEncryptionMetadata_(
  190. initSegment, stsdBox, sourceBox, ancestorBoxes, metadataBoxType) {
  191. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  192. const metadataBoxArray = ContentWorkarounds.createEncryptionMetadata_(
  193. initSegment, sourceBox, metadataBoxType);
  194. // Construct a new init segment array with room for the encryption metadata
  195. // box we're adding.
  196. const newInitSegment =
  197. new Uint8Array(initSegment.byteLength + metadataBoxArray.byteLength);
  198. // For Xbox One & Edge, we cut and insert at the start of the source box.
  199. // For other platforms, we cut and insert at the end of the source box. It's
  200. // not clear why this is necessary on Xbox One, but it seems to be evidence
  201. // of another bug in the firmware implementation of MediaSource & EME.
  202. const cutPoint =
  203. (shaka.util.Platform.isXboxOne() || shaka.util.Platform.isEdge()) ?
  204. sourceBox.start :
  205. sourceBox.start + sourceBox.size;
  206. // The data before the cut point will be copied to the same location as
  207. // before. The data after that will be appended after the added metadata
  208. // box.
  209. const beforeData = initSegment.subarray(0, cutPoint);
  210. const afterData = initSegment.subarray(cutPoint);
  211. newInitSegment.set(beforeData);
  212. newInitSegment.set(metadataBoxArray, cutPoint);
  213. newInitSegment.set(afterData, cutPoint + metadataBoxArray.byteLength);
  214. // The parents up the chain from the encryption metadata box need their
  215. // sizes adjusted to account for the added box. These offsets should not be
  216. // changed, because they should all be within the first section we copy.
  217. for (const box of ancestorBoxes) {
  218. goog.asserts.assert(box.start < cutPoint,
  219. 'Ancestor MP4 box found in the wrong location! ' +
  220. 'Modified init segment will not make sense!');
  221. ContentWorkarounds.updateBoxSize_(
  222. newInitSegment, box.start, box.size + metadataBoxArray.byteLength);
  223. }
  224. // Add one to the sample entries field of the "stsd" box. This is a 4-byte
  225. // field just past the box header.
  226. const stsdBoxView = shaka.util.BufferUtils.toDataView(
  227. newInitSegment, stsdBox.start);
  228. const stsdBoxHeaderSize = shaka.util.Mp4Parser.headerSize(stsdBox);
  229. const numEntries = stsdBoxView.getUint32(stsdBoxHeaderSize);
  230. stsdBoxView.setUint32(stsdBoxHeaderSize, numEntries + 1);
  231. return newInitSegment;
  232. }
  233. /**
  234. * Create an encryption metadata box ("encv" or "enca" box), based on the
  235. * source box ("mp4a", "avc1", etc). Returns a new buffer containing the
  236. * encryption metadata box.
  237. *
  238. * @param {!Uint8Array} initSegment
  239. * @param {shaka.extern.ParsedBox} sourceBox
  240. * @param {number} metadataBoxType
  241. * @return {!Uint8Array}
  242. * @private
  243. */
  244. static createEncryptionMetadata_(initSegment, sourceBox, metadataBoxType) {
  245. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  246. const sinfBoxArray = ContentWorkarounds.CANNED_SINF_BOX_.value();
  247. // Create a subarray which points to the source box data.
  248. const sourceBoxArray = initSegment.subarray(
  249. /* start= */ sourceBox.start,
  250. /* end= */ sourceBox.start + sourceBox.size);
  251. // Create a view on the source box array.
  252. const sourceBoxView = shaka.util.BufferUtils.toDataView(sourceBoxArray);
  253. // Create an array to hold the new encryption metadata box, which is based
  254. // on the source box.
  255. const metadataBoxArray = new Uint8Array(
  256. sourceBox.size + sinfBoxArray.byteLength);
  257. // Copy the source box into the new array.
  258. metadataBoxArray.set(sourceBoxArray, /* targetOffset= */ 0);
  259. // Change the box type.
  260. const metadataBoxView = shaka.util.BufferUtils.toDataView(metadataBoxArray);
  261. metadataBoxView.setUint32(
  262. ContentWorkarounds.BOX_TYPE_OFFSET_, metadataBoxType);
  263. // Append the "sinf" box to the encryption metadata box.
  264. metadataBoxArray.set(sinfBoxArray, /* targetOffset= */ sourceBox.size);
  265. // Update the "sinf" box's format field (in the child "frma" box) to reflect
  266. // the format of the original source box.
  267. const sourceBoxType = sourceBoxView.getUint32(
  268. ContentWorkarounds.BOX_TYPE_OFFSET_);
  269. metadataBoxView.setUint32(
  270. sourceBox.size + ContentWorkarounds.CANNED_SINF_BOX_FORMAT_OFFSET_,
  271. sourceBoxType);
  272. // Now update the encryption metadata box size.
  273. ContentWorkarounds.updateBoxSize_(
  274. metadataBoxArray, /* boxStart= */ 0, metadataBoxArray.byteLength);
  275. return metadataBoxArray;
  276. }
  277. /**
  278. * Modify an MP4 box's size field in-place.
  279. *
  280. * @param {!Uint8Array} dataArray
  281. * @param {number} boxStart The start position of the box in dataArray.
  282. * @param {number} newBoxSize The new size of the box.
  283. * @private
  284. */
  285. static updateBoxSize_(dataArray, boxStart, newBoxSize) {
  286. const ContentWorkarounds = shaka.media.ContentWorkarounds;
  287. const boxView = shaka.util.BufferUtils.toDataView(dataArray, boxStart);
  288. const sizeField = boxView.getUint32(ContentWorkarounds.BOX_SIZE_OFFSET_);
  289. if (sizeField == 0) { // Means "the rest of the box".
  290. // No adjustment needed for this box.
  291. } else if (sizeField == 1) { // Means "use 64-bit size box".
  292. // Set the 64-bit int in two 32-bit parts.
  293. // The high bits should definitely be 0 in practice, but we're being
  294. // thorough here.
  295. boxView.setUint32(ContentWorkarounds.BOX_SIZE_64_OFFSET_,
  296. newBoxSize >> 32);
  297. boxView.setUint32(ContentWorkarounds.BOX_SIZE_64_OFFSET_ + 4,
  298. newBoxSize & 0xffffffff);
  299. } else { // Normal 32-bit size field.
  300. // Not checking the size of the value here, since a box larger than 4GB is
  301. // unrealistic.
  302. boxView.setUint32(ContentWorkarounds.BOX_SIZE_OFFSET_, newBoxSize);
  303. }
  304. }
  305. };
  306. /**
  307. * A canned "sinf" box for use when adding fake encryption metadata to init
  308. * segments.
  309. *
  310. * @const {!shaka.util.Lazy.<!Uint8Array>}
  311. * @private
  312. * @see https://github.com/shaka-project/shaka-player/issues/2759
  313. */
  314. shaka.media.ContentWorkarounds.CANNED_SINF_BOX_ =
  315. new shaka.util.Lazy(() => new Uint8Array([
  316. // sinf box
  317. // Size: 0x50 = 80
  318. 0x00, 0x00, 0x00, 0x50,
  319. // Type: sinf
  320. 0x73, 0x69, 0x6e, 0x66,
  321. // Children of sinf...
  322. // frma box
  323. // Size: 0x0c = 12
  324. 0x00, 0x00, 0x00, 0x0c,
  325. // Type: frma (child of sinf)
  326. 0x66, 0x72, 0x6d, 0x61,
  327. // Format: filled in later based on the source box ("avc1", "mp4a", etc)
  328. 0x00, 0x00, 0x00, 0x00,
  329. // end of frma box
  330. // schm box
  331. // Size: 0x14 = 20
  332. 0x00, 0x00, 0x00, 0x14,
  333. // Type: schm (child of sinf)
  334. 0x73, 0x63, 0x68, 0x6d,
  335. // Version: 0, Flags: 0
  336. 0x00, 0x00, 0x00, 0x00,
  337. // Scheme: cenc
  338. 0x63, 0x65, 0x6e, 0x63,
  339. // Scheme version: 1.0
  340. 0x00, 0x01, 0x00, 0x00,
  341. // end of schm box
  342. // schi box
  343. // Size: 0x28 = 40
  344. 0x00, 0x00, 0x00, 0x28,
  345. // Type: schi (child of sinf)
  346. 0x73, 0x63, 0x68, 0x69,
  347. // Children of schi...
  348. // tenc box
  349. // Size: 0x20 = 32
  350. 0x00, 0x00, 0x00, 0x20,
  351. // Type: tenc (child of schi)
  352. 0x74, 0x65, 0x6e, 0x63,
  353. // Version: 0, Flags: 0
  354. 0x00, 0x00, 0x00, 0x00,
  355. // Reserved fields
  356. 0x00, 0x00,
  357. // Default protected: true
  358. 0x01,
  359. // Default per-sample IV size: 8
  360. 0x08,
  361. // Default key ID: all zeros (dummy)
  362. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  363. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  364. // end of tenc box
  365. // end of schi box
  366. // end of sinf box
  367. ]));
  368. /**
  369. * The location of the format field in the "frma" box inside the canned "sinf"
  370. * box above.
  371. *
  372. * @const {number}
  373. * @private
  374. */
  375. shaka.media.ContentWorkarounds.CANNED_SINF_BOX_FORMAT_OFFSET_ = 0x10;
  376. /**
  377. * Offset to a box's size field.
  378. *
  379. * @const {number}
  380. * @private
  381. */
  382. shaka.media.ContentWorkarounds.BOX_SIZE_OFFSET_ = 0;
  383. /**
  384. * Offset to a box's type field.
  385. *
  386. * @const {number}
  387. * @private
  388. */
  389. shaka.media.ContentWorkarounds.BOX_TYPE_OFFSET_ = 4;
  390. /**
  391. * Offset to a box's 64-bit size field, if it has one.
  392. *
  393. * @const {number}
  394. * @private
  395. */
  396. shaka.media.ContentWorkarounds.BOX_SIZE_64_OFFSET_ = 8;
  397. /**
  398. * Box type for "encv".
  399. *
  400. * @const {number}
  401. * @private
  402. */
  403. shaka.media.ContentWorkarounds.BOX_TYPE_ENCV_ = 0x656e6376;
  404. /**
  405. * Box type for "enca".
  406. *
  407. * @const {number}
  408. * @private
  409. */
  410. shaka.media.ContentWorkarounds.BOX_TYPE_ENCA_ = 0x656e6361;