Open source CapCut alternative.
TypeScript
feat(site): align_to_audio re-times text onto the speech in the mix [rebuild]
David Le73438f666929
diff --git a/evals/cut-sync.latest-report.json b/evals/cut-sync.latest-report.jsonnew file mode 100644index 00000000..0c7a4b28--- /dev/null+++ b/evals/cut-sync.latest-report.json@@ -0,0 +1,221 @@+{+ "cases": [+ {+ "name": "captions/lead-in",+ "what": "The silence before each sentence billed to its first word — the on-device transcriber's habit.",+ "evidence": true,+ "before": {+ "lines": 7,+ "medianStart": 0.004,+ "p90Start": 0.9,+ "worstStart": 0.9,+ "within100ms": 0.571,+ "within250ms": 0.571+ },+ "after": {+ "lines": 7,+ "medianStart": 0.001,+ "p90Start": 0.004,+ "worstStart": 0.004,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.1,+ "p90Start": 0.15,+ "within250ms": 1+ },+ "breaches": []+ },+ {+ "name": "captions/lag",+ "what": "Every cue a quarter second late; the shape is right, the placement is not.",+ "evidence": true,+ "before": {+ "lines": 6,+ "medianStart": 0.251,+ "p90Start": 0.255,+ "worstStart": 0.255,+ "within100ms": 0,+ "within250ms": 0.333+ },+ "after": {+ "lines": 6,+ "medianStart": 0.001,+ "p90Start": 0.005,+ "worstStart": 0.005,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.1,+ "p90Start": 0.15,+ "within250ms": 1+ },+ "breaches": []+ },+ {+ "name": "captions/drift",+ "what": "A clock that slips as the chunk runs on, ending 0.6s out — the hosted transcriber's, unchunked. The tail budget allows one cue: once the slip exceeds the line gap, a caption's true onset sits mid-speech in the previous line's run, which no waveform can testify to. Chunking bounds real drift far under that (cloudTranscribe.ts).",+ "evidence": true,+ "before": {+ "lines": 6,+ "medianStart": 0.305,+ "p90Start": 0.506,+ "worstStart": 0.506,+ "within100ms": 0.167,+ "within250ms": 0.5+ },+ "after": {+ "lines": 6,+ "medianStart": 0.013,+ "p90Start": 0.846,+ "worstStart": 0.846,+ "within100ms": 0.667,+ "within250ms": 0.833+ },+ "budget": {+ "medianStart": 0.12,+ "p90Start": 0.9,+ "within250ms": 0.8+ },+ "breaches": []+ },+ {+ "name": "captions/noisy-room",+ "what": "The same lag over a room 22dB louder — a noise floor close enough to the voice to blur its edges.",+ "evidence": true,+ "before": {+ "lines": 6,+ "medianStart": 0.251,+ "p90Start": 0.255,+ "worstStart": 0.255,+ "within100ms": 0,+ "within250ms": 0.333+ },+ "after": {+ "lines": 6,+ "medianStart": 0.002,+ "p90Start": 0.01,+ "worstStart": 0.01,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.12,+ "p90Start": 0.2,+ "within250ms": 1+ },+ "breaches": []+ },+ {+ "name": "captions/music-bed",+ "what": "A steady bed under the whole cut: the gaps between lines are the only readable quiet.",+ "evidence": true,+ "before": {+ "lines": 6,+ "medianStart": 0.251,+ "p90Start": 0.255,+ "worstStart": 0.255,+ "within100ms": 0,+ "within250ms": 0.333+ },+ "after": {+ "lines": 6,+ "medianStart": 0.001,+ "p90Start": 0.005,+ "worstStart": 0.005,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.15,+ "p90Start": 0.3,+ "within250ms": 0.9+ },+ "breaches": []+ },+ {+ "name": "captions/fast-cadence",+ "what": "Lines a quarter second apart, where a snap that overshoots lands on the wrong line.",+ "evidence": true,+ "before": {+ "lines": 6,+ "medianStart": 0.005,+ "p90Start": 0.4,+ "worstStart": 0.4,+ "within100ms": 0.667,+ "within250ms": 0.667+ },+ "after": {+ "lines": 6,+ "medianStart": 0.003,+ "p90Start": 0.005,+ "worstStart": 0.005,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.12,+ "p90Start": 0.2,+ "within250ms": 1+ },+ "breaches": []+ },+ {+ "name": "lyrics/half-heard",+ "what": "The user's lyrics against a transcript that missed a third of the words and misheard a quarter.",+ "evidence": true,+ "before": {+ "lines": 8,+ "medianStart": 0.193,+ "p90Start": 0.697,+ "worstStart": 0.697,+ "within100ms": 0,+ "within250ms": 0.625+ },+ "after": {+ "lines": 8,+ "medianStart": 0.004,+ "p90Start": 0.006,+ "worstStart": 0.006,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.12,+ "p90Start": 0.25,+ "within250ms": 0.9+ },+ "breaches": []+ },+ {+ "name": "lyrics/mostly-unheard",+ "what": "Singing the recognizer barely follows: two words in three unheard, so most line times are interpolated.",+ "evidence": true,+ "before": {+ "lines": 8,+ "medianStart": 0.296,+ "p90Start": 0.84,+ "worstStart": 0.84,+ "within100ms": 0.125,+ "within250ms": 0.5+ },+ "after": {+ "lines": 8,+ "medianStart": 0.004,+ "p90Start": 0.006,+ "worstStart": 0.006,+ "within100ms": 1,+ "within250ms": 1+ },+ "budget": {+ "medianStart": 0.15,+ "p90Start": 0.35,+ "within250ms": 0.85+ },+ "breaches": []+ }+ ],+ "failed": []+}diff --git a/site/package.json b/site/package.jsonindex d9b5c4bf..2dd6abd7 100644--- a/site/package.json+++ b/site/package.json@@ -28,6 +28,7 @@"test:genvideo": "bun run scripts/genvideo-selftest.ts","eval:genvideo": "bun run scripts/genvideo-eval.ts","eval:cut-perf": "bun run scripts/eval-cut-perf.ts",+ "eval:cut-sync": "bun run scripts/eval-cut-sync.ts","eval:cut-export": "bun run scripts/eval-cut-export.ts"},"dependencies": {diff --git a/site/scripts/eval-cut-sync.ts b/site/scripts/eval-cut-sync.tsnew file mode 100644index 00000000..aa78b14f--- /dev/null+++ b/site/scripts/eval-cut-sync.ts@@ -0,0 +1,413 @@+#!/usr/bin/env bun+/**+ * Caption timing eval: when the words appear, do they appear on the voice?+ *+ * A caption's timing has one truth — the moment the speaker actually says the+ * word — and no eyeball on a preview settles whether a line is 200ms late.+ * So the truth is built rather than measured: a script of lines with exact+ * onsets renders to audio, a transcriber's answer is simulated on top of it+ * with the errors real transcribers make, and the production timing path runs+ * over both. Every number below is |reported − true| in seconds.+ *+ * Two paths, the two ways words get times:+ * captions — a transcript grouped into cues (server/transcribe.ts), then+ * re-timed against the mix (lib/cueSync.ts → lib/cueAlign.ts).+ * lyrics — the user's own text aligned to a degraded transcript+ * (lib/lyricSync.ts), then re-timed the same way. This is the+ * path where half the words are never recognized, so most line+ * times start out interpolated between the ones that were.+ *+ * Each case reports before and after the alignment pass, because the pass is+ * the thing on trial: if `after` is not better than `before`, reading the+ * waveform bought nothing. Budgets are enforced by default — this is a+ * regression guard, and it runs in a couple of seconds with no model, no+ * network, and no credits.+ *+ * npm run eval:cut-sync [--only <case>] [--out path] [--no-enforce] [--verbose]+ */++import { mkdir, writeFile } from "node:fs/promises";+import path from "node:path";+import { syncToSpeech } from "../src/cut/lib/cueSync";+import { syncLines, type TimedWord } from "../src/cut/lib/lyricSync";+import { groupWords } from "../src/cut/server/transcribe";++const SITE = path.resolve(import.meta.dir, "..");+const REPORT = path.resolve(SITE, "..", "evals", "cut-sync.latest-report.json");++const argv = process.argv.slice(2);+const arg = (name: string) => {+ const i = argv.indexOf(name);+ return i >= 0 ? argv[i + 1] : undefined;+};+const ONLY = arg("--only");+const OUT = arg("--out") ?? REPORT;+const ENFORCE = !argv.includes("--no-enforce");+const VERBOSE = argv.includes("--verbose");++const RATE = 16000;++// ── Deterministic noise ─────────────────────────────────────────────────────+// Nothing here may vary run to run: a budget that trips one time in five is+// worse than no budget.+const rng = (seed: number) => () => {+ seed = (seed * 1103515245 + 12345) % 2147483648;+ return seed / 2147483648 - 0.5;+};++// ── The truth ───────────────────────────────────────────────────────────────++interface TrueWord {+ line: number;+ w: string;+ start: number;+ end: number;+}++interface Script {+ words: TrueWord[];+ lines: { text: string; start: number; end: number }[];+ duration: number;+}++const WORDS =+ "the light came down over the harbour and nobody moved a hand until morning broke again on every quiet street we knew".split(+ " "+ );++/**+ * A script of `lines` lines, each a few words long, laid out with real+ * cadence: syllable-length words, a breath between them, a longer beat+ * between lines. `lead` is the silence before anyone speaks.+ */+function script(opts: {+ lines: number;+ wordsPerLine: number;+ wordGap: number;+ lineGap: number;+ lead: number;+ seed: number;+}): Script {+ const rnd = rng(opts.seed);+ const words: TrueWord[] = [];+ const lines: Script["lines"] = [];+ let t = opts.lead;+ for (let li = 0; li < opts.lines; li++) {+ const start = t;+ const text: string[] = [];+ for (let wi = 0; wi < opts.wordsPerLine; wi++) {+ const dur = 0.22 + Math.abs(rnd()) * 0.34;+ const w = WORDS[(li * opts.wordsPerLine + wi) % WORDS.length];+ words.push({ line: li, w, start: t, end: t + dur });+ text.push(w);+ t += dur + (wi + 1 < opts.wordsPerLine ? opts.wordGap : 0);+ }+ lines.push({ text: text.join(" "), start, end: t });+ t += opts.lineGap;+ }+ return { words, lines, duration: t + 1 };+}++/**+ * The script as audio: a burst per word, shaped like a syllable rather than a+ * flat block, over whatever floor the condition asks for. `bed` lays a steady+ * music-like tone under the whole thing — the case where quiet between lines+ * is the only edge the envelope can read.+ */+function render(s: Script, opts: { floorDb: number; bedDb?: number; seed: number }): Float32Array {+ const rnd = rng(opts.seed);+ const out = new Float32Array(Math.ceil(s.duration * RATE));+ const floor = Math.pow(10, opts.floorDb / 20);+ for (let i = 0; i < out.length; i++) out[i] = rnd() * floor;+ if (opts.bedDb !== undefined) {+ const bed = Math.pow(10, opts.bedDb / 20);+ for (let i = 0; i < out.length; i++) out[i] += Math.sin((2 * Math.PI * 110 * i) / RATE) * bed;+ }+ for (const w of s.words) {+ const from = Math.round(w.start * RATE);+ const to = Math.min(out.length, Math.round(w.end * RATE));+ const len = Math.max(1, to - from);+ for (let i = from; i < to; i++) {+ const p = (i - from) / len;+ // Attack, hold, decay — a word does not start and stop square.+ const env = Math.min(1, p / 0.12) * Math.min(1, (1 - p) / 0.2);+ // Two syllables' worth of amplitude wobble inside the word.+ const wobble = 0.7 + 0.3 * Math.sin(p * Math.PI * 4);+ out[i] += rnd() * 0.55 * env * wobble;+ }+ }+ return out;+}++// ── The transcriber's answer ────────────────────────────────────────────────++type Flaw = "lag" | "leadin" | "drift" | "clean";++/**+ * What a recognizer hands back for this audio. Every flaw here is one real+ * transcribers make: a constant lag, the silence before a sentence handed to+ * its first word, and a clock that drifts as a long chunk runs on.+ */+function heard(s: Script, flaw: Flaw): TimedWord[] {+ const out: TimedWord[] = [];+ for (const [i, w] of s.words.entries()) {+ let t0 = w.start;+ let t1 = w.end;+ if (flaw === "lag") {+ t0 += 0.25;+ t1 += 0.25;+ }+ if (flaw === "drift") {+ const k = (i / s.words.length) * 0.6;+ t0 += k;+ t1 += k;+ }+ if (flaw === "leadin" && s.words[i - 1] && s.words[i - 1].line !== w.line) {+ // The pause before the line is billed to the line's first word.+ t0 = s.words[i - 1].end;+ }+ if (flaw === "leadin" && i === 0) t0 = 0;+ out.push({ t0, t1, w: w.w });+ }+ return out;+}++/** A recognizer on singing: words missed outright, words misheard. */+function degrade(words: TimedWord[], opts: { drop: number; wrong: number; seed: number }): TimedWord[] {+ const rnd = rng(opts.seed);+ const out: TimedWord[] = [];+ for (const w of words) {+ const r = Math.abs(rnd()) * 2;+ if (r < opts.drop) continue;+ out.push(r < opts.drop + opts.wrong ? { ...w, w: `${w.w}zz` } : w);+ }+ return out;+}++// ── Scoring ─────────────────────────────────────────────────────────────────++const abs = (n: number) => Math.abs(n);+const round3 = (n: number) => Math.round(n * 1000) / 1000;+const quantile = (xs: number[], q: number) =>+ xs.length === 0 ? 0 : round3([...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor(q * xs.length))]);++interface Score {+ lines: number;+ medianStart: number;+ p90Start: number;+ worstStart: number;+ within100ms: number;+ within250ms: number;+}++function score(got: { start: number }[], truth: { start: number }[]): Score {+ const errs = truth.map((t, i) => (got[i] ? abs(got[i].start - t.start) : Infinity));+ const finite = errs.filter((e) => Number.isFinite(e));+ return {+ lines: truth.length,+ medianStart: quantile(finite, 0.5),+ p90Start: quantile(finite, 0.9),+ worstStart: round3(Math.max(0, ...finite)),+ within100ms: round3(errs.filter((e) => e <= 0.1).length / errs.length),+ within250ms: round3(errs.filter((e) => e <= 0.25).length / errs.length),+ };+}++// ── Cases ───────────────────────────────────────────────────────────────────++interface Case {+ name: string;+ what: string;+ run: () => { before: Score; after: Score; evidence: boolean };+ /** Budgets on the aligned result. A case that breaks one fails the eval. */+ budget: { medianStart: number; p90Start: number; within250ms: number };+}++const clean = { floorDb: -60, seed: 3 };+const noisy = { floorDb: -38, seed: 5 };+const bed = { floorDb: -58, bedDb: -30, seed: 9 };++/** The caption path: a transcript grouped into cues, then aligned. */+function captionCase(+ name: string,+ what: string,+ s: Script,+ audio: Float32Array,+ flaw: Flaw,+ budget: Case["budget"]+): Case {+ return {+ name,+ what,+ budget,+ run: () => {+ // The production grouping decides where the cue boundaries fall — a long+ // line becomes two cues — so the truth for each cue is read off the words+ // it actually carries, not off the line it came from.+ const cues = groupWords(heard(s, flaw).map((w) => ({ t0: w.t0, t1: w.t1, w: w.w })));+ let cursor = 0;+ const truth = cues.map((c) => {+ const count = c.words?.length ?? 1;+ const span = s.words.slice(cursor, cursor + count);+ cursor += count;+ return { start: span[0].start, end: span[span.length - 1].end };+ });+ const report = syncToSpeech(cues, audio, RATE, { reach: 0.6 });+ return {+ before: score(cues, truth),+ after: score(report.items, truth),+ evidence: report.evidence,+ };+ },+ };+}++/** The lyric path: the user's own words against a transcript that heard half+ * of them, then aligned. */+function lyricCase(+ name: string,+ what: string,+ s: Script,+ audio: Float32Array,+ opts: { drop: number; wrong: number },+ budget: Case["budget"]+): Case {+ return {+ name,+ what,+ budget,+ run: () => {+ const transcript = degrade(heard(s, "leadin"), { ...opts, seed: 11 });+ const timed = syncLines(+ s.lines.map((l) => l.text),+ transcript,+ { from: 0, to: s.duration }+ );+ const report = syncToSpeech(timed, audio, RATE, { reach: 0.6 });+ return {+ before: score(timed, s.lines),+ after: score(report.items, s.lines),+ evidence: report.evidence,+ };+ },+ };+}++const talk = script({ lines: 8, wordsPerLine: 5, wordGap: 0.07, lineGap: 0.55, lead: 0.9, seed: 1 });+const fast = script({ lines: 10, wordsPerLine: 4, wordGap: 0.05, lineGap: 0.28, lead: 0.4, seed: 2 });+const song = script({ lines: 8, wordsPerLine: 5, wordGap: 0.09, lineGap: 0.7, lead: 1.4, seed: 4 });++const CASES: Case[] = [+ captionCase(+ "captions/lead-in",+ "The silence before each sentence billed to its first word — the on-device transcriber's habit.",+ talk,+ render(talk, clean),+ "leadin",+ { medianStart: 0.1, p90Start: 0.15, within250ms: 1 }+ ),+ captionCase(+ "captions/lag",+ "Every cue a quarter second late; the shape is right, the placement is not.",+ talk,+ render(talk, clean),+ "lag",+ { medianStart: 0.1, p90Start: 0.15, within250ms: 1 }+ ),+ captionCase(+ "captions/drift",+ "A clock that slips as the chunk runs on, ending 0.6s out — the hosted transcriber's, unchunked. " ++ "The tail budget allows one cue: once the slip exceeds the line gap, a caption's true onset sits " ++ "mid-speech in the previous line's run, which no waveform can testify to. Chunking bounds real " ++ "drift far under that (cloudTranscribe.ts).",+ talk,+ render(talk, clean),+ "drift",+ { medianStart: 0.12, p90Start: 0.9, within250ms: 0.8 }+ ),+ captionCase(+ "captions/noisy-room",+ "The same lag over a room 22dB louder — a noise floor close enough to the voice to blur its edges.",+ talk,+ render(talk, noisy),+ "lag",+ { medianStart: 0.12, p90Start: 0.2, within250ms: 1 }+ ),+ captionCase(+ "captions/music-bed",+ "A steady bed under the whole cut: the gaps between lines are the only readable quiet.",+ talk,+ render(talk, bed),+ "lag",+ { medianStart: 0.15, p90Start: 0.3, within250ms: 0.9 }+ ),+ captionCase(+ "captions/fast-cadence",+ "Lines a quarter second apart, where a snap that overshoots lands on the wrong line.",+ fast,+ render(fast, clean),+ "leadin",+ { medianStart: 0.12, p90Start: 0.2, within250ms: 1 }+ ),+ lyricCase(+ "lyrics/half-heard",+ "The user's lyrics against a transcript that missed a third of the words and misheard a quarter.",+ song,+ render(song, clean),+ { drop: 0.35, wrong: 0.25 },+ { medianStart: 0.12, p90Start: 0.25, within250ms: 0.9 }+ ),+ lyricCase(+ "lyrics/mostly-unheard",+ "Singing the recognizer barely follows: two words in three unheard, so most line times are interpolated.",+ song,+ render(song, clean),+ { drop: 0.68, wrong: 0.2 },+ { medianStart: 0.15, p90Start: 0.35, within250ms: 0.85 }+ ),+];++// ── Run ─────────────────────────────────────────────────────────────────────++const cases = CASES.filter((c) => !ONLY || c.name.includes(ONLY));+if (cases.length === 0) {+ console.error(`No case matches ${ONLY}. Cases: ${CASES.map((c) => c.name).join(", ")}`);+ process.exit(2);+}++const results = cases.map((c) => {+ const { before, after, evidence } = c.run();+ const breaches: string[] = [];+ if (after.medianStart > c.budget.medianStart)+ breaches.push(`median ${after.medianStart}s > ${c.budget.medianStart}s`);+ if (after.p90Start > c.budget.p90Start) breaches.push(`p90 ${after.p90Start}s > ${c.budget.p90Start}s`);+ if (after.within250ms < c.budget.within250ms)+ breaches.push(`within 250ms ${after.within250ms} < ${c.budget.within250ms}`);+ // The pass has to earn its place: aligning must not leave lines worse off+ // than the transcript had them.+ if (after.medianStart > before.medianStart + 0.02)+ breaches.push(`alignment made it worse: ${before.medianStart}s → ${after.medianStart}s`);+ return { name: c.name, what: c.what, evidence, before, after, budget: c.budget, breaches };+});++const failed = results.filter((r) => r.breaches.length > 0);++for (const r of results) {+ const mark = r.breaches.length === 0 ? "ok " : "FAIL";+ console.log(+ `${mark} ${r.name.padEnd(24)} median ${r.before.medianStart.toFixed(3)}s → ${r.after.medianStart.toFixed(3)}s ` ++ `p90 ${r.after.p90Start.toFixed(3)}s within 250ms ${(r.after.within250ms * 100).toFixed(0)}%` ++ (r.evidence ? "" : " (the mix offered no edges)")+ );+ if (VERBOSE) console.log(` ${r.what}`);+ for (const b of r.breaches) console.log(` ✗ ${b}`);+}++await mkdir(path.dirname(OUT), { recursive: true });+await writeFile(+ OUT,+ `${JSON.stringify({ cases: results, failed: failed.map((f) => f.name) }, null, 2)}\n`+);+console.log(`\n${results.length - failed.length}/${results.length} within budget — report at ${OUT}`);++if (failed.length > 0 && ENFORCE) process.exit(1);diff --git a/site/src/cut/components/SubtitlesPanel.tools.ts b/site/src/cut/components/SubtitlesPanel.tools.tsindex 42f482aa..455ac07e 100644--- a/site/src/cut/components/SubtitlesPanel.tools.ts+++ b/site/src/cut/components/SubtitlesPanel.tools.ts@@ -39,7 +39,7 @@ export const SUBTITLES_TOOLS = [{name: "sync_lyrics",description:- "Time a text the user already has — song lyrics, a script, a poem — to the audio in the cut, and put it on a caption track. Transcribes the cut first when the track is empty, then aligns the user's words to the recognized ones and keeps the user's text exactly as written: the recognizer supplies the clock, never the wording, which is what makes it work on singing it half-mishears. Words it missed take interpolated times from the words around them. Pass `look` to dress the track in a text-videos look at the same time (karaoke word highlight included). For lyrics as full-frame cards rather than captions, follow this with add_text_sequence from_captions.",+ "Time a text the user already has — song lyrics, a script, a poem — to the audio in the cut, and put it on a caption track. Transcribes the cut first when the track is empty, then aligns the user's words to the recognized ones and keeps the user's text exactly as written: the recognizer supplies the clock, never the wording, which is what makes it work on singing it half-mishears. Words it missed take interpolated times from the words around them. Pass `look` to dress the track in a text-videos look at the same time (karaoke word highlight included) — only when the user asked for a designed run; without it the captions keep the track's current styling. For lyrics as full-frame cards rather than captions, follow this with add_text_sequence from_captions.",inputSchema: obj({text: str("The lyrics or script, one line per screen (newline separated)"),@@ -47,15 +47,38 @@ export const SUBTITLES_TOOLS = [look: str("Text-videos look id to dress the captions in"),from: num("Ignore audio before this timeline second"),to: num("Ignore audio after this timeline second"),- background: bool("With `look`, also set the project background to its frame color (default true)"),+ background: bool("With `look`, also set the project background to its frame color (default: whatever the look does — the designed looks paint it, plain and over-footage leave it alone)"),},["text"]),},+ {+ name: "align_to_audio",+ description:+ "Re-time captions or a run of text elements onto the speech in the cut's own mix — the waveform, not the transcript. It renders the audible mix, reads a 10ms energy envelope to find where speech actually starts and stops, and moves each edge to the speech edge it belongs to; an edge with no audible boundary near it (mid-sentence, or under a bed of music that never lets up) keeps the time it had. Ids, text, word timings and order all survive, and it is one undo step. This is the answer to \"the subtitles are off\", \"sync the text to the audio\", \"the words land late\" — never retime cue by cue with update_cue guesses, and never re-transcribe (that throws away the user's wording). Follow a lyric sync, a hand-edit, or a run built with add_text_sequence from_captions with it. The result says whether the audio could testify at all: `evidence: false` means the mix offered no readable edges and nothing moved, which is not the same as captions already being in sync.",+ inputSchema: obj({+ target: {+ type: "string",+ enum: ["captions", "elements"],+ description:+ "What to align: captions on a subtitle track (default), or the text elements of a run on a title row.",+ },+ track: num("With target captions: the subtitle track, 0-based (default: the active track)"),+ lane: num("With target elements: the element row to align (default 0)"),+ ids: {+ type: "array",+ items: { type: "string" },+ description: "With target elements: align exactly these elements instead of a whole row.",+ },+ reach: num(+ "How far an edge may travel back to meet a speech edge, seconds (0.1–2, default 0.6). A start also reaches up to 1.5s forward to cross the silence a transcriber hands to a sentence's first word. Widen it for times that are guesses, tighten it when captions are nearly right and should not wander."+ ),+ }),+ },{name: "set_caption_look",description:- "Style the caption track: a text-videos look id in `look` sets everything at once (preset, size, font, karaoke highlight, accent color, frame background), or set the pieces yourself. Karaoke — word_highlight — lights each word as it is spoken or sung, in the preview and the export burn-in; it needs word timings, which transcription and sync_lyrics leave on the cues.",+ "Style the caption track: a text-videos look id in `look` sets everything at once (preset, size, font, karaoke highlight, accent color, frame background), or set the pieces yourself. Restyling captions is a change the user asks for — leave the track as it is when they only asked for the words. Karaoke — word_highlight — lights each word as it is spoken or sung, in the preview and the export burn-in; it needs word timings, which transcription and sync_lyrics leave on the cues.",inputSchema: obj({look: str("Text-videos look id — sets the whole caption look"),style: str("Caption preset: clean, hook, punchy, minimal, editorial, typewriter, block, highlight, bubble, neon"),@@ -66,7 +89,7 @@ export const SUBTITLES_TOOLS = [accent_mode: { type: "string", enum: ["color", "underline", "box"], description: "How the word lights up" },x: num("Caption center x 0..1"),y: num("Caption center y 0..1"),- background: bool("With `look`, also set the project background (default true)"),+ background: bool("With `look`, also set the project background (default: whatever the look does — the designed looks paint it, plain and over-footage leave it alone)"),}),},{diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 3672622d..459ef0c9 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -100,6 +100,7 @@ import {type TextLayout,type TextVariation,} from "./textCompose";+import { partialWrites, syncToSpeech, type SyncReport } from "./cueSync";import { requireTextLook, type TextLook } from "./textLooks";import {MOVE_STRENGTH_MAX,@@ -1619,7 +1620,15 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {to: isNum(input.to) ? input.to : Math.max(projectDuration(st), cues[cues.length - 1]?.end ?? 0),};const timed = syncLines(lines, cueWords(cues), span);- st.setLaneCues(lane, timed);+ // The transcript's clock only covers the words it recognized. Every other+ // line here was interpolated between them, so the run is measured against+ // the mix itself before it is written — the same pass the captions got,+ // reaching wider because these times are guesses.+ const mix = await st.cutMixSamples();+ const report = mix+ ? syncToSpeech(timed, mix.samples, mix.sampleRate, { reach: 0.6 })+ : null;+ st.setLaneCues(lane, report?.evidence ? report.items : timed);if (typeof input.look === "string") {const look = requireTextLook(input.look);st.setSubtitlesView({@@ -1633,14 +1642,140 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {if (paintsFrame(look, input.background)) st.setBackground(look.frame.background);}const heardWords = cueWords(cues).length;+ // What the track now carries, which is what the assistant must reason+ // against: the aligned times when the mix moved them, the transcript's+ // own otherwise.+ const written = report?.evidence ? report.items : timed;return {track: lane,- count: timed.length,- lines: timed.slice(0, 40).map((l) => ({ start: l.start, end: l.end, text: l.text })),- ...(timed.length > 40 ? { linesTruncated: true } : {}),+ count: written.length,+ lines: written.slice(0, 40).map((l) => ({ start: l.start, end: l.end, text: l.text })),+ ...(written.length > 40 ? { linesTruncated: true } : {}),+ aligned: report?.evidence === true,+ ...(report?.evidence ? { movedOntoSpeech: report.moved.length, maxShift: report.maxShift } : {}),note:`Your text is on the track verbatim, timed against ${heardWords} recognized words. ` +- "Words the recognizer missed took interpolated times, so spot-check a line or two with seek + capture_frame and retime with update_cue.",+ (report?.evidence+ ? `${report.moved.length} line(s) then moved onto the speech in the mix itself (farthest ${report.maxShift}s). `+ : "The mix offered no readable speech edges to check them against, so the lines carry the transcript's clock alone. ") ++ "Spot-check a line or two with seek + capture_frame, and retime with update_cue.",+ };+ },++ align_to_audio: async (s, input) => {+ if (!s.projectId) throw new ToolError("No project open.");+ const target = input.target === "elements" ? "elements" : "captions";+ const reach = isNum(input.reach) ? clamp(input.reach, 0.1, 2) : 0.6;+ const only = Array.isArray(input.ids) ? new Set(input.ids.map(String)) : null;+ const mix = await useEditor.getState().cutMixSamples();+ if (!mix)+ throw new ToolError(+ "Nothing audible on the timeline to measure against — the audio or video the words belong to has to be in the cut."+ );++ if (target === "captions") {+ const lane = targetSubtitleTrack(input);+ // The whole track is measured even when only some cues are being+ // written: the pass weighs the transcript against the mix as a whole+ // before it moves anything, and a handful of cues out of a hundred+ // look like a mix about something else.+ const cues = laneCues(useEditor.getState().subtitles, lane);+ if (cues.length === 0)+ throw new ToolError(`Subtitle track ${lane} has no captions to align.`);+ const report = syncToSpeech(cues, mix.samples, mix.sampleRate, { reach });+ // Writing part of an aligned track fits the written cues between the+ // ones left where they were; captions on a track may not overlap.+ const writes = partialWrites(report.items, cues, (c) => !only || only.has(c.id));+ if (report.evidence)+ useEditor.getState().retimeItems({+ cues: writes.map((c) => ({+ id: c.id,+ start: c.start,+ end: c.end,+ ...(c.words ? { words: c.words } : {}),+ })),+ });+ return {+ target,+ track: lane,+ count: cues.length,+ ...syncResult(report, cues, only),+ };+ }++ const overlays = useEditor.getState().overlays;+ const row = isNum(input.lane) ? Math.max(0, Math.round(input.lane)) : 0;+ const picked = only+ ? [...only].map((id) => requireItem(overlays, id, "overlay element"))+ : overlays.filter((o) => (o.lane ?? 0) === row);+ if (picked.length === 0)+ throw new ToolError(`No elements on row ${row} to align — pass ids, or the row the run sits on.`);++ // Rows are measured whole, one at a time. A row's items are what may not+ // overlap each other, and the fit against the mix is read over the whole+ // run rather than the few elements being written.+ const lanes = [...new Set(picked.map((o) => o.lane ?? 0))].sort((a, b) => a - b);+ const writes = new Map<string, { id: string; start: number; end: number }>();+ const partners: { from: { start: number; end: number }; to: { start: number; end: number } }[] = [];+ const reports = lanes.map((lane) => {+ const items = overlays+ .filter((o) => (o.lane ?? 0) === lane)+ .sort((a, b) => a.start - b.start);+ const report = syncToSpeech(+ items.map((o) => ({+ id: o.id,+ text: isTextOverlay(o) ? o.text : o.kind ?? "element",+ start: o.start,+ end: o.end,+ })),+ mix.samples,+ mix.sampleRate,+ { reach }+ );+ if (report.evidence) {+ // Part of a row may be written while the rest stays; each written+ // item is fitted between the neighbours it lands among, since items+ // sharing a row may never overlap.+ const fitted = partialWrites(report.items, items, (next) =>+ picked.some((p) => p.id === next.id)+ );+ for (const next of fitted) {+ const was = items.find((o) => o.id === next.id)!;+ writes.set(next.id, { id: next.id, start: next.start, end: next.end });+ // Only a move that is actually being written can carry a partner+ // with it: a card following a word that stayed put would be the+ // desync this ride-along exists to prevent.+ partners.push({ from: { start: was.start, end: was.end }, to: next });+ }+ }+ return { lane, items, report };+ });++ // A look's color cards sit on the row under its words, one per line and+ // timed to it. They belong to the line, so an element elsewhere holding+ // exactly a moved item's old window rides along — otherwise the words+ // land on the speech and their cards stay behind.+ const EPS = 0.05;+ for (const o of overlays) {+ if (writes.has(o.id) || lanes.includes(o.lane ?? 0)) continue;+ const pair = partners.find(+ (p) => Math.abs(p.from.start - o.start) <= EPS && Math.abs(p.from.end - o.end) <= EPS+ );+ if (pair) writes.set(o.id, { id: o.id, start: pair.to.start, end: pair.to.end });+ }+ if (writes.size > 0) useEditor.getState().retimeItems({ overlays: [...writes.values()] });+ return {+ target,+ lane: lanes[0],+ ...(lanes.length > 1 ? { lanes } : {}),+ count: reports.reduce((n, r) => n + r.items.length, 0),+ ...syncResult(+ mergeReports(reports.map((r) => r.report)),+ reports.flatMap((r) =>+ r.items.map((o) => ({ id: o.id, text: isTextOverlay(o) ? o.text : o.kind ?? "element" }))+ ),+ only+ ),};},@@ -3089,6 +3224,8 @@ export const MEDIA_RUNTIME_TOOLS: ReadonlySet<string> = new Set(["subtitles_generate","captions_generate","subtitles_from_visuals",+ "sync_lyrics",+ "align_to_audio","stock_add",]);@@ -3181,6 +3318,72 @@ function cueWords(cues: { start: number; end: number; text: string; words?: Timeparts.forEach((w, i) => out.push({ w, t0: c.start + step * i, t1: c.start + step * (i + 1) }));}return out;+}++/** An alignment pass as the model reads it. The audio declining to testify is+ * a result of its own, never a silent success: a caller told "0 moved" without+ * `evidence` would report a mix it could not read as captions already in sync. */+function syncResult(+ report: SyncReport<{ id: string; text: string; start: number; end: number }>,+ items: { id: string; text: string }[],+ only: ReadonlySet<string> | null+) {+ if (!report.evidence)+ return {+ evidence: false,+ moved: 0,+ note:+ "The mix has no readable speech edges over these times — digital silence, a bed of music that never lets up, " ++ "or speech that does not line up with them at all. Nothing moved, and nothing was confirmed either: check by ear with listen_audio.",+ };+ const moved = report.moved.filter((m) => !only || only.has(report.items[m.index].id));+ const sizes = moved.map((m) => Math.abs(m.shift)).sort((a, b) => a - b);+ const median = sizes.length > 0 ? sizes[Math.floor(sizes.length / 2)] : 0;+ const worst = sizes.length > 0 ? sizes[sizes.length - 1] : 0;+ return {+ evidence: true,+ moved: moved.length,+ medianShift: median,+ maxShift: worst,+ items: moved.slice(0, 40).map((m) => ({+ id: report.items[m.index].id,+ text: items.find((i) => i.id === report.items[m.index].id)?.text,+ start: m.start,+ end: m.end,+ shift: m.shift,+ })),+ ...(moved.length > 40 ? { itemsTruncated: true } : {}),+ note:+ moved.length === 0+ ? "Every edge was already on the speech; nothing needed moving."+ : `${moved.length} moved onto the speech in the mix itself (median ${median}s, farthest ${worst}s). Times sitting inside continuous speech, where nothing audible marks a boundary, kept what they had.`,+ };+}++/** Several rows' passes read as one. Indexes are rebased onto the concatenated+ * item list the caller reports from. */+function mergeReports<T extends { id: string; text: string; start: number; end: number }>(+ reports: SyncReport<T>[]+): SyncReport<T> {+ const items: T[] = [];+ const moved: SyncReport<T>["moved"] = [];+ let evidence = false;+ for (const r of reports) {+ const base = items.length;+ items.push(...r.items);+ moved.push(...r.moved.map((m) => ({ ...m, index: base + m.index })));+ evidence ||= r.evidence;+ }+ const sizes = moved.map((m) => Math.abs(m.shift)).sort((a, b) => a - b);+ return {+ items,+ evidence,+ moved,+ medianShift: sizes.length > 0 ? sizes[Math.floor(sizes.length / 2)] : 0,+ maxShift: sizes.length > 0 ? sizes[sizes.length - 1] : 0,+ };+}+/** Whether dressing the project in this look repaints the frame color. A look* that keeps the frame only repaints it when the caller asked for it in so* many words — adding words to a cut is not a reason to recolor it. */@@ -3189,8 +3392,6 @@ function paintsFrame(look: TextLook, background: unknown): boolean {return look.keepsFrame !== true;}-}-/** The lines a text sequence should place: the ones passed in, or the caption* track read as a running order. */function textSequenceLines(diff --git a/site/src/cut/lib/cueAlign.ts b/site/src/cut/lib/cueAlign.tsindex d989fa4d..87aa7469 100644--- a/site/src/cut/lib/cueAlign.ts+++ b/site/src/cut/lib/cueAlign.ts@@ -51,6 +51,12 @@ const BRIDGE = 0.12;* that way. */const QUIET_RUN = 0.15;const QUIET_MARGIN = 6;+/** How closely the evidence on both sides of an unverifiable edge must agree+ * before their shift is read as the clock's error and carried through it. The+ * allowance grows with the distance between the two anchors, because the one+ * clock error that varies — a drifting chunk clock — varies with time. */+const AGREE = 0.12;+const AGREE_PER_S = 0.04;/** A cue never collapses below this while being snapped. */const MIN_CUE = 0.2;/** Speech and cues must overlap at least this well before any of this is@@ -147,11 +153,14 @@ export function speechSpans(samples: ArrayLike<number>, rate: number): SpeechSpa}return true;};+ // The window sits one frame off the edge: the frame straddling the onset+ // carries the word's own attack (or decay), and reading it as "not quiet"+ // would disqualify every boundary the threshold split mid-frame.return kept.map((r) => ({start: r.from * HOP,end: r.to * HOP,- cleanStart: r.from === 0 || isQuiet(r.from - span, r.from),- cleanEnd: r.to === frames || isQuiet(r.to, r.to + span),+ cleanStart: r.from === 0 || isQuiet(r.from - span - 1, r.from - 1),+ cleanEnd: r.to === frames || isQuiet(r.to + 1, r.to + span + 1),}));}@@ -182,29 +191,76 @@ function overlap(cues: Uint8Array, speech: Uint8Array): number {return hit / (cueTotal + speechTotal - hit);}-/** The value in `sorted` closest to `t` within [`t - back`, `t + ahead`], and- * inside [`floor`, `ceil`]. Null when the audio offers no edge there. */-function nearest(- sorted: number[],- t: number,- back: number,- ahead: number,- floor: number,- ceil: number-): number | null {- let best: number | null = null;- let bestGap = Infinity;- for (const v of sorted) {- if (v < t - back || v < floor) continue;- if (v > t + ahead) break;- if (v > ceil) break;- const gap = Math.abs(v - t);- if (gap < bestGap) {- bestGap = gap;- best = v;+/** Overlap below this is a rounding sliver, not a claim on the run. */+const SHARED_EPS = 0.05;++/** How much of `cue` falls inside `span`. Which runs of speech a cue is about+ * is decided by this and nothing else. */+const shared = (cue: AlignCue, span: SpeechSpan): number =>+ Math.max(0, Math.min(cue.end, span.end) - Math.max(cue.start, span.start));++/** For each span, the first and last cue meaningfully overlapping it (-1 when+ * none). A caption OPENS a run when no earlier caption covers any of that run,+ * and CLOSES it when no later one does. Only those two roles have an audible+ * boundary of their own: every other edge on the run sits inside continuous+ * speech, where any word boundary could be the true one. */+function spanRoles(cues: readonly AlignCue[], spans: readonly SpeechSpan[]) {+ const opener = spans.map(() => -1);+ const closer = spans.map(() => -1);+ for (const [j, span] of spans.entries()) {+ for (const [i, cue] of cues.entries()) {+ if (shared(cue, span) <= SHARED_EPS) continue;+ if (opener[j] < 0) opener[j] = i;+ closer[j] = i;}}- return best;+ return { opener, closer };+}++/**+ * Where cue `i`'s start may legally travel, or null.+ *+ * Only one boundary can testify about this edge: the opening of the first run+ * of speech this caption covers, and only when the caption is the one that+ * opens it. A start inside that run pulls back to where the run began; one+ * sitting in silence crosses forward to it (the silence a transcriber hands to+ * a sentence's first word). A caption whose first run an earlier caption+ * already covers begins mid-speech — the audio offers no boundary that is+ * hers, and pulling her onto a later run's opening would caption the wrong+ * words.+ */+function startTarget(+ i: number,+ cues: readonly AlignCue[],+ spans: readonly SpeechSpan[],+ opener: readonly number[],+ back: number+): number | null {+ const cue = cues[i];+ const first = spans.findIndex((sp) => shared(cue, sp) > SHARED_EPS);+ if (first < 0 || opener[first] !== i) return null;+ const span = spans[first];+ if (!span.cleanStart) return null;+ const travel = span.start - cue.start;+ return travel >= -back && travel <= LEAD ? span.start : null;+}++/** The same reasoning for the closing edge: the end of the last run this+ * caption covers, only when the caption is the one that closes it. */+function endTarget(+ i: number,+ cues: readonly AlignCue[],+ spans: readonly SpeechSpan[],+ closer: readonly number[],+ back: number+): number | null {+ const cue = cues[i];+ let last = -1;+ for (const [j, sp] of spans.entries()) if (shared(cue, sp) > SHARED_EPS) last = j;+ if (last < 0 || closer[last] !== i) return null;+ const span = spans[last];+ if (!span.cleanEnd) return null;+ return Math.abs(span.end - cue.end) <= back ? span.end : null;}/**@@ -213,8 +269,14 @@ function nearest(* along with them. A cue the audio has nothing to say about arrives unchanged,* as does every cue when the mix as a whole disagrees with the transcript.*+ * Each edge is settled against the run of speech its own cue is about, so a+ * caption can be pulled onto the voice it captions and never onto the next+ * line's. An edge in the middle of continuous speech, where nothing audible+ * says a caption began or ended, keeps the time the transcriber gave it.+ ** `snap` widens the backward search for a transcriber whose times are guesses- * (the hosted model) over one that reports real word ranges.+ * (the hosted model, a lyric sync's interpolated lines) over one that reports+ * real word ranges.*/export function alignCues<T extends AlignCue>(cues: T[],@@ -234,21 +296,57 @@ export function alignCues<T extends AlignCue>(if (fit < MIN_IOU) return cues; // the audio is describing something elseconst back = opts.snap ?? SNAP;- const onsets = spans.filter((s) => s.cleanStart).map((s) => s.start);- const offsets = spans.filter((s) => s.cleanEnd).map((s) => s.end);const roomFor = (cue: AlignCue) => Math.min(MIN_CUE, Math.max(0.05, cue.end - cue.start));- // Starts first: each looks for the voice its caption belongs to, reaching- // well ahead to cross the silence a transcriber hands to a sentence's first- // word, stopping short of the cue's own end so the caption keeps a life on- // screen, and never opening before the cue in front of it.+ // What the audio testifies to directly: each edge's own target, where its+ // run offers one.+ const { opener, closer } = spanRoles(cues, spans);+ const startEvidence = cues.map((_, i) => startTarget(i, cues, spans, opener, back));+ const endEvidence = cues.map((_, i) => endTarget(i, cues, spans, closer, back));++ // The transcriber's clock is one clock, so its error travels: when the+ // verifiable edges on both sides of an unverifiable one moved by the same+ // amount, that boundary — mid-sentence, where nothing audible marks it —+ // was off by the same amount too, and it inherits the interpolated shift.+ // Edges whose neighbours disagree (one moved, one stayed) keep their time:+ // there the error was local, not the clock's.+ // A start that traveled FORWARD is not a clock reading — it crossed the+ // silence a transcriber handed to a sentence's first word, a flaw local to+ // that one edge. The clock shows in starts pulled back and in ends, whose+ // travel has no such flaw to hide.+ const anchors: { t: number; shift: number }[] = [];+ for (const [i, cue] of cues.entries()) {+ const dS = startEvidence[i] !== null ? startEvidence[i]! - cue.start : null;+ if (dS !== null && dS <= 0) anchors.push({ t: cue.start, shift: dS });+ if (endEvidence[i] !== null) anchors.push({ t: cue.end, shift: endEvidence[i]! - cue.end });+ }+ anchors.sort((a, b) => a.t - b.t);+ const inferred = (t: number): number | null => {+ let prev: { t: number; shift: number } | null = null;+ let next: { t: number; shift: number } | null = null;+ for (const a of anchors) {+ if (a.t <= t) prev = a;+ else {+ next = a;+ break;+ }+ }+ if (!prev || !next) return null;+ if (Math.abs(prev.shift - next.shift) > AGREE + AGREE_PER_S * (next.t - prev.t)) return null;+ const k = next.t === prev.t ? 0 : (t - prev.t) / (next.t - prev.t);+ return prev.shift + (next.shift - prev.shift) * k;+ };++ // Starts first: the edge's own evidence, else the clock error its+ // neighbours agree on, else the time the transcriber gave it — stopping+ // short of the cue's own end so the caption keeps a life on screen, and+ // never opening before the cue in front of it.const starts: number[] = [];for (const [i, cue] of cues.entries()) {const floor = i > 0 ? starts[i - 1] : 0;const ceil = cue.end - roomFor(cue);- starts.push(- Math.max(floor, nearest(onsets, cue.start, back, LEAD, floor, ceil) ?? cue.start)- );+ const target = startEvidence[i] ?? (cue.start + (inferred(cue.start) ?? 0));+ starts.push(Math.max(floor, Math.min(target, Math.max(floor, ceil))));}// Ends then close inside the room the next cue's start leaves, which is what@@ -259,7 +357,7 @@ export function alignCues<T extends AlignCue>(const minLen = Math.max(0.01, Math.min(roomFor(cue), ceil - start));const end = Math.max(start + minLen,- Math.min(ceil, nearest(offsets, cue.end, back, back, start, ceil) ?? cue.end)+ Math.min(ceil, endEvidence[i] ?? (cue.end + (inferred(cue.end) ?? 0))));// Word timings follow the edge that moved. A cue that slid whole carriesdiff --git a/site/src/cut/lib/cueSync.test.ts b/site/src/cut/lib/cueSync.test.tsnew file mode 100644index 00000000..2fe73f70--- /dev/null+++ b/site/src/cut/lib/cueSync.test.ts@@ -0,0 +1,275 @@+import { beforeEach, describe, expect, test } from "bun:test";+import { runAiTool } from "./aiTools";+import { syncToSpeech } from "./cueSync";+import { useEditor } from "./store";+import { emptySubtitles, isTextOverlay, type SubtitleCue } from "./types";++/**+ * Re-timing what is already on the timeline onto the speech in the mix.+ *+ * The audio here is built the way cueAlign's own tests build it: noise bursts+ * where speech happens, quiet between them. What these check is the layer above+ * — that the move is reported honestly, that ids and words survive it, and that+ * a mix with nothing to read comes back saying so instead of claiming a fix.+ */++const RATE = 16000;++function mix(duration: number, spans: [number, number][]): Float32Array {+ const samples = new Float32Array(Math.round(duration * RATE));+ let seed = 7;+ const rnd = () => {+ seed = (seed * 1103515245 + 12345) % 2147483648;+ return seed / 2147483648 - 0.5;+ };+ for (let i = 0; i < samples.length; i++) samples[i] = rnd() * 0.002;+ for (const [from, to] of spans) {+ const start = Math.round(from * RATE);+ const stop = Math.min(samples.length, Math.round(to * RATE));+ for (let i = start; i < stop; i++) samples[i] += rnd() * 0.6;+ }+ return samples;+}++const SPEECH: [number, number][] = [+ [1, 2.5],+ [4, 5.5],+ [8, 9.5],+];+const audio = () => mix(12, SPEECH);++const cue = (id: string, start: number, end: number, text = "a line of speech"): SubtitleCue => ({+ id,+ start,+ end,+ text,+});++describe("syncToSpeech", () => {+ test("moves late times onto the speech and reports the move", () => {+ const late = [cue("a", 1.3, 2.8), cue("b", 4.3, 5.8), cue("c", 8.3, 9.8)];+ const report = syncToSpeech(late, audio(), RATE);+ expect(report.evidence).toBe(true);+ expect(report.moved).toHaveLength(3);+ expect(report.items[0].start).toBeCloseTo(1, 1);+ expect(report.items[1].start).toBeCloseTo(4, 1);+ expect(report.items[2].start).toBeCloseTo(8, 1);+ // The report is what the assistant repeats back, so it has to describe the+ // move that actually happened.+ expect(report.maxShift).toBeGreaterThanOrEqual(report.medianShift);+ expect(report.moved.every((m) => m.shift < 0)).toBe(true);+ });++ test("ids, text and word timings ride through", () => {+ const withWords = [+ { ...cue("a", 1.3, 2.8), words: [{ t0: 1.3, t1: 2, w: "a" }, { t0: 2, t1: 2.8, w: "line" }] },+ cue("b", 4.3, 5.8),+ cue("c", 8.3, 9.8),+ ];+ const report = syncToSpeech(withWords, audio(), RATE);+ expect(report.items[0].id).toBe("a");+ expect(report.items[0].text).toBe("a line of speech");+ expect(report.items[0].words?.[0].t0).toBeCloseTo(1, 1);+ expect(report.items[0].words).toHaveLength(2);+ });++ test("times already on the speech move nothing", () => {+ const report = syncToSpeech([cue("a", 1, 2.5), cue("b", 4, 5.5)], audio(), RATE);+ expect(report.moved).toHaveLength(0);+ expect(report.evidence).toBe(true);+ });++ test("audio with nothing to read says so rather than claiming a fix", () => {+ const silent = new Float32Array(RATE * 12);+ const wall = mix(12, [[0, 12]]);+ for (const samples of [silent, wall]) {+ const report = syncToSpeech([cue("a", 1.3, 2.8)], samples, RATE);+ expect(report.evidence).toBe(false);+ expect(report.moved).toHaveLength(0);+ expect(report.items[0].start).toBe(1.3);+ }+ });++ test("one cue out of a long recording is not enough to read the mix by", () => {+ // The fit is weighed over the whole transcript: a single line against+ // twelve seconds of speech describes something else, so nothing moves.+ // This is why the tool measures a whole track even when writing a subset.+ expect(syncToSpeech([cue("a", 1.3, 2.8)], audio(), RATE).evidence).toBe(false);+ });++ test("nothing to align is not an alignment", () => {+ expect(syncToSpeech([], audio(), RATE).evidence).toBe(false);+ });+});++describe("align_to_audio", () => {+ const reset = (cues: SubtitleCue[], overlays: unknown[] = []) =>+ useEditor.setState({+ projectId: "p1",+ aspect: "16:9",+ assets: [],+ clips: [],+ audioClips: [],+ overlays: overlays as never,+ subtitles: { ...emptySubtitles(), cues },+ cutMixSamples: async () => ({ samples: audio(), sampleRate: RATE }),+ });++ const title = (id: string, start: number, end: number) => ({+ id,+ kind: "text" as const,+ text: `line ${id}`,+ start,+ end,+ x: 0.5,+ y: 0.5,+ size: 72,+ color: "#FFFFFF",+ font: "sf",+ weight: 700 as const,+ });++ beforeEach(() => reset([]));++ test("re-times a caption track in place, ids kept", async () => {+ reset([cue("a", 1.3, 2.8), cue("b", 4.3, 5.8), cue("c", 8.3, 9.8)]);+ const res = (await runAiTool("align_to_audio", {})) as {+ target: string;+ moved: number;+ evidence: boolean;+ items: { id: string; shift: number }[];+ };+ expect(res.target).toBe("captions");+ expect(res.evidence).toBe(true);+ expect(res.moved).toBe(3);+ const after = useEditor.getState().subtitles.cues;+ expect(after.map((c) => c.id)).toEqual(["a", "b", "c"]);+ expect(after[0].start).toBeCloseTo(1, 1);+ expect(after[2].start).toBeCloseTo(8, 1);+ // One undo step puts every cue back where it was.+ useEditor.getState().undo();+ expect(useEditor.getState().subtitles.cues[0].start).toBeCloseTo(1.3, 2);+ });++ test("writing part of a track never lands a cue on a neighbour", async () => {+ // The whole track is measured, only `b` is written. `b` wants to move back+ // onto the speech at 4, and `a` — left where it is — still ends at 4.4.+ // Captions on a track may not overlap, so the write is fitted to the room+ // it actually has.+ reset([cue("a", 2.9, 4.4), cue("b", 4.3, 5.8), cue("c", 8.3, 9.8)]);+ await runAiTool("align_to_audio", { ids: ["b"] });+ const after = useEditor.getState().subtitles.cues;+ const by = new Map(after.map((c) => [c.id, c]));+ expect(by.get("a")!.start).toBeCloseTo(2.9, 2);+ expect(by.get("a")!.end).toBeCloseTo(4.4, 2);+ expect(by.get("c")!.start).toBeCloseTo(8.3, 2);+ expect(by.get("b")!.start).toBeGreaterThanOrEqual(by.get("a")!.end - 1e-6);+ for (const [i, c] of after.entries()) {+ if (i > 0) expect(c.start).toBeGreaterThanOrEqual(after[i - 1].end - 1e-6);+ }+ });++ test("a card rides only with a word that actually moved", async () => {+ // `t2` is the only element written, so `c1` — the card behind `t1` — must+ // stay with the word it belongs to rather than following an alignment+ // nobody applied.+ const card = (id: string, start: number, end: number) => ({+ id,+ kind: "rect" as const,+ start,+ end,+ x: 0.5,+ y: 0.5,+ w: 1,+ h: 1,+ fill: "#FF5500",+ });+ reset(+ [],+ [+ { ...title("t1", 1.3, 2.8), lane: 0 },+ { ...title("t2", 4.3, 5.8), lane: 0 },+ { ...card("c1", 1.3, 2.8), lane: 1 },+ ]+ );+ await runAiTool("align_to_audio", { target: "elements", ids: ["t2"] });+ const by = new Map(useEditor.getState().overlays.map((o) => [o.id, o]));+ expect(by.get("t1")!.start).toBeCloseTo(1.3, 2);+ expect(by.get("c1")!.start).toBeCloseTo(1.3, 2);+ expect(by.get("t2")!.start).toBeCloseTo(4, 1);+ });++ test("re-times the elements of a text run", async () => {+ reset([], [title("t1", 1.3, 2.8), title("t2", 4.3, 5.8), title("t3", 8.3, 9.8)]);+ const res = (await runAiTool("align_to_audio", { target: "elements" })) as {+ target: string;+ lane: number;+ moved: number;+ };+ expect(res.target).toBe("elements");+ expect(res.moved).toBe(3);+ const after = useEditor.getState().overlays.filter(isTextOverlay);+ expect(after.map((o) => o.id)).toEqual(["t1", "t2", "t3"]);+ expect(after[0].start).toBeCloseTo(1, 1);+ expect(after[1].start).toBeCloseTo(4, 1);+ // Elements on one row must never overlap, and an alignment is no exception.+ for (let i = 0; i + 1 < after.length; i++)+ expect(after[i].end).toBeLessThanOrEqual(after[i + 1].start + 1e-6);+ });++ test("a mix it cannot read leaves the cut alone and says so", async () => {+ reset([cue("a", 1.3, 2.8)]);+ useEditor.setState({+ cutMixSamples: async () => ({ samples: new Float32Array(RATE * 12), sampleRate: RATE }),+ });+ const res = (await runAiTool("align_to_audio", {})) as { evidence: boolean; moved: number };+ expect(res.evidence).toBe(false);+ expect(res.moved).toBe(0);+ expect(useEditor.getState().subtitles.cues[0].start).toBeCloseTo(1.3, 2);+ });++ const failure = async (input: Record<string, unknown>) => {+ try {+ await runAiTool("align_to_audio", input);+ return "";+ } catch (err) {+ return err instanceof Error ? err.message : String(err);+ }+ };++ test("nothing to align, and nothing audible, are both refused", async () => {+ reset([]);+ expect(await failure({})).toContain("no captions");+ reset([cue("a", 1.3, 2.8)]);+ useEditor.setState({ cutMixSamples: async () => null });+ expect(await failure({})).toContain("audible");+ });++ test("a run's color cards ride with the words they sit behind", async () => {+ const card = (id: string, start: number, end: number) => ({+ id,+ kind: "rect" as const,+ start,+ end,+ x: 0.5,+ y: 0.5,+ w: 1,+ h: 1,+ fill: "#FF5500",+ });+ reset(+ [],+ [+ { ...title("t1", 1.3, 2.8), lane: 0 },+ { ...title("t2", 4.3, 5.8), lane: 0 },+ { ...card("c1", 1.3, 2.8), lane: 1 },+ { ...card("c2", 4.3, 5.8), lane: 1 },+ ]+ );+ await runAiTool("align_to_audio", { target: "elements" });+ const by = new Map(useEditor.getState().overlays.map((o) => [o.id, o]));+ expect(by.get("t1")!.start).toBeCloseTo(1, 1);+ expect(by.get("c1")!.start).toBeCloseTo(by.get("t1")!.start, 3);+ expect(by.get("c2")!.start).toBeCloseTo(by.get("t2")!.start, 3);+ });+});diff --git a/site/src/cut/lib/cueSync.ts b/site/src/cut/lib/cueSync.tsnew file mode 100644index 00000000..d25034eb--- /dev/null+++ b/site/src/cut/lib/cueSync.ts@@ -0,0 +1,144 @@+/**+ * Re-timing what is already on the timeline onto the speech in the cut's mix.+ *+ * The transcriber's clock is only checked once, when captions are written. Everything+ * after that — a lyric sync's interpolated lines, a run of text cards built from+ * those cues, captions the user dragged, a track retimed by hand — carries times+ * nobody measured against the audio. This is the measurement: the same envelope+ * pass captions are snapped with (cueAlign.ts), run over any list of timed items,+ * with a report of what moved so the caller can say it out loud.+ *+ * The audio decides, and it declines often: a mix with no readable quiet, or one+ * whose speech doesn't line up with these times at all, moves nothing and says so.+ * A caller that can't tell "aligned, nothing needed moving" from "the audio had+ * nothing to say" would report a silent no-op as a fix.+ */++import { alignCues, type AlignCue } from "./cueAlign";++/** A move worth reporting. Below this the edge was already on the speech. */+const MOVED = 0.02;++export interface CueMove {+ index: number;+ start: number;+ end: number;+ /** How far the start travelled; negative is earlier. */+ shift: number;+}++export interface SyncReport<T extends AlignCue> {+ items: T[];+ /** False when the audio had nothing to testify to — digital silence, a wall+ * of music with no quiet in it, or speech that does not describe these times.+ * Nothing moved, and nothing about the timing was confirmed either. */+ evidence: boolean;+ moved: CueMove[];+ /** Seconds, over the items that moved. */+ medianShift: number;+ maxShift: number;+}++/**+ * `items` re-timed onto the speech in `samples`. Order, ids and every other+ * field ride through untouched; word timings follow the edge that moved.+ *+ * `reach` widens how far an edge may travel backward to meet a speech edge —+ * times that are guesses (interpolated lyric lines, a hand-dragged cue) earn a+ * wider one than a transcriber's own word ranges.+ */+export function syncToSpeech<T extends AlignCue>(+ items: T[],+ samples: ArrayLike<number>,+ rate: number,+ opts: { reach?: number } = {}+): SyncReport<T> {+ const empty = { items, evidence: false, moved: [], medianShift: 0, maxShift: 0 };+ if (items.length === 0 || rate <= 0) return empty;+ const aligned = alignCues(items, samples, rate, { snap: opts.reach });+ // alignCues hands back the very array it was given when the audio offers no+ // usable edges; anything else means it read the envelope and applied it.+ if (aligned === items) return empty;++ const moved: CueMove[] = [];+ aligned.forEach((next, i) => {+ const before = items[i];+ const shift = next.start - before.start;+ if (Math.abs(shift) >= MOVED || Math.abs(next.end - before.end) >= MOVED)+ moved.push({+ index: i,+ start: round2(next.start),+ end: round2(next.end),+ shift: round2(shift),+ });+ });+ const sizes = moved.map((m) => Math.abs(m.shift)).sort((a, b) => a - b);+ return {+ items: aligned,+ evidence: true,+ moved,+ medianShift: sizes.length > 0 ? round2(sizes[Math.floor(sizes.length / 2)]) : 0,+ maxShift: sizes.length > 0 ? round2(sizes[sizes.length - 1]) : 0,+ };+}++const round2 = (n: number) => Math.round(n * 100) / 100;++/** The least room a re-timed item may be squeezed into before the move is+ * abandoned as not worth making. */+const MIN_LEN = 0.12;++/**+ * The subset of an aligned run that is safe to write on its own.+ *+ * A caller may align a whole row and write only part of it — the model named+ * a few ids. Each side of that is internally sound: the aligned run does not+ * overlap itself and neither does the run already on the timeline. The mix of+ * the two can, and items sharing a row may never overlap, so a partial write+ * is fitted to the neighbours it is landing between: the ones also being+ * written by their new times, the ones left alone by their old ones. What+ * still does not fit stays where it is rather than landing on top of a line+ * nobody asked to move.+ */+export function partialWrites<T extends AlignCue & { id: string }>(+ aligned: readonly T[],+ before: readonly { id: string; start: number; end: number }[],+ chosen: (item: T) => boolean+): T[] {+ const old = new Map(before.map((b) => [b.id, b]));+ const order = [...aligned].sort((a, b) => a.start - b.start);+ const out: T[] = [];+ // Where each item ends up: its aligned times when it is being written, the+ // times it already has when it is not.+ const settled = order.map((item) => {+ const prev = old.get(item.id);+ return chosen(item) || !prev ? { item, start: item.start, end: item.end, write: true } : { item, start: prev.start, end: prev.end, write: false };+ });+ for (const [i, row] of settled.entries()) {+ if (!row.write) continue;+ const floor = i > 0 ? settled[i - 1].end : 0;+ const ceil = i + 1 < settled.length ? settled[i + 1].start : Infinity;+ const start = Math.max(row.start, floor, 0);+ const end = Math.min(row.end, ceil);+ if (end - start < MIN_LEN) {+ // No room between the neighbours: leave this one where it was, and let+ // the ones after it fit against that.+ const prev = old.get(row.item.id);+ row.start = prev?.start ?? row.item.start;+ row.end = prev?.end ?? row.item.end;+ row.write = false;+ continue;+ }+ row.start = start;+ row.end = end;+ // Word timings follow the window they live in, so a cue squeezed by a+ // neighbour never highlights past its own edges.+ const words = row.item.words?.map((w) => ({+ ...w,+ t0: Math.min(Math.max(w.t0, start), end),+ t1: Math.min(Math.max(w.t1, start), end),+ }));+ out.push({ ...row.item, start, end, ...(words ? { words } : {}) });+ }+ return out;+}diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 854663cb..25505214 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -542,6 +542,10 @@ export interface EditorState {setNotes: (patch: Partial<{ text: string; publishedAt: string; links: string[] }>) => void;/** Kick off (and poll) an on-device transcription of the current cut. */generateSubtitles: () => Promise<void>;+ /** The cut's audible mix as mono samples — the audio a caption is measured+ * against. Null when nothing on the timeline makes a sound, or the mix+ * could not be rendered. */+ cutMixSamples: () => Promise<{ samples: Float32Array; sampleRate: number } | null>;/** Transcribe one clip's own audio (even when muted) and merge its cues into* the subtitles; cues elsewhere on the timeline stay put. Throws a* user-facing error on failure. */@@ -578,6 +582,16 @@ export interface EditorState {* right past occupied stretches on the cue's own lane so cues never overlap,* and detach the word timings (they described the old window). One undo step. */setCueTiming: (id: string, start: number, end: number) => void;+ /** Re-time cues and elements onto windows something else measured — the+ * caption alignment pass, which reads the mix itself. Exact times, ids,+ * text, word timings and lanes all kept, in one undo step, and nothing+ * slides: the caller's windows are already in order and non-overlapping,+ * so a per-item write that shoved its neighbours would undo the alignment+ * it was given. */+ retimeItems: (patch: {+ cues?: { id: string; start: number; end: number; words?: { t0: number; t1: number; w: string }[] }[];+ overlays?: { id: string; start: number; end: number }[];+ }) => void;/** Replace one subtitle track's captions wholesale, in timeline seconds —* what a lyric sync writes once it knows when every line lands. */setLaneCues: (lane: number, cues: { start: number; end: number; text: string; words?: { t0: number; t1: number; w: string }[] }[]) => void;@@ -1147,6 +1161,74 @@ function normalizeWrite(prev: EditorState, incoming: Partial<EditorState>): Partreturn next;}+/**+ * The whole cut as a transcribe spec: the track-0 spans in order with their+ * gaps as explicit silent spacers, plus every audible soundtrack and layer+ * clip as a positioned source. Speech can live anywhere on the timeline, so+ * dialogue on a layer clip gets captioned and a layer-only cut still works.+ *+ * One builder serves both readers of the cut's audio — the transcriber and+ * the mix render the caption alignment pass measures against — so a caption is+ * always checked against the same audio it was written from. Null when the+ * timeline has nothing audible.+ */+function cutTranscribeSpec(+ s: Pick<EditorState, "clips" | "assets" | "audioClips" | "overlays">,+ locale?: string+): CloudTranscribeSpec | null {+ const spans = getClipSpans(s.clips, s.assets);+ const duration = projectDuration(s);+ const assetById = new Map(s.assets.map((a) => [a.id, a]));+ const audio = s.audioClips+ .filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId))+ .map((a) => ({+ file: assetById.get(a.assetId)!.fileName,+ in: a.in,+ out: a.out,+ start: a.start,+ volume: a.volume,+ speed: a.speed,+ }))+ .concat(+ overlayLayers(s.clips)+ .filter((c) => !c.hidden && !c.muted && c.start < duration && assetById.has(c.assetId))+ .map((c) => ({+ file: assetById.get(c.assetId)!.fileName,+ in: c.in,+ out: c.out,+ start: c.start,+ volume: 1,+ speed: c.speed,+ }))+ );+ if (spans.length === 0 && audio.length === 0) return null;+ const silentSpacer = (len: number) => ({ file: "", in: 0, out: len, muted: true, speed: 1, transition: 0 });+ return {+ duration,+ ...(locale ? { locale } : {}),+ // The mix is a sequential fold, so gaps between the free-placed clips ship+ // as explicit silent spacers (empty file). An overlay-only cut has no+ // track-0 spans: the whole bed is one spacer.+ clips:+ spans.length === 0+ ? [silentSpacer(duration)]+ : spanSequence(spans).flatMap(({ gapBefore, span: sp }) => [+ ...(gapBefore > 0 ? [silentSpacer(gapBefore)] : []),+ {+ file: sp.asset.fileName,+ in: sp.clip.in,+ out: sp.clip.out,+ muted: sp.clip.muted,+ speed: clipSpeed(sp.clip),+ // The clamped cross-dissolve overlap, so the mix overlaps clip+ // audio the same way the timeline does and cues stay in sync.+ transition: sp.transitionOut,+ },+ ]),+ audio,+ };+}+export const useEditor = create<EditorState>((baseSet, get, api) => {// Normalizing is bolted onto setState itself, not onto a local helper the// actions happen to use: the store's own module-level helpers write through@@ -3516,75 +3598,28 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {setPublish: (patch) => set((s) => ({ publish: { ...s.publish, ...patch } })),setNotes: (patch) => set((s) => ({ notes: { ...s.notes, ...patch } })),+ cutMixSamples: async () => {+ const s = get();+ if (!s.projectId) return null;+ const spec = cutTranscribeSpec(s);+ if (!spec) return null;+ const mix = await renderMix(s.projectId, spec);+ if (!mix) return null;+ return { samples: mix.getChannelData(0), sampleRate: mix.sampleRate };+ },+generateSubtitles: async () => {const s = get();if (!s.projectId || s.subtitleStatus === "running") return;const projectId = s.projectId;- const spans = getClipSpans(s.clips, s.assets);- const duration = projectDuration(s);- const assetById = new Map(s.assets.map((a) => [a.id, a]));- // Speech can live on the soundtrack or on a layer video track, not just- // track 0. Layer-clip audio mixes into the transcribe pass as a- // positioned source (exactly like a soundtrack clip), so dialogue carried- // on a layer clip gets captioned and a layer-only cut still works.- const audio = s.audioClips- .filter((a) => !a.hidden && a.start < duration && assetById.has(a.assetId))- .map((a) => ({- file: assetById.get(a.assetId)!.fileName,- in: a.in,- out: a.out,- start: a.start,- volume: a.volume,- speed: a.speed,- }))- .concat(- overlayLayers(s.clips)- .filter(- (c) => !c.hidden && !c.muted && c.start < duration && assetById.has(c.assetId),- )- .map((c) => ({- file: assetById.get(c.assetId)!.fileName,- in: c.in,- out: c.out,- start: c.start,- volume: 1,- speed: c.speed,- })),- );- if (spans.length === 0 && audio.length === 0) {+ // Generation targets the active subtitle track, with its own language.+ const lane = s.subtitleLane;+ const spec = cutTranscribeSpec(s, trackLocale(s.subtitles, lane));+ if (!spec) {set({ subtitleStatus: "error", subtitleError: "Add a video to the timeline first." });return;}- // Generation targets the active subtitle track, with its own language.- const lane = s.subtitleLane;const epoch = laneEpoch;- const silentSpacer = (len: number) =>- ({ file: "", in: 0, out: len, muted: true, speed: 1, transition: 0 });- const spec = {- duration,- locale: trackLocale(s.subtitles, lane),- // The transcribe mix is a sequential fold, so gaps between the- // free-placed clips ship as explicit silent spacers (empty file). An- // overlay-only cut has no track-0 spans: the whole bed is one spacer.- clips:- spans.length === 0- ? [silentSpacer(duration)]- : spanSequence(spans).flatMap(({ gapBefore, span: sp }) => [- ...(gapBefore > 0 ? [silentSpacer(gapBefore)] : []),- {- file: sp.asset.fileName,- in: sp.clip.in,- out: sp.clip.out,- muted: sp.clip.muted,- speed: clipSpeed(sp.clip),- // The clamped cross-dissolve overlap, so the transcribe mix- // overlaps clip audio the same way the timeline does and cues- // stay in sync.- transition: sp.transitionOut,- },- ]),- audio,- };set({ subtitleStatus: "running", subtitleError: null, subtitleStartedAt: Date.now() });try {const cues = await runTranscription(projectId, spec);@@ -4132,6 +4167,46 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {},})),+ retimeItems: ({ cues = [], overlays = [] }) => {+ if (cues.length === 0 && overlays.length === 0) return;+ const cueBy = new Map(cues.map((c) => [c.id, c]));+ const overlayBy = new Map(overlays.map((o) => [o.id, o]));+ push();+ set((s) => ({+ subtitles:+ cues.length === 0+ ? s.subtitles+ : {+ ...s.subtitles,+ cues: s.subtitles.cues+ .map((c) => {+ const next = cueBy.get(c.id);+ if (!next) return c;+ // The floor is applied before the end is measured against+ // the start, so a negative time can never leave an item+ // ending before it begins.+ const start = Math.max(0, next.start);+ return {+ ...c,+ start,+ end: Math.max(start, next.end),+ ...(next.words ? { words: next.words } : {}),+ };+ })+ .sort((a, b) => a.start - b.start),+ },+ overlays:+ overlays.length === 0+ ? s.overlays+ : s.overlays.map((o) => {+ const next = overlayBy.get(o.id);+ if (!next) return o;+ const start = Math.max(0, next.start);+ return { ...o, start, end: Math.max(start, next.end) };+ }),+ }));+ },+setLaneCues: (lane, cues) => {push();const made: SubtitleCue[] = cuesdiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 0f56aa67..eca51bb8 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -210,13 +210,15 @@ Never lay a run at variation "none" and then repair it with a hundred update_ove1. The song is in the cut (a soundtrack clip). \`get_state\` confirms it and gives the duration.2. sync_lyrics with the lyrics text, one line per screen. It transcribes the cut, aligns the user's words to what it recognized, and writes the user's text — verbatim — onto a caption track with per-word times. Singing defeats recognizers; that is why the wording comes from the user and only the clock comes from the transcript.3. Dress it: set_caption_look with a look id (karaoke-glow for words lighting up, neon-club, serif-mood…), or add_text_sequence from_captions to turn the same timed lines into full-frame cards. Going the element route, re-send the lines yourself with emphasis and section on them rather than from_captions — from_captions carries the timing but knows nothing about which line is the hook.-4. Check it: seek + capture_frame at three or four lines that landed on DIFFERENT rota steps, and listen_audio across one of them. A line that sits early or late retimes with update_cue.+4. Check it: sync_lyrics already snaps its lines to the mix, and align_to_audio re-runs that pass any time (on the caption track, or on the elements of a run with target elements). Then seek + capture_frame at three or four lines that landed on DIFFERENT rota steps, and listen_audio across one of them. A single line still sitting early or late retimes with update_cue.With no lyrics text, transcribe with subtitles_generate and work from the cues it wrote.**Words over the user's footage.** Same flow, with the over-footage look (or any look with no cards) and \`background: false\` — the clips keep playing and the words ride above them. Aim them off the caption band when captions are also on, and prefer layouts that stay out of the middle of the shot.**Words on plain color.** A cut with nothing on track 0 is a complete video: set the background, place the run, export. Cards are how the color changes line to line — the sequence paints one per line on its own row behind the words, so they stack instead of sliding apart.+**When the words are off the audio.** \"The subtitles are late\", \"sync the text to the audio\", \"it drifts by the end\" — that is align_to_audio, and it is the only honest answer to it. It renders the cut's audible mix, reads a 10ms energy envelope to find where speech really starts and stops, and moves each caption or element edge onto the speech edge it belongs to; an edge with nothing audible near it keeps its time. Re-transcribing instead throws away the user's own wording, and retiming cue by cue with update_cue is guessing at what the waveform already knows — reach for update_cue for the one line the pass could not place. The pass reports \`evidence: false\` when the mix gave it nothing to read (a bed of music with no quiet in it, digital silence, or speech that does not line up with these times at all); say that plainly rather than reporting a fix, and check by ear with listen_audio.+**Timing.** One line per screen beats two. A line needs about 0.4s minimum to read; 1.5–2.5s is the normal beat for a spoken line, and a sung line takes whatever the vocal takes. Lines never overlap on a row — the sequence tool lays them end to end from the times you give it.**Fixing a run.** update_overlay retimes or recolors any line, set_overlay_animation swaps its entrance, set_overlay_keyframes gives it a path. Reach for those to fix a handful of lines. When the whole run is wrong, delete it and re-compose with different look, layout, or variation — that is one call against a hundred.`,@@ -367,9 +369,10 @@ Rules:- Edits are undoable (unlimited undo), so prefer doing over asking; only ask when the request is genuinely ambiguous. Ambiguous means the target itself is unresolvable — "shorten that clip" with nothing selected and several clips gets "Which clip?" and no edit; guessing a target and editing it is worse than the question. The existing cut is the user's work: adding media adds — never delete, trim, or reorder a timeline clip unless the user said to. Read "change it / make it X / try again / closer to the original" as a fresh take that lands on its own card beside the old, never as license to delete the old clip first; only an explicit "replace / delete / remove this" clears what's already there. Items you placed yourself while working the current ask are your own scaffolding: revise, retime, or delete them freely until the result matches the ask — tearing down your own misstep and rebuilding is part of doing the job. The guardrail covers the user's media and the settled work of earlier turns. Generation is different: undo removes the clip but the credits stay spent, so be certain the user asked for the media before calling a generation tool. Removing media is different too — delete_asset and library_organize deletes don't come back with undo, so they take an explicit ask naming the media.- Times are seconds. The frame follows project.aspect in editor_state — any "W:H" ratio, short side 1080px; project.frame has the exact pixels. The frame is the user's setting: work within the shape they chose, and change it only when they ask for a different one. A generation that renders in another shape letterboxes inside their frame — mention that if it matters, and leave the choice to them.- Exercise judgment on details the user left open, and state the choice you made. Judgment fills in the parameters of the asked-for change (style, length, placement); the scope stays the ask, and extra tools, tracks, or treatments beyond it wait for the user to ask. Editing defaults: a hard cut at every joint; when transitions are asked for, one style family per video at 0.4–0.6s. The editing-taste skill carries the full doctrine.+- Styling is part of the ask, never a bonus. Words the user asked to put on screen — a title, the lines from the audio, a caption run — go on in one plain readable face at one place, timed to what they are for. Per-line typefaces, tilts, color cards, keyframe moves, karaoke highlights and a repainted frame are a design, and a design is something the user asks for: a lyric video, kinetic type, a named style or vibe, a reference to match, "make it fun". Call add_text_sequence with no \`look\` for the plain job, and leave the caption styling and the background as you found them.- Read list_skills / read_skill before working in an area you're unsure about — they document every setting. A tool whose description already answers the ask goes straight through.- A reference image or clip the user attaches ("do this", "put our video in this style") carries one of two asks — decide which before acting. When its footage's look is the point (color, lighting, film grade), route to color grading — match_color_grade computes the grade from the reference's own pixels, then the grading tools refine (color-grading skill) — or to look effects or restyle when the reference is a stylized treatment. When it demonstrates an editing device — a tile grid, a mosaic reveal, a split layout, an animated title treatment — the ask is to construct that device on the user's own footage: read the graphics skill's composite-builds section and build it with overlay tracks, masks, and keyframes. Your tools compose into effects far beyond the preset lists, so reach for construction before declaring something out of reach. Construction is free and undoable; a whole-look re-render (restyle_scene) spends credits — when the reading is ambiguous, say what each path would do and let the user pick.-- Styling is part of the ask, never a bonus. Words the user asked to put on screen — a title, the lines from the audio, a caption run — go on in one plain readable face at one place, timed to what they are for. Per-line typefaces, tilts, color cards, keyframe moves, karaoke highlights and a repainted frame are a design, and a design is something the user asks for: a lyric video, kinetic type, a named style or vibe, a reference to match, "make it fun". Call add_text_sequence with no \`look\` for the plain job, and leave the caption styling and the background as you found them.+- Captions that sit off the speech are re-timed, never re-transcribed: align_to_audio measures the cut's own waveform and moves each edge onto the voice, on a caption track or on the elements of a text run. Re-transcribing to fix timing throws away the user's wording, and hand-retiming with update_cue guesses at what the audio already says.- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, sources you have watched or listened to carry their own transcript (media entries marked speech: "transcribed"; get_state includes the timed segments), and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud / generate_music make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. When it lands on a card, close with a statement of where it is ("The voiceover is on the card — drag it in or tell me to place it."). Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the storyboard — the user reviews the frames (regenerate_shot redraws any before approval, no credits), then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after). Close a plan message with the approval path as a statement: "Approve it — say so or hit Approve on the card — and I'll render the shots." Tweaks before approval are theirs to name.