Skip to content

Open source CapCut alternative.

TypeScript

feat(site): multi-region video compositor (split-screen + PiP)

David Lebefe83c014b4
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index bc55c71f..ea92b1f1 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -58,6 +58,7 @@ export function Editor({ projectId }: { projectId: string }) {
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
+ overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
},
@@ -70,6 +71,7 @@ export function Editor({ projectId }: { projectId: string }) {
let last: {
clips: unknown;
audioClips: unknown;
+ overlayClips: unknown;
overlays: unknown;
subtitles: unknown;
aspect: string;
@@ -80,12 +82,14 @@ export function Editor({ projectId }: { projectId: string }) {
last !== null &&
(s.clips !== last.clips ||
s.audioClips !== last.audioClips ||
+ s.overlayClips !== last.overlayClips ||
s.overlays !== last.overlays ||
s.subtitles !== last.subtitles ||
s.aspect !== last.aspect);
last = {
clips: s.clips,
audioClips: s.audioClips,
+ overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
aspect: s.aspect,
@@ -137,6 +141,7 @@ export function Editor({ projectId }: { projectId: string }) {
const changed =
s.clips !== (last.clips as unknown) ||
s.audioClips !== (last.audioClips as unknown) ||
+ s.overlayClips !== (last.overlayClips as unknown) ||
s.overlays !== (last.overlays as unknown) ||
s.subtitles !== (last.subtitles as unknown) ||
s.aspect !== last.aspect ||
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index 682db129..acc53403 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -60,6 +60,7 @@ export function ExportDialog() {
assets: s.assets,
clips: s.clips,
audioClips: s.audioClips,
+ overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
}, settings);
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 2af7d0f7..f88e82b0 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -24,10 +24,17 @@ import { writeTextStyle } from "@/cut/lib/textStyle";
import { formatTime } from "@/cut/lib/time";
import {
FONTS,
+ isFullRect,
+ LAYOUTS,
+ rectOf,
+ regionLabel,
SPEED_MAX,
SPEED_MIN,
TRANSITION_MAX,
type AudioClip,
+ type FrameRect,
+ type LayoutId,
+ type OverlayClip,
type TextOverlay,
type VideoClip,
} from "@/cut/lib/types";
@@ -149,6 +156,9 @@ export function Inspector() {
const overlay = useEditor((s) =>
selection?.kind === "text" ? s.overlays.find((o) => o.id === selection.id) : undefined
);
+ const overlayClip = useEditor((s) =>
+ selection?.kind === "overlayClip" ? s.overlayClips.find((c) => c.id === selection.id) : undefined
+ );
return (
<aside className="flex min-h-0 flex-col overflow-y-auto border-l border-border bg-card">
@@ -156,6 +166,8 @@ export function Inspector() {
<ClipPanel key={clip.id} clip={clip} />
) : audio ? (
<AudioPanel key={audio.id} clip={audio} />
+ ) : overlayClip ? (
+ <OverlayClipPanel key={overlayClip.id} clip={overlayClip} />
) : overlay ? (
<TextPanel key={overlay.id} overlay={overlay} />
) : null}
@@ -184,6 +196,45 @@ const Value = ({ children, className }: { children: React.ReactNode; className?:
<span className={cn("font-mono text-[11.5px] tabular-nums", className)}>{children}</span>
);
+/** 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
+ * videos can share the frame; "Full" clears the region. */
+function LayoutButtons({
+ rect,
+ onPick,
+}: {
+ rect: FrameRect;
+ onPick: (frame: FrameRect | undefined, fit: "fit" | "fill") => void;
+}) {
+ const current = regionLabel(rect);
+ return (
+ <div className="flex flex-col gap-1.5 py-1">
+ <span className="text-[11.5px] font-medium text-muted-foreground">Layout</span>
+ <div className="grid grid-cols-3 gap-1">
+ {(Object.keys(LAYOUTS) as LayoutId[]).map((id) => {
+ const L = LAYOUTS[id];
+ const active = current === L.label;
+ return (
+ <button
+ key={id}
+ aria-pressed={active}
+ className={cn(
+ "rounded-md border px-2 py-1 text-[11px] font-medium transition-colors",
+ active
+ ? "border-violet-500 bg-violet-500/10 text-foreground"
+ : "border-input text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => onPick(id === "full" ? undefined : { ...L.rect }, L.fit)}
+ >
+ {L.label}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
function ClipPanel({ clip }: { clip: VideoClip }) {
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const updateClip = useEditor((s) => s.updateClip);
@@ -249,6 +300,12 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
onCheckedChange={(v) => updateClip(clip.id, { muted: v })}
/>
</Row>
+ <Row label="Hide from output">
+ <Switch
+ checked={!!clip.hidden}
+ onCheckedChange={(v) => updateClip(clip.id, { hidden: v })}
+ />
+ </Row>
<Row label="Framing">
<div className="clip-framing flex rounded-lg border border-input p-0.5">
{(["fit", "fill"] as const).map((mode) => (
@@ -278,10 +335,14 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
</button>
</Row>
)}
+ <LayoutButtons
+ rect={rectOf(clip)}
+ onPick={(frame, fit) => updateClip(clip.id, { frame, fit })}
+ />
<p className="mt-2.5 text-[11.5px] leading-relaxed text-muted-foreground">
- {clip.fit === "fill"
- ? "Fill crops the video to cover the frame — drag it in the preview to choose what stays visible."
- : "Drag the clip edges on the timeline to trim it. Fit letterboxes the whole picture; Fill crops it to cover the frame."}
+ {isFullRect(rectOf(clip))
+ ? "Put this clip in half the frame (Top/Bottom or Left/Right) and drop another video on an overlay track to play two at once."
+ : "Sharing the frame — drag the box in the preview to move or resize it. Pick Full to fill the frame again."}
</p>
</div>
</>
@@ -352,6 +413,85 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
{(clip.fadeOut ?? 0).toFixed(1)}s
</Value>
</Row>
+ <Row label="Hide from output">
+ <Switch
+ checked={!!clip.hidden}
+ onCheckedChange={(v) => useEditor.getState().updateAudio(clip.id, { hidden: v })}
+ />
+ </Row>
+ </div>
+ </>
+ );
+}
+
+function OverlayClipPanel({ clip }: { clip: OverlayClip }) {
+ const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
+ const update = useEditor((s) => s.updateOverlayClip);
+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
+ const len = (clip.out - clip.in) / speed;
+ return (
+ <>
+ <PanelTitle>Overlay clip</PanelTitle>
+ <div className="flex flex-col gap-1 px-3.5 pb-4">
+ <div className="mb-1.5 truncate border-b border-border pb-2.5 text-xs font-medium" title={asset?.name}>
+ {asset?.name}
+ </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 })}
+ />
+ <Row label="Framing">
+ <div className="flex rounded-lg border border-input p-0.5">
+ {(["fit", "fill"] as const).map((mode) => (
+ <button
+ key={mode}
+ className={cn(
+ "rounded-md px-2.5 py-1 text-[11.5px] font-medium transition-colors",
+ (clip.fit ?? "fit") === mode
+ ? "bg-neutral-900 text-white"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ onClick={() => update(clip.id, { fit: mode })}
+ >
+ {mode === "fit" ? "Fit" : "Fill"}
+ </button>
+ ))}
+ </div>
+ </Row>
+ <Row label="Mute audio">
+ <Switch checked={clip.muted} onCheckedChange={(v) => update(clip.id, { muted: v })} />
+ </Row>
+ <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/Preview.tsx b/site/src/cut/components/Preview.tsx
index 4160c12e..bb133212 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "react";
import { usePlayback } from "@/cut/hooks/usePlayback";
import { startDrag } from "@/cut/lib/drag";
import { getClipSpans, useEditor } from "@/cut/lib/store";
-import { FRAME, type Aspect, type ClipSpan, type MediaAsset, type VideoClip } from "@/cut/lib/types";
+import { FRAME, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { OverlayLayer, SubtitleLayer } from "./OverlayLayer";
@@ -19,7 +19,9 @@ function pannableSpan(s: {
const span =
spans.find((sp) => s.currentTime >= sp.start && sp.start + sp.len > s.currentTime) ??
spans[spans.length - 1];
- if (!span || span.clip.fit !== "fill") return null;
+ // Pan only makes sense for a full-frame fill clip; a regioned clip is moved
+ // with its own preview handle instead.
+ if (!span || span.clip.fit !== "fill" || !isFullRect(rectOf(span.clip))) return null;
const { width, height } = span.asset;
if (!width || !height) return null;
const frame = FRAME[s.aspect];
@@ -104,6 +106,7 @@ export function Preview() {
}}
>
<canvas ref={canvasRef} width={frame.w} height={frame.h} className="block size-full" />
+ <OverlayPipHandle stage={stage} />
<SubtitleLayer stageWidth={stage.w} />
<OverlayLayer stageWidth={stage.w} />
</div>
@@ -111,3 +114,81 @@ export function Preview() {
</section>
);
}
+
+/**
+ * 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
+ * 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.
+ */
+function OverlayPipHandle({ stage }: { stage: { w: number; h: number } }) {
+ const selection = useEditor((s) => s.selection);
+ const overlayClips = useEditor((s) => s.overlayClips);
+ const clips = useEditor((s) => s.clips);
+ const assets = useEditor((s) => s.assets);
+ const currentTime = useEditor((s) => s.currentTime);
+
+ // Resolve the selected, live, regioned layer plus how to patch its rect.
+ let rect: FrameRect | null = null;
+ let apply: ((frame: FrameRect) => void) | null = null;
+ if (selection?.kind === "overlayClip") {
+ const clip = overlayClips.find((c) => c.id === selection.id);
+ if (clip && !clip.hidden) {
+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
+ const len = Math.max(0.1, (clip.out - clip.in) / speed);
+ if (currentTime >= clip.start && currentTime < clip.start + len) {
+ rect = rectOf(clip);
+ apply = (frame) => useEditor.getState().updateOverlayClipTransient(clip.id, { frame });
+ }
+ }
+ } else if (selection?.kind === "clip") {
+ const sp = getClipSpans(clips, assets).find((x) => x.clip.id === selection.id);
+ if (sp && !sp.clip.hidden && currentTime >= sp.start && currentTime < sp.start + sp.len) {
+ rect = rectOf(sp.clip);
+ apply = (frame) => useEditor.getState().updateClipTransient(sp.clip.id, { frame });
+ }
+ }
+ if (!rect || !apply || isFullRect(rect)) return null;
+ const r = rect;
+ const patch = apply;
+
+ const onMove = (e: React.PointerEvent) => {
+ e.stopPropagation();
+ useEditor.getState().pushHistory();
+ startDrag(e, {
+ onMove: (dx, dy) =>
+ patch({
+ ...r,
+ x: Math.max(0, Math.min(1 - r.w, r.x + dx / stage.w)),
+ y: Math.max(0, Math.min(1 - r.h, r.y + dy / stage.h)),
+ }),
+ });
+ };
+
+ const onResize = (e: React.PointerEvent) => {
+ e.stopPropagation();
+ useEditor.getState().pushHistory();
+ startDrag(e, {
+ onMove: (dx, dy) =>
+ patch({
+ ...r,
+ w: Math.max(0.1, Math.min(1 - r.x, r.w + dx / stage.w)),
+ h: Math.max(0.1, Math.min(1 - r.y, r.h + dy / stage.h)),
+ }),
+ });
+ };
+
+ return (
+ <div
+ className="absolute cursor-move rounded-[3px] shadow-[inset_0_0_0_2px_#a855f7]"
+ style={{ left: r.x * stage.w, top: r.y * stage.h, width: r.w * stage.w, height: r.h * stage.h }}
+ onPointerDown={onMove}
+ >
+ <span
+ className="absolute -right-1.5 -bottom-1.5 size-3 cursor-nwse-resize rounded-full bg-violet-500 shadow-[0_0_0_2px_white]"
+ onPointerDown={onResize}
+ />
+ </div>
+ );
+}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 99c5c419..279efb62 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { Captions, Check, Circle, ClipboardList, Copy, Film, FolderOpen, FolderPlus, Loader2, Mic, Music, Plus, Trash2, Upload, Video } from "lucide-react";
+import { Captions, Check, Circle, ClipboardList, Copy, Film, FolderOpen, FolderPlus, Layers, Loader2, Mic, Music, Plus, Trash2, Upload, Video } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
@@ -410,16 +410,31 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
<span className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums">
{formatTime(asset.duration)}
</span>
- <span
- role="button"
- title="Add to timeline"
- className="absolute top-1 left-1 grid size-5 scale-75 cursor-pointer place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-all group-hover:scale-100 group-hover:opacity-100 hover:brightness-110"
- onClick={(e) => {
- e.stopPropagation();
- add();
- }}
- >
- <Plus className="size-3" />
+ <span className="absolute top-1 left-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
+ <span
+ role="button"
+ title="Add to timeline"
+ className="grid size-5 scale-75 cursor-pointer place-items-center rounded-full bg-primary text-primary-foreground transition-transform group-hover:scale-100 hover:brightness-110"
+ onClick={(e) => {
+ e.stopPropagation();
+ add();
+ }}
+ >
+ <Plus className="size-3" />
+ </span>
+ {asset.type === "video" && (
+ <span
+ role="button"
+ title="Add as an overlay track (PiP / composite)"
+ className="grid size-5 scale-75 cursor-pointer place-items-center rounded-full bg-violet-600 text-white transition-transform group-hover:scale-100 hover:brightness-110"
+ onClick={(e) => {
+ e.stopPropagation();
+ useEditor.getState().addOverlayClipFromAsset(asset.id);
+ }}
+ >
+ <Layers className="size-3" />
+ </span>
+ )}
</span>
<span className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
<span
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index e0893c7f..86d2c569 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -24,10 +24,12 @@ 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 { formatTime, formatTimecode } from "@/cut/lib/time";
-import type { AudioClip, ClipSpan, MediaAsset, SubtitleCue, TextOverlay } from "@/cut/lib/types";
+import { rectOf, regionLabel } from "@/cut/lib/types";
+import type { AudioClip, ClipSpan, MediaAsset, OverlayClip, SubtitleCue, TextOverlay } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
const VIDEO_H = 64;
+const OVERLAY_H = 44;
const AUDIO_H = 44;
const TEXT_H = 28;
const SUB_H = 22;
@@ -83,6 +85,7 @@ function videoInsertIndex(spans: ClipSpan[], t: number): number {
export function Timeline() {
const clips = useEditor((s) => s.clips);
const audioClips = useEditor((s) => s.audioClips);
+ const overlayClips = useEditor((s) => s.overlayClips);
const overlays = useEditor((s) => s.overlays);
const assets = useEditor((s) => s.assets);
const pps = useEditor((s) => s.pxPerSec);
@@ -146,6 +149,13 @@ 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),
+ [overlayClips]
+ );
+
const onTextLaneDrag = useCallback(
(id: string, targetRow: number) => setTextDrag({ id, targetRow }),
[]
@@ -436,6 +446,27 @@ export function Timeline() {
>
<Ruler pps={pps} width={contentW} onScrub={scrub} />
+ {overlayTracks.map((track) => (
+ <div
+ key={`ov-${track}`}
+ className="relative mt-1.5"
+ style={{ height: OVERLAY_H }}
+ onPointerDown={deselectIfSelf}
+ >
+ {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}`)}
+ />
+ ))}
+ </div>
+ ))}
+
<div className="relative mt-1.5" style={{ height: VIDEO_H }} onPointerDown={deselectIfSelf}>
{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">
@@ -1094,6 +1125,110 @@ function AudioView({
);
}
+/** Timeline footprint (seconds) of an overlay clip, honoring its speed. */
+function overlayLen(c: OverlayClip) {
+ const src = c.out - c.in;
+ const eff = c.speed && c.speed > 0 ? src / c.speed : src;
+ return Math.max(0.1, eff);
+}
+
+/**
+ * An upper-track video clip: free-positioned by `start` like an audio clip,
+ * draggable and trimmable. Full-frame layers (`scale === 1`) read as a stacked
+ * composite; smaller ones are picture-in-picture. Hidden clips gray out.
+ */
+function OverlayClipView({
+ clip,
+ asset,
+ pps,
+ selected,
+}: {
+ clip: OverlayClip;
+ asset: MediaAsset | undefined;
+ pps: number;
+ selected: boolean;
+}) {
+ const w = Math.max(10, overlayLen(clip) * pps);
+
+ if (!asset) return null;
+
+ const onBody = (e: React.PointerEvent) => {
+ if (e.metaKey || e.shiftKey) {
+ useEditor.getState().toggleSelect({ kind: "overlayClip", id: clip.id });
+ return;
+ }
+ const s = useEditor.getState();
+ s.select({ kind: "overlayClip", id: clip.id });
+ s.seek(clip.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / pps);
+ s.pushHistory();
+ const start0 = clip.start;
+ startDrag(e, {
+ onMove: (dx) =>
+ s.updateOverlayClipTransient(clip.id, { start: Math.max(0, start0 + dx / pps) }),
+ });
+ };
+
+ const onTrimLeft = (e: React.PointerEvent) => {
+ const s = useEditor.getState();
+ s.select({ kind: "overlayClip", id: clip.id });
+ s.pushHistory();
+ const in0 = clip.in;
+ const start0 = clip.start;
+ startDrag(e, {
+ onMove: (dx) => {
+ let d = dx / pps;
+ d = Math.max(d, -in0, -start0);
+ d = Math.min(d, clip.out - 0.15 - in0);
+ s.updateOverlayClipTransient(clip.id, { in: in0 + d, start: start0 + d });
+ },
+ });
+ };
+
+ const onTrimRight = (e: React.PointerEvent) => {
+ const s = useEditor.getState();
+ s.select({ kind: "overlayClip", id: clip.id });
+ s.pushHistory();
+ const out0 = clip.out;
+ startDrag(e, {
+ onMove: (dx) => {
+ const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + dx / pps));
+ s.updateOverlayClipTransient(clip.id, { out: nout });
+ },
+ });
+ };
+
+ const label = regionLabel(rectOf(clip));
+
+ return (
+ <div
+ className={cn(
+ "tl-overlay-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-[7px] bg-gradient-to-b from-violet-500 to-violet-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
+ selected && SELECTED_SHADOW,
+ clip.hidden && "opacity-40 grayscale"
+ )}
+ style={{ left: clip.start * pps, width: w, height: OVERLAY_H - 4 }}
+ onPointerDown={onBody}
+ >
+ {asset.thumbs?.[0] && (
+ <img
+ src={asset.thumbs[0]}
+ alt=""
+ className="pointer-events-none absolute inset-0 size-full object-cover opacity-30"
+ />
+ )}
+ <span className="pointer-events-none absolute top-[3px] left-2 flex items-center gap-1 text-[9.5px] whitespace-nowrap text-white/90 [text-shadow:0_1px_2px_rgba(0,0,0,0.35)]">
+ {clip.muted && <VolumeX className="size-2.5" />}
+ {asset.name}
+ </span>
+ <span className="pointer-events-none absolute bottom-[3px] left-2 rounded-sm bg-black/30 px-1 text-[8.5px] font-medium text-white/85">
+ {label}
+ </span>
+ <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} />
+ <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} />
+ </div>
+ );
+}
+
function TextBar({
overlay: o,
pps,
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index f622c07b..f3375597 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -2,7 +2,8 @@
import { useEffect, type RefObject } from "react";
import { clipSpeed, getClipSpans, totalDuration, useEditor } from "@/cut/lib/store";
-import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
+import { isFullRect, rectOf } from "@/cut/lib/types";
+import type { ClipSpan, FrameRect, MediaAsset, OverlayClip, VideoClip } from "@/cut/lib/types";
// The canvas backing store is the full frame resolution (1080×1920 or
// 1920×1080, set by Preview from the project aspect) so the preview stays
@@ -17,6 +18,9 @@ import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
*/
class Engine {
private videoEls = new Map<string, HTMLVideoElement>();
+ // One element per overlay clip (keyed by clip id, not asset) so the same
+ // source can appear on two tracks at once.
+ private overlayEls = new Map<string, HTMLVideoElement>();
private audioEls = new Map<string, HTMLAudioElement>();
private raf = 0;
private activeClipId: string | null = null;
@@ -35,8 +39,14 @@ class Engine {
el.removeAttribute("src");
el.load();
}
+ for (const el of this.overlayEls.values()) {
+ el.pause();
+ el.removeAttribute("src");
+ el.load();
+ }
for (const el of this.audioEls.values()) el.pause();
this.videoEls.clear();
+ this.overlayEls.clear();
this.audioEls.clear();
}
@@ -86,6 +96,40 @@ class Engine {
}
}
+ /** Draw a video element into a sub-region of the frame. "fill" covers the
+ * region and crops the overflow (clipped to the rect); "fit" contains the
+ * whole picture inside it, centered. */
+ private drawIntoRect(el: HTMLVideoElement, rect: FrameRect, fill: boolean, alpha: number) {
+ const ctx = this.canvas.getContext("2d");
+ if (!ctx) return;
+ const W = this.canvas.width;
+ const H = this.canvas.height;
+ const rx = rect.x * W;
+ const ry = rect.y * H;
+ const rw = rect.w * W;
+ const rh = rect.h * H;
+ const sc = fill
+ ? Math.max(rw / el.videoWidth, rh / el.videoHeight)
+ : Math.min(rw / el.videoWidth, rh / el.videoHeight);
+ const dw = el.videoWidth * sc;
+ const dh = el.videoHeight * sc;
+ const dx = rx + (rw - dw) / 2;
+ const dy = ry + (rh - dh) / 2;
+ const prevAlpha = ctx.globalAlpha;
+ ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
+ if (fill) {
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(rx, ry, rw, rh);
+ ctx.clip();
+ ctx.drawImage(el, dx, dy, dw, dh);
+ ctx.restore();
+ } else {
+ ctx.drawImage(el, dx, dy, dw, dh);
+ }
+ ctx.globalAlpha = prevAlpha;
+ }
+
private drawLayer(el: HTMLVideoElement | null, clip: VideoClip | undefined, clear: boolean, alpha: number) {
const ctx = this.canvas.getContext("2d");
if (!ctx) return;
@@ -98,6 +142,12 @@ class Engine {
}
return;
}
+ // A hidden clip keeps its slot but renders as black — nothing plays there.
+ if (clip?.hidden) {
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, W, H);
+ return;
+ }
// Mid-seek the element has no decodable frame; keep the previous frame
// on the canvas instead of strobing black (matters while skimming).
if (el.readyState < 2 || !el.videoWidth) return;
@@ -105,6 +155,13 @@ class Engine {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, W, H);
}
+ // A regioned base 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)) {
+ this.drawIntoRect(el, rect, clip?.fit === "fill", alpha);
+ return;
+ }
const fill = clip?.fit === "fill";
const scale = fill
? Math.max(W / el.videoWidth, H / el.videoHeight)
@@ -130,7 +187,8 @@ class Engine {
* is live at time `t`, draw that next clip over it at ramping opacity — a
* true A·(1−α)+B·α blend. Returns the master element (the playback clock). */
private composite(masterSpan: ClipSpan, spans: ClipSpan[], t: number, play: boolean) {
- const masterEl = this.prepare(masterSpan, t, play, masterSpan.clip.muted);
+ // A hidden clip is silent as well as black.
+ const masterEl = this.prepare(masterSpan, t, play, masterSpan.clip.muted || !!masterSpan.clip.hidden);
this.activeClipId = masterSpan.clip.id;
const keep = new Set([masterSpan.asset.id]);
const next = spans[spans.indexOf(masterSpan) + 1];
@@ -149,6 +207,66 @@ class Engine {
return masterEl;
}
+ private overlayVideoFor(clip: OverlayClip, asset: MediaAsset) {
+ let el = this.overlayEls.get(clip.id);
+ if (!el) {
+ el = document.createElement("video");
+ el.playsInline = true;
+ el.preload = "auto";
+ el.crossOrigin = "anonymous";
+ el.muted = true; // overlay audio is mixed on export, not previewed here
+ el.src = asset.url;
+ this.overlayEls.set(clip.id, el);
+ }
+ 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) {
+ const ctx = this.canvas.getContext("2d");
+ if (!ctx) return;
+ const s = useEditor.getState();
+ const active = new Set<string>();
+ const clips = [...s.overlayClips].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);
+ if (!asset) continue;
+ const speed = c.speed && c.speed > 0 ? c.speed : 1;
+ const len = Math.max(0.1, (c.out - c.in) / speed);
+ if (t < c.start || t >= c.start + len) continue;
+ active.add(c.id);
+ const el = this.overlayVideoFor(c, asset);
+ if (el.playbackRate !== speed) el.playbackRate = speed;
+ const target = c.in + Math.max(0, t - c.start) * speed;
+ const tol = play ? 0.34 : 0.05;
+ if (Math.abs(el.currentTime - target) > tol && !el.seeking) el.currentTime = target;
+ if (play) {
+ if (el.paused && el.readyState >= 2) void el.play().catch(() => {});
+ } else if (!el.paused) {
+ el.pause();
+ }
+ 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.
+ for (const [id, el] of this.overlayEls) {
+ if (active.has(id)) continue;
+ if (!el.paused) el.pause();
+ if (!s.overlayClips.some((c) => c.id === id)) {
+ el.removeAttribute("src");
+ el.load();
+ this.overlayEls.delete(id);
+ }
+ }
+ }
+
private syncSoundtrack(t: number, playing: boolean) {
const s = useEditor.getState();
const live = new Set<string>();
@@ -165,7 +283,8 @@ class Engine {
// Detached audio can carry its video clip's rate; footprint is (out-in)/speed.
const speed = a.speed && a.speed > 0 ? a.speed : 1;
const len = Math.max(0.1, (a.out - a.in) / speed);
- const active = playing && t >= a.start && t < a.start + len;
+ // A hidden clip is muted from the mix — keep its element but never play it.
+ const active = playing && !a.hidden && t >= a.start && t < a.start + len;
if (active) {
// Fade envelope: linear ramps at either end of the clip.
const rel = t - a.start;
@@ -218,6 +337,7 @@ class Engine {
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);
this.syncSoundtrack(t, false);
return;
}
@@ -263,6 +383,7 @@ class Engine {
}
}
+ this.drawOverlays(t, true);
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 92def260..8c0f90dd 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -5,7 +5,15 @@ import { clipSpeed, getClipSpans, totalDuration } from "./store";
import { captionStyle, cueOverlay } from "./subtitles";
import { renderOverlayPng } from "./textRender";
import { FRAME } from "./types";
-import type { Aspect, AudioClip, MediaAsset, SubtitlesBlock, TextOverlay, VideoClip } from "./types";
+import type {
+ Aspect,
+ AudioClip,
+ MediaAsset,
+ OverlayClip,
+ SubtitlesBlock,
+ TextOverlay,
+ VideoClip,
+} from "./types";
export interface ExportSettings {
width: number;
@@ -97,6 +105,7 @@ export interface ExportDoc {
assets: MediaAsset[];
clips: VideoClip[];
audioClips: AudioClip[];
+ overlayClips: OverlayClip[];
overlays: TextOverlay[];
subtitles: SubtitlesBlock;
}
@@ -129,12 +138,31 @@ async function buildExportForm(
fit: sp.clip.fit ?? "fit",
panX: sp.clip.panX ?? 0,
panY: sp.clip.panY ?? 0,
+ frame: sp.clip.frame,
speed: clipSpeed(sp.clip),
transition: sp.transitionOut,
+ hidden: sp.clip.hidden,
}));
+ // Upper video tracks composited over the base; hidden ones are dropped.
+ const overlayVideos = doc.overlayClips
+ .filter((c) => !c.hidden && assetById.has(c.assetId) && c.start < duration)
+ .map((c) => ({
+ file: assetById.get(c.assetId)!.fileName,
+ in: c.in,
+ out: c.out,
+ start: c.start,
+ 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.
+ fit: c.fit,
+ muted: c.muted,
+ speed: c.speed,
+ }));
+
const audio = doc.audioClips
- .filter((a) => a.start < duration && assetById.has(a.assetId))
+ .filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId))
.map((a) => ({
file: assetById.get(a.assetId)!.fileName,
in: a.in,
@@ -174,7 +202,7 @@ async function buildExportForm(
form.append(
"spec",
- JSON.stringify({ projectId, target, ...settings, duration, clips, audio, overlays })
+ JSON.stringify({ projectId, target, ...settings, duration, clips, audio, overlayVideos, overlays })
);
return form;
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 07a7e142..84237102 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -6,6 +6,7 @@ import type {
AudioClip,
ClipSpan,
MediaAsset,
+ OverlayClip,
ProjectDoc,
Selection,
StoredAsset,
@@ -36,6 +37,7 @@ export const TIMELINE_H_MAX = 600;
interface DocSnapshot {
clips: VideoClip[];
audioClips: AudioClip[];
+ overlayClips: OverlayClip[];
overlays: TextOverlay[];
subtitles: SubtitlesBlock;
}
@@ -54,6 +56,8 @@ interface EditorState {
assets: MediaAsset[];
clips: VideoClip[];
audioClips: AudioClip[];
+ /** Upper video tracks composited over the base track. */
+ overlayClips: OverlayClip[];
overlays: TextOverlay[];
/** Output frame (9:16 vertical or 16:9 widescreen), persisted per project. */
aspect: Aspect;
@@ -111,6 +115,10 @@ interface EditorState {
updateClipTransient: (id: string, patch: Partial<VideoClip>) => void;
updateAudioTransient: (id: string, patch: Partial<AudioClip>) => void;
moveClip: (id: string, toIndex: number) => void;
+ /** Add a video asset as a full-frame overlay on the next free upper track. */
+ addOverlayClipFromAsset: (assetId: string, start?: number) => void;
+ updateOverlayClip: (id: string, patch: Partial<OverlayClip>) => void;
+ updateOverlayClipTransient: (id: string, patch: Partial<OverlayClip>) => void;
/** iMovie "Detach Audio": lift the selected clip's sound onto the
* soundtrack track (and mute the clip) so it can be cut independently. */
detachAudio: () => void;
@@ -189,10 +197,11 @@ let clipboard: ClipboardItem[] = [];
export const useEditor = create<EditorState>((set, get) => {
const snapshot = (): DocSnapshot => {
- const { clips, audioClips, overlays, subtitles } = get();
+ const { clips, audioClips, overlayClips, overlays, subtitles } = get();
return {
clips: clips.map((c) => ({ ...c })),
audioClips: audioClips.map((c) => ({ ...c })),
+ overlayClips: overlayClips.map((c) => ({ ...c })),
overlays: overlays.map((o) => ({ ...o })),
subtitles: {
...subtitles,
@@ -232,6 +241,7 @@ export const useEditor = create<EditorState>((set, get) => {
assets: [],
clips: [],
audioClips: [],
+ overlayClips: [],
overlays: [],
aspect: "9:16",
selection: null,
@@ -262,6 +272,7 @@ export const useEditor = create<EditorState>((set, get) => {
assets: [],
clips: [],
audioClips: [],
+ overlayClips: [],
overlays: [],
aspect: "9:16",
selection: null,
@@ -286,6 +297,7 @@ export const useEditor = create<EditorState>((set, get) => {
assets,
clips: doc.clips,
audioClips: doc.audioClips,
+ overlayClips: doc.overlayClips ?? [],
overlays: doc.overlays,
aspect: doc.aspect ?? "9:16",
// View state lives in IndexedDB; doc.ui covers projects saved
@@ -544,6 +556,39 @@ export const useEditor = create<EditorState>((set, get) => {
set({ clips: next });
},
+ addOverlayClipFromAsset: (assetId, start) => {
+ const asset = get().assets.find((a) => a.id === assetId);
+ if (!asset || asset.type !== "video") return;
+ push();
+ // Land on the next free track above the highest existing overlay.
+ const track = Math.max(0, ...get().overlayClips.map((c) => c.track)) + 1;
+ const clip: OverlayClip = {
+ id: uid(),
+ assetId,
+ track,
+ start: Math.max(0, start ?? get().currentTime),
+ in: 0,
+ out: asset.duration,
+ muted: false,
+ // Full-frame by default: covers the base ("topmost plays"). A layout
+ // preset in the inspector regions it (split half / corner PiP).
+ };
+ set((s) => ({
+ overlayClips: [...s.overlayClips, clip],
+ ...sole({ kind: "overlayClip", id: clip.id }),
+ }));
+ },
+
+ updateOverlayClip: (id, patch) => {
+ push();
+ get().updateOverlayClipTransient(id, patch);
+ },
+
+ updateOverlayClipTransient: (id, patch) =>
+ set((s) => ({
+ overlayClips: s.overlayClips.map((c) => (c.id === id ? { ...c, ...patch } : c)),
+ })),
+
detachAudio: () => {
const { clips, assets, selection } = get();
if (selection?.kind !== "clip") return;
@@ -630,6 +675,7 @@ export const useEditor = create<EditorState>((set, get) => {
);
const clipIds = idsOf("clip");
const audioIds = idsOf("audio");
+ const overlayClipIds = idsOf("overlayClip");
const textIds = idsOf("text");
const cueIds = idsOf("cue");
// Removing video clips shortens the track; ripple later titles/captions
@@ -640,6 +686,7 @@ export const useEditor = create<EditorState>((set, get) => {
set((s) => ({
clips: s.clips.filter((c) => !clipIds.has(c.id)),
audioClips: s.audioClips.filter((c) => !audioIds.has(c.id)),
+ overlayClips: s.overlayClips.filter((c) => !overlayClipIds.has(c.id)),
overlays: s.overlays.filter((o) => !textIds.has(o.id)).map(bump),
subtitles: {
...s.subtitles,
@@ -806,16 +853,20 @@ export const useEditor = create<EditorState>((set, get) => {
if (get().projectId !== projectId) return;
push();
if (res.ok && Array.isArray(body.texts) && body.texts.length === cues.length) {
- const texts = body.texts;
+ // Key the rewrite to the cue ids it was generated from, so an edit
+ // that reordered/split cues mid-request can't apply text by a stale
+ // index onto the wrong cue.
+ const byId = new Map(cues.map((c, i) => [c.id, body.texts![i]]));
set((cur) => ({
subtitles: {
...cur.subtitles,
style,
// Rewriting the text drops per-word timings (they no longer match),
// but the cue's own start/end are untouched.
- cues: cur.subtitles.cues.map((c, i) =>
- texts[i] && texts[i] !== c.text ? { ...c, text: texts[i], words: undefined } : c
- ),
+ cues: cur.subtitles.cues.map((c) => {
+ const t = byId.get(c.id);
+ return t && t !== c.text ? { ...c, text: t, words: undefined } : c;
+ }),
},
subtitleStatus: "ready",
}));
@@ -1078,6 +1129,7 @@ useEditor.subscribe((s, prev) => {
if (
s.clips !== prev.clips ||
s.audioClips !== prev.audioClips ||
+ s.overlayClips !== prev.overlayClips ||
s.overlays !== prev.overlays ||
s.subtitles !== prev.subtitles
)
@@ -1090,6 +1142,7 @@ export function serializeDoc(s: {
assets: MediaAsset[];
clips: VideoClip[];
audioClips: AudioClip[];
+ overlayClips: OverlayClip[];
overlays: TextOverlay[];
aspect: Aspect;
publish: { caption: string; tags: string; soundTitle: string; handle: string };
@@ -1112,6 +1165,7 @@ export function serializeDoc(s: {
assets,
clips: s.clips,
audioClips: s.audioClips,
+ overlayClips: s.overlayClips,
overlays: s.overlays,
aspect: s.aspect,
subtitles: s.subtitles,
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index df172619..f263b8be 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -36,6 +36,59 @@ export interface MediaAsset extends StoredAsset {
peaks?: number[];
}
+/**
+ * A layout region inside the output frame, as fractions with a top-left origin
+ * (x,y = top-left corner; w,h = size). Absent on a clip means it fills the
+ * whole frame. Regions let two videos share one frame — split top/bottom or
+ * side by side — or place one small (picture-in-picture).
+ */
+export interface FrameRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+export const FULL_FRAME: FrameRect = { x: 0, y: 0, w: 1, h: 1 };
+
+/** A clip's effective region: its own `frame`, or the full frame if unset. */
+export function rectOf(clip: { frame?: FrameRect }): FrameRect {
+ return clip.frame ?? FULL_FRAME;
+}
+
+/** Whether a region covers the whole frame (so it needs no special layout). */
+export function isFullRect(r: FrameRect): boolean {
+ return r.x <= 0.001 && r.y <= 0.001 && r.w >= 0.999 && r.h >= 0.999;
+}
+
+/** One-click layouts for arranging a video layer in the frame. `fit` is the
+ * sensible default meeting for that shape: halves cover their region, a corner
+ * is contained so the whole picture shows. */
+export const LAYOUTS = {
+ full: { label: "Full", rect: FULL_FRAME, fit: "fit" as const },
+ top: { label: "Top", rect: { x: 0, y: 0, w: 1, h: 0.5 }, fit: "fill" as const },
+ bottom: { label: "Bottom", rect: { x: 0, y: 0.5, w: 1, h: 0.5 }, fit: "fill" as const },
+ left: { label: "Left", rect: { x: 0, y: 0, w: 0.5, h: 1 }, fit: "fill" as const },
+ right: { label: "Right", rect: { x: 0.5, y: 0, w: 0.5, h: 1 }, fit: "fill" as const },
+ corner: { label: "PiP", rect: { x: 0.62, y: 0.62, w: 0.34, h: 0.34 }, fit: "fit" as const },
+} as const;
+
+export type LayoutId = keyof typeof LAYOUTS;
+
+/** A short human label for a region: a named layout if it matches one, else
+ * "Full" or "PiP". Used on timeline bars and the inspector. */
+export function regionLabel(r: FrameRect): string {
+ if (isFullRect(r)) return LAYOUTS.full.label;
+ for (const key of ["top", "bottom", "left", "right"] as const) {
+ const q = LAYOUTS[key].rect;
+ const near = (a: number, b: number) => Math.abs(a - b) < 0.02;
+ if (near(q.x, r.x) && near(q.y, r.y) && near(q.w, r.w) && near(q.h, r.h)) {
+ return LAYOUTS[key].label;
+ }
+ }
+ return "PiP";
+}
+
/** A clip on the magnetic video track. Order in the array is timeline order. */
export interface VideoClip {
id: string;
@@ -43,9 +96,12 @@ export interface VideoClip {
in: number; // trim-in inside the source, seconds
out: number; // trim-out inside the source, seconds
muted: boolean;
- /** How the clip meets the 9:16 frame: letterboxed ("fit", default) or
- * scaled to cover it ("fill", cropping the overflow). */
+ /** 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). */
+ frame?: FrameRect;
/** Crop-window pan in fill mode, -1..1 per axis (0 = centered): which part
* of the oversized video stays visible. */
panX?: number;
@@ -56,6 +112,32 @@ export interface VideoClip {
/** Cross-dissolve into the next clip, in timeline seconds (absent/0 = hard
* cut). The two clips overlap by this much, so the cut shortens by it. */
transition?: number;
+ /** Hidden clips stay on the timeline (grayed) but render as black — excluded
+ * from the played/exported picture without disturbing the layout. */
+ hidden?: boolean;
+}
+
+/**
+ * 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).
+ */
+export interface OverlayClip {
+ id: string;
+ assetId: string;
+ track: number; // 1-based; higher = closer to the top
+ start: number; // timeline position, seconds
+ in: number;
+ out: number;
+ muted: boolean;
+ hidden?: boolean;
+ /** The region of the frame this overlay occupies; absent = full frame. */
+ frame?: FrameRect;
+ /** How the video meets its region: cover-and-crop ("fill") or contain ("fit"). */
+ fit?: "fit" | "fill";
+ speed?: number;
}
/** Speed limits — matches the Inspector control and export atempo range. */
@@ -74,6 +156,8 @@ export interface AudioClip {
volume: number; // 0..1.5
fadeIn?: number; // seconds, ramp up from the clip start
fadeOut?: number; // seconds, ramp down into the clip end
+ /** Muted from the final mix but kept on the timeline (grayed). */
+ hidden?: boolean;
/** Playback rate, default 1 (absent). Set only when audio was detached from
* a sped-up video clip, so it stays the same length and in sync with the
* (now muted) picture. The timeline footprint is (out-in)/speed. */
@@ -153,6 +237,7 @@ export const emptySubtitles = (): SubtitlesBlock => ({
export type Selection =
| { kind: "clip"; id: string }
| { kind: "audio"; id: string }
+ | { kind: "overlayClip"; id: string }
| { kind: "text"; id: string }
| { kind: "cue"; id: string }
| null;
@@ -176,6 +261,8 @@ export interface ProjectDoc {
assets: StoredAsset[];
clips: VideoClip[];
audioClips: AudioClip[];
+ /** Upper video tracks composited over the base track (absent in older docs). */
+ overlayClips?: OverlayClip[];
overlays: TextOverlay[];
/** Output frame; absent in older projects (which are all 9:16). */
aspect?: Aspect;
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 2356b5f1..ff49af18 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -102,6 +102,7 @@ export const projectsApi = {
assets: Array.isArray(body.assets) ? body.assets : existing.assets,
clips: Array.isArray(body.clips) ? body.clips : existing.clips,
audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,
+ overlayClips: Array.isArray(body.overlayClips) ? body.overlayClips : existing.overlayClips,
overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
subtitles:
body.subtitles && typeof body.subtitles === "object"
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index c23853ba..351a847d 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -23,13 +23,30 @@ export interface ExportSpec {
in: number;
out: number;
muted: boolean;
- /** "fit" letterboxes (default); "fill" covers the frame and crops. */
+ /** "fit" letterboxes (default); "fill" covers the region and crops. */
fit?: "fit" | "fill";
- panX?: number; // crop-window pan -1..1 (fill mode)
+ panX?: number; // crop-window pan -1..1 (fill mode, full frame)
panY?: number;
+ /** Region of the frame this clip fills; absent = full frame. */
+ frame?: { x: number; y: number; w: number; h: number };
speed?: number; // playback rate, default 1
/** Cross-dissolve into the next clip, in timeline seconds (overlap). */
transition?: number;
+ /** Hidden clips keep their slot but render black + silent. */
+ hidden?: boolean;
+ }[];
+ /** Upper video tracks composited over the base, bottom track first. */
+ overlayVideos?: {
+ file: string;
+ in: number;
+ out: number;
+ start: number; // timeline position, seconds
+ track: number;
+ /** Region of the frame this overlay fills; absent = full frame. */
+ frame?: { x: number; y: number; w: number; h: number };
+ fit?: "fit" | "fill";
+ muted: boolean;
+ speed?: number;
}[];
audio: {
file: string;
@@ -48,6 +65,9 @@ export interface ExportSpec {
export interface Job {
id: string;
projectId: string;
+ /** "preview" is the internal hover-proxy render; only "export" jobs are
+ * surfaced to the client for reconnect/download. */
+ target: "export" | "preview";
status: "running" | "done" | "error";
progress: number; // 0..1
error?: string;
@@ -70,7 +90,7 @@ export function getJob(id: string) {
* reopened (or reloaded) can reconnect to an export still in flight. */
export function listJobsForProject(projectId: string) {
return [...jobs.values()]
- .filter((j) => j.projectId === projectId)
+ .filter((j) => j.projectId === projectId && j.target !== "preview")
.map((j) => ({
id: j.id,
status: j.status,
@@ -100,10 +120,12 @@ export async function createJob(form: FormData): Promise<Job> {
assertLocalRuntime();
const spec = JSON.parse(String(form.get("spec"))) as ExportSpec;
const id = crypto.randomUUID().slice(0, 12);
+ const preview = spec.target === "preview";
if (runningCount() >= MAX_RUNNING) {
const job: Job = {
id,
projectId: spec.projectId,
+ target: preview ? "preview" : "export",
status: "error",
progress: 0,
tmpDir: "",
@@ -116,25 +138,28 @@ export async function createJob(form: FormData): Promise<Job> {
retire(job);
return job;
}
- const preview = spec.target === "preview";
- const outDir = preview ? projectDir(spec.projectId) : exportsDir(spec.projectId);
// Include the unique job id so two exports in the same second can't collide
// on the same output path (which would clobber the first render).
const outName = preview ? "preview.mp4" : `export-${stamp()}-${id}.mp4`;
+ const outPath = path.join(
+ preview ? projectDir(spec.projectId) : exportsDir(spec.projectId),
+ outName
+ );
const job: Job = {
id,
projectId: spec.projectId,
+ target: preview ? "preview" : "export",
status: "running",
progress: 0,
tmpDir: "",
- outPath: path.join(outDir, outName),
+ outPath,
outName,
log: [],
};
jobs.set(id, job); // reserve the concurrency slot before the first await
try {
- await mkdir(outDir, { recursive: true });
+ await mkdir(path.dirname(outPath), { recursive: true });
job.tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-"));
if (!(await readProject(spec.projectId))) throw new Error("Project not found.");
// Overlay PNGs are rendered in the browser and uploaded with the spec.
@@ -174,15 +199,37 @@ function clipRate(c: ExportSpec["clips"][number]) {
return c.speed && c.speed > 0 ? c.speed : 1;
}
+/** A clip's frame region in even pixels, or null when it fills the whole frame
+ * (the common case, which keeps the plain full-frame filter path). */
+function regionPx(
+ frame: { x: number; y: number; w: number; h: number } | undefined,
+ W: number,
+ H: number
+) {
+ if (!frame) return null;
+ const even = (n: number) => 2 * Math.round(n / 2);
+ const rw = Math.min(W, Math.max(2, even(frame.w * W)));
+ const rh = Math.min(H, Math.max(2, even(frame.h * H)));
+ // Clamp the origin so rx+rw ≤ W and ry+rh ≤ H — independent even-rounding can
+ // otherwise push an edge-touching region a pixel past the frame, which makes
+ // the pad filter reject the input ("not within the padded area") and aborts
+ // the whole export.
+ const rx = Math.max(0, Math.min(even(frame.x * W), W - rw));
+ const ry = Math.max(0, Math.min(even(frame.y * H), H - rh));
+ if (rx <= 0 && ry <= 0 && rw >= W && rh >= H) return null;
+ return { rx, ry, rw, rh };
+}
+
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 ?? [];
// One ffmpeg input per distinct media file (from the project folder),
// plus one per uploaded overlay PNG.
const mediaFiles = [
- ...new Set([...spec.clips, ...spec.audio].map((c) => c.file)),
+ ...new Set([...spec.clips, ...spec.audio, ...overlayVideos].map((c) => c.file)),
];
const audioPresence = new Map<string, boolean>();
const videoPresence = new Map<string, boolean>();
@@ -225,27 +272,41 @@ async function runExport(job: Job, spec: ExportSpec) {
const idx = inputIndex.get(c.file)!;
const speed = clipRate(c);
const dur = clipDur(c);
- if (videoPresence.get(c.file)) {
- const frame =
- c.fit === "fill"
- ? // Cover the frame, then crop; the pan chooses the visible window.
- `scale=${W}:${H}:force_original_aspect_ratio=increase,` +
- `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`;
+ if (videoPresence.get(c.file) && !c.hidden) {
+ 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.
+ const { rx, ry, rw, rh } = region;
+ frame =
+ c.fit === "fill"
+ ? `scale=${rw}:${rh}:force_original_aspect_ratio=increase,crop=${rw}:${rh},` +
+ `pad=${W}:${H}:${rx}:${ry}:color=black`
+ : `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`;
+ } else {
+ frame =
+ c.fit === "fill"
+ ? // Cover the frame, then crop; the pan chooses the visible window.
+ `scale=${W}:${H}:force_original_aspect_ratio=increase,` +
+ `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`;
+ }
// 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}]`
);
} else {
- // No video stream in this file: keep the cut alive with black frames.
+ // No video stream, or a hidden clip: keep the slot as black frames.
filters.push(
`color=c=black:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=yuv420p[v${j}]`
);
}
- if (!c.muted && audioPresence.get(c.file)) {
+ if (!c.muted && !c.hidden && audioPresence.get(c.file)) {
const tempo = speed !== 1 ? `${atempoChain(speed)},` : "";
filters.push(
`[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` +
@@ -286,8 +347,65 @@ async function runExport(job: Job, spec: ExportSpec) {
aAcc = aOut;
}
- // Burn in text overlays, each windowed to its timeline range.
+ // 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;
+ 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}`;
+ filters.push(
+ `[${vLabel}][${seg}]overlay=${pos}:enable='between(t,${num(oc.start)},${num(end)})':eof_action=pass[${next}]`
+ );
+ 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);
+ }
+ });
+
+ // Burn in text overlays, each windowed to its timeline range.
spec.overlays.forEach((o, k) => {
const idx = inputIndex.get(o.file)!;
const next = `vov${k}`;
@@ -323,10 +441,11 @@ async function runExport(job: Job, spec: ExportSpec) {
});
let aLabel = aAcc;
- if (soundLabels.length > 0) {
- const mixIn = [aAcc, ...soundLabels].map((l) => `[${l}]`).join("");
+ const extraSound = [...soundLabels, ...overlaySoundLabels];
+ if (extraSound.length > 0) {
+ const mixIn = [aAcc, ...extraSound].map((l) => `[${l}]`).join("");
filters.push(
- `${mixIn}amix=inputs=${soundLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`
+ `${mixIn}amix=inputs=${extraSound.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`
);
aLabel = "amix";
}