forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

surface.rs330 lines, 10.6 KiBHistoryRawDownload
1//! VA surfaces: creation, DRM PRIME export and import, timed sync.
2
3use std::os::fd::AsRawFd;
4use std::rc::Rc;
5use std::time::{Duration, Instant};
6
7use cros_libva::{
8 DrmPrimeSurfaceDescriptor, ExternalBufferDescriptor, MemoryType, UsageHint,
9 VADRMPRIMESurfaceDescriptor, VASurfaceStatus,
10};
11
12use crate::display::Display;
13use crate::error::{Error, Result, va_ok};
14
15pub use cros_libva::Image;
16
17/// A VA surface with no client-side memory descriptor: the driver allocates it.
18pub type Surface = cros_libva::Surface<()>;
19
20/// What a pool of surfaces is made of.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct SurfaceSpec {
23 /// `VA_RT_FORMAT_*` for the config this surface will be used with.
24 pub rt_format: u32,
25 /// Exact pixel layout (FourCC). `None` lets the driver choose.
26 pub fourcc: Option<u32>,
27 /// Width in pixels. Must satisfy [`crate::SurfaceCaps::allows`].
28 pub width: u32,
29 /// Height in pixels.
30 pub height: u32,
31 /// `VA_SURFACE_ATTRIB_USAGE_HINT_*` bitmask; drivers use it to pick tiling.
32 pub usage_hint: u32,
33}
34
35impl SurfaceSpec {
36 /// 8-bit 4:2:0 NV12.
37 pub fn nv12(width: u32, height: u32) -> Self {
38 SurfaceSpec {
39 rt_format: cros_libva::VA_RT_FORMAT_YUV420,
40 fourcc: Some(cros_libva::VA_FOURCC_NV12),
41 width,
42 height,
43 usage_hint: 0,
44 }
45 }
46
47 /// 10-bit 4:2:0 P010 (samples in the top 10 bits of 16-bit words).
48 pub fn p010(width: u32, height: u32) -> Self {
49 SurfaceSpec {
50 rt_format: cros_libva::VA_RT_FORMAT_YUV420_10,
51 fourcc: Some(cros_libva::VA_FOURCC_P010),
52 width,
53 height,
54 usage_hint: 0,
55 }
56 }
57
58 /// The same spec with a `VA_SURFACE_ATTRIB_USAGE_HINT_*` bitmask.
59 pub fn with_usage_hint(mut self, hint: u32) -> Self {
60 self.usage_hint = hint;
61 self
62 }
63}
64
65/// Allocate `count` surfaces described by `spec` (`vaCreateSurfaces`).
66pub fn create_pool(
67 display: &Rc<Display>,
68 spec: &SurfaceSpec,
69 count: usize,
70) -> Result<Vec<Surface>> {
71 let usage = (spec.usage_hint != 0).then(|| UsageHint::from_bits_truncate(spec.usage_hint));
72 va_ok(
73 "vaCreateSurfaces",
74 display.create_surfaces(
75 spec.rt_format,
76 spec.fourcc,
77 spec.width,
78 spec.height,
79 usage,
80 vec![(); count],
81 ),
82 )
83}
84
85/// One exported memory object: a DMA-BUF file descriptor and its size.
86#[derive(Debug)]
87pub struct PrimeObject {
88 /// The DMA-BUF. Owned: it is closed when this value drops.
89 pub fd: std::os::fd::OwnedFd,
90 /// Size of the object in bytes.
91 pub size: u32,
92 /// DRM format modifier of the object.
93 pub modifier: u64,
94}
95
96/// One layer of an exported surface: a DRM format and its planes.
97#[derive(Debug, Clone)]
98pub struct PrimeLayer {
99 /// The DRM fourcc of this layer.
100 pub drm_format: u32,
101 /// `(object index, offset, pitch)` for each plane.
102 pub planes: Vec<(u32, u32, u32)>,
103}
104
105/// A surface exported as DRM PRIME: its objects (DMA-BUFs) and layers.
106#[derive(Debug)]
107pub struct PrimeSurface {
108 /// Pixel format fourcc.
109 pub fourcc: u32,
110 /// Width in pixels.
111 pub width: u32,
112 /// Height in pixels.
113 pub height: u32,
114 /// The memory objects backing the surface.
115 pub objects: Vec<PrimeObject>,
116 /// The layers referring to those objects.
117 pub layers: Vec<PrimeLayer>,
118}
119
120impl From<DrmPrimeSurfaceDescriptor> for PrimeSurface {
121 fn from(d: DrmPrimeSurfaceDescriptor) -> Self {
122 PrimeSurface {
123 fourcc: d.fourcc,
124 width: d.width,
125 height: d.height,
126 objects: d
127 .objects
128 .into_iter()
129 .map(|o| PrimeObject {
130 fd: o.fd,
131 size: o.size,
132 modifier: o.drm_format_modifier,
133 })
134 .collect(),
135 layers: d
136 .layers
137 .into_iter()
138 .map(|l| PrimeLayer {
139 drm_format: l.drm_format,
140 planes: (0..l.num_planes as usize)
141 .map(|i| (u32::from(l.object_index[i]), l.offset[i], l.pitch[i]))
142 .collect(),
143 })
144 .collect(),
145 }
146 }
147}
148
149/// Surface operations that need more than the cros-libva surface offers.
150pub trait SurfaceExt {
151 /// Export as DRM PRIME for zero-copy import elsewhere
152 /// (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`, read-only, composed layers).
153 /// Does not synchronise: call [`SurfaceExt::sync_timeout`] first.
154 fn export(&self) -> Result<PrimeSurface>;
155
156 /// Wait until the surface is no longer being rendered or displayed, or
157 /// fail with `VA_STATUS_ERROR_TIMEDOUT` after `timeout`.
158 ///
159 /// cros-libva does not wrap `vaSyncSurface2`, so this polls
160 /// `vaQuerySurfaceStatus` with a short back-off until the deadline.
161 fn sync_timeout(&self, timeout: Duration) -> Result<()>;
162}
163
164impl<D: cros_libva::SurfaceMemoryDescriptor> SurfaceExt for cros_libva::Surface<D> {
165 fn export(&self) -> Result<PrimeSurface> {
166 let d = va_ok("vaExportSurfaceHandle", self.export_prime())?;
167 Ok(PrimeSurface::from(d))
168 }
169
170 fn sync_timeout(&self, timeout: Duration) -> Result<()> {
171 let deadline = Instant::now() + timeout;
172 let mut pause = Duration::from_micros(50);
173 loop {
174 let status = va_ok("vaQuerySurfaceStatus", self.query_status())?;
175 if status & (VASurfaceStatus::VASurfaceRendering | VASurfaceStatus::VASurfaceDisplaying)
176 == 0
177 {
178 return Ok(());
179 }
180 let now = Instant::now();
181 if now >= deadline {
182 return Err(Error::Va {
183 op: "vaSyncSurface",
184 status: cros_libva::VA_STATUS_ERROR_TIMEDOUT as i32,
185 message: "surface still busy at the deadline".to_string(),
186 });
187 }
188 std::thread::sleep(pause.min(deadline - now));
189 pause = (pause * 2).min(Duration::from_millis(2));
190 }
191 }
192}
193
194/// A PRIME descriptor as a cros-libva memory descriptor: its
195/// `VASurfaceAttribExternalBuffers` attribute is the descriptor itself.
196/// The memory descriptor of a surface imported from DRM PRIME.
197pub struct PrimeImport(VADRMPRIMESurfaceDescriptor);
198
199impl ExternalBufferDescriptor for PrimeImport {
200 const MEMORY_TYPE: MemoryType = MemoryType::DrmPrime2;
201 type DescriptorAttribute = VADRMPRIMESurfaceDescriptor;
202
203 fn va_surface_attribute(&mut self) -> VADRMPRIMESurfaceDescriptor {
204 self.0
205 }
206}
207
208/// Import a DRM PRIME surface as a VA surface (`vaCreateSurfaces` with
209/// `VASurfaceAttribExternalBuffers`). The descriptors' file descriptors are
210/// borrowed for the call: the caller keeps ownership and closes them.
211pub fn import_prime(
212 display: &Rc<Display>,
213 prime: &PrimeSurface,
214) -> Result<cros_libva::Surface<PrimeImport>> {
215 let objects: Vec<RawPrimeObject> = prime
216 .objects
217 .iter()
218 .map(|o| RawPrimeObject {
219 fd: o.fd.as_raw_fd(),
220 size: o.size,
221 modifier: o.modifier,
222 })
223 .collect();
224 import_prime_raw(
225 display,
226 prime.fourcc,
227 (prime.width, prime.height),
228 &objects,
229 &prime.layers,
230 )
231}
232
233/// A DMA-BUF object borrowed by raw fd, for buffers another owner keeps
234/// (e.g. a PipeWire `spa_data` fd).
235#[derive(Debug, Clone, Copy)]
236pub struct RawPrimeObject {
237 /// The DMA-BUF, borrowed only for the duration of the import call.
238 pub fd: std::os::fd::RawFd,
239 /// Size of the object in bytes.
240 pub size: u32,
241 /// DRM format modifier of the object.
242 pub modifier: u64,
243}
244
245/// [`import_prime`] with borrowed raw fds. The driver takes its own reference
246/// to each DMA-BUF during `vaCreateSurfaces`, so the fds may be closed after
247/// this returns; the buffer contents must stay valid while the surface is read.
248pub fn import_prime_raw(
249 display: &Rc<Display>,
250 fourcc: u32,
251 size: (u32, u32),
252 objects: &[RawPrimeObject],
253 layers: &[PrimeLayer],
254) -> Result<cros_libva::Surface<PrimeImport>> {
255 if objects.len() > 4 || layers.len() > 4 {
256 return Err(Error::Protocol(format!(
257 "a PRIME surface has {} objects and {} layers, max 4 each",
258 objects.len(),
259 layers.len()
260 )));
261 }
262 let mut desc = VADRMPRIMESurfaceDescriptor {
263 fourcc,
264 width: size.0,
265 height: size.1,
266 num_objects: objects.len() as u32,
267 num_layers: layers.len() as u32,
268 ..Default::default()
269 };
270 for (i, o) in objects.iter().enumerate() {
271 desc.objects[i].fd = o.fd;
272 desc.objects[i].size = o.size;
273 desc.objects[i].drm_format_modifier = o.modifier;
274 }
275 for (i, l) in layers.iter().enumerate() {
276 if l.planes.len() > 4 {
277 return Err(Error::Protocol(format!(
278 "a PRIME layer has {} planes, max 4",
279 l.planes.len()
280 )));
281 }
282 desc.layers[i].drm_format = l.drm_format;
283 desc.layers[i].num_planes = l.planes.len() as u32;
284 for (p, &(obj, offset, pitch)) in l.planes.iter().enumerate() {
285 desc.layers[i].object_index[p] = obj;
286 desc.layers[i].offset[p] = offset;
287 desc.layers[i].pitch[p] = pitch;
288 }
289 }
290 let mut out = va_ok(
291 "vaCreateSurfaces",
292 display.create_surfaces(
293 cros_libva::VA_RT_FORMAT_YUV420,
294 Some(fourcc),
295 size.0,
296 size.1,
297 None,
298 vec![PrimeImport(desc)],
299 ),
300 )?;
301 out.pop()
302 .ok_or_else(|| Error::Protocol("vaCreateSurfaces returned no surface".into()))
303}
304
305/// The `VAImageFormat` the driver offers for `fourcc` (`vaQueryImageFormats`).
306pub fn image_format(display: &Display, fourcc: u32) -> Result<cros_libva::VAImageFormat> {
307 va_ok("vaQueryImageFormats", display.query_image_formats())?
308 .into_iter()
309 .find(|f| f.fourcc == fourcc)
310 .ok_or_else(|| {
311 Error::Protocol(format!(
312 "the driver offers no image format for {}",
313 crate::caps::fourcc_str(fourcc)
314 ))
315 })
316}
317
318/// `vaCreateImage` plus `vaGetImage`: a copy of `surface`'s pixels in an image
319/// of `format`, of `coded` size, showing `visible`.
320pub fn create_image<'a, D: cros_libva::SurfaceMemoryDescriptor>(
321 surface: &'a cros_libva::Surface<D>,
322 format: cros_libva::VAImageFormat,
323 coded: (u32, u32),
324 visible: (u32, u32),
325) -> Result<Image<'a>> {
326 va_ok(
327 "vaGetImage",
328 Image::create_from(surface, format, coded, visible),
329 )
330}