Skip to main content

mln_gfx/
export.rs

1//! Rings of images that a target allocates and shares with the host: the
2//! ways a texture's memory crosses to another API or process, how a ring
3//! picks one of those that the host imports, and what each frame hands over.
4
5use mln_util::size::Size;
6
7/// A way to share a texture's memory with another API or process.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum ExportKind {
10    /// An `IOSurfaceRef`.
11    IoSurface,
12    /// A Linux dmabuf: file descriptors with a DRM format and modifier.
13    DmaBuf,
14    /// An `AHardwareBuffer*`.
15    AndroidHardwareBuffer,
16    /// A DXGI shared texture's NT handle.
17    DxgiSharedHandle,
18    /// The memory of a Vulkan image, as an opaque file descriptor that only
19    /// APIs of the same driver import.
20    OpaqueFd,
21}
22
23impl ExportKind {
24    /// Every kind, in the order a ring prefers them: each platform's own
25    /// interchange first, and last the opaque file descriptor, which crosses
26    /// only between the APIs of one driver.
27    pub const BY_PREFERENCE: [ExportKind; 5] = [
28        ExportKind::IoSurface,
29        ExportKind::AndroidHardwareBuffer,
30        ExportKind::DxgiSharedHandle,
31        ExportKind::DmaBuf,
32        ExportKind::OpaqueFd,
33    ];
34
35    fn bit(self) -> u8 {
36        1 << self as u8
37    }
38}
39
40/// A set of [`ExportKind`]s.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42pub struct ExportKinds(u8);
43
44impl ExportKinds {
45    pub const NONE: ExportKinds = ExportKinds(0);
46
47    #[must_use]
48    pub fn of(kinds: &[ExportKind]) -> ExportKinds {
49        ExportKinds(kinds.iter().fold(0, |bits, kind| bits | kind.bit()))
50    }
51
52    #[must_use]
53    pub fn contains(self, kind: ExportKind) -> bool {
54        self.0 & kind.bit() != 0
55    }
56
57    #[must_use]
58    pub fn is_empty(self) -> bool {
59        self.0 == 0
60    }
61
62    #[must_use]
63    pub fn with(self, kind: ExportKind) -> ExportKinds {
64        ExportKinds(self.0 | kind.bit())
65    }
66
67    #[must_use]
68    pub fn intersection(self, other: ExportKinds) -> ExportKinds {
69        ExportKinds(self.0 & other.0)
70    }
71
72    /// The kinds, in [`ExportKind::BY_PREFERENCE`] order.
73    pub fn iter(self) -> impl Iterator<Item = ExportKind> {
74        ExportKind::BY_PREFERENCE.into_iter().filter(move |kind| self.contains(*kind))
75    }
76}
77
78/// `DRM_FORMAT_ABGR8888`: red in the lowest byte, as Vulkan's
79/// `R8G8B8A8_UNORM` lays it out.
80pub const DRM_FORMAT_ABGR8888: u32 = u32::from_le_bytes(*b"AB24");
81/// `DRM_FORMAT_ARGB8888`: blue in the lowest byte, as Vulkan's
82/// `B8G8R8A8_UNORM` lays it out.
83pub const DRM_FORMAT_ARGB8888: u32 = u32::from_le_bytes(*b"AR24");
84/// `DRM_FORMAT_MOD_LINEAR`.
85pub const DRM_FORMAT_MOD_LINEAR: u64 = 0;
86/// The most planes that a dmabuf has.
87pub const DMA_BUF_MAX_PLANES: usize = 4;
88
89/// A DRM format and modifier that the host imports.
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
91pub struct DmaBufFormat {
92    pub fourcc: u32,
93    pub modifier: u64,
94}
95
96/// The fourcc that a ring renders, with the modifiers of it that both the
97/// host and the device take, most preferred first.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct DmaBufChoice {
100    pub fourcc: u32,
101    pub modifiers: Vec<u64>,
102}
103
104/// The first of the host's fourccs, in its order, that the renderers draw
105/// (ABGR8888 or ARGB8888) and for which `supported` takes one of the host's
106/// modifiers, with each such modifier. `None` when no fourcc has one.
107pub fn choose_dma_buf_format(
108    formats: &[DmaBufFormat],
109    supported: impl Fn(&DmaBufFormat) -> bool,
110) -> Option<DmaBufChoice> {
111    formats.iter().filter(|candidate| matches!(candidate.fourcc, DRM_FORMAT_ABGR8888 | DRM_FORMAT_ARGB8888)).find_map(
112        |candidate| {
113            let modifiers: Vec<u64> = formats
114                .iter()
115                .filter(|format| format.fourcc == candidate.fourcc && supported(format))
116                .map(|format| format.modifier)
117                .collect();
118            (!modifiers.is_empty()).then_some(DmaBufChoice { fourcc: candidate.fourcc, modifiers })
119        },
120    )
121}
122
123/// A ring of images that the target allocates, as the host asks for it:
124/// `depth` images, shared in a kind of `kinds`.
125#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct ExportedRing {
127    pub depth: usize,
128    /// The kinds that the host imports.
129    pub kinds: ExportKinds,
130    /// The dmabuf formats and modifiers that the host imports, most
131    /// preferred first.
132    pub dma_buf_formats: Vec<DmaBufFormat>,
133    /// More `AHARDWAREBUFFER_USAGE_*` bits that the host's reads need.
134    pub android_hardware_buffer_usage: u64,
135    /// Whether each frame keeps its depth and stencil for the host, in a
136    /// texture of the target's own beside each image.
137    pub keep_depth: bool,
138}
139
140/// Where one plane of a dmabuf keeps its data.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
142pub struct DmaBufPlane {
143    /// The dmabuf's file descriptor, which the target owns.
144    pub fd: i32,
145    pub offset: u32,
146    pub stride: u32,
147}
148
149/// The shared memory of a frame's image. The objects it names are the
150/// target's, and stay valid until the host gives the frame back.
151#[derive(Clone, Debug, PartialEq, Eq, Hash)]
152#[non_exhaustive]
153pub enum ExportedImage {
154    /// An `IOSurfaceRef`, of the pixel format `'BGRA'`.
155    IoSurface { surface: u64 },
156    /// A dmabuf of `fourcc` with `modifier`, and its planes in order.
157    DmaBuf { fourcc: u32, modifier: u64, planes: Vec<DmaBufPlane> },
158    /// An `AHardwareBuffer*` of the format
159    /// `AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM`.
160    AndroidHardwareBuffer { buffer: u64 },
161    /// A Vulkan image's memory: `allocation_size` bytes, the image's own
162    /// when `dedicated`, holding an image of the `VkFormat` `format` with
163    /// optimal tiling.
164    OpaqueFd { fd: i32, allocation_size: u64, dedicated: bool, format: u32 },
165    /// A D3D11 texture's NT `HANDLE`, as an integer, of the `DXGI_FORMAT`
166    /// `format`.
167    DxgiSharedTexture { handle: u64, format: u32 },
168}
169
170/// A format of depth and stencil textures.
171#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
172pub enum DepthStencilFormat {
173    /// 24-bit normalized depth and 8-bit stencil.
174    Depth24Stencil8,
175    /// 32-bit float depth and 8-bit stencil.
176    Depth32FloatStencil8,
177}
178
179impl DepthStencilFormat {
180    /// Every format, the one that a target prefers first.
181    pub const BY_PREFERENCE: [DepthStencilFormat; 2] =
182        [DepthStencilFormat::Depth24Stencil8, DepthStencilFormat::Depth32FloatStencil8];
183
184    fn bit(self) -> u8 {
185        1 << self as u8
186    }
187}
188
189/// A set of [`DepthStencilFormat`]s.
190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
191pub struct DepthStencilFormats(u8);
192
193impl DepthStencilFormats {
194    pub const NONE: DepthStencilFormats = DepthStencilFormats(0);
195
196    #[must_use]
197    pub fn of(formats: &[DepthStencilFormat]) -> DepthStencilFormats {
198        DepthStencilFormats(formats.iter().fold(0, |bits, format| bits | format.bit()))
199    }
200
201    #[must_use]
202    pub fn contains(self, format: DepthStencilFormat) -> bool {
203        self.0 & format.bit() != 0
204    }
205
206    #[must_use]
207    pub fn with(self, format: DepthStencilFormat) -> DepthStencilFormats {
208        DepthStencilFormats(self.0 | format.bit())
209    }
210
211    /// The formats, in [`DepthStencilFormat::BY_PREFERENCE`] order.
212    pub fn iter(self) -> impl Iterator<Item = DepthStencilFormat> {
213        DepthStencilFormat::BY_PREFERENCE.into_iter().filter(move |format| self.contains(*format))
214    }
215}
216
217/// A texture as the API of the device that drew into it names it.
218#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219#[non_exhaustive]
220pub enum NativeTexture {
221    /// A `VkImage` and a `VkImageView` of it, in a `VkFormat`, left in a
222    /// `VkImageLayout`.
223    Vulkan { image: u64, view: u64, format: i32, layout: i32 },
224    /// An `id<MTLTexture>`, in an `MTLPixelFormat`.
225    Metal { texture: u64, pixel_format: u64 },
226    /// An OpenGL texture name, of a texture target, with an internal format,
227    /// or zero where the target doesn't know it.
228    OpenGl { texture: u32, target: u32, internal_format: u32 },
229    /// A WebGPU texture, which the host gave.
230    WebGpu,
231    /// An `ID3D12Resource*`, in a `DXGI_FORMAT`, left in a
232    /// `D3D12_RESOURCE_STATES`.
233    D3d12 { resource: u64, format: u32, state: u32 },
234}
235
236/// An exported ring's frame: the shared memory of its image, and its
237/// textures on the device that drew it. The objects it names stay the
238/// target's until the host gives the frame back.
239#[derive(Clone, Debug, PartialEq, Eq, Hash)]
240pub struct ExportedFrame {
241    pub size: Size,
242    pub image: ExportedImage,
243    /// The image, on the device.
244    pub texture: NativeTexture,
245    /// The frame's depth and stencil, when the ring keeps them.
246    pub depth: Option<FrameDepth>,
247}
248
249/// The texture that holds a frame's depth and stencil.
250#[derive(Clone, Debug, PartialEq, Eq, Hash)]
251pub struct FrameDepth {
252    /// The texture, on the device.
253    pub texture: NativeTexture,
254    /// Its memory, as an opaque file descriptor, when the ring shares its
255    /// images so.
256    pub export: Option<ExportedImage>,
257}
258
259/// A target's generations of images: the ones it renders into now, and the
260/// older ones that frames the host held at a resize keep alive, each with
261/// the slots still held. A generation goes once the host gives back each of
262/// its held slots.
263pub struct Generations<G> {
264    current: G,
265    retired: Vec<(G, Vec<usize>)>,
266}
267
268impl<G> Generations<G> {
269    pub fn new(current: G) -> Self {
270        Generations { current, retired: Vec::new() }
271    }
272
273    pub fn current(&self) -> &G {
274        &self.current
275    }
276
277    pub fn current_mut(&mut self) -> &mut G {
278        &mut self.current
279    }
280
281    /// Renders into `next` from now on. The current generation stays while
282    /// the host holds one of the `held` slots, and goes to `release` now
283    /// otherwise.
284    pub fn replace(&mut self, next: G, held: &[usize], release: impl FnOnce(G)) {
285        let previous = std::mem::replace(&mut self.current, next);
286        // A slot that the host held already in an older generation isn't
287        // the previous one's.
288        let held: Vec<usize> = held.iter().copied().filter(|slot| self.retired_holding(*slot).is_none()).collect();
289        if held.is_empty() {
290            release(previous);
291        } else {
292            self.retired.push((previous, held));
293        }
294    }
295
296    fn retired_holding(&self, slot: usize) -> Option<usize> {
297        self.retired.iter().position(|(_, held)| held.contains(&slot))
298    }
299
300    /// The image of an older generation that the host holds at `slot`.
301    pub fn retired(&self, slot: usize) -> Option<&G> {
302        self.retired_holding(slot).map(|index| &self.retired[index].0)
303    }
304
305    /// The host gave `slot` back: true when an older generation held it,
306    /// which goes to `release` once it holds no slot. The current
307    /// generation's slot is the caller's to give back then.
308    pub fn give_back(&mut self, slot: usize, release: impl FnOnce(G)) -> bool {
309        let Some(index) = self.retired_holding(slot) else { return false };
310        let held = &mut self.retired[index].1;
311        held.retain(|held| *held != slot);
312        if held.is_empty() {
313            release(self.retired.remove(index).0);
314        }
315        true
316    }
317
318    /// Lets go of every generation's images: `release` takes each, the
319    /// older ones first, and the older ones go.
320    pub fn clear(&mut self, mut release: impl FnMut(&mut G)) {
321        for (generation, _) in &mut self.retired {
322            release(generation);
323        }
324        self.retired.clear();
325        release(&mut self.current);
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn kinds_iterate_by_preference() {
335        let kinds = ExportKinds::of(&[ExportKind::OpaqueFd, ExportKind::DmaBuf, ExportKind::IoSurface]);
336        assert_eq!(kinds.iter().collect::<Vec<_>>(), [ExportKind::IoSurface, ExportKind::DmaBuf, ExportKind::OpaqueFd]);
337        assert_eq!(
338            kinds.intersection(ExportKinds::of(&[ExportKind::OpaqueFd])).iter().next(),
339            Some(ExportKind::OpaqueFd)
340        );
341        assert!(ExportKinds::NONE.iter().next().is_none());
342    }
343
344    #[test]
345    fn a_dma_buf_format_follows_the_hosts_order() {
346        let format = |fourcc, modifier| DmaBufFormat { fourcc, modifier };
347        // NV12, which no renderer draws, comes first.
348        let nv12 = u32::from_le_bytes(*b"NV12");
349        let formats = [
350            format(nv12, 0),
351            format(DRM_FORMAT_ARGB8888, 7),
352            format(DRM_FORMAT_ABGR8888, 0),
353            format(DRM_FORMAT_ARGB8888, 0),
354        ];
355        assert_eq!(
356            choose_dma_buf_format(&formats, |_| true),
357            Some(DmaBufChoice { fourcc: DRM_FORMAT_ARGB8888, modifiers: vec![7, 0] })
358        );
359        // A fourcc whose modifiers the device lacks gives way to the next.
360        assert_eq!(
361            choose_dma_buf_format(&formats, |format| format.fourcc == DRM_FORMAT_ABGR8888),
362            Some(DmaBufChoice { fourcc: DRM_FORMAT_ABGR8888, modifiers: vec![0] })
363        );
364        assert_eq!(choose_dma_buf_format(&formats, |_| false), None);
365        assert_eq!(choose_dma_buf_format(&[format(nv12, 0)], |_| true), None);
366    }
367
368    #[test]
369    fn a_generation_stays_until_its_held_slots_come_back() {
370        let mut generations = Generations::new("first");
371        let gone = std::cell::RefCell::new(Vec::new());
372        let release = |generation| gone.borrow_mut().push(generation);
373        generations.replace("second", &[0, 2], release);
374        assert_eq!(*generations.current(), "second");
375        assert_eq!(generations.retired(0), Some(&"first"));
376        assert_eq!(generations.retired(1), None);
377        // Slot 0 is still held at the next resize, in the first generation.
378        generations.replace("third", &[0, 1], release);
379        assert_eq!(generations.retired(0), Some(&"first"));
380        assert_eq!(generations.retired(1), Some(&"second"));
381        assert!(generations.give_back(0, release));
382        assert_eq!(generations.retired(2), Some(&"first"));
383        assert!(gone.borrow().is_empty());
384        assert!(generations.give_back(2, release));
385        assert_eq!(generations.retired(2), None);
386        assert_eq!(*gone.borrow(), ["first"]);
387        assert!(!generations.give_back(2, release));
388        assert!(generations.give_back(1, release));
389        // Nothing held: the previous generation goes at once.
390        generations.replace("fourth", &[], release);
391        assert_eq!(generations.retired(0), None);
392        assert_eq!(*gone.borrow(), ["first", "second", "third"]);
393    }
394}