forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5a2f5efTahinli3 months ago1409 commits

encode_matrix.rs853 lines, 32.2 KiBHistoryRawDownload
1//! Our encoder measured the only way a lossy one can be: encode, decode the
2//! result with ffmpeg, correlate against the samples that went in.
3//!
4//! The bar is the incumbent MP3 encoder this crate replaces, 0.6.1, measured on
5//! the same fixtures and the same metric (see `BAR`, and
6//! `scripts/mp3-incumbent-bar.md` for how those numbers were produced).
7//!
8//! Run the table:
9//! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig};
15
16/// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this
17/// same alignment and metric (its own encoder, ffmpeg's decoder). The tone
18/// fixtures reach 1.0 on both encoders and so cannot separate them; the
19/// `mp3src-*` material — glide, broadband noise and a click every half second —
20/// is what does.
21const BAR: [(&str, [f64; 3]); 4] = [
22 ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]),
23 ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]),
24 ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]),
25 ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]),
26];
27const BITRATES: [u32; 3] = [128, 192, 320];
28
29/// The incumbent's number for this fixture and bitrate. Fixtures it was not
30/// measured on (the tones, which both encoders code perfectly) fall back to its
31/// worst result at that rate.
32fn bar_for(name: &str, kbps: u32) -> f64 {
33 let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0);
34 for (fixture, values) in BAR {
35 if name.starts_with(fixture) {
36 return values[index];
37 }
38 }
39 BAR.iter()
40 .map(|(_, v)| v[index])
41 .fold(f64::INFINITY, f64::min)
42}
43
44fn fixtures() -> PathBuf {
45 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
46}
47
48fn workdir(test: &str) -> PathBuf {
49 let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));
50 std::fs::create_dir_all(&dir).expect("create work dir");
51 dir
52}
53
54/// Reads a WAV fixture as interleaved f32 plus its rate and channel count.
55fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
56 let out = Command::new("ffmpeg")
57 .args(["-v", "error", "-i"])
58 .arg(path)
59 .args(["-f", "f32le", "-"])
60 .output()
61 .ok()?;
62 if !out.status.success() {
63 return None;
64 }
65 let samples = out
66 .stdout
67 .chunks_exact(4)
68 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
69 .collect();
70 let probe = Command::new("ffprobe")
71 .args([
72 "-v",
73 "error",
74 "-select_streams",
75 "a:0",
76 "-show_entries",
77 "stream=channels,sample_rate",
78 "-of",
79 "default=noprint_wrappers=1",
80 ])
81 .arg(path)
82 .output()
83 .ok()?;
84 let text = String::from_utf8_lossy(&probe.stdout);
85 let field = |key: &str| {
86 text.lines()
87 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
88 .and_then(|v| v.trim().parse::<u32>().ok())
89 };
90 Some((samples, field("sample_rate")?, field("channels")? as usize))
91}
92
93fn correlation(a: &[f32], b: &[f32]) -> f64 {
94 let n = a.len().min(b.len());
95 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
96 for i in 0..n {
97 let (x, y) = (a[i] as f64, b[i] as f64);
98 ab += x * y;
99 aa += x * x;
100 bb += y * y;
101 }
102 if aa == 0.0 || bb == 0.0 {
103 return 0.0;
104 }
105 ab / (aa * bb).sqrt()
106}
107
108/// Best correlation over the encoder delay, which no MP3 encoder avoids.
109fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
110 let mut best = (f64::MIN, 0usize);
111 let mut offset = 0;
112 while offset + channels < got.len() && offset <= 3000 * channels {
113 let n = (got.len() - offset).min(want.len());
114 let skip = 1152 * channels;
115 if n <= 2 * skip {
116 break;
117 }
118 let corr = correlation(
119 &got[offset + skip..offset + n - skip],
120 &want[skip..n - skip],
121 );
122 if corr > best.0 {
123 best = (corr, offset);
124 }
125 offset += channels;
126 }
127 best
128}
129
130/// Worst short-window error energy, relative to the source, over the file.
131///
132/// Whole-file correlation cannot see pre-echo: quantisation noise smeared
133/// backwards across a 576-sample granule before an attack is a few
134/// milliseconds of audible hash inside a minute of otherwise clean signal, and
135/// integrating over the minute divides it away. Measured on this crate, going
136/// from one short block per 9196 granules to 526 of them moved whole-file
137/// correlation by 0.00004 -- in the wrong direction -- while changing exactly
138/// the thing short blocks exist to fix. So the sweep also reports the worst
139/// window: error energy over source energy, in dB, over 20 ms windows,
140/// which is the scale a transient's pre-echo lives on.
141fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) -> f64 {
142 let window = 20 * 44100 / 1000 * channels;
143 let skip = 1152 * channels;
144 let n = (got.len() - offset).min(want.len());
145 let mut worst = f64::MIN;
146 let mut start = skip;
147 while start + window + skip <= n {
148 let (mut err, mut sig) = (0.0f64, 0.0f64);
149 for i in start..start + window {
150 let d = f64::from(got[offset + i]) - f64::from(want[i]);
151 err += d * d;
152 sig += f64::from(want[i]) * f64::from(want[i]);
153 }
154 // A window with no signal in it has no pre-echo to hide, and its
155 // ratio would be meaningless; the -60 dBFS gate skips digital silence
156 // and the fade-ins around it.
157 if sig / window as f64 > 1e-6 {
158 let db = 10.0 * (err / sig.max(1e-30)).log10();
159 if db > worst {
160 worst = db;
161 if std::env::var_os("EC_MP3_WORST_WHERE").is_some() {
162 eprintln!(
163 " worst so far {db:+.1} dB at {:.2} s, level {:.1} dBFS",
164 start as f64 / (44100.0 * channels as f64),
165 10.0 * (sig / window as f64).log10()
166 );
167 }
168 }
169 }
170 start += window;
171 }
172 worst
173}
174
175fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
176 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
177 bitrate_kbps: kbps,
178 vbr_quality: None,
179 });
180 encoder
181 .push_pcm_f32(pcm, channels as u16, rate)
182 .expect("encoder accepts the fixture");
183 encoder.finish();
184 let mut out = Vec::new();
185 while let Ok(frame) = encoder.next_packet() {
186 out.extend_from_slice(&frame);
187 }
188 out
189}
190
191/// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it
192/// did before the masking model was put in the quantiser's units (9ac19d6:
193/// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here
194/// while VBR landed; the psychoacoustic change legitimately moves the bytes,
195/// so the gate is the quality those bytes carried.
196#[test]
197fn cbr_quality_holds_its_floor() {
198 let path = fixtures().join("audio/wav16-stereo-48000.wav");
199 let Some((pcm, rate, channels)) = read_wav(&path) else {
200 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
201 return;
202 };
203 let bytes = encode(&pcm, rate, channels, 192);
204 let file = workdir("cbr").join("cbr192.mp3");
205 std::fs::write(&file, &bytes).unwrap();
206 let decoded = decode(&file);
207 assert_eq!(decoded.len(), pcm.len());
208 let corr = correlation(&decoded, &pcm);
209 let (err, sig) = decoded
210 .iter()
211 .zip(&pcm)
212 .fold((0.0f64, 0.0f64), |(e, s), (d, p)| {
213 (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2))
214 });
215 let rms = (err / sig).sqrt();
216 println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0);
217 assert!(corr >= 0.999_99, "corr {corr:.6}");
218 assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0);
219}
220
221fn decode(file: &Path) -> Vec<f32> {
222 let out = Command::new("ffmpeg")
223 .args(["-v", "warning", "-i"])
224 .arg(file)
225 .args(["-f", "f32le", "-"])
226 .output()
227 .expect("run ffmpeg");
228 assert!(
229 out.stderr.is_empty(),
230 "ffmpeg: {}",
231 String::from_utf8_lossy(&out.stderr)
232 );
233 out.stdout
234 .chunks_exact(4)
235 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
236 .collect()
237}
238
239fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> {
240 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
241 bitrate_kbps: 0,
242 vbr_quality: Some(quality),
243 });
244 encoder
245 .push_pcm_f32(pcm, channels as u16, rate)
246 .expect("encoder accepts the fixture");
247 encoder.finish();
248 let mut out = Vec::new();
249 while let Ok(frame) = encoder.next_packet() {
250 out.extend_from_slice(&frame);
251 }
252 out
253}
254
255/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across
256/// frames, decodes at least as well as the incumbent's CBR-192, and announces
257/// itself through a Xing tag ffprobe reads as VBR.
258#[test]
259fn vbr_frames_vary_their_bitrate_index() {
260 let name = "mp3src-stereo-48000";
261 let path = fixtures().join(format!("audio/{name}.wav"));
262 let Some((pcm, rate, channels)) = read_wav(&path) else {
263 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
264 return;
265 };
266 let bytes = encode_vbr(&pcm, rate, channels, 0.5);
267 // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
268 let table = [
269 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
270 ];
271 let mut indices = std::collections::BTreeSet::new();
272 let (mut pos, mut frames) = (0usize, 0usize);
273 while pos + 4 <= bytes.len() {
274 let h = &bytes[pos..pos + 4];
275 assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}");
276 let index = usize::from(h[2] >> 4);
277 let kbps = table[index.min(14)] as usize;
278 assert!(kbps > 0, "free-format header at {pos}");
279 if frames > 0 {
280 indices.insert(index);
281 }
282 frames += 1;
283 pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1);
284 }
285 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
286 let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
287 let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
288 println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
289 assert!(indices.len() >= 3, "only {indices:?}");
290 assert!(
291 (mean - target).abs() <= target * 0.25,
292 "mean {mean:.1} vs {target}"
293 );
294
295 let work = workdir("vbr");
296 let file = work.join("vbr.mp3");
297 std::fs::write(&file, &bytes).unwrap();
298 let out = Command::new("ffmpeg")
299 .args(["-v", "warning", "-i"])
300 .arg(&file)
301 .args(["-f", "f32le", "-"])
302 .output()
303 .expect("run ffmpeg");
304 assert!(
305 out.stderr.is_empty(),
306 "ffmpeg: {}",
307 String::from_utf8_lossy(&out.stderr)
308 );
309 let decoded: Vec<f32> = out
310 .stdout
311 .chunks_exact(4)
312 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
313 .collect();
314 let corr = correlation(&decoded, &pcm);
315 let bar = bar_for(name, 192);
316 println!("vbr corr={corr:.5} bar={bar:.5}");
317 assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
318 let probe = Command::new("ffprobe")
319 .args(["-v", "error", "-show_format"])
320 .arg(&file)
321 .output()
322 .expect("run ffprobe");
323 let probe = String::from_utf8_lossy(&probe.stdout);
324 // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
325 assert!(
326 &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70,
327 "no VBR-flagged Xing tag"
328 );
329 assert!(probe.contains("format_name=mp3"), "{probe}");
330}
331
332#[test]
333fn vbr_mean_bitrate_tracks_quality_on_music() {
334 let path = fixtures().join("audio/wav16-stereo-48000.wav");
335 let Some((pcm, rate, channels)) = read_wav(&path) else {
336 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
337 return;
338 };
339 let mut previous = 0.0;
340 for q in [0.25f32, 0.5, 0.75] {
341 let bytes = encode_vbr(&pcm, rate, channels, q);
342 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
343 let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
344 let target = f64::from(ec_mp3::encode::bitrate_for_quality(q));
345 let tolerance = if q <= 0.5 { 0.70 } else { 0.25 };
346 println!("q={q:.2} mean={mean:.1} target={target:.1}");
347 assert!(
348 mean > previous,
349 "q={q:.2} mean {mean:.1} did not rise above {previous:.1}"
350 );
351 assert!(
352 (mean - target).abs() <= target * tolerance,
353 "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}",
354 tolerance * 100.0,
355 );
356 previous = mean;
357 }
358}
359
360#[test]
361fn encodes_above_the_incumbent_bar() {
362 let dir = fixtures().join("audio");
363 let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir)
364 .into_iter()
365 .flatten()
366 .flatten()
367 .map(|e| e.path())
368 .filter(|p| {
369 let name = p.file_name().map(|n| n.to_string_lossy().to_string());
370 name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-"))
371 && p.extension().is_some_and(|e| e == "wav")
372 })
373 .collect();
374 sources.sort();
375 sources.retain(|p| {
376 let name = p.file_name().unwrap().to_string_lossy().to_string();
377 name.contains("mono") || name.contains("stereo")
378 });
379 if sources.is_empty() {
380 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
381 return;
382 }
383 let work = workdir("encode");
384 println!(
385 "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
386 "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s"
387 );
388 let mut failures = Vec::new();
389 for source in &sources {
390 let Some((pcm, rate, channels)) = read_wav(source) else {
391 continue;
392 };
393 for kbps in BITRATES {
394 let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
395 let bytes = encode(&pcm, rate, channels, kbps);
396 let path = work.join(format!(
397 "{}-{kbps}.mp3",
398 source.file_stem().unwrap().to_string_lossy()
399 ));
400 std::fs::write(&path, &bytes).expect("write encoded file");
401 let out = Command::new("ffmpeg")
402 .args(["-v", "warning", "-i"])
403 .arg(&path)
404 .args(["-f", "f32le", "-"])
405 .output()
406 .expect("run ffmpeg");
407 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
408 if !stderr.is_empty() {
409 failures.push(format!("{}: ffmpeg said {stderr}", path.display()));
410 }
411 let decoded: Vec<f32> = out
412 .stdout
413 .chunks_exact(4)
414 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
415 .collect();
416 // With the Info tag's delay and padding honoured, ffmpeg hands
417 // back exactly the samples that went in: same count, no shift. That
418 // is the gapless claim, so the correlation is measured at lag zero
419 // rather than at whatever lag looks best.
420 if decoded.len() != pcm.len() {
421 failures.push(format!(
422 "{}: decoded {} samples, pushed {}",
423 source.file_name().unwrap().to_string_lossy(),
424 decoded.len(),
425 pcm.len()
426 ));
427 }
428 let corr = correlation(&decoded, &pcm);
429 // A periodic fixture correlates equally well a whole period out,
430 // so a tie is not a misalignment; only a shift that is genuinely
431 // better than lag zero is.
432 let (searched, offset) = aligned(&decoded, &pcm, channels);
433 if offset != 0 && searched > corr + 1e-4 {
434 failures.push(format!(
435 "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}",
436 source.file_name().unwrap().to_string_lossy(),
437 ));
438 }
439 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
440 let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
441 let name = source.file_name().unwrap().to_string_lossy();
442 println!(
443 "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}"
444 );
445 // Matching counts as passing: at 320 kbit/s both encoders are
446 // within a part in 10^5 of the source and the difference between
447 // them is smaller than the metric resolves.
448 if corr < bar - 1e-5 {
449 failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}"));
450 }
451 if (measured - kbps as f64).abs() > kbps as f64 * 0.05 {
452 failures.push(format!(
453 "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s"
454 ));
455 }
456 }
457 }
458 assert!(failures.is_empty(), "{failures:#?}");
459}
460
461// ---------------------------------------------------------------------------
462// The live reference: LAME on the user's own library, at matched constant
463// bitrate. `encodes_above_the_incumbent_bar` measures against a frozen number
464// from the crate this one replaces; that number cannot notice LAME moving, and
465// the fixtures it covers are synthetic. This one encodes the same seconds of
466// the same file with both encoders at the same bitrate and correlates each
467// against the samples that went in.
468// ---------------------------------------------------------------------------
469
470/// Sources for [`real_library_sweep_vs_lame`], the same list the vorbis and
471/// opus library gates use.
472const LIBRARY: [(&str, &str); 7] = [
473 ("nik", "~/Music/reeln.mp4"),
474 ("reelo", "~/Music/reelo.mp3"),
475 ("her", "~/Music/reeli.mp3"),
476 ("reell", "~/Music/reell.mp4"),
477 ("reelm", "~/Music/reelm.wav"),
478 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
479 (
480 "hein",
481 "~/Downloads/reelm.mp3",
482 ),
483];
484
485/// How much worse than LAME a row's worst 20 ms window may be, in dB.
486///
487/// The gap was 12.6 dB when this floor went in, on the two spoken-word
488/// sources; mid/side stereo and the demand-weighted frame split closed it.
489/// Every row now beats libmp3lame's worst window except hein at 192 kbit/s,
490/// which sits 0.2 dB behind, so the floor is one decibel.
491const WORST_WINDOW_EXCESS_DB: f64 = 1.0;
492
493/// How far under LAME a row may sit before the sweep fails, in correlation.
494///
495/// The first measurement put every row between -0.00103 and +0.00142. All
496/// fourteen are now ahead of libmp3lame, the thinnest being hein at 192
497/// kbit/s at +0.00002, so the floor is zero: a row falling behind the
498/// reference at all is the regression.
499const LAME_CORR_FLOOR: f64 = 0.0;
500
501fn expand(path: &str) -> PathBuf {
502 PathBuf::from(match path.strip_prefix("~/") {
503 Some(rest) => format!(
504 "{}/{rest}",
505 std::env::var("HOME").unwrap_or_else(|_| "/home".into())
506 ),
507 None => path.to_string(),
508 })
509}
510
511/// Decodes `seconds` of a source to interleaved stereo f32 at 44.1 kHz.
512fn decode_source(path: &Path, seconds: u32) -> Option<Vec<f32>> {
513 let out = Command::new("ffmpeg")
514 .args(["-v", "error", "-i"])
515 .arg(path)
516 .args([
517 "-vn",
518 "-t",
519 &seconds.to_string(),
520 "-ac",
521 "2",
522 "-ar",
523 "44100",
524 "-f",
525 "f32le",
526 "-",
527 ])
528 .output()
529 .ok()?;
530 if !out.status.success() || out.stdout.is_empty() {
531 return None;
532 }
533 Some(
534 out.stdout
535 .chunks_exact(4)
536 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
537 .collect(),
538 )
539}
540
541/// Ours against LAME on the user's library, at matched constant bitrate:
542///
543/// cargo test -p ec-mp3 --release --test encode_matrix \
544/// real_library_sweep_vs_lame -- --ignored --nocapture
545#[test]
546#[ignore = "needs the user's library and ffmpeg's libmp3lame"]
547fn real_library_sweep_vs_lame() {
548 let seconds = 60u32;
549 let work = workdir("lame-sweep");
550 println!(
551 "{:<7} {:>5} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8}",
552 "source",
553 "kbps",
554 "corr_ours",
555 "corr_lame",
556 "gap",
557 "wworst_o",
558 "wworst_r",
559 "ours_kb",
560 "lame_kb"
561 );
562 let mut rows = 0;
563 let mut failures = Vec::new();
564 // `EC_MP3_SWEEP_ONLY=reelo,dl8a` narrows the sweep to named sources, so a
565 // constant can be swept against the rows it moves without paying for the
566 // rows it does not.
567 let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default();
568 for (name, src) in LIBRARY {
569 if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) {
570 continue;
571 }
572 let src = expand(src);
573 if !src.exists() {
574 println!("{name:<7} SKIP (missing)");
575 continue;
576 }
577 let Some(pcm) = decode_source(&src, seconds) else {
578 println!("{name:<7} SKIP (decode)");
579 continue;
580 };
581 let secs = pcm.len() as f64 / (44100.0 * 2.0);
582 for kbps in [128u32, 192] {
583 let ours_bytes = encode(&pcm, 44100, 2, kbps);
584 let ours_file = work.join(format!("ours-{name}-{kbps}.mp3"));
585 std::fs::write(&ours_file, &ours_bytes).expect("write ours");
586 let lame_file = work.join(format!("lame-{name}-{kbps}.mp3"));
587 let status = Command::new("ffmpeg")
588 .args(["-y", "-v", "error", "-i"])
589 .arg(&src)
590 .args([
591 "-vn",
592 "-t",
593 &seconds.to_string(),
594 "-ac",
595 "2",
596 "-ar",
597 "44100",
598 "-c:a",
599 "libmp3lame",
600 "-b:a",
601 &format!("{kbps}k"),
602 ])
603 .arg(&lame_file)
604 .status()
605 .expect("ffmpeg runs");
606 assert!(status.success(), "libmp3lame encode of {name} at {kbps}k");
607 // Both decoded by the same decoder and aligned the same way: an
608 // encoder delay is not a quality difference.
609 let measure = |file: &Path| -> (f64, f64) {
610 let decoded = decode(file);
611 let (corr, offset) = aligned(&decoded, &pcm, 2);
612 (corr, worst_window_db(&decoded, &pcm, offset, 2))
613 };
614 let ((ours_corr, ours_worst), (lame_corr, lame_worst)) =
615 (measure(&ours_file), measure(&lame_file));
616 let kb =
617 |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;
618 let gap = ours_corr - lame_corr;
619 println!(
620 "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \
621 {ours_worst:>+8.1} {lame_worst:>+8.1} {:>8.1} {:>8.1}",
622 kb(&ours_file),
623 kb(&lame_file)
624 );
625 rows += 1;
626 if gap < LAME_CORR_FLOOR {
627 failures.push(format!(
628 "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}"
629 ));
630 }
631 if ours_worst - lame_worst > WORST_WINDOW_EXCESS_DB {
632 failures.push(format!(
633 "{name} at {kbps} kbit/s: worst window {ours_worst:.1} dB \
634 against LAME's {lame_worst:.1} dB"
635 ));
636 }
637 }
638 }
639 assert!(rows > 0, "no library sources were readable");
640 assert!(failures.is_empty(), "{failures:#?}");
641}
642
643/// The `mode_extension` of every frame of a stream, in order.
644fn mode_exts(bytes: &[u8]) -> Vec<u8> {
645 let mut out = Vec::new();
646 let mut at = 0;
647 while at + 4 <= bytes.len() {
648 let Ok(header) = FrameHeader::parse(&bytes[at..]) else {
649 at += 1;
650 continue;
651 };
652 let Some(len) = header.frame_len() else { break };
653 out.push(header.mode_ext);
654 at += len;
655 }
656 out
657}
658
659/// Mid/side is chosen for the signal it helps and declined for the one it
660/// hurts. Two channels carrying the same waveform put everything in the sum
661/// and nothing in the difference, which is the case mid/side exists for; two
662/// carrying opposite waveforms are its worst case, where the difference is
663/// the loud channel and coding it as such would spend the frame's bits on the
664/// quiet one. Both roundtrip, because the decoder undoes whichever was
665/// written.
666#[test]
667fn mid_side_follows_the_channel_correlation() {
668 let mut seed = 0x2545_f491_4f6c_dd1du64;
669 let mut noise = || {
670 seed ^= seed << 13;
671 seed ^= seed >> 7;
672 seed ^= seed << 17;
673 (seed >> 40) as f32 / 8388608.0 - 0.5
674 };
675 let n = 44100;
676 let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2));
677 for i in 0..n {
678 // Band-limited enough to be codeable: a slow tone under the noise.
679 let tone = (i as f32 * 0.03).sin() * 0.4;
680 let v = tone + noise() * 0.05;
681 same.push(v);
682 same.push(v);
683 opposed.push(v);
684 opposed.push(-v);
685 }
686 for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] {
687 let bytes = encode(&pcm, 44100, 2, 128);
688 let exts = mode_exts(&bytes);
689 assert!(exts.len() > 20, "{label}: only {} frames", exts.len());
690 let ms = exts.iter().filter(|e| *e & 2 != 0).count();
691 // The first and last frames carry priming and a tail, so judge the body.
692 let body = exts.len() - 2;
693 if want_ms {
694 assert!(
695 ms >= body,
696 "{label}: only {ms} of {} frames are mid/side",
697 exts.len()
698 );
699 } else {
700 assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side");
701 }
702 }
703}
704
705/// libmp3lame's VBR levels, encoded once per source so the level that
706/// actually spent what we spent can be picked by measurement. Nominal rates
707/// are no guide: on speech, V6 lands near 60 kbit/s rather than its nominal
708/// 115, because libmp3lame drops the rate hard on easy material.
709const LAME_V_LEVELS: [u32; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
710
711/// How far under libmp3lame a VBR row may sit in correlation when it spent at
712/// least as many bits. Thirteen of the fourteen rows are ahead; the floor is
713/// set by her at quality 0.3, which is 0.00042 behind while spending 1.5%
714/// less.
715const VBR_CORR_FLOOR: f64 = -0.0005;
716
717/// How far behind libmp3lame's worst 20 ms window a VBR row may sit. Set by
718/// nik and reelo at quality 0.3, both 2.8 dB behind: the frames our VBR calls
719/// easy are where it still under-spends against a transient.
720const VBR_WORST_EXCESS_DB: f64 = 3.5;
721
722/// How much of libmp3lame's rate ours may spend at a matched quality. Rows
723/// where libmp3lame is already on its top rung (V0) are exempt: it cannot
724/// spend more there, so a premium measures its ceiling and not our appetite.
725const VBR_RATE_CEILING: f64 = 8.0;
726
727/// Our VBR against libmp3lame's, on the user's own library, at a matched rate.
728///
729/// CBR has had a reference gate since `real_library_sweep_vs_lame`; VBR has
730/// had none, which is why the demand-weighted frame split landed in the CBR
731/// arm only -- VBR's bitrate choice is calibrated to the noise-to-mask ratio
732/// the even split produces, and nothing could tell whether moving both was a
733/// gain or a loss.
734#[test]
735#[ignore = "needs the user's library and ffmpeg's libmp3lame"]
736fn real_library_vbr_vs_lame() {
737 let seconds = 60u32;
738 let work = workdir("lame-vbr");
739 println!(
740 "{:<7} {:>4} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8} {:>4}",
741 "source",
742 "q",
743 "corr_ours",
744 "corr_lame",
745 "gap",
746 "wworst_o",
747 "wworst_r",
748 "ours_kb",
749 "lame_kb",
750 "V"
751 );
752 let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default();
753 let mut rows = 0;
754 let mut failures = Vec::new();
755 for (name, src) in LIBRARY {
756 if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) {
757 continue;
758 }
759 let src = expand(src);
760 if !src.exists() {
761 println!("{name:<7} SKIP (missing)");
762 continue;
763 }
764 let Some(pcm) = decode_source(&src, seconds) else {
765 println!("{name:<7} SKIP (decode)");
766 continue;
767 };
768 let secs = pcm.len() as f64 / (44100.0 * 2.0);
769 let kb = |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;
770 // Every rung of libmp3lame's VBR ladder, measured on this source.
771 let lame_ladder: Vec<(u32, PathBuf, f64)> = LAME_V_LEVELS
772 .iter()
773 .map(|&level| {
774 let file = work.join(format!("lame-{name}-v{level}.mp3"));
775 let status = Command::new("ffmpeg")
776 .args(["-y", "-v", "error", "-i"])
777 .arg(&src)
778 .args([
779 "-vn",
780 "-t",
781 &seconds.to_string(),
782 "-ac",
783 "2",
784 "-ar",
785 "44100",
786 "-c:a",
787 "libmp3lame",
788 "-q:a",
789 &level.to_string(),
790 ])
791 .arg(&file)
792 .status()
793 .expect("ffmpeg runs");
794 assert!(status.success(), "libmp3lame V{level} of {name}");
795 let rate = kb(&file);
796 (level, file, rate)
797 })
798 .collect();
799 for quality in [0.3f32, 0.6] {
800 let ours_bytes = encode_vbr(&pcm, 44100, 2, quality);
801 let ours_file = work.join(format!("ours-{name}-{quality}.mp3"));
802 std::fs::write(&ours_file, &ours_bytes).expect("write ours");
803 let ours_kb = kb(&ours_file);
804 // The level that actually spent what we spent.
805 let (level, lame_file) = lame_ladder
806 .iter()
807 .min_by(|a, b| {
808 (a.2 - ours_kb)
809 .abs()
810 .partial_cmp(&(b.2 - ours_kb).abs())
811 .expect("finite")
812 })
813 .map(|(v, f, _)| (*v, f.clone()))
814 .expect("a ladder rung");
815 let measure = |file: &Path| -> (f64, f64) {
816 let decoded = decode(file);
817 let (corr, offset) = aligned(&decoded, &pcm, 2);
818 (corr, worst_window_db(&decoded, &pcm, offset, 2))
819 };
820 let ((ours_corr, ours_worst), (lame_corr, lame_worst)) =
821 (measure(&ours_file), measure(&lame_file));
822 let lame_kb = kb(&lame_file);
823 let gap = ours_corr - lame_corr;
824 let premium = (ours_kb / lame_kb - 1.0) * 100.0;
825 println!(
826 "{name:<7} {quality:>4} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \
827 {ours_worst:>+8.1} {lame_worst:>+8.1} {ours_kb:>8.1} {lame_kb:>8.1} {level:>4}"
828 );
829 rows += 1;
830 // Being behind on quality is only a failure if we did not also
831 // spend less to get there; spending more is a failure on its own.
832 if gap < VBR_CORR_FLOOR && ours_kb >= lame_kb * 0.98 {
833 failures.push(format!(
834 "{name} at q{quality}: {ours_corr:.5} against LAME's {lame_corr:.5} \
835 at {ours_kb:.1} against {lame_kb:.1} kbit/s"
836 ));
837 }
838 if ours_worst - lame_worst > VBR_WORST_EXCESS_DB {
839 failures.push(format!(
840 "{name} at q{quality}: worst window {ours_worst:.1} dB \
841 against LAME's {lame_worst:.1} dB"
842 ));
843 }
844 if level > 0 && premium > VBR_RATE_CEILING {
845 failures.push(format!(
846 "{name} at q{quality}: {premium:+.1}% of LAME's rate (V{level})"
847 ));
848 }
849 }
850 }
851 assert!(rows > 0, "no library sources were readable");
852 assert!(failures.is_empty(), "{failures:#?}");
853}