forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-vorbis-reservoir': bit reservoir ends the post-transient dropouts in ec-vorbis

Browse files at this commit

2461109b809a49a5af8870f61c379c7174ed157cAhmet Kaan GümüşParent: b284f90fc5a0f8
crates/ec-vorbis/src/encode.rsmodified+23 -3
@@ -257,6 +257,9 @@ pub struct VorbisEncoder {
257 scheduler: Sched,257 scheduler: Sched,
258 /// Headroom under the masking curve, in dB — the rate loop's variable.258 /// Headroom under the masking curve, in dB — the rate loop's variable.
259 headroom: f64,259 headroom: f64,
260+ /// Bits the forced-precision blocks spent past their share, repaid by the
261+ /// steady blocks that follow (see [`VorbisEncoder::update_rate`]).
262+ reservoir_debt: f64,
260 finished: bool,263 finished: bool,
261 packets: std::collections::VecDeque<EncodedPacket>,264 packets: std::collections::VecDeque<EncodedPacket>,
262 }265 }
@@ -342,6 +345,7 @@ impl VorbisEncoder {
342 granule: 0,345 granule: 0,
343 scheduler: Sched::Steady,346 scheduler: Sched::Steady,
344 headroom: 4.0 + 26.0 * quality,347 headroom: 4.0 + 26.0 * quality,
348+ reservoir_debt: 0.0,
345 finished: false,349 finished: false,
346 packets: std::collections::VecDeque::new(),350 packets: std::collections::VecDeque::new(),
347 config,351 config,
@@ -819,7 +823,8 @@ impl VorbisEncoder {
819 );823 );
820 let bits = out.len();824 let bits = out.len();
821 let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre;825 let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre;
822- self.update_rate(bits, half, channels, delta);826+ let steady = plan.is_long && plan.prev_long && plan.next_long;
827+ self.update_rate(bits, half, channels, delta, steady);
823 out.finish()828 out.finish()
824 }829 }
825 830
@@ -833,14 +838,29 @@ impl VorbisEncoder {
833 /// judged against a proportionally small bit budget. The ceiling is well838 /// judged against a proportionally small bit budget. The ceiling is well
834 /// past [`HEADROOM_RANGE`]: beyond it headroom buys bins under the839 /// past [`HEADROOM_RANGE`]: beyond it headroom buys bins under the
835 /// threshold rather than step, which is what quiet content needs.840 /// threshold rather than step, which is what quiet content needs.
836- fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) {841+ ///
842+ /// Blocks next to a short window are quantised with a forced minimum
843+ /// precision the loop cannot lower, so their overspend must not step the
844+ /// headroom: a run of 16–32 short blocks at −2 dB each drove it to the
845+ /// −24 dB floor, which put the floor above the signal and emitted ~10
846+ /// silent long blocks (200 ms dropouts at −20 dBFS) after every
847+ /// transient. Their excess goes into a reservoir debt instead, repaid by
848+ /// the steady blocks that follow at no more than a quarter of each block's
849+ /// share, so the rate still lands on target over about a second.
850+ fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64, steady: bool) {
837 if self.config.bitrate_bps <= 0 || delta <= 0 {851 if self.config.bitrate_bps <= 0 || delta <= 0 {
838 return;852 return;
839 }853 }
840 let target = f64::from(self.config.bitrate_bps) * RATE_TARGET_SCALE * delta as f64854 let target = f64::from(self.config.bitrate_bps) * RATE_TARGET_SCALE * delta as f64
841 / f64::from(self.config.sample_rate);855 / f64::from(self.config.sample_rate);
856+ if !steady {
857+ self.reservoir_debt += bits as f64 - target;
858+ return;
859+ }
860+ let repay = self.reservoir_debt.clamp(-target * 0.25, target * 0.25);
861+ self.reservoir_debt -= repay;
842 let coefficients = (half * channels) as f64;862 let coefficients = (half * channels) as f64;
843- let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);863+ let step = ((target - repay - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);
844 // Negative headroom is not a mistake: it puts the floor *above* the864 // Negative headroom is not a mistake: it puts the floor *above* the
845 // signal, which quantises the coefficients under it to zero and lets a865 // signal, which quantises the coefficients under it to zero and lets a
846 // whole partition become class 0 for two bits. Without that a low target866 // whole partition become class 0 for two bits. Without that a low target
crates/ec-vorbis/tests/oracle.rsmodified+125 -0
@@ -747,3 +747,128 @@ fn quiet_content_reaches_the_target_or_is_transparent() {
747 }747 }
748 }748 }
749 }749 }
750+
751+
752+fn ffmpeg_decode_limited(path: &Path, rate: u32, max_samples: usize) -> Option<(Vec<Vec<f32>>, u32)> {
753+ let out = Command::new("ffmpeg")
754+ .args(["-v", "error", "-i"])
755+ .arg(path)
756+ .args(["-t", &format!("{}", max_samples / rate as usize),
757+ "-ac", "2", "-ar", &rate.to_string(),
758+ "-f", "f32le", "-acodec", "pcm_f32le", "-"])
759+ .output()
760+ .expect("ffmpeg runs");
761+ if !out.stderr.is_empty() {
762+ eprintln!("ffmpeg stderr: {}", String::from_utf8_lossy(&out.stderr));
763+ return None;
764+ }
765+ let channels = 2usize;
766+ let interleaved: Vec<f32> = out
767+ .stdout
768+ .chunks_exact(4)
769+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
770+ .collect();
771+ let n = interleaved.len() / channels;
772+ let n = n.min(max_samples);
773+ let mut planes = vec![Vec::with_capacity(n); channels];
774+ for (i, value) in interleaved.into_iter().enumerate().take(n * channels) {
775+ planes[i % channels].push(value);
776+ }
777+ Some((planes, rate))
778+}
779+
780+
781+
782+fn shellexpand(path: &str) -> String {
783+ if let Some(rest) = path.strip_prefix("~/") {
784+ let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string());
785+ format!("{home}/{rest}")
786+ } else {
787+ path.to_string()
788+ }
789+}
790+
791+
792+/// Full-file sweep over the user's library at the two managed rates: ours
793+/// encoded at the size libvorbis actually produced (ffmpeg's -b:a is
794+/// unmanaged VBR, 10-30% under nominal on real music), bytes within ±3% of
795+/// it and correlation-to-source within .005 of it. Both encodes decode
796+/// through our decoder so the gap measures the encoders, not the decoders.
797+/// Writes `lanes/vorbis-reservoir.sweep.txt`.
798+#[test]
799+#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"]
800+fn real_library_sweep_vs_reference() {
801+ let sources: &[(&str, &str)] = &[
802+ ("nik", "~/Music/reeln.mp4"),
803+ ("reelo", "~/Music/reelo.mp3"),
804+ ("her", "~/Music/reeli.mp3"),
805+ ("reell", "~/Music/reell.mp4"),
806+ ("reelm", "~/Music/reelm.wav"),
807+ ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
808+ ("hein", "~/Downloads/reelm.mp3"),
809+ ];
810+ let rate = 48_000u32;
811+ let max_samples = rate as usize * 600;
812+ let out_dir = scratch().join("vorbis7-sweep");
813+ std::fs::create_dir_all(&out_dir).expect("out dir");
814+ let mut table = String::from("source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap verdict\n");
815+ let mut failures = Vec::new();
816+ let only = std::env::var("SWEEP_ONLY").ok();
817+ for &(name, src_path) in sources {
818+ if only.as_deref().is_some_and(|o| !o.split(',').any(|n| n == name)) {
819+ continue;
820+ }
821+ let src = PathBuf::from(shellexpand(src_path));
822+ if !src.exists() {
823+ table.push_str(&format!("{name:<7} - SKIP (missing)\n"));
824+ continue;
825+ }
826+ let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
827+ table.push_str(&format!("{name:<7} - SKIP (decode)\n"));
828+ continue;
829+ };
830+ let seconds = source_pcm[0].len() as f64 / f64::from(rate);
831+ for &kbps in &[96i32, 128] {
832+ // libvorbis under ffmpeg's -b:a runs unmanaged VBR and lands
833+ // 10-30% under the nominal rate on real music, so ours is asked
834+ // for the bytes it actually produced: quality at equal size.
835+ let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg"));
836+ let status = Command::new("ffmpeg")
837+ .args(["-y", "-v", "error", "-i"])
838+ .arg(&src)
839+ .args(["-vn", "-t", "600", "-ac", "2", "-ar", "48000", "-c:a", "libvorbis", "-b:a", &format!("{kbps}k")])
840+ .arg(&reference)
841+ .status()
842+ .expect("ffmpeg runs");
843+ assert!(status.success(), "libvorbis encode of {name} at {kbps}k");
844+ let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64;
845+ let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0;
846+ let ours = encode_to_file(&source_pcm, rate, (ref_kbps * 1000.0).round() as i32, &format!("vorbis7-sweep/ours-{name}-{kbps}k.ogg"));
847+ let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0;
848+ let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
849+ let corr_of = |p: &Path| -> f64 {
850+ let (pcm, _) = our_decode(p);
851+ let n = pcm[0].len().min(source_pcm[0].len());
852+ (0..2).map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n])).sum::<f64>() / 2.0
853+ };
854+ let corr_ours = corr_of(&ours);
855+ let corr_ref = corr_of(&reference);
856+ let gap = corr_ref - corr_ours;
857+ let pass = rate_pct.abs() <= 3.0 && gap <= 0.005;
858+ if !pass {
859+ failures.push(format!("{name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4}"));
860+ }
861+ table.push_str(&format!(
862+ "{name:<7} {kbps:<6} {ours_kbps:<9.1} {ref_kbps:<8.1} {rate_pct:+6.2} {corr_ours:<9.4} {corr_ref:<8.4} {gap:<7.4} {}\n",
863+ if pass { "PASS" } else { "FAIL" }
864+ ));
865+ eprintln!("{}", table.lines().last().unwrap());
866+ }
867+ }
868+ eprintln!("\n{table}");
869+ let _ = std::fs::write(
870+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis7-bisect.sweep.txt"),
871+ &table,
872+ );
873+ assert!(failures.is_empty(), "sweep failures: {failures:?}");
874+}