Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

connect zoom origin to cursor position

Brendan Allan6c5fb06718b4
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 052010f2e..48f03adf6 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1055,7 +1055,14 @@ async fn render_to_file_impl(
println!("Rendering video to channel");
- cap_rendering::render_video_to_channel(options, project, tx_image_data, decoders).await?;
+ cap_rendering::render_video_to_channel(
+ options,
+ project,
+ tx_image_data,
+ decoders,
+ editor_instance.cursor.clone(),
+ )
+ .await?;
ffmpeg_handle.await.ok();
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 671d381bc..e8aa880a9 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -137,8 +137,8 @@ impl InProgressRecording {
serde_json::to_writer(
&mut file,
&CursorData {
- clicks: self.cursor_moves.await.unwrap(),
- moves: self.cursor_clicks.await.unwrap(),
+ clicks: self.cursor_clicks.await.unwrap(),
+ moves: self.cursor_moves.await.unwrap(),
},
)
.unwrap();
@@ -198,6 +198,8 @@ pub async fn start(
let screen_source =
ScreenCaptureSource::init(dbg!(&recording_options.capture_target), None, None);
let screen_config = screen_source.info();
+ let screen_bounds = screen_source.bounds.clone();
+
let output_config = screen_config.scaled(1920, 30);
let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
let screen_encoder = H264Encoder::init(
@@ -274,8 +276,8 @@ pub async fn start(
cursor_id: get_cursor_id(),
process_time_ms: elapsed,
unix_time_ms: unix_time,
- x: mouse_state.coords.0 as f64,
- y: mouse_state.coords.1 as f64,
+ x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,
+ y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,
};
moves.push(mouse_event);
}
@@ -286,8 +288,8 @@ pub async fn start(
cursor_id: get_cursor_id(),
process_time_ms: elapsed,
unix_time_ms: unix_time,
- x: mouse_state.coords.0 as f64,
- y: mouse_state.coords.1 as f64,
+ x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,
+ y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,
};
clicks.push(mouse_event);
}
diff --git a/apps/desktop/src/flags.ts b/apps/desktop/src/flags.ts
index d2a3cac0a..1f80535b2 100644
--- a/apps/desktop/src/flags.ts
+++ b/apps/desktop/src/flags.ts
@@ -1,4 +1,4 @@
export const flags = {
- split: import.meta.env.DEV,
- pauseResume: import.meta.env.DEV,
+ split: false, //import.meta.env.DEV,
+ pauseResume: false, //import.meta.env.DEV,
};
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 9ec4cd319..59492009a 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -107,7 +107,13 @@ impl EditorInstance {
let (ws_port, ws_shutdown) = create_frames_ws(frame_rx).await;
- let render_constants = Arc::new(RenderVideoConstants::new(render_options).await.unwrap());
+ let cursor = Arc::new(meta.cursor_data());
+
+ let render_constants = Arc::new(
+ RenderVideoConstants::new(render_options, cursor.clone())
+ .await
+ .unwrap(),
+ );
let renderer = Arc::new(editor::Renderer::spawn(render_constants.clone(), frame_tx));
@@ -122,7 +128,7 @@ impl EditorInstance {
renderer,
render_constants,
audio: Arc::new(StdMutex::new(audio)),
- cursor: Arc::new(meta.cursor_data()),
+ cursor,
state: Arc::new(Mutex::new(EditorState {
playhead_position: 0,
playback_task: None,
@@ -279,7 +285,7 @@ impl EditorInstance {
screen_frame,
camera_frame,
project.background.source.clone(),
- ProjectUniforms::new(&self.render_constants, &project),
+ ProjectUniforms::new(&self.render_constants, &project, time as f32),
)
.await;
}
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 8dab3cd82..41498abdc 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -94,7 +94,7 @@ impl Playback {
},
Some((screen_frame, camera_frame)) = self.decoders.get_frames((time * FPS as f64) as u32) => {
// println!("decoded frame in {:?}", debug.elapsed());
- let uniforms = ProjectUniforms::new(&self.render_constants, &project);
+ let uniforms = ProjectUniforms::new(&self.render_constants, &project, time as f32);
self
.renderer
diff --git a/crates/media/src/platform/macos.rs b/crates/media/src/platform/macos.rs
index c944b537e..6c6e88807 100644
--- a/crates/media/src/platform/macos.rs
+++ b/crates/media/src/platform/macos.rs
@@ -1,3 +1,4 @@
+use cocoa::{base::id, foundation::NSDictionary};
use core_foundation::{
array::CFArrayGetCount,
base::FromVoid,
@@ -15,7 +16,7 @@ use core_graphics::{
},
};
pub use nokhwa_bindings_macos::{AVAuthorizationStatus, AVMediaType};
-use std::ffi::c_void;
+use std::{collections::HashMap, ffi::c_void};
use crate::platform::{Bounds, Window};
@@ -249,3 +250,82 @@ pub fn bring_window_to_focus(window_id: u32) {
eprintln!("Window with id {} not found", window_id);
}
}
+
+pub fn window_names() -> HashMap<u32, String> {
+ use cocoa::appkit::NSScreen;
+ use cocoa::base::nil;
+ use cocoa::foundation::{NSArray, NSString};
+ use objc::{msg_send, *};
+ use std::ffi::CStr;
+
+ unsafe {
+ let screens = NSScreen::screens(nil);
+ let screen_count = NSArray::count(screens);
+
+ let mut names = HashMap::new();
+
+ for i in 0..screen_count {
+ let screen: *mut objc::runtime::Object = screens.objectAtIndex(i);
+
+ let name: id = msg_send![screen, localizedName];
+ let name = CStr::from_ptr(NSString::UTF8String(name))
+ .to_string_lossy()
+ .to_string();
+
+ 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();
+
+ names.insert(num, name);
+ }
+
+ names
+ }
+}
+
+pub fn monitor_bounds(id: u32) -> Bounds {
+ 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 == id {
+ let frame = NSScreen::frame(screen);
+
+ return Bounds {
+ x: frame.origin.x,
+ y: frame.origin.y,
+ width: frame.size.width,
+ height: frame.size.height,
+ };
+ }
+ }
+
+ Bounds {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ }
+ }
+}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 882d03ea0..0ca599f2b 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -1,4 +1,3 @@
-use cocoa::{base::id, foundation::NSDictionary};
use flume::Sender;
use scap::{
capturer::{get_output_frame_size, Area, Capturer, Options, Point, Resolution, Size},
@@ -7,13 +6,16 @@ use scap::{
};
use serde::{Deserialize, Serialize};
use specta::Type;
-use std::{collections::HashMap, ffi::c_char};
+use std::collections::HashMap;
-use crate::pipeline::{clock::*, control::Control, task::PipelineSourceTask};
use crate::{
data::{FFVideo, RawVideoFormat, VideoInfo},
platform::{Bounds, Window},
};
+use crate::{
+ pipeline::{clock::*, control::Control, task::PipelineSourceTask},
+ platform,
+};
static EXCLUDED_WINDOWS: [&'static str; 4] = [
"Cap",
@@ -61,6 +63,7 @@ pub struct ScreenCaptureSource {
options: Options,
video_info: VideoInfo,
target: ScreenCaptureTarget,
+ pub bounds: Bounds,
}
impl ScreenCaptureSource {
@@ -88,18 +91,23 @@ impl ScreenCaptureSource {
.map(|t| t.clone())
.collect();
- let crop_area = match capture_target {
- ScreenCaptureTarget::Window(capture_window) => Some(Area {
- size: Size {
- width: capture_window.bounds.width,
- height: capture_window.bounds.height,
- },
- origin: Point {
- x: capture_window.bounds.x,
- y: capture_window.bounds.y,
- },
- }),
- ScreenCaptureTarget::Screen(_capture_screen) => None,
+ let (crop_area, bounds) = match capture_target {
+ ScreenCaptureTarget::Window(capture_window) => (
+ Some(Area {
+ size: Size {
+ width: capture_window.bounds.width,
+ height: capture_window.bounds.height,
+ },
+ origin: Point {
+ x: capture_window.bounds.x,
+ y: capture_window.bounds.y,
+ },
+ }),
+ capture_window.bounds,
+ ),
+ ScreenCaptureTarget::Screen(capture_screen) => {
+ (None, platform::monitor_bounds(capture_screen.id))
+ }
};
let target = match capture_target {
@@ -130,6 +138,7 @@ impl ScreenCaptureSource {
Self {
options,
target: capture_target.clone(),
+ bounds,
video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, fps),
}
}
@@ -146,42 +155,7 @@ impl ScreenCaptureSource {
});
#[cfg(target_os = "macos")]
- let names = {
- use cocoa::appkit::NSScreen;
- use cocoa::base::nil;
- use cocoa::foundation::{NSArray, NSString};
- use objc::{msg_send, *};
- use std::ffi::CStr;
-
- unsafe {
- let screens = NSScreen::screens(nil);
- let screen_count = NSArray::count(screens);
-
- let mut names = HashMap::new();
-
- for i in 0..screen_count {
- let screen: *mut objc::runtime::Object = screens.objectAtIndex(i);
-
- let name: id = msg_send![screen, localizedName];
- let name = CStr::from_ptr(NSString::UTF8String(name))
- .to_string_lossy()
- .to_string();
-
- 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();
-
- names.insert(num, name);
- }
-
- names
- }
- };
+ let names = crate::platform::window_names();
#[cfg(not(target_os = "macos"))]
let names = HashMap::new();
diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rs
index db71df669..4e2b4f48a 100644
--- a/crates/project/src/cursor.rs
+++ b/crates/project/src/cursor.rs
@@ -11,7 +11,7 @@ pub struct CursorEvent {
pub y: f64,
}
-#[derive(Default, Serialize, Deserialize)]
+#[derive(Default, Serialize, Deserialize, Debug)]
pub struct CursorData {
pub clicks: Vec<CursorEvent>,
pub moves: Vec<CursorEvent>,
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 9e40d42e0..b52ea3577 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -111,8 +111,9 @@ pub async fn render_video_to_channel(
project: ProjectConfiguration,
sender: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
decoders: RecordingDecoders,
+ cursor: Arc<CursorData>,
) -> Result<(), String> {
- let constants = RenderVideoConstants::new(options).await?;
+ let constants = RenderVideoConstants::new(options, cursor).await?;
println!("Setting up FFmpeg input for screen recording...");
@@ -125,7 +126,6 @@ pub async fn render_video_to_channel(
let render_handle: tokio::task::JoinHandle<Result<u32, String>> = tokio::spawn(async move {
let mut frame_number = 0;
- let uniforms = ProjectUniforms::new(&constants, &project);
let background = Background::from(project.background.source.clone());
loop {
@@ -142,6 +142,8 @@ pub async fn render_video_to_channel(
frame_number as f64 / 30_f64
};
+ let uniforms = ProjectUniforms::new(&constants, &project, time as f32);
+
let Some((screen_frame, camera_frame)) =
decoders.get_frames((time * 30.0) as u32).await
else {
@@ -205,10 +207,11 @@ pub struct RenderVideoConstants {
pub options: RenderOptions,
composite_video_frame_pipeline: CompositeVideoFramePipeline,
gradient_or_color_pipeline: GradientOrColorPipeline,
+ pub cursor: Arc<CursorData>,
}
impl RenderVideoConstants {
- pub async fn new(options: RenderOptions) -> Result<Self, String> {
+ pub async fn new(options: RenderOptions, cursor: Arc<CursorData>) -> Result<Self, String> {
println!("Initializing wgpu...");
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
let adapter = instance
@@ -228,6 +231,7 @@ impl RenderVideoConstants {
queue,
device,
options,
+ cursor,
})
}
}
@@ -295,11 +299,17 @@ impl ProjectUniforms {
((width + 1) & !1, (height + 1) & !1)
}
- pub fn new(constants: &RenderVideoConstants, project: &ProjectConfiguration) -> Self {
+ pub fn new(
+ constants: &RenderVideoConstants,
+ project: &ProjectConfiguration,
+ time: f32,
+ ) -> Self {
let options = &constants.options;
let output_size = Self::get_output_size(options, project);
let output_aspect = output_size.0 as f32 / output_size.1 as f32;
+ let cursor_position = interpolate_cursor_position(&constants.cursor, time);
+
let display = {
let output_size = [output_size.0 as f32, output_size.1 as f32];
let size = [options.screen_size.0 as f32, options.screen_size.1 as f32];
@@ -356,15 +366,21 @@ impl ProjectUniforms {
target_bounds[3] - target_bounds[1],
];
- let scale = 2.0;
- let scale_origin = (0.0, 0.0);
+ let (zoom, zoom_origin_uv) = if let Some(cursor_position) = cursor_position {
+ (
+ 1.0,
+ (cursor_position.0 as f32, cursor_position.1 as f32),
+ )
+ } else {
+ (1.0, (0.0, 0.0))
+ };
let screen_scale_origin = (
- target_bounds[0] + target_size[0] * (scale_origin.0 / size[0]),
- target_bounds[1] + target_size[1] * (scale_origin.1 / size[1]),
+ target_bounds[0] + target_size[0] * zoom_origin_uv.0,
+ target_bounds[1] + target_size[1] * zoom_origin_uv.1,
);
- let apply_scale = |val, offset| (val - offset) * scale as f32 + offset;
+ let apply_scale = |val, offset| (val - offset) * zoom as f32 + offset;
// post-zoom
let target_bounds = [
@@ -1081,3 +1097,37 @@ impl AsyncVideoDecoderHandle {
println!("Video decoder stopped");
}
}
+
+fn interpolate_cursor_position(cursor: &CursorData, time_secs: f32) -> Option<(f64, d64)> {
+ let time_ms = (time_secs * 1000.0) as f64;
+
+ let cursor_position = if cursor.moves.len() == 0 {
+ None
+ } else {
+ let moves = &cursor.moves;
+
+ let mut position = 0;
+
+ for (i, m) in moves.iter().enumerate() {
+ if m.process_time_ms < time_ms && m.process_time_ms > moves[position].process_time_ms {
+ position = i;
+ }
+ }
+
+ let m = &moves[position];
+ let next = moves.get(position + 1);
+
+ let (x, y) = if let Some(next) = next {
+ let delta = next.process_time_ms - m.process_time_ms;
+ let progress = (time_ms - m.process_time_ms) / delta;
+ (
+ m.x + (next.x - m.x) * progress,
+ m.y + (next.y - m.y) * progress,
+ )
+ } else {
+ (m.x, m.y)
+ };
+
+ Some((x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)))
+ }
+}