Open source CapCut alternative.
TypeScript
feat(site): clip speed, cross-dissolve, and timeline multi-select
David Le813dfc0fc4e7
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 9440d237..75286ea7 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -339,6 +339,14 @@ function ChatSession({const busy = status === "submitted" || status === "streaming";+ // Coalesce every edit the assistant makes in one turn into a single undo+ // step, so ⌘Z reverts the whole turn rather than one tool call at a time.+ useEffect(() => {+ if (!busy) return;+ useEditor.getState().beginHistoryBatch();+ return () => useEditor.getState().endHistoryBatch();+ }, [busy]);+// Keep the thread saved (so it shows up in the Threads panel) as it grows.useEffect(() => {if (messages.length === 0) return;diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 77cd5009..894125b7 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -16,7 +16,15 @@ import { Textarea } from "@/components/ui/textarea";import { useEditor } from "@/cut/lib/store";import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS } from "@/cut/lib/textRender";import { formatTime } from "@/cut/lib/time";-import { FONTS, type AudioClip, type TextOverlay, type VideoClip } from "@/cut/lib/types";+import {+ FONTS,+ SPEED_MAX,+ SPEED_MIN,+ TRANSITION_MAX,+ type AudioClip,+ type TextOverlay,+ type VideoClip,+} from "@/cut/lib/types";import { cn } from "@/lib/utils";const SWATCHES = ["#FFFFFF", "#111114", "#FFD60A", "#FF375F", "#0A84FF", "#30D158"];@@ -131,11 +139,11 @@ export function Inspector() {return (<aside className="flex min-h-0 flex-col overflow-y-auto border-l border-border bg-card">{clip ? (- <ClipPanel clip={clip} />+ <ClipPanel key={clip.id} clip={clip} />) : audio ? (- <AudioPanel clip={audio} />+ <AudioPanel key={audio.id} clip={audio} />) : overlay ? (- <TextPanel overlay={overlay} />+ <TextPanel key={overlay.id} overlay={overlay} />) : null}</aside>);@@ -165,6 +173,17 @@ const Value = ({ children, className }: { children: React.ReactNode; className?:function ClipPanel({ clip }: { clip: VideoClip }) {const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));const updateClip = useEditor((s) => s.updateClip);+ // A cross-dissolve dissolves this clip into the next one, so only offer it+ // when there is a next clip on the track.+ const hasNext = useEditor((s) => {+ const i = s.clips.findIndex((c) => c.id === clip.id);+ return i >= 0 && i < s.clips.length - 1;+ });+ const [speedDraft, setSpeedDraft] = useState<number | null>(null);+ const [xfadeDraft, setXfadeDraft] = useState<number | null>(null);+ const speed = speedDraft ?? clip.speed ?? 1;+ const xfade = xfadeDraft ?? clip.transition ?? 0;+ const speedLen = (clip.out - clip.in) / (speed > 0 ? speed : 1);return (<><PanelTitle>Video clip</PanelTitle>@@ -172,10 +191,44 @@ function ClipPanel({ clip }: { clip: VideoClip }) {<div className="mb-1.5 truncate border-b border-border pb-2.5 text-xs font-medium" title={asset?.name}>{asset?.name}</div>- <Row label="Length"><Value>{formatTime(clip.out - clip.in)}</Value></Row>+ <Row label="Length"><Value>{formatTime(speedLen)}</Value></Row><Row label="Trim"><Value>{formatTime(clip.in)} – {formatTime(clip.out)}</Value></Row>+ <Row label="Speed">+ <Slider+ className="clip-speed data-horizontal:w-24"+ min={SPEED_MIN}+ max={SPEED_MAX}+ step={0.05}+ value={speed}+ onValueChange={(v) => setSpeedDraft(Number(v))}+ onValueCommitted={() => {+ if (speedDraft != null) useEditor.getState().setClipSpeed(clip.id, speedDraft);+ setSpeedDraft(null);+ }}+ />+ <Value className="w-9 text-right text-muted-foreground">{speed.toFixed(2)}×</Value>+ </Row>+ {hasNext && (+ <Row label="Crossfade">+ <Slider+ className="clip-xfade data-horizontal:w-24"+ min={0}+ max={TRANSITION_MAX}+ step={0.1}+ value={xfade}+ onValueChange={(v) => setXfadeDraft(Number(v))}+ onValueCommitted={() => {+ if (xfadeDraft != null) useEditor.getState().setClipTransition(clip.id, xfadeDraft);+ setXfadeDraft(null);+ }}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {xfade < 0.05 ? "Off" : `${xfade.toFixed(1)}s`}+ </Value>+ </Row>+ )}<Row label="Mute audio"><Switchchecked={clip.muted}@@ -229,8 +282,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;// A fade can take at most half the clip so in+out never overlap.- const maxFade = Math.max(0.1, Math.round(((clip.out - clip.in) / 2) * 10) / 10);+ const maxFade = Math.max(0.1, Math.round((len / 2) * 10) / 10);return (<><PanelTitle>Soundtrack</PanelTitle>@@ -238,7 +294,7 @@ function AudioPanel({ clip }: { clip: AudioClip }) {<div className="mb-1.5 truncate border-b border-border pb-2.5 text-xs font-medium" title={asset?.name}>{asset?.name}</div>- <Row label="Length"><Value>{formatTime(clip.out - clip.in)}</Value></Row>+ <Row label="Length"><Value>{formatTime(len)}</Value></Row><Row label="Starts at"><Value>{formatTime(clip.start)}</Value></Row><Row label="Volume"><Sliderdiff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 6b58555a..7d83b599 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -1,7 +1,7 @@"use client";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { AudioLines, EllipsisVertical, Pause, Play, Plus, Scissors, SkipBack, Trash2, Type, VolumeX } from "lucide-react";+import { AudioLines, Blend, EllipsisVertical, Pause, Play, Plus, Scissors, SkipBack, Trash2, Type, VolumeX } from "lucide-react";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -13,7 +13,7 @@ import { Slider } from "@/components/ui/slider";import { clearAssetDrag, draggedAssetId, draggingAssetId, hasAssetDrag } from "@/cut/lib/assetDrag";import { startDrag } from "@/cut/lib/drag";import { ensurePeaks } from "@/cut/lib/media";-import { clipLen, getClipSpans, TIMELINE_H_MAX, totalDuration, useEditor } from "@/cut/lib/store";+import { clipLen, clipSpeed, getClipSpans, TIMELINE_H_MAX, totalDuration, useEditor } from "@/cut/lib/store";import { formatTime, formatTimecode } from "@/cut/lib/time";import type { AudioClip, ClipSpan, MediaAsset, SubtitleCue, TextOverlay } from "@/cut/lib/types";import { cn } from "@/lib/utils";@@ -78,11 +78,18 @@ export function Timeline() {const assets = useEditor((s) => s.assets);const pps = useEditor((s) => s.pxPerSec);const timelineH = useEditor((s) => s.timelineH);- const selection = useEditor((s) => s.selection);+ const multiSelection = useEditor((s) => s.multiSelection);const subtitles = useEditor((s) => s.subtitles);const scrollRef = useRef<HTMLDivElement>(null);const innerRef = useRef<HTMLDivElement>(null);+ // Membership set so every track can highlight all selected items, not just+ // the primary one.+ const selKeys = useMemo(+ () => new Set(multiSelection.map((x) => (x ? `${x.kind}:${x.id}` : ""))),+ [multiSelection]+ );+const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);const total = totalDuration(clips);const contentW = Math.max(total * pps + PAD_END, 900);@@ -216,8 +223,13 @@ export function Timeline() {const t = (el.scrollLeft + px - PAD_SIDE) / cur;zoomTo(cur * Math.exp(-e.deltaY * 0.012), t, px);} else if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {- e.preventDefault();- el.scrollLeft += e.deltaY;+ // When the tracks overflow vertically, let the wheel scroll them;+ // otherwise map vertical wheel to horizontal panning (the timeline is+ // mostly wide).+ if (el.scrollHeight <= el.clientHeight) {+ e.preventDefault();+ el.scrollLeft += e.deltaY;+ }}};el.addEventListener("wheel", onWheel, { passive: false });@@ -339,10 +351,10 @@ export function Timeline() {variant="ghost"size="sm"title="Delete (⌫)"- disabled={!selection}+ disabled={multiSelection.length === 0}onClick={() => useEditor.getState().deleteSelection()}>- <Trash2 /> Delete+ <Trash2 /> {multiSelection.length > 1 ? `Delete ${multiSelection.length}` : "Delete"}</Button><Transport total={total} />@@ -361,11 +373,11 @@ export function Timeline() {</Button></div>- <div ref={scrollRef} className="tl-scroll min-h-0 flex-1 overflow-x-auto overflow-y-hidden">- <div className="h-full" style={{ width: contentW + PAD_SIDE * 2 }}>+ <div ref={scrollRef} className="tl-scroll min-h-0 flex-1 overflow-auto">+ <div className="min-h-full" style={{ width: contentW + PAD_SIDE * 2 }}><divref={innerRef}- className="tl-content relative h-full pb-2"+ className="tl-content relative min-h-full pb-2"style={{ width: contentW, marginLeft: PAD_SIDE }}><Ruler pps={pps} width={contentW} onScrub={scrub} />@@ -404,7 +416,7 @@ export function Timeline() {span={span}index={i}pps={pps}- selected={selection?.kind === "clip" && selection.id === span.clip.id}+ selected={selKeys.has(`clip:${span.clip.id}`)}drag={dragInfo}insertAtIndex={assetDrop ? assetDrop.index : null}insertLen={assetDrop ? assetDrop.len : 0}@@ -413,6 +425,25 @@ export function Timeline() {onDrop={onClipDrop}/>))}+ {/* Cross-dissolve markers sit over the overlap between two clips. */}+ {!clipDrag &&+ spans.map((span) =>+ span.transitionOut > 0 ? (+ <div+ key={`xf-${span.clip.id}`}+ className="tl-xfade pointer-events-none absolute z-6 flex -translate-x-1/2 items-center justify-center rounded-full bg-[#0a84ff] text-white shadow-[0_0_0_2px_rgba(255,255,255,0.9)]"+ style={{+ left: (span.start + span.len - span.transitionOut / 2) * pps,+ top: (VIDEO_H - 4) / 2 - 8,+ width: 16,+ height: 16,+ }}+ title={`Cross-dissolve ${span.transitionOut.toFixed(1)}s`}+ >+ <Blend className="size-2.5" />+ </div>+ ) : null+ )}</div>{audioClips.length > 0 && (@@ -423,7 +454,7 @@ export function Timeline() {clip={a}asset={assets.find((x) => x.id === a.assetId)}pps={pps}- selected={selection?.kind === "audio" && selection.id === a.id}+ selected={selKeys.has(`audio:${a.id}`)}/>))}</div>@@ -449,7 +480,7 @@ export function Timeline() {top={row * TEXT_H}baseRow={baseRow}laneCount={overlayLanes.count}- selected={selection?.kind === "text" && selection.id === o.id}+ selected={selKeys.has(`text:${o.id}`)}onLaneDrag={onTextLaneDrag}onLaneDrop={onTextLaneDrop}/>@@ -469,7 +500,7 @@ export function Timeline() {key={c.id}cue={c}pps={pps}- selected={selection?.kind === "cue" && selection.id === c.id}+ selected={selKeys.has(`cue:${c.id}`)}/>))}</div>@@ -667,12 +698,14 @@ function ClipView({// the clip and the leading area dims as "hidden"; release collapses it.const [trim, setTrim] = useState<{ side: "l"; in0: number } | { side: "r" } | null>(null);const { clip, asset } = span;+ const speed = clipSpeed(clip);const w = span.len * pps;const left = span.start * pps;const trimL = trim?.side === "l" ? trim : null;const stripIn = trimL ? Math.min(clip.in, trimL.in0) : clip.in;- const hidPx = trimL ? Math.max(0, (clip.in - trimL.in0) * pps) : 0;- const boxW = trimL ? (clip.out - stripIn) * pps : w;+ // Source seconds → timeline px goes through the clip's speed.+ const hidPx = trimL ? Math.max(0, ((clip.in - trimL.in0) / speed) * pps) : 0;+ const boxW = trimL ? ((clip.out - stripIn) / speed) * pps : w;const isDragged = drag?.id === clip.id;// Neighbors part to make room for the open slot.const reorderShift =@@ -696,16 +729,20 @@ function ClipView({const imgW = Math.max(26, Math.round((VIDEO_H - 4) * aspect));const count = Math.min(120, Math.ceil(boxW / imgW));return Array.from({ length: count }, (_, k) => {- const timeAt = stripIn + (k * imgW + imgW / 2) / pps;+ const timeAt = stripIn + ((k * imgW + imgW / 2) / pps) * speed;const idx = Math.min(asset.thumbs!.length - 1,Math.max(0, Math.floor(timeAt / asset.thumbStep!)));return { src: asset.thumbs![idx], left: k * imgW, width: imgW };});- }, [asset, stripIn, boxW, pps]);+ }, [asset, stripIn, boxW, pps, speed]);const onBody = (e: React.PointerEvent) => {+ if (e.metaKey || e.shiftKey) {+ useEditor.getState().toggleSelect({ kind: "clip", id: clip.id });+ return;+ }const s = useEditor.getState();s.select({ kind: "clip", id: clip.id });// Clicking anywhere on the timeline moves the playhead — clips included.@@ -731,18 +768,28 @@ function ClipView({});};+ // Shift later titles/captions by however much this clip's footprint changed.+ const rippleTrim = (len0: number) => {+ const c = useEditor.getState().clips.find((x) => x.id === clip.id);+ if (c) useEditor.getState().rippleShift(span.start + len0, clipLen(c) - len0);+ };+const onTrimLeft = (e: React.PointerEvent) => {const s = useEditor.getState();s.select({ kind: "clip", id: clip.id });s.pushHistory();const in0 = clip.in;+ const len0 = span.len;setTrim({ side: "l", in0 });startDrag(e, {onMove: (dx) => {- const nin = Math.min(clip.out - 0.15, Math.max(0, in0 + dx / pps));+ const nin = Math.min(clip.out - 0.15, Math.max(0, in0 + (dx / pps) * speed));s.updateClipTransient(clip.id, { in: nin });},- onUp: () => setTrim(null),+ onUp: () => {+ setTrim(null);+ rippleTrim(len0);+ },});};@@ -752,12 +799,16 @@ function ClipView({s.pushHistory();setTrim({ side: "r" });const out0 = clip.out;+ const len0 = span.len;startDrag(e, {onMove: (dx) => {- const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + dx / pps));+ const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + (dx / pps) * speed));s.updateClipTransient(clip.id, { out: nout });},- onUp: () => setTrim(null),+ onUp: () => {+ setTrim(null);+ rippleTrim(len0);+ },});};@@ -815,6 +866,14 @@ function ClipView({<VolumeX className="size-3" /></span>)}+ {(clip.speed ?? 1) !== 1 && (+ <span+ className="tl-speed-chip absolute right-1.5 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`}+ >+ {+(clip.speed ?? 1).toFixed(2)}×+ </span>+ )}<DropdownMenu><DropdownMenuTriggerrender={@@ -906,6 +965,10 @@ function AudioView({if (!asset) return null;const onBody = (e: React.PointerEvent) => {+ if (e.metaKey || e.shiftKey) {+ useEditor.getState().toggleSelect({ kind: "audio", id: clip.id });+ return;+ }const s = useEditor.getState();s.select({ kind: "audio", id: clip.id });s.seek(clip.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / pps);@@ -999,6 +1062,10 @@ function TextBar({const w = Math.max(8, (o.end - o.start) * pps);const onBody = (e: React.PointerEvent) => {+ if (e.metaKey || e.shiftKey) {+ useEditor.getState().toggleSelect({ kind: "text", id: o.id });+ return;+ }const s = useEditor.getState();s.select({ kind: "text", id: o.id });s.pushHistory();@@ -1076,6 +1143,10 @@ function SubBar({ cue, pps, selected }: { cue: SubtitleCue; pps: number; selecte};const onBody = (e: React.PointerEvent) => {+ if (e.metaKey || e.shiftKey) {+ useEditor.getState().toggleSelect({ kind: "cue", id: cue.id });+ return;+ }const s = useEditor.getState();s.select({ kind: "cue", id: cue.id });s.pushHistory();diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex efd66ef9..f622c07b 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -1,7 +1,7 @@"use client";import { useEffect, type RefObject } from "react";-import { getClipSpans, totalDuration, useEditor } from "@/cut/lib/store";+import { clipSpeed, getClipSpans, totalDuration, useEditor } from "@/cut/lib/store";import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";// The canvas backing store is the full frame resolution (1080×1920 or@@ -20,7 +20,6 @@ class Engine {private audioEls = new Map<string, HTMLAudioElement>();private raf = 0;private activeClipId: string | null = null;- private lastWritten = -1;private disposed = false;constructor(private canvas: HTMLCanvasElement) {@@ -54,36 +53,58 @@ class Engine {return el;}- private switchTo(span: ClipSpan, t: number, play: boolean) {+ /** Seek/rate/play one clip's element toward its frame at timeline time `t`,+ * without touching any other element (the caller pauses stale ones). */+ private prepare(span: ClipSpan, t: number, play: boolean, muted: boolean) {const el = this.videoFor(span.asset);- for (const [assetId, other] of this.videoEls) {- if (assetId !== span.asset.id && !other.paused) other.pause();- }- const target = span.clip.in + Math.max(0, t - span.start);+ const speed = clipSpeed(span.clip);+ if (el.playbackRate !== speed) el.playbackRate = speed;+ const target = span.clip.in + Math.max(0, t - span.start) * speed;+ // While playing, the element is its own clock and advances on its own, so+ // only re-seek on a real jump (a clip switch or a scrub) — never for the+ // sub-second lag between this frame's `target` (built from last frame's+ // clock read) and the freely-running element. At high speed that lag is+ // `speed × frameInterval` every frame, which a tight threshold would seek+ // backward each tick, stalling playback. When paused (scrubbing) keep it+ // tight so the frame under the mouse tracks precisely.// Let an in-flight seek finish before issuing the next one — restarting- // the decoder every mousemove makes scrubbing stutter. The tick loop- // re-applies the newest target as soon as the element is free.- if (Math.abs(el.currentTime - target) > 0.05 && !el.seeking) el.currentTime = target;- this.activeClipId = span.clip.id;- if (play) void el.play().catch(() => {});+ // the decoder every mousemove makes scrubbing stutter.+ const tol = play ? 0.34 : 0.05;+ if (Math.abs(el.currentTime - target) > tol && !el.seeking) el.currentTime = target;+ el.muted = muted;+ if (play) {+ if (el.paused && el.readyState >= 2) void el.play().catch(() => {});+ } else if (!el.paused) {+ el.pause();+ }return el;}- private draw(el: HTMLVideoElement | null, clip?: VideoClip) {+ private pauseExcept(keep: Set<string>) {+ for (const [assetId, el] of this.videoEls) {+ if (!keep.has(assetId) && !el.paused) el.pause();+ }+ }++ private drawLayer(el: HTMLVideoElement | null, clip: VideoClip | undefined, clear: boolean, alpha: number) {const ctx = this.canvas.getContext("2d");if (!ctx) return;const W = this.canvas.width;const H = this.canvas.height;if (!el) {- ctx.fillStyle = "#000";- ctx.fillRect(0, 0, W, H);+ if (clear) {+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, W, H);+ }return;}// Mid-seek the element has no decodable frame; keep the previous frame// on the canvas instead of strobing black (matters while skimming).if (el.readyState < 2 || !el.videoWidth) return;- ctx.fillStyle = "#000";- ctx.fillRect(0, 0, W, H);+ if (clear) {+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, W, H);+ }const fill = clip?.fit === "fill";const scale = fill? Math.max(W / el.videoWidth, H / el.videoHeight)@@ -99,7 +120,33 @@ class Engine {dx = -(dw - W) * kx;dy = -(dh - H) * ky;}+ const prevAlpha = ctx.globalAlpha;+ ctx.globalAlpha = Math.max(0, Math.min(1, alpha));ctx.drawImage(el, dx, dy, dw, dh);+ ctx.globalAlpha = prevAlpha;+ }++ /** Draw `masterSpan` full-frame, and if a cross-dissolve into the next span+ * is live at time `t`, draw that next clip over it at ramping opacity — a+ * true A·(1−α)+B·α blend. Returns the master element (the playback clock). */+ private composite(masterSpan: ClipSpan, spans: ClipSpan[], t: number, play: boolean) {+ const masterEl = this.prepare(masterSpan, t, play, masterSpan.clip.muted);+ this.activeClipId = masterSpan.clip.id;+ const keep = new Set([masterSpan.asset.id]);+ const next = spans[spans.indexOf(masterSpan) + 1];+ let incEl: HTMLVideoElement | null = null;+ let alpha = 0;+ // Same asset on both sides shares one <video>, so it can't show two frames+ // at once — fall back to a hard cut there.+ if (masterSpan.transitionOut > 0 && next && t >= next.start && next.asset.id !== masterSpan.asset.id) {+ alpha = (t - next.start) / masterSpan.transitionOut;+ incEl = this.prepare(next, t, play, true); // the outgoing clip keeps the audio+ keep.add(next.asset.id);+ }+ this.pauseExcept(keep);+ this.drawLayer(masterEl, masterSpan.clip, true, 1);+ if (incEl) this.drawLayer(incEl, next!.clip, false, alpha);+ return masterEl;}private syncSoundtrack(t: number, playing: boolean) {@@ -115,7 +162,9 @@ class Engine {el.preload = "auto";this.audioEls.set(a.id, el);}- const len = Math.max(0.1, a.out - a.in);+ // Detached audio can carry its video clip's rate; footprint is (out-in)/speed.+ const speed = a.speed && a.speed > 0 ? a.speed : 1;+ const len = Math.max(0.1, (a.out - a.in) / speed);const active = playing && t >= a.start && t < a.start + len;if (active) {// Fade envelope: linear ramps at either end of the clip.@@ -126,7 +175,8 @@ class Engine {if (fi > 0 && rel < fi) gain *= rel / fi;if (fo > 0 && rel > len - fo) gain *= Math.max(0, (len - rel) / fo);el.volume = Math.max(0, Math.min(1, a.volume * gain));- const expected = a.in + (t - a.start);+ if (el.playbackRate !== speed) el.playbackRate = speed;+ const expected = a.in + rel * speed;if (Math.abs(el.currentTime - expected) > 0.25) el.currentTime = expected;if (el.paused) void el.play().catch(() => {});} else if (!el.paused) {@@ -150,17 +200,16 @@ class Engine {const total = totalDuration(s.clips);if (spans.length === 0) {- this.draw(null);+ this.pauseExcept(new Set());+ this.drawLayer(null, undefined, true, 1);this.syncSoundtrack(0, false);if (s.playing) useEditor.setState({ playing: false, currentTime: 0 });return;}let t = Math.min(s.currentTime, total);- const externalSeek = Math.abs(t - this.lastWritten) > 0.15;if (!s.playing) {- for (const el of this.videoEls.values()) if (!el.paused) el.pause();// iMovie skimming: while the mouse hovers the timeline, preview the// frame under it. The playhead (currentTime) is never touched.const pt =@@ -168,9 +217,7 @@ class Engine {const span =spans.find((sp) => pt >= sp.start && pt < sp.start + sp.len) ??spans[spans.length - 1];- const el = this.switchTo(span, Math.min(pt, span.start + span.len), false);- this.lastWritten = t;- this.draw(el, span.clip);+ this.composite(span, spans, Math.min(pt, span.start + span.len), false);this.syncSoundtrack(t, false);return;}@@ -179,21 +226,18 @@ class Engine {if (!span) {// Reached the end of the last clip.useEditor.setState({ playing: false, currentTime: total });- this.lastWritten = total;- for (const el of this.videoEls.values()) el.pause();+ this.pauseExcept(new Set());this.syncSoundtrack(total, false);return;}- let el = this.videoFor(span.asset);- if (span.clip.id !== this.activeClipId || externalSeek) {- el = this.switchTo(span, t, true);- }- el.muted = span.clip.muted;- if (el.paused && el.readyState >= 2) void el.play().catch(() => {});+ // Prime the master element (and any dissolve partner) and read the clock.+ let el = this.composite(span, spans, t, true);- // The active element is the master clock.- const derived = span.start + (el.currentTime - span.clip.in);+ // The active element is the master clock; source time maps back through+ // the clip's speed.+ const speed = clipSpeed(span.clip);+ const derived = span.start + (el.currentTime - span.clip.in) / speed;if (Math.abs(derived - t) < 1.5) {t = Math.max(span.start, Math.min(derived, span.start + span.len));}@@ -203,23 +247,23 @@ class Engine {const idx = spans.indexOf(span);const next = spans[idx + 1];if (next) {- t = next.start + 0.0001;+ // Jump past the finished clip's whole footprint (including any+ // cross-dissolve overlap), not back to next.start — which still sits+ // inside the outgoing clip's footprint, so find() would re-pick the+ // clip we just finished and playback would ping-pong across the+ // dissolve forever.+ t = Math.max(next.start + 0.0001, span.start + span.len);span = next;- el = this.switchTo(next, t, true);- el.muted = next.clip.muted;+ el = this.composite(next, spans, t, true);} else {useEditor.setState({ playing: false, currentTime: total });- this.lastWritten = total;el.pause();- this.draw(el, span.clip);this.syncSoundtrack(total, false);return;}}- this.lastWritten = t;useEditor.setState({ currentTime: t });- this.draw(el, span.clip);this.syncSoundtrack(t, true);}}diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 36b10d19..390387bd 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -8,9 +8,15 @@ const r = (n: number) => Math.round(n * 100) / 100;* Compact JSON snapshot of everything the assistant should know: the cut,* the selection, what's on screen, and every user-facing setting. Sent with* each message and served by the get_state tool.+ *+ * `fullCues` includes the entire transcript. The per-message snapshot leaves+ * it off (a long transcript would inflate every turn's token cost, even ones+ * that never touch captions); the get_state tool passes it so the model can+ * pull every cue on demand.*/-export function buildAiContext() {+export function buildAiContext(opts?: { fullCues?: boolean }) {const s = useEditor.getState();+ const cueCap = opts?.fullCues ? Infinity : 60;const spans = getClipSpans(s.clips, s.assets);const duration = totalDuration(s.clips);const assetById = new Map(s.assets.map((a) => [a.id, a]));@@ -21,7 +27,15 @@ export function buildAiContext() {if (kind === "clip") {const sp = spans.find((x) => x.clip.id === id);return sp- ? { kind, id, asset: sp.asset.name, start: r(sp.start), len: r(sp.len), muted: sp.clip.muted }+ ? {+ kind,+ id,+ asset: sp.asset.name,+ start: r(sp.start),+ len: r(sp.len),+ muted: sp.clip.muted,+ speed: r(sp.clip.speed ?? 1),+ }: { kind, id };}if (kind === "audio") {@@ -55,6 +69,8 @@ export function buildAiContext() {sourceDuration: r(sp.asset.duration),muted: sp.clip.muted,framing: sp.clip.fit ?? "fit",+ speed: r(sp.clip.speed ?? 1),+ ...(sp.transitionOut > 0 ? { crossfadeToNext: r(sp.transitionOut) } : {}),...(sp.clip.fit === "fill"? { panX: r(sp.clip.panX ?? 0), panY: r(sp.clip.panY ?? 0) }: {}),@@ -67,13 +83,15 @@ export function buildAiContext() {showOnTimeline: s.subtitles.showOnTimeline,locale: s.subtitles.locale ?? "en-US",status: s.subtitleStatus,- cues: s.subtitles.cues.slice(0, 40).map((c) => ({+ // A window of cues by default; when truncated the model calls get_state+ // for the whole transcript (e.g. "clean up all the captions").+ cues: s.subtitles.cues.slice(0, cueCap).map((c) => ({id: c.id,start: r(c.start),end: r(c.end),text: c.text,})),- cuesTruncated: s.subtitles.cues.length > 40,+ cuesTruncated: s.subtitles.cues.length > cueCap,},publish: s.publish,view: {@@ -85,18 +103,20 @@ export function buildAiContext() {}function describeAudio(- a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number },+ a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number },assets: Map<string, { name: string }>) {+ const speed = a.speed && a.speed > 0 ? a.speed : 1;return {asset: assets.get(a.assetId)?.name ?? a.assetId,start: r(a.start),- len: r(a.out - a.in),+ len: r((a.out - a.in) / speed),in: r(a.in),out: r(a.out),volume: r(a.volume),fadeIn: r(a.fadeIn ?? 0),fadeOut: r(a.fadeOut ?? 0),+ ...(speed !== 1 ? { speed: r(speed) } : {}),};}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex f9253813..ae24c6ce 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -23,7 +23,9 @@ export async function runAiTool(switch (name) {case "get_state":- return buildAiContext();+ // The tool result carries the whole transcript; the per-message context+ // snapshot trims it, so this is how the model pulls every cue when needed.+ return buildAiContext({ fullCues: true });case "capture_frame": {const canvas = document.querySelector<HTMLCanvasElement>(".stage canvas");@@ -142,7 +144,8 @@ export async function runAiTool(case "update_audio": {const a = requireItem(s.audioClips, input.id, "soundtrack clip");- const len = a.out - a.in;+ const aSpeed = a.speed && a.speed > 0 ? a.speed : 1;+ const len = (a.out - a.in) / aSpeed;const patch: Record<string, number> = {};if (isNum(input.volume)) patch.volume = clamp(input.volume, 0, 1.5);if (isNum(input.fadeIn)) patch.fadeIn = clamp(input.fadeIn, 0, len / 2);@@ -311,6 +314,46 @@ export async function runAiTool(return { open: true };}+ case "set_speed": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ if (!isNum(input.speed)) throw new ToolError("speed is required (0.25–4).");+ s.setClipSpeed(clip.id, input.speed);+ const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;+ return { id: next.id, speed: next.speed ?? 1 };+ }++ case "set_transition": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ if (s.clips.findIndex((c) => c.id === clip.id) === s.clips.length - 1)+ throw new ToolError("The last clip has no next clip to dissolve into.");+ if (!isNum(input.seconds)) throw new ToolError("seconds is required (0 clears the crossfade).");+ s.setClipTransition(clip.id, input.seconds);+ const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;+ return { id: next.id, transition: next.transition ?? 0 };+ }++ case "merge_cue": {+ const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");+ if (s.subtitles.cues.findIndex((c) => c.id === cue.id) <= 0)+ throw new ToolError("That is the first cue — nothing before it to merge into.");+ s.mergeCueIntoPrev(cue.id);+ return { mergedInto: "previous cue" };+ }++ case "set_aspect": {+ const a = input.aspect === "16:9" ? "16:9" : input.aspect === "9:16" ? "9:16" : null;+ if (!a) throw new ToolError('aspect must be "9:16" or "16:9".');+ s.setAspect(a);+ return { aspect: a };+ }++ case "set_project_name": {+ if (typeof input.name !== "string" || !input.name.trim())+ throw new ToolError("name is required.");+ s.setProjectName(input.name.trim());+ return { name: input.name.trim() };+ }+default:throw new ToolError(`Unknown tool: ${name}`);}diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 725097cc..f2d71e04 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -1,7 +1,7 @@"use client";import { apiFetch, apiUrl } from "./api";-import { getClipSpans, totalDuration } from "./store";+import { clipSpeed, getClipSpans, totalDuration } from "./store";import { cueOverlay } from "./subtitles";import { renderOverlayPng } from "./textRender";import { FRAME } from "./types";@@ -125,6 +125,9 @@ export function startExport(fit: sp.clip.fit ?? "fit",panX: sp.clip.panX ?? 0,panY: sp.clip.panY ?? 0,+ speed: clipSpeed(sp.clip),+ // The already-clamped dissolve overlap into the next clip.+ transition: sp.transitionOut,}));const audio = doc.audioClips@@ -137,6 +140,7 @@ export function startExport(volume: a.volume,fadeIn: a.fadeIn ?? 0,fadeOut: a.fadeOut ?? 0,+ speed: a.speed,}));const overlays: { file: string; start: number; end: number }[] = [];diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 17ff1a9b..d57ff8ef 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -15,13 +15,19 @@ import type {VideoClip,} from "./types";import { apiFetch } from "./api";-import { emptySubtitles, mediaUrl } from "./types";+import { emptySubtitles, mediaUrl, SPEED_MAX, SPEED_MIN, TRANSITION_MAX } from "./types";import { loadUiState, saveUiState } from "./uiState";const uid = () => crypto.randomUUID().slice(0, 8);const MIN_LEN = 0.1;+/** A single-item selection: the primary that drives the Inspector plus the+ * one-element multiSelection that bulk actions (delete, copy) and the timeline+ * highlight read. Every mutation that selects its own result funnels through+ * this so the two can never drift apart. */+const sole = (sel: NonNullable<Selection>) => ({ selection: sel, multiSelection: [sel] });+export const TIMELINE_H_DEFAULT = 248;export const TIMELINE_H_MIN = 170;export const TIMELINE_H_MAX = 600;@@ -51,6 +57,9 @@ interface EditorState {/** Output frame (9:16 vertical or 16:9 widescreen), persisted per project. */aspect: Aspect;selection: Selection;+ /** Everything selected, including `selection` (the primary that drives the+ * inspector). Bulk actions — delete, copy — act on this whole set. */+ multiSelection: Selection[];currentTime: number;playing: boolean;pxPerSec: number;@@ -87,6 +96,11 @@ interface EditorState {* contiguous, so empty tracks collapse and a past-the-end lane adds one. */moveOverlayToLane: (id: string, lane: number) => void;updateClip: (id: string, patch: Partial<VideoClip>) => void;+ /** Set a clip's playback rate (0.25–4). The clip's timeline footprint+ * changes, so later titles/captions ripple to stay in sync. */+ setClipSpeed: (id: string, speed: number) => void;+ /** Set the cross-dissolve into the next clip (seconds; 0 clears it). */+ setClipTransition: (id: string, seconds: number) => void;updateAudio: (id: string, patch: Partial<AudioClip>) => void;updateOverlay: (id: string, patch: Partial<TextOverlay>) => void;/** Live-drag updates that should not create undo entries. */@@ -114,6 +128,14 @@ interface EditorState {sortCues: () => void;deleteSelection: () => void;select: (sel: Selection) => void;+ /** ⌘/⇧-click: add the item to the selection (or remove it if already in),+ * making it the new primary. */+ toggleSelect: (sel: NonNullable<Selection>) => void;+ /** Shift every free-positioned title and subtitle cue starting at or after+ * `afterTime` by `delta` seconds (clamped to ≥0). Keeps annotations synced+ * when the video track's length changes upstream. Caller owns the history+ * checkpoint. */+ rippleShift: (afterTime: number, delta: number) => void;seek: (t: number) => void;setPlaying: (p: boolean) => void;setPxPerSec: (v: number) => void;@@ -124,9 +146,13 @@ interface EditorState {undo: () => void;redo: () => void;pushHistory: () => void;- /** Copy the selected clip/audio/title to the timeline clipboard. */+ /** Coalesce every edit until the matching `endHistoryBatch` into one undo+ * step. Used so a whole assistant turn reverts with a single ⌘Z. */+ beginHistoryBatch: () => void;+ endHistoryBatch: () => void;+ /** Copy the selected clip/audio/title(s) to the timeline clipboard. */copySelection: () => boolean;- /** Paste the clipboard at the playhead; selects the pasted item. */+ /** Paste the clipboard at the playhead; selects the pasted item(s). */paste: () => boolean;}@@ -142,14 +168,17 @@ let pending: { snap: DocSnapshot; seq: number } | null = null;/** Bumped whenever the persistable doc actually changes, letting a pending* checkpoint tell a real edit apart from a select/seek that touched nothing. */let docSeq = 0;+/** >0 while a run of edits is being coalesced into one undo step (see+ * beginHistoryBatch). One checkpoint is captured when it goes 0→1. */+let batchDepth = 0;-/** Timeline clipboard (⌘C/⌘V) — survives across projects in one session. */-type Clipboard =+/** Timeline clipboard (⌘C/⌘V) — survives across projects in one session. One+ * entry per copied item so a multi-selection round-trips. */+type ClipboardItem =| { kind: "clip"; item: VideoClip }| { kind: "audio"; item: AudioClip }- | { kind: "text"; item: TextOverlay }- | null;-let clipboard: Clipboard = null;+ | { kind: "text"; item: TextOverlay };+let clipboard: ClipboardItem[] = [];export const useEditor = create<EditorState>((set, get) => {const snapshot = (): DocSnapshot => {@@ -179,6 +208,9 @@ export const useEditor = create<EditorState>((set, get) => {};const push = () => {+ // Inside a batch a single checkpoint (taken at beginHistoryBatch) already+ // covers every edit, so individual pushes are no-ops.+ if (batchDepth > 0) return;flush(); // seal the previous edit's checkpoint before starting a new onepending = { snap: snapshot(), seq: docSeq };};@@ -196,6 +228,7 @@ export const useEditor = create<EditorState>((set, get) => {overlays: [],aspect: "9:16",selection: null,+ multiSelection: [],currentTime: 0,playing: false,pxPerSec: 60,@@ -224,6 +257,7 @@ export const useEditor = create<EditorState>((set, get) => {overlays: [],aspect: "9:16",selection: null,+ multiSelection: [],currentTime: 0,playing: false,subtitles: emptySubtitles(),@@ -273,6 +307,18 @@ export const useEditor = create<EditorState>((set, get) => {pushHistory: push,+ beginHistoryBatch: () => {+ if (batchDepth === 0) {+ flush(); // seal any prior edit before opening the batch+ pending = { snap: snapshot(), seq: docSeq };+ }+ batchDepth++;+ },+ endHistoryBatch: () => {+ batchDepth = Math.max(0, batchDepth - 1);+ if (batchDepth === 0) flush(); // commit the whole run as one undo step+ },+setAspect: (a) => set({ aspect: a }),addAsset: (asset) =>@@ -299,19 +345,28 @@ export const useEditor = create<EditorState>((set, get) => {})),removeAsset: (id) => {- if (!get().assets.some((a) => a.id === id)) return;+ const st = get();+ if (!st.assets.some((a) => a.id === id)) return;push();+ // Cascade removes this asset's clips; ripple later annotations so they+ // stay aligned with the content that survives.+ const bump = makeRipple(st.clips, st.clips.filter((c) => c.assetId !== id), st.assets);set((s) => {- const sel = s.selection;- const selGone =- (sel?.kind === "clip" && s.clips.some((c) => c.id === sel.id && c.assetId === id)) ||- (sel?.kind === "audio" &&- s.audioClips.some((c) => c.id === sel.id && c.assetId === id));+ const goneClips = new Set(s.clips.filter((c) => c.assetId === id).map((c) => c.id));+ const goneAudio = new Set(s.audioClips.filter((c) => c.assetId === id).map((c) => c.id));+ const keep = (sel: Selection) =>+ !!sel &&+ !((sel.kind === "clip" && goneClips.has(sel.id)) ||+ (sel.kind === "audio" && goneAudio.has(sel.id)));+ const multiSelection = s.multiSelection.filter(keep);return {assets: s.assets.filter((a) => a.id !== id),clips: s.clips.filter((c) => c.assetId !== id),audioClips: s.audioClips.filter((c) => c.assetId !== id),- selection: selGone ? null : s.selection,+ overlays: s.overlays.map(bump),+ subtitles: { ...s.subtitles, cues: s.subtitles.cues.map(bump) },+ multiSelection,+ selection: keep(s.selection) ? s.selection : multiSelection[multiSelection.length - 1] ?? null,};});},@@ -332,7 +387,7 @@ export const useEditor = create<EditorState>((set, get) => {index === undefined ? s.clips.length : Math.max(0, Math.min(index, s.clips.length));const clips = [...s.clips];clips.splice(at, 0, clip);- return { clips, selection: { kind: "clip", id: clip.id } };+ return { clips, ...sole({ kind: "clip", id: clip.id }) };});},@@ -350,7 +405,7 @@ export const useEditor = create<EditorState>((set, get) => {};set((s) => ({audioClips: [...s.audioClips, clip],- selection: { kind: "audio", id: clip.id },+ ...sole({ kind: "audio", id: clip.id }),}));},@@ -376,7 +431,7 @@ export const useEditor = create<EditorState>((set, get) => {};set((s) => ({overlays: [...s.overlays, overlay],- selection: { kind: "text", id: overlay.id },+ ...sole({ kind: "text", id: overlay.id }),}));},@@ -399,6 +454,38 @@ export const useEditor = create<EditorState>((set, get) => {push();get().updateClipTransient(id, patch);},++ setClipSpeed: (id, speed) => {+ const s = get();+ const clip = s.clips.find((c) => c.id === id);+ if (!clip) return;+ const clamped = Math.max(SPEED_MIN, Math.min(SPEED_MAX, speed));+ if (Math.abs(clamped - clipSpeed(clip)) < 1e-4) return;+ const span = getClipSpans(s.clips, s.assets).find((sp) => sp.clip.id === id);+ const oldLen = span?.len ?? clipLen(clip);+ const newLen = Math.max(MIN_LEN, (clip.out - clip.in) / clamped);+ const editEnd = (span?.start ?? 0) + oldLen;+ push();+ get().updateClipTransient(id, { speed: clamped });+ get().rippleShift(editEnd, newLen - oldLen);+ },++ setClipTransition: (id, seconds) => {+ const s = get();+ const idx = s.clips.findIndex((c) => c.id === id);+ if (idx < 0) return;+ const clip = s.clips[idx];+ const next = s.clips[idx + 1];+ const value = Math.max(0, Math.min(TRANSITION_MAX, seconds));+ const oldOverlap = transitionOverlap(clip, next);+ const newOverlap = transitionOverlap({ ...clip, transition: value }, next);+ const span = getClipSpans(s.clips, s.assets).find((sp) => sp.clip.id === id);+ const editEnd = (span?.start ?? 0) + (span?.len ?? clipLen(clip));+ push();+ get().updateClipTransient(id, { transition: value || undefined });+ get().rippleShift(editEnd, oldOverlap - newOverlap);+ },+updateAudio: (id, patch) => {push();get().updateAudioTransient(id, patch);@@ -453,11 +540,14 @@ export const useEditor = create<EditorState>((set, get) => {in: clip.in,out: clip.out,volume: 1,+ // Carry the clip's rate so the detached track keeps the muted picture's+ // length and stays in sync (an AudioClip plays at its own `speed`).+ ...(clipSpeed(clip) !== 1 ? { speed: clipSpeed(clip) } : {}),};set((s) => ({audioClips: [...s.audioClips, audio],clips: s.clips.map((c) => (c.id === clip.id ? { ...c, muted: true } : c)),- selection: { kind: "audio", id: audio.id },+ ...sole({ kind: "audio", id: audio.id }),}));},@@ -478,7 +568,7 @@ export const useEditor = create<EditorState>((set, get) => {const idx = s.audioClips.findIndex((c) => c.id === a.id);const next = [...s.audioClips];next.splice(idx, 1, left, right);- return { audioClips: next, selection: { kind: "audio", id: right.id } };+ return { audioClips: next, ...sole({ kind: "audio", id: right.id }) };});return;}@@ -490,40 +580,88 @@ export const useEditor = create<EditorState>((set, get) => {);if (!span) return;push();- const cutAt = span.clip.in + (t - span.start);- const left: VideoClip = { ...span.clip, out: cutAt };+ // Source time advances `speed`× faster than timeline time.+ const cutAt = span.clip.in + (t - span.start) * clipSpeed(span.clip);+ // The left half hard-cuts into the right; the right keeps the original+ // dissolve into whatever came after.+ const left: VideoClip = { ...span.clip, out: cutAt, transition: undefined };const right: VideoClip = { ...span.clip, id: uid(), in: cutAt };set((s) => {const idx = s.clips.findIndex((c) => c.id === span.clip.id);const next = [...s.clips];next.splice(idx, 1, left, right);- return { clips: next, selection: { kind: "clip", id: right.id } };+ return { clips: next, ...sole({ kind: "clip", id: right.id }) };});},deleteSelection: () => {- const sel = get().selection;- if (!sel) return;+ const st = get();+ const sels = st.multiSelection.length+ ? st.multiSelection+ : st.selection+ ? [st.selection]+ : [];+ if (sels.length === 0) return;push();+ const idsOf = (k: NonNullable<Selection>["kind"]) =>+ new Set(+ sels+ .filter((x): x is NonNullable<Selection> => !!x && x.kind === k)+ .map((x) => x.id)+ );+ const clipIds = idsOf("clip");+ const audioIds = idsOf("audio");+ const textIds = idsOf("text");+ const cueIds = idsOf("cue");+ // Removing video clips shortens the track; ripple later titles/captions+ // so they stay aligned with the content that survives.+ const bump = clipIds.size+ ? makeRipple(st.clips, st.clips.filter((c) => !clipIds.has(c.id)), st.assets)+ : <T extends { start: number; end: number }>(x: T): T => x;set((s) => ({- clips: sel.kind === "clip" ? s.clips.filter((c) => c.id !== sel.id) : s.clips,- audioClips:- sel.kind === "audio"- ? s.audioClips.filter((c) => c.id !== sel.id)- : s.audioClips,- overlays:- sel.kind === "text"- ? s.overlays.filter((o) => o.id !== sel.id)- : s.overlays,- subtitles:- sel.kind === "cue"- ? { ...s.subtitles, cues: s.subtitles.cues.filter((c) => c.id !== sel.id) }- : s.subtitles,+ clips: s.clips.filter((c) => !clipIds.has(c.id)),+ audioClips: s.audioClips.filter((c) => !audioIds.has(c.id)),+ overlays: s.overlays.filter((o) => !textIds.has(o.id)).map(bump),+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.filter((c) => !cueIds.has(c.id)).map(bump),+ },selection: null,+ multiSelection: [],}));},- select: (sel) => set({ selection: sel }),+ select: (sel) => set({ selection: sel, multiSelection: sel ? [sel] : [] }),++ toggleSelect: (sel) =>+ set((s) => {+ const has = s.multiSelection.some((x) => x?.kind === sel.kind && x.id === sel.id);+ const next = has+ ? s.multiSelection.filter((x) => !(x?.kind === sel.kind && x.id === sel.id))+ : [...s.multiSelection, sel];+ // Primary is the just-added item, or the last survivor when removing.+ const primary = has ? next[next.length - 1] ?? null : sel;+ return { multiSelection: next, selection: primary };+ }),++ rippleShift: (afterTime, delta) => {+ if (delta === 0) return;+ set((s) => ({+ overlays: s.overlays.map((o) =>+ o.start >= afterTime - 0.001+ ? { ...o, start: Math.max(0, o.start + delta), end: Math.max(0, o.end + delta) }+ : o+ ),+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.map((c) =>+ c.start >= afterTime - 0.001+ ? { ...c, start: Math.max(0, c.start + delta), end: Math.max(0, c.end + delta) }+ : c+ ),+ },+ }));+ },seek: (t) => {const total = totalDuration(get().clips);@@ -555,6 +693,10 @@ export const useEditor = create<EditorState>((set, get) => {in: sp.clip.in,out: sp.clip.out,muted: sp.clip.muted,+ speed: clipSpeed(sp.clip),+ // The clamped cross-dissolve overlap, so the transcribe mix overlaps+ // clip audio the same way the timeline does and cues stay in sync.+ transition: sp.transitionOut,})),audio: s.audioClips.filter((a) => a.start < duration && assetById.has(a.assetId))@@ -564,6 +706,7 @@ export const useEditor = create<EditorState>((set, get) => {out: a.out,start: a.start,volume: a.volume,+ speed: a.speed,})),};set({ subtitleStatus: "running", subtitleError: null });@@ -622,14 +765,19 @@ export const useEditor = create<EditorState>((set, get) => {const cue = get().subtitles.cues.find((c) => c.id === id);if (!cue || cue.text === trimmed) return;push();+ // A same-length edit (fixing a misheard word) keeps the real per-word+ // timings, just swapping the text; a word added/removed drops them and+ // falls back to proportional timing.+ const parts = trimmed.split(" ").filter(Boolean);+ const words =+ cue.words && cue.words.length === parts.length+ ? parts.map((w, i) => ({ ...cue.words![i], w }))+ : undefined;set((s) => ({subtitles: {...s.subtitles,cues: trimmed- ? s.subtitles.cues.map((c) =>- // Hand-edited text no longer matches the word timings.- c.id === id ? { ...c, text: trimmed, words: undefined } : c- )+ ? s.subtitles.cues.map((c) => (c.id === id ? { ...c, text: trimmed, words } : c)): s.subtitles.cues.filter((c) => c.id !== id),},}));@@ -760,67 +908,73 @@ export const useEditor = create<EditorState>((set, get) => {copySelection: () => {const s = get();- const sel = s.selection;- if (!sel) return false;- if (sel.kind === "clip") {- const c = s.clips.find((x) => x.id === sel.id);- if (!c) return false;- clipboard = { kind: "clip", item: { ...c } };- } else if (sel.kind === "audio") {- const a = s.audioClips.find((x) => x.id === sel.id);- if (!a) return false;- clipboard = { kind: "audio", item: { ...a } };- } else if (sel.kind === "text") {- const o = s.overlays.find((x) => x.id === sel.id);- if (!o) return false;- clipboard = { kind: "text", item: { ...o } };- } else {- return false;+ const sels = s.multiSelection.length ? s.multiSelection : s.selection ? [s.selection] : [];+ const items: ClipboardItem[] = [];+ for (const sel of sels) {+ if (sel?.kind === "clip") {+ const c = s.clips.find((x) => x.id === sel.id);+ if (c) items.push({ kind: "clip", item: { ...c } });+ } else if (sel?.kind === "audio") {+ const a = s.audioClips.find((x) => x.id === sel.id);+ if (a) items.push({ kind: "audio", item: { ...a } });+ } else if (sel?.kind === "text") {+ const o = s.overlays.find((x) => x.id === sel.id);+ if (o) items.push({ kind: "text", item: { ...o } });+ }}+ if (items.length === 0) return false;+ clipboard = items;return true;},paste: () => {- const cb = clipboard;- if (!cb) return false;+ if (clipboard.length === 0) return false;const s = get();- // The copied item's media must still exist in this project.+ // Every copied clip/audio's media must still exist in this project.if (- (cb.kind === "clip" || cb.kind === "audio") &&- !s.assets.some((a) => a.id === cb.item.assetId)+ clipboard.some(+ (cb) =>+ (cb.kind === "clip" || cb.kind === "audio") &&+ !s.assets.some((a) => a.id === cb.item.assetId)+ ))return false;push();const t = s.currentTime;- if (cb.kind === "clip") {- // Insert after the clip under the playhead (end of track otherwise).- const spans = getClipSpans(s.clips, s.assets);- let index = s.clips.length;- for (let i = 0; i < spans.length; i++) {- if (t < spans[i].start + spans[i].len) {- index = i + 1;- break;- }+ // Video clips insert together, after the clip under the playhead.+ const spans = getClipSpans(s.clips, s.assets);+ let insertAt = s.clips.length;+ for (let i = 0; i < spans.length; i++) {+ if (t < spans[i].start + spans[i].len) {+ insertAt = i + 1;+ break;}- const clip: VideoClip = { ...cb.item, id: uid() };- set((cur) => ({- clips: [...cur.clips.slice(0, index), clip, ...cur.clips.slice(index)],- selection: { kind: "clip", id: clip.id },- }));- } else if (cb.kind === "audio") {- const item: AudioClip = { ...cb.item, id: uid(), start: Math.max(0, t) };- set((cur) => ({- audioClips: [...cur.audioClips, item],- selection: { kind: "audio", id: item.id },- }));- } else {- const len = Math.max(0.2, cb.item.end - cb.item.start);- const item: TextOverlay = { ...cb.item, id: uid(), start: Math.max(0, t), end: Math.max(0, t) + len };- set((cur) => ({- overlays: [...cur.overlays, item],- selection: { kind: "text", id: item.id },- }));}+ const newSel: Selection[] = [];+ set((cur) => {+ let clips = cur.clips;+ let audioClips = cur.audioClips;+ let overlays = cur.overlays;+ let at = insertAt;+ for (const cb of clipboard) {+ if (cb.kind === "clip") {+ const clip: VideoClip = { ...cb.item, id: uid() };+ clips = [...clips.slice(0, at), clip, ...clips.slice(at)];+ at++;+ newSel.push({ kind: "clip", id: clip.id });+ } else if (cb.kind === "audio") {+ const item: AudioClip = { ...cb.item, id: uid(), start: Math.max(0, t) };+ audioClips = [...audioClips, item];+ newSel.push({ kind: "audio", id: item.id });+ } else {+ const len = Math.max(0.2, cb.item.end - cb.item.start);+ const item: TextOverlay = { ...cb.item, id: uid(), start: Math.max(0, t), end: Math.max(0, t) + len };+ overlays = [...overlays, item];+ newSel.push({ kind: "text", id: item.id });+ }+ }+ return { clips, audioClips, overlays, selection: newSel[newSel.length - 1] ?? null, multiSelection: newSel };+ });return true;},@@ -829,7 +983,7 @@ export const useEditor = create<EditorState>((set, get) => {const prev = history.pop();if (!prev) return;future.push(snapshot());- set({ ...prev, selection: null });+ set({ ...prev, selection: null, multiSelection: [] });},redo: () => {@@ -838,7 +992,7 @@ export const useEditor = create<EditorState>((set, get) => {if (!next) return;history.push(snapshot());if (history.length > HISTORY_CAP) history.shift();- set({ ...next, selection: null });+ set({ ...next, selection: null, multiSelection: [] });},};});@@ -889,8 +1043,27 @@ export function serializeDoc(s: {};}+/** Effective playback rate of a video clip (>0, default 1). */+export function clipSpeed(c: VideoClip) {+ const s = c.speed ?? 1;+ return s > 0 ? s : 1;+}+export function clipLen(c: VideoClip | AudioClip) {- return Math.max(MIN_LEN, c.out - c.in);+ const src = c.out - c.in;+ // Video clips play their source at `speed`, so the timeline footprint is+ // shorter/longer than the source. Audio clips have no speed.+ const eff = "speed" in c && c.speed && c.speed > 0 ? src / c.speed : src;+ return Math.max(MIN_LEN, eff);+}++/** Cross-dissolve overlap (timeline seconds) between a clip and its successor,+ * clamped so it can never swallow either clip whole. 0 when there is no next+ * clip or no transition set. */+export function transitionOverlap(a: VideoClip, b: VideoClip | undefined): number {+ const d = a.transition ?? 0;+ if (!b || d <= 0) return 0;+ return Math.min(d, clipLen(a) * 0.9, clipLen(b) * 0.9);}export function getClipSpans(@@ -899,20 +1072,62 @@ export function getClipSpans(): ClipSpan[] {// Map lookup, not a per-clip assets.find — this runs every playback frame.const byId = new Map(assets.map((a) => [a.id, a]));+ // Lay out only clips whose media is present; a transition joins adjacent+ // present clips, so resolve the list first.+ const present = clips+ .map((clip) => ({ clip, asset: byId.get(clip.assetId) }))+ .filter((x): x is { clip: VideoClip; asset: MediaAsset } => !!x.asset);const spans: ClipSpan[] = [];let t = 0;- for (const clip of clips) {- const asset = byId.get(clip.assetId);- if (!asset) continue;+ for (let i = 0; i < present.length; i++) {+ const { clip, asset } = present[i];const len = clipLen(clip);- spans.push({ clip, asset, start: t, len });- t += len;+ const overlap = transitionOverlap(clip, present[i + 1]?.clip);+ spans.push({ clip, asset, start: t, len, transitionOut: overlap });+ t += len - overlap; // the next clip starts early by the dissolve length}return spans;}export function totalDuration(clips: VideoClip[]) {- return clips.reduce((sum, c) => sum + clipLen(c), 0);+ let t = 0;+ for (let i = 0; i < clips.length; i++) {+ t += clipLen(clips[i]) - transitionOverlap(clips[i], clips[i + 1]);+ }+ return Math.max(0, t);+}++/**+ * Build the annotation shifter for a video-track edit (clip delete, asset+ * removal). Titles and cues are pinned to timeline time, so when clips go the+ * track re-lays-out and everything downstream must move with the content it+ * sat over. Comparing the real old/new overlap-aware layouts — rather than+ * assuming each removed clip vacates its full length — keeps annotations+ * aligned even across cross-dissolves. An annotation over surviving content+ * moves by that clip's shift; one over a removed gap collapses to the join;+ * one past everything shifts by the whole-timeline length change.+ */+function makeRipple(oldClips: VideoClip[], newClips: VideoClip[], assets: MediaAsset[]) {+ const newStart = new Map(getClipSpans(newClips, assets).map((sp) => [sp.clip.id, sp.start]));+ const totalDelta = totalDuration(newClips) - totalDuration(oldClips);+ const survivors = getClipSpans(oldClips, assets)+ .filter((sp) => newStart.has(sp.clip.id))+ .map((sp) => ({+ oldStart: sp.start,+ oldEnd: sp.start + sp.len,+ newStart: newStart.get(sp.clip.id)!,+ }));+ const shiftFor = (a: number) => {+ for (const s of survivors) {+ if (a <= s.oldEnd + 1e-6)+ return a >= s.oldStart - 1e-6 ? s.newStart - s.oldStart : s.newStart - a;+ }+ return totalDelta;+ };+ return <T extends { start: number; end: number }>(item: T): T => {+ const d = shiftFor(item.start);+ return d ? { ...item, start: Math.max(0, item.start + d), end: Math.max(0, item.end + d) } : item;+ };}export const useTotalDuration = () => useEditor((s) => totalDuration(s.clips));diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex af630399..29a49193 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -50,8 +50,20 @@ export interface VideoClip {* of the oversized video stays visible. */panX?: number;panY?: number;+ /** Playback rate, default 1 (absent). The source (out-in) seconds play in+ * (out-in)/speed timeline seconds, so >1 is faster and shorter. */+ speed?: number;+ /** Cross-dissolve into the next clip, in timeline seconds (absent/0 = hard+ * cut). The two clips overlap by this much, so the cut shortens by it. */+ transition?: number;}+/** Speed limits — matches the Inspector control and export atempo range. */+export const SPEED_MIN = 0.25;+export const SPEED_MAX = 4;+/** Longest cross-dissolve offered; also clamps against the clips it joins. */+export const TRANSITION_MAX = 2;+/** A clip on the free-form soundtrack track. */export interface AudioClip {id: string;@@ -62,6 +74,10 @@ export interface AudioClip {volume: number; // 0..1.5fadeIn?: number; // seconds, ramp up from the clip startfadeOut?: number; // seconds, ramp down into the clip end+ /** Playback rate, default 1 (absent). Set only when audio was detached from+ * a sped-up video clip, so it stays the same length and in sync with the+ * (now muted) picture. The timeline footprint is (out-in)/speed. */+ speed?: number;}export type FontId = "sf" | "serif" | "rounded" | "mono" | "impact";@@ -110,8 +126,9 @@ export interface SubtitleCue {start: number; // timeline secondsend: number;text: string;- /** Word timings from the transcriber; dropped once the text is hand-edited- * (they no longer match), which falls back to proportional splitting. */+ /** Word timings from the transcriber. A same-word-count hand-edit keeps them+ * (text swapped in place); adding/removing a word drops them and splitting+ * falls back to proportional timing. */words?: { t0: number; t1: number; w: string }[];}@@ -142,7 +159,10 @@ export interface ClipSpan {clip: VideoClip;asset: MediaAsset;start: number; // timeline start- len: number;+ len: number; // own timeline footprint (source length / speed)+ /** Cross-dissolve overlap into the next span, in timeline seconds. The next+ * span's start already sits `transitionOut` earlier, so the two intersect. */+ transitionOut: number;}/** The document persisted as project.json inside each project folder. */diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex de3cd037..836147a3 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -227,6 +227,34 @@ export const AI_TOOLS: AiToolDef[] = ["Open the export dialog so the user can render the cut (TikTok 1080p, Quick share 1080p, or Draft 720p). Exporting itself stays a user action.",inputSchema: obj({}),},+ {+ name: "set_speed",+ description:+ "Set a video clip's playback speed (0.25–4×). Faster shortens the clip on the timeline; slower stretches it. Later titles and captions shift to stay in sync.",+ inputSchema: obj({ clipId: str("Video clip id"), speed: num("Playback rate 0.25–4 (1 = normal)") }, ["clipId", "speed"]),+ },+ {+ name: "set_transition",+ description:+ "Set a cross-dissolve from this clip into the next one, in seconds (0 clears it, max 2). The two clips overlap by that much, so the cut shortens. Only valid when a next clip exists.",+ inputSchema: obj({ clipId: str("Video clip id (the clip the dissolve starts from)"), seconds: num("Dissolve length in seconds, 0–2 (0 = hard cut)") }, ["clipId", "seconds"]),+ },+ {+ name: "merge_cue",+ description: "Merge a subtitle cue into the one before it (joins their text and timing). Not valid for the first cue.",+ inputSchema: obj({ id: str("Cue id to merge into its predecessor") }, ["id"]),+ },+ {+ name: "set_aspect",+ description:+ "Switch the project's output frame: '9:16' vertical (1080×1920, TikTok/Reels/Shorts) or '16:9' widescreen (1920×1080, YouTube).",+ inputSchema: obj({ aspect: { type: "string", enum: ["9:16", "16:9"], description: "Output aspect" } }, ["aspect"]),+ },+ {+ name: "set_project_name",+ description: "Rename the current project.",+ inputSchema: obj({ name: str("New project name") }, ["name"]),+ },{name: "list_skills",description: "List the available skill documents about how this editor works.",@@ -254,10 +282,12 @@ Everything autosaves to the project folder. Undo/redo is unlimited (⌘Z / ⇧Times are in seconds on the shared timeline. The playhead is currentTime; a skimmer previews under the mouse without moving the playhead.`,"timeline-editing": `# Timeline editing-- Video track is magnetic: clips are ordered by index; there are no gaps. move_clip reorders; total duration = sum of (out-in).+- Video track is magnetic: clips are ordered by index; there are no gaps. move_clip reorders. A clip's timeline length is (out-in)/speed; total duration = the sum of those minus any cross-dissolve overlaps.- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.+- set_speed sets a clip's playback rate (0.25–4×); it changes the clip's timeline length, and later titles/captions ripple to stay in sync.+- set_transition adds a cross-dissolve from a clip into the next one (0–2s). The clips overlap by that duration, so the cut gets shorter; splitting or deleting clears the affected dissolve.- split_at cuts the clip under that time into two clips at the exact frame. With a soundtrack clip selected it splits that instead.-- delete_item removes items; the video track closes the gap automatically.+- delete_item removes items; the video track closes the gap automatically. The user can multi-select (⌘/⇧-click) and delete several at once.- detach_audio lifts a video clip's sound to the soundtrack track (and mutes the clip) so audio can be cut independently of video.- freeze_frame grabs one frame (default: the playhead — what the user currently sees) as a still clip and inserts it, by default at index 0 as a cover/hook frame ("make this the first frame"). The still is baked at the project's current aspect with the clip's framing applied; if the user later switches aspect they should capture a fresh one.- set_framing: per-clip Fit (letterbox) vs Fill (crop to cover the project frame). In Fill, panX/panY position the crop window; the user can also drag the video directly in the preview. The control lives in the Inspector under "Framing" when a video clip is selected. Landscape footage usually wants fill + a pan that keeps the subject.diff --git a/site/src/cut/server/jobRegistry.ts b/site/src/cut/server/jobRegistry.tsnew file mode 100644index 00000000..c4bd506f--- /dev/null+++ b/site/src/cut/server/jobRegistry.ts@@ -0,0 +1,47 @@+/**+ * A tiny in-memory job registry shared by the export and transcription+ * subsystems. It survives dev-server module reloads (the map hangs off+ * globalThis under `globalKey`) and keeps the map bounded: settled jobs are+ * dropped after a grace period so status polling still resolves, and the+ * terminal backlog is capped.+ */+export interface JobRegistry<J> {+ jobs: Map<string, J>;+ /** How many jobs are still running (for concurrency caps). */+ runningCount(): number;+ /** Schedule a settled job's eviction and trim the terminal backlog. */+ retire(job: J): void;+}++export function createJobRegistry<J extends { id: string; status: string }>(+ globalKey: string,+ opts: { maxJobs?: number; retireMs?: number } = {}+): JobRegistry<J> {+ const maxJobs = opts.maxJobs ?? 50;+ const retireMs = opts.retireMs ?? 10 * 60 * 1000;+ const g = globalThis as unknown as Record<string, Map<string, J> | undefined>;+ const jobs = (g[globalKey] ??= new Map<string, J>());+ const retiring = new Set<string>();++ const runningCount = () => {+ let n = 0;+ for (const j of jobs.values()) if (j.status === "running") n++;+ return n;+ };++ const retire = (job: J) => {+ if (retiring.has(job.id)) return;+ retiring.add(job.id);+ setTimeout(() => {+ jobs.delete(job.id);+ retiring.delete(job.id);+ }, retireMs).unref();+ const terminal = [...jobs.values()].filter((j) => j.status !== "running");+ for (let i = 0; i < terminal.length - maxJobs; i++) {+ jobs.delete(terminal[i].id);+ retiring.delete(terminal[i].id);+ }+ };++ return { jobs, runningCount, retire };+}diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 13f41772..36743303 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -3,8 +3,9 @@ import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";+import { createJobRegistry } from "./jobRegistry";import { exportsDir, mediaPath, readProject } from "./projects";-import { hasStream, num } from "./util";+import { atempoChain, hasStream, num } from "./util";export interface ExportSpec {projectId: string;@@ -23,6 +24,9 @@ export interface ExportSpec {fit?: "fit" | "fill";panX?: number; // crop-window pan -1..1 (fill mode)panY?: number;+ speed?: number; // playback rate, default 1+ /** Cross-dissolve into the next clip, in timeline seconds (overlap). */+ transition?: number;}[];audio: {file: string;@@ -32,6 +36,8 @@ export interface ExportSpec {volume: number;fadeIn?: number;fadeOut?: number;+ /** Playback rate (detached-audio clips inherit their video clip's speed). */+ speed?: number;}[];overlays: { file: string; start: number; end: number }[];}@@ -48,9 +54,9 @@ export interface Job {log: string[];}-// Survives dev-server module reloads.-const g = globalThis as unknown as { __veditorJobs?: Map<string, Job> };-const jobs = (g.__veditorJobs ??= new Map<string, Job>());+const MAX_RUNNING = 2; // concurrent ffmpeg exports+// Survives dev-server module reloads; caps the terminal backlog.+const { jobs, runningCount, retire } = createJobRegistry<Job>("__veditorJobs");export function getJob(id: string) {return jobs.get(id);@@ -62,6 +68,7 @@ export function cancelJob(id: string) {job.proc.kill("SIGKILL");job.status = "error";job.error = "Export canceled.";+ retire(job);}}@@ -74,10 +81,23 @@ function stamp() {export async function createJob(form: FormData): Promise<Job> {assertLocalRuntime();const spec = JSON.parse(String(form.get("spec"))) as ExportSpec;- const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-"));const id = crypto.randomUUID().slice(0, 12);+ if (runningCount() >= MAX_RUNNING) {+ const job: Job = {+ id,+ status: "error",+ progress: 0,+ tmpDir: "",+ outPath: "",+ outName: "",+ error: "Another export is already running — wait for it to finish.",+ log: [],+ };+ jobs.set(id, job);+ retire(job);+ return job;+ }const outDir = exportsDir(spec.projectId);- await mkdir(outDir, { recursive: true });// Include the unique job id so two exports in the same second can't collide// on the same output path (which would clobber the first render).const outName = `export-${stamp()}-${id}.mp4`;@@ -85,29 +105,38 @@ export async function createJob(form: FormData): Promise<Job> {id,status: "running",progress: 0,- tmpDir,+ tmpDir: "",outPath: path.join(outDir, outName),outName,log: [],};- jobs.set(id, job);+ jobs.set(id, job); // reserve the concurrency slot before the first awaittry {+ await mkdir(outDir, { recursive: true });+ job.tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-"));if (!(await readProject(spec.projectId))) throw new Error("Project not found.");// Overlay PNGs are rendered in the browser and uploaded with the spec.for (const [key, value] of form.entries()) {if (value instanceof File && key !== "spec") {- await writeFile(path.join(tmpDir, path.basename(key)), Buffer.from(await value.arrayBuffer()));+ await writeFile(path.join(job.tmpDir, path.basename(key)), Buffer.from(await value.arrayBuffer()));}}- void runExport(job, spec).catch((err: unknown) => {- job.status = "error";- job.error = err instanceof Error ? err.message : String(err);- void rm(job.outPath, { force: true }); // no half-written files in exports/- });+ void runExport(job, spec)+ .catch((err: unknown) => {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ void rm(job.outPath, { force: true }); // no half-written files in exports/+ })+ .finally(() => {+ void rm(job.tmpDir, { recursive: true, force: true }); // overlay tmp, win or lose+ retire(job);+ });} catch (err) {job.status = "error";job.error = err instanceof Error ? err.message : String(err);+ if (job.tmpDir) void rm(job.tmpDir, { recursive: true, force: true });+ retire(job);}return job;}@@ -119,6 +148,12 @@ async function resolveMedia(spec: ExportSpec, file: string) {return p;}+/** A clip's effective playback rate (>0, default 1). */+function clipRate(c: ExportSpec["clips"][number]) {+ return c.speed && c.speed > 0 ? c.speed : 1;+}++async function runExport(job: Job, spec: ExportSpec) {if (spec.clips.length === 0) throw new Error("Nothing to export.");const { width: W, height: H, fps } = spec;@@ -141,13 +176,16 @@ async function runExport(job: Job, spec: ExportSpec) {});await Promise.all(mediaFiles.map(async (f, i) => {- audioPresence.set(f, await hasStream(paths[i], "a"));- // If the video probe itself fails, assume the clip HAS video rather than- // silently replacing it with black frames — a normal .mp4 must never- // export as a black screen just because one ffprobe hiccupped.- let probeFailed = false;- const hasVideo = await hasStream(paths[i], "v", () => (probeFailed = true));- videoPresence.set(f, hasVideo || probeFailed);+ // A probe that errors (timeout, non-zero exit) must not be read as+ // "no stream" — that would silently drop real audio to silence or real+ // video to black. Genuine absence returns false with no error, so on a+ // probe error we assume the stream is present and let ffmpeg map it.+ let audioProbeFailed = false;+ const hasAudio = await hasStream(paths[i], "a", () => (audioProbeFailed = true));+ audioPresence.set(f, hasAudio || audioProbeFailed);+ let videoProbeFailed = false;+ const hasVideo = await hasStream(paths[i], "v", () => (videoProbeFailed = true));+ videoPresence.set(f, hasVideo || videoProbeFailed);}));for (const o of spec.overlays) {@@ -157,10 +195,15 @@ async function runExport(job: Job, spec: ExportSpec) {const filters: string[] = [];- // Per-clip normalized video + audio segments for concat.+ // Per-clip timeline length (source span compressed/expanded by speed).+ const clipDur = (c: ExportSpec["clips"][number]) =>+ Math.max(0.1, (c.out - c.in) / clipRate(c));++ // Per-clip normalized video + audio segments for the join below.spec.clips.forEach((c, j) => {const idx = inputIndex.get(c.file)!;- const dur = Math.max(0.1, c.out - c.in);+ const speed = clipRate(c);+ const dur = clipDur(c);if (videoPresence.get(c.file)) {const frame =c.fit === "fill"@@ -170,8 +213,9 @@ async function runExport(job: Job, spec: ExportSpec) {`:(ih-oh)*${num(0.5 + Math.max(-1, Math.min(1, c.panY ?? 0)) / 2)}`: `scale=${W}:${H}:force_original_aspect_ratio=decrease,` +`pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black`;+ // setpts/speed rescales the clip's duration on the timeline.filters.push(- `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=PTS-STARTPTS,` ++ `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=(PTS-STARTPTS)/${num(speed)},` +`fps=${fps},${frame},setsar=1,format=yuv420p[v${j}]`);} else {@@ -181,8 +225,9 @@ async function runExport(job: Job, spec: ExportSpec) {);}if (!c.muted && audioPresence.get(c.file)) {+ const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";filters.push(- `[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,` ++ `[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` +`aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` +`apad=whole_dur=${num(dur)},atrim=0:${num(dur)}[a${j}]`);@@ -193,11 +238,35 @@ async function runExport(job: Job, spec: ExportSpec) {}});- const concatIn = spec.clips.map((_, j) => `[v${j}][a${j}]`).join("");- filters.push(`${concatIn}concat=n=${spec.clips.length}:v=1:a=1[vcat][acat]`);+ // Join the segments. Adjacent clips with a transition cross-dissolve+ // (xfade/acrossfade, overlapping by the transition length); the rest hard-cut+ // (concat). Fold left so mixed sequences chain correctly.+ let vAcc = "v0";+ let aAcc = "a0";+ let acc = clipDur(spec.clips[0]); // running timeline length of the accumulator+ for (let j = 1; j < spec.clips.length; j++) {+ const prev = spec.clips[j - 1];+ const durJ = clipDur(spec.clips[j]);+ // The overlap can't exceed most of either clip, matching the editor clamp.+ const d = Math.min(prev.transition ?? 0, acc * 0.9, durJ * 0.9);+ const vOut = `vj${j}`;+ const aOut = `aj${j}`;+ if (d > 0.01) {+ const offset = Math.max(0, acc - d);+ filters.push(`[${vAcc}][v${j}]xfade=transition=fade:duration=${num(d)}:offset=${num(offset)}[${vOut}]`);+ filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${aOut}]`);+ acc = acc + durJ - d;+ } else {+ filters.push(`[${vAcc}][v${j}]concat=n=2:v=1:a=0[${vOut}]`);+ filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${aOut}]`);+ acc = acc + durJ;+ }+ vAcc = vOut;+ aAcc = aOut;+ }// Burn in text overlays, each windowed to its timeline range.- let vLabel = "vcat";+ let vLabel = vAcc;spec.overlays.forEach((o, k) => {const idx = inputIndex.get(o.file)!;const next = `vov${k}`;@@ -212,14 +281,18 @@ async function runExport(job: Job, spec: ExportSpec) {spec.audio.forEach((a, k) => {const idx = inputIndex.get(a.file)!;if (!audioPresence.get(a.file)) return;+ const speed = a.speed && a.speed > 0 ? a.speed : 1;const delayMs = Math.max(0, Math.round(a.start * 1000));- const len = Math.max(0.1, a.out - a.in);+ // Timeline length after any speed change; fade offsets are in these+ // (post-tempo) seconds, so atempo runs before the fades.+ const len = Math.max(0.1, (a.out - a.in) / speed);+ const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";const fades: string[] = [];if (a.fadeIn && a.fadeIn > 0.01) fades.push(`afade=t=in:st=0:d=${num(a.fadeIn)}`);if (a.fadeOut && a.fadeOut > 0.01)fades.push(`afade=t=out:st=${num(Math.max(0, len - a.fadeOut))}:d=${num(a.fadeOut)}`);filters.push(- `[${idx}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,` ++ `[${idx}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,${tempo}` +`aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` +`volume=${num(a.volume)},` +(fades.length ? fades.join(",") + "," : "") +@@ -228,9 +301,9 @@ async function runExport(job: Job, spec: ExportSpec) {soundLabels.push(`snd${k}`);});- let aLabel = "acat";+ let aLabel = aAcc;if (soundLabels.length > 0) {- const mixIn = ["acat", ...soundLabels].map((l) => `[${l}]`).join("");+ const mixIn = [aAcc, ...soundLabels].map((l) => `[${l}]`).join("");filters.push(`${mixIn}amix=inputs=${soundLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`);@@ -260,7 +333,21 @@ async function runExport(job: Job, spec: ExportSpec) {await new Promise<void>((resolve, reject) => {const proc = spawn("ffmpeg", args);job.proc = proc;+ // Stall watchdog: legit exports can run long, so bound silence, not total+ // time — kill only if ffmpeg emits nothing for STALL_MS.+ const STALL_MS = 120_000;+ let watchdog: ReturnType<typeof setTimeout> | undefined;+ const bump = () => {+ clearTimeout(watchdog);+ watchdog = setTimeout(() => {+ proc.kill("SIGKILL");+ reject(new Error("Export stalled — no ffmpeg output for 120s."));+ }, STALL_MS);+ watchdog.unref();+ };+ bump();proc.stderr.on("data", (chunk: Buffer) => {+ bump();const text = chunk.toString();job.log.push(text);if (job.log.length > 200) job.log.shift();@@ -270,14 +357,16 @@ async function runExport(job: Job, spec: ExportSpec) {job.progress = Math.min(0.99, t / Math.max(0.1, spec.duration));}});- proc.on("error", (err) =>+ proc.on("error", (err) => {+ clearTimeout(watchdog);reject(err.message.includes("ENOENT")? new Error("ffmpeg was not found. Install it with: brew install ffmpeg"): err- )- );+ );+ });proc.on("close", (code) => {+ clearTimeout(watchdog);if (code === 0) resolve();else if (job.error) reject(new Error(job.error));else reject(new Error(`ffmpeg exited with code ${code}.\n${job.log.slice(-8).join("")}`));diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.tsindex b3e2881d..ed0fe43e 100644--- a/site/src/cut/server/transcribe.ts+++ b/site/src/cut/server/transcribe.ts@@ -3,16 +3,25 @@ import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";import os from "node:os";import path from "node:path";import { assertLocalRuntime } from "./local-only";+import { createJobRegistry } from "./jobRegistry";import { mediaPath, readProject } from "./projects";-import { findOnPath, hasStream, num, round } from "./util";+import { atempoChain, findOnPath, hasStream, num, round } from "./util";/** The audible slice of the cut, in timeline time (mirrors ExportSpec). */export interface TranscribeSpec {projectId: string;duration: number;locale?: string;- clips: { file: string; in: number; out: number; muted: boolean }[];- audio: { file: string; in: number; out: number; start: number; volume: number }[];+ clips: {+ file: string;+ in: number;+ out: number;+ muted: boolean;+ speed?: number;+ /** Cross-dissolve overlap into the next clip, timeline seconds. */+ transition?: number;+ }[];+ audio: { file: string; in: number; out: number; start: number; volume: number; speed?: number }[];}interface Word {@@ -38,25 +47,32 @@ export interface TranscribeJob {cues?: Cue[];}-// Survives dev-server module reloads (same trick as export jobs).-const g = globalThis as unknown as { __veditorSttJobs?: Map<string, TranscribeJob> };-const jobs = (g.__veditorSttJobs ??= new Map<string, TranscribeJob>());+const MAX_RUNNING = 1; // on-device transcription is heavy; one at a time+// Survives dev-server module reloads; caps the terminal backlog.+const { jobs, runningCount, retire } = createJobRegistry<TranscribeJob>("__veditorSttJobs");export function getTranscribeJob(id: string) {return jobs.get(id);}-function run(cmd: string, args: string[], notFound?: string): Promise<string> {+function run(cmd: string, args: string[], notFound?: string, timeoutMs = 600_000): Promise<string> {return new Promise((resolve, reject) => {const p = spawn(cmd, args);let out = "";let err = "";+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ reject(new Error(`${cmd} timed out after ${Math.round(timeoutMs / 1000)}s.`));+ }, timeoutMs);+ timer.unref();p.stdout.on("data", (d) => (out += d));p.stderr.on("data", (d) => (err += d));- p.on("error", (e) =>- reject(e.message.includes("ENOENT") && notFound ? new Error(notFound) : e)- );+ p.on("error", (e) => {+ clearTimeout(timer);+ reject(e.message.includes("ENOENT") && notFound ? new Error(notFound) : e);+ });p.on("close", (code) => {+ clearTimeout(timer);if (code === 0) resolve(out);else reject(new Error(err.trim().split("\n").slice(-4).join("\n") || `${cmd} exited ${code}`));});@@ -130,17 +146,32 @@ export function groupWords(words: Word[]): Cue[] {export async function createTranscribeJob(spec: TranscribeSpec): Promise<TranscribeJob> {assertLocalRuntime();+ const id = crypto.randomUUID().slice(0, 12);+ if (runningCount() >= MAX_RUNNING) {+ const job: TranscribeJob = {+ id,+ projectId: spec.projectId,+ status: "error",+ stage: "audio",+ error: "A transcription is already running — wait for it to finish.",+ };+ jobs.set(id, job);+ retire(job);+ return job;+ }const job: TranscribeJob = {- id: crypto.randomUUID().slice(0, 12),+ id,projectId: spec.projectId,status: "running",stage: "audio",};jobs.set(job.id, job);- void runTranscribe(job, spec).catch((err: unknown) => {- job.status = "error";- job.error = err instanceof Error ? err.message : String(err);- });+ void runTranscribe(job, spec)+ .catch((err: unknown) => {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ })+ .finally(() => retire(job));return job;}@@ -182,11 +213,19 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {}const filters: string[] = [];+ // Per-clip timeline length: a sped-up clip is shorter and time-stretched,+ // so the transcript's cue times line up with what the user sees.+ const clipDur = (c: TranscribeSpec["clips"][number]) => {+ const speed = c.speed && c.speed > 0 ? c.speed : 1;+ return Math.max(0.1, (c.out - c.in) / speed);+ };spec.clips.forEach((c, j) => {- const dur = Math.max(0.1, c.out - c.in);+ const speed = c.speed && c.speed > 0 ? c.speed : 1;+ const dur = clipDur(c);if (!c.muted && audible.get(c.file)) {+ const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";filters.push(- `[${inputIndex.get(c.file)}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,` ++ `[${inputIndex.get(c.file)}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` +`aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono,` +`apad=whole_dur=${num(dur)},atrim=0:${num(dur)}[a${j}]`);@@ -194,24 +233,43 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {filters.push(`anullsrc=r=16000:cl=mono,atrim=0:${num(dur)},asetpts=PTS-STARTPTS[a${j}]`);}});- filters.push(- spec.clips.map((_, j) => `[a${j}]`).join("") + `concat=n=${spec.clips.length}:v=0:a=1[acat]`- );+ // Join clip audio exactly as the timeline (and export) do: adjacent clips+ // with a cross-dissolve overlap by the transition length (acrossfade), the+ // rest concatenate. A flat concat would run longer than the timeline, so+ // every cue after a dissolve would land progressively late.+ let aAcc = "a0";+ let acc = clipDur(spec.clips[0]);+ for (let j = 1; j < spec.clips.length; j++) {+ const prev = spec.clips[j - 1];+ const durJ = clipDur(spec.clips[j]);+ const d = Math.min(prev.transition ?? 0, acc * 0.9, durJ * 0.9);+ const out = `aj${j}`;+ if (d > 0.01) {+ filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${out}]`);+ acc = acc + durJ - d;+ } else {+ filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${out}]`);+ acc = acc + durJ;+ }+ aAcc = out;+ }const soundLabels: string[] = [];spec.audio.forEach((a, k) => {if (!audible.get(a.file)) return;+ const speed = a.speed && a.speed > 0 ? a.speed : 1;+ const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";filters.push(- `[${inputIndex.get(a.file)}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,` ++ `[${inputIndex.get(a.file)}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,${tempo}` +`aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono,` +`volume=${num(a.volume)},adelay=${Math.max(0, Math.round(a.start * 1000))}:all=1[snd${k}]`);soundLabels.push(`snd${k}`);});- let aLabel = "acat";+ let aLabel = aAcc;if (soundLabels.length > 0) {filters.push(- ["acat", ...soundLabels].map((l) => `[${l}]`).join("") ++ [aAcc, ...soundLabels].map((l) => `[${l}]`).join("") +`amix=inputs=${soundLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`);aLabel = "amix";