From cd1ccff6d1f7bd644bd6fcf323c0f8610aa4827a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:02:36 +0000 Subject: [PATCH] voelin-media: DMA-BUF import into VA-API encoders, up to the GPU conversion FfmpegEncoder::encode_dmabuf maps a DRM PRIME frame onto a VA-API surface (av_hwframe_map) that the encoder reads without a copy. It needs AVFrame.buf[0] and AVFrame.hw_frames_ctx, which have no accessor: their offsets come from a table per libavutil major, buf[0] is checked on a real frame at load and hw_frames_ctx on the encoder's first surface. Only NV12 buffers are taken: screen capture delivers RGB, which needs a colour conversion on the GPU (VA-API video processing) that is not implemented; anything else is refused as unavailable so the caller maps the buffer as before. On the capture side, FrameSink::accepts_dmabuf / dmabuf let the portal hand a buffer over before mapping it (and pass tiled ones through). No sink accepts yet, and the portal still negotiates LINEAR buffers only. The encoder ends its stream when dropped (SVT-AV1 logs an error otherwise). Untested on a GPU: this machine has no render node. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-media/src/capture/mod.rs | 48 ++++++ crates/voelin-media/src/capture/portal.rs | 39 ++++- crates/voelin-media/src/ffmpeg/encoder.rs | 189 ++++++++++++++++++++-- crates/voelin-media/src/ffmpeg/layout.rs | 1 - crates/voelin-media/src/ffmpeg/mod.rs | 1 - crates/voelin-media/src/ffmpeg/sys.rs | 2 + crates/voelin-media/tests/ffmpeg.rs | 27 ++++ 7 files changed, 286 insertions(+), 21 deletions(-) diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index f37ee4d..b4ccc1a 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -110,6 +110,54 @@ pub trait FrameSink: Send { /// One frame. Its pixels are only valid during the call. Returns /// `false` when no more frames are wanted; the backend then stops. fn frame(&mut self, frame: FrameRef<'_>) -> bool; + + /// Whether the sink takes frames that are still in a DMA-BUF (GPU + /// memory) through [`dmabuf`](Self::dmabuf), e.g. for a VA-API encoder + /// that imports them without a copy + /// (`ffmpeg::FfmpegEncoder::encode_dmabuf`). Backends that capture into + /// DMA-BUFs (the portal) then offer the buffer before mapping it. + fn accepts_dmabuf(&self) -> bool { + false + } + + /// A frame in a DMA-BUF, valid during the call. `None`: not taken, the + /// backend maps it and calls [`frame`](Self::frame); `Some(more)` as the + /// result of `frame`. + fn dmabuf(&mut self, frame: &DmaBufRef) -> Option { + let _ = frame; + None + } +} + +/// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`. +pub const fn drm_fourcc(code: &[u8; 4]) -> u32 { + code[0] as u32 | (code[1] as u32) << 8 | (code[2] as u32) << 16 | (code[3] as u32) << 24 +} + +/// `DRM_FORMAT_MOD_LINEAR`. +pub const DRM_MOD_LINEAR: u64 = 0; +/// `DRM_FORMAT_MOD_INVALID`: the driver's implicit layout. +pub const DRM_MOD_INVALID: u64 = 0x00ff_ffff_ffff_ffff; + +/// A captured frame still in a DMA-BUF: one buffer object (a file +/// descriptor borrowed for the call) with one plane per `planes` entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DmaBufRef { + pub width: u32, + pub height: u32, + /// As [`VideoFrame::timestamp`]. + pub timestamp: Duration, + /// DRM format (`drm_fourcc(b"XR24")` for BGRx, `b"NV12"`, ...). + pub fourcc: u32, + /// DRM format modifier (tiling); [`DRM_MOD_LINEAR`] for rows in memory + /// order. + pub modifier: u64, + pub fd: i32, + /// Size of the buffer object in bytes. + pub size: usize, + /// `(offset, stride)` of each plane in the buffer object. + pub planes: [(usize, usize); 4], + pub plane_count: usize, } /// Keeps frames of a source for a frame-rate cap, by their timestamps, so diff --git a/crates/voelin-media/src/capture/portal.rs b/crates/voelin-media/src/capture/portal.rs index ea42eab..7fecbd2 100644 --- a/crates/voelin-media/src/capture/portal.rs +++ b/crates/voelin-media/src/capture/portal.rs @@ -34,7 +34,8 @@ use tracing::{debug, warn}; use crate::capture::dmabuf::DmaBufMap; use crate::capture::pw::{PwThread, pod, serialize}; use crate::capture::{ - BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId, + BoxFuture, CaptureOptions, CaptureSource, DRM_MOD_LINEAR, DmaBufRef, FrameSink, QueueSink, + ScreenCapture, SourceId, drm_fourcc, }; use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame}; use crate::queue::FrameReceiver; @@ -524,8 +525,8 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { } let Some(mut buffer) = stream.dequeue_buffer() else { return }; let Some(format) = state.format else { return }; - if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) { - // Tiled: the CPU cannot read it (we never offer that). + if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) && !state.sink.accepts_dmabuf() { + // Tiled: the CPU cannot read it (we only offer LINEAR). return; } let timestamp = state.started.elapsed(); @@ -564,6 +565,38 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) { state.logged = Some(is_dmabuf); debug!(dmabuf = is_dmabuf, "screen capture buffers"); } + // A sink that imports DMA-BUFs (a VA-API encoder) gets the buffer as it + // is, without a mapping or copy. + if is_dmabuf && state.sink.accepts_dmabuf() { + let raw = data.as_raw(); + let fourcc = match format.format { + VideoFormat::BGRx => drm_fourcc(b"XR24"), + VideoFormat::BGRA => drm_fourcc(b"AR24"), + VideoFormat::RGBx => drm_fourcc(b"XB24"), + _ => drm_fourcc(b"AB24"), + }; + let frame = DmaBufRef { + width: format.width, + height: format.height, + timestamp, + fourcc, + modifier: format.modifier.map_or(DRM_MOD_LINEAR, |m| m as u64), + fd: data.fd(), + size: (raw.mapoffset + raw.maxsize) as usize, + planes: [(raw.mapoffset as usize + offset, stride), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + }; + if let Some(more) = state.sink.dmabuf(&frame) { + if !more && let Some(mainloop) = state.mainloop.upgrade() { + mainloop.quit(); + } + return; + } + } + if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) { + // Tiled and not taken as it is: nothing the CPU can read. + return; + } let started = Instant::now(); let more = if is_dmabuf { let raw = data.as_raw(); diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 4b13d4e..cdd1918 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -18,6 +18,7 @@ use std::time::Duration; use super::layout::{self, HwFramesFields}; use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr}; use super::{Ffmpeg, take_log}; +use crate::capture::{DmaBufRef, drm_fourcc}; use crate::codec::hw::EncoderFactory; use crate::codec::{ Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, H264Profile, @@ -493,6 +494,8 @@ pub struct FfmpegEncoder { reinit: Reinit, /// VA-API only offers the low-power entry point for this codec. low_power: bool, + /// `AVFrame.hw_frames_ctx` was checked on a surface of this encoder. + dmabuf_checked: bool, } impl FfmpegEncoder { @@ -505,7 +508,15 @@ impl FfmpegEncoder { })?; let ffmpeg = Ffmpeg::get() .map_err(|e| Error::CodecUnavailable { codec: spec.codec, reason: e.to_owned() })?; - Ok(Self { ffmpeg, spec, config, session: None, reinit: Reinit::No, low_power: false }) + Ok(Self { + ffmpeg, + spec, + config, + session: None, + reinit: Reinit::No, + low_power: false, + dmabuf_checked: false, + }) } pub fn spec(&self) -> &'static BackendSpec { @@ -873,13 +884,16 @@ impl FfmpegEncoder { Ok(keyframe) } - fn encode_i420( + /// The session for a `width` x `height` frame, opened anew when the size + /// changed or a reinit is due; whether the frame must be a keyframe. + fn prepare( &mut self, - frame: &VideoFrame, + width: u32, + height: u32, force_keyframe: bool, out: &mut dyn FnMut(EncodedChunk<'_>), - ) -> Result<()> { - let (w, h) = Self::coded_size(frame.width, frame.height); + ) -> Result<(Session, bool)> { + let (w, h) = Self::coded_size(width, height); let mut force = force_keyframe; let reopen = match &self.session { None => true, @@ -902,12 +916,154 @@ impl FfmpegEncoder { self.reinit = Reinit::No; force = true; } - let mut session = self.session.take().expect("opened above"); + Ok((self.session.take().expect("opened above"), force)) + } + + fn encode_i420( + &mut self, + frame: &VideoFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; let result = self.encode_in(&mut session, frame, force, out); self.session = Some(session); result } + /// Encode a frame that is still in a DMA-BUF, without a copy: the buffer + /// becomes a VA-API surface (`av_hwframe_map` of a DRM PRIME frame) that + /// the encoder reads directly. + /// + /// VA-API backends and NV12 buffers only: the RGB frames screen capture + /// delivers first need a colour conversion on the GPU (VA-API video + /// processing), which is not implemented. Anything else fails with + /// `Error::CodecUnavailable`; callers then map the buffer and use + /// [`encode_with`](VideoEncoder::encode_with). The buffer must stay + /// unchanged until this frame's packet came out (the encoder reads it + /// asynchronously, one frame deep). + pub fn encode_dmabuf( + &mut self, + frame: &DmaBufRef, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + if !self.spec.is_vaapi() { + return Err(self.unavailable(format!("{} does not import DMA-BUFs", self.spec.name))); + } + if frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2 { + return Err(self.unavailable( + "only NV12 DMA-BUFs are imported (RGB needs GPU colour conversion)".into(), + )); + } + if Self::coded_size(frame.width, frame.height) != (frame.width, frame.height) { + return Err(self.unavailable("odd frame size".into())); + } + let refs = self.ffmpeg.frame_refs.clone().map_err(|e| self.unavailable(e))?; + let drm_prime = + self.ffmpeg.pix.drm_prime.ok_or_else(|| self.unavailable("no DRM PRIME".into()))?; + let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API".into()))?; + let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?; + let result = self.import_and_send(&mut session, frame, force, refs, drm_prime, vaapi, out); + self.session = Some(session); + result + } + + #[allow(clippy::too_many_arguments)] // the parts of one import + fn import_and_send( + &mut self, + session: &mut Session, + frame: &DmaBufRef, + force: bool, + refs: layout::FrameRefs, + drm_prime: c_int, + vaapi: c_int, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let api = &self.ffmpeg.api; + if !self.dmabuf_checked { + // The table's AVFrame.hw_frames_ctx must be where FFmpeg puts + // the pool of a surface it allocates. + // SAFETY: `hw` is our frame, the pool the session's. + let ok = unsafe { + let ret = (api.av_hwframe_get_buffer)(session.pool, session.hw, 0); + let ok = ret >= 0 && layout::check_hw_frames_ctx(session.hw, session.pool, refs); + (api.av_frame_unref)(session.hw); + ok + }; + if !ok { + return Err(self.unavailable("AVFrame.hw_frames_ctx check failed".into())); + } + self.dmabuf_checked = true; + } + let mut descriptor = + sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() }; + descriptor.objects[0] = + sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier }; + descriptor.layers[0].format = frame.fourcc; + descriptor.layers[0].nb_planes = frame.plane_count as c_int; + for (plane, &(offset, pitch)) in + descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count]) + { + *plane = + sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize }; + } + let pts = + self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64); + // SAFETY: the descriptor lives in a buffer the source frame owns + // (buf[0], checked offset), so FFmpeg can keep it while mapped; the + // destination frame gets a reference to the pool at the checked + // hw_frames_ctx offset; av_frame_free / av_frame_unref release both. + unsafe { + let mut buffer = (api.av_buffer_allocz)(std::mem::size_of::()); + let mut src = (api.av_frame_alloc)(); + if buffer.is_null() || src.is_null() { + (api.av_buffer_unref)(&mut buffer); + (api.av_frame_free)(&mut src); + return Err(self.unavailable("out of memory".into())); + } + let data = (*buffer.cast::()).data; + data.cast::().write(descriptor); + let head = src.cast::(); + (*head).format = drm_prime; + (*head).width = frame.width as c_int; + (*head).height = frame.height as c_int; + (*head).data[0] = data; + layout::write::(src, refs.buf, buffer); + let dst = session.hw; + (*dst.cast::()).format = vaapi; + layout::write::(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(session.pool)); + let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ); + (api.av_frame_free)(&mut src); + if ret < 0 { + (api.av_frame_unref)(dst); + return Err(self.error("DMA-BUF import", ret)); + } + let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; + layout::write::(dst, self.ffmpeg.frame.pts, pts); + layout::write::(dst, self.ffmpeg.frame.pict_type, pict_type); + let result = self.send(session, dst, out); + (api.av_frame_unref)(dst); + result.map(|_| ()) + } + } + + /// The pts of a frame taken at `timestamp`: frame numbers at the + /// session's rate (its time base), strictly increasing; remembered with + /// the 90 kHz time for the packets. + fn stamp(&self, session: &mut Session, timestamp: Duration, pts_90khz: u64) -> i64 { + let exact = timestamp.as_secs_f64() * f64::from(session.fps); + let mut pts = exact.round() as i64; + if let Some(last) = session.last_pts + && pts <= last + { + pts = last + 1; + } + session.last_pts = Some(pts); + session.timestamps.push(pts, pts_90khz); + pts + } + fn encode_in( &self, session: &mut Session, @@ -917,16 +1073,7 @@ impl FfmpegEncoder { ) -> Result<()> { let api = &self.ffmpeg.api; self.fill(session, frame)?; - // Frame numbers at the session's rate, strictly increasing. - let exact = frame.timestamp.as_secs_f64() * f64::from(session.fps); - let mut pts = exact.round() as i64; - if let Some(last) = session.last_pts - && pts <= last - { - pts = last + 1; - } - session.last_pts = Some(pts); - session.timestamps.push(pts, frame.pts_90khz()); + let pts = self.stamp(session, frame.timestamp, frame.pts_90khz()); let fields = self.ffmpeg.frame; let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE }; let input = if session.hw.is_null() { @@ -984,6 +1131,16 @@ impl FfmpegEncoder { } } +impl Drop for FfmpegEncoder { + /// Ends the stream properly (SVT-AV1 complains otherwise); the frames + /// still inside are dropped. + fn drop(&mut self) { + if let Some(mut session) = self.session.take() { + let _ = self.send(&mut session, std::ptr::null_mut(), &mut |_| {}); + } + } +} + impl VideoEncoder for FfmpegEncoder { fn codec(&self) -> Codec { self.spec.codec diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 0df7c63..3947825 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -376,7 +376,6 @@ pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result { /// # Safety /// `frame` must be a live AVFrame of this release, `pool` a live buffer /// reference. -#[allow(dead_code)] // for the DMA-BUF import pub unsafe fn check_hw_frames_ctx(frame: Ptr, pool: Ptr, refs: FrameRefs) -> bool { // SAFETY: guaranteed by the caller; the offset is inside AVFrame. unsafe { diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index 47a9162..e565fff 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -65,7 +65,6 @@ pub struct Ffmpeg { /// `AVCodecContext.hw_frames_ctx`. pub(crate) codec_hw_frames: Result, /// `AVFrame.buf[0]` / `hw_frames_ctx`. - #[allow(dead_code)] // for the DMA-BUF import pub(crate) frame_refs: Result, pub(crate) pix: PixFmts, info: LibraryInfo, diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index c95bbb2..8d6f8ce 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -227,6 +227,8 @@ api! { ) -> c_int; fn av_buffer_ref(buf: Ptr) -> Ptr; fn av_buffer_unref(buf: *mut Ptr); + // `size` is an `int` up to libavutil 56: passed in the same register. + fn av_buffer_allocz(size: usize) -> Ptr; fn av_hwdevice_find_type_by_name(name: *const c_char) -> c_int; fn av_hwdevice_ctx_create( device: *mut Ptr, diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index 8393ecc..f495408 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -228,3 +228,30 @@ fn unusable_backends_fail_cleanly() { assert!(encoder.encode(&frame, true).is_err(), "{} passed now", status.spec.name); } } + +/// DMA-BUF import is for VA-API encoders and NV12 buffers; anything else is +/// refused as unavailable, so the caller maps the buffer instead. +#[cfg(target_os = "linux")] +#[test] +fn dmabuf_import_is_refused_cleanly() { + use voelin_media::capture::{DRM_MOD_LINEAR, DmaBufRef, drm_fourcc}; + if ffmpeg().is_none() { + return; + } + let frame = DmaBufRef { + width: W, + height: H, + timestamp: Duration::ZERO, + fourcc: drm_fourcc(b"XR24"), + modifier: DRM_MOD_LINEAR, + fd: -1, + size: (W * H * 4) as usize, + planes: [(0, (W * 4) as usize), (0, 0), (0, 0), (0, 0)], + plane_count: 1, + }; + for name in ["libx264", "h264_vaapi"] { + let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap(); + let err = encoder.encode_dmabuf(&frame, true, &mut |_| {}).unwrap_err(); + assert!(matches!(err, voelin_media::Error::CodecUnavailable { .. }), "{name}: {err}"); + } +}