blob: e41651737ff71e3c8dd329b6acdea79fc6f5bfb9 [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 Walbran43bddb62023-09-01 16:43:09 +010019pub use ffi::{AHardwareBuffer_Format, AHardwareBuffer_UsageFlags};
Jim Shargo7df9f752023-07-18 20:33:45 +000020
Andrew Walbran43bddb62023-09-01 16:43:09 +010021use binder::{
Andrew Walbrane9573af2024-01-11 16:34:16 +000022 binder_impl::{BorrowedParcel, UnstructuredParcelable},
23 impl_deserialize_for_unstructured_parcelable, impl_serialize_for_unstructured_parcelable,
Andrew Walbran43bddb62023-09-01 16:43:09 +010024 unstable_api::{status_result, AsNative},
25 StatusCode,
26};
27use ffi::{AHardwareBuffer, AHardwareBuffer_readFromParcel, AHardwareBuffer_writeToParcel};
Jim Shargob69c6ef2023-10-05 22:54:51 +000028use std::fmt::{self, Debug, Formatter};
29use std::mem::ManuallyDrop;
Andrew Walbran43bddb62023-09-01 16:43:09 +010030use std::ptr::{self, null_mut, NonNull};
Jim Shargo7df9f752023-07-18 20:33:45 +000031
Andrew Walbran43bddb62023-09-01 16:43:09 +010032/// Wrapper around an opaque C `AHardwareBuffer`.
Jim Shargob69c6ef2023-10-05 22:54:51 +000033#[derive(PartialEq, Eq)]
34pub struct HardwareBuffer(NonNull<AHardwareBuffer>);
Jim Shargo7df9f752023-07-18 20:33:45 +000035
Jim Shargob69c6ef2023-10-05 22:54:51 +000036impl HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +000037 /// Test whether the given format and usage flag combination is allocatable. If this function
38 /// returns true, it means that a buffer with the given description can be allocated on this
39 /// implementation, unless resource exhaustion occurs. If this function returns false, it means
40 /// that the allocation of the given description will never succeed.
41 ///
42 /// Available since API 29
43 pub fn is_supported(
44 width: u32,
45 height: u32,
46 layers: u32,
47 format: AHardwareBuffer_Format::Type,
48 usage: AHardwareBuffer_UsageFlags,
49 stride: u32,
50 ) -> bool {
51 let buffer_desc = ffi::AHardwareBuffer_Desc {
52 width,
53 height,
54 layers,
55 format,
56 usage: usage.0,
57 stride,
58 rfu0: 0,
59 rfu1: 0,
60 };
61 // SAFETY: *buffer_desc will never be null.
62 let status = unsafe { ffi::AHardwareBuffer_isSupported(&buffer_desc) };
63
64 status == 1
65 }
66
67 /// Allocates a buffer that matches the passed AHardwareBuffer_Desc. If allocation succeeds, the
68 /// buffer can be used according to the usage flags specified in its description. If a buffer is
69 /// used in ways not compatible with its usage flags, the results are undefined and may include
70 /// program termination.
71 ///
72 /// Available since API level 26.
Jim Shargoe4680d72023-08-07 16:46:45 +000073 #[inline]
Jim Shargo7df9f752023-07-18 20:33:45 +000074 pub fn new(
75 width: u32,
76 height: u32,
77 layers: u32,
78 format: AHardwareBuffer_Format::Type,
79 usage: AHardwareBuffer_UsageFlags,
80 ) -> Option<Self> {
81 let buffer_desc = ffi::AHardwareBuffer_Desc {
82 width,
83 height,
84 layers,
85 format,
86 usage: usage.0,
87 stride: 0,
88 rfu0: 0,
89 rfu1: 0,
90 };
Jim Shargob69c6ef2023-10-05 22:54:51 +000091 let mut ptr = ptr::null_mut();
Jim Shargo7df9f752023-07-18 20:33:45 +000092 // SAFETY: The returned pointer is valid until we drop/deallocate it. The function may fail
93 // and return a status, but we check it later.
Jim Shargob69c6ef2023-10-05 22:54:51 +000094 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_desc, &mut ptr) };
Jim Shargo7df9f752023-07-18 20:33:45 +000095
96 if status == 0 {
Jim Shargob69c6ef2023-10-05 22:54:51 +000097 Some(Self(NonNull::new(ptr).expect("Allocated AHardwareBuffer was null")))
Jim Shargo7df9f752023-07-18 20:33:45 +000098 } else {
99 None
100 }
101 }
102
103 /// Adopts the raw pointer and wraps it in a Rust AHardwareBuffer.
104 ///
105 /// # Errors
106 ///
107 /// Will panic if buffer_ptr is null.
108 ///
109 /// # Safety
110 ///
111 /// This function adopts the pointer but does NOT increment the refcount on the buffer. If the
112 /// caller uses the pointer after the created object is dropped it will cause a memory leak.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000113 pub unsafe fn from_raw(buffer_ptr: NonNull<AHardwareBuffer>) -> Self {
114 Self(buffer_ptr)
115 }
116
117 /// Get the internal |AHardwareBuffer| pointer without decrementing the refcount. This can
118 /// be used to provide a pointer to the AHB for a C/C++ API over the FFI.
119 pub fn into_raw(self) -> NonNull<AHardwareBuffer> {
120 let buffer = ManuallyDrop::new(self);
121 buffer.0
Jim Shargo7df9f752023-07-18 20:33:45 +0000122 }
123
124 /// Get the system wide unique id for an AHardwareBuffer. This function may panic in extreme
125 /// and undocumented circumstances.
126 ///
127 /// Available since API level 31.
128 pub fn id(&self) -> u64 {
129 let mut out_id = 0;
Andrew Walbran43bddb62023-09-01 16:43:09 +0100130 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
131 // because it must have been allocated by `AHardwareBuffer_allocate`,
132 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
133 // released it. The id pointer must be valid because it comes from a reference.
134 let status = unsafe { ffi::AHardwareBuffer_getId(self.0.as_ptr(), &mut out_id) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000135 assert_eq!(status, 0, "id() failed for AHardwareBuffer with error code: {status}");
136
137 out_id
138 }
139
140 /// Get the width of this buffer
141 pub fn width(&self) -> u32 {
142 self.description().width
143 }
144
145 /// Get the height of this buffer
146 pub fn height(&self) -> u32 {
147 self.description().height
148 }
149
150 /// Get the number of layers of this buffer
151 pub fn layers(&self) -> u32 {
152 self.description().layers
153 }
154
155 /// Get the format of this buffer
156 pub fn format(&self) -> AHardwareBuffer_Format::Type {
157 self.description().format
158 }
159
160 /// Get the usage bitvector of this buffer
161 pub fn usage(&self) -> AHardwareBuffer_UsageFlags {
162 AHardwareBuffer_UsageFlags(self.description().usage)
163 }
164
165 /// Get the stride of this buffer
166 pub fn stride(&self) -> u32 {
167 self.description().stride
168 }
169
170 fn description(&self) -> ffi::AHardwareBuffer_Desc {
171 let mut buffer_desc = ffi::AHardwareBuffer_Desc {
172 width: 0,
173 height: 0,
174 layers: 0,
175 format: 0,
176 usage: 0,
177 stride: 0,
178 rfu0: 0,
179 rfu1: 0,
180 };
181 // SAFETY: neither the buffer nor AHardwareBuffer_Desc pointers will be null.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000182 unsafe { ffi::AHardwareBuffer_describe(self.0.as_ref(), &mut buffer_desc) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000183 buffer_desc
184 }
185}
186
Jim Shargob69c6ef2023-10-05 22:54:51 +0000187impl Drop for HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +0000188 fn drop(&mut self) {
Andrew Walbran43bddb62023-09-01 16:43:09 +0100189 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
190 // because it must have been allocated by `AHardwareBuffer_allocate`,
191 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
192 // released it.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000193 unsafe { ffi::AHardwareBuffer_release(self.0.as_ptr()) }
Jim Shargo7df9f752023-07-18 20:33:45 +0000194 }
195}
196
Jim Shargob69c6ef2023-10-05 22:54:51 +0000197impl Debug for HardwareBuffer {
198 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
199 f.debug_struct("HardwareBuffer").field("id", &self.id()).finish()
200 }
201}
202
203impl Clone for HardwareBuffer {
204 fn clone(&self) -> Self {
205 // SAFETY: ptr is guaranteed to be non-null and the acquire can not fail.
206 unsafe { ffi::AHardwareBuffer_acquire(self.0.as_ptr()) };
207 Self(self.0)
208 }
209}
210
Andrew Walbrane9573af2024-01-11 16:34:16 +0000211impl UnstructuredParcelable for HardwareBuffer {
212 fn write_to_parcel(&self, parcel: &mut BorrowedParcel) -> Result<(), StatusCode> {
213 let status =
214 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
215 // because it must have been allocated by `AHardwareBuffer_allocate`,
216 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
217 // released it.
218 unsafe { AHardwareBuffer_writeToParcel(self.0.as_ptr(), parcel.as_native_mut()) };
219 status_result(status)
220 }
221
222 fn from_parcel(parcel: &BorrowedParcel) -> Result<Self, StatusCode> {
223 let mut buffer = null_mut();
224
225 let status =
226 // SAFETY: Both pointers must be valid because they are obtained from references.
227 // `AHardwareBuffer_readFromParcel` doesn't store them or do anything else special
228 // with them. If it returns success then it will have allocated a new
229 // `AHardwareBuffer` and incremented the reference count, so we can use it until we
230 // release it.
231 unsafe { AHardwareBuffer_readFromParcel(parcel.as_native(), &mut buffer) };
232
233 status_result(status)?;
234
235 Ok(Self(
236 NonNull::new(buffer).expect(
237 "AHardwareBuffer_readFromParcel returned success but didn't allocate buffer",
238 ),
239 ))
Andrew Walbran43bddb62023-09-01 16:43:09 +0100240 }
241}
242
Andrew Walbrane9573af2024-01-11 16:34:16 +0000243impl_deserialize_for_unstructured_parcelable!(HardwareBuffer);
244impl_serialize_for_unstructured_parcelable!(HardwareBuffer);
Andrew Walbran43bddb62023-09-01 16:43:09 +0100245
Jim Shargob69c6ef2023-10-05 22:54:51 +0000246// SAFETY: The underlying *AHardwareBuffers can be moved between threads.
247unsafe impl Send for HardwareBuffer {}
248
249// SAFETY: The underlying *AHardwareBuffers can be used from multiple threads.
250//
251// AHardwareBuffers are backed by C++ GraphicBuffers, which are mostly immutable. The only cases
252// where they are not immutable are:
253//
254// - reallocation (which is never actually done across the codebase and requires special
255// privileges/platform code access to do)
256// - "locking" for reading/writing (which is explicitly allowed to be done across multiple threads
257// according to the docs on the underlying gralloc calls)
258unsafe impl Sync for HardwareBuffer {}
259
Jim Shargo7df9f752023-07-18 20:33:45 +0000260#[cfg(test)]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000261mod test {
Jim Shargo7df9f752023-07-18 20:33:45 +0000262 use super::*;
263
264 #[test]
265 fn create_valid_buffer_returns_ok() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000266 let buffer = HardwareBuffer::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000267 512,
268 512,
269 1,
270 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
271 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
272 );
273 assert!(buffer.is_some());
274 }
275
276 #[test]
277 fn create_invalid_buffer_returns_err() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000278 let buffer = HardwareBuffer::new(512, 512, 1, 0, AHardwareBuffer_UsageFlags(0));
Jim Shargo7df9f752023-07-18 20:33:45 +0000279 assert!(buffer.is_none());
280 }
281
282 #[test]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000283 fn from_raw_allows_getters() {
Jim Shargo7df9f752023-07-18 20:33:45 +0000284 let buffer_desc = ffi::AHardwareBuffer_Desc {
285 width: 1024,
286 height: 512,
287 layers: 1,
288 format: AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
289 usage: AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN.0,
290 stride: 0,
291 rfu0: 0,
292 rfu1: 0,
293 };
294 let mut raw_buffer_ptr = ptr::null_mut();
295
Andrew Walbran03350bc2023-08-03 16:02:51 +0000296 // SAFETY: The pointers are valid because they come from references, and
297 // `AHardwareBuffer_allocate` doesn't retain them after it returns.
Jim Shargo7df9f752023-07-18 20:33:45 +0000298 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_desc, &mut raw_buffer_ptr) };
299 assert_eq!(status, 0);
300
Andrew Walbran03350bc2023-08-03 16:02:51 +0000301 // SAFETY: The pointer must be valid because it was just allocated successfully, and we
302 // don't use it after calling this.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000303 let buffer = unsafe { HardwareBuffer::from_raw(NonNull::new(raw_buffer_ptr).unwrap()) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000304 assert_eq!(buffer.width(), 1024);
305 }
306
307 #[test]
308 fn basic_getters() {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000309 let buffer = HardwareBuffer::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000310 1024,
311 512,
312 1,
313 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
314 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
315 )
316 .expect("Buffer with some basic parameters was not created successfully");
317
318 assert_eq!(buffer.width(), 1024);
319 assert_eq!(buffer.height(), 512);
320 assert_eq!(buffer.layers(), 1);
321 assert_eq!(buffer.format(), AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM);
322 assert_eq!(
323 buffer.usage(),
324 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN
325 );
326 }
327
328 #[test]
329 fn id_getter() {
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_ne!(0, buffer.id());
340 }
Jim Shargob69c6ef2023-10-05 22:54:51 +0000341
342 #[test]
343 fn clone() {
344 let buffer = HardwareBuffer::new(
345 1024,
346 512,
347 1,
348 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
349 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
350 )
351 .expect("Buffer with some basic parameters was not created successfully");
352 let buffer2 = buffer.clone();
353
354 assert_eq!(buffer, buffer2);
355 }
356
357 #[test]
358 fn into_raw() {
359 let buffer = HardwareBuffer::new(
360 1024,
361 512,
362 1,
363 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
364 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
365 )
366 .expect("Buffer with some basic parameters was not created successfully");
367 let buffer2 = buffer.clone();
368
369 let raw_buffer = buffer.into_raw();
370 // SAFETY: This is the same pointer we had before.
371 let remade_buffer = unsafe { HardwareBuffer::from_raw(raw_buffer) };
372
373 assert_eq!(remade_buffer, buffer2);
374 }
Jim Shargo7df9f752023-07-18 20:33:45 +0000375}