diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock index 1c5f5fb7ac4..7432fb314cd 100644 --- a/apps/desktop-gpui/Cargo.lock +++ b/apps/desktop-gpui/Cargo.lock @@ -1643,6 +1643,7 @@ dependencies = [ "same-file", "sanitize-filename", "scap-cpal", + "scap-screencapturekit", "scap-targets", "semver", "serde", diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index fcaff1e12be..33501ea1901 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -258,6 +258,7 @@ raw-window-handle = "0.6" x11rb = "0.13" [target.'cfg(target_os = "macos")'.dependencies] +scap-screencapturekit = { path = "../../crates/scap-screencapturekit" } # Native window treatment (panel levels, Spaces) gpui does not expose. Same # direct 0.6 line used by this app's class definitions and AppKit bindings. objc2 = { version = "0.6.5", features = ["exception"] } diff --git a/apps/desktop-gpui/src/target_thumbnails.rs b/apps/desktop-gpui/src/target_thumbnails.rs index 285c12feec2..a43223cfe3e 100644 --- a/apps/desktop-gpui/src/target_thumbnails.rs +++ b/apps/desktop-gpui/src/target_thumbnails.rs @@ -15,15 +15,12 @@ //! 160x90 capture comes back as a full-bleed 320x180. //! * The capture itself (`mac.rs:7-42`): a display filter with **no** window //! exclusions — Cap's own windows deliberately appear in display thumbnails — -//! a `with_desktop_independent_window` filter for windows, and an -//! `sc::StreamCfg` sized 320x180 with the cursor hidden, handed to -//! `sc::ScreenshotManager::capture_sample_buf`. The pixel buffer is asked for -//! at thumbnail size, so nothing full-resolution is ever read back. +//! a `with_desktop_independent_window` filter for windows. The pixel buffer +//! is requested at thumbnail size with the cursor hidden. //! * The pixel conversions (`mac.rs:111-275`): the four 32-bit channel orders //! and video-range NV12, through the same RAII `CVPixelBufferLock`. //! * Sequencing: one shareable-content fetch per batch and one capture at a -//! time (`mod.rs:88-137` is a plain `for` loop; there is no concurrency to -//! port, and SCK screenshots do not like being fanned out). +//! time within each batch (`mod.rs:88-137`). //! * The refresh policy: 5s cheap-list staleness, 10s thumbnail staleness, an //! idle prewarm shortly after launch, and signature-driven refetch while a //! picker is open (see the constants and `*_signature` below). @@ -78,11 +75,7 @@ pub const PREWARM_DELAY: Duration = Duration::from_millis(250); /// A healthy 320x180 thumbnail or shareable-content read takes milliseconds. const CAPTURE_TIMEOUT: Duration = Duration::from_secs(5); -/// How long thumbnail captures stay paused after one hangs. A hung -/// `SCScreenshotManager` request cannot be cancelled and keeps macOS's capture -/// session (and the purple indicator) open in `replayd`, so retrying on every -/// picker poll would only pile up more of them: -/// https://github.com/CapSoftware/Cap/issues/2339 +/// How long thumbnail captures stay paused after a native operation stalls. const CAPTURE_HANG_PAUSE: Duration = Duration::from_secs(5 * 60); static CAPTURE_PAUSE: CapturePause = CapturePause::new(); @@ -113,9 +106,7 @@ impl CapturePause { } } -/// `None` when `future` outlives `limit`, which also starts `pause`. The -/// dropped request may still be pending inside ScreenCaptureKit; this only -/// stops the sweep from waiting on it forever. +/// `None` when `future` outlives `limit`, which also starts `pause`. async fn within_capture_timeout( what: &'static str, limit: Duration, @@ -137,6 +128,32 @@ async fn within_capture_timeout( } } +#[cfg(any(target_os = "macos", test))] +async fn finish_thumbnail_capture( + captured: Option>, + limit: Duration, + pause: &CapturePause, + request_stop: impl FnOnce() -> Stop, +) -> Option> +where + Stop: std::future::Future>, +{ + if matches!(captured, Some(Err(_))) { + return captured; + } + + if let Some(Err(error)) = + within_capture_timeout("stopping thumbnail stream", limit, pause, request_stop()).await + { + tracing::warn!( + ?error, + "could not stop thumbnail stream; pausing thumbnail captures" + ); + pause.start_at(std::time::Instant::now()); + } + captured +} + /// A card's images. Both halves are optional and independent: a window can have /// an icon and no thumbnail (capture refused) or the reverse (no bundle icon). #[derive(Clone, Default)] @@ -531,19 +548,7 @@ pub fn display_signature(list: &[DisplayOption]) -> String { .join("|") } -/// The content rect inside ScreenCaptureKit's 320x180 screenshot buffer: the -/// source's aspect ratio fitted inside 320x180. -/// -/// `SCScreenshotManager` scales the content to FIT the flat 320x180 request, -/// anchors it at the buffer's top-left, and pads the right/bottom with opaque -/// black; since the buffer comes back exactly 320x180, -/// [`normalize_thumbnail_dimensions`]'s early return would keep that padding -/// where SCK put it -- on a card the black bar reads as a broken corner -/// radius down the right side. The capture path crops the buffer to this rect -/// before normalizing, so the letterbox bars end up transparent and centred -/// (the card's slot background shows through, as in the Tauri picker). -/// Requesting this size FROM SCK instead is not an option: for some sizes -/// `capture_sample_buf` never resolves -- no error, the future hangs. +/// The source's aspect ratio fitted inside the 320x180 thumbnail canvas. #[cfg(any(target_os = "macos", test))] pub fn fitted_capture_size(source: Option<(f64, f64)>) -> (usize, usize) { let Some((width, height)) = source else { @@ -567,12 +572,8 @@ pub fn normalize_thumbnail_dimensions(image: &RgbaImage) -> RgbaImage { /// Run a capture sweep somewhere it is allowed to be non-`Send`. /// -/// `sc::ScreenshotManager::capture_sample_buf` holds `&sc::ContentFilter` across -/// its await, and cidre's ObjC handles are `Send` but not `Sync`, so the sweep's -/// future is not `Send` and a multi-threaded tokio worker will not take it. It -/// gets a blocking thread with its own single-threaded runtime instead: the -/// completion block fires on ScreenCaptureKit's dispatch queue and only has to -/// wake a local waker, so nothing in here needs the app's reactor. +/// ScreenCaptureKit handles are held across awaits on a single-threaded +/// runtime. The completion callbacks can wake it from their dispatch queue. /// /// The consequence is that a sweep cannot be aborted mid-capture — dropping the /// caller's task closes the `flume` receiver instead, and the very next `send` @@ -643,14 +644,7 @@ async fn capture_displays_inner(events: flume::Sender) { if captures_paused() { return; } - let Some(capture) = within_capture_timeout( - "display thumbnail", - CAPTURE_TIMEOUT, - &CAPTURE_PAUSE, - capture_display_thumbnail(&display, content.retained()), - ) - .await - else { + let Some(capture) = capture_display_thumbnail(&display, content.retained()).await else { return; }; let Some(rgba) = capture else { @@ -716,14 +710,7 @@ async fn capture_windows_inner( if captures_paused() { return; } - let Some(capture) = within_capture_timeout( - "window thumbnail", - CAPTURE_TIMEOUT, - &CAPTURE_PAUSE, - capture_window_thumbnail(&window, content.retained()), - ) - .await - else { + let Some(capture) = capture_window_thumbnail(&window, content.retained()).await else { return; }; let image = capture.map(crate::library::rgba_to_render_image); @@ -760,6 +747,7 @@ async fn capture_windows_inner( mod platform { use cidre::{arc, cv, sc}; use image::RgbaImage; + use scap_screencapturekit::{Capturer, Frame, VideoFrame}; use tracing::warn; use super::normalize_thumbnail_dimensions; @@ -811,62 +799,112 @@ mod platform { pub async fn capture_display_thumbnail( display: &scap_targets::Display, content: arc::R, - ) -> Option { + ) -> Option> { let size = display .physical_size() .map(|size| (size.width(), size.height())); - let filter = display.raw_handle().as_content_filter(content)?; - capture_thumbnail_from_filter(filter, super::fitted_capture_size(size)).await + let Some(filter) = display.raw_handle().as_content_filter(content) else { + return Some(None); + }; + capture_thumbnail_from_filter( + "display thumbnail", + filter, + super::fitted_capture_size(size), + ) + .await } /// `capture_window_thumbnail` (`mac.rs:14-20`). pub async fn capture_window_thumbnail( window: &scap_targets::Window, content: arc::R, - ) -> Option { + ) -> Option> { let size = window .physical_size() .map(|size| (size.width(), size.height())); - let sc_window = window.raw_handle().as_sc(content)?; + let Some(sc_window) = window.raw_handle().as_sc(content) else { + return Some(None); + }; let filter = sc::ContentFilter::with_desktop_independent_window(&sc_window); - capture_thumbnail_from_filter(filter, super::fitted_capture_size(size)).await + capture_thumbnail_from_filter("window thumbnail", filter, super::fitted_capture_size(size)) + .await } - /// `capture_thumbnail_from_filter` (`mac.rs:22-109`) minus the PNG/base64 - /// tail, which only existed to cross the IPC boundary into a webview. - /// - /// The request is always the flat 320x180 the Tauri code asks for. - /// `SCScreenshotManager` scales the content to FIT that buffer, anchors - /// it top-left, and pads the rest with opaque black -- which is where the - /// picker's black-bar-over-the-card-corner artifact came from. Asking SCK - /// for the aspect-fitted size instead looked cleaner but capture_sample_buf - /// NEVER RESOLVES for some sizes (no error, the future just hangs; every - /// sweep in the app silently froze) -- so the padding is cropped off after - /// conversion instead: the content rect is exactly - /// [`fitted_capture_size`]'s dims at the buffer's top-left, and - /// [`normalize_thumbnail_dimensions`] then letterboxes the cropped image - /// onto the transparent canvas, centred. + // An owned stream lets us request a stop even when no frame arrives. + // SCScreenshotManager's single-frame API has no cancellation handle (#2339). async fn capture_thumbnail_from_filter( + what: &'static str, filter: arc::R, - (content_width, content_height): (usize, usize), - ) -> Option { + (width, height): (usize, usize), + ) -> Option> { let mut config = sc::StreamCfg::new(); - config.set_width(super::THUMBNAIL_WIDTH as usize); - config.set_height(super::THUMBNAIL_HEIGHT as usize); + config.set_width(width); + config.set_height(height); + config.set_pixel_format(cv::PixelFormat::_32_BGRA); + config.set_scales_to_fit(true); config.set_shows_cursor(false); - let sample_buf = - match unsafe { sc::ScreenshotManager::capture_sample_buf(filter.as_ref(), &config) } - .await - { - Ok(buf) => buf, - Err(err) => { - warn!(error = ?err, "Failed to capture sample buffer for thumbnail"); - return None; + let (sender, receiver) = flume::bounded(1); + let mut frame_sender = Some(sender.clone()); + let capturer = match Capturer::builder(filter, config) + .with_output_sample_buf_cb(move |frame| { + if let Frame::Screen(frame) = frame + && matches!( + frame.info().status, + None | Some(sc::FrameStatus::Complete | sc::FrameStatus::Started) + ) + && let Some(sender) = frame_sender.take() + { + let _ = sender.try_send(Ok(frame)); } - }; + }) + .with_stop_with_err_cb(move |_, error| { + let _ = sender.try_send(Err(error.retained())); + }) + .build() + { + Ok(capturer) => capturer, + Err(error) => { + warn!(?error, "could not create thumbnail stream"); + return Some(None); + } + }; + + let captured = super::within_capture_timeout( + what, + super::CAPTURE_TIMEOUT, + &super::CAPTURE_PAUSE, + async { + capturer.start().await?; + receiver.recv_async().await.ok().transpose() + }, + ) + .await; + let captured = super::finish_thumbnail_capture( + captured, + super::CAPTURE_TIMEOUT, + &super::CAPTURE_PAUSE, + || { + let (completed, acknowledgement) = tokio::sync::oneshot::channel(); + capturer.stop_with_completion(move |error| { + let result = error.map_or(Ok(()), |error| Err(error.retained().into())); + let _ = completed.send(result); + }); + async move { acknowledgement.await? } + }, + ) + .await?; + match captured { + Ok(frame) => Some(frame.and_then(thumbnail_from_frame)), + Err(error) => { + warn!(?error, "thumbnail stream failed"); + Some(None) + } + } + } - let Some(image_buf) = sample_buf.image_buf() else { + fn thumbnail_from_frame(frame: VideoFrame) -> Option { + let Some(image_buf) = frame.image_buf() else { warn!("Sample buffer missing image data"); return None; }; @@ -938,16 +976,6 @@ mod platform { warn!("Failed to construct RGBA image for thumbnail"); return None; }; - // Crop SCK's top-left-anchored content out of the padded buffer (see - // the function doc). Bounded to the buffer so a surprise SCK size can - // never panic the crop. - let crop_width = (content_width as u32).min(img.width()).max(1); - let crop_height = (content_height as u32).min(img.height()).max(1); - let img = if crop_width < img.width() || crop_height < img.height() { - image::imageops::crop_imm(&img, 0, 0, crop_width, crop_height).to_image() - } else { - img - }; Some(normalize_thumbnail_dimensions(&img)) } @@ -1093,15 +1121,27 @@ mod platform { pub async fn capture_display_thumbnail( display: &scap_targets::Display, _content: ShareableContent, - ) -> Option { - capture_target_thumbnail(ScreenCaptureTarget::Display { id: display.id() }).await + ) -> Option> { + super::within_capture_timeout( + "display thumbnail", + super::CAPTURE_TIMEOUT, + &super::CAPTURE_PAUSE, + capture_target_thumbnail(ScreenCaptureTarget::Display { id: display.id() }), + ) + .await } pub async fn capture_window_thumbnail( window: &scap_targets::Window, _content: ShareableContent, - ) -> Option { - capture_target_thumbnail(ScreenCaptureTarget::Window { id: window.id() }).await + ) -> Option> { + super::within_capture_timeout( + "window thumbnail", + super::CAPTURE_TIMEOUT, + &super::CAPTURE_PAUSE, + capture_target_thumbnail(ScreenCaptureTarget::Window { id: window.id() }), + ) + .await } async fn capture_target_thumbnail(target: ScreenCaptureTarget) -> Option { @@ -1795,4 +1835,56 @@ mod tests { assert!(pause.active_at(now + CAPTURE_HANG_PAUSE.saturating_sub(Duration::from_millis(1)))); assert!(!pause.active_at(now + CAPTURE_HANG_PAUSE)); } + + #[test] + fn thumbnail_stream_stops_even_when_no_frame_arrives() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let pause = CapturePause::new(); + let stopped = std::cell::Cell::new(false); + let captured = runtime.block_on(within_capture_timeout( + "test thumbnail", + Duration::ZERO, + &pause, + std::future::pending::>(), + )); + let result = runtime.block_on(finish_thumbnail_capture( + captured, + Duration::ZERO, + &pause, + || { + stopped.set(true); + std::future::ready(Ok(())) + }, + )); + assert_eq!(result, None); + assert!(stopped.get()); + assert!(pause.active_at(std::time::Instant::now())); + } + + #[test] + fn thumbnail_frame_survives_stop_acknowledgement_timeout() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let pause = CapturePause::new(); + let (completed, acknowledgement) = tokio::sync::oneshot::channel(); + let stop_requested = std::cell::Cell::new(false); + let result = runtime.block_on(finish_thumbnail_capture( + Some(Ok::<_, ()>(42)), + Duration::ZERO, + &pause, + || { + stop_requested.set(true); + async move { acknowledgement.await? } + }, + )); + assert!(stop_requested.get()); + assert_eq!(result, Some(Ok(42))); + assert!(pause.active_at(std::time::Instant::now())); + assert!(completed.is_closed()); + } } diff --git a/crates/scap-screencapturekit/src/capture.rs b/crates/scap-screencapturekit/src/capture.rs index 1209072377a..f94731d28ac 100644 --- a/crates/scap-screencapturekit/src/capture.rs +++ b/crates/scap-screencapturekit/src/capture.rs @@ -144,6 +144,18 @@ impl Capturer { self.stream.stop().await } + /// Keeps the stream, output queue, and delegate alive through the native + /// stop callback, even if the caller stops waiting for it. + pub fn stop_with_completion(self, complete: impl FnOnce(Option<&ns::Error>) + Send + 'static) { + let stream = self.stream.retained(); + let mut pending = Some((self, complete)); + stream.stop_with_ch(move |error| { + if let Some((_capturer, complete)) = pending.take() { + complete(error); + } + }); + } + /// Starts replacing what the running stream captures; resolves once /// ScreenCaptureKit has applied the new filter. pub fn update_content_filter(