From 4ca031182b0ef0672a6f3f9ef7ddbd938bc5830f 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 20:22:06 +0300 Subject: [PATCH] fix(mp3): wake the block switcher, and measure what it is for The switcher decided a granule was a transient when the next granule's total energy grew eightfold. A granule is 13 ms, and music meets that about once a minute: counting block types in our own coded streams found one short granule in 9196, against libmp3lame's 88 over the same audio. It has been dead code since it was written. Sweeping the constant over 2 through 32 moved whole-file correlation by 0.00004, which is the second half of the finding: the crate's quality gate cannot see pre-echo at all. A few milliseconds of noise smeared backwards before an attack disappears into a minute of correlation, and a gate like that would have accepted the switcher being deleted. So the sweep now also reports the worst 20 ms error-to-signal ratio, for ours and for the reference, skipping windows under -60 dBFS. Against that metric the constant is not flat: at the shipped 8.0 one window of a real file carries more error energy than signal (+1.1 dB), the curve is flat from 1.6 to 4, and the cliff sits between 4 and 8. The shipped value was just past the edge of it. 4.0 lands, at the cheap end of the flat part. The new gate's floor is set from the measurement and the measurement is unflattering: we lead the reference in the worst window on all four music sources and trail it on all three speech ones, worst by 14 dB. On those, the worst window barely improves when the bitrate rises by half, so the limit is the masking model rather than the bits. That is the next round. --- crates/ec-mp3/src/encode.rs | 18 +++++- crates/ec-mp3/tests/encode_matrix.rs | 82 +++++++++++++++++++++++-- lanes/mp3lame-r1.report.md | 89 ++++++++++++++++++++++++++++ 3 files changed, 182 insertions(+), 7 deletions(-) diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs index 518d3aff..f4fd9e33 100644 --- a/crates/ec-mp3/src/encode.rs +++ b/crates/ec-mp3/src/encode.rs @@ -630,7 +630,23 @@ impl Mp3Encode { // the resolution a long block would have spent on the attack // itself, and there is no pre-echo to hide when nothing // precedes it. - let attack = here > 1e-9 && next > here * 8.0 + 1e-6; + // How much louder the next granule has to be to count as an + // attack. Swept against the worst 20 ms error-to-signal ratio + // on real music (`real_library_sweep_vs_lame`), because + // whole-file correlation cannot see pre-echo at all: + // + // ratio 1.3 1.6 2 3 4 8 + // dl8a@128 -2.3 -3.3 -3.3 -3.3 -3.3 +1.1 dB + // dl8a@192 -6.7 -6.7 -6.7 -7.8 -7.8 -4.2 dB + // + // Flat from 1.6 to 4 and then a cliff: at 8 a whole granule + // has to grow eightfold in total energy, which music does + // about once a minute -- one short granule in 9196, against + // libmp3lame's 88 over the same audio. Below 1.6 the extra + // short blocks start costing correlation without buying any + // more of the worst window back, so 4 sits at the cheap end + // of the flat part. + let attack = here > 1e-9 && next > here * 4.0 + 1e-6; let block = match self.previous_block[ch] { 1 => 2, 2 if attack => 2, diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs index 3ac5377f..ed758453 100644 --- a/crates/ec-mp3/tests/encode_matrix.rs +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -127,6 +127,42 @@ fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { best } +/// Worst short-window error energy, relative to the source, over the file. +/// +/// Whole-file correlation cannot see pre-echo: quantisation noise smeared +/// backwards across a 576-sample granule before an attack is a few +/// milliseconds of audible hash inside a minute of otherwise clean signal, and +/// integrating over the minute divides it away. Measured on this crate, going +/// from one short block per 9196 granules to 526 of them moved whole-file +/// correlation by 0.00004 -- in the wrong direction -- while changing exactly +/// the thing short blocks exist to fix. So the sweep also reports the worst +/// window: error energy over source energy, in dB, over 20 ms windows, +/// which is the scale a transient's pre-echo lives on. +fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) -> f64 { + let window = 20 * 44100 / 1000 * channels; + let skip = 1152 * channels; + let n = (got.len() - offset).min(want.len()); + let mut worst = f64::MIN; + let mut start = skip; + while start + window + skip <= n { + let (mut err, mut sig) = (0.0f64, 0.0f64); + for i in start..start + window { + let d = f64::from(got[offset + i]) - f64::from(want[i]); + err += d * d; + sig += f64::from(want[i]) * f64::from(want[i]); + } + // A window with no signal in it has no pre-echo to hide, and its + // ratio would be meaningless; the -60 dBFS gate skips digital silence + // and the fade-ins around it. + if sig / window as f64 > 1e-6 { + let db = 10.0 * (err / sig.max(1e-30)).log10(); + worst = worst.max(db); + } + start += window; + } + worst +} + fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec { let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { bitrate_kbps: kbps, @@ -437,6 +473,16 @@ const LIBRARY: [(&str, &str); 7] = [ ), ]; +/// How much worse than LAME a row's worst 20 ms window may be, in dB. +/// +/// The floor is set from the measurement and the measurement is bad: hein at +/// 192 kbit/s is 14.0 dB behind, and hein and reelm are the two spoken-word +/// sources. LAME's worst window improves by 12 dB from 128 to 192 kbit/s on +/// that file while ours improves by 5, which says our limit there is the +/// masking model rather than the bitrate. That is the next round; the floor +/// exists so it cannot quietly get worse first. +const WORST_WINDOW_EXCESS_DB: f64 = 15.0; + /// How far under LAME a row may sit before the sweep fails, in correlation. /// /// The first measurement (60 s of each source, 44.1 kHz stereo, CBR) put every @@ -497,12 +543,27 @@ fn real_library_sweep_vs_lame() { let seconds = 60u32; let work = workdir("lame-sweep"); println!( - "{:<7} {:>5} {:>9} {:>9} {:>8} {:>9} {:>9}", - "source", "kbps", "corr_ours", "corr_lame", "gap", "ours_kb", "lame_kb" + "{:<7} {:>5} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8}", + "source", + "kbps", + "corr_ours", + "corr_lame", + "gap", + "wworst_o", + "wworst_r", + "ours_kb", + "lame_kb" ); let mut rows = 0; let mut failures = Vec::new(); + // `EC_MP3_SWEEP_ONLY=reelo,dl8a` narrows the sweep to named sources, so a + // constant can be swept against the rows it moves without paying for the + // rows it does not. + let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default(); 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)"); @@ -540,16 +601,19 @@ fn real_library_sweep_vs_lame() { assert!(status.success(), "libmp3lame encode of {name} at {kbps}k"); // Both decoded by the same decoder and aligned the same way: an // encoder delay is not a quality difference. - let corr_of = |file: &Path| -> f64 { + let measure = |file: &Path| -> (f64, f64) { let decoded = decode(file); - aligned(&decoded, &pcm, 2).0 + let (corr, offset) = aligned(&decoded, &pcm, 2); + (corr, worst_window_db(&decoded, &pcm, offset, 2)) }; - let (ours_corr, lame_corr) = (corr_of(&ours_file), corr_of(&lame_file)); + let ((ours_corr, ours_worst), (lame_corr, lame_worst)) = + (measure(&ours_file), measure(&lame_file)); let kb = |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0; let gap = ours_corr - lame_corr; println!( - "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} {:>9.1} {:>9.1}", + "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \ + {ours_worst:>+8.1} {lame_worst:>+8.1} {:>8.1} {:>8.1}", kb(&ours_file), kb(&lame_file) ); @@ -559,6 +623,12 @@ fn real_library_sweep_vs_lame() { "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}" )); } + if ours_worst - lame_worst > WORST_WINDOW_EXCESS_DB { + failures.push(format!( + "{name} at {kbps} kbit/s: worst window {ours_worst:.1} dB \ + against LAME's {lame_worst:.1} dB" + )); + } } } assert!(rows > 0, "no library sources were readable"); diff --git a/lanes/mp3lame-r1.report.md b/lanes/mp3lame-r1.report.md index 3876490e..a06c3a6f 100644 --- a/lanes/mp3lame-r1.report.md +++ b/lanes/mp3lame-r1.report.md @@ -61,3 +61,92 @@ psychoacoustic model. VBR. `encode_vbr` exists and `Mp3EncoderConfig::vbr_quality` is honoured, but LAME's `-q`/`-V` scale does not map onto ours, so a matched-rate comparison needs a rate-matching search before it means anything. That is its own slice. + +## Round 2: the block switcher was inert, and the gate could not see it + +The 128-versus-192 shape pointed at bit allocation, and the first constant on +that path is the one that decides a granule is a transient: +`next_granule_energy > here * 8.0`, on whole-granule totals. Sweeping it over +2, 4, 8, 16, 32 moved the correlation of the three worst sources by 0.00004 +across the whole range, and 8 through 32 were bit-identical. + +Counting block types in the coded streams explains why, and turns up something +worse than a mistuned constant: + +| stream | long | start | short | stop | +|--------|-----:|------:|------:|-----:| +| ours, reelo @128 | 9193 | 1 | **1** | 1 | +| libmp3lame, same | 8988 | 58 | **88** | 58 | +| ours, her @128 | 9190 | 2 | **2** | 2 | +| libmp3lame, same | 8948 | 72 | **102** | 70 | + +One short granule in 9196. A granule is 576 samples, 13 ms; requiring its +*total* energy to grow eightfold is a condition music meets about once a +minute. The switcher has been dead code since it was written. + +Forcing it awake at ratio 2 produces 526 short granules and moves whole-file +correlation by 0.00004, in the wrong direction. That is the finding: **the +crate's quality gate is structurally blind to the thing short blocks exist to +fix.** Pre-echo is a few milliseconds of noise smeared backwards before an +attack; correlating over a minute divides it away. A gate like that would have +accepted the switcher being deleted outright. + +### The metric the gate was missing + +`worst_window_db` now reports the worst 20 ms error-to-signal ratio in each +file, for ours and for LAME, skipping windows under -60 dBFS so silence does +not produce a ratio out of nothing. Against it the constant is not flat at all: + +| ratio | 1.3 | 1.6 | 2 | 3 | 4 | 8 | +|-------|----:|----:|--:|--:|--:|--:| +| dl8a @128 | -2.3 | -3.3 | -3.3 | -3.3 | -3.3 | **+1.1** | +| dl8a @192 | -6.7 | -6.7 | -6.7 | -7.8 | -7.8 | **-4.2** | + +At the shipped value one 20 ms window of dl8a carries more error energy than +signal. The curve is flat from 1.6 to 4 and falls off a cliff between 4 and 8, +so the shipped 8.0 sat just past the edge of a cliff nothing could see. Below +1.6 the extra short blocks cost correlation without buying back any more of the +worst window. **4.0 lands**, at the cheap end of the flat part. + +## Where the lane stands after round 2 + +| source | kbit/s | corr ours | corr LAME | gap | worst 20 ms ours | worst LAME | +|--------|-------:|----------:|----------:|----:|-----------------:|-----------:| +| nik | 128 | 0.99789 | 0.99888 | -0.00099 | -11.4 | -11.2 | +| nik | 192 | 0.99950 | 0.99982 | -0.00032 | -17.7 | -17.2 | +| reelo | 128 | 0.99717 | 0.99855 | -0.00138 | -10.3 | -9.3 | +| reelo | 192 | 0.99927 | 0.99976 | -0.00049 | -16.3 | -16.1 | +| her | 128 | 0.99680 | 0.99565 | +0.00115 | -9.8 | -5.4 | +| her | 192 | 0.99901 | 0.99883 | +0.00018 | -14.7 | -11.1 | +| reell | 128 | 0.99855 | 0.99849 | +0.00006 | -9.3 | -6.1 | +| reell | 192 | 0.99966 | 0.99969 | -0.00003 | -15.2 | -11.7 | +| reelm | 128 | 0.99815 | 0.99897 | -0.00082 | -1.5 | -2.0 | +| reelm | 192 | 0.99951 | 0.99994 | -0.00042 | **-3.4** | **-13.2** | +| dl8a | 128 | 0.99625 | 0.99737 | -0.00111 | -3.3 | -6.0 | +| dl8a | 192 | 0.99894 | 0.99940 | -0.00046 | -7.8 | -12.2 | +| hein | 128 | 0.99858 | 0.99958 | -0.00101 | **-0.1** | **-7.6** | +| hein | 192 | 0.99964 | 0.99996 | -0.00032 | **-5.4** | **-19.4** | + +We are ahead of LAME in the worst window on all four music sources and behind +on all three where the material is speech or speech-dominated. The tell is what +happens between the two rates: on hein, LAME's worst window improves by 11.8 dB +for 50% more bits and ours improves by 5.3. A worst window that will not +improve when handed more bits is not short of bits. It is the masking model +letting a band go, or the distortion loop declining to buy it back. + +## Round 3, named + +Three candidates, in order of what the round-2 evidence points at: + +1. The distortion loop's stop conditions -- `for _round in 0..20`, three bands + amplified per round, and the `spent * 20 > target_bits * 19` budget break. + The comment on that break already admits it is a corner cut against the ISO + outer loop, and a budget break is exactly what would cap the worst window + while bits go unspent. +2. The masking offset, `6.0 + 15.0 * (1.0 - flatness)` dB. Speech is the + material whose flatness estimate a 1024-point FFT gets most wrong. +3. The spreading leaks, 0.0032 upward and 0.1 downward, and the absolute + threshold's `1.0 + 400.0 * (rel - 0.35)^2` shape. + +None of the three has been swept. All of them predate the only metric that can +price them.