forge
Explore
Log in

Don't you dare go Hollow

Let rate-loop headroom past the residue range lower the ATH bound, so quiet/sparse content reaches the target

Browse files at this commit

14b96becf14402b54b6b8711c2d8c9440c6320ddAhmet Kaan GümüşParent: 9b7e0e0
  • fix
    • let rate-loop headroom past the residue range lower the ATH bound, so quiet/sparse content reaches the target
Show full message
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.rsmodified+14 -3
@@ -71,6 +71,13 @@ const FLOOR_CLASS_DIM: usize = 4;
71 const CLASSES: usize = 5;71 const CLASSES: usize = 5;
72 /// Largest quantised residue each class's book can state.72 /// Largest quantised residue each class's book can state.
73 const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127];73 const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127];
74+/// Headroom in dB the widest residue book can actually state: 20 log10 127
75+/// is 42, but a coupled angle channel is a difference of two magnitudes, so a
76+/// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold
77+/// bound instead, so sparse or quiet content — where most partitions sit under
78+/// the threshold and code as class 0 whatever the step — gains bins to spend
79+/// bits on rather than a finer step nothing can represent.
80+const HEADROOM_RANGE: f64 = 36.0;
74 /// Samples per transient-detection tick — the short block's own hop, so a81 /// Samples per transient-detection tick — the short block's own hop, so a
75 /// tick lines up with the finest time resolution the encoder has.82 /// tick lines up with the finest time resolution the encoder has.
76 const TICK: usize = BLOCK_SHORT / 4;83 const TICK: usize = BLOCK_SHORT / 4;
@@ -600,7 +607,9 @@ impl VorbisEncoder {
600 /// within a few blocks and is clamped either side so a transient cannot607 /// within a few blocks and is clamped either side so a transient cannot
601 /// swing the whole file. The target itself scales with this block's own608 /// swing the whole file. The target itself scales with this block's own
602 /// granule advance, so a short block (a small fraction of a long hop) is609 /// granule advance, so a short block (a small fraction of a long hop) is
603- /// judged against a proportionally small bit budget.610+ /// judged against a proportionally small bit budget. The ceiling is well
611+ /// past [`HEADROOM_RANGE`]: beyond it headroom buys bins under the
612+ /// threshold rather than step, which is what quiet content needs.
604 fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) {613 fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) {
605 if self.config.bitrate_bps <= 0 || delta <= 0 {614 if self.config.bitrate_bps <= 0 || delta <= 0 {
606 return;615 return;
@@ -613,7 +622,7 @@ impl VorbisEncoder {
613 // whole partition become class 0 for two bits. Without that a low target622 // whole partition become class 0 for two bits. Without that a low target
614 // cannot be reached at all — coding every coefficient with the shortest623 // cannot be reached at all — coding every coefficient with the shortest
615 // codeword there is already costs about a bit each.624 // codeword there is already costs about a bit each.
616- self.headroom = (self.headroom + step).clamp(-24.0, 36.0);625+ self.headroom = (self.headroom + step).clamp(-24.0, 84.0);
617 }626 }
618 }627 }
619 628
@@ -666,7 +675,9 @@ fn fit_floor(floor: &Floor1, ath: &[f64], headroom: f64, peaks: &[f64]) -> (Vec<
666 let target: Vec<f64> = db675 let target: Vec<f64> = db
667 .iter()676 .iter()
668 .zip(ath.iter())677 .zip(ath.iter())
669- .map(|(&level, &threshold)| (level - headroom).max(threshold))678+ .map(|(&level, &threshold)| {
679+ (level - headroom.min(HEADROOM_RANGE)).max(threshold - (headroom - HEADROOM_RANGE).max(0.0))
680+ })
670 .collect();681 .collect();
671 let y: Vec<i32> = target682 let y: Vec<i32> = target
672 .iter()683 .iter()
crates/ec-vorbis/tests/oracle.rsmodified+69 -0
@@ -651,3 +651,72 @@ fn the_rate_loop_tracks_the_target_bitrate() {
651 );651 );
652 }652 }
653 }653 }
654+
655+/// Quiet and sparse content must reach the target too: with the floor bounded
656+/// by the threshold of hearing, most partitions code as class 0 at any step,
657+/// so the rate loop's extra headroom has to lower that bound to find bits to
658+/// spend. The fixture is a sparse tone at -18 dBFS; the synthetic sources are
659+/// the busy and tonal signals at -40 dBFS, the tones over a -90 dBFS noise
660+/// floor (what any 16-bit source carries; a pure digital tone has nothing
661+/// outside its own bins for any step to find). Noise is incompressible, so the
662+/// quiet noise is held to the full-scale noise's own fidelity rather than a
663+/// fixed bar.
664+#[test]
665+fn quiet_content_reaches_the_target_within_25pct() {
666+ let rate = 48_000u32;
667+ let samples = rate as usize * 3;
668+ let fixture = ffmpeg_decode(&fixtures().join("audio/wav16-stereo-48000.wav"))
669+ .expect("fixture decodes");
670+ assert_eq!(fixture.1, rate);
671+ let attenuate = |mut source: Vec<Vec<f32>>| {
672+ for channel in source.iter_mut() {
673+ for value in channel.iter_mut() {
674+ *value *= 0.01;
675+ }
676+ }
677+ source
678+ };
679+ let corr_at = |path: &Path, source: &[Vec<f32>]| {
680+ let (decoded, _) = our_decode(path);
681+ decoded
682+ .iter()
683+ .zip(source.iter())
684+ .map(|(channel, original)| {
685+ let n = channel.len().min(original.len());
686+ correlation(&channel[..n], &original[..n])
687+ })
688+ .fold(1.0f64, f64::min)
689+ };
690+ let loud = busy(2, rate, samples);
691+ let loud_corr = corr_at(&encode_to_file(&loud, rate, 128_000, "loud-128k.ogg"), &loud);
692+ let quiet_noise = attenuate(loud);
693+ let mut quiet_tones = attenuate(tones(2, rate, samples));
694+ for (channel, noise) in quiet_tones.iter_mut().zip(busy(2, rate, samples)) {
695+ for (value, n) in channel.iter_mut().zip(noise) {
696+ *value += n * 0.0001;
697+ }
698+ }
699+ let cases = [
700+ ("fixture", &fixture.0, 0.99),
701+ ("quiet-tones", &quiet_tones, 0.99),
702+ ("quiet-noise", &quiet_noise, loud_corr - 0.02),
703+ ];
704+ for (name, source, bar) in cases {
705+ let mut measured = Vec::new();
706+ for target in [96_000i32, 128_000, 192_000] {
707+ let path = encode_to_file(source, rate, target, &format!("{name}-{}k.ogg", target / 1000));
708+ let bytes = std::fs::metadata(&path).expect("file").len();
709+ let kbps = bytes as f64 * 8.0 * f64::from(rate) / source[0].len() as f64 / 1000.0;
710+ let corr = corr_at(&path, source);
711+ println!("{name}: target {} kbps -> {kbps:.0} kbps, corr {corr:.4}", target / 1000);
712+ measured.push(kbps);
713+ if target == 128_000 {
714+ assert!(corr >= bar, "{name}: corr {corr:.4} under {bar:.4}");
715+ }
716+ }
717+ assert!(measured[0] < measured[1] && measured[1] < measured[2], "{name}: {measured:?}");
718+ for (kbps, target) in measured.iter().zip([96.0, 128.0, 192.0]) {
719+ assert!((kbps - target).abs() / target < 0.25, "{name}: {kbps:.0} kbps for {target:.0}");
720+ }
721+ }
722+}