waft_embedder/hardware_buffers.rs
1//! GPU memory the system's compositor shows, as a host hands it to the app: on Apple platforms an
2//! `IOSurface`, Android's `HardwareBuffer`, a dmabuf behind Wayland's `wl_buffer`, a shared D3D
3//! texture; and on Wayland, for a producer without a GPU the compositor imports from, shared memory
4//! the compositor maps. Not a dart:ui type: Flutter's engine keeps its buffers to itself. They follow
5//! `wasdk:platform/hardware-buffers` one to one.
6//!
7//! A hardware buffer is memory the app holds: one it allocates
8//! ([`HardwareBufferAllocator::allocate`]), as `IOSurfaceCreate` and `AHardwareBuffer_allocate`
9//! make one, and an image the system's hardware codecs decode
10//! ([`HardwareImageCodecs`](crate::image_codecs::HardwareImageCodecs)), which no system pool waits
11//! for. A video's frame is apart, lent with its slot in a decoder's pool
12//! ([`VideoFrame`](crate::VideoFrame)), and its memory is one of these too, which keeps the frame
13//! while it is held. The app draws into a buffer and samples it through a texture it imports on
14//! its own device ([`Platform::import_texture`](crate::Platform::import_texture)), shows it on a
15//! composition layer ([`CompositionLayer::present`](crate::CompositionLayer::present)), and has
16//! the hardware codecs encode it; its pixels come back to the app's memory only through
17//! [`HardwareBuffer::read_pixels`]. A buffer knows only its own facts, its size, how it lays out
18//! its pixels and what it can be used for, and names no GPU API: the host, which knows both the buffer and the device,
19//! imports it, as each system's GPU API imports such memory.
20//!
21//! Each host implements [`HardwareBuffer`] over its system's buffers. Platform code reaches the
22//! system's own buffer by downcasting through `Any` to the type of the host that handed it out: on
23//! Apple platforms `waft-embedder-winit`'s `SurfaceBuffer`, whose `surface` is the `IOSurface`.
24//!
25//! The invariant a host keeps: a texture imported of a buffer holds the buffer, and the frame it
26//! is the memory of, until the GPU is done with it.
27
28use std::any::Any;
29use std::sync::Arc;
30
31use crate::image_codecs::{ImageError, ImageFuture, PixelBuffer};
32
33/// What makes the app's hardware buffers: the role of Android's graphics allocator (gralloc's
34/// `IAllocator`), Fuchsia's sysmem `Allocator` and a GBM device on Linux. `None` from
35/// [`SystemGpu::hardware_buffer_allocator`](crate::SystemGpu::hardware_buffer_allocator) where the
36/// system allocates none. It may be called from any thread, as a producer allocates a buffer where
37/// it draws.
38pub trait HardwareBufferAllocator: Send + Sync {
39 /// A buffer of `width` by `height` pixels laid out in `format`, for at least what `usage`
40 /// names ([`HardwareBuffer::usage`] answers all it is for), its pixels as the system leaves new
41 /// memory until the app draws them:
42 /// [`ImageErrorKind::Unsupported`](crate::image_codecs::ImageErrorKind::Unsupported) for a
43 /// format the system does not allocate a buffer in, as Apple platforms allocate only
44 /// [`HardwareBufferFormat::Bgra8`], Android only [`HardwareBufferFormat::Rgba8`], and none
45 /// yet a decoder's planes ([`Nv12`](HardwareBufferFormat::Nv12),
46 /// [`P010`](HardwareBufferFormat::P010));
47 /// [`TooLarge`](crate::image_codecs::ImageErrorKind::TooLarge) for a side past the largest the
48 /// system makes a texture of; [`OutOfMemory`](crate::image_codecs::ImageErrorKind::OutOfMemory)
49 /// where the system has no memory left for it; and
50 /// [`Other`](crate::image_codecs::ImageErrorKind::Other) for a side of no pixels.
51 fn allocate(
52 &self,
53 width: u32,
54 height: u32,
55 format: HardwareBufferFormat,
56 usage: HardwareBufferUsage,
57 ) -> Result<Arc<dyn HardwareBuffer>, ImageError>;
58}
59
60/// What a buffer can be used for, named after its users, as Android's `AHardwareBuffer` usage is:
61/// what the GPU does with it, which a texture imported of it allows
62/// ([`Platform::import_texture`](crate::Platform::import_texture)), whether the system's
63/// compositor shows it as an overlay, and whether the CPU reads it. A video encoder joins as it is
64/// needed.
65///
66/// The usage an app allocates a buffer for is the least the buffer is for, and the buffer answers
67/// all it is for ([`HardwareBuffer::usage`]), which every check reads: a system that gives a buffer
68/// more than it was asked, as Apple's give any `IOSurface` every use, says so there rather than
69/// hiding it. Android gives a buffer what it was allocated for, as `AHardwareBuffer_describe`
70/// answers.
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub struct HardwareBufferUsage {
73 /// The GPU samples it in its shaders: Android's `GPU_SAMPLED_IMAGE`.
74 pub gpu_sampled: bool,
75 /// The GPU draws into it, as a render pass's colour output, and copies into it: Android's
76 /// `GPU_COLOR_OUTPUT`.
77 pub gpu_color_output: bool,
78 /// The system's compositor may show it as a plane of the display, without compositing it on
79 /// the GPU: Android's `COMPOSER_OVERLAY`, which a buffer presented to a composition layer
80 /// there wants and SurfaceFlinger otherwise draws with the GPU, at a cost in power. Core
81 /// Animation shows any `IOSurface` so, and every buffer on Apple's systems has it.
82 pub composer_overlay: bool,
83 /// The CPU reads it, through [`HardwareBuffer::read_pixels`], which answers
84 /// [`ImageErrorKind::Unsupported`](crate::image_codecs::ImageErrorKind::Unsupported) for a
85 /// buffer without it: Android's `CPU_READ_RARELY` or `CPU_READ_OFTEN`. The CPU reads any
86 /// `IOSurface` while it is locked, and every buffer on Apple's systems has it.
87 pub cpu_read: bool,
88}
89
90impl HardwareBufferUsage {
91 /// Sampled by the GPU only, as a decoded image's buffer and a video frame's are.
92 pub const GPU_SAMPLED: HardwareBufferUsage = HardwareBufferUsage {
93 gpu_sampled: true,
94 gpu_color_output: false,
95 composer_overlay: false,
96 cpu_read: false,
97 };
98
99 /// Every use, as any `IOSurface` has.
100 pub const ALL: HardwareBufferUsage = HardwareBufferUsage {
101 gpu_sampled: true,
102 gpu_color_output: true,
103 composer_overlay: true,
104 cpu_read: true,
105 };
106}
107
108/// One block of pixels in memory the GPU, the system's compositor and other processes all reach.
109/// Every method may be called from any thread.
110pub trait HardwareBuffer: Any + Send + Sync {
111 /// The buffer's width, in its own pixels.
112 fn width(&self) -> u32;
113
114 /// The buffer's height, in its own pixels.
115 fn height(&self) -> u32;
116
117 /// What the buffer can be used for: at least what it was allocated for, and on some systems
118 /// more (see [`HardwareBufferUsage`]). A texture imported of it allows what this allows, and
119 /// [`read_pixels`](HardwareBuffer::read_pixels) reads it only where this has
120 /// [`cpu_read`](HardwareBufferUsage::cpu_read).
121 fn usage(&self) -> HardwareBufferUsage;
122
123 /// How the buffer lays out its pixels: one plane of colour, or a video decoder's planes.
124 fn format(&self) -> HardwareBufferFormat;
125
126 /// The buffer's pixels copied into the app's memory, in the layout the buffer holds them, for a
127 /// buffer of one plane: BGRA on Apple platforms, RGBA on Android. It reads what the GPU has
128 /// finished writing, so an app that drew into the buffer waits for that work first, as it
129 /// does before presenting it;
130 /// [`ImageErrorKind::Unsupported`](crate::image_codecs::ImageErrorKind::Unsupported) for a
131 /// buffer whose [`usage`](HardwareBuffer::usage) lacks
132 /// [`cpu_read`](HardwareBufferUsage::cpu_read), on every system, and for one whose pixels are
133 /// in no [`PixelFormat`](crate::image_codecs::PixelFormat), as a decoder's planes
134 /// ([`HardwareBufferFormat::Nv12`] and [`P010`](HardwareBufferFormat::P010)) are.
135 fn read_pixels(&self) -> ImageFuture<PixelBuffer>;
136}
137
138/// How a hardware buffer lays out its pixels: one plane of colour, as an app draws, or a video
139/// decoder's own planes of brightness and colour difference, which the system's decoders write and
140/// its compositor shows with no conversion. What the samples mean as colour (matrix, range) is the
141/// picture's ([`VideoFrame::color`](crate::VideoFrame::color)), not the buffer's.
142#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
143#[non_exhaustive]
144pub enum HardwareBufferFormat {
145 /// 8-bit blue, green, red and alpha in one plane: CoreVideo's `32BGRA`, DXGI's
146 /// `B8G8R8A8_UNORM`, DRM's `ARGB8888`.
147 Bgra8,
148 /// 8-bit red, green, blue and alpha in one plane: Android's `R8G8B8A8_UNORM`.
149 Rgba8,
150 /// 8-bit 4:2:0 in two planes: brightness, then blue and red difference interleaved at half
151 /// the size each way. CoreVideo's `420v` and `420f`, DXGI's and DRM's `NV12`. Not Android's
152 /// `Y8Cb8Cr8_420`, whose planes lie as its allocator chooses.
153 Nv12,
154 /// 10-bit 4:2:0 laid out as [`Nv12`](Self::Nv12), each sample in the high ten bits of
155 /// sixteen: CoreVideo's `x420` and `xf20`, DXGI's and DRM's `P010`, Android's `YCbCr_P010`.
156 P010,
157}
158
159impl HardwareBufferFormat {
160 /// How many planes it has: one, or two for [`Nv12`](Self::Nv12) and [`P010`](Self::P010).
161 pub fn plane_count(self) -> usize {
162 match self {
163 HardwareBufferFormat::Bgra8 | HardwareBufferFormat::Rgba8 => 1,
164 HardwareBufferFormat::Nv12 | HardwareBufferFormat::P010 => 2,
165 }
166 }
167
168 /// The texture format plane `plane` is sampled in: `Bgra8Unorm` or `Rgba8Unorm` for one plane;
169 /// `R8Unorm` then `Rg8Unorm` for [`Nv12`](Self::Nv12), as wgpu's `TextureFormat::NV12`
170 /// aspects are; `R16Unorm` then `Rg16Unorm` for [`P010`](Self::P010), which need
171 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`](wgpu::Features::TEXTURE_FORMAT_16BIT_NORM). `None`
172 /// past the last plane.
173 pub fn plane_format(self, plane: usize) -> Option<wgpu::TextureFormat> {
174 let formats: &[wgpu::TextureFormat] = match self {
175 HardwareBufferFormat::Bgra8 => &[wgpu::TextureFormat::Bgra8Unorm],
176 HardwareBufferFormat::Rgba8 => &[wgpu::TextureFormat::Rgba8Unorm],
177 HardwareBufferFormat::Nv12 => {
178 &[wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Rg8Unorm]
179 }
180 HardwareBufferFormat::P010 => &[
181 wgpu::TextureFormat::R16Unorm,
182 wgpu::TextureFormat::Rg16Unorm,
183 ],
184 };
185 formats.get(plane).copied()
186 }
187
188 /// The size of plane `plane` of a buffer of `size` pixels: the whole for the first plane, and
189 /// half each way, rounded up, for the colour plane of [`Nv12`](Self::Nv12) and
190 /// [`P010`](Self::P010). `None` past the last plane.
191 pub fn plane_size(self, plane: usize, size: [u32; 2]) -> Option<[u32; 2]> {
192 match plane {
193 0 => Some(size),
194 1 if self.plane_count() == 2 => Some(size.map(|side| side.div_ceil(2))),
195 _ => None,
196 }
197 }
198}
199
200/// A GPU as its system names it to every API on it and to other processes: what anything that
201/// makes GPU memory for another is told, so the memory opens where it is read. Memory shared by
202/// handle opens only on the adapter that made it: a D3D texture shared by NT handle on Windows, a
203/// dmabuf in a tiled layout on Linux. An `IOSurface` and an `AHardwareBuffer` open on any of their
204/// system's GPUs, so Apple's systems and Android name none.
205///
206/// Two ids are the same GPU exactly when they are equal: a host turns whatever its system says
207/// into this form first, as Wayland's compositor may name a GPU by its primary node or by its
208/// render node.
209#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
210#[non_exhaustive]
211pub enum GpuId {
212 /// Windows: the adapter's locally unique id, as `DXGI_ADAPTER_DESC1::AdapterLuid` holds it,
213 /// `ID3D12Device::GetAdapterLuid` answers it and Vulkan's
214 /// `VkPhysicalDeviceIDProperties::deviceLUID` gives it.
215 Luid { low: u32, high: i32 },
216 /// Linux: the device number of the GPU's DRM render node (226:128 is `/dev/dri/renderD128`),
217 /// as `stat(2)` of the node and Vulkan's `VkPhysicalDeviceDrmPropertiesEXT::renderMajor` and
218 /// `renderMinor` give it.
219 DrmRenderNode { major: u32, minor: u32 },
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 #[test]
227 fn a_decoders_format_has_a_brightness_plane_then_a_colour_plane_at_half_size() {
228 let format = HardwareBufferFormat::Nv12;
229 assert_eq!(format.plane_count(), 2);
230 assert_eq!(format.plane_format(0), Some(wgpu::TextureFormat::R8Unorm));
231 assert_eq!(format.plane_format(1), Some(wgpu::TextureFormat::Rg8Unorm));
232 assert_eq!(format.plane_format(2), None);
233 assert_eq!(format.plane_size(0, [1919, 1081]), Some([1919, 1081]));
234 assert_eq!(format.plane_size(1, [1919, 1081]), Some([960, 541]));
235 assert_eq!(format.plane_size(2, [1919, 1081]), None);
236 assert_eq!(
237 HardwareBufferFormat::P010.plane_format(1),
238 Some(wgpu::TextureFormat::Rg16Unorm)
239 );
240 }
241
242 #[test]
243 fn a_format_of_one_plane_is_that_plane_whole() {
244 let format = HardwareBufferFormat::Bgra8;
245 assert_eq!(format.plane_count(), 1);
246 assert_eq!(
247 format.plane_format(0),
248 Some(wgpu::TextureFormat::Bgra8Unorm)
249 );
250 assert_eq!(format.plane_format(1), None);
251 assert_eq!(format.plane_size(1, [8, 8]), None);
252 }
253}