From 2d69f73db9ee5fd606a8d498067a0f1063abe367 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 10:10:12 +0300 Subject: [PATCH] test(ac3): fixture matrix against ffmpeg, header surface and no-panic floor The matrix decodes every generated ac3/eac3 fixture and compares per channel against ffmpeg with dither off, which is what isolates everything but the two decoders' implementation-defined noise. Alongside it: the exact header calls a container makes, the downmix, and a damage sweep that truncates and corrupts every byte of a frame. The example is the harness those numbers come from -- it also prints the decode speed, 313-514x realtime for 5.1 on real Blu-ray and streaming tracks. --- crates/ec-ac3/examples/ac3dec.rs | 135 +++++++++++++ crates/ec-ac3/tests/decode_matrix.rs | 277 +++++++++++++++++++++++++++ 2 files changed, 412 insertions(+) create mode 100644 crates/ec-ac3/examples/ac3dec.rs create mode 100644 crates/ec-ac3/tests/decode_matrix.rs diff --git a/crates/ec-ac3/examples/ac3dec.rs b/crates/ec-ac3/examples/ac3dec.rs new file mode 100644 index 00000000..664d5cd7 --- /dev/null +++ b/crates/ec-ac3/examples/ac3dec.rs @@ -0,0 +1,135 @@ +//! Decode an AC-3 / E-AC-3 elementary stream to interleaved 32-bit float. +//! +//! ```text +//! cargo run --release --example ac3dec -- in.ac3 out.f32 [--downmix stereo|mono] [--drc 0.0] +//! ``` +//! +//! Prints the stream's layout and the decode speed relative to realtime, which +//! is how the crate's perf claim is measured. + +use std::io::{BufWriter, Write}; +use std::time::Instant; + +use ec_ac3::{Ac3Decoder, Downmix, Options}; + +fn main() { + let argv: Vec = std::env::args().skip(1).collect(); + if argv.len() < 2 { + eprintln!( + "usage: ac3dec [--downmix stereo|mono] [--drc SCALE] \ + [--dither on|off]" + ); + std::process::exit(2); + } + let mut options = Options::default(); + let mut i = 2; + while i + 1 < argv.len() { + match argv[i].as_str() { + "--downmix" => { + options.downmix = match argv[i + 1].as_str() { + "stereo" => Downmix::Stereo, + "mono" => Downmix::Mono, + other => { + eprintln!("ac3dec: unknown downmix {other}"); + std::process::exit(2); + } + } + } + "--drc" => options.drc_scale = argv[i + 1].parse().unwrap_or(1.0), + "--dither" => options.dither = argv[i + 1] != "off", + other => { + eprintln!("ac3dec: unknown flag {other}"); + std::process::exit(2); + } + } + i += 2; + } + + let data = match std::fs::read(&argv[0]) { + Ok(d) => d, + Err(e) => { + eprintln!("ac3dec: {}: {e}", argv[0]); + std::process::exit(2); + } + }; + let mut decoder = Ac3Decoder::with_options(options); + let file = match std::fs::File::create(&argv[1]) { + Ok(f) => f, + Err(e) => { + eprintln!("ac3dec: {}: {e}", argv[1]); + std::process::exit(2); + } + }; + // Streamed, because a two-hour 5.1 track is ten gigabytes of `f32`. + let mut out = BufWriter::with_capacity(1 << 20, file); + let (mut pos, mut frames, mut samples, mut errors) = (0usize, 0u64, 0u64, Vec::new()); + let mut rate = 0; + let mut channels = 0; + let start = Instant::now(); + while pos + 6 <= data.len() { + if data[pos] != 0x0B || data[pos + 1] != 0x77 { + pos += 1; + continue; + } + let size = match ec_ac3::frame_size(&data[pos..]) { + Ok(size) if pos + size <= data.len() => size, + Ok(_) => break, + Err(e) => { + errors.push(format!("frame at {pos}: {e}")); + pos += 2; + continue; + } + }; + match decoder.decode_frame(&data[pos..pos + size]) { + Ok(frame) => { + rate = frame.rate; + channels = frame.channels(); + samples += frame.samples as u64; + frames += 1; + let _ = out.write_all(&frame.data[0]); + } + Err(e) => { + // Keep the timeline: a frame that will not decode becomes the + // silence it represents, so a comparison stays sample-aligned. + errors.push(format!("frame at {pos}: {e}")); + if channels > 0 { + let _ = out.write_all(&vec![0u8; channels * 1536 * 4]); + samples += 1536; + } + } + } + pos += size; + } + let elapsed = start.elapsed().as_secs_f64(); + + if let Err(e) = out.flush() { + eprintln!("ac3dec: {}: {e}", argv[1]); + std::process::exit(2); + } + let seconds = if rate > 0 { + samples as f64 / f64::from(rate) + } else { + 0.0 + }; + println!("frames\t{frames}"); + println!("channels\t{channels}"); + println!("sample_rate\t{rate}"); + println!("samples\t{samples}"); + println!("seconds\t{seconds:.3}"); + println!("decode_seconds\t{elapsed:.3}"); + println!( + "realtime\t{:.1}", + if elapsed > 0.0 { + seconds / elapsed + } else { + 0.0 + } + ); + println!("errors\t{}", errors.len()); + for e in errors.iter().take(5) { + println!("error\t{e}"); + } + if frames == 0 { + std::process::exit(1); + } +} diff --git a/crates/ec-ac3/tests/decode_matrix.rs b/crates/ec-ac3/tests/decode_matrix.rs new file mode 100644 index 00000000..aca3dcb3 --- /dev/null +++ b/crates/ec-ac3/tests/decode_matrix.rs @@ -0,0 +1,277 @@ +//! Fixture matrix: every generated AC-3 and E-AC-3 fixture decoded and +//! compared against ffmpeg, plus the header surface a container reads and the +//! no-panic contract on damaged input. +//! +//! ffmpeg is test tooling — it is driven through `std::process` so the crate +//! itself never gains a media dependency. Missing fixtures or a missing ffmpeg +//! skip the comparison rather than fail it; `scripts/gen-fixtures.sh` writes +//! the fixtures. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo}; + +/// Per-channel correlation floor (rubric: audio-ac3 MUST). +const MIN_CORR: f64 = 0.999; +/// RMS delta ceiling on the fixture matrix, where both decoders see the same +/// synthetic material. +const MAX_RMS: f64 = 1e-3; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/audio") + .canonicalize() + .unwrap_or_else(|_| PathBuf::from("../../fixtures/audio")) +} + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .is_ok_and(|o| o.status.success()) +} + +/// ffmpeg's decode of `path` as interleaved `f32`. +fn reference(path: &Path) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + out.stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() +} + +/// Our decode of a raw elementary stream, and the channel count. +fn decode(path: &Path, options: Options) -> (Vec, usize) { + let data = std::fs::read(path).expect("fixture"); + let mut decoder = Ac3Decoder::with_options(options); + let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize); + while pos + 6 <= data.len() { + if data[pos] != 0x0B || data[pos + 1] != 0x77 { + pos += 1; + continue; + } + let Ok(size) = ec_ac3::frame_size(&data[pos..]) else { + break; + }; + if pos + size > data.len() { + break; + } + let frame = decoder + .decode_frame(&data[pos..pos + size]) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + channels = frame.channels(); + out.extend( + frame.data[0] + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), + ); + pos += size; + } + (out, channels) +} + +fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) { + let n = a.len().min(b.len()); + let (mut sa, mut sb, mut saa, mut sbb, mut sab, mut sd) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); + for i in 0..n { + let (x, y) = (f64::from(a[i]), f64::from(b[i])); + sa += x; + sb += y; + saa += x * x; + sbb += y * y; + sab += x * y; + sd += (x - y) * (x - y); + } + let n = n as f64; + let cov = sab / n - (sa / n) * (sb / n); + let va = saa / n - (sa / n).powi(2); + let vb = sbb / n - (sb / n).powi(2); + let corr = if va <= 0.0 || vb <= 0.0 { + 1.0 + } else { + cov / (va * vb).sqrt() + }; + (corr, (sd / n).sqrt()) +} + +#[test] +fn fixture_matrix_matches_ffmpeg() { + let dir = fixtures(); + if !dir.exists() || !have_ffmpeg() { + eprintln!("skipping: no fixtures or no ffmpeg"); + return; + } + let mut checked = 0; + for entry in std::fs::read_dir(&dir).expect("fixtures dir") { + let path = entry.expect("entry").path(); + let name = path.file_name().unwrap_or_default().to_string_lossy(); + if !(name.starts_with("ac3-") || name.starts_with("eac3-")) { + continue; + } + // Dither is "any reasonably random sequence" (§7.3.4), so two + // conformant decoders differ by exactly that noise. Comparing with it + // off is what isolates everything else; the with-dither run below + // bounds how much noise it adds. + let options = Options { + dither: false, + ..Options::default() + }; + let (ours, channels) = decode(&path, options); + let theirs = reference(&path); + assert!(channels > 0, "{name}: no channels"); + assert_eq!( + ours.len(), + theirs.len(), + "{name}: {} samples vs ffmpeg's {}", + ours.len(), + theirs.len() + ); + for ch in 0..channels { + let a: Vec = ours[ch..].iter().step_by(channels).copied().collect(); + let b: Vec = theirs[ch..].iter().step_by(channels).copied().collect(); + let (corr, rms) = correlation(&a, &b); + assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}"); + assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}"); + } + checked += 1; + } + assert!(checked >= 12, "only {checked} fixtures checked"); +} + +#[test] +fn dither_only_adds_noise_below_the_signal() { + let path = fixtures().join("ac3-5.1-48000.ac3"); + if !path.exists() { + return; + } + let (with, channels) = decode(&path, Options::default()); + let (without, _) = decode( + &path, + Options { + dither: false, + ..Options::default() + }, + ); + assert_eq!(with.len(), without.len()); + let (corr, rms) = correlation(&with, &without); + assert!(channels == 6 && corr > 0.999, "correlation {corr:.6}"); + assert!(rms < 1e-3, "dither RMS {rms:.8}"); +} + +#[test] +fn headers_state_what_the_container_needs() { + let path = fixtures().join("ac3-5.1-48000.ac3"); + if !path.exists() { + return; + } + let data = std::fs::read(&path).expect("fixture"); + // The exact call shape a container makes: syncinfo from the frame start, + // bsi from five bytes in. + let sync = syncinfo::parse(&data).expect("syncinfo"); + assert_eq!(sync.sample_rate, 48_000); + assert_eq!(sync.frame_size % 2, 0); + let bsi = bsi::parse(&data[5..]).expect("bsi"); + assert_eq!(bsi.nfchans, 5); + assert!(bsi.lfeon); + assert_eq!(bsi.channels, 6); + assert!((1..=31).contains(&bsi.dialnorm)); + + let eac3_path = fixtures().join("eac3-5.1-48000.eac3"); + let data = std::fs::read(&eac3_path).expect("fixture"); + let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi"); + assert_eq!(hdr.sample_rate, 48_000); + assert_eq!(hdr.nfchans, 5); + assert!(hdr.bsi.lfeon); + assert_eq!( + hdr.frame_size, + ec_ac3::frame_size(&data).expect("frame size") + ); +} + +#[test] +fn frame_info_surfaces_the_metadata_the_rubric_asks_for() { + let path = fixtures().join("ac3-5.1-48000.ac3"); + if !path.exists() { + return; + } + let data = std::fs::read(&path).expect("fixture"); + let size = ec_ac3::frame_size(&data).expect("frame size"); + let mut decoder = Ac3Decoder::new(); + decoder.decode_frame(&data[..size]).expect("decode"); + let info = decoder.frame_info().expect("frame info"); + assert_eq!(info.syntax, Syntax::Ac3); + assert_eq!(info.sample_rate, 48_000); + assert!((1..=31).contains(&info.dialnorm)); + // ffmpeg's encoder writes cmixlev 1 (-4.5 dB) and surmixlev 1 (-6 dB). + assert_eq!(info.center_mix_level, Some(0.595)); + assert_eq!(info.surround_mix_level, Some(0.5)); + assert_eq!(info.samples, 1536); +} + +#[test] +fn stereo_downmix_folds_five_one_without_clipping() { + let path = fixtures().join("ac3-5.1-48000.ac3"); + if !path.exists() { + return; + } + let (stereo, channels) = decode( + &path, + Options { + downmix: Downmix::Stereo, + ..Options::default() + }, + ); + assert_eq!(channels, 2); + let (native, _) = decode(&path, Options::default()); + assert_eq!(stereo.len() * 3, native.len()); + assert!(stereo.iter().all(|v| v.abs() <= 1.0), "downmix clipped"); + assert!(stereo.iter().any(|v| v.abs() > 0.01), "downmix is silent"); + + let (mono, channels) = decode( + &path, + Options { + downmix: Downmix::Mono, + ..Options::default() + }, + ); + assert_eq!(channels, 1); + assert_eq!(mono.len() * 6, native.len()); +} + +#[test] +fn damaged_input_never_panics() { + let path = fixtures().join("ac3-stereo-48000.ac3"); + if !path.exists() { + return; + } + let data = std::fs::read(&path).expect("fixture"); + let size = ec_ac3::frame_size(&data).expect("frame size"); + let frame = &data[..size]; + let mut decoder = Ac3Decoder::new(); + + // Every truncation. + for cut in 0..frame.len() { + let _ = decoder.decode_frame(&frame[..cut]); + } + // Every single-byte corruption at a stride that still hits every field + // class: header, side information, exponents, mantissas. + for pos in (0..frame.len()).step_by(7) { + let mut broken = frame.to_vec(); + broken[pos] ^= 0xA5; + let _ = decoder.decode_frame(&broken); + } + // Garbage that happens to start with a sync word. + let mut noise = vec![0x0B, 0x77]; + let mut state = 12345u32; + for _ in 0..4096 { + state = state.wrapping_mul(1_103_515_245).wrapping_add(12345); + noise.push((state >> 16) as u8); + } + let _ = decoder.decode_frame(&noise); +}