Skip to content

Open source CapCut alternative.

TypeScript

feat(site): masks and clip pose keyframes in the editor [rebuild]

David Le5f4f42ade040
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 2b1dfc71..da2bc5c3 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -22,11 +22,16 @@ import {
import { Textarea } from "@/components/ui/textarea";
import {
EFFECT_LABELS,
+ hasMaskKeys,
hasOverlayKeys,
KEY_EPSILON,
keyIndexAt,
lineLikeShape,
+ maskFrameAt,
poseAt,
+ type Mask,
+ type MaskKey,
+ type MaskKind,
type OverlayKey,
OVERLAY_ANIM_DEFAULT_SECONDS,
OVERLAY_ANIM_MAX_SECONDS,
@@ -39,6 +44,7 @@ import {
type OverlayLoopStyle,
} from "@donkeycut/effects-kit";
import { clipWindow, useEditor, type EditorState } from "@/cut/lib/store";
+import { clipKeyed, clipPoseAt } from "@/cut/lib/types";
import { AnimationTiles } from "@/cut/components/AnimationTiles";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
import {
@@ -603,6 +609,8 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
rect={rectOf(clip)}
onPick={(frame, fit) => updateClip(clip.id, { frame, fit })}
/>
+ <ClipTransformSection clip={clip} />
+ <ClipMaskSection clip={clip} />
<ClipGeneratedAudio clip={clip} />
</div>
</>
@@ -1507,12 +1515,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
</Row>
</>
</Section>
- <Section
- title="Behind speaker"
- info="Sit the text behind the person in the shot. Needs a clearly separated subject; with no person detected it shows as a normal title."
- enabled={!!o.behindSubject}
- onEnabledChange={(v) => update(o.id, { behindSubject: v || undefined })}
- />
+ <OverlayMaskSection overlay={o} />
<TransformRows overlay={o} />
<GroupRow overlay={o} />
<AnimationRows overlay={o} />
@@ -1935,7 +1938,7 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
}
/** Seconds into the element at the playhead, clamped to its own window. */
-function localTimeOf(o: Overlay, now: number): number {
+function localTimeOf(o: { start: number; end: number }, now: number): number {
return Math.max(0, Math.min(now - o.start, Math.max(0.1, o.end - o.start)));
}
@@ -1949,13 +1952,44 @@ function localTimeOf(o: Overlay, now: number): number {
function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
const now = useEditor((s) => s.currentTime);
const seek = useEditor((s) => s.seek);
- const keys = o.kf ?? [];
- const inWindow = now >= o.start - 1e-6 && now <= o.end + 1e-6;
- const tLocal = localTimeOf(o, now);
- const here = keyIndexAt(keys, tLocal);
- const prev = [...keys].reverse().find((k) => k.t < tLocal - KEY_EPSILON);
- const next = keys.find((k) => k.t > tLocal + KEY_EPSILON);
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}
+ />
+ );
+}
+
+/** The key track row itself — diamond, walkers, count, bin — over whichever
+ * key list it is handed. The pose track and the mask track both mount it. */
+function KeyRow({
+ element,
+ now,
+ keys,
+ onAdd,
+ onRemove,
+ onSeek,
+}: {
+ element: { start: number; end: number };
+ now: number;
+ keys: { t: number }[];
+ onAdd: (tLocal: number) => void;
+ onRemove: (tLocal: number) => void;
+ onSeek: (t: number) => void;
+}) {
+ const inWindow = now >= element.start - 1e-6 && now <= element.end + 1e-6;
+ const tLocal = Math.max(
+ 0,
+ Math.min(now - element.start, Math.max(0.1, element.end - element.start))
+ );
+ const here = keyIndexAt(keys, tLocal);
+ const prev = [...keys].sort((a, b) => a.t - b.t).reverse().find((k) => k.t < tLocal - KEY_EPSILON);
+ const next = [...keys].sort((a, b) => a.t - b.t).find((k) => k.t > tLocal + KEY_EPSILON);
return (
<Row label="Keyframes">
<Button
@@ -1965,7 +1999,7 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
disabled={!inWindow}
title={here >= 0 ? "Update the key here" : "Add a key at the playhead"}
aria-label={here >= 0 ? "Update the key here" : "Add a key at the playhead"}
- onClick={() => st().setOverlayKey(o.id, tLocal)}
+ onClick={() => onAdd(tLocal)}
>
<Diamond className={cn("size-3.5", here >= 0 && "fill-current")} />
</Button>
@@ -1976,7 +2010,7 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
disabled={!prev}
title="Previous key"
aria-label="Previous key"
- onClick={() => prev && seek(o.start + prev.t)}
+ onClick={() => prev && onSeek(element.start + prev.t)}
>
<ChevronLeft className="size-3.5" />
</Button>
@@ -1987,7 +2021,7 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
disabled={!next}
title="Next key"
aria-label="Next key"
- onClick={() => next && seek(o.start + next.t)}
+ onClick={() => next && onSeek(element.start + next.t)}
>
<ChevronRight className="size-3.5" />
</Button>
@@ -2001,7 +2035,7 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
disabled={here < 0}
title="Remove the key here"
aria-label="Remove the key here"
- onClick={() => st().removeOverlayKey(o.id, tLocal)}
+ onClick={() => onRemove(tLocal)}
>
<Trash2 className="size-3.5" />
</Button>
@@ -2009,6 +2043,366 @@ function KeyframeControls({ overlay: o }: { overlay: Overlay }) {
);
}
+const MASK_SHAPES: { id: MaskKind; label: string }[] = [
+ { id: "rect", label: "Rectangle" },
+ { id: "circle", label: "Circle" },
+ { id: "linear", label: "Linear" },
+ { id: "mirror", label: "Mirror" },
+ { id: "subject", label: "Subject" },
+];
+
+/** How a panel's mask section reads and writes its owner's mask — the same
+ * section serves overlay elements and video clips through this. */
+interface MaskTarget {
+ /** Timeline window for the keyframe row and playhead-local time. */
+ element: { start: number; end: number };
+ mask?: Mask;
+ /** Replace the mask outright (or remove it), as one undo step. */
+ set: (mask: Mask | undefined) => void;
+ /** Live-drag mask update, no undo entry. */
+ setTransient: (mask: Mask) => void;
+ setKey: (
+ tLocal: number,
+ patch?: Partial<Omit<MaskKey, "t">>,
+ opts?: { transient?: boolean }
+ ) => void;
+ removeKey: (tLocal: number) => void;
+}
+
+/**
+ * A video clip's pose track: the keyframe row plus, once keys exist, the
+ * position/scale/rotation/opacity rows editing the key at the playhead — the
+ * element Transform contract over the clip's anchor. A clip with no keys
+ * rests in its region, so the rows appear with the first key.
+ */
+function ClipTransformSection({ clip }: { clip: VideoClip }) {
+ const clips = useEditor((s) => s.clips);
+ const assets = useEditor((s) => s.assets);
+ const now = useEditor((s) => s.currentTime);
+ const seek = useEditor((s) => s.seek);
+ const posCk = useSliderCheckpoint();
+ const scaleCk = useSliderCheckpoint();
+ const rotationCk = useSliderCheckpoint();
+ const opacityCk = useSliderCheckpoint();
+ const st = () => useEditor.getState();
+ const win = clipWindow(clips, assets, clip.id);
+ if (!win) return null;
+ const el = { start: win.start, end: win.start + win.len };
+ const tLocal = localTimeOf(el, now);
+ const keyed = clipKeyed(clip);
+ const pose = clipPoseAt(clip, tLocal);
+ const setKey = (patch: Partial<Omit<OverlayKey, "t">>) =>
+ st().setClipKey(clip.id, tLocal, patch, { transient: true });
+ return (
+ <Section title="Transform">
+ <KeyRow
+ element={el}
+ now={now}
+ keys={clip.kf ?? []}
+ onAdd={(t) => st().setClipKey(clip.id, t)}
+ onRemove={(t) => st().removeClipKey(clip.id, t)}
+ onSeek={seek}
+ />
+ {keyed && (
+ <>
+ <Row label="Position">
+ {(["x", "y"] as const).map((axis) => (
+ <span key={axis} className="flex items-center gap-1">
+ <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
+ <ScrubValue
+ label={`${axis.toUpperCase()} position`}
+ className="w-9 text-muted-foreground"
+ value={pose[axis] * 100}
+ min={-50}
+ max={150}
+ step={0.5}
+ keyStep={1}
+ format={(v) => String(Math.round(v))}
+ parse={parseNumberInput}
+ onScrub={(v) => {
+ posCk.begin();
+ setKey({ [axis]: v / 100 });
+ }}
+ onCommit={(v) => {
+ posCk.begin();
+ setKey({ [axis]: v / 100 });
+ posCk.end();
+ }}
+ />
+ </span>
+ ))}
+ </Row>
+ <Row label="Scale">
+ <Slider
+ className="data-horizontal:w-24"
+ min={0.1}
+ max={4}
+ step={0.01}
+ value={pose.scale}
+ onValueChange={(v) => {
+ scaleCk.begin();
+ setKey({ scale: Number(v) });
+ }}
+ onValueCommitted={scaleCk.end}
+ />
+ <Value className="w-9 text-muted-foreground">{Math.round(pose.scale * 100)}%</Value>
+ </Row>
+ <Row label="Rotation">
+ <Slider
+ className="data-horizontal:w-24"
+ min={-180}
+ max={180}
+ step={1}
+ value={pose.rotation}
+ onValueChange={(v) => {
+ rotationCk.begin();
+ setKey({ rotation: Math.round(Number(v)) });
+ }}
+ onValueCommitted={rotationCk.end}
+ />
+ <Value className="w-9 text-muted-foreground">{Math.round(pose.rotation)}°</Value>
+ </Row>
+ <Row label="Opacity">
+ <Slider
+ className="data-horizontal:w-24"
+ min={0}
+ max={1}
+ step={0.01}
+ value={pose.opacity}
+ onValueChange={(v) => {
+ opacityCk.begin();
+ setKey({ opacity: Number(v) });
+ }}
+ onValueCommitted={opacityCk.end}
+ />
+ <Value className="w-9 text-muted-foreground">{Math.round(pose.opacity * 100)}</Value>
+ </Row>
+ </>
+ )}
+ </Section>
+ );
+}
+
+/** The overlay inspector's mask target, over the overlay store actions. */
+function OverlayMaskSection({ overlay: o }: { overlay: Overlay }) {
+ const st = () => useEditor.getState();
+ return (
+ <MaskSection
+ target={{
+ element: o,
+ mask: o.mask,
+ set: (mask) => st().updateOverlay(o.id, { mask }),
+ setTransient: (mask) => st().updateOverlayTransient(o.id, { mask }),
+ setKey: (t, patch, opts) => st().setOverlayMaskKey(o.id, t, patch, opts),
+ removeKey: (t) => st().removeOverlayMaskKey(o.id, t),
+ }}
+ />
+ );
+}
+
+/** The clip inspector's mask target, over the clip store actions. The clip's
+ * timeline window comes through `clipWindow` (track-0 starts derive from the
+ * span layout). */
+function ClipMaskSection({ clip }: { clip: VideoClip }) {
+ const clips = useEditor((s) => s.clips);
+ const assets = useEditor((s) => s.assets);
+ const st = () => useEditor.getState();
+ const win = clipWindow(clips, assets, clip.id);
+ if (!win) return null;
+ return (
+ <MaskSection
+ target={{
+ element: { start: win.start, end: win.start + win.len },
+ mask: clip.mask,
+ set: (mask) => st().updateClip(clip.id, { mask }),
+ setTransient: (mask) => st().updateClipTransient(clip.id, { mask }),
+ setKey: (t, patch, opts) => st().setClipMaskKey(clip.id, t, patch, opts),
+ removeKey: (t) => st().removeClipMaskKey(clip.id, t),
+ }}
+ />
+ );
+}
+
+/**
+ * The mask itself: shape picker, its own keyframe track, and the geometry
+ * rows. With mask keys in play the rows edit the key at the playhead, the
+ * same contract as Transform; otherwise they edit the mask's resting fields.
+ */
+function MaskSection({ target }: { target: MaskTarget }) {
+ const now = useEditor((s) => s.currentTime);
+ const seek = useEditor((s) => s.seek);
+ const posCk = useSliderCheckpoint();
+ const sizeCk = useSliderCheckpoint();
+ const rotationCk = useSliderCheckpoint();
+ const featherCk = useSliderCheckpoint();
+ const radiusCk = useSliderCheckpoint();
+ const m = target.mask;
+ const tLocal = localTimeOf(target.element, now);
+ const geom = m ? maskFrameAt(m, tLocal) : null;
+ const writeGeom = (patch: Partial<Omit<MaskKey, "t">>) => {
+ if (!m) return;
+ if (hasMaskKeys(m)) return target.setKey(tLocal, patch, { transient: true });
+ target.setTransient({ ...m, ...patch });
+ };
+ const showW = m?.kind === "rect" || m?.kind === "circle";
+ const showH = showW || m?.kind === "mirror";
+ const subject = m?.kind === "subject";
+ return (
+ <Section
+ title="Mask"
+ info="Trim the picture to a shape, or to the person in the shot (Subject). Feather softens the edge, and invert keeps what the shape leaves out — an inverted Subject mask sits the picture behind the speaker."
+ enabled={!!m}
+ onEnabledChange={(v) => target.set(v ? { kind: "rect" } : undefined)}
+ >
+ {m && geom && (
+ <>
+ <Row label="Shape">
+ <Select
+ value={m.kind}
+ onValueChange={(kind) => target.set({ ...m, kind: kind as MaskKind })}
+ >
+ <SelectTrigger className="h-8 w-36 text-[12px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MASK_SHAPES.map((s) => (
+ <SelectItem key={s.id} value={s.id} className="text-[12px]">
+ {s.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Row>
+ {!subject && (
+ <KeyRow
+ element={target.element}
+ now={now}
+ keys={m.kf ?? []}
+ onAdd={(t) => target.setKey(t)}
+ onRemove={(t) => target.removeKey(t)}
+ onSeek={seek}
+ />
+ )}
+ {!subject && (
+ <Row label="Position">
+ {(["x", "y"] as const).map((axis) => (
+ <span key={axis} className="flex items-center gap-1">
+ <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
+ <ScrubValue
+ label={`Mask ${axis.toUpperCase()} offset`}
+ className="w-9 text-muted-foreground"
+ value={geom[axis] * 100}
+ min={-100}
+ max={100}
+ step={0.5}
+ keyStep={1}
+ format={(v) => String(Math.round(v))}
+ parse={parseNumberInput}
+ onScrub={(v) => {
+ posCk.begin();
+ writeGeom({ [axis]: v / 100 });
+ }}
+ onCommit={(v) => {
+ posCk.begin();
+ writeGeom({ [axis]: v / 100 });
+ posCk.end();
+ }}
+ />
+ </span>
+ ))}
+ </Row>
+ )}
+ {showH && (
+ <Row label="Size">
+ {(showW ? (["w", "h"] as const) : (["h"] as const)).map((axis) => (
+ <span key={axis} className="flex items-center gap-1">
+ <span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
+ <ScrubValue
+ label={`Mask ${axis === "w" ? "width" : "height"}`}
+ className="w-9 text-muted-foreground"
+ value={geom[axis] * 100}
+ min={1}
+ max={200}
+ step={1}
+ format={(v) => String(Math.round(v))}
+ parse={parseNumberInput}
+ onScrub={(v) => {
+ sizeCk.begin();
+ writeGeom({ [axis]: v / 100 });
+ }}
+ onCommit={(v) => {
+ sizeCk.begin();
+ writeGeom({ [axis]: v / 100 });
+ sizeCk.end();
+ }}
+ />
+ </span>
+ ))}
+ </Row>
+ )}
+ {!subject && (
+ <Row label="Rotation">
+ <Slider
+ className="data-horizontal:w-24"
+ min={-180}
+ max={180}
+ step={1}
+ value={geom.rotation}
+ onValueChange={(v) => {
+ rotationCk.begin();
+ writeGeom({ rotation: Math.round(Number(v)) });
+ }}
+ onValueCommitted={rotationCk.end}
+ />
+ <Value className="w-9 text-muted-foreground">{Math.round(geom.rotation)}°</Value>
+ </Row>
+ )}
+ <Row label="Feather">
+ <Slider
+ className="data-horizontal:w-24"
+ min={0}
+ max={120}
+ step={1}
+ value={geom.feather}
+ onValueChange={(v) => {
+ featherCk.begin();
+ writeGeom({ feather: Math.round(Number(v)) });
+ }}
+ onValueCommitted={featherCk.end}
+ />
+ <Value className="w-9 text-muted-foreground">{Math.round(geom.feather)}</Value>
+ </Row>
+ {m.kind === "rect" && (
+ <Row label="Radius">
+ <Slider
+ className="data-horizontal:w-24"
+ min={0}
+ max={200}
+ step={1}
+ value={m.radius ?? 0}
+ onValueChange={(v) => {
+ radiusCk.begin();
+ const radius = Math.round(Number(v));
+ target.setTransient({ ...m, radius: radius === 0 ? undefined : radius });
+ }}
+ onValueCommitted={radiusCk.end}
+ />
+ <Value className="w-9 text-muted-foreground">{m.radius ?? 0}</Value>
+ </Row>
+ )}
+ <Row label="Invert">
+ <Switch
+ checked={!!m.invert}
+ onCheckedChange={(v) => target.set({ ...m, invert: v || undefined })}
+ aria-label="Invert mask"
+ />
+ </Row>
+ </>
+ )}
+ </Section>
+ );
+}
+
function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
const update = useEditor((s) => s.updateOverlay);
const fillCk = useSliderCheckpoint();
@@ -2110,6 +2504,7 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
)}
</Section>
)}
+ <OverlayMaskSection overlay={o} />
<TransformRows overlay={o} />
<GroupRow overlay={o} />
<AnimationRows overlay={o} />
@@ -2326,6 +2721,7 @@ function StickerPanel({ overlay: o }: { overlay: StickerOverlay }) {
/>
<Value className="w-9 text-muted-foreground">{Math.round(o.w * 100)}</Value>
</Row>
+ <OverlayMaskSection overlay={o} />
<TransformRows overlay={o} />
<GroupRow overlay={o} />
<AnimationRows overlay={o} />
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index fa9a6edf..a92c8232 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -14,7 +14,7 @@ import {
subtitleLaneCount,
trackPos,
} from "@/cut/lib/subtitles";
-import { evalOverlayFrame, hasOverlayKeys, isOverlayAnimated, lineLikeShape, resolveShadow, shapeMetrics, shapePathD, type LottieHandle } from "@donkeycut/effects-kit";
+import { evalOverlayFrame, hasMaskKeys, hasOverlayKeys, isOverlayAnimated, lineLikeShape, maskFrameAt, paintMaskCoverage, resolveShadow, shapeMetrics, shapePathD, type LottieHandle, type MaskKey } from "@donkeycut/effects-kit";
import {
LINE_HEIGHT,
PLATE_PAD_X,
@@ -24,6 +24,7 @@ import {
SHADOW,
} from "@/cut/lib/textRender";
import {
+ behindSubjectOverlay,
clampOverlayPos,
frameOf,
fontStack,
@@ -34,6 +35,7 @@ import {
type ShapeOverlay,
type StickerOverlay,
} from "@/cut/lib/types";
+import { subjectMatteSnapshot } from "@/cut/lib/behindPass";
import { cn } from "@/lib/utils";
// Plate geometry as CSS, kept in lockstep with the export burn-in metrics.
@@ -489,18 +491,27 @@ function OverlayItem({
: isText
? o.text
: "";
- // Behind-speaker titles draw inside the canvas compositor; the DOM keeps an
- // invisible hit target (and the selection chrome) so editing still works.
- const behindHidden = isText && !!o.behindSubject && !editing;
+ // Behind-the-speaker elements draw inside the canvas compositor; the DOM
+ // keeps an invisible hit target (and the selection chrome) so editing
+ // still works.
+ const behindHidden = behindSubjectOverlay(o) && !editing;
- // Every kind shares position, rotation, and opacity; text carries its type
- // styles on the same box so the edit caret inherits them.
+ const tLocal = Math.max(0, t - o.start);
+ // The mask clips the content wrapper only, never the box itself — the
+ // selection chrome and the mask's own grips must stay visible outside it.
+ const maskCss = useMaskCss(o, boxRef, stageWidth, stageHeight, scale, tLocal, editing);
+
+ // The box carries position, rotation, and opacity; the content wrapper
+ // inside it carries a title's type styles (the edit caret inherits them)
+ // and the mask.
const style: CSSProperties = {
// A keyframed element is placed by its pose, not by its resting x/y.
left: `${(live?.x ?? o.x) * 100}%`,
top: `${(live?.y ?? o.y) * 100}%`,
transform: `translate(-50%, -50%)${animTransform}`,
opacity: (live ? live.opacity : (o.opacity ?? 1)) * (ghost ? 0.35 : 1),
+ };
+ const contentStyle: CSSProperties = {
...(isText
? (() => {
const shadow = resolveShadow(o.shadow);
@@ -526,12 +537,13 @@ function OverlayItem({
: undefined,
// A behind-speaker title paints on the canvas; the DOM box keeps
// its footprint but no visible plate.
- background: o.plate && !(o.behindSubject && !editing) ? plateFill(o) : undefined,
+ background: o.plate && !behindHidden ? plateFill(o) : undefined,
padding: o.plate ? PLATE_PADDING : undefined,
borderRadius: o.plate ? `${o.plateRadius ?? PLATE_RADIUS}em` : undefined,
};
})()
: {}),
+ ...(maskCss ?? {}),
};
const commitText = () => {
@@ -741,34 +753,36 @@ function OverlayItem({
}}
onDoubleClick={isText ? () => setEditing(true) : undefined}
>
- {behindHidden ? (
- <span className="opacity-0">{shownText}</span>
- ) : isText ? (
- editing ? (
- <div
- ref={editRef}
- className="min-w-2 outline-none select-text"
- contentEditable
- suppressContentEditableWarning
- onBlur={commitText}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- e.preventDefault();
- commitText();
- }
- e.stopPropagation();
- }}
- >
- {o.text}
- </div>
- ) : (
- <span>{shownText}</span>
- )
- ) : o.kind === "shape" ? (
- <ShapeView shape={o} stageWidth={stageWidth} stageHeight={stageHeight} scale={scale} />
- ) : o.kind === "sticker" ? (
- <StickerView sticker={o} stageWidth={stageWidth} t={t} />
- ) : null}
+ <div style={contentStyle}>
+ {behindHidden ? (
+ <span className="opacity-0">{shownText}</span>
+ ) : isText ? (
+ editing ? (
+ <div
+ ref={editRef}
+ className="min-w-2 outline-none select-text"
+ contentEditable
+ suppressContentEditableWarning
+ onBlur={commitText}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ commitText();
+ }
+ e.stopPropagation();
+ }}
+ >
+ {o.text}
+ </div>
+ ) : (
+ <span>{shownText}</span>
+ )
+ ) : o.kind === "shape" ? (
+ <ShapeView shape={o} stageWidth={stageWidth} stageHeight={stageHeight} scale={scale} />
+ ) : o.kind === "sticker" ? (
+ <StickerView sticker={o} stageWidth={stageWidth} t={t} />
+ ) : null}
+ </div>
{selected && !editing && (
<>
{/* The grab zone is wider than the dot, so the rotate cursor shows
@@ -789,12 +803,272 @@ function OverlayItem({
className="overlay-resize absolute -right-2 -bottom-2 size-[13px] cursor-nwse-resize rounded-full border-[2.5px] border-[#0a84ff] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.4)]"
onPointerDown={resizeFrom}
/>
+ {o.mask && o.mask.kind !== "subject" && (
+ <MaskGizmo
+ overlay={o}
+ stageWidth={stageWidth}
+ stageHeight={stageHeight}
+ tLocal={tLocal}
+ rotation={live?.rotation ?? o.rotation ?? 0}
+ poseScale={live?.scale ?? 1}
+ />
+ )}
</>
)}
</div>
);
}
+/**
+ * The element's mask as CSS: the kit painter draws its coverage on a small
+ * box-sized canvas, and the data URL becomes the content's mask-image. The
+ * mask lives in the element's own space — the box's CSS transform carries it
+ * through pose, rotation and scale — so it clips exactly where the exported
+ * raster clips. Regenerated when the geometry, the box, or (keyed) the
+ * playhead moves; disabled while the text is being edited.
+ */
+/** A keyed mask's CSS repaints on the matte cadence — enough for a soft
+ * moving edge, a quarter of the per-frame PNG encodes. */
+const MASK_CSS_FPS = 15;
+/** The mask canvas's size cap; the CSS mask stretches it over the box, so a
+ * big element pays a small encode. */
+const MASK_CSS_MAX = 512;
+/** Empty coverage: hides the element while a computed matte has no person. */
+const NO_COVERAGE_MASK = "linear-gradient(transparent, transparent)";
+
+function useMaskCss(
+ o: Overlay,
+ boxRef: React.RefObject<HTMLDivElement | null>,
+ stageWidth: number,
+ stageHeight: number,
+ scale: number,
+ tLocal: number,
+ disabled: boolean
+): CSSProperties | undefined {
+ const m = o.mask;
+ // A behind (inverted subject) element renders in the canvas pass; the DOM
+ // masks shapes and front subject elements.
+ const subjectFront = !!m && m.kind === "subject" && !m.invert;
+ const active = !!m && (m.kind !== "subject" || subjectFront) && !disabled;
+ const keyed = !!m && hasMaskKeys(m);
+ // The published matte refreshes at the segmentation cadence; its stamp is
+ // the memo key, so the CSS mask follows the person as the video plays.
+ const snap = subjectFront && active ? subjectMatteSnapshot() : null;
+ // The repaint keys: a keyed mask ticks at the matte cadence, and the
+ // subject branch follows the published matte's stamp.
+ const keyTick = keyed ? Math.round(tLocal * MASK_CSS_FPS) : 0;
+ const snapTick = subjectFront ? (snap?.at ?? -1) : 0;
+ // One canvas per element, reused across repaints.
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const [box, setBox] = useState<{ w: number; h: number } | null>(null);
+ useEffect(() => {
+ if (!active) return;
+ const el = boxRef.current;
+ if (!el) return;
+ const measure = () => setBox({ w: el.offsetWidth, h: el.offsetHeight });
+ measure();
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [active, boxRef]);
+ return useMemo(() => {
+ if (!active || !m || !box || box.w < 1 || box.h < 1) return undefined;
+ const canvas = (canvasRef.current ??= document.createElement("canvas"));
+ if (subjectFront) {
+ // Trim to the person: the published matte becomes the element's
+ // mask-image, positioned so it stays anchored to the frame while the
+ // element sits inside it. A computed matte with no person is empty
+ // coverage (the element hides, like every renderer); before the first
+ // matte lands the element stays whole.
+ if (!snap) return undefined;
+ if (!snap.canvas) {
+ return {
+ maskImage: NO_COVERAGE_MASK,
+ WebkitMaskImage: NO_COVERAGE_MASK,
+ };
+ }
+ if (canvas.width !== snap.canvas.width) canvas.width = snap.canvas.width;
+ if (canvas.height !== snap.canvas.height) canvas.height = snap.canvas.height;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return undefined;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = "source-over";
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ const featherMatte =
+ (m.feather ?? 0) * scale * (snap.canvas.width / Math.max(1, stageWidth));
+ if (featherMatte > 0 && "filter" in ctx) ctx.filter = `blur(${featherMatte / 2}px)`;
+ ctx.drawImage(snap.canvas, 0, 0);
+ ctx.filter = "none";
+ const url = canvas.toDataURL();
+ const boxLeft = o.x * stageWidth - box.w / 2;
+ const boxTop = o.y * stageHeight - box.h / 2;
+ return {
+ maskImage: `url(${url})`,
+ WebkitMaskImage: `url(${url})`,
+ maskRepeat: "no-repeat",
+ WebkitMaskRepeat: "no-repeat",
+ maskSize: `${stageWidth}px ${stageHeight}px`,
+ WebkitMaskSize: `${stageWidth}px ${stageHeight}px`,
+ maskPosition: `${-boxLeft}px ${-boxTop}px`,
+ WebkitMaskPosition: `${-boxLeft}px ${-boxTop}px`,
+ };
+ }
+ // The canvas caps below the box size and the CSS mask stretches it back:
+ // the soft coverage survives the scale and the PNG encode stays small.
+ const s = Math.min(1, MASK_CSS_MAX / Math.max(box.w, box.h));
+ const cw = Math.max(1, Math.round(box.w * s));
+ const ch = Math.max(1, Math.round(box.h * s));
+ if (canvas.width !== cw) canvas.width = cw;
+ if (canvas.height !== ch) canvas.height = ch;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return undefined;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = "source-over";
+ ctx.clearRect(0, 0, cw, ch);
+ if (m.invert) {
+ // Keep-outside: full coverage with the shape cut out of it, because a
+ // CSS mask has no invert of its own.
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(0, 0, cw, ch);
+ ctx.globalCompositeOperation = "destination-out";
+ }
+ // Map frame coordinates onto the box: the element's anchor sits at the
+ // box center, which is where the painter anchors the mask.
+ ctx.scale(s, s);
+ ctx.translate(box.w / 2 - o.x * stageWidth, box.h / 2 - o.y * stageHeight);
+ paintMaskCoverage(
+ ctx,
+ { ...m, invert: undefined },
+ tLocal,
+ { width: stageWidth, height: stageHeight, scale },
+ { x: o.x, y: o.y }
+ );
+ const url = canvas.toDataURL();
+ return {
+ maskImage: `url(${url})`,
+ WebkitMaskImage: `url(${url})`,
+ maskRepeat: "no-repeat",
+ WebkitMaskRepeat: "no-repeat",
+ maskSize: "100% 100%",
+ WebkitMaskSize: "100% 100%",
+ };
+ // The keyed tick folds a 15fps-quantized tLocal in only when the mask
+ // actually animates; the matte stamp refreshes the subject branch.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [active, m, box, o.x, o.y, stageWidth, stageHeight, scale, keyTick, snapTick]);
+}
+
+/** Handle styling shared by the mask gizmo's grips: amber, so mask handles
+ * never read as the element's own blue chrome. */
+const MASK_GRIP =
+ "absolute z-10 rounded-full border-[2.5px] border-[#ff9f0a] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.4)]";
+
+/**
+ * On-canvas mask editing: a center grip that moves the mask and a corner grip
+ * that resizes it (the band height, for mirror). The grips are children of
+ * the element box, so they ride its transform; screen deltas are folded back
+ * through the element's live rotation and scale, then through the mask's own
+ * angle for the resize. With mask keys in play a drag writes the key at the
+ * playhead, the same contract as dragging a keyframed element.
+ */
+function MaskGizmo({
+ overlay: o,
+ stageWidth,
+ stageHeight,
+ tLocal,
+ rotation,
+ poseScale,
+}: {
+ overlay: Overlay;
+ stageWidth: number;
+ stageHeight: number;
+ tLocal: number;
+ rotation: number;
+ poseScale: number;
+}) {
+ const m = o.mask!;
+ const f = maskFrameAt(m, tLocal);
+ const st = () => useEditor.getState();
+ const writeGeom = (patch: Partial<Omit<MaskKey, "t">>) => {
+ const cur = st().overlays.find((x) => x.id === o.id)?.mask;
+ if (!cur) return;
+ if (hasMaskKeys(cur)) return st().setOverlayMaskKey(o.id, tLocal, patch, { transient: true });
+ st().updateOverlayTransient(o.id, { mask: { ...cur, ...patch } });
+ };
+ // Screen deltas → the box's local space (undo the element transform).
+ const toLocal = (dx: number, dy: number) => {
+ const r = (-rotation * Math.PI) / 180;
+ const s = poseScale || 1;
+ return {
+ x: (dx * Math.cos(r) - dy * Math.sin(r)) / s,
+ y: (dx * Math.sin(r) + dy * Math.cos(r)) / s,
+ };
+ };
+ const theta = (f.rotation * Math.PI) / 180;
+ const sizable = m.kind === "rect" || m.kind === "circle" || m.kind === "mirror";
+ // The resize grip sits on the mask's corner (mirror: its lower edge),
+ // turned by the mask's own angle.
+ const gx = m.kind === "mirror" ? 0 : (f.w * stageWidth) / 2;
+ const gy = (f.h * stageHeight) / 2;
+ const rx = gx * Math.cos(theta) - gy * Math.sin(theta);
+ const ry = gx * Math.sin(theta) + gy * Math.cos(theta);
+ const clampSize = (v: number) => Math.min(2, Math.max(0.01, v));
+ return (
+ <>
+ <span
+ title="Drag to move the mask"
+ className={cn(MASK_GRIP, "size-[13px] cursor-move")}
+ style={{
+ left: `calc(50% + ${f.x * stageWidth}px)`,
+ top: `calc(50% + ${f.y * stageHeight}px)`,
+ transform: "translate(-50%, -50%)",
+ }}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ st().pushHistory();
+ const g0 = f;
+ startDrag(e, {
+ onMove: (dx, dy) => {
+ const l = toLocal(dx, dy);
+ writeGeom({ x: g0.x + l.x / stageWidth, y: g0.y + l.y / stageHeight });
+ },
+ });
+ }}
+ />
+ {sizable && (
+ <span
+ title="Drag to resize the mask"
+ className={cn(MASK_GRIP, "size-[11px] cursor-nwse-resize rounded-[3px]")}
+ style={{
+ left: `calc(50% + ${f.x * stageWidth + rx}px)`,
+ top: `calc(50% + ${f.y * stageHeight + ry}px)`,
+ transform: "translate(-50%, -50%)",
+ }}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ st().pushHistory();
+ const g0 = f;
+ startDrag(e, {
+ onMove: (dx, dy) => {
+ const l = toLocal(dx, dy);
+ // Into the mask's own axes for width/height growth.
+ const mx = l.x * Math.cos(theta) + l.y * Math.sin(theta);
+ const my = -l.x * Math.sin(theta) + l.y * Math.cos(theta);
+ writeGeom({
+ ...(m.kind !== "mirror"
+ ? { w: clampSize(g0.w + (2 * mx) / stageWidth) }
+ : {}),
+ h: clampSize(g0.h + (2 * my) / stageHeight),
+ });
+ },
+ });
+ }}
+ />
+ )}
+ </>
+ );
+}
+
/** A shape drawn as inline SVG with the painter's own pixel geometry
* (`shapeMetrics` in stage space), so preview and export burn-in match. */
function ShapeView({
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index d07a8b89..823b1280 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -3137,6 +3137,18 @@ function ClipView({
</DropdownMenuItem>
) : null}
</ClipMenu>
+ {/* Keys sit on the bar where they fall, so a pose track is visible
+ without opening the inspector. */}
+ {(clip.kf ?? []).map((k) => (
+ <KeyMarker
+ key={k.t}
+ item={{ id: clip.id, start: span.start, end: span.start + span.len }}
+ kind="clip"
+ t={k.t}
+ pps={pps}
+ width={w}
+ />
+ ))}
<span
className={cn(trimHandle, "tl-trim-l left-0")}
onPointerDown={(e) => startLaneTrim(e, "clip", clip.id, "l", ui)}
@@ -3846,6 +3858,17 @@ function OverlayClipView({
className="bottom-1 right-2"
onToggle={() => useEditor.getState().updateClip(clip.id, { hidden: !clip.hidden })}
/>
+ {/* Keys sit on the bar where they fall, same as the element bars. */}
+ {(clip.kf ?? []).map((k) => (
+ <KeyMarker
+ key={k.t}
+ item={{ id: clip.id, start: clip.start, end: clip.start + overlayLen(clip) }}
+ kind="clip"
+ t={k.t}
+ pps={pps}
+ width={w}
+ />
+ ))}
<span
className={cn(trimHandle, "tl-trim-l left-0")}
onPointerDown={(e) => startLaneTrim(e, "overlayClip", clip.id, "l", ui)}
@@ -3863,27 +3886,35 @@ function OverlayClipView({
const KEY_HIT = 14;
/**
- * One keyframe on an element's bar: a diamond where the key falls, dragged
- * left and right to retime it. The grab is kept off the bar underneath, so
- * moving a key never moves the element it belongs to.
+ * One keyframe on an item's bar — an element's or a video clip's: a diamond
+ * where the key falls, dragged left and right to retime it. The grab is kept
+ * off the bar underneath, so moving a key never moves the item it belongs
+ * to. `kind` picks which store track the actions write.
*/
function KeyMarker({
- overlay: o,
+ item,
+ kind,
t,
pps,
width,
onMenu,
}: {
- overlay: Overlay;
+ item: { id: string; start: number; end: number };
+ kind: "overlay" | "clip";
t: number;
pps: number;
width: number;
/** The bar's right-click menu; a key click carries its time, so the menu
- * offers to remove it. */
- onMenu: (m: { x: number; y: number; id: string; key?: number }) => void;
+ * offers to remove it. Absent (clip bars), the bar's own menu handles the
+ * click and Delete removes the picked key. */
+ onMenu?: (m: { x: number; y: number; id: string; key?: number }) => void;
}) {
const picked = useEditor(
- (s) => !!s.selectedKey && s.selectedKey.overlayId === o.id && s.selectedKey.t === t
+ (s) =>
+ !!s.selectedKey &&
+ s.selectedKey.kind === kind &&
+ s.selectedKey.id === item.id &&
+ s.selectedKey.t === t
);
// Park clear of the trim handles: a key dragged to the very end would
// otherwise sit under one and stop being grabbable. Those last few pixels
@@ -3897,14 +3928,19 @@ function KeyMarker({
transform: "translate(-50%, -50%)",
}}
title="Drag to retime, Delete to remove"
- onContextMenu={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onMenu({ x: e.clientX, y: e.clientY, id: o.id, key: t });
- }}
+ onContextMenu={
+ onMenu
+ ? (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onMenu({ x: e.clientX, y: e.clientY, id: item.id, key: t });
+ }
+ : undefined
+ }
onPointerDown={(e) => {
const s = useEditor.getState();
- s.selectOverlayKey(o.id, t);
+ if (kind === "overlay") s.selectOverlayKey(item.id, t);
+ else s.selectClipKey(item.id, t);
let live = t;
// The undo step opens on the first movement, so a click that only
// seeks does not leave one behind.
@@ -3916,13 +3952,14 @@ function KeyMarker({
s.pushHistory();
}
const next = Math.max(0, t + dx / pps);
- s.moveOverlayKey(o.id, live, next, { transient: true });
- live = Math.max(0, Math.min(next, Math.max(0.1, o.end - o.start)));
+ if (kind === "overlay") s.moveOverlayKey(item.id, live, next, { transient: true });
+ else s.moveClipKey(item.id, live, next, { transient: true });
+ live = Math.max(0, Math.min(next, Math.max(0.1, item.end - item.start)));
},
// A click that never moved reads as "show me this key": the playhead
// goes there, and the inspector's rows follow it.
onUp: (_dx, _dy, moved) => {
- if (!moved) s.seek(o.start + live);
+ if (!moved) s.seek(item.start + live);
},
});
}}
@@ -4055,7 +4092,7 @@ function TextBar({
{/* Keys sit on the bar where they fall, so a track is visible without
opening the inspector. */}
{(o.kf ?? []).map((k) => (
- <KeyMarker key={k.t} overlay={o} t={k.t} pps={pps} width={w} onMenu={onMenu} />
+ <KeyMarker key={k.t} item={o} kind="overlay" t={k.t} pps={pps} width={w} onMenu={onMenu} />
))}
<HideChip
hidden={!!o.hidden}
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index b07988c9..75946acd 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -4,7 +4,7 @@ import { useEffect, type RefObject } from "react";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } from "@/cut/lib/store";
import { isFullRect, projectFadeSeconds, rectOf } from "@/cut/lib/types";
import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
-import { BehindCompositor } from "@/cut/lib/behindPass";
+import { SubjectMaskCompositor } from "@/cut/lib/behindPass";
import { FrameCompositor, MISSING_FRAME, PENDING_FRAME, type Frame } from "@/cut/lib/composite";
import { duckGainAt, overlayPlan, prerollLead, trackZeroPlan } from "@/cut/lib/framePlan";
import { reportMediaElementError } from "@/cut/lib/mediaLinks";
@@ -520,13 +520,18 @@ class Engine {
return this.elFor(this.overlayEls, clip.id, asset);
}
- // Text-behind-speaker: behind-tagged titles leave the DOM overlay path and
- // composite here — video, then the text raster, then the segmented person
- // back on top (see behindPass.ts). Cheap no-op when nothing is tagged.
- private behind = new BehindCompositor();
+ // The subject-mask pass: behind-tagged elements leave the DOM overlay path
+ // and composite here — video, then the element raster, then the segmented
+ // person back on top — and the pass publishes the matte the DOM's front
+ // subject-masked elements read (see behindPass.ts). Cheap no-op when
+ // nothing reads the matte. Subject-masked video clips pull their matte
+ // mid-stack through the compositor's provider, reading the canvas as it
+ // stands beneath them.
+ private behind = new SubjectMaskCompositor(true);
private drawBehind(t: number) {
const s = useEditor.getState();
+ this.comp.subjectMatteProvider = (at) => this.behind.clipMatteOf(this.canvas, at);
this.behind.draw(this.canvas, s.overlays, s.assets, t);
}
diff --git a/site/src/cut/lib/behindPass.ts b/site/src/cut/lib/behindPass.ts
index d0cfcea2..019ff349 100644
--- a/site/src/cut/lib/behindPass.ts
+++ b/site/src/cut/lib/behindPass.ts
@@ -1,49 +1,90 @@
"use client";
/**
- * The text-behind-speaker pass, shared by the live preview and the in-tab
- * export: with the video layers already on the canvas, snapshot them, draw
- * the behind-tagged title rasters, then segment the snapshot and draw the
- * person back on top. When no person registers the text simply stays on top —
- * the effect degrades to a normal front title instead of hiding words.
+ * The subject-mask pass, shared by the live preview and the in-tab export.
+ * The person matte drives two things: elements behind the speaker (with the
+ * video layers already on the canvas, snapshot them, draw the behind-tagged
+ * rasters, then segment the snapshot and draw the person back on top) and
+ * elements or clips trimmed to the speaker. When no person registers the
+ * behind effect degrades to the plain picture.
*/
-import { evalOverlayFrame } from "@donkeycut/effects-kit";
+import { evalOverlayFrame, maskComposite } from "@donkeycut/effects-kit";
import { personSegmenter, segmentSubjectAlpha } from "./cutout";
import { renderElementPng } from "./textRender";
-import { isTextOverlay, type MediaAsset, type Overlay, type TextOverlay } from "./types";
+import {
+ behindSubjectOverlay,
+ frontSubjectOverlay,
+ isEffectOverlay,
+ isTextOverlay,
+ subjectMasked,
+ type MediaAsset,
+ type Overlay,
+} from "./types";
type Segmenter = import("@mediapipe/tasks-vision").ImageSegmenter;
/** Segmentation input width — small on purpose; this runs per frame. */
const SEG_WIDTH = 256;
-/** The behind-tagged titles live at `t`. */
-export function behindOverlaysAt(overlays: Overlay[], t: number): TextOverlay[] {
+/** Whether the element has pixels the pass could draw at all. */
+function drawable(o: Overlay): boolean {
+ if (o.hidden || isEffectOverlay(o)) return false;
+ if (isTextOverlay(o) && !o.text.trim()) return false;
+ return true;
+}
+
+/** The behind-the-speaker elements live at `t` (any drawable kind). */
+export function behindOverlaysAt(overlays: Overlay[], t: number): Overlay[] {
return overlays.filter(
- (o): o is TextOverlay =>
- isTextOverlay(o) &&
- !!o.behindSubject &&
- !o.hidden &&
- !!o.text.trim() &&
- t >= o.start &&
- t <= o.end
+ (o) => behindSubjectOverlay(o) && drawable(o) && t >= o.start && t <= o.end
);
}
-/** Whether any element in the document wants the behind pass at all. */
+/** Whether any element in the document sits behind the speaker. */
export function hasBehindOverlays(overlays: Overlay[]): boolean {
- return overlays.some((o) => isTextOverlay(o) && !!o.behindSubject && !o.hidden);
+ return overlays.some((o) => behindSubjectOverlay(o) && drawable(o));
+}
+
+/** Whether anything in the document reads the person matte at all. */
+export function hasSubjectOverlays(overlays: Overlay[]): boolean {
+ return overlays.some((o) => subjectMasked(o) && drawable(o));
+}
+
+/** One computed matte frame: `alpha` holds the person's silhouette, and null
+ * means the frame was segmented and no person registered — coverage is
+ * empty, so a front subject layer shows nothing and a behind layer shows
+ * whole. A compositor hands out null (no frame at all) only while the
+ * segmenter is still loading. */
+export interface SubjectMatte {
+ alpha: HTMLCanvasElement | null;
}
-export class BehindCompositor {
+/** The latest matte the running preview computed, published for the DOM
+ * layer: front subject-masked elements turn it into a CSS mask-image. Only
+ * the preview's compositor writes it — an in-tab export runs its own
+ * compositor on its own clock and keeps out of the live editor's mattes. */
+let published: { canvas: HTMLCanvasElement | null; at: number } | null = null;
+export function subjectMatteSnapshot(): { canvas: HTMLCanvasElement | null; at: number } | null {
+ return published;
+}
+
+export class SubjectMaskCompositor {
+ /** `publishes` marks the live preview's instance, the one whose matte the
+ * DOM layer reads. */
+ constructor(private publishes = false) {}
+
private segmenter: Segmenter | null = null;
private segKicked = false;
- private rasters = new WeakMap<TextOverlay, ImageBitmap>();
- private pending = new WeakSet<TextOverlay>();
+ private rasters = new WeakMap<Overlay, ImageBitmap>();
+ private pending = new WeakSet<Overlay>();
private person: HTMLCanvasElement | null = null;
private small: HTMLCanvasElement | null = null;
private mask: { at: number; alpha: HTMLCanvasElement | null } = { at: -1e9, alpha: null };
+ /** A second matte slot for mid-stack clip masks: it snapshots the canvas as
+ * it stands when the masked clip draws (the layers beneath it), so a
+ * masked layer never reads its own trimmed pixels back. */
+ private clipMatte: { at: number; alpha: HTMLCanvasElement | null } = { at: -1e9, alpha: null };
/** Kick the (shared) segmenter load; safe to call every frame. */
private ensureSegmenter() {
@@ -54,12 +95,7 @@ export class BehindCompositor {
});
}
- private rasterFor(
- o: TextOverlay,
- w: number,
- h: number,
- assets: MediaAsset[]
- ): ImageBitmap | null {
+ private rasterFor(o: Overlay, w: number, h: number, assets: MediaAsset[]): ImageBitmap | null {
const hit = this.rasters.get(o);
if (hit) return hit;
if (!this.pending.has(o)) {
@@ -80,9 +116,7 @@ export class BehindCompositor {
await personSegmenter().then((s) => {
this.segmenter = s;
});
- const behind = overlays.filter(
- (o): o is TextOverlay => isTextOverlay(o) && !!o.behindSubject && !o.hidden
- );
+ const behind = overlays.filter((o) => behindSubjectOverlay(o) && drawable(o));
await Promise.all(
behind.map(async (o) => {
if (this.rasters.get(o)) return;
@@ -101,8 +135,129 @@ export class BehindCompositor {
);
}
+ /** Segment `source`'s current pixels into a person-alpha canvas, throttled
+ * into `slot`. Returns null while the segmenter loads; a computed frame
+ * with no person carries `alpha: null`. */
+ private matteOf(
+ source: HTMLCanvasElement | OffscreenCanvas,
+ t: number,
+ slot: { at: number; alpha: HTMLCanvasElement | null },
+ minInterval: number
+ ): SubjectMatte | null {
+ this.ensureSegmenter();
+ if (!this.segmenter) return null;
+ if (slot.at > -1e8 && Math.abs(t - slot.at) < minInterval) return { alpha: slot.alpha };
+ if (!this.small) this.small = document.createElement("canvas");
+ const W = source.width;
+ const H = source.height;
+ const sw = SEG_WIDTH;
+ const sh = Math.max(2, Math.round((SEG_WIDTH * H) / W));
+ if (this.small.width !== sw || this.small.height !== sh) {
+ this.small.width = sw;
+ this.small.height = sh;
+ }
+ const sctx = this.small.getContext("2d", { willReadFrequently: true })!;
+ sctx.clearRect(0, 0, sw, sh);
+ sctx.drawImage(source, 0, 0, sw, sh);
+ slot.at = t;
+ slot.alpha = segmentSubjectAlpha(this.segmenter, this.small);
+ return { alpha: slot.alpha };
+ }
+
+ /**
+ * The matte a subject-masked video clip trims by, read mid-stack: the
+ * canvas holds the layers beneath the clip at call time. Feed this as the
+ * FrameCompositor's subject-matte provider.
+ */
+ clipMatteOf(
+ canvas: HTMLCanvasElement | OffscreenCanvas,
+ t: number,
+ opts: { minMaskInterval?: number } = {}
+ ): SubjectMatte | null {
+ return this.matteOf(canvas, t, this.clipMatte, opts.minMaskInterval ?? 1 / 15);
+ }
+
+ /** Refresh the full-composite matte for front subject-masked elements,
+ * with the video layers already on the canvas; the preview instance also
+ * publishes it for the DOM layer. */
+ publishMatte(
+ canvas: HTMLCanvasElement | OffscreenCanvas,
+ t: number,
+ opts: { minMaskInterval?: number } = {}
+ ): SubjectMatte | null {
+ const res = this.matteOf(canvas, t, this.mask, opts.minMaskInterval ?? 1 / 15);
+ if (this.publishes) {
+ published = res ? { canvas: res.alpha, at: this.mask.at } : null;
+ }
+ return res;
+ }
+
+ /** Trim a stamped layer's pixels to the current matte (`invert` keeps the
+ * outside), through `scratch`; feather blurs the matte edge. A computed
+ * frame with no person clears a front layer (coverage is empty) and keeps
+ * a behind layer whole; with no computed frame the layer stays whole. */
+ applyMatte(
+ target: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
+ scratch: HTMLCanvasElement,
+ invert: boolean,
+ featherPx: number
+ ): void {
+ const matte = this.mask.alpha;
+ const W = target.canvas.width;
+ const H = target.canvas.height;
+ if (!matte) {
+ if (this.mask.at > -1e8 && !invert) target.clearRect(0, 0, W, H);
+ return;
+ }
+ if (scratch.width !== W) scratch.width = W;
+ if (scratch.height !== H) scratch.height = H;
+ const sctx = scratch.getContext("2d")!;
+ sctx.clearRect(0, 0, W, H);
+ if (featherPx > 0 && "filter" in sctx) sctx.filter = `blur(${featherPx / 2}px)`;
+ sctx.imageSmoothingEnabled = true;
+ sctx.drawImage(matte, 0, 0, W, H);
+ sctx.filter = "none";
+ maskComposite(target, scratch, invert);
+ }
+
+ /** One stamped layer trimmed to the current matte: `draw` puts the stamp's
+ * pixels (posed and all) onto a per-instance surface, then the matte
+ * multiplies in at identity — the matte stays anchored to the frame while
+ * the element moves under it. The surfaces live and die with this pass. */
+ private stampSurface: HTMLCanvasElement | null = null;
+ private stampScratch: HTMLCanvasElement | null = null;
+ mattedStamp(
+ o: { mask?: { invert?: boolean; feather?: number } },
+ w: number,
+ h: number,
+ draw: (ctx: CanvasRenderingContext2D) => void
+ ): CanvasImageSource {
+ if (!this.stampSurface || !this.stampScratch) {
+ this.stampSurface = document.createElement("canvas");
+ this.stampScratch = document.createElement("canvas");
+ }
+ if (this.stampSurface.width !== w) this.stampSurface.width = w;
+ if (this.stampSurface.height !== h) this.stampSurface.height = h;
+ const ctx = this.stampSurface.getContext("2d")!;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+ ctx.save();
+ draw(ctx);
+ ctx.restore();
+ this.applyMatte(
+ ctx,
+ this.stampScratch,
+ !!o.mask?.invert,
+ (o.mask?.feather ?? 0) * (Math.min(w, h) / 1080)
+ );
+ return this.stampSurface;
+ }
+
/**
- * Run the pass on `canvas` (video layers already drawn). `minMaskInterval`
+ * Run the behind pass on `canvas` (video layers already drawn): draw the
+ * behind-tagged rasters, then the segmented person back over them. Also
+ * refreshes and publishes the composite matte, so front subject elements
+ * can read it even on frames with no behind element live. `minMaskInterval`
* throttles segmentation for the live preview; pass 0 for exports.
*/
draw(
@@ -113,8 +268,10 @@ export class BehindCompositor {
opts: { minMaskInterval?: number } = {}
): void {
const active = behindOverlaysAt(overlays, t);
- if (active.length === 0) return;
- this.ensureSegmenter();
+ const wantsMatte = overlays.some(
+ (o) => frontSubjectOverlay(o) && drawable(o) && t >= o.start && t <= o.end
+ );
+ if (active.length === 0 && !wantsMatte) return;
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) return;
const W = canvas.width;
@@ -131,9 +288,15 @@ export class BehindCompositor {
pctx.clearRect(0, 0, W, H);
pctx.drawImage(canvas, 0, 0);
- // The behind text, drawn straight onto the composite: a neutral raster
- // under the element's pose for this moment, exactly like the export's
- // stamped layers.
+ // Segment (throttled) and publish before anything composites: between
+ // refreshes the previous matte rides the new frame (the subject moves
+ // little in 1/15s, and a lagging mask beats a stuttering preview).
+ const alpha = this.publishMatte(canvas, t, opts)?.alpha ?? null;
+ if (active.length === 0) return;
+
+ // The behind elements, drawn straight onto the composite: a neutral
+ // raster under the element's pose for this moment, exactly like the
+ // export's stamped layers.
const scale = Math.min(W, H) / 1080;
for (const o of active) {
const bmp = this.rasterFor(o, W, H, assets);
@@ -152,27 +315,15 @@ export class BehindCompositor {
ctx.restore();
}
- // The person back on top. Segmentation is throttled: between refreshes
- // the previous mask rides the new frame (the subject moves little in
- // 1/15s, and a lagging mask beats a stuttering preview).
- if (!this.segmenter) return;
- const minInterval = opts.minMaskInterval ?? 1 / 15;
- if (!this.mask.alpha || Math.abs(t - this.mask.at) >= minInterval) {
- if (!this.small) this.small = document.createElement("canvas");
- const sw = SEG_WIDTH;
- const sh = Math.max(2, Math.round((SEG_WIDTH * H) / W));
- if (this.small.width !== sw || this.small.height !== sh) {
- this.small.width = sw;
- this.small.height = sh;
- }
- const sctx = this.small.getContext("2d", { willReadFrequently: true })!;
- sctx.drawImage(this.person, 0, 0, sw, sh);
- this.mask = { at: t, alpha: segmentSubjectAlpha(this.segmenter, this.small) };
- }
- if (!this.mask.alpha) return; // no person in shot: the text stays in front
+ // The person back on top, its edge softened by the widest feather any
+ // live behind element asks for.
+ if (!alpha) return; // no person in shot: the elements stay in front
+ const feather = Math.max(0, ...active.map((o) => (o.mask?.feather ?? 0) * scale));
pctx.globalCompositeOperation = "destination-in";
pctx.imageSmoothingEnabled = true;
- pctx.drawImage(this.mask.alpha, 0, 0, W, H);
+ if (feather > 0 && "filter" in pctx) pctx.filter = `blur(${feather / 2}px)`;
+ pctx.drawImage(alpha, 0, 0, W, H);
+ pctx.filter = "none";
pctx.globalCompositeOperation = "source-over";
ctx.drawImage(this.person, 0, 0);
}
diff --git a/site/src/cut/lib/composite.ts b/site/src/cut/lib/composite.ts
index 459f94b3..db04dc60 100644
--- a/site/src/cut/lib/composite.ts
+++ b/site/src/cut/lib/composite.ts
@@ -19,8 +19,8 @@
* it was reached by playing there or by rendering the 135th frame.
*/
-import { gradeTint, gradeToCssFilter, grainTile, isNeutralGrade, lookCssFilter, lookPost } from "@donkeycut/effects-kit";
-import { isFullRect, rectOf } from "./types";
+import { applyMaskToCanvas, gradeTint, gradeToCssFilter, grainTile, isNeutralGrade, lookCssFilter, lookPost, maskComposite } from "@donkeycut/effects-kit";
+import { clipKeyed, clipPoseAt, isFullRect, rectOf } from "./types";
import type { FrameRect, TransitionStyle, VideoClip } from "./types";
/** A clip's picture at some instant, or the reasons there isn't one.
@@ -72,6 +72,22 @@ export class FrameCompositor {
private gradeCanvas: Surface | null = null;
private lookScratch: Surface | null = null;
private vignetteCanvas: Surface | null = null;
+ /** The masked/keyframed-layer pass: the layer draws into `layerScratch`,
+ * its mask's coverage paints into `maskScratch`, a keyframed pose blits
+ * through `poseScratch`, and the result composites back onto the frame. */
+ private layerScratch: Surface | null = null;
+ private maskScratch: Surface | null = null;
+ private poseScratch: Surface | null = null;
+
+ /** Where a subject-masked clip's person matte comes from: the host hands a
+ * reader over the canvas as it stands (the layers beneath the clip), so
+ * the matte never includes the masked clip's own pixels. A computed frame
+ * with `alpha: null` means no person registered — empty coverage. Provider
+ * absent, or a null frame = subject masks draw the plain picture (no
+ * segmenter, or the matte pass that must not recurse). */
+ subjectMatteProvider:
+ | ((at: number) => { alpha: CanvasImageSource | null } | null)
+ | null = null;
constructor(private canvas: Surface) {}
@@ -96,7 +112,13 @@ export class FrameCompositor {
* whether it had to be resized — which also cleared it, since setting a
* canvas dimension wipes its contents. */
private scratch(
- field: "gradeCanvas" | "lookScratch" | "vignetteCanvas",
+ field:
+ | "gradeCanvas"
+ | "lookScratch"
+ | "vignetteCanvas"
+ | "layerScratch"
+ | "maskScratch"
+ | "poseScratch",
w: number,
h: number
): { surface: Surface; resized: boolean } {
@@ -308,6 +330,112 @@ export class FrameCompositor {
ctx.globalCompositeOperation = "source-over";
}
+ /** Whether the layer routes through the mask/pose pass at all. */
+ private needsFx(clip?: VideoClip): boolean {
+ return (
+ !!clip &&
+ (clipKeyed(clip) ||
+ !!(clip.mask && (clip.mask.kind !== "subject" || this.subjectMatteProvider)))
+ );
+ }
+
+ /**
+ * Draw one masked or keyframed layer by re-entering `draw` against a
+ * transparent scratch (with the clip's mask and keys stripped so the inner
+ * call draws plainly), then compose in order: the geometry mask trims the
+ * layer in its own space (it rides the clip), the pose blits the result
+ * where the keys put it, and the person matte — anchored to the frame, so
+ * the person never travels with the clip — trims last. The mask and pose
+ * evaluate on the clip's own clock.
+ */
+ private drawFx(
+ clip: VideoClip,
+ at: number,
+ fx: LayerFx | undefined,
+ draw: (plain: VideoClip) => void
+ ) {
+ const ctx = this.ctx();
+ if (!ctx) return;
+ const W = this.canvas.width;
+ const H = this.canvas.height;
+ const tLocal = Math.max(0, at - clip.start);
+ const pose = clipKeyed(clip) ? clipPoseAt(clip, tLocal) : null;
+ if (pose && pose.opacity <= 0.001) return;
+ const mask = clip.mask;
+ const { surface: layer } = this.scratch("layerScratch", W, H);
+ const lctx = layer.getContext("2d") as Ctx | null;
+ if (!lctx) return;
+ lctx.clearRect(0, 0, W, H);
+ const prev = this.canvas;
+ this.canvas = layer;
+ try {
+ draw({ ...clip, mask: undefined, kf: undefined });
+ } finally {
+ this.canvas = prev;
+ }
+ const rect = rectOf(clip);
+ const { surface: cover } = this.scratch("maskScratch", W, H);
+ if (mask && mask.kind !== "subject") {
+ applyMaskToCanvas(
+ lctx,
+ cover,
+ mask,
+ tLocal,
+ { width: W, height: H, scale: Math.min(W, H) / 1080 },
+ { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 }
+ );
+ }
+ let out: Surface = layer;
+ let octx = lctx;
+ if (pose) {
+ const { surface: posed } = this.scratch("poseScratch", W, H);
+ const pctx = posed.getContext("2d") as Ctx | null;
+ if (!pctx) return;
+ pctx.setTransform(1, 0, 0, 1, 0, 0);
+ pctx.clearRect(0, 0, W, H);
+ pctx.save();
+ pctx.globalAlpha = Math.max(0, Math.min(1, pose.opacity));
+ pctx.translate(pose.x * W, pose.y * H);
+ pctx.rotate((pose.rotation * Math.PI) / 180);
+ pctx.scale(pose.scale, pose.scale);
+ pctx.translate(-(rect.x + rect.w / 2) * W, -(rect.y + rect.h / 2) * H);
+ pctx.drawImage(layer, 0, 0);
+ pctx.restore();
+ out = posed;
+ octx = pctx;
+ }
+ if (mask?.kind === "subject") {
+ // The person matte is the coverage: blur its edge by the feather and
+ // multiply it in (or out, inverted), after the pose so the person
+ // stays anchored to the frame. A computed frame with no person means
+ // empty coverage — a front-masked layer shows nothing (the export's
+ // black matte frames land the same way) and a behind-masked one shows
+ // whole.
+ const res = this.subjectMatteProvider?.(at) ?? null;
+ if (res && !res.alpha) {
+ if (!mask.invert) return;
+ } else if (res?.alpha) {
+ const cctx = cover.getContext("2d") as Ctx;
+ cctx.clearRect(0, 0, W, H);
+ const feather = (mask.feather ?? 0) * (Math.min(W, H) / 1080);
+ if (feather > 0 && "filter" in cctx) cctx.filter = `blur(${feather / 2}px)`;
+ cctx.imageSmoothingEnabled = true;
+ cctx.drawImage(res.alpha, 0, 0, W, H);
+ cctx.filter = "none";
+ maskComposite(octx, cover as CanvasImageSource, mask.invert);
+ }
+ }
+ // Transition motion lands on the finished result, so a push carries the
+ // mask and pose along — the export translates the segment the same way.
+ const hasFx = !!fx && (!!fx.dx || !!fx.dy);
+ if (hasFx) {
+ ctx.save();
+ ctx.translate(Math.round(fx.dx ?? 0), Math.round(fx.dy ?? 0));
+ }
+ ctx.drawImage(out, 0, 0);
+ if (hasFx) ctx.restore();
+ }
+
/** Draw a frame into a sub-rectangle of the canvas (a split-screen half, an
* overlay's region), fitted or filled. */
drawIntoRect(
@@ -320,6 +448,12 @@ export class FrameCompositor {
clip?: VideoClip
) {
if (frame.kind !== "ready") return;
+ if (this.needsFx(clip)) {
+ this.drawFx(clip!, at, undefined, (plain) =>
+ this.drawIntoRect(frame, rect, fill, alpha, at, zoom, plain)
+ );
+ return;
+ }
const ctx = this.ctx();
if (!ctx) return;
const W = this.canvas.width;
@@ -386,6 +520,15 @@ export class FrameCompositor {
// instead of strobing black (matters while skimming).
if (frame.kind === "pending") return;
blank();
+ if (this.needsFx(clip)) {
+ // The blank above already settled who owns the black; the layer itself
+ // draws through the mask/pose pass, and any transition motion lands on
+ // the finished result.
+ this.drawFx(clip!, at, fx, (plain) =>
+ this.drawLayer(frame, plain, false, alpha, at, zoom, undefined)
+ );
+ return;
+ }
const hasFx = !!fx && (!!fx.dx || !!fx.dy);
if (hasFx) {
diff --git a/site/src/cut/lib/overlayModel.test.ts b/site/src/cut/lib/overlayModel.test.ts
index 2c5688a9..c43d286a 100644
--- a/site/src/cut/lib/overlayModel.test.ts
+++ b/site/src/cut/lib/overlayModel.test.ts
@@ -7,8 +7,12 @@ import {
type OverlayAnim,
} from "@donkeycut/effects-kit";
import {
+ behindSubjectOverlay,
+ frontSubjectOverlay,
+ migrateBehindSubject,
stampOverlayKinds,
stripDefaultOverlayKinds,
+ subjectMasked,
type Overlay,
type ShapeOverlay,
type TextOverlay,
@@ -74,6 +78,33 @@ describe("overlay kind stamping", () => {
});
});
+describe("behind-speaker migration", () => {
+ test("the stored boolean loads as an inverted subject mask", () => {
+ const behind = { ...legacyTitle(), behindSubject: true } as TextOverlay;
+ const [migrated] = migrateBehindSubject(stampOverlayKinds([behind]));
+ expect(migrated.mask).toEqual({ kind: "subject", invert: true });
+ expect("behindSubject" in migrated).toBe(false);
+ expect(behindSubjectOverlay(migrated)).toBe(true);
+ expect(subjectMasked(migrated)).toBe(true);
+ expect(frontSubjectOverlay(migrated)).toBe(false);
+ // The predicates read the mask alone — the migration is the one door in.
+ expect(behindSubjectOverlay(stampOverlayKinds([behind])[0])).toBe(false);
+ });
+
+ test("nothing to migrate returns the same array identity", () => {
+ const overlays = stampOverlayKinds([legacyTitle()]);
+ expect(migrateBehindSubject(overlays)).toBe(overlays);
+ });
+
+ test("a plain subject mask is front, an inverted one behind", () => {
+ const front: Overlay = { ...legacyTitle(), kind: "text", mask: { kind: "subject" } };
+ const shape: Overlay = { ...legacyTitle(), kind: "text", mask: { kind: "rect" } };
+ expect(frontSubjectOverlay(front)).toBe(true);
+ expect(behindSubjectOverlay(front)).toBe(false);
+ expect(subjectMasked(shape)).toBe(false);
+ });
+});
+
describe("shapeMetrics", () => {
const frame = { width: 1080, height: 1920, scale: 1 }; // 9:16 at design size
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index 418485f9..2577fa74 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -453,7 +453,7 @@ describe("title lanes", () => {
s().setOverlayKey(t1.id, 1);
s().selectOverlayKey(t1.id, 1);
s().moveOverlayKey(t1.id, 1, 2.5, { transient: true });
- expect(s().selectedKey).toEqual({ overlayId: t1.id, t: 2.5 });
+ expect(s().selectedKey).toEqual({ kind: "overlay", id: t1.id, t: 2.5 });
s().deleteSelection();
expect(overlayById(t1.id).kf).toBe(undefined);
});
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index d1f3f798..0877a2f0 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -5,9 +5,11 @@ import {
KEY_EPSILON,
keyAt,
lineLikeShape,
+ maskKeyAt,
removeKeyAt,
upsertKey,
type EffectId,
+ type MaskKey,
type OverlayKey,
} from "@donkeycut/effects-kit";
import { create } from "zustand";
@@ -55,7 +57,7 @@ import { alignCues } from "./cueAlign";
import { useGenNotify } from "./genNotify";
import { engineTranscribeSamples } from "./localStt";
import { trackLocale } from "./subtitles";
-import { ANIM_STYLE_IDS, animStyleOfTransition, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isEffectOverlay, isStickerOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionStyleOfAnim } from "./types";
+import { ANIM_STYLE_IDS, animStyleOfTransition, clipPoseAt, emptySubtitles, frameOf, IMAGE_CLIP_SECONDS, isEffectOverlay, isStickerOverlay, MAX_SUBTITLE_LANES, mediaUrl, migrateBehindSubject, migrateLegacyTransitions, normalizeAspect, overlayAnimStyle, SPEED_FLOOR, SPEED_MIN, stampOverlayKinds, stripDefaultOverlayKinds, TRANSITION_MAX, TRANSITION_STYLE_IDS, transitionStyleOfAnim } from "./types";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState, type ProjectUiState } from "./uiState";
import { captureTimelineFrames } from "./visualFrames";
@@ -165,11 +167,11 @@ export interface EditorState {
/** Everything selected, including `selection` (the primary that drives the
* inspector). Bulk actions — delete, copy — act on this whole set. */
multiSelection: Selection[];
- /** The keyframe picked on an element's timeline bar, if any. It rides
- * alongside the element selection rather than inside it: an element is still
- * what the inspector edits, but Delete takes the key. Any other selection
- * clears it. */
- selectedKey: { overlayId: string; t: number } | null;
+ /** The keyframe picked on a timeline bar — an element's or a video
+ * clip's — if any. It rides alongside the item selection: the item is
+ * still what the inspector edits, but Delete takes the key. Any other
+ * selection clears it. */
+ selectedKey: { kind: "overlay" | "clip"; id: string; t: number } | null;
currentTime: number;
playing: boolean;
/** While playing a scoped effect preview, the time playback auto-pauses at;
@@ -346,6 +348,40 @@ export interface EditorState {
opts?: { transient?: boolean }
) => void;
clearOverlayKeys: (id: string) => void;
+ /** Mask keyframes, the mask's own track beside the pose track. Same rules:
+ * adding a key captures the mask's live geometry, `patch` edits it in
+ * place, and a key already sitting at `tLocal` is replaced. */
+ setOverlayMaskKey: (
+ id: string,
+ tLocal: number,
+ patch?: Partial<Omit<MaskKey, "t">>,
+ opts?: { transient?: boolean }
+ ) => void;
+ removeOverlayMaskKey: (id: string, tLocal: number) => void;
+ clearOverlayMaskKeys: (id: string) => void;
+ /** The same mask-key track on a video clip; `tLocal` is seconds from the
+ * clip's timeline start. */
+ setClipMaskKey: (
+ id: string,
+ tLocal: number,
+ patch?: Partial<Omit<MaskKey, "t">>,
+ opts?: { transient?: boolean }
+ ) => void;
+ removeClipMaskKey: (id: string, tLocal: number) => void;
+ clearClipMaskKeys: (id: string) => void;
+ /** The pose-key track on a video clip, the overlay contract over the
+ * clip's anchor: adding a key captures the clip's pose at that moment,
+ * `patch` edits it in place, and a key already at `tLocal` is replaced. */
+ setClipKey: (
+ id: string,
+ tLocal: number,
+ patch?: Partial<Omit<OverlayKey, "t">>,
+ opts?: { transient?: boolean }
+ ) => void;
+ removeClipKey: (id: string, tLocal: number) => void;
+ selectClipKey: (id: string, tLocal: number) => void;
+ moveClipKey: (id: string, fromT: number, toT: number, opts?: { transient?: boolean }) => void;
+ clearClipKeys: (id: string) => void;
/** Patch several items in one commit — the lane coordinator's gestures part
* and push whole lanes at a time (one bulk patcher per lane-track kind). */
updateOverlaysTransient: (patches: { id: string; patch: OverlayPatch }[]) => void;
@@ -1211,7 +1247,11 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// saved onto a shared row move to one of their own, and a clip graded
// back when a look was a clip property gets that grade as an element
// over it — so a project made before either rule reads like a new one.
- const stamped = normalizeElementLanes(stampOverlayKinds(doc.overlays ?? []));
+ // The behind-speaker boolean becomes an inverted subject mask on load,
+ // so one mask model covers it everywhere in memory and on save.
+ const stamped = normalizeElementLanes(
+ migrateBehindSubject(stampOverlayKinds(doc.overlays ?? []))
+ );
const subtitles = doc.subtitles ?? emptySubtitles();
// Docs saved when edge transition styles existed convert them into the
// equivalent clip animations, and docs saved when a transition was a
@@ -2108,7 +2148,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
if (kf.length === o.kf.length) return;
push();
// The last key going means the element holds its own resting pose
- // again, so the track leaves rather than lingering empty.
+ // again, so the track leaves with it.
get().updateOverlayTransient(id, { kf: kf.length ? kf : undefined });
},
@@ -2116,7 +2156,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
const o = get().overlays.find((x) => x.id === id);
if (!o) return;
get().select({ kind: "overlay", id });
- set({ selectedKey: { overlayId: id, t: tLocal } });
+ set({ selectedKey: { kind: "overlay", id, t: tLocal } });
},
moveOverlayKey: (id, fromT, toT, opts) => {
@@ -2131,8 +2171,13 @@ export const useEditor = create<EditorState>((baseSet, get) => {
});
// The pick follows the key it is on, so dragging never drops it.
const picked = get().selectedKey;
- if (picked && picked.overlayId === id && Math.abs(picked.t - fromT) <= KEY_EPSILON) {
- set({ selectedKey: { overlayId: id, t } });
+ if (
+ picked &&
+ picked.kind === "overlay" &&
+ picked.id === id &&
+ Math.abs(picked.t - fromT) <= KEY_EPSILON
+ ) {
+ set({ selectedKey: { kind: "overlay", id, t } });
}
},
@@ -2143,6 +2188,120 @@ export const useEditor = create<EditorState>((baseSet, get) => {
get().updateOverlayTransient(id, { kf: undefined });
},
+ setOverlayMaskKey: (id, tLocal, patch, opts) => {
+ const o = get().overlays.find((x) => x.id === id);
+ if (!o?.mask) return;
+ const t = Math.max(0, Math.min(tLocal, Math.max(0.1, o.end - o.start)));
+ const existing = o.mask.kf?.find((k) => Math.abs(k.t - t) <= KEY_EPSILON);
+ // A brand-new key holds the geometry the mask already had at `t`, so
+ // adding one changes nothing until something edits it.
+ const next = { ...(existing ?? maskKeyAt(o.mask, t)), ...patch, t };
+ if (!opts?.transient) push();
+ get().updateOverlayTransient(id, { mask: { ...o.mask, kf: upsertKey(o.mask.kf, next) } });
+ },
+
+ removeOverlayMaskKey: (id, tLocal) => {
+ const o = get().overlays.find((x) => x.id === id);
+ if (!o?.mask?.kf?.length) return;
+ const kf = removeKeyAt(o.mask.kf, tLocal);
+ if (kf.length === o.mask.kf.length) return;
+ push();
+ // The last key going means the mask holds its own resting geometry
+ // again, so the track leaves with it.
+ get().updateOverlayTransient(id, { mask: { ...o.mask, kf: kf.length ? kf : undefined } });
+ },
+
+ clearOverlayMaskKeys: (id) => {
+ const o = get().overlays.find((x) => x.id === id);
+ if (!o?.mask?.kf?.length) return;
+ push();
+ get().updateOverlayTransient(id, { mask: { ...o.mask, kf: undefined } });
+ },
+
+ setClipMaskKey: (id, tLocal, patch, opts) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c?.mask) return;
+ const len = Math.max(0.1, (c.out - c.in) / clipSpeed(c));
+ const t = Math.max(0, Math.min(tLocal, len));
+ const existing = c.mask.kf?.find((k) => Math.abs(k.t - t) <= KEY_EPSILON);
+ const next = { ...(existing ?? maskKeyAt(c.mask, t)), ...patch, t };
+ if (!opts?.transient) push();
+ get().updateClipTransient(id, { mask: { ...c.mask, kf: upsertKey(c.mask.kf, next) } });
+ },
+
+ removeClipMaskKey: (id, tLocal) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c?.mask?.kf?.length) return;
+ const kf = removeKeyAt(c.mask.kf, tLocal);
+ if (kf.length === c.mask.kf.length) return;
+ push();
+ get().updateClipTransient(id, { mask: { ...c.mask, kf: kf.length ? kf : undefined } });
+ },
+
+ clearClipMaskKeys: (id) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c?.mask?.kf?.length) return;
+ push();
+ get().updateClipTransient(id, { mask: { ...c.mask, kf: undefined } });
+ },
+
+ setClipKey: (id, tLocal, patch, opts) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c) return;
+ const t = Math.max(0, Math.min(tLocal, clipLen(c)));
+ const existing = c.kf?.find((k) => Math.abs(k.t - t) <= KEY_EPSILON);
+ // A brand-new key holds the pose the clip already had at `t`, so
+ // adding one changes nothing until something edits it.
+ const next = { ...(existing ?? { t, ...clipPoseAt(c, t) }), ...patch, t };
+ if (!opts?.transient) push();
+ get().updateClipTransient(id, { kf: upsertKey(c.kf, next) });
+ },
+
+ removeClipKey: (id, tLocal) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c?.kf?.length) return;
+ const kf = removeKeyAt(c.kf, tLocal);
+ if (kf.length === c.kf.length) return;
+ push();
+ // The last key going means the clip rests in its region again, so the
+ // track leaves with it.
+ get().updateClipTransient(id, { kf: kf.length ? kf : undefined });
+ },
+
+ selectClipKey: (id, tLocal) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c) return;
+ get().select({ kind: "clip", id });
+ set({ selectedKey: { kind: "clip", id, t: tLocal } });
+ },
+
+ moveClipKey: (id, fromT, toT, opts) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c?.kf?.length) return;
+ const key = c.kf.find((k) => Math.abs(k.t - fromT) <= KEY_EPSILON);
+ if (!key) return;
+ const t = Math.max(0, Math.min(toT, clipLen(c)));
+ if (!opts?.transient) push();
+ get().updateClipTransient(id, { kf: upsertKey(removeKeyAt(c.kf, fromT), { ...key, t }) });
+ // The pick follows the key it is on, so dragging never drops it.
+ const picked = get().selectedKey;
+ if (
+ picked &&
+ picked.kind === "clip" &&
+ picked.id === id &&
+ Math.abs(picked.t - fromT) <= KEY_EPSILON
+ ) {
+ set({ selectedKey: { kind: "clip", id, t } });
+ }
+ },
+
+ clearClipKeys: (id) => {
+ const c = get().clips.find((x) => x.id === id);
+ if (!c?.kf?.length) return;
+ push();
+ get().updateClipTransient(id, { kf: undefined });
+ },
+
updateOverlayTransient: (id, patch) =>
set((s) => ({
overlays: s.overlays.map((o) => (o.id === id ? { ...o, ...patch } : o)),
@@ -2487,13 +2646,17 @@ export const useEditor = create<EditorState>((baseSet, get) => {
deleteSelection: () => {
const st = get();
// A picked keyframe is the smaller thing under the cursor: Delete takes
- // the key and leaves the element it belongs to alone.
+ // the key and leaves the item it belongs to alone.
const key = st.selectedKey;
if (key) {
set({ selectedKey: null });
- const o = st.overlays.find((x) => x.id === key.overlayId);
- if (o?.kf?.some((k) => Math.abs(k.t - key.t) <= KEY_EPSILON)) {
- st.removeOverlayKey(key.overlayId, key.t);
+ const item =
+ key.kind === "overlay"
+ ? st.overlays.find((x) => x.id === key.id)
+ : st.clips.find((x) => x.id === key.id);
+ if (item?.kf?.some((k) => Math.abs(k.t - key.t) <= KEY_EPSILON)) {
+ if (key.kind === "overlay") st.removeOverlayKey(key.id, key.t);
+ else st.removeClipKey(key.id, key.t);
return;
}
}
@@ -2830,12 +2993,13 @@ export const useEditor = create<EditorState>((baseSet, get) => {
...(a.duck !== undefined && a.duck < 1 ? { duck: a.duck } : {}),
...(a.lane ? { lane: a.lane } : {}),
}));
- // Templates saved before the union carry bare titles — same stamp as
- // the doc loader, so every in-memory element has its discriminant.
- // Groups are remapped per application, so adding the same template
- // twice gives two independent groups instead of one welded set.
+ // Templates saved before the union carry bare titles — same stamp and
+ // behind-speaker migration as the doc loader, so every in-memory
+ // element has its discriminant and one mask model. Groups are remapped
+ // per application, so adding the same template twice gives two
+ // independent groups.
const regroup = groupRemap(uid);
- const newTexts: Overlay[] = stampOverlayKinds(template.texts).map((o) => ({
+ const newTexts: Overlay[] = migrateBehindSubject(stampOverlayKinds(template.texts)).map((o) => ({
...o,
id: uid(),
start: o.start + shift,
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 43654b4a..9baf509f 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -1,12 +1,17 @@
import {
+ behindSubjectMask,
overlayKind,
+ poseAt,
stampOverlayKinds,
stripDefaultOverlayKinds,
type ColorGrade,
type EffectOverlay,
type LookStyle,
+ type Mask,
type OverlayBase,
+ type OverlayKey,
type OverlayKind,
+ type OverlayPose,
type ShapeKind,
type ShapeOverlay,
type StickerOverlay,
@@ -182,6 +187,56 @@ export function isFullRect(r: FrameRect): boolean {
return r.x <= 0.001 && r.y <= 0.001 && r.w >= 0.999 && r.h >= 0.999;
}
+/** A region's pixel box at an output size, even-rounded and clamped inside
+ * the frame — the one rounding that decides where a regioned clip's segment
+ * sits. The ffmpeg graph frames segments with it and the export client
+ * paints mask coverage with it, so the two land on identical pixels. Null
+ * for the full frame. */
+export function regionPx(
+ frame: { x: number; y: number; w: number; h: number } | undefined,
+ W: number,
+ H: number
+): { rx: number; ry: number; rw: number; rh: number } | null {
+ if (!frame) return null;
+ const even = (n: number) => 2 * Math.round(n / 2);
+ const rw = Math.min(W, Math.max(2, even(frame.w * W)));
+ const rh = Math.min(H, Math.max(2, even(frame.h * H)));
+ // Clamp the origin so rx+rw ≤ W and ry+rh ≤ H — independent even-rounding
+ // can otherwise push an edge-touching region a pixel past the frame, which
+ // makes the pad filter reject the input ("not within the padded area") and
+ // aborts the whole export.
+ const rx = Math.max(0, Math.min(even(frame.x * W), W - rw));
+ const ry = Math.max(0, Math.min(even(frame.y * H), H - rh));
+ if (rx <= 0 && ry <= 0 && rw >= W && rh >= H) return null;
+ return { rx, ry, rw, rh };
+}
+
+/** Whether the clip carries pose keys worth evaluating. */
+export const clipKeyed = (c: { kf?: OverlayKey[] }): boolean => !!c.kf && c.kf.length > 0;
+
+/**
+ * The clip's pose at `tLocal` seconds into its window: resting at its region
+ * center, or moving along its key track — the overlay evaluator over the
+ * clip's own anchor, so clips and elements share one interpolation.
+ */
+export function clipPoseAt(
+ clip: { frame?: FrameRect; in: number; out: number; speed?: number; kf?: OverlayKey[] },
+ tLocal: number
+): OverlayPose {
+ const rect = rectOf(clip);
+ const len = Math.max(0.1, (clip.out - clip.in) / (clip.speed && clip.speed > 0 ? clip.speed : 1));
+ return poseAt(
+ {
+ start: 0,
+ end: len,
+ x: rect.x + rect.w / 2,
+ y: rect.y + rect.h / 2,
+ kf: clip.kf,
+ },
+ tLocal
+ );
+}
+
/** One-click layouts for arranging a video layer in the frame. `fit` is the
* sensible default meeting for that shape: halves cover their region, a corner
* is contained so the whole picture shows. */
@@ -266,6 +321,15 @@ export interface VideoClip {
hidden?: boolean;
/** Manual color adjustments; absent when every value is neutral. */
grade?: ColorGrade;
+ /** Coverage that trims the clip's picture to a shape (see the kit's
+ * mask.ts); absent = the whole picture shows. Anchored on the clip's
+ * region center. */
+ mask?: Mask;
+ /** Keyframed pose track (see the kit's keys.ts), seconds from the clip's
+ * timeline start: x/y move the picture's center (frame fractions), scale
+ * multiplies its fitted size, rotation turns it about its center, opacity
+ * fades it. Absent = the clip sits in its region untransformed. */
+ kf?: OverlayKey[];
}
// Color grading (the dual-renderer math) lives in the effects kit; the model
@@ -709,6 +773,32 @@ export const isShapeOverlay = (o: Overlay): o is ShapeOverlay => o.kind === "sha
export const isStickerOverlay = (o: Overlay): o is StickerOverlay => o.kind === "sticker";
export const isEffectOverlay = (o: Overlay): o is EffectOverlay => o.kind === "effect";
+/** The element rides the person matte in some direction. */
+export const subjectMasked = (o: Overlay): boolean => o.mask?.kind === "subject";
+
+/** The element sits behind the person (an inverted subject mask). */
+export const behindSubjectOverlay = (o: Overlay): boolean => behindSubjectMask(o.mask);
+
+/** The element shows only on the person (a plain subject mask). */
+export const frontSubjectOverlay = (o: Overlay): boolean =>
+ subjectMasked(o) && !behindSubjectOverlay(o);
+
+/** Tolerant-load migration: documents written when behind-speaker was a
+ * boolean load it as an inverted subject mask, so one mask model covers it
+ * everywhere in memory and on save. Returns the same array when nothing
+ * migrates (hosts compare documents by identity). */
+export function migrateBehindSubject<T extends Overlay>(overlays: T[]): T[] {
+ const legacy = (o: Overlay) =>
+ isTextOverlay(o) && !!(o as { behindSubject?: boolean }).behindSubject;
+ if (!overlays.some(legacy)) return overlays;
+ return overlays.map((o) => {
+ if (!legacy(o)) return o;
+ const next = { ...o, mask: o.mask ?? { kind: "subject" as const, invert: true } };
+ delete (next as { behindSubject?: boolean }).behindSubject;
+ return next;
+ });
+}
+
export const SHAPE_LABELS: Record<ShapeKind, string> = {
rect: "Rectangle",
ellipse: "Ellipse",