blob: 9876362cec9d6d901132114655f94e367ddda116 [file] [log] [blame]
Jim Shargo7df9f752023-07-18 20:33:45 +00001// Copyright (C) 2023 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Pleasant Rust bindings for libnativewindow, including AHardwareBuffer
16
17extern crate nativewindow_bindgen as ffi;
18
Andrew Walbran9487efd2024-08-20 18:37:59 +010019mod handle;
Jiyong Park8032bff2024-04-01 16:17:15 +090020mod surface;
Andrew Walbran9487efd2024-08-20 18:37:59 +010021
Andrew Walbran43bddb62023-09-01 16:43:09 +010022pub use ffi::{AHardwareBuffer_Format, AHardwareBuffer_UsageFlags};
Andrew Walbran30262982024-09-27 16:38:42 +010023pub use handle::NativeHandle;
24pub use surface::{buffer::Buffer, Surface};
Jim Shargo7df9f752023-07-18 20:33:45 +000025
Andrew Walbran43bddb62023-09-01 16:43:09 +010026use binder::{
Andrew Walbrane9573af2024-01-11 16:34:16 +000027 binder_impl::{BorrowedParcel, UnstructuredParcelable},
28 impl_deserialize_for_unstructured_parcelable, impl_serialize_for_unstructured_parcelable,
Andrew Walbran43bddb62023-09-01 16:43:09 +010029 unstable_api::{status_result, AsNative},
30 StatusCode,
31};
Andrew Walbranabc932e2024-08-30 14:10:29 +010032use ffi::{
33 AHardwareBuffer, AHardwareBuffer_Desc, AHardwareBuffer_readFromParcel,
Andrew Walbrane0361622024-10-23 18:49:27 +010034 AHardwareBuffer_writeToParcel, ARect,
Andrew Walbranabc932e2024-08-30 14:10:29 +010035};
Andrew Walbrane0361622024-10-23 18:49:27 +010036use std::ffi::c_void;
Jim Shargob69c6ef2023-10-05 22:54:51 +000037use std::fmt::{self, Debug, Formatter};
Andrew Walbrane0361622024-10-23 18:49:27 +010038use std::mem::{forget, ManuallyDrop};
39use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
40use std::ptr::{self, null, null_mut, NonNull};
Jim Shargo7df9f752023-07-18 20:33:45 +000041
Andrew Walbranabc932e2024-08-30 14:10:29 +010042/// Wrapper around a C `AHardwareBuffer_Desc`.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct HardwareBufferDescription(AHardwareBuffer_Desc);
45
46impl HardwareBufferDescription {
47 /// Creates a new `HardwareBufferDescription` with the given parameters.
48 pub fn new(
49 width: u32,
50 height: u32,
51 layers: u32,
52 format: AHardwareBuffer_Format::Type,
53 usage: AHardwareBuffer_UsageFlags,
54 stride: u32,
55 ) -> Self {
56 Self(AHardwareBuffer_Desc {
57 width,
58 height,
59 layers,
60 format,
61 usage: usage.0,
62 stride,
63 rfu0: 0,
64 rfu1: 0,
65 })
66 }
67
68 /// Returns the width from the buffer description.
69 pub fn width(&self) -> u32 {
70 self.0.width
71 }
72
73 /// Returns the height from the buffer description.
74 pub fn height(&self) -> u32 {
75 self.0.height
76 }
77
78 /// Returns the number from layers from the buffer description.
79 pub fn layers(&self) -> u32 {
80 self.0.layers
81 }
82
83 /// Returns the format from the buffer description.
84 pub fn format(&self) -> AHardwareBuffer_Format::Type {
85 self.0.format
86 }
87
88 /// Returns the usage bitvector from the buffer description.
89 pub fn usage(&self) -> AHardwareBuffer_UsageFlags {
90 AHardwareBuffer_UsageFlags(self.0.usage)
91 }
92
93 /// Returns the stride from the buffer description.
94 pub fn stride(&self) -> u32 {
95 self.0.stride
96 }
97}
98
99impl Default for HardwareBufferDescription {
100 fn default() -> Self {
101 Self(AHardwareBuffer_Desc {
102 width: 0,
103 height: 0,
104 layers: 0,
105 format: 0,
106 usage: 0,
107 stride: 0,
108 rfu0: 0,
109 rfu1: 0,
110 })
111 }
112}
113
Andrew Walbran43bddb62023-09-01 16:43:09 +0100114/// Wrapper around an opaque C `AHardwareBuffer`.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000115#[derive(PartialEq, Eq)]
116pub struct HardwareBuffer(NonNull<AHardwareBuffer>);
Jim Shargo7df9f752023-07-18 20:33:45 +0000117
Jim Shargob69c6ef2023-10-05 22:54:51 +0000118impl HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +0000119 /// Test whether the given format and usage flag combination is allocatable. If this function
120 /// returns true, it means that a buffer with the given description can be allocated on this
121 /// implementation, unless resource exhaustion occurs. If this function returns false, it means
122 /// that the allocation of the given description will never succeed.
123 ///
124 /// Available since API 29
Andrew Walbranabc932e2024-08-30 14:10:29 +0100125 pub fn is_supported(buffer_description: &HardwareBufferDescription) -> bool {
126 // SAFETY: The pointer comes from a reference so must be valid.
127 let status = unsafe { ffi::AHardwareBuffer_isSupported(&buffer_description.0) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000128
129 status == 1
130 }
131
132 /// Allocates a buffer that matches the passed AHardwareBuffer_Desc. If allocation succeeds, the
133 /// buffer can be used according to the usage flags specified in its description. If a buffer is
134 /// used in ways not compatible with its usage flags, the results are undefined and may include
135 /// program termination.
136 ///
137 /// Available since API level 26.
Jim Shargoe4680d72023-08-07 16:46:45 +0000138 #[inline]
Andrew Walbranabc932e2024-08-30 14:10:29 +0100139 pub fn new(buffer_description: &HardwareBufferDescription) -> Option<Self> {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000140 let mut ptr = ptr::null_mut();
Jim Shargo7df9f752023-07-18 20:33:45 +0000141 // SAFETY: The returned pointer is valid until we drop/deallocate it. The function may fail
142 // and return a status, but we check it later.
Andrew Walbranabc932e2024-08-30 14:10:29 +0100143 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_description.0, &mut ptr) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000144
145 if status == 0 {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000146 Some(Self(NonNull::new(ptr).expect("Allocated AHardwareBuffer was null")))
Jim Shargo7df9f752023-07-18 20:33:45 +0000147 } else {
148 None
149 }
150 }
151
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100152 /// Creates a `HardwareBuffer` from a native handle.
153 ///
154 /// The native handle is cloned, so this doesn't take ownership of the original handle passed
155 /// in.
156 pub fn create_from_handle(
157 handle: &NativeHandle,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100158 buffer_description: &HardwareBufferDescription,
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100159 ) -> Result<Self, StatusCode> {
160 let mut buffer = ptr::null_mut();
161 // SAFETY: The caller guarantees that `handle` is valid, and the buffer pointer is valid
162 // because it comes from a reference. The method we pass means that
163 // `AHardwareBuffer_createFromHandle` will clone the handle rather than taking ownership of
164 // it.
165 let status = unsafe {
166 ffi::AHardwareBuffer_createFromHandle(
Andrew Walbranabc932e2024-08-30 14:10:29 +0100167 &buffer_description.0,
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100168 handle.as_raw().as_ptr(),
169 ffi::CreateFromHandleMethod_AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE
170 .try_into()
171 .unwrap(),
172 &mut buffer,
173 )
174 };
175 status_result(status)?;
176 Ok(Self(NonNull::new(buffer).expect("Allocated AHardwareBuffer was null")))
177 }
178
179 /// Returns a clone of the native handle of the buffer.
180 ///
181 /// Returns `None` if the operation fails for any reason.
182 pub fn cloned_native_handle(&self) -> Option<NativeHandle> {
183 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
184 // because it must have been allocated by `AHardwareBuffer_allocate`,
185 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
186 // released it.
187 let native_handle = unsafe { ffi::AHardwareBuffer_getNativeHandle(self.0.as_ptr()) };
188 NonNull::new(native_handle.cast_mut()).and_then(|native_handle| {
189 // SAFETY: `AHardwareBuffer_getNativeHandle` should have returned a valid pointer which
190 // is valid at least as long as the buffer is, and `clone_from_raw` clones it rather
191 // than taking ownership of it so the original `native_handle` isn't stored.
192 unsafe { NativeHandle::clone_from_raw(native_handle) }
193 })
194 }
195
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000196 /// Adopts the given raw pointer and wraps it in a Rust HardwareBuffer.
Jim Shargo7df9f752023-07-18 20:33:45 +0000197 ///
198 /// # Safety
199 ///
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000200 /// This function takes ownership of the pointer and does NOT increment the refcount on the
201 /// buffer. If the caller uses the pointer after the created object is dropped it will cause
202 /// undefined behaviour. If the caller wants to continue using the pointer after calling this
203 /// then use [`clone_from_raw`](Self::clone_from_raw) instead.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000204 pub unsafe fn from_raw(buffer_ptr: NonNull<AHardwareBuffer>) -> Self {
205 Self(buffer_ptr)
206 }
207
Andrew Walbran7e947d32024-10-23 17:03:59 +0100208 /// Creates a new Rust HardwareBuffer to wrap the given `AHardwareBuffer` without taking
209 /// ownership of it.
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000210 ///
211 /// Unlike [`from_raw`](Self::from_raw) this method will increment the refcount on the buffer.
212 /// This means that the caller can continue to use the raw buffer it passed in, and must call
213 /// [`AHardwareBuffer_release`](ffi::AHardwareBuffer_release) when it is finished with it to
214 /// avoid a memory leak.
215 ///
216 /// # Safety
217 ///
218 /// The buffer pointer must point to a valid `AHardwareBuffer`.
219 pub unsafe fn clone_from_raw(buffer: NonNull<AHardwareBuffer>) -> Self {
220 // SAFETY: The caller guarantees that the AHardwareBuffer pointer is valid.
221 unsafe { ffi::AHardwareBuffer_acquire(buffer.as_ptr()) };
222 Self(buffer)
223 }
224
Andrew Walbran7e947d32024-10-23 17:03:59 +0100225 /// Returns the internal `AHardwareBuffer` pointer.
226 ///
227 /// This is only valid as long as this `HardwareBuffer` exists, so shouldn't be stored. It can
228 /// be used to provide a pointer for a C/C++ API over FFI.
Ren-Pei Zeng8237ba62024-10-22 15:20:18 +0000229 pub fn as_raw(&self) -> NonNull<AHardwareBuffer> {
230 self.0
231 }
232
Andrew Walbran7e947d32024-10-23 17:03:59 +0100233 /// Gets the internal `AHardwareBuffer` pointer without decrementing the refcount. This can
234 /// be used for a C/C++ API which takes ownership of the pointer.
235 ///
236 /// The caller is responsible for releasing the `AHardwareBuffer` pointer by calling
237 /// `AHardwareBuffer_release` when it is finished with it, or may convert it back to a Rust
238 /// `HardwareBuffer` by calling [`HardwareBuffer::from_raw`].
Jim Shargob69c6ef2023-10-05 22:54:51 +0000239 pub fn into_raw(self) -> NonNull<AHardwareBuffer> {
240 let buffer = ManuallyDrop::new(self);
241 buffer.0
Jim Shargo7df9f752023-07-18 20:33:45 +0000242 }
243
244 /// Get the system wide unique id for an AHardwareBuffer. This function may panic in extreme
245 /// and undocumented circumstances.
246 ///
247 /// Available since API level 31.
248 pub fn id(&self) -> u64 {
249 let mut out_id = 0;
Andrew Walbran43bddb62023-09-01 16:43:09 +0100250 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
251 // because it must have been allocated by `AHardwareBuffer_allocate`,
252 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
253 // released it. The id pointer must be valid because it comes from a reference.
254 let status = unsafe { ffi::AHardwareBuffer_getId(self.0.as_ptr(), &mut out_id) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000255 assert_eq!(status, 0, "id() failed for AHardwareBuffer with error code: {status}");
256
257 out_id
258 }
259
Andrew Walbranabc932e2024-08-30 14:10:29 +0100260 /// Returns the description of this buffer.
261 pub fn description(&self) -> HardwareBufferDescription {
Jim Shargo7df9f752023-07-18 20:33:45 +0000262 let mut buffer_desc = ffi::AHardwareBuffer_Desc {
263 width: 0,
264 height: 0,
265 layers: 0,
266 format: 0,
267 usage: 0,
268 stride: 0,
269 rfu0: 0,
270 rfu1: 0,
271 };
Andrew Walbrane0361622024-10-23 18:49:27 +0100272 // SAFETY: The `AHardwareBuffer` pointer we wrap is always valid, and the
273 // AHardwareBuffer_Desc pointer is valid because it comes from a reference.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000274 unsafe { ffi::AHardwareBuffer_describe(self.0.as_ref(), &mut buffer_desc) };
Andrew Walbranabc932e2024-08-30 14:10:29 +0100275 HardwareBufferDescription(buffer_desc)
Jim Shargo7df9f752023-07-18 20:33:45 +0000276 }
Andrew Walbrane0361622024-10-23 18:49:27 +0100277
278 /// Locks the hardware buffer for direct CPU access.
279 ///
280 /// # Safety
281 ///
282 /// - If `fence` is `None`, the caller must ensure that all writes to the buffer have completed
283 /// before calling this function.
284 /// - If the buffer has `AHARDWAREBUFFER_FORMAT_BLOB`, multiple threads or process may lock the
285 /// buffer simultaneously, but the caller must ensure that they don't access it simultaneously
286 /// and break Rust's aliasing rules, like any other shared memory.
287 /// - Otherwise if `usage` includes `AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY` or
288 /// `AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN`, the caller must ensure that no other threads or
289 /// processes lock the buffer simultaneously for any usage.
290 /// - Otherwise, the caller must ensure that no other threads lock the buffer for writing
291 /// simultaneously.
292 /// - If `rect` is not `None`, the caller must not modify the buffer outside of that rectangle.
293 pub unsafe fn lock<'a>(
294 &'a self,
295 usage: AHardwareBuffer_UsageFlags,
296 fence: Option<BorrowedFd>,
297 rect: Option<&ARect>,
298 ) -> Result<HardwareBufferGuard<'a>, StatusCode> {
299 let fence = if let Some(fence) = fence { fence.as_raw_fd() } else { -1 };
300 let rect = rect.map(ptr::from_ref).unwrap_or(null());
301 let mut address = null_mut();
302 // SAFETY: The `AHardwareBuffer` pointer we wrap is always valid, and the buffer address out
303 // pointer is valid because it comes from a reference. Our caller promises that writes have
304 // completed and there will be no simultaneous read/write locks.
305 let status = unsafe {
306 ffi::AHardwareBuffer_lock(self.0.as_ptr(), usage.0, fence, rect, &mut address)
307 };
308 status_result(status)?;
309 Ok(HardwareBufferGuard {
310 buffer: self,
311 address: NonNull::new(address)
312 .expect("AHardwareBuffer_lock set a null outVirtualAddress"),
313 })
314 }
315
316 /// Locks the hardware buffer for direct CPU access, returning information about the bytes per
317 /// pixel and stride as well.
318 ///
319 /// # Safety
320 ///
321 /// - If `fence` is `None`, the caller must ensure that all writes to the buffer have completed
322 /// before calling this function.
323 /// - If the buffer has `AHARDWAREBUFFER_FORMAT_BLOB`, multiple threads or process may lock the
324 /// buffer simultaneously, but the caller must ensure that they don't access it simultaneously
325 /// and break Rust's aliasing rules, like any other shared memory.
326 /// - Otherwise if `usage` includes `AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY` or
327 /// `AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN`, the caller must ensure that no other threads or
328 /// processes lock the buffer simultaneously for any usage.
329 /// - Otherwise, the caller must ensure that no other threads lock the buffer for writing
330 /// simultaneously.
331 pub unsafe fn lock_and_get_info<'a>(
332 &'a self,
333 usage: AHardwareBuffer_UsageFlags,
334 fence: Option<BorrowedFd>,
335 rect: Option<&ARect>,
336 ) -> Result<LockedBufferInfo<'a>, StatusCode> {
337 let fence = if let Some(fence) = fence { fence.as_raw_fd() } else { -1 };
338 let rect = rect.map(ptr::from_ref).unwrap_or(null());
339 let mut address = null_mut();
340 let mut bytes_per_pixel = 0;
341 let mut stride = 0;
342 // SAFETY: The `AHardwareBuffer` pointer we wrap is always valid, and the various out
343 // pointers are valid because they come from references. Our caller promises that writes have
344 // completed and there will be no simultaneous read/write locks.
345 let status = unsafe {
346 ffi::AHardwareBuffer_lockAndGetInfo(
347 self.0.as_ptr(),
348 usage.0,
349 fence,
350 rect,
351 &mut address,
352 &mut bytes_per_pixel,
353 &mut stride,
354 )
355 };
356 status_result(status)?;
357 Ok(LockedBufferInfo {
358 guard: HardwareBufferGuard {
359 buffer: self,
360 address: NonNull::new(address)
361 .expect("AHardwareBuffer_lockAndGetInfo set a null outVirtualAddress"),
362 },
363 bytes_per_pixel: bytes_per_pixel as u32,
364 stride: stride as u32,
365 })
366 }
367
368 /// Unlocks the hardware buffer from direct CPU access.
369 ///
370 /// Must be called after all changes to the buffer are completed by the caller. This will block
371 /// until the unlocking is complete and the buffer contents are updated.
372 fn unlock(&self) -> Result<(), StatusCode> {
373 // SAFETY: The `AHardwareBuffer` pointer we wrap is always valid.
374 let status = unsafe { ffi::AHardwareBuffer_unlock(self.0.as_ptr(), null_mut()) };
375 status_result(status)?;
376 Ok(())
377 }
378
379 /// Unlocks the hardware buffer from direct CPU access.
380 ///
381 /// Must be called after all changes to the buffer are completed by the caller.
382 ///
383 /// This may not block until all work is completed, but rather will return a file descriptor
384 /// which will be signalled once the unlocking is complete and the buffer contents is updated.
385 /// If `Ok(None)` is returned then unlocking has already completed and no further waiting is
386 /// necessary. The file descriptor may be passed to a subsequent call to [`Self::lock`].
387 pub fn unlock_with_fence(
388 &self,
389 guard: HardwareBufferGuard,
390 ) -> Result<Option<OwnedFd>, StatusCode> {
391 // Forget the guard so that its `Drop` implementation doesn't try to unlock the
392 // HardwareBuffer again.
393 forget(guard);
394
395 let mut fence = -2;
396 // SAFETY: The `AHardwareBuffer` pointer we wrap is always valid.
397 let status = unsafe { ffi::AHardwareBuffer_unlock(self.0.as_ptr(), &mut fence) };
398 let fence = if fence < 0 {
399 None
400 } else {
401 // SAFETY: `AHardwareBuffer_unlock` gives us ownership of the fence file descriptor.
402 Some(unsafe { OwnedFd::from_raw_fd(fence) })
403 };
404 status_result(status)?;
405 Ok(fence)
406 }
Jim Shargo7df9f752023-07-18 20:33:45 +0000407}
408
Jim Shargob69c6ef2023-10-05 22:54:51 +0000409impl Drop for HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +0000410 fn drop(&mut self) {
Andrew Walbran43bddb62023-09-01 16:43:09 +0100411 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
412 // because it must have been allocated by `AHardwareBuffer_allocate`,
413 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
414 // released it.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000415 unsafe { ffi::AHardwareBuffer_release(self.0.as_ptr()) }
Jim Shargo7df9f752023-07-18 20:33:45 +0000416 }
417}
418
Jim Shargob69c6ef2023-10-05 22:54:51 +0000419impl Debug for HardwareBuffer {
Andrew Walbran8ee0ef12024-01-12 15:56:14 +0000420 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000421 f.debug_struct("HardwareBuffer").field("id", &self.id()).finish()
422 }
423}
424
425impl Clone for HardwareBuffer {
426 fn clone(&self) -> Self {
427 // SAFETY: ptr is guaranteed to be non-null and the acquire can not fail.
428 unsafe { ffi::AHardwareBuffer_acquire(self.0.as_ptr()) };
429 Self(self.0)
430 }
431}
432
Andrew Walbrane9573af2024-01-11 16:34:16 +0000433impl UnstructuredParcelable for HardwareBuffer {
434 fn write_to_parcel(&self, parcel: &mut BorrowedParcel) -> Result<(), StatusCode> {
435 let status =
436 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
437 // because it must have been allocated by `AHardwareBuffer_allocate`,
438 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
439 // released it.
440 unsafe { AHardwareBuffer_writeToParcel(self.0.as_ptr(), parcel.as_native_mut()) };
441 status_result(status)
442 }
443
444 fn from_parcel(parcel: &BorrowedParcel) -> Result<Self, StatusCode> {
445 let mut buffer = null_mut();
446
447 let status =
448 // SAFETY: Both pointers must be valid because they are obtained from references.
449 // `AHardwareBuffer_readFromParcel` doesn't store them or do anything else special
450 // with them. If it returns success then it will have allocated a new
451 // `AHardwareBuffer` and incremented the reference count, so we can use it until we
452 // release it.
453 unsafe { AHardwareBuffer_readFromParcel(parcel.as_native(), &mut buffer) };
454
455 status_result(status)?;
456
457 Ok(Self(
458 NonNull::new(buffer).expect(
459 "AHardwareBuffer_readFromParcel returned success but didn't allocate buffer",
460 ),
461 ))
Andrew Walbran43bddb62023-09-01 16:43:09 +0100462 }
463}
464
Andrew Walbrane9573af2024-01-11 16:34:16 +0000465impl_deserialize_for_unstructured_parcelable!(HardwareBuffer);
466impl_serialize_for_unstructured_parcelable!(HardwareBuffer);
Andrew Walbran43bddb62023-09-01 16:43:09 +0100467
Jim Shargob69c6ef2023-10-05 22:54:51 +0000468// SAFETY: The underlying *AHardwareBuffers can be moved between threads.
469unsafe impl Send for HardwareBuffer {}
470
471// SAFETY: The underlying *AHardwareBuffers can be used from multiple threads.
472//
473// AHardwareBuffers are backed by C++ GraphicBuffers, which are mostly immutable. The only cases
474// where they are not immutable are:
475//
476// - reallocation (which is never actually done across the codebase and requires special
477// privileges/platform code access to do)
478// - "locking" for reading/writing (which is explicitly allowed to be done across multiple threads
479// according to the docs on the underlying gralloc calls)
480unsafe impl Sync for HardwareBuffer {}
481
Andrew Walbrane0361622024-10-23 18:49:27 +0100482/// A guard for when a `HardwareBuffer` is locked.
483///
484/// The `HardwareBuffer` will be unlocked when this is dropped, or may be unlocked via
485/// [`HardwareBuffer::unlock_with_fence`].
486#[derive(Debug)]
487pub struct HardwareBufferGuard<'a> {
488 buffer: &'a HardwareBuffer,
489 /// The address of the buffer in memory.
490 pub address: NonNull<c_void>,
491}
492
493impl<'a> Drop for HardwareBufferGuard<'a> {
494 fn drop(&mut self) {
495 self.buffer
496 .unlock()
497 .expect("Failed to unlock HardwareBuffer when dropping HardwareBufferGuard");
498 }
499}
500
501/// A guard for when a `HardwareBuffer` is locked, with additional information about the number of
502/// bytes per pixel and stride.
503#[derive(Debug)]
504pub struct LockedBufferInfo<'a> {
505 /// The locked buffer guard.
506 pub guard: HardwareBufferGuard<'a>,
507 /// The number of bytes used for each pixel in the buffer.
508 pub bytes_per_pixel: u32,
509 /// The stride in bytes between rows in the buffer.
510 pub stride: u32,
511}
512
Jim Shargo7df9f752023-07-18 20:33:45 +0000513#[cfg(test)]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000514mod test {
Jim Shargo7df9f752023-07-18 20:33:45 +0000515 use super::*;
516
517 #[test]
518 fn create_valid_buffer_returns_ok() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100519 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000520 512,
521 512,
522 1,
523 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
524 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100525 0,
526 ));
Jim Shargo7df9f752023-07-18 20:33:45 +0000527 assert!(buffer.is_some());
528 }
529
530 #[test]
531 fn create_invalid_buffer_returns_err() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100532 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
533 512,
534 512,
535 1,
536 0,
537 AHardwareBuffer_UsageFlags(0),
538 0,
539 ));
Jim Shargo7df9f752023-07-18 20:33:45 +0000540 assert!(buffer.is_none());
541 }
542
543 #[test]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000544 fn from_raw_allows_getters() {
Jim Shargo7df9f752023-07-18 20:33:45 +0000545 let buffer_desc = ffi::AHardwareBuffer_Desc {
546 width: 1024,
547 height: 512,
548 layers: 1,
549 format: AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
550 usage: AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN.0,
551 stride: 0,
552 rfu0: 0,
553 rfu1: 0,
554 };
555 let mut raw_buffer_ptr = ptr::null_mut();
556
Andrew Walbran03350bc2023-08-03 16:02:51 +0000557 // SAFETY: The pointers are valid because they come from references, and
558 // `AHardwareBuffer_allocate` doesn't retain them after it returns.
Jim Shargo7df9f752023-07-18 20:33:45 +0000559 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_desc, &mut raw_buffer_ptr) };
560 assert_eq!(status, 0);
561
Andrew Walbran03350bc2023-08-03 16:02:51 +0000562 // SAFETY: The pointer must be valid because it was just allocated successfully, and we
563 // don't use it after calling this.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000564 let buffer = unsafe { HardwareBuffer::from_raw(NonNull::new(raw_buffer_ptr).unwrap()) };
Andrew Walbranabc932e2024-08-30 14:10:29 +0100565 assert_eq!(buffer.description().width(), 1024);
Jim Shargo7df9f752023-07-18 20:33:45 +0000566 }
567
568 #[test]
569 fn basic_getters() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100570 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000571 1024,
572 512,
573 1,
574 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
575 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100576 0,
577 ))
Jim Shargo7df9f752023-07-18 20:33:45 +0000578 .expect("Buffer with some basic parameters was not created successfully");
579
Andrew Walbranabc932e2024-08-30 14:10:29 +0100580 let description = buffer.description();
581 assert_eq!(description.width(), 1024);
582 assert_eq!(description.height(), 512);
583 assert_eq!(description.layers(), 1);
Jim Shargo7df9f752023-07-18 20:33:45 +0000584 assert_eq!(
Andrew Walbranabc932e2024-08-30 14:10:29 +0100585 description.format(),
586 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM
587 );
588 assert_eq!(
589 description.usage(),
Jim Shargo7df9f752023-07-18 20:33:45 +0000590 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN
591 );
592 }
593
594 #[test]
595 fn id_getter() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100596 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000597 1024,
598 512,
599 1,
600 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
601 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100602 0,
603 ))
Jim Shargo7df9f752023-07-18 20:33:45 +0000604 .expect("Buffer with some basic parameters was not created successfully");
605
606 assert_ne!(0, buffer.id());
607 }
Jim Shargob69c6ef2023-10-05 22:54:51 +0000608
609 #[test]
610 fn clone() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100611 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargob69c6ef2023-10-05 22:54:51 +0000612 1024,
613 512,
614 1,
615 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
616 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100617 0,
618 ))
Jim Shargob69c6ef2023-10-05 22:54:51 +0000619 .expect("Buffer with some basic parameters was not created successfully");
620 let buffer2 = buffer.clone();
621
622 assert_eq!(buffer, buffer2);
623 }
624
625 #[test]
626 fn into_raw() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100627 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargob69c6ef2023-10-05 22:54:51 +0000628 1024,
629 512,
630 1,
631 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
632 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100633 0,
634 ))
Jim Shargob69c6ef2023-10-05 22:54:51 +0000635 .expect("Buffer with some basic parameters was not created successfully");
636 let buffer2 = buffer.clone();
637
638 let raw_buffer = buffer.into_raw();
639 // SAFETY: This is the same pointer we had before.
640 let remade_buffer = unsafe { HardwareBuffer::from_raw(raw_buffer) };
641
642 assert_eq!(remade_buffer, buffer2);
643 }
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100644
645 #[test]
646 fn native_handle_and_back() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100647 let buffer_description = HardwareBufferDescription::new(
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100648 1024,
649 512,
650 1,
651 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
652 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100653 1024,
654 );
655 let buffer = HardwareBuffer::new(&buffer_description)
656 .expect("Buffer with some basic parameters was not created successfully");
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100657
658 let native_handle =
659 buffer.cloned_native_handle().expect("Failed to get native handle for buffer");
Andrew Walbranabc932e2024-08-30 14:10:29 +0100660 let buffer2 = HardwareBuffer::create_from_handle(&native_handle, &buffer_description)
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100661 .expect("Failed to create buffer from native handle");
662
Andrew Walbranabc932e2024-08-30 14:10:29 +0100663 assert_eq!(buffer.description(), buffer_description);
664 assert_eq!(buffer2.description(), buffer_description);
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100665 }
Andrew Walbrane0361622024-10-23 18:49:27 +0100666
667 #[test]
668 fn lock() {
669 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
670 1024,
671 512,
672 1,
673 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
674 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
675 0,
676 ))
677 .expect("Failed to create buffer");
678
679 // SAFETY: No other threads or processes have access to the buffer.
680 let guard = unsafe {
681 buffer.lock(
682 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
683 None,
684 None,
685 )
686 }
687 .unwrap();
688
689 drop(guard);
690 }
691
692 #[test]
693 fn lock_with_rect() {
694 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
695 1024,
696 512,
697 1,
698 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
699 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
700 0,
701 ))
702 .expect("Failed to create buffer");
703 let rect = ARect { left: 10, right: 20, top: 35, bottom: 45 };
704
705 // SAFETY: No other threads or processes have access to the buffer.
706 let guard = unsafe {
707 buffer.lock(
708 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
709 None,
710 Some(&rect),
711 )
712 }
713 .unwrap();
714
715 drop(guard);
716 }
717
718 #[test]
719 fn unlock_with_fence() {
720 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
721 1024,
722 512,
723 1,
724 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
725 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
726 0,
727 ))
728 .expect("Failed to create buffer");
729
730 // SAFETY: No other threads or processes have access to the buffer.
731 let guard = unsafe {
732 buffer.lock(
733 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
734 None,
735 None,
736 )
737 }
738 .unwrap();
739
740 buffer.unlock_with_fence(guard).unwrap();
741 }
742
743 #[test]
744 fn lock_with_info() {
745 const WIDTH: u32 = 1024;
746 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
747 WIDTH,
748 512,
749 1,
750 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
751 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
752 0,
753 ))
754 .expect("Failed to create buffer");
755
756 // SAFETY: No other threads or processes have access to the buffer.
757 let info = unsafe {
758 buffer.lock_and_get_info(
759 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
760 None,
761 None,
762 )
763 }
764 .unwrap();
765
766 assert_eq!(info.bytes_per_pixel, 4);
767 assert_eq!(info.stride, WIDTH * 4);
768 drop(info);
769 }
Jim Shargo7df9f752023-07-18 20:33:45 +0000770}