Open source CapCut alternative.
TypeScript
feat(site): sharpen the chat's template replication [rebuild]
David Lef31f1376a8b7
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex 06756f7e..0c207d94 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -15,6 +15,7 @@ import { FIND_MEDIA_DEFAULT, FIND_MEDIA_MAX, FIND_MEDIA_SNAPSHOT_CAP } from "@/cimport { COMPARE_MODES, MAX_COMPARE, SWEEP_TARGET } from "@/cut/lib/frameDiff";import { EASE_IDS } from "@donkeycut/effects-kit";import {+ DETECT_CHANGES_MAX,DETECT_CUTS_MAX,DETECT_CUTS_SPAN_MAX,SAMPLE_COLOR_MAX,@@ -239,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. \`shots\` lists the stretches between the cuts with their length in frames. 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 and ${DETECT_CUTS_MAX} cuts 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\`. 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.`,inputSchema: obj({asset_id: str("Project asset id of the video"),@@ -253,7 +254,7 @@ export const AI_PANEL_TOOLS = [{name: "sample_color",description:- `Read the colour of a source's pixels: the hex of a region or a point of a frame at a source second, so a block, a shape, a title or a background takes the reference's colour as a number. Contact-sheet cells are JPEGs and shift colour; this reads the decoded frame as the preview shows it. Each sample is a moment \`t\` (SOURCE seconds) and a box — x/y its centre and w/h its size as frame fractions, the box add_shape takes; leave out w/h to read a point. Returns per sample \`hex\`, the region's median colour, and \`spread\`, how far its pixels stray from it on average (0-255: under 10 is a flat fill, over 40 a mix — read \`dominant\` there). \`colors\` 2-${SAMPLE_COLORS_K_MAX} adds \`dominant\`, the colours the region is made of with their shares, largest first: a card and the type on it, a bar and the shot behind it. Read a point inside a flat fill for its colour, a box over a title for its ink and its ground. Up to ${SAMPLE_COLOR_MAX} samples a call, at one moment or each at its own. Works on a still image too (t is ignored).`,+ `Read the colour of a source's pixels: the hex of a region or a point of a frame at a source second, so a block, a shape, a title or a background takes the reference's colour as a number. Contact-sheet cells are JPEGs and shift colour; this reads the decoded frame as the preview shows it. Each sample is a moment \`t\` (SOURCE seconds) and a box — x/y its centre and w/h its size as frame fractions, the box add_shape takes; leave out w/h to read a point. Returns per sample \`hex\`, the region's median colour, and \`spread\`, how far its pixels stray from it on average (0-255: under 10 is a flat fill, over 40 a mix — read \`dominant\` there). \`colors\` 2-${SAMPLE_COLORS_K_MAX} adds \`dominant\`, the colours the region is made of with their shares, largest first: a card and the type on it, a bar and the shot behind it. Read a point inside a flat fill for its colour, a box over a title for its ink and its ground; the ink's share tells a filled word (a quarter of its box or more) from an outlined one, so a word that swaps between the two is read shot by shot. Up to ${SAMPLE_COLOR_MAX} samples a call, at one moment or each at its own. Works on a still image too (t is ignored).`,inputSchema: obj({asset_id: str("Project asset id (video or image)"),diff --git a/site/src/cut/components/ElementsPanel.tools.ts b/site/src/cut/components/ElementsPanel.tools.tsindex f6527bf4..fb465271 100644--- a/site/src/cut/components/ElementsPanel.tools.ts+++ b/site/src/cut/components/ElementsPanel.tools.ts@@ -17,43 +17,49 @@ export const SVG_STICKER_MAX_CHARS = 20000;/** Every shape the panel's grid shows, in `SHAPE_LABELS` order. */export const SHAPE_KINDS = Object.keys(SHAPE_LABELS) as ShapeKind[];+/** The fields one shape takes, alone or as an item of `shapes`. */+const SHAPE_FIELDS = {+ shape: { type: "string", enum: [...SHAPE_KINDS], description: "Shape kind" },+ start: num("Start time s (default: playhead)"),+ end: num("End time s (default: start+3)"),+ x: num("Center x 0..1 (default 0.5)"),+ y: num("Center y 0..1 (default 0.5)"),+ w: num("Width, fraction of frame width"),+ h: num("Height, fraction of frame height (line/arrow: thickness)"),+ fill: str("CSS color (default #FFFFFF; a doodle's default is the graffiti set's teal)"),+ inks: {+ type: "array",+ items: { type: "string" },+ maxItems: DOODLE_INKS_MAX,+ description: `Doodle: up to ${DOODLE_INKS_MAX} more paints beside the fill; each mark takes one of them or the fill`,+ },+ fill_opacity: num("Fill opacity 0..1 (rect/ellipse)"),+ radius: num("Rect corner radius, px at 1080 short side"),+ stroke_color: str("Outline color (rect/ellipse)"),+ stroke_width: num("Outline width px at 1080 short side (0 removes it)"),+ pattern: { type: "string", enum: [...PATTERN_KINDS, "none"], description: 'Not line/arrow: the fill color laid as a pattern clipped to the outline — "stripes" are parallel lines with clear gaps (a loading bar); absent or "none" = solid' },+ pattern_width: num(`Stripe line thickness, px at 1080, ${STRIPE_LINE_MIN}..${STRIPE_LINE_MAX} (default 2)`),+ pattern_gap: num(`Clear space between stripes, px at 1080, 0..${STRIPE_GAP_MAX} (default 1)`),+ pattern_angle: num("Stripe direction in degrees clockwise, -90..90; 0 = vertical lines"),+ shadow: bool("Drop shadow on or off (default off); the shadow_* fields switch it on"),+ shadow_color: str("Shadow hex color, e.g. #00E5FF"),+ shadow_blur: num(`Shadow blur, px at 1080, 0..${SHADOW_BLUR_MAX}`),+ shadow_opacity: num("Shadow opacity 0..1"),+ shadow_y: num(`Shadow drop, px at 1080, -${SHADOW_OFFSET_MAX}..${SHADOW_OFFSET_MAX}; 0 with a bright color makes a glow`),+ rotation: num("Degrees clockwise, -180..180, to a tenth (0.4 matches a slight lean)"),+ opacity: num("Whole-element opacity 0..1"),+ lane: num("Element row (0 = the front row, drawn over every higher row). Elements on one row never overlap — a title over a shape needs a lower row than the shape. Use as few rows as the stacking needs: an element shares a row with anything it never overlaps in time."),+};+export const ELEMENTS_TOOLS = [{name: "add_shape",description:- `Add a vector shape overlay (${SHAPE_KINDS.join(", ")}). Position is the shape center as frame fractions; w/h are frame fractions too (a line/arrow's h is its stroke thickness). Rotation gives lines and arrows their direction. A doodle is animated graffiti in translucent paint: inside its box (default: the whole frame) it paints one hand-drawn mark — a dry-brush smear, a painted X, a burst, a tall painted bar, a brushed ring, a pair of fat loops — often with a thin hand line beside it (a tall oval, standing strands, a scribble), and deals new ones ${DOODLE_FPS} times a second, each in the fill or one of its inks (default: the teal, cream, red, orange and white graffiti set). Put it on a row under the titles to paint behind them, or between titles to sit over one line and under another.`,+ `Add a vector shape overlay (${SHAPE_KINDS.join(", ")}). Position is the shape center as frame fractions; w/h are frame fractions too (a line/arrow's h is its stroke thickness). Rotation gives lines and arrows their direction. A doodle is animated graffiti in translucent paint: inside its box (default: the whole frame) it paints one hand-drawn mark — a dry-brush smear, a painted X, a burst, a tall painted bar, a brushed ring, a pair of fat loops — often with a thin hand line beside it (a tall oval, standing strands, a scribble), and deals new ones ${DOODLE_FPS} times a second, each in the fill or one of its inks (default: the teal, cream, red, orange and white graffiti set). Put it on a row under the titles to paint behind them, or between titles to sit over one line and under another. Pass \`shapes\` to place a stretch's shapes in one call.`,inputSchema: obj({- shape: { type: "string", enum: [...SHAPE_KINDS], description: "Shape kind" },- start: num("Start time s (default: playhead)"),- end: num("End time s (default: start+3)"),- x: num("Center x 0..1 (default 0.5)"),- y: num("Center y 0..1 (default 0.5)"),- w: num("Width, fraction of frame width"),- h: num("Height, fraction of frame height (line/arrow: thickness)"),- fill: str("CSS color (default #FFFFFF; a doodle's default is the graffiti set's teal)"),- inks: {- type: "array",- items: { type: "string" },- maxItems: DOODLE_INKS_MAX,- description: `Doodle: up to ${DOODLE_INKS_MAX} more paints beside the fill; each mark takes one of them or the fill`,- },- fill_opacity: num("Fill opacity 0..1 (rect/ellipse)"),- radius: num("Rect corner radius, px at 1080 short side"),- stroke_color: str("Outline color (rect/ellipse)"),- stroke_width: num("Outline width px at 1080 short side (0 removes it)"),- pattern: { type: "string", enum: [...PATTERN_KINDS, "none"], description: 'Not line/arrow: the fill color laid as a pattern clipped to the outline — "stripes" are parallel lines with clear gaps (a loading bar); absent or "none" = solid' },- pattern_width: num(`Stripe line thickness, px at 1080, ${STRIPE_LINE_MIN}..${STRIPE_LINE_MAX} (default 2)`),- pattern_gap: num(`Clear space between stripes, px at 1080, 0..${STRIPE_GAP_MAX} (default 1)`),- pattern_angle: num("Stripe direction in degrees clockwise, -90..90; 0 = vertical lines"),- shadow: bool("Drop shadow on or off (default off); the shadow_* fields switch it on"),- shadow_color: str("Shadow hex color, e.g. #00E5FF"),- shadow_blur: num(`Shadow blur, px at 1080, 0..${SHADOW_BLUR_MAX}`),- shadow_opacity: num("Shadow opacity 0..1"),- shadow_y: num(`Shadow drop, px at 1080, -${SHADOW_OFFSET_MAX}..${SHADOW_OFFSET_MAX}; 0 with a bright color makes a glow`),- rotation: num("Degrees clockwise, -180..180, to a tenth (0.4 matches a slight lean)"),- opacity: num("Whole-element opacity 0..1"),- lane: num("Element row (0 = the front row, drawn over every higher row). Elements on one row never overlap — a title over a shape needs a lower row than the shape. Use as few rows as the stacking needs: an element shares a row with anything it never overlaps in time."),- }, ["shape"]),+ ...SHAPE_FIELDS,+ shapes: { type: "array", description: "Several shapes at once, each the fields one shape takes", items: obj(SHAPE_FIELDS, ["shape"]) },+ }),},{name: "add_sticker",diff --git a/site/src/cut/components/Timeline.tools.ts b/site/src/cut/components/Timeline.tools.tsindex 008d2f37..16e750d0 100644--- a/site/src/cut/components/Timeline.tools.ts+++ b/site/src/cut/components/Timeline.tools.ts@@ -25,6 +25,35 @@ import { BLOCKOUT_MAX } from "@/cut/lib/blockSource";export const TEXT_SIZE_MIN = 16;export const TEXT_SIZE_MAX = 1600;+/** The fields one title takes, alone or as an item of `titles`. */+const TITLE_FIELDS = {+ text: str("The title text (\\n for line breaks)"),+ start: num("Start time s (default: playhead)"),+ end: num("End time s (default: start+3)"),+ x: num("Center x 0..1 (default 0.5)"),+ y: num("Center y 0..1 (default 0.42)"),+ size: num(`Font size px at 1080w, ${TEXT_SIZE_MIN}..${TEXT_SIZE_MAX} (default 88); a capital is about 0.7 of the size tall, so one letter filling a third of a 1080 frame is about 500`),+ color: str("CSS color (default #FFFFFF)"),+ font: str("Font id (see the graphics skill; default sf)"),+ weight: { type: "number", enum: [...TEXT_WEIGHTS], description: "Font weight: 400 regular, 500 medium, 600 semibold, 700 bold, 800 extra bold, 900 black" },+ italic: bool("Italic"),+ align: { type: "string", enum: ["left", "center", "right"], description: "Multi-line alignment (default center)" },+ letter_spacing: num(`Tracking in em, ${LETTER_SPACING_MIN}..${LETTER_SPACING_MAX} (0 = normal, 0.1 = airy, negative = tight)`),+ line_height: num("Line height multiplier (default 1.25)"),+ stroke_color: str("Text outline color"),+ stroke_width: num("Text outline width in em (0..0.15; 0 removes it)"),+ shadow: bool("Drop shadow (default true)"),+ plate: bool("Translucent plate behind text (default false)"),+ texture: {+ type: "string",+ enum: [...TEXT_TEXTURES, "none"],+ description: 'Grain inside the letters: "stipple" breaks each letter into spray-paint specks along its left edge, solid by its middle (the gritty teaser title); "none" makes the type solid again',+ },+ rotation: num("Degrees clockwise, -180..180, to a tenth (0.4 matches a slight lean)"),+ opacity: num("Whole-element opacity 0..1"),+ lane: num("Element row (0 = the front row, drawn over every higher row). Elements on one row never overlap — a title over a shape needs a lower row than the shape. Use as few rows as the stacking needs: an element shares a row with anything it never overlaps in time."),+};+export const TIMELINE_TOOLS = [{name: "select",@@ -150,8 +179,16 @@ export const TIMELINE_TOOLS = [{name: "rename_item",description:- "Name any timeline item — a video or image clip on any track, a soundtrack clip, or a title/shape/sticker/effect element — by id. The name shows on its timeline bar, in the inspector and in editor_state, so a cut full of look-alike items stays legible. An empty name clears it, back to the file's name or what the element is.",- inputSchema: obj({ id: str("Clip, soundtrack clip, or element id"), name: str("The name, up to 60 characters; empty clears") }, ["id", "name"]),+ "Name any timeline item — a video or image clip on any track, a soundtrack clip, or a title/shape/sticker/effect element — by id. The name shows on its timeline bar, in the inspector and in editor_state, so a cut full of look-alike items stays legible. An empty name clears it, back to the file's name or what the element is. Pass `names` to name a whole cut in one call.",+ inputSchema: obj({+ id: str("Clip, soundtrack clip, or element id"),+ name: str("The name, up to 60 characters; empty clears"),+ names: {+ type: "array",+ description: "Several items at once, each {id, name}",+ items: obj({ id: str("Item id"), name: str("Its name") }, ["id", "name"]),+ },+ }),},{name: "set_clip_hidden",@@ -258,34 +295,11 @@ export const TIMELINE_TOOLS = [{name: "add_title",description:- "Add a text title overlay. Position is the text center as a fraction of the frame (x,y in 0..1; y=0.42 is the default band). Size is px at 1080-wide. Font ids come from the graphics skill (system set + the bundled Google families). A line wider than the room its anchor leaves is broken onto more lines when it draws, so a title always sits inside the frame — write the words and pick the size the design wants.",+ "Add a text title overlay. Position is the text center as a fraction of the frame (x,y in 0..1; y=0.42 is the default band). Size is px at 1080-wide. Font ids come from the graphics skill (system set + the bundled Google families). A line wider than the room its anchor leaves is broken onto more lines when it draws, so a title always sits inside the frame — write the words and pick the size the design wants. Pass `titles` to place a stretch's titles in one call.",inputSchema: obj({- text: str("The title text (\\n for line breaks)"),- start: num("Start time s (default: playhead)"),- end: num("End time s (default: start+3)"),- x: num("Center x 0..1 (default 0.5)"),- y: num("Center y 0..1 (default 0.42)"),- size: num(`Font size px at 1080w, ${TEXT_SIZE_MIN}..${TEXT_SIZE_MAX} (default 88); a capital is about 0.7 of the size tall, so one letter filling a third of a 1080 frame is about 500`),- color: str("CSS color (default #FFFFFF)"),- font: str("Font id (see the graphics skill; default sf)"),- weight: { type: "number", enum: [...TEXT_WEIGHTS], description: "Font weight: 400 regular, 500 medium, 600 semibold, 700 bold, 800 extra bold, 900 black" },- italic: bool("Italic"),- align: { type: "string", enum: ["left", "center", "right"], description: "Multi-line alignment (default center)" },- letter_spacing: num(`Tracking in em, ${LETTER_SPACING_MIN}..${LETTER_SPACING_MAX} (0 = normal, 0.1 = airy, negative = tight)`),- line_height: num("Line height multiplier (default 1.25)"),- stroke_color: str("Text outline color"),- stroke_width: num("Text outline width in em (0..0.15; 0 removes it)"),- shadow: bool("Drop shadow (default true)"),- plate: bool("Translucent plate behind text (default false)"),- texture: {- type: "string",- enum: [...TEXT_TEXTURES, "none"],- description: 'Grain inside the letters: "stipple" breaks each letter into spray-paint specks along its left edge, solid by its middle (the gritty teaser title); "none" makes the type solid again',- },- rotation: num("Degrees clockwise, -180..180, to a tenth (0.4 matches a slight lean)"),- opacity: num("Whole-element opacity 0..1"),- lane: num("Element row (0 = the front row, drawn over every higher row). Elements on one row never overlap — a title over a shape needs a lower row than the shape. Use as few rows as the stacking needs: an element shares a row with anything it never overlaps in time."),- }, ["text"]),+ ...TITLE_FIELDS,+ titles: { type: "array", description: "Several titles at once, each the fields one title takes", items: obj(TITLE_FIELDS, ["text"]) },+ }),},{name: "add_text_sequence",diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 42d0ec1d..05caabf6 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -244,7 +244,7 @@ import { COMPARE_MODES, MAX_COMPARE, SWEEP_TARGET } from "./frameDiff";import { compareMoments, sweepSource } from "./sourceCompare";import { findPicture, sampleColors, scanCuts, trackElement, type FrameBox } from "./measure/sourceMeasure";import { FULL_FRAME, isFullFrame } from "./measure/picture";-import { DETECT_CUTS_MAX, DETECT_CUTS_SPAN_MAX, SAMPLE_COLOR_MAX, SAMPLE_COLORS_K_MAX, TRACK_FRAMES_MAX, TRACK_MATCHES, TRACK_PATH_MAX, TRACK_TOLERANCE_DEFAULT } from "./measure/limits";+import { DETECT_CHANGES_MAX, DETECT_CUTS_MAX, DETECT_CUTS_SPAN_MAX, SAMPLE_COLOR_MAX, SAMPLE_COLORS_K_MAX, TRACK_FRAMES_MAX, TRACK_MATCHES, TRACK_PATH_MAX, TRACK_TOLERANCE_DEFAULT } from "./measure/limits";import { renderStageFrame, storeStageStill } from "./stageFrame";import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";import { buildAiContext, describeCameraCard, describeDoc, describeParkedTimeline, hiddenFromChat, OTHER_CHATS_MEDIA_NOTE, roundT } from "./aiContext";@@ -772,6 +772,103 @@ function refuseCardFraming(clip: VideoClip, input: Record<string, unknown>, fielconst aimedLane = (input: Record<string, unknown>): { lane?: number } | undefined =>isNum(input.lane) ? { lane: Math.max(0, Math.round(input.lane)) } : undefined;+/** One placed element as add_title and add_shape report it. */+type Placed = { id: string } & Record<string, unknown>;++/** Run a placing tool over its list (`titles`, `shapes`) or over the call as+ * one item. Every item is checked before the first is placed, so a bad one+ * refuses the whole call and leaves nothing behind; the call is already one+ * undo step. Example: { titles: [{ text: "A" }, { text: "B" }] } →+ * { ids: [a, b], titles: [{ id: a, … }, { id: b, … }] }. */+function placeEach(+ input: Record<string, unknown>,+ key: "titles" | "shapes",+ check: (item: Record<string, unknown>) => void,+ place: (item: Record<string, unknown>) => Placed+): unknown {+ // A one-item call keeps the result it always had.+ const list = input[key];+ if (list === undefined) {+ check(input);+ return place(input);+ }++ // The list holds at least one item and stands alone: fields beside it+ // would be dropped unread.+ if (!Array.isArray(list) || list.length === 0) {+ throw new ToolError(`${key} is a list of one or more items.`);+ }+ const beside = Object.keys(input).filter((k) => k !== key);+ if (beside.length > 0) {+ throw new ToolError(`Pass ${beside.join(", ")} inside each of ${key}; nothing was placed.`);+ }++ // Every item is checked before any is placed, naming the one refused.+ const items = list.map((raw: unknown, i) => {+ const item = (raw !== null && typeof raw === "object" ? raw : {}) as Record<string, unknown>;+ try {+ check(item);+ } catch (e) {+ const why = e instanceof Error ? e.message : String(e);+ throw new ToolError(`${key}[${i}]: ${why} Nothing was placed.`, { cause: e });+ }+ return item;+ });++ // Placed in order, so the ids line up with the items.+ const placed = items.map(place);+ return { ids: placed.map((p) => p.id), [key]: placed };+}++/** add_title's refusals, run before the title exists. */+function checkTitle(input: Record<string, unknown>): void {+ if (typeof input.text !== "string" || !input.text.trim()) {+ throw new ToolError("text is required.");+ }+ overlayPatch(input, "text");+}++/** Place one checked title. */+function placeTitle(input: Record<string, unknown>): Placed {+ const s = useEditor.getState();+ if (isNum(input.start)) {+ s.seek(input.start);+ }+ s.addOverlay({ ...aimedLane(input), seed: "defaults" });+ const sel = useEditor.getState().selection;+ if (sel?.kind !== "overlay") {+ throw new ToolError("Could not create the title.");+ }+ applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "text"));+ const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;+ return { id: o.id, ...(isTextOverlay(o) ? { text: o.text } : {}), start: o.start, end: o.end };+}++/** add_shape's refusals, run before the shape exists. */+function checkShape(input: Record<string, unknown>): void {+ if (!(String(input.shape) in SHAPE_LABELS)) {+ throw new ToolError(`shape must be one of ${SHAPE_KINDS.join(", ")}.`);+ }+ overlayPatch(input, "shape");+}++/** Place one checked shape. */+function placeShape(input: Record<string, unknown>): Placed {+ const s = useEditor.getState();+ const shape = String(input.shape) as ShapeKind;+ if (isNum(input.start)) {+ s.seek(input.start);+ }+ s.addShape(shape, aimedLane(input));+ const sel = useEditor.getState().selection;+ if (sel?.kind !== "overlay") {+ throw new ToolError("Could not create the shape.");+ }+ applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "shape"));+ const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;+ return { id: o.id, shape, start: roundT(o.start), end: roundT(o.end) };+}+/** Every tool that runs in the browser: the full catalog minus the* `server: true` skills tools the engine answers itself. */type BrowserToolName = Exclude<@@ -808,18 +905,7 @@ type ToolRun = (s: Editor, input: Record<string, unknown>, operation?: ProjectOp* modules beside the components export, so a tool added, removed, or renamed* there refuses to compile until this map matches. */const toolRuns: Record<BrowserToolName, ToolRun> = {- add_shape: (s, input) => {- const shape = String(input.shape) as ShapeKind;- if (!(shape in SHAPE_LABELS))- throw new ToolError(`shape must be one of ${SHAPE_KINDS.join(", ")}.`);- if (isNum(input.start)) s.seek(input.start);- s.addShape(shape, aimedLane(input));- const sel = useEditor.getState().selection;- if (sel?.kind !== "overlay") throw new ToolError("Could not create the shape.");- applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "shape"));- const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;- return { id: o.id, shape, start: roundT(o.start), end: roundT(o.end) };- },+ add_shape: (_s, input) => placeEach(input, "shapes", checkShape, placeShape),add_sticker: async (s, input) => {const svg = typeof input.svg === "string" && input.svg.trim() ? input.svg : undefined;@@ -1506,6 +1592,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {(sweep.lost? `Source frames at ${sweep.lost.map((l) => `${l.source}s`).join(", ")} did not decode (${sweep.lost[0].error}) and are left out of the scores. `: "") ++ silenceNote(s, asset) +SWEEP_NOTE,};}@@ -1531,7 +1618,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {// The same shape every look returns, so a record opened by a// comparison knows what the other senses may ask of this source.source: sourceRef(asset),- note: COMPARE_NOTE,+ note: silenceNote(s, asset) + COMPARE_NOTE,};},@@ -1598,6 +1685,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {from,to,maxCuts: DETECT_CUTS_MAX,+ maxChanges: DETECT_CHANGES_MAX,budgetMs: MEASURE_BUDGET_MS,...(isFullFrame(area) ? {} : { area }),})@@ -1613,6 +1701,15 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {to: roundT(end),frames: Math.round((end - edges[i]) * scan.fps),}));+ // Every shot's middle and the frame each change settles on: watch_video+ // lands a frame on each, so a card shorter than its step is still read.+ const settled = scan.changes.map((c) => c.t + c.frames / scan.fps);+ shotMoments.set(asset.id, [+ ...(shotMoments.get(asset.id) ?? []).filter((t) => t < from || t >= scan.coveredTo),+ ...shots.map((sh) => (sh.from + sh.to) / 2),+ ...settled.filter((t) => t < scan.coveredTo),+ ]);+// The span bound ends a pass the caller asked to run further.const truncated = scan.truncated || to < asked;const more = truncated || to < asset.duration - 0.001;@@ -1624,6 +1721,13 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {truncated,cuts: scan.cuts.map((c) => ({ t: roundT(c.t), frame: c.frame, change: c.change })),shots,+ changes: scan.changes.map((c) => ({+ t: roundT(c.t),+ frame: c.frame,+ frames: c.frames,+ change: c.change,+ box: { x: roundT(c.box.x), y: roundT(c.box.y), w: roundT(c.box.w), h: roundT(c.box.h) },+ })),...pictureReport(area),...(keepsPicture ? { pictureKept: true as const } : {}),source: sourceRef(asset),@@ -1783,6 +1887,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {...(isNum(input.interval_seconds) ? { interval: input.interval_seconds } : {}),detail,at: aimed,+ shots: shotMoments.get(asset.id) ?? [],budgetMs: 90_000,})).catch((e) => {@@ -2958,13 +3063,28 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {},rename_item: (s, input) => {- const name = String(input.name ?? "").trim().slice(0, 60) || undefined;- const id = String(input.id ?? "");- if (s.clips.some((c) => c.id === id)) s.updateClip(id, { name });- else if (s.audioClips.some((a) => a.id === id)) s.updateAudio(id, { name });- else if (s.overlays.some((o) => o.id === id)) s.updateOverlay(id, { name });- else throw new ToolError(`No clip, soundtrack clip, or element with id ${id}.`);- return { id, name: name ?? null };+ // One pair, or `names` for a whole cut's worth in one call.+ const pairs = (Array.isArray(input.names) ? input.names : [input]).map((p: unknown) => {+ const rec = (p ?? {}) as Record<string, unknown>;+ return { id: String(rec.id ?? ""), name: String(rec.name ?? "").trim().slice(0, 60) || undefined };+ });++ // Every id is found before any name is written.+ const writers = pairs.map(({ id }) => {+ if (s.clips.some((c) => c.id === id)) {+ return (name: string | undefined) => s.updateClip(id, { name });+ }+ if (s.audioClips.some((a) => a.id === id)) {+ return (name: string | undefined) => s.updateAudio(id, { name });+ }+ if (s.overlays.some((o) => o.id === id)) {+ return (name: string | undefined) => s.updateOverlay(id, { name });+ }+ throw new ToolError(`No clip, soundtrack clip, or element with id ${id}; nothing was renamed.`);+ });+ pairs.forEach(({ name }, i) => writers[i](name));+ const named = pairs.map(({ id, name }) => ({ id, name: name ?? null }));+ return named.length === 1 ? named[0] : { named };},set_clip_hidden: (s, input) => {@@ -3176,21 +3296,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return { closed: { track, ...gap }, ...tracksAfter() };},- add_title: (s, input) => {- if (typeof input.text !== "string" || !input.text.trim())- throw new ToolError("text is required.");- // Refused before the title exists, so a bad font leaves nothing behind.- if (input.font !== undefined) {- knownFont(input.font);- }- if (isNum(input.start)) s.seek(input.start);- s.addOverlay({ ...aimedLane(input), seed: "defaults" });- const sel = useEditor.getState().selection;- if (sel?.kind !== "overlay") throw new ToolError("Could not create the title.");- applyOverlayPatchSettled(sel.id, overlayPatch({ ...input, id: sel.id }, "text"));- const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;- return { id: o.id, ...(isTextOverlay(o) ? { text: o.text } : {}), start: o.start, end: o.end };- },+ add_title: (_s, input) => placeEach(input, "titles", checkTitle, placeTitle),add_text_sequence: (s, input) => {const look = requireTextLook(input.look);@@ -6649,6 +6755,10 @@ function textSequenceLines(* same source asks for the first look's reading before it spends a call. */const unwritten = new Map<string, { from: number; to: number }>();+/** The moments detect_cuts measured in each source, by asset id: the middle+ * of every shot and the frame every change inside one settles on. */+const shotMoments = new Map<string, number[]>();+/** A span counts as written down once notes describe all but a sliver of it. */function spanIsNoted(watch: AssetWatch | undefined, span: { from: number; to: number }): boolean {let cursor = span.from;@@ -6770,6 +6880,22 @@ function soundOf(asset: MediaAsset): "yes" | "none" | "unknown" {return "unknown";}+/** What a comparison says when the cut plays nothing and the reference may+ * have sound: the frames can match while the cut is still mute. */+function silenceNote(s: Editor, asset: MediaAsset): string {+ const sound = soundOf(asset);+ if (sound === "none" || s.audioClips.length > 0) {+ return "";+ }+ const voiced = s.clips.some((c) => !c.muted && s.assets.find((a) => a.id === c.assetId)?.type === "video");+ if (voiced) {+ return "";+ }+ return sound === "yes"+ ? `The cut plays no sound and "${asset.name}" has a soundtrack: detach_audio with its assetId lays that track on the soundtrack from 0, lined up with its picture, and its picture stays off every timeline. `+ : `The cut plays no sound. listen_audio on "${asset.name}" says whether it has a soundtrack to lay down with detach_audio. `;+}+/** How every source-reading tool names the source it read. `type` and `sound`* say which tools it can answer at all, so nothing downstream asks a music* file for its picture or a silent take for its sound. */diff --git a/site/src/cut/lib/chatToolEdges.test.ts b/site/src/cut/lib/chatToolEdges.test.tsindex 56f30c35..cd3bb81d 100644--- a/site/src/cut/lib/chatToolEdges.test.ts+++ b/site/src/cut/lib/chatToolEdges.test.ts@@ -84,3 +84,73 @@ test("set_transition refuses a band on a crossfade before it writes the crossfadawait expect(runAiTool("set_transition", { clipId: first.id, seconds: 0.4, style: "crossfade", band: 0.3 })).rejects.toThrow();expect(useEditor.getState().clips[0].transition ?? 0).toBe(0);});++describe("rename_item", () => {+ test("names many items in one call and undoes in one step", async () => {+ await runAiTool("rename_item", { names: [{ id: "a", name: "s01a" }, { id: "b", name: "s01b" }] });+ expect(overlay("a").name).toBe("s01a");+ expect(overlay("b").name).toBe("s01b");+ useEditor.getState().undo();+ expect(overlay("a").name).toBeUndefined();+ expect(overlay("b").name).toBeUndefined();+ });++ test("an unknown id is refused before any name is written", async () => {+ await expect(runAiTool("rename_item", { names: [{ id: "a", name: "s01a" }, { id: "zz", name: "s02" }] })).rejects.toThrow();+ expect(overlay("a").name).toBeUndefined();+ });+});++describe("add_title and add_shape lists", () => {+ // A stretch of a template's type in one call: each item lands with its own+ // fields and the result lists the new ids in order.+ test("titles land with their fields, ids in order, and undo in one step", async () => {+ const out = (await runAiTool("add_title", {+ titles: [+ { text: "ONE", start: 0, end: 1, x: 0.3, color: "#ff0000", lane: 1 },+ { text: "TWO", start: 1, end: 2, y: 0.7, size: 120 },+ ],+ })) as { ids: string[]; titles: { id: string; text: string }[] };+ const made = useEditor.getState().overlays.filter((o) => out.ids.includes(o.id)) as unknown as Record<string, unknown>[];+ expect(out.ids).toHaveLength(2);+ expect(out.titles.map((t) => t.text)).toEqual(["ONE", "TWO"]);+ expect(made.find((o) => o.id === out.ids[0])).toMatchObject({ text: "ONE", start: 0, end: 1, x: 0.3, color: "#ff0000", lane: 1 });+ expect(made.find((o) => o.id === out.ids[1])).toMatchObject({ text: "TWO", start: 1, end: 2, y: 0.7, size: 120 });+ useEditor.getState().undo();+ expect(useEditor.getState().overlays.map((o) => o.id)).toEqual(["a", "b"]);+ });++ // One bad item refuses the whole call, naming the item.+ test("a bad title is refused before any title is written", async () => {+ await expect(runAiTool("add_title", { titles: [{ text: "ONE" }, { text: "TWO", font: "no-such-face" }] })).rejects.toThrow(/titles\[1\]/);+ await expect(runAiTool("add_title", { titles: [{ text: "ONE" }, { text: " " }] })).rejects.toThrow(/titles\[1\]/);+ expect(useEditor.getState().overlays.map((o) => o.id)).toEqual(["a", "b"]);+ });++ // A one-title call keeps the result it always had.+ test("a single title keeps its result shape", async () => {+ const out = (await runAiTool("add_title", { text: "SOLO", start: 0, end: 1 })) as Record<string, unknown>;+ expect(Object.keys(out).sort()).toEqual(["end", "id", "start", "text"]);+ });++ test("shapes land with their fields, ids in order, and undo in one step", async () => {+ const out = (await runAiTool("add_shape", {+ shapes: [+ { shape: "rect", start: 0, end: 1, w: 0.5, fill: "#00ff00", lane: 2 },+ { shape: "ellipse", start: 1, end: 2, x: 0.2, h: 0.3 },+ ],+ })) as { ids: string[]; shapes: { id: string; shape: string }[] };+ const made = useEditor.getState().overlays as unknown as Record<string, unknown>[];+ expect(out.shapes.map((s) => s.shape)).toEqual(["rect", "ellipse"]);+ expect(made.find((o) => o.id === out.ids[0])).toMatchObject({ shape: "rect", start: 0, end: 1, w: 0.5, fill: "#00ff00", lane: 2 });+ expect(made.find((o) => o.id === out.ids[1])).toMatchObject({ shape: "ellipse", start: 1, end: 2, x: 0.2, h: 0.3 });+ useEditor.getState().undo();+ expect(useEditor.getState().overlays.map((o) => o.id)).toEqual(["a", "b"]);+ });++ test("a bad shape is refused before any shape is written", async () => {+ await expect(runAiTool("add_shape", { shapes: [{ shape: "rect" }, { shape: "blob" }] })).rejects.toThrow(/shapes\[1\]/);+ await expect(runAiTool("add_shape", { shapes: [{ shape: "rect" }, { shape: "rect", pattern: "zigzag" }] })).rejects.toThrow(/shapes\[1\]/);+ expect(useEditor.getState().overlays.map((o) => o.id)).toEqual(["a", "b"]);+ });+});diff --git a/site/src/cut/lib/compareToSource.test.ts b/site/src/cut/lib/compareToSource.test.tsindex fd137ae3..770237f4 100644--- a/site/src/cut/lib/compareToSource.test.ts+++ b/site/src/cut/lib/compareToSource.test.ts@@ -397,3 +397,21 @@ test("a moment no decoder reads names the second and the decoder's own words", aexpect(error).toContain("3s");expect(error).toContain("Decoding error.");});++test("a silent cut held up to a reference with sound says so", async () => {+ // A blocked-out replica built from titles and shapes plays nothing; the+ // reference's sound is what its cuts were timed to.+ useEditor.getState().updateAsset("ref", { watch: { heard: [{ from: 0, to: 33 }] } as never });+ const out = (await runAiTool("compare_to_source", { asset_id: "ref", mode: "sweep", from: 0, to: 1, step: 0.5 })) as { note: string };+ expect(out.note).toContain("plays no sound");+ expect(out.note).toContain("detach_audio");+ // A reference kept off the timelines still lends its sound.+ expect(out.note).toContain("its picture stays off every timeline");+ const look = (await runAiTool("compare_to_source", { asset_id: "ref", times: [1] })) as { note: string };+ expect(look.note).toContain("plays no sound");++ // With the reference's track on the soundtrack, nothing is said.+ useEditor.setState({ audioClips: [{ id: "a1", assetId: "ref", start: 0, in: 0, out: 33.17, volume: 1, lane: 0 }] as never });+ const heard = (await runAiTool("compare_to_source", { asset_id: "ref", mode: "sweep", from: 0, to: 1, step: 0.5 })) as { note: string };+ expect(heard.note).not.toContain("plays no sound");+});diff --git a/site/src/cut/lib/measure/cuts.test.ts b/site/src/cut/lib/measure/cuts.test.tsindex c6eeade5..34ce3641 100644--- a/site/src/cut/lib/measure/cuts.test.ts+++ b/site/src/cut/lib/measure/cuts.test.ts@@ -1,5 +1,5 @@import { expect, test } from "bun:test";-import { changePct, gridMeans, pickCuts } from "./cuts";+import { changePct, gridMeans, pickCuts, scoreFrames } from "./cuts";/** A w×h RGBA frame of one colour. */const solid = (w: number, h: number, rgb: [number, number, number]) => {@@ -38,3 +38,59 @@ test("a small flicker under the floor is not a cut", () => {const scores = [NaN, 0, 0, 5, 0, 0];expect(pickCuts(scores)).toEqual([]);});++/** A w×h RGBA frame of one colour with a rect of another inside it, the rect+ * in pixels [x0, x1) × [y0, y1). */+const card = (w: number, h: number, bg: [number, number, number], ink: [number, number, number], r: [number, number, number, number]) => {+ const px = solid(w, h, bg);+ for (let y = r[2]; y < r[3]; y++) for (let x = r[0]; x < r[1]; x++) px.data.set([...ink, 255], (y * w + x) * 4);+ return px;+};++test("a flat colour swapping for a near one over still frames is a cut", () => {+ // A dark green card cut to a slightly lighter one: every cell moves, each+ // by less than a hard change, and the frames around it are still.+ const frames = [+ ...Array(4).fill([26, 47, 42]),+ ...Array(4).fill([38, 54, 48]),+ ].map((rgb) => solid(64, 64, rgb as [number, number, number]));+ expect(scoreFrames(frames).cuts).toEqual([4]);+});++test("a crossfade moves every cell a little every frame and is not a cut", () => {+ const frames = Array.from({ length: 10 }, (_, i) => solid(64, 64, [239 - i * 10, 170 + i * 8, 127 + i * 9]));+ expect(scoreFrames(frames).cuts).toEqual([]);+});++test("a word appearing on a still card is a change inside the shot, with its box", () => {+ const blank = solid(128, 128, [158, 3, 2]);+ const word = card(128, 128, [158, 3, 2], [227, 177, 177], [72, 96, 56, 70]);+ const { cuts, changes } = scoreFrames([blank, blank, blank, word, word, word]);+ expect(cuts).toEqual([]);+ expect(changes).toHaveLength(1);+ expect(changes[0].frame).toBe(3);+ expect(changes[0].frames).toBe(1);+ expect(changes[0].box.x).toBeCloseTo(84 / 128, 1);+ expect(changes[0].box.y).toBeCloseTo(63 / 128, 1);+ expect(changes[0].box.w).toBeGreaterThan(0.15);+ expect(changes[0].box.w).toBeLessThan(0.3);+});++test("a word fading in over a few frames is one change that runs those frames", () => {+ const bg: [number, number, number] = [158, 3, 2];+ const at = (a: number) => card(128, 128, bg, [Math.round(158 + a * 69), Math.round(3 + a * 174), Math.round(2 + a * 175)], [40, 88, 56, 72]);+ const frames = [at(0), at(0), at(0), at(0.33), at(0.66), at(1), at(1), at(1), at(1)];+ const { cuts, changes } = scoreFrames(frames);+ expect(cuts).toEqual([]);+ expect(changes).toHaveLength(1);+ expect(changes[0].frame).toBe(3);+ expect(changes[0].frames).toBe(3);+});++test("a hard cut is not also reported as a change", () => {+ const red = solid(128, 128, [158, 3, 2]);+ const grey = solid(128, 128, [73, 66, 68]);+ const { cuts, changes } = scoreFrames([red, red, red, grey, grey, grey]);+ expect(cuts).toEqual([3]);+ expect(changes).toEqual([]);+});diff --git a/site/src/cut/lib/measure/cuts.ts b/site/src/cut/lib/measure/cuts.tsindex d9ab06fa..36c8921b 100644--- a/site/src/cut/lib/measure/cuts.ts+++ b/site/src/cut/lib/measure/cuts.ts@@ -17,6 +17,16 @@ export const CUT_TUNING = {SPIKE: 3,/** Frames either side a cut is judged against. */NEIGHBOURS: 3,+ /** Per-channel step a flat fill takes when it cuts to a near colour (a dark+ * green to a slightly lighter one): under CELL_TOL, over grain. */+ FAINT_TOL: 6,+ /** % of cells that must take that faint step together to make a cut. */+ FAINT_ALL: 90,+ /** Cells per side of the finer grid changes inside a shot are read on: a+ * word or a small shape covers a few of its cells. */+ FINE_GRID: 32,+ /** % of the fine grid a change inside a shot covers at least. */+ CHANGE_MIN: 0.3,};/** Per-cell channel means of an RGBA frame on a GRID×GRID grid. */@@ -52,26 +62,172 @@ export const changePct = (a: Float32Array, b: Float32Array): number => diffCellP* the same large change every frame — is not one, and a one-frame shot keeps* both of its cuts because one high neighbour never moves the median. */export function pickCuts(scores: number[]): number[] {- const { MIN_CHANGE, SPIKE, NEIGHBOURS } = CUT_TUNING;+ const { MIN_CHANGE, SPIKE } = CUT_TUNING;const cuts: number[] = [];for (let i = 0; i < scores.length; i++) {const s = scores[i];if (!(s >= MIN_CHANGE)) {continue;}-- // The neighbours on both sides that have a score of their own.- const around: number[] = [];- for (let j = Math.max(0, i - NEIGHBOURS); j <= Math.min(scores.length - 1, i + NEIGHBOURS); j++) {- if (j !== i && Number.isFinite(scores[j])) {- around.push(scores[j]);- }- }- around.sort((a, b) => a - b);- const median = around.length === 0 ? 0 : around[Math.floor((around.length - 1) / 2)];- if (s >= SPIKE * median) {+ if (s >= SPIKE * neighbourMedian(scores, i)) {cuts.push(i);}}return cuts;}++/** A box as centre and size, fractions of the scanned picture. */+export interface ChangeBox {+ x: number;+ y: number;+ w: number;+ h: number;+}++/** One frame reduced for scoring: the cut grid and the finer change grid. */+export interface FrameGrids {+ coarse: Float32Array;+ fine: Float32Array;+}++/** What a frame changed from the one before: `pct` of the cut grid past the+ * hard tolerance, `faint` of it past the faint one, `fine` of the fine grid+ * past the hard tolerance, and the box around those fine cells. */+export interface FrameStep {+ pct: number;+ faint: number;+ fine: number;+ box: ChangeBox | null;+}++/** A change inside a shot: from frame `frame` for `frames` frames, the most+ * of the picture it changed in one frame (`change`, %) and where. */+export interface ShotChange {+ frame: number;+ frames: number;+ change: number;+ box: ChangeBox;+}++export const gridsOf = (px: Pixels): FrameGrids => ({+ coarse: gridMeans(px),+ fine: gridMeans(px, CUT_TUNING.FINE_GRID),+});++/** The fine cells that changed between two frames, and the box around them. */+function fineChange(a: Float32Array, b: Float32Array): { pct: number; box: ChangeBox | null } {+ const grid = CUT_TUNING.FINE_GRID;+ let n = 0;+ let x0 = grid;+ let x1 = -1;+ let y0 = grid;+ let y1 = -1;+ for (let c = 0; c < grid * grid; c++) {+ const i = c * 3;+ const d = Math.max(Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2]));+ if (d <= CUT_TUNING.CELL_TOL) {+ continue;+ }+ n++;+ const gx = c % grid;+ const gy = Math.floor(c / grid);+ x0 = Math.min(x0, gx);+ x1 = Math.max(x1, gx);+ y0 = Math.min(y0, gy);+ y1 = Math.max(y1, gy);+ }+ if (n === 0) {+ return { pct: 0, box: null };+ }+ const box = { x: (x0 + x1 + 1) / 2 / grid, y: (y0 + y1 + 1) / 2 / grid, w: (x1 - x0 + 1) / grid, h: (y1 - y0 + 1) / grid };+ return { pct: (100 * n) / (grid * grid), box };+}++/** How `next` differs from `prev` on both grids. */+export function frameStep(prev: FrameGrids, next: FrameGrids): FrameStep {+ const fine = fineChange(prev.fine, next.fine);+ return {+ pct: changePct(prev.coarse, next.coarse),+ faint: diffCellPct(prev.coarse, next.coarse, CUT_TUNING.FAINT_TOL),+ fine: fine.pct,+ box: fine.box,+ };+}++/** The median of the scores within NEIGHBOURS of `i`, skipping `i`, frames+ * with no score, and any index `skip` holds. */+function neighbourMedian(scores: number[], i: number, skip?: Set<number>): number {+ const around: number[] = [];+ for (let j = Math.max(0, i - CUT_TUNING.NEIGHBOURS); j <= Math.min(scores.length - 1, i + CUT_TUNING.NEIGHBOURS); j++) {+ if (j !== i && Number.isFinite(scores[j]) && !skip?.has(j)) {+ around.push(scores[j]);+ }+ }+ around.sort((a, b) => a - b);+ return around.length === 0 ? 0 : around[Math.floor((around.length - 1) / 2)];+}++/** The frames that open a shot and the changes inside shots, from each+ * frame's step (index 0 has none: NaN fields).+ * 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.+ * A change is a spike on the fine grid in a frame that is no cut — a word+ * 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[] } {+ const { FAINT_ALL, SPIKE, CHANGE_MIN } = CUT_TUNING;+ const hard = pickCuts(steps.map((s) => s.pct));+ const faintScores = steps.map((s) => s.faint);++ // The faint cuts, beside the hard ones.+ const cutSet = new Set(hard);+ for (let i = 0; i < steps.length; i++) {+ if (cutSet.has(i) || !(faintScores[i] >= FAINT_ALL)) {+ continue;+ }+ if (neighbourMedian(faintScores, i) * SPIKE <= FAINT_ALL) {+ cutSet.add(i);+ }+ }+ const cuts = [...cutSet].sort((a, b) => a - b);++ // The changes: fine spikes away from the cuts, runs merged.+ const fineScores = steps.map((s) => s.fine);+ const changes: ShotChange[] = [];+ for (let i = 0; i < steps.length; i++) {+ const s = steps[i];+ if (cutSet.has(i) || !(s.fine >= CHANGE_MIN) || !s.box) {+ continue;+ }+ if (s.fine < SPIKE * neighbourMedian(fineScores, i, cutSet)) {+ continue;+ }+ const last = changes[changes.length - 1];+ if (last && last.frame + last.frames === i) {+ last.frames++;+ last.change = Math.max(last.change, s.fine);+ last.box = unionBox(last.box, s.box);+ continue;+ }+ changes.push({ frame: i, frames: 1, change: s.fine, box: s.box });+ }+ return { cuts, changes };+}++/** The box around two boxes. */+function unionBox(a: ChangeBox, b: ChangeBox): ChangeBox {+ const l = Math.min(a.x - a.w / 2, b.x - b.w / 2);+ const r = Math.max(a.x + a.w / 2, b.x + b.w / 2);+ const t = Math.min(a.y - a.h / 2, b.y - b.h / 2);+ const btm = Math.max(a.y + a.h / 2, b.y + b.h / 2);+ 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[] } {+ 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))));+}diff --git a/site/src/cut/lib/measure/limits.ts b/site/src/cut/lib/measure/limits.tsindex 174fdc06..9d7420a2 100644--- a/site/src/cut/lib/measure/limits.ts+++ b/site/src/cut/lib/measure/limits.ts@@ -7,6 +7,8 @@export const DETECT_CUTS_SPAN_MAX = 120;/** detect_cuts: cuts reported per call. */export const DETECT_CUTS_MAX = 80;+/** detect_cuts: changes inside shots reported per call. */+export const DETECT_CHANGES_MAX = 120;/** sample_color: regions read per call. */export const SAMPLE_COLOR_MAX = 24;/** sample_color: dominant colours per region. */diff --git a/site/src/cut/lib/measure/sourceMeasure.ts b/site/src/cut/lib/measure/sourceMeasure.tsindex 34c0d59b..5c13610d 100644--- a/site/src/cut/lib/measure/sourceMeasure.ts+++ b/site/src/cut/lib/measure/sourceMeasure.ts@@ -9,7 +9,7 @@ import { openMedia, UnreadableMediaError, videoTrackOf, type FrameSize } from ".import { createRasterCanvas, decodeRasterImageUrl } from "../raster";import type { WrappedCanvas } from "mediabunny";import { hexOf, regionColor, parseHex, type PixelRect, type Pixels, type Rgb } from "./color";-import { changePct, gridMeans, pickCuts } from "./cuts";+import { frameStep, gridsOf, pickShotEdges, type FrameGrids, type FrameStep, 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";@@ -22,9 +22,9 @@ export interface FrameBox {h: number;}-/** Every frame of a cut scan is this small: a cut changes the whole picture,- * and 64² holds the 16-grid the scorer reads at four pixels a cell. */-const SCAN_SIZE: FrameSize = { width: 64, height: 64, fit: "fill" };+/** Every frame of a cut scan is this small: 128² holds the 32-grid a word+ * appearing is read on at four pixels a cell, and the 16-grid a cut is. */+const SCAN_SIZE: FrameSize = { width: 128, height: 128, fit: "fill" };/** Long side colours are read at: a 1080p source's own pixels. */const COLOR_LONG_SIDE = 1920;/** Long side elements are tracked at: a pixel is 0.14% of the frame. */@@ -151,6 +151,9 @@ export interface CutScan {fps: number;frames: number;cuts: { t: number; frame: number; change: number }[];+ /** 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 })[];coveredTo: number;truncated: boolean;}@@ -160,7 +163,7 @@ export interface CutScan {* budget, and `coveredTo` says where the next pass picks up. */export async function scanCuts(url: string,- opts: { from: number; to: number; maxCuts: number; budgetMs: number; area?: FrameBox }+ opts: { from: number; to: number; maxCuts: number; maxChanges: number; budgetMs: number; area?: FrameBox }): Promise<CutScan> {return withSourceVideo(url, async (v) => {// Inside a picture box, the frame is read big enough that the box alone@@ -174,16 +177,16 @@ export async function scanCuts(const deadline = Date.now() + opts.budgetMs;const times: number[] = [];const durations: number[] = [];- const scores: number[] = [];- let prev: Float32Array | null = null;+ const steps: FrameStep[] = [];+ 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)) {if (Date.now() > deadline) {outOfTime = true;break;}- const grid = gridMeans(opts.area ? cropPixels(f, toPixels(f, area)) : f);- scores.push(prev ? changePct(prev, grid) : NaN);+ 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 });times.push(f.t);durations.push(f.duration);prev = grid;@@ -191,20 +194,30 @@ 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 picked = pickCuts(scores);- const kept = picked.slice(0, opts.maxCuts);- const capped = picked.length > kept.length;- // A capped pass ends on the frame before the first cut it leaves out, so- // the next pass scores that cut against it.- const coveredTo = capped ? times[picked[kept.length] - 1] : outOfTime ? times[times.length - 1] : opts.to;+ const { cuts: picked, changes: found } = pickShotEdges(steps);++ // 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.+ const firstLeftOut = Math.min(+ picked.length > opts.maxCuts ? picked[opts.maxCuts] : Infinity,+ found.length > opts.maxChanges ? found[opts.maxChanges].frame : Infinity+ );+ const capped = Number.isFinite(firstLeftOut);+ const coveredTo = capped ? times[firstLeftOut - 1] : outOfTime ? times[times.length - 1] : opts.to;+ const frameOf = (i: number) => (fps > 0 ? Math.round((times[i] - v.first) * fps) : i);return {fps,frames: times.length,- cuts: kept.map((i) => ({- t: times[i],- frame: fps > 0 ? Math.round((times[i] - v.first) * fps) : i,- change: Math.round(scores[i]),- })),+ cuts: picked+ .filter((i) => i < firstLeftOut)+ .map((i) => ({+ t: times[i],+ frame: frameOf(i),+ change: Math.round(steps[i].pct),+ })),+ 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 })),coveredTo,truncated: capped || outOfTime,};diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex cc46fd13..560da59a 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -1461,27 +1461,46 @@ function candidateTimes(from: number,to: number,interval: number,- at: number[]+ at: number[],+ shots: number[]): number[] {- const inRange = at.filter((t) => t >= from && t < to).sort((a, b) => a - b);+ const cap = Math.floor(CANDIDATE_CAP * AIMED_SHARE);++ // Measured shots first, each its own decode: a flash card two frames long+ // sits closer to the next than MERGE_EPS, and nothing else would show it.+ const measured = [...new Set(thinAcross(shots.filter((t) => t >= from && t < to), cap).map(round2))];+// More lines than the share allows are thinned across the whole span. Taking// the first of them would aim the head of a densely spoken stretch and leave// its tail sampled thinner than the floor alone would have.- const cap = Math.floor(CANDIDATE_CAP * AIMED_SHARE);- const every = Math.max(1, Math.ceil(inRange.length / cap));+ const lines = thinAcross(at.filter((t) => t >= from && t < to), Math.max(0, cap - measured.length));const aimed: number[] = [];- for (let i = 0; i < inRange.length; i += every) {- const t = inRange[i];- if (aimed.length === 0 || t - aimed[aimed.length - 1] >= MERGE_EPS) aimed.push(round2(t));+ for (const t of lines) {+ if (aimed.length === 0 || t - aimed[aimed.length - 1] >= MERGE_EPS) {+ aimed.push(round2(t));+ }}- const room = Math.max(1, CANDIDATE_CAP - aimed.length);+ const room = Math.max(1, CANDIDATE_CAP - aimed.length - measured.length);const step = Math.max(interval, (to - from) / room);const floor: number[] = [];for (let t = from; t < to && floor.length < room; t += step) floor.push(round2(t));++ // A line or a floor sample crowding a measured shot gives way to it.+ const crowds = (t: number) => measured.some((m) => Math.abs(m - t) < MERGE_EPS);const times: number[] = [];- for (const t of [...aimed, ...floor].sort((a, b) => a - b))+ for (const t of [...aimed, ...floor].filter((t) => !crowds(t)).sort((a, b) => a - b))if (times.length === 0 || t - times[times.length - 1] >= MERGE_EPS) times.push(t);- return times;+ return [...times, ...measured].sort((a, b) => a - b);+}++/** At most `cap` of the ascending times, spread across all of them. */+function thinAcross(times: number[], cap: number): number[] {+ const sorted = [...times].sort((a, b) => a - b);+ if (cap <= 0) {+ return [];+ }+ const every = Math.max(1, Math.ceil(sorted.length / cap));+ return sorted.filter((_, i) => i % every === 0);}/** How much of each kept frame reaches the model, from the tiled thumbnails@@ -1609,6 +1628,10 @@ export async function sampleWatchFrames(* hits — so a source whose audio has already been read is sampled on its* own clock instead of hoping an even sweep lands on each state. */at?: number[];+ /** Moments a frame-by-frame read measured — the middle of each shot+ * detect_cuts found and the frame each change inside a shot settles on.+ * Each gets a decode of its own, however close to the next. */+ shots?: number[];}): Promise<WatchFrames> {const input = openMedia(sourceUrl);@@ -1623,7 +1646,7 @@ export async function sampleWatchFrames(if (!(wanted > from)) throw new Error("from/to describe an empty range.");const to = Math.min(wanted, from + 600); // bound the work per call; callers resume from coveredToconst interval = clamp(opts.interval ?? 1, 0.5, 30);- const times = candidateTimes(from, to, interval, opts.at ?? []);+ const times = candidateTimes(from, to, interval, opts.at ?? [], opts.shots ?? []);const geom = watchGeometry(opts.detail);const srcW = await track.getDisplayWidth();diff --git a/site/src/cut/lib/pictureTools.test.ts b/site/src/cut/lib/pictureTools.test.tsindex 9e958474..3a31bdd1 100644--- a/site/src/cut/lib/pictureTools.test.ts+++ b/site/src/cut/lib/pictureTools.test.ts@@ -150,6 +150,19 @@ test("detect_cuts finds the picture first, then a card that changes a small sharexpect(whole.picture).toBeUndefined();});+test("detect_cuts reports a card landing inside a shot as a change, with its box", async () => {+ // Over the whole recorded frame the card is no cut; it is still the moment+ // a card lands, and where it sits.+ const whole = (await runAiTool("detect_cuts", { asset_id: "ref", picture: "full" })) as {+ changes: { frame: number; frames: number; box: Box }[];+ };+ expect(whole.changes.map((c) => c.frame)).toEqual([90]);+ expect(whole.changes[0].frames).toBe(1);+ expect(whole.changes[0].box.x).toBeCloseTo(0.5, 1);+ expect(whole.changes[0].box.y).toBeCloseTo(0.5, 1);+ expect(whole.changes[0].box.w).toBeCloseTo(CARD.x1 - CARD.x0, 1);+});+test("sample_color reads in the picture's fractions once a picture is stored", async () => {await runAiTool("find_picture", { asset_id: "ref" });const out = (await runAiTool("sample_color", {diff --git a/site/src/cut/lib/sampleWatchFrames.test.ts b/site/src/cut/lib/sampleWatchFrames.test.tsindex a5af9871..e055ba15 100644--- a/site/src/cut/lib/sampleWatchFrames.test.ts+++ b/site/src/cut/lib/sampleWatchFrames.test.ts@@ -76,6 +76,21 @@ test("a source's own lines aim the candidates", async () => {expect(result.candidates).toBe(8);});+test("every shot detect_cuts measured gets a decode of its own, however short", async () => {+ // A strobe of flat cards a few frames each: the moments sit closer together+ // than two speech lines may, and each one is a card nothing else shows. A+ // floor sample that would crowd one of them gives way to it.+ const run = fixture();+ const shots = [1.5, 1.583, 1.633, 1.7, 1.767, 2.41];+ await sampleWatchFrames("fixture.mp4", {+ from: 0, to: 4, interval: 0.5, metadataOnly: true, shots,+ });+ const asked = run.asked();+ for (const t of shots) expect(asked.includes(Math.round(t * 100) / 100)).toBe(true);+ expect(asked.includes(2.5)).toBe(false);+ expect(asked.includes(3)).toBe(true);+});+test("a densely spoken source is aimed end to end", async () => {// More lines than the budget allows: they thin across the whole span. Taking// the first of them would aim the head and leave the tail sampled thinnerdiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 43d5bdc7..46017d39 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -352,17 +352,17 @@ Cutting speech well: pace is part of the message, and it is set in one place —Someone points at a video — a file they imported, a link you brought in, a clip on their timeline — and asks for one like it. Everything on the screen gets rebuilt out of this editor's own parts: every card of type, every shape, every colour, every move, at the time it happens. The footage inside the shots is the one thing you cannot rebuild, because it is the person's to bring — so each shot stands as a block in the colour the reference has behind it, with nothing written on it.**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. A scan cell is a quarter of the frame's width; a small caption in one is a smudge, and a smudge read as a word is how a card ends up saying something the video never said. 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.+**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 and returns each cut on its frame and the \`shots\` between them with their lengths — run it over the whole source, continuing from \`coveredTo\`. 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.+**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.-**Block out the cuts.** add_clip with \`blocks\` lays the skeleton from detect_cuts' \`shots\` in one call — one block per shot on track 0, flash cuts included (a block can be one frame), each that shot's length, \`color\` what sample_color reads behind it and \`label\` naming what the person drops there. The label rides the timeline chip and the editor state; the frame itself shows the colour alone, so a shot never plays a sentence describing itself. A block is filled by dropping footage on it — it takes the block's place and its length — or with replace_item, so everything you build on top keeps its timing. Cuts timed to a reference are timed to what it sounds like, so that sound belongs on the soundtrack under them: detach_audio with the reference's \`assetId\` puts its whole track there and places none of its picture. 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.+**Lay down the sound, then block out the cuts.** Cuts timed to a reference are timed to its sound: detach_audio with the reference's \`assetId\` puts its whole track on the soundtrack and none of its picture. add_clip with \`blocks\` lays the skeleton from \`shots\` in one call — one block per shot on track 0, 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.-**Rebuild the text as elements.** One add_title per card — the words exactly as they read, size in px at 1080 wide, and x/y the centre of its ink box (track_element, match ink, the text's colour). A run of lines timed one after another is add_text_sequence in one call. Match the case the reference uses, and its colour from sample_color. The face comes off the frame: suggest_font with the card's moment, a region close around its words and the words themselves ranks every face Donkey has and hands back the font, weight, size and tracking to set. Call it once per distinct face — a title that cycles through typefaces is one call per face it shows. A no_match verdict means the reference uses a face Donkey does not bundle: say so, and set the closest one it named. Without a suggestion, size comes off the ink: capitals stand about 0.7 of the size tall, so size is the ink height in px at 1080 wide ÷ 0.7 (h × 1920 ÷ 0.7 on 9:16). A cycle whose faces change on the music's beats times itself with set_overlay_animation font_cycle_beats on the soundtrack clip after detect_beats; one whose changes follow the reference's own rhythm takes font_cycle_switches, the timeline seconds detect_cuts reads each change at.+**Rebuild the text as elements.** One title per card, a stretch of cards per add_title call — the words exactly as they read, size in px at 1080 wide, and x/y the centre of its ink box (track_element, match ink, the text's colour). A run of lines timed one after another is add_text_sequence in one call. Match the case the reference uses, and its colour from sample_color. The face comes off the frame: suggest_font with the card's moment, a region close around its words and the words themselves ranks every face Donkey has and hands back the font, weight, size and tracking to set. Call it once per distinct face — a title that cycles through typefaces is one call per face it shows. A no_match verdict means the reference uses a face Donkey does not bundle: say so, and set the closest one it named. Without a suggestion, size comes off the ink: capitals stand about 0.7 of the size tall, so size is the ink height in px at 1080 wide ÷ 0.7 (h × 1920 ÷ 0.7 on 9:16). A cycle whose faces change on the music's beats times itself with set_overlay_animation font_cycle_beats on the soundtrack clip after detect_beats; one whose changes follow the reference's own rhythm takes font_cycle_switches, the timeline seconds detect_cuts reads each change at.-**Then the motion.** set_overlay_keyframes gives each card its own pose track — where it sits, at what scale, at what second. track_element over a move hands you the keys: each move's from/to, start/end and ease, with scale as w over the resting w. set_overlay_animation composes on top for the entrance, the exit, a loop, and what a line does while it holds; 0.3-0.6s reads as an entrance, and a per-letter style is what makes a card read as typed. add_shape is the rest of the graphics: bars, cards, rules, a block of color behind a line.+**Then the motion.** set_overlay_keyframes gives each card its own pose track — where it sits, at what scale, at what second. track_element over a move hands you the keys: each move's from/to, start/end and ease, with scale as w over the resting w. set_overlay_animation composes on top for the entrance, the exit, a loop, and what a line does while it holds; 0.3-0.6s reads as an entrance, and a per-letter style is what makes a card read as typed. add_shape, a stretch per call, is the rest of the graphics: bars, cards, rules, a block of color behind a line.-**Look at what you made.** Watching told you what the reference does; it does not tell you whether what you made does it too, and a build that reads right from your own notes is still a guess until you measure it. compare_to_source does: mode sweep scores every frame of the cut against the source — 0 is the same picture, under ${SWEEP_TARGET} reads as one — and names the worst stretches with a grid of where each differs; mode moments shows those peaks beside the source's frames. Sweep as you build, since an error in the first card is in every card after it: look at the worst stretches, fix what differs, sweep again, and stop when the median is under ${SWEEP_TARGET} and no stretch stands out. A \`shift\` means the right thing lands early or late by that much. Read each picture for colour, the words and their face, where a thing sits, its size, and how far along a move is; a title the same colour as the block behind it reads as correct in the document and shows up here. A block keeps its footage's difference, so judge a shot by the cells over what you built.+**Look at what you made.** A build that reads right from your own notes is still a guess until you measure it. compare_to_source does: mode sweep scores every frame of the cut against the source — 0 is the same picture, under ${SWEEP_TARGET} reads as one — and names the worst stretches with a grid of where each differs; mode moments shows those peaks beside the source's frames. Sweep as you build, since an error in the first card is in every card after it: look at the worst stretches, fix what differs, sweep again, and stop when the median is under ${SWEEP_TARGET} and no stretch stands out. A \`shift\` means the right thing lands early or late by that much. Read each picture for colour, the words and their face, where a thing sits, its size, and how far along a move is; a title the same colour as the block behind it reads as correct in the document and shows up here. A block keeps its footage's difference, so judge a shot by the cells over what you built.**Say what plays.** Close by naming what fills the shots, and what you checked. A shell gets what to drop in: how many shots, how long each one runs, and that the titles and timing are built around them.`,