forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

decode_matrix.rs277 lines, 9.0 KiBHistoryRawDownload
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
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo};
14
15/// Per-channel correlation floor (rubric: audio-ac3 MUST).
16const MIN_CORR: f64 = 0.999;
17/// RMS delta ceiling on the fixture matrix, where both decoders see the same
18/// synthetic material.
19const MAX_RMS: f64 = 1e-3;
20
21fn 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
28fn 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`.
36fn 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.
50fn 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
79fn 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]
104fn 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]
148fn 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]
168fn 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]
198fn 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]
218fn 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]
248fn 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}