forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdb36daaTahinli3 months ago92 commits

surface.rs567 lines, 20.4 KiBHistoryRawDownload
1//! [`Surface`] — GPU-side picture storage, plus the two ways of getting at its
2//! contents: DRM PRIME export (zero-copy handoff) and image mapping (readback).
3
4use std::os::fd::{FromRawFd, OwnedFd};
5use std::sync::Arc;
6
7use crate::display::Display;
8use crate::error::{Error, Result, check};
9use crate::sys;
10
11/// What kind of surface to allocate.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct SurfaceSpec {
14 /// `VA_RT_FORMAT_*` for the config this surface will be used with.
15 pub rt_format: u32,
16 /// Exact pixel layout (FourCC). `None` lets the driver choose.
17 pub fourcc: Option<u32>,
18 /// Width in pixels. Must satisfy [`crate::SurfaceCaps::allows`].
19 pub width: u32,
20 /// Height in pixels.
21 pub height: u32,
22 /// `VA_SURFACE_ATTRIB_USAGE_HINT_*` bitmask; drivers use it to pick tiling.
23 pub usage_hint: u32,
24}
25
26impl SurfaceSpec {
27 /// 8-bit 4:2:0 NV12, the decode output format of every codec in the family.
28 pub fn nv12(width: u32, height: u32) -> Self {
29 SurfaceSpec {
30 rt_format: sys::VA_RT_FORMAT_YUV420,
31 fourcc: Some(sys::VA_FOURCC_NV12),
32 width,
33 height,
34 usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC,
35 }
36 }
37
38 /// 10-bit 4:2:0 P010, for HEVC Main10 / VP9 Profile 2 / AV1 10-bit.
39 ///
40 /// The RT format is derived from the stream's bit depth, never hardcoded to
41 /// 8-bit: an 8-bit context on a 10-bit stream is the incumbent defect this
42 /// constructor exists to make impossible to write by accident.
43 pub fn p010(width: u32, height: u32) -> Self {
44 SurfaceSpec {
45 rt_format: sys::VA_RT_FORMAT_YUV420_10,
46 fourcc: Some(sys::VA_FOURCC_P010),
47 width,
48 height,
49 usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC,
50 }
51 }
52
53 /// Set the usage hint (`VA_SURFACE_ATTRIB_USAGE_HINT_*`).
54 pub fn with_usage_hint(mut self, hint: u32) -> Self {
55 self.usage_hint = hint;
56 self
57 }
58}
59
60/// A live `VASurfaceID`.
61///
62/// Surfaces may only be destroyed after every context using them is gone;
63/// [`crate::Context`] therefore holds `Arc<Surface>` for its render targets and
64/// this `Drop` cannot run too early.
65pub struct Surface {
66 display: Arc<Display>,
67 id: sys::VASurfaceID,
68 spec: SurfaceSpec,
69}
70
71impl Surface {
72 /// Allocate a single surface.
73 pub fn create(display: &Arc<Display>, spec: &SurfaceSpec) -> Result<Arc<Surface>> {
74 let mut pool = Surface::create_pool(display, spec, 1)?;
75 Ok(pool.pop().expect("create_pool(1) returns one surface"))
76 }
77
78 /// Allocate `count` surfaces in one driver call.
79 ///
80 /// Each returned surface owns its own id and destroys exactly that id, so a
81 /// pool can be torn down incrementally as frames are released.
82 pub fn create_pool(
83 display: &Arc<Display>,
84 spec: &SurfaceSpec,
85 count: usize,
86 ) -> Result<Vec<Arc<Surface>>> {
87 if count == 0 {
88 return Ok(Vec::new());
89 }
90 let mut attribs: Vec<sys::VASurfaceAttrib> = Vec::with_capacity(2);
91 if let Some(fourcc) = spec.fourcc {
92 attribs.push(int_attrib(sys::VASurfaceAttribPixelFormat, fourcc as i32));
93 }
94 if spec.usage_hint != sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC {
95 attribs.push(int_attrib(
96 sys::VASurfaceAttribUsageHint,
97 spec.usage_hint as i32,
98 ));
99 }
100
101 let mut ids = vec![sys::VA_INVALID_SURFACE; count];
102 // SAFETY: `ids` has room for exactly `count` surface ids and `attribs`
103 // for exactly `attribs.len()` attributes; both counts are passed
104 // alongside. libva writes only within those bounds and does not retain
105 // either pointer past the call.
106 let status = unsafe {
107 sys::vaCreateSurfaces(
108 display.handle(),
109 spec.rt_format,
110 spec.width,
111 spec.height,
112 ids.as_mut_ptr(),
113 count as u32,
114 attribs.as_mut_ptr(),
115 attribs.len() as u32,
116 )
117 };
118 check("vaCreateSurfaces", status)?;
119
120 if ids.contains(&sys::VA_INVALID_SURFACE) {
121 // Destroy whatever did get created rather than leaking it.
122 let mut good: Vec<sys::VASurfaceID> = ids
123 .iter()
124 .copied()
125 .filter(|&id| id != sys::VA_INVALID_SURFACE)
126 .collect();
127 if !good.is_empty() {
128 // SAFETY: every id in `good` was returned by the successful
129 // vaCreateSurfaces above and has not been destroyed yet.
130 unsafe {
131 sys::vaDestroySurfaces(display.handle(), good.as_mut_ptr(), good.len() as i32)
132 };
133 }
134 return Err(Error::Protocol(
135 "vaCreateSurfaces succeeded but left VA_INVALID_SURFACE in the array".to_string(),
136 ));
137 }
138
139 Ok(ids
140 .into_iter()
141 .map(|id| {
142 Arc::new(Surface {
143 display: Arc::clone(display),
144 id,
145 spec: *spec,
146 })
147 })
148 .collect())
149 }
150
151 /// Block until every operation targeting this surface has completed.
152 pub fn sync(&self) -> Result<()> {
153 // SAFETY: `self.id` is live for the lifetime of `self` on
154 // `self.display`. vaSyncSurface only blocks; it mutates no Rust state.
155 let status = unsafe { sys::vaSyncSurface(self.display.handle(), self.id) };
156 check("vaSyncSurface", status)
157 }
158
159 /// Export as DRM PRIME (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`).
160 ///
161 /// `flags` is a combination of `VA_EXPORT_SURFACE_*`. This performs no
162 /// synchronisation: call [`Surface::sync`] first if the contents will be
163 /// read.
164 pub fn export_prime(&self, flags: u32) -> Result<PrimeSurface> {
165 let mut desc = sys::VADRMPRIMESurfaceDescriptor::default();
166 // SAFETY: `desc` is a valid, fully initialized (zeroed) descriptor of
167 // exactly the type `VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2` selects
168 // (va_drmcommon.h:96-99); passing any other mem_type with this pointer
169 // would be the unsound case, which is why mem_type is not a parameter.
170 let status = unsafe {
171 sys::vaExportSurfaceHandle(
172 self.display.handle(),
173 self.id,
174 sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
175 flags,
176 (&raw mut desc).cast(),
177 )
178 };
179 check("vaExportSurfaceHandle", status)?;
180 PrimeSurface::from_raw(desc)
181 }
182
183 /// A directly mapped view of the surface's own memory (`vaDeriveImage`).
184 ///
185 /// Falls back is the caller's business: drivers may refuse to derive (tiled
186 /// or compressed layouts), reporting `VA_STATUS_ERROR_OPERATION_FAILED`.
187 pub fn derive_image(self: &Arc<Self>) -> Result<Image> {
188 let mut image = sys::VAImage::default();
189 // SAFETY: valid display and surface id; `image` is a valid
190 // out-parameter that libva fully overwrites on success.
191 let status = unsafe { sys::vaDeriveImage(self.display.handle(), self.id, &raw mut image) };
192 check("vaDeriveImage", status)?;
193 Ok(Image {
194 display: Arc::clone(&self.display),
195 _surface: Some(Arc::clone(self)),
196 raw: image,
197 })
198 }
199
200 /// Copy the surface into an [`Image`] created with [`Image::create`].
201 ///
202 /// The readback path for drivers that refuse [`Surface::derive_image`].
203 /// The image must be at least as large as the requested region.
204 pub fn read_into(
205 &self,
206 image: &mut Image,
207 x: i32,
208 y: i32,
209 width: u32,
210 height: u32,
211 ) -> Result<()> {
212 let (img_w, img_h) = image.size();
213 if width > img_w || height > img_h {
214 return Err(Error::Protocol(format!(
215 "vaGetImage region {width}x{height} exceeds image {img_w}x{img_h}"
216 )));
217 }
218 // SAFETY: valid display and surface id; `image.raw.image_id` is a live
219 // image on the same display. The region is bounded above by the image
220 // size, which is what vaGetImage requires (va.h:4827).
221 let status = unsafe {
222 sys::vaGetImage(
223 self.display.handle(),
224 self.id,
225 x,
226 y,
227 width,
228 height,
229 image.raw.image_id,
230 )
231 };
232 check("vaGetImage", status)
233 }
234
235 /// The surface id, for FFI-level callers (`ec-hw` picture parameters).
236 pub fn id(&self) -> sys::VASurfaceID {
237 self.id
238 }
239
240 /// The spec this surface was allocated with.
241 pub fn spec(&self) -> &SurfaceSpec {
242 &self.spec
243 }
244
245 /// Allocated size in pixels.
246 pub fn size(&self) -> (u32, u32) {
247 (self.spec.width, self.spec.height)
248 }
249
250 /// The display this surface belongs to.
251 pub fn display(&self) -> &Arc<Display> {
252 &self.display
253 }
254}
255
256fn int_attrib(type_: sys::VASurfaceAttribType, value: i32) -> sys::VASurfaceAttrib {
257 sys::VASurfaceAttrib {
258 type_,
259 flags: sys::VA_SURFACE_ATTRIB_SETTABLE,
260 value: sys::VAGenericValue {
261 type_: sys::VAGenericValueTypeInteger,
262 value: sys::VAGenericValueUnion { i: value },
263 },
264 }
265}
266
267impl std::fmt::Debug for Surface {
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 f.debug_struct("Surface")
270 .field("id", &self.id)
271 .field("size", &(self.spec.width, self.spec.height))
272 .finish()
273 }
274}
275
276impl Drop for Surface {
277 fn drop(&mut self) {
278 let mut id = self.id;
279 // SAFETY: `id` is live and belongs to `self.display`. Any context that
280 // used it held an `Arc<Surface>`, so it was destroyed first; any
281 // derived Image also held one.
282 unsafe { sys::vaDestroySurfaces(self.display.handle(), &raw mut id, 1) };
283 }
284}
285
286/// One DRM object (buffer object) of an exported surface.
287#[derive(Debug)]
288pub struct PrimeObject {
289 /// The PRIME file descriptor, owned and closed on drop.
290 pub fd: OwnedFd,
291 /// Total size of the object in bytes.
292 pub size: u32,
293 /// DRM format modifier (tiling/compression layout).
294 pub modifier: u64,
295}
296
297/// One layer (plane group) of an exported surface.
298#[derive(Debug, Clone)]
299pub struct PrimeLayer {
300 /// `DRM_FORMAT_*` FourCC of this layer.
301 pub drm_format: u32,
302 /// Per-plane `(object_index, offset, pitch)`.
303 pub planes: Vec<(u32, u32, u32)>,
304}
305
306/// A surface exported as DRM PRIME file descriptors.
307///
308/// Owns the descriptors: dropping this closes them. libva hands over ownership
309/// on export (`va.h:4155`), so anything less would leak one fd per frame.
310#[derive(Debug)]
311pub struct PrimeSurface {
312 /// Surface FourCC (`VA_FOURCC_*`).
313 pub fourcc: u32,
314 /// Width in pixels.
315 pub width: u32,
316 /// Height in pixels.
317 pub height: u32,
318 /// Backing DRM objects.
319 pub objects: Vec<PrimeObject>,
320 /// Layers referencing those objects.
321 pub layers: Vec<PrimeLayer>,
322}
323
324impl PrimeSurface {
325 /// Take ownership of the fds in a filled descriptor.
326 fn from_raw(desc: sys::VADRMPRIMESurfaceDescriptor) -> Result<PrimeSurface> {
327 // The array is 4 elements wide; a driver reporting more would mean our
328 // transcription and the runtime disagree about the struct, so refuse
329 // rather than read past the end.
330 if desc.num_objects as usize > desc.objects.len()
331 || desc.num_layers as usize > desc.layers.len()
332 {
333 return Err(Error::Protocol(format!(
334 "vaExportSurfaceHandle reported {} objects / {} layers, max 4 each",
335 desc.num_objects, desc.num_layers
336 )));
337 }
338
339 let mut objects = Vec::with_capacity(desc.num_objects as usize);
340 for obj in &desc.objects[..desc.num_objects as usize] {
341 if obj.fd < 0 {
342 return Err(Error::Protocol(format!(
343 "vaExportSurfaceHandle returned fd {} for an exported object",
344 obj.fd
345 )));
346 }
347 objects.push(PrimeObject {
348 // SAFETY: libva transfers ownership of every exported fd to the
349 // caller (va.h:4155). Each fd appears exactly once in the
350 // descriptor, so it is wrapped exactly once here and closed
351 // exactly once when this `PrimeSurface` drops.
352 fd: unsafe { OwnedFd::from_raw_fd(obj.fd) },
353 size: obj.size,
354 modifier: obj.drm_format_modifier,
355 });
356 }
357
358 let mut layers = Vec::with_capacity(desc.num_layers as usize);
359 for layer in &desc.layers[..desc.num_layers as usize] {
360 if layer.num_planes as usize > layer.object_index.len() {
361 return Err(Error::Protocol(format!(
362 "vaExportSurfaceHandle reported {} planes in a layer, max 4",
363 layer.num_planes
364 )));
365 }
366 layers.push(PrimeLayer {
367 drm_format: layer.drm_format,
368 planes: (0..layer.num_planes as usize)
369 .map(|i| (layer.object_index[i], layer.offset[i], layer.pitch[i]))
370 .collect(),
371 });
372 }
373
374 Ok(PrimeSurface {
375 fourcc: desc.fourcc,
376 width: desc.width,
377 height: desc.height,
378 objects,
379 layers,
380 })
381 }
382}
383
384/// A `VAImage` bound to a surface (derived) or standalone (created).
385pub struct Image {
386 display: Arc<Display>,
387 /// Kept alive because a derived image aliases the surface's memory.
388 _surface: Option<Arc<Surface>>,
389 raw: sys::VAImage,
390}
391
392impl Image {
393 /// Allocate a standalone image to read a surface back into
394 /// ([`Surface::read_into`]).
395 ///
396 /// `fourcc` must be one of [`crate::CapReport::image_formats`]; the other
397 /// [`sys::VAImageFormat`] fields are only meaningful for RGB layouts and
398 /// are left zero, as libva's own examples do for planar YUV.
399 pub fn create(display: &Arc<Display>, fourcc: u32, width: u32, height: u32) -> Result<Image> {
400 let mut format = sys::VAImageFormat {
401 fourcc,
402 byte_order: 1, // VA_LSB_FIRST
403 bits_per_pixel: match fourcc {
404 sys::VA_FOURCC_NV12 | sys::VA_FOURCC_I420 | sys::VA_FOURCC_YV12 => 12,
405 sys::VA_FOURCC_P010 => 24,
406 _ => 0,
407 },
408 ..sys::VAImageFormat::default()
409 };
410 let mut image = sys::VAImage::default();
411 // SAFETY: `format` and `image` are valid, initialized in/out parameters
412 // that outlive the call; libva copies the format and fully overwrites
413 // `image` on success.
414 let status = unsafe {
415 sys::vaCreateImage(
416 display.handle(),
417 &raw mut format,
418 width as i32,
419 height as i32,
420 &raw mut image,
421 )
422 };
423 check("vaCreateImage", status)?;
424 Ok(Image {
425 display: Arc::clone(display),
426 _surface: None,
427 raw: image,
428 })
429 }
430
431 /// Pixel format FourCC.
432 pub fn fourcc(&self) -> u32 {
433 self.raw.format.fourcc
434 }
435
436 /// `(width, height)` of the image, which may exceed the requested size.
437 pub fn size(&self) -> (u32, u32) {
438 (self.raw.width as u32, self.raw.height as u32)
439 }
440
441 /// Number of planes (at most 3).
442 pub fn num_planes(&self) -> u32 {
443 self.raw.num_planes.min(3)
444 }
445
446 /// Row pitch of plane `i` in bytes.
447 pub fn pitch(&self, plane: usize) -> Option<u32> {
448 self.raw.pitches.get(plane).copied()
449 }
450
451 /// Map the image's buffer into this process.
452 ///
453 /// The returned guard unmaps on drop. That is not politeness: an unmatched
454 /// `vaMapBuffer` leaks the mapping for the lifetime of the display, which
455 /// is how the incumbent stack lost ~3MB per frame.
456 pub fn map(&mut self) -> Result<MappedImage<'_>> {
457 let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut();
458 // SAFETY: `self.raw.buf` is the image buffer libva created and still
459 // owns; `ptr` is a valid out-parameter. On success libva guarantees the
460 // mapping stays valid until vaUnmapBuffer, which `MappedImage::drop`
461 // calls exactly once.
462 let status = unsafe { sys::vaMapBuffer(self.display.handle(), self.raw.buf, &raw mut ptr) };
463 check("vaMapBuffer", status)?;
464 if ptr.is_null() {
465 // SAFETY: the map call reported success, so the buffer is mapped
466 // and must be unmapped even though the pointer is unusable.
467 unsafe { sys::vaUnmapBuffer(self.display.handle(), self.raw.buf) };
468 return Err(Error::Protocol(
469 "vaMapBuffer succeeded but returned NULL".to_string(),
470 ));
471 }
472 Ok(MappedImage {
473 image: self,
474 base: ptr.cast::<u8>(),
475 })
476 }
477}
478
479impl std::fmt::Debug for Image {
480 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
481 f.debug_struct("Image")
482 .field("fourcc", &crate::caps::fourcc_str(self.raw.format.fourcc))
483 .field("size", &(self.raw.width, self.raw.height))
484 .field("num_planes", &self.raw.num_planes)
485 .field("data_size", &self.raw.data_size)
486 .finish()
487 }
488}
489
490impl Drop for Image {
491 fn drop(&mut self) {
492 // SAFETY: `image_id` came from vaDeriveImage/vaCreateImage on
493 // `self.display` and is destroyed once. Any mapping was released
494 // first: `map` borrows `self` mutably, so no `MappedImage` can outlive
495 // this. The surface (if any) is released after, as libva requires.
496 unsafe { sys::vaDestroyImage(self.display.handle(), self.raw.image_id) };
497 }
498}
499
500/// A mapped [`Image`]. Unmaps on drop.
501pub struct MappedImage<'a> {
502 image: &'a mut Image,
503 base: *mut u8,
504}
505
506impl MappedImage<'_> {
507 /// Byte range of plane `i` within the mapped buffer, as `(offset, len)`.
508 ///
509 /// The length runs to the next plane's offset, or to `data_size` for the
510 /// last plane — libva does not report per-plane sizes.
511 fn plane_range(&self, plane: usize) -> Option<(usize, usize)> {
512 let n = self.image.num_planes() as usize;
513 if plane >= n {
514 return None;
515 }
516 let raw = &self.image.raw;
517 let offset = raw.offsets[plane] as usize;
518 let end = raw
519 .offsets
520 .get(plane + 1)
521 .copied()
522 .filter(|_| plane + 1 < n)
523 .unwrap_or(raw.data_size) as usize;
524 // A driver reporting decreasing or out-of-range offsets would otherwise
525 // produce a slice past the mapping.
526 if end < offset || end > raw.data_size as usize {
527 return None;
528 }
529 Some((offset, end - offset))
530 }
531
532 /// Read-only view of plane `plane`.
533 pub fn plane(&self, plane: usize) -> Option<&[u8]> {
534 let (offset, len) = self.plane_range(plane)?;
535 // SAFETY: `base` points at a mapping of `data_size` bytes that libva
536 // keeps valid until vaUnmapBuffer (called only in `drop`). `plane_range`
537 // guarantees `offset + len <= data_size`, so the slice stays inside the
538 // mapping. The borrow is tied to `&self`, so it cannot outlive it.
539 Some(unsafe { std::slice::from_raw_parts(self.base.add(offset), len) })
540 }
541
542 /// Mutable view of plane `plane`, for upload paths.
543 pub fn plane_mut(&mut self, plane: usize) -> Option<&mut [u8]> {
544 let (offset, len) = self.plane_range(plane)?;
545 // SAFETY: as `plane`, plus: `&mut self` guarantees no other slice into
546 // the mapping is alive, so this is the only reference to those bytes.
547 Some(unsafe { std::slice::from_raw_parts_mut(self.base.add(offset), len) })
548 }
549
550 /// Row pitch of plane `plane` in bytes.
551 pub fn pitch(&self, plane: usize) -> Option<u32> {
552 self.image.pitch(plane)
553 }
554
555 /// The image being mapped.
556 pub fn image(&self) -> &Image {
557 self.image
558 }
559}
560
561impl Drop for MappedImage<'_> {
562 fn drop(&mut self) {
563 // SAFETY: the buffer was mapped in `Image::map` and is unmapped exactly
564 // once, here; `self.image` is still alive because this guard borrows it.
565 unsafe { sys::vaUnmapBuffer(self.image.display.handle(), self.image.raw.buf) };
566 }
567}