forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

oracle.rs1009 lines, 35.7 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
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig};
9
10fn fixtures() -> PathBuf {
11 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
12}
13
14fn have_ffmpeg() -> bool {
15 Command::new("ffmpeg")
16 .arg("-version")
17 .output()
18 .map(|o| o.status.success())
19 .unwrap_or(false)
20}
21
22/// ffmpeg's decode of a file, as planar-by-channel `f32`.
23fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
24 let out = Command::new("ffmpeg")
25 .args(["-v", "error", "-i"])
26 .arg(path)
27 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
28 .output()
29 .expect("ffmpeg runs");
30 assert!(
31 out.status.success(),
32 "ffmpeg decode failed: {}",
33 String::from_utf8_lossy(&out.stderr)
34 );
35 deinterleave(&bytes_to_f32(&out.stdout), channels)
36}
37
38fn bytes_to_f32(bytes: &[u8]) -> Vec<f32> {
39 bytes
40 .chunks_exact(4)
41 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
42 .collect()
43}
44
45fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
46 let mut out = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
47 for (i, &v) in samples.iter().enumerate() {
48 out[i % channels].push(v);
49 }
50 out
51}
52
53/// Our decode of an ADTS file, as planar-by-channel `f32`.
54fn our_decode(path: &Path) -> (Vec<Vec<f32>>, u32) {
55 let (planes, rate, _) = our_decode_with_pns(path);
56 (planes, rate)
57}
58
59fn our_decode_with_pns(path: &Path) -> (Vec<Vec<f32>>, u32, usize) {
60 let data = std::fs::read(path).expect("fixture readable");
61 let mut decoder = AacDecoder::new();
62 let mut planes: Vec<Vec<f32>> = Vec::new();
63 let mut rate = 0;
64 let mut at = 0usize;
65 while at + 7 <= data.len() {
66 let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
67 let end = (at + header.frame_length).min(data.len());
68 let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
69 rate = frame.sample_rate;
70 let ch = usize::from(frame.channels);
71 if planes.is_empty() {
72 planes = vec![Vec::new(); ch];
73 }
74 for (i, v) in frame.samples.iter().enumerate() {
75 planes[i % ch].push(*v);
76 }
77 at = end;
78 }
79 (planes, rate, decoder.pns_aus())
80}
81
82/// Pearson correlation over the overlap of two channels.
83fn correlation(a: &[f32], b: &[f32]) -> f64 {
84 let n = a.len().min(b.len());
85 assert!(n > 1024, "not enough overlap to compare: {n} samples");
86 let (a, b) = (&a[..n], &b[..n]);
87 let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
88 let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
89 let mut num = 0.0;
90 let mut da = 0.0;
91 let mut db = 0.0;
92 for i in 0..n {
93 let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
94 num += x * y;
95 da += x * x;
96 db += y * y;
97 }
98 if da == 0.0 || db == 0.0 {
99 return if da == db { 1.0 } else { 0.0 };
100 }
101 num / (da * db).sqrt()
102}
103
104fn compare(path: &Path) -> Vec<f64> {
105 let (ours, _rate) = our_decode(path);
106 assert!(!ours.is_empty(), "no channels decoded from {path:?}");
107 let theirs = ffmpeg_decode(path, ours.len());
108 ours.iter()
109 .zip(&theirs)
110 .map(|(a, b)| correlation(a, b))
111 .collect()
112}
113
114#[test]
115fn adts_fixtures_match_ffmpeg_per_channel() {
116 if !have_ffmpeg() {
117 eprintln!("SKIP: ffmpeg not on PATH");
118 return;
119 }
120 let dir = fixtures().join("audio");
121 let mut checked = 0;
122 for name in [
123 "aac-adts-mono-44100.aac",
124 "aac-adts-mono-48000.aac",
125 "aac-adts-stereo-44100.aac",
126 "aac-adts-stereo-48000.aac",
127 "aac-adts-5.1-44100.aac",
128 "aac-adts-5.1-48000.aac",
129 ] {
130 let path = dir.join(name);
131 if !path.exists() {
132 eprintln!("SKIP {name}: fixture missing");
133 continue;
134 }
135 let corr = compare(&path);
136 println!("{name}: {corr:?}");
137 for (ch, c) in corr.iter().enumerate() {
138 assert!(
139 *c >= 0.999,
140 "{name} channel {ch} correlation {c:.6} < 0.999"
141 );
142 }
143 checked += 1;
144 }
145 assert!(
146 checked > 0,
147 "no AAC fixtures found: run scripts/gen-fixtures.sh"
148 );
149}
150
151#[test]
152fn mp4_fixtures_match_ffmpeg_per_channel() {
153 if !have_ffmpeg() {
154 eprintln!("SKIP: ffmpeg not on PATH");
155 return;
156 }
157 let dir = fixtures().join("audio");
158 let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle");
159 std::fs::create_dir_all(&tmp).expect("temp dir");
160 let mut checked = 0;
161 for name in [
162 "aac-mp4-mono-48000.mp4",
163 "aac-mp4-stereo-48000.mp4",
164 "aac-mp4-5.1-48000.mp4",
165 ] {
166 let path = dir.join(name);
167 if !path.exists() {
168 eprintln!("SKIP {name}: fixture missing");
169 continue;
170 }
171 // The mp4 side of the family is another slice; the elementary stream
172 // comes out with a stream copy so this test stays about AAC.
173 let adts = tmp.join(format!("{name}.aac"));
174 let out = Command::new("ffmpeg")
175 .args(["-v", "error", "-y", "-i"])
176 .arg(&path)
177 .args(["-c:a", "copy", "-f", "adts"])
178 .arg(&adts)
179 .output()
180 .expect("ffmpeg runs");
181 assert!(out.status.success(), "remux failed for {name}");
182 let corr = compare(&adts);
183 println!("{name}: {corr:?}");
184 for (ch, c) in corr.iter().enumerate() {
185 assert!(
186 *c >= 0.999,
187 "{name} channel {ch} correlation {c:.6} < 0.999"
188 );
189 }
190 checked += 1;
191 }
192 assert!(checked > 0, "no AAC-in-mp4 fixtures found");
193}
194
195/// One fixture per §4.6 coding tool ffmpeg's native encoder can force in
196/// isolation (plus one with all four together), pinning the PNS/M-S ordering
197/// bug found against real OBS screen recordings (repo ledger): PNS must fill
198/// its bands before M/S and intensity stereo combine them.
199#[test]
200fn aac_coding_tools_match_ffmpeg_in_isolation() {
201 if !have_ffmpeg() {
202 eprintln!("SKIP: ffmpeg not on PATH");
203 return;
204 }
205 let dir = fixtures().join("audio");
206 let tmp = std::env::temp_dir().join("ec-aac-tools-oracle");
207 std::fs::create_dir_all(&tmp).expect("temp dir");
208 let mut checked = 0;
209 for tool in ["pns", "is", "ms", "tns", "all"] {
210 let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a");
211 let path = dir.join(&name);
212 if !path.exists() {
213 eprintln!("SKIP {name}: fixture missing");
214 continue;
215 }
216 let adts = tmp.join(format!("{name}.aac"));
217 let out = Command::new("ffmpeg")
218 .args(["-v", "error", "-y", "-i"])
219 .arg(&path)
220 .args(["-c:a", "copy", "-f", "adts"])
221 .arg(&adts)
222 .output()
223 .expect("ffmpeg runs");
224 assert!(out.status.success(), "remux failed for {name}");
225 let corr = compare(&adts);
226 let pns = our_decode_with_pns(&adts).2;
227 assert_eq!(
228 pns > 0,
229 matches!(tool, "pns" | "all"),
230 "{name}: pns_aus={pns}"
231 );
232 println!("{name}: {corr:?}");
233 for (ch, c) in corr.iter().enumerate() {
234 assert!(
235 *c >= 0.999,
236 "{name} channel {ch} correlation {c:.6} < 0.999"
237 );
238 }
239 checked += 1;
240 }
241 assert!(checked > 0, "no AAC tool-isolation fixtures found");
242}
243
244/// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR.
245/// Each channel carries its own tone, mapped explicitly onto the layout, so a
246/// wrong element order shows up as the wrong tone on the wrong channel.
247#[test]
248fn five_one_comes_out_in_film_order() {
249 if !have_ffmpeg() {
250 eprintln!("SKIP: ffmpeg not on PATH");
251 return;
252 }
253 let tmp = std::env::temp_dir().join("ec-aac-order");
254 std::fs::create_dir_all(&tmp).expect("temp dir");
255 let src = tmp.join("order.aac");
256 // The LFE tone stays low: the reference encoder band-limits that channel,
257 // and a 1.5 kHz tone would simply not survive the trip.
258 let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0];
259 let mut cmd = Command::new("ffmpeg");
260 cmd.args(["-v", "error", "-y"]);
261 for f in tones {
262 cmd.args([
263 "-f",
264 "lavfi",
265 "-i",
266 &format!("sine=frequency={f}:duration=2:sample_rate=48000"),
267 ]);
268 }
269 let out = cmd
270 .args([
271 "-filter_complex",
272 "[0:a][1:a][2:a][3:a][4:a][5:a]join=inputs=6:channel_layout=5.1:\
273map=0.0-FL|1.0-FR|2.0-FC|3.0-LFE|4.0-BL|5.0-BR[a]",
274 "-map",
275 "[a]",
276 "-c:a",
277 "aac",
278 "-b:a",
279 "320k",
280 "-f",
281 "adts",
282 ])
283 .arg(&src)
284 .output()
285 .expect("ffmpeg runs");
286 assert!(
287 out.status.success(),
288 "tone build failed: {}",
289 String::from_utf8_lossy(&out.stderr)
290 );
291 let (ours, rate) = our_decode(&src);
292 assert_eq!(ours.len(), 6, "5.1 decodes to six channels");
293 for (ch, plane) in ours.iter().enumerate() {
294 let peak = dominant_frequency(plane, rate);
295 let want = tones[ch];
296 assert!(
297 (peak - want).abs() < 40.0,
298 "channel {ch} peaks at {peak:.0} Hz, expected {want:.0} Hz: \
299 the element order was not remapped to FL, FR, FC, LFE, BL, BR"
300 );
301 }
302}
303
304/// Crude DFT peak: enough to tell six well-separated tones apart.
305fn dominant_frequency(samples: &[f32], rate: u32) -> f64 {
306 let n = samples.len().min(16384);
307 let start = samples.len() / 3;
308 let seg = &samples[start..start + n.min(samples.len() - start)];
309 let mut best = (0.0f64, 0.0f64);
310 let mut f = 40.0;
311 while f < 4000.0 {
312 let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
313 let (mut re, mut im) = (0.0, 0.0);
314 for (i, &v) in seg.iter().enumerate() {
315 re += f64::from(v) * (w * i as f64).cos();
316 im += f64::from(v) * (w * i as f64).sin();
317 }
318 let mag = re * re + im * im;
319 if mag > best.1 {
320 best = (f, mag);
321 }
322 f += 5.0;
323 }
324 best.0
325}
326
327#[test]
328fn asc_round_trips_every_sample_rate() {
329 for (index, rate) in ec_aac::SAMPLE_RATES.iter().enumerate() {
330 assert_eq!(ec_aac::sf_index_for_rate(*rate), Some(index as u8));
331 assert_eq!(ec_aac::sample_rate_for_index(index as u8), *rate);
332 for channels in [1u16, 2, 6, 8] {
333 let bytes = ec_aac::audio_specific_config_bytes(*rate, channels);
334 let cfg = ec_aac::parse_audio_specific_config(&bytes).expect("asc parses");
335 assert_eq!(cfg.sample_rate, *rate, "rate round trip at {rate} Hz");
336 assert_eq!(cfg.channels, channels, "channels round trip at {rate} Hz");
337 assert_eq!(cfg.object_type, ec_aac::AOT_AAC_LC);
338 }
339 }
340 assert_eq!(ec_aac::sf_index_for_rate(37_000), None);
341}
342
343/// A refusal is a claim: this pins the current contract -- plain SBR (no
344/// Parametric Stereo) is reconstructed and reports the extension rate; a
345/// Parametric Stereo stream still falls back to its core (PS itself is a
346/// separate, unimplemented tool); plain AAC-LC reports nothing missing.
347#[test]
348fn sbr_is_reported_not_silently_upsampled() {
349 // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz),
350 // then AOT 2 for the core: 00101 0110 0010 0011 00010.
351 let asc = [0x2Bu8, 0x11, 0x88];
352 let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses");
353 assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::V1);
354 assert_eq!(
355 decoder.output_sample_rate(),
356 Some(48_000),
357 "a reconstructed HE-AAC stream must report the extension rate it now actually produces"
358 );
359
360 // Same layout, AOT 29 (PS) instead of 5 (SBR): 11101 0110 0010 0011 00010.
361 let ps_asc = [0xEBu8, 0x11, 0x88];
362 let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses");
363 assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly);
364 assert_eq!(
365 ps_decoder.output_sample_rate(),
366 Some(24_000),
367 "PS is still unreconstructed: must report the core rate it actually produces"
368 );
369
370 let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2))
371 .expect("LC config parses");
372 assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled);
373}
374
375/// The incumbent encoder's per-channel correlation on these exact fixtures,
376/// measured by running the incumbent AAC encoder, 0.5.0, as a black box through the same
377/// ffmpeg decode (2026-08-14). This is the bar the replacement has to clear.
378const INCUMBENT_BAR: &[(&str, usize, u32, f64)] = &[
379 ("mono", 1, 96, 0.9846),
380 ("stereo", 2, 128, 0.9743),
381 ("stereo", 2, 192, 0.9864),
382 ("5.1", 6, 384, 0.9648),
383 ("5.1", 6, 448, 0.9611),
384];
385
386fn encode_to_adts(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec<u8> {
387 let mut enc = AacEncoder::new(AacEncoderConfig {
388 bitrate_bps: kbps * 1000,
389 adts: true,
390 ..Default::default()
391 });
392 enc.push_pcm(pcm, channels, rate).expect("pcm accepted");
393 enc.finish();
394 let mut out = Vec::new();
395 while let Ok(p) = enc.next_packet() {
396 out.extend_from_slice(&p.data);
397 }
398 out
399}
400
401/// Correlation at the encoder's own delay, which is one frame of lookahead.
402fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 {
403 [0usize, ec_aac::FRAME_LEN, 2 * ec_aac::FRAME_LEN]
404 .into_iter()
405 .filter(|lag| decoded.len() > *lag + 1024)
406 .map(|lag| correlation(source, &decoded[lag..]))
407 .fold(f64::MIN, f64::max)
408}
409
410/// Our encode, through ffmpeg, against the incumbent's own numbers on the same
411/// lossless fixtures at the same bitrates.
412#[test]
413fn encoder_beats_the_incumbent_bar() {
414 if !have_ffmpeg() {
415 eprintln!("SKIP: ffmpeg not on PATH");
416 return;
417 }
418 let dir = fixtures().join("audio");
419 let tmp = std::env::temp_dir().join("ec-aac-bar");
420 std::fs::create_dir_all(&tmp).expect("temp dir");
421 let mut checked = 0;
422 for (name, channels, kbps, bar) in INCUMBENT_BAR {
423 let src = dir.join(format!("flac-{name}-48000.flac"));
424 if !src.exists() {
425 eprintln!("SKIP {name}: fixture missing");
426 continue;
427 }
428 let source = ffmpeg_decode(&src, *channels);
429 let mut interleaved = Vec::with_capacity(source[0].len() * channels);
430 for i in 0..source[0].len() {
431 for plane in &source {
432 interleaved.push(plane[i]);
433 }
434 }
435 let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps);
436 let path = tmp.join(format!("{name}-{kbps}k.aac"));
437 std::fs::write(&path, &adts).expect("write");
438 let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0;
439 let ours = ffmpeg_decode(&path, *channels);
440 let corr: Vec<f64> = source
441 .iter()
442 .zip(&ours)
443 .map(|(a, b)| best_correlation(a, b))
444 .collect();
445 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
446 println!(
447 "enc {name} {kbps}k: {rate:.0} kbps actual, worst channel {worst:.4} \
448 (incumbent {bar:.4}) per-channel {corr:?}"
449 );
450 assert!(
451 rate <= f64::from(*kbps) * 1.12,
452 "{name} {kbps}k overshot its target: {rate:.0} kbps"
453 );
454 assert!(
455 worst >= *bar,
456 "{name} {kbps}k worst channel {worst:.4} is under the incumbent's {bar:.4}"
457 );
458 checked += 1;
459 }
460 assert!(checked > 0, "no lossless fixtures found");
461}
462
463fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> {
464 let frames = (f64::from(rate) * secs) as usize;
465 let mut pcm = Vec::with_capacity(frames * channels);
466 for i in 0..frames {
467 let t = i as f64 / f64::from(rate);
468 for c in 0..channels {
469 let f = 220.0 * (c + 1) as f64;
470 let v = (t * f * std::f64::consts::TAU).sin() * 0.35
471 + (t * f * 2.5 * std::f64::consts::TAU).sin() * 0.15;
472 pcm.push(v as f32);
473 }
474 }
475 pcm
476}
477
478#[test]
479fn encoder_output_decodes_in_ffmpeg_without_warnings() {
480 if !have_ffmpeg() {
481 eprintln!("SKIP: ffmpeg not on PATH");
482 return;
483 }
484 let tmp = std::env::temp_dir().join("ec-aac-enc");
485 std::fs::create_dir_all(&tmp).expect("temp dir");
486 for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] {
487 let rate = 48_000;
488 let pcm = tone_pcm(rate, usize::from(channels), 1.5);
489 let adts = encode_to_adts(&pcm, channels, rate, kbps);
490 assert!(!adts.is_empty(), "{channels}ch encode produced nothing");
491 let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac"));
492 std::fs::write(&path, &adts).expect("write");
493 let out = Command::new("ffmpeg")
494 .args(["-v", "warning", "-i"])
495 .arg(&path)
496 .args(["-f", "null", "-"])
497 .output()
498 .expect("ffmpeg runs");
499 // ffmpeg says this about every ADTS file, its own included: the
500 // container has no duration field. It is not a complaint about us.
501 let log = String::from_utf8_lossy(&out.stderr);
502 let log: String = log
503 .lines()
504 .filter(|l| !l.contains("Estimating duration from bitrate"))
505 .collect::<Vec<_>>()
506 .join("\n");
507 assert!(
508 out.status.success() && log.trim().is_empty(),
509 "ffmpeg complained about our {channels}ch/{kbps}k ADTS:\n{log}"
510 );
511 // And the sound survives the trip.
512 let theirs = ffmpeg_decode(&path, usize::from(channels));
513 let ours = deinterleave(&pcm, usize::from(channels));
514 for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
515 // The encoder's own frame of lookahead delays the output by one
516 // frame; line the two up before comparing.
517 let corr = correlation(a, &b[ec_aac::FRAME_LEN..]);
518 println!("enc {channels}ch {kbps}k channel {ch}: corr {corr:.4}");
519 assert!(
520 corr >= 0.90,
521 "{channels}ch/{kbps}k channel {ch} correlation {corr:.4} < 0.90"
522 );
523 }
524 }
525}
526
527/// The derived tables have to be complete prefix codes, and that is checkable
528/// without any oracle: a Kraft sum of exactly 1 with the entry count the
529/// standard prescribes leaves no room for a transcription slip.
530#[test]
531fn every_codebook_is_a_complete_prefix_code() {
532 let expected = [81usize, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289];
533 for (i, cb) in ec_aac::tables::CODEBOOKS.iter().enumerate() {
534 assert_eq!(
535 cb.codes.len(),
536 expected[i],
537 "codebook {} entry count",
538 i + 1
539 );
540 let kraft: f64 = cb
541 .codes
542 .iter()
543 .map(|(l, _)| 2f64.powi(-i32::from(*l)))
544 .sum();
545 assert!(
546 (kraft - 1.0).abs() < 1e-12,
547 "codebook {} Kraft sum {kraft}",
548 i + 1
549 );
550 assert_prefix_free(cb.codes, &format!("codebook {}", i + 1));
551 }
552 let sf = ec_aac::tables::SCALEFACTOR_CODES;
553 assert_eq!(sf.len(), 121, "scalefactor codebook entry count");
554 let kraft: f64 = sf.iter().map(|(l, _)| 2f64.powi(-i32::from(*l))).sum();
555 assert!((kraft - 1.0).abs() < 1e-12, "scalefactor Kraft sum {kraft}");
556 assert_prefix_free(sf, "scalefactor codebook");
557}
558
559fn assert_prefix_free(codes: &[(u8, u32)], what: &str) {
560 for (i, &(li, ci)) in codes.iter().enumerate() {
561 for &(lj, cj) in codes.iter().skip(i + 1) {
562 let short = li.min(lj);
563 if (ci >> (li - short)) == (cj >> (lj - short)) {
564 panic!("{what}: {ci:b}/{li} and {cj:b}/{lj} share a prefix");
565 }
566 }
567 }
568}
569
570/// Band tables must be monotone and land exactly on the window length.
571#[test]
572fn band_tables_span_the_window() {
573 for (i, swb) in ec_aac::tables::SWB_LONG.iter().enumerate() {
574 assert_eq!(swb[0], 0, "long index {i}");
575 assert_eq!(*swb.last().unwrap(), 1024, "long index {i}");
576 assert!(swb.windows(2).all(|w| w[0] < w[1]), "long index {i}");
577 }
578 for (i, swb) in ec_aac::tables::SWB_SHORT.iter().enumerate() {
579 assert_eq!(swb[0], 0, "short index {i}");
580 assert_eq!(*swb.last().unwrap(), 128, "short index {i}");
581 assert!(swb.windows(2).all(|w| w[0] < w[1]), "short index {i}");
582 }
583}
584
585/// The AudioSpecificConfig this crate writes is byte-identical to the one the
586/// reference muxer puts in an `esds`, which is what "ffmpeg accepts our ASC"
587/// means in practice.
588#[test]
589fn asc_matches_the_one_ffmpeg_writes() {
590 if !have_ffmpeg() {
591 eprintln!("SKIP: ffmpeg not on PATH");
592 return;
593 }
594 let tmp = std::env::temp_dir().join("ec-aac-esds");
595 std::fs::create_dir_all(&tmp).expect("temp dir");
596 for (channels, rate) in [(1u16, 48_000u32), (2, 48_000), (2, 44_100), (6, 48_000)] {
597 let pcm = tone_pcm(rate, usize::from(channels), 0.4);
598 let adts = encode_to_adts(&pcm, channels, rate, 128);
599 let src = tmp.join(format!("asc-{channels}-{rate}.aac"));
600 std::fs::write(&src, &adts).expect("write");
601 let mp4 = tmp.join(format!("asc-{channels}-{rate}.mp4"));
602 let out = Command::new("ffmpeg")
603 .args(["-v", "error", "-y", "-i"])
604 .arg(&src)
605 .args(["-c:a", "copy"])
606 .arg(&mp4)
607 .output()
608 .expect("ffmpeg runs");
609 assert!(
610 out.status.success(),
611 "remux of our ADTS failed: {}",
612 String::from_utf8_lossy(&out.stderr)
613 );
614 let theirs = esds_asc(&std::fs::read(&mp4).expect("read mp4"))
615 .expect("the muxer wrote a DecoderSpecificInfo");
616 let ours = ec_aac::audio_specific_config_bytes(rate, channels);
617 assert_eq!(
618 ours, theirs,
619 "{channels}ch/{rate}Hz ASC differs from the reference muxer's"
620 );
621 // And it parses back to the parameters it went in with.
622 let cfg = ec_aac::parse_audio_specific_config(&ours).expect("asc parses");
623 assert_eq!((cfg.sample_rate, cfg.channels), (rate, channels));
624 }
625}
626
627/// The DecoderSpecificInfo payload of the first `esds` box: tag 0x05 inside the
628/// DecoderConfigDescriptor, with the usual 7-bit length encoding.
629fn esds_asc(mp4: &[u8]) -> Option<Vec<u8>> {
630 // Walks the MPEG-4 descriptor tree (tag, BER length, payload) rather than
631 // scanning raw bytes for 0x05: a scalar field elsewhere in the tree
632 // (e.g. avgBitrate) can legitimately contain that byte value, which a
633 // blind byte scan would mistake for the DecSpecificInfoTag.
634 let at = mp4.windows(4).position(|w| w == b"esds")?;
635 let mut i = at + 4 + 4; // "esds" tag, then the box's version+flags
636 while i < mp4.len() {
637 let tag = mp4[i];
638 i += 1;
639 let mut len = 0usize;
640 loop {
641 let b = *mp4.get(i)?;
642 i += 1;
643 len = (len << 7) | usize::from(b & 0x7F);
644 if b & 0x80 == 0 {
645 break;
646 }
647 }
648 match tag {
649 0x05 => return mp4.get(i..i + len).map(<[u8]>::to_vec),
650 // ES_DescrTag: ES_ID(2) + flags(1), then optional fields the
651 // flags select, before its nested descriptors.
652 0x03 => {
653 let flags = *mp4.get(i + 2)?;
654 i += 3;
655 if flags & 0x80 != 0 {
656 i += 2; // dependsOn ES_ID
657 }
658 if flags & 0x40 != 0 {
659 let url_len = usize::from(*mp4.get(i)?);
660 i += 1 + url_len;
661 }
662 if flags & 0x20 != 0 {
663 i += 2; // OCR ES_ID
664 }
665 }
666 // DecoderConfigDescrTag: objectType(1) + streamType/flags(1) +
667 // bufferSizeDB(3) + maxBitrate(4) + avgBitrate(4), then its
668 // nested DecSpecificInfo.
669 0x04 => i += 13,
670 // An opaque leaf descriptor: its whole payload is `len` bytes.
671 _ => i += len,
672 }
673 }
674 None
675}
676
677/// AAC tracks from the machine's own library, not just generated fixtures: the
678/// elementary stream is copied out to ADTS and decoded both ways.
679#[test]
680fn real_library_tracks_match_ffmpeg() {
681 if !have_ffmpeg() {
682 eprintln!("SKIP: ffmpeg not on PATH");
683 return;
684 }
685 let manifest = fixtures().join("real-library-manifest.tsv");
686 let Ok(text) = std::fs::read_to_string(&manifest) else {
687 eprintln!("SKIP: no real-library manifest; run scripts/scan-real-library.sh");
688 return;
689 };
690 let tmp = std::env::temp_dir().join("ec-aac-real");
691 std::fs::create_dir_all(&tmp).expect("temp dir");
692 let mut stereo = 0;
693 let mut wide = 0;
694 let mut checked = 0;
695 for line in text.lines().skip(1) {
696 if stereo >= 3 && wide >= 2 {
697 break;
698 }
699 let path = line.split('\t').next().unwrap_or_default();
700 if path.is_empty() || !line.to_lowercase().contains("aac") {
701 continue;
702 }
703 let file = Path::new(path);
704 if !file.exists() {
705 continue;
706 }
707 let Some((index, channels, profile)) = aac_stream(file) else {
708 continue;
709 };
710 // HE-AAC is reported, not decoded: see `sbr_is_reported_not_silently_upsampled`.
711 if profile.contains("HE-AAC") {
712 continue;
713 }
714 if channels <= 2 {
715 if stereo >= 3 {
716 continue;
717 }
718 stereo += 1;
719 } else {
720 if wide >= 2 {
721 continue;
722 }
723 wide += 1;
724 }
725 let adts = tmp.join(format!("real-{checked}.aac"));
726 let out = Command::new("ffmpeg")
727 .args(["-v", "error", "-y", "-t", "20", "-i"])
728 .arg(file)
729 .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
730 .arg(&adts)
731 .output()
732 .expect("ffmpeg runs");
733 if !out.status.success() {
734 eprintln!("SKIP {path}: stream copy failed");
735 continue;
736 }
737 let corr = compare(&adts);
738 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
739 println!(
740 "real {channels}ch {profile} worst {worst:.6} -- {}",
741 file.file_name().unwrap_or_default().to_string_lossy()
742 );
743 for (ch, c) in corr.iter().enumerate() {
744 assert!(
745 *c >= 0.999,
746 "channel {ch} correlation {c:.6} < 0.999 for {path}"
747 );
748 }
749 checked += 1;
750 }
751 assert!(
752 checked >= 3,
753 "wanted at least three library tracks, swept {checked}"
754 );
755 assert!(wide >= 1, "no multichannel AAC track was swept");
756}
757
758/// The first AAC audio stream of a file: `(stream index, channels, profile)`.
759fn aac_stream(path: &Path) -> Option<(usize, usize, String)> {
760 let out = Command::new("ffprobe")
761 .args([
762 "-v",
763 "error",
764 "-select_streams",
765 "a",
766 "-show_entries",
767 "stream=index,codec_name,channels,profile",
768 "-of",
769 "default=noprint_wrappers=1",
770 ])
771 .arg(path)
772 .output()
773 .ok()?;
774 let text = String::from_utf8_lossy(&out.stdout);
775 let (mut index, mut channels, mut codec, mut profile) =
776 (None, None, String::new(), String::new());
777 for line in text.lines() {
778 let (key, value) = line.split_once('=')?;
779 match key {
780 "index" => {
781 if codec == "aac" {
782 return Some((index?, channels?, profile));
783 }
784 index = value.parse().ok();
785 codec.clear();
786 profile.clear();
787 }
788 "codec_name" => codec = value.to_string(),
789 "channels" => channels = value.parse().ok(),
790 "profile" => profile = value.to_string(),
791 _ => {}
792 }
793 }
794 if codec == "aac" {
795 return Some((index?, channels?, profile));
796 }
797 None
798}
799
800/// Decode speed on 5.1, the shape a film soundtrack has.
801#[test]
802fn five_one_decodes_faster_than_realtime() {
803 let path = fixtures().join("audio/aac-adts-5.1-48000.aac");
804 if !path.exists() {
805 eprintln!("SKIP: 5.1 fixture missing");
806 return;
807 }
808 let data = std::fs::read(&path).expect("fixture readable");
809 let rounds = 8;
810 let start = std::time::Instant::now();
811 let mut frames = 0usize;
812 let mut rate = 48_000u32;
813 for _ in 0..rounds {
814 let mut decoder = AacDecoder::new();
815 let mut at = 0usize;
816 frames = 0;
817 while at + 7 <= data.len() {
818 let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
819 let end = (at + header.frame_length).min(data.len());
820 let block = decoder.decode(&data[at..end], None).expect("decodes");
821 rate = block.sample_rate;
822 frames += block.frames();
823 at = end;
824 }
825 }
826 let audio = (frames * rounds) as f64 / f64::from(rate);
827 let factor = audio / start.elapsed().as_secs_f64();
828 println!(
829 "5.1 decode: {factor:.0}x realtime ({} build)",
830 if cfg!(debug_assertions) {
831 "debug"
832 } else {
833 "release"
834 }
835 );
836 if !cfg!(debug_assertions) {
837 assert!(
838 factor >= 40.0,
839 "5.1 decode {factor:.0}x realtime is under 40x"
840 );
841 }
842}
843
844/// The one HE-AAC track in this machine's library, decoded to its AAC-LC core.
845/// The claim under test is the honest one: the core comes out, at the core
846/// rate, matching what a reference decoder makes of the same core band.
847#[test]
848fn he_aac_library_track_decodes_to_its_core() {
849 if !have_ffmpeg() {
850 eprintln!("SKIP: ffmpeg not on PATH");
851 return;
852 }
853 let manifest = fixtures().join("real-library-manifest.tsv");
854 let Ok(text) = std::fs::read_to_string(&manifest) else {
855 eprintln!("SKIP: no real-library manifest");
856 return;
857 };
858 let tmp = std::env::temp_dir().join("ec-aac-he");
859 std::fs::create_dir_all(&tmp).expect("temp dir");
860 for line in text.lines().skip(1) {
861 let path = line.split('\t').next().unwrap_or_default();
862 let file = Path::new(path);
863 if path.is_empty() || !file.exists() {
864 continue;
865 }
866 let Some((index, _, profile)) = aac_stream_matching(file, "HE-AAC") else {
867 continue;
868 };
869 let _ = profile;
870 let adts = tmp.join("he.aac");
871 let out = Command::new("ffmpeg")
872 .args(["-v", "error", "-y", "-t", "10", "-i"])
873 .arg(file)
874 .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
875 .arg(&adts)
876 .output()
877 .expect("ffmpeg runs");
878 if !out.status.success() {
879 continue;
880 }
881 let (ours, rate) = our_decode(&adts);
882 assert!(!ours.is_empty(), "the HE-AAC core decoded to nothing");
883 // The reference decode carries SBR, so it runs at twice this rate;
884 // resampling it down to the core rate low-passes exactly the band the
885 // core carries, which is the part we are claiming to reproduce.
886 let core = tmp.join("he-core.f32");
887 let out = Command::new("ffmpeg")
888 .args(["-v", "error", "-y", "-i"])
889 .arg(&adts)
890 .args(["-ar", &rate.to_string(), "-f", "f32le"])
891 .arg(&core)
892 .output()
893 .expect("ffmpeg runs");
894 assert!(
895 out.status.success(),
896 "reference decode of the HE-AAC track failed"
897 );
898 let theirs = deinterleave(
899 &bytes_to_f32(&std::fs::read(&core).expect("read")),
900 ours.len(),
901 );
902 // Sample-by-sample comparison would need the reference resampler's own
903 // delay; the claim here is about *content*, so it is checked on the
904 // long-term band energies, which no delay moves.
905 let corr: Vec<f64> = ours
906 .iter()
907 .zip(&theirs)
908 .map(|(a, b)| pearson(&band_energies(a, rate), &band_energies(b, rate)))
909 .collect();
910 let worst = corr.iter().copied().fold(f64::MAX, f64::min);
911 println!("HE-AAC core at {rate} Hz: band-energy match, worst channel {worst:.4} {corr:?}");
912 assert!(
913 worst >= 0.95,
914 "the AAC-LC core of an HE-AAC track should carry the reference's \
915 core band; worst channel {worst:.4}"
916 );
917 return;
918 }
919 eprintln!("SKIP: no HE-AAC track in the library manifest");
920}
921
922/// Pearson correlation with no minimum length: for short feature vectors.
923fn pearson(a: &[f32], b: &[f32]) -> f64 {
924 let n = a.len().min(b.len());
925 let ma = a[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
926 let mb = b[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
927 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
928 for i in 0..n {
929 let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
930 num += x * y;
931 da += x * x;
932 db += y * y;
933 }
934 if da == 0.0 || db == 0.0 {
935 return 1.0;
936 }
937 num / (da * db).sqrt()
938}
939
940/// Long-term energy in 32 logarithmic bands: a spectral fingerprint that a
941/// resampler's delay cannot shift.
942fn band_energies(samples: &[f32], rate: u32) -> Vec<f32> {
943 let bands = 32usize;
944 let mut out = vec![0.0f64; bands];
945 let n = 1024usize;
946 let mut blocks = 0usize;
947 for chunk in samples.chunks_exact(n).take(400) {
948 blocks += 1;
949 for (b, slot) in out.iter_mut().enumerate() {
950 // Geometric spacing from 100 Hz to the Nyquist limit.
951 let lo = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf(b as f64 / bands as f64);
952 let hi = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf((b + 1) as f64 / bands as f64);
953 let (mut re, mut im) = (0.0f64, 0.0f64);
954 let f = (lo * hi).sqrt();
955 let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
956 for (i, &v) in chunk.iter().enumerate() {
957 re += f64::from(v) * (w * i as f64).cos();
958 im += f64::from(v) * (w * i as f64).sin();
959 }
960 *slot += (re * re + im * im).sqrt();
961 }
962 }
963 out.iter()
964 .map(|v| ((v / blocks.max(1) as f64) + 1e-9).ln() as f32)
965 .collect()
966}
967
968fn aac_stream_matching(path: &Path, want: &str) -> Option<(usize, usize, String)> {
969 let out = Command::new("ffprobe")
970 .args([
971 "-v",
972 "error",
973 "-select_streams",
974 "a",
975 "-show_entries",
976 "stream=index,codec_name,channels,profile",
977 "-of",
978 "default=noprint_wrappers=1",
979 ])
980 .arg(path)
981 .output()
982 .ok()?;
983 let text = String::from_utf8_lossy(&out.stdout);
984 let mut index = None;
985 let mut channels = None;
986 let mut codec = String::new();
987 let mut profile = String::new();
988 for line in text.lines() {
989 let (key, value) = line.split_once('=')?;
990 match key {
991 "index" => {
992 if codec == "aac" && profile.contains(want) {
993 return Some((index?, channels?, profile));
994 }
995 index = value.parse().ok();
996 codec.clear();
997 profile.clear();
998 }
999 "codec_name" => codec = value.to_string(),
1000 "channels" => channels = value.parse().ok(),
1001 "profile" => profile = value.to_string(),
1002 _ => {}
1003 }
1004 }
1005 if codec == "aac" && profile.contains(want) {
1006 return Some((index?, channels?, profile));
1007 }
1008 None
1009}