blob: a1d986ed2b468caaf0c5bf48ddd0ce2e96a47bc1 [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,
34 AHardwareBuffer_writeToParcel,
35};
Jim Shargob69c6ef2023-10-05 22:54:51 +000036use std::fmt::{self, Debug, Formatter};
37use std::mem::ManuallyDrop;
Andrew Walbran43bddb62023-09-01 16:43:09 +010038use std::ptr::{self, null_mut, NonNull};
Jim Shargo7df9f752023-07-18 20:33:45 +000039
Andrew Walbranabc932e2024-08-30 14:10:29 +010040/// Wrapper around a C `AHardwareBuffer_Desc`.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct HardwareBufferDescription(AHardwareBuffer_Desc);
43
44impl HardwareBufferDescription {
45 /// Creates a new `HardwareBufferDescription` with the given parameters.
46 pub fn new(
47 width: u32,
48 height: u32,
49 layers: u32,
50 format: AHardwareBuffer_Format::Type,
51 usage: AHardwareBuffer_UsageFlags,
52 stride: u32,
53 ) -> Self {
54 Self(AHardwareBuffer_Desc {
55 width,
56 height,
57 layers,
58 format,
59 usage: usage.0,
60 stride,
61 rfu0: 0,
62 rfu1: 0,
63 })
64 }
65
66 /// Returns the width from the buffer description.
67 pub fn width(&self) -> u32 {
68 self.0.width
69 }
70
71 /// Returns the height from the buffer description.
72 pub fn height(&self) -> u32 {
73 self.0.height
74 }
75
76 /// Returns the number from layers from the buffer description.
77 pub fn layers(&self) -> u32 {
78 self.0.layers
79 }
80
81 /// Returns the format from the buffer description.
82 pub fn format(&self) -> AHardwareBuffer_Format::Type {
83 self.0.format
84 }
85
86 /// Returns the usage bitvector from the buffer description.
87 pub fn usage(&self) -> AHardwareBuffer_UsageFlags {
88 AHardwareBuffer_UsageFlags(self.0.usage)
89 }
90
91 /// Returns the stride from the buffer description.
92 pub fn stride(&self) -> u32 {
93 self.0.stride
94 }
95}
96
97impl Default for HardwareBufferDescription {
98 fn default() -> Self {
99 Self(AHardwareBuffer_Desc {
100 width: 0,
101 height: 0,
102 layers: 0,
103 format: 0,
104 usage: 0,
105 stride: 0,
106 rfu0: 0,
107 rfu1: 0,
108 })
109 }
110}
111
Andrew Walbran43bddb62023-09-01 16:43:09 +0100112/// Wrapper around an opaque C `AHardwareBuffer`.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000113#[derive(PartialEq, Eq)]
114pub struct HardwareBuffer(NonNull<AHardwareBuffer>);
Jim Shargo7df9f752023-07-18 20:33:45 +0000115
Jim Shargob69c6ef2023-10-05 22:54:51 +0000116impl HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +0000117 /// Test whether the given format and usage flag combination is allocatable. If this function
118 /// returns true, it means that a buffer with the given description can be allocated on this
119 /// implementation, unless resource exhaustion occurs. If this function returns false, it means
120 /// that the allocation of the given description will never succeed.
121 ///
122 /// Available since API 29
Andrew Walbranabc932e2024-08-30 14:10:29 +0100123 pub fn is_supported(buffer_description: &HardwareBufferDescription) -> bool {
124 // SAFETY: The pointer comes from a reference so must be valid.
125 let status = unsafe { ffi::AHardwareBuffer_isSupported(&buffer_description.0) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000126
127 status == 1
128 }
129
130 /// Allocates a buffer that matches the passed AHardwareBuffer_Desc. If allocation succeeds, the
131 /// buffer can be used according to the usage flags specified in its description. If a buffer is
132 /// used in ways not compatible with its usage flags, the results are undefined and may include
133 /// program termination.
134 ///
135 /// Available since API level 26.
Jim Shargoe4680d72023-08-07 16:46:45 +0000136 #[inline]
Andrew Walbranabc932e2024-08-30 14:10:29 +0100137 pub fn new(buffer_description: &HardwareBufferDescription) -> Option<Self> {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000138 let mut ptr = ptr::null_mut();
Jim Shargo7df9f752023-07-18 20:33:45 +0000139 // SAFETY: The returned pointer is valid until we drop/deallocate it. The function may fail
140 // and return a status, but we check it later.
Andrew Walbranabc932e2024-08-30 14:10:29 +0100141 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_description.0, &mut ptr) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000142
143 if status == 0 {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000144 Some(Self(NonNull::new(ptr).expect("Allocated AHardwareBuffer was null")))
Jim Shargo7df9f752023-07-18 20:33:45 +0000145 } else {
146 None
147 }
148 }
149
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100150 /// Creates a `HardwareBuffer` from a native handle.
151 ///
152 /// The native handle is cloned, so this doesn't take ownership of the original handle passed
153 /// in.
154 pub fn create_from_handle(
155 handle: &NativeHandle,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100156 buffer_description: &HardwareBufferDescription,
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100157 ) -> Result<Self, StatusCode> {
158 let mut buffer = ptr::null_mut();
159 // SAFETY: The caller guarantees that `handle` is valid, and the buffer pointer is valid
160 // because it comes from a reference. The method we pass means that
161 // `AHardwareBuffer_createFromHandle` will clone the handle rather than taking ownership of
162 // it.
163 let status = unsafe {
164 ffi::AHardwareBuffer_createFromHandle(
Andrew Walbranabc932e2024-08-30 14:10:29 +0100165 &buffer_description.0,
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100166 handle.as_raw().as_ptr(),
167 ffi::CreateFromHandleMethod_AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE
168 .try_into()
169 .unwrap(),
170 &mut buffer,
171 )
172 };
173 status_result(status)?;
174 Ok(Self(NonNull::new(buffer).expect("Allocated AHardwareBuffer was null")))
175 }
176
177 /// Returns a clone of the native handle of the buffer.
178 ///
179 /// Returns `None` if the operation fails for any reason.
180 pub fn cloned_native_handle(&self) -> Option<NativeHandle> {
181 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
182 // because it must have been allocated by `AHardwareBuffer_allocate`,
183 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
184 // released it.
185 let native_handle = unsafe { ffi::AHardwareBuffer_getNativeHandle(self.0.as_ptr()) };
186 NonNull::new(native_handle.cast_mut()).and_then(|native_handle| {
187 // SAFETY: `AHardwareBuffer_getNativeHandle` should have returned a valid pointer which
188 // is valid at least as long as the buffer is, and `clone_from_raw` clones it rather
189 // than taking ownership of it so the original `native_handle` isn't stored.
190 unsafe { NativeHandle::clone_from_raw(native_handle) }
191 })
192 }
193
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000194 /// Adopts the given raw pointer and wraps it in a Rust HardwareBuffer.
Jim Shargo7df9f752023-07-18 20:33:45 +0000195 ///
196 /// # Safety
197 ///
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000198 /// This function takes ownership of the pointer and does NOT increment the refcount on the
199 /// buffer. If the caller uses the pointer after the created object is dropped it will cause
200 /// undefined behaviour. If the caller wants to continue using the pointer after calling this
201 /// then use [`clone_from_raw`](Self::clone_from_raw) instead.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000202 pub unsafe fn from_raw(buffer_ptr: NonNull<AHardwareBuffer>) -> Self {
203 Self(buffer_ptr)
204 }
205
Andrew Walbrana0b3a9d2024-01-12 16:43:12 +0000206 /// Creates a new Rust HardwareBuffer to wrap the given AHardwareBuffer without taking ownership
207 /// of it.
208 ///
209 /// Unlike [`from_raw`](Self::from_raw) this method will increment the refcount on the buffer.
210 /// This means that the caller can continue to use the raw buffer it passed in, and must call
211 /// [`AHardwareBuffer_release`](ffi::AHardwareBuffer_release) when it is finished with it to
212 /// avoid a memory leak.
213 ///
214 /// # Safety
215 ///
216 /// The buffer pointer must point to a valid `AHardwareBuffer`.
217 pub unsafe fn clone_from_raw(buffer: NonNull<AHardwareBuffer>) -> Self {
218 // SAFETY: The caller guarantees that the AHardwareBuffer pointer is valid.
219 unsafe { ffi::AHardwareBuffer_acquire(buffer.as_ptr()) };
220 Self(buffer)
221 }
222
Ren-Pei Zeng8237ba62024-10-22 15:20:18 +0000223 /// Get the internal `AHardwareBuffer` pointer that is only valid when this `HardwareBuffer`
224 /// exists. This can be used to provide a pointer to the AHB for a C/C++ API over the FFI.
225 pub fn as_raw(&self) -> NonNull<AHardwareBuffer> {
226 self.0
227 }
228
229 /// Get the internal `AHardwareBuffer` pointer without decrementing the refcount. This can
Jim Shargob69c6ef2023-10-05 22:54:51 +0000230 /// be used to provide a pointer to the AHB for a C/C++ API over the FFI.
231 pub fn into_raw(self) -> NonNull<AHardwareBuffer> {
232 let buffer = ManuallyDrop::new(self);
233 buffer.0
Jim Shargo7df9f752023-07-18 20:33:45 +0000234 }
235
236 /// Get the system wide unique id for an AHardwareBuffer. This function may panic in extreme
237 /// and undocumented circumstances.
238 ///
239 /// Available since API level 31.
240 pub fn id(&self) -> u64 {
241 let mut out_id = 0;
Andrew Walbran43bddb62023-09-01 16:43:09 +0100242 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
243 // because it must have been allocated by `AHardwareBuffer_allocate`,
244 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
245 // released it. The id pointer must be valid because it comes from a reference.
246 let status = unsafe { ffi::AHardwareBuffer_getId(self.0.as_ptr(), &mut out_id) };
Jim Shargo7df9f752023-07-18 20:33:45 +0000247 assert_eq!(status, 0, "id() failed for AHardwareBuffer with error code: {status}");
248
249 out_id
250 }
251
Andrew Walbranabc932e2024-08-30 14:10:29 +0100252 /// Returns the description of this buffer.
253 pub fn description(&self) -> HardwareBufferDescription {
Jim Shargo7df9f752023-07-18 20:33:45 +0000254 let mut buffer_desc = ffi::AHardwareBuffer_Desc {
255 width: 0,
256 height: 0,
257 layers: 0,
258 format: 0,
259 usage: 0,
260 stride: 0,
261 rfu0: 0,
262 rfu1: 0,
263 };
264 // SAFETY: neither the buffer nor AHardwareBuffer_Desc pointers will be null.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000265 unsafe { ffi::AHardwareBuffer_describe(self.0.as_ref(), &mut buffer_desc) };
Andrew Walbranabc932e2024-08-30 14:10:29 +0100266 HardwareBufferDescription(buffer_desc)
Jim Shargo7df9f752023-07-18 20:33:45 +0000267 }
268}
269
Jim Shargob69c6ef2023-10-05 22:54:51 +0000270impl Drop for HardwareBuffer {
Jim Shargo7df9f752023-07-18 20:33:45 +0000271 fn drop(&mut self) {
Andrew Walbran43bddb62023-09-01 16:43:09 +0100272 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
273 // because it must have been allocated by `AHardwareBuffer_allocate`,
274 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
275 // released it.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000276 unsafe { ffi::AHardwareBuffer_release(self.0.as_ptr()) }
Jim Shargo7df9f752023-07-18 20:33:45 +0000277 }
278}
279
Jim Shargob69c6ef2023-10-05 22:54:51 +0000280impl Debug for HardwareBuffer {
Andrew Walbran8ee0ef12024-01-12 15:56:14 +0000281 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Jim Shargob69c6ef2023-10-05 22:54:51 +0000282 f.debug_struct("HardwareBuffer").field("id", &self.id()).finish()
283 }
284}
285
286impl Clone for HardwareBuffer {
287 fn clone(&self) -> Self {
288 // SAFETY: ptr is guaranteed to be non-null and the acquire can not fail.
289 unsafe { ffi::AHardwareBuffer_acquire(self.0.as_ptr()) };
290 Self(self.0)
291 }
292}
293
Andrew Walbrane9573af2024-01-11 16:34:16 +0000294impl UnstructuredParcelable for HardwareBuffer {
295 fn write_to_parcel(&self, parcel: &mut BorrowedParcel) -> Result<(), StatusCode> {
296 let status =
297 // SAFETY: The AHardwareBuffer pointer we pass is guaranteed to be non-null and valid
298 // because it must have been allocated by `AHardwareBuffer_allocate`,
299 // `AHardwareBuffer_readFromParcel` or the caller of `from_raw` and we have not yet
300 // released it.
301 unsafe { AHardwareBuffer_writeToParcel(self.0.as_ptr(), parcel.as_native_mut()) };
302 status_result(status)
303 }
304
305 fn from_parcel(parcel: &BorrowedParcel) -> Result<Self, StatusCode> {
306 let mut buffer = null_mut();
307
308 let status =
309 // SAFETY: Both pointers must be valid because they are obtained from references.
310 // `AHardwareBuffer_readFromParcel` doesn't store them or do anything else special
311 // with them. If it returns success then it will have allocated a new
312 // `AHardwareBuffer` and incremented the reference count, so we can use it until we
313 // release it.
314 unsafe { AHardwareBuffer_readFromParcel(parcel.as_native(), &mut buffer) };
315
316 status_result(status)?;
317
318 Ok(Self(
319 NonNull::new(buffer).expect(
320 "AHardwareBuffer_readFromParcel returned success but didn't allocate buffer",
321 ),
322 ))
Andrew Walbran43bddb62023-09-01 16:43:09 +0100323 }
324}
325
Andrew Walbrane9573af2024-01-11 16:34:16 +0000326impl_deserialize_for_unstructured_parcelable!(HardwareBuffer);
327impl_serialize_for_unstructured_parcelable!(HardwareBuffer);
Andrew Walbran43bddb62023-09-01 16:43:09 +0100328
Jim Shargob69c6ef2023-10-05 22:54:51 +0000329// SAFETY: The underlying *AHardwareBuffers can be moved between threads.
330unsafe impl Send for HardwareBuffer {}
331
332// SAFETY: The underlying *AHardwareBuffers can be used from multiple threads.
333//
334// AHardwareBuffers are backed by C++ GraphicBuffers, which are mostly immutable. The only cases
335// where they are not immutable are:
336//
337// - reallocation (which is never actually done across the codebase and requires special
338// privileges/platform code access to do)
339// - "locking" for reading/writing (which is explicitly allowed to be done across multiple threads
340// according to the docs on the underlying gralloc calls)
341unsafe impl Sync for HardwareBuffer {}
342
Jim Shargo7df9f752023-07-18 20:33:45 +0000343#[cfg(test)]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000344mod test {
Jim Shargo7df9f752023-07-18 20:33:45 +0000345 use super::*;
346
347 #[test]
348 fn create_valid_buffer_returns_ok() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100349 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000350 512,
351 512,
352 1,
353 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
354 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100355 0,
356 ));
Jim Shargo7df9f752023-07-18 20:33:45 +0000357 assert!(buffer.is_some());
358 }
359
360 #[test]
361 fn create_invalid_buffer_returns_err() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100362 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
363 512,
364 512,
365 1,
366 0,
367 AHardwareBuffer_UsageFlags(0),
368 0,
369 ));
Jim Shargo7df9f752023-07-18 20:33:45 +0000370 assert!(buffer.is_none());
371 }
372
373 #[test]
Jim Shargob69c6ef2023-10-05 22:54:51 +0000374 fn from_raw_allows_getters() {
Jim Shargo7df9f752023-07-18 20:33:45 +0000375 let buffer_desc = ffi::AHardwareBuffer_Desc {
376 width: 1024,
377 height: 512,
378 layers: 1,
379 format: AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
380 usage: AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN.0,
381 stride: 0,
382 rfu0: 0,
383 rfu1: 0,
384 };
385 let mut raw_buffer_ptr = ptr::null_mut();
386
Andrew Walbran03350bc2023-08-03 16:02:51 +0000387 // SAFETY: The pointers are valid because they come from references, and
388 // `AHardwareBuffer_allocate` doesn't retain them after it returns.
Jim Shargo7df9f752023-07-18 20:33:45 +0000389 let status = unsafe { ffi::AHardwareBuffer_allocate(&buffer_desc, &mut raw_buffer_ptr) };
390 assert_eq!(status, 0);
391
Andrew Walbran03350bc2023-08-03 16:02:51 +0000392 // SAFETY: The pointer must be valid because it was just allocated successfully, and we
393 // don't use it after calling this.
Jim Shargob69c6ef2023-10-05 22:54:51 +0000394 let buffer = unsafe { HardwareBuffer::from_raw(NonNull::new(raw_buffer_ptr).unwrap()) };
Andrew Walbranabc932e2024-08-30 14:10:29 +0100395 assert_eq!(buffer.description().width(), 1024);
Jim Shargo7df9f752023-07-18 20:33:45 +0000396 }
397
398 #[test]
399 fn basic_getters() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100400 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000401 1024,
402 512,
403 1,
404 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
405 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100406 0,
407 ))
Jim Shargo7df9f752023-07-18 20:33:45 +0000408 .expect("Buffer with some basic parameters was not created successfully");
409
Andrew Walbranabc932e2024-08-30 14:10:29 +0100410 let description = buffer.description();
411 assert_eq!(description.width(), 1024);
412 assert_eq!(description.height(), 512);
413 assert_eq!(description.layers(), 1);
Jim Shargo7df9f752023-07-18 20:33:45 +0000414 assert_eq!(
Andrew Walbranabc932e2024-08-30 14:10:29 +0100415 description.format(),
416 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM
417 );
418 assert_eq!(
419 description.usage(),
Jim Shargo7df9f752023-07-18 20:33:45 +0000420 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN
421 );
422 }
423
424 #[test]
425 fn id_getter() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100426 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargo7df9f752023-07-18 20:33:45 +0000427 1024,
428 512,
429 1,
430 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
431 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100432 0,
433 ))
Jim Shargo7df9f752023-07-18 20:33:45 +0000434 .expect("Buffer with some basic parameters was not created successfully");
435
436 assert_ne!(0, buffer.id());
437 }
Jim Shargob69c6ef2023-10-05 22:54:51 +0000438
439 #[test]
440 fn clone() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100441 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargob69c6ef2023-10-05 22:54:51 +0000442 1024,
443 512,
444 1,
445 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
446 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100447 0,
448 ))
Jim Shargob69c6ef2023-10-05 22:54:51 +0000449 .expect("Buffer with some basic parameters was not created successfully");
450 let buffer2 = buffer.clone();
451
452 assert_eq!(buffer, buffer2);
453 }
454
455 #[test]
456 fn into_raw() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100457 let buffer = HardwareBuffer::new(&HardwareBufferDescription::new(
Jim Shargob69c6ef2023-10-05 22:54:51 +0000458 1024,
459 512,
460 1,
461 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
462 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100463 0,
464 ))
Jim Shargob69c6ef2023-10-05 22:54:51 +0000465 .expect("Buffer with some basic parameters was not created successfully");
466 let buffer2 = buffer.clone();
467
468 let raw_buffer = buffer.into_raw();
469 // SAFETY: This is the same pointer we had before.
470 let remade_buffer = unsafe { HardwareBuffer::from_raw(raw_buffer) };
471
472 assert_eq!(remade_buffer, buffer2);
473 }
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100474
475 #[test]
476 fn native_handle_and_back() {
Andrew Walbranabc932e2024-08-30 14:10:29 +0100477 let buffer_description = HardwareBufferDescription::new(
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100478 1024,
479 512,
480 1,
481 AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
482 AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
Andrew Walbranabc932e2024-08-30 14:10:29 +0100483 1024,
484 );
485 let buffer = HardwareBuffer::new(&buffer_description)
486 .expect("Buffer with some basic parameters was not created successfully");
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100487
488 let native_handle =
489 buffer.cloned_native_handle().expect("Failed to get native handle for buffer");
Andrew Walbranabc932e2024-08-30 14:10:29 +0100490 let buffer2 = HardwareBuffer::create_from_handle(&native_handle, &buffer_description)
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100491 .expect("Failed to create buffer from native handle");
492
Andrew Walbranabc932e2024-08-30 14:10:29 +0100493 assert_eq!(buffer.description(), buffer_description);
494 assert_eq!(buffer2.description(), buffer_description);
Andrew Walbrana73d62c2024-08-20 17:20:56 +0100495 }
Jim Shargo7df9f752023-07-18 20:33:45 +0000496}