Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): remove the overlay-clip concept — one track-keyed clip list [rebuild]

David Ledf6cc71c6e2a
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index f0c2e658..83846d06 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -72,7 +72,6 @@ export function Editor({
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
- overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
fadeIn: s.fadeIn,
@@ -87,7 +86,6 @@ export function Editor({
let last: {
clips: unknown;
audioClips: unknown;
- overlayClips: unknown;
overlays: unknown;
subtitles: unknown;
aspect: string;
@@ -100,7 +98,6 @@ export function Editor({
last !== null &&
(s.clips !== last.clips ||
s.audioClips !== last.audioClips ||
- s.overlayClips !== last.overlayClips ||
s.overlays !== last.overlays ||
s.subtitles !== last.subtitles ||
s.aspect !== last.aspect ||
@@ -109,7 +106,6 @@ export function Editor({
last = {
clips: s.clips,
audioClips: s.audioClips,
- overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
aspect: s.aspect,
@@ -181,7 +177,6 @@ export function Editor({
assetsDirty ||
s.clips !== (last.clips as unknown) ||
s.audioClips !== (last.audioClips as unknown) ||
- s.overlayClips !== (last.overlayClips as unknown) ||
s.overlays !== (last.overlays as unknown) ||
s.subtitles !== (last.subtitles as unknown) ||
s.aspect !== last.aspect ||
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index 5bb668dc..053d3186 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -61,7 +61,6 @@ export function ExportDialog() {
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
- overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
fadeIn: s.fadeIn,
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 07fc8641..2fed7847 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -18,7 +18,7 @@ import {
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
-import { getClipSpans, useEditor, type EditorState } from "@/cut/lib/store";
+import { baseClips, getClipSpans, useEditor, type EditorState } from "@/cut/lib/store";
import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";
import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS } from "@/cut/lib/textRender";
import { writeTextStyle } from "@/cut/lib/textStyle";
@@ -36,7 +36,6 @@ import {
type AudioClip,
type FrameRect,
type LayoutId,
- type OverlayClip,
type TextOverlay,
type TransitionStyle,
type VideoClip,
@@ -159,18 +158,19 @@ export function Inspector() {
const overlay = useEditor((s) =>
selection?.kind === "text" ? s.overlays.find((o) => o.id === selection.id) : undefined
);
- const overlayClip = useEditor((s) =>
- selection?.kind === "overlayClip" ? s.overlayClips.find((c) => c.id === selection.id) : undefined
- );
return (
<aside className="flex min-h-0 flex-col overflow-y-auto border-l border-border bg-card">
{clip ? (
- <ClipPanel key={clip.id} clip={clip} />
+ // The base row (track 0) carries transitions and the sequence controls;
+ // a layer clip gets the compositing panel (track, framing, layout).
+ clip.track === 0 ? (
+ <ClipPanel key={clip.id} clip={clip} />
+ ) : (
+ <LayerClipPanel key={clip.id} clip={clip} />
+ )
) : audio ? (
<AudioPanel key={audio.id} clip={audio} />
- ) : overlayClip ? (
- <OverlayClipPanel key={overlayClip.id} clip={overlayClip} />
) : overlay ? (
<TextPanel key={overlay.id} overlay={overlay} />
) : null}
@@ -242,15 +242,20 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const updateClip = useEditor((s) => s.updateClip);
// A transition hands this clip into the next one, so only offer it when
- // there is a next clip on the track.
+ // there is a next clip on the base row — layer clips share the sorted array
+ // but sit outside the sequence, so position checks read the base row only.
const hasNext = useEditor((s) => {
- const i = s.clips.findIndex((c) => c.id === clip.id);
- return i >= 0 && i < s.clips.length - 1;
+ const base = baseClips(s.clips);
+ const i = base.findIndex((c) => c.id === clip.id);
+ return i >= 0 && i < base.length - 1;
});
// The whole-video fades are project-level but live on the clips that show
// them: fade in on the first clip's panel, fade out on the last clip's.
- const isFirst = useEditor((s) => s.clips[0]?.id === clip.id);
- const isLast = useEditor((s) => s.clips[s.clips.length - 1]?.id === clip.id);
+ const isFirst = useEditor((s) => baseClips(s.clips)[0]?.id === clip.id);
+ const isLast = useEditor((s) => {
+ const base = baseClips(s.clips);
+ return base[base.length - 1]?.id === clip.id;
+ });
const fadeIn = useEditor((s) => s.fadeIn);
const fadeOut = useEditor((s) => s.fadeOut);
const [speedDraft, setSpeedDraft] = useState<number | null>(null);
@@ -612,14 +617,14 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
);
}
-function OverlayClipPanel({ clip }: { clip: OverlayClip }) {
+function LayerClipPanel({ clip }: { clip: VideoClip }) {
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const update = useEditor((s) => s.updateOverlayClip);
const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
const len = (clip.out - clip.in) / speed;
return (
<>
- <PanelTitle>Overlay clip</PanelTitle>
+ <PanelTitle>Video clip</PanelTitle>
<div className="flex flex-col gap-1 px-3.5 pb-4">
<div className="mb-1.5 truncate border-b border-border pb-2.5 text-xs font-medium" title={asset?.name}>
{asset?.name}
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsx
index 8744d5ca..9113c64b 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -145,30 +145,24 @@ export function Preview() {
*/
function OverlayPipHandle({ stage }: { stage: { w: number; h: number } }) {
const selection = useEditor((s) => s.selection);
- const overlayClips = useEditor((s) => s.overlayClips);
const clips = useEditor((s) => s.clips);
- const assets = useEditor((s) => s.assets);
const currentTime = useEditor((s) => s.currentTime);
- // Resolve the selected, live, regioned layer plus how to patch its rect.
+ // Resolve the selected, live, regioned clip (any track) plus how to patch its
+ // rect. A clip's own footprint equals its span length, so one path serves the
+ // base row and the layers.
let rect: FrameRect | null = null;
let apply: ((frame: FrameRect) => void) | null = null;
- if (selection?.kind === "overlayClip") {
- const clip = overlayClips.find((c) => c.id === selection.id);
+ if (selection?.kind === "clip") {
+ const clip = clips.find((c) => c.id === selection.id);
if (clip && !clip.hidden) {
const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
const len = Math.max(0.1, (clip.out - clip.in) / speed);
if (currentTime >= clip.start && currentTime < clip.start + len) {
rect = rectOf(clip);
- apply = (frame) => useEditor.getState().updateOverlayClipTransient(clip.id, { frame });
+ apply = (frame) => useEditor.getState().updateClipTransient(clip.id, { frame });
}
}
- } else if (selection?.kind === "clip") {
- const sp = getClipSpans(clips, assets).find((x) => x.clip.id === selection.id);
- if (sp && !sp.clip.hidden && currentTime >= sp.start && currentTime < sp.start + sp.len) {
- rect = rectOf(sp.clip);
- apply = (frame) => useEditor.getState().updateClipTransient(sp.clip.id, { frame });
- }
}
if (!rect || !apply || isFullRect(rect)) return null;
const r = rect;
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index cf395ee2..5e6363e4 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -24,12 +24,12 @@ import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";
import { ensurePeaks, importImage, importStockVideo } from "@/cut/lib/media";
-import { clipLen, clipSpeed, getClipSpans, nextFreeStart, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
+import { baseClips, clipLen, clipSpeed, getClipSpans, nextFreeStart, overlayLayers, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
import { IMAGE_CLIP_SECONDS, TRANSITION_STYLE_LABELS } from "@/cut/lib/types";
-import type { AudioClip, ClipSpan, MediaAsset, OverlayClip, SubtitleCue, TextOverlay, TransitionStyle } from "@/cut/lib/types";
+import type { AudioClip, ClipSpan, MediaAsset, SubtitleCue, TextOverlay, TransitionStyle, VideoClip } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
const TRANSITION_ICONS: Record<TransitionStyle, LucideIcon> = {
@@ -123,7 +123,9 @@ function draggingStockVideo(e: React.DragEvent): AssetRef | null {
export function Timeline() {
const clips = useEditor((s) => s.clips);
const audioClips = useEditor((s) => s.audioClips);
- const overlayClips = useEditor((s) => s.overlayClips);
+ // The composited layers (every clip off the base row), derived from the one
+ // clip list — the timeline draws them as the tracks around track 0.
+ const overlayClips = useMemo(() => overlayLayers(clips), [clips]);
const overlays = useEditor((s) => s.overlays);
const assets = useEditor((s) => s.assets);
const pps = useEditor((s) => s.pxPerSec);
@@ -144,7 +146,7 @@ export function Timeline() {
);
const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);
- const total = projectDuration({ clips, overlayClips, audioClips });
+ const total = projectDuration({ clips, audioClips });
// Fill the viewport at minimum so a wide window never leaves the ruler/tracks
// cut off; grow past it once the content is longer. While a trim/slide drag
// is in flight, hold the width at its drag-start value so the scroll area
@@ -176,13 +178,19 @@ export function Timeline() {
// elementFromPoint — rows (new-track rows included) carry a `data-drop`
// placement.
const resolveDropTrack = useCallback((clientX: number, clientY: number): TrackTarget => {
+ // An empty video timeline has no base yet: the first clip always lands on
+ // track 0, whatever height the pointer is at. Otherwise a drop above the
+ // thin empty row resolves to an overlay track, leaving track 0 empty — and
+ // an empty track 0 plays black (the compositor's master lives there).
+ const st = useEditor.getState();
+ if (st.clips.length === 0) return TRACK_ZERO;
const el = document.elementFromPoint(clientX, clientY) as HTMLElement | null;
const zone = el?.closest<HTMLElement>("[data-drop]");
const parsed = zone ? parsePlacement(zone.dataset.drop!) : null;
if (parsed) return parsed;
// Past the ends of the stack → a new track beyond the last one.
const rows = innerRef.current?.querySelectorAll<HTMLElement>("[data-drop]");
- const tracks = useEditor.getState().overlayClips.map((c) => c.track);
+ const tracks = overlayLayers(useEditor.getState().clips).map((c) => c.track);
if (rows && rows.length) {
if (clientY < rows[0].getBoundingClientRect().top)
return { kind: "insert", level: Math.max(0, ...tracks) + 1 };
@@ -205,7 +213,7 @@ export function Timeline() {
(id: string, target: TrackTarget, start: number) => {
previewCross(null);
if (samePlacement(target, TRACK_ZERO)) return;
- useEditor.getState().dropVideoClip({ kind: "clip", id }, target, start);
+ useEditor.getState().dropVideoClip(id, target, start);
},
[previewCross]
);
@@ -215,7 +223,7 @@ export function Timeline() {
const onOverlayCrossDrop = useCallback(
(id: string, target: TrackTarget, start: number) => {
previewCross(null);
- useEditor.getState().dropVideoClip({ kind: "overlay", id }, target, start);
+ useEditor.getState().dropVideoClip(id, target, start);
},
[previewCross]
);
@@ -627,7 +635,7 @@ export function Timeline() {
// stretches to the next free slot, so the dashed box must too — a
// box under the pointer that lands minutes away is a lie.
const cur = useEditor.getState();
- const taken = cur.clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));
+ const taken = baseClips(cur.clips).map((c) => ({ start: c.start, end: c.start + clipLen(c) }));
setAssetDrop({
t: nextFreeStart(taken, Math.max(0, timeAt(e.clientX)), duration),
len: duration,
@@ -801,7 +809,7 @@ export function Timeline() {
clip={c}
asset={assets.find((x) => x.id === c.assetId)}
pps={pps}
- selected={selKeys.has(`overlayClip:${c.id}`)}
+ selected={selKeys.has(`clip:${c.id}`)}
drag={laneDrag?.kind === "overlayClip" && laneDrag.id === c.id ? laneDrag : null}
parting={laneDrag?.kind === "overlayClip" && laneDrag.id !== c.id}
onDrag={setLaneDrag}
@@ -930,7 +938,7 @@ export function Timeline() {
clip={c}
asset={assets.find((x) => x.id === c.assetId)}
pps={pps}
- selected={selKeys.has(`overlayClip:${c.id}`)}
+ selected={selKeys.has(`clip:${c.id}`)}
drag={laneDrag?.kind === "overlayClip" && laneDrag.id === c.id ? laneDrag : null}
parting={laneDrag?.kind === "overlayClip" && laneDrag.id !== c.id}
onDrag={setLaneDrag}
@@ -1711,7 +1719,7 @@ function AudioView({
}
/** Timeline footprint (seconds) of an overlay clip, honoring its speed. */
-function overlayLen(c: OverlayClip) {
+function overlayLen(c: VideoClip) {
const src = c.out - c.in;
const eff = c.speed && c.speed > 0 ? src / c.speed : src;
return Math.max(0.1, eff);
@@ -1736,7 +1744,7 @@ function OverlayClipView({
onCrossDrop,
onDragActive,
}: {
- clip: OverlayClip;
+ clip: VideoClip;
asset: MediaAsset | undefined;
pps: number;
selected: boolean;
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index 6d3b4fe7..89f67d56 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -1,9 +1,9 @@
"use client";
import { useEffect, type RefObject } from "react";
-import { clipSpeed, getClipSpans, projectDuration, useEditor } from "@/cut/lib/store";
+import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } from "@/cut/lib/store";
import { isFullRect, projectFadeSeconds, rectOf, TRANSITION_ZOOM } from "@/cut/lib/types";
-import type { AudioClip, ClipSpan, FrameRect, MediaAsset, OverlayClip, VideoClip } from "@/cut/lib/types";
+import type { AudioClip, ClipSpan, FrameRect, MediaAsset, VideoClip } from "@/cut/lib/types";
/** The gain everything else drops to at time `t` while a ducking voiceover
* clip is audible: the lowest `duck` among the clips live then, 1 when none
@@ -335,7 +335,7 @@ class Engine {
return masterEl;
}
- private overlayVideoFor(clip: OverlayClip, asset: MediaAsset): MediaEl {
+ private overlayVideoFor(clip: VideoClip, asset: MediaAsset): MediaEl {
let el = this.overlayEls.get(clip.id);
if (!el) {
el = makeMediaEl(asset);
@@ -391,8 +391,8 @@ class Engine {
* (further-back first). */
private liveOverlays(t: number, side: "below" | "above") {
const s = useEditor.getState();
- const live: { clip: OverlayClip; asset: MediaAsset }[] = [];
- const clips = s.overlayClips
+ const live: { clip: VideoClip; asset: MediaAsset }[] = [];
+ const clips = overlayLayers(s.clips)
.filter((c) => (side === "below" ? c.track < 0 : c.track > 0))
.sort((a, b) => a.track - b.track);
for (const c of clips) {
@@ -409,7 +409,7 @@ class Engine {
/** Seek/rate/play one overlay clip's element toward its frame at timeline
* time `t` (the overlay counterpart of `prepare`). */
- private prepareOverlay(clip: OverlayClip, asset: MediaAsset, t: number, play: boolean): MediaEl {
+ private prepareOverlay(clip: VideoClip, asset: MediaAsset, t: number, play: boolean): MediaEl {
const el = this.overlayVideoFor(clip, asset);
if (isImageEl(el)) return el;
const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
@@ -445,7 +445,7 @@ class Engine {
play: boolean,
side: "below" | "above",
active: Set<string>,
- prepared?: { clip: OverlayClip; el: MediaEl }[]
+ prepared?: { clip: VideoClip; el: MediaEl }[]
) {
for (const { clip, el } of prepared ?? this.prepareSide(t, play, side)) {
active.add(clip.id);
@@ -462,7 +462,7 @@ class Engine {
for (const [id, el] of this.overlayEls) {
if (active.has(id)) continue;
pauseEl(el);
- if (!s.overlayClips.some((c) => c.id === id)) {
+ if (!overlayLayers(s.clips).some((c) => c.id === id)) {
teardown(el);
this.overlayEls.delete(id);
}
@@ -522,7 +522,10 @@ class Engine {
const s = useEditor.getState();
const spans = getClipSpans(s.clips, s.assets);
// Drop decoders for clips that no longer exist (deleted or replaced).
- if (this.videoEls.size > s.clips.length) {
+ // videoEls holds base-row decoders only, so compare against the spans —
+ // gating on the whole clip list would let layer clips mask deletions and
+ // keep dead <video> elements alive.
+ if (this.videoEls.size > spans.length) {
const live = new Set(s.clips.map((c) => c.id));
for (const [id, el] of this.videoEls) {
if (live.has(id)) continue;
@@ -534,7 +537,11 @@ class Engine {
// soundtrack) is still reachable while scrubbing and playing.
const total = projectDuration(s);
- if (spans.length === 0) {
+ // Nothing anywhere — no track-0 clip, no overlay layer, no soundtrack —
+ // resets to a black frame at 0. An empty track 0 with an overlay clip or
+ // audio still plays: the tick body draws those layers and advances the wall
+ // clock, so the guard must not bail on `spans.length === 0` alone.
+ if (spans.length === 0 && overlayLayers(s.clips).length === 0 && s.audioClips.length === 0) {
this.pauseExcept(new Set());
this.drawLayer(null, undefined, true, 1);
this.syncSoundtrack(0, false);
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 91d91005..b723b6c9 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -1,8 +1,8 @@
"use client";
-import { getClipSpans, totalDuration, useEditor } from "./store";
+import { getClipSpans, overlayLayers, totalDuration, useEditor } from "./store";
import { laneCues, subtitleLaneCount } from "./subtitles";
-import { isCrossStyle, rectOf, regionLabel, type ClipSpan, type OverlayClip } from "./types";
+import { isCrossStyle, rectOf, regionLabel, type ClipSpan, type VideoClip } from "./types";
const r = (n: number) => Math.round(n * 100) / 100;
@@ -45,26 +45,26 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {
const { kind, id } = s.selection;
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,
- speed: r(sp.clip.speed ?? 1),
- }
- : { kind, id };
+ if (sp) {
+ return {
+ kind,
+ id,
+ asset: sp.asset.name,
+ start: r(sp.start),
+ len: r(sp.len),
+ muted: sp.clip.muted,
+ speed: r(sp.clip.speed ?? 1),
+ };
+ }
+ // A layer clip carries no span (spans are the base row); describe its
+ // compositing shape instead.
+ const c = s.clips.find((x) => x.id === id);
+ return c ? { kind, id, ...describeOverlayClip(c, assetById) } : { kind, id };
}
if (kind === "audio") {
const a = s.audioClips.find((x) => x.id === id);
return a ? { kind, id, ...describeAudio(a, assetById) } : { kind, id };
}
- if (kind === "overlayClip") {
- const c = s.overlayClips.find((x) => x.id === id);
- return c ? { kind, id, ...describeOverlayClip(c, assetById) } : { kind, id };
- }
if (kind === "cue") {
const c = s.subtitles.cues.find((x) => x.id === id);
return c
@@ -128,7 +128,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {
})),
// Video layers composited with track 0: track > 0 above it (topmost
// full-frame clip covers the rest), track < 0 behind it.
- overlayVideo: s.overlayClips.map((c) => ({ id: c.id, ...describeOverlayClip(c, assetById) })),
+ overlayVideo: overlayLayers(s.clips).map((c) => ({ id: c.id, ...describeOverlayClip(c, assetById) })),
soundtrack: s.audioClips.map((a) => ({ id: a.id, ...describeAudio(a, assetById) })),
titles: s.overlays.map((o) => ({ id: o.id, ...describeOverlay(o) })),
subtitles: {
@@ -187,7 +187,7 @@ function describeAudio(
};
}
-function describeOverlayClip(c: OverlayClip, assets: Map<string, { name: string }>) {
+function describeOverlayClip(c: VideoClip, assets: Map<string, { name: string }>) {
const speed = c.speed && c.speed > 0 ? c.speed : 1;
const rect = rectOf(c);
return {
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index fb875cb8..92a02665 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -8,7 +8,7 @@ import { enrichAsset, ensurePeaks, importImage, importStockVideo } from "./media
import { characterPrompt, stockTitle } from "./stock";
import { STOCK_IMAGES } from "./stockManifest";
import { STOCK_VIDEOS } from "./stockVideoManifest";
-import { getClipSpans, nextFreeStart, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";
+import { baseClips, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";
import { buildAiContext } from "./aiContext";
import { laneCues, subtitleLaneCount } from "./subtitles";
import { resolveVoice, synthesizeSpeech, SPEECH_VOICES } from "./tts";
@@ -27,8 +27,8 @@ import {
type AudioClip,
type FontId,
type MediaAsset,
- type OverlayClip,
type TransitionStyle,
+ type VideoClip,
} from "./types";
const round2 = (n: number) => Math.round(n * 100) / 100;
@@ -215,20 +215,21 @@ export async function runAiTool(
return { selection: null };
}
const id = String(input.id ?? "");
+ // A video clip on any track selects as "clip"; "overlayClip" is accepted
+ // as a legacy alias for a layer clip and resolves the same way.
const pool =
- kind === "clip"
+ kind === "clip" || kind === "overlayClip"
? s.clips
- : kind === "overlayClip"
- ? s.overlayClips
- : kind === "audio"
- ? s.audioClips
- : kind === "text"
- ? s.overlays
- : null;
+ : kind === "audio"
+ ? s.audioClips
+ : kind === "text"
+ ? s.overlays
+ : null;
if (!pool) throw new ToolError(`Unknown kind: ${kind}`);
if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);
- s.select({ kind: kind as "clip" | "overlayClip" | "audio" | "text", id });
- return { selection: { kind, id } };
+ const selKind = kind === "overlayClip" ? "clip" : (kind as "clip" | "audio" | "text");
+ s.select({ kind: selKind, id });
+ return { selection: { kind: selKind, id } };
}
case "split_at": {
@@ -242,9 +243,16 @@ export async function runAiTool(
case "move_clip": {
const clip = requireItem(s.clips, input.clipId, "video clip");
+ // Reordering by index is a base-sequence operation; a layer clip is
+ // free-positioned — move it with update_overlay_video (start/track).
+ if (clip.track !== 0)
+ throw new ToolError(
+ "That clip is on an overlay track — use update_overlay_video to move it."
+ );
if (!isNum(input.toIndex)) throw new ToolError("toIndex is required.");
- s.moveClip(clip.id, clamp(Math.round(input.toIndex), 0, s.clips.length - 1));
- return { order: useEditor.getState().clips.map((c) => c.id) };
+ const base = baseClips(s.clips);
+ s.moveClip(clip.id, clamp(Math.round(input.toIndex), 0, base.length - 1));
+ return { order: baseClips(useEditor.getState().clips).map((c) => c.id) };
}
case "place_clip": {
@@ -252,7 +260,7 @@ export async function runAiTool(
if (!isNum(input.start)) throw new ToolError("start (seconds) is required.");
const len = (clip.out - clip.in) / (clip.speed && clip.speed > 0 ? clip.speed : 1);
const taken = s.clips
- .filter((c) => c.id !== clip.id)
+ .filter((c) => c.id !== clip.id && c.track === clip.track)
.map((c) => ({
start: c.start,
end: c.start + (c.out - c.in) / (c.speed && c.speed > 0 ? c.speed : 1),
@@ -279,12 +287,12 @@ export async function runAiTool(
s.addVideoFromAsset(asset.id, { kind: "track", track }, start);
const cur = useEditor.getState();
const sel = cur.selection;
- const id = sel?.kind === "overlayClip" ? sel.id : null;
+ const id = sel?.kind === "clip" ? sel.id : null;
if (!id) throw new ToolError("Could not create the overlay clip.");
// Same undo step as the add: the layout rides the transient patch.
if (typeof input.layout === "string")
cur.updateOverlayClipTransient(id, layoutPatch(input.layout));
- const c = useEditor.getState().overlayClips.find((x) => x.id === id)!;
+ const c = useEditor.getState().clips.find((x) => x.id === id)!;
return {
id: c.id,
track: c.track,
@@ -295,11 +303,11 @@ export async function runAiTool(
}
case "update_overlay_video": {
- const c = requireItem(s.overlayClips, input.id, "overlay video clip");
+ const c = requireItem(overlayLayers(s.clips), input.id, "overlay video clip");
const asset = s.assets.find((a) => a.id === c.assetId);
// A still has no source bound, so its clip can stretch to any length.
const dur = asset?.type === "image" ? Infinity : asset?.duration ?? c.out;
- const patch: Partial<OverlayClip> = {};
+ const patch: Partial<VideoClip> = {};
if (isNum(input.start)) patch.start = Math.max(0, input.start);
if (isNum(input.in)) patch.in = clamp(input.in, 0, dur - 0.1);
if (isNum(input.out)) patch.out = clamp(input.out, 0.1, dur);
@@ -328,7 +336,7 @@ export async function runAiTool(
if (isNum(input.speed)) patch.speed = clamp(input.speed, SPEED_MIN, SPEED_MAX);
if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");
s.updateOverlayClip(c.id, patch);
- const next = useEditor.getState().overlayClips.find((x) => x.id === c.id)!;
+ const next = useEditor.getState().clips.find((x) => x.id === c.id)!;
return {
id: next.id,
track: next.track,
@@ -364,6 +372,10 @@ export async function runAiTool(
const id = input.clipId ? String(input.clipId) : s.selection?.kind === "clip" ? s.selection.id : null;
if (!id) throw new ToolError("Pass clipId or select a video clip first.");
const clip = requireItem(s.clips, id, "video clip");
+ // detachAudio lifts sound off the base sequence; a layer clip has no
+ // span there and the store would silently do nothing.
+ if (clip.track !== 0)
+ throw new ToolError("That clip is on an overlay track — detach works on timeline (track 0) clips.");
if (clip.muted) throw new ToolError("That clip's audio is muted — nothing to detach.");
s.select({ kind: "clip", id: clip.id });
s.detachAudio();
@@ -377,17 +389,16 @@ export async function runAiTool(
const kind = String(input.kind) as "clip" | "overlayClip" | "audio" | "text";
const id = String(input.id ?? "");
const pool =
- kind === "clip"
+ kind === "clip" || kind === "overlayClip"
? s.clips
- : kind === "overlayClip"
- ? s.overlayClips
- : kind === "audio"
- ? s.audioClips
- : s.overlays;
+ : kind === "audio"
+ ? s.audioClips
+ : s.overlays;
if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);
- s.select({ kind, id });
+ const selKind = kind === "overlayClip" ? "clip" : (kind as "clip" | "audio" | "text");
+ s.select({ kind: selKind, id });
s.deleteSelection();
- return { deleted: { kind, id } };
+ return { deleted: { kind: selKind, id } };
}
case "add_title": {
@@ -947,7 +958,11 @@ export async function runAiTool(
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)
+ // Transitions join the base sequence; a layer clip has no next clip.
+ if (clip.track !== 0)
+ throw new ToolError("That clip is on an overlay track — transitions join timeline (track 0) clips.");
+ const base = baseClips(s.clips);
+ if (base.findIndex((c) => c.id === clip.id) === base.length - 1)
throw new ToolError("The last clip has no next clip to transition into.");
if (!isNum(input.seconds)) throw new ToolError("seconds is required (0 clears the transition).");
let style: TransitionStyle | undefined;
@@ -1110,7 +1125,6 @@ function resolveWatchTarget(
const id = String(input.clip_id);
const clip =
s.clips.find((c) => c.id === id) ??
- s.overlayClips.find((c) => c.id === id) ??
s.audioClips.find((c) => c.id === id);
if (!clip) throw new ToolError(`No clip with id ${id}. Call get_state for current ids.`);
const asset = s.assets.find((a) => a.id === clip.assetId);
@@ -1201,7 +1215,7 @@ const OVERLAY_LAYOUT_KEYS = {
pip: "corner",
} as const;
-function layoutPatch(layout: string): Partial<OverlayClip> {
+function layoutPatch(layout: string): Partial<VideoClip> {
const key = OVERLAY_LAYOUT_KEYS[layout as keyof typeof OVERLAY_LAYOUT_KEYS];
if (!key)
throw new ToolError(`Unknown layout "${layout}". Use full, top, bottom, left, right, or pip.`);
diff --git a/site/src/cut/lib/chatAssets.ts b/site/src/cut/lib/chatAssets.ts
index 4db6a386..3e73e049 100644
--- a/site/src/cut/lib/chatAssets.ts
+++ b/site/src/cut/lib/chatAssets.ts
@@ -63,7 +63,7 @@ export function threadOwnsAssets(threadId: string): boolean {
export function deleteChatAssets(threadId: string) {
const s = useEditor.getState();
const inUse = new Set(
- [...s.clips, ...s.overlayClips, ...s.audioClips].map((c) => c.assetId)
+ [...s.clips, ...s.audioClips].map((c) => c.assetId)
);
const owned = s.assets.filter(
(a) => a.origin === "chat" && a.chatId === threadId && !inUse.has(a.id)
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 0f72122f..3577524d 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1,7 +1,7 @@
"use client";
import { apiFetch, apiJson, apiUrl } from "./api";
-import { clipSpeed, getClipSpans, projectDuration, spanSequence } from "./store";
+import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
import { renderOverlayPng } from "./textRender";
import { FRAME } from "./types";
@@ -9,7 +9,6 @@ import type {
Aspect,
AudioClip,
MediaAsset,
- OverlayClip,
SubtitlesBlock,
TextOverlay,
VideoClip,
@@ -103,9 +102,9 @@ export async function deleteExport(projectId: string, file: string) {
export interface ExportDoc {
assets: MediaAsset[];
+ /** Every video clip, any track (track 0 = base row, others composite). */
clips: VideoClip[];
audioClips: AudioClip[];
- overlayClips: OverlayClip[];
overlays: TextOverlay[];
subtitles: SubtitlesBlock;
/** Whole-video fades (seconds): in from black / out to black on the final
@@ -136,7 +135,7 @@ async function buildExportForm(
// the length of the project and the overlays/soundtrack composite onto it —
// the same path as a gap before the first track-0 clip. Refuse only a cut with
// no renderable content at all.
- const hasOverlayVideo = doc.overlayClips.some(
+ const hasOverlayVideo = overlayLayers(doc.clips).some(
(c) => !c.hidden && assetById.has(c.assetId) && c.start < duration,
);
const hasAudio = doc.audioClips.some(
@@ -226,7 +225,7 @@ async function buildExportForm(
]);
// Video tracks composited around track 0; hidden ones are dropped.
- const overlayVideos = doc.overlayClips
+ const overlayVideos = overlayLayers(doc.clips)
.filter((c) => !c.hidden && assetById.has(c.assetId) && c.start < duration)
.map((c) => ({
file: assetById.get(c.assetId)!.fileName,
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index 933bd418..a9bf0b67 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -29,11 +29,10 @@
import type React from "react";
import { refFromAsset, startPointerRefDrag } from "./assetRef";
import { startDrag } from "./drag";
-import { clipLen, getClipSpans, projectDuration, transitionOverlap, useEditor } from "./store";
+import { baseClips, clipLen, getClipSpans, overlayLayers, projectDuration, transitionOverlap, useEditor } from "./store";
import type {
AudioClip,
MediaAsset,
- OverlayClip,
Selection,
SubtitleCue,
TextOverlay,
@@ -42,8 +41,15 @@ import type {
type S = ReturnType<typeof useEditor.getState>;
+// A drag lane. "clip" is the base row (track 0), "overlayClip" a layer track —
+// distinct adapters, but both select as a plain video-clip selection.
export type LaneKind = "clip" | "audio" | "text" | "overlayClip" | "cue";
+/** The Selection kind a lane maps to. Base and layer video lanes both select as
+ * `"clip"` — a video clip is a video clip whatever track it sits on. */
+const laneSelectionKind = (kind: LaneKind): NonNullable<Selection>["kind"] =>
+ kind === "overlayClip" ? "clip" : kind;
+
/** Visual gutter between adjacent clips (iMovie); time math stays exact. */
export const CLIP_GAP = 4;
/** Pull a dragged or resized edge to a logical time within this many px. */
@@ -100,7 +106,7 @@ const clipAdapter: LaneAdapter<VideoClip> = {
// Verticality is the video placement system (upper tracks and insert
// zones), fed in as the move gesture's `vertical` strategy.
multiLane: false,
- raws: (s) => s.clips,
+ raws: (s) => baseClips(s.clips),
view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: 0 }),
apply: (patches) => useEditor.getState().updateClipsTransient(patches),
movePatch: (c, start) => ({ id: c.id, patch: { start } }),
@@ -160,12 +166,12 @@ const textAdapter: LaneAdapter<TextOverlay> = {
lanePatch: (o, lane) => ({ id: o.id, patch: { lane } }),
};
-const overlayClipAdapter: LaneAdapter<OverlayClip> = {
+const overlayClipAdapter: LaneAdapter<VideoClip> = {
minLen: 0.15,
// Verticality is the video placement system (tracks and insert zones), fed
// in as the move gesture's `vertical` strategy.
multiLane: false,
- raws: (s) => s.overlayClips,
+ raws: (s) => overlayLayers(s.clips),
view: (c) => ({ id: c.id, start: c.start, len: clipLen(c), lane: c.track }),
apply: (patches) => useEditor.getState().updateOverlayClipsTransient(patches),
movePatch: (c, start) => ({ id: c.id, patch: { start } }),
@@ -208,7 +214,7 @@ const cueAdapter: LaneAdapter<SubtitleCue> = {
onMoved: () => useEditor.getState().sortCues(),
};
-type LaneRaw = VideoClip | AudioClip | TextOverlay | OverlayClip | SubtitleCue;
+type LaneRaw = VideoClip | AudioClip | TextOverlay | SubtitleCue;
// The generic parameter is erased at the registry boundary; each gesture only
// feeds an adapter values that came out of that same adapter, so this is safe.
const ADAPTERS: Record<LaneKind, LaneAdapter<LaneRaw>> = {
@@ -340,14 +346,14 @@ export function startLaneMove<V = unknown>(
settleSnapBack();
const s = useEditor.getState();
if (e.metaKey || e.shiftKey) {
- s.toggleSelect({ kind, id } as NonNullable<Selection>);
+ s.toggleSelect({ kind: laneSelectionKind(kind), id });
return;
}
const ad = ADAPTERS[kind];
const raw0 = ad.raws(s).find((r) => ad.view(r).id === id);
if (!raw0) return;
const self = ad.view(raw0);
- s.select({ kind, id } as Selection);
+ s.select({ kind: laneSelectionKind(kind), id });
// Clicking anywhere on the timeline moves the playhead — bars included.
s.seek(
(ui.visStart ?? self.start) +
@@ -575,7 +581,7 @@ export function startLaneTrim(
const raw0 = ad.raws(s).find((r) => ad.view(r).id === id);
if (!raw0) return;
const self = ad.view(raw0);
- s.select({ kind, id } as Selection);
+ s.select({ kind: laneSelectionKind(kind), id });
s.pushHistory();
const targets = snapTargets(s, kind, id);
const tol = SNAP_PX / ui.pps;
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 5ffb1eef..2292fb3c 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -54,7 +54,7 @@ export async function createProjectFromFile(
};
if (asset.type === "video" || asset.type === "image") {
const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
- doc.clips = [{ id: uid(), assetId: asset.id, start: 0, in: 0, out, muted: false }];
+ doc.clips = [{ id: uid(), assetId: asset.id, track: 0, start: 0, in: 0, out, muted: false }];
} else {
doc.audioClips = [
{ id: uid(), assetId: asset.id, start: 0, in: 0, out: asset.duration, volume: 1 },
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 08c9084f..dc7764b5 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -7,7 +7,6 @@ import type {
ClipSpan,
LibraryTemplate,
MediaAsset,
- OverlayClip,
ProjectDoc,
Selection,
StoredAsset,
@@ -35,23 +34,30 @@ const MIN_LEN = 0.1;
/** Where a video clip lands when dropped: an existing track or a brand-new
* track inserted at z-level `level`. Track numbers are signed: track 0 is the
- * `clips` array, positive tracks sit above it (higher = closer to the top),
- * negative tracks sit below it (more negative = further behind). Inserting
- * shifts the tracks past `level` (up for positive, down for negative) to open
- * the slot. */
+ * base row, positive tracks sit above it (higher = closer to the top), negative
+ * tracks sit below it (more negative = further behind). Inserting shifts the
+ * tracks past `level` (up for positive, down for negative) to open the slot. */
export type VideoTrackPlacement =
| { kind: "track"; track: number }
| { kind: "insert"; level: number };
-/** Open a slot at `level`, moving other clips out of the way: above track 0
- * (level > 0) shifts tracks at/above it up; below track 0 (level < 0) shifts
- * tracks at/below it down. `exclude` is the clip being placed (left untouched). */
-function openInsertSlot(clips: OverlayClip[], level: number, exclude?: string): OverlayClip[] {
+/** The base row (track 0) clips — the master sequence that carries transitions
+ * and drives playback. */
+export const baseClips = (clips: VideoClip[]) => clips.filter((c) => c.track === 0);
+/** Every video clip not on the base row (track 0) — the composited layers. */
+export const overlayLayers = (clips: VideoClip[]) => clips.filter((c) => c.track !== 0);
+
+/** Open a slot at a non-zero `level`, moving other clips out of the way: above
+ * track 0 (level > 0) shifts tracks at/above it up; below track 0 (level < 0)
+ * shifts tracks at/below it down. Track-0 clips never match a non-zero level, so
+ * this is safe to run over the whole clip list. `exclude` is the clip being
+ * placed (left untouched). */
+function openInsertSlot(clips: VideoClip[], level: number, exclude?: string): VideoClip[] {
return level > 0
? clips.map((c) => (c.id !== exclude && c.track >= level ? { ...c, track: c.track + 1 } : c))
: clips.map((c) => (c.id !== exclude && c.track <= level ? { ...c, track: c.track - 1 } : c));
}
-const shiftTracksUp = (clips: OverlayClip[], place: VideoTrackPlacement): OverlayClip[] =>
+const shiftTracksUp = (clips: VideoClip[], place: VideoTrackPlacement): VideoClip[] =>
place.kind === "insert" ? openInsertSlot(clips, place.level) : clips;
/** A single-item selection: the primary that drives the Inspector plus the
@@ -67,7 +73,6 @@ export const TIMELINE_H_MAX = 600;
interface DocSnapshot {
clips: VideoClip[];
audioClips: AudioClip[];
- overlayClips: OverlayClip[];
overlays: TextOverlay[];
subtitles: SubtitlesBlock;
}
@@ -84,10 +89,11 @@ export interface EditorState {
saveState: SaveState;
assets: MediaAsset[];
+ /** Every video clip, on any track. Track 0 is the base row (the master
+ * sequence); other tracks composite around it (positive above, negative
+ * behind). A clip's `track` field is the only thing that places it. */
clips: VideoClip[];
audioClips: AudioClip[];
- /** Video tracks composited around track 0 (`clips`): positive above, negative behind. */
- overlayClips: OverlayClip[];
overlays: TextOverlay[];
/** Output frame (9:16 vertical or 16:9 widescreen), persisted per project. */
aspect: Aspect;
@@ -159,7 +165,9 @@ export interface EditorState {
* and push whole lanes at a time (one bulk patcher per lane-track kind). */
updateOverlaysTransient: (patches: { id: string; patch: Partial<TextOverlay> }[]) => void;
updateAudiosTransient: (patches: { id: string; patch: Partial<AudioClip> }[]) => void;
- updateOverlayClipsTransient: (patches: { id: string; patch: Partial<OverlayClip> }[]) => void;
+ /** Bulk-patch layer (non-base-track) clips in one commit — the lane
+ * coordinator parts and pushes a whole track at a time. */
+ updateOverlayClipsTransient: (patches: { id: string; patch: Partial<VideoClip> }[]) => void;
updateCuesTransient: (patches: { id: string; patch: Partial<SubtitleCue> }[]) => void;
updateClipsTransient: (patches: { id: string; patch: Partial<VideoClip> }[]) => void;
updateClipTransient: (id: string, patch: Partial<VideoClip>) => void;
@@ -174,16 +182,12 @@ export interface EditorState {
/** Add a video asset to the timeline at a placement: an existing track or a
* freshly inserted one. Used by media / library drops. */
addVideoFromAsset: (assetId: string, place: VideoTrackPlacement, start: number) => void;
- /** Move an existing clip (track 0 or upper) to a placement, preserving its
- * trim/region/speed. Inserting a track renumbers the ones above it; dropping
- * onto track 0 lands free-positioned at the drop time. Owns its own history. */
- dropVideoClip: (
- source: { kind: "clip" | "overlay"; id: string },
- place: VideoTrackPlacement,
- start: number
- ) => void;
- updateOverlayClip: (id: string, patch: Partial<OverlayClip>) => void;
- updateOverlayClipTransient: (id: string, patch: Partial<OverlayClip>) => void;
+ /** Move an existing clip to a placement, preserving its trim/region/speed.
+ * Inserting a track renumbers the ones above it; dropping onto track 0 lands
+ * free-positioned at the drop time. Owns its own history. */
+ dropVideoClip: (id: string, place: VideoTrackPlacement, start: number) => void;
+ updateOverlayClip: (id: string, patch: Partial<VideoClip>) => void;
+ updateOverlayClipTransient: (id: string, patch: Partial<VideoClip>) => void;
/** iMovie "Detach Audio": lift the selected clip's sound onto the
* soundtrack track (and mute the clip) so it can be cut independently. */
detachAudio: () => void;
@@ -287,7 +291,6 @@ let batchDepth = 0;
type ClipboardItem =
| { kind: "clip"; item: VideoClip }
| { kind: "audio"; item: AudioClip }
- | { kind: "overlayClip"; item: OverlayClip }
| { kind: "text"; item: TextOverlay };
let clipboard: ClipboardItem[] = [];
@@ -296,17 +299,19 @@ let clipboard: ClipboardItem[] = [];
* what is now a different language's track. */
let laneEpoch = 0;
-/** Resize a track-0 clip's footprint to `newLen` (a trim or speed change),
- * keeping the track sound: a live dissolve into the next clip stays a
- * dissolve (the run follows the resize so the pair keeps its overlap);
- * otherwise a longer footprint pushes the run right by the overflow and a
- * shorter one just opens a gap. One undo step. */
+/** Resize a clip's footprint to `newLen` (a trim or speed change), keeping its
+ * own track sound: a live dissolve into the next clip stays a dissolve (the
+ * run follows the resize so the pair keeps its overlap); otherwise a longer
+ * footprint pushes the run right by the overflow and a shorter one just opens
+ * a gap. Everything is scoped to the clip's track — resizing a base clip never
+ * drags the composited layers (or vice versa), so each track's annotations
+ * keep the timing they were placed at. One undo step. */
function resizeClipFootprint(clip: VideoClip, patch: Partial<VideoClip>, newLen: number) {
useEditor.getState().pushHistory();
useEditor.getState().updateClipTransient(clip.id, patch);
const next = useEditor
.getState()
- .clips.filter((c) => c.id !== clip.id && c.start >= clip.start)
+ .clips.filter((c) => c.id !== clip.id && c.track === clip.track && c.start >= clip.start)
.reduce<VideoClip | null>((m, c) => (!m || c.start < m.start ? c : m), null);
const nextStart = next?.start ?? Infinity;
const keep = next
@@ -324,7 +329,7 @@ function resizeClipFootprint(clip: VideoClip, patch: Partial<VideoClip>, newLen:
useEditor.setState((st) => ({
clips: st.clips
.map((c) =>
- c.id !== clip.id && c.start >= clip.start
+ c.id !== clip.id && c.track === clip.track && c.start >= clip.start
? { ...c, start: Math.max(0, c.start + delta) }
: c
)
@@ -384,11 +389,10 @@ async function runTranscription(projectId: string, spec: object): Promise<Subtit
export const useEditor = create<EditorState>((set, get) => {
const snapshot = (): DocSnapshot => {
- const { clips, audioClips, overlayClips, overlays, subtitles } = get();
+ const { clips, audioClips, overlays, subtitles } = get();
return {
clips: clips.map((c) => ({ ...c })),
audioClips: audioClips.map((c) => ({ ...c })),
- overlayClips: overlayClips.map((c) => ({ ...c })),
overlays: overlays.map((o) => ({ ...o })),
subtitles: {
...subtitles,
@@ -428,7 +432,6 @@ export const useEditor = create<EditorState>((set, get) => {
assets: [],
clips: [],
audioClips: [],
- overlayClips: [],
overlays: [],
aspect: "9:16",
fadeIn: 0,
@@ -462,7 +465,6 @@ export const useEditor = create<EditorState>((set, get) => {
assets: [],
clips: [],
audioClips: [],
- overlayClips: [],
overlays: [],
aspect: "9:16",
fadeIn: 0,
@@ -488,12 +490,28 @@ export const useEditor = create<EditorState>((set, get) => {
// Older docs stored video track 0 packed (array order implied the
// position); bake explicit starts in once so every clip is free-placed.
const legacy = (doc.clips as LegacyClip[]).some((c) => typeof c.start !== "number");
+ const base = (legacy ? packStarts(doc.clips as LegacyClip[]) : doc.clips).map((c) => ({
+ ...c,
+ track: c.track ?? 0,
+ }));
+ // Older docs kept non-base tracks in a separate `overlayClips` array;
+ // fold them into the one clip list (each already carries its `track`).
+ // Entries whose id already sits in `clips` are the same clip persisted
+ // twice by a version-skewed save (an older engine keeps overlayClips
+ // after a merged client writes the folded list) — keep the folded copy.
+ // Entries with track 0 were unreachable dead data under the split shape
+ // (never rendered, never played); promoting them would insert them into
+ // the master sequence, so they stay dropped.
+ const seen = new Set(base.map((c) => c.id));
+ const legacyLayers = (doc.overlayClips ?? []).filter(
+ (c) => c.track !== 0 && !seen.has(c.id)
+ );
+ const merged = [...base, ...legacyLayers];
set({
projectName: doc.name,
assets,
- clips: legacy ? packStarts(doc.clips as LegacyClip[]) : doc.clips,
+ clips: merged,
audioClips: doc.audioClips,
- overlayClips: doc.overlayClips ?? [],
overlays: doc.overlays,
aspect: doc.aspect ?? "9:16",
fadeIn: doc.fadeIn ?? 0,
@@ -584,7 +602,6 @@ export const useEditor = create<EditorState>((set, get) => {
// and wipe the redo branch).
if (
!st.clips.some((c) => c.assetId === id) &&
- !st.overlayClips.some((c) => c.assetId === id) &&
!st.audioClips.some((c) => c.assetId === id)
) {
set((s) => ({ assets: s.assets.filter((a) => a.id !== id) }));
@@ -595,18 +612,15 @@ export const useEditor = create<EditorState>((set, get) => {
// the rest of the timeline (and its annotations) stays where it is.
set((s) => {
const goneClips = new Set(s.clips.filter((c) => c.assetId === id).map((c) => c.id));
- const goneOverlay = new Set(s.overlayClips.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 === "overlayClip" && goneOverlay.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),
- overlayClips: s.overlayClips.filter((c) => c.assetId !== id),
audioClips: s.audioClips.filter((c) => c.assetId !== id),
multiSelection,
selection: keep(s.selection) ? s.selection : multiSelection[multiSelection.length - 1] ?? null,
@@ -620,13 +634,17 @@ export const useEditor = create<EditorState>((set, get) => {
push();
const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
const len = Math.max(MIN_LEN, out);
- // Default: append at the end of track 0; with a target time, slide to
- // the track's next free slot there.
- const want = Math.max(0, start ?? totalDuration(get().clips));
- const taken = footprints(get().clips);
+ const base = baseClips(get().clips);
+ // An explicit target time always wins (a drop at the pointer, AI placing
+ // b-roll against a voiceover). Without one: the first clip on an empty
+ // base row anchors at 0 — a lone clip with dead space before it reads as
+ // broken — and later clips append at the end of the row.
+ const want = Math.max(0, start ?? (base.length === 0 ? 0 : totalDuration(get().clips)));
+ const taken = footprints(base);
const clip: VideoClip = {
id: uid(),
assetId,
+ track: 0,
start: nextFreeStart(taken, want, len),
in: 0,
out,
@@ -747,7 +765,9 @@ export const useEditor = create<EditorState>((set, get) => {
// (and the run behind it, gaps preserved) so it starts `newOverlap`
// before this clip ends — closing any gap, since a dissolve needs
// contact. Clearing one pushes the pair back to a hard cut. Edge styles
- // overlap nothing: they leave the layout alone.
+ // overlap nothing: they leave the layout alone. Only the base row moves:
+ // transitions are a base-sequence concept, and the composited layers
+ // stay pinned to the absolute times they annotate.
if (next) {
const oldOverlap = spans[idx].transitionOut;
const wantStart =
@@ -757,7 +777,9 @@ export const useEditor = create<EditorState>((set, get) => {
set((st) => ({
clips: st.clips
.map((c) =>
- c.start >= next.start - 1e-6 ? { ...c, start: Math.max(0, c.start + delta) } : c
+ c.track === 0 && c.start >= next.start - 1e-6
+ ? { ...c, start: Math.max(0, c.start + delta) }
+ : c
)
.sort((a, b) => a.start - b.start),
}));
@@ -805,7 +827,7 @@ export const useEditor = create<EditorState>((set, get) => {
set((s) => {
const byId = new Map(patches.map((p) => [p.id, p.patch]));
return {
- overlayClips: s.overlayClips.map((c) => {
+ clips: s.clips.map((c) => {
const patch = byId.get(c.id);
return patch ? { ...c, ...patch } : c;
}),
@@ -859,25 +881,26 @@ export const useEditor = create<EditorState>((set, get) => {
// its absolute time, so audio, titles, and captions stay synced to the
// clips they annotate. Pointer drags never come here — they free-place
// through the lane coordinator.
- const clips = [...get().clips].sort((a, b) => a.start - b.start);
- const from = clips.findIndex((c) => c.id === id);
+ const base = baseClips(get().clips).sort((a, b) => a.start - b.start);
+ const from = base.findIndex((c) => c.id === id);
if (from < 0) return;
- const to = Math.max(0, Math.min(clips.length - 1, toIndex));
+ const to = Math.max(0, Math.min(base.length - 1, toIndex));
if (to === from) return;
push();
- const moved = clips[from];
- const others = clips.filter((c) => c.id !== id);
+ const moved = base[from];
+ const others = base.filter((c) => c.id !== id);
const len = clipLen(moved);
const anchor = to < others.length ? others[to] : null;
const newStart = anchor ? anchor.start : totalDuration(others);
- set({
+ set((s) => ({
clips: [
+ ...overlayLayers(s.clips),
...others.map((c) =>
c.start >= newStart - 1e-6 ? { ...c, start: c.start + len } : c
),
{ ...moved, start: newStart },
].sort((a, b) => a.start - b.start),
- });
+ }));
},
addVideoFromAsset: (assetId, place, start) => {
@@ -886,10 +909,11 @@ export const useEditor = create<EditorState>((set, get) => {
const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
push();
if (place.kind === "track" && place.track === 0) {
- const taken = footprints(get().clips);
+ const taken = footprints(baseClips(get().clips));
const v: VideoClip = {
id: uid(),
assetId,
+ track: 0,
start: nextFreeStart(taken, Math.max(0, start), Math.max(MIN_LEN, out)),
in: 0,
out,
@@ -904,7 +928,7 @@ export const useEditor = create<EditorState>((set, get) => {
// Full-frame by default: covers track 0 ("topmost plays"); the inspector
// regions it (split half / corner PiP).
const track = place.kind === "insert" ? place.level : place.track;
- const ov: OverlayClip = {
+ const ov: VideoClip = {
id: uid(),
assetId,
track,
@@ -914,70 +938,45 @@ export const useEditor = create<EditorState>((set, get) => {
muted: false,
};
set((s) => ({
- overlayClips: [...shiftTracksUp(s.overlayClips, place), ov],
- ...sole({ kind: "overlayClip", id: ov.id }),
+ clips: [...shiftTracksUp(s.clips, place), ov],
+ ...sole({ kind: "clip", id: ov.id }),
}));
},
- dropVideoClip: (source, place, start) => {
- const s = get();
- const src =
- source.kind === "clip"
- ? s.clips.find((c) => c.id === source.id)
- : s.overlayClips.find((c) => c.id === source.id);
+ dropVideoClip: (id, place, start) => {
+ const src = get().clips.find((c) => c.id === id);
if (!src) return;
// No checkpoint here: the lane coordinator's drag gesture already pushed
// one at pointer-down, so the whole move is a single undo step.
- const v = {
- assetId: src.assetId,
- in: src.in,
- out: src.out,
- muted: src.muted,
- hidden: src.hidden,
- frame: src.frame,
- fit: src.fit,
- speed: src.speed,
- };
+ const onBase = src.track === 0;
if (place.kind === "track" && place.track === 0) {
- if (source.kind === "clip") return; // a same-track move commits through the lane coordinator
- const taken = footprints(s.clips);
- const clip: VideoClip = {
- id: uid(),
- ...v,
- start: nextFreeStart(taken, Math.max(0, start), clipLen({ ...v, id: "", start: 0 })),
- };
+ if (onBase) return; // a same-track move commits through the lane coordinator
+ // Drop a layer clip down onto the base row: slide to its next free slot.
+ const taken = footprints(baseClips(get().clips));
+ const at = nextFreeStart(taken, Math.max(0, start), clipLen(src));
set((st) => ({
- clips: [...st.clips, clip].sort((a, b) => a.start - b.start),
- overlayClips: st.overlayClips.filter((c) => c.id !== source.id),
- ...sole({ kind: "clip", id: clip.id }),
+ clips: st.clips.map((c) =>
+ c.id === id ? { ...c, track: 0, start: at } : c
+ ).sort((a, b) => a.start - b.start),
+ ...sole({ kind: "clip", id }),
}));
return;
}
const track = place.kind === "insert" ? place.level : place.track;
- if (source.kind === "overlay") {
- set((st) => {
- const shifted =
- place.kind === "insert"
- ? openInsertSlot(st.overlayClips, place.level, source.id)
- : st.overlayClips;
- return {
- overlayClips: shifted.map((c) =>
- c.id === source.id ? { ...c, track, start: Math.max(0, start) } : c
- ),
- ...sole({ kind: "overlayClip", id: source.id }),
- };
- });
- return;
- }
-
- const ov: OverlayClip = { id: uid(), ...v, track, start: Math.max(0, start) };
- set((st) => ({
- clips: st.clips.filter((c) => c.id !== source.id),
- overlayClips: [...shiftTracksUp(st.overlayClips, place), ov],
- ...sole({ kind: "overlayClip", id: ov.id }),
- }));
+ set((st) => {
+ // Inserting a new track opens the slot by renumbering the others; the
+ // moved clip itself is excluded from the shift, then placed at `track`.
+ const shifted =
+ place.kind === "insert" ? openInsertSlot(st.clips, place.level, id) : st.clips;
+ return {
+ clips: shifted
+ .map((c) => (c.id === id ? { ...c, track, start: Math.max(0, start) } : c))
+ .sort((a, b) => a.start - b.start),
+ ...sole({ kind: "clip", id }),
+ };
+ });
},
updateOverlayClip: (id, patch) => {
@@ -987,7 +986,7 @@ export const useEditor = create<EditorState>((set, get) => {
updateOverlayClipTransient: (id, patch) =>
set((s) => ({
- overlayClips: s.overlayClips.map((c) => (c.id === id ? { ...c, ...patch } : c)),
+ clips: s.clips.map((c) => (c.id === id ? { ...c, ...patch } : c)),
})),
detachAudio: () => {
@@ -1039,26 +1038,27 @@ export const useEditor = create<EditorState>((set, get) => {
}
}
- // An overlay clip selected: slice it in place, like a track-0 clip.
- if (selection?.kind === "overlayClip") {
- const c = get().overlayClips.find((x) => x.id === selection.id);
- if (c) {
+ // A layer clip (not on the base row) selected: slice it in place. A base
+ // clip falls through to the playhead-driven span split below.
+ if (selection?.kind === "clip") {
+ const c = get().clips.find((x) => x.id === selection.id);
+ if (c && c.track !== 0) {
const sp = c.speed && c.speed > 0 ? c.speed : 1;
const eff = (c.out - c.in) / sp;
if (t > c.start + 0.05 && t < c.start + eff - 0.05) {
push();
const cutIn = c.in + (t - c.start) * sp;
- const left: OverlayClip = { ...c, out: cutIn };
- const right: OverlayClip = { ...c, id: uid(), start: t, in: cutIn };
+ const left: VideoClip = { ...c, out: cutIn };
+ const right: VideoClip = { ...c, id: uid(), start: t, in: cutIn };
set((s) => {
- const idx = s.overlayClips.findIndex((x) => x.id === c.id);
- const next = [...s.overlayClips];
+ const idx = s.clips.findIndex((x) => x.id === c.id);
+ const next = [...s.clips];
next.splice(idx, 1, left, right);
- return { overlayClips: next, ...sole({ kind: "overlayClip", id: right.id }) };
+ return { clips: next, ...sole({ kind: "clip", id: right.id }) };
});
}
+ return;
}
- return;
}
// A title selected: both halves keep the full text and style.
@@ -1147,7 +1147,6 @@ export const useEditor = create<EditorState>((set, get) => {
);
const clipIds = idsOf("clip");
const audioIds = idsOf("audio");
- const overlayClipIds = idsOf("overlayClip");
const textIds = idsOf("text");
const cueIds = idsOf("cue");
// Every track is free-positioned: deleting leaves a gap and nothing
@@ -1155,7 +1154,6 @@ export const useEditor = create<EditorState>((set, get) => {
set((s) => ({
clips: s.clips.filter((c) => !clipIds.has(c.id)),
audioClips: s.audioClips.filter((c) => !audioIds.has(c.id)),
- overlayClips: s.overlayClips.filter((c) => !overlayClipIds.has(c.id)),
overlays: s.overlays.filter((o) => !textIds.has(o.id)),
subtitles: {
...s.subtitles,
@@ -1181,12 +1179,16 @@ export const useEditor = create<EditorState>((set, get) => {
for (const sel of sels) {
if (sel.kind === "clip") {
const sp = spans.find((x) => x.clip.id === sel.id);
- if (sp) add(sp.start, sp.start + sp.len);
- } else if (sel.kind === "overlayClip") {
- const c = s.overlayClips.find((x) => x.id === sel.id);
- if (c) {
- const sp = c.speed && c.speed > 0 ? c.speed : 1;
- add(c.start, c.start + Math.max(0.1, (c.out - c.in) / sp));
+ if (sp) {
+ add(sp.start, sp.start + sp.len);
+ } else {
+ // A layer clip carries no span (spans are the base row); use its
+ // own footprint.
+ const c = s.clips.find((x) => x.id === sel.id);
+ if (c) {
+ const speed = c.speed && c.speed > 0 ? c.speed : 1;
+ add(c.start, c.start + Math.max(0.1, (c.out - c.in) / speed));
+ }
}
} else if (sel.kind === "audio") {
const c = s.audioClips.find((x) => x.id === sel.id);
@@ -1232,18 +1234,19 @@ export const useEditor = create<EditorState>((set, get) => {
for (const sel of sels) {
if (sel.kind === "clip") {
const sp = spans.find((x) => x.clip.id === sel.id);
- if (!sp) continue;
- const mi = mediaFor(sp.clip.assetId);
- if (mi == null) continue;
- // Track-0 clips re-materialize onto track 0 (asClip), so a template
- // stands up its own video instead of an empty timeline.
- layers.push({ media: mi, start: sp.start - start0, in: sp.clip.in, out: sp.clip.out, frame: sp.clip.frame, fit: sp.clip.fit, muted: sp.clip.muted, speed: sp.clip.speed, track: 1, asClip: true });
- } else if (sel.kind === "overlayClip") {
- const c = s.overlayClips.find((x) => x.id === sel.id);
- if (!c) continue;
- const mi = mediaFor(c.assetId);
- if (mi == null) continue;
- layers.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, frame: c.frame, fit: c.fit, muted: c.muted, speed: c.speed, track: c.track + 1 });
+ if (sp) {
+ const mi = mediaFor(sp.clip.assetId);
+ if (mi == null) continue;
+ // Base-row clips re-materialize onto track 0 (asClip), so a template
+ // stands up its own video instead of an empty timeline.
+ layers.push({ media: mi, start: sp.start - start0, in: sp.clip.in, out: sp.clip.out, frame: sp.clip.frame, fit: sp.clip.fit, muted: sp.clip.muted, speed: sp.clip.speed, track: 1, asClip: true });
+ } else {
+ const c = s.clips.find((x) => x.id === sel.id);
+ if (!c) continue;
+ const mi = mediaFor(c.assetId);
+ if (mi == null) continue;
+ layers.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, frame: c.frame, fit: c.fit, muted: c.muted, speed: c.speed, track: c.track + 1 });
+ }
} else if (sel.kind === "audio") {
const c = s.audioClips.find((x) => x.id === sel.id);
if (!c) continue;
@@ -1273,7 +1276,7 @@ export const useEditor = create<EditorState>((set, get) => {
const isClip = (l: (typeof usable)[number]) =>
l.asClip ?? (l as { onBase?: boolean }).onBase;
const clipLayers = usable.filter((l) => isClip(l));
- const overlayLayers = usable.filter((l) => !isClip(l));
+ const overlayLayerDefs = usable.filter((l) => !isClip(l));
// Clip layers append at the end of the current track 0; the
// free-positioned parts (overlays, audio, captions) shift to line up with
// that segment. A template with no clip layers drops in at the playhead.
@@ -1281,6 +1284,7 @@ export const useEditor = create<EditorState>((set, get) => {
const newClips: VideoClip[] = [...clipLayers]
.sort((a, b) => a.start - b.start)
.map((l) => ({
+ track: 0,
start: l.start + shift,
id: uid(),
assetId: assetIds[l.media],
@@ -1291,11 +1295,16 @@ export const useEditor = create<EditorState>((set, get) => {
...(l.fit ? { fit: l.fit } : {}),
...(l.speed ? { speed: l.speed } : {}),
}));
- const topTrack = Math.max(0, ...get().overlayClips.map((c) => c.track));
- const newOverlays: OverlayClip[] = overlayLayers.map((l) => ({
+ const topTrack = Math.max(0, ...overlayLayers(get().clips).map((c) => c.track));
+ // Template layers store `track` as the source track + 1 (so a track-1
+ // layer saved as 2, a track −1 backdrop as 0). Above-layers stack on top
+ // of the project's current top; a backdrop (stored ≤ 0) goes back behind
+ // the base row at its original negative level — never onto track 0, which
+ // would splice it into the master sequence.
+ const newLayers: VideoClip[] = overlayLayerDefs.map((l) => ({
id: uid(),
assetId: assetIds[l.media],
- track: topTrack + l.track,
+ track: l.track > 0 ? topTrack + l.track : l.track - 1,
start: l.start + shift,
in: l.in,
out: l.out,
@@ -1332,8 +1341,7 @@ export const useEditor = create<EditorState>((set, get) => {
end: c.end + shift,
}));
set((s) => ({
- clips: [...s.clips, ...newClips].sort((a, b) => a.start - b.start),
- overlayClips: [...s.overlayClips, ...newOverlays],
+ clips: [...s.clips, ...newClips, ...newLayers].sort((a, b) => a.start - b.start),
audioClips: [...s.audioClips, ...newAudio],
overlays: [...s.overlays, ...newTexts],
subtitles: {
@@ -1375,10 +1383,10 @@ export const useEditor = create<EditorState>((set, get) => {
const spans = getClipSpans(s.clips, s.assets);
const duration = projectDuration(s);
const assetById = new Map(s.assets.map((a) => [a.id, a]));
- // Speech can live on the soundtrack or on an overlay video track, not just
- // track 0. Overlay-video audio mixes into the transcribe pass as a
+ // Speech can live on the soundtrack or on a layer video track, not just
+ // the base row. Layer-clip audio mixes into the transcribe pass as a
// positioned source (exactly like a soundtrack clip), so dialogue carried
- // on an overlay clip gets captioned and an overlay-only cut still works.
+ // on a layer clip gets captioned and a layer-only cut still works.
const audio = s.audioClips
.filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId))
.map((a) => ({
@@ -1390,7 +1398,7 @@ export const useEditor = create<EditorState>((set, get) => {
speed: a.speed,
}))
.concat(
- s.overlayClips
+ overlayLayers(s.clips)
.filter(
(c) => !c.hidden && !c.muted && c.start < duration && assetById.has(c.assetId),
)
@@ -2005,9 +2013,6 @@ export const useEditor = create<EditorState>((set, get) => {
} 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 === "overlayClip") {
- const c = s.overlayClips.find((x) => x.id === sel.id);
- if (c) items.push({ kind: "overlayClip", item: { ...c } });
} else if (sel?.kind === "text") {
const o = s.overlays.find((x) => x.id === sel.id);
if (o) items.push({ kind: "text", item: { ...o } });
@@ -2034,14 +2039,15 @@ export const useEditor = create<EditorState>((set, get) => {
set((cur) => {
let clips = cur.clips;
let audioClips = cur.audioClips;
- let overlayClips = cur.overlayClips;
let overlays = cur.overlays;
// Every item aims for the playhead but respects what already sits on
// its lane: an occupied spot slides the paste right to the next gap
// that fits. Earlier items of this same paste count too.
for (const cb of clipboard) {
if (cb.kind === "clip") {
- const taken = footprints(clips);
+ // Collision is per-track: a clip lands clear of others on its own
+ // row (the base row, or its layer).
+ const taken = footprints(clips.filter((c) => c.track === cb.item.track));
const clip: VideoClip = {
...cb.item,
id: uid(),
@@ -2056,13 +2062,6 @@ export const useEditor = create<EditorState>((set, get) => {
const item: AudioClip = { ...cb.item, id: uid(), start: nextFreeStart(taken, t, clipLen(cb.item)) };
audioClips = [...audioClips, item];
newSel.push({ kind: "audio", id: item.id });
- } else if (cb.kind === "overlayClip") {
- const taken = footprints(
- overlayClips.filter((c) => c.track === cb.item.track),
- );
- const item: OverlayClip = { ...cb.item, id: uid(), start: nextFreeStart(taken, t, clipLen(cb.item)) };
- overlayClips = [...overlayClips, item];
- newSel.push({ kind: "overlayClip", id: item.id });
} else {
const len = Math.max(0.2, cb.item.end - cb.item.start);
const taken = overlays
@@ -2074,7 +2073,7 @@ export const useEditor = create<EditorState>((set, get) => {
newSel.push({ kind: "text", id: item.id });
}
}
- return { clips, audioClips, overlayClips, overlays, selection: newSel[newSel.length - 1] ?? null, multiSelection: newSel };
+ return { clips, audioClips, overlays, selection: newSel[newSel.length - 1] ?? null, multiSelection: newSel };
});
return true;
},
@@ -2104,7 +2103,6 @@ useEditor.subscribe((s, prev) => {
if (
s.clips !== prev.clips ||
s.audioClips !== prev.audioClips ||
- s.overlayClips !== prev.overlayClips ||
s.overlays !== prev.overlays ||
s.subtitles !== prev.subtitles
)
@@ -2134,7 +2132,6 @@ export function serializeDoc(s: {
assets: MediaAsset[];
clips: VideoClip[];
audioClips: AudioClip[];
- overlayClips: OverlayClip[];
overlays: TextOverlay[];
aspect: Aspect;
fadeIn: number;
@@ -2148,7 +2145,6 @@ export function serializeDoc(s: {
assets: storedAssets(s.assets),
clips: s.clips,
audioClips: s.audioClips,
- overlayClips: s.overlayClips,
overlays: s.overlays,
aspect: s.aspect,
fadeIn: s.fadeIn,
@@ -2188,9 +2184,12 @@ export function getClipSpans(
clips: VideoClip[],
assets: MediaAsset[]
): ClipSpan[] {
+ // Spans are the base row (track 0): the master sequence that carries
+ // transitions and drives playback. Layer clips composite separately.
// Map lookup, not a per-clip assets.find — this runs every playback frame.
const byId = new Map(assets.map((a) => [a.id, a]));
const present = clips
+ .filter((clip) => clip.track === 0)
.map((clip) => ({ clip, asset: byId.get(clip.assetId) }))
.filter((x): x is { clip: VideoClip; asset: MediaAsset } => !!x.asset)
.sort((a, b) => a.clip.start - b.clip.start);
@@ -2212,7 +2211,7 @@ export function getClipSpans(
* so gaps count toward this, they just play black). */
export function totalDuration(clips: VideoClip[]) {
let end = 0;
- for (const c of clips) end = Math.max(end, c.start + clipLen(c));
+ for (const c of clips) if (c.track === 0) end = Math.max(end, c.start + clipLen(c));
return end;
}
@@ -2254,14 +2253,12 @@ export function spanSequence(spans: ClipSpan[]): { gapBefore: number; span: Clip
* reachable. */
export function projectDuration(s: {
clips: VideoClip[];
- overlayClips: OverlayClip[];
audioClips: AudioClip[];
}): number {
- let end = totalDuration(s.clips);
- for (const c of s.overlayClips) {
- const sp = c.speed && c.speed > 0 ? c.speed : 1;
- end = Math.max(end, c.start + Math.max(0.1, (c.out - c.in) / sp));
- }
+ let end = 0;
+ // Any clip on any track extends the timeline; a layer running past track 0's
+ // end is still reachable.
+ for (const c of s.clips) end = Math.max(end, c.start + clipLen(c));
for (const a of s.audioClips) end = Math.max(end, a.start + clipLen(a));
return Math.max(0, end);
}
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index c8b35050..7a668eca 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -107,6 +107,12 @@ export function regionLabel(r: FrameRect): string {
export interface VideoClip {
id: string;
assetId: string;
+ /** Which video track this clip sits on. Track 0 is the base row — its clips
+ * form the master sequence that carries transitions and drives playback.
+ * Positive tracks composite above it (higher = closer to the top and wins
+ * where clips overlap); negative tracks sit behind as a backdrop. Absent in
+ * older docs, which are all track 0. */
+ track: number;
start: number; // timeline position, seconds
in: number; // trim-in inside the source, seconds
out: number; // trim-out inside the source, seconds
@@ -117,7 +123,8 @@ export interface VideoClip {
* cover it ("fill", cropping the overflow). */
fit?: "fit" | "fill";
/** The region of the frame this clip occupies; absent = full frame. Lets a
- * track-0 clip share the frame with an overlay (e.g. sit in the top half). */
+ * clip share the frame with another track (e.g. a split-screen half) or float
+ * small over it (picture-in-picture). */
frame?: FrameRect;
/** Crop-window pan in fill mode, -1..1 per axis (0 = centered): which part
* of the oversized video stays visible. */
@@ -137,30 +144,6 @@ export interface VideoClip {
hidden?: boolean;
}
-/**
- * A clip on a video track other than track 0 — free-positioned in time (like
- * the soundtrack) and composited with the track-0 clips. `track` 1 sits just
- * above track 0, higher tracks sit closer to the top and win where they
- * overlap; negative tracks sit behind. A full-frame overlay covers everything
- * below it ("topmost showing clip plays"); a regioned one shares the frame
- * (split-screen half) or floats small (picture-in-picture).
- */
-export interface OverlayClip {
- id: string;
- assetId: string;
- track: number; // signed, non-zero; higher = closer to the top
- start: number; // timeline position, seconds
- in: number;
- out: number;
- muted: boolean;
- hidden?: boolean;
- /** The region of the frame this overlay occupies; absent = full frame. */
- frame?: FrameRect;
- /** How the video meets its region: cover-and-crop ("fill") or contain ("fit"). */
- fit?: "fit" | "fill";
- speed?: number;
-}
-
/** Speed limits — matches the Inspector control and export atempo range. */
export const SPEED_MIN = 0.25;
export const SPEED_MAX = 4;
@@ -422,7 +405,6 @@ export const emptySubtitles = (): SubtitlesBlock => ({
export type Selection =
| { kind: "clip"; id: string }
| { kind: "audio"; id: string }
- | { kind: "overlayClip"; id: string }
| { kind: "text"; id: string }
| { kind: "cue"; id: string }
| null;
@@ -444,10 +426,14 @@ export interface ProjectDoc {
createdAt: number;
updatedAt: number;
assets: StoredAsset[];
+ /** Every video clip, on any track (the `track` field places it). Older docs
+ * split these into track-0 `clips` plus an `overlayClips` array; the loader
+ * folds that shape into this one. */
clips: VideoClip[];
audioClips: AudioClip[];
- /** Video tracks other than track 0 (`clips`); absent in older docs. */
- overlayClips?: OverlayClip[];
+ /** Legacy: video clips on tracks other than 0, kept a separate array in older
+ * docs. Read on open and merged into `clips`; new saves never write it. */
+ overlayClips?: VideoClip[];
overlays: TextOverlay[];
/** Output frame; absent in older projects (which are all 9:16). */
aspect?: Aspect;
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index c500ec97..3a25cf05 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -80,9 +80,9 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "select",
description:
- "Select a clip, overlay video, soundtrack clip, or title (or clear the selection). Selection drives the inspector panel.",
+ "Select a video clip (on any track), soundtrack clip, or title (or clear the selection). Selection drives the inspector panel.",
inputSchema: obj({
- kind: { type: "string", enum: ["clip", "overlayClip", "audio", "text", "none"], description: "What to select" },
+ kind: { type: "string", enum: ["clip", "audio", "text", "none"], description: "What to select — 'clip' is any video clip, whatever track" },
id: str("The item id (omit for kind=none)"),
}, ["kind"]),
},
@@ -124,9 +124,9 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "delete_item",
description:
- "Delete a video clip, overlay video, soundtrack clip, or title by id. Every track is free-positioned, so deleting leaves a gap; place_clip can slide a neighbor into it if the cut should stay tight.",
+ "Delete a video clip (any track), soundtrack clip, or title by id. Every track is free-positioned, so deleting leaves a gap; place_clip can slide a neighbor into it if the cut should stay tight.",
inputSchema: obj({
- kind: { type: "string", enum: ["clip", "overlayClip", "audio", "text"], description: "Item kind" },
+ kind: { type: "string", enum: ["clip", "audio", "text"], description: "Item kind — 'clip' is any video clip, whatever track" },
id: str("Item id"),
}, ["kind", "id"]),
},
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index f96572a7..1fd4a2ed 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -106,7 +106,16 @@ export const projectsApi = {
assets: Array.isArray(body.assets) ? body.assets : existing.assets,
clips: Array.isArray(body.clips) ? body.clips : existing.clips,
audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,
- overlayClips: Array.isArray(body.overlayClips) ? body.overlayClips : existing.overlayClips,
+ // Layer clips now live in `clips` (each with its `track`). A merged
+ // client saves `clips` with no `overlayClips`, which clears the legacy
+ // array so the two shapes can't drift or duplicate. A pre-merge client
+ // still sends both — its `overlayClips` are real layer data, so they
+ // persist untouched rather than being silently deleted.
+ overlayClips: Array.isArray(body.overlayClips)
+ ? body.overlayClips
+ : Array.isArray(body.clips)
+ ? []
+ : existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
aspect: body.aspect === "9:16" || body.aspect === "16:9" ? body.aspect : existing.aspect,
fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,
diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.ts
index 7e286cd1..f9800e79 100644
--- a/site/src/cut/server/projects.ts
+++ b/site/src/cut/server/projects.ts
@@ -139,9 +139,13 @@ async function dirSize(dir: string): Promise<number> {
}
async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {
- const duration = doc.clips.reduce((sum, c) => sum + Math.max(0, c.out - c.in), 0);
+ // The base row (track 0) is the cut: layer clips composite over it, so they
+ // add nothing to the summary's duration, count, or poster. Legacy docs carry
+ // no `track` on clips — those are all base-row.
+ const base = doc.clips.filter((c) => (c.track ?? 0) === 0);
+ const duration = base.reduce((sum, c) => sum + Math.max(0, c.out - c.in), 0);
// Preview: the first clip's source video, else any video asset.
- const firstClip = doc.clips[0];
+ const firstClip = base[0];
const firstClipAsset = firstClip
? doc.assets.find((a) => a.id === firstClip.assetId)
: undefined;
@@ -159,7 +163,7 @@ async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
duration,
- clipCount: doc.clips.length,
+ clipCount: base.length,
assetCount: doc.assets.length,
previewFile: previewAsset?.fileName,
previewIsImage: previewAsset?.type === "image",