Skip to content

Open source CapCut alternative.

TypeScript

feat(site): track motion for masks and poses [rebuild]

David Le9028e14e7333
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index d980ee57..f8470d58 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -43,7 +43,7 @@ The turn's route is one typed judgment: a System One judge scores the ask's size
The same loop code runs with no browser at all. A headless session opens a project doc into the editor store, binds both transports at an explicit origin with auth headers, and runs the production chat loop against it — which is how a chat turn becomes a durable job. The page or an API caller posts a thread's messages to the cloud project's turns route; the row is the project's agent write lease (one turn at a time per project); the worker container claims it, runs the turn under a runner grant that spends that user's credits and writes that user's project, pushes the doc back through the versioned PUT, and appends the finished exchange to the stored thread.
-A job can do everything a tab can, because the same tool code runs over swapped primitives. The library draws, decodes and measures through narrow seams — a canvas factory, a frame sink, a font installer — which the page fills with the browser's own and the container fills at startup with a native canvas, native decoders, a Web Audio graph, and the editor's font files staged in the image. So watching footage, cutting on silence, freezing a frame, matting a sticker, writing captions and capturing the composited frame all behave in a job the way they behave in the tab, and parity holds by construction: there is one implementation. Two things stay page-only — on-device MediaPipe matting, which falls through to the hosted vision path, and Lottie stickers, which need a DOM.
+A job can do everything a tab can, because the same tool code runs over swapped primitives. The library draws, decodes and measures through narrow seams — a canvas factory, a frame sink, a font installer — which the page fills with the browser's own and the container fills at startup with a native canvas, native decoders, a Web Audio graph, and the editor's font files staged in the image. So watching, silence cuts, freeze frames, sticker matting, captions and frame captures behave in a job as in the tab: there is one implementation. Three things stay page-only: on-device MediaPipe matting, which falls through to the hosted vision path; motion tracking, which a job refuses back to the tab; and Lottie stickers, which need a DOM.
Two mechanisms keep a turn honest. A mutation ledger, computed in code from the tool results, rides every model call as an ephemeral context note: what ran, what failed, and what debris the edits left (a parked transition bar, an item stranded past the video's end) — the model must fix or plainly report each entry before its reply lands, and the note is never stored or rendered. And the step budget extends itself, the same way on every provider: a build that outgrows its 24 steps gets fresh budget automatically (up to three extensions, so 96 in all), so the user never types "keep going". Gemini blocks tool calls at the ceiling and gets one round to say where it landed; a CLI run that spends the budget is resumed from its own session. However a turn ends — at the ceiling, on a provider's error, or saying nothing at all — it closes with a line the person can act on, never with the provider's word for it.
diff --git a/site/.gitignore b/site/.gitignore
index 0e18c8f1..3bc6738d 100644
--- a/site/.gitignore
+++ b/site/.gitignore
@@ -61,6 +61,7 @@ next-env.d.ts
# MediaPipe wasm runtime, staged from node_modules by postinstall
/public/mediapipe/wasm/
+/public/mediapipe/*.task
/public/cut-fonts/
/public/models/rife_v4.25.onnx
/public/ort/
diff --git a/site/packages/effects-kit/src/keys.ts b/site/packages/effects-kit/src/keys.ts
index 5545d14a..07736ad1 100644
--- a/site/packages/effects-kit/src/keys.ts
+++ b/site/packages/effects-kit/src/keys.ts
@@ -124,6 +124,13 @@ export function sortedKeys<K extends { t: number }>(keys: K[]): K[] {
return [...keys].sort((a, b) => a.t - b.t);
}
+function inOrder(keys: { t: number }[]): boolean {
+ for (let i = 1; i < keys.length; i++) {
+ if (keys[i].t < keys[i - 1].t) return false;
+ }
+ return true;
+}
+
/**
* The interpolation core every key track shares: find the surrounding keys,
* hold flat outside them, and hand the pair to `mix`. The pose track and the
@@ -134,12 +141,21 @@ export function lerpKeys<K extends { t: number; ease?: EaseId }>(
tLocal: number,
mix: (a: K, b: K, p: number) => K
): K {
- const ks = sortedKeys(keys);
+ // Stored tracks are already in order, and a tracked mask carries a key per
+ // frame: reading them in place and halving the search keeps a playback
+ // frame free of a copy and a sort.
+ const ks = inOrder(keys) ? keys : sortedKeys(keys);
if (tLocal <= ks[0].t) return ks[0];
const last = ks[ks.length - 1];
if (tLocal >= last.t) return last;
- let i = 0;
- while (i < ks.length - 1 && ks[i + 1].t <= tLocal) i++;
+ let lo = 0;
+ let hi = ks.length - 1;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (ks[mid].t <= tLocal) lo = mid;
+ else hi = mid;
+ }
+ const i = lo;
const a = ks[i];
const b = ks[i + 1];
const span = b.t - a.t;
diff --git a/site/packages/effects-kit/src/mask.test.ts b/site/packages/effects-kit/src/mask.test.ts
index e6a77ffe..94d35e59 100644
--- a/site/packages/effects-kit/src/mask.test.ts
+++ b/site/packages/effects-kit/src/mask.test.ts
@@ -147,3 +147,41 @@ describe("pen masks", () => {
);
});
});
+
+describe("keyed pen outlines", () => {
+ const square = (s: number) => [
+ { x: -s, y: -s },
+ { x: s, y: -s },
+ { x: s, y: s },
+ { x: -s, y: s },
+ ];
+ const pen = (kf: MaskKey[]): Mask => ({ kind: "pen", w: 1, h: 1, points: square(0.1), kf });
+
+ test("an outline blends corner by corner between keys", () => {
+ const m = pen([key(0, { w: 1, h: 1, points: square(0.1) }), key(1, { w: 1, h: 1, points: square(0.3) })]);
+ expect(maskFrameAt(m, 0.5).points).toEqual(square(0.2));
+ });
+
+ test("outlines of different corner counts hold the earlier one", () => {
+ const tri = [{ x: 0, y: -0.2 }, { x: 0.2, y: 0.2 }, { x: -0.2, y: 0.2 }];
+ const m = pen([key(0, { points: square(0.1) }), key(1, { points: tri })]);
+ expect(maskFrameAt(m, 0.5).points).toEqual(square(0.1));
+ expect(maskFrameAt(m, 1).points).toEqual(tri);
+ });
+
+ test("keys without an outline leave the mask's own points in charge", () => {
+ const m = pen([key(0), key(1, { x: 0.2 })]);
+ expect(maskFrameAt(m, 0.5).points).toBeUndefined();
+ expect(maskKeyAt(m, 0.5).points).toBeUndefined();
+ });
+
+ test("a key captured on a tracked outline carries the outline there", () => {
+ const m = pen([key(0, { points: square(0.1) }), key(2, { points: square(0.3) })]);
+ expect(maskKeyAt(m, 1).points).toEqual(square(0.2));
+ });
+
+ test("keys stored out of order still evaluate in time order", () => {
+ const m = pen([key(1, { points: square(0.3) }), key(0, { points: square(0.1) })]);
+ expect(maskFrameAt(m, 0.5).points).toEqual(square(0.2));
+ });
+});
diff --git a/site/packages/effects-kit/src/mask.ts b/site/packages/effects-kit/src/mask.ts
index ed8831fa..ff3beaf4 100644
--- a/site/packages/effects-kit/src/mask.ts
+++ b/site/packages/effects-kit/src/mask.ts
@@ -211,6 +211,9 @@ export interface MaskKey {
feather: number; // edge softness, px at the 1080 design short side
/** Box corner radius, design px; absent = the mask's own. */
radius?: number;
+ /** A pen outline of the key's own, for an outline whose corners move — a
+ * tracked shape. Keys without one draw the mask's `points`. */
+ points?: MaskPoint[];
}
export interface Mask {
@@ -246,6 +249,9 @@ export interface MaskFrame {
rotation: number;
feather: number;
radius: number;
+ /** The keyed pen outline at this moment; absent when the keys carry none
+ * and the mask's own `points` draw. */
+ points?: MaskPoint[];
}
export function restingMaskFrame(m: Mask): MaskFrame {
@@ -293,6 +299,7 @@ export function maskFrameAt(m: Mask, tLocal: number): MaskFrame {
rotation: a.rotation + shortestTurn(a.rotation, b.rotation) * p,
feather: mix(a.feather, b.feather),
radius: mix(a.radius ?? rest, b.radius ?? rest),
+ points: mixPoints(a.points, b.points, p),
};
});
return {
@@ -303,9 +310,17 @@ export function maskFrameAt(m: Mask, tLocal: number): MaskFrame {
rotation: k.rotation,
feather: k.feather,
radius: k.radius ?? rest,
+ ...(k.points ? { points: k.points } : {}),
};
}
+/** Two keyed outlines blended corner by corner. Outlines with different
+ * corner counts cannot blend, so the earlier one holds until the next key. */
+function mixPoints(a: MaskPoint[] | undefined, b: MaskPoint[] | undefined, p: number): MaskPoint[] | undefined {
+ if (!a || !b || a.length !== b.length) return a ?? b;
+ return a.map((q, i) => ({ x: q.x + (b[i].x - q.x) * p, y: q.y + (b[i].y - q.y) * p }));
+}
+
/** A key holding the mask's geometry at `t`, ready to be added — capturing
* the live frame keeps the first key a visual no-op. */
export function maskKeyAt(m: Mask, t: number): MaskKey {
@@ -383,7 +398,7 @@ export function paintMaskCoverage(
} else {
if (feather > 0 && "filter" in ctx) ctx.filter = `blur(${feather / 2}px)`;
ctx.beginPath();
- tracePen(ctx, m.points!, w, h);
+ tracePen(ctx, f.points ?? m.points!, w, h);
ctx.fill();
}
} else if (m.kind === "linear") {
diff --git a/site/scripts/copy-mediapipe-assets.mjs b/site/scripts/copy-mediapipe-assets.mjs
index 3ad48178..f18cea0c 100644
--- a/site/scripts/copy-mediapipe-assets.mjs
+++ b/site/scripts/copy-mediapipe-assets.mjs
@@ -1,9 +1,12 @@
-// Stage the MediaPipe vision runtime into public/ so segmentation runs
-// self-hosted (no runtime Google fetch). The wasm pair is ~12MB, so it is
+// Stage the MediaPipe vision runtime into public/ so segmentation and tracking
+// run self-hosted (no runtime Google fetch). The wasm pair is ~12MB, so it is
// copied from node_modules on install rather than committed; the
-// person-segmentation and tap-to-select models are committed beside it.
+// person-segmentation and tap-to-select models are committed beside it. The
+// landmarker models are ~21MB together, so install fetches them once from
+// Google's model bucket, pinned by version and checksum.
// Runs from postinstall.
-import { copyFileSync, existsSync, mkdirSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -20,3 +23,38 @@ if (!existsSync(src)) {
}
mkdirSync(dest, { recursive: true });
for (const f of files) copyFileSync(path.join(src, f), path.join(dest, f));
+
+// The tracking models (src/cut/lib/tracking.ts reads them from these paths).
+const MODEL_BUCKET = "https://storage.googleapis.com/mediapipe-models";
+const models = [
+ {
+ file: "hand_landmarker.task",
+ url: `${MODEL_BUCKET}/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`,
+ sha256: "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1",
+ },
+ {
+ file: "face_landmarker.task",
+ url: `${MODEL_BUCKET}/face_landmarker/face_landmarker/float16/1/face_landmarker.task`,
+ sha256: "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff",
+ },
+ {
+ file: "pose_landmarker_full.task",
+ url: `${MODEL_BUCKET}/pose_landmarker/pose_landmarker_full/float16/1/pose_landmarker_full.task`,
+ sha256: "5134a3aad27a58b93da0088d431f366da362b44e3ccfbe3462b3827a839011b1",
+ },
+];
+
+const modelDir = path.join(root, "public", "mediapipe");
+const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
+
+for (const m of models) {
+ const out = path.join(modelDir, m.file);
+
+ // A staged model with the pinned checksum is already in place.
+ if (existsSync(out) && digest(readFileSync(out)) === m.sha256) continue;
+ const res = await fetch(m.url);
+ if (!res.ok) throw new Error(`copy-mediapipe-assets: ${m.file} download failed (${res.status})`);
+ const bytes = Buffer.from(await res.arrayBuffer());
+ if (digest(bytes) !== m.sha256) throw new Error(`copy-mediapipe-assets: ${m.file} checksum mismatch`);
+ writeFileSync(out, bytes);
+}
diff --git a/site/src/clients/chatgpt/server/guidance.ts b/site/src/clients/chatgpt/server/guidance.ts
index 5eb87f10..c130ff8d 100644
--- a/site/src/clients/chatgpt/server/guidance.ts
+++ b/site/src/clients/chatgpt/server/guidance.ts
@@ -54,7 +54,7 @@ For one exact instance among similar subjects, ask the user to use Custom, Brush
"graphics": `# Titles, graphics and motion
Use add_title or add_text_sequence for words, add_shape for geometry, add_sticker for an imported image, and add_effect for a treatment over a time range. Read describe_commands for the current supported styles and parameters. set_background sets the project's background color. Use ids and fonts reported by inspect_project.
update_overlay changes text, position, size, color and other element fields, and accepts ids for changes shared by several elements. Layout coordinates are frame fractions. Keep text inside the project's reported safe zones and check legibility with capture_frame.
-set_overlay_keyframes and set_clip_keyframes animate poses at exact times. set_group_camera moves one camera over a group of elements, and blur and motion blur soften what the camera is not on. set_overlay_animation supplies entrances, exits, loops, word motion, a typing caret and a one-shot press at a chosen moment. set_mask clips a layer to a shape and can animate the reveal. Read text-videos for timed text and text-creativity for design choices.
+set_overlay_keyframes and set_clip_keyframes animate poses at exact times. set_group_camera moves one camera over a group of elements, and blur and motion blur soften what the camera is not on. set_overlay_animation supplies entrances, exits, loops, word motion, a typing caret and a one-shot press at a chosen moment. set_mask clips a layer to a shape and can animate the reveal. track_motion keys a mask or a pose to a hand, a head or a person in the footage, frame by frame. Read text-videos for timed text and text-creativity for design choices.
Build composite effects as layers: add_overlay_video for copies of footage, masks for visible regions, shapes for bands, and text for labels. Match source trims so copied footage stays synchronized. Work out geometry and timing, build one representative piece, capture_frame to check it, then repeat and check the whole composition. create_sticker generates a new sticker and spends credits when the user requests it.`,
"audio-and-subtitles": `# Audio and subtitles
diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.ts
index 271aafff..e72690c5 100644
--- a/site/src/cut/components/Inspector.tools.ts
+++ b/site/src/cut/components/Inspector.tools.ts
@@ -35,6 +35,8 @@ import {
import { bool, ids, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";
import { builtinLutCatalogText } from "@/cut/lib/builtinLuts";
import { SPLIT_EDIT_MAX_S } from "@/cut/lib/soundSource";
+import { FOLLOW_MODES } from "@/cut/lib/trackKeys";
+import { TRACK_TARGET_IDS, TRACK_TARGETS, TRACK_USES } from "@/cut/lib/trackTargets";
/** Per-field slider hints; ranges interpolate the exported constants so the
* schema can never drift from the model the renderer clamps to. */
@@ -181,6 +183,22 @@ export const INSPECTOR_TOOLS = [
},
}, ["id"]),
},
+ {
+ name: "track_motion",
+ description:
+ `Track a target through a video clip's footage, frame by frame, with on-device landmark models, and drive an item with the path. Targets: ${TRACK_TARGETS.map((t) => `${t.id} (${t.covers})`).join("; ")}. use "mask" gives the item a pen mask whose outline follows the target on every frame, keyed for you — a filtered copy of the shot that shows only between the hands, a blur only on a face; it replaces the item's mask, and one masked item carries the whole span, so never split a clip into pieces to move a mask. use "follow" keys the item's pose so it rides the target — a sticker on a head, a label beside a hand — keeping where it sits relative to the target at the start (follow_mode says whether it also scales and turns with it); it replaces the item's pose keys. use "read" changes nothing and returns when the target is in view and where it goes. The source is the video clip whose picture is read: a clip is its own source unless source_id names another; an element defaults to the video clip under it. Runs in the editor tab, about a second per second of footage.`,
+ inputSchema: obj({
+ id: str("The item to drive: a video clip id or an overlay element id"),
+ target: { type: "string", enum: TRACK_TARGET_IDS, description: "What to track" },
+ use: { type: "string", enum: TRACK_USES, description: "mask: trace the target as a keyed pen mask; follow: key the item's pose to ride it; read: report only" },
+ source_id: str("Video clip whose footage is tracked; default: the item itself when it is a clip, else the clip under the element"),
+ from: num("Timeline seconds to start tracking; default where the item and the source first overlap"),
+ to: num("Timeline seconds to stop tracking; default where they stop overlapping"),
+ follow_mode: { type: "string", enum: FOLLOW_MODES, description: "follow only: move = position; move_scale = position and size; move_scale_turn = position, size and turn (default move_scale)" },
+ feather: num(`mask only: edge softness, px at the 1080 design short side (0..${MASK_FEATHER_MAX})`),
+ invert: bool("mask only: keep everything outside the target"),
+ }, ["id", "target", "use"]),
+ },
{
name: "set_clip_keyframes",
description:
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 9621d57f..e3d9540b 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { EmojiPicker } from "@/cut/components/EmojiPicker";
import { FontPicker } from "@/cut/components/FontPicker";
import { ClipAnimationTiles, previewBar } from "@/cut/components/TransitionsPanel";
+import { TrackRow } from "@/cut/components/TrackRow";
import {
Select,
SelectContent,
@@ -3545,14 +3546,17 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
const seek = useEditor((s) => s.seek);
const st = () => useEditor.getState();
return (
- <KeyRow
- element={o}
- now={now}
- keys={o.kf ?? []}
- onAdd={(tLocal) => st().setOverlayKey(o.id, tLocal)}
- onRemove={(tLocal) => st().removeOverlayKey(o.id, tLocal)}
- onSeek={seek}
- />
+ <>
+ <KeyRow
+ element={o}
+ now={now}
+ keys={o.kf ?? []}
+ onAdd={(tLocal) => st().setOverlayKey(o.id, tLocal)}
+ onRemove={(tLocal) => st().removeOverlayKey(o.id, tLocal)}
+ onSeek={seek}
+ />
+ <TrackRow id={o.id} use="follow" />
+ </>
);
}
@@ -3725,6 +3729,7 @@ function ClipTransformSection({ clip }: { clip: VideoClip }) {
onRemove={(t) => st().removeClipKey(clip.id, t)}
onSeek={seek}
/>
+ <TrackRow id={clip.id} use="follow" />
{keyed && (
<>
<PositionRow
@@ -4176,6 +4181,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
</button>
))}
</div>
+ {!subject && !drawing && <TrackRow id={target.id} use="mask" />}
{drawing && (
<p className="px-1 py-1.5 text-[11.5px] leading-snug text-muted-foreground">
Click the picture to place corners. Click the first corner, double-click, or press
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 4f784684..b89652a8 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -1820,13 +1820,17 @@ export function MaskGizmoCore({
poseScale: number;
/** Keyed geometry: lands on the key at the playhead when keys exist. */
writeGeom: (patch: Partial<Omit<MaskKey, "t">>) => void;
- /** A pen mask's corners, on the mask itself (corners are never keyed). */
+ /** A pen mask's corners, on the mask itself (a tracked outline keys its own
+ * and shows no corner grips). */
writePoints: (points: MaskPoint[]) => void;
begin: () => void;
}) {
const f = maskFrameAt(m, tLocal);
const pen = m.kind === "pen";
const drawing = pen && !penClosed(m);
+ // A tracked outline keys its corners: the guides trace the outline at the
+ // playhead, and its corners belong to the tracker.
+ const shown = f.points ? { ...m, points: f.points } : m;
// Guide lines while a drag sits on a detent: `rot` is the locked quarter
// turn, `x`/`y` mark the mask centered on an axis, `w`/`h` a size locked at
// exactly full frame. Local space, so on an element they ride its transform
@@ -1979,7 +1983,7 @@ export function MaskGizmoCore({
// σ = feather / 2, so the transition spans about the feather width centered
// on the edge; a mirror band's feather never exceeds the band.
const featherPx = Math.min(f.feather * designScale, m.kind === "mirror" ? h : Infinity);
- const outlineD = maskOutlinePathD(m, w, h, span, radiusPx);
+ const outlineD = maskOutlinePathD(shown, w, h, span, radiusPx);
// Where the shape's bottom edge sits in its own frame, for the feather grip.
const bottom = m.kind === "linear" ? 0 : m.kind === "square" ? w / 2 : h / 2;
const edge = {
@@ -2151,7 +2155,7 @@ export function MaskGizmoCore({
// the outline; linear/mirror get a grabbable strip along their edge line.
const grabW = m.kind === "linear" || m.kind === "mirror" ? span * 2 : w;
const grabH = m.kind === "linear" ? 28 : m.kind === "mirror" ? Math.max(h, 28) : h;
- const points = pen && !drawing ? m.points! : null;
+ const points = pen && !drawing && !f.points ? m.points! : null;
const grip = {
borderColor: "#ff9f0a",
boxShadow: "0 1px 4px rgba(0,0,0,0.4)",
@@ -2224,7 +2228,7 @@ export function MaskGizmoCore({
// ellipse, or the polygon's own outline.
...(m.kind === "linear" || m.kind === "mirror"
? {}
- : { clipPath: `path("${maskOutlinePathD(m, w, h, span, radiusPx, grabW / 2, grabH / 2)}")` }),
+ : { clipPath: `path("${maskOutlinePathD(shown, w, h, span, radiusPx, grabW / 2, grabH / 2)}")` }),
}}
onPointerDown={beginMove}
/>
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index fcaeb134..331d6029 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -1,5 +1,5 @@
"use client";
-import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge, bindCutNotes } from "@/cut/lib/chatRuntime";
+import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge, bindCutNotes, bindCutTracking } from "@/cut/lib/chatRuntime";
import { bindCutColor } from "@/cut/lib/colorSettings";
import { bindCutSound } from "@/cut/lib/soundSettings";
import { bindCutMotion } from "@/cut/lib/motionSettings";
@@ -50,6 +50,7 @@ export function RequireSession({ children }: { children: ReactNode }) {
bindCutJudge(config.data.settings.cutJudge);
bindCutClip(config.data.settings.cutClip);
bindCutNotes(config.data.settings.cutNotes);
+ bindCutTracking(config.data.settings.cutTracking);
bindCutColor(config.data.settings.cutColor);
bindCutSound(config.data.settings.cutSound);
bindCutMotion(config.data.settings.cutMotion);
diff --git a/site/src/cut/components/TrackRow.tsx b/site/src/cut/components/TrackRow.tsx
new file mode 100644
index 00000000..a7d9e9d9
--- /dev/null
+++ b/site/src/cut/components/TrackRow.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { useState } from "react";
+import { Loader2 } from "lucide-react";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { trackMotion } from "@/cut/lib/trackMotion";
+import { TRACK_TARGETS, type TrackTarget } from "@/cut/lib/trackTargets";
+
+/**
+ * The inspector's motion-tracking control: pick what to track and the item's
+ * mask traces it (`use: "mask"`), or the item rides it (`use: "follow"`).
+ * Runs the same path as the chat's track_motion tool; while it reads the
+ * footage the row shows how far it has got.
+ */
+export function TrackRow({ id, use }: { id: string; use: "mask" | "follow" }) {
+ const [progress, setProgress] = useState<number | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ // Tracking runs once per pick; the row holds no target of its own, since
+ // the result lives in the item's keys.
+ const run = async (target: TrackTarget) => {
+ setError(null);
+ setProgress(0);
+ try {
+ await trackMotion({ id, target, use, onProgress: (share) => setProgress(Math.round(share * 100)) });
+ } catch (e) {
+ setError(e instanceof Error ? e.message : "Could not track the footage.");
+ } finally {
+ setProgress(null);
+ }
+ };
+
+ return (
+ <>
+ <div className="flex items-center justify-between gap-2 py-1">
+ <span className="text-[11.5px] font-medium text-muted-foreground">{use === "mask" ? "Track" : "Follow"}</span>
+ {progress !== null ? (
+ <span className="flex h-8 items-center gap-1.5 text-[12px] text-muted-foreground">
+ <Loader2 className="size-3.5 animate-spin" />
+ Tracking {progress}%
+ </span>
+ ) : (
+ <Select
+ value={null}
+ items={Object.fromEntries(TRACK_TARGETS.map((t) => [t.id, t.label]))}
+ onValueChange={(v) => {
+ if (v) void run(v as TrackTarget);
+ }}
+ >
+ <SelectTrigger className="h-8 w-36 text-[12px]">
+ <SelectValue placeholder="Pick a target" />
+ </SelectTrigger>
+ <SelectContent>
+ {TRACK_TARGETS.map((t) => (
+ <SelectItem key={t.id} value={t.id} className="text-[12px]">
+ {t.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </div>
+ {error && <p className="px-1 pb-1 text-[11.5px] leading-snug text-destructive">{error}</p>}
+ </>
+ );
+}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index a5c79bb0..f5f4ee9f 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -252,6 +252,9 @@ import { resolveVoiceAsk, synthesizeSpeech, SPEECH_VOICES } from "./tts";
import { hostedPost } from "./hosted";
import { blockAsset } from "./blockSource";
import { cutClip, cutJudge } from "./chatRuntime";
+import { FOLLOW_MODES } from "./trackKeys";
+import { trackMotion } from "./trackMotion";
+import { TRACK_TARGET_IDS, TRACK_USES } from "./trackTargets";
import { askJudgeChunked, noul } from "./judge";
import { SWEEP_CHUNK, sweepPicks, sweepQuestions, sweepState, type SweepCandidate } from "./sweepSelect";
import { clampVideoDuration, defaultVideoAspects, videoResolutionOf } from "./videoModels";
@@ -910,6 +913,28 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
return { id: input.id, mask: next ?? null };
},
+ track_motion: async (_s, input) => {
+ const target = TRACK_TARGET_IDS.find((t) => t === input.target);
+ if (!target) throw new ToolError(`target must be one of: ${TRACK_TARGET_IDS.join(", ")}.`);
+ const use = TRACK_USES.find((u) => u === input.use);
+ if (!use) throw new ToolError(`use must be one of: ${TRACK_USES.join(", ")}.`);
+ const follow = input.follow_mode === undefined ? undefined : FOLLOW_MODES.find((m) => m === input.follow_mode);
+ if (input.follow_mode !== undefined && !follow) throw new ToolError(`follow_mode must be one of: ${FOLLOW_MODES.join(", ")}.`);
+ return trackMotion({
+ id: String(input.id ?? ""),
+ target,
+ use,
+ ...(typeof input.source_id === "string" ? { sourceId: input.source_id } : {}),
+ ...(isNum(input.from) ? { from: input.from } : {}),
+ ...(isNum(input.to) ? { to: input.to } : {}),
+ ...(follow ? { follow } : {}),
+ ...(isNum(input.feather) ? { feather: input.feather } : {}),
+ ...(typeof input.invert === "boolean" ? { invert: input.invert } : {}),
+ }).catch((e) => {
+ throw new ToolError(e instanceof Error ? e.message : "Could not track the footage.");
+ });
+ },
+
set_transition: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
// A transition joins a clip to the next one on its own track.
@@ -5330,6 +5355,11 @@ export const MEDIA_RUNTIME_TOOLS: ReadonlySet<string> = new Set([
"stock_add",
]);
+/** Tools that need the editor page itself: motion tracking runs MediaPipe's
+ * landmark models, which load into a browser and nowhere else. A headless
+ * session answers these with a refusal that sends the person to the tab. */
+export const PAGE_ONLY_TOOLS: ReadonlySet<string> = new Set(["track_motion"]);
+
export async function runAiTool(
name: string,
input: Record<string, unknown>
diff --git a/site/src/cut/lib/chatRuntime.ts b/site/src/cut/lib/chatRuntime.ts
index 6d4934d4..baf3e605 100644
--- a/site/src/cut/lib/chatRuntime.ts
+++ b/site/src/cut/lib/chatRuntime.ts
@@ -28,6 +28,13 @@ export function bindCutClip(value: unknown): void {
}
export function cutClip(): Settings["cutClip"] { return clip; }
+let tracking: Settings["cutTracking"] = SETTINGS.cutTracking.default;
+export function bindCutTracking(value: unknown): void {
+ const parsed = SETTINGS.cutTracking.schema.safeParse(value);
+ if (parsed.success) tracking = parsed.data;
+}
+export function cutTracking(): Settings["cutTracking"] { return tracking; }
+
let notes: Settings["cutNotes"] = SETTINGS.cutNotes.default;
export function bindCutNotes(value: unknown): void {
const parsed = SETTINGS.cutNotes.schema.safeParse(value);
diff --git a/site/src/cut/lib/cutout.ts b/site/src/cut/lib/cutout.ts
index 9295faed..eac9d5fb 100644
--- a/site/src/cut/lib/cutout.ts
+++ b/site/src/cut/lib/cutout.ts
@@ -23,8 +23,8 @@ import {
import { hostedPost } from "./hosted";
import { decodeRasterImage, rasterCanvasToDataUrl, rasterCanvasToPng } from "./raster";
import { geminiModelRoleNames } from "@/lib/inference/gemini-models";
+import { visionFileset, withQuietWasmLogs } from "./mediapipe";
-const WASM_BASE = "/mediapipe/wasm";
const PERSON_MODEL = "/mediapipe/selfie_segmenter.tflite";
/** Confidence above which a pixel counts as subject. */
const PERSON_THRESHOLD = 0.35;
@@ -32,38 +32,6 @@ type Segmenter = import("@mediapipe/tasks-vision").ImageSegmenter;
let segmenterOnce: Promise<Segmenter | null> | null = null;
-/**
- * Give the wasm module somewhere quiet to log.
- *
- * TFLite writes its start-up notes ("INFO: Created TensorFlow Lite XNNPACK
- * delegate for CPU.", the GL and feedback-manager warnings) to the module's
- * stderr, and Emscripten binds stderr to `console.error` as the glue script
- * evaluates. Next's dev overlay classifies by channel rather than severity, so
- * an INFO line arrives on screen as a page error, pinned to whichever frame
- * happened to be running — in practice the behind-speaker pass, mid-playback.
- *
- * Emscripten reads `print`/`printErr` off the module object, and the task
- * runner passes a pre-set `self.Module` through to the factory (copying its own
- * `locateFile` onto it and clearing the global afterwards). Pointing those at
- * `console.debug` keeps the notes readable under verbose logging and off the
- * error channel. Patching `console.error` around the call cannot work: the glue
- * captured the original binding before we could reach it.
- */
-type EmscriptenScope = typeof globalThis & { Module?: Record<string, unknown> };
-
-async function withQuietWasmLogs<T>(create: () => Promise<T>): Promise<T> {
- const scope = globalThis as EmscriptenScope;
- const prior = scope.Module;
- const note = (...args: unknown[]) => console.debug("[mediapipe]", ...args);
- scope.Module = { print: note, printErr: note };
- try {
- return await create();
- } finally {
- if (prior === undefined) delete scope.Module;
- else scope.Module = prior;
- }
-}
-
/** Build the inference delegate at load time. TFLite defers it to the first
* inference, which would otherwise land on the first playback frame that needs
* a matte. */
@@ -83,8 +51,8 @@ function warmSegmenter(segmenter: Segmenter): void {
export function personSegmenter(): Promise<Segmenter | null> {
segmenterOnce ??= (async () => {
try {
- const { FilesetResolver, ImageSegmenter } = await import("@mediapipe/tasks-vision");
- const fileset = await FilesetResolver.forVisionTasks(WASM_BASE);
+ const { ImageSegmenter } = await import("@mediapipe/tasks-vision");
+ const fileset = await visionFileset();
const segmenter = await withQuietWasmLogs(() =>
ImageSegmenter.createFromOptions(fileset, {
baseOptions: { modelAssetPath: PERSON_MODEL },
diff --git a/site/src/cut/lib/devHooks.ts b/site/src/cut/lib/devHooks.ts
index 2149e2be..8005527a 100644
--- a/site/src/cut/lib/devHooks.ts
+++ b/site/src/cut/lib/devHooks.ts
@@ -16,6 +16,8 @@ import { awaitingFrame, startTrace, stopTrace, traceReport } from "./perfTrace";
import { markSignedBatch } from "./mediaLinks";
import { prefetchCloudMedia } from "./mediaSync";
import { playheadAt } from "./playhead";
+import { bindCutTracking } from "./chatRuntime";
+import { trackFootage } from "./tracking";
import { projectDuration, useEditor } from "./store";
export function installDevHooks(): void {
@@ -52,6 +54,10 @@ export function installDevHooks(): void {
// The export eval starts a real export through the store, the way the
// dialog does, and watches the dock's feed for the file.
useExports,
+ // The tracking check reads a clip's raw landmarks beside the keys the
+ // tracker wrote, to see where the path parts from the picture.
+ trackFootage,
+ bindCutTracking,
};
// The perf eval arms and reads the frame trace through here. Off until
// `start()` is called, so an ordinary dev session records nothing.
diff --git a/site/src/cut/lib/mediapipe.ts b/site/src/cut/lib/mediapipe.ts
new file mode 100644
index 00000000..b42b83aa
--- /dev/null
+++ b/site/src/cut/lib/mediapipe.ts
@@ -0,0 +1,57 @@
+"use client";
+
+/**
+ * The MediaPipe vision runtime every on-device model shares: the self-hosted
+ * wasm (staged into public/ on install) and the quiet log channel its tasks
+ * start under. The person segmenter (cutout.ts) and the landmark trackers
+ * (tracking.ts) both create their tasks through here.
+ */
+
+const WASM_BASE = "/mediapipe/wasm";
+
+type Fileset = Awaited<ReturnType<typeof import("@mediapipe/tasks-vision").FilesetResolver.forVisionTasks>>;
+
+let filesetOnce: Promise<Fileset> | null = null;
+
+/** The wasm fileset, resolved once per page. */
+export function visionFileset(): Promise<Fileset> {
+ filesetOnce ??= import("@mediapipe/tasks-vision")
+ .then(({ FilesetResolver }) => FilesetResolver.forVisionTasks(WASM_BASE))
+ .catch((e: unknown) => {
+ filesetOnce = null;
+ throw e;
+ });
+ return filesetOnce;
+}
+
+/**
+ * Give the wasm module somewhere quiet to log.
+ *
+ * TFLite writes its start-up notes ("INFO: Created TensorFlow Lite XNNPACK
+ * delegate for CPU.", the GL and feedback-manager warnings) to the module's
+ * stderr, and Emscripten binds stderr to `console.error` as the glue script
+ * evaluates. Next's dev overlay classifies by channel rather than severity, so
+ * an INFO line arrives on screen as a page error, pinned to whichever frame
+ * happened to be running — in practice the behind-speaker pass, mid-playback.
+ *
+ * Emscripten reads `print`/`printErr` off the module object, and the task
+ * runner passes a pre-set `self.Module` through to the factory (copying its own
+ * `locateFile` onto it and clearing the global afterwards). Pointing those at
+ * `console.debug` keeps the notes readable under verbose logging and off the
+ * error channel. Patching `console.error` around the call cannot work: the glue
+ * captured the original binding before we could reach it.
+ */
+type EmscriptenScope = typeof globalThis & { Module?: Record<string, unknown> };
+
+export async function withQuietWasmLogs<T>(create: () => Promise<T>): Promise<T> {
+ const scope = globalThis as EmscriptenScope;
+ const prior = scope.Module;
+ const note = (...args: unknown[]) => console.debug("[mediapipe]", ...args);
+ scope.Module = { print: note, printErr: note };
+ try {
+ return await create();
+ } finally {
+ if (prior === undefined) delete scope.Module;
+ else scope.Module = prior;
+ }
+}
diff --git a/site/src/cut/lib/pi/serverDeps.ts b/site/src/cut/lib/pi/serverDeps.ts
index fcfd35dc..6bf2006d 100644
--- a/site/src/cut/lib/pi/serverDeps.ts
+++ b/site/src/cut/lib/pi/serverDeps.ts
@@ -4,7 +4,7 @@ import { AI_SKILL_INDEX, readSkill } from "@/cut/server/ai/catalog";
import { projectOperation } from "../projectOperation";
import { useEditor } from "../store";
import { buildAiContext } from "../aiContext";
-import { MEDIA_RUNTIME_TOOLS, runProjectCommand } from "../aiTools";
+import { MEDIA_RUNTIME_TOOLS, PAGE_ONLY_TOOLS, runProjectCommand } from "../aiTools";
import { normalizeRef } from "../assetRef";
import { DETACHED_UI_NOTE } from "../chatResume";
import { NO_CREDITS_MESSAGE } from "../credits";
@@ -36,6 +36,8 @@ export function headlessDeps(session: HeadlessSession): CutAgentDeps {
if (UI_TOOLS.has(name)) return { noEditor: true, note: DETACHED_UI_NOTE };
// The worker installs canvas and decoders at startup and these run as
// written. A process that came up without them says so plainly.
+ if (PAGE_ONLY_TOOLS.has(name))
+ throw new Error("This tool runs in the editor tab, and this session has none. Tell the user to open the project in Donkey Cut and ask again.");
if (MEDIA_RUNTIME_TOOLS.has(name)) {
const rt = headlessRuntime();
if (!rt?.raster || !rt.media)
diff --git a/site/src/cut/lib/trackKeys.test.ts b/site/src/cut/lib/trackKeys.test.ts
new file mode 100644
index 00000000..7174cadd
--- /dev/null
+++ b/site/src/cut/lib/trackKeys.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, test } from "bun:test";
+import { followKeys, keepTurns, pictureToFrame, settleTrack, trackedMask, type TrackSample } from "./trackKeys";
+import type { Overlay, VideoClip } from "./types";
+
+const tune = { smoothCutoff: 1.5, smoothBeta: 20, bridgeSeconds: 0.25, keyTolerance: 0.0015 };
+
+const clip = (over: Partial<VideoClip> = {}): VideoClip =>
+ ({ id: "c1", assetId: "a1", start: 0, in: 0, out: 10, track: 0, ...over }) as VideoClip;
+
+/** A square target of half-side `r` centered at (x, y), axis left to right. */
+const at = (x: number, y: number, r = 0.1): TrackSample => ({
+ outline: [
+ { x: x - r, y: y - r },
+ { x: x + r, y: y - r },
+ { x: x + r, y: y + r },
+ { x: x - r, y: y + r },
+ ],
+ center: { x, y },
+ axis: [{ x: x - r, y }, { x: x + r, y }],
+});
+
+const times = (n: number, fps = 30) => Array.from({ length: n }, (_, i) => i / fps);
+
+describe("settling a track", () => {
+ test("a short dropout is bridged by blending its neighbors", () => {
+ const t = times(5);
+ const out = settleTrack(t, [at(0.2, 0.5), null, null, at(0.2, 0.5), at(0.2, 0.5)], tune);
+ expect(out.every((s) => s !== null)).toBe(true);
+ });
+
+ test("a long dropout stays a gap, and the run after it restarts the filter", () => {
+ const t = times(20);
+ const samples = t.map((_, i) => (i === 0 ? at(0.2, 0.5) : i === 19 ? at(0.8, 0.5) : null));
+ const out = settleTrack(t, samples, tune);
+ expect(out.slice(1, 19).every((s) => s === null)).toBe(true);
+ // A fresh run starts exactly where the target is, with no pull from before.
+ expect(out[19]!.center.x).toBeCloseTo(0.8, 6);
+ });
+
+ test("jitter on a still target is taken down", () => {
+ const t = times(60);
+ const noisy = t.map((_, i) => at(0.5 + (i % 2 ? 0.004 : -0.004), 0.5));
+ const out = settleTrack(t, noisy, tune);
+ const tail = out.slice(30).map((s) => s!.center.x);
+ expect(Math.max(...tail) - Math.min(...tail)).toBeLessThan(0.004);
+ });
+
+ test("a fast move stays close behind the target", () => {
+ const t = times(30);
+ const moving = t.map((s) => at(0.1 + s * 0.8, 0.5));
+ const out = settleTrack(t, moving, tune);
+ expect(Math.abs(out[29]!.center.x - moving[29].center.x)).toBeLessThan(0.01);
+ });
+});
+
+describe("placing the source picture in the frame", () => {
+ test("a matching aspect maps straight through", () => {
+ const place = pictureToFrame(clip(), { width: 1080, height: 1920 }, "9:16");
+ expect(place({ x: 0.25, y: 0.75 })).toEqual({ x: 0.25, y: 0.75 });
+ });
+
+ test("a landscape picture fitted into a vertical frame letterboxes", () => {
+ const place = pictureToFrame(clip(), { width: 1920, height: 1080 }, "9:16");
+ const top = place({ x: 0, y: 0 });
+ expect(top.x).toBeCloseTo(0, 6);
+ expect(top.y).toBeCloseTo((1920 - 1080 * (1080 / 1920)) / 2 / 1920, 6);
+ });
+
+ test("a covering clip crops and a mirrored one flips about its region", () => {
+ const place = pictureToFrame(clip({ fit: "fill", flipH: true }), { width: 1920, height: 1080 }, "9:16");
+ // Covering: the picture's center column lands on the frame's center.
+ expect(place({ x: 0.5, y: 0.5 }).x).toBeCloseTo(0.5, 6);
+ // Mirrored: a point right of center lands left of it.
+ expect(place({ x: 0.55, y: 0.5 }).x).toBeLessThan(0.5);
+ });
+});
+
+describe("a tracked mask", () => {
+ test("keys the outline relative to the clip's region and folds it where the target is gone", () => {
+ const t = times(4);
+ const m = trackedMask({ kind: "clip", clip: clip() }, "9:16", t, [at(0.6, 0.5), at(0.6, 0.5), null, null], {}, 0)!;
+ expect(m.kind).toBe("pen");
+ expect(m.kf![0].points![0]).toEqual({ x: 0, y: -0.1 });
+ const folded = m.kf![m.kf!.length - 1].points!;
+ expect(folded.every((p) => p.x === 0.1 && p.y === 0)).toBe(true);
+ });
+
+ test("on an element, the outline is carried back through the element's pose", () => {
+ const overlay = { id: "o1", kind: "shape", start: 0, end: 1, x: 0.5, y: 0.5, kf: [{ t: 0, x: 0.3, y: 0.5, scale: 2, rotation: 0, opacity: 1 }] } as unknown as Overlay;
+ const m = trackedMask({ kind: "overlay", overlay }, "9:16", [0], [at(0.3, 0.5)], {}, 0)!;
+ // The element sits at x 0.3, scaled 2×: the target's corner 0.1 to its
+ // left is 0.05 in the element's own space.
+ expect(m.points![0].x).toBeCloseTo(-0.05, 6);
+ });
+
+ test("straight stretches drop their middle keys", () => {
+ const t = times(30);
+ const m = trackedMask({ kind: "clip", clip: clip() }, "9:16", t, t.map((s) => at(0.2 + s * 0.3, 0.5)), {}, 0.0015)!;
+ expect(m.kf!.length).toBe(2);
+ });
+});
+
+describe("following a target", () => {
+ test("the item keeps its offset, grows with the target and turns with it", () => {
+ const t = [0, 1];
+ const turned: TrackSample = {
+ outline: [],
+ center: { x: 0.5, y: 0.5 },
+ axis: [{ x: 0.5, y: 0.5 - 0.2 * (9 / 16) }, { x: 0.5, y: 0.5 + 0.2 * (9 / 16) }],
+ };
+ const keys = followKeys(
+ { kind: "clip", clip: clip() },
+ "9:16",
+ t,
+ [at(0.5, 0.5), turned],
+ { x: 0.6, y: 0.5, scale: 1, rotation: 0, opacity: 1 },
+ "move_scale_turn",
+ 0
+ );
+ expect(keys[0]).toMatchObject({ x: 0.6, y: 0.5, scale: 1, rotation: 0 });
+ expect(keys[1].rotation).toBeCloseTo(90, 1);
+ expect(keys[1].scale).toBeCloseTo(2, 2);
+ expect(keys[1].x).toBeCloseTo(0.5, 3);
+ });
+
+ test("moments without the target write no key", () => {
+ const keys = followKeys({ kind: "clip", clip: clip() }, "9:16", times(3), [at(0.5, 0.5), null, at(0.6, 0.5)], { x: 0.5, y: 0.5, scale: 1, rotation: 0, opacity: 1 }, "move", 0);
+ expect(keys.map((k) => k.x)).toEqual([0.5, 0.6]);
+ });
+});
+
+describe("keeping keys", () => {
+ test("keeps the corners of a path and drops points on its lines", () => {
+ const t = [0, 1, 2, 3, 4];
+ const v = [[0], [1], [2], [1], [0]];
+ expect(keepTurns(t, v, 0.01)).toEqual([0, 2, 4]);
+ });
+});
diff --git a/site/src/cut/lib/trackKeys.ts b/site/src/cut/lib/trackKeys.ts
new file mode 100644
index 00000000..8967c55b
--- /dev/null
+++ b/site/src/cut/lib/trackKeys.ts
@@ -0,0 +1,359 @@
+/**
+ * From a raw track to keys an item plays.
+ *
+ * tracking.ts reports where a target sits in the source picture, frame by
+ * frame. This module settles that path — short dropouts bridged, jitter taken
+ * out with a one-euro filter that stays tight on fast moves — then places it
+ * in the project frame through the clip's own framing (region, fit, zoom,
+ * pan, mirror), and writes it as keys: a pen mask whose outline is keyed per
+ * frame, or a pose track that carries an item along with the target. Keys a
+ * straight line between their neighbors already draws are dropped, so the
+ * doc holds the path's turns and nothing more.
+ *
+ * Everything here is pure geometry, so the page, a test, and any later
+ * surface agree on what a track means.
+ */
+
+import { evalOverlayFrame, type Mask, type MaskKey, type OverlayKey } from "@donkeycut/effects-kit";
+import { clipCovers, clipZoom, contentRect, frameOf, rectOf, type Aspect, type Overlay, type VideoClip } from "./types";
+
+export interface Pt {
+ x: number;
+ y: number;
+}
+
+/** One moment of a target: its outline, its center, and two points along
+ * its own axis, whose angle is the target's turn and whose length its size. */
+export interface TrackSample {
+ outline: Pt[];
+ center: Pt;
+ axis: [Pt, Pt];
+}
+
+export interface TrackTuning {
+ smoothCutoff: number;
+ smoothBeta: number;
+ bridgeSeconds: number;
+ keyTolerance: number;
+}
+
+/** The derivative's own smoothing cutoff, Hz — the one-euro default. */
+const DERIVATIVE_CUTOFF = 1;
+
+/** How much of the target's motion a follow carries. */
+export type FollowMode = "move" | "move_scale" | "move_scale_turn";
+export const FOLLOW_MODES: FollowMode[] = ["move", "move_scale", "move_scale_turn"];
+
+const flatten = (s: TrackSample): number[] => [
+ ...s.outline.flatMap((p) => [p.x, p.y]),
+ s.center.x,
+ s.center.y,
+ s.axis[0].x,
+ s.axis[0].y,
+ s.axis[1].x,
+ s.axis[1].y,
+];
+
+function unflatten(v: number[]): TrackSample {
+ const n = (v.length - 6) / 2;
+ const at = (i: number): Pt => ({ x: v[i * 2], y: v[i * 2 + 1] });
+ return {
+ outline: Array.from({ length: n }, (_, i) => at(i)),
+ center: at(n),
+ axis: [at(n + 1), at(n + 2)],
+ };
+}
+
+/**
+ * Bridge dropouts no longer than `bridgeSeconds` by blending the samples on
+ * either side, then smooth every coordinate along each unbroken run. `times`
+ * are timeline seconds, rising.
+ */
+export function settleTrack(times: number[], samples: (TrackSample | null)[], tune: TrackTuning): (TrackSample | null)[] {
+ const vecs = samples.map((s) => (s ? flatten(s) : null));
+
+ // A short dropout — a blur, a hand turning edge-on — is the target still
+ // there; a longer one is the target gone.
+ for (let i = 0; i < vecs.length; i++) {
+ if (vecs[i]) continue;
+ const before = i - 1;
+ let after = i;
+ while (after < vecs.length && !vecs[after]) after++;
+ const a = vecs[before];
+ const b = vecs[after];
+ if (a && b && a.length === b.length && times[after] - times[before] <= tune.bridgeSeconds + 1e-6) {
+ for (let k = i; k < after; k++) {
+ const p = (times[k] - times[before]) / (times[after] - times[before]);
+ vecs[k] = a.map((u, d) => u + (b[d] - u) * p);
+ }
+ }
+ i = after;
+ }
+
+ // One-euro per coordinate, restarting after every gap: a still target
+ // settles at the low cutoff, a moving one lifts it and keeps up.
+ let filters: OneEuro[] | null = null;
+ return vecs.map((v, i) => {
+ if (!v) {
+ filters = null;
+ return null;
+ }
+ filters ??= v.map(() => new OneEuro(tune.smoothCutoff, tune.smoothBeta));
+ return unflatten(v.map((u, d) => filters![d].next(u, times[i])));
+ });
+}
+
+/** The one-euro filter: an exponential smoother whose cutoff rises with the
+ * signal's speed, so jitter goes and fast moves keep their timing. */
+class OneEuro {
+ private value: number | null = null;
+ private slope = 0;
+ private at = 0;
+
+ constructor(
+ private readonly cutoff: number,
+ private readonly beta: number
+ ) {}
+
+ next(x: number, t: number): number {
+ if (this.value === null) {
+ this.value = x;
+ this.at = t;
+ return x;
+ }
+ const dt = t - this.at;
+ if (dt <= 0) return this.value;
+ const alpha = (hz: number) => 1 / (1 + 1 / (2 * Math.PI * hz * dt));
+ this.slope += alpha(DERIVATIVE_CUTOFF) * ((x - this.value) / dt - this.slope);
+ this.value += alpha(this.cutoff + this.beta * Math.abs(this.slope)) * (x - this.value);
+ this.at = t;
+ return this.value;
+ }
+}
+
+/**
+ * Where a point of a clip's source picture (0..1 across it) lands in the
+ * project frame (fractions of it), the way the compositor draws the clip:
+ * into its region, fitted or covering, zoomed, panned, and mirrored about the
+ * region's center. Pose keys and turns apply after masks, so they stay out.
+ */
+export function pictureToFrame(
+ clip: VideoClip,
+ picture: { width: number; height: number },
+ aspect: Aspect
+): (p: Pt) => Pt {
+ const fr = frameOf(aspect);
+ const r = rectOf(clip);
+ const box = { x: r.x * fr.w, y: r.y * fr.h, w: r.w * fr.w, h: r.h * fr.h };
+ const c = contentRect(box, picture.width, picture.height, clipCovers(clip), clipZoom(clip), clip.panX ?? 0, clip.panY ?? 0);
+ const midX = box.x + box.w / 2;
+ const midY = box.y + box.h / 2;
+ return (p) => {
+ let x = c.x + p.x * c.w;
+ let y = c.y + p.y * c.h;
+ if (clip.flipH) x = 2 * midX - x;
+ if (clip.flipV) y = 2 * midY - y;
+ return { x: x / fr.w, y: y / fr.h };
+ };
+}
+
+/** An item a track writes onto: a video clip or an overlay element. */
+export type TrackItem = { kind: "clip"; clip: VideoClip } | { kind: "overlay"; overlay: Overlay };
+
+const itemStart = (item: TrackItem) => (item.kind === "clip" ? item.clip.start : item.overlay.start);
+
+/**
+ * A frame point as an offset from the item's mask anchor, in the item's own
+ * unposed space at `tLocal`: a clip's masks sit before its pose, so its
+ * region center is the anchor; an element's mask paints under the element's
+ * transform, so the point is carried back through it.
+ */
+function toMaskSpace(item: TrackItem, aspect: Aspect, tLocal: number): (p: Pt) => Pt {
+ if (item.kind === "clip") {
+ const r = rectOf(item.clip);
+ const ax = r.x + r.w / 2;
+ const ay = r.y + r.h / 2;
+ return (p) => ({ x: p.x - ax, y: p.y - ay });
+ }
+ const o = item.overlay;
+ const fr = frameOf(aspect);
+ const ds = Math.min(fr.w, fr.h) / 1080;
+ const ev = evalOverlayFrame(o, tLocal);
+ const turn = (-ev.rotation * Math.PI) / 180;
+ const scale = Math.max(1e-6, ev.scale);
+ return (p) => {
+ const vx = p.x * fr.w - (ev.x * fr.w + ev.dx * ds);
+ const vy = p.y * fr.h - (ev.y * fr.h + ev.dy * ds);
+ const qx = (vx * Math.cos(turn) - vy * Math.sin(turn)) / scale;
+ const qy = (vx * Math.sin(turn) + vy * Math.cos(turn)) / scale;
+ return { x: qx / fr.w, y: qy / fr.h };
+ };
+}
+
+/**
+ * A pen mask that traces the target: one key per kept moment, each carrying
+ * the outline there. Where the target is gone the outline folds to a point at
+ * its last place, so the masked picture shows nothing until it returns.
+ * `times` are timeline seconds; `frame` holds the settled samples already
+ * placed in the project frame.
+ */
+export function trackedMask(
+ item: TrackItem,
+ aspect: Aspect,
+ times: number[],
+ frame: (TrackSample | null)[],
+ base: Pick<Mask, "feather" | "invert">,
+ tolerance: number
+): Mask | null {
+ const first = frame.find((s) => s !== null);
+ if (!first) return null;
+ const corners = first.outline.length;
+ let last = first.center;
+
+ // Each moment's outline in the item's mask space.
+ const outlines = frame.map((s, i) => {
+ const local = toMaskSpace(item, aspect, times[i] - itemStart(item));
+ if (s) last = s.center;
+ const pts = s ? s.outline : Array.from({ length: corners }, () => last);
+ return pts.map(local);
+ });
+ const kept = keepTurns(times, outlines.map((o) => o.flatMap((p) => [p.x, p.y])), tolerance);
+ const feather = base.feather ?? 0;
+ const kf: MaskKey[] = kept.map((i) => ({
+ t: round4(times[i] - itemStart(item)),
+ x: 0,
+ y: 0,
+ w: 1,
+ h: 1,
+ rotation: 0,
+ feather,
+ points: outlines[i].map((p) => ({ x: round4(p.x), y: round4(p.y) })),
+ }));
+ return {
+ kind: "pen",
+ x: 0,
+ y: 0,
+ w: 1,
+ h: 1,
+ rotation: 0,
+ ...(feather > 0 ? { feather } : {}),
+ ...(base.invert ? { invert: true } : {}),
+ points: kf[0].points,
+ kf,
+ };
+}
+
+/** Where an item rests before a follow moves it: its center in frame
+ * fractions, its scale, turn and opacity. */
+export interface RestPose {
+ x: number;
+ y: number;
+ scale: number;
+ rotation: number;
+ opacity: number;
+}
+
+/**
+ * Pose keys that carry an item with the target. The item keeps where it sits
+ * relative to the target at the first tracked moment — beside a head, over a
+ * hand — and from there moves with it; `move_scale` also grows and shrinks
+ * with the target's size, `move_scale_turn` also turns with it. Moments where
+ * the target is gone write no key, so the item holds.
+ */
+export function followKeys(
+ item: TrackItem,
+ aspect: Aspect,
+ times: number[],
+ frame: (TrackSample | null)[],
+ rest: RestPose,
+ mode: FollowMode,
+ tolerance: number
+): OverlayKey[] {
+ const fr = frameOf(aspect);
+ const px = (p: Pt) => ({ x: p.x * fr.w, y: p.y * fr.h });
+ const measure = (s: TrackSample) => {
+ const a = px(s.axis[0]);
+ const b = px(s.axis[1]);
+ return { c: px(s.center), size: Math.max(1e-6, Math.hypot(b.x - a.x, b.y - a.y)), angle: Math.atan2(b.y - a.y, b.x - a.x) };
+ };
+ const firstAt = frame.findIndex((s) => s !== null);
+ if (firstAt < 0) return [];
+ const ref = measure(frame[firstAt]!);
+ const offset = { x: rest.x * fr.w - ref.c.x, y: rest.y * fr.h - ref.c.y };
+
+ // The turn unwraps as it goes, so a key never spins the long way round.
+ let turn = 0;
+ let lastAngle = ref.angle;
+ const poses: { i: number; key: OverlayKey }[] = [];
+ frame.forEach((s, i) => {
+ if (!s) return;
+ const m = measure(s);
+ let step = m.angle - lastAngle;
+ step -= Math.round(step / (Math.PI * 2)) * Math.PI * 2;
+ turn += step;
+ lastAngle = m.angle;
+ const grow = mode === "move" ? 1 : m.size / ref.size;
+ const spin = mode === "move_scale_turn" ? turn : 0;
+ const ox = (offset.x * Math.cos(spin) - offset.y * Math.sin(spin)) * grow;
+ const oy = (offset.x * Math.sin(spin) + offset.y * Math.cos(spin)) * grow;
+ poses.push({
+ i,
+ key: {
+ t: round4(times[i] - itemStart(item)),
+ x: round4((m.c.x + ox) / fr.w),
+ y: round4((m.c.y + oy) / fr.h),
+ scale: round4(rest.scale * grow),
+ rotation: round2(wrapDegrees(rest.rotation + (spin * 180) / Math.PI)),
+ opacity: rest.opacity,
+ },
+ });
+ });
+
+ // Scale and turn weigh in at the tolerance's scale: a 0.3° turn or a 0.3%
+ // size change counts like a position move of the tolerance.
+ const kept = keepTurns(
+ poses.map((p) => times[p.i]),
+ poses.map((p) => [p.key.x, p.key.y, p.key.scale * 0.5, p.key.rotation / 200]),
+ tolerance
+ );
+ return kept.map((k) => poses[k].key);
+}
+
+/**
+ * The indices worth a key: a moment is dropped when the straight line
+ * between the kept moments around it passes within `tolerance` of every
+ * coordinate it had. The first and last always stay.
+ */
+export function keepTurns(times: number[], vecs: number[][], tolerance: number): number[] {
+ const n = vecs.length;
+ if (n <= 2) return vecs.map((_, i) => i);
+ const kept = [0];
+ let anchor = 0;
+ for (let j = 2; j < n; j++) {
+ if (!spans(times, vecs, anchor, j, tolerance)) {
+ kept.push(j - 1);
+ anchor = j - 1;
+ }
+ }
+ kept.push(n - 1);
+ return kept;
+}
+
+/** Whether the line from `a` to `b` stays within `tolerance` of every moment
+ * between them. */
+function spans(times: number[], vecs: number[][], a: number, b: number, tolerance: number): boolean {
+ const span = times[b] - times[a];
+ if (vecs[a].length !== vecs[b].length) return false;
+ for (let k = a + 1; k < b; k++) {
+ const p = span > 0 ? (times[k] - times[a]) / span : 0;
+ const v = vecs[k];
+ for (let d = 0; d < v.length; d++) {
+ if (Math.abs(vecs[a][d] + (vecs[b][d] - vecs[a][d]) * p - v[d]) > tolerance) return false;
+ }
+ }
+ return true;
+}
+
+const wrapDegrees = (deg: number) => ((((deg + 180) % 360) + 360) % 360) - 180;
+const round4 = (v: number) => Math.round(v * 1e4) / 1e4;
+const round2 = (v: number) => Math.round(v * 100) / 100;
diff --git a/site/src/cut/lib/trackMotion.ts b/site/src/cut/lib/trackMotion.ts
new file mode 100644
index 00000000..dfcf5ea1
--- /dev/null
+++ b/site/src/cut/lib/trackMotion.ts
@@ -0,0 +1,182 @@
+"use client";
+
+/**
+ * Track a target through a clip's footage and drive an item with it — the
+ * one path the chat's track_motion tool and the inspector's Track control
+ * both run.
+ *
+ * It picks the footage (the item itself, a named clip, or the clip under an
+ * element), samples the stretch the two share on the timeline's clock, reads
+ * it through the landmarkers (tracking.ts), settles and places the path
+ * (trackKeys.ts), and lands the result on the item as one undo step.
+ */
+
+import { MASK_FEATHER_MAX, poseAt, retimeOf } from "@donkeycut/effects-kit";
+import { cutTracking } from "./chatRuntime";
+import { clipLen, useEditor } from "./store";
+import { trackFootage } from "./tracking";
+import {
+ followKeys,
+ pictureToFrame,
+ settleTrack,
+ trackedMask,
+ type FollowMode,
+ type Pt,
+ type TrackItem,
+ type TrackSample,
+} from "./trackKeys";
+import { trackTargetOf, type TrackTarget, type TrackUse } from "./trackTargets";
+import { clipPoseAt, isEffectOverlay, type MediaAsset, type VideoClip } from "./types";
+
+/** The shortest stretch worth a track: a couple of frames. */
+const MIN_TRACK_SECONDS = 0.05;
+/** The most in-view stretches and path points a track reports. */
+const TRACK_SPANS_MAX = 12;
+const TRACK_PATH_POINTS = 24;
+
+/** A track that cannot run, in words for the person or the model. */
+export class TrackError extends Error {}
+
+export interface TrackRequest {
+ /** The item driven: a video clip or an overlay element. */
+ id: string;
+ target: TrackTarget;
+ use: TrackUse;
+ /** The video clip whose footage is read; see `trackMotion`. */
+ sourceId?: string;
+ /** Timeline seconds bounding the track. */
+ from?: number;
+ to?: number;
+ follow?: FollowMode;
+ feather?: number;
+ invert?: boolean;
+ /** Share of frames read so far, 0..1. */
+ onProgress?: (share: number) => void;
+}
+
+export async function trackMotion(req: TrackRequest) {
+ const s = useEditor.getState();
+ const o = s.overlays.find((x) => x.id === req.id);
+ const own = o ? undefined : s.clips.find((c) => c.id === req.id);
+ if (!o && !own) throw new TrackError("No overlay element or video clip with that id.");
+ if (o && req.use === "mask" && isEffectOverlay(o)) throw new TrackError("Effect elements have no pixels to mask.");
+
+ // The footage read: the named clip, the item itself, or the clip that
+ // most covers the element.
+ const span = o ? { start: o.start, end: o.end } : { start: own!.start, end: own!.start + clipLen(own!) };
+ const named = req.sourceId === undefined ? undefined : s.clips.find((c) => c.id === req.sourceId);
+ if (req.sourceId !== undefined && !named) throw new TrackError("No video clip with that source_id.");
+ const source = named ?? own ?? clipUnder(s.clips, s.assets, span);
+ if (!source) throw new TrackError("No video clip plays under that element — pass source_id.");
+ const asset = s.assets.find((a) => a.id === source.assetId);
+ const picture = asset?.type === "video" && asset.width && asset.height ? { width: asset.width, height: asset.height } : null;
+ if (!asset || !picture) throw new TrackError("The source clip has no video picture to track.");
+
+ // The stretch tracked: where the item and the source overlap, narrowed by
+ // from/to, sampled evenly on the timeline's clock.
+ const srcEnd = source.start + clipLen(source);
+ const a = Math.max(span.start, source.start, req.from ?? -Infinity);
+ const b = Math.min(span.end, srcEnd, req.to ?? Infinity);
+ if (b - a < MIN_TRACK_SECONDS)
+ throw new TrackError(`The item and the source clip share no stretch to track (${round2(source.start)}–${round2(srcEnd)}s holds the footage).`);
+ const tune = cutTracking();
+ const fps = Math.min(tune.sampleFps, tune.maxFrames / (b - a));
+ const n = Math.max(2, Math.floor((b - a) * fps) + 1);
+ const last = b - 1 / (2 * tune.sampleFps);
+ const times = Array.from({ length: n }, (_, k) => a + ((last - a) * k) / (n - 1));
+ const rt = retimeOf(source);
+ const srcTimes = times.map((t) => rt.srcAt(t - source.start));
+
+ // Read, settle, and place the path in the project frame.
+ const raw = await trackFootage(asset.url, picture, req.target, srcTimes, (done, total) => req.onProgress?.(done / total));
+ const settled = settleTrack(times, raw, tune);
+ const place = pictureToFrame(source, picture, s.aspect);
+ const framed = settled.map((x) =>
+ x ? { outline: x.outline.map(place), center: place(x.center), axis: [place(x.axis[0]), place(x.axis[1])] as [Pt, Pt] } : null
+ );
+ const found = framed.filter((x) => x !== null).length;
+ const summary = {
+ target: req.target,
+ source_id: source.id,
+ from: round2(a),
+ to: round2(b),
+ frames: n,
+ found_share: round2(found / n),
+ in_view: inViewSpans(times, framed),
+ };
+ if (req.use === "read") return { ...summary, path: trackPath(times, framed) };
+ const label = trackTargetOf(req.target).label.toLowerCase();
+ if (found === 0) throw new TrackError(`No ${label} found in the source between ${round2(a)}s and ${round2(b)}s.`);
+
+ // The item as it stands now: the read took a while, and the person may
+ // have moved it meanwhile.
+ const now = useEditor.getState();
+ const liveO = o && now.overlays.find((x) => x.id === o.id);
+ const liveClip = own && now.clips.find((c) => c.id === own.id);
+ if (!liveO && !liveClip) throw new TrackError("The item was deleted while it was being tracked.");
+ const item: TrackItem = liveO ? { kind: "overlay", overlay: liveO } : { kind: "clip", clip: liveClip! };
+
+ // A keyed pen mask that traces the target.
+ if (req.use === "mask") {
+ const feather = Math.max(0, Math.min(MASK_FEATHER_MAX, req.feather ?? 0));
+ const invert = req.invert === true;
+ const mask = trackedMask(item, now.aspect, times, framed, { feather, invert }, tune.keyTolerance)!;
+ if (liveO) now.updateOverlay(liveO.id, { mask });
+ else now.updateClip(liveClip!.id, { mask });
+ return { ...summary, id: req.id, mask: { kind: mask.kind, keys: mask.kf!.length, feather, invert } };
+ }
+
+ // Pose keys that carry the item with the target.
+ const follow = req.follow ?? "move_scale";
+ const rest = liveO ? poseAt(liveO, a - liveO.start) : clipPoseAt(liveClip!, a - liveClip!.start);
+ const kf = followKeys(item, now.aspect, times, framed, rest, follow, tune.keyTolerance);
+ if (liveO) now.updateOverlay(liveO.id, { kf });
+ else now.updateClip(liveClip!.id, { kf });
+ return { ...summary, id: req.id, follow_mode: follow, keys: kf.length };
+}
+
+/** The video clip that covers most of `span` — the footage under an element.
+ * A tie goes to the clip nearest track 0, the shot itself. */
+function clipUnder(clips: VideoClip[], assets: MediaAsset[], span: { start: number; end: number }): VideoClip | undefined {
+ const shared = (c: VideoClip) => Math.min(span.end, c.start + clipLen(c)) - Math.max(span.start, c.start);
+ const video = (c: VideoClip) => assets.find((x) => x.id === c.assetId)?.type === "video";
+ return clips
+ .filter((c) => !c.hidden && video(c) && shared(c) > 0)
+ .sort((p, q) => shared(q) - shared(p) || Math.abs(p.track ?? 0) - Math.abs(q.track ?? 0))[0];
+}
+
+/** The stretches, in timeline seconds, where the target was found. */
+function inViewSpans(times: number[], frame: (TrackSample | null)[]): { from: number; to: number }[] {
+ const spans: { from: number; to: number }[] = [];
+ frame.forEach((x, i) => {
+ if (!x) return;
+ const open = spans[spans.length - 1];
+ if (open && frame[i - 1]) open.to = round2(times[i]);
+ else spans.push({ from: round2(times[i]), to: round2(times[i]) });
+ });
+ return spans.slice(0, TRACK_SPANS_MAX);
+}
+
+/** Where the target goes, evenly sampled: its center and its outline's box,
+ * in frame fractions, at timeline seconds. */
+function trackPath(times: number[], frame: (TrackSample | null)[]) {
+ const step = Math.max(1, Math.ceil(frame.length / TRACK_PATH_POINTS));
+ const out: { t: number; x: number; y: number; w: number; h: number }[] = [];
+ for (let i = 0; i < frame.length; i += step) {
+ const x = frame[i];
+ if (!x) continue;
+ const xs = x.outline.map((p) => p.x);
+ const ys = x.outline.map((p) => p.y);
+ out.push({
+ t: round2(times[i]),
+ x: round3(x.center.x),
+ y: round3(x.center.y),
+ w: round3(Math.max(...xs) - Math.min(...xs)),
+ h: round3(Math.max(...ys) - Math.min(...ys)),
+ });
+ }
+ return out;
+}
+
+const round2 = (n: number) => Math.round(n * 100) / 100;
+const round3 = (n: number) => Math.round(n * 1000) / 1000;
diff --git a/site/src/cut/lib/trackTargets.ts b/site/src/cut/lib/trackTargets.ts
new file mode 100644
index 00000000..36d4bb57
--- /dev/null
+++ b/site/src/cut/lib/trackTargets.ts
@@ -0,0 +1,59 @@
+/**
+ * What motion tracking can follow, and what a track can drive. The chat
+ * tool's enums, its description and the inspector's picker all read these
+ * lists, so a new target reaches every surface at once.
+ */
+
+export type TrackTarget = "hands_gap" | "left_hand" | "right_hand" | "head" | "person";
+
+export const TRACK_TARGETS: {
+ id: TrackTarget;
+ label: string;
+ /** What the tracked outline covers, for the tool description. */
+ covers: string;
+ /** How far the outline grows past the landmarks, as a share of its own
+ * size: fingertips mark a window's corners exactly, while a hand, a head
+ * and a body reach past the joints the models place. */
+ pad: number;
+}[] = [
+ {
+ id: "hands_gap",
+ label: "Between hands",
+ covers: "the window both hands frame, its corners on the thumb and index fingertips; it closes to nothing as the fingers meet",
+ pad: 0,
+ },
+ {
+ id: "left_hand",
+ label: "Left hand",
+ covers: "the hand on the left of the picture",
+ pad: 0.25,
+ },
+ {
+ id: "right_hand",
+ label: "Right hand",
+ covers: "the hand on the right of the picture",
+ pad: 0.25,
+ },
+ {
+ id: "head",
+ label: "Head",
+ covers: "the face, forehead to chin, turning with the head",
+ pad: 0.12,
+ },
+ {
+ id: "person",
+ label: "Person",
+ covers: "the body the pose model finds, head to the lowest visible joint",
+ pad: 0.15,
+ },
+];
+
+export const TRACK_TARGET_IDS: TrackTarget[] = TRACK_TARGETS.map((t) => t.id);
+
+/** What a finished track drives: a keyed pen mask on the item, the item's
+ * own position, scale and turn, or nothing — a read of where the target is. */
+export type TrackUse = "mask" | "follow" | "read";
+
+export const TRACK_USES: TrackUse[] = ["mask", "follow", "read"];
+
+export const trackTargetOf = (id: TrackTarget) => TRACK_TARGETS.find((t) => t.id === id)!;
diff --git a/site/src/cut/lib/tracking.test.ts b/site/src/cut/lib/tracking.test.ts
new file mode 100644
index 00000000..4c19b13a
--- /dev/null
+++ b/site/src/cut/lib/tracking.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import { hullRing, sampleOf } from "./tracking";
+
+/** A hand of 21 landmarks with the wrist and the thumb and index tips placed;
+ * the rest sit on the wrist. */
+const hand = (wrist: number, thumb: [number, number], index: [number, number]) => {
+ const l = Array.from({ length: 21 }, () => ({ x: wrist, y: 0.6, z: 0, visibility: 1 }));
+ l[4] = { x: thumb[0], y: thumb[1], z: 0, visibility: 1 };
+ l[8] = { x: index[0], y: index[1], z: 0, visibility: 1 };
+ return l;
+};
+
+describe("the window between the hands", () => {
+ test("its corners are the four fingertips, the left index tip first", () => {
+ const left = hand(0.3, [0.35, 0.55], [0.35, 0.45]);
+ const right = hand(0.7, [0.65, 0.55], [0.65, 0.45]);
+ const s = sampleOf("hands_gap", [right, left], 1, null)!;
+ expect(s.outline[0]).toEqual({ x: 0.35, y: 0.45 });
+ expect(s.outline).toHaveLength(4);
+ expect(s.center.x).toBeCloseTo(0.5, 6);
+ });
+
+ test("needs both hands", () => {
+ expect(sampleOf("hands_gap", [hand(0.3, [0.35, 0.55], [0.35, 0.45])], 1, null)).toBeNull();
+ });
+});
+
+describe("hull rings", () => {
+ test("resample a hull to the same corner count at even angles", () => {
+ const pts = [
+ { x: 0, y: 0 },
+ { x: 1, y: 0 },
+ { x: 1, y: 1 },
+ { x: 0, y: 1 },
+ { x: 0.5, y: 0.5 },
+ ];
+ const ring = hullRing(pts, 0)!;
+ expect(ring).toHaveLength(24);
+ // The first corner points straight up from the middle, onto the top edge.
+ expect(ring[0].x).toBeCloseTo(0.5, 6);
+ expect(ring[0].y).toBeCloseTo(0, 6);
+ });
+});
diff --git a/site/src/cut/lib/tracking.ts b/site/src/cut/lib/tracking.ts
new file mode 100644
index 00000000..9a299c8f
--- /dev/null
+++ b/site/src/cut/lib/tracking.ts
@@ -0,0 +1,326 @@
+"use client";
+
+/**
+ * Motion tracking: MediaPipe's hand, face and pose landmarkers read a clip's
+ * footage frame by frame and report where a target sits in each one — its
+ * outline, its center, and an axis that carries its turn and size.
+ *
+ * The landmarkers run in VIDEO mode, so each frame seeds the next and a
+ * target is followed rather than re-found. Frames decode in source order
+ * whichever way the clip plays, which is the order the trackers expect. Every
+ * coordinate comes back in the source picture's own 0..1 space; placing it in
+ * the project frame is trackKeys.ts's job. The models are self-hosted and the
+ * task closes when the read ends.
+ */
+
+import type { FaceLandmarker, HandLandmarker, NormalizedLandmark, PoseLandmarker } from "@mediapipe/tasks-vision";
+import { cutTracking } from "./chatRuntime";
+import { framesAt } from "./mediaRead";
+import { visionFileset, withQuietWasmLogs } from "./mediapipe";
+import { trackTargetOf, type TrackTarget } from "./trackTargets";
+import type { Pt, TrackSample } from "./trackKeys";
+
+const HAND_MODEL = "/mediapipe/hand_landmarker.task";
+const FACE_MODEL = "/mediapipe/face_landmarker.task";
+const POSE_MODEL = "/mediapipe/pose_landmarker_full.task";
+
+/** Hand landmark indices (MediaPipe hand model). */
+const HAND = { wrist: 0, thumbTip: 4, indexMcp: 5, indexTip: 8, middleMcp: 9, ringMcp: 13, pinkyMcp: 17 };
+/** Face mesh indices for the outer eye corners: the head's roll and size. */
+const FACE = { rightEyeOuter: 33, leftEyeOuter: 263 };
+/** Pose landmark indices for the torso. */
+const POSE = { leftShoulder: 11, rightShoulder: 12, leftHip: 23, rightHip: 24 };
+
+/** Faces and bodies a frame may hold; the track keeps the one it started on. */
+const MAX_PEOPLE = 4;
+/** A pose landmark counts once the model is this sure it is in view. */
+const POSE_VISIBLE = 0.5;
+/** Corners in a hand or body outline: the hull, resampled around its center
+ * so every frame's outline has the same corners to blend between. */
+const RING_POINTS = 24;
+/** How far, in picture fractions, a target may move between two frames and
+ * still be the same one. */
+const SAME_TARGET = 0.25;
+
+type Landmarks = NormalizedLandmark[];
+type Detector = { detect: (frame: TexImageSource, ms: number) => Landmarks[]; close: () => void };
+
+/**
+ * Track `target` through `src` at the given source seconds. Returns one sample
+ * per time, in the order asked, null where the target was not found.
+ * `onFrame` reports progress as frames are read.
+ */
+export async function trackFootage(
+ src: string,
+ size: { width: number; height: number },
+ target: TrackTarget,
+ times: number[],
+ onFrame?: (done: number, total: number) => void
+): Promise<(TrackSample | null)[]> {
+ const settings = cutTracking();
+
+ // Decode at the configured long side, keeping the picture's own aspect.
+ const long = Math.max(size.width, size.height);
+ const k = Math.min(1, settings.longSide / Math.max(1, long));
+ const read = size.width >= size.height ? { width: Math.round(size.width * k) } : { height: Math.round(size.height * k) };
+
+ // Source order: one forward decode pass, and the order the tracker follows.
+ const order = times.map((_, i) => i).sort((a, b) => times[a] - times[b]);
+ const out: (TrackSample | null)[] = times.map(() => null);
+ const detector = await openDetector(target, settings.minConfidence);
+ let prev: Pt | null = null;
+ let seen = 0;
+ let clock = -1;
+ try {
+ for await (const frame of framesAt(src, order.map((i) => times[i]), read)) {
+ const i = order[seen];
+
+ // The tracker's clock is the source's, held strictly rising: a slowed
+ // clip reads the same source frame more than once.
+ const ms = Math.max(clock + 1, Math.round(times[i] * 1000));
+ clock = ms;
+ seen++;
+ onFrame?.(seen, times.length);
+ if (!frame) continue;
+ const w = frame.canvas.width;
+ const h = frame.canvas.height;
+ const found = detector.detect(frame.canvas as TexImageSource, ms);
+ const sample = sampleOf(target, found, w / h, prev);
+ out[i] = sample;
+ if (sample) prev = sample.center;
+ }
+ } finally {
+ detector.close();
+ }
+ return out;
+}
+
+/** One task per read, so VIDEO-mode state never carries from one clip into
+ * another, and its wasm memory goes back when the read ends. */
+async function openDetector(target: TrackTarget, confidence: number): Promise<Detector> {
+ const tasks = await import("@mediapipe/tasks-vision");
+ const fileset = await visionFileset();
+ const base = (modelAssetPath: string) => ({ baseOptions: { modelAssetPath }, runningMode: "VIDEO" as const });
+
+ // Hands: both, whatever the target, so a hand's side reads against the other.
+ if (target === "hands_gap" || target === "left_hand" || target === "right_hand") {
+ const task: HandLandmarker = await withQuietWasmLogs(() =>
+ tasks.HandLandmarker.createFromOptions(fileset, {
+ ...base(HAND_MODEL),
+ numHands: 2,
+ minHandDetectionConfidence: confidence,
+ minHandPresenceConfidence: confidence,
+ minTrackingConfidence: confidence,
+ })
+ );
+ return { detect: (f, ms) => task.detectForVideo(f, ms).landmarks, close: () => task.close() };
+ }
+
+ if (target === "head") {
+ if (ovalOrder.length === 0) ovalOrder = chainLoop(tasks.FaceLandmarker.FACE_LANDMARKS_FACE_OVAL);
+ const task: FaceLandmarker = await withQuietWasmLogs(() =>
+ tasks.FaceLandmarker.createFromOptions(fileset, {
+ ...base(FACE_MODEL),
+ numFaces: MAX_PEOPLE,
+ minFaceDetectionConfidence: confidence,
+ minFacePresenceConfidence: confidence,
+ minTrackingConfidence: confidence,
+ })
+ );
+ return { detect: (f, ms) => task.detectForVideo(f, ms).faceLandmarks, close: () => task.close() };
+ }
+
+ const task: PoseLandmarker = await withQuietWasmLogs(() =>
+ tasks.PoseLandmarker.createFromOptions(fileset, {
+ ...base(POSE_MODEL),
+ numPoses: MAX_PEOPLE,
+ minPoseDetectionConfidence: confidence,
+ minPosePresenceConfidence: confidence,
+ minTrackingConfidence: confidence,
+ })
+ );
+ return { detect: (f, ms) => task.detectForVideo(f, ms).landmarks, close: () => task.close() };
+}
+
+/** The target's sample in one frame's detections, or null when it is not
+ * there. `aspect` is the frame's width over height: hulls, angles and
+ * distances are measured in square pixels. `prev` is the target's center a
+ * frame earlier, which keeps the track on the same hand, face or body. */
+export function sampleOf(target: TrackTarget, found: Landmarks[], aspect: number, prev: Pt | null): TrackSample | null {
+ const pad = trackTargetOf(target).pad;
+ const sq = (p: Pt): Pt => ({ x: p.x * aspect, y: p.y });
+ const unsq = (p: Pt): Pt => ({ x: p.x / aspect, y: p.y });
+ const unsqAll = (s: TrackSample): TrackSample => ({
+ outline: s.outline.map(unsq),
+ center: unsq(s.center),
+ axis: [unsq(s.axis[0]), unsq(s.axis[1])],
+ });
+
+ // The window between two hands: the thumb and index tips of each, in
+ // order around their middle. The hand on the left of the picture is first.
+ if (target === "hands_gap") {
+ if (found.length < 2) return null;
+ const [a, b] = [...found].sort((p, q) => p[HAND.wrist].x - q[HAND.wrist].x).map((l) => l.map(sq));
+ const tips = [a[HAND.thumbTip], a[HAND.indexTip], b[HAND.thumbTip], b[HAND.indexTip]];
+ const center = mean(tips);
+
+ // Corners keep their identity frame to frame — the left index tip leads —
+ // so blending between frames moves each corner along its own path.
+ const ring = aroundCenter(tips, center);
+ const lead = ring.indexOf(a[HAND.indexTip]);
+ return unsqAll({
+ outline: [...ring.slice(lead), ...ring.slice(0, lead)],
+ center,
+ axis: [mean([a[HAND.thumbTip], a[HAND.indexTip]]), mean([b[HAND.thumbTip], b[HAND.indexTip]])],
+ });
+ }
+
+ if (target === "left_hand" || target === "right_hand") {
+ const hand = pickHand(found, target, prev);
+ if (!hand) return null;
+ const pts = hand.map(sq);
+ const center = mean([HAND.wrist, HAND.indexMcp, HAND.middleMcp, HAND.ringMcp, HAND.pinkyMcp].map((j) => pts[j]));
+ const outline = hullRing(pts, pad);
+ if (!outline) return null;
+ return unsqAll({ outline, center, axis: [pts[HAND.wrist], pts[HAND.middleMcp]] });
+ }
+
+ if (target === "head") {
+ const face = pickNearest(found, prev, (l) => mean(l));
+ if (!face) return null;
+ const pts = face.map(sq);
+ const oval = ovalOrder.map((j) => pts[j]);
+ const center = mean(oval);
+ return unsqAll({
+ outline: grow(oval, center, pad),
+ center,
+ axis: [pts[FACE.rightEyeOuter], pts[FACE.leftEyeOuter]],
+ });
+ }
+
+ // A body: the hull of the joints the model can see, around the torso.
+ const torsoOf = (l: Landmarks) => {
+ const torso = [POSE.leftShoulder, POSE.rightShoulder, POSE.leftHip, POSE.rightHip].map((j) => l[j]).filter((p) => (p.visibility ?? 0) >= POSE_VISIBLE);
+ return torso.length > 0 ? mean(torso) : mean(l);
+ };
+ const body = pickNearest(found, prev, torsoOf);
+ if (!body) return null;
+ const visible = body.filter((p) => (p.visibility ?? 0) >= POSE_VISIBLE).map(sq);
+ const outline = hullRing(visible, pad);
+ if (!outline) return null;
+ const pts = body.map(sq);
+ return unsqAll({
+ outline,
+ center: sq(torsoOf(body)),
+ axis: [pts[POSE.rightShoulder], pts[POSE.leftShoulder]],
+ });
+}
+
+/** The hand on the asked-for side of the picture. With both in view, side
+ * decides; with one, it stays the tracked hand while it is near where that
+ * hand was, and otherwise counts when it sits on that half of the picture. */
+function pickHand(found: Landmarks[], side: "left_hand" | "right_hand", prev: Pt | null): Landmarks | null {
+ if (found.length === 0) return null;
+ const left = side === "left_hand";
+ if (found.length >= 2) {
+ const sorted = [...found].sort((p, q) => p[HAND.wrist].x - q[HAND.wrist].x);
+ return left ? sorted[0] : sorted[sorted.length - 1];
+ }
+ const only = found[0];
+ const at = only[HAND.middleMcp];
+ if (prev) return dist(at, prev) <= SAME_TARGET ? only : null;
+ return (at.x < 0.5) === left ? only : null;
+}
+
+/** The detection nearest where the target was; the largest when the track
+ * has no history. Null when every detection is too far to be the same one. */
+function pickNearest(found: Landmarks[], prev: Pt | null, centerOf: (l: Landmarks) => Pt): Landmarks | null {
+ if (found.length === 0) return null;
+ if (!prev) {
+ const spread = (l: Landmarks) => {
+ const xs = l.map((p) => p.x);
+ const ys = l.map((p) => p.y);
+ return (Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys));
+ };
+ return found.reduce((best, l) => (spread(l) > spread(best) ? l : best));
+ }
+ const best = found.reduce((a, l) => (dist(centerOf(l), prev) < dist(centerOf(a), prev) ? l : a));
+ return dist(centerOf(best), prev) <= SAME_TARGET ? best : null;
+}
+
+let ovalOrder: number[] = [];
+
+/** The face mesh's oval as one loop of landmark indices, chained from the
+ * model's own connection list. */
+function chainLoop(edges: { start: number; end: number }[]): number[] {
+ const next = new Map(edges.map((e) => [e.start, e.end]));
+ const loop = [edges[0].start];
+ for (let at = next.get(loop[0]); at !== undefined && at !== loop[0]; at = next.get(at)) loop.push(at);
+ return loop;
+}
+
+const mean = (pts: Pt[]): Pt => ({
+ x: pts.reduce((s, p) => s + p.x, 0) / pts.length,
+ y: pts.reduce((s, p) => s + p.y, 0) / pts.length,
+});
+
+const dist = (a: Pt, b: Pt) => Math.hypot(a.x - b.x, a.y - b.y);
+
+/** Points in order around `c`, starting from the top. */
+function aroundCenter(pts: Pt[], c: Pt): Pt[] {
+ const angle = (p: Pt) => (Math.atan2(p.y - c.y, p.x - c.x) + Math.PI * 2.5) % (Math.PI * 2);
+ return [...pts].sort((a, b) => angle(a) - angle(b));
+}
+
+/** Points pushed out from `c` by `pad` of their distance. */
+const grow = (pts: Pt[], c: Pt, pad: number): Pt[] =>
+ pts.map((p) => ({ x: c.x + (p.x - c.x) * (1 + pad), y: c.y + (p.y - c.y) * (1 + pad) }));
+
+/** The convex hull of `pts`, grown by `pad` and resampled to RING_POINTS
+ * corners at even angles around its middle, so outlines from different
+ * frames line up corner for corner. Null for fewer than three points. */
+export function hullRing(pts: Pt[], pad: number): Pt[] | null {
+ const hull = convexHull(pts);
+ if (hull.length < 3) return null;
+ const c = mean(hull);
+ const ring: Pt[] = [];
+ for (let k = 0; k < RING_POINTS; k++) {
+ const theta = (k / RING_POINTS) * Math.PI * 2 - Math.PI / 2;
+ const d = { x: Math.cos(theta), y: Math.sin(theta) };
+ let reach = 0;
+ for (let i = 0; i < hull.length; i++) {
+ const a = hull[i];
+ const b = hull[(i + 1) % hull.length];
+ const e = { x: b.x - a.x, y: b.y - a.y };
+ const w = { x: a.x - c.x, y: a.y - c.y };
+ const denom = cross(d, e);
+ if (Math.abs(denom) < 1e-12) continue;
+ const t = cross(w, e) / denom;
+ const s = cross(w, d) / denom;
+ if (t >= 0 && s >= -1e-9 && s <= 1 + 1e-9) reach = Math.max(reach, t);
+ }
+ ring.push({ x: c.x + d.x * reach, y: c.y + d.y * reach });
+ }
+ return grow(ring, c, pad);
+}
+
+const cross = (u: Pt, v: Pt) => u.x * v.y - u.y * v.x;
+
+/** Andrew's monotone chain, counter-clockwise without repeats. */
+function convexHull(input: Pt[]): Pt[] {
+ const pts = [...input].sort((a, b) => a.x - b.x || a.y - b.y);
+ if (pts.length < 3) return pts;
+ const turn = (o: Pt, a: Pt, b: Pt) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
+ const lower: Pt[] = [];
+ for (const p of pts) {
+ while (lower.length >= 2 && turn(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
+ lower.push(p);
+ }
+ const upper: Pt[] = [];
+ for (let i = pts.length - 1; i >= 0; i--) {
+ const p = pts[i];
+ while (upper.length >= 2 && turn(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
+ upper.push(p);
+ }
+ return [...lower.slice(0, -1), ...upper.slice(0, -1)];
+}
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 5ddc4199..16a2ddee 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -392,11 +392,11 @@ Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em),
Animation (set_overlay_animation): every element takes preset In/Out ramps (${OVERLAY_ANIM_STYLE_IDS.join(", ")} — ${TEXT_ONLY_ANIM_STYLE_IDS.join(", ")} for titles only; the per-letter styles sweep a title character by character; ${DIVE_ANIM_STYLE_IDS.join(", ")} flies into the last letter until its ink fills the frame, the built-in zoom-through transition), a Loop (${OVERLAY_LOOP_STYLE_IDS.join(", ")}) that runs its whole duration, and a Move that says what it does WHILE it holds. A title takes one more: Words (${WORD_EFFECT_IDS.join(", ")}), which plays the line word by word — an emphasis travelling along a line that is fully up, or a build assembling the line as it is spoken. A typewriter entrance takes a caret (caret, caret_blink, caret_blinks, caret_hide), the blinking bar of a typed comment or search box. Every element takes a Hit (${OVERLAY_HIT_STYLE_IDS.join(", ")}) at hit_at seconds inside it: press is a finger tapping a button — the Post or Like button of a call-to-action card — and a click from stock_search kind "sound" placed at the same moment makes it heard. Entrances 0.3–0.6s read well; one loop per scene, sparingly; a move on the lines that matter. All of them are slots on the element, applied internally, and they compose over its keyframe track. A slot is the reach when the motion is per-letter or per-word — typewriter, the glyph sweeps, the word effects — which one pose track cannot express; what the whole element does is keyed.
Keyframes (set_overlay_keyframes): for motion no preset covers — a path across the frame, a slow push in, a drift that holds first. A key is a whole pose (position, scale, rotation, opacity, blur) at a time in seconds from the element's start; the pose moves between keys along each key's ease (sine.inOut, power2/power3 in/out, default linear) and holds outside them, and presets still compose on top. This is the default way to animate an element: a key names the exact pose at the exact second, where a named ramp only approximates it. Two or three keys carry almost everything. In the UI the diamond in the inspector adds a key at the playhead, and dragging the element then records into it. set_clip_keyframes is the same track on a video clip (any track): pans, push-ins, picture-in-picture flights, spins, and fades on the footage itself.
Camera over a board of cards (set_group_camera): lay the cards out across the frame, group them, and key one camera that steps from card to card, pushes onto the one being talked about, pulls back, or whips — the cards keep their own keys inside it. Depth of field is the neighbours' own keys: blur and dim them at the moments the camera pushes in. motion_blur on the camera (or on an element, through update_overlay) streaks fast moves and leaves still frames sharp.
-Masks (set_mask): trim any element or video clip to a shape — ${MASK_SHAPE_KINDS.join(", ")} — with feather, invert, rounded corners on a box, and its own keyframe track for reveals and wipes. The pen kind takes an outline as points, for any region the fixed shapes miss: the gap framed between two hands, a doorway, a screen — read the region's corners off a captured frame in frame fractions, and stack a masked copy of the shot (a filter, a title) so it shows through only there. The subject kind trims by the person in the shot (on-device segmentation; preview and export match): inverted sits the item behind the speaker, plain keeps it only on the speaker. Behind-speaker reads well when the speaker is clearly separated from the background; with no detectable person it degrades to the plain picture. Group and Ungroup are in the timeline toolbar (⌘/Ctrl+G and ⇧⌘/Ctrl+G).
+Masks (set_mask): trim any element or video clip to a shape — ${MASK_SHAPE_KINDS.join(", ")} — with feather, invert, rounded corners on a box, and its own keyframe track for reveals and wipes. The pen kind takes an outline as points, for any region the fixed shapes miss: a doorway, a screen — read the region's corners off a captured frame in frame fractions, and stack a masked copy of the shot (a filter, a title) so it shows through only there. A region that moves with a hand, the window between the hands, a head or a person is track_motion's: use "mask" keys a pen outline onto it on every frame, one item for the whole span; use "follow" carries an element along with it. The subject kind trims by the person in the shot (on-device segmentation; preview and export match): inverted sits the item behind the speaker, plain keeps it only on the speaker. Behind-speaker reads well when the speaker is clearly separated from the background; with no detectable person it degrades to the plain picture. Group and Ungroup are in the timeline toolbar (⌘/Ctrl+G and ⇧⌘/Ctrl+G).
Composite builds: these primitives compose. Stacked overlay video copies, masks and their keys, pose keyframes, staggered starts, and shapes construct effects beyond any preset list. Given a reference (a screenshot or clip of an effect the user wants), reverse-engineer it:
1. Read the reference as layers. For each visible piece, decide what it is: live footage, a cropped or repeated slice of the footage, a solid graphic, text, or empty background.
2. Map each layer to a primitive. A slice of the picture = a copy of the same asset on its own overlay track (add_overlay_video, layout full, matching trim so every copy's picture lines up with the base) trimmed by a mask whose x/y offsets place it — a full-frame copy under a mask shows the true part of the picture at that spot, so masked copies tile back into the whole image. Gap lines and borders come from sizing masks under their spacing (track 0 left empty plays black through the gaps) or from stroked shapes. Solid panels are shapes; words are titles.
-3. Map the timing. Pieces arriving one after another = staggered start times. Geometry that moves or grows = mask keys; opacity keys fade a piece in place. Pose keyframes and entrance presets (zoom, slide) move the picture UNDER the mask, sliding the slice out of register — save them for pieces where that motion is the point, and reveal aligned tiles with starts, mask keys, and opacity alone.
+3. Map the timing. Pieces arriving one after another = staggered start times. Geometry that moves or grows = mask keys; geometry that follows something in the shot = track_motion; opacity keys fade a piece in place. Pose keyframes and entrance presets (zoom, slide) move the picture UNDER the mask, sliding the slice out of register — save them for pieces where that motion is the point, and reveal aligned tiles with starts, mask keys, and opacity alone.
4. Work out the geometry as numbers before calling any tool. Any screen region converts to mask parameters by plain arithmetic: w and h are fractions of frame width and height — rect takes both, so it expresses any region on any aspect; a square's side rides frame width alone, and a shape meant to hold exact pixel proportions folds in project.frame's pixels — and x/y are the region's center measured from the item's own center. Write every piece's region and timing as numbers, check that together they lay out what the reference shows (coverage, spacing, alignment), then place them.
5. Build one representative piece and capture_frame it against the reference. Then build the rest and capture_frame again, mid-reveal and at the end: every cell present, slices aligned into the whole picture, the target region covered edge to edge. Fix what's off at the right level: a wrong number re-sets in place (set_mask and the keyframe tools overwrite), a mistimed copy retimes, and a wrong cell plan means deleting the copies you added (delete_item) and laying them again from the corrected list — the pieces you placed are yours to tear down. The build is done when the captured frame matches the reference.
All of it is regular timeline editing: free, live, and undoable.
diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.ts
index 075990c0..af66fd13 100644
--- a/site/src/cut/server/ai/headlessTools.ts
+++ b/site/src/cut/server/ai/headlessTools.ts
@@ -1,7 +1,7 @@
import { parseFolderLink } from "@/cut/lib/folderReference";
import { copyFile } from "node:fs/promises";
import { UI_TOOLS } from "@/cut/lib/projectCommands";
-import { runProjectCommand } from "../../lib/aiTools";
+import { PAGE_ONLY_TOOLS, runProjectCommand } from "../../lib/aiTools";
import { projectOperation } from "../../lib/projectOperation";
import { localBackend } from "../../lib/backend/local";
import { DETACHED_MEDIA_ERROR, DETACHED_SESSION_ERROR, DETACHED_UI_NOTE } from "../../lib/chatResume";
@@ -45,6 +45,7 @@ const PAGE_MEDIA_TOOLS: ReadonlySet<string> = new Set([
"captions_generate",
"subtitles_from_visuals",
"stock_add",
+ ...PAGE_ONLY_TOOLS,
]);
const PAGE_SESSION_TOOLS: ReadonlySet<string> = new Set([
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index f7667b2f..970145e1 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -292,6 +292,43 @@ export const SETTINGS = defineSettings({
description:
"How a talk or an interview is read for the moments worth cutting a short from: what a clip may run, how widely the first sweep looks, how many moments earn the close read, and what the ranking weighs.",
},
+ cutTracking: {
+ schema: z
+ .object({
+ // Tracked frames per second of the span, and the most frames one
+ // track reads; a longer span samples more sparsely.
+ sampleFps: z.number().int().min(5).max(60),
+ maxFrames: z.number().int().min(60).max(3600),
+ // The decoded frame's long side the landmarkers read.
+ longSide: z.number().int().min(320).max(1920),
+ // Detection, presence and tracking confidence floors.
+ minConfidence: z.number().min(0.1).max(0.95),
+ // One-euro smoothing: the cutoff (Hz) a still target settles at, and
+ // how fast the cutoff rises with speed.
+ smoothCutoff: z.number().min(0.1).max(30),
+ smoothBeta: z.number().min(0).max(200),
+ // A dropout this short is bridged; a longer one hides the shape.
+ bridgeSeconds: z.number().min(0).max(2),
+ // How far, in frame fractions, a dropped key may sit from the line
+ // its neighbors draw.
+ keyTolerance: z.number().min(0).max(0.02),
+ })
+ .strict(),
+ default: {
+ sampleFps: 30,
+ maxFrames: 1200,
+ longSide: 1280,
+ minConfidence: 0.5,
+ smoothCutoff: 1.5,
+ smoothBeta: 20,
+ bridgeSeconds: 0.25,
+ keyTolerance: 0.0015,
+ },
+ public: true,
+ title: "Motion tracking",
+ description:
+ "How hands, heads and people are tracked through a clip: frames read per second, the frame size and confidence the landmarkers use, how hard the path is smoothed, and how closely the written keys follow it.",
+ },
cutNotes: {
schema: z.object({ autosaveMs: z.number().int().min(200).max(10000) }).strict(),
default: { autosaveMs: 800 },