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): the Linux helper now records video, not just the cursor

Etienne Lescot8143f30b6c8d
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.c b/electron/native/pipewire-capture/csrc/pw_shim.c
index d6377b6d9..1d6470152 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.c
+++ b/electron/native/pipewire-capture/csrc/pw_shim.c
@@ -131,6 +131,7 @@ struct osc_pw_session {
struct osc_pw_callbacks callbacks;
struct spa_video_info_raw format;
int buffer_info_reports;
+ int want_video;
};
static void osc_set_error(char *err, size_t err_len, const char *format, ...)
@@ -321,18 +322,26 @@ static void osc_on_param_changed(void *userdata, uint32_t id, const struct spa_p
}
/*
- * No `size`/`stride` constraint is published: Stage 1 does not map the
- * buffers (see the missing PW_STREAM_FLAG_MAP_BUFFERS in osc_pw_start), so
- * the compositor's own choice is fine. Every dataType is advertised so that
- * the value reported by on_buffer_info reflects what the compositor would
- * prefer, not what we forced it into.
+ * No `size`/`stride` constraint is published: the compositor's own choice is
+ * fine, and osc_read_frame validates whatever comes back.
+ *
+ * The dataType set differs by mode, and the difference is load-bearing.
+ * Cursor-only advertises everything, so that on_buffer_info reports what the
+ * compositor would PREFER rather than what we forced it into. Video mode
+ * advertises shared memory only: pw_stream does not map DmaBuf even with
+ * PW_STREAM_FLAG_MAP_BUFFERS, so accepting one would leave `datas[0].data`
+ * NULL and produce a recording of nothing. Importing DmaBuf properly is its
+ * own piece of work; until then, not offering it is what makes the
+ * compositor fall back to memfd instead.
*/
params[0] = spa_pod_builder_add_object(
&builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, SPA_PARAM_BUFFERS_buffers,
SPA_POD_CHOICE_RANGE_Int(4, 2, 16), SPA_PARAM_BUFFERS_blocks, SPA_POD_Int(1),
SPA_PARAM_BUFFERS_dataType,
- SPA_POD_CHOICE_FLAGS_Int((1 << SPA_DATA_MemPtr) | (1 << SPA_DATA_MemFd) |
- (1 << SPA_DATA_DmaBuf)));
+ SPA_POD_CHOICE_FLAGS_Int(session->want_video
+ ? ((1 << SPA_DATA_MemPtr) | (1 << SPA_DATA_MemFd))
+ : ((1 << SPA_DATA_MemPtr) | (1 << SPA_DATA_MemFd) |
+ (1 << SPA_DATA_DmaBuf))));
params[1] = spa_pod_builder_add_object(
&builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, SPA_PARAM_META_type,
@@ -452,6 +461,77 @@ static int osc_read_cursor(const struct spa_buffer *buffer, struct osc_pw_cursor
return 1;
}
+/*
+ * Extracts the pixels of one buffer. Returns 1 when `out` describes a frame, 0
+ * when this buffer carries none.
+ *
+ * The offset/size clamping against `maxsize` is the standard PipeWire consumer
+ * idiom and is not paranoia: `chunk` lives in memory the PRODUCER writes, so its
+ * fields are untrusted input from another process. A compositor bug — or a
+ * malicious one — that reports a size past the end of the mapping would
+ * otherwise be a read straight off the end of the shared memory.
+ */
+static int osc_read_frame(struct osc_pw_session *session, const struct spa_buffer *buffer,
+ struct osc_pw_frame *out)
+{
+ struct spa_data *data;
+ struct spa_meta_header *header;
+ uint32_t offset;
+ uint32_t size;
+ int32_t stride;
+ int32_t height;
+
+ memset(out, 0, sizeof(*out));
+ out->pts_ns = -1;
+
+ if (buffer->n_datas < 1) {
+ return 0;
+ }
+ data = &buffer->datas[0];
+ /*
+ * NULL means the buffer was never mapped: either this is a cursor-only
+ * session (no PW_STREAM_FLAG_MAP_BUFFERS) or the compositor handed us a
+ * DmaBuf, which pw_stream does not map even with the flag. Neither is an
+ * error here — the format negotiation excludes DmaBuf when want_video is
+ * set, so in practice this is the cursor-only case.
+ */
+ if (data->data == NULL || data->chunk == NULL) {
+ return 0;
+ }
+ /* A zero-sized chunk is how a compositor ships a cursor update with no new
+ * frame attached. Not an error, just not a frame. */
+ if (data->chunk->size == 0) {
+ 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) {
+ return 0;
+ }
+
+ out->data = SPA_PTROFF(data->data, 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) {
+ out->pts_ns = header->pts;
+ }
+ return 1;
+}
+
static const char *osc_meta_type_name(uint32_t type)
{
switch (type) {
@@ -527,6 +607,20 @@ static void osc_inspect_buffer(struct osc_pw_session *session, const struct spa_
if (osc_read_cursor(buffer, &cursor, &meta_size) && session->callbacks.on_cursor != NULL) {
session->callbacks.on_cursor(session->callbacks.user, &cursor);
}
+
+ /*
+ * Cursor first, then pixels. The order matters for the frame the cursor
+ * shape changes on: the consumer stamps its cursor track from the latest
+ * sample, and reading the cursor after the frame would attribute the new
+ * position to the NEXT frame instead of this one.
+ */
+ if (session->want_video && session->callbacks.on_frame != NULL) {
+ struct osc_pw_frame frame;
+
+ if (osc_read_frame(session, buffer, &frame)) {
+ session->callbacks.on_frame(session->callbacks.user, &frame);
+ }
+ }
}
static void osc_on_process(void *userdata)
@@ -546,8 +640,14 @@ static void osc_on_process(void *userdata)
* the cursor never moving.
*
* Reading metadata is a handful of struct field loads, so doing it per
- * buffer costs nothing, and nothing here touches the pixel data — there is
- * no reason to skip a buffer on the grounds that its frame is old.
+ * buffer costs nothing.
+ *
+ * Since Stage 2 this loop DOES touch pixels, and the same reasoning still
+ * holds — but for a different reason. The frame callback copies into a
+ * single-slot mailbox on the Rust side where a newer frame overwrites an
+ * unconsumed older one, so a backlog is dropped there, at the point that
+ * knows whether the encoder is keeping up. Dropping here instead would also
+ * 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);
@@ -562,7 +662,7 @@ static const struct pw_stream_events osc_stream_events = {
.process = osc_on_process,
};
-struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id,
+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)
{
@@ -585,6 +685,7 @@ struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id,
return NULL;
}
session->callbacks = *callbacks;
+ session->want_video = want_video;
session->loop = api.thread_loop_new("openscreen-pipewire", NULL);
if (session->loop == NULL) {
@@ -634,14 +735,14 @@ struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id,
}
/*
- * Flags, and the two that are absent on purpose:
- *
- * No PW_STREAM_FLAG_MAP_BUFFERS: Stage 1 reads metadata only, and mapping a
- * full-screen framebuffer on every buffer would be pure waste. Stage 2 adds
- * it when it starts consuming pixels. Metadata is unaffected — pw_stream maps
- * the buffer skeleton (and therefore every spa_meta) regardless of this flag;
+ * Flags. PW_STREAM_FLAG_MAP_BUFFERS only when the caller wants pixels:
+ * mapping a full-screen framebuffer on every buffer is pure waste for a
+ * cursor-only session. Metadata is unaffected either way — pw_stream maps the
+ * buffer skeleton (and therefore every spa_meta) regardless of this flag;
* MAP_BUFFERS only governs whether `datas[i].data` is populated.
*
+ * And one flag that is absent on purpose:
+ *
* No PW_STREAM_FLAG_DONT_RECONNECT, which this code used to set. That flag
* killed the first real GNOME run, and the chain is worth writing down
* because the symptom names nothing that appears in our source:
@@ -667,7 +768,10 @@ struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id,
* which connects by numeric id and reaches `streaming`).
*/
result = api.stream_connect(session->stream, PW_DIRECTION_INPUT, node_id,
- PW_STREAM_FLAG_AUTOCONNECT, params, 1);
+ want_video ? (PW_STREAM_FLAG_AUTOCONNECT |
+ PW_STREAM_FLAG_MAP_BUFFERS)
+ : PW_STREAM_FLAG_AUTOCONNECT,
+ params, 1);
if (result < 0) {
osc_set_error(err, err_len, "pw_stream_connect failed: %s", spa_strerror(result));
goto fail;
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.h b/electron/native/pipewire-capture/csrc/pw_shim.h
index 666119788..63a2f5d3d 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.h
+++ b/electron/native/pipewire-capture/csrc/pw_shim.h
@@ -45,6 +45,30 @@ struct osc_pw_cursor {
size_t bitmap_len;
};
+/*
+ * One video frame, already bounds-checked and mapped.
+ *
+ * Only produced when `osc_pw_start` was asked for video; a cursor-only session
+ * never maps a pixel. Buffers that carry no frame (chunk size 0 — how some
+ * compositors ship a cursor update on its own) are skipped rather than reported
+ * as a zero-sized frame.
+ */
+struct osc_pw_frame {
+ /* Borrowed for the duration of the callback only. Copy before returning:
+ * the buffer is re-queued to the compositor as soon as it returns. */
+ const uint8_t *data;
+ size_t size;
+ int32_t stride;
+ int32_t width;
+ int32_t height;
+ uint32_t video_format; /* enum spa_video_format */
+ /* SPA_META_Header pts in nanoseconds on the compositor's monotonic clock,
+ * or -1 when the buffer carried no header. Far better than the callback's
+ * arrival time: it is stamped when the frame was composited, not when this
+ * process got round to looking at it. */
+ int64_t pts_ns;
+};
+
/* The negotiated video format. Reported once, from param_changed. */
struct osc_pw_format {
int32_t width;
@@ -62,6 +86,8 @@ 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);
/* 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
@@ -126,9 +152,14 @@ const char *osc_pw_library_version(void);
* have taken it, so it is deliberately leaked rather than risking a double
* close — the caller is on its way to reporting a fatal error either way.
*
+ * `want_video` decides whether pixels are mapped at all. With it set the stream
+ * asks for PW_STREAM_FLAG_MAP_BUFFERS and restricts itself to shared-memory
+ * buffer types; without it neither happens, and a cursor-only session never pays
+ * to map a full-screen framebuffer per frame.
+ *
* Returns NULL on failure, with a message in `err`.
*/
-struct osc_pw_session *osc_pw_start(int fd, uint32_t node_id,
+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);
diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rs
new file mode 100644
index 000000000..8746ee476
--- /dev/null
+++ b/electron/native/pipewire-capture/src/capture.rs
@@ -0,0 +1,339 @@
+//! The video half of Stage 2: PipeWire frames in, MP4 on disk out.
+//!
+//! CONSTANT FRAME RATE, DRIVEN BY A CLOCK, NOT BY ARRIVALS.
+//!
+//! A compositor delivers frames on damage. Nothing moves on screen, no frames
+//! arrive — mutter will happily go seconds without one while the user reads a
+//! page. Writing one output frame per delivered frame would therefore produce a
+//! file whose playback speed depends on how busy the screen was, which is not a
+//! recording of anything.
+//!
+//! So the output rate comes from a monotonic clock instead. [`Capture::advance`]
+//! asks what frame index the wall clock is on and encodes forward to it, holding
+//! the last staged picture across the gap. That is why [`crate::encoder`] splits
+//! conversion from encoding: a held frame costs an upload and an encode (1.4 ms
+//! here) but not the colour conversion (3.6 ms), which is the expensive part.
+//!
+//! The clock is ours, not the compositor's. `SPA_META_Header.pts` is more precise
+//! per frame, but pause/resume and — once Stage 2's audio lands — the audio
+//! epoch all live on this process's monotonic clock, and quantising to 1/60 s
+//! makes the difference between the two immaterial.
+
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+
+use crate::encoder::{Backend, EncodeStats, Muxer, VideoEncoder, VideoParams};
+use crate::ffmpeg as ff;
+use crate::shim;
+
+/// Frames encoded in one `advance` before returning to the event loop.
+///
+/// Without a bound, a long stall would be paid back in a single burst that also
+/// blocks `stop` for as long as it takes. At the measured 1.4 ms per held frame
+/// this is ~11 ms of work per wakeup, which still catches up eight times faster
+/// than real time while leaving the loop responsive.
+const MAX_CATCHUP_FRAMES: u32 = 8;
+
+pub struct Selection {
+ pub backend: Backend,
+ /// One line per backend the ladder tried and refused, in order.
+ pub rejected: Vec<String>,
+}
+
+pub struct Summary {
+ pub path: PathBuf,
+ pub duration_ms: u64,
+ pub frames: u64,
+ pub stats: EncodeStats,
+}
+
+pub struct Capture {
+ encoder: VideoEncoder,
+ /// `None` only between [`Self::finish`] taking it and the struct dropping.
+ muxer: Option<Muxer>,
+ path: PathBuf,
+ fps: i32,
+ /// Monotonic instant of output frame 0. Set when the FIRST frame is staged,
+ /// not at construction: the gap between opening the encoder and the
+ /// compositor's first frame is portal and negotiation latency, and starting
+ /// the timeline before it would put that latency at the head of every
+ /// recording.
+ epoch: Option<Instant>,
+ /// Time spent paused, subtracted from the elapsed clock so a resumed
+ /// recording continues where it left off instead of leaving a gap.
+ paused_total: Duration,
+ paused_at: Option<Instant>,
+ /// The next output frame index to write.
+ next_index: i64,
+ frames_written: u64,
+}
+
+impl Capture {
+ pub fn start(
+ path: &Path,
+ width: i32,
+ height: i32,
+ fps: i32,
+ bitrate: i64,
+ forced: Option<Backend>,
+ ) -> Result<(Self, Selection), String> {
+ let mut rejected = Vec::new();
+ let encoder = VideoEncoder::open(
+ VideoParams { width, height, fps, bitrate },
+ forced,
+ |backend, error| rejected.push(format!("{}: {error}", backend.as_str())),
+ )?;
+ let selection = Selection { backend: encoder.backend(), rejected };
+ let muxer = Muxer::create(path, &encoder)?;
+
+ Ok((
+ Self {
+ encoder,
+ muxer: Some(muxer),
+ path: path.to_path_buf(),
+ fps,
+ epoch: None,
+ paused_total: Duration::ZERO,
+ paused_at: None,
+ next_index: 0,
+ frames_written: 0,
+ },
+ selection,
+ ))
+ }
+
+ /// Converts a captured frame into the encoder's staging buffer. Nothing is
+ /// written until [`Self::advance`] runs.
+ pub fn stage(&mut self, frame: &shim::Frame) -> Result<(), String> {
+ let format = pixel_format(frame.video_format)?;
+ self.encoder.stage(&frame.pixels, frame.stride, format)?;
+ if self.epoch.is_none() {
+ self.epoch = Some(Instant::now());
+ }
+ Ok(())
+ }
+
+ /// Whether a picture has been staged, which is also whether the timeline has
+ /// started.
+ pub fn started(&self) -> bool {
+ self.epoch.is_some()
+ }
+
+ /// Encodes forward to the current clock position. Returns how many frames
+ /// were written.
+ pub fn advance(&mut self) -> Result<u32, String> {
+ if self.paused_at.is_some() || !self.encoder.has_staged_frame() {
+ return Ok(0);
+ }
+ let target = self.current_index();
+ let mut written = 0;
+ let Some(muxer) = self.muxer.as_mut() else {
+ return Ok(0);
+ };
+ while self.next_index <= target && written < MAX_CATCHUP_FRAMES {
+ self.encoder
+ .encode_staged(self.next_index, |packet| muxer.write(packet))?;
+ self.next_index += 1;
+ self.frames_written += 1;
+ written += 1;
+ }
+ Ok(written)
+ }
+
+ pub fn pause(&mut self) {
+ if self.paused_at.is_none() {
+ self.paused_at = Some(Instant::now());
+ }
+ }
+
+ pub fn resume(&mut self) {
+ if let Some(since) = self.paused_at.take() {
+ self.paused_total += since.elapsed();
+ }
+ }
+
+ pub fn is_paused(&self) -> bool {
+ self.paused_at.is_some()
+ }
+
+ /// Flushes the encoder, writes the trailer, and closes the file.
+ pub fn finish(mut self) -> Result<Summary, String> {
+ let mut muxer = self
+ .muxer
+ .take()
+ .ok_or_else(|| "capture was already finished".to_owned())?;
+ self.encoder.finish(|packet| muxer.write(packet))?;
+ muxer.finish()?;
+
+ Ok(Summary {
+ path: self.path.clone(),
+ // From the frames actually written, not from the clock: those are
+ // the same number only when the machine kept up, and the file's real
+ // duration is the one the app should be told about.
+ duration_ms: (self.frames_written as u64 * 1000) / self.fps.max(1) as u64,
+ frames: self.frames_written,
+ stats: self.encoder.stats(),
+ })
+ }
+
+ /// Output frame index the wall clock is currently on, excluding paused time.
+ fn current_index(&self) -> i64 {
+ let Some(epoch) = self.epoch else {
+ return -1;
+ };
+ let mut elapsed = epoch.elapsed();
+ elapsed = elapsed.saturating_sub(self.paused_total);
+ if let Some(since) = self.paused_at {
+ elapsed = elapsed.saturating_sub(since.elapsed());
+ }
+ (elapsed.as_nanos() as i64 * self.fps as i64) / 1_000_000_000
+ }
+}
+
+/// SPA video format id → ffmpeg pixel format.
+///
+/// The ids come from the compiled shim rather than from hardcoded numbers (see
+/// [`shim::constants`]), so this cannot silently mis-map the day upstream
+/// inserts an enum value. Only the four formats
+/// `osc_build_enum_format` advertises can appear here; anything else means the
+/// two lists drifted apart, which is worth an error rather than a guess at the
+/// channel order.
+fn pixel_format(spa_format: u32) -> Result<ff::AVPixelFormat, String> {
+ let constants = shim::constants();
+ // `*0` rather than `*A`: the padding byte carries no alpha, and telling
+ // swscale it does would make it blend against uninitialised data.
+ let table = [
+ (constants.video_format_bgrx, ff::AV_PIX_FMT_BGR0),
+ (constants.video_format_rgbx, ff::AV_PIX_FMT_RGB0),
+ (constants.video_format_bgra, ff::AV_PIX_FMT_BGRA),
+ (constants.video_format_rgba, ff::AV_PIX_FMT_RGBA),
+ ];
+ table
+ .iter()
+ .find(|(id, _)| *id == spa_format)
+ .map(|(_, format)| *format)
+ .ok_or_else(|| {
+ format!(
+ "the compositor negotiated SPA video format {spa_format}, which this helper \
+ does not know how to convert. It should only ever pick one of the four \
+ formats osc_build_enum_format advertises."
+ )
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn frame(width: i32, height: i32, format: u32) -> shim::Frame {
+ let stride = width as usize * 4;
+ shim::Frame {
+ pixels: vec![0x30; stride * height as usize],
+ stride,
+ width,
+ height,
+ video_format: format,
+ pts_ns: -1,
+ }
+ }
+
+ #[test]
+ fn advertised_formats_all_map_to_a_pixel_format() {
+ // The two lists — what osc_build_enum_format offers and what
+ // pixel_format accepts — must not drift. A compositor picking a format
+ // we advertised but cannot convert kills the recording at the first
+ // frame, on that user's machine only.
+ let c = shim::constants();
+ for id in [
+ c.video_format_bgrx,
+ c.video_format_rgbx,
+ c.video_format_bgra,
+ c.video_format_rgba,
+ ] {
+ assert!(pixel_format(id).is_ok(), "SPA format {id} is offered but not convertible");
+ }
+ }
+
+ #[test]
+ fn an_unadvertised_format_is_reported_not_guessed() {
+ let error = pixel_format(u32::MAX).expect_err("must reject");
+ assert!(error.contains("does not know how to convert"), "{error}");
+ }
+
+ #[test]
+ 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, 1_000_000, Some(Backend::Software))
+ .expect("start");
+ assert!(!capture.started());
+ // Nothing staged: advance must not write a frame of uninitialised memory.
+ assert_eq!(capture.advance().expect("advance"), 0);
+
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+ assert!(capture.started());
+ let _ = std::fs::remove_file(&output);
+ }
+
+ #[test]
+ fn a_static_screen_still_produces_frames() {
+ // The whole reason the clock drives the output: one staged frame, no
+ // 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, 1_000_000, Some(Backend::Software))
+ .expect("start");
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+
+ std::thread::sleep(Duration::from_millis(150));
+ let written = capture.advance().expect("advance");
+ assert!(written >= 3, "150 ms at 30 fps should hold at least 3 frames, wrote {written}");
+
+ let summary = capture.finish().expect("finish");
+ assert_eq!(summary.frames, written as u64);
+ let _ = std::fs::remove_file(&output);
+ }
+
+ #[test]
+ 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, 1_000_000, Some(Backend::Software))
+ .expect("start");
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+
+ capture.pause();
+ assert!(capture.is_paused());
+ std::thread::sleep(Duration::from_millis(150));
+ // A paused capture writes nothing, however long it is paused for.
+ assert_eq!(capture.advance().expect("advance"), 0);
+ capture.resume();
+ // And the paused interval is not owed back as a burst of held frames.
+ assert_eq!(capture.advance().expect("advance"), 1, "only frame 0 is due");
+
+ let _ = std::fs::remove_file(&output);
+ }
+
+ #[test]
+ 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, 1_000_000, Some(Backend::Software))
+ .expect("start");
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+
+ // 500 ms at 60 fps is 30 frames due; one advance must not write them all.
+ std::thread::sleep(Duration::from_millis(500));
+ let written = capture.advance().expect("advance");
+ assert_eq!(written, MAX_CATCHUP_FRAMES);
+ let _ = std::fs::remove_file(&output);
+ }
+}
diff --git a/electron/native/pipewire-capture/src/encoder.rs b/electron/native/pipewire-capture/src/encoder.rs
index 3db307ba8..47a17aead 100644
--- a/electron/native/pipewire-capture/src/encoder.rs
+++ b/electron/native/pipewire-capture/src/encoder.rs
@@ -197,6 +197,8 @@ pub struct VideoEncoder {
packet: *mut ff::AVPacket,
params: VideoParams,
stats: EncodeStats,
+ /// Whether `sw_frame` holds a real picture yet.
+ staged: bool,
/// What libswscale reported back after `sws_init_context`, not what we asked
/// for. Requesting threads and silently getting one is indistinguishable
/// from threading not helping.
@@ -284,6 +286,7 @@ impl VideoEncoder {
bitrate: params.bitrate,
},
stats: EncodeStats::default(),
+ staged: false,
sws_threads: 0,
};
@@ -413,17 +416,21 @@ impl VideoEncoder {
self.codec_ctx
}
- /// Converts one captured RGB frame and submits it at `pts` (a frame index).
+ /// Converts one captured RGB frame into the staging buffer, without encoding
+ /// it.
+ ///
+ /// Split from [`Self::encode_staged`] so that a screen which stops changing
+ /// still produces frames: the capture writes at a constant rate, and holding
+ /// the last picture costs an upload and an encode but no conversion, which
+ /// is where three quarters of the per-frame time goes.
///
/// `src_format` is whatever PipeWire negotiated; the swscale context is
/// rebuilt if it ever changes, which it should not mid-stream.
- pub fn submit(
+ pub fn stage(
&mut self,
pixels: &[u8],
stride: usize,
src_format: ff::AVPixelFormat,
- pts: i64,
- mut on_packet: impl FnMut(*mut ff::AVPacket) -> Result<(), String>,
) -> Result<(), String> {
let needed = stride
.checked_mul(self.params.height as usize)
@@ -468,7 +475,33 @@ impl VideoEncoder {
if scaled < 0 {
return Err(format!("sws_scale: {}", ff::err_to_string(scaled)));
}
+ self.staged = true;
+ }
+ Ok(())
+ }
+ /// True once [`Self::stage`] has put a picture in the staging buffer. Before
+ /// that there is nothing to encode and [`Self::encode_staged`] would emit a
+ /// frame of uninitialised memory.
+ pub fn has_staged_frame(&self) -> bool {
+ self.staged
+ }
+
+ /// Encodes whatever is currently staged at `pts` (a frame index).
+ ///
+ /// Called once per staged frame and then once more per frame of a static
+ /// screen, which is what holds the constant frame rate.
+ pub fn encode_staged(
+ &mut self,
+ pts: i64,
+ mut on_packet: impl FnMut(*mut ff::AVPacket) -> Result<(), String>,
+ ) -> Result<(), String> {
+ if !self.staged {
+ return Err("encode_staged called before any frame was staged".to_owned());
+ }
+ // SAFETY: `staged` is only set after a successful sws_scale into
+ // `sw_frame`, and every pointer below is owned by `self`.
+ unsafe {
let upload_started = std::time::Instant::now();
let frame = if self.hw_frames.is_null() {
(*self.sw_frame).pts = pts;
@@ -509,6 +542,20 @@ impl VideoEncoder {
Ok(())
}
+ /// [`Self::stage`] then [`Self::encode_staged`], for callers with nothing to
+ /// gain from the split.
+ pub fn submit(
+ &mut self,
+ pixels: &[u8],
+ stride: usize,
+ src_format: ff::AVPixelFormat,
+ pts: i64,
+ on_packet: impl FnMut(*mut ff::AVPacket) -> Result<(), String>,
+ ) -> Result<(), String> {
+ self.stage(pixels, stride, src_format)?;
+ self.encode_staged(pts, on_packet)
+ }
+
/// Flushes the encoder. Call once, at stop.
pub fn finish(
&mut self,
diff --git a/electron/native/pipewire-capture/src/events.rs b/electron/native/pipewire-capture/src/events.rs
index 4969199e5..edb37c5d4 100644
--- a/electron/native/pipewire-capture/src/events.rs
+++ b/electron/native/pipewire-capture/src/events.rs
@@ -12,6 +12,10 @@
//! Electron session resolves `start()` on `ready` so its readiness timeout
//! does not have to accommodate a human.
//! * `cursor-sample` — one cursor observation.
+//! * `encoder-selection` / `capture-started` / `capture-stopped` — Stage 2's
+//! video half. `capture-started` is the Linux spelling of the "Recording
+//! started" line the Windows helper prints, and the parent waits on it
+//! before telling the UI that recording has begun.
//! * `debug` — the Stage 1 instrumentation, gated on OPENSCREEN_PIPEWIRE_DEBUG.
use std::io::{self, Write};
@@ -73,6 +77,45 @@ pub enum Event {
#[serde(skip_serializing_if = "Option::is_none")]
asset: Option<CursorAsset>,
},
+ /// Which rung of the encoder ladder won, and why the ones above it did not.
+ /// Emitted before `capture-started` so a helper that then fails to start
+ /// still leaves the selection in the log.
+ #[serde(rename_all = "camelCase")]
+ EncoderSelection {
+ /// "vaapi" | "vulkan" | "software".
+ video: String,
+ /// One line per backend that was tried and refused, in ladder order.
+ rejected: Vec<String>,
+ },
+ /// The output file is open and the first frame has been encoded. The parent
+ /// treats this the way it treats Windows's "Recording started".
+ #[serde(rename_all = "camelCase")]
+ CaptureStarted {
+ timestamp_ms: u64,
+ path: String,
+ width: i32,
+ height: i32,
+ fps: i32,
+ },
+ /// The trailer is written and the file is closed and playable.
+ #[serde(rename_all = "camelCase")]
+ CaptureStopped {
+ timestamp_ms: u64,
+ path: String,
+ duration_ms: u64,
+ /// Frames written to the file, including any duplicated to hold the
+ /// constant frame rate.
+ frames: u64,
+ /// Frames the compositor delivered that the encoder never saw, because a
+ /// newer one replaced them in the mailbox first. A non-zero value here
+ /// means the machine could not keep up.
+ dropped: u64,
+ /// Mean milliseconds per frame in each stage, so a slow recording is
+ /// diagnosable from the log alone.
+ convert_ms: f64,
+ upload_ms: f64,
+ encode_ms: f64,
+ },
#[serde(rename_all = "camelCase")]
Warning { code: String, message: String },
#[serde(rename_all = "camelCase")]
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index e025fc75a..a57ad6f4f 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -1,22 +1,31 @@
-//! OpenScreen Linux capture helper — Stage 1: cursor samples only.
+//! OpenScreen Linux capture helper.
//!
-//! WHY THIS EXISTS. `screen.getCursorScreenPoint()` returns {0,0} under Wayland,
-//! so `TelemetryRecordingSession` produced recordings whose every cursor sample
-//! sat in the screen's top-left corner while looking perfectly well-formed. The
-//! only source of truth for the pointer on Wayland is the ScreenCast portal's
-//! METADATA cursor mode, where the compositor keeps the cursor out of the pixels
-//! and attaches a SPA_META_Cursor to each frame instead.
+//! WHY THIS EXISTS. Two reasons, and they turned out to be the same reason.
+//!
+//! `screen.getCursorScreenPoint()` returns {0,0} under Wayland, so
+//! `TelemetryRecordingSession` produced recordings whose every cursor sample sat
+//! in the screen's top-left corner while looking perfectly well-formed. The only
+//! source of truth for the pointer on Wayland is the ScreenCast portal's
+//! METADATA cursor mode.
+//!
+//! And in that same mode the compositor keeps the cursor OUT of the captured
+//! pixels — which is what the editor needs in order to draw its own. Chromium's
+//! `getDisplayMedia` gives the opposite: a frame with the pointer already
+//! painted in, and no way to know where it was. One portal session answers both,
+//! and it has to be one session because SelectSources may only be called once.
//!
//! SHAPE. A stdio sidecar, like the macOS and Windows helpers: JSON request in
-//! argv[1], NDJSON events on stdout, `stop` (or EOF) on stdin. It captures no
-//! video and writes no file — that is Stage 2's job, and it will reuse this same
-//! portal session because SelectSources may only be called once per session.
+//! argv[1], NDJSON events on stdout, `stop`/`pause`/`resume` (or EOF) on stdin.
+//! With `outputPath` it also encodes H.264 and writes an MP4; without it, it is
+//! the cursor-only session Stage 1 shipped, which is what
+//! `PipeWireCursorRecordingSession` still uses.
//!
//! WHAT IT CANNOT DO. Mouse buttons. Wayland exposes no portal for input
//! events, and /dev/input/event* is root:input. Every sample is therefore a
//! "move"; there is no click detection to be had here at any effort level.
mod bitmap;
+mod capture;
mod encoder;
mod events;
mod ffmpeg;
@@ -25,18 +34,31 @@ mod shim;
use std::collections::HashSet;
use std::io::{BufRead, Write};
+use std::path::PathBuf;
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
+use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Deserialize;
+use capture::Capture;
use events::{timestamp_ms, CursorAsset, Emitter, Event};
-use shim::StreamEvent;
+use shim::{FrameMailbox, StreamEvent};
/// Matches the macOS helper's default and the Electron side's sampleIntervalMs.
const DEFAULT_SAMPLE_INTERVAL_MS: u64 = 33;
const MIN_SAMPLE_INTERVAL_MS: u64 = 8;
+const DEFAULT_FPS: i32 = 30;
+const DEFAULT_BITRATE: i64 = 8_000_000;
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+struct VideoRequest {
+ fps: Option<i32>,
+ bitrate: Option<i64>,
+}
+
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
struct Request {
@@ -44,6 +66,14 @@ struct Request {
/// Token from a previous run's `stream-started`. Lets the portal skip the
/// picker for a source the user already approved.
restore_token: Option<String>,
+ /// Where to write the MP4. Absent means cursor-only: no pixels are mapped,
+ /// no encoder is opened, and the helper behaves exactly as Stage 1 did.
+ output_path: Option<String>,
+ /// `"metadata"` (default) keeps the pointer out of the pixels so the editor
+ /// can draw its own; `"embedded"` asks the compositor to paint it in. These
+ /// are the two halves of the HUD's cursor-mode toggle.
+ cursor_mode: Option<String>,
+ video: Option<VideoRequest>,
/// Emit `ready` and exit, without ever calling the portal's `Start()`.
///
/// Everything up to that point is non-interactive; `Start()` is the single
@@ -53,9 +83,40 @@ struct Request {
probe_only: bool,
}
+impl Request {
+ fn cursor_mode(&self) -> Result<portal::CursorMode, String> {
+ match self.cursor_mode.as_deref() {
+ None | Some("") | Some("metadata") => Ok(portal::CursorMode::Metadata),
+ Some("embedded") => Ok(portal::CursorMode::Embedded),
+ Some("hidden") => Ok(portal::CursorMode::Hidden),
+ Some(other) => Err(format!(
+ "cursorMode must be one of metadata, embedded, hidden — got {other:?}"
+ )),
+ }
+ }
+
+ fn fps(&self) -> i32 {
+ self.video
+ .as_ref()
+ .and_then(|video| video.fps)
+ .filter(|fps| *fps > 0 && *fps <= 240)
+ .unwrap_or(DEFAULT_FPS)
+ }
+
+ fn bitrate(&self) -> i64 {
+ self.video
+ .as_ref()
+ .and_then(|video| video.bitrate)
+ .filter(|bitrate| *bitrate > 0)
+ .unwrap_or(DEFAULT_BITRATE)
+ }
+}
+
enum Message {
Portal(Box<Result<portal::PortalStream, portal::PortalError>>),
Stream(StreamEvent),
+ Pause,
+ Resume,
Stop,
}
@@ -71,32 +132,53 @@ fn main() {
fail(&mut emitter, "invalid-arguments", &message);
}
};
- let interval = Duration::from_millis(
+ let cursor_mode = match request.cursor_mode() {
+ Ok(mode) => mode,
+ Err(message) => fail(&mut emitter, "invalid-arguments", &message),
+ };
+ let output_path = request.output_path.as_deref().map(PathBuf::from);
+ let forced_encoder = match encoder::forced_backend_from_env() {
+ Ok(backend) => backend,
+ Err(message) => fail(&mut emitter, "invalid-arguments", &message),
+ };
+
+ // The loop has to serve two clocks: cursor samples at the requested interval
+ // and video frames at the video frame rate. It ticks at whichever is
+ // shorter, so neither is ever late by more than the other's period.
+ let sample_interval = Duration::from_millis(
request
.sample_interval_ms
.unwrap_or(DEFAULT_SAMPLE_INTERVAL_MS)
.max(MIN_SAMPLE_INTERVAL_MS),
);
+ let tick = match output_path {
+ Some(_) => sample_interval.min(Duration::from_nanos(
+ 1_000_000_000 / request.fps().max(1) as u64,
+ )),
+ None => sample_interval,
+ };
if let Err(message) = shim::load() {
fail(&mut emitter, "pipewire-unavailable", &message);
}
// Probed before `ready` so the event can report it, and so an unsupported
- // compositor fails immediately instead of after a pointless picker.
- match pollster::block_on(portal::cursor_metadata_supported()) {
- Ok(true) => {}
- Ok(false) => {
- let error = portal::PortalError::CursorMetadataUnsupported;
- fail(&mut emitter, error.code(), &error.message());
- }
+ // compositor fails immediately instead of after a pointless picker. Only
+ // fatal when METADATA is the mode actually requested — a recording that
+ // wants the system cursor painted in has no use for it.
+ let cursor_metadata_supported = match pollster::block_on(portal::cursor_metadata_supported()) {
+ Ok(supported) => supported,
Err(error) => fail(&mut emitter, error.code(), &error.message()),
+ };
+ if !cursor_metadata_supported && cursor_mode.reports_cursor() {
+ let error = portal::PortalError::CursorMetadataUnsupported;
+ fail(&mut emitter, error.code(), &error.message());
}
let _ = emitter.emit(&Event::Ready {
timestamp_ms: timestamp_ms(),
pipewire_version: shim::library_version(),
- cursor_metadata_supported: true,
+ cursor_metadata_supported,
});
if request.probe_only {
@@ -105,12 +187,34 @@ fn main() {
let (sender, receiver) = mpsc::channel::<Message>();
spawn_stdin_reader(sender.clone());
- spawn_portal(sender.clone(), request.restore_token.clone());
-
- let exit_code = run(&mut emitter, receiver, sender, interval);
+ spawn_portal(sender.clone(), request.restore_token.clone(), cursor_mode);
+
+ let session = RunConfig {
+ tick,
+ sample_interval,
+ output_path,
+ fps: request.fps(),
+ bitrate: request.bitrate(),
+ forced_encoder,
+ cursor_mode,
+ };
+ let exit_code = run(&mut emitter, receiver, sender, session);
std::process::exit(exit_code);
}
+struct RunConfig {
+ /// How often the loop wakes when nothing arrives.
+ tick: Duration,
+ /// Minimum spacing between cursor samples on stdout.
+ sample_interval: Duration,
+ /// `None` for a cursor-only session.
+ output_path: Option<PathBuf>,
+ fps: i32,
+ bitrate: i64,
+ forced_encoder: Option<encoder::Backend>,
+ cursor_mode: portal::CursorMode,
+}
+
fn parse_request() -> Result<Request, String> {
match std::env::args().nth(1) {
None => Ok(Request::default()),
@@ -128,14 +232,29 @@ fn fail<W: Write>(emitter: &mut Emitter<W>, code: &str, message: &str) -> ! {
}
/// EOF counts as `stop`: if the parent dies, so do we.
+///
+/// The command vocabulary is the Windows and macOS helpers': `stop`, `pause`,
+/// `resume`, one per line on stdin (see the `proc.stdin.write("pause\n")` calls
+/// in electron/ipc/handlers.ts). Unknown lines are ignored rather than fatal —
+/// a newer parent talking to an older helper should degrade, not crash.
fn spawn_stdin_reader(sender: Sender<Message>) {
std::thread::spawn(move || {
let stdin = std::io::stdin();
for line in stdin.lock().lines() {
- match line {
- Ok(line) if line.trim() == "stop" => break,
- Ok(_) => continue,
- Err(_) => break,
+ let Ok(line) = line else { break };
+ match line.trim() {
+ "stop" => break,
+ "pause" => {
+ if sender.send(Message::Pause).is_err() {
+ return;
+ }
+ }
+ "resume" => {
+ if sender.send(Message::Resume).is_err() {
+ return;
+ }
+ }
+ _ => continue,
}
}
let _ = sender.send(Message::Stop);
@@ -145,9 +264,13 @@ fn spawn_stdin_reader(sender: Sender<Message>) {
/// The portal runs on its own thread because `Start()` blocks on the user for
/// an unbounded time, and a `stop` arriving during the picker must still be
/// honoured.
-fn spawn_portal(sender: Sender<Message>, restore_token: Option<String>) {
+fn spawn_portal(
+ sender: Sender<Message>,
+ restore_token: Option<String>,
+ cursor_mode: portal::CursorMode,
+) {
std::thread::spawn(move || {
- let result = pollster::block_on(portal::negotiate(restore_token.as_deref()));
+ let result = pollster::block_on(portal::negotiate(restore_token.as_deref(), cursor_mode));
let _ = sender.send(Message::Portal(Box::new(result)));
});
}
@@ -172,7 +295,7 @@ fn run<W: Write>(
emitter: &mut Emitter<W>,
receiver: mpsc::Receiver<Message>,
sender: Sender<Message>,
- interval: Duration,
+ config: RunConfig,
) -> i32 {
let constants = shim::constants();
// Held for the whole loop: dropping it stops and joins the PipeWire thread.
@@ -183,16 +306,85 @@ fn run<W: Write>(
let mut known_assets: HashSet<String> = HashSet::new();
let mut pending_asset: Option<CursorAsset> = None;
let mut reported_cursor_meta = false;
+ // Allocated up front so the PipeWire callback has somewhere to put frames
+ // from the very first buffer; `None` in cursor-only mode, which is also what
+ // tells `Session::start` not to map the buffers at all.
+ let frames: Option<Arc<FrameMailbox>> = config
+ .output_path
+ .as_ref()
+ .map(|_| Arc::new(FrameMailbox::default()));
+ let mut capture: Option<Capture> = None;
+ // Buffered until the format is negotiated: the encoder cannot be opened
+ // before the frame size is known, and `pause` can arrive first.
+ let mut paused = false;
// Backdated so the very first sample is not held back by the throttle.
// `checked_sub` because a bare `Instant - Duration` panics on underflow, and
// this runs milliseconds after process start.
- let mut last_emit = Instant::now().checked_sub(interval).unwrap_or_else(Instant::now);
+ let mut last_emit = Instant::now()
+ .checked_sub(config.sample_interval)
+ .unwrap_or_else(Instant::now);
let mut exit_code = 0;
loop {
- match receiver.recv_timeout(interval) {
+ match receiver.recv_timeout(config.tick) {
Ok(Message::Stop) => break,
+ Ok(Message::Pause) => {
+ paused = true;
+ if let Some(capture) = capture.as_mut() {
+ capture.pause();
+ }
+ }
+
+ Ok(Message::Resume) => {
+ paused = false;
+ if let Some(capture) = capture.as_mut() {
+ capture.resume();
+ }
+ }
+
+ Ok(Message::Stream(StreamEvent::FrameReady)) => {
+ let (Some(mailbox), Some(capture)) = (frames.as_ref(), capture.as_mut()) else {
+ continue;
+ };
+ // `take` can legitimately return None: several FrameReady
+ // notifications can arrive for frames that superseded each other
+ // in the mailbox before the loop got here.
+ if let Some(frame) = mailbox.take() {
+ let first = !capture.started();
+ if let Err(message) = capture.stage(&frame) {
+ let _ = emitter.emit(&Event::Error {
+ code: "encode-failed".to_owned(),
+ message,
+ });
+ exit_code = 1;
+ break;
+ }
+ if first {
+ let _ = emitter.emit(&Event::CaptureStarted {
+ timestamp_ms: timestamp_ms(),
+ path: config
+ .output_path
+ .as_ref()
+ .map(|path| path.display().to_string())
+ .unwrap_or_default(),
+ width: frame.width,
+ height: frame.height,
+ fps: config.fps,
+ });
+ }
+ mailbox.recycle(frame.pixels);
+ }
+ if let Err(message) = capture.advance() {
+ let _ = emitter.emit(&Event::Error {
+ code: "encode-failed".to_owned(),
+ message,
+ });
+ exit_code = 1;
+ break;
+ }
+ }
+
Ok(Message::Portal(result)) => match *result {
Ok(stream) => {
// The fd is consumed by libpipewire; the rest is kept for the
@@ -225,6 +417,7 @@ fn run<W: Write>(
Box::new(move |event| {
let _ = forward.send(Message::Stream(event));
}),
+ frames.clone(),
) {
Ok(started) => {
session = Some(started);
@@ -275,6 +468,59 @@ fn run<W: Write>(
restore_token: stream.restore_token,
});
}
+
+ // The encoder cannot be opened until now: its dimensions are the
+ // negotiated ones, which the compositor picks. Renegotiation
+ // mid-stream would deliver a second Format; the encoder is left
+ // alone in that case, because an MP4 cannot change resolution
+ // mid-file and the alternative — silently starting a new one —
+ // would lose the recording.
+ if let Some(path) = config.output_path.as_ref() {
+ if capture.is_none() {
+ match Capture::start(
+ path,
+ format.width,
+ format.height,
+ config.fps,
+ config.bitrate,
+ config.forced_encoder,
+ ) {
+ Ok((started, selection)) => {
+ let _ = emitter.emit(&Event::EncoderSelection {
+ video: selection.backend.as_str().to_owned(),
+ rejected: selection.rejected,
+ });
+ capture = Some(started);
+ if paused {
+ // A `pause` that arrived while the portal
+ // picker was still up applies to the capture
+ // that picker was for.
+ if let Some(capture) = capture.as_mut() {
+ capture.pause();
+ }
+ }
+ }
+ Err(message) => {
+ let _ = emitter.emit(&Event::Error {
+ code: "encoder-unavailable".to_owned(),
+ message,
+ });
+ exit_code = 1;
+ break;
+ }
+ }
+ } else {
+ let _ = emitter.emit(&Event::Warning {
+ code: "format-renegotiated".to_owned(),
+ message: format!(
+ "the compositor renegotiated to {}x{} mid-recording; the \
+ encoder keeps its original size and the file may be letterboxed \
+ or cropped from here on",
+ format.width, format.height
+ ),
+ });
+ }
+ }
}
Ok(Message::Stream(StreamEvent::BufferInfo {
@@ -411,29 +657,92 @@ fn run<W: Write>(
// A new sprite ships immediately; positions respect the sample
// interval so a 120fps compositor cannot flood stdout.
- if asset_is_new || last_emit.elapsed() >= interval {
+ if asset_is_new || last_emit.elapsed() >= config.sample_interval {
emit_sample(emitter, &cursor, size, &mut pending_asset);
last_emit = Instant::now();
}
}
Err(RecvTimeoutError::Timeout) => {
- if cursor.is_some() {
+ if cursor.is_some() && last_emit.elapsed() >= config.sample_interval {
emit_sample(emitter, &cursor, size, &mut pending_asset);
last_emit = Instant::now();
}
+ // The heartbeat that keeps the output at a constant frame rate
+ // while the screen is static: no frame arrived, but the clock
+ // moved, so the last picture is held forward.
+ if let Some(capture) = capture.as_mut() {
+ if let Err(message) = capture.advance() {
+ let _ = emitter.emit(&Event::Error {
+ code: "encode-failed".to_owned(),
+ message,
+ });
+ exit_code = 1;
+ break;
+ }
+ }
}
Err(RecvTimeoutError::Disconnected) => break,
}
}
- // Explicit: this joins the PipeWire thread before the process exits, so no
- // callback can fire against a freed Sender.
+ // Before the file is closed: this joins the PipeWire thread, so no callback
+ // can fire against a freed Sender or write into a mailbox that is about to
+ // be dropped.
drop(session);
+
+ if let Some(capture) = capture {
+ finish_capture(emitter, capture, frames.as_deref(), &mut exit_code);
+ }
exit_code
}
+/// Writes the trailer and reports what the recording cost.
+///
+/// Runs even when the loop broke on an error: a file whose moov atom was never
+/// written is unplayable, and a partial recording is worth more to the user than
+/// none.
+fn finish_capture<W: Write>(
+ emitter: &mut Emitter<W>,
+ capture: Capture,
+ frames: Option<&FrameMailbox>,
+ exit_code: &mut i32,
+) {
+ match capture.finish() {
+ Ok(summary) => {
+ let dropped = frames.map(FrameMailbox::dropped).unwrap_or(0);
+ if dropped > 0 {
+ let _ = emitter.emit(&Event::Warning {
+ code: "frames-dropped".to_owned(),
+ message: format!(
+ "{dropped} captured frame(s) were replaced before the encoder could \
+ take them, so the recording holds an older picture across those \
+ moments. The machine could not keep up with the capture rate."
+ ),
+ });
+ }
+ let _ = emitter.emit(&Event::CaptureStopped {
+ timestamp_ms: timestamp_ms(),
+ path: summary.path.display().to_string(),
+ duration_ms: summary.duration_ms,
+ frames: summary.frames,
+ dropped,
+ convert_ms: summary.stats.convert_ms(),
+ upload_ms: summary.stats.upload_ms(),
+ encode_ms: summary.stats.encode_ms(),
+ });
+ }
+ Err(message) => {
+ let _ = emitter.emit(&Event::Error {
+ code: "capture-finish-failed".to_owned(),
+ message,
+ });
+ *exit_code = 1;
+ }
+ }
+}
+
fn emit_sample<W: Write>(
emitter: &mut Emitter<W>,
cursor: &Option<CursorState>,
diff --git a/electron/native/pipewire-capture/src/portal.rs b/electron/native/pipewire-capture/src/portal.rs
index 379c4af8f..a34160c3d 100644
--- a/electron/native/pipewire-capture/src/portal.rs
+++ b/electron/native/pipewire-capture/src/portal.rs
@@ -21,11 +21,42 @@
use std::os::fd::OwnedFd;
-use ashpd::desktop::screencast::{CursorMode, Screencast, SourceType};
+use ashpd::desktop::screencast::{CursorMode as PortalCursorMode, Screencast, SourceType};
use ashpd::desktop::PersistMode;
use ashpd::enumflags2::BitFlags;
use ashpd::WindowIdentifier;
+/// Which of the portal's three cursor modes to ask for.
+///
+/// This is the HUD's cursor-mode toggle, one layer down. `Metadata` is what
+/// makes the editable cursor possible at all — the compositor keeps the pointer
+/// out of the pixels and describes it separately — and `Embedded` is the
+/// "system cursor" setting, where the compositor paints it in and the editor
+/// leaves it alone.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CursorMode {
+ Metadata,
+ Embedded,
+ Hidden,
+}
+
+impl CursorMode {
+ fn to_portal(self) -> PortalCursorMode {
+ match self {
+ Self::Metadata => PortalCursorMode::Metadata,
+ Self::Embedded => PortalCursorMode::Embedded,
+ Self::Hidden => PortalCursorMode::Hidden,
+ }
+ }
+
+ /// Only METADATA yields cursor samples; in the other modes the pointer is
+ /// either painted into the frames or absent, and there is no metadata to
+ /// read either way.
+ pub fn reports_cursor(self) -> bool {
+ matches!(self, Self::Metadata)
+ }
+}
+
/// Everything the PipeWire half needs, plus what the helper reports upward.
pub struct PortalStream {
pub fd: OwnedFd,
@@ -85,7 +116,7 @@ pub async fn cursor_metadata_supported() -> Result<bool, PortalError> {
.available_cursor_modes()
.await
.map_err(|error| failed("AvailableCursorModes", error))?;
- Ok(cursor_modes.contains(CursorMode::Metadata))
+ Ok(cursor_modes.contains(PortalCursorMode::Metadata))
}
/// Runs the negotiation to completion. Blocks on the user for as long as the
@@ -95,7 +126,10 @@ pub async fn cursor_metadata_supported() -> Result<bool, PortalError> {
/// ashpd has no `Drop` impl for sessions and holds its D-Bus connection in a
/// process-global `OnceLock`, so the portal session stays open until this
/// process exits — which is exactly the lifetime we want.
-pub async fn negotiate(restore_token: Option<&str>) -> Result<PortalStream, PortalError> {
+pub async fn negotiate(
+ restore_token: Option<&str>,
+ cursor_mode: CursorMode,
+) -> Result<PortalStream, PortalError> {
let proxy = Screencast::new()
.await
.map_err(|error| failed("cannot reach org.freedesktop.portal.ScreenCast", error))?;
@@ -104,8 +138,17 @@ pub async fn negotiate(restore_token: Option<&str>) -> Result<PortalStream, Port
.available_cursor_modes()
.await
.map_err(|error| failed("AvailableCursorModes", error))?;
- if !cursor_modes.contains(CursorMode::Metadata) {
- return Err(PortalError::CursorMetadataUnsupported);
+ // Only METADATA is treated as mandatory, and only when it was asked for.
+ // EMBEDDED is in the portal spec's baseline and every compositor implements
+ // it; refusing to start because a mode we are not using is missing would be
+ // the Stage 1 check applied where it no longer belongs.
+ if !cursor_modes.contains(cursor_mode.to_portal()) {
+ return Err(match cursor_mode {
+ CursorMode::Metadata => PortalError::CursorMetadataUnsupported,
+ other => PortalError::Failed(format!(
+ "the ScreenCast portal does not offer the {other:?} cursor mode"
+ )),
+ });
}
let session = proxy
@@ -119,7 +162,7 @@ pub async fn negotiate(restore_token: Option<&str>) -> Result<PortalStream, Port
proxy
.select_sources(
&session,
- CursorMode::Metadata,
+ cursor_mode.to_portal(),
types,
false,
restore_token,
diff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rs
index b64b2a645..00a8645fd 100644
--- a/electron/native/pipewire-capture/src/shim.rs
+++ b/electron/native/pipewire-capture/src/shim.rs
@@ -31,6 +31,18 @@ pub struct RawCursor {
pub bitmap_len: usize,
}
+#[repr(C)]
+#[derive(Debug)]
+pub struct RawFrame {
+ pub data: *const u8,
+ pub size: usize,
+ pub stride: i32,
+ pub width: i32,
+ pub height: i32,
+ pub video_format: u32,
+ pub pts_ns: i64,
+}
+
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct RawFormat {
@@ -46,6 +58,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_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),
}
@@ -82,6 +95,7 @@ extern "C" {
fn osc_pw_start(
fd: i32,
node_id: u32,
+ want_video: i32,
callbacks: *const RawCallbacks,
err: *mut c_char,
err_len: usize,
@@ -108,6 +122,11 @@ pub enum StreamEvent {
metas: String,
},
Cursor(CursorEvent),
+ /// A frame is waiting in the [`FrameMailbox`]. Carries no payload on
+ /// purpose: an 8 MB frame per channel message would allocate and copy far
+ /// more than the mailbox does, and a notification that arrives after its
+ /// frame was superseded is harmless — `take()` simply returns `None`.
+ FrameReady,
State {
state: String,
error: Option<String>,
@@ -133,6 +152,108 @@ pub struct CursorBitmap {
pub pixels: Vec<u8>,
}
+/// One captured frame, copied out of the PipeWire buffer.
+#[derive(Debug, Default)]
+pub struct Frame {
+ pub pixels: Vec<u8>,
+ pub stride: usize,
+ pub width: i32,
+ pub height: i32,
+ pub video_format: u32,
+ /// Compositor monotonic clock in nanoseconds, or -1 when the buffer carried
+ /// no SPA_META_Header.
+ pub pts_ns: i64,
+}
+
+/// A one-slot mailbox between the PipeWire thread and the encoder.
+///
+/// NEWEST WINS. When the encoder falls behind, an unconsumed frame is
+/// overwritten rather than queued. A queue would be the wrong shape twice over:
+/// it would grow without bound at 8 MB per 1080p frame, and every frame it held
+/// would add latency to a recording that is supposed to track the screen. A
+/// dropped frame costs one duplicated frame in the output; a queued one costs
+/// memory and drift forever.
+///
+/// The buffer of an overwritten or consumed frame is recycled, so after the
+/// first few frames this allocates nothing.
+#[derive(Debug, Default)]
+pub struct FrameMailbox {
+ inner: std::sync::Mutex<Mailbox>,
+ received: std::sync::atomic::AtomicU64,
+ dropped: std::sync::atomic::AtomicU64,
+}
+
+#[derive(Debug, Default)]
+struct Mailbox {
+ pending: Option<Frame>,
+ /// Returned by the consumer, reused by the next copy.
+ spare: Option<Vec<u8>>,
+}
+
+impl FrameMailbox {
+ /// Copies `pixels` into the slot, replacing whatever was there.
+ ///
+ /// Runs on the PipeWire thread and must stay short: the buffer it reads from
+ /// is re-queued to the compositor the moment the callback returns.
+ fn put(&self, source: &[u8], meta: &RawFrame) {
+ use std::sync::atomic::Ordering;
+
+ let Ok(mut inner) = self.inner.lock() else {
+ // A poisoned lock means a previous holder panicked. Dropping the
+ // frame is the only safe option, and it is already counted below.
+ self.dropped.fetch_add(1, Ordering::Relaxed);
+ return;
+ };
+
+ // Recycle, in order of preference: the buffer of the frame we are about
+ // to discard, then the one the consumer handed back, then a new one.
+ let mut pixels = match inner.pending.take() {
+ Some(stale) => {
+ self.dropped.fetch_add(1, Ordering::Relaxed);
+ stale.pixels
+ }
+ None => inner.spare.take().unwrap_or_default(),
+ };
+ pixels.clear();
+ pixels.extend_from_slice(source);
+
+ inner.pending = Some(Frame {
+ pixels,
+ stride: meta.stride as usize,
+ width: meta.width,
+ height: meta.height,
+ video_format: meta.video_format,
+ pts_ns: meta.pts_ns,
+ });
+ self.received.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// Takes the pending frame, if any. Returns `None` when the consumer was
+ /// woken by a notification whose frame has already been superseded.
+ pub fn take(&self) -> Option<Frame> {
+ self.inner.lock().ok()?.pending.take()
+ }
+
+ /// Hands a consumed frame's allocation back for reuse.
+ pub fn recycle(&self, mut pixels: Vec<u8>) {
+ let Ok(mut inner) = self.inner.lock() else {
+ return;
+ };
+ pixels.clear();
+ inner.spare = Some(pixels);
+ }
+
+ /// Frames the compositor delivered.
+ pub fn received(&self) -> u64 {
+ self.received.load(std::sync::atomic::Ordering::Relaxed)
+ }
+
+ /// Frames overwritten before the encoder could take them.
+ pub fn dropped(&self) -> u64 {
+ self.dropped.load(std::sync::atomic::Ordering::Relaxed)
+ }
+}
+
const ERR_LEN: usize = 256;
fn take_error(buffer: &[c_char; ERR_LEN]) -> String {
@@ -180,40 +301,65 @@ pub fn constants() -> Constants {
out
}
+/// What the C side carries as its opaque `user` pointer.
+struct CallbackState {
+ sink: Sink,
+ /// `None` in cursor-only mode, in which case the C side is not asked for
+ /// frames either and `on_frame` can never fire.
+ frames: Option<std::sync::Arc<FrameMailbox>>,
+}
+
/// A running PipeWire stream. Dropping it stops and joins the PipeWire thread.
pub struct Session {
raw: *mut RawSession,
// Kept alive for exactly as long as `raw`: the C side holds a pointer to it
// and hands it back to every callback. Dropped after osc_pw_stop has joined
- // the loop thread, so no callback can be in flight at that point. The outer
- // Box exists to give the fat `dyn Fn` pointer a stable thin address.
- _sink: Box<Sink>,
+ // the loop thread, so no callback can be in flight at that point.
+ _state: Box<CallbackState>,
}
impl Session {
/// Consumes `fd` — libpipewire closes it, on the success and failure paths alike.
- pub fn start(fd: OwnedFd, node_id: u32, sink: Sink) -> Result<Self, String> {
- let boxed: Box<Sink> = Box::new(sink);
- let user = &*boxed as *const Sink as *mut c_void;
+ ///
+ /// `frames` decides the mode. `Some` maps the buffers and copies each frame
+ /// into the mailbox, announcing it with [`StreamEvent::FrameReady`]; `None`
+ /// never maps a pixel, which is what keeps a cursor-only session cheap.
+ pub fn start(
+ fd: OwnedFd,
+ node_id: u32,
+ sink: Sink,
+ frames: Option<std::sync::Arc<FrameMailbox>>,
+ ) -> Result<Self, String> {
+ let want_video = i32::from(frames.is_some());
+ let state = Box::new(CallbackState { sink, frames });
+ let user = &*state as *const CallbackState as *mut c_void;
let callbacks = RawCallbacks {
user,
on_format,
on_cursor,
+ on_frame,
on_buffer_info,
on_state,
};
let mut err = [0 as c_char; ERR_LEN];
- // SAFETY: `callbacks` and `err` outlive the call; `boxed` outlives the
+ // SAFETY: `callbacks` and `err` outlive the call; `state` outlives the
// returned session, which is what keeps `user` valid for the callbacks.
let raw = unsafe {
- osc_pw_start(fd.into_raw_fd(), node_id, &callbacks, err.as_mut_ptr(), ERR_LEN)
+ osc_pw_start(
+ fd.into_raw_fd(),
+ node_id,
+ want_video,
+ &callbacks,
+ err.as_mut_ptr(),
+ ERR_LEN,
+ )
};
if raw.is_null() {
return Err(take_error(&err));
}
- Ok(Self { raw, _sink: boxed })
+ Ok(Self { raw, _state: state })
}
}
@@ -229,18 +375,25 @@ impl Drop for Session {
/// `catch_unwind` is not defensive programming here: unwinding across an
/// `extern "C"` boundary is undefined behaviour, and these functions run on
/// PipeWire's thread where a panic would otherwise abort mid-callback.
-fn with_sink<F>(user: *mut c_void, body: F)
+fn with_state<F>(user: *mut c_void, body: F)
where
- F: FnOnce(&Sink),
+ F: FnOnce(&CallbackState),
{
if user.is_null() {
return;
}
- // SAFETY: `user` is the pointer we handed to osc_pw_start, pointing at a
- // sink owned by the live Session. Callbacks cannot outlive it: osc_pw_stop
- // joins the loop thread before the Session drops the box.
- let sink = unsafe { &*(user as *const Sink) };
- let _ = catch_unwind(AssertUnwindSafe(|| body(sink)));
+ // SAFETY: `user` is the pointer we handed to osc_pw_start, pointing at state
+ // owned by the live Session. Callbacks cannot outlive it: osc_pw_stop joins
+ // the loop thread before the Session drops the box.
+ let state = unsafe { &*(user as *const CallbackState) };
+ let _ = catch_unwind(AssertUnwindSafe(|| body(state)));
+}
+
+fn with_sink<F>(user: *mut c_void, body: F)
+where
+ F: FnOnce(&Sink),
+{
+ with_state(user, |state| body(&state.sink));
}
extern "C" fn on_format(user: *mut c_void, format: *const RawFormat) {
@@ -254,6 +407,37 @@ 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;
+ }
+ // SAFETY: non-NULL for the duration of the callback, by contract.
+ let frame = unsafe { &*frame };
+ 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;
+ }
+ // 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);
+ });
+}
+
extern "C" fn on_buffer_info(
user: *mut c_void,
data_type: u32,
@@ -430,6 +614,9 @@ mod tests {
Box::new(move |event| {
let _ = sender.send(event);
}),
+ // Cursor-only: this test is about negotiation reaching `streaming`
+ // and about which metadata survives, neither of which needs pixels.
+ None,
)
.expect("stream must connect");
@@ -476,6 +663,11 @@ mod tests {
Ok(StreamEvent::Cursor(cursor)) => {
println!("[{:>5}ms] cursor {cursor:?}", stamp(std::time::Instant::now()));
}
+ // Unreachable: this session was started with no mailbox, so the
+ // C side was never asked for frames. Matched rather than
+ // wildcarded so that adding a variant is a compile error here
+ // too, which is how this test stays a full protocol trace.
+ Ok(StreamEvent::FrameReady) => unreachable!("cursor-only session yielded a frame"),
Err(_) => {}
}
}