From 9b7e0e0e2c0d4598b6bc63c9746ae977c4a92a5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 00:56:38 +0300 Subject: [PATCH] fix(vorbis-enc): cap the ATH at -80 dBFS so an onset inside a short block is not coded against a -10 dB floor The pre-echo the verifier measured (gap RMS 0.002261 at 44.1k, peak 0.073) lived entirely in the one short block whose window straddles the onset, not in the long->short transition block: the block plan already puts the onset mid short-run. Its DC bin and every bin above ~17 kHz were quantised against the absolute-threshold floor, whose own curve sits at -13 / -10 dBFS there, so a 0.1-amplitude step coefficient took a 0.2-0.3 quantiser step and its error spread over the whole 256-sample window at -38 dB. Capping the ATH at -80 dBFS gives gap RMS 0.000059 / peak 0.0028 (reference encoder on the same input: 0.000120 / 0.0057). Also gate a steady long block on its lookahead hop being buffered: with chunked input the plan was committed before the detector could see the transient it is supposed to make room for. Test now places the onset off the block grid (0.9137 s) as well as on it, measures the whole [0, onset) gap plus its peak, mono and stereo, 44.1k/48k, our decoder and the reference oracle. --- crates/ec-vorbis/src/encode.rs | 16 ++++- crates/ec-vorbis/tests/oracle.rs | 108 +++++++++++++++---------------- 2 files changed, 69 insertions(+), 55 deletions(-) diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs index c3dc539b..e62ca4e8 100644 --- a/crates/ec-vorbis/src/encode.rs +++ b/crates/ec-vorbis/src/encode.rs @@ -457,6 +457,14 @@ impl VorbisEncoder { if buffer_start < 0 || self.buffer[0].len() < buffer_start as usize + n { break; } + // A steady long block is typed by the hop *after* it; until that + // hop is buffered the plan just peeked was decided blind. + if !self.finished + && matches!(self.scheduler, Sched::Steady) + && self.buffer[0].len() < buffer_start as usize + n + BLOCK_LONG + { + break; + } let granule = match self.finished { true => centre.min(self.fed), false => centre, @@ -933,11 +941,17 @@ fn design_residue_books() -> Vec { } /// Absolute threshold of hearing in dBFS, full scale taken as 96 dB SPL. +/// +/// Capped at -80 dBFS: the curve's own values at DC and above ~17 kHz +/// (-13 / -10 dBFS) are not a quantiser step the rest of a block can live +/// with — an onset inside a short block puts real energy in exactly those +/// bins, and coding them that coarsely leaked -38 dB of pre-echo across the +/// whole 256-sample window. fn absolute_threshold(hz: f64) -> f64 { let khz = (hz / 1000.0).clamp(0.02, 20.0); let spl = 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4); - (spl - 96.0).clamp(-120.0, -10.0) + (spl - 96.0).clamp(-120.0, -80.0) } /// The three header packets, in order. diff --git a/crates/ec-vorbis/tests/oracle.rs b/crates/ec-vorbis/tests/oracle.rs index 35290082..2ab84960 100644 --- a/crates/ec-vorbis/tests/oracle.rs +++ b/crates/ec-vorbis/tests/oracle.rs @@ -561,61 +561,61 @@ fn busy(channels: usize, rate: u32, samples: usize) -> Vec> { /// does. #[test] fn onset_after_silence_has_no_pre_echo() { + // Two onsets: one off the block grid (0.9137 s lands mid short block) and + // one on it. The gap is measured over the WHOLE silence up to the onset, + // so a leak in the last few hundred samples before it cannot hide behind a + // guard band, and the peak is barred too. for rate in [44_100u32, 48_000] { - let silence = rate as usize; - let tone_len = rate as usize; - let mut left = vec![0.0f32; silence + tone_len]; - let mut right = vec![0.0f32; silence + tone_len]; - for i in 0..tone_len { - let t = i as f64 / f64::from(rate); - let v = (2.0 * std::f64::consts::PI * 1_000.0 * t).sin() as f32; - left[silence + i] = v; - right[silence + i] = v; - } - let source = vec![left, right]; - let name = format!("onset-{rate}.ogg"); - let path = encode_to_file(&source, rate, -1, &name); - - // The reference oracle must decode the short-block stream cleanly: - // no warnings, let alone errors. - let warn = Command::new("ffmpeg") - .args(["-v", "warning", "-i"]) - .arg(&path) - .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) - .output(); - if let Ok(out) = warn { - assert!( - out.stderr.is_empty(), - "{name}: oracle decode warnings: {}", - String::from_utf8_lossy(&out.stderr) - ); - } - - let window = |plane: &[f32], rate: u32| -> f64 { - let lo = (0.90 * f64::from(rate)) as usize; - let hi = ((0.995 * f64::from(rate)) as usize).min(plane.len()); - let lo = lo.min(hi); - rms(&plane[lo..hi]) - }; - let tone_rms = { - let lo = silence + rate as usize / 20; - let hi = (silence + tone_len).min(silence + tone_len); - rms(&source[0][lo..hi]) - }; - - let (ours, _) = our_decode(&path); - let gap = window(&ours[0], rate); - assert!( - gap <= 0.002 * tone_rms, - "{name}: our decode gap RMS {gap:.6} vs tone RMS {tone_rms:.6}" - ); - - if let Some((theirs, _)) = ffmpeg_decode(&path) { - let gap = window(&theirs[0], rate); - assert!( - gap <= 0.002 * tone_rms, - "{name}: oracle decode gap RMS {gap:.6} vs tone RMS {tone_rms:.6}" - ); + for channels in [1usize, 2] { + for onset_s in [0.9137f64, 1.0] { + let onset = (onset_s * f64::from(rate)) as usize; + let tone_len = rate as usize; + let mut source = vec![vec![0.0f32; onset + tone_len]; channels]; + for i in 0..tone_len { + let t = i as f64 / f64::from(rate); + let v = (0.7 * (2.0 * std::f64::consts::PI * 1_000.0 * t).sin()) as f32; + for plane in &mut source { + plane[onset + i] = v; + } + } + let name = format!("onset-{rate}-{channels}ch-{onset}.ogg"); + let path = encode_to_file(&source, rate, 128_000, &name); + + // The reference oracle must decode the short-block stream + // cleanly: no warnings, let alone errors. + let warn = Command::new("ffmpeg") + .args(["-v", "warning", "-i"]) + .arg(&path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output(); + if let Ok(out) = warn { + assert!( + out.stderr.is_empty(), + "{name}: oracle decode warnings: {}", + String::from_utf8_lossy(&out.stderr) + ); + } + + let tone_rms = rms(&source[0][onset..]); + let check = |label: &str, planes: &[Vec]| { + for (c, plane) in planes.iter().enumerate() { + let gap = &plane[..onset.min(plane.len())]; + let gap_rms = rms(gap); + let peak = gap.iter().fold(0.0f32, |m, v| m.max(v.abs())); + println!("{name}/{label} ch{c}: gap RMS {gap_rms:.6} peak {peak:.4}"); + assert!( + gap_rms <= 0.002 * tone_rms, + "{name}/{label} ch{c}: gap RMS {gap_rms:.6} vs tone RMS {tone_rms:.6}" + ); + assert!(peak <= 0.007, "{name}/{label} ch{c}: gap peak {peak:.4}"); + } + }; + let (ours, _) = our_decode(&path); + check("ours", &ours); + if let Some((theirs, _)) = ffmpeg_decode(&path) { + check("oracle", &theirs); + } + } } } }