From e7223756ff15347e5f844fa0561f4110ed5b950c 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 19:38:13 +0300 Subject: [PATCH] test(mp3): measure the encoder against LAME on real sources The crate's only quality gate compared correlations against a table frozen from the encoder this one replaces, measured on synthetic fixtures. A frozen number cannot notice the reference moving, and its thinnest row passed by 0.00014. This adds a live one. `real_library_sweep_vs_lame` encodes the same sixty seconds of the same file twice at matched constant bitrate -- once with `Mp3Encoder`, once with libmp3lame -- decodes both through the same decoder, aligns each against the samples that went in, and correlates. Matched CBR puts the two sizes within 0.2% of each other, so what is left is quality. Fourteen rows across seven sources land between -0.00137 and +0.00115, and the floor is set just under the worst of them. The gap halves from 128 to 192 kbit/s on every source and is positive on the sparsest material, which points at bit allocation on dense content rather than at the filterbank. --- crates/ec-mp3/tests/encode_matrix.rs | 152 +++++++++++++++++++++++++++ lanes/mp3lame-r1.report.md | 63 +++++++++++ 2 files changed, 215 insertions(+) create mode 100644 lanes/mp3lame-r1.report.md diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs index dd290911..3ac5377f 100644 --- a/crates/ec-mp3/tests/encode_matrix.rs +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -412,3 +412,155 @@ fn encodes_above_the_incumbent_bar() { } assert!(failures.is_empty(), "{failures:#?}"); } + +// --------------------------------------------------------------------------- +// The live reference: LAME on the user's own library, at matched constant +// bitrate. `encodes_above_the_incumbent_bar` measures against a frozen number +// from the crate this one replaces; that number cannot notice LAME moving, and +// the fixtures it covers are synthetic. This one encodes the same seconds of +// the same file with both encoders at the same bitrate and correlates each +// against the samples that went in. +// --------------------------------------------------------------------------- + +/// Sources for [`real_library_sweep_vs_lame`], the same list the vorbis and +/// opus library gates use. +const LIBRARY: [(&str, &str); 7] = [ + ("nik", "~/Music/reeln.mp4"), + ("reelo", "~/Music/reelo.mp3"), + ("her", "~/Music/reeli.mp3"), + ("reell", "~/Music/reell.mp4"), + ("reelm", "~/Music/reelm.wav"), + ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), + ( + "hein", + "~/Downloads/reelm.mp3", + ), +]; + +/// 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 +/// row between -0.00137 and +0.00115, with the worst two -- reelo and dl8a at +/// 128 kbit/s -- on dense material where LAME's short-block switching earns +/// its keep. The floor sits just under that worst row rather than at zero +/// because two rows are already ahead of LAME and the spread is what a +/// regression would have to widen. +const LAME_CORR_FLOOR: f64 = -0.0020; + +fn expand(path: &str) -> PathBuf { + PathBuf::from(match path.strip_prefix("~/") { + Some(rest) => format!( + "{}/{rest}", + std::env::var("HOME").unwrap_or_else(|_| "/home".into()) + ), + None => path.to_string(), + }) +} + +/// Decodes `seconds` of a source to interleaved stereo f32 at 44.1 kHz. +fn decode_source(path: &Path, seconds: u32) -> Option> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-vn", + "-t", + &seconds.to_string(), + "-ac", + "2", + "-ar", + "44100", + "-f", + "f32le", + "-", + ]) + .output() + .ok()?; + if !out.status.success() || out.stdout.is_empty() { + return None; + } + Some( + out.stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(), + ) +} + +/// Ours against LAME on the user's library, at matched constant bitrate: +/// +/// cargo test -p ec-mp3 --release --test encode_matrix \ +/// real_library_sweep_vs_lame -- --ignored --nocapture +#[test] +#[ignore = "needs the user's library and ffmpeg's libmp3lame"] +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" + ); + let mut rows = 0; + let mut failures = Vec::new(); + for (name, src) in LIBRARY { + 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); + for kbps in [128u32, 192] { + let ours_bytes = encode(&pcm, 44100, 2, kbps); + let ours_file = work.join(format!("ours-{name}-{kbps}.mp3")); + std::fs::write(&ours_file, &ours_bytes).expect("write ours"); + let lame_file = work.join(format!("lame-{name}-{kbps}.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", + "-b:a", + &format!("{kbps}k"), + ]) + .arg(&lame_file) + .status() + .expect("ffmpeg runs"); + 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 decoded = decode(file); + aligned(&decoded, &pcm, 2).0 + }; + let (ours_corr, lame_corr) = (corr_of(&ours_file), corr_of(&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}", + kb(&ours_file), + kb(&lame_file) + ); + rows += 1; + if gap < LAME_CORR_FLOOR { + failures.push(format!( + "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}" + )); + } + } + } + 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 new file mode 100644 index 00000000..3876490e --- /dev/null +++ b/lanes/mp3lame-r1.report.md @@ -0,0 +1,63 @@ +# ec-mp3 against LAME on the real library — round 1 + +## Why the lane opened + +`encodes_above_the_incumbent_bar` was the crate's only quality gate, and it +measures against `BAR` — a table of correlations frozen from the encoder this +crate replaces, on synthetic fixtures. A frozen number cannot notice the +reference moving, and its thinnest row (`mp3src-stereo-48000` at 128 kbit/s) +passed by +0.00014, so the gate was one rounding change away from meaningless +in either direction. The survey ranked it alongside ec-h264's missing +rate-quality reference: an unmeasured gap. + +## What the gate does now + +`real_library_sweep_vs_lame` encodes the first 60 s of seven of the user's own +files twice at matched constant bitrate — once with `Mp3Encoder`, once with +ffmpeg's `libmp3lame` — decodes both with the same decoder, aligns each against +the samples that went in, and correlates. Matched CBR means the sizes agree to +within 0.2%, so the correlation difference is quality and not rate. + +## First measurement + +| source | kbit/s | corr ours | corr LAME | gap | ours kbit/s | LAME kbit/s | +|--------|-------:|----------:|----------:|----:|------------:|------------:| +| nik | 128 | 0.99790 | 0.99888 | -0.00098 | 127.9 | 128.1 | +| nik | 192 | 0.99950 | 0.99982 | -0.00032 | 192.0 | 192.2 | +| reelo | 128 | 0.99718 | 0.99855 | -0.00137 | 127.9 | 128.1 | +| reelo | 192 | 0.99927 | 0.99976 | -0.00048 | 192.0 | 192.2 | +| her | 128 | 0.99680 | 0.99565 | **+0.00115** | 127.9 | 128.2 | +| her | 192 | 0.99901 | 0.99883 | **+0.00018** | 192.0 | 192.3 | +| reell | 128 | 0.99855 | 0.99849 | **+0.00006** | 127.9 | 128.1 | +| reell | 192 | 0.99966 | 0.99969 | -0.00003 | 192.0 | 192.2 | +| reelm | 128 | 0.99816 | 0.99897 | -0.00080 | 127.9 | 128.1 | +| reelm | 192 | 0.99951 | 0.99994 | -0.00042 | 192.0 | 192.2 | +| dl8a | 128 | 0.99623 | 0.99737 | -0.00113 | 127.9 | 128.1 | +| dl8a | 192 | 0.99894 | 0.99940 | -0.00046 | 192.0 | 192.2 | +| hein | 128 | 0.99859 | 0.99958 | -0.00100 | 127.9 | 128.1 | +| hein | 192 | 0.99964 | 0.99996 | -0.00032 | 192.0 | 192.2 | + +Fourteen rows, all seven library sources readable. The floor is set at -0.0020, +just under the worst row. + +## What the numbers say + +The gap closes with rate on every source: the mean 128 kbit/s gap is -0.00058 +and the mean 192 kbit/s gap is -0.00027. That shape — behind where bits are +scarce, level where they are not — is a bit-allocation difference, not a +transform or quantiser defect. A defect in the filterbank or the quantiser +would not politely halve itself when given more bits. + +`her` is the one source where we are ahead at both rates, and it is also the +source with the widest gap in our favour. It is the sparsest material in the +list. `reelo` and `dl8a` are the two worst rows and are the densest. The +ordering is consistent with LAME's short-block switching being worth roughly a +thousandth of correlation on dense content at 128 kbit/s, and nothing at all on +sparse content — which is where the next round should look, rather than at the +psychoacoustic model. + +## Not measured in this round + +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.