Skip to main content

kodecs_vaapi/
surface.rs

1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::any::Any;
6use std::os::fd::FromRawFd;
7use std::os::fd::OwnedFd;
8use std::os::raw::c_void;
9use std::sync::Arc;
10
11use crate::bindings;
12use crate::display::Display;
13use crate::va_check;
14use crate::UsageHint;
15use crate::VASurfaceID;
16use crate::VaError;
17
18/// Trait describing a memory backing for surfaces.
19///
20/// Using external memory for backing a VA surface is done in two steps:
21///
22/// 1. Build the descriptor specific to the memory type we want to use,
23/// 2. Mention this descriptor as an attribute to be passed to `vaDeriveImage`.
24///
25/// This trait allows to do that in a as-safe-as-possible way, by adding the required attributes
26/// and returning a heap-allocated object containing the data pointed to by the attributes. That
27/// way, the caller can keep that object alive until `vaCreateSurfaces` has returned.
28pub trait SurfaceMemoryDescriptor {
29	/// Add the required attributes to `attr` in order to attach the memory of this descriptor to
30	/// the surface when it is created.
31	///
32	/// The returned object, if any, is the descriptor pointed to by the attributes. The caller
33	/// must keep it around and unmoved until `vaCreateSurfaces` has returned.
34	fn add_attrs(&mut self, attrs: &mut Vec<bindings::VASurfaceAttrib>) -> Option<Box<dyn Any>>;
35}
36
37/// VA memory types, aka `VA_SURFACE_ATTRIB_MEM_TYPE_*`.
38#[repr(u32)]
39pub enum MemoryType {
40	Va = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_VA,
41	V4L2 = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_V4L2,
42	UserPtr = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_USER_PTR,
43	DrmPrime2 = bindings::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
44}
45
46/// Used when we want the VA driver to allocate surface memory for us. In this case we don't need
47/// to add any specific attribute for surface creation.
48impl SurfaceMemoryDescriptor for () {
49	fn add_attrs(&mut self, _: &mut Vec<bindings::VASurfaceAttrib>) -> Option<Box<dyn Any>> {
50		None
51	}
52}
53
54/// Sealed trait pattern to avoid reimplementation of our local traits.
55mod private {
56	pub trait Sealed {}
57}
58
59/// Trait for types that can be used as a `VASurfaceAttribExternalBufferDescriptor`.
60pub trait SurfaceExternalDescriptor: private::Sealed {}
61impl private::Sealed for bindings::VASurfaceAttribExternalBuffers {}
62impl SurfaceExternalDescriptor for bindings::VASurfaceAttribExternalBuffers {}
63impl private::Sealed for bindings::VADRMPRIMESurfaceDescriptor {}
64impl SurfaceExternalDescriptor for bindings::VADRMPRIMESurfaceDescriptor {}
65
66/// Trait allowing to import an external memory source to use with a surface by setting the
67/// `VASurfaceAttribMemoryType` and `VASurfaceAttribExternalBuffers` attributes.
68pub trait ExternalBufferDescriptor {
69	/// Memory type to set for `VASurfaceAttribMemoryType`.
70	const MEMORY_TYPE: MemoryType;
71	/// Type of the descriptor to be set with `VASurfaceAttribExternalBuffers`.
72	type DescriptorAttribute: SurfaceExternalDescriptor;
73
74	/// Returns the `Self::DescriptorAttribute` instance allowing this memory to be imported
75	/// into VAAPI.
76	fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute;
77}
78
79impl<T> SurfaceMemoryDescriptor for T
80where
81	T: ExternalBufferDescriptor,
82	<T as ExternalBufferDescriptor>::DescriptorAttribute: 'static,
83{
84	fn add_attrs(&mut self, attrs: &mut Vec<bindings::VASurfaceAttrib>) -> Option<Box<dyn Any>> {
85		let mut desc = Box::new(self.va_surface_attribute());
86
87		attrs.push(bindings::VASurfaceAttrib::new_memory_type(Self::MEMORY_TYPE));
88		attrs.push(bindings::VASurfaceAttrib::new_buffer_descriptor(desc.as_mut()));
89
90		Some(desc)
91	}
92}
93
94/// Decode error type aka `VADecodeErrorType`
95#[repr(u32)]
96#[derive(Debug)]
97pub enum DecodeErrorType {
98	SliceMissing = bindings::VADecodeErrorType::VADecodeSliceMissing,
99	MBError = bindings::VADecodeErrorType::VADecodeMBError,
100	Reset = bindings::VADecodeErrorType::VADecodeReset,
101}
102
103/// Decode error details extracted from `VASurfaceDecodeMBErrors`, result of vaQuerySurfaceError.
104#[derive(Debug)]
105pub struct SurfaceDecodeMBError {
106	/// Start mb address with errors
107	pub start_mb: u32,
108
109	/// End mb address with errors
110	pub end_mb: u32,
111
112	pub decode_error_type: DecodeErrorType,
113
114	/// Number of mbs with errors
115	pub num_mb: u32,
116}
117
118/// An owned VA surface that is tied to a particular `Display`.
119pub struct Surface<D: SurfaceMemoryDescriptor> {
120	display: Arc<Display>,
121	id: bindings::VASurfaceID,
122	descriptor: D,
123	width: u32,
124	height: u32,
125}
126
127impl From<i32> for bindings::VAGenericValue {
128	fn from(i: i32) -> Self {
129		Self {
130			type_: bindings::VAGenericValueType::VAGenericValueTypeInteger,
131			value: bindings::_VAGenericValue__bindgen_ty_1 { i },
132		}
133	}
134}
135
136impl From<f32> for bindings::VAGenericValue {
137	fn from(f: f32) -> Self {
138		Self {
139			type_: bindings::VAGenericValueType::VAGenericValueTypeFloat,
140			value: bindings::_VAGenericValue__bindgen_ty_1 { f },
141		}
142	}
143}
144
145impl From<*mut c_void> for bindings::VAGenericValue {
146	fn from(p: *mut c_void) -> Self {
147		Self {
148			type_: bindings::VAGenericValueType::VAGenericValueTypePointer,
149			value: bindings::_VAGenericValue__bindgen_ty_1 { p },
150		}
151	}
152}
153
154/// Helpers to build valid `VASurfaceAttrib`s.
155impl bindings::VASurfaceAttrib {
156	pub fn new_pixel_format(fourcc: u32) -> Self {
157		Self {
158			type_: bindings::VASurfaceAttribType::VASurfaceAttribPixelFormat,
159			flags: bindings::VA_SURFACE_ATTRIB_SETTABLE,
160			value: bindings::VAGenericValue::from(fourcc as i32),
161		}
162	}
163
164	pub fn new_usage_hint(usage_hint: UsageHint) -> Self {
165		Self {
166			type_: bindings::VASurfaceAttribType::VASurfaceAttribUsageHint,
167			flags: bindings::VA_SURFACE_ATTRIB_SETTABLE,
168			value: bindings::VAGenericValue::from(usage_hint.bits() as i32),
169		}
170	}
171
172	pub fn new_memory_type(mem_type: MemoryType) -> Self {
173		Self {
174			type_: bindings::VASurfaceAttribType::VASurfaceAttribMemoryType,
175			flags: bindings::VA_SURFACE_ATTRIB_SETTABLE,
176			value: bindings::VAGenericValue::from(mem_type as i32),
177		}
178	}
179
180	pub fn new_buffer_descriptor<T: SurfaceExternalDescriptor>(desc: &mut T) -> Self {
181		Self {
182			type_: bindings::VASurfaceAttribType::VASurfaceAttribExternalBufferDescriptor,
183			flags: bindings::VA_SURFACE_ATTRIB_SETTABLE,
184			value: bindings::VAGenericValue::from(desc as *mut _ as *mut c_void),
185		}
186	}
187}
188
189impl<D: SurfaceMemoryDescriptor> Surface<D> {
190	/// Create `Surfaces` by wrapping around a `vaCreateSurfaces` call. This is just a helper for
191	/// [`Display::create_surfaces`].
192	pub(crate) fn new(
193		display: Arc<Display>,
194		rt_format: u32,
195		va_fourcc: Option<u32>,
196		width: u32,
197		height: u32,
198		usage_hint: Option<UsageHint>,
199		descriptors: Vec<D>,
200	) -> Result<Vec<Self>, VaError> {
201		let mut surfaces = vec![];
202
203		for mut descriptor in descriptors {
204			let mut attrs = vec![];
205
206			if let Some(usage_hint) = usage_hint {
207				attrs.push(bindings::VASurfaceAttrib::new_usage_hint(usage_hint));
208			}
209
210			if let Some(fourcc) = va_fourcc {
211				attrs.push(bindings::VASurfaceAttrib::new_pixel_format(fourcc));
212			}
213
214			// Just to be kept alive until we call `vaCreateSurfaces`...
215			let mut _va_desc = descriptor.add_attrs(&mut attrs);
216			let mut surface_id: VASurfaceID = 0;
217
218			// Safe because `self` represents a valid VADisplay. The `surface` and `attrs` vectors are
219			// properly initialized and valid sizes are passed to the C function, so it is impossible to
220			// write past the end of their storage by mistake.
221			//
222			// Also all the pointers in `attrs` are pointing to valid objects that haven't been
223			// moved or destroyed.
224			match va_check(unsafe {
225				bindings::va().vaCreateSurfaces(
226					display.handle(),
227					rt_format,
228					width,
229					height,
230					&mut surface_id,
231					1,
232					attrs.as_mut_ptr(),
233					attrs.len() as u32,
234				)
235			}) {
236				Ok(()) => surfaces.push(Self {
237					display: Arc::clone(&display),
238					id: surface_id,
239					descriptor,
240					width,
241					height,
242				}),
243				Err(e) => return Err(e),
244			}
245		}
246
247		Ok(surfaces)
248	}
249
250	pub fn display(&self) -> &Arc<Display> {
251		&self.display
252	}
253
254	/// Wrapper around `vaSyncSurface` that blocks until all pending operations on the render
255	/// target have been completed.
256	///
257	/// Upon return it
258	/// is safe to use the render target for a different picture.
259	pub fn sync(&self) -> Result<(), VaError> {
260		// Safe because `self` represents a valid VASurface.
261		va_check(unsafe { bindings::va().vaSyncSurface(self.display.handle(), self.id) })
262	}
263
264	/// Convenience function to return a VASurfaceID vector. Useful to interface with the C API
265	/// where a surface array might be needed.
266	pub(crate) fn as_id_vec(surfaces: &[Self]) -> Vec<bindings::VASurfaceID> {
267		surfaces.iter().map(|surface| surface.id).collect()
268	}
269
270	/// Wrapper over `vaQuerySurfaceStatus` to find out any pending ops on the render target.
271	pub(crate) fn query_status(&self) -> Result<bindings::VASurfaceStatus::Type, VaError> {
272		let mut status: bindings::VASurfaceStatus::Type = 0;
273		// Safe because `self` represents a valid VASurface.
274		va_check(unsafe { bindings::va().vaQuerySurfaceStatus(self.display.handle(), self.id, &mut status) })?;
275
276		Ok(status)
277	}
278
279	pub(crate) fn query_error(&self) -> Result<Vec<SurfaceDecodeMBError>, VaError> {
280		let mut raw: *const bindings::VASurfaceDecodeMBErrors = std::ptr::null();
281
282		// Safe because `self` represents a valid VASurface.
283		va_check(unsafe {
284			bindings::va().vaQuerySurfaceError(
285				self.display.handle(),
286				self.id,
287				bindings::VA_STATUS_ERROR_DECODING_ERROR as i32,
288				(&mut raw) as *mut _ as *mut _,
289			)
290		})?;
291
292		let mut errors = vec![];
293
294		while !raw.is_null() {
295			// Safe because raw is a valid pointer
296			let error = unsafe { *raw };
297			if error.status == -1 {
298				break;
299			}
300
301			let type_ = match error.decode_error_type {
302				bindings::VADecodeErrorType::VADecodeSliceMissing => DecodeErrorType::SliceMissing,
303				bindings::VADecodeErrorType::VADecodeMBError => DecodeErrorType::MBError,
304				bindings::VADecodeErrorType::VADecodeReset => DecodeErrorType::Reset,
305				_ => {
306					tracing::warn!("Unrecognized `decode_error_type` value ({})", error.decode_error_type);
307
308					// Safe because status != -1
309					raw = unsafe { raw.offset(1) };
310					continue;
311				}
312			};
313
314			errors.push(SurfaceDecodeMBError {
315				start_mb: error.start_mb,
316				end_mb: error.end_mb,
317				decode_error_type: type_,
318				num_mb: error.num_mb,
319			});
320
321			// Safe because status != -1
322			raw = unsafe { raw.offset(1) };
323		}
324
325		Ok(errors)
326	}
327
328	/// Returns the ID of this surface.
329	pub(crate) fn id(&self) -> bindings::VASurfaceID {
330		self.id
331	}
332
333	/// Returns the dimensions of this surface.
334	pub fn size(&self) -> (u32, u32) {
335		(self.width, self.height)
336	}
337
338	/// Returns a PRIME descriptor for this surface.
339	pub fn export_prime(&self) -> Result<DrmPrimeSurfaceDescriptor, VaError> {
340		let mut desc: bindings::VADRMPRIMESurfaceDescriptor = Default::default();
341
342		va_check(unsafe {
343			bindings::va().vaExportSurfaceHandle(
344				self.display.handle(),
345				self.id(),
346				bindings::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
347				bindings::VA_EXPORT_SURFACE_READ_ONLY | bindings::VA_EXPORT_SURFACE_COMPOSED_LAYERS,
348				&mut desc as *mut _ as *mut c_void,
349			)
350		})?;
351
352		// We do not use a `From<VADRMPRIMESurfaceDescriptor>` implementation as this would allow
353		// to create "safe" descriptors outside of this method and thus from made up values,
354		// violating the safety guarantee that our FDs are legit.
355
356		// Take ownership of every fd the driver exported before validating anything, so
357		// a descriptor we refuse still closes them.
358		let num_objects = desc.num_objects as usize;
359		let objects: Vec<_> = desc
360			.objects
361			.iter()
362			.take(num_objects)
363			.filter(|o| o.fd >= 0)
364			.map(|o| {
365				DrmPrimeSurfaceDescriptorObject {
366					// Safe because `o.fd` is a non-negative file descriptor `vaExportSurfaceHandle`
367					// handed to us, and nothing else owns it.
368					fd: unsafe { OwnedFd::from_raw_fd(o.fd) },
369					size: o.size,
370					drm_format_modifier: o.drm_format_modifier,
371				}
372			})
373			.collect();
374
375		let num_layers = desc.num_layers as usize;
376		let layers_valid = desc.layers.iter().take(num_layers).all(|l| {
377			let planes = l.num_planes as usize;
378			planes <= l.object_index.len() && l.object_index[..planes].iter().all(|&i| (i as usize) < num_objects)
379		});
380		if num_objects > desc.objects.len()
381			|| objects.len() != num_objects
382			|| num_layers > desc.layers.len()
383			|| !layers_valid
384		{
385			return Err(VaError::status(bindings::VA_STATUS_ERROR_OPERATION_FAILED));
386		}
387
388		let layers = (0..num_layers)
389			.map(|i| desc.layers[i])
390			.map(|l| DrmPrimeSurfaceDescriptorLayer {
391				drm_format: l.drm_format,
392				num_planes: l.num_planes,
393				object_index: [
394					l.object_index[0] as u8,
395					l.object_index[1] as u8,
396					l.object_index[2] as u8,
397					l.object_index[3] as u8,
398				],
399				offset: l.offset,
400				pitch: l.pitch,
401			})
402			.collect();
403
404		Ok(DrmPrimeSurfaceDescriptor {
405			fourcc: desc.fourcc,
406			width: desc.width,
407			height: desc.height,
408			objects,
409			layers,
410		})
411	}
412}
413
414impl<D: SurfaceMemoryDescriptor> AsRef<D> for Surface<D> {
415	fn as_ref(&self) -> &D {
416		&self.descriptor
417	}
418}
419
420impl<D: SurfaceMemoryDescriptor> AsMut<D> for Surface<D> {
421	fn as_mut(&mut self) -> &mut D {
422		&mut self.descriptor
423	}
424}
425
426impl<D: SurfaceMemoryDescriptor> Drop for Surface<D> {
427	fn drop(&mut self) {
428		// Safe because `self` represents a valid VASurface.
429		unsafe { bindings::va().vaDestroySurfaces(self.display.handle(), &mut self.id, 1) };
430	}
431}
432
433/// Safe wrapper for the `object` member of `VADRMPRIMESurfaceDescriptor`.
434pub struct DrmPrimeSurfaceDescriptorObject {
435	pub fd: OwnedFd,
436	pub size: u32,
437	pub drm_format_modifier: u64,
438}
439
440/// Safe wrapper for the `layers` member of `VADRMPRIMESurfaceDescriptor`.
441pub struct DrmPrimeSurfaceDescriptorLayer {
442	pub drm_format: u32,
443	pub num_planes: u32,
444	pub object_index: [u8; 4],
445	pub offset: [u32; 4],
446	pub pitch: [u32; 4],
447}
448
449/// Safe wrapper around `VADRMPRIMESurfaceDescriptor`.
450pub struct DrmPrimeSurfaceDescriptor {
451	pub fourcc: u32,
452	pub width: u32,
453	pub height: u32,
454	pub objects: Vec<DrmPrimeSurfaceDescriptorObject>,
455	pub layers: Vec<DrmPrimeSurfaceDescriptorLayer>,
456}