forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

lib.rs413 lines, 15.6 KiBHistoryRawDownload
1//! Pure-Rust **AAC-LC decoder + encoder**, no C and no FFI.
2//!
3//! Extracted from (and the engine of) the
4//! [`remade_ffmpeg_rs`](https://github.com/Remade-With-Rust/remade_ffmpeg_rs)
5//! project. The crate has **zero dependencies**.
6//!
7//! - **Decoder**: complete AAC-LC — long/short/transition windows with grouped
8//! scalefactors, all spectral Huffman codebooks, M/S and intensity stereo,
9//! PNS, TNS — verified against FFmpeg (bit-exact on deterministic features).
10//! Entry point: [`AacDecoder`] (handles ADTS framing and raw MP4 access
11//! units alike) or the lower-level [`decode::Decoder`].
12//! - **Encoder**: psychoacoustic Bark-scale masking model, two-phase bitrate
13//! rate loop, transient-driven block switching, per-SFB M/S stereo, and a
14//! frame-parallel `encode_stream` (~450× realtime). Entry point:
15//! [`AacEncoder`] with [`AacEncoderConfig`].
16//! - **Framing & config**: [`AudioSpecificConfig`] (the MP4 `esds` payload)
17//! and [`AdtsHeader`] (the `.aac` elementary-stream header) parsers plus
18//! their serializers ([`write_audio_specific_config`], [`write_adts_header`],
19//! [`audio_specific_config_bytes`]).
20//!
21//! The `simd` feature (default) enables runtime-detected AVX2 kernels;
22//! `--no-default-features` gives a 100%-safe scalar build. `simd-avx512` adds
23//! an opt-in AVX-512 tier.
24
25mod bits;
26mod codebook;
27pub mod decode;
28mod dsp;
29pub mod encode;
30mod error;
31mod huffman;
32mod ics;
33/// LATM/LOAS transport (ISO 14496-3 §1.7) — the MPEG-TS / broadcast carriage
34/// format, alongside ADTS (`.aac`) and MP4 `esds`.
35pub mod latm;
36/// The quality lab (feature `lab`): deterministic corpus, the NMR metric, and the
37/// bitrate-ladder runner. This is the verdict instrument for the Great Gate
38/// campaign — see `docs/codec-aac-great-gate.md`.
39#[cfg(feature = "lab")]
40pub mod lab;
41/// HE-AAC (SBR / Parametric Stereo) signalling and capability reporting — the
42/// broadcast and low-bitrate-streaming configuration. See the module docs for
43/// exactly which parts are implemented.
44pub mod sbr;
45mod swb;
46mod tables;
47
48pub use bits::BitReader;
49pub use encode::{
50 audio_specific_config_bytes, write_adts_header, write_audio_specific_config, AacEncoder,
51 AacEncoderConfig, EncodedPacket, WindowShape,
52};
53pub use error::{Error, Result};
54
55/// AAC sample-rate table, indexed by `samplingFrequencyIndex` (ISO 14496-3).
56pub const SAMPLE_RATES: [u32; 13] = [
57 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
58];
59
60/// Map a 4-bit sampling-frequency index to a rate (0 for the reserved/escape
61/// values 13-15, which require an explicit 24-bit rate).
62pub fn sample_rate_for_index(idx: u8) -> u32 {
63 SAMPLE_RATES.get(idx as usize).copied().unwrap_or(0)
64}
65
66/// Map a sampling rate to its 4-bit index, or None if non-standard (the encoder
67/// then uses the 0x0F + explicit-24-bit-rate escape).
68pub fn sf_index_for_rate(rate: u32) -> Option<u8> {
69 SAMPLE_RATES
70 .iter()
71 .position(|&r| r == rate)
72 .map(|i| i as u8)
73}
74
75// ---------------------------------------------------------------------------
76// AudioSpecificConfig — the MP4 `esds` DecoderSpecificInfo (raw AAC config).
77// ---------------------------------------------------------------------------
78
79/// Parsed `AudioSpecificConfig` (ISO 14496-3 §1.6.2.1).
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81pub struct AudioSpecificConfig {
82 /// Audio Object Type (2 = AAC-LC, the only one we target).
83 pub object_type: u8,
84 pub sample_rate: u32,
85 /// Channel configuration (1 = mono, 2 = stereo, …).
86 pub channels: u16,
87}
88
89/// Parse an `AudioSpecificConfig` from its raw bytes (the `esds`/`stsd` config).
90pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
91 let mut r = BitReader::new(data);
92 let object_type = read_object_type(&mut r)?;
93 let sf_index = r.read_bits(4)? as u8;
94 let sample_rate = if sf_index == 0x0F {
95 r.read_bits(24)?
96 } else {
97 sample_rate_for_index(sf_index)
98 };
99 let channels = r.read_bits(4)? as u16;
100 if sample_rate == 0 {
101 return Err(Error::invalid("aac: invalid sampling frequency in config"));
102 }
103 Ok(AudioSpecificConfig {
104 object_type,
105 sample_rate,
106 channels,
107 })
108}
109
110/// Read the (possibly escaped) 5-bit Audio Object Type.
111fn read_object_type(r: &mut BitReader) -> Result<u8> {
112 let ot = r.read_bits(5)? as u8;
113 if ot == 31 {
114 Ok((32 + r.read_bits(6)?) as u8)
115 } else {
116 Ok(ot)
117 }
118}
119
120// ---------------------------------------------------------------------------
121// ADTS — the `.aac` elementary-stream frame header.
122// ---------------------------------------------------------------------------
123
124/// A parsed ADTS frame header (ISO 14496-3 §1.A.2.2.1).
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct AdtsHeader {
127 /// Audio Object Type (profile + 1).
128 pub object_type: u8,
129 pub sample_rate: u32,
130 pub channels: u16,
131 /// Total frame length including this header.
132 pub frame_length: usize,
133 /// Header size in bytes (7 without CRC, 9 with).
134 pub header_len: usize,
135}
136
137/// True if `data` begins with an ADTS syncword (0xFFF, layer 00).
138pub fn is_adts(data: &[u8]) -> bool {
139 data.len() >= 2 && data[0] == 0xFF && (data[1] & 0xF6) == 0xF0
140}
141
142/// Parse an ADTS header from the start of `data`.
143pub fn parse_adts(data: &[u8]) -> Result<AdtsHeader> {
144 if !is_adts(data) || data.len() < 7 {
145 return Err(Error::invalid("aac: not an ADTS frame"));
146 }
147 let mut r = BitReader::new(data);
148 r.skip(12)?; // syncword
149 r.skip(1)?; // MPEG version
150 r.skip(2)?; // layer (00)
151 let protection_absent = r.read_bool()?;
152 let profile = r.read_bits(2)? as u8; // object_type - 1
153 let sf_index = r.read_bits(4)? as u8;
154 r.skip(1)?; // private
155 let channel_config = r.read_bits(3)? as u16;
156 r.skip(4)?; // original/home/copyright id+start
157 let frame_length = r.read_bits(13)? as usize;
158 // remaining: buffer_fullness(11) + num_raw_data_blocks(2) — not needed here.
159 let sample_rate = sample_rate_for_index(sf_index);
160 if sample_rate == 0 || frame_length < 7 {
161 return Err(Error::invalid("aac: invalid ADTS header"));
162 }
163 Ok(AdtsHeader {
164 object_type: profile + 1,
165 sample_rate,
166 channels: channel_config,
167 frame_length,
168 header_len: if protection_absent { 7 } else { 9 },
169 })
170}
171
172// ---------------------------------------------------------------------------
173// Decoded PCM — the decoder's native output.
174// ---------------------------------------------------------------------------
175
176/// One decoded frame of PCM: interleaved `f32` samples in [-1, 1].
177#[derive(Debug, Clone)]
178pub struct DecodedAudio {
179 pub sample_rate: u32,
180 pub channels: u16,
181 /// Interleaved samples (`samples.len() = frames × channels`).
182 pub samples: Vec<f32>,
183 /// The presentation timestamp handed to [`AacDecoder::decode`], if any.
184 pub pts: Option<i64>,
185}
186
187impl DecodedAudio {
188 /// Number of PCM frames (samples per channel).
189 pub fn frames(&self) -> usize {
190 self.samples.len() / self.channels.max(1) as usize
191 }
192}
193
194// ---------------------------------------------------------------------------
195// Decoder — stream-level: ADTS stripping + lazy core init.
196// ---------------------------------------------------------------------------
197
198/// Stream-level AAC-LC decoder: accepts either ADTS frames (`.aac` elementary
199/// streams — the config is read from the header) or bare raw access units
200/// (MP4 — configure via [`AacDecoder::with_config`] from the `esds`
201/// [`AudioSpecificConfig`]).
202#[derive(Default)]
203pub struct AacDecoder {
204 config: Option<AudioSpecificConfig>,
205 decoder: Option<decode::Decoder>,
206 /// HE-AAC parameters, when built via [`AacDecoder::with_config_bytes`].
207 sbr: Option<sbr::SbrConfig>,
208}
209
210impl AacDecoder {
211 /// A decoder that learns its parameters from the stream (ADTS headers).
212 pub fn new() -> AacDecoder {
213 AacDecoder::default()
214 }
215
216 /// A decoder pre-configured from an out-of-band [`AudioSpecificConfig`]
217 /// (the MP4 `esds` payload) — required for bare raw access units.
218 pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
219 AacDecoder {
220 config: Some(cfg),
221 decoder: None,
222 sbr: None,
223 }
224 }
225
226 /// A decoder configured from the **raw** `AudioSpecificConfig` bytes.
227 ///
228 /// Prefer this over [`with_config`](Self::with_config) whenever the raw bytes
229 /// are available (they always are — `esds`, `StreamMuxConfig`), because HE-AAC
230 /// signalling lives in fields the plain [`AudioSpecificConfig`] does not
231 /// carry. An HE-AAC stream configured through the plain path reports its
232 /// **core** rate, and a player that believes it plays the audio at half
233 /// speed.
234 pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
235 let sbr = sbr::parse_sbr_config(data)?;
236 let mut cfg = parse_audio_specific_config(data)?;
237 // The core decodes at the core rate whatever the config's first field
238 // said; for hierarchical HE-AAC that field was the extension rate.
239 if sbr.sbr_present {
240 cfg.sample_rate = sbr.core_sample_rate;
241 cfg.object_type = sbr.core_object_type;
242 }
243 Ok(AacDecoder {
244 config: Some(cfg),
245 decoder: None,
246 sbr: Some(sbr),
247 })
248 }
249
250 /// HE-AAC parameters, when the decoder was built from raw config bytes.
251 pub fn sbr_config(&self) -> Option<sbr::SbrConfig> {
252 self.sbr
253 }
254
255 /// How much of this stream can actually be reconstructed.
256 ///
257 /// [`SbrSupport::CoreOnly`](sbr::SbrSupport::CoreOnly) means the output is
258 /// real audio, correct in rate and channels, but band-limited to the core's
259 /// Nyquist because the SBR high band is not reconstructed.
260 pub fn sbr_support(&self) -> sbr::SbrSupport {
261 match self.sbr {
262 Some(s) => s.support(),
263 None => sbr::SbrSupport::NotPresent,
264 }
265 }
266
267 /// The stream's **output** sample rate.
268 ///
269 /// For HE-AAC this is twice the rate the `raw_data_block`s are coded at.
270 /// Returns `None` until the configuration is known.
271 pub fn output_sample_rate(&self) -> Option<u32> {
272 match self.sbr {
273 Some(s) if s.sbr_present => Some(s.output_sample_rate),
274 _ => self.config.map(|c| c.sample_rate),
275 }
276 }
277
278 /// Lazily build the stateful decoder once rate/channels are known.
279 fn ensure_decoder(&mut self) -> Result<&mut decode::Decoder> {
280 if self.decoder.is_none() {
281 let cfg = self
282 .config
283 .ok_or_else(|| Error::invalid("aac: stream parameters unknown"))?;
284 self.decoder = Some(decode::Decoder::new(cfg.sample_rate));
285 }
286 Ok(self.decoder.as_mut().unwrap())
287 }
288
289 /// Decode one packet (an ADTS frame or a bare raw access unit) into PCM.
290 ///
291 /// ADTS framing, if present, is stripped (and configures the decoder on
292 /// first use). Returns [`Error::Again`] for an empty packet (nothing to
293 /// decode — feed the next one).
294 pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
295 // Strip ADTS framing if present; MP4 delivers bare access units.
296 let mut data = packet;
297 if is_adts(data) {
298 let header = parse_adts(data)?;
299 if self.config.is_none() {
300 self.config = Some(AudioSpecificConfig {
301 object_type: header.object_type,
302 sample_rate: header.sample_rate,
303 channels: header.channels,
304 });
305 }
306 data = data
307 .get(header.header_len..header.frame_length.min(data.len()))
308 .unwrap_or(&[]);
309 }
310 if data.is_empty() {
311 return Err(Error::Again);
312 }
313 self.ensure_decoder()?.decode(data, pts)
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn asc_stereo_44100_aac_lc() {
323 // object_type=2 (00010), sf_index=4 (0100)=44100, channels=2 (0010).
324 // 00010 0100 0010 → 0001 0010 0001 0000 = 0x12 0x10 (trailing pad).
325 let cfg = parse_audio_specific_config(&[0x12, 0x10]).unwrap();
326 assert_eq!(cfg.object_type, 2);
327 assert_eq!(cfg.sample_rate, 44_100);
328 assert_eq!(cfg.channels, 2);
329 }
330
331 #[test]
332 fn asc_mono_48000() {
333 // object_type=2 (00010), sf_index=3 (0011)=48000, channels=1 (0001).
334 // 00010 0011 0001 → 0001 0001 1000 1... = 0x11 0x88.
335 let cfg = parse_audio_specific_config(&[0x11, 0x88]).unwrap();
336 assert_eq!(cfg.sample_rate, 48_000);
337 assert_eq!(cfg.channels, 1);
338 }
339
340 #[test]
341 fn adts_header_parses() {
342 // 7-byte ADTS header (no CRC): sync 0xFFF, MPEG-4, layer 0,
343 // protection_absent=1, profile 1 (AAC-LC), sf_index 4 (44100),
344 // channel_config 2, frame_length 100. Layout verified bit-by-bit.
345 let h = [0xFFu8, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC];
346 let hdr = parse_adts(&h).unwrap();
347 assert_eq!(hdr.object_type, 2); // profile 1 + 1
348 assert_eq!(hdr.sample_rate, 44_100);
349 assert_eq!(hdr.channels, 2);
350 assert_eq!(hdr.frame_length, 100);
351 assert_eq!(hdr.header_len, 7);
352 }
353
354 #[test]
355 fn is_adts_detects_syncword() {
356 assert!(is_adts(&[0xFF, 0xF1, 0x00]));
357 assert!(is_adts(&[0xFF, 0xF0, 0x00]));
358 assert!(!is_adts(&[0xFF, 0x00]));
359 assert!(!is_adts(&[0x00, 0xF1]));
360 }
361
362 #[test]
363 fn sample_rate_table() {
364 assert_eq!(sample_rate_for_index(3), 48_000);
365 assert_eq!(sample_rate_for_index(4), 44_100);
366 assert_eq!(sample_rate_for_index(8), 16_000);
367 assert_eq!(sample_rate_for_index(15), 0); // escape value
368 }
369
370 /// The stream-level decoder learns its config from ADTS and decodes to
371 /// interleaved PCM (encoder round-trip; the full-pipeline gates live in
372 /// `encode`'s tests).
373 #[test]
374 fn adts_stream_decodes_via_stream_decoder() {
375 let sr = 44100u32;
376 let n = 4096usize;
377 let pcm: Vec<f32> = (0..n)
378 .map(|i| {
379 ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32
380 })
381 .collect();
382 let mut enc = AacEncoder::new(AacEncoderConfig::default());
383 enc.push_pcm(&pcm, 1, sr).unwrap();
384 enc.finish();
385 let mut adts = Vec::new();
386 while let Ok(p) = enc.next_packet() {
387 let hdr = AdtsHeader {
388 object_type: 2,
389 sample_rate: sr,
390 channels: 1,
391 frame_length: 7 + p.data.len(),
392 header_len: 7,
393 };
394 adts.extend_from_slice(&write_adts_header(&hdr));
395 adts.extend_from_slice(&p.data);
396 }
397
398 let mut dec = AacDecoder::new();
399 let mut decoded = 0usize;
400 let mut pos = 0usize;
401 while pos + 7 <= adts.len() {
402 let hdr = parse_adts(&adts[pos..]).unwrap();
403 let out = dec
404 .decode(&adts[pos..pos + hdr.frame_length], None)
405 .unwrap();
406 assert_eq!(out.sample_rate, sr);
407 assert_eq!(out.channels, 1);
408 decoded += out.frames();
409 pos += hdr.frame_length;
410 }
411 assert!(decoded >= n, "decoded fewer samples than encoded");
412 }
413}