Skip to content

Open source CapCut alternative.

TypeScript

fix(site): place a matched title where its ink lands [rebuild]

David Leefb271944cff
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index 177ceeab..213dffd5 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -304,7 +304,7 @@ export const AI_PANEL_TOOLS = [
{
name: "suggest_font",
description:
- "Name the face a reference's type is set in: reads the source's frame at t, lifts the ink inside region off its ground, and ranks every face Donkey can set a title in — each bundled family at each bundled weight, the system set and the account's own fonts — by how closely its glyphs for the same words match, tracking solved so each runs as wide as the reference. Call it for each distinct face while rebuilding a reference's titles, so the font, weight, size and tracking come from the frame. Pass the words exactly as they read, case and line breaks included, and a region close around them read off watch_video at detail original. Returns the best faces with score (0..1), size (px at the 1080 short side, for the same ink height) and tracking (em), plus the ink's box as centre and size in frame fractions — its x/y are add_title's. Type set at an angle — a column word reading bottom to top — is read upright: pass `rotation`, the angle add_title would set it at (-90 reads bottom to top, 90 top to bottom), with a region around the word as it stands; one line of words in a region taller than wide is tried both ways round without it, and `rotation` comes back with the result to set on the title. verdict no_match means nothing bundled is close: the reference uses a face Donkey does not bundle, so say so and name the stand-in you use, of its kind — `kinds` lists every face by kind (serif, sans, script, display, mono), each as its id and a few words on its look. `inkPx` is how tall a line of the ink runs in the source; under 24 the result is `small`: the glyphs have blurred into their proportions, the ranking cannot tell a serif from a condensed sans, so name the face by eye at detail original and take the closest of its kind from `kinds`.",
+ "Name the face a reference's type is set in: reads the source's frame at t, lifts the ink inside region off its ground, and ranks every face Donkey can set a title in — each bundled family at each bundled weight, the system set and the account's own fonts — by how closely its glyphs for the same words match, tracking solved so each runs as wide as the reference. Call it for each distinct face while rebuilding a reference's titles, so the font, weight, size and tracking come from the frame. Pass the words exactly as they read, case and line breaks included, and a region close around them read off watch_video at detail original. Returns the best faces with score (0..1), size (px at the 1080 short side, for the same ink height) and tracking (em), and x/y, where that face's title sits (add_title's x/y) for its ink to land on the reference's — a title is set from the middle of its line, so its ink centre is off it. `ink` is the ink's own box, centre and size in frame fractions. Type set at an angle — a column word reading bottom to top — is read upright: pass `rotation`, the angle add_title would set it at (-90 reads bottom to top, 90 top to bottom), with a region around the word as it stands; one line of words in a region taller than wide is tried both ways round without it, and `rotation` comes back with the result to set on the title. verdict no_match means nothing bundled is close: the reference uses a face Donkey does not bundle, so say so and name the stand-in you use, of its kind — `kinds` lists every face by kind (serif, sans, script, display, mono), each as its id and a few words on its look. `inkPx` is how tall a line of the ink runs in the source; under 24 the result is `small`: the glyphs have blurred into their proportions, the ranking cannot tell a serif from a condensed sans, so name the face by eye at detail original and take the closest of its kind from `kinds`.",
inputSchema: obj(
{
asset_id: str("Project asset id of the reference (video or image)"),
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 67f5a750..3e07e266 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -238,7 +238,7 @@ import { mixSpecFor, renderProjectFrame } from "./exportRender";
import { renderMix } from "./audioMix";
import { measureLoudnessSliced, roundedLoudness, type LoudnessMeasure } from "./loudness";
import { frameAt, framesAt, readMediaFileSize } from "./mediaRead";
-import { bundledFaces, inkMaskOf, rankFaces } from "./fontMatch";
+import { bundledFaces, inkMaskOf, inkOffset, rankFaces } from "./fontMatch";
import { fontKind, fontLook } from "./fontCatalog";
import { CUT_FONT_MATCH } from "./fontMatchSettings";
import { COMPARE_MODES, MAX_COMPARE, SWEEP_TARGET } from "./frameDiff";
@@ -2350,18 +2350,35 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const inkH = Math.abs(inkBox.w * Math.sin(a)) + Math.abs(inkBox.h * Math.cos(a));
const count = Math.round(clamp(isNum(input.count) ? input.count : FONT_SUGGESTIONS, 1, FONT_SUGGESTIONS_MAX));
const labels = new Map(allFonts().map((f) => [f.id, f.label]));
- const matches = ranked.slice(0, count).map((m) => ({
- font: m.font,
- label: labels.get(m.font) ?? m.font,
- weight: m.weight,
- ...(m.italic ? { italic: true } : {}),
- score: m.score,
- size: m.typePx > 0 ? Math.round((m.typePx / k / Math.min(fw * area.w, fh * area.h)) * DESIGN_SHORT_SIDE) : null,
- tracking: m.tracking,
- }));
+ const round3 = (v: number) => Math.round(v * 1000) / 1000;
+ const ink = {
+ x: ((x0 + inkCx / k) / fw - left) / area.w,
+ y: ((y0 + inkCy / k) / fh - top) / area.h,
+ };
+ // A title is set from the middle of its line, not of its ink, so each
+ // face says where its title sits for its ink to land on the reference's:
+ // the ink's centre less that face's offset, turned as the title is.
+ const frame = frameOf(s.aspect);
+ const matches = await Promise.all(
+ ranked.slice(0, count).map(async (m) => {
+ const size = m.typePx > 0 ? Math.round((m.typePx / k / Math.min(fw * area.w, fh * area.h)) * DESIGN_SHORT_SIDE) : null;
+ const off = size ? await inkOffset(m, size, m.tracking, text, fontStack) : null;
+ const [ox, oy] = off ? [off.dx * Math.cos(a) - off.dy * Math.sin(a), off.dx * Math.sin(a) + off.dy * Math.cos(a)] : [0, 0];
+ return {
+ font: m.font,
+ label: labels.get(m.font) ?? m.font,
+ weight: m.weight,
+ ...(m.italic ? { italic: true } : {}),
+ score: m.score,
+ size,
+ tracking: m.tracking,
+ x: round3(ink.x - ox / frame.w),
+ y: round3(ink.y - oy / frame.h),
+ };
+ })
+ );
const good = CUT_FONT_MATCH.goodScore;
const best = matches[0];
- const round3 = (v: number) => Math.round(v * 1000) / 1000;
// How tall a line of the ink runs in the source's own pixels.
const inkPx = Math.round(inkBox.h / k / lines);
const small = inkPx < FONT_SMALL_INK_PX;
@@ -2374,8 +2391,8 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
t: round2(t),
text,
ink: {
- x: round3(((x0 + inkCx / k) / fw - left) / area.w),
- y: round3(((y0 + inkCy / k) / fh - top) / area.h),
+ x: round3(ink.x),
+ y: round3(ink.y),
w: round3(inkW / k / fw / area.w),
h: round3(inkH / k / fh / area.h),
},
diff --git a/site/src/cut/lib/fontMatch.ts b/site/src/cut/lib/fontMatch.ts
index 44ab2e9c..3a01a752 100644
--- a/site/src/cut/lib/fontMatch.ts
+++ b/site/src/cut/lib/fontMatch.ts
@@ -11,7 +11,7 @@
* rank alike.
*/
-import { ensureFontLoaded, LETTER_SPACING_MAX, LETTER_SPACING_MIN, TEXT_WEIGHTS, type TextWeight } from "@donkeycut/effects-kit";
+import { ensureFontLoaded, LETTER_SPACING_MAX, LETTER_SPACING_MIN, LINE_HEIGHT, TEXT_WEIGHTS, type TextWeight } from "@donkeycut/effects-kit";
import { GOOGLE_FONTS } from "./fontCatalog";
import { createRasterCanvas, type RasterSurface } from "./raster";
import { allFonts, FONTS, hasFont } from "./types";
@@ -164,6 +164,44 @@ export async function rankFaces(
return ranked.sort((a, b) => b.score - a.score);
}
+/** How far a title's ink centre sits from the point it is set at, px, the
+ * type upright: each line centred on x and stacked about y on the middle
+ * baseline, as the kit draws it. Caps stand above that baseline, and a
+ * browser counts tracking after the last letter, so the ink is off the
+ * point; a title set at the reference ink's centre less this lands on it. */
+export async function inkOffset(
+ face: TitleFace,
+ px: number,
+ tracking: number,
+ text: string,
+ fontStack: (font: string) => string
+): Promise<{ dx: number; dy: number } | null> {
+ const lines = text.split("\n");
+ const css = `${face.italic ? "italic " : ""}${face.weight} ${px}px ${fontStack(face.font)}`;
+ await ensureFontLoaded(css, text);
+ const lineH = px * LINE_HEIGHT;
+ const w = Math.ceil(px * (Math.max(...lines.map((l) => [...l].length)) * (1.4 + Math.max(0, tracking)) + 2));
+ const h = Math.ceil(lineH * lines.length + px * 2);
+ const canvas = createRasterCanvas(w, h);
+ try {
+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;
+ if (!ctx) return null;
+ ctx.font = css;
+ if ("letterSpacing" in ctx) ctx.letterSpacing = `${tracking * px}px`;
+ ctx.fillStyle = "#ffffff";
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ lines.forEach((line, i) => ctx.fillText(line, w / 2, h / 2 - (lineH * lines.length) / 2 + lineH * (i + 0.5)));
+ const data = ctx.getImageData(0, 0, w, h).data;
+ const ink = new Uint8Array(w * h);
+ for (let i = 0; i < ink.length; i++) ink[i] = data[i * 4 + 3] > 127 ? 1 : 0;
+ const box = inkBoxOf(ink, w, h, { x: 0, y: 0, w, h });
+ return box ? { dx: box.x + box.w / 2 - w / 2, dy: box.y + box.h / 2 - h / 2 } : null;
+ } finally {
+ canvas.width = 0;
+ }
+}
+
/** One line set in one face against one reference line: tracking solved
* from the width its ink runs at tracking 0. */
function fitLine(
diff --git a/site/src/cut/lib/suggestFontTool.test.ts b/site/src/cut/lib/suggestFontTool.test.ts
index 40ab6589..290146ff 100644
--- a/site/src/cut/lib/suggestFontTool.test.ts
+++ b/site/src/cut/lib/suggestFontTool.test.ts
@@ -147,6 +147,22 @@ test("a word set sideways is read upright, and the rotation that sets it comes b
expect(told.matches[0]).toMatchObject({ font: "oswald", weight: 700 });
});
+test("each face says where its title sits so its ink lands on the reference's", async () => {
+ // A title's x/y is where it is set from, the middle of its line, not the
+ // middle of its ink: caps stand above it, and turned they stand beside it.
+ type Placed = Out & { matches: { x: number; y: number }[] };
+ shows = { text: "PLEASE", css: '700 120px "Oswald"', rotate: -90, at: [192, 540] };
+ const turned = (await runAiTool("suggest_font", { asset_id: "ref", t: 3, region: { x: 0.1, y: 0.5, w: 0.12, h: 0.7 }, text: "PLEASE" })) as Placed;
+ expect(Math.abs(turned.ink.x - 0.1)).toBeGreaterThan(0.002);
+ expect(Math.abs(turned.matches[0].x - 0.1)).toBeLessThan(0.002);
+ expect(Math.abs(turned.matches[0].y - 0.5)).toBeLessThan(0.003);
+
+ shows = { text: "TRAVEL DESTINATION", css: '700 72px "Oswald"', at: [800, 300] };
+ const upright = (await runAiTool("suggest_font", { asset_id: "ref", t: 3, region: { x: 0.42, y: 0.28, w: 0.6, h: 0.2 }, text: "TRAVEL DESTINATION" })) as Placed;
+ expect(Math.abs(upright.matches[0].x - 800 / 1920)).toBeLessThan(0.002);
+ expect(Math.abs(upright.matches[0].y - 300 / 1080)).toBeLessThan(0.003);
+});
+
test("type too small to tell faces apart says so and lists the faces by kind", async () => {
// 18px on a 1080 frame: a few pixels of x-height, where glyph overlap
// sees proportions and not the face.
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index bb43f579..7d33997c 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -358,7 +358,7 @@ Someone points at a video — a file they imported, a link you brought in, a cli
**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, each its shot's \`from\` and \`to\` as read so every cut lands on its frame, flash cuts included, \`color\` what sample_color reads behind it and \`label\` naming what the person drops there. The label rides the timeline chip; the frame shows the colour alone. Footage dropped on a block, or replace_item, takes its place and its length, so everything built on top keeps its timing. When the ask is the reference's own picture playing, add_clip \`spans\` lays its shots down instead, one span per shot at those same times.
-**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.
+**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 where suggest_font sets its face — a title is set from the middle of its line, so the centre of its ink box (track_element, match ink, the text's colour) sits off it by the face's own offset. 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, tracking and x/y 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, a stretch per call, is the rest of the graphics: bars, cards, rules, a block of color behind a line.