Open source CapCut alternative.
TypeScript
feat(site): read a whole-picture fade off a reference and ease a flash fade along its curve [rebuild]
David Le5eaa70e25fc4
diff --git a/evals/cut-perf.latest-report.json b/evals/cut-perf.latest-report.jsonindex d78ebf39..688dd815 100644--- a/evals/cut-perf.latest-report.json+++ b/evals/cut-perf.latest-report.json@@ -51,10 +51,10 @@},"frameMs": 16.7,"scrub": {- "p50": 15.7,- "p95": 32.7,- "mean": 18,- "max": 32.9,+ "p50": 15.8,+ "p95": 31.9,+ "mean": 18.27,+ "max": 32.8,"n": 41},"longTasks": {@@ -64,7 +64,7 @@"max": 0,"n": 0},- "liveSamples": 55,+ "liveSamples": 67,"machine": "desktop"},{@@ -74,17 +74,17 @@"notes": [],"late": {"p50": 0,- "p95": 0,- "mean": 0.05,- "max": 1,+ "p95": 1,+ "mean": 0.15,+ "max": 2,"n": 41},"frameMs": 16.7,"scrub": {"p50": 15.5,- "p95": 16.8,- "mean": 16.14,- "max": 33.2,+ "p95": 33.3,+ "mean": 17.56,+ "max": 45.9,"n": 41},"longTasks": {@@ -94,7 +94,7 @@"max": 0,"n": 0},- "liveSamples": 58,+ "liveSamples": 63,"machine": "desktop"},{@@ -111,10 +111,10 @@},"frameMs": 16.7,"scrub": {- "p50": 15.7,- "p95": 16.6,- "mean": 15.83,- "max": 32.4,+ "p50": 15.2,+ "p95": 17.6,+ "mean": 15.89,+ "max": 31.6,"n": 41},"longTasks": {@@ -124,7 +124,7 @@"max": 0,"n": 0},- "liveSamples": 75,+ "liveSamples": 67,"machine": "desktop"},{@@ -141,10 +141,10 @@},"frameMs": 16.7,"scrub": {- "p50": 15.3,- "p95": 16.7,- "mean": 15.5,- "max": 36.9,+ "p50": 15.4,+ "p95": 17.4,+ "mean": 15.9,+ "max": 32.2,"n": 81},"longTasks": {@@ -166,15 +166,15 @@"p50": 0,"p95": 1,"mean": 0.17,- "max": 2,+ "max": 1,"n": 41},"frameMs": 16.7,"scrub": {"p50": 15.7,- "p95": 32.3,- "mean": 18.24,- "max": 49.2,+ "p95": 32.7,+ "mean": 18.42,+ "max": 33.5,"n": 41},"longTasks": {@@ -184,7 +184,7 @@"max": 0,"n": 0},- "liveSamples": 56,+ "liveSamples": 44,"machine": "desktop"},{@@ -201,10 +201,10 @@},"frameMs": 16.7,"scrub": {- "p50": 15.7,- "p95": 32.5,- "mean": 18.7,- "max": 48.6,+ "p50": 15.8,+ "p95": 31.7,+ "mean": 18.89,+ "max": 49.2,"n": 41},"longTasks": {@@ -214,7 +214,7 @@"max": 0,"n": 0},- "liveSamples": 47,+ "liveSamples": 63,"machine": "desktop"},{@@ -225,16 +225,16 @@"late": {"p50": 1,"p95": 1,- "mean": 0.98,- "max": 2,+ "mean": 0.9,+ "max": 1,"n": 41},"frameMs": 16.7,"scrub": {- "p50": 31.9,- "p95": 32.7,- "mean": 28.87,- "max": 48.8,+ "p50": 31.8,+ "p95": 33.6,+ "mean": 30.35,+ "max": 34,"n": 41},"longTasks": {@@ -289,13 +289,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 810,+ "presented": 809,"lag": {"p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 810+ "n": 809},"stallShare": 0,"decay": {@@ -326,13 +326,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 3237,+ "presented": 3242,"lag": {"p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 3237+ "n": 3242},"stallShare": 0,"decay": {@@ -363,13 +363,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 221,+ "presented": 222,"lag": {- "p50": 0.02,+ "p50": 0.01,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 221+ "n": 222},"stallShare": 0,"decay": {@@ -474,13 +474,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 3444,+ "presented": 3443,"lag": {- "p50": 0.01,+ "p50": 0.02,"p95": 0.03,- "mean": 0.02,+ "mean": 0.01,"max": 0.03,- "n": 3444+ "n": 3443},"stallShare": 0,"decay": {@@ -492,10 +492,10 @@"reported": 0.04},"longTasks": {- "p50": 73,- "p95": 73,- "mean": 73,- "max": 73,+ "p50": 51,+ "p95": 51,+ "mean": 51,+ "max": 51,"n": 1},"liveSamples": 10,@@ -513,7 +513,7 @@"drops": 0,"presented": 3444,"lag": {- "p50": 0.02,+ "p50": 0.01,"p95": 0.03,"mean": 0.02,"max": 0.03,@@ -529,11 +529,11 @@"reported": 0.04},"longTasks": {- "p50": 78,- "p95": 78,- "mean": 65.5,- "max": 78,- "n": 2+ "p50": 59,+ "p95": 59,+ "mean": 59,+ "max": 59,+ "n": 1},"liveSamples": 10,"liveSources": 1,@@ -622,13 +622,13 @@"pass": true,"notes": [],"drops": 0,- "presented": 1621,+ "presented": 1620,"lag": {"p50": 0.02,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 1621+ "n": 1620},"stallShare": 0,"decay": {@@ -692,13 +692,13 @@"pass": true,"notes": [],"drops": 3,- "presented": 1094,+ "presented": 1095,"lag": {- "p50": 0.02,+ "p50": 0.01,"p95": 0.03,"mean": 0.02,"max": 0.03,- "n": 1091+ "n": 1092},"stallShare": 0,"decay": {@@ -710,10 +710,10 @@"reported": 0.04},"longTasks": {- "p50": 202,- "p95": 202,- "mean": 136.5,- "max": 202,+ "p50": 167,+ "p95": 167,+ "mean": 120,+ "max": 167,"n": 2},"liveSamples": 10,diff --git a/site/packages/effects-kit/src/ease.ts b/site/packages/effects-kit/src/ease.tsindex fcc25ad1..2b8bea24 100644--- a/site/packages/effects-kit/src/ease.ts+++ b/site/packages/effects-kit/src/ease.ts@@ -82,3 +82,30 @@ export function easeAt(id: EaseId | undefined, p: number): number {return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;}}++/** easeAt as an ffmpeg expression over progress `u` (already 0..1), so a+ * filter graph runs the same curve the preview does. */+export function easeExpr(id: EaseId | undefined, u: string): string {+ switch (id) {+ case "sine.in":+ return `(1-cos(${u}*PI/2))`;+ case "sine.out":+ return `sin(${u}*PI/2)`;+ case "sine.inOut":+ return `((1-cos(PI*${u}))/2)`;+ case "power2.in":+ return `pow(${u},2)`;+ case "power2.out":+ return `(1-pow(1-${u},2))`;+ case "power2.inOut":+ return `if(lt(${u},0.5),2*pow(${u},2),1-pow(2-2*${u},2)/2)`;+ case "power3.in":+ return `pow(${u},3)`;+ case "power3.out":+ return `(1-pow(1-${u},3))`;+ case "power3.inOut":+ return `if(lt(${u},0.5),4*pow(${u},3),1-pow(2-2*${u},3)/2)`;+ default:+ return u;+ }+}diff --git a/site/packages/effects-kit/src/effects.ts b/site/packages/effects-kit/src/effects.tsindex c3cc5ac8..606b0587 100644--- a/site/packages/effects-kit/src/effects.ts+++ b/site/packages/effects-kit/src/effects.ts@@ -12,6 +12,7 @@ import type { OverlayBase } from "./types";import { AUDIO_EFFECT_IDS, AUDIO_EFFECT_LABELS, type AudioEffectId } from "./audioFx";import { LOOK_LABELS, lookCssFilter, lookFilterLines, lookPost, type LookStyle } from "./looks";import { kitCanvas } from "./surface";+import { easeAt, easeExpr, type EaseId } from "./ease";/** The effects that treat the picture. */export type VisualEffectId =@@ -68,9 +69,12 @@ export interface EffectOverlay extends OverlayBase {rate?: number;/** How a strobe's pulses land; absent = strobe. */rhythm?: FlashRhythm;- /** A flash that ramps evenly across the whole element; absent = the pop- * (or the strobe). */+ /** A flash that ramps across the whole element; absent = the pop (or+ * the strobe). */fade?: FlashFade;+ /** The curve a flash's fade runs along: `power2.out` darkens quickly and+ * settles onto the tone; absent = the even ramp. */+ fadeEase?: EaseId;}/** A flash's color: `white` pops the picture bright, `black` dips it dark. */@@ -89,8 +93,8 @@ export const FLASH_RATE_MAX = 15;export const FLASH_RHYTHMS = ["strobe", "flicker"] as const;export type FlashRhythm = (typeof FLASH_RHYTHMS)[number];-/** A flash that ramps evenly across its element and up- * to the full tone at amount 1: `to` fades the picture into the tone (a fade+/** A flash that ramps across its element (evenly, or along its fadeEase) and+ * up to the full tone at amount 1: `to` fades the picture into the tone (a fade* to black over the end of a scene), `from` starts on the tone and clears (a* fade up from black). It covers everything on the rows behind its own, so* on the front row it fades a whole stacked page as one. */@@ -104,7 +108,7 @@ export const FLASH_FADE_CHOICES = [FLASH_FADE_NONE, ...FLASH_FADES] as const;export type FlashFadeChoice = (typeof FLASH_FADE_CHOICES)[number];/** What a flash plays beyond its amount: its tone, strobe rate, rhythm and fade. */-export type FlashPulse = Pick<EffectOverlay, "tone" | "rate" | "rhythm" | "fade">;+export type FlashPulse = Pick<EffectOverlay, "tone" | "rate" | "rhythm" | "fade" | "fadeEase">;/** How far past a frame's time a pulse is read, in pulses: at the top rate* every 30 fps frame lands on a pulse's edge, and the nudge keeps rounding@@ -1127,10 +1131,10 @@ export function effectPreviewState(case "flash": {// One pop at the element start, decaying over ~0.4s; on a strobe, the// tone held hard for the first half of every pulse; on a fade, the- // tone ramped evenly across the element, to full at amount 1.+ // tone ramped across the element along its ease, to full at amount 1.const tone = pulse?.tone === "black" ? "black" : undefined;if (pulse?.fade && dur) {- const u = Math.max(0, Math.min(1, tLocal / dur));+ const u = easeAt(pulse.fadeEase, tLocal / dur);return { cssFilter: "", flash: k * (pulse.fade === "to" ? u : 1 - u), ...(tone ? { flashTone: tone } : {}) };}const rate = flashRate(pulse);@@ -1840,9 +1844,9 @@ export function effectFilterLines(// frame of the window. White adds to luma; black pulls every plane// toward black at the canvas pass's alpha.if (pulse?.fade) {- // The fade's even ramp: every plane pulled toward the tone at the- // canvas pass's alpha, white as well as black.- const u = `clip((T-${fmt(start)})/${fmt(Math.max(1e-3, end - start))},0,1)`;+ // The fade's ramp along its ease: every plane pulled toward the tone+ // at the canvas pass's alpha, white as well as black.+ const u = easeExpr(pulse.fadeEase, `clip((T-${fmt(start)})/${fmt(Math.max(1e-3, end - start))},0,1)`);const keep = `(1-${fmt(k)}*${pulse.fade === "to" ? u : `(1-${u})`})`;const mid = code(128, chroma.depth);const toward = code(pulse.tone === "black" ? 16 : 235, chroma.depth);diff --git a/site/packages/effects-kit/src/flashFade.test.ts b/site/packages/effects-kit/src/flashFade.test.tsindex b7b7db3b..0934950b 100644--- a/site/packages/effects-kit/src/flashFade.test.ts+++ b/site/packages/effects-kit/src/flashFade.test.ts@@ -47,14 +47,25 @@ describe("a flash that fades", () => {expect(effectPreviewState("flash", 0.5, DUR, undefined, undefined, DUR, { fade: "to" }).flash).toBeCloseTo(0.5, 5);});+ test("an eased fade runs along its curve and still lands on the full tone", () => {+ const at = (t: number, fade: "to" | "from") =>+ effectPreviewState("flash", 1, t, undefined, undefined, DUR, { tone: "black", fade, fadeEase: "power2.out" }).flash ?? 0;+ // Quick at first: three quarters of the way there by half time.+ expect(at(0.5, "to")).toBeCloseTo(0.75, 5);+ expect(at(DUR, "to")).toBeCloseTo(1, 5);+ // Out of the tone the same way: a quarter left by half time.+ expect(at(0, "from")).toBeCloseTo(1, 5);+ expect(at(0.5, "from")).toBeCloseTo(0.25, 5);+ });+test("a full fade to black ends on black in the canvas pass", () => {expect(Math.max(...canvasAt(DUR - 1e-6, { tone: "black", fade: "to" }))).toBeLessThan(2);});for (const tone of ["black", "white"] as const) {test(`ffmpeg fades to and from ${tone} the way the canvas does`, () => {- for (const fade of ["to", "from"] as const) {- const pulse: FlashPulse = { tone: tone === "black" ? "black" : undefined, fade };+ for (const [fade, fadeEase] of [["to", undefined], ["from", undefined], ["to", "sine.out"], ["from", "power3.in"]] as const) {+ const pulse: FlashPulse = { tone: tone === "black" ? "black" : undefined, fade, ...(fadeEase ? { fadeEase } : {}) };const chroma = { pixFmt: "yuv444p", overlay: ":format=yuv444" };const lines = effectFilterLines("in", "out", "flash", 1, 0, DUR, W, H, "t", undefined, undefined, chroma, pulse)!;const graph = `color=c=0x787878:s=${W}x${H}:r=${FPS}:d=${DUR},format=yuv444p[in];${lines.join(";")}`;diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex 662e60c3..a81dd87b 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -241,7 +241,7 @@ export const AI_PANEL_TOOLS = [{name: "detect_cuts",description:- `Find every hard cut in a stretch of a video source, to the frame. Reads every frame between from and to at a few dozen pixels, scores how much of the picture changed since the frame before, and reports each frame that opens a new shot: \`t\` in SOURCE seconds to the millisecond (the new shot's first frame), its \`frame\` index at the source's \`fps\`, and \`change\`, the percent of the picture that changed — near 100 is a new shot, 10-30 a card or a block of type swapping over the same background. A flat colour cut to a near one counts. \`shots\` lists the stretches between the cuts with their length in frames. \`changes\` lists what changes inside a shot over a picture that stays: a word appearing, a word swapping fill for outline, a shape popping in, a face switching — each its first frame (\`t\`, \`frame\`), how many frames it runs (a fade-in runs several), its \`change\` in percent and its \`box\`. A change marked \`flicker\` flips back and forth frame by frame over its run — a strobe, a cutout flashing to its negative — so every frame of it differs from the one before and returns to a look two or three frames old; read its frames one at a time. A fade too faint for any one frame to show — small type easing in or out over half a second — still counts: its \`frame\` is the first step it takes and \`frames\` runs to where it settles, so a title's fade in, fade out and their lengths come from here. Time titles, their fades, outline swaps, shape pops and font_cycle_switches from these. watch_video lands a frame in every shot and change this reads, so read type after this pass. watch_video's sceneChanges come from samples a step apart and lose a shot shorter than the step; this reads every frame, so a five-frame shot in a fast montage is found. Run it before blocking out a reference: add_clip \`blocks\` takes one block per shot at that shot's length. Hard cuts only — a dissolve or a fade between two shots changes a little each frame and reads as no cut. Up to ${DETECT_CUTS_SPAN_MAX}s, ${DETECT_CUTS_MAX} cuts and ${DETECT_CHANGES_MAX} changes a call; when \`truncated\`, call again from \`coveredTo\`. A source with no picture box yet has it found first (find_picture) and kept, and every frame is read inside it, so a card that changes a small part of a recorded frame still counts as the change to the picture it is.`,+ `Find every hard cut in a stretch of a video source, to the frame. Reads every frame between from and to at a few dozen pixels, scores how much of the picture changed since the frame before, and reports each frame that opens a new shot: \`t\` in SOURCE seconds to the millisecond (the new shot's first frame), its \`frame\` index at the source's \`fps\`, and \`change\`, the percent of the picture that changed — near 100 is a new shot, 10-30 a card or a block of type swapping over the same background. A flat colour cut to a near one counts. \`shots\` lists the stretches between the cuts with their length in frames. \`changes\` lists what changes inside a shot over a picture that stays: a word appearing, a word swapping fill for outline, a shape popping in, a face switching — each its first frame (\`t\`, \`frame\`), how many frames it runs (a fade-in runs several), its \`change\` in percent and its \`box\`. A change marked \`flicker\` flips back and forth frame by frame over its run — a strobe, a cutout flashing to its negative — so every frame of it differs from the one before and returns to a look two or three frames old; read its frames one at a time. A fade too faint for any one frame to show — small type easing in or out over half a second — still counts: its \`frame\` is the first step it takes and \`frames\` runs to where it settles, so a title's fade in, fade out and their lengths come from here. Time titles, their fades, outline swaps, shape pops and font_cycle_switches from these. watch_video lands a frame in every shot and change this reads, so read type after this pass. watch_video's sceneChanges come from samples a step apart and lose a shot shorter than the step; this reads every frame, so a five-frame shot in a fast montage is found. Run it before blocking out a reference: add_clip \`blocks\` takes one block per shot at that shot's length. Hard cuts only — a dissolve or a fade between two shots changes a little each frame and reads as no cut. A fade of the whole picture into black or white, or out of it, is listed in \`fades\`: its start \`t\`, \`seconds\`, \`fade\` (to or from), \`tone\`, how far it goes (\`amount\`) and the curve it runs along (\`ease\`), each fitted to every frame — exactly what add_effect flash takes, so a fade to black over the end is set from here, never from sampled colours. Up to ${DETECT_CUTS_SPAN_MAX}s, ${DETECT_CUTS_MAX} cuts and ${DETECT_CHANGES_MAX} changes a call; when \`truncated\`, call again from \`coveredTo\`. A source with no picture box yet has it found first (find_picture) and kept, and every frame is read inside it, so a card that changes a small part of a recorded frame still counts as the change to the picture it is.`,inputSchema: obj({asset_id: str("Project asset id of the video"),diff --git a/site/src/cut/components/EffectsPanel.tools.ts b/site/src/cut/components/EffectsPanel.tools.tsindex f41d277f..ee9ec355 100644--- a/site/src/cut/components/EffectsPanel.tools.ts+++ b/site/src/cut/components/EffectsPanel.tools.ts@@ -6,7 +6,7 @@* removed or renamed tool breaks the build until every side catches up.*/-import { ALL_EFFECT_IDS, AUDIO_EFFECT_IDS, EFFECT_IDS, FLASH_FADE_CHOICES, FLASH_FADE_NONE, FLASH_RHYTHMS, FLASH_RATE_MAX, FLASH_RATE_MIN, FLASH_TONES, GLITCH_KINDS, LEAK_COURSES, LOOK_EFFECTS } from "@donkeycut/effects-kit";+import { ALL_EFFECT_IDS, EASE_IDS, AUDIO_EFFECT_IDS, EFFECT_IDS, FLASH_FADE_CHOICES, FLASH_FADE_NONE, FLASH_RHYTHMS, FLASH_RATE_MAX, FLASH_RATE_MIN, FLASH_TONES, GLITCH_KINDS, LEAK_COURSES, LOOK_EFFECTS } from "@donkeycut/effects-kit";import { num, obj, type AiToolDef } from "@/cut/lib/aiToolDef";/** The effects with a treatment recipe of their own; the rest of the list is@@ -45,6 +45,11 @@ export const EFFECT_SETTING_ARGS = {enum: [...FLASH_FADE_CHOICES],description: `flash only: ramp evenly across the whole element to the full tone at amount 1 — "to" fades the picture into the tone, "from" starts on it and clears, "${FLASH_FADE_NONE}" takes the fade off again. On the front row (lane 0, rows moved down with move_row if it is taken) it fades everything behind it as one, so a fade to black over the end of a stacked page (video, scrims, text, buttons, a pointer) goes black together as one picture`,},+ fade_ease: {+ type: "string",+ enum: [...EASE_IDS],+ description: `flash with a fade only: the curve it runs along — "power2.out" darkens quickly and settles onto the tone, "sine.in" holds the picture and goes late; "linear" (default) is the even ramp. A fade read off a reference (detect_cuts \`fades\`) names its ease: pass it as it comes`,+ },};export const EFFECTS_TOOLS = [diff --git a/site/src/cut/components/FlashPulseRows.tsx b/site/src/cut/components/FlashPulseRows.tsxindex 1db162df..fb7db95c 100644--- a/site/src/cut/components/FlashPulseRows.tsx+++ b/site/src/cut/components/FlashPulseRows.tsx@@ -1,6 +1,7 @@"use client";-import { FLASH_FADE_CHOICES, FLASH_FADE_NONE, FLASH_RHYTHMS, FLASH_RATE_MAX, FLASH_TONES, type FlashFadeChoice, type FlashRhythm, type FlashPulse, type FlashTone } from "@donkeycut/effects-kit";+import { EASE_IDS, EASE_LABELS, FLASH_FADE_CHOICES, FLASH_FADE_NONE, FLASH_RHYTHMS, FLASH_RATE_MAX, FLASH_TONES, type FlashFadeChoice, type FlashRhythm, type FlashPulse, type FlashTone } from "@donkeycut/effects-kit";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Row, useSliderCheckpoint } from "@/cut/components/panelBits";import { parseNumberInput } from "@/cut/components/ScrubValue";import { ValueSlider } from "@/cut/components/ValueSlider";@@ -88,17 +89,41 @@ export function FlashPulseRows({ pulse, write }: { pulse: FlashPulse; write: (pa);}-/** A flash element's fade: off (the pop), into the tone, or out of it,- * evenly across the element. Off writes as absence. */+const FADE_EASE_ITEMS: Record<string, string> = Object.fromEntries(EASE_IDS.map((id) => [id, EASE_LABELS[id]]));++/** A flash element's fade: off (the pop), into the tone, or out of it, and+ * the curve it runs along. Off and the even ramp write as absence. */export function FlashFadeRow({ pulse, write }: { pulse: FlashPulse; write: (patch: FlashPulse, how: PulseWrite) => void }) {return (- <Row label="Fade">- <Segmented- items={FLASH_FADE_CHOICES}- value={pulse.fade ?? FLASH_FADE_NONE}- labels={FLASH_FADE_LABELS}- onPick={(c) => write({ fade: c === FLASH_FADE_NONE ? undefined : c }, "commit")}- />- </Row>+ <>+ <Row label="Fade">+ <Segmented+ items={FLASH_FADE_CHOICES}+ value={pulse.fade ?? FLASH_FADE_NONE}+ labels={FLASH_FADE_LABELS}+ onPick={(c) => write({ fade: c === FLASH_FADE_NONE ? undefined : c }, "commit")}+ />+ </Row>+ {pulse.fade && (+ <Row label="Curve">+ <Select+ value={pulse.fadeEase ?? "linear"}+ items={FADE_EASE_ITEMS}+ onValueChange={(id) => write({ fadeEase: id === "linear" ? undefined : (id as FlashPulse["fadeEase"]) }, "commit")}+ >+ <SelectTrigger className="h-8 w-36 text-[12px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EASE_IDS.map((id) => (+ <SelectItem key={id} value={id} className="text-[12px]">+ {EASE_LABELS[id]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Row>+ )}+ </>);}diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.tsindex 1fed479e..bfa7f95c 100644--- a/site/src/cut/components/Inspector.tools.ts+++ b/site/src/cut/components/Inspector.tools.ts@@ -36,6 +36,7 @@ import {CLIP_EFFECT_IDS,FLASH_RHYTHMS,FLASH_FADES,+ EASE_IDS,FLASH_RATE_MAX,FLASH_RATE_MIN,FLASH_TONES,@@ -425,6 +426,7 @@ export const INSPECTOR_TOOLS = [tone: { type: "string", enum: [...FLASH_TONES], description: 'flash only: "white" (default) or "black"' },rate: num(`flash and negative: strobe pulses a second, ${FLASH_RATE_MIN}..${FLASH_RATE_MAX}, each held for its first half (${FLASH_RATE_MAX} at 30 fps flips every other frame); omit for one pop at the clip's start, or a negative flipped throughout`),rhythm: { type: "string", enum: [...FLASH_RHYTHMS], description: 'flash with a rate only: "strobe" (default) or "flicker", each pulse its own strength, some skipped' },+ fade_ease: { type: "string", enum: [...EASE_IDS], description: 'flash with a fade only: the curve it runs along, as add_effect takes it ("linear", the even ramp, by default)' },fade: { type: "string", enum: [...FLASH_FADES], description: 'flash only: ramp evenly across the clip — "from" starts as the tone alone and clears, "to" ends on it. At amount 1 a one-frame clip fading from white is a solid silhouette of what it shows' },}, ["effect"]),},diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex 97a9f25d..340c684c 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -961,7 +961,7 @@ function describeOverlay(o: Overlay) {...(o.effect === "flash" && o.tone ? { tone: o.tone } : {}),...(o.effect === "flash" && o.rate ? { rate: r(o.rate), rhythm: o.rhythm ?? "strobe" } : {}),...(o.effect === "negative" && o.rate ? { rate: r(o.rate) } : {}),- ...(o.effect === "flash" && o.fade ? { fade: o.fade } : {}),+ ...(o.effect === "flash" && o.fade ? { fade: o.fade, ...(o.fadeEase ? { fade_ease: o.fadeEase } : {}) } : {}),};}return {diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex c4980950..172e2b40 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -856,6 +856,12 @@ const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, vconst isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);const isTextWeight = (v: unknown): v is TextWeight => (TEXT_WEIGHTS as readonly unknown[]).includes(v);+/** A flash fade's ease from a tool call: linear, the even ramp, stores as absence. */+const fadeEaseOf = (v: unknown): EaseId | undefined => {+ if (!isEaseId(v)) throw new ToolError(`fade_ease is one of ${EASE_IDS.join(", ")}.`);+ return v === "linear" ? undefined : v;+};+/** A flash rhythm from a tool call: strobe, the default, stores as absence. */const flashRhythm = (v: unknown): FlashRhythm | undefined => {if (!(FLASH_RHYTHMS as readonly unknown[]).includes(v)) {@@ -1899,6 +1905,21 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {box: { x: roundT(c.box.x), y: roundT(c.box.y), w: roundT(c.box.w), h: roundT(c.box.h) },...(c.flicker ? { flicker: true as const } : {}),})),+ ...(scan.fades.length+ ? {+ fades: scan.fades.map((f) => ({+ t: roundT(f.t),+ frame: f.frame,+ seconds: roundT(f.seconds),+ fade: f.fade,+ tone: f.tone,+ amount: Math.round(f.amount * 100) / 100,+ ease: f.ease,+ })),+ fadesNote:+ "The whole picture fading into the tone (fade to) or out of it (fade from), each read off every frame: add_effect flash with fade, tone, amount and fade_ease as they are, start t and end t + seconds, on the front row. A fade whose end runs a frame or two past the source's end is one the source cuts off: end the effect with the cut.",+ }+ : {}),...pictureReport(area),...(keepsPicture ? { pictureKept: true as const } : {}),source: sourceRef(asset),@@ -4118,7 +4139,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {// a flash also takes its tone, strobe rate and rhythm, a negative its// strobe rate.const effects: ClipEffect[] = [];- for (const e of input.effects as { effect?: unknown; amount?: unknown; tone?: unknown; rate?: unknown; rhythm?: unknown; fade?: unknown }[]) {+ for (const e of input.effects as { effect?: unknown; amount?: unknown; tone?: unknown; rate?: unknown; rhythm?: unknown; fade?: unknown; fade_ease?: unknown }[]) {const effect = CLIP_EFFECT_IDS.find((id) => id === e?.effect);if (!effect) throw new ToolError(`effect must be one of ${CLIP_EFFECT_IDS.join(", ")}.`);if (effects.some((x) => x.effect === effect)) throw new ToolError(`${effect} is listed twice; a clip wears an effect once.`);@@ -4142,6 +4163,8 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {if (e.fade !== undefined && e.fade !== FLASH_FADE_NONE) {if (!(FLASH_FADES as readonly unknown[]).includes(e.fade)) throw new ToolError(`fade is one of ${FLASH_FADE_CHOICES.join(", ")}.`);entry.fade = e.fade as FlashFade;+ const ease = e.fade_ease === undefined ? undefined : fadeEaseOf(e.fade_ease);+ if (ease) entry.fadeEase = ease;}}effects.push(entry);@@ -8385,6 +8408,7 @@ function effectSettings(effect: EffectId, input: Record<string, unknown>): Parti}patch.fade = input.fade === FLASH_FADE_NONE ? undefined : (input.fade as FlashFade);}+ if (input.fade_ease !== undefined) patch.fadeEase = fadeEaseOf(input.fade_ease);return patch;}diff --git a/site/src/cut/lib/effectUpdateTool.test.ts b/site/src/cut/lib/effectUpdateTool.test.tsindex 3e4434b3..ee0e1729 100644--- a/site/src/cut/lib/effectUpdateTool.test.ts+++ b/site/src/cut/lib/effectUpdateTool.test.ts@@ -76,6 +76,21 @@ describe("update_overlay on an effect", () => {expect(props.fade.enum).toContain("none");});+ test("a flash's fade runs along the ease it is given, and linear is the even ramp again", async () => {+ const { id } = (await runAiTool("add_effect", { effect: "flash", tone: "black", start: 2, end: 2.5, fade: "to", fade_ease: "sine.out", amount: 0.94 })) as {+ id: string;+ };+ expect(overlay(id)).toMatchObject({ fade: "to", fadeEase: "sine.out", amount: 0.94 });+ await runAiTool("update_overlay", { id, fade_ease: "linear" });+ expect((overlay(id) as { fadeEase?: string }).fadeEase).toBeUndefined();+ expect(await errorOf(() => runAiTool("update_overlay", { id, fade_ease: "bounce" }))).toContain("fade_ease is one of");+ const props = INSPECTOR_TOOLS.find((t) => t.name === "update_overlay")!.inputSchema.properties as Record<string, { enum?: string[] }>;+ expect(props.fade_ease.enum).toContain("power2.out");+ useEditor.setState({ clips: [{ id: "c1", assetId: "a", start: 0, in: 0, out: 2, speed: 1 } as never] });+ await runAiTool("set_clip_effects", { clipId: "c1", effects: [{ effect: "flash", fade: "to", fade_ease: "power2.out" }] });+ expect(useEditor.getState().clips[0].effects).toEqual([{ effect: "flash", fade: "to", fadeEase: "power2.out" }]);+ });+test("a setting the effect doesn't take is skipped, like any field a kind lacks", async () => {const { id } = (await runAiTool("add_effect", { effect: "flash", start: 2, end: 3 })) as { id: string };await runAiTool("update_overlay", { id, leak: "burn" });diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 29ae1417..1030d7d6 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -31,7 +31,7 @@ import { drawBlock } from "./blockSource";import { createRasterCanvas, rasterCanvasToPng } from "./raster";import { clipLen, clipSpeed, getClipSpans, MICRO_GAP_S, openedTimeline, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";-import { drawStreak, elementLook, isMaskAnimated, isOverlayAnimated, matteLumaToAlpha, normalizeGrade, paintMaskLuma, paintStrokeInk, retimeOf, type FlashFade, type FlashRhythm, type FlashTone, type GlitchKind, type LeakCourse, type Mask, type SpeedNode } from "@donkeycut/effects-kit";+import { drawStreak, elementLook, isMaskAnimated, isOverlayAnimated, matteLumaToAlpha, normalizeGrade, paintMaskLuma, paintStrokeInk, retimeOf, type EaseId, type FlashFade, type FlashRhythm, type FlashTone, type GlitchKind, type LeakCourse, type Mask, type SpeedNode } from "@donkeycut/effects-kit";import { renderElementFrames, renderElementPng, renderStillPng, requireStickers } from "./textRender";import { holdOverlays } from "./frameGrid";import { CLIP_MIN_SECONDS, clipCovers, clipFrameAt, clipKeyed, clipPosed, clipPoseAt, clipZoom, contentRect, frameOf, isStickerOverlay, isTextOverlay, laneOf, overlayAnimStyle, projectBackground, rectOf, regionPx, removalActive, shadowInk, subjectMasked, parkedTimeline } from "./types";@@ -1399,6 +1399,7 @@ export async function buildExportPayload(rate: (o as { rate?: number }).rate,rhythm: (o as { rhythm?: FlashRhythm }).rhythm,fade: (o as { fade?: FlashFade }).fade,+ fadeEase: (o as { fadeEase?: EaseId }).fadeEase,lane: laneOf(o),start: o.start,end: Math.min(o.end, duration),diff --git a/site/src/cut/lib/measure/cuts.test.ts b/site/src/cut/lib/measure/cuts.test.tsindex df5b85e2..26db27a3 100644--- a/site/src/cut/lib/measure/cuts.test.ts+++ b/site/src/cut/lib/measure/cuts.test.ts@@ -1,4 +1,5 @@import { expect, test } from "bun:test";+import { easeAt, type EaseId } from "@donkeycut/effects-kit";import { changePct, gridMeans, pickCuts, scoreFrames } from "./cuts";/** A w×h RGBA frame of one colour. */@@ -175,3 +176,74 @@ test("a shape that pops in and out every few frames is no flicker", () => {const frames = Array.from({ length: 30 }, (_, i) => (Math.floor(i / 3) % 2 ? on : off));expect(scoreFrames(frames).changes.some((c) => c.flicker)).toBe(false);});++type Rgb3 = [number, number, number];++/** A card with a word on it, pulled toward `tone` by `f` (0 clear, 1 the+ * tone alone), as the flash effect fades a picture. */+const toned = (f: number, tone: number, bg: Rgb3 = [167, 15, 3], ink: Rgb3 = [240, 220, 200]) => {+ const px = card(96, 54, bg, ink, [30, 66, 20, 34]);+ for (let i = 0; i < px.data.length; i += 4)+ for (let c = 0; c < 3; c++) px.data[i + c] = Math.round(px.data[i + c] + (tone - px.data[i + c]) * f);+ return px;+};++/** Still frames, then a fade along `ease` from frame `start` over `frames`+ * frames to `amount`, then held: into the tone ("to") or out of it ("from"). */+const fadeRun = (o: { ease: EaseId; start: number; frames: number; amount: number; tone: number; way: "to" | "from"; total: number }) =>+ Array.from({ length: o.total }, (_, i) => {+ const e = easeAt(o.ease, (i - o.start) / o.frames);+ return toned(o.amount * (o.way === "to" ? e : 1 - e), o.tone);+ });++test("a picture fading to black is a fade with its curve, not a cut", () => {+ const frames = fadeRun({ ease: "power2.out", start: 10, frames: 14, amount: 1, tone: 0, way: "to", total: 28 });+ const { cuts, changes, fades } = scoreFrames(frames);+ expect(cuts).toEqual([]);+ expect(changes).toEqual([]);+ expect(fades).toHaveLength(1);+ const f = fades[0];+ expect(f.fade).toBe("to");+ expect(f.tone).toBe("black");+ expect(f.ease).toBe("power2.out");+ expect(f.frame).toBeCloseTo(10, 0);+ expect(f.frames).toBeCloseTo(14, 0);+ expect(f.amount).toBeGreaterThan(0.95);+});++test("a fade that stops short of the tone says how far it goes", () => {+ const frames = fadeRun({ ease: "linear", start: 6, frames: 12, amount: 0.6, tone: 0, way: "to", total: 24 });+ const [f] = scoreFrames(frames).fades;+ expect(f.ease).toBe("linear");+ expect(f.amount).toBeCloseTo(0.6, 1);+ expect(f.frames).toBeCloseTo(12, 0);+});++test("a picture clearing out of white is a fade from white", () => {+ const frames = fadeRun({ ease: "sine.in", start: 4, frames: 15, amount: 1, tone: 255, way: "from", total: 26 });+ const { cuts, fades } = scoreFrames(frames);+ expect(cuts).toEqual([]);+ expect(fades).toHaveLength(1);+ expect(fades[0].fade).toBe("from");+ expect(fades[0].tone).toBe("white");+ expect(fades[0].ease).toBe("sine.in");+ expect(fades[0].frame).toBeCloseTo(4, 0);+});++test("a fade cut short by the end of the source is still read whole", () => {+ // The source ends two frames before the fade lands.+ const frames = fadeRun({ ease: "power3.in", start: 8, frames: 16, amount: 1, tone: 0, way: "to", total: 22 });+ const [f] = scoreFrames(frames).fades;+ expect(f.ease).toBe("power3.in");+ expect(f.frames).toBeCloseTo(16, 0);+});++test("a crossfade between two colours and a hard cut are no fades", () => {+ const cross = Array.from({ length: 10 }, (_, i) => solid(64, 64, [239 - i * 10, 170 + i * 8, 127 + i * 9]));+ expect(scoreFrames(cross).fades).toEqual([]);+ const red = solid(128, 128, [158, 3, 2]);+ const black = solid(128, 128, [0, 0, 0]);+ const hard = scoreFrames([red, red, red, red, black, black, black, black]);+ expect(hard.cuts).toEqual([4]);+ expect(hard.fades).toEqual([]);+});diff --git a/site/src/cut/lib/measure/cuts.ts b/site/src/cut/lib/measure/cuts.tsindex 0bb9e9a1..51ba08f9 100644--- a/site/src/cut/lib/measure/cuts.ts+++ b/site/src/cut/lib/measure/cuts.ts@@ -3,6 +3,7 @@* before, and a cut is a score that stands out against the frames around it.* Pure data in, pure data out; sourceMeasure.ts feeds it decoded frames. */+import { easeAt, EASE_IDS, type EaseId } from "@donkeycut/effects-kit";import { diffCellPct } from "../watch/signatures";import type { Pixels } from "./color";@@ -45,6 +46,15 @@ export const CUT_TUNING = {FLICKER_ECHO: 0.6,/** Flicker frames a run holds at least; one held frame may part two. */FLICKER_RUN: 3,+ /** Mean-luma step (0..255) a frame of a whole-picture fade takes at least. */+ FADE_STEP: 0.5,+ /** Frames a fade's run of steps holds at least. */+ FADE_RUN: 4,+ /** Mean-luma move (0..255) a fade makes in all. */+ FADE_LUMA: 20,+ /** Per-channel RMS (0..255) a frame strays at most from the clear picture+ * pulled toward the tone. */+ FADE_FIT: 6,};/** Per-cell channel means of an RGBA frame on a GRID×GRID grid. */@@ -131,6 +141,18 @@ export interface ShotChange {flicker?: true;}+/** The whole picture fading into a tone or out of it, as the flash effect's+ * fade plays it: from fractional frame `frame` for `frames` frames along+ * `ease`, to `amount` of the tone (1 = the tone alone). */+export interface PictureFade {+ frame: number;+ frames: number;+ fade: "to" | "from";+ tone: "black" | "white";+ amount: number;+ ease: EaseId;+}+export const gridsOf = (px: Pixels): FrameGrids => ({coarse: gridMeans(px),fine: gridMeans(px, CUT_TUNING.FINE_GRID),@@ -207,7 +229,10 @@ function neighbourMedian(scores: number[], i: number, skip?: Set<number>): numbe* appearing, a word swapping fill for outline, a small shape popping in.* Changes on consecutive frames are one change that runs those frames: a* fade-in over three frames reads as one change of three. */-export function pickShotEdges(steps: FrameStep[], fines?: ArrayLike<number>[]): { cuts: number[]; changes: ShotChange[] } {+export function pickShotEdges(+ steps: FrameStep[],+ fines?: ArrayLike<number>[]+): { cuts: number[]; changes: ShotChange[]; fades: PictureFade[] } {const { FAINT_ALL, SPIKE, CHANGE_MIN, MIN_CHANGE, FLASH_LUMA } = CUT_TUNING;const hard = pickCuts(steps.map((s) => s.pct));const faintScores = steps.map((s) => s.faint);@@ -248,13 +273,158 @@ export function pickShotEdges(steps: FrameStep[], fines?: ArrayLike<number>[]):changes.push({ frame: i, frames: 1, change: s.fine, box: s.box });}if (!fines) {- return { cuts, changes };+ return { cuts, changes, fades: [] };}+ // A whole-picture fade moves every cell every frame: its frames are no+ // cuts and no changes, whatever their steps.+ const fades = pictureFades(fines);+ const fading = (i: number) => fades.some((f) => i > Math.floor(f.frame) && i <= Math.ceil(f.frame + f.frames));+ const kept = cuts.filter((i) => !fading(i));const overlaps = (a: ShotChange, b: ShotChange) => a.frame < b.frame + b.frames && b.frame < a.frame + a.frames;const flicks = flickers(fines);- const slow = gradualChanges(fines, cuts).filter((g) => !changes.some((c) => overlaps(g, c)));+ const slow = gradualChanges(fines, kept).filter((g) => !changes.some((c) => overlaps(g, c)));const rest = [...changes, ...slow].filter((c) => !flicks.some((f) => overlaps(c, f)));- return { cuts, changes: [...rest, ...flicks].sort((a, b) => a.frame - b.frame) };+ const inside = (c: ShotChange) => Array.from({ length: c.frames }, (_, k) => c.frame + k).some(fading);+ return {+ cuts: kept,+ changes: [...rest, ...flicks].filter((c) => !inside(c)).sort((a, b) => a.frame - b.frame),+ fades,+ };+}++/** How far frame `x` is pulled from the clear picture `c` toward `tone`+ * (0..255 on every channel), by least squares, and how far it strays from+ * that pull (per-channel RMS). */+function pullOf(c: ArrayLike<number>, x: ArrayLike<number>, tone: number): { f: number; miss: number } {+ let dot = 0;+ let norm = 0;+ for (let i = 0; i < c.length; i++) {+ dot += (x[i] - c[i]) * (tone - c[i]);+ norm += (tone - c[i]) ** 2;+ }+ const f = norm > 0 ? dot / norm : 0;+ let err = 0;+ for (let i = 0; i < c.length; i++) err += (x[i] - c[i] - f * (tone - c[i])) ** 2;+ return { f, miss: Math.sqrt(err / Math.max(1, c.length)) };+}++/** Whole-picture fades into black or white or out of them: runs of frames+ * whose mean luma steps the same way every frame, each frame the clear+ * picture pulled toward the tone. A fade into the tone is held against the+ * frame before the run, a fade out of it against the frame the run lands+ * on; the one that fits is the fade. Its start, length, ease and amount are+ * fitted to every frame's pull. */+export function pictureFades(fines: ArrayLike<number>[]): PictureFade[] {+ const { FADE_STEP, FADE_RUN, FADE_LUMA, FADE_FIT } = CUT_TUNING;+ const luma = fines.map((g) => meanLuma(g as Float32Array));+ const out: PictureFade[] = [];+ for (let a = 1; a < fines.length; a++) {+ const sign = Math.sign(luma[a] - luma[a - 1]);+ if (!(Math.abs(luma[a] - luma[a - 1]) >= FADE_STEP)) continue;+ let b = a;+ while (b + 1 < fines.length && Math.sign(luma[b + 1] - luma[b]) === sign && Math.abs(luma[b + 1] - luma[b]) >= FADE_STEP) b++;+ const run = b - a + 1;+ const moved = Math.abs(luma[b] - luma[a - 1]);+ const next = b;+ if (run < FADE_RUN || moved < FADE_LUMA) {+ a = next;+ continue;+ }+ // Darkening is into black or out of white, brightening into white or+ // out of black: each held against its clear frame.+ const ways: { fade: "to" | "from"; tone: number; clear: number }[] =+ sign < 0+ ? [+ { fade: "to", tone: 0, clear: a - 1 },+ { fade: "from", tone: 255, clear: b },+ ]+ : [+ { fade: "to", tone: 255, clear: a - 1 },+ { fade: "from", tone: 0, clear: b },+ ];+ const read = ways.map((w) => {+ const pulls = new Map<number, number>();+ let worst = 0;+ for (let i = a - 1; i <= b; i++) {+ const p = pullOf(fines[w.clear], fines[i], w.tone);+ pulls.set(i, p.f);+ worst = Math.max(worst, p.miss);+ }+ // The still frames either side that hold the same picture join the+ // fit, so a curve that settles slowly is timed whole.+ for (const [from, step] of [+ [a - 2, -1],+ [b + 1, 1],+ ] as const) {+ for (let i = from, n = 0; i >= 0 && i < fines.length && n < FADE_RUN; i += step, n++) {+ const p = pullOf(fines[w.clear], fines[i], w.tone);+ if (p.miss > FADE_FIT) break;+ pulls.set(i, p.f);+ }+ }+ return { ...w, pulls, worst };+ });+ const best = read.filter((r) => r.worst <= FADE_FIT).sort((x, y) => x.worst - y.worst)[0];+ if (best) {+ const fit = fitFade(best.pulls, best.fade, a - 1, b);+ if (fit) out.push({ ...fit, fade: best.fade, tone: best.tone === 0 ? "black" : "white" });+ }+ a = next;+ }+ return out;+}++/** What a fade pays for stopping short of the tone, against the squared+ * misses of its frames' pulls: enough to settle a tie, never a frame held+ * short of it. */+const FADE_FULL = 0.01;++/** The start, length, ease and amount whose curve best runs through each+ * frame's pull: rising into the tone, falling out of it. */+function fitFade(+ pulls: Map<number, number>,+ fade: "to" | "from",+ first: number,+ last: number+): Omit<PictureFade, "fade" | "tone"> | null {+ // An ease that sets off slowly steps under FADE_STEP at first, so the+ // fade may start on any of the still frames joined in front of the run.+ const frames = [...pulls.keys()];+ const end = Math.max(...frames);+ const lead = Math.min(...frames);+ let best: Omit<PictureFade, "fade" | "tone"> | null = null;+ let bestErr = Infinity;+ for (const ease of EASE_IDS) {+ for (let s = lead - 0.5; s <= first + 1.0001; s += 0.1) {+ for (let n = Math.max(1, last - s - 4); n <= end - s + 4; n += 0.1) {+ // The amount that fits this curve best, by least squares.+ let fg = 0;+ let gg = 0;+ const shape = (i: number) => {+ const e = easeAt(ease, (i - s) / n);+ return fade === "to" ? e : 1 - e;+ };+ for (const [i, f] of pulls) {+ const g = shape(i);+ fg += f * g;+ gg += g * g;+ }+ if (gg <= 0) continue;+ const amount = Math.min(1, Math.max(0, fg / gg));+ let err = 0;+ for (const [i, f] of pulls) err += (f - amount * shape(i)) ** 2;+ // Frames that never show the fade land can't tell how far it goes —+ // a power curve stopped short reads the same as a shorter one gone+ // all the way — so it goes all the way unless the frames say otherwise.+ err += FADE_FULL * (1 - amount) ** 2;+ if (err < bestErr - 1e-9) {+ bestErr = err;+ best = { frame: s, frames: n, amount, ease };+ }+ }+ }+ }+ return best;}/** Runs of frames that flip back and forth — a strobe, a cutout flashing to@@ -399,8 +569,8 @@ function unionBox(a: ChangeBox, b: ChangeBox): ChangeBox {return { x: (l + r) / 2, y: (t + btm) / 2, w: r - l, h: btm - t };}-/** Cuts and changes over a run of frames held in memory. */-export function scoreFrames(frames: Pixels[]): { cuts: number[]; changes: ShotChange[] } {+/** Cuts, changes and fades over a run of frames held in memory. */+export function scoreFrames(frames: Pixels[]): { cuts: number[]; changes: ShotChange[]; fades: PictureFade[] } {const grids = frames.map(gridsOf);const none: FrameStep = { pct: NaN, faint: NaN, fine: NaN, box: null };return pickShotEdges(diff --git a/site/src/cut/lib/measure/sourceMeasure.ts b/site/src/cut/lib/measure/sourceMeasure.tsindex c6f31138..68860545 100644--- a/site/src/cut/lib/measure/sourceMeasure.ts+++ b/site/src/cut/lib/measure/sourceMeasure.ts@@ -10,7 +10,7 @@ import { createRasterCanvas, decodeRasterImageUrl } from "../raster";import type { WrappedCanvas } from "mediabunny";import { CAMERA_LONG_SIDE, cameraPath, grayOf, holdsStill, type CameraPose, type Gray } from "./camera";import { hexOf, regionColor, parseHex, type PixelRect, type Pixels, type Rgb } from "./color";-import { frameStep, gridsOf, pickShotEdges, type FrameGrids, type FrameStep, type ShotChange } from "./cuts";+import { frameStep, gridsOf, pickShotEdges, type FrameGrids, type FrameStep, type PictureFade, type ShotChange } from "./cuts";import { fitMoves, type Move } from "./easeFit";import { FULL_FRAME, areaOf, findPictureBox, intoArea, type PictureFind } from "./picture";import { inkBox, shapeBox } from "./track";@@ -160,6 +160,9 @@ export interface CutScan {/** Changes inside the shots: a word or a shape coming, going or swapping* style over a picture that stays. */changes: (Omit<ShotChange, "frame"> & { t: number; frame: number })[];+ /** The whole picture fading into black or white or out of it: from `t`+ * for `seconds` along `ease`. */+ fades: (Omit<PictureFade, "frame" | "frames"> & { t: number; frame: number; seconds: number })[];coveredTo: number;truncated: boolean;}@@ -204,7 +207,7 @@ export async function scanCuts(if (times.length === 0) throw new Error("Could not read any frames in that span.");const fps = rateOf(times, durations);- const { cuts: picked, changes: found } = pickShotEdges(steps, fines);+ const { cuts: picked, changes: found, fades } = pickShotEdges(steps, fines);// A capped pass ends on the frame before the first cut or change it// leaves out, so the next pass scores that one against it.@@ -228,6 +231,14 @@ export async function scanCuts(changes: found.filter((c) => c.frame < firstLeftOut).map((c) => ({ ...c, t: times[c.frame], frame: frameOf(c.frame), change: Math.round(c.change * 10) / 10 })),+ // A fade starts between frames: its time runs on from the frame before.+ fades: fades+ .filter((f) => f.frame < firstLeftOut)+ .map(({ frame, frames, ...f }) => {+ const i = Math.max(0, Math.min(times.length - 1, Math.floor(frame)));+ const step = fps > 0 ? 1 / fps : 0;+ return { ...f, t: times[i] + (frame - i) * step, frame: frameOf(i), seconds: frames * step };+ }),coveredTo,truncated: capped || outOfTime,};diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex d54b8e39..fb680094 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -354,7 +354,7 @@ Someone points at a video — a file they imported, a link you brought in, a cli**Clipping a long source.** A talk, an interview or a stream is mostly material that only makes sense in place. find_highlights ranks its stretches from the transcript, so an hour is read for its handful of moments without watching all of it; watch_video the spans it returns before committing, since the ranking never saw the picture. add_clip \`spans\` lays a pick down — several stretches of one source as one run of clips, the material between them left out — and a two-span result is one clip whose halves were never next to each other.**Watch the whole thing first.** Every decision below comes off the record, so the record has to be complete: watch from 0 and keep going until \`unwatchedSeconds\` is 0, writing each pass into note_source before the next one. Anything over a couple of minutes gets a coarse pass end to end first (\`interval_seconds\` 15-30) to learn its shape, then a dense pass (0.5) over the stretches that carry text or cut fast. Read every card word for word — its text, its face, where it sits in the frame, when it comes and goes — because a turn later the sheets are gone and the notes are all you have. Reading type is what \`detail\` is for: the dense pass over a stretch carrying words runs at \`detail\` read, and a face or treatment you are about to name runs at original, where the frame arrives at the source's own resolution. When the cards ARE the narration — a caption track of what the speaker is saying — the transcript already holds every word, and the close passes are for how they are set: face, weight, size, colour, placement, how many words ride a card, how it enters and leaves. Read a few of those at original and take the rest from the transcript.-**Measure it.** A contact sheet tells you what happens; the numbers come from the source's pixels. A reference recorded off a screen — a phone filming an editing app, a letterboxed film — has its picture inside a bigger frame: find_picture finds that box and keeps it on the source (detect_cuts does on its first read), every measuring tool and compare_to_source then reads inside it, and their x, y, w, h are fractions of it, so they land on the cut's frame as they are; set_aspect to its \`aspect\`. detect_cuts reads every frame: each cut on its frame, the \`shots\` between them, and the \`changes\` inside a shot — a word landing, a word swapping fill for outline, a shape popping in. Run it over the whole source before the read passes, which then land a frame in every shot and change, and time each title from them. Its times are to the millisecond, and every tool lands such a time on the frame it names: write them back as read. sample_color reads the hex of any region at any second. track_element gives an element's box frame by frame and the ease of each move; with match ink it gives a title's ink box. track_camera gives a shot's camera move frame by frame — zoom, shift, turn — and says when the picture under it is one frozen frame. Run it over every shot before you describe how it moves: a beat zoom on a frozen frame, a shake or a slow push reads on a contact sheet as a held shot with exposure flicker, and detect_cuts lists its pulses as whole-frame \`changes\` — a run of those inside one shot is a camera move until track_camera says otherwise. A cut whose \`change\` sits far below a new shot's, or a few frames that open just before a real cut, is rarely a shot of its own: it is usually the next shot's subject laid over this one, a cutout flashed in. Look at those frames one at a time, and build every one you find; it is part of the edit's look, not a glitch to skip.+**Measure it.** A contact sheet tells you what happens; the numbers come from the source's pixels. A reference recorded off a screen — a phone filming an editing app, a letterboxed film — has its picture inside a bigger frame: find_picture finds that box and keeps it on the source (detect_cuts does on its first read), every measuring tool and compare_to_source then reads inside it, and their x, y, w, h are fractions of it, so they land on the cut's frame as they are; set_aspect to its \`aspect\`. detect_cuts reads every frame: each cut on its frame, the \`shots\` between them, and the \`changes\` inside a shot — a word landing, a word swapping fill for outline, a shape popping in. Run it over the whole source before the read passes, which then land a frame in every shot and change, and time each title from them. Its times are to the millisecond, and every tool lands such a time on the frame it names: write them back as read. sample_color reads the hex of any region at any second. track_element gives an element's box frame by frame and the ease of each move; with match ink it gives a title's ink box. track_camera gives a shot's camera move frame by frame — zoom, shift, turn — and says when the picture under it is one frozen frame. Run it over every shot before you describe how it moves: a beat zoom on a frozen frame, a shake or a slow push reads on a contact sheet as a held shot with exposure flicker, and detect_cuts lists its pulses as whole-frame \`changes\` — a run of those inside one shot is a camera move until track_camera says otherwise. A cut whose \`change\` sits far below a new shot's, or a few frames that open just before a real cut, is rarely a shot of its own: it is usually the next shot's subject laid over this one, a cutout flashed in. Look at those frames one at a time, and build every one you find; it is part of the edit's look, not a glitch to skip. A fade of the whole picture to black or white, or up out of it, is no cut: detect_cuts lists it in \`fades\` with its start, length, amount and ease read off every frame, and add_effect flash takes them as they come (fade, tone, amount, fade_ease) — never time or shape a fade from a few sampled colours.**Lay down the sound, then block out the cuts.** Cuts timed to a reference are timed to its sound, and its music is the cut's soundtrack: bring that track in as an audio file of its own — import_url with \`audio_only\` on the link the reference came from — and add_clip it at 0, where it lines up with the picture. The reference itself stays off every timeline, its sound included, so it can be cleared out once the build is done while the music plays on. A reference with no link (a file the person imported) is the one case for detach_audio with its \`assetId\`, which plays the track straight off the reference. add_clip with \`blocks\` lays the skeleton from \`shots\` in one call — one block per shot on track 0, each its shot's \`from\` and \`to\` as read so every cut lands on its frame, flash cuts included, \`color\` what sample_color reads behind it and \`label\` naming what the person drops there. The label rides the timeline chip; the frame shows the colour alone. Footage dropped on a block, or replace_item, takes its place and its length, so everything built on top keeps its timing. When the ask is the reference's own picture playing, add_clip \`spans\` lays its shots down instead, one span per shot at those same times.diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex 77338022..4e588b45 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -19,7 +19,7 @@ import { masterRawMix, packStems } from "./exportAudio";import { STEM_CHANNELS, STEM_RATE, type StemDef } from "../lib/stems";import { CLIP_MAX_ZOOM, CLIP_MIN_SECONDS, clipFrameAt, regionPx, TRANSITION_ZOOM, type ColorGrade } from "../lib/types";import { gridFrame, heldFrames, type HeldFrames } from "../lib/frameGrid";-import { audioFxFilters, buildClipLut, elementLook, buildTransferLut, CLARITY_EPS, compositeSpaceFor, detailActive, detailGain, detailRadius, effectFilterLines, effectRecipe, type FlashFade, type FlashRhythm, type FlashTone, type GlitchKind, type LeakCourse, graphicsToHlg, hexToHlgHex, hlgToPq, isAudioEffect, lookFilterLines, lutToCube, mirrorRetimable, parseLutFile, recipeKey, retimeOf, shortestTurn, slowRuns, srcSpan, sortedKeys, soundFilters, type ChainChroma, type ClipColorRecipe, type ClipEffect, type ClipSound, type CodeFormat, type EaseId, type OutputSpace, type OverlayKey, type ParsedLut, type Retime, type SpeedNode } from "@donkeycut/effects-kit";+import { audioFxFilters, buildClipLut, elementLook, buildTransferLut, CLARITY_EPS, compositeSpaceFor, detailActive, detailGain, detailRadius, effectFilterLines, easeExpr, effectRecipe, type FlashFade, type FlashRhythm, type FlashTone, type GlitchKind, type LeakCourse, graphicsToHlg, hexToHlgHex, hlgToPq, isAudioEffect, lookFilterLines, lutToCube, mirrorRetimable, parseLutFile, recipeKey, retimeOf, shortestTurn, slowRuns, srcSpan, sortedKeys, soundFilters, type ChainChroma, type ClipColorRecipe, type ClipEffect, type ClipSound, type CodeFormat, type EaseId, type OutputSpace, type OverlayKey, type ParsedLut, type Retime, type SpeedNode } from "@donkeycut/effects-kit";// The render pipeline itself: spec in, finished mp4 out. Shared by the local// engine's job registry (jobs.ts) and the cloud render worker, which stage@@ -410,6 +410,7 @@ export interface ExportSpec {rate?: number;rhythm?: FlashRhythm;fade?: FlashFade;+ fadeEase?: EaseId;/** Its row in the element stack; lane 0 is the top. */lane?: number;start: number;@@ -2084,31 +2085,6 @@ async function renderPass(// The pose track runs key to key along each key's ease with the ends held// flat, exactly the kit evaluator: v0 + Σ Δi·ease(clip((V−ti)/(ti+1−ti),0,1))// builds that shape as one expression, safe inside overlay/scale/rotate.- /** easeAt from the kit as an ffmpeg expression over progress `u`. */- const easeExpr = (ease: EaseId | undefined, u: string): string => {- switch (ease) {- case "sine.in":- return `(1-cos(${u}*PI/2))`;- case "sine.out":- return `sin(${u}*PI/2)`;- case "sine.inOut":- return `((1-cos(PI*${u}))/2)`;- case "power2.in":- return `pow(${u},2)`;- case "power2.out":- return `(1-pow(1-${u},2))`;- case "power2.inOut":- return `if(lt(${u},0.5),2*pow(${u},2),1-pow(2-2*${u},2)/2)`;- case "power3.in":- return `pow(${u},3)`;- case "power3.out":- return `(1-pow(1-${u},3))`;- case "power3.inOut":- return `if(lt(${u},0.5),4*pow(${u},3),1-pow(2-2*${u},3)/2)`;- default:- return u;- }- };const piecewiseExpr = (keys: { t: number; v: number; ease?: EaseId }[], varExpr: string): string => {const ks = [...keys].sort((a, b) => a.t - b.t);let e = `${num(ks[0].v)}`;