voelin-media: the test pattern can arrive as DMA-BUFs, as the portal sends

The DMA-BUF path of a capture sink could only be driven by the ScreenCast
portal, which needs a person to answer its dialog. SyntheticScreen gains
with_dmabuf: it draws into a DMA-BUF of ordinary memory (a sealed memfd
shared through /dev/udmabuf, LINEAR XR24) and offers it to sinks that
take DMA-BUFs, as the portal does; a sink that declines gets the same
memory as a frame. Without /dev/udmabuf it says why and draws into
memory as before.

The udmabuf code moves from the encoder's test into capture/dmabuf.rs
(Udmabuf), which the test now uses as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 07:37:49 +03:00
1 parent a1dae8565d
commit 1bf305cf3c
4 files changed
+253 -83

No files matched your search

+90 -2
View File
@@ -1,11 +1,13 @@
//! CPU access to LINEAR DMA-BUFs (screen capture buffers a compositor
//! shares): a read-only mapping, and `DMA_BUF_IOCTL_SYNC` around each read
//! so caches are coherent with what the GPU wrote. Tiled buffers cannot be
//! read like this; they need a GPU import (not done here).
//! read like this; they go to the GPU (`ffmpeg::GpuConverter`). Also
//! DMA-BUFs of ordinary memory ([`Udmabuf`]), to drive that path without a
//! compositor.
#![allow(unsafe_code)]
use std::io;
use std::os::fd::{BorrowedFd, RawFd};
use std::os::fd::{BorrowedFd, OwnedFd, RawFd};
use memmap2::{Mmap, MmapOptions};
@@ -21,6 +23,92 @@ const DMA_BUF_SYNC_END: u64 = 1 << 2;
/// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`.
const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::<DmaBufSync>(b'b', 0);
/// `struct udmabuf_create` of `<linux/udmabuf.h>`; `UDMABUF_CREATE` returns
/// the new DMA-BUF.
#[repr(C)]
struct UdmabufCreate {
memfd: u32,
flags: u32,
offset: u64,
size: u64,
}
/// `UDMABUF_FLAGS_CLOEXEC`.
const UDMABUF_CLOEXEC: u32 = 1;
// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) only
// reads the struct and returns a new descriptor.
unsafe impl rustix::ioctl::Ioctl for UdmabufCreate {
type Output = OwnedFd;
const IS_MUTATING: bool = false;
fn opcode(&self) -> rustix::ioctl::Opcode {
rustix::ioctl::opcode::write::<UdmabufCreate>(b'u', 0x42)
}
fn as_ptr(&mut self) -> *mut std::ffi::c_void {
(&raw mut *self).cast()
}
unsafe fn output_from_ptr(
out: rustix::ioctl::IoctlOutput,
_: *mut std::ffi::c_void,
) -> rustix::io::Result<OwnedFd> {
// SAFETY: the descriptor the kernel just made, ours to own.
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) })
}
}
/// A DMA-BUF of ordinary memory that the CPU writes into: a sealed memfd
/// shared through `/dev/udmabuf` (LINEAR rows, any pitch). What a
/// compositor that renders on the CPU hands over, and the way to drive the
/// DMA-BUF path without one (the test pattern's
/// [`with_dmabuf`](super::synthetic::SyntheticScreen::with_dmabuf)). Needs
/// read and write access to `/dev/udmabuf`.
pub(crate) struct Udmabuf {
map: memmap2::MmapMut,
dmabuf: OwnedFd,
}
impl Udmabuf {
/// A buffer of at least `len` bytes (whole pages).
pub fn new(len: usize) -> io::Result<Self> {
use rustix::fs::{MemfdFlags, SealFlags};
let len = len.max(1).next_multiple_of(4096);
let flags = MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING;
let memfd = std::fs::File::from(rustix::fs::memfd_create("voelin-udmabuf", flags)?);
memfd.set_len(len as u64)?;
// udmabuf only takes memory that cannot shrink under it.
rustix::fs::fcntl_add_seals(&memfd, SealFlags::SHRINK)?;
let device = std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf")?;
let create = UdmabufCreate {
memfd: std::os::fd::AsRawFd::as_raw_fd(&memfd) as u32,
flags: UDMABUF_CLOEXEC,
offset: 0,
size: len as u64,
};
// SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf.
let dmabuf = unsafe { rustix::ioctl::ioctl(&device, create) }?;
// SAFETY: our own sealed memfd, which nothing else writes or
// truncates; the mapping keeps its pages after the file is closed.
let map = unsafe { memmap2::MmapOptions::new().len(len).map_mut(&memfd) }?;
Ok(Self { map, dmabuf })
}
pub fn fd(&self) -> RawFd {
std::os::fd::AsRawFd::as_raw_fd(&self.dmabuf)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn bytes_mut(&mut self) -> &mut [u8] {
&mut self.map
}
}
/// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a
/// DMA-BUF answers with its buffer object's size without moving anything).
pub(crate) fn size_of(fd: RawFd) -> Option<usize> {
+1 -1
View File
@@ -28,7 +28,7 @@ use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
#[cfg(all(target_os = "linux", feature = "pipewire"))]
mod dmabuf;
pub(crate) mod dmabuf;
pub mod external;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
+150 -10
View File
@@ -6,8 +6,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture,
SourceId, Ticker, Worker,
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, DmaBufRef, FrameSink, QueueSink,
ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::{FrameReceiver, frame_channel};
@@ -224,6 +224,7 @@ pub struct SyntheticScreen {
pattern: Pattern,
desktop: Option<Arc<Desktop>>,
worker: Option<Worker>,
dmabuf: bool,
}
impl SyntheticScreen {
@@ -236,7 +237,18 @@ impl SyntheticScreen {
let (width, height) = (width.max(16), height.max(16));
let desktop = (pattern == Pattern::Desktop)
.then(|| Arc::new(Desktop::render(width as usize, height as usize)));
Self { width, height, pattern, desktop, worker: None }
Self { width, height, pattern, desktop, worker: None, dmabuf: false }
}
/// Draw into a DMA-BUF of ordinary memory and offer it to sinks that
/// take DMA-BUFs ([`FrameSink::accepts_dmabuf`]) as a LINEAR `XR24`
/// buffer, as the ScreenCast portal does; sinks that do not, or decline
/// it, get the same memory as a frame. Linux with the `pipewire`
/// feature and access to `/dev/udmabuf`; elsewhere frames are handed
/// over as before.
pub fn with_dmabuf(mut self, enabled: bool) -> Self {
self.dmabuf = enabled;
self
}
pub fn pattern(&self) -> Pattern {
@@ -251,6 +263,7 @@ impl SyntheticScreen {
pattern: self.pattern,
desktop: self.desktop.clone(),
worker: None,
dmabuf: self.dmabuf,
}
}
@@ -268,8 +281,15 @@ impl SyntheticScreen {
/// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing
/// its memory.
pub fn render(&self, n: u64, out: &mut Vec<u8>) {
out.resize(self.width as usize * self.height as usize * 4, 0);
self.draw(n, out);
}
/// [`render`](Self::render) into the first `width * height * 4` bytes of
/// `out`.
fn draw(&self, n: u64, out: &mut [u8]) {
let (w, h) = (self.width as usize, self.height as usize);
out.resize(w * h * 4, 0);
let out = &mut out[..w * h * 4];
match &self.desktop {
Some(desktop) => desktop.draw(out, w, n as usize * 3),
None => {
@@ -349,17 +369,28 @@ impl ScreenCapture for SyntheticScreen {
let (width, height) = (pattern.width, pattern.height);
let mut fps = sink.max_fps();
let mut ticker = Ticker::new(fps);
let mut buffer = Vec::new();
let mut buffer = Buffer::new(&pattern);
let started = Instant::now();
let mut n = 0;
loop {
let timestamp = started.elapsed();
if sink.wants(timestamp) {
pattern.render(n, &mut buffer);
let plane = PlaneRef::new(&buffer, width as usize * 4);
let frame =
FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) };
if !sink.frame(frame) {
let bytes = buffer.bytes();
pattern.draw(n, bytes);
let taken = match buffer.dmabuf(&pattern, timestamp) {
Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame),
_ => None,
};
let more = taken.unwrap_or_else(|| {
let plane = PlaneRef::new(buffer.bytes(), width as usize * 4);
sink.frame(FrameRef {
width,
height,
timestamp,
pixels: PixelsRef::Bgra(plane),
})
});
if !more {
break;
}
n += 1;
@@ -382,6 +413,58 @@ impl ScreenCapture for SyntheticScreen {
}
}
/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary
/// memory ([`SyntheticScreen::with_dmabuf`]).
enum Buffer {
Memory(Vec<u8>),
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Dmabuf(super::dmabuf::Udmabuf),
}
impl Buffer {
fn new(pattern: &SyntheticScreen) -> Self {
let len = pattern.width as usize * pattern.height as usize * 4;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
if pattern.dmabuf {
match super::dmabuf::Udmabuf::new(len) {
Ok(buffer) => return Self::Dmabuf(buffer),
Err(e) => tracing::warn!("test pattern without DMA-BUFs (/dev/udmabuf): {e}"),
}
}
Self::Memory(vec![0; len])
}
fn bytes(&mut self) -> &mut [u8] {
match self {
Self::Memory(bytes) => bytes,
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Self::Dmabuf(buffer) => buffer.bytes_mut(),
}
}
/// The buffer as a LINEAR `XR24` DMA-BUF, if it is one.
fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option<DmaBufRef> {
match self {
Self::Memory(_) => {
let _ = (pattern, timestamp);
None
}
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Self::Dmabuf(buffer) => Some(DmaBufRef {
width: pattern.width,
height: pattern.height,
timestamp,
fourcc: super::drm_fourcc(b"XR24"),
modifier: super::DRM_MOD_LINEAR,
fd: buffer.fd(),
size: buffer.len(),
planes: [(0, pattern.width as usize * 4), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
}),
}
}
}
/// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers.
pub struct SineSource {
frequency: f32,
@@ -523,4 +606,61 @@ mod tests {
assert_eq!((buffer.channels, buffer.frames()), (2, 480));
tone.stop();
}
/// With DMA-BUFs, a sink that takes them gets the pattern as a LINEAR
/// `XR24` DMA-BUF that reads back as the pattern; one that declines it
/// gets the same picture as a frame.
#[cfg(all(target_os = "linux", feature = "pipewire"))]
#[tokio::test]
async fn the_pattern_as_dmabufs() {
use std::sync::mpsc;
/// Takes DMA-BUFs (or declines them) and reports what it got.
struct Sink {
take: bool,
got: mpsc::Sender<(bool, Vec<u8>)>,
}
impl FrameSink for Sink {
fn max_fps(&self) -> u32 {
50
}
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
let PixelsRef::Bgra(plane) = frame.pixels else { panic!("BGRA") };
self.got.send((false, plane.row(0, 64 * 4).to_vec())).is_ok()
}
fn accepts_dmabuf(&self) -> bool {
true
}
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
assert_eq!(frame.fourcc, crate::capture::drm_fourcc(b"XR24"));
assert_eq!((frame.width, frame.height, frame.planes[0].1), (64, 48, 256));
if !self.take {
return None;
}
let map = super::super::dmabuf::DmaBufMap::new(frame.fd, frame.size).unwrap();
let row = map.read(|bytes| bytes[..64 * 4].to_vec());
Some(self.got.send((true, row)).is_ok())
}
}
if !std::path::Path::new("/dev/udmabuf").exists() {
eprintln!("no /dev/udmabuf, skipped");
return;
}
let mut expected = Vec::new();
SyntheticScreen::new(64, 48).render(0, &mut expected);
for take in [true, false] {
let mut screen = SyntheticScreen::new(64, 48).with_dmabuf(true);
let (got, frames) = mpsc::channel();
let sink = Box::new(Sink { take, got });
screen
.start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink)
.await
.unwrap();
let (dmabuf, row) = frames.recv_timeout(Duration::from_secs(5)).unwrap();
screen.stop();
assert_eq!(dmabuf, take, "taken as a DMA-BUF");
assert_eq!(row, expected[..64 * 4], "the first row of frame 0");
}
}
}
+12 -70
View File
@@ -2335,9 +2335,9 @@ mod tests {
// The buffers: the driver's own (tiled), and a LINEAR one with a
// padded pitch in system memory, which is what the portal negotiates.
#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", feature = "pipewire"))]
let linear = linear_dmabuf(&picture, (SIZE.0 as usize * 4).next_multiple_of(256));
#[cfg(not(target_os = "linux"))]
#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
let linear: Option<((), DmaBufRef)> = None;
if linear.is_none() {
eprintln!("no /dev/udmabuf: the LINEAR buffer is skipped");
@@ -2402,91 +2402,33 @@ mod tests {
}
}
/// `struct udmabuf_create` of `<linux/udmabuf.h>`, and `UDMABUF_CREATE`
/// returning the new DMA-BUF.
#[cfg(target_os = "linux")]
#[repr(C)]
struct UdmabufCreate {
memfd: u32,
flags: u32,
offset: u64,
size: u64,
}
// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`)
// only reads the struct and returns a new descriptor.
#[cfg(target_os = "linux")]
unsafe impl rustix::ioctl::Ioctl for UdmabufCreate {
type Output = std::os::fd::OwnedFd;
const IS_MUTATING: bool = false;
fn opcode(&self) -> rustix::ioctl::Opcode {
rustix::ioctl::opcode::write::<UdmabufCreate>(b'u', 0x42)
}
fn as_ptr(&mut self) -> *mut std::ffi::c_void {
(&raw mut *self).cast()
}
unsafe fn output_from_ptr(
out: rustix::ioctl::IoctlOutput,
_: *mut std::ffi::c_void,
) -> rustix::io::Result<Self::Output> {
// SAFETY: the descriptor the kernel just made, ours to own.
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) })
}
}
/// `picture` (BGRA) in a LINEAR DMA-BUF of system memory, rows `stride`
/// bytes apart: `/dev/udmabuf` over a sealed memfd. The descriptor has
/// to outlive the returned buffer. `None` without access to
/// `picture` (BGRA) in a LINEAR DMA-BUF of ordinary memory, rows
/// `stride` bytes apart ([`Udmabuf`](crate::capture::dmabuf::Udmabuf));
/// the buffer has to outlive the reference. `None` without access to
/// `/dev/udmabuf`.
#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", feature = "pipewire"))]
fn linear_dmabuf(
picture: &VideoFrame,
stride: usize,
) -> Option<(std::os::fd::OwnedFd, DmaBufRef)> {
use rustix::fs::{MemfdFlags, SealFlags};
use std::io::Write;
use std::os::fd::AsRawFd;
) -> Option<(crate::capture::dmabuf::Udmabuf, DmaBufRef)> {
let FrameData::Bgra(pixels) = &picture.data else { return None };
let (w, h) = (picture.width as usize, picture.height as usize);
let size = (stride * h).next_multiple_of(4096);
let memfd = rustix::fs::memfd_create(
"voelin-linear-dmabuf",
MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
)
.ok()?;
let mut bytes = vec![0; size];
for (y, row) in bytes.chunks_exact_mut(stride).take(h).enumerate() {
let mut buffer = crate::capture::dmabuf::Udmabuf::new(stride * h).ok()?;
for (y, row) in buffer.bytes_mut().chunks_exact_mut(stride).take(h).enumerate() {
row[..w * 4].copy_from_slice(pixels.row(y, w * 4));
}
let mut file = std::fs::File::from(memfd);
file.write_all(&bytes).ok()?;
rustix::fs::fcntl_add_seals(&file, SealFlags::SHRINK).ok()?;
let device =
std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf").ok()?;
let create = UdmabufCreate {
memfd: file.as_raw_fd() as u32,
flags: 1,
offset: 0,
size: size as u64,
};
// SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf.
let fd = unsafe { rustix::ioctl::ioctl(&device, create) }.ok()?;
let frame = DmaBufRef {
width: picture.width,
height: picture.height,
timestamp: Duration::ZERO,
fourcc: drm_fourcc(b"XR24"),
modifier: crate::capture::DRM_MOD_LINEAR,
fd: fd.as_raw_fd(),
size,
fd: buffer.fd(),
size: buffer.len(),
planes: [(0, stride), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
Some((fd, frame))
Some((buffer, frame))
}
/// What the CPU spends per frame on its way into a VA-API encoder at