forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.2 MiBa69dfabTahinli5 hours ago4073 commits

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