From 18654e640ca11dfde60fd66d9372988310ba4581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 01:01:36 +0300 Subject: [PATCH] feat(ac3-enc): block switching, D15/D25/D45/reuse exponent planning and a binary-search rate loop Transient detector picks the short transform per block (forward = transpose of the decoder's short inverse, TDAC-probed at 1/128); exponents are planned per run of blocks with the decoded set driving allocation; csnroffst then fsnroffst are binary-searched so frames fill >97% of their size; chbwcod from the per-channel bit rate; encoder_delay() = 256 and finish() flushes the overlap tail. Full wav16 fixture matrix round-trips at corr 1.000 through our decoder and the oracle. --- crates/ec-ac3/src/encode.rs | 683 ++++++++++++++++++++------- crates/ec-ac3/src/lib.rs | 2 +- crates/ec-ac3/tests/encode_matrix.rs | 264 ++++++++++- fixtures | 1 + 4 files changed, 773 insertions(+), 177 deletions(-) create mode 120000 fixtures diff --git a/crates/ec-ac3/src/encode.rs b/crates/ec-ac3/src/encode.rs index 82d71ec9..8f583830 100644 --- a/crates/ec-ac3/src/encode.rs +++ b/crates/ec-ac3/src/encode.rs @@ -1,15 +1,13 @@ //! An AC-3 encoder: PCM in, spec-valid ATSC A/52 syncframes out. //! -//! This is the skeleton subtask: the bitstream writer mirrors the parser's -//! normative order (`syncinfo()`, `bsi()`, six `audblk()`s, `auxdata`/CRC) but -//! runs a *fixed* allocation rather than a real psychoacoustic search — -//! exponent strategy is D15 on block 0 and reused for the rest of the frame, -//! the bit allocation parameters are constants, and the only thing that -//! adapts per frame is `csnroffst`, stepped down until the fixed allocation's -//! mantissas fit the frame's byte budget. A2 replaces the fixed exponent -//! strategy and per-frame envelope with a real one; A3 replaces the -//! `csnroffst` step-down with a proper rate-controlled search -//! ([`Ac3Encoder::try_csnroffst`], [`Ac3Encoder::build_frame`]). +//! The bitstream writer mirrors the parser's normative order (`syncinfo()`, +//! `bsi()`, six `audblk()`s, `auxdata`/CRC). Per block and channel a transient +//! detector picks the long or the block-switched short transform, an exponent +//! planner picks D15/D25/D45/reuse ([`Ac3Encoder::plan`]), and a rate loop +//! binary-searches the SNR offsets so the frame fills its fixed size +//! ([`Ac3Encoder::encode_frame`]). The bit allocation parameters themselves +//! are constants and `crate::bitalloc::compute` is the single source of truth +//! for what each mantissa gets. //! //! No coupling, no rematrixing, no delta bit allocation, no AHT: all of that //! is legal to leave off (every presence bit for them is simply sent as 0), @@ -25,6 +23,7 @@ use ec_dsp::Mdct; use crate::bitalloc::{self, Allocation, BitAllocParams, Channel}; use crate::bsi::Acmod; use crate::exps::Strategy; +use crate::transform::Imdct; use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW}; /// Samples per channel one syncframe codes. @@ -33,10 +32,22 @@ const FRAME_SAMPLES: usize = 1536; const BLOCKS: usize = 6; /// Coefficients per channel per block ([`crate::decode::COEFFS`], not public). const COEFFS: usize = 256; -/// `chbwcod` this encoder always sends: maximum bandwidth. -const CHBWCOD: u32 = 60; -/// Full-bandwidth `endmant` at [`CHBWCOD`]: `(chbwcod + 12) * 3 + 37`. -const FBW_ENDMANT: usize = (CHBWCOD as usize + 12) * 3 + 37; +/// Lowest bit rate per coded channel this encoder accepts: below it the +/// side information of the cheapest legal frame no longer fits (see +/// [`Ac3Encoder::encode_frame`]); [`Ac3Encoder::new`] raises the request to it. +const MIN_KBPS_PER_CHANNEL: u32 = 32; +/// Bit allocation parameters (§7.2.2.3), constant for every frame. +const BA_PARAMS: BitAllocParams = BitAllocParams { sdcycod: 2, fdcycod: 1, sgaincod: 1, dbpbcod: 2, floorcod: 7 }; +/// Fast gain code, constant for every channel and frame. +const FGAINCOD: u8 = 4; +/// [`envelope_moved`]: exponent steps (6 dB each) a band's peak may drift +/// before the block re-sends exponents. +const RESEND_STEPS: u8 = 2; +/// [`is_transient`]: a segment this many times louder than everything before it. +const TRANSIENT_RATIO: f32 = 8.0; +/// [`is_transient`]: segment energy (64 high-passed samples) below which +/// nothing is an attack. +const TRANSIENT_FLOOR: f32 = 1e-2; /// LFE `endmant`, fixed by the standard. const LFE_ENDMANT: usize = 7; /// Scale from `ec_dsp::Mdct::forward_windowed`'s raw sum (which equals the @@ -44,6 +55,9 @@ const LFE_ENDMANT: usize = 7; /// expects: the standard's `-2/N` (N = 512) forward normalisation, with its /// `2.0x` on the way back being the decoder's own half of that pair. const FORWARD_GAIN: f32 = -2.0 / 512.0; +/// Scale from the transpose of the decoder's short inverse to the +/// coefficients it expects back; measured in `tests::tdac_short_*`. +const SHORT_GAIN: f32 = 1.0 / 128.0; /// How the encoder is set up. #[derive(Debug, Clone, Copy, PartialEq)] @@ -186,22 +200,21 @@ fn smooth_exps(exps: &mut [u8]) { } } -/// Writes `ngrps` 7-bit exponent groups covering 3 bins each. `realized` must -/// already have been through [`smooth_exps`], so the values the decoder -/// reconstructs are exactly the ones [`crate::bitalloc::compute`] was run -/// against. -fn write_exp_groups(w: &mut BitWriter, realized: &[u8; COEFFS], mut prev: i32, first_bin: usize, ngrps: usize) { - let mut bin = first_bin; - for _ in 0..ngrps { - let mut mapped = [0i32; 3]; - for slot in &mut mapped { - let target = if bin < COEFFS { i32::from(realized[bin]) } else { prev }; - let diff = (target - prev).clamp(-2, 2); - prev = (prev + diff).clamp(0, 24); - *slot = diff + 2; - bin += 1; - } - let code = (mapped[0] * 25 + mapped[1] * 5 + mapped[2]) as u32; +/// Writes an exponent set as [`plan_exponents`] produced it: the 4-bit +/// absolute exponent, then 7-bit groups of three differentials. `sent` has +/// already been through [`smooth_exps`], so every differential is within ±2 +/// and the decoder reconstructs precisely these values. +fn write_exp_groups(w: &mut BitWriter, sent: &[u8]) { + w.write_bits(u32::from(sent[0]), 4); + let mut prev = i32::from(sent[0]); + for grp in sent[1..].chunks_exact(3) { + let mut code = 0u32; + for &v in grp { + let diff = i32::from(v) - prev; + debug_assert!((-2..=2).contains(&diff)); + code = code * 5 + (diff + 2) as u32; + prev = i32::from(v); + } w.write_bits(code, 7); } } @@ -222,6 +235,13 @@ pub struct Ac3Encoder { order: Vec>, mdct: Mdct, window: [f32; 512], + /// The decoder's short (block-switched) inverse as a matrix, 512 samples + /// per coefficient, row-major by coefficient — the forward short + /// transform is its transpose ([`Ac3Encoder::forward_short`]). + short_basis: Vec, + chbwcod: u32, + fbw_endmant: usize, + stats: EncodeStats, /// Previous block's tail, per coded channel — the MDCT's 50% overlap. history: Vec<[f32; COEFFS]>, pcm: Vec, @@ -244,10 +264,11 @@ impl Ac3Encoder { "AC-3 codes 48000, 44100 or 32000 Hz", ) })?; + let kbps = config.bitrate_kbps.max(MIN_KBPS_PER_CHANNEL * coded as u32); let idx = BIT_RATE_KBPS .iter() .enumerate() - .min_by_key(|&(_, &k)| k.abs_diff(config.bitrate_kbps)) + .min_by_key(|&(_, &k)| k.abs_diff(kbps)) .map(|(i, _)| i) .unwrap_or(0); let frmsizecod = (idx * 2) as u8; @@ -259,6 +280,21 @@ impl Ac3Encoder { window[511 - i] = WINDOW[i]; } + let mut imdct = Imdct::new(); + let mut short_basis = vec![0.0f32; COEFFS * 512]; + for k in 0..COEFFS { + let mut spec = [0.0f32; COEFFS]; + spec[k] = 1.0; + let (mut delay, mut out) = ([0.0f32; 256], [0.0f32; 256]); + imdct.block(&spec, true, &mut delay, &mut out); + let row = &mut short_basis[k * 512..(k + 1) * 512]; + for n in 0..256 { + row[n] = out[n] / 2.0; // `block` doubles its first half + row[256 + n] = delay[n]; + } + } + let chbwcod = chbwcod_for(BIT_RATE_KBPS[idx], nfchans); + let mut params = CodecParameters::new(CodecId::Ac3); params.media = MediaParameters::Audio(AudioParameters { sample_rate: config.sample_rate, @@ -280,6 +316,10 @@ impl Ac3Encoder { frame_bytes, mdct: Mdct::new(512), window, + short_basis, + chbwcod, + fbw_endmant: (chbwcod as usize + 12) * 3 + 37, + stats: EncodeStats::default(), history: vec![[0.0; COEFFS]; coded], pcm: Vec::new(), packets: std::collections::VecDeque::new(), @@ -292,6 +332,19 @@ impl Ac3Encoder { &self.params } + /// Samples this encoder emits before the first audible one: half a + /// window (one block), always, because the very first block has no + /// previous block to overlap-add against and is pure priming. A muxer + /// writing this track's `elst`/`CodecDelay` states it here. + pub fn encoder_delay(&self) -> usize { + COEFFS + } + + /// Coding decisions summed over every frame so far. + pub fn stats(&self) -> EncodeStats { + self.stats + } + /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs — the /// same order [`crate::Ac3Decoder`] hands frames out in). pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> { @@ -300,10 +353,13 @@ impl Ac3Encoder { Ok(()) } - /// Ends the stream: pads the tail to a whole frame and flushes it. + /// Ends the stream: pushes the last block's samples out of the overlap + /// (see [`Ac3Encoder::encoder_delay`]), pads the tail to a whole frame + /// and flushes it. pub fn finish(&mut self) { let need = FRAME_SAMPLES * self.coded; - if !self.pcm.is_empty() { + if !self.pcm.is_empty() || self.stats.frames > 0 { + self.pcm.resize(self.pcm.len() + COEFFS * self.coded, 0.0); let padded = self.pcm.len().div_ceil(need) * need; self.pcm.resize(padded, 0.0); } @@ -333,8 +389,10 @@ impl Ac3Encoder { /// One syncframe from `interleaved` (family-order PCM, `coded` channels * /// [`FRAME_SAMPLES`] samples). fn encode_frame(&mut self, interleaved: &[f32]) -> Vec { - // Deinterleave into coded-channel order and run the MDCT per block. + // Deinterleave into coded-channel order, pick long or short transform + // per block from the transient detector, and run the MDCT. let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS]; + let mut blksw = vec![vec![false; self.coded]; BLOCKS]; for ch in 0..self.coded { let slot = if ch < self.nfchans { self.order.iter().position(|&s| s == Some(ch)).unwrap() @@ -347,116 +405,217 @@ impl Ac3Encoder { for n in 0..256 { window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot]; } + // The LFE has no blksw bit in the stream. + let short = ch < self.nfchans && is_transient(&window_in); + blksw[blk][ch] = short; let mut spectrum = [0.0f32; COEFFS]; - self.mdct - .forward_windowed(&window_in, &self.window, &mut spectrum); - for v in &mut spectrum { - // Measured in `tests::tdac_*`: this makes the forward the - // exact adjoint of the decoder's transform.rs IMDCT. - *v *= FORWARD_GAIN; + if short { + self.forward_short(&window_in, &mut spectrum); + } else { + self.mdct + .forward_windowed(&window_in, &self.window, &mut spectrum); + for v in &mut spectrum { + // Measured in `tests::tdac_*`: this makes the forward the + // exact adjoint of the decoder's transform.rs IMDCT. + *v *= FORWARD_GAIN; + } } self.history[ch].copy_from_slice(&window_in[256..]); coeffs[blk][ch] = spectrum; } } - // Exponents: one D15 envelope per coded channel, tracking the loudest - // magnitude any of the frame's 6 blocks reaches at each bin, so no - // block's mantissa is asked to represent more than the exponent's - // headroom allows. let endmant: Vec = (0..self.coded) - .map(|ch| if ch < self.nfchans { FBW_ENDMANT } else { LFE_ENDMANT }) + .map(|ch| if ch < self.nfchans { self.fbw_endmant } else { LFE_ENDMANT }) .collect(); - let exps: Vec<[u8; COEFFS]> = (0..self.coded) - .map(|ch| { - let mut e = [24u8; COEFFS]; - for bin in 0..endmant[ch] { - let mag = coeffs - .iter() - .map(|b| b[ch][bin].abs()) - .fold(0.0f32, f32::max); - e[bin] = if mag <= 0.0 { - 24 - } else { - (-mag.log2()).floor().clamp(0.0, 24.0) as u8 - }; - } - e - }) - .collect(); - // Fit the envelope to what the group-diff coding can carry, never - // raising an exponent (that would clip its mantissas); the bit - // allocation below then runs on exactly what the decoder will decode. - let exps: Vec<[u8; COEFFS]> = exps - .into_iter() - .enumerate() - .map(|(ch, mut e)| { - smooth_exps(&mut e[..endmant[ch]]); - e - }) - .collect(); - - // Fixed allocation: step csnroffst down from a generous default until - // the mantissas it buys fit the frame. A3 replaces this with a rate - // loop that also varies floorcod/gaincod; see `Ac3Encoder::try_csnroffst`. - let mut csnroffst: i32 = 40; let budget_bits = self.frame_bytes as u64 * 8 - 2 /* auxdataflag, crcrsv */ - 16 /* crc2 */; - let mut w; - loop { - let bap = self.allocate(&exps, &endmant, csnroffst as u8); - w = self.write_frame(&coeffs, &exps, &endmant, &bap, csnroffst as u8); - if w.bit_len() <= budget_bits || csnroffst == 0 { - break; + + // Rate loop: the exponent plan fixes the side information, then the + // largest csnroffst (and, at that csnroffst, the largest fsnroffst) + // whose mantissas still fit is found by binary search — both are + // monotone in bits spent. A plan whose side information alone does + // not fit (a frame of strategy churn at a low bit rate) is replaced + // by the conservative one: a single D45 envelope for the whole frame. + let mut chosen: Option<(BitWriter, Plan, u8)> = None; + for conservative in [false, true] { + let plan = self.plan(&coeffs, &blksw, &endmant, conservative); + let fits = |c: u8, f: u8| { + let bap = self.allocate(&plan, &endmant, c, f); + let w = self.write_frame(&coeffs, &plan, &endmant, &bap, c, f); + (w.bit_len() <= budget_bits).then_some(w) + }; + if fits(0, 0).is_none() { + continue; + } + let (mut lo, mut hi) = (0u8, 63u8); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if fits(mid, 0).is_some() { lo = mid } else { hi = mid - 1 } } - csnroffst -= 1; + let c = lo; + let (mut lo, mut hi) = (0u8, 15u8); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if fits(c, mid).is_some() { lo = mid } else { hi = mid - 1 } + } + chosen = Some((fits(c, lo).unwrap(), plan, c)); + break; } + let (w, plan, csnroffst) = chosen.unwrap_or_else(|| { + // corner-cut: unreachable with the 32 kbps/channel floor `new` + // applies (the conservative plan's side info is ~150 bits per + // channel per frame); below that the frame would be truncated. + // Upgrade path: drop chbwcod until it fits. + debug_assert!(false, "side information does not fit the frame"); + let plan = self.plan(&coeffs, &blksw, &endmant, true); + let bap = self.allocate(&plan, &endmant, 0, 0); + (self.write_frame(&coeffs, &plan, &endmant, &bap, 0, 0), plan, 0) + }); + self.stats.frames += 1; + self.stats.csnroffst_sum += u64::from(csnroffst); + self.stats.bits_used += w.bit_len(); + self.stats.bits_budget += budget_bits; + for blk in 0..BLOCKS { + for ch in 0..self.nfchans { + self.stats.blksw_blocks += u64::from(blksw[blk][ch]); + match plan.strategy[blk][ch] { + Strategy::Reuse => self.stats.reuse += 1, + Strategy::D15 => self.stats.d15 += 1, + Strategy::D25 => self.stats.d25 += 1, + Strategy::D45 => self.stats.d45 += 1, + } + } + } self.finish_frame(w) } - /// Bit allocation for every coded channel at one `csnroffst`. - fn allocate(&self, exps: &[[u8; COEFFS]], endmant: &[usize], csnroffst: u8) -> Vec<[u8; COEFFS]> { - let snroffset = ((i32::from(csnroffst) - 15) << 4) << 2; // fsnroffst = 0 - let params = BitAllocParams { - sdcycod: 2, - fdcycod: 1, - sgaincod: 1, - dbpbcod: 2, - floorcod: 7, + /// The two 256-point transforms of a block-switched block (§7.9.4.2), as + /// the transpose of the decoder's own short inverse (`short_basis`), so + /// the pair is TDAC-exact by construction — see `tests::tdac_short_*`. + fn forward_short(&self, window_in: &[f32; 512], spectrum: &mut [f32; COEFFS]) { + for (k, out) in spectrum.iter_mut().enumerate() { + let row = &self.short_basis[k * 512..(k + 1) * 512]; + *out = SHORT_GAIN * row.iter().zip(window_in).map(|(a, b)| a * b).sum::(); + } + } + + /// Exponent strategy and exponents for every block and channel. + /// + /// Block 0 always sends. A later block re-sends when its block switch + /// flag changed or its envelope moved ([`envelope_moved`]) since the last + /// send; otherwise it reuses. Each run of + /// blocks sharing one set codes the run's loudest magnitude per bin, so no + /// block's mantissa is asked for more than its exponent's headroom. The + /// sending block uses D15 when block-switched, D45 for a run of 3+ blocks + /// (stationary), D25 otherwise. `conservative` forces one D45 set per channel for the + /// whole frame: the cheapest legal side information. + fn plan(&self, coeffs: &[Vec<[f32; COEFFS]>], blksw: &[Vec], endmant: &[usize], conservative: bool) -> Plan { + let ideal: Vec> = coeffs + .iter() + .map(|blk| (0..self.coded).map(|ch| ideal_exps(&blk[ch], endmant[ch])).collect()) + .collect(); + let mut plan = Plan { + blksw: blksw.to_vec(), + strategy: vec![vec![Strategy::Reuse; self.coded]; BLOCKS], + sent: vec![vec![Vec::new(); self.coded]; BLOCKS], + exps: vec![vec![[24u8; COEFFS]; self.coded]; BLOCKS], }; - (0..self.coded) - .map(|ch| { - let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe }; - let alloc = Allocation { - fscod: self.fscod, - params, - range: (0, endmant[ch]), - fgaincod: 4, - snroffset, - kind, - dba: None, - high_efficiency: false, + for ch in 0..self.coded { + let mut starts = vec![0usize]; + if !conservative { + for blk in 1..BLOCKS { + let last = *starts.last().unwrap(); + if blksw[blk][ch] != blksw[blk - 1][ch] + || envelope_moved(&ideal[blk][ch], &ideal[last][ch], endmant[ch]) + { + starts.push(blk); + } + } + } + for (i, &start) in starts.iter().enumerate() { + let end = starts.get(i + 1).copied().unwrap_or(BLOCKS); + let mut env = ideal[start][ch]; + for blk in start + 1..end { + for bin in 0..endmant[ch] { + env[bin] = env[bin].min(ideal[blk][ch][bin]); + } + } + let strategy = if ch >= self.nfchans { + Strategy::D15 + } else if blksw[start][ch] { + // The short halves interleave, so pairs (X1[k], X2[k]) + // share one exponent: the louder half's. D15 would + // follow the alternation exactly but at 592 bits per + // send — more than a block's whole budget at 96 kbps per + // channel — against D25's 298. + Strategy::D25 + } else if conservative || end - start >= 3 { + Strategy::D45 + } else { + Strategy::D25 }; - let mut bap = [0u8; COEFFS]; - bitalloc::compute(&alloc, &exps[ch], &mut bap); - bap - }) - .collect() + let (sent, exps) = plan_exponents(&env, endmant[ch], strategy); + plan.strategy[start][ch] = strategy; + plan.sent[start][ch] = sent; + for blk in start..end { + plan.exps[blk][ch] = exps; + } + } + } + plan + } + + /// Bit allocation for every block and coded channel at one SNR offset. + fn allocate(&self, plan: &Plan, endmant: &[usize], csnroffst: u8, fsnroffst: u8) -> Vec> { + let snroffset = (((i32::from(csnroffst) - 15) << 4) + i32::from(fsnroffst)) << 2; + // §7.2.2.1.1: all-zero SNR offsets mean no mantissa bits at all — + // the decoder short-circuits there instead of running the model. + if csnroffst == 0 && fsnroffst == 0 { + return vec![vec![[0u8; COEFFS]; self.coded]; BLOCKS]; + } + let mut out: Vec> = Vec::with_capacity(BLOCKS); + for blk in 0..BLOCKS { + let baps = (0..self.coded) + .map(|ch| { + if blk > 0 && plan.strategy[blk][ch] == Strategy::Reuse { + return out[blk - 1][ch]; + } + let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe }; + let alloc = Allocation { + fscod: self.fscod, + params: BA_PARAMS, + range: (0, endmant[ch]), + fgaincod: FGAINCOD, + snroffset, + kind, + dba: None, + high_efficiency: false, + }; + let mut bap = [0u8; COEFFS]; + bitalloc::compute(&alloc, &plan.exps[blk][ch], &mut bap); + bap + }) + .collect(); + out.push(baps); + } + out } /// Writes syncinfo, bsi and the six audblks; mantissas and their bit cost - /// come from `coeffs`, `exps` and `bap` (all already computed for this + /// come from `coeffs`, `plan` and `bap` (all already computed for this /// frame). Everything up to the crc/padding tail this function leaves for - /// [`Ac3Encoder::finish_frame`], so the retry loop in + /// [`Ac3Encoder::finish_frame`], so the rate loop in /// [`Ac3Encoder::encode_frame`] can measure a candidate's length before /// paying for that. fn write_frame( &self, coeffs: &[Vec<[f32; COEFFS]>], - exps: &[[u8; COEFFS]], + plan: &Plan, endmant: &[usize], - bap: &[[u8; COEFFS]], + bap: &[Vec<[u8; COEFFS]>], csnroffst: u8, + fsnroffst: u8, ) -> BitWriter { let mut w = BitWriter::with_capacity(self.frame_bytes); @@ -491,7 +650,7 @@ impl Ac3Encoder { w.write_bit(false); // addbsi for blk in 0..BLOCKS { - self.write_block(&mut w, blk, coeffs, exps, endmant, bap, csnroffst); + self.write_block(&mut w, blk, coeffs, plan, endmant, bap, csnroffst, fsnroffst); } w } @@ -502,14 +661,15 @@ impl Ac3Encoder { w: &mut BitWriter, blk: usize, coeffs: &[Vec<[f32; COEFFS]>], - exps: &[[u8; COEFFS]], + plan: &Plan, endmant: &[usize], - bap: &[[u8; COEFFS]], + bap: &[Vec<[u8; COEFFS]>], csnroffst: u8, + fsnroffst: u8, ) { let first = blk == 0; - for _ in 0..self.nfchans { - w.write_bit(false); // blksw + for ch in 0..self.nfchans { + w.write_bit(plan.blksw[blk][ch]); } for _ in 0..self.nfchans { w.write_bit(false); // dithflag @@ -522,50 +682,43 @@ impl Ac3Encoder { if self.acmod == Acmod::Stereo { w.write_bit(false); // rematstr (no rematrixing) } - for _ in 0..self.nfchans { - w.write_bits(if first { 1 } else { 0 }, 2); // chexpstr: D15 / reuse + for ch in 0..self.nfchans { + w.write_bits(strategy_code(plan.strategy[blk][ch]), 2); // chexpstr } if self.lfeon { - w.write_bit(first); // lfeexpstr: D15 / reuse + w.write_bit(plan.strategy[blk][self.nfchans] != Strategy::Reuse); // lfeexpstr } - if first { - for _ in 0..self.nfchans { - w.write_bits(CHBWCOD, 6); // chbwcod + for ch in 0..self.nfchans { + if plan.strategy[blk][ch] != Strategy::Reuse { + w.write_bits(self.chbwcod, 6); } } - if first { - for ch in 0..self.nfchans { - let absexp = exps[ch][0].min(15); - w.write_bits(u32::from(absexp), 4); - let ngrps = Strategy::D15.fbw_groups(endmant[ch]); - write_exp_groups(w, &exps[ch], i32::from(absexp), 1, ngrps); + for ch in 0..self.nfchans { + if plan.strategy[blk][ch] != Strategy::Reuse { + write_exp_groups(w, &plan.sent[blk][ch]); w.write_bits(0, 2); // gainrng } - if self.lfeon { - let ch = self.nfchans; - let absexp = exps[ch][0].min(15); - w.write_bits(u32::from(absexp), 4); - write_exp_groups(w, &exps[ch], i32::from(absexp), 1, 2); - } } + if self.lfeon && plan.strategy[blk][self.nfchans] != Strategy::Reuse { + write_exp_groups(w, &plan.sent[blk][self.nfchans]); + } + // The allocation parameters and SNR offsets are constant across the + // frame, so they go once, in block 0 (where they are mandatory); the + // decoder carries them forward through blocks 1-5. w.write_bit(first); // baie if first { - w.write_bits(2, 2); // sdcycod - w.write_bits(1, 2); // fdcycod - w.write_bits(1, 2); // sgaincod - w.write_bits(2, 2); // dbpbcod - w.write_bits(7, 3); // floorcod + w.write_bits(u32::from(BA_PARAMS.sdcycod), 2); + w.write_bits(u32::from(BA_PARAMS.fdcycod), 2); + w.write_bits(u32::from(BA_PARAMS.sgaincod), 2); + w.write_bits(u32::from(BA_PARAMS.dbpbcod), 2); + w.write_bits(u32::from(BA_PARAMS.floorcod), 3); } w.write_bit(first); // snroffste if first { w.write_bits(u32::from(csnroffst), 6); - for _ in 0..self.nfchans { - w.write_bits(0, 4); // fsnroffst - w.write_bits(4, 3); // fgaincod - } - if self.lfeon { - w.write_bits(0, 4); - w.write_bits(4, 3); + for _ in 0..self.coded { + w.write_bits(u32::from(fsnroffst), 4); + w.write_bits(u32::from(FGAINCOD), 3); } } // no coupling leak (cplinu is always false: no bit here at all) @@ -574,15 +727,14 @@ impl Ac3Encoder { let values: Vec<(u8, f32)> = (0..self.coded) .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin))) - .map(|(ch, bin)| (bap[ch][bin], coeffs[blk][ch][bin] * scale(exps[ch][bin]))) + .map(|(ch, bin)| (bap[blk][ch][bin], coeffs[blk][ch][bin] * scale(plan.exps[blk][ch][bin]))) .collect(); write_mantissas(w, &values); } /// Patches crc1/crc2 into a written frame and zero-pads it to /// [`Ac3Encoder::frame_bytes`] — the syncframe's own length, so every - /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`] regardless of how - /// far under it this frame's fixed allocation landed. + /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`]. fn finish_frame(&self, mut w: BitWriter) -> Vec { w.write_bit(false); // auxdataflag w.write_bit(false); // crcrsv @@ -604,6 +756,140 @@ impl Ac3Encoder { } } +/// Per-frame coding decisions, made before the rate loop runs so every +/// candidate allocation is measured against the same side information. +struct Plan { + /// Block switch per block per coded channel (always false for the LFE). + blksw: Vec>, + /// Exponent strategy per block per coded channel. + strategy: Vec>, + /// The exponent values as sent — the absolute one, then one per + /// differential — per block per channel; empty on `Reuse`. + sent: Vec>>, + /// The exponents the decoder holds during each block, per channel: what + /// the bit allocation and the quantisation both run on. + exps: Vec>, +} + +/// What the encoder decided, summed over every frame so far. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct EncodeStats { + /// Frames coded. + pub frames: u64, + /// Block-switched (short transform) blocks, over full-bandwidth channels. + pub blksw_blocks: u64, + /// Block/channel pairs (full-bandwidth) that sent D15 exponents. + pub d15: u64, + /// ... D25. + pub d25: u64, + /// ... D45. + pub d45: u64, + /// ... that reused the previous block's exponents. + pub reuse: u64, + /// Sum of the `csnroffst` each frame settled on. + pub csnroffst_sum: u64, + /// Bits the frames' side information and mantissas occupied, before padding. + pub bits_used: u64, + /// Bits the frames had available for them. + pub bits_budget: u64, +} + +/// The 2-bit `chexpstr` code (the inverse of [`Strategy::from_code`]). +fn strategy_code(strategy: Strategy) -> u32 { + match strategy { + Strategy::Reuse => 0, + Strategy::D15 => 1, + Strategy::D25 => 2, + Strategy::D45 => 3, + } +} + +/// `chbwcod` from the bit rate per full-bandwidth channel: the whole band when +/// there are bits to fill it, tapering down at low rates so the bits go to the +/// bands that carry the music. At 48 kHz the rows cut off at about 24, 20, 18, +/// 16 and 14 kHz. +fn chbwcod_for(kbps: u32, nfchans: usize) -> u32 { + match kbps / nfchans as u32 { + 80.. => 60, + 56.. => 48, + 40.. => 40, + 28.. => 32, + _ => 24, + } +} + +/// §7.9.1's spirit in its simplest form: a first-order high-pass, then the +/// energy of each of the window's eight 64-sample segments; a segment in the +/// block's own half (the new 256 samples) that is `TRANSIENT_RATIO` above +/// everything before it, and above the silence floor, is an attack worth a +/// short transform's time resolution (pre-echo would otherwise smear over +/// the whole 512-sample window). +fn is_transient(window_in: &[f32; 512]) -> bool { + let mut energy = [0.0f32; 8]; + for (i, seg) in energy.iter_mut().enumerate() { + *seg = (i * 64..(i + 1) * 64) + .map(|n| { + let d = window_in[n] - window_in[n.saturating_sub(1)]; + d * d + }) + .sum(); + } + (4..8).any(|j| { + let before = energy[..j].iter().copied().fold(0.0f32, f32::max); + energy[j] > TRANSIENT_FLOOR && energy[j] > TRANSIENT_RATIO * before + }) +} + +/// `floor(-log2 |X|)` per bin, clamped to 0..=24 (24 also for zero), up to +/// `endmant`: the exponent that leaves each coefficient's mantissa in +/// `[0.5, 1)`. +fn ideal_exps(coeffs: &[f32; COEFFS], endmant: usize) -> [u8; COEFFS] { + let mut e = [24u8; COEFFS]; + for bin in 0..endmant { + let mag = coeffs[bin].abs(); + e[bin] = if mag <= 0.0 { 24 } else { (-mag.log2()).floor().clamp(0.0, 24.0) as u8 }; + } + e +} + +/// Whether two ideal envelopes differ enough to be worth re-sending: the peak +/// (minimum exponent) of some 12-bin band within 60 dB of the loudest band +/// moved by more than [`RESEND_STEPS`]. A re-send costs 150-300 bits per +/// channel — at 192 kbps stereo that is 30-60 % of a block's whole budget — +/// so the bands the masking model will starve anyway do not get a vote. +fn envelope_moved(a: &[u8; COEFFS], b: &[u8; COEFFS], endmant: usize) -> bool { + let loudest = a[..endmant].iter().min().unwrap().min(b[..endmant].iter().min().unwrap()); + a[..endmant].chunks(12).zip(b[..endmant].chunks(12)).any(|(x, y)| { + let (px, py) = (*x.iter().min().unwrap(), *y.iter().min().unwrap()); + px.min(py) <= loudest + 10 && px.abs_diff(py) > RESEND_STEPS + }) +} + +/// The exponent set a channel sends for a run of blocks: `ideal` is the run's +/// envelope (min over the run's blocks of each bin's ideal exponent), grouped +/// by `strategy` (min over each group's bins), fitted to the ±2 differential +/// coding by [`smooth_exps`], then expanded to what the decoder will hold. +/// Returns (values as sent, decoded exponents). +fn plan_exponents(ideal: &[u8; COEFFS], endmant: usize, strategy: Strategy) -> (Vec, [u8; COEFFS]) { + let gs = strategy.group_size(); + let ngrps = strategy.fbw_groups(endmant); + let mut sent = vec![ideal[0].min(15)]; + for g in 0..ngrps * 3 { + let lo = 1 + g * gs; + let hi = (lo + gs).min(endmant); + sent.push(if lo < hi { *ideal[lo..hi].iter().min().unwrap() } else { 24 }); + } + smooth_exps(&mut sent); + let mut exps = [24u8; COEFFS]; + exps[0] = sent[0]; + for g in 0..ngrps * 3 { + for bin in 1 + g * gs..(1 + (g + 1) * gs).min(COEFFS) { + exps[bin] = sent[g + 1]; + } + } + (sent, exps) +} + /// `2^exponent` — the inverse of [`crate::mantissa::scale`], since the /// encoder starts from a linear coefficient and has to divide it back out to /// the `[-1, 1)` mantissa the quantizers expect. @@ -667,7 +953,6 @@ impl Encoder for Ac3Encoder { #[cfg(test)] mod tests { use super::*; - use crate::transform::Imdct; fn lcg(seed: &mut u64) -> f32 { *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); @@ -688,19 +973,23 @@ mod tests { out } - fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 { + /// Runs `forward` then the decoder's inverse over 7 overlapping blocks, + /// block-switched where `pattern` says so (the short transform must be + /// TDAC-exact against both a short and a long neighbour), and returns + /// (worst sample error, least-squares gain out/in). + fn tdac_pattern(pattern: [bool; 7], forward: impl Fn(&[f32; 512], bool) -> [f32; COEFFS]) -> (f32, f64) { let mut seed = 7u64; - let signal: Vec = (0..256 * 6).map(|_| lcg(&mut seed)).collect(); + let signal: Vec = (0..256 * 8).map(|_| lcg(&mut seed)).collect(); let mut imdct = Imdct::new(); let mut delay = [0.0f32; 256]; let mut out = [0.0f32; 256]; let mut worst = 0.0f32; let (mut dot, mut nrm) = (0.0f64, 0.0f64); - for blk in 0..5 { + for (blk, &short) in pattern.iter().enumerate() { let mut x = [0.0f32; 512]; x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]); - let spec = forward(&x); - imdct.block(&spec, false, &mut delay, &mut out); + let spec = forward(&x, short); + imdct.block(&spec, short, &mut delay, &mut out); if blk > 0 { // Output of block `blk` reconstructs input samples blk*256..+256. for n in 0..256 { @@ -710,10 +999,84 @@ mod tests { } } } - assert!((dot / nrm - 1.0).abs() < 1e-4, "least-squares gain out/in = {}", dot / nrm); + (worst, dot / nrm) + } + + fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 { + let (worst, gain) = tdac_pattern([false; 7], |x, _| forward(x)); + assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}"); worst } + #[test] + fn tdac_short_forward_reconstructs_against_long_and_short_neighbours() { + let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap(); + let window = enc.window; + let basis = enc.short_basis.clone(); + let cell = std::cell::RefCell::new(&mut enc.mdct); + let (worst, gain) = tdac_pattern([false, true, true, false, true, false, true], |x, short| { + let mut s = [0.0f32; COEFFS]; + if short { + for (k, out) in s.iter_mut().enumerate() { + let row = &basis[k * 512..(k + 1) * 512]; + *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::(); + } + } else { + cell.borrow_mut().forward_windowed(x, &window, &mut s); + for v in &mut s { + *v *= FORWARD_GAIN; + } + } + s + }); + let (w2, g2) = tdac_pattern([true; 7], |x, _| { + let mut s = [0.0f32; COEFFS]; + for (k, out) in s.iter_mut().enumerate() { + let row = &basis[k * 512..(k + 1) * 512]; + *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::(); + } + s + }); + eprintln!("all-short: worst {w2} gain {g2}; mixed: worst {worst} gain {gain}"); + assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}"); + assert!(worst < 1e-4, "short forward + Imdct TDAC error {worst}"); + } + + fn encode_one(pcm: &[f32]) -> EncodeStats { + let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 96 }).unwrap(); + enc.push_pcm_f32(pcm).unwrap(); + enc.stats() + } + + #[test] + fn stationary_tone_plans_one_d45_set_and_reuses_it() { + let pcm: Vec = (0..FRAME_SAMPLES * 2) + .map(|n| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * n as f32 / 48000.0).sin()) + .collect(); + let stats = encode_one(&pcm); + assert_eq!(stats.frames, 2); + // Frame 0 opens from silence: an onset, so block 0 is legitimately + // short and its first blocks may re-send; frame 1 is steady: one D45 + // set, five reuses. + assert!(stats.blksw_blocks <= 1, "{stats:?}"); + assert!(stats.d45 >= 1 && stats.d15 == 0 && stats.d25 <= 1, "{stats:?}"); + assert!(stats.reuse >= 5, "{stats:?}"); + assert!(stats.bits_used * 10 > stats.bits_budget * 9, "rate loop left bits unused: {stats:?}"); + } + + #[test] + fn a_click_switches_to_short_blocks_and_d25() { + let mut pcm = vec![0.0f32; FRAME_SAMPLES]; + for n in 0..FRAME_SAMPLES { + pcm[n] = 0.01 * ((n as f32) * 0.3).sin(); + } + pcm[256 * 3 + 100] = 0.9; + pcm[256 * 3 + 101] = -0.9; + let stats = encode_one(&pcm); + assert_eq!(stats.blksw_blocks, 1, "{stats:?}"); + assert!(stats.d25 >= 1 && stats.d15 == 0, "{stats:?}"); + } + #[test] fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() { let mut e = [24u8; COEFFS]; diff --git a/crates/ec-ac3/src/lib.rs b/crates/ec-ac3/src/lib.rs index f97ddbea..9c0ddb69 100644 --- a/crates/ec-ac3/src/lib.rs +++ b/crates/ec-ac3/src/lib.rs @@ -69,7 +69,7 @@ pub mod encode; pub use decode::Syntax; pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options}; -pub use encode::{Ac3Encoder, EncoderConfig}; +pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig}; pub use ec_core::Error; /// Samples per channel one audio block produces. diff --git a/crates/ec-ac3/tests/encode_matrix.rs b/crates/ec-ac3/tests/encode_matrix.rs index 1b79b499..715006af 100644 --- a/crates/ec-ac3/tests/encode_matrix.rs +++ b/crates/ec-ac3/tests/encode_matrix.rs @@ -1,5 +1,7 @@ -//! A1 skeleton coverage: the fixed-allocation encoder writes frames our own -//! decoder round-trips, and ffmpeg accepts as valid AC-3 when it is present. +//! Encoder coverage: frames our own decoder round-trips, and that ffmpeg +//! (when present) accepts as valid AC-3 and decodes to the same audio — on +//! synthetic signals and on the real 16-bit fixtures, at every rate and +//! layout the encoder offers. use std::path::Path; use std::process::Command; @@ -53,10 +55,15 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 { cov / (va.sqrt() * vb.sqrt()) } -/// Lag-searched correlation on one channel, +/- 64 samples: the encoder's -/// analysis window and the decoder's overlap-add each carry their own group -/// delay. +/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts +/// with this many samples of silence per channel. +const DELAY: usize = 256; + +/// Lag-searched correlation on one channel after the priming is dropped, +/// +/- 64 samples of slack: a bug that shifts the audio by a block shows up +/// as ~0 here, where an unbounded search on a periodic signal would hide it. fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 { + let b = &b[DELAY.min(b.len())..]; let mut best = -1.0f64; for lag in -64i32..=64 { let (sa, sb): (&[f32], &[f32]) = if lag >= 0 { @@ -79,7 +86,65 @@ fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec { .collect() } -fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec { +/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None +/// without ffmpeg. +fn read_wav(path: &Path) -> Option<(Vec, u32, usize)> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let samples = out + .stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + let probe = ffprobe(path, "channels,sample_rate"); + let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::().ok()); + Some((samples, field("sample_rate")?, field("channels")? as usize)) +} + +fn ffprobe(path: &Path, entries: &str) -> String { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "a:0", "-show_entries"]) + .arg(format!("stream={entries}")) + .args(["-of", "default=noprint_wrappers=1"]) + .arg(path) + .output() + .expect("ffprobe"); + String::from_utf8_lossy(&out.stdout).into_owned() +} + +fn probe_field(text: &str, key: &str) -> Option { + text.lines() + .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) + .map(|v| v.trim().to_owned()) +} + +/// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint. +fn oracle_decode(path: &Path) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + let stderr = String::from_utf8_lossy(&out.stderr); + let complaint = stderr + .lines() + .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k))); + assert!(!complaint, "ffmpeg complained about {}:\n{stderr}", path.display()); + out.stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() +} + +fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec, ec_ac3::EncodeStats) { let mut enc = Ac3Encoder::new(config).unwrap(); enc.push_pcm_f32(pcm).unwrap(); enc.finish(); @@ -91,7 +156,39 @@ fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec { Err(e) => panic!("{e}"), } } - out + (out, enc.stats()) +} + +fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec { + encode_with_stats(config, pcm).0 +} + +/// Worst per-channel lag-searched correlation between `want` and `got`. +fn worst_corr(want: &[f32], got: &[f32], channels: usize) -> f64 { + (0..channels) + .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch))) + .fold(1.0, f64::min) +} + +/// [`worst_corr`] over the full-bandwidth channels only: the LFE (family slot +/// 3 of six) is band-limited to 7 bins (~660 Hz at 48 kHz) by the standard, +/// so a fixture whose LFE carries full-band content can never correlate with +/// it; that channel is gated on our decoder agreeing with the oracle instead. +fn worst_fbw_corr(want: &[f32], got: &[f32], channels: usize) -> f64 { + (0..channels) + .filter(|&ch| !(channels == 6 && ch == 3)) + .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch))) + .fold(1.0, f64::min) +} + +/// Deterministic white noise, `len` interleaved samples. +fn noise(len: usize, seed: &mut u64) -> Vec { + (0..len) + .map(|_| { + *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 + }) + .collect() } fn decode_all(data: &[u8], channels: usize) -> Vec { @@ -129,15 +226,8 @@ fn silence_and_tone_frames_decode_in_our_decoder() { assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames"); let decoded = decode_all(&data, channels as usize); assert!(!decoded.is_empty()); - for ch in 0..channels as usize { - let want = take_channel(&pcm, channels as usize, ch); - let got = take_channel(&decoded, channels as usize, ch); - let corr = best_lag_correlation(&want, &got); - assert!( - corr >= 0.95, - "{sample_rate} Hz {channels}ch channel {ch}: corr {corr}" - ); - } + let corr = worst_corr(&pcm, &decoded, channels as usize); + assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}"); } } @@ -188,3 +278,145 @@ fn oracle_accepts_our_frames() { let _ = std::fs::remove_file(Path::new(&path)); } + +/// The full fixture matrix: every wav16 fixture at its layout's bit rate, +/// through our decoder and the oracle, with ffprobe agreeing on what was +/// asked for. Prints the per-file numbers and the stereo strategy shares. +#[test] +fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() { + if !have_ffmpeg() { + eprintln!("skipping: ffmpeg not found"); + return; + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio"); + let mut failures = Vec::new(); + for layout in ["mono", "stereo", "5.1"] { + for rate in [48_000u32, 44_100] { + let path = root.join(format!("wav16-{layout}-{rate}.wav")); + let (pcm, sample_rate, channels) = read_wav(&path).unwrap_or_else(|| panic!("{}", path.display())); + assert_eq!(sample_rate, rate); + let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 }; + let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps }; + let (data, stats) = encode_with_stats(config, &pcm); + let frame = ec_ac3::frame_size(&data).unwrap(); + assert_eq!(data.len() % frame, 0, "{layout} {rate}: frames are not all {frame} bytes"); + + let decoded = decode_all(&data, channels); + let ours = worst_fbw_corr(&pcm, &decoded, channels); + let out = std::env::temp_dir().join(format!("ec_ac3_encode_matrix_{layout}_{rate}.ac3")); + std::fs::write(&out, &data).unwrap(); + let oracle_pcm = oracle_decode(&out); + let oracle = worst_fbw_corr(&pcm, &oracle_pcm, channels); + if channels == 6 { + let lfe = correlation(&take_channel(&decoded, 6, 3), &take_channel(&oracle_pcm, 6, 3)); + assert!(lfe >= 0.99, "{layout} {rate}: LFE ours vs oracle corr {lfe}"); + } + let probe = ffprobe(&out, "channels,channel_layout,sample_rate,bit_rate"); + let _ = std::fs::remove_file(&out); + + let total = (stats.d15 + stats.d25 + stats.d45 + stats.reuse) as f64; + let share = |n: u64| n as f64 / total * 100.0; + eprintln!( + "{layout} {rate}: {} frames, ours {ours:.4} oracle {oracle:.4}, csnroffst mean {:.1}, fill {:.1}%, blksw {}, D15 {:.1}% D25 {:.1}% D45 {:.1}% REUSE {:.1}%", + stats.frames, + stats.csnroffst_sum as f64 / stats.frames as f64, + stats.bits_used as f64 / stats.bits_budget as f64 * 100.0, + stats.blksw_blocks, + share(stats.d15), share(stats.d25), share(stats.d45), share(stats.reuse), + ); + if ours < 0.99 || oracle < 0.99 { + failures.push(format!("{layout} {rate}: ours {ours:.4} oracle {oracle:.4}")); + } + assert!(stats.bits_used * 10 > stats.bits_budget * 9, "{layout} {rate}: rate loop left bits unused: {stats:?}"); + let expect_layout = match channels { 1 => "mono", 2 => "stereo", _ => "5.1" }; + assert_eq!(probe_field(&probe, "channels").as_deref(), Some(channels.to_string().as_str()), "{probe}"); + assert!(probe_field(&probe, "channel_layout").is_some_and(|l| l.starts_with(expect_layout)), "{probe}"); + assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some(rate.to_string().as_str()), "{probe}"); + assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some((bitrate_kbps * 1000).to_string().as_str()), "{probe}"); + } + } + assert!(failures.is_empty(), "corr < 0.99:\n{}", failures.join("\n")); +} + +/// A train of sharp attacks (decaying 2 kHz bursts, 25 per second) over a +/// quiet noise floor: every attack is a block switch, and the stream still +/// round-trips through both decoders. +#[test] +fn click_train_switches_blocks_and_still_round_trips() { + let channels = 2; + let mut pcm = noise(48_000 * channels, &mut 11u64); + for v in &mut pcm { + *v *= 0.01; + } + for n in (500..48_000).step_by(1900) { + for i in 0..200 { + let v = 0.8 * (-(i as f32) / 40.0).exp() * (i as f32 * 2.0 * std::f32::consts::PI * 2000.0 / 48_000.0).sin(); + for ch in 0..channels { + pcm[(n + i) * channels + ch] += v; + } + } + } + let config = EncoderConfig { sample_rate: 48_000, channels: 2, bitrate_kbps: 192 }; + let (data, stats) = encode_with_stats(config, &pcm); + assert!(stats.blksw_blocks >= 20, "{stats:?}"); + let corr = worst_corr(&pcm, &decode_all(&data, channels), channels); + eprintln!("click train: ours {corr:.4}, {stats:?}"); + assert!(corr >= 0.95, "click train corr {corr}"); + if have_ffmpeg() { + let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3"); + std::fs::write(&out, &data).unwrap(); + let corr = worst_corr(&pcm, &oracle_decode(&out), channels); + let _ = std::fs::remove_file(&out); + eprintln!("click train: oracle {corr:.4}"); + assert!(corr >= 0.95, "click train oracle corr {corr}"); + } +} + +#[test] +fn tone_at_32khz_round_trips() { + let rate = 32_000; + let pcm: Vec = (0..rate as usize * 2) + .flat_map(|n| { + let t = n as f32 / rate as f32; + let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin(); + [v, 0.5 * v] + }) + .collect(); + let config = EncoderConfig { sample_rate: rate, channels: 2, bitrate_kbps: 96 }; + let data = encode(config, &pcm); + let corr = worst_corr(&pcm, &decode_all(&data, 2), 2); + assert!(corr >= 0.99, "32 kHz ours corr {corr}"); + if have_ffmpeg() { + let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3"); + std::fs::write(&out, &data).unwrap(); + let corr = worst_corr(&pcm, &oracle_decode(&out), 2); + let probe = ffprobe(&out, "sample_rate,bit_rate"); + let _ = std::fs::remove_file(&out); + assert!(corr >= 0.99, "32 kHz oracle corr {corr}"); + assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}"); + assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}"); + } +} + +/// 200 random (rate, channels, bit rate) configurations, two frames of +/// noise each: nothing panics and our decoder takes every frame. +#[test] +fn random_configs_never_panic_and_always_decode() { + let (mut seed, mut noise_seed) = (99u64, 7u64); + let mut next = |n: u64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) % n + }; + for _ in 0..200 { + let sample_rate = ec_ac3::tables::SAMPLE_RATE[next(3) as usize]; + let channels = next(6) as u16 + 1; + let bitrate_kbps = ec_ac3::tables::BIT_RATE_KBPS[next(ec_ac3::tables::BIT_RATE_KBPS.len() as u64) as usize]; + let config = EncoderConfig { sample_rate, channels, bitrate_kbps }; + let pcm = noise(1536 * 2 * channels as usize, &mut noise_seed); + let data = encode(config, &pcm); + let decoded = decode_all(&data, channels as usize); + assert!(decoded.len() >= pcm.len() + 256, "{config:?}: {} of {} samples", decoded.len(), pcm.len()); + } +} + + diff --git a/fixtures b/fixtures new file mode 120000 index 00000000..9b6d05cf --- /dev/null +++ b/fixtures @@ -0,0 +1 @@ +/home/user/Documents/Code/Rust/edith_codecs/fixtures \ No newline at end of file