Open source CapCut alternative.
TypeScript
refactor(site): remove the base-track concept — video is tracks around track 0 [rebuild]
David Leb4ae72b428ee
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 760eab4a..1a85ae13 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -205,9 +205,9 @@ export function Editor({const s = useEditor.getState();s.addAsset(asset);if (asset.type === "video" || asset.type === "image") {- // A drop on the timeline lands at the pointer (sliding to the base- // track's next free slot); anywhere else appends at the end. A- // still rides the base track like footage.+ // A drop on the timeline lands at the pointer (sliding to track+ // 0's next free slot); anywhere else appends at the end. A still+ // rides track 0 like footage.s.addClipFromAsset(asset.id, at ?? undefined);} else {// A timeline drop lands at the pointer; anywhere else drops at thediff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 854b2e3e..77fa3e00 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -200,7 +200,7 @@ const Value = ({ children, className }: { children: React.ReactNode; className?:);/** One-click frame layouts (Full / Top / Bottom / Left / Right / PiP) shared by- * the base-clip and overlay-clip panels. Picking one regions the clip so two+ * the video-clip and overlay-clip panels. Picking one regions the clip so two* videos can share the frame; "Full" clears the region. */function LayoutButtons({rect,diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex 677dcb69..8744d5ca 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -139,7 +139,7 @@ export function Preview() {/*** Direct-manipulation handle for the selected video layer's frame region: drag* the box to reposition, drag the corner to resize (both update the clip's- * `frame` rect). Works for a regioned base clip (split-screen half) or an+ * `frame` rect). Works for a regioned track-0 clip (split-screen half) or an* overlay clip, and only while that clip is live under the playhead so it lines* up with the compositor. A full-frame layer needs no handle.*/diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 8968f75c..835d7f75 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -42,23 +42,18 @@ const TRANSITION_ICONS: Record<TransitionStyle, LucideIcon> = {};const VIDEO_H = 64;-const OVERLAY_H = VIDEO_H; // upper video tracks match the base row height+const OVERLAY_H = VIDEO_H; // every video track shares the same row heightconst AUDIO_H = 44;/** Where a dragged video clip can land. Re-exported name for the store's- * placement union (existing track / base row / newly-inserted track). */+ * placement union (existing track, 0 included / newly-inserted track). */type TrackTarget = VideoTrackPlacement;/** Encode/decode a placement in a row's `data-drop` attribute. */function placementAttr(place: TrackTarget): string {- return place.kind === "base"- ? "base"- : place.kind === "track"- ? `track:${place.track}`- : `insert:${place.level}`;+ return place.kind === "track" ? `track:${place.track}` : `insert:${place.level}`;}function parsePlacement(raw: string): TrackTarget | null {- if (raw === "base") return { kind: "base" };const [k, n] = raw.split(":");if (k === "track") return { kind: "track", track: Number(n) };if (k === "insert") return { kind: "insert", level: Number(n) };@@ -69,10 +64,10 @@ function samePlacement(a: TrackTarget | null, b: TrackTarget | null): boolean {if (!a || !b || a.kind !== b.kind) return false;return a.kind === "track"? a.track === (b as { track: number }).track- : a.kind === "insert"- ? a.level === (b as { level: number }).level- : true;+ : a.level === (b as { level: number }).level;}+/** Video track 0 — the store's `clips` array — as a drop placement. */+const TRACK_ZERO: TrackTarget = { kind: "track", track: 0 };const TEXT_H = 28;const SUB_H = 22;const PAD_END = 320;@@ -92,13 +87,13 @@ const trimHandle =/** On-timeline length a dropped image occupies (it has no intrinsic duration). */const STILL_SECONDS = IMAGE_CLIP_SECONDS;-/** A base-track asset type — footage or a still image both ride the video lane. */-const isBaseType = (t: string | undefined): t is "video" | "image" =>+/** An asset type that lands as a video clip — footage or a still image. */+const isClipMedia = (t: string | undefined): t is "video" | "image" =>t === "video" || t === "image";/** The image ref being dragged (a stock tile), null for any other drag —* asset and library drags carry the ref MIME too but with video/audio kinds.- * On the timeline it lands on the base track as a still image. */+ * On the timeline it lands on video track 0 as a still image. */function draggingStill(e: React.DragEvent): AssetRef | null {if (!hasRefDrag(e)) return null;const ref = draggingRef();@@ -149,7 +144,7 @@ export function Timeline() {if (!dragging) heldContentW.current = liveContentW;const contentW = heldContentW.current;- // Drop preview while dragging a media asset onto the base track: where the+ // Drop preview while dragging a media asset onto video track 0: where the// pointer is and how long the clip would run.const [assetDrop, setAssetDrop] = useState<{ t: number; len: number } | null>(null);// Kind of external media being dragged over the timeline (audio vs video).@@ -165,7 +160,7 @@ export function Timeline() {const [snapX, setSnapX] = useState<number | null>(null);const insertMode = videoDragging || dropType === "video";- // Which drop the cursor is over: an upper track, the base row, or a gap+ // Which drop the cursor is over: an existing track (0 included) or a gap// between/above/below tracks that would open a new one. Hit-test live via// elementFromPoint — rows and gap zones carry a `data-drop` placement.const resolveDropTrack = useCallback((clientX: number, clientY: number): TrackTarget => {@@ -182,29 +177,29 @@ export function Timeline() {if (clientY > rows[rows.length - 1].getBoundingClientRect().bottom)return { kind: "insert", level: Math.min(0, ...tracks) - 1 };}- return { kind: "base" };+ return TRACK_ZERO;}, []);// Drive the drop preview while a clip is dragged across tracks: highlight the- // target track, base slot, or a between-track insertion line.+ // target track's slot or a between-track insertion line.const previewCross = useCallback((target: TrackTarget | null, start = 0, len = 0) => {if (target === null) return setOverlayDrop(null);setOverlayDrop({ target, t: start, len });}, []);- // Releasing a base clip anywhere but the base row lifts it out onto that track- // (or a new one); on the base row the lane coordinator commits the move.- const onBaseCrossDrop = useCallback(+ // Releasing a track-0 clip on any other track lifts it out onto that track+ // (or a new one); on its own track the lane coordinator commits the move.+ const onClipCrossDrop = useCallback((id: string, target: TrackTarget, start: number) => {previewCross(null);- if (target.kind === "base") return;- useEditor.getState().dropVideoClip({ kind: "base", id }, target, start);+ if (samePlacement(target, TRACK_ZERO)) return;+ useEditor.getState().dropVideoClip({ kind: "clip", id }, target, start);},[previewCross]);// Releasing an overlay clip anywhere: another track, a new inserted track, or- // down into the base row.+ // down onto track 0.const onOverlayCrossDrop = useCallback((id: string, target: TrackTarget, start: number) => {previewCross(null);@@ -226,9 +221,9 @@ export function Timeline() {return { used, rowOf, count: used.length };}, [overlays]);- // Video tracks either side of the base: positive tracks (PiP / composited- // layers) render above the base, negative ones below it as a backdrop. Both- // list highest-first (nearest the base at the inner edge); empty tracks vanish.+ // Video tracks either side of track 0: positive tracks (PiP / composited+ // layers) render above it, negative ones below it as a backdrop. Both list+ // highest-first (nearest track 0 at the inner edge); empty tracks vanish.const aboveTracks = useMemo(() => [...new Set(overlayClips.map((c) => c.track).filter((n) => n > 0))].sort((a, b) => b - a),[overlayClips]@@ -408,7 +403,7 @@ export function Timeline() {audioRow = 0) => {const s = useEditor.getState();- if (isBaseType(type)) {+ if (isClipMedia(type)) {s.addClipFromAsset(assetId, t);} else {const used = [...new Set(s.audioClips.map((a) => a.lane ?? 0))].sort((a, b) => a - b);@@ -423,13 +418,13 @@ export function Timeline() {const draggedVideo = (e: React.DragEvent): { duration: number } | null => {if (hasLibraryDrag(e)) {const lib = draggingLibrary();- if (!lib || !isBaseType(lib.type)) return null;+ if (!lib || !isClipMedia(lib.type)) return null;return { duration: lib.type === "image" ? STILL_SECONDS : lib.duration };}const id = draggingAssetId();if (id) {const asset = useEditor.getState().assets.find((a) => a.id === id);- if (!asset || !isBaseType(asset.type)) return null;+ if (!asset || !isClipMedia(asset.type)) return null;return { duration: asset.type === "image" ? STILL_SECONDS : asset.duration };}const stockVideo = draggingStockVideo(e);@@ -466,7 +461,7 @@ export function Timeline() {const stockVideo = draggingStockVideo(e);const projectId = useEditor.getState().projectId;clearAssetDrag();- if (libId && lib && isBaseType(lib.type) && projectId) {+ if (libId && lib && isClipMedia(lib.type) && projectId) {void importLibraryAsset(projectId, lib).then((asset) => useEditor.getState().addVideoFromAsset(asset.id, place, t)).catch(() => {});@@ -474,7 +469,7 @@ export function Timeline() {}const id = draggedAssetId(e);const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;- if (id && isBaseType(asset?.type)) {+ if (id && isClipMedia(asset?.type)) {useEditor.getState().addVideoFromAsset(id, place, t);return;}@@ -559,8 +554,8 @@ export function Timeline() {type = asset?.type;duration = asset?.type === "image" ? STILL_SECONDS : asset?.duration ?? 0;}- // A still rides the base (video) lane: light its insertion zones.- setDropType(isBaseType(type) ? "video" : type ?? null);+ // A still rides the video tracks: light their insertion zones.+ setDropType(isClipMedia(type) ? "video" : type ?? null);if (type === "audio") {// Preview which audio row the sound would land on.setAudioDrop({@@ -572,7 +567,7 @@ export function Timeline() {return;}setAudioDrop(null);- if (!isBaseType(type) || !duration) {+ if (!isClipMedia(type) || !duration) {setAssetDrop(null);return;}@@ -619,7 +614,7 @@ export function Timeline() {}// A stock clip imports as footage, an image ref as a still, then each- // snaps into the base-track slot.+ // lands in the track-0 slot.if (stockVideo && projectId) {e.preventDefault();void importStockVideo(projectId, { url: stockVideo.url, name: stockVideo.name })@@ -746,7 +741,7 @@ export function Timeline() {<divclassName="relative mt-1.5"style={{ height: VIDEO_H }}- data-drop="base"+ data-drop={placementAttr(TRACK_ZERO)}onPointerDown={deselectIfSelf}>{insertMode && insertZone(1)}@@ -756,7 +751,7 @@ export function Timeline() {<Plus className="size-3.5" /> Add media to this project</div>)}- {samePlacement(overlayDrop?.target ?? null, { kind: "base" }) && (+ {samePlacement(overlayDrop?.target ?? null, TRACK_ZERO) && (<divclassName="pointer-events-none absolute top-0.5 rounded-lg border-[1.5px] border-dashed border-[#0a84ff]/70 bg-[#0a84ff]/10"style={{@@ -800,7 +795,7 @@ export function Timeline() {onSnap={setSnapX}resolveTarget={resolveDropTrack}onCrossMove={previewCross}- onCrossDrop={onBaseCrossDrop}+ onCrossDrop={onClipCrossDrop}onDragActive={setVideoDragging}/>))}@@ -919,7 +914,7 @@ export function Timeline() {/>)}{audioClips.map((a) => {- const baseRow = audioLanes.rowOf.get(a.lane ?? 0) ?? 0;+ const homeRow = audioLanes.rowOf.get(a.lane ?? 0) ?? 0;const drag = laneDrag?.kind === "audio" && laneDrag.id === a.id ? laneDrag : null;return (<AudioView@@ -927,8 +922,8 @@ export function Timeline() {clip={a}asset={assets.find((x) => x.id === a.assetId)}pps={pps}- top={(drag ? drag.targetRow : baseRow) * AUDIO_H}- baseRow={baseRow}+ top={(drag ? drag.targetRow : homeRow) * AUDIO_H}+ homeRow={homeRow}laneCount={audioLanes.count}selected={selKeys.has(`audio:${a.id}`)}drag={drag}@@ -963,15 +958,15 @@ export function Timeline() {/>)}{overlays.map((o) => {- const baseRow = overlayLanes.rowOf.get(o.lane ?? 0) ?? 0;+ const homeRow = overlayLanes.rowOf.get(o.lane ?? 0) ?? 0;const drag = laneDrag?.kind === "text" && laneDrag.id === o.id ? laneDrag : null;return (<TextBarkey={o.id}overlay={o}pps={pps}- top={(drag ? drag.targetRow : baseRow) * TEXT_H}- baseRow={baseRow}+ top={(drag ? drag.targetRow : homeRow) * TEXT_H}+ homeRow={homeRow}laneCount={overlayLanes.count}selected={selKeys.has(`text:${o.id}`)}drag={drag}@@ -1005,7 +1000,7 @@ export function Timeline() {cue={c}pps={pps}top={(c.lane ?? 0) * SUB_H}- baseRow={c.lane ?? 0}+ homeRow={c.lane ?? 0}selected={selKeys.has(`cue:${c.id}`)}drag={laneDrag?.kind === "cue" && laneDrag.id === c.id ? laneDrag : null}parting={laneDrag?.kind === "cue" && laneDrag.id !== c.id}@@ -1258,11 +1253,11 @@ function ClipView({selected: boolean;/** This clip's live drag when it is the one being carried (ghost mode). */drag: LaneDrag | null;- /** Another base clip is dragging: animate this one's parting shifts. */+ /** Another track-0 clip is dragging: animate this one's parting shifts. */parting: boolean;onDrag: (d: LaneDrag | null) => void;onSnap: (x: number | null) => void;- /** Which drop the given screen point is over (track / base / insert gap). */+ /** Which drop the given screen point is over (a track / an insert gap). */resolveTarget: (clientX: number, clientY: number) => TrackTarget;/** Preview a cross-track drop (null clears it). */onCrossMove: (target: TrackTarget | null, start?: number, len?: number) => void;@@ -1307,12 +1302,12 @@ function ClipView({pps,rowH: VIDEO_H,laneCount: 0,- baseRow: 0,+ homeRow: 0,onDrag,onSnap,vertical: {resolve: (ev: PointerEvent) => resolveTarget(ev.clientX, ev.clientY),- isHome: (t: TrackTarget) => samePlacement(t, { kind: "base" }),+ isHome: (t: TrackTarget) => samePlacement(t, TRACK_ZERO),preview: (t: TrackTarget | null, start: number, len: number) =>t ? onCrossMove(t, start, len) : onCrossMove(null),commit: (id: string, t: TrackTarget, start: number) => onCrossDrop(id, t, start),@@ -1484,7 +1479,7 @@ function AudioView({asset,pps,top,- baseRow,+ homeRow,laneCount,selected,drag,@@ -1497,7 +1492,7 @@ function AudioView({pps: number;/** Rendered row top in px — follows the drag's target row while carried. */top: number;- baseRow: number;+ homeRow: number;laneCount: number;selected: boolean;/** This bar's live drag when it is the one being carried (ghost mode). */@@ -1537,7 +1532,7 @@ function AudioView({if (!asset) return null;- const ui = { pps, rowH: AUDIO_H, laneCount, baseRow, onDrag, onSnap };+ const ui = { pps, rowH: AUDIO_H, laneCount, homeRow, onDrag, onSnap };return (<div@@ -1635,7 +1630,7 @@ function OverlayClipView({}) {const w = Math.max(10, overlayLen(clip) * pps);- // Same filmstrip as a base clip so an overlay reads as a video, not a+ // Same filmstrip as a track-0 clip so an overlay reads as a video, not a// featureless bar — sampled across the clip's trimmed span.const filmstrip = useMemo(() => {if (!asset?.thumbs?.length || !asset.thumbStep) return [];@@ -1656,13 +1651,13 @@ function OverlayClipView({if (!asset) return null;// The move gesture is the shared lane behavior (parting, snapping); its- // verticality is the video placement system — other tracks, insert gaps,- // and the base row — resolved by DOM hit-testing.+ // verticality is the video placement system — other tracks (0 included)+ // and insert gaps — resolved by DOM hit-testing.const ui = {pps,rowH: OVERLAY_H,laneCount: 0,- baseRow: 0,+ homeRow: 0,onDrag,onSnap,vertical: {@@ -1746,7 +1741,7 @@ function TextBar({overlay: o,pps,top,- baseRow,+ homeRow,laneCount,selected,drag,@@ -1757,7 +1752,7 @@ function TextBar({overlay: TextOverlay;pps: number;top: number;- baseRow: number;+ homeRow: number;laneCount: number;selected: boolean;/** This bar's live drag when it is the one being carried (ghost mode). */@@ -1770,7 +1765,7 @@ function TextBar({onSnap: (x: number | null) => void;}) {const w = Math.max(8, (o.end - o.start) * pps);- const ui = { pps, rowH: TEXT_H, laneCount, baseRow, onDrag, onSnap };+ const ui = { pps, rowH: TEXT_H, laneCount, homeRow, onDrag, onSnap };return (<div@@ -1812,7 +1807,7 @@ function SubBar({cue,pps,top,- baseRow,+ homeRow,selected,drag,parting,@@ -1823,7 +1818,7 @@ function SubBar({pps: number;/** Rendered row top in px — one row per subtitle track (language). */top: number;- baseRow: number;+ homeRow: number;selected: boolean;/** This bar's live drag when it is the one being carried (ghost mode). */drag: LaneDrag | null;@@ -1833,7 +1828,7 @@ function SubBar({onSnap: (x: number | null) => void;}) {const w = Math.max(8, (cue.end - cue.start) * pps);- const ui = { pps, rowH: SUB_H, laneCount: 0, baseRow, onDrag, onSnap };+ const ui = { pps, rowH: SUB_H, laneCount: 0, homeRow, onDrag, onSnap };return (<divdiff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex 830a4270..6d3b4fe7 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -19,9 +19,10 @@ function duckGainAt(audioClips: AudioClip[], t: number): number {return g;}-// A base/overlay clip is backed by a <video> for footage or an <img> for a-// still image. These helpers read either kind uniformly so the compositor-// stays one code path — an image never seeks, plays, or carries audio.+// A video clip on any track is backed by a <video> for footage or an <img>+// for a still image. These helpers read either kind uniformly so the+// compositor stays one code path — an image never seeks, plays, or carries+// audio.type MediaEl = HTMLVideoElement | HTMLImageElement;const isImageEl = (el: MediaEl): el is HTMLImageElement =>typeof HTMLImageElement !== "undefined" && el instanceof HTMLImageElement;@@ -71,7 +72,7 @@ function teardown(el: MediaEl) {// frame, so an aspect switch takes effect seamlessly./**- * Preview engine. One hidden <video> per base clip and one <audio> per+ * Preview engine. One hidden <video> per track-0 clip and one <audio> per* soundtrack clip; the active clip's video element is the master clock while* playing and every frame is composited onto the preview canvas (contain-fit,* matching the export's letterboxing).@@ -89,8 +90,9 @@ class Engine {private raf = 0;private activeClipId: string | null = null;private disposed = false;- // Wall-clock stamp for advancing time past the base track, where there is no- // base video element to act as the master clock.+ // Wall-clock stamp for advancing time where track 0 has nothing playing —+ // in a gap or past its end there is no track-0 video element to act as the+ // master clock.private lastPlayNow = 0;constructor(private canvas: HTMLCanvasElement) {@@ -217,7 +219,7 @@ class Engine {ctx.fillStyle = "#000";ctx.fillRect(0, 0, W, H);}- // A regioned base clip (split-screen half) draws into its rect over the+ // A regioned track-0 clip (split-screen half) draws into its rect over the// black frame; the full-frame path below keeps the pan-crop behavior.const rect = rectOf(clip ?? {});if (!isFullRect(rect)) {@@ -263,7 +265,7 @@ class Engine {let alpha = 0;let masterZoom = 1;let incZoom = 1;- let black = 0; // fade-to-black veil over the base, 0..1+ let black = 0; // fade-to-black veil over the master clip, 0..1let gain = 1; // master audio follows the picture through a fade edge// Warm the next clip's decoder shortly before its entrance (the dissolve// start, or the hard cut) so it enters with a frame already decoded — a@@ -315,20 +317,20 @@ class Engine {}}}- // A live voiceover ducks the base clip's sound under it. The clip's own+ // A live voiceover ducks the master clip's sound under it. The clip's own// volume rides on top (the element clamps at 1; export honors up to 1.5).const duck = duckGainAt(useEditor.getState().audioClips, t);if (!isImageEl(masterEl)) {masterEl.volume = Math.max(0, Math.min(1, gain * duck * (masterSpan.clip.volume ?? 1)));}this.pauseExcept(keep);- // No clear here — the tick clears once, then draws the below tracks, so the- // base composites over them (a regioned base leaves them showing).+ // No clear here — the tick clears once, then draws the negative tracks, so+ // track 0 composites over them (a regioned clip leaves them showing).this.drawLayer(masterEl, masterSpan.clip, false, 1, masterZoom);if (incEl) this.drawLayer(incEl, next!.clip, false, alpha, incZoom);- // Veil only the base's own footprint, like the export's per-clip fade- // filter: a regioned base darkens inside its rect while a below track shows- // through the margins; tracks drawn after (above the base) stay lit.+ // Veil only the master clip's own footprint, like the export's per-clip+ // fade filter: a regioned clip darkens inside its rect while a track+ // behind shows through the margins; tracks drawn after (above) stay lit.if (black > 0) this.fillBlackVeil(black, rectOf(masterSpan.clip));return masterEl;}@@ -378,13 +380,13 @@ class Engine {}/** The picture side of the project fade: a black veil over the whole frame- * (everything drawn this tick — base, tracks, at any time), matching the+ * (everything drawn this tick, on every track, at any time), matching the* export's fade on the final composite. */private drawProjectFade(gain: number) {this.fillBlackVeil(1 - gain);}- /** Overlay clips live at time `t` on one side of the base — `below`+ /** Overlay clips live at time `t` on one side of track 0 — `below`* (track < 0) or `above` (track > 0) — with their assets, in z-order* (further-back first). */private liveOverlays(t: number, side: "below" | "above") {@@ -433,7 +435,7 @@ class Engine {}));}- /** Draw the overlay tracks on one side of the base — `below` (track < 0) or+ /** Draw the overlay tracks on one side of track 0 — `below` (track < 0) or* `above` (track > 0) — in z-order (further-back first). A full-frame clip* covers what's under it; a regioned one shares the frame, letting lower* tracks show in its margins. Collects the clips it touched into `active`.@@ -528,7 +530,7 @@ class Engine {this.videoEls.delete(id);}}- // Whole-project length so time past the base (a longer upper/lower track or+ // Whole-project length so time past track 0's end (a longer video track or// soundtrack) is still reachable while scrubbing and playing.const total = projectDuration(s);@@ -551,11 +553,11 @@ class Engine {const pt =s.skimTime !== null ? Math.max(0, Math.min(s.skimTime, total - 0.001)) : t;const span = spans.find((sp) => pt >= sp.start && pt < sp.start + sp.len);- // Prime every layer live at `pt` — the base element and each overlay+ // Prime every layer live at `pt` — the track-0 element and each overlay// track — before repainting (create them, issue any seeks). A cold// element or an unbuffered seek has no decodable frame yet, and painting- // around it tears the composite: black before the base's seek resolves,- // or the base flashing through where an overlay covers it. Hold the last+ // around it tears the composite: black before the track-0 seek resolves,+ // or track 0 flashing through where an overlay covers it. Hold the last// painted frame until every live layer has a frame, so each scrubbed// frame is the same composite playback and export show.let ready = true;@@ -580,8 +582,8 @@ class Engine {const active = new Set<string>();this.clearCanvas();this.drawOverlays(pt, false, "below", active, belowLive);- // Past the base track there is no base frame — just the backdrop and the- // upper/lower tracks that are still running at `pt`.+ // Where track 0 has nothing live there is no master frame — just the+ // backdrop and the other tracks still running at `pt`.if (span) this.composite(span, spans, Math.min(pt, span.start + span.len), false);else this.pauseExcept(new Set());this.drawOverlays(pt, false, "above", active, aboveLive);@@ -640,9 +642,9 @@ class Engine {atEnd = el.currentTime >= span.clip.out - 0.02 || el.ended;}// Clip boundary: hand off to the next clip when it abuts (or dissolves),- // fall into the gap when it doesn't — the base plays black there and the- // wall clock advances — or (if the base is done but an upper/lower track- // runs on) fall through to the wall-clock tail.+ // fall into the gap when it doesn't — track 0 plays black there and the+ // wall clock advances — or (if track 0 is done but another track runs+ // on) fall through to the wall-clock tail.if (atEnd) {const idx = spans.indexOf(span);const next = spans[idx + 1];@@ -662,7 +664,7 @@ class Engine {t = Math.max(t, span.start + span.len + 0.0001);pauseEl(el);} else if (t >= total - 0.001) {- // Base and every other track finished.+ // Track 0 and every other track finished.useEditor.setState({ playing: false, currentTime: total });pauseEl(el);this.drawOverlays(t, true, "above", active);@@ -674,7 +676,7 @@ class Engine {}this.lastPlayNow = now;} else {- // Past the base track but an upper/lower track is still playing: no master+ // Nothing live on track 0 but another track is still playing: no master// element, so advance time by the wall clock and let the overlays follow.this.pauseExcept(new Set());const now = performance.now();diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 2ed2544b..91d91005 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -113,7 +113,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {muted: sp.clip.muted,framing: sp.clip.fit ?? "fit",speed: r(sp.clip.speed ?? 1),- // The base track is free-positioned: empty stretches play black.+ // Track 0 is free-positioned: empty stretches play black....(() => {const prevEnd = index === 0 ? 0 : spans[index - 1].start + spans[index - 1].len;return sp.start - prevEnd > 0.005 ? { gapBefore: r(sp.start - prevEnd) } : {};@@ -126,7 +126,7 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {? { panX: r(sp.clip.panX ?? 0), panY: r(sp.clip.panY ?? 0) }: {}),})),- // Video layers composited with the base: track > 0 above it (topmost+ // 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) })),soundtrack: s.audioClips.map((a) => ({ id: a.id, ...describeAudio(a, assetById) })),@@ -199,7 +199,7 @@ function describeOverlayClip(c: OverlayClip, assets: Map<string, { name: stringout: r(c.out),muted: c.muted,...(c.hidden ? { hidden: true } : {}),- // The frame region this layer occupies: Full covers the base; Top/Bottom/+ // The frame region this layer occupies: Full covers the frame; Top/Bottom/// Left/Right split it; PiP floats inside it.layout: regionLabel(rect),region: { x: r(rect.x), y: r(rect.y), w: r(rect.w), h: r(rect.h) },diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 9e7c1193..62997915 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -144,7 +144,7 @@ export async function runAiTool(throw new ToolError("Only video or image assets can sit on a video track.");const start = isNum(input.start) ? Math.max(0, input.start) : s.currentTime;const track = isNum(input.track) ? Math.round(input.track) : 1;- if (track === 0) throw new ToolError("Track 0 is the base track — use place_clip for it.");+ if (track === 0) throw new ToolError("Track 0 holds the timeline clips — use place_clip for it.");s.addVideoFromAsset(asset.id, { kind: "track", track }, start);const cur = useEditor.getState();const sel = cur.selection;@@ -178,7 +178,7 @@ export async function runAiTool(}if (isNum(input.track)) {const track = Math.round(input.track);- if (track === 0) throw new ToolError("Track 0 is the base track.");+ if (track === 0) throw new ToolError("Track 0 holds the timeline clips — overlays are non-zero.");patch.track = track;}if (typeof input.muted === "boolean") patch.muted = input.muted;diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 307b9c3e..35e4f5d0 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -212,7 +212,7 @@ async function buildExportForm(clipEntries[i],]);- // Upper video tracks composited over the base; hidden ones are dropped.+ // Video tracks composited around track 0; hidden ones are dropped.const overlayVideos = doc.overlayClips.filter((c) => !c.hidden && assetById.has(c.assetId) && c.start < duration).map((c) => ({@@ -223,7 +223,7 @@ async function buildExportForm(track: c.track,frame: c.frame,// Pass `fit` through unset so the server's "default full-frame overlay- // covers the base" branch fires — normalizing to "fit" here defeated it.+ // covers what's below" branch fires — normalizing to "fit" defeated it.fit: c.fit,muted: c.muted,speed: c.speed,diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.tsindex 71da8f92..bc5ee193 100644--- a/site/src/cut/lib/laneTracks.ts+++ b/site/src/cut/lib/laneTracks.ts@@ -21,10 +21,9 @@* lane — the store's `nextFreeStart` is that one primitive.* - Cut: the store's `splitAtPlayhead` slices whichever kind is selected.*- * The base video track and the upper video tracks keep their richer- * verticality (lifting between tracks, insert zones, the base row) by passing- * a `vertical` strategy to the move gesture; everything else about them is- * the shared behavior.+ * The video tracks keep their richer verticality (lifting between tracks,+ * insert zones, dropping onto track 0) by passing a `vertical` strategy to+ * the move gesture; everything else about them is the shared behavior.*/import type React from "react";@@ -215,7 +214,7 @@ const ADAPTERS: Record<LaneKind, LaneAdapter<LaneRaw>> = {cue: cueAdapter as unknown as LaneAdapter<LaneRaw>,};-/** Logical times an edge can snap to: the timeline start, the base track's+/** Logical times an edge can snap to: the timeline start, video track 0's* cut points and end, the playhead, and every other lane item's edges across* all track kinds — a title can align to a music hit and vice versa. */function snapTargets(s: S, kind: LaneKind, selfId: string): number[] {@@ -293,7 +292,7 @@ export interface LaneMoveUI<V = unknown> {/** Display rows currently in use; targetRow may go one past to open a new track. */laneCount: number;/** The grabbed item's current display row. */- baseRow: number;+ homeRow: number;/** Publish (or clear) the in-flight drag so the slot and rows track it. */onDrag(d: LaneDrag | null): void;/** Paint (or clear) the snap guide at this stage-x pixel. */@@ -352,7 +351,7 @@ export function startLaneMove<V = unknown>(const refDrag = asset ? startPointerRefDrag(refFromAsset(asset)) : null;let live = false;- let targetRow = ui.baseRow;+ let targetRow = ui.homeRow;let slotStart = start0;let ds = start0;let awayTarget: V | null = null;@@ -368,8 +367,8 @@ export function startLaneMove<V = unknown>(ds = Math.max(0, start0 + dx / ui.pps);// Carried off its own lane set (an upper video layer headed to another- // track, the base row, or an insert gap): neighbors flow back and the- // placement system previews the target instead.+ // track, down to track 0, or an insert gap): neighbors flow back and+ // the placement system previews the target instead.if (ui.vertical) {const target = ui.vertical.resolve(ev);if (!ui.vertical.isHome(target)) {@@ -380,7 +379,7 @@ export function startLaneMove<V = unknown>(ui.onDrag({kind,id,- targetRow: ui.baseRow,+ targetRow: ui.homeRow,ghostX: ds * ui.pps,slotStart: ds,len,@@ -394,8 +393,8 @@ export function startLaneMove<V = unknown>(// Vertical drag retracks the item; one row past the end opens a new one.targetRow = ad.multiLane- ? Math.min(ui.laneCount, Math.max(0, ui.baseRow + Math.round(dy / ui.rowH)))- : ui.baseRow;+ ? Math.min(ui.laneCount, Math.max(0, ui.homeRow + Math.round(dy / ui.rowH)))+ : ui.homeRow;// A brand-new row has no neighbors to part.const lane = targetRow < usedLanes.length ? usedLanes[targetRow] : Infinity;diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 7b496ac3..ce962483 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -32,19 +32,18 @@ const uid = () => crypto.randomUUID().slice(0, 8);const MIN_LEN = 0.1;-/** Where a video clip lands when dropped: an existing track, the magnetic base- * row, or a brand-new track inserted at z-level `level`. Track numbers are- * signed: positive tracks sit above the base (higher = closer to the top),- * negative tracks sit below it (more negative = further behind), base is 0.- * Inserting shifts the tracks past `level` (up for positive, down for negative)- * to open the slot. */+/** 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. */export type VideoTrackPlacement =| { kind: "track"; track: number }- | { kind: "base" }| { kind: "insert"; level: number };-/** Open a slot at `level`, moving other clips out of the way: above the base- * (level > 0) shifts tracks at/above it up; below the base (level < 0) shifts+/** 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[] {return level > 0@@ -86,7 +85,7 @@ export interface EditorState {assets: MediaAsset[];clips: VideoClip[];audioClips: AudioClip[];- /** Upper video tracks composited over the base track. */+ /** 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. */@@ -131,7 +130,7 @@ export interface EditorState {updateAsset: (id: string, patch: Partial<MediaAsset>) => void;/** Remove a project asset and any clips/audio that reference it. */removeAsset: (id: string) => void;- /** Add a video clip from an asset onto the base track — at `start` (sliding+ /** Add a video clip from an asset onto video track 0 — at `start` (sliding* to the track's next free slot), or appended at the end when omitted. */addClipFromAsset: (assetId: string, start?: number) => void;/** Add a soundtrack clip from an audio asset at `start` (default: the@@ -163,16 +162,16 @@ export interface EditorState {/** Keep the clips array sorted by start (consumers read `clips[0]` as the* timeline's first clip). Called after a lane-coordinator move commits. */sortClips: () => void;- /** Reorder the base track by index and re-pack it (the AI reorder op). */+ /** Reorder video track 0 by index and re-pack it (the AI reorder op). */moveClip: (id: string, toIndex: number) => void;- /** Add a video asset to the timeline at a placement: an upper track, the base- * row, or a freshly inserted track. Used by media / library drops. */+ /** 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 (base or upper) to a placement, preserving its+ /** 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- * on the base row lands free-positioned at the drop time. Owns its own history. */+ * onto track 0 lands free-positioned at the drop time. Owns its own history. */dropVideoClip: (- source: { kind: "base" | "overlay"; id: string },+ source: { kind: "clip" | "overlay"; id: string },place: VideoTrackPlacement,start: number) => void;@@ -426,7 +425,7 @@ export const useEditor = create<EditorState>((set, get) => {...a,url: mediaUrl(id, a.fileName),}));- // Older docs stored the base track packed (array order implied the+ // 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");set({@@ -546,8 +545,8 @@ 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 the base track; with a target time,- // slide to the track's next free slot there.+ // 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 = get().clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));const clip: VideoClip = {@@ -808,7 +807,7 @@ export const useEditor = create<EditorState>((set, get) => {if (!asset || (asset.type !== "video" && asset.type !== "image")) return;const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;push();- if (place.kind === "base") {+ if (place.kind === "track" && place.track === 0) {const taken = get().clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));const v: VideoClip = {id: uid(),@@ -824,7 +823,7 @@ export const useEditor = create<EditorState>((set, get) => {}));return;}- // Full-frame by default: covers the base ("topmost plays"); the inspector+ // 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 = {@@ -845,7 +844,7 @@ export const useEditor = create<EditorState>((set, get) => {dropVideoClip: (source, place, start) => {const s = get();const src =- source.kind === "base"+ source.kind === "clip"? s.clips.find((c) => c.id === source.id): s.overlayClips.find((c) => c.id === source.id);if (!src) return;@@ -862,8 +861,8 @@ export const useEditor = create<EditorState>((set, get) => {speed: src.speed,};- if (place.kind === "base") {- if (source.kind === "base") return; // a same-track move commits through the lane coordinator+ if (place.kind === "track" && place.track === 0) {+ if (source.kind === "clip") return; // a same-track move commits through the lane coordinatorconst taken = s.clips.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));const clip: VideoClip = {id: uid(),@@ -962,7 +961,7 @@ export const useEditor = create<EditorState>((set, get) => {}}- // An overlay clip selected: slice it in place, like the base track.+ // 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) {@@ -1158,9 +1157,9 @@ export const useEditor = create<EditorState>((set, get) => {if (!sp) continue;const mi = mediaFor(sp.clip.assetId);if (mi == null) continue;- // Base-track clips re-materialize onto the base track (onBase), so a- // template stands up its own video instead of an empty base.- 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, onBase: true });+ // 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;@@ -1191,13 +1190,13 @@ export const useEditor = create<EditorState>((set, get) => {insertTemplate: (template, assetIds, offset) => {push();const usable = template.layers.filter((l) => assetIds[l.media]);- const baseLayers = usable.filter((l) => l.onBase);- const overlayLayers = usable.filter((l) => !l.onBase);- // Base clips append (magnetic) at the end of the current base track; the+ const clipLayers = usable.filter((l) => l.asClip);+ const overlayLayers = usable.filter((l) => !l.asClip);+ // 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 base clips drops in at the playhead.- const shift = baseLayers.length ? totalDuration(get().clips) : Math.max(0, offset);- const newClips: VideoClip[] = [...baseLayers]+ // that segment. A template with no clip layers drops in at the playhead.+ const shift = clipLayers.length ? totalDuration(get().clips) : Math.max(0, offset);+ const newClips: VideoClip[] = [...clipLayers].sort((a, b) => a.start - b.start).map((l) => ({start: l.start + shift,@@ -1210,11 +1209,11 @@ export const useEditor = create<EditorState>((set, get) => {...(l.fit ? { fit: l.fit } : {}),...(l.speed ? { speed: l.speed } : {}),}));- const baseTrack = Math.max(0, ...get().overlayClips.map((c) => c.track));+ const topTrack = Math.max(0, ...get().overlayClips.map((c) => c.track));const newOverlays: OverlayClip[] = overlayLayers.map((l) => ({id: uid(),assetId: assetIds[l.media],- track: baseTrack + l.track,+ track: topTrack + l.track,start: l.start + shift,in: l.in,out: l.out,@@ -2076,7 +2075,7 @@ export function getClipSpans(return spans;}-/** End of the base track: where its last clip runs out (clips are free-placed,+/** End of video track 0: where its last clip runs out (clips are free-placed,* so gaps count toward this, they just play black). */export function totalDuration(clips: VideoClip[]) {let end = 0;@@ -2084,7 +2083,7 @@ export function totalDuration(clips: VideoClip[]) {return end;}-/** A base clip as older docs stored it: packed by array order, no `start`. */+/** A track-0 clip as older docs stored it: packed by array order, no `start`. */type LegacyClip = Omit<VideoClip, "start"> & { start?: number };/** Assign packed sequential starts (each clip after the previous, dissolves@@ -2102,7 +2101,7 @@ function packStarts(clips: LegacyClip[]): VideoClip[] {return out;}-/** The base track as a gapless sequence for the sequential render graphs+/** Video track 0 as a gapless sequence for the sequential render graphs* (export, transcription): each span in start order, with the length of the* black/silent spacer that precedes it wherever the free-placed clips leave* the track empty. Sub-50ms gaps are treated as abutting. */@@ -2117,10 +2116,10 @@ export function spanSequence(spans: ClipSpan[]): { gapBefore: number; span: Clipreturn out;}-/** The playable length of the whole project: the base track plus anything that- * runs past it on an upper/lower video track or the soundtrack. Drives the- * timeline extent, the seek clamp, and export length so content beyond the base- * is reachable. */+/** The playable length of the whole project: video track 0 plus anything that+ * runs past it on another video track or the soundtrack. Drives the timeline+ * extent, the seek clamp, and export length so content past track 0's end is+ * reachable. */export function projectDuration(s: {clips: VideoClip[];overlayClips: OverlayClip[];diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex fbb5cd87..378b303b 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -98,9 +98,9 @@ export function regionLabel(r: FrameRect): string {return "PiP";}-/** A clip on the base video track — free-positioned in time like every other- * track. The array is kept sorted by `start` (older docs stored a packed- * sequence; loading bakes their implied starts in). */+/** A clip on video track 0 — free-positioned in time like every other track.+ * The array is kept sorted by `start` (older docs stored a packed sequence;+ * loading bakes their implied starts in). */export interface VideoClip {id: string;assetId: string;@@ -113,8 +113,8 @@ export interface VideoClip {/** How the clip meets its region: letterboxed ("fit", default) or scaled to* cover it ("fill", cropping the overflow). */fit?: "fit" | "fill";- /** The region of the frame this clip occupies; absent = full frame. Lets the- * base video share the frame with an overlay (e.g. sit in the top half). */+ /** 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). */frame?: FrameRect;/** Crop-window pan in fill mode, -1..1 per axis (0 = centered): which part* of the oversized video stays visible. */@@ -135,16 +135,17 @@ export interface VideoClip {}/**- * A clip on an upper video track — free-positioned in time (like the- * soundtrack) and composited over the base track. `track` 1 sits just above the- * base; higher tracks sit closer to the top and win where they overlap. A- * full-frame overlay covers the base ("topmost showing clip plays"); a regioned- * one shares the frame (split-screen half) or floats small (picture-in-picture).+ * 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; // 1-based; higher = closer to the top+ track: number; // signed, non-zero; higher = closer to the topstart: number; // timeline position, secondsin: number;out: number;@@ -257,9 +258,9 @@ export interface TemplateLayer {muted: boolean;speed?: number;track: number;- /** Came from the base (magnetic) track — re-materializes onto it, not an- * overlay track, so a template stands up its own base video. */- onBase?: boolean;+ /** Came from video track 0 — re-materializes as a timeline clip, not an+ * overlay, so a template stands up its own footage. */+ asClip?: boolean;}export interface TemplateAudio {media: number;@@ -442,7 +443,7 @@ export interface ProjectDoc {assets: StoredAsset[];clips: VideoClip[];audioClips: AudioClip[];- /** Upper video tracks composited over the base track (absent in older docs). */+ /** Video tracks other than track 0 (`clips`); absent in older docs. */overlayClips?: OverlayClip[];overlays: TextOverlay[];/** Output frame; absent in older projects (which are all 9:16). */diff --git a/site/src/cut/lib/visualFrames.ts b/site/src/cut/lib/visualFrames.tsindex 1d5c06ca..62ab38d4 100644--- a/site/src/cut/lib/visualFrames.ts+++ b/site/src/cut/lib/visualFrames.ts@@ -3,7 +3,7 @@import type { ClipSpan } from "./types";// Sample the cut's picture for the visual-subtitles pipeline: a handful of-// small jpeg frames spread along the base track, each stamped with its+// small jpeg frames spread along video track 0, each stamped with its// timeline time. Captured in the browser from the same media elements the// preview uses, so nothing re-renders server-side.@@ -47,7 +47,7 @@ function seekTo(v: HTMLVideoElement, t: number): Promise<void> {});}-/** Capture timeline frames from the base track's visible clips. */+/** Capture timeline frames from video track 0's visible clips. */export async function captureTimelineFrames(spans: ClipSpan[]): Promise<CapturedFrame[]> {const visible = spans.filter((sp) => !sp.clip.hidden);if (visible.length === 0) return [];diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 5671fc1e..dafd5467 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -70,13 +70,13 @@ export const AI_TOOLS: AiToolDef[] = [{name: "move_clip",description:- "Reorder a base-track video clip to a new index and re-pack the track end-to-end — this closes every gap. To move one clip in time (keeping gaps), use place_clip.",+ "Reorder a track-0 video clip to a new index and re-pack the track end-to-end — this closes every gap. To move one clip in time (keeping gaps), use place_clip.",inputSchema: obj({ clipId: str("Video clip id"), toIndex: num("Target index, 0-based") }, ["clipId", "toIndex"]),},{name: "place_clip",description:- "Move a base-track video clip to a timeline start time (seconds). The base track is free-positioned: gaps are allowed and play black. If another clip occupies that spot, the clip slides right to the next free one.",+ "Move a track-0 video clip to a timeline start time (seconds). The track is free-positioned: gaps are allowed and play black. If another clip occupies that spot, the clip slides right to the next free one.",inputSchema: obj({ clipId: str("Video clip id"), start: num("Target timeline start s") }, ["clipId", "start"]),},{@@ -108,11 +108,11 @@ export const AI_TOOLS: AiToolDef[] = [{name: "add_overlay_video",description:- "Put a project video or image asset on an overlay video track, composited with the base: track 1+ sits above it (the topmost full-frame clip covers everything below), negative tracks sit behind it. Pick a layout to share the frame — halves for a split screen, pip for picture-in-picture. Asset ids come from `media` in the editor state.",+ "Put a project video or image asset on an overlay video track, composited with track 0: track 1+ sits above it (the topmost full-frame clip covers everything below), negative tracks sit behind it. Pick a layout to share the frame — halves for a split screen, pip for picture-in-picture. Asset ids come from `media` in the editor state.",inputSchema: obj({asset_id: str("Project asset id (video or image)"),start: num("Timeline start s (default: the playhead)"),- track: num("Video track, non-zero; 1 = first layer above the base, -1 = behind it (default 1)"),+ track: num("Video track, non-zero; 1 = first layer above track 0, -1 = behind it (default 1)"),layout: {type: "string",enum: ["full", "top", "bottom", "left", "right", "pip"],@@ -129,7 +129,7 @@ export const AI_TOOLS: AiToolDef[] = [start: num("Timeline start s"),in: num("Source in s"),out: num("Source out s"),- track: num("Video track, non-zero; positive above the base, negative behind"),+ track: num("Video track, non-zero; positive above track 0, negative behind"),muted: bool("Mute the clip's own audio"),hidden: bool("Hide the layer without deleting it"),layout: {@@ -280,7 +280,7 @@ export const AI_TOOLS: AiToolDef[] = ["Import a stock video or image (by stock_search id) into the project and, by default, drop it on the video track. Free — the media ships with Cut.",inputSchema: obj({id: str("Stock item id from stock_search"),- add_to_timeline: bool("Place it on the base video track (default true)"),+ add_to_timeline: bool("Place it on video track 0 (default true)"),start: num("Timeline start s (default: appended at the end)"),}, ["id"]),},@@ -480,19 +480,19 @@ Cut is a local, project-based short-video editor. Each project has an output asp- Media shows only what the user imported. Everything Cut makes carries an origin tag (generated, voiceover, recording, stock, freeze — see \`media\` in editor_state) and lives where it was created, e.g. generated clips in the Video panel's job list; a "…" menu on each files it into Media or the Library.- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.- Right: the Inspector — its content follows the selection (video clip, overlay video, soundtrack clip, title, or cue).-- Bottom: the timeline (resizable by dragging its top border). Rows top-to-bottom: overlay video tracks above the base, the base video track, overlay tracks behind it, soundtrack lanes (green), titles (purple), subtitle tracks (amber, when enabled). Every track is free-positioned in time.+- Bottom: the timeline (resizable by dragging its top border). Rows top-to-bottom: the video tracks in z-order (positive tracks, then track 0, then negative tracks behind it), soundtrack lanes (green), titles (purple), subtitle tracks (amber, when enabled). Every track is free-positioned in time.Everything autosaves to the project folder. Undo/redo is unlimited (⌘Z / ⇧⌘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-- Every track is free-positioned: items carry a start time, gaps are allowed, and a base-track gap plays black (and silence). Deleting leaves a gap. videoTrack entries in editor_state report gapBefore where one exists.-- Two ways to move a base clip: place_clip sets its start (respects gaps, slides right if the spot is taken); move_clip reorders by index and re-packs the whole track end-to-end — the right call for "put this first" or "tighten the cut", wrong when the user laid out deliberate gaps. Index-based inserts (freeze_frame, generated clips) also re-pack.-- Overlay video: a video/image asset can sit on a track above the base (track 1, 2… — topmost wins) or behind it (track -1…). A full-frame overlay covers the base; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above/below the base track; they drag the region in the preview.+- Every track is free-positioned: items carry a start time, gaps are allowed, and a track-0 gap plays black (and silence). Deleting leaves a gap. videoTrack entries in editor_state report gapBefore where one exists.+- Two ways to move a track-0 clip: place_clip sets its start (respects gaps, slides right if the spot is taken); move_clip reorders by index and re-packs the whole track end-to-end — the right call for "put this first" or "tighten the cut", wrong when the user laid out deliberate gaps. Index-based inserts (freeze_frame, generated clips) also re-pack.+- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins) or behind it (track -1…). A full-frame overlay covers everything below it; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above/below track 0; they drag the region in the preview.- A clip's timeline length is (out-in)/speed; total duration runs to the last clip's end, gaps included, minus cross-style transition 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 joins a clip into the next one (0–2s, six styles) — read the transitions-and-fades skill before styling cuts. Splitting or deleting clears the affected transition.-- split_at cuts the base clip under that time into two clips at the exact frame. With a soundtrack or overlay clip selected it splits that instead.+- split_at cuts the track-0 clip under that time into two clips at the exact frame. With a soundtrack or overlay clip selected it splits that instead.- The user can multi-select (⌘/⇧-click) and delete several items at once; a hover chip on each video clip toggles its own audio.- 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.@@ -537,7 +537,7 @@ Caption look: the Subtitles panel offers 10 visual presets (clean, hook, punchy,Two ways to get footage the user doesn't have: bundled stock (local, free) and hosted generation (signed in, spends credits). Prefer stock when it genuinely fits; generate when the shot needs to be specific.Stock: stock_search browses the bundled catalogs — footage clips and images in 8 categories plus ~20 UGC talking characters — matching prompts, categories, and tags. stock_add imports an item into the project (origin "stock") and drops it on the timeline. In the UI these live in the Video and Image tabs beside the generators; clicking a stock tile seeds the generate panel with its prompt.Generation:-- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The image rides the base track as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.+- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The image rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.- generate_video(prompt, tier?, duration_seconds?, aspect?, resolution?, reference_asset_id?, add_to_timeline?, index?): a hosted Veo model renders a 4–8s clip with audio. tier "fast" (default) is quicker/cheaper, "high" is best quality. This takes a minute or two, so the tool returns right away and the clip appears in the Video panel's renders (and on the timeline by default) when it finishes — tell the user it's rendering. Don't call it again for the same shot while one is in flight.- generate_character_video(character_id, line, …): a stock talking character delivers a line to camera, same async render as generate_video. Characters come from stock_search kind:"character" — each has a persona; you write the line (chat deliverable rules apply: asked for "a script", write it in chat first).References: users attach images/clips to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. A model recomposes the prompt around them: for video at most one image survives as the literal opening frame; for images any number can be drawn from. When the user says "use this clip/image", pass the reference — don't just describe it in the prompt.diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 56fba251..0819a626 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -51,7 +51,7 @@ export interface ExportSpec {/** A still image: looped for the clip's length instead of trimmed. */image?: boolean;}[];- /** Upper video tracks composited over the base, bottom track first. */+ /** Video tracks composited around the track-0 `clips`, bottom track first. */overlayVideos?: {file: string;in: number;@@ -352,13 +352,13 @@ async function runExport(job: Job, spec: ExportSpec) {const { width: W, height: H, fps } = spec;const overlayVideos = spec.overlayVideos ?? [];- // Tracks below the base (negative) form a backdrop it draws over; tracks above- // (positive) sit on top. A below track means the base must carry alpha where+ // Negative tracks form a backdrop track 0 draws over; positive tracks sit+ // on top. A below track means the track-0 picture must carry alpha where// it's regioned so the backdrop shows through its margins.const belowVideos = overlayVideos.filter((o) => o.track < 0).sort((a, b) => a.track - b.track);const aboveVideos = overlayVideos.filter((o) => o.track > 0).sort((a, b) => a.track - b.track);const hasBelow = belowVideos.length > 0;- const baseFmt = hasBelow ? "yuva420p" : "yuv420p";+ const clipFmt = hasBelow ? "yuva420p" : "yuv420p";const padColor = hasBelow ? "[email protected]" : "black";// One ffmpeg input per distinct media file (from the project folder),// plus one per uploaded overlay PNG.@@ -490,8 +490,8 @@ async function runExport(job: Job, spec: ExportSpec) {const region = regionPx(c.frame, W, H);let frame: string;if (region) {- // A regioned base clip (split-screen half) scales into its rect, then- // pads out to the full frame with black around it.+ // A regioned track-0 clip (split-screen half) scales into its rect,+ // then pads out to the full frame with black around it.const { rx, ry, rw, rh } = region;frame =c.fit === "fill"@@ -511,7 +511,7 @@ async function runExport(job: Job, spec: ExportSpec) {}// setpts/speed rescales the clip's duration on the timeline (footage);// a still just replays its looped input.- const core = `${timebase},fps=${fps},${frame},setsar=1,format=${baseFmt}`;+ const core = `${timebase},fps=${fps},${frame},setsar=1,format=${clipFmt}`;const fades =(hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}` : "") +(tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");@@ -531,7 +531,7 @@ async function runExport(job: Job, spec: ExportSpec) {: `${num(TRANSITION_ZOOM)}-${k}*in/${frames}`;return (`zoompan=z=${z}:x=iw/2-(iw/zoom/2):y=ih/2-(ih/zoom/2)` +- `:d=1:s=${W}x${H}:fps=${fps},setsar=1,format=${baseFmt}`+ `:d=1:s=${W}x${H}:fps=${fps},setsar=1,format=${clipFmt}`);};const slices: { from: number; to: number; fx?: string }[] = [];@@ -564,7 +564,7 @@ async function runExport(job: Job, spec: ExportSpec) {// track shows) when one exists, otherwise plain black.const slot = hasBelow ? "[email protected]" : "black";filters.push(- `color=c=${slot}:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=${baseFmt}[v${j}]`+ `color=c=${slot}:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=${clipFmt}[v${j}]`);}if (!c.muted && !c.hidden && audioPresence.get(c.file)) {@@ -613,14 +613,15 @@ async function runExport(job: Job, spec: ExportSpec) {aAcc = aOut;}- // Composite the video stack bottom→top: below-base tracks form a backdrop the- // base draws over (a regioned base leaves them showing), then the above-base- // tracks sit on top. A full-frame layer covers; a regioned one shares the frame- // (split half) or floats (PiP). Overlay audio (unless muted) mixes in below.+ // Composite the video stack bottom→top: negative tracks form a backdrop+ // track 0 draws over (a regioned clip leaves them showing), then the+ // positive tracks sit on top. A full-frame layer covers; a regioned one+ // shares the frame (split half) or floats (PiP). Overlay audio (unless+ // muted) mixes in below.const overlaySoundLabels: string[] = [];let ovk = 0;- // Overlay one track clip onto `onto`, returning the new label; also queues its- // audio. Reused for the below backdrop and the above-base stack.+ // Overlay one track clip onto `onto`, returning the new label; also queues+ // its audio. Reused for the backdrop and the positive-track stack.const addOverlay = (oc: (typeof overlayVideos)[number], onto: string): string => {if (!oc.image && !videoPresence.get(oc.file)) return onto;const idx = oc.image ? imageOverlayInput.get(oc)! : inputIndex.get(oc.file)!;@@ -672,16 +673,17 @@ async function runExport(job: Job, spec: ExportSpec) {let vLabel = vAcc;if (hasBelow) {- // Backdrop = black + the below-base tracks; the alpha-carrying base draws- // over it (regioned margins reveal the backdrop), then flatten for encoding.+ // Backdrop = black + the negative tracks; the alpha-carrying track-0+ // picture draws over it (regioned margins reveal the backdrop), then+ // flatten for encoding.filters.push(`color=c=black:s=${W}x${H}:r=${fps},trim=0:${num(spec.duration)},setpts=PTS-STARTPTS,format=yuva420p[below0]`);let belowLabel = "below0";for (const oc of belowVideos) belowLabel = addOverlay(oc, belowLabel);- filters.push(`[${belowLabel}][${vAcc}]overlay=0:0[basecomp]`);- filters.push(`[basecomp]format=yuv420p[baseflat]`);- vLabel = "baseflat";+ filters.push(`[${belowLabel}][${vAcc}]overlay=0:0[t0comp]`);+ filters.push(`[t0comp]format=yuv420p[t0flat]`);+ vLabel = "t0flat";}for (const oc of aboveVideos) vLabel = addOverlay(oc, vLabel);diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex b4508345..699a2da5 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -64,7 +64,7 @@ export interface TemplateLayer {muted: boolean;speed?: number;track: number;- onBase?: boolean; // re-materializes onto the base track rather than an overlay+ asClip?: boolean; // re-materializes as a track-0 timeline clip rather than an overlay}export interface TemplateAudio {media: number;