From 14b96becf14402b54b6b8711c2d8c9440c6320dd 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 01:03:24 +0300 Subject: [PATCH] fix(vorbis-enc): let rate-loop headroom past the residue range lower the ATH bound, so quiet/sparse content reaches the target The widest residue book states +-127 and a coupled angle is a difference of two magnitudes, so a pair's step cannot usefully go past 36 dB under the peak. On sparse or quiet content the floor sits on the absolute threshold almost everywhere, those partitions code as class 0 at any step, and the loop pegged at 36 dB with ~44 kbps against a 128 kbps target. Headroom now clamps at 84 dB; the part past 36 dB lowers the threshold bound instead of the step, which gives the loop bins under the old threshold to spend on. Decoder and stream syntax untouched. --- crates/ec-vorbis/src/encode.rs | 17 ++++++-- crates/ec-vorbis/tests/oracle.rs | 69 ++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs index e62ca4e8..b7914653 100644 --- a/crates/ec-vorbis/src/encode.rs +++ b/crates/ec-vorbis/src/encode.rs @@ -71,6 +71,13 @@ const FLOOR_CLASS_DIM: usize = 4; const CLASSES: usize = 5; /// Largest quantised residue each class's book can state. const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127]; +/// Headroom in dB the widest residue book can actually state: 20 log10 127 +/// is 42, but a coupled angle channel is a difference of two magnitudes, so a +/// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold +/// bound instead, so sparse or quiet content — where most partitions sit under +/// the threshold and code as class 0 whatever the step — gains bins to spend +/// bits on rather than a finer step nothing can represent. +const HEADROOM_RANGE: f64 = 36.0; /// Samples per transient-detection tick — the short block's own hop, so a /// tick lines up with the finest time resolution the encoder has. const TICK: usize = BLOCK_SHORT / 4; @@ -600,7 +607,9 @@ impl VorbisEncoder { /// within a few blocks and is clamped either side so a transient cannot /// swing the whole file. The target itself scales with this block's own /// granule advance, so a short block (a small fraction of a long hop) is - /// judged against a proportionally small bit budget. + /// judged against a proportionally small bit budget. The ceiling is well + /// past [`HEADROOM_RANGE`]: beyond it headroom buys bins under the + /// threshold rather than step, which is what quiet content needs. fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) { if self.config.bitrate_bps <= 0 || delta <= 0 { return; @@ -613,7 +622,7 @@ impl VorbisEncoder { // whole partition become class 0 for two bits. Without that a low target // cannot be reached at all — coding every coefficient with the shortest // codeword there is already costs about a bit each. - self.headroom = (self.headroom + step).clamp(-24.0, 36.0); + self.headroom = (self.headroom + step).clamp(-24.0, 84.0); } } @@ -666,7 +675,9 @@ fn fit_floor(floor: &Floor1, ath: &[f64], headroom: f64, peaks: &[f64]) -> (Vec< let target: Vec = db .iter() .zip(ath.iter()) - .map(|(&level, &threshold)| (level - headroom).max(threshold)) + .map(|(&level, &threshold)| { + (level - headroom.min(HEADROOM_RANGE)).max(threshold - (headroom - HEADROOM_RANGE).max(0.0)) + }) .collect(); let y: Vec = target .iter() diff --git a/crates/ec-vorbis/tests/oracle.rs b/crates/ec-vorbis/tests/oracle.rs index 2ab84960..99273f78 100644 --- a/crates/ec-vorbis/tests/oracle.rs +++ b/crates/ec-vorbis/tests/oracle.rs @@ -651,3 +651,72 @@ fn the_rate_loop_tracks_the_target_bitrate() { ); } } + +/// Quiet and sparse content must reach the target too: with the floor bounded +/// by the threshold of hearing, most partitions code as class 0 at any step, +/// so the rate loop's extra headroom has to lower that bound to find bits to +/// spend. The fixture is a sparse tone at -18 dBFS; the synthetic sources are +/// the busy and tonal signals at -40 dBFS, the tones over a -90 dBFS noise +/// floor (what any 16-bit source carries; a pure digital tone has nothing +/// outside its own bins for any step to find). Noise is incompressible, so the +/// quiet noise is held to the full-scale noise's own fidelity rather than a +/// fixed bar. +#[test] +fn quiet_content_reaches_the_target_within_25pct() { + let rate = 48_000u32; + let samples = rate as usize * 3; + let fixture = ffmpeg_decode(&fixtures().join("audio/wav16-stereo-48000.wav")) + .expect("fixture decodes"); + assert_eq!(fixture.1, rate); + let attenuate = |mut source: Vec>| { + for channel in source.iter_mut() { + for value in channel.iter_mut() { + *value *= 0.01; + } + } + source + }; + let corr_at = |path: &Path, source: &[Vec]| { + let (decoded, _) = our_decode(path); + decoded + .iter() + .zip(source.iter()) + .map(|(channel, original)| { + let n = channel.len().min(original.len()); + correlation(&channel[..n], &original[..n]) + }) + .fold(1.0f64, f64::min) + }; + let loud = busy(2, rate, samples); + let loud_corr = corr_at(&encode_to_file(&loud, rate, 128_000, "loud-128k.ogg"), &loud); + let quiet_noise = attenuate(loud); + let mut quiet_tones = attenuate(tones(2, rate, samples)); + for (channel, noise) in quiet_tones.iter_mut().zip(busy(2, rate, samples)) { + for (value, n) in channel.iter_mut().zip(noise) { + *value += n * 0.0001; + } + } + let cases = [ + ("fixture", &fixture.0, 0.99), + ("quiet-tones", &quiet_tones, 0.99), + ("quiet-noise", &quiet_noise, loud_corr - 0.02), + ]; + for (name, source, bar) in cases { + let mut measured = Vec::new(); + for target in [96_000i32, 128_000, 192_000] { + let path = encode_to_file(source, rate, target, &format!("{name}-{}k.ogg", target / 1000)); + let bytes = std::fs::metadata(&path).expect("file").len(); + let kbps = bytes as f64 * 8.0 * f64::from(rate) / source[0].len() as f64 / 1000.0; + let corr = corr_at(&path, source); + println!("{name}: target {} kbps -> {kbps:.0} kbps, corr {corr:.4}", target / 1000); + measured.push(kbps); + if target == 128_000 { + assert!(corr >= bar, "{name}: corr {corr:.4} under {bar:.4}"); + } + } + assert!(measured[0] < measured[1] && measured[1] < measured[2], "{name}: {measured:?}"); + for (kbps, target) in measured.iter().zip([96.0, 128.0, 192.0]) { + assert!((kbps - target).abs() / target < 0.25, "{name}: {kbps:.0} kbps for {target:.0}"); + } + } +}