Skip to content

Open source CapCut alternative.

TypeScript

fix(cut): land millisecond tool times on their frame [rebuild]

David Leb6e165f42191
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 771e3f74..e1dbc651 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -363,15 +363,59 @@ import { soundSourceOf, SPLIT_EDIT_MAX_S } from "./soundSource";
import { bindRecording, unbindRecording } from "./soundBind";
const round2 = (n: number) => Math.round(n * 100) / 100;
-/** A time written out to the microsecond — 1.016667 for 61/60 — sits a hair
- * past its frame, so that frame still shows what came before. One within 10 µs
- * of a frame at a common rate (the 1/600 s grid holds 24, 25, 30, 50 and 60
- * fps) lands on it exactly. */
+/** A time written out to the millisecond — 0.367 for 22/60, as the tools
+ * report it — sits a hair past its frame, so that frame still shows what came
+ * before. One within half a millisecond of a frame at a common rate (the
+ * 1/600 s grid holds 24, 25, 30, 50 and 60 fps) lands on it exactly. Grid
+ * points are 1.67 ms apart, so no time is in reach of two, and a frame
+ * written to the millisecond is at most a third of one off. */
const FRAME_GRID = 600;
+const FRAME_SNAP_S = 0.0005;
const onFrame = (t: number) => {
const n = Math.round(t * FRAME_GRID);
- return Math.abs(t * FRAME_GRID - n) < FRAME_GRID * 1e-5 ? n / FRAME_GRID : t;
+ return Math.abs(t - n / FRAME_GRID) < FRAME_SNAP_S ? n / FRAME_GRID : t;
};
+
+/** Tool fields that hold seconds: a timeline or source time, or a length. */
+const SECONDS_FIELDS: ReadonlySet<string> = new Set([
+ "start",
+ "end",
+ "in",
+ "out",
+ "at",
+ "t",
+ "times",
+ "seconds",
+ "from",
+ "to",
+ "source",
+ "delta",
+ "hold",
+ "duration",
+ "lead",
+ "tail",
+ "hit_at",
+ "font_cycle_at",
+ "font_cycle_seconds",
+ "font_cycle_switches",
+]);
+
+/** A tool's input with every seconds field on the frame it names, walked
+ * through lists and nested records (keys, lines, spans, blocks), so every
+ * tool takes a time the way the tools report one. Example: { start: 0.367 }
+ * → { start: 22/60 }. */
+function snapSeconds(value: unknown, field?: string): unknown {
+ if (typeof value === "number") {
+ return field !== undefined && SECONDS_FIELDS.has(field) && Number.isFinite(value) ? onFrame(value) : value;
+ }
+ if (Array.isArray(value)) {
+ return value.map((v) => snapSeconds(v, field));
+ }
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, snapSeconds(v, k)]));
+ }
+ return value;
+}
/** A rotation input in degrees, kept to tenths: a screen in the shot can lean
* a fraction of a degree, and whatever is fitted onto it has to match. */
const degInput = (n: number) => Math.round(clamp(n, -180, 180) * 10) / 10;
@@ -6222,7 +6266,8 @@ function droppedByConnection(err: unknown): boolean {
return isOffline() && !(err instanceof ToolError && err.cause === undefined);
}
-async function dispatchTool(s: Editor, name: string, input: Record<string, unknown>, operation?: ProjectOperation): Promise<unknown> {
+async function dispatchTool(s: Editor, name: string, raw: Record<string, unknown>, operation?: ProjectOperation): Promise<unknown> {
+ const input = snapSeconds(raw) as Record<string, unknown>;
// "update_title" stays as an alias so older threads keep working.
const key = name === "update_title" ? "update_overlay" : name;
const run = (toolRuns as Partial<Record<string, ToolRun>>)[key];
diff --git a/site/src/cut/lib/elementTimes.test.ts b/site/src/cut/lib/elementTimes.test.ts
index 471fb17c..ba19932e 100644
--- a/site/src/cut/lib/elementTimes.test.ts
+++ b/site/src/cut/lib/elementTimes.test.ts
@@ -40,7 +40,7 @@ test("a card shorter than 0.2 s retimes against its neighbour without sliding",
const out = (await runAiTool("update_overlay", { id: a.id, start: 0.316667, end: 0.4 })) as { start: number; end: number };
expect([out.start, out.end]).toEqual([0.317, 0.4]);
const after = useEditor.getState().overlays.find((o) => o.id === b.id)!;
- expect([after.start, after.end]).toEqual([0.4, 0.567]);
+ expect([after.start, after.end]).toEqual([24 / 60, 34 / 60]);
});
test("key times read back to the millisecond", async () => {
@@ -70,16 +70,19 @@ test("an undo inside a chat turn steps back one edit at a time, never into the t
s().endHistoryBatch();
});
-test("a time written to the microsecond lands on its frame", async () => {
+test("a time written to the microsecond or the millisecond lands on its frame", async () => {
// 1.016667 is 61/60 to six places, but sits a hair past frame 61, so that
// frame would still show what came before.
const { id } = (await runAiTool("add_shape", { shape: "rect", start: 1.016667, end: 1.233333, lane: 1 })) as { id: string };
const o = () => useEditor.getState().overlays.find((x) => x.id === id)!;
expect(o().start).toBe(61 / 60);
expect(o().end).toBe(74 / 60);
- // A time meant to the millisecond stays as written.
- await runAiTool("update_overlay", { id, start: 1.017, end: 1.234 });
- expect([o().start, o().end]).toEqual([1.017, 1.234]);
+ // So does one written to the millisecond, the way the tools report it;
+ // a time more than half a millisecond off every frame stays as written.
+ await runAiTool("update_overlay", { id, start: 1.017, end: 1.233 });
+ expect([o().start, o().end]).toEqual([61 / 60, 74 / 60]);
+ await runAiTool("update_overlay", { id, start: 1.0177, end: 1.2342 });
+ expect([o().start, o().end]).toEqual([1.0177, 1.2342]);
const { id: title } = (await runAiTool("add_title", { text: "GO", start: 2, end: 3, lane: 2 })) as { id: string };
await runAiTool("set_overlay_animation", { id: title, font_cycle: [{ font: "impact", hold: 0.216667 }, { font: "serif" }], font_cycle_at: 0.083333, font_cycle_seconds: 0.5 });
const fonts = (useEditor.getState().overlays.find((x) => x.id === title) as { anim?: { fonts?: { at: number; faces: { hold?: number }[] } } }).anim?.fonts;
diff --git a/site/src/cut/lib/frameSnap.test.ts b/site/src/cut/lib/frameSnap.test.ts
new file mode 100644
index 00000000..f3c992ac
--- /dev/null
+++ b/site/src/cut/lib/frameSnap.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, expect, test } from "bun:test";
+import { runAiTool } from "./aiTools";
+import { useEditor } from "./store";
+
+// The tools report times to the millisecond — frame 22 at 60 fps is 0.367 —
+// and the model writes them back as it read them. A time that sits a third of
+// a millisecond past its frame shows the frame before it, so every time a tool
+// takes lands on the frame it names: exactly k/fps, the time a render asks for.
+
+/** Frame k at `fps`, as the render's clock asks for it. */
+const frame = (k: number, fps = 60) => k / fps;
+/** A frame's time as a tool reports it: to the millisecond. */
+const ms = (t: number) => Math.round(t * 1000) / 1000;
+
+beforeEach(() => {
+ useEditor.setState({
+ clips: [],
+ overlays: [],
+ transitions: [],
+ audioClips: [],
+ assets: [
+ { id: "v", fileName: "v.mp4", name: "Footage", type: "video", duration: 60, url: "" },
+ { id: "song", fileName: "song.mp3", name: "Song", type: "audio", duration: 60, url: "" },
+ ],
+ });
+});
+
+test("an element written to the millisecond starts and ends on its frames", async () => {
+ await runAiTool("add_shape", { shape: "rect", start: ms(frame(22)), end: ms(frame(83)) });
+ const o = useEditor.getState().overlays[0]!;
+ expect(o.start).toBe(frame(22));
+ expect(o.end).toBe(frame(83));
+});
+
+test("a clip's start, in and out written to the millisecond land on their frames", async () => {
+ await runAiTool("add_clip", { asset_id: "v", start: 0 });
+ const id = useEditor.getState().clips[0]!.id;
+ await runAiTool("trim_clip", { clipId: id, in: ms(frame(7)), out: ms(frame(301)) });
+ await runAiTool("place_clip", { clipId: id, start: ms(frame(41)) });
+ const c = useEditor.getState().clips[0]!;
+ expect(c.in).toBe(frame(7));
+ expect(c.out).toBe(frame(301));
+ expect(c.start).toBe(frame(41));
+});
+
+test("a sound's start written to the millisecond lands on its frame", async () => {
+ await runAiTool("add_clip", { asset_id: "song", start: ms(frame(13)) });
+ const a = useEditor.getState().audioClips[0]!;
+ expect(a.start).toBe(frame(13));
+ await runAiTool("update_audio", { id: a.id, start: ms(frame(97)) });
+ expect(useEditor.getState().audioClips[0]!.start).toBe(frame(97));
+});
+
+test("a split written to the millisecond cuts on its frame", async () => {
+ await runAiTool("add_clip", { asset_id: "v", start: 0 });
+ await runAiTool("split_at", { t: ms(frame(22)) });
+ const starts = useEditor.getState().clips.map((c) => c.start).sort((a, b) => a - b);
+ expect(starts).toEqual([0, frame(22)]);
+});
+
+test("keyframes written to the millisecond sit on their frames", async () => {
+ await runAiTool("add_shape", { shape: "rect", start: 0, end: 4 });
+ const id = useEditor.getState().overlays[0]!.id;
+ await runAiTool("set_overlay_keyframes", { id, keys: [{ t: ms(frame(1)), x: 0.2 }, { t: ms(frame(23)), x: 0.8 }] });
+ const keys = useEditor.getState().overlays[0]!.kf ?? [];
+ expect(keys.map((k) => k.t)).toEqual([frame(1), frame(23)]);
+});
+
+/** Where a shape written to start at `t` starts. */
+async function shapeStart(t: number): Promise<number> {
+ useEditor.setState({ overlays: [] });
+ const { id } = (await runAiTool("add_shape", { shape: "rect", start: t, end: 5 })) as { id: string };
+ return useEditor.getState().overlays.find((o) => o.id === id)!.start;
+}
+
+test("the snap never moves a time between frames at 24, 25, 30, 50 or 60 fps", async () => {
+ // Every frame of every common rate, written to the millisecond, lands on
+ // itself; times that are not on a frame stay where they were written.
+ for (const fps of [24, 25, 30, 50, 60]) {
+ for (let k = 0; k < fps * 3; k++) {
+ expect(await shapeStart(ms(frame(k, fps)))).toBe(frame(k, fps));
+ }
+ }
+ for (const t of [0.3672, 1.2345, 2.0009]) {
+ expect(await shapeStart(t)).toBe(t);
+ }
+});
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 52c7917c..d97b6168 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -354,7 +354,7 @@ Someone points at a video — a file they imported, a link you brought in, a cli
**Clipping a long source.** A talk, an interview or a stream is mostly material that only makes sense in place. find_highlights ranks its stretches from the transcript, so an hour is read for its handful of moments without watching all of it; watch_video the spans it returns before committing, since the ranking never saw the picture. add_clip \`spans\` lays a pick down — several stretches of one source as one run of clips, the material between them left out — and a two-span result is one clip whose halves were never next to each other.
**Watch the whole thing first.** Every decision below comes off the record, so the record has to be complete: watch from 0 and keep going until \`unwatchedSeconds\` is 0, writing each pass into note_source before the next one. Anything over a couple of minutes gets a coarse pass end to end first (\`interval_seconds\` 15-30) to learn its shape, then a dense pass (0.5) over the stretches that carry text or cut fast. Read every card word for word — its text, its face, where it sits in the frame, when it comes and goes — because a turn later the sheets are gone and the notes are all you have. Reading type is what \`detail\` is for: the dense pass over a stretch carrying words runs at \`detail\` read, and a face or treatment you are about to name runs at original, where the frame arrives at the source's own resolution. 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.
-**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\`. 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 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.
**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, 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.