forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

surface.rs290 lines, 9.5 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 if prime.objects.len() > 4 || prime.layers.len() > 4 {
216 return Err(Error::Protocol(format!(
217 "a PRIME surface has {} objects and {} layers, max 4 each",
218 prime.objects.len(),
219 prime.layers.len()
220 )));
221 }
222 let mut desc = VADRMPRIMESurfaceDescriptor {
223 fourcc: prime.fourcc,
224 width: prime.width,
225 height: prime.height,
226 num_objects: prime.objects.len() as u32,
227 num_layers: prime.layers.len() as u32,
228 ..Default::default()
229 };
230 for (i, o) in prime.objects.iter().enumerate() {
231 desc.objects[i].fd = o.fd.as_raw_fd();
232 desc.objects[i].size = o.size;
233 desc.objects[i].drm_format_modifier = o.modifier;
234 }
235 for (i, l) in prime.layers.iter().enumerate() {
236 if l.planes.len() > 4 {
237 return Err(Error::Protocol(format!(
238 "a PRIME layer has {} planes, max 4",
239 l.planes.len()
240 )));
241 }
242 desc.layers[i].drm_format = l.drm_format;
243 desc.layers[i].num_planes = l.planes.len() as u32;
244 for (p, &(obj, offset, pitch)) in l.planes.iter().enumerate() {
245 desc.layers[i].object_index[p] = obj;
246 desc.layers[i].offset[p] = offset;
247 desc.layers[i].pitch[p] = pitch;
248 }
249 }
250 let mut out = va_ok(
251 "vaCreateSurfaces",
252 display.create_surfaces(
253 cros_libva::VA_RT_FORMAT_YUV420,
254 Some(prime.fourcc),
255 prime.width,
256 prime.height,
257 None,
258 vec![PrimeImport(desc)],
259 ),
260 )?;
261 out.pop()
262 .ok_or_else(|| Error::Protocol("vaCreateSurfaces returned no surface".into()))
263}
264
265/// The `VAImageFormat` the driver offers for `fourcc` (`vaQueryImageFormats`).
266pub fn image_format(display: &Display, fourcc: u32) -> Result<cros_libva::VAImageFormat> {
267 va_ok("vaQueryImageFormats", display.query_image_formats())?
268 .into_iter()
269 .find(|f| f.fourcc == fourcc)
270 .ok_or_else(|| {
271 Error::Protocol(format!(
272 "the driver offers no image format for {}",
273 crate::caps::fourcc_str(fourcc)
274 ))
275 })
276}
277
278/// `vaCreateImage` plus `vaGetImage`: a copy of `surface`'s pixels in an image
279/// of `format`, of `coded` size, showing `visible`.
280pub fn create_image<'a, D: cros_libva::SurfaceMemoryDescriptor>(
281 surface: &'a cros_libva::Surface<D>,
282 format: cros_libva::VAImageFormat,
283 coded: (u32, u32),
284 visible: (u32, u32),
285) -> Result<Image<'a>> {
286 va_ok(
287 "vaGetImage",
288 Image::create_from(surface, format, coded, visible),
289 )
290}