Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): apply camera background blur in native live preview

Richie McIlroyde9182abc191
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index 88ef3e84d..7fedbc921 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -51,6 +51,8 @@ pub struct CameraPreviewState {
pub size: f32,
pub shape: CameraPreviewShape,
pub mirrored: bool,
+ #[serde(default)]
+ pub background_blur: cap_project::BackgroundBlurMode,
}
impl Default for CameraPreviewState {
@@ -59,6 +61,7 @@ impl Default for CameraPreviewState {
size: DEFAULT_CAMERA_SIZE,
shape: CameraPreviewShape::default(),
mirrored: false,
+ background_blur: cap_project::BackgroundBlurMode::Off,
}
}
}
@@ -541,6 +544,20 @@ impl InitializedCameraPreview {
..Default::default()
});
+ let blur_processor = match cap_camera_effects::BlurProcessor::new(
+ &device,
+ wgpu::TextureFormat::Rgba8Unorm,
+ ) {
+ Ok(bp) => {
+ info!("Camera background blur processor initialized");
+ Some(bp)
+ }
+ Err(e) => {
+ warn!("Failed to initialize camera background blur: {e}");
+ None
+ }
+ };
+
let mut renderer = Renderer {
surface: Some(surface),
surface_config,
@@ -555,6 +572,8 @@ impl InitializedCameraPreview {
uniform_bind_group,
texture: Cached::default(),
aspect_ratio: Cached::default(),
+ blur_processor,
+ blur_source_texture: None,
};
renderer.update_state_uniforms(default_state);
@@ -563,11 +582,7 @@ impl InitializedCameraPreview {
.await;
renderer.reconfigure_gpu_surface(size.0, size.1);
- let initial_surface = renderer.surface.as_ref().and_then(|s| {
- s.get_current_texture()
- .map_err(|err| error!("Error getting camera renderer surface texture: {err:?}"))
- .ok()
- });
+ let initial_surface = renderer.acquire_surface_texture();
if let Some(surface) = initial_surface {
let output_width = 5;
let output_height = 5;
@@ -607,6 +622,8 @@ struct Renderer {
uniform_bind_group: wgpu::BindGroup,
texture: Cached<(u32, u32), PreparedTexture>,
aspect_ratio: Cached<f32>,
+ blur_processor: Option<cap_camera_effects::BlurProcessor>,
+ blur_source_texture: Option<wgpu::Texture>,
}
impl Renderer {
@@ -657,9 +674,7 @@ impl Renderer {
Ok(ReconfigureEvent::Resume) => {
is_paused = false;
while camera_rx.try_recv().is_ok() {}
- if let Some(surface) = &self.surface
- && let Ok(texture) = surface.get_current_texture()
- {
+ if let Some(texture) = self.acquire_surface_texture() {
let (buffer, stride) =
render_solid_frame([0x11, 0x11, 0x11, 0xFF], 5, 5);
PreparedTexture::init(
@@ -775,13 +790,7 @@ impl Renderer {
self.sync_ratio_uniform_and_resize_window_to_it(&window, &state, aspect_ratio)
.await;
- let surface_result = self.surface.as_ref().and_then(|s| {
- s.get_current_texture()
- .map_err(|err| {
- error!("Error getting camera renderer surface texture: {err:?}")
- })
- .ok()
- });
+ let surface_result = self.acquire_surface_texture();
if let Some(surface) = surface_result {
let window_px = (clamp_size(state.size) as u32) * GPU_SURFACE_SCALE;
let output_width = window_px.max(320).min(frame.inner.width());
@@ -805,8 +814,24 @@ impl Renderer {
continue 'main_loop;
}
- self.texture
- .get_or_init((output_width, output_height), || {
+ let frame_data = resampler_frame.data(0);
+ let frame_stride = resampler_frame.stride(0) as u32;
+
+ let blur_mode = blur_mode_from_project(state.background_blur);
+ let blurred = if let Some(mode) = blur_mode {
+ self.run_background_blur(
+ frame_data,
+ frame_stride,
+ output_width,
+ output_height,
+ mode,
+ )
+ } else {
+ false
+ };
+
+ let prepared =
+ self.texture.get_or_init((output_width, output_height), || {
PreparedTexture::init(
self.device.clone(),
self.queue.clone(),
@@ -817,12 +842,43 @@ impl Renderer {
output_width,
output_height,
)
- })
- .render(
- &surface,
- resampler_frame.data(0),
- resampler_frame.stride(0) as u32,
+ });
+
+ if blurred {
+ let blur_output = self
+ .blur_processor
+ .as_mut()
+ .and_then(|p| p.process_returning_output())
+ .expect("blurred flag guarantees output");
+ let mut encoder = self.device.create_command_encoder(
+ &wgpu::CommandEncoderDescriptor {
+ label: Some("Blur Copy"),
+ },
+ );
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: blur_output,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &prepared.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: output_width,
+ height: output_height,
+ depth_or_array_layers: 1,
+ },
);
+ self.queue.submit(std::iter::once(encoder.finish()));
+ prepared.render_no_upload(&surface);
+ } else {
+ prepared.render(&surface, frame_data, frame_stride);
+ }
surface.present();
}
}
@@ -873,9 +929,7 @@ impl Renderer {
}
Err(ReconfigureEvent::Resume) => {
while camera_rx.try_recv().is_ok() {}
- if let Some(surface) = &self.surface
- && let Ok(texture) = surface.get_current_texture()
- {
+ if let Some(texture) = self.acquire_surface_texture() {
let (buffer, stride) = render_solid_frame([0x11, 0x11, 0x11, 0xFF], 5, 5);
PreparedTexture::init(
self.device.clone(),
@@ -899,6 +953,73 @@ impl Renderer {
}
}
+ fn run_background_blur(
+ &mut self,
+ frame_data: &[u8],
+ frame_stride: u32,
+ width: u32,
+ height: u32,
+ mode: cap_camera_effects::BlurMode,
+ ) -> bool {
+ self.ensure_blur_source_texture(width, height);
+
+ let (Some(src_tex), Some(processor)) = (
+ self.blur_source_texture.as_ref(),
+ self.blur_processor.as_mut(),
+ ) else {
+ return false;
+ };
+
+ self.queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: src_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ frame_data,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(frame_stride),
+ rows_per_image: Some(height),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ processor.process(&self.device, &self.queue, src_tex, mode);
+ true
+ }
+
+ fn ensure_blur_source_texture(&mut self, width: u32, height: u32) -> &wgpu::Texture {
+ if self
+ .blur_source_texture
+ .as_ref()
+ .is_none_or(|t| t.width() != width || t.height() != height)
+ {
+ self.blur_source_texture = Some(self.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Blur Source"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ }));
+ }
+ self.blur_source_texture.as_ref().unwrap()
+ }
+
async fn cleanup_for_shutdown(&mut self, window: &WebviewWindow) {
info!("Camera preview shutdown requested. Cleaning up...");
@@ -922,6 +1043,34 @@ impl Renderer {
tokio::time::sleep(Duration::from_millis(50)).await;
}
+ fn acquire_surface_texture(&mut self) -> Option<wgpu::SurfaceTexture> {
+ let surface = self.surface.as_ref()?;
+ match surface.get_current_texture() {
+ Ok(texture) => Some(texture),
+ Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
+ tracing::warn!("Camera preview surface lost/outdated; reconfiguring");
+ surface.configure(&self.device, &self.surface_config);
+ match surface.get_current_texture() {
+ Ok(texture) => Some(texture),
+ Err(err) => {
+ tracing::error!(
+ "Camera preview surface still failing after reconfigure: {err:?}"
+ );
+ None
+ }
+ }
+ }
+ Err(wgpu::SurfaceError::Timeout) => {
+ tracing::debug!("Camera preview surface acquire timed out; skipping frame");
+ None
+ }
+ Err(err) => {
+ tracing::error!("Error getting camera renderer surface texture: {err:?}");
+ None
+ }
+ }
+ }
+
fn reconfigure_gpu_surface(&mut self, window_width: u32, window_height: u32) {
self.surface_config.width = if window_width > 0 {
window_width * GPU_SURFACE_SCALE
@@ -1164,6 +1313,16 @@ mod tests {
}
}
+fn blur_mode_from_project(
+ mode: cap_project::BackgroundBlurMode,
+) -> Option<cap_camera_effects::BlurMode> {
+ match mode {
+ cap_project::BackgroundBlurMode::Off => None,
+ cap_project::BackgroundBlurMode::Light => Some(cap_camera_effects::BlurMode::Light),
+ cap_project::BackgroundBlurMode::Heavy => Some(cap_camera_effects::BlurMode::Heavy),
+ }
+}
+
fn render_solid_frame(color: [u8; 4], width: u32, height: u32) -> (Vec<u8>, u32) {
let pixel_count = (height * width) as usize;
let buffer: Vec<u8> = color
@@ -1243,6 +1402,45 @@ impl PreparedTexture {
}
}
+ pub fn render_no_upload(&self, surface: &SurfaceTexture) {
+ let surface_view = surface
+ .texture
+ .create_view(&wgpu::TextureViewDescriptor::default());
+
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
+
+ {
+ let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &surface_view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: 0.0,
+ g: 0.0,
+ b: 0.0,
+ a: 0.0,
+ }),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+
+ render_pass.set_pipeline(&self.render_pipeline);
+ render_pass.set_bind_group(0, &self.bind_group, &[]);
+ render_pass.set_bind_group(1, &self.uniform_bind_group, &[]);
+ render_pass.draw(0..6, 0..1);
+ }
+
+ self.queue.submit(Some(encoder.finish()));
+ }
+
pub fn render(&self, surface: &SurfaceTexture, buffer: &[u8], stride: u32) {
let surface_view = surface
.texture