forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

gpu.rs1218 lines, 43.5 KiBHistoryRawDownload
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
11use std::io::Read;
12use std::path::{Path, PathBuf};
13use std::process::{Command, Stdio};
14use std::sync::Arc;
15
16use ec_hw::{
17 Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode,
18};
19use 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.
23const FRAMES: usize = 24;
24
25fn bitstreams() -> PathBuf {
26 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams")
27}
28
29fn 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
39fn 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.
57struct Reference {
58 child: std::process::Child,
59 frame_bytes: usize,
60 ten_bit: bool,
61}
62
63impl 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 // `-fps_mode passthrough`: without it ffmpeg conforms its output to
70 // the container's nominal frame rate, duplicating or dropping
71 // pictures on a film whose real cadence differs — which shows up
72 // here as everything being one frame out from some point onward.
73 .args([
74 "-map", "0:v:0", "-fps_mode", "passthrough", "-pix_fmt", pix, "-f", "rawvideo", "-",
75 ])
76 .stdout(Stdio::piped())
77 .stderr(Stdio::null())
78 .spawn()
79 .ok()?;
80 let samples = (width as usize * height as usize * 3).div_ceil(2);
81 Some(Reference {
82 child,
83 frame_bytes: if ten_bit { samples * 2 } else { samples },
84 ten_bit,
85 })
86 }
87
88 /// The next reference frame, as samples at the stream's own bit depth.
89 ///
90 /// A 10-bit stream is compared at 10 bits rather than converted down:
91 /// `ffmpeg -pix_fmt yuv420p` on a 10-bit source dithers, which would hide a
92 /// real difference behind a fake 53 dB one (measured, not assumed).
93 fn next(&mut self, width: u32, height: u32) -> Option<Planes> {
94 let stdout = self.child.stdout.as_mut()?;
95 let mut buf = vec![0u8; self.frame_bytes];
96 stdout.read_exact(&mut buf).ok()?;
97 let (w, h) = (width as usize, height as usize);
98 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
99 let (y_len, c_len) = (w * h, cw * ch);
100 if self.ten_bit {
101 let read = |slice: &[u8]| -> Vec<u16> {
102 slice
103 .chunks_exact(2)
104 .map(|p| u16::from_le_bytes([p[0], p[1]]))
105 .collect()
106 };
107 Some(Planes {
108 y: read(&buf[..y_len * 2]),
109 u: read(&buf[y_len * 2..(y_len + c_len) * 2]),
110 v: read(&buf[(y_len + c_len) * 2..(y_len + 2 * c_len) * 2]),
111 peak: 1023.0,
112 })
113 } else {
114 let read = |slice: &[u8]| -> Vec<u16> { slice.iter().map(|&v| u16::from(v)).collect() };
115 Some(Planes {
116 y: read(&buf[..y_len]),
117 u: read(&buf[y_len..y_len + c_len]),
118 v: read(&buf[y_len + c_len..y_len + 2 * c_len]),
119 peak: 255.0,
120 })
121 }
122 }
123}
124
125impl Drop for Reference {
126 fn drop(&mut self) {
127 let _ = self.child.kill();
128 let _ = self.child.wait();
129 }
130}
131
132/// Three planes at whatever bit depth the stream carries.
133struct Planes {
134 y: Vec<u16>,
135 u: Vec<u16>,
136 v: Vec<u16>,
137 peak: f64,
138}
139
140impl Planes {
141 fn from_8bit(f: &I420) -> Planes {
142 let read = |v: &[u8]| -> Vec<u16> { v.iter().map(|&s| u16::from(s)).collect() };
143 Planes {
144 y: read(&f.y),
145 u: read(&f.u),
146 v: read(&f.v),
147 peak: 255.0,
148 }
149 }
150
151 fn from_16bit(f: &ec_hw::I420_16) -> Planes {
152 Planes {
153 y: f.y.clone(),
154 u: f.u.clone(),
155 v: f.v.clone(),
156 peak: 1023.0,
157 }
158 }
159}
160
161/// Peak signal to noise ratio over the three planes, in dB; `f64::INFINITY`
162/// when the frames are identical.
163fn psnr(a: &Planes, b: &Planes) -> f64 {
164 let mut sum = 0f64;
165 let mut n = 0usize;
166 for (x, y) in [(&a.y, &b.y), (&a.u, &b.u), (&a.v, &b.v)] {
167 for (p, q) in x.iter().zip(y.iter()) {
168 let d = f64::from(*p) - f64::from(*q);
169 sum += d * d;
170 }
171 n += x.len().min(y.len());
172 }
173 if n == 0 {
174 return 0.0;
175 }
176 let mse = sum / n as f64;
177 if mse == 0.0 {
178 return f64::INFINITY;
179 }
180 10.0 * (a.peak * a.peak / mse).log10()
181}
182
183/// Feed a whole elementary stream to a decoder, collecting frames.
184///
185/// H.264 and HEVC are fed access unit by access unit, which is what a demuxer
186/// hands over; VP9 and AV1 arrive as IVF frames.
187fn decode_stream(
188 decoder: &mut Decoder,
189 codec: Codec,
190 data: &[u8],
191 limit: usize,
192 mut on_frame: impl FnMut(Frame),
193) -> Result<usize, ec_hw::Error> {
194 let mut count = 0usize;
195 let units: Vec<&[u8]> = match codec {
196 Codec::H264 | Codec::H265 => split_access_units(data, codec),
197 Codec::Vp9 | Codec::Av1 => split_ivf(data),
198 };
199 for (i, unit) in units.iter().enumerate() {
200 decoder.decode(unit, i as i64)?;
201 while let Some(frame) = decoder.next_frame() {
202 count += 1;
203 on_frame(frame);
204 if count >= limit {
205 return Ok(count);
206 }
207 }
208 }
209 decoder.flush()?;
210 while let Some(frame) = decoder.next_frame() {
211 count += 1;
212 on_frame(frame);
213 if count >= limit {
214 break;
215 }
216 }
217 Ok(count)
218}
219
220/// Split an Annex B stream into access units: a new one starts at the first
221/// VCL NAL of a picture, i.e. at an AUD, a parameter set, or a slice whose
222/// first-slice flag is set after a previous slice.
223fn split_access_units(data: &[u8], codec: Codec) -> Vec<&[u8]> {
224 let mut starts: Vec<usize> = Vec::new();
225 let mut seen_slice = false;
226 let mut i = 0usize;
227 while i + 3 < data.len() {
228 if data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 {
229 i += 1;
230 continue;
231 }
232 let nal = i + 3;
233 let (is_vcl, first_slice) = match codec {
234 Codec::H264 => {
235 let t = data[nal] & 0x1f;
236 let first = data.get(nal + 1).is_some_and(|&b| b & 0x80 != 0);
237 ((1..=5).contains(&t), first)
238 }
239 _ => {
240 let t = (data[nal] >> 1) & 0x3f;
241 let first = data.get(nal + 2).is_some_and(|&b| b & 0x80 != 0);
242 (t <= 31, first)
243 }
244 };
245 if is_vcl {
246 if seen_slice && first_slice {
247 starts.push(i);
248 seen_slice = false;
249 }
250 if first_slice {
251 seen_slice = true;
252 }
253 }
254 i = nal + 1;
255 }
256 let mut out = Vec::new();
257 let mut prev = 0usize;
258 for &start in &starts {
259 out.push(&data[prev..start]);
260 prev = start;
261 }
262 if prev < data.len() {
263 out.push(&data[prev..]);
264 }
265 out
266}
267
268/// Split an IVF file into its frames.
269fn split_ivf(data: &[u8]) -> Vec<&[u8]> {
270 let mut out = Vec::new();
271 if data.len() < 32 || &data[..4] != b"DKIF" {
272 return out;
273 }
274 let header = u16::from_le_bytes([data[6], data[7]]) as usize;
275 let mut pos = header.max(32);
276 while pos + 12 <= data.len() {
277 let size =
278 u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
279 pos += 12;
280 if pos + size > data.len() {
281 break;
282 }
283 out.push(&data[pos..pos + size]);
284 pos += size;
285 }
286 out
287}
288
289/// Decode every named fixture and compare with ffmpeg, frame by frame.
290fn compare_against_ffmpeg(files: &[PathBuf], codec: Codec, ten_bit: bool) {
291 let Some(display) = display() else { return };
292 if files.is_empty() {
293 eprintln!("skipped: no fixtures — run scripts/gen-bitstream-fixtures.sh");
294 return;
295 }
296 let mut table = Vec::new();
297 for path in files {
298 let data = std::fs::read(path).expect("fixture is readable");
299 let mut decoder = Decoder::new(&display, codec).expect("decoder opens");
300 let mut reference: Option<Reference> = None;
301 let mut worst = f64::INFINITY;
302 let mut identical = 0usize;
303 let mut compared = 0usize;
304 let mut mismatched_size = false;
305
306 let result = decode_stream(&mut decoder, codec, &data, FRAMES, |frame| {
307 let (w, h) = frame.display_size;
308 let reference = reference
309 .get_or_insert_with(|| Reference::open(path, w, h, ten_bit).expect("ffmpeg runs"));
310 let Some(want) = reference.next(w, h) else {
311 return;
312 };
313 let got = if ten_bit {
314 Planes::from_16bit(&frame.to_i420_16().expect("readback"))
315 } else {
316 Planes::from_8bit(&frame.to_i420().expect("readback"))
317 };
318 if got.y.len() != want.y.len() {
319 mismatched_size = true;
320 return;
321 }
322 let db = psnr(&got, &want);
323 if std::env::var_os("EC_HW_DEBUG").is_some() {
324 eprintln!(" frame {compared}: {db:.1} dB (ts {})", frame.timestamp);
325 }
326 if db.is_infinite() {
327 identical += 1;
328 }
329 worst = worst.min(db);
330 compared += 1;
331 });
332 let decoded = result.expect("decode succeeds");
333 assert!(
334 !mismatched_size,
335 "{}: frame size disagrees with ffmpeg",
336 path.display()
337 );
338 assert!(compared > 0, "{}: nothing decoded", path.display());
339 table.push(format!(
340 "{:<40} {decoded:>3} frames, {identical:>3}/{compared} identical, worst {}",
341 path.file_name().unwrap_or_default().to_string_lossy(),
342 if worst.is_infinite() {
343 "exact".to_string()
344 } else {
345 format!("{worst:.1} dB")
346 }
347 ));
348 assert!(
349 worst >= 40.0,
350 "{}: worst frame PSNR {worst:.1} dB against ffmpeg",
351 path.display()
352 );
353 }
354 for row in table {
355 println!("{row}");
356 }
357}
358
359/// The 4:2:0 fixtures of one kind; the 4:4:4 and monochrome ones are the
360/// profiles this GPU does not decode, and have their own test.
361fn profile_420(pattern: &str, codec: &str) -> Vec<PathBuf> {
362 fixtures(pattern)
363 .into_iter()
364 .filter(|p| {
365 let name = p.to_string_lossy().to_string();
366 name.contains(codec) && !name.contains("444") && !name.contains("monochrome")
367 })
368 .collect()
369}
370
371fn eight_bit(pattern: &str, codec: &str) -> Vec<PathBuf> {
372 profile_420(pattern, codec)
373 .into_iter()
374 .filter(|p| !p.to_string_lossy().contains("10bit"))
375 .collect()
376}
377
378fn ten_bit(pattern: &str, codec: &str) -> Vec<PathBuf> {
379 profile_420(pattern, codec)
380 .into_iter()
381 .filter(|p| p.to_string_lossy().contains("10bit"))
382 .collect()
383}
384
385#[test]
386fn h264_matches_ffmpeg() {
387 compare_against_ffmpeg(&fixtures(".264"), Codec::H264, false);
388}
389
390#[test]
391fn hevc_8bit_matches_ffmpeg() {
392 compare_against_ffmpeg(&eight_bit(".265", "hevc"), Codec::H265, false);
393}
394
395/// The 10-bit path, which is the RT format defect this crate exists to not
396/// repeat: a Main10 stream must get a `VA_RT_FORMAT_YUV420_10` context and a
397/// P010 surface, and the ten bits must survive to the caller.
398#[test]
399fn hevc_10bit_decodes_to_p010() {
400 let files = ten_bit(".265", "hevc");
401 if files.is_empty() {
402 eprintln!("skipped: no 10-bit HEVC fixtures");
403 return;
404 }
405 let Some(display) = display() else { return };
406 let data = std::fs::read(&files[0]).expect("fixture is readable");
407 let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
408 let mut depth = 0u8;
409 decode_stream(&mut decoder, Codec::H265, &data, 1, |frame| {
410 depth = frame.bit_depth;
411 })
412 .expect("decode succeeds");
413 assert_eq!(depth, 10, "a Main10 stream decoded at {depth} bits");
414 let info = decoder.stream_info().expect("the session exists");
415 assert_eq!(info.bit_depth, 10);
416 assert_eq!(info.profile, ec_va::caps::Profile::HEVCMain10);
417
418 compare_against_ffmpeg(&files, Codec::H265, true);
419}
420
421#[test]
422fn vp9_matches_ffmpeg() {
423 compare_against_ffmpeg(&eight_bit(".ivf", "vp9"), Codec::Vp9, false);
424}
425
426#[test]
427fn vp9_10bit_matches_ffmpeg() {
428 compare_against_ffmpeg(&ten_bit(".ivf", "vp9"), Codec::Vp9, true);
429}
430
431#[test]
432fn av1_matches_ffmpeg() {
433 compare_against_ffmpeg(&eight_bit(".ivf", "av1"), Codec::Av1, false);
434}
435
436#[test]
437fn av1_10bit_matches_ffmpeg() {
438 compare_against_ffmpeg(&ten_bit(".ivf", "av1"), Codec::Av1, true);
439}
440
441/// Every "not supported" this crate says has to be a fact about the driver, not
442/// a string. This GPU decodes VP9 profiles 0 and 2 and AV1 profiles 0 and 2 —
443/// so the 4:4:4 fixtures must come back as a typed refusal naming the profile,
444/// and the capability report must agree that the profile is absent.
445#[test]
446fn unsupported_profiles_are_refused_with_a_reason() {
447 let Some(display) = display() else { return };
448 let caps = ec_va::CapReport::probe(&display).expect("caps probe");
449 for (file, codec, absent) in [
450 (
451 "vp9-profile1-444.ivf",
452 Codec::Vp9,
453 ec_va::caps::Profile::VP9Profile1,
454 ),
455 (
456 "av1-profile1-444.ivf",
457 Codec::Av1,
458 ec_va::caps::Profile::AV1Profile1,
459 ),
460 ] {
461 let path = bitstreams().join(file);
462 if !path.exists() {
463 eprintln!("skipped: no {file}");
464 continue;
465 }
466 assert!(
467 !caps.supports(absent, ec_va::caps::Entrypoint::VLD),
468 "{absent:?} is in fact supported — the refusal below would be a bug"
469 );
470 let data = std::fs::read(&path).expect("fixture is readable");
471 let mut decoder = Decoder::new(&display, codec).expect("decoder opens");
472 let err = decode_stream(&mut decoder, codec, &data, 1, |_| {})
473 .expect_err("a 4:4:4 stream must be refused");
474 let message = err.to_string();
475 assert!(
476 matches!(err, ec_hw::Error::Unsupported { .. }),
477 "{file}: expected a typed refusal, got {message}"
478 );
479 println!("{file}: {message}");
480 }
481}
482
483// ---------------------------------------------------------------------------
484// Encoding
485// ---------------------------------------------------------------------------
486
487/// A moving synthetic frame: a gradient with a box that travels, so motion
488/// compensation has something to find and a static-image encoder cannot cheat.
489fn source_frame(width: u32, height: u32, t: u32) -> I420 {
490 let (w, h) = (width as usize, height as usize);
491 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
492 let mut f = I420 {
493 y: vec![0; w * h],
494 u: vec![128; cw * ch],
495 v: vec![128; cw * ch],
496 width,
497 height,
498 };
499 for y in 0..h {
500 for x in 0..w {
501 f.y[y * w + x] = ((x * 200 / w) + (y * 55 / h)) as u8;
502 }
503 }
504 let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64));
505 for y in by..by + 64 {
506 for x in bx..bx + 64 {
507 f.y[y * w + x] = 235;
508 }
509 }
510 for y in by / 2..(by + 64) / 2 {
511 for x in bx / 2..(bx + 64) / 2 {
512 f.u[y * cw + x] = 90;
513 f.v[y * cw + x] = 240;
514 }
515 }
516 f
517}
518
519/// Encode `frames` synthetic pictures and return the bitstream.
520fn encode_stream(
521 display: &Arc<Display>,
522 codec: EncCodec,
523 width: u32,
524 height: u32,
525 frames: u32,
526 allow_av1: bool,
527) -> Result<Vec<u8>, ec_hw::Error> {
528 let mut config = EncoderConfig::new(codec, width, height);
529 config.gop_size = 30;
530 config.framerate = (30, 1);
531 config.rate_control = RateControlMode::ConstantQp { qp: 26 };
532 config.allow_av1 = allow_av1;
533 let mut encoder = Encoder::new(display, config)?;
534 let mut out = Vec::new();
535 for t in 0..frames {
536 let coded = encoder.encode(
537 &source_frame(width, height, t),
538 FrameMetadata {
539 timestamp: i64::from(t),
540 force_keyframe: false,
541 },
542 )?;
543 assert_eq!(coded.is_keyframe, t == 0, "GOP structure at frame {t}");
544 out.extend_from_slice(&coded.data);
545 }
546 Ok(out)
547}
548
549/// Decode a bitstream with ffmpeg and compare with the frames that went in.
550fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) {
551 let Some(display) = display() else { return };
552 let frames = 12u32;
553 let stream = match encode_stream(&display, codec, width, height, frames, false) {
554 Ok(stream) => stream,
555 Err(e) => panic!("{codec:?} encode failed: {e}"),
556 };
557 assert!(
558 stream.len() > 1000,
559 "{codec:?}: {} bytes is not a stream",
560 stream.len()
561 );
562
563 let dir = std::env::temp_dir().join(format!("ec-hw-{codec:?}-{width}x{height}"));
564 std::fs::create_dir_all(&dir).expect("temp dir");
565 let path = dir.join(match codec {
566 EncCodec::H264 => "out.264",
567 EncCodec::H265 => "out.265",
568 EncCodec::Av1 => "out.obu",
569 });
570 std::fs::write(&path, &stream).expect("write bitstream");
571
572 // ffprobe first: the conformance window / frame cropping has to survive, so
573 // a 1916-wide encode comes back 1916 wide and not 1920.
574 let probe = Command::new("ffprobe")
575 .args([
576 "-v",
577 "error",
578 "-select_streams",
579 "v:0",
580 "-show_entries",
581 "stream=width,height",
582 "-of",
583 "csv=p=0",
584 ])
585 .arg(&path)
586 .output()
587 .expect("ffprobe runs");
588 let dims = String::from_utf8_lossy(&probe.stdout).trim().to_string();
589 assert_eq!(
590 dims,
591 format!("{width},{height}"),
592 "{codec:?}: ffprobe sees {dims}"
593 );
594
595 let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs");
596 let mut worst = f64::INFINITY;
597 let mut compared = 0u32;
598 for t in 0..frames {
599 let Some(got) = reference.next(width, height) else {
600 break;
601 };
602 let want = Planes::from_8bit(&source_frame(width, height, t));
603 let db = psnr(&got, &want);
604 worst = worst.min(db);
605 compared += 1;
606 }
607 assert_eq!(
608 compared, frames,
609 "{codec:?}: ffmpeg decoded {compared} of {frames}"
610 );
611 println!(
612 "{codec:?} {width}x{height}: {compared} frames, {} bytes, worst {worst:.1} dB vs source",
613 stream.len()
614 );
615 assert!(
616 worst >= min_db,
617 "{codec:?}: worst frame {worst:.1} dB against the source"
618 );
619}
620
621#[test]
622fn h264_encode_round_trips_through_ffmpeg() {
623 round_trip(EncCodec::H264, 640, 480, 30.0);
624}
625
626#[test]
627fn hevc_encode_round_trips_through_ffmpeg() {
628 round_trip(EncCodec::H265, 640, 480, 30.0);
629}
630
631/// 1916x1080 is the shape that broke the incumbent HEVC encoder: the coded size
632/// is 1920x1088, and only the conformance window brings it back.
633#[test]
634fn hevc_encode_honours_the_conformance_window() {
635 round_trip(EncCodec::H265, 1916, 1080, 30.0);
636}
637
638/// What this crate encodes, its own hardware decoder must decode.
639#[test]
640fn our_encoder_and_our_decoder_agree() {
641 let Some(display) = display() else { return };
642 for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] {
643 let stream = encode_stream(&display, enc, 640, 480, 12, false).expect("encode");
644 let mut decoder = Decoder::new(&display, dec).expect("decoder opens");
645 let mut worst = f64::INFINITY;
646 let mut count = 0u32;
647 decode_stream(&mut decoder, dec, &stream, 12, |frame| {
648 let got = Planes::from_8bit(&frame.to_i420().expect("readback"));
649 let want = Planes::from_8bit(&source_frame(640, 480, count));
650 worst = worst.min(psnr(&got, &want));
651 count += 1;
652 })
653 .expect("decode");
654 assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames");
655 println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source");
656 assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB");
657 }
658}
659
660/// AV1 encoding is opt-in, and this test does not turn it on.
661///
662/// It was probed once, live, at the driver's own minimum encode size
663/// (radeonsi reports 320x128 for AV1 `EncSlice`) on 2026-08-14. The submission
664/// took the GPU down:
665///
666/// ```text
667/// amdgpu: The CS has cancelled because the context is lost.
668/// This context is guilty of a hard recovery.
669/// ```
670///
671/// The process was aborted by the driver, not by this crate — there is no error
672/// to return from a context that no longer exists. So the probe is *recorded*
673/// rather than repeated: what this test asserts is the guard that keeps the
674/// path off unless a caller asks for it by name, which is the only defence a
675/// library has against a driver bug of that class.
676#[test]
677fn av1_encode_is_opt_in() {
678 let Some(display) = display() else { return };
679 let refused = Encoder::new(&display, EncoderConfig::new(EncCodec::Av1, 320, 128));
680 assert!(
681 matches!(refused, Err(ec_hw::Error::Unsupported { .. })),
682 "AV1 encoding must be refused without the explicit opt-in"
683 );
684 // With the opt-in the encoder builds — the parameters, the surface pool and
685 // the context are all real; only `encode()` is left untested here.
686 let mut config = EncoderConfig::new(EncCodec::Av1, 320, 128);
687 config.allow_av1 = true;
688 match Encoder::new(&display, config) {
689 Ok(encoder) => println!(
690 "AV1 encode: opt-in encoder built at {:?}, submission deliberately not run",
691 encoder.coded_size()
692 ),
693 Err(e) => println!("AV1 encode: refused by the driver, typed error: {e}"),
694 }
695}
696
697// ---------------------------------------------------------------------------
698// The four incumbent defects, as tests
699// ---------------------------------------------------------------------------
700
701/// A `frame_num` gap is normal, not corruption.
702///
703/// Dropping a reference picture from the middle of a GOP is what a seek, a lost
704/// packet or an encoder that skipped a picture all look like. The incumbent
705/// stack treated it as an error and fell back to software for the rest of the
706/// timeline; here the missing pictures are inferred (8.2.5.2) and decoding
707/// carries on in hardware.
708#[test]
709fn h264_frame_num_gaps_are_synthesised() {
710 let Some(display) = display() else { return };
711 let path = bitstreams().join("h264-1080p-23.976-8bit.264");
712 if !path.exists() {
713 eprintln!("skipped: no H.264 fixture");
714 return;
715 }
716 let data = std::fs::read(&path).expect("fixture is readable");
717 let units = split_access_units(&data, Codec::H264);
718 assert!(
719 units.len() > 8,
720 "fixture is too short to drop a picture from"
721 );
722
723 // Drop two reference pictures from the middle of the first GOP.
724 let mut kept: Vec<&[u8]> = Vec::new();
725 for (i, unit) in units.iter().enumerate() {
726 if (3..=5).contains(&i) {
727 continue;
728 }
729 kept.push(unit);
730 }
731
732 let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
733 let mut frames = 0usize;
734 for (i, unit) in kept.iter().enumerate().take(20) {
735 if let Err(e) = decoder.decode(unit, i as i64) {
736 panic!(
737 "unit {i} failed after {} gap frames: {e}",
738 decoder.gap_frames_synthesized()
739 );
740 }
741 while let Some(frame) = decoder.next_frame() {
742 // The frame is real: reading it back must work, not just arrive.
743 let planes = frame.to_i420().expect("readback");
744 assert_eq!(planes.y.len(), 1920 * 1080);
745 frames += 1;
746 }
747 }
748 decoder.flush().expect("flush");
749 while decoder.next_frame().is_some() {
750 frames += 1;
751 }
752 let synthesised = decoder.gap_frames_synthesized();
753 println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred");
754 assert!(synthesised > 0, "the gap was not detected");
755 assert!(frames >= 10, "only {frames} frames survived the gap");
756}
757
758/// VmRSS in kilobytes, from `/proc/self/status`.
759fn rss_kb() -> u64 {
760 let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
761 status
762 .lines()
763 .find_map(|line| line.strip_prefix("VmRSS:"))
764 .and_then(|v| v.split_whitespace().next().map(|n| n.to_string()))
765 .and_then(|n| n.parse().ok())
766 .unwrap_or(0)
767}
768
769/// Decode and read back for longer than any export, and watch the resident set.
770///
771/// The incumbent leaked ~3 MB per frame by mapping a VA image and never
772/// unmapping it: a 719-frame export lost 2 GB. Every mapping here is a guard
773/// that unmaps on drop, and this is the test that says so out loud.
774#[test]
775fn long_decode_does_not_grow_the_resident_set() {
776 // VmRSS is a process-wide number and the harness runs every test in this
777 // binary as a thread of one process: a sibling allocating between the
778 // baseline and the end reading shows up here as a 200 MB "leak". The
779 // measurement therefore runs in a child process holding only this test.
780 if std::env::var_os("EC_HW_RSS_CHILD").is_none() {
781 let status = Command::new(std::env::current_exe().expect("test binary path"))
782 .args(["--exact", "long_decode_does_not_grow_the_resident_set"])
783 .env("EC_HW_RSS_CHILD", "1")
784 .status()
785 .expect("re-run this test in its own process");
786 assert!(status.success(), "isolated RSS run failed");
787 return;
788 }
789 let Some(display) = display() else { return };
790 let path = bitstreams().join("h264-1080p-23.976-8bit.264");
791 if !path.exists() {
792 eprintln!("skipped: no H.264 fixture");
793 return;
794 }
795 let data = std::fs::read(&path).expect("fixture is readable");
796 let units = split_access_units(&data, Codec::H264);
797 let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
798
799 // Warm up first: the first pictures allocate the surface pool and the
800 // readback image, and that growth is not a leak.
801 let mut decoded = 0usize;
802 let mut baseline = 0u64;
803 let mut readback_ms = 0f64;
804 let mut pending: Vec<Frame> = Vec::new();
805 let target = 719usize;
806 'outer: for pass in 0..16 {
807 if pass > 0 {
808 decoder.reset();
809 }
810 for (i, unit) in units.iter().enumerate() {
811 decoder.decode(unit, i as i64).expect("decode");
812 while let Some(frame) = decoder.next_frame() {
813 // Hold a few frames before reading any back: a decoder that is
814 // read one frame per submission spends its time waiting for the
815 // GPU, which measures latency rather than throughput.
816 pending.push(frame);
817 if pending.len() < 4 {
818 continue;
819 }
820 let start = std::time::Instant::now();
821 for frame in pending.drain(..) {
822 let planes = frame.to_i420().expect("readback");
823 std::hint::black_box(&planes);
824 decoded += 1;
825 }
826 readback_ms += start.elapsed().as_secs_f64() * 1000.0;
827 if decoded == 60 {
828 baseline = rss_kb();
829 }
830 if decoded >= target {
831 break 'outer;
832 }
833 }
834 }
835 }
836 decoder.flush().expect("flush");
837 let end = rss_kb();
838 let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0;
839 println!(
840 "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \
841 decode and read back {:.2} ms/frame at 1920x1080",
842 readback_ms / decoded as f64
843 );
844 assert!(decoded >= target, "only {decoded} frames decoded");
845 assert!(
846 delta_mb < 50.0,
847 "resident set grew {delta_mb:.1} MB over {decoded} frames"
848 );
849}
850
851/// The zero-copy path: a decoded surface exports as DRM PRIME file descriptors.
852///
853/// This is what edith's `engine-hw` imports into gbm, so the fds and the plane
854/// layout matter as much as the pixels do.
855#[test]
856fn frames_export_as_dma_buf() {
857 let Some(display) = display() else { return };
858 let path = bitstreams().join("h264-1080p-23.976-8bit.264");
859 if !path.exists() {
860 eprintln!("skipped: no H.264 fixture");
861 return;
862 }
863 let data = std::fs::read(&path).expect("fixture is readable");
864 let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
865 let mut exported = 0usize;
866 decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| {
867 let prime = frame.export_prime().expect("export");
868 assert_eq!(prime.fourcc, ec_va::sys::VA_FOURCC_NV12);
869 assert_eq!((prime.width, prime.height), frame.coded_size);
870 assert!(!prime.objects.is_empty(), "no DRM objects exported");
871 assert!(!prime.layers.is_empty(), "no layers exported");
872 let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum();
873 assert!(
874 planes >= 2,
875 "NV12 needs a luma and a chroma plane, got {planes}"
876 );
877 exported += 1;
878 })
879 .expect("decode");
880 assert!(exported >= 1, "nothing was exported");
881 println!("DRM PRIME export: {exported} frames");
882}
883
884// ---------------------------------------------------------------------------
885// His library
886// ---------------------------------------------------------------------------
887
888/// Turn any container into an elementary stream ffmpeg and this crate agree on.
889///
890/// `frames` bounds the extraction: piping a two-hour 4K film through memory to
891/// compare its first five hundred pictures is several gigabytes of nothing.
892fn elementary(path: &Path, codec: Codec, frames: usize) -> Option<Vec<u8>> {
893 let args: &[&str] = match codec {
894 Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"],
895 Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"],
896 Codec::Vp9 | Codec::Av1 => &["-f", "ivf"],
897 };
898 let out = Command::new("ffmpeg")
899 .args(["-nostdin", "-v", "error", "-i"])
900 .arg(path)
901 .args(["-map", "0:v:0", "-c:v", "copy"])
902 // A few more coded pictures than frames wanted: reordering means the
903 // last few packets have not been shown yet.
904 .args(["-frames:v", &(frames + 16).to_string()])
905 .args(args)
906 .arg("-")
907 .stderr(Stdio::null())
908 .output()
909 .ok()?;
910 (!out.stdout.is_empty()).then_some(out.stdout)
911}
912
913/// Decode 500 frames of five files from the real library and compare with
914/// ffmpeg, per file.
915///
916/// Fixtures are 5-second synthetic clips at round resolutions; his library is
917/// 1038-high HEVC, 792-high AV1 and hour-long H.264 screen captures. A claim
918/// that has not met those is a claim about fixtures.
919#[test]
920fn real_library_spot_check() {
921 let Some(display) = display() else { return };
922 let manifest =
923 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
924 let Ok(text) = std::fs::read_to_string(&manifest) else {
925 eprintln!(
926 "skipped: no fixtures/real-library-manifest.tsv — run scripts/scan-real-library.sh"
927 );
928 return;
929 };
930
931 // One file per (codec, bit depth) the hardware path serves, five in all.
932 let mut wanted: Vec<(String, Codec, bool)> = Vec::new();
933 let mut seen: Vec<(String, u8)> = Vec::new();
934 for line in text.lines().skip(1) {
935 let f: Vec<&str> = line.split('\t').collect();
936 if f.len() < 7 {
937 continue;
938 }
939 let (path, vcodec, depth) = (f[0].to_string(), f[2], f[6].parse::<u8>().unwrap_or(8));
940 let codec = match vcodec {
941 "h264" => Codec::H264,
942 "hevc" => Codec::H265,
943 "vp9" => Codec::Vp9,
944 "av1" => Codec::Av1,
945 _ => continue,
946 };
947 let key = (vcodec.to_string(), depth);
948 if seen.iter().filter(|k| **k == key).count() >= 2 || wanted.len() >= 5 {
949 continue;
950 }
951 if !Path::new(&path).exists() {
952 continue;
953 }
954 seen.push(key);
955 wanted.push((path, codec, depth > 8));
956 }
957 if wanted.is_empty() {
958 eprintln!("skipped: no files from the manifest are present");
959 return;
960 }
961
962 // 500 frames per file by default; a diagnostic run can ask for fewer.
963 let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES")
964 .ok()
965 .and_then(|v| v.parse().ok())
966 .unwrap_or(500);
967 let mut table = Vec::new();
968 for (path, codec, ten_bit) in &wanted {
969 let path = Path::new(path);
970 let Some(data) = elementary(path, *codec, limit) else {
971 table.push(format!("{:<52} SKIP (no elementary stream)", short(path)));
972 continue;
973 };
974 let mut decoder = Decoder::new(&display, *codec).expect("decoder opens");
975 let mut reference: Option<Reference> = None;
976 let mut worst = f64::INFINITY;
977 let mut compared = 0usize;
978 let mut failed: Option<String> = None;
979 let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| {
980 let (w, h) = frame.display_size;
981 let reference = reference
982 .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs"));
983 let Some(want) = reference.next(w, h) else {
984 return;
985 };
986 let got = if *ten_bit {
987 Planes::from_16bit(&frame.to_i420_16().expect("readback"))
988 } else {
989 Planes::from_8bit(&frame.to_i420().expect("readback"))
990 };
991 if got.y.len() != want.y.len() {
992 failed = Some("frame size disagrees with ffmpeg".to_string());
993 return;
994 }
995 let db = psnr(&got, &want);
996 if std::env::var_os("EC_HW_DEBUG").is_some() {
997 eprintln!(" {} frame {compared}: {db:.1} dB", short(path));
998 }
999 worst = worst.min(db);
1000 compared += 1;
1001 });
1002 match result {
1003 Ok(decoded) => table.push(format!(
1004 "{:<52} {decoded:>4} frames, {compared} compared, worst {}",
1005 short(path),
1006 if worst.is_infinite() {
1007 "exact".to_string()
1008 } else {
1009 format!("{worst:.1} dB")
1010 }
1011 )),
1012 Err(e) => failed = Some(e.to_string()),
1013 }
1014 if let Some(reason) = failed {
1015 table.push(format!("{:<52} FAIL {reason}", short(path)));
1016 }
1017 assert!(compared > 0, "{}: nothing decoded", short(path));
1018 assert!(
1019 worst >= 40.0,
1020 "{}: worst frame {worst:.1} dB against ffmpeg",
1021 short(path)
1022 );
1023 }
1024 for row in table {
1025 println!("{row}");
1026 }
1027}
1028
1029/// A library path without the directory tree, so a report can carry it.
1030fn short(path: &Path) -> String {
1031 path.file_name()
1032 .map(|n| n.to_string_lossy().to_string())
1033 .unwrap_or_default()
1034}
1035
1036/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in
1037/// decode order, even though they display before it (they predict from
1038/// pictures the CRA's own random-access point does not have). A decoder
1039/// started fresh at that CRA — what a seek does — must therefore drop those
1040/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by
1041/// however many RASL pictures the GOP has, handing back the wrong picture for
1042/// every display index at or after the seek target.
1043#[test]
1044fn hevc_seek_matches_linear_mkv() {
1045 let Some(display) = display() else { return };
1046 let path = bitstreams().join("test_hevc.mkv");
1047 let Some(data) = elementary(&path, Codec::H265, 45) else {
1048 eprintln!("skipped: no test_hevc.mkv fixture");
1049 return;
1050 };
1051 let units = split_access_units(&data, Codec::H265);
1052
1053 // Linear decode: every picture from the start, frame 30 kept for
1054 // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture
1055 // GOPs).
1056 const TARGET: usize = 30;
1057 let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1058 let mut linear_frame_30 = None;
1059 let mut index = 0usize;
1060 decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| {
1061 if index == TARGET {
1062 linear_frame_30 = Some(frame.to_i420().expect("readback"));
1063 }
1064 index += 1;
1065 })
1066 .expect("linear decode");
1067 let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
1068
1069 // Find the access unit whose first VCL NAL is the CRA at this GOP
1070 // boundary, and feed the decoder from there on, exactly as a seek would:
1071 // nothing from before it goes in.
1072 let cra_at = units
1073 .iter()
1074 .position(|au| starts_with_cra(au))
1075 .expect("a CRA access unit exists");
1076
1077 // A seek reuses the parameter sets a decoder already learned; a fresh one
1078 // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a
1079 // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown
1080 // away) and reset picture state before feeding the seek target.
1081 let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
1082 seek_decoder.decode(units[0], 0).expect("prime parameter sets");
1083 seek_decoder.reset();
1084 let mut seeked_frame = None;
1085 for (i, unit) in units[cra_at..].iter().enumerate() {
1086 seek_decoder.decode(unit, i as i64).expect("seek decode");
1087 if let Some(frame) = seek_decoder.next_frame() {
1088 seeked_frame = Some(frame.to_i420().expect("readback"));
1089 break;
1090 }
1091 }
1092 if seeked_frame.is_none() {
1093 seek_decoder.flush().expect("flush");
1094 seeked_frame = seek_decoder
1095 .next_frame()
1096 .map(|f| f.to_i420().expect("readback"));
1097 }
1098 let seeked_frame = seeked_frame.expect("a frame came out after the seek");
1099
1100 assert_eq!(
1101 seeked_frame, linear_frame_30,
1102 "seeking to the CRA before frame 30 handed back a different picture \
1103 than a linear decode of frame 30 — RASL pictures were not dropped"
1104 );
1105}
1106
1107/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice
1108/// (`nal_unit_type` 1) whose predecessors in decode order can still hold
1109/// references from before it, so leading pictures between it and the next
1110/// IDR may predict from a picture never decoded since a fresh start there —
1111/// exactly what a seek does. A decoder started at that I must drop those
1112/// leading pictures per D.2.8's recovery point default, or its output shifts
1113/// by however many leading pictures the GOP has.
1114#[test]
1115fn h264_seek_matches_linear_open_gop() {
1116 let Some(display) = display() else { return };
1117 let path = bitstreams().join("h264-open-gop.mp4");
1118 let Some(data) = elementary(&path, Codec::H264, 60) else {
1119 eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)");
1120 return;
1121 };
1122 let units = split_access_units(&data, Codec::H264);
1123
1124 // Linear decode: every picture from the start, frame 30 kept for
1125 // comparison (the fixture's second I picture, `keyint=30`).
1126 const TARGET: usize = 30;
1127 let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1128 let mut linear_frame_30 = None;
1129 let mut index = 0usize;
1130 decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| {
1131 if index == TARGET {
1132 linear_frame_30 = Some(frame.to_i420().expect("readback"));
1133 }
1134 index += 1;
1135 })
1136 .expect("linear decode");
1137 let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
1138
1139 // Find the access unit whose first VCL NAL is the open-GOP I picture at
1140 // this GOP boundary, and feed the decoder from there on, exactly as a
1141 // seek would: nothing from before it goes in.
1142 let open_gop_at = units
1143 .iter()
1144 .position(|au| is_open_gop_i(au))
1145 .expect("an open-GOP I access unit exists");
1146
1147 // A seek reuses the parameter sets a decoder already learned; a fresh one
1148 // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a
1149 // caller to: decode the leading IDR (its picture is thrown away) and
1150 // reset picture state before feeding the seek target.
1151 let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1152 seek_decoder.decode(units[0], 0).expect("prime parameter sets");
1153 seek_decoder.reset();
1154 let mut seeked_frame = None;
1155 for (i, unit) in units[open_gop_at..].iter().enumerate() {
1156 seek_decoder.decode(unit, i as i64).expect("seek decode");
1157 if let Some(frame) = seek_decoder.next_frame() {
1158 seeked_frame = Some(frame.to_i420().expect("readback"));
1159 break;
1160 }
1161 }
1162 if seeked_frame.is_none() {
1163 seek_decoder.flush().expect("flush");
1164 seeked_frame = seek_decoder
1165 .next_frame()
1166 .map(|f| f.to_i420().expect("readback"));
1167 }
1168 let seeked_frame = seeked_frame.expect("a frame came out after the seek");
1169
1170 assert_eq!(
1171 seeked_frame, linear_frame_30,
1172 "seeking to the open-GOP I before frame 30 handed back a different \
1173 picture than a linear decode of frame 30 — leading pictures with \
1174 missing references were not dropped"
1175 );
1176}
1177
1178/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice
1179/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the
1180/// access unit's first start code rather than assuming a fixed prefix length.
1181fn is_open_gop_i(au: &[u8]) -> bool {
1182 let mut i = 0usize;
1183 while i + 3 < au.len() {
1184 if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 {
1185 i += 1;
1186 continue;
1187 }
1188 let header = au[i + 3];
1189 if header & 0x1f != 1 {
1190 return false;
1191 }
1192 let mut r = ec_core::BitReader::new(&au[i + 4..]);
1193 if r.read_ue().is_err() {
1194 return false;
1195 }
1196 return matches!(r.read_ue(), Ok(code) if code % 5 == 2);
1197 }
1198 false
1199}
1200
1201/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21).
1202/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past
1203/// non-VCL NALs to the first one that carries a slice.
1204fn starts_with_cra(au: &[u8]) -> bool {
1205 let mut i = 0usize;
1206 while i + 3 < au.len() {
1207 if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 {
1208 let t = (au[i + 3] >> 1) & 0x3f;
1209 if t <= 31 {
1210 return t == 21;
1211 }
1212 i += 3;
1213 continue;
1214 }
1215 i += 1;
1216 }
1217 false
1218}