Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add mask track with editable mask segments to editor

Richie McIlroyd2c2804ac9ca
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 0fc5b6cb7..af9b13617 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1705,6 +1705,7 @@ fn project_config_from_recording(
segments: timeline_segments,
zoom_segments,
scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
});
config
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index be5deaee7..e2b1d74cf 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -52,13 +52,20 @@ import {
type TimelineSegment,
type ZoomSegment,
} from "~/utils/tauri";
+import IconLucideBoxSelect from "~icons/lucide/box-select";
+import IconLucideGauge from "~icons/lucide/gauge";
+import IconLucideGrid from "~icons/lucide/grid";
import IconLucideMonitor from "~icons/lucide/monitor";
+import IconLucideMoon from "~icons/lucide/moon";
+import IconLucideMove from "~icons/lucide/move";
import IconLucideRabbit from "~icons/lucide/rabbit";
+import IconLucideScan from "~icons/lucide/scan";
import IconLucideSparkles from "~icons/lucide/sparkles";
import IconLucideTimer from "~icons/lucide/timer";
import IconLucideWind from "~icons/lucide/wind";
import { CaptionsTab } from "./CaptionsTab";
import { type CornerRoundingType, useEditorContext } from "./context";
+import { evaluateMask, type MaskKind, type MaskSegment } from "./masks";
import {
DEFAULT_GRADIENT_FROM,
DEFAULT_GRADIENT_TO,
@@ -783,6 +790,73 @@ export function ConfigSidebar() {
<Show when={editorState.timeline.selection}>
{(selection) => (
<Suspense>
+ <Show
+ when={(() => {
+ const maskSelection = selection();
+ if (maskSelection.type !== "mask") return;
+
+ const segments = maskSelection.indices
+ .map((index) => ({
+ index,
+ segment: project.timeline?.maskSegments?.[index],
+ }))
+ .filter(
+ (item): item is { index: number; segment: MaskSegment } =>
+ item.segment !== undefined,
+ );
+
+ if (segments.length === 0) {
+ setEditorState("timeline", "selection", null);
+ return;
+ }
+ return { selection: maskSelection, segments };
+ })()}
+ >
+ {(value) => (
+ <div class="space-y-4">
+ <div class="flex flex-row justify-between items-center">
+ <div class="flex gap-2 items-center">
+ <EditorButton
+ onClick={() =>
+ setEditorState("timeline", "selection", null)
+ }
+ leftIcon={<IconLucideCheck />}
+ >
+ Done
+ </EditorButton>
+ <span class="text-sm text-gray-10">
+ {value().segments.length} mask{" "}
+ {value().segments.length === 1
+ ? "segment"
+ : "segments"}{" "}
+ selected
+ </span>
+ </div>
+ <EditorButton
+ variant="danger"
+ onClick={() =>
+ projectActions.deleteMaskSegments(
+ value().segments.map((s) => s.index),
+ )
+ }
+ leftIcon={<IconCapTrash />}
+ >
+ Delete
+ </EditorButton>
+ </div>
+ <For each={value().segments}>
+ {(item) => (
+ <div class="p-4 rounded-lg border border-gray-200">
+ <MaskSegmentConfig
+ segment={item.segment}
+ segmentIndex={item.index}
+ />
+ </div>
+ )}
+ </For>
+ </div>
+ )}
+ </Show>
<Show
when={(() => {
const zoomSelection = selection();
@@ -2306,6 +2380,164 @@ function CornerStyleSelect(props: {
);
}
+function MaskSegmentConfig(props: {
+ segmentIndex: number;
+ segment: MaskSegment;
+}) {
+ const { setProject, editorState } = useEditorContext();
+
+ const updateSegment = (fn: (segment: MaskSegment) => void) => {
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((segments) => {
+ const target = segments?.[props.segmentIndex];
+ if (!target) return;
+ target.keyframes ??= { position: [], size: [], intensity: [] };
+ fn(target);
+ }),
+ );
+ };
+
+ createEffect(() => {
+ const keyframes = props.segment.keyframes;
+ if (
+ !keyframes ||
+ (keyframes.position.length === 0 &&
+ keyframes.size.length === 0 &&
+ keyframes.intensity.length === 0)
+ )
+ return;
+ updateSegment((segment) => {
+ segment.keyframes = { position: [], size: [], intensity: [] };
+ });
+ });
+
+ const currentAbsoluteTime = () =>
+ editorState.previewTime ?? editorState.playbackTime ?? props.segment.start;
+ const maskState = () => evaluateMask(props.segment, currentAbsoluteTime());
+
+ const clearKeyframes = (segment: MaskSegment) => {
+ segment.keyframes.position = [];
+ segment.keyframes.size = [];
+ segment.keyframes.intensity = [];
+ };
+
+ const setPosition = (value: { x: number; y: number }) =>
+ updateSegment((segment) => {
+ segment.center = value;
+ clearKeyframes(segment);
+ });
+
+ const setSize = (value: { x: number; y: number }) =>
+ updateSegment((segment) => {
+ segment.size = value;
+ clearKeyframes(segment);
+ });
+
+ const setIntensity = (value: number) =>
+ updateSegment((segment) => {
+ segment.opacity = value;
+ clearKeyframes(segment);
+ });
+
+ return (
+ <div class="space-y-4">
+ <Field
+ name={`Mask ${props.segmentIndex + 1}`}
+ icon={<IconLucideBoxSelect class="size-4" />}
+ >
+ <div class="flex items-center justify-between gap-4">
+ <RadioGroup
+ class="grid grid-cols-2 gap-2"
+ value={props.segment.maskType}
+ onChange={(value) =>
+ updateSegment((segment) => {
+ segment.maskType = value as MaskKind;
+ if (segment.maskType === "highlight") {
+ segment.feather = 0;
+ segment.opacity = 1;
+ } else {
+ segment.feather = 0.1;
+ }
+ })
+ }
+ >
+ {[
+ { value: "sensitive", label: "Sensitive" },
+ { value: "highlight", label: "Highlight" },
+ ].map((option) => (
+ <RadioGroup.Item
+ value={option.value}
+ class="rounded-lg border border-gray-3 transition-colors ui-checked:border-blue-8 ui-checked:bg-blue-3/40"
+ >
+ <RadioGroup.ItemInput class="sr-only" />
+ <RadioGroup.ItemLabel class="flex cursor-pointer items-center gap-2 p-2 text-sm text-gray-12">
+ <RadioGroup.ItemControl class="size-4 rounded-full border border-gray-7 ui-checked:border-blue-9 ui-checked:bg-blue-9" />
+ {option.label}
+ </RadioGroup.ItemLabel>
+ </RadioGroup.Item>
+ ))}
+ </RadioGroup>
+ <div class="flex items-center gap-2">
+ <span class="text-xs text-gray-11">Enabled</span>
+ <Toggle
+ checked={props.segment.enabled}
+ onChange={(value) =>
+ updateSegment((segment) => {
+ segment.enabled = value;
+ })
+ }
+ />
+ </div>
+ </div>
+ </Field>
+ <Show when={props.segment.maskType === "sensitive"}>
+ <Field name="Intensity" icon={<IconLucideGauge class="size-4" />}>
+ <Slider
+ value={[props.segment.opacity]}
+ onChange={([v]) => setIntensity(v)}
+ minValue={0}
+ maxValue={1}
+ step={0.01}
+ formatTooltip="%"
+ />
+ </Field>
+ </Show>
+ <Show when={props.segment.maskType === "sensitive"}>
+ <Field name="Pixelation" icon={<IconLucideGrid class="size-4" />}>
+ <Slider
+ value={[props.segment.pixelation]}
+ onChange={([v]) =>
+ updateSegment((segment) => {
+ segment.pixelation = v;
+ })
+ }
+ minValue={1}
+ maxValue={80}
+ step={1}
+ />
+ </Field>
+ </Show>
+ <Show when={props.segment.maskType === "highlight"}>
+ <Field name="Outside Darkness" icon={<IconLucideMoon class="size-4" />}>
+ <Slider
+ value={[props.segment.darkness]}
+ onChange={([v]) =>
+ updateSegment((segment) => {
+ segment.darkness = v;
+ })
+ }
+ minValue={0}
+ maxValue={1}
+ step={0.01}
+ />
+ </Field>
+ </Show>
+ </div>
+ );
+}
+
function ZoomSegmentPreview(props: {
segmentIndex: number;
segment: ZoomSegment;
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 87a6a89a7..b489c33ed 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -1,5 +1,6 @@
import { Button } from "@cap/ui-solid";
import { NumberField } from "@kobalte/core/number-field";
+import { createElementBounds } from "@solid-primitives/bounds";
import { trackDeep } from "@solid-primitives/deep";
import { debounce, throttle } from "@solid-primitives/scheduled";
import { makePersisted } from "@solid-primitives/storage";
@@ -44,6 +45,12 @@ import { Player } from "./Player";
import { Timeline } from "./Timeline";
import { Dialog, DialogContent, EditorButton, Input, Subfield } from "./ui";
+const DEFAULT_TIMELINE_HEIGHT = 260;
+const MIN_PLAYER_CONTENT_HEIGHT = 320;
+const MIN_TIMELINE_HEIGHT = 240;
+const RESIZE_HANDLE_HEIGHT = 16;
+const MIN_PLAYER_HEIGHT = MIN_PLAYER_CONTENT_HEIGHT + RESIZE_HANDLE_HEIGHT;
+
export function Editor() {
return (
<EditorInstanceContextProvider>
@@ -84,6 +91,58 @@ function Inner() {
const { project, editorState, setEditorState, previewResolutionBase } =
useEditorContext();
+ const [layoutRef, setLayoutRef] = createSignal<HTMLDivElement>();
+ const layoutBounds = createElementBounds(layoutRef);
+ const [storedTimelineHeight, setStoredTimelineHeight] = makePersisted(
+ createSignal(DEFAULT_TIMELINE_HEIGHT),
+ { name: "editorTimelineHeight" },
+ );
+ const [isResizingTimeline, setIsResizingTimeline] = createSignal(false);
+
+ const clampTimelineHeight = (value: number) => {
+ const available = layoutBounds.height ?? 0;
+ const maxHeight =
+ available > 0
+ ? Math.max(MIN_TIMELINE_HEIGHT, available - MIN_PLAYER_HEIGHT)
+ : Number.POSITIVE_INFINITY;
+ const upperBound = Number.isFinite(maxHeight)
+ ? maxHeight
+ : Math.max(value, MIN_TIMELINE_HEIGHT);
+ return Math.min(Math.max(value, MIN_TIMELINE_HEIGHT), upperBound);
+ };
+
+ const timelineHeight = createMemo(() =>
+ Math.round(clampTimelineHeight(storedTimelineHeight())),
+ );
+
+ const handleTimelineResizeStart = (event: MouseEvent) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ const startY = event.clientY;
+ const startHeight = timelineHeight();
+ setIsResizingTimeline(true);
+
+ const handleMove = (moveEvent: MouseEvent) => {
+ const delta = moveEvent.clientY - startY;
+ setStoredTimelineHeight(clampTimelineHeight(startHeight - delta));
+ };
+
+ const handleUp = () => {
+ setIsResizingTimeline(false);
+ window.removeEventListener("mousemove", handleMove);
+ window.removeEventListener("mouseup", handleUp);
+ };
+
+ window.addEventListener("mousemove", handleMove);
+ window.addEventListener("mouseup", handleUp);
+ };
+
+ createEffect(() => {
+ const available = layoutBounds.height;
+ if (!available) return;
+ setStoredTimelineHeight((height) => clampTimelineHeight(height));
+ });
+
createTauriEventListener(events.editorStateChanged, (payload) => {
throttledRenderFrame.clear();
trailingRenderFrame.clear();
@@ -139,12 +198,45 @@ function Inner() {
class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-4 w-full min-h-0 leading-5 animate-in fade-in"
data-tauri-drag-region
>
- <div class="flex overflow-hidden flex-col flex-1 min-h-0">
- <div class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2 pb-0.5">
+ <div
+ ref={setLayoutRef}
+ class="flex overflow-hidden flex-col flex-1 min-h-0"
+ >
+ <div
+ class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2 relative"
+ style={{
+ "min-height": `${MIN_PLAYER_HEIGHT}px`,
+ "padding-bottom": `${RESIZE_HANDLE_HEIGHT}px`,
+ }}
+ >
<Player />
<ConfigSidebar />
+ <div
+ role="separator"
+ aria-orientation="horizontal"
+ class="absolute inset-x-0 bottom-0"
+ style={{ height: `${RESIZE_HANDLE_HEIGHT}px` }}
+ >
+ <div
+ class="flex items-center h-full px-3 cursor-row-resize select-none group"
+ classList={{ "bg-gray-3": isResizingTimeline() }}
+ onMouseDown={handleTimelineResizeStart}
+ >
+ <div
+ class="h-1 w-full rounded-full bg-gray-5 transition-colors group-hover:bg-gray-7"
+ classList={{ "bg-gray-8": isResizingTimeline() }}
+ />
+ </div>
+ </div>
+ </div>
+ <div
+ class="flex-none min-h-0 px-2 pb-0.5 overflow-hidden"
+ style={{ height: `${timelineHeight()}px` }}
+ >
+ <div class="h-full">
+ <Timeline />
+ </div>
</div>
- <Timeline />
</div>
<Dialogs />
</div>
diff --git a/apps/desktop/src/routes/editor/MaskOverlay.tsx b/apps/desktop/src/routes/editor/MaskOverlay.tsx
new file mode 100644
index 000000000..c203c0228
--- /dev/null
+++ b/apps/desktop/src/routes/editor/MaskOverlay.tsx
@@ -0,0 +1,230 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { cx } from "cva";
+import { createMemo, createRoot, Show } from "solid-js";
+import { produce } from "solid-js/store";
+
+import { useEditorContext } from "./context";
+import { evaluateMask, type MaskSegment } from "./masks";
+
+type MaskOverlayProps = {
+ size: { width: number; height: number };
+};
+
+export function MaskOverlay(props: MaskOverlayProps) {
+ const { project, setProject, editorState, projectHistory } =
+ useEditorContext();
+
+ const selectedMask = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "mask") return;
+ const index = selection.indices[0];
+ const segment = project.timeline?.maskSegments?.[index];
+ if (!segment) return;
+ return { index, segment };
+ });
+
+ const currentAbsoluteTime = () =>
+ editorState.previewTime ?? editorState.playbackTime ?? 0;
+
+ const maskState = createMemo(() => {
+ const selected = selectedMask();
+ if (!selected) return;
+ return evaluateMask(selected.segment, currentAbsoluteTime());
+ });
+
+ const updateSegment = (fn: (segment: MaskSegment) => void) => {
+ const index = selectedMask()?.index;
+ if (index === undefined) return;
+ setProject(
+ "timeline",
+ "maskSegments",
+ index,
+ produce((segment) => {
+ segment.keyframes ??= { position: [], size: [], intensity: [] };
+ segment.keyframes.position = [];
+ segment.keyframes.size = [];
+ fn(segment);
+ }),
+ );
+ };
+
+ function createMouseDownDrag<T>(
+ setup: () => T,
+ update: (
+ e: MouseEvent,
+ value: T,
+ initialMouse: { x: number; y: number },
+ ) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ downEvent.preventDefault();
+ downEvent.stopPropagation();
+
+ const initial = setup();
+ const initialMouse = { x: downEvent.clientX, y: downEvent.clientY };
+ const resumeHistory = projectHistory.pause();
+
+ function handleUpdate(event: MouseEvent) {
+ update(event, initial, initialMouse);
+ }
+
+ function finish() {
+ resumeHistory();
+ dispose();
+ }
+
+ const dispose = createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: handleUpdate,
+ mouseup: () => {
+ finish();
+ },
+ });
+ return dispose;
+ });
+ };
+ }
+
+ return (
+ <Show when={selectedMask() && maskState()}>
+ {() => {
+ const state = () => maskState()!;
+ const rect = () => {
+ const width = state().size.x * props.size.width;
+ const height = state().size.y * props.size.height;
+ const left = state().position.x * props.size.width - width / 2;
+ const top = state().position.y * props.size.height - height / 2;
+ return { width, height, left, top };
+ };
+
+ const onMove = createMouseDownDrag(
+ () => ({
+ startPos: { ...state().position },
+ }),
+ (e, { startPos }, initialMouse) => {
+ const dx = (e.clientX - initialMouse.x) / props.size.width;
+ const dy = (e.clientY - initialMouse.y) / props.size.height;
+
+ updateSegment((s) => {
+ s.center.x = Math.max(0, Math.min(1, startPos.x + dx));
+ s.center.y = Math.max(0, Math.min(1, startPos.y + dy));
+ });
+ },
+ );
+
+ const createResizeHandler = (dirX: -1 | 0 | 1, dirY: -1 | 0 | 1) => {
+ return createMouseDownDrag(
+ () => ({
+ startPos: { ...state().position },
+ startSize: { ...state().size },
+ }),
+ (e, { startPos, startSize }, initialMouse) => {
+ const dx = (e.clientX - initialMouse.x) / props.size.width;
+ const dy = (e.clientY - initialMouse.y) / props.size.height;
+
+ updateSegment((s) => {
+ if (dirX !== 0) {
+ const newWidth = Math.max(
+ 0.01,
+ startSize.x + dx * dirX, // if dirX is -1 (left), dx needs to be inverted for width? No. If I move mouse left (dx negative), width should increase. So dx * dirX -> (-ve * -1) = +ve. Correct.
+ );
+ // If we clamp width, we need to adjust center calc?
+ // Simple version:
+ s.size.x = newWidth;
+ s.center.x =
+ startPos.x + (dx * dirX) / 2 + dx * (dirX === -1 ? 0 : 0);
+ // Wait, my logic before:
+ // Right (dirX=1): Width = W + dx. Center = C + dx/2.
+ // Left (dirX=-1): Width = W - dx. Center = C + dx/2.
+ // So Center is always C + dx/2 regardless of direction?
+ // Let's re-verify.
+ // Right Handle: move right (+dx). W grows (+dx). Center moves right (+dx/2). Correct.
+ // Left Handle: move left (-dx). W grows (-dx i.e. +ve). Center moves left (-dx/2). Correct.
+ // So yes, Center += dx/2. Width += dx * dirX.
+
+ s.center.x = startPos.x + dx / 2;
+ }
+
+ if (dirY !== 0) {
+ const newHeight = Math.max(0.01, startSize.y + dy * dirY);
+ s.size.y = newHeight;
+ s.center.y = startPos.y + dy / 2;
+ }
+ });
+ },
+ );
+ };
+
+ return (
+ <div class="absolute inset-0 pointer-events-none">
+ <div
+ class="absolute pointer-events-auto group"
+ style={{
+ left: `${rect().left}px`,
+ top: `${rect().top}px`,
+ width: `${rect().width}px`,
+ height: `${rect().height}px`,
+ }}
+ onMouseDown={onMove}
+ >
+ {/* Border/Highlight */}
+ <div class="absolute inset-0 rounded-md border-2 border-blue-9 bg-blue-9/10 cursor-move" />
+
+ {/* Handles */}
+ {/* Corners */}
+ <ResizeHandle
+ class="top-0 left-0 -translate-x-1/2 -translate-y-1/2 cursor-nw-resize"
+ onMouseDown={createResizeHandler(-1, -1)}
+ />
+ <ResizeHandle
+ class="top-0 right-0 translate-x-1/2 -translate-y-1/2 cursor-ne-resize"
+ onMouseDown={createResizeHandler(1, -1)}
+ />
+ <ResizeHandle
+ class="bottom-0 left-0 -translate-x-1/2 translate-y-1/2 cursor-sw-resize"
+ onMouseDown={createResizeHandler(-1, 1)}
+ />
+ <ResizeHandle
+ class="bottom-0 right-0 translate-x-1/2 translate-y-1/2 cursor-se-resize"
+ onMouseDown={createResizeHandler(1, 1)}
+ />
+
+ {/* Sides */}
+ <ResizeHandle
+ class="top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 cursor-n-resize"
+ onMouseDown={createResizeHandler(0, -1)}
+ />
+ <ResizeHandle
+ class="bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2 cursor-s-resize"
+ onMouseDown={createResizeHandler(0, 1)}
+ />
+ <ResizeHandle
+ class="left-0 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-w-resize"
+ onMouseDown={createResizeHandler(-1, 0)}
+ />
+ <ResizeHandle
+ class="right-0 top-1/2 translate-x-1/2 -translate-y-1/2 cursor-e-resize"
+ onMouseDown={createResizeHandler(1, 0)}
+ />
+ </div>
+ </div>
+ );
+ }}
+ </Show>
+ );
+}
+
+function ResizeHandle(props: {
+ class?: string;
+ onMouseDown: (e: MouseEvent) => void;
+}) {
+ return (
+ <div
+ class={cx(
+ "absolute w-3 h-3 bg-blue-9 border border-white rounded-full shadow-sm transition-transform hover:scale-125",
+ props.class,
+ )}
+ onMouseDown={props.onMouseDown}
+ />
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index ac38bdc06..b8f6d95f3 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -14,6 +14,7 @@ import {
serializeProjectConfiguration,
useEditorContext,
} from "./context";
+import { MaskOverlay } from "./MaskOverlay";
import {
EditorButton,
MenuItem,
@@ -518,18 +519,27 @@ function PreviewCanvas() {
return (
<div class="flex overflow-hidden absolute inset-0 justify-center items-center h-full">
- <canvas
+ <div
+ class="relative"
style={{
width: `${size().width}px`,
height: `${size().height}px`,
- ...gridStyle,
}}
- class="rounded"
- ref={canvasRef}
- id="canvas"
- width={frameWidth()}
- height={frameHeight()}
- />
+ >
+ <canvas
+ style={{
+ width: `${size().width}px`,
+ height: `${size().height}px`,
+ ...gridStyle,
+ }}
+ class="rounded"
+ ref={canvasRef}
+ id="canvas"
+ width={frameWidth()}
+ height={frameHeight()}
+ />
+ <MaskOverlay size={size()} />
+ </div>
</div>
);
}}
diff --git a/apps/desktop/src/routes/editor/Timeline/MaskTrack.tsx b/apps/desktop/src/routes/editor/Timeline/MaskTrack.tsx
new file mode 100644
index 000000000..303b43b30
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline/MaskTrack.tsx
@@ -0,0 +1,375 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { cx } from "cva";
+import { createMemo, createRoot, For } from "solid-js";
+import { produce } from "solid-js/store";
+
+import { useEditorContext } from "../context";
+import { defaultMaskSegment } from "../masks";
+import { useTimelineContext } from "./context";
+import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track";
+
+export type MaskSegmentDragState =
+ | { type: "idle" }
+ | { type: "movePending" }
+ | { type: "moving" };
+
+const MIN_SEGMENT_SECS = 1;
+const MIN_SEGMENT_PIXELS = 80;
+
+export function MaskTrack(props: {
+ onDragStateChanged: (v: MaskSegmentDragState) => void;
+ handleUpdatePlayhead: (e: MouseEvent) => void;
+}) {
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ totalDuration,
+ projectHistory,
+ projectActions,
+ } = useEditorContext();
+ const { secsPerPixel, timelineBounds } = useTimelineContext();
+
+ const minDuration = () =>
+ Math.max(MIN_SEGMENT_SECS, secsPerPixel() * MIN_SEGMENT_PIXELS);
+
+ const maskSegments = () => project.timeline?.maskSegments ?? [];
+
+ const neighborBounds = (index: number) => {
+ const segments = maskSegments();
+ return {
+ prevEnd: segments[index - 1]?.end ?? 0,
+ nextStart: segments[index + 1]?.start ?? totalDuration(),
+ };
+ };
+
+ const findPlacement = (time: number, length: number) => {
+ const gaps: Array<{ start: number; end: number }> = [];
+ const sorted = maskSegments()
+ .slice()
+ .sort((a, b) => a.start - b.start);
+
+ let cursor = 0;
+ for (const segment of sorted) {
+ if (segment.start - cursor >= length) {
+ gaps.push({ start: cursor, end: segment.start });
+ }
+ cursor = Math.max(cursor, segment.end);
+ }
+
+ if (totalDuration() - cursor >= length) {
+ gaps.push({ start: cursor, end: totalDuration() });
+ }
+
+ if (gaps.length === 0) return null;
+
+ const maxStart = Math.max(totalDuration() - length, 0);
+ const desiredStart = Math.min(Math.max(time - length / 2, 0), maxStart);
+
+ const containingGap =
+ gaps.find(
+ (gap) => desiredStart >= gap.start && desiredStart + length <= gap.end,
+ ) ??
+ gaps.find((gap) => gap.start >= desiredStart) ??
+ gaps[gaps.length - 1];
+
+ const start = Math.min(
+ Math.max(desiredStart, containingGap.start),
+ containingGap.end - length,
+ );
+
+ return { start, end: start + length };
+ };
+
+ const addSegmentAt = (time: number) => {
+ const length = Math.min(minDuration(), totalDuration());
+ if (length <= 0) return;
+
+ const placement = findPlacement(time, length);
+ if (!placement) return;
+
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((segments) => {
+ segments ??= [];
+ segments.push(defaultMaskSegment(placement.start, placement.end));
+ segments.sort((a, b) => a.start - b.start);
+ }),
+ );
+ };
+
+ const handleBackgroundMouseDown = (e: MouseEvent) => {
+ if (e.button !== 0) return;
+ if ((e.target as HTMLElement).closest("[data-mask-segment]")) return;
+ const timelineTime =
+ editorState.previewTime ??
+ editorState.playbackTime ??
+ secsPerPixel() * (e.clientX - (timelineBounds.left ?? 0));
+ addSegmentAt(timelineTime);
+ };
+
+ function createMouseDownDrag<T>(
+ segmentIndex: () => number,
+ setup: () => T,
+ update: (e: MouseEvent, value: T, initialMouseX: number) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ if (editorState.timeline.interactMode !== "seek") return;
+ downEvent.stopPropagation();
+ const initial = setup();
+ let moved = false;
+ let initialMouseX: number | null = null;
+
+ const resumeHistory = projectHistory.pause();
+ props.onDragStateChanged({ type: "movePending" });
+
+ function finish(e: MouseEvent) {
+ resumeHistory();
+ if (!moved) {
+ e.stopPropagation();
+ const currentSelection = editorState.timeline.selection;
+ const index = segmentIndex();
+ const isMultiSelect = e.ctrlKey || e.metaKey;
+ const isRangeSelect = e.shiftKey;
+
+ if (isRangeSelect && currentSelection?.type === "mask") {
+ const existingIndices = currentSelection.indices;
+ const lastIndex = existingIndices[existingIndices.length - 1];
+ const start = Math.min(lastIndex, index);
+ const end = Math.max(lastIndex, index);
+ const rangeIndices: number[] = [];
+ for (let idx = start; idx <= end; idx++) rangeIndices.push(idx);
+ setEditorState("timeline", "selection", {
+ type: "mask",
+ indices: rangeIndices,
+ });
+ } else if (isMultiSelect) {
+ if (currentSelection?.type === "mask") {
+ const base = currentSelection.indices;
+ const exists = base.includes(index);
+ const next = exists
+ ? base.filter((i) => i !== index)
+ : [...base, index];
+ setEditorState(
+ "timeline",
+ "selection",
+ next.length > 0
+ ? {
+ type: "mask",
+ indices: next,
+ }
+ : null,
+ );
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "mask",
+ indices: [index],
+ });
+ }
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "mask",
+ indices: [index],
+ });
+ }
+ props.handleUpdatePlayhead(e);
+ }
+ props.onDragStateChanged({ type: "idle" });
+ }
+
+ function handleUpdate(event: MouseEvent) {
+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
+ if (!moved) {
+ moved = true;
+ initialMouseX = event.clientX;
+ props.onDragStateChanged({ type: "moving" });
+ }
+ }
+
+ if (initialMouseX === null) return;
+ update(event, initial, initialMouseX);
+ }
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: (e) => handleUpdate(e),
+ mouseup: (e) => {
+ handleUpdate(e);
+ finish(e);
+ dispose();
+ },
+ });
+ });
+ };
+ }
+
+ return (
+ <TrackRoot
+ onMouseEnter={() => setEditorState("timeline", "hoveredTrack", "mask")}
+ onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
+ onMouseDown={handleBackgroundMouseDown}
+ >
+ <For
+ each={maskSegments()}
+ fallback={
+ <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">
+ <div>Click to add a mask</div>
+ <div class="text-[10px] text-[--text-tertiary]/40 mt-0.5">
+ (Combine sensitive blur or highlight masks)
+ </div>
+ </div>
+ }
+ >
+ {(segment, i) => {
+ const isSelected = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "mask") return false;
+ return selection.indices.includes(i());
+ });
+
+ const contentLabel = () =>
+ segment.maskType === "sensitive" ? "Sensitive" : "Highlight";
+
+ const segmentWidth = () => segment.end - segment.start;
+
+ return (
+ <SegmentRoot
+ data-mask-segment
+ data-index={i()}
+ class={cx(
+ "border duration-200 hover:border-gray-12 transition-colors group",
+ "bg-gradient-to-r from-[#1f2022] via-[#2c2d30] to-[#1f2022]",
+ isSelected() ? "border-gray-12" : "border-transparent",
+ )}
+ innerClass="ring-red-5"
+ segment={segment}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ if (editorState.timeline.interactMode === "split") {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+ const splitTime = fraction * segmentWidth();
+ projectActions.splitMaskSegment(i(), splitTime);
+ }
+ }}
+ >
+ <SegmentHandle
+ position="start"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const start = segment.start;
+ const minValue = bounds.prevEnd;
+ const maxValue = Math.max(
+ minValue,
+ Math.min(
+ segment.end - minDuration(),
+ bounds.nextStart - minDuration(),
+ ),
+ );
+ return { start, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.start + delta),
+ );
+ setProject("timeline", "maskSegments", i(), "start", next);
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((items) => {
+ items.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ />
+ <SegmentContent
+ class="flex justify-center items-center cursor-grab px-3"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const original = { ...segment };
+ const bounds = neighborBounds(i());
+ const minDelta = bounds.prevEnd - original.start;
+ const maxDelta = bounds.nextStart - original.end;
+ return {
+ original,
+ minDelta,
+ maxDelta,
+ };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const lowerBound = Math.min(value.minDelta, value.maxDelta);
+ const upperBound = Math.max(value.minDelta, value.maxDelta);
+ const clampedDelta = Math.min(
+ upperBound,
+ Math.max(lowerBound, delta),
+ );
+ setProject("timeline", "maskSegments", i(), {
+ ...value.original,
+ start: value.original.start + clampedDelta,
+ end: value.original.end + clampedDelta,
+ });
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((items) => {
+ items.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ >
+ {(() => {
+ return (
+ <div class="flex flex-col gap-0.5 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
+ <span class="opacity-70">Mask</span>
+ <div class="flex gap-1 items-center text-md">
+ <span>{contentLabel()}</span>
+ </div>
+ </div>
+ );
+ })()}
+ </SegmentContent>
+ <SegmentHandle
+ position="end"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const end = segment.end;
+ const minValue = segment.start + minDuration();
+ const maxValue = Math.max(minValue, bounds.nextStart);
+ return { end, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.end + delta),
+ );
+ setProject("timeline", "maskSegments", i(), "end", next);
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((items) => {
+ items.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ />
+ </SegmentRoot>
+ );
+ }}
+ </For>
+ </TrackRoot>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Timeline/Track.tsx b/apps/desktop/src/routes/editor/Timeline/Track.tsx
index c5581ecc9..85c954f32 100644
--- a/apps/desktop/src/routes/editor/Timeline/Track.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/Track.tsx
@@ -11,13 +11,19 @@ import {
export function TrackRoot(props: ComponentProps<"div">) {
const [ref, setRef] = createSignal<HTMLDivElement>();
+ const height = "var(--track-height, 3.25rem)";
+ const style =
+ typeof props.style === "string"
+ ? `${props.style};height:${height}`
+ : { height, ...(props.style ?? {}) };
return (
<TrackContextProvider ref={ref}>
<div
{...props}
ref={mergeRefs(setRef, props.ref)}
- class={cx("flex flex-row relative h-[3.25rem]", props.class)}
+ class={cx("flex flex-row relative", props.class)}
+ style={style}
>
{props.children}
</div>
diff --git a/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx b/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx
index 798f72178..e9bcd6f52 100644
--- a/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx
@@ -10,6 +10,7 @@ type TrackManagerOption = {
icon: JSX.Element;
active: boolean;
available: boolean;
+ locked: boolean;
};
export function TrackManager(props: {
@@ -22,7 +23,7 @@ export function TrackManager(props: {
try {
const items = await Promise.all(
props.options.map((option) => {
- if (option.type === "scene") {
+ if (!option.locked) {
return CheckMenuItem.new({
text: option.label,
checked: option.active,
@@ -33,7 +34,7 @@ export function TrackManager(props: {
return CheckMenuItem.new({
text: option.label,
- checked: true,
+ checked: option.active,
enabled: false,
});
}),
diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx
index b53bc8df5..b209729d4 100644
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@ -21,6 +21,7 @@ import { FPS, type TimelineTrackType, useEditorContext } from "../context";
import { formatTime } from "../utils";
import { ClipTrack } from "./ClipTrack";
import { TimelineContextProvider, useTimelineContext } from "./context";
+import { type MaskSegmentDragState, MaskTrack } from "./MaskTrack";
import { type SceneSegmentDragState, SceneTrack } from "./SceneTrack";
import { TrackIcon, TrackManager } from "./TrackManager";
import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack";
@@ -28,10 +29,10 @@ import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack";
const TIMELINE_PADDING = 16;
const TRACK_GUTTER = 64;
const TIMELINE_HEADER_HEIGHT = 32;
-const TRACK_MANAGER_BUTTON_SIZE = 56;
const trackIcons: Record<TimelineTrackType, JSX.Element> = {
clip: <IconLucideClapperboard class="size-4" />,
+ mask: <IconLucideBoxSelect class="size-4" />,
zoom: <IconLucideSearch class="size-4" />,
scene: <IconLucideVideo class="size-4" />,
};
@@ -50,6 +51,12 @@ const trackDefinitions: TrackDefinition[] = [
icon: trackIcons.clip,
locked: true,
},
+ {
+ type: "mask",
+ label: "Mask",
+ icon: trackIcons.mask,
+ locked: false,
+ },
{
type: "zoom",
label: "Zoom",
@@ -91,14 +98,31 @@ export function Timeline() {
const trackOptions = () =>
trackDefinitions.map((definition) => ({
...definition,
- active: definition.type === "scene" ? trackState().scene : true,
+ active:
+ definition.type === "scene"
+ ? trackState().scene
+ : definition.type === "mask"
+ ? trackState().mask
+ : true,
available: definition.type === "scene" ? sceneAvailable() : true,
}));
const sceneTrackVisible = () => trackState().scene && sceneAvailable();
+ const visibleTrackCount = () =>
+ 2 + (trackState().mask ? 1 : 0) + (sceneTrackVisible() ? 1 : 0);
+ const trackHeight = () => (visibleTrackCount() > 2 ? "3rem" : "3.25rem");
function handleToggleTrack(type: TimelineTrackType, next: boolean) {
- if (type !== "scene") return;
- setEditorState("timeline", "tracks", "scene", next);
+ if (type === "scene") {
+ setEditorState("timeline", "tracks", "scene", next);
+ return;
+ }
+
+ if (type === "mask") {
+ setEditorState("timeline", "tracks", "mask", next);
+ if (!next && editorState.timeline.selection?.type === "mask") {
+ setEditorState("timeline", "selection", null);
+ }
+ }
}
onMount(() => {
@@ -112,6 +136,9 @@ export function Timeline() {
end: duration(),
},
],
+ zoomSegments: [],
+ sceneSegments: [],
+ maskSegments: [],
});
resume();
}
@@ -148,19 +175,46 @@ export function Timeline() {
},
],
zoomSegments: [],
+ sceneSegments: [],
+ maskSegments: [],
+ };
+ project.timeline.sceneSegments ??= [];
+ project.timeline.maskSegments ??= [];
+ project.timeline.zoomSegments ??= [];
+ }),
+ );
+ }
+
+ if (!project.timeline?.maskSegments) {
+ setProject(
+ produce((project) => {
+ project.timeline ??= {
+ segments: [
+ {
+ start: 0,
+ end: duration(),
+ timescale: 1,
+ },
+ ],
+ zoomSegments: [],
+ sceneSegments: [],
+ maskSegments: [],
};
+ project.timeline.maskSegments ??= [];
}),
);
}
let zoomSegmentDragState = { type: "idle" } as ZoomSegmentDragState;
let sceneSegmentDragState = { type: "idle" } as SceneSegmentDragState;
+ let maskSegmentDragState = { type: "idle" } as MaskSegmentDragState;
async function handleUpdatePlayhead(e: MouseEvent) {
const { left } = timelineBounds;
if (
zoomSegmentDragState.type !== "moving" &&
- sceneSegmentDragState.type !== "moving"
+ sceneSegmentDragState.type !== "moving" &&
+ maskSegmentDragState.type !== "moving"
) {
// Guard against missing bounds and clamp computed time to [0, totalDuration()]
if (left == null) return;
@@ -203,6 +257,8 @@ export function Timeline() {
if (selection.type === "zoom") {
projectActions.deleteZoomSegments(selection.indices);
+ } else if (selection.type === "mask") {
+ projectActions.deleteMaskSegments(selection.indices);
} else if (selection.type === "clip") {
// Delete all selected clips in reverse order
[...selection.indices]
@@ -283,12 +339,13 @@ export function Timeline() {
timelineBounds={timelineBounds}
>
<div
- class="pt-[2rem] relative overflow-hidden flex flex-col gap-2"
+ class="pt-[2rem] relative overflow-hidden flex flex-col gap-2 h-full"
style={{
"padding-left": `${TIMELINE_PADDING}px`,
"padding-right": `${TIMELINE_PADDING}px`,
"mask-image": maskImage(),
"-webkit-mask-image": maskImage(),
+ "--track-height": trackHeight(),
}}
onMouseDown={(e) => {
createRoot((dispose) => {
@@ -371,71 +428,94 @@ export function Timeline() {
</Tooltip>
</div>
</div>
- <Show when={!editorState.playing && editorState.previewTime}>
- {(time) => (
- <div
- class={cx(
- "flex absolute bottom-0 z-10 justify-center items-center w-px pointer-events-none bg-gradient-to-b to-[120%]",
- split() ? "from-red-300" : "from-gray-400",
- )}
- style={{
- left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
- transform: `translateX(${
- (time() - transform().position) / secsPerPixel() - 0.5
- }px)`,
- top: `${TIMELINE_HEADER_HEIGHT}px`,
- }}
- >
+ <div class="relative flex-1 min-h-0">
+ <Show when={!editorState.playing && editorState.previewTime}>
+ {(time) => (
<div
class={cx(
- "absolute -top-2 rounded-full size-3",
- split() ? "bg-red-300" : "bg-gray-10",
+ "flex absolute bottom-0 z-10 justify-center items-center w-px pointer-events-none bg-gradient-to-b to-[120%]",
+ split() ? "from-red-300" : "from-gray-400",
)}
- />
+ style={{
+ left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
+ transform: `translateX(${
+ (time() - transform().position) / secsPerPixel() - 0.5
+ }px)`,
+ top: "0px",
+ }}
+ >
+ <div
+ class={cx(
+ "absolute -top-2 rounded-full size-3",
+ split() ? "bg-red-300" : "bg-gray-10",
+ )}
+ />
+ </div>
+ )}
+ </Show>
+ <div
+ class={cx(
+ "absolute bottom-0 h-full rounded-full z-10 w-px pointer-events-none bg-gradient-to-b to-[120%] from-[rgb(226,64,64)]",
+ split() && "opacity-50",
+ )}
+ style={{
+ left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
+ transform: `translateX(${Math.min(
+ (editorState.playbackTime - transform().position) /
+ secsPerPixel(),
+ timelineBounds.width ?? 0,
+ )}px)`,
+ top: "0px",
+ }}
+ >
+ <div class="size-3 bg-[rgb(226,64,64)] rounded-full -mt-2 -ml-[calc(0.37rem-0.5px)]" />
+ </div>
+ <div
+ class="absolute inset-0 overflow-y-auto overflow-x-hidden pr-1"
+ onWheel={(e) => {
+ if (!e.ctrlKey && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
+ e.stopPropagation();
+ }
+ }}
+ >
+ <div class="flex flex-col gap-2 min-h-full">
+ <TrackRow icon={trackIcons.clip}>
+ <ClipTrack
+ ref={setTimelineRef}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ <Show when={trackState().mask}>
+ <TrackRow icon={trackIcons.mask}>
+ <MaskTrack
+ onDragStateChanged={(v) => {
+ maskSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ </Show>
+ <TrackRow icon={trackIcons.zoom}>
+ <ZoomTrack
+ onDragStateChanged={(v) => {
+ zoomSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ <Show when={sceneTrackVisible()}>
+ <TrackRow icon={trackIcons.scene}>
+ <SceneTrack
+ onDragStateChanged={(v) => {
+ sceneSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ </Show>
</div>
- )}
- </Show>
- <div
- class={cx(
- "absolute bottom-0 h-full rounded-full z-10 w-px pointer-events-none bg-gradient-to-b to-[120%] from-[rgb(226,64,64)]",
- split() && "opacity-50",
- )}
- style={{
- left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
- transform: `translateX(${Math.min(
- (editorState.playbackTime - transform().position) /
- secsPerPixel(),
- timelineBounds.width ?? 0,
- )}px)`,
- top: `${TIMELINE_HEADER_HEIGHT}px`,
- }}
- >
- <div class="size-3 bg-[rgb(226,64,64)] rounded-full -mt-2 -ml-[calc(0.37rem-0.5px)]" />
+ </div>
</div>
- <TrackRow icon={trackIcons.clip}>
- <ClipTrack
- ref={setTimelineRef}
- handleUpdatePlayhead={handleUpdatePlayhead}
- />
- </TrackRow>
- <TrackRow icon={trackIcons.zoom}>
- <ZoomTrack
- onDragStateChanged={(v) => {
- zoomSegmentDragState = v;
- }}
- handleUpdatePlayhead={handleUpdatePlayhead}
- />
- </TrackRow>
- <Show when={sceneTrackVisible()}>
- <TrackRow icon={trackIcons.scene}>
- <SceneTrack
- onDragStateChanged={(v) => {
- sceneSegmentDragState = v;
- }}
- handleUpdatePlayhead={handleUpdatePlayhead}
- />
- </TrackRow>
- </Show>
</div>
</TimelineContextProvider>
);
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 15c17e091..21a60f6e5 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -28,10 +28,15 @@ import {
type MultipleSegments,
type ProjectConfiguration,
type RecordingMeta,
+ type SceneSegment,
type SerializedEditorInstance,
type SingleSegment,
+ type TimelineConfiguration,
+ type TimelineSegment,
type XY,
+ type ZoomSegment,
} from "~/utils/tauri";
+import type { MaskSegment } from "./masks";
import { createProgressBar } from "./utils";
export type CurrentDialog =
@@ -67,7 +72,7 @@ export const getPreviewResolution = (quality: PreviewQuality): XY<number> => {
return { x: width, y: height };
};
-export type TimelineTrackType = "clip" | "zoom" | "scene";
+export type TimelineTrackType = "clip" | "zoom" | "scene" | "mask";
export const MAX_ZOOM_IN = 3;
const PROJECT_SAVE_DEBOUNCE_MS = 250;
@@ -85,12 +90,21 @@ export type CornerRoundingType = "rounded" | "squircle";
type WithCornerStyle<T> = T & { roundingType: CornerRoundingType };
+type EditorTimelineConfiguration = Omit<
+ TimelineConfiguration,
+ "sceneSegments"
+> & {
+ sceneSegments?: SceneSegment[];
+ maskSegments: MaskSegment[];
+};
+
export type EditorProjectConfiguration = Omit<
ProjectConfiguration,
- "background" | "camera"
+ "background" | "camera" | "timeline"
> & {
background: WithCornerStyle<ProjectConfiguration["background"]>;
camera: WithCornerStyle<ProjectConfiguration["camera"]>;
+ timeline?: EditorTimelineConfiguration | null;
};
function withCornerDefaults<
@@ -109,8 +123,22 @@ function withCornerDefaults<
export function normalizeProject(
config: ProjectConfiguration,
): EditorProjectConfiguration {
+ const timeline = config.timeline
+ ? {
+ ...config.timeline,
+ sceneSegments: config.timeline.sceneSegments ?? [],
+ maskSegments:
+ (
+ config.timeline as TimelineConfiguration & {
+ maskSegments?: MaskSegment[];
+ }
+ ).maskSegments ?? [],
+ }
+ : undefined;
+
return {
...config,
+ timeline,
background: withCornerDefaults(config.background),
camera: withCornerDefaults(config.camera),
};
@@ -124,8 +152,16 @@ export function serializeProjectConfiguration(
background;
const { roundingType: cameraRoundingType, ...cameraRest } = camera;
+ const timeline = project.timeline
+ ? {
+ ...project.timeline,
+ maskSegments: project.timeline.maskSegments ?? [],
+ }
+ : project.timeline;
+
return {
...rest,
+ timeline: timeline as unknown as ProjectConfiguration["timeline"],
background: {
...backgroundRest,
roundingType: backgroundRoundingType,
@@ -242,6 +278,45 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
setEditorState("timeline", "selection", null);
});
},
+ splitMaskSegment: (index: number, time: number) => {
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((segments) => {
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const duration = segment.end - segment.start;
+ const remaining = duration - time;
+ if (time < 1 || remaining < 1) return;
+
+ segments.splice(index + 1, 0, {
+ ...segment,
+ start: segment.start + time,
+ end: segment.end,
+ });
+ segments[index].end = segment.start + time;
+ }),
+ );
+ },
+ deleteMaskSegments: (segmentIndices: number[]) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((segments) => {
+ if (!segments) return;
+ const sorted = [...new Set(segmentIndices)]
+ .filter(
+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
+ )
+ .sort((a, b) => b - a);
+ for (const i of sorted) segments.splice(i, 1);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
splitSceneSegment: (index: number, time: number) => {
setProject(
"timeline",
@@ -309,6 +384,11 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
zoomSegment.end += diff(zoomSegment.end);
}
+ for (const maskSegment of timeline.maskSegments) {
+ maskSegment.start += diff(maskSegment.start);
+ maskSegment.end += diff(maskSegment.end);
+ }
+
segment.timescale = timescale;
}),
);
@@ -455,6 +535,9 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
};
}
+ const initialMaskTrackEnabled =
+ (project.timeline?.maskSegments?.length ?? 0) > 0;
+
const [editorState, setEditorState] = createStore({
previewTime: null as number | null,
playbackTime: 0,
@@ -465,7 +548,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
| null
| { type: "zoom"; indices: number[] }
| { type: "clip"; indices: number[] }
- | { type: "scene"; indices: number[] },
+ | { type: "scene"; indices: number[] }
+ | { type: "mask"; indices: number[] },
transform: {
// visible seconds
zoom: zoomOutLimit(),
@@ -506,6 +590,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
clip: true,
zoom: true,
scene: true,
+ mask: initialMaskTrackEnabled,
},
hoveredTrack: null as null | TimelineTrackType,
},
diff --git a/apps/desktop/src/routes/editor/masks.ts b/apps/desktop/src/routes/editor/masks.ts
new file mode 100644
index 000000000..8b7935151
--- /dev/null
+++ b/apps/desktop/src/routes/editor/masks.ts
@@ -0,0 +1,117 @@
+import type { XY } from "~/utils/tauri";
+
+export type MaskKind = "sensitive" | "highlight";
+
+export type MaskScalarKeyframe = {
+ time: number;
+ value: number;
+};
+
+export type MaskVectorKeyframe = {
+ time: number;
+ x: number;
+ y: number;
+};
+
+export type MaskKeyframes = {
+ position: MaskVectorKeyframe[];
+ size: MaskVectorKeyframe[];
+ intensity: MaskScalarKeyframe[];
+};
+
+export type MaskSegment = {
+ start: number;
+ end: number;
+ enabled: boolean;
+ maskType: MaskKind;
+ center: XY<number>;
+ size: XY<number>;
+ feather: number;
+ opacity: number;
+ pixelation: number;
+ darkness: number;
+ keyframes: MaskKeyframes;
+};
+
+export type MaskState = {
+ position: XY<number>;
+ size: XY<number>;
+ intensity: number;
+};
+
+export const defaultMaskSegment = (
+ start: number,
+ end: number,
+): MaskSegment => ({
+ start,
+ end,
+ enabled: true,
+ maskType: "sensitive",
+ center: { x: 0.5, y: 0.5 },
+ size: { x: 0.35, y: 0.35 },
+ feather: 0.1,
+ opacity: 1,
+ pixelation: 18,
+ darkness: 0.5,
+ keyframes: { position: [], size: [], intensity: [] },
+});
+
+export const evaluateMask = (
+ segment: MaskSegment,
+ _time?: number,
+): MaskState => {
+ const position = {
+ x: Math.min(Math.max(segment.center.x, 0), 1),
+ y: Math.min(Math.max(segment.center.y, 0), 1),
+ };
+ const size = {
+ x: Math.min(Math.max(segment.size.x, 0.01), 2),
+ y: Math.min(Math.max(segment.size.y, 0.01), 2),
+ };
+ const intensity = Math.min(Math.max(segment.opacity, 0), 1);
+
+ return { position, size, intensity };
+};
+
+const sortByTime = <T extends { time: number }>(items: T[]) =>
+ [...items].sort((a, b) => a.time - b.time);
+
+const timeMatch = (a: number, b: number) => Math.abs(a - b) < 1e-3;
+
+export const upsertVectorKeyframe = (
+ keyframes: MaskVectorKeyframe[],
+ time: number,
+ value: XY<number>,
+) => {
+ const existingIndex = keyframes.findIndex((k) => timeMatch(k.time, time));
+ if (existingIndex >= 0) {
+ const next = [...keyframes];
+ next[existingIndex] = {
+ ...next[existingIndex],
+ time,
+ x: value.x,
+ y: value.y,
+ };
+ return sortByTime(next);
+ }
+ return sortByTime([...keyframes, { time, x: value.x, y: value.y }]);
+};
+
+export const upsertScalarKeyframe = (
+ keyframes: MaskScalarKeyframe[],
+ time: number,
+ value: number,
+) => {
+ const existingIndex = keyframes.findIndex((k) => timeMatch(k.time, time));
+ if (existingIndex >= 0) {
+ const next = [...keyframes];
+ next[existingIndex] = { ...next[existingIndex], time, value };
+ return sortByTime(next);
+ }
+ return sortByTime([...keyframes, { time, value }]);
+};
+
+export const removeKeyframeAt = <T extends { time: number }>(
+ items: T[],
+ time: number,
+) => items.filter((k) => !timeMatch(k.time, time));
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index d47dea60b..8b076dc2a 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -441,7 +441,12 @@ export type LogicalBounds = { position: LogicalPosition; size: LogicalSize }
export type LogicalPosition = { x: number; y: number }
export type LogicalSize = { width: number; height: number }
export type MainWindowRecordingStartBehaviour = "close" | "minimise"
+export type MaskKeyframes = { position?: MaskVectorKeyframe[]; size?: MaskVectorKeyframe[]; intensity?: MaskScalarKeyframe[] }
+export type MaskKind = "sensitive" | "highlight"
+export type MaskScalarKeyframe = { time: number; value: number }
+export type MaskSegment = { start: number; end: number; enabled?: boolean; maskType: MaskKind; center: XY<number>; size: XY<number>; feather?: number; opacity?: number; pixelation?: number; darkness?: number; keyframes?: MaskKeyframes }
export type MaskType = "blur" | "pixelate"
+export type MaskVectorKeyframe = { time: number; x: number; y: number }
export type ModelIDType = string
export type Mp4ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }
export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; mic?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null }
@@ -498,7 +503,7 @@ export type StereoMode = "stereo" | "monoL" | "monoR"
export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type StudioRecordingStatus = { status: "InProgress" } | { status: "Failed"; error: string } | { status: "Complete" }
export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }
-export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[] }
+export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[] }
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }
export type UploadMeta = { state: "MultipartUpload"; video_id: string; file_path: string; pre_created_video: VideoUploadInfo; recording_dir: string } | { state: "SinglePartUpload"; video_id: string; recording_dir: string; file_path: string; screenshot_path: string } | { state: "Failed"; error: string } | { state: "Complete" }
export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null } } | "Reupload"
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 9920f689c..76ee3cfc2 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -548,6 +548,71 @@ pub enum ZoomMode {
Manual { x: f32, y: f32 },
}
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)]
+#[serde(rename_all = "camelCase")]
+pub enum MaskKind {
+ Sensitive,
+ Highlight,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct MaskScalarKeyframe {
+ pub time: f64,
+ pub value: f64,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct MaskVectorKeyframe {
+ pub time: f64,
+ pub x: f64,
+ pub y: f64,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct MaskKeyframes {
+ #[serde(default)]
+ pub position: Vec<MaskVectorKeyframe>,
+ #[serde(default)]
+ pub size: Vec<MaskVectorKeyframe>,
+ #[serde(default)]
+ pub intensity: Vec<MaskScalarKeyframe>,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct MaskSegment {
+ pub start: f64,
+ pub end: f64,
+ #[serde(default = "MaskSegment::default_enabled")]
+ pub enabled: bool,
+ pub mask_type: MaskKind,
+ pub center: XY<f64>,
+ pub size: XY<f64>,
+ #[serde(default)]
+ pub feather: f64,
+ #[serde(default = "MaskSegment::default_opacity")]
+ pub opacity: f64,
+ #[serde(default)]
+ pub pixelation: f64,
+ #[serde(default)]
+ pub darkness: f64,
+ #[serde(default)]
+ pub keyframes: MaskKeyframes,
+}
+
+impl MaskSegment {
+ fn default_enabled() -> bool {
+ true
+ }
+
+ fn default_opacity() -> f64 {
+ 1.0
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum SceneMode {
@@ -573,6 +638,8 @@ pub struct TimelineConfiguration {
pub zoom_segments: Vec<ZoomSegment>,
#[serde(default)]
pub scene_segments: Vec<SceneSegment>,
+ #[serde(default)]
+ pub mask_segments: Vec<MaskSegment>,
}
impl TimelineConfiguration {
diff --git a/crates/rendering/src/layers/mask.rs b/crates/rendering/src/layers/mask.rs
new file mode 100644
index 000000000..daf62fac4
--- /dev/null
+++ b/crates/rendering/src/layers/mask.rs
@@ -0,0 +1,235 @@
+use bytemuck::{Pod, Zeroable};
+use wgpu::util::DeviceExt;
+
+use crate::{PreparedMask, RenderSession};
+
+pub struct MaskLayer {
+ sampler: wgpu::Sampler,
+ uniforms_buffer: wgpu::Buffer,
+ pipeline: MaskPipeline,
+}
+
+impl MaskLayer {
+ pub fn new(device: &wgpu::Device) -> Self {
+ Self {
+ 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::Nearest,
+ min_filter: wgpu::FilterMode::Nearest,
+ mipmap_filter: wgpu::FilterMode::Nearest,
+ ..Default::default()
+ }),
+ uniforms_buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Mask Uniform Buffer"),
+ contents: bytemuck::cast_slice(&[MaskUniforms::default()]),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ }),
+ pipeline: MaskPipeline::new(device),
+ }
+ }
+
+ pub fn render(
+ &self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ session: &mut RenderSession,
+ encoder: &mut wgpu::CommandEncoder,
+ mask: &PreparedMask,
+ ) {
+ let uniforms = MaskUniforms::from_mask(mask);
+ queue.write_buffer(&self.uniforms_buffer, 0, bytemuck::cast_slice(&[uniforms]));
+
+ let bind_group = self.pipeline.bind_group(
+ device,
+ &self.uniforms_buffer,
+ session.current_texture_view(),
+ &self.sampler,
+ );
+
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("Mask Pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: session.other_texture_view(),
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+
+ pass.set_pipeline(&self.pipeline.render_pipeline);
+ pass.set_bind_group(0, &bind_group, &[]);
+ pass.draw(0..3, 0..1);
+
+ drop(pass);
+ session.swap_textures();
+ }
+}
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Pod, Zeroable, PartialEq)]
+struct MaskUniforms {
+ rect_center: [f32; 2],
+ rect_size: [f32; 2],
+ feather: f32,
+ opacity: f32,
+ pixel_size: f32,
+ darkness: f32,
+ mode: u32,
+ padding0: u32,
+ output_size: [f32; 2],
+ padding1: [f32; 2],
+}
+
+impl Default for MaskUniforms {
+ fn default() -> Self {
+ Self::zeroed()
+ }
+}
+
+impl MaskUniforms {
+ fn from_mask(mask: &PreparedMask) -> Self {
+ Self {
+ rect_center: [mask.center.x, mask.center.y],
+ rect_size: [mask.size.x, mask.size.y],
+ feather: mask.feather,
+ opacity: mask.opacity,
+ pixel_size: mask.pixel_size,
+ darkness: mask.darkness,
+ mode: mask.mode_value(),
+ padding0: 0,
+ output_size: [mask.output_size.x as f32, mask.output_size.y as f32],
+ padding1: [0.0; 2],
+ }
+ }
+}
+
+pub struct MaskPipeline {
+ bind_group_layout: wgpu::BindGroupLayout,
+ render_pipeline: wgpu::RenderPipeline,
+}
+
+impl MaskPipeline {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Mask Bind Group Layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_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::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("Mask Shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/mask.wgsl").into()),
+ });
+
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Mask Pipeline Layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Mask Pipeline"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: Some(wgpu::Face::Back),
+ polygon_mode: wgpu::PolygonMode::Fill,
+ unclipped_depth: false,
+ conservative: false,
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+
+ Self {
+ bind_group_layout,
+ render_pipeline,
+ }
+ }
+
+ pub fn bind_group(
+ &self,
+ device: &wgpu::Device,
+ uniform_buffer: &wgpu::Buffer,
+ texture_view: &wgpu::TextureView,
+ sampler: &wgpu::Sampler,
+ ) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Mask Bind Group"),
+ layout: &self.bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(texture_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(sampler),
+ },
+ ],
+ })
+ }
+}
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index 1469690f2..7b14a8795 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -4,6 +4,7 @@ mod camera;
mod captions;
mod cursor;
mod display;
+mod mask;
pub use background::*;
pub use blur::*;
@@ -11,3 +12,4 @@ pub use camera::*;
pub use captions::*;
pub use cursor::*;
pub use display::*;
+pub use mask::*;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index aa8fb3b58..b9cd8175b 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,7 +1,8 @@
use anyhow::Result;
use cap_project::{
AspectRatio, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, CornerStyle, Crop,
- CursorEvents, ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY,
+ CursorEvents, MaskKind, MaskSegment, ProjectConfiguration, RecordingMeta, StudioRecordingMeta,
+ XY,
};
use composite_frame::CompositeVideoFrameUniforms;
use core::f64;
@@ -12,6 +13,7 @@ use futures::FutureExt;
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer,
+ MaskLayer,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -26,6 +28,7 @@ mod cursor_interpolation;
pub mod decoder;
mod frame_pipeline;
mod layers;
+mod mask;
mod project_recordings;
mod scene;
mod spring_mass_damper;
@@ -36,6 +39,7 @@ pub use decoder::DecodedFrame;
pub use frame_pipeline::RenderedFrame;
pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings};
+use mask::interpolate_masks;
use scene::*;
use zoom::*;
@@ -54,6 +58,42 @@ pub struct RenderOptions {
pub screen_size: XY<u32>,
}
+#[derive(Debug, Clone, Copy)]
+pub enum MaskRenderMode {
+ Sensitive,
+ Highlight,
+}
+
+impl MaskRenderMode {
+ fn from_kind(kind: MaskKind) -> Self {
+ match kind {
+ MaskKind::Sensitive => MaskRenderMode::Sensitive,
+ MaskKind::Highlight => MaskRenderMode::Highlight,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct PreparedMask {
+ pub center: XY<f32>,
+ pub size: XY<f32>,
+ pub feather: f32,
+ pub opacity: f32,
+ pub pixel_size: f32,
+ pub darkness: f32,
+ pub mode: MaskRenderMode,
+ pub output_size: XY<u32>,
+}
+
+impl PreparedMask {
+ fn mode_value(&self) -> u32 {
+ match self.mode {
+ MaskRenderMode::Sensitive => 0,
+ MaskRenderMode::Highlight => 1,
+ }
+ }
+}
+
#[derive(Clone)]
pub struct RecordingSegmentDecoders {
screen: AsyncVideoDecoderHandle,
@@ -382,6 +422,7 @@ pub struct ProjectUniforms {
pub resolution_base: XY<u32>,
pub display_parent_motion_px: XY<f32>,
pub motion_blur_amount: f32,
+ pub masks: Vec<PreparedMask>,
}
#[derive(Debug, Clone)]
@@ -1421,6 +1462,18 @@ impl ProjectUniforms {
}
});
+ let masks = project
+ .timeline
+ .as_ref()
+ .map(|timeline| {
+ interpolate_masks(
+ XY::new(output_size.0, output_size.1),
+ frame_time as f64,
+ &timeline.mask_segments,
+ )
+ })
+ .unwrap_or_default();
+
Self {
output_size,
cursor_size: project.cursor.size as f32,
@@ -1436,6 +1489,7 @@ impl ProjectUniforms {
prev_cursor: prev_interpolated_cursor,
display_parent_motion_px: display_motion_parent,
motion_blur_amount: user_motion_blur,
+ masks,
}
}
}
@@ -1500,6 +1554,7 @@ pub struct RendererLayers {
cursor: CursorLayer,
camera: CameraLayer,
camera_only: CameraLayer,
+ mask: MaskLayer,
#[allow(unused)]
captions: CaptionsLayer,
}
@@ -1513,6 +1568,7 @@ impl RendererLayers {
cursor: CursorLayer::new(device),
camera: CameraLayer::new(device),
camera_only: CameraLayer::new(device),
+ mask: MaskLayer::new(device),
captions: CaptionsLayer::new(device, queue),
}
}
@@ -1583,6 +1639,7 @@ impl RendererLayers {
pub fn render(
&self,
device: &wgpu::Device,
+ queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
session: &mut RenderSession,
uniforms: &ProjectUniforms,
@@ -1645,6 +1702,12 @@ impl RendererLayers {
let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
self.camera.render(&mut pass);
}
+
+ if !uniforms.masks.is_empty() {
+ for mask in &uniforms.masks {
+ self.mask.render(device, queue, session, encoder, mask);
+ }
+ }
}
}
@@ -1807,7 +1870,13 @@ async fn produce_frame(
}),
);
- layers.render(&constants.device, &mut encoder, session, &uniforms);
+ layers.render(
+ &constants.device,
+ &constants.queue,
+ &mut encoder,
+ session,
+ &uniforms,
+ );
finish_encoder(
session,
diff --git a/crates/rendering/src/mask.rs b/crates/rendering/src/mask.rs
new file mode 100644
index 000000000..b89e89c1c
--- /dev/null
+++ b/crates/rendering/src/mask.rs
@@ -0,0 +1,126 @@
+use cap_project::{MaskKind, MaskScalarKeyframe, MaskSegment, MaskVectorKeyframe, XY};
+
+use crate::{MaskRenderMode, PreparedMask};
+
+fn interpolate_vector(base: XY<f64>, keys: &[MaskVectorKeyframe], time: f64) -> XY<f64> {
+ if keys.is_empty() {
+ return base;
+ }
+
+ let mut sorted = keys.to_vec();
+ sorted.sort_by(|a, b| {
+ a.time
+ .partial_cmp(&b.time)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+
+ if time <= sorted[0].time {
+ return XY::new(sorted[0].x, sorted[0].y);
+ }
+
+ for window in sorted.windows(2) {
+ let prev = &window[0];
+ let next = &window[1];
+ if time <= next.time {
+ let span = (next.time - prev.time).max(1e-6);
+ let t = ((time - prev.time) / span).clamp(0.0, 1.0);
+ let x = prev.x + (next.x - prev.x) * t;
+ let y = prev.y + (next.y - prev.y) * t;
+ return XY::new(x, y);
+ }
+ }
+
+ let last = sorted.last().unwrap();
+ XY::new(last.x, last.y)
+}
+
+fn interpolate_scalar(base: f64, keys: &[MaskScalarKeyframe], time: f64) -> f64 {
+ if keys.is_empty() {
+ return base;
+ }
+
+ let mut sorted = keys.to_vec();
+ sorted.sort_by(|a, b| {
+ a.time
+ .partial_cmp(&b.time)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+
+ if time <= sorted[0].time {
+ return sorted[0].value;
+ }
+
+ for window in sorted.windows(2) {
+ let prev = &window[0];
+ let next = &window[1];
+ if time <= next.time {
+ let span = (next.time - prev.time).max(1e-6);
+ let t = ((time - prev.time) / span).clamp(0.0, 1.0);
+ return prev.value + (next.value - prev.value) * t;
+ }
+ }
+
+ sorted.last().map(|k| k.value).unwrap_or(base)
+}
+
+pub fn interpolate_masks(
+ output_size: XY<u32>,
+ frame_time: f64,
+ segments: &[MaskSegment],
+) -> Vec<PreparedMask> {
+ let mut prepared = Vec::new();
+
+ for segment in segments.iter().filter(|s| s.enabled) {
+ if frame_time < segment.start || frame_time > segment.end {
+ continue;
+ }
+
+ let relative_time = (frame_time - segment.start).max(0.0);
+
+ let position =
+ interpolate_vector(segment.center, &segment.keyframes.position, relative_time);
+ let size = interpolate_vector(segment.size, &segment.keyframes.size, relative_time);
+ let mut intensity =
+ interpolate_scalar(segment.opacity, &segment.keyframes.intensity, relative_time);
+
+ if let MaskKind::Highlight = segment.mask_type {
+ let fade_duration = 0.15;
+ let time_since_start = (frame_time - segment.start).max(0.0);
+ let time_until_end = (segment.end - frame_time).max(0.0);
+
+ let fade_in = (time_since_start / fade_duration).min(1.0);
+ let fade_out = (time_until_end / fade_duration).min(1.0);
+
+ intensity *= fade_in * fade_out;
+ }
+
+ let clamped_size = XY::new(size.x.clamp(0.01, 2.0), size.y.clamp(0.01, 2.0));
+
+ let min_axis = clamped_size.x.min(clamped_size.y).abs();
+ let segment_feather = if let MaskKind::Highlight = segment.mask_type {
+ 0.0
+ } else {
+ segment.feather
+ };
+ let feather = (min_axis * 0.5 * segment_feather.max(0.0)).max(0.0001) as f32;
+
+ prepared.push(PreparedMask {
+ center: XY::new(
+ position.x.clamp(0.0, 1.0) as f32,
+ position.y.clamp(0.0, 1.0) as f32,
+ ),
+ size: XY::new(
+ clamped_size.x.clamp(0.0, 2.0) as f32,
+ clamped_size.y.clamp(0.0, 2.0) as f32,
+ ),
+ feather,
+ opacity: intensity.clamp(0.0, 1.0) as f32,
+ pixel_size: segment.pixelation.max(1.0) as f32,
+ darkness: segment.darkness.clamp(0.0, 1.0) as f32,
+ mode: MaskRenderMode::from_kind(segment.mask_type),
+ output_size,
+ });
+ }
+
+ prepared
+}
diff --git a/crates/rendering/src/shaders/mask.wgsl b/crates/rendering/src/shaders/mask.wgsl
new file mode 100644
index 000000000..5269801cc
--- /dev/null
+++ b/crates/rendering/src/shaders/mask.wgsl
@@ -0,0 +1,71 @@
+struct Uniforms {
+ rect_center: vec2<f32>,
+ rect_size: vec2<f32>,
+ feather: f32,
+ opacity: f32,
+ pixel_size: f32,
+ darkness: f32,
+ mode: u32,
+ padding0: u32,
+ output_size: vec2<f32>,
+ padding1: vec2<f32>,
+}
+
+@group(0) @binding(0) var<uniform> uniforms: Uniforms;
+@group(0) @binding(1) var source_texture: texture_2d<f32>;
+@group(0) @binding(2) var source_sampler: sampler;
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+}
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
+ var positions = array<vec2<f32>, 3>(
+ vec2<f32>(-1.0, -1.0),
+ vec2<f32>(3.0, -1.0),
+ vec2<f32>(-1.0, 3.0),
+ );
+
+ let pos = positions[vertex_index];
+ var out: VertexOutput;
+ out.position = vec4<f32>(pos, 0.0, 1.0);
+ out.uv = vec2<f32>(pos.x * 0.5 + 0.5, 1.0 - (pos.y * 0.5 + 0.5));
+ return out;
+}
+
+fn rect_mask(uv: vec2<f32>) -> f32 {
+ let half_size = uniforms.rect_size * 0.5;
+ let delta = abs(uv - uniforms.rect_center) - half_size;
+ let outside = max(delta, vec2<f32>(0.0));
+ let outside_dist = length(outside);
+ let inside_dist = min(max(delta.x, delta.y), 0.0);
+ let sdf = outside_dist + inside_dist;
+ let edge = max(uniforms.feather, 1e-4);
+ return clamp(smoothstep(0.0, edge, -sdf), 0.0, 1.0);
+}
+
+fn pixelate_sample(uv: vec2<f32>) -> vec4<f32> {
+ let px_size = max(uniforms.pixel_size, 1.0);
+ let cell = px_size / uniforms.output_size;
+ let snapped = floor(uv / cell) * cell + cell * 0.5;
+ return textureSample(source_texture, source_sampler, snapped);
+}
+
+@fragment
+fn fs_main(@location(0) uv: vec2<f32>) -> @location(0) vec4<f32> {
+ let base = textureSample(source_texture, source_sampler, uv);
+ let mask = rect_mask(uv);
+
+ if uniforms.mode == 0u {
+ let pixelated = pixelate_sample(uv);
+ let mix_amount = clamp(uniforms.opacity, 0.0, 1.0);
+ let effect = mix(base, pixelated, mix_amount);
+ return mix(base, effect, mask * mix_amount);
+ }
+
+ let darkness = clamp(uniforms.darkness * uniforms.opacity, 0.0, 1.0);
+ let outside = vec4<f32>(base.rgb * (1.0 - darkness), base.a);
+ return mix(outside, base, mask);
+}
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index c10b785a8..c19129bd8 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -67,6 +67,7 @@ declare global {
const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default']
const IconLucideAlertTriangle: typeof import('~icons/lucide/alert-triangle.jsx')['default']
const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']
+ const IconLucideBoxSelect: typeof import('~icons/lucide/box-select.jsx')['default']
const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default']
const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
const IconLucideClapperboard: typeof import('~icons/lucide/clapperboard.jsx')['default']
@@ -92,6 +93,7 @@ declare global {
const IconLucideSave: typeof import('~icons/lucide/save.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']
+ const IconLucideTimer: typeof import('~icons/lucide/timer.jsx')['default']
const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default']
const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']
const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']