Skip to content

Open source CapCut alternative.

TypeScript

feat(site): below-base video tracks and a reachable timeline past the base

David Le5a9cb081ffc2
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index ea92b1f1..d98a9db5 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -8,7 +8,7 @@ import { apiFetch } from "@/cut/lib/api";
import { renderPreviewProxy } from "@/cut/lib/exportClient";
import { useExport } from "@/cut/lib/exportStore";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
-import { serializeDoc, totalDuration, useEditor } from "@/cut/lib/store";
+import { projectDuration, serializeDoc, useEditor } from "@/cut/lib/store";
import { AiPanel } from "./AiPanel";
import { ExportDialog } from "./ExportDialog";
import { ExportStatus } from "./ExportStatus";
@@ -245,7 +245,7 @@ export function Editor({ projectId }: { projectId: string }) {
if (e.code === "Space" && !controlFocused) {
e.preventDefault();
- if (!s.playing && s.currentTime >= totalDuration(s.clips) - 0.01) s.seek(0);
+ if (!s.playing && s.currentTime >= projectDuration(s) - 0.01) s.seek(0);
s.setPlaying(!s.playing);
} else if (e.key === "Backspace" || e.key === "Delete") {
e.preventDefault();
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index fb597738..6e5a3719 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -432,28 +432,6 @@ function OverlayClipPanel({ clip }: { clip: OverlayClip }) {
</div>
<Row label="Length"><Value>{formatTime(len)}</Value></Row>
<Row label="Starts at"><Value>{formatTime(clip.start)}</Value></Row>
- <Row label="Track">
- <div className="flex items-center gap-1.5">
- <Button
- variant="outline"
- size="icon-sm"
- aria-label="Move down a track"
- disabled={clip.track <= 1}
- onClick={() => update(clip.id, { track: Math.max(1, clip.track - 1) })}
- >
- −
- </Button>
- <Value className="w-6 text-center">{clip.track}</Value>
- <Button
- variant="outline"
- size="icon-sm"
- aria-label="Move up a track"
- onClick={() => update(clip.id, { track: clip.track + 1 })}
- >
- +
- </Button>
- </div>
- </Row>
<LayoutButtons
rect={rectOf(clip)}
onPick={(frame, fit) => update(clip.id, { frame, fit })}
@@ -482,10 +460,6 @@ function OverlayClipPanel({ clip }: { clip: OverlayClip }) {
<Row label="Hide from output">
<Switch checked={!!clip.hidden} onCheckedChange={(v) => update(clip.id, { hidden: v })} />
</Row>
- <p className="mt-2.5 text-[11.5px] leading-relaxed text-muted-foreground">
- A full-frame overlay covers the tracks below. Give it a half or corner
- to share the frame; drag the box in the preview to place it.
- </p>
</div>
</>
);
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 5fe32b91..c785e0ac 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -22,7 +22,7 @@ import {
import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";
import { startDrag } from "@/cut/lib/drag";
import { ensurePeaks } from "@/cut/lib/media";
-import { clipLen, clipSpeed, getClipSpans, TIMELINE_H_MAX, totalDuration, useEditor } from "@/cut/lib/store";
+import { clipLen, clipSpeed, getClipSpans, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { formatTime, formatTimecode } from "@/cut/lib/time";
import type { AudioClip, ClipSpan, MediaAsset, OverlayClip, SubtitleCue, TextOverlay } from "@/cut/lib/types";
@@ -139,7 +139,7 @@ export function Timeline() {
);
const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);
- const total = totalDuration(clips);
+ const total = projectDuration({ clips, overlayClips, audioClips });
// Fill the viewport at minimum so a wide window never leaves the ruler/tracks
// cut off; grow past it once the content is longer.
const contentW = Math.max(total * pps + PAD_END, viewportW - PAD_SIDE * 2, 600);
@@ -191,11 +191,14 @@ export function Timeline() {
const zone = el?.closest<HTMLElement>("[data-drop]");
const parsed = zone ? parsePlacement(zone.dataset.drop!) : null;
if (parsed) return parsed;
- // Above every row → a new top track.
- const first = innerRef.current?.querySelector<HTMLElement>("[data-drop]");
- if (first && clientY < first.getBoundingClientRect().top) {
- const top = Math.max(0, ...useEditor.getState().overlayClips.map((c) => c.track));
- return { kind: "insert", level: top + 1 };
+ // Past the ends of the stack → a new track beyond the last one.
+ const rows = innerRef.current?.querySelectorAll<HTMLElement>("[data-drop]");
+ const tracks = useEditor.getState().overlayClips.map((c) => c.track);
+ 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: "base" };
}, []);
@@ -238,10 +241,15 @@ export function Timeline() {
return { used, rowOf, count: used.length };
}, [overlays]);
- // Upper video tracks (PiP / composited layers) render above the base row,
- // highest track at the top. Empty tracks simply don't appear.
- const overlayTracks = useMemo(
- () => [...new Set(overlayClips.map((c) => c.track))].sort((a, b) => b - a),
+ // 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.
+ 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]
);
@@ -318,7 +326,7 @@ export function Timeline() {
const fit = useCallback(() => {
const el = scrollRef.current;
- const dur = totalDuration(useEditor.getState().clips);
+ const dur = projectDuration(useEditor.getState());
if (!el || dur <= 0) return;
zoomTo((el.clientWidth - 60) / dur, 0, PAD_SIDE);
}, [zoomTo]);
@@ -384,7 +392,7 @@ export function Timeline() {
s.seek(0);
} else if (e.key === "End") {
e.preventDefault();
- s.seek(totalDuration(s.clips));
+ s.seek(projectDuration(s));
}
};
window.addEventListener("keydown", onKey);
@@ -472,15 +480,18 @@ export function Timeline() {
});
};
- // A thin drop line in the gap above a track row: dropping here opens a brand
- // new track at z-level `level`. Straddles the gap so a drop near a row edge
- // inserts, while the row's middle still lands on that track.
- const insertZone = (level: number) => {
+ // A thin drop line in the gap above (or below) a track row: dropping here opens
+ // a brand new track at z-level `level`. Straddles the gap so a drop near a row
+ // edge inserts, while the row's middle still lands on that track.
+ const insertZone = (level: number, side: "top" | "bottom" = "top") => {
const active = samePlacement(overlayDrop?.target ?? null, { kind: "insert", level });
return (
<div
data-drop={`insert:${level}`}
- className="absolute inset-x-0 -top-[9px] z-20 flex h-[18px] items-center"
+ className={cn(
+ "absolute inset-x-0 z-20 flex h-[18px] items-center",
+ side === "top" ? "-top-[9px]" : "-bottom-[9px]"
+ )}
{...overlayDropHandlers({ kind: "insert", level })}
>
<div
@@ -616,7 +627,7 @@ export function Timeline() {
>
<Ruler pps={pps} width={contentW} onScrub={scrub} />
- {overlayTracks.map((track) => (
+ {aboveTracks.map((track) => (
<div
key={`ov-${track}`}
className="relative mt-1.5"
@@ -661,6 +672,7 @@ export function Timeline() {
onPointerDown={deselectIfSelf}
>
{insertMode && insertZone(1)}
+ {insertMode && insertZone(-1, "bottom")}
{spans.length === 0 && (
<div className="pointer-events-none sticky left-0 flex h-full w-[calc(100vw-40px)] max-w-[900px] items-center justify-center gap-1.5 rounded-xl border-[1.5px] border-dashed border-input text-xs font-medium text-muted-foreground">
<Plus className="size-3.5" /> Add media to this project
@@ -738,6 +750,44 @@ 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 })}
+ >
+ {insertMode && insertZone(track - 1, "bottom")}
+ {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(`overlayClip:${c.id}`)}
+ resolveTarget={resolveDropTrack}
+ onCrossMove={previewCross}
+ onCrossDrop={onOverlayCrossDrop}
+ onDragActive={setVideoDragging}
+ />
+ ))}
+ {samePlacement(overlayDrop?.target ?? null, { kind: "track", track }) && (
+ <div
+ className="pointer-events-none absolute top-0.5 rounded-lg border-[1.5px] border-dashed border-[#0a84ff]/70 bg-[#0a84ff]/10"
+ style={{
+ left: overlayDrop!.t * pps,
+ width: Math.max(10, overlayDrop!.len * pps - CLIP_GAP),
+ height: OVERLAY_H - 4,
+ }}
+ />
+ )}
+ </div>
+ ))}
+
{audioClips.length > 0 && (
<div className="relative mt-1.5" style={{ height: AUDIO_H }} onPointerDown={deselectIfSelf}>
{audioClips.map((a) => (
@@ -843,7 +893,7 @@ function HoverLine({
if (skimTime === null) return null;
return (
<div
- className="tl-hover-line pointer-events-none absolute top-0 bottom-2 z-6 w-px bg-foreground/30"
+ className="tl-hover-line pointer-events-none absolute top-0 bottom-2 z-30 w-px bg-foreground/30"
style={{ transform: `translateX(${skimTime * pps}px)` }}
/>
);
@@ -998,7 +1048,7 @@ function Playhead({
return (
<div
- className="pointer-events-none absolute top-0 bottom-2 left-0 z-8 w-[1.5px] bg-[#0a84ff] shadow-[0_0_8px_rgba(10,132,255,0.6)]"
+ className="pointer-events-none absolute top-0 bottom-2 left-0 z-30 w-[1.5px] bg-[#0a84ff] shadow-[0_0_8px_rgba(10,132,255,0.6)]"
style={{ transform: `translateX(${x}px)` }}
>
<div
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index f3375597..1d148372 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -1,7 +1,7 @@
"use client";
import { useEffect, type RefObject } from "react";
-import { clipSpeed, getClipSpans, totalDuration, useEditor } from "@/cut/lib/store";
+import { clipSpeed, getClipSpans, projectDuration, useEditor } from "@/cut/lib/store";
import { isFullRect, rectOf } from "@/cut/lib/types";
import type { ClipSpan, FrameRect, MediaAsset, OverlayClip, VideoClip } from "@/cut/lib/types";
@@ -25,6 +25,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.
+ private lastPlayNow = 0;
constructor(private canvas: HTMLCanvasElement) {
this.tick = this.tick.bind(this);
@@ -142,10 +145,13 @@ class Engine {
}
return;
}
- // A hidden clip keeps its slot but renders as black — nothing plays there.
+ // A hidden clip plays nothing: fill black only if we own the clear,
+ // otherwise leave whatever is beneath (a below track) showing.
if (clip?.hidden) {
- ctx.fillStyle = "#000";
- ctx.fillRect(0, 0, W, H);
+ if (clear) {
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, W, H);
+ }
return;
}
// Mid-seek the element has no decodable frame; keep the previous frame
@@ -202,7 +208,9 @@ class Engine {
keep.add(next.asset.id);
}
this.pauseExcept(keep);
- this.drawLayer(masterEl, masterSpan.clip, true, 1);
+ // No clear here — the tick clears once, then draws the below tracks, so the
+ // base composites over them (a regioned base leaves them showing).
+ this.drawLayer(masterEl, masterSpan.clip, false, 1);
if (incEl) this.drawLayer(incEl, next!.clip, false, alpha);
return masterEl;
}
@@ -221,15 +229,22 @@ class Engine {
return el;
}
- /** Composite the upper (overlay) tracks over the base, bottom track first.
- * A full-frame clip covers the base ("topmost showing clip plays"); a
- * regioned one shares the frame (split half) or floats small (PiP). */
- private drawOverlays(t: number, play: boolean) {
+ private clearCanvas() {
const ctx = this.canvas.getContext("2d");
if (!ctx) return;
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
+ }
+
+ /** Draw the overlay tracks on one side of the base — `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`. */
+ private drawOverlays(t: number, play: boolean, side: "below" | "above", active: Set<string>) {
const s = useEditor.getState();
- const active = new Set<string>();
- const clips = [...s.overlayClips].sort((a, b) => a.track - b.track);
+ const clips = s.overlayClips
+ .filter((c) => (side === "below" ? c.track < 0 : c.track > 0))
+ .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);
@@ -250,12 +265,14 @@ class Engine {
}
if (el.readyState < 2 || !el.videoWidth) continue;
const rect = rectOf(c);
- // A full-frame overlay covers the base; a regioned one shares the frame
- // (split half) or floats small (PiP). "fit" contains, "fill" crops.
const cover = c.fit === "fill" || (c.fit == null && isFullRect(rect));
this.drawIntoRect(el, rect, cover, 1);
}
- // Pause inactive elements; drop those whose clip is gone.
+ }
+
+ /** Pause overlay elements not drawn this frame; drop those whose clip is gone. */
+ private cleanupOverlays(active: Set<string>) {
+ const s = useEditor.getState();
for (const [id, el] of this.overlayEls) {
if (active.has(id)) continue;
if (!el.paused) el.pause();
@@ -316,7 +333,9 @@ class Engine {
const s = useEditor.getState();
const spans = getClipSpans(s.clips, s.assets);
- const total = totalDuration(s.clips);
+ // Whole-project length so time past the base (a longer upper/lower track or
+ // soundtrack) is still reachable while scrubbing and playing.
+ const total = projectDuration(s);
if (spans.length === 0) {
this.pauseExcept(new Set());
@@ -333,57 +352,81 @@ class Engine {
// frame under it. The playhead (currentTime) is never touched.
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) ??
- spans[spans.length - 1];
- this.composite(span, spans, Math.min(pt, span.start + span.len), false);
- this.drawOverlays(pt, false);
+ const span = spans.find((sp) => pt >= sp.start && pt < sp.start + sp.len);
+ const active = new Set<string>();
+ this.clearCanvas();
+ this.drawOverlays(pt, false, "below", active);
+ // Past the base track there is no base frame — just the backdrop and the
+ // upper/lower tracks that are 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);
+ this.cleanupOverlays(active);
this.syncSoundtrack(t, false);
return;
}
let span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len);
- if (!span) {
- // Reached the end of the last clip.
- useEditor.setState({ playing: false, currentTime: total });
- this.pauseExcept(new Set());
- this.syncSoundtrack(total, false);
- return;
- }
- // Prime the master element (and any dissolve partner) and read the clock.
- let el = this.composite(span, spans, t, true);
-
- // The active element is the master clock; source time maps back through
- // the clip's speed.
- const speed = clipSpeed(span.clip);
- const derived = span.start + (el.currentTime - span.clip.in) / speed;
- if (Math.abs(derived - t) < 1.5) {
- t = Math.max(span.start, Math.min(derived, span.start + span.len));
- }
+ // Draw the below tracks first (backdrop), then prime the master element
+ // (and any dissolve partner) over them and read the clock.
+ const active = new Set<string>();
+ this.clearCanvas();
+ this.drawOverlays(t, true, "below", active);
- // Clip boundary: hand off to the next clip (or finish).
- if (el.currentTime >= span.clip.out - 0.02 || el.ended) {
- const idx = spans.indexOf(span);
- const next = spans[idx + 1];
- if (next) {
- // Jump past the finished clip's whole footprint (including any
- // cross-dissolve overlap), not back to next.start — which still sits
- // inside the outgoing clip's footprint, so find() would re-pick the
- // clip we just finished and playback would ping-pong across the
- // dissolve forever.
- t = Math.max(next.start + 0.0001, span.start + span.len);
- span = next;
- el = this.composite(next, spans, t, true);
- } else {
+ if (span) {
+ let el = this.composite(span, spans, t, true);
+ // The active element is the master clock; source time maps back through
+ // the clip's speed.
+ const speed = clipSpeed(span.clip);
+ const derived = span.start + (el.currentTime - span.clip.in) / speed;
+ if (Math.abs(derived - t) < 1.5) {
+ t = Math.max(span.start, Math.min(derived, span.start + span.len));
+ }
+ // Clip boundary: hand off to the next clip, or (if the base is done but an
+ // upper/lower track runs on) fall through to the wall-clock tail.
+ if (el.currentTime >= span.clip.out - 0.02 || el.ended) {
+ const idx = spans.indexOf(span);
+ const next = spans[idx + 1];
+ if (next) {
+ // Jump past the finished clip's whole footprint (including any
+ // cross-dissolve overlap), not back to next.start — which still sits
+ // inside the outgoing clip's footprint, so find() would re-pick the
+ // clip we just finished and playback would ping-pong across the
+ // dissolve forever.
+ t = Math.max(next.start + 0.0001, span.start + span.len);
+ span = next;
+ el = this.composite(next, spans, t, true);
+ } else if (t >= total - 0.001) {
+ // Base and every other track finished.
+ useEditor.setState({ playing: false, currentTime: total });
+ el.pause();
+ this.drawOverlays(t, true, "above", active);
+ this.cleanupOverlays(active);
+ this.syncSoundtrack(total, false);
+ return;
+ }
+ }
+ this.lastPlayNow = performance.now();
+ } else {
+ // Past the base track but an upper/lower 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();
+ const dt = this.lastPlayNow ? Math.min(0.25, (now - this.lastPlayNow) / 1000) : 0;
+ this.lastPlayNow = now;
+ t = t + dt;
+ if (t >= total - 0.001) {
useEditor.setState({ playing: false, currentTime: total });
- el.pause();
+ this.drawOverlays(t, true, "above", active);
+ this.cleanupOverlays(active);
this.syncSoundtrack(total, false);
return;
}
}
- this.drawOverlays(t, true);
+ this.drawOverlays(t, true, "above", active);
+ this.cleanupOverlays(active);
useEditor.setState({ currentTime: t });
this.syncSoundtrack(t, true);
}
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 8c0f90dd..b5f19a60 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1,7 +1,7 @@
"use client";
import { apiFetch, apiUrl } from "./api";
-import { clipSpeed, getClipSpans, totalDuration } from "./store";
+import { clipSpeed, getClipSpans, projectDuration } from "./store";
import { captionStyle, cueOverlay } from "./subtitles";
import { renderOverlayPng } from "./textRender";
import { FRAME } from "./types";
@@ -126,7 +126,7 @@ async function buildExportForm(
): Promise<FormData> {
const spans = getClipSpans(doc.clips, doc.assets);
if (spans.length === 0) throw new Error("Add a video to the timeline first.");
- const duration = totalDuration(doc.clips);
+ const duration = projectDuration(doc);
const form = new FormData();
const assetById = new Map(doc.assets.map((a) => [a.id, a]));
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 1b292bed..3d7b17d4 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -29,21 +29,27 @@ const uid = () => crypto.randomUUID().slice(0, 8);
const MIN_LEN = 0.1;
-/** Where a video clip lands when dropped: an existing upper track, the magnetic
- * base row, or a brand-new track inserted at z-level `level` (every upper track
- * at or above it shifts up one to make room). Upper-track numbers are 1-based,
- * higher = closer to the top; `level` = maxTrack+1 is a new top track. */
+/** 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. */
export type VideoTrackPlacement =
| { kind: "track"; track: number }
| { kind: "base" }
| { kind: "insert"; level: number };
-/** Open a slot for an inserted track: every upper track at or above `level`
- * shifts up one. A no-op for non-insert placements. */
+/** 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
+ * 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
+ ? clips.map((c) => (c.id !== exclude && c.track >= level ? { ...c, track: c.track + 1 } : c))
+ : clips.map((c) => (c.id !== exclude && c.track <= level ? { ...c, track: c.track - 1 } : c));
+}
const shiftTracksUp = (clips: OverlayClip[], place: VideoTrackPlacement): OverlayClip[] =>
- place.kind === "insert"
- ? clips.map((c) => (c.track >= place.level ? { ...c, track: c.track + 1 } : c))
- : clips;
+ place.kind === "insert" ? openInsertSlot(clips, place.level) : clips;
/** A single-item selection: the primary that drives the Inspector plus the
* one-element multiSelection that bulk actions (delete, copy) and the timeline
@@ -671,9 +677,7 @@ export const useEditor = create<EditorState>((set, get) => {
set((st) => {
const shifted =
place.kind === "insert"
- ? st.overlayClips.map((c) =>
- c.id !== source.id && c.track >= place.level ? { ...c, track: c.track + 1 } : c
- )
+ ? openInsertSlot(st.overlayClips, place.level, source.id)
: st.overlayClips;
return {
overlayClips: shifted.map((c) =>
@@ -1036,7 +1040,7 @@ export const useEditor = create<EditorState>((set, get) => {
},
seek: (t) => {
- const total = totalDuration(get().clips);
+ const total = projectDuration(get());
set({ currentTime: Math.max(0, Math.min(total, t)) });
},
@@ -1534,6 +1538,24 @@ export function totalDuration(clips: VideoClip[]) {
return Math.max(0, t);
}
+/** 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. */
+export function projectDuration(s: {
+ clips: VideoClip[];
+ overlayClips: OverlayClip[];
+ audioClips: AudioClip[];
+}): number {
+ let end = totalDuration(s.clips);
+ for (const c of s.overlayClips) {
+ const sp = c.speed && c.speed > 0 ? c.speed : 1;
+ end = Math.max(end, c.start + Math.max(0.1, (c.out - c.in) / sp));
+ }
+ for (const a of s.audioClips) end = Math.max(end, a.start + clipLen(a));
+ return Math.max(0, end);
+}
+
/**
* Build the annotation shifter for a video-track edit (clip delete, asset
* removal). Titles and cues are pinned to timeline time, so when clips go the
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 351a847d..8692ba57 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -226,6 +226,14 @@ 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
+ // 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 padColor = hasBelow ? "[email protected]" : "black";
// One ffmpeg input per distinct media file (from the project folder),
// plus one per uploaded overlay PNG.
const mediaFiles = [
@@ -282,9 +290,9 @@ async function runExport(job: Job, spec: ExportSpec) {
frame =
c.fit === "fill"
? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh},` +
- `pad=${W}:${H}:${rx}:${ry}:color=black`
+ `pad=${W}:${H}:${rx}:${ry}:color=${padColor}`
: `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2,` +
- `pad=${W}:${H}:${rx}+(${rw}-iw)/2:${ry}+(${rh}-ih)/2:color=black`;
+ `pad=${W}:${H}:${rx}+(${rw}-iw)/2:${ry}+(${rh}-ih)/2:color=${padColor}`;
} else {
frame =
c.fit === "fill"
@@ -293,17 +301,19 @@ async function runExport(job: Job, spec: ExportSpec) {
`crop=${W}:${H}:(iw-ow)*${num(0.5 + Math.max(-1, Math.min(1, c.panX ?? 0)) / 2)}` +
`:(ih-oh)*${num(0.5 + Math.max(-1, Math.min(1, c.panY ?? 0)) / 2)}`
: `scale=${W}:${H}:force_original_aspect_ratio=decrease,` +
- `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black`;
+ `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=${padColor}`;
}
// setpts/speed rescales the clip's duration on the timeline.
filters.push(
`[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=(PTS-STARTPTS)/${num(speed)},` +
- `fps=${fps},${frame},setsar=1,format=yuv420p[v${j}]`
+ `fps=${fps},${frame},setsar=1,format=${baseFmt}[v${j}]`
);
} else {
- // No video stream, or a hidden clip: keep the slot as black frames.
+ // 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";
filters.push(
- `color=c=black:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=yuv420p[v${j}]`
+ `color=c=${slot}:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=${baseFmt}[v${j}]`
);
}
if (!c.muted && !c.hidden && audioPresence.get(c.file)) {
@@ -347,63 +357,74 @@ async function runExport(job: Job, spec: ExportSpec) {
aAcc = aOut;
}
- // Composite the upper video tracks (bottom track first) over the base. A
- // full-frame clip covers the base; a regioned one shares the frame (split
- // half) or floats small (PiP). Overlay audio (unless muted) mixes in below.
- let vLabel = vAcc;
+ // 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.
const overlaySoundLabels: string[] = [];
- [...overlayVideos]
- .sort((a, b) => a.track - b.track)
- .forEach((oc, k) => {
- if (!videoPresence.get(oc.file)) return;
- const idx = inputIndex.get(oc.file)!;
- const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;
- const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);
- const end = Math.min(oc.start + olen, spec.duration);
- const region = regionPx(oc.frame, W, H);
- // A full-frame overlay covers; a region either covers-and-crops ("fill")
- // or is contained and centered in its rect ("fit"), letting the base show
- // around it (picture-in-picture).
- const cover = oc.fit === "fill" || (oc.fit == null && !region);
- let framing: string;
- let pos: string;
- if (!region) {
- // "fit" stays transparent and centered so the base shows through the
- // margins (matching the preview); black-padding it would occlude the
- // base. "fill" covers and crops.
- framing = cover
- ? `scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H}`
- : `scale=${W}:${H}:force_original_aspect_ratio=decrease:force_divisible_by=2`;
- pos = cover ? "0:0" : `x=(${W}-w)/2:y=(${H}-h)/2`;
- } else {
- const { rx, ry, rw, rh } = region;
- framing = cover
- ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh}`
- : `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2`;
- pos = cover ? `${rx}:${ry}` : `x=${rx}+(${rw}-w)/2:y=${ry}+(${rh}-h)/2`;
- }
- const seg = `ovv${k}`;
- // tpad delays the clip to its timeline start without a leading-frame stall.
- filters.push(
- `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)},` +
- `fps=${fps},${framing},setsar=1,format=yuv420p,tpad=start_duration=${num(oc.start)}[${seg}]`
- );
- const next = `vovv${k}`;
+ 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.
+ const addOverlay = (oc: (typeof overlayVideos)[number], onto: string): string => {
+ if (!videoPresence.get(oc.file)) return onto;
+ const idx = inputIndex.get(oc.file)!;
+ const ospeed = oc.speed && oc.speed > 0 ? oc.speed : 1;
+ const olen = Math.max(0.1, (oc.out - oc.in) / ospeed);
+ const end = Math.min(oc.start + olen, spec.duration);
+ const region = regionPx(oc.frame, W, H);
+ const cover = oc.fit === "fill" || (oc.fit == null && !region);
+ let framing: string;
+ let pos: string;
+ if (!region) {
+ framing = cover
+ ? `scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H}`
+ : `scale=${W}:${H}:force_original_aspect_ratio=decrease:force_divisible_by=2`;
+ pos = cover ? "0:0" : `x=(${W}-w)/2:y=(${H}-h)/2`;
+ } else {
+ const { rx, ry, rw, rh } = region;
+ framing = cover
+ ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh}`
+ : `scale=${rw}:${rh}:force_original_aspect_ratio=decrease:force_divisible_by=2`;
+ pos = cover ? `${rx}:${ry}` : `x=${rx}+(${rw}-w)/2:y=${ry}+(${rh}-h)/2`;
+ }
+ const k = ovk++;
+ const seg = `ovv${k}`;
+ // tpad delays the clip to its timeline start without a leading-frame stall.
+ filters.push(
+ `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)},` +
+ `fps=${fps},${framing},setsar=1,format=yuv420p,tpad=start_duration=${num(oc.start)}[${seg}]`
+ );
+ const next = `vovv${k}`;
+ filters.push(
+ `[${onto}][${seg}]overlay=${pos}:enable='between(t,${num(oc.start)},${num(end)})':eof_action=pass[${next}]`
+ );
+ if (!oc.muted && audioPresence.get(oc.file)) {
+ const tempo = ospeed !== 1 ? `${atempoChain(ospeed)},` : "";
+ const delayMs = Math.max(0, Math.round(oc.start * 1000));
+ const lab = `ovs${k}`;
filters.push(
- `[${vLabel}][${seg}]overlay=${pos}:enable='between(t,${num(oc.start)},${num(end)})':eof_action=pass[${next}]`
+ `[${idx}:a]atrim=${num(oc.in)}:${num(oc.out)},asetpts=PTS-STARTPTS,${tempo}` +
+ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,adelay=${delayMs}:all=1[${lab}]`
);
- vLabel = next;
- if (!oc.muted && audioPresence.get(oc.file)) {
- const tempo = ospeed !== 1 ? `${atempoChain(ospeed)},` : "";
- const delayMs = Math.max(0, Math.round(oc.start * 1000));
- const lab = `ovs${k}`;
- filters.push(
- `[${idx}:a]atrim=${num(oc.in)}:${num(oc.out)},asetpts=PTS-STARTPTS,${tempo}` +
- `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,adelay=${delayMs}:all=1[${lab}]`
- );
- overlaySoundLabels.push(lab);
- }
- });
+ overlaySoundLabels.push(lab);
+ }
+ return next;
+ };
+
+ 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.
+ 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";
+ }
+ for (const oc of aboveVideos) vLabel = addOverlay(oc, vLabel);
// Burn in text overlays, each windowed to its timeline range.
spec.overlays.forEach((o, k) => {