diff --git a/crates/ec-hw/examples/hw_parity.rs b/crates/ec-hw/examples/hw_parity.rs new file mode 100644 index 00000000..14f3901e --- /dev/null +++ b/crates/ec-hw/examples/hw_parity.rs @@ -0,0 +1,466 @@ +//! 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 +//! cargo run --release -p ec-hw --example hw_parity -- +//! ``` + +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 = Command::new("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 = Command::new("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 = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + 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) + ); + } +} diff --git a/crates/ec-hw/src/error.rs b/crates/ec-hw/src/error.rs index 970b1628..051a720a 100644 --- a/crates/ec-hw/src/error.rs +++ b/crates/ec-hw/src/error.rs @@ -87,7 +87,13 @@ impl From for Error { impl From for Error { fn from(e: ec_vk::Error) -> Error { - Error::Vk(e.to_string()) + match e { + ec_vk::Error::DeviceLost(call) => { + crate::reset::report_gpu_reset(); + Error::hw_reset(format!("Vulkan device lost in {call}")) + } + other => Error::Vk(other.to_string()), + } } } diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 1d84309f..1a983868 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -6,6 +6,8 @@ use std::os::fd::BorrowedFd; #[cfg(target_os = "linux")] use ec_vk::DmaBuf; +use std::cell::RefCell; + use crate::error::{Error, Result}; use crate::picture::{Decoded, I420, RgbPicture}; #[cfg(target_os = "linux")] @@ -58,11 +60,41 @@ pub struct Capability { } thread_local! { - static GPU: Option = ec_vk::Gpu::open().ok(); + static GPU: RefCell)>> = const { RefCell::new(None) }; } pub(crate) fn vk_gpu() -> Option { - GPU.with(|gpu| gpu.clone()) + GPU.with_borrow_mut(|cached| { + let epoch = crate::reset::gpu_reset_epoch(); + match cached { + Some((born, gpu)) if *born == epoch => gpu.clone(), + _ => { + let gpu = ec_vk::Gpu::open().ok(); + *cached = Some((epoch, gpu.clone())); + gpu + } + } + }) +} + +fn vk_session_alive(born_epoch: u64) -> Result<()> { + if crate::reset::gpu_reset_epoch() == born_epoch { + Ok(()) + } else { + Err(Error::hw_reset( + "the GPU was reset after this Vulkan session was created; its device is lost", + )) + } +} + +fn vk_grace() -> Result<()> { + if crate::reset::gpu_recently_reset() { + Err(Error::hw_reset( + "the GPU was reset moments ago; new Vulkan sessions wait out the grace period", + )) + } else { + Ok(()) + } } /// Every codec, direction and backend this machine can use. Never fails. @@ -336,6 +368,7 @@ enum EncInner { /// A hardware encoder on whichever backend opened. pub struct HwEncoder { inner: EncInner, + born_epoch: u64, config: EncoderConfig, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] size: (usize, usize), @@ -350,11 +383,13 @@ impl HwEncoder { }; let mut reasons = Vec::new(); for backend in order { + let born_epoch = crate::reset::gpu_reset_epoch(); match open_backend(backend, config) { Ok(inner) => { let size = (config.width as usize, config.height as usize); return Ok(HwEncoder { inner, + born_epoch, config, size, }); @@ -381,6 +416,7 @@ impl HwEncoder { pub fn tune(&mut self, tunings: Tunings) -> Result<()> { match &mut self.inner { EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; let rate = match self.config.rate_control { RateControlMode::ConstantQp { .. } => vk_rate(&self.config), _ => ec_vk::RateControl::Cbr { @@ -399,6 +435,7 @@ impl HwEncoder { pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { match &mut self.inner { EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; let coded = enc.encode(frame, meta.force_keyframe)?; Ok(CodedFrame { data: coded.data, @@ -415,6 +452,7 @@ impl HwEncoder { pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result { match &mut self.inner { EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; let coded = enc.encode_rgb(frame, meta.force_keyframe)?; Ok(CodedFrame { data: coded.data, @@ -436,6 +474,7 @@ impl HwEncoder { ) -> Result { match &mut self.inner { EncInner::Vk(enc) => { + vk_session_alive(self.born_epoch)?; let coded = enc.encode_dmabuf(frame, meta.force_keyframe)?; Ok(CodedFrame { data: coded.data, @@ -459,6 +498,7 @@ fn open_backend(backend: Backend, config: EncoderConfig) -> Result { } fn open_vk(config: EncoderConfig) -> Result { + vk_grace()?; if config.bit_depth != 8 { return Err(Error::unsupported( "10-bit Vulkan Video encode", @@ -594,6 +634,7 @@ enum Mode { /// A hardware decoder on whichever backend opened. pub struct HwDecoder { inner: DecInner, + born_epoch: u64, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] codec: Codec, mode: Mode, @@ -618,16 +659,18 @@ impl HwDecoder { Mode::Rgb(output) => Some(output), }; let mut reasons = Vec::new(); - let vk = match codec { + let born_epoch = crate::reset::gpu_reset_epoch(); + let vk = vk_grace().and_then(|()| match codec { Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264), Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265), Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1), _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), - }; + }); match vk { Ok(inner) => { return Ok(HwDecoder { inner: DecInner::Vk(inner), + born_epoch, codec, mode, replay: Some(Vec::new()), @@ -644,6 +687,7 @@ impl HwDecoder { Ok(inner) => { return Ok(HwDecoder { inner: DecInner::Va(inner), + born_epoch, codec, mode, replay: None, @@ -670,8 +714,9 @@ impl HwDecoder { /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first /// picture comes out moves to VA-API on Linux, replaying what was fed so far. pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + let born_epoch = self.born_epoch; let result = match &mut self.inner { - DecInner::Vk(d) => d.decode(data, timestamp), + DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)), #[cfg(target_os = "linux")] DecInner::Va(d) => d.decode(data, timestamp), }; @@ -722,6 +767,7 @@ impl HwDecoder { fn pull(&mut self) -> Result> { match &mut self.inner { DecInner::Vk(d) => { + vk_session_alive(self.born_epoch)?; let frame = d.next_frame(); if frame.is_some() { self.replay = None; diff --git a/crates/ec-hw/tests/intra_rate.rs b/crates/ec-hw/tests/intra_rate.rs index 2525ef61..7a48ee64 100644 --- a/crates/ec-hw/tests/intra_rate.rs +++ b/crates/ec-hw/tests/intra_rate.rs @@ -24,10 +24,8 @@ use std::fs::File; use std::os::unix::fs::FileExt; use std::path::{Path, PathBuf}; use std::process::Command; -use std::rc::Rc; -use ec_hw::{EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode}; -use ec_va::Display; +use ec_hw::{Backend, EncCodec, EncoderConfig, FrameMetadata, HwEncoder, I420, RateControlMode}; const WIDTH: u32 = 1280; const HEIGHT: u32 = 720; @@ -41,20 +39,30 @@ const CHILD_CODEC: &str = "EC_INTRA_RATE_CODEC"; const CHILD_GOP: &str = "EC_INTRA_RATE_GOP"; const CHILD_BITRATE: &str = "EC_INTRA_RATE_BITRATE"; const CHILD_MODE: &str = "EC_INTRA_RATE_MODE"; +const CHILD_BACKEND: &str = "EC_INTRA_RATE_BACKEND"; const CHILD_SOURCE: &str = "EC_INTRA_RATE_SOURCE"; const CHILD_OUT: &str = "EC_INTRA_RATE_OUT"; const DELIVERED_LINE: &str = "DELIVERED_BPS="; -fn display() -> Option> { - match ec_va::open() { - Ok(display) => Some(display), - Err(e) => { - eprintln!("skipped: no VA display ({e})"); - None - } +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 opens(codec: EncCodec, backend: Backend) -> bool { + let config = EncoderConfig::new(codec, WIDTH, HEIGHT); + HwEncoder::open(config, Some(backend)).is_ok() +} + fn scratch() -> PathBuf { let dir = std::env::temp_dir().join("ec-hw-intra-rate"); std::fs::create_dir_all(&dir).expect("scratch dir"); @@ -104,19 +112,19 @@ fn picture(file: &File, t: u32) -> I420 { /// One encode of the clip with an IDR every `gop` pictures: the stream, and the /// bits per second it actually spent. fn encode( + backend: Backend, codec: EncCodec, gop: u32, bitrate: u32, rate_control: RateControlMode, raw: &File, ) -> (Vec, f64) { - let display = display().expect("a VA display"); let mut config = EncoderConfig::new(codec, WIDTH, HEIGHT); config.framerate = (FPS, 1); config.gop_size = gop; config.bitrate = bitrate; config.rate_control = rate_control; - let mut encoder = Encoder::new(&display, config).expect("encoder"); + let mut encoder = HwEncoder::open(config, Some(backend)).expect("encoder"); let mut out = Vec::new(); for t in 0..FRAMES { let coded = encoder @@ -179,8 +187,9 @@ fn one_encode_in_its_own_process() { }, _ => RateControlMode::ConstantBitrate, }; + let backend = backend_from_key(&std::env::var(CHILD_BACKEND).expect("backend")); let raw = File::open(std::env::var(CHILD_SOURCE).expect("source")).expect("source clip"); - let (stream, delivered) = encode(codec, gop, bitrate, rate_control, &raw); + let (stream, delivered) = encode(backend, codec, gop, bitrate, rate_control, &raw); std::fs::write(std::env::var(CHILD_OUT).expect("out"), &stream).expect("write stream"); println!("{DELIVERED_LINE}{delivered}"); } @@ -188,6 +197,7 @@ fn one_encode_in_its_own_process() { /// One encode in a child process of this test binary. Returns the stream's /// delivered bits per second, written to `out`. fn encode_in_its_own_process( + backend: Backend, codec: EncCodec, gop: u32, bitrate: u32, @@ -207,6 +217,7 @@ fn encode_in_its_own_process( .env(CHILD_GOP, gop.to_string()) .env(CHILD_BITRATE, bitrate.to_string()) .env(CHILD_MODE, if coarsest_qp { "coarsest" } else { "cbr" }) + .env(CHILD_BACKEND, backend_key(backend)) .env(CHILD_SOURCE, source) .env(CHILD_OUT, out) .output() @@ -252,9 +263,6 @@ fn psnr(coded: &Path, format: &str, source: &Path) -> Option { #[test] fn cbr_lands_within_five_percent_on_intra_only_and_gop_30() { - if display().is_none() { - return; - } let dir = scratch(); let Some(source) = testsrc2_raw(&dir) else { eprintln!("skipped: ffmpeg cannot generate testsrc2"); @@ -265,40 +273,47 @@ fn cbr_lands_within_five_percent_on_intra_only_and_gop_30() { println!( "CBR, testsrc2 {WIDTH}x{HEIGHT} {FPS} fps, {FRAMES} pictures (floor = coarsest quantiser):" ); - for (codec, name, format) in [ - (EncCodec::H264, "H.264", "h264"), - (EncCodec::H265, "HEVC", "hevc"), - (EncCodec::Av1, "AV1", "obu"), - ] { - for gop in GOPS { - // The smallest stream this codec makes for the clip at this GOP. - let floor_path = dir.join(format!("{name}-gop{gop}-floor.{format}")); - let floor = encode_in_its_own_process(codec, gop, 0, true, &source, &floor_path); - for bitrate in BITRATES { - let coded = dir.join(format!("{name}-gop{gop}-{bitrate}.{format}")); - let delivered = - encode_in_its_own_process(codec, gop, bitrate, false, &source, &coded); - let db = psnr(&coded, format, &source).unwrap_or(f64::NAN); - let error = delivered / f64::from(bitrate) - 1.0; - let at_floor = - f64::from(bitrate) < floor && (delivered / floor - 1.0).abs() <= 0.05; - println!( - " {name:<6} GOP {gop:>2} request {:>5} kbps -> {:>6.0} kbps ({:+6.1}%), floor {:>6.0} kbps, {db:.2} dB{}", - bitrate / 1000, - delivered / 1000.0, - error * 100.0, - floor / 1000.0, - if at_floor { - " (at the coarsest quantiser)" - } else { - "" + for backend in [Backend::Va, Backend::Vk] { + for (codec, name, format) in [ + (EncCodec::H264, "H.264", "h264"), + (EncCodec::H265, "HEVC", "hevc"), + (EncCodec::Av1, "AV1", "obu"), + ] { + if !opens(codec, backend) { + println!(" {backend:?} {name}: skipped, the encoder does not open"); + continue; + } + for gop in GOPS { + let floor_path = dir.join(format!("{backend:?}-{name}-gop{gop}-floor.{format}")); + let floor = + encode_in_its_own_process(backend, codec, gop, 0, true, &source, &floor_path); + for bitrate in BITRATES { + let coded = dir.join(format!("{backend:?}-{name}-gop{gop}-{bitrate}.{format}")); + let delivered = encode_in_its_own_process( + backend, codec, gop, bitrate, false, &source, &coded, + ); + let db = psnr(&coded, format, &source).unwrap_or(f64::NAN); + let error = delivered / f64::from(bitrate) - 1.0; + let at_floor = + f64::from(bitrate) < floor && (delivered / floor - 1.0).abs() <= 0.05; + println!( + " {backend:?} {name:<6} GOP {gop:>2} request {:>5} kbps -> {:>6.0} kbps ({:+6.1}%), floor {:>6.0} kbps, {db:.2} dB{}", + bitrate / 1000, + delivered / 1000.0, + error * 100.0, + floor / 1000.0, + if at_floor { + " (at the coarsest quantiser)" + } else { + "" + } + ); + if error.abs() > 0.05 && !at_floor { + failures.push(format!( + "{backend:?} {name} GOP {gop} at {bitrate} bps: {:+.1}%", + error * 100.0 + )); } - ); - if error.abs() > 0.05 && !at_floor { - failures.push(format!( - "{name} GOP {gop} at {bitrate} bps: {:+.1}%", - error * 100.0 - )); } } } diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index 6a950550..d5eb05b3 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -70,6 +70,8 @@ pub enum Error { NoDevice, /// A Vulkan call failed: VkResult code and call name. Vk(i32, &'static str), + /// The device was lost (VK_ERROR_DEVICE_LOST): a GPU reset or a hung queue. Every object on it is dead. + DeviceLost(&'static str), /// The requested codec or direction is not supported. Unsupported(String), /// The caller passed an invalid picture, buffer or sequence state. @@ -82,6 +84,7 @@ impl fmt::Display for Error { Error::NoLoader(e) => write!(f, "no Vulkan loader: {e}"), Error::NoDevice => write!(f, "no Vulkan Video device"), Error::Vk(code, call) => write!(f, "{call} failed: VkResult {code}"), + Error::DeviceLost(call) => write!(f, "{call} failed: device lost"), Error::Unsupported(what) => write!(f, "unsupported: {what}"), Error::Invalid(what) => write!(f, "invalid: {what}"), } @@ -172,7 +175,7 @@ fn queue_families(instance: &Instance, physical: vk::PhysicalDevice) -> Families fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Families), Error> { let devices = unsafe { instance.enumerate_physical_devices() } - .map_err(|c| Error::Vk(c.as_raw(), "vkEnumeratePhysicalDevices"))?; + .map_err(|c| crate::session::vk_error(c, "vkEnumeratePhysicalDevices"))?; let (physical, families) = devices .into_iter() .find_map(|pd| { @@ -198,7 +201,7 @@ fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Fam let available: Vec = unsafe { instance.enumerate_device_extension_properties(physical, None) } - .map_err(|c| Error::Vk(c.as_raw(), "vkEnumerateDeviceExtensionProperties"))? + .map_err(|c| crate::session::vk_error(c, "vkEnumerateDeviceExtensionProperties"))? .iter() .map(|e| e.extension_name) .collect(); @@ -233,7 +236,7 @@ fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Fam .enabled_extension_names(&names) .push_next(&mut features); let device = unsafe { instance.create_device(physical, &info, None) } - .map_err(|c| Error::Vk(c.as_raw(), "vkCreateDevice"))?; + .map_err(|c| crate::session::vk_error(c, "vkCreateDevice"))?; let name = unsafe { instance.get_physical_device_properties(physical) } .device_name @@ -256,7 +259,7 @@ impl Gpu { let app = vk::ApplicationInfo::builder().api_version(vk::make_version(1, 3, 0)); let info = vk::InstanceCreateInfo::builder().application_info(&app); let instance = unsafe { entry.create_instance(&info, None) } - .map_err(|c| Error::Vk(c.as_raw(), "vkCreateInstance"))?; + .map_err(|c| crate::session::vk_error(c, "vkCreateInstance"))?; match setup(&instance) { Ok((physical, device, name, families)) => Ok(Gpu { inner: Arc::new(Inner { @@ -483,7 +486,7 @@ impl Gpu { &mut caps, ) } - .map_err(|c| Error::Vk(c.as_raw(), "vkGetPhysicalDeviceVideoCapabilitiesKHR"))?; + .map_err(|c| crate::session::vk_error(c, "vkGetPhysicalDeviceVideoCapabilitiesKHR"))?; Ok(CodecCaps { codec, direction, diff --git a/shims/vk-video-ffi/src/rgb_convert.rs b/shims/vk-video-ffi/src/rgb_convert.rs index 539aefe9..d4c43cbf 100644 --- a/shims/vk-video-ffi/src/rgb_convert.rs +++ b/shims/vk-video-ffi/src/rgb_convert.rs @@ -194,7 +194,7 @@ impl RgbConverter { }; unsafe { d.destroy_shader_module(module, None) }; let pipeline = pipelines - .map_err(|c| Error::Vk(c.as_raw(), "vkCreateComputePipelines"))? + .map_err(|c| crate::session::vk_error(c, "vkCreateComputePipelines"))? .0[0]; let sizes = [vk::DescriptorPoolSize { diff --git a/shims/vk-video-ffi/src/rgb_decode.rs b/shims/vk-video-ffi/src/rgb_decode.rs index c3c1384b..31359b40 100644 --- a/shims/vk-video-ffi/src/rgb_decode.rs +++ b/shims/vk-video-ffi/src/rgb_decode.rs @@ -79,7 +79,7 @@ impl RgbPass { }; unsafe { d.destroy_shader_module(module, None) }; let pipeline = pipelines - .map_err(|c| Error::Vk(c.as_raw(), "vkCreateComputePipelines"))? + .map_err(|c| crate::session::vk_error(c, "vkCreateComputePipelines"))? .0[0]; let sizes = [vk::DescriptorPoolSize { diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index 3499f1ec..c18011b4 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -22,8 +22,16 @@ pub(crate) const INITIAL_VIRTUAL_BUFFER_MS: u32 = 12; pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2); +pub(crate) fn vk_error(code: vk::ErrorCode, call: &'static str) -> Error { + if code == vk::ErrorCode::DEVICE_LOST { + Error::DeviceLost(call) + } else { + Error::Vk(code.as_raw(), call) + } +} + pub(crate) fn vk(result: vulkanalia::VkResult, call: &'static str) -> Result { - result.map_err(|c| Error::Vk(c.as_raw(), call)) + result.map_err(|c| vk_error(c, call)) } pub(crate) fn zeroed() -> T {