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