forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

encode_matrix.rs312 lines, 10.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
23/// Fixture-presence probe for the encoder matrix corpus.
24/// Returns whether the fixture is present, but never silently: under
25/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
26/// and the script that regenerates it, so a host whose fixture library drifted
27/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
28/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
29/// short-circuited because the probe ran first in a compound `if`).
30///
31/// Order is load-bearing: probe, assert, return. Never merge the probe into
32/// the same `if` as the escape.
33fn require_fixture(path: &Path, generator: &str) -> bool {
34 let present = path.exists();
35 assert!(
36 present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
37 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
38 path.display(),
39 generator
40 );
41 if !present {
42 eprintln!("SKIP: fixture {} absent", path.display());
43 }
44 present
45}
46
47fn fixtures() -> PathBuf {
48 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
49}
50
51/// A working directory keyed by test name: these tests are threads of one
52/// process, so a shared temp directory would have them deleting each other's
53/// files.
54fn workdir(test: &str) -> PathBuf {
55 let dir = std::env::temp_dir().join(format!("ec-flac-{}-{test}", std::process::id()));
56 std::fs::create_dir_all(&dir).expect("create work dir");
57 dir
58}
59
60fn probe(path: &Path) -> Option<Source> {
61 let out = Command::new("ffprobe")
62 .args([
63 "-v",
64 "error",
65 "-select_streams",
66 "a:0",
67 "-show_entries",
68 "stream=channels,sample_rate,bits_per_raw_sample,sample_fmt",
69 "-of",
70 "default=noprint_wrappers=1",
71 ])
72 .arg(path)
73 .output()
74 .ok()?;
75 // Key=value, because ffprobe prints its own field order, not the requested
76 // one — a positional parse silently swaps rate and channels.
77 let text = String::from_utf8_lossy(&out.stdout);
78 let field = |key: &str| {
79 text.lines()
80 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
81 .map(str::trim)
82 };
83 let bits = match field("bits_per_raw_sample").and_then(|v| v.parse::<u32>().ok()) {
84 Some(n) => n,
85 // WAV states no `bits_per_raw_sample`; its sample format carries it.
86 None => match field("sample_fmt")? {
87 "s16" | "s16p" => 16,
88 "s32" | "s32p" => 32,
89 "u8" | "u8p" => 8,
90 _ => return None,
91 },
92 };
93 Some(Source {
94 path: path.to_path_buf(),
95 channels: field("channels")?.parse().ok()?,
96 rate: field("sample_rate")?.parse().ok()?,
97 bits,
98 })
99}
100
101fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> {
102 let format = if bits <= 16 { "s16le" } else { "s32le" };
103 let out = Command::new("ffmpeg")
104 .args(["-v", "error", "-i"])
105 .arg(path)
106 .args(["-f", format, "-"])
107 .output()
108 .expect("run ffmpeg");
109 assert!(
110 out.status.success(),
111 "ffmpeg failed on {}: {}",
112 path.display(),
113 String::from_utf8_lossy(&out.stderr)
114 );
115 out.stdout
116}
117
118/// Raw PCM as the samples FLAC codes: the container shift undone.
119fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec<i32> {
120 match bits <= 16 {
121 true => pcm
122 .as_chunks::<2>()
123 .0
124 .iter()
125 .map(|c| i32::from(i16::from_le_bytes(*c)) >> (16 - bits))
126 .collect(),
127 false => pcm
128 .as_chunks::<4>()
129 .0
130 .iter()
131 .map(|c| i32::from_le_bytes(*c) >> (32 - bits))
132 .collect(),
133 }
134}
135
136fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {
137 let _ = std::fs::remove_file(out);
138 let status = Command::new("ffmpeg")
139 .args(["-v", "error", "-y", "-i"])
140 .arg(src)
141 .args(["-c:a", "flac"])
142 .arg(out)
143 .status()
144 .ok()?;
145 match status.success() {
146 true => std::fs::metadata(out).ok().map(|m| m.len()),
147 false => None,
148 }
149}
150
151fn matrix() -> Vec<Source> {
152 let audio = fixtures().join("audio");
153 let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset");
154 let mut paths: Vec<PathBuf> = Vec::new();
155 // Probe first, assert inside the helper, and only then take the empty-list
156 // branch: under EC_REQUIRE_FIXTURES the assert fires instead of a silent
157 // skip that leaves every loop below running zero times.
158 if require_fixture(&audio, "scripts/gen-fixtures.sh") {
159 let entries = std::fs::read_dir(&audio)
160 .unwrap_or_else(|e| panic!("read fixture dir {}: {e}", audio.display()));
161 let mut found: Vec<PathBuf> = entries
162 .filter_map(|e| e.ok().map(|e| e.path()))
163 .filter(|p| {
164 let name = p.file_name().unwrap_or_default().to_string_lossy();
165 name.starts_with("flac-") || name.starts_with("wav16-")
166 })
167 .collect();
168 found.sort();
169 paths.append(&mut found);
170 }
171 // Depth coverage the generated fixtures do not have: 24- and 20-bit.
172 if require_fixture(&vectors, "scripts/fetch-vectors.sh") {
173 for name in [
174 "28 - high resolution audio, default settings.flac",
175 "37 - 20 bit per sample.flac",
176 ] {
177 let p = vectors.join(name);
178 if p.exists() {
179 paths.push(p);
180 }
181 }
182 }
183 paths.iter().filter_map(|p| probe(p)).collect()
184}
185
186#[test]
187fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {
188 let sources = matrix();
189 if sources.is_empty() {
190 eprintln!("skipped: fixtures not generated");
191 return;
192 }
193 // Non-empty floor: the loop below must run, not zero times.
194 assert!(
195 sources.len() >= 5,
196 "encoder matrix holds {} usable sources, expected at least 5",
197 sources.len()
198 );
199 let dir = workdir("roundtrip");
200 let config = EncoderConfig::default();
201 let mut failures = Vec::new();
202 let (mut ours_total, mut theirs_total) = (0u64, 0u64);
203 println!(
204 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
205 "fixture", "ch", "bit", "rate", "ours", "ffmpeg", "ratio"
206 );
207 for source in &sources {
208 let name = source
209 .path
210 .file_name()
211 .unwrap_or_default()
212 .to_string_lossy()
213 .to_string();
214 let pcm = ffmpeg_pcm(&source.path, source.bits);
215 let samples = samples_from_pcm(&pcm, source.bits);
216 let encoded = match encode(&config, &samples, source.channels, source.bits, source.rate) {
217 Ok(bytes) => bytes,
218 Err(e) => {
219 failures.push(format!("{name}: encode failed: {e}"));
220 continue;
221 }
222 };
223 let out = dir.join(format!("{name}.ours.flac"));
224 std::fs::write(&out, &encoded).expect("write encoded");
225 let decoded = ffmpeg_pcm(&out, source.bits);
226 if decoded != pcm {
227 let at = decoded
228 .iter()
229 .zip(&pcm)
230 .position(|(a, b)| a != b)
231 .map_or_else(|| "length only".to_string(), |i| format!("byte {i}"));
232 failures.push(format!(
233 "{name}: ffmpeg decoded our stream differently at {at} ({} vs {} bytes)",
234 decoded.len(),
235 pcm.len()
236 ));
237 continue;
238 }
239 let theirs = ffmpeg_flac_size(&source.path, &dir.join(format!("{name}.ffmpeg.flac")));
240 ours_total += encoded.len() as u64;
241 theirs_total += theirs.unwrap_or(0);
242 println!(
243 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
244 name,
245 source.channels,
246 source.bits,
247 source.rate,
248 encoded.len(),
249 theirs.map_or("-".to_string(), |n| n.to_string()),
250 theirs.map_or("-".to_string(), |n| format!(
251 "{:.3}",
252 encoded.len() as f64 / n as f64
253 )),
254 );
255 }
256 println!(
257 "totals: ours {ours_total}, ffmpeg {theirs_total}, ratio {:.3}",
258 ours_total as f64 / theirs_total.max(1) as f64
259 );
260 assert!(failures.is_empty(), "{}", failures.join("\n"));
261 // Informational bar from the slice charter: within 10% of ffmpeg's default.
262 assert!(
263 ours_total as f64 <= theirs_total as f64 * 1.10,
264 "corpus is {:.1}% larger than ffmpeg's default FLAC",
265 (ours_total as f64 / theirs_total as f64 - 1.0) * 100.0
266 );
267}
268
269#[test]
270fn our_streams_survive_a_probe_and_state_their_shape() {
271 // The 5.1 source this test needs is a named fixture, not a shape we hope the
272 // matrix happens to contain: probe it first so EC_REQUIRE_FIXTURES fails on
273 // a drifted library instead of skipping.
274 let surround = fixtures().join("audio/flac-5.1-44100.flac");
275 if !require_fixture(&surround, "scripts/gen-fixtures.sh") {
276 return;
277 }
278 let source = matrix()
279 .into_iter()
280 .find(|s| s.channels == 6)
281 .or_else(|| probe(&surround))
282 .expect("5.1 source in the encoder matrix");
283 let dir = workdir("probe");
284 let pcm = ffmpeg_pcm(&source.path, source.bits);
285 let samples = samples_from_pcm(&pcm, source.bits);
286 let encoded = encode(
287 &EncoderConfig::default(),
288 &samples,
289 source.channels,
290 source.bits,
291 source.rate,
292 )
293 .expect("encode");
294 let out = dir.join("surround.flac");
295 std::fs::write(&out, &encoded).expect("write");
296 let probed = probe(&out).expect("ffprobe our own output");
297 assert_eq!(probed.channels, source.channels);
298 assert_eq!(probed.rate, source.rate);
299 assert_eq!(probed.bits, source.bits);
300 // `-v error` clean: ffmpeg must find nothing to complain about.
301 let out_err = Command::new("ffmpeg")
302 .args(["-v", "error", "-i"])
303 .arg(&out)
304 .args(["-f", "null", "-"])
305 .output()
306 .expect("run ffmpeg");
307 assert!(
308 out_err.stderr.is_empty(),
309 "ffmpeg complained: {}",
310 String::from_utf8_lossy(&out_err.stderr)
311 );
312}