diff --git a/crates/ec-hw/examples/hw_oracle.rs b/crates/ec-hw/examples/hw_oracle.rs new file mode 100644 index 00000000..03bf66c5 --- /dev/null +++ b/crates/ec-hw/examples/hw_oracle.rs @@ -0,0 +1,139 @@ +//! Decodes each stream through HwDecoder and compares every frame with ffmpeg's software decode (framecrc, all planes). +//! +//! ```text +//! cargo run --release -p ec-hw --example hw_oracle -- ... +//! ``` + +use std::fs; +use std::path::Path; +use std::process::Command; + +use ec_hw::{Backend, Codec, HwDecoder}; + +fn main() { + let mut failed = 0; + for path in std::env::args().skip(1) { + let line = match check(Path::new(&path)) { + Ok((backend, frames)) if backend == Backend::Vk => format!("PASS {path} Vk {frames} frames"), + Ok((backend, frames)) => { + failed += 1; + format!("FALLBACK {path} {backend:?} {frames} frames") + } + Err(e) => { + failed += 1; + format!("FAIL {path}: {e}") + } + }; + println!("{line}"); + } + std::process::exit(i32::from(failed > 0)); +} + +fn check(path: &Path) -> Result<(Backend, usize), String> { + let data = fs::read(path).map_err(|e| e.to_string())?; + let (codec, units) = split(path, &data)?; + let (wide, expected) = reference(path)?; + let mut decoder = HwDecoder::open(codec).map_err(|e| format!("open: {e}"))?; + let mut ours = Vec::new(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).map_err(|e| format!("decode unit {pts}: {e}"))?; + drain(&mut decoder, wide, &mut ours)?; + } + decoder.flush().map_err(|e| format!("flush: {e}"))?; + drain(&mut decoder, wide, &mut ours)?; + let backend = decoder.backend(); + for (index, (got, want)) in ours.iter().zip(&expected).enumerate() { + if got != want { + return Err(format!("{backend:?} frame {index}: ours {got:?}, ffmpeg {want:?}")); + } + } + if ours.len() != expected.len() { + return Err(format!("{backend:?} frame count: ours {}, ffmpeg {}", ours.len(), expected.len())); + } + Ok((backend, ours.len())) +} + +fn drain(decoder: &mut HwDecoder, wide: bool, out: &mut Vec<(usize, u32)>) -> Result<(), String> { + while let Some(picture) = decoder.next_picture().map_err(|e| format!("next picture: {e}"))? { + let bytes = if wide { + let frame = picture.to_i420_16().map_err(|e| format!("to_i420_16: {e}"))?; + [frame.y, frame.u, frame.v] + .concat() + .iter() + .flat_map(|s| s.to_le_bytes()) + .collect() + } else { + let frame = picture.to_i420().map_err(|e| format!("to_i420: {e}"))?; + [frame.y, frame.u, frame.v].concat() + }; + out.push((bytes.len(), adler32(&bytes))); + } + Ok(()) +} + +fn split<'a>(path: &Path, data: &'a [u8]) -> Result<(Codec, Vec<&'a [u8]>), String> { + match path.extension().and_then(|e| e.to_str()) { + Some("h264" | "264") => Ok((Codec::H264, vec![data])), + Some("hevc" | "h265" | "265") => Ok((Codec::H265, vec![data])), + Some("ivf") => { + let codec = match &data[8..12] { + b"AV01" => Codec::Av1, + b"VP90" => Codec::Vp9, + other => return Err(format!("ivf fourcc {other:?}")), + }; + Ok((codec, ivf_units(data))) + } + other => Err(format!("unknown extension {other:?}")), + } +} + +fn ivf_units(ivf: &[u8]) -> Vec<&[u8]> { + let mut pos = usize::from(u16::from_le_bytes([ivf[6], ivf[7]])); + let mut units = Vec::new(); + while pos + 12 <= ivf.len() { + let len = u32::from_le_bytes(ivf[pos..pos + 4].try_into().expect("frame size")) as usize; + units.push(&ivf[pos + 12..(pos + 12 + len).min(ivf.len())]); + pos += 12 + len; + } + units +} + +fn reference(path: &Path) -> Result<(bool, Vec<(usize, u32)>), String> { + let probe = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt", "-of", "csv=p=0"]) + .arg(path) + .output() + .map_err(|e| e.to_string())?; + let wide = String::from_utf8_lossy(&probe.stdout).contains("10"); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-noautoscale", "-pix_fmt", if wide { "yuv420p10le" } else { "yuv420p" }, "-f", "framecrc", "-"]) + .output() + .map_err(|e| e.to_string())?; + if !out.status.success() { + return Err(format!("ffmpeg: {}", String::from_utf8_lossy(&out.stderr).lines().next().unwrap_or(""))); + } + let frames = String::from_utf8_lossy(&out.stdout) + .lines() + .filter(|l| !l.starts_with('#')) + .filter_map(|l| { + let f: Vec<&str> = l.split(',').map(str::trim).collect(); + Some((f.get(4)?.parse().ok()?, u32::from_str_radix(f.get(5)?.trim_start_matches("0x"), 16).ok()?)) + }) + .collect(); + Ok((wide, frames)) +} + +fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (0u32, 0u32); + for chunk in data.chunks(5552) { + for &x in chunk { + a += u32::from(x); + b += a; + } + a %= 65521; + b %= 65521; + } + b << 16 | a +}