Skip to content

A motion design studio on your own machine: Claude makes the video step by step, you approve every stage. Bring your own Claude Code or API key.

Narration: ElevenLabs with every option, or Qwen3-TTS on your own GPU

Gerrod Noordsyde76f14dcaa3
diff --git a/README.md b/README.md
index c6a4eca..dea2fa7 100644
--- a/README.md
+++ b/README.md
@@ -95,11 +95,26 @@ Pick one with `mortiflix init --backend …`, `mortiflix config backend …`, or
| `social-short` | brief → hook frames → final | 15–45 s vertical shorts: hook first, works with sound off |
| `logo-sting` | directions → final | a 3–8 s logo animation; the quickest real run |
-They build in [Remotion](https://www.remotion.dev/) (React video), check every render with ffmpeg (`qc.mjs`: format,
-black or frozen frames, loudness, a frame sheet Claude has to look at), and narrate through ElevenLabs when you put
-a key in the studio's `session.env`. Remotion has its own license: free for individuals and small teams, a company
+They build in [Remotion](https://www.remotion.dev/) (React video) and check every render with ffmpeg (`qc.mjs`:
+format, black or frozen frames, loudness, a frame sheet Claude has to look at). Remotion has its own license: free for individuals and small teams, a company
license above that. Check it for your case.
+## Narration
+
+Pick a voice in **Settings › Narration** (or `mortiflix voice`):
+
+- **ElevenLabs**: connect your key and choose from your voices, the default voices or the Voice Library, with
+ Eleven v4 by default and every option the API offers (models, stability and similarity, language, text
+ normalization, pronunciation dictionaries, audio format, data-residency servers), plus sound effects and music
+ beds. Settings shows your plan, credits, and whether you may use the audio commercially (the free plan doesn't).
+- **This computer**: Qwen3-TTS (open, Apache-2.0) through ComfyUI on your graphics card: free and private. Mortiflix
+ checks your GPU and offers it when it fits (4 GB for the 0.6B voice, 8 GB for the 1.7B voice with delivery
+ instructions).
+- **None**: on-screen text and music.
+
+Every line is checked by speech to text and retaken if words go missing; word timings drive the animation.
+Details: [docs/VOICE.md](docs/VOICE.md).
+
## Make your own pipeline
```sh
@@ -120,6 +135,7 @@ makes it, it can be a pipeline.
- [harness/GATES.md](harness/GATES.md): the protocol every session follows
- [docs/SECURITY.md](docs/SECURITY.md): what a session can and can't reach, and the web server's guards
- [docs/COMPUTE.md](docs/COMPUTE.md): where the tokens, time and disk go, measured on a real project
+- [docs/VOICE.md](docs/VOICE.md): narration with ElevenLabs or on your own GPU, and every option
## Where it came from
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 365f2b0..81b999b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -103,6 +103,16 @@ returns `{ ok, error?, usage?, cost_usd? }`; `available(config, root)` says whet
Adding a backend is adding a module with those two functions to `BACKENDS` in `runner.mjs`.
+## Narration (`src/voice/`)
+
+`voice/index.mjs` holds the studio's choice (`config.json` › `voice`: `none`, `elevenlabs` or `qwen`) and hands a
+session `MFX_VOICE` (the settings) plus `ELEVENLABS_API_KEY` only when ElevenLabs is the engine.
+`voice/elevenlabs.mjs` talks to ElevenLabs for setup (account, models, voices, Voice Library, dictionaries, a test
+line) and builds every text-to-speech request so it carries only what the chosen model takes (Eleven v4: stability and
+similarity only). `voice/qwen.mjs` detects the GPU, reads the installed ComfyUI nodes (models, voices, runtime modes)
+and builds the speak and listen graphs. Sessions narrate with the voiceover skill's `vo.mjs`, which imports these
+modules (`MFX_HOME`), and make effects and music beds with `sound.mjs`. See [VOICE.md](VOICE.md).
+
## The web studio (`src/web/server.mjs`, `web/`)
A plain `node:http` server and a no-build vanilla JS app. JSON API under `/api`, live updates over server-sent events
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index bca8d8d..50beca2 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -46,7 +46,9 @@ rule it out. If you hand a session files or links from sources you don't trust,
- The Anthropic API key (Settings or `mortiflix config api-key`) is stored in `secrets.json` (mode 600) and is never
returned by the API or shown in the UI. Sessions don't get it.
-- `session.env` keys (e.g. `ELEVENLABS_API_KEY`) are given to every session's environment. Only put keys there that
+- The ElevenLabs key (Settings › Narration or `mortiflix voice elevenlabs`) is stored in `secrets.json` too, and
+ given to a session only while ElevenLabs is the narration engine.
+- `session.env` keys are given to every session's environment. Only put keys there that
sessions need, and prefer keys with spending limits.
## The web server
diff --git a/docs/VOICE.md b/docs/VOICE.md
new file mode 100644
index 0000000..a829f37
--- /dev/null
+++ b/docs/VOICE.md
@@ -0,0 +1,103 @@
+# Narration, sound effects and music
+
+Mortiflix can narrate your videos three ways. Pick one in **Settings › Narration** (web) or with `mortiflix voice`.
+
+| | ElevenLabs | This computer (Qwen3-TTS) | No narration |
+|---|---|---|---|
+| Sound | the most natural voices; 90+ languages on Eleven v4 | very good; 10 languages | on-screen text and music carry it |
+| Cost | per character, on your ElevenLabs plan | free (your electricity) | free |
+| Privacy | text goes to ElevenLabs | nothing leaves your machine | nothing to send |
+| Needs | an API key from elevenlabs.io | an NVIDIA GPU with 4 GB+ (8 GB+ for the 1.7B voice), ComfyUI, the TTS Audio Suite | nothing |
+| Voices | thousands (yours, the defaults, the Voice Library, your own clones) | 9 built into the model | |
+| Also | sound effects and music beds | | |
+
+Whichever you choose, every line is checked by speech to text after it's made: a take with missing or extra words
+is made again, and the timings of every word go to the animation.
+
+## ElevenLabs
+
+1. Get an API key: elevenlabs.io › Developers › API keys.
+2. Settings › Narration › ElevenLabs, paste it, **Connect**. You'll see your plan, credits left, when they reset,
+ and whether you may use the audio commercially.
+3. **Choose a voice**: your voices and the default voices, or **Browse the Voice Library** (thousands of community
+ voices; "Add & use" copies one into your account). ▶ plays each voice's own preview, free.
+4. Pick the model and settings, then **Try it** with a line of your own.
+
+Everything is read from your account: the models list comes from the API, so new models appear by themselves.
+
+### The options, and what they do
+
+| Option | What it does |
+|---|---|
+| **Model** | `eleven_v4` (default and recommended: highest quality, best cloning, 90+ languages), `eleven_v4_turbo` (fast), `eleven_v3`, `eleven_multilingual_v2` (29 languages, has style and speed settings), `eleven_flash_v2_5` / `eleven_flash_v2` (fastest) |
+| **Stability** | lower is more expressive and varied, higher is steadier (all models) |
+| **Similarity** | how closely it sticks to the original voice (all models) |
+| **Style, speed, speaker boost** | only on models that have them; Eleven v4 doesn't (it's directed with audio tags instead) |
+| **Language** | an ISO 639-1 code to force the language and how numbers are read; blank detects it |
+| **Text normalization** | auto, on (spell out numbers, dates, abbreviations), off (read as written) |
+| **Pronunciation dictionaries** | up to 3 of your dictionaries, applied in order. Phoneme rules work on v4, v3 and Flash v2; other models use alias rules only |
+| **Audio format** | MP3 128 kbps (default) up to WAV 48 kHz. 192 kbps MP3 needs the Creator plan or above, 44.1 kHz WAV/PCM needs Pro |
+| **Server** | for accounts on a data-residency server (US, EU, India, Singapore) |
+| **Checks** | Scribe v2 speech to text on every take (recommended), or off |
+| **Sound effects** | lets sessions make effects with `eleven_text_to_sound_v2`: 0.5–30 s, loopable |
+| **Music beds** | lets sessions compose with Eleven Music (`music_v2_5`): instrumental, 3 s to 10 min. Usage terms depend on your plan: [elevenlabs.io/music-terms](https://elevenlabs.io/music-terms) |
+
+How lines are made: each one is sent with the text before and after it (so the delivery flows), a seed (so a good
+take can be reproduced), and only the settings the chosen model accepts. Lines run in parallel up to your plan's limit
+minus one (Free 2, Starter 3, Creator 5, Pro 10, Scale and Business 15).
+
+### Directing Eleven v4
+
+Sessions write delivery into the script itself: audio tags like `[warm]`, `[whispers]`, `[excited]`; CAPITALS for
+emphasis; ellipses for pauses; and IPA between slashes for names (`"/ˈkoʊmæl/"`). Eleven v4 doesn't support SSML.
+
+### Good to know
+
+- **Free plan:** audio may be used **non-commercially only, with attribution** to ElevenLabs. Paid plans include
+ commercial rights. Settings shows which you're on, and sessions say so in their notes.
+- **Zero-retention mode** (no logs kept at ElevenLabs) is for Enterprise accounts only.
+- **Voice clones:** only of your own voice, or with the speaker's clear consent.
+- Your key stays in the studio folder (`secrets.json`, readable only by you). Sessions get it only while ElevenLabs
+ is the narration engine.
+
+## This computer: Qwen3-TTS through ComfyUI
+
+[Qwen3-TTS](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice) is an open model (Apache-2.0). Mortiflix
+runs it through [ComfyUI](https://www.comfy.org/) and the [TTS Audio Suite](https://github.com/diodiogod/TTS-Audio-Suite)
+custom nodes, on your graphics card. Settings checks your GPU and only recommends it when it fits:
+
+| Your GPU memory | What you get |
+|---|---|
+| 8 GB or more | **CustomVoice 1.7B**: preset voices plus a delivery instruction ("a calm, warm narrator, unhurried") |
+| 4–8 GB | **CustomVoice 0.6B**: preset voices, no instruction |
+| less | not offered |
+
+Measured on an RTX 3080 (10 GB): the 1.7B voice needs about 6.5 GB free while it speaks, and the listening check
+(Qwen3-ASR 1.7B) about 6 GB. They take turns: Mortiflix speaks every line, frees the GPU, then listens to every
+line. It only asks ComfyUI to free memory when nothing else is queued there, so your other ComfyUI work is never
+interrupted.
+
+### Setting it up
+
+1. Install ComfyUI ([comfy.org/download](https://www.comfy.org/download)) and start it (`http://127.0.0.1:8188`).
+2. In ComfyUI Manager, install **TTS Audio Suite** (or clone it into `custom_nodes/` and run its `install.py`).
+3. Restart ComfyUI, then **Settings › Narration › This computer › Check** (or `mortiflix voice local`).
+ The models download from Hugging Face on first use (about 4 GB for 1.7B).
+
+### The options
+
+- **Voice:** Ryan, Aiden (English); Vivian, Serena, Uncle_Fu, Dylan, Eric (Chinese, two with regional dialects);
+ Ono_Anna (Japanese); Sohee (Korean). Each can speak all 10 languages; that's its native one. They're built into the
+ model, so there's no cloning and no consent question.
+- **Language:** English, Chinese, Japanese, Korean, German, French, Russian, Portuguese, Spanish, Italian.
+- **Delivery** (1.7B only): the instruction, in plain words. Inline tags aren't read.
+- **Runtime:** the suite's own setting. Try Main Environment first; if ComfyUI reports a transformers version
+ error, its Shared Runtime isolates the model.
+- **Checks:** listen back to every line with Qwen3-ASR (retakes and word timings).
+
+The options shown come from the nodes you have installed, so a newer suite with other models or voices still works.
+
+## No narration
+
+Videos are made with on-screen text, music and sound. If a brief asks for a voice anyway, the session asks you at
+the next review whether to continue without one.
diff --git a/pipelines/_shared/skills/voiceover/SKILL.md b/pipelines/_shared/skills/voiceover/SKILL.md
index fd3a640..b9b1b7a 100644
--- a/pipelines/_shared/skills/voiceover/SKILL.md
+++ b/pipelines/_shared/skills/voiceover/SKILL.md
@@ -1,54 +1,112 @@
---
name: voiceover
-description: Narration for a video: lines from the approved script, voice clips, word timings, and one voice track with a timing map the animation follows. Use for any narrated animatic or final.
+description: Narration, sound effects and music beds in the voice the studio set up (ElevenLabs, or Qwen3-TTS on this machine's GPU): lines from the approved script, checked takes, one voice track and a word-timing map the animation follows. Use for any narrated animatic or final, a re-take, or sound design.
---
# Voiceover
-The approved script is spoken **word for word**. Narration is the clock the animation is timed to.
+The approved script is spoken **word for word**, and the narration is the clock the animation is timed to.
-## 0. Is there a voice?
+```
+VO=.claude/skills/voiceover/vo.mjs
+node $VO check # which engine, voice and model; credits; the rules for this engine
+node $VO speak voice/lines.json # every line, checked, retaken if words go missing
+node $VO speak voice/lines.json --only b03-1 # just the lines you fixed
+node $VO build voice/lines.json # voice/voice.wav + voice/timing.json
+```
+
+## 0. Which voice?
+
+`node $VO check` says what the owner set up in Settings (you don't choose the engine or the voice):
-`node .claude/skills/voiceover/vo.mjs check`
+- **`elevenlabs`**: the voice, model and settings are chosen; the key is in your environment (never print it).
+ `check` shows the plan and credits. On the **free plan** the audio is non-commercial and must credit ElevenLabs:
+ say so in your submission note.
+- **`qwen`**: Qwen3-TTS on this machine's GPU through ComfyUI (free, local). If `check` says ComfyUI or the suite
+ isn't ready, that's a `mfx needs-you`.
+- **`none`**: no narration. If the brief asked for one, ask at the next gate whether to go on-screen-text-only
+ (the default) or wait while the owner sets a voice up. Never use a robotic system voice.
+- **The owner's own recording** in `input/`: use it instead (cut it into lines as clips, then `build`).
-- **ElevenLabs** (`ELEVENLABS_API_KEY`, optional `ELEVENLABS_VOICE_ID`, in the studio's `session.env`): the default path below.
-- **No voice service:** don't invent one. If the brief asked for narration, ask at the next gate (or `mfx ask`)
- whether to go on-screen-text-only or wait for a key, with on-screen text as the default. Never ship a robotic
- system voice as the final narration.
-- **The owner's own recording** in `input/`: use it, cut into lines, and skip `speak`.
+Don't change the voice or the model yourself: they're the owner's choice. Suggest a change in the handoff if one
+would clearly be better.
-## 1. Lines
+## 1. Write `voice/lines.json`
-Split the approved script into `voice/lines.json`, one line per sentence or breath:
+One entry per sentence or breath group (under ~600 characters; short lines are cheap to retake):
```json
-[{ "id": "b01-1", "text": "Every city has a heartbeat.", "gap_after": 0.5 }, { "id": "b01-2", "text": "Ours runs on bikes." }]
+[
+ { "id": "b01-1", "text": "[warm, unhurried] Every city has a heartbeat.", "script": "Every city has a heartbeat.", "gap_after": 0.5 },
+ { "id": "b01-2", "text": "Ours runs on \"/ˈbaɪsɪkəlz/\".", "script": "Ours runs on bicycles." }
+]
```
-Ids follow the script's beats (`b01-1`). `gap_after` is the pause after a line (default 0.4 s; longer between beats).
-Write numbers, units and names the way they should be *said* ("twenty twenty-six", "four point five percent").
+- `text` is what the voice reads; `script` is the same words spelled normally (needed whenever `text` has tags or IPA:
+ the check compares against it). `gap_after` is the pause after the line (default 0.4 s; longer between beats).
+- Ids follow the script's beats (`b01-1`), letters, digits and dashes.
+- **Write numbers, dates and money the way they're said** ("twenty twenty-six", "four point five percent").
-## 2. Clips
+### Directing ElevenLabs Eleven v4 (`eleven_v4`, the default)
-```
-node .claude/skills/voiceover/vo.mjs speak voice/lines.json --voice <voice id>
-```
+- **Audio tags** in square brackets steer delivery: `[warm]`, `[measured, curious]`, `[whispers]`, `[sighs]`,
+ `[excited]`, `[quick, light pace]`. One at the start of a line; another only where the mood really turns.
+- **Describe the voice, not a sound.** v4 also makes sound effects, so `[rain]` or `[applause]` can come out as a
+ noise. Write `[soft, hushed voice]`, not `[quiet room]`. The check flags any non-speech sound in a take.
+- **Punctuation and capitals:** ellipses add pauses and weight, CAPITALS add emphasis. **No SSML**: v4 ignores
+ `<break>` and `<phoneme>` (they can be read aloud).
+- **Pronunciation:** IPA between slashes inside quotes, `"/ˈkoʊmæl/"`, with the normal spelling in `script`.
+- v4 has **only stability and similarity** (set in Settings); there's no style or speed: direct pace with tags and
+ punctuation.
+- Each line is sent with its neighbours' text, so the delivery flows across lines.
+
+Other ElevenLabs models (if the owner chose one): `eleven_multilingual_v2` has style and speed settings and takes
+`<break time="1.0s" />` pauses (up to 3 s); `eleven_flash_v2` takes `<phoneme>` tags. Don't use tags v4-style on them.
+
+### Directing Qwen3-TTS (local)
-Listen to the first two clips before making the rest: pace, pronunciation, tone. One voice for the whole video:
-never switch silently. Remake a single bad line with `--force` after editing just that line (or delete its clip).
+- Delivery comes from the **instruction** the owner set (1.7B model); the line is read as plain words. Tags and IPA
+ are dropped before speaking (`script` is read when present), so **spell hard names the way they sound** in `script`.
+- 10 languages (English, Chinese, Japanese, Korean, German, French, Russian, Portuguese, Spanish, Italian).
-## 3. Timing
+## 2. Speak and check
+
+`speak` makes each line, listens to it with speech to text (ElevenLabs Scribe v2, or Qwen3-ASR locally), and keeps
+it when at least 92% of the words match the script with no 3-word run missing or added, and no stray sounds. A line
+that fails is retaken with a new seed (up to `--max-takes`, default 3); the best take is kept either way. ElevenLabs
+lines run several at once (the plan's limit minus one); local lines run speak-all, then listen-all, because the two
+models take turns on the GPU.
+
+- Results: `voice/clips/<id>.(mp3|wav)` + `<id>.json` (engine, take, seed, the transcript, word timings),
+ every take in `voice/takes/`, and `voice/speak-report.json`.
+- **A line that keeps failing: fix the input, don't re-roll.** Split a long sentence, spell out a number, add IPA
+ (ElevenLabs) or a sounds-like spelling (local), then `speak --only` it.
+- **Listen** to the first two lines before making the rest: pace, pronunciation, tone. The check catches missing
+ words, not taste.
+
+## 3. Build
+
+`build` joins the clips with their gaps into `voice/voice.wav` (48 kHz mono) and writes `voice/timing.json`: every
+line's start and end, and every word's start and end when the check measured them (`"timing": "words"`), otherwise
+the line only. Turn the times you animate to into frames (`Math.round(seconds * fps)`) in `video/src/timing.ts`,
+and copy `voice.wav` into `video/public/`. Never cut inside a word: cut in the silences.
+
+## 4. Sound effects and music (ElevenLabs, when switched on)
```
-node .claude/skills/voiceover/vo.mjs time voice/lines.json # word timings from speech-to-text
-node .claude/skills/voiceover/vo.mjs build voice/lines.json # voice/voice.wav + voice/timing.json
+node .claude/skills/voiceover/sound.mjs sfx "soft glassy whoosh, left to right" --seconds 1.2 --out sfx/whoosh.mp3
+node .claude/skills/voiceover/sound.mjs sfx "low city ambience, distant traffic" --seconds 20 --loop --out sfx/city.mp3
+node .claude/skills/voiceover/sound.mjs music "warm minimal synth bed, 90 bpm, hopeful" --seconds 45 --out music/bed.mp3
```
-- `time` warns when what it heard differs from the line: a skipped or misread word. Remake that line.
-- `voice/timing.json` has every line's and word's start and end in the finished track. Turn the ones you animate
- to into frames (`Math.round(seconds * fps)`) in `video/src/timing.ts`.
-- Copy `voice/voice.wav` into `video/public/` for the render.
+Sound effects: 0.5–30 s, `--loop` for seamless ambience, `--influence` 0–1 (how literally it follows the prompt).
+Music: instrumental unless `--vocals`, 3 s to 10 min. Note every prompt in `assets/SOURCES.md`.
+
+## 5. Mix
+
+Music about 18 dB under the voice while it speaks; it can come up in the gaps. The final mix: -14 LUFS, true peak
+≤ -1 dBTP (final-pass skill).
-## 4. Mix
+## 6. Record
-Music about 18 dB under the voice while it speaks. The final mix: -14 LUFS, true peak ≤ -1 dBTP (final-pass skill).
+Write `voice/VOICE.md`: engine, voice, model, settings, tags used, pronunciation fixes, rejected takes and why.
diff --git a/pipelines/_shared/skills/voiceover/sound.mjs b/pipelines/_shared/skills/voiceover/sound.mjs
new file mode 100644
index 0000000..9d27452
--- /dev/null
+++ b/pipelines/_shared/skills/voiceover/sound.mjs
@@ -0,0 +1,52 @@
+#!/usr/bin/env node
+// sound.mjs: sound effects and music beds from ElevenLabs, when the studio has them switched on.
+//
+// node .claude/skills/voiceover/sound.mjs sfx "soft glassy whoosh, left to right" --seconds 1.2 [--loop] [--influence 0.3] --out sfx/whoosh.mp3
+// node .claude/skills/voiceover/sound.mjs music "warm, minimal synth bed, 90 bpm, no vocals" --seconds 45 [--vocals] --out music/bed.mp3
+//
+// sfx: eleven_text_to_sound_v2, 0.5 to 30 s (or let it choose), --loop for a seamless loop, --influence 0-1 (how
+// literally it follows the prompt; default 0.3).
+// music: Eleven Music (music_v2_5 by default, --model to change), 3 s to 10 min, instrumental unless --vocals.
+// Usage terms for music depend on the ElevenLabs plan: https://elevenlabs.io/music-terms
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+
+const args = process.argv.slice(2);
+const [kind, prompt] = args;
+const opt = (name, def = null) => { const i = args.indexOf(`--${name}`); return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : def; };
+const die = (msg) => { console.error(`sound: ${msg}`); process.exit(1); };
+
+const voice = (() => { try { return JSON.parse(process.env.MFX_VOICE || '{}'); } catch { return {}; } })();
+const cfg = voice.elevenlabs || {};
+const key = process.env.ELEVENLABS_API_KEY;
+const SERVERS = { default: 'https://api.elevenlabs.io', us: 'https://api.us.elevenlabs.io', eu: 'https://api.eu.residency.elevenlabs.io', in: 'https://api.in.residency.elevenlabs.io', sg: 'https://api.sg.residency.elevenlabs.io' };
+
+if (!['sfx', 'music'].includes(kind) || !prompt) die('usage: sound.mjs sfx|music "prompt" [--seconds N] --out file.mp3');
+if (voice.engine !== 'elevenlabs' || !key) die('ElevenLabs isn\'t set up in this studio: make the sound another way (or ask the owner).');
+if (kind === 'sfx' && cfg.sfx === false) die('the studio switched ElevenLabs sound effects off');
+if (kind === 'music' && !cfg.music) die('the studio hasn\'t switched Eleven Music on (Settings › Voice). Use another music source.');
+const out = opt('out') || die('--out file.mp3 is required');
+const seconds = opt('seconds') === null ? null : Number(opt('seconds'));
+
+let path, body;
+if (kind === 'sfx') {
+ if (seconds !== null && !(seconds >= 0.5 && seconds <= 30)) die('--seconds must be 0.5 to 30 for a sound effect');
+ const influence = Number(opt('influence', 0.3));
+ if (!(influence >= 0 && influence <= 1)) die('--influence must be 0 to 1');
+ path = '/v1/sound-generation';
+ body = { text: prompt, model_id: 'eleven_text_to_sound_v2', prompt_influence: influence, loop: args.includes('--loop'), ...(seconds !== null ? { duration_seconds: seconds } : {}) };
+} else {
+ if (seconds !== null && !(seconds >= 3 && seconds <= 600)) die('--seconds must be 3 to 600 for music');
+ path = '/v1/music';
+ body = { prompt, model_id: opt('model', 'music_v2_5'), force_instrumental: !args.includes('--vocals'), ...(seconds !== null ? { music_length_ms: Math.round(seconds * 1000) } : {}) };
+}
+
+const res = await fetch(new URL(`${path}?output_format=mp3_44100_128`, SERVERS[cfg.server] || SERVERS.default), {
+ method: 'POST',
+ headers: { 'xi-api-key': key, 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+});
+if (!res.ok) die(`ElevenLabs ${res.status} ${(await res.text()).slice(0, 300)}`);
+mkdirSync(dirname(out), { recursive: true });
+writeFileSync(out, Buffer.from(await res.arrayBuffer()));
+console.log(`${out}: ${kind}${seconds ? `, ${seconds} s` : ''}. Note its prompt in assets/SOURCES.md.`);
diff --git a/pipelines/_shared/skills/voiceover/vo.mjs b/pipelines/_shared/skills/voiceover/vo.mjs
index 3210f2e..22abfc3 100644
--- a/pipelines/_shared/skills/voiceover/vo.mjs
+++ b/pipelines/_shared/skills/voiceover/vo.mjs
@@ -1,121 +1,321 @@
#!/usr/bin/env node
-// vo.mjs: narration for a video.
+// vo.mjs: narration for a video, in the voice the studio set up (ElevenLabs, or Qwen3-TTS on this machine's GPU).
//
-// node .claude/skills/voiceover/vo.mjs check is a voice service set up?
-// node .claude/skills/voiceover/vo.mjs speak voice/lines.json [--voice ID] [--model ID] [--force]
-// one clip per line → voice/clips/<id>.mp3 (ElevenLabs; needs ELEVENLABS_API_KEY in the session)
-// node .claude/skills/voiceover/vo.mjs time voice/lines.json word timings per clip (speech-to-text)
-// node .claude/skills/voiceover/vo.mjs build voice/lines.json [--gap 0.4]
-// joins the clips with gaps → voice/voice.wav + voice/timing.json (line and word start times in the video)
+// node .claude/skills/voiceover/vo.mjs check
+// node .claude/skills/voiceover/vo.mjs speak voice/lines.json [--only id,id] [--max-takes 3] [--jobs N]
+// node .claude/skills/voiceover/vo.mjs build voice/lines.json [--gap 0.4] → voice/voice.wav + voice/timing.json
//
-// voice/lines.json: [{ "id": "b01", "text": "The exact words.", "gap_after": 0.4 }, ...] (ids: letters, digits, -)
+// voice/lines.json: [{ "id": "b01-1", "text": "[warm] The words as spoken.", "script": "The words as spoken.", "gap_after": 0.5 }]
+// text what the voice reads (ElevenLabs v4 takes [audio tags] and "/IPA/"; the local voice reads `script` if given)
+// script the same words spelled normally, for the check (needed when text has tags or IPA)
+//
+// The voice comes from the studio's settings ($MFX_VOICE); keys are in the environment, never printed.
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, rmSync } from 'node:fs';
+import { join, extname } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const args = process.argv.slice(2);
+const [cmd, file] = args;
+const opt = (name, def = null) => { const i = args.indexOf(`--${name}`); return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : def; };
+const die = (msg) => { console.error(`vo: ${msg}`); process.exit(1); };
+const OUT = 'voice';
+
+const voice = (() => { try { return JSON.parse(process.env.MFX_VOICE || '{}'); } catch { return {}; } })();
+const engine = voice.engine || 'none';
+const home = process.env.MFX_HOME;
+const lib = async (name) => {
+ if (!home) die('MFX_HOME is not set (run this inside a Mortiflix session)');
+ return import(pathToFileURL(join(home, 'src', 'voice', name)).href);
+};
-const API = 'https://api.elevenlabs.io/v1';
-const [cmd, file, ...rest] = process.argv.slice(2);
-const opt = (name, def = null) => { const i = rest.indexOf(`--${name}`); return i >= 0 ? rest[i + 1] : def; };
-const key = process.env.ELEVENLABS_API_KEY;
+// ---------------------------------------------------------------------------------------------------------------
+// lines and the check
function lines() {
if (!file || !existsSync(file)) die(`no lines file: ${file || '(missing)'}`);
const list = JSON.parse(readFileSync(file, 'utf8'));
- for (const l of list) if (!/^[A-Za-z0-9-]{1,40}$/.test(l.id || '') || !String(l.text || '').trim()) die(`bad line: ${JSON.stringify(l)}`);
- return list;
+ const ids = new Set();
+ for (const l of list) {
+ if (!/^[A-Za-z0-9-]{1,40}$/.test(l.id || '') || !String(l.text || '').trim()) die(`bad line: ${JSON.stringify(l)}`);
+ if (ids.has(l.id)) die(`line id ${l.id} appears twice`);
+ ids.add(l.id);
+ }
+ const only = opt('only');
+ return only ? list.filter((l) => only.split(',').includes(l.id)) : list;
}
-function die(msg) { console.error(`vo: ${msg}`); process.exit(1); }
+// The words as they should be heard: tags and IPA out, spelled normally.
+const heard = (l) => String(l.script || l.text).replace(/\[[^\]]*\]/g, ' ').replace(/"?\/[^/\s][^/]*\/"?/g, ' ');
+const words = (s) => String(s).toLowerCase().replace(/[’']/g, '').replace(/[^\p{L}\p{N}]+/gu, ' ').trim().split(' ').filter(Boolean);
+
+// How much of the script was said: matched words (longest common subsequence) and the longest run left out or added.
+function compare(script, transcript) {
+ const a = words(script), b = words(transcript);
+ const dp = Array.from({ length: a.length + 1 }, () => new Int32Array(b.length + 1));
+ for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
+ let i = 0, j = 0, missing = 0, extra = 0, maxMissing = 0, maxExtra = 0;
+ while (i < a.length || j < b.length) {
+ if (i < a.length && j < b.length && a[i] === b[j]) { i++; j++; missing = 0; extra = 0; }
+ else if (j >= b.length || (i < a.length && dp[i + 1][j] >= dp[i][j + 1])) { i++; maxMissing = Math.max(maxMissing, ++missing); extra = 0; }
+ else { j++; maxExtra = Math.max(maxExtra, ++extra); missing = 0; }
+ }
+ const matched = dp[0][0];
+ return { similarity: a.length + b.length ? Math.round((2 * matched / (a.length + b.length)) * 1000) / 1000 : 1, longest_missing: maxMissing, longest_extra: maxExtra };
+}
+
+function judge(l, t) {
+ const c = compare(heard(l), t.text);
+ const problems = [];
+ if (c.similarity < Number(opt('threshold', 0.92))) problems.push(`said ${Math.round(c.similarity * 100)}% of the words right`);
+ if (c.longest_missing >= 3) problems.push(`${c.longest_missing} words in a row missing`);
+ if (c.longest_extra >= 3) problems.push(`${c.longest_extra} extra words in a row`);
+ if (t.events?.length) problems.push(`non-speech sounds: ${t.events.join(', ')} (a tag became a sound effect?)`);
+ return { pass: !problems.length, compare: c, problems };
+}
function duration(f) {
const r = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', f], { encoding: 'utf8' });
return Number(r.stdout.trim());
}
-async function speak() {
- if (!key) die('ELEVENLABS_API_KEY is not set. Add it to the studio\'s session.env, or make the video without narration (ask the owner first).');
- const voice = opt('voice', process.env.ELEVENLABS_VOICE_ID);
- if (!voice) die('no voice: pass --voice <voice id> or set ELEVENLABS_VOICE_ID');
- const model = opt('model', process.env.ELEVENLABS_MODEL || 'eleven_multilingual_v2');
- mkdirSync('voice/clips', { recursive: true });
- for (const l of lines()) {
- const out = join('voice/clips', `${l.id}.mp3`);
- if (existsSync(out) && !rest.includes('--force')) { console.log(`skip ${l.id} (exists; --force to remake)`); continue; }
- const res = await fetch(`${API}/text-to-speech/${encodeURIComponent(voice)}?output_format=mp3_44100_128`, {
- method: 'POST',
- headers: { 'xi-api-key': key, 'content-type': 'application/json' },
- body: JSON.stringify({ text: l.text, model_id: model }),
- });
- if (!res.ok) die(`${l.id}: ElevenLabs ${res.status} ${(await res.text()).slice(0, 300)}`);
- writeFileSync(out, Buffer.from(await res.arrayBuffer()));
- console.log(`${l.id}: ${duration(out).toFixed(2)} s`);
- }
+function run(argv) {
+ const r = spawnSync(argv[0], argv.slice(1), { encoding: 'utf8' });
+ if (r.status !== 0) die(`${argv[0]} failed: ${r.stderr.slice(-400)}`);
}
-// Word timings from speech-to-text on the audio itself (more reliable than the synthesizer's own timestamps).
-async function time() {
- if (!key) die('ELEVENLABS_API_KEY is not set (speech-to-text needs it).');
- mkdirSync('voice/timing', { recursive: true });
- for (const l of lines()) {
- const clip = join('voice/clips', `${l.id}.mp3`);
- if (!existsSync(clip)) die(`${clip} is missing: speak first`);
- const form = new FormData();
- form.append('model_id', 'scribe_v1');
- form.append('file', new Blob([readFileSync(clip)], { type: 'audio/mpeg' }), `${l.id}.mp3`);
- const res = await fetch(`${API}/speech-to-text`, { method: 'POST', headers: { 'xi-api-key': key }, body: form });
- if (!res.ok) die(`${l.id}: speech-to-text ${res.status} ${(await res.text()).slice(0, 300)}`);
- const body = await res.json();
- const words = (body.words || []).filter((w) => w.type === 'word' || !w.type).map((w) => ({ word: w.text, start: w.start, end: w.end }));
- writeFileSync(join('voice/timing', `${l.id}.json`), JSON.stringify({ id: l.id, heard: body.text, words }, null, 2));
- const said = norm(body.text), meant = norm(l.text);
- console.log(`${l.id}: ${words.length} words${said === meant ? '' : ` ⚠ heard "${body.text}"`}`);
+async function pool(items, n, fn) {
+ const out = new Array(items.length);
+ let next = 0;
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, async () => {
+ while (next < items.length) { const k = next++; out[k] = await fn(items[k], k); }
+ }));
+ return out;
+}
+
+function keep(l, take, rep) {
+ mkdirSync(join(OUT, 'clips'), { recursive: true });
+ for (const ext of ['.mp3', '.wav', '.flac', '.opus']) rmSync(join(OUT, 'clips', `${l.id}${ext}`), { force: true });
+ copyFileSync(take, join(OUT, 'clips', `${l.id}${extname(take)}`));
+ writeFileSync(join(OUT, 'clips', `${l.id}.json`), JSON.stringify(rep, null, 2));
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// ElevenLabs
+
+async function elevenlabs() {
+ const key = process.env.ELEVENLABS_API_KEY;
+ if (!key) die('ELEVENLABS_API_KEY is not set: the studio\'s voice is ElevenLabs but no key reached this session. mfx needs-you');
+ const el = await lib('elevenlabs.mjs');
+ const cfg = { ...el.DEFAULTS, ...(voice.elevenlabs || {}) };
+ const base = el.SERVERS[cfg.server] || el.SERVERS.default;
+ const api = async (path, init = {}) => {
+ const res = await fetch(new URL(path, base), { ...init, headers: { 'xi-api-key': key, ...(init.headers || {}) } });
+ if (!res.ok) throw new Error(`ElevenLabs ${res.status} ${(await res.text()).slice(0, 300)}`);
+ return res;
+ };
+ return { el, cfg, api };
+}
+
+async function listenEleven({ api, cfg }, path, l) {
+ const form = new FormData();
+ form.append('model_id', cfg.check_model || 'scribe_v2');
+ form.append('timestamps_granularity', 'word');
+ form.append('tag_audio_events', 'true');
+ if (cfg.language_code) form.append('language_code', cfg.language_code);
+ // Names and unusual words from the line help the transcriber spell what it hears.
+ for (const k of [...new Set(heard(l).match(/\b[A-Z][\p{L}\p{N}'-]{2,}\b/gu) || [])].slice(0, 50)) form.append('keyterms', k);
+ form.append('file', new Blob([readFileSync(path)]), `take${extname(path)}`);
+ const body = await (await api('/v1/speech-to-text', { method: 'POST', body: form })).json();
+ const all = body.words || [];
+ return {
+ engine: `elevenlabs/${cfg.check_model || 'scribe_v2'}`,
+ text: body.text || '',
+ words: all.filter((w) => w.type === 'word').map((w) => ({ text: w.text, start: w.start, end: w.end })),
+ events: all.filter((w) => w.type === 'audio_event').map((w) => w.text),
+ };
+}
+
+async function speakEleven(list) {
+ const ctx = await elevenlabs();
+ const { el, cfg, api } = ctx;
+ if (!cfg.voice_id) die('no ElevenLabs voice chosen: pick one in the studio\'s Settings (or `mortiflix voice`), then run again. mfx needs-you');
+ const maxTakes = Number(opt('max-takes', 3));
+ const all = JSON.parse(readFileSync(file, 'utf8'));
+ const fmt = cfg.output_format || 'mp3_44100_128';
+ const ext = fmt.startsWith('wav') ? '.wav' : fmt.startsWith('opus') ? '.opus' : fmt.startsWith('pcm') ? '.pcm' : '.mp3';
+ if (ext === '.pcm') die('pcm output has no container; choose WAV in Settings for narration');
+ // Parallel lines: the plan's concurrency (saved when the key was connected) minus one, so the studio's own checks fit.
+ const jobs = Number(opt('jobs', 0)) || Math.max(1, (el.CONCURRENCY[String(cfg.tier || '').replace(/_.*/, '')] ?? 3) - 1);
+ mkdirSync(join(OUT, 'takes'), { recursive: true });
+ const report = {};
+ await pool(list, jobs, async (l) => {
+ const k = all.findIndex((x) => x.id === l.id);
+ for (let n = 1; n <= maxTakes; n++) {
+ const seed = Math.floor(Math.random() * 4294967295);
+ const body = el.requestBody(cfg, l.text, { previous_text: k > 0 ? all[k - 1].text : undefined, next_text: k < all.length - 1 ? all[k + 1].text : undefined, seed });
+ let res;
+ try {
+ res = await api(`/v1/text-to-speech/${encodeURIComponent(cfg.voice_id)}?output_format=${fmt}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ } catch (e) { report[l.id] = { pass: false, problems: [e.message] }; if (/40[13]|quota|credits/i.test(e.message)) break; continue; }
+ const take = join(OUT, 'takes', `${l.id}-t${n}${ext}`);
+ writeFileSync(take, Buffer.from(await res.arrayBuffer()));
+ let t = null, verdict = { pass: true, compare: null, problems: [] };
+ if (cfg.check_model !== 'off') {
+ try { t = await listenEleven(ctx, take, l); verdict = judge(l, t); } catch (e) { verdict = { pass: true, compare: null, problems: [], note: `not checked: ${e.message}` }; }
+ }
+ const rep = { id: l.id, engine: `elevenlabs/${cfg.model_id}`, voice: cfg.voice_name || cfg.voice_id, take: n, seed, request_id: res.headers.get('request-id'), seconds: duration(take), ...verdict, words: t?.words || [], transcript: t?.text ?? null };
+ report[l.id] = rep;
+ const best = report[`${l.id}:best`];
+ if (verdict.pass || !best || (verdict.compare?.similarity ?? 0) > (best.compare?.similarity ?? 0)) { keep(l, take, rep); report[`${l.id}:best`] = rep; }
+ console.log(`${l.id} take ${n}: ${verdict.pass ? 'ok' : verdict.problems.join('; ')}${verdict.note ? ` (${verdict.note})` : ''}`);
+ if (verdict.pass) break;
+ }
+ });
+ finish(list, report);
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Qwen3-TTS through ComfyUI, on this machine's GPU
+
+async function speakQwen(list) {
+ const q = await lib('qwen.mjs');
+ const cfg = { ...q.DEFAULTS, ...(voice.qwen || {}) };
+ const comfy = new q.ComfyUI({ url: cfg.url });
+ const st = await comfy.status();
+ if (!st.ok) die(`${st.reason} mfx needs-you`);
+ cfg.variant = q.ComfyUI.variant(st.models, cfg.model);
+ if (!st.voices.includes(cfg.voice)) die(`voice ${cfg.voice} isn't offered by this model (${st.voices.join(', ')})`);
+ const maxTakes = Number(opt('max-takes', 3));
+ mkdirSync(join(OUT, 'takes'), { recursive: true });
+ const report = {};
+ let todo = list;
+ for (let n = 1; n <= maxTakes && todo.length; n++) {
+ // Speak everything, then free the GPU, then listen to everything: the two models take turns on the card.
+ const made = [];
+ for (const l of todo) {
+ const seed = n === 1 ? 1 : Math.floor(Math.random() * 2 ** 31);
+ try {
+ const out = await comfy.run(q.speakGraph(cfg, heard(l).trim(), seed));
+ const f = out['3'].audio[0];
+ const raw = join(OUT, 'takes', `${l.id}-t${n}.${f.filename.split('.').pop()}`);
+ writeFileSync(raw, await comfy.file(f));
+ const take = join(OUT, 'takes', `${l.id}-t${n}.wav`);
+ run(['ffmpeg', '-y', '-loglevel', 'error', '-i', raw, '-ar', '48000', '-ac', '1', take]);
+ if (raw !== take) rmSync(raw, { force: true });
+ made.push({ l, take, seed });
+ console.log(`${l.id} take ${n}: spoken`);
+ } catch (e) { report[l.id] = { pass: false, problems: [e.message] }; console.log(`${l.id} take ${n}: ${e.message}`); }
+ }
+ await comfy.free();
+ const failed = [];
+ for (const { l, take, seed } of made) {
+ let t = null, verdict = { pass: true, compare: null, problems: [] };
+ if (cfg.check && st.can_listen) {
+ try { t = await listenQwen(comfy, q, cfg, take, `${l.id}-t${n}`); verdict = judge(l, t); } catch (e) { verdict = { pass: true, compare: null, problems: [], note: `not checked: ${e.message}` }; }
+ }
+ const rep = { id: l.id, engine: `qwen3-tts/${cfg.variant} (local)`, voice: cfg.voice, take: n, seed, seconds: duration(take), ...verdict, words: t?.words || [], transcript: t?.text ?? null };
+ const best = report[`${l.id}:best`];
+ if (verdict.pass || !best || (verdict.compare?.similarity ?? 0) > (best.compare?.similarity ?? 0)) { keep(l, take, rep); report[`${l.id}:best`] = rep; }
+ report[l.id] = rep;
+ console.log(`${l.id} take ${n}: ${verdict.pass ? 'ok' : verdict.problems.join('; ')}${verdict.note ? ` (${verdict.note})` : ''}`);
+ if (!verdict.pass) failed.push(l);
+ }
+ await comfy.free();
+ todo = failed;
}
+ finish(list, report);
+}
+
+async function listenQwen(comfy, q, cfg, path, name) {
+ const form = new FormData();
+ form.append('image', new Blob([readFileSync(path)]), `${name}.wav`);
+ form.append('subfolder', 'mortiflix');
+ form.append('type', 'input');
+ const res = await fetch(`${comfy.url}/upload/image`, { method: 'POST', body: form });
+ if (!res.ok) throw new Error(`upload ${res.status}`);
+ const up = await res.json();
+ const out = await comfy.run(q.listenGraph(cfg, up.subfolder ? `${up.subfolder}/${up.name}` : up.name));
+ const d = JSON.parse(out['4'].text[0]);
+ return { engine: `qwen3-asr/${cfg.asr_model} (local)`, text: d.text || '', words: (d.segments || []).flatMap((s) => s.words || []).map((w) => ({ text: w.text, start: Number(w.start), end: Number(w.end) })), events: [] };
+}
+
+function finish(list, report) {
+ const lines_ = list.map((l) => report[`${l.id}:best`] || report[l.id] || { id: l.id, pass: false });
+ writeFileSync(join(OUT, 'speak-report.json'), JSON.stringify(lines_, null, 2));
+ const bad = lines_.filter((r) => !r.pass);
+ console.log(`\n${list.length - bad.length}/${list.length} lines passed${bad.length ? `; failing: ${bad.map((r) => r.id).join(', ')} (see voice/speak-report.json: fix the text, then --only those)` : ''}`);
+ if (bad.length) process.exitCode = 1;
}
-const norm = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9 ]+/g, '').replace(/\s+/g, ' ').trim();
+// ---------------------------------------------------------------------------------------------------------------
+// build: one track with gaps, and where every line and word lands in it
function build() {
const list = lines();
const defaultGap = Number(opt('gap', 0.4));
- mkdirSync('voice/build', { recursive: true });
+ mkdirSync(join(OUT, 'build'), { recursive: true });
const parts = [];
const timing = [];
let t = 0;
for (const l of list) {
- const clip = [join('voice/clips', `${l.id}.mp3`), join('voice/clips', `${l.id}.wav`)].find(existsSync);
- if (!clip) die(`no clip for ${l.id}`);
- const wav = join('voice/build', `${l.id}.wav`);
+ const clip = ['.wav', '.mp3', '.flac', '.opus'].map((e) => join(OUT, 'clips', `${l.id}${e}`)).find(existsSync);
+ if (!clip) die(`no clip for ${l.id}: speak it first`);
+ const wav = join(OUT, 'build', `${l.id}.wav`);
run(['ffmpeg', '-y', '-loglevel', 'error', '-i', clip, '-ar', '48000', '-ac', '1', wav]);
const d = duration(wav);
- const words = existsSync(join('voice/timing', `${l.id}.json`))
- ? JSON.parse(readFileSync(join('voice/timing', `${l.id}.json`), 'utf8')).words.map((w) => ({ ...w, start: r3(t + w.start), end: r3(t + w.end) }))
- : [];
- timing.push({ id: l.id, text: l.text, start: r3(t), end: r3(t + d), words });
+ const meta = existsSync(join(OUT, 'clips', `${l.id}.json`)) ? JSON.parse(readFileSync(join(OUT, 'clips', `${l.id}.json`), 'utf8')) : {};
+ const ws = (meta.words || []).map((w) => ({ text: w.text, start: r3(t + w.start), end: r3(t + w.end) }));
+ timing.push({ id: l.id, text: heard(l).replace(/\s+/g, ' ').trim(), start: r3(t), end: r3(t + d), words: ws, timing: ws.length ? 'words' : 'line' });
parts.push(wav);
t += d;
const gap = l.gap_after ?? defaultGap;
if (gap > 0) {
- const sil = join('voice/build', `gap-${l.id}.wav`);
- run(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'lavfi', '-i', `anullsrc=r=48000:cl=mono`, '-t', String(gap), sil]);
+ const sil = join(OUT, 'build', `gap-${l.id}.wav`);
+ run(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=mono', '-t', String(gap), sil]);
parts.push(sil);
t += gap;
}
}
- writeFileSync('voice/build/list.txt', parts.map((p) => `file '${p.replace(/^voice\/build\//, '')}'`).join('\n') + '\n');
- run(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', 'voice/build/list.txt', '-c', 'pcm_s16le', 'voice/voice.wav']);
- writeFileSync('voice/timing.json', JSON.stringify({ seconds: r3(t), lines: timing }, null, 2));
+ writeFileSync(join(OUT, 'build', 'list.txt'), parts.map((p) => `file '${p.replace(/^voice\/build\//, '')}'`).join('\n') + '\n');
+ run(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', join(OUT, 'build', 'list.txt'), '-c', 'pcm_s16le', join(OUT, 'voice.wav')]);
+ writeFileSync(join(OUT, 'timing.json'), JSON.stringify({ seconds: r3(t), lines: timing }, null, 2));
console.log(`voice/voice.wav: ${t.toFixed(2)} s, ${timing.length} lines → voice/timing.json`);
}
-function run(argv) {
- const r = spawnSync(argv[0], argv.slice(1), { encoding: 'utf8' });
- if (r.status !== 0) die(`${argv[0]} failed: ${r.stderr.slice(-400)}`);
-}
-
const r3 = (v) => Math.round(v * 1000) / 1000;
-if (cmd === 'check') console.log(key ? 'ElevenLabs: key present' : 'No voice service: ELEVENLABS_API_KEY is not set');
-else if (cmd === 'speak') await speak();
-else if (cmd === 'time') await time();
-else if (cmd === 'build') build();
-else die('usage: vo.mjs check | speak <lines.json> | time <lines.json> | build <lines.json>');
+// ---------------------------------------------------------------------------------------------------------------
+
+async function check() {
+ if (engine === 'elevenlabs') {
+ const { el, cfg, api } = await elevenlabs();
+ const s = await (await api('/v1/user/subscription')).json();
+ const tier = String(s.tier || 'free');
+ console.log(JSON.stringify({
+ engine, model: cfg.model_id, voice: cfg.voice_name || cfg.voice_id, settings: el.voiceSettings(cfg),
+ plan: tier, characters_left: Math.max(0, s.character_limit - s.character_count),
+ commercial_use: !tier.startsWith('free') ? true : 'NO: free plan audio is non-commercial and needs attribution',
+ parallel_lines: Math.max(1, (el.CONCURRENCY[tier.replace(/_.*/, '')] ?? 3) - 1),
+ sound_effects: cfg.sfx !== false, music: Boolean(cfg.music),
+ v4_rules: el.isV4(cfg.model_id) ? 'audio tags in [brackets], IPA as "/.../", CAPITALS for emphasis, no SSML, only stability + similarity' : null,
+ }, null, 2));
+ } else if (engine === 'qwen') {
+ const q = await lib('qwen.mjs');
+ const cfg = { ...q.DEFAULTS, ...(voice.qwen || {}) };
+ const st = await new q.ComfyUI({ url: cfg.url }).status();
+ console.log(JSON.stringify({ engine, ...st, chosen: { model: cfg.model, voice: cfg.voice, language: cfg.language, instruct: /1\.7B/.test(cfg.model) ? cfg.instruct : '(the 0.6B model takes no instructions)' }, notes: 'tags and IPA are not read: write delivery into the instruction and spell names the way they sound' }, null, 2));
+ if (!st.ok) process.exitCode = 1;
+ } else {
+ console.log(JSON.stringify({ engine: 'none', note: 'No voice is set up in this studio. Make the video with on-screen text, or ask the owner (mfx ask) whether to wait for a voice.' }, null, 2));
+ }
+}
+
+if (cmd === 'check') await check();
+else if (cmd === 'speak') {
+ const list = lines();
+ if (engine === 'elevenlabs') await speakEleven(list);
+ else if (engine === 'qwen') await speakQwen(list);
+ else die('no voice is set up in this studio (vo.mjs check)');
+} else if (cmd === 'build') build();
+else die('usage: vo.mjs check | speak <lines.json> [--only ids] [--max-takes 3] [--jobs N] | build <lines.json> [--gap 0.4]');
diff --git a/pipelines/explainer/pipeline.json b/pipelines/explainer/pipeline.json
index 608ecd0..0e7f59b 100644
--- a/pipelines/explainer/pipeline.json
+++ b/pipelines/explainer/pipeline.json
@@ -54,7 +54,7 @@
"On-screen text and music only"
],
"default": "Narrated",
- "help": "Narration needs a voice: an ElevenLabs key in the studio's session.env, or a local TTS. Without one, the studio asks."
+ "help": "Uses the studio's narration voice (Settings › Narration: ElevenLabs, or Qwen3-TTS on your own GPU). With none set up, the studio asks."
},
{
"id": "script",
diff --git a/src/cli.mjs b/src/cli.mjs
index 42fe412..c90a71e 100644
--- a/src/cli.mjs
+++ b/src/cli.mjs
@@ -8,6 +8,7 @@ import { listPipelines, findPipeline } from './pipelines.mjs';
import { createProject, addIntakeFile, startProject, listProjects, loadProject, projectPaths, projectPipeline, readEvents } from './projects.mjs';
import * as gates from './gates.mjs';
import { Runner, BACKENDS } from './runner.mjs';
+import * as voice from './voice/index.mjs';
const C = process.stdout.isTTY && !process.env.NO_COLOR
? { b: (s) => `\x1b[1m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m`, acc: (s) => `\x1b[38;5;208m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m` }
@@ -32,6 +33,13 @@ const HELP = `${C.b('mortiflix')}: a motion design studio on your machine. Claud
${C.b('The web studio')}
mortiflix serve [--port 4646] [--host 127.0.0.1] the studio in your browser, with the runner
+ ${C.b('Narration')}
+ mortiflix voice what narrates your videos, and what this machine can run
+ mortiflix voice elevenlabs set up ElevenLabs (key, voice, model)
+ mortiflix voice local set up Qwen3-TTS on your GPU through ComfyUI
+ mortiflix voice none no narration (on-screen text and music)
+ mortiflix voice test ["a line to speak"] hear the current voice
+
${C.b('Settings')}
mortiflix config [key [value]] show or change settings
mortiflix config api-key store an Anthropic API key (asked, not echoed)
@@ -73,6 +81,7 @@ export async function run(argv = process.argv.slice(2)) {
case 'serve': return serve(root, a);
case 'config': return config(root, rest);
case 'checks': return checks(root, rest);
+ case 'voice': return voiceCmd(root, rest);
case undefined: case 'help': return console.log(HELP);
default: throw new Error(`unknown command "${cmd}" (mortiflix help)`);
}
@@ -140,6 +149,7 @@ function init(root, a) {
console.log(`${C.green('✔')} Studio ready at ${C.b(root)}`);
console.log(` Backend: ${C.b(backend)} ${C.dim(BACKENDS[backend].available(loadConfig(root), root).detail)}`);
if (backend === 'demo') console.log(C.dim(' (No Claude Code login or API key found: the demo backend makes placeholder work. Install Claude Code, or `mortiflix config api-key`.)'));
+ console.log(`\n ${C.b('Narration')} (optional): ${voiceOffer()}`);
console.log(`\n Next: ${C.b('mortiflix demo')} for a free walk-through, or ${C.b('mortiflix serve')} to open the studio in your browser.`);
}
@@ -413,6 +423,102 @@ function checks(root, [action, id]) {
if (!all.active.length) console.log(C.dim(' none yet'));
}
+// The narration offer: ElevenLabs always; the local voice when this machine's graphics card can run it.
+function voiceOffer() {
+ const rec = voice.qwen.recommend(voice.qwen.detectGpus());
+ const eleven = `${C.b('mortiflix voice elevenlabs')} for ElevenLabs voices (a key from elevenlabs.io)`;
+ return rec.fits ? `${eleven}, or ${C.b('mortiflix voice local')}: ${rec.reason} Free and private, through ComfyUI.` : `${eleven}.`;
+}
+
+async function voiceCmd(root, [sub, ...words]) {
+ needStudio(root);
+ const v = voice.voiceConfig(root);
+ if (!sub) {
+ const o = voice.voiceOverview(root);
+ console.log(`Narration: ${C.b({ none: 'none', elevenlabs: 'ElevenLabs', qwen: 'Qwen3-TTS on this computer' }[o.engine])}`);
+ if (o.engine === 'elevenlabs') console.log(` voice ${o.elevenlabs.voice_name || C.red('not chosen')} · model ${o.elevenlabs.model_id} · key ${o.elevenlabs_key || C.red('missing')}`);
+ if (o.engine === 'qwen') console.log(` ${o.qwen.voice} · ${o.qwen.model} · ${o.qwen.language} · ComfyUI ${o.qwen.url}`);
+ console.log(`\nThis machine: ${o.gpus.length ? o.gpus.map((g) => `${g.name} (${g.vram_gb} GB)`).join(', ') : 'no NVIDIA GPU found'}`);
+ console.log(` ${o.local.reason}`);
+ console.log(`\nOptions: ${voiceOffer()}`);
+ return;
+ }
+ if (sub === 'none') { voice.saveVoice(root, { engine: 'none' }); return console.log('Narration off: videos use on-screen text, music and sound.'); }
+ if (sub === 'test') return voiceTest(root, words.join(' '));
+ const rl = prompter();
+ try {
+ if (sub === 'elevenlabs') {
+ if (!voice.elevenKey(root)) {
+ rl.close();
+ const key = (await hiddenPrompt('ElevenLabs API key (elevenlabs.io › Developers › API keys): ')).trim();
+ if (!key) throw new Error('no key given');
+ voice.setElevenKey(root, key);
+ return voiceCmd(root, ['elevenlabs']);
+ }
+ const el = new voice.eleven.ElevenLabs({ key: voice.elevenKey(root), server: v.elevenlabs.server });
+ const a = await el.account();
+ voice.saveVoice(root, { engine: 'elevenlabs', elevenlabs: { tier: a.tier } });
+ console.log(`${C.green('✔')} ${a.tier} plan · ${a.characters_left.toLocaleString()} credits left${a.commercial_use ? ' · commercial use' : C.red(' · free plan: non-commercial, credit ElevenLabs')}`);
+ const search = (await rl.question(`Find a voice (e.g. "warm narrator", blank for all)${v.elevenlabs.voice_name ? C.dim(` [keep ${v.elevenlabs.voice_name}]`) : ''}: `)).trim();
+ if (search || !v.elevenlabs.voice_id) {
+ let { voices: list } = await el.voices({ search, page_size: 15 });
+ let fromLibrary = false;
+ if (!list.length) { list = (await el.library({ search, page_size: 15 })).voices; fromLibrary = true; }
+ if (!list.length) throw new Error('no voices match');
+ list.forEach((x, i) => console.log(` ${String(i + 1).padStart(2)}. ${C.b(x.name)} ${C.dim(Object.values(x.labels || {}).filter(Boolean).join(' · '))}${fromLibrary ? C.dim(' (Voice Library)') : ''}`));
+ const pick = list[Number((await rl.question('Number: ')).trim()) - 1];
+ if (!pick) throw new Error('no voice picked');
+ const id = fromLibrary ? (await el.addFromLibrary(pick.owner, pick.id, pick.name)).id : pick.id;
+ voice.saveVoice(root, { elevenlabs: { voice_id: id, voice_name: pick.name } });
+ }
+ const models = await el.models();
+ console.log(`Model: ${models.map((m, i) => `${i + 1}. ${m.id}${m.recommended ? C.dim(' (recommended)') : ''}`).join(' ')}`);
+ const m = models[Number((await rl.question(`Number ${C.dim(`[${v.elevenlabs.model_id}]`)}: `)).trim()) - 1];
+ if (m) voice.saveVoice(root, { elevenlabs: { model_id: m.id } });
+ const now = voice.voiceConfig(root).elevenlabs;
+ console.log(`${C.green('✔')} ElevenLabs: ${now.voice_name} on ${now.model_id}. Every other option (stability, format, dictionaries, sound effects, music) is in the web studio's Settings.`);
+ console.log(` Hear it: ${C.b('mortiflix voice test')}`);
+ return;
+ }
+ if (sub === 'local') {
+ const rec = voice.qwen.recommend(voice.qwen.detectGpus());
+ console.log(rec.fits ? `${C.green('✔')} ${rec.reason}` : C.red(rec.reason));
+ const url = (await rl.question(`ComfyUI address ${C.dim(`[${v.qwen.url}]`)}: `)).trim() || v.qwen.url;
+ const st = await new voice.qwen.ComfyUI({ url }).status();
+ if (!st.ok) {
+ console.log(C.red(st.reason));
+ console.log(' 1. Install ComfyUI: https://www.comfy.org/download (it listens on http://127.0.0.1:8188)');
+ console.log(' 2. In ComfyUI Manager install "TTS Audio Suite" (github.com/diodiogod/TTS-Audio-Suite), restart ComfyUI');
+ console.log(` 3. Run ${C.b('mortiflix voice local')} again. The Qwen3-TTS models (Apache-2.0) download on first use, about 4 GB.`);
+ voice.saveVoice(root, { qwen: { url } });
+ return;
+ }
+ console.log(`${C.green('✔')} ComfyUI ${st.comfyui || ''} with the TTS Audio Suite · ${st.gpu} · ${st.vram_free_gb} GB free`);
+ st.voices.forEach((name, i) => { const p = voice.qwen.PRESETS.find((x) => x.id === name); console.log(` ${i + 1}. ${C.b(name)} ${C.dim(p ? `${p.language}: ${p.about}` : '')}`); });
+ const name = st.voices[Number((await rl.question(`Voice ${C.dim(`[${v.qwen.voice}]`)}: `)).trim()) - 1] || v.qwen.voice;
+ voice.saveVoice(root, { engine: 'qwen', qwen: { url, voice: name, model: rec.model || v.qwen.model } });
+ console.log(`${C.green('✔')} Local narration: ${name} on Qwen3-TTS ${rec.model || v.qwen.model}. Hear it: ${C.b('mortiflix voice test')}`);
+ return;
+ }
+ throw new Error('mortiflix voice [elevenlabs|local|none|test]');
+ } finally {
+ rl.close();
+ }
+}
+
+async function voiceTest(root, text) {
+ const v = voice.voiceConfig(root);
+ const line = text || 'Every city has a heartbeat. Ours runs on bikes.';
+ let out;
+ if (v.engine === 'elevenlabs') out = { ...(await new voice.eleven.ElevenLabs({ key: voice.elevenKey(root), server: v.elevenlabs.server }).sample(v.elevenlabs, line)), format: 'mp3' };
+ else if (v.engine === 'qwen') out = await new voice.qwen.ComfyUI({ url: v.qwen.url }).sample(v.qwen, line);
+ else throw new Error('no narration engine set up (mortiflix voice elevenlabs | local)');
+ const file = join(paths(root).run, `voice-test.${out.format}`);
+ writeFileSync(file, out.audio);
+ console.log(`${C.green('✔')} ${file}`);
+ if (spawnSync('ffplay', ['-version']).status === 0) spawnSync('ffplay', ['-nodisp', '-autoexit', '-loglevel', 'error', file], { stdio: 'inherit' });
+}
+
// The walk-through: a logo sting made by the demo backend, so the whole loop can be tried for free.
async function demo(root) {
if (!existsSync(paths(root).config)) init(root, {});
diff --git a/src/runner.mjs b/src/runner.mjs
index 611ddf7..fdfe432 100644
--- a/src/runner.mjs
+++ b/src/runner.mjs
@@ -3,7 +3,8 @@
import { EventEmitter } from 'node:events';
import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, appendFileSync } from 'node:fs';
import { join } from 'node:path';
-import { paths, loadConfig, readSessionEnv } from './studio.mjs';
+import { REPO, paths, loadConfig, readSessionEnv } from './studio.mjs';
+import { sessionVoiceEnv } from './voice/index.mjs';
import { listProjects, loadProject, projectPaths, projectPipeline, update, event, readEvents, now } from './projects.mjs';
import { settle } from './gates.mjs';
import { prepareWorkdir, writeTorch, sessionReason } from './torch.mjs';
@@ -122,7 +123,8 @@ export class Runner extends EventEmitter {
prepareWorkdir(root, projectId);
mkdirSync(join(paths(root).run, 'shared'), { recursive: true });
writeTorch(root, projectId, { backend: config.backend, reason });
- const sessionEnv = readSessionEnv(root);
+ // Keys and settings for the session: session.env, then the studio's voice (its key only if it narrates with it).
+ const sessionEnv = { ...readSessionEnv(root), ...sessionVoiceEnv(root), MFX_HOME: REPO };
bridge = await openBridge({ root, projectId, sessionId, workdir: pp.work, renders: this.renders, sessionEnv });
this.addActivity(projectId, { kind: 'info', text: `Session started (${config.backend}). ${reason}` });
result = await backend.run({
diff --git a/src/voice/elevenlabs.mjs b/src/voice/elevenlabs.mjs
new file mode 100644
index 0000000..404e693
--- /dev/null
+++ b/src/voice/elevenlabs.mjs
@@ -0,0 +1,217 @@
+// ElevenLabs, for setting a studio up (the account, models, voices, the Voice Library, a test line). Sessions make
+// their narration with the voiceover skill's vo.mjs; this module is what Settings and `mortiflix voice` use.
+// Reference: https://elevenlabs.io/docs (models, voices, text to speech, user/subscription), checked Oct 2026.
+
+export const SERVERS = {
+ default: 'https://api.elevenlabs.io',
+ us: 'https://api.us.elevenlabs.io',
+ eu: 'https://api.eu.residency.elevenlabs.io',
+ in: 'https://api.in.residency.elevenlabs.io',
+ sg: 'https://api.sg.residency.elevenlabs.io',
+};
+
+// What each output format needs (from the API reference): 192 kbps MP3 needs Creator or above, 44.1 kHz PCM/WAV Pro.
+export const OUTPUT_FORMATS = [
+ { id: 'mp3_44100_128', label: 'MP3 44.1 kHz 128 kbps', tier: null, note: 'default' },
+ { id: 'mp3_44100_192', label: 'MP3 44.1 kHz 192 kbps', tier: 'creator' },
+ { id: 'wav_44100', label: 'WAV 44.1 kHz', tier: 'pro' },
+ { id: 'pcm_44100', label: 'PCM 44.1 kHz (raw)', tier: 'pro' },
+ { id: 'wav_48000', label: 'WAV 48 kHz', tier: 'pro' },
+ { id: 'wav_24000', label: 'WAV 24 kHz', tier: null },
+ { id: 'opus_48000_128', label: 'Opus 48 kHz 128 kbps', tier: null },
+];
+
+const TIER_ORDER = ['free', 'starter', 'creator', 'pro', 'scale', 'business', 'enterprise'];
+export const tierAtLeast = (tier, need) => !need || TIER_ORDER.indexOf(String(tier || 'free').toLowerCase().replace(/_.*/, '')) >= TIER_ORDER.indexOf(need);
+
+// Concurrent requests per plan for the standard models (docs: Models > Concurrency and priority).
+export const CONCURRENCY = { free: 2, starter: 3, creator: 5, pro: 10, scale: 15, business: 15 };
+
+// Eleven v4 (and v4 Turbo) take only stability and similarity: no style, no speed, no SSML (docs: Eleven v4).
+export const isV4 = (modelId) => /^eleven_v4/.test(modelId || '');
+
+export const DEFAULTS = {
+ model_id: 'eleven_v4',
+ voice_id: null,
+ voice_name: null,
+ stability: 0.5,
+ similarity_boost: 0.75,
+ style: 0,
+ speed: 1,
+ use_speaker_boost: true,
+ output_format: 'mp3_44100_128',
+ language_code: null,
+ apply_text_normalization: 'auto',
+ pronunciation_dictionaries: [], // up to 3 {id, version_id, name}
+ server: 'default',
+ check_model: 'scribe_v2', // speech to text for checking takes and word timing
+ sfx: true, // sessions may make sound effects (eleven_text_to_sound_v2)
+ music: false, // sessions may compose music beds (Eleven Music)
+};
+
+// The voice settings a model actually uses.
+export function voiceSettings(cfg, model) {
+ const s = { stability: num(cfg.stability, 0.5), similarity_boost: num(cfg.similarity_boost, 0.75) };
+ if (isV4(cfg.model_id)) return s;
+ if (!model || model.can_use_style !== false) s.style = num(cfg.style, 0);
+ if (!model || model.can_use_speaker_boost !== false) s.use_speaker_boost = cfg.use_speaker_boost !== false;
+ s.speed = Math.min(1.2, Math.max(0.7, num(cfg.speed, 1)));
+ return s;
+}
+
+const num = (v, d) => (Number.isFinite(Number(v)) ? Number(v) : d);
+
+export class ElevenLabs {
+ constructor({ key, server = 'default', fetch = globalThis.fetch }) {
+ if (!key) throw new Error('no ElevenLabs API key');
+ this.key = key;
+ this.base = SERVERS[server] || SERVERS.default;
+ this.fetch = fetch;
+ }
+
+ async call(path, { method = 'GET', body, query, raw = false } = {}) {
+ const url = new URL(path, this.base);
+ for (const [k, v] of Object.entries(query || {})) {
+ if (v === undefined || v === null || v === '') continue;
+ if (Array.isArray(v)) for (const x of v) url.searchParams.append(k, x); else url.searchParams.set(k, String(v));
+ }
+ const res = await this.fetch(url, {
+ method,
+ headers: { 'xi-api-key': this.key, ...(body ? { 'content-type': 'application/json' } : {}) },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ let detail = text;
+ try { const j = JSON.parse(text); detail = j.detail?.message || j.detail?.[0]?.msg || j.detail || text; } catch { /* plain text */ }
+ const err = new Error(`ElevenLabs ${res.status}: ${String(typeof detail === 'string' ? detail : JSON.stringify(detail)).slice(0, 300)}`);
+ err.status = res.status;
+ throw err;
+ }
+ if (raw) return res;
+ return res.json();
+ }
+
+ // The plan, credits and what it allows. Free-plan audio may only be used non-commercially, with attribution.
+ async account() {
+ const s = await this.call('/v1/user/subscription');
+ const tier = String(s.tier || 'free').toLowerCase();
+ return {
+ tier,
+ status: s.status,
+ characters_used: s.character_count,
+ character_limit: s.character_limit,
+ characters_left: Math.max(0, (s.character_limit || 0) - (s.character_count || 0)),
+ resets_at: s.next_character_count_reset_unix ? new Date(s.next_character_count_reset_unix * 1000).toISOString() : null,
+ commercial_use: !tier.startsWith('free'),
+ instant_cloning: Boolean(s.can_use_instant_voice_cloning),
+ professional_cloning: Boolean(s.can_use_professional_voice_cloning),
+ voice_slots: { used: s.voice_slots_used, limit: s.voice_limit },
+ concurrency: CONCURRENCY[tier.replace(/_.*/, '')] ?? null,
+ };
+ }
+
+ // Text-to-speech models, newest recommendation first.
+ async models() {
+ const list = await this.call('/v1/models');
+ const tts = list.filter((m) => m.can_do_text_to_speech);
+ const rank = (id) => ['eleven_v4', 'eleven_multilingual_v2', 'eleven_v3', 'eleven_v4_turbo', 'eleven_flash_v2_5', 'eleven_flash_v2'].indexOf(id);
+ return tts
+ .map((m) => ({
+ id: m.model_id,
+ name: m.name,
+ description: m.description,
+ languages: (m.languages || []).length,
+ max_characters: m.maximum_text_length_per_request ?? null,
+ can_use_style: isV4(m.model_id) ? false : m.can_use_style !== false,
+ can_use_speaker_boost: isV4(m.model_id) ? false : m.can_use_speaker_boost !== false,
+ recommended: m.model_id === 'eleven_v4',
+ alpha: Boolean(m.requires_alpha_access),
+ }))
+ .sort((a, b) => (rank(a.id) < 0 ? 99 : rank(a.id)) - (rank(b.id) < 0 ? 99 : rank(b.id)));
+ }
+
+ // Voices in the account (the default voices included): GET /v2/voices.
+ async voices({ search, page_token, page_size = 50 } = {}) {
+ const r = await this.call('/v2/voices', { query: { search, next_page_token: page_token, page_size, include_total_count: true } });
+ return { voices: r.voices.map(voiceCard), next: r.has_more ? r.next_page_token : null, total: r.total_count ?? null };
+ }
+
+ // The public Voice Library: GET /v1/shared-voices.
+ async library({ search, gender, age, accent, language, use_cases, page = 0, page_size = 30 } = {}) {
+ const r = await this.call('/v1/shared-voices', { query: { search, gender, age, accent, language, use_cases, page, page_size } });
+ return {
+ voices: (r.voices || []).map((v) => ({
+ id: v.voice_id,
+ owner: v.public_owner_id,
+ name: v.name,
+ description: v.description,
+ labels: { gender: v.gender, age: v.age, accent: v.accent, language: v.language, use_case: v.use_case, descriptive: v.descriptive },
+ preview_url: v.preview_url,
+ free_users_allowed: v.free_users_allowed,
+ })),
+ more: Boolean(r.has_more),
+ };
+ }
+
+ // Copy a Voice Library voice into the account so it can be used: POST /v1/voices/add/{owner}/{voice}.
+ async addFromLibrary(owner, voiceId, name) {
+ const r = await this.call(`/v1/voices/add/${encodeURIComponent(owner)}/${encodeURIComponent(voiceId)}`, { method: 'POST', body: { new_name: name } });
+ return { id: r.voice_id };
+ }
+
+ async dictionaries() {
+ const r = await this.call('/v1/pronunciation-dictionaries', { query: { page_size: 100 } });
+ return (r.pronunciation_dictionaries || []).map((d) => ({ id: d.id, version_id: d.latest_version_id, name: d.name, description: d.description }));
+ }
+
+ // One line in the chosen voice and settings, for "Try it". Costs credits like any generation.
+ async sample(cfg, text) {
+ const res = await this.call(`/v1/text-to-speech/${encodeURIComponent(cfg.voice_id)}`, {
+ method: 'POST',
+ raw: true,
+ query: { output_format: 'mp3_44100_128' },
+ body: requestBody(cfg, text),
+ });
+ return {
+ audio: Buffer.from(await res.arrayBuffer()),
+ concurrency: Number(res.headers.get('maximum-concurrent-requests')) || null,
+ characters: String(text).length,
+ };
+ }
+}
+
+// The body of a text-to-speech request: only what the chosen model takes.
+export function requestBody(cfg, text, { previous_text, next_text, seed, model } = {}) {
+ const body = { text, model_id: cfg.model_id || DEFAULTS.model_id, voice_settings: voiceSettings(cfg, model) };
+ if (cfg.language_code) body.language_code = cfg.language_code;
+ if (cfg.apply_text_normalization && cfg.apply_text_normalization !== 'auto') body.apply_text_normalization = cfg.apply_text_normalization;
+ const dicts = (cfg.pronunciation_dictionaries || []).slice(0, 3);
+ if (dicts.length) body.pronunciation_dictionary_locators = dicts.map((d) => ({ pronunciation_dictionary_id: d.id, ...(d.version_id ? { version_id: d.version_id } : {}) }));
+ if (previous_text) body.previous_text = previous_text;
+ if (next_text) body.next_text = next_text;
+ if (Number.isInteger(seed)) body.seed = seed;
+ return body;
+}
+
+function voiceCard(v) {
+ return {
+ id: v.voice_id,
+ name: v.name,
+ category: v.category,
+ description: v.description || '',
+ labels: v.labels || {},
+ preview_url: v.preview_url || null,
+ languages: (v.verified_languages || []).map((l) => l.language).filter(Boolean),
+ models: v.high_quality_base_model_ids || [],
+ mine: Boolean(v.is_owner),
+ };
+}
+
+// Voice preview files live on ElevenLabs' storage; the studio fetches them for the page (its CSP allows only itself).
+export function previewAllowed(url) {
+ try {
+ const u = new URL(url);
+ return u.protocol === 'https:' && (u.hostname === 'storage.googleapis.com' || u.hostname.endsWith('.elevenlabs.io') || u.hostname === 'elevenlabs.io');
+ } catch { return false; }
+}
diff --git a/src/voice/index.mjs b/src/voice/index.mjs
new file mode 100644
index 0000000..f39f730
--- /dev/null
+++ b/src/voice/index.mjs
@@ -0,0 +1,83 @@
+// The studio's narration setup: which engine (ElevenLabs, local Qwen3-TTS, or none) and its settings. The settings
+// live in config.json under `voice`; the ElevenLabs key lives in secrets.json and reaches only sessions that use it.
+import { loadConfig, saveConfig, readSecret, writeSecret, readSessionEnv } from '../studio.mjs';
+import * as eleven from './elevenlabs.mjs';
+import * as qwen from './qwen.mjs';
+
+export const ENGINES = ['none', 'elevenlabs', 'qwen'];
+
+export function voiceConfig(root) {
+ const v = loadConfig(root).voice || {};
+ return {
+ engine: ENGINES.includes(v.engine) ? v.engine : 'none',
+ elevenlabs: { ...eleven.DEFAULTS, ...(v.elevenlabs || {}) },
+ qwen: { ...qwen.DEFAULTS, ...(v.qwen || {}) },
+ };
+}
+
+// Merge a change into the voice settings (only known fields, ranges enforced).
+export function saveVoice(root, patch = {}) {
+ const cur = voiceConfig(root);
+ const next = { engine: cur.engine, elevenlabs: { ...cur.elevenlabs }, qwen: { ...cur.qwen } };
+ if (patch.engine !== undefined) {
+ if (!ENGINES.includes(patch.engine)) throw new Error(`voice engine must be one of ${ENGINES.join(', ')}`);
+ next.engine = patch.engine;
+ }
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, Number(v)));
+ for (const [k, v] of Object.entries(patch.elevenlabs || {})) {
+ if (!(k in eleven.DEFAULTS) && k !== 'tier') continue;
+ if (['stability', 'similarity_boost', 'style'].includes(k)) next.elevenlabs[k] = clamp(v, 0, 1);
+ else if (k === 'speed') next.elevenlabs[k] = clamp(v, 0.7, 1.2);
+ else if (k === 'apply_text_normalization') { if (['auto', 'on', 'off'].includes(v)) next.elevenlabs[k] = v; }
+ else if (k === 'output_format') { if (eleven.OUTPUT_FORMATS.some((f) => f.id === v)) next.elevenlabs[k] = v; }
+ else if (k === 'server') { if (v in eleven.SERVERS) next.elevenlabs[k] = v; }
+ else if (k === 'check_model') { if (['scribe_v2', 'off'].includes(v)) next.elevenlabs[k] = v; }
+ else if (k === 'pronunciation_dictionaries') next.elevenlabs[k] = (Array.isArray(v) ? v : []).slice(0, 3).map((d) => ({ id: String(d.id), version_id: d.version_id ? String(d.version_id) : null, name: String(d.name || '') }));
+ else if (['use_speaker_boost', 'sfx', 'music'].includes(k)) next.elevenlabs[k] = Boolean(v);
+ else next.elevenlabs[k] = v === '' ? null : v === null ? null : String(v).slice(0, 200);
+ }
+ for (const [k, v] of Object.entries(patch.qwen || {})) {
+ if (!(k in qwen.DEFAULTS)) continue;
+ if (k === 'check') next.qwen[k] = Boolean(v);
+ else if (k === 'url') { if (/^https?:\/\/[^\s]+$/.test(String(v))) next.qwen[k] = String(v).replace(/\/+$/, ''); }
+ else next.qwen[k] = String(v).slice(0, 1000);
+ }
+ saveConfig(root, { voice: next });
+ return next;
+}
+
+export function elevenKey(root) {
+ return readSecret(root, 'elevenlabs_api_key') || readSessionEnv(root).ELEVENLABS_API_KEY || process.env.ELEVENLABS_API_KEY || null;
+}
+
+export function setElevenKey(root, key) {
+ writeSecret(root, 'elevenlabs_api_key', key ? String(key).trim() : null);
+}
+
+// What a session gets: the settings (never a key) plus the key itself only when the studio narrates with ElevenLabs.
+export function sessionVoiceEnv(root) {
+ const v = voiceConfig(root);
+ const env = { MFX_VOICE: JSON.stringify(v) };
+ if (v.engine === 'elevenlabs') {
+ const key = elevenKey(root);
+ if (key) env.ELEVENLABS_API_KEY = key;
+ }
+ return env;
+}
+
+// Everything the setup screens show. Network calls are optional (`live`): the page asks for them separately.
+export function voiceOverview(root) {
+ const v = voiceConfig(root);
+ const gpus = qwen.detectGpus();
+ return {
+ ...v,
+ elevenlabs_key: Boolean(readSecret(root, 'elevenlabs_api_key')) ? 'saved' : elevenKey(root) ? 'from the environment' : null,
+ gpus,
+ local: qwen.recommend(gpus),
+ presets: qwen.PRESETS,
+ output_formats: eleven.OUTPUT_FORMATS,
+ servers: Object.keys(eleven.SERVERS),
+ };
+}
+
+export { eleven, qwen };
diff --git a/src/voice/qwen.mjs b/src/voice/qwen.mjs
new file mode 100644
index 0000000..b220c9b
--- /dev/null
+++ b/src/voice/qwen.mjs
@@ -0,0 +1,186 @@
+// Local narration: Qwen3-TTS (Apache-2.0) through ComfyUI and the TTS Audio Suite custom nodes, on your own graphics
+// card. Nothing leaves the machine and nothing is billed. This module detects the GPU, checks ComfyUI, and makes a test
+// line for Settings and `mortiflix voice`; sessions use the voiceover skill's vo.mjs, which builds the same graphs.
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+
+// Built into the CustomVoice checkpoints (Qwen's model card): name, native language, character.
+export const PRESETS = [
+ { id: 'Ryan', language: 'English', about: 'dynamic male voice with strong rhythmic drive' },
+ { id: 'Aiden', language: 'English', about: 'sunny American male voice, clear midrange' },
+ { id: 'Vivian', language: 'Chinese', about: 'bright, slightly edgy young female voice' },
+ { id: 'Serena', language: 'Chinese', about: 'warm, gentle young female voice' },
+ { id: 'Uncle_Fu', language: 'Chinese', about: 'seasoned male voice, low and mellow' },
+ { id: 'Dylan', language: 'Chinese (Beijing)', about: 'youthful Beijing male voice' },
+ { id: 'Eric', language: 'Chinese (Sichuan)', about: 'lively Chengdu male voice, slightly husky' },
+ { id: 'Ono_Anna', language: 'Japanese', about: 'playful Japanese female voice' },
+ { id: 'Sohee', language: 'Korean', about: 'warm Korean female voice, rich emotion' },
+];
+
+export const DEFAULTS = {
+ url: 'http://127.0.0.1:8188',
+ model: 'CustomVoice 1.7B', // matched against the installed node's model list
+ voice: 'Ryan',
+ language: 'English',
+ instruct: 'A calm, clear, warm narrator. Steady, unhurried pace, natural pauses between ideas.',
+ runtime_mode: 'Main Environment', // the suite's own options; some installs need its "Shared Runtime"
+ check: true, // listen back to every take with Qwen3-ASR (word timings come from it)
+ asr_model: '1.7B',
+};
+
+// Measured: the 1.7B voice model needs about 6.5 GB free while it speaks, the 1.7B listening model about 6 GB (they
+// take turns, so the card needs room for one at a time). The 0.6B models fit in about half.
+export const NEEDS = { '1.7B': 8, '0.6B': 4 };
+
+// The machine's graphics cards (NVIDIA through nvidia-smi; ComfyUI's own report covers the rest when it's running).
+export function detectGpus() {
+ const r = spawnSync('nvidia-smi', ['--query-gpu=name,memory.total,memory.used', '--format=csv,noheader,nounits'], { encoding: 'utf8', timeout: 5000 });
+ if (r.status !== 0) return [];
+ return r.stdout.trim().split('\n').filter(Boolean).map((line) => {
+ const [name, total, used] = line.split(',').map((s) => s.trim());
+ return { name, vram_gb: round(Number(total) / 1024), used_gb: round(Number(used) / 1024), vendor: 'nvidia' };
+ });
+}
+
+// Which model this card can run, or why not.
+export function recommend(gpus) {
+ const best = [...gpus].sort((a, b) => b.vram_gb - a.vram_gb)[0];
+ if (!best) return { fits: false, model: null, reason: 'No NVIDIA graphics card found. Qwen3-TTS can run on other GPUs through ComfyUI, but Mortiflix can only check NVIDIA cards itself.' };
+ if (best.vram_gb >= NEEDS['1.7B']) return { fits: true, model: 'CustomVoice 1.7B', gpu: best, reason: `${best.name} (${best.vram_gb} GB) runs the 1.7B voice, which takes delivery instructions.` };
+ if (best.vram_gb >= NEEDS['0.6B']) return { fits: true, model: 'CustomVoice 0.6B', gpu: best, reason: `${best.name} (${best.vram_gb} GB) fits the 0.6B voice (preset voices, no delivery instructions).` };
+ return { fits: false, model: null, gpu: best, reason: `${best.name} has ${best.vram_gb} GB; Qwen3-TTS needs at least ${NEEDS['0.6B']} GB.` };
+}
+
+const round = (v) => Math.round(v * 10) / 10;
+
+export class ComfyUI {
+ constructor({ url = DEFAULTS.url, fetch = globalThis.fetch } = {}) {
+ this.url = url.replace(/\/+$/, '');
+ this.fetch = fetch;
+ }
+
+ async get(path) {
+ const res = await this.fetch(this.url + path, { signal: AbortSignal.timeout(15_000) });
+ if (!res.ok) throw new Error(`ComfyUI ${res.status} on ${path}`);
+ return res.json();
+ }
+
+ async post(path, body) {
+ const res = await this.fetch(this.url + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ if (!res.ok) throw new Error(`ComfyUI ${res.status} on ${path}: ${(await res.text()).slice(0, 300)}`);
+ const t = await res.text();
+ return t ? JSON.parse(t) : {};
+ }
+
+ // Is ComfyUI up, is the TTS Audio Suite installed, and what does it offer? Everything comes from the installed
+ // nodes, so a newer suite with other model names or options still works.
+ async status() {
+ let stats;
+ try { stats = await this.get('/system_stats'); } catch (e) {
+ return { ok: false, step: 'comfyui', reason: `ComfyUI isn't answering at ${this.url} (${e.cause?.code || e.message}).` };
+ }
+ const dev = stats.devices?.[0] || {};
+ const base = { comfyui: stats.system?.comfyui_version || null, gpu: dev.name ? String(dev.name).replace(/^cuda:\d+\s*/, '').replace(/\s*:.*$/, '') : null, vram_gb: dev.vram_total ? round(dev.vram_total / 2 ** 30) : null, vram_free_gb: dev.vram_free ? round(dev.vram_free / 2 ** 30) : null };
+ let info;
+ try { info = await this.get('/object_info/Qwen3TTSEngineNode'); } catch { info = {}; }
+ const engine = info.Qwen3TTSEngineNode;
+ if (!engine) return { ok: false, step: 'suite', ...base, reason: 'ComfyUI is running, but the TTS Audio Suite (with Qwen3-TTS) isn\'t installed.' };
+ // Some inputs (runtime_mode) are optional on the node: read both.
+ const inputs = { ...(engine.input.optional || {}), ...(engine.input.required || {}) };
+ const options = (k) => (Array.isArray(inputs[k]?.[0]) ? inputs[k][0] : []);
+ const variants = options('model_variant');
+ let asr = false;
+ try { asr = Boolean((await this.get('/object_info/UnifiedASRTranscribeNode')).UnifiedASRTranscribeNode); } catch { /* older suite */ }
+ return {
+ ok: true,
+ ...base,
+ models: variants.filter((v) => /CustomVoice|VoiceDesign|Base/.test(v) && !v.startsWith('local:')),
+ asr_models: variants.filter((v) => /^\d(\.\d)?B$/.test(v)),
+ voices: options('voice_preset').filter((v) => !v.startsWith('None')),
+ languages: options('language'),
+ runtime_modes: options('runtime_mode'),
+ can_listen: asr,
+ };
+ }
+
+ // The installed model variant that matches a short name like "CustomVoice 1.7B".
+ static variant(models, want) {
+ const [kind, size] = String(want).split(/\s+/);
+ return models.find((m) => m.includes(kind) && m.includes(size)) || models.find((m) => m.includes(kind)) || models[0];
+ }
+
+ async run(graph, { timeoutMs = 30 * 60_000 } = {}) {
+ const { prompt_id: id } = await this.post('/prompt', { prompt: graph, client_id: randomUUID() });
+ const end = Date.now() + timeoutMs;
+ while (Date.now() < end) {
+ const h = await this.get(`/history/${id}`);
+ if (h[id]) {
+ const st = h[id].status || {};
+ if (st.status_str === 'error') {
+ const err = (st.messages || []).find((m) => m[0] === 'execution_error')?.[1] || {};
+ throw new Error(`${err.node_type || 'ComfyUI'}: ${err.exception_message || 'failed'}`.trim());
+ }
+ return h[id].outputs;
+ }
+ await new Promise((ok) => setTimeout(ok, 1000));
+ }
+ throw new Error('ComfyUI took too long');
+ }
+
+ async file({ filename, subfolder, type }) {
+ const q = new URLSearchParams({ filename, subfolder: subfolder || '', type: type || 'temp' });
+ const res = await this.fetch(`${this.url}/view?${q}`);
+ if (!res.ok) throw new Error(`ComfyUI ${res.status} fetching audio`);
+ return Buffer.from(await res.arrayBuffer());
+ }
+
+ // Unload models between speaking and listening: the two don't share a mid-size card. Only when ComfyUI has nothing
+ // else queued or running, so someone else's ComfyUI work is never pulled out from under it.
+ async free() {
+ try {
+ const q = await this.get('/queue');
+ if ((q.queue_running || []).length || (q.queue_pending || []).length) return false;
+ await this.post('/free', { unload_models: true, free_memory: true });
+ return true;
+ } catch { return false; /* older ComfyUI */ }
+ }
+
+ // One line in the chosen voice, for "Try it".
+ async sample(cfg, text, status) {
+ const s = status || await this.status();
+ if (!s.ok) throw new Error(s.reason);
+ const graph = speakGraph({ ...cfg, variant: ComfyUI.variant(s.models, cfg.model) }, text, 1);
+ const out = await this.run(graph);
+ const f = out['3'].audio[0];
+ return { audio: await this.file(f), format: (f.filename.split('.').pop() || 'flac') };
+ }
+}
+
+// The graph that speaks one line: the Qwen3-TTS engine node, the suite's text node, a preview (kept in ComfyUI's temp
+// folder, which empties on restart, so takes don't pile up there).
+export function speakGraph(cfg, text, seed) {
+ const instructable = /CustomVoice 1\.7B/.test(cfg.variant);
+ return {
+ 1: { class_type: 'Qwen3TTSEngineNode', inputs: {
+ model_variant: cfg.variant, device: 'auto', voice_preset: cfg.voice, language: cfg.language || 'English',
+ instruct: instructable ? (cfg.instruct || '') : '', top_k: 50, top_p: 1.0, temperature: 0.8, repetition_penalty: 1.05,
+ max_new_tokens: 4096, asr_use_forced_aligner: true, runtime_mode: cfg.runtime_mode || DEFAULTS.runtime_mode } },
+ 2: { class_type: 'UnifiedTTSTextNode', inputs: {
+ TTS_engine: ['1', 0], text, narrator_voice: 'none', seed, enable_audio_cache: false, enable_chunking: true,
+ max_chars_per_chunk: 400, chunk_combination_method: 'silence_padding', silence_between_chunks_ms: 250 } },
+ 3: { class_type: 'PreviewAudio', inputs: { audio: ['2', 0] } },
+ };
+}
+
+// The graph that listens to one take (uploaded to ComfyUI's input folder) and returns its words with timings.
+export function listenGraph(cfg, inputName) {
+ return {
+ 1: { class_type: 'Qwen3TTSEngineNode', inputs: {
+ model_variant: cfg.asr_model || DEFAULTS.asr_model, device: 'auto', voice_preset: 'None (Zero-shot / Custom)', language: cfg.language || 'English',
+ instruct: '', top_k: 50, top_p: 1.0, temperature: 0.8, repetition_penalty: 1.05, max_new_tokens: 4096,
+ asr_use_forced_aligner: true, runtime_mode: cfg.runtime_mode || DEFAULTS.runtime_mode } },
+ 2: { class_type: 'LoadAudio', inputs: { audio: inputName } },
+ 3: { class_type: 'UnifiedASRTranscribeNode', inputs: { engine: ['1', 0], audio: ['2', 0], language: cfg.language || 'English', task: 'transcribe', timestamps: 'word', enable_asr_cache: false } },
+ 4: { class_type: 'PreviewAny', inputs: { source: ['3', 1] } },
+ };
+}
diff --git a/src/web/server.mjs b/src/web/server.mjs
index 3131eb2..711130d 100644
--- a/src/web/server.mjs
+++ b/src/web/server.mjs
@@ -14,6 +14,7 @@ import { listPipelines } from '../pipelines.mjs';
import { createProject, addIntakeFile, startProject, listProjects, loadProject, projectPaths, projectPipeline, readEvents, readJournal } from '../projects.mjs';
import * as gates from '../gates.mjs';
import { Runner, BACKENDS } from '../runner.mjs';
+import * as voice from '../voice/index.mjs';
const MIME = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
@@ -102,6 +103,7 @@ export async function startServer(root, { port = 4646, host = '127.0.0.1', runne
if ('api_key' in body) writeSecret(root, 'anthropic_api_key', body.api_key ? String(body.api_key).trim() : null);
return after(studioInfo(root, runner));
}
+ if (p.startsWith('/voice')) return voiceApi(root, req, res, url, p, method, after);
if (p === '/pipelines' && method === 'GET') {
return send(res, 200, listPipelines(root).map(({ dir, ...x }) => x));
}
@@ -218,6 +220,75 @@ export async function startServer(root, { port = 4646, host = '127.0.0.1', runne
class BadRequest extends Error {}
+// Narration setup: the engine, ElevenLabs (account, models, voices, Voice Library, dictionaries, a test line) and
+// local Qwen3-TTS through ComfyUI. Calls to ElevenLabs happen only when the page asks.
+async function voiceApi(root, req, res, url, p, method, after) {
+ const q = (k) => url.searchParams.get(k) || undefined;
+ const client = () => {
+ const key = voice.elevenKey(root);
+ if (!key) throw new BadRequest('connect an ElevenLabs API key first');
+ return new voice.eleven.ElevenLabs({ key, server: voice.voiceConfig(root).elevenlabs.server });
+ };
+ const wrap = async (fn) => {
+ try { return await fn(); } catch (e) {
+ if (e instanceof BadRequest || e instanceof UserError) throw e;
+ throw new BadRequest(e.status === 401 ? 'ElevenLabs refused the key (401): check it, or make a new one at elevenlabs.io › Developers › API keys' : e.message);
+ }
+ };
+ if (p === '/voice' && method === 'GET') return send(res, 200, voice.voiceOverview(root));
+ if (p === '/voice' && method === 'PUT') {
+ const body = await json(req);
+ if ('elevenlabs_key' in body) voice.setElevenKey(root, body.elevenlabs_key);
+ try { voice.saveVoice(root, body); } catch (e) { throw new BadRequest(e.message); }
+ return after(voice.voiceOverview(root));
+ }
+ if (p === '/voice/elevenlabs/account' && method === 'GET') {
+ const account = await wrap(() => client().account());
+ voice.saveVoice(root, { elevenlabs: { tier: account.tier } });
+ return send(res, 200, account);
+ }
+ if (p === '/voice/elevenlabs/models' && method === 'GET') return send(res, 200, await wrap(() => client().models()));
+ if (p === '/voice/elevenlabs/voices' && method === 'GET') return send(res, 200, await wrap(() => client().voices({ search: q('search'), page_token: q('page') })));
+ if (p === '/voice/elevenlabs/library' && method === 'GET') {
+ return send(res, 200, await wrap(() => client().library({ search: q('search'), gender: q('gender'), age: q('age'), accent: q('accent'), language: q('language'), use_cases: q('use_case') ? [q('use_case')] : undefined, page: Number(q('page') || 0) })));
+ }
+ if (p === '/voice/elevenlabs/library/add' && method === 'POST') {
+ const { owner, voice_id: vid, name } = await json(req);
+ return after(await wrap(() => client().addFromLibrary(owner, vid, String(name || 'Mortiflix voice').slice(0, 100))));
+ }
+ if (p === '/voice/elevenlabs/dictionaries' && method === 'GET') return send(res, 200, await wrap(() => client().dictionaries()));
+ if (p === '/voice/elevenlabs/preview' && method === 'GET') {
+ const target = q('url');
+ if (!voice.eleven.previewAllowed(target)) throw new BadRequest('not an ElevenLabs preview');
+ const r = await fetch(target);
+ if (!r.ok) throw new BadRequest(`preview ${r.status}`);
+ res.writeHead(200, { 'content-type': r.headers.get('content-type') || 'audio/mpeg', 'cache-control': 'private, max-age=86400', 'x-content-type-options': 'nosniff' });
+ return res.end(Buffer.from(await r.arrayBuffer()));
+ }
+ if (p === '/voice/qwen/status' && method === 'GET') {
+ const cfg = voice.voiceConfig(root).qwen;
+ return send(res, 200, await new voice.qwen.ComfyUI({ url: q('url') || cfg.url }).status());
+ }
+ if (p === '/voice/sample' && method === 'POST') {
+ const { engine, text } = await json(req);
+ const line = String(text || '').trim().slice(0, 300) || 'This is how your narration will sound.';
+ const cfg = voice.voiceConfig(root);
+ if (engine === 'elevenlabs') {
+ if (!cfg.elevenlabs.voice_id) throw new BadRequest('choose a voice first');
+ const out = await wrap(() => client().sample(cfg.elevenlabs, line));
+ res.writeHead(200, { 'content-type': 'audio/mpeg', 'x-characters': String(out.characters), 'cache-control': 'no-store' });
+ return res.end(out.audio);
+ }
+ if (engine === 'qwen') {
+ const out = await wrap(() => new voice.qwen.ComfyUI({ url: cfg.qwen.url }).sample(cfg.qwen, line));
+ res.writeHead(200, { 'content-type': out.format === 'wav' ? 'audio/wav' : out.format === 'mp3' ? 'audio/mpeg' : 'audio/flac', 'cache-control': 'no-store' });
+ return res.end(out.audio);
+ }
+ throw new BadRequest('engine must be elevenlabs or qwen');
+ }
+ return send(res, 404, { error: 'not found' });
+}
+
function send(res, code, body) {
res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
res.end(JSON.stringify(body));
diff --git a/test/fixtures/fake-voice-apis.mjs b/test/fixtures/fake-voice-apis.mjs
new file mode 100644
index 0000000..46d49cb
--- /dev/null
+++ b/test/fixtures/fake-voice-apis.mjs
@@ -0,0 +1,61 @@
+// Loaded with `node --import` into vo.mjs for tests: answers ElevenLabs and ComfyUI requests from memory.
+// FAKE_WAV is a real audio file every "generation" returns; FAKE_LOG collects the requests for assertions.
+import { readFileSync, appendFileSync } from 'node:fs';
+
+const wav = readFileSync(process.env.FAKE_WAV);
+const LINES = { 'Every city has a heartbeat.': 'every city has a heartbeat', 'Ours runs on bikes, all night long.': 'ours runs on bikes all night long' };
+let stt = 0;
+let prompts = 0;
+const graphs = {};
+const log = (row) => process.env.FAKE_LOG && appendFileSync(process.env.FAKE_LOG, JSON.stringify(row) + '\n');
+const json = (v, init = {}) => new Response(JSON.stringify(v), { status: 200, headers: { 'content-type': 'application/json', ...(init.headers || {}) } });
+const words = (text) => text.split(' ').map((w, i) => ({ text: w, type: 'word', start: i * 0.3, end: i * 0.3 + 0.25 }));
+
+globalThis.fetch = async (input, init = {}) => {
+ const url = new URL(String(input));
+ const method = init.method || 'GET';
+ if (url.hostname.endsWith('elevenlabs.io')) {
+ if (url.pathname.startsWith('/v1/text-to-speech/')) {
+ const body = JSON.parse(init.body);
+ log({ api: 'tts', voice: url.pathname.split('/').pop(), format: url.searchParams.get('output_format'), body });
+ return new Response(wav, { status: 200, headers: { 'request-id': `req-${Math.random().toString(36).slice(2, 8)}` } });
+ }
+ if (url.pathname === '/v1/speech-to-text') {
+ stt++;
+ const keyterms = init.body.getAll('keyterms');
+ log({ api: 'stt', model: init.body.get('model_id'), keyterms });
+ // The second check (line 2, take 1) hears words missing: the line must be retaken.
+ const heard = stt === 2 ? 'ours runs' : stt === 1 ? LINES['Every city has a heartbeat.'] : LINES['Ours runs on bikes, all night long.'];
+ return json({ text: heard, words: words(heard) });
+ }
+ if (url.pathname === '/v1/user/subscription') return json({ tier: 'creator', character_count: 1000, character_limit: 100000 });
+ }
+ if (url.port === '8188') {
+ if (url.pathname === '/system_stats') return json({ system: { comfyui_version: '0.35.0' }, devices: [{ name: 'cuda:0 Fake GPU : cudaMallocAsync', vram_total: 10 * 2 ** 30, vram_free: 9 * 2 ** 30 }] });
+ if (url.pathname === '/object_info/Qwen3TTSEngineNode') return json({ Qwen3TTSEngineNode: { input: { required: {
+ model_variant: [['TTS - CustomVoice 1.7B (Presets + Instruction)', 'TTS - CustomVoice 0.6B (Presets)', '1.7B', '0.6B']],
+ voice_preset: [['None (Zero-shot / Custom)', 'Ryan', 'Aiden']], language: [['Auto', 'English']] },
+ // As on a real install: runtime_mode is an optional input.
+ optional: { runtime_mode: [['Main Environment', '⚠️ Shared Runtime']] } } } });
+ if (url.pathname === '/object_info/UnifiedASRTranscribeNode') return json({ UnifiedASRTranscribeNode: { input: { required: {} } } });
+ if (url.pathname === '/queue') return json({ queue_running: [], queue_pending: [] });
+ if (url.pathname === '/free') { log({ api: 'free' }); return json({}); }
+ if (url.pathname === '/prompt') {
+ const { prompt } = JSON.parse(init.body);
+ const id = `p${++prompts}`;
+ graphs[id] = prompt;
+ log({ api: 'prompt', classes: Object.values(prompt).map((n) => n.class_type), engine: prompt['1'].inputs });
+ return json({ prompt_id: id });
+ }
+ if (url.pathname.startsWith('/history/')) {
+ const id = url.pathname.split('/').pop();
+ const g = graphs[id];
+ if (g['3'].class_type === 'PreviewAudio') return json({ [id]: { status: { status_str: 'success' }, outputs: { 3: { audio: [{ filename: `${id}.flac`, subfolder: '', type: 'temp' }] } } } });
+ const said = 'every city has a heartbeat';
+ return json({ [id]: { status: { status_str: 'success' }, outputs: { 4: { text: [JSON.stringify({ text: said, segments: [{ words: words(said) }] })] } } } });
+ }
+ if (url.pathname === '/view') return new Response(wav, { status: 200 });
+ if (url.pathname === '/upload/image' && method === 'POST') return json({ name: 'take.wav', subfolder: 'mortiflix', type: 'input' });
+ }
+ throw new Error(`fake: no route for ${method} ${url}`);
+};
diff --git a/test/voice.test.mjs b/test/voice.test.mjs
new file mode 100644
index 0000000..7a7f589
--- /dev/null
+++ b/test/voice.test.mjs
@@ -0,0 +1,169 @@
+// Narration: the ElevenLabs and ComfyUI clients, the settings rules, and vo.mjs end to end against fake APIs
+// (loaded into its process with --import): no network, no key, no GPU.
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { tempStudio } from './helpers.mjs';
+import { requestBody, voiceSettings, ElevenLabs } from '../src/voice/elevenlabs.mjs';
+import { recommend, ComfyUI, speakGraph } from '../src/voice/qwen.mjs';
+import { saveVoice, voiceConfig, sessionVoiceEnv, setElevenKey } from '../src/voice/index.mjs';
+
+const REPO = fileURLToPath(new URL('..', import.meta.url));
+const VO = join(REPO, 'pipelines/_shared/skills/voiceover/vo.mjs');
+const FAKE = join(REPO, 'test/fixtures/fake-voice-apis.mjs');
+
+test('ElevenLabs requests carry only what the model takes', () => {
+ const base = { voice_id: 'v', stability: 0.4, similarity_boost: 0.8, style: 0.3, speed: 1.1, use_speaker_boost: false };
+ const v4 = requestBody({ ...base, model_id: 'eleven_v4' }, 'Hi', { previous_text: 'Before', next_text: 'After', seed: 7 });
+ assert.deepEqual(v4.voice_settings, { stability: 0.4, similarity_boost: 0.8 });
+ assert.equal(v4.model_id, 'eleven_v4');
+ assert.equal(v4.previous_text, 'Before');
+ assert.equal(v4.next_text, 'After');
+ assert.equal(v4.seed, 7);
+ const v2 = voiceSettings({ ...base, model_id: 'eleven_multilingual_v2' });
+ assert.deepEqual(v2, { stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: false, speed: 1.1 });
+ const dict = requestBody({ ...base, model_id: 'eleven_v4', language_code: 'en', apply_text_normalization: 'on', pronunciation_dictionaries: [{ id: 'a', version_id: '1' }, { id: 'b' }, { id: 'c' }, { id: 'd' }] }, 'x');
+ assert.equal(dict.pronunciation_dictionary_locators.length, 3);
+ assert.deepEqual(dict.pronunciation_dictionary_locators[0], { pronunciation_dictionary_id: 'a', version_id: '1' });
+ assert.equal(dict.language_code, 'en');
+ assert.equal(dict.apply_text_normalization, 'on');
+ assert.equal(requestBody({ model_id: 'eleven_v4' }, 'x').apply_text_normalization, undefined);
+});
+
+test('the ElevenLabs client reads the plan, ranks models and refuses bad keys clearly', async () => {
+ const calls = [];
+ const fetch = async (url, init) => {
+ calls.push(String(url));
+ const u = new URL(String(url));
+ if (init.headers['xi-api-key'] !== 'good') return new Response('{"detail":{"message":"Invalid API key"}}', { status: 401 });
+ if (u.pathname === '/v1/user/subscription') return Response.json({ tier: 'free', character_count: 9000, character_limit: 10000, can_use_instant_voice_cloning: false });
+ if (u.pathname === '/v1/models') return Response.json([
+ { model_id: 'eleven_flash_v2_5', can_do_text_to_speech: true, languages: [{}, {}] },
+ { model_id: 'eleven_multilingual_sts_v2', can_do_text_to_speech: false },
+ { model_id: 'eleven_v4', name: 'Eleven v4', can_do_text_to_speech: true, can_use_style: true, maximum_text_length_per_request: 10000, languages: Array(90).fill({}) },
+ ]);
+ if (u.pathname === '/v2/voices') return Response.json({ voices: [{ voice_id: 'x1', name: 'Ada', category: 'premade', labels: { accent: 'british' }, preview_url: 'https://storage.googleapis.com/p.mp3' }], has_more: false, total_count: 1 });
+ if (u.pathname.startsWith('/v1/voices/add/')) return Response.json({ voice_id: 'copied' });
+ return new Response('', { status: 404 });
+ };
+ const el = new ElevenLabs({ key: 'good', server: 'eu', fetch });
+ const a = await el.account();
+ assert.equal(a.characters_left, 1000);
+ assert.equal(a.commercial_use, false);
+ assert.equal(a.concurrency, 2);
+ const models = await el.models();
+ assert.deepEqual(models.map((m) => m.id), ['eleven_v4', 'eleven_flash_v2_5']);
+ assert.equal(models[0].can_use_style, false); // v4 has no style setting, whatever the flag says
+ assert.equal((await el.voices({ search: 'ada' })).voices[0].labels.accent, 'british');
+ assert.equal((await el.addFromLibrary('owner1', 'lib1', 'Ada')).id, 'copied');
+ assert.ok(calls.every((c) => c.startsWith('https://api.eu.residency.elevenlabs.io/')));
+ await assert.rejects(new ElevenLabs({ key: 'bad', fetch }).account(), /401: Invalid API key/);
+});
+
+test('the local voice is offered only when the card can run it', () => {
+ assert.equal(recommend([{ name: 'RTX 3080', vram_gb: 10 }]).model, 'CustomVoice 1.7B');
+ assert.equal(recommend([{ name: 'RTX 3060', vram_gb: 6 }]).model, 'CustomVoice 0.6B');
+ assert.equal(recommend([{ name: 'GTX 1050', vram_gb: 2 }]).fits, false);
+ assert.equal(recommend([]).fits, false);
+ const g = speakGraph({ variant: 'TTS - CustomVoice 0.6B (Presets)', voice: 'Ryan', instruct: 'calm' }, 'Hi', 3);
+ assert.equal(g[1].inputs.instruct, ''); // 0.6B takes no instruction
+ assert.equal(ComfyUI.variant(['TTS - CustomVoice 1.7B (Presets + Instruction)', 'TTS - CustomVoice 0.6B (Presets)'], 'CustomVoice 0.6B'), 'TTS - CustomVoice 0.6B (Presets)');
+});
+
+test('ComfyUI is never told to unload while it has other work', async () => {
+ const posts = [];
+ const busy = new ComfyUI({ fetch: async (url, init) => {
+ if (String(url).endsWith('/queue')) return Response.json({ queue_running: [[1, 'someone-else']], queue_pending: [] });
+ posts.push(String(url));
+ return Response.json({});
+ } });
+ assert.equal(await busy.free(), false);
+ assert.equal(posts.length, 0);
+});
+
+test('voice settings: ranges enforced, the key reaches sessions only for ElevenLabs', (t) => {
+ const root = tempStudio(t);
+ saveVoice(root, { engine: 'elevenlabs', elevenlabs: { stability: 7, speed: 3, output_format: 'nope', apply_text_normalization: 'on', unknown: 1 } });
+ const v = voiceConfig(root);
+ assert.equal(v.elevenlabs.stability, 1);
+ assert.equal(v.elevenlabs.speed, 1.2);
+ assert.equal(v.elevenlabs.output_format, 'mp3_44100_128');
+ assert.equal(v.elevenlabs.unknown, undefined);
+ assert.throws(() => saveVoice(root, { engine: 'robot' }), /engine/);
+ setElevenKey(root, 'secret-key');
+ assert.equal(sessionVoiceEnv(root).ELEVENLABS_API_KEY, 'secret-key');
+ assert.ok(!sessionVoiceEnv(root).MFX_VOICE.includes('secret-key'));
+ saveVoice(root, { engine: 'qwen' });
+ assert.equal(sessionVoiceEnv(root).ELEVENLABS_API_KEY, undefined);
+});
+
+function voFixture(t) {
+ if (spawnSync('ffmpeg', ['-version']).status !== 0) { t.skip('no ffmpeg'); return null; }
+ const dir = mkdtempSync(join(tmpdir(), 'mfx-vo-'));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ spawnSync('ffmpeg', ['-loglevel', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=300:duration=1.2', join(dir, 'tone.wav')]);
+ writeFileSync(join(dir, 'lines.json'), JSON.stringify([
+ { id: 'b01-1', text: '[warm] Every city has a heartbeat.', script: 'Every city has a heartbeat.', gap_after: 0.5 },
+ { id: 'b01-2', text: 'Ours runs on bikes, all night long.' },
+ ]));
+ const run = (args, voice) => spawnSync('node', ['--import', FAKE, VO, ...args], {
+ cwd: dir, encoding: 'utf8',
+ env: { ...process.env, MFX_HOME: REPO, MFX_VOICE: JSON.stringify(voice), ELEVENLABS_API_KEY: 'k', FAKE_WAV: join(dir, 'tone.wav'), FAKE_LOG: join(dir, 'log.jsonl') },
+ });
+ const log = () => readFileSync(join(dir, 'log.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
+ return { dir, run, log };
+}
+
+test('vo.mjs with ElevenLabs: speaks with context, checks every take, retakes a bad one, builds the timing', (t) => {
+ const f = voFixture(t);
+ if (!f) return;
+ const voice = { engine: 'elevenlabs', elevenlabs: { voice_id: 'voice1', voice_name: 'Ada', model_id: 'eleven_v4', output_format: 'wav_24000', stability: 0.5, similarity_boost: 0.75, style: 0.9 } };
+ const r = f.run(['speak', 'lines.json', '--jobs', '1'], voice);
+ assert.equal(r.status, 0, r.stderr + r.stdout);
+ assert.match(r.stdout, /b01-2 take 1: .*words in a row missing/);
+ assert.match(r.stdout, /2\/2 lines passed/);
+ const calls = f.log();
+ const tts = calls.filter((c) => c.api === 'tts');
+ assert.equal(tts.length, 3);
+ assert.equal(tts[0].format, 'wav_24000');
+ assert.deepEqual(Object.keys(tts[0].body.voice_settings), ['stability', 'similarity_boost']); // v4: no style
+ assert.equal(tts[0].body.next_text, 'Ours runs on bikes, all night long.');
+ assert.equal(tts[1].body.previous_text, '[warm] Every city has a heartbeat.');
+ assert.notEqual(tts[1].body.seed, tts[2].body.seed);
+ const stt = calls.filter((c) => c.api === 'stt');
+ assert.equal(stt[0].model, 'scribe_v2');
+ assert.deepEqual(stt[0].keyterms, ['Every']);
+ const clip = JSON.parse(readFileSync(join(f.dir, 'voice/clips/b01-2.json'), 'utf8'));
+ assert.equal(clip.take, 2);
+ assert.equal(clip.pass, true);
+
+ const b = f.run(['build', 'lines.json'], voice);
+ assert.equal(b.status, 0, b.stderr);
+ const timing = JSON.parse(readFileSync(join(f.dir, 'voice/timing.json'), 'utf8'));
+ assert.equal(timing.lines.length, 2);
+ assert.equal(timing.lines[0].timing, 'words');
+ assert.equal(timing.lines[1].start, 1.7); // 1.2 s clip + 0.5 s gap
+ assert.ok(existsSync(join(f.dir, 'voice/voice.wav')));
+});
+
+test('vo.mjs with local Qwen3-TTS: speaks plain words, frees the GPU between speaking and listening', (t) => {
+ const f = voFixture(t);
+ if (!f) return;
+ const voice = { engine: 'qwen', qwen: { url: 'http://127.0.0.1:8188', model: 'CustomVoice 1.7B', voice: 'Ryan', language: 'English', instruct: 'calm', check: true } };
+ const r = f.run(['speak', 'lines.json', '--only', 'b01-1'], voice);
+ assert.equal(r.status, 0, r.stderr + r.stdout);
+ const calls = f.log();
+ const prompts = calls.filter((c) => c.api === 'prompt');
+ assert.deepEqual(prompts[0].classes, ['Qwen3TTSEngineNode', 'UnifiedTTSTextNode', 'PreviewAudio']);
+ assert.equal(prompts[0].engine.model_variant, 'TTS - CustomVoice 1.7B (Presets + Instruction)');
+ assert.equal(prompts[0].engine.instruct, 'calm');
+ assert.deepEqual(prompts[1].classes, ['Qwen3TTSEngineNode', 'LoadAudio', 'UnifiedASRTranscribeNode', 'PreviewAny']);
+ assert.ok(calls.findIndex((c) => c.api === 'free') > calls.indexOf(prompts[0]));
+ const clip = JSON.parse(readFileSync(join(f.dir, 'voice/clips/b01-1.json'), 'utf8'));
+ assert.equal(clip.pass, true);
+ assert.match(clip.engine, /qwen3-tts/);
+});
diff --git a/web/app.js b/web/app.js
index 3b51054..3f5c59a 100644
--- a/web/app.js
+++ b/web/app.js
@@ -40,7 +40,7 @@ async function api(path, { method = 'GET', body, raw } = {}) {
function toast(text, bad = false) {
const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, text);
- document.body.append(t);
+ document.add(body, t);
setTimeout(() => t.remove(), bad ? 6000 : 2600);
}
@@ -95,6 +95,11 @@ function fill(el, ...kids) {
el.replaceChildren(...kids.flat(Infinity).filter((k) => k !== null && k !== undefined && k !== false));
}
+// append() would print null as "null" too.
+function add(el, ...kids) {
+ el.append(...kids.flat(Infinity).filter((k) => k !== null && k !== undefined && k !== false));
+}
+
function mount(...kids) {
fill($app, ...kids);
}
@@ -287,7 +292,7 @@ function appendLog(log, a, scroll = true) {
const atEnd = log.scrollHeight - log.scrollTop - log.clientHeight < 40;
const t = new Date(a.t).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
const mark = { text: '│', tool: '›', error: '!', info: '●' }[a.kind] || ' ';
- log.append(h('div', { class: 'l' }, h('span', { class: 't' }, t), h('span', { class: 'k' }, mark), h('span', { class: a.kind }, a.text)));
+ add(log, h('div', { class: 'l' }, h('span', { class: 't' }, t), h('span', { class: 'k' }, mark), h('span', { class: a.kind }, a.text)));
if (log.children.length > 400) log.firstChild.remove();
if (scroll && atEnd) log.scrollTop = log.scrollHeight;
}
@@ -316,7 +321,7 @@ function choiceChips(choices, selected, onPick) {
b.classList.add('on'); b.setAttribute('aria-checked', 'true');
onPick(c);
} }, c);
- wrap.append(b);
+ add(wrap, b);
}
return wrap;
}
@@ -384,7 +389,7 @@ async function reviewView(id, stepKey, versionParam) {
if (editable) {
tools.append(
h('button', { class: 'btn', onclick: () => addNote({ item: sel, time_sec: Math.round(video.currentTime * 100) / 100 }) }, 'Note at this moment'),
- h('button', { class: 'btn', onclick: () => { video.pause(); pinMode = !pinMode; stage.append(catcher); if (!pinMode) catcher.remove(); } }, 'Pin a spot in this frame'));
+ h('button', { class: 'btn', onclick: () => { video.pause(); pinMode = !pinMode; add(stage, catcher); if (!pinMode) catcher.remove(); } }, 'Pin a spot in this frame'));
}
} else if (it.kind === 'audio') {
const audio = h('audio', { src: url, controls: true, style: { width: '100%' } });
@@ -612,10 +617,12 @@ async function settingsView() {
const decideCheck = (cid, approve) => async () => { try { await api(`/api/checks/${cid}`, { method: 'POST', body: { approve } }); settingsView(); } catch (e) { toast(e.message, true); } };
- body.append(
+ const voiceBlock = await voiceSection();
+ add(body,
h('section', null, h('h2', null, 'Who makes the videos'), h('ul', { class: 'rows' }, backendRows), extra,
field('Session limit', h('input', { type: 'number', min: 5, max: 1440, value: c.maxSessionMinutes, oninput: (e) => { c.maxSessionMinutes = e.target.value; }, style: { maxWidth: '120px' } }), 'Minutes before a session is stopped (the next one picks up from its handoff).'),
h('div', { class: 'form-end' }, msg, save)),
+ voiceBlock,
h('section', null, h('h2', null, 'The error checklist', h('span', { class: 'count' }, checks.proposed.length ? `${checks.proposed.length} proposed` : '')),
h('p', { class: 'meta' }, 'When you point out a real mistake, the session proposes a check so it never reaches you again. Approved checks run on every future video.'),
checks.proposed.length ? h('ul', { class: 'rows' }, checks.proposed.map((k) => h('li', { class: 'row' }, icon('in_review'),
@@ -623,13 +630,204 @@ async function settingsView() {
h('div', { class: 'end' }, h('button', { class: 'btn', onclick: decideCheck(k.id, true) }, 'Add'), h('button', { class: 'btn link', onclick: decideCheck(k.id, false) }, 'Dismiss'))))) : null,
checks.active.length ? h('ul', { class: 'rows' }, checks.active.map((k) => h('li', { class: 'row' }, icon('done'), h('div', { class: 'main' }, h('span', { class: 'title' }, k.title)), h('div', { class: 'end' }, (k.applies_to || []).join(', '))))) : h('p', { class: 'meta' }, 'No studio checks yet (each pipeline has its own).')),
h('section', null, h('h2', null, 'Keys for sessions'),
- h('p', null, studio.session_env ? 'session.env is set: its keys are handed to every session.' : 'Optional. To give sessions keys (for example ELEVENLABS_API_KEY for narration), put KEY=value lines in session.env in the studio folder.'),
+ h('p', null, studio.session_env ? 'session.env is set: its keys are handed to every session.' : 'Optional. To give sessions other keys, put KEY=value lines in session.env in the studio folder. (Narration keys belong in Narration above.)'),
h('p', { class: 'meta' }, `Studio folder: ${studio.root}`)),
);
mount(h('div', { class: 'head' }, h('h1', null, 'Settings')), body);
draw();
}
+// ---------- narration (Settings › Voice) ----------
+
+const ENGINE_LABELS = {
+ elevenlabs: ['ElevenLabs', 'The most natural voices, 90+ languages, your own voice clones. Paid per character (their free plan is non-commercial).'],
+ qwen: ['This computer (Qwen3-TTS)', 'Open model on your graphics card through ComfyUI: free, private, nothing leaves the machine.'],
+ none: ['No narration', 'Videos carry their story with on-screen text, music and sound.'],
+};
+
+async function voiceSection() {
+ let v = await api('/api/voice');
+ const wrap = h('section', { id: 'voice' });
+ const msg = h('span', { class: 'okmsg' });
+ const save = async (patch, note = 'Saved') => {
+ try { v = await api('/api/voice', { method: 'PUT', body: patch }); msg.textContent = note; setTimeout(() => { msg.textContent = ''; }, 1800); }
+ catch (e) { toast(e.message, true); }
+ };
+ const field = (label, control, help) => h('div', { class: 'field' }, h('label', null, label), h('div', null, control, help ? h('div', { class: 'help' }, help) : null));
+
+ async function draw() {
+ const chip = (name) => {
+ if (name === 'elevenlabs') return h('span', { class: `chip ${v.elevenlabs_key ? 'ok' : ''}` }, v.elevenlabs_key ? 'key saved' : 'needs a key');
+ if (name === 'qwen') return h('span', { class: `chip ${v.local.fits ? 'ok' : 'warn'}` }, v.local.fits ? `${v.local.gpu.name.replace(/^NVIDIA (GeForce )?/, '')} · ${v.local.gpu.vram_gb} GB fits` : 'no suitable GPU found');
+ return null;
+ };
+ const rows = h('ul', { class: 'rows' }, Object.entries(ENGINE_LABELS).map(([name, [title, about]]) => h('li', { class: 'row', style: { cursor: 'pointer' }, onclick: async () => { if (v.engine !== name) { await save({ engine: name }); draw(); } } },
+ h('input', { type: 'radio', name: 'voice-engine', checked: v.engine === name, 'aria-label': title }),
+ h('div', { class: 'main' }, h('span', { class: 'title' }, title), h('div', { class: 'meta', style: { whiteSpace: 'normal' } }, about)),
+ h('div', { class: 'end' }, chip(name)))));
+ const panel = h('div');
+ fill(wrap, h('h2', null, 'Narration', msg), rows, panel);
+ if (v.engine === 'elevenlabs') await elevenPanel(panel);
+ else if (v.engine === 'qwen') await qwenPanel(panel);
+ else fill(panel, h('p', { class: 'meta', style: { padding: '12px 0' } }, v.local.fits
+ ? `Want a voice? ${v.local.reason} Pick "This computer" to narrate for free, or ElevenLabs for the most natural voices.`
+ : 'Want a voice? Pick ElevenLabs above (a key from elevenlabs.io).'));
+ }
+
+ // ---- ElevenLabs ----
+ async function elevenPanel(panel) {
+ const e = v.elevenlabs;
+ const keyInput = h('input', { type: 'password', autocomplete: 'off', placeholder: v.elevenlabs_key === 'saved' ? 'Saved (type to replace)' : v.elevenlabs_key ? 'Using ELEVENLABS_API_KEY' : 'xi-… from elevenlabs.io › Developers › API keys' });
+ const account = h('div', { class: 'help' });
+ const accountRow = field('API key', h('div', null, h('div', { class: 'actions' }, keyInput, h('button', { class: 'btn', onclick: async () => {
+ if (keyInput.value.trim()) await save({ elevenlabs_key: keyInput.value.trim() }, 'Key saved');
+ keyInput.value = '';
+ draw();
+ } }, 'Connect')), account), 'Kept only in the studio folder (secrets.json). Sessions get it only while ElevenLabs is the narration engine.');
+ fill(panel, accountRow);
+ if (!v.elevenlabs_key) return;
+
+ let acct = null;
+ try {
+ acct = await api('/api/voice/elevenlabs/account');
+ fill(account,
+ h('span', { class: 'chip ok' }, `${acct.tier} plan`), ' ',
+ `${acct.characters_left.toLocaleString()} of ${acct.character_limit.toLocaleString()} credits left`,
+ acct.resets_at ? ` · resets ${new Date(acct.resets_at).toLocaleDateString()}` : '', ' ',
+ acct.commercial_use ? h('span', { class: 'chip ok' }, 'commercial use') : h('span', { class: 'chip bad' }, 'free plan: non-commercial, credit ElevenLabs'),
+ acct.concurrency ? ` · ${acct.concurrency} lines at once` : '');
+ } catch (err) { fill(account, h('span', { class: 'err' }, err.message)); return; }
+
+ const models = await api('/api/voice/elevenlabs/models').catch(() => []);
+ const model = models.find((m) => m.id === e.model_id) || { id: e.model_id, can_use_style: !/^eleven_v4/.test(e.model_id), can_use_speaker_boost: !/^eleven_v4/.test(e.model_id) };
+ const v4 = /^eleven_v4/.test(e.model_id);
+
+ // The voice: current choice, then a picker (my voices / Voice Library) with previews.
+ const picker = h('div');
+ const current = h('div', { class: 'actions' }, h('span', { class: 'title' }, e.voice_name || 'No voice chosen yet'),
+ h('button', { class: 'btn', onclick: () => openPicker('mine') }, 'Choose a voice'),
+ h('button', { class: 'btn link', onclick: () => openPicker('library') }, 'Browse the Voice Library'));
+ const play = (url) => { const a = new Audio(url); a.play().catch(() => toast('Could not play the preview', true)); };
+ async function openPicker(where, search = '') {
+ const input = h('input', { type: 'text', placeholder: where === 'mine' ? 'Search your voices (name, accent, use…)' : 'Search the Voice Library (e.g. "warm narrator", "British")', value: search });
+ const list = h('ul', { class: 'rows' }, h('li', { class: 'meta' }, 'Loading…'));
+ input.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') openPicker(where, input.value); });
+ fill(picker, h('div', { class: 'actions', style: { margin: '10px 0' } }, input, h('button', { class: 'btn', onclick: () => openPicker(where, input.value) }, 'Search'),
+ h('button', { class: 'btn link', onclick: () => openPicker(where === 'mine' ? 'library' : 'mine', input.value) }, where === 'mine' ? 'Voice Library instead' : 'My voices instead'),
+ h('button', { class: 'btn link', onclick: () => fill(picker) }, 'Close')), list);
+ try {
+ const r = where === 'mine'
+ ? await api(`/api/voice/elevenlabs/voices?search=${encodeURIComponent(search)}`)
+ : await api(`/api/voice/elevenlabs/library?search=${encodeURIComponent(search)}`);
+ fill(list, r.voices.length ? r.voices.map((x) => h('li', { class: 'row' },
+ x.preview_url ? h('button', { class: 'btn link', 'aria-label': `Play ${x.name}`, onclick: () => play(`/api/voice/elevenlabs/preview?url=${encodeURIComponent(x.preview_url)}`) }, '▶') : h('span'),
+ h('div', { class: 'main' }, h('span', { class: 'title' }, x.name),
+ h('div', { class: 'meta', style: { whiteSpace: 'normal' } }, Object.values(x.labels || {}).filter(Boolean).join(' · ') || x.category || '', where === 'library' && x.free_users_allowed === false ? ' · paid plans only' : '')),
+ h('div', { class: 'end' }, h('button', { class: 'btn', onclick: async () => {
+ try {
+ let id = x.id;
+ if (where === 'library') id = (await api('/api/voice/elevenlabs/library/add', { method: 'POST', body: { owner: x.owner, voice_id: x.id, name: x.name } })).id;
+ await save({ elevenlabs: { voice_id: id, voice_name: x.name } }, `${x.name} chosen`);
+ draw();
+ } catch (err) { toast(err.message, true); }
+ } }, where === 'library' ? 'Add & use' : 'Use')))) : h('li', { class: 'meta' }, 'No voices match.'));
+ } catch (err) { fill(list, h('li', { class: 'err' }, err.message)); }
+ }
+
+ const slider = (key, label, lo, hi, step, help) => {
+ const out = h('span', { class: 'meta' }, String(e[key]));
+ return field(label, h('div', { class: 'actions' }, h('input', { type: 'range', min: lo, max: hi, step, value: e[key], style: { width: '220px' },
+ oninput: (ev) => { out.textContent = ev.target.value; }, onchange: (ev) => save({ elevenlabs: { [key]: Number(ev.target.value) } }) }), out), help);
+ };
+ const select = (key, options, help, label) => field(label, h('select', { style: { maxWidth: '320px' }, onchange: (ev) => save({ elevenlabs: { [key]: ev.target.value } }) },
+ options.map((o) => h('option', { value: o.value, selected: String(e[key] ?? '') === String(o.value), disabled: o.disabled }, o.label))), help);
+
+ const dicts = await api('/api/voice/elevenlabs/dictionaries').catch(() => []);
+ const chosenDicts = new Set((e.pronunciation_dictionaries || []).map((d) => d.id));
+ const sampleText = h('textarea', { style: { minHeight: '60px' } }, v4 ? '[warm] Every city has a heartbeat. Ours runs on bikes.' : 'Every city has a heartbeat. Ours runs on bikes.');
+ const player = h('div');
+
+ fill(panel, accountRow,
+ field('Voice', h('div', null, current, picker), 'Your voices, the default voices and any you add from the Voice Library. ▶ plays the voice\'s own preview (free).'),
+ field('Model', choiceChips(models.map((m) => m.id), e.model_id, (id) => save({ elevenlabs: { model_id: id } }).then(draw)),
+ models.length ? `${models.find((m) => m.id === e.model_id)?.name || e.model_id}: ${models.find((m) => m.id === e.model_id)?.languages || '?'} languages, up to ${(models.find((m) => m.id === e.model_id)?.max_characters || 0).toLocaleString()} characters a line. eleven_v4 is ElevenLabs' newest and recommended for narration.` : null),
+ slider('stability', 'Stability', 0, 1, 0.05, 'Lower: more expressive and varied. Higher: steadier. Promos 0.4–0.5, long narration 0.55–0.65.'),
+ slider('similarity_boost', 'Similarity', 0, 1, 0.05, 'How closely it sticks to the original voice. Raise it if a clone drifts.'),
+ v4 ? field('Direction', h('div', { class: 'meta', style: { whiteSpace: 'normal' } }, 'Eleven v4 is directed in the script itself: audio tags like [warm] or [whispers], CAPITALS for emphasis, ellipses for pauses, and "/IPA/" for names. It has no style or speed settings and ignores SSML.')) : null,
+ !v4 && model.can_use_style ? slider('style', 'Style', 0, 1, 0.05, 'Exaggerates the voice\'s style. Above 0 can cost stability and speed.') : null,
+ !v4 ? slider('speed', 'Speed', 0.7, 1.2, 0.05, '1.0 is the voice\'s natural pace.') : null,
+ !v4 && model.can_use_speaker_boost ? field('Speaker boost', h('label', { class: 'toggle' }, h('input', { type: 'checkbox', checked: e.use_speaker_boost, onchange: (ev) => save({ elevenlabs: { use_speaker_boost: ev.target.checked } }) }), 'Closer to the original speaker (slightly slower)')) : null,
+ field('Language', h('input', { type: 'text', style: { maxWidth: '140px' }, placeholder: 'auto', value: e.language_code || '', onchange: (ev) => save({ elevenlabs: { language_code: ev.target.value.trim().toLowerCase() } }) }), 'Optional ISO 639-1 code (en, es, de…) to force a language and its number reading. Blank: detected from the text.'),
+ select('apply_text_normalization', [{ value: 'auto', label: 'Auto' }, { value: 'on', label: 'Always spell out numbers, dates…' }, { value: 'off', label: 'Off (read exactly as written)' }], 'How numbers, dates and abbreviations are read. Writing them out in the script is the most reliable.', 'Text normalization'),
+ dicts.length ? field('Pronunciation', h('div', null, dicts.map((d) => h('label', { class: 'toggle' }, h('input', { type: 'checkbox', checked: chosenDicts.has(d.id), onchange: (ev) => {
+ const next = [...(e.pronunciation_dictionaries || []).filter((x) => x.id !== d.id), ...(ev.target.checked ? [{ id: d.id, version_id: d.version_id, name: d.name }] : [])].slice(0, 3);
+ save({ elevenlabs: { pronunciation_dictionaries: next } });
+ } }), d.name))), 'Up to 3 of your pronunciation dictionaries, applied in order. Phoneme rules work on v4, v3 and Flash v2; other models use alias rules only.') : null,
+ select('output_format', v.output_formats.map((f) => ({ value: f.id, label: `${f.label}${f.tier ? ` (${f.tier} plan or above)` : ''}`, disabled: f.tier && !tierOk(acct.tier, f.tier) })), 'What each line is saved as. MP3 128 kbps is plenty for narration under music.', 'Audio format'),
+ select('server', v.servers.map((x) => ({ value: x, label: { default: 'Default (global)', us: 'United States', eu: 'EU data residency', in: 'India data residency', sg: 'Singapore data residency' }[x] })), 'Only change this if your account lives on a data-residency server.', 'Server'),
+ select('check_model', [{ value: 'scribe_v2', label: 'Check every line with Scribe v2 (recommended)' }, { value: 'off', label: 'Don\'t check' }], 'Speech to text listens to every take, retakes lines with missing words, and gives the animation exact word timings. Costs a little extra.', 'Checks'),
+ field('Also use for', h('div', null,
+ h('label', { class: 'toggle' }, h('input', { type: 'checkbox', checked: e.sfx, onchange: (ev) => save({ elevenlabs: { sfx: ev.target.checked } }) }), 'Sound effects (whooshes, hits, ambience: up to 30 s, loopable)'),
+ h('label', { class: 'toggle' }, h('input', { type: 'checkbox', checked: e.music, onchange: (ev) => save({ elevenlabs: { music: ev.target.checked } }) }), 'Music beds (Eleven Music: instrumental, 3 s to 10 min)')),
+ h('span', null, 'Music usage terms depend on your plan: ', h('a', { href: 'https://elevenlabs.io/music-terms', target: '_blank', rel: 'noopener' }, 'elevenlabs.io/music-terms'))),
+ field('Try it', h('div', null, sampleText, h('div', { class: 'actions', style: { marginTop: '8px' } }, h('button', { class: 'btn', onclick: () => trySample('elevenlabs', sampleText.value, player) }, 'Speak this line'), h('span', { class: 'meta' }, 'uses about one credit per character')), player)),
+ h('p', { class: 'meta', style: { padding: '10px 0' } }, 'Zero-retention mode (no logs at ElevenLabs) is for Enterprise accounts only, so it isn\'t offered here. Voice clones: only of your own voice or with the speaker\'s consent.'),
+ );
+ }
+
+ // ---- Qwen3-TTS through ComfyUI ----
+ async function qwenPanel(panel) {
+ const qc = v.qwen;
+ const status = h('div', { class: 'help' }, 'Checking ComfyUI…');
+ const url = h('input', { type: 'text', value: qc.url, style: { maxWidth: '280px' } });
+ const gpuLine = h('p', { class: 'meta', style: { padding: '8px 0', whiteSpace: 'normal' } }, v.local.reason);
+ fill(panel, gpuLine, field('ComfyUI', h('div', null, h('div', { class: 'actions' }, url, h('button', { class: 'btn', onclick: async () => { await save({ qwen: { url: url.value.trim() } }); draw(); } }, 'Check')), status)));
+ let st;
+ try { st = await api(`/api/voice/qwen/status?url=${encodeURIComponent(qc.url)}`); } catch (err) { st = { ok: false, reason: err.message }; }
+ if (!st.ok) {
+ fill(status, h('span', { class: 'err' }, st.reason));
+ add(panel, h('div', { class: 'field' }, h('label', null, 'Set it up'), h('ol', { style: { margin: 0, paddingLeft: '18px' } },
+ st.step !== 'suite' ? h('li', null, 'Install ComfyUI and start it (', h('a', { href: 'https://www.comfy.org/download', target: '_blank', rel: 'noopener' }, 'comfy.org/download'), '). It listens on http://127.0.0.1:8188 by default.') : null,
+ h('li', null, 'In ComfyUI Manager, install "TTS Audio Suite" (or clone ', h('a', { href: 'https://github.com/diodiogod/TTS-Audio-Suite', target: '_blank', rel: 'noopener' }, 'diodiogod/TTS-Audio-Suite'), ' into custom_nodes and run its install.py).'),
+ h('li', null, 'Restart ComfyUI, then press Check. The Qwen3-TTS models (Apache-2.0) download from Hugging Face on first use: about 4 GB for 1.7B.'))));
+ return;
+ }
+ fill(status, h('span', { class: 'chip ok' }, 'ready'), ` ComfyUI ${st.comfyui || ''} · TTS Audio Suite · ${st.gpu || 'GPU'}${st.vram_free_gb !== null ? ` · ${st.vram_free_gb} GB free now` : ''}`, st.can_listen ? '' : ' · (this suite version has no Qwen3-ASR: lines won\'t be checked)');
+ const custom = st.models.filter((m) => /CustomVoice/.test(m));
+ const pickModel = (m) => (/1\.7B/.test(m) ? 'CustomVoice 1.7B' : 'CustomVoice 0.6B');
+ const sampleText = h('textarea', { style: { minHeight: '60px' } }, 'Every city has a heartbeat. Ours runs on bikes.');
+ const player = h('div');
+ const is17 = /1\.7B/.test(qc.model);
+ add(panel,
+ field('Model', choiceChips(custom.map(pickModel), qc.model, (m) => save({ qwen: { model: m } }).then(draw)), is17 ? 'Takes a delivery instruction. Needs about 6.5 GB of free GPU memory while it speaks.' : 'Preset voices only, no delivery instruction. About half the memory of 1.7B.'),
+ field('Voice', h('select', { style: { maxWidth: '100%' }, onchange: (ev) => save({ qwen: { voice: ev.target.value } }) },
+ st.voices.map((name) => { const p = v.presets.find((x) => x.id === name); return h('option', { value: name, selected: qc.voice === name }, p ? `${name} · ${p.language} · ${p.about}` : name); })),
+ 'Built into the model (no cloning, no consent question). Each speaks all 10 languages; the listed one is its native language.'),
+ field('Language', h('select', { style: { maxWidth: '200px' }, onchange: (ev) => save({ qwen: { language: ev.target.value } }) }, st.languages.map((l) => h('option', { value: l, selected: qc.language === l }, l)))),
+ is17 ? field('Delivery', h('textarea', { style: { minHeight: '60px' }, onchange: (ev) => save({ qwen: { instruct: ev.target.value } }) }, qc.instruct), 'How it should sound, in plain words: pace, warmth, energy. Inline tags like [warm] are not read.') : null,
+ st.runtime_modes.length ? field('Runtime', h('select', { style: { maxWidth: '240px' }, onchange: (ev) => save({ qwen: { runtime_mode: ev.target.value } }) }, st.runtime_modes.map((m) => h('option', { value: m, selected: qc.runtime_mode === m }, m))), 'The suite\'s own setting. Try Main Environment first; if ComfyUI reports a transformers version error, choose its Shared Runtime.') : null,
+ field('Checks', h('label', { class: 'toggle' }, h('input', { type: 'checkbox', checked: qc.check, disabled: !st.can_listen, onchange: (ev) => save({ qwen: { check: ev.target.checked } }) }), 'Listen back to every line with Qwen3-ASR (retakes misread lines, gives word timings)')),
+ field('Try it', h('div', null, sampleText, h('div', { class: 'actions', style: { marginTop: '8px' } }, h('button', { class: 'btn', onclick: () => trySample('qwen', sampleText.value, player) }, 'Speak this line'), h('span', { class: 'meta' }, 'the first run downloads the model')), player)),
+ );
+ }
+
+ async function trySample(engine, text, player) {
+ fill(player, h('span', { class: 'meta' }, 'Speaking…'));
+ try {
+ const res = await fetch('/api/voice/sample', { method: 'POST', headers: { 'x-mortiflix': '1', 'content-type': 'application/json' }, body: JSON.stringify({ engine, text }) });
+ if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || `HTTP ${res.status}`);
+ const url = URL.createObjectURL(await res.blob());
+ fill(player, h('audio', { src: url, controls: true, autoplay: true, style: { width: '100%', marginTop: '8px' } }));
+ } catch (err) { fill(player, h('span', { class: 'err' }, err.message)); }
+ }
+
+ await draw();
+ return wrap;
+}
+
+const TIERS = ['free', 'starter', 'creator', 'pro', 'scale', 'business', 'enterprise'];
+const tierOk = (tier, need) => TIERS.indexOf(String(tier || 'free').replace(/_.*/, '')) >= TIERS.indexOf(need);
+
// ---------- start ----------
await loadStudio();