Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): transitions between clips on every video track [rebuild]

David Le2882295fe4fa
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 00493b3d..7cea0c7e 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -286,14 +286,12 @@ 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 transition hands this clip into the next one, so only offer it when
- // there is a next clip on track 0 — layer clips share the sorted array
- // but sit outside the sequence, so position checks read track 0 only.
- const hasNext = useEditor((s) => {
- const row = track0Clips(s.clips);
- const i = row.findIndex((c) => c.id === clip.id);
- return i >= 0 && i < row.length - 1;
- });
+ // A transition hands this clip into the next one on its own track — every
+ // track carries transitions — so offer it whenever a same-track clip
+ // follows this one.
+ const hasNext = useEditor((s) =>
+ s.clips.some((c) => c.track === clip.track && c.start > clip.start + 1e-6)
+ );
// 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) => track0Clips(s.clips)[0]?.id === clip.id);
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index b14138ba..233924fd 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -206,6 +206,14 @@ export function Timeline() {
);
const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);
+ // Per-upper-track spans: each track carries its own transitions, so its row
+ // needs the same overlap-aware geometry (insets, badges) as track 0's.
+ const overlayTrackSpans = useMemo(() => {
+ const m = new Map<number, ClipSpan[]>();
+ for (const c of overlayClips)
+ if (!m.has(c.track)) m.set(c.track, getClipSpans(clips, assets, c.track));
+ return m;
+ }, [overlayClips, clips, assets]);
const total = projectDuration({ clips, 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. While a trim/slide drag
@@ -958,25 +966,36 @@ export function Timeline() {
className="rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4)]"
/>
)}
- {overlayClips
- .filter((c) => c.track === track)
- .map((c) => (
- <OverlayClipView
- key={c.id}
- clip={c}
- asset={assets.find((x) => x.id === c.assetId)}
- pps={pps}
- selected={selKeys.has(`clip:${c.id}`)}
- drag={laneDrag?.kind === "overlayClip" && laneDrag.id === c.id ? laneDrag : null}
- parting={laneDrag?.kind === "overlayClip" && laneDrag.id !== c.id}
- onDrag={setLaneDrag}
- onSnap={setSnapX}
- resolveTarget={resolveDropTrack}
- onCrossMove={previewCross}
- onCrossDrop={onOverlayCrossDrop}
- onDragActive={setVideoDragging}
- />
- ))}
+ {(overlayTrackSpans.get(track) ?? []).map((span, i, tSpans) => (
+ <OverlayClipView
+ key={span.clip.id}
+ clip={span.clip}
+ asset={span.asset}
+ prevOverlap={tSpans[i - 1]?.transitionOut ?? 0}
+ overlap={span.transitionOut}
+ pps={pps}
+ selected={selKeys.has(`clip:${span.clip.id}`)}
+ drag={
+ laneDrag?.kind === "overlayClip" && laneDrag.id === span.clip.id
+ ? laneDrag
+ : null
+ }
+ parting={laneDrag?.kind === "overlayClip" && laneDrag.id !== span.clip.id}
+ onDrag={setLaneDrag}
+ onSnap={setSnapX}
+ resolveTarget={resolveDropTrack}
+ onCrossMove={previewCross}
+ onCrossDrop={onOverlayCrossDrop}
+ onDragActive={setVideoDragging}
+ />
+ ))}
+ {laneDrag?.kind !== "overlayClip" && (
+ <TransitionBadges
+ spans={overlayTrackSpans.get(track) ?? []}
+ pps={pps}
+ rowH={OVERLAY_H}
+ />
+ )}
{trackSlot({ kind: "track", track }, OVERLAY_H - 4)}
</div>
))}
@@ -1065,33 +1084,9 @@ export function Timeline() {
onDragActive={setVideoDragging}
/>
))}
- {/* Transition badge, floating in the gutter where the two clips
- meet (the overlap midpoint; a hard cut for edge styles),
- vertically centered on the clip row. */}
- {laneDrag?.kind !== "clip" &&
- spans.map((span, i) => {
- const d = span.clip.transition ?? 0;
- if (!spans[i + 1] || d <= 0) return null;
- const style = span.clip.transitionStyle ?? "crossfade";
- const Icon = TRANSITION_ICONS[style];
- return (
- <div
- key={`xf-${span.clip.id}`}
- // Above SELECTED_SHADOW's z-10: the badge marks the joint even
- // when a selected clip's ring runs under it.
- className="tl-xfade pointer-events-none absolute z-11 flex -translate-x-1/2 items-center justify-center rounded-full bg-[#0a84ff] text-white shadow-[0_0_0_2px_rgba(255,255,255,0.9)]"
- style={{
- left: (span.start + span.len - span.transitionOut / 2) * pps - CLIP_GAP / 2,
- top: 2 + (VIDEO_H - 4) / 2 - 8,
- width: 16,
- height: 16,
- }}
- title={`${TRANSITION_STYLE_LABELS[style]} ${d.toFixed(1)}s`}
- >
- <Icon className="size-2.5" />
- </div>
- );
- })}
+ {laneDrag?.kind !== "clip" && (
+ <TransitionBadges spans={spans} pps={pps} rowH={VIDEO_H} />
+ )}
</div>
)}
@@ -1547,6 +1542,47 @@ function Playhead({
);
}
+/** Transition badges for one track row, floating in the gutter where each
+ * pair meets (the overlap midpoint; a hard cut for edge styles), vertically
+ * centered on the row. Shared by track 0 and the upper tracks. */
+function TransitionBadges({
+ spans,
+ pps,
+ rowH,
+}: {
+ spans: ClipSpan[];
+ pps: number;
+ rowH: number;
+}) {
+ return (
+ <>
+ {spans.map((span, i) => {
+ const d = span.clip.transition ?? 0;
+ if (!spans[i + 1] || d <= 0) return null;
+ const style = span.clip.transitionStyle ?? "crossfade";
+ const Icon = TRANSITION_ICONS[style];
+ return (
+ <div
+ key={`xf-${span.clip.id}`}
+ // Above SELECTED_SHADOW's z-10: the badge marks the joint even
+ // when a selected clip's ring runs under it.
+ className="tl-xfade pointer-events-none absolute z-11 flex -translate-x-1/2 items-center justify-center rounded-full bg-[#0a84ff] text-white shadow-[0_0_0_2px_rgba(255,255,255,0.9)]"
+ style={{
+ left: (span.start + span.len - span.transitionOut / 2) * pps - CLIP_GAP / 2,
+ top: 2 + (rowH - 4) / 2 - 8,
+ width: 16,
+ height: 16,
+ }}
+ title={`${TRANSITION_STYLE_LABELS[style]} ${d.toFixed(1)}s`}
+ >
+ <Icon className="size-2.5" />
+ </div>
+ );
+ })}
+ </>
+ );
+}
+
function ClipView({
span,
prevOverlap,
@@ -2019,6 +2055,8 @@ function overlayLen(c: VideoClip) {
function OverlayClipView({
clip,
asset,
+ prevOverlap,
+ overlap,
pps,
selected,
drag,
@@ -2032,6 +2070,11 @@ function OverlayClipView({
}: {
clip: VideoClip;
asset: MediaAsset | undefined;
+ /** Cross-dissolve overlap of the previous same-track clip into this one —
+ * the room the incoming transition claims on this clip's left. */
+ prevOverlap: number;
+ /** This clip's own dissolve into the next same-track clip (its right). */
+ overlap: number;
pps: number;
selected: boolean;
/** This clip's live drag when it is the one being carried (ghost mode). */
@@ -2045,7 +2088,17 @@ function OverlayClipView({
onCrossDrop: (id: string, target: TrackTarget, start: number) => void;
onDragActive: (active: boolean) => void;
}) {
- const w = Math.max(10, overlayLen(clip) * pps);
+ // A cross-dissolve overlaps two clips; inset each box by half the overlap
+ // so the pair meets at the overlap midpoint with the same CLIP_GAP gutter
+ // as a hard cut — identical to the track-0 boxes.
+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
+ const leftXf = prevOverlap / 2;
+ const rightXf = overlap / 2;
+ const visStart = clip.start + leftXf;
+ const w = Math.max(10, Math.max(0, overlayLen(clip) - leftXf - rightXf) * pps);
+ // Frames start where the box does: skip the source seconds the left
+ // dissolve consumed so the filmstrip stays aligned under the inset edge.
+ const filmIn = clip.in + leftXf * speed;
// Same filmstrip as a track-0 clip so an overlay reads as a video, not a
// featureless bar — sampled across the clip's trimmed span.
@@ -2054,16 +2107,15 @@ function OverlayClipView({
const aspect = (asset.width ?? 16) / Math.max(1, asset.height ?? 9);
const imgW = Math.max(24, Math.round((OVERLAY_H - 4) * aspect));
const count = Math.min(120, Math.ceil(w / imgW));
- const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
return Array.from({ length: count }, (_, k) => {
- const at = clip.in + ((k * imgW + imgW / 2) / pps) * speed;
+ const at = filmIn + ((k * imgW + imgW / 2) / pps) * speed;
const idx = Math.min(
asset.thumbs!.length - 1,
Math.max(0, Math.floor(at / asset.thumbStep!))
);
return { src: asset.thumbs![idx], left: k * imgW, width: imgW };
});
- }, [asset, clip.in, clip.speed, w, pps]);
+ }, [asset, filmIn, speed, w, pps]);
if (!asset) return null;
@@ -2075,6 +2127,9 @@ function OverlayClipView({
rowH: OVERLAY_H,
laneCount: 0,
homeRow: 0,
+ // The box is inset by half the incoming dissolve; click-to-seek anchors
+ // on where the box is drawn, not the clip's footprint start.
+ visStart,
onDrag,
onSnap,
vertical: {
@@ -2098,7 +2153,8 @@ function OverlayClipView({
: parting && "transition-[left] duration-150 ease-out"
)}
style={{
- left: drag ? drag.ghostX : clip.start * pps,
+ // The ghost keeps the box's dissolve insets, offset to follow the pointer.
+ left: drag ? drag.ghostX + leftXf * pps : visStart * pps,
top: drag ? 2 + drag.ghostY : undefined,
width: Math.max(10, w - CLIP_GAP),
height: OVERLAY_H - 4,
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index 535fc82d..d459b55e 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -5,6 +5,70 @@ import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } fr
import { isFullRect, projectFadeSeconds, rectOf, TRANSITION_ZOOM } from "@/cut/lib/types";
import type { AudioClip, ClipSpan, FrameRect, MediaAsset, VideoClip } from "@/cut/lib/types";
+/** The alpha/zoom/gain ramps a transition puts on one upper-track clip at
+ * `t`. Cross styles blend the incoming clip in over the outgoing one (which
+ * keeps full alpha and its audio until its footprint ends); edge styles ramp
+ * a clip's own edge. On an upper track a fade ramps to transparent — the
+ * tracks beneath show through — matching the export's alpha fades. */
+function overlayTransitionFx(
+ span: ClipSpan,
+ prev: ClipSpan | undefined,
+ next: ClipSpan | undefined,
+ t: number
+): { alpha: number; zoom: number; gain: number } {
+ let alpha = 1;
+ let zoom = 1;
+ let gain = 1;
+ const style = span.clip.transitionStyle ?? "crossfade";
+ const prevStyle = prev?.clip.transitionStyle ?? "crossfade";
+ // Incoming side of the previous clip's cross transition: blend in.
+ if (prev && prev.transitionOut > 0) {
+ const rel = t - span.start;
+ if (rel < prev.transitionOut) {
+ const p = Math.max(0, rel / prev.transitionOut);
+ alpha = Math.min(alpha, p);
+ gain = Math.min(gain, p);
+ if (prevStyle === "crosszoom") zoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;
+ }
+ }
+ // Outgoing side of this clip's own cross zoom: the picture pushes in while
+ // the incoming clip settles back (it stays opaque — the blend is the
+ // incoming clip's alpha).
+ if (next && span.transitionOut > 0 && t >= next.start && style === "crosszoom") {
+ const p = Math.min(1, (t - next.start) / span.transitionOut);
+ zoom = 1 + (TRANSITION_ZOOM - 1) * p;
+ }
+ // Edge style on this clip's own tail (fade out / zoom in).
+ if (next && span.transitionOut === 0 && (style === "fadeout" || style === "zoomin")) {
+ const d = Math.min(span.clip.transition ?? 0, span.len);
+ const left = span.start + span.len - t;
+ if (d > 0 && left < d) {
+ const p = 1 - left / d;
+ if (style === "fadeout") {
+ alpha = Math.min(alpha, 1 - p);
+ gain = Math.min(gain, 1 - p);
+ } else {
+ zoom = 1 + (TRANSITION_ZOOM - 1) * p;
+ }
+ }
+ }
+ // Edge style the previous clip set on this clip's head (fade in / zoom out).
+ if (prev && prev.transitionOut === 0 && (prevStyle === "fadein" || prevStyle === "zoomout")) {
+ const d = Math.min(prev.clip.transition ?? 0, span.len);
+ const rel = t - span.start;
+ if (d > 0 && rel < d) {
+ const p = rel / d;
+ if (prevStyle === "fadein") {
+ alpha = Math.min(alpha, p);
+ gain = Math.min(gain, p);
+ } else {
+ zoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;
+ }
+ }
+ }
+ return { alpha, zoom, gain };
+}
+
/** The gain everything else drops to at time `t` while a ducking voiceover
* clip is audible: the lowest `duck` among the clips live then, 1 when none
* (mirrors the export's timeline-windowed volume filters). */
@@ -485,27 +549,30 @@ class Engine {
this.fillBlackVeil(1 - gain);
}
- /** Overlay clips live at time `t` — every track above 0, with their assets,
- * in z-order (further-back first). */
+ /** Overlay clips live at time `t` — every track above 0, with their assets
+ * and transition ramps, in draw order: further-back tracks first, and
+ * within a track earlier clips first, so a dissolving pair blends the
+ * incoming clip in over the outgoing one. */
private liveOverlays(t: number) {
const s = useEditor.getState();
- const live: { clip: VideoClip; asset: MediaAsset }[] = [];
- const clips = overlayLayers(s.clips).sort((a, b) => a.track - b.track);
- for (const c of clips) {
- if (c.hidden) continue;
- const asset = s.assets.find((a) => a.id === c.assetId);
- 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;
- live.push({ clip: c, asset });
+ const live: { clip: VideoClip; asset: MediaAsset; alpha: number; zoom: number; gain: number }[] = [];
+ const tracks = [...new Set(overlayLayers(s.clips).map((c) => c.track))].sort((a, b) => a - b);
+ for (const track of tracks) {
+ const spans = getClipSpans(s.clips, s.assets, track);
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ if (sp.clip.hidden) continue;
+ if (t < sp.start || t >= sp.start + sp.len) continue;
+ live.push({ clip: sp.clip, asset: sp.asset, ...overlayTransitionFx(sp, spans[i - 1], spans[i + 1], t) });
+ }
}
return live;
}
/** Seek/rate/play one overlay clip's element toward its frame at timeline
- * time `t` (the overlay counterpart of `prepare`). */
- private prepareOverlay(clip: VideoClip, asset: MediaAsset, t: number, play: boolean): MediaEl {
+ * time `t` (the overlay counterpart of `prepare`). `gain` carries the
+ * clip's transition ramp, so a fading picture takes its sound with it. */
+ private prepareOverlay(clip: VideoClip, asset: MediaAsset, t: number, play: boolean, gain = 1): MediaEl {
const el = this.overlayVideoFor(clip, asset);
if (isImageEl(el)) return el;
const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
@@ -520,7 +587,7 @@ class Engine {
el.muted = !!clip.muted;
el.volume = Math.max(
0,
- Math.min(1, (clip.volume ?? 1) * duckGainAt(useEditor.getState().audioClips, t))
+ Math.min(1, gain * (clip.volume ?? 1) * duckGainAt(useEditor.getState().audioClips, t))
);
if (play) {
if (el.paused && el.readyState >= 2) void el.play().catch(() => {});
@@ -534,9 +601,11 @@ class Engine {
* skim path's readiness check and the draw step share the same
* filter/sort/seek instead of repeating it per frame. */
private prepareOverlays(t: number, play: boolean) {
- return this.liveOverlays(t).map(({ clip, asset }) => ({
+ return this.liveOverlays(t).map(({ clip, asset, alpha, zoom, gain }) => ({
clip,
- el: this.prepareOverlay(clip, asset, t, play),
+ alpha,
+ zoom,
+ el: this.prepareOverlay(clip, asset, t, play, gain),
}));
}
@@ -549,14 +618,14 @@ class Engine {
t: number,
play: boolean,
active: Set<string>,
- prepared?: { clip: VideoClip; el: MediaEl }[]
+ prepared?: { clip: VideoClip; el: MediaEl; alpha: number; zoom: number }[]
) {
- for (const { clip, el } of prepared ?? this.prepareOverlays(t, play)) {
+ for (const { clip, el, alpha, zoom } of prepared ?? this.prepareOverlays(t, play)) {
active.add(clip.id);
if (!elReady(el)) continue;
const rect = rectOf(clip);
const cover = clip.fit === "fill" || (clip.fit == null && isFullRect(rect));
- this.drawIntoRect(el, rect, cover, 1);
+ this.drawIntoRect(el, rect, cover, alpha, zoom);
}
}
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 94ee2018..f0d790f7 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -183,8 +183,19 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
: {}),
})),
// Video layers composited over track 0 in track order (the topmost
- // full-frame clip covers the rest).
- overlayVideo: overlayLayers(s.clips).map((c) => ({ id: c.id, ...describeOverlayClip(c, assetById) })),
+ // full-frame clip covers the rest). Each track carries its own
+ // transitions, reported per clip like track 0's.
+ overlayVideo: [...new Set(overlayLayers(s.clips).map((c) => c.track))].flatMap((track) => {
+ const trackSpans = getClipSpans(s.clips, s.assets, track);
+ return trackSpans.map((sp, i) => ({
+ id: sp.clip.id,
+ ...describeOverlayClip(sp.clip, assetById),
+ ...(() => {
+ const t = transitionToNext(sp, i, trackSpans);
+ return t ? { transitionToNext: t } : {};
+ })(),
+ }));
+ }),
soundtrack: s.audioClips.map((a) => ({ id: a.id, ...describeAudio(a, assetById) })),
titles: s.overlays.map((o) => ({ id: o.id, ...describeOverlay(o) })),
subtitles: {
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 0945dc6d..c27fb524 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -1502,12 +1502,10 @@ export async function runAiTool(
case "set_transition": {
const clip = requireItem(s.clips, input.clipId, "video clip");
- // Transitions join the track-0 sequence; a layer clip has no next clip.
- if (clip.track !== 0)
- throw new ToolError("That clip is on an overlay track — transitions join timeline (track 0) clips.");
- const row = track0Clips(s.clips);
+ // A transition joins a clip to the next one on its own track.
+ const row = s.clips.filter((c) => c.track === clip.track);
if (row.findIndex((c) => c.id === clip.id) === row.length - 1)
- throw new ToolError("The last clip has no next clip to transition into.");
+ throw new ToolError("That is its track's last clip — nothing after it to transition into.");
if (!isNum(input.seconds)) throw new ToolError("seconds is required (0 clears the transition).");
let style: TransitionStyle | undefined;
if (input.style !== undefined) {
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index e9dd1c03..ac655926 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -245,24 +245,53 @@ async function buildExportForm(
clipEntries[i],
]);
- // Video tracks composited over track 0; hidden ones are dropped.
- const overlayVideos = overlayLayers(doc.clips)
- .filter((c) => !c.hidden && assetById.has(c.assetId) && c.start < duration)
- .map((c) => ({
- 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 what's below" branch fires — normalizing to "fit" defeated it.
- fit: c.fit,
- muted: c.muted,
- volume: c.volume,
- speed: c.speed,
- image: assetById.get(c.assetId)!.type === "image",
- }));
+ // Video tracks composited over track 0; hidden ones are dropped. Each
+ // track's transitions translate into per-clip head/tail ramps: on an upper
+ // track a fade is an alpha fade (transparent, so the tracks beneath show
+ // through), and a cross style blends the incoming clip in over the
+ // outgoing one — the incoming alpha-fades in for the overlap while the
+ // outgoing stays opaque underneath it.
+ const overlayTracks = [...new Set(overlayLayers(doc.clips).map((c) => c.track))];
+ const overlayVideos = overlayTracks.flatMap((track) => {
+ const trackSpans = getClipSpans(doc.clips, doc.assets, track);
+ const ramps = trackSpans.map(() => ({ headFade: 0, tailFade: 0, headZoom: 0, tailZoom: 0 }));
+ trackSpans.forEach((sp, i) => {
+ const next = trackSpans[i + 1];
+ if (!next) return;
+ const style = sp.clip.transitionStyle ?? "crossfade";
+ const d = sp.clip.transition ?? 0;
+ if (d <= 0) return;
+ if (sp.transitionOut > 0) {
+ ramps[i + 1].headFade = sp.transitionOut;
+ if (style === "crosszoom") {
+ ramps[i].tailZoom = sp.transitionOut;
+ ramps[i + 1].headZoom = sp.transitionOut;
+ }
+ } else if (style === "fadeout") ramps[i].tailFade = Math.min(d, sp.len);
+ else if (style === "zoomin") ramps[i].tailZoom = Math.min(d, sp.len);
+ else if (style === "fadein") ramps[i + 1].headFade = Math.min(d, next.len);
+ else if (style === "zoomout") ramps[i + 1].headZoom = Math.min(d, next.len);
+ });
+ return trackSpans
+ .map((sp, i) => ({ c: sp.clip, ramp: ramps[i] }))
+ .filter(({ c }) => !c.hidden && c.start < duration)
+ .map(({ c, ramp }) => ({
+ 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 what's below" branch fires — normalizing to "fit" defeated it.
+ fit: c.fit,
+ muted: c.muted,
+ volume: c.volume,
+ speed: c.speed,
+ image: assetById.get(c.assetId)!.type === "image",
+ ...ramp,
+ }));
+ });
const audio = doc.audioClips
.filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId))
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index e68cf148..9b6f6430 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -188,6 +188,7 @@ const overlayClipAdapter: LaneAdapter<VideoClip> = {
maxLen: (s, c) =>
((s.assets.find((x) => x.id === c.assetId)?.duration ?? c.out) - c.in) / speedOf(c),
assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),
+ overlapInto: (c, next) => transitionOverlap(c, next),
};
const cueAdapter: LaneAdapter<SubtitleCue> = {
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index 8a32961c..e71ec294 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -393,3 +393,49 @@ describe("spine grounding", () => {
expectLaneSound(videoLane(0));
});
});
+
+describe("upper-track transitions", () => {
+ test("setClipTransition on an upper track pulls the pair into overlap contact", () => {
+ const av = asset(4);
+ const bv = asset(4);
+ const spine = vclip({ track: 0, start: 0, out: 4 });
+ const a = vclip({ track: 1, start: 0, out: 4, assetId: av.id });
+ const b = vclip({ track: 1, start: 4, out: 4, assetId: bv.id });
+ useEditor.setState({ assets: [av, bv], clips: [spine, a, b] });
+ s().setClipTransition(a.id, 1);
+ expect(clipById(a.id).transition).toBeCloseTo(1);
+ expect(clipById(b.id).start).toBeCloseTo(3); // slid into the dissolve
+ expect(clipById(spine.id).start).toBeCloseTo(0); // track 0 untouched
+ });
+
+ test("setClipTransition slides only its own track's run", () => {
+ const av = asset(4);
+ const spine1 = vclip({ track: 0, start: 0, out: 4 });
+ const spine2 = vclip({ track: 0, start: 4, out: 4 });
+ const a = vclip({ track: 1, start: 0, out: 4, assetId: av.id });
+ const b = vclip({ track: 1, start: 4, out: 4, assetId: av.id });
+ useEditor.setState({ assets: [av], clips: [spine1, spine2, a, b] });
+ s().setClipTransition(a.id, 1);
+ expect(clipById(b.id).start).toBeCloseTo(3);
+ expect(clipById(spine2.id).start).toBeCloseTo(4);
+ });
+
+ test("splitting a layer clip clears the left half's transition", () => {
+ const av = asset(8);
+ const spine = vclip({ track: 0, start: 0, out: 8 });
+ const a = vclip({ track: 1, start: 0, out: 8, transition: 1, assetId: av.id });
+ useEditor.setState({
+ assets: [av],
+ clips: [spine, a],
+ selection: { kind: "clip", id: a.id },
+ currentTime: 4,
+ });
+ s().splitAtPlayhead();
+ const halves = s().clips.filter((c) => c.track === 1);
+ expect(halves.length).toBe(2);
+ const left = halves.find((c) => c.start === 0)!;
+ const right = halves.find((c) => c.start === 4)!;
+ expect(left.transition).toBeUndefined();
+ expect(right.transition).toBe(1);
+ });
+});
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 9c329981..56b88185 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -43,8 +43,7 @@ export type VideoTrackPlacement =
| { kind: "track"; track: number }
| { kind: "insert"; level: number };
-/** The track-0 clips — the sequence that carries transitions and drives
- * playback. */
+/** The track-0 clips — the sequence that drives playback and ripple. */
export const track0Clips = (clips: VideoClip[]) => clips.filter((c) => c.track === 0);
/** Every video clip not on track 0 — the composited layers. */
export const overlayLayers = (clips: VideoClip[]) => clips.filter((c) => c.track !== 0);
@@ -1199,7 +1198,9 @@ export const useEditor = create<EditorState>((baseSet, get) => {
setClipTransition: (id, seconds, style) => {
const s = get();
- const spans = getClipSpans(s.clips, s.assets);
+ const self = s.clips.find((c) => c.id === id);
+ if (!self) return;
+ const spans = getClipSpans(s.clips, s.assets, self.track);
const idx = spans.findIndex((sp) => sp.clip.id === id);
if (idx < 0) return;
const clip = spans[idx].clip;
@@ -1220,9 +1221,9 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// (and the run behind it, gaps preserved) so it starts `newOverlap`
// before this clip ends — closing any gap, since a dissolve needs
// contact. Clearing one pushes the pair back to a hard cut. Edge styles
- // overlap nothing: they leave the layout alone. Only track 0 moves:
- // transitions live on its sequence, and the composited layers
- // stay pinned to the absolute times they annotate.
+ // overlap nothing: they leave the layout alone. Only the clip's own
+ // track moves: every other track stays pinned to the absolute times it
+ // annotates.
if (next) {
const oldOverlap = spans[idx].transitionOut;
const wantStart =
@@ -1232,7 +1233,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
set((st) => ({
clips: st.clips
.map((c) =>
- c.track === 0 && c.start >= next.start - 1e-6
+ c.track === self.track && c.start >= next.start - 1e-6
? { ...c, start: Math.max(0, c.start + delta) }
: c
)
@@ -1503,7 +1504,9 @@ export const useEditor = create<EditorState>((baseSet, get) => {
if (t > c.start + 0.05 && t < c.start + eff - 0.05) {
push();
const cutIn = c.in + (t - c.start) * sp;
- const left: VideoClip = { ...c, out: cutIn };
+ // The left half hard-cuts into the right; the right keeps the
+ // original dissolve into whatever came after (same as track 0).
+ const left: VideoClip = { ...c, out: cutIn, transition: undefined, transitionStyle: undefined };
const right: VideoClip = { ...c, id: uid(), start: t, in: cutIn };
set((s) => {
const idx = s.clips.findIndex((x) => x.id === c.id);
@@ -2759,14 +2762,16 @@ export function transitionOverlap(a: VideoClip, b: VideoClip | undefined): numbe
export function getClipSpans(
clips: VideoClip[],
- assets: MediaAsset[]
+ assets: MediaAsset[],
+ track = 0
): ClipSpan[] {
- // Spans are track 0: the sequence that carries transitions and drives
- // playback. Layer clips composite separately.
+ // One track's clips in sequence, each with its live dissolve overlap into
+ // the next. Track 0 is the spine that drives playback; upper tracks carry
+ // their own transitions between their own clips.
// Map lookup, not a per-clip assets.find — this runs every playback frame.
const byId = new Map(assets.map((a) => [a.id, a]));
const present = clips
- .filter((clip) => clip.track === 0)
+ .filter((clip) => clip.track === track)
.map((clip) => ({ clip, asset: byId.get(clip.assetId) }))
.filter((x): x is { clip: VideoClip; asset: MediaAsset } => !!x.asset)
.sort((a, b) => a.clip.start - b.clip.start);
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index f80334d1..d53bd1cf 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -112,10 +112,11 @@ export interface VideoClip {
id: string;
assetId: string;
/** Which video track this clip sits on. Tracks number 0..N bottom-up:
- * track 0's clips form the sequence that carries transitions and drives
- * playback; higher tracks composite in front (highest wins where clips
- * overlap). Absent in older docs, which are all track 0; docs saved when
- * tracks could go negative lift on load so the lowest row becomes 0. */
+ * track 0's clips form the sequence that drives playback; higher tracks
+ * composite in front (highest wins where clips overlap). Every track
+ * carries transitions between its own clips. Absent in older docs, which
+ * are all track 0; docs saved when tracks could go negative lift on load
+ * so the lowest row becomes 0. */
track: number;
start: number; // timeline position, seconds
in: number; // trim-in inside the source, seconds
@@ -137,9 +138,11 @@ export interface VideoClip {
/** Playback rate, default 1 (absent). The source (out-in) seconds play in
* (out-in)/speed timeline seconds, so >1 is faster and shorter. */
speed?: number;
- /** Transition into the next clip, in timeline seconds (absent/0 = hard cut).
- * Cross styles overlap the two clips by this much (the cut shortens); edge
- * styles ramp one clip's edge over this window around a hard cut. */
+ /** Transition into the next clip on this clip's track, in timeline seconds
+ * (absent/0 = hard cut). Cross styles overlap the two clips by this much
+ * (the cut shortens); edge styles ramp one clip's edge over this window
+ * around a hard cut. On upper tracks the fades ramp to transparent instead
+ * of black, so the tracks beneath show through. */
transition?: number;
/** Look of that transition; absent = "crossfade". */
transitionStyle?: TransitionStyle;
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 6b2e9834..4e60df7a 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -638,7 +638,7 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "set_transition",
description:
- "Set the transition from this clip into the next one, in seconds (0 clears it, max 2). crossfade/crosszoom overlap the two clips so the cut shortens; fadeout/zoomin ramp the outgoing tail and fadein/zoomout the incoming head around a hard cut. Only valid when a next clip exists.",
+ "Set the transition from this clip into the next clip on its track (any video track), in seconds (0 clears it, max 2). crossfade/crosszoom overlap the two clips so the cut shortens; fadeout/zoomin ramp the outgoing tail and fadein/zoomout the incoming head around a hard cut. On upper tracks fades are alpha fades (the tracks beneath show through). Only valid when a next same-track clip exists.",
inputSchema: obj({
clipId: str("Video clip id (the clip the transition starts from)"),
seconds: num("Transition length in seconds, 0–2 (0 = hard cut)"),
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 3c2b5c99..d279f791 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -66,6 +66,16 @@ export interface ExportSpec {
/** Gain on the clip's own audio, 0..1.5; absent = 1 (unchanged). */
volume?: number;
speed?: number;
+ /** Transition ramps, timeline seconds from this overlay's head/tail. On
+ * an upper track a fade is an alpha fade (the tracks beneath show
+ * through); a cross transition arrives as the incoming clip's headFade
+ * while the outgoing clip stays opaque under it, and cross zoom adds a
+ * tailZoom/headZoom pair riding that overlap. The audio fades with the
+ * picture. */
+ headFade?: number;
+ tailFade?: number;
+ headZoom?: number;
+ tailZoom?: number;
/** A still image: looped for the clip's length instead of trimmed. */
image?: boolean;
}[];
@@ -467,7 +477,11 @@ async function runExport(job: Job, spec: ExportSpec) {
// Tracks number 0..N bottom-up: track 0 folds sequentially into the base
// picture, the rest overlay it in track order (highest last = frontmost).
- const overlayVideos = [...(spec.overlayVideos ?? [])].sort((a, b) => a.track - b.track);
+ // Within a track, earlier clips composite first, so a dissolving pair
+ // blends the incoming clip in over the outgoing one.
+ const overlayVideos = [...(spec.overlayVideos ?? [])].sort(
+ (a, b) => a.track - b.track || a.start - b.start
+ );
const clipFmt = "yuv420p";
const padColor = "black";
// One ffmpeg input per distinct media file (from the project folder),
@@ -588,6 +602,66 @@ async function runExport(job: Job, spec: ExportSpec) {
const clipDur = (c: ExportSpec["clips"][number]) =>
c.file ? Math.max(0.1, (c.out - c.in) / clipRate(c)) : Math.max(0, c.out - c.in);
+ /** Emit `core` into `[out]` with zoom ramps confined to the head/tail
+ * windows and `fades` appended. Zoom runs zoompan over just the touched
+ * slice (split → ramp → concat) so the per-frame zoom stays inside the
+ * short transition window. A head ramp settles TRANSITION_ZOOM→1 (zoom
+ * out), a tail ramp pushes 1→TRANSITION_ZOOM (zoom in); zoompan clamps z
+ * below 1 itself, so the plain arithmetic needs no guards. `w`×`h` is the
+ * segment's constant frame size; `tag` uniquifies intermediate labels.
+ * Shared by the track-0 segments and the overlay-track segments. */
+ const pushZoomRamped = (
+ core: string,
+ dur: number,
+ hz: number,
+ tz: number,
+ w: number,
+ h: number,
+ fmt: string,
+ fades: string,
+ out: string,
+ tag: string
+ ) => {
+ const ramp = (side: "head" | "tail", secs: number) => {
+ const frames = Math.max(1, Math.round(secs * fps) - 1);
+ const k = num(TRANSITION_ZOOM - 1);
+ const z =
+ side === "tail"
+ ? `1+${k}*in/${frames}`
+ : `${num(TRANSITION_ZOOM)}-${k}*in/${frames}`;
+ return (
+ `zoompan=z=${z}:x=iw/2-(iw/zoom/2):y=ih/2-(ih/zoom/2)` +
+ `:d=1:s=${w}x${h}:fps=${fps},setsar=1,format=${fmt}`
+ );
+ };
+ if (hz <= 0.01 && tz <= 0.01) {
+ filters.push(`${core}${fades}[${out}]`);
+ return;
+ }
+ const slices: { from: number; to: number; fx?: string }[] = [];
+ if (hz > 0.01) slices.push({ from: 0, to: hz, fx: ramp("head", hz) });
+ const mid0 = hz > 0.01 ? hz : 0;
+ const mid1 = tz > 0.01 ? dur - tz : dur;
+ if (mid1 - mid0 > 0.01) slices.push({ from: mid0, to: mid1 });
+ if (tz > 0.01) slices.push({ from: dur - tz, to: dur, fx: ramp("tail", tz) });
+ if (slices.length === 1) {
+ filters.push(`${core},${slices[0].fx}${fades}[${out}]`);
+ return;
+ }
+ filters.push(`${core},split=${slices.length}${slices.map((_, k) => `[zs${tag}_${k}]`).join("")}`);
+ slices.forEach((sl, k) => {
+ filters.push(
+ `[zs${tag}_${k}]trim=${num(sl.from)}:${num(sl.to)},setpts=PTS-STARTPTS` +
+ (sl.fx ? `,${sl.fx}` : "") +
+ `[zp${tag}_${k}]`
+ );
+ });
+ filters.push(
+ slices.map((_, k) => `[zp${tag}_${k}]`).join("") +
+ `concat=n=${slices.length}:v=1:a=0${fades}[${out}]`
+ );
+ };
+
// Per-clip normalized video + audio segments for the join below.
spec.clips.forEach((c, j) => {
const idx = c.image ? imageClipInput.get(j)! : inputIndex.get(c.file)!;
@@ -632,50 +706,7 @@ async function runExport(job: Job, spec: ExportSpec) {
const fades =
(hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}` : "") +
(tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");
- if (hz > 0.01 || tz > 0.01) {
- // Zoom ramp on the touched slice only: split the segment, run zoompan
- // over the head/tail window, and concat back — the per-frame zoom
- // stays confined to the short transition window. A head ramp settles
- // TRANSITION_ZOOM→1 (zoom out), a tail ramp pushes 1→TRANSITION_ZOOM
- // (zoom in); zoompan clamps z below 1 itself, so the plain arithmetic
- // needs no guards.
- const ramp = (side: "head" | "tail", secs: number) => {
- const frames = Math.max(1, Math.round(secs * fps) - 1);
- const k = num(TRANSITION_ZOOM - 1);
- const z =
- side === "tail"
- ? `1+${k}*in/${frames}`
- : `${num(TRANSITION_ZOOM)}-${k}*in/${frames}`;
- return (
- `zoompan=z=${z}:x=iw/2-(iw/zoom/2):y=ih/2-(ih/zoom/2)` +
- `:d=1:s=${W}x${H}:fps=${fps},setsar=1,format=${clipFmt}`
- );
- };
- const slices: { from: number; to: number; fx?: string }[] = [];
- if (hz > 0.01) slices.push({ from: 0, to: hz, fx: ramp("head", hz) });
- const mid0 = hz > 0.01 ? hz : 0;
- const mid1 = tz > 0.01 ? dur - tz : dur;
- if (mid1 - mid0 > 0.01) slices.push({ from: mid0, to: mid1 });
- if (tz > 0.01) slices.push({ from: dur - tz, to: dur, fx: ramp("tail", tz) });
- if (slices.length === 1) {
- filters.push(`${core},${slices[0].fx}${fades}[v${j}]`);
- } else {
- filters.push(`${core},split=${slices.length}${slices.map((_, k) => `[vs${j}_${k}]`).join("")}`);
- slices.forEach((sl, k) => {
- filters.push(
- `[vs${j}_${k}]trim=${num(sl.from)}:${num(sl.to)},setpts=PTS-STARTPTS` +
- (sl.fx ? `,${sl.fx}` : "") +
- `[vp${j}_${k}]`
- );
- });
- filters.push(
- slices.map((_, k) => `[vp${j}_${k}]`).join("") +
- `concat=n=${slices.length}:v=1:a=0${fades}[v${j}]`
- );
- }
- } else {
- filters.push(`${core}${fades}[v${j}]`);
- }
+ pushZoomRamped(core, dur, hz, tz, W, H, clipFmt, fades, `v${j}`, `c${j}`);
} else {
// No video stream, or a hidden clip: the slot plays black.
filters.push(
@@ -744,6 +775,17 @@ async function runExport(job: Job, spec: ExportSpec) {
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);
+ // Transition ramps, clamped so head+tail never overrun the segment. On an
+ // upper track the fades are alpha fades — the clip dissolves against
+ // whatever is beneath it (a cross transition ships as the incoming clip's
+ // head fade, blending it in over the still-opaque outgoing clip).
+ const hz = Math.max(0, Math.min(oc.headZoom ?? 0, olen));
+ const tz = Math.max(0, Math.min(oc.tailZoom ?? 0, olen - hz));
+ const hf = Math.max(0, Math.min(oc.headFade ?? 0, olen));
+ const tf = Math.max(0, Math.min(oc.tailFade ?? 0, olen - hf));
+ const ramped = hz > 0.01 || tz > 0.01;
+ const boxW = region ? region.rw : W;
+ const boxH = region ? region.rh : H;
let framing: string;
let pos: string;
if (!region) {
@@ -758,6 +800,17 @@ async function runExport(job: Job, spec: ExportSpec) {
: `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`;
}
+ // zoompan needs a constant frame size: pad a letterboxed segment out to
+ // its exact box with transparent margins (the tracks beneath keep showing
+ // through) and anchor the overlay at the box origin.
+ if (ramped && !cover) {
+ framing += `,format=yuva420p,pad=${boxW}:${boxH}:(ow-iw)/2:(oh-ih)/2:[email protected]`;
+ pos = region ? `${region.rx}:${region.ry}` : "0:0";
+ }
+ const fmt = hf > 0.01 || tf > 0.01 || (ramped && !cover) ? "yuva420p" : "yuv420p";
+ const fades =
+ (hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}:alpha=1` : "") +
+ (tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, olen - tf))}:d=${num(tf)}:alpha=1` : "");
const k = ovk++;
const seg = `ovv${k}`;
// A still replays its looped input; footage trims its source span and
@@ -765,10 +818,13 @@ async function runExport(job: Job, spec: ExportSpec) {
const timebase = oc.image
? `[${idx}:v]setpts=PTS-STARTPTS`
: `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)}`;
- filters.push(
- `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}format=yuv420p,` +
- `tpad=start_duration=${num(oc.start)}[${seg}]`
- );
+ const core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}format=${fmt}`;
+ const pre = `ovp${k}`;
+ pushZoomRamped(core, olen, hz, tz, boxW, boxH, fmt, fades, pre, `o${k}`);
+ // The zoom slices' concat drops the stream's frame-rate metadata, and
+ // tpad converts start_duration to a frame count through it — without the
+ // fps re-stamp it pads zero frames and the overlay lands early.
+ filters.push(`[${pre}]fps=${fps},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}]`
@@ -776,10 +832,14 @@ async function runExport(job: Job, spec: ExportSpec) {
if (!oc.muted && audioPresence.get(oc.file)) {
const tempo = ospeed !== 1 ? `${atempoChain(ospeed)},` : "";
const vol = (oc.volume ?? 1) !== 1 ? `volume=${num(oc.volume ?? 1)},` : "";
+ // The picture's fade edges carry the sound with them; zoom edges don't.
+ const afades =
+ (hf > 0.01 ? `afade=t=in:st=0:d=${num(hf)},` : "") +
+ (tf > 0.01 ? `afade=t=out:st=${num(Math.max(0, olen - tf))}:d=${num(tf)},` : "");
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}${vol}` +
+ `[${idx}:a]atrim=${num(oc.in)}:${num(oc.out)},asetpts=PTS-STARTPTS,${tempo}${vol}${afades}` +
`aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,adelay=${delayMs}:all=1[${lab}]`
);
overlaySoundLabels.push(lab);