From 806ee38e8b3065a8b880a2159d57b682f6e1088c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 23 Aug 2026 23:17:31 +0300 Subject: [PATCH] mp3: gate VBR against the reference ladder, and split its frames too VBR had no reference gate, which is why the demand-weighted frame split landed in the CBR arm only. The gate encodes every rung of libmp3lame's VBR ladder on each source and compares against the rung that actually spent what we spent -- nominal rates are no guide, since V6 is nominally 115 kbit/s and lands near 60 on speech. Measured that way the shipped VBR lost almost everywhere: 11 of 14 rows behind on correlation and up to 8 dB behind on the worst 20 ms window at the same rate. The demand split takes that to 10 rows ahead, and recalibrating the quality bar takes it to 13. The recalibration is the second half of the split: reaching the same masking bar for fewer bits has to be spent, not pocketed, because the quality knob promises a mean rate. The bar now tightens by 1.6 - 12q decibels, fitted so quality 0.3 lands at 162 kbit/s against its promised 163 and quality 0.6 at 232 against 230. Floors are set from the measurement: correlation -0.0005, worst-window excess 3.5 dB, and 8% of the matched rung's rate, with top-rung rows exempt from the rate check because the reference cannot spend more there. --- crates/ec-mp3/src/encode.rs | 17 +-- crates/ec-mp3/tests/encode_matrix.rs | 150 +++++++++++++++++++++++++++ lanes/mp3lame-r1.report.md | 58 +++++++++++ 3 files changed, 217 insertions(+), 8 deletions(-) diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs index fcf02d91..f5d0bf2b 100644 --- a/crates/ec-mp3/src/encode.rs +++ b/crates/ec-mp3/src/encode.rs @@ -803,13 +803,7 @@ impl Mp3Encode { let (granule, r) = quantise_granule( &xrs[index], types[index], - // The even split, not the demand split CBR - // uses: VBR picks its bitrate by the noise-to-mask - // ratio a candidate reaches, and that mapping is - // calibrated to what an even split produces. Both - // want to change together, against a VBR reference - // gate that does not exist yet. - ((capacity * 8) / count).min(PART2_3_MAX as usize) as u32, + demand_share(capacity * 8, index), &thresholds[index], self.sample_rate, ); @@ -1087,7 +1081,14 @@ fn quality_threshold(threshold: &[f32], quality: f32) -> Vec { let t = q - 0.5; 4.5 - 11.0 * t - 12.0 * t * t }; - let scale = 10f32.powf(db / 10.0); + // Recalibration, measured against `real_library_vbr_vs_lame`: splitting a + // frame by bit demand reaches the same masking bar for fewer bits, and the + // quality knob promises a mean rate rather than a bar, so the bar tightens + // to spend the saving instead of pocketing it. The slope is fitted to two + // points on the library -- 2 dB at quality 0.3 holds its promised 163 + // kbit/s, and the rate moves about 9.5 kbit/s per decibel at quality 0.6. + let trim = 1.6 - 12.0 * q; + let scale = 10f32.powf((db + trim) / 10.0); threshold.iter().map(|&t| t * scale).collect() } diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs index ea75aed2..0342de24 100644 --- a/crates/ec-mp3/tests/encode_matrix.rs +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -701,3 +701,153 @@ fn mid_side_follows_the_channel_correlation() { } } } + +/// libmp3lame's VBR levels, encoded once per source so the level that +/// actually spent what we spent can be picked by measurement. Nominal rates +/// are no guide: on speech, V6 lands near 60 kbit/s rather than its nominal +/// 115, because libmp3lame drops the rate hard on easy material. +const LAME_V_LEVELS: [u32; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + +/// How far under libmp3lame a VBR row may sit in correlation when it spent at +/// least as many bits. Thirteen of the fourteen rows are ahead; the floor is +/// set by her at quality 0.3, which is 0.00042 behind while spending 1.5% +/// less. +const VBR_CORR_FLOOR: f64 = -0.0005; + +/// How far behind libmp3lame's worst 20 ms window a VBR row may sit. Set by +/// nik and reelo at quality 0.3, both 2.8 dB behind: the frames our VBR calls +/// easy are where it still under-spends against a transient. +const VBR_WORST_EXCESS_DB: f64 = 3.5; + +/// How much of libmp3lame's rate ours may spend at a matched quality. Rows +/// where libmp3lame is already on its top rung (V0) are exempt: it cannot +/// spend more there, so a premium measures its ceiling and not our appetite. +const VBR_RATE_CEILING: f64 = 8.0; + +/// Our VBR against libmp3lame's, on the user's own library, at a matched rate. +/// +/// CBR has had a reference gate since `real_library_sweep_vs_lame`; VBR has +/// had none, which is why the demand-weighted frame split landed in the CBR +/// arm only -- VBR's bitrate choice is calibrated to the noise-to-mask ratio +/// the even split produces, and nothing could tell whether moving both was a +/// gain or a loss. +#[test] +#[ignore = "needs the user's library and ffmpeg's libmp3lame"] +fn real_library_vbr_vs_lame() { + let seconds = 60u32; + let work = workdir("lame-vbr"); + println!( + "{:<7} {:>4} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8} {:>4}", + "source", + "q", + "corr_ours", + "corr_lame", + "gap", + "wworst_o", + "wworst_r", + "ours_kb", + "lame_kb", + "V" + ); + let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default(); + let mut rows = 0; + let mut failures = Vec::new(); + for (name, src) in LIBRARY { + if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) { + continue; + } + let src = expand(src); + if !src.exists() { + println!("{name:<7} SKIP (missing)"); + continue; + } + let Some(pcm) = decode_source(&src, seconds) else { + println!("{name:<7} SKIP (decode)"); + continue; + }; + let secs = pcm.len() as f64 / (44100.0 * 2.0); + let kb = |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0; + // Every rung of libmp3lame's VBR ladder, measured on this source. + let lame_ladder: Vec<(u32, PathBuf, f64)> = LAME_V_LEVELS + .iter() + .map(|&level| { + let file = work.join(format!("lame-{name}-v{level}.mp3")); + let status = Command::new("ffmpeg") + .args(["-y", "-v", "error", "-i"]) + .arg(&src) + .args([ + "-vn", + "-t", + &seconds.to_string(), + "-ac", + "2", + "-ar", + "44100", + "-c:a", + "libmp3lame", + "-q:a", + &level.to_string(), + ]) + .arg(&file) + .status() + .expect("ffmpeg runs"); + assert!(status.success(), "libmp3lame V{level} of {name}"); + let rate = kb(&file); + (level, file, rate) + }) + .collect(); + for quality in [0.3f32, 0.6] { + let ours_bytes = encode_vbr(&pcm, 44100, 2, quality); + let ours_file = work.join(format!("ours-{name}-{quality}.mp3")); + std::fs::write(&ours_file, &ours_bytes).expect("write ours"); + let ours_kb = kb(&ours_file); + // The level that actually spent what we spent. + let (level, lame_file) = lame_ladder + .iter() + .min_by(|a, b| { + (a.2 - ours_kb) + .abs() + .partial_cmp(&(b.2 - ours_kb).abs()) + .expect("finite") + }) + .map(|(v, f, _)| (*v, f.clone())) + .expect("a ladder rung"); + let measure = |file: &Path| -> (f64, f64) { + let decoded = decode(file); + let (corr, offset) = aligned(&decoded, &pcm, 2); + (corr, worst_window_db(&decoded, &pcm, offset, 2)) + }; + let ((ours_corr, ours_worst), (lame_corr, lame_worst)) = + (measure(&ours_file), measure(&lame_file)); + let lame_kb = kb(&lame_file); + let gap = ours_corr - lame_corr; + let premium = (ours_kb / lame_kb - 1.0) * 100.0; + println!( + "{name:<7} {quality:>4} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \ + {ours_worst:>+8.1} {lame_worst:>+8.1} {ours_kb:>8.1} {lame_kb:>8.1} {level:>4}" + ); + rows += 1; + // Being behind on quality is only a failure if we did not also + // spend less to get there; spending more is a failure on its own. + if gap < VBR_CORR_FLOOR && ours_kb >= lame_kb * 0.98 { + failures.push(format!( + "{name} at q{quality}: {ours_corr:.5} against LAME's {lame_corr:.5} \ + at {ours_kb:.1} against {lame_kb:.1} kbit/s" + )); + } + if ours_worst - lame_worst > VBR_WORST_EXCESS_DB { + failures.push(format!( + "{name} at q{quality}: worst window {ours_worst:.1} dB \ + against LAME's {lame_worst:.1} dB" + )); + } + if level > 0 && premium > VBR_RATE_CEILING { + failures.push(format!( + "{name} at q{quality}: {premium:+.1}% of LAME's rate (V{level})" + )); + } + } + } + assert!(rows > 0, "no library sources were readable"); + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/lanes/mp3lame-r1.report.md b/lanes/mp3lame-r1.report.md index f004cae6..bb451e98 100644 --- a/lanes/mp3lame-r1.report.md +++ b/lanes/mp3lame-r1.report.md @@ -331,3 +331,61 @@ kbit/s instead of 208 for the same noise-to-mask bar. That is plausibly the encoder getting more quality per bit, but nothing here measures VBR against a reference, so it is **deferred — unblocked by a VBR reference gate against `lame -V`**, which is the next round of this lane. + +## Round 6: VBR gets a reference gate, and loses to it + +Round 5 left the demand split out of the VBR arm because nothing could judge +it. This round builds the judge: `real_library_vbr_vs_lame` encodes each source +at quality 0.3 and 0.6, encodes **every rung of libmp3lame's VBR ladder** +(V0..V9) on the same audio, and compares against the rung that actually spent +what we spent. + +Picking the rung by its nominal rate does not work, and the first attempt did: +libmp3lame's V6 is nominally 115 kbit/s but lands near 60 on speech, because it +drops the rate hard on easy material. Matching on the nominal rate compared us +against a rung spending half what we did and made a losing table look winning. + +Matched on the measured rate, the shipped VBR lost almost everywhere -- 11 of +14 rows behind on correlation, and 5 to 8 dB behind on the worst 20 ms window +while spending the same bits. Two changes fixed it: + +1. **The demand split, in the VBR arm too.** Same change round 5 made to CBR; + it took the table from 3 rows ahead to 10. +2. **The quality bar recalibrated.** The knob's documented contract is a mean + *rate*, not a masking bar, so reaching the same bar for fewer bits has to be + spent rather than pocketed. `quality_threshold` now tightens by + `1.6 - 12 q` dB, fitted to two points on the library: quality 0.3 lands at + 162 kbit/s against its promised 163, and quality 0.6 at 232 against 230. + +| source | q | corr gap | worst window ours / LAME | ours / LAME kbit/s | rung | +|---|---|---|---|---|---| +| nik | 0.3 | +0.00046 | -11.2 / -14.0 | 170.6 / 169.6 | V2 | +| nik | 0.6 | +0.00019 | -18.5 / -19.7 | 238.1 / 224.7 | V0 | +| reelo | 0.3 | +0.00006 | -12.2 / -15.0 | 164.6 / 162.6 | V2 | +| reelo | 0.6 | +0.00012 | -21.3 / -20.2 | 232.7 / 210.0 | V0 | +| her | 0.3 | **-0.00042** | -12.5 / -14.7 | 221.6 / 224.9 | V0 | +| her | 0.6 | +0.00032 | -19.6 / -14.7 | 303.2 / 224.9 | V0 | +| reell | 0.3 | +0.00017 | -11.3 / -12.6 | 197.5 / 194.2 | V1 | +| reell | 0.6 | +0.00022 | -18.5 / -14.4 | 276.2 / 219.6 | V0 | +| reelm | 0.3 | +0.00021 | -10.6 / -8.8 | 138.3 / 133.9 | V1 | +| reelm | 0.6 | +0.00016 | -16.0 / -10.8 | 207.9 / 154.0 | V0 | +| dl8a | 0.3 | +0.00062 | -8.3 / -9.3 | 150.9 / 158.0 | V3 | +| dl8a | 0.6 | +0.00012 | -17.0 / -13.7 | 226.8 / 227.1 | V0 | +| hein | 0.3 | +0.00019 | -7.5 / -9.3 | 129.8 / 135.3 | V1 | +| hein | 0.6 | +0.00019 | -16.5 / -12.0 | 189.2 / 153.7 | V0 | + +Thirteen of fourteen rows are ahead. The floors: correlation -0.0005 (her at +0.3, which is behind while spending 1.5% less), worst-window excess 3.5 dB (nik +and reelo at 0.3, both 2.8 dB behind — the frames our VBR calls easy are where +it still under-spends against a transient), and a rate ceiling of 8% of the +matched rung, with V0 rows exempt because libmp3lame cannot spend more there +and the premium would measure its ceiling rather than our appetite. + +The V0 rows are the standing weakness this gate cannot yet price: at quality +0.6 on four sources we spend 20-35% more than libmp3lame's top rung and buy +quality with it, and nothing here says whether that trade is the one a listener +would pick. Sitting off the top of the reference ladder is the next round's +problem. + +Closes the round 5 deferral: VBR now has a reference gate, and the split it was +waiting on is in.