Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(capture): panic-safety, stale hw surface, and a non-fatal dmabuf drop
Benjamin Freemanea22c1497b5f
diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rsindex 22b1b8b53..15265a219 100644--- a/electron/native/pipewire-capture/src/capture.rs+++ b/electron/native/pipewire-capture/src/capture.rs@@ -227,6 +227,18 @@ pub struct Capture {committed_height: i32,}+/// The outcome of staging one captured frame.+#[derive(Debug, PartialEq, Eq)]+pub enum StageOutcome {+ /// A new frame was staged; `advance` will encode it.+ Staged,+ /// A recoverable per-frame failure — one dmabuf the GPU could not map, or a+ /// transient EAGAIN. The frame is skipped and `advance` holds the previously+ /// staged one forward, so a single bad frame costs one frame, not the whole+ /// recording. Carries the reason for a log warning.+ Dropped(String),+}+impl Capture {pub fn start(path: &Path,@@ -364,8 +376,10 @@ impl Capture {}/// 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> {+ /// written until [`Self::advance`] runs. A recoverable per-frame failure (a+ /// dmabuf the GPU cannot map) returns `Ok(Dropped)` rather than `Err`, so it+ /// costs one frame, not the recording; a genuine encoder error still errors.+ pub fn stage(&mut self, frame: &shim::Frame) -> Result<StageOutcome, String> {// Zero-copy dmabuf path: import the tiled GPU buffer into an NV12 VAAPI// surface (the VPP crops a window to its committed rectangle) and hand it// to the encoder as-is — no swscale. See issue #507.@@ -388,7 +402,7 @@ impl Capture {stride: plane.stride,}).collect();- let nv12 = importer.import(+ let nv12 = match importer.import(&crate::dmabuf_import::DmabufFrame {width: desc.width,height: desc.height,@@ -398,12 +412,18 @@ impl Capture {},crop_x,crop_y,- )?;+ ) {+ Ok(nv12) => nv12,+ // A single un-mappable buffer must not end the recording. Skip it;+ // `advance` holds the previous frame, and the shm path is still in+ // the offer for a full downgrade later (a planned follow-up).+ Err(reason) => return Ok(StageOutcome::Dropped(reason)),+ };// SAFETY: `nv12` is a VAAPI NV12 frame from the pool the encoder was// opened against; the encoder takes ownership.unsafe { self.encoder.stage_hw(nv12) };self.mark_started();- return Ok(());+ return Ok(StageOutcome::Staged);}let format = pixel_format(frame.video_format)?;@@ -425,7 +445,7 @@ impl Capture {self.encoder.stage(pixels, frame.stride, format)?;self.mark_started();- Ok(())+ Ok(StageOutcome::Staged)}/// Starts the timeline on the first staged frame and drops the audio backlog.diff --git a/electron/native/pipewire-capture/src/encoder.rs b/electron/native/pipewire-capture/src/encoder.rsindex 3b06ab4a8..8e197dddd 100644--- a/electron/native/pipewire-capture/src/encoder.rs+++ b/electron/native/pipewire-capture/src/encoder.rs@@ -559,6 +559,15 @@ impl VideoEncoder {if scaled < 0 {return Err(format!("sws_scale: {}", ff::err_to_string(scaled)));}+ // This CPU frame is now what `encode_staged` must send, so drop any hw+ // surface a previous dmabuf frame left staged — e.g. after the stream+ // renegotiates to a modifier-less format and frames start arriving on+ // the sws path. `encode_staged` prefers `hw_staged` whenever it is+ // non-null, so without this it would keep re-sending that stale surface+ // and freeze the video. `av_frame_free` nulls the pointer.+ if !self.hw_staged.is_null() {+ ff::av_frame_free(&mut self.hw_staged);+ }self.staged = true;}Ok(())diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rsindex 6d07bd0a4..cc52d9486 100644--- a/electron/native/pipewire-capture/src/main.rs+++ b/electron/native/pipewire-capture/src/main.rs@@ -778,15 +778,29 @@ fn run<W: Write>(let staged = capture.stage(&frame);let (width, height) = (frame.crop.width, frame.crop.height);mailbox.recycle(frame.pixels);- if let Err(message) = staged {- let _ = emitter.emit(&Event::Error {- code: "encode-failed".to_owned(),- message,- });- exit_code = 1;- break;+ match staged {+ Ok(capture::StageOutcome::Staged) => {}+ // Recoverable: one frame the GPU could not import. Warn so+ // it is answerable from the log, then carry on — `advance`+ // holds the previous frame — rather than ending the file.+ Ok(capture::StageOutcome::Dropped(reason)) => {+ let _ = emitter.emit(&Event::Warning {+ code: "frame-dropped".to_owned(),+ message: reason,+ });+ }+ Err(message) => {+ let _ = emitter.emit(&Event::Error {+ code: "encode-failed".to_owned(),+ message,+ });+ exit_code = 1;+ break;+ }}- if first {+ // Only once a frame has actually staged — a first frame that+ // dropped leaves capture unstarted, so this waits for a real one.+ if first && capture.started() {let _ = emitter.emit(&Event::CaptureStarted {timestamp_ms: timestamp_ms(),path: configdiff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rsindex 08bc20cf7..7a0635f0d 100644--- a/electron/native/pipewire-capture/src/shim.rs+++ b/electron/native/pipewire-capture/src/shim.rs@@ -1010,9 +1010,22 @@ extern "C" fn on_frame(user: *mut c_void, frame: *const RawFrame) -> i32 {// 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) };+ // Same guard `with_state` gives every other callback, which this one cannot use+ // because it returns a value: a panic (an allocation failure in+ // `Vec::with_capacity`, a capacity overflow in `put`) must not unwind across the+ // `extern "C"` boundary and abort the helper. Decline the frame on panic (0) so+ // the shim re-queues it rather than leaking the buffer.+ catch_unwind(AssertUnwindSafe(|| on_frame_inner(state, frame))).unwrap_or(0)+}++/// The body of [`on_frame`], split out so the callback can wrap it in+/// `catch_unwind`. `frame` is non-null (checked by the caller) and valid for the+/// callback's duration.+fn on_frame_inner(state: &CallbackState, frame: *const RawFrame) -> i32 {let Some(mailbox) = state.frames.as_ref() else {return 0;};+ // SAFETY: non-null (checked in `on_frame`) and valid for the callback duration.let frame = unsafe { &*frame };// Tiled dmabuf: no pixels to copy. Take the PipeWire buffer (hold it out of