Open source CapCut alternative.
TypeScript
feat(cut): number video tracks 0..N bottom-up, below-drop inserts a new track 0 [rebuild]
David Lea426348f63f1
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 5b4e9004..e8ab3f63 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -251,14 +251,15 @@ export function Timeline() {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.+ // Past the ends of the stack → above opens a new top track; below the+ // bottom row opens a new track 0 (the spine transplants onto the drop).const rows = innerRef.current?.querySelectorAll<HTMLElement>("[data-drop]");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 };if (clientY > rows[rows.length - 1].getBoundingClientRect().bottom)- return { kind: "insert", level: Math.min(0, ...tracks) - 1 };+ return { kind: "insert", level: 0 };}return TRACK_ZERO;}, []);@@ -304,20 +305,17 @@ export function Timeline() {return { used, rowOf, count: used.length };}, [overlays]);- // 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.+ // Video tracks above track 0 (PiP / composited layers), listed highest-first+ // so the top row is the frontmost layer and track 0 sits at the bottom of+ // the stack; empty tracks vanish.const aboveTracks = useMemo(() => [...new Set(overlayClips.map((c) => c.track).filter((n) => n > 0))].sort((a, b) => b - a),[overlayClips]);- const belowTracks = useMemo(- () => [...new Set(overlayClips.map((c) => c.track).filter((n) => n < 0))].sort((a, b) => b - a),- [overlayClips]- );- // The z-levels a drop past the stack's edges would open a new track at.+ // The z-levels a drop past the stack's edges would open a new track at: a+ // new top layer above, or a new track 0 below (the spine transplants there).const topInsertLevel = (aboveTracks[0] ?? 0) + 1;- const bottomInsertLevel = (belowTracks[belowTracks.length - 1] ?? 0) - 1;+ const bottomInsertLevel = 0;// Audio tracks mirror the title tracks: clips carry a `lane`; used lanes// compact to contiguous display rows, so empty tracks disappear on their own.@@ -1065,51 +1063,10 @@ export function Timeline() {</div>)}- {belowTracks.map((track) => (- <div- key={`ov-${track}`}- className="relative mt-1.5"- style={{ height: OVERLAY_H }}- data-drop={placementAttr({ kind: "track", track })}- onPointerDown={deselectIfSelf}- {...overlayDropHandlers({ kind: "track", track })}- >- {laneRail(OVERLAY_H - 2)}- {videoDragActive && trackGuide({ kind: "track", track })}- {draggedOverlayTrack === track && laneDrag && (- <LaneSlot- drag={laneDrag}- pps={pps}- rowH={OVERLAY_H}- barH={OVERLAY_H - 4}- className="rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]"- />- )}- {overlayClips- .filter((c) => c.track === track)- .map((c) => (- <OverlayClipView- key={c.id}- clip={c}- asset={assets.find((x) => x.id === c.assetId)}- pps={pps}- 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}- onSnap={setSnapX}- resolveTarget={resolveDropTrack}- onCrossMove={previewCross}- onCrossDrop={onOverlayCrossDrop}- onDragActive={setVideoDragging}- />- ))}- {trackSlot({ kind: "track", track }, OVERLAY_H - 4)}- </div>- ))}-{/* The bottom-side new track grows the stack downward, like the- audio and title lanes' extra row — nothing above it moves. */}+ audio and title lanes' extra row — nothing above it moves.+ Dropping here opens a new track 0: the whole stack renumbers up+ and the spine (ripple, transitions) transplants onto the drop. */}{videoDragActive && newTrackRow(bottomInsertLevel)}{(audioClips.length > 0 || audioDrop !== null) && (diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex c41ee625..535fc82d 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -310,7 +310,7 @@ class Engine {return;}// A hidden clip plays nothing: fill black only if we own the clear,- // otherwise leave whatever is beneath (a below track) showing.+ // otherwise leave the frame as drawn so far.if (clip?.hidden) {if (clear) {ctx.fillStyle = "#000";@@ -430,8 +430,8 @@ class Engine {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 negative tracks, so- // track 0 composites over them (a regioned clip leaves them showing).+ // No clear here — the tick clears once before compositing, so a regioned+ // clip draws into its rect over the already-black frame.this.drawLayer(masterEl, masterSpan.clip, false, 1, masterZoom);if (incEl) this.drawLayer(incEl, next!.clip, false, alpha, incZoom);// Veil only the master clip's own footprint, like the export's per-clip@@ -485,15 +485,12 @@ class Engine {this.fillBlackVeil(1 - gain);}- /** 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") {+ /** Overlay clips live at time `t` — every track above 0, with their assets,+ * in z-order (further-back first). */+ private liveOverlays(t: number) {const s = useEditor.getState();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);+ const clips = overlayLayers(s.clips).sort((a, b) => a.track - b.track);for (const c of clips) {if (c.hidden) continue;const asset = s.assets.find((a) => a.id === c.assetId);@@ -533,29 +530,28 @@ class Engine {return el;}- /** Live overlays for one side, each already primed toward `t`. Computed once- * so the skim path's readiness check and the draw step share the same+ /** The live overlays, each already primed toward `t`. Computed once so the+ * skim path's readiness check and the draw step share the same* filter/sort/seek instead of repeating it per frame. */- private prepareSide(t: number, play: boolean, side: "below" | "above") {- return this.liveOverlays(t, side).map(({ clip, asset }) => ({+ private prepareOverlays(t: number, play: boolean) {+ return this.liveOverlays(t).map(({ clip, asset }) => ({clip,el: this.prepareOverlay(clip, asset, t, play),}));}- /** 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`.- * Pass `prepared` (from `prepareSide`) to reuse an already-primed side. */+ /** Draw the overlay tracks over 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`. Pass `prepared` (from `prepareOverlays`) to reuse an+ * already-primed set. */private drawOverlays(t: number,play: boolean,- side: "below" | "above",active: Set<string>,prepared?: { clip: VideoClip; el: MediaEl }[]) {- for (const { clip, el } of prepared ?? this.prepareSide(t, play, side)) {+ for (const { clip, el } of prepared ?? this.prepareOverlays(t, play)) {active.add(clip.id);if (!elReady(el)) continue;const rect = rectOf(clip);@@ -703,11 +699,10 @@ class Engine {// wedging the preview on it.if (!elErrored(el) && !elReady(el)) ready = false;}- // Prime each side once; the readiness scan and the draw step below reuse- // these instead of re-filtering/seeking the overlays a second time.- const belowLive = this.prepareSide(pt, false, "below");- const aboveLive = this.prepareSide(pt, false, "above");- for (const { el } of [...belowLive, ...aboveLive]) {+ // Prime the overlays once; the readiness scan and the draw step below+ // reuse these instead of re-filtering/seeking them a second time.+ const overlaysLive = this.prepareOverlays(pt, false);+ for (const { el } of overlaysLive) {if (!elErrored(el) && !elReady(el)) ready = false;}if (!ready) {@@ -717,12 +712,11 @@ class Engine {}const active = new Set<string>();this.clearCanvas();- this.drawOverlays(pt, false, "below", active, belowLive);- // Where track 0 has nothing live there is no master frame — just the- // backdrop and the other tracks still running at `pt`.+ // Where track 0 has nothing live there is no master frame — just black+ // 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);+ this.drawOverlays(pt, false, active, overlaysLive);this.drawProjectFade(this.projectFadeGain(pt, total));this.cleanupOverlays(active);this.syncSoundtrack(t, false);@@ -746,11 +740,10 @@ class Engine {}}- // Draw the below tracks first (backdrop), then prime the master element- // (and any dissolve partner) over them and read the clock.+ // Clear to black, then prime the master element (and any dissolve+ // partner) over it and read the clock.const active = new Set<string>();this.clearCanvas();- this.drawOverlays(t, true, "below", active);if (span) {let el = this.composite(span, spans, t, true);@@ -804,7 +797,7 @@ class Engine {// Track 0 and every other track finished.useEditor.setState({ playing: false, currentTime: total });pauseEl(el);- this.drawOverlays(t, true, "above", active);+ this.drawOverlays(t, true, active);this.drawProjectFade(this.projectFadeGain(total, total));this.cleanupOverlays(active);this.syncSoundtrack(total, false);@@ -822,7 +815,7 @@ class Engine {t = t + dt;if (t >= total - 0.001) {useEditor.setState({ playing: false, currentTime: total });- this.drawOverlays(t, true, "above", active);+ this.drawOverlays(t, true, active);this.drawProjectFade(this.projectFadeGain(total, total));this.cleanupOverlays(active);this.syncSoundtrack(total, false);@@ -830,7 +823,7 @@ class Engine {}}- this.drawOverlays(t, true, "above", active);+ this.drawOverlays(t, true, active);// The whole-video fade veils the finished frame and dims the sound —// the master's element volume (set by composite) and the soundtrack.const fadeGain = this.projectFadeGain(t, total);diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex b89cf8df..94ee2018 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -182,8 +182,8 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu? { panX: r(sp.clip.panX ?? 0), panY: r(sp.clip.panY ?? 0) }: {}),})),- // Video layers composited with track 0: track > 0 above it (topmost- // full-frame clip covers the rest), track < 0 behind it.+ // Video layers composited over track 0 in track order (the topmost+ // full-frame clip covers the rest).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) })),diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex a3de7f17..1bceaf24 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -341,8 +341,11 @@ export async function runAiTool(if (asset.type !== "video" && asset.type !== "image")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 holds the timeline clips — use place_clip for it.");+ // Tracks stack bottom-up from track 0; overlays live on 1+. A stale+ // negative (the old behind-track model) clamps to the first layer.+ const track = isNum(input.track) ? Math.max(1, Math.round(input.track)) : 1;+ if (isNum(input.track) && Math.round(input.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;@@ -376,8 +379,8 @@ export async function runAiTool(}if (isNum(input.track)) {const track = Math.round(input.track);- if (track === 0) throw new ToolError("Track 0 holds the timeline clips — overlays are non-zero.");- patch.track = track;+ if (track === 0) throw new ToolError("Track 0 holds the timeline clips — overlays are 1 or higher.");+ patch.track = Math.max(1, track);}if (typeof input.muted === "boolean") patch.muted = input.muted;if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 2bb409f3..e9dd1c03 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -245,7 +245,7 @@ async function buildExportForm(clipEntries[i],]);- // Video tracks composited around track 0; hidden ones are dropped.+ // Video tracks composited over track 0; hidden ones are dropped.const overlayVideos = overlayLayers(doc.clips).filter((c) => !c.hidden && assetById.has(c.assetId) && c.start < duration).map((c) => ({diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 1294275e..068f3373 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -35,10 +35,10 @@ const uid = () => crypto.randomUUID().slice(0, 8);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: positive tracks- * sit above track 0 (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. */+ * track inserted at z-level `level`. Tracks number 0..N bottom-up: track 0 is+ * the bottom row, higher tracks composite in front. Inserting shifts the+ * tracks at/above `level` up to open the slot — inserting at 0 opens a new+ * bottom row, which becomes the spine (ripple, transitions, playback master). */export type VideoTrackPlacement =| { kind: "track"; track: number }| { kind: "insert"; level: number };@@ -49,15 +49,13 @@ export const track0Clips = (clips: VideoClip[]) => clips.filter((c) => c.track =/** Every video clip not on 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). */+/** Open a slot at `level`, shifting the tracks at/above it up by one. `exclude`+ * is the clip being placed (left untouched). Level 0 shifts the whole stack up:+ * the placed clip becomes the new track 0 — the spine transplants to it. */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));+ return clips.map((c) =>+ c.id !== exclude && c.track >= level ? { ...c, track: c.track + 1 } : c+ );}const shiftTracksUp = (clips: VideoClip[], place: VideoTrackPlacement): VideoClip[] =>place.kind === "insert" ? openInsertSlot(clips, place.level) : clips;@@ -91,8 +89,8 @@ export interface EditorState {saveState: SaveState;assets: MediaAsset[];- /** Every video clip, on any track. Track 0 carries the transition sequence;- * other tracks composite around it (positive above, negative behind). A+ /** Every video clip, on any track. Tracks number 0..N bottom-up: track 0+ * carries the transition sequence, higher tracks composite in front. A* clip's `track` field is the only thing that places it. */clips: VideoClip[];audioClips: AudioClip[];@@ -645,7 +643,12 @@ export const useEditor = create<EditorState>((set, get) => {const legacyLayers = (doc.overlayClips ?? []).filter((c) => c.track !== 0 && !seen.has(c.id));- const merged = [...folded, ...legacyLayers];+ // Tracks number 0..N bottom-up. Docs saved when tracks could go+ // negative (backdrop rows below the spine) lift wholesale so the+ // lowest row becomes track 0 — the bottom row is the spine now.+ const joined = [...folded, ...legacyLayers];+ const lift = Math.max(0, ...joined.map((c) => -c.track));+ const merged = lift ? joined.map((c) => ({ ...c, track: c.track + lift })) : joined;set({projectName: doc.name,assets,@@ -1640,14 +1643,14 @@ export const useEditor = create<EditorState>((set, get) => {}));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- // track 0 at its original negative level — never onto track 0 itself,- // which would splice it into the transition sequence.+ // layer saved as 2). Layers stack on top of the project's current top —+ // never onto track 0 itself, which would splice them into the transition+ // sequence. Templates saved when tracks could go negative (backdrops)+ // clamp into the stack above too.const newLayers: VideoClip[] = overlayLayerDefs.map((l) => ({id: uid(),assetId: assetIds[l.media],- track: l.track > 0 ? topTrack + l.track : l.track - 1,+ track: topTrack + Math.max(1, l.track),start: l.start + shift,in: l.in,out: l.out,diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 8db46091..f80334d1 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -111,11 +111,11 @@ export function regionLabel(r: FrameRect): string {export interface VideoClip {id: string;assetId: string;- /** Which video track this clip sits on. Track 0's clips form the 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. */+ /** Which video track this clip sits on. Tracks number 0..N bottom-up:+ * track 0's clips form the sequence that carries transitions and drives+ * playback; higher tracks composite in front (highest wins where clips+ * overlap). Absent in older docs, which are all track 0; docs saved when+ * tracks could go negative lift on load so the lowest row becomes 0. */track: number;start: number; // timeline position, secondsin: number; // trim-in inside the source, secondsdiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex aca11068..3534a923 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -171,11 +171,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 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.",+ "Put a project video or image asset on an overlay video track, composited over track 0: tracks stack bottom-up, and the topmost full-frame clip covers everything below. 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 track 0, -1 = behind it (default 1)"),+ track: num("Video track, 1 or higher; 1 = first layer above track 0, higher = further in front (default 1)"),layout: {type: "string",enum: ["full", "top", "bottom", "left", "right", "pip"],@@ -192,7 +192,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 track 0, negative behind"),+ track: num("Video track, 1 or higher; higher = further in front"),muted: bool("Mute the clip's own audio"),hidden: bool("Hide the layer without deleting it"),layout: {@@ -698,7 +698,7 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim- Deleting a track-0 clip ripples: the span it occupied closes, later items on every track slide left together, items wholly inside the span go with it, and straddlers are trimmed. A gap that already existed stays. Deletes on other tracks remove just that item.- 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, opening a slot at the landing point — clips after it shift right, every other gap survives. Index-based inserts (freeze_frame, generated clips) open a slot the same way.- add_clip puts a project asset on the timeline the way a drag does: video/image onto track 0 (a \`start\`, an \`index\` insert, or appended at the end), audio onto the soundtrack.-- 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.+- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins). 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 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; it changes the clip's timeline length, and later titles/captions ripple to stay in sync.diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex fcd0ebc8..08a91100 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -52,7 +52,7 @@ export interface ExportSpec {/** A still image: looped for the clip's length instead of trimmed. */image?: boolean;}[];- /** Video tracks composited around the track-0 `clips`, bottom track first. */+ /** Video tracks composited over the track-0 `clips`, lowest track first. */overlayVideos?: {file: string;in: number;@@ -444,15 +444,11 @@ async function runExport(job: Job, spec: ExportSpec) {if (spec.clips.length === 0) throw new Error("Nothing to export.");const { width: W, height: H, fps } = spec;- const overlayVideos = spec.overlayVideos ?? [];- // 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 clipFmt = hasBelow ? "yuva420p" : "yuv420p";- const padColor = hasBelow ? "[email protected]" : "black";+ // Tracks number 0..N bottom-up: track 0 folds sequentially into the base+ // picture, the rest overlay it in track order (highest last = frontmost).+ const overlayVideos = [...(spec.overlayVideos ?? [])].sort((a, b) => a.track - b.track);+ const clipFmt = "yuv420p";+ const padColor = "black";// One ffmpeg input per distinct media file (from the project folder),// plus one per uploaded overlay PNG.// Still images are excluded here: a plain `-i file` decodes one frame, so@@ -656,11 +652,9 @@ async function runExport(job: Job, spec: ExportSpec) {filters.push(`${core}${fades}[v${j}]`);}} else {- // No video stream, or a hidden clip: keep the slot transparent (so a below- // track shows) when one exists, otherwise plain black.- const slot = hasBelow ? "[email protected]" : "black";+ // No video stream, or a hidden clip: the slot plays black.filters.push(- `color=c=${slot}:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=${clipFmt}[v${j}]`+ `color=c=black: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)) {@@ -709,15 +703,14 @@ async function runExport(job: Job, spec: ExportSpec) {aAcc = aOut;}- // 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+ // Composite the video stack bottom→top: the overlay tracks draw over the+ // track-0 base in track order. 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 backdrop and the positive-track stack.+ // its audio.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)!;@@ -769,20 +762,7 @@ async function runExport(job: Job, spec: ExportSpec) {};let vLabel = vAcc;- if (hasBelow) {- // 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[t0comp]`);- filters.push(`[t0comp]format=yuv420p[t0flat]`);- vLabel = "t0flat";- }- for (const oc of aboveVideos) vLabel = addOverlay(oc, vLabel);+ for (const oc of overlayVideos) vLabel = addOverlay(oc, vLabel);// Burn in text overlays, each windowed to its timeline range. Half-open so// back-to-back overlays sharing a boundary never composite on the same frame.