Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(capture): wire the dmabuf importer through to the encoder (#507)
Benjamin Freeman6a99c4737ccd
diff --git a/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md b/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.mdindex 050326110..db9e093b3 100644--- a/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md+++ b/electron/native/pipewire-capture/docs/dmabuf-vaapi-plan.md@@ -120,12 +120,20 @@ Key architecture calls:no unref between the clock-driven re-encodes).### Remaining-- [ ] `dmabuf_import.rs`: the map + scale_vaapi VPP → NV12 module (above).-- [ ] `shim.rs`: `DmabufDesc` (OwnedFd planes) + `Frame.dmabuf` + `on_frame` dup +- mailbox variant (no memcpy).-- [ ] `encoder.rs`: shared device + deferred open + `stage_hw`/`hw_staged` path.-- [ ] `capture.rs`: dmabuf branch → importer → `stage_hw`.-- [ ] Shm fallback guard + error paths; then on-device record/check/fix.+- [x] `dmabuf_import.rs`: the map + scale_vaapi VPP → NV12 module.+- [x] `shim.rs`: `DmabufDesc` (OwnedFd planes) + `Frame.dmabuf` + `on_frame` dup ++ mailbox `put_dmabuf` (no memcpy).+- [x] `encoder.rs`: `open_importing` (shared device + external NV12 pool) ++ `stage_hw`/`hw_staged` path (held across re-encodes) + Drop.+- [x] `capture.rs`: dmabuf branch → importer → `stage_hw`; deferred encoder open.+- [x] Whole pipeline compiles and links; full helper builds, libavfilter staged.+- [ ] **On-device record/check/fix.** Test via `OPENSCREEN_PIPEWIRE_FORCE_DMABUF=1`+ (dmabuf still opt-in until proven). Expect a NON-garbled full-monitor recording+ at distinct-fps ≈ OBS (~24). Likely first-try failure points: `av_hwframe_map`+ wanting `buf[0]` on the DRM_PRIME source; scale_vaapi output pool size; the+ DRM/VAAPI derive on radeonsi.+- [ ] Once proven: make dmabuf preference automatic when the backend is VAAPI+ (drop the FORCE env gate) + window/crop via VPP + non-VAAPI fallback guard.- [ ] Test on AMD/GNOME: confirm `uses_dmabuf=1`, distinct-fps ≈ OBS (~24),crop correct for window captures, cursor unaffected. Regression-checksoftware encode and a wlroots/niri compositor.diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rsindex 17c42f801..628eba3a4 100644--- a/electron/native/pipewire-capture/src/capture.rs+++ b/electron/native/pipewire-capture/src/capture.rs@@ -192,6 +192,11 @@ pub struct Summary {pub struct Capture {encoder: VideoEncoder,+ /// The dmabuf → VAAPI importer, present only on the zero-copy path (issue+ /// #507). When set, [`Self::stage`] imports the frame's descriptor into an+ /// NV12 surface instead of running swscale, and the encoder was opened+ /// against this importer's pool.+ importer: Option<crate::dmabuf_import::DmabufImporter>,video_track: TrackId,audio: Option<AudioMix>,/// `None` only between [`Self::finish`] taking it and the struct dropping.@@ -233,14 +238,45 @@ impl Capture {bitrate: Option<i64>,forced: Option<Backend>,audio_sources: Vec<AudioSource>,+ // Present when the first frame is a tiled dmabuf: the encoder is then+ // opened to consume the importer's NV12 pool directly (issue #507).+ dmabuf: Option<&shim::DmabufDesc>,) -> Result<(Self, Selection), String> {let bitrate = bitrate.unwrap_or_else(|| default_bitrate(width, height, fps));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 (encoder, importer) = match dmabuf {+ Some(desc) => {+ // v1 targets the whole monitor: the importer and encoder are+ // sized to the full stream (no crop). The encoder is FORCED to+ // VAAPI because that is the only backend that can consume the+ // mapped surface; a non-VAAPI machine should never have+ // negotiated dmabuf in the first place.+ let importer = crate::dmabuf_import::DmabufImporter::new(+ desc.width,+ desc.height,+ desc.drm_fourcc,+ )?;+ // SAFETY: the importer's device and NV12 frames context are live+ // for as long as the returned encoder, which the Capture owns+ // alongside it below.+ let encoder = unsafe {+ VideoEncoder::open_importing(+ VideoParams { width: desc.width, height: desc.height, fps, bitrate },+ importer.device(),+ importer.output_frames_ctx(),+ )?+ };+ (encoder, Some(importer))+ }+ None => {+ let encoder = VideoEncoder::open(+ VideoParams { width, height, fps, bitrate },+ forced,+ |backend, error| rejected.push(format!("{}: {error}", backend.as_str())),+ )?;+ (encoder, None)+ }+ };let selection = Selection { backend: encoder.backend(), rejected };// Every track must exist before the header: MP4 fixes its track list@@ -274,6 +310,7 @@ impl Capture {Ok((Self {encoder,+ importer,video_track,audio,muxer: Some(muxer),@@ -323,6 +360,38 @@ 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> {+ // Zero-copy dmabuf path: import the tiled GPU buffer into an NV12 VAAPI+ // surface and hand it to the encoder as-is — no swscale, no crop math+ // (v1 is whole-monitor only). See issue #507.+ if let Some(desc) = &frame.dmabuf {+ use std::os::fd::AsRawFd;+ let importer = self+ .importer+ .as_mut()+ .ok_or_else(|| "dmabuf frame arrived but no importer was built".to_owned())?;+ let planes: Vec<crate::dmabuf_import::DmabufPlane> = desc+ .planes+ .iter()+ .map(|plane| crate::dmabuf_import::DmabufPlane {+ fd: plane.fd.as_raw_fd(),+ offset: plane.offset,+ stride: plane.stride,+ })+ .collect();+ let nv12 = importer.import(&crate::dmabuf_import::DmabufFrame {+ width: desc.width,+ height: desc.height,+ drm_fourcc: desc.drm_fourcc,+ modifier: desc.modifier,+ planes: &planes,+ })?;+ // 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(());+ }+let format = pixel_format(frame.video_format)?;// Address the crop by moving the START of the slice, and hand swscale the@@ -341,21 +410,28 @@ impl Capture {.ok_or_else(|| format!("crop offset {offset} is past the end of the frame"))?;self.encoder.stage(pixels, frame.stride, format)?;- if self.epoch.is_none() {- self.epoch = Some(Instant::now());- // Audio has been accumulating since the process started, while the- // portal picker was up and the format was being negotiated. None of- // it belongs to the recording: video frame 0 is now, so audio- // sample 0 is now too. Keeping the backlog would shift the whole- // track earlier by however long the user took to click.- if let Some(mix) = &mut self.audio {- for input in &mut mix.inputs {- input.ring.clear();- input.pending.clear();- }+ self.mark_started();+ Ok(())+ }++ /// Starts the timeline on the first staged frame and drops the audio backlog.+ ///+ /// Audio has been accumulating since the process started, while the portal+ /// picker was up and the format was being negotiated. None of it belongs to+ /// the recording: video frame 0 is now, so audio sample 0 is now too. Keeping+ /// the backlog would shift the whole track earlier by however long the user+ /// took to click.+ fn mark_started(&mut self) {+ if self.epoch.is_some() {+ return;+ }+ self.epoch = Some(Instant::now());+ if let Some(mix) = &mut self.audio {+ for input in &mut mix.inputs {+ input.ring.clear();+ input.pending.clear();}}- Ok(())}/// Whether a picture has been staged, which is also whether the timeline hasdiff --git a/electron/native/pipewire-capture/src/encoder.rs b/electron/native/pipewire-capture/src/encoder.rsindex e574ae405..0d66f5c90 100644--- a/electron/native/pipewire-capture/src/encoder.rs+++ b/electron/native/pipewire-capture/src/encoder.rs@@ -193,6 +193,11 @@ pub struct VideoEncoder {sw_frame: *mut ff::AVFrame,/// The GPU-side frame handed to a hardware encoder. Null for software.hw_frame: *mut ff::AVFrame,+ /// A ready-to-encode VAAPI NV12 surface produced by the dmabuf importer+ /// (issue #507). When non-null it is sent directly — no sws_scale, no upload —+ /// and held across the clock-driven re-encodes until the next frame replaces+ /// it. Null on the shm/software path.+ hw_staged: *mut ff::AVFrame,sws: *mut ff::SwsContext,sws_src_format: ff::AVPixelFormat,packet: *mut ff::AVPacket,@@ -235,7 +240,7 @@ impl VideoEncoder {failures.push(format!("{}: {reason}", backend.as_str()));continue;}- match Self::open_backend(backend, ¶ms) {+ match Self::open_backend(backend, ¶ms, None) {Ok(encoder) => return Ok(encoder),Err(error) => {on_attempt(backend, &error);@@ -252,7 +257,26 @@ impl VideoEncoder {))}- fn open_backend(backend: Backend, params: &VideoParams) -> Result<Self, String> {+ /// Opens the VAAPI encoder to consume surfaces from an EXISTING device and+ /// NV12 frames pool — the ones the dmabuf importer built. Sharing the pool is+ /// what lets `encode_staged` send an imported surface straight to+ /// `avcodec_send_frame` without a copy (issue #507).+ ///+ /// SAFETY: `device` and `frames_ctx` must be a live VAAPI device and an NV12+ /// VAAPI frames context on it; the encoder takes its own references.+ pub unsafe fn open_importing(+ params: VideoParams,+ device: *mut ff::AVBufferRef,+ frames_ctx: *mut ff::AVBufferRef,+ ) -> Result<Self, String> {+ Self::open_backend(Backend::Vaapi, ¶ms, Some((device, frames_ctx)))+ }++ fn open_backend(+ backend: Backend,+ params: &VideoParams,+ external: Option<(*mut ff::AVBufferRef, *mut ff::AVBufferRef)>,+ ) -> Result<Self, String> {// SAFETY: this whole function is a single ffmpeg setup sequence. Every// allocation is stored in `encoder` as soon as it succeeds, so the Drop// impl frees whatever was reached if a later step fails.@@ -277,6 +301,7 @@ impl VideoEncoder {hw_frames: ptr::null_mut(),sw_frame: ptr::null_mut(),hw_frame: ptr::null_mut(),+ hw_staged: ptr::null_mut(),sws: ptr::null_mut(),sws_src_format: ff::AV_PIX_FMT_NONE,packet: ptr::null_mut(),@@ -320,7 +345,7 @@ impl VideoEncoder {(*codec_ctx).flags |= ff::AV_CODEC_FLAG_GLOBAL_HEADER as i32;if let Some(device_type) = backend.hw_device_type() {- encoder.attach_hardware(device_type, params)?;+ encoder.attach_hardware(device_type, params, external)?;}let opened = ff::avcodec_open2(codec_ctx, codec, ptr::null_mut());@@ -350,7 +375,24 @@ impl VideoEncoder {&mut self,device_type: ff::AVHWDeviceType,params: &VideoParams,+ external: Option<(*mut ff::AVBufferRef, *mut ff::AVBufferRef)>,) -> Result<(), String> {+ // The dmabuf importer already built a VAAPI device and an NV12 pool; the+ // encoder must consume from THAT pool, so take references to it instead of+ // creating a second, incompatible one. See `open_importing`.+ if let Some((device, frames_ctx)) = external {+ self.hw_device = ff::av_buffer_ref(device);+ self.hw_frames = ff::av_buffer_ref(frames_ctx);+ if self.hw_device.is_null() || self.hw_frames.is_null() {+ return Err("av_buffer_ref on the shared VAAPI context returned null".to_owned());+ }+ (*self.codec_ctx).hw_frames_ctx = ff::av_buffer_ref(self.hw_frames);+ if (*self.codec_ctx).hw_frames_ctx.is_null() {+ return Err("av_buffer_ref on the shared frames context returned null".to_owned());+ }+ return Ok(());+ }+let created = ff::av_hwdevice_ctx_create(&mut self.hw_device,device_type,@@ -498,9 +540,24 @@ impl VideoEncoder {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.+ /// Stages a ready VAAPI NV12 surface produced by the dmabuf importer. Takes+ /// ownership of `frame`; the previous one is released. Unlike [`Self::stage`]+ /// there is no conversion or upload — the surface is encoded as-is and held+ /// across the clock-driven re-encodes until the next frame replaces it.+ ///+ /// SAFETY: `frame` must be a valid VAAPI NV12 `AVFrame` from the shared pool+ /// the encoder was opened against (see `open_importing`).+ pub unsafe fn stage_hw(&mut self, frame: *mut ff::AVFrame) {+ if !self.hw_staged.is_null() {+ let mut old = self.hw_staged;+ ff::av_frame_free(&mut old);+ }+ self.hw_staged = frame;+ self.staged = true;+ }++ /// True once a picture has been staged — via [`Self::stage`] (shm/software)+ /// or [`Self::stage_hw`] (dmabuf). Before that there is nothing to encode.pub fn has_staged_frame(&self) -> bool {self.staged}@@ -521,7 +578,13 @@ impl VideoEncoder {// `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() {+ let mut used_upload = false;+ let frame = if !self.hw_staged.is_null() {+ // Imported dmabuf surface: already NV12 on the GPU. No upload, no+ // conversion — just timestamp it. Held for the next re-encode.+ (*self.hw_staged).pts = pts;+ self.hw_staged+ } else if self.hw_frames.is_null() {(*self.sw_frame).pts = pts;self.sw_frame} else {@@ -540,6 +603,7 @@ impl VideoEncoder {));}(*self.hw_frame).pts = pts;+ used_upload = true;self.hw_frame};self.stats.upload_ns += upload_started.elapsed().as_nanos();@@ -549,11 +613,13 @@ impl VideoEncoder {self.stats.encode_ns += encode_started.elapsed().as_nanos();self.stats.frames += 1;- if !self.hw_frame.is_null() {- // Release our reference to the GPU surface; the encoder keeps- // its own for as long as it needs one. Without this the pool- // drains after `initial_pool_size` frames and every subsequent- // av_hwframe_get_buffer blocks.+ if used_upload {+ // Release our reference to the per-encode upload surface; the+ // encoder keeps its own for as long as it needs one. Without this+ // the pool drains after `initial_pool_size` frames and every+ // subsequent av_hwframe_get_buffer blocks. The imported+ // `hw_staged` surface is NOT released here — it is held for the+ // next clock-driven re-encode and freed in `stage_hw`/`Drop`.ff::av_frame_unref(self.hw_frame);}}@@ -697,6 +763,9 @@ impl Drop for VideoEncoder {if !self.hw_frame.is_null() {ff::av_frame_free(&mut self.hw_frame);}+ if !self.hw_staged.is_null() {+ ff::av_frame_free(&mut self.hw_staged);+ }if !self.sw_frame.is_null() {ff::av_frame_free(&mut self.sw_frame);}diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rsindex 344d84b4b..d12b225f3 100644--- a/electron/native/pipewire-capture/src/main.rs+++ b/electron/native/pipewire-capture/src/main.rs@@ -693,6 +693,7 @@ fn run<W: Write>(config.bitrate,config.forced_encoder,std::mem::take(&mut audio_sources),+ frame.dmabuf.as_ref(),) {Ok((started, selection)) => {let _ = emitter.emit(&Event::EncoderSelection {diff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rsindex 5d1975d54..6be0424e3 100644--- a/electron/native/pipewire-capture/src/shim.rs+++ b/electron/native/pipewire-capture/src/shim.rs@@ -191,6 +191,30 @@ pub struct Frame {/// "invalid meta" and "meta covering everything" alike — none of which is a/// reason to crop, and none of which may be guessed apart.pub has_crop: bool,+ /// Set for a tiled dmabuf frame (issue #507): `pixels` is empty and the+ /// content is on the GPU, described here for a VAAPI import instead. The+ /// owned fds close when the frame is dropped or superseded.+ 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)]+pub struct DmabufDesc {+ pub width: i32,+ pub height: i32,+ pub drm_fourcc: u32,+ pub modifier: u64,+ pub planes: Vec<DmabufPlaneOwned>,+}++/// One dmabuf plane: an owned (dup'd) fd plus its layout. The fd is closed when+/// this drops.+#[derive(Debug)]+pub struct DmabufPlaneOwned {+ pub fd: std::os::fd::OwnedFd,+ pub offset: i32,+ pub stride: i32,}/// A rectangle inside a captured frame, in stream pixels.@@ -268,6 +292,43 @@ impl FrameMailbox {height: meta.crop_height,},has_crop: meta.has_crop != 0,+ dmabuf: None,+ });+ self.received.fetch_add(1, Ordering::Relaxed);+ }++ /// Stores a tiled dmabuf frame — the descriptor only, no pixel copy. Same+ /// newest-wins discipline as [`Self::put`]; a superseded frame's owned fds+ /// close when its `Frame` drops here.+ fn put_dmabuf(&self, desc: DmabufDesc, meta: &RawFrame) {+ use std::sync::atomic::Ordering;++ let Ok(mut inner) = self.inner.lock() else {+ self.dropped.fetch_add(1, Ordering::Relaxed);+ return;+ };+ let pixels = match inner.pending.take() {+ Some(stale) => {+ self.dropped.fetch_add(1, Ordering::Relaxed);+ stale.pixels+ }+ None => inner.spare.take().unwrap_or_default(),+ };+ 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,+ crop: CropRect {+ x: meta.crop_x,+ y: meta.crop_y,+ width: meta.crop_width,+ height: meta.crop_height,+ },+ has_crop: meta.has_crop != 0,+ dmabuf: Some(desc),});self.received.fetch_add(1, Ordering::Relaxed);}@@ -854,6 +915,49 @@ extern "C" fn on_frame(user: *mut c_void, frame: *const RawFrame) {}// 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 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;}