Home Reference Source

src/demux/adts.ts

  1. /**
  2. * ADTS parser helper
  3. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  4. */
  5. import { logger } from '../utils/logger';
  6. import { ErrorTypes, ErrorDetails } from '../errors';
  7. import type { HlsEventEmitter } from '../events';
  8. import { Events } from '../events';
  9. import type {
  10. DemuxedAudioTrack,
  11. AudioFrame,
  12. AudioSample,
  13. } from '../types/demuxer';
  14.  
  15. type AudioConfig = {
  16. config: number[];
  17. samplerate: number;
  18. channelCount: number;
  19. codec: string;
  20. manifestCodec: string;
  21. };
  22.  
  23. type FrameHeader = {
  24. headerLength: number;
  25. frameLength: number;
  26. stamp: number;
  27. };
  28.  
  29. export function getAudioConfig(
  30. observer,
  31. data: Uint8Array,
  32. offset: number,
  33. audioCodec: string
  34. ): AudioConfig | void {
  35. let adtsObjectType: number;
  36. let adtsExtensionSamplingIndex: number;
  37. let adtsChanelConfig: number;
  38. let config: number[];
  39. const userAgent = navigator.userAgent.toLowerCase();
  40. const manifestCodec = audioCodec;
  41. const adtsSampleingRates = [
  42. 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025,
  43. 8000, 7350,
  44. ];
  45. // byte 2
  46. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  47. const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  48. if (adtsSamplingIndex > adtsSampleingRates.length - 1) {
  49. observer.trigger(Events.ERROR, {
  50. type: ErrorTypes.MEDIA_ERROR,
  51. details: ErrorDetails.FRAG_PARSING_ERROR,
  52. fatal: true,
  53. reason: `invalid ADTS sampling index:${adtsSamplingIndex}`,
  54. });
  55. return;
  56. }
  57. adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
  58. // byte 3
  59. adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  60. logger.log(
  61. `manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`
  62. );
  63. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  64. if (/firefox/i.test(userAgent)) {
  65. if (adtsSamplingIndex >= 6) {
  66. adtsObjectType = 5;
  67. config = new Array(4);
  68. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  69. // there is a factor 2 between frame sample rate and output sample rate
  70. // multiply frequency by 2 (see table below, equivalent to substract 3)
  71. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  72. } else {
  73. adtsObjectType = 2;
  74. config = new Array(2);
  75. adtsExtensionSamplingIndex = adtsSamplingIndex;
  76. }
  77. // Android : always use AAC
  78. } else if (userAgent.indexOf('android') !== -1) {
  79. adtsObjectType = 2;
  80. config = new Array(2);
  81. adtsExtensionSamplingIndex = adtsSamplingIndex;
  82. } else {
  83. /* for other browsers (Chrome/Vivaldi/Opera ...)
  84. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  85. */
  86. adtsObjectType = 5;
  87. config = new Array(4);
  88. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  89. if (
  90. (audioCodec &&
  91. (audioCodec.indexOf('mp4a.40.29') !== -1 ||
  92. audioCodec.indexOf('mp4a.40.5') !== -1)) ||
  93. (!audioCodec && adtsSamplingIndex >= 6)
  94. ) {
  95. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  96. // there is a factor 2 between frame sample rate and output sample rate
  97. // multiply frequency by 2 (see table below, equivalent to substract 3)
  98. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  99. } else {
  100. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  101. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  102. if (
  103. (audioCodec &&
  104. audioCodec.indexOf('mp4a.40.2') !== -1 &&
  105. ((adtsSamplingIndex >= 6 && adtsChanelConfig === 1) ||
  106. /vivaldi/i.test(userAgent))) ||
  107. (!audioCodec && adtsChanelConfig === 1)
  108. ) {
  109. adtsObjectType = 2;
  110. config = new Array(2);
  111. }
  112. adtsExtensionSamplingIndex = adtsSamplingIndex;
  113. }
  114. }
  115. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  116. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  117. Audio Profile / Audio Object Type
  118. 0: Null
  119. 1: AAC Main
  120. 2: AAC LC (Low Complexity)
  121. 3: AAC SSR (Scalable Sample Rate)
  122. 4: AAC LTP (Long Term Prediction)
  123. 5: SBR (Spectral Band Replication)
  124. 6: AAC Scalable
  125. sampling freq
  126. 0: 96000 Hz
  127. 1: 88200 Hz
  128. 2: 64000 Hz
  129. 3: 48000 Hz
  130. 4: 44100 Hz
  131. 5: 32000 Hz
  132. 6: 24000 Hz
  133. 7: 22050 Hz
  134. 8: 16000 Hz
  135. 9: 12000 Hz
  136. 10: 11025 Hz
  137. 11: 8000 Hz
  138. 12: 7350 Hz
  139. 13: Reserved
  140. 14: Reserved
  141. 15: frequency is written explictly
  142. Channel Configurations
  143. These are the channel configurations:
  144. 0: Defined in AOT Specifc Config
  145. 1: 1 channel: front-center
  146. 2: 2 channels: front-left, front-right
  147. */
  148. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  149. config[0] = adtsObjectType << 3;
  150. // samplingFrequencyIndex
  151. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  152. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  153. // channelConfiguration
  154. config[1] |= adtsChanelConfig << 3;
  155. if (adtsObjectType === 5) {
  156. // adtsExtensionSampleingIndex
  157. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  158. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  159. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  160. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  161. config[2] |= 2 << 2;
  162. config[3] = 0;
  163. }
  164. return {
  165. config,
  166. samplerate: adtsSampleingRates[adtsSamplingIndex],
  167. channelCount: adtsChanelConfig,
  168. codec: 'mp4a.40.' + adtsObjectType,
  169. manifestCodec,
  170. };
  171. }
  172.  
  173. export function isHeaderPattern(data: Uint8Array, offset: number): boolean {
  174. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  175. }
  176.  
  177. export function getHeaderLength(data: Uint8Array, offset: number): number {
  178. return data[offset + 1] & 0x01 ? 7 : 9;
  179. }
  180.  
  181. export function getFullFrameLength(data: Uint8Array, offset: number): number {
  182. return (
  183. ((data[offset + 3] & 0x03) << 11) |
  184. (data[offset + 4] << 3) |
  185. ((data[offset + 5] & 0xe0) >>> 5)
  186. );
  187. }
  188.  
  189. export function canGetFrameLength(data: Uint8Array, offset: number): boolean {
  190. return offset + 5 < data.length;
  191. }
  192.  
  193. export function isHeader(data: Uint8Array, offset: number): boolean {
  194. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  195. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  196. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  197. return offset + 1 < data.length && isHeaderPattern(data, offset);
  198. }
  199.  
  200. export function canParse(data: Uint8Array, offset: number): boolean {
  201. return (
  202. canGetFrameLength(data, offset) &&
  203. isHeaderPattern(data, offset) &&
  204. getFullFrameLength(data, offset) <= data.length - offset
  205. );
  206. }
  207.  
  208. export function probe(data: Uint8Array, offset: number): boolean {
  209. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  210. // or end of data is reached
  211. if (isHeader(data, offset)) {
  212. // ADTS header Length
  213. const headerLength = getHeaderLength(data, offset);
  214. if (offset + headerLength >= data.length) {
  215. return false;
  216. }
  217. // ADTS frame Length
  218. const frameLength = getFullFrameLength(data, offset);
  219. if (frameLength <= headerLength) {
  220. return false;
  221. }
  222.  
  223. const newOffset = offset + frameLength;
  224. return newOffset === data.length || isHeader(data, newOffset);
  225. }
  226. return false;
  227. }
  228.  
  229. export function initTrackConfig(
  230. track: DemuxedAudioTrack,
  231. observer: HlsEventEmitter,
  232. data: Uint8Array,
  233. offset: number,
  234. audioCodec: string
  235. ) {
  236. if (!track.samplerate) {
  237. const config = getAudioConfig(observer, data, offset, audioCodec);
  238. if (!config) {
  239. return;
  240. }
  241. track.config = config.config;
  242. track.samplerate = config.samplerate;
  243. track.channelCount = config.channelCount;
  244. track.codec = config.codec;
  245. track.manifestCodec = config.manifestCodec;
  246. logger.log(
  247. `parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`
  248. );
  249. }
  250. }
  251.  
  252. export function getFrameDuration(samplerate: number): number {
  253. return (1024 * 90000) / samplerate;
  254. }
  255.  
  256. export function parseFrameHeader(
  257. data: Uint8Array,
  258. offset: number,
  259. pts: number,
  260. frameIndex: number,
  261. frameDuration: number
  262. ): FrameHeader | void {
  263. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  264. const headerLength = getHeaderLength(data, offset);
  265. // retrieve frame size
  266. let frameLength = getFullFrameLength(data, offset);
  267. frameLength -= headerLength;
  268.  
  269. if (frameLength > 0) {
  270. const stamp = pts + frameIndex * frameDuration;
  271. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  272. return { headerLength, frameLength, stamp };
  273. }
  274. }
  275.  
  276. export function appendFrame(
  277. track: DemuxedAudioTrack,
  278. data: Uint8Array,
  279. offset: number,
  280. pts: number,
  281. frameIndex: number
  282. ): AudioFrame | void {
  283. const frameDuration = getFrameDuration(track.samplerate as number);
  284. const header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
  285. if (header) {
  286. const { frameLength, headerLength, stamp } = header;
  287. const length = headerLength + frameLength;
  288. const missing = Math.max(0, offset + length - data.length);
  289. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  290. let unit: Uint8Array;
  291. if (missing) {
  292. unit = new Uint8Array(length - headerLength);
  293. unit.set(data.subarray(offset + headerLength, data.length), 0);
  294. } else {
  295. unit = data.subarray(offset + headerLength, offset + length);
  296. }
  297.  
  298. const sample: AudioSample = {
  299. unit,
  300. pts: stamp,
  301. };
  302. if (!missing) {
  303. track.samples.push(sample as AudioSample);
  304. }
  305.  
  306. return { sample, length, missing };
  307. }
  308. }