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