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.

Recording booth: narrate in your own voice (web, terminal, or imported files)

Gerrod Noordsy7bd5fff1b9ae
diff --git a/README.md b/README.md
index 39220bd..c5e080c 100644
--- a/README.md
+++ b/README.md
@@ -131,9 +131,13 @@ Pick a voice in **Settings › Narration** (or `mortiflix voice`):
- **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).
+- **Your own voice**: you read the script yourself, one short line at a time, in the **recording booth**: in the web
+ studio (hold Space to record, listen back, keep the best take), in a terminal (`mortiflix record <project>`), or by
+ importing files you recorded elsewhere (`mortiflix record <project> --import <folder>`). The studio asks for you when
+ the script is ready and carries on once every line has a kept take.
- **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.
+Generated lines are checked by speech to text and retaken if words go missing; word timings drive the animation.
Details: [docs/VOICE.md](docs/VOICE.md).
## Setup: music, assets and 3D
@@ -185,7 +189,7 @@ Mortiflix began as a hosted motion design studio, where every video was made sta
gates, with clients approving each one. This repository is that process, boiled down to one machine and opened up,
so it can be improved by more people than one studio.
-Not here yet (from the hosted studio, contributions welcome): a recording booth for your own narration, workflow
+Not here yet (from the hosted studio, contributions welcome): workflow
preferences learned from your pins, redo rounds on a delivered video, share links, music in the social-short pipeline,
and more pipelines (codebase explainers, 3D music videos, real estate films).
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4e05a58..3c27ae1 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -126,7 +126,7 @@ keys for sessions go to `session.env` through `setSessionKey`; only their names
## Narration (`src/voice/`)
-`voice/index.mjs` holds the studio's choice (`config.json` › `voice`: `none`, `elevenlabs` or `qwen`) and hands a
+`voice/index.mjs` holds the studio's choice (`config.json` › `voice`: `none`, `elevenlabs`, `qwen` or `own`) 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
@@ -134,6 +134,14 @@ similarity only). `voice/qwen.mjs` detects the GPU, reads the installed ComfyUI
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 recording booth** (`src/booth.mjs`) is the `own` engine: the owner reads the session's `voice/lines.json`. Every
+take is kept under `voice/takes/` with its measurements; the kept take of a line is copied to `voice/clips/<line>.wav`
+with the same report shape `vo.mjs` writes, plus the `script` it was recorded for, so `vo.mjs speak` knows which lines
+are done (and which changed since) and `build` works unchanged. Three front ends share it: the web booth
+(`web/app.js` `boothView`, an AudioWorklet in `web/booth-worklet.js`, takes uploaded as WAV to
+`/api/projects/<id>/booth/…`), the terminal booth (`src/record.mjs`, ffmpeg from the system microphone) and
+`mortiflix record --import` for files recorded elsewhere.
+
## 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/VOICE.md b/docs/VOICE.md
index b6e0b93..70aea5e 100644
--- a/docs/VOICE.md
+++ b/docs/VOICE.md
@@ -1,18 +1,37 @@
# 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.
+Mortiflix can narrate your videos four ways. Pick one in **Settings › Narration** (web) or with `mortiflix voice`.
+
+| | ElevenLabs | This computer (Qwen3-TTS) | Your own voice | No narration |
+|---|---|---|---|---|
+| Sound | the most natural voices; 90+ languages on Eleven v4 | very good; 10 languages | you | on-screen text and music carry it |
+| Cost | per character, on your ElevenLabs plan | free (your electricity) | free (your time) | free |
+| Privacy | text goes to ElevenLabs | nothing leaves your machine | 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 | a microphone (and ffmpeg for the terminal booth) | nothing |
+| Voices | thousands (yours, the defaults, the Voice Library, your own clones) | 9 built into the model | yours | |
+| Also | sound effects and music beds | | | |
+
+Generated lines are checked by speech to text after they're made: a take with missing or extra words is made again,
+and the timings of every word go to the animation. Your own recordings are timed line by line.
+
+## Your own voice: the recording booth
+
+Choose **Your own voice** in Settings › Narration (or `mortiflix voice own`). When a video reaches its narration, the
+studio writes the script as short lines and pauses the project with a note asking you to record. Then any of:
+
+- **In the web studio**: open the project and choose **Record narration**. Check your microphone and the room, then
+ read each line: hold **Space** (or the big button) while you speak, let go to stop. It plays the take back and flags
+ a take that clipped, is very quiet, or seems too short or long. Record as many takes as you like, **Enter** keeps
+ the selected one and moves on, ← → move between lines. Takes save as you go, so you can stop and come back. When
+ every line has a kept take, **Done** hands it to the studio. (Browsers allow the microphone on the computer the
+ studio runs on, or over HTTPS.)
+- **In a terminal**: `mortiflix record <project>`. **Enter** starts and stops a take, **p** plays it, **k** keeps it,
+ **n**/**b** move between lines, **q** stops for now. It records with ffmpeg from the default microphone; pick another
+ with `--device` (`mortiflix record --list-devices`).
+- **From files you recorded elsewhere** (a DAW, a phone): name each file after its line (`b01-1.wav`, `b01-2.m4a`, …;
+ the booth and `voice/lines.json` show the ids) and run `mortiflix record <project> --import <folder>`.
+
+If the studio rewrites a line after you recorded it, that line asks for a new take.
## ElevenLabs
diff --git a/pipelines/_shared/skills/voiceover/SKILL.md b/pipelines/_shared/skills/voiceover/SKILL.md
index b9b1b7a..12c66de 100644
--- a/pipelines/_shared/skills/voiceover/SKILL.md
+++ b/pipelines/_shared/skills/voiceover/SKILL.md
@@ -1,6 +1,6 @@
---
name: voiceover
-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.
+description: Narration, sound effects and music beds in the voice the studio set up (ElevenLabs, Qwen3-TTS on this machine's GPU, or the owner's own voice from the recording booth): 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
@@ -26,7 +26,13 @@ node $VO build voice/lines.json # voice/voice.wav + voice/timin
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`).
+- **`own`**: the owner narrates in their own voice. Write `voice/lines.json` exactly as below (short lines; put
+ delivery notes as a `[tag]` at the start, which the owner sees as direction; skip IPA and v4 tricks, a person reads
+ `script`). `node $VO speak voice/lines.json` then lists the lines still to record and prints the `mfx needs-you`
+ text that sends the owner to the recording booth (the web studio, `mortiflix record`, or importing files). Send it
+ and stop. When they resume, `speak` passes and `build` makes the track, timed per line. If you change a line after
+ it was recorded, `speak` asks for that line again.
+- **The owner's own recording** in `input/` (one long file, any engine): use it instead (cut it into lines as clips, then `build`).
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.
diff --git a/pipelines/_shared/skills/voiceover/vo.mjs b/pipelines/_shared/skills/voiceover/vo.mjs
index 22abfc3..02056e9 100644
--- a/pipelines/_shared/skills/voiceover/vo.mjs
+++ b/pipelines/_shared/skills/voiceover/vo.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-// vo.mjs: narration for a video, in the voice the studio set up (ElevenLabs, or Qwen3-TTS on this machine's GPU).
+// vo.mjs: narration for a video, in the voice the studio set up (ElevenLabs, Qwen3-TTS on this machine's GPU, or the
+// owner's own voice from the recording booth).
//
// 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]
@@ -248,6 +249,27 @@ function finish(list, report) {
if (bad.length) process.exitCode = 1;
}
+// ---------------------------------------------------------------------------------------------------------------
+// The owner's own voice: nothing to generate. The recording booth (web studio or `mortiflix record`) puts each kept
+// take in voice/clips/<id>.wav with a report whose `script` says which words it was recorded for.
+
+function speakOwn(list) {
+ const report = list.map((l) => {
+ const meta = existsSync(join(OUT, 'clips', `${l.id}.json`)) ? JSON.parse(readFileSync(join(OUT, 'clips', `${l.id}.json`), 'utf8')) : null;
+ const clip = existsSync(join(OUT, 'clips', `${l.id}.wav`));
+ const script = heard(l).replace(/\s+/g, ' ').trim();
+ const pass = Boolean(clip && meta?.engine === 'own voice' && (meta.script === undefined || meta.script === script));
+ return { id: l.id, engine: 'own voice', pass, ...(pass ? { take: meta.take, seconds: meta.seconds } : { problems: [clip && meta?.script !== script ? 'the line changed since it was recorded' : 'not recorded yet'] }) };
+ });
+ writeFileSync(join(OUT, 'speak-report.json'), JSON.stringify(report, null, 2));
+ const todo = report.filter((r) => !r.pass);
+ if (!todo.length) return console.log(`${list.length}/${list.length} lines recorded by the owner: run build next`);
+ const project = process.env.MFX_PROJECT || '<project>';
+ console.log(`${list.length - todo.length}/${list.length} lines recorded; ${todo.length} still need the owner's voice: ${todo.map((r) => r.id).join(', ')}`);
+ console.log(`Ask the owner (then stop; they resume when it's done):\n mfx needs-you "The narration script is ready: please record ${todo.length} line${todo.length === 1 ? '' : 's'} in the recording booth (open the project and choose Record narration, or run: mortiflix record ${project})."`);
+ process.exitCode = 1;
+}
+
// ---------------------------------------------------------------------------------------------------------------
// build: one track with gaps, and where every line and word lands in it
@@ -306,6 +328,8 @@ async function check() {
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 if (engine === 'own') {
+ console.log(JSON.stringify({ engine, note: 'The owner narrates in their own voice. Write voice/lines.json, then `speak` lists the lines still to record and the mfx needs-you text for the owner; after they record, `speak` passes and `build` makes the track (timed per line).' }, null, 2));
} 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));
}
@@ -316,6 +340,7 @@ else if (cmd === 'speak') {
const list = lines();
if (engine === 'elevenlabs') await speakEleven(list);
else if (engine === 'qwen') await speakQwen(list);
+ else if (engine === 'own') speakOwn(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/src/booth.mjs b/src/booth.mjs
new file mode 100644
index 0000000..ffe2ca6
--- /dev/null
+++ b/src/booth.mjs
@@ -0,0 +1,210 @@
+// The recording booth: the owner narrates a project's script in their own voice, one line at a time.
+// The session writes the script as voice/lines.json (the same file the AI voices read). Every take is kept on disk;
+// the take the owner keeps for a line becomes voice/clips/<line>.wav, exactly where vo.mjs puts a generated line,
+// so `vo.mjs build` makes the voice track the same way whichever voice spoke it.
+//
+// Three ways in, all through this module: the web booth (`mortiflix serve`), the terminal booth
+// (`mortiflix record <project>`), and importing files recorded elsewhere (`mortiflix record <project> --import <dir>`).
+//
+// projects/<id>/voice/lines.json the script, from the session
+// projects/<id>/voice/takes/<line>-<n>.wav every take
+// projects/<id>/voice/takes/takes.json what each take measured, and which one is kept
+// projects/<id>/voice/clips/<line>.wav the kept take (+ <line>.json, the same report shape vo.mjs writes)
+import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, rmSync, readdirSync } from 'node:fs';
+import { join, extname, basename } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { readJson, writeJson, withLock, UserError } from './studio.mjs';
+import { projectPaths } from './projects.mjs';
+
+export const MAX_TAKE_BYTES = 60 * 1024 * 1024; // ~10 minutes of 48 kHz 16-bit mono
+const LINE_ID = /^[A-Za-z0-9-]{1,40}$/;
+
+export function boothPaths(root, id) {
+ const voice = join(projectPaths(root, id).work, 'voice');
+ return { voice, lines: join(voice, 'lines.json'), takes: join(voice, 'takes'), index: join(voice, 'takes', 'takes.json'), clips: join(voice, 'clips'), lock: join(voice, '.booth-lock') };
+}
+
+// The words as they should be heard: audio tags and IPA out (the same rule vo.mjs uses).
+export const heard = (l) => String(l.script || l.text || '').replace(/\[[^\]]*\]/g, ' ').replace(/"?\/[^/\s][^/]*\/"?/g, ' ').replace(/\s+/g, ' ').trim();
+// Delivery notes for the reader: the [tags] at the start of the line, if any.
+const direction = (l) => [...String(l.text || '').matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]).join(', ') || null;
+// About 2.6 words a second is an unhurried narration pace.
+const estSeconds = (s) => Math.max(1, Math.round((s.split(/\s+/).filter(Boolean).length / 2.6) * 10) / 10);
+
+/** The script as the booth shows it, or null when the session hasn't written one yet. */
+export function readLines(root, id) {
+ const bp = boothPaths(root, id);
+ if (!existsSync(bp.lines)) return null;
+ let list;
+ try { list = JSON.parse(readFileSync(bp.lines, 'utf8')); } catch { throw new UserError('voice/lines.json is not valid JSON'); }
+ if (!Array.isArray(list)) throw new UserError('voice/lines.json must be a list of lines');
+ return list
+ .filter((l) => LINE_ID.test(l?.id || '') && heard(l))
+ .map((l) => {
+ const script = heard(l);
+ return { id: l.id, script, direction: direction(l), est_seconds: estSeconds(script), gap_after: l.gap_after ?? null };
+ });
+}
+
+function readIndex(bp) {
+ return existsSync(bp.index) ? readJson(bp.index) : [];
+}
+
+/** Lines, every take, and which lines still have no kept take. */
+export function boothStatus(root, id) {
+ const bp = boothPaths(root, id);
+ const lines = readLines(root, id);
+ const takes = readIndex(bp);
+ if (!lines) return { lines: null, takes, kept: 0, missing: [] };
+ // A kept take counts only while its line still reads the same: if the session rewrote the line, record it again.
+ const script = new Map(lines.map((l) => [l.id, l.script]));
+ const kept = new Set(takes.filter((t) => t.kept && (t.script === undefined || t.script === script.get(t.line_id))).map((t) => t.line_id));
+ return { lines, takes, kept: lines.filter((l) => kept.has(l.id)).length, missing: lines.filter((l) => !kept.has(l.id)).map((l) => l.id) };
+}
+
+// ------------------------------------------------------------------------------------------------ WAV
+
+/** Reads a PCM WAV (16/24/32-bit integer or 32-bit float, any rate, mono or stereo) and measures it. */
+export function wavInfo(buf) {
+ if (!Buffer.isBuffer(buf) || buf.length < 44 || buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') throw new UserError('not a WAV file');
+ let off = 12;
+ let fmt = null;
+ let data = null;
+ while (off + 8 <= buf.length) {
+ const tag = buf.toString('ascii', off, off + 4);
+ const size = buf.readUInt32LE(off + 4);
+ const body = off + 8;
+ if (tag === 'fmt ') fmt = { format: buf.readUInt16LE(body), channels: buf.readUInt16LE(body + 2), rate: buf.readUInt32LE(body + 4), bits: buf.readUInt16LE(body + 14) };
+ else if (tag === 'data') { data = { start: body, end: Math.min(buf.length, body + size) }; break; }
+ off = body + size + (size % 2);
+ }
+ if (!fmt || !data) throw new UserError('WAV is missing its format or data');
+ const pcm = fmt.format === 1 || fmt.format === 0xfffe;
+ const float = fmt.format === 3;
+ if (!(pcm && [16, 24, 32].includes(fmt.bits)) && !(float && fmt.bits === 32)) throw new UserError('WAV must be PCM (16/24/32-bit) or 32-bit float');
+ if (fmt.channels < 1 || fmt.channels > 2 || fmt.rate < 8000 || fmt.rate > 192000) throw new UserError('WAV must be mono or stereo, 8–192 kHz');
+ const bytes = fmt.bits / 8;
+ const frame = bytes * fmt.channels;
+ const frames = Math.floor((data.end - data.start) / frame);
+ let peak = 0;
+ let sum = 0;
+ for (let i = 0; i < frames; i++) {
+ const o = data.start + i * frame; // first channel is enough to judge levels
+ const v = float ? buf.readFloatLE(o) : bytes === 2 ? buf.readInt16LE(o) / 32768 : bytes === 3 ? buf.readIntLE(o, 3) / 8388608 : buf.readInt32LE(o) / 2147483648;
+ const a = Math.abs(v);
+ if (a > peak) peak = a;
+ sum += v * v;
+ }
+ const db = (x) => (x > 0 ? Math.round(20 * Math.log10(x) * 10) / 10 : -120);
+ return { rate: fmt.rate, channels: fmt.channels, duration_ms: Math.round((frames / fmt.rate) * 1000), peak_db: db(peak), rms_db: db(Math.sqrt(sum / Math.max(1, frames))) };
+}
+
+/** The booth's take checks, worded for the reader. */
+export function takeFlags(info, line) {
+ const flags = [];
+ if (info.peak_db > -0.5) flags.push('clipped');
+ if (info.peak_db < -28) flags.push('quiet');
+ const s = info.duration_ms / 1000;
+ if (line?.est_seconds && s < line.est_seconds * 0.5) flags.push('short');
+ if (line?.est_seconds && s > line.est_seconds * 2 + 1.5) flags.push('long');
+ return flags;
+}
+
+export const FLAG_ADVICE = {
+ clipped: 'it hit the top: move back a little or speak a touch softer',
+ quiet: 'it is very quiet: move closer to the microphone',
+ short: 'it seems short for this line: check it has every word',
+ long: 'it runs long: a little quicker, or trim the pauses',
+};
+
+// ------------------------------------------------------------------------------------------------ takes
+
+function lineFor(root, id, lineId) {
+ if (!LINE_ID.test(lineId || '')) throw new UserError(`bad line id "${lineId}"`);
+ const lines = readLines(root, id);
+ if (!lines) throw new UserError('This project has no script to record yet (voice/lines.json).');
+ const line = lines.find((l) => l.id === lineId);
+ if (!line) throw new UserError(`no line "${lineId}" in voice/lines.json`);
+ return line;
+}
+
+/** Saves a take (a WAV buffer) for a line. Returns the take record. */
+export function addTake(root, id, lineId, wav, { source = 'booth' } = {}) {
+ const line = lineFor(root, id, lineId);
+ if (wav.length > MAX_TAKE_BYTES) throw new UserError('that take is too long (over 10 minutes)');
+ const info = wavInfo(wav);
+ if (info.duration_ms < 200) throw new UserError('that take is under a fifth of a second: hold the button while you speak');
+ const bp = boothPaths(root, id);
+ mkdirSync(bp.takes, { recursive: true });
+ return withLock(bp.lock, () => {
+ const takes = readIndex(bp);
+ const take_no = takes.filter((t) => t.line_id === lineId).reduce((n, t) => Math.max(n, t.take_no), 0) + 1;
+ const file = `${lineId}-${take_no}.wav`;
+ writeFileSync(join(bp.takes, file), wav);
+ const take = { line_id: lineId, take_no, file, ...info, flags: takeFlags(info, line), source, kept: false, at: new Date().toISOString() };
+ takes.push(take);
+ writeJson(bp.index, takes);
+ return take;
+ });
+}
+
+/** Keeps one take for its line: it becomes voice/clips/<line>.wav for vo.mjs build. */
+export function keepTake(root, id, lineId, takeNo) {
+ const line = lineFor(root, id, lineId);
+ const bp = boothPaths(root, id);
+ return withLock(bp.lock, () => {
+ const takes = readIndex(bp);
+ const take = takes.find((t) => t.line_id === lineId && t.take_no === Number(takeNo));
+ if (!take) throw new UserError(`no take ${takeNo} for line ${lineId}`);
+ for (const t of takes) if (t.line_id === lineId) t.kept = t === take;
+ take.script = line.script;
+ writeJson(bp.index, takes);
+ mkdirSync(bp.clips, { recursive: true });
+ for (const ext of ['.mp3', '.wav', '.flac', '.opus']) rmSync(join(bp.clips, `${lineId}${ext}`), { force: true });
+ copyFileSync(join(bp.takes, take.file), join(bp.clips, `${lineId}.wav`));
+ // The same report shape vo.mjs writes for a generated line. No word timings: build times this line as a whole.
+ writeJson(join(bp.clips, `${lineId}.json`), {
+ id: lineId, engine: 'own voice', voice: 'the owner', script: line.script, take: take.take_no, seconds: take.duration_ms / 1000,
+ pass: true, peak_db: take.peak_db, rms_db: take.rms_db, flags: take.flags, words: [], transcript: null,
+ });
+ return take;
+ });
+}
+
+/** Absolute path of a take's audio, for playback. */
+export function takeFile(root, id, lineId, takeNo) {
+ const bp = boothPaths(root, id);
+ const take = readIndex(bp).find((t) => t.line_id === lineId && t.take_no === Number(takeNo));
+ if (!take) throw new UserError(`no take ${takeNo} for line ${lineId}`);
+ return join(bp.takes, take.file);
+}
+
+// ------------------------------------------------------------------------------------------------ import
+
+/**
+ * Imports takes recorded elsewhere (a DAW, a phone): files named after the line ids (`b01-1.wav`, `b01-1.m4a`, …).
+ * WAVs are read directly; other formats are converted with ffmpeg. Each imported file becomes a kept take.
+ */
+export function importFolder(root, id, dir) {
+ if (!existsSync(dir)) throw new UserError(`no folder ${dir}`);
+ const lines = readLines(root, id);
+ if (!lines) throw new UserError('This project has no script to record yet (voice/lines.json).');
+ const files = readdirSync(dir);
+ const done = [];
+ const skipped = [];
+ for (const line of lines) {
+ const f = files.find((n) => basename(n, extname(n)) === line.id && /\.(wav|mp3|m4a|flac|ogg|opus|aiff?)$/i.test(n));
+ if (!f) { skipped.push(line.id); continue; }
+ let wav;
+ if (/\.wav$/i.test(f)) wav = readFileSync(join(dir, f));
+ else {
+ const r = spawnSync('ffmpeg', ['-v', 'error', '-i', join(dir, f), '-ac', '1', '-ar', '48000', '-c:a', 'pcm_s16le', '-f', 'wav', 'pipe:1'], { maxBuffer: MAX_TAKE_BYTES });
+ if (r.status !== 0) throw new UserError(`could not convert ${f} (is ffmpeg installed?)`);
+ wav = r.stdout;
+ }
+ const take = addTake(root, id, line.id, wav, { source: 'import' });
+ keepTake(root, id, line.id, take.take_no);
+ done.push({ line: line.id, file: f, ...take });
+ }
+ return { imported: done, missing: skipped };
+}
diff --git a/src/cli.mjs b/src/cli.mjs
index c179e04..1e03fc8 100644
--- a/src/cli.mjs
+++ b/src/cli.mjs
@@ -12,6 +12,8 @@ import * as voice from './voice/index.mjs';
import * as keys from './keys.mjs';
import * as setup from './setup.mjs';
import { costText } from './usage.mjs';
+import * as booth from './booth.mjs';
+import * as rec from './record.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` }
@@ -43,8 +45,12 @@ const HELP = `${C.b('mortiflix')}: a motion design studio on your machine. Claud
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 own narrate in your own voice, recorded in the booth
mortiflix voice none no narration (on-screen text and music)
mortiflix voice test ["a line to speak"] hear the current voice
+ mortiflix record [<project>] [--device <mic>] the recording booth in this terminal: read each line, keep the best take
+ mortiflix record <project> --import <folder> use files you recorded elsewhere, named after the lines (b01-1.wav…)
+ mortiflix record --list-devices the microphones ffmpeg can record from
${C.b('3D')}
mortiflix blender [file.blend] open the studio's Blender, with its toolkits and Camera Flight
@@ -97,6 +103,7 @@ export async function run(argv = process.argv.slice(2)) {
case 'config': return config(root, rest);
case 'checks': return checks(root, rest);
case 'voice': return voiceCmd(root, rest);
+ case 'record': return recordCmd(root, rest, a);
case undefined: case 'help': return console.log(HELP);
default: throw new Error(`unknown command "${cmd}" (mortiflix help)`);
}
@@ -563,10 +570,11 @@ async function setupPart(root, id, st) {
if (id === 'narration') {
const v = voice.voiceConfig(root);
const local = st.gpu;
- console.log(` Now: ${C.b({ none: 'no narration', elevenlabs: 'ElevenLabs', qwen: 'Qwen3-TTS on this computer' }[v.engine])}`);
+ console.log(` Now: ${C.b({ none: 'no narration', elevenlabs: 'ElevenLabs', qwen: 'Qwen3-TTS on this computer', own: 'your own voice' }[v.engine])}`);
console.log(` 1. ElevenLabs: their voices, paid per character. Needs an API key.`);
console.log(` 2. This computer: Qwen3-TTS through ComfyUI, free and private. ${local.fits ? C.green(local.reason) : C.red(local.reason)}`);
console.log(' 3. No narration: on-screen text, music and sound.');
+ console.log(' 4. Your own voice: you read the script line by line in the recording booth (web studio or terminal), or import files.');
const pick = (await prompterOnce(` Which? ${C.dim(`[Enter keeps ${v.engine}]`)} `)).trim();
if (pick === '1') { await voiceCmd(root, ['elevenlabs']); }
else if (pick === '2') {
@@ -577,6 +585,7 @@ async function setupPart(root, id, st) {
}
await voiceCmd(root, ['local']);
} else if (pick === '3') { voice.saveVoice(root, { engine: 'none' }); console.log(' Narration off.'); }
+ else if (pick === '4') await voiceCmd(root, ['own']);
return;
}
if (id === 'music') {
@@ -697,12 +706,42 @@ function voiceOffer() {
return rec.fits ? `${eleven}, or ${C.b('mortiflix voice local')}: ${rec.reason} Free and private, through ComfyUI.` : `${eleven}.`;
}
+// The recording booth (src/booth.mjs) from a terminal, or importing takes recorded elsewhere.
+async function recordCmd(root, rest, a) {
+ if (a['list-devices']) {
+ const args = rec.listDevicesArgs();
+ if (!args) return console.log('Linux: `pactl list short sources` (PipeWire/PulseAudio) or `arecord -l` (ALSA). Pass one with --device pulse:<name> or --device alsa:hw:1.');
+ spawnSync('ffmpeg', args, { stdio: 'inherit' });
+ return;
+ }
+ const id = pick(root, rest[0]);
+ if (typeof a.import === 'string') {
+ const r = booth.importFolder(root, id, a.import);
+ for (const t of r.imported) console.log(` ${C.green('✔')} ${t.line} ${t.file} ${(t.duration_ms / 1000).toFixed(1)} s${t.flags.length ? C.red(` · ${booth.FLAG_ADVICE[t.flags[0]]}`) : ''}`);
+ if (r.missing.length) console.log(` ${C.red(`${r.missing.length} line(s) had no file`)}: ${r.missing.join(', ')}`);
+ return recordDone(root, id);
+ }
+ await rec.terminalBooth(root, id, { device: typeof a.device === 'string' ? a.device : null });
+ return recordDone(root, id);
+}
+
+async function recordDone(root, id) {
+ const st = booth.boothStatus(root, id);
+ if (st.missing.length) return console.log(`\n${st.kept} of ${st.lines.length} lines kept. Carry on any time: ${C.b(`mortiflix record ${id}`)}`);
+ console.log(`\n${C.green('✔')} Every line has a kept take.`);
+ const p = loadProject(root, id);
+ if (p.state === 'paused' && process.stdin.isTTY && !/^n/i.test((await prompterOnce('Give it to the studio now? [Y/n] ')).trim())) {
+ gates.resume(root, id);
+ console.log('Resumed: the studio builds the narration from your takes.');
+ }
+}
+
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])}`);
+ console.log(`Narration: ${C.b({ none: 'none', elevenlabs: 'ElevenLabs', qwen: 'Qwen3-TTS on this computer', own: 'your own voice (the recording booth)' }[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'}`);
@@ -711,6 +750,13 @@ async function voiceCmd(root, [sub, ...words]) {
return;
}
if (sub === 'none') { voice.saveVoice(root, { engine: 'none' }); return console.log('Narration off: videos use on-screen text, music and sound.'); }
+ if (sub === 'own') {
+ voice.saveVoice(root, { engine: 'own' });
+ console.log(`${C.green('✔')} Narration: your own voice. When a video reaches its narration, the studio writes the script as short lines and asks you to record them:`);
+ console.log(` in the web studio (the project's ${C.b('Record narration')} button), in a terminal (${C.b('mortiflix record <project>')}),`);
+ console.log(` or from files you recorded elsewhere (${C.b('mortiflix record <project> --import <folder>')}).`);
+ return;
+ }
if (sub === 'test') return voiceTest(root, words.join(' '));
const rl = prompter();
try {
diff --git a/src/record.mjs b/src/record.mjs
new file mode 100644
index 0000000..6b2316b
--- /dev/null
+++ b/src/record.mjs
@@ -0,0 +1,156 @@
+// The recording booth in a terminal: `mortiflix record <project>`. Same booth as the web studio (src/booth.mjs),
+// so takes made here and there are interchangeable. ffmpeg records from the system's default microphone:
+// Linux PulseAudio / PipeWire (-f pulse), else ALSA
+// macOS AVFoundation (-f avfoundation, device :0 unless --device)
+// Windows DirectShow (-f dshow, needs --device "audio=<name>"; --list-devices shows the names)
+import { spawn, spawnSync } from 'node:child_process';
+import { readFileSync, rmSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { emitKeypressEvents } from 'node:readline';
+import * as booth from './booth.mjs';
+
+const has = (bin) => spawnSync(bin, ['-version'], { stdio: 'ignore' }).status === 0;
+
+/** ffmpeg input arguments for a platform. `device` overrides: "pulse:<source>", "alsa:hw:1", ":1" (macOS), "audio=Mic" (Windows). */
+export function captureInput(platform = process.platform, device = null) {
+ if (device) {
+ const m = /^(pulse|alsa|avfoundation|dshow):(.+)$/.exec(device);
+ if (m) return ['-f', m[1], '-i', m[2]];
+ if (platform === 'darwin') return ['-f', 'avfoundation', '-i', device.startsWith(':') ? device : `:${device}`];
+ if (platform === 'win32') return ['-f', 'dshow', '-i', device.startsWith('audio=') ? device : `audio=${device}`];
+ return ['-f', 'pulse', '-i', device];
+ }
+ if (platform === 'darwin') return ['-f', 'avfoundation', '-i', ':0'];
+ if (platform === 'win32') return null; // DirectShow needs a device name
+ return ['-f', 'pulse', '-i', 'default'];
+}
+
+/** The command that lists microphones on this platform. */
+export function listDevicesArgs(platform = process.platform) {
+ if (platform === 'darwin') return ['-hide_banner', '-f', 'avfoundation', '-list_devices', 'true', '-i', ''];
+ if (platform === 'win32') return ['-hide_banner', '-list_devices', 'true', '-f', 'dshow', '-i', 'dummy'];
+ return null; // Linux: `pactl list short sources` (PipeWire/Pulse) or `arecord -l` (ALSA)
+}
+
+/** Plays a WAV with whatever this machine has. */
+function playFile(file) {
+ const players = [['ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet', file]], ['afplay', [file]], ['paplay', [file]], ['aplay', ['-q', file]]];
+ for (const [bin, args] of players) {
+ const r = spawnSync(bin, args, { stdio: 'ignore' });
+ if (!r.error) return true;
+ }
+ return false;
+}
+
+/** Starts recording; returns stop(), which resolves with the WAV once ffmpeg has finished (after a short post-roll). */
+function startCapture(input, file) {
+ const ff = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', ...input, '-ac', '1', '-ar', '48000', '-c:a', 'pcm_s16le', file], { stdio: ['pipe', 'ignore', 'pipe'] });
+ let err = '';
+ ff.stderr.on('data', (d) => { err += d; });
+ const done = new Promise((ok, fail) => {
+ ff.on('error', fail);
+ ff.on('close', (code) => (code === 0 || code === 255 ? ok() : fail(new Error(`ffmpeg could not record (${err.trim().split('\n').pop() || `exit ${code}`}). Try --device, or mortiflix record --list-devices.`))));
+ });
+ return {
+ stop: async () => {
+ await new Promise((r) => setTimeout(r, 400)); // post-roll: keep the end of the last word
+ ff.stdin.write('q');
+ ff.stdin.end();
+ await done;
+ return readFileSync(file);
+ },
+ failed: done,
+ };
+}
+
+const C = {
+ b: (s) => `\x1b[1m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m`,
+ green: (s) => `\x1b[32m${s}\x1b[0m`, acc: (s) => `\x1b[35m${s}\x1b[0m`,
+};
+
+/** The interactive terminal booth. Resolves with the booth status when the owner quits or finishes. */
+export async function terminalBooth(root, id, { device = null, out = process.stdout, input = process.stdin } = {}) {
+ if (!input.isTTY) throw new Error('the terminal booth needs an interactive terminal (or use --import <folder>)');
+ if (!has('ffmpeg')) throw new Error('recording needs ffmpeg (https://ffmpeg.org/download.html)');
+ const inArgs = captureInput(process.platform, device);
+ if (!inArgs) throw new Error('on Windows, pass the microphone: --device "audio=<name>" (mortiflix record --list-devices)');
+ let st = booth.boothStatus(root, id);
+ if (!st.lines) throw new Error('this project has no script to record yet (the studio writes voice/lines.json first)');
+
+ const tmp = mkdtempSync(join(tmpdir(), 'mfx-rec-'));
+ const say = (s = '') => out.write(`${s}\n`);
+ let idx = Math.max(0, st.lines.findIndex((l) => st.missing.includes(l.id)));
+ let capture = null;
+ let busy = false;
+
+ const takesFor = (lineId) => st.takes.filter((t) => t.line_id === lineId);
+ const show = () => {
+ const l = st.lines[idx];
+ const takes = takesFor(l.id);
+ say(`\n${C.b(`Line ${idx + 1} of ${st.lines.length}`)} ${C.dim(`${st.kept} kept`)}${l.direction ? ` ${C.acc(`[${l.direction}]`)}` : ''} ${C.dim(`about ${l.est_seconds} s`)}`);
+ if (st.lines[idx - 1]) say(C.dim(` ${st.lines[idx - 1].script}`));
+ say(` ${C.b(l.script)}`);
+ if (st.lines[idx + 1]) say(C.dim(` ${st.lines[idx + 1].script}`));
+ if (takes.length) say(` takes: ${takes.map((t) => `${t.take_no}${t.kept ? '✓' : ''} (${(t.duration_ms / 1000).toFixed(1)} s)`).join(' ')}`);
+ say(C.dim(' [Enter] record / stop [p] play last take [k] keep last take [1-9] play that take [n] next [b] back [q] quit'));
+ };
+
+ emitKeypressEvents(input);
+ input.setRawMode(true);
+ input.resume();
+ show();
+ try {
+ await new Promise((resolve) => {
+ input.on('keypress', async (str, key) => {
+ if (busy) return;
+ const l = st.lines[idx];
+ const last = takesFor(l.id).at(-1);
+ try {
+ busy = true;
+ if (key?.ctrl && key.name === 'c') return resolve();
+ if (key?.name === 'return') {
+ if (!capture) {
+ capture = startCapture(inArgs, join(tmp, 'take.wav'));
+ capture.failed.catch((e) => { say(C.red(e.message)); capture = null; });
+ say(C.red(' ● recording… press Enter to stop'));
+ } else {
+ const wav = await capture.stop();
+ capture = null;
+ const t = booth.addTake(root, id, l.id, wav, { source: 'terminal' });
+ st = booth.boothStatus(root, id);
+ say(` take ${t.take_no}: ${(t.duration_ms / 1000).toFixed(1)} s, peak ${t.peak_db} dB${t.flags.length ? C.red(` · ${booth.FLAG_ADVICE[t.flags[0]]}`) : ''}`);
+ if (!playFile(booth.takeFile(root, id, l.id, t.take_no))) say(C.dim(' (no audio player found to play it back: install ffmpeg\'s ffplay)'));
+ say(C.dim(' [k] keep it [Enter] try again [p] play it again'));
+ }
+ } else if (capture) {
+ // While recording, only Enter (stop) does anything.
+ } else if (str === 'p' && last) playFile(booth.takeFile(root, id, l.id, last.take_no));
+ else if (/^[1-9]$/.test(str || '') && takesFor(l.id)[Number(str) - 1]) playFile(booth.takeFile(root, id, l.id, Number(str)));
+ else if (str === 'k' && last) {
+ booth.keepTake(root, id, l.id, last.take_no);
+ st = booth.boothStatus(root, id);
+ say(C.green(` ✔ kept take ${last.take_no}`));
+ if (!st.missing.length) return resolve();
+ const next = st.lines.findIndex((x, i) => i > idx && st.missing.includes(x.id));
+ idx = next !== -1 ? next : st.lines.findIndex((x) => st.missing.includes(x.id));
+ show();
+ } else if (str === 'n') { idx = Math.min(st.lines.length - 1, idx + 1); show(); }
+ else if (str === 'b') { idx = Math.max(0, idx - 1); show(); }
+ else if (str === 'q') return resolve();
+ } catch (e) {
+ say(C.red(` ${e.message}`));
+ } finally {
+ busy = false;
+ }
+ });
+ });
+ } finally {
+ if (capture) await capture.stop().catch(() => {});
+ input.setRawMode(false);
+ input.pause();
+ input.removeAllListeners('keypress');
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ return booth.boothStatus(root, id);
+}
diff --git a/src/setup.mjs b/src/setup.mjs
index 2cfcf04..31c111f 100644
--- a/src/setup.mjs
+++ b/src/setup.mjs
@@ -39,7 +39,7 @@ export const PARTS = [
id: 'narration',
title: 'Narration',
why: 'A voice reads the script, and the animation is timed to its words.',
- needs: 'Either an ElevenLabs API key (their voices, paid per character), or ComfyUI with Qwen3-TTS on your own NVIDIA graphics card (free and private, about 10 GB to install), or no narration.',
+ needs: 'Either an ElevenLabs API key (their voices, paid per character), or ComfyUI with Qwen3-TTS on your own NVIDIA graphics card (free and private, about 10 GB to install), or your own voice (you record the lines in the booth), or no narration.',
},
{
id: 'music',
diff --git a/src/torch.mjs b/src/torch.mjs
index c0526e4..9c45945 100644
--- a/src/torch.mjs
+++ b/src/torch.mjs
@@ -1,6 +1,7 @@
// Passing the torch: before every session the working folder gets a fresh CLAUDE.md (where things stand, what the
// owner said, the error checks, the brief) plus a clean copy of the pinned pipeline, its skills and the gate
// protocol. Every session ends with `mfx handoff`, which appends to JOURNAL.md; the next one starts from there.
+import { voiceConfig } from './voice/index.mjs';
import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, cpSync, readdirSync, copyFileSync } from 'node:fs';
import { join } from 'node:path';
import { REPO, paths } from './studio.mjs';
@@ -41,6 +42,7 @@ function studioSection(root) {
if (st.music.engine === 'none') lines.push('- **Music:** the owner chose no music. Skip any music step with a short note (`mfx step-done`), never improvise one.');
else if (st.strudel.ok && st.chrome.ok) lines.push(`- **Music:** Strudel ${st.strudel.version}, scored after the animatic with the **music** skill.${st.music.midi ? ' The owner also wants the **MIDI pack** (every part, the cue sheet) with the final.' : ''}`);
else lines.push('- **Music:** Strudel isn\'t set up yet. When a music step is ready, `mfx needs-you`: "Run `mortiflix setup music`, then resume."');
+ if (voiceConfig(root).engine === 'own') lines.push('- **Narration:** the owner narrates in their **own voice**. Write `voice/lines.json` as usual (short lines; delivery notes as a `[tag]` at the start, which the owner sees as direction), then `vo.mjs speak`: it lists the lines that still need a recording and the exact `mfx needs-you` text that sends the owner to the recording booth. When they resume, `speak` passes and `build` makes the track (timed per line).');
if (st.assets.sites.length && st['browser-harness'].ok) {
lines.push(`- **Asset sites** (the **assets** skill, in the owner's own Chrome): ${st.assets.sites.map((x) => `${x.url}${x.notes ? ` (${x.notes})` : ''}`).join('; ')}. Only these.`);
} else lines.push('- **Asset sites:** none. Make every visual yourself; never download assets from the web.');
diff --git a/src/voice/index.mjs b/src/voice/index.mjs
index f39f730..f0e7324 100644
--- a/src/voice/index.mjs
+++ b/src/voice/index.mjs
@@ -1,10 +1,11 @@
-// The studio's narration setup: which engine (ElevenLabs, local Qwen3-TTS, or none) and its settings. The settings
+// The studio's narration setup: which engine (ElevenLabs, local Qwen3-TTS, the owner's own voice, 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'];
+// own: the owner narrates in their own voice, line by line, in the recording booth (src/booth.mjs).
+export const ENGINES = ['none', 'elevenlabs', 'qwen', 'own'];
export function voiceConfig(root) {
const v = loadConfig(root).voice || {};
diff --git a/src/web/server.mjs b/src/web/server.mjs
index 445dde4..dfc42b1 100644
--- a/src/web/server.mjs
+++ b/src/web/server.mjs
@@ -17,6 +17,7 @@ import { Runner, BACKENDS } from '../runner.mjs';
import * as voice from '../voice/index.mjs';
import * as keys from '../keys.mjs';
import * as setup from '../setup.mjs';
+import * as booth from '../booth.mjs';
import { costText } from '../usage.mjs';
const MIME = {
@@ -185,6 +186,39 @@ export async function startServer(root, { port = 4646, host = '127.0.0.1', runne
const { answer } = await json(req);
return after(gates.answerQuestion(root, id, m[1], answer ?? null));
}
+ if (sub.startsWith('/booth')) return boothApi(req, res, id, sub, method, after);
+ return send(res, 404, { error: 'not found' });
+ }
+
+ // The recording booth (src/booth.mjs): the script, takes as raw WAV bodies, keeping a take, and "done", which
+ // resumes the project when it was waiting for the recording.
+ async function boothApi(req, res, id, sub, method, after) {
+ let m;
+ if (sub === '/booth' && method === 'GET') {
+ const p = loadProject(root, id);
+ return send(res, 200, { project: { id, title: p.title, state: p.state, needs_you: p.needs_you }, engine: voice.voiceConfig(root).engine, ...booth.boothStatus(root, id), advice: booth.FLAG_ADVICE });
+ }
+ if ((m = sub.match(/^\/booth\/lines\/([A-Za-z0-9-]{1,40})\/takes$/)) && method === 'POST') {
+ const take = booth.addTake(root, id, m[1], await rawBody(req, booth.MAX_TAKE_BYTES));
+ changed();
+ return send(res, 200, { take });
+ }
+ if ((m = sub.match(/^\/booth\/lines\/([A-Za-z0-9-]{1,40})\/takes\/(\d+)\/keep$/)) && method === 'POST') {
+ return after({ take: booth.keepTake(root, id, m[1], Number(m[2])) });
+ }
+ if ((m = sub.match(/^\/booth\/lines\/([A-Za-z0-9-]{1,40})\/takes\/(\d+)\/audio$/)) && method === 'GET') {
+ const file = booth.takeFile(root, id, m[1], Number(m[2]));
+ res.writeHead(200, { 'content-type': 'audio/wav', 'content-length': statSync(file).size, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
+ return createReadStream(file).pipe(res);
+ }
+ if (sub === '/booth/done' && method === 'POST') {
+ const st = booth.boothStatus(root, id);
+ if (!st.lines) throw new BadRequest('there is no script to record yet');
+ if (st.missing.length) return send(res, 409, { error: `${st.missing.length} line(s) still need a kept take: ${st.missing.join(', ')}`, missing: st.missing });
+ const p = loadProject(root, id);
+ if (p.state === 'paused') gates.resume(root, id);
+ return after({ resumed: p.state === 'paused' });
+ }
return send(res, 404, { error: 'not found' });
}
@@ -343,6 +377,17 @@ function same(a, b) {
return x.length === y.length && timingSafeEqual(x, y);
}
+// A raw request body (a recorded take), refused past `limit` bytes.
+function rawBody(req, limit) {
+ return new Promise((ok, fail) => {
+ const parts = [];
+ let n = 0;
+ req.on('data', (d) => { n += d.length; if (n > limit) { fail(new BadRequest('too large')); req.destroy(); } else parts.push(d); });
+ req.on('end', () => ok(Buffer.concat(parts)));
+ req.on('error', fail);
+ });
+}
+
function json(req, limit = 2_000_000) {
return new Promise((ok, fail) => {
let body = '';
diff --git a/test/booth.test.mjs b/test/booth.test.mjs
new file mode 100644
index 0000000..50d4897
--- /dev/null
+++ b/test/booth.test.mjs
@@ -0,0 +1,207 @@
+// The recording booth: the shared core (takes, keeping, checks, imports), the web API, the session side (vo.mjs with
+// the owner's own voice) and the terminal booth's microphone setup. Takes are generated tones; no microphone needed.
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { request } from 'node:http';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { randomBytes } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { tempStudio } from './helpers.mjs';
+import { REPO } from '../src/studio.mjs';
+import { createProject, projectPaths } from '../src/projects.mjs';
+import * as booth from '../src/booth.mjs';
+import { captureInput } from '../src/record.mjs';
+import { startServer } from '../src/web/server.mjs';
+import { run as cli } from '../src/cli.mjs';
+
+const VO = join(REPO, 'pipelines/_shared/skills/voiceover/vo.mjs');
+
+// A mono 16-bit WAV: a sine at `amp` (0..1) for `seconds`.
+function tone(seconds, amp = 0.3, rate = 48000) {
+ const n = Math.round(seconds * rate);
+ const buf = Buffer.alloc(44 + n * 2);
+ buf.write('RIFF', 0); buf.writeUInt32LE(36 + n * 2, 4); buf.write('WAVE', 8); buf.write('fmt ', 12);
+ buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(1, 22); buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * 2, 28); buf.writeUInt16LE(2, 32); buf.writeUInt16LE(16, 34); buf.write('data', 36); buf.writeUInt32LE(n * 2, 40);
+ for (let i = 0; i < n; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 220 * i) / rate) * amp * 32767), 44 + i * 2);
+ return buf;
+}
+
+const LINES = [
+ { 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 bicycles.' },
+];
+
+function projectWithScript(t, lines = LINES) {
+ const root = tempStudio(t);
+ const { id } = createProject(root, { pipeline: 'logo-sting', title: 'Booth test' });
+ const voice = join(projectPaths(root, id).work, 'voice');
+ mkdirSync(voice, { recursive: true });
+ writeFileSync(join(voice, 'lines.json'), JSON.stringify(lines));
+ return { root, id, voice };
+}
+
+test('booth: the script as the reader sees it, takes, checks and keeping', (t) => {
+ const { root, id, voice } = projectWithScript(t);
+ const lines = booth.readLines(root, id);
+ assert.deepEqual(lines.map((l) => [l.id, l.script, l.direction]), [['b01-1', 'Every city has a heartbeat.', 'warm, unhurried'], ['b01-2', 'Ours runs on bicycles.', null]]);
+ assert.ok(lines[0].est_seconds >= 1);
+
+ // Measured and checked: a quiet take, a clipped one, a good one.
+ const quiet = booth.addTake(root, id, 'b01-1', tone(1.5, 0.01));
+ assert.equal(quiet.take_no, 1);
+ assert.ok(quiet.flags.includes('quiet'));
+ const hot = booth.addTake(root, id, 'b01-1', tone(1.5, 1));
+ assert.ok(hot.flags.includes('clipped'));
+ const good = booth.addTake(root, id, 'b01-1', tone(1.8, 0.4));
+ assert.deepEqual(good.flags, []);
+ assert.equal(good.take_no, 3);
+ assert.equal(good.duration_ms, 1800);
+
+ assert.deepEqual(booth.boothStatus(root, id).missing, ['b01-1', 'b01-2']);
+ booth.keepTake(root, id, 'b01-1', 3);
+ // The kept take is where vo.mjs looks for a line, with the same report shape.
+ assert.ok(existsSync(join(voice, 'clips', 'b01-1.wav')));
+ const rep = JSON.parse(readFileSync(join(voice, 'clips', 'b01-1.json'), 'utf8'));
+ assert.equal(rep.engine, 'own voice');
+ assert.equal(rep.take, 3);
+ assert.equal(rep.script, 'Every city has a heartbeat.');
+ const st = booth.boothStatus(root, id);
+ assert.equal(st.kept, 1);
+ assert.deepEqual(st.missing, ['b01-2']);
+
+ // Keeping another take moves the mark; only one take per line is kept.
+ booth.keepTake(root, id, 'b01-1', 1);
+ assert.deepEqual(booth.boothStatus(root, id).takes.filter((x) => x.kept).map((x) => x.take_no), [1]);
+
+ // If the session rewrites a line, its old take no longer counts.
+ writeFileSync(join(voice, 'lines.json'), JSON.stringify([{ ...LINES[0], script: 'Every town has a heartbeat.' }, LINES[1]]));
+ assert.deepEqual(booth.boothStatus(root, id).missing, ['b01-1', 'b01-2']);
+
+ // Bad input is refused with a reason.
+ assert.throws(() => booth.addTake(root, id, 'b01-1', Buffer.from('not audio at all, really not')), /WAV/);
+ assert.throws(() => booth.addTake(root, id, 'nope', tone(1)), /no line/);
+ assert.throws(() => booth.addTake(root, id, 'b01-2', tone(0.05)), /fifth of a second/);
+});
+
+test('booth: importing files recorded elsewhere keeps one take per line', (t) => {
+ const { root, id } = projectWithScript(t);
+ const dir = join(tmpdir(), `mfx-import-${randomBytes(3).toString('hex')}`);
+ mkdirSync(dir);
+ t.after(() => spawnSync('rm', ['-rf', dir]));
+ writeFileSync(join(dir, 'b01-2.wav'), tone(1.2));
+ writeFileSync(join(dir, 'notes.txt'), 'ignored');
+ const r = booth.importFolder(root, id, dir);
+ assert.deepEqual(r.imported.map((x) => x.line), ['b01-2']);
+ assert.deepEqual(r.missing, ['b01-1']);
+ assert.deepEqual(booth.boothStatus(root, id).missing, ['b01-1']);
+ assert.equal(booth.boothStatus(root, id).takes[0].source, 'import');
+});
+
+test('booth: `mortiflix record --import` from the command line', async (t) => {
+ const { root, id } = projectWithScript(t);
+ const dir = join(tmpdir(), `mfx-import-${randomBytes(3).toString('hex')}`);
+ mkdirSync(dir);
+ t.after(() => spawnSync('rm', ['-rf', dir]));
+ for (const l of LINES) writeFileSync(join(dir, `${l.id}.wav`), tone(1.5));
+ const log = [];
+ const orig = console.log;
+ console.log = (...a) => log.push(a.join(' '));
+ try { await cli(['record', id, '--import', dir, '--studio', root]); } finally { console.log = orig; }
+ assert.deepEqual(booth.boothStatus(root, id).missing, []);
+ assert.match(log.join('\n'), /Every line has a kept take/);
+});
+
+test('booth: the terminal booth records from each platform\'s microphone', () => {
+ assert.deepEqual(captureInput('linux'), ['-f', 'pulse', '-i', 'default']);
+ assert.deepEqual(captureInput('darwin'), ['-f', 'avfoundation', '-i', ':0']);
+ assert.equal(captureInput('win32'), null); // DirectShow needs a device name
+ assert.deepEqual(captureInput('win32', 'Microphone (USB)'), ['-f', 'dshow', '-i', 'audio=Microphone (USB)']);
+ assert.deepEqual(captureInput('darwin', '2'), ['-f', 'avfoundation', '-i', ':2']);
+ assert.deepEqual(captureInput('linux', 'alsa:hw:1'), ['-f', 'alsa', '-i', 'hw:1']);
+});
+
+function call(socketPath, method, path, { body, raw } = {}) {
+ return new Promise((ok, fail) => {
+ const data = raw ?? (body !== undefined ? JSON.stringify(body) : null);
+ const req = request({ socketPath, method, path, headers: { host: 'localhost', ...(method !== 'GET' ? { 'x-mortiflix': '1' } : {}) } }, (res) => {
+ const chunks = [];
+ res.on('data', (c) => chunks.push(c));
+ res.on('end', () => {
+ const buf = Buffer.concat(chunks);
+ let json = null;
+ try { json = JSON.parse(buf.toString()); } catch { /* audio */ }
+ ok({ status: res.statusCode, headers: res.headers, json, buf });
+ });
+ });
+ req.on('error', fail);
+ req.end(data);
+ });
+}
+
+test('booth: the web API records, keeps, plays back and hands over', async (t) => {
+ const { root, id } = projectWithScript(t);
+ const socketPath = join(tmpdir(), `mfx-booth-${randomBytes(4).toString('hex')}.sock`);
+ const srv = await startServer(root, { socketPath, quiet: true });
+ t.after(() => srv.close());
+ const s = (...a) => call(socketPath, ...a);
+
+ const view = (await s('GET', `/api/projects/${id}/booth`)).json;
+ assert.equal(view.lines.length, 2);
+ assert.equal(view.lines[0].direction, 'warm, unhurried');
+ assert.ok(view.advice.clipped);
+
+ const up = await s('POST', `/api/projects/${id}/booth/lines/b01-1/takes`, { raw: tone(1.4) });
+ assert.equal(up.status, 200);
+ assert.equal(up.json.take.take_no, 1);
+ assert.equal((await s('POST', `/api/projects/${id}/booth/lines/b01-1/takes`, { raw: Buffer.from('nope') })).status, 400);
+
+ const audio = await s('GET', `/api/projects/${id}/booth/lines/b01-1/takes/1/audio`);
+ assert.equal(audio.headers['content-type'], 'audio/wav');
+ assert.equal(audio.buf.toString('ascii', 0, 4), 'RIFF');
+
+ assert.equal((await s('POST', `/api/projects/${id}/booth/lines/b01-1/takes/1/keep`)).status, 200);
+ const early = await s('POST', `/api/projects/${id}/booth/done`);
+ assert.equal(early.status, 409);
+ assert.deepEqual(early.json.missing, ['b01-2']);
+
+ await s('POST', `/api/projects/${id}/booth/lines/b01-2/takes`, { raw: tone(1.2) });
+ await s('POST', `/api/projects/${id}/booth/lines/b01-2/takes/1/keep`);
+ const done = await s('POST', `/api/projects/${id}/booth/done`);
+ assert.equal(done.status, 200);
+ assert.equal(done.json.resumed, false); // a draft isn't waiting on the recording
+
+ // Writes still need the X-Mortiflix header.
+ const csrf = await new Promise((ok) => {
+ const req = request({ socketPath, method: 'POST', path: `/api/projects/${id}/booth/done`, headers: { host: 'localhost' } }, (res) => { res.resume(); ok(res.statusCode); });
+ req.end();
+ });
+ assert.equal(csrf, 403);
+});
+
+test('vo.mjs with the owner\'s own voice: asks for the recording, then builds from the kept takes', (t) => {
+ const { root, id, voice } = projectWithScript(t);
+ const work = projectPaths(root, id).work;
+ const env = { ...process.env, MFX_VOICE: JSON.stringify({ engine: 'own' }), MFX_PROJECT: id };
+ const vo = (...args) => spawnSync('node', [VO, ...args], { cwd: work, env, encoding: 'utf8' });
+
+ const before = vo('speak', 'voice/lines.json');
+ assert.equal(before.status, 1);
+ assert.match(before.stdout, /2 still need the owner's voice: b01-1, b01-2/);
+ assert.match(before.stdout, new RegExp(`mfx needs-you ".*mortiflix record ${id}`));
+
+ for (const l of LINES) booth.keepTake(root, id, l.id, booth.addTake(root, id, l.id, tone(1.5)).take_no);
+ const after = vo('speak', 'voice/lines.json');
+ assert.equal(after.status, 0, after.stderr);
+ assert.match(after.stdout, /2\/2 lines recorded/);
+
+ if (spawnSync('ffmpeg', ['-version']).status !== 0) return t.skip('no ffmpeg for build');
+ const built = vo('build', 'voice/lines.json');
+ assert.equal(built.status, 0, built.stderr);
+ const timing = JSON.parse(readFileSync(join(voice, 'timing.json'), 'utf8'));
+ assert.equal(timing.lines.length, 2);
+ assert.equal(timing.lines[0].timing, 'line');
+ assert.ok(Math.abs(timing.lines[1].start - 2.0) < 0.05); // 1.5 s take + 0.5 s gap
+});
diff --git a/web/app.css b/web/app.css
index 998765a..ad0b5f8 100644
--- a/web/app.css
+++ b/web/app.css
@@ -237,3 +237,34 @@ details > summary { cursor: pointer; color: var(--muted); font-size: 13px; paddi
.tool-row { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; margin: 10px 0; }
.tool-row .chip { white-space: normal; }
.setup-log { max-height: 220px; overflow: auto; background: var(--raise); border-radius: 8px; padding: 8px 10px; margin-top: 8px; font-size: 12px; line-height: 1.45; white-space: pre-wrap; word-break: break-all; }
+
+/* ---------- recording booth ---------- */
+.booth-tips { color: var(--body); margin: 0 0 8px; padding-left: 18px; }
+.booth-tips li { margin: 4px 0; }
+.booth-meter { height: 6px; background: var(--line); margin: 12px 0 6px; max-width: 360px; }
+.booth-meter i { display: block; height: 100%; width: 0; background: var(--ok); transition: width 60ms linear; }
+.booth-meter i.hot { background: var(--bad); }
+.booth-stage { padding-top: 6px; }
+.booth-progress { display: flex; gap: 14px; align-items: center; color: var(--muted); font-size: 13px; flex-wrap: wrap; }
+.booth-dots { display: flex; gap: 4px; list-style: none; padding: 0; margin: 0; flex-wrap: wrap; }
+.booth-dots button { width: 10px; height: 10px; border: 1px solid var(--muted); background: transparent; padding: 0; cursor: pointer; display: block; }
+.booth-dots .done button { background: var(--ok); border-color: var(--ok); }
+.booth-dots .current button { outline: 2px solid var(--ink); outline-offset: 2px; }
+.booth-script { margin: 34px 0 12px; border-left: 3px solid var(--accent); padding-left: 18px; }
+.booth-line { font-family: var(--display); color: var(--ink); font-size: clamp(22px, 3.2vw, 34px); line-height: 1.3; margin: 10px 0; }
+.booth-near { color: var(--faint); font-size: 15px; margin: 0; }
+.booth-direction { display: flex; gap: 12px; align-items: center; margin-bottom: 26px; }
+.booth-controls { display: flex; gap: 18px; align-items: center; padding: 18px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
+.booth-rec { width: 76px; height: 76px; border-radius: 50%; border: 2px solid var(--accent); background: transparent; cursor: pointer; display: grid; place-items: center; touch-action: none; }
+.booth-rec-dot { width: 30px; height: 30px; border-radius: 50%; background: var(--accent); transition: transform 120ms ease, border-radius 120ms ease; }
+.is-recording .booth-rec { border-color: var(--bad); }
+.is-recording .booth-rec-dot { background: var(--bad); transform: scale(0.8); border-radius: 6px; }
+.booth-after { padding: 16px 0; }
+.booth-takes { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; }
+.booth-take { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; border: 1px solid var(--line); background: transparent; color: var(--body); padding: 6px 12px; cursor: pointer; font-size: 13px; }
+.booth-take b { color: var(--ink); font-weight: 500; }
+.booth-take.on { border-color: var(--ink); }
+.booth-take.kept b::after { content: " ✓"; color: var(--ok); }
+.booth-keys { margin-top: 18px; color: var(--faint); }
+.booth-review .row { grid-template-columns: 28px 1fr auto; }
+.booth-review .main span { white-space: normal; }
diff --git a/web/app.js b/web/app.js
index dcbaf43..f20de5a 100644
--- a/web/app.js
+++ b/web/app.js
@@ -6,6 +6,7 @@ const $status = document.getElementById('top-status');
let studio = null;
let projectsCache = [];
let current = { name: null, refresh: null };
+let leaveView = null; // a view that holds something open (the booth's microphone) releases it here
// ---------- helpers ----------
@@ -71,6 +72,7 @@ const routes = [
[/^new(?:\/([a-z0-9_-]+))?$/, newView, 'new'],
[/^p\/([a-z0-9-]+)$/, projectView, 'studio'],
[/^p\/([a-z0-9-]+)\/review\/([a-z0-9_-]+)(?:\/(\d+))?$/, reviewView, 'studio'],
+ [/^p\/([a-z0-9-]+)\/booth$/, boothView, 'studio'],
[/^pipelines$/, pipelinesView, 'pipelines'],
[/^settings$/, settingsView, 'settings'],
];
@@ -80,6 +82,7 @@ async function render() {
const hit = routes.find(([re]) => re.test(path));
const [re, view, nav] = hit || routes[0];
for (const a of document.querySelectorAll('[data-nav]')) a.classList.toggle('on', a.dataset.nav === nav);
+ if (leaveView) { try { leaveView(); } catch { /* already closed */ } leaveView = null; }
current = { name: view.name, refresh: null, args: path.match(re)?.slice(1) || [] };
// The review room is wider; the header widens with it so both keep one left edge.
document.body.classList.toggle('wide', view === reviewView);
@@ -238,6 +241,13 @@ async function projectView(id) {
const questions = openQs.length ? h('section', null, h('h2', null, 'Questions'), openQs.map((q) => questionForm(id, q))) : null;
+ // Your own voice: once the script exists, the booth is one click away.
+ const b = await api(`/api/projects/${id}/booth`).catch(() => null);
+ const narration = b?.lines && (b.engine === 'own' || b.takes.length) ? h('div', { class: b.missing.length ? 'turn-line' : 'state-line' },
+ h('div', null, h('div', { class: 'what' }, b.missing.length ? 'Record your narration' : 'Narration recorded'),
+ h('div', { class: 'why' }, `${b.kept} of ${b.lines.length} lines kept${b.missing.length ? ' · or in a terminal: ' : ''}`, b.missing.length ? h('code', null, `mortiflix record ${id}`) : null)),
+ h('a', { class: b.missing.length ? 'btn primary' : 'btn', href: `#/p/${id}/booth` }, b.missing.length ? 'Record narration' : 'Open the booth')) : null;
+
const subsByStep = (key) => d.submissions.filter((s) => s.step === key);
const steps = h('section', null, h('h2', null, 'Steps', h('span', { class: 'count' }, `${d.steps.filter((s) => ['approved', 'done', 'skipped'].includes(s.state)).length}/${d.steps.length}`)),
h('ul', { class: 'rows' }, d.steps.map((s) => h('li', { class: 'row' }, icon(s.state),
@@ -270,7 +280,7 @@ async function projectView(id) {
mount(
h('a', { class: 'crumb', href: '#/' }, '← Studio'),
h('div', { class: 'head' }, h('div', null, h('h1', null, p.title), h('div', { class: 'sub' }, h('span', { class: 'chip' }, d.pipeline.name), h('span', null, p.backend ? `${BACKEND_NAMES[p.backend]} backend` : ''))), actions),
- stateBlock, deliverables, questions, steps, activity, brief, events, journal,
+ stateBlock, narration, deliverables, questions, steps, activity, brief, events, journal,
h('p', { class: 'meta', style: { color: 'var(--faint)', fontSize: '12px', marginTop: '18px' } },
`${usage.sessions} session${usage.sessions === 1 ? '' : 's'}${usage.output_tokens ? ` · ${usage.output_tokens.toLocaleString()} output tokens` : ''}${usage.cost_text ? ` · ${usage.cost_text}` : ''}`),
);
@@ -791,6 +801,7 @@ async function keysSection() {
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.'],
+ own: ['Your own voice', 'You read the script yourself, one short line at a time, in the recording booth: in this studio, in a terminal (mortiflix record), or from files you recorded elsewhere.'],
none: ['No narration', 'Videos carry their story with on-screen text, music and sound.'],
};
@@ -818,6 +829,10 @@ async function voiceSection() {
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 if (v.engine === 'own') fill(panel, h('div', { class: 'help', style: { padding: '12px 0' } },
+ h('p', null, 'When a video reaches its narration, the studio writes the script as short lines and asks you to record them. Open the project and choose ', h('b', null, 'Record narration'), ', or run ', h('code', null, 'mortiflix record <project>'), ' in a terminal.'),
+ h('p', null, 'Recorded somewhere else (a DAW, your phone)? Name each file after its line (b01-1.wav, b01-2.m4a…) and run ', h('code', null, 'mortiflix record <project> --import <folder>'), '.'),
+ h('p', null, 'For the best sound: a quiet room with soft things around, a hand\'s width from the microphone, headphones on.')));
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).'));
@@ -982,3 +997,239 @@ const tierOk = (tier, need) => TIERS.indexOf(String(tier || 'free').replace(/_.*
await loadStudio();
connect();
render();
+
+// ---------- the recording booth ----------
+// You read the script one short line at a time. Hold Space (or the big button) to record, let go to stop; listen,
+// try again, keep the best take, next line. Takes save as they're made (src/booth.mjs), so you can stop and come back.
+// The kept take of each line becomes the narration the studio builds the video's timing on.
+
+const BOOTH = { preRoll: 0.3, postRoll: 0.4 };
+
+async function boothView(id) {
+ let d = await api(`/api/projects/${id}/booth`);
+ const back = h('a', { class: 'crumb', href: `#/p/${id}` }, `← ${d.project.title}`);
+ if (!d.lines) {
+ mount(back, h('div', { class: 'empty' }, h('div', { class: 'big' }, 'No script to record yet'),
+ 'The studio writes the narration script first (voice/lines.json). When it is ready, the project asks for you and this booth opens it.'));
+ return;
+ }
+
+ // ---- audio: a worklet taps the microphone; a rolling pre-roll keeps the first syllable ----
+ let ctx = null; let stream = null; let node = null; let rate = 48000;
+ let ring = []; let rec = null; let stopping = null; let onTake = null; let onBlock = null;
+ const meter = { level: 0 };
+ const db = (x) => (x > 0 ? 20 * Math.log10(x) : -120);
+
+ async function startMic(deviceId) {
+ stream?.getTracks().forEach((t) => t.stop());
+ stream = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: deviceId ? { exact: deviceId } : undefined, channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
+ if (!ctx) { ctx = new AudioContext(); await ctx.audioWorklet.addModule('booth-worklet.js'); }
+ rate = ctx.sampleRate;
+ node?.disconnect();
+ const src = ctx.createMediaStreamSource(stream);
+ node = new AudioWorkletNode(ctx, 'booth-tap');
+ node.port.onmessage = (e) => block(e.data);
+ src.connect(node);
+ if (ctx.state === 'suspended') await ctx.resume();
+ }
+ function block(b) {
+ let peak = 0;
+ for (let i = 0; i < b.length; i += 1) { const v = Math.abs(b[i]); if (v > peak) peak = v; }
+ meter.level = Math.max(peak, meter.level * 0.85);
+ onBlock?.(b);
+ if (rec) {
+ rec.push(b);
+ if (stopping !== null && (stopping -= b.length) <= 0) finishTake();
+ return;
+ }
+ ring.push(b);
+ let have = ring.reduce((a, x) => a + x.length, 0);
+ while (have - ring[0].length > BOOTH.preRoll * rate) { have -= ring[0].length; ring.shift(); }
+ }
+ function wavFrom(blocks) {
+ const n = blocks.reduce((a, b) => a + b.length, 0);
+ const out = new DataView(new ArrayBuffer(44 + n * 2));
+ const w = (o, s) => { for (let i = 0; i < s.length; i += 1) out.setUint8(o + i, s.charCodeAt(i)); };
+ w(0, 'RIFF'); out.setUint32(4, 36 + n * 2, true); w(8, 'WAVE'); w(12, 'fmt ');
+ out.setUint32(16, 16, true); out.setUint16(20, 1, true); out.setUint16(22, 1, true); out.setUint32(24, rate, true);
+ out.setUint32(28, rate * 2, true); out.setUint16(32, 2, true); out.setUint16(34, 16, true); w(36, 'data'); out.setUint32(40, n * 2, true);
+ let o = 44;
+ for (const b of blocks) for (let i = 0; i < b.length; i += 1) { const v = Math.max(-1, Math.min(1, b[i])); out.setInt16(o, v < 0 ? v * 0x8000 : v * 0x7fff, true); o += 2; }
+ return new Blob([out.buffer], { type: 'audio/wav' });
+ }
+ let recStart = 0; let recTimer = null;
+ const startTake = () => {
+ if (rec || !node) return;
+ rec = [...ring]; ring = []; stopping = null; recStart = performance.now();
+ document.body.classList.add('is-recording');
+ recTimer = setInterval(() => { const t = document.getElementById('rec-time'); if (t) t.textContent = clock((performance.now() - recStart) / 1000); }, 200);
+ };
+ const stopTake = () => { if (rec && stopping === null) stopping = Math.round(BOOTH.postRoll * rate); };
+ function finishTake() {
+ const blocks = rec; rec = null; stopping = null;
+ clearInterval(recTimer);
+ const t = document.getElementById('rec-time'); if (t) t.textContent = '';
+ document.body.classList.remove('is-recording');
+ onTake?.(wavFrom(blocks));
+ }
+
+ const player = new Audio();
+ const takeUrl = (t) => `/api/projects/${id}/booth/lines/${encodeURIComponent(t.line_id)}/takes/${t.take_no}/audio`;
+ const play = (t) => { player.src = takeUrl(t); player.play().catch(() => {}); };
+ const takesFor = (lineId) => d.takes.filter((t) => t.line_id === lineId);
+ const keptFor = (lineId) => takesFor(lineId).find((t) => t.kept);
+ let lineIdx = Math.max(0, d.lines.findIndex((l) => !keptFor(l.id)));
+ let raf = 0;
+
+ const keys = (e) => {
+ if (!document.querySelector('.booth-stage') || e.target.closest('input, textarea, select')) return;
+ if (e.code === 'Space') { e.preventDefault(); if (!e.repeat) startTake(); }
+ else if (e.key === 'p' || e.key === 'P') document.getElementById('booth-preview')?.click();
+ else if (e.key === 'Enter') { e.preventDefault(); document.getElementById('booth-keep')?.click(); }
+ else if (e.key === 'ArrowRight' && !rec) { lineIdx = Math.min(d.lines.length - 1, lineIdx + 1); stage(); }
+ else if (e.key === 'ArrowLeft' && !rec) { lineIdx = Math.max(0, lineIdx - 1); stage(); }
+ };
+ const keyUp = (e) => { if (e.code === 'Space' && document.querySelector('.booth-stage')) { e.preventDefault(); stopTake(); } };
+ document.addEventListener('keydown', keys);
+ document.addEventListener('keyup', keyUp);
+ leaveView = () => {
+ cancelAnimationFrame(raf);
+ document.removeEventListener('keydown', keys);
+ document.removeEventListener('keyup', keyUp);
+ stream?.getTracks().forEach((t) => t.stop());
+ ctx?.close();
+ player.pause();
+ document.body.classList.remove('is-recording');
+ };
+
+ // ---- before the first take: microphone, level, the room ----
+ async function micCheck() {
+ const bar = h('i');
+ const status = h('p', { class: 'help' });
+ const select = h('select', { 'aria-label': 'Microphone', style: { maxWidth: '360px' } });
+ const roomNote = h('span', { class: 'help' });
+ const roomBtn = h('button', { class: 'btn' }, 'Check the room (3 s of quiet)');
+ const go = h('button', { class: 'btn primary' }, 'Start recording');
+ const loop = () => { bar.style.width = `${Math.min(100, Math.round(meter.level * 140))}%`; bar.classList.toggle('hot', meter.level > 0.89); raf = requestAnimationFrame(loop); };
+ mount(back, h('div', { class: 'head' }, h('h1', null, 'Recording booth')),
+ h('section', null, h('h2', null, 'Before you start'),
+ h('ul', { class: 'booth-tips' },
+ h('li', null, 'A quiet room with soft things around you (a wardrobe full of clothes is perfect).'),
+ h('li', null, 'About a hand\'s width from the microphone. Headphones help you hear yourself back.'),
+ h('li', null, `${d.lines.length} short lines. Hold Space (or the big button) while you speak, let go when you are done.`)),
+ h('div', { class: 'field' }, h('label', null, 'Microphone'), h('div', null, select, h('div', { class: 'booth-meter', 'aria-hidden': 'true' }, bar), status)),
+ h('div', { class: 'field' }, h('label', null, 'The room'), h('div', { class: 'actions' }, roomBtn, roomNote)),
+ h('div', { class: 'actions', style: { marginTop: '18px' } }, go)));
+ try {
+ await startMic();
+ const devices = (await navigator.mediaDevices.enumerateDevices()).filter((x) => x.kind === 'audioinput');
+ fill(select, devices.map((x, i) => h('option', { value: x.deviceId }, x.label || `Microphone ${i + 1}`)));
+ select.addEventListener('change', () => startMic(select.value));
+ status.textContent = 'Say something: the bar should jump to the middle and never hit the end.';
+ loop();
+ } catch {
+ status.textContent = window.isSecureContext
+ ? 'The booth needs your microphone. Allow it for this page (the icon by the address bar), then reload.'
+ : `Browsers only allow the microphone on this computer (localhost) or over HTTPS. Open the studio on the computer it runs on, or record in a terminal: mortiflix record ${id}`;
+ go.disabled = true; roomBtn.disabled = true;
+ }
+ roomBtn.addEventListener('click', () => {
+ roomBtn.disabled = true; roomNote.textContent = 'Stay quiet…';
+ let n = 0; let sum = 0;
+ onBlock = (b) => { for (let i = 0; i < b.length; i += 1) sum += b[i] * b[i]; n += b.length; };
+ setTimeout(() => {
+ onBlock = null; roomBtn.disabled = false;
+ const floor = db(Math.sqrt(sum / Math.max(1, n)));
+ roomNote.textContent = floor < -55 ? 'Nice and quiet.' : floor < -45 ? 'A little background noise: fine, but a quieter spot is better.' : 'It is noisy there (a fan, traffic, a TV?). A quieter room will sound much better.';
+ }, 3000);
+ });
+ go.addEventListener('click', () => { cancelAnimationFrame(raf); stage(); });
+ }
+
+ // ---- one line at a time ----
+ function stage() {
+ const lines = d.lines;
+ lineIdx = Math.min(lineIdx, lines.length - 1);
+ const line = lines[lineIdx];
+ let selected = keptFor(line.id) || takesFor(line.id).at(-1) || null;
+ const strip = h('div', { class: 'booth-takes' });
+ const flags = h('p', { class: 'help' });
+ const saving = h('span', { class: 'help' });
+ const previewBtn = h('button', { class: 'btn', id: 'booth-preview' }, 'Preview (P)');
+ const keepBtn = h('button', { class: 'btn primary', id: 'booth-keep' }, lineIdx === lines.length - 1 ? 'Keep (Enter)' : 'Keep & next (Enter)');
+ const paint = () => {
+ fill(strip, takesFor(line.id).map((t) => h('button', { class: `booth-take${selected === t ? ' on' : ''}${t.kept ? ' kept' : ''}`, onclick: () => { selected = t; paint(); play(t); } },
+ h('b', null, `Take ${t.take_no}`), h('span', null, `${(t.duration_ms / 1000).toFixed(1)} s${t.kept ? ' · kept' : ''}`))));
+ previewBtn.disabled = keepBtn.disabled = !selected;
+ flags.textContent = selected?.flags?.length ? `That take: ${d.advice[selected.flags[0]]}.` : '';
+ };
+ previewBtn.addEventListener('click', () => selected && play(selected));
+ keepBtn.addEventListener('click', async () => {
+ if (!selected) return;
+ keepBtn.disabled = true;
+ try {
+ await api(`/api/projects/${id}/booth/lines/${encodeURIComponent(line.id)}/takes/${selected.take_no}/keep`, { method: 'POST' });
+ } catch (e) { keepBtn.disabled = false; toast(e.message, true); return; }
+ for (const t of takesFor(line.id)) t.kept = t === selected;
+ const next = lines.findIndex((l, i) => i > lineIdx && !keptFor(l.id));
+ const anyLeft = lines.findIndex((l) => !keptFor(l.id));
+ if (anyLeft === -1) { finish(); return; }
+ lineIdx = next !== -1 ? next : anyLeft;
+ stage();
+ });
+ onTake = async (blob) => {
+ saving.textContent = 'Saving…';
+ try {
+ const r = await api(`/api/projects/${id}/booth/lines/${encodeURIComponent(line.id)}/takes`, { method: 'POST', raw: blob });
+ d.takes.push(r.take);
+ selected = r.take;
+ saving.textContent = 'Saved';
+ paint();
+ play(r.take);
+ } catch (e) { saving.textContent = ''; toast(e.message, true); }
+ };
+ const recBtn = h('button', { class: 'booth-rec', 'aria-label': 'Hold to record' }, h('span', { class: 'booth-rec-dot' }));
+ recBtn.addEventListener('pointerdown', (e) => { e.preventDefault(); recBtn.setPointerCapture(e.pointerId); startTake(); });
+ for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) recBtn.addEventListener(ev, stopTake);
+ recBtn.addEventListener('contextmenu', (e) => e.preventDefault());
+ const kept = lines.filter((l) => keptFor(l.id)).length;
+ mount(back,
+ h('div', { class: 'booth-stage' },
+ h('div', { class: 'booth-progress' }, h('span', null, `Line ${lineIdx + 1} of ${lines.length}`),
+ h('ol', { class: 'booth-dots', 'aria-label': 'Lines' }, lines.map((l, i) => h('li', { class: `${keptFor(l.id) ? 'done' : ''}${i === lineIdx ? ' current' : ''}` },
+ h('button', { 'aria-label': `Line ${i + 1}${keptFor(l.id) ? ' (kept)' : ''}`, onclick: () => { lineIdx = i; stage(); } })))),
+ h('span', null, `${kept} kept`), kept === lines.length ? h('button', { class: 'btn link', onclick: finish }, 'Review & finish') : null),
+ h('div', { class: 'booth-script' },
+ lineIdx > 0 ? h('p', { class: 'booth-near' }, lines[lineIdx - 1].script) : null,
+ h('p', { class: 'booth-line' }, line.script),
+ lineIdx < lines.length - 1 ? h('p', { class: 'booth-near' }, lines[lineIdx + 1].script) : null),
+ h('div', { class: 'booth-direction' }, line.direction ? h('span', { class: 'chip' }, line.direction) : null, h('span', { class: 'help' }, `About ${line.est_seconds} s`)),
+ h('div', { class: 'booth-controls' }, recBtn, h('p', { class: 'help' }, h('span', { id: 'rec-time' }), ' ', matchMedia('(pointer: coarse)').matches ? 'Hold the button while you speak' : 'Hold Space or the button while you speak')),
+ h('div', { class: 'booth-after' }, strip, flags, h('div', { class: 'actions' }, previewBtn, keepBtn, saving)),
+ h('p', { class: 'help booth-keys' }, 'Keys: hold Space to record · P preview · Enter keep · ← → move between lines')));
+ paint();
+ }
+
+ // ---- every line kept: listen back, then hand it to the studio ----
+ function finish() {
+ const totalMs = d.lines.reduce((a, l) => a + (keptFor(l.id)?.duration_ms || 0), 0);
+ const done = h('button', { class: 'btn primary' }, 'Done: give it to the studio');
+ done.addEventListener('click', async () => {
+ done.disabled = true;
+ try {
+ const r = await api(`/api/projects/${id}/booth/done`, { method: 'POST' });
+ toast(r.resumed ? 'Sent: the studio carries on with your voice' : 'Saved: the studio uses your voice');
+ location.hash = `#/p/${id}`;
+ } catch (e) { done.disabled = false; toast(e.message, true); }
+ });
+ mount(back, h('div', { class: 'head' }, h('h1', null, 'Every line recorded')),
+ h('p', { class: 'meta' }, `${d.lines.length} lines · ${d.takes.length} takes · ${clock(totalMs / 1000)} of narration. Listen back if you like; you can still redo any line.`),
+ h('ol', { class: 'rows booth-review' }, d.lines.map((l, i) => h('li', { class: 'row' }, h('span', { class: 'meta' }, String(i + 1)),
+ h('div', { class: 'main' }, h('span', null, l.script)),
+ h('div', { class: 'end' }, h('button', { class: 'btn link', onclick: () => play(keptFor(l.id)) }, 'Play'), h('button', { class: 'btn link', onclick: () => { lineIdx = i; stage(); } }, 'Redo'))))),
+ h('div', { class: 'actions', style: { marginTop: '18px' } }, done));
+ }
+
+ if (d.missing.length) await micCheck();
+ else finish();
+}
diff --git a/web/booth-worklet.js b/web/booth-worklet.js
new file mode 100644
index 0000000..b3254be
--- /dev/null
+++ b/web/booth-worklet.js
@@ -0,0 +1,25 @@
+// Microphone samples for the recording booth: mono Float32 blocks posted to the page (which keeps a short rolling
+// pre-roll, records while the button is held, and measures levels for the meter).
+class BoothTap extends AudioWorkletProcessor {
+ constructor() {
+ super();
+ this.buf = new Float32Array(2048);
+ this.n = 0;
+ }
+
+ process(inputs) {
+ const ch = inputs[0] && inputs[0][0];
+ if (ch) {
+ for (let i = 0; i < ch.length; i += 1) {
+ this.buf[this.n++] = ch[i];
+ if (this.n === this.buf.length) {
+ this.port.postMessage(this.buf.slice(0));
+ this.n = 0;
+ }
+ }
+ }
+ return true;
+ }
+}
+
+registerProcessor('booth-tap', BoothTap);