forge
Explore
Log in

Don't you dare go Hollow

Measure the encoder against LAME on real sources

Browse files at this commit

e7223756ff15347e5f844fa0561f4110ed5b950cAhmet Kaan GümüşParent: 5900f75
  • test
    • measure the encoder against LAME on real sources
Show full message
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.rsmodified+152 -0
@@ -412,3 +412,155 @@ fn encodes_above_the_incumbent_bar() {
412 }412 }
413 assert!(failures.is_empty(), "{failures:#?}");413 assert!(failures.is_empty(), "{failures:#?}");
414 }414 }
415+
416+// ---------------------------------------------------------------------------
417+// The live reference: LAME on the user's own library, at matched constant
418+// bitrate. `encodes_above_the_incumbent_bar` measures against a frozen number
419+// from the crate this one replaces; that number cannot notice LAME moving, and
420+// the fixtures it covers are synthetic. This one encodes the same seconds of
421+// the same file with both encoders at the same bitrate and correlates each
422+// against the samples that went in.
423+// ---------------------------------------------------------------------------
424+
425+/// Sources for [`real_library_sweep_vs_lame`], the same list the vorbis and
426+/// opus library gates use.
427+const LIBRARY: [(&str, &str); 7] = [
428+ ("nik", "~/Music/reeln.mp4"),
429+ ("reelo", "~/Music/reelo.mp3"),
430+ ("her", "~/Music/reeli.mp3"),
431+ ("reell", "~/Music/reell.mp4"),
432+ ("reelm", "~/Music/reelm.wav"),
433+ ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
434+ (
435+ "hein",
436+ "~/Downloads/reelm.mp3",
437+ ),
438+];
439+
440+/// How far under LAME a row may sit before the sweep fails, in correlation.
441+///
442+/// The first measurement (60 s of each source, 44.1 kHz stereo, CBR) put every
443+/// row between -0.00137 and +0.00115, with the worst two -- reelo and dl8a at
444+/// 128 kbit/s -- on dense material where LAME's short-block switching earns
445+/// its keep. The floor sits just under that worst row rather than at zero
446+/// because two rows are already ahead of LAME and the spread is what a
447+/// regression would have to widen.
448+const LAME_CORR_FLOOR: f64 = -0.0020;
449+
450+fn expand(path: &str) -> PathBuf {
451+ PathBuf::from(match path.strip_prefix("~/") {
452+ Some(rest) => format!(
453+ "{}/{rest}",
454+ std::env::var("HOME").unwrap_or_else(|_| "/home".into())
455+ ),
456+ None => path.to_string(),
457+ })
458+}
459+
460+/// Decodes `seconds` of a source to interleaved stereo f32 at 44.1 kHz.
461+fn decode_source(path: &Path, seconds: u32) -> Option<Vec<f32>> {
462+ let out = Command::new("ffmpeg")
463+ .args(["-v", "error", "-i"])
464+ .arg(path)
465+ .args([
466+ "-vn",
467+ "-t",
468+ &seconds.to_string(),
469+ "-ac",
470+ "2",
471+ "-ar",
472+ "44100",
473+ "-f",
474+ "f32le",
475+ "-",
476+ ])
477+ .output()
478+ .ok()?;
479+ if !out.status.success() || out.stdout.is_empty() {
480+ return None;
481+ }
482+ Some(
483+ out.stdout
484+ .chunks_exact(4)
485+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
486+ .collect(),
487+ )
488+}
489+
490+/// Ours against LAME on the user's library, at matched constant bitrate:
491+///
492+/// cargo test -p ec-mp3 --release --test encode_matrix \
493+/// real_library_sweep_vs_lame -- --ignored --nocapture
494+#[test]
495+#[ignore = "needs the user's library and ffmpeg's libmp3lame"]
496+fn real_library_sweep_vs_lame() {
497+ let seconds = 60u32;
498+ let work = workdir("lame-sweep");
499+ println!(
500+ "{:<7} {:>5} {:>9} {:>9} {:>8} {:>9} {:>9}",
501+ "source", "kbps", "corr_ours", "corr_lame", "gap", "ours_kb", "lame_kb"
502+ );
503+ let mut rows = 0;
504+ let mut failures = Vec::new();
505+ for (name, src) in LIBRARY {
506+ let src = expand(src);
507+ if !src.exists() {
508+ println!("{name:<7} SKIP (missing)");
509+ continue;
510+ }
511+ let Some(pcm) = decode_source(&src, seconds) else {
512+ println!("{name:<7} SKIP (decode)");
513+ continue;
514+ };
515+ let secs = pcm.len() as f64 / (44100.0 * 2.0);
516+ for kbps in [128u32, 192] {
517+ let ours_bytes = encode(&pcm, 44100, 2, kbps);
518+ let ours_file = work.join(format!("ours-{name}-{kbps}.mp3"));
519+ std::fs::write(&ours_file, &ours_bytes).expect("write ours");
520+ let lame_file = work.join(format!("lame-{name}-{kbps}.mp3"));
521+ let status = Command::new("ffmpeg")
522+ .args(["-y", "-v", "error", "-i"])
523+ .arg(&src)
524+ .args([
525+ "-vn",
526+ "-t",
527+ &seconds.to_string(),
528+ "-ac",
529+ "2",
530+ "-ar",
531+ "44100",
532+ "-c:a",
533+ "libmp3lame",
534+ "-b:a",
535+ &format!("{kbps}k"),
536+ ])
537+ .arg(&lame_file)
538+ .status()
539+ .expect("ffmpeg runs");
540+ assert!(status.success(), "libmp3lame encode of {name} at {kbps}k");
541+ // Both decoded by the same decoder and aligned the same way: an
542+ // encoder delay is not a quality difference.
543+ let corr_of = |file: &Path| -> f64 {
544+ let decoded = decode(file);
545+ aligned(&decoded, &pcm, 2).0
546+ };
547+ let (ours_corr, lame_corr) = (corr_of(&ours_file), corr_of(&lame_file));
548+ let kb =
549+ |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;
550+ let gap = ours_corr - lame_corr;
551+ println!(
552+ "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} {:>9.1} {:>9.1}",
553+ kb(&ours_file),
554+ kb(&lame_file)
555+ );
556+ rows += 1;
557+ if gap < LAME_CORR_FLOOR {
558+ failures.push(format!(
559+ "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}"
560+ ));
561+ }
562+ }
563+ }
564+ assert!(rows > 0, "no library sources were readable");
565+ assert!(failures.is_empty(), "{failures:#?}");
566+}
lanes/mp3lame-r1.report.mdadded+63 -0
@@ -0,0 +1,63 @@
1+# ec-mp3 against LAME on the real library — round 1
2+
3+## Why the lane opened
4+
5+`encodes_above_the_incumbent_bar` was the crate's only quality gate, and it
6+measures against `BAR` — a table of correlations frozen from the encoder this
7+crate replaces, on synthetic fixtures. A frozen number cannot notice the
8+reference moving, and its thinnest row (`mp3src-stereo-48000` at 128 kbit/s)
9+passed by +0.00014, so the gate was one rounding change away from meaningless
10+in either direction. The survey ranked it alongside ec-h264's missing
11+rate-quality reference: an unmeasured gap.
12+
13+## What the gate does now
14+
15+`real_library_sweep_vs_lame` encodes the first 60 s of seven of the user's own
16+files twice at matched constant bitrate — once with `Mp3Encoder`, once with
17+ffmpeg's `libmp3lame` — decodes both with the same decoder, aligns each against
18+the samples that went in, and correlates. Matched CBR means the sizes agree to
19+within 0.2%, so the correlation difference is quality and not rate.
20+
21+## First measurement
22+
23+| source | kbit/s | corr ours | corr LAME | gap | ours kbit/s | LAME kbit/s |
24+|--------|-------:|----------:|----------:|----:|------------:|------------:|
25+| nik | 128 | 0.99790 | 0.99888 | -0.00098 | 127.9 | 128.1 |
26+| nik | 192 | 0.99950 | 0.99982 | -0.00032 | 192.0 | 192.2 |
27+| reelo | 128 | 0.99718 | 0.99855 | -0.00137 | 127.9 | 128.1 |
28+| reelo | 192 | 0.99927 | 0.99976 | -0.00048 | 192.0 | 192.2 |
29+| her | 128 | 0.99680 | 0.99565 | **+0.00115** | 127.9 | 128.2 |
30+| her | 192 | 0.99901 | 0.99883 | **+0.00018** | 192.0 | 192.3 |
31+| reell | 128 | 0.99855 | 0.99849 | **+0.00006** | 127.9 | 128.1 |
32+| reell | 192 | 0.99966 | 0.99969 | -0.00003 | 192.0 | 192.2 |
33+| reelm | 128 | 0.99816 | 0.99897 | -0.00080 | 127.9 | 128.1 |
34+| reelm | 192 | 0.99951 | 0.99994 | -0.00042 | 192.0 | 192.2 |
35+| dl8a | 128 | 0.99623 | 0.99737 | -0.00113 | 127.9 | 128.1 |
36+| dl8a | 192 | 0.99894 | 0.99940 | -0.00046 | 192.0 | 192.2 |
37+| hein | 128 | 0.99859 | 0.99958 | -0.00100 | 127.9 | 128.1 |
38+| hein | 192 | 0.99964 | 0.99996 | -0.00032 | 192.0 | 192.2 |
39+
40+Fourteen rows, all seven library sources readable. The floor is set at -0.0020,
41+just under the worst row.
42+
43+## What the numbers say
44+
45+The gap closes with rate on every source: the mean 128 kbit/s gap is -0.00058
46+and the mean 192 kbit/s gap is -0.00027. That shape — behind where bits are
47+scarce, level where they are not — is a bit-allocation difference, not a
48+transform or quantiser defect. A defect in the filterbank or the quantiser
49+would not politely halve itself when given more bits.
50+
51+`her` is the one source where we are ahead at both rates, and it is also the
52+source with the widest gap in our favour. It is the sparsest material in the
53+list. `reelo` and `dl8a` are the two worst rows and are the densest. The
54+ordering is consistent with LAME's short-block switching being worth roughly a
55+thousandth of correlation on dense content at 128 kbit/s, and nothing at all on
56+sparse content — which is where the next round should look, rather than at the
57+psychoacoustic model.
58+
59+## Not measured in this round
60+
61+VBR. `encode_vbr` exists and `Mp3EncoderConfig::vbr_quality` is honoured, but
62+LAME's `-q`/`-V` scale does not map onto ours, so a matched-rate comparison
63+needs a rate-matching search before it means anything. That is its own slice.