Drive Google Flow from Claude, Codex or a local control panel, on Mac or Windows — using your Google AI subscription credits instead of the pay-per-use video API. No browser extension.
Captions: burn spoken-word captions into any video, from the Studio tab or flow_captions
GTAI-1722044d27be9
diff --git a/CLAUDE.md b/CLAUDE.mdindex d3ce793..d65cdd4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -432,3 +432,27 @@ The preview tool could not read the project while it lived in ~/Desktop; check ta 250 ms hover then a wait for the More options button itself (locator.isVisible({ timeout }) does NOT wait - itanswers at once), 250 ms polling, and each download held to a random 4-4.4 s (downloadPace). Measured on 6 images:4.2, 4.1, 4.2, 4.0, 4.4, 4.4 s, all 1024x1024 originals in scene order. Other hoverTile callers keep 900 ms.+- CAPTIONS (built 2026-10-08, `src/captions.ts`, Studio tab "Captions", MCP `flow_captions`): Homebrew's ffmpeg 8.1+ has NO text filters at all (no ass, subtitles, drawtext - no libass/freetype), so captions are drawn by headless+ Chrome (playwright-core `chromium.launch` on the system Chrome with a throwaway profile, never the Flow profile) as+ transparent full-frame PNGs, one per distinct caption state, played as an ffconcat image track with exact durations+ and `overlay`-ed onto the video (libx264 veryfast crf 18, AAC copied). Words come from whisper.cpp (`whisper-cli`,+ brew `whisper-cpp`) with `-ojf`: build words from TOKENS (leading space = new word), because `-ml 1 -sow` segments+ run each word into the next and hide every pause. Measured against the waveform: plain token offsets land within+ ~50 ms of the real word onset; `-dtw` (needs `-nfa`, else t_dtw is -1) was ~150 ms LATE; large-v3-turbo placed a+ word 0.6 s early and drops punctuation - so small.en > base.en > ... > turbo. 20 s of speech: 1 s to transcribe,+ ~0.3 s per preview, ~8 s to burn. Transcripts cache in ~/.flow-mcp/captions; the media route only serves+ OUTPUT_ROOT, uploads and that folder (previews 404'd until it was allowed). Edited text is re-timed by LCS against+ the heard words; a line break forces a new caption. Captions break at commas and sentence ends; `text-wrap:balance`+ stops a lone word on line two. The model download (base.en, 148 MB, huggingface ggerganov/whisper.cpp) and+ set_key are panel-only - a big download should be the user's click.+- TESTING THE PANEL without touching the real one or Flow: a script that sets FLOW_MCP_PORT=8799, FLOW_MCP_HOME and+ FLOW_MCP_OUTPUT to scratch dirs BEFORE dynamically importing dist/core.js + dist/server.js, overrides+ core.status/characters/assets (status -> getFlowState -> getBrowser LAUNCHES the Flow Chrome when CDP is down), then+ startServer(core); open http://127.0.0.1:8799 in the Browser pane. Kill the node pid itself afterwards - pkill on+ the background shell left it listening.+- Caption placement: `position` is bottom|middle|top or a number 0-100 (how far down the frame the caption's middle+ sits); the panel has an exact-height slider and tap-the-preview. Bold pop scales the spoken word by 1.06 - at 1.08+ with no word margin it swallowed the space beside it ("EVERYTHINGAFTER"), so words carry a .07em margin.+ First Ascent's finished film survived the Trash only because it was published in an artifact (film.mp4); it is back+ at ~/flow-mcp-out/Ascent/ascent-1080.mp4.diff --git a/src/captions.ts b/src/captions.tsnew file mode 100644index 0000000..e16f4dd--- /dev/null+++ b/src/captions.ts@@ -0,0 +1,575 @@+import { execFile } from "node:child_process";+import { createHash } from "node:crypto";+import { createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";+import { cpus, homedir, tmpdir } from "node:os";+import { basename, extname, join } from "node:path";+import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";+import type { ReadableStream } from "node:stream/web";+import { promisify } from "node:util";+import { chromium, type Browser, type Page } from "playwright-core";++import { chromeExecutable, HOME_DIR } from "./chrome.js";+import { FFMPEG_HINT, IS_MAC, IS_WIN } from "./platform.js";++// Captions in the style short-form apps use, burned into the picture. The words and their timings come from+// whisper.cpp on this computer; the lettering is drawn by headless Chrome and laid over the video by ffmpeg. Chrome+// does the drawing because Homebrew's ffmpeg is built without any text filter (no ass, subtitles or drawtext), and+// Chrome is already a requirement - so the same code runs on a Mac and on Windows with nothing extra to install.++const run = promisify(execFile);+const FFMPEG = process.env.FLOW_MCP_FFMPEG ?? "ffmpeg";+const FFPROBE = process.env.FLOW_MCP_FFPROBE ?? "ffprobe";+const WHISPER = process.env.FLOW_MCP_WHISPER ?? "whisper-cli";+// Transcripts and preview stills; the panel is allowed to show pictures from here.+export const CACHE_DIR = join(HOME_DIR, "captions");+const MODEL_DIR = join(HOME_DIR, "models");+const BIG = { maxBuffer: 64 * 1024 * 1024 };+type RunError = NodeJS.ErrnoException & { stderr?: string };++export interface Word {+ text: string;+ start: number;+ end: number;+ // A line break typed before this word in the panel: start a new caption here.+ br?: boolean;+}++export interface Transcript {+ words: Word[];+ text: string;+ language: string;+ model: string;+}++export const CAPTION_STYLES = {+ bold: { label: "Bold pop", blurb: "Big capitals, a few words at a time; the word being said lights up", maxWords: 3, highlight: true, pop: true, color: "#FFE135" },+ highlight: { label: "Highlight", blurb: "The word being said sits on a coloured block", maxWords: 4, highlight: true, pop: false, color: "#7C3AED" },+ reveal: { label: "Word by word", blurb: "Each word appears the moment it is said", maxWords: 5, highlight: true, pop: false, color: "#FFFFFF" },+ clean: { label: "Clean", blurb: "Classic subtitles: easy to read, nothing moves", maxWords: 8, highlight: false, pop: false, color: "#FFFFFF" },+ boxed: { label: "Boxed", blurb: "White words on a dark band, readable over anything", maxWords: 7, highlight: false, pop: false, color: "#FFFFFF" },+} as const;+export type CaptionStyle = keyof typeof CAPTION_STYLES;+// A preset, or how far down the frame the middle of the caption sits: 0 = top edge, 100 = bottom edge.+export type CaptionPosition = "bottom" | "middle" | "top" | number;+export type CaptionSize = "small" | "medium" | "large";++export interface CaptionOptions {+ style: CaptionStyle;+ position: CaptionPosition;+ size: CaptionSize;+ color?: string;+ text?: string;+ language?: string;+}++// Letter size as a share of the frame's short side, so a 9:16 phone video and a 16:9 landscape one read the same.+const FONT = { bold: 7.2, highlight: 6.2, reveal: 6.4, clean: 4.6, boxed: 4.6 };+const CHAR_EM = { bold: 0.74, highlight: 0.56, reveal: 0.56, clean: 0.52, boxed: 0.52 };+const SIZE = { small: 0.82, medium: 1, large: 1.2 };++/* ---------- hearing the words ---------- */++const MODEL_PREFERENCE = [+ // English-only models time words best. large-v3-turbo is the most accurate listener but placed "picks" 0.6 s+ // early in a test where small.en was 30 ms out, so it comes last.+ "ggml-small.en.bin",+ "ggml-base.en.bin",+ "ggml-medium.en.bin",+ "ggml-small.bin",+ "ggml-base.bin",+ "ggml-medium.bin",+ "ggml-large-v3-turbo.bin",+ "ggml-large-v3.bin",+];++function findModel(language: string): string {+ if (process.env.FLOW_MCP_WHISPER_MODEL) return process.env.FLOW_MCP_WHISPER_MODEL;+ const dirs = [MODEL_DIR, join(homedir(), ".cache", "whisper-models"), join(homedir(), ".cache", "whisper.cpp")];+ const found = MODEL_PREFERENCE.flatMap((name) => dirs.map((d) => join(d, name))).filter((p) => existsSync(p));+ // An English-only model cannot hear another language, so prefer a multilingual one when one is asked for.+ const wantOther = language !== "auto" && language !== "en";+ const pick = (wantOther ? found.find((p) => !p.includes(".en.")) : undefined) ?? found[0];+ if (!pick)+ throw new Error(+ `Captions need a speech model to hear the words. Download ggml-small.en.bin (466 MB) or ggml-base.en.bin (148 MB) from huggingface.co/ggerganov/whisper.cpp and put it in ${MODEL_DIR}.`,+ );+ return pick;+}++const WHISPER_HINT = IS_MAC+ ? "brew install whisper-cpp"+ : IS_WIN+ ? "download whisper-cli from github.com/ggml-org/whisper.cpp/releases and put it on your PATH (or set FLOW_MCP_WHISPER)"+ : "install whisper.cpp so whisper-cli is on your PATH";++// What the panel needs to know before offering captions, and the fix for whatever is missing.+export async function captionSetup(): Promise<{ ready: boolean; whisper: boolean; whisper_hint?: string; model?: string; models_dir: string }> {+ const whisper = await run(WHISPER, ["--help"]).then(+ () => true,+ (err: RunError) => err.code !== "ENOENT",+ );+ let model: string | undefined;+ try {+ model = basename(findModel("auto"));+ } catch {+ model = undefined;+ }+ return { ready: whisper && Boolean(model), whisper, whisper_hint: whisper ? undefined : WHISPER_HINT, model, models_dir: MODEL_DIR };+}++// The one-click "Get the speech model" in the panel: base.en from whisper.cpp's own model page, 148 MB.+let fetching: Promise<{ model: string; size: number }> | null = null;+export function downloadSpeechModel(): Promise<{ model: string; size: number }> {+ fetching ??= (async () => {+ const name = "ggml-base.en.bin";+ const dest = join(MODEL_DIR, name);+ if (existsSync(dest)) return { model: name, size: statSync(dest).size };+ mkdirSync(MODEL_DIR, { recursive: true });+ const res = await fetch(`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${name}`);+ if (!res.ok || !res.body) throw new Error(`The speech model could not be downloaded (${res.status}). Try again in a moment.`);+ const part = `${dest}.part`;+ await pipeline(Readable.fromWeb(res.body as unknown as ReadableStream), createWriteStream(part));+ const size = statSync(part).size;+ if (size < 100_000_000) {+ rmSync(part, { force: true });+ throw new Error("The speech model arrived incomplete. Try again.");+ }+ renameSync(part, dest);+ return { model: name, size };+ })().finally(() => {+ fetching = null;+ });+ return fetching;+}++async function probe(file: string): Promise<{ width: number; height: number; duration: number; audio?: string }> {+ if (!existsSync(file)) throw new Error(`No video at ${file}.`);+ const { stdout } = await run(+ FFPROBE,+ ["-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height:stream_side_data=rotation:stream_tags=rotate:format=duration", "-of", "json", file],+ BIG,+ ).catch((err: NodeJS.ErrnoException) => {+ if (err.code === "ENOENT") throw new Error(`ffmpeg is not installed. Install it with: ${FFMPEG_HINT}`);+ throw new Error(`"${basename(file)}" isn't a playable video.`);+ });+ const data = JSON.parse(stdout) as {+ streams: { codec_type: string; codec_name?: string; width?: number; height?: number; side_data_list?: { rotation?: number }[]; tags?: { rotate?: string } }[];+ format: { duration?: string };+ };+ const v = data.streams.find((s) => s.codec_type === "video");+ if (!v?.width || !v.height) throw new Error(`"${basename(file)}" has no picture to put captions on.`);+ // Phone videos are often stored sideways with a rotation flag; ffmpeg turns them upright, so measure them upright.+ const rotation = Math.abs(Number(v.side_data_list?.find((d) => d.rotation !== undefined)?.rotation ?? v.tags?.rotate ?? 0)) % 180;+ const [width, height] = rotation === 90 ? [v.height, v.width] : [v.width, v.height];+ return { width, height, duration: Number(data.format.duration ?? 0), audio: data.streams.find((s) => s.codec_type === "audio")?.codec_name };+}++// whisper.cpp's word-sized segments (-ml 1) run each word into the next, hiding every pause. Its tokens keep the real+// gaps, so words are rebuilt from those: a token that starts with a space starts a new word, anything else (", 't")+// belongs to the word before it.+function wordsFromTokens(json: { transcription: { tokens?: { text: string; offsets: { from: number; to: number } }[] }[] }): Word[] {+ const words: Word[] = [];+ for (const seg of json.transcription) {+ for (const t of seg.tokens ?? []) {+ if (/^\s*\[_/.test(t.text)) continue;+ const clean = t.text.trim();+ if (!clean) continue;+ const last = words.at(-1);+ if (last && (!/^\s/.test(t.text) || /^[.,!?;:%)\]}"'»…-]/.test(clean))) {+ last.text += clean;+ last.end = t.offsets.to / 1000;+ } else words.push({ text: clean, start: t.offsets.from / 1000, end: t.offsets.to / 1000 });+ }+ }+ // Drop what whisper writes for non-speech: [MUSIC], (laughs), ♪.+ return words.filter((w) => !/^[[(♪*].*[\])♪*]$|^♪+$/.test(w.text));+}++export async function transcribe(video: string, language = "auto"): Promise<Transcript> {+ const info = await probe(video);+ if (!info.audio) throw new Error(`"${basename(video)}" has no sound, so there are no words to caption.`);+ const model = findModel(language);+ const lang = basename(model).includes(".en.") ? "en" : language;+ const st = statSync(video);+ const key = createHash("sha1").update(`${video}|${st.size}|${st.mtimeMs}|${basename(model)}|${lang}`).digest("hex").slice(0, 16);+ const cached = join(CACHE_DIR, `${key}.json`);+ if (existsSync(cached)) return JSON.parse(readFileSync(cached, "utf8")) as Transcript;++ const work = mkdtempSync(join(tmpdir(), "flow-captions-"));+ try {+ const wav = join(work, "audio.wav");+ await run(FFMPEG, ["-v", "error", "-y", "-i", video, "-vn", "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav], BIG);+ const threads = String(Math.max(2, Math.min(8, cpus().length - 1)));+ await run(WHISPER, ["-m", model, "-f", wav, "-l", lang, "-t", threads, "-ojf", "-of", join(work, "words"), "-np"], BIG).catch((err: RunError) => {+ if (err.code === "ENOENT") throw new Error(`Captions need whisper.cpp to hear the words. Install it: ${WHISPER_HINT}.`);+ throw new Error(`whisper.cpp could not read the sound: ${String(err.stderr ?? err.message).trim().split("\n").at(-1)}`);+ });+ const json = JSON.parse(readFileSync(join(work, "words.json"), "utf8")) as Parameters<typeof wordsFromTokens>[0] & { result?: { language?: string } };+ const words = wordsFromTokens(json);+ if (!words.length) throw new Error(`No speech was heard in "${basename(video)}".`);+ const out: Transcript = { words, text: words.map((w) => w.text).join(" "), language: json.result?.language ?? lang, model: basename(model) };+ mkdirSync(CACHE_DIR, { recursive: true });+ writeFileSync(cached, JSON.stringify(out));+ return out;+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+}++/* ---------- fixing the words ---------- */++const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}']+/gu, "");++// Lines up a corrected transcript with the timed one. Every word that still matches keeps its timing; new or changed+// words are spread evenly over the gap they fill, so fixing "flo" to "Flow" or adding a missed word just works.+export function alignText(timed: Word[], text: string): Word[] {+ const toks: { text: string; br: boolean }[] = [];+ text.split("\n").forEach((line, li) =>+ line+ .split(/\s+/)+ .filter(Boolean)+ .forEach((t, i) => toks.push({ text: t, br: li > 0 && i === 0 })),+ );+ if (!toks.length) return [];+ const a = timed.map((w) => norm(w.text));+ const b = toks.map((t) => norm(t.text));+ const n = a.length;+ const m = b.length;+ const match = new Array<number>(m).fill(-1);+ if (n * m <= 25_000_000) {+ // Longest common subsequence; 25 M cells is roughly an hour of speech on either side.+ const W = m + 1;+ const L = new Uint16Array((n + 1) * W);+ for (let i = n - 1; i >= 0; i--)+ for (let j = m - 1; j >= 0; j--) L[i * W + j] = a[i] && a[i] === b[j] ? L[(i + 1) * W + j + 1] + 1 : Math.max(L[(i + 1) * W + j], L[i * W + j + 1]);+ for (let i = 0, j = 0; i < n && j < m; ) {+ if (a[i] && a[i] === b[j]) match[j++] = i++;+ else if (L[(i + 1) * W + j] >= L[i * W + j + 1]) i++;+ else j++;+ }+ } else {+ // Very long texts: match greedily, looking a little way ahead.+ for (let i = 0, j = 0; j < m; j++) {+ const k = a.slice(i, i + 40).indexOf(b[j]);+ if (b[j] && k >= 0) {+ match[j] = i + k;+ i += k + 1;+ }+ }+ }+ const out: Word[] = toks.map((t, k) => (match[k] >= 0 ? { ...t, start: timed[match[k]].start, end: timed[match[k]].end } : { ...t, start: NaN, end: NaN }));+ for (let k = 0; k < m; ) {+ if (!Number.isNaN(out[k].start)) {+ k++;+ continue;+ }+ let e = k;+ while (e < m && Number.isNaN(out[e].start)) e++;+ const from = k > 0 ? out[k - 1].end : (timed[0]?.start ?? 0);+ const to = e < m ? out[e].start : Math.max(from + 0.35 * (e - k), timed.at(-1)?.end ?? 0);+ const step = Math.max(0.05, (to - from) / (e - k));+ for (let q = k; q < e; q++) {+ out[q].start = from + step * (q - k);+ out[q].end = from + step * (q - k + 1);+ }+ k = e;+ }+ return out;+}++/* ---------- laying out captions ---------- */++interface State {+ words: string[];+ active: number;+ scale: number;+ from: number;+ to: number;+}++function paginate(words: Word[], maxWords: number, maxChars: number): Word[][] {+ const pages: Word[][] = [];+ let cur: Word[] = [];+ let chars = 0;+ for (const w of words) {+ const prev = cur.at(-1);+ const brk =+ prev !== undefined &&+ (w.br ||+ cur.length >= maxWords ||+ chars + w.text.length > maxChars ||+ /[.!?…]["')\]]*$/.test(prev.text) ||+ /[,;:]$/.test(prev.text) ||+ w.start - prev.end > 0.6);+ if (brk) {+ pages.push(cur);+ cur = [];+ chars = 0;+ }+ cur.push(w);+ chars += w.text.length + 1;+ }+ if (cur.length) pages.push(cur);+ return pages;+}++function layout(words: Word[], style: CaptionStyle, width: number, height: number, size: CaptionSize): { pages: Word[][]; states: State[] } {+ const s = CAPTION_STYLES[style];+ const u = (Math.min(width, height) / 100) * SIZE[size];+ const perLine = Math.max(8, Math.floor(boxWidth(style, width, height) / (FONT[style] * u * CHAR_EM[style])));+ const pages = paginate(words, s.maxWords, perLine * 2);+ // Bold capitals read better without commas and full stops; question and exclamation marks stay.+ const shown = (t: string) => (style === "bold" ? t.replace(/[.,;:]+$/, "") : t);+ const states: State[] = [];+ let clock = 0;+ const push = (st: State) => {+ st.from = Math.max(st.from, clock);+ if (st.to - st.from < 0.02) return;+ states.push(st);+ clock = st.to;+ };+ pages.forEach((p, pi) => {+ const start = p[0].start;+ const next = pages[pi + 1]?.[0].start;+ let end = p[p.length - 1].end + 0.25;+ // Close a short gap to the next caption instead of flashing an empty frame; never overlap it.+ if (next !== undefined) end = next - end < 0.5 ? next : Math.min(end, next);+ const texts = p.map((w) => shown(w.text));+ const first = states.length;+ if (!s.highlight) push({ words: texts, active: -1, scale: 1, from: start, to: end });+ else p.forEach((w, i) => push({ words: texts, active: i, scale: 1, from: i === 0 ? start : w.start, to: i < p.length - 1 ? p[i + 1].start : end }));+ // A quick grow-in for each new caption: three frames, then still.+ const lead = states[first];+ if (s.pop && lead && lead.to - lead.from > 0.2) {+ const t = lead.from;+ states.splice(+ first,+ 1,+ { ...lead, scale: 0.78, from: t, to: t + 0.05 },+ { ...lead, scale: 0.94, from: t + 0.05, to: t + 0.1 },+ { ...lead, scale: 1.05, from: t + 0.1, to: t + 0.15 },+ { ...lead, from: t + 0.15 },+ );+ }+ });+ return { pages, states };+}++const boxWidth = (style: CaptionStyle, width: number, height: number) =>+ width * (height > width ? 0.86 : style === "clean" || style === "boxed" ? 0.8 : 0.72);++function textOn(hex: string): string {+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.6 ? "#111111" : "#FFFFFF";+}++function pageHtml(style: CaptionStyle, o: { width: number; height: number; position: CaptionPosition; size: CaptionSize; color: string; background?: string }): string {+ const { width: W, height: H } = o;+ const vertical = H > W;+ const font = FONT[style] * (Math.min(W, H) / 100) * SIZE[o.size];+ const place =+ typeof o.position === "number"+ ? `top:${Math.min(96, Math.max(4, o.position))}%;transform:translate(-50%,-50%)`+ : o.position === "middle"+ ? "top:50%;transform:translate(-50%,-50%)"+ : o.position === "top"+ ? `top:${vertical ? 13 : 7}%;transform:translateX(-50%)`+ : `bottom:${vertical ? 21 : 8}%;transform:translateX(-50%)`;+ const sans = `system-ui,-apple-system,"Segoe UI","Helvetica Neue",Arial,sans-serif`;+ // The outline is a copy of each word drawn underneath with a thick stroke, so it never eats into the letters.+ const outline = (w: string) => `.w{position:relative;display:inline-block}.w::before{content:attr(data-t);position:absolute;left:0;top:0;z-index:-1;-webkit-text-stroke:${w} #000;color:#000}`;+ const css = {+ bold: `.cap{font:900 ${font}px/1.12 "Arial Black","Arial Bold",Impact,${sans};text-transform:uppercase;letter-spacing:.01em;color:#fff}+ ${outline(".17em")}.w::before{text-shadow:0 .07em 0 rgba(0,0,0,.55)}.w{margin:0 .07em}.w.on{color:var(--hl);transform:scale(1.06)}`,+ highlight: `.cap{font:800 ${font}px/1.32 ${sans};color:#fff}+ .w{display:inline-block;padding:.02em .13em .07em;margin:0 -.04em;border-radius:.2em;text-shadow:0 .05em .2em rgba(0,0,0,.75)}.w.on{background:var(--hl);color:var(--on);text-shadow:none}`,+ reveal: `.cap{font:800 ${font}px/1.2 ${sans};color:#fff}${outline(".13em")}.later{visibility:hidden}.w.on{color:var(--hl)}`,+ clean: `.cap{font:700 ${font}px/1.25 ${sans};color:#fff;text-shadow:0 .04em .12em rgba(0,0,0,.9),0 0 .35em rgba(0,0,0,.55)}`,+ boxed: `.cap{font:700 ${font}px/1.55 ${sans};color:#fff}.inner{display:inline;background:rgba(0,0,0,.74);padding:.12em .45em;border-radius:.28em;-webkit-box-decoration-break:clone;box-decoration-break:clone}`,+ }[style];+ return `<!doctype html><html><head><meta charset="utf-8"><style>+html,body{margin:0;width:${W}px;height:${H}px;overflow:hidden;background:${o.background ? `#000 url(${o.background}) center/100% 100% no-repeat` : "transparent"}}+.cap{position:absolute;left:50%;width:${boxWidth(style, W, H)}px;text-align:center;text-wrap:balance;--hl:${o.color};--on:${textOn(o.color)};${place};-webkit-font-smoothing:antialiased}+.inner{display:block;transform-origin:50% 60%}+${css}+</style></head><body><div class="cap"><div class="inner" id="inner"></div></div><script>+const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);+window.paint = (s) => {+ const el = document.getElementById("inner");+ el.style.transform = s.scale === 1 ? "" : "scale(" + s.scale + ")";+ el.innerHTML = s.words.map((w, i) => '<span class="w' + (i === s.active ? " on" : "") + (${style === "reveal"} && i > s.active ? " later" : "") + '" data-t="' + esc(w) + '">' + esc(w) + "</span>").join(" ");+};+</script></body></html>`;+}++/* ---------- drawing ---------- */++let browser: Promise<Browser> | null = null;+let idle: NodeJS.Timeout | undefined;++// One headless Chrome, with its own throwaway profile, kept warm for a minute and a half so previews are quick.+async function drawingBrowser(): Promise<Browser> {+ clearTimeout(idle);+ browser ??= chromium.launch({ executablePath: chromeExecutable(), headless: true, args: ["--hide-scrollbars", "--force-color-profile=srgb"] }).catch((err) => {+ browser = null;+ throw err;+ });+ return browser;+}+function releaseBrowser(): void {+ clearTimeout(idle);+ idle = setTimeout(async () => {+ const b = await browser?.catch(() => null);+ browser = null;+ await b?.close().catch(() => {});+ }, 90_000);+ idle.unref?.();+}++async function withPage<T>(width: number, height: number, html: string, use: (page: Page) => Promise<T>): Promise<T> {+ const b = await drawingBrowser();+ const ctx = await b.newContext({ viewport: { width, height }, deviceScaleFactor: 1 });+ try {+ const page = await ctx.newPage();+ await page.setContent(html, { waitUntil: "load" });+ await page.evaluate(() => document.fonts.ready.then(() => true));+ return await use(page);+ } finally {+ await ctx.close().catch(() => {});+ releaseBrowser();+ }+}++/* ---------- putting it together ---------- */++const pickColor = (o: CaptionOptions) => (o.color && /^#[0-9a-f]{6}$/i.test(o.color) ? o.color : CAPTION_STYLES[o.style].color);++async function timedWords(video: string, o: CaptionOptions): Promise<{ transcript: Transcript; words: Word[] }> {+ const transcript = await transcribe(video, o.language ?? "auto");+ const edited = o.text?.trim();+ const same = edited !== undefined && norm(edited.replace(/\s+/g, "")) === norm(transcript.text.replace(/\s+/g, "")) && !edited.includes("\n");+ return { transcript, words: edited && !same ? alignText(transcript.words, edited) : transcript.words };+}++// One still of the real video with the real captions on it, so the panel shows exactly what will be made.+export async function previewCaptions(video: string, o: CaptionOptions): Promise<{ image: string; at: number }> {+ const info = await probe(video);+ const { words } = await timedWords(video, o);+ const { pages, states } = layout(words, o.style, info.width, info.height, o.size);+ // A caption of a few words, about a third of the way in, mid-sentence.+ const want = (pages[0]?.[0].start ?? 0) + ((pages.at(-1)?.at(-1)?.end ?? 0) - (pages[0]?.[0].start ?? 0)) * 0.33;+ const page = pages.filter((p) => p.length >= Math.min(2, CAPTION_STYLES[o.style].maxWords)).sort((p, q) => Math.abs(p[0].start - want) - Math.abs(q[0].start - want))[0] ?? pages[0];+ const mid = page ? page[Math.floor((page.length - 1) / 2)] : undefined;+ const state = states.find((s) => mid && s.from <= mid.start + 0.01 && s.to > mid.start && s.scale === 1) ?? states.find((s) => s.scale === 1);+ const at = state ? (state.from + state.to) / 2 : Math.min(1, info.duration / 2);++ mkdirSync(CACHE_DIR, { recursive: true });+ const key = createHash("sha1").update(video).digest("hex").slice(0, 12);+ const frame = join(CACHE_DIR, `frame-${key}.jpg`);+ await run(FFMPEG, ["-v", "error", "-y", "-ss", at.toFixed(3), "-i", video, "-frames:v", "1", "-q:v", "3", frame], BIG);+ const background = `data:image/jpeg;base64,${readFileSync(frame).toString("base64")}`;+ const image = join(CACHE_DIR, `preview-${key}.jpg`);+ await withPage(info.width, info.height, pageHtml(o.style, { ...info, position: o.position, size: o.size, color: pickColor(o), background }), async (p) => {+ if (state) await p.evaluate((s) => (window as unknown as { paint: (s: unknown) => void }).paint(s), state);+ await p.screenshot({ path: image, type: "jpeg", quality: 85 });+ });+ rmSync(frame, { force: true });+ return { image, at };+}++const stamp = (t: number) => {+ const ms = Math.max(0, Math.round(t * 1000));+ const p = (n: number, w = 2) => String(n).padStart(w, "0");+ return `${p(Math.floor(ms / 3_600_000))}:${p(Math.floor(ms / 60_000) % 60)}:${p(Math.floor(ms / 1000) % 60)},${p(ms % 1000, 3)}`;+};++export interface CaptionResult {+ output: string;+ srt: string;+ captions: number;+ words: number;+ duration: number;+ transcript: string;+ model: string;+}++export async function burnCaptions(video: string, o: CaptionOptions, output: string): Promise<CaptionResult> {+ const info = await probe(video);+ const { transcript, words } = await timedWords(video, o);+ const { pages, states } = layout(words, o.style, info.width, info.height, o.size);+ if (!states.length) throw new Error("There are no words to put on screen.");++ const work = mkdtempSync(join(tmpdir(), "flow-captions-"));+ try {+ // Draw every distinct caption once, as a transparent picture the size of the video.+ const files = new Map<string, string>();+ await withPage(info.width, info.height, pageHtml(o.style, { ...info, position: o.position, size: o.size, color: pickColor(o) }), async (p) => {+ await p.screenshot({ path: join(work, "blank.png"), omitBackground: true });+ for (const s of states) {+ const id = JSON.stringify([s.words, s.active, s.scale]);+ if (files.has(id)) continue;+ const name = `c${String(files.size + 1).padStart(5, "0")}.png`;+ await p.evaluate((st) => (window as unknown as { paint: (s: unknown) => void }).paint(st), s);+ await p.screenshot({ path: join(work, name), omitBackground: true });+ files.set(id, name);+ }+ });++ // Play those pictures as a second video track with exact timings, and lay it over the original.+ const lines = ["ffconcat version 1.0"];+ let t = 0;+ const add = (file: string, dur: number) => lines.push(`file '${file}'`, `duration ${dur.toFixed(3)}`);+ for (const s of states) {+ if (s.from - t > 0.0005) add("blank.png", s.from - t);+ add(files.get(JSON.stringify([s.words, s.active, s.scale]))!, s.to - s.from);+ t = s.to;+ }+ add("blank.png", Math.max(0.05, info.duration - t + 1));+ lines.push("file 'blank.png'");+ writeFileSync(join(work, "captions.ffconcat"), lines.join("\n") + "\n");++ await run(+ FFMPEG,+ [+ "-v", "error", "-y",+ "-i", video,+ "-f", "concat", "-safe", "0", "-i", join(work, "captions.ffconcat"),+ "-filter_complex", "[0:v][1:v]overlay=0:0:format=auto:eof_action=pass[v]",+ "-map", "[v]", "-map", "0:a?",+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p",+ "-c:a", info.audio === "aac" ? "copy" : "aac", ...(info.audio === "aac" ? [] : ["-b:a", "192k"]),+ "-movflags", "+faststart",+ output,+ ],+ BIG,+ ).catch((err: RunError) => {+ throw new Error(`ffmpeg could not add the captions: ${String(err.stderr ?? err.message).trim().split("\n").at(-1)}`);+ });++ // The same words as a subtitle file, for YouTube and other players that show their own captions.+ const srt = output.replace(/\.[^.]+$/, ".srt");+ writeFileSync(+ srt,+ pages+ .map((p, i) => {+ const next = pages[i + 1]?.[0].start;+ const end = next !== undefined ? Math.min(p[p.length - 1].end + 0.25, next) : p[p.length - 1].end + 0.25;+ return `${i + 1}\n${stamp(p[0].start)} --> ${stamp(end)}\n${p.map((w) => w.text).join(" ")}\n`;+ })+ .join("\n"),+ );+ return { output, srt, captions: pages.length, words: words.length, duration: info.duration, transcript: words.map((w) => w.text).join(" "), model: transcript.model };+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+}++// "clip.mp4" -> "<dir>/clip-captions.mp4", then -captions-2 and so on, so nothing is ever overwritten.+export function captionedName(dir: string, video: string): string {+ const stem = basename(video, extname(video)).replace(/[^\w.-]+/g, "_");+ for (let i = 1; ; i++) {+ const out = join(dir, `${stem}-captions${i > 1 ? `-${i}` : ""}.mp4`);+ if (!existsSync(out)) return out;+ }+}diff --git a/src/chrome.ts b/src/chrome.tsindex 3dd6ca0..ea7208f 100644--- a/src/chrome.ts+++ b/src/chrome.ts@@ -43,11 +43,14 @@ async function cdpUp(): Promise<boolean> {// Real Chrome with a dedicated profile: Google sign-in works normally and the// session persists, while the user's everyday profile is never touched.-async function launchChrome(): Promise<void> {+export function chromeExecutable(): string {const chromePath = CHROME_PATHS.find((p) => existsSync(p));- if (!chromePath) {- throw new Error("Google Chrome not found. Set FLOW_MCP_CHROME to the Chrome executable path.");- }+ if (!chromePath) throw new Error("Google Chrome not found. Set FLOW_MCP_CHROME to the Chrome executable path.");+ return chromePath;+}++async function launchChrome(): Promise<void> {+ const chromePath = chromeExecutable();mkdirSync(PROFILE_DIR, { recursive: true });const child = spawn(chromePath,diff --git a/src/core.ts b/src/core.tsindex 2edff70..41f197c 100644--- a/src/core.ts+++ b/src/core.ts@@ -1,10 +1,11 @@import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";import { homedir } from "node:os";-import { isAbsolute, join, relative, resolve } from "node:path";+import { dirname, isAbsolute, join, relative, resolve } from "node:path";import { z } from "zod";import { assemble, localVoices, speakLocally } from "./assemble.js";import { GEMINI_VOICES, geminiKey, saveGeminiKey, speakWithGemini } from "./gemini.js";import { extractLastFrame } from "./chain.js";+import { burnCaptions, captionedName, captionSetup, downloadSpeechModel, previewCaptions, transcribe } from "./captions.js";import { characterLook, createCharacter, downloadAsset, trashAsset, editCharacter, getFlowState, listAssets, listCharacters, rememberCharacter, runAgentBatch, runContinue, runEdit, runGeneration } from "./flow.js";import { JobQueue, type Job } from "./queue.js";import { BIN, COMPUTER, IS_MAC, IS_WIN, moveToBin } from "./platform.js";@@ -50,6 +51,24 @@ const sceneSchema = z.object({});// Raw shapes double as MCP input schemas and, wrapped in z.object, as HTTP body validators.+const captionFields = {+ video: z.string().min(1).describe("Absolute path of the video to caption: any MP4 or MOV on this computer, such as a film made with flow_assemble."),+ style: z+ .enum(["bold", "highlight", "reveal", "clean", "boxed"])+ .default("bold")+ .describe(+ "bold: big capitals, 1-3 words at a time, the spoken word lights up (the short-form look). highlight: the spoken word sits on a coloured block. reveal: words appear as they are said. clean: classic subtitles. boxed: white words on a dark band.",+ ),+ position: z+ .union([z.enum(["bottom", "middle", "top"]), z.number().min(0).max(100)])+ .default("bottom")+ .describe("bottom, middle or top - or a number for an exact height: how far down the frame the middle of the caption sits, 0 = top edge, 100 = bottom edge."),+ size: z.enum(["small", "medium", "large"]).default("medium"),+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("Highlight colour as #RRGGBB, for bold, highlight and reveal."),+ text: z.string().max(50_000).optional().describe("Corrected words, to fix anything misheard. Timings are kept for every word that still matches; a line break starts a new caption."),+ language: z.string().default("auto").describe("Spoken language code (en, es, de...) or auto."),+};+export const shapes = {status: { detailed: z.boolean().default(true).describe("false skips the plan/credits readout, which briefly opens Flow's account panel.") },generate: {@@ -83,6 +102,14 @@ export const shapes = {output_name: z.string().default("final"),hold_last_frame: z.boolean().default(true).describe("Freeze the final frame so a longer voiceover is not cut off."),},+ transcribe: { video: z.string().min(1), language: z.string().default("auto") },+ caption_preview: captionFields,+ captions: {+ ...captionFields,+ project: z.string().optional().describe("Films folder to save into. Default: the video's own folder when it is already in the films folder, otherwise 'Captions'."),+ },+ caption_setup: {},+ caption_model: {},agent: {project: z.string().min(1).describe("Folder name for the downloaded images."),scenes: z.array(z.string().min(1)).min(1).max(50).describe("One image description per scene, in order."),@@ -219,6 +246,11 @@ export interface Core {continue_shot(a: Args<"continue_shot">): Promise<unknown>;agent(a: Args<"agent">): Promise<unknown>;outputs(): Promise<unknown>;+ transcribe(a: Args<"transcribe">): Promise<unknown>;+ caption_preview(a: Args<"caption_preview">): Promise<unknown>;+ captions(a: Args<"captions">): Promise<unknown>;+ caption_setup(): Promise<unknown>;+ caption_model(): Promise<unknown>;}// Flow's own voices: still offered when giving a character a voice, but narration no longer goes through Flow.@@ -390,6 +422,34 @@ export class LocalCore implements Core {return assemble({ dir: projectDir(project), ...rest });}+ // Captions never touch Flow or its queue: whisper.cpp hears the words, a headless Chrome of its own draws them.+ async transcribe({ video, language }: Args<"transcribe">) {+ const t = await transcribe(video, language);+ return { text: t.text, words: t.words.length, language: t.language, model: t.model };+ }++ async caption_preview(a: Args<"caption_preview">) {+ return previewCaptions(a.video, a);+ }++ async captions({ project, ...a }: Args<"captions">) {+ // Save next to the video when it is already one of the user's films, otherwise in a Captions folder.+ const rel = relative(OUTPUT_ROOT, dirname(a.video));+ const inFilms = rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);+ const dir = project ? projectDir(project) : inFilms ? dirname(a.video) : projectDir("Captions");+ mkdirSync(dir, { recursive: true });+ return burnCaptions(a.video, a, captionedName(dir, a.video));+ }++ async caption_setup() {+ return captionSetup();+ }++ // Panel only, like set_key: a 148 MB download should be the user's own click.+ async caption_model() {+ return downloadSpeechModel();+ }+// Everything already downloaded, newest project first, so the panel can show past work after a restart.async outputs() {if (!existsSync(OUTPUT_ROOT)) return { root: OUTPUT_ROOT, projects: [] };diff --git a/src/index.ts b/src/index.tsindex 09a559e..0bae12b 100644--- a/src/index.ts+++ b/src/index.ts@@ -295,4 +295,16 @@ server.registerTool((args) => reply(patient("flow_assemble", core.assemble(args))),);+server.registerTool(+ "flow_captions",+ {+ title: "Add captions to a video",+ description:+ "Burn spoken-word captions into a video, in the style short-form apps use, for landscape or vertical footage (local and free: whisper.cpp hears the words on this computer, nothing is uploaded). Styles: bold (big capitals, the spoken word lights up), highlight, reveal, clean, boxed. Saves <name>-captions.mp4 plus an .srt, and returns the transcript: if a word was misheard, call again with the corrected `text` - matching words keep their timing.",+ inputSchema: shapes.captions,+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ },+ (args) => reply(patient("flow_captions", core.captions(args))),+);+await server.connect(new StdioServerTransport());diff --git a/src/playbook.ts b/src/playbook.tsindex e2055b5..ed8ca8d 100644--- a/src/playbook.ts+++ b/src/playbook.ts@@ -5,6 +5,7 @@ export const PLAYBOOK = {"Plan the whole piece as scenes of one shot each, then send them in ONE flow_generate call so file numbering and chaining work.","Tell the user the expected credit total before queueing anything that costs credits.","Call flow_wait repeatedly until finished is true; scenes run one at a time with 25-70 s pauses.",+ "To put the spoken words on screen, call flow_captions on the finished film (style bold for short-form, clean for subtitles). Read the transcript it returns; if a word is misheard, call again with the corrected text.","If an image batch finishes with \"still failed: scene ...\" in its note, call flow_retry with its job id: only those images are made again, under their own scene numbers.","No call blocks for more than about 45 s. A reply with still_working and a task_id means Flow is still busy with it: pass the task_id to flow_wait, and never repeat the call.",],diff --git a/src/remote.ts b/src/remote.tsindex 8bf3224..afc3d1e 100644--- a/src/remote.ts+++ b/src/remote.ts@@ -35,6 +35,11 @@ export class RemoteCore implements Core {continue_shot = (a: unknown) => call("continue_shot", a);agent = (a: unknown) => call("agent", a);outputs = () => call("outputs", {});+ transcribe = (a: unknown) => call("transcribe", a);+ caption_preview = (a: unknown) => call("caption_preview", a);+ captions = (a: unknown) => call("captions", a);+ caption_setup = () => call("caption_setup", {});+ caption_model = () => call("caption_model", {});// Long waits are split up so no single HTTP request outlives fetch's header timeout.async wait(a: { job_ids?: string[]; timeout_seconds: number }): Promise<unknown> {diff --git a/src/server.ts b/src/server.tsindex 113b534..0b497ca 100644--- a/src/server.ts+++ b/src/server.ts@@ -4,6 +4,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:htimport { basename, extname, join, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";import { z } from "zod";+import { CACHE_DIR as CAPTIONS_DIR } from "./captions.js";import { HOME_DIR } from "./chrome.js";import { OUTPUT_ROOT, shapes, type Core } from "./core.js";@@ -43,7 +44,7 @@ function readBody(req: IncomingMessage, limit: number): Promise<Buffer> {const inside = (file: string, dir: string) => resolve(file).startsWith(resolve(dir) + sep);function sendMedia(req: IncomingMessage, res: ServerResponse, file: string) {- if (!(inside(file, OUTPUT_ROOT) || inside(file, UPLOAD_DIR)) || !existsSync(file)) return json(res, 404, { error: "Not found." });+ if (!(inside(file, OUTPUT_ROOT) || inside(file, UPLOAD_DIR) || inside(file, CAPTIONS_DIR)) || !existsSync(file)) return json(res, 404, { error: "Not found." });const { size } = statSync(file);const type = MIME[extname(file).toLowerCase()] ?? "application/octet-stream";const range = req.headers.range?.match(/bytes=(\d*)-(\d*)/);diff --git a/studio/index.html b/studio/index.htmlindex 58019ea..9b59551 100644--- a/studio/index.html+++ b/studio/index.html@@ -146,6 +146,29 @@ audio{width:100%;margin-top:8px;filter:invert(1) hue-rotate(180deg)}.cast-card b{display:block;font:800 20px var(--display);letter-spacing:.04em}.cast-card .grow{flex:1;min-width:0}.pickrow{display:grid;gap:8px}+.capstyles{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px}+.capstyle{display:flex;flex-direction:column;gap:8px;padding:10px;text-align:left;color:var(--bone);background:var(--ink);border:2px solid var(--line);border-radius:12px;cursor:pointer;font:500 16px var(--body)}+.capstyle:hover{border-color:var(--bone)}+.capstyle.on{border-color:var(--tally);box-shadow:inset 0 0 0 2px var(--tally)}+.capstyle b{font:800 22px var(--display);letter-spacing:.05em;text-transform:uppercase}+.capstyle small{color:var(--dim);font-size:15px;line-height:1.3}+.demo{height:80px;border-radius:8px;display:flex;align-items:center;justify-content:center;padding:0 8px;text-align:center;background:linear-gradient(135deg,#46576b,#151b22);color:#fff;overflow:hidden}+.demo em,.demo i{font-style:normal}+.d-bold{font:900 25px/1.05 "Arial Black",Impact,sans-serif;text-transform:uppercase;text-shadow:2px 2px 0 #000,-2px 2px 0 #000,2px -2px 0 #000,-2px -2px 0 #000,0 3px 0 #000}+.d-bold em{color:var(--hl)}+.d-highlight{font:800 23px system-ui,sans-serif}+.d-highlight em{background:var(--hl);color:#fff;padding:0 .2em;border-radius:.2em}+.d-reveal{font:800 23px system-ui,sans-serif;text-shadow:2px 2px 0 #000,-2px 2px 0 #000,2px -2px 0 #000,-2px -2px 0 #000}+.d-reveal i{opacity:.22}+.d-clean{font:700 21px system-ui,sans-serif;text-shadow:0 1px 4px #000}+.d-boxed{font:700 20px system-ui,sans-serif}+.d-boxed span{background:rgba(0,0,0,.78);padding:.12em .45em;border-radius:.28em}+.swatches{display:flex;gap:12px;flex-wrap:wrap}+.swatches button{width:54px;height:54px;border-radius:50%;border:3px solid var(--line);cursor:pointer}+.swatches button.on{border-color:var(--bone);box-shadow:0 0 0 3px var(--tally)}+.capprev{border-radius:12px;background:#000;overflow:hidden;display:flex;align-items:center;justify-content:center;min-height:140px;padding:0}+.capprev img{display:block;max-width:100%;max-height:72vh;object-fit:contain;cursor:crosshair}+.capprev .empty{padding:24px;text-align:center}@media(min-width:760px){.pickrow{grid-template-columns:1fr 1fr}}</style></head><body>@@ -165,6 +188,7 @@ audio{width:100%;margin-top:8px;filter:invert(1) hue-rotate(180deg)}<button data-tab="narrate">Voice<small>narration</small></button><button data-tab="restyle">Restyle<small>edit a clip</small></button><button data-tab="cut">Cut<small>assemble film</small></button>+ <button data-tab="captions">Captions<small>words on screen</small></button><button data-tab="library">Library<small>in Flow</small></button></nav>@@ -331,6 +355,40 @@ audio{width:100%;margin-top:8px;filter:invert(1) hue-rotate(180deg)}</div></section>+ <!-- CAPTIONS -->+ <section class="panel" data-panel="captions">+ <div class="step">Step 6</div>+ <h2>Captions <small>free · local</small></h2>+ <p class="lede">Put the spoken words on screen, the way short-form videos do, on wide or vertical videos. <span data-place="computer">This Mac</span> listens to the video and times every word itself; nothing is uploaded.</p>+ <div id="cap_setup"></div>+ <div class="card">+ <label class="f">Video</label>+ <div id="cap_video" class="cliplist"></div>+ <div class="rowbtns" style="margin-top:8px">+ <button type="button" class="btn small ghost" id="cap_up">Upload a video</button>+ <button type="button" class="btn small ghost" id="cap_film">From my films</button>+ </div>+ <div class="rowbtns" style="flex-wrap:nowrap"><input type="text" id="cap_path" spellcheck="false" placeholder="…or paste where a video is saved" style="flex:1;min-width:0"><button type="button" class="btn small" id="cap_pathgo">Use</button></div>+ <label class="f">Style</label>+ <div class="capstyles" id="cap_styles"></div>+ <div class="grid2">+ <div><label class="f">Position</label><div class="seg" data-seg="cap_pos"></div></div>+ <div><label class="f">Size</label><div class="seg" data-seg="cap_size"></div></div>+ </div>+ <label class="f">Exact height <span id="cap_yOut" style="text-transform:none;letter-spacing:0"></span></label>+ <input type="range" id="cap_y" min="5" max="95" value="80" aria-label="How far down the screen the captions sit">+ <p class="empty" style="margin-top:4px">Drag to place the words anywhere, or tap the preview where you want them.</p>+ <div id="cap_colorWrap"><label class="f">Highlight colour</label><div class="swatches" id="cap_colors"></div></div>+ <label class="f">Preview <span id="cap_previewNote" style="text-transform:none;letter-spacing:0"></span></label>+ <div class="capprev"><img id="cap_preview" alt="Your video with the captions on it" hidden><p class="empty" id="cap_previewEmpty">Pick a video to see your captions on it.</p></div>+ <label class="f" for="cap_text">The words <span id="cap_textNote" style="text-transform:none;letter-spacing:0"></span></label>+ <textarea id="cap_text" placeholder="The words appear here once the video has been listened to."></textarea>+ <p class="empty" style="margin-top:6px">Fix anything misheard: each word keeps its timing. Press Enter to start a new caption at that point.</p>+ <div class="rowbtns"><button class="btn" id="cap_go">Add captions</button></div>+ <div id="cap_out" style="margin-top:16px"></div>+ </div>+ </section>+<!-- LIBRARY --><section class="panel" data-panel="library"><div class="step">Reference</div>@@ -396,6 +454,7 @@ const DEFAULTS = {shots: { project: "MyFilm", model: "Omni 1.1 Flash", aspect: "16:9", duration: 8, resolution: "720p", variants: 1, quality: "original", max: 25, scenes: [blank()] },narrate: { project: "MyFilm", engine: "gemini", geminiVoice: "Charon", macVoice: "Zoe (Premium)", text: "", style: "" },cut: { project: "MyFilm", music: null, voiceover: null, hold: true, clips: [] },+ captions: { video: null, style: "bold", position: "bottom", size: "medium", colors: {}, text: "" },};const S = Object.assign(structuredClone(DEFAULTS), JSON.parse(localStorage.getItem("flow-studio-v2") || "{}"));const save = () => localStorage.setItem("flow-studio-v2", JSON.stringify(S));@@ -409,6 +468,8 @@ function showTab(name) {// Each tab shows the files it can use. Voice has its own narration list and Library its own Flow list, so the// gallery would only be in the way there.$("#galCard").hidden = !GALLERY_KINDS[name];+ if (name === "captions" && LIVE && S.captions.video && capFor !== S.captions.video.path) capListen();+ else if (name === "captions" && LIVE) capReady();if (GAL.length) renderGallery();estimate();window.scrollTo({ top: 0, behavior: "smooth" });@@ -425,6 +486,8 @@ const SEGS = {s_resolution: { get: () => S.shots.resolution, set: (v) => (S.shots.resolution = v), opts: ["360p", "720p"] },s_quality: { get: () => S.shots.quality, set: (v) => (S.shots.quality = v), opts: ["original", "upscaled"], labels: { original: "720p", upscaled: "1080p" } },s_variants: { get: () => S.shots.variants, set: (v) => (S.shots.variants = +v), opts: [1, 2, 3, 4] },+ cap_pos: { get: () => (typeof S.captions.position === "string" ? S.captions.position : ""), set: (v) => { S.captions.position = v; capPreviewSoon(); }, opts: ["bottom", "middle", "top"], labels: { bottom: "Bottom", middle: "Middle", top: "Top" } },+ cap_size: { get: () => S.captions.size, set: (v) => { S.captions.size = v; capPreviewSoon(); }, opts: ["small", "medium", "large"], labels: { small: "Small", medium: "Medium", large: "Large" } },n_engine: { get: () => S.narrate.engine, set: (v) => (S.narrate.engine = v), opts: ["gemini", "mac"], labels: { gemini: "Google AI Studio", get mac() { return PLACE.local_engine; } } },};function renderSegs() {@@ -450,6 +513,7 @@ function slotHtml(kind, i, val, label) {: `<span>${label}</span><span class="two"><button type="button" data-src="upload">Upload</button><button type="button" data-src="flow">${/music|voiceover/.test(kind) ? "My narrations" : "From Flow"}</button></span>`}</div>`;}function setSlot(kind, idx, val) {+ if (kind === "capvideo") return void setCapVideo(val);if (kind === "cast") castImage = val;else if (kind === "music" || kind === "voiceover") S.cut[kind] = val;else if (kind === "clip") { (S.cut.clips ??= []); if (val) S.cut.clips.push(val); }@@ -732,8 +796,11 @@ function renderClips() {}$("#c_clips").addEventListener("click", (e) => { const b = e.target.closest("[data-clipdel]"); if (!b) return; S.cut.clips.splice(+b.dataset.clipdel, 1); save(); renderClips(); });$("#c_addup").onclick = () => { pickTarget = { kind: "clip", i: 0 }; $("#file").accept = "video/*"; $("#file").click(); };-$("#c_addfilm").onclick = async () => {+let filmFor = "cut";+$("#c_addfilm").onclick = () => openFilms("cut");+async function openFilms(target) {if (!guard()) return;+ filmFor = target;$("#picker h2").textContent = "Pick from my films"; $("#picker p.empty").textContent = `Videos already saved on ${PLACE.computer}.`;$("#pickList").innerHTML = `<p class="empty">Reading your films…</p>`; picker.showModal();try {@@ -741,9 +808,9 @@ $("#c_addfilm").onclick = async () => {const vids = projects.flatMap((p) => p.files.filter((f) => f.kind === "video").map((f) => ({ path: f.path, name: `${p.name} / ${f.name}` })));$("#pickList").innerHTML = vids.map((v) => `<button data-film="${esc(v.path)}" data-name="${esc(v.name)}"><span>${esc(v.name)}</span><em>video</em></button>`).join("") || `<p class="empty">No saved videos yet.</p>`;} catch (err) { $("#pickList").innerHTML = `<p class="empty" style="color:var(--bad)">${esc(err.message)}</p>`; }-};+}$("#pickList").addEventListener("click", (e) => { const b = e.target.closest("button[data-audio]"); if (!b || !pickTarget) return; setSlot(pickTarget.kind, pickTarget.i, { path: b.dataset.audio, name: b.dataset.name }); picker.close(); });-$("#pickList").addEventListener("click", (e) => { const b = e.target.closest("button[data-film]"); if (!b) return; (S.cut.clips ??= []).push({ path: b.dataset.film, name: b.dataset.name }); save(); renderClips(); picker.close(); });+$("#pickList").addEventListener("click", (e) => { const b = e.target.closest("button[data-film]"); if (!b) return; if (filmFor === "captions") { picker.close(); return void setCapVideo({ path: b.dataset.film, name: b.dataset.name }); } (S.cut.clips ??= []).push({ path: b.dataset.film, name: b.dataset.name }); save(); renderClips(); picker.close(); });$("#c_vol").oninput = (e) => ($("#c_volOut").textContent = e.target.value + "%");$("#c_clipvol").oninput = (e) => ($("#c_clipVolOut").textContent = e.target.value + "%");$("#c_hold").onchange = (e) => { S.cut.hold = e.target.checked; save(); };@@ -753,12 +820,132 @@ $("#c_go").onclick = async () => {try {const out = await api("assemble", { project: $("#c_project").value.trim() || "MyFilm", clips: S.cut.clips?.length ? S.cut.clips.map((c) => c.path) : undefined, music: S.cut.music?.path, voiceover: S.cut.voiceover?.path, music_volume: +$("#c_vol").value / 100, clip_volume: +$("#c_clipvol").value / 100, hold_last_frame: $("#c_hold").checked, output_name: "final" });$("#c_out").innerHTML = `<video controls playsinline src="${media(out.output)}&t=${Date.now()}" style="width:100%;border-radius:12px;background:#000"></video>- <p class="empty" style="margin-top:8px">${out.clips.length} clip(s) · ${out.duration.toFixed(1)}s${out.held_last_frame ? ` · last frame held ${out.held_last_frame}s for the narration` : ""}<br>${esc(out.output)}</p>`;+ <p class="empty" style="margin-top:8px">${out.clips.length} clip(s) · ${out.duration.toFixed(1)}s${out.held_last_frame ? ` · last frame held ${out.held_last_frame}s for the narration` : ""}<br>${esc(out.output)}</p>+ <div class="rowbtns"><button type="button" class="btn small" data-capthis="${esc(out.output)}">Add captions to this film</button></div>`;loadGallery();} catch (err) { $("#c_out").innerHTML = `<p class="empty" style="color:var(--bad)">${esc(err.message)}</p>`; toast(err.message, true); }b.disabled = false; b.textContent = "Assemble film";};+/* ---------- captions ---------- */+const CAP_STYLES = [+ { id: "bold", name: "Bold pop", blurb: "Big capitals; the spoken word lights up", demo: "Like <em>this</em>" },+ { id: "highlight", name: "Highlight", blurb: "The spoken word on a coloured block", demo: "like <em>this</em> one" },+ { id: "reveal", name: "Word by word", blurb: "Words appear as they are said", demo: "word by <i>word</i>" },+ { id: "clean", name: "Clean", blurb: "Classic subtitles; nothing moves", demo: "Easy to read" },+ { id: "boxed", name: "Boxed", blurb: "White words on a dark band", demo: "<span>Readable anywhere</span>" },+];+const CAP_COLORS = {+ bold: ["#FFE135", "#9FE06A", "#FF5A1F", "#38BDF8", "#FF4FA3"],+ highlight: ["#7C3AED", "#16A34A", "#E11D48", "#2563EB", "#F59E0B"],+ reveal: ["#FFFFFF", "#FFE135", "#9FE06A", "#38BDF8", "#FF4FA3"],+};+let capHeard = "", capFor = "", capSetup = null, capTimer, capSeq = 0, capVertical = false;+const capColor = (style) => S.captions.colors?.[style] ?? CAP_COLORS[style]?.[0];+function capOpts() {+ const c = S.captions, o = { video: c.video.path, style: c.style, position: c.position, size: c.size };+ if (CAP_COLORS[c.style]) o.color = capColor(c.style);+ const t = $("#cap_text").value;+ if (t.trim() && t.trim() !== capHeard.trim()) o.text = t;+ return o;+}+function renderCaptions() {+ const c = S.captions;+ $("#cap_video").innerHTML = c.video ? `<div class="cliprow"><b>▶</b><span title="${esc(c.video.path)}">${esc(c.video.name)}</span><button type="button" id="cap_clear" aria-label="Remove ${esc(c.video.name)}">×</button></div>` : "";+ $("#cap_styles").innerHTML = CAP_STYLES.map((s) => `<button type="button" class="capstyle${c.style === s.id ? " on" : ""}" data-capstyle="${s.id}"><span class="demo d-${s.id}" style="--hl:${capColor(s.id) ?? "#fff"}"><span>${s.demo}</span></span><b>${s.name}</b><small>${s.blurb}</small></button>`).join("");+ const cols = CAP_COLORS[c.style];+ $("#cap_colorWrap").hidden = !cols;+ if (cols) $("#cap_colors").innerHTML = cols.map((h) => `<button type="button" data-capcolor="${h}" class="${h === capColor(c.style) ? "on" : ""}" style="background:${h}" aria-label="Colour ${h}"></button>`).join("");+ $("#cap_path").placeholder = `…or paste where a video is saved on ${PLACE.computer}`;+ // Presets show where they put the words on this video's shape; a number is the user's own height.+ const y = typeof c.position === "number" ? c.position : { top: capVertical ? 18 : 12, middle: 50, bottom: capVertical ? 75 : 87 }[c.position];+ $("#cap_y").value = y;+ $("#cap_yOut").textContent = typeof c.position === "number" ? `· ${y}% down` : `· ${c.position}`;+ $("#cap_go").disabled = !c.video;+}+function showPreview(src, msg, bad) {+ $("#cap_preview").hidden = !src;+ if (src) $("#cap_preview").src = src;+ const e = $("#cap_previewEmpty"); e.hidden = Boolean(src);+ e.textContent = msg ?? "Pick a video to see your captions on it."; e.style.color = bad ? "var(--bad)" : "";+}+// Setup is checked once: whisper.cpp to hear the words, and a speech model it listens with.+async function capReady() {+ if (capSetup?.ready) return true;+ try { capSetup = await api("caption_setup"); } catch (err) { toast(err.message, true); return false; }+ const s = capSetup;+ $("#cap_setup").innerHTML = s.ready ? "" : `<div class="hint" style="margin:0 0 18px"><b>One-time setup.</b> To hear the words, captions need two free things on ${PLACE.computer}:<br>+ ${s.whisper ? "✓ whisper.cpp is installed" : `<b>1.</b> whisper.cpp: ${esc(s.whisper_hint)}`}<br>+ ${s.model ? `✓ Speech model: ${esc(s.model)}` : `<b>2.</b> A speech model (148 MB, from whisper.cpp's own page) <div class="rowbtns" style="margin-top:10px"><button class="btn small" id="cap_getmodel" type="button">Get the speech model</button></div>`}+ ${s.whisper ? "" : `<div class="rowbtns" style="margin-top:10px"><button class="btn small ghost" id="cap_recheck" type="button">I've installed it — check again</button></div>`}</div>`;+ return s.ready;+}+async function setCapVideo(v) {+ S.captions.video = v; S.captions.text = ""; save();+ capHeard = ""; capFor = ""; $("#cap_text").value = ""; $("#cap_out").innerHTML = "";+ renderCaptions(); await capListen();+}+async function capListen() {+ const c = S.captions;+ if (!c.video || !guard() || !(await capReady())) return;+ showPreview(null, "Listening to the video…"); $("#cap_textNote").textContent = "";+ try {+ const out = await api("transcribe", { video: c.video.path });+ capHeard = out.text; capFor = c.video.path;+ $("#cap_text").value = c.text || out.text;+ $("#cap_textNote").textContent = `· ${out.words} words heard`;+ await capPreview();+ } catch (err) { showPreview(null, err.message, true); }+}+async function capPreview() {+ const c = S.captions;+ if (!c.video || capFor !== c.video.path) return;+ const seq = ++capSeq; $("#cap_previewNote").textContent = "· updating…";+ try {+ const out = await api("caption_preview", capOpts());+ if (seq !== capSeq) return;+ showPreview(`${media(out.image)}&t=${Date.now()}`);+ $("#cap_previewNote").textContent = `· a frame at ${out.at.toFixed(1)}s`;+ } catch (err) { if (seq === capSeq) { showPreview(null, err.message, true); $("#cap_previewNote").textContent = ""; } }+}+function capPreviewSoon(ms = 350) { clearTimeout(capTimer); capTimer = setTimeout(capPreview, ms); }+$("#cap_styles").addEventListener("click", (e) => { const b = e.target.closest("[data-capstyle]"); if (!b) return; S.captions.style = b.dataset.capstyle; save(); renderCaptions(); capPreviewSoon(); });+$("#cap_colors").addEventListener("click", (e) => { const b = e.target.closest("[data-capcolor]"); if (!b) return; (S.captions.colors ??= {})[S.captions.style] = b.dataset.capcolor; save(); renderCaptions(); capPreviewSoon(); });+$("#cap_video").addEventListener("click", (e) => { if (!e.target.closest("#cap_clear")) return; S.captions.video = null; S.captions.text = ""; save(); capHeard = ""; capFor = ""; $("#cap_text").value = ""; $("#cap_textNote").textContent = ""; showPreview(null); renderCaptions(); });+$("#cap_up").onclick = () => { pickTarget = { kind: "capvideo", i: 0 }; $("#file").accept = "video/*"; $("#file").click(); };+$("#cap_film").onclick = () => openFilms("captions");+$("#cap_pathgo").onclick = () => { const p = $("#cap_path").value.trim().replace(/^["']|["']$/g, ""); if (!p) return; $("#cap_path").value = ""; setCapVideo({ path: p, name: p.split(/[\\/]/).pop() }); };+const capPlace = (y) => { S.captions.position = Math.round(Math.min(95, Math.max(5, y))); save(); renderSegs(); renderCaptions(); capPreviewSoon(); };+$("#cap_y").addEventListener("input", (e) => capPlace(+e.target.value));+$("#cap_preview").addEventListener("click", (e) => { const r = e.target.getBoundingClientRect(); capPlace(((e.clientY - r.top) / r.height) * 100); });+$("#cap_preview").addEventListener("load", (e) => { const v = e.target.naturalHeight > e.target.naturalWidth; if (v !== capVertical) { capVertical = v; renderCaptions(); } });+$("#cap_path").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#cap_pathgo").click(); });+$("#cap_text").addEventListener("input", () => { S.captions.text = $("#cap_text").value.trim() === capHeard.trim() ? "" : $("#cap_text").value; save(); capPreviewSoon(1200); });+document.addEventListener("click", async (e) => {+ const take = e.target.closest("[data-capthis]");+ if (take) { const p = take.dataset.capthis; showTab("captions"); return void setCapVideo({ path: p, name: p.split(/[\\/]/).pop() }); }+ if (e.target.closest("#cap_recheck")) { capSetup = null; if (await capReady()) capListen(); }+ const get = e.target.closest("#cap_getmodel");+ if (get) {+ get.disabled = true; get.textContent = "Downloading 148 MB…";+ try { await api("caption_model"); capSetup = null; if (await capReady()) { toast("Speech model ready"); capListen(); } }+ catch (err) { toast(err.message, true); get.disabled = false; get.textContent = "Get the speech model"; }+ }+});+$("#cap_go").onclick = async () => {+ const c = S.captions;+ if (!c.video || !guard()) return;+ const b = $("#cap_go"); b.disabled = true; b.textContent = "Adding captions…";+ $("#cap_out").innerHTML = `<p class="empty">Drawing the captions and laying them over your video. A one-minute video takes about half a minute.</p>`;+ try {+ const out = await api("captions", capOpts());+ $("#cap_out").innerHTML = `<video controls playsinline src="${media(out.output)}&t=${Date.now()}" style="width:100%;max-height:72vh;border-radius:12px;background:#000"></video>+ <p class="empty" style="margin-top:8px">${out.captions} captions · ${out.words} words · ${out.duration.toFixed(1)}s<br>${esc(out.output)}<br>Subtitle file (for YouTube): ${esc(out.srt)}</p>`;+ loadGallery();+ } catch (err) { $("#cap_out").innerHTML = `<p class="empty" style="color:var(--bad)">${esc(err.message)}</p>`; toast(err.message, true); }+ b.disabled = false; b.textContent = "Add captions";+};+/* ---------- library ---------- */const chosen = new Set();$("#l_load").onclick = async () => {@@ -854,7 +1041,7 @@ async function loadGallery(prefer) {renderGallery(); renderTakes();}// Which saved files each tab's gallery shows. Shots uses stills as first and last frames as well as clips.-const GALLERY_KINDS = { cast: ["image"], frames: ["image"], shots: ["video", "image"], restyle: ["video"], cut: ["video"] };+const GALLERY_KINDS = { cast: ["image"], frames: ["image"], shots: ["video", "image"], restyle: ["video"], cut: ["video"], captions: ["video"] };// How to name this computer and its bin. Starts with the Mac wording and is replaced by what the server reports, so a// PC says "this PC" and "the Recycle Bin".let PLACE = { computer: "this Mac", bin: "the Mac's Trash", binShort: "Mac Trash", local_engine: "macOS voice", platform: "darwin" };@@ -950,7 +1137,7 @@ function renderAll() {if (mus) mus.outerHTML = slotHtml("music", 0, S.cut.music, "Music track");if (vo) vo.outerHTML = slotHtml("voiceover", 0, S.cut.voiceover, "Narration");$("#c_hold").checked = S.cut.hold;- renderClips();+ renderClips(); renderCaptions();if ($("#n_style")) $("#n_style").value = S.narrate.style ?? "";estimate(); save();}