//! Vulkan Video against VA-API on the same clips: H.264, HEVC and AV1 encode at three CQP and three CBR points, reporting bytes, kbps, PSNR-Y against the source and encode ms/frame; then decode ms/frame of the CBR 3 Mb/s streams with both decoders. //! //! Every encode and decode runs in a child process of this binary, because the driver's state outlives a display: within one process the same encode lands at different sizes depending on what ran before it. //! //! ```text //! ``` use std::fmt::Display; use std::fs; use std::os::unix::fs::FileExt; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Instant; use ec_hw::{ Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, RateControlMode, }; const FRAMES: usize = 60; const FPS: u32 = 30; const GOP: u32 = 30; const SIZES: [(u32, u32); 2] = [(1280, 720), (1920, 1080)]; const SOURCES: [&str; 2] = ["testsrc2", "mandelbrot"]; const CBR: [u32; 3] = [1_000_000, 3_000_000, 6_000_000]; const DECODE_BITRATE: u32 = 3_000_000; const JOB: &str = "HW_PARITY_JOB"; #[derive(Clone, Copy)] enum Mode { Cqp(u32), Cbr(u32), } impl Mode { fn label(self) -> String { match self { Mode::Cqp(qp) => format!("CQP {qp}"), Mode::Cbr(bps) => format!("CBR {}M", bps / 1_000_000), } } fn env(self) -> (&'static str, u32) { match self { Mode::Cqp(qp) => ("cqp", qp), Mode::Cbr(bps) => ("cbr", bps), } } } #[derive(Clone, Copy)] struct Spec { name: &'static str, key: &'static str, format: &'static str, enc: EncCodec, dec: Codec, } const SPECS: [Spec; 3] = [ Spec { name: "H.264", key: "h264", format: "h264", enc: EncCodec::H264, dec: Codec::H264, }, Spec { name: "HEVC", key: "hevc", format: "hevc", enc: EncCodec::H265, dec: Codec::H265, }, Spec { name: "AV1", key: "av1", format: "obu", enc: EncCodec::Av1, dec: Codec::Av1, }, ]; fn modes(spec: Spec) -> Vec { let qps = if spec.key == "av1" { [110, 135, 160] } else { [22, 27, 32] }; qps.into_iter() .map(Mode::Cqp) .chain(CBR.into_iter().map(Mode::Cbr)) .collect() } fn backend_key(backend: Backend) -> &'static str { match backend { Backend::Vk => "vk", Backend::Va => "va", } } fn backend_from_key(key: &str) -> Backend { match key { "vk" => Backend::Vk, _ => Backend::Va, } } fn spec_from_key(key: &str) -> Spec { *SPECS.iter().find(|s| s.key == key).expect("known codec key") } fn make_source(dir: &Path, source: &str, w: u32, h: u32) -> PathBuf { let path = dir.join(format!("{source}-{w}x{h}.yuv")); if !path.exists() { let status = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) .arg(format!("{source}=size={w}x{h}:rate={FPS}")) .args(["-frames:v", &FRAMES.to_string(), "-pix_fmt", "yuv420p", "-f", "rawvideo"]) .arg(&path) .status() .expect("run ffmpeg"); assert!(status.success(), "ffmpeg cannot generate {source}"); } path } fn read_frames(path: &Path, w: u32, h: u32) -> Vec { let (wu, hu) = (w as usize, h as usize); let (cw, ch) = (wu / 2, hu / 2); let file = fs::File::open(path).expect("source clip"); (0..FRAMES as u64) .map(|t| { let len = wu * hu + 2 * cw * ch; let mut buf = vec![0u8; len]; file.read_exact_at(&mut buf, t * len as u64) .expect("read picture"); let (y, rest) = buf.split_at(wu * hu); let (u, v) = rest.split_at(cw * ch); I420 { y: y.to_vec(), u: u.to_vec(), v: v.to_vec(), width: w, height: h, } }) .collect() } fn write_aus(path: &Path, aus: &[Vec]) { let mut out = Vec::new(); for au in aus { out.extend_from_slice(&(au.len() as u32).to_le_bytes()); out.extend_from_slice(au); } fs::write(path, out).expect("write access units"); } fn read_aus(path: &Path) -> Vec> { let data = fs::read(path).expect("read access units"); let mut aus = Vec::new(); let mut at = 0; while at + 4 <= data.len() { let len = u32::from_le_bytes(data[at..at + 4].try_into().expect("4 bytes")) as usize; aus.push(data[at + 4..at + 4 + len].to_vec()); at += 4 + len; } aus } fn or_exit(result: Result) -> T { match result { Ok(value) => value, Err(e) => { println!("ERR {e}"); std::process::exit(3) } } } fn encode_job() { let env = |k: &str| std::env::var(k).expect("job variable"); let num = |k: &str| env(k).parse::().expect("job number"); let spec = spec_from_key(&env("CODEC")); let (w, h) = (num("W"), num("H")); let backend = backend_from_key(&env("BACKEND")); let value = num("VALUE"); let mode = if env("MODE") == "cqp" { Mode::Cqp(value) } else { Mode::Cbr(value) }; let frames = read_frames(Path::new(&env("SOURCE")), w, h); let mut config = EncoderConfig::new(spec.enc, w, h); config.framerate = (FPS, 1); config.gop_size = GOP; match mode { Mode::Cqp(qp) => config.rate_control = RateControlMode::ConstantQp { qp }, Mode::Cbr(bps) => { config.bitrate = bps; config.rate_control = RateControlMode::ConstantBitrate; } } let mut encoder = or_exit(HwEncoder::open(config, Some(backend))); let mut aus = Vec::with_capacity(frames.len()); let start = Instant::now(); for (t, frame) in frames.iter().enumerate() { let coded = or_exit(encoder.encode( frame, FrameMetadata { timestamp: t as i64, force_keyframe: false, }, )); aus.push(coded.data); } let ms = start.elapsed().as_secs_f64() * 1000.0 / frames.len() as f64; write_aus(Path::new(&env("OUT")), &aus); println!("ENC ms={ms:.3} backend={:?}", encoder.backend()); } fn decode_job() { let env = |k: &str| std::env::var(k).expect("job variable"); let spec = spec_from_key(&env("CODEC")); let backend = backend_from_key(&env("BACKEND")); let aus = read_aus(Path::new(&env("AUS"))); let mut frames = 0usize; let elapsed = match backend { Backend::Vk => { let mut decoder = or_exit(HwDecoder::open(spec.dec)); if decoder.backend() != Backend::Vk { println!("ERR opened on {:?}", decoder.backend()); std::process::exit(3) } let start = Instant::now(); for (t, au) in aus.iter().enumerate() { or_exit(decoder.decode(au, t as i64)); while or_exit(decoder.next_frame()).is_some() { frames += 1; } } or_exit(decoder.flush()); while or_exit(decoder.next_frame()).is_some() { frames += 1; } start.elapsed() } Backend::Va => { let display = or_exit(ec_va::open()); let mut decoder = or_exit(ec_hw::Decoder::new(&display, spec.dec)); let start = Instant::now(); for (t, au) in aus.iter().enumerate() { or_exit(decoder.decode(au, t as i64)); while let Some(frame) = decoder.next_frame() { or_exit(frame.to_i420()); frames += 1; } } or_exit(decoder.flush()); while let Some(frame) = decoder.next_frame() { or_exit(frame.to_i420()); frames += 1; } start.elapsed() } }; if frames != FRAMES { println!("ERR decoded {frames} of {FRAMES} frames"); std::process::exit(3) } println!("DEC ms={:.3}", elapsed.as_secs_f64() * 1000.0 / FRAMES as f64); } fn run_job(me: &Path, envs: &[(&str, String)]) -> Result { let output = Command::new(me) .envs(envs.iter().map(|(k, v)| (*k, v.as_str()))) .output() .expect("run child job"); let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); if output.status.success() { Ok(stdout) } else { let reason = stdout .lines() .rev() .find(|l| l.starts_with("ERR")) .unwrap_or("child failed") .to_string(); Err(reason) } } fn field(out: &str, key: &str) -> Option { out.lines() .find_map(|l| l.strip_prefix(key)) .and_then(|rest| rest.split_whitespace().next()) .and_then(|v| v.parse().ok()) } fn psnr_y(stream: &Path, format: &str, source: &Path, (w, h): (u32, u32)) -> Option { let rate = FPS.to_string(); let size = format!("{w}x{h}"); let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) .arg(stream) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", &size, "-r", &rate, "-i"]) .arg(source) .args(["-lavfi", "psnr", "-f", "null", "-"]) .output() .ok()?; let text = String::from_utf8_lossy(&out.stderr); let at = text.rfind("PSNR y:")?; text[at + "PSNR y:".len()..] .split_whitespace() .next()? .parse::() .ok() .filter(|v| !v.is_nan()) } struct Row { bytes: usize, ms: f64, psnr: Option, } fn encode_row( me: &Path, dir: &Path, tag: &str, raw: &Path, (w, h): (u32, u32), spec: Spec, mode: Mode, backend: Backend, ) -> Result<(Row, PathBuf), String> { let (mode_key, value) = mode.env(); let aus_path = dir.join(format!("{tag}.aus")); let out = run_job( me, &[ (JOB, "enc".to_string()), ("CODEC", spec.key.to_string()), ("W", w.to_string()), ("H", h.to_string()), ("BACKEND", backend_key(backend).to_string()), ("MODE", mode_key.to_string()), ("VALUE", value.to_string()), ("SOURCE", raw.display().to_string()), ("OUT", aus_path.display().to_string()), ], )?; let ms = field(&out, "ENC ms=").ok_or("no timing from encode job")?; let aus = read_aus(&aus_path); let stream = dir.join(format!("{tag}.{}", spec.format)); fs::write(&stream, aus.concat()).expect("write stream"); let row = Row { bytes: aus.iter().map(Vec::len).sum(), ms, psnr: psnr_y(&stream, spec.format, raw, (w, h)), }; Ok((row, aus_path)) } fn decode_ms(me: &Path, aus: &Path, spec: Spec, backend: Backend) -> Result { let out = run_job( me, &[ (JOB, "dec".to_string()), ("CODEC", spec.key.to_string()), ("BACKEND", backend_key(backend).to_string()), ("AUS", aus.display().to_string()), ], )?; field(&out, "DEC ms=").ok_or_else(|| "no timing from decode job".to_string()) } fn cell(v: Option, digits: usize) -> String { match v { Some(v) => format!("{v:.digits$}"), None => "n/a".to_string(), } } fn main() { if let Ok(job) = std::env::var(JOB) { match job.as_str() { "enc" => encode_job(), _ => decode_job(), } return; } let dir = std::env::temp_dir(); let me = std::env::current_exe().expect("own path"); let mut decode_inputs: Vec<(&'static str, (u32, u32), Spec, Backend, PathBuf)> = Vec::new(); for source in SOURCES { for (w, h) in SIZES { let raw = make_source(&dir, source, w, h); println!("== {source} {w}x{h}, {FRAMES} frames at {FPS} fps =="); println!( "{:<6} {:<8} {:<4} {:>9} {:>7} {:>8} {:>9}", "codec", "rc", "enc", "bytes", "kbps", "PSNR-Y", "ms/frame" ); for spec in SPECS { for mode in modes(spec) { for backend in [Backend::Vk, Backend::Va] { let tag = format!( "{source}-{w}x{h}-{}-{}-{}", spec.key, mode.label().replace(' ', ""), backend_key(backend) ); let label = mode.label(); let name = format!("{backend:?}"); match encode_row(&me, &dir, &tag, &raw, (w, h), spec, mode, backend) { Ok((row, aus)) => { let kbps = row.bytes as f64 * 8.0 * f64::from(FPS) / FRAMES as f64 / 1000.0; println!( "{:<6} {:<8} {:<4} {:>9} {:>7.0} {:>8} {:>9.2}", spec.name, label, name, row.bytes, kbps, cell(row.psnr, 2), row.ms ); if matches!(mode, Mode::Cbr(b) if b == DECODE_BITRATE) { decode_inputs.push((source, (w, h), spec, backend, aus)); } } Err(reason) => println!( "{:<6} {:<8} {:<4} n/a: {reason}", spec.name, label, name ), } } } } println!(); } } println!("== decode, CBR {}M streams, ms/frame ==", DECODE_BITRATE / 1_000_000); println!( "{:<6} {:<10} {:<9} {:<4} {:>10} {:>10}", "codec", "source", "res", "enc", "Vk dec", "VA dec" ); for (source, (w, h), spec, enc_backend, aus) in &decode_inputs { let vk = decode_ms(&me, aus, *spec, Backend::Vk); let va = decode_ms(&me, aus, *spec, Backend::Va); println!( "{:<6} {:<10} {:<9} {:<4} {:>10} {:>10}", spec.name, source, format!("{w}x{h}"), format!("{enc_backend:?}"), cell(vk.ok(), 2), cell(va.ok(), 2) ); } }