forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

gpu.rs547 lines, 20.6 KiBHistoryRawDownload
1//! Live GPU tests. Not `#[ignore]`d: this machine has the hardware, and a test
2//! that never runs is not a test. On a machine with no VA-API device every one
3//! of these fails at `Display::open`, which is the honest outcome — the crate
4//! has no meaning without a driver.
5//!
6//! Everything lives in one test binary on purpose (a file per feature is a
7//! serial link-and-run tax). Every test opens its own display and takes
8//! [`serial`], so the two process-wide measurements below stay meaningful.
9//!
10//! Reference: `vainfo` on this box (Mesa 26.1.6, radeonsi gfx1200, RX 9060 XT).
11
12use std::os::fd::AsRawFd;
13use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
14
15use ec_va::caps::{Entrypoint, Profile};
16use ec_va::{
17 CapReport, Config, Context, Display, Error, Image, Picture, Surface, SurfaceSpec, sys,
18};
19
20/// Runs the tests in this binary one at a time.
21///
22/// Two of them measure process-wide state — `VmRSS` for the surface-pool leak
23/// check and `/proc/self/fd` for the PRIME export ownership check — and a
24/// sibling test allocating a 1080p pool on another thread would make both
25/// meaningless. Serialising is cheaper and more honest than loosening the
26/// thresholds until concurrency stops mattering.
27fn serial() -> MutexGuard<'static, ()> {
28 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
29 LOCK.get_or_init(|| Mutex::new(()))
30 .lock()
31 // A panicking test poisons the mutex; the rest are still worth running.
32 .unwrap_or_else(|poisoned| poisoned.into_inner())
33}
34
35fn display() -> Arc<Display> {
36 Display::open().expect("no VA-API display; this test needs the GPU")
37}
38
39// --------------------------------------------------------------------------
40// Display
41// --------------------------------------------------------------------------
42
43#[test]
44fn display_opens_on_a_render_node() {
45 let _serial = serial();
46 let display = display();
47 assert!(display.is_valid());
48 let (major, minor) = display.version();
49 assert_eq!(major, ec_va::MIN_VA_MAJOR);
50 assert!(
51 minor >= ec_va::MIN_VA_MINOR,
52 "runtime libva {major}.{minor} is older than the transcribed ABI"
53 );
54 assert!(
55 display
56 .device_path()
57 .to_string_lossy()
58 .starts_with("/dev/dri/renderD"),
59 "expected a render node, got {:?}",
60 display.device_path()
61 );
62 let vendor = display.vendor().expect("vendor string");
63 assert!(!vendor.is_empty(), "driver reported an empty vendor string");
64}
65
66// --------------------------------------------------------------------------
67// Capabilities — the table must match `vainfo` on this GPU
68// --------------------------------------------------------------------------
69
70#[test]
71fn caps_match_vainfo_on_this_gpu() {
72 let _serial = serial();
73 let display = display();
74 let caps = CapReport::probe(&display).expect("probe");
75
76 // Decode: every codec the family hands to hardware.
77 for profile in [
78 Profile::H264ConstrainedBaseline,
79 Profile::H264Main,
80 Profile::H264High,
81 Profile::HEVCMain,
82 Profile::HEVCMain10,
83 Profile::VP9Profile0,
84 Profile::VP9Profile2,
85 Profile::AV1Profile0,
86 Profile::AV1Profile2,
87 ] {
88 assert!(
89 caps.supports(profile, Entrypoint::VLD),
90 "{} VLD missing from the probe but present in vainfo",
91 profile.name()
92 );
93 }
94
95 // Encode: H.264 and HEVC are the two the family ships (AV1 encode exists on
96 // this GPU too, but stays opt-in — see the family plan).
97 for profile in [
98 Profile::H264ConstrainedBaseline,
99 Profile::H264Main,
100 Profile::H264High,
101 Profile::HEVCMain,
102 Profile::HEVCMain10,
103 ] {
104 assert!(
105 caps.supports(profile, Entrypoint::EncSlice),
106 "{} EncSlice missing from the probe but present in vainfo",
107 profile.name()
108 );
109 }
110
111 // Post-processing, used later for colour conversion.
112 assert!(caps.supports(Profile::None, Entrypoint::VideoProc));
113
114 // A pair this GPU genuinely lacks must be absent, not silently invented:
115 // vainfo lists VP9 profiles 0 and 2 only.
116 assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD));
117 assert!(!caps.supports(Profile::VP9Profile3, Entrypoint::VLD));
118 assert!(!caps.supports(Profile::VP9Profile0, Entrypoint::EncSlice));
119
120 // 10-bit decode must advertise a 10-bit RT format, or `ec-hw` would derive
121 // an 8-bit context for Main10 — the incumbent's D2 defect.
122 let main10 = caps
123 .entry(Profile::HEVCMain10, Entrypoint::VLD)
124 .expect("HEVC Main10 VLD");
125 assert!(
126 main10.supports_rt_format(sys::VA_RT_FORMAT_YUV420_10),
127 "HEVC Main10 VLD advertised rt_formats 0x{:08x} without a 10-bit format",
128 main10.rt_formats
129 );
130 let p010_supported = main10
131 .surfaces
132 .as_ref()
133 .expect("surface caps")
134 .supports_fourcc(sys::VA_FOURCC_P010);
135 assert!(p010_supported, "Main10 cannot allocate P010 surfaces");
136
137 // 8-bit decode: NV12 everywhere.
138 let h264 = caps
139 .entry(Profile::H264Main, Entrypoint::VLD)
140 .expect("H264 Main VLD");
141 assert!(h264.supports_rt_format(sys::VA_RT_FORMAT_YUV420));
142 assert!(
143 h264.surfaces
144 .as_ref()
145 .expect("surface caps")
146 .supports_fourcc(sys::VA_FOURCC_NV12)
147 );
148
149 // Readback formats: `vaGetImage` must be able to produce NV12 and P010.
150 assert!(caps.image_formats.contains(&sys::VA_FOURCC_NV12));
151 assert!(caps.image_formats.contains(&sys::VA_FOURCC_P010));
152
153 assert!(
154 caps.profiles_for(Entrypoint::VLD).len() >= 9,
155 "expected at least 9 decode profiles, got {:?}",
156 caps.profiles_for(Entrypoint::VLD)
157 );
158}
159
160#[test]
161fn caps_report_driver_legal_surface_sizes() {
162 let _serial = serial();
163 let display = display();
164 let caps = CapReport::probe(&display).expect("probe");
165 let entry = caps
166 .entry(Profile::H264Main, Entrypoint::VLD)
167 .expect("H264 Main VLD");
168 let surfaces = entry.surfaces.as_ref().expect("surface caps");
169
170 // radeonsi rejects decode surfaces below 64x64. Probing with a hardcoded
171 // 16x16 config is what used to panic here, so the minimum is reported
172 // rather than assumed.
173 assert_eq!(surfaces.min_width, Some(64));
174 assert_eq!(surfaces.min_height, Some(64));
175 assert!(surfaces.max_width.unwrap() >= 4096);
176 assert!(
177 !surfaces.allows(16, 16),
178 "16x16 must be refused by the caps"
179 );
180 assert!(surfaces.allows(1920, 1088));
181
182 // DRM PRIME 2 export must be advertised: that is how frames leave the GPU.
183 assert!(
184 surfaces.memory_types & sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 != 0,
185 "memory types 0x{:08x} lack DRM_PRIME_2",
186 surfaces.memory_types
187 );
188}
189
190#[test]
191fn unsupported_pair_is_refused_by_the_driver() {
192 let _serial = serial();
193 // A refusal is a claim: prove the capability is genuinely absent rather
194 // than assumed absent.
195 let display = display();
196 let caps = CapReport::probe(&display).expect("probe");
197 assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD));
198
199 let err = Config::new(&display, Profile::VP9Profile1, Entrypoint::VLD, &[])
200 .expect_err("VP9 Profile1 decode does not exist on this GPU");
201 let status = err.status().expect("a VAStatus-carrying error");
202 assert!(
203 status == sys::VA_STATUS_ERROR_UNSUPPORTED_PROFILE
204 || status == sys::VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT,
205 "unexpected refusal: {err}"
206 );
207 assert!(err.to_string().contains("vaCreateConfig"), "{err}");
208}
209
210// --------------------------------------------------------------------------
211// Surfaces
212// --------------------------------------------------------------------------
213
214#[test]
215fn surface_pool_create_and_destroy_is_leak_free() {
216 let _serial = serial();
217 let display = display();
218 let spec = SurfaceSpec::nv12(64, 64);
219
220 // Warm up so first-touch allocations are not counted as a leak.
221 for _ in 0..4 {
222 let pool = Surface::create_pool(&display, &spec, 16).expect("pool");
223 assert_eq!(pool.len(), 16);
224 drop(pool);
225 }
226
227 let before = vm_rss_kb();
228 for _ in 0..100 {
229 let pool = Surface::create_pool(&display, &spec, 16).expect("pool");
230 // Every id must be distinct and valid, or the pool is aliasing memory.
231 let mut ids: Vec<_> = pool.iter().map(|s| s.id()).collect();
232 ids.sort_unstable();
233 ids.dedup();
234 assert_eq!(ids.len(), 16, "vaCreateSurfaces returned duplicate ids");
235 assert!(ids.iter().all(|&id| id != sys::VA_INVALID_SURFACE));
236 drop(pool);
237 }
238 let after = vm_rss_kb();
239
240 // 1600 surfaces created and destroyed. A per-surface leak would be obvious
241 // at this scale; the incumbent's unmatched map leaked ~3MB per frame.
242 let delta_kb = after.saturating_sub(before);
243 assert!(
244 delta_kb < 50 * 1024,
245 "VmRSS grew {delta_kb} kB over 100 create/destroy cycles"
246 );
247}
248
249#[test]
250fn derive_image_maps_and_reads_back() {
251 let _serial = serial();
252 let display = display();
253 let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface");
254 let mut image = surface.derive_image().expect("vaDeriveImage");
255
256 assert_eq!(image.fourcc(), sys::VA_FOURCC_NV12);
257 assert_eq!(image.size(), (64, 64));
258 assert_eq!(image.num_planes(), 2, "NV12 is luma + interleaved chroma");
259 let pitch = image.pitch(0).expect("luma pitch");
260 assert!(pitch >= 64, "luma pitch {pitch} is narrower than the image");
261
262 {
263 let mut mapped = image.map().expect("vaMapBuffer");
264 let luma = mapped.plane_mut(0).expect("luma plane");
265 assert_eq!(
266 luma.len(),
267 pitch as usize * 64,
268 "luma plane length must be pitch * height"
269 );
270 for (i, byte) in luma.iter_mut().enumerate() {
271 *byte = (i % 251) as u8;
272 }
273 let chroma = mapped.plane(1).expect("chroma plane");
274 assert!(!chroma.is_empty());
275 assert!(mapped.plane(2).is_none(), "NV12 has no third plane");
276
277 let luma = mapped.plane(0).expect("luma plane");
278 assert_eq!(luma[0], 0);
279 assert_eq!(luma[250], 250);
280 assert_eq!(luma[251], 0, "write did not survive within the mapping");
281 }
282
283 // Re-mapping after the guard dropped proves the unmap actually happened:
284 // libva returns the same buffer only once per map, and a never-unmapped
285 // mapping is the incumbent's per-frame leak.
286 //
287 // What is deliberately *not* asserted: that the bytes written above are
288 // readable through this second mapping. On radeonsi 26.1 a derived-image
289 // mapping is write-oriented staging — the write reaches the surface (see
290 // `created_image_reads_a_surface_back`), but a fresh map reads back zeros.
291 // Readback therefore goes through `vaGetImage`, never through a re-derive.
292 let mapped = image.map().expect("second vaMapBuffer after unmap");
293 assert_eq!(
294 mapped.plane(0).expect("luma").len(),
295 pitch as usize * 64,
296 "second mapping has a different geometry"
297 );
298}
299
300#[test]
301fn created_image_reads_a_surface_back() {
302 let _serial = serial();
303 let display = display();
304 let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface");
305 // Paint through the derived image so there is something known to read back.
306 {
307 let mut derived = surface.derive_image().expect("derive");
308 let mut mapped = derived.map().expect("map");
309 for byte in mapped.plane_mut(0).expect("luma") {
310 *byte = 0x5a;
311 }
312 }
313 surface.sync().expect("sync");
314
315 let mut image = Image::create(&display, sys::VA_FOURCC_NV12, 64, 64).expect("vaCreateImage");
316 surface
317 .read_into(&mut image, 0, 0, 64, 64)
318 .expect("vaGetImage");
319 let mapped = image.map().expect("map");
320 let luma = mapped.plane(0).expect("luma");
321 assert!(
322 luma.iter().take(64).all(|&b| b == 0x5a),
323 "vaGetImage did not return the painted luma"
324 );
325
326 // Out-of-range regions are refused before reaching the driver.
327 drop(mapped);
328 let err = surface
329 .read_into(&mut image, 0, 0, 128, 128)
330 .expect_err("region larger than the image must be refused");
331 assert!(matches!(err, Error::Protocol(_)), "{err}");
332}
333
334#[test]
335fn prime_export_owns_and_releases_its_descriptors() {
336 let _serial = serial();
337 let display = display();
338 let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface");
339 surface.sync().expect("sync before export");
340
341 let baseline = open_fd_count();
342 let exported = surface
343 .export_prime(sys::VA_EXPORT_SURFACE_READ_ONLY)
344 .expect("vaExportSurfaceHandle");
345
346 assert_eq!(exported.fourcc, sys::VA_FOURCC_NV12);
347 assert_eq!((exported.width, exported.height), (64, 64));
348 assert!(!exported.objects.is_empty(), "no DRM objects exported");
349 assert!(!exported.layers.is_empty(), "no layers exported");
350 for object in &exported.objects {
351 assert!(object.fd.as_raw_fd() >= 0);
352 assert!(object.size > 0);
353 }
354 for layer in &exported.layers {
355 assert!(!layer.planes.is_empty());
356 for &(object_index, _offset, pitch) in &layer.planes {
357 assert!((object_index as usize) < exported.objects.len());
358 assert!(pitch > 0);
359 }
360 }
361
362 let with_export = open_fd_count();
363 assert_eq!(
364 with_export - baseline,
365 exported.objects.len(),
366 "exported fd count does not match the descriptor"
367 );
368 drop(exported);
369 assert_eq!(
370 open_fd_count(),
371 baseline,
372 "dropping the export leaked file descriptors"
373 );
374}
375
376// --------------------------------------------------------------------------
377// Context / picture protocol
378// --------------------------------------------------------------------------
379
380#[test]
381fn picture_typestate_walks_the_va_protocol() {
382 let _serial = serial();
383 let display = display();
384 let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config");
385 let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 2).expect("pool");
386 let context =
387 Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context");
388
389 // New -> Rendering. Each transition consumes the picture, so nothing can
390 // call `begin` twice or reach `sync` without `end` (see the compile_fail
391 // examples in the `picture` module docs).
392 let picture = Picture::new(&context, Arc::clone(&targets[0]));
393 let picture = picture.begin().expect("vaBeginPicture");
394 assert_eq!(picture.target().id(), targets[0].id());
395
396 // Rendering -> Ended. Submitting a picture with no parameter buffers is a
397 // driver-level error here (mesa creates the decoder lazily from the picture
398 // parameters, so it has nothing to end); what matters is that it surfaces
399 // as a typed error instead of a panic, an abort or a GPU hang. Real
400 // submissions carry parameter/slice buffers and are `ec-hw`'s job.
401 let err = picture
402 .end()
403 .expect_err("empty submission is rejected by radeonsi");
404 assert_eq!(
405 err.status(),
406 Some(sys::VA_STATUS_ERROR_INVALID_CONTEXT),
407 "{err}"
408 );
409 assert!(err.to_string().contains("vaEndPicture"), "{err}");
410
411 // The display is still usable afterwards: an abandoned picture must not
412 // wedge the context.
413 let picture = Picture::new(&context, Arc::clone(&targets[1]))
414 .begin()
415 .expect("second vaBeginPicture after a failed end");
416 drop(picture);
417 assert!(display.is_valid());
418}
419
420#[test]
421fn buffers_map_unmap_and_destroy() {
422 let _serial = serial();
423 let display = display();
424 let config =
425 Config::new(&display, Profile::H264Main, Entrypoint::EncSlice, &[]).expect("config");
426 let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 1).expect("pool");
427 let context =
428 Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context");
429
430 // Coded-output buffer: allocated empty, mapped, written, unmapped, dropped.
431 const CODED_SIZE: u32 = 1 << 20;
432 let mut coded = ec_va::Buffer::allocate(&context, sys::VAEncCodedBufferType, CODED_SIZE)
433 .expect("vaCreateBuffer");
434 assert_eq!(coded.buffer_type(), sys::VAEncCodedBufferType);
435 assert_ne!(coded.id(), sys::VA_INVALID_ID);
436 {
437 let mut mapped = coded.map().expect("vaMapBuffer");
438 // SAFETY: 64 bytes of a 1 MiB allocation.
439 let slice = unsafe { mapped.as_mut_slice(64) };
440 slice[0] = 0x42;
441 // SAFETY: same 64-byte window, now read-only.
442 assert_eq!(unsafe { mapped.as_slice(64) }[0], 0x42);
443 }
444 // Mapping again proves the guard released the mapping.
445 drop(coded.map().expect("second vaMapBuffer after unmap"));
446
447 // Parameter buffer: data is copied into driver memory during the call.
448 let params = [0u8; 32];
449 let buffer = ec_va::Buffer::from_bytes(&context, sys::VAEncMiscParameterBufferType, &params)
450 .expect("vaCreateBuffer from bytes");
451 assert_ne!(buffer.id(), sys::VA_INVALID_ID);
452
453 // An empty buffer is refused before it reaches the driver.
454 let err = ec_va::Buffer::from_bytes(&context, sys::VAEncMiscParameterBufferType, &[])
455 .expect_err("empty buffer must be refused");
456 assert!(matches!(err, Error::Protocol(_)), "{err}");
457}
458
459#[test]
460fn context_keeps_its_dependencies_alive() {
461 let _serial = serial();
462 // Dropping the config and the surfaces while the context lives must be
463 // safe: the context holds `Arc`s, so libva's destruction order (buffers ->
464 // context -> surfaces -> config -> display) cannot be violated.
465 let display = display();
466 let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config");
467 let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 2).expect("pool");
468 let context =
469 Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context");
470 let target = Arc::clone(&targets[0]);
471 drop(config);
472 drop(targets);
473
474 let picture = Picture::new(&context, target).begin().expect("begin");
475 drop(picture);
476 drop(context);
477 assert!(display.is_valid());
478}
479
480// --------------------------------------------------------------------------
481// VPP
482// --------------------------------------------------------------------------
483
484/// `vaQueryVideoProcFilters` on the real display: whatever this driver
485/// advertises, the call must succeed and return values `Vpp` can act on. Not
486/// a claim about which filters exist — radeonsi's list is print-only here —
487/// just that the query path works end to end.
488#[test]
489fn vpp_filters_probe() {
490 let _serial = serial();
491 let display = display();
492 let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1080), 1).expect("pool");
493 let vpp = ec_va::Vpp::new(&display, sys::VA_RT_FORMAT_YUV420, &targets).expect("vpp opens");
494 let filters = vpp.filters().expect("vaQueryVideoProcFilters");
495 println!("radeonsi VAProcFilterType list: {filters:?}");
496 println!(
497 "HighDynamicRangeToneMapping (8) advertised: {}",
498 filters.contains(&sys::VAProcFilterHighDynamicRangeToneMapping)
499 );
500}
501
502/// `Vpp::convert` end to end: a P010 source surface into an NV12 destination,
503/// no readback — the conversion `ec-hw`'s `encode_frame` relies on for a
504/// 10-bit source.
505#[test]
506fn vpp_converts_p010_to_nv12() {
507 let _serial = serial();
508 let display = display();
509 let src_spec = SurfaceSpec::p010(64, 64);
510 let source = Surface::create(&display, &src_spec).expect("p010 source surface");
511 let dest_targets = Surface::create_pool(&display, &SurfaceSpec::nv12(64, 64), 1).expect("pool");
512 let vpp = ec_va::Vpp::new(
513 &display,
514 sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10,
515 &dest_targets,
516 )
517 .expect("vpp opens");
518 let dest = vpp
519 .convert(&source, Arc::clone(&dest_targets[0]))
520 .expect("convert");
521 assert_eq!(dest.id(), dest_targets[0].id());
522 assert!(display.is_valid());
523}
524
525// --------------------------------------------------------------------------
526// helpers
527// --------------------------------------------------------------------------
528
529fn vm_rss_kb() -> u64 {
530 let status = std::fs::read_to_string("/proc/self/status").expect("/proc/self/status");
531 for line in status.lines() {
532 if let Some(rest) = line.strip_prefix("VmRSS:") {
533 return rest
534 .split_whitespace()
535 .next()
536 .and_then(|v| v.parse().ok())
537 .expect("VmRSS value");
538 }
539 }
540 panic!("VmRSS not found in /proc/self/status");
541}
542
543fn open_fd_count() -> usize {
544 std::fs::read_dir("/proc/self/fd")
545 .expect("/proc/self/fd")
546 .count()
547}