Skip to main content

waft_test/
hardware_buffers.rs

1//! Hardware buffers in memory, as a host with no GPU of its own hands them out: each knows its
2//! size, format and usage, is imported as no texture (`TestPlatform::import_texture`), and reads
3//! back opaque black, in BGRA as Apple's buffers are, where its usage has `cpu_read` and it is in
4//! BGRA; and the system's
5//! allocator, which allocates them for exactly what the app asked for, and keeps each ask. A
6//! buffer the codecs decode or a video frame's is for what Apple's systems give one
7//! ([`SYSTEM_GIVEN`]).
8
9use std::sync::{Arc, Mutex};
10
11use waft_embedder::image_codecs::{
12    ImageError, ImageErrorKind, ImageFuture, PixelBuffer, PixelFormat,
13};
14use waft_embedder::{
15    HardwareBuffer, HardwareBufferAllocator, HardwareBufferFormat, HardwareBufferUsage,
16};
17
18use crate::image_codecs::pixels_of;
19
20/// What a decoded image's buffer and a video frame's are for: sampled, as the system made them,
21/// and shown by the compositor and read by the CPU, as on Apple's systems.
22pub(crate) const SYSTEM_GIVEN: HardwareBufferUsage = HardwareBufferUsage {
23    composer_overlay: true,
24    cpu_read: true,
25    ..HardwareBufferUsage::GPU_SAMPLED
26};
27
28/// A hardware buffer of a size, in the format the test gives, with no pixels on any GPU: it is
29/// imported as no texture, as a buffer a device cannot take, which a drawing skips, and its pixels
30/// read back opaque black where it is in BGRA.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct MockHardwareBuffer {
33    pub width: u32,
34    pub height: u32,
35    pub format: HardwareBufferFormat,
36    pub usage: HardwareBufferUsage,
37}
38
39impl HardwareBuffer for MockHardwareBuffer {
40    fn width(&self) -> u32 {
41        self.width
42    }
43
44    fn height(&self) -> u32 {
45        self.height
46    }
47
48    fn usage(&self) -> HardwareBufferUsage {
49        self.usage
50    }
51
52    fn format(&self) -> HardwareBufferFormat {
53        self.format
54    }
55
56    fn read_pixels(&self) -> ImageFuture<PixelBuffer> {
57        let read = if !self.usage.cpu_read {
58            Err(ImageError::new(
59                ImageErrorKind::Unsupported,
60                "a buffer whose usage lacks `cpu_read`",
61            ))
62        } else if self.format != HardwareBufferFormat::Bgra8 {
63            Err(ImageError::new(
64                ImageErrorKind::Unsupported,
65                "a buffer whose pixels are in no pixel format",
66            ))
67        } else if self.width == 0 || self.height == 0 {
68            Err(ImageError::new(
69                ImageErrorKind::Other,
70                "a buffer with no pixels",
71            ))
72        } else {
73            Ok(pixels_of(
74                [self.width, self.height],
75                [0, 0, 0, 255],
76                PixelFormat::Bgra8,
77            ))
78        };
79        Box::pin(std::future::ready(read))
80    }
81}
82
83/// The system's hardware buffer allocator, which allocates [`MockHardwareBuffer`]s in BGRA, as
84/// Apple's systems do, and keeps each allocation asked for. Every clone is the same allocator.
85#[derive(Clone, Default)]
86pub struct MockHardwareBufferAllocator(Arc<Mutex<Vec<AskedAllocation>>>);
87
88/// An allocation the app asked for.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct AskedAllocation {
91    pub width: u32,
92    pub height: u32,
93    pub format: HardwareBufferFormat,
94    pub usage: HardwareBufferUsage,
95}
96
97impl MockHardwareBufferAllocator {
98    pub fn new() -> MockHardwareBufferAllocator {
99        MockHardwareBufferAllocator::default()
100    }
101
102    /// The allocations asked for, in order, those refused among them.
103    pub fn asked(&self) -> Vec<AskedAllocation> {
104        self.0.lock().expect("never held across a panic").clone()
105    }
106}
107
108impl HardwareBufferAllocator for MockHardwareBufferAllocator {
109    /// A buffer of the size asked; [`ImageErrorKind::Unsupported`] for any format but BGRA and
110    /// [`ImageErrorKind::Other`] for a side of no pixels.
111    fn allocate(
112        &self,
113        width: u32,
114        height: u32,
115        format: HardwareBufferFormat,
116        usage: HardwareBufferUsage,
117    ) -> Result<Arc<dyn HardwareBuffer>, ImageError> {
118        self.0
119            .lock()
120            .expect("never held across a panic")
121            .push(AskedAllocation {
122                width,
123                height,
124                format,
125                usage,
126            });
127        if width == 0 || height == 0 {
128            return Err(ImageError::new(
129                ImageErrorKind::Other,
130                "a buffer with no pixels",
131            ));
132        }
133        if format != HardwareBufferFormat::Bgra8 {
134            return Err(ImageError::new(
135                ImageErrorKind::Unsupported,
136                "these buffers are BGRA",
137            ));
138        }
139        Ok(Arc::new(MockHardwareBuffer {
140            width,
141            height,
142            format,
143            usage,
144        }))
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use std::task::{Context, Poll, Waker};
151
152    use super::*;
153
154    fn now<T>(future: impl Future<Output = T>) -> T {
155        let mut future = std::pin::pin!(future);
156        match future
157            .as_mut()
158            .poll(&mut Context::from_waker(Waker::noop()))
159        {
160            Poll::Ready(output) => output,
161            Poll::Pending => panic!("answers at once"),
162        }
163    }
164
165    #[test]
166    fn a_buffer_answers_what_it_was_allocated_for_and_is_read_only_with_cpu_read() {
167        let allocator = MockHardwareBufferAllocator::new();
168        let drawn = allocator
169            .allocate(
170                4,
171                4,
172                HardwareBufferFormat::Bgra8,
173                HardwareBufferUsage::GPU_SAMPLED,
174            )
175            .expect("a buffer");
176        assert_eq!(drawn.usage(), HardwareBufferUsage::GPU_SAMPLED);
177        let refused = now(drawn.read_pixels()).err().map(|error| error.kind);
178        assert_eq!(refused, Some(ImageErrorKind::Unsupported));
179
180        let read = HardwareBufferUsage {
181            cpu_read: true,
182            ..HardwareBufferUsage::default()
183        };
184        let readable = allocator
185            .allocate(4, 4, HardwareBufferFormat::Bgra8, read)
186            .expect("a buffer");
187        assert!(now(readable.read_pixels()).is_ok());
188    }
189}