diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs index 864d4653720..6bd18dc0ffc 100644 --- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs +++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs @@ -184,6 +184,7 @@ pub struct SegmentedVideoEncoder { segment_tx: SegmentSender, segment_duration: Duration, + segment_keyframes: Option, disk_space_callback: Option, @@ -194,6 +195,41 @@ pub struct SegmentedVideoEncoder { flush_failure: Option, } +const SPARSE_SEGMENT_SCAN_INTERVAL: Duration = Duration::from_secs(1); + +struct SegmentKeyframes { + segment_duration: Duration, + encoder_interval: u32, + last: Option, + frames_since: u32, +} + +impl SegmentKeyframes { + fn new(segment_duration: Duration, video_config: &VideoInfo) -> Self { + Self { + segment_duration, + encoder_interval: crate::video::h264::keyframe_interval_frames(video_config) as u32, + last: None, + frames_since: 0, + } + } + + fn must_force(&mut self, timestamp: Duration) -> bool { + let Some(last) = self.last else { + self.last = Some(timestamp); + return false; + }; + self.frames_since += 1; + let encoder_due = self.frames_since >= self.encoder_interval; + let overdue = timestamp.saturating_sub(last) >= self.segment_duration; + if encoder_due || overdue { + self.last = Some(timestamp); + self.frames_since = 0; + } + overdue && !encoder_due + } +} + struct SegmentMux { base_path: PathBuf, output: format::context::Output, @@ -203,6 +239,7 @@ struct SegmentMux { completed_segments: Vec, frames_since_segment_scan: u32, + last_segment_scan: std::time::Instant, codec_info: CodecInfo, @@ -232,8 +269,11 @@ impl MuxTarget for SegmentMux { self.try_notify_init_segment(); self.frames_since_segment_scan += 1; - if self.frames_since_segment_scan >= 10 { + if self.frames_since_segment_scan >= 10 + || self.last_segment_scan.elapsed() >= SPARSE_SEGMENT_SCAN_INTERVAL + { self.frames_since_segment_scan = 0; + self.last_segment_scan = std::time::Instant::now(); self.flush_pending_segments(); } } @@ -507,6 +547,7 @@ impl SegmentedVideoEncoder { current_index: 1, completed_segments: Vec::new(), frames_since_segment_scan: 0, + last_segment_scan: std::time::Instant::now(), codec_info, segment_tx: SegmentSender::default(), init_notified: false, @@ -521,6 +562,8 @@ impl SegmentedVideoEncoder { mux: MuxSink::Direct(mux), segment_tx, segment_duration: config.segment_duration, + segment_keyframes: (!timed_fragments) + .then(|| SegmentKeyframes::new(config.segment_duration, &video_config)), disk_space_callback: None, runtime_fallback: RUNTIME_SOFTWARE_FALLBACK, codec_failures: CodecFailureHistory::default(), @@ -585,9 +628,18 @@ impl SegmentedVideoEncoder { pub fn queue_frame( &mut self, - frame: frame::Video, + mut frame: frame::Video, timestamp: Duration, ) -> Result<(), QueueFrameError> { + // Keyframes cut the segments, and the encoder places them by frame + // count. A source that only delivers on change falls behind that + // count, so a keyframe is forced once a segment's worth of time has + // passed since the last one. + if let Some(keyframes) = &mut self.segment_keyframes + && keyframes.must_force(timestamp) + { + frame.set_kind(ffmpeg::picture::Type::I); + } // Encode with the frame's real capture-derived timestamp. The encoder // anchors pts at the first frame, so capture gaps (static content, // stream restarts, dropped frames) stay in the timeline instead of @@ -2001,6 +2053,91 @@ mod tests { assert!(crate::remux::probe_video_can_decode(&remuxed_path).unwrap_or(false)); } + fn sparse_segment_durations(timestamps: &[Duration]) -> Vec { + ffmpeg::init().ok(); + let temp = tempfile::tempdir().unwrap(); + let base_path = temp.path().to_path_buf(); + let mut video_info = test_video_info(); + video_info.pixel_format = cap_media_info::Pixel::BGRA; + let mut encoder = SegmentedVideoEncoder::init( + base_path.clone(), + video_info, + SegmentedVideoEncoderConfig::default(), + ) + .unwrap(); + for ×tamp in timestamps { + let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 320, 240); + frame.data_mut(0).fill(128); + encoder.queue_frame(frame, timestamp).unwrap(); + } + encoder.finish().unwrap(); + std::fs::read_to_string(base_path.join("media_0.m3u8")) + .unwrap() + .lines() + .filter_map(|line| line.strip_prefix("#EXTINF:")) + .map(|line| line.trim_end_matches(',').parse().unwrap()) + .collect() + } + + #[test] + fn a_static_source_refreshed_once_per_segment_still_cuts_every_segment() { + let refresh = Duration::from_secs(2) + Duration::from_secs(1) / 30; + let timestamps: Vec = (0..6).map(|index| refresh * index).collect(); + let durations = sparse_segment_durations(×tamps); + assert!(durations.len() >= 5, "segments: {durations:?}"); + for duration in &durations[..durations.len() - 1] { + assert!((2.0..2.1).contains(duration), "segments: {durations:?}"); + } + } + + #[test] + fn a_static_source_publishes_each_segment_without_waiting_for_ten_frames() { + ffmpeg::init().ok(); + let temp = tempfile::tempdir().unwrap(); + let mut encoder = SegmentedVideoEncoder::init( + temp.path().to_path_buf(), + test_video_info(), + SegmentedVideoEncoderConfig::default(), + ) + .unwrap(); + let (tx, rx) = mpsc::channel(); + encoder.set_segment_callback(tx); + let refresh = Duration::from_secs(2) + Duration::from_secs(1) / 30; + for index in 0..4 { + if index == 3 { + std::thread::sleep(SPARSE_SEGMENT_SCAN_INTERVAL); + } + encoder + .queue_frame(create_test_frame(320, 240), refresh * index) + .unwrap(); + } + let published = rx.try_iter().filter(|event| !event.is_init).count(); + assert!(published >= 1, "no segment published after four frames"); + encoder.finish().unwrap(); + } + + #[test] + fn a_sparse_source_cuts_segments_by_time_instead_of_frame_count() { + let timestamps: Vec = (0..80) + .map(|index| Duration::from_millis(125) * index) + .collect(); + let durations = sparse_segment_durations(×tamps); + assert!(durations.len() >= 4, "segments: {durations:?}"); + for duration in &durations[..durations.len() - 1] { + assert!((2.0..2.2).contains(duration), "segments: {durations:?}"); + } + } + + #[test] + fn a_full_rate_source_leaves_keyframes_to_the_encoder() { + let mut keyframes = SegmentKeyframes::new(Duration::from_secs(2), &test_video_info()); + for index in 0..600u32 { + let jitter = Duration::from_millis(u64::from(index % 3)); + let timestamp = Duration::from_secs(1) * index / 30 + jitter; + assert!(!keyframes.must_force(timestamp), "forced frame {index}"); + } + } + fn recorded_track(base_path: &Path) -> PathBuf { let mut segment_paths: Vec = std::fs::read_dir(base_path) .unwrap() diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs index 6f10c31278f..abac856a176 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -1284,6 +1284,7 @@ impl H264Encoder { super::convert_or_scale(&frame, converted, converter) .map_err(QueueFrameError::Converter)?; converted.set_pts(pts); + converted.set_kind(frame.kind()); converted as &frame::Video } else { &frame @@ -1655,6 +1656,15 @@ fn export_encoder_priority_override( pub const DEFAULT_KEYFRAME_INTERVAL_SECS: u32 = 2; +pub(crate) fn keyframe_interval_frames(config: &VideoInfo) -> i32 { + let denominator = config.frame_rate.denominator(); + let frames_per_sec = config.frame_rate.numerator() as f64 + / if denominator == 0 { 1 } else { denominator } as f64; + (DEFAULT_KEYFRAME_INTERVAL_SECS as f64 * frames_per_sec) + .round() + .max(1.0) as i32 +} + fn get_codec_and_options( config: &VideoInfo, preset: H264Preset, @@ -1662,14 +1672,7 @@ fn get_codec_and_options( is_export: bool, crf: Option, ) -> Vec<(Codec, Dictionary<'static>)> { - let keyframe_interval_secs = DEFAULT_KEYFRAME_INTERVAL_SECS; - let denominator = config.frame_rate.denominator(); - let frames_per_sec = config.frame_rate.numerator() as f64 - / if denominator == 0 { 1 } else { denominator } as f64; - let keyframe_interval = (keyframe_interval_secs as f64 * frames_per_sec) - .round() - .max(1.0) as i32; - let keyframe_interval_str = keyframe_interval.to_string(); + let keyframe_interval_str = keyframe_interval_frames(config).to_string(); let encoder_priority = if crf.is_some() { &["libx264"] as &[&str] diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml index 84d8000acf2..1270bb2c3e5 100644 --- a/crates/recording/Cargo.toml +++ b/crates/recording/Cargo.toml @@ -108,7 +108,7 @@ ashpd = { version = "0.11.0", default-features = false, features = ["tokio"] } glow = "0.16" khronos-egl = { version = "6", features = ["dynamic"] } pipewire = "0.10.0" -x11rb = { version = "0.13.2", features = ["composite", "shm", "xfixes"] } +x11rb = { version = "0.13.2", features = ["composite", "damage", "shm", "xfixes"] } [dev-dependencies] tempfile = "3.20.0" diff --git a/crates/recording/examples/x11-idle-recording-benchmark.rs b/crates/recording/examples/x11-idle-recording-benchmark.rs new file mode 100644 index 00000000000..88bebea4120 --- /dev/null +++ b/crates/recording/examples/x11-idle-recording-benchmark.rs @@ -0,0 +1,345 @@ +#[cfg(not(target_os = "linux"))] +fn main() { + eprintln!("x11-idle-recording-benchmark: skipped (not Linux)"); +} + +#[cfg(target_os = "linux")] +fn main() -> anyhow::Result<()> { + linux::run() +} + +#[cfg(target_os = "linux")] +mod linux { + use std::{ + path::{Path, PathBuf}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread, + time::{Duration, Instant}, + }; + + use anyhow::{Context, bail}; + use cap_recording::{screen_capture::ScreenCaptureTarget, studio_recording}; + use clap::{Parser, ValueEnum}; + use scap_targets::Display; + use x11rb::{ + connection::Connection, + protocol::xproto::{ + ChangeGCAux, ConnectionExt as _, CreateGCAux, CreateWindowAux, Rectangle, WindowClass, + }, + rust_connection::RustConnection, + wrapper::ConnectionExt as _, + }; + + #[derive(Clone, Copy, PartialEq, Eq, ValueEnum)] + enum Scene { + Static, + Typing, + Video, + } + + impl Scene { + fn name(self) -> &'static str { + match self { + Scene::Static => "static", + Scene::Typing => "typing", + Scene::Video => "video", + } + } + } + + #[derive(Parser)] + #[command(about = "Process CPU and encoded frames of a Studio recording of an X11 display")] + struct Args { + #[arg(long, default_value_t = 20)] + seconds: u64, + #[arg(long, default_value_t = 30)] + fps: u32, + #[arg(long = "scene", value_enum)] + scenes: Vec, + #[arg(long)] + json: bool, + #[arg(long)] + keep: Option, + } + + struct Measurement { + wall: Duration, + cpu: Duration, + frames: usize, + bytes: u64, + seconds: f64, + } + + pub fn run() -> anyhow::Result<()> { + let mut args = Args::parse(); + if args.scenes.is_empty() { + args.scenes = vec![Scene::Static, Scene::Typing, Scene::Video]; + } + let size = Display::primary() + .physical_size() + .context("primary display has no size")?; + let runtime = tokio::runtime::Runtime::new()?; + + if !args.json { + println!( + "# Studio recording of a {}x{} X11 display at {} fps for {} s\n", + size.width(), + size.height(), + args.fps, + args.seconds + ); + println!( + "| scene | process CPU, % of one core | frames encoded | video seconds | MB written |" + ); + println!("|---|---|---|---|---|"); + } + + for scene in args.scenes.clone() { + let result = runtime.block_on(record(scene, &args))?; + let cpu_percent = result.cpu.as_secs_f64() * 100.0 / result.wall.as_secs_f64(); + if args.json { + println!( + "{}", + serde_json::json!({ + "scene": scene.name(), + "width": size.width(), + "height": size.height(), + "fps": args.fps, + "wallSeconds": result.wall.as_secs_f64(), + "cpuMs": result.cpu.as_secs_f64() * 1000.0, + "cpuPercent": cpu_percent, + "frames": result.frames, + "videoSeconds": result.seconds, + "bytes": result.bytes, + }) + ); + } else { + println!( + "| {} | {:.1} | {} | {:.2} | {:.2} |", + scene.name(), + cpu_percent, + result.frames, + result.seconds, + result.bytes as f64 / 1_000_000.0 + ); + } + } + Ok(()) + } + + async fn record(scene: Scene, args: &Args) -> anyhow::Result { + let (conn, screen) = x11rb::connect(None).context("connect to the X11 display")?; + let root = conn.setup().roots[screen].root; + let width = conn.setup().roots[screen].width_in_pixels; + let height = conn.setup().roots[screen].height_in_pixels; + let window = conn.generate_id()?; + conn.create_window( + x11rb::COPY_DEPTH_FROM_PARENT, + window, + root, + 0, + 0, + width, + height, + 0, + WindowClass::INPUT_OUTPUT, + x11rb::COPY_FROM_PARENT, + &CreateWindowAux::new() + .override_redirect(1) + .background_pixel(0x1e1e1e), + )?; + conn.map_window(window)?; + fill_background(&conn, window, width, height)?; + + let directory = tempfile::tempdir()?; + let project = match &args.keep { + Some(keep) => keep.join(format!("{}.cap", scene.name())), + None => directory.path().join("benchmark.cap"), + }; + let handle = studio_recording::Actor::builder( + project.clone(), + ScreenCaptureTarget::Display { + id: Display::primary().id(), + }, + ) + .with_system_audio(false) + .with_keyboard_capture(false) + .with_max_fps(args.fps) + .build() + .await?; + + let stop = Arc::new(AtomicBool::new(false)); + let painter = { + let stop = Arc::clone(&stop); + thread::spawn(move || paint(scene, conn, window, width, height, &stop)) + }; + + let cpu_start = process_cpu(); + let started = Instant::now(); + tokio::time::sleep(Duration::from_secs(args.seconds)).await; + stop.store(true, Ordering::Relaxed); + painter + .join() + .map_err(|_| anyhow::anyhow!("the painter thread panicked"))??; + handle.stop().await?; + let wall = started.elapsed(); + let cpu = process_cpu().saturating_sub(cpu_start); + + let (frames, bytes, seconds) = + count_frames(&project.join("content/segments/segment-0/display"))?; + Ok(Measurement { + wall, + cpu, + frames, + bytes, + seconds, + }) + } + + fn rect(x: u16, y: u16, width: u16, height: u16) -> Rectangle { + Rectangle { + x: x as i16, + y: y as i16, + width, + height, + } + } + + fn fill_background( + conn: &RustConnection, + window: u32, + width: u16, + height: u16, + ) -> anyhow::Result<()> { + let gc = conn.generate_id()?; + conn.create_gc(gc, window, &CreateGCAux::new().foreground(0x1e1e1e))?; + conn.poly_fill_rectangle(window, gc, &[rect(0, 0, width, height)])?; + conn.free_gc(gc)?; + conn.sync()?; + Ok(()) + } + + fn paint( + scene: Scene, + conn: RustConnection, + window: u32, + width: u16, + height: u16, + stop: &AtomicBool, + ) -> anyhow::Result<()> { + let gc = conn.generate_id()?; + conn.create_gc(gc, window, &CreateGCAux::new())?; + let interval = match scene { + Scene::Static => Duration::from_millis(100), + Scene::Typing => Duration::from_millis(125), + Scene::Video => Duration::from_secs(1) / 30, + }; + let columns = u32::from(width.saturating_sub(200) / 12).max(1); + let rows = u32::from(height.saturating_sub(200) / 24).max(1); + let video_width = width.min(1280); + let video_height = height.min(720); + let mut step = 0u32; + let mut next = Instant::now(); + while !stop.load(Ordering::Relaxed) { + match scene { + Scene::Static => {} + Scene::Typing => { + let column = step % columns; + let row = (step / columns) % rows; + if column == 0 && row == 0 { + conn.change_gc(gc, &ChangeGCAux::new().foreground(0x1e1e1e))?; + conn.poly_fill_rectangle( + window, + gc, + &[rect(100, 100, width - 200, height - 200)], + )?; + } + conn.change_gc(gc, &ChangeGCAux::new().foreground(0xd4d4d4))?; + conn.poly_fill_rectangle( + window, + gc, + &[rect( + 100 + (column * 12) as u16, + 100 + (row * 24) as u16, + 9, + 16, + )], + )?; + } + Scene::Video => { + let stripes = 32u16; + let stripe_width = video_width / stripes; + for index in 0..stripes { + let shade = (u32::from(index) * 8 + step * 5) & 0xff; + conn.change_gc( + gc, + &ChangeGCAux::new() + .foreground((shade << 16) | ((255 - shade) << 8) | 0x40), + )?; + conn.poly_fill_rectangle( + window, + gc, + &[rect(index * stripe_width, 0, stripe_width, video_height)], + )?; + } + } + } + conn.flush()?; + step = step.wrapping_add(1); + next += interval; + thread::sleep(next.saturating_duration_since(Instant::now())); + } + conn.free_gc(gc)?; + conn.destroy_window(window)?; + conn.sync()?; + Ok(()) + } + + fn count_frames(directory: &Path) -> anyhow::Result<(usize, u64, f64)> { + let mut media = std::fs::read(directory.join("init.mp4"))?; + let mut segments = std::fs::read_dir(directory)? + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| path.extension().is_some_and(|extension| extension == "m4s")) + .collect::>(); + segments.sort(); + for segment in &segments { + media.extend(std::fs::read(segment)?); + } + let bytes = media.len() as u64; + let joined = tempfile::Builder::new().suffix(".mp4").tempfile()?; + std::fs::write(joined.path(), &media)?; + + ffmpeg::init()?; + let mut input = ffmpeg::format::input(joined.path())?; + let Some(stream) = input.streams().best(ffmpeg::media::Type::Video) else { + bail!("the recording has no video stream"); + }; + let index = stream.index(); + let time_base = f64::from(stream.time_base()); + let mut frames = 0; + let mut end = 0i64; + for (stream, packet) in input.packets() { + if stream.index() != index { + continue; + } + frames += 1; + end = end.max(packet.pts().unwrap_or(0) + packet.duration()); + } + Ok((frames, bytes, end as f64 * time_base)) + } + + fn process_cpu() -> Duration { + let mut usage = std::mem::MaybeUninit::::zeroed(); + let usage = unsafe { + libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()); + usage.assume_init() + }; + let time = |value: libc::timeval| { + Duration::from_secs(value.tv_sec as u64) + Duration::from_micros(value.tv_usec as u64) + }; + time(usage.ru_utime) + time(usage.ru_stime) + } +} diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs index 48d0ae69e84..a0d590c4e4e 100644 --- a/crates/recording/src/capture_pipeline.rs +++ b/crates/recording/src/capture_pipeline.rs @@ -420,13 +420,18 @@ impl MakeCapturePipeline for screen_capture::X11Capture { start_gate: Option, segment_tx: Option>, ) -> anyhow::Result { + let segment_duration = std::time::Duration::from_secs(2); + let frame_interval = + std::time::Duration::from_secs_f64(1.0 / f64::from(screen_capture.video_info().fps())); OutputPipeline::builder(segments_dir) - .with_video::(screen_capture) + .with_video::( + screen_capture.with_refresh_interval(segment_duration + frame_interval), + ) .with_timestamps(start_time) .with_start_gate(start_gate.clone()) .build::(crate::ffmpeg::SegmentedVideoMuxerConfig { timed_fragments: false, - segment_duration: std::time::Duration::from_secs(2), + segment_duration, preset: H264Preset::Ultrafast, output_size: Some(output_size), shared_pause_state: None, diff --git a/crates/recording/src/instant_recording/linux_camera.rs b/crates/recording/src/instant_recording/linux_camera.rs index efb0fc4fcb0..211923f0982 100644 --- a/crates/recording/src/instant_recording/linux_camera.rs +++ b/crates/recording/src/instant_recording/linux_camera.rs @@ -694,9 +694,13 @@ impl VideoSource for CameraCompositeSource { } = frames; validate_camera_frame(&first_camera, Instant::now())?; 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 inner = screen_capture::VideoSource::setup( + config.screen_capture.with_every_frame(), + screen_tx, + ctx, + ) + .await + .context("screen source setup for camera compositor")?; let health_tx = ctx.health_tx().clone(); let runtime = tokio::runtime::Handle::current(); ctx.tasks() diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs index 8296ebe2220..a7b277631e3 100644 --- a/crates/recording/src/output_pipeline/core.rs +++ b/crates/recording/src/output_pipeline/core.rs @@ -2025,6 +2025,13 @@ impl SharedPauseState { self.flag.clone() } + pub(crate) fn offset(&self) -> Duration { + self.inner + .lock() + .unwrap_or_else(|error| error.into_inner()) + .offset + } + pub fn new(flag: Arc) -> Self { Self { flag, @@ -2114,6 +2121,7 @@ struct SharedWallClockPauseInner { #[derive(Clone)] pub struct SharedWallClockPause { flag: Arc, + resumes: Arc, inner: Arc>, } @@ -2121,6 +2129,7 @@ impl SharedWallClockPause { pub fn new(flag: Arc) -> Self { Self { flag, + resumes: Arc::default(), inner: Arc::new(std::sync::Mutex::new(SharedWallClockPauseInner { capture_pauses: Vec::new(), pause_started_at: None, @@ -2155,6 +2164,9 @@ impl SharedWallClockPause { .saturating_add(instant.saturating_duration_since(started)); } self.flag.store(paused, Ordering::Release); + if !paused { + self.resumes.fetch_add(1, Ordering::Release); + } } fn captured_pause_duration(&self, instant: Instant) -> Duration { @@ -2250,6 +2262,15 @@ impl SharedWallClockPause { Err(poisoned) => poisoned.into_inner().total_pause_duration, } } + + fn unfinished_pause_duration(&self) -> Duration { + self.inner + .lock() + .unwrap_or_else(|error| error.into_inner()) + .pause_started_at + .map(|started| started.elapsed()) + .unwrap_or_default() + } } pub struct OnceSender(Option>); @@ -2317,6 +2338,7 @@ pub struct SetupCtx { stop_signal: PipelineStopSignal, digital_silence_ms: Arc, capture_exit: Arc, + video_refresh_requests: Arc, } impl SetupCtx { @@ -2334,6 +2356,7 @@ impl SetupCtx { stop_signal, digital_silence_ms: Arc::new(AtomicU64::new(0)), capture_exit: Arc::default(), + video_refresh_requests: Arc::default(), } } @@ -2360,6 +2383,10 @@ impl SetupCtx { pub fn stop_signal(&self) -> PipelineStopSignal { self.stop_signal.clone() } + + pub fn video_refresh_requests(&self) -> Arc { + self.video_refresh_requests.clone() + } } type AudioSourceSetupFn = Box< @@ -3031,7 +3058,8 @@ impl OutputPipelineBuilder> { ) .await?; - let shared_pause = SharedWallClockPause::new(build_ctx.pause_flag.clone()); + let mut shared_pause = SharedWallClockPause::new(build_ctx.pause_flag.clone()); + shared_pause.resumes = setup_ctx.video_refresh_requests(); let video_frame_count = Arc::new(AtomicU64::new(0)); let video_timestamp_span = Arc::new(VideoTimestampSpan::default()); @@ -3156,7 +3184,8 @@ impl OutputPipelineBuilder { ) .await?; - let shared_pause = SharedWallClockPause::new(build_ctx.pause_flag.clone()); + let mut shared_pause = SharedWallClockPause::new(build_ctx.pause_flag.clone()); + shared_pause.resumes = setup_ctx.video_refresh_requests(); let audio_gap_summary = Arc::new(OnceLock::new()); let digital_silence_ms = setup_ctx.digital_silence_ms(); let capture_exit = setup_ctx.capture_exit.clone(); @@ -3489,6 +3518,7 @@ async fn setup_muxer( .await?; muxer.set_health_sender(setup_ctx.health_tx().clone()); + muxer.set_video_refresh_requests(setup_ctx.video_refresh_requests()); Ok(Arc::new(Mutex::new(muxer))) } @@ -3875,7 +3905,8 @@ fn spawn_video_encoder, TVideo: V let stopped_at = timestamps .instant() .elapsed() - .saturating_sub(shared_pause.total_pause_duration()); + .saturating_sub(shared_pause.total_pause_duration()) + .saturating_sub(shared_pause.unfinished_pause_duration()); if was_cancelled { info!("mux-video cancelled, draining remaining frames from channel"); @@ -3895,6 +3926,10 @@ fn spawn_video_encoder, TVideo: V match tokio::time::timeout_at(drain_deadline, video_rx.next()).await { Ok(Some(frame)) => { + if shared_pause.check().0 { + dropped_during_pause += 1; + continue; + } let timestamp = frame.timestamp(); if let Some(gate) = &start_gate { if !gate.admits_video(timestamp) { @@ -4025,7 +4060,6 @@ fn spawn_video_encoder, TVideo: V let video_stopped_at = stopped_at.saturating_sub(first_frame_offset.unwrap_or(stopped_at)); if was_cancelled - && !shared_pause.check().0 && let Some(mut frame) = last_frame && let Some((_, last_timestamp)) = timestamp_span.get() && let Some(final_timestamp) = static_video_tail_timestamp( @@ -4042,7 +4076,7 @@ fn spawn_video_encoder, TVideo: V muxer .lock() .await - .send_video_frame(frame, penultimate_timestamp) + .send_video_tail_frame(frame, penultimate_timestamp) .map_err(|error| video_mux_send_error(frame_count + 1, error))?; timestamp_span.record(penultimate_timestamp); frame_count += 1; @@ -4051,7 +4085,7 @@ fn spawn_video_encoder, TVideo: V muxer .lock() .await - .send_video_frame(frame, final_timestamp) + .send_video_tail_frame(frame, final_timestamp) .map_err(|error| video_mux_send_error(frame_count + 1, error))?; timestamp_span.record(final_timestamp); frame_count += 1; @@ -5552,6 +5586,8 @@ pub trait Muxer: Send + 'static { fn finish(&mut self, timestamp: Duration) -> anyhow::Result>; fn set_health_sender(&mut self, _tx: HealthSender) {} + + fn set_video_refresh_requests(&mut self, _requests: Arc) {} } pub trait AudioMuxer: Muxer { @@ -5566,6 +5602,14 @@ pub trait VideoMuxer: Muxer { frame: Self::VideoFrame, timestamp: Duration, ) -> anyhow::Result<()>; + + fn send_video_tail_frame( + &mut self, + frame: Self::VideoFrame, + timestamp: Duration, + ) -> anyhow::Result<()> { + self.send_video_frame(frame, timestamp) + } } #[cfg(test)] @@ -6676,6 +6720,18 @@ mod tests { mod shared_pause_state { use super::*; + #[test] + fn every_resume_is_counted_for_sources_that_deliver_on_change() { + let pause = SharedWallClockPause::new(Arc::new(AtomicBool::new(false))); + let start = Instant::now(); + pause.set_paused_at(true, start); + assert_eq!(pause.resumes.load(Ordering::Acquire), 0); + pause.set_paused_at(false, start); + pause.set_paused_at(true, start); + pause.set_paused_at(false, start); + assert_eq!(pause.resumes.load(Ordering::Acquire), 2); + } + #[test] fn wall_clock_pause_counts_pauses_no_frame_observed() { let pause = SharedWallClockPause::new(Arc::new(AtomicBool::new(false))); @@ -9156,6 +9212,93 @@ mod tests { (timestamps, capture_duration) } + #[tokio::test] + async fn a_still_screen_stopped_while_paused_runs_to_the_pause_point() { + let temp_dir = tempfile::tempdir().unwrap(); + let (sender, receiver) = flume::bounded(4); + let sent = Arc::new(std::sync::Mutex::new(Vec::new())); + let pipeline = OutputPipeline::builder(temp_dir.path().join("paused.mp4")) + .with_video::>(ChannelVideoSourceConfig::new( + VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 16, 16, 30), + receiver, + )) + .with_timestamps(Timestamps::now()) + .build::(sent.clone()) + .await + .unwrap(); + + let first_frame_at = Instant::now(); + sender + .send_async(StaticFrame { + timestamp: Timestamp::Instant(first_frame_at), + }) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(300)).await; + pipeline.pause(); + let recorded = first_frame_at.elapsed(); + tokio::time::sleep(Duration::from_millis(400)).await; + pipeline.stop().await.unwrap(); + + let timestamps = sent.lock().unwrap().clone(); + let last = timestamps.last().copied().unwrap(); + assert!(timestamps.len() >= 2, "{timestamps:?}"); + assert!( + last + Duration::from_millis(34) + >= recorded.saturating_sub(Duration::from_millis(60)) + && last <= recorded + Duration::from_millis(60), + "paused after {recorded:?}, video ends at {timestamps:?}" + ); + } + + #[tokio::test] + async fn frames_drained_at_a_paused_stop_do_not_cut_the_tail_short() { + let temp_dir = tempfile::tempdir().unwrap(); + let (sender, receiver) = flume::bounded(4); + let sent = Arc::new(std::sync::Mutex::new(Vec::new())); + let pipeline = OutputPipeline::builder(temp_dir.path().join("paused-drain.mp4")) + .with_video::>(ChannelVideoSourceConfig::new( + VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 16, 16, 30), + receiver, + )) + .with_timestamps(Timestamps::now()) + .build::(sent.clone()) + .await + .unwrap(); + + let first_frame_at = Instant::now(); + sender + .send_async(StaticFrame { + timestamp: Timestamp::Instant(first_frame_at), + }) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(300)).await; + pipeline.pause(); + let recorded = first_frame_at.elapsed(); + tokio::time::sleep(Duration::from_millis(400)).await; + let (stopped, _) = tokio::join!(pipeline.stop(), async { + for _ in 0..3 { + let _ = sender.try_send(StaticFrame { + timestamp: Timestamp::Instant(Instant::now()), + }); + tokio::task::yield_now().await; + } + }); + stopped.unwrap(); + + let timestamps = sent.lock().unwrap().clone(); + let last = timestamps.last().copied().unwrap(); + assert!( + timestamps.len() >= 2 && last <= recorded + Duration::from_millis(60), + "paused after {recorded:?}, video ends at {timestamps:?}" + ); + assert!( + last + Duration::from_millis(94) >= recorded, + "paused after {recorded:?}, video ends at {timestamps:?}" + ); + } + #[tokio::test] async fn primed_pipeline_discards_video_captured_before_the_start_gate_arms() { let temp_dir = tempfile::tempdir().unwrap(); diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rs index 8a10285e247..ad18bb2572d 100644 --- a/crates/recording/src/output_pipeline/ffmpeg.rs +++ b/crates/recording/src/output_pipeline/ffmpeg.rs @@ -345,6 +345,7 @@ struct FrameDropTracker { total_drops: u64, total_frames: u64, last_check: std::time::Instant, + refresh_requests: Option>, } impl FrameDropTracker { @@ -355,6 +356,7 @@ impl FrameDropTracker { total_drops: 0, total_frames: 0, last_check: std::time::Instant::now(), + refresh_requests: None, } } @@ -367,6 +369,9 @@ impl FrameDropTracker { fn record_drop(&mut self) { self.drops_in_window += 1; self.total_drops += 1; + if let Some(requests) = &self.refresh_requests { + requests.fetch_add(1, std::sync::atomic::Ordering::Release); + } self.check_drop_rate(); } @@ -559,6 +564,10 @@ impl Muxer for SegmentedVideoMuxer { } } + fn set_video_refresh_requests(&mut self, requests: Arc) { + self.frame_drops.refresh_requests = Some(requests); + } + fn finish(&mut self, timestamp: Duration) -> anyhow::Result> { if self.strict_finish { return Ok(self.finish_joined(timestamp)); @@ -817,7 +826,24 @@ impl VideoMuxer for SegmentedVideoMuxer { let Some(adjusted_timestamp) = self.pause.adjust(timestamp)? else { return Ok(()); }; + self.queue_video_frame(frame, adjusted_timestamp) + } + fn send_video_tail_frame( + &mut self, + frame: Self::VideoFrame, + timestamp: Duration, + ) -> anyhow::Result<()> { + self.queue_video_frame(frame, timestamp.saturating_sub(self.pause.offset())) + } +} + +impl SegmentedVideoMuxer { + fn queue_video_frame( + &mut self, + frame: FFmpegVideoFrame, + timestamp: Duration, + ) -> anyhow::Result<()> { if !self.started { self.start_encoder()?; } @@ -825,7 +851,7 @@ impl VideoMuxer for SegmentedVideoMuxer { if let Some(state) = &self.state { send_segmented_frame( &state.video_tx, - Some((frame.inner, adjusted_timestamp)), + Some((frame.inner, timestamp)), &mut self.frame_drops, )?; } @@ -1048,6 +1074,65 @@ mod tests { assert_eq!(drops.total_drops, 1); } + #[test] + fn a_frame_dropped_at_the_encoder_queue_asks_the_source_to_send_it_again() { + let (sender, _receiver) = flume::bounded(1); + sender.send(1).unwrap(); + let requests = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let mut drops = FrameDropTracker::new(); + drops.refresh_requests = Some(requests.clone()); + + send_segmented_frame(&sender, 2, &mut drops).unwrap(); + assert_eq!(drops.total_drops, 1); + assert_eq!(requests.load(std::sync::atomic::Ordering::Acquire), 1); + + drop(_receiver); + let (sender, receiver) = flume::bounded(1); + send_segmented_frame(&sender, 3, &mut drops).unwrap(); + assert_eq!(receiver.recv().unwrap(), 3); + assert_eq!(requests.load(std::sync::atomic::Ordering::Acquire), 1); + } + + #[tokio::test] + async fn a_tail_frame_reaches_the_encoder_while_paused() { + use super::{SegmentedVideoMuxer, SegmentedVideoMuxerConfig}; + use crate::{Muxer, TaskPool, output_pipeline::VideoMuxer}; + use std::time::Duration; + + let directory = tempfile::tempdir().unwrap(); + let paused = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let mut muxer = SegmentedVideoMuxer::setup( + SegmentedVideoMuxerConfig::default(), + directory.path().join("display"), + Some(cap_media_info::VideoInfo::from_raw_ffmpeg( + ffmpeg::format::Pixel::BGRA, + 64, + 64, + 30, + )), + None, + paused, + &mut TaskPool::default(), + ) + .await + .unwrap(); + let frame = || FFmpegVideoFrame { + inner: ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, 64, 64), + timestamp: Timestamp::Instant(Instant::now()), + }; + + muxer + .send_video_frame(frame(), Duration::from_secs(1)) + .unwrap(); + assert_eq!(muxer.frame_drops.total_frames, 0); + + muxer + .send_video_tail_frame(frame(), Duration::from_secs(1)) + .unwrap(); + assert_eq!(muxer.frame_drops.total_frames, 1); + muxer.finish(Duration::from_secs(1)).unwrap().unwrap(); + } + #[test] fn segmented_encoder_reports_disconnected_queue() { let (sender, receiver) = flume::bounded(1); diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index bd767a84f7d..ff33fb962b9 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -41,6 +41,9 @@ mod frame_scaler; #[cfg(test)] mod x11_tests; +#[cfg(test)] +mod x11_delivery_tests; + #[cfg(test)] mod system_audio_channel_tests; @@ -72,12 +75,28 @@ impl ScreenCaptureFormat for X11Capture { pub struct VideoSourceConfig { video_info: VideoInfo, input: LinuxInputConfig, + every_frame: bool, + refresh_interval: Option, } impl VideoSourceConfig { pub(crate) fn video_info(&self) -> VideoInfo { self.video_info } + + pub(crate) fn with_every_frame(self) -> Self { + Self { + every_frame: true, + ..self + } + } + + pub(crate) fn with_refresh_interval(self, interval: Duration) -> Self { + Self { + refresh_interval: Some(interval), + ..self + } + } } enum LinuxInputConfig { @@ -165,6 +184,8 @@ impl ScreenCaptureConfig { VideoSourceConfig { video_info, input: LinuxInputConfig::Wayland(input), + every_frame: false, + refresh_interval: None, } } else { let display = Display::from_id(&self.config.display) @@ -224,6 +245,8 @@ impl ScreenCaptureConfig { fps: self.config.fps, show_cursor: self.config.show_cursor, }), + every_frame: false, + refresh_interval: None, } }; let system_audio = if self.system_audio { @@ -339,11 +362,16 @@ impl OutputVideoSource for VideoSource { let stop_token = ctx.stop_token(); let health_tx = ctx.health_tx().clone(); let info = config.video_info; + let delivery = X11Delivery { + every_frame: config.every_frame, + refresh_interval: config.refresh_interval, + refresh_requests: ctx.video_refresh_requests(), + }; match config.input { LinuxInputConfig::X11(input) => { ctx.tasks().spawn_thread("x11-capture-thread", { let stop_token = stop_token.clone(); - move || capture_x11(info, input, video_tx, stop_token, health_tx) + move || capture_x11(info, input, delivery, video_tx, stop_token, health_tx) }); } LinuxInputConfig::Wayland(input) => { @@ -2425,24 +2453,75 @@ fn pactl_default_device(command: &str) -> Option { .filter(|sink| !sink.is_empty()) } +struct X11Delivery { + every_frame: bool, + refresh_interval: Option, + refresh_requests: Arc, +} + fn capture_x11( video_info: VideoInfo, input_config: X11InputConfig, + delivery: X11Delivery, mut video_tx: mpsc::Sender, stop_token: CancellationToken, health_tx: output_pipeline::HealthSender, ) -> anyhow::Result<()> { let mut grabber = X11Grabber::new(&input_config)?; grabber.output = video_info; + if !delivery.every_frame + && let Err(error) = grabber.track_changes() + { + tracing::info!( + error = %format!("{error:#}"), + "X11 DAMAGE unavailable, capturing every frame" + ); + } let frame_interval = Duration::from_secs_f64(1.0 / f64::from(input_config.fps.max(1))); let started = Instant::now(); let mut next_capture = Instant::now(); let mut sent = 0u64; let mut dropped = 0u64; + let mut unchanged = 0u64; + let mut refresh_requests = delivery.refresh_requests.load(Ordering::Acquire); + let mut last_sent = Instant::now(); while !stop_token.is_cancelled() { - let mut frame = match grabber.grab() { - Ok(frame) => frame, + let requested = delivery.refresh_requests.load(Ordering::Acquire); + if requested != refresh_requests + || delivery + .refresh_interval + .is_some_and(|interval| last_sent.elapsed() >= interval) + { + grabber.mark_changed(); + } + refresh_requests = requested; + match grabber.grab_if_changed() { + Ok(Some(mut frame)) => { + frame.set_pts(Some(started.elapsed().as_micros() as i64)); + + let timestamp = Timestamp::Instant(Instant::now()); + match send_with_stall_budget_futures( + &mut video_tx, + FFmpegVideoFrame { + inner: frame, + timestamp, + }, + "linux-screen-video", + &health_tx, + ) { + StallSendOutcome::Sent => { + sent += 1; + last_sent = Instant::now(); + } + StallSendOutcome::StalledAndDropped { .. } => { + dropped += 1; + grabber.mark_changed(); + } + StallSendOutcome::Disconnected => return Ok(()), + } + } + Ok(None) => unchanged += 1, Err(error) if input_config.window_id.is_some() => return Err(error), Err(error) => { // X11 servers can transiently fail GetImage (e.g. while the @@ -2451,22 +2530,6 @@ fn capture_x11( std::thread::sleep(frame_interval); continue; } - }; - frame.set_pts(Some(started.elapsed().as_micros() as i64)); - - let timestamp = Timestamp::Instant(Instant::now()); - match send_with_stall_budget_futures( - &mut video_tx, - FFmpegVideoFrame { - inner: frame, - timestamp, - }, - "linux-screen-video", - &health_tx, - ) { - StallSendOutcome::Sent => sent += 1, - StallSendOutcome::StalledAndDropped { .. } => dropped += 1, - StallSendOutcome::Disconnected => return Ok(()), } // Pace to the requested framerate without accumulating drift, while @@ -2483,6 +2546,7 @@ fn capture_x11( tracing::info!( sent, dropped, + unchanged, elapsed_ms = started.elapsed().as_millis() as u64, "Linux X11 capture stopped" ); @@ -2515,6 +2579,13 @@ pub struct X11Grabber { scaler: Option, show_cursor: bool, force_shm_row_copy: bool, + changes: Option, +} + +struct X11Changes { + damage: x11rb::protocol::damage::Damage, + pending: bool, + pointer: Option<(i16, i16)>, } enum GrabBackend { @@ -2834,6 +2905,7 @@ impl X11Grabber { scaler: None, show_cursor, force_shm_row_copy: false, + changes: None, }; grabber.refresh_window_pixmap()?; grabber.backend = grabber.initial_backend(allow_shm); @@ -2920,27 +2992,105 @@ impl X11Grabber { pool.publish_idle(width, height, image_bytes, format) } - fn refresh_window_pixmap(&mut self) -> anyhow::Result<()> { - let Some(window) = self.window.as_mut() else { - return Ok(()); + #[doc(hidden)] + pub fn track_changes(&mut self) -> anyhow::Result<()> { + use x11rb::protocol::damage::{ConnectionExt as _, ReportLevel}; + use x11rb::protocol::xfixes::{ConnectionExt as _, CursorNotifyMask}; + + self.conn + .damage_query_version(1, 1)? + .reply() + .context("query X11 DAMAGE version")?; + let damage = self.conn.generate_id()?; + let drawable = self.window.as_ref().map_or(self.root, |window| window.id); + self.conn + .damage_create(damage, drawable, ReportLevel::NON_EMPTY)? + .check() + .context("create X11 damage tracker")?; + if self.show_cursor { + self.conn + .xfixes_select_cursor_input(self.root, CursorNotifyMask::DISPLAY_CURSOR)? + .check() + .context("watch X11 cursor shape")?; + } + self.changes = Some(X11Changes { + damage, + pending: true, + pointer: None, + }); + Ok(()) + } + + #[doc(hidden)] + pub fn mark_changed(&mut self) { + if let Some(changes) = self.changes.as_mut() { + changes.pending = true; + } + } + + #[doc(hidden)] + pub fn grab_if_changed(&mut self) -> anyhow::Result> { + if self.changes.is_none() { + return self.grab().map(Some); + } + self.refresh_window_pixmap()?; + let pointer = if self.show_cursor { + let pointer = self + .conn + .query_pointer(self.root)? + .reply() + .context("read X11 pointer position")?; + Some((pointer.root_x, pointer.root_y)) + } else { + None + }; + let Some(changes) = self.changes.as_mut() else { + return self.grab().map(Some); }; + if changes.pointer != pointer { + changes.pointer = pointer; + changes.pending = true; + } + if !changes.pending { + return Ok(None); + } + self.capture().map(Some) + } + + fn drain_events(&mut self) -> anyhow::Result { + let window = self.window.as_ref().map(|window| window.id); let mut storage_changed = false; while let Some(event) = self.conn.poll_for_event()? { match event { - Event::UnmapNotify(event) if event.window == window.id => { + Event::DamageNotify(_) | Event::XfixesCursorNotify(_) => { + if let Some(changes) = self.changes.as_mut() { + changes.pending = true; + } + } + Event::UnmapNotify(event) if Some(event.window) == window => { bail!("Selected X11 window was unmapped"); } - Event::DestroyNotify(event) if event.window == window.id => { + Event::DestroyNotify(event) if Some(event.window) == window => { bail!("Selected X11 window was closed"); } - Event::ConfigureNotify(event) if event.window == window.id => { + Event::ConfigureNotify(event) if Some(event.window) == window => { 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, + Event::ReparentNotify(event) if Some(event.window) == window => { + storage_changed = true + } + Event::MapNotify(event) if Some(event.window) == window => storage_changed = true, _ => {} } } + Ok(storage_changed) + } + + fn refresh_window_pixmap(&mut self) -> anyhow::Result<()> { + let storage_changed = self.drain_events()?; + let Some(window) = self.window.as_mut() else { + return Ok(()); + }; let attributes = self .conn .get_window_attributes(window.id)? @@ -2976,6 +3126,9 @@ impl X11Grabber { self.width = geometry.width; self.height = geometry.height; window.border_width = geometry.border_width; + if let Some(changes) = self.changes.as_mut() { + changes.pending = true; + } } if self.show_cursor { @@ -2993,6 +3146,26 @@ impl X11Grabber { /// Capture one frame of the configured region as a BGRZ video frame. pub fn grab(&mut self) -> anyhow::Result { self.refresh_window_pixmap()?; + self.capture() + } + + fn capture(&mut self) -> anyhow::Result { + if let Some(changes) = self.changes.as_mut() { + use x11rb::protocol::damage::ConnectionExt as _; + self.conn + .damage_subtract(changes.damage, x11rb::NONE, x11rb::NONE)?; + changes.pending = false; + } + let frame = self.read_frame(); + if frame.is_err() + && let Some(changes) = self.changes.as_mut() + { + changes.pending = true; + } + frame + } + + fn read_frame(&mut self) -> anyhow::Result { let (drawable, x, y) = match &self.window { Some(window) => { let border = i16::try_from(window.border_width) diff --git a/crates/recording/src/sources/screen_capture/linux/x11_delivery_tests.rs b/crates/recording/src/sources/screen_capture/linux/x11_delivery_tests.rs new file mode 100644 index 00000000000..32f9f46a02a --- /dev/null +++ b/crates/recording/src/sources/screen_capture/linux/x11_delivery_tests.rs @@ -0,0 +1,238 @@ +use super::*; +use std::{ + io::{BufRead, BufReader}, + process::{Child, Command, Stdio}, +}; +use x11rb::{ + protocol::xproto::{CreateGCAux, Rectangle}, + wrapper::ConnectionExt as _, +}; + +const WIDTH: u16 = 320; +const HEIGHT: u16 = 240; +const RED: u32 = 0xff0000; +const GREEN: u32 = 0x00ff00; + +struct Xvfb { + child: Child, + display: String, +} + +impl Xvfb { + fn start() -> Option { + let (reader, writer) = std::io::pipe().ok()?; + let mut child = Command::new("Xvfb") + .args(["-displayfd", "1", "-screen", "0"]) + .arg(format!("{WIDTH}x{HEIGHT}x24")) + .args(["-nolisten", "tcp"]) + .stdin(Stdio::null()) + .stdout(writer) + .stderr(Stdio::null()) + .spawn() + .inspect_err(|error| eprintln!("skipping X11 delivery test: no Xvfb: {error}")) + .ok()?; + let mut line = String::new(); + let read = BufReader::new(reader).read_line(&mut line); + let Some(number) = read.ok().and_then(|_| line.trim().parse::().ok()) else { + let _ = child.kill(); + let _ = child.wait(); + return None; + }; + Some(Self { + child, + display: format!(":{number}"), + }) + } +} + +impl Drop for Xvfb { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +struct Screen { + conn: RustConnection, + root: u32, +} + +impl Screen { + fn connect(server: &Xvfb) -> Self { + let (conn, screen) = x11rb::connect(Some(&server.display)).unwrap(); + let root = conn.setup().roots[screen].root; + Self { conn, root } + } + + fn fill(&self, color: u32) { + let gc = self.conn.generate_id().unwrap(); + self.conn + .create_gc(gc, self.root, &CreateGCAux::new().foreground(color)) + .unwrap(); + self.conn + .poly_fill_rectangle( + self.root, + gc, + &[Rectangle { + x: 0, + y: 0, + width: WIDTH, + height: HEIGHT, + }], + ) + .unwrap(); + self.conn.free_gc(gc).unwrap(); + self.conn.sync().unwrap(); + } +} + +struct Capture { + frames: mpsc::Receiver, + refresh_requests: Arc, + stop: CancellationToken, + thread: Option>>, + _health: tokio::sync::mpsc::Receiver, +} + +impl Capture { + fn start(server: &Xvfb, channel_buffer: usize, refresh_interval: Option) -> Self { + let input = X11InputConfig { + display_name: server.display.clone(), + window_id: None, + x: 0, + y: 0, + width: u32::from(WIDTH), + height: u32::from(HEIGHT), + fps: 60, + show_cursor: false, + }; + let info = VideoInfo::from_raw_ffmpeg( + ffmpeg::format::Pixel::BGRZ, + u32::from(WIDTH), + u32::from(HEIGHT), + 60, + ); + let refresh_requests = Arc::new(AtomicU64::new(0)); + let delivery = X11Delivery { + every_frame: false, + refresh_interval, + refresh_requests: refresh_requests.clone(), + }; + let (tx, frames) = mpsc::channel(channel_buffer); + let (health_tx, health) = tokio::sync::mpsc::channel(64); + let stop = CancellationToken::new(); + let thread_stop = stop.clone(); + let thread = std::thread::spawn(move || { + capture_x11(info, input, delivery, tx, thread_stop, health_tx) + }); + Self { + frames, + refresh_requests, + stop, + thread: Some(thread), + _health: health, + } + } + + async fn next_color(&mut self) -> Option { + let frame = tokio::time::timeout(Duration::from_secs(2), self.frames.next()) + .await + .ok()?? + .inner; + let center = usize::from(HEIGHT / 2) * frame.stride(0) + usize::from(WIDTH / 2) * 4; + let pixel = &frame.data(0)[center..center + 3]; + Some(u32::from(pixel[2]) << 16 | u32::from(pixel[1]) << 8 | u32::from(pixel[0])) + } + + async fn count_for(&mut self, window: Duration) -> usize { + let deadline = tokio::time::Instant::now() + window; + let mut count = 0; + while let Ok(Some(_)) = tokio::time::timeout_at(deadline, self.frames.next()).await { + count += 1; + } + count + } +} + +impl Drop for Capture { + fn drop(&mut self) { + self.stop.cancel(); + self.frames.close(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +#[tokio::test] +async fn a_change_discarded_downstream_is_delivered_again_on_request() { + let Some(server) = Xvfb::start() else { + return; + }; + let screen = Screen::connect(&server); + screen.fill(RED); + let mut capture = Capture::start(&server, 4, None); + assert_eq!(capture.next_color().await, Some(RED)); + + screen.fill(GREEN); + capture.count_for(Duration::from_millis(300)).await; + assert_eq!(capture.count_for(Duration::from_millis(200)).await, 0); + + capture.refresh_requests.fetch_add(1, Ordering::Release); + assert_eq!(capture.next_color().await, Some(GREEN)); + assert_eq!(capture.count_for(Duration::from_millis(200)).await, 0); +} + +#[tokio::test] +async fn a_request_right_after_a_delivery_still_sends_the_frame_again() { + let Some(server) = Xvfb::start() else { + return; + }; + let screen = Screen::connect(&server); + screen.fill(RED); + let mut capture = Capture::start(&server, 4, None); + assert_eq!(capture.next_color().await, Some(RED)); + + screen.fill(GREEN); + assert_eq!(capture.next_color().await, Some(GREEN)); + capture.refresh_requests.fetch_add(1, Ordering::Release); + assert_eq!(capture.next_color().await, Some(GREEN)); + assert_eq!(capture.count_for(Duration::from_millis(200)).await, 0); +} + +#[tokio::test] +async fn a_change_dropped_under_backpressure_is_delivered_once_the_channel_drains() { + let Some(server) = Xvfb::start() else { + return; + }; + let screen = Screen::connect(&server); + screen.fill(RED); + let mut capture = Capture::start(&server, 0, None); + tokio::time::sleep(Duration::from_millis(300)).await; + + screen.fill(GREEN); + tokio::time::sleep(Duration::from_millis(output_pipeline::STALL_BUDGET_MS * 6)).await; + + assert_eq!(capture.next_color().await, Some(RED)); + assert_eq!(capture.next_color().await, Some(GREEN)); + assert_eq!(capture.count_for(Duration::from_millis(200)).await, 0); +} + +#[tokio::test] +async fn a_static_screen_is_resent_at_the_refresh_interval() { + let Some(server) = Xvfb::start() else { + return; + }; + let screen = Screen::connect(&server); + screen.fill(RED); + + let mut unrefreshed = Capture::start(&server, 4, None); + assert_eq!(unrefreshed.next_color().await, Some(RED)); + assert_eq!(unrefreshed.count_for(Duration::from_millis(600)).await, 0); + drop(unrefreshed); + + let mut refreshed = Capture::start(&server, 4, Some(Duration::from_millis(200))); + assert_eq!(refreshed.next_color().await, Some(RED)); + let resent = refreshed.count_for(Duration::from_millis(1100)).await; + assert!((4..=6).contains(&resent), "resent {resent} frames"); +} diff --git a/crates/recording/src/sources/screen_capture/linux/x11_tests.rs b/crates/recording/src/sources/screen_capture/linux/x11_tests.rs index 18c951e0025..bb4dc3fd725 100644 --- a/crates/recording/src/sources/screen_capture/linux/x11_tests.rs +++ b/crates/recording/src/sources/screen_capture/linux/x11_tests.rs @@ -39,7 +39,14 @@ async fn capture_frame( let (health_tx, _health_rx) = tokio::sync::mpsc::channel(4); let stop = CancellationToken::new(); let thread_stop = stop.clone(); - let thread = std::thread::spawn(move || capture_x11(info, input, tx, thread_stop, health_tx)); + let thread = std::thread::spawn(move || { + let delivery = X11Delivery { + every_frame: false, + refresh_interval: None, + refresh_requests: Arc::default(), + }; + capture_x11(info, input, delivery, tx, thread_stop, health_tx) + }); let frame = tokio::time::timeout(Duration::from_secs(5), rx.next()).await; stop.cancel(); drop(rx); diff --git a/crates/recording/tests/x11_shm_capture.rs b/crates/recording/tests/x11_shm_capture.rs index 96403ab706d..346a74b0b90 100644 --- a/crates/recording/tests/x11_shm_capture.rs +++ b/crates/recording/tests/x11_shm_capture.rs @@ -572,6 +572,163 @@ fn window_capture_uses_shm_and_survives_resize() { ); } +fn tracking_grabber(config: &X11InputConfig) -> X11Grabber { + let mut grabber = grabber(config, true); + grabber.track_changes().unwrap(); + grabber +} + +fn assert_unchanged(grabber: &mut X11Grabber) { + for _ in 0..3 { + assert!(grabber.grab_if_changed().unwrap().is_none()); + } +} + +#[test] +fn static_screen_is_grabbed_once_until_damaged() { + let _guard = serial(); + let Some(server) = Xvfb::start(320, 240, &["-nolisten", "tcp"]) else { + return; + }; + let (conn, root) = connect(&server.display()); + draw_pattern(&conn, root, 320, 240); + conn.sync().unwrap(); + + let mut grabber = tracking_grabber(&config(&server.display(), 0, 0, 320, 240)); + let first = grabber.grab_if_changed().unwrap().unwrap(); + assert_eq!(bgr_rows(&first), expected_bgr(0, 0, 320, 240)); + drop(first); + assert_unchanged(&mut grabber); + + fill_rect(&conn, root, 320, 240, 0x00ff00); + let damaged = grabber.grab_if_changed().unwrap().unwrap(); + assert!( + bgr_rows(&damaged) + .chunks_exact(3) + .all(|pixel| pixel == [0, 255, 0]) + ); + drop(damaged); + assert_unchanged(&mut grabber); +} + +#[test] +fn display_capture_tracks_damage_to_child_windows() { + let _guard = serial(); + let Some(server) = Xvfb::start(320, 240, &["-nolisten", "tcp"]) else { + return; + }; + let (conn, root) = connect(&server.display()); + let window = conn.generate_id().unwrap(); + conn.create_window( + 24, + window, + root, + 20, + 20, + 100, + 80, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().background_pixel(0), + ) + .unwrap() + .check() + .unwrap(); + conn.map_window(window).unwrap().check().unwrap(); + conn.sync().unwrap(); + + let mut grabber = tracking_grabber(&config(&server.display(), 0, 0, 320, 240)); + assert!(grabber.grab_if_changed().unwrap().is_some()); + assert_unchanged(&mut grabber); + + fill_rect(&conn, window, 100, 80, 0x0000ff); + let frame = grabber.grab_if_changed().unwrap().unwrap(); + let rows = bgr_rows(&frame); + let pixel = (30 * 320 + 30) * 3; + assert_eq!(&rows[pixel..pixel + 3], [255, 0, 0]); + drop(frame); + assert_unchanged(&mut grabber); +} + +#[test] +fn untracked_grabber_grabs_every_frame() { + let _guard = serial(); + let Some(server) = Xvfb::start(320, 240, &["-nolisten", "tcp"]) else { + return; + }; + let mut grabber = grabber(&config(&server.display(), 0, 0, 320, 240), true); + for _ in 0..3 { + assert!(grabber.grab_if_changed().unwrap().is_some()); + } +} + +#[test] +fn pointer_motion_changes_a_frame_that_draws_the_cursor() { + let _guard = serial(); + let Some(server) = Xvfb::start(320, 240, &["-nolisten", "tcp"]) else { + return; + }; + let (conn, root) = connect(&server.display()); + let mut config = config(&server.display(), 0, 0, 320, 240); + config.show_cursor = true; + let mut grabber = tracking_grabber(&config); + assert!(grabber.grab_if_changed().unwrap().is_some()); + assert_unchanged(&mut grabber); + + conn.warp_pointer(x11rb::NONE, root, 0, 0, 0, 0, 100, 80) + .unwrap() + .check() + .unwrap(); + assert!(grabber.grab_if_changed().unwrap().is_some()); + assert_unchanged(&mut grabber); +} + +#[test] +fn window_capture_tracks_damage_to_the_window() { + let _guard = serial(); + let Some(server) = Xvfb::start(640, 480, &["-nolisten", "tcp"]) else { + return; + }; + let (conn, root) = connect(&server.display()); + let window = conn.generate_id().unwrap(); + conn.create_window( + 24, + window, + root, + 40, + 30, + 200, + 150, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().background_pixel(0), + ) + .unwrap() + .check() + .unwrap(); + conn.map_window(window).unwrap().check().unwrap(); + conn.sync().unwrap(); + + let mut config = config(&server.display(), 40, 30, 200, 150); + config.window_id = Some(window); + let mut grabber = tracking_grabber(&config); + assert!(grabber.grab_if_changed().unwrap().is_some()); + assert_unchanged(&mut grabber); + + draw_pattern(&conn, window, 200, 150); + conn.sync().unwrap(); + let frame = grabber.grab_if_changed().unwrap().unwrap(); + assert_eq!(bgr_rows(&frame), expected_bgr(0, 0, 200, 150)); + drop(frame); + assert_unchanged(&mut grabber); + + conn.destroy_window(window).unwrap().check().unwrap(); + conn.sync().unwrap(); + assert!(grabber.grab_if_changed().is_err()); +} + fn soak(frames: usize) { let _guard = serial(); let Some(server) = Xvfb::start(256, 256, &["-nolisten", "tcp"]) else {