Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

connect cursor rendering to multi-segment (#313)

Brendan Allan979b1862c5ee
diff --git a/apps/desktop/app.config.timestamp_1738664231384.js b/apps/desktop/app.config.timestamp_1738664231384.js
deleted file mode 100644
index ed99ad588..000000000
--- a/apps/desktop/app.config.timestamp_1738664231384.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// app.config.ts
-import { defineConfig } from "@solidjs/start/config";
-import capUIPlugin from "@cap/ui-solid/vite";
-import tsconfigPaths from "vite-tsconfig-paths";
-var app_config_default = defineConfig({
- ssr: false,
- server: { preset: "static" },
- // https://vitejs.dev/config
- vite: () => ({
- // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
- // 1. tauri expects a fixed port, fail if that port is not available
- server: {
- port: 3001,
- strictPort: true,
- watch: {
- // 2. tell vite to ignore watching `src-tauri`
- ignored: ["**/src-tauri/**"]
- }
- },
- // 3. to make use of `TAURI_DEBUG` and other env variables
- // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
- envPrefix: ["VITE_", "TAURI_"],
- plugins: [
- capUIPlugin,
- tsconfigPaths({
- // If this isn't set Vinxi hangs on startup
- root: "."
- })
- ]
- })
-});
-export {
- app_config_default as default
-};
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index cdf9fb767..f883d7804 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -1,11 +1,10 @@
-use std::{
- collections::HashMap,
- ops::Deref,
- sync::{Arc, RwLock},
-};
+use std::{collections::HashMap, ops::Deref, sync::Arc};
use cap_editor::EditorInstance;
use tauri::{ipc::CommandArg, Manager, Runtime, Window};
+use tokio::sync::RwLock;
+
+use crate::create_editor_instance_impl;
#[derive(Clone)]
pub struct EditorInstances(Arc<RwLock<HashMap<String, Arc<EditorInstance>>>>);
@@ -39,22 +38,17 @@ impl<'de, R: Runtime> CommandArg<'de, R> for WindowEditorInstance {
let window = Window::from_command(command)?;
let instances = window.state::<EditorInstances>();
- let instance = instances.0.read().unwrap();
+ let instance = futures::executor::block_on(instances.0.read());
Ok(Self(instance.get(window.label()).cloned().unwrap()))
}
}
impl EditorInstances {
- pub fn get(window: &Window) -> Option<Arc<EditorInstance>> {
- let instances = window.try_state::<EditorInstances>()?;
-
- let instances = instances.0.read().unwrap();
-
- instances.get(window.label()).cloned()
- }
-
- pub fn add(window: &Window, instance: Arc<EditorInstance>) {
+ pub async fn get_or_create(
+ window: &Window,
+ video_id: &str,
+ ) -> Result<Arc<EditorInstance>, String> {
let instances = match window.try_state::<EditorInstances>() {
Some(s) => (*s).clone(),
None => {
@@ -64,16 +58,25 @@ impl EditorInstances {
}
};
- let mut instances = instances.0.write().unwrap();
+ let mut instances = instances.0.write().await;
+
+ use std::collections::hash_map::Entry;
- instances.insert(window.label().to_string(), instance);
+ match instances.entry(window.label().to_string()) {
+ Entry::Vacant(entry) => {
+ let instance = create_editor_instance_impl(window.app_handle(), video_id).await?;
+ entry.insert(instance.clone());
+ Ok(instance)
+ }
+ Entry::Occupied(entry) => Ok(entry.get().clone()),
+ }
}
- pub fn remove(window: &Window) {
+ pub async fn remove(window: &Window) {
let Some(instances) = window.try_state::<EditorInstances>() else {
return;
};
- instances.0.write().unwrap().remove(window.label());
+ instances.0.write().await.remove(window.label());
}
}
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 4cfcf926a..5a93e44b8 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -1,8 +1,9 @@
use crate::{
- create_editor_instance_impl, get_video_metadata, windows::ShowCapWindow, AuthStore,
- RenderProgress, VideoType,
+ create_editor_instance_impl, get_video_metadata, recordings_path, windows::ShowCapWindow,
+ AuthStore, RenderProgress, VideoType,
};
-use cap_project::{ProjectConfiguration, XY};
+use cap_editor::EditorInstance;
+use cap_project::{ProjectConfiguration, RecordingMeta, XY};
use std::path::PathBuf;
use tauri::AppHandle;
@@ -138,15 +139,14 @@ pub async fn get_export_estimates(
.await
.ok();
- let editor_instance = create_editor_instance_impl(&app, &video_id).await?;
-
let raw_duration = screen_metadata.duration.max(
camera_metadata
.map(|m| m.duration)
.unwrap_or(screen_metadata.duration),
);
- let meta = editor_instance.meta();
+ let project_path = EditorInstance::project_path(&recordings_path(&app), &video_id);
+ let meta = RecordingMeta::load_for_project(&project_path).unwrap();
let project_config = meta.project_config();
let duration_seconds = if let Some(timeline) = &project_config.timeline {
timeline
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index df44b3844..0520c4add 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -919,15 +919,7 @@ async fn create_editor_instance(
window: Window,
video_id: String,
) -> Result<SerializedEditorInstance, String> {
- let editor_instance = match EditorInstances::get(&window) {
- Some(editor_instance) => editor_instance,
- None => {
- let editor_instance =
- create_editor_instance_impl(window.app_handle(), &video_id).await?;
- EditorInstances::add(&window, editor_instance.clone());
- editor_instance
- }
- };
+ let editor_instance = EditorInstances::get_or_create(&window, &video_id).await?;
// Load the RecordingMeta to get the pretty name
let meta = RecordingMeta::load_for_project(&editor_instance.project_path)
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index e4bb5e27f..50f7d188b 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -13,7 +13,7 @@
"app": {
"macOSPrivateApi": true,
"security": {
- "csp": "default-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost",
+ "csp": "default-src 'self' ws: ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost",
"assetProtocol": {
"enable": true,
"scope": ["$APPDATA/**", "**/*.jpg", "$RESOURCE/**", "$HOME/**"]
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 14ed4c456..df90a0617 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -822,10 +822,13 @@ function MicrophoneSelect(props: {
<div class="flex flex-col gap-[0.25rem] items-stretch text-[--text-primary]">
<label class="text-[--text-tertiary]">Microphone</label>
<KSelect<Option>
- options={[{ name: "No Audio", deviceId: "" }, ...(devices.data ?? [])]}
+ options={[
+ { name: "No Microphone", deviceId: "" },
+ ...(devices.data ?? []),
+ ]}
optionValue="deviceId"
optionTextValue="name"
- placeholder="No Audio"
+ placeholder="No Microphone"
value={value()}
disabled={!!currentRecording.data}
onChange={handleMicrophoneChange}
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index b8e16ca6c..39b2f5c59 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -621,8 +621,8 @@ export function ConfigSidebar() {
const file = e.currentTarget.files?.[0];
if (!file) return;
- /*
- this is a Tauri bug in WebKit so we need to validate the file type manually
+ /*
+ this is a Tauri bug in WebKit so we need to validate the file type manually
https://github.com/tauri-apps/tauri/issues/9158
*/
const validExtensions = [
@@ -1127,7 +1127,7 @@ export function ConfigSidebar() {
</Field>
</KTabs.Content>
<KTabs.Content value="cursor" class="flex flex-col gap-6">
- {window.FLAGS.recordMouse === false ? (
+ {window.FLAGS.recordMouseState === false ? (
<>
<Field name="Cursor" icon={<IconCapCursor />}>
<Subfield name="Hide cursor when not moving">
@@ -1144,54 +1144,53 @@ export function ConfigSidebar() {
minValue={20}
maxValue={300}
step={1}
- disabled={window.FLAGS.recordMouse}
/>
</Field>
- <Field name="Animation Style" icon={<IconLucideRabbit />}>
- <RadioGroup
- defaultValue="regular"
- value={project.cursor.animationStyle}
- onChange={(value) => {
- setProject(
- "cursor",
- "animationStyle",
- value as CursorAnimationStyle
- );
- }}
- class="flex flex-col gap-2"
- disabled
- >
- {(
- Object.entries(CURSOR_ANIMATION_STYLES) as [
- CursorAnimationStyle,
- string
- ][]
- ).map(([value, label]) => (
- <RadioGroup.Item value={value} class="flex items-center">
- <RadioGroup.ItemInput class="peer sr-only" />
- <RadioGroup.ItemControl
- class={cx(
- "w-4 h-4 rounded-full border border-gray-300 mr-2",
- "relative after:absolute after:inset-0 after:m-auto after:block after:w-2 after:h-2 after:rounded-full",
- "after:transition-colors after:duration-200",
- "peer-checked:border-blue-500 peer-checked:after:bg-blue-400",
- "peer-focus-visible:ring-2 peer-focus-visible:ring-blue-400/50",
- "peer-disabled:opacity-50"
- )}
- />
- <span
- class={cx(
- "text-gray-500",
- "peer-checked:text-gray-900",
- "peer-disabled:opacity-50"
- )}
- >
- {label}
- </span>
- </RadioGroup.Item>
- ))}
- </RadioGroup>
- </Field>
+ {/* <Field name="Animation Style" icon={<IconLucideRabbit />}>
+ <RadioGroup
+ defaultValue="regular"
+ value={project.cursor.animationStyle}
+ onChange={(value) => {
+ setProject(
+ "cursor",
+ "animationStyle",
+ value as CursorAnimationStyle
+ );
+ }}
+ class="flex flex-col gap-2"
+ disabled
+ >
+ {(
+ Object.entries(CURSOR_ANIMATION_STYLES) as [
+ CursorAnimationStyle,
+ string
+ ][]
+ ).map(([value, label]) => (
+ <RadioGroup.Item value={value} class="flex items-center">
+ <RadioGroup.ItemInput class="peer sr-only" />
+ <RadioGroup.ItemControl
+ class={cx(
+ "w-4 h-4 rounded-full border border-gray-300 mr-2",
+ "relative after:absolute after:inset-0 after:m-auto after:block after:w-2 after:h-2 after:rounded-full",
+ "after:transition-colors after:duration-200",
+ "peer-checked:border-blue-500 peer-checked:after:bg-blue-400",
+ "peer-focus-visible:ring-2 peer-focus-visible:ring-blue-400/50",
+ "peer-disabled:opacity-50"
+ )}
+ />
+ <span
+ class={cx(
+ "text-gray-500",
+ "peer-checked:text-gray-900",
+ "peer-disabled:opacity-50"
+ )}
+ >
+ {label}
+ </span>
+ </RadioGroup.Item>
+ ))}
+ </RadioGroup>
+ </Field> */}
</>
) : (
<div class="flex flex-col items-center justify-center gap-2 text-gray-400 p-4">
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 8eb573ce9..563aaf25a 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -72,37 +72,16 @@ export function Editor() {
}
function Inner() {
- const {
- project,
- playbackTime,
- setPlaybackTime,
- playing,
- previewTime,
- videoId,
- } = useEditorContext();
+ const { project, playbackTime, setPlaybackTime, playing, previewTime } =
+ useEditorContext();
- const [isLoading, setIsLoading] = createSignal(true);
-
- onMount(async () => {
- try {
- // Initialize critical resources first
- await Promise.all([
- commands.createEditorInstance(videoId),
- // Load initial project config
- ]);
-
- setIsLoading(false);
-
- events.editorStateChanged.listen((e) => {
- renderFrame.clear();
- untrack(() => {
- setPlaybackTime(e.payload.playhead_position / FPS);
- });
+ onMount(() => {
+ events.editorStateChanged.listen((e) => {
+ renderFrame.clear();
+ untrack(() => {
+ setPlaybackTime(e.payload.playhead_position / FPS);
});
- } catch (error) {
- console.error("Failed to initialize editor:", error);
- setIsLoading(false);
- }
+ });
});
const renderFrame = throttle((time: number) => {
@@ -130,44 +109,28 @@ function Inner() {
createEffect(
on(
- () => {
- trackDeep(project);
- },
- () => {
- renderFrame(playbackTime());
- }
+ () => trackDeep(project),
+ () => renderFrame(playbackTime())
)
);
return (
- <Show
- when={!isLoading()}
- fallback={
- <div class="w-screen h-screen flex items-center justify-center bg-gray-50">
- <div class="flex flex-col items-center gap-4">
- <div class="animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-blue-400" />
- <span class="text-gray-500">Loading editor...</span>
- </div>
- </div>
- }
- >
- <div class="w-screen h-screen flex flex-col">
- <Header />
- <div
- class="p-5 pt-0 flex-1 w-full overflow-y-hidden flex flex-col gap-4 bg-gray-50 leading-5 animate-in fade-in"
- data-tauri-drag-region
- >
- <div class="rounded-2xl overflow-hidden shadow border flex-1 flex flex-col divide-y bg-white">
- <div class="flex flex-row flex-1 divide-x overflow-y-hidden">
- <Player />
- <ConfigSidebar />
- </div>
- <Timeline />
+ <div class="w-screen h-screen flex flex-col">
+ <Header />
+ <div
+ class="p-5 pt-0 flex-1 w-full overflow-y-hidden flex flex-col gap-4 bg-gray-50 leading-5 animate-in fade-in"
+ data-tauri-drag-region
+ >
+ <div class="rounded-2xl overflow-hidden shadow border flex-1 flex flex-col divide-y bg-white">
+ <div class="flex flex-row flex-1 divide-x overflow-y-hidden">
+ <Player />
+ <ConfigSidebar />
</div>
- <Dialogs />
+ <Timeline />
</div>
+ <Dialogs />
</div>
- </Show>
+ </div>
);
}
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
index 7c66bd5dc..81865575b 100644
--- a/apps/desktop/src/routes/editor/Timeline.tsx
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -482,7 +482,7 @@ function ZoomTrack(props: {
}) {
const { project, setProject, history, setState, state } = useEditorContext();
- const { duration, timelineBounds, secsPerPixel } = useTimelineContext();
+ const { duration, secsPerPixel } = useTimelineContext();
const [hoveringSegment, setHoveringSegment] = createSignal(false);
const [hoveredTime, setHoveredTime] = createSignal<number>();
@@ -505,15 +505,15 @@ function ZoomTrack(props: {
(e.clientX - bounds.left) * secsPerPixel() +
state.timelineTransform.position;
- const prevSegmentIndex = project.timeline?.zoomSegments?.findIndex(
- (s) => s.end < time
- );
-
const nextSegmentIndex = project.timeline?.zoomSegments?.findIndex(
(s) => time < s.start
);
if (nextSegmentIndex !== undefined) {
+ const prevSegmentIndex = nextSegmentIndex - 1;
+
+ if (prevSegmentIndex === undefined) return;
+
const nextSegment =
project.timeline?.zoomSegments?.[nextSegmentIndex];
@@ -552,7 +552,17 @@ function ZoomTrack(props: {
"zoomSegments",
produce((zoomSegments) => {
zoomSegments ??= [];
- zoomSegments.push({
+
+ let index = zoomSegments.length;
+
+ for (let i = zoomSegments.length - 1; i >= 0; i--) {
+ if (zoomSegments[i].start > time) {
+ index = i;
+ break;
+ }
+ }
+
+ zoomSegments.splice(index, 0, {
start: time,
end: time + 1,
amount: 1.5,
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 332f16286..9cb677005 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -87,10 +87,12 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
const [playbackTime, setPlaybackTime] = createSignal<number>(0);
const [playing, setPlaying] = createSignal(false);
- createEffect(() => {
- if (!playing())
- commands.setPlayheadPosition(Math.floor(playbackTime() * FPS));
- });
+ createEffect(
+ on(playing, () => {
+ if (!playing())
+ commands.setPlayheadPosition(Math.floor(playbackTime() * FPS));
+ })
+ );
const [split, setSplit] = createSignal(false);
diff --git a/apps/desktop/src/routes/editor/index.tsx b/apps/desktop/src/routes/editor/index.tsx
index c2a5731c8..f4d4a502f 100644
--- a/apps/desktop/src/routes/editor/index.tsx
+++ b/apps/desktop/src/routes/editor/index.tsx
@@ -1,5 +1,11 @@
+import { Suspense } from "solid-js";
import { Editor } from "./Editor";
+import { AbsoluteInsetLoader } from "~/components/Loader";
export default function () {
- return <Editor />;
+ return (
+ <Suspense fallback={<AbsoluteInsetLoader />}>
+ <Editor />
+ </Suspense>
+ );
}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 1d278e6d4..e0c6304e3 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -248,7 +248,7 @@ export type CursorType = "pointer" | "circle"
export type Display = { path: string; fps?: number }
export type EditorStateChanged = { playhead_position: number }
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
-export type Flags = { recordMouse: boolean; split: boolean; timelineZooming: boolean }
+export type Flags = { recordMouseState: boolean; split: boolean }
export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; recordingConfig?: RecordingConfig | null }
export type HapticPattern = "Alignment" | "LevelChange" | "Generic"
export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 133135447..c1c74f95e 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -1,7 +1,7 @@
use std::{sync::Arc, time::Instant};
use cap_media::{feeds::RawCameraFrame, frame_ws::WSFrame};
-use cap_project::{BackgroundSource, RecordingMeta, XY};
+use cap_project::{BackgroundSource, CursorEvents, RecordingMeta, XY};
use cap_rendering::{
decoder::DecodedFrame, DecodedSegmentFrames, FrameRenderer, ProjectRecordings, ProjectUniforms,
RenderVideoConstants,
@@ -18,6 +18,7 @@ pub enum RendererMessage {
uniforms: ProjectUniforms,
finished: oneshot::Sender<()>,
resolution_base: XY<u32>,
+ cursor: Arc<CursorEvents>,
},
Stop {
finished: oneshot::Sender<()>,
@@ -81,6 +82,7 @@ impl Renderer {
uniforms,
finished,
resolution_base,
+ cursor,
} => {
if let Some(task) = frame_task.as_ref() {
if task.is_finished() {
@@ -90,12 +92,17 @@ impl Renderer {
}
}
- let render_constants = self.render_constants.clone();
let frame_tx = self.frame_tx.clone();
// frame_task = Some(tokio::spawn(async move {
let frame = frame_renderer
- .render(segment_frames, background, &uniforms, resolution_base)
+ .render(
+ segment_frames,
+ background,
+ &uniforms,
+ resolution_base,
+ &cursor,
+ )
.await
.unwrap();
@@ -137,6 +144,7 @@ impl RendererHandle {
background: BackgroundSource,
uniforms: ProjectUniforms,
resolution_base: XY<u32>,
+ cursor: Arc<CursorEvents>,
) {
let (finished_tx, finished_rx) = oneshot::channel();
@@ -146,6 +154,7 @@ impl RendererHandle {
uniforms,
finished: finished_tx,
resolution_base,
+ cursor,
})
.await;
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index e9944c539..c118c67b6 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -11,6 +11,7 @@ use cap_rendering::{
RecordingSegmentDecoders, RenderOptions, RenderVideoConstants, SegmentVideoPaths,
};
use std::ops::Deref;
+use std::path::Path;
use std::sync::Mutex as StdMutex;
use std::time::Instant;
use std::{path::PathBuf, sync::Arc};
@@ -36,6 +37,18 @@ pub struct EditorInstance {
}
impl EditorInstance {
+ pub fn project_path(projects_path: &PathBuf, video_id: &str) -> PathBuf {
+ projects_path.join(format!(
+ "{}{}",
+ video_id,
+ if video_id.ends_with(".cap") {
+ ""
+ } else {
+ ".cap"
+ }
+ ))
+ }
+
pub async fn new(
projects_path: PathBuf,
video_id: &str,
@@ -269,8 +282,10 @@ impl EditorInstance {
fps,
resolution_base,
get_is_upgraded(),
+ &segment.cursor,
),
resolution_base,
+ segment.cursor.clone(),
)
.await;
}
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index d229cd1f2..49346f56c 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -104,6 +104,7 @@ impl Playback {
fps,
resolution_base,
is_upgraded,
+ &segment.cursor
);
self
@@ -112,7 +113,8 @@ impl Playback {
segment_frames,
project.background.source.clone(),
uniforms,
- resolution_base
+ resolution_base,
+ segment.cursor.clone()
)
.await;
}
diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs
index 991c9d5ea..3906df988 100644
--- a/crates/flags/src/lib.rs
+++ b/crates/flags/src/lib.rs
@@ -1,13 +1,11 @@
#[derive(serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct Flags {
- pub record_mouse: bool,
+ pub record_mouse_state: bool,
pub split: bool,
- pub timeline_zooming: bool,
}
pub const FLAGS: Flags = Flags {
- record_mouse: true,
+ record_mouse_state: cfg!(debug_assertions),
split: cfg!(debug_assertions),
- timeline_zooming: cfg!(debug_assertions),
};
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 3ba4e593a..b41c338c3 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -246,7 +246,7 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
Options {
fps: self.fps,
- show_cursor: FLAGS.record_mouse,
+ show_cursor: !FLAGS.record_mouse_state,
show_highlight: true,
target: Some(target),
crop_area,
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 70af3ce0e..123e5a8c9 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -137,6 +137,17 @@ impl<T: Div<Output = T> + Copy> Div<T> for XY<T> {
}
}
+impl<T: Div<Output = T>> Div<XY<T>> for XY<T> {
+ type Output = Self;
+
+ fn div(self, other: XY<T>) -> Self {
+ Self {
+ x: self.x / other.x,
+ y: self.y / other.y,
+ }
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Crop {
diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rs
index 41309320e..e4a118122 100644
--- a/crates/project/src/cursor.rs
+++ b/crates/project/src/cursor.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::fs::File;
-use std::path::Path;
+use std::path::{Path, PathBuf};
#[derive(Serialize, Deserialize, Clone, Type, Debug)]
pub struct CursorMoveEvent {
@@ -28,7 +28,7 @@ pub struct CursorClickEvent {
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
#[serde(transparent)]
-pub struct CursorImages(pub HashMap<String, String>);
+pub struct CursorImages(pub HashMap<String, PathBuf>);
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct CursorData {
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index 408f2045a..efb2fc613 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -176,9 +176,7 @@ impl SingleSegment {
.and_then(|s| s.strip_suffix(".png"))
{
println!("Found cursor image: {} -> {}", id, filename_str);
- data.cursor_images
- .0
- .insert(id.to_string(), filename.to_string_lossy().into_owned());
+ data.cursor_images.0.insert(id.to_string(), entry.path());
}
}
}
@@ -193,7 +191,8 @@ impl SingleSegment {
pub struct MultipleSegments {
pub segments: Vec<MultipleSegment>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
- pub cursors: HashMap<String, PathBuf>,
+ #[specta(type = HashMap<String, String>)]
+ pub cursors: HashMap<String, RelativePathBuf>,
}
impl MultipleSegments {
@@ -202,40 +201,12 @@ impl MultipleSegments {
}
pub fn cursor_images(&self, meta: &RecordingMeta) -> Result<CursorImages, String> {
- let file = File::open(self.path(meta, "content/cursors.json"))
- .map_err(|e| format!("Failed to open cursor file: {}", e))?;
- let cursor_images: CursorImages = serde_json::from_reader(file)
- .map_err(|e| format!("Failed to parse cursor data: {}", e))?;
-
- // let cursors_dir = self.path(meta, "content/cursors");
- // if cursor_images.0.is_empty() && cursors_dir.exists() {
- // println!("Scanning cursors directory: {:?}", cursors_dir);
- // if let Ok(entries) = std::fs::read_dir(&cursors_dir) {
- // for entry in entries {
- // let Ok(entry) = entry else {
- // continue;
- // };
-
- // let filename = entry.file_name();
- // let filename_str = filename.to_string_lossy();
- // if filename_str.starts_with("cursor_") && filename_str.ends_with(".png") {
- // // Extract cursor ID from filename (cursor_X.png -> X)
- // if let Some(id) = filename_str
- // .strip_prefix("cursor_")
- // .and_then(|s| s.strip_suffix(".png"))
- // {
- // println!("Found cursor image: {} -> {}", id, filename_str);
- // cursor_images
- // .0
- // .insert(id.to_string(), filename.to_string_lossy().into_owned());
- // }
- // }
- // }
- // }
- // println!("Found {} cursor images", cursor_images.0.len());
- // }
-
- Ok(cursor_images)
+ Ok(CursorImages(
+ self.cursors
+ .iter()
+ .map(|(k, v)| (k.clone(), meta.path(v)))
+ .collect::<_>(),
+ ))
}
}
@@ -247,7 +218,8 @@ pub struct MultipleSegment {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio: Option<AudioMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub cursor: Option<PathBuf>,
+ #[specta(type = Option<String>)]
+ pub cursor: Option<RelativePathBuf>,
}
impl MultipleSegment {
@@ -260,7 +232,7 @@ impl MultipleSegment {
return CursorEvents::default();
};
- let full_path = self.path(meta, cursor_path);
+ let full_path = meta.path(cursor_path);
println!("Loading cursor data from: {:?}", full_path);
// Try to load the cursor data
diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rs
index 4e258b2e4..f0fdf8fe1 100644
--- a/crates/recording/src/actor.rs
+++ b/crates/recording/src/actor.rs
@@ -76,7 +76,7 @@ struct RecordingPipeline {
struct CursorPipeline {
output_path: PathBuf,
- actor: CursorActor,
+ actor: Option<CursorActor>,
}
#[derive(Clone)]
@@ -237,8 +237,10 @@ pub async fn spawn_recording_actor(
loop {
let msg = tokio::select! {
_ = &mut pipeline_done_rx => {
- if let Some(cursor) = pipeline.cursor.take() {
- cursor.actor.stop().await;
+ if let Some(cursor) = &mut pipeline.cursor {
+ if let Some(actor) = cursor.actor.take() {
+ actor.stop().await;
+ }
}
break 'outer;
@@ -262,18 +264,22 @@ pub async fn spawn_recording_actor(
let segment_stop_time = current_time_f64();
- let cursors = if let Some(cursor) = pipeline.cursor.take() {
- let res = cursor.actor.stop().await;
-
- std::fs::write(
- &cursor.output_path,
- serde_json::to_string_pretty(&CursorEvents {
- clicks: res.clicks,
- moves: res.moves,
- })?,
- )?;
-
- (res.cursors, res.next_cursor_id)
+ let cursors = if let Some(cursor) = &mut pipeline.cursor {
+ if let Some(actor) = cursor.actor.take() {
+ let res = actor.stop().await;
+
+ std::fs::write(
+ &cursor.output_path,
+ serde_json::to_string_pretty(&CursorEvents {
+ clicks: res.clicks,
+ moves: res.moves,
+ })?,
+ )?;
+
+ (res.cursors, res.next_cursor_id)
+ } else {
+ Default::default()
+ }
} else {
Default::default()
};
@@ -457,7 +463,16 @@ async fn stop_recording(
)
.unwrap(),
}),
- cursor: None,
+ cursor: s.pipeline.cursor.as_ref().map(|cursor| {
+ RelativePathBuf::from_path(
+ cursor
+ .output_path
+ .strip_prefix(&actor.recording_dir)
+ .unwrap()
+ .to_owned(),
+ )
+ .unwrap()
+ }),
})
.collect()
},
@@ -466,7 +481,7 @@ async fn stop_recording(
.map(|(file_name, id)| {
(
id.to_string(),
- PathBuf::from("content/cursors").join(&file_name),
+ RelativePathBuf::from("content/cursors").join(&file_name),
)
})
.collect(),
@@ -607,7 +622,7 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
- let cursor = FLAGS.record_mouse.then(|| {
+ let cursor = FLAGS.record_mouse_state.then(|| {
let cursor = spawn_cursor_recorder(
screen_bounds,
cursors_dir.clone(),
@@ -617,7 +632,7 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
CursorPipeline {
output_path: dir.join("cursor.json"),
- actor: cursor,
+ actor: Some(cursor),
}
});
diff --git a/crates/rendering/src/coord.rs b/crates/rendering/src/coord.rs
index 17ab72a4f..241caf44e 100644
--- a/crates/rendering/src/coord.rs
+++ b/crates/rendering/src/coord.rs
@@ -2,7 +2,7 @@ use std::ops::{Add, Deref, Mul, Sub};
use cap_project::{ProjectConfiguration, XY};
-use crate::{ProjectUniforms, RenderOptions};
+use crate::{zoom::InterpolatedZoom, ProjectUniforms, RenderOptions};
#[derive(Default, Clone, Copy, Debug)]
pub struct RawDisplaySpace;
@@ -17,6 +17,9 @@ pub struct CroppedDisplaySpace;
#[derive(Default, Clone, Copy, Debug)]
pub struct FrameSpace;
+#[derive(Default, Clone, Copy, Debug)]
+pub struct ZoomedFrameSpace;
+
#[derive(Default, Clone, Copy, Debug)]
pub struct TransformedDisplaySpace;
@@ -81,6 +84,8 @@ impl Coord<RawDisplaySpace> {
}
}
+fn frame_size() {}
+
impl Coord<CroppedDisplaySpace> {
pub fn to_frame_space(
&self,
@@ -88,8 +93,40 @@ impl Coord<CroppedDisplaySpace> {
project: &ProjectConfiguration,
resolution_base: XY<u32>,
) -> Coord<FrameSpace> {
- let padding = ProjectUniforms::get_display_offset(options, project, resolution_base);
- Coord::new(self.coord + *padding)
+ let crop = ProjectUniforms::get_crop(options, project);
+ let output_size = ProjectUniforms::get_output_size(options, project, resolution_base);
+ let padding_offset = ProjectUniforms::display_offset(options, project, resolution_base);
+
+ let output_size = XY::new(output_size.0, output_size.1).map(|v| v as f64);
+
+ let position_ratio = self.coord / crop.size.map(|v| v as f64);
+
+ Coord::new(
+ padding_offset.coord + (output_size - padding_offset.coord * 2.0) * position_ratio,
+ )
+ }
+}
+
+impl Coord<FrameSpace> {
+ pub fn to_zoomed_frame_space(
+ &self,
+ options: &RenderOptions,
+ project: &ProjectConfiguration,
+ resolution_base: XY<u32>,
+ zoom: &InterpolatedZoom,
+ ) -> Coord<ZoomedFrameSpace> {
+ let padding_offset = ProjectUniforms::display_offset(options, project, resolution_base);
+ let display_size = ProjectUniforms::display_size(options, project, resolution_base);
+
+ let size_ratio = zoom.bounds.bottom_right - zoom.bounds.top_left;
+
+ let screen_position = (*self - padding_offset).coord;
+
+ Coord::new(
+ screen_position * size_ratio
+ + zoom.bounds.top_left * display_size.coord
+ + padding_offset.coord,
+ )
}
}
diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rs
index 2591afd49..182477b43 100644
--- a/crates/rendering/src/frame_pipeline.rs
+++ b/crates/rendering/src/frame_pipeline.rs
@@ -40,6 +40,10 @@ impl<'a> FramePipelineState<'a> {
}
}
+ pub fn is_left(&self) -> bool {
+ self.output_is_left
+ }
+
pub fn get_current_texture_view(&self) -> &wgpu::TextureView {
get_either(
(&self.texture_views.0, &self.texture_views.1),
@@ -55,11 +59,11 @@ impl<'a> FramePipelineState<'a> {
}
pub fn get_current_texture(&self) -> &wgpu::Texture {
- get_either((&self.textures.1, &self.textures.0), self.output_is_left)
+ get_either((&self.textures.0, &self.textures.1), self.output_is_left)
}
pub fn get_other_texture(&self) -> &wgpu::Texture {
- get_either((&self.textures.1, &self.textures.0), !self.output_is_left)
+ get_either((&self.textures.0, &self.textures.1), !self.output_is_left)
}
pub fn switch_output(&mut self) {
@@ -105,7 +109,7 @@ impl FramePipelineEncoder {
render_pass.set_pipeline(render_pipeline);
render_pass.set_bind_group(0, &bind_group, &[]);
- render_pass.draw(0..3, 0..1);
+ render_pass.draw(0..4, 0..1);
}
pub fn padded_bytes_per_row(&self, state: &FramePipelineState<'_>) -> u32 {
@@ -145,33 +149,31 @@ impl FramePipelineEncoder {
mapped_at_creation: false,
});
- {
- let mut encoder = constants.device.create_command_encoder(
- &(wgpu::CommandEncoderDescriptor {
- label: Some("Copy Encoder"),
- }),
- );
-
- encoder.copy_texture_to_buffer(
- wgpu::ImageCopyTexture {
- texture: state.get_current_texture(),
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::ImageCopyBuffer {
- buffer: &output_buffer,
- layout: wgpu::ImageDataLayout {
- offset: 0,
- bytes_per_row: Some(padded_bytes_per_row),
- rows_per_image: Some(state.uniforms.output_size.1),
- },
+ let mut encoder = constants.device.create_command_encoder(
+ &(wgpu::CommandEncoderDescriptor {
+ label: Some("Copy Encoder"),
+ }),
+ );
+
+ encoder.copy_texture_to_buffer(
+ wgpu::ImageCopyTexture {
+ texture: state.get_current_texture(),
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::ImageCopyBuffer {
+ buffer: &output_buffer,
+ layout: wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(padded_bytes_per_row),
+ rows_per_image: Some(state.uniforms.output_size.1),
},
- output_texture_size,
- );
+ },
+ output_texture_size,
+ );
- constants.queue.submit(std::iter::once(encoder.finish()));
- }
+ constants.queue.submit(std::iter::once(encoder.finish()));
let buffer_slice = output_buffer.slice(..);
let (tx, rx) = oneshot_channel();
diff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rs
index 6ce266a55..96e99e71f 100644
--- a/crates/rendering/src/layers/background.rs
+++ b/crates/rendering/src/layers/background.rs
@@ -77,6 +77,8 @@ impl BackgroundLayer {
let constants = pipeline.state.constants;
let uniforms = pipeline.state.uniforms;
+ pipeline.state.switch_output();
+
// First, handle the background
match background {
Background::Image { path } => {
@@ -193,9 +195,9 @@ impl BackgroundLayer {
}
}
- pipeline.state.switch_output();
-
if uniforms.project.background.blur > 0.0 {
+ pipeline.state.switch_output();
+
let blur_strength = uniforms.project.background.blur as f32 / 100.0;
let blur_uniform = BackgroundBlurUniforms {
output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],
@@ -233,8 +235,6 @@ impl BackgroundLayer {
blur_bind_group,
wgpu::LoadOp::Clear(wgpu::Color::BLACK),
);
-
- pipeline.state.switch_output();
}
Ok(())
diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rs
index 3d25b3a4b..cd077dbef 100644
--- a/crates/rendering/src/layers/camera.rs
+++ b/crates/rendering/src/layers/camera.rs
@@ -34,6 +34,8 @@ impl CameraLayer {
},
);
+ pipeline.state.switch_output();
+
pipeline.encoder.do_render_pass(
pipeline.state.get_current_texture_view(),
&constants.composite_video_frame_pipeline.render_pipeline,
@@ -45,7 +47,5 @@ impl CameraLayer {
),
wgpu::LoadOp::Load,
);
-
- pipeline.state.switch_output();
}
}
diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs
index c161ccb9a..f0a795b2b 100644
--- a/crates/rendering/src/layers/cursor.rs
+++ b/crates/rendering/src/layers/cursor.rs
@@ -6,7 +6,8 @@ use wgpu::{include_wgsl, util::DeviceExt};
use crate::{
frame_pipeline::{FramePipeline, FramePipelineState},
- Coord, DecodedSegmentFrames, RawDisplayUVSpace, STANDARD_CURSOR_HEIGHT,
+ zoom::InterpolatedZoom,
+ Coord, DecodedSegmentFrames, ProjectUniforms, RawDisplayUVSpace, STANDARD_CURSOR_HEIGHT,
};
pub struct CursorLayer;
@@ -16,6 +17,8 @@ impl CursorLayer {
pipeline: &mut FramePipeline,
segment_frames: &DecodedSegmentFrames,
resolution_base: XY<u32>,
+ cursor: &CursorEvents,
+ zoom: &InterpolatedZoom,
) {
let FramePipelineState {
uniforms,
@@ -25,7 +28,7 @@ impl CursorLayer {
let segment_time = segment_frames.segment_time;
let Some(cursor_position) = interpolate_cursor_position(
- &Default::default(), // constants.cursor,
+ cursor,
segment_time,
&uniforms.project.cursor.animation_style,
) else {
@@ -33,40 +36,36 @@ impl CursorLayer {
};
// Calculate previous position for velocity
- let prev_position = interpolate_cursor_position(
- &Default::default(), // constants.cursor,
- segment_time - 1.0 / 30.0,
- &uniforms.project.cursor.animation_style,
- );
+ // let prev_position = interpolate_cursor_position(
+ // cursor,
+ // segment_time - 1.0 / 30.0,
+ // &uniforms.project.cursor.animation_style,
+ // );
// Calculate velocity in screen space
- let velocity = if let Some(prev_pos) = prev_position {
- let curr_frame_pos = cursor_position.to_frame_space(
- &constants.options,
- &uniforms.project,
- resolution_base,
- );
- let prev_frame_pos =
- prev_pos.to_frame_space(&constants.options, &uniforms.project, resolution_base);
- let frame_velocity = curr_frame_pos.coord - prev_frame_pos.coord;
-
- // Convert to pixels per frame
- [frame_velocity.x as f32, frame_velocity.y as f32]
- } else {
- [0.0, 0.0]
- };
+ let velocity: [f32; 2] = [0.0, 0.0];
+ // if let Some(prev_pos) = prev_position {
+ // let curr_frame_pos =
+ // cursor_position.to_frame_space(&constants.options, &uniforms.project, resolution_base);
+ // let prev_frame_pos =
+ // prev_pos.to_frame_space(&constants.options, &uniforms.project, resolution_base);
+ // let frame_velocity = curr_frame_pos.coord - prev_frame_pos.coord;
+
+ // // Convert to pixels per frame
+ // [frame_velocity.x as f32, frame_velocity.y as f32]
+ // } else {
+ // [0.0, 0.0]
+ // };
// Calculate motion blur amount based on velocity magnitude
let speed = (velocity[0] * velocity[0] + velocity[1] * velocity[1]).sqrt();
let motion_blur_amount =
(speed * 0.3).min(1.0) * uniforms.project.motion_blur.unwrap_or(0.8);
- let cursor = Default::default();
- let cursor_event = find_cursor_event(&cursor /* constants.cursor */, segment_time);
+ let cursor_event = find_cursor_event(&cursor, segment_time);
- let last_click_time = /* constants
- .cursor
- .clicks */ Vec::<CursorClickEvent>::new()
+ let last_click_time = cursor
+ .clicks
.iter()
.filter(|click| click.down && click.process_time_ms <= (segment_time as f64) * 1000.0)
.max_by_key(|click| click.process_time_ms as i64)
@@ -91,12 +90,29 @@ impl CursorLayer {
STANDARD_CURSOR_HEIGHT * cursor_size_percentage,
];
- let frame_position =
- cursor_position.to_frame_space(&constants.options, &uniforms.project, resolution_base);
- // let position = uniforms.zoom.apply_scale(frame_position);
- let position = frame_position;
+ let position = cursor_position
+ .to_frame_space(&constants.options, &uniforms.project, resolution_base)
+ .to_zoomed_frame_space(&constants.options, &uniforms.project, resolution_base, zoom);
let relative_position = [position.x as f32, position.y as f32];
+ fn smoothstep(low: f32, high: f32, v: f32) -> f32 {
+ let t = f32::clamp((v - low) / (high - low), 0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+ }
+
+ let click_scale = 1.0
+ - (0.2
+ * smoothstep(0.0, 0.25, last_click_time)
+ * (1.0 - smoothstep(0.25, 0.5, last_click_time)));
+
+ let output_size = ProjectUniforms::get_output_size(
+ &constants.options,
+ &uniforms.project,
+ resolution_base,
+ );
+ let display_size =
+ ProjectUniforms::display_size(&constants.options, &uniforms.project, resolution_base);
+
let cursor_uniforms = CursorUniforms {
position: [relative_position[0], relative_position[1], 0.0, 0.0],
size: [normalized_size[0], normalized_size[1], 0.0, 0.0],
@@ -107,7 +123,10 @@ impl CursorLayer {
0.0,
],
screen_bounds: uniforms.display.target_bounds,
- cursor_size: cursor_size_percentage,
+ cursor_size: cursor_size_percentage
+ * click_scale
+ * zoom.display_amount() as f32
+ * (display_size.coord.x as f32 / output_size.0 as f32),
last_click_time,
velocity,
motion_blur_amount,
@@ -156,8 +175,6 @@ impl CursorLayer {
cursor_bind_group,
wgpu::LoadOp::Load,
);
-
- pipeline.state.switch_output();
}
}
@@ -180,9 +197,13 @@ pub struct CursorUniforms {
_alignment: [f32; 7],
}
-pub fn find_cursor_event(cursor: &CursorData, time: f32) -> &CursorMoveEvent {
+pub fn find_cursor_event(cursor: &CursorEvents, time: f32) -> &CursorMoveEvent {
let time_ms = time * 1000.0;
+ if cursor.moves[0].process_time_ms > time_ms.into() {
+ return &cursor.moves[0];
+ }
+
let event = cursor
.moves
.iter()
@@ -301,7 +322,7 @@ impl CursorPipeline {
}
fn interpolate_cursor_position(
- cursor: &CursorData,
+ cursor: &CursorEvents,
time_secs: f32,
animation_style: &CursorAnimationStyle,
) -> Option<Coord<RawDisplayUVSpace>> {
@@ -311,108 +332,36 @@ fn interpolate_cursor_position(
return None;
}
- // Get style-specific parameters
- let (num_samples, velocity_threshold) = match animation_style {
- CursorAnimationStyle::Slow => (SLOW_SMOOTHING_SAMPLES, SLOW_VELOCITY_THRESHOLD),
- CursorAnimationStyle::Regular => (REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD),
- CursorAnimationStyle::Fast => (FAST_SMOOTHING_SAMPLES, FAST_VELOCITY_THRESHOLD),
- };
+ if cursor.moves[0].process_time_ms > time_ms.into() {
+ let event = &cursor.moves[0];
- // Find the closest move events around current time
- let mut closest_events: Vec<&CursorMoveEvent> = cursor
- .moves
- .iter()
- .filter(|m| (m.process_time_ms - time_ms).abs() <= 100.0) // Look at events within 100ms
- .collect();
-
- closest_events.sort_by(|a, b| {
- (a.process_time_ms - time_ms)
- .abs()
- .partial_cmp(&(b.process_time_ms - time_ms).abs())
- .unwrap()
- });
-
- // Take the nearest events up to num_samples
- let samples: Vec<(f64, f64, f64)> = closest_events
- .iter()
- .take(num_samples)
- .map(|m| (m.process_time_ms, m.x, m.y))
- .collect();
-
- if samples.is_empty() {
- // Fallback to nearest event if no samples in range
- let nearest = cursor
- .moves
- .iter()
- .min_by_key(|m| (m.process_time_ms - time_ms).abs() as i64)?;
return Some(Coord::new(XY {
- x: nearest.x.clamp(0.0, 1.0),
- y: nearest.y.clamp(0.0, 1.0),
+ x: event.x,
+ y: event.y,
}));
}
- // Calculate velocities between consecutive points
- let mut velocities = Vec::with_capacity(samples.len() - 1);
- for i in 0..samples.len() - 1 {
- let (t1, x1, y1) = samples[i];
- let (t2, x2, y2) = samples[i + 1];
- let dt = (t2 - t1).max(1.0); // Avoid division by zero
- let dx = x2 - x1;
- let dy = y2 - y1;
- let velocity = ((dx * dx + dy * dy) / (dt * dt)).sqrt();
- velocities.push(velocity);
+ if let Some(event) = cursor.moves.last() {
+ if event.process_time_ms < time_ms.into() {
+ return Some(Coord::new(XY {
+ x: event.x,
+ y: event.y,
+ }));
+ }
}
- // Apply adaptive smoothing based on velocities and time distance
- let mut x = 0.0;
- let mut y = 0.0;
- let mut total_weight = 0.0;
-
- for (i, &(t, px, py)) in samples.iter().enumerate() {
- // Time-based weight with style-specific falloff
- let time_diff = (t - time_ms).abs();
- let style_factor = match animation_style {
- CursorAnimationStyle::Slow => 0.0005,
- CursorAnimationStyle::Regular => 0.001,
- CursorAnimationStyle::Fast => 0.002,
- };
- let time_weight = 1.0 / (1.0 + time_diff * style_factor);
-
- // Velocity-based weight
- let velocity_weight = if i < velocities.len() {
- let vel = velocities[i];
- if vel > velocity_threshold {
- (velocity_threshold / vel).powf(match animation_style {
- CursorAnimationStyle::Slow => 1.5,
- CursorAnimationStyle::Regular => 1.0,
- CursorAnimationStyle::Fast => 0.5,
- })
- } else {
- 1.0
- }
+ let Some(event) = cursor.moves.windows(2).find_map(|chunk| {
+ if time_ms >= chunk[0].process_time_ms && time_ms < chunk[1].process_time_ms {
+ Some(&chunk[0])
} else {
- 1.0
- };
-
- // Combine weights with style-specific emphasis
- let weight = match animation_style {
- CursorAnimationStyle::Slow => time_weight * velocity_weight.powf(1.5),
- CursorAnimationStyle::Regular => time_weight * velocity_weight,
- CursorAnimationStyle::Fast => time_weight * velocity_weight.powf(0.5),
- };
-
- x += px * weight;
- y += py * weight;
- total_weight += weight;
- }
-
- if total_weight > 0.0 {
- x /= total_weight;
- y /= total_weight;
- }
+ None
+ }
+ }) else {
+ return None;
+ };
Some(Coord::new(XY {
- x: x.clamp(0.0, 1.0),
- y: y.clamp(0.0, 1.0),
+ x: event.x,
+ y: event.y,
}))
}
diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs
index 20fa01281..8b891ac1c 100644
--- a/crates/rendering/src/layers/display.rs
+++ b/crates/rendering/src/layers/display.rs
@@ -30,6 +30,8 @@ impl DisplayLayer {
},
);
+ pipeline.state.switch_output();
+
pipeline.encoder.do_render_pass(
pipeline.state.get_current_texture_view(),
&constants.composite_video_frame_pipeline.render_pipeline,
@@ -41,7 +43,5 @@ impl DisplayLayer {
),
wgpu::LoadOp::Load,
);
-
- pipeline.state.switch_output();
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index dce85da66..77b7285ed 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -137,7 +137,7 @@ pub async fn render_video_to_channel(
resolution_base: XY<u32>,
is_upgraded: bool,
) -> Result<(), RenderingError> {
- let mut constants = RenderVideoConstants::new(options, meta).await?;
+ let constants = RenderVideoConstants::new(options, meta).await?;
let recordings = ProjectRecordings::new(meta);
ffmpeg::init().unwrap();
@@ -189,6 +189,7 @@ pub async fn render_video_to_channel(
fps,
resolution_base,
is_upgraded,
+ &segment.cursor,
);
let frame = frame_renderer
.render(
@@ -196,6 +197,7 @@ pub async fn render_video_to_channel(
background.clone(),
&uniforms,
resolution_base,
+ &segment.cursor,
)
.await?;
@@ -393,18 +395,17 @@ impl RenderVideoConstants {
Content::MultipleSegments { inner } => inner.cursor_images(meta).unwrap_or_default(),
};
- for (cursor_id, filename) in &cursor_images.0 {
- println!("Loading cursor image: {} -> {}", cursor_id, filename);
+ for (cursor_id, path) in &cursor_images.0 {
+ println!("Loading cursor image: {} -> {}", cursor_id, path.display());
- let cursor_path = cursors_dir.join(filename);
- println!("Full cursor path: {:?}", cursor_path);
+ println!("Full cursor path: {:?}", path);
- if !cursor_path.exists() {
- println!("Cursor image file does not exist: {:?}", cursor_path);
+ if !path.exists() {
+ println!("Cursor image file does not exist: {:?}", path);
continue;
}
- match image::open(&cursor_path) {
+ match image::open(&path) {
Ok(img) => {
let dimensions = img.dimensions();
println!(
@@ -454,7 +455,7 @@ impl RenderVideoConstants {
println!("Successfully loaded cursor texture: {}", cursor_id);
}
Err(e) => {
- println!("Failed to load cursor image {}: {}", filename, e);
+ println!("Failed to load cursor image {}: {}", path.display(), e);
// Don't return error, just skip this cursor image
continue;
}
@@ -477,6 +478,7 @@ pub struct ProjectUniforms {
camera: Option<CompositeVideoFrameUniforms>,
pub project: ProjectConfiguration,
pub is_upgraded: bool,
+ pub zoom: InterpolatedZoom,
}
#[derive(Debug, Clone)]
@@ -579,7 +581,7 @@ impl ProjectUniforms {
// ((base_width + 1) & !1, (base_height + 1) & !1)
}
- pub fn get_display_offset(
+ pub fn display_offset(
options: &RenderOptions,
project: &ProjectConfiguration,
resolution_base: XY<u32>,
@@ -622,6 +624,21 @@ impl ProjectUniforms {
})
}
+ pub fn display_size(
+ options: &RenderOptions,
+ project: &ProjectConfiguration,
+ resolution_base: XY<u32>,
+ ) -> Coord<FrameSpace> {
+ let output_size = Self::get_output_size(options, project, resolution_base);
+ let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
+
+ let display_offset = Self::display_offset(options, project, resolution_base);
+
+ let end = Coord::new(output_size) - display_offset;
+
+ end - display_offset
+ }
+
pub fn new(
constants: &RenderVideoConstants,
project: &ProjectConfiguration,
@@ -629,17 +646,12 @@ impl ProjectUniforms {
fps: u32,
resolution_base: XY<u32>,
is_upgraded: bool,
+ cursor_events: &CursorEvents,
) -> Self {
let options = &constants.options;
let output_size = Self::get_output_size(options, project, resolution_base);
let frame_time = frame_number as f32 / fps as f32;
- // let cursor_position = interpolate_cursor_position(
- // &Default::default(), /*constants.cursor*/
- // frame_time,
- // &project.cursor.animation_style,
- // );
-
// let zoom_keyframes = ZoomKeyframes::new(project);
// let current_zoom = zoom_keyframes.interpolate(time as f64);
// let prev_zoom = zoom_keyframes.interpolate((time - 1.0 / 30.0) as f64);
@@ -689,15 +701,14 @@ impl ProjectUniforms {
(crop.position.y + crop.size.y) as f64,
));
- let display_offset = Self::get_display_offset(options, project, resolution_base);
+ let display_offset = Self::display_offset(options, project, resolution_base);
+ let display_size = Self::display_size(options, project, resolution_base);
let end = Coord::new(output_size) - display_offset;
- let target_size = end - display_offset;
-
let (zoom_start, zoom_end) = (
- Coord::new(zoom.bounds.top_left * target_size.coord),
- Coord::new((zoom.bounds.bottom_right - 1.0) * target_size.coord),
+ Coord::new(zoom.bounds.top_left * display_size.coord),
+ Coord::new((zoom.bounds.bottom_right - 1.0) * display_size.coord),
);
let start = display_offset + zoom_start;
@@ -832,6 +843,7 @@ impl ProjectUniforms {
camera,
project: project.clone(),
is_upgraded,
+ zoom,
}
}
}
@@ -901,6 +913,7 @@ impl<'a> FrameRenderer<'a> {
background: BackgroundSource,
uniforms: &ProjectUniforms,
resolution_base: XY<u32>,
+ cursor: &CursorEvents,
) -> Result<RenderedFrame, RenderingError> {
self.update_output_textures(uniforms.output_size.0, uniforms.output_size.1);
@@ -911,6 +924,7 @@ impl<'a> FrameRenderer<'a> {
uniforms,
resolution_base,
self.output_textures.as_ref().unwrap(),
+ cursor,
)
.await
}
@@ -923,6 +937,7 @@ async fn produce_frame(
uniforms: &ProjectUniforms,
resolution_base: XY<u32>,
textures: &(wgpu::Texture, wgpu::Texture),
+ cursor: &CursorEvents,
) -> Result<RenderedFrame, RenderingError> {
let background = Background::from(background);
@@ -939,7 +954,13 @@ async fn produce_frame(
DisplayLayer::render(&mut pipeline, &segment_frames);
- CursorLayer::render(&mut pipeline, &segment_frames, resolution_base);
+ CursorLayer::render(
+ &mut pipeline,
+ &segment_frames,
+ resolution_base,
+ &cursor,
+ &uniforms.zoom,
+ );
if let (
Some(camera_size),
diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgsl
index 7935de49c..e251e8183 100644
--- a/crates/rendering/src/shaders/cursor.wgsl
+++ b/crates/rendering/src/shaders/cursor.wgsl
@@ -27,10 +27,10 @@ var s_cursor: sampler;
@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
var positions = array<vec2<f32>, 4>(
- vec2<f32>(-0.5, 0.5),
- vec2<f32>(-0.5, -0.5),
- vec2<f32>(0.5, 0.5),
- vec2<f32>(0.5, -0.5)
+ vec2<f32>(0.0, 0.0),
+ vec2<f32>(0.0, -1.0),
+ vec2<f32>(1.0, 0.0),
+ vec2<f32>(1.0, -1.0)
);
var uvs = array<vec2<f32>, 4>(
@@ -43,19 +43,17 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
let pos = positions[vertex_index];
let size = uniforms.size.xy;
let screen_pos = uniforms.position.xy;
-
+
// Calculate click animation scale factor
let time_since_click = uniforms.last_click_time;
- let click_scale = 1.0 - (0.2 * smoothstep(0.0, 0.25, time_since_click) * (1.0 - smoothstep(0.25, 0.5, time_since_click)));
-
- // Apply cursor size scaling with click animation
- let scaled_size = size * uniforms.cursor_size * click_scale;
-
+
+ let scaled_size = size * uniforms.cursor_size;
+
// Calculate final position - centered around cursor position
// Flip the Y coordinate by subtracting from output height
var adjusted_pos = screen_pos;
adjusted_pos.y = uniforms.output_size.y - adjusted_pos.y; // Flip Y coordinate
-
+
let final_pos = ((pos * scaled_size) + adjusted_pos) / uniforms.output_size.xy * 2.0 - 1.0;
var output: VertexOutput;
@@ -70,42 +68,42 @@ fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
let num_samples = 16;
var color_sum = vec4<f32>(0.0);
var weight_sum = 0.0;
-
+
// Calculate velocity magnitude for adaptive blur strength
let velocity_mag = length(uniforms.velocity);
let adaptive_blur = uniforms.motion_blur_amount * smoothstep(0.0, 50.0, velocity_mag);
-
+
// Calculate blur direction from velocity
var blur_dir = vec2<f32>(0.0);
if (velocity_mag > 0.0) {
blur_dir = uniforms.velocity / velocity_mag;
}
-
+
// Enhanced blur trail
let max_blur_offset = 3.0 * adaptive_blur;
-
+
for (var i = 0; i < num_samples; i++) {
// Non-linear sampling for better blur distribution
let t = pow(f32(i) / f32(num_samples - 1), 1.5) * 2.0 - 1.0;
-
+
// Gaussian-like weight distribution
let weight = exp(-3.0 * t * t);
-
+
// Calculate sample offset with velocity-based scaling
let offset = blur_dir * max_blur_offset * t;
let sample_uv = input.uv + offset / uniforms.output_size.xy;
-
+
// Sample with bilinear filtering
let sample = textureSample(t_cursor, s_cursor, sample_uv);
-
+
// Accumulate weighted sample
color_sum += sample * weight;
weight_sum += weight;
}
-
+
// Normalize the result
var final_color = color_sum / weight_sum;
-
+
// Enhance contrast slightly for fast movements
if (velocity_mag > 30.0) {
// Create new color with enhanced contrast instead of modifying components
@@ -116,6 +114,6 @@ fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
final_color.a
);
}
-
+
return final_color;
}
diff --git a/crates/rendering/src/zoom.rs b/crates/rendering/src/zoom.rs
index 2b2ff1f32..d626ea5f9 100644
--- a/crates/rendering/src/zoom.rs
+++ b/crates/rendering/src/zoom.rs
@@ -101,6 +101,11 @@ impl InterpolatedZoom {
Self::new_with_easing(cursor, ease_in, ease_out)
}
+ // the multiplier applied to the display width/height
+ pub fn display_amount(&self) -> f64 {
+ (self.bounds.bottom_right - self.bounds.top_left).x
+ }
+
pub(self) fn new_with_easing(
cursor: SegmentsCursor,
ease_in: impl Fn(f32) -> f32,