Source: lib/media/segment_utils.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.SegmentUtils');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.media.Capabilities');
  10. goog.require('shaka.media.ClosedCaptionParser');
  11. goog.require('shaka.util.BufferUtils');
  12. goog.require('shaka.util.ManifestParserUtils');
  13. goog.require('shaka.util.MimeUtils');
  14. goog.require('shaka.util.Mp4BoxParsers');
  15. goog.require('shaka.util.Mp4Parser');
  16. goog.require('shaka.util.TsParser');
  17. /**
  18. * @summary Utility functions for segment parsing.
  19. */
  20. shaka.media.SegmentUtils = class {
  21. /**
  22. * @param {string} mimeType
  23. * @return {shaka.media.SegmentUtils.BasicInfo}
  24. */
  25. static getBasicInfoFromMimeType(mimeType) {
  26. const baseMimeType = shaka.util.MimeUtils.getBasicType(mimeType);
  27. const type = baseMimeType.split('/')[0];
  28. const codecs = shaka.util.MimeUtils.getCodecs(mimeType);
  29. return {
  30. type: type,
  31. mimeType: baseMimeType,
  32. codecs: codecs,
  33. language: null,
  34. height: null,
  35. width: null,
  36. channelCount: null,
  37. sampleRate: null,
  38. closedCaptions: new Map(),
  39. videoRange: null,
  40. colorGamut: null,
  41. frameRate: null,
  42. };
  43. }
  44. /**
  45. * @param {!BufferSource} data
  46. * @return {?shaka.media.SegmentUtils.BasicInfo}
  47. */
  48. static getBasicInfoFromTs(data) {
  49. const uint8ArrayData = shaka.util.BufferUtils.toUint8(data);
  50. const tsParser = new shaka.util.TsParser().parse(uint8ArrayData);
  51. const tsCodecs = tsParser.getCodecs();
  52. const videoInfo = tsParser.getVideoInfo();
  53. const codecs = [];
  54. let hasAudio = false;
  55. let hasVideo = false;
  56. switch (tsCodecs.audio) {
  57. case 'aac':
  58. case 'aac-loas':
  59. codecs.push('mp4a.40.2');
  60. hasAudio = true;
  61. break;
  62. case 'mp3':
  63. codecs.push('mp4a.40.34');
  64. hasAudio = true;
  65. break;
  66. case 'ac3':
  67. codecs.push('ac-3');
  68. hasAudio = true;
  69. break;
  70. case 'ec3':
  71. codecs.push('ec-3');
  72. hasAudio = true;
  73. break;
  74. case 'opus':
  75. codecs.push('opus');
  76. hasAudio = true;
  77. break;
  78. }
  79. switch (tsCodecs.video) {
  80. case 'avc':
  81. if (videoInfo.codec) {
  82. codecs.push(videoInfo.codec);
  83. } else {
  84. codecs.push('avc1.42E01E');
  85. }
  86. hasVideo = true;
  87. break;
  88. case 'hvc':
  89. if (videoInfo.codec) {
  90. codecs.push(videoInfo.codec);
  91. } else {
  92. codecs.push('hvc1.1.6.L93.90');
  93. }
  94. hasVideo = true;
  95. break;
  96. case 'av1':
  97. codecs.push('av01.0.01M.08');
  98. hasVideo = true;
  99. break;
  100. }
  101. if (!codecs.length) {
  102. return null;
  103. }
  104. const onlyAudio = hasAudio && !hasVideo;
  105. const closedCaptions = new Map();
  106. if (hasVideo) {
  107. const captionParser = new shaka.media.ClosedCaptionParser('video/mp2t');
  108. captionParser.parseFrom(data);
  109. for (const stream of captionParser.getStreams()) {
  110. closedCaptions.set(stream, stream);
  111. }
  112. captionParser.reset();
  113. }
  114. return {
  115. type: onlyAudio ? 'audio' : 'video',
  116. mimeType: 'video/mp2t',
  117. codecs: codecs.join(', '),
  118. language: null,
  119. height: videoInfo.height,
  120. width: videoInfo.width,
  121. channelCount: null,
  122. sampleRate: null,
  123. closedCaptions: closedCaptions,
  124. videoRange: null,
  125. colorGamut: null,
  126. frameRate: videoInfo.frameRate,
  127. };
  128. }
  129. /**
  130. * @param {?BufferSource} initData
  131. * @param {!BufferSource} data
  132. * @return {?shaka.media.SegmentUtils.BasicInfo}
  133. */
  134. static getBasicInfoFromMp4(initData, data) {
  135. const Mp4Parser = shaka.util.Mp4Parser;
  136. const SegmentUtils = shaka.media.SegmentUtils;
  137. const audioCodecs = [];
  138. let videoCodecs = [];
  139. let hasAudio = false;
  140. let hasVideo = false;
  141. const addCodec = (codec) => {
  142. const codecLC = codec.toLowerCase();
  143. switch (codecLC) {
  144. case 'avc1':
  145. case 'avc3':
  146. videoCodecs.push(codecLC + '.42E01E');
  147. hasVideo = true;
  148. break;
  149. case 'hev1':
  150. case 'hvc1':
  151. videoCodecs.push(codecLC + '.1.6.L93.90');
  152. hasVideo = true;
  153. break;
  154. case 'dvh1':
  155. case 'dvhe':
  156. videoCodecs.push(codecLC + '.05.04');
  157. hasVideo = true;
  158. break;
  159. case 'vp09':
  160. videoCodecs.push(codecLC + '.00.10.08');
  161. hasVideo = true;
  162. break;
  163. case 'av01':
  164. videoCodecs.push(codecLC + '.0.01M.08');
  165. hasVideo = true;
  166. break;
  167. case 'mp4a':
  168. // We assume AAC, but this can be wrong since mp4a supports
  169. // others codecs
  170. audioCodecs.push('mp4a.40.2');
  171. hasAudio = true;
  172. break;
  173. case 'ac-3':
  174. case 'ec-3':
  175. case 'ac-4':
  176. case 'opus':
  177. case 'flac':
  178. audioCodecs.push(codecLC);
  179. hasAudio = true;
  180. break;
  181. }
  182. };
  183. const codecBoxParser = (box) => addCodec(box.name);
  184. /** @type {?string} */
  185. let language = null;
  186. /** @type {?string} */
  187. let height = null;
  188. /** @type {?string} */
  189. let width = null;
  190. /** @type {?number} */
  191. let channelCount = null;
  192. /** @type {?number} */
  193. let sampleRate = null;
  194. /** @type {?string} */
  195. let realVideoRange = null;
  196. /** @type {?string} */
  197. let realColorGamut = null;
  198. /** @type {?string} */
  199. const realFrameRate = null;
  200. /** @type {?string} */
  201. let baseBox;
  202. const genericAudioBox = (box) => {
  203. const parsedAudioSampleEntryBox =
  204. shaka.util.Mp4BoxParsers.audioSampleEntry(box.reader);
  205. channelCount = parsedAudioSampleEntryBox.channelCount;
  206. sampleRate = parsedAudioSampleEntryBox.sampleRate;
  207. codecBoxParser(box);
  208. };
  209. const genericVideoBox = (box) => {
  210. baseBox = box.name;
  211. const parsedVisualSampleEntryBox =
  212. shaka.util.Mp4BoxParsers.visualSampleEntry(box.reader);
  213. width = String(parsedVisualSampleEntryBox.width);
  214. height = String(parsedVisualSampleEntryBox.height);
  215. if (box.reader.hasMoreData()) {
  216. Mp4Parser.children(box);
  217. }
  218. };
  219. new Mp4Parser()
  220. .box('moov', Mp4Parser.children)
  221. .box('trak', Mp4Parser.children)
  222. .box('mdia', Mp4Parser.children)
  223. .fullBox('mdhd', (box) => {
  224. goog.asserts.assert(
  225. box.version != null,
  226. 'MDHD is a full box and should have a valid version.');
  227. const parsedMDHDBox = shaka.util.Mp4BoxParsers.parseMDHD(
  228. box.reader, box.version);
  229. language = parsedMDHDBox.language;
  230. })
  231. .box('minf', Mp4Parser.children)
  232. .box('stbl', Mp4Parser.children)
  233. .fullBox('stsd', Mp4Parser.sampleDescription)
  234. // AUDIO
  235. // These are the various boxes that signal a codec.
  236. .box('mp4a', (box) => {
  237. const parsedAudioSampleEntryBox =
  238. shaka.util.Mp4BoxParsers.audioSampleEntry(box.reader);
  239. channelCount = parsedAudioSampleEntryBox.channelCount;
  240. sampleRate = parsedAudioSampleEntryBox.sampleRate;
  241. if (box.reader.hasMoreData()) {
  242. Mp4Parser.children(box);
  243. } else {
  244. codecBoxParser(box);
  245. }
  246. })
  247. .box('esds', (box) => {
  248. const parsedESDSBox = shaka.util.Mp4BoxParsers.parseESDS(box.reader);
  249. audioCodecs.push(parsedESDSBox.codec);
  250. hasAudio = true;
  251. })
  252. .box('ac-3', genericAudioBox)
  253. .box('ec-3', genericAudioBox)
  254. .box('ac-4', genericAudioBox)
  255. .box('Opus', genericAudioBox)
  256. .box('fLaC', genericAudioBox)
  257. // VIDEO
  258. // These are the various boxes that signal a codec.
  259. .box('avc1', genericVideoBox)
  260. .box('avc3', genericVideoBox)
  261. .box('hev1', genericVideoBox)
  262. .box('hvc1', genericVideoBox)
  263. .box('dva1', genericVideoBox)
  264. .box('dvav', genericVideoBox)
  265. .box('dvh1', genericVideoBox)
  266. .box('dvhe', genericVideoBox)
  267. .box('vp09', genericVideoBox)
  268. .box('av01', genericVideoBox)
  269. .box('avcC', (box) => {
  270. let codecBase = baseBox || '';
  271. switch (baseBox) {
  272. case 'dvav':
  273. codecBase = 'avc3';
  274. break;
  275. case 'dva1':
  276. codecBase = 'avc1';
  277. break;
  278. }
  279. const parsedAVCCBox = shaka.util.Mp4BoxParsers.parseAVCC(
  280. codecBase, box.reader, box.name);
  281. videoCodecs.push(parsedAVCCBox.codec);
  282. hasVideo = true;
  283. })
  284. .box('hvcC', (box) => {
  285. let codecBase = baseBox || '';
  286. switch (baseBox) {
  287. case 'dvh1':
  288. codecBase = 'hvc1';
  289. break;
  290. case 'dvhe':
  291. codecBase = 'hev1';
  292. break;
  293. }
  294. const parsedHVCCBox = shaka.util.Mp4BoxParsers.parseHVCC(
  295. codecBase, box.reader, box.name);
  296. videoCodecs.push(parsedHVCCBox.codec);
  297. hasVideo = true;
  298. })
  299. .box('dvcC', (box) => {
  300. let codecBase = baseBox || '';
  301. switch (baseBox) {
  302. case 'hvc1':
  303. codecBase = 'dvh1';
  304. break;
  305. case 'hev1':
  306. codecBase = 'dvhe';
  307. break;
  308. case 'avc1':
  309. codecBase = 'dva1';
  310. break;
  311. case 'avc3':
  312. codecBase = 'dvav';
  313. break;
  314. case 'av01':
  315. codecBase = 'dav1';
  316. break;
  317. }
  318. const parsedDVCCBox = shaka.util.Mp4BoxParsers.parseDVCC(
  319. codecBase, box.reader, box.name);
  320. videoCodecs.push(parsedDVCCBox.codec);
  321. hasVideo = true;
  322. })
  323. .box('dvvC', (box) => {
  324. let codecBase = baseBox || '';
  325. switch (baseBox) {
  326. case 'hvc1':
  327. codecBase = 'dvh1';
  328. break;
  329. case 'hev1':
  330. codecBase = 'dvhe';
  331. break;
  332. case 'avc1':
  333. codecBase = 'dva1';
  334. break;
  335. case 'avc3':
  336. codecBase = 'dvav';
  337. break;
  338. case 'av01':
  339. codecBase = 'dav1';
  340. break;
  341. }
  342. const parsedDVCCBox = shaka.util.Mp4BoxParsers.parseDVVC(
  343. codecBase, box.reader, box.name);
  344. videoCodecs.push(parsedDVCCBox.codec);
  345. hasVideo = true;
  346. })
  347. .fullBox('vpcC', (box) => {
  348. const codecBase = baseBox || '';
  349. const parsedVPCCBox = shaka.util.Mp4BoxParsers.parseVPCC(
  350. codecBase, box.reader, box.name);
  351. videoCodecs.push(parsedVPCCBox.codec);
  352. hasVideo = true;
  353. })
  354. .box('av1C', (box) => {
  355. let codecBase = baseBox || '';
  356. switch (baseBox) {
  357. case 'dav1':
  358. codecBase = 'av01';
  359. break;
  360. }
  361. const parsedAV1CBox = shaka.util.Mp4BoxParsers.parseAV1C(
  362. codecBase, box.reader, box.name);
  363. videoCodecs.push(parsedAV1CBox.codec);
  364. hasVideo = true;
  365. })
  366. // This signals an encrypted sample, which we can go inside of to
  367. // find the codec used.
  368. // Note: If encrypted, you can only have audio or video, not both.
  369. .box('enca', Mp4Parser.audioSampleEntry)
  370. .box('encv', Mp4Parser.visualSampleEntry)
  371. .box('sinf', Mp4Parser.children)
  372. .box('frma', (box) => {
  373. const {codec} = shaka.util.Mp4BoxParsers.parseFRMA(box.reader);
  374. addCodec(codec);
  375. })
  376. .box('colr', (box) => {
  377. videoCodecs = videoCodecs.map((codec) => {
  378. if (codec.startsWith('av01.')) {
  379. return shaka.util.Mp4BoxParsers.updateAV1CodecWithCOLRBox(
  380. codec, box.reader);
  381. }
  382. return codec;
  383. });
  384. const {videoRange, colorGamut} =
  385. shaka.util.Mp4BoxParsers.parseCOLR(box.reader);
  386. realVideoRange = videoRange;
  387. realColorGamut = colorGamut;
  388. })
  389. .parse(initData || data, /* partialOkay= */ true);
  390. if (!audioCodecs.length && !videoCodecs.length) {
  391. return null;
  392. }
  393. const onlyAudio = hasAudio && !hasVideo;
  394. const closedCaptions = new Map();
  395. if (hasVideo) {
  396. const captionParser = new shaka.media.ClosedCaptionParser('video/mp4');
  397. if (initData) {
  398. captionParser.init(initData);
  399. }
  400. captionParser.parseFrom(data);
  401. for (const stream of captionParser.getStreams()) {
  402. closedCaptions.set(stream, stream);
  403. }
  404. captionParser.reset();
  405. }
  406. const codecs = audioCodecs.concat(videoCodecs);
  407. return {
  408. type: onlyAudio ? 'audio' : 'video',
  409. mimeType: onlyAudio ? 'audio/mp4' : 'video/mp4',
  410. codecs: SegmentUtils.codecsFiltering(codecs).join(', '),
  411. language: language,
  412. height: height,
  413. width: width,
  414. channelCount: channelCount,
  415. sampleRate: sampleRate,
  416. closedCaptions: closedCaptions,
  417. videoRange: realVideoRange,
  418. colorGamut: realColorGamut,
  419. frameRate: realFrameRate,
  420. };
  421. }
  422. /**
  423. * @param {!Array.<string>} codecs
  424. * @return {!Array.<string>} codecs
  425. */
  426. static codecsFiltering(codecs) {
  427. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  428. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  429. const SegmentUtils = shaka.media.SegmentUtils;
  430. const allCodecs = SegmentUtils.filterDuplicateCodecs_(codecs);
  431. const audioCodecs =
  432. ManifestParserUtils.guessAllCodecsSafe(ContentType.AUDIO, allCodecs);
  433. const videoCodecs =
  434. ManifestParserUtils.guessAllCodecsSafe(ContentType.VIDEO, allCodecs);
  435. const textCodecs =
  436. ManifestParserUtils.guessAllCodecsSafe(ContentType.TEXT, allCodecs);
  437. const validVideoCodecs = SegmentUtils.chooseBetterCodecs_(videoCodecs);
  438. const finalCodecs =
  439. audioCodecs.concat(validVideoCodecs).concat(textCodecs);
  440. if (allCodecs.length && !finalCodecs.length) {
  441. return allCodecs;
  442. }
  443. return finalCodecs;
  444. }
  445. /**
  446. * @param {!Array.<string>} codecs
  447. * @return {!Array.<string>} codecs
  448. * @private
  449. */
  450. static filterDuplicateCodecs_(codecs) {
  451. // Filter out duplicate codecs.
  452. const seen = new Set();
  453. const ret = [];
  454. for (const codec of codecs) {
  455. const shortCodec = shaka.util.MimeUtils.getCodecBase(codec);
  456. if (!seen.has(shortCodec)) {
  457. ret.push(codec);
  458. seen.add(shortCodec);
  459. } else {
  460. shaka.log.debug('Ignoring duplicate codec');
  461. }
  462. }
  463. return ret;
  464. }
  465. /**
  466. * Prioritizes Dolby Vision if supported. This is necessary because with
  467. * Dolby Vision we could have hvcC and dvcC boxes at the same time.
  468. *
  469. * @param {!Array.<string>} codecs
  470. * @return {!Array.<string>} codecs
  471. * @private
  472. */
  473. static chooseBetterCodecs_(codecs) {
  474. if (codecs.length <= 1) {
  475. return codecs;
  476. }
  477. const dolbyVision = codecs.find((codec) => {
  478. return codec.startsWith('dvav.') ||
  479. codec.startsWith('dva1.') ||
  480. codec.startsWith('dvh1.') ||
  481. codec.startsWith('dvhe.') ||
  482. codec.startsWith('dav1.') ||
  483. codec.startsWith('dvc1.') ||
  484. codec.startsWith('dvi1.');
  485. });
  486. if (!dolbyVision) {
  487. return codecs;
  488. }
  489. const type = `video/mp4; codecs="${dolbyVision}"`;
  490. if (shaka.media.Capabilities.isTypeSupported(type)) {
  491. return [dolbyVision];
  492. }
  493. return codecs.filter((codec) => codec != dolbyVision);
  494. }
  495. /**
  496. * @param {!BufferSource} data
  497. * @return {?string}
  498. */
  499. static getDefaultKID(data) {
  500. const Mp4Parser = shaka.util.Mp4Parser;
  501. let defaultKID = null;
  502. new Mp4Parser()
  503. .box('moov', Mp4Parser.children)
  504. .box('trak', Mp4Parser.children)
  505. .box('mdia', Mp4Parser.children)
  506. .box('minf', Mp4Parser.children)
  507. .box('stbl', Mp4Parser.children)
  508. .fullBox('stsd', Mp4Parser.sampleDescription)
  509. .box('encv', Mp4Parser.visualSampleEntry)
  510. .box('enca', Mp4Parser.audioSampleEntry)
  511. .box('sinf', Mp4Parser.children)
  512. .box('schi', Mp4Parser.children)
  513. .fullBox('tenc', (box) => {
  514. const parsedTENCBox = shaka.util.Mp4BoxParsers.parseTENC(box.reader);
  515. defaultKID = parsedTENCBox.defaultKID;
  516. })
  517. .parse(data, /* partialOkay= */ true);
  518. return defaultKID;
  519. }
  520. /**
  521. * @param {!BufferSource} rawResult
  522. * @param {shaka.extern.aesKey} aesKey
  523. * @param {number} position
  524. * @return {!Promise.<!BufferSource>}
  525. */
  526. static async aesDecrypt(rawResult, aesKey, position) {
  527. const key = aesKey;
  528. if (!key.cryptoKey) {
  529. goog.asserts.assert(key.fetchKey, 'If AES cryptoKey was not ' +
  530. 'preloaded, fetchKey function should be provided');
  531. await key.fetchKey();
  532. goog.asserts.assert(key.cryptoKey, 'AES cryptoKey should now be set');
  533. }
  534. let iv = key.iv;
  535. if (!iv) {
  536. iv = shaka.util.BufferUtils.toUint8(new ArrayBuffer(16));
  537. let sequence = key.firstMediaSequenceNumber + position;
  538. for (let i = iv.byteLength - 1; i >= 0; i--) {
  539. iv[i] = sequence & 0xff;
  540. sequence >>= 8;
  541. }
  542. }
  543. let algorithm;
  544. if (aesKey.blockCipherMode == 'CBC') {
  545. algorithm = {
  546. name: 'AES-CBC',
  547. iv,
  548. };
  549. } else {
  550. algorithm = {
  551. name: 'AES-CTR',
  552. counter: iv,
  553. // NIST SP800-38A standard suggests that the counter should occupy half
  554. // of the counter block
  555. length: 64,
  556. };
  557. }
  558. return window.crypto.subtle.decrypt(algorithm, key.cryptoKey, rawResult);
  559. }
  560. };
  561. /**
  562. * @typedef {{
  563. * type: string,
  564. * mimeType: string,
  565. * codecs: string,
  566. * language: ?string,
  567. * height: ?string,
  568. * width: ?string,
  569. * channelCount: ?number,
  570. * sampleRate: ?number,
  571. * closedCaptions: Map.<string, string>,
  572. * videoRange: ?string,
  573. * colorGamut: ?string,
  574. * frameRate: ?string
  575. * }}
  576. *
  577. * @property {string} type
  578. * @property {string} mimeType
  579. * @property {string} codecs
  580. * @property {?string} language
  581. * @property {?string} height
  582. * @property {?string} width
  583. * @property {?number} channelCount
  584. * @property {?number} sampleRate
  585. * @property {Map.<string, string>} closedCaptions
  586. * @property {?string} videoRange
  587. * @property {?string} colorGamut
  588. * @property {?string} frameRate
  589. */
  590. shaka.media.SegmentUtils.BasicInfo;