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.
Kokoro narration, editing without an editor, sharper captions and Flow fixes
GTAI-11d17b7b5ecc6
diff --git a/CLAUDE.md b/CLAUDE.mdindex efd19fa..529f3d6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -510,3 +510,193 @@ The preview tool could not read the project while it lived in ~/Desktop; check t- CAPTIONS WORKFLOW (the user's rule, 2026-10-18): transcribe first, show the words with likely mishearings fixed,get the user's OK, THEN make the video once. The playbook and the flow_captions description say so too.+- KOKORO (2026-10-29, the user's call: the default narration voice). `engine: "kokoro"` is now flow_narrate's default+ (then gemini, mac). It runs through kokoro-js (npm, so `npm install` is the whole setup on Mac and PC, no Python) in+ its OWN process, dist/kokoro-worker.js, so the 326 MB model and Hugging Face's fetch-based download never live in the+ panel or Claude's connector. The model downloads itself on first use into ~/.flow-mcp/models/kokoro (measured 17 s+ to 93 s); a take after that is ~2 s, 36 s of speech in 8 s. Takes run one at a time. Kokoro reads at most 510 phoneme+ tokens per pass and silently drops the rest, so the worker splits sentences into <=300-character chunks; each pass+ also opens with ~0.45 s of silence (joins measured 1.1 s), so every chunk is trimmed to its speech and joined with a+ 0.4 s pause. A 538-character line checked with whisper: every word present, pauses 0.26-0.67 s. 28 English voices,+ graded on the model card (af_heart A, af_bella A-; the user's pick am_michael C+, the default), `speed` 0.5-2 (panel+ slider 0.70-1.30). When Google's daily limit answers 429/quota, a gemini take is recorded with Kokoro and the result+ carries `fell_back_from` + a note - that fallback is NOT tested against a real exhausted key yet. Voice tab: Kokoro |+ Google AI Studio, each engine keeps its own voice pick (S.narrate.kokoroVoice / geminiVoice).+- COMPUTER VOICES REMOVED (2026-10-29, the user's call): the `mac` engine (`say` on a Mac, System.Speech on Windows),+ localVoices and speakLocally are gone; narration is kokoro | gemini only. A panel that saved engine "mac" switches+ to Kokoro. Kokoro was kept local at first; the user cleared it for GitHub on 2026-11-07.+- NARRATION RUNS IN THE CALLER (2026-10-29): voices/narrate are module functions (voicesHere, narrateHere) used by+ LocalCore AND RemoteCore, because they never touch Chrome. Claude Desktop's own flow-mcp often owns 8787 with code a+ release behind (the user cannot always restart), and a client forwarding narrate to it got the old engine list.+ Verified: a fresh client process recorded a Kokoro line while the stale owner (pid unchanged) kept 8787. The panel+ page itself is read from disk on every request, so after a build the PANEL is new while its API is the owner's: the+ Voice tab stays broken until the owner restarts. story_pitches (playbook) is served by the caller's index.ts too.+- FIRST FRAME FROM A CLIP (2026-10-29): flow_generate's `first_frame` may be a finished .mp4; the queue swaps in its+ last frame (extractLastFrame), i.e. chain_previous across separate calls, so each clip can be reviewed before the+ next is paid for. Made for The Last Slice (3 x 10 s Omni 1.1 Flash 720p = 45 credits, every join invisible).+- CAPTIONS FROM THE CLEAN NARRATION (2026-10-29, captions came out "off" on The Last Slice): transcribing the MIXED+ film (narration + the clips' crashes at 30%) made whisper squeeze the first five words after each pause onto one+ instant (10.18 s, zero length) and drop all punctuation, so the panel's captions ran up to 1.5 s early. flow_assemble+ keeps the narration as <film>-voice.wav on the film's timeline (it can be shorter than the film); transcribe now+ hears that instead. Even the clean track squeezed words after long silences ("Why risk it all for one" at 20.24 s),+ so its spoken stretches (silencedetect -40 dB, >= 0.6 s) are each heard separately and shifted back. Measured against+ the known narration times: Tonight 10.41 (true 10.42), Why 20.42 (20.42), waiting 27.03 (27.0), punctuation back.+ Cache key carries the voice track + "spans". Transcribe/captions now also run in the CALLER like narration.+- CAPTIONS ON DIALOGUE (2026-10-30, First Lesson: two people talking in a car, no narration track): heard whole, the+ engine noise made whisper put "See?" 0.5 s and "You were braver" 0.9 s early. Every non-clean track is now cut into+ speech stretches by whisper.cpp's own detector, `whisper-vad-speech-segments` (ships with brew whisper-cpp; model+ ggml-silero-v5.1.2.bin, 0.9 MB, fetched on first use from huggingface ggml-org/whisper-vad), each heard on its own,+ and no word may start before its stretch's detected onset (whisper liked to start the first word at the window's+ edge, 0.3 s early). whisper-cli's own --vad is NOT usable for this: its token times are on the squeezed timeline and+ its segments run on through seconds of noise. The detector's list comes out once (stdout or stderr) in centiseconds.+ A first stretch within 2 s of the start is opened to 0:00 with no floor ("Dad!" over the stall noise was missed).+ Measured against the loudness (-40 -> -20 dB jumps): See? 15.39, Don't 18.27, You 23.78, all exact; The Last Slice+ (clean track, silencedetect path) unchanged. Cache tag "spans-v5".+- LAST FRAME FROM A CLIP (2026-10-30): flow_generate's `last_frame` may be a finished .mp4; the queue swaps in its+ FIRST frame (extractFirstFrame in chain.ts). With first_frame = the clip before and last_frame = the clip after, a+ middle clip is redone with both cuts invisible (Midnight clip 2: Flow had dissolved from the gears to the clock face;+ the redo is one move down, and its last frame matched clip 3's first exactly).+- CORRECTED WORDS TAKE THE MISHEARD WORD'S TIME (2026-10-30, Midnight): alignText spread an unmatched corrected word+ over the whole gap between its matched neighbours, so "Pim" (heard "Pym") started right after the previous line,+ 4.6 s early. Now the heard words in the same gap are used: equal counts map one to one ("Pym"->"Pim", "12"->"twelve"),+ otherwise the corrected words share the heard words' stretch. Checked: "Pim found the" 10.30 s (line placed at 10.5).+- ALIGNMENT, TWO MORE CASES (2026-10-30, Last Train dialogue): (1) a word the listener missed entirely ("That" in+ "That was the 949") sat at the start of the pause before it (2 s early); now it goes just before the next word, 0.3 s+ per word. (2) whisper prints a speaker-change dash as its own token; pairing "fifty" with "-" made a zero-length+ caption. Only tokens with letters or digits count when corrected words borrow heard times.+- OPENING STRETCH (2026-10-30, Last Train: footsteps for 1.3 s before the first line): opening the first stretch to+ 0:00 with no floor bunched Theo's whole line at 0:00. It now starts 0.2 s before the first loud spike (18 dB over the+ quietest fifth of the track, or the detector's onset if earlier), which is also its floor. Checked: Last Train+ "You" 1.26 / "fifteen" 1.98 (speech 1.3-3.0), First Lesson "Dad!" 0.53 (spike 0.55). Cache tag "spans-v7".+- NEW PROJECT, TRIMS, END CARD (2026-10-30, for a UGC ad shot from scratch): `flow_new_project` (createProject in+ flow.ts) - Flow's home page has one button "New project" (getByRole button /new project/i, mapped live), which opens+ /project/<uuid>; the project's name is the textbox "Editable text" on the project page, filled + Enter. Not yet run+ live (its first run was meant to be on camera). flow_assemble got `trims` (one {from,to}|null per clip, applied as+ input -ss/-t, clamped to the clip) and `end_card` {text, seconds}: renderEndCard (captions.ts, the captions' headless+ Chrome) draws big centred words (12% of the frame's short side, 8.5% past 40 characters) over the last kept frame,+ blurred 28 px at 42% brightness, saved as <name>-endcard.mp4 with silent audio and joined like a clip. Tested on+ Last Train: trims [{from:1}, null, {to:8}] + a 2.5 s card -> 29.55 s, 4.7 s to make.+- SETTINGS POPOVER CLOSED BY THE MODEL MENU'S ESCAPE (2026-10-30, first image in a brand-new project): the project+ already sat on the newest Nano Banana, so pickModel closed its menu with Escape - which also closed the settings+ popover, and the next pickRadio failed with 'Flow has no "x2" option'. pickRadio now reopens the popover+ (openSettings) before giving up. Until the owner process reloads, naming the model ("Nano Banana 2.1") avoids it.+- FIRST FRAME AT A CHOSEN SECOND (2026-10-30, KOVA bottle ad: clip 1's speech ended at 6.5 s, then 3 s of nodding):+ flow_generate's `first_frame_at` (seconds) with a clip as first_frame starts the next clip from that frame instead of+ the last (extractFrameAt in chain.ts); flow_assemble's `trims` cuts the earlier clip at the same second, so the join+ stays invisible with no editor. The user's line for the video: "Flow MCP cuts it for you." Also: size clips to their+ words (Omni 4/6/8/10 s) instead of always 10 s.+- PRODUCT FLIPS MORPH (2026-10-30, KOVA clip 2, 10 credits): "turn the bottle upside down, shake, turn it upright" came back+ with the lid jumping to the other end of the bottle around 4.3 s, while the first and last frames looked perfect, so a+ start/end check missed it. A symmetric object turned end over end loses its ends. The playbook now says: keep a+ product's orientation fixed, and check every 1/8 s of motion before showing a clip.+- B-ROLL INSERTS + OUTFIT (2026-10-30, matcha UGC ad, the structure the user took from ChatGPT: talk / product shot /+ talk). flow_assemble `inserts` [{clip, over, at, seconds, from, volume}] lays a cutaway's picture over part of a clip+ while that clip's own sound keeps playing: the line "Strawberry, milk, and matcha..." from clip 3 plays over the drink+ close-up and the picture cuts back to her on "Would you try it", in sync. voice_lines was wrong for this: it levels+ each line to -16 LUFS while Flow takes sit near -24, an 8 dB jump. flow_generate `outfit` (per scene) keeps the+ character lock on face/hair/build but takes the clothes from the scene; without it the lock's saved look (Skye's+ denim shirt) fights a costume (cream sweatshirt). Both need the owner process restarted; this ad was cut by running+ dist/assemble.js directly. Talking clips: R2V with ["asset:Skye", the car still] (her saved voice Aoede in both);+ product shot: I2V from a free still. 3 clips, 40 credits, every clip right first time.+- MATCHA AD V2 + LOUDNESS (2026-10-30): flow_assemble `loudness` (LUFS, -30..-9) runs loudnorm on the finished mix;+ Flow takes sit near -24 LUFS, quiet on a phone, so ads go out at -14. "Too static, like a robot" was fixed with a+ hand-held selfie take (her arm runs out of frame, gentle sway) and one simple action with the product already in+ hand (one sip through a straw), plus a hand-held arc on the B-roll instead of a locked-off cup. Both passed the 1/8 s+ check first time (22 credits). Flow's "Add AI credits" banner (low balance) also ends in "credits": the quote is now+ read from a link named "<N> credits" only. A take can open on a stray half-word (heard as "suffix"): listen to the+ first second of every take and trim it.+- SIP CLIPS + REPEATED LINES (2026-10-30, matcha v3, 12 credits): with a CLEAR straw the model never moved liquid up it+ ("when she drinks nothing going up on the straw"); the redo used an opaque pink paper straw, in the free still first+ and then in the prompt, and passed the 1/8 s check. The take then said "Would you try?" and then the whole line+ ("Would you try it, or stick to coffee?"). Cut the repeat with no new code: list the clip TWICE in flow_assemble's+ `clips` with two `trims` that skip the first attempt, cutting in the quiet gaps (token times + 50 ms RMS). Same pose on+ both sides, so the jump is barely visible. Transcribe EVERY take with token times before showing it.+ The first v3 cut was wrong at the clip 2 -> 3 join (the user heard it): scene-10 opens on a stray syllable+ (0.05-0.35 s, heard as "This.") and I cut at 0.3, leaving its tail on the cut; and that take's room noise sat 8 dB+ above clip 2's, so the background jumped. trims entries now take `volume` (0-2), `fade_in`, `fade_out`, and every+ trimmed edge gets a 15 ms fade so a cut never clicks. Fixed with from 0.45, volume 0.4 on the sip stretch: the level+ is -38 on both sides of the cut. Check 50 ms RMS ACROSS every join, not just the words.+ Then an "s" was still audible (the user again): plain RMS hid it under the room noise. Above 4 kHz+ (highpass=f=4000 twice, 20 ms RMS) it stood out: -31 dB at 0.40-0.56 s of the take against -89 around it, plus a+ 40 ms tick at 3.46. Cut points moved to 0.6 / 3.44 / 4.44; every join now reads -82 dB or lower in that band. Check+ the HISS BAND across every join too, not only loudness and words.+- CHARACTER FROM A PICTURE KEPT A STALE LOOK (2026-10-30, protein soda ad): characters.json is keyed by name and only+ `describe` wrote it, so a new "Maya" made from the user's photo would have been locked to an OLD Maya description+ (ponytail, mustard sweater) in every scene. flow_character now takes `look` (the picture in words) with `image`, and+ without it drops any older description under that name (forgetCharacter). Needs the owner restart; until then the+ look was written with dist/flow.js rememberCharacter directly.+- "PROMINENT PEOPLE" REFUSAL (2026-10-30, protein soda clip 1): a character made from the USER'S UPLOADED PHOTO made+ free stills fine, but every VIDEO with it failed: the tile said "This prompt might violate our policies about+ generating prominent people" (refunded, 61 credits kept). The queue only reported a generic "failed" and pressed+ Flow's Retry, which cannot help. waitForNewMedia now reads `.error-message-text` (errorReason; checked on the live+ tile), never retries a policy refusal, and says in Flow's words what happened plus what to do: draw the character+ from a description instead. Never try to get the same face past the filter.+- NO SUBTITLES BY DEFAULT (2026-10-30, the user's rule: "it should be default for you to tell flow never to generate+ subtitles"). Omni burned garbled captions ("thyel", "voch", "roil") into 0.8-4.9 s of a 15-credit talking clip, though+ the prompt said "No text, captions or subtitles" near its end. core.generate now opens AND closes every video prompt+ with a no-subtitles/no-text clause; `on_screen_text: true` on a scene turns it off (a sign, a title card). Checked by+ building prompts with a stubbed queue. Captions are made afterwards with flow_captions, where the words are checked.+- PHONE IN THE SHOT + CROP (2026-10-30, protein soda clip 3, 12 credits, only 9 left so no redo): the prompt said "the+ phone is propped upright ... she is never holding the phone", and Omni drew a second iPhone on a stand in the+ bottom-left corner for the whole clip. Naming an object, even to rule it out, can put it in the picture: describe the+ camera ("a fixed camera at her eye level, about 70 cm away") and never mention the phone. flow_assemble `trims`+ entries now take `crop` {x, y, w, h?} (fractions; h defaults to w so the shape holds): {x:0, y:0, w:0.78} punched in+ 1.28x and dropped the corner; checked at 2 frames a second along the bottom edge, nothing left. The punch-in sits+ right after the can cutaway, where an editor would put one anyway. Ad: protein-soda-ad.mp4, 16.4 s, -13.1 LUFS.+- REFRAMING SOMEONE ELSE'S EXPORT (2026-10-30): the user cut the ad in another Google tool and got a 1920x1080 file with+ the vertical picture in the middle (x 656-1263), white bars both sides, a soft subtitle track, and Gemini's sparkle+ mark in the picture's bottom-right corner. flow_assemble now sizes a cropped clip by what it KEEPS (it used to size the+ film by the landscape canvas), crop fractions go down to 0.1, and `size` ("1080x1920") sets the master. One clip with+ crop {x:0.3638, y:0, w:0.2724, h:0.8602} -> 1080x1920, bars and mark gone (corner checked once a second), subtitle+ track dropped, -13.9 LUFS. Voice check by median pitch (numpy autocorrelation): Flow's Callirrhoe takes ~215 Hz, that+ tool's takes ~230 Hz on both talking clips, so its voice is consistent within itself but not Flow's.+- CAPTION CORRECTIONS SPLITTING A WORD WERE IGNORED (2026-10-30, matcha ad): whisper heard "your iced" as "youriced"; the+ corrected text was compared with the transcript with every space removed, so "your iced" == "youriced" and the+ correction was dropped as "no change". timedWords now compares word by word (space-free only for unspaced languages).+ Also, burnCaptions/previewCaptions called directly with no `size`/`position` drew tiny serif captions (no font size+ on the page): they now default to medium/bottom themselves. Both need the owner restart; the matcha captions were+ made by running dist/captions.js directly. Two looks for the two ads, the user's call: soda = bold, lime #B8E62E;+ matcha = highlight, strawberry #F2557E.+- HITCH AT EVERY JOIN (2026-10-31, the user saw it at 47-48 s of Three Tiers): AI clips carry 0.03-0.05 s more sound+ than picture, and the concat filter pads the shorter picture with repeated frames, so each cut froze for a frame or+ two (found at 37.79/38.00/48.04 s by frame differences < 0.2). assemble's probe now takes the VIDEO stream's duration+ and trims every clip's sound to it (atrim=end). Checked: the same three clips -> no frozen frames, cuts exactly at+ 37.75 and 47.75, picture and sound both 57.75 s. When joining by hand, trim the audio to the picture the same way.+- SHARPNESS SNAP AT A CONTINUATION (2026-10-31, "a skip frame" at 47.75 s of Three Tiers): a clip animated from the+ previous clip's exact last frame matched it in position, zoom and colour, but Omni clips soften over their 10 s+ while the continuation is drawn from a crisp still: detail jumped 190 -> 330 (Laplacian variance) in one frame.+ flow_assemble `trims[i].soften_in` (seconds) measures both sides, picks the gblur sigma that matches the earlier+ clip's end (0.6 here) and fades that blur out over the given time: the curve now runs 1895 -> 1779 -> 1701, no step.+ Tried and REJECTED: dissolving from the frozen last frame (stalls the motion for two frames: a hitch of its own) and+ a 3-frame crossfade of the moving tails (ghosted both faces into double images). The remaining tiny jump is the+ model redrawing the frame; only a new clip can remove it.+- LOUDNESS LANDS ON TARGET (2026-10-31): flow_assemble's single loudnorm pass is held back by its -1.5 dBTP ceiling+ (Three Tiers: asked -14, got -14.9; the ads earlier came out -13.1/-13.9). It now measures the finished film and, when+ more than 0.3 LU off, corrects with plain gain + alimiter (limit 0.84) on a video-copy remux; the result carries+ `loudness`. Three Tiers: -14.1 LUFS, true peak -1.4 dBTP.+- CONTINUATION CAMERA (2026-10-31, Three Tiers clip 6, five takes): a clip animated from the previous clip's last frame+ must keep the camera moving the SAME WAY. Clip 5 ended drifting slowly backwards; takes that pushed in (or pulled+ back to make room for a dismount) read as a "skip" at the join even with matching frames. Measure the drift on both+ sides (best-fit scale of the top band between frames 12 apart: s>1 = moving back) and name it in the prompt ("keeps+ drifting very slowly backwards, exactly as it already is; never moves toward them"). A whisper slice that cuts a+ line's first word in half invents words ("Told" -> "Totally"): it is not a false start.+- WATERMARK (2026-10-31, the user asked): Google's video models (Vids, Flow) put a four-point sparkle, 71 px at+ 1080p, in the bottom-right corner (centre ~1740,900). flow_assemble `remove_watermark: true` finds it without being+ told where: frames sampled across every clip at film size (1.5 per second), each pixel's 5th-percentile value, points+ 45+ brighter than their 31x31 neighbourhood, the densest 100 px window = the mark (a white wall shared by clips also+ passes, so never take the bbox of all hits). Its centre is see-through and barely stands out, so the mask is a filled+ astroid around that box (P5 PGM), painted out with `removelogo` on the joined picture. Three Tiers: box 1704-1775 x+ 864-935, corner shows plain cobbles at 5 moments. With 32 samples only the bottom half registered: keep the sample+ count up. The invisible SynthID mark stays; platforms still expect an AI-content label.+- WATERMARK ON VERTICAL FILMS (2026-11-01, Glow UGC): watermarkMask scaled its search window by height / 1080, so a 1080x1920+ film got a 178 px window, spurious bright points widened the box to 125x93, and a corner of the sparkle stayed visible+ while the tool reported "painted out". Scale is now by the short side: box 864-935 x 1704-1776, the same 71 px mark.+ Always look at the corner after painting; the returned message only says a mask was made. Faint smudges remain where+ the mark crossed sharp edges.+- MUSIC UNDER A VOICE + THICK WATERMARK (2026-11-01, The Last Delivery): flow_assemble `duck_music` pulls the music down with sidechaincompress while the voice+ speaks, and `music_curve` [{at, volume}] shapes it over the film (straight lines, volume expression with eval=frame). A long Extend chain redraws+ Google's sparkle each hop, so by clip 8 it had a black outline and a fatter diamond that the star mask missed while the tool still said "painted out"+ (outline visible at 72 and 88 s). `watermark_margin` (10 here) grows the mask and makes it a diamond: no outline, a soft smudge remains on hard texture.+ `end_hold` {seconds, fade} holds the last frame and fades the picture to black (music_curve fades the sound with it). Checked on The Last Delivery: 103.75 s, -14.4 LUFS.+ The speech check hears "deliveries stopped" as "delivery stopped" on both Tyra and Kokoro: it is the listener, not the voice. Pass the real words as `text` to burnCaptions.+diff --git a/README.md b/README.mdindex 1ecf800..8ae3a7e 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@ New here? [GETTING-STARTED.md](GETTING-STARTED.md) takes you from nothing to you| | ||---|---|-| **macOS or Windows 10/11** | Developed and tested on macOS. Windows is supported (Chrome, the computer's own voices, the Recycle Bin and the panel launcher all have Windows versions), but it hasn't been run on a real PC yet, so please report anything that breaks |+| **macOS or Windows 10/11** | Developed and tested on macOS. Windows is supported (Chrome, the Recycle Bin and the panel launcher all have Windows versions), but it hasn't been run on a real PC yet, so please report anything that breaks || **Node.js 22 or newer** | `node --version` || **Google Chrome** | Any recent version || **A Google account** | Free. Flow gives every account 50 credits a day; a paid Google AI plan adds more and unlocks 1080p downloads. Developed on a Pro plan |@@ -150,7 +150,8 @@ Eight tabs, in the order you would use them:- **Frames**: free stills, with *match previous frame* to keep a set on-model.- **Shots**: paid clips, with first/last frames, chaining, a live credit estimate, and a card thatcontinues a finished clip from its own last frame.-- **Voice**: free narration in Google's voices or your computer's own. Your saved narrations are listed+- **Voice**: free narration with Kokoro (the default: 28 voices, runs on your computer, no key) or Google's+ voices. Your saved narrations are listedhere to play or delete, and there's a field for your Google AI Studio key (checked with Google, storedonly on your computer; never paste it into a chat).- **Restyle**: change a clip you already have.@@ -202,8 +203,8 @@ agree on what is running. That API listens on 127.0.0.1 only and needs a per-run| `flow_character_edit` | Restyle an existing character in place (free) and save the new portrait; name, personality and voice are kept, so every scene referencing it updates. Pass `look` with the updated description; with only a name it re-saves the current portrait || `flow_characters` | List the project's characters || `flow_techniques` | 39 film-technique prompt presets (camera moves, product shots, transitions, image commands); pass an id as a scene's `technique` |-| `flow_narrate` | Free narration audio, any length: `gemini` (Google AI Studio text-to-speech, with the same voices Flow has, plus a `style` note) or `mac` (a voice installed on this computer, no key needed) |-| `flow_voices` | Narrator voices available, and whether a Google key is set up |+| `flow_narrate` | Free narration audio, any length: `kokoro` (the default, a voice that runs on your computer, 28 voices and a `speed`), or `gemini` (Google AI Studio text-to-speech, with the same voices Flow has, plus a `style` note; falls back to Kokoro when the daily limit is used up) |+| `flow_voices` | Narrator voices available, whether Kokoro's model is downloaded yet, and whether a Google key is set up || `flow_captions` | Burn spoken-word captions into any video, landscape or vertical, in one of five styles, at any height and size, in normal, capital or lowercase letters, in about 100 languages; returns the transcript so a misheard word can be fixed and the call repeated (local whisper.cpp, Chrome and FFmpeg, no credits) || `flow_transcribe` | Hear the words in any video or audio on your computer, with each word's start and end time (local whisper.cpp, free) || `flow_assemble` | Join clips into one MP4 (a project's clips, or any you list, in order) with optional music and voiceover, and separate volume for the clips' own sound. A voiceover can also be built line by line (`voice_lines`), each line cut from a take and placed at its own moment, for narration timed to on-screen titles (local FFmpeg, no credits) |@@ -216,10 +217,15 @@ Flow's agent mode and does both.Output lands in `~/flow-mcp-out/<project>/scene-NN.ext`.-### Narration with Google's voices (optional)+### Narration voices-`flow_narrate` with `engine: "mac"` uses your computer's own voices and works out of the box: macOS voices on a-Mac, the built-in speech voices on Windows. For Google's voices (the same ones Flow offers), get a free key from+`flow_narrate` uses **Kokoro** by default: a free voice that runs on your own computer, with no key, no daily+limit and no length cap. Pick any of its 28 English voices (American and British) and a speed. The first take+downloads its model once (326 MB, about a minute); after that a take records in a couple of seconds.++#### Google's voices (optional)++For Google's voices (the same ones Flow offers), get a free key from[Google AI Studio](https://aistudio.google.com/apikey) and paste it into **Flow Studio → Voice → Google AI Studiokey → Save key**. It's checked with Google before it's saved, and stored only on your computer. Or set`GEMINI_API_KEY`. Either way, never paste the key into a chat; it would end up in the conversation history.diff --git a/package-lock.json b/package-lock.jsonindex d082a06..e74865c 100644--- a/package-lock.json+++ b/package-lock.json@@ -9,7 +9,9 @@"version": "0.1.0","license": "ISC","dependencies": {+ "@huggingface/transformers": "^3.8.1","@modelcontextprotocol/sdk": "^1.30.0",+ "kokoro-js": "^1.2.1","playwright-core": "^1.63.0","zod": "^4.6.5"},@@ -21,16 +23,524 @@"typescript": "^7.0.2"}},+ "node_modules/@emnapi/runtime": {+ "version": "1.11.3",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },"node_modules/@hono/node-server": {"version": "2.1.1","resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz","integrity": "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==","license": "MIT","engines": {- "node": ">=20"+ "node": ">=20"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@huggingface/jinja": {+ "version": "0.5.11",+ "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.11.tgz",+ "integrity": "sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@huggingface/transformers": {+ "version": "3.8.1",+ "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-3.8.1.tgz",+ "integrity": "sha512-tsTk4zVjImqdqjS8/AOZg2yNLd1z9S5v+7oUPpXaasDRwEDhB+xnglK1k5cad26lL5/ZIaeREgWWy0bs9y9pPA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@huggingface/jinja": "^0.5.3",+ "onnxruntime-node": "1.21.0",+ "onnxruntime-web": "1.22.0-dev.20250409-89f8206ba4",+ "sharp": "^0.34.1"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",+ "cpu": [+ "arm"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",+ "cpu": [+ "ppc64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",+ "cpu": [+ "riscv64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",+ "cpu": [+ "s390x"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",+ "cpu": [+ "arm"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",+ "cpu": [+ "ppc64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",+ "cpu": [+ "riscv64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",+ "cpu": [+ "s390x"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",+ "cpu": [+ "wasm32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.7.0"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"},- "peerDependencies": {- "hono": "^4"+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",+ "cpu": [+ "ia32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@isaacs/fs-minipass": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",+ "license": "ISC",+ "dependencies": {+ "minipass": "^7.0.4"+ },+ "engines": {+ "node": ">=18.0.0"}},"node_modules/@modelcontextprotocol/sdk": {@@ -73,11 +583,67 @@}}},+ "node_modules/@protobufjs/aspromise": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/base64": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/codegen": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",+ "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/eventemitter": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",+ "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/fetch": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",+ "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@protobufjs/aspromise": "^1.1.1"+ }+ },+ "node_modules/@protobufjs/float": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/path": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/pool": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/utf8": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",+ "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",+ "license": "BSD-3-Clause"+ },"node_modules/@types/node": {"version": "26.6.2","resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.2.tgz","integrity": "sha512-X1P21scMv4zGKLYqjdGjaKa7COa0RKVYYZZN/NfvLQ1JegxFhdhpZG/Lyn8AXx6CDUavKAd11v6BvfpkDByK8g==",- "dev": true,"license": "MIT","dependencies": {"undici-types": "~8.9.0"@@ -506,6 +1072,13 @@"url": "https://opencollective.com/express"}},+ "node_modules/boolean": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",+ "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "license": "MIT"+ },"node_modules/bytes": {"version": "3.1.2","resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",@@ -544,6 +1117,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/chownr": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/content-disposition": {"version": "1.1.0","resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",@@ -632,6 +1214,40 @@}}},+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "license": "MIT",+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/depd": {"version": "2.0.0","resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",@@ -641,6 +1257,21 @@"node": ">= 0.8"}},+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/detect-node": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",+ "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",+ "license": "MIT"+ },"node_modules/dunder-proto": {"version": "1.0.1","resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",@@ -700,12 +1331,30 @@"node": ">= 0.4"}},+ "node_modules/es6-error": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",+ "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",+ "license": "MIT"+ },"node_modules/escape-html": {"version": "1.0.3","resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz","integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==","license": "MIT"},+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/etag": {"version": "1.8.1","resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",@@ -841,6 +1490,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/flatbuffers": {+ "version": "25.9.23",+ "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz",+ "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==",+ "license": "Apache-2.0"+ },"node_modules/forwarded": {"version": "0.2.0","resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",@@ -905,6 +1560,39 @@"node": ">= 0.4"}},+ "node_modules/global-agent": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",+ "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "boolean": "^3.0.1",+ "es6-error": "^4.1.1",+ "matcher": "^3.0.0",+ "roarr": "^2.15.3",+ "semver": "^7.3.2",+ "serialize-error": "^7.0.1"+ },+ "engines": {+ "node": ">=10.0"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "license": "MIT",+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/gopd": {"version": "1.2.0","resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",@@ -917,6 +1605,24 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/guid-typescript": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz",+ "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==",+ "license": "ISC"+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "license": "MIT",+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/has-symbols": {"version": "1.1.0","resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",@@ -1043,6 +1749,40 @@"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==","license": "BSD-2-Clause"},+ "node_modules/json-stringify-safe": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",+ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",+ "license": "ISC"+ },+ "node_modules/kokoro-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/kokoro-js/-/kokoro-js-1.2.1.tgz",+ "integrity": "sha512-oq0HZJWis3t8lERkMJh84WLU86dpYD0EuBPtqYnLlQzyFP1OkyBRDcweAqCfhNOpltyN9j/azp1H6uuC47gShw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@huggingface/transformers": "^3.5.1",+ "phonemizer": "^1.2.1"+ }+ },+ "node_modules/long": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",+ "license": "Apache-2.0"+ },+ "node_modules/matcher": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",+ "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",+ "license": "MIT",+ "dependencies": {+ "escape-string-regexp": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/math-intrinsics": {"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",@@ -1102,6 +1842,27 @@"url": "https://opencollective.com/express"}},+ "node_modules/minipass": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=16 || 14 >=14.17"+ }+ },+ "node_modules/minizlib": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",+ "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",+ "license": "MIT",+ "dependencies": {+ "minipass": "^7.1.2"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",@@ -1158,6 +1919,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/on-finished": {"version": "2.4.1","resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",@@ -1179,6 +1949,49 @@"wrappy": "1"}},+ "node_modules/onnxruntime-common": {+ "version": "1.21.0",+ "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.21.0.tgz",+ "integrity": "sha512-Q632iLLrtCAVOTO65dh2+mNbQir/QNTVBG3h/QdZBpns7mZ0RYbLRBgGABPbpU9351AgYy7SJf1WaeVwMrBFPQ==",+ "license": "MIT"+ },+ "node_modules/onnxruntime-node": {+ "version": "1.21.0",+ "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.21.0.tgz",+ "integrity": "sha512-NeaCX6WW2L8cRCSqy3bInlo5ojjQqu2fD3D+9W5qb5irwxhEyWKXeH2vZ8W9r6VxaMPUan+4/7NDwZMtouZxEw==",+ "hasInstallScript": true,+ "license": "MIT",+ "os": [+ "win32",+ "darwin",+ "linux"+ ],+ "dependencies": {+ "global-agent": "^3.0.0",+ "onnxruntime-common": "1.21.0",+ "tar": "^7.0.1"+ }+ },+ "node_modules/onnxruntime-web": {+ "version": "1.22.0-dev.20250409-89f8206ba4",+ "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.22.0-dev.20250409-89f8206ba4.tgz",+ "integrity": "sha512-0uS76OPgH0hWCPrFKlL8kYVV7ckM7t/36HfbgoFw6Nd0CZVVbQC4PkrR8mBX8LtNUFZO25IQBqV2Hx2ho3FlbQ==",+ "license": "MIT",+ "dependencies": {+ "flatbuffers": "^25.1.24",+ "guid-typescript": "^1.0.9",+ "long": "^5.2.3",+ "onnxruntime-common": "1.22.0-dev.20250409-89f8206ba4",+ "platform": "^1.3.6",+ "protobufjs": "^7.2.4"+ }+ },+ "node_modules/onnxruntime-web/node_modules/onnxruntime-common": {+ "version": "1.22.0-dev.20250409-89f8206ba4",+ "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.22.0-dev.20250409-89f8206ba4.tgz",+ "integrity": "sha512-vDJMkfCfb0b1A836rgHj+ORuZf4B4+cc2bASQtpeoJLueuFc5DuYwjIZUBrSvx/fO5IrLjLz+oTrB3pcGlhovQ==",+ "license": "MIT"+ },"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",@@ -1207,6 +2020,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/phonemizer": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/phonemizer/-/phonemizer-1.2.1.tgz",+ "integrity": "sha512-v0KJ4mi2T4Q7eJQ0W15Xd4G9k4kICSXE8bpDeJ8jisL4RyJhNWsweKTOi88QXFc4r4LZlz5jVL5lCHhkpdT71A==",+ "license": "Apache-2.0"+ },"node_modules/pkce-challenge": {"version": "5.0.1","resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",@@ -1216,6 +2035,12 @@"node": ">=16.20.0"}},+ "node_modules/platform": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",+ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==",+ "license": "MIT"+ },"node_modules/playwright-core": {"version": "1.63.0","resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",@@ -1228,6 +2053,29 @@"node": ">=20"}},+ "node_modules/protobufjs": {+ "version": "7.6.6",+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",+ "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",+ "hasInstallScript": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "@protobufjs/aspromise": "^1.1.2",+ "@protobufjs/base64": "^1.1.2",+ "@protobufjs/codegen": "^2.0.5",+ "@protobufjs/eventemitter": "^1.1.1",+ "@protobufjs/fetch": "^1.1.1",+ "@protobufjs/float": "^1.0.2",+ "@protobufjs/path": "^1.1.2",+ "@protobufjs/pool": "^1.1.0",+ "@protobufjs/utf8": "^1.1.1",+ "@types/node": ">=13.7.0",+ "long": "^5.3.2"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },"node_modules/proxy-addr": {"version": "2.0.8","resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",@@ -1298,6 +2146,23 @@"node": ">=0.10.0"}},+ "node_modules/roarr": {+ "version": "2.15.4",+ "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",+ "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "boolean": "^3.0.1",+ "detect-node": "^2.0.4",+ "globalthis": "^1.0.1",+ "json-stringify-safe": "^5.0.1",+ "semver-compare": "^1.0.0",+ "sprintf-js": "^1.1.2"+ },+ "engines": {+ "node": ">=8.0"+ }+ },"node_modules/router": {"version": "2.2.0","resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",@@ -1320,6 +2185,24 @@"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==","license": "MIT"},+ "node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/semver-compare": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",+ "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",+ "license": "MIT"+ },"node_modules/send": {"version": "1.2.1","resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",@@ -1346,6 +2229,21 @@"url": "https://opencollective.com/express"}},+ "node_modules/serialize-error": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",+ "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",+ "license": "MIT",+ "dependencies": {+ "type-fest": "^0.13.1"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/serve-static": {"version": "2.2.1","resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",@@ -1371,6 +2269,50 @@"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==","license": "ISC"},+ "node_modules/sharp": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@img/colour": "^1.0.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.7.3"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.34.5",+ "@img/sharp-darwin-x64": "0.34.5",+ "@img/sharp-libvips-darwin-arm64": "1.2.4",+ "@img/sharp-libvips-darwin-x64": "1.2.4",+ "@img/sharp-libvips-linux-arm": "1.2.4",+ "@img/sharp-libvips-linux-arm64": "1.2.4",+ "@img/sharp-libvips-linux-ppc64": "1.2.4",+ "@img/sharp-libvips-linux-riscv64": "1.2.4",+ "@img/sharp-libvips-linux-s390x": "1.2.4",+ "@img/sharp-libvips-linux-x64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",+ "@img/sharp-linux-arm": "0.34.5",+ "@img/sharp-linux-arm64": "0.34.5",+ "@img/sharp-linux-ppc64": "0.34.5",+ "@img/sharp-linux-riscv64": "0.34.5",+ "@img/sharp-linux-s390x": "0.34.5",+ "@img/sharp-linux-x64": "0.34.5",+ "@img/sharp-linuxmusl-arm64": "0.34.5",+ "@img/sharp-linuxmusl-x64": "0.34.5",+ "@img/sharp-wasm32": "0.34.5",+ "@img/sharp-win32-arm64": "0.34.5",+ "@img/sharp-win32-ia32": "0.34.5",+ "@img/sharp-win32-x64": "0.34.5"+ }+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",@@ -1464,6 +2406,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/sprintf-js": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",+ "license": "BSD-3-Clause"+ },"node_modules/statuses": {"version": "2.0.2","resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",@@ -1473,6 +2421,22 @@"node": ">= 0.8"}},+ "node_modules/tar": {+ "version": "7.5.22",+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",+ "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "@isaacs/fs-minipass": "^4.0.0",+ "chownr": "^3.0.0",+ "minipass": "^7.1.2",+ "minizlib": "^3.1.0",+ "yallist": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/toidentifier": {"version": "1.0.1","resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",@@ -1482,6 +2446,25 @@"node": ">=0.6"}},+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD",+ "optional": true+ },+ "node_modules/type-fest": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",+ "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",+ "license": "(MIT OR CC0-1.0)",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/type-is": {"version": "2.1.0","resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",@@ -1552,7 +2535,6 @@"version": "8.9.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz","integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",- "dev": true,"license": "MIT"},"node_modules/unpipe": {@@ -1594,6 +2576,15 @@"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==","license": "ISC"},+ "node_modules/yallist": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/zod": {"version": "4.6.5","resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",diff --git a/package.json b/package.jsonindex bd505be..12400f0 100644--- a/package.json+++ b/package.json@@ -18,7 +18,9 @@"flow-mcp": "dist/index.js"},"dependencies": {+ "@huggingface/transformers": "^3.8.1","@modelcontextprotocol/sdk": "^1.30.0",+ "kokoro-js": "^1.2.1","playwright-core": "^1.63.0","zod": "^4.6.5"},diff --git a/src/assemble.ts b/src/assemble.tsindex 839910e..85019c6 100644--- a/src/assemble.ts+++ b/src/assemble.ts@@ -1,10 +1,11 @@import { execFile } from "node:child_process";-import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { basename, join } from "node:path";import { promisify } from "node:util";-import { FFMPEG_HINT, IS_WIN, powershell, psQuote } from "./platform.js";+import { renderEndCard } from "./captions.js";+import { FFMPEG_HINT } from "./platform.js";const run = promisify(execFile);const FFMPEG = process.env.FLOW_MCP_FFMPEG ?? "ffmpeg";@@ -16,9 +17,29 @@ export interface AssembleOptions {music?: string;music_volume: number;clip_volume?: number;+ // Music volume over time, on top of music_volume: {at: seconds in the film, volume: 0-2}, straight lines between points.+ music_curve?: { at: number; volume: number }[];+ // Pull the music down automatically while the voiceover speaks, and let it back up in the gaps.+ duck_music?: boolean;voiceover?: string;output_name: string;hold_last_frame?: boolean;+ // One entry per clip, in play order: seconds to keep from each clip (null or missing keeps it whole).+ trims?: ({ from?: number; to?: number; volume?: number; fade_in?: number; fade_out?: number; soften_in?: number; saturation?: number; crop?: { x?: number; y?: number; w: number; h?: number } } | null)[];+ // Words for a closing card over the film's blurred last frame.+ end_card?: { text: string; seconds?: number };+ // Cutaways laid over part of a clip; the covered clip's own sound carries on underneath.+ inserts?: { clip: string; over: number; at: number; seconds?: number; from?: number; volume?: number; crop?: { x?: number; y?: number; w: number; h?: number } }[];+ // Target loudness of the finished film in LUFS; Flow's takes come out near -24, social video sits around -14.+ loudness?: number;+ // Paint out the generator's corner mark (Vids'/Flow's sparkle), found automatically from where it never moves.+ remove_watermark?: boolean;+ // A long Extend chain redraws the mark each hop, until it has a thick outline and a fatter diamond shape that the normal+ // star mask misses (The Last Delivery, 2026-11-01: an outline stayed at 72 and 88 s). Pixels added around a diamond mask.+ watermark_margin?: number;+ // Hold the last frame this long at the end, fading to black over its last `fade` seconds.+ end_hold?: { seconds: number; fade?: number };+ size?: string;}interface ClipInfo {@@ -28,18 +49,180 @@ interface ClipInfo {hasAudio: boolean;}+type Crop = { x?: number; y?: number; w: number; h?: number };+function cropFilter(c: Crop | undefined): { crop: string; cw: number; ch: number } {+ if (!c) return { crop: "", cw: 1, ch: 1 };+ const cw = Math.min(1, Math.max(0.1, c.w));+ const ch = Math.min(1, Math.max(0.1, c.h ?? c.w));+ const x = Math.min(1 - cw, Math.max(0, c.x ?? (1 - cw) / 2));+ const y = Math.min(1 - ch, Math.max(0, c.y ?? (1 - ch) / 2));+ return { crop: `crop=iw*${cw.toFixed(4)}:ih*${ch.toFixed(4)}:iw*${x.toFixed(4)}:ih*${y.toFixed(4)},`, cw, ch };+}++// Fine detail in one frame (variance of a Laplacian over a 480x270 grey copy). Comparable between clips, not absolute.+async function sharpness(file: string, at: number, sigma = 0): Promise<number> {+ const { stdout } = await run(FFMPEG, [+ "-v", "error", "-ss", Math.max(0, at).toFixed(3), "-i", file, "-frames:v", "1",+ "-vf", `${sigma > 0 ? `gblur=sigma=${sigma.toFixed(2)},` : ""}scale=480:270,format=gray`, "-f", "rawvideo", "-",+ ], { encoding: "buffer", maxBuffer: 1 << 22 });+ const g = stdout as unknown as Buffer;+ const w = 480, h = 270;+ let sum = 0, sq = 0, n = 0;+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {+ const i = y * w + x;+ const l = 4 * g[i] - g[i - 1] - g[i + 1] - g[i - w] - g[i + w];+ sum += l; sq += l * l; n++;+ }+ return n ? sq / n - (sum / n) ** 2 : 0;+}++// A clip that continues another from its last frame often starts much SHARPER than that clip ends (Vids/Omni clips+// soften over their 10 s; a continuation is drawn from a crisp still), so the join pops even though the picture is the+// same (Three Tiers, 2026-10-31: 190 -> 330, the user saw "a skip frame"). soften_in starts the clip blurred to the+// previous clip's sharpness and lets it sharpen over that many seconds. Returns the blur to start from (0 = none).+async function matchSoftness(prev: string, prevEnd: number, clip: string, from: number): Promise<number> {+ const target = await sharpness(prev, prevEnd - 0.05);+ if ((await sharpness(clip, from)) < target * 1.15) return 0;+ let best = 0, gap = Infinity;+ for (const sigma of [0.3, 0.45, 0.6, 0.8, 1.0, 1.3, 1.7, 2.2]) {+ const d = Math.abs((await sharpness(clip, from, sigma)) - target);+ if (d < gap) { gap = d; best = sigma; }+ }+ return best;+}++// The mark Google's video models put in the bottom-right corner (a four-point sparkle, 71 px at 1080p) sits in the+// same place in every frame while the picture moves under it. Sample frames from every clip at the film's size, keep+// each pixel's darkest value (a low percentile, so a clip without the mark cannot erase it), and the mark is what stays+// brighter than its surroundings. It is masked as a filled four-point star (its centre is see-through and barely+// differs from the background) and painted out with removelogo, which fills it from the pixels around it.+export async function watermarkMask(samples: { file: string; at: number; vf: string }[], width: number, height: number, out: string, margin = 0): Promise<{ cx: number; cy: number; r: number } | null> {+ const x0 = Math.floor(width * 0.7), y0 = Math.floor(height * 0.65);+ const w = width - x0, h = height - y0;+ const frames: Buffer[] = [];+ for (const sm of samples) {+ const { stdout } = await run(FFMPEG, [+ "-v", "error", "-ss", Math.max(0, sm.at).toFixed(3), "-i", sm.file, "-frames:v", "1",+ "-vf", `${sm.vf},crop=${w}:${h}:${x0}:${y0},format=gray`, "-f", "rawvideo", "-",+ ], { encoding: "buffer", maxBuffer: 1 << 24 }).catch(() => ({ stdout: Buffer.alloc(0) }));+ const b = stdout as unknown as Buffer;+ if (b.length === w * h) frames.push(b);+ }+ if (frames.length < 8) return null;+ const k = Math.floor(frames.length * 0.05);+ const low = new Float64Array(w * h);+ const col = new Array<number>(frames.length);+ for (let i = 0; i < w * h; i++) {+ for (let f = 0; f < frames.length; f++) col[f] = frames[f][i];+ col.sort((p, q) => p - q);+ low[i] = col[k];+ }+ // Brighter than the local average of that darkest-value picture by a clear margin.+ const sat = new Float64Array((w + 1) * (h + 1));+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) sat[(y + 1) * (w + 1) + x + 1] = low[y * w + x] + sat[y * (w + 1) + x + 1] + sat[(y + 1) * (w + 1) + x] - sat[y * (w + 1) + x];+ const box = (x: number, y: number, r: number) => {+ const a = Math.max(0, x - r), b = Math.max(0, y - r), c = Math.min(w, x + r + 1), d = Math.min(h, y + r + 1);+ return (sat[d * (w + 1) + c] - sat[b * (w + 1) + c] - sat[d * (w + 1) + a] + sat[b * (w + 1) + a]) / ((c - a) * (d - b));+ };+ // Other bright, steady things in the corner (a white wall that several clips share) pass too, so the mark is taken+ // as the densest cluster: the window of about its size holding the most such pixels.+ const hit = new Uint8Array(w * h);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (low[y * w + x] - box(x, y, 15) > 45) hit[y * w + x] = 1;+ // By the SHORT side: on a vertical film height / 1080 made the window 178 px, spurious bright points widened the box,+ // and part of the mark stayed behind.+ const scale = Math.min(width, height) / 1080;+ const win = Math.round(100 * scale);+ const hs = new Float64Array((w + 1) * (h + 1));+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) hs[(y + 1) * (w + 1) + x + 1] = hit[y * w + x] + hs[y * (w + 1) + x + 1] + hs[(y + 1) * (w + 1) + x] - hs[y * (w + 1) + x];+ let best = 0, bx = 0, by = 0;+ for (let y = 0; y + win <= h; y += 2) for (let x = 0; x + win <= w; x += 2) {+ const c = hs[(y + win) * (w + 1) + x + win] - hs[y * (w + 1) + x + win] - hs[(y + win) * (w + 1) + x] + hs[y * (w + 1) + x];+ if (c > best) { best = c; bx = x; by = y; }+ }+ let minX = w, maxX = -1, minY = h, maxY = -1;+ for (let y = by; y < by + win; y++) for (let x = bx; x < bx + win; x++) {+ if (hit[y * w + x]) { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); }+ }+ const bw = maxX - minX + 1, bh = maxY - minY + 1;+ if (process.env.FLOW_MCP_DEBUG) console.error("watermark", { frames: frames.length, best, box: [x0 + minX, x0 + maxX, y0 + minY, y0 + maxY] });+ if (best < 30 * scale * scale || maxX < 0 || bw < 20 * scale || bw > 160 * scale || Math.abs(bw - bh) > 0.3 * Math.max(bw, bh)) return null;+ const cx = x0 + (minX + maxX) / 2, cy = y0 + (minY + maxY) / 2, r = Math.max(bw, bh) / 2 + 3 + 3 * scale + margin * scale;+ const mask = Buffer.alloc(width * height);+ for (let y = Math.floor(cy - r - 2); y <= Math.ceil(cy + r + 2); y++) for (let x = Math.floor(cx - r - 2); x <= Math.ceil(cx + r + 2); x++) {+ if (x < 0 || y < 0 || x >= width || y >= height) continue;+ // A slightly fattened astroid (|x|^2/3 + |y|^2/3 <= 1): the sparkle's shape with its concave sides.+ const ax = Math.abs(x - cx) / r, ay = Math.abs(y - cy) / r;+ if (margin > 0 ? ax + ay <= 1 : Math.cbrt(ax * ax) + Math.cbrt(ay * ay) <= 1.15) mask[y * width + x] = 255;+ }+ writeFileSync(out, Buffer.concat([Buffer.from(`P5\n${width} ${height}\n255\n`), mask]));+ return { cx, cy, r };+}++// A clip animated from the last frame of the one before can carry a SECOND, drifting copy of the mark for a moment+// (Last Train, 2026-11-06: beside the real one at 12.0-12.5 s and 20.0 s, up to 60 px to its right), which the fixed+// mask misses while the note says "painted out". After painting, the mark's own band is scanned every frame for+// anything still much brighter than its surroundings, and only those moments get the mark-shaped fill over the leftover.+// Floor reflections sit below the band, so they are not mistaken for marks.+async function ghostMarks(file: string, width: number, height: number, mark: { cx: number; cy: number; r: number }): Promise<{ at: number; to: number; x: number; y: number }[]> {+ const scale = Math.min(width, height) / 1080;+ const pad = Math.round(90 * scale);+ const x0 = Math.max(0, Math.round(mark.cx - mark.r - pad)), x1 = Math.min(width, Math.round(mark.cx + mark.r + pad));+ const y0 = Math.max(0, Math.round(mark.cy - mark.r)), y1 = Math.min(height, Math.round(mark.cy + mark.r));+ const w = x1 - x0, h = y1 - y0, fps = 24;+ const { stdout } = await run(FFMPEG, ["-v", "error", "-i", file, "-vf", `fps=${fps},crop=${w}:${h}:${x0}:${y0},format=gray`, "-f", "rawvideo", "-"], { encoding: "buffer", maxBuffer: 1 << 30 })+ .catch(() => ({ stdout: Buffer.alloc(0) }));+ const all = stdout as unknown as Buffer;+ const n = Math.floor(all.length / (w * h));+ const r = Math.round(15 * scale);+ const hits: { t: number; x: number; y: number }[] = [];+ for (let f = 0; f < n; f++) {+ const fr = all.subarray(f * w * h, (f + 1) * w * h);+ const sat = new Float64Array((w + 1) * (h + 1));+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) sat[(y + 1) * (w + 1) + x + 1] = fr[y * w + x] + sat[y * (w + 1) + x + 1] + sat[(y + 1) * (w + 1) + x] - sat[y * (w + 1) + x];+ let count = 0, sx = 0, sy = 0, minX = w, maxX = -1, minY = h, maxY = -1;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ const a = Math.max(0, x - r), b = Math.max(0, y - r), c = Math.min(w, x + r + 1), d = Math.min(h, y + r + 1);+ const mean = (sat[d * (w + 1) + c] - sat[b * (w + 1) + c] - sat[d * (w + 1) + a] + sat[b * (w + 1) + a]) / ((c - a) * (d - b));+ if (fr[y * w + x] - mean > 38) { count++; sx += x; sy += y; minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); }+ }+ // Only something shaped like the mark counts: about square and about its size. A lamp's reflection on wet ground is+ // a long thin streak and passes the brightness test (Last Train, 0.5 s).+ const bw = maxX - minX + 1, bh = maxY - minY + 1;+ const markLike = bw >= mark.r * 0.8 && bh >= mark.r * 0.8 && bw <= mark.r * 3.2 && Math.abs(bw - bh) <= 0.5 * Math.max(bw, bh);+ // A copy sits level with the real mark; reflections lie lower, at the band's bottom edge.+ const level = Math.abs(y0 + sy / Math.max(1, count) - mark.cy) < mark.r * 0.5;+ if (count > 150 * scale * scale && markLike && level) hits.push({ t: f / fps, x: x0 + sx / count, y: y0 + sy / count });+ }+ // The copy drifts while it shows (12.0-12.8 s moved it about 40 px), so a span only lasts while it stays within a few+ // pixels, and each is painted where it averages.+ const near = 8 * scale;+ const spans: { at: number; to: number; x: number; y: number; n: number }[] = [];+ for (const h2 of hits) {+ const last = spans.at(-1);+ if (last && h2.t - last.to <= 0.3 && Math.hypot(h2.x - last.x / last.n, h2.y - last.y / last.n) < near) {+ last.to = h2.t; last.x += h2.x; last.y += h2.y; last.n++;+ continue;+ }+ spans.push({ at: h2.t, to: h2.t, x: h2.x, y: h2.y, n: 1 });+ }+ return spans.map((sp) => ({ at: Math.max(0, sp.at - 0.07), to: sp.to + 1 / fps + 0.07, x: sp.x / sp.n, y: sp.y / sp.n }));+}+async function probe(file: string): Promise<ClipInfo> {// A raw ffprobe dump ("moov atom not found") told the user nothing. Say which file and what to do about it.- const { stdout } = await run(FFPROBE, ["-v", "error", "-show_entries", "stream=codec_type,width,height:format=duration", "-of", "json", file]).catch(() => {+ const { stdout } = await run(FFPROBE, ["-v", "error", "-show_entries", "stream=codec_type,width,height,duration:format=duration", "-of", "json", file]).catch(() => {throw new Error(`"${basename(file)}" isn't a playable video - it may be an unfinished download or a ZIP of several clips. Remove it, or pick other clips.`);});- const data = JSON.parse(stdout) as { streams: { codec_type: string; width?: number; height?: number }[]; format: { duration: string } };+ const data = JSON.parse(stdout) as { streams: { codec_type: string; width?: number; height?: number; duration?: string }[]; format: { duration: string } };const video = data.streams.find((s) => s.codec_type === "video");if (!video?.width || !video.height) throw new Error(`${file} has no video stream.`);+ // A clip lasts as long as its PICTURE. AI clips carry 0.03-0.05 s more sound than picture, and the file's duration is+ // the longer of the two, so each join padded the picture with repeated frames: a visible hitch at every cut.+ const picture = Number(video.duration);return {width: video.width,height: video.height,- duration: Number(data.format.duration),+ duration: picture > 0 ? picture : Number(data.format.duration),hasAudio: data.streams.some((s) => s.codec_type === "audio"),};}@@ -71,60 +254,6 @@ export async function extractAudio(video: string, target: string): Promise<{ outreturn { output: target, duration: Number(stdout.trim()) };}-const SAY = process.env.FLOW_MCP_SAY ?? "say";--// The voices this computer has installed. On a Mac that is `say` (Premium voices appear as soon as the user downloads-// them in System Settings); on Windows it is the built-in speech engine, the voices under Settings > Time & language >-// Speech. The Windows branch is written to the documented System.Speech API but has not been run on a real PC yet.-export async function localVoices(): Promise<{ name: string; description: string }[]> {- if (IS_WIN) {- try {- const out = powershell(- "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).GetInstalledVoices() | Where-Object { $_.Enabled } | ForEach-Object { $_.VoiceInfo.Name + '|' + $_.VoiceInfo.Culture.Name }",- );- return out- .split(/\r?\n/)- .map((l) => l.trim().split("|"))- .filter(([name, culture]) => name && /^en-/i.test(culture ?? ""))- .map(([name, culture]) => ({ name, description: `${culture} · Windows, free` }));- } catch {- return [];- }- }- const { stdout } = await run(SAY, ["-v", "?"], { maxBuffer: 4 * 1024 * 1024 }).catch(() => ({ stdout: "" }));- return stdout- .split("\n")- .map((line) => line.match(/^(.+?)\s{2,}(\w{2}_\w{2})\s+#\s*(.*)$/))- .filter((m): m is RegExpMatchArray => Boolean(m) && /^en_/.test(m![2]))- .map((m) => ({ name: m[1].trim(), description: `${m[2].replace("_", "-")} · macOS, free` }))- .filter((v) => !/^(Bad News|Bahh|Bells|Boing|Bubbles|Cellos|Good News|Jester|Organ|Superstar|Trinoids|Whisper|Wobble|Zarvox|Albert|Fred|Grandma|Grandpa|Junior|Kathy|Princess|Ralph|Rocko|Shelley|Sandy|Eddy|Flo|Reed|Rishi)/.test(v.name));-}--// Speaks a line with this computer's own voice. Free and instant, but only as good as the installed voice.-export async function speakLocally(text: string, voice: string, target: string): Promise<{ output: string; duration: number }> {- const stem = target.replace(/\.\w+$/, "");- const raw = stem + (IS_WIN ? ".wav" : ".aiff");- if (IS_WIN) {- // The line goes through a file, never the command line, so quotes or symbols in it cannot break the script.- const lineFile = stem + ".line.txt";- writeFileSync(lineFile, text, "utf8");- try {- powershell(- `Add-Type -AssemblyName System.Speech; $s = New-Object System.Speech.Synthesis.SpeechSynthesizer; $s.SelectVoice(${psQuote(voice)}); $s.SetOutputToWaveFile(${psQuote(raw)}); $s.Speak([System.IO.File]::ReadAllText(${psQuote(lineFile)}, [System.Text.Encoding]::UTF8)); $s.Dispose()`,- 300_000,- );- } finally {- rmSync(lineFile, { force: true });- }- } else {- await run(SAY, ["-v", voice, "-r", "168", "-o", raw, text]);- }- await run(FFMPEG, ["-y", "-i", raw, "-af", "highpass=f=80,acompressor=threshold=-18dB:ratio=3:attack=5:release=120,loudnorm=I=-16:TP=-1.5:LRA=11", "-ar", "48000", "-ac", "2", target]);- rmSync(raw, { force: true });- const { stdout } = await run(FFPROBE, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", target]);- return { output: target, duration: Number(stdout.trim()) };-}-export interface VoiceLine {file: string;from?: number;@@ -199,62 +328,226 @@ export async function voiceTrack(lines: VoiceLine[], out: string): Promise<{ fil}}+// A music level that changes over the film, as one ffmpeg volume expression of straight lines between the given points.+function musicCurve(points?: { at: number; volume: number }[]): string {+ if (!points?.length) return "";+ const p = [...points].sort((a, b) => a.at - b.at);+ let expr = p[p.length - 1].volume.toFixed(3);+ for (let i = p.length - 2; i >= 0; i--) {+ const [a, b] = [p[i], p[i + 1]];+ const line = `${a.volume.toFixed(3)}+(${(b.volume - a.volume).toFixed(3)})*(t-${a.at.toFixed(3)})/${Math.max(0.001, b.at - a.at).toFixed(3)}`;+ expr = `if(lt(t,${b.at.toFixed(3)}),${line},${expr})`;+ }+ return `,volume='if(lt(t,${p[0].at.toFixed(3)}),${p[0].volume.toFixed(3)},${expr})':eval=frame`;+}+// Joins the scene clips into one film, keeping their own sound and laying music / voiceover on top.-export async function assemble(o: AssembleOptions): Promise<{ output: string; clips: string[]; duration: number; held_last_frame: number }> {+export async function assemble(o: AssembleOptions): Promise<{ output: string; clips: string[]; duration: number; held_last_frame: number; loudness?: number }> {// Clips can now come from anywhere, so the project folder the film is saved into may not exist yet.if (o.clips?.length) mkdirSync(o.dir, { recursive: true });const out = join(o.dir, o.output_name.replace(/[^\w.-]+/g, "_").replace(/(\.mp4)?$/, ".mp4"));const clips = (o.clips?.length ? o.clips : defaultClips(o.dir)).filter((c) => c !== out);if (!clips.length) throw new Error(`No clips found in ${o.dir}. Generate or download a clip first, or pass clips explicitly.`);- for (const f of [...clips, o.music, o.voiceover]) if (f && !existsSync(f)) throw new Error(`File not found: ${f}`);+ for (const f of [...clips, o.music, o.voiceover, ...(o.inserts ?? []).map((x) => x.clip)]) if (f && !existsSync(f)) throw new Error(`File not found: ${f}`);+ // Trimming lives here, so a dead second at the start of a take or an awkward pause at its end never needs a+ // separate editor. The window is clamped to the clip, so a slightly long "to" is harmless.let infos = await Promise.all(clips.map(probe));+ const windows = clips.map((_, i) => {+ const t = o.trims?.[i];+ const from = Math.min(Math.max(0, t?.from ?? 0), Math.max(0, infos[i].duration - 0.2));+ const to = Math.min(infos[i].duration, Math.max(from + 0.2, t?.to ?? infos[i].duration));+ const trimmed = from > 0.01 || to < infos[i].duration - 0.01;+ // A take's background noise can sit several dB above the clip before it, so the room "jumps" at the cut: volume+ // levels it, and fades ease it in. Trimmed edges always get a 15 ms fade so a cut never clicks.+ const fade = (s: number | undefined, cut: boolean) => Math.min(2, Math.max(cut ? 0.015 : 0, s ?? 0));+ // A crop is a punch-in on part of the frame, in fractions of its width and height (h defaults to w, which keeps the+ // shape): it hides something the model put at an edge, like a phone on a stand in the corner of a take.+ const { crop, cw, ch } = cropFilter(t?.crop);+ return {+ from, to, trimmed, crop, cw, ch,+ volume: Math.min(2, Math.max(0, t?.volume ?? 1)),+ fadeIn: fade(t?.fade_in, from > 0.01), fadeOut: fade(t?.fade_out, to < infos[i].duration - 0.01),+ soften: Math.min(3, Math.max(0, t?.soften_in ?? 0)),+ // A clip animated from the one before's last frame starts on the same picture but can come back paler (Last Train,+ // 2026-11-06: colour 6.8 -> 5.7, so the join showed): saturation scales its colour to match its neighbours.+ saturation: Math.min(2, Math.max(0.5, t?.saturation ?? 1)),+ };+ });+ // A cropped clip is only as big as what is kept, so a vertical picture cut out of a 16:9 export sizes the film as+ // vertical, not as the landscape canvas it came in.+ infos = infos.map((info, i) => ({+ ...info,+ duration: windows[i].to - windows[i].from,+ width: Math.round(info.width * windows[i].cw),+ height: Math.round(info.height * windows[i].ch),+ }));+ // A cutaway is placed in the covered clip's own kept time and clamped to it, so it can never run into the next clip.+ const userClips = clips.length;+ const inserts = await Promise.all(+ (o.inserts ?? []).map(async (x) => {+ if (x.over < 1 || x.over > userClips) throw new Error(`Insert "${basename(x.clip)}" covers clip ${x.over}, but the film has ${userClips} clip(s).`);+ const k = x.over - 1;+ const info = await probe(x.clip);+ const from = Math.min(Math.max(0, x.from ?? 0), Math.max(0, info.duration - 0.2));+ const at = Math.min(Math.max(0, x.at), Math.max(0, infos[k].duration - 0.2));+ const seconds = Math.min(x.seconds ?? Infinity, info.duration - from, infos[k].duration - at);+ return { k, file: x.clip, from, at, seconds, volume: x.volume ?? 0.3, hasAudio: info.hasAudio, crop: cropFilter(x.crop).crop };+ }),+ );+ if (o.end_card?.text.trim()) {+ // The card is made at the film's size from the last kept frame of the last clip, then joined like any other clip.+ const work = mkdtempSync(join(tmpdir(), "flow-card-"));+ const last = clips.length - 1;+ const { width: w, height: h } = infos.reduce((a, b) => (b.width * b.height > a.width * a.height ? b : a));+ const still = join(work, "last.jpg");+ await run(FFMPEG, ["-y", "-ss", Math.max(0, windows[last].to - 0.1).toFixed(3), "-i", clips[last], "-frames:v", "1", "-q:v", "2", still]).catch(() => undefined);+ const png = await renderEndCard(o.end_card.text, w, h, still, join(work, "card.png"));+ const seconds = Math.min(10, Math.max(1, o.end_card.seconds ?? 2.5));+ const card = join(o.dir, `${o.output_name.replace(/[^\w.-]+/g, "_").replace(/\.mp4$/, "")}-endcard.mp4`);+ await run(FFMPEG, [+ "-y", "-loop", "1", "-t", seconds.toFixed(2), "-i", png, "-f", "lavfi", "-t", seconds.toFixed(2), "-i", "anullsrc=r=48000:cl=stereo",+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", "24", "-c:a", "aac", "-shortest", card,+ ]);+ rmSync(work, { recursive: true, force: true });+ clips.push(card);+ windows.push({ from: 0, to: seconds, trimmed: false, crop: "", cw: 1, ch: 1, volume: 1, fadeIn: 0, fadeOut: 0, soften: 0, saturation: 1 });+ infos.push({ width: w, height: h, duration: seconds, hasAudio: true });+ }// A narration longer than the footage would be cut off, so the last frame is held until the voice finishes.let hold = 0;if (o.hold_last_frame !== false && o.voiceover) {const { stdout } = await run(FFPROBE, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", o.voiceover]);hold = Math.max(0, Number(stdout.trim()) + 0.6 - infos.reduce((sum, i) => sum + i.duration, 0));}- // Size the film to the biggest clip so a 720p opener cannot pull a 1080p clip down with it.- const { width, height } = infos.reduce((a, b) => (b.width * b.height > a.width * a.height ? b : a));+ if (o.end_hold) hold = Math.max(hold, o.end_hold.seconds);+ // Size the film to the biggest clip so a 720p opener cannot pull a 1080p clip down with it, or to `size` when given+ // ("1080x1920" for a phone-ready master). Always even, which the encoder needs.+ const biggest = infos.reduce((a, b) => (b.width * b.height > a.width * a.height ? b : a));+ const asked = o.size?.match(/^(\d{2,4})x(\d{2,4})$/);+ const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);+ const width = even(asked ? Number(asked[1]) : biggest.width);+ const height = even(asked ? Number(asked[2]) : biggest.height);const args: string[] = ["-y"];- for (const clip of clips) args.push("-i", clip);+ clips.forEach((clip, i) => {+ const win = windows[i];+ if (win.trimmed) args.push("-ss", win.from.toFixed(3), "-t", (win.to - win.from).toFixed(3));+ args.push("-i", clip);+ });const filters: string[] = [];// The clips' own sound used to play at full volume no matter what, drowning a narration laid on top. Music already// had its own level; the clips now do too.const clipVolume = Math.min(1, Math.max(0, o.clip_volume ?? 1));+ const edges = (i: number) => {+ const { fadeIn, fadeOut } = windows[i];+ return (fadeIn > 0 ? `,afade=t=in:d=${fadeIn.toFixed(3)}` : "") ++ (fadeOut > 0 ? `,afade=t=out:st=${Math.max(0, infos[i].duration - fadeOut).toFixed(3)}:d=${fadeOut.toFixed(3)}` : "");+ };+ const blurs = await Promise.all(+ clips.map((clip, i) => (i > 0 && windows[i].soften > 0 ? matchSoftness(clips[i - 1], windows[i - 1].to, clip, windows[i].from) : Promise.resolve(0))),+ );infos.forEach((info, i) => {const freeze = hold > 0.05 && i === infos.length - 1 ? `,tpad=stop_mode=clone:stop_duration=${hold.toFixed(2)}` : "";- filters.push(- `[${i}:v]scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=24${freeze}[v${i}]`,- );+ const base = `[${i}:v]${windows[i].crop}scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=24,setpts=PTS-STARTPTS${Math.abs(windows[i].saturation - 1) > 0.005 ? `,hue=s=${windows[i].saturation.toFixed(3)}` : ""}`;+ const end = `${freeze}[v${i}]`;+ if (blurs[i] > 0) {+ // Blurred copy on top, fading out over soften seconds: the clip opens as soft as the one before ends.+ const d = windows[i].soften.toFixed(2);+ filters.push(+ `${base},split[sh${i}][so${i}]`,+ `[so${i}]gblur=sigma=${blurs[i].toFixed(2)}[bl${i}]`,+ `[bl${i}][sh${i}]blend=all_expr='A*(1-min(1,T/${d}))+B*min(1,T/${d})'${end}`,+ );+ } else {+ filters.push(`${base}${end}`);+ }filters.push(info.hasAudio- ? `[${i}:a]aresample=48000,aformat=channel_layouts=stereo,volume=${clipVolume}${hold > 0.05 && i === infos.length - 1 ? `,apad=pad_dur=${hold.toFixed(2)}` : ""}[a${i}]`+ ? `[${i}:a]atrim=end=${info.duration.toFixed(3)},asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume=${(clipVolume * windows[i].volume).toFixed(3)}${edges(i)}${hold > 0.05 && i === infos.length - 1 ? `,apad=pad_dur=${hold.toFixed(2)}` : ""}[a${i}]`: `anullsrc=r=48000:cl=stereo,atrim=duration=${(info.duration + (i === infos.length - 1 ? hold : 0)).toFixed(2)}[a${i}]`,);});- filters.push(`${infos.map((_, i) => `[v${i}][a${i}]`).join("")}concat=n=${clips.length}:v=1:a=1[v][clipaudio]`);+ let input = clips.length;+ const vOut = infos.map((_, i) => `[v${i}]`);+ const aOut = infos.map((_, i) => `[a${i}]`);+ inserts.forEach((x, j) => {+ args.push("-i", x.file);+ const end = (x.at + x.seconds).toFixed(3);+ filters.push(+ `[${input}:v]trim=start=${x.from.toFixed(3)}:duration=${x.seconds.toFixed(3)},setpts=PTS-STARTPTS+${x.at.toFixed(3)}/TB,${x.crop}` ++ `scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=24[iv${j}]`,+ `${vOut[x.k]}[iv${j}]overlay=enable='between(t,${x.at.toFixed(3)},${end})':eof_action=pass[ov${j}]`,+ );+ vOut[x.k] = `[ov${j}]`;+ if (x.hasAudio && x.volume > 0) {+ const ms = Math.round(x.at * 1000);+ filters.push(+ `[${input}:a]atrim=start=${x.from.toFixed(3)}:duration=${x.seconds.toFixed(3)},asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume=${x.volume},adelay=${ms}|${ms}[ia${j}]`,+ `${aOut[x.k]}[ia${j}]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[oa${j}]`,+ );+ aOut[x.k] = `[oa${j}]`;+ }+ input++;+ });+ let watermarkNote: string | undefined;+ let markDir = "";+ let markBox: { cx: number; cy: number; r: number } | null = null;+ if (o.remove_watermark) {+ markDir = mkdtempSync(join(tmpdir(), "flow-mark-"));+ const mask = join(markDir, "mark.pgm");+ const samples = clips.slice(0, userClips).flatMap((file, i) => {+ const vf = `${windows[i].crop}scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2`;+ const span = windows[i].to - windows[i].from;+ const n = Math.max(6, Math.min(24, Math.round(span * 1.5)));+ return Array.from({ length: n }, (_, j) => ({ file, at: windows[i].from + (span * (j + 0.5)) / n, vf }));+ });+ markBox = await watermarkMask(samples, width, height, mask, o.watermark_margin ?? 0);+ if (markBox) {+ filters.push(`${infos.map((_, i) => `${vOut[i]}${aOut[i]}`).join("")}concat=n=${clips.length}:v=1:a=1[vraw][clipaudio]`);+ filters.push(`[vraw]removelogo=filename=${mask.replace(/[\\:']/g, "\\$&")}[v]`);+ watermarkNote = "watermark painted out";+ } else {+ filters.push(`${infos.map((_, i) => `${vOut[i]}${aOut[i]}`).join("")}concat=n=${clips.length}:v=1:a=1[v][clipaudio]`);+ watermarkNote = "no corner watermark found; nothing painted out";+ }+ } else {+ filters.push(`${infos.map((_, i) => `${vOut[i]}${aOut[i]}`).join("")}concat=n=${clips.length}:v=1:a=1[v][clipaudio]`);+ }+ let picture = "[v]";+ if (o.end_hold?.fade) {+ const total = infos.reduce((sum, i) => sum + i.duration, 0) + hold;+ filters.push(`[v]fade=t=out:st=${(total - o.end_hold.fade).toFixed(3)}:d=${o.end_hold.fade.toFixed(3)}[vfade]`);+ picture = "[vfade]";+ }const mix = ["[clipaudio]"];- let input = clips.length;if (o.music) {args.push("-stream_loop", "-1", "-i", o.music);- filters.push(`[${input}:a]aresample=48000,aformat=channel_layouts=stereo,volume=${o.music_volume}[music]`);+ const curve = musicCurve(o.music_curve);+ filters.push(`[${input}:a]aresample=48000,aformat=channel_layouts=stereo,volume=${o.music_volume}${curve}[music]`);mix.push("[music]");input++;}if (o.voiceover) {args.push("-i", o.voiceover);- filters.push(`[${input}:a]aresample=48000,aformat=channel_layouts=stereo[vo]`);+ if (o.music && o.duck_music) {+ filters.push(+ `[${input}:a]aresample=48000,aformat=channel_layouts=stereo,asplit=2[vo][side]`,+ `[music][side]sidechaincompress=threshold=0.02:ratio=6:attack=60:release=500[ducked]`,+ );+ mix[mix.indexOf("[music]")] = "[ducked]";+ } else {+ filters.push(`[${input}:a]aresample=48000,aformat=channel_layouts=stereo[vo]`);+ }mix.push("[vo]");}- filters.push(mix.length > 1 ? `${mix.join("")}amix=inputs=${mix.length}:duration=first:dropout_transition=0:normalize=0[a]` : "[clipaudio]anull[a]");+ const level = o.loudness !== undefined ? `loudnorm=I=${Math.min(-9, Math.max(-30, o.loudness))}:TP=-1.5:LRA=11,aresample=48000` : "anull";+ filters.push(mix.length > 1 ? `${mix.join("")}amix=inputs=${mix.length}:duration=first:dropout_transition=0:normalize=0,${level}[a]` : `[clipaudio]${level}[a]`);const output = out;args.push("-filter_complex", filters.join(";"),- "-map", "[v]", "-map", "[a]",+ "-map", picture, "-map", "[a]","-c:v", "libx264", "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p","-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart",output,@@ -264,6 +557,63 @@ export async function assemble(o: AssembleOptions): Promise<{ output: string; cl} catch (err) {const e = err as NodeJS.ErrnoException & { stderr?: string };throw new Error(e.code === "ENOENT" ? `ffmpeg is not installed (${FFMPEG_HINT}).` : `ffmpeg failed: ${(e.stderr ?? String(e)).slice(-600)}`);+ } finally {+ if (markDir) rmSync(markDir, { recursive: true, force: true });+ }+ if (markBox) {+ const ghosts = await ghostMarks(output, width, height, markBox);+ if (ghosts.length) {+ // The same filled-sparkle fill as the main mark, moved onto each copy and switched on only while it shows: a box+ // fill (delogo) left a visible smudged rectangle on the wet floor.+ const dir = mkdtempSync(join(tmpdir(), "flow-ghost-"));+ const R = markBox.r + 6 * (Math.min(width, height) / 1080);+ const steps = ghosts.map((g, n) => {+ const mask = Buffer.alloc(width * height);+ for (let y = Math.floor(g.y - R - 2); y <= Math.ceil(g.y + R + 2); y++) for (let x = Math.floor(g.x - R - 2); x <= Math.ceil(g.x + R + 2); x++) {+ if (x < 0 || y < 0 || x >= width || y >= height) continue;+ const ax = Math.abs(x - g.x) / R, ay = Math.abs(y - g.y) / R;+ if (Math.cbrt(ax * ax) + Math.cbrt(ay * ay) <= 1.15) mask[y * width + x] = 255;+ }+ const file = join(dir, `ghost-${n}.pgm`);+ writeFileSync(file, Buffer.concat([Buffer.from(`P5\n${width} ${height}\n255\n`), mask]));+ return `removelogo=filename=${file.replace(/[\\:']/g, "\\$&")}:enable='between(t,${g.at.toFixed(2)},${g.to.toFixed(2)})'`;+ });+ const fixed = output.replace(/\.mp4$/, "") + "-ghosts.mp4";+ try {+ await run(FFMPEG, ["-y", "-v", "error", "-i", output, "-vf", steps.join(","), "-c:v", "libx264", "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p", "-c:a", "copy", "-movflags", "+faststart", fixed], { maxBuffer: 32 * 1024 * 1024 });+ renameSync(fixed, output);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ watermarkNote = `watermark painted out, plus ${ghosts.length} brief second cop${ghosts.length === 1 ? "y" : "ies"} at ${ghosts.map((g) => `${g.at.toFixed(1)}-${g.to.toFixed(1)} s`).join(", ")}`;+ }+ }+ // One loudnorm pass is held back by its true-peak ceiling: Three Tiers asked for -14 and came out at -14.9. Measure+ // the film and close the gap with plain gain, a limiter keeping the peaks under -1.5 dB.+ let lufs: number | undefined;+ if (o.loudness !== undefined) {+ const target = Math.min(-9, Math.max(-30, o.loudness));+ lufs = await integratedLoudness(output);+ if (lufs !== undefined && Math.abs(lufs - target) > 0.3) {+ const fixed = output.replace(/\.mp4$/, "") + "-level.mp4";+ await run(FFMPEG, [+ "-y", "-i", output, "-c:v", "copy",+ "-af", `volume=${(target - lufs).toFixed(2)}dB,alimiter=limit=0.84:level=false:attack=2:release=50`,+ "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", fixed,+ ], { maxBuffer: 32 * 1024 * 1024 });+ renameSync(fixed, output);+ lufs = await integratedLoudness(output);+ }}- return { output, clips, duration: infos.reduce((sum, i) => sum + i.duration, 0) + hold, held_last_frame: Number(hold.toFixed(2)) };+ return {+ output, clips, duration: infos.reduce((sum, i) => sum + i.duration, 0) + hold, held_last_frame: Number(hold.toFixed(2)),+ ...(lufs !== undefined ? { loudness: Number(lufs.toFixed(1)) } : {}),+ ...(watermarkNote ? { watermark: watermarkNote } : {}),+ };+}++async function integratedLoudness(file: string): Promise<number | undefined> {+ const { stderr } = await run(FFMPEG, ["-hide_banner", "-i", file, "-vn", "-af", "loudnorm=print_format=json", "-f", "null", "-"], { maxBuffer: 32 * 1024 * 1024 });+ const m = String(stderr).match(/"input_i"\s*:\s*"(-?[\d.]+)"/);+ return m ? Number(m[1]) : undefined;}diff --git a/src/captions.ts b/src/captions.tsindex 8bbf662..7781104 100644--- a/src/captions.ts+++ b/src/captions.ts@@ -34,6 +34,9 @@ const SPEECH_MODELS = {// Only names the spoken language, for "auto": right on all 8 test languages in 0.2 s, so an English speaker who never// picks a language is not sent the 574 MB model.detect: { file: "ggml-base-q5_1.bin", mb: 60, purpose: "that recognises the language" },+ // Silero voice-activity detection (0.9 MB): finds where people actually speak, so each stretch can be heard on its+ // own (see speechSpans). Lives in ggml-org's own collection, not whisper.cpp's.+ vad: { file: "ggml-silero-v5.1.2.bin", mb: 0.8, purpose: "that finds where the speech is", base: "https://huggingface.co/ggml-org/whisper-vad/resolve/main" },} as const;type SpeechModel = keyof typeof SPEECH_MODELS;const MODEL_BASE = (process.env.FLOW_MCP_MODEL_BASE ?? "https://huggingface.co/ggerganov/whisper.cpp/resolve/main").replace(/\/+$/, "");@@ -85,6 +88,10 @@ export interface CaptionOptions {lead?: number;text?: string;language?: string;+ // Word timings measured elsewhere, used instead of hearing the whole film. A film joined from separate takes is+ // better timed from each take heard on its own: heard whole, Last Train's train noise stretched "second date" over+ // 7 s and squeezed "Go. You'll miss" onto one instant, while each clip on its own was timed right.+ words?: Word[];}// The languages the panel offers, by their own names. whisper.cpp knows about 100; any other code works through the MCP.@@ -135,6 +142,7 @@ const PREFERENCE: Record<SpeechModel, string[]> = {other: ["ggml-large-v3-turbo.bin", "ggml-large-v3-turbo-q5_0.bin", "ggml-large-v3.bin", "ggml-medium.bin", "ggml-small.bin"],// Any multilingual model can name the language; the fastest goes first.detect: ["ggml-base-q5_1.bin", "ggml-base.bin", "ggml-small-q5_1.bin", "ggml-small.bin", "ggml-large-v3-turbo-q5_0.bin", "ggml-large-v3-turbo.bin", "ggml-medium.bin", "ggml-large-v3.bin"],+ vad: ["ggml-silero-v5.1.2.bin"],};const installed = (kind: SpeechModel): string | undefined => PREFERENCE[kind].flatMap((name) => MODEL_DIRS.map((d) => join(d, name))).find((p) => existsSync(p));@@ -175,8 +183,8 @@ export async function captionSetup(): Promise<{const forced = Boolean(process.env.FLOW_MCP_WHISPER_MODEL);// The models are not a precondition: each downloads itself the first time it is needed. The panel uses these to say// how big the wait will be.- const models = { english: forced || Boolean(installed("english")), other: forced || Boolean(installed("other")), detect: forced || Boolean(installed("detect")) };- const download_mb = { english: SPEECH_MODELS.english.mb, other: SPEECH_MODELS.other.mb, detect: SPEECH_MODELS.detect.mb };+ const models = { english: forced || Boolean(installed("english")), other: forced || Boolean(installed("other")), detect: forced || Boolean(installed("detect")), vad: Boolean(installed("vad")) };+ const download_mb = { english: SPEECH_MODELS.english.mb, other: SPEECH_MODELS.other.mb, detect: SPEECH_MODELS.detect.mb, vad: SPEECH_MODELS.vad.mb };return { ready: whisper, whisper, whisper_hint: whisper ? undefined : WHISPER_HINT, models, download_mb, languages: CAPTION_LANGUAGES, models_dir: MODEL_DIR };}@@ -197,7 +205,7 @@ function fetchModel(kind: SpeechModel): Promise<string> {// Claude's connector. curl ships with macOS and Windows 10+, follows the redirect to the download host, and can// only fail itself.const part = `${dest}.part`;- await run("curl", ["-L", "--fail", "--silent", "--show-error", "--connect-timeout", "20", "--retry", "2", "-o", part, `${MODEL_BASE}/${file}`], BIG).catch((err: RunError) => {+ await run("curl", ["-L", "--fail", "--silent", "--show-error", "--connect-timeout", "20", "--retry", "2", "-o", part, `${process.env.FLOW_MCP_MODEL_BASE || !("base" in SPEECH_MODELS[kind]) ? MODEL_BASE : (SPEECH_MODELS[kind] as { base: string }).base}/${file}`], BIG).catch((err: RunError) => {rmSync(part, { force: true });throw new Error(err.code === "ENOENT" ? "curl is not installed" : String(err.stderr || err.message).trim().split("\n").at(-1));});@@ -242,7 +250,7 @@ async function probe(file: string, needPicture = true): Promise<{ width: number;}interface WhisperJson {- transcription: { tokens?: { text: string; offsets: { from: number; to: number } }[] }[];+ transcription: { offsets: { from: number; to: number }; tokens?: { text: string; offsets: { from: number; to: number } }[] }[];result?: { language?: string };}@@ -330,13 +338,90 @@ function whisperFailed(err: RunError): never {}// language: a whisper code (en, es, ja...) or "auto", which detects it first.+// Where people speak in a mixed sound track (dialogue over engine noise, narration over crashes), from whisper.cpp's+// own voice-activity detector (whisper-vad-speech-segments, installed with whisper-cpp). Measured on First Lesson+// against the loudness: "See?" 15.39 s and "You were braver" 23.78 s, where hearing the whole track had them 0.5 and+// 0.9 s early. Whisper's own segments are no substitute: they run on through seconds of engine noise, and a long tail+// mis-times words just as a long lead does. Stretches closer than 0.4 s are heard together; a first stretch that+// starts within 2 s keeps the opening, where a shout over a sound effect can slip past the detector.+const VAD_SEGMENTS = process.env.FLOW_MCP_WHISPER_VAD ?? WHISPER.replace(/whisper-cli(\.exe)?$/, "whisper-vad-speech-segments$1");+async function voiceSpans(wav: string): Promise<[number, number, number][]> {+ const vad = installed("vad") ?? (await fetchModel("vad"));+ const { stdout, stderr } = await run(VAD_SEGMENTS, ["-vm", vad, "-f", wav], BIG);+ // The list is printed once, on stdout or stderr depending on the build, in centiseconds.+ const pick = (t: string) => [...t.matchAll(/start = ([\d.]+), end = ([\d.]+)/g)].map((m) => [Number(m[1]) / 100, Number(m[2]) / 100]);+ const found = (pick(stdout).length ? pick(stdout) : pick(stderr)).filter(([a, b], i, all) => b > a && (i === 0 || a >= all[i - 1][0]));+ // Each stretch: [window start, window end, where the speech itself starts].+ const spans: [number, number, number][] = [];+ for (const [from, to] of found) {+ const last = spans[spans.length - 1];+ if (last && from - last[1] < 0.4) last[1] = to + 0.3;+ else spans.push([Math.max(last ? last[1] : 0, from - 0.3), to + 0.3, from]);+ }+ // The opening stretch is heard from 0:00, because the detector can miss a first shout over a sound effect ("Dad!" over+ // the stall in First Lesson). Its floor is the first loud spike well above the background (18 dB over the quietest+ // fifth), or the detector's onset if that comes first: without a floor, Theo's line at 1.3 s in Last Train was+ // bunched at 0:00, with "fifteen" lit before it was said.+ if (spans.length && spans[0][0] < 2) {+ const level = loudness(wav);+ const quiet = [...level].sort((x, y) => x - y)[Math.floor(level.length / 5)] ?? -60;+ const onset = spans[0][2];+ let spike = level.findIndex((v) => v > quiet + 18) * FRAME;+ if (spike < 0 || spike > onset) spike = onset;+ // Heard from just before that spike, not from 0:00: a second of footsteps ahead of the first word was enough for+ // whisper to bunch the whole line onto one instant.+ spans[0] = [Math.max(0, spike - 0.2), spans[0][1], Math.max(0, spike - 0.05)];+ }+ return spans;+}++// Loudness of a 16 kHz mono 16-bit WAV in 50 ms frames, in dB.+const FRAME = 0.05;+function loudness(wav: string): number[] {+ const buf = readFileSync(wav);+ const data = buf.indexOf("data") + 8;+ const step = Math.round(16000 * FRAME);+ const out: number[] = [];+ for (let at = data; at + step * 2 <= buf.length; at += step * 2) {+ let sum = 0;+ for (let i = 0; i < step; i++) sum += buf.readInt16LE(at + i * 2) ** 2;+ out.push(10 * Math.log10(sum / step / 32768 ** 2 + 1e-12));+ }+ return out;+}++// The stretches of a clean narration track that hold speech: everything between silences of 0.6 s or more, with a+// little air kept either side so no word is clipped.+async function speechSpans(wav: string): Promise<[number, number][]> {+ const { stderr } = await run(FFMPEG, ["-v", "info", "-i", wav, "-af", "silencedetect=noise=-40dB:d=0.6", "-f", "null", "-"], BIG);+ const total = Number(stderr.match(/Duration: (\d+):(\d+):([\d.]+)/)?.slice(1).reduce((t, v) => t * 60 + Number(v), 0) ?? 0);+ const quiet = [...stderr.matchAll(/silence_start: ([\d.]+)[\s\S]*?silence_end: ([\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]);+ const spans: [number, number][] = [];+ let at = 0;+ for (const [a, b] of quiet) {+ if (a - at > 0.2) spans.push([Math.max(0, at - 0.15), a + 0.15]);+ at = b;+ }+ if (total - at > 0.2) spans.push([Math.max(0, at - 0.15), total]);+ return spans.length ? spans : [[0, total]];+}+export async function transcribe(video: string, language = "auto"): Promise<Transcript> {const info = await probe(video, false);if (!info.audio) throw new Error(`"${basename(video)}" has no sound, so there are no words to caption.`);const asked = language.trim().toLowerCase() || "auto";if (!/^(auto|[a-z]{2,3})$/.test(asked)) throw new Error(`"${language}" isn't a language code. Use a code such as en, es or ja, or auto.`);const st = statSync(video);- const cacheFile = (...parts: string[]) => join(CACHE_DIR, `${createHash("sha1").update([video, st.size, st.mtimeMs, ...parts].join("|")).digest("hex").slice(0, 16)}.json`);+ // flow_assemble keeps the narration it laid over a film as <film>-voice.wav, on the film's own timeline. Words are+ // timed from that clean track when it is there: under the clips' crashes and music, whisper squeezed every word+ // after a pause onto one instant (five words at 10.18 s, zero length) and dropped the punctuation.+ const voice = video.replace(/\.\w+$/, "") + "-voice.wav";+ // It starts at 0:00 like the film and ends with the last line, so it may be shorter, never longer.+ const voiceLength = existsSync(voice) ? (await probe(voice, false).catch(() => ({ duration: 0 }))).duration : 0;+ const clean = voiceLength > 0 && voiceLength <= info.duration + 1 ? voice : undefined;+ const vst = clean ? statSync(clean) : undefined;+ const cacheFile = (...parts: string[]) =>+ join(CACHE_DIR, `${createHash("sha1").update([video, st.size, st.mtimeMs, ...(vst ? [clean!, vst.size, vst.mtimeMs] : []), "spans-v7", ...parts].join("|")).digest("hex").slice(0, 16)}.json`);const keep = (t: Transcript, ...files: (string | undefined)[]) => {mkdirSync(CACHE_DIR, { recursive: true });for (const f of files) if (f) writeFileSync(f, JSON.stringify(t));@@ -348,7 +433,7 @@ export async function transcribe(video: string, language = "auto"): Promise<Tranconst work = mkdtempSync(join(tmpdir(), "flow-captions-"));const wav = join(work, "audio.wav");- const extract = () => run(FFMPEG, ["-v", "error", "-y", "-i", video, "-vn", "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav], BIG);+ const extract = () => run(FFMPEG, ["-v", "error", "-y", "-i", clean ?? video, "-vn", "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav], BIG);try {let lang = asked;if (lang === "auto" && !process.env.FLOW_MCP_WHISPER_MODEL) {@@ -360,12 +445,36 @@ export async function transcribe(video: string, language = "auto"): Promise<Tranconst cached = cacheFile(basename(model), lang);if (existsSync(cached)) return keep(JSON.parse(readFileSync(cached, "utf8")) as Transcript, autoFile);if (!existsSync(wav)) await extract();- await run(WHISPER, ["-m", model, "-f", wav, "-l", lang, "-t", THREADS, "-ojf", "-of", join(work, "words"), "-np"], BIG).catch(whisperFailed);- // whisper-cli exits 0 even when it cannot read the audio, and simply writes nothing.- if (!existsSync(join(work, "words.json"))) throw new Error(`whisper.cpp could not read the sound in "${basename(video)}".`);- const json = JSON.parse(readFileSync(join(work, "words.json"), "utf8")) as WhisperJson;- const heard = json.result?.language ?? lang;- const words = wordsFromTokens(json, heard);+ const listen = async (file: string, out: string) => {+ await run(WHISPER, ["-m", model, "-f", file, "-l", lang, "-t", THREADS, "-ojf", "-of", out, "-np"], BIG).catch(whisperFailed);+ // whisper-cli exits 0 even when it cannot read the audio, and simply writes nothing.+ if (!existsSync(out + ".json")) throw new Error(`whisper.cpp could not read the sound in "${basename(video)}".`);+ return JSON.parse(readFileSync(out + ".json", "utf8")) as WhisperJson;+ };+ let heard = lang;+ let words: Word[] = [];+ // Heard as one piece, whisper squeezes the first words after every pause onto one instant (measured: "Why risk it+ // all for one" all at 20.24 s, five words at 10.18 s with zero length) and can lose the punctuation. Each spoken+ // stretch is therefore heard on its own, starting on speech, where token times land within ~50 ms, and shifted back+ // onto the film's timeline. The clean narration track finds its stretches by silence; a mixed track asks whisper's+ // voice-activity detection. If neither works, the whole track is heard at once, as before.+ const spans = clean ? await speechSpans(wav) : await voiceSpans(wav).catch(() => undefined);+ if (spans?.length) {+ for (const [i, [from, to, onset]] of spans.entries()) {+ const part = join(work, `part-${i}.wav`);+ await run(FFMPEG, ["-v", "error", "-y", "-ss", from.toFixed(3), "-t", (to - from).toFixed(3), "-i", wav, "-c:a", "pcm_s16le", part], BIG);+ const json = await listen(part, join(work, `part-${i}`));+ heard = json.result?.language ?? heard;+ // whisper tends to start the first word right at the window's edge, in the air before the speech; the detector+ // knows when the speech begins, so no word starts earlier than that (measured: 0.3 s early without this).+ const floor = onset ?? 0;+ words.push(...wordsFromTokens(json, heard).map((w) => ({ ...w, start: Math.max(w.start + from, floor), end: Math.max(w.end + from, floor + 0.05) })));+ }+ } else {+ const json = await listen(wav, join(work, "words"));+ heard = json.result?.language ?? lang;+ words = wordsFromTokens(json, heard);+ }if (!words.length) throw new Error(`No speech was heard in "${basename(video)}".`);return keep({ words, text: words.map((w) => w.text).join(joiner(heard)), language: heard, model: basename(model) }, cached, autoFile);} finally {@@ -419,8 +528,26 @@ export function alignText(timed: Word[], text: string, lang = "en"): Word[] {}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);+ // The heard words in the same gap are what these replace ("Pym" for "Pim", "12" for "twelve"). Same count: each+ // takes its counterpart's time. Otherwise they share that stretch. Spreading over the whole gap instead put "Pim"+ // straight after the previous line, 4.6 s before it was said.+ // Only real words count: whisper prints a dash between speakers as a token of its own, and pairing "fifty" with+ // it gave a caption of zero length.+ const heard: number[] = [];+ for (let i = k > 0 ? match[k - 1] + 1 : 0; i < (e < m ? match[e] : n); i++) if (a[i]) heard.push(i);+ if (heard.length === e - k) {+ for (let q = k; q < e; q++) {+ out[q].start = timed[heard[q - k]].start;+ out[q].end = timed[heard[q - k]].end;+ }+ k = e;+ continue;+ }+ let from = heard.length ? timed[heard[0]].start : k > 0 ? out[k - 1].end : (timed[0]?.start ?? 0);+ const to = heard.length ? timed[heard[heard.length - 1]].end : e < m ? out[e].start : Math.max(from + 0.35 * (e - k), timed.at(-1)?.end ?? 0);+ // Words the listener missed altogether ("That was the nine forty-nine" heard as "was the 949") were swallowed just+ // before the next word, not somewhere in the pause before them: spread over a 2 s pause, "That" showed 2 s early.+ if (!heard.length && e < m) from = Math.max(from, to - 0.3 * (e - k));const step = Math.max(0.05, (to - from) / (e - k));for (let q = k; q < e; q++) {out[q].start = from + step * (q - k);@@ -468,7 +595,13 @@ function paginate(words: Word[], maxWords: number, maxChars: number, sep: string}function layout(heard: Word[], style: CaptionStyle, width: number, height: number, size: CaptionSize, letters: CaptionLetters, lead: number, lang: string): { pages: Word[][]; states: State[] } {- const words = heard.map((w) => ({ ...w, start: Math.max(0, w.start - lead), end: Math.max(0, w.end - lead) }));+ // A word's end is capped by its length: the speech model lets the last word of a line run on through laughter or a+ // train arriving, which kept "Adventurous!" and "To a second date." on screen for 7 s (Last Train).+ const longest = (t: string) => Math.min(1.4, 0.35 + 0.075 * t.replace(/[^\p{L}\p{N}]/gu, "").length);+ const words = heard.map((w) => {+ const start = Math.max(0, w.start - lead);+ return { ...w, start, end: Math.max(start, Math.min(w.end - lead, start + longest(w.text))) };+ });const s = CAPTION_STYLES[style];const u = (Math.min(width, height) / 100) * scaleOf(size);// Capitals are wider than small letters, so fewer of them fit on a line.@@ -624,14 +757,23 @@ async function withPage<T>(width: number, height: number, html: string, use: (paconst 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 given = o.words?.filter((w) => w.text.trim() && Number.isFinite(w.start) && Number.isFinite(w.end)).sort((p, q) => p.start - q.start);+ const transcript: Transcript = given?.length+ ? { words: given, text: given.map((w) => w.text).join(" "), language: o.language && o.language !== "auto" ? o.language : "en", model: "given timings" }+ : 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");+ // "Unchanged" is judged word by word. Comparing with every space removed made "your iced" equal the misheard+ // "youriced", so a correction that only splits a run-together word was silently thrown away. Only the languages+ // written without spaces compare that way.+ const flat = (s: string) =>+ UNSPACED.has(transcript.language) ? norm(s.replace(/\s+/g, "")) : s.split(/\s+/).map(norm).filter(Boolean).join(" ");+ const same = edited !== undefined && flat(edited) === flat(transcript.text) && !edited.includes("\n");return { transcript, words: edited && !same ? alignText(transcript.words, edited, transcript.language) : 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 }> {+export async function previewCaptions(video: string, opts: CaptionOptions): Promise<{ image: string; at: number }> {+ const o = withDefaults(opts);const info = await probe(video);const { transcript, words } = await timedWords(video, o);const lang = transcript.language;@@ -674,7 +816,12 @@ export interface CaptionResult {model: string;}-export async function burnCaptions(video: string, o: CaptionOptions, output: string): Promise<CaptionResult> {+// The tool and the panel always pass a size and position, but a direct caller may not: without them the page got no+// font size, fell back to the browser's tiny serif default and drew captions nobody could read.+const withDefaults = (o: CaptionOptions): CaptionOptions => ({ ...o, size: o.size ?? "medium", position: o.position ?? "bottom" });++export async function burnCaptions(video: string, opts: CaptionOptions, output: string): Promise<CaptionResult> {+ const o = withDefaults(opts);const info = await probe(video);const { transcript, words } = await timedWords(video, o);const lang = transcript.language;@@ -755,3 +902,25 @@ export function captionedName(dir: string, video: string): string {if (!existsSync(out)) return out;}}++// A closing card for an ad or a film: big centred words over the film's own last frame, blurred and darkened, so the+// card belongs to the film instead of cutting to a flat colour. Drawn by the same headless Chrome as the captions+// (ffmpeg here has no text filters). Type is sized from the frame's short side, so a vertical 9:16 card reads on a phone.+export async function renderEndCard(text: string, width: number, height: number, background: string | undefined, out: string): Promise<string> {+ const bg = background && existsSync(background) ? `data:image/jpeg;base64,${readFileSync(background).toString("base64")}` : "";+ const size = Math.round(Math.min(width, height) * (text.length > 40 ? 0.085 : 0.12));+ const esc = (t: string) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>+ html,body{margin:0;width:${width}px;height:${height}px;overflow:hidden;background:#111}+ .bg{position:absolute;inset:-40px;background:${bg ? `url(${bg}) center/cover` : "#111"};filter:blur(28px) brightness(.42)}+ .t{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:0 8%;+ font:900 ${size}px/1.12 "Arial Black","Helvetica Neue",Arial,sans-serif;color:#fff;text-wrap:balance;+ text-shadow:0 ${Math.round(size / 12)}px ${Math.round(size / 3)}px rgba(0,0,0,.55);white-space:pre-line}+ </style></head><body><div class="bg"></div><div class="t">${esc(text.trim())}</div></body></html>`;+ try {+ await withPage(width, height, html, (page) => page.screenshot({ path: out, type: "png" }));+ } finally {+ releaseBrowser();+ }+ return out;+}diff --git a/src/chain.ts b/src/chain.tsindex bf3f72c..d9b8452 100644--- a/src/chain.ts+++ b/src/chain.ts@@ -16,3 +16,29 @@ export async function extractLastFrame(video: string): Promise<string> {}return out;}++// Saves the first frame of a clip, so a new clip can be made to end exactly where that one begins (redoing a middle+// clip with both of its cuts kept invisible).+export async function extractFirstFrame(video: string): Promise<string> {+ const out = video.replace(/\.\w+$/, "") + "-firstframe.jpg";+ try {+ await run(FFMPEG, ["-y", "-i", video, "-frames:v", "1", "-q:v", "2", out]);+ } catch (err) {+ const reason = (err as NodeJS.ErrnoException).code === "ENOENT" ? `ffmpeg is not installed (${FFMPEG_HINT})` : String(err);+ throw new Error(`last_frame needs ffmpeg to grab that clip's first frame: ${reason}`);+ }+ return out;+}++// Saves the frame at a chosen second of a clip - where the speech ends, say - so the next clip can start from there+// instead of from dead time at the end. flow_assemble's `trims` then cuts the earlier clip at the same second.+export async function extractFrameAt(video: string, seconds: number): Promise<string> {+ const out = `${video.replace(/\.\w+$/, "")}-frame-${seconds.toFixed(2)}s.jpg`;+ try {+ await run(FFMPEG, ["-y", "-ss", seconds.toFixed(3), "-i", video, "-frames:v", "1", "-q:v", "2", out]);+ } catch (err) {+ const reason = (err as NodeJS.ErrnoException).code === "ENOENT" ? `ffmpeg is not installed (${FFMPEG_HINT})` : String(err);+ throw new Error(`first_frame_at needs ffmpeg to grab that frame: ${reason}`);+ }+ return out;+}diff --git a/src/core.ts b/src/core.tsindex 95d6993..107b252 100644--- a/src/core.ts+++ b/src/core.ts@@ -2,13 +2,15 @@ import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";import { homedir } from "node:os";import { dirname, isAbsolute, join, relative, resolve } from "node:path";import { z } from "zod";-import { assemble, localVoices, speakLocally, voiceTrack } from "./assemble.js";+import { assemble, voiceTrack } from "./assemble.js";import { GEMINI_VOICES, geminiKey, saveGeminiKey, speakWithGemini } from "./gemini.js";-import { extractLastFrame } from "./chain.js";+import { KOKORO_DEFAULT_VOICE, KOKORO_MB, KOKORO_VOICES, kokoroReady, speakWithKokoro } from "./kokoro.js";+import { extractFirstFrame, extractFrameAt, extractLastFrame } from "./chain.js";import { burnCaptions, captionedName, captionSetup, previewCaptions, transcribe } from "./captions.js";-import { characterLook, createCharacter, downloadAsset, trashAsset, editCharacter, getFlowState, listAssets, listCharacters, rememberCharacter, runAgentBatch, runContinue, runEdit, runGeneration } from "./flow.js";+import { presenter } from "./presenter.js";+import { characterLook, createCharacter, createProject, downloadAsset, trashAsset, editCharacter, getFlowState, listAssets, forgetCharacter, 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";+import { BIN, COMPUTER, moveToBin } from "./platform.js";import { TECHNIQUES, techniqueById } from "./techniques.js";export const OUTPUT_ROOT = process.env.FLOW_MCP_OUTPUT ?? join(homedir(), "flow-mcp-out");@@ -28,8 +30,19 @@ const sceneSchema = z.object({resolution: z.enum(["360p", "720p"]).optional().describe("Video resolution. Omni models only."),max_credits: z.number().int().min(0).default(25).describe("Safety cap: the scene is skipped (nothing spent) if Flow quotes more credits than this."),variants: z.number().int().min(1).max(4).optional().describe("Outputs per prompt (each one spends credits). Default 1."),- first_frame: z.string().optional().describe("First frame: absolute image path, or 'asset:<title>' for an image already in the Flow project."),- last_frame: z.string().optional().describe("Last frame: absolute image path, or 'asset:<title>'."),+ first_frame: z+ .string()+ .optional()+ .describe("First frame: absolute image path, 'asset:<title>' for an image already in the Flow project, or the absolute path of a finished clip (.mp4) to start exactly on its last frame - chain_previous across separate calls."),+ first_frame_at: z+ .number()+ .min(0)+ .optional()+ .describe("When first_frame is a clip: start from the frame at this second instead of its last frame, e.g. right where the speech ends, so dead time at the end of a take is skipped. Cut that clip at the same second in flow_assemble's `trims` and the join stays invisible."),+ last_frame: z+ .string()+ .optional()+ .describe("Last frame: absolute image path, 'asset:<title>', or the absolute path of a finished clip (.mp4) to end exactly where that clip begins. With first_frame set to the clip before, this redoes a middle clip and keeps both cuts invisible."),reference_images: z.array(z.string()).max(3)@@ -40,6 +53,15 @@ const sceneSchema = z.object({download_quality: z.enum(["original", "upscaled"]).optional().describe("'upscaled' fetches 1080p video / 2K image (free, slower). Default original."),retries: z.number().int().min(0).max(3).default(1).describe("Automatic retries when Flow itself reports the generation failed."),technique: z.string().optional().describe("Id from flow_techniques (e.g. 'orbit-360'); its exact phrase is appended to the prompt. One per scene."),+ on_screen_text: z+ .boolean()+ .optional()+ .describe("Video only: true when words SHOULD appear in the picture (a sign, a title card). By default every video prompt forbids subtitles and on-screen text, because Omni otherwise burns in its own garbled captions."),+ outfit: z+ .string()+ .max(300)+ .optional()+ .describe("What a referenced character wears in this scene when it differs from their saved look, e.g. 'a plain cream crewneck sweatshirt'. The character lock then keeps face, hair and build but takes the clothes from here."),reference_previous: z.boolean().optional()@@ -84,6 +106,11 @@ const captionFields = {.optional().describe("Lowercase only: names to keep capitalised even where they start a sentence (e.g. [\"Juno\"]). Names in the middle of a sentence are found by themselves."),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."),+ words: z+ .array(z.object({ text: z.string().min(1), start: z.number().min(0), end: z.number().min(0) }))+ .max(5000)+ .optional()+ .describe("Word timings to use instead of hearing the whole video, e.g. from flow_transcribe on each clip of a joined film, shifted by where each clip starts in it. Use it when the film's own sound (music, a train, crowd) throws the timing off. text still corrects the words on top."),language: z.string().default("auto")@@ -115,6 +142,9 @@ export const shapes = {clips: z.array(z.string()).optional().describe("Absolute clip paths in play order. Default: every scene-NN.mp4 in the project folder (first variant of each)."),music: z.string().optional().describe("Absolute path to a music file; looped and trimmed to the film length."),music_volume: z.number().min(0).max(1).default(0.25),+ end_hold: z.object({ seconds: z.number().min(0).max(10), fade: z.number().min(0).max(10).optional() }).optional().describe("Hold the last frame this many seconds at the end, fading to black over its last `fade` seconds."),+ music_curve: z.array(z.object({ at: z.number().min(0), volume: z.number().min(0).max(2) })).optional().describe("Music level over the film on top of music_volume: {at: seconds, volume}, straight lines between points. Fade in, drop for a quiet moment, rise for the ending."),+ duck_music: z.boolean().optional().describe("Pull the music down automatically while the voiceover speaks, and let it back up in the gaps."),clip_volume: z.number().min(0)@@ -139,6 +169,71 @@ 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."),+ trims: z+ .array(+ z+ .object({+ from: z.number().min(0).optional(),+ to: z.number().min(0).optional(),+ volume: z.number().min(0).max(2).optional().describe("This clip's own sound level, 1 = as made. Lower a take whose background noise is louder than the clip before it, so the room does not jump at the cut."),+ fade_in: z.number().min(0).max(2).optional().describe("Seconds to fade this clip's sound in (trimmed edges always get 0.015 s so a cut never clicks)."),+ fade_out: z.number().min(0).max(2).optional().describe("Seconds to fade this clip's sound out."),+ soften_in: z.number().min(0).max(3).optional().describe("For a clip that continues the one before from its last frame: if it starts noticeably sharper than that clip ends (a visible 'skip' at the join), it opens equally soft and sharpens over this many seconds (1 is good). Measured automatically; does nothing when the two already match."),+ saturation: z.number().min(0.5).max(2).optional().describe("Scales this clip's colour (1 = as is). For a clip animated from the last frame of the one before, which can come back paler, so the join shows: measure both sides and match."),+ crop: z+ .object({+ x: z.number().min(0).max(1).optional().describe("Left edge, as a fraction of the width. Default: centred."),+ y: z.number().min(0).max(1).optional().describe("Top edge, as a fraction of the height. Default: centred."),+ w: z.number().min(0.1).max(1).describe("Width kept, as a fraction (0.8 = a 1.25x punch-in)."),+ h: z.number().min(0.1).max(1).optional().describe("Height kept; defaults to w, which keeps the frame's shape."),+ })+ .optional()+ .describe("Punch in on part of this clip, e.g. {x: 0, y: 0, w: 0.78} drops the bottom and right edges to hide something the model put in a corner."),+ })+ .nullable(),+ )+ .optional()+ .describe("One entry per clip, in play order: the seconds of that clip to keep, e.g. [{from: 0.6}, null, {to: 8.4}] cuts a dead start off clip 1 and an awkward pause off the end of clip 3 (null keeps a clip whole). The same clip may be listed twice with two windows to cut a repeated or fluffed line out of its middle. Use flow_transcribe's word times to find the cut points, and never cut inside a stray sound at the start of a take."),+ end_card: z+ .object({+ text: z.string().min(1).max(120).describe("The words, e.g. 'Link in bio' or 'Desk lamp · link below'. A line break starts a new line."),+ seconds: z.number().min(1).max(10).optional().describe("How long it shows. Default 2.5."),+ })+ .optional()+ .describe("A closing card: big centred words over the film's own last frame, blurred and darkened. Free, made on this computer."),+ inserts: z+ .array(+ z.object({+ clip: z.string().min(1).describe("Absolute path of the cutaway clip, e.g. a product close-up."),+ over: z.number().int().min(1).describe("Which clip it covers, counting from 1 in play order."),+ at: z.number().min(0).describe("Where it starts, in seconds into that clip's kept part (after its trim)."),+ seconds: z.number().min(0.2).optional().describe("How long it shows. Default: as long as the cutaway lasts, or to the end of the covered clip."),+ from: z.number().min(0).optional().describe("Start inside the cutaway clip. Default 0."),+ volume: z.number().min(0).max(1).optional().describe("The cutaway's own sound under the covered clip's sound. Default 0.3."),+ crop: z+ .object({ x: z.number().min(0).max(1).optional(), y: z.number().min(0).max(1).optional(), w: z.number().min(0.1).max(1), h: z.number().min(0.1).max(1).optional() })+ .optional()+ .describe("Crop the cutaway like a clip's `trims` crop (fractions), e.g. to take a vertical picture out of a 16:9 export."),+ }),+ )+ .optional()+ .describe("B-roll cutaways: show another clip's picture over part of a clip while that clip's own sound keeps playing - the person keeps talking over the product shot and the picture cuts back to them mid-take, in sync and at the same loudness. Better than voice_lines when the line comes from one of the film's own clips."),+ size: z+ .string()+ .regex(/^\d{2,4}x\d{2,4}$/)+ .optional()+ .describe("Film size as WIDTHxHEIGHT, e.g. '1080x1920' for a phone-ready vertical master. Default: the biggest clip, after any crop."),+ loudness: z+ .number()+ .min(-30)+ .max(-9)+ .optional()+ .describe("Level the finished film's sound to this loudness in LUFS. Flow's takes come out near -24, which is quiet on a phone; social video sits around -14."),+ remove_watermark: z+ .boolean()+ .optional()+ .describe("Paint out the sparkle mark Google's video models put in the bottom-right corner, found automatically and filled from the pixels around it (no crop). The invisible SynthID mark stays, and platforms still expect an AI-content label."),+ watermark_margin: z.number().min(0).max(40).optional().describe("With remove_watermark: grow the mask by this many pixels and make it a diamond. Use about 10 after a long Extend chain, where the mark has been redrawn thicker. Look at the corner afterwards."),},transcribe: {video: z.string().min(1).describe("Absolute path of a video or audio file on this computer."),@@ -146,6 +241,44 @@ export const shapes = {words: z.boolean().default(true).describe("Include every word with its start and end time in seconds."),},caption_preview: captionFields,+ presenter: {+ project: z.string().min(1).describe("Films folder to save into."),+ presenter: z.string().min(1).describe("Absolute path of the talking recording (an avatar video, say). Its sound plays throughout."),+ segments: z+ .array(+ z.object({+ from: z.number().min(0).describe("Start in the recording, in seconds."),+ to: z.number().min(0).describe("End in the recording, in seconds."),+ layout: z.enum(["full", "corner"]).describe("full: the presenter fills the frame. corner: a circle in the corner over `background`."),+ zoom: z+ .object({ from: z.number().min(1).max(3).optional(), to: z.number().min(1).max(3).optional(), x: z.number().min(0).max(1).optional(), y: z.number().min(0).max(1).optional() })+ .optional()+ .describe("Full layout only. A slow move from `from` to `to`, where 1 is the whole frame; x and y are the point to zoom toward, as fractions of the frame (default 0.5, 0.45)."),+ background: z+ .object({+ clip: z.string().min(1),+ from: z.number().min(0).optional(),+ retime: z.array(z.object({ from: z.number().min(0), to: z.number().min(0), speed: z.number().min(0.1).max(8) })).optional().describe("Parts of the clip to play faster or slower, so its action lands on the presenter's words. Times are in the original clip; `from` above is measured after this."),+ })+ .optional()+ .describe("Corner layout only: the clip behind the presenter, and where in it to start."),+ shrink: z.number().min(0.1).max(3).optional().describe("Corner layout only: animate from full frame into the circle over this many seconds at the start of the stretch."),+ }),+ )+ .min(1)+ .describe("The film in order. Each stretch is cut in as listed."),+ corner: z+ .object({+ position: z.enum(["bottom-right", "bottom-left", "top-right", "top-left"]).optional(),+ size: z.number().min(0.15).max(0.7).optional().describe("Circle diameter as a fraction of the frame's height. Default 0.36: readable on a phone."),+ face: z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1), w: z.number().min(0.1).max(1) }).optional().describe("The square of the recording to show in the circle: centre x, centre y, width, as fractions of the recording."),+ margin: z.number().min(0).max(0.2).optional(),+ ring_color: z.string().optional(),+ })+ .optional(),+ size: z.string().regex(/^\d{2,4}x\d{2,4}$/).optional().describe("Film size. Default 1920x1080."),+ output_name: z.string().optional(),+ },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'."),@@ -177,14 +310,19 @@ export const shapes = {narrate: {project: z.string().min(1).describe("Folder for the narration audio."),engine: z- .enum(["gemini", "mac"])- .default("gemini")+ .enum(["kokoro", "gemini"])+ .default("kokoro").describe(- "'gemini' uses Google AI Studio's text-to-speech - the same voices Flow has, free on the AI Studio tier, no length limit, needs a key in ~/.flow-mcp/gemini-key. 'mac' uses a voice installed on this computer (macOS voices on a Mac, the built-in speech voices on Windows): free, instant, no key.",+ "'kokoro' (the default) is Kokoro, a free voice that runs on this computer: no key, no quota, any length; the first take downloads its model once (326 MB). 'gemini' uses Google AI Studio's text-to-speech - the same voices Flow has, free on the AI Studio tier but with a daily limit, needs a key in ~/.flow-mcp/gemini-key; when that limit is used up the take is recorded with Kokoro instead and the result says so.",),- text: z.string().min(1).max(400).describe("The line to speak. About 20 words fits 8 s, 30 words fits 12 s; anything longer needs a longer take."),- voice: z.string().min(1).default("Charon").describe("Voice name from flow_voices, e.g. Charon (informative), Aoede (breezy), Gacrux (mature) for Google; Zoe or Samantha for macOS."),- style: z.string().max(200).optional().describe("Delivery note for the 'gemini' engine, e.g. 'slowly and warmly, like a documentary narrator'."),+ text: z.string().min(1).max(3000).describe("The line to speak. About 2.5 words per second: 25 words fit 10 s, 75 words fit 30 s. Record a whole narration in one take."),+ voice: z+ .string()+ .min(1)+ .optional()+ .describe("Voice name from flow_voices for the chosen engine. Defaults: am_michael for Kokoro (try af_heart, af_bella, bf_emma), Charon for Google (Aoede, Gacrux...)."),+ speed: z.number().min(0.5).max(2).optional().describe("Kokoro only: speaking speed, 1 = normal. 0.9 is a calmer narrator pace."),+ style: z.string().max(200).optional().describe("Delivery note for the 'gemini' engine, e.g. 'slowly and warmly'. Keep it to a few words: long notes make the model ramble."),},edit: {project: z.string().min(1).describe("Local folder for the edited clip."),@@ -244,6 +382,9 @@ export const shapes = {"The character's whole description AFTER the change, e.g. the old one with 'navy coat' swapped for 'red coat'. Scenes quote it word for word to hold the design, so a stale colour in it fights the new portrait. Without it, the change is added to the end of the old description.",),},+ new_project: {+ title: z.string().max(80).optional().describe("Name for the new project, e.g. 'Desk lamp UGC ad'. Default: Flow's own date-and-time name."),+ },character: {name: z.string().min(1).max(60).describe("Character name; scenes then reference it as 'asset:<name>' in reference_images."),describe: z@@ -257,6 +398,11 @@ export const shapes = {.optional().describe("Existing picture instead of `describe`: absolute path, or 'asset:<title>' of an image already in the Flow project."),aspect_ratio: z.enum(["3:4", "1:1", "9:16", "16:9", "4:3"]).optional().describe("Frame for the drawn portrait when using `describe`. Default 3:4."),+ look: z+ .string()+ .max(1200)+ .optional()+ .describe("With `image`: the person in the picture in words (face, hair, clothes). Every scene's character lock quotes it word for word, so describe only what the picture shows. Without it, an older description saved under the same name is dropped."),personality: z.string().max(500).optional().describe("How the character acts; Flow uses it when crafting scenes."),voice: z.string().optional().describe("Flow voice name, e.g. 'Charon' (male, informative) or 'Aoede' (female, breezy)."),},@@ -293,6 +439,7 @@ export interface Core {techniques(a: Args<"techniques">): Promise<unknown>;voices(): Promise<unknown>;narrate(a: Args<"narrate">): Promise<unknown>;+ new_project(a: Args<"new_project">): Promise<unknown>;character(a: Args<"character">): Promise<unknown>;characters(): Promise<unknown>;character_edit(a: Args<"character_edit">): Promise<unknown>;@@ -306,6 +453,7 @@ export interface Core {transcribe(a: Args<"transcribe">): Promise<unknown>;caption_preview(a: Args<"caption_preview">): Promise<unknown>;captions(a: Args<"captions">): Promise<unknown>;+ presenter(a: Args<"presenter">): Promise<unknown>;caption_setup(): Promise<unknown>;}@@ -338,6 +486,15 @@ export class LocalCore implements Core {if (!still) throw new Error(`reference_previous: the previous scene (${reference_from}) produced no image.`);job.params.reference_images = [still, ...(job.params.reference_images ?? [])].slice(0, 3);}+ // A clip given as the first frame means "carry on from where it ends", so a clip made in an earlier call can be+ // continued after the user has looked at it.+ const ff = job.params.first_frame;+ if (ff && !ff.startsWith("asset:") && /\.(mp4|webm|mov)$/i.test(ff))+ job.params.first_frame = job.params.first_frame_at !== undefined ? await extractFrameAt(ff, job.params.first_frame_at) : await extractLastFrame(ff);+ // And a clip given as the last frame means "end where it begins": with both, a middle clip can be redone without+ // touching the clips on either side.+ const lf = job.params.last_frame;+ if (lf && !lf.startsWith("asset:") && /\.(mp4|webm|mov)$/i.test(lf)) job.params.last_frame = await extractFirstFrame(lf);if (chain_from) {const clip = this.queue.get(chain_from)?.files.find((f) => /\.(mp4|webm|mov)$/i.test(f));if (!clip) throw new Error(`chain_previous: the previous scene (${chain_from}) produced no video, so this scene was skipped.`);@@ -370,7 +527,7 @@ export class LocalCore implements Core {const queued = this.queue.list().filter((j) => j.params.output_dir === output_dir).map((j) => Number(j.params.file_stem.match(/\d+/)?.[0] ?? 0));const offset = Math.max(0, ...onDisk, ...queued);const jobs: Job[] = [];- for (const [i, { chain_previous, reference_previous, technique, ...scene }] of scenes.entries()) {+ for (const [i, { chain_previous, reference_previous, technique, outfit, on_screen_text, ...scene }] of scenes.entries()) {const phrase = technique ? techniqueById(technique)!.phrase : "";// A referenced character must come out identical, not merely similar, so the scene says so explicitly. The// wording stays medium-neutral: the same lock has to serve a flat cartoon character and a photoreal avatar.@@ -378,10 +535,20 @@ export class LocalCore implements Core {.filter((r) => r.startsWith("asset:")).map((r) => r.slice(6).trim()).filter((n) => characterLook(n) !== undefined || /^[\w .'-]{1,60}$/.test(n));+ // With an outfit the lock still pins face, hair and build, but the clothes come from the scene: otherwise the+ // saved look (Skye's denim shirt) fights a costume the prompt asks for.const lock = cast.length- ? ` CHARACTER LOCK — ${cast.join(" and ")} must match the reference image exactly, as if copying it: same head shape and size, same face, same eyes, same hair, same skin, same build and proportions, same clothing items in the same colours, same hands, and the same rendering style and level of realism as the reference. Never redesign, restyle, re-proportion, re-age or re-colour them, and never swap an item for a similar one.${cast+ ? ` CHARACTER LOCK — ${cast.join(" and ")} must match the reference image exactly, as if copying it: same head shape and size, same face, same eyes, same hair, same skin, same build and proportions,${outfit ? "" : " same clothing items in the same colours,"} same hands, and the same rendering style and level of realism as the reference. Never redesign, ${outfit ? "" : "restyle, "}re-proportion, re-age or re-colour them${outfit ? "" : ", and never swap an item for a similar one"}.${cast.map((n) => (characterLook(n) ? ` ${n} is exactly: ${characterLook(n)}.` : ""))- .join("")}`+ .join("")}${outfit ? ` WARDROBE IN THIS SCENE: ${outfit.trim().replace(/\.$/, "")}. This replaces any clothing in the reference image or the description above, and stays identical for the whole scene.` : ""}`+ : "";+ // Omni burns its own subtitles into talking clips now and then, garbled ("thyel", "voch"), even when the prompt+ // says "no captions" near the end (protein soda clip 1, 15 credits). Every video therefore opens AND closes on it,+ // unless the scene really wants words in the picture. Captions are added afterwards by flow_captions.+ const noText = scene.type !== "image" && !on_screen_text;+ const textFirst = noText ? "NO SUBTITLES, NO CAPTIONS, NO TEXT OF ANY KIND ON SCREEN. " : "";+ const textLast = noText+ ? " NO TEXT ON SCREEN: never add subtitles, captions, titles, speech transcripts, words or letters anywhere in the picture, at any moment; any speech is heard only, never written.": "";const inherit = reference_previous? " Match the previous image exactly for the subject's appearance, colour palette, lighting and rendering style; this is the same scene a moment later."@@ -389,7 +556,7 @@ export class LocalCore implements Core {jobs.push(this.queue.add({...scene,- prompt: `${scene.prompt.trim().replace(/\.?$/, ".")}${phrase ? ` ${phrase}` : ""}${lock}${inherit}`,+ prompt: `${textFirst}${scene.prompt.trim().replace(/\.?$/, ".")}${phrase ? ` ${phrase}` : ""}${lock}${inherit}${textLast}`,chain_from: chain_previous ? jobs[i - 1].id : undefined,reference_from: reference_previous ? jobs[i - 1].id : undefined,output_dir,@@ -484,34 +651,11 @@ export class LocalCore implements Core {return { ...film, voice: track };}- // Captions never touch Flow or its queue: whisper.cpp hears the words, a headless Chrome of its own draws them.- async transcribe({ video, language, words }: Args<"transcribe">) {- const t = await transcribe(video, language);- return {- text: t.text,- word_count: t.words.length,- language: t.language,- model: t.model,- ...(words ? { words: t.words.map((w) => ({ text: w.text, start: Number(w.start.toFixed(2)), end: Number(w.end.toFixed(2)) })) } : {}),- };- }-- 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();- }+ transcribe = transcribeHere;+ caption_preview = captionPreviewHere;+ captions = captionsHere;+ presenter = presenterHere;+ caption_setup = captionSetupHere;// Everything already downloaded, newest project first, so the panel can show past work after a restart.async outputs() {@@ -621,11 +765,22 @@ export class LocalCore implements Core {return trashAsset(name);}+ async new_project({ title }: Args<"new_project">) {+ if (this.queue.busy) throw new Error(BUSY);+ const made = await createProject(title);+ return { ...made, note: "The Flow window now has this empty project open; every generation goes into it. Characters belong to a project, so make them again here." };+ }+async character(a: Args<"character">) {if (this.queue.busy) throw new Error(BUSY);if (!a.image && !a.describe) throw new Error("Pass either `describe` (Flow draws the portrait) or `image`.");const made = await createCharacter(a);+ // Every scene quotes the saved description in its character lock, so a character made from a picture must not+ // inherit an older description saved under the same name: it described someone else (a "Maya" with a ponytail and+ // a mustard sweater, when the new picture showed loose hair and a grey tee).if (a.describe) rememberCharacter(a.name, a.describe);+ else if (a.look) rememberCharacter(a.name, a.look);+ else forgetCharacter(a.name);return { ...made, use_as: `asset:${a.name}` };}@@ -649,21 +804,77 @@ export class LocalCore implements Core {return saveGeminiKey(key);}- async voices() {- // The panel words itself from these, so a PC never reads "this Mac".- const place = { computer: COMPUTER, bin: BIN, local_engine: IS_MAC ? "macOS voice" : IS_WIN ? "Windows voice" : "System voice", platform: process.platform };- return { gemini: GEMINI_VOICES, gemini_ready: Boolean(geminiKey()), mac: await localVoices(), place };- }-- async narrate({ project, text, voice, engine, style }: Args<"narrate">) {- const output_dir = projectDir(project);- mkdirSync(output_dir, { recursive: true });- const target = join(output_dir, `${this.nextStem(output_dir, "narration")}.m4a`);- const spoken = engine === "mac" ? await speakLocally(text.trim(), voice, target) : await speakWithGemini(text.trim(), voice, target, style);- return { output_dir, credits: 0, engine, voice, ...spoken };- }+ voices = voicesHere;+ narrate = narrateHere;async techniques({ category }: Args<"techniques">) {return TECHNIQUES.filter((t) => !category || t.category === category);}}++// Narration never touches Chrome, so it runs in whichever process gets the call. A client then never depends on the+// owner's code: Claude Desktop's own flow-mcp process can be a release behind until the user restarts the app.+export async function voicesHere() {+ // The panel words itself from these, so a PC never reads "this Mac".+ const place = { computer: COMPUTER, bin: BIN, platform: process.platform };+ return { kokoro: KOKORO_VOICES, kokoro_ready: kokoroReady(), kokoro_mb: KOKORO_MB, gemini: GEMINI_VOICES, gemini_ready: Boolean(geminiKey()), place };+}++export async function narrateHere({ project, text, voice, engine, speed, style }: Args<"narrate">) {+ const output_dir = projectDir(project);+ mkdirSync(output_dir, { recursive: true });+ const taken = readdirSync(output_dir).map((f) => Number(f.match(/^narration-(\d+)/)?.[1] ?? 0));+ const target = join(output_dir, `narration-${String(Math.max(0, ...taken) + 1).padStart(2, "0")}.m4a`);+ const line = text.trim();+ if (engine === "kokoro") {+ const v = voice ?? KOKORO_DEFAULT_VOICE;+ return { output_dir, credits: 0, engine, voice: v, ...(await speakWithKokoro(line, v, target, speed)) };+ }+ const v = voice ?? "Charon";+ try {+ return { output_dir, credits: 0, engine, voice: v, ...(await speakWithGemini(line, v, target, style)) };+ } catch (err) {+ // The free AI Studio tier has a daily limit. Running out of it should not stop the film: Kokoro records the line+ // now, and the note says how to get the Google voice back once the limit resets.+ if (!/\b429\b|quota|RESOURCE_EXHAUSTED|rate limit/i.test(String((err as Error).message))) throw err;+ const spoken = await speakWithKokoro(line, KOKORO_DEFAULT_VOICE, target);+ return {+ output_dir, credits: 0, engine: "kokoro", voice: KOKORO_DEFAULT_VOICE, fell_back_from: "gemini", ...spoken,+ note: `Google AI Studio's daily limit is used up, so this take was recorded with Kokoro (${KOKORO_DEFAULT_VOICE}) instead. Record it again with ${v} once the limit resets.`,+ };+ }+}++// Captions never touch Flow or its queue: whisper.cpp hears the words, a headless Chrome of its own draws them. So,+// like narration, they run in whichever process gets the call and never wait for the owner to be restarted.+export async function transcribeHere({ video, language, words }: Args<"transcribe">) {+ const t = await transcribe(video, language);+ return {+ text: t.text,+ word_count: t.words.length,+ language: t.language,+ model: t.model,+ ...(words ? { words: t.words.map((w) => ({ text: w.text, start: Number(w.start.toFixed(2)), end: Number(w.end.toFixed(2)) })) } : {}),+ };+}++export async function presenterHere({ project, ...a }: Args<"presenter">) {+ return presenter({ ...a, dir: projectDir(project) });+}++export async function captionPreviewHere(a: Args<"caption_preview">) {+ return previewCaptions(a.video, a);+}++export async function captionsHere({ 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));+}++export async function captionSetupHere() {+ return captionSetup();+}diff --git a/src/flow.ts b/src/flow.tsindex 1a8d4ac..4e8d132 100644--- a/src/flow.ts+++ b/src/flow.ts@@ -161,6 +161,18 @@ export async function newErrorTiles(page: Page, known: Iterable<string>): Promis}, [[...known], TILE_ID_JS] as [string[], string]);}+// Flow says WHY on the tile (".error-message-text"): a busy server, or a policy refusal such as "This prompt might+// violate our policies about generating prominent people". The second never succeeds on retry, so it must not be+// retried and the user must see Flow's own words, not a generic "failed".+async function errorReason(page: Page): Promise<string> {+ return page+ .locator("flow-grid-tile-container flow-error-tile")+ .first()+ .evaluate((el) => ((el.querySelector(".error-message-text") as HTMLElement | null)?.innerText || (el as HTMLElement).innerText).replace(/\s+/g, " ").trim())+ .catch(() => "");+}+const POLICY = /polic|violat|prominent|safety|not allowed|guideline/i;+// Flow's Retry replaces the failed tile with a fresh render of the same prompt and settings, free of charge.// Tiles produced by Agent mode only offer Delete, so the button may not be there at all.async function retryErrorTile(page: Page, tile: Locator): Promise<boolean> {@@ -285,6 +297,13 @@ async function waitForNewMedia(page: Page, before: string[], count: number, timeconst errors = progress.length ? 0 : await newErrorTiles(page, before);if (!errors) continue;failures += errors;+ const reason = await errorReason(page);+ if (POLICY.test(reason)) {+ const hint = /prominent|public figure|celebrit/i.test(reason)+ ? " Flow thinks a face in this scene looks like a real, well-known person, usually one from an uploaded photo or a character made from one. Retrying will not change that: use a character drawn from a description (flow_character with `describe`) instead."+ : " Retrying the same prompt will not change that.";+ throw new Error(`Flow refused this generation on policy grounds: "${reason}" Nothing was charged.${hint}`);+ }if (retriesLeft > 0) {retriesLeft--;if (job) job.progress = "Flow failed, retrying";@@ -292,7 +311,7 @@ async function waitForNewMedia(page: Page, before: string[], count: number, timeif (retried) continue;}if (fresh.length) return fresh;- throw new Error(`Flow failed this generation ${failures} time(s) ("Sorry, this image/video failed to generate"). Nothing was charged. Try again later or reword the prompt.`);+ throw new Error(`Flow failed this generation ${failures} time(s) ("${reason || "Sorry, this image/video failed to generate"}"). Nothing was charged. Try again later or reword the prompt.`);}throw new Error(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for Flow to finish.`);}@@ -309,6 +328,9 @@ async function openSettings(page: Page): Promise<void> {async function pickRadio(page: Page, name: string | RegExp): Promise<void> {const radio = page.getByRole("radio", { name, exact: typeof name === "string" }).first();+ // The Escape that closes the model menu when no model change is needed can close the whole settings popover with+ // it (a brand-new project already on the newest Nano Banana: "Flow has no "x2" option"), so reopen it and look again.+ if (!(await radio.isVisible().catch(() => false))) await openSettings(page).catch(() => undefined);if (!(await radio.isVisible().catch(() => false))) {throw new Error(`Flow has no "${name}" option for the current mode/model.`);}@@ -359,6 +381,19 @@ async function pickModel(page: Page, model: string): Promise<void> {}// Applies the scene settings and returns the credit cost Flow quotes for them.+// One Escape does not always shut the settings popover (2026-10-30: it stayed open after a run and its credit label+// swallowed the next click on the prompt box, so flow_character timed out). Check it is gone, and try again.+async function closeSettings(page: Page): Promise<void> {+ const popover = page.locator(".cdk-overlay-pane:has(.credit-cost-label)");+ for (let i = 0; i < 3; i++) {+ if (!(await popover.count())) return;+ await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur?.());+ await page.keyboard.press("Escape");+ await pause(page, 400);+ }+ if (await popover.count()) await page.getByRole("button", { name: "Settings trigger" }).click({ timeout: 5000 }).catch(() => undefined);+}+async function applySettings(page: Page, job: Job): Promise<number> {const s = job.params;const framesMode = Boolean(s.first_frame || s.last_frame);@@ -372,10 +407,10 @@ async function applySettings(page: Page, job: Job): Promise<number> {if (s.type === "video" && s.duration) await pickRadio(page, `${s.duration}s`);await pickRadio(page, `x${s.variants ?? 1}`);await pause(page, 600);- const costText = await page.getByRole("link", { name: /credits?$/ }).innerText();+ // The quote is "<N> credits". Low balances add an "Add AI credits" banner link that the old /credits?$/ also matched.+ const costText = await page.getByRole("link", { name: /^\d[\d,]*\s+credits?$/ }).first().innerText();const cost = Number(costText.match(/\d+/)?.[0] ?? NaN);- await page.keyboard.press("Escape");- await pause(page, 400);+ await closeSettings(page);if (Number.isNaN(cost)) throw new Error(`Could not read the credit cost from Flow ("${costText}").`);return cost;}@@ -1138,6 +1173,12 @@ const loadLooks = (): Record<string, string> => {}};export const characterLook = (name: string): string | undefined => loadLooks()[name.toLowerCase()];+export function forgetCharacter(name: string): void {+ const all = loadLooks();+ if (!(name.toLowerCase() in all)) return;+ delete all[name.toLowerCase()];+ writeFileSync(LOOKS_FILE, JSON.stringify(all, null, 2));+}export function rememberCharacter(name: string, look: string): void {const all = { ...loadLooks(), [name.toLowerCase()]: look.trim() };mkdirSync(HOME_DIR, { recursive: true });@@ -1795,3 +1836,29 @@ export async function runAgentBatch(job: Job): Promise<string[]> {if (balance !== undefined && left !== undefined) job.credits = balance - left;return files;}++// A fresh Flow project, so a film can start from scratch without anyone clicking. Mapped live (2026-10-30): Flow's home+// page has one button "New project", which opens /project/<uuid>; on the project page the name is a text box whose+// accessible name is "Editable text" (it holds Flow's default name, e.g. "Oct 29 - 22:17").+export async function createProject(title?: string): Promise<{ id: string; url: string; title: string }> {+ const page = await getFlowPage();+ await page.goto(inEnglish("https://flow.google.com/"), { waitUntil: "domcontentloaded" });+ const button = page.getByRole("button", { name: /new project/i }).first();+ await button.waitFor({ state: "visible", timeout: 30_000 }).catch(() => {+ throw new Error("Flow's home page shows no \"New project\" button. Check the Flow window is signed in.");+ });+ await button.click();+ await page.waitForURL(/\/project\/[0-9a-f-]{36}/, { timeout: 30_000 }).catch(() => {+ throw new Error("Pressed \"New project\" but Flow did not open a project within 30 s.");+ });+ const id = page.url().match(/\/project\/([0-9a-f-]{36})/)![1];+ const name = page.getByRole("textbox", { name: "Editable text" }).first();+ await name.waitFor({ state: "visible", timeout: 15_000 }).catch(() => undefined);+ if (title?.trim()) {+ await name.fill(title.trim()).catch(() => undefined);+ await name.press("Enter").catch(() => undefined);+ await page.waitForTimeout(1200);+ }+ const shown = (await name.inputValue().catch(() => "")) || title || "";+ return { id, url: `https://flow.google.com/project/${id}`, title: shown };+}diff --git a/src/index.ts b/src/index.tsindex 3a149cb..e7058a0 100644--- a/src/index.ts+++ b/src/index.ts@@ -237,6 +237,17 @@ server.registerTool((args) => reply(patient("flow_character_edit", core.character_edit(args))),);+server.registerTool(+ "flow_new_project",+ {+ title: "Start a new Flow project",+ description: "Create a new, empty Google Flow project and open it in the Flow window, optionally with a name - for starting a film or ad from scratch. Free. Characters belong to a project, so make them again in the new one.",+ inputSchema: shapes.new_project,+ annotations: { openWorldHint: true },+ },+ (args) => reply(patient("flow_new_project", core.new_project(args))),+);+server.registerTool("flow_characters",{@@ -263,9 +274,9 @@ server.registerTool(server.registerTool("flow_narrate",{- title: "Record narration in a Flow voice",+ title: "Record narration",description:- "Record narration as an .m4a, free and instantly. `engine: \"gemini\"` uses Google AI Studio's text-to-speech (the same voices Flow has, needs a free key in ~/.flow-mcp/gemini-key, and takes a `style` note like 'warmly, like a documentary narrator'); `engine: \"mac\"` uses a voice installed on this computer (macOS, or Windows' built-in speech voices). Neither costs credits or caps the length. flow_assemble can lay the result over a film.",+ "Record narration as an .m4a, free. The default `engine: \"kokoro\"` is Kokoro, a voice that runs on this computer: no key, no daily limit, any length, 28 English voices (flow_voices lists them; default am_michael) and a `speed`. The first Kokoro take downloads its model once (326 MB, about a minute). `engine: \"gemini\"` uses Google AI Studio's text-to-speech (the same voices Flow has, a free key in ~/.flow-mcp/gemini-key, a daily limit, takes a short `style` note); if that limit is used up the line is recorded with Kokoro and the result says so. Neither costs credits. Record a whole narration in one take; flow_assemble can lay it over a film.",inputSchema: shapes.narrate,annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },},@@ -276,7 +287,7 @@ server.registerTool("flow_voices",{title: "List Flow voices",- description: "Narrator voices available for flow_narrate: Google AI Studio's (with whether a key is set up) and the English voices installed on this computer.",+ description: "Narrator voices available for flow_narrate: Kokoro's (free, on this computer, with whether its model is downloaded yet) and Google AI Studio's (with whether a key is set up).",inputSchema: shapes.voices,annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },},@@ -319,4 +330,16 @@ server.registerTool((args) => reply(patient("flow_captions", core.captions(args))),);+server.registerTool(+ "flow_presenter",+ {+ title: "Talking presenter over footage",+ description:+ "Build an explainer from one recording of a talking presenter (an avatar video, say): each stretch shows them full frame, with an optional slow zoom, or in a circle in a corner over another clip. Their sound plays throughout. Local and free. Add music, loudness and watermark removal afterwards with flow_assemble.",+ inputSchema: shapes.presenter,+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ },+ (args) => reply(patient("flow_presenter", core.presenter(args))),+);+await server.connect(new StdioServerTransport());diff --git a/src/kokoro-worker.ts b/src/kokoro-worker.tsnew file mode 100644index 0000000..e9dda03--- /dev/null+++ b/src/kokoro-worker.ts@@ -0,0 +1,81 @@+// Runs one Kokoro take in its own process, so the 300 MB model and Hugging Face's download code never live inside the+// panel or Claude's connector: a crash here ends this take only. Input is a JSON file (the line never goes on a command+// line); output is a 16-bit mono WAV at 24 kHz, and one line of JSON on stdout.+import { readFileSync, writeFileSync } from "node:fs";+import { env } from "@huggingface/transformers";+import { KokoroTTS, TextSplitterStream } from "kokoro-js";++interface Job {+ text: string;+ voice: string;+ speed: number;+ out: string;+ cache: string;+ model: string;+}++const job = JSON.parse(readFileSync(process.argv[2], "utf8")) as Job;+env.cacheDir = job.cache;++// Kokoro reads at most 510 phoneme tokens per pass and silently drops the rest, so a long narration is cut into+// sentences and packed into chunks well under that (roughly one token per character of English).+const CHUNK = 300;+function chunks(text: string): string[] {+ const splitter = new TextSplitterStream();+ splitter.push(text);+ splitter.close();+ const out: string[] = [];+ for (const sentence of splitter) {+ const pieces = sentence.length > CHUNK ? sentence.split(/(?<=[,;:])\s+/) : [sentence];+ for (const piece of pieces) {+ if (out.length && out[out.length - 1].length + piece.length + 1 <= CHUNK) out[out.length - 1] += " " + piece;+ else out.push(piece);+ }+ }+ return out;+}++// Every pass starts with about half a second of silence and ends with some more, so chunks joined as they come leave+// a gap of over a second (measured). Each is trimmed to its speech and joined with an ordinary sentence pause.+const RATE = 24000;+function trim(a: Float32Array): Float32Array {+ const loud = (x: number) => Math.abs(x) > 0.01;+ let start = a.findIndex(loud);+ if (start < 0) return a.subarray(0, 0);+ let end = a.length - 1;+ while (end > start && !loud(a[end])) end--;+ const margin = Math.round(RATE * 0.04);+ return a.subarray(Math.max(0, start - margin), Math.min(a.length, end + 1 + margin));+}++const tts = await KokoroTTS.from_pretrained(job.model, { dtype: "fp32", device: "cpu" });+const pause = new Float32Array(Math.round(RATE * 0.4));+const parts: Float32Array[] = [];+for (const [i, chunk] of chunks(job.text).entries()) {+ if (i) parts.push(pause);+ const audio = await tts.generate(chunk, { voice: job.voice as never, speed: job.speed });+ parts.push(trim(audio.audio as Float32Array));+}++const samples = parts.reduce((n, p) => n + p.length, 0);+const wav = Buffer.alloc(44 + samples * 2);+wav.write("RIFF", 0);+wav.writeUInt32LE(36 + samples * 2, 4);+wav.write("WAVEfmt ", 8);+wav.writeUInt32LE(16, 16);+wav.writeUInt16LE(1, 20);+wav.writeUInt16LE(1, 22);+wav.writeUInt32LE(RATE, 24);+wav.writeUInt32LE(RATE * 2, 28);+wav.writeUInt16LE(2, 32);+wav.writeUInt16LE(16, 34);+wav.write("data", 36);+wav.writeUInt32LE(samples * 2, 40);+let at = 44;+for (const part of parts)+ for (const s of part) {+ wav.writeInt16LE(Math.round(Math.max(-1, Math.min(1, s)) * 32767), at);+ at += 2;+ }+writeFileSync(job.out, wav);+console.log(JSON.stringify({ seconds: samples / RATE }));diff --git a/src/kokoro.ts b/src/kokoro.tsnew file mode 100644index 0000000..2a8285a--- /dev/null+++ b/src/kokoro.ts@@ -0,0 +1,74 @@+// Kokoro: a free voice that runs on this computer (Kokoro-82M, Apache 2.0, through kokoro-js). No key, no quota, no+// length limit, same on a Mac and a PC. The model (326 MB) downloads itself into ~/.flow-mcp/models/kokoro the first+// time a line is spoken; every take after that starts in well under a second.+import { execFile } from "node:child_process";+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";+import { HOME_DIR } from "./chrome.js";++const run = promisify(execFile);+const FFMPEG = process.env.FLOW_MCP_FFMPEG ?? "ffmpeg";+const FFPROBE = process.env.FLOW_MCP_FFPROBE ?? "ffprobe";+const MODEL = "onnx-community/Kokoro-82M-v1.0-ONNX";+const CACHE = join(HOME_DIR, "models", "kokoro");+const WORKER = join(dirname(fileURLToPath(import.meta.url)), "kokoro-worker.js");++export const KOKORO_MB = 326;+export const KOKORO_DEFAULT_VOICE = "am_michael";++// Kokoro's English voices, best first by the model card's own grades. The letter in the id is the accent+// (a American, b British) and the second the speaker (f female, m male).+const GRADED: [string, string, string][] = [+ ["af_heart", "Heart", "A"], ["af_bella", "Bella", "A-"], ["af_nicole", "Nicole", "B-"], ["bf_emma", "Emma", "B-"],+ ["am_michael", "Michael", "C+"], ["am_fenrir", "Fenrir", "C+"], ["am_puck", "Puck", "C+"], ["af_aoede", "Aoede", "C+"],+ ["af_kore", "Kore", "C+"], ["af_sarah", "Sarah", "C+"], ["bm_george", "George", "C"], ["bm_fable", "Fable", "C"],+ ["bf_isabella", "Isabella", "C"], ["af_alloy", "Alloy", "C"], ["af_nova", "Nova", "C"], ["af_sky", "Sky", "C-"],+ ["bm_lewis", "Lewis", "D+"], ["am_echo", "Echo", "D"], ["am_eric", "Eric", "D"], ["am_liam", "Liam", "D"],+ ["am_onyx", "Onyx", "D"], ["bm_daniel", "Daniel", "D"], ["bf_alice", "Alice", "D"], ["bf_lily", "Lily", "D"],+ ["af_jessica", "Jessica", "D"], ["af_river", "River", "D"], ["am_santa", "Santa", "D-"], ["am_adam", "Adam", "F+"],+];+export const KOKORO_VOICES = GRADED.map(([name, label, grade]) => ({+ name,+ label,+ description: `${name[0] === "b" ? "British" : "American"}, ${name[1] === "m" ? "male" : "female"} · grade ${grade}`,+}));++export const kokoroReady = () => existsSync(join(CACHE, MODEL, "onnx", "model.onnx"));++// One take at a time: two first-time takes at once would download the model twice into the same folder.+let queue: Promise<unknown> = Promise.resolve();++export function speakWithKokoro(text: string, voice: string, target: string, speed = 1): Promise<{ output: string; duration: number }> {+ if (!KOKORO_VOICES.some((v) => v.name === voice))+ throw new Error(`Kokoro has no voice "${voice}". Pick one of: ${KOKORO_VOICES.map((v) => v.name).join(", ")}.`);+ const take = queue.then(async () => {+ const stem = target.replace(/\.\w+$/, "");+ const jobFile = stem + ".kokoro.json";+ const raw = stem + ".kokoro.wav";+ const firstTime = !kokoroReady();+ mkdirSync(CACHE, { recursive: true });+ writeFileSync(jobFile, JSON.stringify({ text, voice, speed, out: raw, cache: CACHE, model: MODEL }), "utf8");+ try {+ await run(process.execPath, [WORKER, jobFile], { timeout: firstTime ? 20 * 60_000 : 5 * 60_000, maxBuffer: 16 * 1024 * 1024 }).catch(+ (err: Error & { stderr?: string }) => {+ const detail = String(err.stderr || err.message).trim().split("\n").filter(Boolean).at(-1) ?? "no detail";+ throw new Error(+ firstTime+ ? `Kokoro needs its voice model the first time (${KOKORO_MB} MB, downloaded once) and that failed: ${detail}. Check the internet connection and try again.`+ : `Kokoro could not record this line: ${detail}`,+ );+ },+ );+ await run(FFMPEG, ["-y", "-i", raw, "-af", "highpass=f=80,loudnorm=I=-16:TP=-1.5:LRA=11", "-ar", "48000", "-ac", "2", target]);+ } finally {+ rmSync(jobFile, { force: true });+ rmSync(raw, { force: true });+ }+ const { stdout } = await run(FFPROBE, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", target]);+ return { output: target, duration: Number(stdout.trim()) };+ });+ queue = take.catch(() => undefined);+ return take;+}diff --git a/src/playbook.ts b/src/playbook.tsindex fe149a2..f04bf25 100644--- a/src/playbook.ts+++ b/src/playbook.ts@@ -22,7 +22,31 @@ export const PLAYBOOK = {"Name the camera behaviour explicitly (static locked-off, slow push-in, orbit, crane up, handheld).","Repeat the full description of a recurring character or product in every scene; Flow has no memory between scenes.","Put spoken lines in quotes and say who speaks; keep a line short enough for the clip length.",+ "Put every spoken line INSIDE the second-by-second timeline, at the moment it is said, and spell out its order against the actions ('0.0-1.2 s: she says \"Watch this.\" with her hands still; 1.2-2.5 s: only after saying it, she taps the lamp'). A separate DIALOGUE block lets the model choose the order, and it did: she tapped the lamp first, then said \"Watch this.\"",+ "Decide how clips join before writing them: continue from the previous clip's last frame (one continuous take: she must move into each new position on screen) or a deliberate jump cut to a new setup. Say which to the user; an unexplained new position looks like a mistake.","For 9:16 social video set aspect_ratio on every scene.",+ "Give every clip ONE specific action with a beginning and an end (a switch clicked off, one leap, one decisive pull), with the character's face in frame. A continuous activity ('working a knot', 'wandering') makes the model loop aimless fidgeting for the whole clip.",+ "A sip through a CLEAR straw comes back with the straw empty: the model never moves liquid up it, and viewers notice. Give the drink an opaque straw (a matte paper or solid-coloured straw) so nothing has to be seen rising, or have the person drink from the rim. State it in the prompt AND the still, and look at the straw frame by frame before showing the clip.",+ "Never have a product turned end over end or upside down and back (a bottle, can, phone, tube). Halfway through the turn the model loses which end is which and the cap jumps to the other end: a KOVA bottle flipped for a leak test came back with its lid on the wrong side. Keep the product's orientation fixed ('the lid stays at the top in every frame') and show the claim another way.",+ "Characters for video should be DRAWN from a description (flow_character with `describe`). A character made from an uploaded photo of a real-looking person can make stills, but Flow may refuse every video with it as possibly a prominent real person.",+ "Never name an object you do not want in the picture, even to rule it out: \"she is never holding the phone\" put a second iPhone on a stand in the corner of a whole clip. Describe the camera instead (\"a fixed camera at her eye level, about 70 cm away\").",+ "UGC talking clips that must match each other: a phone propped on a stand or the counter, the same position and framing in every clip, the same still as reference. Omni does not keep a hand-held selfie consistent from clip to clip. Make the person lively with their body (leaning on the counter, a weight shift, a head tilt, a shrug), not with camera sway.",+ "UGC product ads: the person only talks and holds the product still near the lens (hands are where video models break). Show the proof or demo as its own short hands-free product shot in the same place (e.g. the bottle standing upside down on its lid on the laptop), cut in between two talking clips; the cutaway hides the join, as in real UGC.",+ "Before showing a clip, check EVERY moment of its motion (8 frames a second through each move), not just the first and last frame. Morphs happen mid-move.",+ "A spoken line that refers to something (\"Downhill!\", \"Look at the sea\", \"It's falling\") must have a matching PICTURE instruction at the same second that makes it visible, written from the camera's side (\"behind them the street climbs steeply, so we see they are rolling down a steep slope\"). The model never infers the scene from the dialogue: Lia shouted \"Downhill!\" on a flat street.",+ "Never ask for a turn ('take the left', 'turns into the side street') in a shot where the camera travels ahead of or beside the subject: Omni shows it as the subject sliding sideways in frame, which reads as nonsense. Keep the subject going straight and change the PLACE around them instead, or cut. Describe that change as something they ride THROUGH (the walls beside them end, light floods in, the road widens onto the seafront): \"at 7 s the alley opens out with the bay behind them\" came back as a hard jump cut from the alley to the seafront, and so did \"from 6 s they ride out as the walls end and sunlight floods over them, into a small square\" (cut at 7.9 s). A new place given a TIME mid-clip comes back as a cut. What worked: naming the new place from the clip's first second with no time (\"the lane levels out into a small morning market\"), which grew in around them with no cut. Or trim the take at the cut.",+ ],+ story_pitches: [+ "The film has to hook someone who is scrolling. Open in the middle of danger, a chase or an impossible image, never on a character standing still, waking up or looking around. The first two seconds decide whether anyone watches the rest.",+ "Pitch three ideas in different genres - a chase, a heist, an escape, a stunt gone wrong, a race against a clock - never three versions of one idea.",+ "Stakes the viewer gets instantly with no explanation: something is chasing them, a clock is running out, they are about to fall, something precious is about to break.",+ "Three clips, three escalations: each clip ends on a cliffhanger that the next one resolves and tops, and the last one lands a twist, a reversal or a punchline nobody saw coming.",+ "Every clip has one clear action the video model renders well: people walking, running or riding straight, talking, reaching, hugging, a door opening, the light or the weather changing. Spell out what happens second by second.",+ "Never build a beat on what video models break: many small moving pieces (confetti, sparks, splashes, smashing crates, flying debris), crowds reacting, anything thrown, falling or caught, objects appearing, props passing between hands, vehicles turning, or text. Check every pitch line by line against this list before showing it (the user, 2026-11-05: 'you are adding details that are hard for the video to make').",+ "Ground the story in real people and a situation the viewer recognises. The turn comes from what the characters say or reveal, not from a gimmick premise or a physics stunt: high-concept setups (lasers that are art, a bomb that is a proposal) read as weird, not exciting.",+ "Never pitch gentle or wonder-led shorts: discovering something magical, chasing lights, watching a sunset, a quiet friendship, a robot finding a flower. If nothing dangerous or surprising happens, it is the wrong pitch.",+ "Design for Flow: one continuous location (each clip starts on the last frame of the one before), the same character throughout, no lip-synced dialogue (the narration carries the words).",+ "For each pitch give: the logline, the opening image, the three beats, the ending, and one sentence on why it hooks. Then let the user pick and generate nothing until they have.",],continuity: ["chain_previous: true starts a scene on the last frame of the scene before it, giving one continuous take across clips.",diff --git a/src/presenter.ts b/src/presenter.tsnew file mode 100644index 0000000..d2d645d--- /dev/null+++ b/src/presenter.ts@@ -0,0 +1,240 @@+import { execFile } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { promisify } from "node:util";++import { FFMPEG_HINT } from "./platform.js";++const run = promisify(execFile);+const FFMPEG = process.env.FLOW_MCP_FFMPEG ?? "ffmpeg";+const FFPROBE = process.env.FLOW_MCP_FFPROBE ?? "ffprobe";++// A talking presenter over footage, built from one recording of them: each stretch of the recording is shown full+// frame (optionally with a slow zoom) or in a circle in a corner over another clip. The sound is always the presenter's.+export interface PresenterSegment {+ from: number;+ to: number;+ layout: "full" | "corner";+ /** Full frame only: 1 shows the whole picture, 1.15 is 15% closer. Goes from `from` to `to` over the stretch. */+ zoom?: { from?: number; to?: number; x?: number; y?: number };+ /** Corner only: the clip behind the presenter. `from` is measured after any retime. */+ background?: { clip: string; from?: number; retime?: { from: number; to: number; speed: number }[] };+ /** Corner only: animate from full frame into the circle over this many seconds at the start of the stretch. */+ shrink?: number;+}++export interface PresenterOptions {+ presenter: string;+ segments: PresenterSegment[];+ dir: string;+ output_name?: string;+ size?: string;+ corner?: {+ position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";+ /** Circle diameter as a fraction of the frame's height. */+ size?: number;+ /** Square taken from the recording for the circle: centre x, centre y, and width, as fractions of the recording. */+ face?: { x: number; y: number; w: number };+ margin?: number;+ ring_color?: string;+ };+}++const even = (n: number) => Math.round(n / 2) * 2;++async function probe(file: string): Promise<{ width: number; height: number; fps: number; duration: number }> {+ const { stdout } = await run(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate:format=duration", "-of", "json", file]).catch(() => {+ throw new Error(`Could not read ${file}. ${FFMPEG_HINT}`);+ });+ const j = JSON.parse(stdout);+ const [n, d] = String(j.streams[0].r_frame_rate).split("/").map(Number);+ return { width: j.streams[0].width, height: j.streams[0].height, fps: n / (d || 1), duration: Number(j.format.duration) };+}++// Plays parts of a clip faster or slower, so its action lands on the presenter's words. Picture only: the presenter's+// sound is the film's sound. Anything not named plays at normal speed.+async function retimeClip(file: string, stretches: { from: number; to: number; speed: number }[], fps: number, out: string): Promise<void> {+ const { duration } = await probe(file);+ const sorted = [...stretches].sort((a, b) => a.from - b.from);+ const parts: { from: number; to: number; speed: number }[] = [];+ let at = 0;+ for (const r of sorted) {+ if (r.from < at - 0.001 || r.to <= r.from || r.speed <= 0) throw new Error(`Retime stretches must be in order and not overlap (${r.from} to ${r.to}).`);+ if (r.from > at) parts.push({ from: at, to: r.from, speed: 1 });+ parts.push({ from: r.from, to: Math.min(r.to, duration), speed: r.speed });+ at = r.to;+ }+ if (at < duration) parts.push({ from: at, to: duration, speed: 1 });+ const filters = parts.map((p, i) => `[0:v]trim=start=${p.from}:end=${p.to},setpts=(PTS-STARTPTS)/${p.speed}[p${i}]`);+ filters.push(`${parts.map((_, i) => `[p${i}]`).join("")}concat=n=${parts.length}:v=1:a=0,fps=${fps},format=yuv420p[v]`);+ await run(FFMPEG, ["-v", "error", "-y", "-i", file, "-filter_complex", filters.join(";"), "-map", "[v]", "-c:v", "libx264", "-preset", "veryfast", "-crf", "15", out]);+}++// The presenter shrinking from full frame into the circle, one frame at a time: the framing, the size, the place and+// the corner radius all ease together. ffmpeg's scale and overlay round to whole pixels, so a filter-graph move shakes.+async function shrinkClip(o: {+ presenter: string; from: number; seconds: number; background: string; backgroundFrom: number; fps: number; W: number; H: number;+ crop: { x: number; y: number; w: number }; info: { width: number; height: number }; target: { x: number; y: number; d: number }; ringColor: string; ring: number; dir: string; out: string;+}): Promise<void> {+ const frames = Math.max(2, Math.round(o.seconds * o.fps));+ const ease = (t: number) => t * t * (3 - 2 * t);+ for (let i = 0; i < frames; i++) {+ const t = ease(i / (frames - 1));+ const at = o.from + i / o.fps;+ const lerp = (a: number, b: number) => a + (b - a) * t;+ const outW = even(lerp(o.W, o.target.d));+ const outH = even(lerp(o.H, o.target.d));+ const x = Math.round(lerp(0, o.target.x));+ const y = Math.round(lerp(0, o.target.y));+ // Keep the source's shape for this frame's box, moving from the whole picture to the face square.+ const shapeW = lerp(o.info.width, o.crop.w);+ const shapeH = Math.min(o.info.height, shapeW * (outH / outW));+ const sx = Math.max(0, Math.round(lerp(0, o.crop.x)));+ const sy = Math.max(0, Math.min(o.info.height - shapeH, Math.round(lerp(0, o.crop.y))));+ const radius = lerp(0, o.target.d / 2);+ const inside = `if(gt(abs(X-${outW / 2})\\,${outW / 2 - radius})*gt(abs(Y-${outH / 2})\\,${outH / 2 - radius})\\,hypot(abs(X-${outW / 2})-${outW / 2 - radius}\\,abs(Y-${outH / 2})-${outH / 2 - radius})\\,${radius - 1})`;+ const alpha = radius < 1 ? "255" : `255*clip(${radius}-(${inside})+0.5\\,0\\,1)`;+ const ringOn = t > 0.02;+ const graph = [+ `[0:v]scale=${o.W}:${o.H}:flags=lanczos,format=rgba[bg]`,+ `[1:v]crop=${even(shapeW)}:${even(shapeH)}:${sx}:${Math.round(sy)},scale=${outW}:${outH}:flags=lanczos,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${alpha}'[fg]`,+ ringOn+ ? `color=${o.ringColor}:s=${outW + o.ring * 2}x${outH + o.ring * 2},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${radius < 1 ? "255" : `255*clip(${radius + o.ring}-(if(gt(abs(X-${outW / 2 + o.ring})\\,${outW / 2 - radius})*gt(abs(Y-${outH / 2 + o.ring})\\,${outH / 2 - radius})\\,hypot(abs(X-${outW / 2 + o.ring})-${outW / 2 - radius}\\,abs(Y-${outH / 2 + o.ring})-${outH / 2 - radius})\\,${radius + o.ring - 1}))+0.5\\,0\\,1)`}'[r];[bg][r]overlay=${x - o.ring}:${y - o.ring}[b2];[b2][fg]overlay=${x}:${y},format=rgb24[out]`+ : `[bg][fg]overlay=${x}:${y},format=rgb24[out]`,+ ].join(";");+ await run(FFMPEG, ["-v", "error", "-y", "-ss", (o.backgroundFrom + i / o.fps).toFixed(3), "-i", o.background, "-ss", at.toFixed(3), "-i", o.presenter, "-filter_complex", graph, "-map", "[out]", "-frames:v", "1", join(o.dir, `f${String(i).padStart(4, "0")}.png`)]);+ }+ await run(FFMPEG, ["-v", "error", "-y", "-framerate", String(o.fps), "-i", join(o.dir, "f%04d.png"), "-c:v", "libx264", "-preset", "veryfast", "-crf", "15", "-pix_fmt", "yuv420p", o.out]);+}++const q = (s: string) => s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");++export async function presenter(o: PresenterOptions): Promise<{ output: string; duration: number; segments: number }> {+ if (!o.segments.length) throw new Error("Give at least one segment.");+ for (const f of [o.presenter, ...o.segments.map((s) => s.background?.clip)]) if (f && !existsSync(f)) throw new Error(`File not found: ${f}`);+ const info = await probe(o.presenter);+ for (const [i, s] of o.segments.entries()) {+ if (s.to <= s.from) throw new Error(`Segment ${i + 1} ends before it starts.`);+ if (s.to > info.duration + 0.05) throw new Error(`Segment ${i + 1} runs to ${s.to} s, but the recording is ${info.duration.toFixed(2)} s long.`);+ if (s.layout === "corner" && !s.background) throw new Error(`Segment ${i + 1} is in the corner but has no background clip.`);+ }+ const asked = o.size?.match(/^(\d{2,4})x(\d{2,4})$/);+ const W = even(asked ? Number(asked[1]) : 1920);+ const H = even(asked ? Number(asked[2]) : 1080);+ const fps = Math.round(info.fps) || 24;++ const D = even(H * (o.corner?.size ?? 0.36));+ const ring = even(H * 0.006);+ const margin = Math.round(H * (o.corner?.margin ?? 0.045));+ const R = D + ring * 2;+ const pos = o.corner?.position ?? "bottom-right";+ const X = pos.endsWith("right") ? W - R - margin : margin;+ const Y = pos.startsWith("bottom") ? H - R - margin : margin;+ const face = o.corner?.face ?? { x: 0.5, y: 0.42, w: 0.45 };+ const cw = even(info.width * face.w);+ const cx = Math.max(0, Math.min(info.width - cw, Math.round(info.width * face.x - cw / 2)));+ const cy = Math.max(0, Math.min(info.height - cw, Math.round(info.height * face.y - cw / 2)));++ const work = mkdtempSync(join(tmpdir(), "flow-presenter-"));+ try {+ const circle = (size: number) => `255*clip(${size / 2}-hypot(X-${size / 2}+0.5\\,Y-${size / 2}+0.5)+0.5\\,0\\,1)`;+ const mask = join(work, "mask.png");+ const ringPng = join(work, "ring.png");+ await run(FFMPEG, ["-v", "error", "-y", "-f", "lavfi", "-i", `color=black:s=${D}x${D}`, "-frames:v", "1", "-vf", `format=gray,geq=lum='${circle(D)}'`, mask]);+ const c = o.corner?.ring_color ?? "white";+ await run(FFMPEG, ["-v", "error", "-y", "-f", "lavfi", "-i", `color=${c}:s=${R}x${R}`, "-frames:v", "1", "-vf", `format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${circle(R)}'`, ringPng]);++ const total = o.segments.reduce((sum, s) => sum + (s.to - s.from), 0);+ // Retime first, once per clip: everything below reads the retimed copy.+ const retimed = new Map<string, string>();+ for (const s of o.segments) {+ const b = s.background;+ if (!b?.retime?.length) continue;+ const key = `${b.clip}|${JSON.stringify(b.retime)}`;+ if (!retimed.has(key)) {+ const out = join(work, `retimed-${retimed.size}.mp4`);+ await retimeClip(b.clip, b.retime, fps, out);+ retimed.set(key, out);+ }+ s.background = { ...b, clip: retimed.get(key)! };+ }+ const backgrounds = [...new Set(o.segments.flatMap((s) => (s.background ? [s.background.clip] : [])))];+ // The shrink is rendered ahead of time and cut in as its own stretch.+ const shrinks = new Map<number, string>();+ for (const [i, s] of o.segments.entries()) {+ if (s.layout !== "corner" || !s.shrink) continue;+ const out = join(work, `shrink-${i}.mp4`);+ const frames = join(work, `frames-${i}`);+ mkdirSync(frames);+ await shrinkClip({ presenter: o.presenter, from: s.from, seconds: s.shrink, background: s.background!.clip, backgroundFrom: s.background!.from ?? 0, fps, W, H, crop: { x: cx, y: cy, w: cw }, info, target: { x: X + ring, y: Y + ring, d: D }, ringColor: c, ring, dir: frames, out });+ shrinks.set(i, out);+ }+ const args = ["-v", "error", "-y", "-i", o.presenter];+ for (const b of backgrounds) args.push("-i", b);+ const shrinkInputs = new Map<number, number>();+ for (const [i, file] of shrinks) {+ args.push("-i", file);+ shrinkInputs.set(i, backgrounds.length + 1 + shrinkInputs.size);+ }+ const maskIn = backgrounds.length + 1 + shrinkInputs.size;+ args.push("-loop", "1", "-framerate", String(fps), "-t", (total + 1).toFixed(3), "-i", mask);+ args.push("-loop", "1", "-framerate", String(fps), "-t", (total + 1).toFixed(3), "-i", ringPng);++ const filters: string[] = [];+ const parts: string[] = [];+ o.segments.forEach((s, i) => {+ const dur = (s.to - s.from).toFixed(3);+ const take = `[0:v]trim=start=${s.from}:end=${s.to},setpts=PTS-STARTPTS,fps=${fps},format=yuv420p`;+ if (s.layout === "full") {+ const z0 = s.zoom?.from ?? 1;+ const z1 = s.zoom?.to ?? z0;+ const scaled = `${take},scale=${W}:${H}:flags=lanczos,setsar=1`;+ if (z0 === 1 && z1 === 1) filters.push(`${scaled}[s${i}]`);+ else {+ // perspective samples between pixels, so a slow zoom does not stair-step the way zoompan and crop do.+ const frames = Math.max(1, Math.round((s.to - s.from) * fps) - 1);+ const zt = `(${z0}+(${z1 - z0})*min(in/${frames}\\,1))`;+ const fx = (s.zoom?.x ?? 0.5) * W;+ const fy = (s.zoom?.y ?? 0.45) * H;+ const hw = `(W/2/${zt})`;+ const hh = `(H/2/${zt})`;+ const left = `max(0\\,min(W-2*${hw}\\,${fx}-${hw}))`;+ const top = `max(0\\,min(H-2*${hh}\\,${fy}-${hh}))`;+ const p = `perspective=x0='${left}':y0='${top}':x1='${left}+2*${hw}':y1='${top}':x2='${left}':y2='${top}+2*${hh}':x3='${left}+2*${hw}':y3='${top}+2*${hh}':interpolation=cubic:sense=source:eval=frame`;+ filters.push(`${scaled},${p}[s${i}]`);+ }+ } else {+ const b = s.background!;+ const input = backgrounds.indexOf(b.clip) + 1;+ const lead = s.shrink ?? 0;+ const start = (b.from ?? 0) + lead;+ const rest = (s.to - s.from - lead).toFixed(3);+ filters.push(`[${input}:v]trim=start=${start}:duration=${rest},setpts=PTS-STARTPTS,fps=${fps},scale=${W}:${H}:force_original_aspect_ratio=increase:flags=lanczos,crop=${W}:${H},setsar=1,format=yuv420p[bg${i}]`);+ filters.push(`[0:v]trim=start=${s.from + lead}:end=${s.to},setpts=PTS-STARTPTS,fps=${fps},format=yuv420p,crop=${cw}:${cw}:${cx}:${cy},scale=${D}:${D}:flags=lanczos,setsar=1[f${i}]`);+ filters.push(`[${maskIn}:v]trim=duration=${rest},setpts=PTS-STARTPTS,format=gray[m${i}]`);+ filters.push(`[f${i}][m${i}]alphamerge[fa${i}]`);+ filters.push(`[${maskIn + 1}:v]trim=duration=${rest},setpts=PTS-STARTPTS,format=rgba[r${i}]`);+ filters.push(`[bg${i}][r${i}]overlay=${X}:${Y}:shortest=1[br${i}]`);+ if (shrinkInputs.has(i)) {+ filters.push(`[br${i}][fa${i}]overlay=${X + ring}:${Y + ring}:shortest=1,format=yuv420p[c${i}]`);+ filters.push(`[${shrinkInputs.get(i)}:v]fps=${fps},setsar=1,format=yuv420p[h${i}]`);+ filters.push(`[h${i}][c${i}]concat=n=2:v=1:a=0[s${i}]`);+ } else filters.push(`[br${i}][fa${i}]overlay=${X + ring}:${Y + ring}:shortest=1,format=yuv420p[s${i}]`);+ }+ filters.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS[a${i}]`);+ parts.push(`[s${i}][a${i}]`);+ });+ filters.push(`${parts.join("")}concat=n=${o.segments.length}:v=1:a=1[v][a]`);++ mkdirSync(o.dir, { recursive: true });+ const output = join(o.dir, `${(o.output_name ?? "presenter").replace(/[^\w.-]+/g, "_").replace(/\.mp4$/i, "")}.mp4`);+ args.push("-filter_complex", filters.join(";"), "-map", "[v]", "-map", "[a]", "-r", String(fps), "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", output);+ await run(FFMPEG, args, { maxBuffer: 1 << 24 }).catch((e: { stderr?: string; message: string }) => {+ throw new Error(`The presenter video could not be made: ${q(String(e.stderr ?? e.message)).slice(-800)}`);+ });+ return { output, duration: (await probe(output)).duration, segments: o.segments.length };+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+}diff --git a/src/queue.ts b/src/queue.tsindex ef48c90..c8e1b6b 100644--- a/src/queue.ts+++ b/src/queue.ts@@ -12,6 +12,7 @@ export interface SceneParams {aspect_ratio?: "16:9" | "9:16" | "1:1" | "4:3" | "3:4";variants?: number;first_frame?: string;+ first_frame_at?: number;last_frame?: string;reference_images?: string[];chain_from?: string;diff --git a/src/remote.ts b/src/remote.tsindex be2f64c..cb3bd1f 100644--- a/src/remote.ts+++ b/src/remote.ts@@ -1,5 +1,5 @@import { readFileSync } from "node:fs";-import type { Core } from "./core.js";+import { captionPreviewHere, captionSetupHere, captionsHere, narrateHere, presenterHere, transcribeHere, voicesHere, type Core } from "./core.js";import { PORT, TOKEN_FILE } from "./server.js";// Used when another flow-mcp process (Studio or a second Claude client) already owns the Flow tab and queue.@@ -23,8 +23,10 @@ export class RemoteCore implements Core {download = (a: unknown) => call("download", a);assemble = (a: unknown) => call("assemble", a);techniques = (a: unknown) => call("techniques", a);- voices = () => call("voices", {});- narrate = (a: unknown) => call("narrate", a);+ // Run here, not in the owner: they never touch Chrome, and the owner may be running older code.+ voices = voicesHere;+ narrate = narrateHere;+ new_project = (a: unknown) => call("new_project", a);character = (a: unknown) => call("character", a);characters = () => call("characters", {});character_edit = (a: unknown) => call("character_edit", a);@@ -35,10 +37,12 @@ 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", {});+ // Captions, like narration, run here: they never touch the Flow Chrome.+ transcribe = transcribeHere;+ caption_preview = captionPreviewHere;+ captions = captionsHere;+ presenter = presenterHere;+ caption_setup = captionSetupHere;// 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/studio/index.html b/studio/index.htmlindex 4471020..3e0a10d 100644--- a/studio/index.html+++ b/studio/index.html@@ -289,7 +289,7 @@ audio{width:100%;margin-top:8px;filter:invert(1) hue-rotate(180deg)}<section class="panel" data-panel="narrate"><div class="step">Step 4</div><h2>Voice</h2>- <p class="lede">Record narration for free, at any length. <b>Google AI Studio</b> gives you the same voices Flow uses and takes a delivery note; <b data-place="local_engine">macOS voice</b> speaks with a voice installed on <span data-place="computer">this Mac</span> and needs no key. Neither spends credits.</p>+ <p class="lede">Record narration for free, at any length. <b>Kokoro</b> runs on <span data-place="computer">this Mac</span>: no key, no daily limit, 28 voices. <b>Google AI Studio</b> gives you the same voices Flow uses and takes a delivery note. Neither spends credits.</p><div class="card"><label class="f">Project folder</label><input type="text" id="n_project" placeholder="MyFilm"><label class="f">Line to speak</label><textarea id="n_text" style="min-height:100px" placeholder="Sometimes the obstacles in your life aren't there to block you…"></textarea>@@ -303,6 +303,7 @@ audio{width:100%;margin-top:8px;filter:invert(1) hue-rotate(180deg)}<div class="grid2"><div><label class="f">Voice</label><select id="n_voice"></select></div></div>+ <div id="n_speedWrap"><label class="f" for="n_speed">Speed <span id="n_speedOut" style="text-transform:none;letter-spacing:0"></span></label><input type="range" id="n_speed" min="70" max="130" step="5" value="100"></div><div id="n_styleWrap"><label class="f">Delivery (optional)</label><input type="text" id="n_style" placeholder="slowly and warmly, like a documentary narrator"></div><p class="empty" id="n_fit" style="margin-top:10px"></p><div class="rowbtns"><button class="btn" id="n_go">Record take</button></div>@@ -455,13 +456,14 @@ const DEFAULTS = {tab: "cast",frames: { project: "MyFilm", aspect: "16:9", variants: 1, engine: "exact", scenes: [blank()] },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: "" },+ narrate: { project: "MyFilm", engine: "kokoro", kokoroVoice: "am_michael", speed: 100, geminiVoice: "Charon", text: "", style: "" },cut: { project: "MyFilm", music: null, voiceover: null, hold: true, clips: [] },captions: { video: null, style: "bold", position: "bottom", size: 100, 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));-let TECH = [], VOICES = { gemini: [], mac: [] }, CAST = [], LIB = [], GAL = [], castImage = null, pickTarget = null, busy = false;+if (!["kokoro", "gemini"].includes(S.narrate.engine)) S.narrate.engine = "kokoro"; // the computer-voice engine is gone+let TECH = [], VOICES = { kokoro: [], gemini: [] }, CAST = [], LIB = [], GAL = [], castImage = null, pickTarget = null, busy = false;/* ---------- tabs ---------- */function showTab(name) {@@ -478,6 +480,9 @@ function showTab(name) {window.scrollTo({ top: 0, behavior: "smooth" });}$("#tabs").addEventListener("click", (e) => { const b = e.target.closest("button[data-tab]"); if (b) showTab(b.dataset.tab); });+// A link can open a tab directly, e.g. http://127.0.0.1:8787/#captions.+const hashTab = () => { const t = location.hash.slice(1); return $(`#tabs button[data-tab="${CSS.escape(t)}"]`) ? t : null; };+addEventListener("hashchange", () => { const t = hashTab(); if (t) showTab(t); });/* ---------- segmented controls ---------- */const SEGS = {@@ -491,7 +496,7 @@ const SEGS = {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_letters: { get: () => capLetters(S.captions.style), set: (v) => { (S.captions.letters ??= {})[S.captions.style] = v; capPreviewSoon(); }, opts: ["as_said", "capitals", "lowercase"], labels: { as_said: "Normal", capitals: "CAPS", lowercase: "lower" } },- 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; } } },+ n_engine: { get: () => S.narrate.engine, set: (v) => (S.narrate.engine = v), opts: ["kokoro", "gemini"], labels: { kokoro: "Kokoro", gemini: "Google AI Studio" } },};function renderSegs() {for (const [key, cfg] of Object.entries(SEGS)) {@@ -683,38 +688,51 @@ document.addEventListener("click", (e) => {});/* ---------- narrate ---------- */+// Each engine keeps its own voice choice, so switching engines and back never loses the pick.+const VOICE_KEY = { kokoro: "kokoroVoice", gemini: "geminiVoice" };+const pickedVoice = () => S.narrate[VOICE_KEY[S.narrate.engine]] ?? (S.narrate.engine === "kokoro" ? "am_michael" : undefined);function renderNarrate() {- const mac = S.narrate.engine === "mac";- const list = (mac ? VOICES.mac : VOICES.gemini) ?? [];- const picked = mac ? S.narrate.macVoice : S.narrate.geminiVoice;- $("#n_voice").innerHTML = list.map((v) => `<option value="${v.name}" ${v.name === picked ? "selected" : ""}>${v.name} — ${v.description}</option>`).join("") || `<option value="">No voices found</option>`;- $("#n_styleWrap").style.display = mac ? "none" : "";- $("#n_engineNote").innerHTML = !mac- ? (VOICES.gemini_ready- ? "Google's own text-to-speech — the same voices Flow uses, free on the AI Studio tier, any length, and no Flow credits."- : `<b>Needs a free key.</b> Get one at <a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">aistudio.google.com/apikey</a> and paste it below. Same voices as Flow, free, no length limit.`)- : `Spoken on ${PLACE.computer} — free, instant, any length. Quality depends on the installed voice: ${PLACE.platform === "win32" ? "add more English voices in <b>Settings → Time & language → Speech</b> and they appear here" : "download a <b>Premium</b> English voice in System Settings → Accessibility → Spoken Content → System Voice → Manage Voices and it appears here automatically"}. ${(VOICES.mac ?? []).length} voice(s) available.`;- $("#n_keyWrap").hidden = mac;+ const eng = S.narrate.engine, kokoro = eng === "kokoro";+ const list = (VOICES[eng] ?? []);+ const picked = pickedVoice();+ $("#n_voice").innerHTML = list.map((v) => `<option value="${v.name}" ${v.name === picked ? "selected" : ""}>${v.label ?? v.name} — ${v.description}</option>`).join("") || `<option value="">No voices found</option>`;+ $("#n_styleWrap").style.display = eng === "gemini" ? "" : "none";+ $("#n_speedWrap").style.display = kokoro ? "" : "none";+ $("#n_speed").value = S.narrate.speed ?? 100;+ $("#n_speedOut").textContent = `${((S.narrate.speed ?? 100) / 100).toFixed(2)}×`;+ $("#n_engineNote").innerHTML = kokoro+ ? `A free voice that runs on ${PLACE.computer}: no key, no daily limit, any length. ` ++ (VOICES.kokoro_ready ? "Ready." : `The first take downloads it once (${VOICES.kokoro_mb ?? 326} MB, about a minute).`)+ : VOICES.gemini_ready+ ? "Google's own text-to-speech — the same voices Flow uses, free on the AI Studio tier with a daily limit, and no Flow credits. If the limit runs out, the take is recorded with Kokoro."+ : `<b>Needs a free key.</b> Get one at <a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">aistudio.google.com/apikey</a> and paste it below. Same voices as Flow, free, no length limit.`;+ $("#n_keyWrap").hidden = eng !== "gemini";$("#n_keyStatus").innerHTML = VOICES.gemini_ready? `A key is saved on ${PLACE.computer}. Paste a new one only to replace it.`: `Paste it here, not into a chat — it's saved only on ${PLACE.computer} and checked with Google first.`;const words = $("#n_text").value.trim().split(/\s+/).filter(Boolean).length;- const secs = Math.ceil(words / 2.5);+ const secs = Math.ceil(words / 2.5 / (kokoro ? (S.narrate.speed ?? 100) / 100 : 1));$("#n_fit").textContent = words ? `${words} words ≈ ${secs}s of speech. No length limit, no credits.` : "";}$("#n_text").addEventListener("input", () => { S.narrate.text = $("#n_text").value; save(); renderNarrate(); });-$("#n_voice").addEventListener("change", () => { S.narrate[S.narrate.engine === "mac" ? "macVoice" : "geminiVoice"] = $("#n_voice").value; save(); });+$("#n_voice").addEventListener("change", () => { S.narrate[VOICE_KEY[S.narrate.engine]] = $("#n_voice").value; save(); });+$("#n_speed").addEventListener("input", () => { S.narrate.speed = +$("#n_speed").value; save(); renderNarrate(); });$("#n_style").addEventListener("input", () => { S.narrate.style = $("#n_style").value; save(); });$("#n_go").onclick = async () => {if (!guard()) return;const text = $("#n_text").value.trim(); if (!text) return toast("Write the line first.", true);- const eng = S.narrate.engine, mac = eng === "mac";- const voice = mac ? S.narrate.macVoice : S.narrate.geminiVoice;- const b = $("#n_go"); b.disabled = true; b.textContent = "Recording…";+ const eng = S.narrate.engine;+ const voice = pickedVoice() || undefined;+ const b = $("#n_go"); b.disabled = true; b.textContent = eng === "kokoro" && !VOICES.kokoro_ready ? "Getting Kokoro (one time only)…" : "Recording…";try {- const out = await api("narrate", { project: $("#n_project").value.trim() || S.narrate.project, text, voice, engine: eng, style: mac ? undefined : $("#n_style").value.trim() || undefined });+ const out = await api("narrate", {+ project: $("#n_project").value.trim() || S.narrate.project, text, voice, engine: eng,+ speed: eng === "kokoro" ? (S.narrate.speed ?? 100) / 100 : undefined,+ style: eng === "gemini" ? $("#n_style").value.trim() || undefined : undefined,+ });+ if (eng === "kokoro") VOICES.kokoro_ready = true;{- $("#n_out").innerHTML = `<audio controls src="${media(out.output)}&t=${Date.now()}"></audio><p class="empty" style="margin-top:8px">${out.duration.toFixed(1)}s · free · ${esc(out.output)}</p>+ $("#n_out").innerHTML = `<audio controls src="${media(out.output)}&t=${Date.now()}"></audio>${out.note ? `<p class="empty" style="margin-top:8px;color:var(--warn)">${esc(out.note)}</p>` : ""}<p class="empty" style="margin-top:8px">${out.duration.toFixed(1)}s · ${esc(out.voice)} · free · ${esc(out.output)}</p><div class="rowbtns"><button class="btn small" data-usevo="${esc(out.output)}">Use in Cut</button></div>`;loadGallery();}@@ -1037,7 +1055,7 @@ function estimate() {} else {const narrateCost = "Free";$("#estNum").textContent = { cast: "Free", narrate: narrateCost, restyle: "≈ 20 credits", cut: "Free", library: "Free" }[tab] ?? "";- $("#estSub").textContent = { cast: "characters cost nothing", narrate: S.narrate.engine === "mac" ? `spoken on ${PLACE.computer}` : "Google AI Studio, free", restyle: "use Restyle clip", cut: "use Assemble film", library: "downloads cost nothing" }[tab] ?? "";+ $("#estSub").textContent = { cast: "characters cost nothing", narrate: S.narrate.engine === "gemini" ? "Google AI Studio, free" : `Kokoro, on ${PLACE.computer}`, restyle: "use Restyle clip", cut: "use Assemble film", library: "downloads cost nothing" }[tab] ?? "";btn.disabled = true;}}@@ -1081,7 +1099,7 @@ async function loadGallery(prefer) {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" };+let PLACE = { computer: "this Mac", bin: "the Mac's Trash", binShort: "Mac Trash", platform: "darwin" };function applyPlace(p) {if (!p) return;PLACE = { ...PLACE, ...p, binShort: p.platform === "win32" ? "Recycle Bin" : p.platform === "darwin" ? "Mac Trash" : "Trash" };@@ -1187,10 +1205,10 @@ for (const [id, path] of [["f_project", "frames"], ["s_project", "shots"], ["n_p$("#status").innerHTML = `<span class="pill"><i class="tally down"></i>Not connected</span>`;renderAll(); showTab(S.tab); return;}- try { [TECH, VOICES] = await Promise.all([api("techniques"), api("voices")]); } catch { VOICES = { gemini: [], mac: [] }; }+ try { [TECH, VOICES] = await Promise.all([api("techniques"), api("voices")]); } catch { VOICES = { kokoro: [], gemini: [] }; }applyPlace(VOICES.place);loadCast().then((c) => { CAST = c; renderCast(); }).catch(() => {});- renderAll(); showTab(S.tab); poll(true); loadGallery();+ renderAll(); showTab(hashTab() ?? S.tab); poll(true); loadGallery();})();</script></body>