forge
Explore
Log in

Don't you dare go Hollow

Block switching, D15/D25/D45/reuse exponent planning and a binary-search rate loop

Browse files at this commit

18654e640ca11dfde60fd66d9372988310ba4581Ahmet Kaan GümüşParent: f663ba5
  • feat
    • block switching, D15/D25/D45/reuse exponent planning and a binary-search rate loop
Show full message
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.rsmodified+523 -160
@@ -1,15 +1,13 @@
1 //! An AC-3 encoder: PCM in, spec-valid ATSC A/52 syncframes out.1 //! An AC-3 encoder: PCM in, spec-valid ATSC A/52 syncframes out.
2 //!2 //!
3-//! This is the skeleton subtask: the bitstream writer mirrors the parser's3+//! The bitstream writer mirrors the parser's normative order (`syncinfo()`,
4-//! normative order (`syncinfo()`, `bsi()`, six `audblk()`s, `auxdata`/CRC) but4+//! `bsi()`, six `audblk()`s, `auxdata`/CRC). Per block and channel a transient
5-//! runs a *fixed* allocation rather than a real psychoacoustic search —5+//! detector picks the long or the block-switched short transform, an exponent
6-//! exponent strategy is D15 on block 0 and reused for the rest of the frame,6+//! planner picks D15/D25/D45/reuse ([`Ac3Encoder::plan`]), and a rate loop
7-//! the bit allocation parameters are constants, and the only thing that7+//! binary-searches the SNR offsets so the frame fills its fixed size
8-//! adapts per frame is `csnroffst`, stepped down until the fixed allocation's8+//! ([`Ac3Encoder::encode_frame`]). The bit allocation parameters themselves
9-//! mantissas fit the frame's byte budget. A2 replaces the fixed exponent9+//! are constants and `crate::bitalloc::compute` is the single source of truth
10-//! strategy and per-frame envelope with a real one; A3 replaces the10+//! for what each mantissa gets.
11-//! `csnroffst` step-down with a proper rate-controlled search
12-//! ([`Ac3Encoder::try_csnroffst`], [`Ac3Encoder::build_frame`]).
13 //!11 //!
14 //! No coupling, no rematrixing, no delta bit allocation, no AHT: all of that12 //! No coupling, no rematrixing, no delta bit allocation, no AHT: all of that
15 //! is legal to leave off (every presence bit for them is simply sent as 0),13 //! is legal to leave off (every presence bit for them is simply sent as 0),
@@ -25,6 +23,7 @@ use ec_dsp::Mdct;
25 use crate::bitalloc::{self, Allocation, BitAllocParams, Channel};23 use crate::bitalloc::{self, Allocation, BitAllocParams, Channel};
26 use crate::bsi::Acmod;24 use crate::bsi::Acmod;
27 use crate::exps::Strategy;25 use crate::exps::Strategy;
26+use crate::transform::Imdct;
28 use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW};27 use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW};
29 28
30 /// Samples per channel one syncframe codes.29 /// Samples per channel one syncframe codes.
@@ -33,10 +32,22 @@ const FRAME_SAMPLES: usize = 1536;
33 const BLOCKS: usize = 6;32 const BLOCKS: usize = 6;
34 /// Coefficients per channel per block ([`crate::decode::COEFFS`], not public).33 /// Coefficients per channel per block ([`crate::decode::COEFFS`], not public).
35 const COEFFS: usize = 256;34 const COEFFS: usize = 256;
36-/// `chbwcod` this encoder always sends: maximum bandwidth.35+/// Lowest bit rate per coded channel this encoder accepts: below it the
37-const CHBWCOD: u32 = 60;36+/// side information of the cheapest legal frame no longer fits (see
38-/// Full-bandwidth `endmant` at [`CHBWCOD`]: `(chbwcod + 12) * 3 + 37`.37+/// [`Ac3Encoder::encode_frame`]); [`Ac3Encoder::new`] raises the request to it.
39-const FBW_ENDMANT: usize = (CHBWCOD as usize + 12) * 3 + 37;38+const MIN_KBPS_PER_CHANNEL: u32 = 32;
39+/// Bit allocation parameters (§7.2.2.3), constant for every frame.
40+const BA_PARAMS: BitAllocParams = BitAllocParams { sdcycod: 2, fdcycod: 1, sgaincod: 1, dbpbcod: 2, floorcod: 7 };
41+/// Fast gain code, constant for every channel and frame.
42+const FGAINCOD: u8 = 4;
43+/// [`envelope_moved`]: exponent steps (6 dB each) a band's peak may drift
44+/// before the block re-sends exponents.
45+const RESEND_STEPS: u8 = 2;
46+/// [`is_transient`]: a segment this many times louder than everything before it.
47+const TRANSIENT_RATIO: f32 = 8.0;
48+/// [`is_transient`]: segment energy (64 high-passed samples) below which
49+/// nothing is an attack.
50+const TRANSIENT_FLOOR: f32 = 1e-2;
40 /// LFE `endmant`, fixed by the standard.51 /// LFE `endmant`, fixed by the standard.
41 const LFE_ENDMANT: usize = 7;52 const LFE_ENDMANT: usize = 7;
42 /// Scale from `ec_dsp::Mdct::forward_windowed`'s raw sum (which equals the53 /// Scale from `ec_dsp::Mdct::forward_windowed`'s raw sum (which equals the
@@ -44,6 +55,9 @@ const LFE_ENDMANT: usize = 7;
44 /// expects: the standard's `-2/N` (N = 512) forward normalisation, with its55 /// expects: the standard's `-2/N` (N = 512) forward normalisation, with its
45 /// `2.0x` on the way back being the decoder's own half of that pair.56 /// `2.0x` on the way back being the decoder's own half of that pair.
46 const FORWARD_GAIN: f32 = -2.0 / 512.0;57 const FORWARD_GAIN: f32 = -2.0 / 512.0;
58+/// Scale from the transpose of the decoder's short inverse to the
59+/// coefficients it expects back; measured in `tests::tdac_short_*`.
60+const SHORT_GAIN: f32 = 1.0 / 128.0;
47 61
48 /// How the encoder is set up.62 /// How the encoder is set up.
49 #[derive(Debug, Clone, Copy, PartialEq)]63 #[derive(Debug, Clone, Copy, PartialEq)]
@@ -186,22 +200,21 @@ fn smooth_exps(exps: &mut [u8]) {
186 }200 }
187 }201 }
188 202
189-/// Writes `ngrps` 7-bit exponent groups covering 3 bins each. `realized` must203+/// Writes an exponent set as [`plan_exponents`] produced it: the 4-bit
190-/// already have been through [`smooth_exps`], so the values the decoder204+/// absolute exponent, then 7-bit groups of three differentials. `sent` has
191-/// reconstructs are exactly the ones [`crate::bitalloc::compute`] was run205+/// already been through [`smooth_exps`], so every differential is within ±2
192-/// against.206+/// and the decoder reconstructs precisely these values.
193-fn write_exp_groups(w: &mut BitWriter, realized: &[u8; COEFFS], mut prev: i32, first_bin: usize, ngrps: usize) {207+fn write_exp_groups(w: &mut BitWriter, sent: &[u8]) {
194- let mut bin = first_bin;208+ w.write_bits(u32::from(sent[0]), 4);
195- for _ in 0..ngrps {209+ let mut prev = i32::from(sent[0]);
196- let mut mapped = [0i32; 3];210+ for grp in sent[1..].chunks_exact(3) {
197- for slot in &mut mapped {211+ let mut code = 0u32;
198- let target = if bin < COEFFS { i32::from(realized[bin]) } else { prev };212+ for &v in grp {
199- let diff = (target - prev).clamp(-2, 2);213+ let diff = i32::from(v) - prev;
200- prev = (prev + diff).clamp(0, 24);214+ debug_assert!((-2..=2).contains(&diff));
201- *slot = diff + 2;215+ code = code * 5 + (diff + 2) as u32;
202- bin += 1;216+ prev = i32::from(v);
203- }217+ }
204- let code = (mapped[0] * 25 + mapped[1] * 5 + mapped[2]) as u32;
205 w.write_bits(code, 7);218 w.write_bits(code, 7);
206 }219 }
207 }220 }
@@ -222,6 +235,13 @@ pub struct Ac3Encoder {
222 order: Vec<Option<usize>>,235 order: Vec<Option<usize>>,
223 mdct: Mdct<f32>,236 mdct: Mdct<f32>,
224 window: [f32; 512],237 window: [f32; 512],
238+ /// The decoder's short (block-switched) inverse as a matrix, 512 samples
239+ /// per coefficient, row-major by coefficient — the forward short
240+ /// transform is its transpose ([`Ac3Encoder::forward_short`]).
241+ short_basis: Vec<f32>,
242+ chbwcod: u32,
243+ fbw_endmant: usize,
244+ stats: EncodeStats,
225 /// Previous block's tail, per coded channel — the MDCT's 50% overlap.245 /// Previous block's tail, per coded channel — the MDCT's 50% overlap.
226 history: Vec<[f32; COEFFS]>,246 history: Vec<[f32; COEFFS]>,
227 pcm: Vec<f32>,247 pcm: Vec<f32>,
@@ -244,10 +264,11 @@ impl Ac3Encoder {
244 "AC-3 codes 48000, 44100 or 32000 Hz",264 "AC-3 codes 48000, 44100 or 32000 Hz",
245 )265 )
246 })?;266 })?;
267+ let kbps = config.bitrate_kbps.max(MIN_KBPS_PER_CHANNEL * coded as u32);
247 let idx = BIT_RATE_KBPS268 let idx = BIT_RATE_KBPS
248 .iter()269 .iter()
249 .enumerate()270 .enumerate()
250- .min_by_key(|&(_, &k)| k.abs_diff(config.bitrate_kbps))271+ .min_by_key(|&(_, &k)| k.abs_diff(kbps))
251 .map(|(i, _)| i)272 .map(|(i, _)| i)
252 .unwrap_or(0);273 .unwrap_or(0);
253 let frmsizecod = (idx * 2) as u8;274 let frmsizecod = (idx * 2) as u8;
@@ -259,6 +280,21 @@ impl Ac3Encoder {
259 window[511 - i] = WINDOW[i];280 window[511 - i] = WINDOW[i];
260 }281 }
261 282
283+ let mut imdct = Imdct::new();
284+ let mut short_basis = vec![0.0f32; COEFFS * 512];
285+ for k in 0..COEFFS {
286+ let mut spec = [0.0f32; COEFFS];
287+ spec[k] = 1.0;
288+ let (mut delay, mut out) = ([0.0f32; 256], [0.0f32; 256]);
289+ imdct.block(&spec, true, &mut delay, &mut out);
290+ let row = &mut short_basis[k * 512..(k + 1) * 512];
291+ for n in 0..256 {
292+ row[n] = out[n] / 2.0; // `block` doubles its first half
293+ row[256 + n] = delay[n];
294+ }
295+ }
296+ let chbwcod = chbwcod_for(BIT_RATE_KBPS[idx], nfchans);
297+
262 let mut params = CodecParameters::new(CodecId::Ac3);298 let mut params = CodecParameters::new(CodecId::Ac3);
263 params.media = MediaParameters::Audio(AudioParameters {299 params.media = MediaParameters::Audio(AudioParameters {
264 sample_rate: config.sample_rate,300 sample_rate: config.sample_rate,
@@ -280,6 +316,10 @@ impl Ac3Encoder {
280 frame_bytes,316 frame_bytes,
281 mdct: Mdct::new(512),317 mdct: Mdct::new(512),
282 window,318 window,
319+ short_basis,
320+ chbwcod,
321+ fbw_endmant: (chbwcod as usize + 12) * 3 + 37,
322+ stats: EncodeStats::default(),
283 history: vec![[0.0; COEFFS]; coded],323 history: vec![[0.0; COEFFS]; coded],
284 pcm: Vec::new(),324 pcm: Vec::new(),
285 packets: std::collections::VecDeque::new(),325 packets: std::collections::VecDeque::new(),
@@ -292,6 +332,19 @@ impl Ac3Encoder {
292 &self.params332 &self.params
293 }333 }
294 334
335+ /// Samples this encoder emits before the first audible one: half a
336+ /// window (one block), always, because the very first block has no
337+ /// previous block to overlap-add against and is pure priming. A muxer
338+ /// writing this track's `elst`/`CodecDelay` states it here.
339+ pub fn encoder_delay(&self) -> usize {
340+ COEFFS
341+ }
342+
343+ /// Coding decisions summed over every frame so far.
344+ pub fn stats(&self) -> EncodeStats {
345+ self.stats
346+ }
347+
295 /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs — the348 /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs — the
296 /// same order [`crate::Ac3Decoder`] hands frames out in).349 /// same order [`crate::Ac3Decoder`] hands frames out in).
297 pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> {350 pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> {
@@ -300,10 +353,13 @@ impl Ac3Encoder {
300 Ok(())353 Ok(())
301 }354 }
302 355
303- /// Ends the stream: pads the tail to a whole frame and flushes it.356+ /// Ends the stream: pushes the last block's samples out of the overlap
357+ /// (see [`Ac3Encoder::encoder_delay`]), pads the tail to a whole frame
358+ /// and flushes it.
304 pub fn finish(&mut self) {359 pub fn finish(&mut self) {
305 let need = FRAME_SAMPLES * self.coded;360 let need = FRAME_SAMPLES * self.coded;
306- if !self.pcm.is_empty() {361+ if !self.pcm.is_empty() || self.stats.frames > 0 {
362+ self.pcm.resize(self.pcm.len() + COEFFS * self.coded, 0.0);
307 let padded = self.pcm.len().div_ceil(need) * need;363 let padded = self.pcm.len().div_ceil(need) * need;
308 self.pcm.resize(padded, 0.0);364 self.pcm.resize(padded, 0.0);
309 }365 }
@@ -333,8 +389,10 @@ impl Ac3Encoder {
333 /// One syncframe from `interleaved` (family-order PCM, `coded` channels *389 /// One syncframe from `interleaved` (family-order PCM, `coded` channels *
334 /// [`FRAME_SAMPLES`] samples).390 /// [`FRAME_SAMPLES`] samples).
335 fn encode_frame(&mut self, interleaved: &[f32]) -> Vec<u8> {391 fn encode_frame(&mut self, interleaved: &[f32]) -> Vec<u8> {
336- // Deinterleave into coded-channel order and run the MDCT per block.392+ // Deinterleave into coded-channel order, pick long or short transform
393+ // per block from the transient detector, and run the MDCT.
337 let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS];394 let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS];
395+ let mut blksw = vec![vec![false; self.coded]; BLOCKS];
338 for ch in 0..self.coded {396 for ch in 0..self.coded {
339 let slot = if ch < self.nfchans {397 let slot = if ch < self.nfchans {
340 self.order.iter().position(|&s| s == Some(ch)).unwrap()398 self.order.iter().position(|&s| s == Some(ch)).unwrap()
@@ -347,116 +405,217 @@ impl Ac3Encoder {
347 for n in 0..256 {405 for n in 0..256 {
348 window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot];406 window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot];
349 }407 }
408+ // The LFE has no blksw bit in the stream.
409+ let short = ch < self.nfchans && is_transient(&window_in);
410+ blksw[blk][ch] = short;
350 let mut spectrum = [0.0f32; COEFFS];411 let mut spectrum = [0.0f32; COEFFS];
351- self.mdct412+ if short {
352- .forward_windowed(&window_in, &self.window, &mut spectrum);413+ self.forward_short(&window_in, &mut spectrum);
353- for v in &mut spectrum {414+ } else {
354- // Measured in `tests::tdac_*`: this makes the forward the415+ self.mdct
355- // exact adjoint of the decoder's transform.rs IMDCT.416+ .forward_windowed(&window_in, &self.window, &mut spectrum);
356- *v *= FORWARD_GAIN;417+ for v in &mut spectrum {
418+ // Measured in `tests::tdac_*`: this makes the forward the
419+ // exact adjoint of the decoder's transform.rs IMDCT.
420+ *v *= FORWARD_GAIN;
421+ }
357 }422 }
358 self.history[ch].copy_from_slice(&window_in[256..]);423 self.history[ch].copy_from_slice(&window_in[256..]);
359 coeffs[blk][ch] = spectrum;424 coeffs[blk][ch] = spectrum;
360 }425 }
361 }426 }
362 427
363- // Exponents: one D15 envelope per coded channel, tracking the loudest
364- // magnitude any of the frame's 6 blocks reaches at each bin, so no
365- // block's mantissa is asked to represent more than the exponent's
366- // headroom allows.
367 let endmant: Vec<usize> = (0..self.coded)428 let endmant: Vec<usize> = (0..self.coded)
368- .map(|ch| if ch < self.nfchans { FBW_ENDMANT } else { LFE_ENDMANT })429+ .map(|ch| if ch < self.nfchans { self.fbw_endmant } else { LFE_ENDMANT })
369 .collect();430 .collect();
370- let exps: Vec<[u8; COEFFS]> = (0..self.coded)
371- .map(|ch| {
372- let mut e = [24u8; COEFFS];
373- for bin in 0..endmant[ch] {
374- let mag = coeffs
375- .iter()
376- .map(|b| b[ch][bin].abs())
377- .fold(0.0f32, f32::max);
378- e[bin] = if mag <= 0.0 {
379- 24
380- } else {
381- (-mag.log2()).floor().clamp(0.0, 24.0) as u8
382- };
383- }
384- e
385- })
386- .collect();
387- // Fit the envelope to what the group-diff coding can carry, never
388- // raising an exponent (that would clip its mantissas); the bit
389- // allocation below then runs on exactly what the decoder will decode.
390- let exps: Vec<[u8; COEFFS]> = exps
391- .into_iter()
392- .enumerate()
393- .map(|(ch, mut e)| {
394- smooth_exps(&mut e[..endmant[ch]]);
395- e
396- })
397- .collect();
398-
399- // Fixed allocation: step csnroffst down from a generous default until
400- // the mantissas it buys fit the frame. A3 replaces this with a rate
401- // loop that also varies floorcod/gaincod; see `Ac3Encoder::try_csnroffst`.
402- let mut csnroffst: i32 = 40;
403 let budget_bits = self.frame_bytes as u64 * 8 - 2 /* auxdataflag, crcrsv */ - 16 /* crc2 */;431 let budget_bits = self.frame_bytes as u64 * 8 - 2 /* auxdataflag, crcrsv */ - 16 /* crc2 */;
404- let mut w;432+
405- loop {433+ // Rate loop: the exponent plan fixes the side information, then the
406- let bap = self.allocate(&exps, &endmant, csnroffst as u8);434+ // largest csnroffst (and, at that csnroffst, the largest fsnroffst)
407- w = self.write_frame(&coeffs, &exps, &endmant, &bap, csnroffst as u8);435+ // whose mantissas still fit is found by binary search — both are
408- if w.bit_len() <= budget_bits || csnroffst == 0 {436+ // monotone in bits spent. A plan whose side information alone does
409- break;437+ // not fit (a frame of strategy churn at a low bit rate) is replaced
438+ // by the conservative one: a single D45 envelope for the whole frame.
439+ let mut chosen: Option<(BitWriter, Plan, u8)> = None;
440+ for conservative in [false, true] {
441+ let plan = self.plan(&coeffs, &blksw, &endmant, conservative);
442+ let fits = |c: u8, f: u8| {
443+ let bap = self.allocate(&plan, &endmant, c, f);
444+ let w = self.write_frame(&coeffs, &plan, &endmant, &bap, c, f);
445+ (w.bit_len() <= budget_bits).then_some(w)
446+ };
447+ if fits(0, 0).is_none() {
448+ continue;
449+ }
450+ let (mut lo, mut hi) = (0u8, 63u8);
451+ while lo < hi {
452+ let mid = (lo + hi).div_ceil(2);
453+ if fits(mid, 0).is_some() { lo = mid } else { hi = mid - 1 }
410 }454 }
411- csnroffst -= 1;455+ let c = lo;
456+ let (mut lo, mut hi) = (0u8, 15u8);
457+ while lo < hi {
458+ let mid = (lo + hi).div_ceil(2);
459+ if fits(c, mid).is_some() { lo = mid } else { hi = mid - 1 }
460+ }
461+ chosen = Some((fits(c, lo).unwrap(), plan, c));
462+ break;
412 }463 }
464+ let (w, plan, csnroffst) = chosen.unwrap_or_else(|| {
465+ // corner-cut: unreachable with the 32 kbps/channel floor `new`
466+ // applies (the conservative plan's side info is ~150 bits per
467+ // channel per frame); below that the frame would be truncated.
468+ // Upgrade path: drop chbwcod until it fits.
469+ debug_assert!(false, "side information does not fit the frame");
470+ let plan = self.plan(&coeffs, &blksw, &endmant, true);
471+ let bap = self.allocate(&plan, &endmant, 0, 0);
472+ (self.write_frame(&coeffs, &plan, &endmant, &bap, 0, 0), plan, 0)
473+ });
413 474
475+ self.stats.frames += 1;
476+ self.stats.csnroffst_sum += u64::from(csnroffst);
477+ self.stats.bits_used += w.bit_len();
478+ self.stats.bits_budget += budget_bits;
479+ for blk in 0..BLOCKS {
480+ for ch in 0..self.nfchans {
481+ self.stats.blksw_blocks += u64::from(blksw[blk][ch]);
482+ match plan.strategy[blk][ch] {
483+ Strategy::Reuse => self.stats.reuse += 1,
484+ Strategy::D15 => self.stats.d15 += 1,
485+ Strategy::D25 => self.stats.d25 += 1,
486+ Strategy::D45 => self.stats.d45 += 1,
487+ }
488+ }
489+ }
414 self.finish_frame(w)490 self.finish_frame(w)
415 }491 }
416 492
417- /// Bit allocation for every coded channel at one `csnroffst`.493+ /// The two 256-point transforms of a block-switched block (§7.9.4.2), as
418- fn allocate(&self, exps: &[[u8; COEFFS]], endmant: &[usize], csnroffst: u8) -> Vec<[u8; COEFFS]> {494+ /// the transpose of the decoder's own short inverse (`short_basis`), so
419- let snroffset = ((i32::from(csnroffst) - 15) << 4) << 2; // fsnroffst = 0495+ /// the pair is TDAC-exact by construction — see `tests::tdac_short_*`.
420- let params = BitAllocParams {496+ fn forward_short(&self, window_in: &[f32; 512], spectrum: &mut [f32; COEFFS]) {
421- sdcycod: 2,497+ for (k, out) in spectrum.iter_mut().enumerate() {
422- fdcycod: 1,498+ let row = &self.short_basis[k * 512..(k + 1) * 512];
423- sgaincod: 1,499+ *out = SHORT_GAIN * row.iter().zip(window_in).map(|(a, b)| a * b).sum::<f32>();
424- dbpbcod: 2,500+ }
425- floorcod: 7,501+ }
502+
503+ /// Exponent strategy and exponents for every block and channel.
504+ ///
505+ /// Block 0 always sends. A later block re-sends when its block switch
506+ /// flag changed or its envelope moved ([`envelope_moved`]) since the last
507+ /// send; otherwise it reuses. Each run of
508+ /// blocks sharing one set codes the run's loudest magnitude per bin, so no
509+ /// block's mantissa is asked for more than its exponent's headroom. The
510+ /// sending block uses D15 when block-switched, D45 for a run of 3+ blocks
511+ /// (stationary), D25 otherwise. `conservative` forces one D45 set per channel for the
512+ /// whole frame: the cheapest legal side information.
513+ fn plan(&self, coeffs: &[Vec<[f32; COEFFS]>], blksw: &[Vec<bool>], endmant: &[usize], conservative: bool) -> Plan {
514+ let ideal: Vec<Vec<[u8; COEFFS]>> = coeffs
515+ .iter()
516+ .map(|blk| (0..self.coded).map(|ch| ideal_exps(&blk[ch], endmant[ch])).collect())
517+ .collect();
518+ let mut plan = Plan {
519+ blksw: blksw.to_vec(),
520+ strategy: vec![vec![Strategy::Reuse; self.coded]; BLOCKS],
521+ sent: vec![vec![Vec::new(); self.coded]; BLOCKS],
522+ exps: vec![vec![[24u8; COEFFS]; self.coded]; BLOCKS],
426 };523 };
427- (0..self.coded)524+ for ch in 0..self.coded {
428- .map(|ch| {525+ let mut starts = vec![0usize];
429- let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe };526+ if !conservative {
430- let alloc = Allocation {527+ for blk in 1..BLOCKS {
431- fscod: self.fscod,528+ let last = *starts.last().unwrap();
432- params,529+ if blksw[blk][ch] != blksw[blk - 1][ch]
433- range: (0, endmant[ch]),530+ || envelope_moved(&ideal[blk][ch], &ideal[last][ch], endmant[ch])
434- fgaincod: 4,531+ {
435- snroffset,532+ starts.push(blk);
436- kind,533+ }
437- dba: None,534+ }
438- high_efficiency: false,535+ }
536+ for (i, &start) in starts.iter().enumerate() {
537+ let end = starts.get(i + 1).copied().unwrap_or(BLOCKS);
538+ let mut env = ideal[start][ch];
539+ for blk in start + 1..end {
540+ for bin in 0..endmant[ch] {
541+ env[bin] = env[bin].min(ideal[blk][ch][bin]);
542+ }
543+ }
544+ let strategy = if ch >= self.nfchans {
545+ Strategy::D15
546+ } else if blksw[start][ch] {
547+ // The short halves interleave, so pairs (X1[k], X2[k])
548+ // share one exponent: the louder half's. D15 would
549+ // follow the alternation exactly but at 592 bits per
550+ // send — more than a block's whole budget at 96 kbps per
551+ // channel — against D25's 298.
552+ Strategy::D25
553+ } else if conservative || end - start >= 3 {
554+ Strategy::D45
555+ } else {
556+ Strategy::D25
439 };557 };
440- let mut bap = [0u8; COEFFS];558+ let (sent, exps) = plan_exponents(&env, endmant[ch], strategy);
441- bitalloc::compute(&alloc, &exps[ch], &mut bap);559+ plan.strategy[start][ch] = strategy;
442- bap560+ plan.sent[start][ch] = sent;
443- })561+ for blk in start..end {
444- .collect()562+ plan.exps[blk][ch] = exps;
563+ }
564+ }
565+ }
566+ plan
567+ }
568+
569+ /// Bit allocation for every block and coded channel at one SNR offset.
570+ fn allocate(&self, plan: &Plan, endmant: &[usize], csnroffst: u8, fsnroffst: u8) -> Vec<Vec<[u8; COEFFS]>> {
571+ let snroffset = (((i32::from(csnroffst) - 15) << 4) + i32::from(fsnroffst)) << 2;
572+ // §7.2.2.1.1: all-zero SNR offsets mean no mantissa bits at all —
573+ // the decoder short-circuits there instead of running the model.
574+ if csnroffst == 0 && fsnroffst == 0 {
575+ return vec![vec![[0u8; COEFFS]; self.coded]; BLOCKS];
576+ }
577+ let mut out: Vec<Vec<[u8; COEFFS]>> = Vec::with_capacity(BLOCKS);
578+ for blk in 0..BLOCKS {
579+ let baps = (0..self.coded)
580+ .map(|ch| {
581+ if blk > 0 && plan.strategy[blk][ch] == Strategy::Reuse {
582+ return out[blk - 1][ch];
583+ }
584+ let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe };
585+ let alloc = Allocation {
586+ fscod: self.fscod,
587+ params: BA_PARAMS,
588+ range: (0, endmant[ch]),
589+ fgaincod: FGAINCOD,
590+ snroffset,
591+ kind,
592+ dba: None,
593+ high_efficiency: false,
594+ };
595+ let mut bap = [0u8; COEFFS];
596+ bitalloc::compute(&alloc, &plan.exps[blk][ch], &mut bap);
597+ bap
598+ })
599+ .collect();
600+ out.push(baps);
601+ }
602+ out
445 }603 }
446 604
447 /// Writes syncinfo, bsi and the six audblks; mantissas and their bit cost605 /// Writes syncinfo, bsi and the six audblks; mantissas and their bit cost
448- /// come from `coeffs`, `exps` and `bap` (all already computed for this606+ /// come from `coeffs`, `plan` and `bap` (all already computed for this
449 /// frame). Everything up to the crc/padding tail this function leaves for607 /// frame). Everything up to the crc/padding tail this function leaves for
450- /// [`Ac3Encoder::finish_frame`], so the retry loop in608+ /// [`Ac3Encoder::finish_frame`], so the rate loop in
451 /// [`Ac3Encoder::encode_frame`] can measure a candidate's length before609 /// [`Ac3Encoder::encode_frame`] can measure a candidate's length before
452 /// paying for that.610 /// paying for that.
453 fn write_frame(611 fn write_frame(
454 &self,612 &self,
455 coeffs: &[Vec<[f32; COEFFS]>],613 coeffs: &[Vec<[f32; COEFFS]>],
456- exps: &[[u8; COEFFS]],614+ plan: &Plan,
457 endmant: &[usize],615 endmant: &[usize],
458- bap: &[[u8; COEFFS]],616+ bap: &[Vec<[u8; COEFFS]>],
459 csnroffst: u8,617 csnroffst: u8,
618+ fsnroffst: u8,
460 ) -> BitWriter {619 ) -> BitWriter {
461 let mut w = BitWriter::with_capacity(self.frame_bytes);620 let mut w = BitWriter::with_capacity(self.frame_bytes);
462 621
@@ -491,7 +650,7 @@ impl Ac3Encoder {
491 w.write_bit(false); // addbsi650 w.write_bit(false); // addbsi
492 651
493 for blk in 0..BLOCKS {652 for blk in 0..BLOCKS {
494- self.write_block(&mut w, blk, coeffs, exps, endmant, bap, csnroffst);653+ self.write_block(&mut w, blk, coeffs, plan, endmant, bap, csnroffst, fsnroffst);
495 }654 }
496 w655 w
497 }656 }
@@ -502,14 +661,15 @@ impl Ac3Encoder {
502 w: &mut BitWriter,661 w: &mut BitWriter,
503 blk: usize,662 blk: usize,
504 coeffs: &[Vec<[f32; COEFFS]>],663 coeffs: &[Vec<[f32; COEFFS]>],
505- exps: &[[u8; COEFFS]],664+ plan: &Plan,
506 endmant: &[usize],665 endmant: &[usize],
507- bap: &[[u8; COEFFS]],666+ bap: &[Vec<[u8; COEFFS]>],
508 csnroffst: u8,667 csnroffst: u8,
668+ fsnroffst: u8,
509 ) {669 ) {
510 let first = blk == 0;670 let first = blk == 0;
511- for _ in 0..self.nfchans {671+ for ch in 0..self.nfchans {
512- w.write_bit(false); // blksw672+ w.write_bit(plan.blksw[blk][ch]);
513 }673 }
514 for _ in 0..self.nfchans {674 for _ in 0..self.nfchans {
515 w.write_bit(false); // dithflag675 w.write_bit(false); // dithflag
@@ -522,50 +682,43 @@ impl Ac3Encoder {
522 if self.acmod == Acmod::Stereo {682 if self.acmod == Acmod::Stereo {
523 w.write_bit(false); // rematstr (no rematrixing)683 w.write_bit(false); // rematstr (no rematrixing)
524 }684 }
525- for _ in 0..self.nfchans {685+ for ch in 0..self.nfchans {
526- w.write_bits(if first { 1 } else { 0 }, 2); // chexpstr: D15 / reuse686+ w.write_bits(strategy_code(plan.strategy[blk][ch]), 2); // chexpstr
527 }687 }
528 if self.lfeon {688 if self.lfeon {
529- w.write_bit(first); // lfeexpstr: D15 / reuse689+ w.write_bit(plan.strategy[blk][self.nfchans] != Strategy::Reuse); // lfeexpstr
530 }690 }
531- if first {691+ for ch in 0..self.nfchans {
532- for _ in 0..self.nfchans {692+ if plan.strategy[blk][ch] != Strategy::Reuse {
533- w.write_bits(CHBWCOD, 6); // chbwcod693+ w.write_bits(self.chbwcod, 6);
534 }694 }
535 }695 }
536- if first {696+ for ch in 0..self.nfchans {
537- for ch in 0..self.nfchans {697+ if plan.strategy[blk][ch] != Strategy::Reuse {
538- let absexp = exps[ch][0].min(15);698+ write_exp_groups(w, &plan.sent[blk][ch]);
539- w.write_bits(u32::from(absexp), 4);
540- let ngrps = Strategy::D15.fbw_groups(endmant[ch]);
541- write_exp_groups(w, &exps[ch], i32::from(absexp), 1, ngrps);
542 w.write_bits(0, 2); // gainrng699 w.write_bits(0, 2); // gainrng
543 }700 }
544- if self.lfeon {
545- let ch = self.nfchans;
546- let absexp = exps[ch][0].min(15);
547- w.write_bits(u32::from(absexp), 4);
548- write_exp_groups(w, &exps[ch], i32::from(absexp), 1, 2);
549- }
550 }701 }
702+ if self.lfeon && plan.strategy[blk][self.nfchans] != Strategy::Reuse {
703+ write_exp_groups(w, &plan.sent[blk][self.nfchans]);
704+ }
705+ // The allocation parameters and SNR offsets are constant across the
706+ // frame, so they go once, in block 0 (where they are mandatory); the
707+ // decoder carries them forward through blocks 1-5.
551 w.write_bit(first); // baie708 w.write_bit(first); // baie
552 if first {709 if first {
553- w.write_bits(2, 2); // sdcycod710+ w.write_bits(u32::from(BA_PARAMS.sdcycod), 2);
554- w.write_bits(1, 2); // fdcycod711+ w.write_bits(u32::from(BA_PARAMS.fdcycod), 2);
555- w.write_bits(1, 2); // sgaincod712+ w.write_bits(u32::from(BA_PARAMS.sgaincod), 2);
556- w.write_bits(2, 2); // dbpbcod713+ w.write_bits(u32::from(BA_PARAMS.dbpbcod), 2);
557- w.write_bits(7, 3); // floorcod714+ w.write_bits(u32::from(BA_PARAMS.floorcod), 3);
558 }715 }
559 w.write_bit(first); // snroffste716 w.write_bit(first); // snroffste
560 if first {717 if first {
561 w.write_bits(u32::from(csnroffst), 6);718 w.write_bits(u32::from(csnroffst), 6);
562- for _ in 0..self.nfchans {719+ for _ in 0..self.coded {
563- w.write_bits(0, 4); // fsnroffst720+ w.write_bits(u32::from(fsnroffst), 4);
564- w.write_bits(4, 3); // fgaincod721+ w.write_bits(u32::from(FGAINCOD), 3);
565- }
566- if self.lfeon {
567- w.write_bits(0, 4);
568- w.write_bits(4, 3);
569 }722 }
570 }723 }
571 // no coupling leak (cplinu is always false: no bit here at all)724 // no coupling leak (cplinu is always false: no bit here at all)
@@ -574,15 +727,14 @@ impl Ac3Encoder {
574 727
575 let values: Vec<(u8, f32)> = (0..self.coded)728 let values: Vec<(u8, f32)> = (0..self.coded)
576 .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin)))729 .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin)))
577- .map(|(ch, bin)| (bap[ch][bin], coeffs[blk][ch][bin] * scale(exps[ch][bin])))730+ .map(|(ch, bin)| (bap[blk][ch][bin], coeffs[blk][ch][bin] * scale(plan.exps[blk][ch][bin])))
578 .collect();731 .collect();
579 write_mantissas(w, &values);732 write_mantissas(w, &values);
580 }733 }
581 734
582 /// Patches crc1/crc2 into a written frame and zero-pads it to735 /// Patches crc1/crc2 into a written frame and zero-pads it to
583 /// [`Ac3Encoder::frame_bytes`] — the syncframe's own length, so every736 /// [`Ac3Encoder::frame_bytes`] — the syncframe's own length, so every
584- /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`] regardless of how737+ /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`].
585- /// far under it this frame's fixed allocation landed.
586 fn finish_frame(&self, mut w: BitWriter) -> Vec<u8> {738 fn finish_frame(&self, mut w: BitWriter) -> Vec<u8> {
587 w.write_bit(false); // auxdataflag739 w.write_bit(false); // auxdataflag
588 w.write_bit(false); // crcrsv740 w.write_bit(false); // crcrsv
@@ -604,6 +756,140 @@ impl Ac3Encoder {
604 }756 }
605 }757 }
606 758
759+/// Per-frame coding decisions, made before the rate loop runs so every
760+/// candidate allocation is measured against the same side information.
761+struct Plan {
762+ /// Block switch per block per coded channel (always false for the LFE).
763+ blksw: Vec<Vec<bool>>,
764+ /// Exponent strategy per block per coded channel.
765+ strategy: Vec<Vec<Strategy>>,
766+ /// The exponent values as sent — the absolute one, then one per
767+ /// differential — per block per channel; empty on `Reuse`.
768+ sent: Vec<Vec<Vec<u8>>>,
769+ /// The exponents the decoder holds during each block, per channel: what
770+ /// the bit allocation and the quantisation both run on.
771+ exps: Vec<Vec<[u8; COEFFS]>>,
772+}
773+
774+/// What the encoder decided, summed over every frame so far.
775+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
776+pub struct EncodeStats {
777+ /// Frames coded.
778+ pub frames: u64,
779+ /// Block-switched (short transform) blocks, over full-bandwidth channels.
780+ pub blksw_blocks: u64,
781+ /// Block/channel pairs (full-bandwidth) that sent D15 exponents.
782+ pub d15: u64,
783+ /// ... D25.
784+ pub d25: u64,
785+ /// ... D45.
786+ pub d45: u64,
787+ /// ... that reused the previous block's exponents.
788+ pub reuse: u64,
789+ /// Sum of the `csnroffst` each frame settled on.
790+ pub csnroffst_sum: u64,
791+ /// Bits the frames' side information and mantissas occupied, before padding.
792+ pub bits_used: u64,
793+ /// Bits the frames had available for them.
794+ pub bits_budget: u64,
795+}
796+
797+/// The 2-bit `chexpstr` code (the inverse of [`Strategy::from_code`]).
798+fn strategy_code(strategy: Strategy) -> u32 {
799+ match strategy {
800+ Strategy::Reuse => 0,
801+ Strategy::D15 => 1,
802+ Strategy::D25 => 2,
803+ Strategy::D45 => 3,
804+ }
805+}
806+
807+/// `chbwcod` from the bit rate per full-bandwidth channel: the whole band when
808+/// there are bits to fill it, tapering down at low rates so the bits go to the
809+/// bands that carry the music. At 48 kHz the rows cut off at about 24, 20, 18,
810+/// 16 and 14 kHz.
811+fn chbwcod_for(kbps: u32, nfchans: usize) -> u32 {
812+ match kbps / nfchans as u32 {
813+ 80.. => 60,
814+ 56.. => 48,
815+ 40.. => 40,
816+ 28.. => 32,
817+ _ => 24,
818+ }
819+}
820+
821+/// §7.9.1's spirit in its simplest form: a first-order high-pass, then the
822+/// energy of each of the window's eight 64-sample segments; a segment in the
823+/// block's own half (the new 256 samples) that is `TRANSIENT_RATIO` above
824+/// everything before it, and above the silence floor, is an attack worth a
825+/// short transform's time resolution (pre-echo would otherwise smear over
826+/// the whole 512-sample window).
827+fn is_transient(window_in: &[f32; 512]) -> bool {
828+ let mut energy = [0.0f32; 8];
829+ for (i, seg) in energy.iter_mut().enumerate() {
830+ *seg = (i * 64..(i + 1) * 64)
831+ .map(|n| {
832+ let d = window_in[n] - window_in[n.saturating_sub(1)];
833+ d * d
834+ })
835+ .sum();
836+ }
837+ (4..8).any(|j| {
838+ let before = energy[..j].iter().copied().fold(0.0f32, f32::max);
839+ energy[j] > TRANSIENT_FLOOR && energy[j] > TRANSIENT_RATIO * before
840+ })
841+}
842+
843+/// `floor(-log2 |X|)` per bin, clamped to 0..=24 (24 also for zero), up to
844+/// `endmant`: the exponent that leaves each coefficient's mantissa in
845+/// `[0.5, 1)`.
846+fn ideal_exps(coeffs: &[f32; COEFFS], endmant: usize) -> [u8; COEFFS] {
847+ let mut e = [24u8; COEFFS];
848+ for bin in 0..endmant {
849+ let mag = coeffs[bin].abs();
850+ e[bin] = if mag <= 0.0 { 24 } else { (-mag.log2()).floor().clamp(0.0, 24.0) as u8 };
851+ }
852+ e
853+}
854+
855+/// Whether two ideal envelopes differ enough to be worth re-sending: the peak
856+/// (minimum exponent) of some 12-bin band within 60 dB of the loudest band
857+/// moved by more than [`RESEND_STEPS`]. A re-send costs 150-300 bits per
858+/// channel — at 192 kbps stereo that is 30-60 % of a block's whole budget —
859+/// so the bands the masking model will starve anyway do not get a vote.
860+fn envelope_moved(a: &[u8; COEFFS], b: &[u8; COEFFS], endmant: usize) -> bool {
861+ let loudest = a[..endmant].iter().min().unwrap().min(b[..endmant].iter().min().unwrap());
862+ a[..endmant].chunks(12).zip(b[..endmant].chunks(12)).any(|(x, y)| {
863+ let (px, py) = (*x.iter().min().unwrap(), *y.iter().min().unwrap());
864+ px.min(py) <= loudest + 10 && px.abs_diff(py) > RESEND_STEPS
865+ })
866+}
867+
868+/// The exponent set a channel sends for a run of blocks: `ideal` is the run's
869+/// envelope (min over the run's blocks of each bin's ideal exponent), grouped
870+/// by `strategy` (min over each group's bins), fitted to the ±2 differential
871+/// coding by [`smooth_exps`], then expanded to what the decoder will hold.
872+/// Returns (values as sent, decoded exponents).
873+fn plan_exponents(ideal: &[u8; COEFFS], endmant: usize, strategy: Strategy) -> (Vec<u8>, [u8; COEFFS]) {
874+ let gs = strategy.group_size();
875+ let ngrps = strategy.fbw_groups(endmant);
876+ let mut sent = vec![ideal[0].min(15)];
877+ for g in 0..ngrps * 3 {
878+ let lo = 1 + g * gs;
879+ let hi = (lo + gs).min(endmant);
880+ sent.push(if lo < hi { *ideal[lo..hi].iter().min().unwrap() } else { 24 });
881+ }
882+ smooth_exps(&mut sent);
883+ let mut exps = [24u8; COEFFS];
884+ exps[0] = sent[0];
885+ for g in 0..ngrps * 3 {
886+ for bin in 1 + g * gs..(1 + (g + 1) * gs).min(COEFFS) {
887+ exps[bin] = sent[g + 1];
888+ }
889+ }
890+ (sent, exps)
891+}
892+
607 /// `2^exponent` — the inverse of [`crate::mantissa::scale`], since the893 /// `2^exponent` — the inverse of [`crate::mantissa::scale`], since the
608 /// encoder starts from a linear coefficient and has to divide it back out to894 /// encoder starts from a linear coefficient and has to divide it back out to
609 /// the `[-1, 1)` mantissa the quantizers expect.895 /// the `[-1, 1)` mantissa the quantizers expect.
@@ -667,7 +953,6 @@ impl Encoder for Ac3Encoder {
667 #[cfg(test)]953 #[cfg(test)]
668 mod tests {954 mod tests {
669 use super::*;955 use super::*;
670- use crate::transform::Imdct;
671 956
672 fn lcg(seed: &mut u64) -> f32 {957 fn lcg(seed: &mut u64) -> f32 {
673 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);958 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
@@ -688,19 +973,23 @@ mod tests {
688 out973 out
689 }974 }
690 975
691- fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 {976+ /// Runs `forward` then the decoder's inverse over 7 overlapping blocks,
977+ /// block-switched where `pattern` says so (the short transform must be
978+ /// TDAC-exact against both a short and a long neighbour), and returns
979+ /// (worst sample error, least-squares gain out/in).
980+ fn tdac_pattern(pattern: [bool; 7], forward: impl Fn(&[f32; 512], bool) -> [f32; COEFFS]) -> (f32, f64) {
692 let mut seed = 7u64;981 let mut seed = 7u64;
693- let signal: Vec<f32> = (0..256 * 6).map(|_| lcg(&mut seed)).collect();982+ let signal: Vec<f32> = (0..256 * 8).map(|_| lcg(&mut seed)).collect();
694 let mut imdct = Imdct::new();983 let mut imdct = Imdct::new();
695 let mut delay = [0.0f32; 256];984 let mut delay = [0.0f32; 256];
696 let mut out = [0.0f32; 256];985 let mut out = [0.0f32; 256];
697 let mut worst = 0.0f32;986 let mut worst = 0.0f32;
698 let (mut dot, mut nrm) = (0.0f64, 0.0f64);987 let (mut dot, mut nrm) = (0.0f64, 0.0f64);
699- for blk in 0..5 {988+ for (blk, &short) in pattern.iter().enumerate() {
700 let mut x = [0.0f32; 512];989 let mut x = [0.0f32; 512];
701 x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]);990 x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]);
702- let spec = forward(&x);991+ let spec = forward(&x, short);
703- imdct.block(&spec, false, &mut delay, &mut out);992+ imdct.block(&spec, short, &mut delay, &mut out);
704 if blk > 0 {993 if blk > 0 {
705 // Output of block `blk` reconstructs input samples blk*256..+256.994 // Output of block `blk` reconstructs input samples blk*256..+256.
706 for n in 0..256 {995 for n in 0..256 {
@@ -710,10 +999,84 @@ mod tests {
710 }999 }
711 }1000 }
712 }1001 }
713- assert!((dot / nrm - 1.0).abs() < 1e-4, "least-squares gain out/in = {}", dot / nrm);1002+ (worst, dot / nrm)
1003+ }
1004+
1005+ fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 {
1006+ let (worst, gain) = tdac_pattern([false; 7], |x, _| forward(x));
1007+ assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}");
714 worst1008 worst
715 }1009 }
716 1010
1011+ #[test]
1012+ fn tdac_short_forward_reconstructs_against_long_and_short_neighbours() {
1013+ let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1014+ let window = enc.window;
1015+ let basis = enc.short_basis.clone();
1016+ let cell = std::cell::RefCell::new(&mut enc.mdct);
1017+ let (worst, gain) = tdac_pattern([false, true, true, false, true, false, true], |x, short| {
1018+ let mut s = [0.0f32; COEFFS];
1019+ if short {
1020+ for (k, out) in s.iter_mut().enumerate() {
1021+ let row = &basis[k * 512..(k + 1) * 512];
1022+ *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>();
1023+ }
1024+ } else {
1025+ cell.borrow_mut().forward_windowed(x, &window, &mut s);
1026+ for v in &mut s {
1027+ *v *= FORWARD_GAIN;
1028+ }
1029+ }
1030+ s
1031+ });
1032+ let (w2, g2) = tdac_pattern([true; 7], |x, _| {
1033+ let mut s = [0.0f32; COEFFS];
1034+ for (k, out) in s.iter_mut().enumerate() {
1035+ let row = &basis[k * 512..(k + 1) * 512];
1036+ *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>();
1037+ }
1038+ s
1039+ });
1040+ eprintln!("all-short: worst {w2} gain {g2}; mixed: worst {worst} gain {gain}");
1041+ assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}");
1042+ assert!(worst < 1e-4, "short forward + Imdct TDAC error {worst}");
1043+ }
1044+
1045+ fn encode_one(pcm: &[f32]) -> EncodeStats {
1046+ let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 96 }).unwrap();
1047+ enc.push_pcm_f32(pcm).unwrap();
1048+ enc.stats()
1049+ }
1050+
1051+ #[test]
1052+ fn stationary_tone_plans_one_d45_set_and_reuses_it() {
1053+ let pcm: Vec<f32> = (0..FRAME_SAMPLES * 2)
1054+ .map(|n| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * n as f32 / 48000.0).sin())
1055+ .collect();
1056+ let stats = encode_one(&pcm);
1057+ assert_eq!(stats.frames, 2);
1058+ // Frame 0 opens from silence: an onset, so block 0 is legitimately
1059+ // short and its first blocks may re-send; frame 1 is steady: one D45
1060+ // set, five reuses.
1061+ assert!(stats.blksw_blocks <= 1, "{stats:?}");
1062+ assert!(stats.d45 >= 1 && stats.d15 == 0 && stats.d25 <= 1, "{stats:?}");
1063+ assert!(stats.reuse >= 5, "{stats:?}");
1064+ assert!(stats.bits_used * 10 > stats.bits_budget * 9, "rate loop left bits unused: {stats:?}");
1065+ }
1066+
1067+ #[test]
1068+ fn a_click_switches_to_short_blocks_and_d25() {
1069+ let mut pcm = vec![0.0f32; FRAME_SAMPLES];
1070+ for n in 0..FRAME_SAMPLES {
1071+ pcm[n] = 0.01 * ((n as f32) * 0.3).sin();
1072+ }
1073+ pcm[256 * 3 + 100] = 0.9;
1074+ pcm[256 * 3 + 101] = -0.9;
1075+ let stats = encode_one(&pcm);
1076+ assert_eq!(stats.blksw_blocks, 1, "{stats:?}");
1077+ assert!(stats.d25 >= 1 && stats.d15 == 0, "{stats:?}");
1078+ }
1079+
717 #[test]1080 #[test]
718 fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() {1081 fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() {
719 let mut e = [24u8; COEFFS];1082 let mut e = [24u8; COEFFS];
crates/ec-ac3/src/lib.rsmodified+1 -1
@@ -69,7 +69,7 @@ pub mod encode;
69 69
70 pub use decode::Syntax;70 pub use decode::Syntax;
71 pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};71 pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};
72-pub use encode::{Ac3Encoder, EncoderConfig};72+pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig};
73 pub use ec_core::Error;73 pub use ec_core::Error;
74 74
75 /// Samples per channel one audio block produces.75 /// Samples per channel one audio block produces.
crates/ec-ac3/tests/encode_matrix.rsmodified+248 -16
@@ -1,5 +1,7 @@
1-//! A1 skeleton coverage: the fixed-allocation encoder writes frames our own1+//! Encoder coverage: frames our own decoder round-trips, and that ffmpeg
2-//! decoder round-trips, and ffmpeg accepts as valid AC-3 when it is present.2+//! (when present) accepts as valid AC-3 and decodes to the same audio — on
3+//! synthetic signals and on the real 16-bit fixtures, at every rate and
4+//! layout the encoder offers.
3 5
4 use std::path::Path;6 use std::path::Path;
5 use std::process::Command;7 use std::process::Command;
@@ -53,10 +55,15 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 {
53 cov / (va.sqrt() * vb.sqrt())55 cov / (va.sqrt() * vb.sqrt())
54 }56 }
55 57
56-/// Lag-searched correlation on one channel, +/- 64 samples: the encoder's58+/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts
57-/// analysis window and the decoder's overlap-add each carry their own group59+/// with this many samples of silence per channel.
58-/// delay.60+const DELAY: usize = 256;
61+
62+/// Lag-searched correlation on one channel after the priming is dropped,
63+/// +/- 64 samples of slack: a bug that shifts the audio by a block shows up
64+/// as ~0 here, where an unbounded search on a periodic signal would hide it.
59 fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 {65 fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 {
66+ let b = &b[DELAY.min(b.len())..];
60 let mut best = -1.0f64;67 let mut best = -1.0f64;
61 for lag in -64i32..=64 {68 for lag in -64i32..=64 {
62 let (sa, sb): (&[f32], &[f32]) = if lag >= 0 {69 let (sa, sb): (&[f32], &[f32]) = if lag >= 0 {
@@ -79,7 +86,65 @@ fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> {
79 .collect()86 .collect()
80 }87 }
81 88
82-fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> {89+/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None
90+/// without ffmpeg.
91+fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
92+ let out = Command::new("ffmpeg")
93+ .args(["-v", "error", "-i"])
94+ .arg(path)
95+ .args(["-f", "f32le", "-"])
96+ .output()
97+ .ok()?;
98+ if !out.status.success() {
99+ return None;
100+ }
101+ let samples = out
102+ .stdout
103+ .chunks_exact(4)
104+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
105+ .collect();
106+ let probe = ffprobe(path, "channels,sample_rate");
107+ let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::<u32>().ok());
108+ Some((samples, field("sample_rate")?, field("channels")? as usize))
109+}
110+
111+fn ffprobe(path: &Path, entries: &str) -> String {
112+ let out = Command::new("ffprobe")
113+ .args(["-v", "error", "-select_streams", "a:0", "-show_entries"])
114+ .arg(format!("stream={entries}"))
115+ .args(["-of", "default=noprint_wrappers=1"])
116+ .arg(path)
117+ .output()
118+ .expect("ffprobe");
119+ String::from_utf8_lossy(&out.stdout).into_owned()
120+}
121+
122+fn probe_field(text: &str, key: &str) -> Option<String> {
123+ text.lines()
124+ .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
125+ .map(|v| v.trim().to_owned())
126+}
127+
128+/// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint.
129+fn oracle_decode(path: &Path) -> Vec<f32> {
130+ let out = Command::new("ffmpeg")
131+ .args(["-v", "warning", "-i"])
132+ .arg(path)
133+ .args(["-f", "f32le", "-"])
134+ .output()
135+ .expect("ffmpeg");
136+ let stderr = String::from_utf8_lossy(&out.stderr);
137+ let complaint = stderr
138+ .lines()
139+ .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
140+ assert!(!complaint, "ffmpeg complained about {}:\n{stderr}", path.display());
141+ out.stdout
142+ .chunks_exact(4)
143+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
144+ .collect()
145+}
146+
147+fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec<u8>, ec_ac3::EncodeStats) {
83 let mut enc = Ac3Encoder::new(config).unwrap();148 let mut enc = Ac3Encoder::new(config).unwrap();
84 enc.push_pcm_f32(pcm).unwrap();149 enc.push_pcm_f32(pcm).unwrap();
85 enc.finish();150 enc.finish();
@@ -91,7 +156,39 @@ fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> {
91 Err(e) => panic!("{e}"),156 Err(e) => panic!("{e}"),
92 }157 }
93 }158 }
94- out159+ (out, enc.stats())
160+}
161+
162+fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> {
163+ encode_with_stats(config, pcm).0
164+}
165+
166+/// Worst per-channel lag-searched correlation between `want` and `got`.
167+fn worst_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
168+ (0..channels)
169+ .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
170+ .fold(1.0, f64::min)
171+}
172+
173+/// [`worst_corr`] over the full-bandwidth channels only: the LFE (family slot
174+/// 3 of six) is band-limited to 7 bins (~660 Hz at 48 kHz) by the standard,
175+/// so a fixture whose LFE carries full-band content can never correlate with
176+/// it; that channel is gated on our decoder agreeing with the oracle instead.
177+fn worst_fbw_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
178+ (0..channels)
179+ .filter(|&ch| !(channels == 6 && ch == 3))
180+ .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
181+ .fold(1.0, f64::min)
182+}
183+
184+/// Deterministic white noise, `len` interleaved samples.
185+fn noise(len: usize, seed: &mut u64) -> Vec<f32> {
186+ (0..len)
187+ .map(|_| {
188+ *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
189+ ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
190+ })
191+ .collect()
95 }192 }
96 193
97 fn decode_all(data: &[u8], channels: usize) -> Vec<f32> {194 fn decode_all(data: &[u8], channels: usize) -> Vec<f32> {
@@ -129,15 +226,8 @@ fn silence_and_tone_frames_decode_in_our_decoder() {
129 assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames");226 assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames");
130 let decoded = decode_all(&data, channels as usize);227 let decoded = decode_all(&data, channels as usize);
131 assert!(!decoded.is_empty());228 assert!(!decoded.is_empty());
132- for ch in 0..channels as usize {229+ let corr = worst_corr(&pcm, &decoded, channels as usize);
133- let want = take_channel(&pcm, channels as usize, ch);230+ assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}");
134- let got = take_channel(&decoded, channels as usize, ch);
135- let corr = best_lag_correlation(&want, &got);
136- assert!(
137- corr >= 0.95,
138- "{sample_rate} Hz {channels}ch channel {ch}: corr {corr}"
139- );
140- }
141 }231 }
142 }232 }
143 233
@@ -188,3 +278,145 @@ fn oracle_accepts_our_frames() {
188 let _ = std::fs::remove_file(Path::new(&path));278 let _ = std::fs::remove_file(Path::new(&path));
189 }279 }
190 280
281+
282+/// The full fixture matrix: every wav16 fixture at its layout's bit rate,
283+/// through our decoder and the oracle, with ffprobe agreeing on what was
284+/// asked for. Prints the per-file numbers and the stereo strategy shares.
285+#[test]
286+fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() {
287+ if !have_ffmpeg() {
288+ eprintln!("skipping: ffmpeg not found");
289+ return;
290+ }
291+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio");
292+ let mut failures = Vec::new();
293+ for layout in ["mono", "stereo", "5.1"] {
294+ for rate in [48_000u32, 44_100] {
295+ let path = root.join(format!("wav16-{layout}-{rate}.wav"));
296+ let (pcm, sample_rate, channels) = read_wav(&path).unwrap_or_else(|| panic!("{}", path.display()));
297+ assert_eq!(sample_rate, rate);
298+ let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 };
299+ let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps };
300+ let (data, stats) = encode_with_stats(config, &pcm);
301+ let frame = ec_ac3::frame_size(&data).unwrap();
302+ assert_eq!(data.len() % frame, 0, "{layout} {rate}: frames are not all {frame} bytes");
303+
304+ let decoded = decode_all(&data, channels);
305+ let ours = worst_fbw_corr(&pcm, &decoded, channels);
306+ let out = std::env::temp_dir().join(format!("ec_ac3_encode_matrix_{layout}_{rate}.ac3"));
307+ std::fs::write(&out, &data).unwrap();
308+ let oracle_pcm = oracle_decode(&out);
309+ let oracle = worst_fbw_corr(&pcm, &oracle_pcm, channels);
310+ if channels == 6 {
311+ let lfe = correlation(&take_channel(&decoded, 6, 3), &take_channel(&oracle_pcm, 6, 3));
312+ assert!(lfe >= 0.99, "{layout} {rate}: LFE ours vs oracle corr {lfe}");
313+ }
314+ let probe = ffprobe(&out, "channels,channel_layout,sample_rate,bit_rate");
315+ let _ = std::fs::remove_file(&out);
316+
317+ let total = (stats.d15 + stats.d25 + stats.d45 + stats.reuse) as f64;
318+ let share = |n: u64| n as f64 / total * 100.0;
319+ eprintln!(
320+ "{layout} {rate}: {} frames, ours {ours:.4} oracle {oracle:.4}, csnroffst mean {:.1}, fill {:.1}%, blksw {}, D15 {:.1}% D25 {:.1}% D45 {:.1}% REUSE {:.1}%",
321+ stats.frames,
322+ stats.csnroffst_sum as f64 / stats.frames as f64,
323+ stats.bits_used as f64 / stats.bits_budget as f64 * 100.0,
324+ stats.blksw_blocks,
325+ share(stats.d15), share(stats.d25), share(stats.d45), share(stats.reuse),
326+ );
327+ if ours < 0.99 || oracle < 0.99 {
328+ failures.push(format!("{layout} {rate}: ours {ours:.4} oracle {oracle:.4}"));
329+ }
330+ assert!(stats.bits_used * 10 > stats.bits_budget * 9, "{layout} {rate}: rate loop left bits unused: {stats:?}");
331+ let expect_layout = match channels { 1 => "mono", 2 => "stereo", _ => "5.1" };
332+ assert_eq!(probe_field(&probe, "channels").as_deref(), Some(channels.to_string().as_str()), "{probe}");
333+ assert!(probe_field(&probe, "channel_layout").is_some_and(|l| l.starts_with(expect_layout)), "{probe}");
334+ assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some(rate.to_string().as_str()), "{probe}");
335+ assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some((bitrate_kbps * 1000).to_string().as_str()), "{probe}");
336+ }
337+ }
338+ assert!(failures.is_empty(), "corr < 0.99:\n{}", failures.join("\n"));
339+}
340+
341+/// A train of sharp attacks (decaying 2 kHz bursts, 25 per second) over a
342+/// quiet noise floor: every attack is a block switch, and the stream still
343+/// round-trips through both decoders.
344+#[test]
345+fn click_train_switches_blocks_and_still_round_trips() {
346+ let channels = 2;
347+ let mut pcm = noise(48_000 * channels, &mut 11u64);
348+ for v in &mut pcm {
349+ *v *= 0.01;
350+ }
351+ for n in (500..48_000).step_by(1900) {
352+ for i in 0..200 {
353+ 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();
354+ for ch in 0..channels {
355+ pcm[(n + i) * channels + ch] += v;
356+ }
357+ }
358+ }
359+ let config = EncoderConfig { sample_rate: 48_000, channels: 2, bitrate_kbps: 192 };
360+ let (data, stats) = encode_with_stats(config, &pcm);
361+ assert!(stats.blksw_blocks >= 20, "{stats:?}");
362+ let corr = worst_corr(&pcm, &decode_all(&data, channels), channels);
363+ eprintln!("click train: ours {corr:.4}, {stats:?}");
364+ assert!(corr >= 0.95, "click train corr {corr}");
365+ if have_ffmpeg() {
366+ let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3");
367+ std::fs::write(&out, &data).unwrap();
368+ let corr = worst_corr(&pcm, &oracle_decode(&out), channels);
369+ let _ = std::fs::remove_file(&out);
370+ eprintln!("click train: oracle {corr:.4}");
371+ assert!(corr >= 0.95, "click train oracle corr {corr}");
372+ }
373+}
374+
375+#[test]
376+fn tone_at_32khz_round_trips() {
377+ let rate = 32_000;
378+ let pcm: Vec<f32> = (0..rate as usize * 2)
379+ .flat_map(|n| {
380+ let t = n as f32 / rate as f32;
381+ let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
382+ [v, 0.5 * v]
383+ })
384+ .collect();
385+ let config = EncoderConfig { sample_rate: rate, channels: 2, bitrate_kbps: 96 };
386+ let data = encode(config, &pcm);
387+ let corr = worst_corr(&pcm, &decode_all(&data, 2), 2);
388+ assert!(corr >= 0.99, "32 kHz ours corr {corr}");
389+ if have_ffmpeg() {
390+ let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3");
391+ std::fs::write(&out, &data).unwrap();
392+ let corr = worst_corr(&pcm, &oracle_decode(&out), 2);
393+ let probe = ffprobe(&out, "sample_rate,bit_rate");
394+ let _ = std::fs::remove_file(&out);
395+ assert!(corr >= 0.99, "32 kHz oracle corr {corr}");
396+ assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}");
397+ assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}");
398+ }
399+}
400+
401+/// 200 random (rate, channels, bit rate) configurations, two frames of
402+/// noise each: nothing panics and our decoder takes every frame.
403+#[test]
404+fn random_configs_never_panic_and_always_decode() {
405+ let (mut seed, mut noise_seed) = (99u64, 7u64);
406+ let mut next = |n: u64| {
407+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
408+ (seed >> 33) % n
409+ };
410+ for _ in 0..200 {
411+ let sample_rate = ec_ac3::tables::SAMPLE_RATE[next(3) as usize];
412+ let channels = next(6) as u16 + 1;
413+ let bitrate_kbps = ec_ac3::tables::BIT_RATE_KBPS[next(ec_ac3::tables::BIT_RATE_KBPS.len() as u64) as usize];
414+ let config = EncoderConfig { sample_rate, channels, bitrate_kbps };
415+ let pcm = noise(1536 * 2 * channels as usize, &mut noise_seed);
416+ let data = encode(config, &pcm);
417+ let decoded = decode_all(&data, channels as usize);
418+ assert!(decoded.len() >= pcm.len() + 256, "{config:?}: {} of {} samples", decoded.len(), pcm.len());
419+ }
420+}
421+
422+
fixturesadded+1 -0
@@ -0,0 +1 @@
1+/home/user/Documents/Code/Rust/edith_codecs/fixtures
\ No newline at end of file\ No newline at end of file