forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a26b91Tahinli3 months ago348 commits

encode_matrix.rs414 lines, 15.0 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 this crate replaces, `rusty_mp3` 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::{Mp3Encoder, Mp3EncoderConfig};
15
16/// Correlation `rusty_mp3` 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
130fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
131 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
132 bitrate_kbps: kbps,
133 vbr_quality: None,
134 });
135 encoder
136 .push_pcm_f32(pcm, channels as u16, rate)
137 .expect("encoder accepts the fixture");
138 encoder.finish();
139 let mut out = Vec::new();
140 while let Ok(frame) = encoder.next_packet() {
141 out.extend_from_slice(&frame);
142 }
143 out
144}
145
146/// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it
147/// did before the masking model was put in the quantiser's units (9ac19d6:
148/// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here
149/// while VBR landed; the psychoacoustic change legitimately moves the bytes,
150/// so the gate is the quality those bytes carried.
151#[test]
152fn cbr_quality_holds_its_floor() {
153 let path = fixtures().join("audio/wav16-stereo-48000.wav");
154 let Some((pcm, rate, channels)) = read_wav(&path) else {
155 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
156 return;
157 };
158 let bytes = encode(&pcm, rate, channels, 192);
159 let file = workdir("cbr").join("cbr192.mp3");
160 std::fs::write(&file, &bytes).unwrap();
161 let decoded = decode(&file);
162 assert_eq!(decoded.len(), pcm.len());
163 let corr = correlation(&decoded, &pcm);
164 let (err, sig) = decoded
165 .iter()
166 .zip(&pcm)
167 .fold((0.0f64, 0.0f64), |(e, s), (d, p)| {
168 (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2))
169 });
170 let rms = (err / sig).sqrt();
171 println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0);
172 assert!(corr >= 0.999_99, "corr {corr:.6}");
173 assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0);
174}
175
176fn decode(file: &Path) -> Vec<f32> {
177 let out = Command::new("ffmpeg")
178 .args(["-v", "warning", "-i"])
179 .arg(file)
180 .args(["-f", "f32le", "-"])
181 .output()
182 .expect("run ffmpeg");
183 assert!(
184 out.stderr.is_empty(),
185 "ffmpeg: {}",
186 String::from_utf8_lossy(&out.stderr)
187 );
188 out.stdout
189 .chunks_exact(4)
190 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
191 .collect()
192}
193
194fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> {
195 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
196 bitrate_kbps: 0,
197 vbr_quality: Some(quality),
198 });
199 encoder
200 .push_pcm_f32(pcm, channels as u16, rate)
201 .expect("encoder accepts the fixture");
202 encoder.finish();
203 let mut out = Vec::new();
204 while let Ok(frame) = encoder.next_packet() {
205 out.extend_from_slice(&frame);
206 }
207 out
208}
209
210/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across
211/// frames, decodes at least as well as the incumbent's CBR-192, and announces
212/// itself through a Xing tag ffprobe reads as VBR.
213#[test]
214fn vbr_frames_vary_their_bitrate_index() {
215 let name = "mp3src-stereo-48000";
216 let path = fixtures().join(format!("audio/{name}.wav"));
217 let Some((pcm, rate, channels)) = read_wav(&path) else {
218 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
219 return;
220 };
221 let bytes = encode_vbr(&pcm, rate, channels, 0.5);
222 // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
223 let table = [
224 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
225 ];
226 let mut indices = std::collections::BTreeSet::new();
227 let (mut pos, mut frames) = (0usize, 0usize);
228 while pos + 4 <= bytes.len() {
229 let h = &bytes[pos..pos + 4];
230 assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}");
231 let index = usize::from(h[2] >> 4);
232 let kbps = table[index.min(14)] as usize;
233 assert!(kbps > 0, "free-format header at {pos}");
234 if frames > 0 {
235 indices.insert(index);
236 }
237 frames += 1;
238 pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1);
239 }
240 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
241 let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
242 let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
243 println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
244 assert!(indices.len() >= 3, "only {indices:?}");
245 assert!(
246 (mean - target).abs() <= target * 0.25,
247 "mean {mean:.1} vs {target}"
248 );
249
250 let work = workdir("vbr");
251 let file = work.join("vbr.mp3");
252 std::fs::write(&file, &bytes).unwrap();
253 let out = Command::new("ffmpeg")
254 .args(["-v", "warning", "-i"])
255 .arg(&file)
256 .args(["-f", "f32le", "-"])
257 .output()
258 .expect("run ffmpeg");
259 assert!(
260 out.stderr.is_empty(),
261 "ffmpeg: {}",
262 String::from_utf8_lossy(&out.stderr)
263 );
264 let decoded: Vec<f32> = out
265 .stdout
266 .chunks_exact(4)
267 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
268 .collect();
269 let corr = correlation(&decoded, &pcm);
270 let bar = bar_for(name, 192);
271 println!("vbr corr={corr:.5} bar={bar:.5}");
272 assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
273 let probe = Command::new("ffprobe")
274 .args(["-v", "error", "-show_format"])
275 .arg(&file)
276 .output()
277 .expect("run ffprobe");
278 let probe = String::from_utf8_lossy(&probe.stdout);
279 // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
280 assert!(
281 &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70,
282 "no VBR-flagged Xing tag"
283 );
284 assert!(probe.contains("format_name=mp3"), "{probe}");
285}
286
287#[test]
288fn vbr_mean_bitrate_tracks_quality_on_music() {
289 let path = fixtures().join("audio/wav16-stereo-48000.wav");
290 let Some((pcm, rate, channels)) = read_wav(&path) else {
291 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
292 return;
293 };
294 let mut previous = 0.0;
295 for q in [0.25f32, 0.5, 0.75] {
296 let bytes = encode_vbr(&pcm, rate, channels, q);
297 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
298 let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
299 let target = f64::from(ec_mp3::encode::bitrate_for_quality(q));
300 let tolerance = if q <= 0.5 { 0.70 } else { 0.25 };
301 println!("q={q:.2} mean={mean:.1} target={target:.1}");
302 assert!(
303 mean > previous,
304 "q={q:.2} mean {mean:.1} did not rise above {previous:.1}"
305 );
306 assert!(
307 (mean - target).abs() <= target * tolerance,
308 "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}",
309 tolerance * 100.0,
310 );
311 previous = mean;
312 }
313}
314
315#[test]
316fn encodes_above_the_incumbent_bar() {
317 let dir = fixtures().join("audio");
318 let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir)
319 .into_iter()
320 .flatten()
321 .flatten()
322 .map(|e| e.path())
323 .filter(|p| {
324 let name = p.file_name().map(|n| n.to_string_lossy().to_string());
325 name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-"))
326 && p.extension().is_some_and(|e| e == "wav")
327 })
328 .collect();
329 sources.sort();
330 sources.retain(|p| {
331 let name = p.file_name().unwrap().to_string_lossy().to_string();
332 name.contains("mono") || name.contains("stereo")
333 });
334 if sources.is_empty() {
335 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
336 return;
337 }
338 let work = workdir("encode");
339 println!(
340 "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
341 "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s"
342 );
343 let mut failures = Vec::new();
344 for source in &sources {
345 let Some((pcm, rate, channels)) = read_wav(source) else {
346 continue;
347 };
348 for kbps in BITRATES {
349 let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
350 let bytes = encode(&pcm, rate, channels, kbps);
351 let path = work.join(format!(
352 "{}-{kbps}.mp3",
353 source.file_stem().unwrap().to_string_lossy()
354 ));
355 std::fs::write(&path, &bytes).expect("write encoded file");
356 let out = Command::new("ffmpeg")
357 .args(["-v", "warning", "-i"])
358 .arg(&path)
359 .args(["-f", "f32le", "-"])
360 .output()
361 .expect("run ffmpeg");
362 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
363 if !stderr.is_empty() {
364 failures.push(format!("{}: ffmpeg said {stderr}", path.display()));
365 }
366 let decoded: Vec<f32> = out
367 .stdout
368 .chunks_exact(4)
369 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
370 .collect();
371 // With the Info tag's delay and padding honoured, ffmpeg hands
372 // back exactly the samples that went in: same count, no shift. That
373 // is the gapless claim, so the correlation is measured at lag zero
374 // rather than at whatever lag looks best.
375 if decoded.len() != pcm.len() {
376 failures.push(format!(
377 "{}: decoded {} samples, pushed {}",
378 source.file_name().unwrap().to_string_lossy(),
379 decoded.len(),
380 pcm.len()
381 ));
382 }
383 let corr = correlation(&decoded, &pcm);
384 // A periodic fixture correlates equally well a whole period out,
385 // so a tie is not a misalignment; only a shift that is genuinely
386 // better than lag zero is.
387 let (searched, offset) = aligned(&decoded, &pcm, channels);
388 if offset != 0 && searched > corr + 1e-4 {
389 failures.push(format!(
390 "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}",
391 source.file_name().unwrap().to_string_lossy(),
392 ));
393 }
394 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
395 let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
396 let name = source.file_name().unwrap().to_string_lossy();
397 println!(
398 "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}"
399 );
400 // Matching counts as passing: at 320 kbit/s both encoders are
401 // within a part in 10^5 of the source and the difference between
402 // them is smaller than the metric resolves.
403 if corr < bar - 1e-5 {
404 failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}"));
405 }
406 if (measured - kbps as f64).abs() > kbps as f64 * 0.05 {
407 failures.push(format!(
408 "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s"
409 ));
410 }
411 }
412 }
413 assert!(failures.is_empty(), "{failures:#?}");
414}