Fixture matrix against ffmpeg, header surface and no-panic floor
Browse files at this commit2d69f73db9ee5fd606a8d498067a0f1063abe367Parent: 7fa4038- test
- fixture matrix against ffmpeg, header surface and no-panic floor
2 changed files +412 -0
crates/ec-ac3/examples/ac3dec.rsadded+135 -0
| @@ -0,0 +1,135 @@ | ||
| 1 | +//! Decode an AC-3 / E-AC-3 elementary stream to interleaved 32-bit float. | |
| 2 | +//! | |
| 3 | +//! ```text | |
| 4 | +//! cargo run --release --example ac3dec -- in.ac3 out.f32 [--downmix stereo|mono] [--drc 0.0] | |
| 5 | +//! ``` | |
| 6 | +//! | |
| 7 | +//! Prints the stream's layout and the decode speed relative to realtime, which | |
| 8 | +//! is how the crate's perf claim is measured. | |
| 9 | + | |
| 10 | +use std::io::{BufWriter, Write}; | |
| 11 | +use std::time::Instant; | |
| 12 | + | |
| 13 | +use ec_ac3::{Ac3Decoder, Downmix, Options}; | |
| 14 | + | |
| 15 | +fn main() { | |
| 16 | + let argv: Vec<String> = std::env::args().skip(1).collect(); | |
| 17 | + if argv.len() < 2 { | |
| 18 | + eprintln!( | |
| 19 | + "usage: ac3dec <in.ac3> <out.f32> [--downmix stereo|mono] [--drc SCALE] \ | |
| 20 | + [--dither on|off]" | |
| 21 | + ); | |
| 22 | + std::process::exit(2); | |
| 23 | + } | |
| 24 | + let mut options = Options::default(); | |
| 25 | + let mut i = 2; | |
| 26 | + while i + 1 < argv.len() { | |
| 27 | + match argv[i].as_str() { | |
| 28 | + "--downmix" => { | |
| 29 | + options.downmix = match argv[i + 1].as_str() { | |
| 30 | + "stereo" => Downmix::Stereo, | |
| 31 | + "mono" => Downmix::Mono, | |
| 32 | + other => { | |
| 33 | + eprintln!("ac3dec: unknown downmix {other}"); | |
| 34 | + std::process::exit(2); | |
| 35 | + } | |
| 36 | + } | |
| 37 | + } | |
| 38 | + "--drc" => options.drc_scale = argv[i + 1].parse().unwrap_or(1.0), | |
| 39 | + "--dither" => options.dither = argv[i + 1] != "off", | |
| 40 | + other => { | |
| 41 | + eprintln!("ac3dec: unknown flag {other}"); | |
| 42 | + std::process::exit(2); | |
| 43 | + } | |
| 44 | + } | |
| 45 | + i += 2; | |
| 46 | + } | |
| 47 | + | |
| 48 | + let data = match std::fs::read(&argv[0]) { | |
| 49 | + Ok(d) => d, | |
| 50 | + Err(e) => { | |
| 51 | + eprintln!("ac3dec: {}: {e}", argv[0]); | |
| 52 | + std::process::exit(2); | |
| 53 | + } | |
| 54 | + }; | |
| 55 | + let mut decoder = Ac3Decoder::with_options(options); | |
| 56 | + let file = match std::fs::File::create(&argv[1]) { | |
| 57 | + Ok(f) => f, | |
| 58 | + Err(e) => { | |
| 59 | + eprintln!("ac3dec: {}: {e}", argv[1]); | |
| 60 | + std::process::exit(2); | |
| 61 | + } | |
| 62 | + }; | |
| 63 | + // Streamed, because a two-hour 5.1 track is ten gigabytes of `f32`. | |
| 64 | + let mut out = BufWriter::with_capacity(1 << 20, file); | |
| 65 | + let (mut pos, mut frames, mut samples, mut errors) = (0usize, 0u64, 0u64, Vec::new()); | |
| 66 | + let mut rate = 0; | |
| 67 | + let mut channels = 0; | |
| 68 | + let start = Instant::now(); | |
| 69 | + while pos + 6 <= data.len() { | |
| 70 | + if data[pos] != 0x0B || data[pos + 1] != 0x77 { | |
| 71 | + pos += 1; | |
| 72 | + continue; | |
| 73 | + } | |
| 74 | + let size = match ec_ac3::frame_size(&data[pos..]) { | |
| 75 | + Ok(size) if pos + size <= data.len() => size, | |
| 76 | + Ok(_) => break, | |
| 77 | + Err(e) => { | |
| 78 | + errors.push(format!("frame at {pos}: {e}")); | |
| 79 | + pos += 2; | |
| 80 | + continue; | |
| 81 | + } | |
| 82 | + }; | |
| 83 | + match decoder.decode_frame(&data[pos..pos + size]) { | |
| 84 | + Ok(frame) => { | |
| 85 | + rate = frame.rate; | |
| 86 | + channels = frame.channels(); | |
| 87 | + samples += frame.samples as u64; | |
| 88 | + frames += 1; | |
| 89 | + let _ = out.write_all(&frame.data[0]); | |
| 90 | + } | |
| 91 | + Err(e) => { | |
| 92 | + // Keep the timeline: a frame that will not decode becomes the | |
| 93 | + // silence it represents, so a comparison stays sample-aligned. | |
| 94 | + errors.push(format!("frame at {pos}: {e}")); | |
| 95 | + if channels > 0 { | |
| 96 | + let _ = out.write_all(&vec![0u8; channels * 1536 * 4]); | |
| 97 | + samples += 1536; | |
| 98 | + } | |
| 99 | + } | |
| 100 | + } | |
| 101 | + pos += size; | |
| 102 | + } | |
| 103 | + let elapsed = start.elapsed().as_secs_f64(); | |
| 104 | + | |
| 105 | + if let Err(e) = out.flush() { | |
| 106 | + eprintln!("ac3dec: {}: {e}", argv[1]); | |
| 107 | + std::process::exit(2); | |
| 108 | + } | |
| 109 | + let seconds = if rate > 0 { | |
| 110 | + samples as f64 / f64::from(rate) | |
| 111 | + } else { | |
| 112 | + 0.0 | |
| 113 | + }; | |
| 114 | + println!("frames\t{frames}"); | |
| 115 | + println!("channels\t{channels}"); | |
| 116 | + println!("sample_rate\t{rate}"); | |
| 117 | + println!("samples\t{samples}"); | |
| 118 | + println!("seconds\t{seconds:.3}"); | |
| 119 | + println!("decode_seconds\t{elapsed:.3}"); | |
| 120 | + println!( | |
| 121 | + "realtime\t{:.1}", | |
| 122 | + if elapsed > 0.0 { | |
| 123 | + seconds / elapsed | |
| 124 | + } else { | |
| 125 | + 0.0 | |
| 126 | + } | |
| 127 | + ); | |
| 128 | + println!("errors\t{}", errors.len()); | |
| 129 | + for e in errors.iter().take(5) { | |
| 130 | + println!("error\t{e}"); | |
| 131 | + } | |
| 132 | + if frames == 0 { | |
| 133 | + std::process::exit(1); | |
| 134 | + } | |
| 135 | +} |
crates/ec-ac3/tests/decode_matrix.rsadded+277 -0
| @@ -0,0 +1,277 @@ | ||
| 1 | +//! Fixture matrix: every generated AC-3 and E-AC-3 fixture decoded and | |
| 2 | +//! compared against ffmpeg, plus the header surface a container reads and the | |
| 3 | +//! no-panic contract on damaged input. | |
| 4 | +//! | |
| 5 | +//! ffmpeg is test tooling — it is driven through `std::process` so the crate | |
| 6 | +//! itself never gains a media dependency. Missing fixtures or a missing ffmpeg | |
| 7 | +//! skip the comparison rather than fail it; `scripts/gen-fixtures.sh` writes | |
| 8 | +//! the fixtures. | |
| 9 | + | |
| 10 | +use std::path::{Path, PathBuf}; | |
| 11 | +use std::process::Command; | |
| 12 | + | |
| 13 | +use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo}; | |
| 14 | + | |
| 15 | +/// Per-channel correlation floor (rubric: audio-ac3 MUST). | |
| 16 | +const MIN_CORR: f64 = 0.999; | |
| 17 | +/// RMS delta ceiling on the fixture matrix, where both decoders see the same | |
| 18 | +/// synthetic material. | |
| 19 | +const MAX_RMS: f64 = 1e-3; | |
| 20 | + | |
| 21 | +fn fixtures() -> PathBuf { | |
| 22 | + Path::new(env!("CARGO_MANIFEST_DIR")) | |
| 23 | + .join("../../fixtures/audio") | |
| 24 | + .canonicalize() | |
| 25 | + .unwrap_or_else(|_| PathBuf::from("../../fixtures/audio")) | |
| 26 | +} | |
| 27 | + | |
| 28 | +fn have_ffmpeg() -> bool { | |
| 29 | + Command::new("ffmpeg") | |
| 30 | + .arg("-version") | |
| 31 | + .output() | |
| 32 | + .is_ok_and(|o| o.status.success()) | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// ffmpeg's decode of `path` as interleaved `f32`. | |
| 36 | +fn reference(path: &Path) -> Vec<f32> { | |
| 37 | + let out = Command::new("ffmpeg") | |
| 38 | + .args(["-v", "error", "-i"]) | |
| 39 | + .arg(path) | |
| 40 | + .args(["-f", "f32le", "-"]) | |
| 41 | + .output() | |
| 42 | + .expect("ffmpeg"); | |
| 43 | + out.stdout | |
| 44 | + .chunks_exact(4) | |
| 45 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| 46 | + .collect() | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Our decode of a raw elementary stream, and the channel count. | |
| 50 | +fn decode(path: &Path, options: Options) -> (Vec<f32>, usize) { | |
| 51 | + let data = std::fs::read(path).expect("fixture"); | |
| 52 | + let mut decoder = Ac3Decoder::with_options(options); | |
| 53 | + let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize); | |
| 54 | + while pos + 6 <= data.len() { | |
| 55 | + if data[pos] != 0x0B || data[pos + 1] != 0x77 { | |
| 56 | + pos += 1; | |
| 57 | + continue; | |
| 58 | + } | |
| 59 | + let Ok(size) = ec_ac3::frame_size(&data[pos..]) else { | |
| 60 | + break; | |
| 61 | + }; | |
| 62 | + if pos + size > data.len() { | |
| 63 | + break; | |
| 64 | + } | |
| 65 | + let frame = decoder | |
| 66 | + .decode_frame(&data[pos..pos + size]) | |
| 67 | + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); | |
| 68 | + channels = frame.channels(); | |
| 69 | + out.extend( | |
| 70 | + frame.data[0] | |
| 71 | + .chunks_exact(4) | |
| 72 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), | |
| 73 | + ); | |
| 74 | + pos += size; | |
| 75 | + } | |
| 76 | + (out, channels) | |
| 77 | +} | |
| 78 | + | |
| 79 | +fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) { | |
| 80 | + let n = a.len().min(b.len()); | |
| 81 | + 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); | |
| 82 | + for i in 0..n { | |
| 83 | + let (x, y) = (f64::from(a[i]), f64::from(b[i])); | |
| 84 | + sa += x; | |
| 85 | + sb += y; | |
| 86 | + saa += x * x; | |
| 87 | + sbb += y * y; | |
| 88 | + sab += x * y; | |
| 89 | + sd += (x - y) * (x - y); | |
| 90 | + } | |
| 91 | + let n = n as f64; | |
| 92 | + let cov = sab / n - (sa / n) * (sb / n); | |
| 93 | + let va = saa / n - (sa / n).powi(2); | |
| 94 | + let vb = sbb / n - (sb / n).powi(2); | |
| 95 | + let corr = if va <= 0.0 || vb <= 0.0 { | |
| 96 | + 1.0 | |
| 97 | + } else { | |
| 98 | + cov / (va * vb).sqrt() | |
| 99 | + }; | |
| 100 | + (corr, (sd / n).sqrt()) | |
| 101 | +} | |
| 102 | + | |
| 103 | +#[test] | |
| 104 | +fn fixture_matrix_matches_ffmpeg() { | |
| 105 | + let dir = fixtures(); | |
| 106 | + if !dir.exists() || !have_ffmpeg() { | |
| 107 | + eprintln!("skipping: no fixtures or no ffmpeg"); | |
| 108 | + return; | |
| 109 | + } | |
| 110 | + let mut checked = 0; | |
| 111 | + for entry in std::fs::read_dir(&dir).expect("fixtures dir") { | |
| 112 | + let path = entry.expect("entry").path(); | |
| 113 | + let name = path.file_name().unwrap_or_default().to_string_lossy(); | |
| 114 | + if !(name.starts_with("ac3-") || name.starts_with("eac3-")) { | |
| 115 | + continue; | |
| 116 | + } | |
| 117 | + // Dither is "any reasonably random sequence" (§7.3.4), so two | |
| 118 | + // conformant decoders differ by exactly that noise. Comparing with it | |
| 119 | + // off is what isolates everything else; the with-dither run below | |
| 120 | + // bounds how much noise it adds. | |
| 121 | + let options = Options { | |
| 122 | + dither: false, | |
| 123 | + ..Options::default() | |
| 124 | + }; | |
| 125 | + let (ours, channels) = decode(&path, options); | |
| 126 | + let theirs = reference(&path); | |
| 127 | + assert!(channels > 0, "{name}: no channels"); | |
| 128 | + assert_eq!( | |
| 129 | + ours.len(), | |
| 130 | + theirs.len(), | |
| 131 | + "{name}: {} samples vs ffmpeg's {}", | |
| 132 | + ours.len(), | |
| 133 | + theirs.len() | |
| 134 | + ); | |
| 135 | + for ch in 0..channels { | |
| 136 | + let a: Vec<f32> = ours[ch..].iter().step_by(channels).copied().collect(); | |
| 137 | + let b: Vec<f32> = theirs[ch..].iter().step_by(channels).copied().collect(); | |
| 138 | + let (corr, rms) = correlation(&a, &b); | |
| 139 | + assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}"); | |
| 140 | + assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}"); | |
| 141 | + } | |
| 142 | + checked += 1; | |
| 143 | + } | |
| 144 | + assert!(checked >= 12, "only {checked} fixtures checked"); | |
| 145 | +} | |
| 146 | + | |
| 147 | +#[test] | |
| 148 | +fn dither_only_adds_noise_below_the_signal() { | |
| 149 | + let path = fixtures().join("ac3-5.1-48000.ac3"); | |
| 150 | + if !path.exists() { | |
| 151 | + return; | |
| 152 | + } | |
| 153 | + let (with, channels) = decode(&path, Options::default()); | |
| 154 | + let (without, _) = decode( | |
| 155 | + &path, | |
| 156 | + Options { | |
| 157 | + dither: false, | |
| 158 | + ..Options::default() | |
| 159 | + }, | |
| 160 | + ); | |
| 161 | + assert_eq!(with.len(), without.len()); | |
| 162 | + let (corr, rms) = correlation(&with, &without); | |
| 163 | + assert!(channels == 6 && corr > 0.999, "correlation {corr:.6}"); | |
| 164 | + assert!(rms < 1e-3, "dither RMS {rms:.8}"); | |
| 165 | +} | |
| 166 | + | |
| 167 | +#[test] | |
| 168 | +fn headers_state_what_the_container_needs() { | |
| 169 | + let path = fixtures().join("ac3-5.1-48000.ac3"); | |
| 170 | + if !path.exists() { | |
| 171 | + return; | |
| 172 | + } | |
| 173 | + let data = std::fs::read(&path).expect("fixture"); | |
| 174 | + // The exact call shape a container makes: syncinfo from the frame start, | |
| 175 | + // bsi from five bytes in. | |
| 176 | + let sync = syncinfo::parse(&data).expect("syncinfo"); | |
| 177 | + assert_eq!(sync.sample_rate, 48_000); | |
| 178 | + assert_eq!(sync.frame_size % 2, 0); | |
| 179 | + let bsi = bsi::parse(&data[5..]).expect("bsi"); | |
| 180 | + assert_eq!(bsi.nfchans, 5); | |
| 181 | + assert!(bsi.lfeon); | |
| 182 | + assert_eq!(bsi.channels, 6); | |
| 183 | + assert!((1..=31).contains(&bsi.dialnorm)); | |
| 184 | + | |
| 185 | + let eac3_path = fixtures().join("eac3-5.1-48000.eac3"); | |
| 186 | + let data = std::fs::read(&eac3_path).expect("fixture"); | |
| 187 | + let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi"); | |
| 188 | + assert_eq!(hdr.sample_rate, 48_000); | |
| 189 | + assert_eq!(hdr.nfchans, 5); | |
| 190 | + assert!(hdr.bsi.lfeon); | |
| 191 | + assert_eq!( | |
| 192 | + hdr.frame_size, | |
| 193 | + ec_ac3::frame_size(&data).expect("frame size") | |
| 194 | + ); | |
| 195 | +} | |
| 196 | + | |
| 197 | +#[test] | |
| 198 | +fn frame_info_surfaces_the_metadata_the_rubric_asks_for() { | |
| 199 | + let path = fixtures().join("ac3-5.1-48000.ac3"); | |
| 200 | + if !path.exists() { | |
| 201 | + return; | |
| 202 | + } | |
| 203 | + let data = std::fs::read(&path).expect("fixture"); | |
| 204 | + let size = ec_ac3::frame_size(&data).expect("frame size"); | |
| 205 | + let mut decoder = Ac3Decoder::new(); | |
| 206 | + decoder.decode_frame(&data[..size]).expect("decode"); | |
| 207 | + let info = decoder.frame_info().expect("frame info"); | |
| 208 | + assert_eq!(info.syntax, Syntax::Ac3); | |
| 209 | + assert_eq!(info.sample_rate, 48_000); | |
| 210 | + assert!((1..=31).contains(&info.dialnorm)); | |
| 211 | + // ffmpeg's encoder writes cmixlev 1 (-4.5 dB) and surmixlev 1 (-6 dB). | |
| 212 | + assert_eq!(info.center_mix_level, Some(0.595)); | |
| 213 | + assert_eq!(info.surround_mix_level, Some(0.5)); | |
| 214 | + assert_eq!(info.samples, 1536); | |
| 215 | +} | |
| 216 | + | |
| 217 | +#[test] | |
| 218 | +fn stereo_downmix_folds_five_one_without_clipping() { | |
| 219 | + let path = fixtures().join("ac3-5.1-48000.ac3"); | |
| 220 | + if !path.exists() { | |
| 221 | + return; | |
| 222 | + } | |
| 223 | + let (stereo, channels) = decode( | |
| 224 | + &path, | |
| 225 | + Options { | |
| 226 | + downmix: Downmix::Stereo, | |
| 227 | + ..Options::default() | |
| 228 | + }, | |
| 229 | + ); | |
| 230 | + assert_eq!(channels, 2); | |
| 231 | + let (native, _) = decode(&path, Options::default()); | |
| 232 | + assert_eq!(stereo.len() * 3, native.len()); | |
| 233 | + assert!(stereo.iter().all(|v| v.abs() <= 1.0), "downmix clipped"); | |
| 234 | + assert!(stereo.iter().any(|v| v.abs() > 0.01), "downmix is silent"); | |
| 235 | + | |
| 236 | + let (mono, channels) = decode( | |
| 237 | + &path, | |
| 238 | + Options { | |
| 239 | + downmix: Downmix::Mono, | |
| 240 | + ..Options::default() | |
| 241 | + }, | |
| 242 | + ); | |
| 243 | + assert_eq!(channels, 1); | |
| 244 | + assert_eq!(mono.len() * 6, native.len()); | |
| 245 | +} | |
| 246 | + | |
| 247 | +#[test] | |
| 248 | +fn damaged_input_never_panics() { | |
| 249 | + let path = fixtures().join("ac3-stereo-48000.ac3"); | |
| 250 | + if !path.exists() { | |
| 251 | + return; | |
| 252 | + } | |
| 253 | + let data = std::fs::read(&path).expect("fixture"); | |
| 254 | + let size = ec_ac3::frame_size(&data).expect("frame size"); | |
| 255 | + let frame = &data[..size]; | |
| 256 | + let mut decoder = Ac3Decoder::new(); | |
| 257 | + | |
| 258 | + // Every truncation. | |
| 259 | + for cut in 0..frame.len() { | |
| 260 | + let _ = decoder.decode_frame(&frame[..cut]); | |
| 261 | + } | |
| 262 | + // Every single-byte corruption at a stride that still hits every field | |
| 263 | + // class: header, side information, exponents, mantissas. | |
| 264 | + for pos in (0..frame.len()).step_by(7) { | |
| 265 | + let mut broken = frame.to_vec(); | |
| 266 | + broken[pos] ^= 0xA5; | |
| 267 | + let _ = decoder.decode_frame(&broken); | |
| 268 | + } | |
| 269 | + // Garbage that happens to start with a sync word. | |
| 270 | + let mut noise = vec![0x0B, 0x77]; | |
| 271 | + let mut state = 12345u32; | |
| 272 | + for _ in 0..4096 { | |
| 273 | + state = state.wrapping_mul(1_103_515_245).wrapping_add(12345); | |
| 274 | + noise.push((state >> 16) as u8); | |
| 275 | + } | |
| 276 | + let _ = decoder.decode_frame(&noise); | |
| 277 | +} |