forge
Explore
Log in

Don't you dare go Hollow

hw_parity example; intra_rate runs both backends; Vulkan device-lost maps to the GPU reset epoch

Browse files at this commit

ca831cefdbc632e7c659acbc74ae4b4cd58bbf77Ahmet Kaan GümüşParent: abe484f
vk-video-ffi: VK_ERROR_DEVICE_LOST surfaces as Error::DeviceLost, one helper for every Vk error mapping.
ec-hw: DeviceLost bumps the reset epoch via report_gpu_reset; Vk sessions check the epoch on use, new Vk sessions wait out the grace period; the thread-local Gpu is reopened after an epoch change.
crates/ec-hw/examples/hw_parity.rsadded+466 -0
@@ -0,0 +1,466 @@
1+//! 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.
2+//!
3+//! 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.
4+//!
5+//! ```text
6+//! cargo run --release -p ec-hw --example hw_parity -- <scratch dir>
7+//! ```
8+
9+use std::fmt::Display;
10+use std::fs;
11+use std::os::unix::fs::FileExt;
12+use std::path::{Path, PathBuf};
13+use std::process::Command;
14+use std::time::Instant;
15+
16+use ec_hw::{
17+ Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420,
18+ RateControlMode,
19+};
20+
21+const FRAMES: usize = 60;
22+const FPS: u32 = 30;
23+const GOP: u32 = 30;
24+const SIZES: [(u32, u32); 2] = [(1280, 720), (1920, 1080)];
25+const SOURCES: [&str; 2] = ["testsrc2", "mandelbrot"];
26+const CBR: [u32; 3] = [1_000_000, 3_000_000, 6_000_000];
27+const DECODE_BITRATE: u32 = 3_000_000;
28+const JOB: &str = "HW_PARITY_JOB";
29+
30+#[derive(Clone, Copy)]
31+enum Mode {
32+ Cqp(u32),
33+ Cbr(u32),
34+}
35+
36+impl Mode {
37+ fn label(self) -> String {
38+ match self {
39+ Mode::Cqp(qp) => format!("CQP {qp}"),
40+ Mode::Cbr(bps) => format!("CBR {}M", bps / 1_000_000),
41+ }
42+ }
43+
44+ fn env(self) -> (&'static str, u32) {
45+ match self {
46+ Mode::Cqp(qp) => ("cqp", qp),
47+ Mode::Cbr(bps) => ("cbr", bps),
48+ }
49+ }
50+}
51+
52+#[derive(Clone, Copy)]
53+struct Spec {
54+ name: &'static str,
55+ key: &'static str,
56+ format: &'static str,
57+ enc: EncCodec,
58+ dec: Codec,
59+}
60+
61+const SPECS: [Spec; 3] = [
62+ Spec {
63+ name: "H.264",
64+ key: "h264",
65+ format: "h264",
66+ enc: EncCodec::H264,
67+ dec: Codec::H264,
68+ },
69+ Spec {
70+ name: "HEVC",
71+ key: "hevc",
72+ format: "hevc",
73+ enc: EncCodec::H265,
74+ dec: Codec::H265,
75+ },
76+ Spec {
77+ name: "AV1",
78+ key: "av1",
79+ format: "obu",
80+ enc: EncCodec::Av1,
81+ dec: Codec::Av1,
82+ },
83+];
84+
85+fn modes(spec: Spec) -> Vec<Mode> {
86+ let qps = if spec.key == "av1" {
87+ [110, 135, 160]
88+ } else {
89+ [22, 27, 32]
90+ };
91+ qps.into_iter()
92+ .map(Mode::Cqp)
93+ .chain(CBR.into_iter().map(Mode::Cbr))
94+ .collect()
95+}
96+
97+fn backend_key(backend: Backend) -> &'static str {
98+ match backend {
99+ Backend::Vk => "vk",
100+ Backend::Va => "va",
101+ }
102+}
103+
104+fn backend_from_key(key: &str) -> Backend {
105+ match key {
106+ "vk" => Backend::Vk,
107+ _ => Backend::Va,
108+ }
109+}
110+
111+fn spec_from_key(key: &str) -> Spec {
112+ *SPECS.iter().find(|s| s.key == key).expect("known codec key")
113+}
114+
115+fn make_source(dir: &Path, source: &str, w: u32, h: u32) -> PathBuf {
116+ let path = dir.join(format!("{source}-{w}x{h}.yuv"));
117+ if !path.exists() {
118+ let status = Command::new("ffmpeg")
119+ .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"])
120+ .arg(format!("{source}=size={w}x{h}:rate={FPS}"))
121+ .args(["-frames:v", &FRAMES.to_string(), "-pix_fmt", "yuv420p", "-f", "rawvideo"])
122+ .arg(&path)
123+ .status()
124+ .expect("run ffmpeg");
125+ assert!(status.success(), "ffmpeg cannot generate {source}");
126+ }
127+ path
128+}
129+
130+fn read_frames(path: &Path, w: u32, h: u32) -> Vec<I420> {
131+ let (wu, hu) = (w as usize, h as usize);
132+ let (cw, ch) = (wu / 2, hu / 2);
133+ let file = fs::File::open(path).expect("source clip");
134+ (0..FRAMES as u64)
135+ .map(|t| {
136+ let len = wu * hu + 2 * cw * ch;
137+ let mut buf = vec![0u8; len];
138+ file.read_exact_at(&mut buf, t * len as u64)
139+ .expect("read picture");
140+ let (y, rest) = buf.split_at(wu * hu);
141+ let (u, v) = rest.split_at(cw * ch);
142+ I420 {
143+ y: y.to_vec(),
144+ u: u.to_vec(),
145+ v: v.to_vec(),
146+ width: w,
147+ height: h,
148+ }
149+ })
150+ .collect()
151+}
152+
153+fn write_aus(path: &Path, aus: &[Vec<u8>]) {
154+ let mut out = Vec::new();
155+ for au in aus {
156+ out.extend_from_slice(&(au.len() as u32).to_le_bytes());
157+ out.extend_from_slice(au);
158+ }
159+ fs::write(path, out).expect("write access units");
160+}
161+
162+fn read_aus(path: &Path) -> Vec<Vec<u8>> {
163+ let data = fs::read(path).expect("read access units");
164+ let mut aus = Vec::new();
165+ let mut at = 0;
166+ while at + 4 <= data.len() {
167+ let len = u32::from_le_bytes(data[at..at + 4].try_into().expect("4 bytes")) as usize;
168+ aus.push(data[at + 4..at + 4 + len].to_vec());
169+ at += 4 + len;
170+ }
171+ aus
172+}
173+
174+fn or_exit<T, E: Display>(result: Result<T, E>) -> T {
175+ match result {
176+ Ok(value) => value,
177+ Err(e) => {
178+ println!("ERR {e}");
179+ std::process::exit(3)
180+ }
181+ }
182+}
183+
184+fn encode_job() {
185+ let env = |k: &str| std::env::var(k).expect("job variable");
186+ let num = |k: &str| env(k).parse::<u32>().expect("job number");
187+ let spec = spec_from_key(&env("CODEC"));
188+ let (w, h) = (num("W"), num("H"));
189+ let backend = backend_from_key(&env("BACKEND"));
190+ let value = num("VALUE");
191+ let mode = if env("MODE") == "cqp" {
192+ Mode::Cqp(value)
193+ } else {
194+ Mode::Cbr(value)
195+ };
196+ let frames = read_frames(Path::new(&env("SOURCE")), w, h);
197+ let mut config = EncoderConfig::new(spec.enc, w, h);
198+ config.framerate = (FPS, 1);
199+ config.gop_size = GOP;
200+ match mode {
201+ Mode::Cqp(qp) => config.rate_control = RateControlMode::ConstantQp { qp },
202+ Mode::Cbr(bps) => {
203+ config.bitrate = bps;
204+ config.rate_control = RateControlMode::ConstantBitrate;
205+ }
206+ }
207+ let mut encoder = or_exit(HwEncoder::open(config, Some(backend)));
208+ let mut aus = Vec::with_capacity(frames.len());
209+ let start = Instant::now();
210+ for (t, frame) in frames.iter().enumerate() {
211+ let coded = or_exit(encoder.encode(
212+ frame,
213+ FrameMetadata {
214+ timestamp: t as i64,
215+ force_keyframe: false,
216+ },
217+ ));
218+ aus.push(coded.data);
219+ }
220+ let ms = start.elapsed().as_secs_f64() * 1000.0 / frames.len() as f64;
221+ write_aus(Path::new(&env("OUT")), &aus);
222+ println!("ENC ms={ms:.3} backend={:?}", encoder.backend());
223+}
224+
225+fn decode_job() {
226+ let env = |k: &str| std::env::var(k).expect("job variable");
227+ let spec = spec_from_key(&env("CODEC"));
228+ let backend = backend_from_key(&env("BACKEND"));
229+ let aus = read_aus(Path::new(&env("AUS")));
230+ let mut frames = 0usize;
231+ let elapsed = match backend {
232+ Backend::Vk => {
233+ let mut decoder = or_exit(HwDecoder::open(spec.dec));
234+ if decoder.backend() != Backend::Vk {
235+ println!("ERR opened on {:?}", decoder.backend());
236+ std::process::exit(3)
237+ }
238+ let start = Instant::now();
239+ for (t, au) in aus.iter().enumerate() {
240+ or_exit(decoder.decode(au, t as i64));
241+ while or_exit(decoder.next_frame()).is_some() {
242+ frames += 1;
243+ }
244+ }
245+ or_exit(decoder.flush());
246+ while or_exit(decoder.next_frame()).is_some() {
247+ frames += 1;
248+ }
249+ start.elapsed()
250+ }
251+ Backend::Va => {
252+ let display = or_exit(ec_va::open());
253+ let mut decoder = or_exit(ec_hw::Decoder::new(&display, spec.dec));
254+ let start = Instant::now();
255+ for (t, au) in aus.iter().enumerate() {
256+ or_exit(decoder.decode(au, t as i64));
257+ while let Some(frame) = decoder.next_frame() {
258+ or_exit(frame.to_i420());
259+ frames += 1;
260+ }
261+ }
262+ or_exit(decoder.flush());
263+ while let Some(frame) = decoder.next_frame() {
264+ or_exit(frame.to_i420());
265+ frames += 1;
266+ }
267+ start.elapsed()
268+ }
269+ };
270+ if frames != FRAMES {
271+ println!("ERR decoded {frames} of {FRAMES} frames");
272+ std::process::exit(3)
273+ }
274+ println!("DEC ms={:.3}", elapsed.as_secs_f64() * 1000.0 / FRAMES as f64);
275+}
276+
277+fn run_job(me: &Path, envs: &[(&str, String)]) -> Result<String, String> {
278+ let output = Command::new(me)
279+ .envs(envs.iter().map(|(k, v)| (*k, v.as_str())))
280+ .output()
281+ .expect("run child job");
282+ let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
283+ if output.status.success() {
284+ Ok(stdout)
285+ } else {
286+ let reason = stdout
287+ .lines()
288+ .rev()
289+ .find(|l| l.starts_with("ERR"))
290+ .unwrap_or("child failed")
291+ .to_string();
292+ Err(reason)
293+ }
294+}
295+
296+fn field(out: &str, key: &str) -> Option<f64> {
297+ out.lines()
298+ .find_map(|l| l.strip_prefix(key))
299+ .and_then(|rest| rest.split_whitespace().next())
300+ .and_then(|v| v.parse().ok())
301+}
302+
303+fn psnr_y(stream: &Path, format: &str, source: &Path, (w, h): (u32, u32)) -> Option<f64> {
304+ let rate = FPS.to_string();
305+ let size = format!("{w}x{h}");
306+ let out = Command::new("ffmpeg")
307+ .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"])
308+ .arg(stream)
309+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", &size, "-r", &rate, "-i"])
310+ .arg(source)
311+ .args(["-lavfi", "psnr", "-f", "null", "-"])
312+ .output()
313+ .ok()?;
314+ let text = String::from_utf8_lossy(&out.stderr);
315+ let at = text.rfind("PSNR y:")?;
316+ text[at + "PSNR y:".len()..]
317+ .split_whitespace()
318+ .next()?
319+ .parse::<f64>()
320+ .ok()
321+ .filter(|v| !v.is_nan())
322+}
323+
324+struct Row {
325+ bytes: usize,
326+ ms: f64,
327+ psnr: Option<f64>,
328+}
329+
330+fn encode_row(
331+ me: &Path,
332+ dir: &Path,
333+ tag: &str,
334+ raw: &Path,
335+ (w, h): (u32, u32),
336+ spec: Spec,
337+ mode: Mode,
338+ backend: Backend,
339+) -> Result<(Row, PathBuf), String> {
340+ let (mode_key, value) = mode.env();
341+ let aus_path = dir.join(format!("{tag}.aus"));
342+ let out = run_job(
343+ me,
344+ &[
345+ (JOB, "enc".to_string()),
346+ ("CODEC", spec.key.to_string()),
347+ ("W", w.to_string()),
348+ ("H", h.to_string()),
349+ ("BACKEND", backend_key(backend).to_string()),
350+ ("MODE", mode_key.to_string()),
351+ ("VALUE", value.to_string()),
352+ ("SOURCE", raw.display().to_string()),
353+ ("OUT", aus_path.display().to_string()),
354+ ],
355+ )?;
356+ let ms = field(&out, "ENC ms=").ok_or("no timing from encode job")?;
357+ let aus = read_aus(&aus_path);
358+ let stream = dir.join(format!("{tag}.{}", spec.format));
359+ fs::write(&stream, aus.concat()).expect("write stream");
360+ let row = Row {
361+ bytes: aus.iter().map(Vec::len).sum(),
362+ ms,
363+ psnr: psnr_y(&stream, spec.format, raw, (w, h)),
364+ };
365+ Ok((row, aus_path))
366+}
367+
368+fn decode_ms(me: &Path, aus: &Path, spec: Spec, backend: Backend) -> Result<f64, String> {
369+ let out = run_job(
370+ me,
371+ &[
372+ (JOB, "dec".to_string()),
373+ ("CODEC", spec.key.to_string()),
374+ ("BACKEND", backend_key(backend).to_string()),
375+ ("AUS", aus.display().to_string()),
376+ ],
377+ )?;
378+ field(&out, "DEC ms=").ok_or_else(|| "no timing from decode job".to_string())
379+}
380+
381+fn cell(v: Option<f64>, digits: usize) -> String {
382+ match v {
383+ Some(v) => format!("{v:.digits$}"),
384+ None => "n/a".to_string(),
385+ }
386+}
387+
388+fn main() {
389+ if let Ok(job) = std::env::var(JOB) {
390+ match job.as_str() {
391+ "enc" => encode_job(),
392+ _ => decode_job(),
393+ }
394+ return;
395+ }
396+ let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
397+ let me = std::env::current_exe().expect("own path");
398+ let mut decode_inputs: Vec<(&'static str, (u32, u32), Spec, Backend, PathBuf)> = Vec::new();
399+
400+ for source in SOURCES {
401+ for (w, h) in SIZES {
402+ let raw = make_source(&dir, source, w, h);
403+ println!("== {source} {w}x{h}, {FRAMES} frames at {FPS} fps ==");
404+ println!(
405+ "{:<6} {:<8} {:<4} {:>9} {:>7} {:>8} {:>9}",
406+ "codec", "rc", "enc", "bytes", "kbps", "PSNR-Y", "ms/frame"
407+ );
408+ for spec in SPECS {
409+ for mode in modes(spec) {
410+ for backend in [Backend::Vk, Backend::Va] {
411+ let tag = format!(
412+ "{source}-{w}x{h}-{}-{}-{}",
413+ spec.key,
414+ mode.label().replace(' ', ""),
415+ backend_key(backend)
416+ );
417+ let label = mode.label();
418+ let name = format!("{backend:?}");
419+ match encode_row(&me, &dir, &tag, &raw, (w, h), spec, mode, backend) {
420+ Ok((row, aus)) => {
421+ let kbps = row.bytes as f64 * 8.0 * f64::from(FPS) / FRAMES as f64 / 1000.0;
422+ println!(
423+ "{:<6} {:<8} {:<4} {:>9} {:>7.0} {:>8} {:>9.2}",
424+ spec.name,
425+ label,
426+ name,
427+ row.bytes,
428+ kbps,
429+ cell(row.psnr, 2),
430+ row.ms
431+ );
432+ if matches!(mode, Mode::Cbr(b) if b == DECODE_BITRATE) {
433+ decode_inputs.push((source, (w, h), spec, backend, aus));
434+ }
435+ }
436+ Err(reason) => println!(
437+ "{:<6} {:<8} {:<4} n/a: {reason}",
438+ spec.name, label, name
439+ ),
440+ }
441+ }
442+ }
443+ }
444+ println!();
445+ }
446+ }
447+
448+ println!("== decode, CBR {}M streams, ms/frame ==", DECODE_BITRATE / 1_000_000);
449+ println!(
450+ "{:<6} {:<10} {:<9} {:<4} {:>10} {:>10}",
451+ "codec", "source", "res", "enc", "Vk dec", "VA dec"
452+ );
453+ for (source, (w, h), spec, enc_backend, aus) in &decode_inputs {
454+ let vk = decode_ms(&me, aus, *spec, Backend::Vk);
455+ let va = decode_ms(&me, aus, *spec, Backend::Va);
456+ println!(
457+ "{:<6} {:<10} {:<9} {:<4} {:>10} {:>10}",
458+ spec.name,
459+ source,
460+ format!("{w}x{h}"),
461+ format!("{enc_backend:?}"),
462+ cell(vk.ok(), 2),
463+ cell(va.ok(), 2)
464+ );
465+ }
466+}
crates/ec-hw/src/error.rsmodified+7 -1
@@ -87,7 +87,13 @@ impl From<ec_va::Error> for Error {
8787
8888 impl From<ec_vk::Error> for Error {
8989 fn from(e: ec_vk::Error) -> Error {
90- Error::Vk(e.to_string())
90+ match e {
91+ ec_vk::Error::DeviceLost(call) => {
92+ crate::reset::report_gpu_reset();
93+ Error::hw_reset(format!("Vulkan device lost in {call}"))
94+ }
95+ other => Error::Vk(other.to_string()),
96+ }
9197 }
9298 }
9399
crates/ec-hw/src/hw.rsmodified+51 -5
@@ -6,6 +6,8 @@ use std::os::fd::BorrowedFd;
66 #[cfg(target_os = "linux")]
77 use ec_vk::DmaBuf;
88
9+use std::cell::RefCell;
10+
911 use crate::error::{Error, Result};
1012 use crate::picture::{Decoded, I420, RgbPicture};
1113 #[cfg(target_os = "linux")]
@@ -58,11 +60,41 @@ pub struct Capability {
5860 }
5961
6062 thread_local! {
61- static GPU: Option<ec_vk::Gpu> = ec_vk::Gpu::open().ok();
63+ static GPU: RefCell<Option<(u64, Option<ec_vk::Gpu>)>> = const { RefCell::new(None) };
6264 }
6365
6466 pub(crate) fn vk_gpu() -> Option<ec_vk::Gpu> {
65- GPU.with(|gpu| gpu.clone())
67+ GPU.with_borrow_mut(|cached| {
68+ let epoch = crate::reset::gpu_reset_epoch();
69+ match cached {
70+ Some((born, gpu)) if *born == epoch => gpu.clone(),
71+ _ => {
72+ let gpu = ec_vk::Gpu::open().ok();
73+ *cached = Some((epoch, gpu.clone()));
74+ gpu
75+ }
76+ }
77+ })
78+}
79+
80+fn vk_session_alive(born_epoch: u64) -> Result<()> {
81+ if crate::reset::gpu_reset_epoch() == born_epoch {
82+ Ok(())
83+ } else {
84+ Err(Error::hw_reset(
85+ "the GPU was reset after this Vulkan session was created; its device is lost",
86+ ))
87+ }
88+}
89+
90+fn vk_grace() -> Result<()> {
91+ if crate::reset::gpu_recently_reset() {
92+ Err(Error::hw_reset(
93+ "the GPU was reset moments ago; new Vulkan sessions wait out the grace period",
94+ ))
95+ } else {
96+ Ok(())
97+ }
6698 }
6799
68100 /// Every codec, direction and backend this machine can use. Never fails.
@@ -336,6 +368,7 @@ enum EncInner {
336368 /// A hardware encoder on whichever backend opened.
337369 pub struct HwEncoder {
338370 inner: EncInner,
371+ born_epoch: u64,
339372 config: EncoderConfig,
340373 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
341374 size: (usize, usize),
@@ -350,11 +383,13 @@ impl HwEncoder {
350383 };
351384 let mut reasons = Vec::new();
352385 for backend in order {
386+ let born_epoch = crate::reset::gpu_reset_epoch();
353387 match open_backend(backend, config) {
354388 Ok(inner) => {
355389 let size = (config.width as usize, config.height as usize);
356390 return Ok(HwEncoder {
357391 inner,
392+ born_epoch,
358393 config,
359394 size,
360395 });
@@ -381,6 +416,7 @@ impl HwEncoder {
381416 pub fn tune(&mut self, tunings: Tunings) -> Result<()> {
382417 match &mut self.inner {
383418 EncInner::Vk(enc) => {
419+ vk_session_alive(self.born_epoch)?;
384420 let rate = match self.config.rate_control {
385421 RateControlMode::ConstantQp { .. } => vk_rate(&self.config),
386422 _ => ec_vk::RateControl::Cbr {
@@ -399,6 +435,7 @@ impl HwEncoder {
399435 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
400436 match &mut self.inner {
401437 EncInner::Vk(enc) => {
438+ vk_session_alive(self.born_epoch)?;
402439 let coded = enc.encode(frame, meta.force_keyframe)?;
403440 Ok(CodedFrame {
404441 data: coded.data,
@@ -415,6 +452,7 @@ impl HwEncoder {
415452 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
416453 match &mut self.inner {
417454 EncInner::Vk(enc) => {
455+ vk_session_alive(self.born_epoch)?;
418456 let coded = enc.encode_rgb(frame, meta.force_keyframe)?;
419457 Ok(CodedFrame {
420458 data: coded.data,
@@ -436,6 +474,7 @@ impl HwEncoder {
436474 ) -> Result<CodedFrame> {
437475 match &mut self.inner {
438476 EncInner::Vk(enc) => {
477+ vk_session_alive(self.born_epoch)?;
439478 let coded = enc.encode_dmabuf(frame, meta.force_keyframe)?;
440479 Ok(CodedFrame {
441480 data: coded.data,
@@ -459,6 +498,7 @@ fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> {
459498 }
460499
461500 fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
501+ vk_grace()?;
462502 if config.bit_depth != 8 {
463503 return Err(Error::unsupported(
464504 "10-bit Vulkan Video encode",
@@ -594,6 +634,7 @@ enum Mode {
594634 /// A hardware decoder on whichever backend opened.
595635 pub struct HwDecoder {
596636 inner: DecInner,
637+ born_epoch: u64,
597638 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
598639 codec: Codec,
599640 mode: Mode,
@@ -618,16 +659,18 @@ impl HwDecoder {
618659 Mode::Rgb(output) => Some(output),
619660 };
620661 let mut reasons = Vec::new();
621- let vk = match codec {
662+ let born_epoch = crate::reset::gpu_reset_epoch();
663+ let vk = vk_grace().and_then(|()| match codec {
622664 Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264),
623665 Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265),
624666 Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1),
625667 _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")),
626- };
668+ });
627669 match vk {
628670 Ok(inner) => {
629671 return Ok(HwDecoder {
630672 inner: DecInner::Vk(inner),
673+ born_epoch,
631674 codec,
632675 mode,
633676 replay: Some(Vec::new()),
@@ -644,6 +687,7 @@ impl HwDecoder {
644687 Ok(inner) => {
645688 return Ok(HwDecoder {
646689 inner: DecInner::Va(inner),
690+ born_epoch,
647691 codec,
648692 mode,
649693 replay: None,
@@ -670,8 +714,9 @@ impl HwDecoder {
670714 /// Feed one access unit. A stream Vulkan refuses (an unsupported profile) before its first
671715 /// picture comes out moves to VA-API on Linux, replaying what was fed so far.
672716 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
717+ let born_epoch = self.born_epoch;
673718 let result = match &mut self.inner {
674- DecInner::Vk(d) => d.decode(data, timestamp),
719+ DecInner::Vk(d) => vk_session_alive(born_epoch).and_then(|()| d.decode(data, timestamp)),
675720 #[cfg(target_os = "linux")]
676721 DecInner::Va(d) => d.decode(data, timestamp),
677722 };
@@ -722,6 +767,7 @@ impl HwDecoder {
722767 fn pull(&mut self) -> Result<Option<(i64, Decoded)>> {
723768 match &mut self.inner {
724769 DecInner::Vk(d) => {
770+ vk_session_alive(self.born_epoch)?;
725771 let frame = d.next_frame();
726772 if frame.is_some() {
727773 self.replay = None;
crates/ec-hw/tests/intra_rate.rsmodified+64 -49
@@ -24,10 +24,8 @@ use std::fs::File;
2424 use std::os::unix::fs::FileExt;
2525 use std::path::{Path, PathBuf};
2626 use std::process::Command;
27-use std::rc::Rc;
2827
29-use ec_hw::{EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode};
30-use ec_va::Display;
28+use ec_hw::{Backend, EncCodec, EncoderConfig, FrameMetadata, HwEncoder, I420, RateControlMode};
3129
3230 const WIDTH: u32 = 1280;
3331 const HEIGHT: u32 = 720;
@@ -41,20 +39,30 @@ const CHILD_CODEC: &str = "EC_INTRA_RATE_CODEC";
4139 const CHILD_GOP: &str = "EC_INTRA_RATE_GOP";
4240 const CHILD_BITRATE: &str = "EC_INTRA_RATE_BITRATE";
4341 const CHILD_MODE: &str = "EC_INTRA_RATE_MODE";
42+const CHILD_BACKEND: &str = "EC_INTRA_RATE_BACKEND";
4443 const CHILD_SOURCE: &str = "EC_INTRA_RATE_SOURCE";
4544 const CHILD_OUT: &str = "EC_INTRA_RATE_OUT";
4645 const DELIVERED_LINE: &str = "DELIVERED_BPS=";
4746
48-fn display() -> Option<Rc<Display>> {
49- match ec_va::open() {
50- Ok(display) => Some(display),
51- Err(e) => {
52- eprintln!("skipped: no VA display ({e})");
53- None
54- }
47+fn backend_key(backend: Backend) -> &'static str {
48+ match backend {
49+ Backend::Vk => "vk",
50+ Backend::Va => "va",
51+ }
52+}
53+
54+fn backend_from_key(key: &str) -> Backend {
55+ match key {
56+ "vk" => Backend::Vk,
57+ _ => Backend::Va,
5558 }
5659 }
5760
61+fn opens(codec: EncCodec, backend: Backend) -> bool {
62+ let config = EncoderConfig::new(codec, WIDTH, HEIGHT);
63+ HwEncoder::open(config, Some(backend)).is_ok()
64+}
65+
5866 fn scratch() -> PathBuf {
5967 let dir = std::env::temp_dir().join("ec-hw-intra-rate");
6068 std::fs::create_dir_all(&dir).expect("scratch dir");
@@ -104,19 +112,19 @@ fn picture(file: &File, t: u32) -> I420 {
104112 /// One encode of the clip with an IDR every `gop` pictures: the stream, and the
105113 /// bits per second it actually spent.
106114 fn encode(
115+ backend: Backend,
107116 codec: EncCodec,
108117 gop: u32,
109118 bitrate: u32,
110119 rate_control: RateControlMode,
111120 raw: &File,
112121 ) -> (Vec<u8>, f64) {
113- let display = display().expect("a VA display");
114122 let mut config = EncoderConfig::new(codec, WIDTH, HEIGHT);
115123 config.framerate = (FPS, 1);
116124 config.gop_size = gop;
117125 config.bitrate = bitrate;
118126 config.rate_control = rate_control;
119- let mut encoder = Encoder::new(&display, config).expect("encoder");
127+ let mut encoder = HwEncoder::open(config, Some(backend)).expect("encoder");
120128 let mut out = Vec::new();
121129 for t in 0..FRAMES {
122130 let coded = encoder
@@ -179,8 +187,9 @@ fn one_encode_in_its_own_process() {
179187 },
180188 _ => RateControlMode::ConstantBitrate,
181189 };
190+ let backend = backend_from_key(&std::env::var(CHILD_BACKEND).expect("backend"));
182191 let raw = File::open(std::env::var(CHILD_SOURCE).expect("source")).expect("source clip");
183- let (stream, delivered) = encode(codec, gop, bitrate, rate_control, &raw);
192+ let (stream, delivered) = encode(backend, codec, gop, bitrate, rate_control, &raw);
184193 std::fs::write(std::env::var(CHILD_OUT).expect("out"), &stream).expect("write stream");
185194 println!("{DELIVERED_LINE}{delivered}");
186195 }
@@ -188,6 +197,7 @@ fn one_encode_in_its_own_process() {
188197 /// One encode in a child process of this test binary. Returns the stream's
189198 /// delivered bits per second, written to `out`.
190199 fn encode_in_its_own_process(
200+ backend: Backend,
191201 codec: EncCodec,
192202 gop: u32,
193203 bitrate: u32,
@@ -207,6 +217,7 @@ fn encode_in_its_own_process(
207217 .env(CHILD_GOP, gop.to_string())
208218 .env(CHILD_BITRATE, bitrate.to_string())
209219 .env(CHILD_MODE, if coarsest_qp { "coarsest" } else { "cbr" })
220+ .env(CHILD_BACKEND, backend_key(backend))
210221 .env(CHILD_SOURCE, source)
211222 .env(CHILD_OUT, out)
212223 .output()
@@ -252,9 +263,6 @@ fn psnr(coded: &Path, format: &str, source: &Path) -> Option<f64> {
252263
253264 #[test]
254265 fn cbr_lands_within_five_percent_on_intra_only_and_gop_30() {
255- if display().is_none() {
256- return;
257- }
258266 let dir = scratch();
259267 let Some(source) = testsrc2_raw(&dir) else {
260268 eprintln!("skipped: ffmpeg cannot generate testsrc2");
@@ -265,40 +273,47 @@ fn cbr_lands_within_five_percent_on_intra_only_and_gop_30() {
265273 println!(
266274 "CBR, testsrc2 {WIDTH}x{HEIGHT} {FPS} fps, {FRAMES} pictures (floor = coarsest quantiser):"
267275 );
268- for (codec, name, format) in [
269- (EncCodec::H264, "H.264", "h264"),
270- (EncCodec::H265, "HEVC", "hevc"),
271- (EncCodec::Av1, "AV1", "obu"),
272- ] {
273- for gop in GOPS {
274- // The smallest stream this codec makes for the clip at this GOP.
275- let floor_path = dir.join(format!("{name}-gop{gop}-floor.{format}"));
276- let floor = encode_in_its_own_process(codec, gop, 0, true, &source, &floor_path);
277- for bitrate in BITRATES {
278- let coded = dir.join(format!("{name}-gop{gop}-{bitrate}.{format}"));
279- let delivered =
280- encode_in_its_own_process(codec, gop, bitrate, false, &source, &coded);
281- let db = psnr(&coded, format, &source).unwrap_or(f64::NAN);
282- let error = delivered / f64::from(bitrate) - 1.0;
283- let at_floor =
284- f64::from(bitrate) < floor && (delivered / floor - 1.0).abs() <= 0.05;
285- println!(
286- " {name:<6} GOP {gop:>2} request {:>5} kbps -> {:>6.0} kbps ({:+6.1}%), floor {:>6.0} kbps, {db:.2} dB{}",
287- bitrate / 1000,
288- delivered / 1000.0,
289- error * 100.0,
290- floor / 1000.0,
291- if at_floor {
292- " (at the coarsest quantiser)"
293- } else {
294- ""
276+ for backend in [Backend::Va, Backend::Vk] {
277+ for (codec, name, format) in [
278+ (EncCodec::H264, "H.264", "h264"),
279+ (EncCodec::H265, "HEVC", "hevc"),
280+ (EncCodec::Av1, "AV1", "obu"),
281+ ] {
282+ if !opens(codec, backend) {
283+ println!(" {backend:?} {name}: skipped, the encoder does not open");
284+ continue;
285+ }
286+ for gop in GOPS {
287+ let floor_path = dir.join(format!("{backend:?}-{name}-gop{gop}-floor.{format}"));
288+ let floor =
289+ encode_in_its_own_process(backend, codec, gop, 0, true, &source, &floor_path);
290+ for bitrate in BITRATES {
291+ let coded = dir.join(format!("{backend:?}-{name}-gop{gop}-{bitrate}.{format}"));
292+ let delivered = encode_in_its_own_process(
293+ backend, codec, gop, bitrate, false, &source, &coded,
294+ );
295+ let db = psnr(&coded, format, &source).unwrap_or(f64::NAN);
296+ let error = delivered / f64::from(bitrate) - 1.0;
297+ let at_floor =
298+ f64::from(bitrate) < floor && (delivered / floor - 1.0).abs() <= 0.05;
299+ println!(
300+ " {backend:?} {name:<6} GOP {gop:>2} request {:>5} kbps -> {:>6.0} kbps ({:+6.1}%), floor {:>6.0} kbps, {db:.2} dB{}",
301+ bitrate / 1000,
302+ delivered / 1000.0,
303+ error * 100.0,
304+ floor / 1000.0,
305+ if at_floor {
306+ " (at the coarsest quantiser)"
307+ } else {
308+ ""
309+ }
310+ );
311+ if error.abs() > 0.05 && !at_floor {
312+ failures.push(format!(
313+ "{backend:?} {name} GOP {gop} at {bitrate} bps: {:+.1}%",
314+ error * 100.0
315+ ));
295316 }
296- );
297- if error.abs() > 0.05 && !at_floor {
298- failures.push(format!(
299- "{name} GOP {gop} at {bitrate} bps: {:+.1}%",
300- error * 100.0
301- ));
302317 }
303318 }
304319 }
shims/vk-video-ffi/src/lib.rsmodified+8 -5
@@ -70,6 +70,8 @@ pub enum Error {
7070 NoDevice,
7171 /// A Vulkan call failed: VkResult code and call name.
7272 Vk(i32, &'static str),
73+ /// The device was lost (VK_ERROR_DEVICE_LOST): a GPU reset or a hung queue. Every object on it is dead.
74+ DeviceLost(&'static str),
7375 /// The requested codec or direction is not supported.
7476 Unsupported(String),
7577 /// The caller passed an invalid picture, buffer or sequence state.
@@ -82,6 +84,7 @@ impl fmt::Display for Error {
8284 Error::NoLoader(e) => write!(f, "no Vulkan loader: {e}"),
8385 Error::NoDevice => write!(f, "no Vulkan Video device"),
8486 Error::Vk(code, call) => write!(f, "{call} failed: VkResult {code}"),
87+ Error::DeviceLost(call) => write!(f, "{call} failed: device lost"),
8588 Error::Unsupported(what) => write!(f, "unsupported: {what}"),
8689 Error::Invalid(what) => write!(f, "invalid: {what}"),
8790 }
@@ -172,7 +175,7 @@ fn queue_families(instance: &Instance, physical: vk::PhysicalDevice) -> Families
172175
173176 fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Families), Error> {
174177 let devices = unsafe { instance.enumerate_physical_devices() }
175- .map_err(|c| Error::Vk(c.as_raw(), "vkEnumeratePhysicalDevices"))?;
178+ .map_err(|c| crate::session::vk_error(c, "vkEnumeratePhysicalDevices"))?;
176179 let (physical, families) = devices
177180 .into_iter()
178181 .find_map(|pd| {
@@ -198,7 +201,7 @@ fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Fam
198201
199202 let available: Vec<vk::ExtensionName> =
200203 unsafe { instance.enumerate_device_extension_properties(physical, None) }
201- .map_err(|c| Error::Vk(c.as_raw(), "vkEnumerateDeviceExtensionProperties"))?
204+ .map_err(|c| crate::session::vk_error(c, "vkEnumerateDeviceExtensionProperties"))?
202205 .iter()
203206 .map(|e| e.extension_name)
204207 .collect();
@@ -233,7 +236,7 @@ fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String, Fam
233236 .enabled_extension_names(&names)
234237 .push_next(&mut features);
235238 let device = unsafe { instance.create_device(physical, &info, None) }
236- .map_err(|c| Error::Vk(c.as_raw(), "vkCreateDevice"))?;
239+ .map_err(|c| crate::session::vk_error(c, "vkCreateDevice"))?;
237240
238241 let name = unsafe { instance.get_physical_device_properties(physical) }
239242 .device_name
@@ -256,7 +259,7 @@ impl Gpu {
256259 let app = vk::ApplicationInfo::builder().api_version(vk::make_version(1, 3, 0));
257260 let info = vk::InstanceCreateInfo::builder().application_info(&app);
258261 let instance = unsafe { entry.create_instance(&info, None) }
259- .map_err(|c| Error::Vk(c.as_raw(), "vkCreateInstance"))?;
262+ .map_err(|c| crate::session::vk_error(c, "vkCreateInstance"))?;
260263 match setup(&instance) {
261264 Ok((physical, device, name, families)) => Ok(Gpu {
262265 inner: Arc::new(Inner {
@@ -483,7 +486,7 @@ impl Gpu {
483486 &mut caps,
484487 )
485488 }
486- .map_err(|c| Error::Vk(c.as_raw(), "vkGetPhysicalDeviceVideoCapabilitiesKHR"))?;
489+ .map_err(|c| crate::session::vk_error(c, "vkGetPhysicalDeviceVideoCapabilitiesKHR"))?;
487490 Ok(CodecCaps {
488491 codec,
489492 direction,
shims/vk-video-ffi/src/rgb_convert.rsmodified+1 -1
@@ -194,7 +194,7 @@ impl RgbConverter {
194194 };
195195 unsafe { d.destroy_shader_module(module, None) };
196196 let pipeline = pipelines
197- .map_err(|c| Error::Vk(c.as_raw(), "vkCreateComputePipelines"))?
197+ .map_err(|c| crate::session::vk_error(c, "vkCreateComputePipelines"))?
198198 .0[0];
199199
200200 let sizes = [vk::DescriptorPoolSize {
shims/vk-video-ffi/src/rgb_decode.rsmodified+1 -1
@@ -79,7 +79,7 @@ impl RgbPass {
7979 };
8080 unsafe { d.destroy_shader_module(module, None) };
8181 let pipeline = pipelines
82- .map_err(|c| Error::Vk(c.as_raw(), "vkCreateComputePipelines"))?
82+ .map_err(|c| crate::session::vk_error(c, "vkCreateComputePipelines"))?
8383 .0[0];
8484
8585 let sizes = [vk::DescriptorPoolSize {
shims/vk-video-ffi/src/session.rsmodified+9 -1
@@ -22,8 +22,16 @@ pub(crate) const INITIAL_VIRTUAL_BUFFER_MS: u32 = 12;
2222
2323 pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2);
2424
25+pub(crate) fn vk_error(code: vk::ErrorCode, call: &'static str) -> Error {
26+ if code == vk::ErrorCode::DEVICE_LOST {
27+ Error::DeviceLost(call)
28+ } else {
29+ Error::Vk(code.as_raw(), call)
30+ }
31+}
32+
2533 pub(crate) fn vk<T>(result: vulkanalia::VkResult<T>, call: &'static str) -> Result<T, Error> {
26- result.map_err(|c| Error::Vk(c.as_raw(), call))
34+ result.map_err(|c| vk_error(c, call))
2735 }
2836
2937 pub(crate) fn zeroed<T>() -> T {