forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf44b458Tahinli3 months ago649 commits

encode_matrix.rs263 lines, 8.6 KiBHistoryRawDownload
1//! Our encoder against the fixture matrix, proven the only way a lossless
2//! codec can be: encode, decode the result with ffmpeg, compare with the input
3//! byte for byte.
4//!
5//! The size column is informational — it is the same corpus measured against
6//! `ffmpeg -c:a flac` at its default compression level.
7//!
8//! Run the table:
9//! cargo test -p ec-flac --release --test encode_matrix -- --nocapture
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use ec_flac::encode::{EncoderConfig, encode};
15
16struct Source {
17 path: PathBuf,
18 channels: usize,
19 rate: u32,
20 bits: u32,
21}
22
23fn fixtures() -> PathBuf {
24 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
25}
26
27/// A working directory keyed by test name: these tests are threads of one
28/// process, so a shared temp directory would have them deleting each other's
29/// files.
30fn workdir(test: &str) -> PathBuf {
31 let dir = std::env::temp_dir().join(format!("ec-flac-{}-{test}", std::process::id()));
32 std::fs::create_dir_all(&dir).expect("create work dir");
33 dir
34}
35
36fn probe(path: &Path) -> Option<Source> {
37 let out = Command::new("ffprobe")
38 .args([
39 "-v",
40 "error",
41 "-select_streams",
42 "a:0",
43 "-show_entries",
44 "stream=channels,sample_rate,bits_per_raw_sample,sample_fmt",
45 "-of",
46 "default=noprint_wrappers=1",
47 ])
48 .arg(path)
49 .output()
50 .ok()?;
51 // Key=value, because ffprobe prints its own field order, not the requested
52 // one — a positional parse silently swaps rate and channels.
53 let text = String::from_utf8_lossy(&out.stdout);
54 let field = |key: &str| {
55 text.lines()
56 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
57 .map(str::trim)
58 };
59 let bits = match field("bits_per_raw_sample").and_then(|v| v.parse::<u32>().ok()) {
60 Some(n) => n,
61 // WAV states no `bits_per_raw_sample`; its sample format carries it.
62 None => match field("sample_fmt")? {
63 "s16" | "s16p" => 16,
64 "s32" | "s32p" => 32,
65 "u8" | "u8p" => 8,
66 _ => return None,
67 },
68 };
69 Some(Source {
70 path: path.to_path_buf(),
71 channels: field("channels")?.parse().ok()?,
72 rate: field("sample_rate")?.parse().ok()?,
73 bits,
74 })
75}
76
77fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> {
78 let format = if bits <= 16 { "s16le" } else { "s32le" };
79 let out = Command::new("ffmpeg")
80 .args(["-v", "error", "-i"])
81 .arg(path)
82 .args(["-f", format, "-"])
83 .output()
84 .expect("run ffmpeg");
85 assert!(
86 out.status.success(),
87 "ffmpeg failed on {}: {}",
88 path.display(),
89 String::from_utf8_lossy(&out.stderr)
90 );
91 out.stdout
92}
93
94/// Raw PCM as the samples FLAC codes: the container shift undone.
95fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec<i32> {
96 match bits <= 16 {
97 true => pcm
98 .chunks_exact(2)
99 .map(|c| i32::from(i16::from_le_bytes([c[0], c[1]])) >> (16 - bits))
100 .collect(),
101 false => pcm
102 .chunks_exact(4)
103 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> (32 - bits))
104 .collect(),
105 }
106}
107
108fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {
109 let _ = std::fs::remove_file(out);
110 let status = Command::new("ffmpeg")
111 .args(["-v", "error", "-y", "-i"])
112 .arg(src)
113 .args(["-c:a", "flac"])
114 .arg(out)
115 .status()
116 .ok()?;
117 match status.success() {
118 true => std::fs::metadata(out).ok().map(|m| m.len()),
119 false => None,
120 }
121}
122
123fn matrix() -> Vec<Source> {
124 let audio = fixtures().join("audio");
125 let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset");
126 let mut paths: Vec<PathBuf> = Vec::new();
127 if let Ok(entries) = std::fs::read_dir(&audio) {
128 let mut found: Vec<PathBuf> = entries
129 .filter_map(|e| e.ok().map(|e| e.path()))
130 .filter(|p| {
131 let name = p.file_name().unwrap_or_default().to_string_lossy();
132 name.starts_with("flac-") || name.starts_with("wav16-")
133 })
134 .collect();
135 found.sort();
136 paths.append(&mut found);
137 }
138 // Depth coverage the generated fixtures do not have: 24- and 20-bit.
139 for name in [
140 "28 - high resolution audio, default settings.flac",
141 "37 - 20 bit per sample.flac",
142 ] {
143 let p = vectors.join(name);
144 if p.exists() {
145 paths.push(p);
146 }
147 }
148 paths.iter().filter_map(|p| probe(p)).collect()
149}
150
151#[test]
152fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {
153 let sources = matrix();
154 if sources.is_empty() {
155 eprintln!("skipped: fixtures not generated");
156 return;
157 }
158 let dir = workdir("roundtrip");
159 let config = EncoderConfig::default();
160 let mut failures = Vec::new();
161 let (mut ours_total, mut theirs_total) = (0u64, 0u64);
162 println!(
163 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
164 "fixture", "ch", "bit", "rate", "ours", "ffmpeg", "ratio"
165 );
166 for source in &sources {
167 let name = source
168 .path
169 .file_name()
170 .unwrap_or_default()
171 .to_string_lossy()
172 .to_string();
173 let pcm = ffmpeg_pcm(&source.path, source.bits);
174 let samples = samples_from_pcm(&pcm, source.bits);
175 let encoded = match encode(&config, &samples, source.channels, source.bits, source.rate) {
176 Ok(bytes) => bytes,
177 Err(e) => {
178 failures.push(format!("{name}: encode failed: {e}"));
179 continue;
180 }
181 };
182 let out = dir.join(format!("{name}.ours.flac"));
183 std::fs::write(&out, &encoded).expect("write encoded");
184 let decoded = ffmpeg_pcm(&out, source.bits);
185 if decoded != pcm {
186 let at = decoded
187 .iter()
188 .zip(&pcm)
189 .position(|(a, b)| a != b)
190 .map_or_else(|| "length only".to_string(), |i| format!("byte {i}"));
191 failures.push(format!(
192 "{name}: ffmpeg decoded our stream differently at {at} ({} vs {} bytes)",
193 decoded.len(),
194 pcm.len()
195 ));
196 continue;
197 }
198 let theirs = ffmpeg_flac_size(&source.path, &dir.join(format!("{name}.ffmpeg.flac")));
199 ours_total += encoded.len() as u64;
200 theirs_total += theirs.unwrap_or(0);
201 println!(
202 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
203 name,
204 source.channels,
205 source.bits,
206 source.rate,
207 encoded.len(),
208 theirs.map_or("-".to_string(), |n| n.to_string()),
209 theirs.map_or("-".to_string(), |n| format!(
210 "{:.3}",
211 encoded.len() as f64 / n as f64
212 )),
213 );
214 }
215 println!(
216 "totals: ours {ours_total}, ffmpeg {theirs_total}, ratio {:.3}",
217 ours_total as f64 / theirs_total.max(1) as f64
218 );
219 assert!(failures.is_empty(), "{}", failures.join("\n"));
220 // Informational bar from the slice charter: within 10% of ffmpeg's default.
221 assert!(
222 ours_total as f64 <= theirs_total as f64 * 1.10,
223 "corpus is {:.1}% larger than ffmpeg's default FLAC",
224 (ours_total as f64 / theirs_total as f64 - 1.0) * 100.0
225 );
226}
227
228#[test]
229fn our_streams_survive_a_probe_and_state_their_shape() {
230 let Some(source) = matrix().into_iter().find(|s| s.channels == 6) else {
231 eprintln!("skipped: no 5.1 fixture");
232 return;
233 };
234 let dir = workdir("probe");
235 let pcm = ffmpeg_pcm(&source.path, source.bits);
236 let samples = samples_from_pcm(&pcm, source.bits);
237 let encoded = encode(
238 &EncoderConfig::default(),
239 &samples,
240 source.channels,
241 source.bits,
242 source.rate,
243 )
244 .expect("encode");
245 let out = dir.join("surround.flac");
246 std::fs::write(&out, &encoded).expect("write");
247 let probed = probe(&out).expect("ffprobe our own output");
248 assert_eq!(probed.channels, source.channels);
249 assert_eq!(probed.rate, source.rate);
250 assert_eq!(probed.bits, source.bits);
251 // `-v error` clean: ffmpeg must find nothing to complain about.
252 let out_err = Command::new("ffmpeg")
253 .args(["-v", "error", "-i"])
254 .arg(&out)
255 .args(["-f", "null", "-"])
256 .output()
257 .expect("run ffmpeg");
258 assert!(
259 out_err.stderr.is_empty(),
260 "ffmpeg complained: {}",
261 String::from_utf8_lossy(&out_err.stderr)
262 );
263}