Skip to main content

video_interop/
dmabuf.rs

1use std::{
2    collections::BTreeSet,
3    os::fd::{OwnedFd, RawFd},
4};
5
6use crate::{
7    DmaBufAllocationSizeError, DuplicateError, Modifier, ValidationError, duplicate_fd_cloexec,
8};
9
10#[cfg(not(target_os = "linux"))]
11use libc::{fstat, lseek, stat as Stat};
12#[cfg(target_os = "linux")]
13use libc::{fstat64 as fstat, lseek64 as lseek, stat64 as Stat};
14
15pub const AV_DRM_MAX_ENTRIES: usize = 4;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub(crate) struct DmaBufProbe {
19    pub device: u64,
20    pub inode: u64,
21    pub allocation_size: u64,
22}
23
24/// Returns the complete allocation size exposed by a DMA-BUF fd.
25///
26/// This is not a visible image or plane span. The allocation size includes any exporter alignment
27/// padding outside the final addressable plane byte. A descriptor must report the complete size
28/// returned by the fd.
29pub fn dmabuf_allocation_size(fd: RawFd) -> Result<u64, DmaBufAllocationSizeError> {
30    probe_dmabuf(fd).map(|probe| probe.allocation_size)
31}
32
33pub(crate) fn probe_dmabuf(fd: RawFd) -> Result<DmaBufProbe, DmaBufAllocationSizeError> {
34    // Keep inode identities and file offsets 64-bit on 32-bit Linux too.
35    let mut stat = std::mem::MaybeUninit::<Stat>::zeroed();
36    // SAFETY: `stat` points to writable storage and this call does not take ownership of `fd`.
37    if unsafe { fstat(fd, stat.as_mut_ptr()) } != 0 {
38        return Err(DmaBufAllocationSizeError::Stat(
39            std::io::Error::last_os_error(),
40        ));
41    }
42    // SAFETY: fstat initialized the complete structure after returning success.
43    let stat = unsafe { stat.assume_init() };
44
45    // Linux DMA-BUF exporters expose their complete allocation through SEEK_END. Preserve the
46    // shared file position when this fd also supports SEEK_CUR/SEEK_SET.
47    let original_position = unsafe { lseek(fd, 0, libc::SEEK_CUR) };
48    let allocation_end = unsafe { lseek(fd, 0, libc::SEEK_END) };
49    let seek_error = (allocation_end < 0).then(std::io::Error::last_os_error);
50    if original_position >= 0 && unsafe { lseek(fd, original_position, libc::SEEK_SET) } < 0 {
51        return Err(DmaBufAllocationSizeError::Restore(
52            std::io::Error::last_os_error(),
53        ));
54    }
55    if let Some(error) = seek_error {
56        return Err(DmaBufAllocationSizeError::Seek(error));
57    }
58
59    let allocation_size =
60        u64::try_from(allocation_end).expect("a non-negative off64_t always fits in u64");
61    if allocation_size == 0 {
62        return Err(DmaBufAllocationSizeError::Zero);
63    }
64    if stat.st_size < 0 {
65        return Err(DmaBufAllocationSizeError::NegativeStat(stat.st_size));
66    }
67    if stat.st_size > 0 {
68        let stat_size = u64::try_from(stat.st_size).expect("a positive off64_t always fits in u64");
69        if stat_size != allocation_size {
70            return Err(DmaBufAllocationSizeError::ProbeMismatch {
71                stat: stat_size,
72                seek_end: allocation_size,
73            });
74        }
75    }
76
77    Ok(DmaBufProbe {
78        #[allow(clippy::unnecessary_cast)] // dev_t is signed 32-bit on macOS, u64 on Linux.
79        device: stat.st_dev as u64,
80        inode: stat.st_ino,
81        allocation_size,
82    })
83}
84
85#[derive(Clone, Debug)]
86#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
87#[cfg_attr(feature = "rustler", module = "VideoInterop.DMABuf.Object")]
88pub struct Object {
89    pub fd: i32,
90    pub size: u64,
91    pub modifier: Modifier,
92}
93
94#[derive(Clone, Debug, PartialEq, Eq)]
95#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
96#[cfg_attr(feature = "rustler", module = "VideoInterop.DMABuf.Plane")]
97pub struct Plane {
98    pub object_index: u32,
99    pub offset: u64,
100    pub pitch: u32,
101}
102
103#[derive(Clone, Debug, PartialEq, Eq)]
104#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
105#[cfg_attr(feature = "rustler", rustler(encode))]
106#[cfg_attr(feature = "rustler", module = "VideoInterop.DMABuf.Layer")]
107pub struct Layer {
108    pub fourcc: u32,
109    pub planes: Vec<Plane>,
110}
111
112#[derive(Clone, Debug)]
113#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
114#[cfg_attr(feature = "rustler", rustler(encode))]
115#[cfg_attr(feature = "rustler", module = "VideoInterop.DMABuf.Descriptor")]
116pub struct Descriptor {
117    pub version: u32,
118    pub objects: Vec<Object>,
119    pub layers: Vec<Layer>,
120}
121
122#[derive(Debug)]
123pub struct OwnedObject {
124    pub fd: OwnedFd,
125    pub size: u64,
126    pub modifier: Modifier,
127}
128
129#[derive(Debug)]
130pub struct OwnedDescriptor {
131    pub version: u32,
132    pub objects: Vec<OwnedObject>,
133    pub layers: Vec<Layer>,
134}
135
136impl Descriptor {
137    pub fn validate(&self) -> Result<(), ValidationError> {
138        if self.version != 1 {
139            return Err(ValidationError::UnsupportedDescriptorVersion(self.version));
140        }
141        if self.objects.is_empty() {
142            return Err(ValidationError::EmptyObjects);
143        }
144        if self.objects.len() > AV_DRM_MAX_ENTRIES {
145            return Err(ValidationError::TooManyEntries {
146                kind: "objects",
147                actual: self.objects.len(),
148                maximum: AV_DRM_MAX_ENTRIES,
149            });
150        }
151        if self.layers.is_empty() {
152            return Err(ValidationError::EmptyLayers);
153        }
154        if self.layers.len() > AV_DRM_MAX_ENTRIES {
155            return Err(ValidationError::TooManyEntries {
156                kind: "layers",
157                actual: self.layers.len(),
158                maximum: AV_DRM_MAX_ENTRIES,
159            });
160        }
161
162        for (index, object) in self.objects.iter().enumerate() {
163            if object.fd < 0 {
164                return Err(ValidationError::NegativeFd {
165                    index,
166                    fd: object.fd,
167                });
168            }
169            if object.size == 0 {
170                return Err(ValidationError::ZeroObjectSize { index });
171            }
172        }
173
174        for (layer_index, layer) in self.layers.iter().enumerate() {
175            if layer.fourcc == 0 {
176                return Err(ValidationError::InvalidFourcc { index: layer_index });
177            }
178            if layer.planes.is_empty() {
179                return Err(ValidationError::EmptyPlanes { index: layer_index });
180            }
181            if layer.planes.len() > AV_DRM_MAX_ENTRIES {
182                return Err(ValidationError::TooManyEntries {
183                    kind: "planes in one layer",
184                    actual: layer.planes.len(),
185                    maximum: AV_DRM_MAX_ENTRIES,
186                });
187            }
188
189            for (plane_index, plane) in layer.planes.iter().enumerate() {
190                if plane.pitch == 0 {
191                    return Err(ValidationError::ZeroPitch {
192                        layer: layer_index,
193                        plane: plane_index,
194                    });
195                }
196
197                let object = self.objects.get(plane.object_index as usize).ok_or(
198                    ValidationError::InvalidObjectIndex {
199                        layer: layer_index,
200                        plane: plane_index,
201                        object_index: plane.object_index,
202                        object_count: self.objects.len(),
203                    },
204                )?;
205
206                if plane.offset >= object.size {
207                    return Err(ValidationError::PlaneOffsetOutOfBounds {
208                        layer: layer_index,
209                        plane: plane_index,
210                        object_index: plane.object_index,
211                        offset: plane.offset,
212                        object_size: object.size,
213                    });
214                }
215            }
216        }
217
218        let total_planes = self.layers.iter().map(|layer| layer.planes.len()).sum();
219        if total_planes > AV_DRM_MAX_ENTRIES {
220            return Err(ValidationError::TooManyPlanes {
221                actual: total_planes,
222                maximum: AV_DRM_MAX_ENTRIES,
223            });
224        }
225
226        let referenced = self
227            .layers
228            .iter()
229            .flat_map(|layer| layer.planes.iter())
230            .map(|plane| plane.object_index as usize)
231            .collect::<BTreeSet<_>>();
232        if let Some(index) = (0..self.objects.len()).find(|index| !referenced.contains(index)) {
233            return Err(ValidationError::UnreferencedObject { index });
234        }
235
236        Ok(())
237    }
238
239    pub fn duplicate_cloexec(&self) -> Result<OwnedDescriptor, DuplicateError> {
240        self.duplicate_with(duplicate_fd_cloexec)
241    }
242
243    fn duplicate_with<F>(&self, mut duplicate: F) -> Result<OwnedDescriptor, DuplicateError>
244    where
245        F: FnMut(i32) -> std::io::Result<OwnedFd>,
246    {
247        self.validate()?;
248
249        let objects = self
250            .objects
251            .iter()
252            .enumerate()
253            .map(|(index, object)| {
254                duplicate(object.fd)
255                    .map(|fd| OwnedObject {
256                        fd,
257                        size: object.size,
258                        modifier: object.modifier,
259                    })
260                    .map_err(|source| DuplicateError::DuplicateObjectFd {
261                        index,
262                        fd: object.fd,
263                        source,
264                    })
265            })
266            .collect::<Result<Vec<_>, _>>()?;
267
268        Ok(OwnedDescriptor {
269            version: self.version,
270            objects,
271            layers: self.layers.clone(),
272        })
273    }
274}
275
276#[cfg(feature = "rustler")]
277mod rustler_impl {
278    use rustler::{Atom, Decoder, Error, ListIterator, NifResult, Term};
279
280    use super::{AV_DRM_MAX_ENTRIES, Descriptor, Layer};
281
282    mod atoms {
283        rustler::atoms! {
284            atom_struct = "__struct__",
285            version,
286            objects,
287            layers,
288            fourcc,
289            planes
290        }
291    }
292
293    impl<'a> Decoder<'a> for Layer {
294        fn decode(term: Term<'a>) -> NifResult<Self> {
295            ensure_struct(term, "Elixir.VideoInterop.DMABuf.Layer")?;
296
297            Ok(Self {
298                fourcc: term.map_get(atoms::fourcc())?.decode()?,
299                planes: decode_bounded_list(term.map_get(atoms::planes())?)?,
300            })
301        }
302    }
303
304    impl<'a> Decoder<'a> for Descriptor {
305        fn decode(term: Term<'a>) -> NifResult<Self> {
306            ensure_struct(term, "Elixir.VideoInterop.DMABuf.Descriptor")?;
307
308            Ok(Self {
309                version: term.map_get(atoms::version())?.decode()?,
310                objects: decode_bounded_list(term.map_get(atoms::objects())?)?,
311                layers: decode_bounded_list(term.map_get(atoms::layers())?)?,
312            })
313        }
314    }
315
316    fn ensure_struct(term: Term<'_>, module: &str) -> NifResult<()> {
317        let actual: Atom = term.map_get(atoms::atom_struct())?.decode()?;
318        let expected = Atom::from_str(term.get_env(), module)?;
319
320        if actual == expected {
321            Ok(())
322        } else {
323            Err(Error::BadArg)
324        }
325    }
326
327    fn decode_bounded_list<'a, T>(term: Term<'a>) -> NifResult<Vec<T>>
328    where
329        T: Decoder<'a>,
330    {
331        let iterator: ListIterator<'a> = term.decode()?;
332        let mut values = Vec::with_capacity(AV_DRM_MAX_ENTRIES);
333
334        for item in iterator {
335            if values.len() == AV_DRM_MAX_ENTRIES {
336                return Err(Error::BadArg);
337            }
338            values.push(item.decode()?);
339        }
340
341        Ok(values)
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use std::io;
348    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
349
350    use super::{Descriptor, Layer, Modifier, Object, Plane, dmabuf_allocation_size};
351    use crate::{DmaBufAllocationSizeError, duplicate_fd_cloexec};
352
353    #[cfg(target_os = "linux")]
354    fn memfd(size: i64) -> OwnedFd {
355        let raw =
356            unsafe { libc::memfd_create(c"video-interop-size-test".as_ptr(), libc::MFD_CLOEXEC) };
357        assert!(raw >= 0);
358        assert_eq!(unsafe { libc::ftruncate64(raw, size) }, 0);
359        // SAFETY: memfd_create returned one owned descriptor.
360        unsafe { OwnedFd::from_raw_fd(raw) }
361    }
362
363    #[cfg(not(target_os = "linux"))]
364    fn memfd(size: i64) -> OwnedFd {
365        let path = std::env::temp_dir().join("video-interop-size-XXXXXX");
366        let mut template = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
367            .unwrap()
368            .into_bytes_with_nul();
369        let raw = unsafe { libc::mkstemp(template.as_mut_ptr().cast()) };
370        assert!(raw >= 0);
371        let fd = unsafe { OwnedFd::from_raw_fd(raw) };
372        assert_eq!(unsafe { libc::unlink(template.as_ptr().cast()) }, 0);
373        assert_eq!(unsafe { libc::ftruncate(fd.as_raw_fd(), size) }, 0);
374        fd
375    }
376
377    #[test]
378    fn allocation_size_reports_complete_size_and_restores_position() {
379        let fd = memfd(4_096);
380        assert_eq!(
381            unsafe { super::lseek(fd.as_raw_fd(), 17, libc::SEEK_SET) },
382            17
383        );
384
385        assert_eq!(dmabuf_allocation_size(fd.as_raw_fd()).unwrap(), 4_096);
386        assert_eq!(
387            unsafe { super::lseek(fd.as_raw_fd(), 0, libc::SEEK_CUR) },
388            17
389        );
390    }
391
392    #[test]
393    fn allocation_size_and_identity_preserve_large_file_values() {
394        use std::os::unix::fs::MetadataExt;
395
396        let position = i64::from(i32::MAX) + 1;
397        let size = position + 4096;
398        // ftruncate64 creates a sparse memfd; no multi-gigabyte buffer is allocated.
399        let fd = memfd(size);
400        assert_eq!(
401            unsafe { super::lseek(fd.as_raw_fd(), position, libc::SEEK_SET) },
402            position
403        );
404
405        let probe = super::probe_dmabuf(fd.as_raw_fd()).unwrap();
406        assert_eq!(probe.allocation_size, size as u64);
407        assert_eq!(
408            unsafe { super::lseek(fd.as_raw_fd(), 0, libc::SEEK_CUR) },
409            position
410        );
411
412        let metadata = std::fs::File::from(fd).metadata().unwrap();
413        assert_eq!(probe.device, metadata.dev());
414        assert_eq!(probe.inode, metadata.ino());
415    }
416
417    #[test]
418    fn allocation_size_rejects_zero_and_nonseekable_fds() {
419        let empty = memfd(0);
420        assert!(matches!(
421            dmabuf_allocation_size(empty.as_raw_fd()),
422            Err(DmaBufAllocationSizeError::Zero)
423        ));
424
425        let (read, _write) = std::os::unix::net::UnixStream::pair().unwrap();
426        assert!(matches!(
427            dmabuf_allocation_size(read.as_raw_fd()),
428            Err(DmaBufAllocationSizeError::Seek(_))
429        ));
430    }
431
432    #[test]
433    fn closes_earlier_duplicates_when_a_later_duplicate_fails() {
434        let (read, write) = std::os::unix::net::UnixStream::pair().unwrap();
435
436        let descriptor = Descriptor {
437            version: 1,
438            objects: vec![
439                Object {
440                    fd: write.as_raw_fd(),
441                    size: 4096,
442                    modifier: Modifier::Implicit,
443                },
444                Object {
445                    fd: write.as_raw_fd(),
446                    size: 4096,
447                    modifier: Modifier::Implicit,
448                },
449            ],
450            layers: vec![Layer {
451                fourcc: u32::from_le_bytes(*b"XR24"),
452                planes: vec![
453                    Plane {
454                        object_index: 0,
455                        offset: 0,
456                        pitch: 256,
457                    },
458                    Plane {
459                        object_index: 1,
460                        offset: 0,
461                        pitch: 256,
462                    },
463                ],
464            }],
465        };
466
467        let mut calls = 0;
468        let result = descriptor.duplicate_with(|fd| {
469            calls += 1;
470            if calls == 2 {
471                Err(io::Error::other("injected duplicate failure"))
472            } else {
473                duplicate_fd_cloexec(fd)
474            }
475        });
476
477        assert!(result.is_err());
478        assert_eq!(calls, 2);
479        drop(write);
480
481        let mut byte = 0_u8;
482        // SAFETY: read points to one writable byte and the pipe read descriptor is still owned.
483        let read_count =
484            unsafe { libc::read(read.as_raw_fd(), std::ptr::addr_of_mut!(byte).cast(), 1) };
485        assert_eq!(
486            read_count, 0,
487            "the failed operation leaked a duplicated write fd"
488        );
489    }
490}