forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB06be466Tahinli2 months ago3574 commits

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