forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encode_matrix.rs416 lines, 16.2 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};
10use crate::common::have_ffmpeg;
11
12/// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`.
13fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec<f32> {
14 let tone_samples = sample_rate as usize;
15 let silence_samples = sample_rate as usize / 2;
16 let mut out = Vec::with_capacity((tone_samples + silence_samples) * channels);
17 for n in 0..tone_samples {
18 let t = n as f32 / sample_rate as f32;
19 let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
20 for _ in 0..channels {
21 out.push(v);
22 }
23 }
24 out.extend(std::iter::repeat_n(0.0f32, silence_samples * channels));
25 out
26}
27
28fn correlation(a: &[f32], b: &[f32]) -> f64 {
29 let n = a.len().min(b.len());
30 if n == 0 {
31 return 0.0;
32 }
33 let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0);
34 for i in 0..n {
35 let (x, y) = (f64::from(a[i]), f64::from(b[i]));
36 sa += x;
37 sb += y;
38 saa += x * x;
39 sbb += y * y;
40 sab += x * y;
41 }
42 let n = n as f64;
43 let cov = sab / n - (sa / n) * (sb / n);
44 let va = (saa / n - (sa / n).powi(2)).max(0.0);
45 let vb = (sbb / n - (sb / n).powi(2)).max(0.0);
46 if va <= 0.0 || vb <= 0.0 {
47 return 1.0; // both flat (silence): trivially aligned
48 }
49 cov / (va.sqrt() * vb.sqrt())
50}
51
52/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts
53/// with this many samples of silence per channel.
54const DELAY: usize = 256;
55
56/// Lag-searched correlation on one channel after the priming is dropped,
57/// +/- 64 samples of slack: a bug that shifts the audio by a block shows up
58/// as ~0 here, where an unbounded search on a periodic signal would hide it.
59fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 {
60 let b = &b[DELAY.min(b.len())..];
61 let mut best = -1.0f64;
62 for lag in -64i32..=64 {
63 let (sa, sb): (&[f32], &[f32]) = if lag >= 0 {
64 (&a[lag as usize..], b)
65 } else {
66 (a, &b[(-lag) as usize..])
67 };
68 best = best.max(correlation(sa, sb));
69 }
70 best
71}
72
73/// Deinterleave channel `ch` of `channels`.
74fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> {
75 interleaved
76 .iter()
77 .skip(ch)
78 .step_by(channels)
79 .copied()
80 .collect()
81}
82
83/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None
84/// without ffmpeg.
85fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
86 let out = Command::new("ffmpeg")
87 .args(["-v", "error", "-i"])
88 .arg(path)
89 .args(["-f", "f32le", "-"])
90 .output()
91 .ok()?;
92 if !out.status.success() {
93 return None;
94 }
95 let samples = out
96 .stdout
97 .as_chunks::<4>().0.iter()
98 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
99 .collect();
100 let probe = ffprobe(path, "channels,sample_rate");
101 let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::<u32>().ok());
102 Some((samples, field("sample_rate")?, field("channels")? as usize))
103}
104
105fn ffprobe(path: &Path, entries: &str) -> String {
106 let out = Command::new("ffprobe")
107 .args(["-v", "error", "-select_streams", "a:0", "-show_entries"])
108 .arg(format!("stream={entries}"))
109 .args(["-of", "default=noprint_wrappers=1"])
110 .arg(path)
111 .output()
112 .expect("ffprobe");
113 String::from_utf8_lossy(&out.stdout).into_owned()
114}
115
116fn probe_field(text: &str, key: &str) -> Option<String> {
117 text.lines()
118 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
119 .map(|v| v.trim().to_owned())
120}
121
122/// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint.
123fn oracle_decode(path: &Path) -> Vec<f32> {
124 let out = Command::new("ffmpeg")
125 .args(["-v", "warning", "-i"])
126 .arg(path)
127 .args(["-f", "f32le", "-"])
128 .output()
129 .expect("ffmpeg");
130 let stderr = String::from_utf8_lossy(&out.stderr);
131 let complaint = stderr
132 .lines()
133 .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
134 assert!(!complaint, "ffmpeg complained about {}:\n{stderr}", path.display());
135 out.stdout
136 .as_chunks::<4>().0.iter()
137 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
138 .collect()
139}
140
141fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec<u8>, ec_ac3::EncodeStats) {
142 let mut enc = Ac3Encoder::new(config).unwrap();
143 enc.push_pcm_f32(pcm).unwrap();
144 enc.finish();
145 let mut out = Vec::new();
146 loop {
147 match enc.next_packet() {
148 Ok(frame) => out.extend_from_slice(&frame),
149 Err(e) if e.is_eof() => break,
150 Err(e) => panic!("{e}"),
151 }
152 }
153 (out, enc.stats())
154}
155
156fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> {
157 encode_with_stats(config, pcm).0
158}
159
160/// Worst per-channel lag-searched correlation between `want` and `got`.
161fn worst_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
162 (0..channels)
163 .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
164 .fold(1.0, f64::min)
165}
166
167/// [`worst_corr`] over the full-bandwidth channels only: the LFE (family slot
168/// 3 of six) is band-limited to 7 bins (~660 Hz at 48 kHz) by the standard,
169/// so a fixture whose LFE carries full-band content can never correlate with
170/// it; that channel is gated on our decoder agreeing with the oracle instead.
171fn worst_fbw_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
172 (0..channels)
173 .filter(|&ch| !(channels == 6 && ch == 3))
174 .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
175 .fold(1.0, f64::min)
176}
177
178/// Deterministic white noise, `len` interleaved samples.
179fn noise(len: usize, seed: &mut u64) -> Vec<f32> {
180 (0..len)
181 .map(|_| {
182 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
183 ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
184 })
185 .collect()
186}
187
188fn decode_all(data: &[u8], channels: usize) -> Vec<f32> {
189 let mut decoder = Ac3Decoder::new();
190 let mut out = Vec::new();
191 let mut pos = 0;
192 while pos + 6 <= data.len() {
193 let size = ec_ac3::frame_size(&data[pos..]).unwrap();
194 assert!(pos + size <= data.len(), "frame overruns the stream");
195 let frame = decoder
196 .decode_frame(&data[pos..pos + size])
197 .unwrap_or_else(|e| panic!("frame at byte {pos}: {e}"));
198 assert_eq!(frame.samples, 1536);
199 assert_eq!(frame.channels(), channels);
200 out.extend(
201 frame.data[0]
202 .as_chunks::<4>().0.iter()
203 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
204 );
205 pos += size;
206 }
207 out
208}
209
210#[test]
211fn silence_and_tone_frames_decode_in_our_decoder() {
212 for &(sample_rate, channels) in &[(48_000u32, 1u16), (48_000, 2), (48_000, 6), (44_100, 2)] {
213 let config = EncoderConfig {
214 sample_rate,
215 channels,
216 bitrate_kbps: if channels >= 5 { 384 } else { 192 },
217 };
218 let pcm = tone_then_silence(sample_rate, channels as usize);
219 let data = encode(config, &pcm);
220 assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames");
221 let decoded = decode_all(&data, channels as usize);
222 assert!(!decoded.is_empty());
223 let corr = worst_corr(&pcm, &decoded, channels as usize);
224 assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}");
225 }
226}
227
228#[test]
229fn oracle_accepts_our_frames() {
230 if !have_ffmpeg() {
231 eprintln!("skipping: ffmpeg not found");
232 return;
233 }
234 let config = EncoderConfig {
235 sample_rate: 48_000,
236 channels: 2,
237 bitrate_kbps: 192,
238 };
239 let pcm = tone_then_silence(48_000, 2);
240 let data = encode(config, &pcm);
241 let dir = std::env::temp_dir();
242 let path = dir.join("ec_ac3_encode_matrix_oracle.ac3");
243 std::fs::write(&path, &data).unwrap();
244
245 let out = Command::new("ffmpeg")
246 .args(["-v", "warning", "-i"])
247 .arg(&path)
248 .args(["-f", "f32le", "-"])
249 .output()
250 .expect("ffmpeg");
251 let stderr = String::from_utf8_lossy(&out.stderr);
252 let complaint = stderr
253 .lines()
254 .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
255 assert!(
256 !complaint,
257 "ffmpeg complained about our frames:\n{stderr}"
258 );
259
260 let decoded: Vec<f32> = out
261 .stdout
262 .as_chunks::<4>().0.iter()
263 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
264 .collect();
265 for ch in 0..2 {
266 let want = take_channel(&pcm, 2, ch);
267 let got = take_channel(&decoded, 2, ch);
268 let corr = best_lag_correlation(&want, &got);
269 assert!(corr >= 0.95, "oracle channel {ch} corr {corr}");
270 }
271
272 let _ = std::fs::remove_file(Path::new(&path));
273}
274
275
276/// The full fixture matrix: every wav16 fixture at its layout's bit rate,
277/// through our decoder and the oracle, with ffprobe agreeing on what was
278/// asked for. Prints the per-file numbers and the stereo strategy shares.
279#[test]
280fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() {
281 if !have_ffmpeg() {
282 eprintln!("skipping: ffmpeg not found");
283 return;
284 }
285 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio");
286 let mut failures = Vec::new();
287 for layout in ["mono", "stereo", "5.1"] {
288 for rate in [48_000u32, 44_100] {
289 let path = root.join(format!("wav16-{layout}-{rate}.wav"));
290 let (pcm, sample_rate, channels) = read_wav(&path).unwrap_or_else(|| panic!("{}", path.display()));
291 assert_eq!(sample_rate, rate);
292 let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 };
293 let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps };
294 let (data, stats) = encode_with_stats(config, &pcm);
295 let frame = ec_ac3::frame_size(&data).unwrap();
296 assert_eq!(data.len() % frame, 0, "{layout} {rate}: frames are not all {frame} bytes");
297
298 let decoded = decode_all(&data, channels);
299 let ours = worst_fbw_corr(&pcm, &decoded, channels);
300 let out = std::env::temp_dir().join(format!("ec_ac3_encode_matrix_{layout}_{rate}.ac3"));
301 std::fs::write(&out, &data).unwrap();
302 let oracle_pcm = oracle_decode(&out);
303 let oracle = worst_fbw_corr(&pcm, &oracle_pcm, channels);
304 if channels == 6 {
305 let lfe = correlation(&take_channel(&decoded, 6, 3), &take_channel(&oracle_pcm, 6, 3));
306 assert!(lfe >= 0.99, "{layout} {rate}: LFE ours vs oracle corr {lfe}");
307 }
308 let probe = ffprobe(&out, "channels,channel_layout,sample_rate,bit_rate");
309 let _ = std::fs::remove_file(&out);
310
311 let total = (stats.d15 + stats.d25 + stats.d45 + stats.reuse) as f64;
312 let share = |n: u64| n as f64 / total * 100.0;
313 eprintln!(
314 "{layout} {rate}: {} frames, ours {ours:.4} oracle {oracle:.4}, csnroffst mean {:.1}, fill {:.1}%, blksw {}, D15 {:.1}% D25 {:.1}% D45 {:.1}% REUSE {:.1}%",
315 stats.frames,
316 stats.csnroffst_sum as f64 / stats.frames as f64,
317 stats.bits_used as f64 / stats.bits_budget as f64 * 100.0,
318 stats.blksw_blocks,
319 share(stats.d15), share(stats.d25), share(stats.d45), share(stats.reuse),
320 );
321 if ours < 0.99 || oracle < 0.99 {
322 failures.push(format!("{layout} {rate}: ours {ours:.4} oracle {oracle:.4}"));
323 }
324 assert!(stats.bits_used * 10 > stats.bits_budget * 9, "{layout} {rate}: rate loop left bits unused: {stats:?}");
325 let expect_layout = match channels { 1 => "mono", 2 => "stereo", _ => "5.1" };
326 assert_eq!(probe_field(&probe, "channels").as_deref(), Some(channels.to_string().as_str()), "{probe}");
327 assert!(probe_field(&probe, "channel_layout").is_some_and(|l| l.starts_with(expect_layout)), "{probe}");
328 assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some(rate.to_string().as_str()), "{probe}");
329 assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some((bitrate_kbps * 1000).to_string().as_str()), "{probe}");
330 }
331 }
332 assert!(failures.is_empty(), "corr < 0.99:\n{}", failures.join("\n"));
333}
334
335/// A train of sharp attacks (decaying 2 kHz bursts, 25 per second) over a
336/// quiet noise floor: every attack is a block switch, and the stream still
337/// round-trips through both decoders.
338#[test]
339fn click_train_switches_blocks_and_still_round_trips() {
340 let channels = 2;
341 let mut pcm = noise(48_000 * channels, &mut 11u64);
342 for v in &mut pcm {
343 *v *= 0.01;
344 }
345 for n in (500..48_000).step_by(1900) {
346 for i in 0..200 {
347 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();
348 for ch in 0..channels {
349 pcm[(n + i) * channels + ch] += v;
350 }
351 }
352 }
353 let config = EncoderConfig { sample_rate: 48_000, channels: 2, bitrate_kbps: 192 };
354 let (data, stats) = encode_with_stats(config, &pcm);
355 assert!(stats.blksw_blocks >= 20, "{stats:?}");
356 let corr = worst_corr(&pcm, &decode_all(&data, channels), channels);
357 eprintln!("click train: ours {corr:.4}, {stats:?}");
358 assert!(corr >= 0.95, "click train corr {corr}");
359 if have_ffmpeg() {
360 let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3");
361 std::fs::write(&out, &data).unwrap();
362 let corr = worst_corr(&pcm, &oracle_decode(&out), channels);
363 let _ = std::fs::remove_file(&out);
364 eprintln!("click train: oracle {corr:.4}");
365 assert!(corr >= 0.95, "click train oracle corr {corr}");
366 }
367}
368
369#[test]
370fn tone_at_32khz_round_trips() {
371 let rate = 32_000;
372 let pcm: Vec<f32> = (0..rate as usize * 2)
373 .flat_map(|n| {
374 let t = n as f32 / rate as f32;
375 let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
376 [v, 0.5 * v]
377 })
378 .collect();
379 let config = EncoderConfig { sample_rate: rate, channels: 2, bitrate_kbps: 96 };
380 let data = encode(config, &pcm);
381 let corr = worst_corr(&pcm, &decode_all(&data, 2), 2);
382 assert!(corr >= 0.99, "32 kHz ours corr {corr}");
383 if have_ffmpeg() {
384 let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3");
385 std::fs::write(&out, &data).unwrap();
386 let corr = worst_corr(&pcm, &oracle_decode(&out), 2);
387 let probe = ffprobe(&out, "sample_rate,bit_rate");
388 let _ = std::fs::remove_file(&out);
389 assert!(corr >= 0.99, "32 kHz oracle corr {corr}");
390 assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}");
391 assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}");
392 }
393}
394
395/// 200 random (rate, channels, bit rate) configurations, two frames of
396/// noise each: nothing panics and our decoder takes every frame.
397#[test]
398fn random_configs_never_panic_and_always_decode() {
399 let (mut seed, mut noise_seed) = (99u64, 7u64);
400 let mut next = |n: u64| {
401 seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
402 (seed >> 33) % n
403 };
404 for _ in 0..200 {
405 let sample_rate = ec_ac3::tables::SAMPLE_RATE[next(3) as usize];
406 let channels = next(6) as u16 + 1;
407 let bitrate_kbps = ec_ac3::tables::BIT_RATE_KBPS[next(ec_ac3::tables::BIT_RATE_KBPS.len() as u64) as usize];
408 let config = EncoderConfig { sample_rate, channels, bitrate_kbps };
409 let pcm = noise(1536 * 2 * channels as usize, &mut noise_seed);
410 let data = encode(config, &pcm);
411 let decoded = decode_all(&data, channels as usize);
412 assert!(decoded.len() >= pcm.len() + 256, "{config:?}: {} of {} samples", decoded.len(), pcm.len());
413 }
414}
415
416