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
5/// A way to share a texture's memory with another API or process.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub enum ExportKind {
8    /// An `IOSurfaceRef`.
9    IoSurface,
10    /// A Linux dmabuf: file descriptors with a DRM format and modifier.
11    DmaBuf,
12    /// An `AHardwareBuffer*`.
13    AndroidHardwareBuffer,
14    /// A DXGI shared texture's NT handle.
15    DxgiSharedHandle,
16    /// The memory of a Vulkan image, as an opaque file descriptor that only
17    /// APIs of the same driver import.
18    OpaqueFd,
19}
20
21impl ExportKind {
22    /// Every kind, in the order a ring prefers them: each platform's own
23    /// interchange first, and last the opaque file descriptor, which crosses
24    /// only between the APIs of one driver.
25    pub const BY_PREFERENCE: [ExportKind; 5] = [
26        ExportKind::IoSurface,
27        ExportKind::AndroidHardwareBuffer,
28        ExportKind::DxgiSharedHandle,
29        ExportKind::DmaBuf,
30        ExportKind::OpaqueFd,
31    ];
32
33    fn bit(self) -> u8 {
34        1 << self as u8
35    }
36}
37
38/// A set of [`ExportKind`]s.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
40pub struct ExportKinds(u8);
41
42impl ExportKinds {
43    pub const NONE: ExportKinds = ExportKinds(0);
44
45    #[must_use]
46    pub fn of(kinds: &[ExportKind]) -> ExportKinds {
47        ExportKinds(kinds.iter().fold(0, |bits, kind| bits | kind.bit()))
48    }
49
50    #[must_use]
51    pub fn contains(self, kind: ExportKind) -> bool {
52        self.0 & kind.bit() != 0
53    }
54
55    #[must_use]
56    pub fn is_empty(self) -> bool {
57        self.0 == 0
58    }
59
60    #[must_use]
61    pub fn with(self, kind: ExportKind) -> ExportKinds {
62        ExportKinds(self.0 | kind.bit())
63    }
64
65    #[must_use]
66    pub fn union(self, other: ExportKinds) -> ExportKinds {
67        ExportKinds(self.0 | other.0)
68    }
69
70    #[must_use]
71    pub fn intersection(self, other: ExportKinds) -> ExportKinds {
72        ExportKinds(self.0 & other.0)
73    }
74
75    /// The kinds, in [`ExportKind::BY_PREFERENCE`] order.
76    pub fn iter(self) -> impl Iterator<Item = ExportKind> {
77        ExportKind::BY_PREFERENCE.into_iter().filter(move |kind| self.contains(*kind))
78    }
79}
80
81/// `DRM_FORMAT_ABGR8888`: red in the lowest byte, as Vulkan's
82/// `R8G8B8A8_UNORM` lays it out.
83pub const DRM_FORMAT_ABGR8888: u32 = u32::from_le_bytes(*b"AB24");
84/// `DRM_FORMAT_ARGB8888`: blue in the lowest byte, as Vulkan's
85/// `B8G8R8A8_UNORM` lays it out.
86pub const DRM_FORMAT_ARGB8888: u32 = u32::from_le_bytes(*b"AR24");
87/// `DRM_FORMAT_MOD_LINEAR`.
88pub const DRM_FORMAT_MOD_LINEAR: u64 = 0;
89/// The most planes that a dmabuf has.
90pub const DMA_BUF_MAX_PLANES: usize = 4;
91
92/// A DRM format and modifier that the host imports.
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94pub struct DmaBufFormat {
95    pub fourcc: u32,
96    pub modifier: u64,
97}
98
99/// The fourcc that a ring renders, with the modifiers of it that both the
100/// host and the device take, most preferred first.
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub struct DmaBufChoice {
103    pub fourcc: u32,
104    pub modifiers: Vec<u64>,
105}
106
107/// The first of the host's fourccs, in its order, that the renderers draw
108/// (ABGR8888 or ARGB8888) and for which `supported` takes one of the host's
109/// modifiers, with each such modifier. `None` when no fourcc has one.
110pub fn choose_dma_buf_format(
111    formats: &[DmaBufFormat],
112    supported: impl Fn(&DmaBufFormat) -> bool,
113) -> Option<DmaBufChoice> {
114    formats.iter().filter(|candidate| matches!(candidate.fourcc, DRM_FORMAT_ABGR8888 | DRM_FORMAT_ARGB8888)).find_map(
115        |candidate| {
116            let modifiers: Vec<u64> = formats
117                .iter()
118                .filter(|format| format.fourcc == candidate.fourcc && supported(format))
119                .map(|format| format.modifier)
120                .collect();
121            (!modifiers.is_empty()).then_some(DmaBufChoice { fourcc: candidate.fourcc, modifiers })
122        },
123    )
124}
125
126/// A ring of images that the target allocates, as the host asks for it:
127/// `depth` images, shared in a kind of `kinds`.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct ExportedRing {
130    pub depth: usize,
131    /// The kinds that the host imports.
132    pub kinds: ExportKinds,
133    /// The dmabuf formats and modifiers that the host imports, most
134    /// preferred first.
135    pub dma_buf_formats: Vec<DmaBufFormat>,
136    /// More `AHARDWAREBUFFER_USAGE_*` bits that the host's reads need.
137    pub android_hardware_buffer_usage: u64,
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 target's generations of images: the ones it renders into now, and the
171/// older ones that frames the host held at a resize keep alive, each with
172/// the slots still held. A generation goes once the host gives back each of
173/// its held slots.
174pub struct Generations<G> {
175    current: G,
176    retired: Vec<(G, Vec<usize>)>,
177}
178
179impl<G> Generations<G> {
180    pub fn new(current: G) -> Self {
181        Generations { current, retired: Vec::new() }
182    }
183
184    pub fn current(&self) -> &G {
185        &self.current
186    }
187
188    /// Renders into `next` from now on. The current generation stays while
189    /// the host holds one of the `held` slots, and goes now otherwise.
190    pub fn replace(&mut self, next: G, held: &[usize]) {
191        let previous = std::mem::replace(&mut self.current, next);
192        // A slot that the host held already in an older generation isn't
193        // the previous one's.
194        let held: Vec<usize> = held.iter().copied().filter(|slot| self.retired_holding(*slot).is_none()).collect();
195        if !held.is_empty() {
196            self.retired.push((previous, held));
197        }
198    }
199
200    fn retired_holding(&self, slot: usize) -> Option<usize> {
201        self.retired.iter().position(|(_, held)| held.contains(&slot))
202    }
203
204    /// The image of an older generation that the host holds at `slot`.
205    pub fn retired(&self, slot: usize) -> Option<&G> {
206        self.retired_holding(slot).map(|index| &self.retired[index].0)
207    }
208
209    /// The host gave `slot` back: true when an older generation held it,
210    /// which goes once it holds no slot. The current generation's slot is
211    /// the caller's to give back then.
212    pub fn give_back(&mut self, slot: usize) -> bool {
213        let Some(index) = self.retired_holding(slot) else { return false };
214        let held = &mut self.retired[index].1;
215        held.retain(|held| *held != slot);
216        if held.is_empty() {
217            drop(self.retired.remove(index));
218        }
219        true
220    }
221
222    /// Lets go of every older generation.
223    pub fn clear_retired(&mut self) {
224        self.retired.clear();
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn kinds_iterate_by_preference() {
234        let kinds = ExportKinds::of(&[ExportKind::OpaqueFd, ExportKind::DmaBuf, ExportKind::IoSurface]);
235        assert_eq!(kinds.iter().collect::<Vec<_>>(), [ExportKind::IoSurface, ExportKind::DmaBuf, ExportKind::OpaqueFd]);
236        assert_eq!(
237            kinds.intersection(ExportKinds::of(&[ExportKind::OpaqueFd])).iter().next(),
238            Some(ExportKind::OpaqueFd)
239        );
240        assert!(ExportKinds::NONE.iter().next().is_none());
241    }
242
243    #[test]
244    fn a_dma_buf_format_follows_the_hosts_order() {
245        let format = |fourcc, modifier| DmaBufFormat { fourcc, modifier };
246        // NV12, which no renderer draws, comes first.
247        let nv12 = u32::from_le_bytes(*b"NV12");
248        let formats = [
249            format(nv12, 0),
250            format(DRM_FORMAT_ARGB8888, 7),
251            format(DRM_FORMAT_ABGR8888, 0),
252            format(DRM_FORMAT_ARGB8888, 0),
253        ];
254        assert_eq!(
255            choose_dma_buf_format(&formats, |_| true),
256            Some(DmaBufChoice { fourcc: DRM_FORMAT_ARGB8888, modifiers: vec![7, 0] })
257        );
258        // A fourcc whose modifiers the device lacks gives way to the next.
259        assert_eq!(
260            choose_dma_buf_format(&formats, |format| format.fourcc == DRM_FORMAT_ABGR8888),
261            Some(DmaBufChoice { fourcc: DRM_FORMAT_ABGR8888, modifiers: vec![0] })
262        );
263        assert_eq!(choose_dma_buf_format(&formats, |_| false), None);
264        assert_eq!(choose_dma_buf_format(&[format(nv12, 0)], |_| true), None);
265    }
266
267    #[test]
268    fn a_generation_stays_until_its_held_slots_come_back() {
269        let mut generations = Generations::new("first");
270        generations.replace("second", &[0, 2]);
271        assert_eq!(*generations.current(), "second");
272        assert_eq!(generations.retired(0), Some(&"first"));
273        assert_eq!(generations.retired(1), None);
274        // Slot 0 is still held at the next resize, in the first generation.
275        generations.replace("third", &[0, 1]);
276        assert_eq!(generations.retired(0), Some(&"first"));
277        assert_eq!(generations.retired(1), Some(&"second"));
278        assert!(generations.give_back(0));
279        assert_eq!(generations.retired(2), Some(&"first"));
280        assert!(generations.give_back(2));
281        assert_eq!(generations.retired(2), None);
282        assert!(!generations.give_back(2));
283        assert!(generations.give_back(1));
284        // Nothing held: the previous generation goes at once.
285        generations.replace("fourth", &[]);
286        assert_eq!(generations.retired(0), None);
287    }
288}