makepad/libs/game/audio/examples/vorbis_trim.rs
Admin 62d6732504 Vorbis: mono decodes sample-exact (115/160 files exact, was 0)
Two root causes, both found by building an oracle rather than guessing.

1. Amplitude ~75x low: the IMDCT applied a 2/n normalisation the encoder's
   forward transform had already carried. Because 2/n varies with block size
   it produced DIFFERENT errors on 256- vs 2048-sample blocks — exactly the
   reported symptom. Removing it gives fit scale 1.0000.

2. Leading trim, the real remaining defect. The first audio packet produces NO
   output (its window only primes the overlap-add) but we emitted from the
   first block's centre, injecting half a priming window of garbage and
   shifting everything early. And Vorbis carries encoder delay in the GRANULE
   POSITION, which varies per file — afinfo confirms 128 / 1103 / 960 frames
   on three samples — while our Ogg reader kept only last_granule and
   discarded per-page granules, making it unrecoverable. Added per-page
   granule tracking: the first page reporting a granule pins priming as
   centre - granule, and valid audio starts at priming + blocksize_0/2. That
   reproduces afinfo's numbers exactly on all three.

A premise in the brief was also wrong and worth recording: our output length
was already correct. afinfo reports valid frames matching OUR output — it is
afconvert that trims a further 128. The reference WAV was short, not us.

  mono    47 files  mean corr 1.00000 (min 1.00000)  47/47 exact
  stereo 107 files  mean corr 0.826                  68/107 exact

Decode cost 5.13 ms/file average; 11.5 MB compressed expands to 143.3 MB of
f32 PCM, which is why the sample bank's LRU cap matters.

Honest remaining defect: ~39 stereo files decode wrongly and it is NOT
alignment — a full lag sweep peaks at 0.40-0.89 with fit scales 0.40-1.87, so
specific blocks have wrong amplitude. Mono being 47/47 rules out floor,
residue 0/1, MDCT, windowing and priming; coupling matches the spec's
square-polar mapping including reverse order; floor 0 is rejected rather than
mis-decoded; and both channels are identical in the failing files, so it is
not a swap. The failing set is transient-heavy impact/footstep sounds, so the
lead is residue type 2 partition counting on short blocks.

reference_decode.rs is no longer #[ignore]d: 3 real tests asserting mono
correlation > 0.999 and length == granule, plus a 3000-mutation fuzz that must
never panic, all skipping cleanly without fixtures.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 09:26:27 +02:00

86 lines
2.9 KiB
Rust

//! Derive the trim rule: search (start, len) against a reference so the
//! correct offset is measured, not assumed.
//! Usage: vorbis_trim <file.ogg> <ref.wav>
use makepad_game_audio as audio;
fn main() {
let a: Vec<String> = std::env::args().collect();
let ogg = std::fs::read(&a[1]).expect("ogg");
let refw = std::fs::read(&a[2]).expect("ref");
let (buf, first_center, granule) = audio::vorbis::debug_raw(&ogg).expect("raw");
let want = audio::wav::decode(&refw).expect("ref wav");
let ch = buf.len();
let buflen = buf[0].len();
let wf = want.frames();
println!("buflen={buflen} first_center={first_center} granule={granule} ref_frames={wf} ch={ch}");
// Exact-match search: for each candidate start, how well does
// buf[start .. start+ref_frames] line up with the reference?
let mut best = (0usize, f64::INFINITY);
let lo = first_center.saturating_sub(1024);
let hi = (first_center + 1024).min(buflen.saturating_sub(wf));
for start in lo..=hi {
if start + wf > buflen {
break;
}
let mut err = 0f64;
// Sparse but dense enough to rank candidates unambiguously.
let mut i = 0usize;
while i < wf {
for c in 0..ch {
let g = buf[c][start + i] as f64;
let w = want.samples[i * ch + c] as f64;
err += (g - w) * (g - w);
}
i += 7;
}
if err < best.1 {
best = (start, err);
}
}
let rms = (best.1 / (wf / 7).max(1) as f64).sqrt();
println!(
"BEST start={} (first_center{:+}) rms_err={:.3e} | granule-reflen={}",
best.0,
best.0 as i64 - first_center as i64,
rms,
granule as i64 - wf as i64
);
println!(
" tail: buflen-(start+reflen)={}",
buflen as i64 - (best.0 + wf) as i64
);
// Is the region our decode emits before the reference's first sample
// actually silent? If so afconvert trimmed it and we are not wrong.
let rms_of = |lo: usize, hi: usize| -> f64 {
if hi <= lo {
return 0.0;
}
let mut s = 0f64;
let mut n = 0usize;
for c in 0..ch {
for i in lo..hi.min(buflen) {
s += (buf[c][i] as f64).powi(2);
n += 1;
}
}
if n == 0 { 0.0 } else { (s / n as f64).sqrt() }
};
let peak_of = |lo: usize, hi: usize| -> f64 {
let mut p = 0f64;
for c in 0..ch {
for i in lo..hi.min(buflen) {
p = p.max((buf[c][i] as f64).abs());
}
}
p
};
println!(
" lead region [{}..{}]: rms={:.3e} peak={:.3e} (signal rms={:.3e})",
first_center,
best.0,
rms_of(first_center, best.0),
peak_of(first_center, best.0),
rms_of(best.0, best.0 + wf.min(4096))
);
}