Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(capture): add the dmabuf -> VAAPI importer module (#507)
Benjamin Freemana15d95f7b4b2
diff --git a/electron/native/pipewire-capture/build.rs b/electron/native/pipewire-capture/build.rsindex 7c863210f..d6aec8e88 100644--- a/electron/native/pipewire-capture/build.rs+++ b/electron/native/pipewire-capture/build.rs@@ -127,7 +127,9 @@ fn link_ffmpeg(root: &Path) {);println!("cargo:rustc-link-search=native={}", lib.display());- for name in ["avcodec", "avformat", "avutil", "swscale", "swresample"] {+ // avfilter is for the VAAPI VPP (scale_vaapi) that converts an imported+ // dmabuf surface to NV12 for the encoder — see the dmabuf import path.+ for name in ["avcodec", "avformat", "avutil", "avfilter", "swscale", "swresample"] {println!("cargo:rustc-link-lib={name}");}// A SUBDIRECTORY, NOT `$ORIGIN`. The helper is staged into@@ -170,6 +172,9 @@ fn link_ffmpeg(root: &Path) {#include <libavutil/hwcontext_drm.h>#include <libavutil/imgutils.h>#include <libavutil/opt.h>+ #include <libavfilter/avfilter.h>+ #include <libavfilter/buffersrc.h>+ #include <libavfilter/buffersink.h>#include <libswresample/swresample.h>#include <libswscale/swscale.h>"#,@@ -182,6 +187,9 @@ fn link_ffmpeg(root: &Path) {.allowlist_function("avcodec_.*").allowlist_function("avformat_.*").allowlist_function("avio_.*")+ .allowlist_function("avfilter_.*")+ .allowlist_function("av_buffersrc_.*")+ .allowlist_function("av_buffersink_.*").allowlist_function("sws_.*").allowlist_function("swr_.*").allowlist_type("AV.*")diff --git a/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md b/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.mdindex 15ac518e8..050326110 100644--- a/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md+++ b/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md@@ -91,10 +91,41 @@ Key architecture calls:`osc_on_add_buffer` latches `import_dmabuf` on mmap failure instead of erroring;fourcc mapping added. shm/linear-dmabuf paths unchanged. `on_frame` currentlyskips dmabuf frames (data==null) — safe no-op until the importer lands.-- [ ] Mailbox + requeue-handle rework (no memcpy for dmabuf).-- [ ] Encoder: DRM_PRIME → `av_hwframe_map` → VAAPI VPP (crop) → NV12 pool- surface; `encode_staged` direct.-- [ ] Shm fallback guard + error paths.+- [x] Build foundation for the importer: vendored **libavfilter** wired in+ (bindgen headers `avfilter.h`/`buffersrc.h`/`buffersink.h` + allowlist, link,+ and staged into `helper-ffmpeg/` by the build script). `av_hwframe_map`,+ `av_hwdevice_ctx_create_derived`, `AVDRMFrameDescriptor`, `AV_PIX_FMT_DRM_PRIME`,+ `avfilter_graph_*`, `av_buffersrc/sink_*` all generate and link. Builds green.++### Importer design decisions (settled while scoping)++- **v1 buffer lifetime**: `on_frame` (PW thread) `dup()`s the plane fds into+ `OwnedFd`s (std, no libc), puts the descriptor in the mailbox, and requeues the+ PW buffer normally. The map+VPP+encode runs on the **main loop** — all VAAPI on+ one thread, no cross-thread device or mutex. The fds keep the dmabuf alive for+ the import; content-tear risk (compositor reusing the requeued buffer before the+ main loop imports, ~1 tick later) is low with a 4–16 buffer pool and is the one+ thing to watch. Upgrade to buffer-holding only if tearing shows.+- **Device & pool ownership**: create ONE standalone VAAPI `AVHWDeviceContext`;+ derive a DRM device from it for the DRM_PRIME source frames ctx. Build the+ `scale_vaapi` filtergraph (buffersrc VAAPI-BGR0 → `format=nv12` → buffersink)+ and take the buffersink's **output NV12 hw_frames_ctx** as the encoder's+ `codec_ctx->hw_frames_ctx`. That means for the dmabuf path the **encoder is+ opened AFTER the importer/filtergraph is built**, so their pools match and+ `avcodec_send_frame` accepts the surface directly.+- **Per frame**: build `AVDRMFrameDescriptor` (1 object: fd/size/modifier; 1+ layer: fourcc; 1 plane: offset/pitch) → DRM_PRIME AVFrame → `av_hwframe_map`+ DIRECT|READ → VAAPI BGR0 → buffersrc→scale_vaapi→buffersink → NV12 VAAPI →+ `encoder.stage_hw()` (held as `hw_staged`; `encode_staged` sends it with pts,+ no unref between the clock-driven re-encodes).++### Remaining+- [ ] `dmabuf_import.rs`: the map + scale_vaapi VPP → NV12 module (above).+- [ ] `shim.rs`: `DmabufDesc` (OwnedFd planes) + `Frame.dmabuf` + `on_frame` dup ++ mailbox variant (no memcpy).+- [ ] `encoder.rs`: shared device + deferred open + `stage_hw`/`hw_staged` path.+- [ ] `capture.rs`: dmabuf branch → importer → `stage_hw`.+- [ ] Shm fallback guard + error paths; then on-device record/check/fix.- [ ] Test on AMD/GNOME: confirm `uses_dmabuf=1`, distinct-fps ≈ OBS (~24),crop correct for window captures, cursor unaffected. Regression-checksoftware encode and a wlroots/niri compositor.diff --git a/electron/native/pipewire-capture/src/dmabuf_import.rs b/electron/native/pipewire-capture/src/dmabuf_import.rsnew file mode 100644index 000000000..7697c84d1--- /dev/null+++ b/electron/native/pipewire-capture/src/dmabuf_import.rs@@ -0,0 +1,363 @@+//! Zero-copy import of a compositor dmabuf into a VAAPI NV12 surface (issue #507).+//!+//! On GNOME/Wayland + AMD a whole-monitor capture arrives as a *tiled* dmabuf+//! that cannot be CPU-mapped. Rather than fall back to the shm path (which mutter+//! throttles hard), we keep the frame on the GPU: wrap the dmabuf as a+//! `DRM_PRIME` frame, [`av_hwframe_map`] it into a VAAPI surface, and run it+//! through a `scale_vaapi` VPP that converts the BGRx layout to the NV12 the+//! H.264 VAAPI encoder wants. Nothing is read back to system memory.+//!+//! The importer owns the VAAPI device and the filtergraph. The encoder is opened+//! against [`Self::output_frames_ctx`] so the NV12 surface this produces is one+//! `avcodec_send_frame` accepts directly. See docs/dmabuf-vaapi-plan.md.++use crate::ffmpeg as ff;+use std::ffi::CString;+use std::ptr;++/// `av_frame_free` wants a `**AVFrame`; wrap the pointer in a local so the null+/// it writes back does not land in a temporary.+unsafe fn free_frame(frame: *mut ff::AVFrame) {+ let mut p = frame;+ ff::av_frame_free(&mut p);+}++/// One dmabuf plane. `fd` is borrowed for the duration of [`DmabufImporter::import`]+/// only — VAAPI dups it during surface creation, so the caller may close it after.+pub struct DmabufPlane {+ pub fd: i32,+ pub offset: i32,+ pub stride: i32,+}++/// A dmabuf frame to import. Borrows the fds; see [`DmabufPlane`].+pub struct DmabufFrame<'a> {+ pub width: i32,+ pub height: i32,+ pub drm_fourcc: u32,+ pub modifier: u64,+ pub planes: &'a [DmabufPlane],+}++/// The pixel format the VAAPI-mapped surface presents, derived from the dmabuf's+/// DRM fourcc. Only the 32-bit RGB layouts we negotiate are handled.+fn sw_format_for_fourcc(drm_fourcc: u32) -> Option<ff::AVPixelFormat> {+ // DRM fourccs (little-endian) → the matching packed ffmpeg format.+ const XRGB8888: u32 = 0x34325258; // SPA BGRx+ const ARGB8888: u32 = 0x34325241; // SPA BGRA+ const XBGR8888: u32 = 0x34324258; // SPA RGBx+ const ABGR8888: u32 = 0x34324241; // SPA RGBA+ match drm_fourcc {+ XRGB8888 => Some(ff::AV_PIX_FMT_BGR0),+ ARGB8888 => Some(ff::AV_PIX_FMT_BGRA),+ XBGR8888 => Some(ff::AV_PIX_FMT_0BGR),+ ABGR8888 => Some(ff::AV_PIX_FMT_ABGR),+ _ => None,+ }+}++pub struct DmabufImporter {+ width: i32,+ height: i32,+ sw_format: ff::AVPixelFormat,+ /// VAAPI device, shared with the encoder (whose `hw_frames_ctx` comes from+ /// [`Self::output_frames_ctx`]).+ va_device: *mut ff::AVBufferRef,+ /// DRM device derived from `va_device`; backs the DRM_PRIME source frames.+ drm_device: *mut ff::AVBufferRef,+ /// Frames context for the incoming DRM_PRIME buffers.+ drm_frames: *mut ff::AVBufferRef,+ /// Frames context for the VAAPI surface the dmabuf maps into (still BGRx).+ va_map_frames: *mut ff::AVBufferRef,+ graph: *mut ff::AVFilterGraph,+ buffersrc_ctx: *mut ff::AVFilterContext,+ buffersink_ctx: *mut ff::AVFilterContext,+}++impl DmabufImporter {+ /// Builds the device, frames contexts and `scale_vaapi` graph for a stream of+ /// `width`×`height` `drm_fourcc` buffers.+ pub fn new(width: i32, height: i32, drm_fourcc: u32) -> Result<Self, String> {+ let sw_format =+ sw_format_for_fourcc(drm_fourcc).ok_or_else(|| format!("unsupported dmabuf fourcc {drm_fourcc:#x}"))?;++ // SAFETY: every pointer is checked before use and freed in Drop.+ unsafe {+ let mut me = DmabufImporter {+ width,+ height,+ sw_format,+ va_device: ptr::null_mut(),+ drm_device: ptr::null_mut(),+ drm_frames: ptr::null_mut(),+ va_map_frames: ptr::null_mut(),+ graph: ptr::null_mut(),+ buffersrc_ctx: ptr::null_mut(),+ buffersink_ctx: ptr::null_mut(),+ };++ // A standalone VAAPI device (the encoder will share it). Default+ // device selection matches how the encoder opens VAAPI today.+ let created = ff::av_hwdevice_ctx_create(+ &mut me.va_device,+ ff::AV_HWDEVICE_TYPE_VAAPI,+ ptr::null(),+ ptr::null_mut(),+ 0,+ );+ if created < 0 {+ return Err(format!("av_hwdevice_ctx_create(VAAPI): {}", ff::err_to_string(created)));+ }++ // DRM device derived from the same GPU, so the mapped surface and the+ // VAAPI device share a backing.+ let derived = ff::av_hwdevice_ctx_create_derived(+ &mut me.drm_device,+ ff::AV_HWDEVICE_TYPE_DRM,+ me.va_device,+ 0,+ );+ if derived < 0 {+ return Err(format!(+ "av_hwdevice_ctx_create_derived(DRM): {}",+ ff::err_to_string(derived)+ ));+ }++ me.drm_frames = me.alloc_frames(me.drm_device, ff::AV_PIX_FMT_DRM_PRIME)?;+ me.va_map_frames = me.alloc_frames(me.va_device, ff::AV_PIX_FMT_VAAPI)?;+ me.build_graph()?;+ Ok(me)+ }+ }++ /// Allocates and initialises a frames context of `hw_format` (VAAPI or+ /// DRM_PRIME) whose software format is the stream's RGB layout.+ unsafe fn alloc_frames(+ &self,+ device: *mut ff::AVBufferRef,+ hw_format: ff::AVPixelFormat,+ ) -> Result<*mut ff::AVBufferRef, String> {+ let frames = ff::av_hwframe_ctx_alloc(device);+ if frames.is_null() {+ return Err("av_hwframe_ctx_alloc failed".to_owned());+ }+ let ctx = (*frames).data as *mut ff::AVHWFramesContext;+ (*ctx).format = hw_format;+ (*ctx).sw_format = self.sw_format;+ (*ctx).width = self.width;+ (*ctx).height = self.height;+ // A small pool: the mapped surface is short-lived (consumed by the VPP in+ // the same call). DRM_PRIME frames are imported, not pooled, so the count+ // is nominal there.+ (*ctx).initial_pool_size = 4;+ let init = ff::av_hwframe_ctx_init(frames);+ if init < 0 {+ let mut f = frames;+ ff::av_buffer_unref(&mut f);+ return Err(format!("av_hwframe_ctx_init: {}", ff::err_to_string(init)));+ }+ Ok(frames)+ }++ /// Builds `buffer (VAAPI/BGRx) -> scale_vaapi=format=nv12 -> buffersink`.+ unsafe fn build_graph(&mut self) -> Result<(), String> {+ self.graph = ff::avfilter_graph_alloc();+ if self.graph.is_null() {+ return Err("avfilter_graph_alloc failed".to_owned());+ }++ let buffersrc = ff::avfilter_get_by_name(c"buffer".as_ptr());+ let buffersink = ff::avfilter_get_by_name(c"buffersink".as_ptr());+ let scale = ff::avfilter_get_by_name(c"scale_vaapi".as_ptr());+ if buffersrc.is_null() || buffersink.is_null() || scale.is_null() {+ return Err("a required filter (buffer/buffersink/scale_vaapi) is missing".to_owned());+ }++ // buffersrc: the input is a VAAPI surface, so pix_fmt is VAAPI and the+ // real (sw) format rides on the hw_frames_ctx set below.+ let args = CString::new(format!(+ "video_size={}x{}:pix_fmt={}:time_base=1/1000000:pixel_aspect=1/1",+ self.width,+ self.height,+ ff::AV_PIX_FMT_VAAPI as i32+ ))+ .map_err(|_| "buffersrc args contained a NUL".to_owned())?;++ let rc = ff::avfilter_graph_create_filter(+ &mut self.buffersrc_ctx,+ buffersrc,+ c"in".as_ptr(),+ args.as_ptr(),+ ptr::null_mut(),+ self.graph,+ );+ if rc < 0 {+ return Err(format!("create buffersrc: {}", ff::err_to_string(rc)));+ }++ // Attach the VAAPI (BGRx) frames context the mapped surfaces come from.+ let par = ff::av_buffersrc_parameters_alloc();+ if par.is_null() {+ return Err("av_buffersrc_parameters_alloc failed".to_owned());+ }+ (*par).hw_frames_ctx = ff::av_buffer_ref(self.va_map_frames);+ let set = ff::av_buffersrc_parameters_set(self.buffersrc_ctx, par);+ ff::av_free(par as *mut _);+ if set < 0 {+ return Err(format!("av_buffersrc_parameters_set: {}", ff::err_to_string(set)));+ }++ let rc = ff::avfilter_graph_create_filter(+ &mut self.buffersink_ctx,+ buffersink,+ c"out".as_ptr(),+ ptr::null(),+ ptr::null_mut(),+ self.graph,+ );+ if rc < 0 {+ return Err(format!("create buffersink: {}", ff::err_to_string(rc)));+ }++ let mut scale_ctx: *mut ff::AVFilterContext = ptr::null_mut();+ let rc = ff::avfilter_graph_create_filter(+ &mut scale_ctx,+ scale,+ c"vpp".as_ptr(),+ c"format=nv12".as_ptr(),+ ptr::null_mut(),+ self.graph,+ );+ if rc < 0 {+ return Err(format!("create scale_vaapi: {}", ff::err_to_string(rc)));+ }+ // scale_vaapi needs a device to allocate its NV12 output pool; take it+ // from the shared VAAPI device rather than relying on propagation.+ (*scale_ctx).hw_device_ctx = ff::av_buffer_ref(self.va_device);++ let rc = ff::avfilter_link(self.buffersrc_ctx, 0, scale_ctx, 0);+ if rc >= 0 {+ ff::avfilter_link(scale_ctx, 0, self.buffersink_ctx, 0);+ }+ if rc < 0 {+ return Err(format!("avfilter_link: {}", ff::err_to_string(rc)));+ }++ let rc = ff::avfilter_graph_config(self.graph, ptr::null_mut());+ if rc < 0 {+ return Err(format!("avfilter_graph_config: {}", ff::err_to_string(rc)));+ }+ Ok(())+ }++ /// The NV12 VAAPI frames context the graph emits into — the encoder opens+ /// against this so it accepts the surfaces [`Self::import`] returns.+ pub fn output_frames_ctx(&self) -> *mut ff::AVBufferRef {+ // SAFETY: valid after a successful `build_graph`; the sink has one input.+ unsafe { ff::av_buffersink_get_hw_frames_ctx(self.buffersink_ctx) }+ }++ /// The shared VAAPI device, for the encoder's `hwaccel` context.+ pub fn device(&self) -> *mut ff::AVBufferRef {+ self.va_device+ }++ /// Maps one dmabuf and returns an NV12 VAAPI frame (caller unrefs it). The+ /// plane fds are only touched during this call.+ pub fn import(&mut self, frame: &DmabufFrame) -> Result<*mut ff::AVFrame, String> {+ if frame.planes.is_empty() || frame.planes.len() > 4 {+ return Err(format!("dmabuf has {} planes", frame.planes.len()));+ }+ // SAFETY: the descriptor outlives the map call it is passed to; every+ // allocated frame is unref'd on the error paths and on success ownership+ // of the NV12 frame passes to the caller.+ unsafe {+ // Build the DRM PRIME descriptor. One object per unique fd; our RGB+ // formats are a single object with a single layer and plane.+ let mut desc: ff::AVDRMFrameDescriptor = std::mem::zeroed();+ desc.nb_objects = 1;+ desc.objects[0].fd = frame.planes[0].fd;+ desc.objects[0].size = 0; // recovered by the driver from the fd+ desc.objects[0].format_modifier = frame.modifier;+ desc.nb_layers = 1;+ desc.layers[0].format = frame.drm_fourcc;+ desc.layers[0].nb_planes = frame.planes.len() as i32;+ for (i, plane) in frame.planes.iter().enumerate() {+ desc.layers[0].planes[i].object_index = 0;+ desc.layers[0].planes[i].offset = plane.offset as isize;+ desc.layers[0].planes[i].pitch = plane.stride as isize;+ }++ let src = ff::av_frame_alloc();+ if src.is_null() {+ return Err("av_frame_alloc(src) failed".to_owned());+ }+ (*src).format = ff::AV_PIX_FMT_DRM_PRIME as i32;+ (*src).width = self.width;+ (*src).height = self.height;+ (*src).data[0] = &mut desc as *mut _ as *mut u8;+ (*src).hw_frames_ctx = ff::av_buffer_ref(self.drm_frames);++ // Map the dmabuf into a VAAPI (BGRx) surface, zero-copy.+ let mapped = ff::av_frame_alloc();+ if mapped.is_null() {+ free_frame(src);+ return Err("av_frame_alloc(mapped) failed".to_owned());+ }+ (*mapped).format = ff::AV_PIX_FMT_VAAPI as i32;+ (*mapped).hw_frames_ctx = ff::av_buffer_ref(self.va_map_frames);+ let mrc = ff::av_hwframe_map(+ mapped,+ src,+ (ff::AV_HWFRAME_MAP_DIRECT | ff::AV_HWFRAME_MAP_READ) as i32,+ );+ // `src` (and thus `desc`) is no longer needed once mapped.+ free_frame(src);+ if mrc < 0 {+ free_frame(mapped);+ return Err(format!("av_hwframe_map: {}", ff::err_to_string(mrc)));+ }++ // Push through scale_vaapi → NV12.+ let pushed = ff::av_buffersrc_add_frame(self.buffersrc_ctx, mapped);+ free_frame(mapped);+ if pushed < 0 {+ return Err(format!("av_buffersrc_add_frame: {}", ff::err_to_string(pushed)));+ }++ let nv12 = ff::av_frame_alloc();+ if nv12.is_null() {+ return Err("av_frame_alloc(nv12) failed".to_owned());+ }+ let got = ff::av_buffersink_get_frame(self.buffersink_ctx, nv12);+ if got < 0 {+ free_frame(nv12);+ return Err(format!("av_buffersink_get_frame: {}", ff::err_to_string(got)));+ }+ Ok(nv12)+ }+ }+}++impl Drop for DmabufImporter {+ fn drop(&mut self) {+ // SAFETY: each pointer is freed once; nulls are ignored by the ffmpeg+ // frees, and the order is graph → frames → devices.+ unsafe {+ if !self.graph.is_null() {+ ff::avfilter_graph_free(&mut self.graph);+ }+ for frames in [&mut self.drm_frames, &mut self.va_map_frames] {+ if !frames.is_null() {+ ff::av_buffer_unref(frames);+ }+ }+ for device in [&mut self.drm_device, &mut self.va_device] {+ if !device.is_null() {+ ff::av_buffer_unref(device);+ }+ }+ }+ }+}diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rsindex 8ec4078c2..344d84b4b 100644--- a/electron/native/pipewire-capture/src/main.rs+++ b/electron/native/pipewire-capture/src/main.rs@@ -26,6 +26,7 @@mod bitmap;mod capture;+mod dmabuf_import;mod encoder;mod events;mod ffmpeg;diff --git a/scripts/build-linux-pipewire-helper.mjs b/scripts/build-linux-pipewire-helper.mjsindex ac898c4c2..b6928c3a8 100644--- a/scripts/build-linux-pipewire-helper.mjs+++ b/scripts/build-linux-pipewire-helper.mjs@@ -143,7 +143,7 @@ function stageFfmpeg(dir) {// Only the sonames the helper actually links, and only the real files —// the tree also holds unversioned `.so` symlinks that the loader never// consults at runtime.- const wanted = /^lib(avcodec|avformat|avutil|swscale|swresample)\.so\.\d+$/;+ const wanted = /^lib(avcodec|avformat|avutil|avfilter|swscale|swresample)\.so\.\d+$/;let copied = 0;for (const entry of fs.readdirSync(source)) {if (!wanted.test(entry)) {