Skip to content

Open source CapCut alternative.

TypeScript

feat(site): add whole-video fade in and out

David Lefd7b2605ee84
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index d98a9db5..1ec6c927 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -61,6 +61,8 @@ export function Editor({ projectId }: { projectId: string }) {
overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
+ fadeIn: s.fadeIn,
+ fadeOut: s.fadeOut,
},
s.aspect
);
@@ -145,6 +147,8 @@ export function Editor({ projectId }: { projectId: string }) {
s.overlays !== (last.overlays as unknown) ||
s.subtitles !== (last.subtitles as unknown) ||
s.aspect !== last.aspect ||
+ s.fadeIn !== (last.fadeIn ?? 0) ||
+ s.fadeOut !== (last.fadeOut ?? 0) ||
s.assets.length !== last.assets?.length ||
s.publish.caption !== last.publish?.caption ||
s.publish.tags !== last.publish?.tags ||
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index eac11243..8faa7822 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -65,6 +65,8 @@ export function ExportDialog() {
overlayClips: s.overlayClips,
overlays: s.overlays,
subtitles: s.subtitles,
+ fadeIn: s.fadeIn,
+ fadeOut: s.fadeOut,
}, settings);
};
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 4e364dc6..5550560f 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -239,12 +239,18 @@ function LayoutButtons({
function ClipPanel({ clip }: { clip: VideoClip }) {
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const updateClip = useEditor((s) => s.updateClip);
- // A cross-dissolve dissolves this clip into the next one, so only offer it
- // when there is a next clip on the track.
+ // A transition hands this clip into the next one, so only offer it when
+ // there is a next clip on the track.
const hasNext = useEditor((s) => {
const i = s.clips.findIndex((c) => c.id === clip.id);
return i >= 0 && i < s.clips.length - 1;
});
+ // The whole-video fades are project-level but live on the clips that show
+ // them: fade in on the first clip's panel, fade out on the last clip's.
+ const isFirst = useEditor((s) => s.clips[0]?.id === clip.id);
+ const isLast = useEditor((s) => s.clips[s.clips.length - 1]?.id === clip.id);
+ const fadeIn = useEditor((s) => s.fadeIn);
+ const fadeOut = useEditor((s) => s.fadeOut);
const [speedDraft, setSpeedDraft] = useState<number | null>(null);
const [xfadeDraft, setXfadeDraft] = useState<number | null>(null);
const speed = speedDraft ?? clip.speed ?? 1;
@@ -276,6 +282,36 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
/>
<Value className="w-9 text-right text-muted-foreground">{speed.toFixed(2)}×</Value>
</Row>
+ {isFirst && (
+ <Row label="Fade in">
+ <Slider
+ className="project-fade-in data-horizontal:w-24"
+ min={0}
+ max={TRANSITION_MAX}
+ step={0.1}
+ value={fadeIn}
+ onValueChange={(v) => useEditor.getState().setProjectFade({ fadeIn: Number(v) })}
+ />
+ <Value className="w-9 text-right text-muted-foreground">
+ {fadeIn < 0.05 ? "Off" : `${fadeIn.toFixed(1)}s`}
+ </Value>
+ </Row>
+ )}
+ {isLast && (
+ <Row label="Fade out">
+ <Slider
+ className="project-fade-out data-horizontal:w-24"
+ min={0}
+ max={TRANSITION_MAX}
+ step={0.1}
+ value={fadeOut}
+ onValueChange={(v) => useEditor.getState().setProjectFade({ fadeOut: Number(v) })}
+ />
+ <Value className="w-9 text-right text-muted-foreground">
+ {fadeOut < 0.05 ? "Off" : `${fadeOut.toFixed(1)}s`}
+ </Value>
+ </Row>
+ )}
{hasNext && (
<>
<Row label="Transition">
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index dcd78e4f..284d4bf8 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -305,6 +305,28 @@ class Engine {
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
+ /** Whole-video fade gain at time `t`: ramps 0→1 over the project fade-in and
+ * 1→0 over the fade-out at the end of the cut. 1 when neither applies. */
+ private projectFadeGain(t: number, total: number) {
+ const s = useEditor.getState();
+ let g = 1;
+ if (s.fadeIn > 0 && t < s.fadeIn) g = Math.min(g, Math.max(0, t / s.fadeIn));
+ if (s.fadeOut > 0 && t > total - s.fadeOut)
+ g = Math.min(g, Math.max(0, (total - t) / s.fadeOut));
+ return Math.min(1, g);
+ }
+
+ /** The picture side of the project fade: a black veil over the whole frame
+ * (everything drawn this tick — base, tracks, at any time), matching the
+ * export's fade on the final composite. */
+ private drawProjectFade(gain: number) {
+ if (gain >= 1) return;
+ const ctx = this.canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.fillStyle = `rgba(0,0,0,${(1 - Math.max(0, gain)).toFixed(3)})`;
+ 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
@@ -353,7 +375,7 @@ class Engine {
}
}
- private syncSoundtrack(t: number, playing: boolean) {
+ private syncSoundtrack(t: number, playing: boolean, fadeGain = 1) {
const s = useEditor.getState();
const live = new Set<string>();
for (const a of s.audioClips) {
@@ -379,7 +401,7 @@ class Engine {
let gain = 1;
if (fi > 0 && rel < fi) gain *= rel / fi;
if (fo > 0 && rel > len - fo) gain *= Math.max(0, (len - rel) / fo);
- el.volume = Math.max(0, Math.min(1, a.volume * gain));
+ el.volume = Math.max(0, Math.min(1, a.volume * gain * fadeGain));
if (el.playbackRate !== speed) el.playbackRate = speed;
const expected = a.in + rel * speed;
if (Math.abs(el.currentTime - expected) > 0.25) el.currentTime = expected;
@@ -456,6 +478,7 @@ class Engine {
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.drawProjectFade(this.projectFadeGain(pt, total));
this.cleanupOverlays(active);
this.syncSoundtrack(t, false);
return;
@@ -517,6 +540,7 @@ class Engine {
useEditor.setState({ playing: false, currentTime: total });
el.pause();
this.drawOverlays(t, true, "above", active);
+ this.drawProjectFade(this.projectFadeGain(total, total));
this.cleanupOverlays(active);
this.syncSoundtrack(total, false);
return;
@@ -534,6 +558,7 @@ class Engine {
if (t >= total - 0.001) {
useEditor.setState({ playing: false, currentTime: total });
this.drawOverlays(t, true, "above", active);
+ this.drawProjectFade(this.projectFadeGain(total, total));
this.cleanupOverlays(active);
this.syncSoundtrack(total, false);
return;
@@ -541,9 +566,17 @@ class Engine {
}
this.drawOverlays(t, true, "above", 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);
+ if (fadeGain < 1 && span) {
+ const mel = this.videoEls.get(span.clip.id);
+ if (mel) mel.volume = Math.min(mel.volume, fadeGain);
+ }
+ this.drawProjectFade(fadeGain);
this.cleanupOverlays(active);
useEditor.setState({ currentTime: t });
- this.syncSoundtrack(t, true);
+ this.syncSoundtrack(t, true, fadeGain);
}
}
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index c4cf5df2..8a5ffa76 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -53,6 +53,8 @@ export function buildAiContext(opts?: { fullCues?: boolean }) {
duration: r(duration),
aspect: s.aspect,
frame: s.aspect === "9:16" ? "1080x1920" : "1920x1080",
+ ...(s.fadeIn > 0 ? { fadeIn: r(s.fadeIn) } : {}),
+ ...(s.fadeOut > 0 ? { fadeOut: r(s.fadeOut) } : {}),
},
playhead: r(s.currentTime),
skimmer: s.skimTime === null ? null : r(s.skimTime),
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 76307044..f4f42e73 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -374,6 +374,17 @@ export async function runAiTool(
return { aspect: a };
}
+ case "set_project_fade": {
+ if (!isNum(input.fadeIn) && !isNum(input.fadeOut))
+ throw new ToolError("Pass fadeIn and/or fadeOut seconds (0 clears).");
+ s.setProjectFade({
+ ...(isNum(input.fadeIn) ? { fadeIn: input.fadeIn } : {}),
+ ...(isNum(input.fadeOut) ? { fadeOut: input.fadeOut } : {}),
+ });
+ const after = useEditor.getState();
+ return { fadeIn: after.fadeIn, fadeOut: after.fadeOut };
+ }
+
case "set_project_name": {
if (typeof input.name !== "string" || !input.name.trim())
throw new ToolError("name is required.");
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index a5f85ddf..814b286e 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -108,6 +108,10 @@ export interface ExportDoc {
overlayClips: OverlayClip[];
overlays: TextOverlay[];
subtitles: SubtitlesBlock;
+ /** Whole-video fades (seconds): in from black / out to black on the final
+ * composite. */
+ fadeIn?: number;
+ fadeOut?: number;
}
export interface ExportHandle {
@@ -232,7 +236,18 @@ async function buildExportForm(
form.append(
"spec",
- JSON.stringify({ projectId, target, ...settings, duration, clips, audio, overlayVideos, overlays })
+ JSON.stringify({
+ projectId,
+ target,
+ ...settings,
+ duration,
+ fadeIn: doc.fadeIn ?? 0,
+ fadeOut: doc.fadeOut ?? 0,
+ clips,
+ audio,
+ overlayVideos,
+ overlays,
+ })
);
return form;
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index e2a2cb5d..3430e1c2 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -89,6 +89,10 @@ interface EditorState {
overlays: TextOverlay[];
/** Output frame (9:16 vertical or 16:9 widescreen), persisted per project. */
aspect: Aspect;
+ /** Whole-video fades, seconds (0 = off): in from black at the start, out to
+ * black at the end of the cut. Applied to the final picture and mix. */
+ fadeIn: number;
+ fadeOut: number;
selection: Selection;
/** Everything selected, including `selection` (the primary that drives the
* inspector). Bulk actions — delete, copy — act on this whole set. */
@@ -118,6 +122,9 @@ interface EditorState {
setSaveState: (s: SaveState) => void;
setAspect: (a: Aspect) => void;
+ /** Set the whole-video fade in/out (seconds; 0 clears). Like the aspect,
+ * project-level settings sit outside the undo history. */
+ setProjectFade: (patch: { fadeIn?: number; fadeOut?: number }) => void;
addAsset: (asset: MediaAsset) => void;
updateAsset: (id: string, patch: Partial<MediaAsset>) => void;
/** Remove a project asset and any clips/audio that reference it. */
@@ -293,6 +300,8 @@ export const useEditor = create<EditorState>((set, get) => {
overlayClips: [],
overlays: [],
aspect: "9:16",
+ fadeIn: 0,
+ fadeOut: 0,
selection: null,
multiSelection: [],
currentTime: 0,
@@ -324,6 +333,8 @@ export const useEditor = create<EditorState>((set, get) => {
overlayClips: [],
overlays: [],
aspect: "9:16",
+ fadeIn: 0,
+ fadeOut: 0,
selection: null,
multiSelection: [],
currentTime: 0,
@@ -349,6 +360,8 @@ export const useEditor = create<EditorState>((set, get) => {
overlayClips: doc.overlayClips ?? [],
overlays: doc.overlays,
aspect: doc.aspect ?? "9:16",
+ fadeIn: doc.fadeIn ?? 0,
+ fadeOut: doc.fadeOut ?? 0,
// View state lives in IndexedDB; doc.ui covers projects saved
// before the move.
pxPerSec: Math.max(12, Math.min(800, ui.pxPerSec ?? doc.ui?.pxPerSec ?? 60)),
@@ -394,6 +407,14 @@ export const useEditor = create<EditorState>((set, get) => {
},
setAspect: (a) => set({ aspect: a }),
+ setProjectFade: (patch) => {
+ const clamp = (v: number | undefined) =>
+ v === undefined ? undefined : Math.max(0, Math.min(TRANSITION_MAX, v));
+ set((s) => ({
+ fadeIn: clamp(patch.fadeIn) ?? s.fadeIn,
+ fadeOut: clamp(patch.fadeOut) ?? s.fadeOut,
+ }));
+ },
addAsset: (asset) =>
set((s) => {
@@ -1478,6 +1499,8 @@ export function serializeDoc(s: {
overlayClips: OverlayClip[];
overlays: TextOverlay[];
aspect: Aspect;
+ fadeIn: number;
+ fadeOut: number;
publish: { caption: string; tags: string; soundTitle: string; handle: string };
notes: { text: string; publishedAt: string; links: string[] };
subtitles: SubtitlesBlock;
@@ -1501,6 +1524,8 @@ export function serializeDoc(s: {
overlayClips: s.overlayClips,
overlays: s.overlays,
aspect: s.aspect,
+ ...(s.fadeIn > 0 ? { fadeIn: s.fadeIn } : {}),
+ ...(s.fadeOut > 0 ? { fadeOut: s.fadeOut } : {}),
subtitles: s.subtitles,
publish: { ...s.publish },
notes: { ...s.notes, links: [...s.notes.links] },
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 11589132..f9a3d428 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -358,6 +358,11 @@ export interface ProjectDoc {
overlays: TextOverlay[];
/** Output frame; absent in older projects (which are all 9:16). */
aspect?: Aspect;
+ /** Whole-video fades, seconds: in from black at the start, out to black at
+ * the end. Applied to the final picture and mix (titles, captions, and
+ * soundtrack fade together), so they survive clip reordering. */
+ fadeIn?: number;
+ fadeOut?: number;
/** Auto-generated (then hand-edited) subtitles. */
subtitles?: SubtitlesBlock;
/** Legacy per-project view metadata — view state now lives in IndexedDB;
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 8be71283..7c7c9be8 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -264,6 +264,12 @@ export const AI_TOOLS: AiToolDef[] = [
"Switch the project's output frame: '9:16' vertical (1080×1920, TikTok/Reels/Shorts) or '16:9' widescreen (1920×1080, YouTube).",
inputSchema: obj({ aspect: { type: "string", enum: ["9:16", "16:9"], description: "Output aspect" } }, ["aspect"]),
},
+ {
+ name: "set_project_fade",
+ description:
+ "Set the whole video's fade in from black and/or fade out to black, in seconds (0 clears, max 2). Applied to the final picture and mix at the start/end of the cut, independent of which clip sits there.",
+ inputSchema: obj({ fadeIn: num("Fade-in seconds (omit to keep)"), fadeOut: num("Fade-out seconds (omit to keep)") }),
+ },
{
name: "set_project_name",
description: "Rename the current project.",
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 548941f9..e851093b 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -18,6 +18,10 @@ export interface ExportSpec {
crf: number;
preset: string;
duration: number;
+ /** Whole-video fades, seconds: in from black / out to black, applied to the
+ * final composite and mix after all overlays and soundtrack. */
+ fadeIn?: number;
+ fadeOut?: number;
clips: {
file: string;
in: number;
@@ -612,6 +616,24 @@ async function runExport(job: Job, spec: ExportSpec) {
aLabel = "amix";
}
+ // Whole-video fades on the final composite and mix, so titles, captions,
+ // overlays, and soundtrack all fade together.
+ const fadeIn = Math.max(0, Math.min(spec.fadeIn ?? 0, spec.duration / 2));
+ const fadeOut = Math.max(0, Math.min(spec.fadeOut ?? 0, spec.duration / 2));
+ if (fadeIn > 0.01 || fadeOut > 0.01) {
+ const win = (f: string) =>
+ [
+ ...(fadeIn > 0.01 ? [`${f}=t=in:st=0:d=${num(fadeIn)}`] : []),
+ ...(fadeOut > 0.01
+ ? [`${f}=t=out:st=${num(Math.max(0, spec.duration - fadeOut))}:d=${num(fadeOut)}`]
+ : []),
+ ].join(",");
+ filters.push(`[${vLabel}]${win("fade")}[vfinal]`);
+ vLabel = "vfinal";
+ filters.push(`[${aLabel}]${win("afade")}[afinal]`);
+ aLabel = "afinal";
+ }
+
const enc = await h264Encoder();
const videoCodecArgs =
enc === "libx264"