Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): split the preview into a compositor and a frame plan

David Le7a8121030a85
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index 26204249..af4d223e 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -2,167 +2,13 @@
import { useEffect, type RefObject } from "react";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } from "@/cut/lib/store";
-import { isFullRect, overlayAnimStyle, projectFadeSeconds, rectOf, TRANSITION_ZOOM } from "@/cut/lib/types";
-import type { AudioClip, ClipAnim, ClipSpan, FrameRect, MediaAsset, TransitionStyle, VideoClip } from "@/cut/lib/types";
-import { gradeTint, gradeToCssFilter, isNeutralGrade } from "@/cut/lib/colorGrade";
-import { grainTile, lookCssFilter, lookPost } from "@/cut/lib/looks";
+import { isFullRect, projectFadeSeconds, rectOf } from "@/cut/lib/types";
+import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
+import { FrameCompositor, MISSING_FRAME, PENDING_FRAME, type Frame } from "@/cut/lib/composite";
+import { duckGainAt, overlayPlan, PREROLL_LEAD_S, trackZeroPlan } from "@/cut/lib/framePlan";
import { reportMediaElementError } from "@/cut/lib/mediaLinks";
import { registerSourceSampler } from "@/cut/lib/previewCanvas";
-/** The alpha/zoom/gain ramps a transition or clip animation puts on one
- * upper-track clip at `t`. A transition blends the incoming clip in over the
- * outgoing one (which keeps full alpha and its audio until its footprint
- * ends); a clip animation ramps the clip's own edge. On an upper track a fade
- * ramps to transparent — the tracks beneath show through — and the animation
- * styles that need frame motion degrade to a fade, both matching the export's
- * alpha ramps. */
-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 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;
- }
- // The clip's own entrance/exit animations. A transitioned joint owns its
- // edges: the transition plays there and the adjacent animation is held
- // (running both would fight over the same window).
- if (span.clip.animIn && !(prev && prev.transitionOut > 0)) {
- const d = Math.min(span.clip.animIn.seconds, span.len);
- const rel = t - span.start;
- if (d > 0 && rel < d) {
- const p = Math.max(0, rel / d);
- if (overlayAnimStyle(span.clip.animIn.style) === "zoom") {
- zoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;
- } else {
- alpha = Math.min(alpha, p);
- gain = Math.min(gain, p);
- }
- }
- }
- if (span.clip.animOut && span.transitionOut <= 0) {
- const d = Math.min(span.clip.animOut.seconds, span.len);
- const left = span.start + span.len - t;
- if (d > 0 && left < d) {
- const p = Math.max(0, left / d);
- if (overlayAnimStyle(span.clip.animOut.style) === "zoom") {
- zoom = 1 + (TRANSITION_ZOOM - 1) * (1 - p);
- } else {
- alpha = Math.min(alpha, p);
- gain = Math.min(gain, p);
- }
- }
- }
- return { alpha, zoom, gain };
-}
-
-/** A track-0 clip's own entrance/exit animation state at `rel` seconds into
- * its `len`-second footprint. Mirrors the export's per-segment ramps: fades
- * veil to/from black with the audio following; zoom uses the shared
- * TRANSITION_ZOOM ramps; pop scales from/to 80% with an alpha fade; slides
- * translate the frame (fractions of the canvas, matching xfade against
- * black); wipes reveal/conceal through a moving edge. */
-function clipAnimFx(
- clip: VideoClip,
- rel: number,
- len: number,
- // Edge context from the caller: a transitioned joint owns its edges (skip
- // that side), and an abutting hard cut gives the side a backdrop — the
- // neighbor's held frame — so a fade blends by alpha there instead of
- // veiling to black.
- edges?: { skipIn?: boolean; skipOut?: boolean; backdropIn?: boolean; backdropOut?: boolean }
-) {
- const fx = {
- alpha: 1,
- zoom: 1,
- gain: 1,
- veil: 0, // fade-to-black amount, drawn by the caller's veil pass
- dxFrac: 0, // frame translation, fraction of canvas width/height
- dyFrac: 0,
- };
- const apply = (a: ClipAnim, side: "in" | "out") => {
- const d = Math.min(a.seconds, len);
- if (d <= 0) return;
- // p runs 0→1 as the visible ramp progresses on either side: entrance
- // completeness on the head, remaining presence on the tail.
- const p =
- side === "in"
- ? Math.min(1, Math.max(0, rel / d))
- : Math.min(1, Math.max(0, (len - rel) / d));
- if (p >= 1) return;
- switch (a.style) {
- case "zoom":
- // Entrance settles TRANSITION_ZOOM→1; exit pushes 1→TRANSITION_ZOOM.
- fx.zoom *=
- side === "in"
- ? TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p
- : 1 + (TRANSITION_ZOOM - 1) * (1 - p);
- break;
- case "pop":
- fx.zoom *= 0.8 + 0.2 * p;
- fx.alpha *= p;
- break;
- case "slideleft": // frame moves left: enters from the right, exits off the left
- fx.dxFrac += side === "in" ? 1 - p : -(1 - p);
- break;
- case "slideright":
- fx.dxFrac += side === "in" ? -(1 - p) : 1 - p;
- break;
- case "slideup": // frame moves up: enters from the bottom, exits off the top
- fx.dyFrac += side === "in" ? 1 - p : -(1 - p);
- break;
- case "slidedown":
- fx.dyFrac += side === "in" ? -(1 - p) : 1 - p;
- break;
- case "fade":
- default:
- // Fade — and the graceful fallback for a stored style this build no
- // longer knows (the export treats unknown styles the same way).
- if (side === "in" ? edges?.backdropIn : edges?.backdropOut) fx.alpha *= p;
- else fx.veil = Math.max(fx.veil, 1 - p);
- fx.gain = Math.min(fx.gain, p);
- break;
- }
- };
- if (clip.animIn && !edges?.skipIn) apply(clip.animIn, "in");
- if (clip.animOut && !edges?.skipOut) apply(clip.animOut, "out");
- return fx;
-}
-
-/** 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). */
-function duckGainAt(audioClips: AudioClip[], t: number): number {
- let g = 1;
- for (const a of audioClips) {
- if (a.hidden || a.duck === undefined || a.duck >= 1) continue;
- const speed = a.speed && a.speed > 0 ? a.speed : 1;
- const len = Math.max(0.1, (a.out - a.in) / speed);
- if (t >= a.start && t < a.start + len) g = Math.min(g, Math.max(0, a.duck));
- }
- return g;
-}
-
// A video clip on any track is backed by a <video> for footage or an <img>
// for a still image. These helpers read either kind uniformly so the
// compositor stays one code path — an image never seeks, plays, or carries
@@ -208,12 +54,11 @@ const DECODER_STALL_MS = 10_000;
const DECODER_RETRY_MS = 1_000;
const DECODER_REBUILDS = 3;
-// Pre-roll lead. Inside this many seconds of a clip's entrance, its element is
-// played muted and undrawn so the decoder is already running across the
-// in-point when the cut lands — the handoff play() then resumes hot instead of
-// spinning a cold decoder up. Kept short so the pre-rolled picture arrives at
-// the in-point right as the playhead reaches the cut.
-const PREROLL_LEAD_S = 0.5;
+// Inside PREROLL_LEAD_S of a clip's entrance its element is played muted and
+// undrawn, so the decoder is already running across the in-point when the cut
+// lands and the handoff play() resumes hot instead of spinning a cold decoder
+// up. The lead itself is part of the frame plan, which is what decides when a
+// clip is about to be needed.
const pauseEl = (el: MediaEl) => {
if (!isImageEl(el) && !el.paused) el.pause();
@@ -278,21 +123,17 @@ class Engine {
private raf = 0;
private activeClipId: string | null = null;
private disposed = false;
- // Scratch surface for per-clip color grades: the source draws here through
- // ctx.filter (+ a multiply tint), and the graded result is what the
- // compositor stamps onto the main canvas. One instance suffices — every use
- // is draw-then-immediately-copy.
- private gradeCanvas: HTMLCanvasElement | null = null;
- // Cached buffers for look post passes: a canvas-sized scratch for glow and
- // ghost self-copies, and a footprint-sized vignette gradient.
- private lookScratch: HTMLCanvasElement | null = null;
- private vignetteCanvas: HTMLCanvasElement | null = null;
// Wall-clock stamp for advancing time where track 0 has nothing playing —
// in a gap or past its end there is no track-0 video element to act as the
// master clock.
private lastPlayNow = 0;
+ // Everything this engine puts on the canvas goes through here. The engine
+ // owns the decoders and the clock; the compositor owns the picture, and an
+ // export renders through the same one.
+ private comp: FrameCompositor;
constructor(private canvas: HTMLCanvasElement) {
+ this.comp = new FrameCompositor(canvas);
this.tick = this.tick.bind(this);
this.raf = requestAnimationFrame(this.tick);
}
@@ -494,271 +335,13 @@ class Engine {
return el && elReady(el) ? el : null;
}
- /** The clip's picture with its color grade and look grading applied, or the
- * raw element when there is nothing to apply. Mirrors the export's chain
- * order — grade first (lutrgb/hue), then the look's color pass — as CSS
- * filters, with the grade's warm tint as a multiply pass, and source alpha
- * restored so transparent stills keep their transparency. The look's post
- * passes (vignette, grain, glow…) draw over the composited layer instead —
- * see applyLookPost. */
- private gradedSource(el: MediaEl, clip: VideoClip | undefined): CanvasImageSource {
- const grade = clip?.grade;
- const lookCss = lookCssFilter(clip?.look, clip?.lookAmount);
- if (isNeutralGrade(grade) && !lookCss) return el;
- const scratch = (this.gradeCanvas ??= document.createElement("canvas"));
- const w = elW(el);
- const h = elH(el);
- // Match both dimensions — a transition alternates two differently-sized
- // sources through this one scratch every frame, and a stale dimension
- // leaves the previous clip's pixels in the draw.
- if (scratch.width !== w) scratch.width = w;
- if (scratch.height !== h) scratch.height = h;
- const ctx = scratch.getContext("2d");
- // Without ctx.filter support, skip the whole treatment (never half-apply
- // the tint); export still renders it.
- if (!ctx || !("filter" in ctx)) return el;
- ctx.clearRect(0, 0, w, h);
- ctx.filter = [gradeToCssFilter(grade), lookCss].filter(Boolean).join(" ") || "none";
- ctx.drawImage(el, 0, 0, w, h);
- ctx.filter = "none";
- const tint = gradeTint(grade);
- if (tint) {
- ctx.globalCompositeOperation = "multiply";
- ctx.fillStyle = tint;
- ctx.fillRect(0, 0, w, h);
- // Multiply painted the transparent areas solid; carve the source's
- // alpha back in.
- ctx.globalCompositeOperation = "destination-in";
- ctx.drawImage(el, 0, 0, w, h);
- ctx.globalCompositeOperation = "source-over";
- }
- return scratch;
- }
-
- /** Draw a look's post passes over one composited layer's footprint (canvas
- * pixels): vignette, animated grain, self-copy glow, color washes, chroma
- * ghosts. `alpha` follows the layer so a dissolving clip's grain dissolves
- * with it. Every buffer here is cached — no per-frame allocation or pixel
- * reads. */
- private applyLookPost(clip: VideoClip | undefined, rx: number, ry: number, rw: number, rh: number, alpha: number) {
- const post = lookPost(clip?.look, clip?.lookAmount);
- if (!post || alpha <= 0 || rw <= 0 || rh <= 0) return;
- const ctx = this.canvas.getContext("2d");
- if (!ctx || !("filter" in ctx)) return;
- ctx.save();
- ctx.beginPath();
- ctx.rect(rx, ry, rw, rh);
- ctx.clip();
- if (post.glow) {
- // Copy the just-drawn region through a blur (and a highlight isolation
- // for halation) and lay it back over itself.
- const scratch = (this.lookScratch ??= document.createElement("canvas"));
- if (scratch.width !== this.canvas.width) scratch.width = this.canvas.width;
- if (scratch.height !== this.canvas.height) scratch.height = this.canvas.height;
- const sctx = scratch.getContext("2d");
- if (sctx && "filter" in sctx) {
- const blurPx = Math.max(1, post.glow.blurFrac * this.canvas.height);
- sctx.clearRect(rx, ry, rw, rh);
- sctx.filter = post.glow.bright
- ? `contrast(2.5) brightness(0.55) saturate(1.4) sepia(0.35) blur(${blurPx}px)`
- : `blur(${blurPx}px)`;
- sctx.drawImage(this.canvas, rx, ry, rw, rh, rx, ry, rw, rh);
- sctx.filter = "none";
- ctx.globalAlpha = post.glow.alpha * alpha;
- ctx.globalCompositeOperation = post.glow.mode;
- ctx.drawImage(scratch, rx, ry, rw, rh, rx, ry, rw, rh);
- }
- }
- if (post.ghost) {
- // VHS chroma fringing: warm and cool copies of the region nudged apart.
- const scratch = (this.lookScratch ??= document.createElement("canvas"));
- if (scratch.width !== this.canvas.width) scratch.width = this.canvas.width;
- if (scratch.height !== this.canvas.height) scratch.height = this.canvas.height;
- const sctx = scratch.getContext("2d");
- if (sctx && "filter" in sctx) {
- const shift = Math.max(1, post.ghost.shiftFrac * this.canvas.width);
- sctx.clearRect(rx, ry, rw, rh);
- sctx.filter = "sepia(1) saturate(4) hue-rotate(-40deg) brightness(0.55)";
- sctx.drawImage(this.canvas, rx, ry, rw, rh, rx, ry, rw, rh);
- sctx.filter = "none";
- ctx.globalAlpha = post.ghost.alpha * alpha;
- ctx.globalCompositeOperation = "lighter";
- ctx.drawImage(scratch, rx, ry, rw, rh, rx + shift, ry, rw, rh);
- if (sctx) {
- sctx.clearRect(rx, ry, rw, rh);
- sctx.filter = "sepia(1) saturate(4) hue-rotate(140deg) brightness(0.55)";
- sctx.drawImage(this.canvas, rx, ry, rw, rh, rx, ry, rw, rh);
- sctx.filter = "none";
- ctx.drawImage(scratch, rx, ry, rw, rh, rx - shift, ry, rw, rh);
- }
- }
- }
- ctx.globalCompositeOperation = "source-over";
- for (const wash of post.washes ?? []) {
- ctx.globalAlpha = wash.alpha * alpha;
- ctx.globalCompositeOperation = wash.mode;
- ctx.fillStyle = wash.color;
- ctx.fillRect(rx, ry, rw, rh);
- }
- if (post.grain) {
- const tile = grainTile(Math.floor(performance.now() / 80));
- if (tile) {
- ctx.globalAlpha = post.grain * alpha;
- ctx.globalCompositeOperation = "overlay";
- for (let y = ry; y < ry + rh; y += tile.height) {
- for (let x = rx; x < rx + rw; x += tile.width) {
- ctx.drawImage(tile, x, y);
- }
- }
- }
- }
- if (post.vignette) {
- // Cached radial gradient, rebuilt only when the footprint size changes.
- const vg = (this.vignetteCanvas ??= document.createElement("canvas"));
- if (vg.width !== Math.round(rw) || vg.height !== Math.round(rh)) {
- vg.width = Math.max(1, Math.round(rw));
- vg.height = Math.max(1, Math.round(rh));
- const vctx = vg.getContext("2d");
- if (vctx) {
- const g = vctx.createRadialGradient(
- vg.width / 2,
- vg.height / 2,
- Math.min(vg.width, vg.height) * 0.35,
- vg.width / 2,
- vg.height / 2,
- Math.hypot(vg.width, vg.height) / 2
- );
- g.addColorStop(0, "rgba(0,0,0,0)");
- g.addColorStop(1, "rgba(0,0,0,1)");
- vctx.clearRect(0, 0, vg.width, vg.height);
- vctx.fillStyle = g;
- vctx.fillRect(0, 0, vg.width, vg.height);
- }
- }
- ctx.globalAlpha = post.vignette * alpha;
- ctx.globalCompositeOperation = "source-over";
- ctx.drawImage(vg, rx, ry, rw, rh);
- }
- ctx.restore();
- ctx.globalAlpha = 1;
- ctx.globalCompositeOperation = "source-over";
- }
-
- private drawIntoRect(
- el: MediaEl,
- rect: FrameRect,
- fill: boolean,
- alpha: number,
- zoom = 1,
- clip?: VideoClip
- ) {
- 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 vw = elW(el);
- const vh = elH(el);
- const sc = (fill ? Math.max(rw / vw, rh / vh) : Math.min(rw / vw, rh / vh)) * zoom;
- const dw = vw * sc;
- const dh = vh * sc;
- const dx = rx + (rw - dw) / 2;
- const dy = ry + (rh - dh) / 2;
- const src = this.gradedSource(el, clip);
- const prevAlpha = ctx.globalAlpha;
- ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
- if (fill || zoom > 1) {
- ctx.save();
- ctx.beginPath();
- ctx.rect(rx, ry, rw, rh);
- ctx.clip();
- ctx.drawImage(src, dx, dy, dw, dh);
- ctx.restore();
- } else {
- ctx.drawImage(src, dx, dy, dw, dh);
- }
- ctx.globalAlpha = prevAlpha;
- this.applyLookPost(clip, rx, ry, rw, rh, alpha);
- }
-
- /** Frame-motion effect a transition or animation puts on one layer draw:
- * a whole-frame translation in canvas px. */
- private drawLayer(
- el: MediaEl | null,
- clip: VideoClip | undefined,
- clear: boolean,
- alpha: number,
- zoom = 1,
- fx?: { dx?: number; dy?: number }
- ) {
- const ctx = this.canvas.getContext("2d");
- if (!ctx) return;
- const W = this.canvas.width;
- const H = this.canvas.height;
- if (!el) {
- if (clear) {
- ctx.fillStyle = "#000";
- ctx.fillRect(0, 0, W, H);
- }
- return;
- }
- // A hidden clip plays nothing: fill black only if we own the clear,
- // otherwise leave the frame as drawn so far.
- if (clip?.hidden) {
- if (clear) {
- 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 (!elReady(el)) return;
- if (clear) {
- ctx.fillStyle = "#000";
- ctx.fillRect(0, 0, W, H);
- }
- const hasFx = !!fx && (!!fx.dx || !!fx.dy);
- if (hasFx) {
- // Motion runs in full-canvas space — the export translates the whole
- // padded segment frame, so a regioned clip rides along with it.
- // Whole-pixel translation: a fractional offset antialiases both frame
- // edges and draws a hairline seam where a push's frames meet.
- ctx.save();
- ctx.translate(Math.round(fx!.dx ?? 0), Math.round(fx!.dy ?? 0));
- }
- // A regioned track-0 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, zoom, clip);
- if (hasFx) ctx.restore();
- return;
- }
- const fill = clip?.fit === "fill";
- const vw = elW(el);
- const vh = elH(el);
- const scale = (fill ? Math.max(W / vw, H / vh) : Math.min(W / vw, H / vh)) * zoom;
- const dw = vw * scale;
- const dh = vh * scale;
- let dx = (W - dw) / 2;
- let dy = (H - dh) / 2;
- if (fill) {
- // Pan the crop window across the overflow (matches the export crop).
- const kx = 0.5 + (clip?.panX ?? 0) / 2;
- const ky = 0.5 + (clip?.panY ?? 0) / 2;
- dx = -(dw - W) * kx;
- dy = -(dh - H) * ky;
- }
- const prevAlpha = ctx.globalAlpha;
- ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
- ctx.drawImage(this.gradedSource(el, clip), dx, dy, dw, dh);
- ctx.globalAlpha = prevAlpha;
- this.applyLookPost(clip, 0, 0, W, H, alpha);
- if (hasFx) ctx.restore();
+ /** The picture a media element is currently showing, in the form the
+ * compositor takes. An element that exists but has no decodable frame is
+ * `pending`, which is what keeps a skim from strobing black. */
+ private frameOf(el: MediaEl | null | undefined): Frame {
+ if (!el) return MISSING_FRAME;
+ if (!elReady(el)) return PENDING_FRAME;
+ return { kind: "ready", image: el, width: elW(el), height: elH(el) };
}
/** Draw `masterSpan` full-frame, plus any transition live at time `t` in
@@ -766,266 +349,66 @@ class Engine {
* clips' own entrance/exit animations. Returns the master element (the
* playback clock). */
private composite(masterSpan: ClipSpan, spans: ClipSpan[], t: number, play: boolean) {
+ // A hidden clip is silent as well as black.
+ // What the frame should be at `t` — the same answer an export gets.
+ const plan = trackZeroPlan(masterSpan, spans, t);
// 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.clip.id]);
- const idx = spans.indexOf(masterSpan);
- const next = spans[idx + 1];
- const prev = spans[idx - 1];
- const style = masterSpan.clip.transitionStyle ?? "crossfade";
- let incEl: MediaEl | null = null;
- let alpha = 0;
- let masterZoom = 1;
- let incZoom = 1;
- let black = 0; // fade-to-black veil over the master clip, 0..1
- let gain = 1; // master audio follows the picture through a fade edge
// Prime the next clip's decoder+audio pipeline shortly before its entrance
// (the dissolve start, or the hard cut) so the handoff `play()` resumes hot
// — no cold-start spin-up freezing the picture and playhead at the cut.
- if (next && t < next.start && t >= next.start - PREROLL_LEAD_S) {
- this.warmNext(next, t);
- keep.add(next.clip.id);
+ if (plan.upcoming) {
+ this.warmNext(plan.upcoming, t);
+ keep.add(plan.upcoming.clip.id);
}
- // Transitions: once the incoming footprint starts, blend it in over the
- // master. Each clip owns its element, so the two decode side by side — a
- // true blend even when they are trims of the same source.
- let p = 0;
- if (masterSpan.transitionOut > 0 && next && t >= next.start) {
- p = Math.min(1, (t - next.start) / masterSpan.transitionOut);
- alpha = p;
- incEl = this.prepare(next, t, play, true); // the outgoing clip keeps the audio
- keep.add(next.clip.id);
- if (style === "crosszoom") {
- // The outgoing picture pushes in while the incoming one settles back.
- masterZoom = 1 + (TRANSITION_ZOOM - 1) * p;
- incZoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;
- }
+ // Each clip owns its element, so a transition's two clips decode side by
+ // side — a true blend even when they are trims of the same source.
+ let incEl: MediaEl | null = null;
+ if (plan.incoming) {
+ incEl = this.prepare(plan.incoming, t, play, true); // the outgoing clip keeps the audio
+ keep.add(plan.incoming.clip.id);
}
- // The master's own entrance/exit animations; the export bakes the same
- // ramps into the segment before the join. A transitioned joint owns its
- // edges: with a live overlap behind or ahead, that side's animation is
- // held so it never fights the transition's motion (the incoming clip's
- // entrance is likewise held — its joint is this transition). An abutting
- // hard cut gives the animation a backdrop: the neighbor's held frame
- // shows behind it instead of black (black stays for the timeline's ends
- // and across gaps).
- const W = this.canvas.width;
- const H = this.canvas.height;
- const rel = t - masterSpan.start;
- const abutPrev =
- !!prev &&
- !prev.clip.hidden &&
- prev.transitionOut <= 0 &&
- Math.abs(prev.start + prev.len - masterSpan.start) < 0.02;
- const abutNext =
- !!next &&
- !next.clip.hidden &&
- masterSpan.transitionOut <= 0 &&
- Math.abs(masterSpan.start + masterSpan.len - next.start) < 0.02;
- const mAnim = clipAnimFx(masterSpan.clip, rel, masterSpan.len, {
- skipIn: (prev?.transitionOut ?? 0) > 0,
- skipOut: masterSpan.transitionOut > 0,
- backdropIn: abutPrev,
- backdropOut: abutNext,
- });
- const masterFx = { dx: mAnim.dxFrac * W, dy: mAnim.dyFrac * H };
- masterZoom *= mAnim.zoom;
- black = Math.max(black, mAnim.veil);
- gain = Math.min(gain, mAnim.gain);
// A live voiceover ducks the master clip's sound under it. The clip's own
// volume rides on top (the element clamps at 1; export honors up to 1.5).
const duck = duckGainAt(useEditor.getState().audioClips, t);
if (!isImageEl(masterEl)) {
- masterEl.volume = Math.max(0, Math.min(1, gain * duck * (masterSpan.clip.volume ?? 1)));
+ masterEl.volume = Math.max(
+ 0,
+ Math.min(1, plan.gain * duck * (masterSpan.clip.volume ?? 1))
+ );
}
this.pauseExcept(keep);
// No clear here — the tick clears once before compositing, so a regioned
// clip draws into its rect over the already-black frame.
- // Backdrop for a live edge animation at an abutting cut: the previous
- // clip's last frame behind an entrance, the next clip's first frame
- // behind an exit. Zoom keeps the frame covered, so it skips the draw.
- if (!incEl) {
- const winLive = (a: ClipAnim | undefined, side: "in" | "out") => {
- if (!a || a.style === "zoom") return false;
- const d = Math.min(a.seconds, masterSpan.len);
- return side === "in" ? rel < d : masterSpan.len - rel < d;
- };
- if (abutPrev && winLive(masterSpan.clip.animIn, "in")) {
- this.drawBackdropFrame(prev!, prev!.clip.out - 0.05);
- } else if (abutNext && winLive(masterSpan.clip.animOut, "out")) {
- this.drawBackdropFrame(next!, next!.clip.in);
- }
- }
- this.drawCrossJoin(style, p, {
- masterEl,
- masterClip: masterSpan.clip,
- masterAlpha: mAnim.alpha,
- masterZoom,
- masterFx,
- incEl,
- incClip: next?.clip,
- incAlpha: alpha,
- incZoom,
- });
+ if (plan.backdrop) this.drawBackdropFrame(plan.backdrop.span, plan.backdrop.at, t);
+ this.comp.drawCrossJoin(
+ plan.style,
+ plan.p,
+ {
+ masterFrame: this.frameOf(masterEl),
+ masterClip: masterSpan.clip,
+ masterAlpha: plan.masterAlpha,
+ masterZoom: plan.masterZoom,
+ masterFx: {
+ dx: plan.masterFxFrac.dx * this.canvas.width,
+ dy: plan.masterFxFrac.dy * this.canvas.height,
+ },
+ incFrame: this.frameOf(incEl),
+ incClip: plan.incoming?.clip,
+ incAlpha: plan.incAlpha,
+ incZoom: plan.incZoom,
+ },
+ t
+ );
// Veil only the master clip's own footprint, like the export's per-clip
// fade filter: a regioned clip darkens inside its rect while a track
// behind shows through the margins; tracks drawn after (above) stay lit.
- if (black > 0) this.fillBlackVeil(black, rectOf(masterSpan.clip));
+ if (plan.veil > 0) this.comp.fillBlackVeil(plan.veil, rectOf(masterSpan.clip));
return masterEl;
}
- /** Draw the master layer, and during a transition (`p` > 0, incoming
- * element live) compose the incoming clip over it in the style's geometry.
- * Everything runs in full-canvas space, matching the export's xfade over
- * fully padded segment frames. */
- private drawCrossJoin(
- style: TransitionStyle,
- p: number,
- d: {
- masterEl: MediaEl | null;
- masterClip: VideoClip;
- masterAlpha: number;
- masterZoom: number;
- masterFx: { dx: number; dy: number };
- incEl: MediaEl | null;
- incClip: VideoClip | undefined;
- incAlpha: number;
- incZoom: number;
- }
- ) {
- const ctx = this.canvas.getContext("2d");
- if (!ctx) return;
- const W = this.canvas.width;
- const H = this.canvas.height;
- const drawMaster = (fx = d.masterFx, alpha = d.masterAlpha) =>
- this.drawLayer(d.masterEl, d.masterClip, false, alpha, d.masterZoom, fx);
- // The blend styles ramp the incoming alpha; the geometric styles draw it
- // opaque inside their own moving region.
- const drawInc = (alpha = d.incAlpha, fx?: { dx: number; dy: number }) => {
- if (d.incEl) this.drawLayer(d.incEl, d.incClip, false, alpha, d.incZoom, fx);
- };
- const clipped = (path: () => void, draw: () => void) => {
- ctx.save();
- ctx.beginPath();
- path();
- ctx.clip();
- draw();
- ctx.restore();
- };
- if (!d.incEl || p <= 0) {
- drawMaster();
- return;
- }
- switch (style) {
- case "dipblack":
- case "dipwhite": {
- // Matches xfade fadeblack/fadewhite's measured plateau: out by ~30%,
- // solid to ~60%, in over the rest.
- const veil = Math.max(0, Math.min(1, Math.min(p / 0.3, (1 - p) / 0.4)));
- if (p < 0.45) drawMaster();
- else drawInc(1);
- this.fillVeil(style === "dipwhite" ? "255,255,255" : "0,0,0", veil);
- break;
- }
- case "blur": {
- // Defocus blend: blur peaks mid-transition on both sides (isotropic
- // here vs ffmpeg's horizontal hblur — reads the same). Without
- // ctx.filter this degrades to the plain crossfade below.
- const supports = "filter" in ctx;
- const r = Math.max(0.5, (Math.min(W, H) / 24) * (1 - Math.abs(2 * p - 1)));
- if (supports) ctx.filter = `blur(${r.toFixed(2)}px)`;
- drawMaster();
- drawInc();
- if (supports) ctx.filter = "none";
- break;
- }
- case "pushleft":
- case "pushright":
- case "pushup":
- case "pushdown": {
- // Both frames travel together; the incoming clip shoves the outgoing
- // one off the named edge.
- const [mx, my, ix, iy] =
- style === "pushleft"
- ? [-p * W, 0, (1 - p) * W, 0]
- : style === "pushright"
- ? [p * W, 0, -(1 - p) * W, 0]
- : style === "pushup"
- ? [0, -p * H, 0, (1 - p) * H]
- : [0, p * H, 0, -(1 - p) * H];
- drawMaster({ ...d.masterFx, dx: d.masterFx.dx + mx, dy: d.masterFx.dy + my });
- drawInc(1, { dx: ix, dy: iy });
- break;
- }
- case "wipeleft":
- case "wiperight":
- case "wipeup":
- case "wipedown": {
- // Hard reveal edge traveling in the named direction.
- const r =
- style === "wipeleft"
- ? { x: (1 - p) * W, y: 0, w: p * W, h: H }
- : style === "wiperight"
- ? { x: 0, y: 0, w: p * W, h: H }
- : style === "wipeup"
- ? { x: 0, y: (1 - p) * H, w: W, h: p * H }
- : { x: 0, y: 0, w: W, h: p * H };
- drawMaster();
- clipped(
- () => ctx.rect(r.x, r.y, r.w, r.h),
- () => drawInc(1)
- );
- break;
- }
- case "circleopen": {
- drawMaster();
- clipped(
- () => ctx.arc(W / 2, H / 2, (p * Math.hypot(W, H)) / 2, 0, Math.PI * 2),
- () => drawInc(1)
- );
- break;
- }
- case "circleclose": {
- // The outgoing picture collapses into a shrinking circle over the
- // incoming one.
- drawInc(1);
- clipped(
- () => ctx.arc(W / 2, H / 2, ((1 - p) * Math.hypot(W, H)) / 2, 0, Math.PI * 2),
- () => drawMaster()
- );
- break;
- }
- case "splitopen": {
- // Barn doors part from the center.
- drawMaster();
- clipped(
- () => ctx.rect(((1 - p) * W) / 2, 0, p * W, H),
- () => drawInc(1)
- );
- break;
- }
- case "splitclose": {
- // The incoming picture closes in from both side edges.
- drawMaster();
- clipped(
- () => {
- ctx.rect(0, 0, (p * W) / 2, H);
- ctx.rect(W - (p * W) / 2, 0, (p * W) / 2, H);
- },
- () => drawInc(1)
- );
- break;
- }
- default: {
- // crossfade / crosszoom: the classic A·(1−α)+B·α blend (zooms already
- // folded into the layer zoom factors).
- drawMaster();
- drawInc();
- }
- }
- }
-
private overlayVideoFor(clip: VideoClip, asset: MediaAsset): MediaEl {
return this.elFor(this.overlayEls, clip.id, asset);
}
@@ -1037,19 +420,12 @@ class Engine {
* moments ahead of its entrance, close enough at the cut. Until the
* element has a decodable frame this draws nothing and the tick's black
* clear shows, same as before. */
- private drawBackdropFrame(span: ClipSpan, at: number) {
+ private drawBackdropFrame(span: ClipSpan, at: number, t: number) {
const el = this.videoFor(span.clip, span.asset);
if (!isImageEl(el) && el.paused && !el.seeking && Math.abs(el.currentTime - at) > 0.15) {
el.currentTime = Math.max(0, at);
}
- if (elReady(el)) this.drawLayer(el, span.clip, false, 1, 1);
- }
-
- private clearCanvas() {
- const ctx = this.canvas.getContext("2d");
- if (!ctx) return;
- ctx.fillStyle = "#000";
- ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
+ this.comp.drawLayer(this.frameOf(el), span.clip, false, 1, t);
}
/** Whole-video fade gain at time `t`: ramps 0→1 over the project fade-in and
@@ -1064,50 +440,15 @@ class Engine {
return Math.min(1, g);
}
- /** Paint an `amount` (0..1) color veil (`rgb` = "r,g,b") — over the whole
- * frame, or clipped to `rect` for a per-clip fade. Shared by the fade
- * animations, the dip transitions, and the whole-video project fade so
- * they can never drift apart. */
- private fillVeil(rgb: string, amount: number, rect?: FrameRect) {
- if (amount <= 0) return;
- const ctx = this.canvas.getContext("2d");
- if (!ctx) return;
- const W = this.canvas.width;
- const H = this.canvas.height;
- ctx.fillStyle = `rgba(${rgb},${Math.min(1, amount).toFixed(3)})`;
- if (rect) ctx.fillRect(rect.x * W, rect.y * H, rect.w * W, rect.h * H);
- else ctx.fillRect(0, 0, W, H);
- }
-
- private fillBlackVeil(amount: number, rect?: FrameRect) {
- this.fillVeil("0,0,0", amount, rect);
- }
-
- /** The picture side of the project fade: a black veil over the whole frame
- * (everything drawn this tick, on every track, at any time), matching the
- * export's fade on the final composite. */
- private drawProjectFade(gain: number) {
- this.fillBlackVeil(1 - gain);
- }
-
- /** 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. */
+ /** Overlay clips live at time `t`, with their assets and transition ramps,
+ * in draw order. */
private liveOverlays(t: number) {
const s = useEditor.getState();
- 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;
+ return overlayPlan(
+ [...new Set(overlayLayers(s.clips).map((c) => c.track))],
+ (track) => getClipSpans(s.clips, s.assets, track),
+ t
+ );
}
/** Seek/rate/play one overlay clip's element toward its frame at timeline
@@ -1166,7 +507,7 @@ class Engine {
if (!elReady(el)) continue;
const rect = rectOf(clip);
const cover = clip.fit === "fill" || (clip.fit == null && isFullRect(rect));
- this.drawIntoRect(el, rect, cover, alpha, zoom, clip);
+ this.comp.drawIntoRect(this.frameOf(el), rect, cover, alpha, t, zoom, clip);
}
}
@@ -1268,7 +609,7 @@ class Engine {
// clock, so the guard must not bail on `spans.length === 0` alone.
if (spans.length === 0 && overlayLayers(s.clips).length === 0 && s.audioClips.length === 0) {
this.pauseExcept(new Set());
- this.drawLayer(null, undefined, true, 1);
+ this.comp.drawLayer(MISSING_FRAME, undefined, true, 1, 0);
this.syncSoundtrack(0, false);
if (s.playing) useEditor.setState({ playing: false, currentTime: 0 });
return;
@@ -1326,13 +667,13 @@ class Engine {
return;
}
const active = new Set<string>();
- this.clearCanvas();
+ this.comp.clear();
// Where track 0 has nothing live there is no master frame — just black
// and the other tracks still running at `pt`.
if (span) this.composite(span, spans, Math.min(pt, span.start + span.len), false);
else this.pauseExcept(new Set());
this.drawOverlays(pt, false, active, overlaysLive);
- this.drawProjectFade(this.projectFadeGain(pt, total));
+ this.comp.drawProjectFade(this.projectFadeGain(pt, total));
this.cleanupOverlays(active);
this.syncSoundtrack(t, false);
return;
@@ -1358,7 +699,7 @@ class Engine {
// Clear to black, then prime the master element (and any dissolve
// partner) over it and read the clock.
const active = new Set<string>();
- this.clearCanvas();
+ this.comp.clear();
if (span) {
let el = this.composite(span, spans, t, true);
@@ -1413,7 +754,7 @@ class Engine {
useEditor.setState({ playing: false, currentTime: total, previewStopAt: null });
pauseEl(el);
this.drawOverlays(t, true, active);
- this.drawProjectFade(this.projectFadeGain(total, total));
+ this.comp.drawProjectFade(this.projectFadeGain(total, total));
this.cleanupOverlays(active);
this.syncSoundtrack(total, false);
return;
@@ -1431,7 +772,7 @@ class Engine {
if (t >= total - 0.001) {
useEditor.setState({ playing: false, currentTime: total, previewStopAt: null });
this.drawOverlays(t, true, active);
- this.drawProjectFade(this.projectFadeGain(total, total));
+ this.comp.drawProjectFade(this.projectFadeGain(total, total));
this.cleanupOverlays(active);
this.syncSoundtrack(total, false);
return;
@@ -1451,7 +792,7 @@ class Engine {
if (!isImageEl(el)) el.volume = Math.min(el.volume, fadeGain);
}
}
- this.drawProjectFade(fadeGain);
+ this.comp.drawProjectFade(fadeGain);
this.cleanupOverlays(active);
// A scoped effect preview auto-pauses at its stop mark (the frame this
// tick just painted is the stop frame — close enough at tick rate).
diff --git a/site/src/cut/lib/composite.ts b/site/src/cut/lib/composite.ts
new file mode 100644
index 00000000..1d2ca9bf
--- /dev/null
+++ b/site/src/cut/lib/composite.ts
@@ -0,0 +1,574 @@
+"use client";
+
+/**
+ * Painting one frame of the cut.
+ *
+ * This is the whole picture side of Cut in one place: how a clip's grade and
+ * look become pixels, how a transition's geometry joins two clips, how a
+ * region, a pan, a zoom, and a fade land on the frame. It knows nothing about
+ * where the pixels came from — a caller hands it a `Frame` and it draws.
+ *
+ * That indifference is the point. The live preview feeds it video elements it
+ * is steering in real time; an export feeds it decoded frames it pulled at an
+ * exact timestamp. Both draw through this same code, so what the editor shows
+ * and what the file contains cannot drift apart by one being taught something
+ * the other wasn't.
+ *
+ * Time is a parameter rather than a reading of the clock, which is what makes
+ * an export deterministic: film grain at 4.5 seconds is the same grain whether
+ * it was reached by playing there or by rendering the 135th frame.
+ */
+
+import { gradeTint, gradeToCssFilter, isNeutralGrade } from "./colorGrade";
+import { grainTile, lookCssFilter, lookPost } from "./looks";
+import { isFullRect, rectOf } from "./types";
+import type { FrameRect, TransitionStyle, VideoClip } from "./types";
+
+/** A clip's picture at some instant, or the reasons there isn't one.
+ *
+ * `missing` and `pending` differ in what they do to the frame: a clip with
+ * nothing to draw yields to whatever should be behind it, while a clip whose
+ * decoder just hasn't caught up keeps the last frame on screen. Painting black
+ * for the second one is what strobing looks like while skimming.
+ */
+export type Frame =
+ | { kind: "missing" }
+ | { kind: "pending" }
+ | { kind: "ready"; image: CanvasImageSource; width: number; height: number };
+
+export const MISSING_FRAME: Frame = { kind: "missing" };
+export const PENDING_FRAME: Frame = { kind: "pending" };
+
+/** Frame motion a transition or animation puts on a layer, in canvas pixels. */
+export interface LayerFx {
+ dx?: number;
+ dy?: number;
+}
+
+/** The two clips a transition joins, each with its ramps already resolved. */
+export interface CrossJoin {
+ masterFrame: Frame;
+ masterClip: VideoClip;
+ masterAlpha: number;
+ masterZoom: number;
+ masterFx: { dx: number; dy: number };
+ incFrame: Frame;
+ incClip: VideoClip | undefined;
+ incAlpha: number;
+ incZoom: number;
+}
+
+/** Canvas kinds the compositor can draw onto and allocate beside. */
+type Surface = HTMLCanvasElement | OffscreenCanvas;
+type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+
+/** The grain tile advances on this cadence, in seconds per step. */
+const GRAIN_STEP = 0.08;
+
+export class FrameCompositor {
+ /** Scratch buffers, kept for the compositor's life: the grade pass, the
+ * look's self-copy passes, and the vignette gradient. Allocating these per
+ * frame is the difference between a preview that holds 60fps and one that
+ * fights the garbage collector. */
+ private gradeCanvas: Surface | null = null;
+ private lookScratch: Surface | null = null;
+ private vignetteCanvas: Surface | null = null;
+
+ constructor(private canvas: Surface) {}
+
+ /** Point the compositor at a different surface, keeping the scratch buffers. */
+ setCanvas(canvas: Surface) {
+ this.canvas = canvas;
+ }
+
+ get width() {
+ return this.canvas.width;
+ }
+
+ get height() {
+ return this.canvas.height;
+ }
+
+ private ctx(): Ctx | null {
+ return this.canvas.getContext("2d") as Ctx | null;
+ }
+
+ /** A scratch surface of exactly `w`×`h`, reused across frames. Returns
+ * whether it had to be resized — which also cleared it, since setting a
+ * canvas dimension wipes its contents. */
+ private scratch(
+ field: "gradeCanvas" | "lookScratch" | "vignetteCanvas",
+ w: number,
+ h: number
+ ): { surface: Surface; resized: boolean } {
+ let surface = this[field];
+ if (!surface) {
+ surface =
+ typeof document === "undefined"
+ ? new OffscreenCanvas(Math.max(1, w), Math.max(1, h))
+ : document.createElement("canvas");
+ this[field] = surface;
+ }
+ // Match both dimensions — a transition alternates two differently-sized
+ // sources through one scratch every frame, and a stale dimension leaves the
+ // previous clip's pixels in the draw.
+ const resized = surface.width !== w || surface.height !== h;
+ if (surface.width !== w) surface.width = w;
+ if (surface.height !== h) surface.height = h;
+ return { surface, resized };
+ }
+
+ clear() {
+ const ctx = this.ctx();
+ if (!ctx) return;
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
+ }
+
+ /**
+ * Paint an `amount` (0..1) color veil (`rgb` = "r,g,b") — over the whole
+ * frame, or clipped to `rect` for a per-clip fade. Shared by the fade
+ * animations, the dip transitions, and the whole-video project fade so they
+ * can never drift apart.
+ */
+ fillVeil(rgb: string, amount: number, rect?: FrameRect) {
+ if (amount <= 0) return;
+ const ctx = this.ctx();
+ if (!ctx) return;
+ const W = this.canvas.width;
+ const H = this.canvas.height;
+ ctx.fillStyle = `rgba(${rgb},${Math.min(1, amount).toFixed(3)})`;
+ if (rect) ctx.fillRect(rect.x * W, rect.y * H, rect.w * W, rect.h * H);
+ else ctx.fillRect(0, 0, W, H);
+ }
+
+ fillBlackVeil(amount: number, rect?: FrameRect) {
+ this.fillVeil("0,0,0", amount, rect);
+ }
+
+ /** The picture side of the project fade: a black veil over the whole frame —
+ * everything drawn this tick, on every track, at any time — matching the
+ * export's fade on the final composite. */
+ drawProjectFade(gain: number) {
+ this.fillBlackVeil(1 - gain);
+ }
+
+ /**
+ * The clip's picture with its color grade and look grading applied, or the
+ * raw image when there is nothing to apply. Mirrors the export's chain order
+ * — grade first (lutrgb/hue), then the look's color pass — as CSS filters,
+ * with the grade's warm tint as a multiply pass, and source alpha restored so
+ * transparent stills keep their transparency. The look's post passes
+ * (vignette, grain, glow…) draw over the composited layer instead.
+ */
+ private gradedSource(
+ frame: Extract<Frame, { kind: "ready" }>,
+ clip: VideoClip | undefined
+ ): CanvasImageSource {
+ const grade = clip?.grade;
+ const lookCss = lookCssFilter(clip?.look, clip?.lookAmount);
+ if (isNeutralGrade(grade) && !lookCss) return frame.image;
+ const w = frame.width;
+ const h = frame.height;
+ const { surface: scratch } = this.scratch("gradeCanvas", w, h);
+ const ctx = scratch.getContext("2d") as Ctx | null;
+ // Without ctx.filter support, skip the whole treatment rather than
+ // half-applying the tint.
+ if (!ctx || !("filter" in ctx)) return frame.image;
+ ctx.clearRect(0, 0, w, h);
+ ctx.filter = [gradeToCssFilter(grade), lookCss].filter(Boolean).join(" ") || "none";
+ ctx.drawImage(frame.image, 0, 0, w, h);
+ ctx.filter = "none";
+ const tint = gradeTint(grade);
+ if (tint) {
+ ctx.globalCompositeOperation = "multiply";
+ ctx.fillStyle = tint;
+ ctx.fillRect(0, 0, w, h);
+ // Multiply painted the transparent areas solid; carve the source's alpha
+ // back in.
+ ctx.globalCompositeOperation = "destination-in";
+ ctx.drawImage(frame.image, 0, 0, w, h);
+ ctx.globalCompositeOperation = "source-over";
+ }
+ return scratch;
+ }
+
+ /**
+ * Draw a look's post passes over one composited layer's footprint (canvas
+ * pixels): vignette, animated grain, self-copy glow, color washes, chroma
+ * ghosts. `alpha` follows the layer so a dissolving clip's grain dissolves
+ * with it, and `at` drives the grain so the same second of the cut always
+ * grains the same way. Every buffer here is cached — no per-frame allocation
+ * or pixel reads.
+ */
+ private applyLookPost(
+ clip: VideoClip | undefined,
+ rx: number,
+ ry: number,
+ rw: number,
+ rh: number,
+ alpha: number,
+ at: number
+ ) {
+ const post = lookPost(clip?.look, clip?.lookAmount);
+ if (!post || alpha <= 0 || rw <= 0 || rh <= 0) return;
+ const ctx = this.ctx();
+ if (!ctx || !("filter" in ctx)) return;
+ const W = this.canvas.width;
+ const H = this.canvas.height;
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(rx, ry, rw, rh);
+ ctx.clip();
+ if (post.glow) {
+ // Copy the just-drawn region through a blur (and a highlight isolation
+ // for halation) and lay it back over itself.
+ const { surface: scratch } = this.scratch("lookScratch", W, H);
+ const sctx = scratch.getContext("2d") as Ctx | null;
+ if (sctx && "filter" in sctx) {
+ const blurPx = Math.max(1, post.glow.blurFrac * H);
+ sctx.clearRect(rx, ry, rw, rh);
+ sctx.filter = post.glow.bright
+ ? `contrast(2.5) brightness(0.55) saturate(1.4) sepia(0.35) blur(${blurPx}px)`
+ : `blur(${blurPx}px)`;
+ sctx.drawImage(this.canvas, rx, ry, rw, rh, rx, ry, rw, rh);
+ sctx.filter = "none";
+ ctx.globalAlpha = post.glow.alpha * alpha;
+ ctx.globalCompositeOperation = post.glow.mode;
+ ctx.drawImage(scratch, rx, ry, rw, rh, rx, ry, rw, rh);
+ }
+ }
+ if (post.ghost) {
+ // VHS chroma fringing: warm and cool copies of the region nudged apart.
+ const { surface: scratch } = this.scratch("lookScratch", W, H);
+ const sctx = scratch.getContext("2d") as Ctx | null;
+ if (sctx && "filter" in sctx) {
+ const shift = Math.max(1, post.ghost.shiftFrac * W);
+ sctx.clearRect(rx, ry, rw, rh);
+ sctx.filter = "sepia(1) saturate(4) hue-rotate(-40deg) brightness(0.55)";
+ sctx.drawImage(this.canvas, rx, ry, rw, rh, rx, ry, rw, rh);
+ sctx.filter = "none";
+ ctx.globalAlpha = post.ghost.alpha * alpha;
+ ctx.globalCompositeOperation = "lighter";
+ ctx.drawImage(scratch, rx, ry, rw, rh, rx + shift, ry, rw, rh);
+ sctx.clearRect(rx, ry, rw, rh);
+ sctx.filter = "sepia(1) saturate(4) hue-rotate(140deg) brightness(0.55)";
+ sctx.drawImage(this.canvas, rx, ry, rw, rh, rx, ry, rw, rh);
+ sctx.filter = "none";
+ ctx.drawImage(scratch, rx, ry, rw, rh, rx - shift, ry, rw, rh);
+ }
+ }
+ ctx.globalCompositeOperation = "source-over";
+ for (const wash of post.washes ?? []) {
+ ctx.globalAlpha = wash.alpha * alpha;
+ ctx.globalCompositeOperation = wash.mode;
+ ctx.fillStyle = wash.color;
+ ctx.fillRect(rx, ry, rw, rh);
+ }
+ if (post.grain) {
+ const tile = grainTile(Math.floor(at / GRAIN_STEP));
+ if (tile) {
+ ctx.globalAlpha = post.grain * alpha;
+ ctx.globalCompositeOperation = "overlay";
+ for (let y = ry; y < ry + rh; y += tile.height) {
+ for (let x = rx; x < rx + rw; x += tile.width) {
+ ctx.drawImage(tile, x, y);
+ }
+ }
+ }
+ }
+ if (post.vignette) {
+ // Cached radial gradient, rebuilt only when the footprint size changes.
+ const vw = Math.max(1, Math.round(rw));
+ const vh = Math.max(1, Math.round(rh));
+ const { surface: vg, resized } = this.scratch("vignetteCanvas", vw, vh);
+ if (resized) {
+ const vctx = vg.getContext("2d") as Ctx | null;
+ if (vctx) {
+ const g = vctx.createRadialGradient(
+ vw / 2,
+ vh / 2,
+ Math.min(vw, vh) * 0.35,
+ vw / 2,
+ vh / 2,
+ Math.hypot(vw, vh) / 2
+ );
+ g.addColorStop(0, "rgba(0,0,0,0)");
+ g.addColorStop(1, "rgba(0,0,0,1)");
+ vctx.clearRect(0, 0, vw, vh);
+ vctx.fillStyle = g;
+ vctx.fillRect(0, 0, vw, vh);
+ }
+ }
+ ctx.globalAlpha = post.vignette * alpha;
+ ctx.globalCompositeOperation = "source-over";
+ ctx.drawImage(vg, rx, ry, rw, rh);
+ }
+ ctx.restore();
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = "source-over";
+ }
+
+ /** Draw a frame into a sub-rectangle of the canvas (a split-screen half, an
+ * overlay's region), fitted or filled. */
+ drawIntoRect(
+ frame: Frame,
+ rect: FrameRect,
+ fill: boolean,
+ alpha: number,
+ at: number,
+ zoom = 1,
+ clip?: VideoClip
+ ) {
+ if (frame.kind !== "ready") return;
+ const ctx = this.ctx();
+ 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 vw = frame.width;
+ const vh = frame.height;
+ const sc = (fill ? Math.max(rw / vw, rh / vh) : Math.min(rw / vw, rh / vh)) * zoom;
+ const dw = vw * sc;
+ const dh = vh * sc;
+ const dx = rx + (rw - dw) / 2;
+ const dy = ry + (rh - dh) / 2;
+ const src = this.gradedSource(frame, clip);
+ const prevAlpha = ctx.globalAlpha;
+ ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
+ if (fill || zoom > 1) {
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(rx, ry, rw, rh);
+ ctx.clip();
+ ctx.drawImage(src, dx, dy, dw, dh);
+ ctx.restore();
+ } else {
+ ctx.drawImage(src, dx, dy, dw, dh);
+ }
+ ctx.globalAlpha = prevAlpha;
+ this.applyLookPost(clip, rx, ry, rw, rh, alpha, at);
+ }
+
+ /**
+ * Draw one clip's layer over the frame, honouring its region, fit, pan, zoom,
+ * alpha and any frame motion a transition puts on it.
+ *
+ * `clear` says this layer owns the black behind it. A layer with nothing to
+ * draw takes the black with it; a layer whose picture merely hasn't arrived
+ * leaves the frame as it stands.
+ */
+ drawLayer(
+ frame: Frame,
+ clip: VideoClip | undefined,
+ clear: boolean,
+ alpha: number,
+ at: number,
+ zoom = 1,
+ fx?: LayerFx
+ ) {
+ const ctx = this.ctx();
+ if (!ctx) return;
+ const W = this.canvas.width;
+ const H = this.canvas.height;
+ const blank = () => {
+ if (clear) {
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, W, H);
+ }
+ };
+ // A hidden clip plays nothing, and a clip with no picture at all yields the
+ // frame; both fill black only when they own the clear.
+ if (frame.kind === "missing" || clip?.hidden) return blank();
+ // Mid-seek there is no decodable frame; keep the previous one on the canvas
+ // instead of strobing black (matters while skimming).
+ if (frame.kind === "pending") return;
+ blank();
+
+ const hasFx = !!fx && (!!fx.dx || !!fx.dy);
+ if (hasFx) {
+ // Motion runs in full-canvas space — the export translates the whole
+ // padded segment frame, so a regioned clip rides along with it.
+ // Whole-pixel translation: a fractional offset antialiases both frame
+ // edges and draws a hairline seam where a push's frames meet.
+ ctx.save();
+ ctx.translate(Math.round(fx.dx ?? 0), Math.round(fx.dy ?? 0));
+ }
+ // A regioned track-0 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(frame, rect, clip?.fit === "fill", alpha, at, zoom, clip);
+ if (hasFx) ctx.restore();
+ return;
+ }
+ const fill = clip?.fit === "fill";
+ const vw = frame.width;
+ const vh = frame.height;
+ const scale = (fill ? Math.max(W / vw, H / vh) : Math.min(W / vw, H / vh)) * zoom;
+ const dw = vw * scale;
+ const dh = vh * scale;
+ let dx = (W - dw) / 2;
+ let dy = (H - dh) / 2;
+ if (fill) {
+ // Pan the crop window across the overflow (matches the export crop).
+ const kx = 0.5 + (clip?.panX ?? 0) / 2;
+ const ky = 0.5 + (clip?.panY ?? 0) / 2;
+ dx = -(dw - W) * kx;
+ dy = -(dh - H) * ky;
+ }
+ const prevAlpha = ctx.globalAlpha;
+ ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
+ ctx.drawImage(this.gradedSource(frame, clip), dx, dy, dw, dh);
+ ctx.globalAlpha = prevAlpha;
+ this.applyLookPost(clip, 0, 0, W, H, alpha, at);
+ if (hasFx) ctx.restore();
+ }
+
+ /**
+ * Draw the outgoing and incoming clips of a transition at progress `p`
+ * (0..1), in the geometry the style calls for: a blend, a dip through a
+ * colour, a push, a wipe, or a shape reveal.
+ */
+ drawCrossJoin(style: TransitionStyle, p: number, d: CrossJoin, at: number) {
+ const ctx = this.ctx();
+ if (!ctx) return;
+ const W = this.canvas.width;
+ const H = this.canvas.height;
+ const drawMaster = (fx = d.masterFx, alpha = d.masterAlpha) =>
+ this.drawLayer(d.masterFrame, d.masterClip, false, alpha, at, d.masterZoom, fx);
+ // The blend styles ramp the incoming alpha; the geometric styles draw it
+ // opaque inside their own moving region.
+ const drawInc = (alpha = d.incAlpha, fx?: LayerFx) => {
+ this.drawLayer(d.incFrame, d.incClip, false, alpha, at, d.incZoom, fx);
+ };
+ const clipped = (path: () => void, draw: () => void) => {
+ ctx.save();
+ ctx.beginPath();
+ path();
+ ctx.clip();
+ draw();
+ ctx.restore();
+ };
+ // Only the absence of an incoming clip cancels the transition. One whose
+ // picture merely hasn't decoded yet still runs its style: the geometry —
+ // a dip's veil, a circle's clip path — is what the frame should look like
+ // mid-transition, and skipping it flashes the outgoing clip at full
+ // brightness for as long as the decoder lags. `drawLayer` declines to draw
+ // the pending picture itself.
+ if (d.incFrame.kind === "missing" || p <= 0) {
+ drawMaster();
+ return;
+ }
+ switch (style) {
+ case "dipblack":
+ case "dipwhite": {
+ // Matches xfade fadeblack/fadewhite's measured plateau: out by ~30%,
+ // solid to ~60%, in over the rest.
+ const veil = Math.max(0, Math.min(1, Math.min(p / 0.3, (1 - p) / 0.4)));
+ if (p < 0.45) drawMaster();
+ else drawInc(1);
+ this.fillVeil(style === "dipwhite" ? "255,255,255" : "0,0,0", veil);
+ break;
+ }
+ case "blur": {
+ // Defocus blend: blur peaks mid-transition on both sides (isotropic
+ // here vs ffmpeg's horizontal hblur — reads the same). Without
+ // ctx.filter this degrades to the plain crossfade below.
+ const supports = "filter" in ctx;
+ const r = Math.max(0.5, (Math.min(W, H) / 24) * (1 - Math.abs(2 * p - 1)));
+ if (supports) ctx.filter = `blur(${r.toFixed(2)}px)`;
+ drawMaster();
+ drawInc();
+ if (supports) ctx.filter = "none";
+ break;
+ }
+ case "pushleft":
+ case "pushright":
+ case "pushup":
+ case "pushdown": {
+ // Both frames travel together; the incoming clip shoves the outgoing
+ // one off the named edge.
+ const [mx, my, ix, iy] =
+ style === "pushleft"
+ ? [-p * W, 0, (1 - p) * W, 0]
+ : style === "pushright"
+ ? [p * W, 0, -(1 - p) * W, 0]
+ : style === "pushup"
+ ? [0, -p * H, 0, (1 - p) * H]
+ : [0, p * H, 0, -(1 - p) * H];
+ drawMaster({ ...d.masterFx, dx: d.masterFx.dx + mx, dy: d.masterFx.dy + my });
+ drawInc(1, { dx: ix, dy: iy });
+ break;
+ }
+ case "wipeleft":
+ case "wiperight":
+ case "wipeup":
+ case "wipedown": {
+ // Hard reveal edge traveling in the named direction.
+ const r =
+ style === "wipeleft"
+ ? { x: (1 - p) * W, y: 0, w: p * W, h: H }
+ : style === "wiperight"
+ ? { x: 0, y: 0, w: p * W, h: H }
+ : style === "wipeup"
+ ? { x: 0, y: (1 - p) * H, w: W, h: p * H }
+ : { x: 0, y: 0, w: W, h: p * H };
+ drawMaster();
+ clipped(
+ () => ctx.rect(r.x, r.y, r.w, r.h),
+ () => drawInc(1)
+ );
+ break;
+ }
+ case "circleopen": {
+ drawMaster();
+ clipped(
+ () => ctx.arc(W / 2, H / 2, (p * Math.hypot(W, H)) / 2, 0, Math.PI * 2),
+ () => drawInc(1)
+ );
+ break;
+ }
+ case "circleclose": {
+ // The outgoing picture collapses into a shrinking circle over the
+ // incoming one.
+ drawInc(1);
+ clipped(
+ () => ctx.arc(W / 2, H / 2, ((1 - p) * Math.hypot(W, H)) / 2, 0, Math.PI * 2),
+ () => drawMaster()
+ );
+ break;
+ }
+ case "splitopen": {
+ // Barn doors part from the center.
+ drawMaster();
+ clipped(
+ () => ctx.rect(((1 - p) * W) / 2, 0, p * W, H),
+ () => drawInc(1)
+ );
+ break;
+ }
+ case "splitclose": {
+ // The incoming picture closes in from both side edges.
+ drawMaster();
+ clipped(
+ () => {
+ ctx.rect(0, 0, (p * W) / 2, H);
+ ctx.rect(W - (p * W) / 2, 0, (p * W) / 2, H);
+ },
+ () => drawInc(1)
+ );
+ break;
+ }
+ default: {
+ // crossfade / crosszoom: the classic A·(1−α)+B·α blend (zooms already
+ // folded into the layer zoom factors).
+ drawMaster();
+ drawInc();
+ }
+ }
+ }
+}
diff --git a/site/src/cut/lib/framePlan.test.ts b/site/src/cut/lib/framePlan.test.ts
new file mode 100644
index 00000000..ef9c37f0
--- /dev/null
+++ b/site/src/cut/lib/framePlan.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, test } from "bun:test";
+import { clipAnimFx, duckGainAt, trackZeroPlan } from "./framePlan";
+import { TRANSITION_ZOOM } from "./types";
+import type { AudioClip, ClipSpan, MediaAsset, VideoClip } from "./types";
+
+const asset: MediaAsset = {
+ id: "asset",
+ fileName: "a.mp4",
+ name: "a",
+ type: "video",
+ duration: 100,
+ url: "blob:a",
+};
+
+let nextId = 0;
+const videoClip = (over: Partial<VideoClip> = {}): VideoClip => ({
+ id: `clip-${nextId++}`,
+ assetId: "asset",
+ track: 0,
+ start: 0,
+ in: 0,
+ out: 4,
+ muted: false,
+ ...over,
+});
+
+/** Spans laid end to end, each dissolving into the next by `transitions[i]`. */
+function spansOf(count: number, len = 4, transitions: number[] = []): ClipSpan[] {
+ const spans: ClipSpan[] = [];
+ let at = 0;
+ for (let i = 0; i < count; i++) {
+ const transitionOut = transitions[i] ?? 0;
+ spans.push({
+ clip: videoClip({ start: at, out: len }),
+ asset,
+ start: at,
+ len,
+ transitionOut,
+ });
+ at += len - transitionOut;
+ }
+ return spans;
+}
+
+describe("trackZeroPlan", () => {
+ test("reports no transition in the middle of a clip", () => {
+ const spans = spansOf(2);
+ const plan = trackZeroPlan(spans[0], spans, 2);
+ expect(plan.p).toBe(0);
+ expect(plan.incoming).toBe(null);
+ expect(plan.masterAlpha).toBe(1);
+ expect(plan.masterZoom).toBe(1);
+ });
+
+ test("ramps a dissolve from 0 to 1 across the overlap", () => {
+ const spans = spansOf(2, 4, [2]);
+ const start = spans[1].start;
+ expect(trackZeroPlan(spans[0], spans, start).p).toBeCloseTo(0, 5);
+ expect(trackZeroPlan(spans[0], spans, start + 1).p).toBeCloseTo(0.5, 5);
+ expect(trackZeroPlan(spans[0], spans, start + 2).p).toBeCloseTo(1, 5);
+ });
+
+ test("names the incoming clip only while its overlap is live", () => {
+ const spans = spansOf(2, 4, [2]);
+ expect(trackZeroPlan(spans[0], spans, spans[1].start - 0.1).incoming).toBe(null);
+ expect(trackZeroPlan(spans[0], spans, spans[1].start + 0.1).incoming).toBe(spans[1]);
+ });
+
+ test("pushes the outgoing clip in and settles the incoming one on a cross zoom", () => {
+ const spans = spansOf(2, 4, [2]);
+ spans[0].clip.transitionStyle = "crosszoom";
+ const mid = trackZeroPlan(spans[0], spans, spans[1].start + 1);
+ expect(mid.masterZoom).toBeCloseTo(1 + (TRANSITION_ZOOM - 1) * 0.5, 5);
+ expect(mid.incZoom).toBeCloseTo(TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * 0.5, 5);
+ });
+
+ test("veils a fade-in from black at the head of the timeline", () => {
+ const spans = spansOf(1);
+ spans[0].clip.animIn = { style: "fade", seconds: 1 };
+ expect(trackZeroPlan(spans[0], spans, 0).veil).toBeCloseTo(1, 5);
+ expect(trackZeroPlan(spans[0], spans, 0.5).veil).toBeCloseTo(0.5, 5);
+ expect(trackZeroPlan(spans[0], spans, 1).veil).toBe(0);
+ });
+
+ test("holds an animation on the side a transition already owns", () => {
+ const spans = spansOf(2, 4, [2]);
+ // The second clip's entrance sits inside the dissolve, so the dissolve
+ // plays there and the animation stands down.
+ spans[1].clip.animIn = { style: "fade", seconds: 1 };
+ const plan = trackZeroPlan(spans[1], spans, spans[1].start + 0.2);
+ expect(plan.veil).toBe(0);
+ expect(plan.masterAlpha).toBe(1);
+ });
+
+ test("puts the previous clip's frame behind a fade at an abutting cut", () => {
+ const spans = spansOf(2);
+ spans[1].clip.animIn = { style: "fade", seconds: 1 };
+ const plan = trackZeroPlan(spans[1], spans, spans[1].start + 0.2);
+ expect(plan.backdrop?.span).toBe(spans[0]);
+ // With something behind it the fade blends by alpha rather than to black.
+ expect(plan.masterAlpha).toBeLessThan(1);
+ expect(plan.veil).toBe(0);
+ });
+
+ test("has no backdrop for a zoom, which covers the frame anyway", () => {
+ const spans = spansOf(2);
+ spans[1].clip.animIn = { style: "zoom", seconds: 1 };
+ expect(trackZeroPlan(spans[1], spans, spans[1].start + 0.2).backdrop).toBe(null);
+ });
+
+ test("flags the next clip once it is close enough to warm", () => {
+ const spans = spansOf(2);
+ expect(trackZeroPlan(spans[0], spans, 1).upcoming).toBe(null);
+ expect(trackZeroPlan(spans[0], spans, spans[1].start - 0.2).upcoming).toBe(spans[1]);
+ });
+});
+
+describe("clipAnimFx", () => {
+ test("leaves a clip alone outside its animation windows", () => {
+ const fx = clipAnimFx(videoClip({ animIn: { style: "fade", seconds: 1 } }), 2, 4);
+ expect(fx).toEqual({ alpha: 1, zoom: 1, gain: 1, veil: 0, dxFrac: 0, dyFrac: 0 });
+ });
+
+ test("drops the audio with the picture through a fade", () => {
+ const fx = clipAnimFx(videoClip({ animIn: { style: "fade", seconds: 2 } }), 0.5, 4);
+ expect(fx.gain).toBeCloseTo(0.25, 5);
+ expect(fx.veil).toBeCloseTo(0.75, 5);
+ });
+
+ test("slides the frame in from the right and out to the left", () => {
+ const clip = videoClip({
+ animIn: { style: "slideleft", seconds: 1 },
+ animOut: { style: "slideleft", seconds: 1 },
+ });
+ // Enters a full frame to the right, settles at 0, then leaves to the left.
+ expect(clipAnimFx(clip, 0, 4).dxFrac).toBeCloseTo(1, 5);
+ expect(clipAnimFx(clip, 1, 4).dxFrac).toBeCloseTo(0, 5);
+ expect(clipAnimFx(clip, 3.5, 4).dxFrac).toBeCloseTo(-0.5, 5);
+ expect(clipAnimFx(clip, 4, 4).dxFrac).toBeCloseTo(-1, 5);
+ });
+
+ test("treats a style it does not know as a fade", () => {
+ const fx = clipAnimFx(
+ videoClip({ animIn: { style: "kaleidoscope" as never, seconds: 2 } }),
+ 0,
+ 4
+ );
+ expect(fx.veil).toBeCloseTo(1, 5);
+ });
+
+ test("clamps an animation longer than the clip to the clip", () => {
+ const fx = clipAnimFx(videoClip({ animIn: { style: "fade", seconds: 10 } }), 1, 2);
+ expect(fx.veil).toBeCloseTo(0.5, 5);
+ });
+});
+
+describe("duckGainAt", () => {
+ const voice = (over: Partial<AudioClip> = {}): AudioClip => ({
+ id: "vo",
+ assetId: "asset",
+ start: 1,
+ in: 0,
+ out: 3,
+ volume: 1,
+ duck: 0.2,
+ ...over,
+ });
+
+ test("is 1 with no ducking clip live", () => {
+ expect(duckGainAt([voice()], 0)).toBe(1);
+ expect(duckGainAt([voice()], 5)).toBe(1);
+ });
+
+ test("drops to the duck while the voiceover speaks", () => {
+ expect(duckGainAt([voice()], 2)).toBeCloseTo(0.2, 5);
+ });
+
+ test("takes the deepest duck when two overlap", () => {
+ expect(duckGainAt([voice(), voice({ id: "b", duck: 0.05 })], 2)).toBeCloseTo(0.05, 5);
+ });
+
+ test("ignores a hidden clip", () => {
+ expect(duckGainAt([voice({ hidden: true })], 2)).toBe(1);
+ });
+});
diff --git a/site/src/cut/lib/framePlan.ts b/site/src/cut/lib/framePlan.ts
new file mode 100644
index 00000000..55d43778
--- /dev/null
+++ b/site/src/cut/lib/framePlan.ts
@@ -0,0 +1,341 @@
+"use client";
+
+/**
+ * What the cut looks like at one instant, worked out from the document alone.
+ *
+ * Given the clips and a time, this says which pictures are on screen, how far
+ * through a transition they are, what each one's alpha, zoom and frame motion
+ * come to, and how loud it should be. It touches no decoder, no canvas and no
+ * clock, which is what lets the live preview and an export ask the same
+ * question and be given the same answer.
+ *
+ * Keeping it apart from both matters more than it looks. The preview reaches
+ * this state by playing towards it; an export reaches it by jumping straight
+ * there. If each worked out its own ramps, a fade would be a fade in the editor
+ * and something slightly else in the file, and nobody would find out until they
+ * watched the download.
+ */
+
+import { overlayAnimStyle, TRANSITION_ZOOM } from "./types";
+import type { AudioClip, ClipAnim, ClipSpan, MediaAsset, TransitionStyle, VideoClip } from "./types";
+
+/** The ramps a transition or clip animation puts on one upper-track clip. */
+export interface OverlayFx {
+ alpha: number;
+ zoom: number;
+ gain: number;
+}
+
+/**
+ * The alpha/zoom/gain ramps a transition or clip animation puts on one
+ * upper-track clip at `t`. A transition blends the incoming clip in over the
+ * outgoing one (which keeps full alpha and its audio until its footprint
+ * ends); a clip animation ramps the clip's own edge. On an upper track a fade
+ * ramps to transparent — the tracks beneath show through — and the animation
+ * styles that need frame motion degrade to a fade, both matching the export's
+ * alpha ramps.
+ */
+export function overlayTransitionFx(
+ span: ClipSpan,
+ prev: ClipSpan | undefined,
+ next: ClipSpan | undefined,
+ t: number
+): OverlayFx {
+ 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 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;
+ }
+ // The clip's own entrance/exit animations. A transitioned joint owns its
+ // edges: the transition plays there and the adjacent animation is held
+ // (running both would fight over the same window).
+ if (span.clip.animIn && !(prev && prev.transitionOut > 0)) {
+ const d = Math.min(span.clip.animIn.seconds, span.len);
+ const rel = t - span.start;
+ if (d > 0 && rel < d) {
+ const p = Math.max(0, rel / d);
+ if (overlayAnimStyle(span.clip.animIn.style) === "zoom") {
+ zoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;
+ } else {
+ alpha = Math.min(alpha, p);
+ gain = Math.min(gain, p);
+ }
+ }
+ }
+ if (span.clip.animOut && span.transitionOut <= 0) {
+ const d = Math.min(span.clip.animOut.seconds, span.len);
+ const left = span.start + span.len - t;
+ if (d > 0 && left < d) {
+ const p = Math.max(0, left / d);
+ if (overlayAnimStyle(span.clip.animOut.style) === "zoom") {
+ zoom = 1 + (TRANSITION_ZOOM - 1) * (1 - p);
+ } else {
+ alpha = Math.min(alpha, p);
+ gain = Math.min(gain, p);
+ }
+ }
+ }
+ return { alpha, zoom, gain };
+}
+
+/** A track-0 clip's animation state: what its entrance/exit does to the frame. */
+export interface ClipAnimFx {
+ alpha: number;
+ zoom: number;
+ gain: number;
+ /** Fade-to-black amount, painted by the caller's veil pass. */
+ veil: number;
+ /** Frame translation, as a fraction of canvas width/height. */
+ dxFrac: number;
+ dyFrac: number;
+}
+
+/**
+ * A track-0 clip's own entrance/exit animation state at `rel` seconds into its
+ * `len`-second footprint. Mirrors the export's per-segment ramps: fades veil
+ * to/from black with the audio following; zoom uses the shared TRANSITION_ZOOM
+ * ramps; pop scales from/to 80% with an alpha fade; slides translate the frame
+ * (fractions of the canvas, matching xfade against black); wipes
+ * reveal/conceal through a moving edge.
+ */
+export function clipAnimFx(
+ clip: VideoClip,
+ rel: number,
+ len: number,
+ // Edge context from the caller: a transitioned joint owns its edges (skip
+ // that side), and an abutting hard cut gives the side a backdrop — the
+ // neighbor's held frame — so a fade blends by alpha there instead of
+ // veiling to black.
+ edges?: { skipIn?: boolean; skipOut?: boolean; backdropIn?: boolean; backdropOut?: boolean }
+): ClipAnimFx {
+ const fx: ClipAnimFx = { alpha: 1, zoom: 1, gain: 1, veil: 0, dxFrac: 0, dyFrac: 0 };
+ const apply = (a: ClipAnim, side: "in" | "out") => {
+ const d = Math.min(a.seconds, len);
+ if (d <= 0) return;
+ // p runs 0→1 as the visible ramp progresses on either side: entrance
+ // completeness on the head, remaining presence on the tail.
+ const p =
+ side === "in"
+ ? Math.min(1, Math.max(0, rel / d))
+ : Math.min(1, Math.max(0, (len - rel) / d));
+ if (p >= 1) return;
+ switch (a.style) {
+ case "zoom":
+ // Entrance settles TRANSITION_ZOOM→1; exit pushes 1→TRANSITION_ZOOM.
+ fx.zoom *=
+ side === "in"
+ ? TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p
+ : 1 + (TRANSITION_ZOOM - 1) * (1 - p);
+ break;
+ case "pop":
+ fx.zoom *= 0.8 + 0.2 * p;
+ fx.alpha *= p;
+ break;
+ case "slideleft": // frame moves left: enters from the right, exits off the left
+ fx.dxFrac += side === "in" ? 1 - p : -(1 - p);
+ break;
+ case "slideright":
+ fx.dxFrac += side === "in" ? -(1 - p) : 1 - p;
+ break;
+ case "slideup": // frame moves up: enters from the bottom, exits off the top
+ fx.dyFrac += side === "in" ? 1 - p : -(1 - p);
+ break;
+ case "slidedown":
+ fx.dyFrac += side === "in" ? -(1 - p) : 1 - p;
+ break;
+ case "fade":
+ default:
+ // Fade — and the graceful fallback for a stored style this build no
+ // longer knows (the export treats unknown styles the same way).
+ if (side === "in" ? edges?.backdropIn : edges?.backdropOut) fx.alpha *= p;
+ else fx.veil = Math.max(fx.veil, 1 - p);
+ fx.gain = Math.min(fx.gain, p);
+ break;
+ }
+ };
+ if (clip.animIn && !edges?.skipIn) apply(clip.animIn, "in");
+ if (clip.animOut && !edges?.skipOut) apply(clip.animOut, "out");
+ return fx;
+}
+
+/**
+ * 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).
+ */
+export function duckGainAt(audioClips: AudioClip[], t: number): number {
+ let g = 1;
+ for (const a of audioClips) {
+ if (a.hidden || a.duck === undefined || a.duck >= 1) continue;
+ const speed = a.speed && a.speed > 0 ? a.speed : 1;
+ const len = Math.max(0.1, (a.out - a.in) / speed);
+ if (t >= a.start && t < a.start + len) g = Math.min(g, Math.max(0, a.duck));
+ }
+ return g;
+}
+
+/** How much of a clip's animation window is still running at `rel`, for the
+ * sides that show a neighbour's frame behind them. */
+function animLive(a: ClipAnim | undefined, side: "in" | "out", rel: number, len: number) {
+ if (!a || a.style === "zoom") return false;
+ const d = Math.min(a.seconds, len);
+ return side === "in" ? rel < d : len - rel < d;
+}
+
+/** Everything track 0 does at one instant. */
+export interface TrackZeroPlan {
+ master: ClipSpan;
+ /** The clip blending in over the master, when a transition is live. */
+ incoming: ClipSpan | null;
+ style: TransitionStyle;
+ /** Transition progress, 0 when none is live. */
+ p: number;
+ masterAlpha: number;
+ masterZoom: number;
+ /** Frame motion on the master, as a fraction of canvas width/height. */
+ masterFxFrac: { dx: number; dy: number };
+ incAlpha: number;
+ incZoom: number;
+ /** Fade-to-black over the master clip's own footprint, 0..1. */
+ veil: number;
+ /** What the master clip's audio is scaled by, before volume and ducking. */
+ gain: number;
+ /** A neighbour's held frame to draw behind a live edge animation. */
+ backdrop: { span: ClipSpan; at: number } | null;
+ /** The next clip, when it is close enough to be worth warming. */
+ upcoming: ClipSpan | null;
+}
+
+/** How long before a clip's entrance its decoder should be spun up. */
+export const PREROLL_LEAD_S = 0.5;
+
+/**
+ * Work out track 0's state at time `t`: the transition live across the join,
+ * the master clip's own entrance/exit ramps, and the neighbour frame that
+ * belongs behind an animation at an abutting cut.
+ */
+export function trackZeroPlan(master: ClipSpan, spans: ClipSpan[], t: number): TrackZeroPlan {
+ const idx = spans.indexOf(master);
+ const next = spans[idx + 1];
+ const prev = spans[idx - 1];
+ const style = master.clip.transitionStyle ?? "crossfade";
+
+ let p = 0;
+ let incAlpha = 0;
+ let masterZoom = 1;
+ let incZoom = 1;
+ let incoming: ClipSpan | null = null;
+ // Once the incoming footprint starts, blend it in over the master.
+ if (master.transitionOut > 0 && next && t >= next.start) {
+ p = Math.min(1, (t - next.start) / master.transitionOut);
+ incAlpha = p;
+ incoming = next;
+ if (style === "crosszoom") {
+ // The outgoing picture pushes in while the incoming one settles back.
+ masterZoom = 1 + (TRANSITION_ZOOM - 1) * p;
+ incZoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;
+ }
+ }
+
+ const rel = t - master.start;
+ const abutPrev =
+ !!prev &&
+ !prev.clip.hidden &&
+ prev.transitionOut <= 0 &&
+ Math.abs(prev.start + prev.len - master.start) < 0.02;
+ const abutNext =
+ !!next &&
+ !next.clip.hidden &&
+ master.transitionOut <= 0 &&
+ Math.abs(master.start + master.len - next.start) < 0.02;
+ const anim = clipAnimFx(master.clip, rel, master.len, {
+ skipIn: (prev?.transitionOut ?? 0) > 0,
+ skipOut: master.transitionOut > 0,
+ backdropIn: abutPrev,
+ backdropOut: abutNext,
+ });
+
+ // A neighbour's held frame goes behind a live edge animation at an abutting
+ // cut: the previous clip's last frame behind an entrance, the next clip's
+ // first frame behind an exit. A zoom keeps the frame covered, so it has none.
+ let backdrop: TrackZeroPlan["backdrop"] = null;
+ if (!incoming) {
+ if (abutPrev && animLive(master.clip.animIn, "in", rel, master.len)) {
+ backdrop = { span: prev, at: prev.clip.out - 0.05 };
+ } else if (abutNext && animLive(master.clip.animOut, "out", rel, master.len)) {
+ backdrop = { span: next, at: next.clip.in };
+ }
+ }
+
+ return {
+ master,
+ incoming,
+ style,
+ p,
+ masterAlpha: anim.alpha,
+ masterZoom: masterZoom * anim.zoom,
+ masterFxFrac: { dx: anim.dxFrac, dy: anim.dyFrac },
+ incAlpha,
+ incZoom,
+ veil: anim.veil,
+ gain: anim.gain,
+ backdrop,
+ upcoming: next && t < next.start && t >= next.start - PREROLL_LEAD_S ? next : null,
+ };
+}
+
+/** One upper-track clip on screen, with its ramps resolved. */
+export interface OverlayPlanItem {
+ clip: VideoClip;
+ asset: MediaAsset;
+ alpha: number;
+ zoom: number;
+ gain: number;
+}
+
+/**
+ * The upper-track clips live at `t`, 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.
+ *
+ * `spansOf` supplies a track's spans; callers pass the store's own
+ * `getClipSpans` so span geometry is computed one way everywhere.
+ */
+export function overlayPlan(
+ tracks: number[],
+ spansOf: (track: number) => ClipSpan[],
+ t: number
+): OverlayPlanItem[] {
+ const live: OverlayPlanItem[] = [];
+ for (const track of [...tracks].sort((a, b) => a - b)) {
+ const spans = spansOf(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;
+}