Open source CapCut alternative.
TypeScript
feat(site): the speed curve editor
David Le4962a3a1e708
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex e2d4f9fc..d6260077 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -74,6 +74,7 @@ import { Inspector } from "./Inspector";import { Lightbox } from "./Lightbox";import { Preview } from "./Preview";import { SidePanel } from "./SidePanel";+import { SpeedCurveStrip } from "./SpeedCurveStrip";import { Timeline } from "./Timeline";import { StorageUpgradeDialog } from "./StorageUpgradeDialog";import { TopBar } from "./TopBar";@@ -1122,7 +1123,7 @@ export function Editor({<div ref={shellRef} tabIndex={-1} className="flex h-full min-w-0 overflow-hidden outline-none">{/* The tab wears whatever is still running here. */}<TabStatus />- <div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">+ <div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto_auto]">{viewer ? (<ViewerTopBar />) : (@@ -1148,6 +1149,7 @@ export function Editor({</div>{hasInspector && <Inspector />}</div>+ <SpeedCurveStrip /><Timeline /></div>{aiOpen && (!viewer || sharedFeatures?.chat) && (diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 7a380924..866ec946 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -4,6 +4,7 @@ import { useQueryClient } from "@tanstack/react-query";import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Frame, Italic, Loader2, Palette, Scissors, Smile, Trash2, Type, Volume2 } from "lucide-react";import { Button } from "@/components/ui/button";+import { useSpeedCurveUi } from "@/cut/lib/speedCurveUi";import { EmojiPicker } from "@/cut/components/EmojiPicker";import { FontPicker } from "@/cut/components/FontPicker";import {@@ -65,6 +66,9 @@ import {type OverlayAnimStyle,type OverlayLoopStyle,type WordEffectId,+ retimeOf,+ flatSpeedCurve,+ hasSpeedCurve,} from "@donkeycut/effects-kit";import { clipWindow, maxClipFade, useEditor, type EditorState } from "@/cut/lib/store";import { usePanelView } from "@/cut/lib/panelViews";@@ -995,8 +999,11 @@ function ClipPanel({ clip }: { clip: VideoClip }) {const turnCk = useSliderCheckpoint();const fadeCk = useSliderCheckpoint();const [speedDraft, setSpeedDraft] = useState<number | null>(null);- const speed = speedDraft ?? clip.speed ?? 1;- const speedLen = (clip.out - clip.in) / (speed > 0 ? speed : 1);+ const curved = hasSpeedCurve(clip);+ const speed = speedDraft ?? (curved ? retimeOf(clip).rate : (clip.speed ?? 1));+ const speedLen =+ curved && speedDraft === null ? retimeOf(clip).len : (clip.out - clip.in) / (speed > 0 ? speed : 1);+ const curveOpen = useSpeedCurveUi((s) => s.clipId === clip.id);// Typing can trim out to the source's end but no further; an image has no// intrinsic duration, so its clip can be any length.const maxOut = asset && asset.type !== "image" ? asset.duration : Infinity;@@ -1100,13 +1107,39 @@ function ClipPanel({ clip }: { clip: VideoClip }) {/><ResetButtontitle="Reset speed"- show={Math.abs(speed - 1) > 1e-4}+ show={curved || Math.abs(speed - 1) > 1e-4}onClick={() => {useEditor.getState().setClipSpeed(clip.id, 1);setSpeedDraft(null);}}/></Row>+ <Row label="Speed Curve">+ <Button+ variant={curveOpen ? "secondary" : "outline"}+ size="sm"+ className="h-6 px-2 text-[11px]"+ title="Shape the speed across the footage with nodes"+ onClick={() => {+ const ui = useSpeedCurveUi.getState();+ if (curveOpen) {+ ui.close();+ return;+ }+ if (!curved) {+ useEditor.getState().setClipSpeedCurve(clip.id, flatSpeedCurve(clip));+ }+ ui.open(clip.id);+ }}+ >+ {curveOpen ? "Editing" : curved ? "Edit" : "Add"}+ </Button>+ {curved && (+ <span className="text-[11px] tabular-nums text-muted-foreground">+ {clip.speedCurve!.length} nodes+ </span>+ )}+ </Row>{/* Picture */}<div className="my-1.5 h-px bg-border" />@@ -1322,7 +1355,7 @@ function ClipGeneratedAudio({ clip }: { clip: VideoClip }) {);return s.audioClips.filter((a) => {- const len = (a.out - a.in) / (a.speed && a.speed > 0 ? a.speed : 1);+ const len = retimeOf(a).len;return (voiceAssets.has(a.assetId) && a.start < sp.start + sp.len && a.start + len > sp.start);@@ -1425,9 +1458,11 @@ function AudioPanel({ clip }: { clip: AudioClip }) {ck.begin();updateAudioTransient(clip.id, patch);};- // Detached audio can carry a playback rate; its timeline length is (out-in)/speed.- const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;- const len = (clip.out - clip.in) / speed;+ // Detached audio carries the picture's rate, so its length goes through it;+ // the slider shows one number — the average under a curve — and setting it+ // makes the rate uniform.+ const len = retimeOf(clip).len;+ const speed = retimeOf(clip).rate;const maxFade = maxClipFade(clip);// Commit closes the checkpoint setAudio opened (or opens+closes one for a// typed entry), so any adjustment lands as a single undo step.@@ -1506,13 +1541,13 @@ function AudioPanel({ clip }: { clip: AudioClip }) {scrubMax={Infinity}format={formatSpeed}parse={parseSpeedInput}- onDraft={(v) => setAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v })}- onCommit={(v) => commitAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v })}+ onDraft={(v) => setAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v, speedCurve: undefined })}+ onCommit={(v) => commitAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v, speedCurve: undefined })}/><ResetButtontitle="Reset speed"- show={Math.abs(speed - 1) > 1e-4}- onClick={() => commitAudio({ speed: undefined })}+ show={Math.abs(speed - 1) > 1e-4 || !!clip.speedCurve}+ onClick={() => commitAudio({ speed: undefined, speedCurve: undefined })}/></Row><Row label="Volume">diff --git a/site/src/cut/components/SpeedCurveStrip.tsx b/site/src/cut/components/SpeedCurveStrip.tsxnew file mode 100644index 00000000..efe82486--- /dev/null+++ b/site/src/cut/components/SpeedCurveStrip.tsx@@ -0,0 +1,471 @@+"use client";++import { Minus, Plus, RotateCcw, X } from "lucide-react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import {+ flatSpeedCurve,+ retimeOf,+ SPEED_CURVE_MAX,+ SPEED_CURVE_MIN,+ SPEED_CURVE_PRESETS,+ speedCurveOf,+ type Retime,+ type SpeedNode,+} from "@donkeycut/effects-kit";+import { startDrag } from "@/cut/lib/drag";+import { planFilmstrip, type FilmTile } from "@/cut/lib/filmstrip";+import { playheadAt, subscribePlayhead } from "@/cut/lib/playhead";+import { useSpeedCurveUi } from "@/cut/lib/speedCurveUi";+import { useEditor } from "@/cut/lib/store";+import type { MediaAsset, VideoClip } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++/**+ * The speed curve editor: a strip docked over the timeline that draws one+ * clip's rate across its footage. Left to right is the clip's trimmed source;+ * up and down is the rate on a log scale, 1× through the middle. Nodes are+ * the curve's control points: drag one to move it, click the graph to add+ * one on the curve, double-click a node to take it away. The picture behind+ * the graph is the footage at 1×, so a node lands on the moment it slows or+ * hurries. Drags scrub the preview to the node, so what plays there is on+ * screen while it is placed.+ *+ * Edits draft locally and commit on release through the store's one curve+ * setter, so every gesture is one undo step and every surface reads the+ * same map.+ */++const GRAPH_H = 116;+const PAD_X = 14;+const PAD_Y = 10;+/** Pixels within which a drag lands on a beat or the 1× line. */+const SNAP_PX = 6;+/** Closest two nodes may sit, source seconds. */+const MIN_GAP = 1 / 60;+const FRAME = 1 / 30;+const RATE_LINES = [0.1, 0.25, 0.5, 1, 2, 4, 10];++const LOG_MIN = Math.log10(SPEED_CURVE_MIN);+const LOG_MAX = Math.log10(SPEED_CURVE_MAX);++const clampRate = (r: number) => Math.min(SPEED_CURVE_MAX, Math.max(SPEED_CURVE_MIN, r));+/** A rate as people say it: 2×, 0.5×, 0.25×. */+const fmtRate = (r: number) => `${+r.toFixed(2)}×`;+const fmtSec = (s: number) => `${s.toFixed(1)}s`;++export function SpeedCurveStrip() {+ const clipId = useSpeedCurveUi((s) => s.clipId);+ const clip = useEditor((s) => (clipId ? s.clips.find((c) => c.id === clipId) : undefined));+ const selected = useEditor(+ (s) => !!clipId && s.selection?.kind === "clip" && s.selection.id === clipId+ );+ // The strip follows the clip it opened for: a selection elsewhere, or the+ // clip going away, closes it.+ useEffect(() => {+ if (clipId && (!clip || !selected)) useSpeedCurveUi.getState().close();+ }, [clipId, clip, selected]);+ if (!clip || !selected) return null;+ return <Strip key={clip.id} clip={clip} />;+}++function Strip({ clip }: { clip: VideoClip }) {+ const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));+ const picked = useEditor((s) =>+ s.selectedKey?.track === "speed" && s.selectedKey.id === clip.id ? s.selectedKey.t : null+ );+ const [draft, setDraft] = useState<SpeedNode[] | null>(null);+ // The axis a drag started on. Width is timeline time, so editing the curve+ // moves the ground under the cursor; holding the axis for the length of a+ // drag keeps the node under the pointer and the tiles still.+ const [heldAxis, setHeldAxis] = useState<Retime | null>(null);+ const nodes = useMemo(+ () => draft ?? speedCurveOf(clip) ?? flatSpeedCurve(clip),+ [draft, clip]+ );+ const rt = useMemo(() => retimeOf({ in: clip.in, out: clip.out, speedCurve: nodes }), [clip.in, clip.out, nodes]);++ const boxRef = useRef<HTMLDivElement | null>(null);+ const [width, setWidth] = useState(0);+ useLayoutEffect(() => {+ const box = boxRef.current;+ if (!box) return;+ const ro = new ResizeObserver(([e]) => setWidth(e.contentRect.width));+ ro.observe(box);+ setWidth(box.clientWidth);+ return () => ro.disconnect();+ }, []);++ const innerW = Math.max(1, width - PAD_X * 2);+ const innerH = GRAPH_H - PAD_Y * 2;+ // Left to right is the clip as it plays, the same axis the timeline bar+ // uses, so a node sits over the picture the bar shows at that moment.+ const axis = heldAxis ?? rt;+ const axisLen = Math.max(1e-3, axis.len);+ const xOf = (src: number) => PAD_X + (axis.tAt(src) / axisLen) * innerW;+ const srcOf = (x: number) =>+ axis.srcAt(Math.max(0, Math.min(axisLen, ((x - PAD_X) / innerW) * axisLen)));+ const yOf = (rate: number) =>+ PAD_Y + (1 - (Math.log10(clampRate(rate)) - LOG_MIN) / (LOG_MAX - LOG_MIN)) * innerH;+ const rateOf = (y: number) =>+ clampRate(Math.pow(10, LOG_MIN + (1 - (y - PAD_Y) / innerH) * (LOG_MAX - LOG_MIN)));++ const beats = useMemo(+ () => (asset?.beats?.beats ?? []).filter((b) => b >= clip.in && b <= clip.out),+ [asset?.beats, clip.in, clip.out]+ );++ const tiles = useMemo<FilmTile[]>(+ () => (asset && innerW > 1 ? stripTiles(asset, clip, innerW, axis) : []),+ [asset, clip, innerW, axis]+ );++ const curvePath = useMemo(() => {+ if (innerW <= 1) return "";+ const steps = Math.max(2, Math.min(400, Math.round(innerW / 2)));+ const pts: string[] = [];+ for (let i = 0; i <= steps; i++) {+ const x = PAD_X + (i / steps) * innerW;+ pts.push(`${x.toFixed(1)},${yOf(rt.rateAtSrc(srcOf(x))).toFixed(1)}`);+ }+ return `M${pts.join("L")}`;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [rt, axis, innerW, innerH]);++ // The playhead, mapped through the clip's map onto the source axis. One DOM+ // write per move.+ const playheadRef = useRef<HTMLDivElement | null>(null);+ const geom = useRef({ xOf, rt, start: clip.start, len: rt.len });+ const paintPlayhead = () => {+ const el = playheadRef.current;+ if (!el) return;+ const g = geom.current;+ const tLocal = playheadAt() - g.start;+ if (tLocal < -1e-6 || tLocal > g.len + 1e-6) {+ el.style.opacity = "0";+ return;+ }+ el.style.opacity = "1";+ el.style.left = `${g.xOf(g.rt.srcAt(tLocal))}px`;+ };+ // The map and the geometry change with every draft and resize; the line+ // reads the newest through the ref and repaints after each render.+ useEffect(() => {+ geom.current = { xOf, rt, start: clip.start, len: rt.len };+ paintPlayhead();+ });+ useEffect(() => subscribePlayhead(paintPlayhead), []);++ const pick = (src: number | null) => {+ useEditor.setState({+ selectedKey: src === null ? null : { kind: "clip", id: clip.id, t: src, track: "speed" },+ });+ };+ const commit = (next: SpeedNode[]) => {+ setDraft(null);+ useEditor.getState().setClipSpeedCurve(clip.id, next);+ };+ const seekToSrc = (src: number, list: SpeedNode[]) => {+ const map = retimeOf({ in: clip.in, out: clip.out, speedCurve: list });+ useEditor.getState().seek(clip.start + map.tAt(src));+ };++ /** Where a node may sit between its neighbours. */+ const bounds = (list: SpeedNode[], i: number) => ({+ lo: i > 0 ? list[i - 1][0] + MIN_GAP : clip.in,+ hi: i < list.length - 1 ? list[i + 1][0] - MIN_GAP : clip.out,+ });++ const insertAt = (src: number, rate: number, list: SpeedNode[]): SpeedNode[] => {+ const next: SpeedNode[] = [...list, [src, clampRate(rate)]];+ next.sort((a, b) => a[0] - b[0]);+ return next;+ };++ const addAtPlayhead = () => {+ const tLocal = Math.max(0, Math.min(rt.len, playheadAt() - clip.start));+ const src = Math.min(clip.out, Math.max(clip.in, rt.srcAt(tLocal)));+ if (nodes.some((n) => Math.abs(n[0] - src) < MIN_GAP)) return;+ const next = insertAt(src, rt.rateAtSrc(src), nodes);+ pick(src);+ commit(next);+ };++ const removePicked = () => {+ if (picked === null || nodes.length <= 1) return;+ const next = nodes.filter((n) => Math.abs(n[0] - picked) > 1e-6);+ if (next.length === nodes.length) return;+ pick(null);+ commit(next);+ };++ const nudge = (dSrc: number, rateScale: number) => {+ if (picked === null) return;+ const i = nodes.findIndex((n) => Math.abs(n[0] - picked) < 1e-6);+ if (i < 0) return;+ const { lo, hi } = bounds(nodes, i);+ const src = Math.min(hi, Math.max(lo, nodes[i][0] + dSrc));+ const rate = clampRate(nodes[i][1] * rateScale);+ const next = nodes.map((n, j) => (j === i ? ([src, rate] as SpeedNode) : n));+ pick(src);+ commit(next);+ seekToSrc(src, next);+ };++ const onGraphPointerDown = (e: React.PointerEvent<SVGSVGElement>) => {+ if (e.button !== 0) return;+ const rect = e.currentTarget.getBoundingClientRect();+ const x = e.clientX - rect.left;+ const src = Math.min(clip.out, Math.max(clip.in, srcOf(x)));+ if (nodes.some((n) => Math.abs(xOf(n[0]) - x) < SNAP_PX * 2)) return;+ const next = insertAt(src, rt.rateAtSrc(src), nodes);+ pick(src);+ commit(next);+ seekToSrc(src, next);+ };++ const onNodePointerDown = (e: React.PointerEvent, i: number) => {+ const node = nodes[i];+ pick(node[0]);+ setHeldAxis(axis);+ const x0 = xOf(node[0]);+ const y0 = yOf(node[1]);+ const { lo, hi } = bounds(nodes, i);+ let live: SpeedNode[] = nodes;+ startDrag(e, {+ onMove: (dx, dy, ev) => {+ let x = x0 + dx;+ let y = y0 + dy;+ if (!ev.altKey) {+ const beat = beats.find((b) => Math.abs(xOf(b) - x) <= SNAP_PX);+ if (beat !== undefined) x = xOf(beat);+ if (Math.abs(yOf(1) - y) <= SNAP_PX) y = yOf(1);+ }+ const src = Math.min(hi, Math.max(lo, srcOf(x)));+ const rate = rateOf(Math.min(GRAPH_H - PAD_Y, Math.max(PAD_Y, y)));+ live = nodes.map((n, j) => (j === i ? ([src, rate] as SpeedNode) : n));+ setDraft(live);+ pick(src);+ seekToSrc(src, live);+ },+ onUp: (_dx, _dy, moved) => {+ setHeldAxis(null);+ if (moved) commit(live);+ else seekToSrc(node[0], nodes);+ },+ });+ };++ const onKeyDown = (e: React.KeyboardEvent) => {+ const big = e.shiftKey;+ switch (e.key) {+ case "ArrowLeft":+ nudge(-(big ? FRAME * 10 : FRAME), 1);+ break;+ case "ArrowRight":+ nudge(big ? FRAME * 10 : FRAME, 1);+ break;+ case "ArrowUp":+ nudge(0, big ? 1.25 : 1.05);+ break;+ case "ArrowDown":+ nudge(0, 1 / (big ? 1.25 : 1.05));+ break;+ case "Delete":+ case "Backspace":+ removePicked();+ break;+ case "Escape":+ useSpeedCurveUi.getState().close();+ break;+ default:+ return;+ }+ e.preventDefault();+ e.stopPropagation();+ };++ const pickedRate = picked === null ? null : nodes.find((n) => Math.abs(n[0] - picked) < 1e-6)?.[1];++ return (+ <div+ className="flex min-w-0 flex-col border-t border-border bg-background outline-none"+ tabIndex={0}+ onKeyDown={onKeyDown}+ data-testid="speed-curve-strip"+ >+ <div className="flex h-8 items-center gap-1.5 px-2 text-[11px]">+ <span className="font-medium">Speed Curve</span>+ {pickedRate != null && (+ <span className="tabular-nums text-foreground/70">+ node {fmtRate(pickedRate)} at {fmtSec(rt.tAt(picked!))}+ </span>+ )}+ <span className="flex-1" />+ {SPEED_CURVE_PRESETS.map((p) => (+ <button+ key={p.id}+ type="button"+ title={p.hint}+ className="rounded px-1.5 py-0.5 text-foreground hover:bg-accent"+ onClick={() => {+ pick(null);+ setDraft(null);+ useEditor.getState().setClipSpeedPreset(clip.id, p.id);+ }}+ >+ {p.label}+ </button>+ ))}+ <span className="mx-1 h-4 w-px bg-border" />+ <IconButton title="Add a node at the playhead" onClick={addAtPlayhead}>+ <Plus className="size-3.5" />+ </IconButton>+ <IconButton+ title="Remove the picked node (Delete)"+ disabled={picked === null || nodes.length <= 1}+ onClick={removePicked}+ >+ <Minus className="size-3.5" />+ </IconButton>+ <IconButton+ title="Flatten to 1×"+ onClick={() => {+ pick(null);+ commit(flatSpeedCurve({ in: clip.in, out: clip.out, speed: 1 }));+ }}+ >+ <RotateCcw className="size-3.5" />+ </IconButton>+ <IconButton title="Close (Esc)" onClick={() => useSpeedCurveUi.getState().close()}>+ <X className="size-3.5" />+ </IconButton>+ </div>+ <div ref={boxRef} className="relative select-none overflow-hidden" style={{ height: GRAPH_H }}>+ {/* The footage at 1×, dimmed, so a node sits on its moment. */}+ <div className="pointer-events-none absolute inset-y-0" style={{ left: PAD_X, width: innerW }}>+ {tiles.map((t, i) => (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ key={i}+ src={t.src}+ alt=""+ draggable={false}+ className="absolute top-0 h-full object-cover opacity-30"+ style={{ left: t.left, width: t.width }}+ />+ ))}+ </div>+ <svg+ className="absolute inset-0 h-full w-full cursor-crosshair"+ onPointerDown={onGraphPointerDown}+ >+ {RATE_LINES.map((r) => (+ <g key={r}>+ <line+ x1={PAD_X}+ x2={PAD_X + innerW}+ y1={yOf(r)}+ y2={yOf(r)}+ stroke="currentColor"+ strokeOpacity={r === 1 ? 0.45 : 0.14}+ strokeDasharray={r === 1 ? undefined : "2 3"}+ />+ <text x={PAD_X + 3} y={yOf(r) - 2} fontSize={9} fill="currentColor" fillOpacity={0.85}>+ {fmtRate(r)}+ </text>+ </g>+ ))}+ {beats.map((b) => (+ <line+ key={b}+ x1={xOf(b)}+ x2={xOf(b)}+ y1={PAD_Y}+ y2={GRAPH_H - PAD_Y}+ stroke="#ff9f0a"+ strokeOpacity={0.5}+ />+ ))}+ <path d={curvePath} fill="none" stroke="#0a84ff" strokeWidth={2} />+ {nodes.map((n, i) => {+ const isPicked = picked !== null && Math.abs(n[0] - picked) < 1e-6;+ return (+ <circle+ key={i}+ cx={xOf(n[0])}+ cy={yOf(n[1])}+ r={isPicked ? 6 : 5}+ fill="white"+ stroke={isPicked ? "#0a84ff" : "rgba(0,0,0,0.5)"}+ strokeWidth={isPicked ? 2 : 1}+ className="cursor-move"+ onPointerDown={(e) => {+ e.stopPropagation();+ onNodePointerDown(e, i);+ }}+ onDoubleClick={(e) => {+ e.stopPropagation();+ if (nodes.length <= 1) return;+ pick(null);+ commit(nodes.filter((_, j) => j !== i));+ }}+ />+ );+ })}+ </svg>+ <div+ ref={playheadRef}+ className="pointer-events-none absolute top-0 h-full w-px bg-red-500"+ style={{ opacity: 0 }}+ />+ </div>+ </div>+ );+}++function IconButton({+ title,+ disabled,+ onClick,+ children,+}: {+ title: string;+ disabled?: boolean;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ title={title}+ disabled={disabled}+ onClick={onClick}+ className={cn(+ "grid size-6 place-items-center rounded text-foreground hover:bg-accent",+ disabled && "pointer-events-none opacity-40"+ )}+ >+ {children}+ </button>+ );+}++/** The strip's tiles: the same plan the clip's bar draws, laid across `w`+ * pixels — same map, same tile times, so the two pictures agree. */+function stripTiles(asset: MediaAsset, clip: VideoClip, w: number, retime: Retime): FilmTile[] {+ if (!asset.thumbs?.length || !asset.thumbStep) return [];+ return planFilmstrip({+ thumbs: asset.thumbs,+ thumbStep: asset.thumbStep,+ duration: asset.duration,+ aspect: (asset.width ?? 16) / Math.max(1, asset.height ?? 9),+ filmIn: clip.in,+ w,+ pps: w / Math.max(1e-3, retime.len),+ speed: retime.rate,+ retime,+ tileH: GRAPH_H,+ minTileW: 24,+ cuts: asset.sceneCuts,+ });+}diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 737b52cd..81228a05 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -58,7 +58,7 @@ import { useBrushUi } from "@/cut/lib/removal/brushUi";import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";import { formatTime, formatTimecode } from "@/cut/lib/time";-import { EFFECT_LABELS, type EffectId } from "@donkeycut/effects-kit";+import { EFFECT_LABELS, hasSpeedCurve, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";import { assetIsSilent, emptySubtitles, IMAGE_CLIP_SECONDS, isAudioTransition, SHAPE_LABELS, TRANSITION_MAX, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, type ShapeKind } from "@/cut/lib/types";import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionBoundaryKind, TransitionStyle, VideoClip } from "@/cut/lib/types";import { isLottieAsset } from "@/cut/lib/lottieAssets";@@ -623,7 +623,7 @@ export function Timeline() {// A row whose clips carry mask keys grows by the rail band, so the diamonds// sit fully below the clips with the usual row gap kept under them.const railFor = (list: { clip: VideoClip }[]) =>- list.some((sp) => sp.clip.mask?.kf?.length) ? KEYRAIL_EXTRA : 0;+ list.some((sp) => sp.clip.mask?.kf?.length || hasSpeedCurve(sp.clip)) ? KEYRAIL_EXTRA : 0;const rail0 = railFor(spans);const rowH0 = videoRowH(spans);// Per-upper-track spans: each track carries its own transitions, so its row@@ -3757,7 +3757,7 @@ function ClipView({const spine = lane === "clip";const loading = useEditor((s) => s.loadingMedia.has(asset.fileName));const baking = useMatteBakes((s) => s.jobs[clip.id]?.status === "running");- const speed = clipSpeed(clip);+ const rt = retimeOf(clip);// Every box is its clip's whole footprint. Clips never overlap — a// transition is a render-time blend at the cut, drawn as the bar above the// tracks — so a box's width is the clip's own length, whatever joins it.@@ -3766,7 +3766,7 @@ function ClipView({// out inside it — the strip, the dots — measures against this, not `w`.const barW = Math.max(10, w - CLIP_GAP);const filmIn = clip.in;- const filmOut = filmIn + span.len * speed;+ const filmOut = clip.out;const startFrame = useEdgeFrame(asset, filmIn, `${clip.id}:in`);const endFrame = useEdgeFrame(asset, filmOut, `${clip.id}:out`);@@ -3795,16 +3795,16 @@ function ClipView({filmIn,w,pps,- speed,+ rt,FILM_H,26,{ start: startFrame, end: endFrame },view),// eslint-disable-next-line react-hooks/exhaustive-deps- [asset, filmIn, w, pps, speed, startFrame, endFrame, filmGen, view]+ [asset, filmIn, w, pps, rt, startFrame, endFrame, filmGen, view]);- useTileFrames(boxRef, clip.id, asset, filmstrip, filmIn, w, pps, speed, onTileFrame);+ useTileFrames(boxRef, clip.id, asset, filmstrip, filmIn, w, pps, rt.key, onTileFrame);// The move gesture is the shared lane behavior (parting, snapping); its// verticality is the video placement system — the other tracks and the new@@ -3862,7 +3862,7 @@ function ClipView({const rect = e.currentTarget.getBoundingClientRect();onFrameMenu(e, {asset,- srcT: filmIn + ((e.clientX - rect.left) / pps) * speed,+ srcT: rt.srcAt((e.clientX - rect.left) / pps),from: { x: e.clientX, top: rect.top, height: rect.height },});}}@@ -3875,7 +3875,7 @@ function ClipView({className="tl-clip-wave pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-b from-[#59c09d] to-[#43b18d]"style={{ height: WAVE_H }}>- <WaveformCanvas asset={asset} from={filmIn} to={filmOut} w={barW} h={WAVE_H - 4} className="inset-x-0 inset-y-0.5" />+ <WaveformCanvas asset={asset} from={filmIn} to={filmOut} w={barW} h={WAVE_H - 4} map={rt.uniform ? undefined : (px) => rt.srcAt(px / pps)} className="inset-x-0 inset-y-0.5" /></div>)}{selected && (@@ -3910,13 +3910,22 @@ function ClipView({onToggle={() => useEditor.getState().updateClip(clip.id, { muted: !clip.muted })}/>)}- {(clip.speed ?? 1) !== 1 && (+ {!rt.uniform ? (<spanclassName="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"- title={`${clip.speed}× speed`}+ title={`Speed curve · ${+rt.rate.toFixed(2)}× on average`}>- {+(clip.speed ?? 1).toFixed(2)}×+ ∿ {+rt.rate.toFixed(1)}×</span>+ ) : (+ rt.rate !== 1 && (+ <span+ className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"+ title={`${rt.rate}× speed`}+ >+ {+rt.rate.toFixed(2)}×+ </span>+ ))}{!loading && (<HideChip@@ -3942,7 +3951,7 @@ function ClipView({) : null}</ClipMenu>)}- <ClipStrokeMarks clip={clip} spanStart={span.start} speed={speed} pps={pps} barW={barW} />+ <ClipStrokeMarks clip={clip} spanStart={span.start} retime={rt} pps={pps} barW={barW} />{/* Keys sit on the bar where they fall — pose and mask tracks both —so the animation is visible without opening the inspector. */}{(clip.kf ?? []).map((k) => (@@ -3958,7 +3967,7 @@ function ClipView({{/* Drawn wherever the source has a grid: on the band when there is one,along the bar's bottom edge when the clip plays silent. Every edgesnaps to them either way. */}- <BeatDots asset={asset} from={filmIn} to={filmOut} speed={speed} pps={pps} w={barW} />+ <BeatDots asset={asset} from={filmIn} to={filmOut} retime={rt} pps={pps} w={barW} /><spanclassName={cn(trimFor(barW), "tl-trim-l left-0")}onPointerDown={(e) => startLaneTrim(e, lane, clip.id, "l", ui)}@@ -3977,10 +3986,79 @@ function ClipView({boxH={hasWave ? VIDEO_H - 4 : FILM_H}hidden={!!drag}/>+ <ClipSpeedRail+ retime={rt}+ start={span.start}+ pps={pps}+ w={w}+ view={view}+ boxH={hasWave ? VIDEO_H - 4 : FILM_H}+ hidden={!!drag || offscreen || !!clip.mask?.kf?.length}+ /></>);}+/** A curved clip's pace, drawn on the rail under its box: the rate through+ * the clip's own timeline on a log scale, 1× as the dashed midline, so a+ * ramp reads at a glance without opening the editor. It shares the rail with+ * the mask keys and yields to them. */+function ClipSpeedRail({+ retime,+ start,+ pps,+ w,+ view,+ boxH,+ hidden,+}: {+ retime: Retime;+ start: number;+ pps: number;+ w: number;+ /** The stretch of the box the scroller shows — the sketch is drawn for+ * that slice, so a long clip at a deep zoom costs what is on screen. */+ view: { lo: number; hi: number };+ boxH: number;+ hidden: boolean;+}) {+ if (hidden || retime.uniform) return null;+ const barW = Math.max(10, w - CLIP_GAP);+ const from = Math.max(0, Math.min(barW, view.lo));+ const to = Math.max(from, Math.min(barW, view.hi));+ if (to - from < 1) return null;+ const h = 14;+ const lo = Math.log10(SPEED_CURVE_MIN);+ const hi = Math.log10(SPEED_CURVE_MAX);+ const yOf = (rate: number) => (1 - (Math.log10(rate) - lo) / (hi - lo)) * (h - 2) + 1;+ const step = 3;+ const pts: string[] = [];+ for (let x = from; x <= to; x += step) {+ pts.push(`${(x - from).toFixed(1)},${yOf(retime.rateAt(Math.min(retime.len, x / pps))).toFixed(1)}`);+ }+ const lastX = (to - from).toFixed(1);+ pts.push(`${lastX},${yOf(retime.rateAt(Math.min(retime.len, to / pps))).toFixed(1)}`);+ const mid = yOf(1).toFixed(1);+ const width = to - from;+ return (+ <div+ className="pointer-events-none absolute z-5"+ style={{ left: start * pps + from, top: boxH + 3, width, height: h + 2 }}+ >+ <svg width={width} height={h + 2} className="overflow-visible">+ <line x1={0} y1={mid} x2={width} y2={mid} stroke="currentColor" strokeOpacity={0.25} strokeDasharray="3 3" />+ <polyline+ points={`0,${h} ${pts.join(" ")} ${lastX},${h}`}+ fill="#0a84ff"+ fillOpacity={0.18}+ stroke="none"+ />+ <polyline points={pts.join(" ")} fill="none" stroke="#0a84ff" strokeWidth={1.5} strokeLinejoin="round" />+ </svg>+ </div>+ );+}+/** The clip's brush-stroke frames, as red tabs hanging from the bar's top* edge while its brush session is open. A stroke lives on the one frame it* was drawn on — the stage overlay shows it only there — so each tab points@@ -3990,13 +4068,13 @@ function ClipView({function ClipStrokeMarks({clip,spanStart,- speed,+ retime,pps,barW,}: {clip: VideoClip;spanStart: number;- speed: number;+ retime: Retime;pps: number;barW: number;}) {@@ -4014,14 +4092,14 @@ function ClipStrokeMarks({key={`s${t}`}className="tl-stroke-mark pointer-events-auto absolute top-0 z-5 flex h-3 w-3.5 cursor-pointer justify-center"style={{- left: Math.min(barW - 4, Math.max(4, ((t - clip.in) / speed) * pps)),+ left: Math.min(barW - 4, Math.max(4, retime.tAt(t) * pps)),transform: "translateX(-50%)",}}title="Brush stroke"onPointerDown={(e) => {e.stopPropagation();e.preventDefault();- useEditor.getState().seek(spanStart + (t - clip.in) / speed);+ useEditor.getState().seek(spanStart + retime.tAt(t));}}><span@@ -4389,7 +4467,7 @@ function filmstripFrames(filmIn: number,w: number,pps: number,- speed: number,+ retime: Retime,tileH: number,minTileW: number,edges?: { start: string | null; end: string | null },@@ -4414,7 +4492,8 @@ function filmstripFrames(filmIn,w,pps,- speed,+ speed: retime.rate,+ retime,tileH,minTileW,cuts: asset.sceneCuts,@@ -4451,7 +4530,8 @@ function useTileFrames(filmIn: number,w: number,pps: number,- speed: number,+ /** The clip's map, as a key: a changed rate re-plans the tiles. */+ mapKey: string,onFrame: () => void) {// The landed-frame re-render hands this hook a fresh `tiles` array with the@@ -4517,7 +4597,7 @@ function useTileFrames(scroller?.removeEventListener("scroll", schedule);};// Geometry names the plan; `tiles` itself rides the ref above.- }, [boxRef, clipId, asset, wanted, filmIn, w, pps, speed, onFrame]);+ }, [boxRef, clipId, asset, wanted, filmIn, w, pps, mapKey, onFrame]);}/** The exact source frame at a clip edge. Returns null (the nearest sampled@@ -4813,6 +4893,7 @@ function WaveformCanvas({to,w,h,+ map,className,}: {asset: MediaAsset;@@ -4820,6 +4901,9 @@ function WaveformCanvas({to: number;w: number;h: number;+ /** Source second at a pixel across the strip, for a clip whose rate changes+ * through the footage; absent, the strip runs linearly from `from` to `to`. */+ map?: (px: number) => number;className?: string;}) {const peaks = asset.peaks;@@ -4839,8 +4923,8 @@ function WaveformCanvas({peaks={peaks}gain={gain}duration={asset.duration}- from={from + (to - from) * (t.left / width)}- to={from + (to - from) * ((t.left + t.tw) / width)}+ from={map ? map(t.left) : from + (to - from) * (t.left / width)}+ to={map ? map(t.left + t.tw) : from + (to - from) * ((t.left + t.tw) / width)}left={t.left}tw={t.tw}h={h}@@ -4944,15 +5028,14 @@ function writeBeats(assetId: string, edit: (beats: number[]) => number[]) {function addBeatAt(e: React.PointerEvent<HTMLElement>,asset: MediaAsset,- clip: { in: number; speed?: number },+ clip: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[] },pps: number) {e.preventDefault();e.stopPropagation();const rect = e.currentTarget.getBoundingClientRect();- const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;useEditor.getState().pushHistory();- writeBeats(asset.id, (list) => [...list, clip.in + ((e.clientX - rect.left) / pps) * speed]);+ writeBeats(asset.id, (list) => [...list, retimeOf(clip).srcAt((e.clientX - rect.left) / pps)]);}/**@@ -4965,8 +5048,7 @@ function BeatDot({assetId,duration,t,- from,- speed,+ retime,pps,w,}: {@@ -4975,9 +5057,8 @@ function BeatDot({duration: number;/** The beat, source seconds. */t: number;- /** The bar's own source window start and rate. */- from: number;- speed: number;+ /** The bar's own map from its footage onto the timeline. */+ retime: Retime;pps: number;/** Visible bar width, px, for parking the edge dots inside it. */w: number;@@ -4986,7 +5067,7 @@ function BeatDot({<spanclassName="tl-beat absolute bottom-0 z-5 grid h-3.5 w-3 cursor-ew-resize place-items-end justify-center pb-[3px]"style={{- left: Math.min(w - 4, Math.max(4, ((t - from) / speed) * pps)),+ left: Math.min(w - 4, Math.max(4, retime.tAt(t) * pps)),transform: "translateX(-50%)",}}title="Drag to move, double-click to remove"@@ -5004,7 +5085,9 @@ function BeatDot({}// Rounded the way the grid stores, so the moved beat is found again.const next =- Math.round(Math.min(duration, Math.max(0, t + (dx / pps) * speed)) * 1000) / 1000;+ Math.round(+ Math.min(duration, Math.max(0, retime.srcAt(retime.tAt(t) + dx / pps))) * 1000+ ) / 1000;const at = live;writeBeats(assetId, (list) => list.map((b) => (b === at ? next : b)));live = next;@@ -5028,14 +5111,14 @@ function BeatDots({asset,from,to,- speed,+ retime,pps,w,}: {asset: MediaAsset;from: number;to: number;- speed: number;+ retime: Retime;pps: number;w: number;}) {@@ -5051,8 +5134,7 @@ function BeatDots({assetId={asset.id}duration={asset.duration}t={b}- from={from}- speed={speed}+ retime={retime}pps={pps}w={w}/>@@ -5105,7 +5187,7 @@ function AudioView({// The bar is drawn a gutter narrower than the footprint; what sits inside// it measures against that.const barW = Math.max(10, w - CLIP_GAP);- const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;+ const rt = retimeOf(clip);// The fade being dragged, held here rather than in the grip: the ramp line// and the waveform's clip both follow it, so all three move as one.const [liveFade, setLiveFade] = useState<{ side: "in" | "out"; v: number } | null>(null);@@ -5154,9 +5236,9 @@ function AudioView({className="pointer-events-none absolute inset-0"style={{ clipPath: fadeClipPath(fadeInPx, fadeOutPx, barW) }}>- <WaveformCanvas asset={asset} from={clip.in} to={clip.out} w={barW} h={AUDIO_H - 8} className="inset-x-0 inset-y-1" />+ <WaveformCanvas asset={asset} from={clip.in} to={clip.out} w={barW} h={AUDIO_H - 8} map={rt.uniform ? undefined : (px) => rt.srcAt(px / pps)} className="inset-x-0 inset-y-1" /></div>- <BeatDots asset={asset} from={clip.in} to={clip.out} speed={speed} pps={pps} w={barW} />+ <BeatDots asset={asset} from={clip.in} to={clip.out} retime={rt} pps={pps} w={barW} /><FadeEnvelope inPx={fadeInPx} outPx={fadeOutPx} barW={barW} /><FadeGrip clip={clip} side="in" pps={pps} barW={barW} fade={fadeIn} live={liveFade?.side === "in"} onLive={setLiveFade} /><FadeGrip clip={clip} side="out" pps={pps} barW={barW} fade={fadeOut} live={liveFade?.side === "out"} onLive={setLiveFade} />diff --git a/site/src/cut/lib/speedCurveUi.ts b/site/src/cut/lib/speedCurveUi.tsnew file mode 100644index 00000000..b3f93c48--- /dev/null+++ b/site/src/cut/lib/speedCurveUi.ts@@ -0,0 +1,20 @@+"use client";++import { create } from "zustand";++/**+ * Which clip's speed curve is open in the strip over the timeline, if any.+ * The Inspector's Speed row opens it, the strip closes itself, and any+ * selection that leaves the clip closes it too.+ */+interface SpeedCurveUi {+ clipId: string | null;+ open: (clipId: string) => void;+ close: () => void;+}++export const useSpeedCurveUi = create<SpeedCurveUi>((set) => ({+ clipId: null,+ open: (clipId) => set({ clipId }),+ close: () => set({ clipId: null }),+}));