forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli4 days ago4021 commits

ps_oracle.rs146 lines, 5.8 KiBHistoryRawDownload
1//! Parametric Stereo (HE-AACv2) against FFmpeg's native AAC decoder.
2//!
3//! Each fixture is a 2-second HE-AACv2 stereo ADTS stream (generated by
4//! `scripts/aac-tables/make-ps-fixtures.sh`). The reference is FFmpeg's own
5//! decode of the same file. The acceptance bar is a per-channel correlation of
6//! at least 0.999 after a bounded lag search, which absorbs decoder priming
7//! delay, as `sbr_real_library.rs` does for HE-AAC v1.
8
9use crate::shared::have_ffmpeg;
10use crate::common::fixture;
11use crate::common::deinterleave;
12use crate::common::correlation;
13use ec_aac::AacDecoder;
14use std::path::Path;
15use std::process::Command;
16
17/// Per-channel correlation the reconstruction must reach against FFmpeg.
18const MIN_CORR: f64 = 0.999;
19/// Fixtures whose PS reconstruction is known to differ from FFmpeg, with the
20/// correlation floor the current code is held to. Empty: every PS fixture
21/// matches FFmpeg at `MIN_CORR` or better. An entry here needs a one-line reason
22/// and a measured floor; remove it once the fixture passes at `MIN_CORR`.
23const KNOWN_INEXACT: &[&str] = &[];
24const KNOWN_INEXACT_FLOOR: f64 = 0.69;
25/// Lag search bound, in samples. A winning lag at this bound is not a measurement.
26const LAG_MAX: i64 = 4096;
27/// Window (in samples) the coarse lag search correlates over.
28const WINDOW: usize = 16_384;
29/// Where the coarse window starts, past the decoder's start-up transient.
30const WINDOW_START: usize = 32_768;
31
32/// (fixture, sample rate it decodes to)
33const FIXTURES: &[(&str, u32)] = &[
34 ("ps_44100_sine.aac", 44_100),
35 ("ps_44100_music.aac", 44_100),
36 ("ps_48000_sine.aac", 48_000),
37 ("ps_48000_music.aac", 48_000),
38];
39
40/// FFmpeg's decode of `path` as planar stereo `f32`.
41fn ffmpeg_reference(path: &Path) -> Vec<Vec<f32>> {
42 let out = Command::new("ffmpeg")
43 .args(["-v", "error", "-i"])
44 .arg(path)
45 .args(["-ac", "2", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
46 .output()
47 .expect("ffmpeg runs");
48 assert!(
49 out.status.success(),
50 "ffmpeg decode failed: {}",
51 String::from_utf8_lossy(&out.stderr)
52 );
53 deinterleave(
54 &out.stdout
55 .chunks(4)
56 .filter(|c| c.len() == 4)
57 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
58 .collect::<Vec<f32>>(),
59 2,
60 )
61}
62
63/// The overlap of `ours` and `theirs` at `lag`: `ours[i]` pairs with `theirs[i + lag]`.
64fn aligned<'a>(ours: &'a [f32], theirs: &'a [f32], lag: i64) -> (&'a [f32], &'a [f32]) {
65 let (a0, b0) = if lag >= 0 {
66 (0usize, lag as usize)
67 } else {
68 ((-lag) as usize, 0usize)
69 };
70 let n = ours.len().saturating_sub(a0).min(theirs.len().saturating_sub(b0));
71 (&ours[a0..a0 + n], &theirs[b0..b0 + n])
72}
73
74/// The lag that best aligns `ours` with `theirs`, and the full-overlap
75/// correlation at that lag. A winning lag on the search bound is refused: the
76/// true alignment may lie outside the search, so the number would be noise.
77fn best_lag(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
78 let mut best = (0i64, 0.0f64);
79 for lag in -LAG_MAX..=LAG_MAX {
80 let (a, b) = aligned(ours, theirs, lag);
81 if a.len() < WINDOW_START + WINDOW {
82 continue;
83 }
84 let c = correlation(&a[WINDOW_START..WINDOW_START + WINDOW], &b[WINDOW_START..WINDOW_START + WINDOW]);
85 if c.abs() > best.1.abs() {
86 best = (lag, c);
87 }
88 }
89 assert!(
90 best.0.abs() < LAG_MAX,
91 "winning lag {} sits at the search bound -- the alignment is outside the search",
92 best.0
93 );
94 let (a, b) = aligned(ours, theirs, best.0);
95 (best.0, correlation(a, b))
96}
97
98#[test]
99fn ps_fixtures_decode_to_stereo_matching_ffmpeg() {
100 let require = std::env::var_os("EC_REQUIRE_FIXTURES").is_some();
101 if !have_ffmpeg() {
102 assert!(!require, "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed");
103 eprintln!("SKIP: ffmpeg not installed");
104 return;
105 }
106 let mut failures = Vec::new();
107 for &(name, rate) in FIXTURES {
108 let path = fixture(name);
109 assert!(
110 path.exists() || !require,
111 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent",
112 path.display()
113 );
114 if !path.exists() {
115 eprintln!("SKIP: fixture {} absent", path.display());
116 continue;
117 }
118 let bytes = std::fs::read(&path).expect("fixture reads");
119 let audio = AacDecoder::new()
120 .decode(&bytes, None)
121 .unwrap_or_else(|e| panic!("{name}: decode failed: {e:?}"));
122 assert_eq!(audio.channels, 2, "{name}: PS must decode to two channels");
123 assert_eq!(audio.sample_rate, rate, "{name}: PS must decode at the extension rate");
124 let ours = deinterleave(&audio.samples, 2);
125 let theirs = ffmpeg_reference(&path);
126 for ch in 0..2 {
127 // The primary check is the full overlap at zero lag: both decoders
128 // emit the same frame count and the same start, so no delay is
129 // expected. The bounded search is reported as a diagnostic only, since
130 // on a pure tone it returns aliases of the period.
131 let (a, b) = aligned(&ours[ch], &theirs[ch], 0);
132 let corr = correlation(a, b);
133 let (lag, search_corr) = best_lag(&ours[ch], &theirs[ch]);
134 println!(
135 "{name} ch{ch}: ours {} frames, ffmpeg {} frames, corr@0 {corr:.6}, search lag {lag} corr {search_corr:.6}",
136 ours[ch].len(),
137 theirs[ch].len()
138 );
139 let floor = if KNOWN_INEXACT.contains(&name) { KNOWN_INEXACT_FLOOR } else { MIN_CORR };
140 if corr < floor {
141 failures.push(format!("{name} ch{ch}: corr@0 {corr:.6} < {floor}"));
142 }
143 }
144 }
145 assert!(failures.is_empty(), "PS does not match ffmpeg:\n{}", failures.join("\n"));
146}