forge
Explore
Log in

Don't you dare go Hollow

A/52 headers, bit allocation model and transform primitives

Browse files at this commit

bd2188ce165ddad575264b8a221f3732fe75f27dAhmet Kaan GümüşParent: ece2a35
  • feat
    • A/52 headers, bit allocation model and transform primitives
Show full message
feat(ac3): A/52 headers, bit allocation model and transform primitives

syncinfo/bsi (including the Annex D alternate syntax), the parametric bit
allocation of section 7.2.2 with its spec tables, exponent and mantissa
unpacking, and the 512/256-sample IMDCT with window and overlap-add over
the shared ec-dsp FFT.

Grouped mantissas are shared across exponent sets, per section 7.3.5: the
group state belongs to the audio block, not to the channel.
Cargo.tomlmodified+1 -0
@@ -9,6 +9,7 @@ license = "MIT OR Apache-2.0"
99 authors = ["Ahmet Kaan Gümüş"]
1010
1111 [workspace.dependencies]
12+ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }
1213 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }
1314 ec-core = { path = "crates/ec-core", version = "0.1.0" }
1415 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
crates/ec-ac3/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "ec-ac3"
3+description = "AC-3 and Enhanced AC-3 (ATSC A/52) decoder built on the edith_codecs IR."
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-ac3/src/bitalloc.rsadded+348 -0
@@ -0,0 +1,348 @@
1+//! The parametric bit allocation model of A/52 §7.2.2.
2+//!
3+//! This is the part of AC-3 that has no slack in it: the decoder recomputes,
4+//! from the exponents alone, exactly how many bits the encoder spent on every
5+//! mantissa. One wrong `bap` and the rest of the block is read at the wrong bit
6+//! offset, so the seven steps below are transcribed step for step, integer for
7+//! integer, from the standard's pseudo code.
8+
9+use crate::aht_tables::HEBAPTAB;
10+use crate::tables::{
11+ BAPTAB, BNDTAB, DBPBTAB, FASTDEC, FASTGAIN, FLOORTAB, HTH, LATAB, MASKTAB, SLOWDEC, SLOWGAIN,
12+};
13+
14+/// The bit allocation parameters a block either sends (`baie`) or reuses.
15+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16+pub struct BitAllocParams {
17+ /// Slow decay code.
18+ pub sdcycod: u8,
19+ /// Fast decay code.
20+ pub fdcycod: u8,
21+ /// Slow gain code.
22+ pub sgaincod: u8,
23+ /// dB/bit code.
24+ pub dbpbcod: u8,
25+ /// Masking floor code.
26+ pub floorcod: u8,
27+}
28+
29+/// Delta bit allocation for one channel (§7.2.2.6): up to 8 segments of
30+/// masking-curve adjustment. `nseg == 0` means "no adjustment", which is the
31+/// state the standard asks decoders to initialise to every syncframe.
32+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33+pub struct DeltaBa {
34+ /// Number of active segments.
35+ pub nseg: usize,
36+ /// Band offset of each segment, relative to the previous segment's end.
37+ pub offset: [u8; 8],
38+ /// Band count of each segment.
39+ pub length: [u8; 8],
40+ /// Adjustment code of each segment.
41+ pub delta: [u8; 8],
42+}
43+
44+/// Which kind of channel the allocation is being run for; it selects the two
45+/// special cases the standard carves out of the excitation function.
46+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47+pub enum Channel {
48+ /// A full-bandwidth channel: starts at bin 0, runs the `lowcomp` path.
49+ Fbw,
50+ /// The LFE channel: like `Fbw`, but `calc_lowcomp` is skipped for its last
51+ /// band (bin 6) because there is no band above it.
52+ Lfe,
53+ /// The coupling channel: starts high, and its leak state is initialised
54+ /// from `cplfleak`/`cplsleak` rather than from the first bands.
55+ Coupling {
56+ /// `(cplfleak, cplsleak)` as sent, already shifted into leak units.
57+ leak: (i32, i32),
58+ },
59+}
60+
61+/// One channel's inputs to the model.
62+#[derive(Debug, Clone, Copy)]
63+pub struct Allocation<'a> {
64+ /// Sample rate code, indexing the hearing threshold table.
65+ pub fscod: usize,
66+ /// Parameters shared by every channel of the block.
67+ pub params: BitAllocParams,
68+ /// First and last-plus-one mantissa bin.
69+ pub range: (usize, usize),
70+ /// Fast gain code for this channel.
71+ pub fgaincod: u8,
72+ /// SNR offset, already combined from `csnroffst` and the channel's fine
73+ /// offset: `(((csnroffst - 15) << 4) + fsnroffst) << 2`.
74+ pub snroffset: i32,
75+ /// Channel kind.
76+ pub kind: Channel,
77+ /// Delta bit allocation, when the block sent or is reusing some.
78+ pub dba: Option<&'a DeltaBa>,
79+ /// Emit Annex E's high-efficiency pointers (`hebaptab[]`, Table E3.1)
80+ /// instead of `baptab[]`, which is what an AHT channel is allocated with
81+ /// (§E3.4.3.1). Everything up to the final table lookup is identical.
82+ pub high_efficiency: bool,
83+}
84+
85+/// Log-domain addition of two PSD values (§7.2.2.3).
86+fn logadd(a: i32, b: i32) -> i32 {
87+ let c = a - b;
88+ let address = ((c.abs() >> 1) as usize).min(255);
89+ if c >= 0 {
90+ a + LATAB[address]
91+ } else {
92+ b + LATAB[address]
93+ }
94+}
95+
96+/// `calc_lowcomp()` (§7.2.2.4).
97+fn calc_lowcomp(a: i32, b0: i32, b1: i32, bin: usize) -> i32 {
98+ if bin < 7 {
99+ if b0 + 256 == b1 {
100+ 384
101+ } else if b0 > b1 {
102+ (a - 64).max(0)
103+ } else {
104+ a
105+ }
106+ } else if bin < 20 {
107+ if b0 + 256 == b1 {
108+ 320
109+ } else if b0 > b1 {
110+ (a - 64).max(0)
111+ } else {
112+ a
113+ }
114+ } else {
115+ (a - 128).max(0)
116+ }
117+}
118+
119+/// Run the seven steps for one channel, filling `bap[start..end]`.
120+///
121+/// `exps` is indexed by mantissa bin and holds the decoded 5-bit exponents.
122+/// Everything outside `range` in `bap` is left alone.
123+pub fn compute(alloc: &Allocation<'_>, exps: &[u8], bap: &mut [u8]) {
124+ let (start, end) = alloc.range;
125+ if start >= end {
126+ return;
127+ }
128+ let sdecay = SLOWDEC[alloc.params.sdcycod as usize & 3];
129+ let fdecay = FASTDEC[alloc.params.fdcycod as usize & 3];
130+ let sgain = SLOWGAIN[alloc.params.sgaincod as usize & 3];
131+ let dbknee = DBPBTAB[alloc.params.dbpbcod as usize & 3];
132+ let floor = FLOORTAB[alloc.params.floorcod as usize & 7];
133+ let fgain = FASTGAIN[alloc.fgaincod as usize & 7];
134+ let snroffset = alloc.snroffset;
135+
136+ // Step: exponents into PSD.
137+ let mut psd = [0i32; 256];
138+ for bin in start..end {
139+ psd[bin] = 3072 - (i32::from(exps[bin]) << 7);
140+ }
141+
142+ // Step: PSD integration into 1/6-octave bands.
143+ let mut bndpsd = [0i32; 50];
144+ let mut j = start;
145+ let mut k = MASKTAB[start];
146+ loop {
147+ let lastbin = BNDTAB[k + 1].min(end);
148+ bndpsd[k] = psd[j];
149+ j += 1;
150+ while j < lastbin {
151+ bndpsd[k] = logadd(bndpsd[k], psd[j]);
152+ j += 1;
153+ }
154+ k += 1;
155+ if end <= lastbin {
156+ break;
157+ }
158+ }
159+
160+ // Step: excitation function.
161+ let bndstrt = MASKTAB[start];
162+ let bndend = MASKTAB[end - 1] + 1;
163+ let mut excite = [0i32; 50];
164+ let (mut fastleak, mut slowleak) = match alloc.kind {
165+ Channel::Coupling { leak } => leak,
166+ _ => (0, 0),
167+ };
168+ let begin = if bndstrt == 0 {
169+ // fbw and lfe channels. The standard writes the LFE exception as
170+ // `bndend != 7`; the LFE is the only channel that can end there, so
171+ // the kind says it more plainly.
172+ let is_lfe = alloc.kind == Channel::Lfe;
173+ let mut lowcomp = 0;
174+ lowcomp = calc_lowcomp(lowcomp, bndpsd[0], bndpsd[1], 0);
175+ excite[0] = bndpsd[0] - fgain - lowcomp;
176+ lowcomp = calc_lowcomp(lowcomp, bndpsd[1], bndpsd[2], 1);
177+ excite[1] = bndpsd[1] - fgain - lowcomp;
178+ let mut begin = 7;
179+ for bin in 2..7 {
180+ if !(is_lfe && bin == 6) {
181+ lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);
182+ }
183+ fastleak = bndpsd[bin] - fgain;
184+ slowleak = bndpsd[bin] - sgain;
185+ excite[bin] = fastleak - lowcomp;
186+ if !(is_lfe && bin == 6) && bndpsd[bin] <= bndpsd[bin + 1] {
187+ begin = bin + 1;
188+ break;
189+ }
190+ }
191+ for bin in begin..bndend.min(22) {
192+ if !(is_lfe && bin == 6) {
193+ lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);
194+ }
195+ fastleak = (fastleak - fdecay).max(bndpsd[bin] - fgain);
196+ slowleak = (slowleak - sdecay).max(bndpsd[bin] - sgain);
197+ excite[bin] = (fastleak - lowcomp).max(slowleak);
198+ }
199+ 22
200+ } else {
201+ bndstrt
202+ };
203+ for bin in begin..bndend {
204+ fastleak = (fastleak - fdecay).max(bndpsd[bin] - fgain);
205+ slowleak = (slowleak - sdecay).max(bndpsd[bin] - sgain);
206+ excite[bin] = fastleak.max(slowleak);
207+ }
208+
209+ // Step: masking curve.
210+ let mut mask = [0i32; 50];
211+ for bin in bndstrt..bndend {
212+ if bndpsd[bin] < dbknee {
213+ excite[bin] += (dbknee - bndpsd[bin]) >> 2;
214+ }
215+ mask[bin] = excite[bin].max(HTH[alloc.fscod.min(2)][bin]);
216+ }
217+
218+ // Step: delta bit allocation.
219+ if let Some(dba) = alloc.dba {
220+ let mut band = 0usize;
221+ for seg in 0..dba.nseg {
222+ band += usize::from(dba.offset[seg]);
223+ let delta = if dba.delta[seg] >= 4 {
224+ (i32::from(dba.delta[seg]) - 3) << 7
225+ } else {
226+ (i32::from(dba.delta[seg]) - 4) << 7
227+ };
228+ for _ in 0..dba.length[seg] {
229+ if band >= 50 {
230+ break;
231+ }
232+ mask[band] += delta;
233+ band += 1;
234+ }
235+ }
236+ }
237+
238+ // Step: bap from the gap between psd and the adjusted mask.
239+ let mut i = start;
240+ let mut j = MASKTAB[start];
241+ loop {
242+ let lastbin = BNDTAB[j + 1].min(end);
243+ mask[j] -= snroffset;
244+ mask[j] -= floor;
245+ if mask[j] < 0 {
246+ mask[j] = 0;
247+ }
248+ mask[j] &= 0x1fe0;
249+ mask[j] += floor;
250+ while i < lastbin {
251+ let address = ((psd[i] - mask[j]) >> 5).clamp(0, 63) as usize;
252+ bap[i] = if alloc.high_efficiency {
253+ HEBAPTAB[address]
254+ } else {
255+ BAPTAB[address]
256+ };
257+ i += 1;
258+ }
259+ j += 1;
260+ if end <= lastbin {
261+ break;
262+ }
263+ }
264+}
265+
266+#[cfg(test)]
267+mod tests {
268+ use super::*;
269+
270+ fn flat_alloc(snroffset: i32) -> Allocation<'static> {
271+ Allocation {
272+ fscod: 0,
273+ params: BitAllocParams {
274+ sdcycod: 2,
275+ fdcycod: 1,
276+ sgaincod: 1,
277+ dbpbcod: 2,
278+ floorcod: 4,
279+ },
280+ range: (0, 253),
281+ fgaincod: 4,
282+ snroffset,
283+ kind: Channel::Fbw,
284+ dba: None,
285+ high_efficiency: false,
286+ }
287+ }
288+
289+ #[test]
290+ fn louder_signal_and_bigger_snroffset_buy_more_bits() {
291+ // A flat, loud spectrum against a flat, quiet one: every allocated
292+ // pointer must be at least as large for the loud one, and raising the
293+ // SNR offset must not reduce any pointer. Those two monotonicities are
294+ // what the model exists to provide.
295+ let loud = [2u8; 256];
296+ let quiet = [20u8; 256];
297+ let (mut a, mut b, mut c) = ([0u8; 256], [0u8; 256], [0u8; 256]);
298+ compute(&flat_alloc(1000), &loud, &mut a);
299+ compute(&flat_alloc(1000), &quiet, &mut b);
300+ compute(&flat_alloc(1400), &quiet, &mut c);
301+ for bin in 0..253 {
302+ assert!(a[bin] >= b[bin], "bin {bin}: {} < {}", a[bin], b[bin]);
303+ assert!(c[bin] >= b[bin], "bin {bin}: {} < {}", c[bin], b[bin]);
304+ }
305+ assert!(a.iter().any(|&v| v > 0));
306+ }
307+
308+ #[test]
309+ fn delta_bit_allocation_lowers_the_mask_where_it_points() {
310+ // A quiet-ish flat spectrum with a modest SNR offset, so the affected
311+ // bands are not already pinned at the top of baptab[].
312+ let exps = [16u8; 256];
313+ let (mut plain, mut with_dba) = ([0u8; 256], [0u8; 256]);
314+ compute(&flat_alloc(0), &exps, &mut plain);
315+ let dba = DeltaBa {
316+ nseg: 1,
317+ offset: [10, 0, 0, 0, 0, 0, 0, 0],
318+ length: [4, 0, 0, 0, 0, 0, 0, 0],
319+ // delta 0 => (0 - 4) << 7, a 4 x -6 dB mask reduction => more bits.
320+ delta: [0, 0, 0, 0, 0, 0, 0, 0],
321+ };
322+ let mut alloc = flat_alloc(0);
323+ alloc.dba = Some(&dba);
324+ compute(&alloc, &exps, &mut with_dba);
325+ for bin in BNDTAB[10]..BNDTAB[14] {
326+ assert!(with_dba[bin] >= plain[bin], "bin {bin}");
327+ }
328+ assert!(
329+ (BNDTAB[10]..BNDTAB[14]).any(|bin| with_dba[bin] > plain[bin]),
330+ "the -6 dB segment bought no bits anywhere"
331+ );
332+ for bin in BNDTAB[14]..253 {
333+ assert_eq!(with_dba[bin], plain[bin], "bin {bin}");
334+ }
335+ for bin in 0..BNDTAB[10] {
336+ assert_eq!(with_dba[bin], plain[bin], "bin {bin}");
337+ }
338+ }
339+
340+ #[test]
341+ fn all_zero_range_is_a_no_op() {
342+ let mut bap = [7u8; 256];
343+ let mut alloc = flat_alloc(0);
344+ alloc.range = (37, 37);
345+ compute(&alloc, &[5u8; 256], &mut bap);
346+ assert!(bap.iter().all(|&v| v == 7));
347+ }
348+}
crates/ec-ac3/src/bsi.rsadded+325 -0
@@ -0,0 +1,325 @@
1+//! `bsi()` — AC-3 bit stream information (A/52 §5.3.2), including the
2+//! alternate syntax of Annex D that `bsid == 6` streams carry.
3+
4+use ec_core::{BitReader, Error, Result};
5+
6+use crate::tables;
7+
8+/// Audio coding mode (Table 5.8): how many channels there are and where.
9+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10+pub enum Acmod {
11+ /// 1+1: two completely independent programs (dual mono).
12+ DualMono,
13+ /// 1/0: centre only.
14+ Mono,
15+ /// 2/0: left, right.
16+ #[default]
17+ Stereo,
18+ /// 3/0: left, centre, right.
19+ Surround3_0,
20+ /// 2/1: left, right, mono surround.
21+ Surround2_1,
22+ /// 3/1: left, centre, right, mono surround.
23+ Surround3_1,
24+ /// 2/2: left, right, left surround, right surround.
25+ Surround2_2,
26+ /// 3/2: left, centre, right, left surround, right surround.
27+ Surround3_2,
28+}
29+
30+impl Acmod {
31+ /// The raw 3-bit code.
32+ pub fn code(self) -> u8 {
33+ self as u8
34+ }
35+
36+ /// From the raw 3-bit code; anything wider is masked to 3 bits.
37+ pub fn from_code(code: u8) -> Acmod {
38+ match code & 7 {
39+ 0 => Acmod::DualMono,
40+ 1 => Acmod::Mono,
41+ 2 => Acmod::Stereo,
42+ 3 => Acmod::Surround3_0,
43+ 4 => Acmod::Surround2_1,
44+ 5 => Acmod::Surround3_1,
45+ 6 => Acmod::Surround2_2,
46+ _ => Acmod::Surround3_2,
47+ }
48+ }
49+
50+ /// Full-bandwidth channels, excluding the LFE.
51+ pub fn nfchans(self) -> usize {
52+ tables::NFCHANS[self.code() as usize]
53+ }
54+
55+ /// True when a centre channel is coded (acmod 3, 5, 7).
56+ pub fn has_center(self) -> bool {
57+ matches!(self.code(), 3 | 5 | 7)
58+ }
59+
60+ /// Number of surround channels coded: 0, 1 (mono surround) or 2.
61+ pub fn surround_channels(self) -> usize {
62+ match self.code() {
63+ 4 | 5 => 1,
64+ 6 | 7 => 2,
65+ _ => 0,
66+ }
67+ }
68+}
69+
70+/// Centre mix level in linear gain (Table 5.9). The reserved code takes the
71+/// middle value, as §7.8.2 instructs.
72+pub fn center_mix_level(cmixlev: u8) -> f32 {
73+ match cmixlev {
74+ 0 => 0.707,
75+ 2 => 0.500,
76+ _ => 0.595,
77+ }
78+}
79+
80+/// Surround mix level in linear gain (Table 5.10). The reserved code takes the
81+/// middle value, as §7.8.2 instructs.
82+pub fn surround_mix_level(surmixlev: u8) -> f32 {
83+ match surmixlev {
84+ 0 => 0.707,
85+ 2 => 0.0,
86+ _ => 0.500,
87+ }
88+}
89+
90+/// Everything `bsi()` carries. Optional fields are [`None`] when their
91+/// presence bit was clear, which is the difference between "the encoder said
92+/// 0 dB" and "the encoder said nothing".
93+#[derive(Debug, Clone, PartialEq, Eq, Default)]
94+pub struct Bsi {
95+ /// Bit stream identification: 8 for standard AC-3, 6 for the Annex D
96+ /// alternate syntax, 16 for E-AC-3 (which uses [`crate::eac3::bsi`]).
97+ pub bsid: u8,
98+ /// Bit stream mode (Table 5.7).
99+ pub bsmod: u8,
100+ /// Audio coding mode.
101+ pub acmod: Acmod,
102+ /// Centre mix level code, present with three front channels.
103+ pub cmixlev: Option<u8>,
104+ /// Surround mix level code, present with a surround channel.
105+ pub surmixlev: Option<u8>,
106+ /// Dolby Surround mode, present in 2/0.
107+ pub dsurmod: Option<u8>,
108+ /// LFE channel present.
109+ pub lfeon: bool,
110+ /// Dialogue normalisation, in -dB below full scale (1..=31).
111+ pub dialnorm: u8,
112+ /// Heavy compression gain word.
113+ pub compr: Option<u8>,
114+ /// Language code (deprecated by the standard, still carried).
115+ pub langcod: Option<u8>,
116+ /// Mixing level in dB SPL, when audio production info is present.
117+ pub mixlevel: Option<u8>,
118+ /// Room type, when audio production info is present.
119+ pub roomtyp: Option<u8>,
120+ /// Second program's dialogue normalisation, in 1+1 mode.
121+ pub dialnorm2: Option<u8>,
122+ /// Second program's heavy compression gain word, in 1+1 mode.
123+ pub compr2: Option<u8>,
124+ /// Copyright bit.
125+ pub copyrightb: bool,
126+ /// Original bit stream bit.
127+ pub origbs: bool,
128+ /// Preferred stereo downmix mode (Annex D `dmixmod`).
129+ pub dmixmod: Option<u8>,
130+ /// Lt/Rt centre and surround mix levels (Annex D).
131+ pub ltrt_mixlev: Option<(u8, u8)>,
132+ /// Lo/Ro centre and surround mix levels (Annex D).
133+ pub loro_mixlev: Option<(u8, u8)>,
134+ /// Dolby Surround EX mode (Annex D `dsurexmod`).
135+ pub dsurexmod: Option<u8>,
136+ /// Full-bandwidth channels, excluding the LFE.
137+ pub nfchans: usize,
138+ /// Coded channels including the LFE — what a decoder hands out natively.
139+ pub channels: usize,
140+}
141+
142+/// Parse `bsi()` from the bits that follow `syncinfo()`.
143+///
144+/// `data` starts at the first byte after the five `syncinfo()` bytes, which is
145+/// how every caller has it: `bsi::parse(&frame[5..])`.
146+pub fn parse(data: &[u8]) -> Result<Bsi> {
147+ parse_from(&mut BitReader::new(data))
148+}
149+
150+/// [`parse`] against a reader the caller keeps, so a decoder can carry on into
151+/// the first audio block on the same bit position.
152+pub fn parse_from(r: &mut BitReader<'_>) -> Result<Bsi> {
153+ let bsid = r.read_bits(5)? as u8;
154+ if bsid > 10 {
155+ return Err(Error::unsupported(
156+ format!("AC-3 bsi: bsid = {bsid}"),
157+ "bsid above 10 is Enhanced AC-3; parse it with eac3::bsi",
158+ ));
159+ }
160+ let bsmod = r.read_bits(3)? as u8;
161+ let acmod = Acmod::from_code(r.read_bits(3)? as u8);
162+ let cmixlev = (acmod.code() & 1 != 0 && acmod.code() != 1)
163+ .then(|| r.read_bits(2))
164+ .transpose()?
165+ .map(|v| v as u8);
166+ let surmixlev = (acmod.code() & 4 != 0)
167+ .then(|| r.read_bits(2))
168+ .transpose()?
169+ .map(|v| v as u8);
170+ let dsurmod = (acmod == Acmod::Stereo)
171+ .then(|| r.read_bits(2))
172+ .transpose()?
173+ .map(|v| v as u8);
174+ let lfeon = r.read_bit()?;
175+ let dialnorm = r.read_bits(5)? as u8;
176+ let compr = read_optional(r, 8)?;
177+ let langcod = read_optional(r, 8)?;
178+ let (mixlevel, roomtyp) = if r.read_bit()? {
179+ (Some(r.read_bits(5)? as u8), Some(r.read_bits(2)? as u8))
180+ } else {
181+ (None, None)
182+ };
183+ let (mut dialnorm2, mut compr2) = (None, None);
184+ if acmod == Acmod::DualMono {
185+ dialnorm2 = Some(r.read_bits(5)? as u8);
186+ compr2 = read_optional(r, 8)?;
187+ let _langcod2 = read_optional(r, 8)?;
188+ if r.read_bit()? {
189+ let _mixlevel2 = r.read_bits(5)?;
190+ let _roomtyp2 = r.read_bits(2)?;
191+ }
192+ }
193+ let copyrightb = r.read_bit()?;
194+ let origbs = r.read_bit()?;
195+
196+ let mut bsi = Bsi {
197+ bsid,
198+ bsmod,
199+ acmod,
200+ cmixlev,
201+ surmixlev,
202+ dsurmod,
203+ lfeon,
204+ dialnorm,
205+ compr,
206+ langcod,
207+ mixlevel,
208+ roomtyp,
209+ dialnorm2,
210+ compr2,
211+ copyrightb,
212+ origbs,
213+ dmixmod: None,
214+ ltrt_mixlev: None,
215+ loro_mixlev: None,
216+ dsurexmod: None,
217+ nfchans: acmod.nfchans(),
218+ channels: acmod.nfchans() + usize::from(lfeon),
219+ };
220+
221+ if bsid == 6 {
222+ // Annex D: the time code fields are replaced by the extra mix and
223+ // downmix metadata a modern encoder actually has to say.
224+ if r.read_bit()? {
225+ bsi.dmixmod = Some(r.read_bits(2)? as u8);
226+ bsi.ltrt_mixlev = Some((r.read_bits(3)? as u8, r.read_bits(3)? as u8));
227+ bsi.loro_mixlev = Some((r.read_bits(3)? as u8, r.read_bits(3)? as u8));
228+ }
229+ if r.read_bit()? {
230+ bsi.dsurexmod = Some(r.read_bits(2)? as u8);
231+ let _dheadphonmod = r.read_bits(2)?;
232+ let _adconvtyp = r.read_bit()?;
233+ let _xbsi2 = r.read_bits(8)?;
234+ let _encinfo = r.read_bit()?;
235+ }
236+ } else {
237+ if r.read_bit()? {
238+ let _timecod1 = r.read_bits(14)?;
239+ }
240+ if r.read_bit()? {
241+ let _timecod2 = r.read_bits(14)?;
242+ }
243+ }
244+ if r.read_bit()? {
245+ let addbsil = r.read_bits(6)? as u64;
246+ r.skip_bits((addbsil + 1) * 8)?;
247+ }
248+ Ok(bsi)
249+}
250+
251+/// A presence bit followed by an `n`-bit value.
252+fn read_optional(r: &mut BitReader<'_>, n: u32) -> Result<Option<u8>> {
253+ if r.read_bit()? {
254+ Ok(Some(r.read_bits(n)? as u8))
255+ } else {
256+ Ok(None)
257+ }
258+}
259+
260+#[cfg(test)]
261+mod tests {
262+ use super::*;
263+ use ec_core::BitWriter;
264+
265+ fn write_minimal_bsi(bsid: u8, acmod: u8, lfeon: bool, dialnorm: u8) -> Vec<u8> {
266+ let mut w = BitWriter::new();
267+ w.write_bits(u32::from(bsid), 5);
268+ w.write_bits(0, 3); // bsmod
269+ w.write_bits(u32::from(acmod), 3);
270+ if acmod & 1 != 0 && acmod != 1 {
271+ w.write_bits(1, 2); // cmixlev
272+ }
273+ if acmod & 4 != 0 {
274+ w.write_bits(0, 2); // surmixlev
275+ }
276+ if acmod == 2 {
277+ w.write_bits(0, 2); // dsurmod
278+ }
279+ w.write_bit(lfeon);
280+ w.write_bits(u32::from(dialnorm), 5);
281+ w.write_bit(false); // compre
282+ w.write_bit(false); // langcode
283+ w.write_bit(false); // audprodie
284+ w.write_bit(false); // copyrightb
285+ w.write_bit(false); // origbs
286+ w.write_bit(false); // timecod1e
287+ w.write_bit(false); // timecod2e
288+ w.write_bit(false); // addbsie
289+ w.align_to_byte();
290+ w.into_bytes()
291+ }
292+
293+ #[test]
294+ fn parses_a_5_1_header() {
295+ let bytes = write_minimal_bsi(8, 7, true, 27);
296+ let bsi = parse(&bytes).unwrap();
297+ assert_eq!(bsi.acmod, Acmod::Surround3_2);
298+ assert_eq!(bsi.nfchans, 5);
299+ assert!(bsi.lfeon);
300+ assert_eq!(bsi.channels, 6);
301+ assert_eq!(bsi.dialnorm, 27);
302+ assert_eq!(bsi.cmixlev, Some(1));
303+ assert_eq!(bsi.surmixlev, Some(0));
304+ }
305+
306+ #[test]
307+ fn parses_mono_and_refuses_eac3_bsid() {
308+ let bsi = parse(&write_minimal_bsi(8, 1, false, 31)).unwrap();
309+ assert_eq!(bsi.acmod, Acmod::Mono);
310+ assert_eq!(bsi.channels, 1);
311+ assert!(matches!(
312+ parse(&write_minimal_bsi(16, 7, true, 27)),
313+ Err(Error::Unsupported { .. })
314+ ));
315+ assert!(matches!(parse(&[]), Err(Error::NeedMore)));
316+ }
317+
318+ #[test]
319+ fn mix_levels_follow_tables_5_9_and_5_10() {
320+ assert_eq!(center_mix_level(0), 0.707);
321+ assert_eq!(center_mix_level(2), 0.500);
322+ assert_eq!(center_mix_level(3), center_mix_level(1));
323+ assert_eq!(surround_mix_level(2), 0.0);
324+ }
325+}
crates/ec-ac3/src/exps.rsadded+178 -0
@@ -0,0 +1,178 @@
1+//! Exponent decoding (A/52 §7.1.3).
2+//!
3+//! Exponents travel as 7-bit groups of three differential values, each of which
4+//! covers one, two or four mantissas depending on the strategy. A group whose
5+//! mapped value exceeds 124, or a running exponent outside 0..=24, is a corrupt
6+//! stream rather than a clamp: the bit allocation that follows would otherwise
7+//! read the rest of the block at the wrong offsets and call it audio.
8+
9+use ec_core::{BitReader, Error, Result};
10+
11+/// Exponent strategy (Tables 7.4, 7.5).
12+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13+pub enum Strategy {
14+ /// Keep the previous block's exponents for this channel.
15+ #[default]
16+ Reuse,
17+ /// One exponent per mantissa.
18+ D15,
19+ /// One exponent per pair.
20+ D25,
21+ /// One exponent per quad.
22+ D45,
23+}
24+
25+impl Strategy {
26+ /// From the 2-bit `chexpstr`/`cplexpstr` code.
27+ pub fn from_code(code: u32) -> Strategy {
28+ match code & 3 {
29+ 0 => Strategy::Reuse,
30+ 1 => Strategy::D15,
31+ 2 => Strategy::D25,
32+ _ => Strategy::D45,
33+ }
34+ }
35+
36+ /// Mantissas covered by one differential exponent: 1, 2 or 4.
37+ pub fn group_size(self) -> usize {
38+ match self {
39+ Strategy::Reuse => 0,
40+ Strategy::D15 => 1,
41+ Strategy::D25 => 2,
42+ Strategy::D45 => 4,
43+ }
44+ }
45+
46+ /// Number of 7-bit groups for a full-bandwidth or coupled channel whose
47+ /// mantissas end at `endmant` (§7.1.3), not counting the absolute exponent.
48+ pub fn fbw_groups(self, endmant: usize) -> usize {
49+ match self {
50+ Strategy::Reuse => 0,
51+ Strategy::D15 => endmant.saturating_sub(1) / 3,
52+ Strategy::D25 => (endmant + 2) / 6,
53+ Strategy::D45 => (endmant + 8) / 12,
54+ }
55+ }
56+
57+ /// Number of 7-bit groups for the coupling channel over `[start, end)`.
58+ pub fn coupling_groups(self, start: usize, end: usize) -> usize {
59+ let span = end.saturating_sub(start);
60+ match self {
61+ Strategy::Reuse => 0,
62+ Strategy::D15 => span / 3,
63+ Strategy::D25 => span / 6,
64+ Strategy::D45 => span / 12,
65+ }
66+ }
67+}
68+
69+/// Read `ngrps` groups and expand them into `exps`, starting at `first_bin`.
70+///
71+/// `previous` is the absolute exponent the first differential is applied to:
72+/// `exps[ch][0]` for a full-bandwidth or LFE channel (which the caller has
73+/// already stored), or `cplabsexp << 1` for the coupling channel.
74+pub fn decode(
75+ r: &mut BitReader<'_>,
76+ strategy: Strategy,
77+ ngrps: usize,
78+ previous: u8,
79+ first_bin: usize,
80+ exps: &mut [u8],
81+) -> Result<()> {
82+ let group_size = strategy.group_size();
83+ if group_size == 0 {
84+ return Ok(());
85+ }
86+ let mut prev = i32::from(previous);
87+ let mut bin = first_bin;
88+ for _ in 0..ngrps {
89+ let gexp = r.read_bits(7)?;
90+ if gexp > 124 {
91+ return Err(Error::corrupt(format!(
92+ "AC-3 exponents: grouped value {gexp} > 124"
93+ )));
94+ }
95+ for mapped in [gexp / 25, (gexp % 25) / 5, gexp % 5] {
96+ prev += mapped as i32 - 2;
97+ if !(0..=24).contains(&prev) {
98+ return Err(Error::corrupt(format!(
99+ "AC-3 exponents: absolute exponent {prev} outside 0..=24"
100+ )));
101+ }
102+ for _ in 0..group_size {
103+ if bin >= exps.len() {
104+ // The last group of a D25/D45 set can overrun the channel's
105+ // own bandwidth by design; those values are not used.
106+ break;
107+ }
108+ exps[bin] = prev as u8;
109+ bin += 1;
110+ }
111+ }
112+ }
113+ Ok(())
114+}
115+
116+#[cfg(test)]
117+mod tests {
118+ use super::*;
119+ use ec_core::BitWriter;
120+
121+ #[test]
122+ fn d15_expands_one_exponent_per_mantissa() {
123+ // Two groups: deltas (+2, 0, -1) and (0, +1, +1) from an absolute 5.
124+ let mut w = BitWriter::new();
125+ w.write_bits(4 * 25 + 2 * 5 + 1, 7);
126+ w.write_bits(2 * 25 + 3 * 5 + 3, 7);
127+ let bytes = w.into_bytes();
128+ let mut r = BitReader::new(&bytes);
129+ let mut exps = [0u8; 16];
130+ exps[0] = 5;
131+ decode(&mut r, Strategy::D15, 2, 5, 1, &mut exps).unwrap();
132+ assert_eq!(&exps[..7], &[5, 7, 7, 6, 6, 7, 8]);
133+ }
134+
135+ #[test]
136+ fn d45_repeats_each_exponent_four_times() {
137+ let mut w = BitWriter::new();
138+ w.write_bits(3 * 25 + 2 * 5 + 2, 7); // +1, 0, 0
139+ let bytes = w.into_bytes();
140+ let mut r = BitReader::new(&bytes);
141+ let mut exps = [0u8; 16];
142+ exps[0] = 10;
143+ decode(&mut r, Strategy::D45, 1, 10, 1, &mut exps).unwrap();
144+ assert_eq!(
145+ &exps[..13],
146+ &[10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11]
147+ );
148+ }
149+
150+ #[test]
151+ fn out_of_range_exponents_are_corrupt_not_clamped() {
152+ let mut w = BitWriter::new();
153+ w.write_bits(4 * 25 + 4 * 5 + 4, 7); // +2, +2, +2 from 23 => 29
154+ let bytes = w.into_bytes();
155+ let mut r = BitReader::new(&bytes);
156+ let mut exps = [0u8; 16];
157+ assert!(matches!(
158+ decode(&mut r, Strategy::D15, 1, 23, 1, &mut exps),
159+ Err(Error::Corrupt { .. })
160+ ));
161+ // And a truncated group is NeedMore, never a panic.
162+ let mut r = BitReader::new(&[0u8; 0]);
163+ assert!(matches!(
164+ decode(&mut r, Strategy::D15, 1, 5, 1, &mut exps),
165+ Err(Error::NeedMore)
166+ ));
167+ }
168+
169+ #[test]
170+ fn group_counts_match_the_standards_formulas() {
171+ // §7.1.3 worked cases: a full-bandwidth channel ending at 253.
172+ assert_eq!(Strategy::D15.fbw_groups(253), 84);
173+ assert_eq!(Strategy::D25.fbw_groups(253), 42);
174+ assert_eq!(Strategy::D45.fbw_groups(253), 21);
175+ assert_eq!(Strategy::D15.fbw_groups(7), 2);
176+ assert_eq!(Strategy::D25.coupling_groups(37, 253), 36);
177+ }
178+}
crates/ec-ac3/src/mantissa.rsadded+184 -0
@@ -0,0 +1,184 @@
1+//! Mantissa unpacking (A/52 §7.3), including the grouped quantizers and the
2+//! dither the standard puts in place of zero-bit mantissas.
3+
4+use ec_core::{BitReader, Result};
5+
6+use crate::tables::{QNTZTAB, QUANT_LEVELS, symmetric_level};
7+
8+/// The pseudo-random source for `bap == 0` mantissas (§7.3.4).
9+///
10+/// The standard asks only for "any reasonably random sequence" scaled to a
11+/// uniform distribution between ±0.707, so this is the classic 16-bit LFSR the
12+/// AC-3 reference decoder uses. It is deterministic, which is what makes a
13+/// decode reproducible from one run to the next.
14+#[derive(Debug, Clone, Copy, Default)]
15+pub struct Dither(u32);
16+
17+impl Dither {
18+ /// Next dither value, uniform in ±0.707.
19+ pub fn value(&mut self) -> f32 {
20+ self.uniform() * 0.707
21+ }
22+
23+ /// Next value from a zero-mean, unit-variance source — what Annex E
24+ /// §3.6.4.2.4 calls `noise()`. A uniform distribution on `[-1, 1)` has
25+ /// variance 1/3, so it is scaled by `sqrt(3)`.
26+ pub fn unit_variance(&mut self) -> f32 {
27+ self.uniform() * 1.732_050_8
28+ }
29+
30+ fn uniform(&mut self) -> f32 {
31+ self.0 = self.0.wrapping_mul(25173).wrapping_add(13849) & 0xffff;
32+ f32::from(self.0 as u16 as i16) * (1.0 / 32768.0)
33+ }
34+}
35+
36+/// Reads one exponent set's mantissas, holding the two-and-three value groups
37+/// that baps 1, 2 and 4 pack into a single code word.
38+///
39+/// A reader belongs to one channel's run of mantissas: the standard restarts
40+/// grouping at each exponent set, so a partly consumed group is dropped when
41+/// the next channel begins.
42+#[derive(Debug, Clone, Copy, Default)]
43+pub struct Mantissas {
44+ group3: [f32; 3],
45+ left3: usize,
46+ group5: [f32; 3],
47+ left5: usize,
48+ group11: [f32; 2],
49+ left11: usize,
50+}
51+
52+impl Mantissas {
53+ /// A reader with no group in flight.
54+ pub fn new() -> Mantissas {
55+ Mantissas::default()
56+ }
57+
58+ /// One mantissa value in `[-1, 1)`, before the exponent is applied.
59+ ///
60+ /// `bap == 0` returns 0.0; the caller decides whether that bin gets dither,
61+ /// because in the coupled range the decision belongs to the channel rather
62+ /// than to the coupling channel the mantissa came from.
63+ pub fn read(&mut self, r: &mut BitReader<'_>, bap: u8) -> Result<f32> {
64+ Ok(match bap {
65+ 0 => 0.0,
66+ 1 => {
67+ if self.left3 == 0 {
68+ let code = r.read_bits(5)?.min(26);
69+ let levels = QUANT_LEVELS[1];
70+ self.group3 = [
71+ symmetric_level(levels, code / 9),
72+ symmetric_level(levels, (code % 9) / 3),
73+ symmetric_level(levels, code % 3),
74+ ];
75+ self.left3 = 3;
76+ }
77+ self.left3 -= 1;
78+ self.group3[2 - self.left3]
79+ }
80+ 2 => {
81+ if self.left5 == 0 {
82+ let code = r.read_bits(7)?.min(124);
83+ let levels = QUANT_LEVELS[2];
84+ self.group5 = [
85+ symmetric_level(levels, code / 25),
86+ symmetric_level(levels, (code % 25) / 5),
87+ symmetric_level(levels, code % 5),
88+ ];
89+ self.left5 = 3;
90+ }
91+ self.left5 -= 1;
92+ self.group5[2 - self.left5]
93+ }
94+ 4 => {
95+ if self.left11 == 0 {
96+ let code = r.read_bits(7)?.min(120);
97+ let levels = QUANT_LEVELS[4];
98+ self.group11 = [
99+ symmetric_level(levels, code / 11),
100+ symmetric_level(levels, code % 11),
101+ ];
102+ self.left11 = 2;
103+ }
104+ self.left11 -= 1;
105+ self.group11[1 - self.left11]
106+ }
107+ 3 | 5 => {
108+ let bits = QNTZTAB[bap as usize];
109+ let code = r.read_bits(bits)?;
110+ symmetric_level(QUANT_LEVELS[bap as usize], code)
111+ }
112+ _ => {
113+ // 6..=15: asymmetric two's complement, decimal point left of
114+ // the MSB (§7.3.2).
115+ let bits = QNTZTAB[(bap as usize).min(15)];
116+ let value = r.read_signed(bits)?;
117+ value as f32 / (1u32 << (bits - 1)) as f32
118+ }
119+ })
120+ }
121+}
122+
123+/// `2^-exponent`, the right shift §7.3 applies to every mantissa.
124+pub fn scale(exponent: u8) -> f32 {
125+ // Exponents are 0..=24, so a table lookup would buy nothing over the
126+ // exponent arithmetic the compiler folds here.
127+ f32::from_bits(127u32.wrapping_sub(u32::from(exponent)) << 23)
128+}
129+
130+#[cfg(test)]
131+mod tests {
132+ use super::*;
133+ use ec_core::BitWriter;
134+
135+ #[test]
136+ fn grouped_quantizers_unpack_three_and_two_at_a_time() {
137+ // One bap-1 group holding codes (2, 1, 0) => (+2/3, 0, -2/3), then one
138+ // bap-4 group holding (10, 0) => (+10/11, -10/11).
139+ let mut w = BitWriter::new();
140+ w.write_bits(2 * 9 + 3, 5);
141+ w.write_bits(10 * 11, 7);
142+ let bytes = w.into_bytes();
143+ let mut r = BitReader::new(&bytes);
144+ let mut m = Mantissas::new();
145+ let got: Vec<f32> = (0..3).map(|_| m.read(&mut r, 1).unwrap()).collect();
146+ assert!((got[0] - 2.0 / 3.0).abs() < 1e-6);
147+ assert!(got[1].abs() < 1e-6);
148+ assert!((got[2] + 2.0 / 3.0).abs() < 1e-6);
149+ let a = m.read(&mut r, 4).unwrap();
150+ let b = m.read(&mut r, 4).unwrap();
151+ assert!((a - 10.0 / 11.0).abs() < 1e-6);
152+ assert!((b + 10.0 / 11.0).abs() < 1e-6);
153+ }
154+
155+ #[test]
156+ fn asymmetric_mantissas_span_minus_one_to_just_under_one() {
157+ let mut w = BitWriter::new();
158+ w.write_bits(0b100000, 6); // most negative 6-bit word
159+ w.write_bits(0b011111, 6); // most positive
160+ let bytes = w.into_bytes();
161+ let mut r = BitReader::new(&bytes);
162+ let mut m = Mantissas::new();
163+ assert!((m.read(&mut r, 7).unwrap() + 1.0).abs() < 1e-6);
164+ assert!((m.read(&mut r, 7).unwrap() - 31.0 / 32.0).abs() < 1e-6);
165+ assert_eq!(m.read(&mut r, 0).unwrap(), 0.0);
166+ }
167+
168+ #[test]
169+ fn exponent_scale_is_a_power_of_two() {
170+ assert_eq!(scale(0), 1.0);
171+ assert_eq!(scale(1), 0.5);
172+ assert_eq!(scale(24), 1.0 / 16_777_216.0);
173+ }
174+
175+ #[test]
176+ fn dither_stays_inside_its_stated_range_and_repeats() {
177+ let mut d = Dither::default();
178+ let first: Vec<f32> = (0..64).map(|_| d.value()).collect();
179+ assert!(first.iter().all(|v| v.abs() <= 0.707));
180+ assert!(first.iter().any(|v| v.abs() > 0.1));
181+ let mut d2 = Dither::default();
182+ assert_eq!(first, (0..64).map(|_| d2.value()).collect::<Vec<_>>());
183+ }
184+}
crates/ec-ac3/src/syncinfo.rsadded+96 -0
@@ -0,0 +1,96 @@
1+//! `syncinfo()` — the five bytes an AC-3 syncframe opens with (A/52 §5.3.1).
2+
3+use ec_core::{BitReader, Error, Result};
4+
5+use crate::tables;
6+
7+/// The AC-3 sync word, `0x0B77`, in the order it appears on the wire.
8+pub const SYNCWORD: u16 = 0x0B77;
9+
10+/// Everything `syncinfo()` states, plus the two values every caller derives
11+/// from it (sample rate and frame size).
12+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13+pub struct SyncInfo {
14+ /// CRC over the first 5/8 of the frame (§7.10.1). Carried, not checked.
15+ pub crc1: u16,
16+ /// Sample rate code (Table 5.6).
17+ pub fscod: u8,
18+ /// Frame size code (Table 5.18).
19+ pub frmsizecod: u8,
20+ /// Sample rate in Hz, from `fscod`.
21+ pub sample_rate: u32,
22+ /// Whole frame length in bytes, from `frmsizecod` and `fscod`.
23+ pub frame_size: usize,
24+ /// Nominal bit rate in kbit/s.
25+ pub bit_rate_kbps: u32,
26+}
27+
28+/// Parse `syncinfo()` from the start of a syncframe.
29+///
30+/// `data` starts at the sync word. Fewer than 5 bytes is [`Error::NeedMore`];
31+/// a wrong sync word or a reserved `fscod`/`frmsizecod` is [`Error::Corrupt`],
32+/// which is what makes this usable as a "is this AC-3?" probe.
33+pub fn parse(data: &[u8]) -> Result<SyncInfo> {
34+ parse_from(&mut BitReader::new(data))
35+}
36+
37+/// [`parse`] against a reader the caller keeps, so a decoder can carry on into
38+/// `bsi()` on the same bit position.
39+pub fn parse_from(r: &mut BitReader<'_>) -> Result<SyncInfo> {
40+ let syncword = r.read_bits(16)? as u16;
41+ if syncword != SYNCWORD {
42+ return Err(Error::corrupt(format!(
43+ "AC-3 syncinfo: syncword {syncword:#06x}, expected {SYNCWORD:#06x}"
44+ )));
45+ }
46+ let crc1 = r.read_bits(16)? as u16;
47+ let fscod = r.read_bits(2)? as u8;
48+ let frmsizecod = r.read_bits(6)? as u8;
49+ let sample_rate = tables::SAMPLE_RATE[fscod as usize];
50+ if sample_rate == 0 {
51+ return Err(Error::corrupt("AC-3 syncinfo: fscod = 3 (reserved)"));
52+ }
53+ let Some(words) = tables::FRAME_SIZE_WORDS.get(frmsizecod as usize) else {
54+ return Err(Error::corrupt(format!(
55+ "AC-3 syncinfo: frmsizecod = {frmsizecod} (reserved)"
56+ )));
57+ };
58+ Ok(SyncInfo {
59+ crc1,
60+ fscod,
61+ frmsizecod,
62+ sample_rate,
63+ frame_size: usize::from(words[fscod as usize]) * 2,
64+ bit_rate_kbps: tables::BIT_RATE_KBPS[frmsizecod as usize >> 1],
65+ })
66+}
67+
68+#[cfg(test)]
69+mod tests {
70+ use super::*;
71+
72+ #[test]
73+ fn parses_a_48k_448k_header() {
74+ // syncword, crc1 = 0x1234, fscod = 0 (48 kHz), frmsizecod = 30 (448k).
75+ let data = [0x0B, 0x77, 0x12, 0x34, 0b0001_1110];
76+ let si = parse(&data).unwrap();
77+ assert_eq!(si.crc1, 0x1234);
78+ assert_eq!(si.sample_rate, 48_000);
79+ assert_eq!(si.bit_rate_kbps, 448);
80+ assert_eq!(si.frame_size, 896 * 2);
81+ }
82+
83+ #[test]
84+ fn refuses_a_bad_syncword_and_short_input() {
85+ assert!(matches!(
86+ parse(&[0x0B, 0x78, 0, 0, 0]),
87+ Err(Error::Corrupt { .. })
88+ ));
89+ assert!(matches!(parse(&[0x0B, 0x77, 0]), Err(Error::NeedMore)));
90+ // fscod = 3 is reserved.
91+ assert!(matches!(
92+ parse(&[0x0B, 0x77, 0, 0, 0b1100_0000]),
93+ Err(Error::Corrupt { .. })
94+ ));
95+ }
96+}
crates/ec-ac3/src/tables.rsadded+237 -0
@@ -0,0 +1,237 @@
1+//! Constant tables from ATSC A/52:2012 — the ones a decoder cannot derive.
2+//!
3+//! Everything here is a transcription of a numbered table in the standard, kept
4+//! in one place so a reader can check it against the document without walking
5+//! the decoder: §5.4.1.4 (frame sizes), §7.2.3 (bit allocation), §7.3
6+//! (quantizers), §7.9.4 (transform window).
7+//!
8+//! The symmetric quantizer levels of Tables 7.19-7.23 are *not* transcribed:
9+//! every one of them is the uniform midtread set `(2k - (L-1))/L`, so
10+//! [`symmetric_level`] computes it and a test asserts the printed values.
11+
12+/// Sample rates by `fscod` (Table 5.6); `0` marks the reserved code.
13+pub const SAMPLE_RATE: [u32; 4] = [48_000, 44_100, 32_000, 0];
14+
15+/// Frame size in 16-bit words, `[frmsizecod][fscod]` (Table 5.18).
16+pub const FRAME_SIZE_WORDS: [[u16; 3]; 38] = [
17+ [64, 69, 96],
18+ [64, 70, 96],
19+ [80, 87, 120],
20+ [80, 88, 120],
21+ [96, 104, 144],
22+ [96, 105, 144],
23+ [112, 121, 168],
24+ [112, 122, 168],
25+ [128, 139, 192],
26+ [128, 140, 192],
27+ [160, 174, 240],
28+ [160, 175, 240],
29+ [192, 208, 288],
30+ [192, 209, 288],
31+ [224, 243, 336],
32+ [224, 244, 336],
33+ [256, 278, 384],
34+ [256, 279, 384],
35+ [320, 348, 480],
36+ [320, 349, 480],
37+ [384, 417, 576],
38+ [384, 418, 576],
39+ [448, 487, 672],
40+ [448, 488, 672],
41+ [512, 557, 768],
42+ [512, 558, 768],
43+ [640, 696, 960],
44+ [640, 697, 960],
45+ [768, 835, 1152],
46+ [768, 836, 1152],
47+ [896, 975, 1344],
48+ [896, 976, 1344],
49+ [1024, 1114, 1536],
50+ [1024, 1115, 1536],
51+ [1152, 1253, 1728],
52+ [1152, 1254, 1728],
53+ [1280, 1393, 1920],
54+ [1280, 1394, 1920],
55+];
56+
57+/// Nominal bit rate in kbit/s by `frmsizecod >> 1` (Table 5.18).
58+pub const BIT_RATE_KBPS: [u32; 19] = [
59+ 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640,
60+];
61+
62+/// Number of full-bandwidth channels by `acmod` (Table 5.8).
63+pub const NFCHANS: [usize; 8] = [2, 1, 2, 3, 3, 4, 4, 5];
64+
65+/// First mantissa bin of each 1/6-octave band, `bndtab[]` (Table 7.12).
66+pub const BNDTAB: [usize; 51] = [
67+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
68+ 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181,
69+ 205, 229, 253,
70+];
71+
72+/// Bin number to band number, `masktab[]` (Table 7.13), derived from
73+/// [`BNDTAB`] — the standard prints both and says they duplicate each other.
74+pub const MASKTAB: [usize; 256] = {
75+ let mut t = [49usize; 256];
76+ let mut band = 0;
77+ while band < 50 {
78+ let mut bin = BNDTAB[band];
79+ while bin < BNDTAB[band + 1] {
80+ t[bin] = band;
81+ bin += 1;
82+ }
83+ band += 1;
84+ }
85+ t
86+};
87+
88+/// Slow decay, `slowdec[]` (Table 7.6).
89+pub const SLOWDEC: [i32; 4] = [0x0f, 0x11, 0x13, 0x15];
90+/// Fast decay, `fastdec[]` (Table 7.7).
91+pub const FASTDEC: [i32; 4] = [0x3f, 0x53, 0x67, 0x7b];
92+/// Slow gain, `slowgain[]` (Table 7.8).
93+pub const SLOWGAIN: [i32; 4] = [0x540, 0x4d8, 0x478, 0x410];
94+/// dB per bit, `dbpbtab[]` (Table 7.9).
95+pub const DBPBTAB: [i32; 4] = [0x000, 0x700, 0x900, 0xb00];
96+/// Masking floor, `floortab[]` (Table 7.10). Entry 7 is `0xf800`, which is
97+/// -0x800 as the 16-bit signed value the masking arithmetic wants.
98+pub const FLOORTAB: [i32; 8] = [0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, -0x800];
99+/// Fast gain, `fastgain[]` (Table 7.11).
100+pub const FASTGAIN: [i32; 8] = [0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400];
101+
102+/// Log-addition table, `latab[]` (Table 7.14).
103+pub const LATAB: [i32; 256] = [
104+ 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 52, 51, 50, 49, 48, 47, 47, 46, 45, 44, 44,
105+ 43, 42, 41, 41, 40, 39, 38, 38, 37, 36, 36, 35, 35, 34, 33, 33, 32, 32, 31, 30, 30, 29, 29, 28,
106+ 28, 27, 27, 26, 26, 25, 25, 24, 24, 23, 23, 22, 22, 21, 21, 21, 20, 20, 19, 19, 19, 18, 18, 18,
107+ 17, 17, 17, 16, 16, 16, 15, 15, 15, 14, 14, 14, 13, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 11,
108+ 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6,
109+ 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
110+ 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
111+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
112+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
113+ 0, 0,
114+];
115+
116+/// Hearing threshold, `hth[fscod][band]` (Table 7.15).
117+pub const HTH: [[i32; 50]; 3] = [
118+ [
119+ 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0,
120+ 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, 0x0360, 0x0360,
121+ 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0,
122+ 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, 0x0460, 0x0490, 0x04a0, 0x0460,
123+ 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840,
124+ ],
125+ [
126+ 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0,
127+ 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0370,
128+ 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0,
129+ 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, 0x0420, 0x0450, 0x04a0, 0x0490,
130+ 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840,
131+ ],
132+ [
133+ 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0,
134+ 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390,
135+ 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, 0x0340, 0x0330, 0x0320,
136+ 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0330, 0x0350, 0x03c0, 0x0410,
137+ 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0,
138+ ],
139+];
140+
141+/// Bit allocation pointer table, `baptab[]` (Table 7.16).
142+pub const BAPTAB: [u8; 64] = [
143+ 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
144+ 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14,
145+ 15, 15, 15, 15, 15, 15, 15, 15, 15,
146+];
147+
148+/// Mantissa bits per bap, `qntztab[]` (Table 7.18). Entries 1, 2 and 4 are the
149+/// *group* widths (5, 7 and 7 bits) — those baps are ungrouped by
150+/// [`crate::mantissa`], not read one mantissa at a time.
151+pub const QNTZTAB: [u32; 16] = [0, 5, 7, 3, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16];
152+
153+/// Quantizer levels for the symmetric baps 1-5 (Table 7.17).
154+pub const QUANT_LEVELS: [u32; 6] = [0, 3, 5, 7, 11, 15];
155+
156+/// The `k`-th reconstruction level of a `levels`-level symmetric quantizer
157+/// (Tables 7.19-7.23): the uniform midtread set `(2k - (levels-1)) / levels`.
158+pub fn symmetric_level(levels: u32, k: u32) -> f32 {
159+ (2.0 * k as f32 - (levels as f32 - 1.0)) / levels as f32
160+}
161+
162+/// Transform window `w[]`: 256 values used back to back to form the 512-point
163+/// window (Table 7.33).
164+// One printed value happens to sit within rounding distance of pi/4; it is a
165+// window sample, not that constant.
166+#[allow(clippy::approx_constant)]
167+pub const WINDOW: [f32; 256] = [
168+ 0.00014, 0.00024, 0.00037, 0.00051, 0.00067, 0.00086, 0.00107, 0.00130, 0.00157, 0.00187,
169+ 0.00220, 0.00256, 0.00297, 0.00341, 0.00390, 0.00443, 0.00501, 0.00564, 0.00632, 0.00706,
170+ 0.00785, 0.00871, 0.00962, 0.01061, 0.01166, 0.01279, 0.01399, 0.01526, 0.01662, 0.01806,
171+ 0.01959, 0.02121, 0.02292, 0.02472, 0.02662, 0.02863, 0.03073, 0.03294, 0.03527, 0.03770,
172+ 0.04025, 0.04292, 0.04571, 0.04862, 0.05165, 0.05481, 0.05810, 0.06153, 0.06508, 0.06878,
173+ 0.07261, 0.07658, 0.08069, 0.08495, 0.08935, 0.09389, 0.09859, 0.10343, 0.10842, 0.11356,
174+ 0.11885, 0.12429, 0.12988, 0.13563, 0.14152, 0.14757, 0.15376, 0.16011, 0.16661, 0.17325,
175+ 0.18005, 0.18699, 0.19407, 0.20130, 0.20867, 0.21618, 0.22382, 0.23161, 0.23952, 0.24757,
176+ 0.25574, 0.26404, 0.27246, 0.28100, 0.28965, 0.29841, 0.30729, 0.31626, 0.32533, 0.33450,
177+ 0.34376, 0.35311, 0.36253, 0.37204, 0.38161, 0.39126, 0.40096, 0.41072, 0.42054, 0.43040,
178+ 0.44030, 0.45023, 0.46020, 0.47019, 0.48020, 0.49022, 0.50025, 0.51028, 0.52031, 0.53033,
179+ 0.54033, 0.55031, 0.56026, 0.57019, 0.58007, 0.58991, 0.59970, 0.60944, 0.61912, 0.62873,
180+ 0.63827, 0.64774, 0.65713, 0.66643, 0.67564, 0.68476, 0.69377, 0.70269, 0.71150, 0.72019,
181+ 0.72877, 0.73723, 0.74557, 0.75378, 0.76186, 0.76981, 0.77762, 0.78530, 0.79283, 0.80022,
182+ 0.80747, 0.81457, 0.82151, 0.82831, 0.83496, 0.84145, 0.84779, 0.85398, 0.86001, 0.86588,
183+ 0.87160, 0.87716, 0.88257, 0.88782, 0.89291, 0.89785, 0.90264, 0.90728, 0.91176, 0.91610,
184+ 0.92028, 0.92432, 0.92822, 0.93197, 0.93558, 0.93906, 0.94240, 0.94560, 0.94867, 0.95162,
185+ 0.95444, 0.95713, 0.95971, 0.96217, 0.96451, 0.96674, 0.96887, 0.97089, 0.97281, 0.97463,
186+ 0.97635, 0.97799, 0.97953, 0.98099, 0.98236, 0.98366, 0.98488, 0.98602, 0.98710, 0.98811,
187+ 0.98905, 0.98994, 0.99076, 0.99153, 0.99225, 0.99291, 0.99353, 0.99411, 0.99464, 0.99513,
188+ 0.99558, 0.99600, 0.99639, 0.99674, 0.99706, 0.99736, 0.99763, 0.99788, 0.99811, 0.99831,
189+ 0.99850, 0.99867, 0.99882, 0.99895, 0.99908, 0.99919, 0.99929, 0.99938, 0.99946, 0.99953,
190+ 0.99959, 0.99965, 0.99969, 0.99974, 0.99978, 0.99981, 0.99984, 0.99986, 0.99988, 0.99990,
191+ 0.99992, 0.99993, 0.99994, 0.99995, 0.99996, 0.99997, 0.99998, 0.99998, 0.99998, 0.99999,
192+ 0.99999, 0.99999, 0.99999, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000,
193+ 1.00000, 1.00000, 1.00000, 1.00000, 1.00000, 1.00000,
194+];
195+
196+#[cfg(test)]
197+mod tests {
198+ use super::*;
199+
200+ #[test]
201+ fn masktab_matches_band_boundaries() {
202+ // Table 7.13 spot values, then the invariant that every bin lands in
203+ // the band whose [start, next start) range contains it.
204+ assert_eq!(MASKTAB[0], 0);
205+ assert_eq!(MASKTAB[28], 28);
206+ assert_eq!(MASKTAB[30], 28);
207+ assert_eq!(MASKTAB[31], 29);
208+ assert_eq!(MASKTAB[252], 49);
209+ for band in 0..50 {
210+ for bin in BNDTAB[band]..BNDTAB[band + 1] {
211+ assert_eq!(MASKTAB[bin], band, "bin {bin}");
212+ }
213+ }
214+ }
215+
216+ #[test]
217+ fn symmetric_quantizer_matches_printed_tables() {
218+ // Tables 7.19-7.23, as printed.
219+ assert!((symmetric_level(3, 0) + 2.0 / 3.0).abs() < 1e-6);
220+ assert!(symmetric_level(3, 1).abs() < 1e-6);
221+ assert!((symmetric_level(5, 3) - 2.0 / 5.0).abs() < 1e-6);
222+ assert!((symmetric_level(7, 6) - 6.0 / 7.0).abs() < 1e-6);
223+ assert!((symmetric_level(11, 0) + 10.0 / 11.0).abs() < 1e-6);
224+ assert!((symmetric_level(15, 14) - 14.0 / 15.0).abs() < 1e-6);
225+ }
226+
227+ #[test]
228+ fn window_is_princen_bradley() {
229+ // §7.9.4: the 512-point sequence formed from w[] satisfies
230+ // w[n]^2 + w[511-n]^2 = 1. The printed table carries 5 decimals, which
231+ // is what bounds the error here.
232+ for n in 0..256 {
233+ let (a, b) = (WINDOW[n], WINDOW[255 - n]);
234+ assert!((a * a + b * b - 1.0).abs() < 2e-5, "n = {n}");
235+ }
236+ }
237+}
crates/ec-ac3/src/transform.rsadded+239 -0
@@ -0,0 +1,239 @@
1+//! The inverse transform of A/52 §7.9.4: one 512-sample IMDCT, or two
2+//! 256-sample IMDCTs when the block switch flag is set, followed by the window
3+//! and overlap-add of §7.9.4 step 6.
4+//!
5+//! Both cases are the standard's own factorisation — pre-twiddle, an `N/4` (or
6+//! `N/8`) point complex inverse FFT from `ec_dsp`, post-twiddle, then the
7+//! interleaved windowing step. Writing it that way rather than calling a
8+//! generic MDCT keeps the sign and ordering conventions the standard's, so
9+//! there is nothing to reconcile when reading the two side by side.
10+
11+use ec_dsp::Fft;
12+use ec_dsp::fft::Complex;
13+
14+use crate::tables::WINDOW;
15+
16+/// Samples produced per audio block, per channel.
17+pub const BLOCK_SAMPLES: usize = 256;
18+
19+/// The plans and twiddles for both transform lengths.
20+#[derive(Clone)]
21+pub struct Imdct {
22+ long: Fft<f32>,
23+ short: Fft<f32>,
24+ /// Pre-twiddle for N = 512: `-cos/-sin(2π(8k+1)/4096)`, k < 128.
25+ pre_long: Vec<Complex<f32>>,
26+ /// Post-twiddle for N = 512: the same, scaled by 128 to undo the `1/n`
27+ /// that [`Fft::inverse`] applies but the standard's IFFT step does not.
28+ post_long: Vec<Complex<f32>>,
29+ /// Pre-twiddle for the 256-sample halves: `-cos/-sin(2π(8k+1)/2048)`.
30+ pre_short: Vec<Complex<f32>>,
31+ /// Post-twiddle for the halves, scaled by 64.
32+ post_short: Vec<Complex<f32>>,
33+ z: Vec<Complex<f32>>,
34+ z2: Vec<Complex<f32>>,
35+ x: Vec<f32>,
36+}
37+
38+impl Default for Imdct {
39+ fn default() -> Imdct {
40+ Imdct::new()
41+ }
42+}
43+
44+fn twiddles(count: usize, denom: f64, scale: f64) -> Vec<Complex<f32>> {
45+ (0..count)
46+ .map(|k| {
47+ let angle = 2.0 * std::f64::consts::PI * (8.0 * k as f64 + 1.0) / denom;
48+ Complex::new((-angle.cos() * scale) as f32, (-angle.sin() * scale) as f32)
49+ })
50+ .collect()
51+}
52+
53+impl Imdct {
54+ /// Build both plans. Allocates once; [`Imdct::block`] allocates nothing.
55+ pub fn new() -> Imdct {
56+ const N: f64 = 512.0;
57+ Imdct {
58+ long: Fft::new(128),
59+ short: Fft::new(64),
60+ pre_long: twiddles(128, 8.0 * N, 1.0),
61+ post_long: twiddles(128, 8.0 * N, 128.0),
62+ pre_short: twiddles(64, 4.0 * N, 1.0),
63+ post_short: twiddles(64, 4.0 * N, 64.0),
64+ z: vec![Complex::new(0.0, 0.0); 128],
65+ z2: vec![Complex::new(0.0, 0.0); 64],
66+ x: vec![0.0; 512],
67+ }
68+ }
69+
70+ /// One audio block: `coeffs` (256 spectral values) in, 256 PCM samples out,
71+ /// carrying `delay` across the call as the overlap-add tail.
72+ ///
73+ /// `block_switch` selects the two 256-sample transforms of §7.9.4.2.
74+ pub fn block(
75+ &mut self,
76+ coeffs: &[f32],
77+ block_switch: bool,
78+ delay: &mut [f32],
79+ out: &mut [f32],
80+ ) {
81+ debug_assert!(coeffs.len() >= 256 && delay.len() >= 256 && out.len() >= 256);
82+ if block_switch {
83+ self.short_transform(coeffs);
84+ } else {
85+ self.long_transform(coeffs);
86+ }
87+ // §7.9.4 step 6. The factor of 2 undoes the encoder's headroom scaling.
88+ for n in 0..BLOCK_SAMPLES {
89+ out[n] = 2.0 * (self.x[n] + delay[n]);
90+ delay[n] = self.x[BLOCK_SAMPLES + n];
91+ }
92+ }
93+
94+ /// Drop the overlap-add tail; a seek makes it belong to frames that were
95+ /// never decoded.
96+ pub fn reset(delay: &mut [f32]) {
97+ delay.fill(0.0);
98+ }
99+
100+ fn long_transform(&mut self, coeffs: &[f32]) {
101+ // Step 2: pre-IFFT complex multiply.
102+ for k in 0..128 {
103+ let (a, b) = (coeffs[255 - 2 * k], coeffs[2 * k]);
104+ let t = self.pre_long[k];
105+ self.z[k] = Complex::new(a * t.re - b * t.im, b * t.re + a * t.im);
106+ }
107+ // Step 3: N/4-point complex IFFT.
108+ self.long.inverse(&mut self.z);
109+ // Step 4: post-IFFT complex multiply (with the 1/n undone).
110+ for n in 0..128 {
111+ let (zr, zi) = (self.z[n].re, self.z[n].im);
112+ let t = self.post_long[n];
113+ self.z[n] = Complex::new(zr * t.re - zi * t.im, zi * t.re + zr * t.im);
114+ }
115+ // Step 5: windowing and de-interleaving.
116+ let (y, x) = (&self.z, &mut self.x);
117+ for n in 0..64 {
118+ x[2 * n] = -y[64 + n].im * WINDOW[2 * n];
119+ x[2 * n + 1] = y[63 - n].re * WINDOW[2 * n + 1];
120+ x[128 + 2 * n] = -y[n].re * WINDOW[128 + 2 * n];
121+ x[128 + 2 * n + 1] = y[127 - n].im * WINDOW[128 + 2 * n + 1];
122+ x[256 + 2 * n] = -y[64 + n].re * WINDOW[255 - 2 * n];
123+ x[256 + 2 * n + 1] = y[63 - n].im * WINDOW[254 - 2 * n];
124+ x[384 + 2 * n] = y[n].im * WINDOW[127 - 2 * n];
125+ x[384 + 2 * n + 1] = -y[127 - n].re * WINDOW[126 - 2 * n];
126+ }
127+ }
128+
129+ fn short_transform(&mut self, coeffs: &[f32]) {
130+ // Step 1-2: split the coefficients even/odd, then pre-twiddle each.
131+ for k in 0..64 {
132+ let (a1, b1) = (coeffs[2 * (127 - 2 * k)], coeffs[2 * (2 * k)]);
133+ let (a2, b2) = (coeffs[2 * (127 - 2 * k) + 1], coeffs[2 * (2 * k) + 1]);
134+ let t = self.pre_short[k];
135+ self.z[k] = Complex::new(a1 * t.re - b1 * t.im, b1 * t.re + a1 * t.im);
136+ self.z2[k] = Complex::new(a2 * t.re - b2 * t.im, b2 * t.re + a2 * t.im);
137+ }
138+ // Step 3: two N/8-point complex IFFTs.
139+ self.short.inverse(&mut self.z[..64]);
140+ self.short.inverse(&mut self.z2);
141+ // Step 4: post-twiddle both.
142+ for n in 0..64 {
143+ let t = self.post_short[n];
144+ let (zr, zi) = (self.z[n].re, self.z[n].im);
145+ self.z[n] = Complex::new(zr * t.re - zi * t.im, zi * t.re + zr * t.im);
146+ let (zr, zi) = (self.z2[n].re, self.z2[n].im);
147+ self.z2[n] = Complex::new(zr * t.re - zi * t.im, zi * t.re + zr * t.im);
148+ }
149+ // Step 5: windowing and de-interleaving.
150+ let (y1, y2, x) = (&self.z, &self.z2, &mut self.x);
151+ for n in 0..64 {
152+ x[2 * n] = -y1[n].im * WINDOW[2 * n];
153+ x[2 * n + 1] = y1[63 - n].re * WINDOW[2 * n + 1];
154+ x[128 + 2 * n] = -y1[n].re * WINDOW[128 + 2 * n];
155+ x[128 + 2 * n + 1] = y1[63 - n].im * WINDOW[128 + 2 * n + 1];
156+ x[256 + 2 * n] = -y2[n].re * WINDOW[255 - 2 * n];
157+ x[256 + 2 * n + 1] = y2[63 - n].im * WINDOW[254 - 2 * n];
158+ x[384 + 2 * n] = y2[n].im * WINDOW[127 - 2 * n];
159+ x[384 + 2 * n + 1] = -y2[63 - n].re * WINDOW[126 - 2 * n];
160+ }
161+ }
162+}
163+
164+/// A single MDCT coefficient's worth of energy, used by the round-trip test
165+/// below and by nothing else: the forward transform the standard's encoder
166+/// side describes, at the one length the test needs.
167+#[cfg(test)]
168+fn forward_mdct_512(input: &[f32], out: &mut [f32]) {
169+ use std::f64::consts::PI;
170+ let n = 512.0;
171+ for (k, o) in out.iter_mut().enumerate().take(256) {
172+ let mut acc = 0.0f64;
173+ for (i, &s) in input.iter().enumerate().take(512) {
174+ let angle = 2.0 * PI / n * (i as f64 + 0.5 + n / 4.0) * (k as f64 + 0.5);
175+ acc += f64::from(s) * f64::from(WINDOW[window_index(i)]) * angle.cos();
176+ }
177+ *o = (-acc * 2.0 / n) as f32;
178+ }
179+}
180+
181+#[cfg(test)]
182+fn window_index(i: usize) -> usize {
183+ if i < 256 { i } else { 511 - i }
184+}
185+
186+#[cfg(test)]
187+mod tests {
188+ use super::*;
189+
190+ #[test]
191+ fn long_blocks_reconstruct_under_overlap_add() {
192+ // Feed two overlapping windowed transforms of one signal and check the
193+ // overlap-add of their inverses returns the middle 256 samples. This is
194+ // the property the whole §7.9.4 factorisation exists to have; getting a
195+ // sign or an index wrong in step 5 destroys it.
196+ let signal: Vec<f32> = (0..768)
197+ .map(|n| (n as f32 * 0.077).sin() * 0.4 + (n as f32 * 0.31).cos() * 0.2)
198+ .collect();
199+ let mut spec_a = [0.0f32; 256];
200+ let mut spec_b = [0.0f32; 256];
201+ forward_mdct_512(&signal[0..512], &mut spec_a);
202+ forward_mdct_512(&signal[256..768], &mut spec_b);
203+
204+ let mut imdct = Imdct::new();
205+ let mut delay = [0.0f32; 256];
206+ let mut out = [0.0f32; 256];
207+ imdct.block(&spec_a, false, &mut delay, &mut out);
208+ imdct.block(&spec_b, false, &mut delay, &mut out);
209+ for n in 0..256 {
210+ let want = signal[256 + n];
211+ assert!(
212+ (out[n] - want).abs() < 2e-3,
213+ "n = {n}: {} vs {want}",
214+ out[n]
215+ );
216+ }
217+ }
218+
219+ #[test]
220+ fn short_blocks_produce_the_same_energy_as_the_signal() {
221+ // A block-switched pair of 256-point transforms has no closed-form
222+ // reference here, so the check is the weaker but still load-bearing
223+ // one: a single non-zero coefficient must produce a bounded, non-silent
224+ // output, and silence must stay silent.
225+ let mut imdct = Imdct::new();
226+ let mut delay = [0.0f32; 256];
227+ let mut out = [0.0f32; 256];
228+ let mut spec = [0.0f32; 256];
229+ spec[40] = 0.5;
230+ imdct.block(&spec, true, &mut delay, &mut out);
231+ let energy: f32 = out.iter().map(|v| v * v).sum();
232+ assert!(energy > 1e-6, "block-switched output is silent");
233+ assert!(out.iter().all(|v| v.abs() < 4.0));
234+
235+ let mut silent_delay = [0.0f32; 256];
236+ imdct.block(&[0.0; 256], true, &mut silent_delay, &mut out);
237+ assert!(out.iter().all(|v| *v == 0.0));
238+ }
239+}