Skip to main content

wgpu_external_frame/dma_buf/
frame.rs

1use std::os::fd::{AsRawFd as _, OwnedFd};
2
3const DRM_FORMAT_ARGB8888: u32 = u32::from_le_bytes(*b"AR24");
4const DRM_FORMAT_XRGB8888: u32 = u32::from_le_bytes(*b"XR24");
5const DRM_FORMAT_ABGR8888: u32 = u32::from_le_bytes(*b"AB24");
6const DRM_FORMAT_XBGR8888: u32 = u32::from_le_bytes(*b"XB24");
7
8/// The DRM format modifier that means "no modifier was negotiated".
9///
10/// Vulkan import needs an explicit modifier and rejects this value; EGL import
11/// treats it as "omit the modifier attributes entirely".
12pub const DRM_FORMAT_MOD_INVALID: u64 = u64::MAX;
13
14/// Pixel format of a DMA-BUF frame.
15///
16/// Only the single-plane packed 32-bit formats are covered, which is what
17/// browser and compositor output uses.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum DmaBufFormat {
20    /// Little-endian BGRA with meaningful alpha.
21    Bgra8,
22    /// Little-endian BGRX; consumers must force alpha to one.
23    Bgrx8,
24    /// Little-endian RGBA with meaningful alpha.
25    Rgba8,
26    /// Little-endian RGBX; consumers must force alpha to one.
27    Rgbx8,
28}
29
30impl DmaBufFormat {
31    /// Maps a DRM `fourcc` code onto the format it names.
32    ///
33    /// # Panics
34    ///
35    /// Panics for any code outside the four packed 32-bit formats above.
36    #[must_use]
37    pub fn from_fourcc(value: u32) -> Self {
38        match value {
39            DRM_FORMAT_ARGB8888 => Self::Bgra8,
40            DRM_FORMAT_XRGB8888 => Self::Bgrx8,
41            DRM_FORMAT_ABGR8888 => Self::Rgba8,
42            DRM_FORMAT_XBGR8888 => Self::Rgbx8,
43            _ => panic!("unsupported DMA-BUF DRM fourcc 0x{value:08x}"),
44        }
45    }
46
47    /// The DRM `fourcc` code for this format.
48    #[must_use]
49    pub const fn fourcc(self) -> u32 {
50        match self {
51            Self::Bgra8 => DRM_FORMAT_ARGB8888,
52            Self::Bgrx8 => DRM_FORMAT_XRGB8888,
53            Self::Rgba8 => DRM_FORMAT_ABGR8888,
54            Self::Rgbx8 => DRM_FORMAT_XBGR8888,
55        }
56    }
57
58    /// The `wgpu` format an imported texture of this format carries.
59    ///
60    /// The `X` variants have no alpha of their own but still occupy the
61    /// channel, so they import as their `A` counterpart; see
62    /// [`Self::force_opaque`].
63    #[must_use]
64    pub const fn texture_format(self) -> wgpu::TextureFormat {
65        match self {
66            Self::Bgra8 | Self::Bgrx8 => wgpu::TextureFormat::Bgra8Unorm,
67            Self::Rgba8 | Self::Rgbx8 => wgpu::TextureFormat::Rgba8Unorm,
68        }
69    }
70
71    /// Whether a consumer must ignore the imported alpha channel and treat the
72    /// frame as opaque.
73    #[must_use]
74    pub const fn force_opaque(self) -> bool {
75        matches!(self, Self::Bgrx8 | Self::Rgbx8)
76    }
77}
78
79/// One owned plane in a DMA-BUF frame.
80#[derive(Debug)]
81pub struct DmaBufPlane {
82    /// Owned DMA-BUF file descriptor.
83    pub fd: OwnedFd,
84    /// Byte offset of this plane.
85    pub offset: u32,
86    /// Bytes between adjacent rows.
87    pub stride: u32,
88}
89
90/// The producer's ownership of the buffer behind a [`DmaBufFrame`].
91///
92/// A producer that hands out a buffer from a pool needs to know when the
93/// importer has read it, so it can put the buffer back. That is a two-step
94/// protocol — the import is recorded, then the GPU work referencing it
95/// completes — and this trait is both steps.
96///
97/// A lease is dropped rather than released whenever an import path is
98/// abandoned, so implementations must treat `Drop` as an implicit release.
99pub trait DmaBufLease: core::fmt::Debug + Send {
100    /// Tells the producer the frame has been imported or copied.
101    ///
102    /// The GPU work reading it may still be in flight; only [`Self::release`]
103    /// says it has finished.
104    fn presented(&mut self);
105
106    /// Returns the buffer to the producer once the importing GPU work has
107    /// completed.
108    ///
109    /// `release_fence` is a fence the producer must wait on before reusing the
110    /// buffer, for importers that can supply one instead of waiting themselves.
111    fn release(self: Box<Self>, release_fence: Option<OwnedFd>);
112}
113
114/// A DMA-BUF frame, its planes, and the producer's lease on the buffer.
115#[derive(Debug)]
116pub struct DmaBufFrame {
117    /// Pixel width of the allocation.
118    pub width: u32,
119    /// Pixel height of the allocation.
120    pub height: u32,
121    /// Pixel format.
122    pub format: DmaBufFormat,
123    /// DRM format modifier describing the plane layout.
124    pub modifier: u64,
125    /// Owned planes.
126    pub planes: Vec<DmaBufPlane>,
127    /// Rendering completion fence supplied by the producer.
128    pub rendering_fence: Option<OwnedFd>,
129    /// The part of the buffer that actually holds the image, when it is smaller
130    /// than the allocation.
131    visible: Option<(u32, u32)>,
132    lease: Option<Box<dyn DmaBufLease>>,
133}
134
135impl DmaBufFrame {
136    /// Creates a frame whose descriptors this side owns outright.
137    ///
138    /// Attach a producer's buffer lease with [`Self::with_lease`].
139    ///
140    /// # Panics
141    ///
142    /// Panics when the dimensions are zero or the frame is not a single packed
143    /// 32-bit plane.
144    #[must_use]
145    pub fn new(
146        width: u32,
147        height: u32,
148        format: DmaBufFormat,
149        modifier: u64,
150        planes: Vec<DmaBufPlane>,
151        rendering_fence: Option<OwnedFd>,
152    ) -> Self {
153        assert!(width > 0 && height > 0, "DMA-BUF frame must be non-zero");
154        assert_eq!(
155            planes.len(),
156            1,
157            "DMA-BUF frames require one packed 32-bit plane"
158        );
159        Self {
160            width,
161            height,
162            format,
163            modifier,
164            planes,
165            rendering_fence,
166            visible: None,
167            lease: None,
168        }
169    }
170
171    /// Attaches the producer's lease on the buffer this frame borrows.
172    ///
173    /// # Panics
174    ///
175    /// Panics when the frame already carries a lease, since only one producer
176    /// can own the buffer.
177    #[must_use]
178    pub fn with_lease(mut self, lease: Box<dyn DmaBufLease>) -> Self {
179        assert!(
180            self.lease.is_none(),
181            "a DMA-BUF frame carries at most one buffer lease"
182        );
183        self.lease = Some(lease);
184        self
185    }
186
187    /// Narrows the frame to the region that actually holds the image.
188    ///
189    /// Presenting a padded buffer edge to edge stretches the picture and draws
190    /// the padding gutter, which is what happens whenever a producer's coded
191    /// size exceeds its visible rect.
192    ///
193    /// # Panics
194    ///
195    /// Panics when the visible size is zero or exceeds the buffer, since such
196    /// a region cannot describe any part of the image this frame holds.
197    #[must_use]
198    pub fn with_visible_size(mut self, width: u32, height: u32) -> Self {
199        assert!(
200            width > 0 && height > 0 && width <= self.width && height <= self.height,
201            "a DMA-BUF frame's visible size must be non-zero and within the buffer"
202        );
203        self.visible = Some((width, height));
204        self
205    }
206
207    /// The extent that should be presented: the visible region when the buffer
208    /// is padded, the whole buffer otherwise.
209    #[must_use]
210    pub fn visible_size(&self) -> (u32, u32) {
211        self.visible.unwrap_or((self.width, self.height))
212    }
213
214    /// Returns whether the explicit rendering fence has signalled.
215    ///
216    /// A frame with no fence is ready as soon as it arrives.
217    ///
218    /// # Panics
219    ///
220    /// Panics when polling the rendering fence fails.
221    #[must_use]
222    pub fn is_render_ready(&self) -> bool {
223        let Some(fence) = &self.rendering_fence else {
224            return true;
225        };
226        let mut descriptor = libc::pollfd {
227            fd: fence.as_raw_fd(),
228            events: libc::POLLIN,
229            revents: 0,
230        };
231        // SAFETY: `poll` reads `nfds` entries of the array it is given and
232        // writes their `revents`. `descriptor` is one fully initialized
233        // `pollfd` local, and `1` is exactly its length. Its `fd` is borrowed
234        // from the `OwnedFd` this frame holds, so it is open for the call, and
235        // a zero timeout makes the call return without blocking.
236        let result = unsafe { libc::poll(&raw mut descriptor, 1, 0) };
237        assert!(result >= 0, "failed to poll the DMA-BUF rendering fence");
238        result == 1
239    }
240
241    /// Tells the producer the frame has been imported or copied.
242    ///
243    /// Does nothing for a frame with no lease.
244    ///
245    /// # Panics
246    ///
247    /// Panics when the producer rejects the transition, typically because the
248    /// frame was presented twice.
249    pub fn presented(&mut self) {
250        if let Some(lease) = self.lease.as_mut() {
251            lease.presented();
252        }
253    }
254
255    /// Returns the buffer to the producer and drops the frame's descriptors.
256    ///
257    /// # Panics
258    ///
259    /// Panics when a frame with no lease is given a release fence: there is no
260    /// producer to hand it to, so accepting it would silently discard it.
261    pub fn release(self, release_fence: Option<OwnedFd>) {
262        match self.lease {
263            Some(lease) => lease.release(release_fence),
264            None => assert!(
265                release_fence.is_none(),
266                "an unleased DMA-BUF frame does not accept a release fence"
267            ),
268        }
269    }
270}