forge
Explore
Log in

Don't you dare go Hollow

Live GPU tests against ffmpeg, and Annex B fixtures

Browse files at this commit

43c80978624f5963a1770af57711a4db27282efdAhmet Kaan GümüşParent: 7368f27
  • test
    • live GPU tests against ffmpeg, and Annex B fixtures
Show full message
test(hw): live GPU tests against ffmpeg, and Annex B fixtures

Every test here talks to the real driver — a hardware crate whose tests
do not touch the hardware tests nothing — and none is `#[ignore]`d; they
skip when there is no VA display or the fixtures are missing. ffmpeg's
software decoder is the oracle: each fixture is decoded both ways and
compared frame by frame, at the stream's own bit depth (converting a
10-bit reference down to 8 dithers, which would hide a real difference
behind a fake 53 dB one).

Alongside the four codecs: the `frame_num` gap synthesis, a 719-frame
decode-and-read-back loop watching `VmRSS`, the DRM PRIME export, the
encoders round-tripping through ffmpeg *and* through this crate's own
decoder, and a spot check against his real library rather than the
fixtures alone.

`scripts/gen-bitstream-fixtures.sh` gains the H.264 and HEVC elementary
streams — including B-frame clips, so output reordering is exercised
rather than assumed.
crates/ec-hw/tests/gpu.rsadded+1000 -0
@@ -0,0 +1,1000 @@
1+//! Live GPU tests: every one of these talks to the real VA-API driver.
2+//!
3+//! They are not `#[ignore]`d — a hardware crate whose tests do not touch the
4+//! hardware tests nothing — but they *skip* (print and return) when there is no
5+//! VA display or when the fixtures have not been generated. That keeps a
6+//! checkout without a GPU green while making this machine's run meaningful.
7+//!
8+//! The oracle is ffmpeg's software decoder: every fixture is decoded here and
9+//! by `ffmpeg -f rawvideo`, and the two are compared frame by frame.
10+
11+use std::io::Read;
12+use std::path::{Path, PathBuf};
13+use std::process::{Command, Stdio};
14+use std::sync::Arc;
15+
16+use ec_hw::{
17+ Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode,
18+};
19+use ec_va::Display;
20+
21+/// Frames compared per fixture: enough to cover several GOPs and any
22+/// reordering, few enough to keep the suite under a minute.
23+const FRAMES: usize = 24;
24+
25+fn bitstreams() -> PathBuf {
26+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams")
27+}
28+
29+fn display() -> Option<Arc<Display>> {
30+ match Display::open() {
31+ Ok(display) => Some(display),
32+ Err(e) => {
33+ eprintln!("skipped: no VA display ({e})");
34+ None
35+ }
36+ }
37+}
38+
39+fn fixtures(pattern: &str) -> Vec<PathBuf> {
40+ let Ok(dir) = std::fs::read_dir(bitstreams()) else {
41+ return Vec::new();
42+ };
43+ let mut out: Vec<PathBuf> = dir
44+ .flatten()
45+ .map(|e| e.path())
46+ .filter(|p| {
47+ p.file_name()
48+ .and_then(|n| n.to_str())
49+ .is_some_and(|n| n.ends_with(pattern))
50+ })
51+ .collect();
52+ out.sort();
53+ out
54+}
55+
56+/// The software reference: ffmpeg decoding the same file to raw planes.
57+struct Reference {
58+ child: std::process::Child,
59+ frame_bytes: usize,
60+ ten_bit: bool,
61+}
62+
63+impl Reference {
64+ fn open(path: &Path, width: u32, height: u32, ten_bit: bool) -> Option<Reference> {
65+ let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
66+ let child = Command::new("ffmpeg")
67+ .args(["-nostdin", "-v", "error", "-i"])
68+ .arg(path)
69+ .args(["-map", "0:v:0", "-pix_fmt", pix, "-f", "rawvideo", "-"])
70+ .stdout(Stdio::piped())
71+ .stderr(Stdio::null())
72+ .spawn()
73+ .ok()?;
74+ let samples = (width as usize * height as usize * 3).div_ceil(2);
75+ Some(Reference {
76+ child,
77+ frame_bytes: if ten_bit { samples * 2 } else { samples },
78+ ten_bit,
79+ })
80+ }
81+
82+ /// The next reference frame, as samples at the stream's own bit depth.
83+ ///
84+ /// A 10-bit stream is compared at 10 bits rather than converted down:
85+ /// `ffmpeg -pix_fmt yuv420p` on a 10-bit source dithers, which would hide a
86+ /// real difference behind a fake 53 dB one (measured, not assumed).
87+ fn next(&mut self, width: u32, height: u32) -> Option<Planes> {
88+ let stdout = self.child.stdout.as_mut()?;
89+ let mut buf = vec![0u8; self.frame_bytes];
90+ stdout.read_exact(&mut buf).ok()?;
91+ let (w, h) = (width as usize, height as usize);
92+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
93+ let (y_len, c_len) = (w * h, cw * ch);
94+ if self.ten_bit {
95+ let read = |slice: &[u8]| -> Vec<u16> {
96+ slice
97+ .chunks_exact(2)
98+ .map(|p| u16::from_le_bytes([p[0], p[1]]))
99+ .collect()
100+ };
101+ Some(Planes {
102+ y: read(&buf[..y_len * 2]),
103+ u: read(&buf[y_len * 2..(y_len + c_len) * 2]),
104+ v: read(&buf[(y_len + c_len) * 2..(y_len + 2 * c_len) * 2]),
105+ peak: 1023.0,
106+ })
107+ } else {
108+ let read = |slice: &[u8]| -> Vec<u16> { slice.iter().map(|&v| u16::from(v)).collect() };
109+ Some(Planes {
110+ y: read(&buf[..y_len]),
111+ u: read(&buf[y_len..y_len + c_len]),
112+ v: read(&buf[y_len + c_len..y_len + 2 * c_len]),
113+ peak: 255.0,
114+ })
115+ }
116+ }
117+}
118+
119+impl Drop for Reference {
120+ fn drop(&mut self) {
121+ let _ = self.child.kill();
122+ let _ = self.child.wait();
123+ }
124+}
125+
126+/// Three planes at whatever bit depth the stream carries.
127+struct Planes {
128+ y: Vec<u16>,
129+ u: Vec<u16>,
130+ v: Vec<u16>,
131+ peak: f64,
132+}
133+
134+impl Planes {
135+ fn from_8bit(f: &I420) -> Planes {
136+ let read = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() };
137+ Planes {
138+ y: read(&f.y),
139+ u: read(&f.u),
140+ v: read(&f.v),
141+ peak: 255.0,
142+ }
143+ }
144+
145+ fn from_16bit(f: &ec_hw::I420_16) -> Planes {
146+ Planes {
147+ y: f.y.clone(),
148+ u: f.u.clone(),
149+ v: f.v.clone(),
150+ peak: 1023.0,
151+ }
152+ }
153+}
154+
155+/// Peak signal to noise ratio over the three planes, in dB; `f64::INFINITY`
156+/// when the frames are identical.
157+fn psnr(a: &Planes, b: &Planes) -> f64 {
158+ let mut sum = 0f64;
159+ let mut n = 0usize;
160+ for (x, y) in [(&a.y, &b.y), (&a.u, &b.u), (&a.v, &b.v)] {
161+ for (p, q) in x.iter().zip(y.iter()) {
162+ let d = f64::from(*p) - f64::from(*q);
163+ sum += d * d;
164+ }
165+ n += x.len().min(y.len());
166+ }
167+ if n == 0 {
168+ return 0.0;
169+ }
170+ let mse = sum / n as f64;
171+ if mse == 0.0 {
172+ return f64::INFINITY;
173+ }
174+ 10.0 * (a.peak * a.peak / mse).log10()
175+}
176+
177+/// Feed a whole elementary stream to a decoder, collecting frames.
178+///
179+/// H.264 and HEVC are fed access unit by access unit, which is what a demuxer
180+/// hands over; VP9 and AV1 arrive as IVF frames.
181+fn decode_stream(
182+ decoder: &mut Decoder,
183+ codec: Codec,
184+ data: &[u8],
185+ limit: usize,
186+ mut on_frame: impl FnMut(Frame),
187+) -> Result<usize, ec_hw::Error> {
188+ let mut count = 0usize;
189+ let units: Vec<&[u8]> = match codec {
190+ Codec::H264 | Codec::H265 => split_access_units(data, codec),
191+ Codec::Vp9 | Codec::Av1 => split_ivf(data),
192+ };
193+ for (i, unit) in units.iter().enumerate() {
194+ decoder.decode(unit, i as i64)?;
195+ while let Some(frame) = decoder.next_frame() {
196+ count += 1;
197+ on_frame(frame);
198+ if count >= limit {
199+ return Ok(count);
200+ }
201+ }
202+ }
203+ decoder.flush()?;
204+ while let Some(frame) = decoder.next_frame() {
205+ count += 1;
206+ on_frame(frame);
207+ if count >= limit {
208+ break;
209+ }
210+ }
211+ Ok(count)
212+}
213+
214+/// Split an Annex B stream into access units: a new one starts at the first
215+/// VCL NAL of a picture, i.e. at an AUD, a parameter set, or a slice whose
216+/// first-slice flag is set after a previous slice.
217+fn split_access_units(data: &[u8], codec: Codec) -> Vec<&[u8]> {
218+ let mut starts: Vec<usize> = Vec::new();
219+ let mut seen_slice = false;
220+ let mut i = 0usize;
221+ while i + 3 < data.len() {
222+ if data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 {
223+ i += 1;
224+ continue;
225+ }
226+ let nal = i + 3;
227+ let (is_vcl, first_slice) = match codec {
228+ Codec::H264 => {
229+ let t = data[nal] & 0x1f;
230+ let first = data.get(nal + 1).is_some_and(|&b| b & 0x80 != 0);
231+ ((1..=5).contains(&t), first)
232+ }
233+ _ => {
234+ let t = (data[nal] >> 1) & 0x3f;
235+ let first = data.get(nal + 2).is_some_and(|&b| b & 0x80 != 0);
236+ (t <= 31, first)
237+ }
238+ };
239+ if is_vcl {
240+ if seen_slice && first_slice {
241+ starts.push(i);
242+ seen_slice = false;
243+ }
244+ if first_slice {
245+ seen_slice = true;
246+ }
247+ }
248+ i = nal + 1;
249+ }
250+ let mut out = Vec::new();
251+ let mut prev = 0usize;
252+ for &start in &starts {
253+ out.push(&data[prev..start]);
254+ prev = start;
255+ }
256+ if prev < data.len() {
257+ out.push(&data[prev..]);
258+ }
259+ out
260+}
261+
262+/// Split an IVF file into its frames.
263+fn split_ivf(data: &[u8]) -> Vec<&[u8]> {
264+ let mut out = Vec::new();
265+ if data.len() < 32 || &data[..4] != b"DKIF" {
266+ return out;
267+ }
268+ let header = u16::from_le_bytes([data[6], data[7]]) as usize;
269+ let mut pos = header.max(32);
270+ while pos + 12 <= data.len() {
271+ let size =
272+ u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
273+ pos += 12;
274+ if pos + size > data.len() {
275+ break;
276+ }
277+ out.push(&data[pos..pos + size]);
278+ pos += size;
279+ }
280+ out
281+}
282+
283+/// Decode every named fixture and compare with ffmpeg, frame by frame.
284+fn compare_against_ffmpeg(files: &[PathBuf], codec: Codec, ten_bit: bool) {
285+ let Some(display) = display() else { return };
286+ if files.is_empty() {
287+ eprintln!("skipped: no fixtures — run scripts/gen-bitstream-fixtures.sh");
288+ return;
289+ }
290+ let mut table = Vec::new();
291+ for path in files {
292+ let data = std::fs::read(path).expect("fixture is readable");
293+ let mut decoder = Decoder::new(&display, codec).expect("decoder opens");
294+ let mut reference: Option<Reference> = None;
295+ let mut worst = f64::INFINITY;
296+ let mut identical = 0usize;
297+ let mut compared = 0usize;
298+ let mut mismatched_size = false;
299+
300+ let result = decode_stream(&mut decoder, codec, &data, FRAMES, |frame| {
301+ let (w, h) = frame.display_size;
302+ let reference = reference
303+ .get_or_insert_with(|| Reference::open(path, w, h, ten_bit).expect("ffmpeg runs"));
304+ let Some(want) = reference.next(w, h) else {
305+ return;
306+ };
307+ let got = if ten_bit {
308+ Planes::from_16bit(&frame.to_i420_16().expect("readback"))
309+ } else {
310+ Planes::from_8bit(&frame.to_i420().expect("readback"))
311+ };
312+ if got.y.len() != want.y.len() {
313+ mismatched_size = true;
314+ return;
315+ }
316+ let db = psnr(&got, &want);
317+ if std::env::var_os("EC_HW_DEBUG").is_some() {
318+ eprintln!(" frame {compared}: {db:.1} dB (ts {})", frame.timestamp);
319+ }
320+ if db.is_infinite() {
321+ identical += 1;
322+ }
323+ worst = worst.min(db);
324+ compared += 1;
325+ });
326+ let decoded = result.expect("decode succeeds");
327+ assert!(
328+ !mismatched_size,
329+ "{}: frame size disagrees with ffmpeg",
330+ path.display()
331+ );
332+ assert!(compared > 0, "{}: nothing decoded", path.display());
333+ table.push(format!(
334+ "{:<40} {decoded:>3} frames, {identical:>3}/{compared} identical, worst {}",
335+ path.file_name().unwrap_or_default().to_string_lossy(),
336+ if worst.is_infinite() {
337+ "exact".to_string()
338+ } else {
339+ format!("{worst:.1} dB")
340+ }
341+ ));
342+ assert!(
343+ worst >= 40.0,
344+ "{}: worst frame PSNR {worst:.1} dB against ffmpeg",
345+ path.display()
346+ );
347+ }
348+ for row in table {
349+ println!("{row}");
350+ }
351+}
352+
353+/// The 4:2:0 fixtures of one kind; the 4:4:4 and monochrome ones are the
354+/// profiles this GPU does not decode, and have their own test.
355+fn profile_420(pattern: &str, codec: &str) -> Vec<PathBuf> {
356+ fixtures(pattern)
357+ .into_iter()
358+ .filter(|p| {
359+ let name = p.to_string_lossy().to_string();
360+ name.contains(codec) && !name.contains("444") && !name.contains("monochrome")
361+ })
362+ .collect()
363+}
364+
365+fn eight_bit(pattern: &str, codec: &str) -> Vec<PathBuf> {
366+ profile_420(pattern, codec)
367+ .into_iter()
368+ .filter(|p| !p.to_string_lossy().contains("10bit"))
369+ .collect()
370+}
371+
372+fn ten_bit(pattern: &str, codec: &str) -> Vec<PathBuf> {
373+ profile_420(pattern, codec)
374+ .into_iter()
375+ .filter(|p| p.to_string_lossy().contains("10bit"))
376+ .collect()
377+}
378+
379+#[test]
380+fn h264_matches_ffmpeg() {
381+ compare_against_ffmpeg(&fixtures(".264"), Codec::H264, false);
382+}
383+
384+#[test]
385+fn hevc_8bit_matches_ffmpeg() {
386+ compare_against_ffmpeg(&eight_bit(".265", "hevc"), Codec::H265, false);
387+}
388+
389+/// The 10-bit path, which is the RT format defect this crate exists to not
390+/// repeat: a Main10 stream must get a `VA_RT_FORMAT_YUV420_10` context and a
391+/// P010 surface, and the ten bits must survive to the caller.
392+#[test]
393+fn hevc_10bit_decodes_to_p010() {
394+ let files = ten_bit(".265", "hevc");
395+ if files.is_empty() {
396+ eprintln!("skipped: no 10-bit HEVC fixtures");
397+ return;
398+ }
399+ let Some(display) = display() else { return };
400+ let data = std::fs::read(&files[0]).expect("fixture is readable");
401+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
402+ let mut depth = 0u8;
403+ decode_stream(&mut decoder, Codec::H265, &data, 1, |frame| {
404+ depth = frame.bit_depth;
405+ })
406+ .expect("decode succeeds");
407+ assert_eq!(depth, 10, "a Main10 stream decoded at {depth} bits");
408+ let info = decoder.stream_info().expect("the session exists");
409+ assert_eq!(info.bit_depth, 10);
410+ assert_eq!(info.profile, ec_va::caps::Profile::HEVCMain10);
411+
412+ compare_against_ffmpeg(&files, Codec::H265, true);
413+}
414+
415+#[test]
416+fn vp9_matches_ffmpeg() {
417+ compare_against_ffmpeg(&eight_bit(".ivf", "vp9"), Codec::Vp9, false);
418+}
419+
420+#[test]
421+fn vp9_10bit_matches_ffmpeg() {
422+ compare_against_ffmpeg(&ten_bit(".ivf", "vp9"), Codec::Vp9, true);
423+}
424+
425+#[test]
426+fn av1_matches_ffmpeg() {
427+ compare_against_ffmpeg(&eight_bit(".ivf", "av1"), Codec::Av1, false);
428+}
429+
430+#[test]
431+fn av1_10bit_matches_ffmpeg() {
432+ compare_against_ffmpeg(&ten_bit(".ivf", "av1"), Codec::Av1, true);
433+}
434+
435+/// Every "not supported" this crate says has to be a fact about the driver, not
436+/// a string. This GPU decodes VP9 profiles 0 and 2 and AV1 profiles 0 and 2 —
437+/// so the 4:4:4 fixtures must come back as a typed refusal naming the profile,
438+/// and the capability report must agree that the profile is absent.
439+#[test]
440+fn unsupported_profiles_are_refused_with_a_reason() {
441+ let Some(display) = display() else { return };
442+ let caps = ec_va::CapReport::probe(&display).expect("caps probe");
443+ for (file, codec, absent) in [
444+ (
445+ "vp9-profile1-444.ivf",
446+ Codec::Vp9,
447+ ec_va::caps::Profile::VP9Profile1,
448+ ),
449+ (
450+ "av1-profile1-444.ivf",
451+ Codec::Av1,
452+ ec_va::caps::Profile::AV1Profile1,
453+ ),
454+ ] {
455+ let path = bitstreams().join(file);
456+ if !path.exists() {
457+ eprintln!("skipped: no {file}");
458+ continue;
459+ }
460+ assert!(
461+ !caps.supports(absent, ec_va::caps::Entrypoint::VLD),
462+ "{absent:?} is in fact supported — the refusal below would be a bug"
463+ );
464+ let data = std::fs::read(&path).expect("fixture is readable");
465+ let mut decoder = Decoder::new(&display, codec).expect("decoder opens");
466+ let err = decode_stream(&mut decoder, codec, &data, 1, |_| {})
467+ .expect_err("a 4:4:4 stream must be refused");
468+ let message = err.to_string();
469+ assert!(
470+ matches!(err, ec_hw::Error::Unsupported { .. }),
471+ "{file}: expected a typed refusal, got {message}"
472+ );
473+ println!("{file}: {message}");
474+ }
475+}
476+
477+// ---------------------------------------------------------------------------
478+// Encoding
479+// ---------------------------------------------------------------------------
480+
481+/// A moving synthetic frame: a gradient with a box that travels, so motion
482+/// compensation has something to find and a static-image encoder cannot cheat.
483+fn source_frame(width: u32, height: u32, t: u32) -> I420 {
484+ let (w, h) = (width as usize, height as usize);
485+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
486+ let mut f = I420 {
487+ y: vec![0; w * h],
488+ u: vec![128; cw * ch],
489+ v: vec![128; cw * ch],
490+ width,
491+ height,
492+ };
493+ for y in 0..h {
494+ for x in 0..w {
495+ f.y[y * w + x] = ((x * 200 / w) + (y * 55 / h)) as u8;
496+ }
497+ }
498+ let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64));
499+ for y in by..by + 64 {
500+ for x in bx..bx + 64 {
501+ f.y[y * w + x] = 235;
502+ }
503+ }
504+ for y in by / 2..(by + 64) / 2 {
505+ for x in bx / 2..(bx + 64) / 2 {
506+ f.u[y * cw + x] = 90;
507+ f.v[y * cw + x] = 240;
508+ }
509+ }
510+ f
511+}
512+
513+/// Encode `frames` synthetic pictures and return the bitstream.
514+fn encode_stream(
515+ display: &Arc<Display>,
516+ codec: EncCodec,
517+ width: u32,
518+ height: u32,
519+ frames: u32,
520+ allow_av1: bool,
521+) -> Result<Vec<u8>, ec_hw::Error> {
522+ let mut config = EncoderConfig::new(codec, width, height);
523+ config.gop_size = 30;
524+ config.framerate = (30, 1);
525+ config.rate_control = RateControlMode::ConstantQp { qp: 26 };
526+ config.allow_av1 = allow_av1;
527+ let mut encoder = Encoder::new(display, config)?;
528+ let mut out = Vec::new();
529+ for t in 0..frames {
530+ let coded = encoder.encode(
531+ &source_frame(width, height, t),
532+ FrameMetadata {
533+ timestamp: i64::from(t),
534+ force_keyframe: false,
535+ },
536+ )?;
537+ assert_eq!(coded.is_keyframe, t == 0, "GOP structure at frame {t}");
538+ out.extend_from_slice(&coded.data);
539+ }
540+ Ok(out)
541+}
542+
543+/// Decode a bitstream with ffmpeg and compare with the frames that went in.
544+fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) {
545+ let Some(display) = display() else { return };
546+ let frames = 12u32;
547+ let stream = match encode_stream(&display, codec, width, height, frames, false) {
548+ Ok(stream) => stream,
549+ Err(e) => panic!("{codec:?} encode failed: {e}"),
550+ };
551+ assert!(
552+ stream.len() > 1000,
553+ "{codec:?}: {} bytes is not a stream",
554+ stream.len()
555+ );
556+
557+ let dir = std::env::temp_dir().join(format!("ec-hw-{codec:?}-{width}x{height}"));
558+ std::fs::create_dir_all(&dir).expect("temp dir");
559+ let path = dir.join(match codec {
560+ EncCodec::H264 => "out.264",
561+ EncCodec::H265 => "out.265",
562+ EncCodec::Av1 => "out.obu",
563+ });
564+ std::fs::write(&path, &stream).expect("write bitstream");
565+
566+ // ffprobe first: the conformance window / frame cropping has to survive, so
567+ // a 1916-wide encode comes back 1916 wide and not 1920.
568+ let probe = Command::new("ffprobe")
569+ .args([
570+ "-v",
571+ "error",
572+ "-select_streams",
573+ "v:0",
574+ "-show_entries",
575+ "stream=width,height",
576+ "-of",
577+ "csv=p=0",
578+ ])
579+ .arg(&path)
580+ .output()
581+ .expect("ffprobe runs");
582+ let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string();
583+ assert_eq!(
584+ dims,
585+ format!("{width},{height}"),
586+ "{codec:?}: ffprobe sees {dims}"
587+ );
588+
589+ let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs");
590+ let mut worst = f64::INFINITY;
591+ let mut compared = 0u32;
592+ for t in 0..frames {
593+ let Some(got) = reference.next(width, height) else {
594+ break;
595+ };
596+ let want = Planes::from_8bit(&source_frame(width, height, t));
597+ let db = psnr(&got, &want);
598+ worst = worst.min(db);
599+ compared += 1;
600+ }
601+ assert_eq!(
602+ compared, frames,
603+ "{codec:?}: ffmpeg decoded {compared} of {frames}"
604+ );
605+ println!(
606+ "{codec:?} {width}x{height}: {compared} frames, {} bytes, worst {worst:.1} dB vs source",
607+ stream.len()
608+ );
609+ assert!(
610+ worst >= min_db,
611+ "{codec:?}: worst frame {worst:.1} dB against the source"
612+ );
613+}
614+
615+#[test]
616+fn h264_encode_round_trips_through_ffmpeg() {
617+ round_trip(EncCodec::H264, 640, 480, 30.0);
618+}
619+
620+#[test]
621+fn hevc_encode_round_trips_through_ffmpeg() {
622+ round_trip(EncCodec::H265, 640, 480, 30.0);
623+}
624+
625+/// 1916x1080 is the shape that broke the incumbent HEVC encoder: the coded size
626+/// is 1920x1088, and only the conformance window brings it back.
627+#[test]
628+fn hevc_encode_honours_the_conformance_window() {
629+ round_trip(EncCodec::H265, 1916, 1080, 30.0);
630+}
631+
632+/// What this crate encodes, its own hardware decoder must decode.
633+#[test]
634+fn our_encoder_and_our_decoder_agree() {
635+ let Some(display) = display() else { return };
636+ for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
637+ let stream = encode_stream(&display, enc, 640, 480, 12, false).expect("encode");
638+ let mut decoder = Decoder::new(&display, dec).expect("decoder opens");
639+ let mut worst = f64::INFINITY;
640+ let mut count = 0u32;
641+ decode_stream(&mut decoder, dec, &stream, 12, |frame| {
642+ let got = Planes::from_8bit(&frame.to_i420().expect("readback"));
643+ let want = Planes::from_8bit(&source_frame(640, 480, count));
644+ worst = worst.min(psnr(&got, &want));
645+ count += 1;
646+ })
647+ .expect("decode");
648+ assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames");
649+ println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source");
650+ assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB");
651+ }
652+}
653+
654+/// AV1 encoding is opt-in, and this test does not turn it on.
655+///
656+/// It was probed once, live, at the driver's own minimum encode size
657+/// (radeonsi reports 320x128 for AV1 `EncSlice`) on 2026-08-14. The submission
658+/// took the GPU down:
659+///
660+/// ```text
661+/// amdgpu: The CS has cancelled because the context is lost.
662+/// This context is guilty of a hard recovery.
663+/// ```
664+///
665+/// The process was aborted by the driver, not by this crate — there is no error
666+/// to return from a context that no longer exists. So the probe is *recorded*
667+/// rather than repeated: what this test asserts is the guard that keeps the
668+/// path off unless a caller asks for it by name, which is the only defence a
669+/// library has against a driver bug of that class.
670+#[test]
671+fn av1_encode_is_opt_in() {
672+ let Some(display) = display() else { return };
673+ let refused = Encoder::new(&display, EncoderConfig::new(EncCodec::Av1, 320, 128));
674+ assert!(
675+ matches!(refused, Err(ec_hw::Error::Unsupported { .. })),
676+ "AV1 encoding must be refused without the explicit opt-in"
677+ );
678+ // With the opt-in the encoder builds — the parameters, the surface pool and
679+ // the context are all real; only `encode()` is left untested here.
680+ let mut config = EncoderConfig::new(EncCodec::Av1, 320, 128);
681+ config.allow_av1 = true;
682+ match Encoder::new(&display, config) {
683+ Ok(encoder) => println!(
684+ "AV1 encode: opt-in encoder built at {:?}, submission deliberately not run",
685+ encoder.coded_size()
686+ ),
687+ Err(e) => println!("AV1 encode: refused by the driver, typed error: {e}"),
688+ }
689+}
690+
691+// ---------------------------------------------------------------------------
692+// The four incumbent defects, as tests
693+// ---------------------------------------------------------------------------
694+
695+/// A `frame_num` gap is normal, not corruption.
696+///
697+/// Dropping a reference picture from the middle of a GOP is what a seek, a lost
698+/// packet or an encoder that skipped a picture all look like. The incumbent
699+/// stack treated it as an error and fell back to software for the rest of the
700+/// timeline; here the missing pictures are inferred (8.2.5.2) and decoding
701+/// carries on in hardware.
702+#[test]
703+fn h264_frame_num_gaps_are_synthesised() {
704+ let Some(display) = display() else { return };
705+ let path = bitstreams().join("h264-1080p-23.976-8bit.264");
706+ if !path.exists() {
707+ eprintln!("skipped: no H.264 fixture");
708+ return;
709+ }
710+ let data = std::fs::read(&path).expect("fixture is readable");
711+ let units = split_access_units(&data, Codec::H264);
712+ assert!(
713+ units.len() > 8,
714+ "fixture is too short to drop a picture from"
715+ );
716+
717+ // Drop two reference pictures from the middle of the first GOP.
718+ let mut kept: Vec<&[u8]> = Vec::new();
719+ for (i, unit) in units.iter().enumerate() {
720+ if (3..=5).contains(&i) {
721+ continue;
722+ }
723+ kept.push(unit);
724+ }
725+
726+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
727+ let mut frames = 0usize;
728+ for (i, unit) in kept.iter().enumerate().take(20) {
729+ if let Err(e) = decoder.decode(unit, i as i64) {
730+ panic!(
731+ "unit {i} failed after {} gap frames: {e}",
732+ decoder.gap_frames_synthesized()
733+ );
734+ }
735+ while let Some(frame) = decoder.next_frame() {
736+ // The frame is real: reading it back must work, not just arrive.
737+ let planes = frame.to_i420().expect("readback");
738+ assert_eq!(planes.y.len(), 1920 * 1080);
739+ frames += 1;
740+ }
741+ }
742+ decoder.flush().expect("flush");
743+ while decoder.next_frame().is_some() {
744+ frames += 1;
745+ }
746+ let synthesised = decoder.gap_frames_synthesized();
747+ println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred");
748+ assert!(synthesised > 0, "the gap was not detected");
749+ assert!(frames >= 10, "only {frames} frames survived the gap");
750+}
751+
752+/// VmRSS in kilobytes, from `/proc/self/status`.
753+fn rss_kb() -> u64 {
754+ let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
755+ status
756+ .lines()
757+ .find_map(|line| line.strip_prefix("VmRSS:"))
758+ .and_then(|v| v.split_whitespace().next().map(|n| n.to_string()))
759+ .and_then(|n| n.parse().ok())
760+ .unwrap_or(0)
761+}
762+
763+/// Decode and read back for longer than any export, and watch the resident set.
764+///
765+/// The incumbent leaked ~3 MB per frame by mapping a VA image and never
766+/// unmapping it: a 719-frame export lost 2 GB. Every mapping here is a guard
767+/// that unmaps on drop, and this is the test that says so out loud.
768+#[test]
769+fn long_decode_does_not_grow_the_resident_set() {
770+ let Some(display) = display() else { return };
771+ let path = bitstreams().join("h264-1080p-23.976-8bit.264");
772+ if !path.exists() {
773+ eprintln!("skipped: no H.264 fixture");
774+ return;
775+ }
776+ let data = std::fs::read(&path).expect("fixture is readable");
777+ let units = split_access_units(&data, Codec::H264);
778+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
779+
780+ // Warm up first: the first pictures allocate the surface pool and the
781+ // readback image, and that growth is not a leak.
782+ let mut decoded = 0usize;
783+ let mut baseline = 0u64;
784+ let mut readback_ms = 0f64;
785+ let mut pending: Vec<Frame> = Vec::new();
786+ let target = 719usize;
787+ 'outer: for pass in 0..16 {
788+ if pass > 0 {
789+ decoder.reset();
790+ }
791+ for (i, unit) in units.iter().enumerate() {
792+ decoder.decode(unit, i as i64).expect("decode");
793+ while let Some(frame) = decoder.next_frame() {
794+ // Hold a few frames before reading any back: a decoder that is
795+ // read one frame per submission spends its time waiting for the
796+ // GPU, which measures latency rather than throughput.
797+ pending.push(frame);
798+ if pending.len() < 4 {
799+ continue;
800+ }
801+ let start = std::time::Instant::now();
802+ for frame in pending.drain(..) {
803+ let planes = frame.to_i420().expect("readback");
804+ std::hint::black_box(&planes);
805+ decoded += 1;
806+ }
807+ readback_ms += start.elapsed().as_secs_f64() * 1000.0;
808+ if decoded == 60 {
809+ baseline = rss_kb();
810+ }
811+ if decoded >= target {
812+ break 'outer;
813+ }
814+ }
815+ }
816+ }
817+ decoder.flush().expect("flush");
818+ let end = rss_kb();
819+ let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0;
820+ println!(
821+ "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \
822+ decode and read back {:.2} ms/frame at 1920x1080",
823+ readback_ms / decoded as f64
824+ );
825+ assert!(decoded >= target, "only {decoded} frames decoded");
826+ assert!(
827+ delta_mb < 50.0,
828+ "resident set grew {delta_mb:.1} MB over {decoded} frames"
829+ );
830+}
831+
832+/// The zero-copy path: a decoded surface exports as DRM PRIME file descriptors.
833+///
834+/// This is what edith's `engine-hw` imports into gbm, so the fds and the plane
835+/// layout matter as much as the pixels do.
836+#[test]
837+fn frames_export_as_dma_buf() {
838+ let Some(display) = display() else { return };
839+ let path = bitstreams().join("h264-1080p-23.976-8bit.264");
840+ if !path.exists() {
841+ eprintln!("skipped: no H.264 fixture");
842+ return;
843+ }
844+ let data = std::fs::read(&path).expect("fixture is readable");
845+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
846+ let mut exported = 0usize;
847+ decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| {
848+ let prime = frame.export_prime().expect("export");
849+ assert_eq!(prime.fourcc, ec_va::sys::VA_FOURCC_NV12);
850+ assert_eq!((prime.width, prime.height), frame.coded_size);
851+ assert!(!prime.objects.is_empty(), "no DRM objects exported");
852+ assert!(!prime.layers.is_empty(), "no layers exported");
853+ let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum();
854+ assert!(
855+ planes >= 2,
856+ "NV12 needs a luma and a chroma plane, got {planes}"
857+ );
858+ exported += 1;
859+ })
860+ .expect("decode");
861+ assert!(exported >= 1, "nothing was exported");
862+ println!("DRM PRIME export: {exported} frames");
863+}
864+
865+// ---------------------------------------------------------------------------
866+// His library
867+// ---------------------------------------------------------------------------
868+
869+/// Turn any container into an elementary stream ffmpeg and this crate agree on.
870+fn elementary(path: &Path, codec: Codec) -> Option<Vec<u8>> {
871+ let args: &[&str] = match codec {
872+ Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"],
873+ Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"],
874+ Codec::Vp9 | Codec::Av1 => &["-f", "ivf"],
875+ };
876+ let out = Command::new("ffmpeg")
877+ .args(["-nostdin", "-v", "error", "-i"])
878+ .arg(path)
879+ .args(["-map", "0:v:0", "-c:v", "copy"])
880+ .args(args)
881+ .arg("-")
882+ .stderr(Stdio::null())
883+ .output()
884+ .ok()?;
885+ (!out.stdout.is_empty()).then_some(out.stdout)
886+}
887+
888+/// Decode 500 frames of five files from the real library and compare with
889+/// ffmpeg, per file.
890+///
891+/// Fixtures are 5-second synthetic clips at round resolutions; his library is
892+/// 1038-high HEVC, 792-high AV1 and hour-long H.264 screen captures. A claim
893+/// that has not met those is a claim about fixtures.
894+#[test]
895+fn real_library_spot_check() {
896+ let Some(display) = display() else { return };
897+ let manifest =
898+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
899+ let Ok(text) = std::fs::read_to_string(&manifest) else {
900+ eprintln!(
901+ "skipped: no fixtures/real-library-manifest.tsv — run scripts/scan-real-library.sh"
902+ );
903+ return;
904+ };
905+
906+ // One file per (codec, bit depth) the hardware path serves, five in all.
907+ let mut wanted: Vec<(String, Codec, bool)> = Vec::new();
908+ let mut seen: Vec<(String, u8)> = Vec::new();
909+ for line in text.lines().skip(1) {
910+ let f: Vec<&str> = line.split('\t').collect();
911+ if f.len() < 7 {
912+ continue;
913+ }
914+ let (path, vcodec, depth) = (f[0].to_string(), f[2], f[6].parse::<u8>().unwrap_or(8));
915+ let codec = match vcodec {
916+ "h264" => Codec::H264,
917+ "hevc" => Codec::H265,
918+ "vp9" => Codec::Vp9,
919+ "av1" => Codec::Av1,
920+ _ => continue,
921+ };
922+ let key = (vcodec.to_string(), depth);
923+ if seen.iter().filter(|k| **k == key).count() >= 2 || wanted.len() >= 5 {
924+ continue;
925+ }
926+ if !Path::new(&path).exists() {
927+ continue;
928+ }
929+ seen.push(key);
930+ wanted.push((path, codec, depth > 8));
931+ }
932+ if wanted.is_empty() {
933+ eprintln!("skipped: no files from the manifest are present");
934+ return;
935+ }
936+
937+ let mut table = Vec::new();
938+ for (path, codec, ten_bit) in &wanted {
939+ let path = Path::new(path);
940+ let Some(data) = elementary(path, *codec) else {
941+ table.push(format!("{:<52} SKIP (no elementary stream)", short(path)));
942+ continue;
943+ };
944+ let mut decoder = Decoder::new(&display, *codec).expect("decoder opens");
945+ let mut reference: Option<Reference> = None;
946+ let mut worst = f64::INFINITY;
947+ let mut compared = 0usize;
948+ let mut failed: Option<String> = None;
949+ let result = decode_stream(&mut decoder, *codec, &data, 500, |frame| {
950+ let (w, h) = frame.display_size;
951+ let reference = reference
952+ .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs"));
953+ let Some(want) = reference.next(w, h) else {
954+ return;
955+ };
956+ let got = if *ten_bit {
957+ Planes::from_16bit(&frame.to_i420_16().expect("readback"))
958+ } else {
959+ Planes::from_8bit(&frame.to_i420().expect("readback"))
960+ };
961+ if got.y.len() != want.y.len() {
962+ failed = Some("frame size disagrees with ffmpeg".to_string());
963+ return;
964+ }
965+ worst = worst.min(psnr(&got, &want));
966+ compared += 1;
967+ });
968+ match result {
969+ Ok(decoded) => table.push(format!(
970+ "{:<52} {decoded:>4} frames, {compared} compared, worst {}",
971+ short(path),
972+ if worst.is_infinite() {
973+ "exact".to_string()
974+ } else {
975+ format!("{worst:.1} dB")
976+ }
977+ )),
978+ Err(e) => failed = Some(e.to_string()),
979+ }
980+ if let Some(reason) = failed {
981+ table.push(format!("{:<52} FAIL {reason}", short(path)));
982+ }
983+ assert!(compared > 0, "{}: nothing decoded", short(path));
984+ assert!(
985+ worst >= 40.0,
986+ "{}: worst frame {worst:.1} dB against ffmpeg",
987+ short(path)
988+ );
989+ }
990+ for row in table {
991+ println!("{row}");
992+ }
993+}
994+
995+/// A library path without the directory tree, so a report can carry it.
996+fn short(path: &Path) -> String {
997+ path.file_name()
998+ .map(|n| n.to_string_lossy().to_string())
999+ .unwrap_or_default()
1000+}
scripts/gen-bitstream-fixtures.shmodified+24 -0
@@ -54,6 +54,20 @@ for src in "$FIXTURES"/video/*vp9*.mp4 "$FIXTURES"/video/*av1*.mp4; do
54 run "$OUT/${base%.*}.ivf" -i "$src" -map 0:v:0 -c:v copy -f ivf54 run "$OUT/${base%.*}.ivf" -i "$src" -map 0:v:0 -c:v copy -f ivf
55 done55 done
56 56
57+# (a2) H.264/HEVC elementary streams in Annex B form, for the hardware decoder:
58+# a stateless decoder is fed NAL units, and the mp4 fixtures carry them
59+# length-prefixed. `-bsf` puts the start codes and the in-band parameter sets back.
60+for src in "$FIXTURES"/video/*h264*.mp4; do
61+ [ -e "$src" ] || continue
62+ base=$(basename "$src")
63+ run "$OUT/${base%.*}.264" -i "$src" -map 0:v:0 -c:v copy -bsf:v h264_mp4toannexb -f h264
64+done
65+for src in "$FIXTURES"/video/*hevc*.mp4; do
66+ [ -e "$src" ] || continue
67+ base=$(basename "$src")
68+ run "$OUT/${base%.*}.265" -i "$src" -map 0:v:0 -c:v copy -bsf:v hevc_mp4toannexb -f hevc
69+done
70+
57 # (b) branch coverage the container set does not have.71 # (b) branch coverage the container set does not have.
58 SYN="-f lavfi -i testsrc2=size=320x240:rate=30:duration=2"72 SYN="-f lavfi -i testsrc2=size=320x240:rate=30:duration=2"
59 73
@@ -96,6 +110,16 @@ run "$OUT/av1-monochrome.ivf" $SYN -c:v libaom-av1 -pix_fmt gray \
96 -cpu-used 8 -b:v 300k -f ivf110 -cpu-used 8 -b:v 300k -f ivf
97 run "$OUT/av1-tiles-1280.ivf" -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \111 run "$OUT/av1-tiles-1280.ivf" -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \
98 -c:v libaom-av1 -pix_fmt yuv420p -tiles 2x2 -cpu-used 8 -b:v 1M -f ivf112 -c:v libaom-av1 -pix_fmt yuv420p -tiles 2x2 -cpu-used 8 -b:v 1M -f ivf
113+# H.264 with B frames and an open GOP: reordering, so the decoder's output order
114+# is exercised rather than assumed, plus 4 reference frames for the DPB.
115+# shellcheck disable=SC2086
116+run "$OUT/h264-bframes-320.264" $SYN -c:v libx264 -pix_fmt yuv420p -bf 3 -refs 4 \
117+ -g 30 -b:v 500k -f h264
118+# HEVC with B frames, for the same reason on the reference-picture-set side.
119+# shellcheck disable=SC2086
120+run "$OUT/hevc-bframes-320.265" $SYN -c:v libx265 -pix_fmt yuv420p \
121+ -x265-params "bframes=3:ref=3:keyint=30:log-level=none" -b:v 500k -f hevc
122+
99 # AV1 with a hidden ALTREF: forward keyframe + show_existing_frame headers.123 # AV1 with a hidden ALTREF: forward keyframe + show_existing_frame headers.
100 # shellcheck disable=SC2086124 # shellcheck disable=SC2086
101 run "$OUT/av1-altref.ivf" $SYN -c:v libaom-av1 -pix_fmt yuv420p \125 run "$OUT/av1-altref.ivf" $SYN -c:v libaom-av1 -pix_fmt yuv420p \