Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(recording): replace ffmpeg x11grab with native x11rb capture

Richie McIlroy37bf23ee3bc7
diff --git a/crates/recording/src/screenshot.rs b/crates/recording/src/screenshot.rs
index 7f7bbe42e..01a4787e6 100644
--- a/crates/recording/src/screenshot.rs
+++ b/crates/recording/src/screenshot.rs
@@ -1,8 +1,6 @@
use crate::sources::screen_capture::ScreenCaptureTarget;
#[cfg(target_os = "linux")]
-use crate::sources::screen_capture::{
- X11InputConfig, frame_from_x11_packet, open_x11_input, x11_capture_rect,
-};
+use crate::sources::screen_capture::{X11Grabber, X11InputConfig, x11_capture_rect};
#[cfg(target_os = "macos")]
use anyhow::Context;
#[cfg(target_os = "linux")]
@@ -1232,22 +1230,9 @@ fn capture_screenshot_x11_blocking(target: &ScreenCaptureTarget) -> anyhow::Resu
fps: 1,
show_cursor: false,
};
- let mut input = open_x11_input(&config)?;
- let stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or_else(|| anyhow!("x11grab did not expose a video stream"))?;
- let stream_index = stream.index();
-
- for (stream, packet) in input.packets() {
- if stream.index() != stream_index {
- continue;
- }
- let frame = frame_from_x11_packet(&packet, config.width, config.height)?;
- return convert_ffmpeg_frame_to_image(&frame);
- }
-
- Err(anyhow!("x11grab ended before producing a screenshot frame"))
+ let mut grabber = X11Grabber::new(&config)?;
+ let frame = grabber.grab()?;
+ convert_ffmpeg_frame_to_image(&frame)
}
#[cfg(target_os = "linux")]
diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs
index 0ecb0698f..8687dea97 100644
--- a/crates/recording/src/sources/screen_capture/linux.rs
+++ b/crates/recording/src/sources/screen_capture/linux.rs
@@ -11,13 +11,11 @@ use ashpd::desktop::{
screencast::{CursorMode, Screencast, SourceType, Stream as PortalStream},
};
use cap_timestamp::Timestamp;
-use ffmpeg::codec::packet::Packet;
use futures::channel::mpsc;
use kameo::Actor as _;
use pipewire as pw;
use pw::{properties::properties, spa};
use std::{
- ffi::CString,
os::fd::OwnedFd,
process::Command,
sync::{
@@ -27,6 +25,9 @@ use std::{
time::{Duration, Instant},
};
use tokio_util::sync::CancellationToken;
+use x11rb::connection::Connection as _;
+use x11rb::protocol::xproto::{ConnectionExt as _, ImageFormat, ImageOrder};
+use x11rb::rust_connection::RustConnection;
#[derive(Debug)]
pub struct X11Capture;
@@ -241,7 +242,7 @@ impl OutputVideoSource for VideoSource {
let info = config.video_info;
match config.input {
LinuxInputConfig::X11(input) => {
- ctx.tasks().spawn_thread("x11grab-capture-thread", {
+ ctx.tasks().spawn_thread("x11-capture-thread", {
let stop_token = stop_token.clone();
move || capture_x11(info, input, video_tx, stop_token, health_tx)
});
@@ -1121,38 +1122,32 @@ impl FrameScaler {
}
fn capture_x11(
- video_info: VideoInfo,
+ _video_info: VideoInfo,
input_config: X11InputConfig,
mut video_tx: mpsc::Sender<FFmpegVideoFrame>,
stop_token: CancellationToken,
health_tx: output_pipeline::HealthSender,
) -> anyhow::Result<()> {
- let mut input = open_x11_input(&input_config)?;
- let stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or_else(|| anyhow!("x11grab did not expose a video stream"))?;
- let stream_index = stream.index();
- let mut scaler = FrameScaler::new(
- video_info.pixel_format,
- video_info.width,
- video_info.height,
- video_info,
- )?;
+ let mut grabber = X11Grabber::new(&input_config)?;
+ let frame_interval = Duration::from_secs_f64(1.0 / f64::from(input_config.fps.max(1)));
let started = Instant::now();
+ let mut next_capture = Instant::now();
let mut sent = 0u64;
let mut dropped = 0u64;
- for (stream, packet) in input.packets() {
- if stop_token.is_cancelled() {
- break;
- }
- if stream.index() != stream_index {
- continue;
- }
+ while !stop_token.is_cancelled() {
+ let mut frame = match grabber.grab() {
+ Ok(frame) => frame,
+ Err(error) => {
+ // X11 servers can transiently fail GetImage (e.g. while the
+ // root geometry changes). Log, back off one interval, retry.
+ tracing::warn!(error = %error, "X11 frame capture failed");
+ std::thread::sleep(frame_interval);
+ continue;
+ }
+ };
+ frame.set_pts(Some(started.elapsed().as_micros() as i64));
- let raw_frame = frame_from_x11_packet(&packet, input_config.width, input_config.height)?;
- let frame = scaler.scale(&raw_frame, video_info)?;
let timestamp = Timestamp::Instant(Instant::now());
match send_with_stall_budget_futures(
&mut video_tx,
@@ -1167,6 +1162,16 @@ fn capture_x11(
StallSendOutcome::StalledAndDropped { .. } => dropped += 1,
StallSendOutcome::Disconnected => return Ok(()),
}
+
+ // Pace to the requested framerate without accumulating drift, while
+ // staying responsive to stop requests (wake at most once per interval).
+ next_capture += frame_interval;
+ let now = Instant::now();
+ if next_capture > now {
+ std::thread::sleep((next_capture - now).min(frame_interval));
+ } else {
+ next_capture = now;
+ }
}
tracing::info!(
@@ -1179,76 +1184,284 @@ fn capture_x11(
Ok(())
}
-pub(crate) fn frame_from_x11_packet(
- packet: &Packet,
- width: u32,
- height: u32,
-) -> anyhow::Result<ffmpeg::frame::Video> {
- let data = packet
- .data()
- .ok_or_else(|| anyhow!("x11grab packet did not contain frame data"))?;
- let source_stride = width as usize * 4;
- let expected_len = source_stride * height as usize;
- if data.len() < expected_len {
- bail!(
- "x11grab packet was too small: {} bytes for {}x{}",
- data.len(),
- width,
- height
+/// Native X11 screen capture via the (pure-Rust) `x11rb` protocol client.
+///
+/// This replaces FFmpeg's `x11grab` libavdevice input, which the bundled
+/// FFmpeg (spacedrive native-deps) is built without. Capturing with `x11rb`
+/// keeps us off any system FFmpeg/libavdevice and adds no new runtime
+/// shared-library dependency (`x11rb` speaks the X11 protocol over a socket).
+pub(crate) struct X11Grabber {
+ conn: RustConnection,
+ root: x11rb::protocol::xproto::Window,
+ x: i16,
+ y: i16,
+ width: u16,
+ height: u16,
+ source_pixel: ffmpeg::format::Pixel,
+ output: VideoInfo,
+ scaler: Option<FrameScaler>,
+ show_cursor: bool,
+}
+
+impl X11Grabber {
+ pub(crate) fn new(config: &X11InputConfig) -> anyhow::Result<Self> {
+ ffmpeg::init().context("initialize FFmpeg")?;
+
+ let (conn, screen_num) = x11rb::connect(Some(config.display_name.as_str()))
+ .with_context(|| format!("connect to X11 display {}", config.display_name))?;
+
+ let setup = conn.setup();
+ let screen = setup
+ .roots
+ .get(screen_num)
+ .ok_or_else(|| anyhow!("X11 screen {screen_num} not found"))?;
+ let root = screen.root;
+ let root_depth = screen.root_depth;
+ let root_visual_id = screen.root_visual;
+
+ let visual = screen
+ .allowed_depths
+ .iter()
+ .flat_map(|depth| depth.visuals.iter())
+ .find(|visual| visual.visual_id == root_visual_id)
+ .ok_or_else(|| anyhow!("X11 root visual {root_visual_id} not found"))?;
+
+ let bits_per_pixel = setup
+ .pixmap_formats
+ .iter()
+ .find(|format| format.depth == root_depth)
+ .map(|format| format.bits_per_pixel)
+ .ok_or_else(|| anyhow!("X11 pixmap format for depth {root_depth} not found"))?;
+
+ let source_pixel = x11_source_pixel(
+ setup.image_byte_order == ImageOrder::MSB_FIRST,
+ bits_per_pixel,
+ visual.red_mask,
+ visual.green_mask,
+ visual.blue_mask,
+ )?;
+
+ let x = i16::try_from(config.x)
+ .map_err(|_| anyhow!("X11 capture x offset {} out of range", config.x))?;
+ let y = i16::try_from(config.y)
+ .map_err(|_| anyhow!("X11 capture y offset {} out of range", config.y))?;
+ let width = u16::try_from(config.width)
+ .map_err(|_| anyhow!("X11 capture width {} out of range", config.width))?;
+ let height = u16::try_from(config.height)
+ .map_err(|_| anyhow!("X11 capture height {} out of range", config.height))?;
+ if width == 0 || height == 0 {
+ bail!("X11 capture size must be non-zero");
+ }
+
+ // xfixes is needed to fetch the cursor image; only probe it when asked
+ // to draw the cursor, and degrade gracefully if it is unavailable.
+ let show_cursor = config.show_cursor && {
+ use x11rb::protocol::xfixes::ConnectionExt as _;
+ conn.xfixes_query_version(5, 0)
+ .ok()
+ .and_then(|cookie| cookie.reply().ok())
+ .is_some()
+ };
+
+ let output = VideoInfo::from_raw_ffmpeg(
+ ffmpeg::format::Pixel::BGRZ,
+ u32::from(width),
+ u32::from(height),
+ config.fps.max(1),
);
- }
- let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRZ, width, height);
- let target_stride = frame.stride(0);
- if target_stride < source_stride {
- bail!(
- "x11grab frame stride was too small: {} for {}x{}",
- target_stride,
+ Ok(Self {
+ conn,
+ root,
+ x,
+ y,
width,
- height
- );
+ height,
+ source_pixel,
+ output,
+ scaler: None,
+ show_cursor,
+ })
}
- for y in 0..height as usize {
- let source_start = y * source_stride;
- let target_start = y * target_stride;
- let target_end = target_start + source_stride;
- frame.data_mut(0)[target_start..target_end]
- .copy_from_slice(&data[source_start..source_start + source_stride]);
+ /// Capture one frame of the configured region as a BGRZ video frame.
+ pub(crate) fn grab(&mut self) -> anyhow::Result<ffmpeg::frame::Video> {
+ let reply = self
+ .conn
+ .get_image(
+ ImageFormat::Z_PIXMAP,
+ self.root,
+ self.x,
+ self.y,
+ self.width,
+ self.height,
+ u32::MAX,
+ )
+ .context("request X11 image")?
+ .reply()
+ .context("read X11 image")?;
+
+ let width = usize::from(self.width);
+ let height = usize::from(self.height);
+ let row_bytes = width * 4;
+ let source_stride = reply
+ .data
+ .len()
+ .checked_div(height)
+ .filter(|stride| *stride >= row_bytes)
+ .ok_or_else(|| {
+ anyhow!(
+ "X11 image too small: {} bytes for {}x{}",
+ reply.data.len(),
+ width,
+ height
+ )
+ })?;
+
+ let mut source = ffmpeg::frame::Video::new(
+ self.source_pixel,
+ u32::from(self.width),
+ u32::from(self.height),
+ );
+ let dst_stride = source.stride(0);
+ let copy = row_bytes.min(dst_stride);
+ for row in 0..height {
+ let src_start = row * source_stride;
+ let dst_start = row * dst_stride;
+ source.data_mut(0)[dst_start..dst_start + copy]
+ .copy_from_slice(&reply.data[src_start..src_start + copy]);
+ }
+
+ // Convert to BGRZ only when the server's visual differs; the common
+ // case (32-bit little-endian BGRX) is already BGRZ and short-circuits.
+ let mut frame = if self.source_pixel == self.output.pixel_format {
+ source
+ } else {
+ if self.scaler.is_none() {
+ self.scaler = Some(FrameScaler::new(
+ self.source_pixel,
+ u32::from(self.width),
+ u32::from(self.height),
+ self.output,
+ )?);
+ }
+ self.scaler
+ .as_mut()
+ .expect("scaler initialized")
+ .scale(&source, self.output)?
+ };
+
+ if self.show_cursor {
+ if let Err(error) = self.composite_cursor(&mut frame) {
+ tracing::trace!(error = %error, "X11 cursor composite skipped");
+ }
+ }
+
+ Ok(frame)
}
- frame.set_pts(packet.pts());
- Ok(frame)
-}
+ /// Alpha-blend the X11 cursor onto a BGRZ frame (mirrors x11grab's
+ /// `draw_mouse`). xfixes returns premultiplied ARGB, so we composite with
+ /// straight `src + dst * (1 - a)`.
+ fn composite_cursor(&self, frame: &mut ffmpeg::frame::Video) -> anyhow::Result<()> {
+ use x11rb::protocol::xfixes::ConnectionExt as _;
+
+ let cursor = self
+ .conn
+ .xfixes_get_cursor_image()
+ .context("request X11 cursor image")?
+ .reply()
+ .context("read X11 cursor image")?;
+
+ let cursor_width = i32::from(cursor.width);
+ let cursor_height = i32::from(cursor.height);
+ if cursor_width <= 0 || cursor_height <= 0 {
+ return Ok(());
+ }
+ if cursor.cursor_image.len() != (cursor_width * cursor_height) as usize {
+ return Ok(());
+ }
-pub(crate) fn open_x11_input(
- config: &X11InputConfig,
-) -> anyhow::Result<ffmpeg::format::context::Input> {
- ffmpeg::init().context("initialize FFmpeg")?;
+ // Top-left of the cursor image in capture-region coordinates.
+ let origin_x = i32::from(cursor.x) - i32::from(cursor.xhot) - i32::from(self.x);
+ let origin_y = i32::from(cursor.y) - i32::from(cursor.yhot) - i32::from(self.y);
- let format_name = CString::new("x11grab")?;
- let input_format = unsafe {
- let ptr = ffmpeg::ffi::av_find_input_format(format_name.as_ptr());
- if ptr.is_null() {
- bail!("FFmpeg was built without x11grab input support");
+ let frame_width = i32::from(self.width);
+ let frame_height = i32::from(self.height);
+ let stride = frame.stride(0);
+ let buf = frame.data_mut(0);
+
+ for cy in 0..cursor_height {
+ let fy = origin_y + cy;
+ if fy < 0 || fy >= frame_height {
+ continue;
+ }
+ for cx in 0..cursor_width {
+ let fx = origin_x + cx;
+ if fx < 0 || fx >= frame_width {
+ continue;
+ }
+ let pixel = cursor.cursor_image[(cy * cursor_width + cx) as usize];
+ let alpha = (pixel >> 24) & 0xff;
+ if alpha == 0 {
+ continue;
+ }
+ let inv = 255 - alpha;
+ let src_b = pixel & 0xff;
+ let src_g = (pixel >> 8) & 0xff;
+ let src_r = (pixel >> 16) & 0xff;
+ let idx = fy as usize * stride + fx as usize * 4;
+ buf[idx] = (src_b + buf[idx] as u32 * inv / 255).min(255) as u8;
+ buf[idx + 1] = (src_g + buf[idx + 1] as u32 * inv / 255).min(255) as u8;
+ buf[idx + 2] = (src_r + buf[idx + 2] as u32 * inv / 255).min(255) as u8;
+ }
}
- ffmpeg::format::Input::wrap(ptr as *mut _)
+
+ Ok(())
+ }
+}
+
+/// Map an X11 32-bit TrueColor visual (byte order + RGB masks) to the matching
+/// packed FFmpeg pixel format. The overwhelmingly common desktop case
+/// (depth 24/32, little-endian, BGRX) resolves to BGRZ.
+fn x11_source_pixel(
+ msb_first: bool,
+ bits_per_pixel: u8,
+ red_mask: u32,
+ green_mask: u32,
+ blue_mask: u32,
+) -> anyhow::Result<ffmpeg::format::Pixel> {
+ if bits_per_pixel != 32 {
+ bail!("Unsupported X11 visual: {bits_per_pixel}bpp (expected a 32-bit TrueColor visual)");
+ }
+
+ // Address index (0 = lowest byte) that a colour channel occupies in memory.
+ let address_index = |mask: u32| -> Option<usize> {
+ let position = match mask {
+ 0x0000_00ff => 0,
+ 0x0000_ff00 => 1,
+ 0x00ff_0000 => 2,
+ 0xff00_0000 => 3,
+ _ => return None,
+ };
+ Some(if msb_first { 3 - position } else { position })
};
- let source = format!("{}+{},{}", config.display_name, config.x, config.y);
- let mut options = ffmpeg::Dictionary::new();
- options.set("framerate", &config.fps.to_string());
- options.set("video_size", &format!("{}x{}", config.width, config.height));
- options.set("draw_mouse", if config.show_cursor { "1" } else { "0" });
-
- Ok(
- ffmpeg::format::open_with(&source, &ffmpeg::Format::Input(input_format), options)
- .with_context(|| {
- format!(
- "open x11grab source {source} at {}x{}",
- config.width, config.height
- )
- })?
- .input(),
- )
+ let (Some(red), Some(green), Some(blue)) = (
+ address_index(red_mask),
+ address_index(green_mask),
+ address_index(blue_mask),
+ ) else {
+ bail!(
+ "Unsupported X11 visual masks: r={red_mask:#010x} g={green_mask:#010x} b={blue_mask:#010x}"
+ );
+ };
+
+ Ok(match (blue, green, red) {
+ (0, 1, 2) => ffmpeg::format::Pixel::BGRZ,
+ (2, 1, 0) => ffmpeg::format::Pixel::RGBZ,
+ (1, 2, 3) => ffmpeg::format::Pixel::ZBGR,
+ (3, 2, 1) => ffmpeg::format::Pixel::ZRGB,
+ _ => bail!("Unsupported X11 channel order: b={blue} g={green} r={red}"),
+ })
}