forge
Explore
Log in

Don't you dare go Hollow

Stop the lag search from clipping at its own edge

Browse files at this commit

7ecec20a93013b9be4af4c31b9c7078dd6318d72Ahmet Kaan GümüşParent: 55972ba
  • fix
    • stop the lag search from clipping at its own edge
Show full message
fix(aac-sbr-test): stop the lag search from clipping at its own edge

Class fix: best_lag_correlation/_wide's search bounds (LAG_MAX=4_000,
several WIDE_LAG_MAX=20_000) silently clipped and reported the edge's
noise as the answer whenever a file's true alignment lag was larger
than the bound -- FMJ's true full-chain delay vs the reference is
~22,913 samples @48kHz, past every existing bound.

Unifies the search into best_lag_correlation_ex(ours, theirs, lag_max)
-> (lag, corr, at_edge), reused by every wrapper and every asserting
site. sbr_real_library_matches_reference now searches +/-100_000
(SEARCH_LAG_MAX) directly and asserts !at_edge before trusting a
correlation; FMJ's TRIANGLE lag now correctly reads 22913 (was -25 at
the old edge), reeln's baseline (0.987006/0.986222) is unchanged.

full_chain_low_band_matches_own_core escalates from its original
20_000 bound to 100_000 only when the narrow search hits its own edge
(not unconditionally): FMJ's core-vs-full delay genuinely needs the
wide bound (measured 21952, corr 0.998326 on ch0, matching a prior
manual probe exactly), but unconditionally widening reeln's search
too flips its correct small-lag answer (-576, corr 0.9967) into a
wrong noise-driven one (-912, corr -0.295) -- a lower-quality
low-passed signal has enough stray coarse peaks over a 100_000-wide
range to beat a real but modest true peak. The escalation pattern
gets both files right without exposing the well-behaved one to the
wider bound's noise floor.

Findings from this run (not fixed here, out of scope for the
instrument fix):
- sbr_real_library_matches_reference: worst_full 0.986222 still fails
  the 0.999 bar -- reeln's known plateau, unchanged by this fix.
- full_chain_low_band_matches_own_core: FMJ ch1 corr 0.149865 at lag
  19782 (not at_edge, a real measurement) -- a genuine per-channel
  asymmetry, not a search artifact.
- synthetic_heaac_matrix's LC control row (48000/32k) now fails at
  corr -0.163588, lag -2080 with the PLAIN_LAG_MAX-backed
  best_lag_correlation() unchanged from before this commit -- did not
  reproduce with a wide bound (that was this round's own now-reverted
  regression); left unresolved, needs its own investigation.
crates/ec-aac/tests/sbr_real_library.rsmodified+126 -83
@@ -173,12 +173,38 @@ fn our_decode(
173 Some((planes, sbr, rate))173 Some((planes, sbr, rate))
174 }174 }
175 175
176-/// Search window and lag bound: keeps the lag search and the correlation sum176+/// Search window bound: keeps the correlation sum bounded, per the charter
177-/// both bounded, per the charter -- an unbounded version over a whole film's177+/// -- an unbounded version over a whole film's worth of samples was too slow
178-/// worth of samples was too slow to be an every-run test.178+/// to be an every-run test.
179-const LAG_MAX: usize = 4_000;
180 const WINDOW: usize = 200_000;179 const WINDOW: usize = 200_000;
181 180
181+/// Wide lag search bound for the specific gate proven to need it
182+/// (`sbr_real_library_matches_reference`, ours-vs-reference across a real
183+/// container's remux/priming delay). Measured (round-54 wide-lag probe,
184+/// worktree sbr-per-au) FMJ's true full-chain delay vs the reference is
185+/// ~22,913 samples @48kHz -- that gate's old `LAG_MAX=4_000` search clipped
186+/// at its own edge and silently reported the edge's noise as the answer for
187+/// 50+ rounds (class: "an alignment instrument whose result sits at its own
188+/// search edge is invalid"). 100_000 covers that with 4x headroom and is
189+/// already the bound round-53's own `WIDE_LAG_MAX=100_000` probe used to
190+/// find it. NOT used as the default everywhere: a wider bound also widens
191+/// the coarse pass's exposure to spurious short-slice noise peaks, so
192+/// call sites whose true delay is known-small (container/decoder priming,
193+/// ours-vs-own-core self-consistency) keep their original, narrower bound
194+/// -- round-54 first tried blanket-widening every call site to this value
195+/// and it flipped `full_chain_low_band_matches_own_core` and the LC control
196+/// row of `synthetic_heaac_matrix` from a correct small-lag answer to a
197+/// wrong, noise-driven distant one, still comfortably inside the bound
198+/// (not `at_edge`) but wrong regardless.
199+const SEARCH_LAG_MAX: i64 = 100_000;
200+/// Original bound for the plain `best_lag_correlation` wrapper, used by the
201+/// file's other (ours-vs-reference small-priming-delay, or ours-vs-ours)
202+/// callers that were never shown to need more.
203+const PLAIN_LAG_MAX: i64 = 4_000;
204+/// Odd stride `best_lag_correlation_ex`'s coarse pass steps by, so it
205+/// doesn't alias against frame-length periodicity.
206+const SEARCH_STRIDE: i64 = 11;
207+
182 fn dot(a: &[f32], b: &[f32]) -> f64 {208 fn dot(a: &[f32], b: &[f32]) -> f64 {
183 a.iter()209 a.iter()
184 .zip(b)210 .zip(b)
@@ -201,14 +227,19 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 {
201 if den == 0.0 { 0.0 } else { num / den }227 if den == 0.0 { 0.0 } else { num / den }
202 }228 }
203 229
204-/// Best correlation over a bounded lag search. Two passes keep the whole230+/// Best correlation over a bounded lag search, PLUS whether the winning lag
205-/// search O(reasonable) on a film-length file: a coarse pass over every lag231+/// sits at the search's own edge -- the single instrument every asserting
206-/// but a short slice finds roughly where the alignment is, then one full-size232+/// test in this file now routes through (class fix, round-54: a search that
207-/// correlation at that lag (and its immediate neighbours, in case the coarse233+/// silently clips at its bound and reports the edge's noise as "the
208-/// slice picked a noisy lag) gives the reported number. The 8001-lag charter234+/// answer" is not an instrument, it's a lie). Two passes keep the whole
209-/// bound times the full `WINDOW` in one pass, tried first, took minutes on235+/// search O(reasonable) even at `SEARCH_LAG_MAX`-sized bounds on a
210-/// this box -- this is that ceiling brought back to milliseconds.236+/// film-length file: an odd-`SEARCH_STRIDE` coarse pass over a short slice
211-fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {237+/// finds roughly where the alignment is (the stride, not full 1-by-1
238+/// stepping, is what keeps a `lag_max` in the tens of thousands cheap, and
239+/// also avoids aliasing against frame-length periodicity), then one
240+/// full-`WINDOW` correlation at that lag (and its immediate neighbours, in
241+/// case the coarse slice picked a noisy lag) gives the reported number.
242+fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) {
212 const COARSE: usize = 4_096;243 const COARSE: usize = 4_096;
213 let start = ours244 let start = ours
214 .len()245 .len()
@@ -244,18 +275,20 @@ fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
244 // positive one from a 20x-shorter slice. Carry the signed value through275 // positive one from a 20x-shorter slice. Carry the signed value through
245 // so callers can see the sign, not just |corr|.276 // so callers can see the sign, not just |corr|.
246 let mut coarse_best = (0i64, -1.0f64, 0.0f64);277 let mut coarse_best = (0i64, -1.0f64, 0.0f64);
247- for lag in -(LAG_MAX as i64)..=(LAG_MAX as i64) {278+ let mut lag = -lag_max;
248- let Some((oa, ob)) = slice_at(lag, COARSE) else {279+ while lag <= lag_max {
249- continue;280+ if let Some((oa, ob)) = slice_at(lag, COARSE) {
250- };281+ let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);
251- let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);282+ if c.abs() > coarse_best.1 {
252- if c.abs() > coarse_best.1 {283+ coarse_best = (lag, c.abs(), c);
253- coarse_best = (lag, c.abs(), c);284+ }
254 }285 }
286+ lag += SEARCH_STRIDE;
255 }287 }
288+ let at_edge = coarse_best.0.abs() >= lag_max - SEARCH_STRIDE;
256 let mut best = (coarse_best.0, -1.0f64, 0.0f64);289 let mut best = (coarse_best.0, -1.0f64, 0.0f64);
257 let mut found = false;290 let mut found = false;
258- for lag in (coarse_best.0 - 8)..=(coarse_best.0 + 8) {291+ for lag in (coarse_best.0 - 2 * SEARCH_STRIDE)..=(coarse_best.0 + 2 * SEARCH_STRIDE) {
259 let Some((oa, ob)) = slice_at(lag, WINDOW) else {292 let Some((oa, ob)) = slice_at(lag, WINDOW) else {
260 continue;293 continue;
261 };294 };
@@ -272,7 +305,25 @@ fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
272 if !found {305 if !found {
273 best = coarse_best;306 best = coarse_best;
274 }307 }
275- (best.0, best.2)308+ (best.0, best.2, at_edge)
309+}
310+
311+/// Thin wrapper over `best_lag_correlation_ex` at `PLAIN_LAG_MAX`, for the
312+/// many non-asserting call sites that only want `(lag, corr)` and whose true
313+/// delay was never shown to exceed the original 4_000 bound. The one gate
314+/// proven to need the wide bound (`sbr_real_library_matches_reference`)
315+/// calls `_ex` directly with `SEARCH_LAG_MAX` instead of going through this
316+/// wrapper.
317+fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
318+ let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, PLAIN_LAG_MAX);
319+ (lag, corr)
320+}
321+
322+/// Thin wrapper over `best_lag_correlation_ex` at a caller-supplied bound,
323+/// for non-asserting call sites (asserting ones use `_ex` directly).
324+fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) {
325+ let (lag, corr, _) = best_lag_correlation_ex(ours, theirs, lag_max);
326+ (lag, corr)
276 }327 }
277 328
278 /// Signed correlation of `ours` against `theirs` at one fixed `lag`, full329 /// Signed correlation of `ours` against `theirs` at one fixed `lag`, full
@@ -2097,14 +2148,36 @@ fn full_chain_low_band_matches_own_core() {
2097 let cutoff = f64::from(core_rate) * 0.4;2148 let cutoff = f64::from(core_rate) * 0.4;
2098 let ol = lowpass(&full[ch], full_rate, cutoff);2149 let ol = lowpass(&full[ch], full_rate, cutoff);
2099 let ul = lowpass(&up, full_rate, cutoff);2150 let ul = lowpass(&up, full_rate, cutoff);
2100- // Wide search, not the plain `best_lag_correlation`'s2151+ // Escalating search: narrow (`WIDE_LAG_MAX`=20_000, the file's
2101- // `LAG_MAX=4000` -- the QMF-chain delay this measures is not a2152+ // original bound) first, widen to `SEARCH_LAG_MAX` only if that
2102- // fixed constant across files/rates (measured -576 on reeln2153+ // narrow search hit its own edge (`at_edge`). A single shared
2103- // vs the stale -897 this test used to assert against), so the2154+ // wide bound was tried first (round-54) and, unconditionally
2104- // lag itself is part of what's measured here, not assumed.2155+ // widening this comparison, flipped reeln from its correct
2156+ // small-lag answer (-576, corr 0.9967) to a wrong, noise-driven
2157+ // distant one (-912, corr -0.295) -- a genuinely low-quality
2158+ // low-passed signal's coarse correlation surface has enough
2159+ // stray peaks over a 100_000-wide range to beat a real but
2160+ // modest true peak. Escalating only when the narrow bound
2161+ // proves insufficient (FMJ's own core-vs-full delay lands AT
2162+ // the 20_000 edge, corr 0.217393 there, the same edge-noise
2163+ // class the reference-vs-ours gate had) gets both files right
2164+ // without exposing the well-behaved one to the wider bound's
2165+ // noise floor.
2105 const WIDE_LAG_MAX: i64 = 20_000;2166 const WIDE_LAG_MAX: i64 = 20_000;
2106- let (lag, corr) = best_lag_correlation_wide(&ol, &ul, WIDE_LAG_MAX);2167+ let (mut lag, mut corr, mut at_edge) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX);
2168+ let mut bound = WIDE_LAG_MAX;
2169+ if at_edge {
2170+ bound = SEARCH_LAG_MAX;
2171+ (lag, corr, at_edge) = best_lag_correlation_ex(&ol, &ul, SEARCH_LAG_MAX);
2172+ }
2107 println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");2173 println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");
2174+ assert!(
2175+ !at_edge,
2176+ "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \
2177+ search bound -- the true alignment is outside the search, \
2178+ corr {corr:.6} is noise, not a measurement",
2179+ c.path.display()
2180+ );
2108 assert!(2181 assert!(
2109 corr >= 0.99,2182 corr >= 0.99,
2110 "{} ch{ch}: full-chain low band vs our own core-only decode \2183 "{} ch{ch}: full-chain low band vs our own core-only decode \
@@ -2117,60 +2190,6 @@ fn full_chain_low_band_matches_own_core() {
2117 }2190 }
2118 }2191 }
2119 2192
2120-/// Follow-up to round-52: `best_lag_correlation`'s `LAG_MAX=4000` bound was
2121-/// landing HE-AAC winning lags right at its own edge (-3634..-3882) on the
2122-/// synthetic matrix -- this is the same shape `wide_lag_search_full_chain`
2123-/// diagnosed on FMJ. Mirrors that diagnostic's odd-stride coarse pass, but
2124-/// over a caller-supplied `lag_max` and followed by the same full-`WINDOW`
2125-/// refine `best_lag_correlation` does, so its result is directly comparable
2126-/// (not just a coarse `|corr|` estimate).
2127-fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64) {
2128- const COARSE: usize = 4096;
2129- let start = ours
2130- .len()
2131- .min(theirs.len())
2132- .saturating_sub(WINDOW)
2133- .min(ours.len() / 4);
2134- let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
2135- let (oa, ob) = if lag >= 0 {
2136- (start, start + lag as usize)
2137- } else {
2138- (start + (-lag) as usize, start)
2139- };
2140- if oa + len > ours.len() || ob + len > theirs.len() {
2141- None
2142- } else {
2143- Some((oa, ob))
2144- }
2145- };
2146- let mut coarse_best = (0i64, -1.0f64);
2147- let mut lag = -lag_max;
2148- while lag <= lag_max {
2149- if let Some((oa, ob)) = slice_at(lag, COARSE) {
2150- let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]).abs();
2151- if c > coarse_best.1 {
2152- coarse_best = (lag, c);
2153- }
2154- }
2155- lag += 11; // odd stride so it doesn't alias against frame-length periodicity
2156- }
2157- let mut best = (coarse_best.0, -1.0f64, 0.0f64);
2158- for lag in (coarse_best.0 - 16)..=(coarse_best.0 + 16) {
2159- let Some((oa, ob)) = slice_at(lag, WINDOW) else {
2160- continue;
2161- };
2162- let n = WINDOW.min(ours.len() - oa).min(theirs.len() - ob);
2163- if n < 1024 {
2164- continue;
2165- }
2166- let c = correlation(&ours[oa..oa + n], &theirs[ob..ob + n]);
2167- if c.abs() > best.1 {
2168- best = (lag, c.abs(), c);
2169- }
2170- }
2171- (best.0, best.2)
2172-}
2173-
2174 /// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real2193 /// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real
2175 /// file each, whose sample rate, bitrate and content all differ at once),2194 /// file each, whose sample rate, bitrate and content all differ at once),
2176 /// every row here decodes the SAME synthesized source (three summed sine2195 /// every row here decodes the SAME synthesized source (three summed sine
@@ -2448,6 +2467,7 @@ fn sbr_real_library_matches_reference() {
2448 let mut checked = 0;2467 let mut checked = 0;
2449 let mut worst_full = 1.0f64;2468 let mut worst_full = 1.0f64;
2450 let mut worst_low = 1.0f64;2469 let mut worst_low = 1.0f64;
2470+ let mut any_at_edge: Option<String> = None;
2451 for c in &list {2471 for c in &list {
2452 let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {2472 let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {
2453 eprintln!("SKIP {}: could not decode", c.path.display());2473 eprintln!("SKIP {}: could not decode", c.path.display());
@@ -2518,7 +2538,15 @@ fn sbr_real_library_matches_reference() {
2518 rms(t),2538 rms(t),
2519 &t[..10.min(t.len())],2539 &t[..10.min(t.len())],
2520 );2540 );
2521- let (lag, full) = best_lag_correlation(o, t);2541+ let (lag, full, full_at_edge) = best_lag_correlation_ex(o, t, SEARCH_LAG_MAX);
2542+ if full_at_edge {
2543+ any_at_edge.get_or_insert_with(|| {
2544+ format!(
2545+ "{} ch{ch} full-band: winning lag {lag} at +/-{SEARCH_LAG_MAX} search edge",
2546+ c.path.display()
2547+ )
2548+ });
2549+ }
2522 // Re-slice both signals at the winning lag before splitting into2550 // Re-slice both signals at the winning lag before splitting into
2523 // bands, so the band correlations are aligned too.2551 // bands, so the band correlations are aligned too.
2524 let (oa, ob) = if lag >= 0 {2552 let (oa, ob) = if lag >= 0 {
@@ -2546,7 +2574,16 @@ fn sbr_real_library_matches_reference() {
2546 let low = {2574 let low = {
2547 let ol_full = lowpass(o, rate, c.crossover_hz);2575 let ol_full = lowpass(o, rate, c.crossover_hz);
2548 let tl_full = lowpass(t, rate, c.crossover_hz);2576 let tl_full = lowpass(t, rate, c.crossover_hz);
2549- let (low_lag, low_corr) = best_lag_correlation(&ol_full, &tl_full);2577+ let (low_lag, low_corr, low_at_edge) =
2578+ best_lag_correlation_ex(&ol_full, &tl_full, SEARCH_LAG_MAX);
2579+ if low_at_edge {
2580+ any_at_edge.get_or_insert_with(|| {
2581+ format!(
2582+ "{} ch{ch} below-crossover: winning lag {low_lag} at +/-{SEARCH_LAG_MAX} search edge",
2583+ c.path.display()
2584+ )
2585+ });
2586+ }
2550 if low_lag != lag {2587 if low_lag != lag {
2551 eprintln!(2588 eprintln!(
2552 " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}"2589 " ch{ch} below-crossover band's own best lag {low_lag} differs from full-band lag {lag}"
@@ -2973,6 +3010,12 @@ fn sbr_real_library_matches_reference() {
2973 eprintln!("SKIP: no plain-SBR real files decoded");3010 eprintln!("SKIP: no plain-SBR real files decoded");
2974 return;3011 return;
2975 }3012 }
3013+ assert!(
3014+ any_at_edge.is_none(),
3015+ "lag search hit its bound: {} -- the reported correlations are noise \
3016+ at the search edge, not a measurement",
3017+ any_at_edge.unwrap_or_default()
3018+ );
2976 assert!(3019 assert!(
2977 worst_full >= 0.999,3020 worst_full >= 0.999,
2978 "worst full-band correlation {worst_full:.6} < 0.999 bar"3021 "worst full-band correlation {worst_full:.6} < 0.999 bar"