forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBca831ceTahinli6 days ago3966 commits

main.rs579 lines, 19.4 KiBHistoryRawDownload
1//! `oracle` — ffmpeg-backed comparison harness for the edith_codecs family.
2//!
3//! ffmpeg/ffprobe are ORACLE tooling: they are driven here through `std::process`
4//! pipes so no `ec-*` crate ever gains a media dependency, sync or async.
5//!
6//! Subcommands:
7//! `bit-exact <a> <b>` byte-identical check
8//! `audio-compare <ours.raw> <ref-file>` per-channel correlation + RMS delta
9//! `video-compare <ours.raw> <ref-file>` per-frame PSNR, min/mean
10//!
11//! `<ours.raw>` is our decoder's raw output: interleaved f32 LE for audio, raw
12//! planar/packed frames in `--pix-fmt` order for video. The reference is any file
13//! ffmpeg can decode; it is decoded to the same raw layout and compared.
14//!
15//! stdout is TSV (every line `type<TAB>...`), stderr is the human summary.
16//! Exit code: 0 = PASS, 1 = FAIL, 2 = usage/IO error.
17
18#![forbid(unsafe_code)]
19
20use std::collections::HashMap;
21use std::process::{Command, Stdio};
22
23const USAGE: &str = "\
24oracle — comparison harness (ffmpeg is test tooling only)
25
26 oracle bit-exact <a> <b>
27 oracle audio-compare <ours.f32le.raw> <ref-file> [--channels N] [--min-corr F] [--max-rms F]
28 oracle video-compare <ours.raw> <ref-file> [--pix-fmt FMT] [--size WxH] [--min-psnr DB]
29
30Defaults: --min-corr 0.999 --max-rms 1e-3 --min-psnr 40
31Missing --channels/--pix-fmt/--size are probed from <ref-file> with ffprobe.
32";
33
34fn main() {
35 let argv: Vec<String> = std::env::args().skip(1).collect();
36 let rc = match argv.first().map(String::as_str) {
37 Some("bit-exact") => run(cmd_bit_exact(&argv[1..])),
38 Some("audio-compare") => run(cmd_audio_compare(&argv[1..])),
39 Some("video-compare") => run(cmd_video_compare(&argv[1..])),
40 Some("-h") | Some("--help") => {
41 print!("{USAGE}");
42 0
43 }
44 _ => {
45 eprint!("{USAGE}");
46 2
47 }
48 };
49 std::process::exit(rc);
50}
51
52fn run(r: Result<bool, String>) -> i32 {
53 match r {
54 Ok(true) => 0,
55 Ok(false) => 1,
56 Err(e) => {
57 eprintln!("oracle: {e}");
58 2
59 }
60 }
61}
62
63// ------------------------------------------------------------------ args ---
64
65struct Args {
66 pos: Vec<String>,
67 flags: HashMap<String, String>,
68}
69
70impl Args {
71 fn parse(argv: &[String]) -> Result<Self, String> {
72 let mut pos = Vec::new();
73 let mut flags = HashMap::new();
74 let mut it = argv.iter();
75 while let Some(a) = it.next() {
76 if let Some(key) = a.strip_prefix("--") {
77 let v = it
78 .next()
79 .ok_or_else(|| format!("flag --{key} needs a value"))?;
80 flags.insert(key.to_string(), v.clone());
81 } else {
82 pos.push(a.clone());
83 }
84 }
85 Ok(Self { pos, flags })
86 }
87
88 fn num<T: std::str::FromStr>(&self, key: &str, default: T) -> Result<T, String> {
89 match self.flags.get(key) {
90 None => Ok(default),
91 Some(v) => v.parse().map_err(|_| format!("bad --{key} value: {v}")),
92 }
93 }
94}
95
96// --------------------------------------------------------------- ffmpeg ----
97
98/// Decode `input` with ffmpeg and return the raw bytes it writes to stdout.
99/// stderr is inherited so a large error log can never deadlock the pipe.
100fn ffmpeg_raw(input: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
101 let out = Command::new("ffmpeg")
102 .args(["-nostdin", "-v", "error", "-i", input])
103 .args(extra)
104 .arg("-")
105 .stdout(Stdio::piped())
106 .stderr(Stdio::inherit())
107 .output()
108 .map_err(|e| format!("spawning ffmpeg: {e}"))?;
109 if !out.status.success() {
110 return Err(format!("ffmpeg failed on {input} ({})", out.status));
111 }
112 if out.stdout.is_empty() {
113 return Err(format!("ffmpeg produced no data for {input}"));
114 }
115 Ok(out.stdout)
116}
117
118/// `ffprobe -show_entries stream=<entries>` as a key -> value map (first stream wins).
119fn ffprobe(input: &str, select: &str, entries: &str) -> Result<HashMap<String, String>, String> {
120 let out = Command::new("ffprobe")
121 .args(["-v", "error", "-select_streams", select, "-show_entries"])
122 .arg(format!("stream={entries}"))
123 .args(["-of", "default=nw=1"])
124 .arg(input)
125 .stderr(Stdio::inherit())
126 .output()
127 .map_err(|e| format!("spawning ffprobe: {e}"))?;
128 if !out.status.success() {
129 return Err(format!("ffprobe failed on {input} ({})", out.status));
130 }
131 let mut map = HashMap::new();
132 for line in String::from_utf8_lossy(&out.stdout).lines() {
133 if let Some((k, v)) = line.split_once('=')
134 && v != "N/A"
135 {
136 map.entry(k.to_string()).or_insert_with(|| v.to_string());
137 }
138 }
139 Ok(map)
140}
141
142fn read_file(path: &str) -> Result<Vec<u8>, String> {
143 std::fs::read(path).map_err(|e| format!("reading {path}: {e}"))
144}
145
146// ------------------------------------------------------------ bit-exact ----
147
148fn cmd_bit_exact(argv: &[String]) -> Result<bool, String> {
149 let a = Args::parse(argv)?;
150 if a.pos.len() != 2 {
151 return Err("bit-exact needs exactly two files".into());
152 }
153 let (x, y) = (read_file(&a.pos[0])?, read_file(&a.pos[1])?);
154 let first_diff = x.iter().zip(&y).position(|(p, q)| p != q);
155 let pass = x.len() == y.len() && first_diff.is_none();
156
157 println!("meta\ta\t{}", a.pos[0]);
158 println!("meta\tb\t{}", a.pos[1]);
159 println!("meta\tlen_a\t{}", x.len());
160 println!("meta\tlen_b\t{}", y.len());
161 match first_diff {
162 Some(off) => println!("diff\tfirst_offset\t{off}"),
163 None => println!("diff\tfirst_offset\t-"),
164 }
165 println!("verdict\t{}", if pass { "PASS" } else { "FAIL" });
166 eprintln!(
167 "bit-exact: {} ({} vs {} bytes, first diff {})",
168 if pass { "PASS" } else { "FAIL" },
169 x.len(),
170 y.len(),
171 first_diff.map_or("-".into(), |o| o.to_string())
172 );
173 Ok(pass)
174}
175
176// -------------------------------------------------------------- audio ------
177
178fn deinterleave_f32(buf: &[u8], channels: usize) -> Vec<Vec<f64>> {
179 let frames = buf.len() / 4 / channels;
180 let mut out = vec![Vec::with_capacity(frames); channels];
181 for f in 0..frames {
182 for (c, ch) in out.iter_mut().enumerate() {
183 let i = (f * channels + c) * 4;
184 ch.push(f32::from_le_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as f64);
185 }
186 }
187 out
188}
189
190/// Pearson correlation. Two constant signals correlate perfectly iff equal.
191fn corr(a: &[f64], b: &[f64]) -> f64 {
192 let n = a.len().min(b.len());
193 if n == 0 {
194 return 0.0;
195 }
196 let (ma, mb) = (
197 a[..n].iter().sum::<f64>() / n as f64,
198 b[..n].iter().sum::<f64>() / n as f64,
199 );
200 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
201 for i in 0..n {
202 let (x, y) = (a[i] - ma, b[i] - mb);
203 num += x * y;
204 da += x * x;
205 db += y * y;
206 }
207 if da == 0.0 || db == 0.0 {
208 return if da == db && (ma - mb).abs() < 1e-12 {
209 1.0
210 } else {
211 0.0
212 };
213 }
214 num / (da * db).sqrt()
215}
216
217fn rms_delta(a: &[f64], b: &[f64]) -> (f64, f64) {
218 let n = a.len().min(b.len());
219 if n == 0 {
220 return (f64::INFINITY, f64::INFINITY);
221 }
222 let mut sum = 0.0;
223 let mut peak: f64 = 0.0;
224 for i in 0..n {
225 let d = a[i] - b[i];
226 sum += d * d;
227 peak = peak.max(d.abs());
228 }
229 ((sum / n as f64).sqrt(), peak)
230}
231
232fn cmd_audio_compare(argv: &[String]) -> Result<bool, String> {
233 let a = Args::parse(argv)?;
234 if a.pos.len() != 2 {
235 return Err("audio-compare needs <ours.raw> <ref-file>".into());
236 }
237 let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]);
238 let min_corr: f64 = a.num("min-corr", 0.999)?;
239 let max_rms: f64 = a.num("max-rms", 1e-3)?;
240
241 let probe = ffprobe(ref_path, "a:0", "channels,sample_rate")?;
242 let channels: usize = match a.flags.get("channels") {
243 Some(v) => v.parse().map_err(|_| "bad --channels".to_string())?,
244 None => probe
245 .get("channels")
246 .ok_or("could not probe channel count; pass --channels")?
247 .parse()
248 .map_err(|_| "bad probed channel count".to_string())?,
249 };
250 if channels == 0 {
251 return Err("channel count is zero".into());
252 }
253 let rate = probe
254 .get("sample_rate")
255 .cloned()
256 .unwrap_or_else(|| "-".into());
257
258 let ours = read_file(ours_path)?;
259 let reference = ffmpeg_raw(
260 ref_path,
261 &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"],
262 )?;
263 let (na, nb) = (ours.len() / 4 / channels, reference.len() / 4 / channels);
264 let (ca, cb) = (
265 deinterleave_f32(&ours, channels),
266 deinterleave_f32(&reference, channels),
267 );
268
269 println!("meta\tours\t{ours_path}");
270 println!("meta\tref\t{ref_path}");
271 println!("meta\tchannels\t{channels}");
272 println!("meta\tsample_rate\t{rate}");
273 println!("meta\tframes_ours\t{na}");
274 println!("meta\tframes_ref\t{nb}");
275
276 // A length gap beyond one percent is a decoder bug (dropped/duplicated
277 // packets), not a comparison detail — it fails on its own.
278 let len_ok = na.abs_diff(nb) as f64 <= 0.01 * na.max(nb) as f64;
279 let mut min_c = f64::INFINITY;
280 let mut max_r: f64 = 0.0;
281 for c in 0..channels {
282 let k = corr(&ca[c], &cb[c]);
283 let (r, p) = rms_delta(&ca[c], &cb[c]);
284 min_c = min_c.min(k);
285 max_r = max_r.max(r);
286 println!("ch\t{c}\tcorr\t{k:.6}\trms\t{r:.8}\tpeak\t{p:.8}");
287 }
288 let pass = len_ok && min_c >= min_corr && max_r <= max_rms;
289 println!(
290 "verdict\t{}\tmin_corr={min_c:.6}\tmax_rms={max_r:.8}\tlen_ok={len_ok}",
291 if pass { "PASS" } else { "FAIL" }
292 );
293 eprintln!(
294 "audio-compare: {} — {channels}ch @{rate}, min corr {min_c:.6} (>= {min_corr}), \
295 max RMS delta {max_r:.8} (<= {max_rms}), lengths {na}/{nb}",
296 if pass { "PASS" } else { "FAIL" }
297 );
298 Ok(pass)
299}
300
301// -------------------------------------------------------------- video ------
302
303/// Raw-frame geometry for a pixel format: total samples, luma samples (0 when the
304/// format is packed and has no contiguous luma plane), bytes per sample, max value.
305struct PixGeom {
306 samples: usize,
307 luma: usize,
308 bps: usize,
309 max: f64,
310}
311
312fn pix_geom(pix_fmt: &str, w: usize, h: usize) -> Result<PixGeom, String> {
313 let wh = w * h;
314 let g = |samples: usize, luma: usize, bps: usize, max: f64| PixGeom {
315 samples,
316 luma,
317 bps,
318 max,
319 };
320 // Semi-planar formats carry their depth inside the name, so match them first.
321 match pix_fmt {
322 "nv12" | "nv21" => return Ok(g(wh * 3 / 2, wh, 1, 255.0)),
323 "p010le" | "p010be" => return Ok(g(wh * 3 / 2, wh, 2, 1023.0)),
324 "p016le" | "p016be" => return Ok(g(wh * 3 / 2, wh, 2, 65535.0)),
325 _ => {}
326 }
327 let mut base = pix_fmt;
328 let mut bps = 1;
329 let mut max = 255.0;
330 for (suffix, depth) in [("9", 9u32), ("10", 10), ("12", 12), ("14", 14), ("16", 16)] {
331 for endian in ["le", "be"] {
332 let s = format!("{suffix}{endian}");
333 if let Some(b) = pix_fmt.strip_suffix(&s) {
334 base = b;
335 bps = 2;
336 max = ((1u32 << depth) - 1) as f64;
337 }
338 }
339 }
340 let geom = match base {
341 "yuv420p" | "yuvj420p" => g(wh * 3 / 2, wh, bps, max),
342 "yuv422p" | "yuvj422p" => g(wh * 2, wh, bps, max),
343 "yuv444p" | "yuvj444p" | "gbrp" => g(wh * 3, wh, bps, max),
344 "gray" => g(wh, wh, bps, max),
345 // Packed: no contiguous luma plane, so luma PSNR falls back to all-plane.
346 "yuyv422" | "uyvy422" => g(wh * 2, 0, bps, max),
347 "rgb24" | "bgr24" => g(wh * 3, 0, bps, max),
348 "rgba" | "bgra" | "argb" | "abgr" => g(wh * 4, 0, bps, max),
349 _ => return Err(format!("unsupported pix_fmt for raw compare: {pix_fmt}")),
350 };
351 Ok(geom)
352}
353
354fn sample(buf: &[u8], i: usize, bps: usize) -> f64 {
355 if bps == 1 {
356 buf[i] as f64
357 } else {
358 u16::from_le_bytes([buf[2 * i], buf[2 * i + 1]]) as f64
359 }
360}
361
362/// PSNR over `n` samples starting at sample index `off` in both buffers.
363fn psnr(a: &[u8], b: &[u8], off: usize, n: usize, bps: usize, max: f64) -> f64 {
364 let mut sum = 0.0;
365 for i in off..off + n {
366 let d = sample(a, i, bps) - sample(b, i, bps);
367 sum += d * d;
368 }
369 let mse = sum / n as f64;
370 if mse == 0.0 {
371 f64::INFINITY
372 } else {
373 10.0 * (max * max / mse).log10()
374 }
375}
376
377fn cmd_video_compare(argv: &[String]) -> Result<bool, String> {
378 let a = Args::parse(argv)?;
379 if a.pos.len() != 2 {
380 return Err("video-compare needs <ours.raw> <ref-file>".into());
381 }
382 let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]);
383 let min_psnr: f64 = a.num("min-psnr", 40.0)?;
384
385 let probe = ffprobe(ref_path, "v:0", "width,height,pix_fmt")?;
386 let pix = match a.flags.get("pix-fmt") {
387 Some(v) => v.clone(),
388 None => probe
389 .get("pix_fmt")
390 .cloned()
391 .ok_or("could not probe pix_fmt; pass --pix-fmt")?,
392 };
393 let (w, h) = match a.flags.get("size") {
394 Some(s) => {
395 let (ws, hs) = s.split_once('x').ok_or("--size must look like 1920x1080")?;
396 (
397 ws.parse::<usize>().map_err(|_| "bad --size width")?,
398 hs.parse::<usize>().map_err(|_| "bad --size height")?,
399 )
400 }
401 None => (
402 probe
403 .get("width")
404 .ok_or("could not probe width; pass --size")?
405 .parse()
406 .map_err(|_| "bad probed width".to_string())?,
407 probe
408 .get("height")
409 .ok_or("could not probe height; pass --size")?
410 .parse()
411 .map_err(|_| "bad probed height".to_string())?,
412 ),
413 };
414
415 let geom = pix_geom(&pix, w, h)?;
416 let frame_bytes = geom.samples * geom.bps;
417 if frame_bytes == 0 {
418 return Err("frame size computed as zero".into());
419 }
420
421 let ours = read_file(ours_path)?;
422 let reference = ffmpeg_raw(
423 ref_path,
424 &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", &pix],
425 )?;
426 let (fa, fb) = (ours.len() / frame_bytes, reference.len() / frame_bytes);
427 let frames = fa.min(fb);
428
429 println!("meta\tours\t{ours_path}");
430 println!("meta\tref\t{ref_path}");
431 println!("meta\tpix_fmt\t{pix}");
432 println!("meta\tdims\t{w}x{h}");
433 println!("meta\tframe_bytes\t{frame_bytes}");
434 println!("meta\tframes_ours\t{fa}");
435 println!("meta\tframes_ref\t{fb}");
436 if frames == 0 {
437 println!("verdict\tFAIL\tno complete frame in common");
438 eprintln!("video-compare: FAIL — no complete frame in common ({fa} vs {fb})");
439 return Ok(false);
440 }
441
442 let luma_n = if geom.luma == 0 {
443 geom.samples
444 } else {
445 geom.luma
446 };
447 let mut min_y = f64::INFINITY;
448 let mut sum_y = 0.0;
449 let mut min_all = f64::INFINITY;
450 let mut sum_all = 0.0;
451 let mut finite_y = 0usize;
452 let mut finite_all = 0usize;
453 for f in 0..frames {
454 let off = f * geom.samples;
455 let py = psnr(&ours, &reference, off, luma_n, geom.bps, geom.max);
456 let pa = psnr(&ours, &reference, off, geom.samples, geom.bps, geom.max);
457 min_y = min_y.min(py);
458 min_all = min_all.min(pa);
459 if py.is_finite() {
460 sum_y += py;
461 finite_y += 1;
462 }
463 if pa.is_finite() {
464 sum_all += pa;
465 finite_all += 1;
466 }
467 println!("frame\t{f}\tpsnr_y\t{py:.4}\tpsnr_all\t{pa:.4}");
468 }
469 // Mean over finite frames only: identical frames give +inf and would otherwise
470 // poison the average of a run that also contains real differences.
471 let mean_y = if finite_y == 0 {
472 f64::INFINITY
473 } else {
474 sum_y / finite_y as f64
475 };
476 let mean_all = if finite_all == 0 {
477 f64::INFINITY
478 } else {
479 sum_all / finite_all as f64
480 };
481 let len_ok = fa == fb;
482 let pass = len_ok && min_y >= min_psnr;
483 println!("stats\tpsnr_y\tmin\t{min_y:.4}\tmean\t{mean_y:.4}");
484 println!("stats\tpsnr_all\tmin\t{min_all:.4}\tmean\t{mean_all:.4}");
485 println!(
486 "verdict\t{}\tmin_psnr_y={min_y:.4}\tframes={frames}\tlen_ok={len_ok}",
487 if pass { "PASS" } else { "FAIL" }
488 );
489 eprintln!(
490 "video-compare: {} — {frames} frames {w}x{h} {pix}, min luma PSNR {min_y:.4} dB \
491 (>= {min_psnr}), mean {mean_y:.4} dB, frame counts {fa}/{fb}",
492 if pass { "PASS" } else { "FAIL" }
493 );
494 Ok(pass)
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 #[test]
502 fn corr_identical_and_inverted() {
503 let a = [0.0, 1.0, -1.0, 0.5, -0.25];
504 let inv: Vec<f64> = a.iter().map(|x| -x).collect();
505 assert!((corr(&a, &a) - 1.0).abs() < 1e-12);
506 assert!((corr(&a, &inv) + 1.0).abs() < 1e-12);
507 // Silence vs silence correlates; silence vs DC offset does not.
508 assert_eq!(corr(&[0.0; 4], &[0.0; 4]), 1.0);
509 assert_eq!(corr(&[0.0; 4], &[1.0; 4]), 0.0);
510 }
511
512 #[test]
513 fn rms_and_peak_delta() {
514 let (r, p) = rms_delta(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]);
515 assert_eq!((r, p), (0.0, 0.0));
516 let (r, p) = rms_delta(&[1.0, -1.0], &[0.0, 0.0]);
517 assert!((r - 1.0).abs() < 1e-12 && (p - 1.0).abs() < 1e-12);
518 }
519
520 #[test]
521 fn psnr_identical_is_infinite_and_differing_is_finite() {
522 let a = vec![10u8, 20, 30, 40];
523 assert!(psnr(&a, &a, 0, 4, 1, 255.0).is_infinite());
524 let b = vec![11u8, 21, 31, 41];
525 let p = psnr(&a, &b, 0, 4, 1, 255.0);
526 // MSE 1 over 8-bit range: 10*log10(255^2) = 48.13 dB.
527 assert!((p - 48.1308).abs() < 1e-3, "psnr={p}");
528 // 10-bit path reads little-endian u16 pairs.
529 let x = [0u8, 1, 0, 1];
530 let y = [1u8, 1, 0, 1];
531 assert!(psnr(&x, &y, 0, 2, 2, 1023.0).is_finite());
532 }
533
534 #[test]
535 fn pix_geom_covers_the_generated_fixture_formats() {
536 let (w, h) = (1920, 1080);
537 let g = pix_geom("yuv420p", w, h).unwrap();
538 assert_eq!(
539 (g.samples, g.luma, g.bps, g.max),
540 (w * h * 3 / 2, w * h, 1, 255.0)
541 );
542 let g = pix_geom("yuv420p10le", w, h).unwrap();
543 assert_eq!(
544 (g.samples, g.luma, g.bps, g.max),
545 (w * h * 3 / 2, w * h, 2, 1023.0)
546 );
547 let g = pix_geom("p010le", w, h).unwrap();
548 assert_eq!((g.samples, g.bps, g.max), (w * h * 3 / 2, 2, 1023.0));
549 assert_eq!(pix_geom("yuv444p", w, h).unwrap().samples, w * h * 3);
550 assert_eq!(pix_geom("yuyv422", w, h).unwrap().luma, 0);
551 assert!(pix_geom("no_such_fmt", w, h).is_err());
552 }
553
554 #[test]
555 fn deinterleave_splits_channels() {
556 let mut buf = Vec::new();
557 for f in 0..3u32 {
558 for c in 0..2u32 {
559 buf.extend_from_slice(&((f * 10 + c) as f32).to_le_bytes());
560 }
561 }
562 let ch = deinterleave_f32(&buf, 2);
563 assert_eq!(ch[0], vec![0.0, 10.0, 20.0]);
564 assert_eq!(ch[1], vec![1.0, 11.0, 21.0]);
565 }
566
567 #[test]
568 fn args_parse_flags_and_positionals() {
569 let argv: Vec<String> = ["a.raw", "b.mp4", "--min-corr", "0.5"]
570 .iter()
571 .map(|s| s.to_string())
572 .collect();
573 let a = Args::parse(&argv).unwrap();
574 assert_eq!(a.pos, ["a.raw", "b.mp4"]);
575 assert_eq!(a.num::<f64>("min-corr", 0.999).unwrap(), 0.5);
576 assert_eq!(a.num::<f64>("max-rms", 1e-3).unwrap(), 1e-3);
577 assert!(Args::parse(&["--dangling".to_string()]).is_err());
578 }
579}