forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

decode_matrix.rs180 lines, 6.1 KiBHistoryRawDownload
1//! Our decoder against ffmpeg's, over every MP3 fixture: same sample count,
2//! same samples.
3//!
4//! Correlation rather than a bit-exact compare, because Layer III's output is
5//! defined by an inverse transform rather than by an integer recipe; ISO/IEC
6//! 11172-4 states decoder accuracy the same way. The bar here is 0.999, and
7//! what the fixtures actually reach is printed.
8//!
9//! Run the table:
10//! cargo test -p ec-mp3 --release --test decode_matrix -- --nocapture
11
12use std::path::{Path, PathBuf};
13use std::process::Command;
14use std::time::Instant;
15
16use ec_mp3::Mp3Reader;
17
18fn fixtures() -> PathBuf {
19 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
20}
21
22fn mp3_fixtures() -> Vec<PathBuf> {
23 let dir = fixtures().join("audio");
24 let Ok(entries) = std::fs::read_dir(&dir) else {
25 return Vec::new();
26 };
27 let mut out: Vec<PathBuf> = entries
28 .flatten()
29 .map(|e| e.path())
30 .filter(|p| p.extension().is_some_and(|e| e == "mp3"))
31 .collect();
32 out.sort();
33 out
34}
35
36fn ffmpeg_decode(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
37 let out = Command::new("ffmpeg")
38 .args(["-v", "error", "-i"])
39 .arg(path)
40 .args(["-f", "f32le", "-"])
41 .output()
42 .ok()?;
43 if !out.status.success() {
44 return None;
45 }
46 let samples = out
47 .stdout
48 .chunks_exact(4)
49 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
50 .collect();
51 let probe = Command::new("ffprobe")
52 .args([
53 "-v",
54 "error",
55 "-select_streams",
56 "a:0",
57 "-show_entries",
58 "stream=channels,sample_rate",
59 "-of",
60 "default=noprint_wrappers=1",
61 ])
62 .arg(path)
63 .output()
64 .ok()?;
65 let text = String::from_utf8_lossy(&probe.stdout);
66 let field = |key: &str| {
67 text.lines()
68 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
69 .and_then(|v| v.trim().parse::<u32>().ok())
70 };
71 Some((samples, field("sample_rate")?, field("channels")? as usize))
72}
73
74fn correlation(a: &[f32], b: &[f32]) -> f64 {
75 let n = a.len().min(b.len());
76 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
77 for i in 0..n {
78 let (x, y) = (a[i] as f64, b[i] as f64);
79 ab += x * y;
80 aa += x * x;
81 bb += y * y;
82 }
83 if aa == 0.0 || bb == 0.0 {
84 return f64::from(u8::from(aa == bb));
85 }
86 ab / (aa * bb).sqrt()
87}
88
89/// Best correlation over the priming shift ffmpeg applied, and that shift.
90///
91/// The score is the whole overlap rather than a window: fixture tones are
92/// periodic, so a short window correlates almost as well one period out and
93/// the search would settle on the wrong shift.
94fn best_alignment(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
95 let mut best = (f64::MIN, 0usize);
96 let mut offset = 0;
97 while offset < got.len() && offset <= 2304 * channels {
98 let n = (got.len() - offset).min(want.len()).min(200_000);
99 let corr = correlation(&got[offset..offset + n], &want[..n]);
100 if corr > best.0 {
101 best = (corr, offset);
102 }
103 offset += channels;
104 }
105 let (_, offset) = best;
106 // The first and last frames are the encoder-delay and padding regions that
107 // gapless trimming exists for: the reservoir the first frame points back
108 // into predates the stream, and the last frame's tail is padding ffmpeg
109 // drops. Every frame between them is compared.
110 let skip = 1152 * channels;
111 let n = (got.len() - offset)
112 .min(want.len())
113 .saturating_sub(2 * skip);
114 (
115 correlation(
116 &got[offset + skip..offset + skip + n],
117 &want[skip..skip + n],
118 ),
119 offset,
120 )
121}
122
123#[test]
124fn decodes_every_fixture_like_ffmpeg() {
125 let files = mp3_fixtures();
126 if files.is_empty() {
127 eprintln!("no MP3 fixtures: run scripts/gen-fixtures.sh and scripts/gen-mp3-fixtures.sh");
128 return;
129 }
130 println!(
131 "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}",
132 "fixture", "rate", "ch", "samples", "corr", "x rt"
133 );
134 let mut worst = 1.0f64;
135 let mut failures = Vec::new();
136 for path in &files {
137 let bytes = std::fs::read(path).expect("read fixture");
138 let Some((want, rate, channels)) = ffmpeg_decode(path) else {
139 panic!("ffmpeg could not decode {}", path.display());
140 };
141 let start = Instant::now();
142 let mut reader = Mp3Reader::new();
143 reader.push(&bytes);
144 let frames = reader.decode_all();
145 let elapsed = start.elapsed().as_secs_f64();
146 let mut got = Vec::with_capacity(want.len());
147 for frame in &frames {
148 got.extend_from_slice(&frame.samples);
149 }
150 let name = path.file_name().unwrap().to_string_lossy();
151 // ffmpeg honours the LAME delay/padding tags and drops the encoder's
152 // priming samples; we hand back every frame we were given, so the
153 // comparison finds the shift first. Gapless trimming is a container
154 // concern, not a decoder one.
155 let (corr, offset) = best_alignment(&got, &want, channels);
156 let seconds = got.len() as f64 / (rate as f64 * channels as f64);
157 let realtime = seconds / elapsed.max(1e-9);
158 println!(
159 "{name:<34} {rate:>6} {channels:>3} {:>9} {corr:>9.6} {realtime:>8.0} (+{offset})",
160 got.len()
161 );
162 // A sample count that disagrees by more than the encoder delay plus
163 // padding means we lost or invented audio, which correlation alone
164 // would hide. Two frames covers both ends of the gapless trim.
165 let slack = 2 * 1152 * channels;
166 if got.len() + slack < want.len() || want.len() + slack < got.len() {
167 failures.push(format!(
168 "{name}: {} samples, ffmpeg {} ",
169 got.len(),
170 want.len()
171 ));
172 }
173 if corr < 0.999 {
174 failures.push(format!("{name}: correlation {corr:.6}"));
175 }
176 worst = worst.min(corr);
177 }
178 println!("worst correlation {worst:.6} over {} fixtures", files.len());
179 assert!(failures.is_empty(), "{failures:#?}");
180}