1 // 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 //! Wrapper around the HardwareBuffer 16 17 use nativewindow::*; 18 19 use super::{buffer_owner::NoBufferOwner, BufferOwner}; 20 21 /// A wrapper for a hardware buffer. 22 /// 23 /// This buffer may be associated with a buffer pool to which it will be returned to it when dropped. 24 pub struct Buffer { 25 buffer_owner: Box<dyn BufferOwner>, 26 hardware_buffer: HardwareBuffer, 27 } 28 29 impl Buffer { 30 /// Create new buffer with a custom [BufferOwner]. new(buffer_owner: Box<dyn BufferOwner>, hardware_buffer: HardwareBuffer) -> Self31 pub fn new(buffer_owner: Box<dyn BufferOwner>, hardware_buffer: HardwareBuffer) -> Self { 32 Self { buffer_owner, hardware_buffer } 33 } 34 35 /// Create a new buffer with no association to any buffer pool. new_unowned(hardware_buffer: HardwareBuffer) -> Self36 pub fn new_unowned(hardware_buffer: HardwareBuffer) -> Self { 37 Self { buffer_owner: Box::new(NoBufferOwner), hardware_buffer } 38 } 39 40 /// Get the id of the underlying buffer. id(&self) -> u6441 pub fn id(&self) -> u64 { 42 self.hardware_buffer.id() 43 } 44 45 /// Get a reference to the underlying hardware buffer. buffer(&self) -> &HardwareBuffer46 pub fn buffer(&self) -> &HardwareBuffer { 47 &self.hardware_buffer 48 } 49 } 50 51 impl Drop for Buffer { drop(&mut self)52 fn drop(&mut self) { 53 self.buffer_owner.on_return(self); 54 } 55 } 56 57 #[cfg(test)] 58 mod test { 59 use super::*; 60 61 use crate::StreamConfig; 62 63 const STREAM_CONFIG: StreamConfig = StreamConfig { 64 width: 1, 65 height: 1, 66 layers: 1, 67 format: AHardwareBuffer_Format::AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM, 68 usage: AHardwareBuffer_UsageFlags::AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN, 69 stride: 0, 70 }; 71 72 #[test] test_get_buffer_id()73 fn test_get_buffer_id() { 74 let hardware_buffer = STREAM_CONFIG.create_hardware_buffer().unwrap(); 75 let buffer_id = hardware_buffer.id(); 76 77 let buffer = Buffer::new_unowned(hardware_buffer); 78 assert_eq!(buffer_id, buffer.id()); 79 } 80 } 81