forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe2fa4f0Tahinli2 months ago3028 commits

encode_matrix.rs422 lines, 16.3 KiBHistoryRawDownload
1//! Encoder coverage: frames our own decoder round-trips, and that ffmpeg
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.
5
6use std::path::Path;
7use std::process::Command;
8
9use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig};
10
11fn have_ffmpeg() -> bool {
12 Command::new("ffmpeg")
13 .arg("-version")
14 .output()
15 .is_ok_and(|o| o.status.success())
16}
17
18/// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`.
19fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec<f32> {
20 let tone_samples = sample_rate as usize;
21 let silence_samples = sample_rate as usize / 2;
22 let mut out = Vec::with_capacity((tone_samples + silence_samples) * channels);
23 for n in 0..tone_samples {
24 let t = n as f32 / sample_rate as f32;
25 let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
26 for _ in 0..channels {
27 out.push(v);
28 }
29 }
30 out.extend(std::iter::repeat_n(0.0f32, silence_samples * channels));
31 out
32}
33
34fn correlation(a: &[f32], b: &[f32]) -> f64 {
35 let n = a.len().min(b.len());
36 if n == 0 {
37 return 0.0;
38 }
39 let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0);
40 for i in 0..n {
41 let (x, y) = (f64::from(a[i]), f64::from(b[i]));
42 sa += x;
43 sb += y;
44 saa += x * x;
45 sbb += y * y;
46 sab += x * y;
47 }
48 let n = n as f64;
49 let cov = sab / n - (sa / n) * (sb / n);
50 let va = (saa / n - (sa / n).powi(2)).max(0.0);
51 let vb = (sbb / n - (sb / n).powi(2)).max(0.0);
52 if va <= 0.0 || vb <= 0.0 {
53 return 1.0; // both flat (silence): trivially aligned
54 }
55 cov / (va.sqrt() * vb.sqrt())
56}
57
58/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts
59/// with this many samples of silence per channel.
60const 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.
65fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 {
66 let b = &b[DELAY.min(b.len())..];
67 let mut best = -1.0f64;
68 for lag in -64i32..=64 {
69 let (sa, sb): (&[f32], &[f32]) = if lag >= 0 {
70 (&a[lag as usize..], b)
71 } else {
72 (a, &b[(-lag) as usize..])
73 };
74 best = best.max(correlation(sa, sb));
75 }
76 best
77}
78
79/// Deinterleave channel `ch` of `channels`.
80fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> {
81 interleaved
82 .iter()
83 .skip(ch)
84 .step_by(channels)
85 .copied()
86 .collect()
87}
88
89/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None
90/// without ffmpeg.
91fn 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
111fn 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
122fn 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.
129fn 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
147fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec<u8>, ec_ac3::EncodeStats) {
148 let mut enc = Ac3Encoder::new(config).unwrap();
149 enc.push_pcm_f32(pcm).unwrap();
150 enc.finish();
151 let mut out = Vec::new();
152 loop {
153 match enc.next_packet() {
154 Ok(frame) => out.extend_from_slice(&frame),
155 Err(e) if e.is_eof() => break,
156 Err(e) => panic!("{e}"),
157 }
158 }
159 (out, enc.stats())
160}
161
162fn 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`.
167fn 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.
177fn 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.
185fn 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()
192}
193
194fn decode_all(data: &[u8], channels: usize) -> Vec<f32> {
195 let mut decoder = Ac3Decoder::new();
196 let mut out = Vec::new();
197 let mut pos = 0;
198 while pos + 6 <= data.len() {
199 let size = ec_ac3::frame_size(&data[pos..]).unwrap();
200 assert!(pos + size <= data.len(), "frame overruns the stream");
201 let frame = decoder
202 .decode_frame(&data[pos..pos + size])
203 .unwrap_or_else(|e| panic!("frame at byte {pos}: {e}"));
204 assert_eq!(frame.samples, 1536);
205 assert_eq!(frame.channels(), channels);
206 out.extend(
207 frame.data[0]
208 .chunks_exact(4)
209 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
210 );
211 pos += size;
212 }
213 out
214}
215
216#[test]
217fn silence_and_tone_frames_decode_in_our_decoder() {
218 for &(sample_rate, channels) in &[(48_000u32, 1u16), (48_000, 2), (48_000, 6), (44_100, 2)] {
219 let config = EncoderConfig {
220 sample_rate,
221 channels,
222 bitrate_kbps: if channels >= 5 { 384 } else { 192 },
223 };
224 let pcm = tone_then_silence(sample_rate, channels as usize);
225 let data = encode(config, &pcm);
226 assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames");
227 let decoded = decode_all(&data, channels as usize);
228 assert!(!decoded.is_empty());
229 let corr = worst_corr(&pcm, &decoded, channels as usize);
230 assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}");
231 }
232}
233
234#[test]
235fn oracle_accepts_our_frames() {
236 if !have_ffmpeg() {
237 eprintln!("skipping: ffmpeg not found");
238 return;
239 }
240 let config = EncoderConfig {
241 sample_rate: 48_000,
242 channels: 2,
243 bitrate_kbps: 192,
244 };
245 let pcm = tone_then_silence(48_000, 2);
246 let data = encode(config, &pcm);
247 let dir = std::env::temp_dir();
248 let path = dir.join("ec_ac3_encode_matrix_oracle.ac3");
249 std::fs::write(&path, &data).unwrap();
250
251 let out = Command::new("ffmpeg")
252 .args(["-v", "warning", "-i"])
253 .arg(&path)
254 .args(["-f", "f32le", "-"])
255 .output()
256 .expect("ffmpeg");
257 let stderr = String::from_utf8_lossy(&out.stderr);
258 let complaint = stderr
259 .lines()
260 .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
261 assert!(
262 !complaint,
263 "ffmpeg complained about our frames:\n{stderr}"
264 );
265
266 let decoded: Vec<f32> = out
267 .stdout
268 .chunks_exact(4)
269 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
270 .collect();
271 for ch in 0..2 {
272 let want = take_channel(&pcm, 2, ch);
273 let got = take_channel(&decoded, 2, ch);
274 let corr = best_lag_correlation(&want, &got);
275 assert!(corr >= 0.95, "oracle channel {ch} corr {corr}");
276 }
277
278 let _ = std::fs::remove_file(Path::new(&path));
279}
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]
286fn 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]
345fn 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]
376fn 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]
404fn 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