Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(recording): harden Linux capture and camera compositing

Richie McIlroy5b8389c0d9e5
diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs
index 04617847f..92aa09977 100644
--- a/apps/cli/src/record.rs
+++ b/apps/cli/src/record.rs
@@ -2,7 +2,7 @@ use cap_project::{
InstantRecordingMeta, Platform, ProjectConfiguration, RecordingMeta, RecordingMetaInner,
};
use cap_recording::{
- CameraFeed, MicrophoneFeed,
+ CameraFeed, DoneFut, MicrophoneFeed, PipelineStoppedByUser,
feeds::{camera, microphone},
instant_recording,
screen_capture::ScreenCaptureTarget,
@@ -697,6 +697,13 @@ enum ActorHandle {
}
impl ActorHandle {
+ fn done_fut(&self) -> DoneFut {
+ match self {
+ Self::Studio(actor) => actor.done_fut(),
+ Self::Instant(actor) => actor.done_fut(),
+ }
+ }
+
async fn stop(&self) -> Result<CompletedRecording, String> {
match self {
Self::Studio(actor) => actor
@@ -704,12 +711,12 @@ impl ActorHandle {
.await
.map(Box::new)
.map(CompletedRecording::Studio)
- .map_err(|e| e.to_string()),
+ .map_err(|e| format!("{e:#}")),
Self::Instant(actor) => actor
.stop()
.await
.map(CompletedRecording::Instant)
- .map_err(|e| e.to_string()),
+ .map_err(|e| format!("{e:#}")),
}
}
}
@@ -826,6 +833,10 @@ async fn start_recording(
}
RecordMode::Instant => {
let mut builder = instant_builder;
+ #[cfg(target_os = "linux")]
+ if camera_active {
+ builder = builder.with_linux_camera_composition();
+ }
builder = builder.with_max_output_size(
cap_recording::RecordingDefaults::default().instant_mode_max_resolution,
);
@@ -935,22 +946,44 @@ async fn finalize(
stop_file: Option<&Path>,
) -> Result<CompletedRecording, String> {
let outcome = std::panic::AssertUnwindSafe(async {
- wait_for_stop(duration, interactive, stop_file).await;
- actor.stop().await.map_err(|e| e.to_string())
+ finalize_after_stop_trigger(
+ actor.done_fut().map(|result| match result {
+ Err(error) if error.is_caused_by::<PipelineStoppedByUser>() => Ok(()),
+ result => result.map_err(|error| error.to_string()),
+ }),
+ wait_for_stop(duration, interactive, stop_file),
+ async { finalize_completed(actor.stop().await?).await },
+ )
+ .await
})
.catch_unwind()
.await;
- let completed = match outcome {
- Ok(Ok(completed)) => completed,
- Ok(Err(error)) => return Err(error),
- Err(_) => actor
- .stop()
- .await
- .map_err(|e| format!("recording panicked; finalize failed: {e}"))?,
- };
+ match outcome {
+ Ok(result) => result,
+ Err(_) => {
+ let completed = actor
+ .stop()
+ .await
+ .map_err(|e| format!("recording panicked; finalize failed: {e}"))?;
+ finalize_completed(completed).await
+ }
+ }
+}
- finalize_completed(completed).await
+async fn finalize_after_stop_trigger<T>(
+ capture_done: impl Future<Output = Result<(), String>>,
+ stop_requested: impl Future<Output = ()>,
+ finalize: impl Future<Output = Result<T, String>>,
+) -> Result<T, String> {
+ let capture_result = tokio::select! {
+ biased;
+ result = capture_done => result,
+ _ = stop_requested => Ok(()),
+ };
+ let finalized = finalize.await;
+ capture_result?;
+ finalized
}
async fn finalize_completed(completed: CompletedRecording) -> Result<CompletedRecording, String> {
@@ -1202,6 +1235,59 @@ fn emit_record_event(format: OutputFormat, event: &RecordEvent<'_>) -> Result<()
mod tests {
use super::*;
+ #[tokio::test]
+ async fn capture_failure_finalizes_without_waiting_for_stop_request() {
+ let finalized = std::cell::Cell::new(false);
+ let result = finalize_after_stop_trigger(
+ std::future::ready(Err("capture window disappeared".to_string())),
+ std::future::pending(),
+ async {
+ finalized.set(true);
+ Err::<(), _>("display".to_string())
+ },
+ )
+ .await;
+
+ assert!(finalized.get());
+ assert_eq!(result.unwrap_err(), "capture window disappeared");
+ }
+
+ #[tokio::test]
+ async fn stop_request_finalizes_while_capture_is_running() {
+ let result = finalize_after_stop_trigger(
+ std::future::pending(),
+ std::future::ready(()),
+ std::future::ready(Ok(42)),
+ )
+ .await;
+
+ assert_eq!(result.unwrap(), 42);
+ }
+
+ #[tokio::test]
+ async fn completed_capture_finalizes_without_stop_request() {
+ let result = finalize_after_stop_trigger(
+ std::future::ready(Ok(())),
+ std::future::pending(),
+ std::future::ready(Ok(42)),
+ )
+ .await;
+
+ assert_eq!(result.unwrap(), 42);
+ }
+
+ #[tokio::test]
+ async fn finalization_error_is_returned_after_stop_request() {
+ let result = finalize_after_stop_trigger(
+ std::future::pending(),
+ std::future::ready(()),
+ std::future::ready(Err::<(), _>("failed to finalize recording".to_string())),
+ )
+ .await;
+
+ assert_eq!(result.unwrap_err(), "failed to finalize recording");
+ }
+
#[test]
fn record_event_fields_are_camel_case() {
let started = serde_json::to_value(RecordEvent::Started {
diff --git a/apps/desktop-gpui/src/diagnostics.rs b/apps/desktop-gpui/src/diagnostics.rs
index 26ff28578..404458359 100644
--- a/apps/desktop-gpui/src/diagnostics.rs
+++ b/apps/desktop-gpui/src/diagnostics.rs
@@ -1139,7 +1139,7 @@ mod tests {
std::fs::write(target.join(cap_bin_name()), b"dev").unwrap();
assert_eq!(
resolve_selftest_binary_in(None, Some(&exe_dir), Some(&bundle), Some(&root)),
- Some(target.join(cap_bin_name()))
+ cfg!(debug_assertions).then(|| target.join(cap_bin_name()))
);
// The installed app beats the dev checkout.
diff --git a/apps/desktop-gpui/src/target_thumbnails.rs b/apps/desktop-gpui/src/target_thumbnails.rs
index dc6a36649..dcd90e0bf 100644
--- a/apps/desktop-gpui/src/target_thumbnails.rs
+++ b/apps/desktop-gpui/src/target_thumbnails.rs
@@ -976,7 +976,7 @@ mod platform {
async fn capture_target_thumbnail(target: ScreenCaptureTarget) -> Option<RgbaImage> {
#[cfg(target_os = "linux")]
- if cap_recording::screenshot::is_pure_wayland_session() {
+ if cap_recording::screenshot::uses_wayland_portal() {
return None;
}
diff --git a/apps/desktop/src-tauri/src/thumbnails/linux.rs b/apps/desktop/src-tauri/src/thumbnails/linux.rs
index fbb3d7a29..f163cce7b 100644
--- a/apps/desktop/src-tauri/src/thumbnails/linux.rs
+++ b/apps/desktop/src-tauri/src/thumbnails/linux.rs
@@ -14,7 +14,7 @@ pub async fn capture_window_thumbnail(window: &scap_targets::Window) -> Option<S
}
async fn capture_target_thumbnail(target: ScreenCaptureTarget) -> Option<String> {
- if cap_recording::screenshot::is_pure_wayland_session() {
+ if cap_recording::screenshot::uses_wayland_portal() {
return None;
}
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index 92732a056..75a2488cc 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -102,7 +102,7 @@ scap-cpal = { path = "../scap-cpal" }
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.11.0", default-features = false, features = ["tokio"] }
pipewire = "0.10.0"
-x11rb = { version = "0.13.2", features = ["xfixes"] }
+x11rb = { version = "0.13.2", features = ["composite", "xfixes"] }
[dev-dependencies]
tempfile = "3.20.0"
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index 48f3ef059..aeeacc018 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -44,6 +44,93 @@ pub struct IncrementalCaptureOutputs {
pub keyboard: Option<PathBuf>,
}
+pub struct CursorCaptureTarget {
+ pub crop_bounds: CursorCropBounds,
+ pub display: scap_targets::Display,
+ #[cfg(target_os = "linux")]
+ pub window: Option<scap_targets::WindowId>,
+}
+
+#[cfg(target_os = "linux")]
+struct X11WindowCursor {
+ connection: x11rb::rust_connection::RustConnection,
+ window: u32,
+}
+
+#[cfg(target_os = "linux")]
+impl X11WindowCursor {
+ fn new(id: &scap_targets::WindowId) -> anyhow::Result<Self> {
+ let (connection, _) = x11rb::connect(None)?;
+ Ok(Self {
+ connection,
+ window: id.to_string().parse()?,
+ })
+ }
+
+ fn position(&self) -> Option<(f64, f64)> {
+ use x11rb::protocol::xproto::ConnectionExt as _;
+
+ let geometry = self
+ .connection
+ .get_geometry(self.window)
+ .ok()?
+ .reply()
+ .ok()?;
+ let pointer = self
+ .connection
+ .query_pointer(self.window)
+ .ok()?
+ .reply()
+ .ok()?;
+ if !pointer.same_screen {
+ return None;
+ }
+ normalized_window_cursor(
+ pointer.win_x,
+ pointer.win_y,
+ geometry.width,
+ geometry.height,
+ )
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn normalized_window_cursor(x: i16, y: i16, width: u16, height: u16) -> Option<(f64, f64)> {
+ (width != 0 && height != 0).then(|| {
+ (
+ f64::from(x) / f64::from(width),
+ f64::from(y) / f64::from(height),
+ )
+ })
+}
+
+#[cfg(all(test, target_os = "linux"))]
+mod window_cursor_tests {
+ use super::normalized_window_cursor;
+
+ #[test]
+ fn window_local_cursor_coordinates_follow_resized_content() {
+ assert_eq!(
+ normalized_window_cursor(300, 150, 600, 300),
+ Some((0.5, 0.5))
+ );
+ assert_eq!(
+ normalized_window_cursor(300, 150, 1200, 600),
+ Some((0.25, 0.25))
+ );
+ assert_eq!(
+ normalized_window_cursor(-60, 330, 600, 300),
+ Some((-0.1, 1.1))
+ );
+ }
+
+ #[test]
+ fn empty_windows_cannot_produce_cursor_coordinates() {
+ assert_eq!(normalized_window_cursor(1, 1, 0, 300), None);
+ assert_eq!(normalized_window_cursor(1, 1, 600, 0), None);
+ }
+}
+
impl CursorActor {
pub fn stop(&mut self) {
drop(self.stop.take());
@@ -207,8 +294,7 @@ fn keycode_to_string(key: &device_query::Keycode) -> (String, String) {
#[tracing::instrument(name = "cursor", skip_all)]
pub fn spawn_cursor_recorder(
- crop_bounds: CursorCropBounds,
- display: scap_targets::Display,
+ target: CursorCaptureTarget,
cursors_dir: PathBuf,
prev_cursors: Cursors,
next_cursor_id: u32,
@@ -244,6 +330,16 @@ pub fn spawn_cursor_recorder(
let stop_token_child = stop_token.child_token();
let thread = std::thread::spawn(move || {
+ let crop_bounds = target.crop_bounds;
+ let display = target.display;
+ #[cfg(target_os = "linux")]
+ let window_cursor = target.window.as_ref().and_then(|id| {
+ X11WindowCursor::new(id)
+ .inspect_err(|error| tracing::error!(%error, "X11 window cursor setup failed"))
+ .ok()
+ });
+ #[cfg(target_os = "linux")]
+ let mut last_window_position = None;
let device_state = DeviceState::new();
let mut last_mouse_state = device_state.get_mouse();
let mut last_keys: Vec<device_query::Keycode> = device_state.get_keys();
@@ -285,6 +381,15 @@ pub fn spawn_cursor_recorder(
if position_changed {
last_position = position;
}
+ #[cfg(target_os = "linux")]
+ let window_position = window_cursor.as_ref().and_then(X11WindowCursor::position);
+ #[cfg(target_os = "linux")]
+ let position_changed = position_changed
+ || (target.window.is_some() && window_position != last_window_position);
+ #[cfg(target_os = "linux")]
+ {
+ last_window_position = window_position;
+ }
let cursor_id = if let Some(data) = get_cursor_data() {
let hash_bytes = Sha256::digest(&data.image);
@@ -337,15 +442,22 @@ pub fn spawn_cursor_recorder(
let cropped_norm_pos = position
.relative_to_display(display)
.and_then(|p| p.normalize())
- .map(|p| p.with_crop(crop_bounds));
+ .map(|p| p.with_crop(crop_bounds))
+ .map(|p| (p.x(), p.y()));
+ #[cfg(target_os = "linux")]
+ let cropped_norm_pos = if target.window.is_some() {
+ window_position
+ } else {
+ cropped_norm_pos
+ };
- if let Some(pos) = cropped_norm_pos {
+ if let Some((x, y)) = cropped_norm_pos {
let mouse_event = CursorMoveEvent {
active_modifiers: vec![],
cursor_id: cursor_id.clone(),
time_ms: elapsed,
- x: pos.x(),
- y: pos.y(),
+ x,
+ y,
};
response.moves.push(mouse_event);
}
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 4b36f968b..c75ca2237 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -1,5 +1,8 @@
#[cfg(target_os = "macos")]
use crate::SendableShareableContent;
+#[cfg(target_os = "linux")]
+mod linux_camera;
+
use crate::{
RecordingBaseInputs,
capture_pipeline::{
@@ -307,15 +310,27 @@ pub struct CompletedRecording {
pub health: crate::RecordingHealth,
}
+struct ScreenPipelineInput {
+ source: crate::sources::screen_capture::VideoSourceConfig,
+ info: VideoInfo,
+ #[cfg(target_os = "linux")]
+ camera_feed: Option<Arc<crate::feeds::camera::CameraFeedLock>>,
+}
+
async fn create_pipeline(
content_dir: PathBuf,
- screen_capture: crate::sources::screen_capture::VideoSourceConfig,
- screen_info: cap_media_info::VideoInfo,
+ screen: ScreenPipelineInput,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
system_audio_source: Option<crate::sources::screen_capture::SystemAudioSourceConfig>,
max_output_size: Option<u32>,
start_time: Timestamps,
) -> anyhow::Result<Pipeline> {
+ let ScreenPipelineInput {
+ source: screen_capture,
+ info: screen_info,
+ #[cfg(target_os = "linux")]
+ camera_feed,
+ } = screen;
let output_resolution = max_output_size
.map(|max_output_size| {
clamp_size(
@@ -343,6 +358,7 @@ async fn create_pipeline(
let segment_tx_for_video = segment_channel.as_ref().map(|(tx, _)| tx.clone());
+ #[cfg(not(target_os = "linux"))]
let video = ScreenCaptureMethod::make_instant_segmented_video_pipeline(
screen_capture,
segments_dir.clone(),
@@ -352,11 +368,42 @@ async fn create_pipeline(
)
.await?;
+ #[cfg(target_os = "linux")]
+ let video = if let Some(camera_feed) = camera_feed {
+ OutputPipeline::builder(segments_dir.clone())
+ .with_video::<linux_camera::CameraCompositeSource>(linux_camera::Config {
+ screen_capture,
+ camera_feed,
+ })
+ .with_timestamps(start_time)
+ .build::<crate::ffmpeg::SegmentedVideoMuxer>(crate::ffmpeg::SegmentedVideoMuxerConfig {
+ segment_duration: std::time::Duration::from_secs(2),
+ preset: cap_enc_ffmpeg::h264::H264Preset::Ultrafast,
+ output_size: Some(output_resolution),
+ shared_pause_state: None,
+ segment_tx: segment_tx_for_video,
+ })
+ .await?
+ } else {
+ ScreenCaptureMethod::make_instant_segmented_video_pipeline(
+ screen_capture,
+ segments_dir.clone(),
+ output_resolution,
+ start_time,
+ segment_tx_for_video,
+ )
+ .await?
+ };
+
let has_audio = mic_feed.is_some() || system_audio_source.is_some();
let audio = if has_audio {
let audio_dir = content_dir.join("audio");
let mut builder =
output_pipeline::OutputPipeline::builder(audio_dir.clone()).with_timestamps(start_time);
+ #[cfg(target_os = "linux")]
+ {
+ builder = builder.with_audio_anchor(output_pipeline::AudioAnchor::PipelineEpoch);
+ }
if let Some(sys_audio) = system_audio_source {
builder = builder
@@ -413,6 +460,8 @@ pub struct ActorBuilder {
system_audio: bool,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
camera_feed: Option<Arc<crate::feeds::camera::CameraFeedLock>>,
+ #[cfg(target_os = "linux")]
+ composite_camera: bool,
max_output_size: Option<u32>,
max_fps: u32,
#[cfg(target_os = "macos")]
@@ -427,6 +476,8 @@ impl ActorBuilder {
system_audio: false,
mic_feed: None,
camera_feed: None,
+ #[cfg(target_os = "linux")]
+ composite_camera: false,
max_output_size: None,
max_fps: crate::defaults::DEFAULT_INSTANT_MODE_FPS,
#[cfg(target_os = "macos")]
@@ -457,6 +508,12 @@ impl ActorBuilder {
self
}
+ #[cfg(target_os = "linux")]
+ pub fn with_linux_camera_composition(mut self) -> Self {
+ self.composite_camera = true;
+ self
+ }
+
pub fn with_max_fps(mut self, max_fps: u32) -> Self {
self.max_fps = max_fps.clamp(1, 120);
self
@@ -472,7 +529,7 @@ impl ActorBuilder {
self,
#[cfg(target_os = "macos")] shareable_content: Option<SendableShareableContent>,
) -> anyhow::Result<ActorHandle> {
- spawn_instant_recording_actor(
+ spawn_instant_recording_actor_inner(
self.output_path,
RecordingBaseInputs {
capture_target: self.capture_target,
@@ -486,17 +543,37 @@ impl ActorBuilder {
},
self.max_output_size,
self.max_fps,
+ #[cfg(target_os = "linux")]
+ self.composite_camera,
)
.await
}
}
-#[tracing::instrument("instant_recording", skip_all)]
pub async fn spawn_instant_recording_actor(
recording_dir: PathBuf,
inputs: RecordingBaseInputs,
max_output_size: Option<u32>,
max_fps: u32,
+) -> anyhow::Result<ActorHandle> {
+ spawn_instant_recording_actor_inner(
+ recording_dir,
+ inputs,
+ max_output_size,
+ max_fps,
+ #[cfg(target_os = "linux")]
+ false,
+ )
+ .await
+}
+
+#[tracing::instrument("instant_recording", skip_all)]
+async fn spawn_instant_recording_actor_inner(
+ recording_dir: PathBuf,
+ inputs: RecordingBaseInputs,
+ max_output_size: Option<u32>,
+ max_fps: u32,
+ #[cfg(target_os = "linux")] composite_camera: bool,
) -> anyhow::Result<ActorHandle> {
ensure_dir(&recording_dir)?;
@@ -653,13 +730,22 @@ pub async fn spawn_instant_recording_actor(
debug!("screen capture: {screen_source:#?}");
+ #[cfg(not(target_os = "linux"))]
let screen_info = screen_source.info();
let (screen_capture, system_audio_source) = screen_source.to_sources().await?;
+ #[cfg(target_os = "linux")]
+ let screen_info = screen_capture.video_info();
+ #[cfg(target_os = "linux")]
+ let timestamps = Timestamps::now();
let pipeline = create_pipeline(
content_dir.clone(),
- screen_capture,
- screen_info,
+ ScreenPipelineInput {
+ source: screen_capture,
+ info: screen_info,
+ #[cfg(target_os = "linux")]
+ camera_feed: inputs.camera_feed.clone().filter(|_| composite_camera),
+ },
inputs.mic_feed.clone(),
system_audio_source,
max_output_size,
@@ -802,6 +888,8 @@ mod tests {
#[test]
fn test_clamp_size_16_9_ish_landscape() {
+ assert_eq!(clamp_size((2880, 1800), (1920, 1080)), (1920, 1200));
+
// Test 16:9 aspect ratio (boundary case)
let result = clamp_size((1920, 1080), (1920, 1080));
assert_eq!(result, (1920, 1080));
diff --git a/crates/recording/src/instant_recording/linux_camera.rs b/crates/recording/src/instant_recording/linux_camera.rs
new file mode 100644
index 000000000..5502e874c
--- /dev/null
+++ b/crates/recording/src/instant_recording/linux_camera.rs
@@ -0,0 +1,811 @@
+use crate::{
+ feeds::camera::{self, CameraFeedLock},
+ ffmpeg::FFmpegVideoFrame,
+ output_pipeline::{
+ self, SetupCtx, StallSendOutcome, VideoSource, send_with_stall_budget_futures,
+ },
+ sources::screen_capture,
+};
+use anyhow::{Context, anyhow};
+use cap_media_info::VideoInfo;
+use cap_timestamp::Timestamp;
+use ffmpeg::format::Pixel;
+use futures::{FutureExt, StreamExt, channel::mpsc};
+use std::{
+ sync::Arc,
+ time::{Duration, Instant},
+};
+use tokio_util::sync::CancellationToken;
+
+const CAMERA_ATTACH_TIMEOUT: Duration = Duration::from_millis(1500);
+const CAMERA_STALE_AFTER: Duration = Duration::from_secs(1);
+const SCREEN_CHANNEL_CAPACITY: usize = 4;
+
+pub(super) struct Config {
+ pub(super) screen_capture: screen_capture::VideoSourceConfig,
+ pub(super) camera_feed: Arc<CameraFeedLock>,
+}
+
+pub(super) struct CameraCompositeSource {
+ inner: screen_capture::VideoSource,
+ info: VideoInfo,
+ _camera_feed: Arc<CameraFeedLock>,
+}
+
+impl VideoSource for CameraCompositeSource {
+ type Config = Config;
+ type Frame = FFmpegVideoFrame;
+
+ async fn setup(
+ config: Self::Config,
+ video_tx: mpsc::Sender<Self::Frame>,
+ ctx: &mut SetupCtx,
+ ) -> anyhow::Result<Self>
+ where
+ Self: Sized,
+ {
+ let (camera_tx, camera_rx) = flume::bounded(1);
+ tokio::time::timeout(
+ CAMERA_ATTACH_TIMEOUT,
+ config.camera_feed.ask(camera::AddSender(camera_tx)),
+ )
+ .await
+ .map_err(|_| {
+ anyhow!("Camera compositor timed out attaching to feed after {CAMERA_ATTACH_TIMEOUT:?}")
+ })?
+ .map_err(|error| anyhow!("Camera compositor failed to attach to feed: {error}"))?;
+
+ let (screen_tx, screen_rx) = mpsc::channel(SCREEN_CHANNEL_CAPACITY);
+ let inner = screen_capture::VideoSource::setup(config.screen_capture, screen_tx, ctx)
+ .await
+ .context("screen source setup for camera compositor")?;
+ let info = inner.video_info();
+ let stop_token = ctx.stop_token();
+ let health_tx = ctx.health_tx().clone();
+ ctx.tasks()
+ .spawn_thread("linux-instant-camera-compositor", move || {
+ compositor_thread(
+ screen_rx,
+ Some(camera_rx),
+ video_tx,
+ stop_token,
+ health_tx,
+ info,
+ )
+ });
+
+ Ok(Self {
+ inner,
+ info,
+ _camera_feed: config.camera_feed,
+ })
+ }
+
+ fn start(&mut self) -> futures::future::BoxFuture<'_, anyhow::Result<()>> {
+ self.inner.start()
+ }
+
+ fn video_info(&self) -> VideoInfo {
+ self.info
+ }
+
+ fn stop(&mut self) -> futures::future::BoxFuture<'_, anyhow::Result<()>> {
+ self.inner.stop()
+ }
+}
+
+fn compositor_thread(
+ screen_rx: mpsc::Receiver<FFmpegVideoFrame>,
+ camera_rx: Option<flume::Receiver<FFmpegVideoFrame>>,
+ mut video_tx: mpsc::Sender<FFmpegVideoFrame>,
+ stop_token: CancellationToken,
+ health_tx: output_pipeline::HealthSender,
+ info: VideoInfo,
+) -> anyhow::Result<()> {
+ futures::executor::block_on(async move {
+ let mut screen_rx = screen_rx.fuse();
+ let mut camera_closed = camera_rx.is_none();
+ let camera_started_at = Instant::now();
+ let mut camera_seen = camera_rx.is_none();
+ let mut latest_camera: Option<(FFmpegVideoFrame, Instant)> = None;
+ let mut compositor = Compositor::new(info);
+ let mut logged_compose_failure = false;
+ let mut logged_camera_disconnect = false;
+ let mut logged_camera_stale = false;
+
+ loop {
+ let stop = stop_token.cancelled().fuse();
+ let active_camera = camera_rx.as_ref().filter(|_| !camera_closed);
+ let camera = async {
+ match active_camera {
+ Some(receiver) => receiver.recv_async().await,
+ None => std::future::pending().await,
+ }
+ }
+ .fuse();
+ let screen = screen_rx.next().fuse();
+ futures::pin_mut!(stop, camera, screen);
+
+ futures::select! {
+ _ = stop => break,
+ camera_result = camera => match camera_result {
+ Ok(frame) => {
+ camera_seen = true;
+ let received_at = Instant::now();
+ let freshness_anchor = camera_freshness_anchor(&frame, received_at);
+ latest_camera = Some((frame, freshness_anchor));
+ }
+ Err(_) => {
+ camera_closed = true;
+ latest_camera = None;
+ if !logged_camera_disconnect {
+ tracing::warn!("Camera feed disconnected; continuing with screen-only output");
+ output_pipeline::emit_health(
+ &health_tx,
+ output_pipeline::PipelineHealthEvent::DeviceLost {
+ subsystem: "camera".to_string(),
+ },
+ );
+ logged_camera_disconnect = true;
+ }
+ }
+ },
+ screen_result = screen => {
+ let Some(screen) = screen_result else { break };
+
+ if let Some(camera_rx) = camera_rx.as_ref() {
+ loop {
+ match camera_rx.try_recv() {
+ Ok(frame) => {
+ camera_seen = true;
+ let received_at = Instant::now();
+ let freshness_anchor =
+ camera_freshness_anchor(&frame, received_at);
+ latest_camera = Some((frame, freshness_anchor));
+ }
+ Err(flume::TryRecvError::Empty) => break,
+ Err(flume::TryRecvError::Disconnected) => {
+ camera_closed = true;
+ latest_camera = None;
+ if !logged_camera_disconnect {
+ tracing::warn!("Camera feed disconnected; continuing with screen-only output");
+ output_pipeline::emit_health(
+ &health_tx,
+ output_pipeline::PipelineHealthEvent::DeviceLost {
+ subsystem: "camera".to_string(),
+ },
+ );
+ logged_camera_disconnect = true;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ let mut clear_latest_camera = false;
+ let now = Instant::now();
+ let camera_is_stale = latest_camera
+ .as_ref()
+ .is_some_and(|(_, received_at)| !camera_is_fresh(*received_at, now));
+ let camera_waiting_for_first_frame = !camera_closed
+ && !camera_seen
+ && now.saturating_duration_since(camera_started_at) > CAMERA_STALE_AFTER;
+ if (camera_is_stale || camera_waiting_for_first_frame) && !logged_camera_stale {
+ tracing::warn!(
+ stale_after_ms = CAMERA_STALE_AFTER.as_millis(),
+ "Camera feed is stale; continuing with screen-only output"
+ );
+ output_pipeline::emit_health(
+ &health_tx,
+ output_pipeline::PipelineHealthEvent::Stalled {
+ source: "camera-compositor".to_string(),
+ waited_ms: CAMERA_STALE_AFTER.as_millis() as u64,
+ },
+ );
+ logged_camera_stale = true;
+ }
+ if !camera_is_stale && !camera_waiting_for_first_frame {
+ logged_camera_stale = false;
+ }
+ let output = match latest_camera
+ .as_ref()
+ .filter(|(_, received_at)| camera_is_fresh(*received_at, now))
+ {
+ Some((camera, _)) => match compositor.compose(&screen, camera) {
+ Ok(frame) => frame,
+ Err(error) => {
+ clear_latest_camera = true;
+ if !logged_compose_failure {
+ tracing::warn!(error = %error, "Camera compositor degraded to screen-only output");
+ logged_compose_failure = true;
+ }
+ screen
+ }
+ },
+ None => screen,
+ };
+ if clear_latest_camera {
+ latest_camera = None;
+ }
+
+ if matches!(
+ send_with_stall_budget_futures(
+ &mut video_tx,
+ output,
+ "linux-instant-camera-compositor",
+ &health_tx,
+ ),
+ StallSendOutcome::Disconnected
+ ) {
+ break;
+ }
+ },
+ }
+ }
+
+ Ok(())
+ })
+}
+
+fn camera_is_fresh(received_at: Instant, now: Instant) -> bool {
+ now.saturating_duration_since(received_at) <= CAMERA_STALE_AFTER
+}
+
+fn camera_freshness_anchor(frame: &FFmpegVideoFrame, received_at: Instant) -> Instant {
+ match frame.timestamp {
+ Timestamp::Instant(captured_at) => captured_at,
+ _ => received_at,
+ }
+}
+
+struct Compositor {
+ info: VideoInfo,
+ screen_to_rgba: Option<RgbaConverter>,
+ camera_to_rgba: Option<RgbaConverter>,
+ rgba_to_screen: Option<RgbaConverter>,
+}
+
+impl Compositor {
+ fn new(info: VideoInfo) -> Self {
+ Self {
+ info,
+ screen_to_rgba: None,
+ camera_to_rgba: None,
+ rgba_to_screen: None,
+ }
+ }
+
+ fn compose(
+ &mut self,
+ screen: &FFmpegVideoFrame,
+ camera: &FFmpegVideoFrame,
+ ) -> anyhow::Result<FFmpegVideoFrame> {
+ let screen_rgba = self.convert_screen(&screen.inner)?;
+ let rect = overlay_rect(self.info.width, self.info.height);
+ if rect.2 == 0 {
+ return Err(anyhow!("screen dimensions are empty"));
+ }
+ let camera_rgba = self.convert_camera(&camera.inner, rect.2)?;
+ let camera_overlay = center_crop_square(&camera_rgba, rect.2)?;
+ let mut composed = screen_rgba;
+ blend_rgba(&mut composed, &camera_overlay, rect.0, rect.1)?;
+ let mut output = self.convert_to_screen(&composed)?;
+ output.set_pts(screen.inner.pts());
+
+ Ok(FFmpegVideoFrame {
+ inner: output,
+ timestamp: screen.timestamp,
+ })
+ }
+
+ fn convert_screen(
+ &mut self,
+ input: &ffmpeg::frame::Video,
+ ) -> anyhow::Result<ffmpeg::frame::Video> {
+ let needs_converter = self.screen_to_rgba.as_ref().is_none_or(|converter| {
+ converter.source_format != input.format()
+ || converter.source_width != input.width()
+ || converter.source_height != input.height()
+ });
+ if needs_converter {
+ self.screen_to_rgba = Some(RgbaConverter::new(
+ input.format(),
+ input.width(),
+ input.height(),
+ Pixel::RGBA,
+ self.info.width,
+ self.info.height,
+ )?);
+ }
+ self.screen_to_rgba
+ .as_mut()
+ .expect("screen converter initialized")
+ .convert(input)
+ }
+
+ fn convert_camera(
+ &mut self,
+ input: &ffmpeg::frame::Video,
+ size: u32,
+ ) -> anyhow::Result<ffmpeg::frame::Video> {
+ let (destination_width, destination_height) =
+ aspect_fill_dimensions(input.width(), input.height(), size)?;
+ let needs_converter = self.camera_to_rgba.as_ref().is_none_or(|converter| {
+ converter.source_format != input.format()
+ || converter.source_width != input.width()
+ || converter.source_height != input.height()
+ || converter.destination_width != destination_width
+ || converter.destination_height != destination_height
+ });
+ if needs_converter {
+ self.camera_to_rgba = Some(RgbaConverter::new(
+ input.format(),
+ input.width(),
+ input.height(),
+ Pixel::RGBA,
+ destination_width,
+ destination_height,
+ )?);
+ }
+ self.camera_to_rgba
+ .as_mut()
+ .expect("camera converter initialized")
+ .convert(input)
+ }
+
+ fn convert_to_screen(
+ &mut self,
+ input: &ffmpeg::frame::Video,
+ ) -> anyhow::Result<ffmpeg::frame::Video> {
+ if self.rgba_to_screen.is_none() {
+ self.rgba_to_screen = Some(RgbaConverter::new(
+ Pixel::RGBA,
+ self.info.width,
+ self.info.height,
+ self.info.pixel_format,
+ self.info.width,
+ self.info.height,
+ )?);
+ }
+ self.rgba_to_screen
+ .as_mut()
+ .expect("screen output converter initialized")
+ .convert(input)
+ }
+}
+
+struct RgbaConverter {
+ context: ffmpeg::software::scaling::Context,
+ source_format: ffmpeg::format::Pixel,
+ source_width: u32,
+ source_height: u32,
+ destination_format: ffmpeg::format::Pixel,
+ destination_width: u32,
+ destination_height: u32,
+}
+
+impl RgbaConverter {
+ fn new(
+ source_format: ffmpeg::format::Pixel,
+ source_width: u32,
+ source_height: u32,
+ destination_format: ffmpeg::format::Pixel,
+ destination_width: u32,
+ destination_height: u32,
+ ) -> anyhow::Result<Self> {
+ if source_width == 0
+ || source_height == 0
+ || destination_width == 0
+ || destination_height == 0
+ {
+ return Err(anyhow!("invalid video dimensions for compositor"));
+ }
+ let context = ffmpeg::software::scaling::Context::get(
+ source_format,
+ source_width,
+ source_height,
+ destination_format,
+ destination_width,
+ destination_height,
+ ffmpeg::software::scaling::Flags::BILINEAR,
+ )?;
+ Ok(Self {
+ context,
+ source_format,
+ source_width,
+ source_height,
+ destination_format,
+ destination_width,
+ destination_height,
+ })
+ }
+
+ fn convert(&mut self, input: &ffmpeg::frame::Video) -> anyhow::Result<ffmpeg::frame::Video> {
+ if self.source_format != input.format()
+ || self.source_width != input.width()
+ || self.source_height != input.height()
+ {
+ let destination_format = self.destination_format;
+ let destination_width = self.destination_width;
+ let destination_height = self.destination_height;
+ *self = Self::new(
+ input.format(),
+ input.width(),
+ input.height(),
+ destination_format,
+ destination_width,
+ destination_height,
+ )?;
+ }
+ let mut output = ffmpeg::frame::Video::empty();
+ self.context.run(input, &mut output)?;
+ output.set_pts(input.pts());
+ Ok(output)
+ }
+}
+
+fn overlay_rect(width: u32, height: u32) -> (usize, usize, u32) {
+ if width == 0 || height == 0 {
+ return (0, 0, 0);
+ }
+ let short = width.min(height);
+ let size = ((u64::from(short) * 30) / 100).clamp(1, u64::from(short)) as u32;
+ let margin = (u64::from(short) * 2 / 100) as u32;
+ let x = width.saturating_sub(size.saturating_add(margin));
+ let y = height.saturating_sub(size.saturating_add(margin));
+ (x as usize, y as usize, size)
+}
+
+fn aspect_fill_dimensions(width: u32, height: u32, size: u32) -> anyhow::Result<(u32, u32)> {
+ if width == 0 || height == 0 || size == 0 {
+ return Err(anyhow!("invalid dimensions for camera scaling"));
+ }
+ if width >= height {
+ let scaled_width = (u64::from(size) * u64::from(width)).div_ceil(u64::from(height));
+ Ok((scaled_width.min(u64::from(u32::MAX)) as u32, size))
+ } else {
+ let scaled_height = (u64::from(size) * u64::from(height)).div_ceil(u64::from(width));
+ Ok((size, scaled_height.min(u64::from(u32::MAX)) as u32))
+ }
+}
+
+fn center_crop_square(
+ source: &ffmpeg::frame::Video,
+ size: u32,
+) -> anyhow::Result<ffmpeg::frame::Video> {
+ if size == 0 || source.width() == 0 || source.height() == 0 {
+ return Err(anyhow!("invalid camera dimensions for compositor"));
+ }
+ let source_width = source.width() as usize;
+ let source_height = source.height() as usize;
+ let crop_size = source_width.min(source_height);
+ if crop_size < size as usize {
+ return Err(anyhow!("scaled camera frame is smaller than overlay"));
+ }
+ let crop_x = (source_width - size as usize) / 2;
+ let crop_y = (source_height - size as usize) / 2;
+ let mut output = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, size, size);
+ let source_stride = source.stride(0);
+ let output_stride = output.stride(0);
+ let source_data = source.data(0);
+ let output_data = output.data_mut(0);
+ for y in 0..size as usize {
+ let source_y = crop_y + y;
+ for x in 0..size as usize {
+ let source_x = crop_x + x;
+ let source_offset = source_y * source_stride + source_x * 4;
+ let output_offset = y * output_stride + x * 4;
+ if source_offset + 4 > source_data.len() || output_offset + 4 > output_data.len() {
+ return Err(anyhow!(
+ "RGBA camera frame layout is smaller than dimensions"
+ ));
+ }
+ output_data[output_offset..output_offset + 4]
+ .copy_from_slice(&source_data[source_offset..source_offset + 4]);
+ }
+ }
+ output.set_pts(source.pts());
+ Ok(output)
+}
+
+fn blend_rgba(
+ destination: &mut ffmpeg::frame::Video,
+ source: &ffmpeg::frame::Video,
+ x: usize,
+ y: usize,
+) -> anyhow::Result<()> {
+ if destination.format() != ffmpeg::format::Pixel::RGBA
+ || source.format() != ffmpeg::format::Pixel::RGBA
+ {
+ return Err(anyhow!("RGBA blend requires RGBA frames"));
+ }
+ let destination_stride = destination.stride(0);
+ let source_stride = source.stride(0);
+ let destination_width = destination.width() as usize;
+ let destination_height = destination.height() as usize;
+ let source_width = source.width() as usize;
+ let source_height = source.height() as usize;
+ if x.saturating_add(source_width) > destination_width
+ || y.saturating_add(source_height) > destination_height
+ {
+ return Err(anyhow!("camera overlay exceeds screen frame"));
+ }
+ let source_data = source.data(0);
+ let destination_data = destination.data_mut(0);
+ for row in 0..source_height {
+ for column in 0..source_width {
+ let source_offset = row * source_stride + column * 4;
+ let destination_offset = (y + row) * destination_stride + (x + column) * 4;
+ let alpha = u16::from(source_data[source_offset + 3]);
+ let inverse_alpha = 255 - alpha;
+ for channel in 0..3 {
+ destination_data[destination_offset + channel] =
+ ((u16::from(source_data[source_offset + channel]) * alpha
+ + u16::from(destination_data[destination_offset + channel])
+ * inverse_alpha
+ + 127)
+ / 255) as u8;
+ }
+ destination_data[destination_offset + 3] = 255;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use futures::SinkExt;
+
+ #[test]
+ fn camera_freshness_expires_after_one_second() {
+ let now = Instant::now();
+ assert!(!camera_is_fresh(
+ now,
+ now + CAMERA_STALE_AFTER + Duration::from_millis(1)
+ ));
+ assert!(camera_is_fresh(now, now + CAMERA_STALE_AFTER));
+ }
+
+ #[test]
+ fn camera_freshness_uses_capture_time_for_queued_frames() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let now = Instant::now();
+ let captured_at = now
+ .checked_sub(CAMERA_STALE_AFTER + Duration::from_millis(1))
+ .expect("test instant has enough history");
+ let frame = FFmpegVideoFrame {
+ inner: ffmpeg::frame::Video::new(Pixel::RGBA, 1, 1),
+ timestamp: Timestamp::Instant(captured_at),
+ };
+ assert!(!camera_is_fresh(camera_freshness_anchor(&frame, now), now));
+ assert_eq!(camera_freshness_anchor(&frame, now), captured_at);
+ }
+
+ #[test]
+ fn overlay_rect_is_bottom_right_and_safe_for_tiny_frames() {
+ assert_eq!(overlay_rect(100, 50), (84, 34, 15));
+ assert_eq!(overlay_rect(1, 1), (0, 0, 1));
+ assert_eq!(overlay_rect(0, 50), (0, 0, 0));
+ assert_eq!(overlay_rect(100, 0), (0, 0, 0));
+ }
+
+ #[test]
+ fn center_crop_square_preserves_center_pixel() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let mut source = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, 6, 4);
+ source.data_mut(0).fill(0);
+ let stride = source.stride(0);
+ let center = 2 * stride + 2 * 4;
+ source.data_mut(0)[center..center + 4].copy_from_slice(&[1, 2, 3, 255]);
+ let cropped = center_crop_square(&source, 2).expect("crop succeeds");
+ assert_eq!(
+ &cropped.data(0)[cropped.stride(0)..cropped.stride(0) + 4],
+ &[1, 2, 3, 255]
+ );
+ }
+
+ #[test]
+ fn compositor_converts_nv12_camera_without_mutating_screen_and_preserves_pts() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let timestamp = Timestamp::Instant(Instant::now());
+ let info = VideoInfo::from_raw_ffmpeg(ffmpeg::format::Pixel::BGRA, 8, 8, 30);
+ let mut screen = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 8, 8);
+ for pixel in screen.data_mut(0).chunks_exact_mut(4) {
+ pixel.copy_from_slice(&[0, 255, 0, 255]);
+ }
+ screen.set_pts(Some(1234));
+ let original = screen.data(0).to_vec();
+ let mut camera = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, 4, 4);
+ camera.data_mut(0).fill(235);
+ camera.data_mut(1).fill(128);
+ let camera_before = (camera.data(0).to_vec(), camera.data(1).to_vec());
+ let screen_frame = FFmpegVideoFrame {
+ inner: screen,
+ timestamp,
+ };
+ let camera_frame = FFmpegVideoFrame {
+ inner: camera,
+ timestamp,
+ };
+ let mut compositor = Compositor::new(info);
+ let output = compositor
+ .compose(&screen_frame, &camera_frame)
+ .expect("composition succeeds");
+ assert_eq!(screen_frame.inner.data(0), original.as_slice());
+ assert_eq!(camera_frame.inner.data(0), camera_before.0.as_slice());
+ assert_eq!(camera_frame.inner.data(1), camera_before.1.as_slice());
+ assert_eq!(output.inner.pts(), Some(1234));
+ assert!(matches!(
+ (output.timestamp, timestamp),
+ (Timestamp::Instant(actual), Timestamp::Instant(expected)) if actual == expected
+ ));
+ assert_ne!(
+ &output.inner.data(0)[output.inner.stride(0) * 7 + 7 * 4..][..3],
+ &[0, 255, 0]
+ );
+ }
+
+ #[test]
+ fn compositor_converts_nv12_screen_and_preserves_input() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let timestamp = Timestamp::Instant(Instant::now());
+ let info = VideoInfo::from_raw_ffmpeg(Pixel::NV12, 8, 8, 30);
+ let mut screen = ffmpeg::frame::Video::new(Pixel::NV12, 8, 8);
+ screen.data_mut(0).fill(16);
+ screen.data_mut(1).fill(128);
+ screen.set_pts(Some(4321));
+ let original_y = screen.data(0).to_vec();
+ let mut camera = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);
+ for pixel in camera.data_mut(0).chunks_exact_mut(4) {
+ pixel.copy_from_slice(&[0, 0, 255, 255]);
+ }
+ let screen_frame = FFmpegVideoFrame {
+ inner: screen,
+ timestamp,
+ };
+ let camera_frame = FFmpegVideoFrame {
+ inner: camera,
+ timestamp,
+ };
+ let mut compositor = Compositor::new(info);
+ let output = compositor
+ .compose(&screen_frame, &camera_frame)
+ .expect("composition succeeds");
+ assert_eq!(screen_frame.inner.data(0), original_y.as_slice());
+ assert_eq!(output.inner.format(), Pixel::NV12);
+ assert_eq!(output.inner.pts(), Some(4321));
+ assert_ne!(output.inner.data(0)[output.inner.stride(0) * 7 + 7], 16);
+ }
+
+ #[tokio::test]
+ async fn compositor_passes_screen_without_camera_and_closes_on_cancel() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let timestamp = Timestamp::Instant(Instant::now());
+ let info = VideoInfo::from_raw_ffmpeg(Pixel::BGRA, 4, 4, 30);
+ let mut inner = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);
+ inner.data_mut(0).fill(17);
+ inner.set_pts(Some(77));
+ let expected = inner.data(0).to_vec();
+ let frame = FFmpegVideoFrame { inner, timestamp };
+ let (mut screen_tx, screen_rx) = mpsc::channel(1);
+ let (video_tx, mut video_rx) = mpsc::channel(1);
+ let (health_tx, _health_rx) = tokio::sync::mpsc::channel(1);
+ let stop_token = CancellationToken::new();
+ let _stop_guard = stop_token.clone().drop_guard();
+ let worker_stop = stop_token.clone();
+ let (done_tx, done_rx) = std::sync::mpsc::channel();
+ let worker = std::thread::spawn(move || {
+ let result = compositor_thread(screen_rx, None, video_tx, worker_stop, health_tx, info);
+ let _ = done_tx.send(result);
+ });
+
+ screen_tx.send(frame).await.expect("screen frame sent");
+ let output = tokio::time::timeout(Duration::from_secs(2), video_rx.next())
+ .await
+ .expect("screen-only output arrives promptly")
+ .expect("screen-only frame emitted");
+ assert_eq!(output.inner.data(0), expected.as_slice());
+ assert_eq!(output.inner.pts(), Some(77));
+ assert!(matches!(
+ (output.timestamp, timestamp),
+ (Timestamp::Instant(actual), Timestamp::Instant(expected)) if actual == expected
+ ));
+
+ stop_token.cancel();
+ drop(screen_tx);
+ done_rx
+ .recv_timeout(Duration::from_secs(2))
+ .expect("compositor exits promptly")
+ .expect("compositor stopped");
+ worker.join().expect("compositor thread joined");
+ assert!(video_rx.next().await.is_none());
+ }
+
+ #[tokio::test]
+ async fn compositor_reports_silent_attached_camera_and_keeps_screen_output() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let timestamp = Timestamp::Instant(Instant::now());
+ let info = VideoInfo::from_raw_ffmpeg(Pixel::BGRA, 4, 4, 30);
+ let mut first_inner = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);
+ first_inner.data_mut(0).fill(17);
+ first_inner.set_pts(Some(77));
+ let first_frame = FFmpegVideoFrame {
+ inner: first_inner,
+ timestamp,
+ };
+ let mut second_inner = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);
+ second_inner.data_mut(0).fill(23);
+ second_inner.set_pts(Some(88));
+ let second_frame = FFmpegVideoFrame {
+ inner: second_inner,
+ timestamp,
+ };
+ let (mut screen_tx, screen_rx) = mpsc::channel(1);
+ let (camera_tx, camera_rx) = flume::bounded(1);
+ let (video_tx, mut video_rx) = mpsc::channel(1);
+ let (health_tx, mut health_rx) = tokio::sync::mpsc::channel(4);
+ let stop_token = CancellationToken::new();
+ let _stop_guard = stop_token.clone().drop_guard();
+ let worker_stop = stop_token.clone();
+ let (done_tx, done_rx) = std::sync::mpsc::channel();
+ let worker = std::thread::spawn(move || {
+ let result = compositor_thread(
+ screen_rx,
+ Some(camera_rx),
+ video_tx,
+ worker_stop,
+ health_tx,
+ info,
+ );
+ let _ = done_tx.send(result);
+ });
+
+ screen_tx
+ .send(first_frame)
+ .await
+ .expect("first screen frame sent");
+ let first_output = tokio::time::timeout(Duration::from_secs(2), video_rx.next())
+ .await
+ .expect("first screen-only output arrives promptly")
+ .expect("first screen-only frame emitted");
+ assert_eq!(first_output.inner.pts(), Some(77));
+
+ tokio::time::sleep(CAMERA_STALE_AFTER + Duration::from_millis(20)).await;
+ screen_tx
+ .send(second_frame)
+ .await
+ .expect("second screen frame sent");
+ let second_output = tokio::time::timeout(Duration::from_secs(2), video_rx.next())
+ .await
+ .expect("silent-camera screen output arrives promptly")
+ .expect("silent-camera screen frame emitted");
+ assert_eq!(second_output.inner.pts(), Some(88));
+ assert!(matches!(
+ tokio::time::timeout(Duration::from_secs(2), health_rx.recv())
+ .await
+ .expect("silent camera reports its health promptly"),
+ Some(output_pipeline::PipelineHealthEvent::Stalled { source, .. })
+ if source == "camera-compositor"
+ ));
+
+ stop_token.cancel();
+ drop(camera_tx);
+ drop(screen_tx);
+ done_rx
+ .recv_timeout(Duration::from_secs(2))
+ .expect("compositor exits promptly")
+ .expect("compositor stopped");
+ worker.join().expect("compositor thread joined");
+ assert!(video_rx.next().await.is_none());
+ }
+
+ #[test]
+ fn blend_rejects_overlay_outside_screen_bounds() {
+ ffmpeg::init().expect("FFmpeg initializes");
+ let mut destination = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, 2, 2);
+ let source = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, 2, 2);
+ assert!(blend_rgba(&mut destination, &source, 1, 0).is_err());
+ }
+}
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index b02ec1396..75b4cbf9c 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -2141,6 +2141,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
let mut source_clock = SourceClockState::new("video");
let mut dropped_during_pause: u64 = 0;
let mut last_frame = None;
+ let mut first_frame_offset = None;
let res = stop_token
.run_until_cancelled(async {
@@ -2207,6 +2208,10 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
}
};
+ if first_frame_offset.is_none() {
+ first_frame_offset = Some(remap.duration().saturating_sub(total_pause_duration));
+ }
+
if anomaly_tracker.take_resync_flag() {
info!(
raw_duration_ms = raw_duration.as_millis(),
@@ -2320,6 +2325,12 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
}
};
+ if first_frame_offset.is_none() {
+ first_frame_offset = Some(
+ remap.duration().saturating_sub(shared_pause.total_pause_duration()),
+ );
+ }
+
let _ = anomaly_tracker.take_resync_flag();
let duration =
drift_tracker.calculate_timestamp(raw_duration, wall_clock_elapsed);
@@ -2359,6 +2370,8 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
}
let final_pause_duration = shared_pause.total_pause_duration();
+ // Video PTS begin at the first frame, which may arrive minutes after a portal request starts.
+ let video_stopped_at = stopped_at.saturating_sub(first_frame_offset.unwrap_or(stopped_at));
if was_cancelled
&& !shared_pause.check().0
@@ -2366,7 +2379,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
&& let Some((_, last_timestamp)) = timestamp_span.get()
&& let Some(final_timestamp) = static_video_tail_timestamp(
last_timestamp,
- stopped_at,
+ video_stopped_at,
Duration::from_nanos(frame_duration_ns),
)
{
@@ -5165,10 +5178,10 @@ mod tests {
}
}
- #[tokio::test]
- async fn static_capture_finishes_with_two_nominally_spaced_frames() {
+ async fn record_static_capture(startup_delay: Duration) -> (Vec<Duration>, Duration) {
let temp_dir = tempfile::tempdir().unwrap();
let clock = Timestamps::now();
+ tokio::time::sleep(startup_delay).await;
let (sender, receiver) = flume::bounded(4);
let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
let pipeline = OutputPipeline::builder(temp_dir.path().join("static.mp4"))
@@ -5181,16 +5194,24 @@ mod tests {
.await
.unwrap();
+ let first_frame_at = Instant::now();
sender
.send_async(StaticFrame {
- timestamp: Timestamp::Instant(clock.instant()),
+ timestamp: Timestamp::Instant(first_frame_at),
})
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(180)).await;
+ let capture_duration = first_frame_at.elapsed();
pipeline.stop().await.unwrap();
let timestamps = sent.lock().unwrap().clone();
+ (timestamps, capture_duration)
+ }
+
+ #[tokio::test]
+ async fn static_capture_finishes_with_two_nominally_spaced_frames() {
+ let (timestamps, _) = record_static_capture(Duration::ZERO).await;
assert_eq!(timestamps.len(), 3);
let final_frame = timestamps[timestamps.len() - 1];
let penultimate_frame = timestamps[timestamps.len() - 2];
@@ -5200,6 +5221,16 @@ mod tests {
);
assert!(final_frame > Duration::from_millis(100));
}
+
+ #[tokio::test]
+ async fn static_tail_excludes_source_initialization_delay() {
+ let (timestamps, capture_duration) =
+ record_static_capture(Duration::from_secs(1)).await;
+ assert_eq!(timestamps.first(), Some(&Duration::ZERO));
+ let final_frame = *timestamps.last().unwrap();
+ assert!(final_frame > capture_duration.saturating_sub(Duration::from_millis(100)));
+ assert!(final_frame < capture_duration.saturating_add(Duration::from_millis(250)));
+ }
}
mod blocking_thread_finish {
diff --git a/crates/recording/src/screenshot.rs b/crates/recording/src/screenshot.rs
index 11f1bfb9b..f17f72050 100644
--- a/crates/recording/src/screenshot.rs
+++ b/crates/recording/src/screenshot.rs
@@ -1,6 +1,8 @@
use crate::sources::screen_capture::ScreenCaptureTarget;
#[cfg(target_os = "linux")]
-use crate::sources::screen_capture::{X11Grabber, X11InputConfig, x11_capture_rect};
+use crate::sources::screen_capture::{
+ X11Grabber, X11InputConfig, prefers_wayland_portal, x11_capture_rect,
+};
#[cfg(target_os = "macos")]
use anyhow::Context;
#[cfg(target_os = "linux")]
@@ -819,7 +821,7 @@ fn try_fast_capture(target: &ScreenCaptureTarget) -> Option<DynamicImage> {
#[cfg(target_os = "linux")]
pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<DynamicImage> {
- if is_pure_wayland_session() {
+ if uses_wayland_portal() {
let image = capture_screenshot_wayland(&target).await?;
return Ok(finalize_screenshot(image, &target));
}
@@ -829,19 +831,8 @@ pub async fn capture_screenshot(target: ScreenCaptureTarget) -> anyhow::Result<D
}
#[cfg(target_os = "linux")]
-pub fn is_pure_wayland_session() -> bool {
- is_pure_wayland_environment(
- std::env::var_os("WAYLAND_DISPLAY").as_deref(),
- std::env::var_os("DISPLAY").as_deref(),
- )
-}
-
-#[cfg(target_os = "linux")]
-fn is_pure_wayland_environment(
- wayland_display: Option<&std::ffi::OsStr>,
- x11_display: Option<&std::ffi::OsStr>,
-) -> bool {
- wayland_display.is_some() && x11_display.is_none()
+pub fn uses_wayland_portal() -> bool {
+ prefers_wayland_portal()
}
#[cfg(target_os = "linux")]
@@ -1437,6 +1428,12 @@ fn capture_screenshot_x11_blocking(target: &ScreenCaptureTarget) -> anyhow::Resu
let (display_name, x, y, width, height) = linux_capture_geometry(target)?;
let config = X11InputConfig {
display_name,
+ window_id: match target {
+ ScreenCaptureTarget::Window { id } => {
+ Some(id.to_string().parse().context("Invalid X11 window ID")?)
+ }
+ _ => None,
+ },
x,
y,
width,
@@ -1477,34 +1474,17 @@ fn linux_capture_geometry(
ScreenCaptureTarget::Window { id } => {
let window =
scap_targets::Window::from_id(id).ok_or_else(|| anyhow!("Window not found"))?;
- let display = window
- .display()
- .ok_or_else(|| anyhow!("Window display unavailable"))?;
- let display_position = display
- .raw_handle()
- .physical_position()
- .ok_or_else(|| anyhow!("Display position unavailable"))?;
- let display_size = display
- .physical_size()
- .ok_or_else(|| anyhow!("Display size unavailable"))?;
let bounds = window
.raw_handle()
.physical_bounds()
.ok_or_else(|| anyhow!("Window bounds unavailable"))?;
- let crop = (
- bounds.position().x() - display_position.x(),
- bounds.position().y() - display_position.y(),
- bounds.size().width(),
- bounds.size().height(),
- );
- let (x, y, width, height) = x11_capture_rect(
- display_position.x(),
- display_position.y(),
- display_size.width(),
- display_size.height(),
- Some(crop),
- )?;
- Ok((display_name, x, y, width, height))
+ Ok((
+ display_name,
+ 0,
+ 0,
+ bounds.size().width() as u32,
+ bounds.size().height() as u32,
+ ))
}
ScreenCaptureTarget::Area { screen, bounds } => {
let display = scap_targets::Display::from_id(screen)
@@ -1541,7 +1521,6 @@ fn linux_capture_geometry(
mod wayland_screenshot_tests {
use super::*;
use scap_targets::bounds::{LogicalBounds, LogicalPosition, LogicalSize};
- use std::ffi::OsStr;
fn area_target(x: f64, y: f64, width: f64, height: f64) -> ScreenCaptureTarget {
ScreenCaptureTarget::Area {
@@ -1550,20 +1529,6 @@ mod wayland_screenshot_tests {
}
}
- #[test]
- fn pure_wayland_requires_wayland_socket_without_x11_display() {
- assert!(is_pure_wayland_environment(
- Some(OsStr::new("wayland-1")),
- None
- ));
- assert!(!is_pure_wayland_environment(
- Some(OsStr::new("wayland-1")),
- Some(OsStr::new(":99"))
- ));
- assert!(!is_pure_wayland_environment(None, None));
- assert!(!is_pure_wayland_environment(None, Some(OsStr::new(":99"))));
- }
-
#[test]
fn only_local_file_screenshot_uris_are_accepted() {
assert!(is_local_wayland_screenshot_uri("file", None));
diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs
index bf9291e4c..fee1e5bef 100644
--- a/crates/recording/src/sources/screen_capture/linux.rs
+++ b/crates/recording/src/sources/screen_capture/linux.rs
@@ -1,3 +1,4 @@
+use super::cadence::FrameCadenceGate;
use super::*;
use crate::feeds::microphone::{self, MicrophoneFeed, MicrophoneFeedLock};
use crate::ffmpeg::FFmpegVideoFrame;
@@ -26,7 +27,11 @@ use std::{
};
use tokio_util::sync::CancellationToken;
use x11rb::connection::Connection as _;
-use x11rb::protocol::xproto::{ConnectionExt as _, ImageFormat, ImageOrder};
+use x11rb::protocol::Event;
+use x11rb::protocol::composite::{ConnectionExt as _, Redirect};
+use x11rb::protocol::xproto::{
+ ChangeWindowAttributesAux, ConnectionExt as _, EventMask, ImageFormat, ImageOrder, MapState,
+};
use x11rb::rust_connection::RustConnection;
#[derive(Debug)]
@@ -54,6 +59,12 @@ pub struct VideoSourceConfig {
input: LinuxInputConfig,
}
+impl VideoSourceConfig {
+ pub(crate) fn video_info(&self) -> VideoInfo {
+ self.video_info
+ }
+}
+
enum LinuxInputConfig {
X11(X11InputConfig),
Wayland(WaylandInputConfig),
@@ -61,6 +72,7 @@ enum LinuxInputConfig {
pub(crate) struct X11InputConfig {
pub display_name: String,
+ pub window_id: Option<u32>,
pub x: i32,
pub y: i32,
pub width: u32,
@@ -91,79 +103,75 @@ impl ScreenCaptureConfig<X11Capture> {
pub async fn to_sources(
&self,
) -> anyhow::Result<(VideoSourceConfig, Option<SystemAudioSourceConfig>)> {
- let system_audio = if self.system_audio {
- Some(create_system_audio_source_config().await?)
- } else {
- None
- };
-
- if prefers_wayland_portal() {
- match create_wayland_source_config(self).await {
- Ok((video_info, input)) => {
- return Ok((
- VideoSourceConfig {
- video_info,
- input: LinuxInputConfig::Wayland(input),
- },
- system_audio,
- ));
- }
- Err(error) if std::env::var_os("DISPLAY").is_some() => {
- tracing::warn!(
- error = %error,
- "Wayland portal capture failed; falling back to X11 capture"
- );
- }
- Err(error) => return Err(error),
+ let source = if prefers_wayland_portal() {
+ let (video_info, input) = create_wayland_source_config(self).await?;
+ VideoSourceConfig {
+ video_info,
+ input: LinuxInputConfig::Wayland(input),
}
- }
-
- let display =
- Display::from_id(&self.config.display).ok_or_else(|| anyhow!("Display not found"))?;
- let display_position = display
- .raw_handle()
- .physical_position()
- .ok_or_else(|| anyhow!("Display position unavailable"))?;
- let display_size = display
- .physical_size()
- .ok_or_else(|| anyhow!("Display size unavailable"))?;
-
- let crop = self.config.crop_bounds.map(|crop| {
- (
- crop.position().x(),
- crop.position().y(),
- crop.size().width(),
- crop.size().height(),
- )
- });
- let (x, y, width, height) = x11_capture_rect(
- display_position.x(),
- display_position.y(),
- display_size.width(),
- display_size.height(),
- crop,
- )?;
- let video_info = VideoInfo {
- width,
- height,
- ..self.video_info
- };
+ } else {
+ let display = Display::from_id(&self.config.display)
+ .ok_or_else(|| anyhow!("Display not found"))?;
+ let display_position = display
+ .raw_handle()
+ .physical_position()
+ .ok_or_else(|| anyhow!("Display position unavailable"))?;
+ let display_size = display
+ .physical_size()
+ .ok_or_else(|| anyhow!("Display size unavailable"))?;
+
+ let crop = self.config.crop_bounds.map(|crop| {
+ (
+ crop.position().x(),
+ crop.position().y(),
+ crop.size().width(),
+ crop.size().height(),
+ )
+ });
+ let (x, y, width, height) = x11_capture_rect(
+ display_position.x(),
+ display_position.y(),
+ display_size.width(),
+ display_size.height(),
+ crop,
+ )?;
+ let video_info =
+ if matches!(&self.config.linux_source, LinuxCaptureSource::Window { .. }) {
+ self.video_info
+ } else {
+ VideoInfo {
+ width,
+ height,
+ ..self.video_info
+ }
+ };
- Ok((
VideoSourceConfig {
video_info,
input: LinuxInputConfig::X11(X11InputConfig {
display_name: std::env::var("DISPLAY").unwrap_or_else(|_| ":0".to_string()),
+ window_id: match &self.config.linux_source {
+ LinuxCaptureSource::Window { id } => {
+ Some(id.to_string().parse().context("Invalid X11 window ID")?)
+ }
+ LinuxCaptureSource::Display | LinuxCaptureSource::Area => None,
+ },
x,
y,
- width,
- height,
+ width: video_info.width,
+ height: video_info.height,
fps: self.config.fps,
show_cursor: self.config.show_cursor,
}),
- },
- system_audio,
- ))
+ }
+ };
+ let system_audio = if self.system_audio {
+ Some(create_system_audio_source_config().await?)
+ } else {
+ None
+ };
+
+ Ok((source, system_audio))
}
}
@@ -286,6 +294,9 @@ struct PipewireCaptureState {
fatal_error: Arc<parking_lot::Mutex<Option<String>>>,
sent: Arc<AtomicU64>,
dropped: Arc<AtomicU64>,
+ rate_limited: Arc<AtomicU64>,
+ capture_clock: Instant,
+ cadence_gate: FrameCadenceGate,
}
impl PipewireCaptureState {
@@ -300,10 +311,11 @@ impl PipewireCaptureState {
async fn create_wayland_source_config(
config: &ScreenCaptureConfig<X11Capture>,
) -> anyhow::Result<(VideoInfo, WaylandInputConfig)> {
- let portal = open_wayland_portal(config.config.linux_source, config.config.show_cursor).await?;
- let crop_bounds = match config.config.linux_source {
+ let portal =
+ open_wayland_portal(&config.config.linux_source, config.config.show_cursor).await?;
+ let crop_bounds = match &config.config.linux_source {
LinuxCaptureSource::Area => config.config.crop_bounds,
- LinuxCaptureSource::Display | LinuxCaptureSource::Window => None,
+ LinuxCaptureSource::Display | LinuxCaptureSource::Window { .. } => None,
};
let video_info = wayland_video_info(&portal.stream, config.video_info, crop_bounds);
@@ -320,7 +332,7 @@ async fn create_wayland_source_config(
}
async fn open_wayland_portal(
- source: LinuxCaptureSource,
+ source: &LinuxCaptureSource,
show_cursor: bool,
) -> anyhow::Result<WaylandPortalCapture> {
let proxy: Screencast<'static> = Screencast::new()
@@ -374,19 +386,21 @@ async fn open_wayland_portal(
})
}
-fn prefers_wayland_portal() -> bool {
- if std::env::var_os("WAYLAND_DISPLAY").is_none() {
- return false;
- }
+pub(crate) fn prefers_wayland_portal() -> bool {
+ prefers_wayland_environment(
+ std::env::var_os("WAYLAND_DISPLAY").is_some(),
+ std::env::var_os("DISPLAY").is_some(),
+ std::env::var("XDG_SESSION_TYPE").ok().as_deref(),
+ )
+}
- std::env::var_os("DISPLAY").is_none()
- || std::env::var("XDG_SESSION_TYPE")
- .is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))
+fn prefers_wayland_environment(wayland: bool, x11: bool, session: Option<&str>) -> bool {
+ wayland && (!x11 || session.is_some_and(|session| session.eq_ignore_ascii_case("wayland")))
}
-fn wayland_source_type(source: LinuxCaptureSource) -> ashpd::enumflags2::BitFlags<SourceType> {
+fn wayland_source_type(source: &LinuxCaptureSource) -> ashpd::enumflags2::BitFlags<SourceType> {
match source {
- LinuxCaptureSource::Window => SourceType::Window.into(),
+ LinuxCaptureSource::Window { .. } => SourceType::Window.into(),
LinuxCaptureSource::Display | LinuxCaptureSource::Area => SourceType::Monitor.into(),
}
}
@@ -427,6 +441,7 @@ fn capture_wayland(
let fatal_error = Arc::new(parking_lot::Mutex::new(None));
let sent = Arc::new(AtomicU64::new(0));
let dropped = Arc::new(AtomicU64::new(0));
+ let rate_limited = Arc::new(AtomicU64::new(0));
let started = Instant::now();
let thread_loop = unsafe { pw::thread_loop::ThreadLoopBox::new(Some("cap-wayland"), None) }
@@ -448,6 +463,9 @@ fn capture_wayland(
fatal_error: fatal_error.clone(),
sent: sent.clone(),
dropped: dropped.clone(),
+ rate_limited: rate_limited.clone(),
+ capture_clock: started,
+ cadence_gate: FrameCadenceGate::new(1_000_000_000 / i64::from(input.fps.max(1))),
};
let stream = pw::stream::StreamBox::new(
@@ -524,6 +542,7 @@ fn capture_wayland(
tracing::info!(
sent = sent.load(Ordering::Relaxed),
dropped = dropped.load(Ordering::Relaxed),
+ rate_limited = rate_limited.load(Ordering::Relaxed),
elapsed_ms = started.elapsed().as_millis() as u64,
"Linux Wayland PipeWire capture stopped"
);
@@ -582,12 +601,24 @@ fn process_pipewire_frame(
return Ok(None);
}
+ let captured_at = Instant::now();
+ let ticks = i64::try_from(
+ captured_at
+ .saturating_duration_since(state.capture_clock)
+ .as_nanos(),
+ )
+ .unwrap_or(i64::MAX);
+ if !state.cadence_gate.admit(ticks) {
+ state.rate_limited.fetch_add(1, Ordering::Relaxed);
+ return Ok(None);
+ }
+
let Some(raw_frame) = frame_from_pipewire_data(&mut datas[0], state.format, state.crop_bounds)?
else {
return Ok(Some(StallSendOutcome::StalledAndDropped { waited_ms: 0 }));
};
let frame = prepare_pipewire_frame(raw_frame, &mut state.scaler, state.video_info)?;
- let timestamp = Timestamp::Instant(Instant::now());
+ let timestamp = Timestamp::Instant(captured_at);
Ok(Some(send_with_stall_budget_futures(
&mut state.video_tx,
@@ -1370,6 +1401,7 @@ fn capture_x11(
while !stop_token.is_cancelled() {
let mut frame = match grabber.grab() {
Ok(frame) => frame,
+ Err(error) if input_config.window_id.is_some() => return Err(error),
Err(error) => {
// X11 servers can transiently fail GetImage (e.g. while the
// root geometry changes). Log, back off one interval, retry.
@@ -1425,6 +1457,7 @@ fn capture_x11(
pub(crate) struct X11Grabber {
conn: RustConnection,
root: x11rb::protocol::xproto::Window,
+ window: Option<X11WindowCapture>,
x: i16,
y: i16,
width: u16,
@@ -1435,6 +1468,12 @@ pub(crate) struct X11Grabber {
show_cursor: bool,
}
+struct X11WindowCapture {
+ id: u32,
+ pixmap: u32,
+ border_width: u16,
+}
+
impl X11Grabber {
pub(crate) fn new(config: &X11InputConfig) -> anyhow::Result<Self> {
ffmpeg::init().context("initialize FFmpeg")?;
@@ -1448,22 +1487,38 @@ impl X11Grabber {
.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_id = match config.window_id {
+ Some(id) => {
+ if id == root || id == 0 {
+ bail!("X11 window capture requires a non-root window");
+ }
+ conn.get_window_attributes(id)
+ .context("request X11 window attributes")?
+ .reply()
+ .context("read X11 window attributes")?
+ .visual
+ }
+ None => screen.root_visual,
+ };
- let visual = screen
+ let (depth, 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"))?;
+ .find_map(|depth| {
+ depth
+ .visuals
+ .iter()
+ .find(|visual| visual.visual_id == visual_id)
+ .map(|visual| (depth.depth, visual))
+ })
+ .ok_or_else(|| anyhow!("X11 visual {visual_id} not found"))?;
let bits_per_pixel = setup
.pixmap_formats
.iter()
- .find(|format| format.depth == root_depth)
+ .find(|format| format.depth == depth)
.map(|format| format.bits_per_pixel)
- .ok_or_else(|| anyhow!("X11 pixmap format for depth {root_depth} not found"))?;
+ .ok_or_else(|| anyhow!("X11 pixmap format for depth {depth} not found"))?;
let source_pixel = x11_source_pixel(
setup.image_byte_order == ImageOrder::MSB_FIRST,
@@ -1502,9 +1557,37 @@ impl X11Grabber {
config.fps.max(1),
);
- Ok(Self {
+ let window = if let Some(id) = config.window_id {
+ let version = conn
+ .composite_query_version(0, 4)
+ .context("XComposite is required for isolated window capture")?
+ .reply()
+ .context("query XComposite version")?;
+ if version.major_version == 0 && version.minor_version < 2 {
+ bail!("XComposite 0.2 or later is required for isolated window capture");
+ }
+ conn.change_window_attributes(
+ id,
+ &ChangeWindowAttributesAux::new().event_mask(EventMask::STRUCTURE_NOTIFY),
+ )?
+ .check()?;
+ conn.composite_redirect_window(id, Redirect::AUTOMATIC)
+ .context("redirect X11 window for isolated capture")?
+ .check()
+ .context("enable isolated X11 window capture")?;
+ Some(X11WindowCapture {
+ id,
+ pixmap: 0,
+ border_width: 0,
+ })
+ } else {
+ None
+ };
+
+ let mut grabber = Self {
conn,
root,
+ window,
x,
y,
width,
@@ -1513,18 +1596,99 @@ impl X11Grabber {
output,
scaler: None,
show_cursor,
- })
+ };
+ grabber.refresh_window_pixmap()?;
+ Ok(grabber)
+ }
+
+ fn refresh_window_pixmap(&mut self) -> anyhow::Result<()> {
+ let Some(window) = self.window.as_mut() else {
+ return Ok(());
+ };
+ let mut storage_changed = false;
+ while let Some(event) = self.conn.poll_for_event()? {
+ match event {
+ Event::UnmapNotify(event) if event.window == window.id => {
+ bail!("Selected X11 window was unmapped");
+ }
+ Event::DestroyNotify(event) if event.window == window.id => {
+ bail!("Selected X11 window was closed");
+ }
+ Event::ConfigureNotify(event) if event.window == window.id => {
+ storage_changed = true
+ }
+ Event::ReparentNotify(event) if event.window == window.id => storage_changed = true,
+ Event::MapNotify(event) if event.window == window.id => storage_changed = true,
+ _ => {}
+ }
+ }
+ let attributes = self
+ .conn
+ .get_window_attributes(window.id)?
+ .reply()
+ .context("selected X11 window is no longer available")?;
+ if attributes.map_state != MapState::VIEWABLE {
+ bail!("Selected X11 window is no longer viewable");
+ }
+ let geometry = self
+ .conn
+ .get_geometry(window.id)?
+ .reply()
+ .context("read selected X11 window geometry")?;
+ if geometry.width == 0 || geometry.height == 0 {
+ bail!("Selected X11 window has no content");
+ }
+
+ if storage_changed
+ || window.pixmap == 0
+ || self.width != geometry.width
+ || self.height != geometry.height
+ || window.border_width != geometry.border_width
+ {
+ let pixmap = self.conn.generate_id()?;
+ self.conn
+ .composite_name_window_pixmap(window.id, pixmap)?
+ .check()
+ .context("access isolated X11 window pixels")?;
+ let previous = std::mem::replace(&mut window.pixmap, pixmap);
+ if previous != 0 {
+ self.conn.free_pixmap(previous)?.check()?;
+ }
+ self.width = geometry.width;
+ self.height = geometry.height;
+ window.border_width = geometry.border_width;
+ }
+
+ if self.show_cursor {
+ let position = self
+ .conn
+ .translate_coordinates(window.id, self.root, 0, 0)?
+ .reply()
+ .context("locate selected X11 window cursor")?;
+ self.x = position.dst_x;
+ self.y = position.dst_y;
+ }
+ Ok(())
}
/// Capture one frame of the configured region as a BGRZ video frame.
pub(crate) fn grab(&mut self) -> anyhow::Result<ffmpeg::frame::Video> {
+ self.refresh_window_pixmap()?;
+ let (drawable, x, y) = match &self.window {
+ Some(window) => {
+ let border = i16::try_from(window.border_width)
+ .context("X11 window border exceeds capture limits")?;
+ (window.pixmap, border, border)
+ }
+ None => (self.root, self.x, self.y),
+ };
let reply = self
.conn
.get_image(
ImageFormat::Z_PIXMAP,
- self.root,
- self.x,
- self.y,
+ drawable,
+ x,
+ y,
self.width,
self.height,
u32::MAX,
@@ -1564,29 +1728,12 @@ impl X11Grabber {
.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)?
- };
+ let mut frame = prepare_pipewire_frame(source, &mut self.scaler, self.output)?;
- if self.show_cursor {
- if let Err(error) = self.composite_cursor(&mut frame) {
- tracing::trace!(error = %error, "X11 cursor composite skipped");
- }
+ if self.show_cursor
+ && let Err(error) = self.composite_cursor(&mut frame)
+ {
+ tracing::trace!(error = %error, "X11 cursor composite skipped");
}
Ok(frame)
@@ -1605,21 +1752,26 @@ impl X11Grabber {
.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 {
+ if cursor.width == 0 || cursor.height == 0 {
return Ok(());
}
- if cursor.cursor_image.len() != (cursor_width * cursor_height) as usize {
+ if cursor.cursor_image.len() != usize::from(cursor.width) * usize::from(cursor.height) {
return Ok(());
}
- // 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 frame_width = i32::from(self.width);
- let frame_height = i32::from(self.height);
+ let scale_x = f64::from(frame.width()) / f64::from(self.width);
+ let scale_y = f64::from(frame.height()) / f64::from(self.height);
+ let cursor_width = (f64::from(cursor.width) * scale_x).ceil() as i32;
+ let cursor_height = (f64::from(cursor.height) * scale_y).ceil() as i32;
+ let origin_x = ((f64::from(cursor.x) - f64::from(cursor.xhot) - f64::from(self.x))
+ * scale_x)
+ .floor() as i32;
+ let origin_y = ((f64::from(cursor.y) - f64::from(cursor.yhot) - f64::from(self.y))
+ * scale_y)
+ .floor() as i32;
+
+ let frame_width = frame.width() as i32;
+ let frame_height = frame.height() as i32;
let stride = frame.stride(0);
let buf = frame.data_mut(0);
@@ -1633,7 +1785,11 @@ impl X11Grabber {
if fx < 0 || fx >= frame_width {
continue;
}
- let pixel = cursor.cursor_image[(cy * cursor_width + cx) as usize];
+ let source_x =
+ ((f64::from(cx) / scale_x) as usize).min(usize::from(cursor.width) - 1);
+ let source_y =
+ ((f64::from(cy) / scale_y) as usize).min(usize::from(cursor.height) - 1);
+ let pixel = cursor.cursor_image[source_y * usize::from(cursor.width) + source_x];
let alpha = (pixel >> 24) & 0xff;
if alpha == 0 {
continue;
@@ -1826,7 +1982,17 @@ mod system_audio_tests {
#[cfg(test)]
mod pipewire_frame_tests {
- use super::{FrameScaler, VideoInfo, prepare_pipewire_frame};
+ use super::{FrameScaler, VideoInfo, prefers_wayland_environment, prepare_pipewire_frame};
+
+ #[test]
+ fn active_wayland_sessions_use_the_portal_even_with_xwayland() {
+ assert!(prefers_wayland_environment(true, false, None));
+ assert!(prefers_wayland_environment(true, true, Some("wayland")));
+ assert!(prefers_wayland_environment(true, true, Some("Wayland")));
+ assert!(!prefers_wayland_environment(true, true, Some("x11")));
+ assert!(!prefers_wayland_environment(true, true, None));
+ assert!(!prefers_wayland_environment(false, true, Some("wayland")));
+ }
#[test]
fn matching_pipewire_frames_reuse_owned_pixel_storage_without_a_scaler() {
diff --git a/crates/recording/src/sources/screen_capture/mod.rs b/crates/recording/src/sources/screen_capture/mod.rs
index 2282ccad8..6a61479f0 100644
--- a/crates/recording/src/sources/screen_capture/mod.rs
+++ b/crates/recording/src/sources/screen_capture/mod.rs
@@ -73,10 +73,10 @@ pub enum ScreenCaptureTarget {
}
#[cfg(target_os = "linux")]
-#[derive(Clone, Copy, Debug)]
+#[derive(Clone, Debug)]
pub enum LinuxCaptureSource {
Display,
- Window,
+ Window { id: WindowId },
Area,
}
@@ -84,7 +84,7 @@ pub enum LinuxCaptureSource {
impl LinuxCaptureSource {
pub fn from_target(target: &ScreenCaptureTarget) -> Self {
match target {
- ScreenCaptureTarget::Window { .. } => Self::Window,
+ ScreenCaptureTarget::Window { id } => Self::Window { id: id.clone() },
ScreenCaptureTarget::Area { .. } => Self::Area,
ScreenCaptureTarget::Display { .. } | ScreenCaptureTarget::CameraOnly => Self::Display,
}
@@ -714,6 +714,18 @@ fn list_windows_inner(_include_accessory_panels: bool) -> Vec<(CaptureWindow, Wi
mod tests {
use super::*;
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn linux_window_source_preserves_selected_window_id() {
+ let id: WindowId = "247".parse().unwrap();
+ let target = ScreenCaptureTarget::Window { id: id.clone() };
+ let LinuxCaptureSource::Window { id: selected } = LinuxCaptureSource::from_target(&target)
+ else {
+ panic!("window target must retain a window source");
+ };
+ assert_eq!(selected, id);
+ }
+
#[test]
fn logical_area_to_physical_bounds_scales_each_axis() {
let bounds = LogicalBounds::new(
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 113057691..909f23369 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1411,6 +1411,10 @@ async fn create_segment_pipeline(
base_inputs.capture_target,
screen_capture::ScreenCaptureTarget::CameraOnly
);
+ #[cfg(target_os = "linux")]
+ let custom_cursor_capture = custom_cursor_capture && !screen_capture::prefers_wayland_portal();
+ #[cfg(target_os = "linux")]
+ let mut start_time = start_time;
let (screen, system_audio, cursor_display) = if camera_only {
#[cfg(target_os = "linux")]
@@ -1535,6 +1539,10 @@ async fn create_segment_pipeline(
);
let (capture_source, system_audio) = screen_config.to_sources().await?;
+ #[cfg(target_os = "linux")]
+ {
+ start_time = Timestamps::now();
+ }
let screen = ScreenCaptureMethod::make_studio_mode_pipeline(
capture_source,
@@ -1728,8 +1736,12 @@ async fn create_segment_pipeline(
let cursor_display = cursor_display.ok_or(CreateSegmentPipelineError::NoDisplay)?;
let cursor = spawn_cursor_recorder(
- cursor_crop_bounds,
- cursor_display,
+ crate::cursor::CursorCaptureTarget {
+ crop_bounds: cursor_crop_bounds,
+ display: cursor_display,
+ #[cfg(target_os = "linux")]
+ window: base_inputs.capture_target.window(),
+ },
cursors_dir.to_path_buf(),
prev_cursors,
next_cursors_id,