blob: ffde137ccbf4fa7919ff9a94807a489f67daea59 [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
22pub use handle::NativeHandle;
Jiyong Park8032bff2024-04-01 16:17:15 +090023pub use surface::Surface;
Andrew Walbran8ee0ef12024-01-12 15:56:14 +000024
Andrew Walbran43bddb62023-09-01 16:43:09 +010025pub use ffi::{AHardwareBuffer_Format, AHardwareBuffer_UsageFlags};
Jim Shargo7df9f752023-07-18 20:33:45 +000026
Andrew Walbran43bddb62023-09-01 16:43:09 +010027use binder::{
Andrew Walbrane9573af2024-01-11 16:34:16 +000028 binder_impl::{BorrowedParcel, UnstructuredParcelable},
29 impl_deserialize_for_unstructured_parcelable, impl_serialize_for_unstructured_parcelable,
Andrew Walbran43bddb62023-09-01 16:43:09 +010030 unstable_api::{status_result, AsNative},
31 StatusCode,
32};
33use ffi::{AHardwareBuffer, AHardwareBuffer_readFromParcel, AHardwareBuffer_writeToParcel};
Jim Shargob69c6ef2023-10-05 22:54:51 +000034use std::fmt::{self, Debug, Formatter};
35use std::mem::ManuallyDrop;
Andrew Walbran43bddb62023-09-01 16:43:09 +010036use std::ptr::{self, null_mut, NonNull};
Jim Shargo7df9f752023-07-18 20:33:45 +000037
Andrew Walbran43bddb62023-09-01 16:43:09 +010038/// Wrapper around an opaque C `AHardwareBuffer`.
Jim Shargob69c6ef2023-10-05 22:54:51 +000039#[derive(PartialEq, Eq)]
40pub struct HardwareBuffer(NonNull<AHardwareBuffer>);
Jim Shargo7df9f752023-07-18 20:33:45 +000041
Jim Shargob69c6ef2023-10-05 22:54:51 +000042impl HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +000043 /// Test whether the given format and usage flag combination is allocatable. If this function
44 /// returns true, it means that a buffer with the given description can be allocated on this
45 /// implementation, unless resource exhaustion occurs. If this function returns false, it means
46 /// that the allocation of the given description will never succeed.
47 ///
48 /// Available since API 29
49 pub fn is_supported(
50 width: u32,
51 height: u32,
52 layers: u32,
53 format: AHardwareBuffer_Format::Type,
54 usage: AHardwareBuffer_UsageFlags,
55 stride: u32,
56 ) -> bool {
57 let buffer_desc = ffi::AHardwareBuffer_Desc {
58 width,
59 height,
60 layers,
61 format,
62 usage: usage.0,
63 stride,
64 rfu0: 0,
65 rfu1: 0,
66 };
67 // SAFETY: *buffer_desc will never be null.
68 let status = unsafe { ffi::AHardwareBuffer_isSupported(&buffer_desc) };
69
70 status == 1
71 }
72
73 /// Allocates a buffer that matches the passed AHardwareBuffer_Desc. If allocation succeeds, the
74 /// buffer can be used according to the usage flags specified in its description. If a buffer is
75 /// used in ways not compatible with its usage flags, the results are undefined and may include
76 /// program termination.
77 ///
78 /// Available since API level 26.
Jim Shargoe4680d72023-08-07 16:46:45 +000079 #[inline]
Jim Shargo7df9f752023-07-18 20:33:45 +000080 pub fn new(
81 width: u32,
82 height: u32,
83 layers: u32,
84 format: AHardwareBuffer_Format::Type,
85 usage: AHardwareBuffer_UsageFlags,
86 ) -> Option<Self> {
87 let buffer_desc = ffi::AHardwareBuffer_Desc {
88 width,
89 height,
90 layers,
91 format,
92 usage: usage.0,
93 stride: 0,
94 rfu0: 0,
95 rfu1: 0,
96 };
Jim Shargob69c6ef2023-10-05 22:54:51 +000097 let mut ptr = ptr::null_mut();
Jim Shargo7df9f752023-07-18 20:33:45 +000098 // SAFETY: The returned pointer is valid until we drop/deallocate it. The function may fail
99 // and return a status, but we check it later.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000100 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_desc, &mut ptr) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000101
102 if status == 0 {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000103 Some(Self(NonNull::new(ptr).expect("Allocated AHardwareBuffer was null")))
Jim Shargo7df9f752023-07-18 20:33:45 +0000104 } else {
105 None
106 }
107 }
108
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000109 /// Adopts the given raw pointer and wraps it in a Rust HardwareBuffer.
Jim Shargo7df9f752023-07-18 20:33:45 +0000110 ///
111 /// # Safety
112 ///
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000113 /// This function takes ownership of the pointer and does NOT increment the refcount on the
114 /// buffer. If the caller uses the pointer after the created object is dropped it will cause
115 /// undefined behaviour. If the caller wants to continue using the pointer after calling this
116 /// then use [`clone_from_raw`](Self::clone_from_raw) instead.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000117 pub unsafe fn from_raw(buffer_ptr: NonNull<AHardwareBuffer>) -> Self {
118 Self(buffer_ptr)
119 }
120
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000121 /// Creates a new Rust HardwareBuffer to wrap the given AHardwareBuffer without taking ownership
122 /// of it.
123 ///
124 /// Unlike [`from_raw`](Self::from_raw) this method will increment the refcount on the buffer.
125 /// This means that the caller can continue to use the raw buffer it passed in, and must call
126 /// [`AHardwareBuffer_release`](ffi::AHardwareBuffer_release) when it is finished with it to
127 /// avoid a memory leak.
128 ///
129 /// # Safety
130 ///
131 /// The buffer pointer must point to a valid `AHardwareBuffer`.
132 pub unsafe fn clone_from_raw(buffer: NonNull<AHardwareBuffer>) -> Self {
133 // SAFETY: The caller guarantees that the AHardwareBuffer pointer is valid.
134 unsafe { ffi::AHardwareBuffer_acquire(buffer.as_ptr()) };
135 Self(buffer)
136 }
137
Jim Shargob69c6ef2023-10-05 22:54:51 +0000138 /// Get the internal |AHardwareBuffer| pointer without decrementing the refcount. This can
139 /// be used to provide a pointer to the AHB for a C/C++ API over the FFI.
140 pub fn into_raw(self) -> NonNull<AHardwareBuffer> {
141 let buffer = ManuallyDrop::new(self);
142 buffer.0
Jim Shargo7df9f752023-07-18 20:33:45 +0000143 }
144
145 /// Get the system wide unique id for an AHardwareBuffer. This function may panic in extreme
146 /// and undocumented circumstances.
147 ///
148 /// Available since API level 31.
149 pub fn id(&self) -> u64 {
150 let mut out_id = 0;
Andrew Walbran43bddb62023-09-01 16:43:09 +0100151 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
152 // because it must have been allocated by `AHardwareBuffer_allocate`,
153 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
154 // released it. The id pointer must be valid because it comes from a reference.
155 let status = unsafe { ffi::AHardwareBuffer_getId(self.0.as_ptr(), &mut out_id) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000156 assert_eq!(status, 0, "id() failed for AHardwareBuffer with error code: {status}");
157
158 out_id
159 }
160
161 /// Get the width of this buffer
162 pub fn width(&self) -> u32 {
163 self.description().width
164 }
165
166 /// Get the height of this buffer
167 pub fn height(&self) -> u32 {
168 self.description().height
169 }
170
171 /// Get the number of layers of this buffer
172 pub fn layers(&self) -> u32 {
173 self.description().layers
174 }
175
176 /// Get the format of this buffer
177 pub fn format(&self) -> AHardwareBuffer_Format::Type {
178 self.description().format
179 }
180
181 /// Get the usage bitvector of this buffer
182 pub fn usage(&self) -> AHardwareBuffer_UsageFlags {
183 AHardwareBuffer_UsageFlags(self.description().usage)
184 }
185
186 /// Get the stride of this buffer
187 pub fn stride(&self) -> u32 {
188 self.description().stride
189 }
190
191 fn description(&self) -> ffi::AHardwareBuffer_Desc {
192 let mut buffer_desc = ffi::AHardwareBuffer_Desc {
193 width: 0,
194 height: 0,
195 layers: 0,
196 format: 0,
197 usage: 0,
198 stride: 0,
199 rfu0: 0,
200 rfu1: 0,
201 };
202 // SAFETY: neither the buffer nor AHardwareBuffer_Desc pointers will be null.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000203 unsafe { ffi::AHardwareBuffer_describe(self.0.as_ref(), &mut buffer_desc) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000204 buffer_desc
205 }
206}
207
Jim Shargob69c6ef2023-10-05 22:54:51 +0000208impl Drop for HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +0000209 fn drop(&mut self) {
Andrew Walbran43bddb62023-09-01 16:43:09 +0100210 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
211 // because it must have been allocated by `AHardwareBuffer_allocate`,
212 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
213 // released it.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000214 unsafe { ffi::AHardwareBuffer_release(self.0.as_ptr()) }
Jim Shargo7df9f752023-07-18 20:33:45 +0000215 }
216}
217
Jim Shargob69c6ef2023-10-05 22:54:51 +0000218impl Debug for HardwareBuffer {
Andrew Walbran8ee0ef12024-01-12 15:56:14 +0000219 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000220 f.debug_struct("HardwareBuffer").field("id", &self.id()).finish()
221 }
222}
223
224impl Clone for HardwareBuffer {
225 fn clone(&self) -> Self {
226 // SAFETY: ptr is guaranteed to be non-null and the acquire can not fail.
227 unsafe { ffi::AHardwareBuffer_acquire(self.0.as_ptr()) };
228 Self(self.0)
229 }
230}
231
Andrew Walbrane9573af2024-01-11 16:34:16 +0000232impl UnstructuredParcelable for HardwareBuffer {
233 fn write_to_parcel(&self, parcel: &mut BorrowedParcel) -> Result<(), StatusCode> {
234 let status =
235 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
236 // because it must have been allocated by `AHardwareBuffer_allocate`,
237 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
238 // released it.
239 unsafe { AHardwareBuffer_writeToParcel(self.0.as_ptr(), parcel.as_native_mut()) };
240 status_result(status)
241 }
242
243 fn from_parcel(parcel: &BorrowedParcel) -> Result<Self, StatusCode> {
244 let mut buffer = null_mut();
245
246 let status =
247 // SAFETY: Both pointers must be valid because they are obtained from references.
248 // `AHardwareBuffer_readFromParcel` doesn't store them or do anything else special
249 // with them. If it returns success then it will have allocated a new
250 // `AHardwareBuffer` and incremented the reference count, so we can use it until we
251 // release it.
252 unsafe { AHardwareBuffer_readFromParcel(parcel.as_native(), &mut buffer) };
253
254 status_result(status)?;
255
256 Ok(Self(
257 NonNull::new(buffer).expect(
258 "AHardwareBuffer_readFromParcel returned success but didn't allocate buffer",
259 ),
260 ))
Andrew Walbran43bddb62023-09-01 16:43:09 +0100261 }
262}
263
Andrew Walbrane9573af2024-01-11 16:34:16 +0000264impl_deserialize_for_unstructured_parcelable!(HardwareBuffer);
265impl_serialize_for_unstructured_parcelable!(HardwareBuffer);
Andrew Walbran43bddb62023-09-01 16:43:09 +0100266
Jim Shargob69c6ef2023-10-05 22:54:51 +0000267// SAFETY: The underlying *AHardwareBuffers can be moved between threads.
268unsafe impl Send for HardwareBuffer {}
269
270// SAFETY: The underlying *AHardwareBuffers can be used from multiple threads.
271//
272// AHardwareBuffers are backed by C++ GraphicBuffers, which are mostly immutable. The only cases
273// where they are not immutable are:
274//
275// - reallocation (which is never actually done across the codebase and requires special
276// privileges/platform code access to do)
277// - "locking" for reading/writing (which is explicitly allowed to be done across multiple threads
278// according to the docs on the underlying gralloc calls)
279unsafe impl Sync for HardwareBuffer {}
280
Jim Shargo7df9f752023-07-18 20:33:45 +0000281#[cfg(test)]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000282mod test {
Jim Shargo7df9f752023-07-18 20:33:45 +0000283 use super::*;
284
285 #[test]
286 fn create_valid_buffer_returns_ok() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000287 let buffer = HardwareBuffer::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000288 512,
289 512,
290 1,
291 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
292 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
293 );
294 assert!(buffer.is_some());
295 }
296
297 #[test]
298 fn create_invalid_buffer_returns_err() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000299 let buffer = HardwareBuffer::new(512, 512, 1, 0, AHardwareBuffer_UsageFlags(0));
Jim Shargo7df9f752023-07-18 20:33:45 +0000300 assert!(buffer.is_none());
301 }
302
303 #[test]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000304 fn from_raw_allows_getters() {
Jim Shargo7df9f752023-07-18 20:33:45 +0000305 let buffer_desc = ffi::AHardwareBuffer_Desc {
306 width: 1024,
307 height: 512,
308 layers: 1,
309 format: AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
310 usage: AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN.0,
311 stride: 0,
312 rfu0: 0,
313 rfu1: 0,
314 };
315 let mut raw_buffer_ptr = ptr::null_mut();
316
Andrew Walbran03350bc2023-08-03 16:02:51 +0000317 // SAFETY: The pointers are valid because they come from references, and
318 // `AHardwareBuffer_allocate` doesn't retain them after it returns.
Jim Shargo7df9f752023-07-18 20:33:45 +0000319 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_desc, &mut raw_buffer_ptr) };
320 assert_eq!(status, 0);
321
Andrew Walbran03350bc2023-08-03 16:02:51 +0000322 // SAFETY: The pointer must be valid because it was just allocated successfully, and we
323 // don't use it after calling this.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000324 let buffer = unsafe { HardwareBuffer::from_raw(NonNull::new(raw_buffer_ptr).unwrap()) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000325 assert_eq!(buffer.width(), 1024);
326 }
327
328 #[test]
329 fn basic_getters() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000330 let buffer = HardwareBuffer::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000331 1024,
332 512,
333 1,
334 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
335 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
336 )
337 .expect("Buffer with some basic parameters was not created successfully");
338
339 assert_eq!(buffer.width(), 1024);
340 assert_eq!(buffer.height(), 512);
341 assert_eq!(buffer.layers(), 1);
342 assert_eq!(buffer.format(), AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM);
343 assert_eq!(
344 buffer.usage(),
345 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN
346 );
347 }
348
349 #[test]
350 fn id_getter() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000351 let buffer = HardwareBuffer::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000352 1024,
353 512,
354 1,
355 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
356 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
357 )
358 .expect("Buffer with some basic parameters was not created successfully");
359
360 assert_ne!(0, buffer.id());
361 }
Jim Shargob69c6ef2023-10-05 22:54:51 +0000362
363 #[test]
364 fn clone() {
365 let buffer = HardwareBuffer::new(
366 1024,
367 512,
368 1,
369 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
370 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
371 )
372 .expect("Buffer with some basic parameters was not created successfully");
373 let buffer2 = buffer.clone();
374
375 assert_eq!(buffer, buffer2);
376 }
377
378 #[test]
379 fn into_raw() {
380 let buffer = HardwareBuffer::new(
381 1024,
382 512,
383 1,
384 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
385 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
386 )
387 .expect("Buffer with some basic parameters was not created successfully");
388 let buffer2 = buffer.clone();
389
390 let raw_buffer = buffer.into_raw();
391 // SAFETY: This is the same pointer we had before.
392 let remade_buffer = unsafe { HardwareBuffer::from_raw(raw_buffer) };
393
394 assert_eq!(remade_buffer, buffer2);
395 }
Jim Shargo7df9f752023-07-18 20:33:45 +0000396}