forge
Explore
Log in

Don't you dare go Hollow

AAC-LC decoder, encoder and rusty_aac shim

Browse files at this commit

9a848b4fa6828124de4e43f1b1a721248666f04eAhmet Kaan GümüşParent: cd996f4
  • feat
    • AAC-LC decoder, encoder and rusty_aac shim
Show full message
feat(aac): AAC-LC decoder, encoder and rusty_aac shim

Decoder covers AAC-LC end to end: AudioSpecificConfig and ADTS framing,
all four window sequences and both window shapes, section and scalefactor
data, every spectral codebook including the escape one, pulse data, TNS,
M/S and intensity stereo, PNS, and SCE/CPE/LFE/DSE/PCE/FIL elements.
Output is film order FL, FR, FC, LFE, BL, BR (SL, SR), which is the order
the downmix in this family folds, so a 5.1 track needs no caller-side
permutation. HE-AAC's SBR is not reconstructed: such a stream decodes to
its AAC-LC core and reports the core rate rather than claiming the
extension's.

Encoder is a full two-loop search: 2048-point FFT masking with spectral
flatness for tonality, bark-ish spreading, a relative hearing-threshold
floor, transient-driven window switching, per-band mid/side, exact
Huffman bit counts for codebook choice, and a bit reservoir against a CBR
target. Both ADTS and bare raw_data_block output.

The normative tables were derived rather than transcribed: access units
with a chosen spectral payload were decoded by a reference decoder and
read back through the inverse MDCT, which enumerates each codebook by a
binary tree walk. Every one came out with a Kraft sum of exactly 1 and
the entry count the standard prescribes.

forbid(unsafe_code) in both crates.
crates/ec-aac/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "ec-aac"
3+description = "AAC-LC decoder and encoder: ADTS and AudioSpecificConfig framing, mono through 7.1."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core = { workspace = true }
11+ec-dsp = { workspace = true }
crates/ec-aac/src/config.rsadded+310 -0
@@ -0,0 +1,310 @@
1+//! AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2) and ADTS (§1.A.2) framing.
2+
3+use ec_core::{BitReader, BitWriter, Error, Result};
4+
5+use crate::tables::SAMPLE_RATES;
6+
7+/// AAC Low Complexity.
8+pub const AOT_AAC_LC: u8 = 2;
9+/// Spectral Band Replication (HE-AAC v1).
10+pub const AOT_SBR: u8 = 5;
11+/// Parametric Stereo (HE-AAC v2).
12+pub const AOT_PS: u8 = 29;
13+
14+/// A rate's `samplingFrequencyIndex`, or `None` when AAC cannot carry it.
15+pub fn sf_index_for_rate(rate: u32) -> Option<u8> {
16+ SAMPLE_RATES
17+ .iter()
18+ .position(|&r| r == rate)
19+ .map(|i| i as u8)
20+}
21+
22+/// The rate a `samplingFrequencyIndex` names; 0 for the escape and reserved
23+/// values.
24+pub fn sample_rate_for_index(index: u8) -> u32 {
25+ SAMPLE_RATES.get(usize::from(index)).copied().unwrap_or(0)
26+}
27+
28+/// A decoded AudioSpecificConfig.
29+#[derive(Clone, Debug, PartialEq, Eq)]
30+pub struct AudioSpecificConfig {
31+ /// Audio object type; 2 is AAC-LC, the only one this decoder codes.
32+ pub object_type: u8,
33+ pub sample_rate: u32,
34+ pub sf_index: u8,
35+ /// Channels the configuration implies, PCE included.
36+ pub channels: u16,
37+ /// `channelConfiguration`; 0 means the layout came from a PCE.
38+ pub channel_config: u8,
39+ /// True when the config signals SBR, i.e. HE-AAC.
40+ pub sbr_present: bool,
41+ /// True when the config signals Parametric Stereo, i.e. HE-AAC v2.
42+ pub ps_present: bool,
43+ /// The rate SBR would output at, when signalled.
44+ pub extension_sample_rate: Option<u32>,
45+}
46+
47+/// Channels implied by `channelConfiguration` (ISO 14496-3 tbl 1.19).
48+pub fn channels_for_config(config: u8) -> u16 {
49+ match config {
50+ 1..=6 => u16::from(config),
51+ 7 => 8,
52+ _ => 0,
53+ }
54+}
55+
56+fn object_type(r: &mut BitReader<'_>) -> Result<u8> {
57+ let t = r.read_bits(5)? as u8;
58+ if t == 31 {
59+ return Ok(32 + r.read_bits(6)? as u8);
60+ }
61+ Ok(t)
62+}
63+
64+fn sampling_frequency(r: &mut BitReader<'_>) -> Result<(u8, u32)> {
65+ let index = r.read_bits(4)? as u8;
66+ if index == 15 {
67+ return Ok((index, r.read_bits(24)?));
68+ }
69+ Ok((index, sample_rate_for_index(index)))
70+}
71+
72+/// Parses an AudioSpecificConfig, the `esds`/`CodecPrivate` payload.
73+pub fn parse_audio_specific_config(data: &[u8]) -> Result<AudioSpecificConfig> {
74+ let mut r = BitReader::new(data);
75+ let mut object = object_type(&mut r)?;
76+ let (mut sf_index, mut rate) = sampling_frequency(&mut r)?;
77+ let mut channel_config = r.read_bits(4)? as u8;
78+ let mut sbr = false;
79+ let mut ps = false;
80+ let mut ext_rate = None;
81+ if object == AOT_SBR || object == AOT_PS {
82+ sbr = true;
83+ ps = object == AOT_PS;
84+ let (_, er) = sampling_frequency(&mut r)?;
85+ ext_rate = Some(er);
86+ object = object_type(&mut r)?;
87+ if object == 22 {
88+ let _ext_channel_config = r.read_bits(4)?;
89+ }
90+ } else if object == AOT_AAC_LC {
91+ // GASpecificConfig; the fields matter only for the PCE that may follow.
92+ let _frame_length_flag = r.read_bit()?;
93+ if r.read_bit()? {
94+ let _core_coder_delay = r.read_bits(14)?;
95+ }
96+ let _extension_flag = r.read_bit()?;
97+ if channel_config == 0 {
98+ let pce = parse_program_config(&mut r)?;
99+ channel_config = 0;
100+ sf_index = pce.sf_index;
101+ rate = sample_rate_for_index(pce.sf_index);
102+ return Ok(AudioSpecificConfig {
103+ object_type: object,
104+ sample_rate: rate,
105+ sf_index,
106+ channels: pce.channels,
107+ channel_config,
108+ sbr_present: false,
109+ ps_present: false,
110+ extension_sample_rate: None,
111+ });
112+ }
113+ // A backward-compatible SBR signal rides in a sync extension at the end.
114+ if r.bits_remaining() >= 16 && r.read_bits(11)? == 0x2B7 {
115+ let ext = object_type(&mut r)?;
116+ if ext == AOT_SBR && r.read_bit()? {
117+ sbr = true;
118+ let (_, er) = sampling_frequency(&mut r)?;
119+ ext_rate = Some(er);
120+ }
121+ }
122+ }
123+ if rate == 0 {
124+ return Err(Error::corrupt("aac: reserved samplingFrequencyIndex"));
125+ }
126+ Ok(AudioSpecificConfig {
127+ object_type: object,
128+ sample_rate: rate,
129+ sf_index,
130+ channels: channels_for_config(channel_config),
131+ channel_config,
132+ sbr_present: sbr,
133+ ps_present: ps,
134+ extension_sample_rate: ext_rate,
135+ })
136+}
137+
138+/// Serialises the two-byte (plus SBR extension) AudioSpecificConfig.
139+pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec<u8> {
140+ let mut w = BitWriter::new();
141+ w.write_bits(u32::from(cfg.object_type), 5);
142+ w.write_bits(u32::from(cfg.sf_index), 4);
143+ w.write_bits(u32::from(cfg.channel_config), 4);
144+ w.write_bit(false); // frameLengthFlag: 1024 samples
145+ w.write_bit(false); // dependsOnCoreCoder
146+ w.write_bit(false); // extensionFlag
147+ w.align_to_byte();
148+ w.into_bytes()
149+}
150+
151+/// The AudioSpecificConfig an AAC-LC track of this shape needs.
152+pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec<u8> {
153+ let sf_index = sf_index_for_rate(sample_rate).unwrap_or(3);
154+ write_audio_specific_config(&AudioSpecificConfig {
155+ object_type: AOT_AAC_LC,
156+ sample_rate,
157+ sf_index,
158+ channels,
159+ channel_config: config_for_channels(channels),
160+ sbr_present: false,
161+ ps_present: false,
162+ extension_sample_rate: None,
163+ })
164+}
165+
166+/// The `channelConfiguration` that carries this many channels.
167+pub fn config_for_channels(channels: u16) -> u8 {
168+ match channels {
169+ 1..=6 => channels as u8,
170+ 8 => 7,
171+ _ => 0,
172+ }
173+}
174+
175+/// What a program_config_element says about the stream.
176+#[derive(Clone, Debug, Default)]
177+pub struct ProgramConfig {
178+ pub sf_index: u8,
179+ pub channels: u16,
180+}
181+
182+/// Parses a program_config_element far enough to count its channels.
183+pub fn parse_program_config(r: &mut BitReader<'_>) -> Result<ProgramConfig> {
184+ let _tag = r.read_bits(4)?;
185+ let _object_type = r.read_bits(2)?;
186+ let sf_index = r.read_bits(4)? as u8;
187+ let front = r.read_bits(4)? as usize;
188+ let side = r.read_bits(4)? as usize;
189+ let back = r.read_bits(4)? as usize;
190+ let lfe = r.read_bits(2)? as usize;
191+ let assoc = r.read_bits(3)? as usize;
192+ let cc = r.read_bits(4)? as usize;
193+ if r.read_bit()? {
194+ let _mono_mixdown = r.read_bits(4)?;
195+ }
196+ if r.read_bit()? {
197+ let _stereo_mixdown = r.read_bits(4)?;
198+ }
199+ if r.read_bit()? {
200+ let _matrix_mixdown = r.read_bits(3)?;
201+ }
202+ let mut channels = 0u16;
203+ for _ in 0..front + side + back {
204+ channels += if r.read_bit()? { 2 } else { 1 };
205+ let _tag = r.read_bits(4)?;
206+ }
207+ channels += lfe as u16;
208+ for _ in 0..lfe + assoc {
209+ let _tag = r.read_bits(4)?;
210+ }
211+ for _ in 0..cc {
212+ let _is_ind_sw = r.read_bit()?;
213+ let _tag = r.read_bits(4)?;
214+ }
215+ r.align_to_byte();
216+ let comment = r.read_bits(8)? as u64;
217+ r.skip_bits(comment * 8)?;
218+ Ok(ProgramConfig { sf_index, channels })
219+}
220+
221+pub(crate) fn skip_program_config(r: &mut BitReader<'_>) -> Result<()> {
222+ parse_program_config(r).map(|_| ())
223+}
224+
225+/// An ADTS frame header (§1.A.2.2).
226+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227+pub struct AdtsHeader {
228+ pub object_type: u8,
229+ pub sf_index: u8,
230+ pub sample_rate: u32,
231+ pub channels: u16,
232+ pub channel_config: u8,
233+ /// Whole frame length in bytes, header included.
234+ pub frame_length: usize,
235+ /// Header length in bytes: 7, or 9 when the CRC is present.
236+ pub header_len: usize,
237+ pub raw_blocks: u8,
238+}
239+
240+/// True when `data` opens on an ADTS syncword.
241+pub fn is_adts(data: &[u8]) -> bool {
242+ data.len() >= 2 && data[0] == 0xFF && data[1] & 0xF6 == 0xF0
243+}
244+
245+/// Parses one ADTS header.
246+pub fn parse_adts(data: &[u8]) -> Result<AdtsHeader> {
247+ if data.len() < 7 {
248+ return Err(Error::NeedMore);
249+ }
250+ let mut r = BitReader::new(data);
251+ if r.read_bits(12)? != 0xFFF {
252+ return Err(Error::corrupt("aac: no ADTS syncword"));
253+ }
254+ let _id = r.read_bit()?;
255+ let layer = r.read_bits(2)?;
256+ if layer != 0 {
257+ return Err(Error::corrupt("aac: ADTS layer is not zero"));
258+ }
259+ let protection_absent = r.read_bit()?;
260+ let object_type = r.read_bits(2)? as u8 + 1;
261+ let sf_index = r.read_bits(4)? as u8;
262+ let _private = r.read_bit()?;
263+ let channel_config = r.read_bits(3)? as u8;
264+ let _original = r.read_bit()?;
265+ let _home = r.read_bit()?;
266+ let _copyright_id = r.read_bit()?;
267+ let _copyright_start = r.read_bit()?;
268+ let frame_length = r.read_bits(13)? as usize;
269+ let _fullness = r.read_bits(11)?;
270+ let raw_blocks = r.read_bits(2)? as u8 + 1;
271+ let header_len = if protection_absent { 7 } else { 9 };
272+ if frame_length < header_len {
273+ return Err(Error::corrupt("aac: ADTS frame shorter than its header"));
274+ }
275+ let sample_rate = sample_rate_for_index(sf_index);
276+ if sample_rate == 0 {
277+ return Err(Error::corrupt("aac: reserved samplingFrequencyIndex"));
278+ }
279+ Ok(AdtsHeader {
280+ object_type,
281+ sf_index,
282+ sample_rate,
283+ channels: channels_for_config(channel_config),
284+ channel_config,
285+ frame_length,
286+ header_len,
287+ raw_blocks,
288+ })
289+}
290+
291+/// Serialises a 7-byte ADTS header (no CRC).
292+pub fn write_adts_header(header: &AdtsHeader) -> Vec<u8> {
293+ let mut w = BitWriter::with_capacity(7);
294+ w.write_bits(0xFFF, 12);
295+ w.write_bit(false); // MPEG-4
296+ w.write_bits(0, 2); // layer
297+ w.write_bit(true); // protection absent
298+ w.write_bits(u32::from(header.object_type.saturating_sub(1)), 2);
299+ w.write_bits(u32::from(header.sf_index), 4);
300+ w.write_bit(false); // private
301+ w.write_bits(u32::from(header.channel_config), 3);
302+ w.write_bit(false); // original
303+ w.write_bit(false); // home
304+ w.write_bit(false); // copyright id
305+ w.write_bit(false); // copyright start
306+ w.write_bits(header.frame_length as u32, 13);
307+ w.write_bits(0x7FF, 11); // buffer fullness: variable rate
308+ w.write_bits(u32::from(header.raw_blocks.saturating_sub(1)), 2);
309+ w.into_bytes()
310+}
crates/ec-aac/src/decode.rsadded+951 -0
@@ -0,0 +1,951 @@
1+//! `raw_data_block` decoding: ISO/IEC 14496-3 §4.4.2 syntax, §4.6 tools.
2+//!
3+//! Band, group and window indices are the domain's own coordinates and address
4+//! several parallel arrays at once, so the loops here are written over indices
5+//! rather than iterators.
6+#![allow(clippy::needless_range_loop)]
7+
8+use ec_core::{BitReader, Error, Result};
9+use ec_dsp::{Mdct, Window};
10+
11+use crate::huffman::Books;
12+use crate::tables::{CODEBOOKS, SWB_LONG, SWB_SHORT, TNS_MAX_BANDS_LONG, TNS_MAX_BANDS_SHORT};
13+
14+/// Samples one AAC frame carries per channel.
15+pub const FRAME_LEN: usize = 1024;
16+/// Samples one short block carries.
17+pub const SHORT_LEN: usize = 128;
18+/// The `sect_cb` value for a band coded as all zeroes.
19+const ZERO_HCB: u8 = 0;
20+/// The `sect_cb` value for perceptual noise substitution.
21+const NOISE_HCB: u8 = 13;
22+/// Out-of-phase intensity stereo.
23+const INTENSITY_HCB2: u8 = 14;
24+/// In-phase intensity stereo.
25+const INTENSITY_HCB: u8 = 15;
26+/// `sf` is an exponent in quarter-powers of two around this offset (§4.6.2).
27+const SF_OFFSET: i32 = 100;
28+/// The dequantiser works in the standard's own units, where full scale is
29+/// 2^16; the public API speaks the usual +/-1 float range. Checked against a
30+/// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares
31+/// amplitudes and not just shape.
32+const OUTPUT_SCALE: f32 = 1.0 / 65536.0;
33+/// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7).
34+const TNS_MAX_ORDER_LONG: usize = 12;
35+const TNS_MAX_ORDER_SHORT: usize = 7;
36+
37+/// The four window sequences of §4.6.11.
38+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
39+pub enum WindowSequence {
40+ OnlyLong,
41+ LongStart,
42+ EightShort,
43+ LongStop,
44+}
45+
46+impl WindowSequence {
47+ fn from_bits(v: u32) -> WindowSequence {
48+ match v {
49+ 1 => WindowSequence::LongStart,
50+ 2 => WindowSequence::EightShort,
51+ 3 => WindowSequence::LongStop,
52+ _ => WindowSequence::OnlyLong,
53+ }
54+ }
55+
56+ /// True for `EIGHT_SHORT_SEQUENCE`, which changes almost every field width.
57+ pub fn is_short(self) -> bool {
58+ self == WindowSequence::EightShort
59+ }
60+}
61+
62+/// `ics_info` (§4.4.2.1) plus the grouping it implies.
63+#[derive(Clone, Debug)]
64+pub struct IcsInfo {
65+ pub window_sequence: WindowSequence,
66+ /// False for the sine window, true for Kaiser-Bessel-derived.
67+ pub window_shape_kbd: bool,
68+ pub max_sfb: usize,
69+ pub num_windows: usize,
70+ pub num_groups: usize,
71+ /// Windows per group, `num_groups` entries.
72+ pub group_len: [usize; 8],
73+ /// Band offsets in force for this window shape, `num_swb + 1` entries.
74+ pub swb: &'static [u16],
75+ /// Highest band a TNS filter may reach at this rate and window length.
76+ pub tns_max_bands: usize,
77+}
78+
79+impl IcsInfo {
80+ fn num_swb(&self) -> usize {
81+ self.swb.len() - 1
82+ }
83+
84+ /// First window index of each group.
85+ fn group_start(&self, g: usize) -> usize {
86+ self.group_len[..g].iter().sum()
87+ }
88+}
89+
90+fn parse_ics_info(r: &mut BitReader<'_>, sf_index: u8) -> Result<IcsInfo> {
91+ let _reserved = r.read_bit()?;
92+ let window_sequence = WindowSequence::from_bits(r.read_bits(2)?);
93+ let window_shape_kbd = r.read_bit()?;
94+ let idx = usize::from(sf_index).min(11);
95+ let (max_sfb, num_windows, num_groups, group_len, swb, tns_max_bands) =
96+ if window_sequence.is_short() {
97+ let max_sfb = r.read_bits(4)? as usize;
98+ let grouping = r.read_bits(7)?;
99+ let mut group_len = [0usize; 8];
100+ let mut groups = 1;
101+ group_len[0] = 1;
102+ for i in 0..7 {
103+ if (grouping >> (6 - i)) & 1 == 1 {
104+ group_len[groups - 1] += 1;
105+ } else {
106+ group_len[groups] = 1;
107+ groups += 1;
108+ }
109+ }
110+ (
111+ max_sfb,
112+ 8,
113+ groups,
114+ group_len,
115+ SWB_SHORT[idx],
116+ TNS_MAX_BANDS_SHORT[idx],
117+ )
118+ } else {
119+ let max_sfb = r.read_bits(6)? as usize;
120+ if r.read_bit()? {
121+ // AAC-LC has no predictor; LTP/main streams are a different profile.
122+ return Err(Error::unsupported(
123+ "aac",
124+ "predictor_data_present: main or LTP profile, not AAC-LC",
125+ ));
126+ }
127+ let mut group_len = [0usize; 8];
128+ group_len[0] = 1;
129+ (
130+ max_sfb,
131+ 1,
132+ 1,
133+ group_len,
134+ SWB_LONG[idx],
135+ TNS_MAX_BANDS_LONG[idx],
136+ )
137+ };
138+ if max_sfb > swb.len() - 1 {
139+ return Err(Error::corrupt("aac: max_sfb past the band table"));
140+ }
141+ Ok(IcsInfo {
142+ window_sequence,
143+ window_shape_kbd,
144+ max_sfb,
145+ num_windows,
146+ num_groups,
147+ group_len,
148+ swb,
149+ tns_max_bands,
150+ })
151+}
152+
153+/// One TNS filter as transmitted, already converted to LPC coefficients.
154+#[derive(Clone, Debug, Default)]
155+struct TnsFilter {
156+ /// Bands the filter spans, counted down from the top.
157+ length: usize,
158+ order: usize,
159+ /// True when the filter runs from high frequency down.
160+ downward: bool,
161+ lpc: Vec<f32>,
162+}
163+
164+#[derive(Clone, Debug, Default)]
165+struct Tns {
166+ /// Filters per window.
167+ filters: Vec<Vec<TnsFilter>>,
168+}
169+
170+fn parse_tns(r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Tns> {
171+ let short = ics.window_sequence.is_short();
172+ let (n_filt_bits, len_bits, order_bits) = if short { (1, 4, 3) } else { (2, 6, 5) };
173+ let max_order = if short {
174+ TNS_MAX_ORDER_SHORT
175+ } else {
176+ TNS_MAX_ORDER_LONG
177+ };
178+ let mut filters = Vec::with_capacity(ics.num_windows);
179+ for _ in 0..ics.num_windows {
180+ let n_filt = r.read_bits(n_filt_bits)? as usize;
181+ let mut coef_res = 0;
182+ if n_filt > 0 {
183+ coef_res = u32::from(r.read_bit()?);
184+ }
185+ let mut win = Vec::with_capacity(n_filt);
186+ for _ in 0..n_filt {
187+ let length = r.read_bits(len_bits)? as usize;
188+ let order = r.read_bits(order_bits)? as usize;
189+ if order == 0 {
190+ win.push(TnsFilter {
191+ length,
192+ ..TnsFilter::default()
193+ });
194+ continue;
195+ }
196+ // A stream may state a longer filter than the profile allows; the
197+ // extra taps are dropped rather than the frame refused.
198+ let order = order.min(max_order);
199+ let downward = r.read_bit()?;
200+ let compress = u32::from(r.read_bit()?);
201+ let res_bits = coef_res + 3;
202+ let bits = res_bits - compress;
203+ // §4.6.9.3: the transmitted index is a signed fraction of a quarter
204+ // turn, and the two half-step factors keep the mapping symmetric.
205+ let iqfac = ((1 << (res_bits - 1)) as f64 - 0.5) / core::f64::consts::FRAC_PI_2;
206+ let iqfac_m = ((1 << (res_bits - 1)) as f64 + 0.5) / core::f64::consts::FRAC_PI_2;
207+ let mut parcor = Vec::with_capacity(order);
208+ for _ in 0..order {
209+ let raw = r.read_bits(bits)? as i32;
210+ let sign_bit = 1 << (bits - 1);
211+ let value = if raw & sign_bit != 0 {
212+ raw - (1 << bits)
213+ } else {
214+ raw
215+ };
216+ let scaled = if value >= 0 {
217+ f64::from(value) / iqfac
218+ } else {
219+ f64::from(value) / iqfac_m
220+ };
221+ parcor.push(scaled.sin());
222+ }
223+ win.push(TnsFilter {
224+ length,
225+ order,
226+ downward,
227+ lpc: parcor_to_lpc(&parcor),
228+ });
229+ }
230+ filters.push(win);
231+ }
232+ Ok(Tns { filters })
233+}
234+
235+/// Reflection coefficients to direct-form LPC (§4.6.9.3), `a[0] == 1`.
236+fn parcor_to_lpc(parcor: &[f64]) -> Vec<f32> {
237+ let mut a = vec![0.0f64; parcor.len() + 1];
238+ let mut tmp = vec![0.0f64; parcor.len() + 1];
239+ a[0] = 1.0;
240+ for (m, &k) in parcor.iter().enumerate() {
241+ for i in 1..=m {
242+ tmp[i] = a[i] + k * a[m + 1 - i];
243+ }
244+ a[1..=m].copy_from_slice(&tmp[1..=m]);
245+ a[m + 1] = k;
246+ }
247+ a.into_iter().map(|v| v as f32).collect()
248+}
249+
250+/// Applies every TNS filter of one window in place (§4.6.9.2).
251+fn apply_tns(coef: &mut [f32], tns: &Tns, ics: &IcsInfo, window: usize) {
252+ let Some(filters) = tns.filters.get(window) else {
253+ return;
254+ };
255+ let num_swb = ics.num_swb();
256+ let mut bottom = num_swb;
257+ for filter in filters {
258+ let top = bottom;
259+ bottom = top.saturating_sub(filter.length);
260+ if filter.order == 0 {
261+ continue;
262+ }
263+ let cap = ics.max_sfb.min(ics.tns_max_bands);
264+ let start = usize::from(ics.swb[bottom.min(cap)]);
265+ let end = usize::from(ics.swb[top.min(cap)]);
266+ if end <= start {
267+ continue;
268+ }
269+ let order = filter.order;
270+ let mut state = vec![0.0f32; order + 1];
271+ let walk = |i: usize, state: &mut Vec<f32>, coef: &mut [f32]| {
272+ let mut y = coef[i];
273+ for j in 1..=order {
274+ y -= filter.lpc[j] * state[j - 1];
275+ }
276+ for j in (1..=order).rev() {
277+ state[j] = state[j - 1];
278+ }
279+ state[0] = y;
280+ coef[i] = y;
281+ };
282+ if filter.downward {
283+ for i in (start..end).rev() {
284+ walk(i, &mut state, coef);
285+ }
286+ } else {
287+ for i in start..end {
288+ walk(i, &mut state, coef);
289+ }
290+ }
291+ }
292+}
293+
294+/// Per-channel data of one `individual_channel_stream`.
295+struct Ics {
296+ ics: IcsInfo,
297+ /// `sect_cb` by group and band.
298+ cb: Vec<Vec<u8>>,
299+ /// Scalefactor, intensity position or noise energy by group and band.
300+ sf: Vec<Vec<i32>>,
301+ coef: Vec<f32>,
302+ tns: Tns,
303+}
304+
305+/// The decoder's per-channel memory: the filterbank overlap and the window
306+/// shape the next frame's rising edge has to match.
307+#[derive(Clone, Debug)]
308+pub struct ChannelState {
309+ overlap: Vec<f32>,
310+ prev_shape_kbd: bool,
311+ prev_short: bool,
312+}
313+
314+impl Default for ChannelState {
315+ fn default() -> ChannelState {
316+ ChannelState {
317+ overlap: vec![0.0; FRAME_LEN],
318+ prev_shape_kbd: false,
319+ prev_short: false,
320+ }
321+ }
322+}
323+
324+/// The four windows and two transforms the filterbank needs, built once.
325+pub struct FilterBank {
326+ long: Mdct<f32>,
327+ short: Mdct<f32>,
328+ sine_long: Vec<f32>,
329+ kbd_long: Vec<f32>,
330+ sine_short: Vec<f32>,
331+ kbd_short: Vec<f32>,
332+ scratch_long: Vec<f32>,
333+ scratch_short: Vec<f32>,
334+}
335+
336+impl FilterBank {
337+ pub fn new() -> FilterBank {
338+ FilterBank {
339+ long: Mdct::new(2 * FRAME_LEN),
340+ short: Mdct::new(2 * SHORT_LEN),
341+ sine_long: Window::<f32>::sine(2 * FRAME_LEN).as_slice().to_vec(),
342+ kbd_long: Window::<f32>::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(),
343+ sine_short: Window::<f32>::sine(2 * SHORT_LEN).as_slice().to_vec(),
344+ kbd_short: Window::<f32>::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(),
345+ scratch_long: vec![0.0; 2 * FRAME_LEN],
346+ scratch_short: vec![0.0; 2 * SHORT_LEN],
347+ }
348+ }
349+
350+ fn long_win(&self, kbd: bool) -> &[f32] {
351+ if kbd { &self.kbd_long } else { &self.sine_long }
352+ }
353+
354+ fn short_win(&self, kbd: bool) -> &[f32] {
355+ if kbd {
356+ &self.kbd_short
357+ } else {
358+ &self.sine_short
359+ }
360+ }
361+
362+ /// Inverse filterbank and overlap-add for one channel (§4.6.11).
363+ fn synthesize(
364+ &mut self,
365+ spec: &[f32],
366+ ics: &IcsInfo,
367+ state: &mut ChannelState,
368+ out: &mut [f32],
369+ ) {
370+ let mut frame = vec![0.0f32; 2 * FRAME_LEN];
371+ match ics.window_sequence {
372+ WindowSequence::EightShort => {
373+ for w in 0..8 {
374+ let src = &spec[w * SHORT_LEN..(w + 1) * SHORT_LEN];
375+ self.short.inverse(src, &mut self.scratch_short);
376+ let rise = self.short_win(if w == 0 {
377+ state.prev_shape_kbd
378+ } else {
379+ ics.window_shape_kbd
380+ });
381+ let fall = self.short_win(ics.window_shape_kbd);
382+ let base = 448 + w * SHORT_LEN;
383+ for i in 0..SHORT_LEN {
384+ frame[base + i] += self.scratch_short[i] * rise[i];
385+ frame[base + SHORT_LEN + i] +=
386+ self.scratch_short[SHORT_LEN + i] * fall[SHORT_LEN + i];
387+ }
388+ }
389+ }
390+ seq => {
391+ self.long.inverse(spec, &mut self.scratch_long);
392+ let prev_long = self.long_win(state.prev_shape_kbd);
393+ let prev_short = self.short_win(state.prev_shape_kbd);
394+ let cur_long = self.long_win(ics.window_shape_kbd);
395+ let cur_short = self.short_win(ics.window_shape_kbd);
396+ for i in 0..FRAME_LEN {
397+ let rise = match seq {
398+ // A stop window opens flat: nothing to overlap with the
399+ // short block that preceded it until sample 448.
400+ WindowSequence::LongStop => match i {
401+ 0..448 => 0.0,
402+ 448..576 => prev_short[i - 448],
403+ _ => 1.0,
404+ },
405+ _ => prev_long[i],
406+ };
407+ frame[i] = self.scratch_long[i] * rise;
408+ }
409+ for i in 0..FRAME_LEN {
410+ let fall = match seq {
411+ WindowSequence::LongStart => match i {
412+ 0..448 => 1.0,
413+ 448..576 => cur_short[SHORT_LEN + i - 448],
414+ _ => 0.0,
415+ },
416+ _ => cur_long[FRAME_LEN + i],
417+ };
418+ frame[FRAME_LEN + i] = self.scratch_long[FRAME_LEN + i] * fall;
419+ }
420+ }
421+ }
422+ for i in 0..FRAME_LEN {
423+ out[i] = (state.overlap[i] + frame[i]) * OUTPUT_SCALE;
424+ }
425+ state.overlap.copy_from_slice(&frame[FRAME_LEN..]);
426+ state.prev_shape_kbd = ics.window_shape_kbd;
427+ state.prev_short = ics.window_sequence.is_short();
428+ }
429+}
430+
431+impl Default for FilterBank {
432+ fn default() -> FilterBank {
433+ FilterBank::new()
434+ }
435+}
436+
437+/// Deterministic noise source for PNS; the standard leaves the sequence free,
438+/// only the band energy is normative.
439+#[derive(Clone, Debug)]
440+pub struct Noise(u32);
441+
442+impl Noise {
443+ fn next(&mut self) -> f32 {
444+ self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
445+ (self.0 >> 8) as f32 / (1 << 23) as f32 - 1.0
446+ }
447+}
448+
449+/// The syntactic and tool state one `raw_data_block` needs.
450+pub struct BlockDecoder {
451+ pub books: Books,
452+ pub bank: FilterBank,
453+ pub states: Vec<ChannelState>,
454+ noise: Noise,
455+ sf_index: u8,
456+}
457+
458+impl BlockDecoder {
459+ pub fn new(sf_index: u8) -> BlockDecoder {
460+ BlockDecoder {
461+ books: Books::new(),
462+ bank: FilterBank::new(),
463+ states: Vec::new(),
464+ noise: Noise(0x1234_5678),
465+ sf_index,
466+ }
467+ }
468+
469+ pub fn set_sf_index(&mut self, sf_index: u8) {
470+ self.sf_index = sf_index;
471+ }
472+
473+ fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> {
474+ let bits = if ics.window_sequence.is_short() { 3 } else { 5 };
475+ let esc = (1u32 << bits) - 1;
476+ let mut out = Vec::with_capacity(ics.num_groups);
477+ for _ in 0..ics.num_groups {
478+ let mut row = vec![ZERO_HCB; ics.max_sfb];
479+ let mut k = 0usize;
480+ while k < ics.max_sfb {
481+ let cb = r.read_bits(4)? as u8;
482+ let mut len = 0usize;
483+ loop {
484+ let incr = r.read_bits(bits)?;
485+ len += incr as usize;
486+ if incr != esc {
487+ break;
488+ }
489+ }
490+ if len == 0 || k + len > ics.max_sfb {
491+ return Err(Error::corrupt("aac: section runs past max_sfb"));
492+ }
493+ row[k..k + len].fill(cb);
494+ k += len;
495+ }
496+ out.push(row);
497+ }
498+ Ok(out)
499+ }
500+
501+ fn scale_factor_data(
502+ &self,
503+ r: &mut BitReader<'_>,
504+ ics: &IcsInfo,
505+ cb: &[Vec<u8>],
506+ global_gain: u8,
507+ ) -> Result<Vec<Vec<i32>>> {
508+ let mut scale = i32::from(global_gain);
509+ let mut intensity = 0i32;
510+ let mut noise = i32::from(global_gain) - 90;
511+ let mut noise_pcm = true;
512+ let mut out = Vec::with_capacity(ics.num_groups);
513+ for g in 0..ics.num_groups {
514+ let mut row = vec![0i32; ics.max_sfb];
515+ for sfb in 0..ics.max_sfb {
516+ row[sfb] = match cb[g][sfb] {
517+ ZERO_HCB => 0,
518+ INTENSITY_HCB | INTENSITY_HCB2 => {
519+ intensity += self.books.scalefactor.decode(r)? as i32 - 60;
520+ intensity
521+ }
522+ NOISE_HCB => {
523+ if noise_pcm {
524+ noise_pcm = false;
525+ noise += r.read_bits(9)? as i32 - 256;
526+ } else {
527+ noise += self.books.scalefactor.decode(r)? as i32 - 60;
528+ }
529+ noise
530+ }
531+ _ => {
532+ scale += self.books.scalefactor.decode(r)? as i32 - 60;
533+ if !(0..=255).contains(&scale) {
534+ return Err(Error::corrupt("aac: scalefactor out of range"));
535+ }
536+ scale
537+ }
538+ };
539+ }
540+ out.push(row);
541+ }
542+ Ok(out)
543+ }
544+
545+ /// `spectral_data` (§4.4.2.7) into quantised integers, window-major.
546+ fn spectral_data(
547+ &self,
548+ r: &mut BitReader<'_>,
549+ ics: &IcsInfo,
550+ cb: &[Vec<u8>],
551+ quant: &mut [i32],
552+ ) -> Result<()> {
553+ for g in 0..ics.num_groups {
554+ let start = ics.group_start(g);
555+ for sfb in 0..ics.max_sfb {
556+ let book = cb[g][sfb];
557+ if !(1..=11).contains(&book) {
558+ continue;
559+ }
560+ let spec = &CODEBOOKS[usize::from(book) - 1];
561+ let tree = &self.books.spectral[usize::from(book) - 1];
562+ let lo = usize::from(ics.swb[sfb]);
563+ let hi = usize::from(ics.swb[sfb + 1]);
564+ for w in 0..ics.group_len[g] {
565+ let base = if ics.window_sequence.is_short() {
566+ (start + w) * SHORT_LEN
567+ } else {
568+ 0
569+ };
570+ let mut k = lo;
571+ while k < hi {
572+ let mut values = [0i32; 4];
573+ let symbol = tree.decode(r)?;
574+ decode_tuple(spec, symbol, &mut values);
575+ let dim = usize::from(spec.dim);
576+ if spec.unsigned {
577+ for v in values.iter_mut().take(dim) {
578+ if *v != 0 && r.read_bit()? {
579+ *v = -*v;
580+ }
581+ }
582+ }
583+ if spec.esc {
584+ for v in values.iter_mut().take(dim) {
585+ if v.unsigned_abs() == 16 {
586+ let mut n = 0u32;
587+ while r.read_bit()? {
588+ n += 1;
589+ if n > 20 {
590+ return Err(Error::corrupt("aac: escape too long"));
591+ }
592+ }
593+ let magnitude = (1i32 << (n + 4)) | r.read_bits(n + 4)? as i32;
594+ *v = if *v < 0 { -magnitude } else { magnitude };
595+ }
596+ }
597+ }
598+ for (i, &v) in values.iter().take(dim).enumerate() {
599+ if k + i < hi {
600+ quant[base + k + i] = v;
601+ }
602+ }
603+ k += dim;
604+ }
605+ }
606+ }
607+ }
608+ Ok(())
609+ }
610+
611+ /// One `individual_channel_stream` (§4.4.2.4).
612+ fn channel_stream(&mut self, r: &mut BitReader<'_>, shared: Option<&IcsInfo>) -> Result<Ics> {
613+ let global_gain = r.read_bits(8)? as u8;
614+ let ics = match shared {
615+ Some(info) => info.clone(),
616+ None => parse_ics_info(r, self.sf_index)?,
617+ };
618+ let cb = self.section_data(r, &ics)?;
619+ let sf = self.scale_factor_data(r, &ics, &cb, global_gain)?;
620+ let mut pulse = None;
621+ if r.read_bit()? {
622+ if ics.window_sequence.is_short() {
623+ return Err(Error::corrupt("aac: pulse data on a short window"));
624+ }
625+ pulse = Some(parse_pulse(r)?);
626+ }
627+ let tns = if r.read_bit()? {
628+ parse_tns(r, &ics)?
629+ } else {
630+ Tns::default()
631+ };
632+ if r.read_bit()? {
633+ return Err(Error::unsupported("aac", "gain control data: SSR profile"));
634+ }
635+ let mut quant = vec![0i32; FRAME_LEN];
636+ self.spectral_data(r, &ics, &cb, &mut quant)?;
637+ if let Some(p) = pulse {
638+ apply_pulse(&mut quant, &p, &ics);
639+ }
640+ Ok(Ics {
641+ coef: dequantize(&quant, &ics, &cb, &sf),
642+ ics,
643+ cb,
644+ sf,
645+ tns,
646+ })
647+ }
648+
649+ /// Runs the stereo tools, TNS and the filterbank over one element's
650+ /// channels, appending each channel's PCM to `out`.
651+ fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec<Vec<f32>>) {
652+ if let ([left, right], Some(mask)) = (&mut *chans, ms) {
653+ apply_ms(left, right, mask);
654+ }
655+ if let [left, right] = &mut *chans {
656+ apply_intensity(left, right, ms);
657+ }
658+ for ch in chans.iter_mut() {
659+ fill_noise(ch, &mut self.noise);
660+ let windows = if ch.ics.window_sequence.is_short() {
661+ 8
662+ } else {
663+ 1
664+ };
665+ for w in 0..windows {
666+ let len = if windows == 8 { SHORT_LEN } else { FRAME_LEN };
667+ apply_tns(&mut ch.coef[w * len..(w + 1) * len], &ch.tns, &ch.ics, w);
668+ }
669+ let mut pcm = vec![0.0f32; FRAME_LEN];
670+ let index = out.len();
671+ while self.states.len() <= index {
672+ self.states.push(ChannelState::default());
673+ }
674+ self.bank
675+ .synthesize(&ch.coef, &ch.ics, &mut self.states[index], &mut pcm);
676+ out.push(pcm);
677+ }
678+ }
679+
680+ /// Decodes one `raw_data_block`, returning one PCM plane per channel in
681+ /// bitstream element order.
682+ pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> {
683+ let mut out: Vec<Vec<f32>> = Vec::new();
684+ loop {
685+ if r.bits_remaining() < 3 {
686+ break;
687+ }
688+ let id = r.read_bits(3)?;
689+ match id {
690+ // SCE and LFE are one channel each; CCE (2) is a coupling
691+ // element this profile never emits and cannot be skipped
692+ // blind, so it is refused rather than silently mis-parsed.
693+ 0 | 3 => {
694+ let _tag = r.read_bits(4)?;
695+ let mut ch = [self.channel_stream(r, None)?];
696+ self.finish(&mut ch, None, &mut out);
697+ }
698+ 1 => {
699+ let _tag = r.read_bits(4)?;
700+ let common = r.read_bit()?;
701+ let (shared, mask) = if common {
702+ let info = parse_ics_info(r, self.sf_index)?;
703+ let present = r.read_bits(2)?;
704+ let mask = match present {
705+ 0 => MsMask::None,
706+ 1 => {
707+ let mut bits = vec![vec![false; info.max_sfb]; info.num_groups];
708+ for row in bits.iter_mut() {
709+ for b in row.iter_mut() {
710+ *b = r.read_bit()?;
711+ }
712+ }
713+ MsMask::Some(bits)
714+ }
715+ 2 => MsMask::All,
716+ _ => return Err(Error::corrupt("aac: reserved ms_mask_present")),
717+ };
718+ (Some(info), mask)
719+ } else {
720+ (None, MsMask::None)
721+ };
722+ let mut pair = [
723+ self.channel_stream(r, shared.as_ref())?,
724+ self.channel_stream(r, shared.as_ref())?,
725+ ];
726+ self.finish(&mut pair, Some(&mask), &mut out);
727+ }
728+ 2 => return Err(Error::unsupported("aac", "coupling channel element")),
729+ 4 => {
730+ let _tag = r.read_bits(4)?;
731+ let align = r.read_bit()?;
732+ let mut count = r.read_bits(8)? as u64;
733+ if count == 255 {
734+ count += r.read_bits(8)? as u64;
735+ }
736+ if align {
737+ r.align_to_byte();
738+ }
739+ r.skip_bits(count * 8)?;
740+ }
741+ 5 => {
742+ crate::config::skip_program_config(r)?;
743+ }
744+ 6 => {
745+ let mut count = r.read_bits(4)? as u64;
746+ if count == 15 {
747+ count += r.read_bits(8)? as u64 - 1;
748+ }
749+ r.skip_bits(count * 8)?;
750+ }
751+ _ => break,
752+ }
753+ }
754+ r.align_to_byte();
755+ Ok(out)
756+ }
757+}
758+
759+#[derive(Debug)]
760+enum MsMask {
761+ None,
762+ All,
763+ Some(Vec<Vec<bool>>),
764+}
765+
766+impl MsMask {
767+ fn used(&self, g: usize, sfb: usize) -> bool {
768+ match self {
769+ MsMask::None => false,
770+ MsMask::All => true,
771+ MsMask::Some(bits) => bits[g][sfb],
772+ }
773+ }
774+}
775+
776+/// The symbol index back into its tuple; the index is the tuple read as digits
777+/// in base `lav + 1` (unsigned) or `2 * lav + 1` (signed), first coefficient
778+/// most significant.
779+fn decode_tuple(cb: &crate::tables::Codebook, symbol: usize, out: &mut [i32; 4]) {
780+ let span = if cb.unsigned {
781+ usize::from(cb.lav) + 1
782+ } else {
783+ 2 * usize::from(cb.lav) + 1
784+ };
785+ let off = if cb.unsigned { 0 } else { i32::from(cb.lav) };
786+ let dim = usize::from(cb.dim);
787+ let mut rest = symbol;
788+ for i in (0..dim).rev() {
789+ out[i] = (rest % span) as i32 - off;
790+ rest /= span;
791+ }
792+}
793+
794+#[derive(Debug)]
795+struct Pulse {
796+ start_sfb: usize,
797+ offsets: Vec<usize>,
798+ amps: Vec<i32>,
799+}
800+
801+fn parse_pulse(r: &mut BitReader<'_>) -> Result<Pulse> {
802+ let count = r.read_bits(2)? as usize + 1;
803+ let start_sfb = r.read_bits(6)? as usize;
804+ let mut offsets = Vec::with_capacity(count);
805+ let mut amps = Vec::with_capacity(count);
806+ for _ in 0..count {
807+ offsets.push(r.read_bits(5)? as usize);
808+ amps.push(r.read_bits(4)? as i32);
809+ }
810+ Ok(Pulse {
811+ start_sfb,
812+ offsets,
813+ amps,
814+ })
815+}
816+
817+fn apply_pulse(quant: &mut [i32], pulse: &Pulse, ics: &IcsInfo) {
818+ if pulse.start_sfb >= ics.swb.len() {
819+ return;
820+ }
821+ let mut k = usize::from(ics.swb[pulse.start_sfb]);
822+ for (&off, &amp) in pulse.offsets.iter().zip(&pulse.amps) {
823+ k += off;
824+ if k >= quant.len() {
825+ return;
826+ }
827+ // The pulse grows the magnitude, keeping whatever sign the coefficient
828+ // already had (§4.6.3).
829+ quant[k] += if quant[k] < 0 { -amp } else { amp };
830+ }
831+}
832+
833+/// `x^(4/3) * 2^((sf - 100) / 4)` per band (§4.6.2), window-major.
834+fn dequantize(quant: &[i32], ics: &IcsInfo, cb: &[Vec<u8>], sf: &[Vec<i32>]) -> Vec<f32> {
835+ let mut coef = vec![0.0f32; FRAME_LEN];
836+ let short = ics.window_sequence.is_short();
837+ for g in 0..ics.num_groups {
838+ let start = ics.group_start(g);
839+ for sfb in 0..ics.max_sfb {
840+ let book = cb[g][sfb];
841+ if !(1..=11).contains(&book) {
842+ continue;
843+ }
844+ let gain = 2f32.powf((sf[g][sfb] - SF_OFFSET) as f32 * 0.25);
845+ let lo = usize::from(ics.swb[sfb]);
846+ let hi = usize::from(ics.swb[sfb + 1]);
847+ for w in 0..ics.group_len[g] {
848+ let base = if short { (start + w) * SHORT_LEN } else { 0 };
849+ for k in lo..hi {
850+ let q = quant[base + k];
851+ if q != 0 {
852+ let mag = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain;
853+ coef[base + k] = if q < 0 { -mag } else { mag };
854+ }
855+ }
856+ }
857+ }
858+ }
859+ coef
860+}
861+
862+/// Mid/side to left/right, for every band the mask marks and no other (§4.6.8.1).
863+fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) {
864+ let ics = &left.ics;
865+ let short = ics.window_sequence.is_short();
866+ for g in 0..ics.num_groups {
867+ let start = ics.group_start(g);
868+ for sfb in 0..ics.max_sfb {
869+ if !mask.used(g, sfb) || is_intensity(right.cb[g][sfb]) {
870+ continue;
871+ }
872+ let lo = usize::from(ics.swb[sfb]);
873+ let hi = usize::from(ics.swb[sfb + 1]);
874+ for w in 0..ics.group_len[g] {
875+ let base = if short { (start + w) * SHORT_LEN } else { 0 };
876+ for k in base + lo..base + hi {
877+ let (m, s) = (left.coef[k], right.coef[k]);
878+ left.coef[k] = m + s;
879+ right.coef[k] = m - s;
880+ }
881+ }
882+ }
883+ }
884+}
885+
886+fn is_intensity(cb: u8) -> bool {
887+ cb == INTENSITY_HCB || cb == INTENSITY_HCB2
888+}
889+
890+/// Intensity stereo: the right channel's marked bands are the left channel's,
891+/// scaled by `0.5^(is_position / 4)` and signed by the codebook (§4.6.8.2).
892+fn apply_intensity(left: &mut Ics, right: &mut Ics, ms: Option<&MsMask>) {
893+ let ics = right.ics.clone();
894+ let short = ics.window_sequence.is_short();
895+ for g in 0..ics.num_groups {
896+ let start = ics.group_start(g);
897+ for sfb in 0..ics.max_sfb {
898+ let cb = right.cb[g][sfb];
899+ if !is_intensity(cb) {
900+ continue;
901+ }
902+ let mut sign = if cb == INTENSITY_HCB { 1.0 } else { -1.0 };
903+ if ms.is_some_and(|m| m.used(g, sfb)) {
904+ sign = -sign;
905+ }
906+ let scale = sign * 0.5f32.powf(0.25 * right.sf[g][sfb] as f32);
907+ let lo = usize::from(ics.swb[sfb]);
908+ let hi = usize::from(ics.swb[sfb + 1]);
909+ for w in 0..ics.group_len[g] {
910+ let base = if short { (start + w) * SHORT_LEN } else { 0 };
911+ for k in base + lo..base + hi {
912+ right.coef[k] = left.coef[k] * scale;
913+ }
914+ }
915+ }
916+ }
917+}
918+
919+/// Perceptual noise substitution: the band is filled with noise carrying the
920+/// transmitted energy (§4.6.13). The sequence is free, the energy is not.
921+fn fill_noise(ch: &mut Ics, rng: &mut Noise) {
922+ let ics = ch.ics.clone();
923+ let short = ics.window_sequence.is_short();
924+ for g in 0..ics.num_groups {
925+ let start = ics.group_start(g);
926+ for sfb in 0..ics.max_sfb {
927+ if ch.cb[g][sfb] != NOISE_HCB {
928+ continue;
929+ }
930+ let lo = usize::from(ics.swb[sfb]);
931+ let hi = usize::from(ics.swb[sfb + 1]);
932+ for w in 0..ics.group_len[g] {
933+ let base = if short { (start + w) * SHORT_LEN } else { 0 };
934+ let mut energy = 0.0f32;
935+ for k in base + lo..base + hi {
936+ let v = rng.next();
937+ ch.coef[k] = v;
938+ energy += v * v;
939+ }
940+ if energy <= 0.0 {
941+ continue;
942+ }
943+ let target = 2f32.powf(0.25 * ch.sf[g][sfb] as f32);
944+ let scale = target / energy.sqrt();
945+ for k in base + lo..base + hi {
946+ ch.coef[k] *= scale;
947+ }
948+ }
949+ }
950+ }
951+}
crates/ec-aac/src/encode.rsadded+1074 -0
@@ -0,0 +1,1074 @@
1+//! AAC-LC encoding: psychoacoustics, window decision, quantisation and the
2+//! `raw_data_block` writer.
3+//!
4+//! The psychoacoustic model is the classic three-stage one, and this is exactly
5+//! what it does: a 2048-point FFT of the windowed input gives per-band energy;
6+//! energy is spread across bands with a two-slope spreading function at
7+//! scalefactor-band resolution; tonality is estimated by each band's spectral
8+//! flatness (**not** by phase unpredictability, which needs two frames of
9+//! history for a fraction of a dB); the signal-to-mask ratio runs from 6 dB on
10+//! noise-like bands to 24 dB on tonal ones. Rate control is the two-loop
11+//! search of the informative part of ISO/IEC 14496-3: an inner distortion loop
12+//! choosing each band's scalefactor against its mask, and an outer rate loop
13+//! over a common offset, against a bit reservoir.
14+//!
15+//! The window decision is shared by every channel of a frame, which is what
16+//! lets a channel pair use `common_window` and therefore mid/side coding.
17+//!
18+//! Band, group and window indices are the domain's own coordinates and address
19+//! several parallel arrays at once, so the loops here are written over indices
20+//! rather than iterators.
21+#![allow(clippy::needless_range_loop)]
22+
23+use ec_core::{BitWriter, Error, Result};
24+use ec_dsp::{Complex, Mdct, RealFft, Window};
25+
26+use crate::config::{AdtsHeader, config_for_channels, sf_index_for_rate};
27+use crate::decode::{FRAME_LEN, SHORT_LEN, WindowSequence};
28+use crate::tables::{CODEBOOKS, Codebook, SCALEFACTOR_CODES, SWB_LONG, SWB_SHORT};
29+
30+const SF_OFFSET: i32 = 100;
31+/// The decoder divides by this; the encoder multiplies by it, so a round trip
32+/// is unity gain.
33+const INPUT_SCALE: f32 = 65536.0;
34+/// Quantiser rounding bias of the informative encoder (§4.6.2).
35+const ROUND_BIAS: f32 = 0.4054;
36+/// Ceiling on what the reservoir may lend one frame, per channel.
37+const RESERVOIR_MAX: i32 = 6144;
38+/// Largest magnitude the escape codebook can carry.
39+const MAX_QUANT: i32 = 8191;
40+/// Masking floor relative to the loudest band of the frame, standing in for the
41+/// absolute threshold of hearing (see [`AacEncoder::psychoacoustics`]).
42+const ATH_FLOOR: f32 = 1e-7;
43+
44+/// Which window shape the encoder asks for.
45+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46+pub enum WindowShape {
47+ /// Sine window everywhere.
48+ #[default]
49+ Sine,
50+ /// Kaiser-Bessel-derived everywhere: better stop-band rejection, which
51+ /// suits tonal material.
52+ Kbd,
53+}
54+
55+/// Encoder options.
56+#[derive(Debug, Clone, Copy)]
57+pub struct AacEncoderConfig {
58+ /// Target bitrate in bits per second, over all channels.
59+ pub bitrate_bps: u32,
60+ /// Window shape policy.
61+ pub window_shape: WindowShape,
62+ /// Emit ADTS framing around each packet instead of a bare `raw_data_block`.
63+ pub adts: bool,
64+ /// Allow mid/side coding on channel pairs.
65+ pub mid_side: bool,
66+ /// Allow the long/short window switch on transients.
67+ pub window_switching: bool,
68+}
69+
70+impl Default for AacEncoderConfig {
71+ fn default() -> AacEncoderConfig {
72+ AacEncoderConfig {
73+ bitrate_bps: 128_000,
74+ window_shape: WindowShape::Sine,
75+ adts: false,
76+ mid_side: true,
77+ window_switching: true,
78+ }
79+ }
80+}
81+
82+/// One encoded access unit.
83+#[derive(Debug, Clone)]
84+pub struct EncodedPacket {
85+ pub data: Vec<u8>,
86+ /// Presentation time in samples (frame index * 1024).
87+ pub pts: i64,
88+ /// Duration in samples; always one AAC frame.
89+ pub duration: u32,
90+}
91+
92+/// One channel's transform and masking thresholds for a frame.
93+#[derive(Clone)]
94+struct ChannelFrame {
95+ /// MDCT coefficients, window-major for short sequences.
96+ coef: Vec<f32>,
97+ /// Masking threshold per band.
98+ threshold: Vec<f32>,
99+}
100+
101+/// An AAC-LC encoder.
102+pub struct AacEncoder {
103+ config: AacEncoderConfig,
104+ sample_rate: u32,
105+ sf_index: u8,
106+ channels: usize,
107+ /// Input not yet turned into frames, per channel.
108+ pcm: Vec<Vec<f32>>,
109+ /// The previous frame's samples, the MDCT block's left half.
110+ prev: Vec<Vec<f32>>,
111+ seq: WindowSequence,
112+ energy: f32,
113+ mdct_long: Mdct<f32>,
114+ mdct_short: Mdct<f32>,
115+ fft: RealFft<f32>,
116+ sine_long: Vec<f32>,
117+ kbd_long: Vec<f32>,
118+ sine_short: Vec<f32>,
119+ kbd_short: Vec<f32>,
120+ queue: std::collections::VecDeque<EncodedPacket>,
121+ frames_out: i64,
122+ reservoir: i32,
123+ flushed: bool,
124+ initialised: bool,
125+}
126+
127+impl AacEncoder {
128+ pub fn new(config: AacEncoderConfig) -> AacEncoder {
129+ AacEncoder {
130+ config,
131+ sample_rate: 0,
132+ sf_index: 3,
133+ channels: 0,
134+ pcm: Vec::new(),
135+ prev: Vec::new(),
136+ seq: WindowSequence::OnlyLong,
137+ energy: 0.0,
138+ mdct_long: Mdct::new(2 * FRAME_LEN),
139+ mdct_short: Mdct::new(2 * SHORT_LEN),
140+ fft: RealFft::new(2 * FRAME_LEN),
141+ sine_long: Window::<f32>::sine(2 * FRAME_LEN).as_slice().to_vec(),
142+ kbd_long: Window::<f32>::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(),
143+ sine_short: Window::<f32>::sine(2 * SHORT_LEN).as_slice().to_vec(),
144+ kbd_short: Window::<f32>::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(),
145+ queue: std::collections::VecDeque::new(),
146+ frames_out: 0,
147+ reservoir: 0,
148+ flushed: false,
149+ initialised: false,
150+ }
151+ }
152+
153+ /// The stream's sample rate; 0 until the first PCM arrives.
154+ pub fn sample_rate(&self) -> u32 {
155+ self.sample_rate
156+ }
157+
158+ /// The stream's channel count; 0 until the first PCM arrives.
159+ pub fn channels(&self) -> u16 {
160+ self.channels as u16
161+ }
162+
163+ /// The AudioSpecificConfig a container needs for this stream.
164+ pub fn audio_specific_config(&self) -> Vec<u8> {
165+ crate::config::audio_specific_config_bytes(self.sample_rate, self.channels as u16)
166+ }
167+
168+ fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> {
169+ if self.initialised {
170+ if self.channels != usize::from(channels) || self.sample_rate != sample_rate {
171+ return Err(Error::corrupt("aac: stream parameters changed mid-encode"));
172+ }
173+ return Ok(());
174+ }
175+ let sf_index = sf_index_for_rate(sample_rate).ok_or_else(|| {
176+ Error::unsupported("aac", format!("{sample_rate} Hz is not an AAC sample rate"))
177+ })?;
178+ if channels == 0 || channels == 7 || channels > 8 {
179+ return Err(Error::unsupported(
180+ "aac",
181+ format!("{channels} channels has no channelConfiguration"),
182+ ));
183+ }
184+ self.sf_index = sf_index;
185+ self.sample_rate = sample_rate;
186+ self.channels = usize::from(channels);
187+ self.pcm = vec![Vec::new(); self.channels];
188+ self.prev = vec![vec![0.0; FRAME_LEN]; self.channels];
189+ self.initialised = true;
190+ Ok(())
191+ }
192+
193+ /// Appends interleaved PCM.
194+ pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
195+ self.init(channels, sample_rate)?;
196+ let n = usize::from(channels);
197+ for (i, sample) in interleaved.iter().enumerate() {
198+ self.pcm[i % n].push(*sample);
199+ }
200+ self.drain_frames();
201+ Ok(())
202+ }
203+
204+ /// Appends planar PCM, one slice per channel.
205+ pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
206+ self.init(planes.len() as u16, sample_rate)?;
207+ for (buf, plane) in self.pcm.iter_mut().zip(planes) {
208+ buf.extend_from_slice(plane);
209+ }
210+ self.drain_frames();
211+ Ok(())
212+ }
213+
214+ /// Marks the end of input; the tail is padded to a whole frame.
215+ pub fn finish(&mut self) {
216+ if !self.initialised || self.flushed {
217+ self.flushed = true;
218+ return;
219+ }
220+ self.flushed = true;
221+ let left = self.pcm.iter().map(|c| c.len()).max().unwrap_or(0);
222+ if left > 0 {
223+ // One frame of lookahead is held back for the window decision, and
224+ // the filterbank needs another frame of zeroes to flush its tail.
225+ let pad = left.div_ceil(FRAME_LEN) * FRAME_LEN + 2 * FRAME_LEN;
226+ for c in self.pcm.iter_mut() {
227+ c.resize(pad, 0.0);
228+ }
229+ }
230+ self.drain_frames();
231+ }
232+
233+ /// Takes the next encoded packet, or [`Error::Eof`] once drained.
234+ pub fn next_packet(&mut self) -> Result<EncodedPacket> {
235+ self.queue.pop_front().ok_or(Error::Eof)
236+ }
237+
238+ fn drain_frames(&mut self) {
239+ while self.pcm.iter().all(|c| c.len() >= 2 * FRAME_LEN) {
240+ self.encode_frame();
241+ }
242+ }
243+
244+ fn long_window(&self) -> &[f32] {
245+ match self.config.window_shape {
246+ WindowShape::Sine => &self.sine_long,
247+ WindowShape::Kbd => &self.kbd_long,
248+ }
249+ }
250+
251+ fn short_window(&self) -> &[f32] {
252+ match self.config.window_shape {
253+ WindowShape::Sine => &self.sine_short,
254+ WindowShape::Kbd => &self.kbd_short,
255+ }
256+ }
257+
258+ fn swb(&self, seq: WindowSequence) -> &'static [u16] {
259+ let idx = usize::from(self.sf_index).min(11);
260+ if seq == WindowSequence::EightShort {
261+ SWB_SHORT[idx]
262+ } else {
263+ SWB_LONG[idx]
264+ }
265+ }
266+
267+ /// Transform, psychoacoustics, quantisation and bitstream for one frame.
268+ fn encode_frame(&mut self) {
269+ // One window decision for the whole frame: a channel pair can only
270+ // share `ics_info` -- and so only use mid/side -- if it shares its
271+ // window sequence.
272+ let transient = self.config.window_switching && self.frame_transient();
273+ self.seq = match self.seq {
274+ WindowSequence::LongStart => WindowSequence::EightShort,
275+ WindowSequence::EightShort if transient => WindowSequence::EightShort,
276+ WindowSequence::EightShort => WindowSequence::LongStop,
277+ _ if transient => WindowSequence::LongStart,
278+ _ => WindowSequence::OnlyLong,
279+ };
280+ let seq = self.seq;
281+
282+ let mut frames = Vec::with_capacity(self.channels);
283+ for ch in 0..self.channels {
284+ let cur: Vec<f32> = self.pcm[ch][..FRAME_LEN]
285+ .iter()
286+ .map(|v| v * INPUT_SCALE)
287+ .collect();
288+ let mut block = Vec::with_capacity(2 * FRAME_LEN);
289+ block.extend_from_slice(&self.prev[ch]);
290+ block.extend_from_slice(&cur);
291+ self.prev[ch] = cur;
292+ let coef = self.transform(&block, seq);
293+ let threshold = self.psychoacoustics(&block, &coef, seq);
294+ frames.push(ChannelFrame { coef, threshold });
295+ }
296+ for c in self.pcm.iter_mut() {
297+ c.drain(..FRAME_LEN);
298+ }
299+
300+ let target = (u64::from(self.config.bitrate_bps) * FRAME_LEN as u64
301+ / u64::from(self.sample_rate.max(1))) as i32;
302+ let budget = target
303+ + self
304+ .reservoir
305+ .clamp(0, RESERVOIR_MAX * self.channels as i32);
306+ let data = self.write_frame(&frames, seq, budget);
307+ let used = data.len() as i32 * 8;
308+ self.reservoir =
309+ (self.reservoir + target - used).clamp(0, RESERVOIR_MAX * self.channels as i32);
310+ let data = if self.config.adts {
311+ let header = AdtsHeader {
312+ object_type: 2,
313+ sf_index: self.sf_index,
314+ sample_rate: self.sample_rate,
315+ channels: self.channels as u16,
316+ channel_config: config_for_channels(self.channels as u16),
317+ frame_length: data.len() + 7,
318+ header_len: 7,
319+ raw_blocks: 1,
320+ };
321+ let mut out = crate::config::write_adts_header(&header);
322+ out.extend_from_slice(&data);
323+ out
324+ } else {
325+ data
326+ };
327+ self.queue.push_back(EncodedPacket {
328+ data,
329+ pts: self.frames_out * FRAME_LEN as i64,
330+ duration: FRAME_LEN as u32,
331+ });
332+ self.frames_out += 1;
333+ }
334+
335+ /// An eighth-frame energy jump anywhere in the frame ahead is a transient.
336+ ///
337+ /// The running average is primed by the first frame rather than starting at
338+ /// zero: from zero every opening sample looks like an attack, and the frames
339+ /// that carry a file's first second would all be coded short.
340+ fn frame_transient(&mut self) -> bool {
341+ let mut hit = false;
342+ let primed = self.energy > 0.0;
343+ let mut running = self.energy;
344+ for i in 0..8 {
345+ let mut e = 0.0f32;
346+ for ch in 0..self.channels {
347+ let lo = FRAME_LEN + i * SHORT_LEN;
348+ for v in &self.pcm[ch][lo..lo + SHORT_LEN] {
349+ e += v * v;
350+ }
351+ }
352+ e /= (SHORT_LEN * self.channels) as f32;
353+ if primed && e > running * 8.0 && e > 1e-7 {
354+ hit = true;
355+ }
356+ running = if i == 0 && !primed {
357+ e
358+ } else {
359+ running * 0.7 + e * 0.3
360+ };
361+ }
362+ self.energy = running;
363+ hit
364+ }
365+
366+ fn transform(&mut self, block: &[f32], seq: WindowSequence) -> Vec<f32> {
367+ let mut coef = vec![0.0f32; FRAME_LEN];
368+ if seq == WindowSequence::EightShort {
369+ let win = self.short_window().to_vec();
370+ for w in 0..8 {
371+ let base = 448 + w * SHORT_LEN;
372+ self.mdct_short.forward_windowed(
373+ &block[base..base + 2 * SHORT_LEN],
374+ &win,
375+ &mut coef[w * SHORT_LEN..(w + 1) * SHORT_LEN],
376+ );
377+ }
378+ return coef;
379+ }
380+ let long = self.long_window().to_vec();
381+ let short = self.short_window().to_vec();
382+ let mut win = vec![1.0f32; 2 * FRAME_LEN];
383+ match seq {
384+ WindowSequence::LongStart => {
385+ win[..FRAME_LEN].copy_from_slice(&long[..FRAME_LEN]);
386+ win[FRAME_LEN + 448..FRAME_LEN + 576]
387+ .copy_from_slice(&short[SHORT_LEN..2 * SHORT_LEN]);
388+ win[FRAME_LEN + 576..].fill(0.0);
389+ }
390+ WindowSequence::LongStop => {
391+ win[..448].fill(0.0);
392+ win[448..576].copy_from_slice(&short[..SHORT_LEN]);
393+ win[FRAME_LEN..].copy_from_slice(&long[FRAME_LEN..]);
394+ }
395+ _ => win.copy_from_slice(&long),
396+ }
397+ self.mdct_long.forward_windowed(block, &win, &mut coef);
398+ coef
399+ }
400+
401+ /// Per-band masking thresholds; see the module docs for the model.
402+ fn psychoacoustics(&mut self, block: &[f32], coef: &[f32], seq: WindowSequence) -> Vec<f32> {
403+ let swb = self.swb(seq);
404+ let bands = swb.len() - 1;
405+ let windowed: Vec<f32> = block
406+ .iter()
407+ .zip(self.sine_long.iter())
408+ .map(|(v, w)| v * w)
409+ .collect();
410+ let mut spectrum = vec![
411+ Complex {
412+ re: 0.0f32,
413+ im: 0.0f32
414+ };
415+ FRAME_LEN + 1
416+ ];
417+ self.fft.forward(&windowed, &mut spectrum);
418+ let short = seq == WindowSequence::EightShort;
419+ let windows = if short { 8 } else { 1 };
420+ let mut energy = vec![0.0f32; bands];
421+ let mut flatness = vec![0.0f32; bands];
422+ for b in 0..bands {
423+ let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
424+ // Level comes from the MDCT itself, so the threshold and the
425+ // quantisation noise it is compared against are in the same units;
426+ // an FFT-scaled threshold would be a constant factor out, and that
427+ // constant is the difference between masking a band and coding it.
428+ let mut sum = 0.0f64;
429+ let mut n = 0usize;
430+ for w in 0..windows {
431+ let base = if short { w * SHORT_LEN } else { 0 };
432+ for k in base + lo..base + hi {
433+ sum += f64::from(coef[k]) * f64::from(coef[k]);
434+ n += 1;
435+ }
436+ }
437+ energy[b] = (sum / n.max(1) as f64) as f32;
438+ // Tonality comes from the FFT, which is what it is good for. A short
439+ // block's bands index 128 lines against the FFT's 1024, the same
440+ // eightfold ratio the filterbank uses.
441+ let (flo, fhi) = if short { (lo * 8, hi * 8) } else { (lo, hi) };
442+ let fhi = fhi.min(FRAME_LEN);
443+ let fn_ = fhi.saturating_sub(flo).max(1);
444+ let mut fsum = 0.0f64;
445+ let mut log_sum = 0.0f64;
446+ for k in flo..fhi {
447+ let p = f64::from(spectrum[k].norm_sqr()) + 1e-9;
448+ fsum += p;
449+ log_sum += p.ln();
450+ }
451+ let geometric = (log_sum / fn_ as f64).exp();
452+ flatness[b] = (geometric / (fsum / fn_ as f64).max(1e-30)) as f32;
453+ }
454+ // Two-slope spreading at band resolution: about 10 dB per band upward
455+ // in frequency, 25 dB downward.
456+ let mut spread = energy.clone();
457+ for b in 1..bands {
458+ spread[b] = spread[b].max(spread[b - 1] * 0.1);
459+ }
460+ for b in (0..bands.saturating_sub(1)).rev() {
461+ spread[b] = spread[b].max(spread[b + 1] * 0.003);
462+ }
463+ // Standing in for the absolute threshold of hearing: nothing this far
464+ // under the loudest band of the frame is audible, and without a floor
465+ // of this kind the spreading function falls away faster than the
466+ // filterbank's own leakage does, so an encoder spends its whole budget
467+ // coding the skirts of a tone at full precision.
468+ let floor = energy.iter().copied().fold(0.0f32, f32::max) * ATH_FLOOR;
469+ (0..bands)
470+ .map(|b| {
471+ // Flat (noise-like) bands mask well, peaky (tonal) ones badly.
472+ let tonality = (1.0 - flatness[b]).clamp(0.0, 1.0);
473+ let smr = 10f32.powf((6.0 + 18.0 * tonality) / 10.0);
474+ (spread[b] / smr).max(floor).max(1e-3)
475+ })
476+ .collect()
477+ }
478+
479+ /// Quantises every channel against a shared rate loop and writes the block.
480+ fn write_frame(
481+ &mut self,
482+ frames: &[ChannelFrame],
483+ seq: WindowSequence,
484+ budget: i32,
485+ ) -> Vec<u8> {
486+ let layout = element_layout(self.channels);
487+ let swb = self.swb(seq);
488+ let short = seq == WindowSequence::EightShort;
489+ let max_sfb = (swb.len() - 1).min(if short { 15 } else { 51 });
490+
491+ // Mid/side per band, decided once: the pair that codes to the more
492+ // lopsided energy split is the one that costs fewer bits.
493+ let mut elements: Vec<ElementPlan> = Vec::with_capacity(layout.len());
494+ for (element, chans) in &layout {
495+ let mut pair: Vec<ChannelFrame> = chans.iter().map(|&c| frames[c].clone()).collect();
496+ let mut ms = vec![false; max_sfb];
497+ if *element == Element::Cpe && self.config.mid_side {
498+ for b in 0..max_sfb {
499+ if ms_wins(&pair[0], &pair[1], swb, b, short) {
500+ ms[b] = true;
501+ }
502+ }
503+ apply_ms(&mut pair, &ms, swb, max_sfb, short);
504+ }
505+ elements.push(ElementPlan {
506+ element: *element,
507+ frames: pair,
508+ ms,
509+ });
510+ }
511+
512+ // Outer rate loop. Bits fall monotonically as the common offset rises,
513+ // so the finest quantisation that fits the budget is a bisection --
514+ // which also means the psychoacoustic model only has to get the shape
515+ // of the allocation right, not its absolute level.
516+ let cost = |enc: &AacEncoder, offset: i32| -> (i32, Vec<Coded>) {
517+ let mut coded = Vec::new();
518+ let mut bits = 10i32; // END element plus byte-alignment slack
519+ for plan in &elements {
520+ bits += 3
521+ + 4
522+ + if plan.element == Element::Cpe {
523+ 1 + 2 + max_sfb as i32
524+ } else {
525+ 0
526+ };
527+ for frame in &plan.frames {
528+ let c = enc.quantise(frame, seq, swb, max_sfb, offset);
529+ bits += c.bits;
530+ coded.push(c);
531+ }
532+ }
533+ (bits, coded)
534+ };
535+ let (mut lo, mut hi) = (-240i32, 240i32);
536+ let (mut bits, mut coded) = cost(self, hi);
537+ if bits > budget {
538+ // Even the coarsest setting overflows: take it and let the
539+ // reservoir absorb the overshoot.
540+ lo = hi;
541+ } else {
542+ while lo < hi {
543+ let mid = lo + (hi - lo) / 2;
544+ let (b, c) = cost(self, mid);
545+ if b <= budget {
546+ hi = mid;
547+ bits = b;
548+ coded = c;
549+ } else {
550+ lo = mid + 1;
551+ }
552+ }
553+ if lo < 240 {
554+ let (b, c) = cost(self, lo);
555+ if b <= budget {
556+ bits = b;
557+ coded = c;
558+ }
559+ }
560+ }
561+ let _ = (lo, bits);
562+
563+ let mut w = BitWriter::new();
564+ let mut at = 0usize;
565+ for plan in &elements {
566+ let id = match plan.element {
567+ Element::Sce => 0u32,
568+ Element::Cpe => 1,
569+ Element::Lfe => 3,
570+ };
571+ w.write_bits(id, 3);
572+ w.write_bits(0, 4); // element_instance_tag
573+ if plan.element == Element::Cpe {
574+ w.write_bit(true); // common_window
575+ write_ics_info(&mut w, &coded[at]);
576+ w.write_bits(1, 2); // ms_mask_present: per band
577+ for b in 0..coded[at].max_sfb {
578+ w.write_bit(plan.ms[b]);
579+ }
580+ write_ics(&mut w, &coded[at], false);
581+ write_ics(&mut w, &coded[at + 1], false);
582+ at += 2;
583+ } else {
584+ write_ics(&mut w, &coded[at], true);
585+ at += 1;
586+ }
587+ }
588+ w.write_bits(7, 3); // END
589+ w.align_to_byte();
590+ w.into_bytes()
591+ }
592+
593+ /// Inner distortion loop: the coarsest scalefactor per band whose noise
594+ /// still sits under the mask, then codebook choice and an exact bit count.
595+ ///
596+ /// Only bands that actually code anything carry a scalefactor, and the
597+ /// codebook can only code a delta of +/-60 between consecutive ones. Both
598+ /// facts are settled here rather than at write time -- a scalefactor the
599+ /// bitstream cannot carry would come back at the wrong gain, and chaining
600+ /// the constraint through *silent* bands is what drags a fine scalefactor
601+ /// into the empty top of the spectrum and spends the frame on leakage.
602+ fn quantise(
603+ &self,
604+ frame: &ChannelFrame,
605+ seq: WindowSequence,
606+ swb: &'static [u16],
607+ max_sfb: usize,
608+ offset: i32,
609+ ) -> Coded {
610+ let short = seq == WindowSequence::EightShort;
611+ let windows = if short { 8 } else { 1 };
612+ let mut sf = vec![0i32; max_sfb];
613+ let mut floor = vec![0i32; max_sfb];
614+ let mut zero = vec![true; max_sfb];
615+ for b in 0..max_sfb {
616+ let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
617+ let mut peak = 0.0f32;
618+ for w in 0..windows {
619+ let base = if short { w * SHORT_LEN } else { 0 };
620+ for k in base + lo..base + hi {
621+ peak = peak.max(frame.coef[k].abs());
622+ }
623+ }
624+ if peak < 1e-4 {
625+ continue;
626+ }
627+ // The rate loop scales the whole mask rather than shifting the
628+ // scalefactors: that keeps the noise following the shape the model
629+ // asked for, and lets a band whose signal falls under its own mask
630+ // drop out entirely instead of being coded ever more coarsely.
631+ let target = frame.threshold[b] * 2f32.powf(offset as f32 * 0.5);
632+ let mut energy = 0.0f32;
633+ let mut count = 0usize;
634+ for w in 0..windows {
635+ let base = if short { w * SHORT_LEN } else { 0 };
636+ for k in base + lo..base + hi {
637+ energy += frame.coef[k] * frame.coef[k];
638+ count += 1;
639+ }
640+ }
641+ if energy / count.max(1) as f32 <= target {
642+ continue;
643+ }
644+ floor[b] = sf_floor(peak).max(0);
645+ let mut best = floor[b];
646+ let mut level = best;
647+ while level < 255 {
648+ if self.band_noise(frame, swb, b, level, windows, short) > target {
649+ break;
650+ }
651+ best = level;
652+ level += 1;
653+ }
654+ sf[b] = best.clamp(floor[b], 255);
655+ zero[b] = false;
656+ }
657+
658+ let mut quant = vec![0i32; FRAME_LEN];
659+ let mut books = vec![0u8; max_sfb];
660+ for _ in 0..4 {
661+ let mut settled = true;
662+ let mut prev: Option<i32> = None;
663+ for b in 0..max_sfb {
664+ if zero[b] {
665+ continue;
666+ }
667+ let fixed = match prev {
668+ None => sf[b],
669+ Some(p) => sf[b].clamp(p - 60, p + 60).clamp(0, 255),
670+ };
671+ if fixed != sf[b] {
672+ sf[b] = fixed;
673+ settled = false;
674+ }
675+ prev = Some(sf[b]);
676+ }
677+ for b in 0..max_sfb {
678+ let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
679+ if zero[b] {
680+ books[b] = 0;
681+ for w in 0..windows {
682+ let base = if short { w * SHORT_LEN } else { 0 };
683+ quant[base + lo..base + hi].fill(0);
684+ }
685+ continue;
686+ }
687+ let mut peak = 0i32;
688+ for w in 0..windows {
689+ let base = if short { w * SHORT_LEN } else { 0 };
690+ for k in lo..hi {
691+ let q = quantise_one(frame.coef[base + k], sf[b]);
692+ quant[base + k] = q;
693+ peak = peak.max(q.abs());
694+ }
695+ }
696+ books[b] = codebook_for(peak);
697+ if peak == 0 {
698+ // Nothing survived: the band leaves the delta chain, which
699+ // may free the bands after it to go coarser.
700+ zero[b] = true;
701+ settled = false;
702+ }
703+ }
704+ if settled {
705+ break;
706+ }
707+ }
708+
709+ let mut bits = 8 + 3; // global_gain plus the three tool flags
710+ let mut prev: Option<i32> = None;
711+ for b in 0..max_sfb {
712+ if books[b] == 0 {
713+ continue;
714+ }
715+ bits += band_bits(&quant, swb, b, books[b], windows, short);
716+ let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120));
717+ bits += i32::from(SCALEFACTOR_CODES[value as usize].0);
718+ prev = Some(sf[b]);
719+ }
720+ let mut sections = 0;
721+ let mut b = 0usize;
722+ while b < max_sfb {
723+ let book = books[b];
724+ while b < max_sfb && books[b] == book {
725+ b += 1;
726+ }
727+ sections += 1;
728+ }
729+ bits += sections * (4 + if short { 3 } else { 5 });
730+ Coded {
731+ seq,
732+ max_sfb,
733+ swb,
734+ sf,
735+ books,
736+ quant,
737+ bits,
738+ short,
739+ }
740+ }
741+
742+ /// Quantisation noise energy of one band at a candidate scalefactor.
743+ fn band_noise(
744+ &self,
745+ frame: &ChannelFrame,
746+ swb: &[u16],
747+ band: usize,
748+ sf: i32,
749+ windows: usize,
750+ short: bool,
751+ ) -> f32 {
752+ let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
753+ let gain = 2f32.powf((sf - SF_OFFSET) as f32 * 0.25);
754+ let mut noise = 0.0f32;
755+ let mut count = 0usize;
756+ for w in 0..windows {
757+ let base = if short { w * SHORT_LEN } else { 0 };
758+ for k in base + lo..base + hi {
759+ let x = frame.coef[k];
760+ let q = quantise_one(x, sf);
761+ let mut back = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain;
762+ if q < 0 {
763+ back = -back;
764+ }
765+ noise += (x - back) * (x - back);
766+ count += 1;
767+ }
768+ }
769+ noise / count.max(1) as f32
770+ }
771+}
772+
773+struct ElementPlan {
774+ element: Element,
775+ frames: Vec<ChannelFrame>,
776+ ms: Vec<bool>,
777+}
778+
779+/// A channel's quantised frame, ready to write.
780+struct Coded {
781+ seq: WindowSequence,
782+ max_sfb: usize,
783+ swb: &'static [u16],
784+ sf: Vec<i32>,
785+ books: Vec<u8>,
786+ quant: Vec<i32>,
787+ bits: i32,
788+ short: bool,
789+}
790+
791+/// True when mid/side splits this band's energy more lopsidedly than left/right
792+/// does, which is when it costs fewer bits.
793+fn ms_wins(l: &ChannelFrame, r: &ChannelFrame, swb: &[u16], band: usize, short: bool) -> bool {
794+ let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
795+ let windows = if short { 8 } else { 1 };
796+ let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
797+ for w in 0..windows {
798+ let base = if short { w * SHORT_LEN } else { 0 };
799+ for k in base + lo..base + hi {
800+ let (a, b) = (f64::from(l.coef[k]), f64::from(r.coef[k]));
801+ el += a * a;
802+ er += b * b;
803+ em += (a + b) * (a + b) * 0.25;
804+ es += (a - b) * (a - b) * 0.25;
805+ }
806+ }
807+ let lr = (el.max(er) + 1e-9) / (el.min(er) + 1e-9);
808+ let ms = (em.max(es) + 1e-9) / (em.min(es) + 1e-9);
809+ ms > lr * 1.5
810+}
811+
812+fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) {
813+ let windows = if short { 8 } else { 1 };
814+ for b in 0..max_sfb {
815+ if !ms[b] {
816+ continue;
817+ }
818+ let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
819+ for w in 0..windows {
820+ let base = if short { w * SHORT_LEN } else { 0 };
821+ for k in base + lo..base + hi {
822+ let (a, b2) = (pair[0].coef[k], pair[1].coef[k]);
823+ pair[0].coef[k] = (a + b2) * 0.5;
824+ pair[1].coef[k] = (a - b2) * 0.5;
825+ }
826+ }
827+ // The side channel inherits the pair's tighter mask.
828+ let t = pair[0].threshold[b].min(pair[1].threshold[b]);
829+ pair[0].threshold[b] = t;
830+ pair[1].threshold[b] = t;
831+ }
832+}
833+
834+/// The finest scalefactor at which a peak of this size still fits the escape
835+/// codebook: below it the quantiser saturates, which costs bits *and* adds
836+/// distortion.
837+fn sf_floor(peak: f32) -> i32 {
838+ let want = (0.75 * peak.log2() - (MAX_QUANT as f32).log2()) / 0.1875;
839+ SF_OFFSET + want.ceil() as i32
840+}
841+
842+fn quantise_one(x: f32, sf: i32) -> i32 {
843+ if x == 0.0 {
844+ return 0;
845+ }
846+ let gain = 2f32.powf(-(sf - SF_OFFSET) as f32 * 0.25);
847+ let q = ((x.abs() * gain).powf(0.75) + ROUND_BIAS) as i32;
848+ let q = q.min(MAX_QUANT);
849+ if x < 0.0 { -q } else { q }
850+}
851+
852+/// The cheapest codebook that can carry a peak magnitude.
853+fn codebook_for(peak: i32) -> u8 {
854+ match peak {
855+ 0 => 0,
856+ 1 => 1,
857+ 2 => 3,
858+ 3..=4 => 5,
859+ 5..=7 => 7,
860+ 8..=12 => 9,
861+ _ => 11,
862+ }
863+}
864+
865+fn band_bits(
866+ quant: &[i32],
867+ swb: &[u16],
868+ band: usize,
869+ book: u8,
870+ windows: usize,
871+ short: bool,
872+) -> i32 {
873+ let cb = &CODEBOOKS[usize::from(book) - 1];
874+ let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
875+ let dim = usize::from(cb.dim);
876+ let mut bits = 0i32;
877+ for w in 0..windows {
878+ let base = if short { w * SHORT_LEN } else { 0 };
879+ let mut k = lo;
880+ while k < hi {
881+ let end = (k + dim).min(hi);
882+ bits += tuple_bits(cb, &quant[base + k..base + end]);
883+ k += dim;
884+ }
885+ }
886+ bits
887+}
888+
889+/// Bits one Huffman tuple costs, sign and escape included.
890+fn tuple_bits(cb: &Codebook, values: &[i32]) -> i32 {
891+ let mut bits = i32::from(cb.codes[tuple_index(cb, values)].0);
892+ for &v in values {
893+ if cb.unsigned && v != 0 {
894+ bits += 1;
895+ }
896+ if cb.esc && v.unsigned_abs() >= 16 {
897+ let n = escape_order(v.unsigned_abs());
898+ bits += 2 * n + 5;
899+ }
900+ }
901+ bits
902+}
903+
904+/// The escape's unary length: `value` needs `n + 4` payload bits.
905+fn escape_order(mag: u32) -> i32 {
906+ (32 - mag.leading_zeros()) as i32 - 5
907+}
908+
909+/// Tuple to codebook index, clamped into the codebook's range.
910+fn tuple_index(cb: &Codebook, values: &[i32]) -> usize {
911+ let span = if cb.unsigned {
912+ usize::from(cb.lav) + 1
913+ } else {
914+ 2 * usize::from(cb.lav) + 1
915+ };
916+ let mut idx = 0usize;
917+ for i in 0..usize::from(cb.dim) {
918+ let v = values.get(i).copied().unwrap_or(0);
919+ let digit = if cb.unsigned {
920+ v.unsigned_abs().min(u32::from(cb.lav)) as usize
921+ } else {
922+ (v.clamp(-i32::from(cb.lav), i32::from(cb.lav)) + i32::from(cb.lav)) as usize
923+ };
924+ idx = idx * span + digit;
925+ }
926+ idx
927+}
928+
929+fn write_tuple(w: &mut BitWriter, cb: &Codebook, values: &[i32]) {
930+ let (len, code) = cb.codes[tuple_index(cb, values)];
931+ w.write_bits(code, u32::from(len));
932+ if cb.unsigned {
933+ for &v in values.iter().take(usize::from(cb.dim)) {
934+ if v != 0 {
935+ w.write_bit(v < 0);
936+ }
937+ }
938+ }
939+ if cb.esc {
940+ for &v in values.iter().take(usize::from(cb.dim)) {
941+ let mag = v.unsigned_abs();
942+ if mag >= 16 {
943+ let n = escape_order(mag) as u32;
944+ for _ in 0..n {
945+ w.write_bit(true);
946+ }
947+ w.write_bit(false);
948+ w.write_bits(mag & ((1 << (n + 4)) - 1), n + 4);
949+ }
950+ }
951+ }
952+}
953+
954+fn write_ics_info(w: &mut BitWriter, c: &Coded) {
955+ w.write_bit(false); // ics_reserved_bit
956+ let seq = match c.seq {
957+ WindowSequence::OnlyLong => 0,
958+ WindowSequence::LongStart => 1,
959+ WindowSequence::EightShort => 2,
960+ WindowSequence::LongStop => 3,
961+ };
962+ w.write_bits(seq, 2);
963+ w.write_bit(false); // sine window shape
964+ if c.short {
965+ w.write_bits(c.max_sfb as u32, 4);
966+ w.write_bits(0x7F, 7); // one group of eight windows
967+ } else {
968+ w.write_bits(c.max_sfb as u32, 6);
969+ w.write_bit(false); // predictor_data_present
970+ }
971+}
972+
973+fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
974+ let first = c.books.iter().position(|&b| b != 0);
975+ let global_gain = first.map_or(100, |b| c.sf[b]).clamp(0, 255) as u32;
976+ w.write_bits(global_gain, 8);
977+ if own_info {
978+ write_ics_info(w, c);
979+ }
980+ // section_data
981+ let esc_bits = if c.short { 3 } else { 5 };
982+ let esc = (1u32 << esc_bits) - 1;
983+ let mut b = 0usize;
984+ while b < c.max_sfb {
985+ let book = c.books[b];
986+ let start = b;
987+ while b < c.max_sfb && c.books[b] == book {
988+ b += 1;
989+ }
990+ w.write_bits(u32::from(book), 4);
991+ let mut left = (b - start) as u32;
992+ while left >= esc {
993+ w.write_bits(esc, esc_bits);
994+ left -= esc;
995+ }
996+ w.write_bits(left, esc_bits);
997+ }
998+ // scale_factor_data
999+ let mut prev = global_gain as i32;
1000+ for b in 0..c.max_sfb {
1001+ if c.books[b] == 0 {
1002+ continue;
1003+ }
1004+ let value = (60 + c.sf[b] - prev).clamp(0, 120) as usize;
1005+ let (len, code) = SCALEFACTOR_CODES[value];
1006+ w.write_bits(code, u32::from(len));
1007+ prev += value as i32 - 60;
1008+ }
1009+ w.write_bit(false); // pulse_data_present
1010+ w.write_bit(false); // tns_data_present
1011+ w.write_bit(false); // gain_control_data_present
1012+ // spectral_data
1013+ let windows = if c.short { 8 } else { 1 };
1014+ for b in 0..c.max_sfb {
1015+ let book = c.books[b];
1016+ if book == 0 {
1017+ continue;
1018+ }
1019+ let cb = &CODEBOOKS[usize::from(book) - 1];
1020+ let dim = usize::from(cb.dim);
1021+ let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1]));
1022+ for win in 0..windows {
1023+ let base = if c.short { win * SHORT_LEN } else { 0 };
1024+ let mut k = lo;
1025+ while k < hi {
1026+ let end = (k + dim).min(hi);
1027+ write_tuple(w, cb, &c.quant[base + k..base + end]);
1028+ k += dim;
1029+ }
1030+ }
1031+ }
1032+}
1033+
1034+/// Which channel element carries which of the caller's channels. The caller
1035+/// speaks film order (`FL, FR, FC, LFE, BL, BR, SL, SR`); the bitstream wants
1036+/// centre first and LFE last (ISO/IEC 14496-3 tbl 1.19).
1037+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1038+enum Element {
1039+ Sce,
1040+ Cpe,
1041+ Lfe,
1042+}
1043+
1044+fn element_layout(channels: usize) -> Vec<(Element, Vec<usize>)> {
1045+ match channels {
1046+ 1 => vec![(Element::Sce, vec![0])],
1047+ 2 => vec![(Element::Cpe, vec![0, 1])],
1048+ 3 => vec![(Element::Sce, vec![2]), (Element::Cpe, vec![0, 1])],
1049+ 4 => vec![
1050+ (Element::Sce, vec![2]),
1051+ (Element::Cpe, vec![0, 1]),
1052+ (Element::Sce, vec![3]),
1053+ ],
1054+ 5 => vec![
1055+ (Element::Sce, vec![2]),
1056+ (Element::Cpe, vec![0, 1]),
1057+ (Element::Cpe, vec![3, 4]),
1058+ ],
1059+ 6 => vec![
1060+ (Element::Sce, vec![2]),
1061+ (Element::Cpe, vec![0, 1]),
1062+ (Element::Cpe, vec![4, 5]),
1063+ (Element::Lfe, vec![3]),
1064+ ],
1065+ 8 => vec![
1066+ (Element::Sce, vec![2]),
1067+ (Element::Cpe, vec![0, 1]),
1068+ (Element::Cpe, vec![6, 7]),
1069+ (Element::Cpe, vec![4, 5]),
1070+ (Element::Lfe, vec![3]),
1071+ ],
1072+ n => (0..n).map(|i| (Element::Sce, vec![i])).collect(),
1073+ }
1074+}
crates/ec-aac/src/huffman.rsadded+85 -0
@@ -0,0 +1,85 @@
1+//! Prefix-code decoding for the spectral and scalefactor codebooks.
2+//!
3+//! Every codebook is a complete prefix code (Kraft sum exactly 1, asserted in
4+//! the tests), so a binary tree walk is total: no bit pattern falls off the
5+//! tree, and the only failure a stream can produce is running out of bits.
6+
7+use ec_core::{BitReader, Error, Result};
8+
9+/// A codebook as a walkable binary tree. `nodes[i]` holds the two children of
10+/// node `i`; a non-negative child is another node, a negative one is the leaf
11+/// `-(index + 1)`.
12+#[derive(Debug, Clone)]
13+pub struct Tree {
14+ nodes: Vec<[i32; 2]>,
15+}
16+
17+impl Tree {
18+ /// Builds the tree from `(length, code)` by symbol index.
19+ ///
20+ /// # Panics
21+ /// If two symbols share a prefix, which would mean a corrupt table.
22+ pub fn new(codes: &[(u8, u32)]) -> Tree {
23+ let mut nodes = vec![[0i32; 2]];
24+ for (symbol, &(len, code)) in codes.iter().enumerate() {
25+ let mut at = 0usize;
26+ for depth in (0..len).rev() {
27+ let bit = ((code >> depth) & 1) as usize;
28+ let last = depth == 0;
29+ if last {
30+ assert_eq!(nodes[at][bit], 0, "codebook prefix collision");
31+ nodes[at][bit] = -(symbol as i32 + 1);
32+ } else if nodes[at][bit] == 0 {
33+ nodes.push([0i32; 2]);
34+ let next = nodes.len() as i32 - 1;
35+ nodes[at][bit] = next;
36+ at = next as usize;
37+ } else {
38+ at = nodes[at][bit] as usize;
39+ }
40+ }
41+ }
42+ Tree { nodes }
43+ }
44+
45+ /// Reads one symbol index.
46+ pub fn decode(&self, r: &mut BitReader<'_>) -> Result<usize> {
47+ let mut at = 0usize;
48+ loop {
49+ let bit = usize::from(r.read_bit()?);
50+ let next = self.nodes[at][bit];
51+ if next < 0 {
52+ return Ok((-next - 1) as usize);
53+ }
54+ if next == 0 {
55+ return Err(Error::corrupt("aac: undefined Huffman code"));
56+ }
57+ at = next as usize;
58+ }
59+ }
60+}
61+
62+/// The eleven spectral trees plus the scalefactor tree, built once per decoder.
63+#[derive(Debug, Clone)]
64+pub struct Books {
65+ pub spectral: Vec<Tree>,
66+ pub scalefactor: Tree,
67+}
68+
69+impl Books {
70+ pub fn new() -> Books {
71+ Books {
72+ spectral: crate::tables::CODEBOOKS
73+ .iter()
74+ .map(|cb| Tree::new(cb.codes))
75+ .collect(),
76+ scalefactor: Tree::new(crate::tables::SCALEFACTOR_CODES),
77+ }
78+ }
79+}
80+
81+impl Default for Books {
82+ fn default() -> Books {
83+ Books::new()
84+ }
85+}
crates/ec-aac/src/lib.rsadded+230 -0
@@ -0,0 +1,230 @@
1+//! AAC-LC: decoder (mono through 7.1) and encoder, in safe Rust.
2+//!
3+//! # Where the tables come from
4+//!
5+//! The Huffman codebooks, the scalefactor codebook and the scalefactor-band
6+//! offsets in [`tables`] were **derived**, not transcribed: `scripts/derive-aac-tables.py`
7+//! synthesises access units whose spectral payload is a chosen bit string, has a
8+//! reference decoder decode them, and reads the quantised spectrum back through
9+//! the inverse MDCT. Walking the binary tree of probes enumerates each codebook
10+//! in about `2M` frames for `M` codewords. Every table came out with a Kraft
11+//! sum of exactly 1 and the entry count ISO/IEC 14496-3 prescribes, which is
12+//! what makes the derivation self-checking rather than a transcription to be
13+//! trusted.
14+//!
15+//! # What is here and what is not
16+//!
17+//! AAC-LC (audio object type 2) is complete: all four window sequences, both
18+//! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE,
19+//! LFE, DSE, PCE and FIL elements. HE-AAC's SBR and Parametric Stereo are
20+//! **not** implemented; a stream that signals them decodes to its AAC-LC core,
21+//! at the core sample rate, and says so through [`AacDecoder::sbr_support`] and
22+//! [`AacDecoder::output_sample_rate`] rather than silently claiming the
23+//! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests.
24+
25+#![forbid(unsafe_code)]
26+
27+mod config;
28+mod decode;
29+mod encode;
30+mod huffman;
31+pub mod tables;
32+
33+pub use config::{
34+ AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig,
35+ audio_specific_config_bytes, channels_for_config, config_for_channels, is_adts, parse_adts,
36+ parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate,
37+ write_adts_header, write_audio_specific_config,
38+};
39+pub use decode::{FRAME_LEN, WindowSequence};
40+pub use ec_core::{Error, Result};
41+pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape};
42+pub use tables::SAMPLE_RATES;
43+
44+use decode::BlockDecoder;
45+use ec_core::BitReader;
46+
47+/// What this decoder does with a High Efficiency stream.
48+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49+pub enum SbrSupport {
50+ /// The stream is plain AAC-LC: nothing is missing.
51+ NotSignalled,
52+ /// SBR (and possibly PS) is signalled and is **not** reconstructed. The
53+ /// AAC-LC core decodes, at the core rate, half the signalled bandwidth.
54+ CoreOnly,
55+}
56+
57+/// One decoded frame: interleaved `f32` in film channel order.
58+#[derive(Clone, Debug, Default)]
59+pub struct DecodedAudio {
60+ pub sample_rate: u32,
61+ pub channels: u16,
62+ /// Interleaved samples, `frames() * channels` of them.
63+ pub samples: Vec<f32>,
64+ pub pts: Option<i64>,
65+}
66+
67+impl DecodedAudio {
68+ /// Sample frames in this block.
69+ pub fn frames(&self) -> usize {
70+ if self.channels == 0 {
71+ 0
72+ } else {
73+ self.samples.len() / usize::from(self.channels)
74+ }
75+ }
76+}
77+
78+/// Bitstream element order to the film order `FL, FR, FC, LFE, BL, BR, SL, SR`
79+/// that every downmix in this family folds (ISO/IEC 14496-3 tbl 1.19: the
80+/// elements arrive centre first, LFE last).
81+fn film_order(channels: usize) -> &'static [usize] {
82+ match channels {
83+ 3 => &[1, 2, 0],
84+ 4 => &[1, 2, 0, 3],
85+ 5 => &[1, 2, 0, 3, 4],
86+ 6 => &[1, 2, 0, 5, 3, 4],
87+ 8 => &[1, 2, 0, 7, 5, 6, 3, 4],
88+ _ => &[0, 1, 2, 3, 4, 5, 6, 7],
89+ }
90+}
91+
92+/// An AAC-LC decoder.
93+pub struct AacDecoder {
94+ block: BlockDecoder,
95+ config: Option<AudioSpecificConfig>,
96+ sample_rate: u32,
97+ channels: u16,
98+}
99+
100+impl AacDecoder {
101+ /// A decoder with no configuration yet: it will take its parameters from
102+ /// the first ADTS header it sees.
103+ pub fn new() -> AacDecoder {
104+ AacDecoder {
105+ block: BlockDecoder::new(3),
106+ config: None,
107+ sample_rate: 0,
108+ channels: 0,
109+ }
110+ }
111+
112+ /// A decoder configured from a parsed AudioSpecificConfig.
113+ pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
114+ let mut d = AacDecoder::new();
115+ d.block.set_sf_index(cfg.sf_index);
116+ d.sample_rate = cfg.sample_rate;
117+ d.channels = cfg.channels;
118+ d.config = Some(cfg);
119+ d
120+ }
121+
122+ /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4
123+ /// `esds` payload or a Matroska `CodecPrivate`.
124+ pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
125+ Ok(AacDecoder::with_config(parse_audio_specific_config(data)?))
126+ }
127+
128+ /// The configuration this decoder was built with, if any.
129+ pub fn config(&self) -> Option<&AudioSpecificConfig> {
130+ self.config.as_ref()
131+ }
132+
133+ /// Whether the stream asked for SBR, and what became of it.
134+ pub fn sbr_support(&self) -> SbrSupport {
135+ match &self.config {
136+ Some(c) if c.sbr_present || c.ps_present => SbrSupport::CoreOnly,
137+ _ => SbrSupport::NotSignalled,
138+ }
139+ }
140+
141+ /// The rate the samples this decoder hands back are actually at.
142+ ///
143+ /// For an HE-AAC stream this is the **core** rate, not the doubled rate the
144+ /// configuration advertises: the SBR extension is not reconstructed, so
145+ /// claiming its rate would be claiming bandwidth that is not there.
146+ pub fn output_sample_rate(&self) -> Option<u32> {
147+ self.config.as_ref().map(|c| c.sample_rate)
148+ }
149+
150+ /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames.
151+ pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
152+ let mut planes: Vec<Vec<f32>> = Vec::new();
153+ if is_adts(packet) {
154+ let mut at = 0usize;
155+ while at + 7 <= packet.len() {
156+ let header = parse_adts(&packet[at..])?;
157+ let end = (at + header.frame_length).min(packet.len());
158+ let body = &packet[at + header.header_len..end];
159+ if self.config.is_none() {
160+ self.sample_rate = header.sample_rate;
161+ self.channels = header.channels;
162+ self.block.set_sf_index(header.sf_index);
163+ }
164+ let mut r = BitReader::new(body);
165+ for _ in 0..header.raw_blocks {
166+ let block = self.block.raw_data_block(&mut r)?;
167+ merge(&mut planes, block);
168+ if r.bits_remaining() < 8 {
169+ break;
170+ }
171+ }
172+ if header.frame_length == 0 {
173+ break;
174+ }
175+ at += header.frame_length;
176+ }
177+ } else {
178+ let mut r = BitReader::new(packet);
179+ planes = self.block.raw_data_block(&mut r)?;
180+ }
181+ let channels = planes.len();
182+ if channels == 0 {
183+ return Ok(DecodedAudio {
184+ sample_rate: self.sample_rate,
185+ channels: self.channels,
186+ samples: Vec::new(),
187+ pts,
188+ });
189+ }
190+ if self.channels == 0 {
191+ self.channels = channels as u16;
192+ }
193+ let order = film_order(channels);
194+ let frames = planes[0].len();
195+ let mut samples = vec![0.0f32; frames * channels];
196+ for (out_ch, &src) in order.iter().take(channels).enumerate() {
197+ let plane = &planes[src.min(channels - 1)];
198+ for (i, &v) in plane.iter().enumerate() {
199+ samples[i * channels + out_ch] = v;
200+ }
201+ }
202+ Ok(DecodedAudio {
203+ sample_rate: self.sample_rate,
204+ channels: channels as u16,
205+ samples,
206+ pts,
207+ })
208+ }
209+}
210+
211+/// Appends a block's planes to the packet's, growing the plane count if a later
212+/// `raw_data_block` carries more channels than an earlier one.
213+fn merge(planes: &mut Vec<Vec<f32>>, block: Vec<Vec<f32>>) {
214+ if planes.is_empty() {
215+ *planes = block;
216+ return;
217+ }
218+ for (i, plane) in block.into_iter().enumerate() {
219+ match planes.get_mut(i) {
220+ Some(dst) => dst.extend_from_slice(&plane),
221+ None => planes.push(plane),
222+ }
223+ }
224+}
225+
226+impl Default for AacDecoder {
227+ fn default() -> AacDecoder {
228+ AacDecoder::new()
229+ }
230+}
crates/ec-aac/src/tables.rsadded+1609 -0
@@ -0,0 +1,1609 @@
1+//! Normative AAC tables (ISO/IEC 14496-3 §4.6.2, §4.6.9, tbl 4.140).
2+//!
3+//! Every number here was derived by black-box probing of a reference decoder,
4+//! not copied from an implementation: `scripts/derive-aac-tables.py` synthesises
5+//! access units whose spectral payload is a chosen bit string, decodes them, and
6+//! reads the quantised spectrum back through the inverse MDCT. Each codebook
7+//! came out with a Kraft sum of exactly 1 and the entry count the standard
8+//! prescribes, which is what makes the derivation self-checking.
9+/// Codebook 1: dim 4, lav 1, signed.
10+static HCB1: [(u8, u32); 81] = [
11+ (11, 2040),
12+ (9, 497),
13+ (11, 2045),
14+ (10, 1013),
15+ (7, 104),
16+ (10, 1008),
17+ (11, 2039),
18+ (9, 492),
19+ (11, 2037),
20+ (10, 1009),
21+ (7, 114),
22+ (10, 1012),
23+ (7, 116),
24+ (5, 17),
25+ (7, 118),
26+ (9, 491),
27+ (7, 108),
28+ (10, 1014),
29+ (11, 2044),
30+ (9, 481),
31+ (11, 2033),
32+ (9, 496),
33+ (7, 97),
34+ (9, 502),
35+ (11, 2034),
36+ (9, 490),
37+ (11, 2043),
38+ (9, 498),
39+ (7, 105),
40+ (9, 493),
41+ (7, 119),
42+ (5, 23),
43+ (7, 111),
44+ (9, 486),
45+ (7, 100),
46+ (9, 485),
47+ (7, 103),
48+ (5, 21),
49+ (7, 98),
50+ (5, 18),
51+ (1, 0),
52+ (5, 20),
53+ (7, 101),
54+ (5, 22),
55+ (7, 109),
56+ (9, 489),
57+ (7, 99),
58+ (9, 484),
59+ (7, 107),
60+ (5, 19),
61+ (7, 113),
62+ (9, 483),
63+ (7, 112),
64+ (9, 499),
65+ (11, 2046),
66+ (9, 487),
67+ (11, 2035),
68+ (9, 495),
69+ (7, 96),
70+ (9, 494),
71+ (11, 2032),
72+ (9, 482),
73+ (11, 2042),
74+ (10, 1011),
75+ (7, 106),
76+ (9, 488),
77+ (7, 117),
78+ (5, 16),
79+ (7, 115),
80+ (9, 500),
81+ (7, 110),
82+ (10, 1015),
83+ (11, 2038),
84+ (9, 480),
85+ (11, 2041),
86+ (10, 1010),
87+ (7, 102),
88+ (9, 501),
89+ (11, 2047),
90+ (9, 503),
91+ (11, 2036),
92+];
93+/// Codebook 2: dim 4, lav 1, signed.
94+static HCB2: [(u8, u32); 81] = [
95+ (9, 499),
96+ (7, 111),
97+ (9, 509),
98+ (8, 235),
99+ (6, 35),
100+ (8, 234),
101+ (9, 503),
102+ (8, 232),
103+ (9, 506),
104+ (8, 242),
105+ (6, 45),
106+ (7, 112),
107+ (6, 32),
108+ (5, 6),
109+ (6, 43),
110+ (7, 110),
111+ (6, 40),
112+ (8, 233),
113+ (9, 505),
114+ (7, 102),
115+ (8, 248),
116+ (8, 231),
117+ (6, 27),
118+ (8, 241),
119+ (9, 500),
120+ (7, 107),
121+ (9, 501),
122+ (8, 236),
123+ (6, 42),
124+ (7, 108),
125+ (6, 44),
126+ (5, 10),
127+ (6, 39),
128+ (7, 103),
129+ (6, 26),
130+ (8, 245),
131+ (6, 36),
132+ (5, 8),
133+ (6, 31),
134+ (5, 9),
135+ (3, 0),
136+ (5, 7),
137+ (6, 29),
138+ (5, 11),
139+ (6, 48),
140+ (8, 239),
141+ (6, 28),
142+ (7, 100),
143+ (6, 30),
144+ (5, 12),
145+ (6, 41),
146+ (8, 243),
147+ (6, 47),
148+ (8, 240),
149+ (9, 508),
150+ (7, 113),
151+ (9, 498),
152+ (8, 244),
153+ (6, 33),
154+ (8, 230),
155+ (8, 247),
156+ (7, 104),
157+ (9, 504),
158+ (8, 238),
159+ (6, 34),
160+ (7, 101),
161+ (6, 49),
162+ (4, 2),
163+ (6, 38),
164+ (8, 237),
165+ (6, 37),
166+ (7, 106),
167+ (9, 507),
168+ (7, 114),
169+ (9, 510),
170+ (7, 105),
171+ (6, 46),
172+ (8, 246),
173+ (9, 511),
174+ (7, 109),
175+ (9, 502),
176+];
177+/// Codebook 3: dim 4, lav 2, unsigned.
178+static HCB3: [(u8, u32); 81] = [
179+ (1, 0),
180+ (4, 9),
181+ (8, 239),
182+ (4, 11),
183+ (5, 25),
184+ (8, 240),
185+ (9, 491),
186+ (9, 486),
187+ (10, 1010),
188+ (4, 10),
189+ (6, 53),
190+ (9, 495),
191+ (6, 52),
192+ (6, 55),
193+ (9, 489),
194+ (9, 493),
195+ (9, 487),
196+ (10, 1011),
197+ (9, 494),
198+ (10, 1005),
199+ (13, 8186),
200+ (9, 492),
201+ (9, 498),
202+ (11, 2041),
203+ (11, 2040),
204+ (10, 1016),
205+ (12, 4088),
206+ (4, 8),
207+ (6, 56),
208+ (10, 1014),
209+ (6, 54),
210+ (7, 117),
211+ (10, 1009),
212+ (10, 1003),
213+ (10, 1004),
214+ (12, 4084),
215+ (5, 24),
216+ (7, 118),
217+ (11, 2036),
218+ (6, 57),
219+ (7, 116),
220+ (10, 1007),
221+ (9, 499),
222+ (9, 500),
223+ (11, 2038),
224+ (9, 488),
225+ (10, 1002),
226+ (13, 8188),
227+ (8, 242),
228+ (9, 497),
229+ (12, 4091),
230+ (10, 1013),
231+ (11, 2035),
232+ (12, 4092),
233+ (8, 238),
234+ (10, 1015),
235+ (15, 32766),
236+ (9, 496),
237+ (11, 2037),
238+ (15, 32765),
239+ (13, 8187),
240+ (14, 16378),
241+ (16, 65535),
242+ (8, 241),
243+ (10, 1008),
244+ (14, 16380),
245+ (9, 490),
246+ (10, 1006),
247+ (14, 16379),
248+ (12, 4086),
249+ (12, 4090),
250+ (15, 32764),
251+ (11, 2034),
252+ (12, 4085),
253+ (16, 65534),
254+ (10, 1012),
255+ (11, 2039),
256+ (15, 32763),
257+ (12, 4087),
258+ (12, 4089),
259+ (15, 32762),
260+];
261+/// Codebook 4: dim 4, lav 2, unsigned.
262+static HCB4: [(u8, u32); 81] = [
263+ (4, 7),
264+ (5, 22),
265+ (8, 246),
266+ (5, 24),
267+ (4, 8),
268+ (8, 239),
269+ (9, 495),
270+ (8, 243),
271+ (11, 2040),
272+ (5, 25),
273+ (5, 23),
274+ (8, 237),
275+ (5, 21),
276+ (4, 1),
277+ (8, 226),
278+ (8, 240),
279+ (7, 112),
280+ (10, 1008),
281+ (9, 494),
282+ (8, 241),
283+ (11, 2042),
284+ (8, 238),
285+ (8, 228),
286+ (10, 1010),
287+ (11, 2038),
288+ (10, 1007),
289+ (11, 2045),
290+ (4, 5),
291+ (5, 20),
292+ (8, 242),
293+ (4, 9),
294+ (4, 4),
295+ (8, 229),
296+ (8, 244),
297+ (8, 232),
298+ (10, 1012),
299+ (4, 6),
300+ (4, 2),
301+ (8, 231),
302+ (4, 3),
303+ (4, 0),
304+ (7, 107),
305+ (8, 227),
306+ (7, 105),
307+ (9, 499),
308+ (8, 235),
309+ (8, 230),
310+ (10, 1014),
311+ (7, 110),
312+ (7, 106),
313+ (9, 500),
314+ (10, 1004),
315+ (9, 496),
316+ (10, 1017),
317+ (8, 245),
318+ (8, 236),
319+ (11, 2043),
320+ (8, 234),
321+ (7, 111),
322+ (10, 1015),
323+ (11, 2041),
324+ (10, 1011),
325+ (12, 4095),
326+ (8, 233),
327+ (7, 109),
328+ (10, 1016),
329+ (7, 108),
330+ (7, 104),
331+ (9, 501),
332+ (10, 1006),
333+ (9, 498),
334+ (11, 2036),
335+ (11, 2039),
336+ (10, 1009),
337+ (12, 4094),
338+ (10, 1005),
339+ (9, 497),
340+ (11, 2037),
341+ (11, 2046),
342+ (10, 1013),
343+ (11, 2044),
344+];
345+/// Codebook 5: dim 2, lav 4, signed.
346+static HCB5: [(u8, u32); 81] = [
347+ (13, 8191),
348+ (12, 4087),
349+ (11, 2036),
350+ (11, 2024),
351+ (10, 1009),
352+ (11, 2030),
353+ (11, 2041),
354+ (12, 4088),
355+ (13, 8189),
356+ (12, 4093),
357+ (11, 2033),
358+ (10, 1000),
359+ (9, 488),
360+ (8, 240),
361+ (9, 492),
362+ (10, 1006),
363+ (11, 2034),
364+ (12, 4090),
365+ (12, 4084),
366+ (10, 1007),
367+ (9, 498),
368+ (8, 232),
369+ (7, 112),
370+ (8, 236),
371+ (9, 496),
372+ (10, 1002),
373+ (11, 2035),
374+ (11, 2027),
375+ (9, 491),
376+ (8, 234),
377+ (5, 26),
378+ (4, 8),
379+ (5, 25),
380+ (8, 238),
381+ (9, 495),
382+ (11, 2029),
383+ (10, 1008),
384+ (8, 242),
385+ (7, 115),
386+ (4, 11),
387+ (1, 0),
388+ (4, 10),
389+ (7, 113),
390+ (8, 243),
391+ (11, 2025),
392+ (11, 2031),
393+ (9, 494),
394+ (8, 239),
395+ (5, 24),
396+ (4, 9),
397+ (5, 27),
398+ (8, 235),
399+ (9, 489),
400+ (11, 2028),
401+ (11, 2038),
402+ (10, 1003),
403+ (9, 499),
404+ (8, 237),
405+ (7, 114),
406+ (8, 233),
407+ (9, 497),
408+ (10, 1005),
409+ (11, 2039),
410+ (12, 4086),
411+ (11, 2032),
412+ (10, 1001),
413+ (9, 493),
414+ (8, 241),
415+ (9, 490),
416+ (10, 1004),
417+ (11, 2040),
418+ (12, 4089),
419+ (13, 8188),
420+ (12, 4092),
421+ (12, 4085),
422+ (11, 2026),
423+ (10, 1011),
424+ (10, 1010),
425+ (11, 2037),
426+ (12, 4091),
427+ (13, 8190),
428+];
429+/// Codebook 6: dim 2, lav 4, signed.
430+static HCB6: [(u8, u32); 81] = [
431+ (11, 2046),
432+ (10, 1021),
433+ (9, 497),
434+ (9, 491),
435+ (9, 500),
436+ (9, 490),
437+ (9, 496),
438+ (10, 1020),
439+ (11, 2045),
440+ (10, 1014),
441+ (9, 485),
442+ (8, 234),
443+ (7, 108),
444+ (7, 113),
445+ (7, 104),
446+ (8, 240),
447+ (9, 486),
448+ (10, 1015),
449+ (9, 499),
450+ (8, 239),
451+ (6, 50),
452+ (6, 39),
453+ (6, 40),
454+ (6, 38),
455+ (6, 49),
456+ (8, 235),
457+ (9, 503),
458+ (9, 488),
459+ (7, 111),
460+ (6, 46),
461+ (4, 8),
462+ (4, 4),
463+ (4, 6),
464+ (6, 41),
465+ (7, 107),
466+ (9, 494),
467+ (9, 495),
468+ (7, 114),
469+ (6, 45),
470+ (4, 2),
471+ (4, 0),
472+ (4, 3),
473+ (6, 47),
474+ (7, 115),
475+ (9, 506),
476+ (9, 487),
477+ (7, 110),
478+ (6, 43),
479+ (4, 7),
480+ (4, 1),
481+ (4, 5),
482+ (6, 44),
483+ (7, 109),
484+ (9, 492),
485+ (9, 505),
486+ (8, 238),
487+ (6, 48),
488+ (6, 36),
489+ (6, 42),
490+ (6, 37),
491+ (6, 51),
492+ (8, 236),
493+ (9, 498),
494+ (10, 1016),
495+ (9, 484),
496+ (8, 237),
497+ (7, 106),
498+ (7, 112),
499+ (7, 105),
500+ (7, 116),
501+ (8, 241),
502+ (10, 1018),
503+ (11, 2047),
504+ (10, 1017),
505+ (9, 502),
506+ (9, 493),
507+ (9, 504),
508+ (9, 489),
509+ (9, 501),
510+ (10, 1019),
511+ (11, 2044),
512+];
513+/// Codebook 7: dim 2, lav 7, unsigned.
514+static HCB7: [(u8, u32); 64] = [
515+ (1, 0),
516+ (3, 5),
517+ (6, 55),
518+ (7, 116),
519+ (8, 242),
520+ (9, 491),
521+ (10, 1005),
522+ (11, 2039),
523+ (3, 4),
524+ (4, 12),
525+ (6, 53),
526+ (7, 113),
527+ (8, 236),
528+ (8, 238),
529+ (9, 494),
530+ (9, 501),
531+ (6, 54),
532+ (6, 52),
533+ (7, 114),
534+ (8, 234),
535+ (8, 241),
536+ (9, 489),
537+ (9, 499),
538+ (10, 1013),
539+ (7, 115),
540+ (7, 112),
541+ (8, 235),
542+ (8, 240),
543+ (9, 497),
544+ (9, 496),
545+ (10, 1004),
546+ (10, 1018),
547+ (8, 243),
548+ (8, 237),
549+ (9, 488),
550+ (9, 495),
551+ (10, 1007),
552+ (10, 1009),
553+ (10, 1017),
554+ (11, 2043),
555+ (9, 493),
556+ (8, 239),
557+ (9, 490),
558+ (9, 498),
559+ (10, 1011),
560+ (10, 1016),
561+ (11, 2041),
562+ (11, 2044),
563+ (10, 1006),
564+ (9, 492),
565+ (9, 500),
566+ (10, 1012),
567+ (10, 1015),
568+ (11, 2040),
569+ (12, 4093),
570+ (12, 4094),
571+ (11, 2038),
572+ (10, 1008),
573+ (10, 1010),
574+ (10, 1014),
575+ (11, 2042),
576+ (11, 2045),
577+ (12, 4092),
578+ (12, 4095),
579+];
580+/// Codebook 8: dim 2, lav 7, unsigned.
581+static HCB8: [(u8, u32); 64] = [
582+ (5, 14),
583+ (4, 5),
584+ (5, 16),
585+ (6, 48),
586+ (7, 111),
587+ (8, 241),
588+ (9, 506),
589+ (10, 1022),
590+ (4, 3),
591+ (3, 0),
592+ (4, 4),
593+ (5, 18),
594+ (6, 44),
595+ (7, 106),
596+ (7, 117),
597+ (8, 248),
598+ (5, 15),
599+ (4, 2),
600+ (4, 6),
601+ (5, 20),
602+ (6, 46),
603+ (7, 105),
604+ (7, 114),
605+ (8, 245),
606+ (6, 47),
607+ (5, 17),
608+ (5, 19),
609+ (6, 42),
610+ (6, 50),
611+ (7, 108),
612+ (8, 236),
613+ (8, 250),
614+ (7, 113),
615+ (6, 43),
616+ (6, 45),
617+ (6, 49),
618+ (7, 109),
619+ (7, 112),
620+ (8, 242),
621+ (9, 505),
622+ (8, 239),
623+ (7, 104),
624+ (6, 51),
625+ (7, 107),
626+ (7, 110),
627+ (8, 238),
628+ (8, 249),
629+ (10, 1020),
630+ (9, 504),
631+ (7, 116),
632+ (7, 115),
633+ (8, 237),
634+ (8, 240),
635+ (8, 246),
636+ (9, 502),
637+ (9, 509),
638+ (10, 1021),
639+ (8, 243),
640+ (8, 244),
641+ (8, 247),
642+ (9, 503),
643+ (9, 507),
644+ (9, 508),
645+ (10, 1023),
646+];
647+/// Codebook 9: dim 2, lav 12, unsigned.
648+static HCB9: [(u8, u32); 169] = [
649+ (1, 0),
650+ (3, 5),
651+ (6, 55),
652+ (8, 231),
653+ (9, 478),
654+ (10, 974),
655+ (10, 985),
656+ (11, 1992),
657+ (11, 1997),
658+ (12, 4040),
659+ (12, 4061),
660+ (13, 8164),
661+ (13, 8172),
662+ (3, 4),
663+ (4, 12),
664+ (6, 53),
665+ (7, 114),
666+ (8, 234),
667+ (8, 237),
668+ (9, 482),
669+ (10, 977),
670+ (10, 979),
671+ (10, 992),
672+ (11, 2008),
673+ (12, 4047),
674+ (12, 4053),
675+ (6, 54),
676+ (6, 52),
677+ (7, 113),
678+ (8, 232),
679+ (8, 236),
680+ (9, 481),
681+ (10, 975),
682+ (10, 989),
683+ (10, 987),
684+ (11, 2000),
685+ (12, 4039),
686+ (12, 4052),
687+ (12, 4068),
688+ (8, 230),
689+ (7, 112),
690+ (8, 233),
691+ (9, 477),
692+ (9, 483),
693+ (10, 978),
694+ (10, 988),
695+ (11, 1996),
696+ (11, 1994),
697+ (11, 2014),
698+ (12, 4056),
699+ (12, 4074),
700+ (13, 8155),
701+ (9, 479),
702+ (8, 235),
703+ (9, 476),
704+ (9, 486),
705+ (10, 981),
706+ (10, 990),
707+ (11, 1995),
708+ (11, 2013),
709+ (11, 2012),
710+ (12, 4045),
711+ (12, 4066),
712+ (12, 4071),
713+ (13, 8161),
714+ (10, 976),
715+ (9, 480),
716+ (9, 484),
717+ (10, 982),
718+ (11, 1989),
719+ (11, 2001),
720+ (11, 2011),
721+ (12, 4050),
722+ (11, 2016),
723+ (12, 4057),
724+ (12, 4075),
725+ (13, 8163),
726+ (13, 8169),
727+ (11, 1988),
728+ (9, 485),
729+ (10, 983),
730+ (11, 1990),
731+ (11, 1999),
732+ (11, 2010),
733+ (12, 4043),
734+ (12, 4058),
735+ (12, 4067),
736+ (12, 4073),
737+ (13, 8166),
738+ (13, 8179),
739+ (13, 8183),
740+ (11, 2003),
741+ (10, 984),
742+ (10, 993),
743+ (11, 2004),
744+ (11, 2009),
745+ (12, 4051),
746+ (12, 4062),
747+ (13, 8157),
748+ (13, 8153),
749+ (13, 8162),
750+ (13, 8170),
751+ (13, 8177),
752+ (13, 8182),
753+ (11, 2002),
754+ (10, 980),
755+ (10, 986),
756+ (11, 1991),
757+ (11, 2007),
758+ (11, 2018),
759+ (12, 4046),
760+ (12, 4059),
761+ (13, 8152),
762+ (13, 8174),
763+ (14, 16368),
764+ (13, 8180),
765+ (14, 16370),
766+ (11, 2017),
767+ (10, 991),
768+ (11, 1993),
769+ (11, 2006),
770+ (12, 4042),
771+ (12, 4048),
772+ (12, 4069),
773+ (12, 4070),
774+ (13, 8171),
775+ (13, 8175),
776+ (14, 16371),
777+ (14, 16372),
778+ (14, 16373),
779+ (12, 4064),
780+ (11, 1998),
781+ (11, 2005),
782+ (12, 4038),
783+ (12, 4049),
784+ (12, 4065),
785+ (13, 8160),
786+ (13, 8168),
787+ (13, 8176),
788+ (14, 16369),
789+ (14, 16376),
790+ (14, 16374),
791+ (15, 32764),
792+ (12, 4072),
793+ (11, 2015),
794+ (12, 4041),
795+ (12, 4055),
796+ (12, 4060),
797+ (13, 8156),
798+ (13, 8159),
799+ (13, 8173),
800+ (13, 8181),
801+ (14, 16377),
802+ (14, 16379),
803+ (15, 32765),
804+ (15, 32766),
805+ (13, 8167),
806+ (12, 4044),
807+ (12, 4054),
808+ (12, 4063),
809+ (13, 8158),
810+ (13, 8154),
811+ (13, 8165),
812+ (13, 8178),
813+ (14, 16378),
814+ (14, 16375),
815+ (14, 16380),
816+ (14, 16381),
817+ (15, 32767),
818+];
819+/// Codebook 10: dim 2, lav 12, unsigned.
820+static HCB10: [(u8, u32); 169] = [
821+ (6, 34),
822+ (5, 8),
823+ (6, 29),
824+ (6, 38),
825+ (7, 95),
826+ (8, 211),
827+ (9, 463),
828+ (10, 976),
829+ (10, 983),
830+ (10, 1005),
831+ (11, 2032),
832+ (11, 2038),
833+ (12, 4093),
834+ (5, 7),
835+ (4, 0),
836+ (4, 1),
837+ (5, 9),
838+ (6, 32),
839+ (7, 84),
840+ (7, 96),
841+ (8, 213),
842+ (8, 220),
843+ (9, 468),
844+ (10, 973),
845+ (10, 990),
846+ (11, 2023),
847+ (6, 28),
848+ (4, 2),
849+ (5, 6),
850+ (5, 12),
851+ (6, 30),
852+ (6, 40),
853+ (7, 91),
854+ (8, 205),
855+ (8, 217),
856+ (9, 462),
857+ (9, 476),
858+ (10, 985),
859+ (10, 1009),
860+ (6, 37),
861+ (5, 11),
862+ (5, 10),
863+ (5, 13),
864+ (6, 36),
865+ (7, 87),
866+ (7, 97),
867+ (8, 204),
868+ (8, 221),
869+ (9, 460),
870+ (9, 478),
871+ (10, 979),
872+ (10, 999),
873+ (7, 93),
874+ (6, 33),
875+ (6, 31),
876+ (6, 35),
877+ (6, 39),
878+ (7, 89),
879+ (7, 100),
880+ (8, 216),
881+ (8, 223),
882+ (9, 466),
883+ (9, 482),
884+ (10, 989),
885+ (10, 1006),
886+ (8, 209),
887+ (7, 85),
888+ (6, 41),
889+ (7, 86),
890+ (7, 88),
891+ (7, 98),
892+ (8, 206),
893+ (8, 224),
894+ (8, 226),
895+ (9, 474),
896+ (10, 980),
897+ (10, 995),
898+ (11, 2027),
899+ (9, 457),
900+ (7, 94),
901+ (7, 90),
902+ (7, 92),
903+ (7, 99),
904+ (8, 202),
905+ (8, 218),
906+ (9, 455),
907+ (9, 458),
908+ (9, 480),
909+ (10, 987),
910+ (10, 1000),
911+ (11, 2028),
912+ (9, 483),
913+ (8, 210),
914+ (8, 203),
915+ (8, 208),
916+ (8, 215),
917+ (8, 219),
918+ (9, 454),
919+ (9, 469),
920+ (9, 472),
921+ (10, 970),
922+ (10, 986),
923+ (11, 2026),
924+ (11, 2033),
925+ (9, 481),
926+ (8, 212),
927+ (8, 207),
928+ (8, 214),
929+ (8, 222),
930+ (8, 225),
931+ (9, 464),
932+ (9, 470),
933+ (10, 977),
934+ (10, 981),
935+ (10, 1010),
936+ (11, 2030),
937+ (11, 2043),
938+ (10, 1001),
939+ (9, 461),
940+ (9, 456),
941+ (9, 459),
942+ (9, 465),
943+ (9, 471),
944+ (9, 479),
945+ (10, 975),
946+ (10, 992),
947+ (10, 1007),
948+ (11, 2022),
949+ (11, 2040),
950+ (12, 4090),
951+ (10, 1003),
952+ (9, 477),
953+ (9, 467),
954+ (9, 473),
955+ (9, 475),
956+ (10, 978),
957+ (10, 972),
958+ (10, 988),
959+ (10, 1002),
960+ (11, 2029),
961+ (11, 2035),
962+ (11, 2041),
963+ (12, 4089),
964+ (11, 2034),
965+ (10, 974),
966+ (9, 484),
967+ (10, 971),
968+ (10, 984),
969+ (10, 982),
970+ (10, 994),
971+ (10, 997),
972+ (11, 2024),
973+ (11, 2036),
974+ (11, 2037),
975+ (11, 2039),
976+ (12, 4091),
977+ (11, 2042),
978+ (10, 1004),
979+ (10, 991),
980+ (10, 993),
981+ (10, 996),
982+ (10, 998),
983+ (10, 1008),
984+ (11, 2025),
985+ (11, 2031),
986+ (12, 4088),
987+ (12, 4094),
988+ (12, 4092),
989+ (12, 4095),
990+];
991+/// Codebook 11: dim 2, lav 16, unsigned, escape.
992+static HCB11: [(u8, u32); 289] = [
993+ (4, 0),
994+ (5, 6),
995+ (6, 25),
996+ (7, 61),
997+ (8, 156),
998+ (8, 198),
999+ (9, 423),
1000+ (10, 912),
1001+ (10, 962),
1002+ (10, 991),
1003+ (11, 2022),
1004+ (11, 2035),
1005+ (12, 4091),
1006+ (11, 2028),
1007+ (12, 4090),
1008+ (12, 4094),
1009+ (10, 910),
1010+ (5, 5),
1011+ (4, 1),
1012+ (5, 8),
1013+ (6, 20),
1014+ (7, 55),
1015+ (7, 66),
1016+ (8, 146),
1017+ (8, 175),
1018+ (9, 401),
1019+ (9, 421),
1020+ (9, 437),
1021+ (10, 926),
1022+ (10, 960),
1023+ (10, 930),
1024+ (10, 973),
1025+ (11, 2006),
1026+ (8, 174),
1027+ (6, 23),
1028+ (5, 7),
1029+ (5, 9),
1030+ (6, 24),
1031+ (7, 57),
1032+ (7, 64),
1033+ (8, 142),
1034+ (8, 163),
1035+ (8, 184),
1036+ (9, 409),
1037+ (9, 428),
1038+ (9, 449),
1039+ (10, 945),
1040+ (10, 918),
1041+ (10, 958),
1042+ (10, 970),
1043+ (8, 157),
1044+ (7, 60),
1045+ (6, 21),
1046+ (6, 22),
1047+ (6, 26),
1048+ (7, 59),
1049+ (7, 68),
1050+ (8, 145),
1051+ (8, 165),
1052+ (8, 190),
1053+ (9, 406),
1054+ (9, 430),
1055+ (9, 441),
1056+ (10, 929),
1057+ (10, 913),
1058+ (10, 933),
1059+ (10, 981),
1060+ (8, 148),
1061+ (8, 154),
1062+ (7, 54),
1063+ (7, 56),
1064+ (7, 58),
1065+ (7, 65),
1066+ (8, 140),
1067+ (8, 155),
1068+ (8, 176),
1069+ (8, 195),
1070+ (9, 414),
1071+ (9, 427),
1072+ (9, 444),
1073+ (10, 927),
1074+ (10, 911),
1075+ (10, 937),
1076+ (10, 975),
1077+ (8, 147),
1078+ (8, 191),
1079+ (7, 62),
1080+ (7, 63),
1081+ (7, 67),
1082+ (7, 69),
1083+ (8, 158),
1084+ (8, 167),
1085+ (8, 185),
1086+ (9, 404),
1087+ (9, 418),
1088+ (9, 442),
1089+ (9, 451),
1090+ (10, 934),
1091+ (10, 935),
1092+ (10, 955),
1093+ (10, 980),
1094+ (8, 159),
1095+ (9, 416),
1096+ (8, 143),
1097+ (8, 141),
1098+ (8, 144),
1099+ (8, 152),
1100+ (8, 166),
1101+ (8, 182),
1102+ (8, 196),
1103+ (9, 415),
1104+ (9, 431),
1105+ (9, 447),
1106+ (10, 921),
1107+ (10, 959),
1108+ (10, 948),
1109+ (10, 969),
1110+ (10, 999),
1111+ (8, 168),
1112+ (9, 438),
1113+ (8, 171),
1114+ (8, 164),
1115+ (8, 170),
1116+ (8, 178),
1117+ (8, 194),
1118+ (8, 197),
1119+ (9, 408),
1120+ (9, 420),
1121+ (9, 440),
1122+ (10, 908),
1123+ (10, 932),
1124+ (10, 964),
1125+ (10, 966),
1126+ (10, 989),
1127+ (10, 1000),
1128+ (8, 173),
1129+ (10, 943),
1130+ (9, 402),
1131+ (8, 189),
1132+ (8, 188),
1133+ (9, 398),
1134+ (9, 407),
1135+ (9, 410),
1136+ (9, 419),
1137+ (9, 433),
1138+ (10, 909),
1139+ (10, 920),
1140+ (10, 951),
1141+ (10, 979),
1142+ (10, 977),
1143+ (10, 987),
1144+ (11, 2013),
1145+ (8, 180),
1146+ (10, 990),
1147+ (9, 425),
1148+ (9, 411),
1149+ (9, 412),
1150+ (9, 417),
1151+ (9, 426),
1152+ (9, 429),
1153+ (9, 435),
1154+ (10, 907),
1155+ (10, 946),
1156+ (10, 952),
1157+ (10, 974),
1158+ (10, 993),
1159+ (10, 992),
1160+ (11, 2002),
1161+ (11, 2021),
1162+ (8, 183),
1163+ (11, 2019),
1164+ (9, 443),
1165+ (9, 424),
1166+ (9, 422),
1167+ (9, 432),
1168+ (9, 434),
1169+ (9, 439),
1170+ (10, 923),
1171+ (10, 922),
1172+ (10, 954),
1173+ (10, 949),
1174+ (10, 982),
1175+ (11, 2007),
1176+ (10, 996),
1177+ (11, 2008),
1178+ (11, 2026),
1179+ (8, 186),
1180+ (11, 2024),
1181+ (10, 928),
1182+ (9, 445),
1183+ (9, 436),
1184+ (10, 906),
1185+ (9, 452),
1186+ (10, 914),
1187+ (10, 938),
1188+ (10, 944),
1189+ (10, 956),
1190+ (10, 983),
1191+ (11, 2004),
1192+ (11, 2012),
1193+ (11, 2011),
1194+ (11, 2005),
1195+ (11, 2032),
1196+ (8, 193),
1197+ (11, 2043),
1198+ (10, 968),
1199+ (10, 931),
1200+ (10, 917),
1201+ (10, 925),
1202+ (10, 940),
1203+ (10, 942),
1204+ (10, 965),
1205+ (10, 984),
1206+ (10, 994),
1207+ (10, 998),
1208+ (11, 2020),
1209+ (11, 2023),
1210+ (11, 2016),
1211+ (11, 2025),
1212+ (11, 2039),
1213+ (9, 400),
1214+ (11, 2034),
1215+ (10, 915),
1216+ (9, 446),
1217+ (9, 448),
1218+ (10, 916),
1219+ (10, 919),
1220+ (10, 941),
1221+ (10, 963),
1222+ (10, 961),
1223+ (10, 978),
1224+ (11, 2010),
1225+ (11, 2009),
1226+ (11, 2015),
1227+ (11, 2027),
1228+ (11, 2036),
1229+ (11, 2042),
1230+ (9, 405),
1231+ (11, 2040),
1232+ (10, 957),
1233+ (10, 924),
1234+ (10, 939),
1235+ (10, 936),
1236+ (10, 947),
1237+ (10, 953),
1238+ (10, 976),
1239+ (10, 995),
1240+ (10, 997),
1241+ (11, 2018),
1242+ (11, 2014),
1243+ (11, 2029),
1244+ (11, 2033),
1245+ (11, 2041),
1246+ (11, 2044),
1247+ (9, 403),
1248+ (12, 4093),
1249+ (10, 988),
1250+ (10, 950),
1251+ (10, 967),
1252+ (10, 972),
1253+ (10, 971),
1254+ (10, 985),
1255+ (10, 986),
1256+ (11, 2003),
1257+ (11, 2017),
1258+ (11, 2030),
1259+ (11, 2031),
1260+ (11, 2037),
1261+ (11, 2038),
1262+ (12, 4092),
1263+ (12, 4095),
1264+ (9, 413),
1265+ (9, 450),
1266+ (8, 181),
1267+ (8, 161),
1268+ (8, 150),
1269+ (8, 151),
1270+ (8, 149),
1271+ (8, 153),
1272+ (8, 160),
1273+ (8, 162),
1274+ (8, 172),
1275+ (8, 169),
1276+ (8, 177),
1277+ (8, 179),
1278+ (8, 187),
1279+ (8, 192),
1280+ (9, 399),
1281+ (5, 4),
1282+];
1283+/// Scalefactor codebook: index is the coded value, delta = index - 60.
1284+static HCB_SF: [(u8, u32); 121] = [
1285+ (18, 262120),
1286+ (18, 262118),
1287+ (18, 262119),
1288+ (18, 262117),
1289+ (19, 524277),
1290+ (19, 524273),
1291+ (19, 524269),
1292+ (19, 524278),
1293+ (19, 524270),
1294+ (19, 524271),
1295+ (19, 524272),
1296+ (19, 524284),
1297+ (19, 524285),
1298+ (19, 524287),
1299+ (19, 524286),
1300+ (19, 524279),
1301+ (19, 524280),
1302+ (19, 524283),
1303+ (19, 524281),
1304+ (18, 262116),
1305+ (19, 524282),
1306+ (18, 262115),
1307+ (17, 131055),
1308+ (17, 131056),
1309+ (16, 65525),
1310+ (17, 131054),
1311+ (16, 65522),
1312+ (16, 65523),
1313+ (16, 65524),
1314+ (16, 65521),
1315+ (15, 32758),
1316+ (15, 32759),
1317+ (14, 16377),
1318+ (14, 16373),
1319+ (14, 16375),
1320+ (14, 16371),
1321+ (14, 16374),
1322+ (14, 16370),
1323+ (13, 8183),
1324+ (13, 8181),
1325+ (12, 4089),
1326+ (12, 4087),
1327+ (12, 4086),
1328+ (11, 2041),
1329+ (12, 4084),
1330+ (11, 2040),
1331+ (10, 1017),
1332+ (10, 1015),
1333+ (10, 1013),
1334+ (9, 504),
1335+ (9, 503),
1336+ (8, 250),
1337+ (8, 248),
1338+ (8, 246),
1339+ (7, 121),
1340+ (6, 58),
1341+ (6, 56),
1342+ (5, 26),
1343+ (4, 11),
1344+ (3, 4),
1345+ (1, 0),
1346+ (4, 10),
1347+ (4, 12),
1348+ (5, 27),
1349+ (6, 57),
1350+ (6, 59),
1351+ (7, 120),
1352+ (7, 122),
1353+ (8, 247),
1354+ (8, 249),
1355+ (9, 502),
1356+ (9, 505),
1357+ (10, 1012),
1358+ (10, 1014),
1359+ (10, 1016),
1360+ (11, 2037),
1361+ (11, 2036),
1362+ (11, 2038),
1363+ (11, 2039),
1364+ (12, 4085),
1365+ (12, 4088),
1366+ (13, 8180),
1367+ (13, 8182),
1368+ (13, 8184),
1369+ (14, 16376),
1370+ (14, 16372),
1371+ (16, 65520),
1372+ (15, 32756),
1373+ (16, 65526),
1374+ (15, 32757),
1375+ (18, 262114),
1376+ (19, 524249),
1377+ (19, 524250),
1378+ (19, 524251),
1379+ (19, 524252),
1380+ (19, 524253),
1381+ (19, 524254),
1382+ (19, 524248),
1383+ (19, 524242),
1384+ (19, 524243),
1385+ (19, 524244),
1386+ (19, 524245),
1387+ (19, 524246),
1388+ (19, 524274),
1389+ (19, 524255),
1390+ (19, 524263),
1391+ (19, 524264),
1392+ (19, 524265),
1393+ (19, 524266),
1394+ (19, 524267),
1395+ (19, 524262),
1396+ (19, 524256),
1397+ (19, 524257),
1398+ (19, 524258),
1399+ (19, 524259),
1400+ (19, 524260),
1401+ (19, 524261),
1402+ (19, 524247),
1403+ (19, 524268),
1404+ (19, 524276),
1405+ (19, 524275),
1406+];
1407+/// Scalefactor-band offsets for 1024-line windows, by samplingFrequencyIndex.
1408+pub static SWB_LONG: [&[u16]; 12] = [
1409+ &[
1410+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132,
1411+ 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960,
1412+ 1024,
1413+ ],
1414+ &[
1415+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132,
1416+ 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960,
1417+ 1024,
1418+ ],
1419+ &[
1420+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, 112, 124,
1421+ 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704,
1422+ 744, 784, 824, 864, 904, 944, 984, 1024,
1423+ ],
1424+ &[
1425+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144,
1426+ 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
1427+ 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
1428+ ],
1429+ &[
1430+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144,
1431+ 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
1432+ 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
1433+ ],
1434+ &[
1435+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144,
1436+ 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
1437+ 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
1438+ ],
1439+ &[
1440+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124,
1441+ 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
1442+ 600, 652, 704, 768, 832, 896, 960, 1024,
1443+ ],
1444+ &[
1445+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124,
1446+ 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
1447+ 600, 652, 704, 768, 832, 896, 960, 1024,
1448+ ],
1449+ &[
1450+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196,
1451+ 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716,
1452+ 772, 832, 896, 960, 1024,
1453+ ],
1454+ &[
1455+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196,
1456+ 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716,
1457+ 772, 832, 896, 960, 1024,
1458+ ],
1459+ &[
1460+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196,
1461+ 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716,
1462+ 772, 832, 896, 960, 1024,
1463+ ],
1464+ &[
1465+ 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
1466+ 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820,
1467+ 880, 944, 1024,
1468+ ],
1469+];
1470+/// Scalefactor-band offsets for 128-line windows, by samplingFrequencyIndex.
1471+pub static SWB_SHORT: [&[u16]; 12] = [
1472+ &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128],
1473+ &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128],
1474+ &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128],
1475+ &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128],
1476+ &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128],
1477+ &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128],
1478+ &[
1479+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
1480+ ],
1481+ &[
1482+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
1483+ ],
1484+ &[
1485+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
1486+ ],
1487+ &[
1488+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
1489+ ],
1490+ &[
1491+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
1492+ ],
1493+ &[
1494+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
1495+ ],
1496+];
1497+
1498+/// One spectral codebook's shape.
1499+#[derive(Clone, Copy, Debug)]
1500+pub struct Codebook {
1501+ /// Coefficients per Huffman codeword (2 or 4).
1502+ pub dim: u8,
1503+ /// Largest absolute value the codebook can carry.
1504+ pub lav: u8,
1505+ /// True when magnitudes are coded and each non-zero one takes a sign bit.
1506+ pub unsigned: bool,
1507+ /// True for codebook 11, whose magnitude 16 opens an escape sequence.
1508+ pub esc: bool,
1509+ /// `(length, code)` by tuple index, most-significant bit first.
1510+ pub codes: &'static [(u8, u32)],
1511+}
1512+
1513+/// The eleven spectral codebooks, indexed by `sect_cb - 1`.
1514+pub static CODEBOOKS: [Codebook; 11] = [
1515+ Codebook {
1516+ dim: 4,
1517+ lav: 1,
1518+ unsigned: false,
1519+ esc: false,
1520+ codes: &HCB1,
1521+ },
1522+ Codebook {
1523+ dim: 4,
1524+ lav: 1,
1525+ unsigned: false,
1526+ esc: false,
1527+ codes: &HCB2,
1528+ },
1529+ Codebook {
1530+ dim: 4,
1531+ lav: 2,
1532+ unsigned: true,
1533+ esc: false,
1534+ codes: &HCB3,
1535+ },
1536+ Codebook {
1537+ dim: 4,
1538+ lav: 2,
1539+ unsigned: true,
1540+ esc: false,
1541+ codes: &HCB4,
1542+ },
1543+ Codebook {
1544+ dim: 2,
1545+ lav: 4,
1546+ unsigned: false,
1547+ esc: false,
1548+ codes: &HCB5,
1549+ },
1550+ Codebook {
1551+ dim: 2,
1552+ lav: 4,
1553+ unsigned: false,
1554+ esc: false,
1555+ codes: &HCB6,
1556+ },
1557+ Codebook {
1558+ dim: 2,
1559+ lav: 7,
1560+ unsigned: true,
1561+ esc: false,
1562+ codes: &HCB7,
1563+ },
1564+ Codebook {
1565+ dim: 2,
1566+ lav: 7,
1567+ unsigned: true,
1568+ esc: false,
1569+ codes: &HCB8,
1570+ },
1571+ Codebook {
1572+ dim: 2,
1573+ lav: 12,
1574+ unsigned: true,
1575+ esc: false,
1576+ codes: &HCB9,
1577+ },
1578+ Codebook {
1579+ dim: 2,
1580+ lav: 12,
1581+ unsigned: true,
1582+ esc: false,
1583+ codes: &HCB10,
1584+ },
1585+ Codebook {
1586+ dim: 2,
1587+ lav: 16,
1588+ unsigned: true,
1589+ esc: true,
1590+ codes: &HCB11,
1591+ },
1592+];
1593+
1594+/// The scalefactor codebook, as a `Codebook`-shaped table of `(length, code)`.
1595+pub static SCALEFACTOR_CODES: &[(u8, u32)] = &HCB_SF;
1596+
1597+/// Sampling frequencies by `samplingFrequencyIndex` (ISO 14496-3 tbl 1.18).
1598+pub static SAMPLE_RATES: [u32; 13] = [
1599+ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
1600+];
1601+
1602+/// Highest scalefactor band a TNS filter may touch (§4.6.9.1), by
1603+/// samplingFrequencyIndex, for 1024-line windows. Derived the same way as the
1604+/// codebooks: sweeping `max_sfb` against a reference decode and watching where
1605+/// the filter stops being applied.
1606+pub static TNS_MAX_BANDS_LONG: [usize; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39];
1607+
1608+/// The same limit for 128-line windows.
1609+pub static TNS_MAX_BANDS_SHORT: [usize; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14];
crates/ec-aac/tests/oracle.rsadded+458 -0
@@ -0,0 +1,458 @@
1+//! Decoder and encoder against ffmpeg, on the generated fixtures and on the
2+//! real library. Every test that needs a fixture or ffmpeg skips loudly when it
3+//! is absent rather than passing quietly.
4+
5+use std::path::{Path, PathBuf};
6+use std::process::Command;
7+
8+use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig};
9+
10+fn fixtures() -> PathBuf {
11+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
12+}
13+
14+fn have_ffmpeg() -> bool {
15+ Command::new("ffmpeg")
16+ .arg("-version")
17+ .output()
18+ .map(|o| o.status.success())
19+ .unwrap_or(false)
20+}
21+
22+/// ffmpeg's decode of a file, as planar-by-channel `f32`.
23+fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
24+ let out = Command::new("ffmpeg")
25+ .args(["-v", "error", "-i"])
26+ .arg(path)
27+ .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
28+ .output()
29+ .expect("ffmpeg runs");
30+ assert!(
31+ out.status.success(),
32+ "ffmpeg decode failed: {}",
33+ String::from_utf8_lossy(&out.stderr)
34+ );
35+ deinterleave(&bytes_to_f32(&out.stdout), channels)
36+}
37+
38+fn bytes_to_f32(bytes: &[u8]) -> Vec<f32> {
39+ bytes
40+ .chunks_exact(4)
41+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
42+ .collect()
43+}
44+
45+fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
46+ let mut out = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
47+ for (i, &v) in samples.iter().enumerate() {
48+ out[i % channels].push(v);
49+ }
50+ out
51+}
52+
53+/// Our decode of an ADTS file, as planar-by-channel `f32`.
54+fn our_decode(path: &Path) -> (Vec<Vec<f32>>, u32) {
55+ let data = std::fs::read(path).expect("fixture readable");
56+ let mut decoder = AacDecoder::new();
57+ let mut planes: Vec<Vec<f32>> = Vec::new();
58+ let mut rate = 0;
59+ let mut at = 0usize;
60+ while at + 7 <= data.len() {
61+ let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
62+ let end = (at + header.frame_length).min(data.len());
63+ let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
64+ rate = frame.sample_rate;
65+ let ch = usize::from(frame.channels);
66+ if planes.is_empty() {
67+ planes = vec![Vec::new(); ch];
68+ }
69+ for (i, v) in frame.samples.iter().enumerate() {
70+ planes[i % ch].push(*v);
71+ }
72+ at = end;
73+ }
74+ (planes, rate)
75+}
76+
77+/// Pearson correlation over the overlap of two channels.
78+fn correlation(a: &[f32], b: &[f32]) -> f64 {
79+ let n = a.len().min(b.len());
80+ assert!(n > 1024, "not enough overlap to compare: {n} samples");
81+ let (a, b) = (&a[..n], &b[..n]);
82+ let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
83+ let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
84+ let mut num = 0.0;
85+ let mut da = 0.0;
86+ let mut db = 0.0;
87+ for i in 0..n {
88+ let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
89+ num += x * y;
90+ da += x * x;
91+ db += y * y;
92+ }
93+ if da == 0.0 || db == 0.0 {
94+ return if da == db { 1.0 } else { 0.0 };
95+ }
96+ num / (da * db).sqrt()
97+}
98+
99+fn compare(path: &Path) -> Vec<f64> {
100+ let (ours, _rate) = our_decode(path);
101+ assert!(!ours.is_empty(), "no channels decoded from {path:?}");
102+ let theirs = ffmpeg_decode(path, ours.len());
103+ ours.iter()
104+ .zip(&theirs)
105+ .map(|(a, b)| correlation(a, b))
106+ .collect()
107+}
108+
109+#[test]
110+fn adts_fixtures_match_ffmpeg_per_channel() {
111+ if !have_ffmpeg() {
112+ eprintln!("SKIP: ffmpeg not on PATH");
113+ return;
114+ }
115+ let dir = fixtures().join("audio");
116+ let mut checked = 0;
117+ for name in [
118+ "aac-adts-mono-44100.aac",
119+ "aac-adts-mono-48000.aac",
120+ "aac-adts-stereo-44100.aac",
121+ "aac-adts-stereo-48000.aac",
122+ "aac-adts-5.1-44100.aac",
123+ "aac-adts-5.1-48000.aac",
124+ ] {
125+ let path = dir.join(name);
126+ if !path.exists() {
127+ eprintln!("SKIP {name}: fixture missing");
128+ continue;
129+ }
130+ let corr = compare(&path);
131+ println!("{name}: {corr:?}");
132+ for (ch, c) in corr.iter().enumerate() {
133+ assert!(
134+ *c >= 0.999,
135+ "{name} channel {ch} correlation {c:.6} < 0.999"
136+ );
137+ }
138+ checked += 1;
139+ }
140+ assert!(
141+ checked > 0,
142+ "no AAC fixtures found: run scripts/gen-fixtures.sh"
143+ );
144+}
145+
146+#[test]
147+fn mp4_fixtures_match_ffmpeg_per_channel() {
148+ if !have_ffmpeg() {
149+ eprintln!("SKIP: ffmpeg not on PATH");
150+ return;
151+ }
152+ let dir = fixtures().join("audio");
153+ let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle");
154+ std::fs::create_dir_all(&tmp).expect("temp dir");
155+ let mut checked = 0;
156+ for name in [
157+ "aac-mp4-mono-48000.mp4",
158+ "aac-mp4-stereo-48000.mp4",
159+ "aac-mp4-5.1-48000.mp4",
160+ ] {
161+ let path = dir.join(name);
162+ if !path.exists() {
163+ eprintln!("SKIP {name}: fixture missing");
164+ continue;
165+ }
166+ // The mp4 side of the family is another slice; the elementary stream
167+ // comes out with a stream copy so this test stays about AAC.
168+ let adts = tmp.join(format!("{name}.aac"));
169+ let out = Command::new("ffmpeg")
170+ .args(["-v", "error", "-y", "-i"])
171+ .arg(&path)
172+ .args(["-c:a", "copy", "-f", "adts"])
173+ .arg(&adts)
174+ .output()
175+ .expect("ffmpeg runs");
176+ assert!(out.status.success(), "remux failed for {name}");
177+ let corr = compare(&adts);
178+ println!("{name}: {corr:?}");
179+ for (ch, c) in corr.iter().enumerate() {
180+ assert!(
181+ *c >= 0.999,
182+ "{name} channel {ch} correlation {c:.6} < 0.999"
183+ );
184+ }
185+ checked += 1;
186+ }
187+ assert!(checked > 0, "no AAC-in-mp4 fixtures found");
188+}
189+
190+/// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR.
191+/// Each channel carries its own tone, mapped explicitly onto the layout, so a
192+/// wrong element order shows up as the wrong tone on the wrong channel.
193+#[test]
194+fn five_one_comes_out_in_film_order() {
195+ if !have_ffmpeg() {
196+ eprintln!("SKIP: ffmpeg not on PATH");
197+ return;
198+ }
199+ let tmp = std::env::temp_dir().join("ec-aac-order");
200+ std::fs::create_dir_all(&tmp).expect("temp dir");
201+ let src = tmp.join("order.aac");
202+ // The LFE tone stays low: the reference encoder band-limits that channel,
203+ // and a 1.5 kHz tone would simply not survive the trip.
204+ let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0];
205+ let mut cmd = Command::new("ffmpeg");
206+ cmd.args(["-v", "error", "-y"]);
207+ for f in tones {
208+ cmd.args([
209+ "-f",
210+ "lavfi",
211+ "-i",
212+ &format!("sine=frequency={f}:duration=2:sample_rate=48000"),
213+ ]);
214+ }
215+ let out = cmd
216+ .args([
217+ "-filter_complex",
218+ "[0:a][1:a][2:a][3:a][4:a][5:a]join=inputs=6:channel_layout=5.1:\
219+map=0.0-FL|1.0-FR|2.0-FC|3.0-LFE|4.0-BL|5.0-BR[a]",
220+ "-map",
221+ "[a]",
222+ "-c:a",
223+ "aac",
224+ "-b:a",
225+ "320k",
226+ "-f",
227+ "adts",
228+ ])
229+ .arg(&src)
230+ .output()
231+ .expect("ffmpeg runs");
232+ assert!(
233+ out.status.success(),
234+ "tone build failed: {}",
235+ String::from_utf8_lossy(&out.stderr)
236+ );
237+ let (ours, rate) = our_decode(&src);
238+ assert_eq!(ours.len(), 6, "5.1 decodes to six channels");
239+ for (ch, plane) in ours.iter().enumerate() {
240+ let peak = dominant_frequency(plane, rate);
241+ let want = tones[ch];
242+ assert!(
243+ (peak - want).abs() < 40.0,
244+ "channel {ch} peaks at {peak:.0} Hz, expected {want:.0} Hz: \
245+ the element order was not remapped to FL, FR, FC, LFE, BL, BR"
246+ );
247+ }
248+}
249+
250+/// Crude DFT peak: enough to tell six well-separated tones apart.
251+fn dominant_frequency(samples: &[f32], rate: u32) -> f64 {
252+ let n = samples.len().min(16384);
253+ let start = samples.len() / 3;
254+ let seg = &samples[start..start + n.min(samples.len() - start)];
255+ let mut best = (0.0f64, 0.0f64);
256+ let mut f = 40.0;
257+ while f < 4000.0 {
258+ let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
259+ let (mut re, mut im) = (0.0, 0.0);
260+ for (i, &v) in seg.iter().enumerate() {
261+ re += f64::from(v) * (w * i as f64).cos();
262+ im += f64::from(v) * (w * i as f64).sin();
263+ }
264+ let mag = re * re + im * im;
265+ if mag > best.1 {
266+ best = (f, mag);
267+ }
268+ f += 5.0;
269+ }
270+ best.0
271+}
272+
273+#[test]
274+fn asc_round_trips_every_sample_rate() {
275+ for (index, rate) in ec_aac::SAMPLE_RATES.iter().enumerate() {
276+ assert_eq!(ec_aac::sf_index_for_rate(*rate), Some(index as u8));
277+ assert_eq!(ec_aac::sample_rate_for_index(index as u8), *rate);
278+ for channels in [1u16, 2, 6, 8] {
279+ let bytes = ec_aac::audio_specific_config_bytes(*rate, channels);
280+ let cfg = ec_aac::parse_audio_specific_config(&bytes).expect("asc parses");
281+ assert_eq!(cfg.sample_rate, *rate, "rate round trip at {rate} Hz");
282+ assert_eq!(cfg.channels, channels, "channels round trip at {rate} Hz");
283+ assert_eq!(cfg.object_type, ec_aac::AOT_AAC_LC);
284+ }
285+ }
286+ assert_eq!(ec_aac::sf_index_for_rate(37_000), None);
287+}
288+
289+/// A refusal is a claim: this one proves the SBR extension really is absent and
290+/// that the decoder says so instead of quietly claiming the doubled rate.
291+#[test]
292+fn sbr_is_reported_not_silently_upsampled() {
293+ // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz),
294+ // then AOT 2 for the core: 00101 0110 0010 0011 00010.
295+ let asc = [0x2Bu8, 0x11, 0x88];
296+ let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses");
297+ assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly);
298+ assert_eq!(
299+ decoder.output_sample_rate(),
300+ Some(24_000),
301+ "an HE-AAC stream must report the core rate it actually produces"
302+ );
303+ let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2))
304+ .expect("LC config parses");
305+ assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled);
306+}
307+
308+/// The incumbent encoder's per-channel correlation on these exact fixtures,
309+/// measured by running `rusty_aac` 0.5.0 as a black box through the same
310+/// ffmpeg decode (2026-08-14). This is the bar the replacement has to clear.
311+const INCUMBENT_BAR: &[(&str, usize, u32, f64)] = &[
312+ ("mono", 1, 96, 0.9846),
313+ ("stereo", 2, 128, 0.9743),
314+ ("stereo", 2, 192, 0.9864),
315+ ("5.1", 6, 384, 0.9648),
316+ ("5.1", 6, 448, 0.9611),
317+];
318+
319+fn encode_to_adts(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec<u8> {
320+ let mut enc = AacEncoder::new(AacEncoderConfig {
321+ bitrate_bps: kbps * 1000,
322+ adts: true,
323+ ..Default::default()
324+ });
325+ enc.push_pcm(pcm, channels, rate).expect("pcm accepted");
326+ enc.finish();
327+ let mut out = Vec::new();
328+ while let Ok(p) = enc.next_packet() {
329+ out.extend_from_slice(&p.data);
330+ }
331+ out
332+}
333+
334+/// Correlation at the encoder's own delay, which is one frame of lookahead.
335+fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 {
336+ [0usize, ec_aac::FRAME_LEN, 2 * ec_aac::FRAME_LEN]
337+ .into_iter()
338+ .filter(|lag| decoded.len() > *lag + 1024)
339+ .map(|lag| correlation(source, &decoded[lag..]))
340+ .fold(f64::MIN, f64::max)
341+}
342+
343+/// Our encode, through ffmpeg, against the incumbent's own numbers on the same
344+/// lossless fixtures at the same bitrates.
345+#[test]
346+fn encoder_beats_the_incumbent_bar() {
347+ if !have_ffmpeg() {
348+ eprintln!("SKIP: ffmpeg not on PATH");
349+ return;
350+ }
351+ let dir = fixtures().join("audio");
352+ let tmp = std::env::temp_dir().join("ec-aac-bar");
353+ std::fs::create_dir_all(&tmp).expect("temp dir");
354+ let mut checked = 0;
355+ for (name, channels, kbps, bar) in INCUMBENT_BAR {
356+ let src = dir.join(format!("flac-{name}-48000.flac"));
357+ if !src.exists() {
358+ eprintln!("SKIP {name}: fixture missing");
359+ continue;
360+ }
361+ let source = ffmpeg_decode(&src, *channels);
362+ let mut interleaved = Vec::with_capacity(source[0].len() * channels);
363+ for i in 0..source[0].len() {
364+ for plane in &source {
365+ interleaved.push(plane[i]);
366+ }
367+ }
368+ let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps);
369+ let path = tmp.join(format!("{name}-{kbps}k.aac"));
370+ std::fs::write(&path, &adts).expect("write");
371+ let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
372+ let ours = ffmpeg_decode(&path, *channels);
373+ let corr: Vec<f64> = source
374+ .iter()
375+ .zip(&ours)
376+ .map(|(a, b)| best_correlation(a, b))
377+ .collect();
378+ let worst = corr.iter().copied().fold(f64::MAX, f64::min);
379+ println!(
380+ "enc {name} {kbps}k: {rate:.0} kbps actual, worst channel {worst:.4} \
381+ (incumbent {bar:.4}) per-channel {corr:?}"
382+ );
383+ assert!(
384+ rate <= f64::from(*kbps) * 1.12,
385+ "{name} {kbps}k overshot its target: {rate:.0} kbps"
386+ );
387+ assert!(
388+ worst >= *bar,
389+ "{name} {kbps}k worst channel {worst:.4} is under the incumbent's {bar:.4}"
390+ );
391+ checked += 1;
392+ }
393+ assert!(checked > 0, "no lossless fixtures found");
394+}
395+
396+fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> {
397+ let frames = (f64::from(rate) * secs) as usize;
398+ let mut pcm = Vec::with_capacity(frames * channels);
399+ for i in 0..frames {
400+ let t = i as f64 / f64::from(rate);
401+ for c in 0..channels {
402+ let f = 220.0 * (c + 1) as f64;
403+ let v = (t * f * std::f64::consts::TAU).sin() * 0.35
404+ + (t * f * 2.5 * std::f64::consts::TAU).sin() * 0.15;
405+ pcm.push(v as f32);
406+ }
407+ }
408+ pcm
409+}
410+
411+#[test]
412+fn encoder_output_decodes_in_ffmpeg_without_warnings() {
413+ if !have_ffmpeg() {
414+ eprintln!("SKIP: ffmpeg not on PATH");
415+ return;
416+ }
417+ let tmp = std::env::temp_dir().join("ec-aac-enc");
418+ std::fs::create_dir_all(&tmp).expect("temp dir");
419+ for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] {
420+ let rate = 48_000;
421+ let pcm = tone_pcm(rate, usize::from(channels), 1.5);
422+ let adts = encode_to_adts(&pcm, channels, rate, kbps);
423+ assert!(!adts.is_empty(), "{channels}ch encode produced nothing");
424+ let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac"));
425+ std::fs::write(&path, &adts).expect("write");
426+ let out = Command::new("ffmpeg")
427+ .args(["-v", "warning", "-i"])
428+ .arg(&path)
429+ .args(["-f", "null", "-"])
430+ .output()
431+ .expect("ffmpeg runs");
432+ // ffmpeg says this about every ADTS file, its own included: the
433+ // container has no duration field. It is not a complaint about us.
434+ let log = String::from_utf8_lossy(&out.stderr);
435+ let log: String = log
436+ .lines()
437+ .filter(|l| !l.contains("Estimating duration from bitrate"))
438+ .collect::<Vec<_>>()
439+ .join("\n");
440+ assert!(
441+ out.status.success() && log.trim().is_empty(),
442+ "ffmpeg complained about our {channels}ch/{kbps}k ADTS:\n{log}"
443+ );
444+ // And the sound survives the trip.
445+ let theirs = ffmpeg_decode(&path, usize::from(channels));
446+ let ours = deinterleave(&pcm, usize::from(channels));
447+ for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
448+ // The encoder's own frame of lookahead delays the output by one
449+ // frame; line the two up before comparing.
450+ let corr = correlation(a, &b[ec_aac::FRAME_LEN..]);
451+ println!("enc {channels}ch {kbps}k channel {ch}: corr {corr:.4}");
452+ assert!(
453+ corr >= 0.90,
454+ "{channels}ch/{kbps}k channel {ch} correlation {corr:.4} < 0.90"
455+ );
456+ }
457+ }
458+}
shims/rusty_aac/src/lib.rsadded+233 -0
@@ -0,0 +1,233 @@
1+//! The `rusty_aac` 0.5 surface, served by `ec-aac`.
2+//!
3+//! Only what edith consumes is here, at the incumbent's signatures:
4+//! `AacDecoder::with_config_bytes` (audio.rs:1731), `AacEncoder::new` with
5+//! `AacEncoderConfig` (mux.rs:2116, export.rs:1756) and `sf_index_for_rate`
6+//! (export.rs:1678). The encoder's tool flags are kept as fields so a caller
7+//! written against the incumbent still compiles; each one names what it maps to.
8+
9+#![forbid(unsafe_code)]
10+
11+pub use ec_aac::{
12+ AdtsHeader, AudioSpecificConfig, SAMPLE_RATES, audio_specific_config_bytes, is_adts,
13+ parse_adts, parse_audio_specific_config, sample_rate_for_index, sf_index_for_rate,
14+ write_adts_header, write_audio_specific_config,
15+};
16+
17+/// The incumbent's error type: one variant per refusal reason, `Eof` included
18+/// so `while let Ok(p) = next_packet()` still terminates.
19+#[derive(Debug)]
20+pub enum Error {
21+ Eof,
22+ NeedMore,
23+ Invalid(String),
24+ Unsupported(String),
25+}
26+
27+impl std::fmt::Display for Error {
28+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29+ match self {
30+ Error::Eof => write!(f, "end of stream"),
31+ Error::NeedMore => write!(f, "need more data"),
32+ Error::Invalid(m) => write!(f, "invalid: {m}"),
33+ Error::Unsupported(m) => write!(f, "unsupported: {m}"),
34+ }
35+ }
36+}
37+
38+impl std::error::Error for Error {}
39+
40+impl Error {
41+ pub fn invalid(msg: impl Into<String>) -> Error {
42+ Error::Invalid(msg.into())
43+ }
44+
45+ pub fn unsupported(msg: impl Into<String>) -> Error {
46+ Error::Unsupported(msg.into())
47+ }
48+}
49+
50+impl From<ec_aac::Error> for Error {
51+ fn from(e: ec_aac::Error) -> Error {
52+ match e {
53+ ec_aac::Error::Eof => Error::Eof,
54+ ec_aac::Error::NeedMore => Error::NeedMore,
55+ ec_aac::Error::Unsupported { .. } => Error::Unsupported(e.to_string()),
56+ other => Error::Invalid(other.to_string()),
57+ }
58+ }
59+}
60+
61+pub type Result<T> = std::result::Result<T, Error>;
62+
63+/// One decoded frame, interleaved, in film channel order.
64+#[derive(Clone, Debug, Default)]
65+pub struct DecodedAudio {
66+ pub sample_rate: u32,
67+ pub channels: u16,
68+ pub samples: Vec<f32>,
69+ pub pts: Option<i64>,
70+}
71+
72+impl DecodedAudio {
73+ pub fn frames(&self) -> usize {
74+ if self.channels == 0 {
75+ 0
76+ } else {
77+ self.samples.len() / usize::from(self.channels)
78+ }
79+ }
80+}
81+
82+/// What the decoder does with a High Efficiency stream.
83+pub use ec_aac::SbrSupport;
84+
85+/// An AAC-LC decoder.
86+pub struct AacDecoder(ec_aac::AacDecoder);
87+
88+impl AacDecoder {
89+ pub fn new() -> AacDecoder {
90+ AacDecoder(ec_aac::AacDecoder::new())
91+ }
92+
93+ pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder {
94+ AacDecoder(ec_aac::AacDecoder::with_config(cfg))
95+ }
96+
97+ pub fn with_config_bytes(data: &[u8]) -> Result<AacDecoder> {
98+ Ok(AacDecoder(ec_aac::AacDecoder::with_config_bytes(data)?))
99+ }
100+
101+ pub fn sbr_support(&self) -> SbrSupport {
102+ self.0.sbr_support()
103+ }
104+
105+ pub fn output_sample_rate(&self) -> Option<u32> {
106+ self.0.output_sample_rate()
107+ }
108+
109+ pub fn decode(&mut self, packet: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
110+ let d = self.0.decode(packet, pts)?;
111+ Ok(DecodedAudio {
112+ sample_rate: d.sample_rate,
113+ channels: d.channels,
114+ samples: d.samples,
115+ pts: d.pts,
116+ })
117+ }
118+}
119+
120+impl Default for AacDecoder {
121+ fn default() -> AacDecoder {
122+ AacDecoder::new()
123+ }
124+}
125+
126+/// Window-shape policy.
127+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128+pub enum WindowShape {
129+ #[default]
130+ Sine,
131+ Kbd,
132+ /// Per-frame dispatch on content tonality; served here as [`WindowShape::Sine`].
133+ Auto,
134+}
135+
136+/// Encoder options, at the incumbent's field set.
137+#[derive(Debug, Clone, Copy)]
138+pub struct AacEncoderConfig {
139+ /// Target bitrate in bits per second.
140+ pub bitrate_bps: u32,
141+ /// Window-shape policy.
142+ pub window_shape: WindowShape,
143+ /// The `Auto` gate's threshold; unused here, `Auto` codes as sine.
144+ pub shape_tonality_pct: f32,
145+ /// Run the psychoacoustic model on short blocks: always on here.
146+ pub short_block_psy: bool,
147+ /// Make the signal-to-mask ratio a function of band tonality: always on here.
148+ pub tonality_smr: bool,
149+ /// Emit TNS on long blocks; not emitted by this encoder (decoding it is
150+ /// complete either way).
151+ pub tns: bool,
152+ /// Level-invariant transient detector: always on here.
153+ pub relative_transients: bool,
154+ /// Perceptual noise substitution; not emitted by this encoder.
155+ pub pns: bool,
156+ /// Intensity stereo; not emitted by this encoder.
157+ pub intensity: bool,
158+ /// Split a pair's bit budget by perceptual demand: always on here, the rate
159+ /// loop is joint over the whole frame.
160+ pub stereo_bit_split: bool,
161+}
162+
163+impl Default for AacEncoderConfig {
164+ fn default() -> AacEncoderConfig {
165+ AacEncoderConfig {
166+ bitrate_bps: 128_000,
167+ window_shape: WindowShape::Sine,
168+ shape_tonality_pct: 0.5,
169+ short_block_psy: true,
170+ tonality_smr: true,
171+ tns: false,
172+ relative_transients: true,
173+ pns: false,
174+ intensity: false,
175+ stereo_bit_split: true,
176+ }
177+ }
178+}
179+
180+/// One encoded raw access unit (a `raw_data_block`, no ADTS framing).
181+#[derive(Debug, Clone)]
182+pub struct EncodedPacket {
183+ pub data: Vec<u8>,
184+ pub pts: i64,
185+ pub duration: u32,
186+}
187+
188+/// An AAC-LC encoder.
189+pub struct AacEncoder(ec_aac::AacEncoder);
190+
191+impl AacEncoder {
192+ pub fn new(config: AacEncoderConfig) -> AacEncoder {
193+ AacEncoder(ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig {
194+ bitrate_bps: config.bitrate_bps.max(1),
195+ window_shape: match config.window_shape {
196+ WindowShape::Kbd => ec_aac::WindowShape::Kbd,
197+ _ => ec_aac::WindowShape::Sine,
198+ },
199+ adts: false,
200+ mid_side: true,
201+ window_switching: true,
202+ }))
203+ }
204+
205+ pub fn sample_rate(&self) -> u32 {
206+ self.0.sample_rate()
207+ }
208+
209+ pub fn channels(&self) -> u16 {
210+ self.0.channels()
211+ }
212+
213+ pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
214+ Ok(self.0.push_pcm(interleaved, channels, sample_rate)?)
215+ }
216+
217+ pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
218+ Ok(self.0.push_pcm_planar(planes, sample_rate)?)
219+ }
220+
221+ pub fn finish(&mut self) {
222+ self.0.finish();
223+ }
224+
225+ pub fn next_packet(&mut self) -> Result<EncodedPacket> {
226+ let p = self.0.next_packet()?;
227+ Ok(EncodedPacket {
228+ data: p.data,
229+ pts: p.pts,
230+ duration: p.duration,
231+ })
232+ }
233+}