forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

oracle.rs1247 lines, 47.6 KiBHistoryRawDownload
1//! Decoder and encoder against ffmpeg, on the generated fixtures and on the
2//! real library. Every test that needs a fixture or ffmpeg skips loudly when it
3//! is absent rather than passing quietly.
4
5mod common;
6
7use common::{fixtures, have_ffmpeg};
8use std::path::{Path, PathBuf};
9use std::process::Command;
10
11use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig};
12
13/// Fixture-presence probe for the committed `fixtures/audio` media this file
14/// decodes. Returns whether the fixture is present, but never silently: under
15/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
16/// and the script that regenerates it, so a host whose fixture library drifted
17/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
18/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
19/// short-circuited because the probe ran first in a compound `if`).
20///
21/// Order is load-bearing: probe, assert, return. Never merge the probe into
22/// the same `if` as the escape.
23fn require_fixture(path: &Path, generator: &str) -> bool {
24 let present = path.exists();
25 assert!(
26 present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
27 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
28 path.display(),
29 generator
30 );
31 if !present {
32 eprintln!("SKIP: fixture {} absent", path.display());
33 }
34 present
35}
36
37/// ffmpeg's decode of a file, as planar-by-channel `f32`.
38fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
39 let out = Command::new("ffmpeg")
40 .args(["-v", "error", "-i"])
41 .arg(path)
42 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
43 .output()
44 .expect("ffmpeg runs");
45 assert!(
46 out.status.success(),
47 "ffmpeg decode failed: {}",
48 String::from_utf8_lossy(&out.stderr)
49 );
50 deinterleave(&bytes_to_f32(&out.stdout), channels)
51}
52
53fn bytes_to_f32(bytes: &[u8]) -> Vec<f32> {
54 bytes
55 .as_chunks::<4>().0.iter()
56 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
57 .collect()
58}
59
60fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
61 let mut out = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
62 for (i, &v) in samples.iter().enumerate() {
63 out[i % channels].push(v);
64 }
65 out
66}
67
68/// Our decode of an ADTS file, as planar-by-channel `f32`.
69fn our_decode(path: &Path) -> (Vec<Vec<f32>>, u32) {
70 let (planes, rate, _) = our_decode_with_pns(path);
71 (planes, rate)
72}
73
74fn our_decode_with_pns(path: &Path) -> (Vec<Vec<f32>>, u32, usize) {
75 let data = std::fs::read(path).expect("fixture readable");
76 let mut decoder = AacDecoder::new();
77 let mut planes: Vec<Vec<f32>> = Vec::new();
78 let mut rate = 0;
79 let mut at = 0usize;
80 while at + 7 <= data.len() {
81 let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
82 let end = (at + header.frame_length).min(data.len());
83 let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
84 rate = frame.sample_rate;
85 let ch = usize::from(frame.channels);
86 if planes.is_empty() {
87 planes = vec![Vec::new(); ch];
88 }
89 for (i, v) in frame.samples.iter().enumerate() {
90 planes[i % ch].push(*v);
91 }
92 at = end;
93 }
94 (planes, rate, decoder.pns_aus())
95}
96
97/// Pearson correlation over the overlap of two channels.
98fn correlation(a: &[f32], b: &[f32]) -> f64 {
99 let n = a.len().min(b.len());
100 assert!(n > 1024, "not enough overlap to compare: {n} samples");
101 let (a, b) = (&a[..n], &b[..n]);
102 let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
103 let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
104 let mut num = 0.0;
105 let mut da = 0.0;
106 let mut db = 0.0;
107 for i in 0..n {
108 let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
109 num += x * y;
110 da += x * x;
111 db += y * y;
112 }
113 if da == 0.0 || db == 0.0 {
114 return if da == db { 1.0 } else { 0.0 };
115 }
116 num / (da * db).sqrt()
117}
118
119fn compare(path: &Path) -> Vec<f64> {
120 let (ours, _rate) = our_decode(path);
121 assert!(!ours.is_empty(), "no channels decoded from {path:?}");
122 let theirs = ffmpeg_decode(path, ours.len());
123 ours.iter()
124 .zip(&theirs)
125 .map(|(a, b)| correlation(a, b))
126 .collect()
127}
128
129#[test]
130fn adts_fixtures_match_ffmpeg_per_channel() {
131 if !have_ffmpeg() {
132 eprintln!("SKIP: ffmpeg not on PATH");
133 return;
134 }
135 let dir = fixtures().join("audio");
136 let mut checked = 0;
137 for name in [
138 "aac-adts-mono-44100.aac",
139 "aac-adts-mono-48000.aac",
140 "aac-adts-stereo-44100.aac",
141 "aac-adts-stereo-48000.aac",
142 "aac-adts-5.1-44100.aac",
143 "aac-adts-5.1-48000.aac",
144 ] {
145 let path = dir.join(name);
146 if !require_fixture(&path, "scripts/gen-fixtures.sh") {
147 continue;
148 }
149 let corr = compare(&path);
150 println!("{name}: {corr:?}");
151 for (ch, c) in corr.iter().enumerate() {
152 assert!(
153 *c >= 0.999,
154 "{name} channel {ch} correlation {c:.6} < 0.999"
155 );
156 }
157 checked += 1;
158 }
159 assert!(
160 checked > 0,
161 "no AAC fixtures found: run scripts/gen-fixtures.sh"
162 );
163}
164
165#[test]
166fn mp4_fixtures_match_ffmpeg_per_channel() {
167 if !have_ffmpeg() {
168 eprintln!("SKIP: ffmpeg not on PATH");
169 return;
170 }
171 let dir = fixtures().join("audio");
172 let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle");
173 std::fs::create_dir_all(&tmp).expect("temp dir");
174 let mut checked = 0;
175 for name in [
176 "aac-mp4-mono-48000.mp4",
177 "aac-mp4-stereo-48000.mp4",
178 "aac-mp4-5.1-48000.mp4",
179 ] {
180 let path = dir.join(name);
181 if !require_fixture(&path, "scripts/gen-fixtures.sh") {
182 continue;
183 }
184 // The mp4 side of the family is another slice; the elementary stream
185 // comes out with a stream copy so this test stays about AAC.
186 let adts = tmp.join(format!("{name}.aac"));
187 let out = Command::new("ffmpeg")
188 .args(["-v", "error", "-y", "-i"])
189 .arg(&path)
190 .args(["-c:a", "copy", "-f", "adts"])
191 .arg(&adts)
192 .output()
193 .expect("ffmpeg runs");
194 assert!(out.status.success(), "remux failed for {name}");
195 let corr = compare(&adts);
196 println!("{name}: {corr:?}");
197 for (ch, c) in corr.iter().enumerate() {
198 assert!(
199 *c >= 0.999,
200 "{name} channel {ch} correlation {c:.6} < 0.999"
201 );
202 }
203 checked += 1;
204 }
205 assert!(checked > 0, "no AAC-in-mp4 fixtures found");
206}
207
208/// One fixture per §4.6 coding tool ffmpeg's native encoder can force in
209/// isolation (plus one with all four together), pinning the PNS/M-S ordering
210/// bug found against real OBS screen recordings (repo ledger): PNS must fill
211/// its bands before M/S and intensity stereo combine them.
212#[test]
213fn aac_coding_tools_match_ffmpeg_in_isolation() {
214 if !have_ffmpeg() {
215 eprintln!("SKIP: ffmpeg not on PATH");
216 return;
217 }
218 let dir = fixtures().join("audio");
219 let tmp = std::env::temp_dir().join("ec-aac-tools-oracle");
220 std::fs::create_dir_all(&tmp).expect("temp dir");
221 let mut checked = 0;
222 for tool in ["pns", "is", "ms", "tns", "all"] {
223 let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a");
224 let path = dir.join(&name);
225 if !require_fixture(&path, "scripts/gen-fixtures.sh") {
226 continue;
227 }
228 let adts = tmp.join(format!("{name}.aac"));
229 let out = Command::new("ffmpeg")
230 .args(["-v", "error", "-y", "-i"])
231 .arg(&path)
232 .args(["-c:a", "copy", "-f", "adts"])
233 .arg(&adts)
234 .output()
235 .expect("ffmpeg runs");
236 assert!(out.status.success(), "remux failed for {name}");
237 let corr = compare(&adts);
238 let pns = our_decode_with_pns(&adts).2;
239 assert_eq!(
240 pns > 0,
241 matches!(tool, "pns" | "all"),
242 "{name}: pns_aus={pns}"
243 );
244 println!("{name}: {corr:?}");
245 for (ch, c) in corr.iter().enumerate() {
246 assert!(
247 *c >= 0.999,
248 "{name} channel {ch} correlation {c:.6} < 0.999"
249 );
250 }
251 checked += 1;
252 }
253 assert!(checked > 0, "no AAC tool-isolation fixtures found");
254}
255
256/// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR.
257/// Each channel carries its own tone, mapped explicitly onto the layout, so a
258/// wrong element order shows up as the wrong tone on the wrong channel.
259#[test]
260fn five_one_comes_out_in_film_order() {
261 if !have_ffmpeg() {
262 eprintln!("SKIP: ffmpeg not on PATH");
263 return;
264 }
265 let tmp = std::env::temp_dir().join("ec-aac-order");
266 std::fs::create_dir_all(&tmp).expect("temp dir");
267 let src = tmp.join("order.aac");
268 // The LFE tone stays low: the reference encoder band-limits that channel,
269 // and a 1.5 kHz tone would simply not survive the trip.
270 let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0];
271 let mut cmd = Command::new("ffmpeg");
272 cmd.args(["-v", "error", "-y"]);
273 for f in tones {
274 cmd.args([
275 "-f",
276 "lavfi",
277 "-i",
278 &format!("sine=frequency={f}:duration=2:sample_rate=48000"),
279 ]);
280 }
281 let out = cmd
282 .args([
283 "-filter_complex",
284 "[0:a][1:a][2:a][3:a][4:a][5:a]join=inputs=6:channel_layout=5.1:\
285map=0.0-FL|1.0-FR|2.0-FC|3.0-LFE|4.0-BL|5.0-BR[a]",
286 "-map",
287 "[a]",
288 "-c:a",
289 "aac",
290 "-b:a",
291 "320k",
292 "-f",
293 "adts",
294 ])
295 .arg(&src)
296 .output()
297 .expect("ffmpeg runs");
298 assert!(
299 out.status.success(),
300 "tone build failed: {}",
301 String::from_utf8_lossy(&out.stderr)
302 );
303 let (ours, rate) = our_decode(&src);
304 assert_eq!(ours.len(), 6, "5.1 decodes to six channels");
305 for (ch, plane) in ours.iter().enumerate() {
306 let peak = dominant_frequency(plane, rate);
307 let want = tones[ch];
308 assert!(
309 (peak - want).abs() < 40.0,
310 "channel {ch} peaks at {peak:.0} Hz, expected {want:.0} Hz: \
311 the element order was not remapped to FL, FR, FC, LFE, BL, BR"
312 );
313 }
314}
315
316/// Crude DFT peak: enough to tell six well-separated tones apart.
317fn dominant_frequency(samples: &[f32], rate: u32) -> f64 {
318 let n = samples.len().min(16384);
319 let start = samples.len() / 3;
320 let seg = &samples[start..start + n.min(samples.len() - start)];
321 let mut best = (0.0f64, 0.0f64);
322 let mut f = 40.0;
323 while f < 4000.0 {
324 let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
325 let (mut re, mut im) = (0.0, 0.0);
326 for (i, &v) in seg.iter().enumerate() {
327 re += f64::from(v) * (w * i as f64).cos();
328 im += f64::from(v) * (w * i as f64).sin();
329 }
330 let mag = re * re + im * im;
331 if mag > best.1 {
332 best = (f, mag);
333 }
334 f += 5.0;
335 }
336 best.0
337}
338
339#[test]
340fn asc_round_trips_every_sample_rate() {
341 for (index, rate) in ec_aac::SAMPLE_RATES.iter().enumerate() {
342 assert_eq!(ec_aac::sf_index_for_rate(*rate), Some(index as u8));
343 assert_eq!(ec_aac::sample_rate_for_index(index as u8), *rate);
344 for channels in [1u16, 2, 6, 8] {
345 let bytes = ec_aac::audio_specific_config_bytes(*rate, channels);
346 let cfg = ec_aac::parse_audio_specific_config(&bytes).expect("asc parses");
347 assert_eq!(cfg.sample_rate, *rate, "rate round trip at {rate} Hz");
348 assert_eq!(cfg.channels, channels, "channels round trip at {rate} Hz");
349 assert_eq!(cfg.object_type, ec_aac::AOT_AAC_LC);
350 }
351 }
352 assert_eq!(ec_aac::sf_index_for_rate(37_000), None);
353}
354
355/// A refusal is a claim: this pins the current contract -- SBR and HE-AACv2
356/// (SBR with Parametric Stereo) are reconstructed and report the extension
357/// rate; plain AAC-LC reports nothing missing.
358#[test]
359fn sbr_is_reported_not_silently_upsampled() {
360 // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz),
361 // then AOT 2 for the core: 00101 0110 0010 0011 00010.
362 let asc = [0x2Bu8, 0x11, 0x88];
363 let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses");
364 assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::V1);
365 assert_eq!(
366 decoder.output_sample_rate(),
367 Some(48_000),
368 "a reconstructed HE-AAC stream must report the extension rate it now actually produces"
369 );
370
371 // Same layout, AOT 29 (PS) instead of 5 (SBR): 11101 0110 0010 0011 00010.
372 // Parametric Stereo is reconstructed now, so this reports the extension
373 // rate (the decoder also outputs two channels for it).
374 let ps_asc = [0xEBu8, 0x11, 0x88];
375 let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses");
376 assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::V1);
377 assert_eq!(
378 ps_decoder.output_sample_rate(),
379 Some(48_000),
380 "a reconstructed HE-AACv2 stream must report the extension rate it produces"
381 );
382
383 let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2))
384 .expect("LC config parses");
385 assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled);
386}
387
388/// The incumbent encoder's per-channel correlation on these exact fixtures,
389/// measured by running the incumbent AAC encoder, 0.5.0, as a black box through the same
390/// ffmpeg decode (2026-08-14). This is the bar the replacement has to clear.
391const INCUMBENT_BAR: &[(&str, usize, u32, f64)] = &[
392 ("mono", 1, 96, 0.9846),
393 ("stereo", 2, 128, 0.9743),
394 ("stereo", 2, 192, 0.9864),
395 ("5.1", 6, 384, 0.9648),
396 ("5.1", 6, 448, 0.9611),
397];
398
399fn encode_to_adts(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec<u8> {
400 let mut enc = AacEncoder::new(AacEncoderConfig {
401 bitrate_bps: kbps * 1000,
402 adts: true,
403 ..Default::default()
404 });
405 enc.push_pcm(pcm, channels, rate).expect("pcm accepted");
406 enc.finish();
407 let mut out = Vec::new();
408 while let Ok(p) = enc.next_packet() {
409 out.extend_from_slice(&p.data);
410 }
411 out
412}
413
414/// Correlation at the encoder's own delay, which is one frame of lookahead.
415fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 {
416 [0usize, ec_aac::FRAME_LEN, 2 * ec_aac::FRAME_LEN]
417 .into_iter()
418 .filter(|lag| decoded.len() > *lag + 1024)
419 .map(|lag| correlation(source, &decoded[lag..]))
420 .fold(f64::MIN, f64::max)
421}
422
423/// Our encode, through ffmpeg, against the incumbent's own numbers on the same
424/// lossless fixtures at the same bitrates.
425#[test]
426fn encoder_beats_the_incumbent_bar() {
427 if !have_ffmpeg() {
428 eprintln!("SKIP: ffmpeg not on PATH");
429 return;
430 }
431 let dir = fixtures().join("audio");
432 let tmp = std::env::temp_dir().join("ec-aac-bar");
433 std::fs::create_dir_all(&tmp).expect("temp dir");
434 let mut checked = 0;
435 for (name, channels, kbps, bar) in INCUMBENT_BAR {
436 let src = dir.join(format!("flac-{name}-48000.flac"));
437 if !require_fixture(&src, "scripts/gen-fixtures.sh") {
438 continue;
439 }
440 let source = ffmpeg_decode(&src, *channels);
441 let mut interleaved = Vec::with_capacity(source[0].len() * channels);
442 for i in 0..source[0].len() {
443 for plane in &source {
444 interleaved.push(plane[i]);
445 }
446 }
447 let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps);
448 let path = tmp.join(format!("{name}-{kbps}k.aac"));
449 std::fs::write(&path, &adts).expect("write");
450 let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
451 let ours = ffmpeg_decode(&path, *channels);
452 let corr: Vec<f64> = source
453 .iter()
454 .zip(&ours)
455 .map(|(a, b)| best_correlation(a, b))
456 .collect();
457 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
458 println!(
459 "enc {name} {kbps}k: {rate:.0} kbps actual, worst channel {worst:.4} \
460 (incumbent {bar:.4}) per-channel {corr:?}"
461 );
462 assert!(
463 rate <= f64::from(*kbps) * 1.12,
464 "{name} {kbps}k overshot its target: {rate:.0} kbps"
465 );
466 assert!(
467 worst >= *bar,
468 "{name} {kbps}k worst channel {worst:.4} is under the incumbent's {bar:.4}"
469 );
470 checked += 1;
471 }
472 assert!(checked > 0, "no lossless fixtures found");
473}
474
475/// Every channel count the encoder claims (1 to 6 and 8), at 64 kbps per channel, the
476/// scaling the stereo row uses (128 kbps for 2 channels). Each row is
477/// (layout, channels, kbps, bar, which incumbent the bar is). rusty_aac 0.5.0 (the
478/// INCUMBENT_BAR incumbent above) refuses 7+ channels, so the 8-channel bar is ffmpeg's
479/// native AAC encoder on the same fixture at the same bitrate, a stricter proxy.
480/// Measured 2026-10-18 by running each incumbent through the same decode and
481/// best-lag correlation (`~/.cache/aacencbar-inc`, not in the repo).
482const LAYOUT_BAR: &[(&str, usize, u32, f64, &str)] = &[
483 ("mono", 1, 64, 0.9698, "rusty_aac 0.5.0"),
484 ("stereo", 2, 128, 0.9743, "rusty_aac 0.5.0"),
485 ("3.0", 3, 192, 0.9711, "rusty_aac 0.5.0"),
486 ("4.0", 4, 256, 0.9645, "rusty_aac 0.5.0"),
487 ("5.0", 5, 320, 0.9712, "rusty_aac 0.5.0"),
488 ("5.1", 6, 384, 0.9648, "rusty_aac 0.5.0"),
489 ("7.1", 8, 512, 0.9994, "ffmpeg native aac"),
490];
491
492/// Every LAYOUT_BAR row: worst-channel correlation against its incumbent's bar, and the
493/// ADTS rate within 5% of the target.
494#[test]
495fn encoder_meets_every_layout_bar() {
496 if !have_ffmpeg() {
497 eprintln!("SKIP: ffmpeg not on PATH");
498 return;
499 }
500 let dir = fixtures().join("audio");
501 let tmp = std::env::temp_dir().join("ec-aac-layout-bar");
502 std::fs::create_dir_all(&tmp).expect("temp dir");
503 let mut checked = 0;
504 let mut failed = Vec::new();
505 for (name, channels, kbps, bar, incumbent) in LAYOUT_BAR {
506 let src = dir.join(format!("flac-{name}-48000.flac"));
507 if !require_fixture(&src, "scripts/gen-aac-layouts.sh OUTDIR (3.0, 4.0, 5.0, 7.1)") {
508 continue;
509 }
510 let source = ffmpeg_decode(&src, *channels);
511 let mut interleaved = Vec::with_capacity(source[0].len() * channels);
512 for i in 0..source[0].len() {
513 for plane in &source {
514 interleaved.push(plane[i]);
515 }
516 }
517 let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps);
518 let path = tmp.join(format!("{name}-{kbps}k.aac"));
519 std::fs::write(&path, &adts).expect("write");
520 let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
521 let ours = ffmpeg_decode(&path, *channels);
522 let corr: Vec<f64> = source
523 .iter()
524 .zip(&ours)
525 .map(|(a, b)| best_correlation(a, b))
526 .collect();
527 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
528 println!(
529 "layout {name} {kbps}k: {rate:.1} kbps ({:+.1}%), worst channel {worst:.4} \
530 (bar {bar:.4}, {incumbent}) per-channel {corr:.4?}",
531 (rate / f64::from(*kbps) - 1.0) * 100.0
532 );
533 if (rate / f64::from(*kbps) - 1.0).abs() > 0.05 {
534 failed.push(format!("{name} {kbps}k: rate {rate:.1} kbps outside +-5%"));
535 }
536 if worst < *bar {
537 failed.push(format!(
538 "{name} {kbps}k: worst channel {worst:.4} under the bar {bar:.4} ({incumbent})"
539 ));
540 }
541 checked += 1;
542 }
543 assert!(checked > 0, "no lossless fixtures found");
544 assert!(failed.is_empty(), "layout bars missed:\n{}", failed.join("\n"));
545}
546
547/// Noise-bearing synthetic content for NOISY_BAR. Each clip is 10 s, 48 kHz, stereo, built
548/// here by ffmpeg's lavfi sources, so no media is committed. Each entry is
549/// (name, lavfi inputs, filter_complex ending in [o]).
550const NOISY_CLIPS: &[(&str, &[&str], &str)] = &[
551 (
552 // (a) the bench content: two slow-AM tone pairs plus independent pink noise at 0.03.
553 "bench",
554 &[
555 "aevalsrc='0.25*sin(2*PI*220*t)+0.12*sin(2*PI*277.18*t)*(0.5+0.5*sin(2*PI*2*t))+0.1*sin(2*PI*329.63*t)|0.25*sin(2*PI*222*t)+0.12*sin(2*PI*280*t)*(0.5+0.5*sin(2*PI*2*t))+0.1*sin(2*PI*331*t)':s=48000:d=10",
556 "anoisesrc=d=10:c=pink:a=0.03:s=48000:r=48000:seed=1",
557 "anoisesrc=d=10:c=pink:a=0.03:s=48000:r=48000:seed=2",
558 ],
559 "[1:a][2:a]amerge=inputs=2,aformat=channel_layouts=stereo[n];[0:a][n]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
560 ),
561 (
562 // (b) music-like: four harmonics with 5.5 Hz vibrato per channel, a white burst every
563 // 0.5 s (exponential decay), and a low-level white noise floor.
564 "music",
565 &[
566 "aevalsrc='0.12*sin(2*PI*(196*t+2*sin(2*PI*5.5*t))) + 0.07*sin(2*PI*(392*t+2*sin(2*PI*5.5*t))) + 0.05*sin(2*PI*(588*t+2*sin(2*PI*5.5*t))) + 0.04*sin(2*PI*(784*t+2*sin(2*PI*5.5*t)))|0.12*sin(2*PI*(247*t+2*sin(2*PI*5.3*t+1))) + 0.07*sin(2*PI*(494*t+2*sin(2*PI*5.3*t+1))) + 0.05*sin(2*PI*(741*t+2*sin(2*PI*5.3*t+1))) + 0.04*sin(2*PI*(988*t+2*sin(2*PI*5.3*t+1)))':s=48000:d=10",
567 "anoisesrc=d=10:c=white:a=0.5:s=48000:r=48000:seed=3",
568 "anoisesrc=d=10:c=white:a=0.004:s=48000:r=48000:seed=5",
569 "anoisesrc=d=10:c=white:a=0.004:s=48000:r=48000:seed=6",
570 ],
571 "[1:a]aeval='val(0)*exp(-30*mod(t,0.5))|val(0)*exp(-30*mod(t,0.5))':c=stereo[b];[2:a][3:a]amerge=inputs=2,aformat=channel_layouts=stereo[f];[0:a][b]amix=inputs=2:normalize=0[t1];[t1][f]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
572 ),
573 (
574 // (c) speech-like: white noise bursts through two formant band pairs, gated at 4 Hz,
575 // plus 120 Hz and 118 Hz decaying pitch pulses.
576 "speech",
577 &[
578 "anoisesrc=d=10:c=white:a=0.3:s=48000:r=48000:seed=7",
579 "anoisesrc=d=10:c=white:a=0.3:s=48000:r=48000:seed=8",
580 "aevalsrc='exp(-600*mod(t,1/120))*sin(2*PI*120*t)*0.5|exp(-600*mod(t,1/118))*sin(2*PI*118*t)*0.5':s=48000:d=10",
581 ],
582 "[0:a]bandpass=f=700:width_type=h:w=150,bandpass=f=1200:width_type=h:w=200[a1];[1:a]bandpass=f=1200:width_type=h:w=200,bandpass=f=2600:width_type=h:w=300[a2];[a1][a2]amerge=inputs=2[nz];[nz]aeval='val(0)*(0.5+0.5*sin(2*PI*4*t))|val(1)*(0.5+0.5*sin(2*PI*4*t))'[nzg];[2:a]aeval='val(0)*0.3|val(1)*0.3'[p];[nzg][p]amix=inputs=2:normalize=0,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
583 ),
584 (
585 // (d) independent white noise per channel at about -20 dBFS RMS (measured -19.97).
586 "white",
587 &[
588 "anoisesrc=d=10:c=white:a=0.1738:s=48000:r=48000:seed=9",
589 "anoisesrc=d=10:c=white:a=0.1738:s=48000:r=48000:seed=10",
590 ],
591 "[0:a][1:a]amerge=inputs=2,aformat=sample_fmts=s16:channel_layouts=stereo[o]",
592 ),
593];
594
595/// Incumbent (ffmpeg's native AAC encoder, `-c:a aac -b:a <kbps>k`, 2026-10-18) per-channel
596/// correlation on each NOISY_CLIPS entry, at the best lag in {0, 1024, 2048}, minimum over
597/// the two channels. The bar is the incumbent minus 0.002, rounded down to four decimals.
598/// Only 128k and 192k are gated (the 96k rows are measured and reported only).
599/// (clip, kbps, incumbent, bar, gated)
600const NOISY_BAR: &[(&str, u32, f64, f64, bool)] = &[
601 ("bench", 96, 0.999344, 0.9973, false),
602 ("bench", 128, 0.999594, 0.9975, true),
603 ("bench", 192, 0.999618, 0.9976, true),
604 ("music", 96, 0.942434, 0.9404, false),
605 ("music", 128, 0.962250, 0.9602, true),
606 ("music", 192, 0.978655, 0.9766, true),
607 ("speech", 96, 0.991754, 0.9897, false),
608 ("speech", 128, 0.999023, 0.9970, true),
609 ("speech", 192, 0.999609, 0.9976, true),
610 ("white", 96, 0.572339, 0.5703, false),
611 ("white", 128, 0.668895, 0.6668, true),
612 ("white", 192, 0.702850, 0.7008, true),
613];
614
615/// Renders one NOISY_CLIPS entry to a 16-bit WAV in `dir` (cached across rows).
616fn noisy_clip(name: &str, dir: &Path) -> PathBuf {
617 let out = dir.join(format!("noisy-{name}.wav"));
618 if out.exists() {
619 return out;
620 }
621 let (_, inputs, filter) = NOISY_CLIPS
622 .iter()
623 .find(|(n, _, _)| *n == name)
624 .expect("a NOISY_CLIPS entry");
625 let mut cmd = Command::new("ffmpeg");
626 cmd.args(["-v", "error", "-y"]);
627 for input in *inputs {
628 cmd.args(["-f", "lavfi", "-i", input]);
629 }
630 cmd.args(["-filter_complex", filter, "-map", "[o]", "-c:a", "pcm_s16le"])
631 .arg(&out);
632 let run = cmd.output().expect("ffmpeg runs");
633 assert!(
634 run.status.success(),
635 "ffmpeg could not render {name}: {}",
636 String::from_utf8_lossy(&run.stderr)
637 );
638 out
639}
640
641/// Stereo AAC-LC at each NOISY_BAR bitrate on the noise-bearing clips: worst-channel
642/// correlation against the incumbent's bar, and the ADTS rate within 5% of the target.
643#[test]
644fn encoder_meets_noisy_bar() {
645 if !have_ffmpeg() {
646 eprintln!("SKIP: ffmpeg not on PATH");
647 return;
648 }
649 let tmp = std::env::temp_dir().join("ec-aac-noisy-bar");
650 std::fs::create_dir_all(&tmp).expect("temp dir");
651 let mut failed = Vec::new();
652 for (name, kbps, incumbent, bar, gated) in NOISY_BAR {
653 let src = noisy_clip(name, &tmp);
654 let source = ffmpeg_decode(&src, 2);
655 let mut interleaved = Vec::with_capacity(source[0].len() * 2);
656 for i in 0..source[0].len() {
657 for plane in &source {
658 interleaved.push(plane[i]);
659 }
660 }
661 let adts = encode_to_adts(&interleaved, 2, 48_000, *kbps);
662 let path = tmp.join(format!("{name}-{kbps}k.aac"));
663 std::fs::write(&path, &adts).expect("write");
664 let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
665 let ours = ffmpeg_decode(&path, 2);
666 let corr: Vec<f64> = source
667 .iter()
668 .zip(&ours)
669 .map(|(a, b)| best_correlation(a, b))
670 .collect();
671 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
672 println!(
673 "noisy {name} {kbps}k: {rate:.1} kbps ({:+.1}%), worst channel {worst:.4} \
674 (incumbent {incumbent:.4}, bar {bar:.4}, gated {gated}) per-channel {corr:.4?}",
675 (rate / f64::from(*kbps) - 1.0) * 100.0
676 );
677 if !gated {
678 continue;
679 }
680 if (rate / f64::from(*kbps) - 1.0).abs() > 0.05 {
681 failed.push(format!("{name} {kbps}k: rate {rate:.1} kbps outside +-5%"));
682 }
683 if worst < *bar {
684 failed.push(format!(
685 "{name} {kbps}k: worst channel {worst:.4} under the bar {bar:.4}"
686 ));
687 }
688 }
689 assert!(failed.is_empty(), "noisy bars missed:\n{}", failed.join("\n"));
690}
691
692fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> {
693 let frames = (f64::from(rate) * secs) as usize;
694 let mut pcm = Vec::with_capacity(frames * channels);
695 for i in 0..frames {
696 let t = i as f64 / f64::from(rate);
697 for c in 0..channels {
698 let f = 220.0 * (c + 1) as f64;
699 let v = (t * f * std::f64::consts::TAU).sin() * 0.35
700 + (t * f * 2.5 * std::f64::consts::TAU).sin() * 0.15;
701 pcm.push(v as f32);
702 }
703 }
704 pcm
705}
706
707#[test]
708fn encoder_output_decodes_in_ffmpeg_without_warnings() {
709 if !have_ffmpeg() {
710 eprintln!("SKIP: ffmpeg not on PATH");
711 return;
712 }
713 let tmp = std::env::temp_dir().join("ec-aac-enc");
714 std::fs::create_dir_all(&tmp).expect("temp dir");
715 for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] {
716 let rate = 48_000;
717 let pcm = tone_pcm(rate, usize::from(channels), 1.5);
718 let adts = encode_to_adts(&pcm, channels, rate, kbps);
719 assert!(!adts.is_empty(), "{channels}ch encode produced nothing");
720 let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac"));
721 std::fs::write(&path, &adts).expect("write");
722 let out = Command::new("ffmpeg")
723 .args(["-v", "warning", "-i"])
724 .arg(&path)
725 .args(["-f", "null", "-"])
726 .output()
727 .expect("ffmpeg runs");
728 // ffmpeg says this about every ADTS file, its own included: the
729 // container has no duration field. It is not a complaint about us.
730 let log = String::from_utf8_lossy(&out.stderr);
731 let log: String = log
732 .lines()
733 .filter(|l| !l.contains("Estimating duration from bitrate"))
734 .collect::<Vec<_>>()
735 .join("\n");
736 assert!(
737 out.status.success() && log.trim().is_empty(),
738 "ffmpeg complained about our {channels}ch/{kbps}k ADTS:\n{log}"
739 );
740 // And the sound survives the trip.
741 let theirs = ffmpeg_decode(&path, usize::from(channels));
742 let ours = deinterleave(&pcm, usize::from(channels));
743 for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
744 // The encoder's own frame of lookahead delays the output by one
745 // frame; line the two up before comparing.
746 let corr = correlation(a, &b[ec_aac::FRAME_LEN..]);
747 println!("enc {channels}ch {kbps}k channel {ch}: corr {corr:.4}");
748 assert!(
749 corr >= 0.90,
750 "{channels}ch/{kbps}k channel {ch} correlation {corr:.4} < 0.90"
751 );
752 }
753 }
754}
755
756/// The derived tables have to be complete prefix codes, and that is checkable
757/// without any oracle: a Kraft sum of exactly 1 with the entry count the
758/// standard prescribes leaves no room for a transcription slip.
759#[test]
760fn every_codebook_is_a_complete_prefix_code() {
761 let expected = [81usize, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289];
762 for (i, cb) in ec_aac::tables::CODEBOOKS.iter().enumerate() {
763 assert_eq!(
764 cb.codes.len(),
765 expected[i],
766 "codebook {} entry count",
767 i + 1
768 );
769 let kraft: f64 = cb
770 .codes
771 .iter()
772 .map(|(l, _)| 2f64.powi(-i32::from(*l)))
773 .sum();
774 assert!(
775 (kraft - 1.0).abs() < 1e-12,
776 "codebook {} Kraft sum {kraft}",
777 i + 1
778 );
779 assert_prefix_free(cb.codes, &format!("codebook {}", i + 1));
780 }
781 let sf = ec_aac::tables::SCALEFACTOR_CODES;
782 assert_eq!(sf.len(), 121, "scalefactor codebook entry count");
783 let kraft: f64 = sf.iter().map(|(l, _)| 2f64.powi(-i32::from(*l))).sum();
784 assert!((kraft - 1.0).abs() < 1e-12, "scalefactor Kraft sum {kraft}");
785 assert_prefix_free(sf, "scalefactor codebook");
786}
787
788fn assert_prefix_free(codes: &[(u8, u32)], what: &str) {
789 for (i, &(li, ci)) in codes.iter().enumerate() {
790 for &(lj, cj) in codes.iter().skip(i + 1) {
791 let short = li.min(lj);
792 if (ci >> (li - short)) == (cj >> (lj - short)) {
793 panic!("{what}: {ci:b}/{li} and {cj:b}/{lj} share a prefix");
794 }
795 }
796 }
797}
798
799/// Band tables must be monotone and land exactly on the window length.
800#[test]
801fn band_tables_span_the_window() {
802 for (i, swb) in ec_aac::tables::SWB_LONG.iter().enumerate() {
803 assert_eq!(swb[0], 0, "long index {i}");
804 assert_eq!(*swb.last().unwrap(), 1024, "long index {i}");
805 assert!(swb.windows(2).all(|w| w[0] < w[1]), "long index {i}");
806 }
807 for (i, swb) in ec_aac::tables::SWB_SHORT.iter().enumerate() {
808 assert_eq!(swb[0], 0, "short index {i}");
809 assert_eq!(*swb.last().unwrap(), 128, "short index {i}");
810 assert!(swb.windows(2).all(|w| w[0] < w[1]), "short index {i}");
811 }
812}
813
814/// The AudioSpecificConfig this crate writes is byte-identical to the one the
815/// reference muxer puts in an `esds`, which is what "ffmpeg accepts our ASC"
816/// means in practice.
817#[test]
818fn asc_matches_the_one_ffmpeg_writes() {
819 if !have_ffmpeg() {
820 eprintln!("SKIP: ffmpeg not on PATH");
821 return;
822 }
823 let tmp = std::env::temp_dir().join("ec-aac-esds");
824 std::fs::create_dir_all(&tmp).expect("temp dir");
825 for (channels, rate) in [(1u16, 48_000u32), (2, 48_000), (2, 44_100), (6, 48_000)] {
826 let pcm = tone_pcm(rate, usize::from(channels), 0.4);
827 let adts = encode_to_adts(&pcm, channels, rate, 128);
828 let src = tmp.join(format!("asc-{channels}-{rate}.aac"));
829 std::fs::write(&src, &adts).expect("write");
830 let mp4 = tmp.join(format!("asc-{channels}-{rate}.mp4"));
831 let out = Command::new("ffmpeg")
832 .args(["-v", "error", "-y", "-i"])
833 .arg(&src)
834 .args(["-c:a", "copy"])
835 .arg(&mp4)
836 .output()
837 .expect("ffmpeg runs");
838 assert!(
839 out.status.success(),
840 "remux of our ADTS failed: {}",
841 String::from_utf8_lossy(&out.stderr)
842 );
843 let theirs = esds_asc(&std::fs::read(&mp4).expect("read mp4"))
844 .expect("the muxer wrote a DecoderSpecificInfo");
845 let ours = ec_aac::audio_specific_config_bytes(rate, channels);
846 assert_eq!(
847 ours, theirs,
848 "{channels}ch/{rate}Hz ASC differs from the reference muxer's"
849 );
850 // And it parses back to the parameters it went in with.
851 let cfg = ec_aac::parse_audio_specific_config(&ours).expect("asc parses");
852 assert_eq!((cfg.sample_rate, cfg.channels), (rate, channels));
853 }
854}
855
856/// The DecoderSpecificInfo payload of the first `esds` box: tag 0x05 inside the
857/// DecoderConfigDescriptor, with the usual 7-bit length encoding.
858fn esds_asc(mp4: &[u8]) -> Option<Vec<u8>> {
859 // Walks the MPEG-4 descriptor tree (tag, BER length, payload) rather than
860 // scanning raw bytes for 0x05: a scalar field elsewhere in the tree
861 // (e.g. avgBitrate) can legitimately contain that byte value, which a
862 // blind byte scan would mistake for the DecSpecificInfoTag.
863 let at = mp4.windows(4).position(|w| w == b"esds")?;
864 let mut i = at + 4 + 4; // "esds" tag, then the box's version+flags
865 while i < mp4.len() {
866 let tag = mp4[i];
867 i += 1;
868 let mut len = 0usize;
869 loop {
870 let b = *mp4.get(i)?;
871 i += 1;
872 len = (len << 7) | usize::from(b & 0x7F);
873 if b & 0x80 == 0 {
874 break;
875 }
876 }
877 match tag {
878 0x05 => return mp4.get(i..i + len).map(<[u8]>::to_vec),
879 // ES_DescrTag: ES_ID(2) + flags(1), then optional fields the
880 // flags select, before its nested descriptors.
881 0x03 => {
882 let flags = *mp4.get(i + 2)?;
883 i += 3;
884 if flags & 0x80 != 0 {
885 i += 2; // dependsOn ES_ID
886 }
887 if flags & 0x40 != 0 {
888 let url_len = usize::from(*mp4.get(i)?);
889 i += 1 + url_len;
890 }
891 if flags & 0x20 != 0 {
892 i += 2; // OCR ES_ID
893 }
894 }
895 // DecoderConfigDescrTag: objectType(1) + streamType/flags(1) +
896 // bufferSizeDB(3) + maxBitrate(4) + avgBitrate(4), then its
897 // nested DecSpecificInfo.
898 0x04 => i += 13,
899 // An opaque leaf descriptor: its whole payload is `len` bytes.
900 _ => i += len,
901 }
902 }
903 None
904}
905
906/// AAC tracks from the machine's own library, not just generated fixtures: the
907/// elementary stream is copied out to ADTS and decoded both ways.
908// lane-h264reallib: same shape as the ec-h264 `real_library_streams_match_ffmpeg`
909// fix, same reason. The manifest is generated by `scripts/scan-real-library.sh`
910// from `~/Videos ~/Downloads ~/Music` and is gitignored because it is
911// machine-local. The guard below makes a host with NO manifest print green
912// (nothing was checked), and a host that ran the scan but has since moved or
913// deleted files falls through to `checked >= 3` and goes red for a reason that
914// has nothing to do with the decoder. An ignore is visible in `--list` and
915// cannot go green silently, which an env gate would.
916// Run on the workstation: cargo test -p ec-aac --test oracle real_library_tracks_match_ffmpeg -- --ignored
917#[ignore = "sweeps the PERSONAL media library (~/Videos, ~/Downloads, ~/Music) through the gitignored fixtures/real-library-manifest.tsv and asserts >= 3 tracks swept; a runner host has no such library, so it is either a silent green or a red for the wrong reason. Run it on the workstation with --ignored."]
918#[test]
919fn real_library_tracks_match_ffmpeg() {
920 if !have_ffmpeg() {
921 eprintln!("SKIP: ffmpeg not on PATH");
922 return;
923 }
924 let manifest = fixtures().join("real-library-manifest.tsv");
925 let Ok(text) = std::fs::read_to_string(&manifest) else {
926 eprintln!("SKIP: no real-library manifest; run scripts/scan-real-library.sh");
927 return;
928 };
929 let tmp = std::env::temp_dir().join("ec-aac-real");
930 std::fs::create_dir_all(&tmp).expect("temp dir");
931 let mut stereo = 0;
932 let mut wide = 0;
933 let mut checked = 0;
934 for line in text.lines().skip(1) {
935 if stereo >= 3 && wide >= 2 {
936 break;
937 }
938 let path = line.split('\t').next().unwrap_or_default();
939 if path.is_empty() || !line.to_lowercase().contains("aac") {
940 continue;
941 }
942 let file = Path::new(path);
943 if !file.exists() {
944 continue;
945 }
946 let Some((index, channels, profile)) = aac_stream(file) else {
947 continue;
948 };
949 // HE-AAC is reported, not decoded: see `sbr_is_reported_not_silently_upsampled`.
950 if profile.contains("HE-AAC") {
951 continue;
952 }
953 if channels <= 2 {
954 if stereo >= 3 {
955 continue;
956 }
957 stereo += 1;
958 } else {
959 if wide >= 2 {
960 continue;
961 }
962 wide += 1;
963 }
964 let adts = tmp.join(format!("real-{checked}.aac"));
965 let out = Command::new("ffmpeg")
966 .args(["-v", "error", "-y", "-t", "20", "-i"])
967 .arg(file)
968 .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
969 .arg(&adts)
970 .output()
971 .expect("ffmpeg runs");
972 if !out.status.success() {
973 eprintln!("SKIP {path}: stream copy failed");
974 continue;
975 }
976 let corr = compare(&adts);
977 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
978 println!(
979 "real {channels}ch {profile} worst {worst:.6} -- {}",
980 file.file_name().unwrap_or_default().to_string_lossy()
981 );
982 for (ch, c) in corr.iter().enumerate() {
983 assert!(
984 *c >= 0.999,
985 "channel {ch} correlation {c:.6} < 0.999 for {path}"
986 );
987 }
988 checked += 1;
989 }
990 assert!(
991 checked >= 3,
992 "wanted at least three library tracks, swept {checked}"
993 );
994 assert!(wide >= 1, "no multichannel AAC track was swept");
995}
996
997/// The first AAC audio stream of a file: `(stream index, channels, profile)`.
998fn aac_stream(path: &Path) -> Option<(usize, usize, String)> {
999 let out = Command::new("ffprobe")
1000 .args([
1001 "-v",
1002 "error",
1003 "-select_streams",
1004 "a",
1005 "-show_entries",
1006 "stream=index,codec_name,channels,profile",
1007 "-of",
1008 "default=noprint_wrappers=1",
1009 ])
1010 .arg(path)
1011 .output()
1012 .ok()?;
1013 let text = String::from_utf8_lossy(&out.stdout);
1014 let (mut index, mut channels, mut codec, mut profile) =
1015 (None, None, String::new(), String::new());
1016 for line in text.lines() {
1017 let (key, value) = line.split_once('=')?;
1018 match key {
1019 "index" => {
1020 if codec == "aac" {
1021 return Some((index?, channels?, profile));
1022 }
1023 index = value.parse().ok();
1024 codec.clear();
1025 profile.clear();
1026 }
1027 "codec_name" => codec = value.to_string(),
1028 "channels" => channels = value.parse().ok(),
1029 "profile" => profile = value.to_string(),
1030 _ => {}
1031 }
1032 }
1033 if codec == "aac" {
1034 return Some((index?, channels?, profile));
1035 }
1036 None
1037}
1038
1039/// Decode speed on 5.1, the shape a film soundtrack has.
1040#[test]
1041fn five_one_decodes_faster_than_realtime() {
1042 let path = fixtures().join("audio/aac-adts-5.1-48000.aac");
1043 if !require_fixture(&path, "scripts/gen-fixtures.sh") {
1044 return;
1045 }
1046 let data = std::fs::read(&path).expect("fixture readable");
1047 let rounds = 8;
1048 let start = std::time::Instant::now();
1049 let mut frames = 0usize;
1050 let mut rate = 48_000u32;
1051 for _ in 0..rounds {
1052 let mut decoder = AacDecoder::new();
1053 let mut at = 0usize;
1054 frames = 0;
1055 while at + 7 <= data.len() {
1056 let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
1057 let end = (at + header.frame_length).min(data.len());
1058 let block = decoder.decode(&data[at..end], None).expect("decodes");
1059 rate = block.sample_rate;
1060 frames += block.frames();
1061 at = end;
1062 }
1063 }
1064 let audio = (frames * rounds) as f64 / f64::from(rate);
1065 let factor = audio / start.elapsed().as_secs_f64();
1066 println!(
1067 "5.1 decode: {factor:.0}x realtime ({} build)",
1068 if cfg!(debug_assertions) {
1069 "debug"
1070 } else {
1071 "release"
1072 }
1073 );
1074 if !cfg!(debug_assertions) {
1075 assert!(
1076 factor >= 40.0,
1077 "5.1 decode {factor:.0}x realtime is under 40x"
1078 );
1079 }
1080}
1081
1082/// The one HE-AAC track in this machine's library, decoded to its AAC-LC core.
1083/// The claim under test is the honest one: the core comes out, at the core
1084/// rate, matching what a reference decoder makes of the same core band.
1085#[test]
1086fn he_aac_library_track_decodes_to_its_core() {
1087 if !have_ffmpeg() {
1088 eprintln!("SKIP: ffmpeg not on PATH");
1089 return;
1090 }
1091 let manifest = fixtures().join("real-library-manifest.tsv");
1092 let Ok(text) = std::fs::read_to_string(&manifest) else {
1093 eprintln!("SKIP: no real-library manifest");
1094 return;
1095 };
1096 let tmp = std::env::temp_dir().join("ec-aac-he");
1097 std::fs::create_dir_all(&tmp).expect("temp dir");
1098 for line in text.lines().skip(1) {
1099 let path = line.split('\t').next().unwrap_or_default();
1100 let file = Path::new(path);
1101 if path.is_empty() || !file.exists() {
1102 continue;
1103 }
1104 let Some((index, _, profile)) = aac_stream_matching(file, "HE-AAC") else {
1105 continue;
1106 };
1107 let _ = profile;
1108 let adts = tmp.join("he.aac");
1109 let out = Command::new("ffmpeg")
1110 .args(["-v", "error", "-y", "-t", "10", "-i"])
1111 .arg(file)
1112 .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
1113 .arg(&adts)
1114 .output()
1115 .expect("ffmpeg runs");
1116 if !out.status.success() {
1117 continue;
1118 }
1119 let (ours, rate) = our_decode(&adts);
1120 assert!(!ours.is_empty(), "the HE-AAC core decoded to nothing");
1121 // The reference decode carries SBR, so it runs at twice this rate;
1122 // resampling it down to the core rate low-passes exactly the band the
1123 // core carries, which is the part we are claiming to reproduce.
1124 let core = tmp.join("he-core.f32");
1125 let out = Command::new("ffmpeg")
1126 .args(["-v", "error", "-y", "-i"])
1127 .arg(&adts)
1128 .args(["-ar", &rate.to_string(), "-f", "f32le"])
1129 .arg(&core)
1130 .output()
1131 .expect("ffmpeg runs");
1132 assert!(
1133 out.status.success(),
1134 "reference decode of the HE-AAC track failed"
1135 );
1136 let theirs = deinterleave(
1137 &bytes_to_f32(&std::fs::read(&core).expect("read")),
1138 ours.len(),
1139 );
1140 // Sample-by-sample comparison would need the reference resampler's own
1141 // delay; the claim here is about *content*, so it is checked on the
1142 // long-term band energies, which no delay moves.
1143 let corr: Vec<f64> = ours
1144 .iter()
1145 .zip(&theirs)
1146 .map(|(a, b)| pearson(&band_energies(a, rate), &band_energies(b, rate)))
1147 .collect();
1148 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
1149 println!("HE-AAC core at {rate} Hz: band-energy match, worst channel {worst:.4} {corr:?}");
1150 assert!(
1151 worst >= 0.95,
1152 "the AAC-LC core of an HE-AAC track should carry the reference's \
1153 core band; worst channel {worst:.4}"
1154 );
1155 return;
1156 }
1157 eprintln!("SKIP: no HE-AAC track in the library manifest");
1158}
1159
1160/// Pearson correlation with no minimum length: for short feature vectors.
1161fn pearson(a: &[f32], b: &[f32]) -> f64 {
1162 let n = a.len().min(b.len());
1163 let ma = a[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1164 let mb = b[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1165 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1166 for i in 0..n {
1167 let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
1168 num += x * y;
1169 da += x * x;
1170 db += y * y;
1171 }
1172 if da == 0.0 || db == 0.0 {
1173 return 1.0;
1174 }
1175 num / (da * db).sqrt()
1176}
1177
1178/// Long-term energy in 32 logarithmic bands: a spectral fingerprint that a
1179/// resampler's delay cannot shift.
1180fn band_energies(samples: &[f32], rate: u32) -> Vec<f32> {
1181 let bands = 32usize;
1182 let mut out = vec![0.0f64; bands];
1183 let n = 1024usize;
1184 let mut blocks = 0usize;
1185 for chunk in samples.chunks_exact(n).take(400) {
1186 blocks += 1;
1187 for (b, slot) in out.iter_mut().enumerate() {
1188 // Geometric spacing from 100 Hz to the Nyquist limit.
1189 let lo = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf(b as f64 / bands as f64);
1190 let hi = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf((b + 1) as f64 / bands as f64);
1191 let (mut re, mut im) = (0.0f64, 0.0f64);
1192 let f = (lo * hi).sqrt();
1193 let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
1194 for (i, &v) in chunk.iter().enumerate() {
1195 re += f64::from(v) * (w * i as f64).cos();
1196 im += f64::from(v) * (w * i as f64).sin();
1197 }
1198 *slot += (re * re + im * im).sqrt();
1199 }
1200 }
1201 out.iter()
1202 .map(|v| ((v / blocks.max(1) as f64) + 1e-9).ln() as f32)
1203 .collect()
1204}
1205
1206fn aac_stream_matching(path: &Path, want: &str) -> Option<(usize, usize, String)> {
1207 let out = Command::new("ffprobe")
1208 .args([
1209 "-v",
1210 "error",
1211 "-select_streams",
1212 "a",
1213 "-show_entries",
1214 "stream=index,codec_name,channels,profile",
1215 "-of",
1216 "default=noprint_wrappers=1",
1217 ])
1218 .arg(path)
1219 .output()
1220 .ok()?;
1221 let text = String::from_utf8_lossy(&out.stdout);
1222 let mut index = None;
1223 let mut channels = None;
1224 let mut codec = String::new();
1225 let mut profile = String::new();
1226 for line in text.lines() {
1227 let (key, value) = line.split_once('=')?;
1228 match key {
1229 "index" => {
1230 if codec == "aac" && profile.contains(want) {
1231 return Some((index?, channels?, profile));
1232 }
1233 index = value.parse().ok();
1234 codec.clear();
1235 profile.clear();
1236 }
1237 "codec_name" => codec = value.to_string(),
1238 "channels" => channels = value.parse().ok(),
1239 "profile" => profile = value.to_string(),
1240 _ => {}
1241 }
1242 }
1243 if codec == "aac" && profile.contains(want) {
1244 return Some((index?, channels?, profile));
1245 }
1246 None
1247}