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