Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(capture): negotiate tiled dmabuf and plumb the GPU descriptor (#507)

Benjamin Freemand6c997614dca
diff --git a/electron/native/pipewire-capture/build.rs b/electron/native/pipewire-capture/build.rs
index 43ff9d6d4..7c863210f 100644
--- a/electron/native/pipewire-capture/build.rs
+++ b/electron/native/pipewire-capture/build.rs
@@ -24,7 +24,7 @@ fn main() {
fn build_pipewire_shim(root: &Path) {
let vendor = root.join("vendor/pipewire-1.0.5/include");
- let sources = ["csrc/pw_shim.c", "csrc/pw_audio.c"];
+ let sources = ["csrc/pw_shim.c", "csrc/pw_audio.c", "csrc/dmabuf_modifiers.c"];
assert!(
vendor.join("pipewire/pipewire.h").is_file(),
@@ -167,6 +167,7 @@ fn link_ffmpeg(root: &Path) {
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/hwcontext.h>
+ #include <libavutil/hwcontext_drm.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
diff --git a/electron/native/pipewire-capture/csrc/dmabuf_modifiers.c b/electron/native/pipewire-capture/csrc/dmabuf_modifiers.c
new file mode 100644
index 000000000..96f1849c8
--- /dev/null
+++ b/electron/native/pipewire-capture/csrc/dmabuf_modifiers.c
@@ -0,0 +1,94 @@
+#include "dmabuf_modifiers.h"
+
+#include <dlfcn.h>
+#include <stddef.h>
+
+/*
+ * Minimal EGL surface, spelled out rather than pulled from <EGL/egl.h> so the
+ * build needs no EGL dev package (same reasoning as the DRM modifier constants
+ * in pw_shim.c). libEGL itself is dlopen'd at runtime; if it is absent the
+ * caller degrades to the LINEAR/INVALID offer.
+ */
+typedef void *EGLDisplay;
+typedef unsigned int EGLBoolean;
+typedef int EGLint;
+typedef intptr_t EGLAttrib;
+typedef uint64_t EGLuint64KHR;
+
+#define OSC_EGL_TRUE 1
+#define OSC_EGL_NO_DISPLAY ((EGLDisplay)0)
+#define OSC_EGL_DEFAULT_DISPLAY ((void *)0)
+/* EGL_MESA_platform_surfaceless — a display with no window system, exactly what
+ * a one-shot capability query wants. */
+#define OSC_EGL_PLATFORM_SURFACELESS_MESA 0x31DD
+
+typedef void *(*osc_eglGetProcAddress)(const char *);
+typedef EGLDisplay (*osc_eglGetPlatformDisplay)(EGLint platform, void *native,
+ const EGLAttrib *attrib_list);
+typedef EGLBoolean (*osc_eglInitialize)(EGLDisplay, EGLint *major, EGLint *minor);
+typedef EGLBoolean (*osc_eglTerminate)(EGLDisplay);
+typedef EGLBoolean (*osc_eglQueryDmaBufModifiersEXT)(EGLDisplay, EGLint format,
+ EGLint max_modifiers,
+ EGLuint64KHR *modifiers,
+ EGLBoolean *external_only,
+ EGLint *num_modifiers);
+
+int osc_query_dmabuf_modifiers(uint32_t fourcc, uint64_t *out, int max_out)
+{
+ if (out == NULL || max_out <= 0) {
+ return 0;
+ }
+
+ /* RTLD_NODELETE: EGL keeps process-global state, so never let dlclose run
+ * its destructors — we deliberately do not dlclose at all. */
+ void *egl = dlopen("libEGL.so.1", RTLD_NOW | RTLD_LOCAL | RTLD_NODELETE);
+ if (egl == NULL) {
+ return 0;
+ }
+
+ osc_eglGetProcAddress get_proc =
+ (osc_eglGetProcAddress)dlsym(egl, "eglGetProcAddress");
+ osc_eglInitialize egl_init = (osc_eglInitialize)dlsym(egl, "eglInitialize");
+ osc_eglTerminate egl_terminate = (osc_eglTerminate)dlsym(egl, "eglTerminate");
+ if (get_proc == NULL || egl_init == NULL || egl_terminate == NULL) {
+ return 0;
+ }
+
+ osc_eglGetPlatformDisplay get_display =
+ (osc_eglGetPlatformDisplay)get_proc("eglGetPlatformDisplayEXT");
+ osc_eglQueryDmaBufModifiersEXT query_mods =
+ (osc_eglQueryDmaBufModifiersEXT)get_proc("eglQueryDmaBufModifiersEXT");
+ if (get_display == NULL || query_mods == NULL) {
+ return 0;
+ }
+
+ EGLDisplay dpy = get_display(OSC_EGL_PLATFORM_SURFACELESS_MESA,
+ OSC_EGL_DEFAULT_DISPLAY, NULL);
+ if (dpy == OSC_EGL_NO_DISPLAY) {
+ return 0;
+ }
+ if (egl_init(dpy, NULL, NULL) != OSC_EGL_TRUE) {
+ return 0;
+ }
+
+ int written = 0;
+ EGLint count = 0;
+ if (query_mods(dpy, (EGLint)fourcc, 0, NULL, NULL, &count) == OSC_EGL_TRUE &&
+ count > 0) {
+ EGLuint64KHR mods[128];
+ EGLBoolean external[128];
+ EGLint cap = (EGLint)(sizeof(mods) / sizeof(mods[0]));
+ if (count > cap) {
+ count = cap;
+ }
+ if (query_mods(dpy, (EGLint)fourcc, count, mods, external, &count) ==
+ OSC_EGL_TRUE) {
+ for (EGLint i = 0; i < count && written < max_out; i++) {
+ out[written++] = (uint64_t)mods[i];
+ }
+ }
+ }
+
+ egl_terminate(dpy);
+ return written;
+}
diff --git a/electron/native/pipewire-capture/csrc/dmabuf_modifiers.h b/electron/native/pipewire-capture/csrc/dmabuf_modifiers.h
new file mode 100644
index 000000000..be6ac1212
--- /dev/null
+++ b/electron/native/pipewire-capture/csrc/dmabuf_modifiers.h
@@ -0,0 +1,20 @@
+#ifndef OSC_DMABUF_MODIFIERS_H
+#define OSC_DMABUF_MODIFIERS_H
+
+#include <stdint.h>
+
+/*
+ * Query the DRM format modifiers the local GPU's EGL stack can import for a
+ * given DRM fourcc (e.g. XRGB8888). These are the modifiers we can legitimately
+ * advertise to the compositor in the dmabuf EnumFormat: a compositor buffer
+ * whose modifier is in this set is one we can hand to VAAPI. Fills `out` with up
+ * to `max_out` modifiers and returns the count, or 0 when enumeration is
+ * unavailable (no libEGL, no surfaceless platform, driver refuses) — in which
+ * case the caller falls back to LINEAR/INVALID only.
+ *
+ * libEGL is loaded with dlopen, matching how this crate treats libpipewire: the
+ * helper stays buildable and runnable on a box without EGL dev packages.
+ */
+int osc_query_dmabuf_modifiers(uint32_t fourcc, uint64_t *out, int max_out);
+
+#endif
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.c b/electron/native/pipewire-capture/csrc/pw_shim.c
index 82a8a129e..ece1e67ad 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.c
+++ b/electron/native/pipewire-capture/csrc/pw_shim.c
@@ -45,6 +45,7 @@
#include <spa/utils/result.h>
#include "pw_shim.h"
+#include "dmabuf_modifiers.h"
/* Defined next to osc_map_dmabuf; used earlier, at format negotiation. */
static int osc_debug_enabled(void);
@@ -61,16 +62,43 @@ static int osc_debug_enabled(void);
* header would put libdrm-dev in the build path of every contributor and CI
* runner for two integers. That is the same trade the dlopen above makes.
*
- * These two are the ONLY modifiers this helper advertises, and the reason is
- * osc_map_dmabuf(): a linear or implicit buffer can be read through a plain
- * mmap of the dmabuf fd, while a tiled or compression-enabled one cannot — its
- * bytes are not in raster order, so handing them to the encoder would produce a
- * scrambled recording rather than an error. Anything else needs a real GPU
- * import (EGL/gbm), which this helper deliberately does not link.
+ * LINEAR and INVALID are the universal fallbacks: a linear or implicit buffer
+ * can be read through a plain mmap of the dmabuf fd (osc_map_dmabuf). Tiled or
+ * compression-enabled buffers cannot — their bytes are not in raster order — so
+ * they require a real GPU import, which is being added for the VAAPI path (see
+ * issue #507 and docs/dmabuf-vaapi-plan.md). The additional importable modifiers
+ * are enumerated at runtime via EGL (osc_query_dmabuf_modifiers).
*/
#define OSC_DRM_FORMAT_MOD_LINEAR 0ULL
#define OSC_DRM_FORMAT_MOD_INVALID 0x00ffffffffffffffULL
+/* DRM fourccs for the 32-bit RGB formats we offer. XRGB8888 = fourcc('X','R',
+ * '2','4'); the others follow the same little-endian spelling. Used to enumerate
+ * importable modifiers and to describe a dmabuf to the GPU importer. Spelled out
+ * for the same reason as the modifiers above. */
+#define OSC_DRM_FORMAT_XRGB8888 0x34325258u /* SPA BGRx */
+#define OSC_DRM_FORMAT_ARGB8888 0x34325241u /* SPA BGRA */
+#define OSC_DRM_FORMAT_XBGR8888 0x34324258u /* SPA RGBx */
+#define OSC_DRM_FORMAT_ABGR8888 0x34324241u /* SPA RGBA */
+
+/* SPA video format (byte order B,G,R,x ...) → the matching DRM fourcc (a
+ * little-endian 32-bit word), for the GPU dmabuf import. 0 = unmapped. */
+static uint32_t osc_spa_format_to_drm_fourcc(uint32_t spa_format)
+{
+ switch (spa_format) {
+ case SPA_VIDEO_FORMAT_BGRx:
+ return OSC_DRM_FORMAT_XRGB8888;
+ case SPA_VIDEO_FORMAT_BGRA:
+ return OSC_DRM_FORMAT_ARGB8888;
+ case SPA_VIDEO_FORMAT_RGBx:
+ return OSC_DRM_FORMAT_XBGR8888;
+ case SPA_VIDEO_FORMAT_RGBA:
+ return OSC_DRM_FORMAT_ABGR8888;
+ default:
+ return 0;
+ }
+}
+
/*
* Mapped dmabuf fds, keyed by fd.
*
@@ -182,6 +210,10 @@ struct osc_pw_session {
/* Set from the negotiated format's SPA_VIDEO_FLAG_MODIFIER, which is what
* decides whether buffers arrive as dmabuf fds or shared memory. */
int uses_dmabuf;
+ /* Latched when a dmabuf buffer cannot be CPU-mmap'd (a tiled buffer on, e.g.,
+ * AMD/mutter). Frames then travel as raw dmabuf descriptors for a GPU import
+ * (issue #507) instead of the shared-memory path. */
+ int import_dmabuf;
struct osc_dmabuf_map dmabuf_maps[OSC_MAX_DMABUF_MAPS];
/* fd whose DMA_BUF_SYNC_START has not been closed by its END yet, or -1.
* The bracket has to span the on_frame callback, not just osc_read_frame,
@@ -415,9 +447,22 @@ static const struct spa_pod *osc_build_enum_format_dmabuf(struct spa_pod_builder
* tolerating the key. */
spa_pod_builder_prop(builder, SPA_FORMAT_VIDEO_modifier, SPA_POD_PROP_FLAG_MANDATORY);
spa_pod_builder_push_choice(builder, &choice_frame, SPA_CHOICE_Enum, 0);
- /* Default first, then every alternative — the default is repeated, same
+ /* Advertise the modifiers our GPU's EGL can import, so a tiled compositor
+ * buffer — the common case on AMD/mutter — negotiates as dmabuf instead of
+ * falling back to the throttled shm path (issue #507). LINEAR and INVALID
+ * stay as universal fallbacks. Modifiers match across the 32-bit RGB formats
+ * we offer, so enumerating XRGB8888 is representative.
+ *
+ * Default first, then every alternative — the default is repeated, same
* idiom as SPA_POD_CHOICE_ENUM_Id above. */
- spa_pod_builder_long(builder, (int64_t)OSC_DRM_FORMAT_MOD_LINEAR);
+ uint64_t egl_mods[128];
+ int egl_mod_count = osc_query_dmabuf_modifiers(OSC_DRM_FORMAT_XRGB8888, egl_mods, 128);
+ int64_t default_mod =
+ egl_mod_count > 0 ? (int64_t)egl_mods[0] : (int64_t)OSC_DRM_FORMAT_MOD_LINEAR;
+ spa_pod_builder_long(builder, default_mod);
+ for (int i = 0; i < egl_mod_count; i++) {
+ spa_pod_builder_long(builder, (int64_t)egl_mods[i]);
+ }
spa_pod_builder_long(builder, (int64_t)OSC_DRM_FORMAT_MOD_LINEAR);
spa_pod_builder_long(builder, (int64_t)OSC_DRM_FORMAT_MOD_INVALID);
spa_pod_builder_pop(builder, &choice_frame);
@@ -805,23 +850,17 @@ static void osc_on_add_buffer(void *userdata, struct pw_buffer *pw_buf)
maplen = data->maxsize;
session->dmabuf_maps[i].ptr = osc_map_dmabuf((int)data->fd, &maplen, &why);
if (session->dmabuf_maps[i].ptr == NULL) {
- /* Reported once, through the buffer-info channel that already exists
- * for describing what the compositor handed us — a mapping failure
- * here means no frames at all, and silence would read as a hang.
- *
- * The reason is carried up rather than assumed: this used to say the
- * driver refused CPU mapping no matter what actually went wrong, and
- * that message sent the one real investigation of this path looking
- * at the GPU for a size the compositor had simply left at 0. */
- if (session->callbacks.on_buffer_info != NULL &&
- session->buffer_info_reports < OSC_BUFFER_INFO_REPORTS) {
- char detail[256];
-
- snprintf(detail, sizeof(detail), "dmabuf import failed: %s; capture cannot proceed",
- why);
- session->buffer_info_reports++;
- session->callbacks.on_buffer_info(session->callbacks.user, data->type,
- pw_buf->buffer->n_datas, 0, 0, detail);
+ /*
+ * A mmap failure on a dmabuf is the tiled-buffer case (e.g. a whole
+ * monitor on AMD/mutter): the bytes are not in raster order and the
+ * driver refuses CPU access. That is no longer fatal — the frame
+ * instead travels as a raw dmabuf descriptor for a GPU import (see
+ * osc_read_frame and issue #507). Latch the mode; osc_read_frame will
+ * populate the descriptor from the same fd. No mapping is stored.
+ */
+ session->import_dmabuf = 1;
+ if (osc_debug_enabled()) {
+ fprintf(stderr, "[osc-dmabuf] mmap failed (%s) — using GPU import path\n", why);
}
return;
}
@@ -985,6 +1024,7 @@ static int osc_read_frame(struct osc_pw_session *session, const struct spa_buffe
uint32_t size;
int32_t stride;
int32_t height;
+ int is_dmabuf_import = 0;
const uint8_t *base;
@@ -1008,7 +1048,12 @@ static int osc_read_frame(struct osc_pw_session *session, const struct spa_buffe
*/
base = osc_find_dmabuf_map(session, (int)data->fd);
if (base == NULL) {
- return 0;
+ if (!session->import_dmabuf) {
+ return 0;
+ }
+ /* Tiled dmabuf: no CPU mapping exists. It travels up as a raw
+ * descriptor for a GPU import instead of being read here. */
+ is_dmabuf_import = 1;
}
} else if (data->data == NULL) {
/*
@@ -1025,36 +1070,74 @@ static int osc_read_frame(struct osc_pw_session *session, const struct spa_buffe
return 0;
}
- offset = SPA_MIN(data->chunk->offset, data->maxsize);
- size = SPA_MIN(data->chunk->size, data->maxsize - offset);
-
height = (int32_t)session->format.size.height;
stride = data->chunk->stride;
- if (stride <= 0 || height <= 0) {
- return 0;
- }
- /* One short row is one row of garbage in the recording; refuse the whole
- * frame instead, and let the caller count it as dropped. */
- if ((uint64_t)stride * (uint64_t)height > (uint64_t)size) {
+ if (height <= 0) {
return 0;
}
- /*
- * Open the CPU-access window on a dmabuf and leave it open: the pixels are
- * read by the on_frame callback, not here, so the matching SYNC_END lives in
- * osc_inspect_buffer once that callback has returned.
- */
- if (data->type == SPA_DATA_DmaBuf) {
- session->dmabuf_sync_fd = (int)data->fd;
- osc_dmabuf_sync(session->dmabuf_sync_fd, 1);
- }
+ if (is_dmabuf_import) {
+ /*
+ * GPU import path. The buffer is not CPU-readable, so the raster bounds
+ * checks below do not apply — the modifier is what makes the producer's
+ * strides/offsets meaningful, and the importer validates the rest. We
+ * hand up the fd(s), modifier and fourcc; no SYNC bracket is opened
+ * because nothing here touches the pixels. n_datas is the plane count for
+ * a dmabuf (one per plane); our RGB formats are single-plane.
+ */
+ uint32_t fourcc = osc_spa_format_to_drm_fourcc(session->format.format);
+ int32_t import_stride =
+ stride > 0 ? stride : (int32_t)session->format.size.width * 4;
+ int32_t p;
+ if (fourcc == 0) {
+ return 0;
+ }
+ out->is_dmabuf = 1;
+ out->data = NULL;
+ out->size = 0;
+ out->stride = import_stride;
+ out->width = (int32_t)session->format.size.width;
+ out->height = height;
+ out->video_format = session->format.format;
+ out->modifier = session->format.modifier;
+ out->drm_fourcc = fourcc;
+ out->n_planes = (int32_t)buffer->n_datas > 4 ? 4 : (int32_t)buffer->n_datas;
+ for (p = 0; p < out->n_planes; p++) {
+ const struct spa_data *pd = &buffer->datas[p];
+ out->plane_fd[p] = (int)pd->fd;
+ out->plane_offset[p] = pd->chunk != NULL ? (int32_t)pd->chunk->offset : 0;
+ out->plane_stride[p] =
+ (pd->chunk != NULL && pd->chunk->stride > 0) ? pd->chunk->stride : import_stride;
+ }
+ } else {
+ offset = SPA_MIN(data->chunk->offset, data->maxsize);
+ size = SPA_MIN(data->chunk->size, data->maxsize - offset);
+ if (stride <= 0) {
+ return 0;
+ }
+ /* One short row is one row of garbage in the recording; refuse the whole
+ * frame instead, and let the caller count it as dropped. */
+ if ((uint64_t)stride * (uint64_t)height > (uint64_t)size) {
+ return 0;
+ }
+
+ /*
+ * Open the CPU-access window on a dmabuf and leave it open: the pixels
+ * are read by the on_frame callback, not here, so the matching SYNC_END
+ * lives in osc_inspect_buffer once that callback has returned.
+ */
+ if (data->type == SPA_DATA_DmaBuf) {
+ session->dmabuf_sync_fd = (int)data->fd;
+ osc_dmabuf_sync(session->dmabuf_sync_fd, 1);
+ }
- out->data = SPA_PTROFF(base, offset, const uint8_t);
- out->size = size;
- out->stride = stride;
- out->width = (int32_t)session->format.size.width;
- out->height = height;
- out->video_format = session->format.format;
+ out->data = SPA_PTROFF(base, offset, const uint8_t);
+ out->size = size;
+ out->stride = stride;
+ out->width = (int32_t)session->format.size.width;
+ out->height = height;
+ out->video_format = session->format.format;
+ }
header = spa_buffer_find_meta_data(buffer, SPA_META_Header, sizeof(*header));
if (header != NULL) {
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.h b/electron/native/pipewire-capture/csrc/pw_shim.h
index ab6f78305..878f2445c 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.h
+++ b/electron/native/pipewire-capture/csrc/pw_shim.h
@@ -94,6 +94,26 @@ struct osc_pw_frame {
* both draw the line in exactly this place.
*/
int has_crop;
+
+ /*
+ * Zero-copy dmabuf hand-off (issue #507). When `is_dmabuf` is 1, `data` is
+ * NULL and the frame is not CPU-readable — a tiled compositor buffer that
+ * lives on the GPU. The consumer imports it as a VAAPI surface from the
+ * descriptor below instead of reading `data`. When 0, the CPU path above
+ * applies unchanged (shm, or a linear/implicit dmabuf we could mmap).
+ *
+ * The fds are BORROWED for the callback's duration only, exactly like
+ * `data`: the buffer re-queues to the compositor when the callback returns,
+ * so the import (map + GPU copy into an owned surface) must complete before
+ * then. `modifier`/`drm_fourcc` describe the tiling and pixel layout.
+ */
+ int is_dmabuf;
+ uint64_t modifier; /* DRM format modifier of the buffer */
+ uint32_t drm_fourcc; /* DRM fourcc matching `video_format` */
+ int32_t n_planes; /* number of populated plane_* entries (1..4) */
+ int plane_fd[4];
+ int32_t plane_offset[4];
+ int32_t plane_stride[4];
};
/* The negotiated video format. Reported once, from param_changed. */
diff --git a/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md b/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md
new file mode 100644
index 000000000..15ac518e8
--- /dev/null
+++ b/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md
@@ -0,0 +1,108 @@
+# Zero-copy dmabuf → VAAPI capture (fix for #507)
+
+## Problem
+
+On GNOME/mutter + AMD, the helper only advertises `LINEAR`/`INVALID` dmabuf
+modifiers (it reads frames via CPU `mmap`, which needs linear). AMD monitor
+buffers are **tiled**, so dmabuf negotiation can't succeed and we fall back to
+**shm/memfd**. mutter throttles whole-monitor shm delivery hard (GPU→CPU copy
+per frame), starving the recorder to ~2–11 distinct fps while OBS gets ~24 over
+dmabuf. Result: whole-screen recordings look frozen. Window capture is less
+affected (smaller surface → shm copy keeps up).
+
+Goal: import the compositor's **tiled** dmabuf directly as a VAAPI surface and
+encode with the existing `h264_vaapi` path — no CPU readback, no shm.
+
+## Constraint that shapes the design: the clock-driven encoder
+
+`capture.rs` writes constant-frame-rate output by *holding the last staged
+picture* across gaps (a static screen delivers no frames). We therefore cannot
+pin the PipeWire dmabuf across that gap — the pool is 4–16 buffers. So on each
+arriving frame we must copy it into a surface **we own**, then requeue the
+compositor buffer promptly. The copy stays on the GPU (VAAPI VPP), so it's cheap.
+
+## Pipeline (new dmabuf path, shm path kept as fallback)
+
+1. **Negotiation** — advertise the dmabuf modifiers our importer supports.
+ Enumerate them from the DRM render node (VAAPI/`vaQuerySurfaceAttributes` or
+ EGL `eglQueryDmaBufModifiersEXT`), per fourcc, like OBS. Offer that list in
+ `osc_build_enum_format_dmabuf` instead of just LINEAR/INVALID.
+2. **C shim** — on `SPA_DATA_DmaBuf`, stop mmap'ing. Extract the raw descriptor:
+ fd(s), `format_modifier`, and per-plane `offset`/`stride`, plus fourcc. Pass
+ them to Rust via an extended `osc_pw_frame`/`RawFrame`. Keep the
+ `DMA_BUF_IOCTL_SYNC` bracket only for the (unused-on-dmabuf) CPU path.
+3. **Frame lifecycle** — the mailbox must not `memcpy` for dmabuf. It holds the
+ descriptor + a handle that keeps the PipeWire buffer un-requeued until the
+ main loop imports it; newest-wins requeues the superseded buffer. Requeue
+ happens right after import (fast), never across the clock gap.
+4. **Encoder** — build an `AVFrame` of `AV_PIX_FMT_DRM_PRIME` wrapping an
+ `AVDRMFrameDescriptor`, `av_hwframe_map()` it to a VAAPI frame (DRM→VAAPI
+ zero-copy), then VPP (`scale_vaapi`/`vpp_vaapi`) into our own NV12 VAAPI pool
+ surface — this also applies the **crop** (VideoCrop) on the GPU, replacing the
+ current CPU pointer-offset crop. That owned surface becomes the staged frame;
+ `encode_staged` sends it directly (no `av_hwframe_transfer_data` upload).
+5. **Fallback** — the dmabuf path is NOT GNOME-specific: it applies to any
+ compositor that offers dmabuf (GNOME/mutter, KDE/kwin, most wlroots) whenever
+ the encoder is **VAAPI** (the default Linux backend with any GPU), so the large
+ majority of PipeWire desktop users benefit. shm stays as the fallback only for:
+ (a) compositors that offer *only* shm (some `xdg-desktop-portal-wlr` configs —
+ why shm is listed first today), and (b) non-VAAPI encoders (software
+ libopenh264 / Vulkan), whose dmabuf import isn't wired yet — they keep today's
+ shm + sws_scale + hwupload path. Also fall back if enumeration/import/VPP fails.
+ Never regress software-encode or shm-only-compositor users.
+
+## Decision: zero-copy (option B)
+
+Chosen over the pragmatic GPU-detile→CPU-readback path. The dmabuf stays on the
+GPU end to end: `av_hwframe_map` (DRM_PRIME→VAAPI) → `scale_vaapi` VPP (format +
+crop) into our own NV12 surface → encode. No CPU readback.
+
+Key architecture calls:
+- **One shared VAAPI `AVHWDeviceContext`** created up front, used by BOTH the
+ importer (PipeWire thread) and the encoder (main loop). A single mutex guards
+ all VADisplay ops (import+VPP vs encode) since libva isn't thread-safe per
+ display. Contention is negligible (both are GPU-driven).
+- **Import runs on the PipeWire thread inside `on_frame`**, while the PW buffer is
+ still held (before requeue), so the dmabuf content is stable during the map+VPP
+ copy. The result is our own NV12 VAAPI surface (ref-counted `AVFrame`) placed in
+ the mailbox; the PW buffer requeues immediately after. This preserves the
+ clock-driven hold (we own the surface; the compositor buffer is returned).
+- **v1 targets full monitor (no crop)**: importer/VPP sized to the stream at
+ `stream-started`. Window crop via VPP is a follow-up.
+- **Fallback** to the existing shm + sws_scale + hwupload path when: backend isn't
+ VAAPI, the compositor only offers shm, or any of map/VPP/import fails.
+
+## Status / steps
+
+- [x] **Foundation**: generate ffmpeg DRM bindings (`build.rs` +
+ `hwcontext_drm.h`). Verified `AVDRMFrameDescriptor`, `AV_PIX_FMT_DRM_PRIME`,
+ `AV_HWDEVICE_TYPE_DRM` present.
+- [x] **Negotiation** (validated on AMD/mutter): enumerate importable modifiers
+ via EGL surfaceless (`csrc/dmabuf_modifiers.c`) and advertise them in
+ `osc_build_enum_format_dmabuf`. Confirmed mutter now negotiates a **tiled
+ dmabuf** (`stream-started` fires) where before it failed with "no more input
+ formats". Enumeration returns 10 AMD GFX9 modifiers for XRGB8888. The existing
+ `mmap` path then correctly reports "driver does not allow CPU mapping" — the
+ exact branch point for the GPU import below.
+- [x] Extend `osc_pw_frame` (pw_shim.h) + `RawFrame` (shim.rs) with
+ is_dmabuf/modifier/fourcc/n_planes/plane_fd/offset/stride. Layouts mirror
+ exactly; builds green.
+- [x] C: `osc_read_frame` populates the descriptor for a tiled dmabuf;
+ `osc_on_add_buffer` latches `import_dmabuf` on mmap failure instead of erroring;
+ fourcc mapping added. shm/linear-dmabuf paths unchanged. `on_frame` currently
+ skips 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.
+- [ ] Test on AMD/GNOME: confirm `uses_dmabuf=1`, distinct-fps ≈ OBS (~24),
+ crop correct for window captures, cursor unaffected. Regression-check
+ software encode and a wlroots/niri compositor.
+
+## Risk notes
+
+- radeonsi VAAPI must import the specific tiled modifier mutter exports — highly
+ likely OK (GNOME/OBS do DRM→VAAPI on this GPU), but the concrete failure mode
+ is `av_hwframe_map` returning an error → must fall back cleanly.
+- Concurrency: import/VPP needs the VAAPI context; keep it on the main loop
+ (as sws_scale is today), holding the PW buffer only until the next tick.
diff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rs
index 9d3a03ec7..5d1975d54 100644
--- a/electron/native/pipewire-capture/src/shim.rs
+++ b/electron/native/pipewire-capture/src/shim.rs
@@ -46,6 +46,17 @@ pub struct RawFrame {
pub crop_width: i32,
pub crop_height: i32,
pub has_crop: i32,
+ /// Zero-copy dmabuf hand-off (issue #507). When non-zero, `data` is null and
+ /// the frame is a tiled GPU buffer described by the fields below — imported
+ /// as a VAAPI surface rather than read from `data`. Layout mirrors
+ /// `struct osc_pw_frame` in pw_shim.h exactly.
+ pub is_dmabuf: i32,
+ pub modifier: u64,
+ pub drm_fourcc: u32,
+ pub n_planes: i32,
+ pub plane_fd: [i32; 4],
+ pub plane_offset: [i32; 4],
+ pub plane_stride: [i32; 4],
}
#[repr(C)]