1use 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
18pub trait SurfaceMemoryDescriptor {
29 fn add_attrs(&mut self, attrs: &mut Vec<bindings::VASurfaceAttrib>) -> Option<Box<dyn Any>>;
35}
36
37#[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
46impl SurfaceMemoryDescriptor for () {
49 fn add_attrs(&mut self, _: &mut Vec<bindings::VASurfaceAttrib>) -> Option<Box<dyn Any>> {
50 None
51 }
52}
53
54mod private {
56 pub trait Sealed {}
57}
58
59pub 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
66pub trait ExternalBufferDescriptor {
69 const MEMORY_TYPE: MemoryType;
71 type DescriptorAttribute: SurfaceExternalDescriptor;
73
74 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#[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#[derive(Debug)]
105pub struct SurfaceDecodeMBError {
106 pub start_mb: u32,
108
109 pub end_mb: u32,
111
112 pub decode_error_type: DecodeErrorType,
113
114 pub num_mb: u32,
116}
117
118pub 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
154impl 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 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 let mut _va_desc = descriptor.add_attrs(&mut attrs);
216 let mut surface_id: VASurfaceID = 0;
217
218 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 pub fn sync(&self) -> Result<(), VaError> {
260 va_check(unsafe { bindings::va().vaSyncSurface(self.display.handle(), self.id) })
262 }
263
264 pub(crate) fn as_id_vec(surfaces: &[Self]) -> Vec<bindings::VASurfaceID> {
267 surfaces.iter().map(|surface| surface.id).collect()
268 }
269
270 pub(crate) fn query_status(&self) -> Result<bindings::VASurfaceStatus::Type, VaError> {
272 let mut status: bindings::VASurfaceStatus::Type = 0;
273 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 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 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 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 raw = unsafe { raw.offset(1) };
323 }
324
325 Ok(errors)
326 }
327
328 pub(crate) fn id(&self) -> bindings::VASurfaceID {
330 self.id
331 }
332
333 pub fn size(&self) -> (u32, u32) {
335 (self.width, self.height)
336 }
337
338 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 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 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 unsafe { bindings::va().vaDestroySurfaces(self.display.handle(), &mut self.id, 1) };
430 }
431}
432
433pub struct DrmPrimeSurfaceDescriptorObject {
435 pub fd: OwnedFd,
436 pub size: u32,
437 pub drm_format_modifier: u64,
438}
439
440pub 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
449pub 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}