forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

encode_matrix.rs223 lines, 7.7 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#[test]
147fn encodes_above_the_incumbent_bar() {
148 let dir = fixtures().join("audio");
149 let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir)
150 .into_iter()
151 .flatten()
152 .flatten()
153 .map(|e| e.path())
154 .filter(|p| {
155 let name = p.file_name().map(|n| n.to_string_lossy().to_string());
156 name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-"))
157 && p.extension().is_some_and(|e| e == "wav")
158 })
159 .collect();
160 sources.sort();
161 sources.retain(|p| {
162 let name = p.file_name().unwrap().to_string_lossy().to_string();
163 name.contains("mono") || name.contains("stereo")
164 });
165 if sources.is_empty() {
166 eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
167 return;
168 }
169 let work = workdir("encode");
170 println!(
171 "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
172 "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s"
173 );
174 let mut failures = Vec::new();
175 for source in &sources {
176 let Some((pcm, rate, channels)) = read_wav(source) else {
177 continue;
178 };
179 for kbps in BITRATES {
180 let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
181 let bytes = encode(&pcm, rate, channels, kbps);
182 let path = work.join(format!(
183 "{}-{kbps}.mp3",
184 source.file_stem().unwrap().to_string_lossy()
185 ));
186 std::fs::write(&path, &bytes).expect("write encoded file");
187 let out = Command::new("ffmpeg")
188 .args(["-v", "warning", "-i"])
189 .arg(&path)
190 .args(["-f", "f32le", "-"])
191 .output()
192 .expect("run ffmpeg");
193 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
194 if !stderr.is_empty() {
195 failures.push(format!("{}: ffmpeg said {stderr}", path.display()));
196 }
197 let decoded: Vec<f32> = out
198 .stdout
199 .chunks_exact(4)
200 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
201 .collect();
202 let (corr, _offset) = aligned(&decoded, &pcm, channels);
203 let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
204 let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
205 let name = source.file_name().unwrap().to_string_lossy();
206 println!(
207 "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}"
208 );
209 // Matching counts as passing: at 320 kbit/s both encoders are
210 // within a part in 10^5 of the source and the difference between
211 // them is smaller than the metric resolves.
212 if corr < bar - 1e-5 {
213 failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}"));
214 }
215 if (measured - kbps as f64).abs() > kbps as f64 * 0.05 {
216 failures.push(format!(
217 "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s"
218 ));
219 }
220 }
221 }
222 assert!(failures.is_empty(), "{failures:#?}");
223}