Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix window capture occluder (#428)
Brendan Allan34a5a5f79de0
diff --git a/Cargo.lock b/Cargo.lockindex 08e5a89bb..45b06e7ab 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6374,7 +6374,7 @@ dependencies = [[[package]]name = "scap"version = "0.0.8"-source = "git+https://github.com/CapSoftware/scap?rev=e7897ad88d1b#e7897ad88d1b641a69cbf0f1ef3c5ae8b813309f"+source = "git+https://github.com/CapSoftware/scap?rev=98a1b3c6d650#98a1b3c6d65096625493161c23387c6d0d0bf3b9"dependencies = ["cocoa 0.25.0","core-foundation 0.10.0",diff --git a/Cargo.toml b/Cargo.tomlindex 90ca99631..6da6abae7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -25,7 +25,7 @@ specta = { version = "=2.0.0-rc.20", features = ["uuid",] }-scap = { git = "https://github.com/CapSoftware/scap", rev = "e7897ad88d1b" }+scap = { git = "https://github.com/CapSoftware/scap", rev = "98a1b3c6d650" }nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "b9c8079e82e2", features = ["input-native","serialize",diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 7be4ce20e..5b1fccea8 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -139,29 +139,22 @@ pub struct VideoUploadInfo {impl App {pub fn set_current_recording(&mut self, actor: InProgressRecording) {- let current_recording = self.current_recording.insert(actor);+ self.current_recording.insert(actor);CurrentRecordingChanged.emit(&self.handle).ok();-- if matches!(- current_recording.capture_target(),- ScreenCaptureTarget::Window { .. } | ScreenCaptureTarget::Area { .. }- ) {- let _ = ShowCapWindow::WindowCaptureOccluder.show(&self.handle);- } else {- self.close_occluder_window();- }}pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {- self.close_occluder_window();+ self.close_occluder_windows();self.current_recording.take()}- fn close_occluder_window(&self) {- if let Some(window) = CapWindowId::WindowCaptureOccluder.get(&self.handle) {- window.close().ok();+ fn close_occluder_windows(&self) {+ for window in self.handle.webview_windows() {+ if window.0.starts_with("window-capture-occluder-") {+ let _ = window.1.close();+ }}}@@ -2243,7 +2236,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {}).with_denylist(&[CapWindowId::Setup.label().as_str(),- CapWindowId::WindowCaptureOccluder.label().as_str(),+ "window-capture-occluder",+ // CapWindowId::WindowCaptureOccluder.label().as_str(),CapWindowId::CaptureArea.label().as_str(),CapWindowId::Camera.label().as_str(),CapWindowId::RecordingsOverlay.label().as_str(),@@ -2252,6 +2246,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) {]).map_label(|label| match label {label if label.starts_with("editor-") => "editor",+ label if label.starts_with("window-capture-occluder-") => {+ "window-capture-occluder"+ }_ => label,}).build(),diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 29d9e8202..03cb79cec 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -16,7 +16,7 @@ use crate::{RecordingStarted, RecordingStopped, VideoUploadInfo,};use cap_fail::fail;-use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};+use cap_media::{feeds::CameraFeed, platform::display_for_window, sources::ScreenCaptureTarget};use cap_media::{platform::Bounds,sources::{CaptureScreen, CaptureWindow},@@ -32,6 +32,7 @@ use cap_recording::{};use cap_rendering::ProjectRecordings;use cap_utils::{ensure_dir, spawn_actor};+use scap::Target;use tauri::{AppHandle, Manager};use tauri_specta::Event;use tracing::{error, info};@@ -218,11 +219,30 @@ pub async fn start_recording(RecordingMode::Studio => None,};- if matches!(- recording_options.capture_target,- ScreenCaptureTarget::Window { .. } | ScreenCaptureTarget::Area { .. }- ) {- let _ = ShowCapWindow::WindowCaptureOccluder.show(&app);+ match &recording_options.capture_target {+ ScreenCaptureTarget::Window { id } => {+ #[cfg(target_os = "macos")]+ let display = display_for_window(*id).unwrap().id;++ #[cfg(windows)]+ let display = {+ let Target::Window(target) = recording_options.capture_target.get_target().unwrap()+ else {+ unreachable!();+ };+ display_for_window(target.raw_handle).unwrap().0 as u32+ };++ let _ = ShowCapWindow::WindowCaptureOccluder { screen_id: display }+ .show(&app)+ .await;+ }+ ScreenCaptureTarget::Area { screen, .. } => {+ let _ = ShowCapWindow::WindowCaptureOccluder { screen_id: *screen }+ .show(&app)+ .await;+ }+ _ => {}}let (finish_upload_tx, finish_upload_rx) = flume::bounded(1);diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 39543ce49..91506b0ea 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -3,7 +3,7 @@use crate::{fake_window, general_settings::AppTheme, permissions, App, ArcLock};use cap_flags::FLAGS;-use cap_media::sources::CaptureScreen;+use cap_media::{platform::logical_monitor_bounds, sources::CaptureScreen};use futures::pin_mut;use serde::Deserialize;use specta::Type;@@ -26,7 +26,7 @@ pub enum CapWindowId {Settings,Editor { project_id: String },RecordingsOverlay,- WindowCaptureOccluder,+ WindowCaptureOccluder { screen_id: u32 },CaptureArea,Camera,InProgressRecording,@@ -44,7 +44,6 @@ impl FromStr for CapWindowId {"main" => Self::Main,"settings" => Self::Settings,"camera" => Self::Camera,- "window-capture-occluder" => Self::WindowCaptureOccluder,"capture-area" => Self::CaptureArea,"in-progress-recording" => Self::InProgressRecording,"recordings-overlay" => Self::RecordingsOverlay,@@ -54,6 +53,12 @@ impl FromStr for CapWindowId {s if s.starts_with("editor-") => Self::Editor {project_id: s.replace("editor-", ""),},+ s if s.starts_with("window-capture-occluder-") => Self::WindowCaptureOccluder {+ screen_id: s+ .replace("window-capture-occluder-", "")+ .parse::<u32>()+ .map_err(|e| e.to_string())?,+ },_ => return Err(format!("unknown window label: {}", s)),})}@@ -66,7 +71,9 @@ impl std::fmt::Display for CapWindowId {Self::Main => write!(f, "main"),Self::Settings => write!(f, "settings"),Self::Camera => write!(f, "camera"),- Self::WindowCaptureOccluder => write!(f, "window-capture-occluder"),+ Self::WindowCaptureOccluder { screen_id } => {+ write!(f, "window-capture-occluder-{screen_id}")+ }Self::CaptureArea => write!(f, "capture-area"),Self::InProgressRecording => write!(f, "in-progress-recording"),Self::RecordingsOverlay => write!(f, "recordings-overlay"),@@ -87,7 +94,7 @@ impl CapWindowId {match self {Self::Setup => "Cap Setup".to_string(),Self::Settings => "Cap Settings".to_string(),- Self::WindowCaptureOccluder => "Cap Window Capture Occluder".to_string(),+ Self::WindowCaptureOccluder { .. } => "Cap Window Capture Occluder".to_string(),Self::CaptureArea => "Cap Capture Area".to_string(),Self::InProgressRecording => "Cap In Progress Recording".to_string(),Self::Editor { .. } => "Cap Editor".to_string(),@@ -123,7 +130,7 @@ impl CapWindowId {Self::Editor { .. } => Some(Some(LogicalPosition::new(20.0, 32.0))),Self::InProgressRecording => Some(Some(LogicalPosition::new(-100.0, -100.0))),Self::Camera- | Self::WindowCaptureOccluder+ | Self::WindowCaptureOccluder { .. }| Self::CaptureArea| Self::RecordingsOverlay => None,_ => Some(None),@@ -152,7 +159,7 @@ pub enum ShowCapWindow {Settings { page: Option<String> },Editor { project_id: String },RecordingsOverlay,- WindowCaptureOccluder,+ WindowCaptureOccluder { screen_id: u32 },CaptureArea { screen_id: u32 },Camera { ws_port: u16 },InProgressRecording { position: Option<(f64, f64)> },@@ -169,7 +176,7 @@ impl ShowCapWindow {}let id = self.id();- let monitor = app.primary_monitor()?.unwrap();+ let monitor = app.primary_monitor().unwrap().unwrap();let window = match self {Self::Setup => self@@ -299,7 +306,11 @@ impl ShowCapWindow {window}- Self::WindowCaptureOccluder => {+ Self::WindowCaptureOccluder { screen_id } => {+ let Some(bounds) = logical_monitor_bounds(*screen_id) else {+ return Err(tauri::Error::WindowNotFound);+ };+let mut window_builder = self.window_builder(app, "/window-capture-occluder").maximized(false)@@ -310,11 +321,8 @@ impl ShowCapWindow {.visible_on_all_workspaces(true).content_protected(true).skip_taskbar(true)- .inner_size(- (monitor.size().width as f64) / monitor.scale_factor(),- (monitor.size().height as f64) / monitor.scale_factor(),- )- .position(0.0, 0.0)+ .inner_size(bounds.size.width, bounds.size.height)+ .position(bounds.position.x, bounds.position.y).transparent(true);let window = window_builder.build()?;@@ -523,7 +531,11 @@ impl ShowCapWindow {project_id: project_id.clone(),},ShowCapWindow::RecordingsOverlay => CapWindowId::RecordingsOverlay,- ShowCapWindow::WindowCaptureOccluder => CapWindowId::WindowCaptureOccluder,+ ShowCapWindow::WindowCaptureOccluder { screen_id } => {+ CapWindowId::WindowCaptureOccluder {+ screen_id: *screen_id,+ }+ }ShowCapWindow::CaptureArea { .. } => CapWindowId::CaptureArea,ShowCapWindow::Camera { .. } => CapWindowId::Camera,ShowCapWindow::InProgressRecording { .. } => CapWindowId::InProgressRecording,diff --git a/apps/desktop/src/routes/window-capture-occluder.tsx b/apps/desktop/src/routes/window-capture-occluder.tsxindex 81b3ea7ba..168de46c2 100644--- a/apps/desktop/src/routes/window-capture-occluder.tsx+++ b/apps/desktop/src/routes/window-capture-occluder.tsx@@ -1,6 +1,7 @@-import { getAllWindows } from "@tauri-apps/api/window";+import { getAllWindows, getCurrentWindow } from "@tauri-apps/api/window";+import { getCurrent } from "@tauri-apps/plugin-deep-link";import { type as ostype } from "@tauri-apps/plugin-os";-import { onMount, Show, Suspense } from "solid-js";+import { createResource, Show, Suspense } from "solid-js";import CropAreaRenderer from "~/components/CropAreaRenderer";import { createCurrentRecordingQuery } from "~/utils/queries";@@ -24,6 +25,9 @@ export default function () {}};++ const [scale] = createResource(() => getCurrentWindow().scaleFactor(), { initialValue: 0 });+return (<Suspense><Show when={bounds()}>@@ -37,8 +41,13 @@ export default function () {return (<CropAreaRenderer- bounds={bounds()}- borderRadius={ostype() === "macos" ? 9 : 7}+ bounds={ostype() === "macos" ? bounds() : {+ x: bounds().x / scale(),+ y: bounds().y / scale(),+ width: bounds().width / scale(),+ height: bounds().height / scale()+ }}+ // no border radius as that should be added in editor/>);}}diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 6ede462a1..eb7585982 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -312,7 +312,7 @@ export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audexport type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; meta: RecordingMeta }export type ShadowConfiguration = { size: number; opacity: number; blur: number }export type SharingMeta = { id: string; link: string }-export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "RecordingsOverlay" | "WindowCaptureOccluder" | { CaptureArea: { screen_id: number } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn" | "ModeSelect"+export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "RecordingsOverlay" | { WindowCaptureOccluder: { screen_id: number } } | { CaptureArea: { screen_id: number } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn" | "ModeSelect"export type SingleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; cursor?: string | null }export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }diff --git a/crates/media/src/platform/macos.rs b/crates/media/src/platform/macos.rsindex 256cd720d..72b9eeb33 100644--- a/crates/media/src/platform/macos.rs+++ b/crates/media/src/platform/macos.rs@@ -18,7 +18,9 @@ use core_graphics::{pub use nokhwa_bindings_macos::{AVAuthorizationStatus, AVMediaType};use std::{collections::HashMap, ffi::c_void};-use crate::platform::{Bounds, Window};+use crate::platform::{Bounds, LogicalPosition, LogicalSize, Window};++use super::LogicalBounds;#[link(name = "CoreGraphics", kind = "framework")]extern "C" {@@ -384,3 +386,98 @@ pub fn primary_monitor_bounds() -> Bounds {height: height as f64,}}++#[derive(Debug, Clone, Copy)]+pub struct MonitorHandle(pub u32);++impl MonitorHandle {+ pub fn primary() -> Self {+ let display = CGDisplay::main();+ Self(display.id)+ }++ pub fn list_all() -> Vec<Self> {+ use cocoa::appkit::NSScreen;+ use cocoa::base::nil;+ use cocoa::foundation::{NSArray, NSDictionary, NSString};++ let mut ret = vec![];++ unsafe {+ let screens = NSScreen::screens(nil);+ let screen_count = NSArray::count(screens);++ for i in 0..screen_count {+ let screen: *mut objc::runtime::Object = screens.objectAtIndex(i);++ let device_description = NSScreen::deviceDescription(screen);+ let num = NSDictionary::valueForKey_(+ device_description,+ NSString::alloc(nil).init_str("NSScreenNumber"),+ ) as id;+ let num: *const objc2_foundation::NSNumber = num.cast();+ let num = { &*num };+ let num = num.as_u32();++ ret.push(Self(num));+ }++ ret+ }+ }+}++pub fn logical_monitor_bounds(monitor_id: u32) -> Option<LogicalBounds> {+ use cocoa::appkit::NSScreen;+ use cocoa::base::nil;+ use cocoa::foundation::{NSArray, NSDictionary, NSString};++ unsafe {+ let screens = NSScreen::screens(nil);+ let screen_count = NSArray::count(screens);++ for i in 0..screen_count {+ let screen: *mut objc::runtime::Object = screens.objectAtIndex(i);++ let device_description = NSScreen::deviceDescription(screen);+ let num = NSDictionary::valueForKey_(+ device_description,+ NSString::alloc(nil).init_str("NSScreenNumber"),+ ) as id;+ let num: *const objc2_foundation::NSNumber = num.cast();+ let num = { &*num };+ let num = num.as_u32();++ if num == monitor_id {+ let frame = NSScreen::frame(screen);++ return Some(LogicalBounds {+ position: LogicalPosition {+ x: frame.origin.x,+ y: frame.origin.y+ + (CGDisplay::main().pixels_high() as f64 - frame.size.height),+ },+ size: LogicalSize {+ width: frame.size.width,+ height: frame.size.height,+ },+ });+ }+ }++ None+ }+}++#[cfg(test)]+mod test {+ use super::*;++ #[test]+ fn bruh() {+ dbg!(MonitorHandle::list_all()+ .into_iter()+ .map(|v| logical_monitor_bounds(v.0))+ .collect::<Vec<_>>());+ }+}diff --git a/crates/media/src/platform/mod.rs b/crates/media/src/platform/mod.rsindex 063d45ca1..fc667d5d7 100644--- a/crates/media/src/platform/mod.rs+++ b/crates/media/src/platform/mod.rs@@ -95,3 +95,21 @@ pub enum CursorShape {/// Couldn't get the cursor shape.Unknown,}++#[derive(Debug, Clone, Copy)]+pub struct LogicalPosition {+ pub x: f64,+ pub y: f64,+}++#[derive(Debug, Clone, Copy)]+pub struct LogicalSize {+ pub width: f64,+ pub height: f64,+}++#[derive(Debug, Clone, Copy)]+pub struct LogicalBounds {+ pub position: LogicalPosition,+ pub size: LogicalSize,+}diff --git a/crates/media/src/platform/win.rs b/crates/media/src/platform/win.rsindex 8b4e58b09..3f63be172 100644--- a/crates/media/src/platform/win.rs+++ b/crates/media/src/platform/win.rs@@ -3,7 +3,7 @@ use std::ffi::{c_void, OsString};use std::os::windows::ffi::OsStringExt;use std::path::PathBuf;-use super::{Bounds, CursorShape, Window};+use super::{Bounds, CursorShape, LogicalBounds, LogicalPosition, LogicalSize, Window};use tracing::debug;use windows::core::{PCWSTR, PWSTR};@@ -193,8 +193,6 @@ pub fn get_on_screen_windows() -> Vec<Window> {dpi => dpi,} as i32;- let scale_factor = dpi as f64 / BASE_DPI as f64;-let mut rect = RECT::default();DwmGetWindowAttribute(hwnd,@@ -204,10 +202,10 @@ pub fn get_on_screen_windows() -> Vec<Window> {).ok();- let rect_left = rect.left as f64 / scale_factor;- let rect_top = rect.top as f64 / scale_factor;- let rect_right = rect.right as f64 / scale_factor;- let rect_bottom = rect.bottom as f64 / scale_factor;+ let rect_left = rect.left as f64;+ let rect_top = rect.top as f64;+ let rect_right = rect.right as f64;+ let rect_bottom = rect.bottom as f64;let window = Window {window_id: hwnd.0 as u32,@@ -305,6 +303,20 @@ pub fn monitor_bounds(id: u32) -> Bounds {lparams.1.unwrap()}+pub fn logical_monitor_bounds(id: u32) -> Option<LogicalBounds> {+ let bounds = monitor_bounds(id);+ Some(LogicalBounds {+ position: LogicalPosition {+ x: bounds.x,+ y: bounds.y,+ },+ size: LogicalSize {+ width: bounds.width,+ height: bounds.height,+ },+ })+}+pub fn display_names() -> HashMap<u32, String> {let mut names = HashMap::new();diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex bd54e7a2f..1884b9562 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -19,7 +19,7 @@ use tracing::{debug, error, info, trace, warn};use crate::{data::{AudioInfo, FFVideo, PlanarData, RawVideoFormat, VideoInfo},pipeline::{clock::*, control::Control, task::PipelineSourceTask},- platform::{self, Bounds, Window},+ platform::{self, logical_monitor_bounds, Bounds, Window},MediaError,};@@ -171,7 +171,7 @@ impl ScreenCaptureFormat for AVFrameCapture {info.sample_format = Sample::F32(ffmpeg::format::sample::Type::Packed);- dbg!(info)+ info}}@@ -241,8 +241,12 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {this.options = Arc::new(options);- let [frame_width, frame_height] = get_output_frame_size(&this.options);- this.video_info = VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, fps);+ this.video_info = VideoInfo::from_raw(+ RawVideoFormat::Bgra,+ bounds.width as u32,+ bounds.height as u32,+ fps,+ );Ok(this)}@@ -260,26 +264,57 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {ScreenCaptureTarget::Window { id } => {let windows = list_windows();- let (window_info, target) = windows+ let (mut window_info, target) = windows.into_iter().find(|t| t.0.id == *id).ok_or_else(|| "Capture window not found".to_string())?;+ let Target::Display(display) = display_for_target(&target, &targets)+ .ok_or_else(|| "Screen for capture window not found".to_string())?+ else {+ unreachable!()+ };++ let id = {+ #[cfg(target_os = "macos")]+ {+ display.raw_handle.id+ }++ #[cfg(windows)]+ {+ display.raw_handle.0 as u32+ }+ };++ let monitor_bounds = logical_monitor_bounds(id).unwrap();++ window_info.bounds.x -= monitor_bounds.position.x;+ window_info.bounds.y -= monitor_bounds.position.y;++ fn div_by_2able(n: f64) -> f64 {+ n + n % 2.0+ }+let crop = Area {size: Size {- width: window_info.bounds.width,- height: window_info.bounds.height,+ width: div_by_2able(window_info.bounds.width),+ height: div_by_2able(window_info.bounds.height),},origin: Point {- x: window_info.bounds.x,- y: window_info.bounds.y,+ x: div_by_2able(window_info.bounds.x),+ y: div_by_2able(window_info.bounds.y),},};(- display_for_target(&target, &targets)- .ok_or_else(|| "Screen for capture window not found".to_string())?,- window_info.bounds,+ Target::Display(display),+ Bounds {+ x: crop.origin.x,+ y: crop.origin.y,+ width: crop.size.width,+ height: crop.size.height,+ },Some(crop),)}@@ -350,7 +385,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {crop_area,output_type: self.output_type.unwrap_or(FrameType::BGRAFrame),output_resolution: self.output_resolution.unwrap_or(ScapResolution::Captured),- excluded_targets: Some(excluded_targets),+ excluded_targets: (!excluded_targets.is_empty()).then(|| excluded_targets),captures_audio,exclude_current_process_audio: true,})diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex 74c985d61..6efa5839b 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -116,7 +116,6 @@ pub fn spawn_cursor_recorder(} else {"default".to_string()};- // dbg!(&mouse_state, &screen_bounds);if mouse_state.coords != last_mouse_state.coords {// Get the actual mouse coordinatesdiff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex f49349212..0a7df623c 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -191,6 +191,8 @@ pub async fn spawn_studio_recording_actor(let bounds = pipeline.screen.bounds;+ debug!("screen bounds: {bounds:?}");+spawn_actor({let options = options.clone();let fps = pipeline.screen.video_info.fps();