Open source CapCut alternative.
TypeScript
feat(site): time faint fades in detect_cuts [rebuild]
David Le319ab90c84a2
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex 0c207d94..79ffa82d 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -240,7 +240,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\`. Time titles, 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 changes a little each frame and reads as none. 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 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.`,inputSchema: obj({asset_id: str("Project asset id of the video"),diff --git a/site/src/cut/lib/measure/cuts.test.ts b/site/src/cut/lib/measure/cuts.test.tsindex 34ce3641..aeb93a0a 100644--- a/site/src/cut/lib/measure/cuts.test.ts+++ b/site/src/cut/lib/measure/cuts.test.ts@@ -94,3 +94,45 @@ test("a hard cut is not also reported as a change", () => {expect(cuts).toEqual([3]);expect(changes).toEqual([]);});++test("a faint word fading in over many frames is one change that runs its fade", () => {+ // White on maroon over 12 frames: no single frame moves a cell past the+ // hard tolerance, the fade as a whole does.+ const bg: [number, number, number] = [113, 8, 41];+ const at = (a: number) => card(128, 128, bg, [Math.round(113 + a * 142), Math.round(8 + a * 247), Math.round(41 + a * 214)], [40, 88, 60, 68]);+ const frames = [0, 0, 0, ...Array.from({ length: 12 }, (_, i) => (i + 1) / 12), ...Array(20).fill(1)].map(at);+ const { cuts, changes } = scoreFrames(frames);+ expect(cuts).toEqual([]);+ expect(changes).toHaveLength(1);+ expect(changes[0].frame).toBe(3);+ expect(changes[0].frames).toBe(12);+ expect(changes[0].box.x).toBeCloseTo(64 / 128, 1);+ expect(changes[0].box.y).toBeCloseTo(64 / 128, 1);+});++test("a faint word fading out before a cut is timed inside its shot", () => {+ const bg: [number, number, number] = [113, 8, 41];+ const at = (a: number) => card(128, 128, bg, [Math.round(113 + a * 142), Math.round(8 + a * 247), Math.round(41 + a * 214)], [40, 88, 60, 68]);+ const fadeOut = [...Array(20).fill(1), ...Array.from({ length: 10 }, (_, i) => 1 - (i + 1) / 10), 0, 0, 0].map(at);+ const next = Array.from({ length: 10 }, () => solid(128, 128, [6, 196, 85]));+ const { cuts, changes } = scoreFrames([...fadeOut, ...next]);+ expect(cuts).toEqual([33]);+ expect(changes).toHaveLength(1);+ expect(changes[0].frame).toBe(20);+ expect(changes[0].frames).toBe(10);+});++test("a slow pan over a gradient reports no changes", () => {+ const pan = (shift: number) => {+ const px = solid(128, 128, [0, 0, 0]);+ for (let y = 0; y < 128; y++)+ for (let x = 0; x < 128; x++) {+ const v = Math.round(127 + 120 * Math.sin((x + shift) / 9));+ px.data.set([v, v, 255 - v, 255], (y * 128 + x) * 4);+ }+ return px;+ };+ const { cuts, changes } = scoreFrames(Array.from({ length: 40 }, (_, i) => pan(i * 0.6)));+ expect(cuts).toEqual([]);+ expect(changes).toEqual([]);+});diff --git a/site/src/cut/lib/measure/cuts.ts b/site/src/cut/lib/measure/cuts.tsindex 36c8921b..efafc9a7 100644--- a/site/src/cut/lib/measure/cuts.ts+++ b/site/src/cut/lib/measure/cuts.ts@@ -27,6 +27,13 @@ export const CUT_TUNING = {FINE_GRID: 32,/** % of the fine grid a change inside a shot covers at least. */CHANGE_MIN: 0.3,+ /** Frames back a frame is held against to find a change too gradual for+ * any one frame to show: a fade of faint type over half a second. */+ SLOW_SPAN: 15,+ /** The share of a gradual change's total move that marks its first frame,+ * and the share that marks its last. */+ SLOW_START: 0.05,+ SLOW_END: 0.95,};/** Per-cell channel means of an RGBA frame on a GRID×GRID grid. */@@ -168,7 +175,8 @@ function neighbourMedian(scores: number[], i: number, skip?: Set<number>): numbe}/** The frames that open a shot and the changes inside shots, from each- * frame's step (index 0 has none: NaN fields).+ * frame's step (index 0 has none: NaN fields), and each frame's fine grid+ * when the gradual changes are wanted too (gradualChanges).* A cut is a hard spike (pickCuts) or a faint step taken by the whole* picture at once over still frames — a flat card cut to a near colour. A* crossfade takes that step every frame, so its neighbours rule it out.@@ -176,7 +184,7 @@ 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[]): { cuts: number[]; changes: ShotChange[] } {+export function pickShotEdges(steps: FrameStep[], fines?: ArrayLike<number>[]): { cuts: number[]; changes: ShotChange[] } {const { FAINT_ALL, SPIKE, CHANGE_MIN } = CUT_TUNING;const hard = pickCuts(steps.map((s) => s.pct));const faintScores = steps.map((s) => s.faint);@@ -213,7 +221,104 @@ export function pickShotEdges(steps: FrameStep[]): { cuts: number[]; changes: Sh}changes.push({ frame: i, frames: 1, change: s.fine, box: s.box });}- return { cuts, changes };+ if (!fines) {+ return { cuts, changes };+ }+ const slow = gradualChanges(fines, cuts).filter(+ (g) => !changes.some((c) => g.frame < c.frame + c.frames && c.frame < g.frame + g.frames)+ );+ return { cuts, changes: [...changes, ...slow].sort((a, b) => a.frame - b.frame) };+}++/** The fine cells that differ between two grids past the hard tolerance. */+function cellsApart(a: ArrayLike<number>, b: ArrayLike<number>): number[] {+ const out: number[] = [];+ for (let c = 0; c < a.length / 3; c++) {+ const i = c * 3;+ if (Math.max(Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2])) > CUT_TUNING.CELL_TOL) {+ out.push(c);+ }+ }+ return out;+}++/** The box around a set of fine cells. */+function boxOfCells(cells: number[]): ChangeBox {+ const grid = CUT_TUNING.FINE_GRID;+ const xs = cells.map((c) => c % grid);+ const ys = cells.map((c) => Math.floor(c / grid));+ const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];+ return { x: (x0 + x1 + 1) / 2 / grid, y: (y0 + y1 + 1) / 2 / grid, w: (x1 - x0 + 1) / grid, h: (y1 - y0 + 1) / grid };+}++/** Changes too gradual for any one frame to show — faint type fading in or+ * out over many frames, each step under the hard tolerance. Each frame is+ * held against the one SLOW_SPAN back inside its shot; frames that differ+ * from it on a few cells, where the shot's typical frame differs on far+ * fewer (footage that moves throughout differs everywhere), are a change.+ * Its first and last frames are where the cells it moved are SLOW_START and+ * SLOW_END of the way from where they were to where they settle. */+export function gradualChanges(fines: ArrayLike<number>[], cuts: number[]): ShotChange[] {+ const { SLOW_SPAN, CHANGE_MIN, SPIKE, SLOW_START, SLOW_END } = CUT_TUNING;+ const cells = fines.length > 0 ? fines[0].length / 3 : 0;+ const bounds = [0, ...cuts, fines.length];+ const out: ShotChange[] = [];+ for (let k = 0; k + 1 < bounds.length; k++) {+ const [s, e] = [bounds[k], bounds[k + 1]];+ if (e - s < 3) {+ continue;+ }+ const back = (i: number) => Math.max(s, i - SLOW_SPAN);+ const pct = new Map<number, number>();+ for (let i = s + 1; i < e; i++) {+ pct.set(i, (100 * cellsApart(fines[i], fines[back(i)]).length) / cells);+ }+ const sorted = [...pct.values()].sort((a, b) => a - b);+ const floor = sorted[Math.floor((sorted.length - 1) / 4)];+ const hit = (i: number) => (pct.get(i) ?? 0) >= Math.max(CHANGE_MIN, SPIKE * floor);+ for (let i = s + 1; i < e; i++) {+ if (!hit(i)) {+ continue;+ }+ let r1 = i;+ while (r1 + 1 < e && hit(r1 + 1)) {+ r1++;+ }+ const pre = back(i);+ const moved = cellsApart(fines[pre], fines[r1]);+ i = r1;+ if (moved.length === 0) {+ continue;+ }+ // How far along the moved cells are, 0 at `pre` and 1 at `r1`.+ const a = fines[pre];+ const z = fines[r1];+ let norm = 0;+ for (const c of moved) for (let ch = 0; ch < 3; ch++) norm += (z[c * 3 + ch] - a[c * 3 + ch]) ** 2;+ const along = (f: ArrayLike<number>) => {+ let dot = 0;+ for (const c of moved) for (let ch = 0; ch < 3; ch++) dot += (f[c * 3 + ch] - a[c * 3 + ch]) * (z[c * 3 + ch] - a[c * 3 + ch]);+ return dot / norm;+ };+ let first = -1;+ let last = r1;+ for (let j = pre + 1; j <= r1; j++) {+ const p = along(fines[j]);+ if (first < 0 && p > SLOW_START) {+ first = j;+ }+ if (first >= 0 && p >= SLOW_END) {+ last = j;+ break;+ }+ }+ if (first < 0) {+ continue;+ }+ out.push({ frame: first, frames: last - first + 1, change: (100 * moved.length) / cells, box: boxOfCells(moved) });+ }+ }+ return out;}/** The box around two boxes. */@@ -229,5 +334,8 @@ function unionBox(a: ChangeBox, b: ChangeBox): ChangeBox {export function scoreFrames(frames: Pixels[]): { cuts: number[]; changes: ShotChange[] } {const grids = frames.map(gridsOf);const none: FrameStep = { pct: NaN, faint: NaN, fine: NaN, box: null };- return pickShotEdges(grids.map((g, i) => (i === 0 ? none : frameStep(grids[i - 1], g))));+ return pickShotEdges(+ grids.map((g, i) => (i === 0 ? none : frameStep(grids[i - 1], g))),+ grids.map((g) => g.fine)+ );}diff --git a/site/src/cut/lib/measure/sourceMeasure.ts b/site/src/cut/lib/measure/sourceMeasure.tsindex 5c13610d..bedd23c8 100644--- a/site/src/cut/lib/measure/sourceMeasure.ts+++ b/site/src/cut/lib/measure/sourceMeasure.ts@@ -178,6 +178,9 @@ export async function scanCuts(const times: number[] = [];const durations: number[] = [];const steps: FrameStep[] = [];+ // Each frame's fine grid, rounded to bytes, for the changes too gradual+ // for one frame to show.+ const fines: Uint8Array[] = [];let prev: FrameGrids | null = null;let outOfTime = false;for await (const f of v.frames(Math.max(0, opts.from - LEAD_S), opts.to, size)) {@@ -187,6 +190,7 @@ export async function scanCuts(}const grid = gridsOf(opts.area ? cropPixels(f, toPixels(f, area)) : f);steps.push(prev ? frameStep(prev, grid) : { pct: NaN, faint: NaN, fine: NaN, box: null });+ fines.push(Uint8Array.from(grid.fine, Math.round));times.push(f.t);durations.push(f.duration);prev = grid;@@ -194,7 +198,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);+ const { cuts: picked, changes: found } = 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.