Open source CapCut alternative.
TypeScript
feat(site): read a sweep's titles on every frame they are up, and small labels off the ground around them
David Le25c6672a6d89
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex e7881fe2..c2954266 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -202,7 +202,7 @@ export const AI_PANEL_TOOLS = ["Check the cut against the thing it was built from, in numbers and in pictures. Every frame is scored by `diff`: the mean difference per pixel between your frame and the source's, 0 (the same) to 255, read at one small size so a score means the same thing in every call; under " +`${SWEEP_TARGET} reads as the same picture. ` +"mode sweep scores every step of the cut (or from/to) with no pictures and returns the median, p95 and max with the worst stretches, each with its peak frame and a 4×4 grid of where in the frame it differs, and `edges`: stretches whose difference runs along whole edges of the frame while the middle matches — a border, band or letterbox — listed under target too, since thin bars barely move the mean. The picture box is already cut out of any app or bars around it, so a band inside it is part of the picture: build it, with shapes or a smaller block. " +- "`titles` names each title whose letters read another colour than the source's under it (`ink` yours, `sourceInk` the source's, read at the title's middle), which a frame score at this size barely moves for. " ++ "`titles` names each title whose letters read another colour than the source's under it, on every frame it is up: `from`-`to` and how many `frames`, with `ink` yours and `sourceInk` the source's at the worst one, null where that side shows no letters (a title up before the source's, or washed out). A frame score at this size barely moves for any of it. " +"A decoder that fails mid-read is replaced and the read goes on: `lost` names source frames no decoder read, and a source that stops decoding ends the sweep at `coveredTo` with `stopped` saying where and why. " +`mode moments (the default) takes up to ${MAX_COMPARE} \`times\` and hands back each as the source's frame and yours side by side, with its score and grid. ` +"Either mode says when a frame matches the source better a few frames away: `shift` is that distance, and a positive one means move what is there later by that much. " +diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex d42a7675..b6b5c10f 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -874,7 +874,7 @@ const SWEEP_NOTE ="diff is the mean difference per pixel between your frame and the source's, 0 (the same) to 255; median is the typical frame, p95 the bad tail, max the worst. " +"worst lists the stretches most off, worst first, each with its peak frame (at on the cut, source on the source) and that frame's 4×4 grid, top row first. " +"edges lists stretches whose difference runs along whole edges of the frame (top, bottom, left, right) while the middle matches: a border, band or letterbox one side has and the other lacks. Thin bars barely move the mean, so these come back under target too. The picture box is already cut out of any app around it, so a band inside it is part of the picture, never the recording's: build it. " +- "titles lists titles whose letters read another colour than the source's under them, ink yours and sourceInk the source's: a small label in the wrong colour barely moves the score, so set each one's color to what the source draws. " ++ "titles lists titles whose letters read another colour than the source's under them over from-to, ink yours and sourceInk the source's at the worst frame; null on one side means its letters do not show there, a title up before the source's, or washed out. A small label barely moves the score, so retime or recolour each to what the source draws. " +"Look at them: compare_to_source with times [{at, source}] at those peaks, fix what differs, then sweep again, until the median is under target and each stretch in worst and edges is fixed or sits over a block standing in for footage, the one difference no edit removes: a glow, a tint, a blurred or soft edge, a flash are all built, so a stretch over what you built is yours to fix. " +"shift on a stretch, or timing for the whole span, means the source matches better that many seconds away: positive, move it later by that much; negative, earlier. " +"onBlocks is the share of samples over blocks standing in for footage; those keep a difference no edit removes.";diff --git a/site/src/cut/lib/frameDiff.test.ts b/site/src/cut/lib/frameDiff.test.tsindex 5e4649d2..288c8b0e 100644--- a/site/src/cut/lib/frameDiff.test.ts+++ b/site/src/cut/lib/frameDiff.test.ts@@ -152,8 +152,8 @@ test("a title's ink is the colour its letters stand off the ground in", () => {const box = { x: 2, y: 2, w: 10, h: 5 };expect(inkColor(lettered(16, 9, [237, 105, 87], [0, 0, 0]), 16, 9, box)).toEqual({ ink: [0, 0, 0], ground: [237, 105, 87] });expect(inkColor(lettered(16, 9, [237, 105, 87], [255, 255, 255]), 16, 9, box)?.ink).toEqual([255, 255, 255]);- // Nothing stands off a flat ground: no letters to read.- expect(inkColor(solid(16, 9, [237, 105, 87]), 16, 9, box)).toBeNull();+ // Nothing stands off a flat ground: no letters, only the ground.+ expect(inkColor(solid(16, 9, [237, 105, 87]), 16, 9, box)).toEqual({ ink: null, ground: [237, 105, 87] });});test("white letters where the source has black ones are off; the same letters a shade apart aren't", () => {@@ -163,7 +163,7 @@ test("white letters where the source has black ones are off; the same letters aconst softer = inkColor(lettered(16, 9, [237, 105, 87], [20, 14, 12]), 16, 9, box)!;expect(inkOff(white, black)).toBeGreaterThan(150);expect(inkOff(softer, black)).toBeLessThan(30);- expect(inkDiff(white.ink, black.ink)).toBe(255);+ expect(inkDiff(white.ink!, black.ink!)).toBe(255);});test("thinner letters of the same colour, blended into their ground, are not off", () => {@@ -192,3 +192,21 @@ test("a box past the frame's edge reads only what is inside it", () => {expect(inkColor(px, 16, 9, { x: 6, y: -4, w: 20, h: 20 })?.ink).toEqual([255, 255, 255]);expect(inkColor(px, 16, 9, { x: 20, y: 20, w: 4, h: 4 })).toBeNull();});++test("a small label that fills its own box reads its ground off what's around it", () => {+ const px = solid(16, 9, [44, 75, 241]);+ for (let y = 3; y <= 5; y++) for (let x = 6; x <= 9; x++) px.set([235, 238, 254, 255], (y * 16 + x) * 4);+ expect(inkColor(px, 16, 9, { x: 6, y: 3, w: 4, h: 3 })).toEqual({ ink: [235, 238, 254], ground: [44, 75, 241] });+});++test("letters the source shows where yours don't are off by how far they stand out", () => {+ // A strobe's white frame: the source's letters read pale cyan on white,+ // ours wash out into the white.+ const white = [249, 245, 244] as [number, number, number];+ const gone = { ink: null, ground: white };+ const cyan = { ink: [184, 232, 253] as [number, number, number], ground: white };+ expect(inkOff(gone, cyan)).toBe(65);+ expect(inkOff(cyan, gone)).toBe(65);+ // Neither shows letters: nothing to tell apart.+ expect(inkOff(gone, gone)).toBe(0);+});diff --git a/site/src/cut/lib/frameDiff.ts b/site/src/cut/lib/frameDiff.tsindex b36e2473..d579bde3 100644--- a/site/src/cut/lib/frameDiff.ts+++ b/site/src/cut/lib/frameDiff.ts@@ -260,6 +260,11 @@ const INK_SHARE = 0.08;* thinner or smaller letters read part way, never past the colour itself. */const INK_BLEND = [0.3, 1.1] as const;+/** The ring around a title's box its ground is read from, as a share of the+ * box's height, and never under 2 px: a small label fills most of its own+ * box, so the box alone would read its letters as the ground. */+const GROUND_RING = 0.25;+/** How far apart the grounds under a title may be for its letters to be* compared: past it the title sits on something else in one frame — a card's* edge, another shape — which is the frame score's to find, not the ink's. */@@ -267,8 +272,9 @@ const GROUND_SLACK = 48;type Rgb3 = [number, number, number];-/** A title's letters as a frame shows them: their colour and the ground's. */-export type Ink = { ink: Rgb3; ground: Rgb3 };+/** A title's letters as a frame shows them: their colour, null where none+ * stand off the ground, and the ground's. */+export type Ink = { ink: Rgb3 | null; ground: Rgb3 };/** How far apart two colours are: the largest of their channel differences. */export function inkDiff(a: Rgb3, b: Rgb3): number {@@ -280,13 +286,18 @@ export function inkDiff(a: Rgb3, b: Rgb3): number {* thinner, smaller or softer than ours read as our colour part way into their* ground, so the source's ink is held against the nearest blend of ours into* the source's ground: white letters read pale over purple are the same- * white, black ones where ours are white are not. Null when the two sit on- * different grounds.+ * white, black ones where ours are white are not. Letters only one side+ * shows are off by how far they stand off its ground. Null when the two sit+ * on different grounds.*/export function inkOff(cut: Ink, source: Ink): number | null {if (inkDiff(cut.ground, source.ground) > GROUND_SLACK) {return null;}+ if (!cut.ink || !source.ink) {+ const shown = cut.ink ? cut : source;+ return shown.ink ? inkDiff(shown.ink, shown.ground) : 0;+ }const dir = cut.ink.map((v, c) => v - cut.ground[c]);const seen = source.ink.map((v, c) => v - source.ground[c]);const len = dir.reduce((a, v) => a + v * v, 0);@@ -295,12 +306,12 @@ export function inkOff(cut: Ink, source: Ink): number | null {}/**- * The colour a title's letters are drawn in, read off a frame: inside the- * box, the ground is the median colour and the ink is the mean of the pixels- * furthest from it. A title's box is mostly ground, so this holds on a flat+ * The colour a title's letters are drawn in, read off a frame: the ground is+ * the median colour of a ring around the box, and the ink the mean of the+ * pixels inside it furthest from that. A title's box is mostly ground, so this holds on a flat* card and on footage alike, and it reads the letters' colour where a frame- * score at a sweep's size barely moves for it. Null when nothing in the box- * stands off the ground.+ * score at a sweep's size barely moves for it. Null when the box is outside+ * the frame.*/export function inkColor(px: Uint8ClampedArray,@@ -316,22 +327,32 @@ export function inkColor(return null;}const at: number[] = [];- const ch: number[][] = [[], [], []];+ const inside: number[][] = [[], [], []];for (let y = y0; y < y1; y++) {for (let x = x0; x < x1; x++) {const i = (y * w + x) * 4;at.push(i);- for (let c = 0; c < 3; c++) ch[c].push(px[i + c]);+ for (let c = 0; c < 3; c++) inside[c].push(px[i + c]);+ }+ }+ const pad = Math.max(2, Math.round(box.h * GROUND_RING));+ const ring: number[][] = [[], [], []];+ for (let y = Math.max(0, y0 - pad); y < Math.min(h, y1 + pad); y++) {+ for (let x = Math.max(0, x0 - pad); x < Math.min(w, x1 + pad); x++) {+ if (x >= x0 && x < x1 && y >= y0 && y < y1) continue;+ const i = (y * w + x) * 4;+ for (let c = 0; c < 3; c++) ring[c].push(px[i + c]);}}- const ground = ch.map((v) => v.sort((a, b) => a - b)[v.length >> 1]) as Rgb3;+ const median = (v: number[]) => v.sort((a, b) => a - b)[v.length >> 1];+ const ground = (ring[0].length > 0 ? ring : inside).map(median) as Rgb3;const off = at.map((i) => ({ i, d: inkDiff([px[i], px[i + 1], px[i + 2]], ground) })).filter((p) => p.d > INK_MIN).sort((a, b) => b.d - a.d).slice(0, Math.max(1, Math.ceil(at.length * INK_SHARE)));if (off.length === 0) {- return null;+ return { ink: null, ground };}const sum = [0, 0, 0];for (const { i } of off) for (let c = 0; c < 3; c++) sum[c] += px[i + c];diff --git a/site/src/cut/lib/sourceCompare.ts b/site/src/cut/lib/sourceCompare.tsindex 06490ebe..4394cc3b 100644--- a/site/src/cut/lib/sourceCompare.ts+++ b/site/src/cut/lib/sourceCompare.ts@@ -1,7 +1,7 @@import { renderProjectFrames } from "./exportRender";import { FULL_FRAME, isFullFrame } from "./measure/picture";import type { FrameBox } from "./measure/sourceMeasure";-import { bestShift, diffPixels, edgeBand, inkColor, inkOff, meanDiff, runShift, SCORE_LONG_SIDE, SWEEP_TARGET, sweepStats, worstStretches, type Edge } from "./frameDiff";+import { bestShift, diffPixels, edgeBand, inkColor, inkOff, meanDiff, type Ink, runShift, SCORE_LONG_SIDE, SWEEP_TARGET, sweepStats, worstStretches, type Edge } from "./frameDiff";import { hexOf } from "./measure/color";import { composeComparison, makeStillFrame } from "./media";import type { WrappedCanvas } from "mediabunny";@@ -54,9 +54,19 @@ const READ_LOST_RUN = 3;const READ_RETRY_MS = 100;/** How far a title's ink may sit from the source's (inkOff) before the sweep- * names it: a white label where the source's is black reads near 230, the- * same label a shade off or a little thinner under 30. */-const INK_TOLERANCE = 64;+ * counts the frame: a white label where the source's is black reads near 230,+ * pale cyan letters washed to white near 65, the same label a shade off or a+ * little thinner under 30. */+const INK_TOLERANCE = 48;++/** Frames a title has to be off on before the sweep names it, so a single+ * frame of a move caught mid-way does not. */+const MIN_TITLE_FRAMES = 2;++/** The shortest box a title is read in, px at the sweep's size: type smaller+ * than this is a few pixels of strokes on either side, and their colour comes+ * and goes with the decode. */+const MIN_TITLE_PX = 8;/** The most titles one sweep names. */const MAX_TITLES = 8;@@ -421,10 +431,16 @@ type Stretch = {export type TitleInk = {id: string;text: string;+ /** The span the title's letters were off over, and on how many frames. */+ from: number;+ to: number;+ frames: number;+ /** Its worst frame, and the letters' colour there on each side: null+ * where that side shows none. */at: number;source: number;- ink: string;- sourceInk: string;+ ink: string | null;+ sourceInk: string | null;};export type SweepResult = {@@ -496,11 +512,18 @@ export async function sweepSource(const size = sizeOf(doc, SWEEP_LONG_SIDE);const scorer = makeScorer(doc, area, fit);- // Titles read at the render's own size, where letters still have cores.+ // Titles read at the render's own size, where letters still have cores,+ // on every sample they are up for: the source's letters as it is decoded,+ // the cut's as it renders.const reads = titleReads(doc, samples);const fine = reads.size > 0 ? makeScorer(doc, area, fit, SWEEP_LONG_SIDE) : null;- const fineSources = new Map<number, Uint8ClampedArray>();- const titles: (TitleInk & { off: number })[] = [];+ const sourceInks = new Map<number, (Ink | null)[]>();+ const readInks = (j: number, px: Uint8ClampedArray, f: NonNullable<typeof fine>) =>+ (reads.get(j) ?? []).map((o) => {+ const box = titleBox(doc, o, samples[j].at, f.size);+ return box.h < MIN_TITLE_PX ? null : inkColor(px, f.size.width, f.size.height, box);+ });+ const offs = new Map<string, { o: TextOverlay; hits: { j: number; off: number; ink: Ink; sourceInk: Ink }[] }>();const width = SHIFT_REACH * 2 + 1;const started = performance.now();const outOfTime = (j: number) => j > 0 && performance.now() - started > SWEEP_BUDGET_MS;@@ -517,7 +540,7 @@ export async function sweepSource(sources.push(...samples.map(() => still));if (fine) {const px = (await stillPixels(asset, fine, area)).pixels;- for (const j of reads.keys()) fineSources.set(j, px);+ for (const j of reads.keys()) sourceInks.set(j, readInks(j, px, fine));}} else {try {@@ -526,7 +549,7 @@ export async function sweepSource(break;}if (c && fine && reads.has(sources.length)) {- fineSources.set(sources.length, fine.pixels(c.canvas, c.canvas.width, c.canvas.height));+ sourceInks.set(sources.length, readInks(sources.length, fine.pixels(c.canvas, c.canvas.width, c.canvas.height), fine));}sources.push(c ? scorer.pixels(c.canvas, c.canvas.width, c.canvas.height) : null);}@@ -572,18 +595,19 @@ export async function sweepSource(cuts.set(j, cut);cuts.delete(j - SHIFT_REACH);- const fineSrc = fineSources.get(j);- if (fine && fineSrc) {- const fineCut = fine.cut(canvas, canvas.width, canvas.height);- for (const o of reads.get(j) ?? []) {- const box = titleBox(doc, o, samples[j].at, fine.size);- const ink = inkColor(fineCut, fine.size.width, fine.size.height, box);- const sourceInk = inkColor(fineSrc, fine.size.width, fine.size.height, box);+ const theirs = sourceInks.get(j);+ if (fine && theirs) {+ const ours = readInks(j, fine.cut(canvas, canvas.width, canvas.height), fine);+ (reads.get(j) ?? []).forEach((o, k) => {+ const ink = ours[k];+ const sourceInk = theirs[k];const off = ink && sourceInk ? inkOff(ink, sourceInk) : null;if (off !== null && off > INK_TOLERANCE) {- titles.push({ id: o.id, text: o.text, at: samples[j].at, source: samples[j].source, ink: hexOf(...ink!.ink), sourceInk: hexOf(...sourceInk!.ink), off });+ const rec = offs.get(o.id) ?? { o, hits: [] };+ rec.hits.push({ j, off, ink: ink!, sourceInk: sourceInk! });+ offs.set(o.id, rec);}- }+ });}});} catch (e) {@@ -637,6 +661,25 @@ export async function sweepSource(};});const timing = still ? undefined : runShift(near, SHIFT_REACH, 0, diffs.length - 1, step);+ const hex = (c: Ink["ink"]) => (c ? hexOf(...c) : null);+ const titles: TitleInk[] = [...offs.values()]+ .filter((r) => r.hits.length >= MIN_TITLE_FRAMES)+ .sort((a, b) => b.hits.length - a.hits.length)+ .slice(0, MAX_TITLES)+ .map(({ o, hits }) => {+ const worst = hits.reduce((a, b) => (b.off > a.off ? b : a));+ return {+ id: o.id,+ text: o.text,+ from: samples[hits[0].j].at,+ to: round3(Math.min(samples[hits[hits.length - 1].j].at + step, to)),+ frames: hits.length,+ at: samples[worst.j].at,+ source: samples[worst.j].source,+ ink: hex(worst.ink.ink),+ sourceInk: hex(worst.sourceInk.ink),+ };+ });const onBlocks = scored.filter((s) => blockAt(doc, s.at)).length / scored.length;const frame = frameNote(doc, scorer.reshaped, area, fit);const reached = diffs.length < samples.length ? samples[diffs.length].at : undefined;@@ -652,9 +695,7 @@ export async function sweepSource(target: SWEEP_TARGET,worst,...(edges.length > 0 ? { edges } : {}),- ...(titles.length > 0- ? { titles: titles.sort((a, b) => b.off - a.off).slice(0, MAX_TITLES).map(({ off: _off, ...t }) => t) }- : {}),+ ...(titles.length > 0 ? { titles } : {}),...(timing ? { timing } : {}),...(onBlocks > 0 ? { onBlocks: Math.round(onBlocks * 100) / 100 } : {}),...(frame ? { frame } : {}),@@ -663,26 +704,15 @@ export async function sweepSource(};}-/** The titles a sweep reads the ink of, by the sample each is read at: the- * one nearest the title's middle, so it is read settled, past its way in. */+/** The titles up at each sample, by the sample's index: a title faded under+ * half is left out there. */function titleReads(doc: ExportDoc, samples: { at: number }[]): Map<number, TextOverlay[]> {+ const titles = doc.overlays.filter((o): o is TextOverlay => isTextOverlay(o) && !o.hidden && !!o.text.trim());const reads = new Map<number, TextOverlay[]>();- const first = samples[0].at;- const last = samples[samples.length - 1].at;- for (const o of doc.overlays) {- if (!isTextOverlay(o) || o.hidden || !o.text.trim() || o.end <= first || o.start > last) {- continue;- }- const mid = clamp((o.start + o.end) / 2, Math.max(first, o.start), Math.min(last, o.end));- let j = 0;- for (let i = 1; i < samples.length; i++) {- if (Math.abs(samples[i].at - mid) < Math.abs(samples[j].at - mid)) j = i;- }- if (samples[j].at < o.start || samples[j].at >= o.end || poseAt(o, samples[j].at - o.start).opacity < 0.5) {- continue;- }- reads.set(j, [...(reads.get(j) ?? []), o]);- }+ samples.forEach(({ at }, j) => {+ const up = titles.filter((o) => at >= o.start && at < o.end && poseAt(o, at - o.start).opacity >= 0.5);+ if (up.length > 0) reads.set(j, up);+ });return reads;}