From c9881a4f22a3b7f3c49f2745cb155bd158f2daca Mon Sep 17 00:00:00 2001 From: Kyzer Date: Mon, 23 Nov 2026 16:24:09 +0000 Subject: [PATCH 1/3] feat: record Wayland pointer clicks for auto zoom PipeWire cursor metadata carries position and appearance, not buttons. Read pointer buttons from the session input nodes and store the clicks with the cursor events auto zoom already reads. --- .../examples/cursor-poll-benchmark.rs | 2 + crates/recording/src/cursor.rs | 243 +++++- crates/recording/src/lib.rs | 2 + .../src/sources/screen_capture/linux.rs | 174 ++++- .../linux/wayland_portal_tests.rs | 61 ++ crates/recording/src/studio_recording.rs | 25 +- crates/recording/src/wayland_pointer.rs | 713 ++++++++++++++++++ 7 files changed, 1192 insertions(+), 28 deletions(-) create mode 100644 crates/recording/src/wayland_pointer.rs diff --git a/crates/recording/examples/cursor-poll-benchmark.rs b/crates/recording/examples/cursor-poll-benchmark.rs index af314a6f197..d34f3091499 100644 --- a/crates/recording/examples/cursor-poll-benchmark.rs +++ b/crates/recording/examples/cursor-poll-benchmark.rs @@ -64,6 +64,8 @@ fn main() -> anyhow::Result<()> { keyboard: None, }, keyboard, + #[cfg(target_os = "linux")] + None, ); std::thread::sleep(Duration::from_secs(seconds)); actor.stop(); diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs index 8ca123d3498..cbb43ff4a13 100644 --- a/crates/recording/src/cursor.rs +++ b/crates/recording/src/cursor.rs @@ -662,6 +662,224 @@ fn input_epoch(start_gate: Option<&RecordingStartGate>, start_time: Timestamps) } } +#[cfg(target_os = "linux")] +fn png_rgba_cursor( + rgba: &[u8], + width: u32, + height: u32, + hotspot_x: f64, + hotspot_y: f64, +) -> Option { + let image = image::RgbaImage::from_raw(width, height, rgba.to_vec())?; + let mut bytes = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image) + .write_to(&mut bytes, image::ImageFormat::Png) + .ok()?; + Some(CursorData { + image: bytes.into_inner(), + hotspot: XY::new(hotspot_x, hotspot_y), + shape: None, + }) +} + +#[cfg(target_os = "linux")] +fn transparent_cursor_data() -> CursorData { + png_rgba_cursor(&[0, 0, 0, 0], 1, 1, 0.0, 0.0).expect("1x1 cursor png") +} + +#[cfg(target_os = "linux")] +#[allow(clippy::too_many_arguments)] +pub(crate) fn spawn_wayland_cursor_recorder( + cursors_dir: PathBuf, + prev_cursors: Cursors, + next_cursor_id: u32, + start_time: Timestamps, + start_gate: Option, + incremental_outputs: IncrementalCaptureOutputs, + wayland_pointer: Option, + readers: Vec, +) -> CursorActor { + use crate::wayland_pointer::{ClickSource, PointerPlace, PointerTrack}; + use std::sync::mpsc::{RecvTimeoutError, TryRecvError}; + use std::time::Duration; + + let stop_token = CancellationToken::new(); + let (tx, rx) = oneshot::channel(); + let (stop_wakeup_tx, stop_wakeup_rx) = std::sync::mpsc::channel(); + let scope = crate::output_pipeline::PipelineBuildScope::current(); + if let Some(scope) = &scope { + scope.register_token(stop_token.clone()); + } + let completion = scope.map(|scope| scope.task_completion()); + let stop_token_child = stop_token.child_token(); + let thread = std::thread::spawn(move || { + let _completion = completion; + let (mut click_source, mut buttons) = ClickSource::open(); + for reader in readers { + click_source.push_reader(reader); + } + let mut track = PointerTrack::new(); + std::fs::create_dir_all(&cursors_dir).unwrap(); + let mut response = CursorActorResponse { + cursors: prev_cursors, + next_cursor_id, + moves: vec![], + clicks: vec![], + keyboard_presses: vec![], + }; + let has_incremental_outputs = incremental_outputs.cursor.is_some(); + let writer = CursorFileWriter::spawn(incremental_outputs.clone()) + .inspect_err(|error| { + tracing::error!("Failed to start cursor writer, writing inline: {error}") + }) + .ok(); + let mut inline_files = IncrementalFiles::new(incremental_outputs.clone()); + let mut flushed = FlushedEvents::default(); + let mut last_flush = Instant::now(); + let flush_interval = Duration::from_secs(CURSOR_FLUSH_INTERVAL_SECS); + let mut last_cursor_image = None; + let mut sprite_id: Option = None; + let mut cursor_id: Option = None; + + loop { + let stop_requested = stop_token_child.is_cancelled() + || matches!( + stop_wakeup_rx.try_recv(), + Ok(()) | Err(TryRecvError::Disconnected) + ); + let changes = if click_source.is_empty() { + if stop_requested { + break; + } + match stop_wakeup_rx.recv_timeout(Duration::from_millis(16)) { + Ok(()) | Err(RecvTimeoutError::Disconnected) => break, + Err(RecvTimeoutError::Timeout) => continue, + } + } else { + click_source.poll( + &mut buttons, + if stop_requested { + Duration::ZERO + } else { + Duration::from_millis(16) + }, + ) + }; + + let Some(epoch) = input_epoch(start_gate.as_ref(), start_time) else { + if stop_requested { + break; + } + continue; + }; + let elapsed = epoch.elapsed().as_secs_f64() * 1000.0; + let place = wayland_pointer + .as_ref() + .map(|feed| feed.place()) + .unwrap_or(PointerPlace::Pending); + let tick = track.tick(place, &changes); + let sprite = wayland_pointer.as_ref().and_then(|feed| feed.sprite()); + let incoming_sprite = sprite.as_ref().map(|sprite| sprite.id); + let shape_changed = cursor_id.is_some() + && incoming_sprite != sprite_id + && matches!(place, PointerPlace::At(_, _)); + if (tick.moved_to.is_some() || tick.clicks > 0 || shape_changed) + && (cursor_id.is_none() || incoming_sprite != sprite_id) + { + let data = sprite + .as_ref() + .and_then(|sprite| { + png_rgba_cursor( + &sprite.rgba, + sprite.width, + sprite.height, + sprite.hotspot_x, + sprite.hotspot_y, + ) + }) + .unwrap_or_else(transparent_cursor_data); + sprite_id = incoming_sprite; + cursor_id = Some(cursor_id_for_image( + data, + &mut response, + &cursors_dir, + writer.as_ref(), + &mut last_cursor_image, + )); + } + let Some(active_cursor) = cursor_id.clone() else { + if stop_requested { + break; + } + continue; + }; + if let Some((x, y)) = tick.moved_to.or(match place { + PointerPlace::At(x, y) if shape_changed => Some((x, y)), + _ => None, + }) { + response.moves.push(CursorMoveEvent { + active_modifiers: vec![], + cursor_id: active_cursor.clone(), + time_ms: elapsed, + x, + y, + }); + } + for change in track.clicks() { + response.clicks.push(CursorClickEvent { + down: change.down, + active_modifiers: vec![], + cursor_num: change.cursor_num, + cursor_id: active_cursor.clone(), + time_ms: elapsed, + }); + } + + if has_incremental_outputs && last_flush.elapsed() >= flush_interval { + let delta = flushed.take(&incremental_outputs, &response); + match &writer { + Some(writer) => writer.flush(delta), + None => inline_files.flush(delta), + } + last_flush = Instant::now(); + } + if stop_requested { + break; + } + } + + tracing::info!("cursor recorder done"); + if let Some(epoch) = input_epoch(start_gate.as_ref(), start_time) + && let Some(confirmation) = + still_shape_confirmation(&response.moves, epoch.elapsed().as_secs_f64() * 1000.0) + { + response.moves.push(confirmation); + } + let delta = has_incremental_outputs.then(|| flushed.take(&incremental_outputs, &response)); + match writer { + Some(writer) => { + let unsaved = writer.finish(delta); + response.cursors.retain(|_, cursor| { + !unsaved.iter().any(|path| path.ends_with(&cursor.file_name)) + }); + } + None => { + if let Some(delta) = delta { + inline_files.flush(delta); + } + } + } + let _ = tx.send(response); + }); + + CursorActor { + stop: Some(stop_token.drop_guard()), + stop_wakeup: Some(stop_wakeup_tx), + thread: Some(thread), + rx: rx.shared(), + } +} + #[tracing::instrument(name = "cursor", skip_all)] #[allow(clippy::too_many_arguments)] pub fn spawn_cursor_recorder( @@ -673,24 +891,23 @@ pub fn spawn_cursor_recorder( start_gate: Option, incremental_outputs: IncrementalCaptureOutputs, keyboard_capture: bool, + #[cfg(target_os = "linux")] wayland_pointer: Option, ) -> CursorActor { #[cfg(target_os = "linux")] if prefers_wayland_portal_cursor() { - let (tx, rx) = oneshot::channel(); - let _ = tx.send(CursorActorResponse { - cursors: prev_cursors, + return spawn_wayland_cursor_recorder( + cursors_dir, + prev_cursors, next_cursor_id, - moves: vec![], - clicks: vec![], - keyboard_presses: vec![], - }); - return CursorActor { - stop: None, - stop_wakeup: None, - thread: None, - rx: rx.shared(), - }; + start_time, + start_gate, + incremental_outputs, + wayland_pointer, + Vec::new(), + ); } + #[cfg(target_os = "linux")] + let _ = wayland_pointer; use device_query::{DeviceQuery, DeviceState}; use std::time::Duration; diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs index 341ed4c47f1..7e4c948509c 100644 --- a/crates/recording/src/lib.rs +++ b/crates/recording/src/lib.rs @@ -22,6 +22,8 @@ pub mod track_heal; pub mod upload_preparation; pub mod upload_resume; pub mod upload_verification; +#[cfg(target_os = "linux")] +pub mod wayland_pointer; #[cfg(target_os = "linux")] pub use capture_pipeline::target_to_display_and_crop; diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index bd767a84f7d..233d52de3b8 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -78,6 +78,15 @@ impl VideoSourceConfig { pub(crate) fn video_info(&self) -> VideoInfo { self.video_info } + + pub(crate) fn wayland_pointer_feed( + &self, + ) -> Option { + match &self.input { + LinuxInputConfig::Wayland(input) => Some(input.pointer.clone()), + LinuxInputConfig::X11(_) => None, + } + } } enum LinuxInputConfig { @@ -103,6 +112,8 @@ struct WaylandInputConfig { fps: u32, crop_bounds: Option, portal_session: WaylandPortalSession, + pointer: crate::wayland_pointer::WaylandPointerFeed, + publish_sprites: bool, } struct WaylandPortalSession { @@ -372,6 +383,7 @@ struct WaylandPortalCapture { stream: PortalStream, fd: OwnedFd, portal_session: WaylandPortalSession, + cursor_embedded: bool, } struct PipewireCaptureState { @@ -391,6 +403,9 @@ struct PipewireCaptureState { /// Reads frames with a GPU-tiled modifier; `None` without a usable EGL. importer: Option, imported: Vec, + pointer: Option, + publish_sprites: bool, + last_sprite_id: Option, } impl PipewireCaptureState { @@ -407,6 +422,7 @@ async fn create_wayland_source_config( ) -> anyhow::Result<(VideoInfo, WaylandInputConfig)> { let portal = open_wayland_portal(&config.config.linux_source, config.config.show_cursor).await?; + let pointer = crate::wayland_pointer::WaylandPointerFeed::default(); if matches!(config.config.linux_source, LinuxCaptureSource::Area) { let displays = Display::list(); let selected = displays @@ -441,6 +457,8 @@ async fn create_wayland_source_config( fps: config.config.fps, crop_bounds, portal_session: portal.portal_session, + pointer, + publish_sprites: !portal.cursor_embedded, }, )) } @@ -452,21 +470,43 @@ async fn open_wayland_portal( let proxy: Screencast<'static> = Screencast::new() .await .context("connect to XDG Desktop Portal ScreenCast")?; + if !show_cursor { + let session = proxy + .create_session() + .await + .context("create XDG Desktop Portal ScreenCast session")?; + let portal_session = WaylandPortalSession::new(session); + // A rejected SelectSources closes that session. The embedded fallback + // has to be a new session, and only a refused mode takes it. + if let Err(error) = proxy + .select_sources( + &portal_session.session, + CursorMode::Metadata, + wayland_source_type(source), + false, + None, + PersistMode::DoNot, + ) + .await + { + tracing::warn!( + %error, + "Wayland cursor metadata was refused, embedding the cursor" + ); + drop(portal_session); + } else { + return finish_wayland_portal(&proxy, portal_session, false).await; + } + } let session = proxy .create_session() .await .context("create XDG Desktop Portal ScreenCast session")?; let portal_session = WaylandPortalSession::new(session); - let cursor_mode = if show_cursor { - CursorMode::Embedded - } else { - CursorMode::Hidden - }; - proxy .select_sources( &portal_session.session, - cursor_mode, + CursorMode::Embedded, wayland_source_type(source), false, None, @@ -474,7 +514,14 @@ async fn open_wayland_portal( ) .await .context("select Wayland screen capture source")?; + finish_wayland_portal(&proxy, portal_session, true).await +} +async fn finish_wayland_portal( + proxy: &Screencast<'static>, + portal_session: WaylandPortalSession, + cursor_embedded: bool, +) -> anyhow::Result { let response = proxy .start(&portal_session.session, None) .await @@ -495,6 +542,7 @@ async fn open_wayland_portal( stream, fd, portal_session, + cursor_embedded, }) } @@ -569,6 +617,8 @@ fn capture_wayland( fps, crop_bounds, portal_session: _portal_session, + pointer, + publish_sprites, } = input; capture_pipewire_node( video_info, @@ -577,6 +627,8 @@ fn capture_wayland( node_id, fps, crop_bounds, + pointer: Some(pointer), + publish_sprites, }, video_tx, stop_token, @@ -591,6 +643,8 @@ struct PipewireNodeInput { node_id: u32, fps: u32, crop_bounds: Option, + pointer: Option, + publish_sprites: bool, } fn capture_pipewire_node( @@ -643,6 +697,9 @@ fn capture_pipewire_node( cadence_gate: FrameCadenceGate::new(1_000_000_000 / i64::from(input.fps.max(1))), importer, imported: Vec::new(), + pointer: input.pointer.clone(), + publish_sprites: input.publish_sprites, + last_sprite_id: None, }; let stream = pw::stream::StreamBox::new( @@ -708,6 +765,7 @@ fn capture_pipewire_node( pipewire_dmabuf_format_param(input.fps)?, ]; param_bytes.extend(imported_params); + param_bytes.push(pipewire_cursor_meta_param()?); let mut params = param_bytes .iter() .map(|bytes| { @@ -919,6 +977,105 @@ impl Drop for DmaBufMapping { } } +fn pipewire_cursor_meta_param() -> anyhow::Result> { + // SPA_PARAM_META_type is 1 and SPA_PARAM_META_size is 2. libspa does not + // export that enum. The bitmap budget is a 384px square, which is enough + // for the cursor images compositors put in this meta. + let header = std::mem::size_of::() + + std::mem::size_of::(); + let cursor_meta_bytes = i32::try_from(header).unwrap_or(i32::MAX) + 384 * 384 * 4; + let object = spa::pod::object!( + spa::utils::SpaTypes::ObjectParamMeta, + spa::param::ParamType::Meta, + spa::pod::Property::new( + 1, + spa::pod::Value::Id(spa::utils::Id( + ::META_TYPE, + )), + ), + spa::pod::Property::new(2, spa::pod::Value::Int(cursor_meta_bytes)), + ); + serialize_pod(object, "PipeWire cursor metadata parameter") +} + +fn publish_pipewire_cursor(buffer: &pw::buffer::Buffer, state: &mut PipewireCaptureState) { + let Some(feed) = state.pointer.clone() else { + return; + }; + let Some(cursor) = buffer.find_meta::() else { + return; + }; + let size = state.format.size(); + if size.width == 0 || size.height == 0 { + return; + } + let Ok((crop_x, crop_y, crop_width, crop_height)) = pipewire_crop( + usize::try_from(size.width).unwrap_or(0), + usize::try_from(size.height).unwrap_or(0), + state.crop_bounds, + ) else { + return; + }; + if state.publish_sprites + && cursor.id() != 0 + && state.last_sprite_id != Some(cursor.id()) + && let Some(sprite) = sprite_from_cursor(cursor) + { + state.last_sprite_id = Some(cursor.id()); + feed.publish_sprite(Arc::new(sprite)); + } + feed.publish_position(crate::wayland_pointer::cursor_meta_update( + cursor.id(), + cursor.flags(), + cursor.position().x, + cursor.position().y, + crate::wayland_pointer::CaptureRect { + x: i32::try_from(crop_x).unwrap_or(i32::MAX), + y: i32::try_from(crop_y).unwrap_or(i32::MAX), + width: u32::try_from(crop_width).unwrap_or(0), + height: u32::try_from(crop_height).unwrap_or(0), + }, + )); +} + +fn sprite_from_cursor( + cursor: &spa::buffer::meta::MetaCursor, +) -> Option { + use crate::wayland_pointer::{CursorPixelFormat, WaylandCursorSprite, cursor_rgba}; + use spa::param::video::VideoFormat; + + let bitmap = cursor.bitmap()?; + let format = match bitmap.format() { + VideoFormat::RGBA => CursorPixelFormat::Rgba, + VideoFormat::BGRA => CursorPixelFormat::Bgra, + VideoFormat::ARGB => CursorPixelFormat::Argb, + VideoFormat::ABGR => CursorPixelFormat::Abgr, + _ => return None, + }; + let size = bitmap.size(); + let rgba = cursor_rgba( + format, + size.width, + size.height, + bitmap.stride(), + bitmap.bitmap_data()?, + )?; + let width = f64::from(size.width); + let height = f64::from(size.height); + if width == 0.0 || height == 0.0 { + return None; + } + let hotspot = cursor.hotspot(); + Some(WaylandCursorSprite { + id: cursor.id(), + width: size.width, + height: size.height, + hotspot_x: f64::from(hotspot.x) / width, + hotspot_y: f64::from(hotspot.y) / height, + rgba, + }) +} + fn serialize_pod(object: spa::pod::Object, what: &str) -> anyhow::Result> { Ok(spa::pod::serialize::PodSerializer::serialize( std::io::Cursor::new(Vec::new()), @@ -936,6 +1093,7 @@ fn process_pipewire_frame( let Some(mut buffer) = stream.dequeue_buffer() else { return Ok(None); }; + publish_pipewire_cursor(&buffer, state); let datas = buffer.datas_mut(); if datas.is_empty() { return Ok(None); @@ -3815,6 +3973,8 @@ mod pipewire_frame_tests { node_id, fps: 30, crop_bounds: None, + pointer: None, + publish_sprites: false, }, video_tx, stop, diff --git a/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs b/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs index c93e41ba0ff..279ad47a0dd 100644 --- a/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs +++ b/crates/recording/src/sources/screen_capture/linux/wayland_portal_tests.rs @@ -289,10 +289,12 @@ async fn probe(case: &str) -> anyhow::Result<()> { ); } assert_eq!(capture.stream.pipe_wire_node_id(), 42); + assert!(!capture.cursor_embedded); let WaylandPortalCapture { stream, fd, portal_session, + cursor_embedded: _, } = capture; drop(stream); drop(fd); @@ -383,3 +385,62 @@ fn portal_sessions_end_with_capture() { ); } } + +#[tokio::test] +#[ignore = "needs headless sway, pipewire, and xdg-desktop-portal-wlr"] +async fn headless_sway_cursor_metadata_reaches_the_feed() { + pipewire::init(); + let portal = open_wayland_portal(&LinuxCaptureSource::Display, false) + .await + .expect("open the sway screencast portal"); + assert!(!portal.cursor_embedded); + let feed = crate::wayland_pointer::WaylandPointerFeed::default(); + let feed_thread = feed.clone(); + let (video_tx, mut video_rx) = futures::channel::mpsc::channel(8); + let stop = tokio_util::sync::CancellationToken::new(); + let stop_thread = stop.clone(); + let (health_tx, _health_rx) = tokio::sync::mpsc::channel(8); + let node_id = portal.stream.pipe_wire_node_id(); + let fd = portal.fd; + let capture = std::thread::spawn(move || { + super::capture_pipewire_node( + cap_media_info::VideoInfo::from_raw_ffmpeg(cap_media_info::Pixel::BGRA, 1280, 720, 30), + super::PipewireNodeInput { + fd, + node_id, + fps: 30, + crop_bounds: None, + pointer: Some(feed_thread), + publish_sprites: true, + }, + video_tx, + stop_thread, + health_tx, + ) + }); + let mut place = None; + for _ in 0..40 { + let _ = Command::new("wlrctl") + .args(["pointer", "move", "640", "360"]) + .status(); + tokio::time::sleep(Duration::from_millis(100)).await; + while video_rx.try_next().ok().flatten().is_some() {} + if let crate::wayland_pointer::PointerPlace::At(x, y) = feed.place() { + place = Some((x, y)); + break; + } + } + let metadata = !portal.cursor_embedded; + stop.cancel(); + let capture = capture.join().expect("capture thread"); + drop(portal.portal_session); + assert!(capture.is_ok(), "capture failed: {capture:?}"); + if let Some((x, y)) = place { + assert!( + (0.3..0.7).contains(&x) && (0.3..0.7).contains(&y), + "cursor {x},{y} was not near the virtual pointer" + ); + } else if metadata { + panic!("PipeWire cursor metadata never published a position"); + } +} diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 676a181178b..89e2cf4f2e9 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -3712,7 +3712,11 @@ async fn create_segment_pipeline( ); let audio_only = base_inputs.capture_target.is_audio_only(); #[cfg(target_os = "linux")] - let custom_cursor_capture = custom_cursor_capture && !screen_capture::prefers_wayland_portal(); + let record_wayland_pointer = screen_capture::prefers_wayland_portal(); + #[cfg(not(target_os = "linux"))] + let record_wayland_pointer = false; + #[cfg(target_os = "linux")] + let mut wayland_pointer = None; #[cfg(target_os = "linux")] let mut start_time = start_time; @@ -3870,6 +3874,7 @@ async fn create_segment_pipeline( let (capture_source, system_audio) = screen_config.to_sources().await?; #[cfg(target_os = "linux")] { + wayland_pointer = capture_source.wayland_pointer_feed(); start_time = Timestamps::now(); } @@ -4060,7 +4065,7 @@ async fn create_segment_pipeline( let cursor = if camera_only || audio_only { None } else { - (custom_cursor_capture || keyboard_capture) + (custom_cursor_capture || keyboard_capture || record_wayland_pointer) .then(move || { let cursor_crop_bounds = base_inputs .capture_target @@ -4069,11 +4074,12 @@ async fn create_segment_pipeline( let cursor_output_path = dir.join("cursor.json"); let keyboard_output_path = dir.join(cap_project::KEYBOARD_EVENTS_FILE_NAME); - let incremental_output = if fragmented && custom_cursor_capture { - Some(cursor_output_path.clone()) - } else { - None - }; + let incremental_output = + if fragmented && (custom_cursor_capture || record_wayland_pointer) { + Some(cursor_output_path.clone()) + } else { + None + }; let keyboard_incremental_output = if fragmented && keyboard_capture { Some(keyboard_output_path.clone()) } else { @@ -4104,10 +4110,13 @@ async fn create_segment_pipeline( keyboard: keyboard_incremental_output, }, keyboard_capture, + #[cfg(target_os = "linux")] + wayland_pointer, ); Ok::<_, CreateSegmentPipelineError>(CursorPipeline { - output_path: custom_cursor_capture.then_some(cursor_output_path), + output_path: (custom_cursor_capture || record_wayland_pointer) + .then_some(cursor_output_path), keyboard_output_path: keyboard_capture.then_some(keyboard_output_path), actor: cursor, }) diff --git a/crates/recording/src/wayland_pointer.rs b/crates/recording/src/wayland_pointer.rs new file mode 100644 index 00000000000..2b3a405b685 --- /dev/null +++ b/crates/recording/src/wayland_pointer.rs @@ -0,0 +1,713 @@ +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::sync::Arc; +use std::time::Duration; + +use parking_lot::Mutex; + +pub const EV_KEY: u16 = 1; +pub const BTN_LEFT: u16 = 0x110; +const BTN_TASK: u16 = 0x117; +const KEY_BITS: u32 = 96; +// spa_meta_cursor.flags bit 0. This spa header does not name it. +const CURSOR_HIDDEN: u32 = 1; + +const fn ioc(dir: u32, ty: u32, nr: u32, size: u32) -> u64 { + ((dir << 30) | (size << 16) | (ty << 8) | nr) as u64 +} + +const fn eviocgbit(ev: u32, len: u32) -> u64 { + ioc(2, b'E' as u32, 0x20 + ev, len) +} + +const fn eviocgkey(len: u32) -> u64 { + ioc(2, b'E' as u32, 0x18, len) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PointerButtonChange { + pub cursor_num: u8, + pub down: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PointerButtons { + down: [bool; 8], +} + +impl PointerButtons { + pub fn observe(&mut self, type_: u16, code: u16, value: i32) -> Option { + if type_ != EV_KEY || !(0..=1).contains(&value) { + return None; + } + let index = code.checked_sub(BTN_LEFT)?; + if index > BTN_TASK - BTN_LEFT { + return None; + } + let index = usize::from(index); + let down = value == 1; + if self.down[index] == down { + return None; + } + self.down[index] = down; + Some(PointerButtonChange { + cursor_num: (index as u8) + 1, + down, + }) + } + + pub fn changes_from_event_bytes(&mut self, bytes: &[u8]) -> Vec { + let stride = std::mem::size_of::(); + let mut changes = Vec::new(); + for chunk in bytes.chunks_exact(stride) { + let event = + unsafe { std::ptr::read_unaligned(chunk.as_ptr().cast::()) }; + if let Some(change) = self.observe(event.type_, event.code, event.value) { + changes.push(change); + } + } + changes + } + + fn absorb_bits(&mut self, bits: &[u8]) { + for (index, down) in self.down.iter_mut().enumerate() { + let code = BTN_LEFT + u16::try_from(index).unwrap_or(u16::MAX); + if bit_is_set(bits, code) { + *down = true; + } + } + } +} + +fn bit_is_set(bits: &[u8], code: u16) -> bool { + let index = usize::from(code); + bits.get(index / 8) + .is_some_and(|byte| byte & (1 << (index % 8)) != 0) +} + +fn has_left_button(bits: &[u8]) -> bool { + bit_is_set(bits, BTN_LEFT) +} + +fn is_event_node(name: &str) -> bool { + let Some(index) = name.strip_prefix("event") else { + return false; + }; + !index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CaptureRect { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum CursorMetaUpdate { + Unchanged, + Hidden, + At(Option<(f64, f64)>), +} + +pub fn cursor_meta_update( + id: u32, + flags: u32, + x: i32, + y: i32, + frame: CaptureRect, +) -> CursorMetaUpdate { + if id == 0 { + return CursorMetaUpdate::Unchanged; + } + if flags & CURSOR_HIDDEN != 0 { + return CursorMetaUpdate::Hidden; + } + CursorMetaUpdate::At(normalize_pointer(x, y, frame)) +} + +pub fn normalize_pointer(x: i32, y: i32, frame: CaptureRect) -> Option<(f64, f64)> { + if frame.width == 0 || frame.height == 0 { + return None; + } + let dx = x.checked_sub(frame.x)?; + let dy = y.checked_sub(frame.y)?; + if dx < 0 || dy < 0 { + return None; + } + let dx = dx as u32; + let dy = dy as u32; + if dx >= frame.width || dy >= frame.height { + return None; + } + Some(( + f64::from(dx) / f64::from(frame.width), + f64::from(dy) / f64::from(frame.height), + )) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CursorPixelFormat { + Rgba, + Bgra, + Argb, + Abgr, +} + +pub fn cursor_rgba( + format: CursorPixelFormat, + width: u32, + height: u32, + stride: i32, + data: &[u8], +) -> Option> { + if width == 0 || height == 0 || stride < 0 { + return None; + } + let row = usize::try_from(stride).ok()?; + let minimum = usize::try_from(width).ok()?.checked_mul(4)?; + if row < minimum { + return None; + } + let rows = usize::try_from(height).ok()?; + let needed = row.checked_mul(rows)?; + if data.len() < needed { + return None; + } + let mut rgba = Vec::with_capacity(minimum.checked_mul(rows)?); + for y in 0..rows { + let start = y * row; + for pixel in data[start..start + minimum].chunks_exact(4) { + let (r, g, b, a) = match format { + CursorPixelFormat::Rgba => (pixel[0], pixel[1], pixel[2], pixel[3]), + CursorPixelFormat::Bgra => (pixel[2], pixel[1], pixel[0], pixel[3]), + CursorPixelFormat::Argb => (pixel[1], pixel[2], pixel[3], pixel[0]), + CursorPixelFormat::Abgr => (pixel[3], pixel[2], pixel[1], pixel[0]), + }; + rgba.extend_from_slice(&[r, g, b, a]); + } + } + Some(rgba) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct WaylandCursorSprite { + pub id: u32, + pub width: u32, + pub height: u32, + pub hotspot_x: f64, + pub hotspot_y: f64, + pub rgba: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PointerPlace { + Pending, + Hidden, + Outside, + At(f64, f64), +} + +#[derive(Clone, Default)] +struct FeedState { + place: PointerPlace, + sprite: Option>, +} + +impl Default for PointerPlace { + fn default() -> Self { + Self::Pending + } +} + +#[derive(Clone, Default)] +pub struct WaylandPointerFeed { + state: Arc>, +} + +impl WaylandPointerFeed { + pub fn publish_position(&self, update: CursorMetaUpdate) { + let mut state = self.state.lock(); + state.place = match update { + CursorMetaUpdate::Unchanged => return, + CursorMetaUpdate::Hidden => PointerPlace::Hidden, + CursorMetaUpdate::At(None) => PointerPlace::Outside, + CursorMetaUpdate::At(Some((x, y))) => PointerPlace::At(x, y), + }; + } + + pub fn publish_sprite(&self, sprite: Arc) { + self.state.lock().sprite = Some(sprite); + } + + pub fn place(&self) -> PointerPlace { + self.state.lock().place + } + + pub fn sprite(&self) -> Option> { + self.state.lock().sprite.clone() + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PointerTick { + pub moved_to: Option<(f64, f64)>, + pub clicks: usize, +} + +#[derive(Debug)] +pub struct PointerTrack { + last: Option<(f64, f64)>, + kept: Vec, +} + +impl PointerTrack { + pub fn new() -> Self { + Self { + last: None, + kept: Vec::new(), + } + } + + pub fn tick(&mut self, place: PointerPlace, changes: &[PointerButtonChange]) -> PointerTick { + self.kept.clear(); + let moved_to = match place { + PointerPlace::At(x, y) => { + self.kept.extend_from_slice(changes); + (self.last != Some((x, y))).then_some((x, y)) + } + PointerPlace::Pending => { + self.kept.extend_from_slice(changes); + None + } + PointerPlace::Hidden | PointerPlace::Outside => None, + }; + if let PointerPlace::At(x, y) = place { + self.last = Some((x, y)); + } + PointerTick { + moved_to, + clicks: self.kept.len(), + } + } + + pub fn clicks(&self) -> &[PointerButtonChange] { + &self.kept + } +} + +impl Default for PointerTrack { + fn default() -> Self { + Self::new() + } +} + +pub struct ClickSource { + fds: Vec, +} + +impl ClickSource { + // Logind puts an ACL on the active session's seat input nodes, so the + // desktop user can read them without the input group. Key codes stay out + // of the recording: only BTN_LEFT through BTN_TASK become clicks. + pub fn open() -> (Self, PointerButtons) { + let mut buttons = PointerButtons::default(); + let mut nodes = Vec::new(); + if let Ok(entries) = std::fs::read_dir("/dev/input") { + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + if is_event_node(name) { + nodes.push(entry.path()); + } + } + } + nodes.sort(); + let mut fds = Vec::new(); + for path in nodes { + let Some(fd) = open_readonly(&path) else { + continue; + }; + let Some(bits) = read_key_bits(fd.as_raw_fd(), eviocgbit(u32::from(EV_KEY), KEY_BITS)) + else { + continue; + }; + if !has_left_button(&bits) { + continue; + } + if let Some(held) = read_key_bits(fd.as_raw_fd(), eviocgkey(KEY_BITS)) { + buttons.absorb_bits(&held); + } + fds.push(fd); + } + if fds.is_empty() { + tracing::info!("Wayland click source has no pointer the session can read"); + } else { + tracing::info!(pointers = fds.len(), "Wayland click source opened"); + } + (Self { fds }, buttons) + } + + pub fn is_empty(&self) -> bool { + self.fds.is_empty() + } + + pub(crate) fn push_reader(&mut self, fd: OwnedFd) { + self.fds.push(fd); + } + + pub fn poll( + &mut self, + buttons: &mut PointerButtons, + timeout: Duration, + ) -> Vec { + if self.fds.is_empty() { + return Vec::new(); + } + let mut polls: Vec = self + .fds + .iter() + .map(|fd| libc::pollfd { + fd: fd.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }) + .collect(); + let millis = i32::try_from(timeout.as_millis()).unwrap_or(i32::MAX); + let ready = unsafe { libc::poll(polls.as_mut_ptr(), polls.len() as libc::nfds_t, millis) }; + if ready <= 0 { + return Vec::new(); + } + let mut changes = Vec::new(); + let mut dead = Vec::new(); + for (index, poll) in polls.iter().enumerate() { + if poll.revents & (libc::POLLIN | libc::POLLERR | libc::POLLHUP) == 0 { + continue; + } + if poll.revents & libc::POLLIN == 0 { + dead.push(index); + continue; + } + match read_events(poll.fd) { + Ok(bytes) => changes.extend(buttons.changes_from_event_bytes(&bytes)), + Err(ReadEvents::Retry) => {} + Err(ReadEvents::Closed) => dead.push(index), + } + } + for index in dead.into_iter().rev() { + self.fds.swap_remove(index); + } + changes + } +} + +enum ReadEvents { + Retry, + Closed, +} + +fn open_readonly(path: &std::path::Path) -> Option { + let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).ok()?; + let fd = unsafe { + libc::open( + path.as_ptr(), + libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) + }; + if fd < 0 { + return None; + } + Some(unsafe { OwnedFd::from_raw_fd(fd) }) +} + +fn read_key_bits(fd: std::os::fd::RawFd, request: u64) -> Option<[u8; KEY_BITS as usize]> { + let mut bits = [0u8; KEY_BITS as usize]; + let result = unsafe { libc::ioctl(fd, request as libc::c_ulong, bits.as_mut_ptr()) }; + (result >= 0).then_some(bits) +} + +fn read_events(fd: std::os::fd::RawFd) -> Result, ReadEvents> { + let mut buffer = vec![0u8; std::mem::size_of::() * 16]; + let read = unsafe { libc::read(fd, buffer.as_mut_ptr().cast(), buffer.len()) }; + if read < 0 { + let error = std::io::Error::last_os_error(); + return Err(match error.raw_os_error() { + Some(libc::EAGAIN | libc::EINTR) => ReadEvents::Retry, + _ => ReadEvents::Closed, + }); + } + if read == 0 { + return Err(ReadEvents::Closed); + } + let read = usize::try_from(read).map_err(|_| ReadEvents::Closed)?; + buffer.truncate(read); + Ok(buffer) +} + +#[cfg(test)] +mod tests { + use super::*; + use cap_project::CursorClickEvent; + use cap_project::auto_zoom::generate_auto_zoom_segments; + + fn press(buttons: &mut PointerButtons) -> PointerButtonChange { + buttons.observe(EV_KEY, BTN_LEFT, 1).unwrap() + } + + fn click(change: &PointerButtonChange, time_ms: f64) -> CursorClickEvent { + CursorClickEvent { + active_modifiers: Vec::new(), + cursor_num: change.cursor_num, + cursor_id: "0".to_string(), + time_ms, + down: change.down, + } + } + + fn event_bytes(type_: u16, code: u16, value: i32) -> Vec { + let event = libc::input_event { + time: libc::timeval { + tv_sec: 0, + tv_usec: 0, + }, + type_, + code, + value, + }; + let bytes = unsafe { + std::slice::from_raw_parts( + (&event as *const libc::input_event).cast::(), + std::mem::size_of::(), + ) + }; + bytes.to_vec() + } + + #[test] + fn cursor_mode_metadata_is_the_portal_bit() { + use ashpd::desktop::screencast::CursorMode; + assert_eq!(CursorMode::Hidden as u32, 1); + assert_eq!(CursorMode::Embedded as u32, 2); + assert_eq!(CursorMode::Metadata as u32, 4); + } + + #[test] + fn evdev_queries_match_linux_input_h() { + assert_eq!(eviocgbit(u32::from(EV_KEY), KEY_BITS), 2_153_792_801); + assert_eq!(eviocgkey(KEY_BITS), 2_153_792_792); + } + + #[test] + fn left_press_and_release_are_primary_clicks_and_keys_are_not() { + let mut buttons = PointerButtons::default(); + let press = press(&mut buttons); + assert_eq!( + press, + PointerButtonChange { + cursor_num: 1, + down: true + } + ); + assert!(buttons.observe(EV_KEY, BTN_LEFT, 2).is_none()); + assert!(buttons.observe(EV_KEY, 30, 1).is_none()); + assert!(buttons.observe(EV_KEY, 0x14a, 1).is_none()); + let release = buttons.observe(EV_KEY, BTN_LEFT, 0).unwrap(); + assert!(!release.down); + assert!(buttons.observe(EV_KEY, BTN_LEFT, 0).is_none()); + } + + #[test] + fn event_bytes_drive_the_same_decoder_the_device_reader_uses() { + let mut buttons = PointerButtons::default(); + let mut bytes = event_bytes(EV_KEY, 30, 1); + bytes.extend(event_bytes(EV_KEY, BTN_LEFT, 1)); + bytes.push(0); + let changes = buttons.changes_from_event_bytes(&bytes); + assert_eq!(changes.len(), 1); + assert!(changes[0].down); + let clicks = vec![click(&changes[0], 5_000.0)]; + assert!(!generate_auto_zoom_segments(&clicks, 20.0, 2.0).is_empty()); + } + + #[test] + fn held_bits_seed_the_left_button_without_emitting_a_press() { + let mut bits = [0u8; KEY_BITS as usize]; + assert!(!has_left_button(&bits)); + bits[usize::from(BTN_LEFT) / 8] |= 1 << (usize::from(BTN_LEFT) % 8); + assert!(has_left_button(&bits)); + let mut buttons = PointerButtons::default(); + buttons.absorb_bits(&bits); + assert!(buttons.observe(EV_KEY, BTN_LEFT, 1).is_none()); + assert!(!buttons.observe(EV_KEY, BTN_LEFT, 0).unwrap().down); + } + + #[test] + fn pointer_outside_the_capture_is_not_a_position() { + let frame = CaptureRect { + x: 10, + y: 20, + width: 100, + height: 50, + }; + assert_eq!(normalize_pointer(10, 20, frame), Some((0.0, 0.0))); + assert_eq!(normalize_pointer(60, 45, frame), Some((0.5, 0.5))); + assert_eq!(normalize_pointer(9, 20, frame), None); + assert_eq!(normalize_pointer(110, 20, frame), None); + assert_eq!( + cursor_meta_update(0, 0, 60, 45, frame), + CursorMetaUpdate::Unchanged + ); + assert_eq!( + cursor_meta_update(4, CURSOR_HIDDEN, 60, 45, frame), + CursorMetaUpdate::Hidden + ); + assert_eq!( + cursor_meta_update(4, 0, 60, 45, frame), + CursorMetaUpdate::At(Some((0.5, 0.5))) + ); + assert_eq!( + cursor_meta_update(4, 0, 9, 20, frame), + CursorMetaUpdate::At(None) + ); + } + + #[test] + fn scripted_metadata_and_clicks_fill_auto_zoom_and_skip_other_monitors() { + let frame = CaptureRect { + x: 0, + y: 0, + width: 1000, + height: 500, + }; + let feed = WaylandPointerFeed::default(); + let mut buttons = PointerButtons::default(); + let mut track = PointerTrack::new(); + let early = press(&mut buttons); + let before = track.tick(feed.place(), &[early]); + assert_eq!(before.moved_to, None); + assert_eq!(before.clicks, 1); + feed.publish_position(cursor_meta_update(3, 0, 250, 100, frame)); + let release = buttons.observe(EV_KEY, BTN_LEFT, 0).unwrap(); + let inside = track.tick(feed.place(), &[release]); + assert_eq!(inside.moved_to, Some((0.25, 0.2))); + assert_eq!(track.clicks()[0].cursor_num, 1); + feed.publish_position(cursor_meta_update(3, 0, -5, 10, frame)); + let outside_press = buttons.observe(EV_KEY, BTN_LEFT, 1).unwrap(); + let outside = track.tick(feed.place(), &[outside_press]); + assert_eq!(outside.clicks, 0); + let clicks = vec![click(&early, 5_000.0)]; + assert_eq!(generate_auto_zoom_segments(&clicks, 20.0, 2.0).len(), 1); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("cursor.json"); + let events = cap_project::CursorEvents { + clicks, + moves: vec![cap_project::CursorMoveEvent { + active_modifiers: Vec::new(), + cursor_id: "0".to_string(), + time_ms: 5_000.0, + x: 0.25, + y: 0.2, + }], + }; + std::fs::write(&path, serde_json::to_vec_pretty(&events).unwrap()).unwrap(); + let loaded = cap_project::CursorEvents::load_from_file(&path).unwrap(); + assert_eq!(loaded.clicks[0].cursor_num, 1); + assert_eq!( + generate_auto_zoom_segments(&loaded.clicks, 20.0, 2.0).len(), + 1 + ); + } + + #[test] + fn cursor_pixels_become_straight_rgba() { + let rgba = cursor_rgba(CursorPixelFormat::Rgba, 1, 1, 4, &[1, 2, 3, 4]).unwrap(); + assert_eq!(rgba, [1, 2, 3, 4]); + let bgra = cursor_rgba(CursorPixelFormat::Bgra, 1, 1, 4, &[1, 2, 3, 4]).unwrap(); + assert_eq!(bgra, [3, 2, 1, 4]); + let argb = cursor_rgba(CursorPixelFormat::Argb, 1, 1, 4, &[4, 1, 2, 3]).unwrap(); + assert_eq!(argb, [1, 2, 3, 4]); + assert!(cursor_rgba(CursorPixelFormat::Rgba, 1, 1, -4, &[1, 2, 3, 4]).is_none()); + assert!(cursor_rgba(CursorPixelFormat::Rgba, 2, 1, 4, &[0, 0, 0, 0]).is_none()); + } + + fn record(feed: &WaylandPointerFeed, bytes: &[u8]) -> crate::cursor::CursorActorResponse { + let mut ends = [0; 2]; + assert_eq!( + unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) }, + 0 + ); + let read = unsafe { OwnedFd::from_raw_fd(ends[0]) }; + let write = unsafe { OwnedFd::from_raw_fd(ends[1]) }; + let wrote = unsafe { libc::write(write.as_raw_fd(), bytes.as_ptr().cast(), bytes.len()) }; + assert_eq!(wrote, isize::try_from(bytes.len()).unwrap()); + let dir = tempfile::tempdir().unwrap(); + let mut actor = crate::cursor::spawn_wayland_cursor_recorder( + dir.path().join("cursors"), + Default::default(), + 0, + cap_timestamp::Timestamps::now(), + None, + crate::cursor::IncrementalCaptureOutputs { + cursor: None, + keyboard: None, + }, + Some(feed.clone()), + vec![read], + ); + actor.stop(); + drop(write); + futures::executor::block_on(actor.rx).expect("cursor recorder response") + } + + #[test] + fn piped_clicks_reach_cursor_json_and_auto_zoom() { + let frame = CaptureRect { + x: 0, + y: 0, + width: 1000, + height: 500, + }; + let inside = WaylandPointerFeed::default(); + inside.publish_position(cursor_meta_update(7, 0, 250, 100, frame)); + let mut bytes = event_bytes(EV_KEY, 30, 1); + bytes.extend(event_bytes(EV_KEY, BTN_LEFT, 1)); + let response = record(&inside, &bytes); + assert!(response.keyboard_presses.is_empty()); + assert!( + response + .clicks + .iter() + .any(|click| click.cursor_num == 1 && click.down) + ); + assert!( + response + .moves + .iter() + .any(|move_| move_.x == 0.25 && move_.y == 0.2) + ); + let outside = WaylandPointerFeed::default(); + outside.publish_position(cursor_meta_update(8, 0, -20, 10, frame)); + let dropped = record(&outside, &event_bytes(EV_KEY, BTN_LEFT + 1, 1)); + assert!(dropped.clicks.is_empty()); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("cursor.json"); + let events = cap_project::CursorEvents { + clicks: response.clicks, + moves: response.moves, + }; + std::fs::write(&path, serde_json::to_vec_pretty(&events).unwrap()).unwrap(); + let loaded = cap_project::CursorEvents::load_from_file(&path).unwrap(); + assert!(!generate_auto_zoom_segments(&loaded.clicks, 20.0, 2.0).is_empty()); + } + + #[test] + fn event_node_names_are_event_plus_digits() { + assert!(is_event_node("event0")); + assert!(is_event_node("event12")); + assert!(!is_event_node("event")); + assert!(!is_event_node("mouse0")); + assert!(!is_event_node("event1a")); + } +} From a33db8844868fd0b9eabca3d7ca0ea0f12d372c0 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:45:22 +0000 Subject: [PATCH 2/3] fix: keep the Wayland pointer when the click source is missing An empty /dev/input wait used to skip the PipeWire cursor sample, so a recording with custom cursor capture lost the pointer as well as the clicks. Process that sample every tick. A hidden or out-of-frame pointer now writes one off-frame move, the same kind of coordinate the X11 window recorder stores, and the next visible position brings it back. Pointer nodes that appear after the recording starts are opened on inotify or on a one-second rescan, without reopening nodes that are already held. --- crates/recording/src/cursor.rs | 36 +- crates/recording/src/wayland_pointer.rs | 422 +++++++++++++++++++----- 2 files changed, 363 insertions(+), 95 deletions(-) diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs index cbb43ff4a13..8838acf2a3a 100644 --- a/crates/recording/src/cursor.rs +++ b/crates/recording/src/cursor.rs @@ -698,9 +698,10 @@ pub(crate) fn spawn_wayland_cursor_recorder( incremental_outputs: IncrementalCaptureOutputs, wayland_pointer: Option, readers: Vec, + session_devices: bool, ) -> CursorActor { - use crate::wayland_pointer::{ClickSource, PointerPlace, PointerTrack}; - use std::sync::mpsc::{RecvTimeoutError, TryRecvError}; + use crate::wayland_pointer::{ClickSource, PointerButtons, PointerPlace, PointerTrack}; + use std::sync::mpsc::TryRecvError; use std::time::Duration; let stop_token = CancellationToken::new(); @@ -714,7 +715,11 @@ pub(crate) fn spawn_wayland_cursor_recorder( let stop_token_child = stop_token.child_token(); let thread = std::thread::spawn(move || { let _completion = completion; - let (mut click_source, mut buttons) = ClickSource::open(); + let (mut click_source, mut buttons) = if session_devices { + ClickSource::open() + } else { + (ClickSource::detached(), PointerButtons::default()) + }; for reader in readers { click_source.push_reader(reader); } @@ -747,24 +752,14 @@ pub(crate) fn spawn_wayland_cursor_recorder( stop_wakeup_rx.try_recv(), Ok(()) | Err(TryRecvError::Disconnected) ); - let changes = if click_source.is_empty() { + let changes = click_source.poll( + &mut buttons, if stop_requested { - break; - } - match stop_wakeup_rx.recv_timeout(Duration::from_millis(16)) { - Ok(()) | Err(RecvTimeoutError::Disconnected) => break, - Err(RecvTimeoutError::Timeout) => continue, - } - } else { - click_source.poll( - &mut buttons, - if stop_requested { - Duration::ZERO - } else { - Duration::from_millis(16) - }, - ) - }; + Duration::ZERO + } else { + Duration::from_millis(16) + }, + ); let Some(epoch) = input_epoch(start_gate.as_ref(), start_time) else { if stop_requested { @@ -904,6 +899,7 @@ pub fn spawn_cursor_recorder( incremental_outputs, wayland_pointer, Vec::new(), + true, ); } #[cfg(target_os = "linux")] diff --git a/crates/recording/src/wayland_pointer.rs b/crates/recording/src/wayland_pointer.rs index 2b3a405b685..42c53969587 100644 --- a/crates/recording/src/wayland_pointer.rs +++ b/crates/recording/src/wayland_pointer.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; use parking_lot::Mutex; @@ -10,6 +12,11 @@ const BTN_TASK: u16 = 0x117; const KEY_BITS: u32 = 96; // spa_meta_cursor.flags bit 0. This spa header does not name it. const CURSOR_HIDDEN: u32 = 1; +const DEVICE_SCAN_INTERVAL: Duration = Duration::from_secs(1); +// Playback clips a coordinate outside the captured frame to the card edge. +// Hidden metadata has no off-frame position, so one full frame outside stands +// in for it and the pointer comes back on the next finite position. +const CONCEALED_POSITION: (f64, f64) = (-1.0, -1.0); const fn ioc(dir: u32, ty: u32, nr: u32, size: u32) -> u64 { ((dir << 30) | (size << 16) | (ty << 8) | nr) as u64 @@ -107,7 +114,7 @@ pub struct CaptureRect { pub enum CursorMetaUpdate { Unchanged, Hidden, - At(Option<(f64, f64)>), + At(f64, f64), } pub fn cursor_meta_update( @@ -123,27 +130,28 @@ pub fn cursor_meta_update( if flags & CURSOR_HIDDEN != 0 { return CursorMetaUpdate::Hidden; } - CursorMetaUpdate::At(normalize_pointer(x, y, frame)) + let Some((x, y)) = pointer_ratio(x, y, frame) else { + return CursorMetaUpdate::Unchanged; + }; + CursorMetaUpdate::At(x, y) } -pub fn normalize_pointer(x: i32, y: i32, frame: CaptureRect) -> Option<(f64, f64)> { +fn pointer_ratio(x: i32, y: i32, frame: CaptureRect) -> Option<(f64, f64)> { if frame.width == 0 || frame.height == 0 { return None; } - let dx = x.checked_sub(frame.x)?; - let dy = y.checked_sub(frame.y)?; - if dx < 0 || dy < 0 { - return None; - } - let dx = dx as u32; - let dy = dy as u32; - if dx >= frame.width || dy >= frame.height { - return None; - } - Some(( - f64::from(dx) / f64::from(frame.width), - f64::from(dy) / f64::from(frame.height), - )) + let x = (f64::from(x) - f64::from(frame.x)) / f64::from(frame.width); + let y = (f64::from(y) - f64::from(frame.y)) / f64::from(frame.height); + (x.is_finite() && y.is_finite()).then_some((x, y)) +} + +fn inside_capture(x: f64, y: f64) -> bool { + (0.0..1.0).contains(&x) && (0.0..1.0).contains(&y) +} + +pub fn normalize_pointer(x: i32, y: i32, frame: CaptureRect) -> Option<(f64, f64)> { + let (x, y) = pointer_ratio(x, y, frame)?; + inside_capture(x, y).then_some((x, y)) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -204,7 +212,7 @@ pub struct WaylandCursorSprite { pub enum PointerPlace { Pending, Hidden, - Outside, + Outside(f64, f64), At(f64, f64), } @@ -231,8 +239,8 @@ impl WaylandPointerFeed { state.place = match update { CursorMetaUpdate::Unchanged => return, CursorMetaUpdate::Hidden => PointerPlace::Hidden, - CursorMetaUpdate::At(None) => PointerPlace::Outside, - CursorMetaUpdate::At(Some((x, y))) => PointerPlace::At(x, y), + CursorMetaUpdate::At(x, y) if inside_capture(x, y) => PointerPlace::At(x, y), + CursorMetaUpdate::At(x, y) => PointerPlace::Outside(x, y), }; } @@ -271,19 +279,21 @@ impl PointerTrack { pub fn tick(&mut self, place: PointerPlace, changes: &[PointerButtonChange]) -> PointerTick { self.kept.clear(); - let moved_to = match place { + let position = match place { PointerPlace::At(x, y) => { self.kept.extend_from_slice(changes); - (self.last != Some((x, y))).then_some((x, y)) + Some((x, y)) } + PointerPlace::Outside(x, y) => Some((x, y)), + PointerPlace::Hidden => Some(CONCEALED_POSITION), PointerPlace::Pending => { self.kept.extend_from_slice(changes); None } - PointerPlace::Hidden | PointerPlace::Outside => None, }; - if let PointerPlace::At(x, y) = place { - self.last = Some((x, y)); + let moved_to = position.filter(|position| self.last != Some(*position)); + if let Some(position) = position { + self.last = Some(position); } PointerTick { moved_to, @@ -302,8 +312,18 @@ impl Default for PointerTrack { } } +struct OpenNode { + path: Option, + fd: OwnedFd, +} + pub struct ClickSource { - fds: Vec, + nodes: Vec, + open_paths: HashSet, + directory: Option, + last_scan: Instant, + pending_rescan: bool, + inotify: Option, } impl ClickSource { @@ -311,51 +331,93 @@ impl ClickSource { // desktop user can read them without the input group. Key codes stay out // of the recording: only BTN_LEFT through BTN_TASK become clicks. pub fn open() -> (Self, PointerButtons) { + let directory = PathBuf::from("/dev/input"); + let mut source = Self::detached(); + source.directory = Some(directory.clone()); + source.inotify = arm_inotify(&directory); let mut buttons = PointerButtons::default(); - let mut nodes = Vec::new(); - if let Ok(entries) = std::fs::read_dir("/dev/input") { - for entry in entries.flatten() { - let name = entry.file_name(); - let Some(name) = name.to_str() else { - continue; - }; - if is_event_node(name) { - nodes.push(entry.path()); - } - } - } - nodes.sort(); - let mut fds = Vec::new(); - for path in nodes { - let Some(fd) = open_readonly(&path) else { - continue; - }; - let Some(bits) = read_key_bits(fd.as_raw_fd(), eviocgbit(u32::from(EV_KEY), KEY_BITS)) - else { - continue; - }; - if !has_left_button(&bits) { - continue; - } - if let Some(held) = read_key_bits(fd.as_raw_fd(), eviocgkey(KEY_BITS)) { - buttons.absorb_bits(&held); - } - fds.push(fd); - } - if fds.is_empty() { + source.rescan(&mut buttons); + if source.nodes.is_empty() { tracing::info!("Wayland click source has no pointer the session can read"); } else { - tracing::info!(pointers = fds.len(), "Wayland click source opened"); + tracing::info!(pointers = source.nodes.len(), "Wayland click source opened"); } - (Self { fds }, buttons) + (source, buttons) } - pub fn is_empty(&self) -> bool { - self.fds.is_empty() + pub(crate) fn detached() -> Self { + Self { + nodes: Vec::new(), + open_paths: HashSet::new(), + directory: None, + last_scan: Instant::now(), + pending_rescan: false, + inotify: None, + } } pub(crate) fn push_reader(&mut self, fd: OwnedFd) { - self.fds.push(fd); + self.nodes.push(OpenNode { path: None, fd }); + } + + fn scan_due(&self) -> bool { + self.directory.is_some() + && (self.pending_rescan || self.last_scan.elapsed() >= DEVICE_SCAN_INTERVAL) + } + + // Readdir at most once a second, and again when a node disconnects or + // inotify reports a change. The 16 ms poll must not scan /dev/input. + fn rescan(&mut self, buttons: &mut PointerButtons) { + self.pending_rescan = false; + self.last_scan = Instant::now(); + let Some(directory) = self.directory.clone() else { + return; + }; + for path in event_node_paths(&directory) { + if self.open_paths.contains(&path) { + continue; + } + self.try_open(&path, buttons); + } + } + + fn try_open(&mut self, path: &Path, buttons: &mut PointerButtons) -> bool { + if self.open_paths.contains(path) { + return false; + } + let Some(fd) = open_readonly(path) else { + return false; + }; + self.adopt(path.to_path_buf(), fd, buttons, None) + } + + fn adopt( + &mut self, + path: PathBuf, + fd: OwnedFd, + buttons: &mut PointerButtons, + bits: Option<[u8; KEY_BITS as usize]>, + ) -> bool { + if self.open_paths.contains(&path) { + return false; + } + let Some(bits) = + bits.or_else(|| read_key_bits(fd.as_raw_fd(), eviocgbit(u32::from(EV_KEY), KEY_BITS))) + else { + return false; + }; + if !has_left_button(&bits) { + return false; + } + if let Some(held) = read_key_bits(fd.as_raw_fd(), eviocgkey(KEY_BITS)) { + buttons.absorb_bits(&held); + } + self.open_paths.insert(path.clone()); + self.nodes.push(OpenNode { + path: Some(path), + fd, + }); + true } pub fn poll( @@ -363,18 +425,31 @@ impl ClickSource { buttons: &mut PointerButtons, timeout: Duration, ) -> Vec { - if self.fds.is_empty() { + if self.scan_due() { + self.rescan(buttons); + } + let device_count = self.nodes.len(); + if device_count == 0 && self.inotify.is_none() { + if !timeout.is_zero() { + std::thread::sleep(timeout); + } return Vec::new(); } - let mut polls: Vec = self - .fds - .iter() - .map(|fd| libc::pollfd { - fd: fd.as_raw_fd(), + let mut polls = Vec::with_capacity(device_count + usize::from(self.inotify.is_some())); + for node in &self.nodes { + polls.push(libc::pollfd { + fd: node.fd.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }); + } + if let Some(watch) = &self.inotify { + polls.push(libc::pollfd { + fd: watch.as_raw_fd(), events: libc::POLLIN, revents: 0, - }) - .collect(); + }); + } let millis = i32::try_from(timeout.as_millis()).unwrap_or(i32::MAX); let ready = unsafe { libc::poll(polls.as_mut_ptr(), polls.len() as libc::nfds_t, millis) }; if ready <= 0 { @@ -382,7 +457,7 @@ impl ClickSource { } let mut changes = Vec::new(); let mut dead = Vec::new(); - for (index, poll) in polls.iter().enumerate() { + for (index, poll) in polls.iter().enumerate().take(device_count) { if poll.revents & (libc::POLLIN | libc::POLLERR | libc::POLLHUP) == 0 { continue; } @@ -396,11 +471,76 @@ impl ClickSource { Err(ReadEvents::Closed) => dead.push(index), } } + if self.inotify.is_some() + && let Some(watch) = polls.last() + { + if watch.revents & libc::POLLIN != 0 { + self.drain_inotify(); + self.pending_rescan = true; + } + if watch.revents & (libc::POLLERR | libc::POLLHUP | libc::POLLNVAL) != 0 { + self.inotify = None; + } + } for index in dead.into_iter().rev() { - self.fds.swap_remove(index); + if let Some(path) = self.nodes.swap_remove(index).path { + self.open_paths.remove(&path); + } + self.pending_rescan = true; + } + if self.pending_rescan { + self.rescan(buttons); } changes } + + fn drain_inotify(&self) { + let Some(watch) = &self.inotify else { + return; + }; + let mut buffer = [0u8; 4096]; + loop { + let read = + unsafe { libc::read(watch.as_raw_fd(), buffer.as_mut_ptr().cast(), buffer.len()) }; + if read <= 0 { + break; + } + } + } +} + +fn event_node_paths(directory: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(directory) else { + return Vec::new(); + }; + let mut paths = Vec::new(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + if is_event_node(name) { + paths.push(entry.path()); + } + } + paths.sort(); + paths +} + +fn arm_inotify(directory: &Path) -> Option { + let fd = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) }; + if fd < 0 { + return None; + } + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + let path = std::ffi::CString::new(directory.as_os_str().as_encoded_bytes()).ok()?; + let mask = libc::IN_CREATE + | libc::IN_MOVED_TO + | libc::IN_DELETE + | libc::IN_MOVED_FROM + | libc::IN_ATTRIB; + let watch = unsafe { libc::inotify_add_watch(fd.as_raw_fd(), path.as_ptr(), mask) }; + (watch >= 0).then_some(fd) } enum ReadEvents { @@ -565,11 +705,11 @@ mod tests { ); assert_eq!( cursor_meta_update(4, 0, 60, 45, frame), - CursorMetaUpdate::At(Some((0.5, 0.5))) + CursorMetaUpdate::At(0.5, 0.5) ); assert_eq!( cursor_meta_update(4, 0, 9, 20, frame), - CursorMetaUpdate::At(None) + CursorMetaUpdate::At(-1.0 / 100.0, 0.0) ); } @@ -597,6 +737,7 @@ mod tests { let outside_press = buttons.observe(EV_KEY, BTN_LEFT, 1).unwrap(); let outside = track.tick(feed.place(), &[outside_press]); assert_eq!(outside.clicks, 0); + assert_eq!(outside.moved_to, Some((-5.0 / 1000.0, 10.0 / 500.0))); let clicks = vec![click(&early, 5_000.0)]; assert_eq!(generate_auto_zoom_segments(&clicks, 20.0, 2.0).len(), 1); let dir = tempfile::tempdir().unwrap(); @@ -655,6 +796,7 @@ mod tests { }, Some(feed.clone()), vec![read], + true, ); actor.stop(); drop(write); @@ -691,6 +833,7 @@ mod tests { outside.publish_position(cursor_meta_update(8, 0, -20, 10, frame)); let dropped = record(&outside, &event_bytes(EV_KEY, BTN_LEFT + 1, 1)); assert!(dropped.clicks.is_empty()); + assert!(dropped.moves.iter().any(|move_| move_.x < 0.0)); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("cursor.json"); let events = cap_project::CursorEvents { @@ -702,6 +845,135 @@ mod tests { assert!(!generate_auto_zoom_segments(&loaded.clicks, 20.0, 2.0).is_empty()); } + #[test] + fn the_pointer_leaves_the_card_and_comes_back() { + let mut track = PointerTrack::new(); + assert_eq!( + track.tick(PointerPlace::At(0.25, 0.2), &[]).moved_to, + Some((0.25, 0.2)) + ); + let outside = track.tick(PointerPlace::Outside(-0.1, 0.2), &[]); + assert_eq!(outside.moved_to, Some((-0.1, 0.2))); + assert_eq!(outside.clicks, 0); + assert_eq!( + track.tick(PointerPlace::Outside(-0.1, 0.2), &[]).moved_to, + None + ); + assert_eq!( + track.tick(PointerPlace::At(0.25, 0.2), &[]).moved_to, + Some((0.25, 0.2)) + ); + + assert_eq!( + track.tick(PointerPlace::Hidden, &[]).moved_to, + Some(CONCEALED_POSITION) + ); + assert_eq!(track.tick(PointerPlace::Hidden, &[]).moved_to, None); + assert_eq!( + track.tick(PointerPlace::At(0.25, 0.2), &[]).moved_to, + Some((0.25, 0.2)) + ); + } + + #[test] + fn pipewire_cursor_moves_are_written_without_a_click_source() { + let frame = CaptureRect { + x: 0, + y: 0, + width: 1000, + height: 500, + }; + let feed = WaylandPointerFeed::default(); + feed.publish_position(cursor_meta_update(7, 0, 250, 100, frame)); + let dir = tempfile::tempdir().unwrap(); + let mut actor = crate::cursor::spawn_wayland_cursor_recorder( + dir.path().join("cursors"), + Default::default(), + 0, + cap_timestamp::Timestamps::now(), + None, + crate::cursor::IncrementalCaptureOutputs { + cursor: None, + keyboard: None, + }, + Some(feed), + Vec::new(), + false, + ); + actor.stop(); + let response = futures::executor::block_on(actor.rx).expect("cursor recorder response"); + assert!(response.clicks.is_empty()); + assert!( + response + .moves + .iter() + .any(|move_| move_.x == 0.25 && move_.y == 0.2) + ); + } + + fn left_button_bits() -> [u8; KEY_BITS as usize] { + let mut bits = [0u8; KEY_BITS as usize]; + let code = usize::from(BTN_LEFT); + bits[code / 8] |= 1 << (code % 8); + bits + } + + fn pipe_pair() -> (OwnedFd, OwnedFd) { + let mut ends = [0; 2]; + assert_eq!( + unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) }, + 0 + ); + unsafe { (OwnedFd::from_raw_fd(ends[0]), OwnedFd::from_raw_fd(ends[1])) } + } + + #[test] + fn a_reconnected_pointer_is_adopted_once() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("mouse0"), b"").unwrap(); + std::fs::write(dir.path().join("event"), b"").unwrap(); + std::fs::File::create(dir.path().join("event0")).unwrap(); + let mut source = ClickSource::detached(); + source.directory = Some(dir.path().to_path_buf()); + let mut buttons = PointerButtons::default(); + source.rescan(&mut buttons); + assert!(source.nodes.is_empty()); + + let event1 = dir.path().join("event1"); + let (reader, writer) = pipe_pair(); + assert!(source.adopt( + event1.clone(), + reader, + &mut buttons, + Some(left_button_bits()) + )); + let (duplicate, _keep) = pipe_pair(); + assert!(!source.adopt( + event1.clone(), + duplicate, + &mut buttons, + Some(left_button_bits()) + )); + assert_eq!(source.nodes.len(), 1); + assert!(source.open_paths.contains(&event1)); + + drop(writer); + assert!(source.poll(&mut buttons, Duration::ZERO).is_empty()); + assert!(source.nodes.is_empty()); + assert!(!source.open_paths.contains(&event1)); + + let (reader, _writer) = pipe_pair(); + assert!(source.adopt( + event1.clone(), + reader, + &mut buttons, + Some(left_button_bits()) + )); + assert_eq!(source.nodes.len(), 1); + let paths = event_node_paths(dir.path()); + assert_eq!(paths, vec![dir.path().join("event0")]); + } + #[test] fn event_node_names_are_event_plus_digits() { assert!(is_event_node("event0")); From 7d4c668421ffc8dc4904594cd408af9fea8ef3e4 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:16:35 +0800 Subject: [PATCH 3/3] chore: retrigger CI after Windows late-mic export-timing flake