Open source CapCut alternative.
TypeScript
feat(cut): rebuild clip effects — 17 transitions, in/out animations, looks [rebuild]
David Le8e4f89504f36
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex 0bda2d5d..26e8a424 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -2,16 +2,19 @@import { useEffect, type RefObject } from "react";import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } from "@/cut/lib/store";-import { isFullRect, projectFadeSeconds, rectOf, TRANSITION_ZOOM } from "@/cut/lib/types";-import type { AudioClip, ClipSpan, ColorGrade, FrameRect, MediaAsset, VideoClip } from "@/cut/lib/types";+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 { registerSourceSampler } from "@/cut/lib/previewCanvas";-/** 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. */+/** 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,@@ -23,7 +26,7 @@ function overlayTransitionFx(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.+ // Incoming side of the previous clip's transition: blend in.if (prev && prev.transitionOut > 0) {const rel = t - span.start;if (rel < prev.transitionOut) {@@ -40,37 +43,111 @@ function overlayTransitionFx(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);+ // 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 {- zoom = 1 + (TRANSITION_ZOOM - 1) * p;+ alpha = Math.min(alpha, p);+ gain = Math.min(gain, 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") {+ 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);- } else {- zoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * 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). */@@ -182,6 +259,10 @@ class Engine {// 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.@@ -344,24 +425,31 @@ class Engine {return el && elReady(el) ? el : null;}- /** The clip's picture with its color grade applied, or the raw element when- * there is nothing to grade. Mirrors the export's lutrgb/hue chain: CSS- * filter first (gain/contrast/saturate/hue), then the warm tint as a- * multiply pass, with source alpha restored so transparent stills keep- * their transparency. */- private gradedSource(el: MediaEl, grade: ColorGrade | undefined): CanvasImageSource {- if (isNeutralGrade(grade)) return el;+ /** 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 grade (never half-apply the- // tint); export still renders it.+ // 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);+ ctx.filter = [gradeToCssFilter(grade), lookCss].filter(Boolean).join(" ") || "none";ctx.drawImage(el, 0, 0, w, h);ctx.filter = "none";const tint = gradeTint(grade);@@ -378,13 +466,122 @@ class Engine {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,- grade?: ColorGrade+ clip?: VideoClip) {const ctx = this.canvas.getContext("2d");if (!ctx) return;@@ -401,7 +598,7 @@ class Engine {const dh = vh * sc;const dx = rx + (rw - dw) / 2;const dy = ry + (rh - dh) / 2;- const src = this.gradedSource(el, grade);+ const src = this.gradedSource(el, clip);const prevAlpha = ctx.globalAlpha;ctx.globalAlpha = Math.max(0, Math.min(1, alpha));if (fill || zoom > 1) {@@ -415,9 +612,19 @@ class Engine {ctx.drawImage(src, dx, dy, dw, dh);}ctx.globalAlpha = prevAlpha;+ this.applyLookPost(clip, rx, ry, rw, rh, alpha);}- private drawLayer(el: MediaEl | null, clip: VideoClip | undefined, clear: boolean, alpha: number, zoom = 1) {+ /** 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;@@ -445,11 +652,21 @@ class Engine {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?.grade);+ this.drawIntoRect(el, rect, clip?.fit === "fill", alpha, zoom, clip);+ if (hasFx) ctx.restore();return;}const fill = clip?.fit === "fill";@@ -469,15 +686,16 @@ class Engine {}const prevAlpha = ctx.globalAlpha;ctx.globalAlpha = Math.max(0, Math.min(1, alpha));- ctx.drawImage(this.gradedSource(el, clip?.grade), dx, dy, dw, dh);+ 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();}- /** Draw `masterSpan` full-frame, plus any transition live at time `t`: a- * cross style blends (and for cross zoom, scales) the next clip over it — a- * true A·(1−α)+B·α blend — while an edge style fades or zooms the master's- * own edge around a hard cut. Returns the master element (the playback- * clock). */+ /** Draw `masterSpan` full-frame, plus any transition live at time `t` in+ * its style's geometry (blend, dip, push, wipe, shape reveal), plus the+ * 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.const masterEl = this.prepare(masterSpan, t, play, masterSpan.clip.muted || !!masterSpan.clip.hidden);@@ -500,11 +718,12 @@ class Engine {this.warmNext(next, t);keep.add(next.clip.id);}- // Cross styles: once the incoming footprint starts, blend it in over the+ // 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) {- const p = Math.min(1, (t - next.start) / masterSpan.transitionOut);+ p = Math.min(1, (t - next.start) / masterSpan.transitionOut);alpha = p;incEl = this.prepare(next, t, play, true); // the outgoing clip keeps the audiokeep.add(next.clip.id);@@ -514,35 +733,37 @@ class Engine {incZoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;}}- // Edge style on this clip's own tail (fade out / zoom in).- if (next && (style === "fadeout" || style === "zoomin")) {- const d = Math.min(masterSpan.clip.transition ?? 0, masterSpan.len);- const left = masterSpan.start + masterSpan.len - t;- if (d > 0 && left < d) {- const p = 1 - left / d;- if (style === "fadeout") {- black = Math.max(black, p);- gain = Math.min(gain, 1 - p);- } else {- masterZoom = 1 + (TRANSITION_ZOOM - 1) * p;- }- }- }- // Edge style the previous clip set on this clip's head (fade in / zoom out).- const prevStyle = prev?.clip.transitionStyle ?? "crossfade";- if (prev && prev.transitionOut === 0 && (prevStyle === "fadein" || prevStyle === "zoomout")) {- const d = Math.min(prev.clip.transition ?? 0, masterSpan.len);- const rel = t - masterSpan.start;- if (d > 0 && rel < d) {- const p = rel / d;- if (prevStyle === "fadein") {- black = Math.max(black, 1 - p);- gain = Math.min(gain, p);- } else {- masterZoom = TRANSITION_ZOOM - (TRANSITION_ZOOM - 1) * p;- }- }- }+ // 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);@@ -552,8 +773,32 @@ class Engine {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.- this.drawLayer(masterEl, masterSpan.clip, false, 1, masterZoom);- if (incEl) this.drawLayer(incEl, next!.clip, false, alpha, incZoom);+ // 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,+ });// 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.@@ -561,10 +806,176 @@ class Engine {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);}+ /** Draw a neighbor clip's held frame full-frame beneath an edge animation.+ * A paused element parks on the wanted frame (the previous clip already+ * rests at its out point after the handoff; warm-ahead parks the next one+ * on its entrance frame); a pre-rolling element draws where it is — frames+ * 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) {+ 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;@@ -584,20 +995,25 @@ class Engine {return Math.min(1, g);}- /** Paint an `amount` (0..1) black veil — over the whole frame, or clipped to- * `rect` for a per-clip fade. Shared by the edge-transition fade and the- * whole-video project fade so the two can never drift apart. */- private fillBlackVeil(amount: number, rect?: FrameRect) {+ /** 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(0,0,0,${Math.min(1, amount).toFixed(3)})`;+ 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. */@@ -681,7 +1097,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.grade);+ this.drawIntoRect(el, rect, cover, alpha, zoom, clip);}}@@ -920,7 +1336,7 @@ class Engine {pauseEl(el);} else if (t >= total - 0.001) {// Track 0 and every other track finished.- useEditor.setState({ playing: false, currentTime: total });+ useEditor.setState({ playing: false, currentTime: total, previewStopAt: null });pauseEl(el);this.drawOverlays(t, true, active);this.drawProjectFade(this.projectFadeGain(total, total));@@ -939,7 +1355,7 @@ class Engine {this.lastPlayNow = now;t = t + dt;if (t >= total - 0.001) {- useEditor.setState({ playing: false, currentTime: total });+ useEditor.setState({ playing: false, currentTime: total, previewStopAt: null });this.drawOverlays(t, true, active);this.drawProjectFade(this.projectFadeGain(total, total));this.cleanupOverlays(active);@@ -963,6 +1379,17 @@ class Engine {}this.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).+ if (s.previewStopAt != null && t >= s.previewStopAt) {+ useEditor.setState({+ playing: false,+ currentTime: Math.min(t, s.previewStopAt),+ previewStopAt: null,+ });+ this.syncSoundtrack(Math.min(t, s.previewStopAt), false);+ return;+ }useEditor.setState({ currentTime: t });this.syncSoundtrack(t, true, fadeGain);}diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 078272d2..72bd6ce4 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -5,10 +5,11 @@ import { normalizeGrade } from "./colorGrade";import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";import { renderOverlayPng } from "./textRender";-import { FRAME } from "./types";+import { FRAME, overlayAnimStyle } from "./types";import type {Aspect,AudioClip,+ ClipAnim,MediaAsset,SubtitlesBlock,TextOverlay,@@ -179,43 +180,21 @@ async function buildExportForm(frame: sp.clip.frame,speed: clipSpeed(sp.clip),transition: sp.transitionOut,+ // The style rides along with the overlap; the server resolves it to an+ // xfade name (and the cross-zoom ramps) itself, so the spec carries only+ // the id.+ transitionStyle: sp.clip.transitionStyle,+ animIn: sp.clip.animIn,+ animOut: sp.clip.animOut,+ look: sp.clip.look,+ lookAmount: sp.clip.lookAmount,hidden: sp.clip.hidden,// A still: the server loops the image for the clip's length instead of// trimming a source span.image: sp.asset.type === "image",grade: normalizeGrade(sp.clip.grade),- headFade: 0,- tailFade: 0,- headZoom: 0,- tailZoom: 0,}));- // Translate each joint's transition style into per-segment ramps so the- // server spec stays dumb. Cross zoom rides the crossfade overlap with a zoom- // ramp on both sides; edge styles ramp one clip's edge around a hard cut- // (their `transition` ships as 0 overlap, so the join stays a plain concat).- spans.forEach((sp, i) => {- const next = spans[i + 1];- if (!next) return;- const style = sp.clip.transitionStyle ?? "crossfade";- const d = sp.clip.transition ?? 0;- if (d <= 0) return;- const a = clipEntries[i];- const b = clipEntries[i + 1];- if (style === "crosszoom" && sp.transitionOut > 0) {- a.tailZoom = sp.transitionOut;- b.headZoom = sp.transitionOut;- } else if (style === "fadeout") {- a.tailFade = Math.min(d, sp.len);- } else if (style === "zoomin") {- a.tailZoom = Math.min(d, sp.len);- } else if (style === "fadein") {- b.headFade = Math.min(d, next.len);- } else if (style === "zoomout") {- b.headZoom = Math.min(d, next.len);- }- });-// The server's video graph is a sequential fold, so gaps between the// free-placed clips ship as explicit spacer segments: no file, hidden and// muted, which the server renders as black + silence for the gap's length.@@ -233,10 +212,6 @@ async function buildExportForm(transition: 0,hidden: true,image: false,- headFade: 0,- tailFade: 0,- headZoom: 0,- tailZoom: 0,});// An overlay-only cut has no track-0 spans: the whole base is one black bed.const clips =@@ -248,31 +223,40 @@ async function buildExportForm(]);// 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.+ // track's transitions and animations 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 transition blends the incoming clip+ // in over the outgoing one — the incoming alpha-fades in for the overlap+ // while the outgoing stays opaque underneath it (cross zoom adds its zoom+ // ramps). Animations map fade/zoom natively; the styles that need frame+ // motion degrade to a fade up here.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;+ const r = ramps[i];+ const applyAnim = (a: ClipAnim | undefined, side: "head" | "tail") => {+ if (!a) return;+ const secs = Math.min(a.seconds, sp.len);+ if (overlayAnimStyle(a.style) === "zoom") {+ r[side === "head" ? "headZoom" : "tailZoom"] = secs;+ } else {+ r[side === "head" ? "headFade" : "tailFade"] = secs;}- } 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);+ };+ // A transitioned joint owns its edges: that side's animation is held so+ // it never fights the transition's blend (mirrors preview and track 0).+ if (!((trackSpans[i - 1]?.transitionOut ?? 0) > 0)) applyAnim(sp.clip.animIn, "head");+ if (!(sp.transitionOut > 0)) applyAnim(sp.clip.animOut, "tail");+ if (sp.transitionOut > 0 && trackSpans[i + 1]) {+ const nr = ramps[i + 1];+ nr.headFade = Math.max(nr.headFade, sp.transitionOut);+ if ((sp.clip.transitionStyle ?? "crossfade") === "crosszoom") {+ r.tailZoom = Math.max(r.tailZoom, sp.transitionOut);+ nr.headZoom = Math.max(nr.headZoom, sp.transitionOut);+ }+ }});return trackSpans.map((sp, i) => ({ c: sp.clip, ramp: ramps[i] }))@@ -292,6 +276,8 @@ async function buildExportForm(speed: c.speed,image: assetById.get(c.assetId)!.type === "image",grade: normalizeGrade(c.grade),+ look: c.look,+ lookAmount: c.lookAmount,...ramp,}));});diff --git a/site/src/cut/lib/looks.test.ts b/site/src/cut/lib/looks.test.tsnew file mode 100644index 00000000..3bbcad1c--- /dev/null+++ b/site/src/cut/lib/looks.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from "bun:test";+import { lookCssFilter, lookFilterLines, lookPost } from "./looks";+import { LOOK_IDS } from "./types";++describe("lookFilterLines", () => {+ test("every look renders lines from [in] to [out] ending in the format", () => {+ for (const id of LOOK_IDS) {+ const lines = lookFilterLines("in0", "out0", id, 1, 1920, "yuv420p", "t0");+ expect(lines === null).toBe(false);+ expect(lines![0].startsWith("[in0]")).toBe(true);+ const last = lines![lines!.length - 1];+ expect(last.endsWith("[out0]")).toBe(true);+ expect(last.includes("format=yuv420p")).toBe(true);+ }+ });++ test("halation and dreamy are split/blend graphs", () => {+ expect(lookFilterLines("a", "b", "halation", 1, 1920, "yuv420p", "t")!.length).toBe(3);+ expect(lookFilterLines("a", "b", "dreamy", 1, 1920, "yuv420p", "t")!.length).toBe(3);+ });++ test("an unknown id returns null instead of failing the job", () => {+ expect(lookFilterLines("a", "b", "sparkle", 1, 1920, "yuv420p", "t")).toBe(null);+ expect(lookFilterLines("a", "b", "", 1, 1920, "yuv420p", "t")).toBe(null);+ });++ test("amount is clamped into (0.05..1]", () => {+ const over = lookFilterLines("a", "b", "noir", 5, 1920, "yuv420p", "t")!;+ const full = lookFilterLines("a", "b", "noir", 1, 1920, "yuv420p", "t")!;+ expect(over).toEqual(full);+ const zero = lookFilterLines("a", "b", "noir", 0, 1920, "yuv420p", "t")!;+ const floor = lookFilterLines("a", "b", "noir", 0.05, 1920, "yuv420p", "t")!;+ expect(zero).toEqual(floor);+ });++ test("blur radii scale with the output height", () => {+ const at1080 = lookFilterLines("a", "b", "halation", 1, 1920, "yuv420p", "t")!.join(";");+ const at720 = lookFilterLines("a", "b", "halation", 1, 1280, "yuv420p", "t")!.join(";");+ expect(at1080.includes("gblur=sigma=18")).toBe(true);+ expect(at720.includes("gblur=sigma=12")).toBe(true);+ });+});++describe("canvas recipes", () => {+ test("every look has a css filter or a post pass", () => {+ for (const id of LOOK_IDS) {+ expect(lookCssFilter(id, 1) !== "" || lookPost(id, 1) !== null).toBe(true);+ }+ });++ test("no look leaks NaN into its css filter", () => {+ for (const id of LOOK_IDS) {+ expect(lookCssFilter(id, 0.3).includes("NaN")).toBe(false);+ }+ });+});diff --git a/site/src/cut/lib/looks.ts b/site/src/cut/lib/looks.tsnew file mode 100644index 00000000..bcfe554a--- /dev/null+++ b/site/src/cut/lib/looks.ts@@ -0,0 +1,233 @@+import type { LookStyle } from "./types";++/**+ * Preset filter looks, one recipe per style with two renderers — the preview+ * canvas (a CSS filter string plus post passes: vignette, grain, glow, color+ * washes, chroma ghosts) and the export filtergraph (an ffmpeg chain built+ * server-side from the same `amount` knob). Both sides interpolate the same+ * conceptual parameters toward identity as the amount drops, so 30% reads the+ * same in the editor and the rendered file.+ *+ * Known approximations, accepted by design: blockbuster's shadow/highlight+ * split-toning previews as two soft-light washes (CSS has no per-luminance+ * masking); VHS chroma fringing previews as tinted ghost copies rather than a+ * true channel shift; tech's unsharp crispness is export-only.+ */++const clampAmount = (k: number | undefined) => Math.max(0.05, Math.min(1, k ?? 1));++const fmt = (n: number) => (Math.round(n * 1000) / 1000).toString();++/* ---------------------------------------------------------------- canvas */++/** `ctx.filter` value for the clip's base grading pass; "" when none. */+export function lookCssFilter(style: LookStyle | undefined, amount?: number): string {+ if (!style) return "";+ const k = clampAmount(amount);+ switch (style) {+ case "vintage":+ return `sepia(${fmt(0.25 * k)}) saturate(${fmt(1 - 0.15 * k)}) contrast(${fmt(1 - 0.08 * k)}) brightness(1.03)`;+ case "vhs":+ return `saturate(${fmt(1 - 0.35 * k)}) contrast(${fmt(1 - 0.05 * k)}) blur(${fmt(0.6 * k)}px)`;+ case "horror":+ return `grayscale(${fmt(0.55 * k)}) brightness(${fmt(1 - 0.12 * k)}) contrast(${fmt(1 + 0.1 * k)})`;+ case "halation":+ return `saturate(${fmt(1 + 0.05 * k)})`;+ case "tech":+ return `contrast(${fmt(1 + 0.12 * k)}) saturate(${fmt(1 + 0.08 * k)})`;+ case "noir":+ return `grayscale(${fmt(k)}) contrast(${fmt(1 + 0.08 * k)})`;+ case "grain":+ return "";+ case "pastel":+ return `brightness(${fmt(1 + 0.06 * k)}) contrast(${fmt(1 - 0.15 * k)}) saturate(${fmt(1 - 0.18 * k)})`;+ case "blockbuster":+ return `contrast(${fmt(1 + 0.1 * k)}) saturate(${fmt(1 + 0.15 * k)})`;+ case "dreamy":+ return `brightness(1.02) saturate(${fmt(1 + 0.05 * k)})`;+ }+}++/** Post passes drawn over the clip's footprint after its graded picture. */+export interface LookPost {+ /** Radial corner-darkening strength 0..1. */+ vignette?: number;+ /** Animated noise-tile overlay alpha 0..1. */+ grain?: number;+ /** Self-copy glow: blur radius as a fraction of the frame height, blended+ * back over the picture. `bright` isolates highlights first (halation). */+ glow?: { blurFrac: number; alpha: number; mode: "screen" | "lighten"; bright?: boolean };+ /** Flat color layers composited over the picture. */+ washes?: { color: string; alpha: number; mode: GlobalCompositeOperation }[];+ /** VHS-style chroma fringing: tinted copies offset horizontally by a+ * fraction of the frame width. */+ ghost?: { shiftFrac: number; alpha: number };+}++export function lookPost(style: LookStyle | undefined, amount?: number): LookPost | null {+ if (!style) return null;+ const k = clampAmount(amount);+ switch (style) {+ case "vintage":+ return { vignette: 0.35 * k, grain: 0.05 * k };+ case "vhs":+ return { grain: 0.09 * k, ghost: { shiftFrac: 0.004 * k, alpha: 0.35 * k } };+ case "horror":+ return { vignette: 0.55 * k, grain: 0.14 * k };+ case "halation":+ return { glow: { blurFrac: 14 / 1920, alpha: 0.6 * k, mode: "screen", bright: true } };+ case "tech":+ return { washes: [{ color: "#3b9dff", alpha: 0.1 * k, mode: "soft-light" }] };+ case "noir":+ return { grain: 0.06 * k };+ case "grain":+ return { grain: 0.04 + 0.12 * k };+ case "pastel":+ return null;+ case "blockbuster":+ return {+ washes: [+ { color: "#ff9a3c", alpha: 0.12 * k, mode: "soft-light" },+ { color: "#0e7490", alpha: 0.08 * k, mode: "overlay" },+ ],+ };+ case "dreamy":+ return { glow: { blurFrac: 10 / 1920, alpha: 0.45 * k, mode: "lighten" } };+ }+}++/** Pre-rendered monochrome noise tiles, cycled per frame for shimmer. Built+ * once on first use (client only) — never per-frame pixel work. */+const GRAIN_TILE = 256;+const GRAIN_COUNT = 3;+let grainTiles: HTMLCanvasElement[] | null = null;++export function grainTile(tick: number): HTMLCanvasElement | null {+ if (typeof document === "undefined") return null;+ if (!grainTiles) {+ grainTiles = [];+ for (let n = 0; n < GRAIN_COUNT; n++) {+ const c = document.createElement("canvas");+ c.width = GRAIN_TILE;+ c.height = GRAIN_TILE;+ const ctx = c.getContext("2d");+ if (!ctx) return null;+ const img = ctx.createImageData(GRAIN_TILE, GRAIN_TILE);+ for (let i = 0; i < img.data.length; i += 4) {+ const v = Math.floor(Math.random() * 256);+ img.data[i] = v;+ img.data[i + 1] = v;+ img.data[i + 2] = v;+ img.data[i + 3] = 255;+ }+ ctx.putImageData(img, 0, 0);+ grainTiles.push(c);+ }+ }+ return grainTiles[(tick >> 1) % GRAIN_COUNT];+}++/* ---------------------------------------------------------------- ffmpeg */++const PI = Math.PI;++/** Single-chain looks: the filter run (no leading label, no trailing format). */+function lookChain(style: LookStyle, k: number): string | null {+ switch (style) {+ case "vintage":+ return (+ `curves=master='0/${fmt(0.06 * k)} 0.5/${fmt(0.5 + 0.02 * k)} 1/${fmt(1 - 0.05 * k)}'` ++ `:r='0/${fmt(0.02 * k)} 1/1':b='0/0 1/${fmt(1 - 0.1 * k)}',` ++ `colortemperature=temperature=${Math.round(6500 - 1800 * k)},` ++ `vibrance=intensity=${fmt(-0.25 * k)},` ++ `vignette=angle=${fmt((k * PI) / 5)},` ++ `noise=alls=${Math.round(6 * k)}:allf=t+u`+ );+ case "vhs":+ return (+ `rgbashift=rh=${Math.round(3 * k)}:bh=${-Math.round(3 * k)},` ++ `hue=s=${fmt(1 - 0.4 * k)},` ++ `gblur=sigma=${fmt(0.8 * k)},` ++ `curves=master='0/${fmt(0.04 * k)} 1/${fmt(1 - 0.07 * k)}',` ++ `noise=alls=${Math.round(14 * k)}:allf=t+u`+ );+ case "horror":+ return (+ `huesaturation=saturation=${fmt(-0.6 * k)}:intensity=${fmt(-0.15 * k)},` ++ `curves=master='0/0 0.5/${fmt(0.5 - 0.08 * k)} 1/${fmt(1 - 0.1 * k)}',` ++ `vignette=angle=${fmt((k * PI) / 3.5)},` ++ `noise=alls=${Math.round(22 * k)}:allf=t+u`+ );+ case "tech":+ return (+ `colortemperature=temperature=${Math.round(6500 + 3500 * k)},` ++ `curves=master='0/0 0.5/${fmt(0.5 - 0.02 * k)} 1/1',` ++ `vibrance=intensity=${fmt(0.15 * k)},` ++ `unsharp=5:5:${fmt(0.8 * k)}`+ );+ case "noir":+ return (+ `hue=s=${fmt(1 - k)},` ++ `curves=master='0/0 0.5/${fmt(0.5 - 0.03 * k)} 1/1',` ++ `noise=alls=${Math.round(8 * k)}:allf=t+u`+ );+ case "grain":+ return `noise=alls=${Math.round(4 + 16 * k)}:allf=t+u`;+ case "pastel":+ return (+ `curves=master='0/${fmt(0.09 * k)} 1/${fmt(1 - 0.06 * k)}',` ++ `vibrance=intensity=${fmt(-0.2 * k)},` ++ `colortemperature=temperature=${Math.round(6500 - 800 * k)}`+ );+ case "blockbuster":+ return (+ `colorbalance=rs=${fmt(-0.1 * k)}:bs=${fmt(0.15 * k)}` ++ `:rm=${fmt(0.05 * k)}:bm=${fmt(-0.05 * k)}` ++ `:rh=${fmt(0.1 * k)}:bh=${fmt(-0.1 * k)},` ++ `vibrance=intensity=${fmt(0.2 * k)}`+ );+ default:+ return null; // halation and dreamy are split/blend graphs+ }+}++/**+ * ffmpeg filter_complex lines rendering `style` from `[inLabel]` into+ * `[outLabel]`, ending in `format=${pixFmt}` so the segment's format+ * invariant holds through xfade/concat joins. Null for an unknown style — the+ * segment renders ungraded rather than failing the job (the spec carries only+ * ids, never filter text). `hPx` scales blur radii so 720p drafts and 1080p+ * exports bloom proportionally; `tag` uniquifies inner labels.+ */+export function lookFilterLines(+ inLabel: string,+ outLabel: string,+ style: string,+ amount: number | undefined,+ hPx: number,+ pixFmt: string,+ tag: string+): string[] | null {+ const k = clampAmount(amount);+ if (style === "halation") {+ return [+ `[${inLabel}]split=2[lkb${tag}][lkh${tag}]`,+ `[lkh${tag}]lutyuv=y='clip((val-160)*3,0,255)',` ++ `gblur=sigma=${fmt((18 * hPx) / 1920)},` ++ `colorchannelmixer=rr=1:gg=0.55:bb=0.35[lkg${tag}]`,+ `[lkb${tag}][lkg${tag}]blend=all_mode=screen:all_opacity=${fmt(0.6 * k)},format=${pixFmt}[${outLabel}]`,+ ];+ }+ if (style === "dreamy") {+ return [+ `[${inLabel}]split=2[lkb${tag}][lkh${tag}]`,+ `[lkh${tag}]gblur=sigma=${fmt((10 * hPx) / 1920)}[lkg${tag}]`,+ `[lkb${tag}][lkg${tag}]blend=all_mode=lighten:all_opacity=${fmt(0.45 * k)},` ++ `curves=master='0/${fmt(0.03 * k)} 1/${fmt(1 - 0.03 * k)}',` ++ `vibrance=intensity=${fmt(0.1 * k)},format=${pixFmt}[${outLabel}]`,+ ];+ }+ const chain = lookChain(style as LookStyle, k);+ if (!chain) return null;+ return [`[${inLabel}]${chain},format=${pixFmt}[${outLabel}]`];+}diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.tsindex 51d80341..af30306e 100644--- a/site/src/cut/lib/store.test.ts+++ b/site/src/cut/lib/store.test.ts@@ -449,3 +449,88 @@ describe("upper-track transitions", () => {expect(right.transition).toBe(1);});});++describe("transitioned joints own their edges", () => {+ test("setting a transition clears the animations adjacent to its joint", () => {+ const av = asset(4);+ const a = vclip({+ track: 0,+ start: 0,+ out: 4,+ assetId: av.id,+ animIn: { style: "fade", seconds: 0.5 },+ animOut: { style: "slideleft", seconds: 0.5 },+ });+ const b = vclip({+ track: 0,+ start: 4,+ out: 4,+ assetId: av.id,+ animIn: { style: "pop", seconds: 0.5 },+ animOut: { style: "fade", seconds: 0.5 },+ });+ useEditor.setState({ assets: [av], clips: [a, b] });+ s().setClipTransition(a.id, 0.8, "pushdown");+ // The joint's own edges clear; the far edges stay.+ expect(clipById(a.id).animOut).toBeUndefined();+ expect(clipById(b.id).animIn).toBeUndefined();+ expect(clipById(a.id).animIn).toEqual({ style: "fade", seconds: 0.5 });+ expect(clipById(b.id).animOut).toEqual({ style: "fade", seconds: 0.5 });+ });++ test("clearing a transition leaves the neighbors' animations alone", () => {+ const av = asset(4);+ const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id, transition: 0.8 });+ const b = vclip({+ track: 0,+ start: 3.2,+ out: 4,+ assetId: av.id,+ animOut: { style: "fade", seconds: 0.5 },+ });+ useEditor.setState({ assets: [av], clips: [a, b] });+ s().setClipTransition(a.id, 0);+ expect(clipById(a.id).transition).toBeUndefined();+ expect(clipById(b.id).animOut).toEqual({ style: "fade", seconds: 0.5 });+ });+});++describe("last pick wins per edge", () => {+ test("an entrance animation on the following clip replaces the joint's transition", () => {+ const av = asset(4);+ const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });+ const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });+ useEditor.setState({ assets: [av], clips: [a, b] });+ s().setClipTransition(a.id, 0.8, "pushdown");+ expect(clipById(b.id).start).toBeCloseTo(3.2);+ s().setClipAnim(b.id, "in", { style: "slideleft", seconds: 0.5 });+ expect(clipById(a.id).transition).toBeUndefined();+ expect(clipById(b.id).start).toBeCloseTo(4); // back to a hard cut+ expect(clipById(b.id).animIn).toEqual({ style: "slideleft", seconds: 0.5 });+ });++ test("an exit animation on the leading clip replaces the joint's transition", () => {+ const av = asset(4);+ const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });+ const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });+ useEditor.setState({ assets: [av], clips: [a, b] });+ s().setClipTransition(a.id, 0.8, "circleopen");+ s().setClipAnim(a.id, "out", { style: "fade", seconds: 0.4 });+ expect(clipById(a.id).transition).toBeUndefined();+ expect(clipById(a.id).animOut).toEqual({ style: "fade", seconds: 0.4 });+ expect(clipById(b.id).start).toBeCloseTo(4);+ });++ test("an animation on a far edge leaves an unrelated transition alone", () => {+ const av = asset(4);+ const a = vclip({ track: 0, start: 0, out: 4, assetId: av.id });+ const b = vclip({ track: 0, start: 4, out: 4, assetId: av.id });+ useEditor.setState({ assets: [av], clips: [a, b] });+ s().setClipTransition(a.id, 0.8);+ s().setClipAnim(a.id, "in", { style: "fade", seconds: 0.5 }); // A's entrance, not the joint+ s().setClipAnim(b.id, "out", { style: "fade", seconds: 0.5 }); // B's exit, not the joint+ expect(clipById(a.id).transition).toBeCloseTo(0.8);+ expect(clipById(a.id).animIn).toEqual({ style: "fade", seconds: 0.5 });+ expect(clipById(b.id).animOut).toEqual({ style: "fade", seconds: 0.5 });+ });+});diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex acbbfbc9..a86ecdea 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -4,8 +4,10 @@ import { create } from "zustand";import type {Aspect,AudioClip,+ ClipAnim,ClipSpan,LibraryTemplate,+ LookStyle,MediaAsset,ProjectDoc,Selection,@@ -25,7 +27,7 @@ import type { VideoProject } from "./genvideo/types";import { fillSlot } from "./genvideo/fillSlot";import { apiFetch, apiJson } from "./api";import { trackLocale } from "./subtitles";-import { emptySubtitles, IMAGE_CLIP_SECONDS, isCrossStyle, MAX_SUBTITLE_LANES, mediaUrl, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";+import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";import { readTextStyle } from "./textStyle";import { loadUiState, saveUiState } from "./uiState";import { captureTimelineFrames } from "./visualFrames";@@ -115,6 +117,9 @@ export interface EditorState {multiSelection: Selection[];currentTime: number;playing: boolean;+ /** While playing a scoped effect preview, the time playback auto-pauses at;+ * null otherwise. Manual seek/play/pause clears it. */+ previewStopAt: number | null;pxPerSec: number;/** Timeline panel height in px (drag the panel's top border to change). */timelineH: number;@@ -202,6 +207,11 @@ export interface EditorState {/** Set the transition into the next clip (seconds; 0 clears it), optionally* changing its style; omitting the style keeps the clip's current one. */setClipTransition: (id: string, seconds: number, style?: TransitionStyle) => void;+ /** Set (or clear with null) a clip's own entrance/exit animation. Never+ * moves the layout — an animation belongs to one clip's edge. */+ setClipAnim: (id: string, which: "in" | "out", anim: ClipAnim | null) => void;+ /** Set (or clear with null) a clip's preset filter look; amount 0..1. */+ setClipLook: (id: string, style: LookStyle | null, amount?: number) => void;updateAudio: (id: string, patch: Partial<AudioClip>) => void;updateOverlay: (id: string, patch: Partial<TextOverlay>) => void;/** Live-drag updates that should not create undo entries. */@@ -313,6 +323,10 @@ export interface EditorState {toggleSelect: (sel: NonNullable<Selection>) => void;seek: (t: number) => void;setPlaying: (p: boolean) => void;+ /** Play just the [start, end] stretch in the preview: seek to `start`,+ * play, and auto-pause at `end`. Effect pickers use it so choosing a+ * transition/animation immediately shows the real footage doing it. */+ previewRange: (start: number, end: number) => void;setPxPerSec: (v: number) => void;setTimelineH: (h: number) => void;setExportOpen: (v: boolean) => void;@@ -722,6 +736,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {multiSelection: [],currentTime: 0,playing: false,+ previewStopAt: null,pxPerSec: 60,timelineH: TIMELINE_H_DEFAULT,skimTime: null,@@ -762,6 +777,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {multiSelection: [],currentTime: 0,playing: false,+ previewStopAt: null,subtitles: emptySubtitles(),subtitleLane: 0,subtitleStatus: "idle",@@ -809,7 +825,10 @@ export const useEditor = create<EditorState>((baseSet, get) => {// lowest row becomes track 0 — the bottom row is the spine now.const joined = [...folded, ...legacyLayers];const lift = Math.max(0, ...joined.map((c) => -c.track));- const merged = lift ? joined.map((c) => ({ ...c, track: c.track + lift })) : joined;+ const lifted = lift ? joined.map((c) => ({ ...c, track: c.track + lift })) : joined;+ // Docs saved when edge transition styles existed convert them into the+ // equivalent clip animations.+ const merged = migrateLegacyTransitions(lifted);set({projectName: doc.name,assets,@@ -1215,7 +1234,12 @@ export const useEditor = create<EditorState>((baseSet, get) => {transition: value || undefined,// "crossfade" is the default — store it as absence to keep docs lean.transitionStyle: newStyle === "crossfade" ? undefined : newStyle,+ // A transitioned joint owns its edges: the transition replaces the+ // animations adjacent to it, so stored state always matches what+ // plays (the picker disables those edges while the joint is live).+ ...(value > 0 ? { animOut: undefined } : {}),});+ if (value > 0 && next) get().updateClipTransient(next.id, { animIn: undefined });// A dissolve is a physical overlap: setting one slides the next clip// (and the run behind it, gaps preserved) so it starts `newOverlap`// before this clip ends — closing any gap, since a dissolve needs@@ -1242,6 +1266,51 @@ export const useEditor = create<EditorState>((baseSet, get) => {}},+ setClipAnim: (id, which, anim) => {+ const s = get();+ const clip = s.clips.find((c) => c.id === id);+ if (!clip) return;+ const value =+ anim && ANIM_STYLE_IDS.includes(anim.style)+ ? { style: anim.style, seconds: Math.max(0.1, Math.min(TRANSITION_MAX, anim.seconds)) }+ : undefined;+ // Last pick wins per edge: animating an edge a live transition owns+ // replaces that transition (the pair slides back to a hard cut), just+ // as setting a transition clears the animations adjacent to its joint.+ // The clear and the animation land in one undo entry.+ let pushed = false;+ if (value) {+ const row = s.clips+ .filter((c) => c.track === clip.track)+ .sort((a, b) => a.start - b.start);+ const i = row.findIndex((c) => c.id === clip.id);+ const lead = which === "in" ? row[i - 1] : row[i];+ const follow = which === "in" ? row[i] : row[i + 1];+ if (lead && follow && lead.id !== follow.id) {+ const physical = lead.start + clipLen(lead) - follow.start;+ if (Math.min(transitionOverlap(lead, follow), Math.max(0, physical)) > 1e-6) {+ get().setClipTransition(lead.id, 0);+ pushed = true;+ }+ }+ }+ if (!pushed) push();+ get().updateClipTransient(id, { [which === "in" ? "animIn" : "animOut"]: value });+ },++ setClipLook: (id, style, amount) => {+ const clip = get().clips.find((c) => c.id === id);+ if (!clip) return;+ const look = style && LOOK_IDS.includes(style) ? style : undefined;+ const k = amount === undefined ? undefined : Math.max(0.05, Math.min(1, amount));+ push();+ get().updateClipTransient(id, {+ look,+ // Full strength is the default — store it as absence to keep docs lean.+ lookAmount: look && k !== undefined && k < 1 ? k : undefined,+ });+ },+updateAudio: (id, patch) => {push();get().updateAudioTransient(id, patch);@@ -1505,8 +1574,11 @@ export const useEditor = create<EditorState>((baseSet, get) => {const cutIn = c.in + (t - c.start) * sp;// 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 };+ // The cut lands mid-footage, so the edges it creates stay plain:+ // the exit animation belongs to the right half's tail and the+ // entrance to the left half's head.+ const left: VideoClip = { ...c, out: cutIn, transition: undefined, transitionStyle: undefined, animOut: undefined };+ const right: VideoClip = { ...c, id: uid(), start: t, in: cutIn, animIn: undefined };set((s) => {const idx = s.clips.findIndex((x) => x.id === c.id);const next = [...s.clips];@@ -1576,9 +1648,12 @@ export const useEditor = create<EditorState>((baseSet, get) => {// Source time advances `speed`× faster than timeline time.const cutAt = span.clip.in + (t - span.start) * clipSpeed(span.clip);// The left half hard-cuts into the right; the right keeps the original- // dissolve into whatever came after. Both halves stay in place.- const left: VideoClip = { ...span.clip, out: cutAt, transition: undefined, transitionStyle: undefined };- const right: VideoClip = { ...span.clip, id: uid(), in: cutAt, start: t };+ // dissolve into whatever came after. Both halves stay in place. The cut+ // lands mid-footage, so the edges it creates stay plain: the exit+ // animation stays on the right half's tail, the entrance on the left's+ // head.+ const left: VideoClip = { ...span.clip, out: cutAt, transition: undefined, transitionStyle: undefined, animOut: undefined };+ const right: VideoClip = { ...span.clip, id: uid(), in: cutAt, start: t, animIn: undefined };set((s) => {const idx = s.clips.findIndex((c) => c.id === span.clip.id);const next = [...s.clips];@@ -1920,10 +1995,19 @@ export const useEditor = create<EditorState>((baseSet, get) => {seek: (t) => {const total = projectDuration(get());- set({ currentTime: Math.max(0, Math.min(total, t)) });+ // A manual seek cancels any scoped effect preview.+ set({ currentTime: Math.max(0, Math.min(total, t)), previewStopAt: null });},- setPlaying: (p) => set({ playing: p }),+ // A manual play/pause cancels any scoped effect preview.+ setPlaying: (p) => set({ playing: p, previewStopAt: null }),++ previewRange: (start, end) => {+ const total = projectDuration(get());+ const from = Math.max(0, Math.min(total, start));+ const to = Math.max(from + 0.05, Math.min(total, end));+ set({ currentTime: from, playing: true, previewStopAt: to });+ },setSkimTime: (t) => {if (get().skimTime !== t) set({ skimTime: t });},@@ -2745,13 +2829,11 @@ export function clipLen(c: VideoClip | AudioClip) {}/** Overlap (timeline seconds) between a clip and its successor, clamped so it- * can never swallow either clip whole. 0 when there is no next clip, no- * transition set, or the style is an edge style (those ramp one clip's edge- * around a hard cut instead of overlapping). */+ * can never swallow either clip whole. 0 when there is no next clip or no+ * transition set — every transition style is a physical overlap. */export function transitionOverlap(a: VideoClip, b: VideoClip | undefined): number {const d = a.transition ?? 0;if (!b || d <= 0) return 0;- if (!isCrossStyle(a.transitionStyle ?? "crossfade")) return 0;return Math.min(d, clipLen(a) * 0.9, clipLen(b) * 0.9);}diff --git a/site/src/cut/lib/types.test.ts b/site/src/cut/lib/types.test.tsnew file mode 100644index 00000000..0585450c--- /dev/null+++ b/site/src/cut/lib/types.test.ts@@ -0,0 +1,98 @@+import { describe, expect, test } from "bun:test";+import { migrateLegacyTransitions, TRANSITION_STYLE_IDS, type VideoClip } from "./types";++/** A minimal track-0 clip; legacy docs carry retired transitionStyle strings. */+function clip(+ id: string,+ start: number,+ patch: Omit<Partial<VideoClip>, "transitionStyle"> & { transitionStyle?: string } = {}+): VideoClip {+ return {+ id,+ assetId: `asset-${id}`,+ track: 0,+ start,+ in: 0,+ out: 4,+ muted: false,+ ...patch,+ } as VideoClip;+}++describe("migrateLegacyTransitions", () => {+ test("docs without legacy styles pass through untouched", () => {+ const clips = [clip("a", 0, { transition: 0.5 }), clip("b", 4)];+ expect(migrateLegacyTransitions(clips)).toBe(clips);+ });++ test("fadeout/zoomin become the leading clip's exit animation", () => {+ const out = migrateLegacyTransitions([+ clip("a", 0, { transition: 0.8, transitionStyle: "fadeout" }),+ clip("b", 4, { transition: 0.6, transitionStyle: "zoomin" }),+ clip("c", 8),+ ]);+ expect(out[0].animOut).toEqual({ style: "fade", seconds: 0.8 });+ expect(out[0].transition).toBeUndefined();+ expect(out[0].transitionStyle).toBeUndefined();+ expect(out[1].animOut).toEqual({ style: "zoom", seconds: 0.6 });+ });++ test("fadein/zoomout become the following clip's entrance animation", () => {+ const out = migrateLegacyTransitions([+ clip("a", 0, { transition: 0.5, transitionStyle: "fadein" }),+ clip("b", 4, { transition: 0.4, transitionStyle: "zoomout" }),+ clip("c", 8),+ ]);+ expect(out[1].animIn).toEqual({ style: "fade", seconds: 0.5 });+ expect(out[2].animIn).toEqual({ style: "zoom", seconds: 0.4 });+ expect(out[0].transition).toBeUndefined();+ });++ test("fadein on a track's last clip drops (no next clip to enter)", () => {+ const out = migrateLegacyTransitions([+ clip("a", 0),+ clip("b", 4, { transition: 0.5, transitionStyle: "fadein" }),+ ]);+ expect(out.every((c) => !c.animIn && !c.animOut)).toBe(true);+ expect(out[1].transition).toBeUndefined();+ });++ test("migration stays within each track", () => {+ const out = migrateLegacyTransitions([+ clip("a0", 0, { transition: 0.5, transitionStyle: "fadein" }),+ clip("b1", 1, { track: 1 }),+ clip("c0", 4),+ ]);+ expect(out.find((c) => c.id === "c0")?.animIn).toEqual({ style: "fade", seconds: 0.5 });+ expect(out.find((c) => c.id === "b1")?.animIn).toBeUndefined();+ });++ test("an existing animation is never overwritten", () => {+ const out = migrateLegacyTransitions([+ clip("a", 0, {+ transition: 0.5,+ transitionStyle: "fadeout",+ animOut: { style: "pop", seconds: 0.3 },+ }),+ clip("b", 4),+ ]);+ expect(out[0].animOut).toEqual({ style: "pop", seconds: 0.3 });+ });++ test("unknown styles clear to a hard cut", () => {+ const out = migrateLegacyTransitions([+ clip("a", 0, { transition: 0.5, transitionStyle: "sparkle-explosion" }),+ clip("b", 4),+ ]);+ expect(out[0].transition).toBeUndefined();+ expect(out[0].transitionStyle).toBeUndefined();+ expect(out[0].animOut).toBeUndefined();+ });++ test("current style ids are never treated as legacy", () => {+ for (const id of TRANSITION_STYLE_IDS) {+ const clips = [clip("a", 0, { transition: 0.5, transitionStyle: id }), clip("b", 4)];+ expect(migrateLegacyTransitions(clips)).toBe(clips);+ }+ });+});diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 16756b20..f3060b39 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -139,13 +139,23 @@ export interface VideoClip {* (out-in)/speed timeline seconds, so >1 is faster and shorter. */speed?: number;/** 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. */+ * (absent/0 = hard cut). Every style overlaps the two clips by this much,+ * so the cut shortens. On upper tracks a transition blends the incoming+ * clip in over the outgoing one (the tracks beneath show through). */transition?: number;/** Look of that transition; absent = "crossfade". */transitionStyle?: TransitionStyle;+ /** Entrance animation on this clip's own head (absent = none). Unlike a+ * transition it belongs to one clip and never moves its neighbors. */+ animIn?: ClipAnim;+ /** Exit animation on this clip's own tail (absent = none). */+ animOut?: ClipAnim;+ /** Preset filter look baked over the clip's picture (absent = none).+ * Composes with `grade`: the look is the base, manual adjustments ride on+ * top of it. */+ look?: LookStyle;+ /** Look strength 0..1; absent = 1 (full). */+ lookAmount?: number;/** Hidden clips stay on the timeline (grayed) but render as black — excluded* from the played/exported picture without disturbing the layout. */hidden?: boolean;@@ -184,43 +194,229 @@ export function projectFadeSeconds(fade: number | undefined, duration: number):return Math.max(0, Math.min(fade ?? 0, duration / 2));}-/** How a clip hands off to the next one. Cross styles overlap the two clips;- * edge styles ramp one side of a hard cut — the outgoing tail (fadeout,- * zoomin) or the incoming head (fadein, zoomout). */+/** How a clip hands off to the next one. Every style is a physical overlap:+ * the two clips run together for the transition length and the cut shortens+ * by it. Directional names describe the motion (pushleft pushes the frame+ * leftward; wipeleft's reveal edge travels leftward). */export type TransitionStyle =| "crossfade"| "crosszoom"- | "zoomin"- | "zoomout"- | "fadein"- | "fadeout";--export const TRANSITION_STYLE_IDS: TransitionStyle[] = [- "crossfade",- "crosszoom",- "zoomin",- "zoomout",- "fadein",- "fadeout",+ | "dipblack"+ | "dipwhite"+ | "blur"+ | "pushleft"+ | "pushright"+ | "pushup"+ | "pushdown"+ | "wipeleft"+ | "wiperight"+ | "wipeup"+ | "wipedown"+ | "circleopen"+ | "circleclose"+ | "splitopen"+ | "splitclose";++/** The ffmpeg xfade transition each style renders with on export. Doubles as+ * the sanitizing allowlist: the server looks the style up here and falls back+ * to plain "fade" for anything unknown. Cross zoom is a fade — its zoom+ * ramps ride the overlap as segment-edge zooms. */+export const TRANSITION_XFADE: Record<TransitionStyle, string> = {+ crossfade: "fade",+ crosszoom: "fade",+ dipblack: "fadeblack",+ dipwhite: "fadewhite",+ blur: "hblur",+ pushleft: "slideleft",+ pushright: "slideright",+ pushup: "slideup",+ pushdown: "slidedown",+ wipeleft: "wipeleft",+ wiperight: "wiperight",+ wipeup: "wipeup",+ wipedown: "wipedown",+ circleopen: "circleopen",+ circleclose: "circleclose",+ splitopen: "vertopen",+ splitclose: "vertclose",+};++/** Picker layout: styles grouped by family, in display order. */+export const TRANSITION_STYLE_GROUPS: { label: string; ids: TransitionStyle[] }[] = [+ { label: "Fade", ids: ["crossfade", "dipblack", "dipwhite", "blur"] },+ { label: "Zoom", ids: ["crosszoom"] },+ { label: "Push", ids: ["pushleft", "pushright", "pushup", "pushdown"] },+ { label: "Wipe", ids: ["wipeleft", "wiperight", "wipeup", "wipedown"] },+ { label: "Shape", ids: ["circleopen", "circleclose", "splitopen", "splitclose"] },];+export const TRANSITION_STYLE_IDS: TransitionStyle[] = TRANSITION_STYLE_GROUPS.flatMap(+ (g) => g.ids+);+export const TRANSITION_STYLE_LABELS: Record<TransitionStyle, string> = {crossfade: "Cross fade",crosszoom: "Cross zoom",- zoomin: "Zoom in",- zoomout: "Zoom out",- fadein: "Fade in",- fadeout: "Fade out",+ dipblack: "Dip to black",+ dipwhite: "Dip to white",+ blur: "Blur",+ pushleft: "Push left",+ pushright: "Push right",+ pushup: "Push up",+ pushdown: "Push down",+ wipeleft: "Wipe left",+ wiperight: "Wipe right",+ wipeup: "Wipe up",+ wipedown: "Wipe down",+ circleopen: "Circle open",+ circleclose: "Circle close",+ splitopen: "Split open",+ splitclose: "Split close",};-/** Cross styles overlap the clips they join; edge styles never do. */-export function isCrossStyle(style: TransitionStyle): boolean {- return style === "crossfade" || style === "crosszoom";-}-/** Peak scale the zoom transitions push into (preview and export). */export const TRANSITION_ZOOM = 1.18;+/** A clip's own entrance/exit animation. The same style id serves both sides:+ * directional names describe the motion (slideleft moves the picture+ * leftward — entering from the right edge, or exiting off the left one).+ * Edge reveals (wipes, circles, splits) live on transitions only — as an+ * animation they'd duplicate the same visual. */+export type AnimStyle =+ | "fade"+ | "zoom"+ | "pop"+ | "slideleft"+ | "slideright"+ | "slideup"+ | "slidedown";++export interface ClipAnim {+ style: AnimStyle;+ /** Ramp length in timeline seconds, 0.1..TRANSITION_MAX. */+ seconds: number;+}++export const ANIM_STYLE_IDS: AnimStyle[] = [+ "fade",+ "zoom",+ "pop",+ "slideleft",+ "slideright",+ "slideup",+ "slidedown",+];++export const ANIM_STYLE_LABELS: Record<AnimStyle, string> = {+ fade: "Fade",+ zoom: "Zoom",+ pop: "Pop",+ slideleft: "Slide left",+ slideright: "Slide right",+ slideup: "Slide up",+ slidedown: "Slide down",+};++export const ANIM_DEFAULT_SECONDS = 0.5;++/** Animation styles an overlay-track clip can render natively (its segment+ * composites via alpha, so fade and zoom map onto the existing alpha/zoom+ * ramps; slides, wipes and pop would need per-frame overlay motion). Anything+ * else degrades to a fade on upper tracks. */+export function overlayAnimStyle(style: AnimStyle): "fade" | "zoom" {+ return style === "zoom" ? "zoom" : "fade";+}++/** Preset filter looks: a named color/effect treatment baked over a clip's+ * picture in both preview and export. */+export type LookStyle =+ | "vintage"+ | "vhs"+ | "horror"+ | "halation"+ | "tech"+ | "noir"+ | "grain"+ | "pastel"+ | "blockbuster"+ | "dreamy";++export const LOOK_IDS: LookStyle[] = [+ "vintage",+ "vhs",+ "horror",+ "halation",+ "tech",+ "noir",+ "grain",+ "pastel",+ "blockbuster",+ "dreamy",+];++export const LOOK_LABELS: Record<LookStyle, string> = {+ vintage: "Vintage",+ vhs: "VHS",+ horror: "Analogue horror",+ halation: "Halation",+ tech: "Modern tech",+ noir: "Noir",+ grain: "Film grain",+ pastel: "Pastel",+ blockbuster: "Blockbuster",+ dreamy: "Dreamy",+};++/** Migrate docs saved before per-clip animations existed: the retired edge+ * transition styles (fadein/fadeout/zoomin/zoomout ramped one side of a hard+ * cut) become the equivalent clip animation — fadeout/zoomin on the leading+ * clip's own tail, fadein/zoomout on the following clip's head — and any+ * unknown style falls back to crossfade. Visuals are unchanged; layout never+ * moves (edge styles overlapped nothing, and animations don't either). */+export function migrateLegacyTransitions(clips: VideoClip[]): VideoClip[] {+ const LEGACY: Record<string, { side: "out" | "in"; style: AnimStyle }> = {+ fadeout: { side: "out", style: "fade" },+ zoomin: { side: "out", style: "zoom" },+ fadein: { side: "in", style: "fade" },+ zoomout: { side: "in", style: "zoom" },+ };+ const known = new Set<string>(TRANSITION_STYLE_IDS);+ if (+ !clips.some(+ (c) => c.transitionStyle && !known.has(c.transitionStyle as string)+ )+ ) {+ return clips;+ }+ const out = clips.map((c) => ({ ...c }));+ const byTrack = new Map<number, VideoClip[]>();+ for (const c of out) {+ const row = byTrack.get(c.track) ?? [];+ row.push(c);+ byTrack.set(c.track, row);+ }+ for (const row of byTrack.values()) {+ row.sort((a, b) => a.start - b.start);+ row.forEach((c, i) => {+ const raw = c.transitionStyle as string | undefined;+ if (!raw || known.has(raw)) return;+ const legacy = LEGACY[raw];+ const seconds = Math.min(c.transition ?? 0, TRANSITION_MAX);+ if (legacy && seconds > 0) {+ const target = legacy.side === "out" ? c : row[i + 1];+ if (target) {+ const key = legacy.side === "out" ? "animOut" : "animIn";+ target[key] ??= { style: legacy.style, seconds };+ }+ }+ // The edge ramp never overlapped, so the joint itself was a hard cut.+ c.transition = undefined;+ c.transitionStyle = undefined;+ });+ }+ return out;+}+/** A clip on the free-form soundtrack track. */export interface AudioClip {id: string;diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 7185db31..2ef97284 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -7,8 +7,9 @@ import { createJobRegistry } from "./jobRegistry";import { exportsDir, mediaPath, projectDir, readProject } from "./projects";import { currentCutUser } from "./userScope";import { atempoChain, hasStream, num, videoColorInfo } from "./util";-import { projectFadeSeconds, TRANSITION_ZOOM, type ColorGrade } from "../lib/types";+import { projectFadeSeconds, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";import { gradeToFfmpegFilter } from "../lib/colorGrade";+import { lookFilterLines } from "../lib/looks";export interface ExportSpec {projectId: string;@@ -39,15 +40,22 @@ export interface ExportSpec {/** Region of the frame this clip fills; absent = full frame. */frame?: { x: number; y: number; w: number; h: number };speed?: number; // playback rate, default 1- /** Cross-dissolve into the next clip, in timeline seconds (overlap). */+ /** Transition into the next clip, in timeline seconds (overlap). */transition?: number;- /** Edge-transition ramps, timeline seconds from this segment's head/tail:- * fades to/from black and zoom pushes. Cross zoom arrives as a tailZoom on- * one clip plus a headZoom on the next, riding the crossfade overlap. */- headFade?: number;- tailFade?: number;- headZoom?: number;- tailZoom?: number;+ /** Transition look id, resolved to an xfade name through the+ * TRANSITION_XFADE allowlist (unknown ids render as a plain fade). Cross+ * zoom renders as the fade plus zoom ramps on both segments' overlap+ * windows. */+ transitionStyle?: string;+ /** This clip's own entrance/exit animation, baked into the segment's+ * head/tail window: fade (audio follows), zoom, pop, or a slide+ * against black. Unknown styles render as a fade. */+ animIn?: { style: string; seconds: number };+ animOut?: { style: string; seconds: number };+ /** Preset filter look id + strength 0..1, baked into the segment (the+ * spec carries only the id — the chain is built server-side). */+ look?: string;+ lookAmount?: number;/** Hidden clips keep their slot but render black + silent. */hidden?: boolean;/** A still image: looped for the clip's length instead of trimmed. */@@ -83,6 +91,10 @@ export interface ExportSpec {image?: boolean;/** Manual color adjustments, baked into this overlay's segment. */grade?: ColorGrade;+ /** Preset filter look id + strength (footage overlays only — image+ * overlays may carry alpha the look chain would flatten). */+ look?: string;+ lookAmount?: number;}[];audio: {file: string;@@ -617,19 +629,24 @@ 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 = (+ /** One edge effect on a segment's head or tail window. `zoom` ramps scale+ * (settling in on the head, pushing in on the tail); `xfade` runs the named+ * xfade transition against a backdrop — the label in `bg` (a neighbor's+ * held frame), or a black frame when absent; `pop` scales the picture up+ * from / down to 80% with a fade over the same backdrop. */+ type EdgeFx = { kind: "zoom" | "pop" | "xfade"; secs: number; xfade?: string; bg?: string };++ /** Emit `core` into `[out]` with the head/tail edge effects confined to+ * their windows and `fades` appended. Each effected window is sliced out+ * (split → trim → fx → concat) so per-frame effects stay inside the short+ * ramp; plain fades ride `fades` inline instead. `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 pushEdgeFx = (core: string,dur: number,- hz: number,- tz: number,+ head: EdgeFx | null,+ tail: EdgeFx | null,w: number,h: number,fmt: string,@@ -637,7 +654,10 @@ async function runExport(job: Job, spec: ExportSpec) {out: string,tag: string) => {- const ramp = (side: "head" | "tail", secs: number) => {+ const zoomRamp = (side: "head" | "tail", secs: number) => {+ // 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 frames = Math.max(1, Math.round(secs * fps) - 1);const k = num(TRANSITION_ZOOM - 1);const z =@@ -649,44 +669,178 @@ async function runExport(job: Job, spec: ExportSpec) {`:d=1:s=${w}x${h}:fps=${fps},setsar=1,format=${fmt}`);};- if (hz <= 0.01 && tz <= 0.01) {+ // Emit one sliced window's effect from `[inLab]` to `[outLab]`. The+ // multi-input effects push their own filter lines.+ const applyFx = (fx: EdgeFx, side: "head" | "tail", inLab: string, outLab: string) => {+ const d = num(fx.secs);+ if (fx.kind === "zoom") {+ filters.push(`[${inLab}]${zoomRamp(side, fx.secs)}[${outLab}]`);+ return;+ }+ // The backdrop behind the window: a neighbor's held frame when given+ // (an abutting cut), else black (timeline ends and gaps).+ let bg = fx.bg;+ if (!bg) {+ bg = `xb${tag}_${side}`;+ filters.push(`color=c=black:s=${w}x${h}:r=${fps}:d=${d},format=${fmt}[${bg}]`);+ }+ if (fx.kind === "xfade") {+ // Entering: the backdrop hands off to the picture; exiting: the+ // picture hands off to the backdrop. Anim style ids map straight to+ // xfade names (probed: slideleft moves the frame leftward, so it+ // enters from the right edge and exits off the left; cover/reveal+ // and wipes share the same direction footprints).+ filters.push(+ side === "head"+ ? `[${bg}][${inLab}]xfade=transition=${fx.xfade}:duration=${d}:offset=0[${outLab}]`+ : `[${inLab}][${bg}]xfade=transition=${fx.xfade}:duration=${d}:offset=0[${outLab}]`+ );+ return;+ }+ // Pop: scale 80%↔100% over the window (even dimensions for yuv420p),+ // centered over the backdrop. With a held-frame backdrop the picture+ // alpha-fades so the neighbor stays visible behind it; over black the+ // plain fade is the same thing cheaper.+ const p = side === "head" ? `min(t/${d},1)` : `1-min(t/${d},1)`;+ const sc = `sc${tag}_${side}`;+ const scaleExpr = `scale=w='trunc(iw*(0.8+0.2*(${p}))/2)*2':h=-2:eval=frame`;+ if (fx.bg) {+ filters.push(+ `[${inLab}]format=yuva420p,` ++ `fade=t=${side === "head" ? "in" : "out"}:st=0:d=${d}:alpha=1,${scaleExpr}[${sc}]`+ );+ filters.push(+ `[${bg}][${sc}]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1,format=${fmt}[${outLab}]`+ );+ return;+ }+ filters.push(`[${inLab}]${scaleExpr}[${sc}]`);+ filters.push(+ `[${bg}][${sc}]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1,` ++ `fade=t=${side === "head" ? "in" : "out"}:st=0:d=${d},format=${fmt}[${outLab}]`+ );+ };+ const hs = head && head.secs > 0.01 ? head : null;+ const ts = tail && tail.secs > 0.01 ? tail : null;+ if (!hs && !ts) {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;- }+ const slices: { from: number; to: number; fx?: EdgeFx; side: "head" | "tail" }[] = [];+ if (hs) slices.push({ from: 0, to: hs.secs, fx: hs, side: "head" });+ const mid0 = hs ? hs.secs : 0;+ const mid1 = ts ? dur - ts.secs : dur;+ if (mid1 - mid0 > 0.01) slices.push({ from: mid0, to: mid1, side: "head" });+ if (ts) slices.push({ from: dur - ts.secs, to: dur, fx: ts, side: "tail" });filters.push(`${core},split=${slices.length}${slices.map((_, k) => `[zs${tag}_${k}]`).join("")}`);slices.forEach((sl, k) => {+ const cut = `zc${tag}_${k}`;+ // setpts clears the constant-frame-rate metadata the slice xfades+ // demand — re-stamp it on every cut.filters.push(- `[zs${tag}_${k}]trim=${num(sl.from)}:${num(sl.to)},setpts=PTS-STARTPTS` +- (sl.fx ? `,${sl.fx}` : "") +- `[zp${tag}_${k}]`+ `[zs${tag}_${k}]trim=${num(sl.from)}:${num(sl.to)},setpts=PTS-STARTPTS,fps=${fps}[${cut}]`);+ if (sl.fx) applyFx(sl.fx, sl.side, cut, `zp${tag}_${k}`);+ else filters.push(`[${cut}]null[zp${tag}_${k}]`);});+ // concat drops the stream's constant-frame-rate metadata and a downstream+ // xfade join refuses a variable-rate input — re-stamp it.filters.push(slices.map((_, k) => `[zp${tag}_${k}]`).join("") +- `concat=n=${slices.length}:v=1:a=0${fades}[${out}]`+ `concat=n=${slices.length}:v=1:a=0,fps=${fps}${fades}[${out}]`);};+ /** The edge effect a clip animation asks for, or null when it's a plain+ * fade (fades ride the inline `fade`/`afade` filters instead of a slice).+ * Unknown styles fall back to the fade path. */+ const animEdgeFx = (a: { style: string; seconds: number } | undefined, max: number): EdgeFx | null => {+ if (!a || a.seconds <= 0.01 || max <= 0.01) return null;+ const secs = Math.min(a.seconds, max);+ if (a.style === "zoom") return { kind: "zoom", secs };+ if (a.style === "pop") return { kind: "pop", secs };+ if (/^slide(left|right|up|down)$/.test(a.style)) {+ return { kind: "xfade", secs, xfade: a.style };+ }+ return null;+ };++ /** Whether an animation renders through the inline fade filters. */+ const isFadeAnim = (a: { style: string; seconds: number } | undefined) =>+ !!a && a.seconds > 0.01 && !animEdgeFx(a, Infinity);++ // A clip animation at an abutting hard cut plays over the neighbor's held+ // frame instead of black — an entrance covers the previous clip's last+ // frame, an exit reveals the next clip's first frame. Black remains where+ // there is no neighbor: the timeline's ends, gaps (the adjacent entry is a+ // spacer), and hidden neighbors. Zoom never uncovers the frame, so it needs+ // no backdrop. Precomputed so pass 1 can defer these animations and split+ // off the freeze sources the second pass consumes.+ const freezable = (c?: ExportSpec["clips"][number]) =>+ !!c && !!c.file && !c.hidden && (!!c.image || !!videoPresence.get(c.file));+ const effAnimIn = (j: number) => {+ const p = spec.clips[j - 1];+ return p && (p.transition ?? 0) > 0.01 ? undefined : spec.clips[j].animIn;+ };+ const effAnimOut = (j: number) => {+ const n = spec.clips[j + 1];+ return n && (spec.clips[j].transition ?? 0) > 0.01 ? undefined : spec.clips[j].animOut;+ };+ const backdropAnim = (a?: { style: string; seconds: number }) =>+ a && a.seconds > 0.01 && a.style !== "zoom" ? a : undefined;+ const headBd = spec.clips.map(+ (c, j) => !!(freezable(c) && backdropAnim(effAnimIn(j)) && freezable(spec.clips[j - 1]))+ );+ const tailBd = spec.clips.map(+ (c, j) => !!(freezable(c) && backdropAnim(effAnimOut(j)) && freezable(spec.clips[j + 1]))+ );+ const needFirstFreeze = spec.clips.map((_, j) => j > 0 && tailBd[j - 1]);+ const needLastFreeze = spec.clips.map((_, j) => j < spec.clips.length - 1 && headBd[j + 1]);+// 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)!;const speed = clipRate(c);const dur = clipDur(c);- // Edge-transition ramps, clamped so head+tail never overrun the segment.- const hz = Math.max(0, Math.min(c.headZoom ?? 0, dur));- const tz = Math.max(0, Math.min(c.tailZoom ?? 0, dur - hz));- const hf = Math.max(0, Math.min(c.headFade ?? 0, dur));- const tf = Math.max(0, Math.min(c.tailFade ?? 0, dur - hf));+ const prevC = spec.clips[j - 1];+ const nextC = spec.clips[j + 1];+ // Cross zoom renders as the fade join plus zoom ramps riding the overlap+ // window on both segments (clamped like the join clamps its overlap).+ const czOverlap = (a: (typeof spec.clips)[number], aDur: number, bDur: number) =>+ a.transitionStyle === "crosszoom"+ ? Math.min(a.transition ?? 0, aDur * 0.9, bDur * 0.9)+ : 0;+ const czHead = prevC ? czOverlap(prevC, clipDur(prevC), dur) : 0;+ const czTail = nextC ? czOverlap(c, dur, clipDur(nextC)) : 0;+ // A transitioned joint owns its edges: with a live overlap into or out of+ // this clip, that side's animation is held (running both would fight over+ // the same window) — `transition` in the spec is already the clamped live+ // overlap, so 0 means a hard cut and the animation plays. Matches the+ // preview's suppression exactly.+ const animIn = prevC && (prevC.transition ?? 0) > 0.01 ? undefined : c.animIn;+ const animOut = nextC && (c.transition ?? 0) > 0.01 ? undefined : c.animOut;+ // The clip's own animations own their edge windows (fade animations ride+ // the inline fade filters below); cross zoom fills a side its animation+ // leaves free. Clamped so head+tail never overrun the segment. Backdrop+ // animations are deferred to the second pass, which runs them against the+ // neighbor's held frame — only their audio fade stays here.+ const animInNow = headBd[j] ? undefined : animIn;+ const animOutNow = tailBd[j] ? undefined : animOut;+ let headFx = animEdgeFx(animInNow, dur);+ let tailFx = animEdgeFx(animOutNow, dur - (headFx?.secs ?? 0));+ const hf = isFadeAnim(animInNow) ? Math.min(animInNow!.seconds, dur) : 0;+ const tf = isFadeAnim(animOutNow) ? Math.min(animOutNow!.seconds, dur - hf) : 0;+ // The sound of a fade animation follows the picture whether the fade+ // renders inline (over black) or in the backdrop pass.+ const ahf = animIn?.style === "fade" ? Math.min(animIn.seconds, dur) : 0;+ const atf =+ animOut?.style === "fade" ? Math.min(animOut.seconds, Math.max(0, dur - ahf)) : 0;+ if (!headFx && hf <= 0.01 && czHead > 0.01) {+ headFx = { kind: "zoom", secs: Math.min(czHead, dur) };+ }+ if (!tailFx && tf <= 0.01 && czTail > 0.01) {+ tailFx = { kind: "zoom", secs: Math.min(czTail, dur - (headFx?.secs ?? 0)) };+ }// A still's looped input is already the right length at `fps`; it has no// source span to trim. Footage trims `in..out` and re-times by speed.const timebase = c.image@@ -719,11 +873,32 @@ async function runExport(job: Job, spec: ExportSpec) {// a still just replays its looped input.// The grade sits after the color conversion (so it acts on the same// BT.709 values the preview shows) and before the terminal format.- const core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeToFfmpegFilter(c.grade)}format=${clipFmt}`;+ let core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeToFfmpegFilter(c.grade)}format=${clipFmt}`;+ // The look bakes in after grade + framing, before the edge effects, so+ // animations move already-graded pixels (matching the preview order).+ if (c.look) {+ const lines = lookFilterLines(`lki${j}`, `lko${j}`, c.look, c.lookAmount, H, clipFmt, `c${j}`);+ if (lines) {+ filters.push(`${core}[lki${j}]`);+ filters.push(...lines);+ core = `[lko${j}]null`;+ }+ }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)}` : "");- pushZoomRamped(core, dur, hz, tz, W, H, clipFmt, fades, `v${j}`, `c${j}`);+ // A neighbor's backdrop animation freezes a frame of this segment —+ // split the copies it needs off the pre-backdrop picture.+ const nFz = (needFirstFreeze[j] ? 1 : 0) + (needLastFreeze[j] ? 1 : 0);+ const segOut = nFz > 0 ? `vseg${j}` : `v${j}`;+ pushEdgeFx(core, dur, headFx, tailFx, W, H, clipFmt, fades, segOut, `c${j}`);+ if (nFz > 0) {+ filters.push(+ `[vseg${j}]split=${nFz + 1}[v${j}]` ++ (needFirstFreeze[j] ? `[vff${j}]` : "") ++ (needLastFreeze[j] ? `[vfl${j}]` : "")+ );+ }} else {// No video stream, or a hidden clip: the slot plays black.filters.push(@@ -735,8 +910,8 @@ async function runExport(job: Job, spec: ExportSpec) {const vol = (c.volume ?? 1) !== 1 ? `volume=${num(c.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, dur - tf))}:d=${num(tf)}` : "");+ (ahf > 0.01 ? `,afade=t=in:st=0:d=${num(ahf)}` : "") ++ (atf > 0.01 ? `,afade=t=out:st=${num(Math.max(0, dur - atf))}:d=${num(atf)}` : "");filters.push(`[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,${tempo}` +`aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,${vol}` +@@ -749,10 +924,82 @@ async function runExport(job: Job, spec: ExportSpec) {}});+ // Second pass: the backdrop animations. Each slices its edge window and+ // runs the effect against the neighbor's held frame — frozen via tpad+ // clone from the copies split off above, so a slide-in covers the previous+ // clip's last frame and a slide-out reveals the next clip's first frame.+ // Slides become cover/reveal (the backdrop stays put); pop alpha-blends+ // over the frozen frame; fade — and any unknown stored style — crossfades.+ const segLabel = spec.clips.map((_, j) => `v${j}`);+ const backdropFx = (+ a: { style: string; seconds: number },+ side: "head" | "tail",+ secs: number,+ bg: string+ ): EdgeFx => {+ if (a.style === "pop") return { kind: "pop", secs, bg };+ if (/^slide(left|right|up|down)$/.test(a.style)) {+ const dir = a.style.slice(5);+ return { kind: "xfade", secs, xfade: `${side === "head" ? "cover" : "reveal"}${dir}`, bg };+ }+ return { kind: "xfade", secs, xfade: "fade", bg };+ };+ spec.clips.forEach((c, j) => {+ if (!headBd[j] && !tailBd[j]) return;+ const dur = clipDur(c);+ if (headBd[j]) {+ const a = backdropAnim(effAnimIn(j))!;+ const d = Math.min(a.seconds, dur);+ const durPrev = clipDur(spec.clips[j - 1]);+ // fps is re-stamped before tpad — cloning needs a live frame rate, and+ // trim+setpts strip it (without this the freeze collapses to 1 frame).+ filters.push(+ `[vfl${j - 1}]trim=${num(Math.max(0, durPrev - 0.05))}:${num(durPrev)},setpts=PTS-STARTPTS,fps=${fps},` ++ `tpad=stop_mode=clone:stop_duration=${num(d + 0.5)},trim=0:${num(d)},` ++ `setpts=PTS-STARTPTS,fps=${fps}[fzh${j}]`+ );+ pushEdgeFx(+ `[${segLabel[j]}]null`,+ dur,+ backdropFx(a, "head", d, `fzh${j}`),+ null,+ W,+ H,+ clipFmt,+ "",+ `vhb${j}`,+ `hb${j}`+ );+ segLabel[j] = `vhb${j}`;+ }+ if (tailBd[j]) {+ const a = backdropAnim(effAnimOut(j))!;+ const d = Math.min(a.seconds, dur);+ filters.push(+ `[vff${j + 1}]trim=0:0.05,setpts=PTS-STARTPTS,fps=${fps},` ++ `tpad=stop_mode=clone:stop_duration=${num(d + 0.5)},trim=0:${num(d)},` ++ `setpts=PTS-STARTPTS,fps=${fps}[fzt${j}]`+ );+ pushEdgeFx(+ `[${segLabel[j]}]null`,+ dur,+ null,+ backdropFx(a, "tail", d, `fzt${j}`),+ W,+ H,+ clipFmt,+ "",+ `vtb${j}`,+ `tb${j}`+ );+ segLabel[j] = `vtb${j}`;+ }+ });+// Join the segments. Adjacent clips with a transition cross-dissolve// (xfade/acrossfade, overlapping by the transition length); the rest hard-cut// (concat). Fold left so mixed sequences chain correctly.- let vAcc = "v0";+ let vAcc = segLabel[0];let aAcc = "a0";let acc = clipDur(spec.clips[0]); // running timeline length of the accumulatorfor (let j = 1; j < spec.clips.length; j++) {@@ -764,11 +1011,14 @@ async function runExport(job: Job, spec: ExportSpec) {const aOut = `aj${j}`;if (d > 0.01) {const offset = Math.max(0, acc - d);- filters.push(`[${vAcc}][v${j}]xfade=transition=fade:duration=${num(d)}:offset=${num(offset)}[${vOut}]`);+ // The style id resolves through the allowlist map; anything unknown+ // (or an old spec without a style) renders as a plain fade.+ const kind = TRANSITION_XFADE[prev.transitionStyle as TransitionStyle] ?? "fade";+ filters.push(`[${vAcc}][${segLabel[j]}]xfade=transition=${kind}:duration=${num(d)}:offset=${num(offset)}[${vOut}]`);filters.push(`[${aAcc}][a${j}]acrossfade=d=${num(d)}[${aOut}]`);acc = acc + durJ - d;} else {- filters.push(`[${vAcc}][v${j}]concat=n=2:v=1:a=0[${vOut}]`);+ filters.push(`[${vAcc}][${segLabel[j]}]concat=n=2:v=1:a=0[${vOut}]`);filters.push(`[${aAcc}][a${j}]concat=n=2:v=0:a=1[${aOut}]`);acc = acc + durJ;}@@ -835,9 +1085,32 @@ 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)}`;- const core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${fmt}`;+ let core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${fmt}`;+ // Looks bake into footage overlays only: an image may carry alpha, and a+ // padded letterbox has transparent margins — the look chain's internal+ // filters would flatten either onto black over the tracks beneath. The+ // alpha fades stay safe: they apply after the look.+ if (oc.look && !oc.image && !(ramped && !cover)) {+ const lines = lookFilterLines(`olki${k}`, `olko${k}`, oc.look, oc.lookAmount, H, fmt, `o${k}`);+ if (lines) {+ filters.push(`${core}[olki${k}]`);+ filters.push(...lines);+ core = `[olko${k}]null`;+ }+ }const pre = `ovp${k}`;- pushZoomRamped(core, olen, hz, tz, boxW, boxH, fmt, fades, pre, `o${k}`);+ pushEdgeFx(+ core,+ olen,+ hz > 0.01 ? { kind: "zoom", secs: hz } : null,+ tz > 0.01 ? { kind: "zoom", secs: tz } : null,+ 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.