Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(gpui): display transparent camera cutout frames

Richie McIlroyee4e52b1dd12
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index d7ddafcc6..f9f47c33e 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -2971,7 +2971,7 @@ pub(crate) fn refresh_linux_instant_camera(
effects: LinuxCameraProcessing {
mirrored: snapshot.state.mirrored,
blur: match snapshot.state.background_blur {
- BlurMode::Off => LinuxCameraBlur::Off,
+ BlurMode::Off | BlurMode::Remove => LinuxCameraBlur::Off,
BlurMode::Light => LinuxCameraBlur::Light,
BlurMode::Heavy => LinuxCameraBlur::Heavy,
},
diff --git a/apps/desktop-gpui/src/camera_blur.rs b/apps/desktop-gpui/src/camera_blur.rs
index a5adde3da..1ff061685 100644
--- a/apps/desktop-gpui/src/camera_blur.rs
+++ b/apps/desktop-gpui/src/camera_blur.rs
@@ -16,7 +16,7 @@
//! Imports are cached per ring slot (keyed by pixel-buffer pointer +
//! ring generation), so the steady state creates no textures.
//! 3. `BlurProcessor::process_into_encoder` runs the segmentation mask +
-//! separable blur + composite, with the preview's 150ms inference interval
+//! separable blur + composite, with the preview's 33ms inference interval
//! (`CAMERA_PREVIEW_BLUR_INFERENCE_INTERVAL`, `camera.rs:50`).
//! 4. `cap_rendering::RgbaToBgraSurfaceConverter` blits the RGBA output into
//! a BGRA IOSurface-backed CVPixelBuffer from its own ring, and
@@ -25,7 +25,7 @@
//!
//! Everything runs on one dedicated `camera-blur` thread (the Tauri preview
//! renders on a dedicated thread too, `camera.rs:466-490`), so the ~10ms
-//! CoreML/CPU segmentation inference every 150ms never blocks the UI thread.
+//! CoreML/CPU segmentation inference every 33ms never blocks the UI thread.
//! The channel back to the window is how "what you see is what records" holds:
//! this is the same `BlurProcessor` the editor/export camera layer runs
//! (`cap-rendering/src/lib.rs:5742`), fed by the same `BackgroundBlurMode`
@@ -57,7 +57,7 @@ use cidre::{arc, cv};
pub const BLUR_MAX_DIMS: (usize, usize) = (640, 360);
/// `CAMERA_PREVIEW_BLUR_INFERENCE_INTERVAL` (`camera.rs:50`).
-const BLUR_INFERENCE_INTERVAL: Duration = Duration::from_millis(150);
+const BLUR_INFERENCE_INTERVAL: Duration = Duration::from_millis(33);
/// `LOW_SPEC_PREVIEW_RAM_THRESHOLD_BYTES` (`camera.rs:66`): machines at or
/// under 8GB never spin up the ONNX/wgpu blur processor -- the heaviest cost
@@ -113,6 +113,8 @@ pub struct BlurJob {
}
pub struct BlurOutput {
+ pub mode: cap_camera_effects::BlurMode,
+ pub cutout: Option<std::sync::Arc<gpui::RenderImage>>,
/// Blurred BGRA IOSurface pixel buffer, GPU work complete.
pub buffer: SendPixelBuf,
pub width: u32,
@@ -291,7 +293,21 @@ impl Worker {
let frame = runtime
.block_on(pending.wait(&self.device, &self.queue))
.map_err(|error| anyhow!("{error}"))?;
+ let cutout = if mode == cap_camera_effects::BlurMode::Remove {
+ use core_foundation::base::TCFType as _;
+ use core_video::pixel_buffer::{CVPixelBuffer, CVPixelBufferRef};
+ let raw = &*frame.pixel_buffer as *const cv::PixelBuf as CVPixelBufferRef;
+ let buffer = unsafe { CVPixelBuffer::wrap_under_get_rule(raw) };
+ Some(
+ crate::camera_window::snapshot_preview(&buffer)
+ .context("cutout preview pixels unavailable")?,
+ )
+ } else {
+ None
+ };
Ok(BlurOutput {
+ mode,
+ cutout,
buffer: SendPixelBuf(frame.pixel_buffer),
width: frame.width,
height: frame.height,
@@ -333,3 +349,94 @@ impl Worker {
Ok(&self.imported.last().expect("just pushed").1)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_camera_effects::BlurMode;
+ use cidre::cf;
+ use core_foundation::base::TCFType as _;
+ use core_video::pixel_buffer::{CVPixelBuffer, CVPixelBufferRef};
+ use std::time::Instant;
+
+ #[test]
+ #[ignore = "requires CAP_CAMERA_EFFECT_TEST_FRAME containing a 640x360 RGBA webcam frame"]
+ fn native_cutout_preserves_alpha_through_iosurface_and_preview_image() {
+ let pixels = std::fs::read(std::env::var("CAP_CAMERA_EFFECT_TEST_FRAME").unwrap()).unwrap();
+ let (width, height) = BLUR_MAX_DIMS;
+ assert_eq!(pixels.len(), width * height * 4);
+ let properties = cf::Dictionary::new();
+ let attributes = cf::Dictionary::with_keys_values(
+ &[
+ cv::pixel_buffer::keys::io_surf_props().as_ref(),
+ cv::pixel_buffer::keys::metal_compatibility().as_ref(),
+ ],
+ &[properties.as_ref(), cf::Boolean::value_true().as_ref()],
+ )
+ .unwrap();
+ let buffer =
+ cv::PixelBuf::new(width, height, cv::PixelFormat::_32_BGRA, Some(&attributes)).unwrap();
+ let raw = &*buffer as *const cv::PixelBuf as CVPixelBufferRef;
+ let wrapped = unsafe { CVPixelBuffer::wrap_under_get_rule(raw) };
+ assert_eq!(wrapped.lock_base_address(0), 0);
+ let stride = wrapped.get_bytes_per_row();
+ let destination = unsafe {
+ std::slice::from_raw_parts_mut(wrapped.get_base_address().cast::<u8>(), stride * height)
+ };
+ for (source, target) in pixels
+ .chunks_exact(width * 4)
+ .zip(destination.chunks_exact_mut(stride))
+ {
+ for (source, target) in source.chunks_exact(4).zip(target.chunks_exact_mut(4)) {
+ target.copy_from_slice(&[source[2], source[1], source[0], source[3]]);
+ }
+ }
+ assert_eq!(wrapped.unlock_base_address(0), 0);
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_time()
+ .build()
+ .unwrap();
+ let (device, queue) = shared_device(&runtime).unwrap();
+ let mut worker = Worker::new(device, queue).unwrap();
+ for mode in [
+ BlurMode::Remove,
+ BlurMode::Heavy,
+ BlurMode::Light,
+ BlurMode::Remove,
+ ] {
+ let mut timings = Vec::new();
+ for _ in 0..30 {
+ let start = Instant::now();
+ let output = worker
+ .process(
+ &runtime,
+ BlurJob {
+ buffer: SendPixelBuf(buffer.clone()),
+ width: width as u32,
+ height: height as u32,
+ ring_generation: 1,
+ mode,
+ },
+ )
+ .unwrap();
+ timings.push(start.elapsed().as_secs_f64() * 1000.0);
+ assert_eq!(output.mode, mode);
+ if mode == BlurMode::Remove {
+ let image = output.cutout.unwrap();
+ let bytes = image.as_bytes(0).unwrap();
+ assert!(bytes.chunks_exact(4).any(|pixel| pixel[3] == 0));
+ assert!(bytes.chunks_exact(4).any(|pixel| pixel[3] == 255));
+ } else {
+ assert!(output.cutout.is_none());
+ }
+ std::thread::sleep(Duration::from_millis(33).saturating_sub(start.elapsed()));
+ }
+ timings.sort_by(f64::total_cmp);
+ eprintln!(
+ "native {mode:?} preview worker: p50={:.2}ms p95={:.2}ms",
+ timings[15], timings[28]
+ );
+ }
+ assert_eq!(worker.imported.len(), 1);
+ }
+}
diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rs
index 90219560d..c930b1d68 100644
--- a/apps/desktop-gpui/src/camera_window.rs
+++ b/apps/desktop-gpui/src/camera_window.rs
@@ -161,6 +161,9 @@ fn normalized_size(state: &CameraWindowState) -> f32 {
/// the native page's issue overlay, and the native WGSL mask uses its own
/// smaller radii; the 24px container is what users see.
pub(crate) fn preview_radius(state: &CameraWindowState) -> f32 {
+ if cfg!(target_os = "macos") && state.background_blur == BlurMode::Remove {
+ return 0.;
+ }
match state.shape {
CameraShape::Round => clamp_size(state.size) / 2.,
_ => 24.,
@@ -168,6 +171,9 @@ pub(crate) fn preview_radius(state: &CameraWindowState) -> f32 {
}
fn picker_preview_radius(state: &CameraWindowState, picker_size: Option<(f32, f32)>) -> f32 {
+ if cfg!(target_os = "macos") && state.background_blur == BlurMode::Remove {
+ return 0.;
+ }
match (state.shape, picker_size) {
(CameraShape::Round, Some((width, height))) => {
width.max(0.).min((height - CAMERA_TOOLBAR_HEIGHT).max(0.)) / 2.
@@ -859,7 +865,7 @@ pub(crate) fn clear_parked_camera_preview(cx: &mut gpui::App) {
}
#[cfg(target_os = "macos")]
-fn snapshot_preview(
+pub(crate) fn snapshot_preview(
buffer: &core_video::pixel_buffer::CVPixelBuffer,
) -> Option<Arc<gpui::RenderImage>> {
use core_video::pixel_buffer::{kCVPixelBufferLock_ReadOnly, kCVPixelFormatType_32BGRA};
@@ -895,7 +901,7 @@ fn snapshot_preview(
let offset = source_y * stride + source_x * 4;
let pixel = unsafe { std::slice::from_raw_parts(base.add(offset), 4) };
// RenderImage consumes BGRA bytes even though image::Frame wraps RgbaImage.
- image::Rgba([pixel[0], pixel[1], pixel[2], 255])
+ image::Rgba([pixel[0], pixel[1], pixel[2], pixel[3]])
});
Some(Arc::new(gpui::RenderImage::new(smallvec::smallvec![
image::Frame::new(image)
@@ -912,6 +918,10 @@ fn snapshot_preview(
/// goes through the parent [`CameraWindow`] instead, so a frame draw reuses
/// the cached toolbar subtree.
struct CameraPreviewView {
+ #[cfg(target_os = "macos")]
+ cutout_frame: Option<Arc<gpui::RenderImage>>,
+ #[cfg(target_os = "macos")]
+ painted_cutout_frame: Option<Arc<gpui::RenderImage>>,
theme: Theme,
radius: f32,
/// Clamped bubble size, for the issue overlay's scaled text metrics.
@@ -997,6 +1007,10 @@ impl CameraPreviewView {
}
});
Self {
+ #[cfg(target_os = "macos")]
+ cutout_frame: None,
+ #[cfg(target_os = "macos")]
+ painted_cutout_frame: None,
theme,
radius,
size,
@@ -1027,6 +1041,7 @@ impl CameraPreviewView {
dims: (usize, usize),
cx: &mut Context<Self>,
) {
+ self.cutout_frame = None;
self.latest_frame = Some(frame);
self.frame_dims = Some(dims);
self.frame_revision = Some(self.selection_revision);
@@ -1064,12 +1079,24 @@ impl CameraPreviewView {
impl Render for CameraPreviewView {
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ #[cfg(target_os = "macos")]
+ if self.painted_cutout_frame.as_ref().is_some_and(|painted| {
+ self.cutout_frame
+ .as_ref()
+ .is_none_or(|current| !Arc::ptr_eq(painted, current))
+ }) && let Some(image) = self.painted_cutout_frame.take()
+ {
+ let _ = window.drop_image(image);
+ }
if self
.frame_revision
.is_some_and(|revision| revision != self.selection_revision)
{
#[cfg(target_os = "macos")]
{
+ if let Some(image) = self.cutout_frame.take() {
+ let _ = window.drop_image(image);
+ }
self.latest_frame = None;
}
#[cfg(not(target_os = "macos"))]
@@ -1096,11 +1123,15 @@ impl Render for CameraPreviewView {
.size_full()
.overflow_hidden()
.rounded(px(radius))
- .bg(theme.gray_1)
+ .when(radius > 0., |this| this.bg(theme.gray_1))
.text_color(theme.gray_12);
#[cfg(target_os = "macos")]
- if let Some(buffer) = self.latest_frame.clone() {
+ if let Some(buffer) = self
+ .latest_frame
+ .clone()
+ .filter(|_| self.cutout_frame.is_none())
+ {
let frame_dims = self.frame_dims;
let paints = self.paints.clone();
// Cover-fit painted straight from the IOSurface: `ObjectFit::Cover`
@@ -1132,6 +1163,17 @@ impl Render for CameraPreviewView {
);
}
+ #[cfg(target_os = "macos")]
+ if let Some(image) = self.cutout_frame.clone() {
+ self.painted_cutout_frame = Some(image.clone());
+ self.paints.fetch_add(1, Ordering::Relaxed);
+ container = container.child(
+ gpui::img(image)
+ .size_full()
+ .object_fit(gpui::ObjectFit::Cover),
+ );
+ }
+
#[cfg(not(target_os = "macos"))]
if let Some(image) = self.latest_frame.clone() {
self.paints.fetch_add(1, Ordering::Relaxed);
@@ -1678,6 +1720,7 @@ impl CameraWindow {
BlurMode::Off => None,
BlurMode::Light => Some(cap_camera_effects::BlurMode::Light),
BlurMode::Heavy => Some(cap_camera_effects::BlurMode::Heavy),
+ BlurMode::Remove => Some(cap_camera_effects::BlurMode::Remove),
}
}
@@ -1748,7 +1791,7 @@ impl CameraWindow {
) -> bool {
// A stale output can land after the mode flips back to Off; the raw
// path is already painting again, so drop it.
- if self.state.background_blur == BlurMode::Off
+ if self.active_blur_mode() != Some(output.mode)
|| Feeds::global(cx).read(cx).camera_preview_epoch() != Some(epoch)
{
return false;
@@ -1763,8 +1806,10 @@ impl CameraWindow {
let dims = (output.width as usize, output.height as usize);
let raw = &*output.buffer.0 as *const cidre::cv::PixelBuf as CVPixelBufferRef;
let buffer = unsafe { CVPixelBuffer::wrap_under_get_rule(raw) };
- self.preview
- .update(cx, |preview, cx| preview.set_frame(buffer, dims, cx));
+ self.preview.update(cx, |preview, cx| {
+ preview.set_frame(buffer, dims, cx);
+ preview.cutout_frame = output.cutout;
+ });
first
}
@@ -2848,6 +2893,28 @@ mod retained_preview_tests {
assert_eq!(&image.as_bytes(0).unwrap()[..4], &[19, 71, 143, 255]);
}
+ #[test]
+ fn cutout_preview_preserves_transparent_and_feathered_pixels() {
+ let buffer = buffer(3, 1);
+ assert_eq!(buffer.lock_base_address(0), 0);
+ let base = unsafe { buffer.get_base_address().cast::<u8>() };
+ unsafe {
+ base.add(3).write(0);
+ base.add(7).write(128);
+ }
+ assert_eq!(buffer.unlock_base_address(0), 0);
+ let image = snapshot_preview(&buffer).unwrap();
+ let bytes = image.as_bytes(0).unwrap();
+ assert_eq!([bytes[3], bytes[7], bytes[11]], [0, 128, 255]);
+ let state = CameraWindowState {
+ background_blur: BlurMode::Remove,
+ ..Default::default()
+ };
+ assert_eq!(preview_radius(&state), 0.0);
+ assert_eq!(picker_preview_radius(&state, Some((230.0, 286.0))), 0.0);
+ assert_eq!(state.shape, CameraShape::Round);
+ }
+
#[test]
fn retained_preview_rejects_non_bgra_surfaces() {
let buffer = CVPixelBuffer::new(kCVPixelFormatType_32ARGB, 32, 16, None).unwrap();
diff --git a/apps/desktop-gpui/src/deeplink.rs b/apps/desktop-gpui/src/deeplink.rs
index 6ea0e3315..a4d52683e 100644
--- a/apps/desktop-gpui/src/deeplink.rs
+++ b/apps/desktop-gpui/src/deeplink.rs
@@ -512,6 +512,7 @@ impl DeepLinkAction {
cap_project::BackgroundBlurMode::Off => crate::store::BlurMode::Off,
cap_project::BackgroundBlurMode::Light => crate::store::BlurMode::Light,
cap_project::BackgroundBlurMode::Heavy => crate::store::BlurMode::Heavy,
+ cap_project::BackgroundBlurMode::Remove => crate::store::BlurMode::Remove,
};
crate::store::update(|persisted| {
persisted.camera_window = Some(crate::store::CameraWindowState {
diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rs
index 05570c5da..1df51a623 100644
--- a/apps/desktop-gpui/src/feeds.rs
+++ b/apps/desktop-gpui/src/feeds.rs
@@ -845,6 +845,7 @@ impl Feeds {
crate::store::BlurMode::Off => 0,
crate::store::BlurMode::Light => 1,
crate::store::BlurMode::Heavy => 2,
+ crate::store::BlurMode::Remove => 0,
},
Ordering::Relaxed,
);
diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs
index b217d5065..cd12fe31c 100644
--- a/apps/desktop-gpui/src/store.rs
+++ b/apps/desktop-gpui/src/store.rs
@@ -42,6 +42,7 @@ pub enum BlurMode {
Off,
Light,
Heavy,
+ Remove,
}
impl BlurMode {
@@ -49,7 +50,8 @@ impl BlurMode {
match self {
Self::Off => Self::Light,
Self::Light => Self::Heavy,
- Self::Heavy => Self::Off,
+ Self::Heavy if cfg!(target_os = "macos") => Self::Remove,
+ Self::Heavy | Self::Remove => Self::Off,
}
}
@@ -60,6 +62,7 @@ impl BlurMode {
Self::Off => None,
Self::Light => Some("Light"),
Self::Heavy => Some("Heavy"),
+ Self::Remove => Some("Cutout"),
}
}
}