Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Native camera preview (#777)
Oscar Beaumont74e8d412f6d3
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 61d8475ad..fbd74c573 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -29,7 +29,7 @@ There are many ways to contribute to Cap. You can:Before anything else, make sure you have the following installed:- Node Version 20+-- Rust 1.84.0++- Rust 1.88.0+- pnpm 8.10.5+- Docker ([OrbStack](https://orbstack.dev/) recommended)diff --git a/Cargo.lock b/Cargo.lockindex a9c4b6fbb..53ec989ba 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -831,9 +831,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"[[package]]name = "bytemuck"-version = "1.22.0"+version = "1.23.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540"+checksum = "5c76a5792e44e4abe34d3abf15636779261d45a7450612059293d1d2cfc63422"dependencies = ["bytemuck_derive",]@@ -1000,6 +1000,7 @@ dependencies = ["anyhow","axum","base64 0.22.1",+ "bytemuck","cap-audio","cap-editor","cap-export",@@ -1074,6 +1075,7 @@ dependencies = ["tracing-appender","tracing-subscriber","uuid",+ "wgpu","whisper-rs","windows 0.58.0","windows-sys 0.59.0",diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 8b52e94aa..c90a428a6 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -3,7 +3,7 @@ name = "cap-desktop"version = "0.3.60"description = "Beautiful screen recordings, owned by you."authors = ["you"]-edition = "2021"+edition = "2024"[lints]workspace = true@@ -98,6 +98,8 @@ cap-fail = { version = "0.1.0", path = "../../../crates/fail" }tokio-stream = { version = "0.1.17", features = ["sync"] }md5 = "0.7.0"tokio-util = "0.7.15"+wgpu.workspace = true+bytemuck = "1.23.1"[target.'cfg(target_os = "macos")'.dependencies]core-graphics = "0.24.0"diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rsindex 6b5ad7c95..dd2a758c2 100644--- a/apps/desktop/src-tauri/src/camera.rs+++ b/apps/desktop/src-tauri/src/camera.rs@@ -1,70 +1,849 @@-use cap_media::{feeds::RawCameraFrame, frame_ws::WSFrame};-use flume::Sender;-use tokio_util::sync::CancellationToken;--pub async fn create_camera_preview_ws() -> (Sender<RawCameraFrame>, u16, CancellationToken) {- let (camera_tx, mut _camera_rx) = flume::bounded::<RawCameraFrame>(4);- let (_camera_tx, camera_rx) = flume::bounded::<WSFrame>(4);- std::thread::spawn(move || {- use ffmpeg::format::Pixel;-- let mut converter: Option<(Pixel, ffmpeg::software::scaling::Context)> = None;-- while let Ok(raw_frame) = _camera_rx.recv() {- let mut frame = raw_frame.frame;-- if frame.format() != Pixel::RGBA || frame.width() > 1280 || frame.height() > 720 {- let converter = match &mut converter {- Some((format, converter))- if *format == frame.format()- && converter.input().width == frame.width()- && converter.input().height == frame.height() =>+use anyhow::Context;+use cap_media::feeds::RawCameraFrame;+use ffmpeg::{+ format::{self, Pixel},+ frame,+ software::scaling,+};+use flume::Receiver;+use futures::{executor::block_on, future::Either};+use serde::{Deserialize, Serialize};+use specta::Type;+use std::{+ pin::pin,+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+ thread,+ time::Duration,+};+use tauri::{LogicalPosition, LogicalSize, Manager, PhysicalSize, WebviewWindow, Wry};+use tauri_plugin_store::Store;+use tokio::sync::{broadcast, oneshot};+use tracing::error;+use wgpu::{CompositeAlphaMode, SurfaceTexture};++static TOOLBAR_HEIGHT: f32 = 56.0; // also defined in Typescript++// We scale up the GPU surfaces resolution by this amount from the OS window's size.+// This smooths out the curved edges of the window.+// Basically poor man's MSAA+static GPU_SURFACE_SCALE: u32 = 4;++#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Type)]+#[serde(rename_all = "lowercase")]+pub enum CameraPreviewSize {+ #[default]+ Sm,+ Lg,+}++#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Type)]+#[serde(rename_all = "lowercase")]+pub enum CameraPreviewShape {+ #[default]+ Round,+ Square,+ Full,+}++#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Type)]+pub struct CameraWindowState {+ size: CameraPreviewSize,+ shape: CameraPreviewShape,+ mirrored: bool,+}++pub struct CameraPreview {+ reconfigure: (+ broadcast::Sender<Option<(u32, u32)>>,+ broadcast::Receiver<Option<(u32, u32)>>,+ ),+ loading: Arc<AtomicBool>,+ store: Arc<Store<Wry>>,+}++impl CameraPreview {+ pub fn init(manager: &impl Manager<Wry>) -> tauri_plugin_store::Result<Self> {+ Ok(Self {+ reconfigure: broadcast::channel(1),+ loading: Arc::new(AtomicBool::new(false)),+ store: tauri_plugin_store::StoreBuilder::new(manager, "cameraPreview").build()?,+ })+ }++ pub async fn init_preview_window(+ &self,+ window: WebviewWindow,+ camera_rx: Receiver<RawCameraFrame>,+ ) -> anyhow::Result<()> {+ self.loading.store(true, Ordering::Relaxed);++ let mut renderer = Renderer::init(window.clone()).await?;++ let store = self.store.clone();+ let mut reconfigure = self.reconfigure.1.resubscribe();+ let loading_state = self.loading.clone();+ thread::spawn(move || {+ let mut window_visible = false;+ let mut first = true;+ let mut loading = true;+ let mut window_size = None;+ let mut resampler_frame = Cached::default();+ let mut aspect_ratio = None;+ let Ok(mut scaler) = scaling::Context::get(+ Pixel::RGBA,+ 1,+ 1,+ Pixel::RGBA,+ 1,+ 1,+ scaling::Flags::empty(),+ )+ .map_err(|err| error!("Error initializing ffmpeg scaler: {err:?}")) else {+ return;+ };++ while let Some((frame, reconfigure)) = block_on({+ let camera_rx = &camera_rx;+ let reconfigure = &mut reconfigure;++ async {+ // Triggers the first paint+ if first {+ // We don't set `first = false` as that is done within the loop.+ return Some((None, true));+ }++ match futures::future::select(+ pin!(camera_rx.recv_async()),+ pin!(reconfigure.recv()),+ )+ .await{- converter+ Either::Left((frame, _)) => frame.ok().map(|f| (Some(f.frame), false)),+ Either::Right((event, _)) => {+ if let Ok(Some((width, height))) = event {+ window_size = Some((width, height));+ }++ Some((None, true))+ }}- _ => {- &mut converter- .insert((- frame.format(),- ffmpeg::software::scaling::Context::get(- frame.format(),- frame.width(),- frame.height(),- Pixel::RGBA,- 1280,- (1280.0 / (frame.width() as f64 / frame.height() as f64))- as u32,- ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR,- )- .unwrap(),- ))- .1+ }+ }) {+ let window_resize_required =+ if reconfigure && renderer.refresh_state(&store) || first {+ first = false;+ renderer.update_state_uniforms();+ true+ } else if let Some(frame) = frame.as_ref()+ && renderer.frame_info.update_key_and_should_init((+ frame.format(),+ frame.width(),+ frame.height(),+ ))+ {+ aspect_ratio = Some(frame.width() as f32 / frame.height() as f32);++ true+ } else {+ false+ };++ let camera_aspect_ratio =+ aspect_ratio.unwrap_or(if renderer.state.shape == CameraPreviewShape::Full {+ 16.0 / 9.0+ } else {+ 1.0+ });++ if window_resize_required {+ renderer.update_camera_aspect_ratio_uniforms(camera_aspect_ratio);++ match renderer.resize_window(camera_aspect_ratio) {+ Ok(size) => window_size = Some(size),+ Err(err) => {+ error!("Error updating window size: {err:?}");+ continue;+ }}+ }++ let (window_width, window_height) = match window_size {+ Some(s) => s,+ // Calling `window.outer_size` will hang when a native menu is opened.+ // So we only callback to it if absolute required as it could randomly hang.+ None => match renderer+ .window+ .inner_size()+ .and_then(|size| Ok(size.to_logical(renderer.window.scale_factor()?)))+ {+ Ok(size) => {+ window_size = Some((size.width, size.height));+ (size.width, size.height)+ }+ Err(err) => {+ error!("Error getting window size: {err:?}");+ continue;+ }+ },+ };++ if let Err(err) = renderer.reconfigure_gpu_surface(window_width, window_height) {+ error!("Error reconfiguring GPU surface: {err:?}");+ continue;+ }++ if let Ok(surface) = renderer+ .surface+ .get_current_texture()+ .map_err(|err| error!("Error getting camera renderer surface texture: {err:?}"))+ {+ let output_width = 1280;+ let output_height = (1280.0 / camera_aspect_ratio) as u32;++ let new_texture_value = if let Some(frame) = frame {+ if loading == true {+ loading_state.store(false, Ordering::Relaxed);+ loading = false;+ }++ let resampler_frame = resampler_frame+ .get_or_init((output_width, output_height), || frame::Video::empty());++ scaler.cached(+ frame.format(),+ frame.width(),+ frame.height(),+ format::Pixel::RGBA,+ output_width,+ output_height,+ ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR,+ );++ if let Err(err) = scaler.run(&frame, resampler_frame) {+ error!("Error rescaling frame with ffmpeg: {err:?}");+ continue;+ }++ Some((+ resampler_frame.data(0).to_vec(),+ resampler_frame.stride(0) as u32,+ ))+ } else if loading {+ let (buffer, stride) = render_solid_frame(+ [0x11, 0x11, 0x11, 0xFF], // #111111+ output_width,+ output_height,+ );++ Some((buffer, stride))+ } else {+ None // This will reuse the existing texture+ };++ renderer.render(+ surface,+ new_texture_value.as_ref().map(|(b, s)| (&**b, *s)),+ output_width,+ output_height,+ );+ }++ if !window_visible {+ window_visible = true;+ if let Err(err) = renderer.window.show() {+ error!("Failed to show camera preview window: {}", err);+ }+ }+ }++ window.close().ok();+ });++ Ok(())+ }++ /// Save the current state of the camera window.+ pub fn save(&self, state: &CameraWindowState) -> tauri_plugin_store::Result<()> {+ self.store.set("state", serde_json::to_value(&state)?);+ self.store.save()?;+ self.reconfigure.0.send(None).ok();+ Ok(())+ }++ /// Wait for the camera to load.+ pub async fn wait_for_camera_to_load(&self) {+ // The webview is generally slow to load so it's rare this will actually loop.+ while self.loading.load(Ordering::Relaxed) {+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }++ /// Update the size of the window.+ /// Using `window.outer_size` just never resolves when a native menu is open.+ pub fn update_window_size(&self, width: u32, height: u32) {+ self.reconfigure.0.send(Some((width, height))).ok();+ }+}++struct Renderer {+ surface: wgpu::Surface<'static>,+ surface_config: wgpu::SurfaceConfiguration,+ render_pipeline: wgpu::RenderPipeline,+ device: wgpu::Device,+ queue: wgpu::Queue,+ sampler: wgpu::Sampler,+ bind_group_layout: wgpu::BindGroupLayout,+ uniform_buffer: wgpu::Buffer,+ window_uniform_buffer: wgpu::Buffer,+ camera_uniform_buffer: wgpu::Buffer,+ uniform_bind_group: wgpu::BindGroup,+ window: tauri::WebviewWindow<Wry>,++ state: CameraWindowState,+ frame_info: Cached<(format::Pixel, u32, u32)>,+ surface_size: Cached<(u32, u32)>,+ texture: Cached<(u32, u32), (wgpu::Texture, wgpu::TextureView, wgpu::BindGroup)>,+}++impl Renderer {+ /// Initialize a new renderer for a specific Tauri window.+ async fn init(window: WebviewWindow) -> anyhow::Result<Self> {+ let size = window+ .inner_size()+ .with_context(|| "Error getting the window size")?+ .to_logical(+ window+ .scale_factor()+ .with_context(|| "Error getting the window scale")?,+ );++ let (tx, rx) = oneshot::channel();+ window+ .run_on_main_thread({+ let window = window.clone();+ move || {+ let instance = wgpu::Instance::default();+ let surface = instance.create_surface(window.clone());+ tx.send((instance, surface)).ok();+ }+ })+ .with_context(|| "Failed to initialize wgpu instance")?;++ let (instance, surface) = rx+ .await+ .with_context(|| "Failed to receive initialized wgpu instance and surface")?;+ let surface = surface.with_context(|| "Failed to initialize wgpu surface")?;++ let adapter = instance+ .request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::default(),+ force_fallback_adapter: false,+ compatible_surface: Some(&surface),+ })+ .await+ .with_context(|| "Failed to find an appropriate wgpu adapter")?;++ let (device, queue) = adapter+ .request_device(&wgpu::DeviceDescriptor {+ label: None,+ required_features: wgpu::Features::empty(),+ required_limits: wgpu::Limits::downlevel_webgl2_defaults()+ .using_resolution(adapter.limits()),+ memory_hints: Default::default(),+ trace: wgpu::Trace::Off,+ })+ .await+ .with_context(|| "Failed to create wgpu device")?;++ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: None,+ source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!(+ "./camera.wgsl"+ ))),+ });++ let uniform_bind_group_layout =+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("Uniform Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, // Add FRAGMENT here+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ ],+ });++ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("Texture Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });++ let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("Uniform Buffer"),+ size: std::mem::size_of::<StateUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ let window_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("Window Uniform Buffer"),+ size: std::mem::size_of::<WindowUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ let camera_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("Camera Uniform Buffer"),+ size: std::mem::size_of::<CameraUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("Uniform Bind Group"),+ layout: &uniform_bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: uniform_buffer.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: window_uniform_buffer.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: camera_uniform_buffer.as_entire_binding(),+ },+ ],+ });++ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: None,+ bind_group_layouts: &[&bind_group_layout, &uniform_bind_group_layout],+ push_constant_ranges: &[],+ });++ let swapchain_format = wgpu::TextureFormat::Bgra8Unorm;+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: None,+ layout: Some(&pipeline_layout),+ vertex: wgpu::VertexState {+ module: &shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: swapchain_format,+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: Default::default(),+ multiview: None,+ cache: None,+ });++ let surface_config = wgpu::SurfaceConfiguration {+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ format: swapchain_format,+ width: size.width,+ height: size.height,+ present_mode: wgpu::PresentMode::Fifo,+ alpha_mode: CompositeAlphaMode::PostMultiplied,+ view_formats: vec![],+ desired_maximum_frame_latency: 2,+ };++ surface.configure(&device, &surface_config);++ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ address_mode_w: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::FilterMode::Linear,+ ..Default::default()+ });++ Ok(Self {+ surface,+ surface_config,+ render_pipeline,+ device,+ queue,+ sampler,+ bind_group_layout,+ uniform_buffer,+ window_uniform_buffer,+ camera_uniform_buffer,+ uniform_bind_group,+ window,++ state: Default::default(),+ frame_info: Cached::default(),+ surface_size: Cached::default(),+ texture: Cached::default(),+ })+ }++ /// Update the local cache of the camera state+ fn refresh_state(&mut self, store: &Store<tauri::Wry>) -> bool {+ let current = self.state.clone();++ self.state = store+ .get("state")+ .and_then(|v| serde_json::from_value(v).ok())+ .unwrap_or_default();++ current != self.state+ }++ /// Resize the OS window to the correct size+ fn resize_window(&self, aspect: f32) -> tauri::Result<(u32, u32)> {+ let base: f32 = if self.state.size == CameraPreviewSize::Sm {+ 230.0+ } else {+ 400.0+ };+ let window_width = if self.state.shape == CameraPreviewShape::Full {+ if aspect >= 1.0 { base * aspect } else { base }+ } else {+ base+ };+ let window_height = if self.state.shape == CameraPreviewShape::Full {+ if aspect >= 1.0 { base } else { base / aspect }+ } else {+ base+ } + TOOLBAR_HEIGHT;++ let (monitor_size, monitor_offset, monitor_scale_factor): (+ PhysicalSize<u32>,+ LogicalPosition<u32>,+ _,+ ) = if let Some(monitor) = self.window.current_monitor()? {+ let size = monitor.position().to_logical(monitor.scale_factor());+ (monitor.size().clone(), size, monitor.scale_factor())+ } else {+ (PhysicalSize::new(640, 360), LogicalPosition::new(0, 0), 1.0)+ };++ let x = (monitor_size.width as f64 / monitor_scale_factor - window_width as f64 - 100.0)+ as u32+ + monitor_offset.x;+ let y = (monitor_size.height as f64 / monitor_scale_factor - window_height as f64 - 100.0)+ as u32+ + monitor_offset.y;++ self.window+ .set_size(LogicalSize::new(window_width, window_height))?;+ self.window.set_position(LogicalPosition::new(x, y))?;++ Ok((window_width as u32, window_height as u32))+ }++ /// Reconfigure the GPU surface if the window has changed size+ fn reconfigure_gpu_surface(+ &mut self,+ window_width: u32,+ window_height: u32,+ ) -> tauri::Result<()> {+ self.surface_size+ .get_or_init((window_width, window_height), || {+ self.surface_config.width = if window_width > 0 {+ window_width * GPU_SURFACE_SCALE+ } else {+ 1+ };+ self.surface_config.height = if window_height > 0 {+ window_height * GPU_SURFACE_SCALE+ } else {+ 1};+ self.surface.configure(&self.device, &self.surface_config);- let mut new_frame = ffmpeg::util::frame::Video::new(- Pixel::RGBA,- converter.output().width,- converter.output().height,+ let window_uniforms = WindowUniforms {+ window_height: window_height as f32,+ window_width: window_width as f32,+ toolbar_percentage: (TOOLBAR_HEIGHT * GPU_SURFACE_SCALE as f32)+ / self.surface_config.height as f32,+ _padding: 0.0,+ };+ self.queue.write_buffer(+ &self.window_uniform_buffer,+ 0,+ bytemuck::cast_slice(&[window_uniforms]),);+ });++ Ok(())+ }++ /// Update the uniforms which hold the camera preview state+ fn update_state_uniforms(&self) {+ let state_uniforms = StateUniforms {+ shape: match self.state.shape {+ CameraPreviewShape::Round => 0.0,+ CameraPreviewShape::Square => 1.0,+ CameraPreviewShape::Full => 2.0,+ },+ size: match self.state.size {+ CameraPreviewSize::Sm => 0.0,+ CameraPreviewSize::Lg => 1.0,+ },+ mirrored: if self.state.mirrored { 1.0 } else { 0.0 },+ _padding: 0.0,+ };+ self.queue.write_buffer(+ &self.uniform_buffer,+ 0,+ bytemuck::cast_slice(&[state_uniforms]),+ );+ }++ /// Update the uniforms which hold the camera aspect ratio+ fn update_camera_aspect_ratio_uniforms(&self, camera_aspect_ratio: f32) {+ let camera_uniforms = CameraUniforms {+ camera_aspect_ratio,+ _padding: 0.0,+ };+ self.queue.write_buffer(+ &self.camera_uniform_buffer,+ 0,+ bytemuck::cast_slice(&[camera_uniforms]),+ );+ }++ /// Render the camera preview to the window.+ fn render(+ &mut self,+ surface: SurfaceTexture,+ new_texture_value: Option<(&[u8], u32)>,+ width: u32,+ height: u32,+ ) {+ let surface_view = surface+ .texture+ .create_view(&wgpu::TextureViewDescriptor::default());- converter.run(&frame, &mut new_frame).unwrap();+ let surface_width = surface.texture.width();+ let surface_height = surface.texture.height();- frame = new_frame;+ 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, // Some(&surface_view),+ 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,+ });++ // Get or reinitialize the texture if necessary+ let (texture, _, bind_group) = &*self.texture.get_or_init((width, height), || {+ let texture = self.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("Camera Texture"),+ 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,+ view_formats: &[],+ });++ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());++ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("Texture Bind Group"),+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(&texture_view),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::Sampler(&self.sampler),+ },+ ],+ });++ (texture, texture_view, bind_group)+ });++ if let Some((buffer, stride)) = new_texture_value {+ self.queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ &buffer,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(stride),+ rows_per_image: Some(height),+ },+ wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ );}- _camera_tx- .send(WSFrame {- data: frame.data(0).to_vec(),- width: frame.width(),- height: frame.height(),- stride: frame.stride(0) as u32,- })- .ok();+ render_pass.set_pipeline(&self.render_pipeline);+ render_pass.set_bind_group(0, bind_group, &[]);+ render_pass.set_bind_group(1, &self.uniform_bind_group, &[]);+ render_pass.draw(0..6, 0..1);}- });- // _shutdown needs to be kept alive to keep the camera ws running- let (camera_ws_port, _shutdown) = cap_media::frame_ws::create_frame_ws(camera_rx.clone()).await;- (camera_tx, camera_ws_port, _shutdown)+ self.queue.submit(Some(encoder.finish()));+ surface.present();+ }+}++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+ .iter()+ .cycle()+ .take(pixel_count * 4)+ .copied()+ .collect();++ (buffer, 4 * width)+}++struct Cached<K, V = ()> {+ value: Option<(K, V)>,+}++impl<K, V> Default for Cached<K, V> {+ fn default() -> Self {+ Self { value: None }+ }+}++impl<K: PartialEq, V> Cached<K, V> {+ pub fn get_or_init<'a>(&'a mut self, key: K, init: impl FnOnce() -> V) -> &'a mut V {+ if self.value.as_ref().is_none_or(|(k, _)| *k != key) {+ self.value = Some((key, init()));+ }++ &mut self.value.as_mut().expect("checked above").1+ }+}++impl<K: PartialEq> Cached<K, ()> {+ /// Updates the key and returns `true` when the key was changed.+ pub fn update_key_and_should_init(&mut self, key: K) -> bool {+ if self.value.as_ref().is_none_or(|(k, _)| *k != key) {+ self.value = Some((key, ()));+ true+ } else {+ false+ }+ }+}++#[repr(C)]+#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]+struct StateUniforms {+ shape: f32,+ size: f32,+ mirrored: f32,+ _padding: f32,+}++#[repr(C)]+#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]+struct WindowUniforms {+ window_height: f32,+ window_width: f32,+ toolbar_percentage: f32,+ _padding: f32,+}++#[repr(C)]+#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]+struct CameraUniforms {+ camera_aspect_ratio: f32,+ _padding: f32,}diff --git a/apps/desktop/src-tauri/src/camera.wgsl b/apps/desktop/src-tauri/src/camera.wgslnew file mode 100644index 000000000..a55893f3f--- /dev/null+++ b/apps/desktop/src-tauri/src/camera.wgsl@@ -0,0 +1,180 @@+struct StateUniforms {+ shape: f32,+ size: f32,+ mirrored: f32,+ _padding: f32,+}++struct WindowUniforms {+ window_height: f32,+ window_width: f32,+ toolbar_percentage: f32,+ _padding: f32,+}++struct CameraUniforms {+ camera_aspect_ratio: f32,+ _padding: f32,+}++@group(1) @binding(0)+var<uniform> uniforms: StateUniforms;++@group(1) @binding(1)+var<uniform> window_uniforms: WindowUniforms;++@group(1) @binding(2)+var<uniform> camera_uniforms: CameraUniforms;++@group(0) @binding(0)+var t_camera: texture_2d<f32>;++@group(0) @binding(1)+var s_camera: sampler;++struct VertexOutput {+ @builtin(position) position: vec4<f32>,+ @location(0) uv: vec2<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {+ var out: VertexOutput;++ // We use the vertex_index to determine the position of each vertex.+ // This maps the 6 vertex indices to NDC coordinates for a fullscreen quad.+ var indexes = array<vec2<f32>, 6>(+ vec2<f32>(-1.0, -1.0),// First triangle (bottom-left)+ vec2<f32>(1.0, -1.0),+ vec2<f32>(-1.0, 1.0),+ vec2<f32>(-1.0, 1.0), // Second triangle (top-right)+ vec2<f32>(1.0, -1.0),+ vec2<f32>(1.0, 1.0),+ );+ var uv = array<vec2<f32>, 6>(+ vec2<f32>(0.0, 1.0),+ vec2<f32>(1.0, 1.0),+ vec2<f32>(0.0, 0.0),+ vec2<f32>(0.0, 0.0),+ vec2<f32>(1.0, 1.0),+ vec2<f32>(1.0, 0.0),+ );++ var pos: vec2<f32> = indexes[idx];+ pos.y *= (1.0 - window_uniforms.toolbar_percentage);+ pos.y -= window_uniforms.toolbar_percentage;++ out.position = vec4<f32>(pos, 0.0, 1.0);+ out.uv = uv[idx];+ return out;+}++@fragment+fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {+ // Calculate the effective rendering dimensions (accounting for toolbar)+ let effective_height = window_uniforms.window_height * (1.0 - window_uniforms.toolbar_percentage);+ let crop_width = window_uniforms.window_width;+ let crop_height = effective_height;+ let crop_aspect = crop_width / crop_height;+ let camera_aspect = camera_uniforms.camera_aspect_ratio;++ // Calculate UV coordinates for proper "cover" behavior+ var final_uv = in.uv;++ // Determine which dimension needs to be scaled to cover the crop region+ if (camera_aspect > crop_aspect) {+ // Camera is wider than crop region - scale horizontally+ let scale = crop_aspect / camera_aspect;+ let offset = (1.0 - scale) * 0.5;+ final_uv.x = final_uv.x * scale + offset;+ } else {+ // Camera is taller than crop region - scale vertically+ let scale = camera_aspect / crop_aspect;+ let offset = (1.0 - scale) * 0.5;+ final_uv.y = final_uv.y * scale + offset;+ }++ // Apply mirroring if enabled+ if (uniforms.mirrored == 1.0) {+ final_uv.x = 1.0 - final_uv.x;+ }++ // Shape constants: 0 = Round, 1 = Square, 2 = Full+ // Size constants: 0 = Sm, 1 = Lg+ let shape = uniforms.shape;+ let size = uniforms.size;++ // Convert UV coordinates to center-based coordinates [-1, 1]+ let center_uv = (in.uv - 0.5) * 2.0;++ var mask = 1.0;++ if (shape == 0.0) {+ // Round shape with enhanced anti-aliasing+ let distance = length(center_uv);+ let radius = 1.0;++ // Multi-level anti-aliasing approach+ let pixel_size = length(fwidth(center_uv));+ let aa_width = max(pixel_size, 0.003); // Reduced minimum AA width++ // Primary edge calculation+ let edge_distance = distance - radius;+ mask = 1.0 - smoothstep(-aa_width, aa_width, edge_distance);++ } else if (shape == 1.0) {+ // Square shape with enhanced corner anti-aliasing+ let corner_radius = select(0.1, 0.12, size == 1.0);+ let abs_uv = abs(center_uv);+ let corner_pos = abs_uv - (1.0 - corner_radius);+ let corner_dist = length(max(corner_pos, vec2<f32>(0.0, 0.0)));++ // Enhanced anti-aliasing for corners+ let pixel_size = length(fwidth(center_uv));+ let aa_width = max(pixel_size, 0.002);++ let edge_distance = corner_dist - corner_radius;+ mask = 1.0 - smoothstep(-aa_width, aa_width, edge_distance);+ } else if (shape == 2.0) {+ // Full shape with aspect ratio-corrected rounded corners+ let window_aspect = window_uniforms.window_width / window_uniforms.window_height;+ let corner_radius = select(0.08, 0.1, size == 1.0); // radius based on size (8% for small, 10% for large)++ let abs_uv = abs(center_uv);+ let corner_pos = abs_uv - (1.0 - corner_radius);++ // Use aspect-ratio aware distance calculation for circular corners+ var adjusted_corner_pos = max(corner_pos, vec2<f32>(0.0, 0.0));+ if (window_aspect > 1.0) {+ // For wide windows, scale X component to make distance calculation circular+ adjusted_corner_pos.x *= window_aspect;+ } else {+ // For tall windows, scale Y component to make distance calculation circular+ adjusted_corner_pos.y /= window_aspect;+ }++ let corner_dist = length(adjusted_corner_pos);++ // Enhanced anti-aliasing for corners+ let pixel_size = length(fwidth(center_uv));+ let aa_width = max(pixel_size, 0.002);++ let edge_distance = corner_dist - corner_radius;+ mask = 1.0 - smoothstep(-aa_width, aa_width, edge_distance);+ } else {+ // For any other shape, default to no masking (rectangular)+ mask = 1.0;+ }++ // Apply the mask with cleaner alpha handling to reduce ghosting+ if (mask < 0.05) {+ return vec4<f32>(0.0, 0.0, 0.0, 0.0);+ }++ // Sample the camera texture+ let camera_color = textureSample(t_camera, s_camera, final_uv);++ // Use sharper alpha cutoff to reduce ghosting+ let final_alpha = select(1.0, mask, mask < 0.95);+ return vec4<f32>(camera_color.rgb, final_alpha);+}diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rsindex 9ac4f022e..10b7f0f23 100644--- a/apps/desktop/src-tauri/src/captions.rs+++ b/apps/desktop/src-tauri/src/captions.rs@@ -2,10 +2,9 @@ use anyhow::Result;use cap_audio::AudioData;use cap_project;use ffmpeg::{- codec as avcodec,+ ChannelLayout, codec as avcodec,format::{self as avformat},software::resampling,- ChannelLayout,};use reqwest::Client;use serde::{Deserialize, Serialize};diff --git a/apps/desktop/src-tauri/src/deeplink_actions.rs b/apps/desktop/src-tauri/src/deeplink_actions.rsindex 101e69dc1..e3f6fd229 100644--- a/apps/desktop/src-tauri/src/deeplink_actions.rs+++ b/apps/desktop/src-tauri/src/deeplink_actions.rs@@ -2,7 +2,9 @@ use cap_recording::RecordingMode;use serde::{Deserialize, Serialize};use tauri::{AppHandle, Manager, Url};-use crate::{recording::StartRecordingInputs, windows::ShowCapWindow, App, ArcLock};+use crate::{+ App, ArcLock, camera::CameraPreview, recording::StartRecordingInputs, windows::ShowCapWindow,+};#[derive(Debug, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]@@ -105,8 +107,10 @@ impl DeepLinkAction {mode,} => {let state = app.state::<ArcLock<App>>();+ let camera_preview = app.state::<CameraPreview>();- crate::set_camera_input(state.clone(), camera_label).await?;+ crate::set_camera_input(app.clone(), state.clone(), camera_preview, camera_label)+ .await?;crate::set_mic_input(state.clone(), mic_label).await?;use cap_media::sources::ScreenCaptureTarget;diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rsindex 9dd7295e7..d75f59276 100644--- a/apps/desktop/src-tauri/src/editor_window.rs+++ b/apps/desktop/src-tauri/src/editor_window.rs@@ -1,7 +1,7 @@use std::{collections::HashMap, ops::Deref, path::PathBuf, sync::Arc};use cap_editor::EditorInstance;-use tauri::{ipc::CommandArg, Manager, Runtime, Window};+use tauri::{Manager, Runtime, Window, ipc::CommandArg};use tokio::sync::RwLock;use crate::create_editor_instance_impl;diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex 984f6d11e..a6621463a 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -1,4 +1,4 @@-use crate::{get_video_metadata, FramesRendered};+use crate::{FramesRendered, get_video_metadata};use cap_export::ExporterBase;use cap_project::{RecordingMeta, XY};use serde::Deserialize;diff --git a/apps/desktop/src-tauri/src/flags.rs b/apps/desktop/src-tauri/src/flags.rsindex dbc06054b..0d763f502 100644--- a/apps/desktop/src-tauri/src/flags.rs+++ b/apps/desktop/src-tauri/src/flags.rs@@ -1,8 +1,8 @@pub mod plugin {use cap_flags::FLAGS;use tauri::{- plugin::{Builder, TauriPlugin},Runtime,+ plugin::{Builder, TauriPlugin},};pub fn init<R: Runtime>() -> TauriPlugin<R> {diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rsindex a5c69a9b5..fde775035 100644--- a/apps/desktop/src-tauri/src/hotkeys.rs+++ b/apps/desktop/src-tauri/src/hotkeys.rs@@ -1,4 +1,4 @@-use crate::{recording, RequestStartRecording};+use crate::{RequestStartRecording, recording};use global_hotkey::HotKeyState;use serde::{Deserialize, Serialize};use specta::Type;diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex dc5f5a9cc..11151bf4a 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -22,7 +22,7 @@ mod windows;use audio::AppSounds;use auth::{AuthStore, AuthenticationInvalid, Plan};-use camera::create_camera_preview_ws;+use camera::{CameraPreview, CameraWindowState};use cap_editor::EditorInstance;use cap_editor::EditorState;use cap_media::feeds::RawCameraFrame;@@ -69,27 +69,27 @@ use tauri_plugin_notification::{NotificationExt, PermissionState};use tauri_plugin_opener::OpenerExt;use tauri_plugin_shell::ShellExt;use tauri_specta::Event;+use tokio::sync::mpsc;use tokio::sync::{Mutex, RwLock};use tracing::debug;use tracing::error;+use tracing_subscriber::Layer;use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;-use tracing_subscriber::Layer;-use upload::{create_or_get_video, upload_image, upload_video, S3UploadMeta};+use upload::{S3UploadMeta, create_or_get_video, upload_image, upload_video};use web_api::ManagerExt as WebManagerExt;-use windows::set_window_transparent;use windows::EditorWindowIds;+use windows::set_window_transparent;use windows::{CapWindowId, ShowCapWindow};#[derive(specta::Type, Serialize)]#[serde(rename_all = "camelCase")]pub struct App {- #[serde(skip)]- camera_tx: flume::Sender<RawCameraFrame>,- camera_ws_port: u16,#[serde(skip)]camera_feed: Option<Arc<Mutex<CameraFeed>>>,#[serde(skip)]+ camera_feed_initialization: Option<mpsc::Sender<()>>,+ #[serde(skip)]mic_feed: Option<AudioInputFeed>,#[serde(skip)]mic_samples_tx: AudioInputSamplesSender,@@ -182,7 +182,9 @@ async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> R#[tauri::command]#[specta::specta]async fn set_camera_input(+ app_handle: AppHandle,state: MutableState<'_, App>,+ camera_preview: State<'_, CameraPreview>,label: Option<String>,) -> Result<bool, String> {let mut app = state.write().await;@@ -198,41 +200,65 @@ async fn set_camera_input(Ok(true)}(Some(label), None) => {- let camera_tx = app.camera_tx.clone();+ let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);+ if let Some(cancel) = app.camera_feed_initialization.as_ref() {+ // Ask currently running setup to abort+ cancel.send(()).await.ok();++ // We can assume a window was already initialized.+ // Stop it so we can recreate it with the correct `camera_tx`+ if let Some(win) = CapWindowId::Camera.get(&app_handle) {+ win.close().unwrap(); // TODO: Error handling+ };+ } else {+ app.camera_feed_initialization = Some(shutdown_tx);+ }++ let window = ShowCapWindow::Camera.show(&app_handle).await.unwrap();+ if let Some(win) = CapWindowId::Main.get(&app_handle) {+ win.set_focus().ok();+ };++ let (camera_tx, camera_rx) = flume::bounded::<RawCameraFrame>(4);+ camera_preview+ .init_preview_window(window, camera_rx)+ .await+ .unwrap();+drop(app);- let init_rx = CameraFeed::init_async(label);-- loop {- tokio::select! {- result = init_rx.recv_async() => {- match result {- Ok(Ok(feed)) => {- let mut app = state.write().await;- if app.camera_feed.is_none() {- feed.attach(camera_tx);- app.camera_feed = Some(Arc::new(Mutex::new(feed)));- return Ok(true);- } else {- return Ok(false);- }- }- Ok(Err(e)) => return Err(e.to_string()),- Err(_) => return Ok(false),- }+ let fut = CameraFeed::init(label);++ tokio::select! {+ result = fut => {+ let feed = result.map_err(|err| err.to_string())?;+ let mut app = state.write().await;++ if let Some(cancel) = app.camera_feed_initialization.take() {+ cancel.send(()).await.ok();}- _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {- let app = state.read().await;- if app.camera_feed.is_some() {- return Ok(false);- }+ if app.camera_feed.is_none() {+ feed.attach(camera_tx);+ app.camera_feed = Some(Arc::new(Mutex::new(feed)));+ return Ok(true);+ } else {+ return Ok(false);}}+ _ = shutdown_rx.recv() => {+ return Ok(false);+ }}}(None, _) => {+ if let Some(cancel) = app.camera_feed_initialization.take() {+ cancel.send(()).await.ok();+ }app.camera_feed.take();+ if let Some(w) = CapWindowId::Camera.get(&app_handle) {+ w.close().ok();+ }Ok(true)}}@@ -1726,6 +1752,27 @@ async fn set_server_url(app: MutableState<'_, App>, server_url: String) -> ResulOk(())}+#[tauri::command]+#[specta::specta]+async fn set_camera_preview_state(+ store: State<'_, CameraPreview>,+ state: CameraWindowState,+) -> Result<(), ()> {+ store.save(&state).map_err(|err| {+ error!("Error saving camera window state: {err}");+ ()+ })?;++ Ok(())+}++#[tauri::command]+#[specta::specta]+async fn await_camera_preview_ready(store: State<'_, CameraPreview>) -> Result<bool, ()> {+ store.wait_for_camera_to_load().await;+ Ok(true)+}+#[tauri::command]#[specta::specta]async fn update_auth_plan(app: AppHandle) {@@ -1806,6 +1853,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {set_window_transparent,get_editor_meta,set_server_url,+ set_camera_preview_state,+ await_camera_preview_ready,captions::create_dir,captions::save_model_file,captions::transcribe_audio,@@ -1850,8 +1899,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {).expect("Failed to export typescript bindings");- let (camera_tx, camera_ws_port, _shutdown) = create_camera_preview_ws().await;-let (audio_input_tx, audio_input_rx) = AudioInputFeed::create_channel();tauri::async_runtime::set(tokio::runtime::Handle::current());@@ -1939,9 +1986,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {{app.manage(Arc::new(RwLock::new(App {handle: app.clone(),- camera_tx,- camera_ws_port,camera_feed: None,+ camera_feed_initialization: None,mic_samples_tx: audio_input_tx,mic_feed: None,current_recording: None,@@ -1957,6 +2003,12 @@ pub async fn run(recording_logging_handle: LoggingHandle) {}),})));+ if let Ok(s) = CameraPreview::init(&app)+ .map_err(|err| error!("Error initializing camera preview: {err}"))+ {+ app.manage(s);+ }+app.manage(Arc::new(RwLock::new(ClipboardContext::new().expect("Failed to create clipboard context"),)));@@ -2088,7 +2140,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {}).build(tauri_context).expect("error while running tauri application")- .run(|handle, event| match event {+ .run(move |handle, event| match event {#[cfg(target_os = "macos")]tauri::RunEvent::Reopen { .. } => {let has_window = handle.webview_windows().iter().any(|(label, _)| {@@ -2120,6 +2172,18 @@ pub async fn run(recording_logging_handle: LoggingHandle) {api.prevent_exit();}}+ tauri::RunEvent::WindowEvent {+ event: WindowEvent::Resized(size),+ label,+ ..+ } => {+ if let Some(window) = handle.get_webview_window(&label) {+ let size = size.to_logical(window.scale_factor().unwrap_or(1.0));+ handle+ .state::<CameraPreview>()+ .update_window_size(size.width, size.height);+ }+ }_ => {}});}diff --git a/apps/desktop/src-tauri/src/notifications.rs b/apps/desktop/src-tauri/src/notifications.rsindex 6012ab32d..76fa4619c 100644--- a/apps/desktop/src-tauri/src/notifications.rs+++ b/apps/desktop/src-tauri/src/notifications.rs@@ -1,4 +1,4 @@-use crate::{general_settings::GeneralSettingsStore, AppSounds};+use crate::{AppSounds, general_settings::GeneralSettingsStore};use tauri_plugin_notification::NotificationExt;pub enum NotificationType {diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rsindex 92ae3f99a..572fbea99 100644--- a/apps/desktop/src-tauri/src/permissions.rs+++ b/apps/desktop/src-tauri/src/permissions.rs@@ -2,10 +2,10 @@ use serde::{Deserialize, Serialize};#[cfg(target_os = "macos")]#[link(name = "ApplicationServices", kind = "framework")]-extern "C" {+unsafe extern "C" {fn AXIsProcessTrusted() -> bool;fn AXIsProcessTrustedWithOptions(options: core_foundation::dictionary::CFDictionaryRef)- -> bool;+ -> bool;}#[derive(Serialize, Deserialize, specta::Type)]diff --git a/apps/desktop/src-tauri/src/platform/macos/delegates.rs b/apps/desktop/src-tauri/src/platform/macos/delegates.rsindex 4f7065f9d..a4959ee23 100644--- a/apps/desktop/src-tauri/src/platform/macos/delegates.rs+++ b/apps/desktop/src-tauri/src/platform/macos/delegates.rs@@ -12,7 +12,7 @@/// (Electron) https://github.com/electron/electron/blob/38512efd25a159ddc64a54c22ef9eb6dd60064ec/shell/browser/native_window_mac.mm#L1454///use objc::{msg_send, sel, sel_impl};-use rand::{distributions::Alphanumeric, Rng};+use rand::{Rng, distributions::Alphanumeric};use tauri::{Emitter, LogicalPosition, Runtime, Window};pub struct UnsafeWindowHandle(pub *mut std::ffi::c_void);@@ -70,7 +70,7 @@ pub fn position_window_controls(pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>) {use cocoa::appkit::NSWindow;- use cocoa::base::{id, BOOL};+ use cocoa::base::{BOOL, id};use cocoa::foundation::NSUInteger;use objc::runtime::{Object, Sel};use std::ffi::c_void;diff --git a/apps/desktop/src-tauri/src/platform/macos/mod.rs b/apps/desktop/src-tauri/src/platform/macos/mod.rsindex 7a0c86349..fd771803c 100644--- a/apps/desktop/src-tauri/src/platform/macos/mod.rs+++ b/apps/desktop/src-tauri/src/platform/macos/mod.rs@@ -30,7 +30,7 @@ pub fn get_ns_window_number(ns_window: *mut c_void) -> isize {}#[link(name = "CoreGraphics", kind = "framework")]-extern "C" {+unsafe extern "C" {pub fn CGRectMakeWithDictionaryRepresentation(dict: CFDictionaryRef,rect: *mut CGRect,diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 2f111f49c..6eabf8894 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,6 +1,8 @@use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration};use crate::{+ App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded,+ RecordingStarted, RecordingStopped, VideoUploadInfo,audio::AppSounds,auth::AuthStore,create_screenshot,@@ -10,13 +12,11 @@ use crate::{open_external_link,presets::PresetsStore,upload::{- build_video_meta, create_or_get_video, prepare_screenshot_upload, upload_video,- InstantMultipartUpload,+ InstantMultipartUpload, build_video_meta, create_or_get_video, prepare_screenshot_upload,+ upload_video,},web_api::ManagerExt,windows::{CapWindowId, ShowCapWindow},- App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded,- RecordingStarted, RecordingStopped, VideoUploadInfo,};use cap_fail::fail;use cap_media::{feeds::CameraFeed, platform::display_for_window, sources::ScreenCaptureTarget};@@ -29,8 +29,8 @@ use cap_project::{StudioRecordingMeta, TimelineConfiguration, TimelineSegment, ZoomSegment,};use cap_recording::{- instant_recording::{CompletedInstantRecording, InstantRecordingHandle},CompletedStudioRecording, RecordingError, RecordingMode, StudioRecordingHandle,+ instant_recording::{CompletedInstantRecording, InstantRecordingHandle},};use cap_rendering::ProjectRecordingsMeta;use cap_utils::{ensure_dir, spawn_actor};@@ -692,7 +692,9 @@ async fn handle_recording_finish(.and_then(|r| r){Ok(()) => {- info!("Not attempting instant recording upload as progressive upload succeeded");+ info!(+ "Not attempting instant recording upload as progressive upload succeeded"+ );true}Err(e) => {diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rsindex 0b0d28912..3d76112f8 100644--- a/apps/desktop/src-tauri/src/tray.rs+++ b/apps/desktop/src-tauri/src/tray.rs@@ -1,17 +1,17 @@use crate::windows::ShowCapWindow;use crate::{- recording, RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings,+ RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings, recording,};-use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;-use tauri::menu::{MenuId, PredefinedMenuItem};+use std::sync::atomic::{AtomicBool, Ordering};use tauri::Manager;+use tauri::menu::{MenuId, PredefinedMenuItem};use tauri::{+ AppHandle,image::Image,menu::{Menu, MenuItem},tray::TrayIconBuilder,- AppHandle,};use tauri_specta::Event;diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 61ab74cdd..60e59c389 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -1,39 +1,28 @@// credit @filleduchaos+use crate::web_api::ManagerExt;+use crate::{UploadProgress, VideoUploadInfo};use axum::http::{HeaderMap, HeaderName, HeaderValue};use cap_utils::spawn_actor;use flume::Receiver;-use futures::{stream, StreamExt};-use image::codecs::jpeg::JpegEncoder;+use futures::{StreamExt, stream};use image::ImageReader;+use image::codecs::jpeg::JpegEncoder;+use reqwest::StatusCode;use reqwest::header::CONTENT_LENGTH;-use reqwest::{multipart::Form, StatusCode};+use serde::de::{self, Deserializer};+use serde::{Deserialize, Serialize};use serde_json::json;-use std::collections::HashMap;-use std::io::SeekFrom;+use specta::Type;use std::path::PathBuf;-use std::str::FromStr;-use std::sync::Arc;use std::time::Duration;-use tauri::{AppHandle, Manager, Runtime};+use tauri::AppHandle;use tauri_plugin_clipboard_manager::ClipboardExt;use tauri_specta::Event;use tokio::io::{AsyncReadExt, AsyncSeekExt};-use tokio::sync::mpsc;-use tokio::sync::RwLock;use tokio::task;use tokio::time::sleep;-use tracing::{error, info, trace, warn};--use crate::web_api::{self, ManagerExt};--use crate::{- get_video_metadata, notifications, App, MutableState, RecordingStopped, UploadProgress,- VideoUploadInfo,-};-use serde::de::{self, Deserializer};-use serde::{Deserialize, Serialize};-use specta::Type;+use tracing::{error, info, warn};#[derive(Deserialize, Serialize, Clone, Type, Debug)]pub struct S3UploadMeta {@@ -880,7 +869,7 @@ impl InstantMultipartUpload {return Err(format!("Failed to request presigned URL for part {}: {}",*part_number, e- ))+ ));}};@@ -981,7 +970,7 @@ impl InstantMultipartUpload {return Err(format!("Failed to upload part {} after {} attempts",*part_number, max_retries- ))+ ));}};diff --git a/apps/desktop/src-tauri/src/web_api.rs b/apps/desktop/src-tauri/src/web_api.rsindex 43e1e838c..b5da3ef90 100644--- a/apps/desktop/src-tauri/src/web_api.rs+++ b/apps/desktop/src-tauri/src/web_api.rs@@ -3,8 +3,8 @@ use tauri::{Emitter, Manager, Runtime};use tauri_specta::Event;use crate::{- auth::{AuthSecret, AuthStore, AuthenticationInvalid},ArcLock,+ auth::{AuthSecret, AuthStore, AuthenticationInvalid},};async fn do_authed_request(diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 8548fd4e2..bcc1f578c 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -1,17 +1,20 @@#![allow(unused_mut)]#![allow(unused_imports)]-use crate::{fake_window, general_settings::AppTheme, permissions, App, ArcLock};+use crate::{+ App, ArcLock, camera::CameraPreview, fake_window, general_settings::AppTheme, permissions,+};use cap_flags::FLAGS;use cap_media::{platform::logical_monitor_bounds, sources::CaptureScreen};-use futures::pin_mut;+use futures::{executor::block_on, pin_mut};use serde::Deserialize;use specta::Type;use std::{+ borrow::Cow,ops::Deref,path::PathBuf,str::FromStr,- sync::{atomic::AtomicU32, Arc, Mutex},+ sync::{Arc, Mutex, atomic::AtomicU32, mpsc},};use tauri::{AppHandle, LogicalPosition, Manager, Monitor, PhysicalPosition, PhysicalSize, WebviewUrl,@@ -317,8 +320,6 @@ impl ShowCapWindow {Self::Camera => {const WINDOW_SIZE: f64 = 230.0 * 2.0;- let port = app.state::<Arc<RwLock<App>>>().read().await.camera_ws_port;-let mut window_builder = self.window_builder(app, "/camera").maximized(false)@@ -334,13 +335,8 @@ impl ShowCapWindow {- WINDOW_SIZE- 100.0,)- .initialization_script(&format!(- "- window.__CAP__ = window.__CAP__ ?? {{}};- window.__CAP__.cameraWsPort = {port};- ",- ))- .transparent(true);+ .transparent(true)+ .visible(false); // We set this true in `CameraWindowState::init_window`let window = window_builder.build()?;@@ -662,7 +658,7 @@ fn position_traffic_lights_impl(window: &tauri::Window,controls_inset: Option<LogicalPosition<f64>>,) {- use crate::platform::delegates::{position_window_controls, UnsafeWindowHandle};+ use crate::platform::delegates::{UnsafeWindowHandle, position_window_controls};let c_win = window.clone();window.run_on_main_thread(move || {diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsxindex 18376185c..628fa820e 100644--- a/apps/desktop/src/App.tsx+++ b/apps/desktop/src/App.tsx@@ -83,7 +83,7 @@ function Inner() {if (match.route.info?.AUTO_SHOW_WINDOW === false) return;}- currentWindow.show();+ if (location.pathname !== "/camera") currentWindow.show();});return (diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsxindex b79b5f14c..a6e007ce0 100644--- a/apps/desktop/src/routes/camera.tsx+++ b/apps/desktop/src/routes/camera.tsx@@ -1,30 +1,19 @@import { ToggleButton as KToggleButton } from "@kobalte/core/toggle-button";import { makePersisted } from "@solid-primitives/storage";-import {- LogicalPosition,- LogicalSize,- currentMonitor,- getCurrentWindow,-} from "@tauri-apps/api/window";-import { cx } from "cva";import {type ComponentProps,- Show,- Suspense,createEffect,createResource,- createSignal,- on,- onCleanup,+ Show,} from "solid-js";import { createStore } from "solid-js/store";import { createCameraMutation } from "~/utils/queries";-import { createImageDataWS, createLazySignal } from "~/utils/socket";import {RecordingOptionsProvider,useRecordingOptions,} from "./(window-chrome)/OptionsContext";+import { commands } from "~/utils/tauri";namespace CameraWindow {export type Size = "sm" | "lg";@@ -36,10 +25,6 @@ namespace CameraWindow {};}-const BAR_HEIGHT = 56;--const { cameraWsPort } = (window as any).__CAP__;-export default function () {document.documentElement.classList.toggle("dark", true);@@ -62,117 +47,20 @@ function Page() {{ name: "cameraWindowState" });- const [latestFrame, setLatestFrame] = createLazySignal<{- width: number;- data: ImageData;- } | null>();-- const [frameDimensions, setFrameDimensions] = createSignal<{- width: number;- height: number;- } | null>(null);-- function imageDataHandler(imageData: { width: number; data: ImageData }) {- setLatestFrame(imageData);-- const currentDimensions = frameDimensions();- if (- !currentDimensions ||- currentDimensions.width !== imageData.data.width ||- currentDimensions.height !== imageData.data.height- ) {- setFrameDimensions({- width: imageData.data.width,- height: imageData.data.height,- });- }-- const ctx = cameraCanvasRef?.getContext("2d");- ctx?.putImageData(imageData.data, 0, 0);- }+ createEffect(() => commands.setCameraPreviewState(state));- const [ws, isConnected] = createImageDataWS(- `ws://localhost:${cameraWsPort}`,- imageDataHandler+ const [cameraPreviewReady] = createResource(() =>+ commands.awaitCameraPreviewReady());- const reconnectInterval = setInterval(() => {- if (!isConnected()) {- console.log("Attempting to reconnect...");- ws.close();-- const newWs = createImageDataWS(- `ws://localhost:${cameraWsPort}`,- imageDataHandler- );- Object.assign(ws, newWs[0]);- }- }, 5000);-- onCleanup(() => {- clearInterval(reconnectInterval);- ws.close();- });-- const [windowSize] = createResource(- () =>- [- state.size,- state.shape,- frameDimensions()?.width,- frameDimensions()?.height,- ] as const,- async ([size, shape, frameWidth, frameHeight]) => {- const monitor = await currentMonitor();-- const base = size === "sm" ? 230 : 400;- const aspect = frameWidth && frameHeight ? frameWidth / frameHeight : 1;- const windowWidth =- shape === "full" ? (aspect >= 1 ? base * aspect : base) : base;- const windowHeight =- shape === "full" ? (aspect >= 1 ? base : base / aspect) : base;- const totalHeight = windowHeight + BAR_HEIGHT;-- if (!monitor) return;-- const scalingFactor = monitor.scaleFactor;- const width = monitor.size.width / scalingFactor - windowWidth - 100;- const height = monitor.size.height / scalingFactor - totalHeight - 100;-- const currentWindow = getCurrentWindow();- currentWindow.setSize(new LogicalSize(windowWidth, totalHeight));- currentWindow.setPosition(- new LogicalPosition(- width + monitor.position.toLogical(scalingFactor).x,- height + monitor.position.toLogical(scalingFactor).y- )- );-- return { width, height, size: base, windowWidth, windowHeight };- }- );-- let cameraCanvasRef: HTMLCanvasElement | undefined;-const setCamera = createCameraMutation();- createEffect(- on(- () => rawOptions.cameraLabel,- (label) => {- if (label === null) getCurrentWindow().close();- },- { defer: true }- )- );-return (<divdata-tauri-drag-regionclass="flex relative flex-col w-screen h-screen cursor-move group"- style={{ "border-radius": cameraBorderRadius(state) }}>- <div class="h-14">+ <div class="h-13"><div class="flex flex-row justify-center items-center"><div class="flex flex-row gap-[0.25rem] p-[0.25rem] opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 rounded-xl transition-[opacity,transform] bg-gray-1 border border-white-transparent-20 text-gray-10"><ControlButton onClick={() => setCamera.mutate(null)}>@@ -209,89 +97,17 @@ function Page() {</div></div></div>- <div- class={cx(- "flex flex-col flex-1 relative overflow-hidden pointer-events-none border-none shadow-lg bg-gray-1 text-gray-12",- state.shape === "round" ? "rounded-full" : "rounded-3xl"- )}- data-tauri-drag-region- >- <Suspense fallback={<CameraLoadingState />}>- <Show when={latestFrame()}>- {(latestFrame) => {- const style = () => {- const aspectRatio =- latestFrame().data.width / latestFrame().data.height;-- const base = windowSize.latest?.size ?? 0;- const winWidth = windowSize.latest?.windowWidth ?? base;- const winHeight = windowSize.latest?.windowHeight ?? base;-- if (state.shape === "full") {- return {- width: `${winWidth}px`,- height: `${winHeight}px`,- transform: state.mirrored ? "scaleX(-1)" : "scaleX(1)",- };- }-- const size = (() => {- if (aspectRatio > 1)- return {- width: base * aspectRatio,- height: base,- };- else- return {- width: base,- height: base * aspectRatio,- };- })();-- const left = aspectRatio > 1 ? (size.width - base) / 2 : 0;- const top = aspectRatio > 1 ? 0 : (base - size.height) / 2;-- return {- width: `${size.width}px`,- height: `${size.height}px`,- left: `-${left}px`,- top: `-${top}px`,- transform: state.mirrored ? "scaleX(-1)" : "scaleX(1)",- };- };-- return (- <canvas- data-tauri-drag-region- class={cx("absolute")}- style={style()}- width={latestFrame().data.width}- height={latestFrame().data.height}- ref={cameraCanvasRef!}- />- );- }}- </Show>- </Suspense>- </div>- </div>- );-}-function CameraLoadingState() {- return (- <div class="w-full flex-1 flex items-center justify-center">- <div class="text-gray-11">Loading camera...</div>+ {/* The camera preview is rendered in Rust by wgpu */}+ <Show when={cameraPreviewReady.loading}>+ <div class="w-full flex-1 flex items-center justify-center">+ <div class="text-gray-11">Loading camera...</div>+ </div>+ </Show></div>);}-function cameraBorderRadius(state: CameraWindow.State) {- if (state.shape === "round") return "9999px";- if (state.size === "sm") return "3rem";- return "4rem";-}-function ControlButton(props: Omit<ComponentProps<typeof KToggleButton>, "type" | "class"> & {active?: boolean;diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.tsindex 87994044c..e0c7f03e1 100644--- a/apps/desktop/src/utils/queries.ts+++ b/apps/desktop/src/utils/queries.ts@@ -142,10 +142,6 @@ export function createCameraMutation() {const setCameraInput = createMutation(() => ({mutationFn: async (label: string | null) => {setOptions("cameraLabel", label);- if (label) {- await commands.showWindow("Camera");- getCurrentWindow().setFocus();- }await commands.setCameraInput(label);},}));diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 00722d98d..c1c4df699 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -185,6 +185,12 @@ async getEditorMeta() : Promise<RecordingMeta> {async setServerUrl(serverUrl: string) : Promise<null> {return await TAURI_INVOKE("set_server_url", { serverUrl });},+async setCameraPreviewState(state: CameraWindowState) : Promise<null> {+ return await TAURI_INVOKE("set_camera_preview_state", { state });+},+async awaitCameraPreviewReady() : Promise<boolean> {+ return await TAURI_INVOKE("await_camera_preview_ready");+},/*** Function to handle creating directories for the model*/@@ -304,7 +310,10 @@ export type BackgroundSource = { type: "wallpaper"; path: string | null } | { tyexport type Bounds = { x: number; y: number; width: number; height: number }export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoom_size: number | null; rounding?: number; shadow?: number; advanced_shadow?: ShadowConfiguration | null; shape?: CameraShape }export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }+export type CameraPreviewShape = "round" | "square" | "full"+export type CameraPreviewSize = "sm" | "lg"export type CameraShape = "square" | "source"+export type CameraWindowState = { size: CameraPreviewSize; shape: CameraPreviewShape; mirrored: boolean }export type CameraXPosition = "left" | "center" | "right"export type CameraYPosition = "top" | "bottom"export type CaptionData = { segments: CaptionSegment[]; settings: CaptionSettings | null }diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rsindex 7bddd2180..110e130fd 100644--- a/crates/media/src/feeds/camera.rs+++ b/crates/media/src/feeds/camera.rs@@ -3,11 +3,9 @@ use ffmpeg::format::Pixel;use flume::{Receiver, Sender, TryRecvError, TrySendError};use nokhwa::{pixel_format::RgbAFormat, utils::*, Camera};use std::{- sync::Arc,thread::{self},time::SystemTime,};-use tokio::sync::Mutex;use tracing::{debug, error, info, trace, warn};use crate::{