Skip to content

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

fix(capture): address CodeRabbit review on #508

Benjamin Freemandd1b40e264f1
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.c b/electron/native/pipewire-capture/csrc/pw_shim.c
index d094e3007..95915dc98 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.c
+++ b/electron/native/pipewire-capture/csrc/pw_shim.c
@@ -432,7 +432,8 @@ static const struct spa_pod *osc_build_enum_format(struct spa_pod_builder *build
* which needs a GPU query, so letting the producer fixate is both simpler and
* one fewer round trip that can go wrong.
*/
-static const struct spa_pod *osc_build_enum_format_dmabuf(struct spa_pod_builder *builder)
+static const struct spa_pod *osc_build_enum_format_dmabuf(struct spa_pod_builder *builder,
+ int prefer_dmabuf)
{
struct spa_pod_frame object_frame;
struct spa_pod_frame choice_frame;
@@ -459,10 +460,17 @@ static const struct spa_pod *osc_build_enum_format_dmabuf(struct spa_pod_builder
* stay as universal fallbacks. Modifiers match across the 32-bit RGB formats
* we offer, so enumerating XRGB8888 is representative.
*
+ * ONLY when prefer_dmabuf: the tiled modifiers are advertised solely when the
+ * VAAPI import pipeline is available. Otherwise a producer that offers no shm
+ * format (some wlroots/portal setups) could select a tiled buffer we cannot
+ * read, where before it would have fallen to a CPU-mappable LINEAR/INVALID
+ * dmabuf. Offering just those two keeps that path intact.
+ *
* Default first, then every alternative — the default is repeated, same
* idiom as SPA_POD_CHOICE_ENUM_Id above. */
uint64_t egl_mods[128];
- int egl_mod_count = osc_query_dmabuf_modifiers(OSC_DRM_FORMAT_XRGB8888, egl_mods, 128);
+ int egl_mod_count =
+ prefer_dmabuf ? osc_query_dmabuf_modifiers(OSC_DRM_FORMAT_XRGB8888, egl_mods, 128) : 0;
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);
@@ -577,7 +585,9 @@ int osc_pw_enum_format_accepts_dmabuf_producer(int with_modifier, int64_t produc
const struct spa_pod *consumer;
const struct spa_pod *producer;
- consumer = with_modifier ? osc_build_enum_format_dmabuf(&ours) : osc_build_enum_format(&ours);
+ /* The unit test exercises the full tiled offer, so enumerate unconditionally. */
+ consumer =
+ with_modifier ? osc_build_enum_format_dmabuf(&ours, 1) : osc_build_enum_format(&ours);
if (consumer == NULL) {
return -1;
}
@@ -1241,8 +1251,11 @@ static void osc_describe_metas(const struct spa_buffer *buffer, char *out, size_
}
}
-static void osc_inspect_buffer(struct osc_pw_session *session, const struct spa_buffer *buffer)
+/* Returns 1 when the on_frame callback took ownership of `pw_buf` (a dmabuf frame
+ * held for GPU import); the caller must then NOT re-queue it. 0 otherwise. */
+static int osc_inspect_buffer(struct osc_pw_session *session, struct pw_buffer *pw_buf)
{
+ const struct spa_buffer *buffer = pw_buf->buffer;
struct osc_pw_cursor cursor;
uint32_t meta_size = 0;
@@ -1274,7 +1287,15 @@ static void osc_inspect_buffer(struct osc_pw_session *session, const struct spa_
session->dmabuf_sync_fd = -1;
if (osc_read_frame(session, buffer, &frame)) {
- session->callbacks.on_frame(session->callbacks.user, &frame);
+ /* The callback needs the pw_buffer to hand back to osc_pw_requeue_buffer
+ * if it takes ownership of a dmabuf frame. */
+ frame.buffer_handle = pw_buf;
+ if (session->callbacks.on_frame(session->callbacks.user, &frame)) {
+ /* Taken: leave it un-queued; the consumer will re-queue it once the
+ * import has copied the pixels. No SYNC bracket is open on this
+ * path (the import path does not CPU-read), so nothing to close. */
+ return 1;
+ }
}
/* Closes the DMA_BUF_SYNC_START osc_read_frame opened, if any. Placed
* here rather than inside it because the callback above is what actually
@@ -1284,6 +1305,7 @@ static void osc_inspect_buffer(struct osc_pw_session *session, const struct spa_
session->dmabuf_sync_fd = -1;
}
}
+ return 0;
}
static void osc_on_process(void *userdata)
@@ -1313,11 +1335,26 @@ static void osc_on_process(void *userdata)
* throw away the cursor metadata riding on the same buffers.
*/
while ((b = api.stream_dequeue_buffer(session->stream)) != NULL) {
- osc_inspect_buffer(session, b->buffer);
- api.stream_queue_buffer(session->stream, b);
+ /* A dmabuf frame the consumer takes is held out of the queue until it has
+ * imported the pixels — see osc_pw_requeue_buffer. Everything else (shm,
+ * cursor-only buffers, declined frames) re-queues immediately. */
+ if (!osc_inspect_buffer(session, b)) {
+ api.stream_queue_buffer(session->stream, b);
+ }
}
}
+/* See the header. Locks the thread loop so a foreign thread can queue safely. */
+void osc_pw_requeue_buffer(struct osc_pw_session *session, void *buffer_handle)
+{
+ if (session == NULL || buffer_handle == NULL || session->stream == NULL) {
+ return;
+ }
+ api.thread_loop_lock(session->loop);
+ api.stream_queue_buffer(session->stream, (struct pw_buffer *)buffer_handle);
+ api.thread_loop_unlock(session->loop);
+}
+
static const struct pw_stream_events osc_stream_events = {
PW_VERSION_STREAM_EVENTS,
.state_changed = osc_on_state_changed,
@@ -1410,7 +1447,7 @@ struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id, int want_video,
* previously failed the whole negotiation with "no more input formats".
*/
params[0] = osc_build_enum_format(&builder);
- params[1] = osc_build_enum_format_dmabuf(&builder);
+ params[1] = osc_build_enum_format_dmabuf(&builder, session->prefer_dmabuf);
/*
* When the GPU import path is available (prefer_dmabuf), offer dmabuf FIRST
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.h b/electron/native/pipewire-capture/csrc/pw_shim.h
index f4d3a04c3..1f013e426 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.h
+++ b/electron/native/pipewire-capture/csrc/pw_shim.h
@@ -102,10 +102,13 @@ struct osc_pw_frame {
* 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.
+ * When the on_frame callback TAKES a dmabuf frame (returns non-zero), the
+ * PipeWire buffer is NOT re-queued here — `buffer_handle` is retained by the
+ * consumer, which keeps the fds and their CONTENT valid until it has imported
+ * and copied the surface, then calls osc_pw_requeue_buffer. Duplicating the
+ * fds alone would preserve the dmabuf object but not a snapshot of its pixels,
+ * so a re-queued buffer the compositor overwrote could be encoded torn.
+ * `modifier`/`drm_fourcc` describe the tiling and pixel layout.
*/
int is_dmabuf;
uint64_t modifier; /* DRM format modifier of the buffer */
@@ -114,6 +117,10 @@ struct osc_pw_frame {
int plane_fd[4];
int32_t plane_offset[4];
int32_t plane_stride[4];
+ /* The `struct pw_buffer *` this frame came from, opaque to the consumer.
+ * Passed back to osc_pw_requeue_buffer once the import is done. Only set (and
+ * only meaningful) for a dmabuf frame the consumer intends to take. */
+ void *buffer_handle;
};
/* The negotiated video format. Reported once, from param_changed. */
@@ -133,8 +140,12 @@ struct osc_pw_callbacks {
void *user;
void (*on_format)(void *user, const struct osc_pw_format *format);
void (*on_cursor)(void *user, const struct osc_pw_cursor *cursor);
- /* Only ever called when osc_pw_start was given want_video != 0. */
- void (*on_frame)(void *user, const struct osc_pw_frame *frame);
+ /* Only ever called when osc_pw_start was given want_video != 0. Returns
+ * non-zero to TAKE OWNERSHIP of the PipeWire buffer (`frame->buffer_handle`):
+ * the shim then does NOT re-queue it, and the consumer must later call
+ * osc_pw_requeue_buffer. Zero (the shm/CPU path, and any dmabuf frame the
+ * consumer declines) re-queues immediately as before. */
+ int (*on_frame)(void *user, const struct osc_pw_frame *frame);
/* Emitted once per negotiated buffer set. `data_type` is the SPA_DATA_* of
* datas[0]; `metas` is a borrowed "Header:12,Cursor:589872" listing of every
* metadata block that survived negotiation, which is what distinguishes a
@@ -228,6 +239,18 @@ struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id, int want_video,
const struct osc_pw_callbacks *callbacks, char *err,
size_t err_len);
+/*
+ * Re-queues a PipeWire buffer the on_frame callback took ownership of (returned
+ * non-zero for), identified by the `buffer_handle` it was given. Call it once the
+ * frame's pixels have been imported and copied.
+ *
+ * SAFE TO CALL FROM ANY THREAD: it takes the PipeWire thread-loop lock around the
+ * queue, so unlike the shim's own callbacks it must NOT be called from the
+ * PipeWire thread itself (that would deadlock). The consumer requeues from its
+ * own loop, which is a different thread. NULL session or handle is a no-op.
+ */
+void osc_pw_requeue_buffer(struct osc_pw_session *session, void *buffer_handle);
+
/* Stops the thread loop, joins it, and frees everything. Safe with NULL. */
void osc_pw_stop(struct osc_pw_session *session);
diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rs
index 4324f3b01..f6fe75dc3 100644
--- a/electron/native/pipewire-capture/src/capture.rs
+++ b/electron/native/pipewire-capture/src/capture.rs
@@ -244,7 +244,11 @@ impl Capture {
) -> Result<(Self, Selection), String> {
let bitrate = bitrate.unwrap_or_else(|| default_bitrate(width, height, fps));
let mut rejected = Vec::new();
- let (encoder, importer) = match dmabuf {
+ // The dmabuf import can only feed VAAPI, so a user forcing `software` or
+ // `vulkan` must skip it — otherwise the documented `forced` workaround
+ // (VideoEncoder::open) would be silently ignored on the dmabuf path.
+ let use_dmabuf = matches!(forced, None | Some(Backend::Vaapi));
+ let (encoder, importer) = match dmabuf.filter(|_| use_dmabuf) {
Some(desc) => {
// The importer maps the full stream (`desc`) and its VPP crops to
// the committed record size (`width`/`height`): equal to the source
@@ -366,7 +370,6 @@ impl Capture {
// surface (the VPP crops a window to its committed rectangle) and hand it
// to the encoder as-is — no swscale. See issue #507.
if frame.dmabuf.is_some() {
- use std::os::fd::AsRawFd;
// The crop origin, clamped to stay inside the buffer — same rule as the
// CPU path. Computed before the mutable importer borrow. For a monitor
// this is (0, 0).
@@ -380,7 +383,7 @@ impl Capture {
.planes
.iter()
.map(|plane| crate::dmabuf_import::DmabufPlane {
- fd: plane.fd.as_raw_fd(),
+ fd: plane.fd,
offset: plane.offset,
stride: plane.stride,
})
@@ -633,6 +636,7 @@ mod tests {
pts_ns: -1,
crop: shim::CropRect { x: 0, y: 0, width, height },
has_crop: false,
+ dmabuf: None,
}
}
@@ -677,7 +681,7 @@ mod tests {
fn the_timeline_does_not_start_until_the_first_frame_is_staged() {
let output = std::env::temp_dir().join("openscreen-capture-epoch.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
assert!(!capture.started());
// Nothing staged: advance must not write a frame of uninitialised memory.
@@ -696,7 +700,7 @@ mod tests {
// further arrivals, and the file must still fill with frames.
let output = std::env::temp_dir().join("openscreen-capture-static.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
capture
.stage(&frame(320, 240, shim::constants().video_format_bgrx))
@@ -721,7 +725,7 @@ mod tests {
fn a_window_is_staged_from_its_crop_inside_a_larger_frame() {
let output = std::env::temp_dir().join("openscreen-capture-crop.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
// A 1920x1080 stream carrying a 320x240 window at (100, 50).
@@ -752,7 +756,7 @@ mod tests {
fn a_crop_against_the_right_edge_is_not_rejected_as_truncated() {
let output = std::env::temp_dir().join("openscreen-capture-edge.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
let staged = capture.stage(&cropped_frame(
@@ -775,7 +779,7 @@ mod tests {
fn a_shrunken_window_is_read_from_inside_the_frame() {
let output = std::env::temp_dir().join("openscreen-capture-shrunk.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
// Origin so close to the edge that a 320x240 read from it would overrun.
@@ -801,7 +805,7 @@ mod tests {
let output = std::env::temp_dir().join("openscreen-capture-odd.mp4");
// 321x241 rounds to the 320x240 the encoder is opened at.
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
let frame = cropped_frame(
@@ -820,7 +824,7 @@ mod tests {
fn an_uncropped_frame_reports_no_divergence() {
let output = std::env::temp_dir().join("openscreen-capture-nocrop.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
assert!(!capture.crop_diverged(&frame(320, 240, shim::constants().video_format_bgrx)));
@@ -832,7 +836,7 @@ mod tests {
fn paused_time_does_not_advance_the_timeline() {
let output = std::env::temp_dir().join("openscreen-capture-pause.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 30, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
capture
.stage(&frame(320, 240, shim::constants().video_format_bgrx))
@@ -872,6 +876,7 @@ mod tests {
Some(1_000_000),
Some(Backend::Software),
vec![AudioSource { label: "system", ring: ring.clone(), gain: 1.0, bitrate: 128_000 }],
+ None,
)
.expect("start");
@@ -908,6 +913,7 @@ mod tests {
Some(1_000_000),
Some(Backend::Software),
vec![AudioSource { label: "system", ring: ring.clone(), gain: 1.0, bitrate: 128_000 }],
+ None,
)
.expect("start");
capture
@@ -950,6 +956,7 @@ mod tests {
Some(1_000_000),
Some(Backend::Software),
vec![AudioSource { label: "microphone", ring, gain: 4.0, bitrate: 128_000 }],
+ None,
)
.expect("start");
capture
@@ -989,6 +996,7 @@ mod tests {
AudioSource { label: "system", ring: system.clone(), gain: 1.0, bitrate: 128_000 },
AudioSource { label: "microphone", ring: mic.clone(), gain: 1.0, bitrate: 128_000 },
],
+ None,
)
.expect("start");
@@ -1038,6 +1046,7 @@ mod tests {
AudioSource { label: "system", ring: system.clone(), gain: 1.0, bitrate: 128_000 },
AudioSource { label: "microphone", ring: dead, gain: 1.0, bitrate: 128_000 },
],
+ None,
)
.expect("start");
capture
@@ -1061,7 +1070,7 @@ mod tests {
fn catch_up_is_bounded_so_a_stall_cannot_block_stop() {
let output = std::env::temp_dir().join("openscreen-capture-catchup.mp4");
let (mut capture, _) =
- Capture::start(&output, 320, 240, 60, Some(1_000_000), Some(Backend::Software), Vec::new())
+ Capture::start(&output, 320, 240, 60, Some(1_000_000), Some(Backend::Software), Vec::new(), None)
.expect("start");
capture
.stage(&frame(320, 240, shim::constants().video_format_bgrx))
diff --git a/electron/native/pipewire-capture/src/dmabuf_import.rs b/electron/native/pipewire-capture/src/dmabuf_import.rs
index 1cc7669ee..71b8d9a6f 100644
--- a/electron/native/pipewire-capture/src/dmabuf_import.rs
+++ b/electron/native/pipewire-capture/src/dmabuf_import.rs
@@ -21,9 +21,12 @@ unsafe fn free_frame(frame: *mut ff::AVFrame) {
ff::av_frame_free(&mut p);
}
-/// The AVBufferRef around the DRM descriptor owns nothing heap-allocated (the
-/// descriptor is a stack local that outlives the map), so freeing it is a no-op.
-unsafe extern "C" fn noop_buffer_free(_opaque: *mut std::ffi::c_void, _data: *mut u8) {}
+/// Frees the heap-allocated `AVDRMFrameDescriptor` when its AVBufferRef drops —
+/// which is after the mapped frame that retained the source (and thus this
+/// buffer) is released.
+unsafe extern "C" fn drm_descriptor_free(_opaque: *mut std::ffi::c_void, data: *mut u8) {
+ ff::av_free(data as *mut std::ffi::c_void);
+}
/// 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.
@@ -272,11 +275,12 @@ impl DmabufImporter {
(*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(in->vpp): {}", ff::err_to_string(rc)));
}
+ let rc = ff::avfilter_link(scale_ctx, 0, self.buffersink_ctx, 0);
if rc < 0 {
- return Err(format!("avfilter_link: {}", ff::err_to_string(rc)));
+ return Err(format!("avfilter_link(vpp->out): {}", ff::err_to_string(rc)));
}
let rc = ff::avfilter_graph_config(self.graph, ptr::null_mut());
@@ -311,44 +315,58 @@ impl DmabufImporter {
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.
+ // All planes must share one fd: we build a single DRM object from
+ // planes[0].fd and point every plane at it, so a buffer whose planes span
+ // multiple fds would make VAAPI read the wrong memory. Our RGB formats are
+ // single-plane; guard the assumption rather than rely on it.
+ if frame.planes.iter().any(|plane| plane.fd != frame.planes[0].fd) {
+ return Err("dmabuf planes span multiple fds, which this importer does not handle".to_owned());
+ }
+ // SAFETY: every allocated frame/buffer is freed 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;
+ // The DRM descriptor must outlive the mapped frame: av_hwframe_map
+ // retains `src` (ref-counted) until the mapping is released, so a
+ // stack descriptor would dangle once this function returns. Allocate
+ // it on the heap and free it from the AVBufferRef's own callback.
+ let desc = ff::av_mallocz(std::mem::size_of::<ff::AVDRMFrameDescriptor>())
+ as *mut ff::AVDRMFrameDescriptor;
+ if desc.is_null() {
+ return Err("av_mallocz(drm descriptor) failed".to_owned());
+ }
+ (*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;
+ (*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() {
+ ff::av_free(desc as *mut std::ffi::c_void);
return Err("av_frame_alloc(src) failed".to_owned());
}
(*src).format = ff::AV_PIX_FMT_DRM_PRIME as i32;
(*src).width = self.src_width;
(*src).height = self.src_height;
- // av_hwframe_map rejects a source frame that is not ref-counted, so
- // wrap the descriptor in an AVBufferRef (freed as a no-op — `desc`
- // lives on the stack until this function returns, past the map).
+ // av_hwframe_map needs a ref-counted source; wrap the heap descriptor
+ // in an AVBufferRef that frees it when the last reference drops (which
+ // is after the mapped frame that retains `src` is released).
let buf = ff::av_buffer_create(
- &mut desc as *mut _ as *mut u8,
+ desc as *mut u8,
std::mem::size_of::<ff::AVDRMFrameDescriptor>(),
- Some(noop_buffer_free),
+ Some(drm_descriptor_free),
ptr::null_mut(),
0,
);
if buf.is_null() {
+ ff::av_free(desc as *mut std::ffi::c_void);
free_frame(src);
return Err("av_buffer_create(drm descriptor) failed".to_owned());
}
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index 61aba8c8f..2d547ac7a 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -609,6 +609,18 @@ fn run<W: Write>(
let mut exit_code = 0;
loop {
+ // Return PipeWire buffers whose dmabuf imports completed last iteration
+ // (or that were superseded on the capture thread). This MUST run on this
+ // loop, not the PipeWire thread — `Session::requeue` takes the thread-loop
+ // lock, which would deadlock from inside the loop. The one-tick delay is
+ // harmless: the import has already copied the pixels, so the buffer is
+ // free, and the pool has other buffers in flight meanwhile.
+ if let (Some(session), Some(mailbox)) = (session.as_ref(), frames.as_ref()) {
+ for handle in mailbox.drain_requeue() {
+ session.requeue(handle);
+ }
+ }
+
match receiver.recv_timeout(config.tick) {
Ok(Message::Stop) => break,
diff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rs
index a37693b81..3a4024b23 100644
--- a/electron/native/pipewire-capture/src/shim.rs
+++ b/electron/native/pipewire-capture/src/shim.rs
@@ -57,8 +57,22 @@ pub struct RawFrame {
pub plane_fd: [i32; 4],
pub plane_offset: [i32; 4],
pub plane_stride: [i32; 4],
+ /// The `struct pw_buffer *` this frame came from (opaque). Returned to
+ /// `osc_pw_requeue_buffer` once the dmabuf import has copied the pixels, if
+ /// `on_frame` took ownership of it. Null/unused on the CPU path.
+ pub buffer_handle: *mut c_void,
}
+/// A `struct pw_buffer *` we are holding out of PipeWire's queue until its dmabuf
+/// content has been imported. Send so it can travel through the mailbox; the raw
+/// pointer is only ever handed back to `osc_pw_requeue_buffer`, never dereferenced
+/// on the Rust side.
+#[derive(Debug, Clone, Copy)]
+pub struct BufferHandle(pub *mut c_void);
+// SAFETY: the pointer is an opaque token owned by libpipewire; Rust neither reads
+// nor writes through it, only returns it to the shim's locked requeue.
+unsafe impl Send for BufferHandle {}
+
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct RawFormat {
@@ -74,7 +88,7 @@ struct RawCallbacks {
user: *mut c_void,
on_format: extern "C" fn(*mut c_void, *const RawFormat),
on_cursor: extern "C" fn(*mut c_void, *const RawCursor),
- on_frame: extern "C" fn(*mut c_void, *const RawFrame),
+ on_frame: extern "C" fn(*mut c_void, *const RawFrame) -> i32,
on_buffer_info: extern "C" fn(*mut c_void, u32, u32, i32, u32, *const c_char),
on_state: extern "C" fn(*mut c_void, *const c_char, *const c_char),
}
@@ -123,6 +137,7 @@ extern "C" {
err_len: usize,
) -> *mut RawSession;
fn osc_pw_stop(session: *mut RawSession);
+ fn osc_pw_requeue_buffer(session: *mut RawSession, buffer_handle: *mut c_void);
}
/// Where stream events go. Called on the PipeWire thread, so it must not block:
@@ -198,22 +213,54 @@ pub struct Frame {
pub dmabuf: Option<DmabufDesc>,
}
-/// A tiled dmabuf handed up for GPU import. Owns duplicated plane fds so the
-/// descriptor outlives the PipeWire buffer it came from.
-#[derive(Debug)]
+/// A tiled dmabuf handed up for GPU import. Holds the PipeWire buffer OUT of the
+/// queue (via `buffer_handle`) so the plane fds AND their content stay valid until
+/// the import copies the surface — dup'ing the fds alone would preserve the object
+/// but not a content snapshot, letting the compositor overwrite a re-queued buffer
+/// (CodeRabbit / issue #507). On drop the handle is pushed to `requeue`, which the
+/// main loop drains and hands back to the shim's locked re-queue.
pub struct DmabufDesc {
pub width: i32,
pub height: i32,
pub drm_fourcc: u32,
pub modifier: u64,
- pub planes: Vec<DmabufPlaneOwned>,
+ pub planes: Vec<DmabufPlane>,
+ buffer_handle: BufferHandle,
+ requeue: std::sync::Arc<std::sync::Mutex<Vec<BufferHandle>>>,
+}
+
+impl std::fmt::Debug for DmabufDesc {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("DmabufDesc")
+ .field("width", &self.width)
+ .field("height", &self.height)
+ .field("drm_fourcc", &self.drm_fourcc)
+ .field("modifier", &self.modifier)
+ .field("planes", &self.planes)
+ .finish_non_exhaustive()
+ }
+}
+
+impl Drop for DmabufDesc {
+ fn drop(&mut self) {
+ // Return the held PipeWire buffer once the import that read it is done
+ // (which is why this runs at drop, after `Capture::stage`). Pushed to the
+ // queue rather than re-queued here because re-queue must run on the main
+ // loop, not the PipeWire thread that supersedes a frame — see
+ // FrameMailbox and osc_pw_requeue_buffer.
+ if !self.buffer_handle.0.is_null() {
+ if let Ok(mut queue) = self.requeue.lock() {
+ queue.push(self.buffer_handle);
+ }
+ }
+ }
}
-/// One dmabuf plane: an owned (dup'd) fd plus its layout. The fd is closed when
-/// this drops.
+/// One dmabuf plane: a BORROWED fd (owned by the still-held PipeWire buffer) plus
+/// its layout. Valid until the buffer is re-queued.
#[derive(Debug)]
-pub struct DmabufPlaneOwned {
- pub fd: std::os::fd::OwnedFd,
+pub struct DmabufPlane {
+ pub fd: i32,
pub offset: i32,
pub stride: i32,
}
@@ -243,6 +290,11 @@ pub struct FrameMailbox {
inner: std::sync::Mutex<Mailbox>,
received: std::sync::atomic::AtomicU64,
dropped: std::sync::atomic::AtomicU64,
+ /// PipeWire buffers held for a dmabuf import, to be re-queued once their
+ /// `DmabufDesc` drops (import done, or frame superseded). Drained by the main
+ /// loop, which re-queues each through the shim's locked path. Shared into each
+ /// `DmabufDesc` so its Drop can push here from either thread.
+ requeue: std::sync::Arc<std::sync::Mutex<Vec<BufferHandle>>>,
}
#[derive(Debug, Default)]
@@ -349,6 +401,21 @@ impl FrameMailbox {
inner.spare = Some(pixels);
}
+ /// A clone of the held-buffer re-queue queue, for a `DmabufDesc` to push its
+ /// PipeWire buffer to when it drops.
+ fn requeue_queue(&self) -> std::sync::Arc<std::sync::Mutex<Vec<BufferHandle>>> {
+ self.requeue.clone()
+ }
+
+ /// Takes the PipeWire buffers whose dmabuf imports have completed (or were
+ /// superseded), for the main loop to re-queue through the shim.
+ pub fn drain_requeue(&self) -> Vec<BufferHandle> {
+ match self.requeue.lock() {
+ Ok(mut queue) => std::mem::take(&mut *queue),
+ Err(_) => Vec::new(),
+ }
+ }
+
/// Frames the compositor delivered.
pub fn received(&self) -> u64 {
self.received.load(std::sync::atomic::Ordering::Relaxed)
@@ -865,6 +932,16 @@ impl Session {
Ok(Self { raw, _state: state })
}
+
+ /// Re-queues a PipeWire buffer a dmabuf frame took ownership of, once its
+ /// import has copied the pixels. Call from the main loop (NOT the PipeWire
+ /// thread) — the shim takes the thread-loop lock. Drain the mailbox's
+ /// `drain_requeue` for the handles.
+ pub fn requeue(&self, handle: BufferHandle) {
+ // SAFETY: `raw` is a live session for the lifetime of `self`; the handle
+ // is an opaque pw_buffer token the shim validates and only re-queues.
+ unsafe { osc_pw_requeue_buffer(self.raw, handle.0) };
+ }
}
impl Drop for Session {
@@ -911,78 +988,73 @@ extern "C" fn on_format(user: *mut c_void, format: *const RawFormat) {
});
}
-extern "C" fn on_frame(user: *mut c_void, frame: *const RawFrame) {
- with_state(user, |state| {
- let Some(mailbox) = state.frames.as_ref() else {
- return;
- };
- if frame.is_null() {
- return;
+/// Returns 1 when we TAKE OWNERSHIP of the PipeWire buffer — a tiled dmabuf held
+/// out of the queue until the main loop imports it — so the shim must not re-queue
+/// it. 0 otherwise (the CPU path, or any frame we decline), which re-queues as
+/// before.
+extern "C" fn on_frame(user: *mut c_void, frame: *const RawFrame) -> i32 {
+ if user.is_null() || frame.is_null() {
+ return 0;
+ }
+ // SAFETY: `user` is the CallbackState pointer given to osc_pw_start, valid for
+ // the session's lifetime; `frame` is valid for the callback's duration.
+ let state = unsafe { &*(user as *const CallbackState) };
+ let Some(mailbox) = state.frames.as_ref() else {
+ return 0;
+ };
+ let frame = unsafe { &*frame };
+
+ // Tiled dmabuf: no pixels to copy. Take the PipeWire buffer (hold it out of
+ // the queue) so the plane fds AND their content stay valid until the main-loop
+ // import copies the surface; the buffer is re-queued when the DmabufDesc drops.
+ if frame.is_dmabuf != 0 {
+ let n = frame.n_planes.clamp(0, 4) as usize;
+ if n == 0 {
+ return 0;
}
- // SAFETY: non-NULL for the duration of the callback, by contract.
- let frame = unsafe { &*frame };
-
- // Tiled dmabuf: no pixels to copy. Duplicate the plane fds (cheap, and it
- // keeps the buffer's content reachable after the PW buffer re-queues) and
- // hand the descriptor to the main loop for a GPU import.
- if frame.is_dmabuf != 0 {
- use std::os::fd::{AsRawFd, BorrowedFd};
- let n = frame.n_planes.clamp(0, 4) as usize;
- if n == 0 {
- return;
+ let mut planes = Vec::with_capacity(n);
+ for i in 0..n {
+ let fd = frame.plane_fd[i];
+ if fd < 0 {
+ return 0;
}
- let mut planes = Vec::with_capacity(n);
- for i in 0..n {
- let raw = frame.plane_fd[i];
- if raw < 0 {
- return;
- }
- // SAFETY: `raw` is valid for the callback's duration; try_clone
- // dups it (F_DUPFD_CLOEXEC) into an fd we own.
- let borrowed = unsafe { BorrowedFd::borrow_raw(raw) };
- let Ok(owned) = borrowed.try_clone_to_owned() else {
- return;
- };
- debug_assert!(owned.as_raw_fd() >= 0);
- planes.push(DmabufPlaneOwned {
- fd: owned,
- offset: frame.plane_offset[i],
- stride: frame.plane_stride[i],
- });
- }
- mailbox.put_dmabuf(
- DmabufDesc {
- width: frame.width,
- height: frame.height,
- drm_fourcc: frame.drm_fourcc,
- modifier: frame.modifier,
- planes,
- },
- frame,
- );
- (state.sink)(StreamEvent::FrameReady);
- return;
- }
-
- if frame.data.is_null() || frame.stride <= 0 || frame.height <= 0 {
- return;
- }
- // Copy only the rows, not the whole mapping. `size` can include trailing
- // slack the compositor allocated, and re-checking the product here means
- // the slice below cannot outrun the region the C side validated.
- let Some(rows) = (frame.stride as usize).checked_mul(frame.height as usize) else {
- return;
- };
- if rows > frame.size {
- return;
+ planes.push(DmabufPlane { fd, offset: frame.plane_offset[i], stride: frame.plane_stride[i] });
}
- // SAFETY: the shim clamped `size` against the mapping's `maxsize` before
- // the callback, `rows <= size` was just checked, and the mapping stays
- // live until this returns.
- let pixels = unsafe { std::slice::from_raw_parts(frame.data, rows) };
- mailbox.put(pixels, frame);
+ mailbox.put_dmabuf(
+ DmabufDesc {
+ width: frame.width,
+ height: frame.height,
+ drm_fourcc: frame.drm_fourcc,
+ modifier: frame.modifier,
+ planes,
+ buffer_handle: BufferHandle(frame.buffer_handle),
+ requeue: mailbox.requeue_queue(),
+ },
+ frame,
+ );
(state.sink)(StreamEvent::FrameReady);
- });
+ return 1;
+ }
+
+ if frame.data.is_null() || frame.stride <= 0 || frame.height <= 0 {
+ return 0;
+ }
+ // Copy only the rows, not the whole mapping. `size` can include trailing
+ // slack the compositor allocated, and re-checking the product here means
+ // the slice below cannot outrun the region the C side validated.
+ let Some(rows) = (frame.stride as usize).checked_mul(frame.height as usize) else {
+ return 0;
+ };
+ if rows > frame.size {
+ return 0;
+ }
+ // SAFETY: the shim clamped `size` against the mapping's `maxsize` before
+ // the callback, `rows <= size` was just checked, and the mapping stays
+ // live until this returns.
+ let pixels = unsafe { std::slice::from_raw_parts(frame.data, rows) };
+ mailbox.put(pixels, frame);
+ (state.sink)(StreamEvent::FrameReady);
+ 0
}
extern "C" fn on_buffer_info(
@@ -1207,6 +1279,8 @@ mod tests {
// Cursor-only: this test is about negotiation reaching `streaming`
// and about which metadata survives, neither of which needs pixels.
None,
+ // Cursor-only, so dmabuf preference is irrelevant.
+ false,
)
.expect("stream must connect");