kodecs_vaapi/image.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::marker::PhantomData;
6use std::sync::Arc;
7
8use crate::bindings;
9use crate::va_check;
10use crate::Display;
11use crate::Surface;
12use crate::SurfaceMemoryDescriptor;
13use crate::VaError;
14
15/// A `VAImage` libva created, destroyed on drop.
16struct Created {
17 display: Arc<Display>,
18 image: bindings::VAImage,
19}
20
21impl Drop for Created {
22 fn drop(&mut self) {
23 // Safe since `self.image` is a valid `VAImage` of `self.display`.
24 unsafe {
25 bindings::va().vaDestroyImage(self.display.handle(), self.image.image_id);
26 }
27 }
28}
29
30/// A [`Created`] image whose buffer is mapped into our address space, unmapped
31/// on drop before the image is destroyed.
32struct Mapping {
33 created: Created,
34 data: *mut u8,
35 /// Cleared once the buffer is unmapped, so drop never unmaps it twice.
36 mapped: bool,
37}
38
39// Safe since `data` is plain client memory owned by the mapping, and the libva calls
40// that release it go through `Display`, which is thread-safe. `Image` reads it only
41// through `&self` and `ImageMut` writes it only through `&mut self`, so the borrow
42// rules still exclude a data race.
43unsafe impl Send for Mapping {}
44unsafe impl Sync for Mapping {}
45
46impl Mapping {
47 /// Maps `created`'s buffer, destroying the image if that fails.
48 fn new(created: Created, display_resolution: (u32, u32)) -> Result<Self, VaError> {
49 let mut addr = std::ptr::null_mut();
50 // Safe since `created.image` is a valid `VAImage` of `created.display`.
51 va_check(unsafe { bindings::va().vaMapBuffer(created.display.handle(), created.image.buf, &mut addr) })?;
52 let mapping = Self {
53 created,
54 data: addr.cast(),
55 mapped: true,
56 };
57
58 // The guard unmaps and destroys the image when the driver hands back a
59 // mapping we cannot use.
60 let image = &mapping.created.image;
61 if mapping.data.is_null()
62 || u32::from(image.width) < display_resolution.0
63 || u32::from(image.height) < display_resolution.1
64 {
65 return Err(VaError::status(bindings::VA_STATUS_ERROR_INVALID_IMAGE));
66 }
67 Ok(mapping)
68 }
69
70 fn image(&self) -> &bindings::VAImage {
71 &self.created.image
72 }
73
74 fn len(&self) -> usize {
75 self.created.image.data_size as usize
76 }
77
78 /// Unmaps the buffer, leaving the image to be destroyed on drop.
79 fn unmap(&mut self) -> Result<(), VaError> {
80 self.mapped = false;
81 // Safe since the buffer was mapped in `new` and not unmapped since.
82 va_check(unsafe { bindings::va().vaUnmapBuffer(self.created.display.handle(), self.created.image.buf) })
83 }
84}
85
86impl Drop for Mapping {
87 fn drop(&mut self) {
88 if self.mapped {
89 // Nothing to report a failure to; the image is destroyed regardless.
90 let _ = self.unmap();
91 }
92 }
93}
94
95/// Creates a `VAImage` in `format` at `coded_resolution`.
96fn create(
97 display: &Arc<Display>,
98 mut format: bindings::VAImageFormat,
99 coded_resolution: (u32, u32),
100) -> Result<Created, VaError> {
101 // An all-zero byte-pattern is a valid initial value for `VAImage`.
102 let mut image: bindings::VAImage = Default::default();
103 // Safe because `display` is a valid display handle.
104 va_check(unsafe {
105 bindings::va().vaCreateImage(
106 display.handle(),
107 &mut format,
108 coded_resolution.0 as i32,
109 coded_resolution.1 as i32,
110 &mut image,
111 )
112 })?;
113 Ok(Created {
114 display: Arc::clone(display),
115 image,
116 })
117}
118
119/// A read-only view of a surface's pixels in client memory, borrowing the surface.
120///
121/// For writing pixels into a surface, see [`ImageMut`].
122pub struct Image<'a> {
123 mapping: Mapping,
124 /// Whether the image was derived using the `vaDeriveImage` API or created using the
125 /// `vaCreateImage` API.
126 derived: bool,
127 /// The display resolution requested by the client. The implementation is
128 /// free to enlarge this value as needed. In any case, we guarantee that an
129 /// image at least as large is returned.
130 display_resolution: (u32, u32),
131 /// Keeps the surface from being dropped or written through an [`ImageMut`] while we exist.
132 surface: PhantomData<&'a ()>,
133}
134
135impl<'a> Image<'a> {
136 fn new(created: Created, derived: bool, display_resolution: (u32, u32)) -> Result<Self, VaError> {
137 Ok(Image {
138 mapping: Mapping::new(created, display_resolution)?,
139 derived,
140 display_resolution,
141 surface: PhantomData,
142 })
143 }
144
145 /// Create a new derived image from this `surface` using `vaDeriveImage`.
146 ///
147 /// Derived images are a direct view (i.e. without any copy) on the buffer content of
148 /// `surface`. On the other hand, not all `Surface`s can be derived.
149 ///
150 /// `visible_rect` is the visible rectangle inside `surface` that we want to access.
151 ///
152 /// The view is the surface's own memory, so it borrows the surface mutably:
153 /// nothing, not even a GPU operation taking `&Surface`, can write it while the
154 /// view is alive. It first waits for any write still in flight.
155 pub fn derive_from<D: SurfaceMemoryDescriptor>(
156 surface: &'a mut Surface<D>,
157 visible_rect: (u32, u32),
158 ) -> Result<Self, VaError> {
159 surface.sync()?;
160 // Safe since the mutable borrow excludes every writer for `'a`, and the
161 // sync finished any that came before it.
162 unsafe { Self::derive_shared(surface, visible_rect) }
163 }
164
165 /// [`derive_from`](Self::derive_from) through a shared borrow.
166 ///
167 /// # Safety
168 ///
169 /// Nothing may write `surface`, through VA-API or otherwise, while the image
170 /// lives, nor still be writing it, such as a synced decoded picture the pool
171 /// hands out again only once every reference to it has dropped.
172 pub(crate) unsafe fn derive_shared<D: SurfaceMemoryDescriptor>(
173 surface: &'a Surface<D>,
174 visible_rect: (u32, u32),
175 ) -> Result<Self, VaError> {
176 // An all-zero byte-pattern is a valid initial value for `VAImage`.
177 let mut image: bindings::VAImage = Default::default();
178
179 // Safe because `surface` has a valid display handle and ID.
180 va_check(unsafe { bindings::va().vaDeriveImage(surface.display().handle(), surface.id(), &mut image) })?;
181 let created = Created {
182 display: Arc::clone(surface.display()),
183 image,
184 };
185
186 Self::new(created, true, visible_rect)
187 }
188
189 /// Create new image from `surface` using `vaCreateImage` and `vaGetImage`.
190 ///
191 /// `visible_rect` is the visible rectangle inside `surface` that we want to access.
192 ///
193 /// The image will contain a copy of `surface`'s data' in the desired `format` and
194 /// `coded_resolution`, meaning the data can be scaled if `coded_resolution` and `visible_rect`
195 /// differ.
196 pub fn create_from<D: SurfaceMemoryDescriptor>(
197 surface: &'a Surface<D>,
198 format: bindings::VAImageFormat,
199 coded_resolution: (u32, u32),
200 visible_rect: (u32, u32),
201 ) -> Result<Image<'a>, VaError> {
202 let created = create(surface.display(), format, coded_resolution)?;
203
204 // Safe because the display handle is valid, `surface` is a valid VASurface and
205 // `created.image` is a valid `VAImage`.
206 va_check(unsafe {
207 bindings::va().vaGetImage(
208 surface.display().handle(),
209 surface.id(),
210 0,
211 0,
212 coded_resolution.0,
213 coded_resolution.1,
214 created.image.image_id,
215 )
216 })?;
217
218 Self::new(created, false, visible_rect)
219 }
220
221 /// Get a reference to the underlying `VAImage` that describes this image.
222 pub fn image(&self) -> &bindings::VAImage {
223 self.mapping.image()
224 }
225
226 /// Returns whether this image is directly derived from its underlying `Picture`, as opposed to
227 /// being a view/copy of said `Picture` in a guaranteed pixel format.
228 pub fn is_derived(&self) -> bool {
229 self.derived
230 }
231
232 /// Returns the display resolution as passed in by the client. This is a
233 /// value that is less than or equal to the coded resolution.
234 pub fn display_resolution(&self) -> (u32, u32) {
235 self.display_resolution
236 }
237
238 /// Returns the coded resolution. This value can be larger than the value
239 /// passed in when the image was created if the driver needs to.
240 pub fn coded_resolution(&self) -> (u32, u32) {
241 (self.image().width.into(), self.image().height.into())
242 }
243}
244
245impl AsRef<[u8]> for Image<'_> {
246 fn as_ref(&self) -> &[u8] {
247 // Safe since the buffer stays mapped for `data_size` bytes while `self` lives, and
248 // nothing writes it: a created image is our own copy, and a derived one excludes
249 // every writer of the surface (see `derive_from`).
250 unsafe { std::slice::from_raw_parts(self.mapping.data, self.mapping.len()) }
251 }
252}
253
254/// Pixels to write into a surface, borrowing it mutably until [`put`](Self::put)
255/// copies them in.
256///
257/// Dropped without `put`, the image is discarded and the surface left as it was.
258///
259/// No other image of the surface, read or write, can exist alongside it:
260///
261/// ```compile_fail,E0502
262/// fn alias(surface: &mut kodecs_vaapi::Surface<()>, format: kodecs_vaapi::VAImageFormat) {
263/// let read = kodecs_vaapi::Image::create_from(surface, format, surface.size(), surface.size()).unwrap();
264/// let write = kodecs_vaapi::ImageMut::create_uninitialized(surface, format).unwrap();
265/// drop((read, write));
266/// }
267/// ```
268///
269/// Nor can a derived image share its surface with anything that writes it, a
270/// GPU operation through `&Surface` included:
271///
272/// ```compile_fail,E0502
273/// fn alias(surface: &mut kodecs_vaapi::Surface<()>) {
274/// let size = surface.size();
275/// let view = kodecs_vaapi::Image::derive_from(surface, size).unwrap();
276/// let shared: &kodecs_vaapi::Surface<()> = surface;
277/// drop((view, shared));
278/// }
279/// ```
280///
281/// An image unmaps and destroys itself only before its surface is destroyed:
282///
283/// ```compile_fail,E0505
284/// fn destroy_first(mut surface: kodecs_vaapi::Surface<()>) {
285/// let size = surface.size();
286/// let _view = kodecs_vaapi::Image::derive_from(&mut surface, size).unwrap();
287/// drop(surface);
288/// }
289/// ```
290///
291/// ```compile_fail,E0505
292/// fn destroy_first(mut surface: kodecs_vaapi::Surface<()>, format: kodecs_vaapi::VAImageFormat) {
293/// let _write = kodecs_vaapi::ImageMut::create_uninitialized(&mut surface, format).unwrap();
294/// drop(surface);
295/// }
296/// ```
297///
298/// ```compile_fail,E0499
299/// fn alias(surface: &mut kodecs_vaapi::Surface<()>, format: kodecs_vaapi::VAImageFormat) {
300/// let first = kodecs_vaapi::ImageMut::create_uninitialized(surface, format).unwrap();
301/// let second = kodecs_vaapi::ImageMut::create_uninitialized(surface, format).unwrap();
302/// drop((first, second));
303/// }
304/// ```
305#[must_use = "an image is written into its surface only by `put`"]
306pub struct ImageMut<'a> {
307 mapping: Mapping,
308 surface_id: bindings::VASurfaceID,
309 /// The surface's size, which the driver may have enlarged the image past.
310 size: (u32, u32),
311 surface: PhantomData<&'a mut ()>,
312}
313
314impl<'a> ImageMut<'a> {
315 /// Creates an image in `format` at `surface`'s size without reading the
316 /// surface back first, so every byte starts unspecified.
317 ///
318 /// Write every pixel [`put`](Self::put) should not leave unspecified: it
319 /// copies the image's top-left area, the surface's size, into the surface.
320 pub fn create_uninitialized<D: SurfaceMemoryDescriptor>(
321 surface: &'a mut Surface<D>,
322 format: bindings::VAImageFormat,
323 ) -> Result<Self, VaError> {
324 let size = surface.size();
325 let created = create(surface.display(), format, size)?;
326 Ok(Self {
327 mapping: Mapping::new(created, size)?,
328 surface_id: surface.id(),
329 size,
330 surface: PhantomData,
331 })
332 }
333
334 /// Get a reference to the underlying `VAImage` that describes this image.
335 pub fn image(&self) -> &bindings::VAImage {
336 self.mapping.image()
337 }
338
339 /// Copies the image into its surface with `vaPutImage`, returning once the
340 /// surface holds it.
341 pub fn put(mut self) -> Result<(), VaError> {
342 // libva requires the buffer unmapped before the driver reads it.
343 self.mapping.unmap()?;
344 let display = self.mapping.created.display.handle();
345 let (width, height) = self.size;
346 // Safe because the display handle is valid, `self.surface_id` is a surface we
347 // borrow, and the image is a valid, unmapped `VAImage` at least this large.
348 va_check(unsafe {
349 bindings::va().vaPutImage(
350 display,
351 self.surface_id,
352 self.mapping.image().image_id,
353 0,
354 0,
355 width,
356 height,
357 0,
358 0,
359 width,
360 height,
361 )
362 })?;
363 // The copy may still be in flight, and the borrow ends with `self`, so
364 // nothing after would know to wait for it.
365 // Safe for the same reasons as above.
366 va_check(unsafe { bindings::va().vaSyncSurface(display, self.surface_id) })
367 }
368}
369
370// The mapping that unmaps and destroys the image carries no lifetime, so these empty
371// drops are what make the drop checker hold the surface borrowed until it has run: libva
372// destroys an image only while its surface lives.
373impl Drop for Image<'_> {
374 fn drop(&mut self) {}
375}
376
377impl Drop for ImageMut<'_> {
378 fn drop(&mut self) {}
379}
380
381impl AsMut<[u8]> for ImageMut<'_> {
382 fn as_mut(&mut self) -> &mut [u8] {
383 // Safe since the buffer stays mapped for `data_size` bytes while `self` lives, and
384 // `&mut self` makes this the only reference to it.
385 unsafe { std::slice::from_raw_parts_mut(self.mapping.data, self.mapping.len()) }
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 #[test]
394 fn images_can_cross_threads() {
395 fn assert_send_sync<T: Send + Sync>() {}
396 assert_send_sync::<Image<'static>>();
397 assert_send_sync::<ImageMut<'static>>();
398 }
399}