forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

decode_matrix.rs351 lines, 12.4 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};
14use crate::common::have_ffmpeg;
15
16/// Per-channel correlation floor (rubric: audio-ac3 MUST).
17const MIN_CORR: f64 = 0.999;
18/// RMS delta ceiling on the fixture matrix, where both decoders see the same
19/// synthetic material.
20const MAX_RMS: f64 = 1e-3;
21
22fn fixtures() -> PathBuf {
23 Path::new(env!("CARGO_MANIFEST_DIR"))
24 .join("../../fixtures/audio")
25 .canonicalize()
26 .unwrap_or_else(|_| PathBuf::from("../../fixtures/audio"))
27}
28
29/// ffmpeg's decode of `path` as interleaved `f32`.
30fn reference(path: &Path) -> Vec<f32> {
31 let out = Command::new("ffmpeg")
32 .args(["-v", "error", "-i"])
33 .arg(path)
34 .args(["-f", "f32le", "-"])
35 .output()
36 .expect("ffmpeg");
37 out.stdout
38 .as_chunks::<4>().0.iter()
39 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
40 .collect()
41}
42
43/// Our decode of a raw elementary stream, and the channel count.
44fn decode(path: &Path, options: Options) -> (Vec<f32>, usize) {
45 let data = std::fs::read(path).expect("fixture");
46 let mut decoder = Ac3Decoder::with_options(options);
47 let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize);
48 while pos + 6 <= data.len() {
49 if data[pos] != 0x0B || data[pos + 1] != 0x77 {
50 pos += 1;
51 continue;
52 }
53 let Ok(size) = ec_ac3::frame_size(&data[pos..]) else {
54 break;
55 };
56 if pos + size > data.len() {
57 break;
58 }
59 let frame = decoder
60 .decode_frame(&data[pos..pos + size])
61 .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
62 channels = frame.channels();
63 out.extend(
64 frame.data[0]
65 .as_chunks::<4>().0.iter()
66 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
67 );
68 pos += size;
69 }
70 (out, channels)
71}
72
73fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) {
74 let n = a.len().min(b.len());
75 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);
76 for i in 0..n {
77 let (x, y) = (f64::from(a[i]), f64::from(b[i]));
78 sa += x;
79 sb += y;
80 saa += x * x;
81 sbb += y * y;
82 sab += x * y;
83 sd += (x - y) * (x - y);
84 }
85 let n = n as f64;
86 let cov = sab / n - (sa / n) * (sb / n);
87 let va = saa / n - (sa / n).powi(2);
88 let vb = sbb / n - (sb / n).powi(2);
89 let corr = if va <= 0.0 || vb <= 0.0 {
90 1.0
91 } else {
92 cov / (va * vb).sqrt()
93 };
94 (corr, (sd / n).sqrt())
95}
96
97#[test]
98fn fixture_matrix_matches_ffmpeg() {
99 let dir = fixtures();
100 if !dir.exists() || !have_ffmpeg() {
101 eprintln!("skipping: no fixtures or no ffmpeg");
102 return;
103 }
104 let mut checked = 0;
105 for entry in std::fs::read_dir(&dir).expect("fixtures dir") {
106 let path = entry.expect("entry").path();
107 let name = path.file_name().unwrap_or_default().to_string_lossy();
108 if !(name.starts_with("ac3-") || name.starts_with("eac3-")) {
109 continue;
110 }
111 // Dither is "any reasonably random sequence" (§7.3.4), so two
112 // conformant decoders differ by exactly that noise. Comparing with it
113 // off is what isolates everything else; the with-dither run below
114 // bounds how much noise it adds.
115 let options = Options {
116 dither: false,
117 ..Options::default()
118 };
119 let (ours, channels) = decode(&path, options);
120 let theirs = reference(&path);
121 assert!(channels > 0, "{name}: no channels");
122 assert_eq!(
123 ours.len(),
124 theirs.len(),
125 "{name}: {} samples vs ffmpeg's {}",
126 ours.len(),
127 theirs.len()
128 );
129 for ch in 0..channels {
130 let a: Vec<f32> = ours[ch..].iter().step_by(channels).copied().collect();
131 let b: Vec<f32> = theirs[ch..].iter().step_by(channels).copied().collect();
132 let (corr, rms) = correlation(&a, &b);
133 assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}");
134 assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}");
135 }
136 checked += 1;
137 }
138 assert!(checked >= 12, "only {checked} fixtures checked");
139}
140
141#[test]
142fn dither_only_adds_noise_below_the_signal() {
143 let path = fixtures().join("ac3-5.1-48000.ac3");
144 if !path.exists() {
145 return;
146 }
147 let (with, channels) = decode(&path, Options::default());
148 let (without, _) = decode(
149 &path,
150 Options {
151 dither: false,
152 ..Options::default()
153 },
154 );
155 assert_eq!(with.len(), without.len());
156 let (corr, rms) = correlation(&with, &without);
157 assert!(channels == 6 && corr > 0.999, "correlation {corr:.6}");
158 assert!(rms < 1e-3, "dither RMS {rms:.8}");
159}
160
161#[test]
162fn headers_state_what_the_container_needs() {
163 let path = fixtures().join("ac3-5.1-48000.ac3");
164 if !path.exists() {
165 return;
166 }
167 let data = std::fs::read(&path).expect("fixture");
168 // The exact call shape a container makes: syncinfo from the frame start,
169 // bsi from five bytes in.
170 let sync = syncinfo::parse(&data).expect("syncinfo");
171 assert_eq!(sync.sample_rate, 48_000);
172 assert_eq!(sync.frame_size % 2, 0);
173 let bsi = bsi::parse(&data[5..]).expect("bsi");
174 assert_eq!(bsi.nfchans, 5);
175 assert!(bsi.lfeon);
176 assert_eq!(bsi.channels, 6);
177 assert!((1..=31).contains(&bsi.dialnorm));
178
179 let eac3_path = fixtures().join("eac3-5.1-48000.eac3");
180 let data = std::fs::read(&eac3_path).expect("fixture");
181 let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi");
182 assert_eq!(hdr.sample_rate, 48_000);
183 assert_eq!(hdr.nfchans, 5);
184 assert!(hdr.bsi.lfeon);
185 assert_eq!(
186 hdr.frame_size,
187 ec_ac3::frame_size(&data).expect("frame size")
188 );
189}
190
191#[test]
192fn frame_info_surfaces_the_metadata_the_rubric_asks_for() {
193 let path = fixtures().join("ac3-5.1-48000.ac3");
194 if !path.exists() {
195 return;
196 }
197 let data = std::fs::read(&path).expect("fixture");
198 let size = ec_ac3::frame_size(&data).expect("frame size");
199 let mut decoder = Ac3Decoder::new();
200 decoder.decode_frame(&data[..size]).expect("decode");
201 let info = decoder.frame_info().expect("frame info");
202 assert_eq!(info.syntax, Syntax::Ac3);
203 assert_eq!(info.sample_rate, 48_000);
204 assert!((1..=31).contains(&info.dialnorm));
205 // ffmpeg's encoder writes cmixlev 1 (-4.5 dB) and surmixlev 1 (-6 dB).
206 assert_eq!(info.center_mix_level, Some(0.595));
207 assert_eq!(info.surround_mix_level, Some(0.5));
208 assert_eq!(info.samples, 1536);
209}
210
211#[test]
212fn stereo_downmix_folds_five_one_without_clipping() {
213 let path = fixtures().join("ac3-5.1-48000.ac3");
214 if !path.exists() {
215 return;
216 }
217 let (stereo, channels) = decode(
218 &path,
219 Options {
220 downmix: Downmix::Stereo,
221 ..Options::default()
222 },
223 );
224 assert_eq!(channels, 2);
225 let (native, _) = decode(&path, Options::default());
226 assert_eq!(stereo.len() * 3, native.len());
227 assert!(stereo.iter().all(|v| v.abs() <= 1.0), "downmix clipped");
228 assert!(stereo.iter().any(|v| v.abs() > 0.01), "downmix is silent");
229
230 let (mono, channels) = decode(
231 &path,
232 Options {
233 downmix: Downmix::Mono,
234 ..Options::default()
235 },
236 );
237 assert_eq!(channels, 1);
238 assert_eq!(mono.len() * 6, native.len());
239}
240
241#[test]
242fn damaged_input_never_panics() {
243 let path = fixtures().join("ac3-stereo-48000.ac3");
244 if !path.exists() {
245 return;
246 }
247 let data = std::fs::read(&path).expect("fixture");
248 let size = ec_ac3::frame_size(&data).expect("frame size");
249 let frame = &data[..size];
250 let mut decoder = Ac3Decoder::new();
251
252 // Every truncation.
253 for cut in 0..frame.len() {
254 let _ = decoder.decode_frame(&frame[..cut]);
255 }
256 // Every single-byte corruption at a stride that still hits every field
257 // class: header, side information, exponents, mantissas.
258 for pos in (0..frame.len()).step_by(7) {
259 let mut broken = frame.to_vec();
260 broken[pos] ^= 0xA5;
261 let _ = decoder.decode_frame(&broken);
262 }
263 // Garbage that happens to start with a sync word.
264 let mut noise = vec![0x0B, 0x77];
265 let mut state = 12345u32;
266 for _ in 0..4096 {
267 state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
268 noise.push((state >> 16) as u8);
269 }
270 let _ = decoder.decode_frame(&noise);
271}
272
273/// A packet that carries a second frame after the first — the shape a
274/// Matroska block for 7.1 DD+ really has (independent substream plus its
275/// dependent) — must not decode to the first frame's samples in silence:
276/// the tail is stream, and dropping it loses the extension channels without
277/// a word. Built from two real frames of the fixture: the tail as it stands
278/// (another independent frame) is refused as a second syncframe, and the
279/// same packet with the tail's stream-type bits flipped to `dependent` is
280/// refused as the dependent substream it then claims to be. The AC-3 path
281/// answers the same way for an AC-3 tail.
282#[test]
283fn a_concatenated_tail_is_refused_by_name_not_dropped() {
284 let dir = fixtures();
285 if !dir.join("eac3-5.1-48000.eac3").exists() {
286 eprintln!("skipping: no fixtures");
287 return;
288 }
289 for name in ["ac3-5.1-48000.ac3", "eac3-5.1-48000.eac3"] {
290 let data = std::fs::read(dir.join(name)).expect("fixture");
291 let first = ec_ac3::frame_size(&data).expect("first frame size");
292 let second = ec_ac3::frame_size(&data[first..]).expect("second frame size");
293 let mut packet = data[..first].to_vec();
294 packet.extend_from_slice(&data[first..first + second]);
295
296 let mut dec = Ac3Decoder::new();
297 let err = dec
298 .decode_frame(&packet)
299 .expect_err("{name}: the tail is stream, not padding");
300 let text = err.to_string();
301 eprintln!("{name}: {text}");
302 assert!(
303 text.contains("second syncframe"),
304 "{name}: the independent tail must name itself: {text}"
305 );
306 if name.starts_with("eac3") {
307 // Flip the tail's stream-type (bits 16..18 of a frame: the top
308 // two bits of byte 2) to `dependent`. The packet is then the
309 // shape a 7.1 DD+ block carries, and the refusal names the
310 // dependent substream.
311 let mut dep_packet = packet.clone();
312 dep_packet[first + 2] = (dep_packet[first + 2] & 0x3F) | 0x40;
313 let err = dec
314 .decode_frame(&dep_packet)
315 .expect_err("the dependent tail is stream");
316 let text = err.to_string();
317 eprintln!("{name} (tail flipped to dependent): {text}");
318 assert!(
319 text.contains("dependent substream"),
320 "the dependent tail must name itself: {text}"
321 );
322 }
323 }
324}
325
326/// The spec's own allowance: a container may pad a block around a frame, and
327/// padding that is not itself a syncframe decodes exactly like the bare
328/// frame — sample for sample, whatever its length.
329#[test]
330fn padding_that_is_not_a_syncframe_still_decodes() {
331 let path = fixtures().join("ac3-5.1-48000.ac3");
332 if !path.exists() {
333 eprintln!("skipping: no fixtures");
334 return;
335 }
336 let data = std::fs::read(&path).expect("fixture");
337 let first = ec_ac3::frame_size(&data).expect("frame size");
338 let frame = &data[..first];
339 let mut dec = Ac3Decoder::new();
340 let bare = dec.decode_frame(frame).expect("bare frame");
341 for pad in [1usize, 6, 64, 1024] {
342 let mut padded = frame.to_vec();
343 padded.resize(first + pad, 0x00);
344 let mut dec = Ac3Decoder::new();
345 let got = dec.decode_frame(&padded).expect("padded frame decodes");
346 assert!(
347 got.data[0].iter().eq(bare.data[0].iter()),
348 "pad of {pad} bytes changed the audio"
349 );
350 }
351}