commit 963067a91691834050a71cc2e94c035e8ca790a2
parent 2a7883cf8aad9d26ad06e4330de2940b57eca989
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 21:57:43 -0500
Merge lane/record-filter: record, filter, preview on the record page -- a recording is cleaned, cut and converted to its character's voice before it is kept, played beside the raw read; cut marks, pitch, hands-free keys; and a convert derive takes its voice from the character
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
25 files changed, 2758 insertions(+), 113 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **umtool: record, filter and listen before anything is kept.** On the record page a recording became a take the moment its last part was in, and hearing it in the character's voice meant importing it on the Voices page and waiting for three takes (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"). With **Filter before keeping** (on by itself for a post whose character has a stock voice to convert to) the post now waits. **Filter** (`f`) runs the character's recorded preset as one job: clean, cut, convert. Its result is a preview in `narration/.record-preview/<postId>.<label>/`, not a take. The page shows the three stages and the time it has run, and a wait at the editor's queue or the machine's heavy slot reads "waiting for memory … the gate working, not an error". **▶ Raw** and **▶ Filtered** play at one loudness. **Keep** (`Enter`) makes the recorded, cleaned and converted takes from the preview's files, converts nothing again, picks the last and opens the next post not recorded; **Again** (`Backspace` or `r`) drops the preview and records the part again. Each part's waveform carries two **cut marks** at the auto trim's answer; drag one, or press the arrow keys on it, to cut a keyboard click off the start or the end. **Pitch** and **semitones** (a Seed-VC convert) default to the preset's and re-run the convert alone; **Save to character** writes them back, and a post read as the narrator or as nobody offers **Keep in this video only**. Above the record button: the character, its direction line and **▶ <voice> reads it** (its synthetic preset's voice), which plays the read kept from before when there is one and asks the editor only when pressed. Cancel stops the editor's job too. Opened over http from the LAN the page says the microphone is off (a browser opens it only on localhost or https); **Use a sound file…** takes a recording made elsewhere, and Filter, the preview and Keep work there. From a terminal: `umtool posts narrate <p> <item> --recording <file> --preview [--out <file>] [--trim-span 0.4-3.1]` prints the paths and makes no take, `--keep-preview` keeps it, `--discard-preview` drops it. A "start on speech" trigger was not built: it would lose the start of the first word, and the auto trim already cuts the silence before it. ([knobs.md](../umtool/docs/knobs.md#record-filter-preview-on-the-record-page))
+- **umtool: a convert made from a take uses its character's voice, not the editor's default.** On 11 Nov `umtool posts narrate <p> <item> --derive <n> --op convert` with no flags made a take in the wrong voice: it asked the editor with nothing, and the editor used its own default target. A convert now takes its engine, stock voice, pitch and semitones from the recorded preset of the character the read is made as (`--as`, else the item's own, this video's for the author, the cast's, the narrator); a flag overrides its own key. With no character and no `--voice` it is refused in one sentence. The post bench's **run AI on take** does the same on the server.
- **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published.
- **umtool: a character is a preset, and a video can have characters of its own.** The operator wanted "a preset of voice and other settings" per character, applied to that author's posts, anonymous characters with their own profile per video, a pool reused across videos, and different presets for synthetic and recorded voices. A cast character now carries two presets. `synthetic` is the stock voice and its speed. `recorded` is what a recording of them is made into: the stock voice it is converted to, the engine, the pitch and semitones, whether it is cleaned first, whether its edges are trimmed and how much room is kept, and a one-line direction for the person reading, which is never sent to a model. An existing `cast.json` (`voice`, `convert`) reads as these presets, and the first write makes it version 2; `umtool cast undo` puts the old file back. A video's own characters live in `<project>/narration/characters.json`, for people who must not enter the pool. An anonymous one goes by a shown name, "Anon 1", "Anon 2" by default, on the Voices page, in `umtool cast project` and in a recording's note, and is refused the pool. `narration/voices.json` keeps working and is not rewritten. A post item can name its own character (`umtool posts character <p> <item> <id>`, `--clear`). One read asks, first hit wins: the command's flags, the item's character, the video's character for the author, the cast's, the narrator's, the default. `umtool cast project <p>` prints the answer and its source for each author. A thread read ignored `--speed`: each part is now asked at its character's speed, and `--speed` sets every part. A recording made a read (`posts narrate --recording`) applies its character's clean and trim settings; `--clean`, `--no-clean`, `--trim` and `--no-trim` override them for one read. The Voices page edits both presets, keeps the video's own characters, and has "Add to the pool" and "Keep in this video only"; none of it needs an agent. New: `umtool cast set <id> --speed --enhance --trim --trim-pad --direction`, `umtool cast project <p> add|set|rm|undo|pool|keep`. A convert target is still always a stock synthetic voice, and the disclosure line is unchanged. Not built yet: the on-screen card is not anonymised (a cut still shows the post's author for an anonymous character), and the record page does not show the direction (umtool/docs/knobs.md, "A character is a preset").
- **A converted read can follow your pitch.** Converting a recorded read to a stock voice threw the voice acting away. On 11 Nov, reads with a median pitch of 128, 212, 225 and 237 Hz all came out at 196–199 Hz, and a 152–321 Hz range came out as 165–240 Hz: both converters speak at the stock voice's own pitch. `pnpm ops voice-convert` now takes `"pitch"`: `target` (as before), `source` (the pitch you read at: raise your voice and the result rises) or `contour` (your rises and falls, moved as a whole to the stock voice's register), and `"semitones"` (-12 to 12) moves a followed pitch. The same read that came out at 197 Hz now comes out at 211 Hz with a 148–314 Hz range, against 212 Hz and 152–321 Hz read. `source` and `contour` are seed-vc's, on its f0-conditioned model: optional files, fetched by `archilyzer voice setup --engine seed-vc --with f0` (1.49 GB). An install without them converts as before, and a followed pitch is refused naming that command; openvoice refuses a pitch it cannot follow. It takes about 1.7 times as long, and more memory (5.8 GB at its peak on a take of 20 s or more). `settings.voice.convert.pitch` and `.semitones` are the defaults (`target`, 0). In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch contour --convert-semitones 2`, shown on Voices), and `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive <n> --op convert` set it for one read; the post bench's **run AI on take** has the same two controls for a convert on seed-vc, starting from the character's. The disclosure line is unchanged.
diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts
@@ -1,9 +1,20 @@
-import { readFile, stat } from "node:fs/promises";
+import { mkdir, readFile, rename, stat } from "node:fs/promises";
+import path from "node:path";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
-import { discardPart, finishSession, partFile, readSession, savePart } from "@/lib/report/recordSession.mjs";
+import { clearSession, discardPart, finishSession, partFile, readSession, savePart, sessionParts } from "@/lib/report/recordSession.mjs";
+import { discardPreview, keepPreview, preparePreview, previewFile, previewView, readPreview } from "@/lib/report/recordPreview.mjs";
+import { readLayers } from "@/lib/report/characterLayers.mjs";
+import { derivePitchOf } from "@/lib/report/derivePitch.mjs";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { PARTS_CACHE, partKey } from "@/lib/report/postThreadRead.mjs";
+import { projectRedaction } from "@/lib/report/postRedaction.mjs";
+import { cancelJob, getJob, jobView, recentJobs, runningJob, startJob, type Job } from "@/lib/jobs";
+import { editorCall, jobState, startJob as startEditorJob } from "@/lib/research/case-editor";
+import { CAST_PITCH_ENGINES, characterSpeed, characterVoice, projectCharactersOf, recordedPresetOf, shownNameOf, voiceRefOf } from "umtool-report-to-video/cast";
+import { spokenRead } from "umtool-report-to-video/post-redact";
export const dynamic = "force-dynamic";
@@ -12,10 +23,40 @@ export const dynamic = "force-dynamic";
//
// GET ?project&id[&label] the session: the parts kept so far (a reload resumes)
// GET ?project&id&n[&label] one kept part's audio (play it back)
-// POST multipart {project, id, n, count, text, para, label?, part} keep part n of count
+// POST multipart {project, id, n, count, text, para, label?, part} keep part n of count (a recording, or a
+// sound file chosen for it)
// POST {project, op: "discard", id, n, label?} drop part n (redo it)
-// POST {project, op: "finish", id, label?, script?} every part in: one recorded
-// take, trimmed, joined, levelled, PICKED
+// POST {project, op: "finish", id, label?, script?, spans?} every part in: one recorded take, cut at the
+// marks (`spans`, per part) else trimmed, joined,
+// levelled, PICKED
+//
+// RECORD -> FILTER -> PREVIEW (lib/report/recordPreview.mjs): the session's parts run through the character's
+// recorded preset into a SCRATCH DIR (narration/.record-preview/<postId>.<label>/), no take made, listened to beside
+// the raw read, then kept or recorded again.
+//
+// GET ?project&id&preview[&label] who it is read as (its direction, convert, clean, trim), the preview as
+// it stands (each part's waveform and marks, what was made), the Filter
+// job running or last run
+// GET ?project&id&preview&file=raw|clean|filtered|part[&n] one of its sounds
+// GET ?project&id&job=<id> the Filter job: its state, the stage it is at (and whether it WAITS --
+// queued, or at the heavy slot for memory: the gate, not an error)
+// GET ?project&id&stock&job=<id>&key a stock read asked for: running | done {file} | failed
+// POST {project, op: "prepare", id} the parts decoded: lengths, waveforms, the auto trim's marks (no editor)
+// POST {project, op: "filter", id, spans?, pitch?, semitones?} THE CHAIN as one job (`umtool posts narrate <p>
+// <item> --preview --events`): clean, cut, convert -- a step whose inputs
+// stand is not run again (another pitch: the convert alone)
+// POST {project, op: "cancel", id, job} stop that job AND the editor's job it waits on (its engine holds the
+// heavy slot otherwise); `editor.note` when that one was not known yet
+// keep, again, discard-preview, finish, discard and a part's upload answer 409 while the item's Filter runs
+// POST {project, op: "keep", id, filtered, spans?, script?} filtered: the preview's files made the takes
+// (recorded, cleaned, converted; the last picked) -- nothing converted
+// again; else the recorded take alone (finish). The session and the
+// scratch dir are cleared.
+// POST {project, op: "again", id, n?} the preview dropped (and part n, to record it again)
+// POST {project, op: "discard-preview", id} the scratch dir removed (the page is left; a beacon)
+// POST {project, op: "stock", id, text} the character's SYNTHETIC preset voice reading the line: the cached read when there
+// is one (narration/parts-cache/, a thread read's), else asked of the
+// editor's tts op (a job) -- only when a person asks
const noStore = { "cache-control": "no-store" };
type Entry = Record<string, unknown> & { id: string; type?: string };
@@ -32,7 +73,75 @@ function itemOf(manifest: Record<string, unknown>, id: string): Entry | null {
return tl.find((e) => e?.type === "post" && e.id === id) ?? null;
}
-const TYPES: Record<string, string> = { webm: "audio/webm", ogg: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4" };
+const TYPES: Record<string, string> = { webm: "audio/webm", ogg: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4", mp3: "audio/mpeg", flac: "audio/flac" };
+
+/** The Filter job of one post item (lib/jobs.ts: one job at a time, its log, Cancel). */
+const filterKind = (project: string, id: string) => `record-filter ${project} ${id}`;
+/** Is that item's Filter running now? Its scratch dir and its session are the job's until it ends. */
+const filterRunning = (project: string, id: string) => runningJob()?.kind === filterKind(project, id);
+const busy = () => Response.json({ error: "its Filter is still running: wait for it, or Cancel it", busy: true }, { status: 409 });
+
+type Stage = { stage?: string; state?: string; message?: string; line?: string; job?: string };
+const WAITS = ["queued", "memory", "slot"];
+/**
+ * The Filter job as the record page reads it: its state, the STAGE it is at (the chain's last `stage` event:
+ * recordPreview.mjs runPreview), every stage's last word, and whether it is WAITING -- `queued` behind the editor's
+ * other jobs, `memory` / `slot` at the machine's heavy slot. A wait is the gate working: it is never an error here.
+ */
+function filterJobView(job: Job) {
+ const stages = (job.events as Array<Stage & { ev?: string }>).filter((x) => x.ev === "stage");
+ const at = stages.at(-1) ?? null;
+ const last: Record<string, Stage> = {};
+ for (const x of stages) if (x.stage) last[x.stage] = { state: x.state, message: x.message };
+ const failed = job.state === "failed";
+ return {
+ id: job.id, state: job.state, startedAt: job.startedAt, endedAt: job.endedAt,
+ stage: at?.stage ?? null, stageState: at?.state ?? null, message: at?.message ?? null,
+ waiting: at && job.state === "running" && WAITS.includes(String(at.state)) ? at.state : null,
+ // Every wait it went through, in order (said after the fact too: "waited for memory").
+ waited: [...new Set(stages.filter((x) => WAITS.includes(String(x.state))).map((x) => String(x.state)))],
+ stages: last,
+ // The editor's job it waits on now (the clean, the convert): what Cancel stops there too. null: none known yet.
+ editorJob: job.state === "running" ? (stages.filter((x) => typeof x.job === "string").at(-1)?.job ?? null) : null,
+ // A failure in the CLI's own words (its last line), not "exited 1".
+ error: failed ? (job.log.filter((l) => !l.startsWith("**") && !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? job.error) : null,
+ };
+}
+
+/** Who a recording of `e` is read as, and that character's recorded preset (cast.mjs characterForRead, recordedPresetOf). */
+async function whoOf(dir: string, e: Entry) {
+ const layers = await readLayers(dir);
+ const who = layers.characterForRead(e);
+ const c = who?.character ?? null;
+ const preset = c ? recordedPresetOf(c) : null;
+ // Where a change to it is written: this video's own characters, else the cast.
+ const own = c ? projectCharactersOf(layers.project).some((x: { id: string }) => x.id === c.id) : false;
+ return {
+ character: c ? { id: c.id as string, name: shownNameOf(c) as string, layer: who.layer as string, scope: own ? "project" : "cast" } : null,
+ convert: preset ? preset.convert : null,
+ recorded: preset ? { enhance: preset.enhance, trim: preset.trim, direction: preset.direction } : null,
+ // The voice it reads in when it is SYNTHESIZED (the synthetic preset: the cheap one to hear the line in).
+ synthetic: c && characterVoice(c) ? { voice: String(characterVoice(c)), speed: characterSpeed(c) as number | null } : null,
+ pitchEngines: CAST_PITCH_ENGINES,
+ };
+}
+
+/** The file a stock read of `text` is cached at (a thread read's part: postThreadRead.mjs partKey), project-relative. */
+const stockRel = (key: string) => `${PARTS_CACHE}/${key}.wav`;
+const isKey = (k: string) => /^[0-9a-f]{40}$/.test(k);
+
+/** A stock read asked of the editor: where its job is; done, its file is put in the cache. */
+async function stockPoll(dir: string, job: string, key: string) {
+ if (!isKey(key)) return Response.json({ error: "which read?" }, { status: 400 });
+ const abs = path.join(dir, ...stockRel(key).split("/"));
+ const st = await jobState(job);
+ if (!st.done) return Response.json({ state: "running", status: st.status }, { headers: noStore });
+ if (st.status !== "done") return Response.json({ state: "failed", error: st.tail.slice(-3).join(" / ") }, { headers: noStore });
+ const tmp = `${abs}.pending.tmp.wav`;
+ if (await stat(tmp).catch(() => null)) await rename(tmp, abs);
+ if (!(await stat(abs).catch(() => null))?.isFile()) return Response.json({ state: "failed", error: "the job is done but its read is not there" }, { headers: noStore });
+ return Response.json({ state: "done", file: stockRel(key) }, { headers: noStore });
+}
export async function GET(request: Request) {
const q = new URL(request.url).searchParams;
@@ -42,6 +151,22 @@ export async function GET(request: Request) {
if (!e) return Response.json({ error: `no post item ${q.get("id")}` }, { status: 404 });
const label = q.get("label") ?? "operator";
try {
+ if (q.get("stock") !== null) return await stockPoll(r.project.dir, String(q.get("job") ?? ""), String(q.get("key") ?? ""));
+ if (q.get("job") !== null) {
+ const job = getJob(String(q.get("job")));
+ if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 });
+ return Response.json({ ok: true, job: filterJobView(job), ...(job.state === "done" ? { preview: previewView(await readPreview(r.project.dir, e, label)) } : {}) }, { headers: noStore });
+ }
+ if (q.get("preview") !== null) {
+ const which = q.get("file");
+ if (which !== null) {
+ const f = await previewFile(r.project.dir, e, which, { label, n: q.get("n") === null ? null : Number(q.get("n")) });
+ if (!f) return new Response("no such sound", { status: 404 });
+ return new Response(new Uint8Array(await readFile(f)), { headers: { "content-type": "audio/wav", ...noStore } });
+ }
+ const mine = [runningJob(), ...recentJobs(20)].find((j) => j && j.kind === filterKind(r.project.id, e.id)) ?? null;
+ return Response.json({ ok: true, ...(await whoOf(r.project.dir, e)), preview: previewView(await readPreview(r.project.dir, e, label)), job: mine ? filterJobView(mine) : null }, { headers: noStore });
+ }
const n = q.get("n");
if (n !== null) {
const f = await partFile(r.project.dir, e, Number(n), label);
@@ -76,11 +201,14 @@ export async function POST(request: Request) {
if (!e) return Response.json({ error: `no post item ${String(form.get("id"))}` }, { status: 404 });
const blob = form.get("part");
if (!blob || typeof blob === "string") return Response.json({ error: "no part" }, { status: 400 });
+ if (filterRunning(r.project.id, e.id)) return busy();
try {
const session = await savePart(r.project.dir, e, {
n: Number(form.get("n")), count: Number(form.get("count")), text: String(form.get("text") ?? ""), para: Number(form.get("para")),
bytes: new Uint8Array(await blob.arrayBuffer()), type: blob.type || "audio/webm", label: String(form.get("label") ?? "operator").toLowerCase(),
});
+ // Another recording than the one a preview was made from: that preview goes (it must never be kept for this one).
+ await discardPreview(r.project.dir, e, String(form.get("label") ?? "operator").toLowerCase());
return Response.json({ ok: true, session }, { headers: noStore });
} catch (err) {
return fail(err);
@@ -99,12 +227,109 @@ export async function POST(request: Request) {
const label = String(body.label ?? "operator").toLowerCase();
try {
if (body.op === "discard") return Response.json({ ok: true, session: await discardPart(r.project.dir, e, Number(body.n), label) }, { headers: noStore });
+ const script = typeof body.script === "string" ? body.script : null;
+ const spans = spansOf(body.spans);
if (body.op === "finish") {
- const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script: typeof body.script === "string" ? body.script : null });
+ const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script, spans });
+ await discardPreview(r.project.dir, e, label);
return Response.json({ ok: true, take: kept.take, gain: kept.gain, entry: kept.result.entry, token: kept.result.token }, { headers: noStore });
}
- return Response.json({ error: "op is discard or finish" }, { status: 400 });
+ if (body.op === "prepare") {
+ // The parts decoded into the scratch dir: their waveforms and the auto trim's marks. No editor, no take.
+ const who = await whoOf(r.project.dir, e);
+ const doc = await preparePreview(r.project, e, await sessionParts(r.project.dir, e, label), { label, trim: who.recorded?.trim ?? null });
+ return Response.json({ ok: true, ...who, preview: previewView(doc) }, { headers: noStore });
+ }
+ if (body.op === "filter") {
+ // THE CHAIN, as one job of umtool's (its log, Cancel): the CLI's own command over the session's parts.
+ const running = runningJob();
+ if (running) return Response.json({ error: `umtool is running another job (${running.kind}): Filter when it is done`, busy: true }, { status: 409 });
+ await sessionParts(r.project.dir, e, label);
+ const checked = derivePitchOf({ pitch: body.pitch, semitones: body.semitones });
+ if (!checked.ok) return Response.json({ error: checked.error }, { status: 400 });
+ const pitched: { pitch?: string; semitones?: number } = checked.value ?? {};
+ const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+ const argv = [
+ process.execPath, cliPath, "posts", "narrate", r.project.id, e.id, "--preview", "--events", "--label", label,
+ ...(spans ?? []).flatMap((sp, k) => (sp ? ["--trim-span", `${k + 1}=${sp.from}-${sp.to}`] : [])),
+ ...(pitched.pitch ? ["--pitch", pitched.pitch] : []),
+ ...(typeof pitched.semitones === "number" && pitched.pitch !== "target" ? ["--semitones", String(pitched.semitones)] : []),
+ ];
+ const job = startJob(filterKind(r.project.id, e.id), [{ label: `${e.id}: its recording cleaned, cut, converted (a preview: no take)`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000, ndjson: true }], { project: r.project.id });
+ return Response.json({ ok: true, job: filterJobView(job) }, { headers: noStore });
+ }
+ if (body.op === "cancel") {
+ const job = getJob(String(body.job ?? ""));
+ if (!job || job.kind !== filterKind(r.project.id, e.id)) return Response.json({ error: "no such job" }, { status: 404 });
+ // The editor's job too: its engine holds (or waits at) the heavy slot whether or not umtool still follows it.
+ const editorJob = filterJobView(job).editorJob;
+ const cancelled = cancelJob(job.id);
+ let editor: { job: string | null; cancelled: boolean; note?: string } = { job: editorJob, cancelled: false };
+ if (editorJob) {
+ const a = await editorCall("/api/ops/job", { method: "POST", body: { verb: "cancel", ids: [editorJob] } }).catch((err: Error) => ({ ok: false, status: 502, body: { error: err.message } as Record<string, unknown> }));
+ editor = a.ok ? { job: editorJob, cancelled: true } : { job: editorJob, cancelled: false, note: `the editor's job ${editorJob} was not cancelled (${String(a.body.error ?? `HTTP ${a.status}`)}): cancel it on the editor's /jobs` };
+ } else if (cancelled) editor = { job: null, cancelled: false, note: "the editor's job was not known yet: if one started, cancel it on the editor's /jobs" };
+ return Response.json({ ok: true, cancelled, editor }, { headers: noStore });
+ }
+ if (["keep", "again", "discard-preview", "finish", "discard"].includes(String(body.op)) && filterRunning(r.project.id, e.id)) return busy();
+ if (body.op === "keep") {
+ if (body.filtered === true) {
+ // The preview's files made the takes: it must be OF this recording and these marks (nothing is converted here).
+ const doc = await readPreview(r.project.dir, e, label);
+ const view = previewView(doc);
+ if (!view?.raw) return Response.json({ error: "there is no preview to keep: Filter it first" }, { status: 409 });
+ if (spans && view.parts.some((p: { span: { from: number; to: number } | null }, k: number) => spans[k] && p.span && (Math.abs(p.span.from - spans[k]!.from) > 0.002 || Math.abs(p.span.to - spans[k]!.to) > 0.002))) {
+ return Response.json({ error: "the cut marks moved since the Filter: Filter again, or keep the recording alone" }, { status: 409 });
+ }
+ // Of the session as it is NOW: a part recorded again since the Filter is another recording (409, nothing kept).
+ const kept = await keepPreview(r.project, e, { label, script, parts: doc?.session ? await sessionParts(r.project.dir, e, label) : null });
+ if (kept.session) await clearSession(r.project.dir, e, label);
+ return Response.json({ ok: true, takes: kept.takes, picked: kept.picked, notes: kept.notes, disclosure: kept.disclosure, entry: kept.entry, token: kept.token }, { headers: noStore });
+ }
+ const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script, spans });
+ await discardPreview(r.project.dir, e, label);
+ return Response.json({ ok: true, takes: [{ step: "recorded", file: kept.take.file }], picked: kept.take.file, notes: [], entry: kept.result.entry, token: kept.result.token }, { headers: noStore });
+ }
+ if (body.op === "again") {
+ await discardPreview(r.project.dir, e, label);
+ const session = body.n === undefined || body.n === null ? await readSession(r.project.dir, e, label) : await discardPart(r.project.dir, e, Number(body.n), label);
+ return Response.json({ ok: true, session }, { headers: noStore });
+ }
+ if (body.op === "discard-preview") {
+ await discardPreview(r.project.dir, e, label);
+ return Response.json({ ok: true }, { headers: noStore });
+ }
+ if (body.op === "stock") {
+ // The character's stock voice reading the line -- what the redaction, the slur filter and the lexicon leave of it.
+ const who = await whoOf(r.project.dir, e);
+ const ref = voiceRefOf(who.synthetic?.voice ?? "") as { engine: string | null; voice: string } | null;
+ const speed = ref?.engine && ref.engine !== "orpheus" && typeof who.synthetic?.speed === "number" ? who.synthetic.speed : null;
+ if (!ref?.engine) return Response.json({ error: "this post's character has no synthetic voice to hear" }, { status: 400 });
+ const text = String(body.text ?? "").trim();
+ if (!text) return Response.json({ error: "no line to read" }, { status: 400 });
+ const red = await projectRedaction(r.project.dir, r.manifest as Record<string, unknown>);
+ const spoken = String(spokenRead(text, e, red, { voice: red?.slurs?.voice === "beep" ? "skip" : undefined }).text);
+ const key = partKey(ref.engine, ref.voice, spoken, speed) as string;
+ const abs = path.join(r.project.dir, ...stockRel(key).split("/"));
+ if ((await stat(abs).catch(() => null))?.isFile()) return Response.json({ ok: true, cached: true, file: stockRel(key), voice: who.synthetic?.voice }, { headers: noStore });
+ if (body.cachedOnly === true) return Response.json({ ok: true, cached: false, voice: who.synthetic?.voice }, { headers: noStore });
+ await mkdir(path.dirname(abs), { recursive: true });
+ // The job writes BESIDE the cache; its poll renames it in (a half-written read is never a cached part).
+ const jobId = await startEditorJob("/api/ops/tts", { text: spoken, engine: ref.engine, voice: ref.voice, out: `${abs}.pending.tmp.wav`, ...(speed ? { speed } : {}) });
+ return Response.json({ ok: true, cached: false, jobId, key, voice: who.synthetic?.voice }, { headers: noStore });
+ }
+ return Response.json({ error: "op is discard, finish, prepare, filter, cancel, keep, again, discard-preview or stock" }, { status: 400 });
} catch (err) {
return fail(err);
}
}
+
+/** A body's `spans` as cut marks per part: `[{from, to} | null]`, or null when it gives none. */
+function spansOf(v: unknown): Array<{ from: number; to: number } | null> | null {
+ if (!Array.isArray(v) || !v.length || v.length > 200) return null;
+ const out = v.map((x) => {
+ const sp = x as { from?: unknown; to?: unknown } | null;
+ return sp && typeof sp.from === "number" && typeof sp.to === "number" && Number.isFinite(sp.from) && Number.isFinite(sp.to) && sp.to - sp.from >= 0.2 && sp.from >= 0 ? { from: Math.round(sp.from * 1000) / 1000, to: Math.round(sp.to * 1000) / 1000 } : null;
+ });
+ return out.some(Boolean) ? out : null;
+}
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -23,7 +23,7 @@ import { projectRedaction } from "@/lib/report/postRedaction.mjs";
import { spokenRead } from "umtool-report-to-video/post-redact";
import { recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs";
-import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
+import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
export const dynamic = "force-dynamic";
@@ -47,8 +47,11 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// GET ?project&id&convert=1 what a convert of this post defaults to: its author's character in
// the cast (else the narrator) and that character's convert
// target -- {character, convert: {engine, voice, pitch?, semitones?}}
-// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?, pitch?, semitones?}
-// a NEW take made from take `from` by the editor's voice op
+// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?, pitch?, semitones?, as?}
+// a NEW take made from take `from` by the editor's voice op; a
+// convert's engine, voice, pitch and semitones default to the
+// CHARACTER's recorded preset (`as`, else the post's), and with
+// none and no voice it is refused -- the answer names what was asked
// (a job; kept by GET ?job&derive=<from>[&pitch&semitones]);
// `installed: false` when the editor has no engine for it. A
// convert's `pitch` (target | source | contour) and `semitones`
@@ -274,11 +277,24 @@ async function postHere(request: Request) {
if (!t) return Response.json({ error: `${id} has no take ${from + 1}` }, { status: 404 });
const op = String(body.op2 ?? "");
if (!(POST_DERIVE_OPS as readonly string[]).includes(op)) return Response.json({ error: `op2 is one of ${POST_DERIVE_OPS.join(", ")}` }, { status: 400 });
- const engine = body.engine ? String(body.engine) : null;
- const voice = body.voice ? String(body.voice) : null;
+ let engine = body.engine ? String(body.engine) : null;
+ let voice = body.voice ? String(body.voice) : null;
// A convert's pitch (target | source | contour) and semitones, checked here; the editor refuses what its engine cannot do.
- const pitched = derivePitchOf({ pitch: body.pitch, semitones: body.semitones }, op);
- if (!pitched.ok) return Response.json({ error: pitched.error }, { status: 400 });
+ const checked = derivePitchOf({ pitch: body.pitch, semitones: body.semitones }, op);
+ if (!checked.ok) return Response.json({ error: checked.error }, { status: 400 });
+ let pitch: { pitch?: string; semitones?: number } = checked.value ?? {};
+ if (op === "convert") {
+ // A convert is the CHARACTER's (the CLI's rule, derivePitch.mjs convertAskOf): what the body does not name is
+ // its recorded preset's -- engine, stock voice, pitch, semitones -- and with no character and no voice it is
+ // refused: the editor's default voice is never asked for.
+ const who = (await readLayers(r.project.dir)).characterForRead(e, typeof body.as === "string" && body.as ? body.as : null);
+ if (typeof body.as === "string" && body.as && !who?.character) return Response.json({ error: `no such character: ${body.as}` }, { status: 400 });
+ const d = convertAskOf({ engine, voice, ...pitch }, who?.character ? recordedPresetOf(who.character).convert : null, who?.character?.id ?? null);
+ if (!d.ok) return Response.json({ error: `${d.error}: name a stock voice here, or give the character one on the Voices page` }, { status: 400 });
+ engine = d.value.engine ?? null;
+ voice = d.value.voice;
+ pitch = { ...(d.value.pitch !== undefined ? { pitch: d.value.pitch } : {}), ...(d.value.semitones !== undefined ? { semitones: d.value.semitones } : {}) };
+ }
const pid = postIdOf(e);
const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
@@ -290,8 +306,8 @@ async function postHere(request: Request) {
: null;
try {
// `voice` is the convert op's stock target; enhance takes none.
- const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...pitched.value, ...(parts ? { parts } : {}) });
- return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice, ...pitched.value }, { headers: noStore });
+ const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice && op === "convert" ? { voice } : {}), ...pitch, ...(parts ? { parts } : {}) });
+ return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice, ...pitch }, { headers: noStore });
} catch (err) {
const status = (err as { status?: number }).status ?? 502;
const msg = err instanceof Error ? err.message : String(err);
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -234,7 +234,9 @@ export default function PostNarrationPanel({
setChain([]);
return;
}
- if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null, pitch: step.pitch ?? null, semitones: step.semitones ?? null } });
+ // What the server asked the editor with (a convert's defaults are its character's): the keeper records those.
+ const asked = (k: string) => (typeof j?.[k] === "string" && j[k] ? (j[k] as string) : null);
+ if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: asked("engine") ?? step.engine ?? null, voice: asked("voice") ?? step.voice ?? null, pitch: asked("pitch") ?? step.pitch ?? null, semitones: typeof j.semitones === "number" ? j.semitones : step.semitones ?? null } });
};
const retake = async () => {
const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script });
diff --git a/umtool/components/projects/RecordFilter.tsx b/umtool/components/projects/RecordFilter.tsx
@@ -0,0 +1,206 @@
+"use client";
+
+import { useCallback, useRef, useState, type PointerEvent as RPointerEvent } from "react";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// RECORD -> FILTER -> PREVIEW, the record page's pieces (RecordSession.tsx; the
+// chain is lib/report/recordPreview.mjs, its route app/api/report/post-narration/
+// record): the types the page and the route share, a part's WAVEFORM with its
+// two CUT MARKS (draggable; the arrow keys move one 0.05 s), and the Filter
+// job's progress -- each stage's state, and a wait at the editor's queue or the
+// machine's heavy slot said as what it is: the gate working, not an error.
+// ---------------------------------------------------------------------------
+
+export type Span = { from: number; to: number };
+export type PreviewPart = { n: number; text: string; seconds: number; auto: Span; peaks: number[]; span: Span | null };
+export type Made = { seconds: number | null; lufs: number | null };
+export type Preview = {
+ id: string;
+ source: string;
+ trim: { on: boolean; padMs: number | null };
+ parts: PreviewPart[];
+ cleaned: "done" | "skipped" | "off" | null;
+ raw: Made | null;
+ clean: Made | null;
+ filtered: (Made & { engine: string | null; voice: string; pitch: string; semitones: number; asked: { pitch?: string; semitones?: number } | null }) | null;
+ notes: string[];
+};
+export type Who = {
+ character: { id: string; name: string; layer: string; scope: "project" | "cast" } | null;
+ convert: { engine: string | null; voice: string | null; pitch?: string; semitones?: number } | null;
+ recorded: { enhance: boolean; trim: { on: boolean; padMs: number | null }; direction: string | null } | null;
+ synthetic: { voice: string; speed: number | null } | null;
+ pitchEngines: string[];
+};
+export type FilterJob = {
+ id: string;
+ state: "running" | "done" | "failed";
+ startedAt: number;
+ endedAt: number | null;
+ stage: string | null;
+ stageState: string | null;
+ message: string | null;
+ waiting: "queued" | "memory" | "slot" | null;
+ waited: string[];
+ editorJob?: string | null;
+ stages: Record<string, { state?: string; message?: string }>;
+ error: string | null;
+};
+
+const r3 = (v: number) => Math.round(v * 1000) / 1000;
+export const sameSpan = (a: Span | null | undefined, b: Span | null | undefined) => !!a && !!b && Math.abs(a.from - b.from) < 0.002 && Math.abs(a.to - b.to) < 0.002;
+
+/** The least a cut may keep, and one press of an arrow key. */
+const MIN_KEPT = 0.2;
+const NUDGE = 0.05;
+
+/**
+ * A part's waveform with its cut marks: what is outside them is dimmed (it is cut), the dashed lines are the auto
+ * trim's answer. Drag a mark, or focus it and press the arrow keys (Shift: 0.25 s).
+ */
+export function TrimWave({ part, span, onChange, disabled = false }: { part: PreviewPart; span: Span; onChange: (s: Span) => void; disabled?: boolean }) {
+ const box = useRef<HTMLDivElement | null>(null);
+ const [drag, setDrag] = useState<"from" | "to" | null>(null);
+ const secs = Math.max(part.seconds, 0.001);
+ const pct = (t: number) => `${Math.max(0, Math.min(100, (t / secs) * 100))}%`;
+ const set = useCallback(
+ (edge: "from" | "to", t: number) => {
+ const v = edge === "from" ? Math.max(0, Math.min(span.to - MIN_KEPT, t)) : Math.min(secs, Math.max(span.from + MIN_KEPT, t));
+ onChange(edge === "from" ? { from: r3(v), to: span.to } : { from: span.from, to: r3(v) });
+ },
+ [span, secs, onChange],
+ );
+ const at = (ev: RPointerEvent) => {
+ const r = box.current?.getBoundingClientRect();
+ return r && r.width > 0 ? ((ev.clientX - r.left) / r.width) * secs : 0;
+ };
+ const mark = (edge: "from" | "to") => (
+ <button
+ type="button"
+ role="slider"
+ aria-label={edge === "from" ? `part ${part.n}: cut in` : `part ${part.n}: cut out`}
+ aria-valuemin={0}
+ aria-valuemax={r3(secs)}
+ aria-valuenow={span[edge]}
+ aria-valuetext={`${span[edge].toFixed(2)} s`}
+ disabled={disabled}
+ className={cn("absolute top-0 z-10 h-full w-3 -translate-x-1/2 cursor-ew-resize touch-none border-0 bg-transparent p-0", disabled && "cursor-default")}
+ style={{ left: pct(span[edge]) }}
+ onPointerDown={(ev) => {
+ if (disabled) return;
+ ev.currentTarget.setPointerCapture(ev.pointerId);
+ setDrag(edge);
+ }}
+ onPointerMove={(ev) => drag === edge && set(edge, at(ev))}
+ onPointerUp={() => setDrag(null)}
+ onPointerCancel={() => setDrag(null)}
+ onKeyDown={(ev) => {
+ const step = (ev.shiftKey ? 5 : 1) * NUDGE;
+ if (ev.key === "ArrowLeft" || ev.key === "ArrowDown") set(edge, span[edge] - step);
+ else if (ev.key === "ArrowRight" || ev.key === "ArrowUp") set(edge, span[edge] + step);
+ else return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ }}
+ data-record-mark={edge}
+ data-record-mark-at={span[edge]}
+ >
+ <span className="mx-auto block h-full w-0.5 bg-amber-400" />
+ <span className={cn("absolute h-2 w-2 -translate-x-1/2 rounded-full bg-amber-400", edge === "from" ? "left-1/2 top-0" : "bottom-0 left-1/2")} />
+ </button>
+ );
+ const n = part.peaks.length || 1;
+ return (
+ <div className="space-y-1" data-record-wave={part.n} data-record-wave-auto={`${part.auto.from}-${part.auto.to}`}>
+ <div ref={box} className="relative h-14 w-full overflow-visible rounded bg-black/40">
+ <svg viewBox={`0 0 ${n} 100`} preserveAspectRatio="none" className="absolute inset-0 h-full w-full text-emerald-500" aria-hidden="true">
+ {part.peaks.map((v, i) => {
+ const h = Math.max(1.5, Math.min(100, v * 100));
+ return <rect key={i} x={i + 0.15} y={50 - h / 2} width={0.7} height={h} fill="currentColor" />;
+ })}
+ </svg>
+ {/* What the marks cut away. */}
+ <div className="absolute inset-y-0 left-0 bg-black/65" style={{ width: pct(span.from) }} />
+ <div className="absolute inset-y-0 right-0 bg-black/65" style={{ width: `${Math.max(0, 100 - (span.to / secs) * 100)}%` }} />
+ {/* The auto trim's answer. */}
+ <div className="absolute inset-y-0 w-px border-l border-dashed border-white/40" style={{ left: pct(part.auto.from) }} />
+ <div className="absolute inset-y-0 w-px border-l border-dashed border-white/40" style={{ left: pct(part.auto.to) }} />
+ {mark("from")}
+ {mark("to")}
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <span className="font-mono tabular-nums" data-record-span={`${span.from}-${span.to}`}>
+ cut in {span.from.toFixed(2)} s · out {span.to.toFixed(2)} s · keeps {(span.to - span.from).toFixed(2)} of {part.seconds.toFixed(2)} s
+ </span>
+ {!sameSpan(span, part.auto) && (
+ <button type="button" className="ink-link" disabled={disabled} onClick={() => onChange(part.auto)} data-record-span-auto="">
+ back to the auto trim
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+const STAGES: Array<[string, string]> = [["clean", "Clean"], ["trim", "Cut"], ["convert", "Convert"]];
+const mmss = (ms: number) => `${Math.floor(ms / 60000)}:${String(Math.floor((ms % 60000) / 1000)).padStart(2, "0")}`;
+
+/** What a wait is, in a sentence: the gate working. */
+export const waitText = (w: FilterJob["waiting"]) =>
+ w === "memory" ? "waiting for memory — the machine's heavy slot lets it in when there is room. This is the gate working, not an error."
+ : w === "slot" ? "waiting for the heavy slot — another heavy job (a render, a build, a test run) holds it. This is the gate working, not an error."
+ : w === "queued" ? "queued at the editor behind its other voice jobs."
+ : "";
+
+/** The Filter job as it runs: the three stages, the wait when it waits, how long it has run. */
+export function FilterProgress({ job, now, onCancel }: { job: FilterJob; now: number; onCancel: () => void }) {
+ const running = job.state === "running";
+ return (
+ <div className="space-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12.5px]" data-record-filter-job={job.state} data-record-filter-stage={job.stage ?? ""} data-record-filter-waiting={job.waiting ?? ""} data-record-filter-waited={(job.waited ?? []).join(" ")}>
+ <div className="flex flex-wrap items-center gap-2">
+ {STAGES.map(([key, label]) => {
+ const st = job.stages[key]?.state;
+ const here = running && job.stage === key;
+ const wait = here && job.waiting;
+ return (
+ <span
+ key={key}
+ className={cn(
+ "rounded px-1.5 py-0.5",
+ wait ? "bg-amber-400/25" : here ? "bg-[var(--color-sel)]/25" : st === "done" || st === "cached" ? "bg-emerald-500/20" : st === "skipped" ? "bg-white/10 text-text-2" : "text-text-2",
+ )}
+ data-record-filter-step={key}
+ data-record-filter-step-state={st ?? ""}
+ >
+ {label}
+ {wait ? ": waiting" : here ? "…" : st === "done" ? " ✓" : st === "cached" ? " ✓ (kept from before)" : st === "skipped" ? " — skipped" : ""}
+ </span>
+ );
+ })}
+ <span className="font-mono tabular-nums text-text-2" data-record-filter-elapsed="">
+ {mmss((job.endedAt ?? now) - job.startedAt)}
+ </span>
+ {running && (
+ <button type="button" className="ink-link" onClick={onCancel} data-record-filter-cancel="">
+ Cancel
+ </button>
+ )}
+ </div>
+ {running && job.waiting && (
+ <div className="text-amber-300" data-record-filter-wait={job.waiting}>
+ {waitText(job.waiting)}
+ </div>
+ )}
+ {running && !job.waiting && <div className="text-text-2">{job.message ?? "starting…"} — a short read takes two or three minutes here.</div>}
+ {job.state === "done" && (job.waited ?? []).some((w) => w !== "queued") && (
+ <div className="text-text-2">it waited at the heavy slot ({(job.waited ?? []).filter((w) => w !== "queued").map((w) => (w === "memory" ? "for memory" : "for another heavy job")).join(", ")}) on the way: the gate, not a fault</div>
+ )}
+ {job.state === "failed" && (
+ <div className="text-[var(--color-blocking,#c33)]" data-record-filter-error="">
+ the Filter did not finish: {job.error ?? "it failed"}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx
@@ -3,10 +3,11 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { postBenchHref } from "@/lib/hrefs";
+import { postBenchHref, voicesHref } from "@/lib/hrefs";
import { scriptParts } from "umtool-report-to-video/post-narration";
import { redactText } from "umtool-report-to-video/post-redact";
import { MIC_KEY, ls, useMic } from "./useMic";
+import { FilterProgress, TrimWave, sameSpan, type FilterJob, type Preview, type Span, type Who } from "./RecordFilter";
// ---------------------------------------------------------------------------
// THE RECORDING SESSION, the client half (RecordPage.tsx): one post at a time,
@@ -23,6 +24,23 @@ import { MIC_KEY, ls, useMic } from "./useMic";
// and a reload resumes; when the last part is in, the post's recorded take is
// made (trimmed, joined with the parts' pauses, levelled to the placeholder's)
// and PICKED.
+//
+// RECORD -> FILTER -> PREVIEW ("Filter before keeping": on when the post's
+// character has a stock voice to convert to; lib/report/recordPreview.mjs): the
+// last part in, the post WAITS -- each part's waveform with its cut marks (the
+// auto trim's answer, draggable), the pitch the converted read lands on, and
+//
+// f Filter: the character's recorded preset as ONE job (clean,
+// cut, convert), into a scratch dir -- no take -- then the raw
+// read and the filtered one play at one loudness
+// Enter Keep: the takes made from the preview's files (nothing is
+// converted again), picked, awaiting approval; the next post
+// not recorded yet is opened
+// Backspace / r Again: the preview dropped, the part recorded again
+//
+// The scratch dir (<project>/narration/.record-preview/<postId>.operator/) is
+// removed on Keep, on Again, and when the post or the page is left (unless its
+// Filter is still running: it is there when you come back).
// ---------------------------------------------------------------------------
type Part = { n: number; para: number; text: string; start?: number; seconds?: number; file?: string };
@@ -64,6 +82,12 @@ function SkipMarked({ text, skip }: { text: string; skip?: RecordItem["skip"] })
type Session = { count: number | null; parts: Record<string, { file: string; text: string; at: string }> };
const COUNT_KEY = "umtool.record.count-in";
+/** "Filter before keeping", when a person set it ("1" / "0"); unset: on for a post whose character converts. */
+const REVIEW_KEY = "umtool.record.filter-first";
+const RECORD_API = "/api/report/post-narration/record";
+/** The gain that plays a sound of `lufs` at the level of the quieter of the two (an <audio> can only turn down). */
+const levelFor = (lufs: number | null | undefined, other: number | null | undefined) =>
+ typeof lufs === "number" && typeof other === "number" && Number.isFinite(lufs) && Number.isFinite(other) ? Math.min(1, 10 ** ((Math.min(lufs, other) - lufs) / 20)) : 1;
const enc = encodeURIComponent;
const fileUrl = (project: string, rel: string) => `/api/report/file?project=${enc(project)}&path=${enc(rel)}`;
const postFileUrl = (project: string, rel: string) => `/api/report/post-item?project=${enc(project)}&file=${enc(rel)}`;
@@ -87,8 +111,113 @@ export default function RecordSession({ project, items: initial, start, box }: {
const [error, setError] = useState<string | null>(null);
const mic = useMic();
const kept = (n: number) => !!session.parts[String(n)] && session.count === parts.length;
+ // RECORD -> FILTER -> PREVIEW: who the post is read as, the preview as it stands, the marks and the pitch asked.
+ const [who, setWho] = useState<Who | null>(null);
+ const [reviewSet, setReviewSet] = useState<boolean | null>(null);
+ const [preview, setPreview] = useState<Preview | null>(null);
+ const [spans, setSpans] = useState<Span[]>([]);
+ const [pitch, setPitch] = useState("target");
+ const [semitones, setSemitones] = useState("0");
+ const [fjob, setFjob] = useState<FilterJob | null>(null);
+ const [now, setNow] = useState(0);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [saved, setSaved] = useState<string | null>(null);
+ const [lastKept, setLastKept] = useState<string | null>(null);
+ const [stock, setStock] = useState<{ state: "idle" | "cached" | "asking" | "failed"; file?: string; error?: string }>({ state: "idle" });
+ // The microphone needs a secure context (localhost, https): a page opened from the LAN over http has none.
+ const [micOk, setMicOk] = useState(true);
+ useEffect(() => setMicOk(typeof window !== "undefined" && window.isSecureContext && !!navigator.mediaDevices?.getUserMedia), []);
+ useEffect(() => {
+ const v = ls.get(REVIEW_KEY);
+ setReviewSet(v === "1" ? true : v === "0" ? false : null);
+ }, []);
+ const converts = !!who?.convert?.voice;
+ // On by itself for a post whose character converts; while the next post's character loads it stays as it was.
+ const autoReview = useRef(false);
+ if (who) autoReview.current = converts;
+ const review = reviewSet ?? (who ? converts : autoReview.current);
+ const pitched = !!who?.convert?.engine && (who.pitchEngines ?? []).includes(who.convert.engine);
+ const semis = Number(semitones || 0);
+ const semisBad = pitched && pitch !== "target" && !(Number.isFinite(semis) && Math.abs(semis) <= 12);
+ const asked = pitched ? { pitch, semitones: pitch === "target" ? 0 : semis } : null;
useEffect(() => setCountIn(ls.get(COUNT_KEY) !== "0"), []);
+ const postOp = useCallback(
+ async (body: Record<string, unknown>) => {
+ const r = await fetch(RECORD_API, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: item.id, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ return { ok: r.ok, status: r.status, j };
+ },
+ [project, item.id],
+ );
+ // Who this post is read as (its direction, its convert), the preview a Filter left, the Filter still running.
+ const spanSource = useRef<string | null>(null);
+ const takePreview = useCallback((p: Preview | null) => {
+ setPreview(p);
+ if (!p) return;
+ setSpans(p.parts.map((x) => x.span ?? x.auto));
+ spanSource.current = p.source;
+ }, []);
+ const dropPreview = useCallback(() => {
+ setPreview(null);
+ spanSource.current = null;
+ setFjob(null);
+ }, []);
+ const loadWho = useCallback(async () => {
+ const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&preview`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as Partial<Who> & { preview?: Preview | null; job?: FilterJob | null };
+ const w: Who = { character: j.character ?? null, convert: j.convert ?? null, recorded: j.recorded ?? null, synthetic: j.synthetic ?? null, pitchEngines: j.pitchEngines ?? [] };
+ setWho(w);
+ setPitch(j.preview?.filtered?.asked?.pitch ?? w.convert?.pitch ?? "target");
+ setSemitones(String(j.preview?.filtered?.asked?.semitones ?? w.convert?.semitones ?? 0));
+ takePreview(j.preview ?? null);
+ setFjob(j.job && j.job.state === "running" ? j.job : null);
+ return w;
+ }, [project, item.id, takePreview]);
+ // Whether the last part in WAITS (Filter before keeping), asked when it lands: what a person set, else whether the
+ // post's character converts -- the character awaited, so a part that lands before it has loaded is not kept at once.
+ const whoReady = useRef<Promise<Who | null>>(Promise.resolve(null));
+ const reviewAsked = useRef<boolean | null>(null);
+ reviewAsked.current = reviewSet;
+ const waits = useCallback(async () => reviewAsked.current ?? !!(await whoReady.current.catch(() => null))?.convert?.voice, []);
+ useEffect(() => {
+ setWho(null);
+ setPreview(null);
+ setSpans([]);
+ spanSource.current = null;
+ setFjob(null);
+ setSaved(null);
+ setStock({ state: "idle" });
+ whoReady.current = loadWho();
+ void whoReady.current.catch(() => {});
+ }, [loadWho]);
+ // LEAVING the post (another one, the page closed): its scratch dir goes -- unless its Filter is still running.
+ const running = useRef(false);
+ running.current = fjob?.state === "running";
+ const leaving = useRef<{ id: string; timer: ReturnType<typeof setTimeout> } | null>(null);
+ useEffect(() => {
+ // The same post again at once (a development build mounts an effect twice): it was not left.
+ if (leaving.current?.id === item.id) clearTimeout(leaving.current.timer);
+ leaving.current = null;
+ const id = item.id;
+ const wasRunning = () => running.current;
+ const drop = () => {
+ try {
+ navigator.sendBeacon(RECORD_API, new Blob([JSON.stringify({ project, id, op: "discard-preview" })], { type: "application/json" }));
+ } catch {
+ // no beacon here: the scratch dir is removed a day later (recordPreview.mjs)
+ }
+ };
+ const onHide = () => {
+ if (!wasRunning()) drop();
+ };
+ window.addEventListener("pagehide", onHide);
+ return () => {
+ window.removeEventListener("pagehide", onHide);
+ if (wasRunning()) return;
+ leaving.current = { id, timer: setTimeout(drop, 150) };
+ };
+ }, [project, item.id]);
// The post's session: what was kept before (a reload resumes at the first part not kept).
const loadSession = useCallback(async () => {
const r = await fetch(`/api/report/post-narration/record?project=${enc(project)}&id=${enc(item.id)}`, { cache: "no-store" });
@@ -110,6 +239,53 @@ export default function RecordSession({ project, items: initial, start, box }: {
}, [loadSession, item.id]);
const done = parts.length > 0 && parts.every((p) => kept(p.n));
+ // The post waits to be filtered and kept: every part in, "Filter before keeping" on.
+ const reviewing = review && done;
+ // The marks and the pitch the filtered read was made with: moved since, it is not what Keep would keep.
+ const filtered = preview?.filtered ?? (preview?.cleaned === "done" && preview.clean ? preview.clean : null);
+ const current =
+ !!preview?.raw && !!filtered && preview.parts.length === spans.length && preview.parts.every((p, k) => sameSpan(p.span, spans[k])) &&
+ (!preview.filtered || !asked || ((preview.filtered.asked?.pitch ?? "target") === asked.pitch && (preview.filtered.asked?.semitones ?? 0) === asked.semitones));
+
+ // The parts decoded once the last one is in: their waveforms and the auto trim's marks (no editor, no take).
+ const sessionAt = Object.values(session.parts).map((p) => p.at).join("|");
+ useEffect(() => {
+ if (!reviewing) return;
+ let live = true;
+ void (async () => {
+ const { ok, j } = await postOp({ op: "prepare" });
+ if (!live) return;
+ if (!ok) return setError(String(j.error ?? "the recording could not be read"));
+ const p = j.preview as Preview;
+ // Marks a person set stand for the same recording; a new recording starts from the auto trim's.
+ if (spanSource.current === p.source) setPreview(p);
+ else takePreview(p);
+ })();
+ return () => {
+ live = false;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [reviewing, sessionAt, postOp, takePreview]);
+
+ // The Filter job, followed to its end.
+ useEffect(() => {
+ if (fjob?.state !== "running") return;
+ setNow(Date.now());
+ const clock = setInterval(() => setNow(Date.now()), 1000);
+ let live = true;
+ const poll = setInterval(async () => {
+ const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&job=${enc(fjob.id)}`, { cache: "no-store" }).catch(() => null);
+ const j = (await r?.json().catch(() => null)) as { job?: FilterJob; preview?: Preview | null } | null;
+ if (!live || !j?.job) return;
+ setFjob(j.job);
+ if (j.job.state === "done" && j.preview) takePreview(j.preview);
+ }, 1000);
+ return () => {
+ live = false;
+ clearInterval(clock);
+ clearInterval(poll);
+ };
+ }, [fjob?.state, fjob?.id, project, item.id, takePreview]);
const finish = useCallback(async () => {
setPhase("finishing");
@@ -168,12 +344,123 @@ export default function RecordSession({ project, items: initial, start, box }: {
setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`} — record it again`);
return;
}
+ // Another recording than the one a preview was made from: that preview is gone (the server dropped it too).
+ dropPreview();
setSession(j.session);
const s = j.session;
const next = parts.findIndex((q) => !(s.parts[String(q.n)] && s.count === parts.length));
- if (next < 0) await finish();
- else setCur(next);
- }, [phase, mic, parts, cur, project, item.id, finish]);
+ // The last part in: the take is made -- or, with "Filter before keeping", the post waits to be filtered and kept.
+ if (next >= 0) setCur(next);
+ else if (!(await waits())) await finish();
+ }, [phase, mic, parts, cur, project, item.id, finish, waits, dropPreview]);
+
+ // A sound file for the current part (a recording made elsewhere: a phone's recorder, the LAN where the mic is off).
+ const takeFile = useCallback(
+ async (file: File) => {
+ if (phase !== "idle" || !parts[cur]) return;
+ setError(null);
+ setPhase("saving");
+ const p = parts[cur];
+ const fd = new FormData();
+ fd.set("project", project);
+ fd.set("id", item.id);
+ fd.set("n", String(p.n));
+ fd.set("count", String(parts.length));
+ fd.set("text", p.text);
+ fd.set("para", String(p.para));
+ fd.set("part", file, file.name || `p${p.n}.wav`);
+ const r = await fetch(RECORD_API, { method: "POST", body: fd });
+ const j = (await r.json().catch(() => ({}))) as { session?: Session; error?: string };
+ setPhase("idle");
+ if (!r.ok || !j.session) return setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`}`);
+ dropPreview();
+ setSession(j.session);
+ const sdoc = j.session;
+ const next = parts.findIndex((q) => !(sdoc.parts[String(q.n)] && sdoc.count === parts.length));
+ if (next >= 0) setCur(next);
+ else if (!(await waits())) await finish();
+ },
+ [phase, parts, cur, project, item.id, finish, waits, dropPreview],
+ );
+
+ // FILTER: the character's recorded preset as one job -- clean, cut at the marks, convert -- into the scratch dir.
+ const filter = useCallback(async () => {
+ if (!reviewing || phase !== "idle" || fjob?.state === "running" || semisBad) return;
+ setError(null);
+ setStatus(null);
+ const { ok, j } = await postOp({ op: "filter", spans, ...(asked ? { pitch: asked.pitch, ...(asked.pitch !== "target" ? { semitones: asked.semitones } : {}) } : {}) });
+ if (!ok || !j.job) return setError(String(j.error ?? "the Filter did not start"));
+ setFjob(j.job as FilterJob);
+ }, [reviewing, phase, fjob?.state, semisBad, postOp, spans, asked]);
+
+ // KEEP: the preview's files made the takes (when it is of these marks and this pitch), else the recording alone.
+ const keep = useCallback(async () => {
+ // No preview: the recording is still being read (a part just landed) -- there is nothing to judge or keep yet.
+ if (!reviewing || phase !== "idle" || fjob?.state === "running" || !preview) return;
+ setError(null);
+ setPhase("finishing");
+ const { ok, j } = await postOp({ op: "keep", filtered: current, spans, script: item.script });
+ setPhase("idle");
+ if (!ok || !j.picked) return setError(String(j.error ?? "it was not kept"));
+ const takes = (j.takes ?? []) as Array<{ step: string; file: string }>;
+ setItems((xs) => xs.map((x) => (x.id === item.id ? { ...x, recorded: true, plays: "recorded" } : x)));
+ setSession({ count: null, parts: {} });
+ setPreview(null);
+ spanSource.current = null;
+ const said = `kept post ${item.n}: ${takes.map((t) => `${t.step} (${t.file.split("/").pop()})`).join(", ")} — picked, awaiting approval`;
+ setLastKept(said);
+ // The next post not recorded yet (after this one, else before it); none: this one stays, and says so.
+ const order = [...items.keys()].filter((i) => i !== at);
+ const next = order.find((i) => i > at && !items[i].recorded) ?? order.find((i) => !items[i].recorded);
+ if (next === undefined) setStatus(`${said}. Every post is recorded.`);
+ else setAt(next);
+ }, [reviewing, phase, fjob?.state, preview, postOp, current, spans, item.script, item.id, item.n, items, at]);
+
+ // The pitch asked here, written back to the character (the Voices page's own write: POST /api/report/voices).
+ const voices = useCallback(
+ async (body: Record<string, unknown>) => {
+ const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; character?: { id?: string } };
+ return { ok: r.ok, j };
+ },
+ [project],
+ );
+ const saveToCharacter = useCallback(async () => {
+ const c = who?.character;
+ if (!c || !asked || semisBad) return;
+ setBusy("save");
+ setSaved(null);
+ const { ok, j } = await voices({ op: "character-set", scope: c.scope, id: c.id, convertPitch: asked.pitch, convertSemitones: String(asked.semitones) });
+ setBusy(null);
+ if (!ok) return setError(String(j.error ?? "the character was not changed"));
+ setSaved(`saved to ${c.name}${c.scope === "cast" ? " (the cast: every project)" : " (this video's own)"}`);
+ setWho((w) => (w ? { ...w, convert: w.convert ? { ...w.convert, pitch: asked.pitch, semitones: asked.semitones } : w.convert } : w));
+ }, [who, asked, semisBad, voices]);
+ // "Keep in this video only": the post's author given a character of this video's own (the narrator's convert with
+ // it, at the pitch asked here) -- the cast, and every other project, stay as they are.
+ const keepInVideo = useCallback(async () => {
+ if (!item.handle) return;
+ setBusy("keep-in-video");
+ setSaved(null);
+ const made = await voices({ op: "character-keep", who: `@${item.handle}` });
+ const id = made.j.character?.id;
+ if (!made.ok || !id) {
+ setBusy(null);
+ return setError(String(made.j.error ?? "the character was not made"));
+ }
+ const cv = who?.convert;
+ if (cv?.voice) {
+ const set = await voices({
+ op: "character-set", scope: "project", id, convertVoice: cv.voice, ...(cv.engine ? { convertEngine: cv.engine } : {}),
+ ...(asked ? { convertPitch: asked.pitch, convertSemitones: String(asked.semitones) } : {}),
+ });
+ if (!set.ok) setError(String(set.j.error ?? "its convert was not set"));
+ }
+ setBusy(null);
+ whoReady.current = loadWho();
+ await whoReady.current.catch(() => null);
+ setSaved(`${id} is this video's own character for @${item.handle} now`);
+ }, [item.handle, voices, who, asked, loadWho]);
const redo = useCallback(async () => {
if (phase !== "idle") return;
@@ -187,6 +474,19 @@ export default function RecordSession({ project, items: initial, start, box }: {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [phase, parts, cur, project, item.id, record, session]);
+ // AGAIN: the preview dropped, the current part recorded again.
+ const again = useCallback(async () => {
+ if (phase !== "idle" || fjob?.state === "running") return;
+ const p = parts[cur];
+ const { j } = await postOp({ op: "again", ...(p && kept(p.n) ? { n: p.n } : {}) });
+ if (j.session) setSession(j.session as Session);
+ setPreview(null);
+ spanSource.current = null;
+ setFjob(null);
+ if (micOk) await record();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [phase, fjob?.state, parts, cur, postOp, record, session, micOk]);
+
const go = useCallback((k: number) => {
if (phase !== "idle") return;
setAt((x) => Math.max(0, Math.min(items.length - 1, x + k)));
@@ -199,31 +499,56 @@ export default function RecordSession({ project, items: initial, start, box }: {
// A text box or a select keeps its keys; a checkbox (the count-in) does not -- Space still records.
if (tgt?.closest("textarea, select, input:not([type=checkbox])")) return;
if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
+ // A key held down is one press: a held Space must not stop the recording it started, nor a held Enter keep twice.
+ if (ev.repeat) {
+ if ([" ", "Enter", "Backspace"].includes(ev.key) && !tgt?.closest("button, a, [role=slider]")) ev.preventDefault();
+ return;
+ }
+ // A button keeps its own Enter and Space (a cut mark keeps its arrows): the page's keys are for hands off it.
+ const onButton = !!tgt?.closest("button, a, [role=slider]");
+ // While the Filter runs the recording it reads is not recorded over: the keys wait for it (n / p still walk).
+ const filtering = fjob?.state === "running";
+ if (filtering && (ev.key === " " || ev.key === "r" || ev.key === "Backspace" || ev.key === "Enter" || ev.key === "f")) {
+ if (!onButton) ev.preventDefault();
+ return;
+ }
if (ev.key === " ") {
+ if (onButton) return;
ev.preventDefault();
if (phase === "recording") void stop();
- else void record();
- } else if (ev.key === "r") {
+ else if (micOk) void record();
+ } else if (ev.key === "r" || (ev.key === "Backspace" && reviewing)) {
ev.preventDefault();
- void redo();
+ if (reviewing) void again();
+ else if (micOk) void redo();
+ } else if (ev.key === "f" && reviewing) {
+ ev.preventDefault();
+ void filter();
} else if (ev.key === "Enter") {
+ if (onButton) return;
ev.preventDefault();
- if (done || item.recorded && !Object.keys(session.parts).length) go(1);
+ if (reviewing) void keep();
+ else if (done || item.recorded && !Object.keys(session.parts).length) go(1);
else if (phase === "idle") setCur((c) => Math.min(parts.length - 1, c + 1));
} else if (ev.key === "n") go(1);
else if (ev.key === "p") go(-1);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [phase, stop, record, redo, done, item.recorded, session.parts, go, parts.length]);
+ }, [phase, stop, record, redo, done, item.recorded, session.parts, go, parts.length, reviewing, again, filter, keep, micOk, fjob?.state]);
// Play a kept part back, or the placeholder's part for reference.
const player = useRef<HTMLAudioElement | null>(null);
const stopAt = useRef<number | null>(null);
- const play = (src: string, from = 0, seconds: number | null = null) => {
+ const then = useRef<(() => void) | null>(null);
+ const [playing, setPlaying] = useState<string | null>(null);
+ const play = (src: string, from = 0, seconds: number | null = null, { volume = 1, what = null, after = null }: { volume?: number; what?: string | null; after?: (() => void) | null } = {}) => {
const a = player.current;
if (!a) return;
a.src = src;
+ a.volume = volume;
+ then.current = after;
+ setPlaying(what);
a.currentTime = 0;
const go2 = () => {
try {
@@ -245,6 +570,30 @@ export default function RecordSession({ project, items: initial, start, box }: {
else play(fileUrl(project, ph.file));
};
+ // The raw read and the filtered one, at ONE loudness: the louder of the two turned down to the other's.
+ const previewUrl = (which: string, n?: number) => `${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&preview&file=${which}${n ? `&n=${n}` : ""}&v=${enc(`${preview?.source ?? ""}.${fjob?.id ?? ""}.${spans.map((x) => `${x.from}-${x.to}`).join(",")}`)}`;
+ const playRaw = (after: (() => void) | null = null) => play(previewUrl("raw"), 0, null, { volume: levelFor(preview?.raw?.lufs, filtered?.lufs), what: "raw", after });
+ const playFiltered = () => play(previewUrl(preview?.filtered ? "filtered" : "clean"), 0, null, { volume: levelFor(filtered?.lufs, preview?.raw?.lufs), what: "filtered" });
+ // The character's stock voice reading the line: the cached read when there is one, else asked of the editor.
+ const playStock = async () => {
+ const text = parts[cur]?.text;
+ if (!text || stock.state === "asking") return;
+ setStock({ state: "asking" });
+ const { ok, j } = await postOp({ op: "stock", text });
+ if (!ok) return setStock({ state: "failed", error: String(j.error ?? "it could not be asked") });
+ let file = typeof j.file === "string" ? j.file : null;
+ for (let i = 0; !file && typeof j.jobId === "string" && i < 600; i += 1) {
+ await new Promise((res) => setTimeout(res, 1000));
+ const r = await fetch(`${RECORD_API}?project=${enc(project)}&id=${enc(item.id)}&stock&job=${enc(j.jobId)}&key=${enc(String(j.key))}`, { cache: "no-store" }).catch(() => null);
+ const st = (await r?.json().catch(() => null)) as { state?: string; file?: string; error?: string } | null;
+ if (st?.state === "failed") return setStock({ state: "failed", error: st.error ?? "the editor's read failed" });
+ if (st?.state === "done" && st.file) file = st.file;
+ }
+ if (!file) return setStock({ state: "failed", error: "the editor's read did not come" });
+ setStock({ state: "cached", file });
+ play(fileUrl(project, file), 0, null, { what: "stock" });
+ };
+
const recordedCount = items.filter((x) => x.recorded).length;
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const scale = 0.42;
@@ -342,8 +691,30 @@ export default function RecordSession({ project, items: initial, start, box }: {
/>
count-in
</label>
- <span className="text-text-2">Space record / stop · r redo the part · Enter next part · n / p next / previous post</span>
+ <label className="flex items-center gap-1" title="The last part in, the post waits: Filter runs its character's recorded preset (clean, cut, convert) into a preview, and Keep makes the takes. Off: the last part makes the recorded take at once.">
+ <input
+ type="checkbox"
+ checked={review}
+ disabled={phase !== "idle" || fjob?.state === "running"}
+ onChange={(e) => {
+ setReviewSet(e.target.checked);
+ ls.set(REVIEW_KEY, e.target.checked ? "1" : "0");
+ }}
+ data-record-review=""
+ />
+ Filter before keeping
+ </label>
+ <span className="text-text-2">
+ {reviewing ? "f Filter · Enter Keep · Backspace / r Again · n / p next / previous post" : "Space record / stop · r redo the part · Enter next part · n / p next / previous post"}
+ </span>
</div>
+ {!micOk && (
+ <div className="rounded border border-amber-400/50 bg-amber-400/10 px-3 py-2 text-[13px]" role="note" data-record-no-mic="">
+ <b>The microphone is off on this page.</b> A browser opens it only on <code>localhost</code> or over https, and this page was opened over plain http from another machine. Record on
+ the machine umtool runs on (<code>http://localhost:…</code>), or choose a sound file for a part below. Everything else works here: Filter a recording already made, listen to the
+ preview, move the cut marks, Keep.
+ </div>
+ )}
{/* The teleprompter: every part, the current one large. */}
<ol className="m-0 list-none space-y-2 p-0" data-record-teleprompter="">
@@ -381,6 +752,186 @@ export default function RecordSession({ project, items: initial, start, box }: {
{!parts.length && <li className="text-text-2">no script yet — write one on its bench</li>}
</ol>
+ {/* Who it is read as: the character, its direction (for the person reading: never sent to a model), its stock voice. */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[13px]" data-record-character={who?.character?.id ?? ""} data-record-character-layer={who?.character?.layer ?? ""}>
+ {who?.character ? (
+ <>
+ <span>
+ read as <b data-record-character-name="">{who.character.name}</b>
+ <span className="text-text-2">
+ {" "}
+ ({who.character.layer === "narrator" ? "the cast's narrator: this author has no character" : who.character.scope === "project" ? "this video's own" : "the cast"})
+ </span>
+ </span>
+ {who.recorded?.direction && (
+ <span className="text-[15px] italic text-amber-300" data-record-direction="">
+ “{who.recorded.direction}”
+ </span>
+ )}
+ {who.synthetic?.voice ? (
+ <button
+ type="button"
+ className={btn}
+ disabled={stock.state === "asking" || !parts.length}
+ onClick={() => void playStock()}
+ title="The character's synthetic voice reading this line (its synthetic preset; a recording is converted to its convert voice, which may be another): the read kept from before when there is one, else the editor is asked to synthesize it (Kokoro is quick; Orpheus is slow and takes the heavy slot)."
+ data-record-stock={stock.state}
+ >
+ {stock.state === "asking" ? "asking the editor…" : `▶ ${who.synthetic.voice} reads it`}
+ </button>
+ ) : (
+ <span className="text-text-2">no synthetic voice to hear it in</span>
+ )}
+ {stock.state === "failed" && <span className="text-[var(--color-blocking,#c33)]" data-record-stock-error="">{stock.error}</span>}
+ </>
+ ) : (
+ <span className="text-text-2" data-record-no-character="">
+ {who ? `no character reads @${item.handle || "this author"}: a recording is cleaned and kept in your own voice` : "…"}
+ </span>
+ )}
+ {who && (!who.character || who.character.layer === "narrator") && item.handle && (
+ <button type="button" className={btn} disabled={busy !== null} onClick={() => void keepInVideo()} title={`Give @${item.handle} a character of this video's own${who.convert?.voice ? ", converted as here" : ""}; the cast and every other project stay as they are.`} data-record-keep-in-video="">
+ Keep in this video only
+ </button>
+ )}
+ <a href={voicesHref(project, { who: who?.character?.id ?? (item.handle ? `@${item.handle}` : null) })} className="ink-link ml-auto" data-record-voices-link="">
+ Voices ›
+ </a>
+ </div>
+
+ {/* RECORD -> FILTER -> PREVIEW: the post waits -- its cut marks, the pitch, the Filter, the two reads, Keep / Again. */}
+ {reviewing && (
+ <div className="space-y-3 rounded border border-amber-400/40 p-3" data-record-review-panel="" data-record-preview-current={current ? "1" : "0"}>
+ {preview ? (
+ preview.parts.map((p, k) => (
+ <div key={p.n} className="space-y-1">
+ {preview.parts.length > 1 && <div className="micro">part {p.n}</div>}
+ <TrimWave part={p} span={spans[k] ?? p.auto} disabled={fjob?.state === "running"} onChange={(sp) => setSpans((xs) => xs.map((x, i) => (i === k ? sp : x)))} />
+ <button
+ type="button"
+ className="ink-link text-[12px]"
+ onClick={() => play(previewUrl("part", p.n), (spans[k] ?? p.auto).from, (spans[k] ?? p.auto).to - (spans[k] ?? p.auto).from, { what: `part-${p.n}` })}
+ data-record-play-cut={p.n}
+ >
+ ▶ what the marks keep
+ </button>
+ </div>
+ ))
+ ) : (
+ <div className="text-[12.5px] text-text-2">reading the recording…</div>
+ )}
+ {preview && !preview.trim.on && <div className="text-[12px] text-text-2" data-record-trim-off="">its edges are kept as recorded (the character's preset: trim off) — the marks still cut where you put them</div>}
+ {pitched && (
+ <div className="flex flex-wrap items-center gap-2 text-[12.5px]" data-record-pitch-row="">
+ <label className="flex items-center gap-1">
+ pitch
+ <select value={pitch} onChange={(e) => setPitch(e.target.value)} disabled={fjob?.state === "running"} aria-label="the pitch the converted read lands on" data-record-pitch="">
+ <option value="target">target — the stock voice's own</option>
+ <option value="source">source — the pitch you read it at</option>
+ <option value="contour">contour — your rises and falls, at its register</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-1">
+ semitones
+ <input
+ type="number"
+ min={-12}
+ max={12}
+ step={0.5}
+ value={pitch === "target" ? "" : semitones}
+ disabled={pitch === "target" || fjob?.state === "running"}
+ onChange={(e) => setSemitones(e.target.value)}
+ placeholder="0"
+ className="w-16"
+ aria-label="semitones"
+ data-record-semitones=""
+ />
+ </label>
+ {semisBad && <span className="text-[var(--color-blocking,#c33)]">semitones is a number from -12 to 12</span>}
+ {who?.character && who.character.layer !== "narrator" && (
+ <button
+ type="button"
+ className={btn}
+ disabled={busy !== null || semisBad || ((who.convert?.pitch ?? "target") === asked?.pitch && (who.convert?.semitones ?? 0) === asked?.semitones)}
+ onClick={() => void saveToCharacter()}
+ title={`Write this pitch and these semitones to ${who.character.name}'s recorded preset${who.character.scope === "cast" ? " in the cast (every project)" : " (this video's own character)"}.`}
+ data-record-save-character=""
+ >
+ Save to character
+ </button>
+ )}
+ {saved && <span className="text-emerald-500" data-record-saved="">{saved}</span>}
+ </div>
+ )}
+ {!pitched && saved && <div className="text-[12.5px] text-emerald-500" data-record-saved="">{saved}</div>}
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ className={cn(buttonVariants({ variant: current ? "outline" : "go", size: "sm" }))}
+ disabled={phase !== "idle" || fjob?.state === "running" || !preview || semisBad}
+ onClick={() => void filter()}
+ title="Run the character's recorded preset on this recording — clean, cut at the marks, convert — as one job. No take is made: the result is a preview."
+ data-record-filter=""
+ >
+ {current ? "Filtered ✓" : preview?.raw ? "Filter again (f)" : "Filter (f)"}
+ </button>
+ <button
+ type="button"
+ className={cn(buttonVariants({ variant: current ? "go" : "outline", size: "sm" }))}
+ disabled={phase !== "idle" || fjob?.state === "running" || !preview}
+ onClick={() => void keep()}
+ title={current ? "Make the takes from the preview's files (nothing is converted again): the recording, the cleaned one, the converted one — the last picked, awaiting approval." : "Keep the recording alone, cut at the marks: one recorded take, picked."}
+ data-record-keep=""
+ data-record-keep-what={current ? "filtered" : "recording"}
+ >
+ {current ? "Keep (Enter)" : "Keep the recording alone (Enter)"}
+ </button>
+ <button type="button" className={btn} disabled={phase !== "idle" || fjob?.state === "running"} onClick={() => void again()} title="Drop the preview and record the part again." data-record-again="">
+ Again (Backspace)
+ </button>
+ </div>
+ {!current && preview?.raw && filtered && fjob?.state !== "running" && <div className="text-[12.5px] text-amber-300" data-record-preview-stale="">the marks or the pitch moved since the Filter: Filter again to hear and keep them</div>}
+ {fjob && (
+ <FilterProgress
+ job={fjob}
+ now={now}
+ onCancel={() =>
+ void postOp({ op: "cancel", job: fjob.id }).then(({ j }) => {
+ const note = (j.editor as { note?: string } | undefined)?.note;
+ if (note) setError(note);
+ })
+ }
+ />
+ )}
+ {preview?.raw && filtered && fjob?.state !== "running" && (
+ <div className="flex flex-wrap items-center gap-2 text-[12.5px]" data-record-compare="">
+ <button type="button" className={btn} onClick={() => playRaw()} data-record-play-raw="" data-record-playing={playing === "raw" ? "1" : undefined}>
+ ▶ Raw
+ </button>
+ <button type="button" className={btn} onClick={() => playFiltered()} data-record-play-filtered="" data-record-playing={playing === "filtered" ? "1" : undefined}>
+ ▶ Filtered
+ </button>
+ <button type="button" className={btn} onClick={() => playRaw(() => playFiltered())} data-record-play-both="">
+ ▶ Raw, then filtered
+ </button>
+ <span className="text-text-2" data-record-compare-what="">
+ {preview.cleaned === "done" ? "cleaned" : "not cleaned"}
+ {preview.filtered ? ` · converted to ${preview.filtered.voice}${preview.filtered.engine ? ` by ${preview.filtered.engine}` : ""}${preview.filtered.pitch !== "target" ? ` · pitch ${preview.filtered.pitch}${preview.filtered.semitones ? ` ${preview.filtered.semitones > 0 ? "+" : "−"}${Math.abs(preview.filtered.semitones)} st` : ""}` : ""}` : " · not converted"}
+ {" · both at one loudness"}
+ </span>
+ </div>
+ )}
+ {preview?.raw && !filtered && fjob?.state !== "running" && (
+ <div className="text-[12.5px] text-text-2" data-record-nothing-filtered="">nothing filtered it: no clean engine answered and no character converts it — Keep keeps the recording alone</div>
+ )}
+ {(preview?.notes ?? []).map((n) => (
+ <div key={n} className="text-[12px] text-text-2" data-record-preview-note="">
+ {n}
+ </div>
+ ))}
+ </div>
+ )}
+
<div className="flex flex-wrap items-center gap-2">
{phase === "count" && (
<span className="text-[28px] font-bold tabular-nums" data-record-count={count}>
@@ -390,24 +941,44 @@ export default function RecordSession({ project, items: initial, start, box }: {
<button
type="button"
className={cn(buttonVariants({ variant: phase === "recording" ? "outline" : "go", size: "sm" }))}
- disabled={(phase !== "idle" && phase !== "recording") || !parts.length}
+ disabled={(phase !== "idle" && phase !== "recording") || !parts.length || !micOk || fjob?.state === "running"}
onClick={() => void (phase === "recording" ? stop() : record())}
data-record-toggle=""
>
{phase === "recording" ? "Stop (Space)" : `Record part ${parts[cur]?.n ?? 1} (Space)`}
</button>
- <button type="button" className={btn} disabled={phase !== "idle" || !parts.length} onClick={() => void redo()} data-record-redo="">
+ <button type="button" className={btn} disabled={phase !== "idle" || !parts.length || !micOk || fjob?.state === "running"} onClick={() => void redo()} data-record-redo="">
Redo part (r)
</button>
<button type="button" className={btn} disabled={phase !== "idle" || cur >= parts.length - 1} onClick={() => setCur((c) => c + 1)} data-record-next-part="">
Next part (Enter)
</button>
+ <label className={cn(btn, "cursor-pointer")} title="A sound file for this part instead of the microphone: a recording made elsewhere (any sound ffmpeg reads).">
+ Use a sound file…
+ <input
+ type="file"
+ accept="audio/*,video/webm,video/mp4"
+ className="sr-only"
+ disabled={phase !== "idle" || !parts.length || fjob?.state === "running"}
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ e.target.value = "";
+ if (f) void takeFile(f);
+ }}
+ data-record-file=""
+ />
+ </label>
{phase === "recording" && <span className="text-red-400" data-record-recording="">● recording part {parts[cur]?.n}</span>}
{phase === "saving" && <span className="text-text-2">saving the part…</span>}
- {phase === "finishing" && <span className="text-text-2">joining the parts into the take…</span>}
+ {phase === "finishing" && <span className="text-text-2">{reviewing ? "making the takes…" : "joining the parts into the take…"}</span>}
{status && <span className="text-emerald-500" data-record-status="">{status}</span>}
{error && <span className="text-[var(--color-blocking,#c33)]" data-record-error="">{error}</span>}
</div>
+ {lastKept && (
+ <div className="text-[12.5px] text-emerald-500" data-record-last-kept="">
+ {lastKept}
+ </div>
+ )}
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
<audio
ref={player}
@@ -415,6 +986,12 @@ export default function RecordSession({ project, items: initial, start, box }: {
onTimeUpdate={(e) => {
if (stopAt.current !== null && e.currentTarget.currentTime >= stopAt.current) e.currentTarget.pause();
}}
+ onEnded={() => {
+ const next = then.current;
+ then.current = null;
+ setPlaying(null);
+ next?.();
+ }}
data-record-player=""
/>
</section>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -135,7 +135,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
| `posts character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2** |
| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
-| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l]` · `<item> --derive <n> --op convert [--engine e] [--voice v] [--pitch …] [--semitones n]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1** |
+| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l]` · `<item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]… [--engine e] [--voice v] [--events]` · `<item> --keep-preview` · `<item> --discard-preview` · `<item> --derive <n> --op convert [--as <character>] [--engine e] [--voice v] [--pitch …] [--semitones n]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**. **`--preview`** runs the same chain with NO TAKE made ([knobs.md](knobs.md#record-filter-preview-on-the-record-page); the record page's Filter): cleaned whole, cut (`--trim-span`: at these seconds of the recording instead of the auto trim's), converted, into the scratch dir `narration/.record-preview/<postId>.<label>/` -- its paths printed, `--out <file>` a copy of the filtered read; without `--recording` it is the record page's session of the item. A step whose inputs stand is not run again (another `--pitch`: the convert alone). `--keep-preview` makes its takes from those files (nothing converted again), `--discard-preview` removes it. **`--derive <n> --op convert`** is the character's too: its recorded preset's engine, stock voice, pitch and semitones, each unless its flag says otherwise (`--as` names another character); no character and no `--voice`: refused (**exit 2**) -- the editor's default voice is never asked for |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
| `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell] [--bar "…" [--bar-style dark\|gold\|plain]]` · `set <n> [those flags; --bar off clears it]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1164,7 +1164,7 @@ the shape, the mix, recordings, parts, the best part). One writer for a post's n
| Knob | In umtool | From a terminal | Route |
|---|---|---|---|
| `narration.script` — what is read: the post, verbatim; Orpheus's tags for emotion | post bench, **script**, **Save script** | `umtool posts narrate <p> <item> --script "…"` · every post's drafted: `--all --draft-scripts [--force]` | `op: "set", patch: {script}` |
-| **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id}` |
+| **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in -- or, with **Filter before keeping**, the post waits: [filter, preview, Keep](#record-filter-preview-on-the-record-page) | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder**; **Use a sound file…** (a recording made elsewhere, for the part); the character it is read as, its direction, **▶ <voice> reads it** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id, spans?}` |
| a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` |
| a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done |
| a THREAD READ — the post it answers (or every ancestor), the post it quotes, the linked posts and his words, each in its author's voice, parts cached, one take picked ([below](#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)) | — | `umtool posts narrate <p> <item> --take --thread [--parents 0\|all] [--skip-parent <id>]… [--voice-for <handle>=<voice>]… [--dry-run] [--json]` | — |
@@ -1379,6 +1379,8 @@ for one read).
| the voice a character reads in -- this project, or everywhere | an audition's **Use for this project** / **Use everywhere** | `umtool cast use <p> <character\|@handle> <voice> [--everywhere]` (the project's own override goes with `--everywhere`) | `POST … {op: "use", who, voice, scope}` |
| the re-reads a voice change asks for | the confirm under the audition: the items, **Queue N re-reads** (steps of the queue: /jobs; each a new take, picked, awaiting approval) | `umtool cast reread <p> <character> [--dry-run]` | `POST … {op: "reread", who}` |
| a recording made a character's read | **Voices** → *a recording*: the item, as whom (this video's own, the cast's), drop a file, clean / convert, **Import** (a job) | `umtool posts narrate <p> <item> --recording <file> [--as <character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch …] [--semitones n]` | `POST … multipart {op: "recording", item, as?, file}` |
+| the same chain with NO TAKE made -- a preview in the scratch dir `narration/.record-preview/<postId>.<label>/`, then kept or dropped ([below](#record-filter-preview-on-the-record-page)) | the record page's **Filter**, **Keep**, **Again** | `umtool posts narrate <p> <item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]… [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--engine e] [--voice v] [--pitch …] [--semitones n]` · `--keep-preview` · `--discard-preview` | `POST /api/report/post-narration/record {op: "prepare" \| "filter" \| "keep" \| "again" \| "discard-preview"}` |
+| a convert made from a take -- its engine, stock voice, pitch and semitones are the CHARACTER's recorded preset, each unless said; no character and no voice: refused (the editor's default voice is never asked for) | post bench, **run AI on take** → convert | `umtool posts narrate <p> <item> --derive <n> --op convert [--as <character>] [--engine e] [--voice v] [--pitch …] [--semitones n]` | `POST /api/report/post-narration {op: "derive", op2: "convert", as?, engine?, voice?, pitch?, semitones?}` |
```sh
umtool cast add thequartering --name TheQuartering --voice kokoro:am_michael --handles thequartering --speakers Jeremy
@@ -1393,6 +1395,78 @@ umtool cast project quartering-diet keep @madamsavvy # a character of th
umtool posts character quartering-diet <item> anon-1 # this one item read as that character (--clear: by its handle)
```
+### Record, filter, preview on the record page
+
+The operator, 11 Nov 2026: "run the filter and preview it seamlessly in the record UI". On
+`/projects/<p>/narration/record`, above the record button: **who the post is read as** (the chain's character and
+where it comes from), its **direction** line, and **▶ <voice> reads it** -- the character's SYNTHETIC preset voice
+(`synthetic.voice`, at its speed: the cheap one to hear the line in -- the voice a recording is CONVERTED to is
+`recorded.convert.voice`, which may be another) reading the part: the read kept from before when there is one
+(`narration/parts-cache/`, a thread read's), else asked of the editor's tts op when the button is pressed, never before.
+
+**Filter before keeping** (a checkbox; on by itself for a post whose character has a stock voice to convert to, off
+otherwise -- the last part then makes the recorded take at once, as before): the last part in, the post WAITS.
+
+- **The cut marks**: each part's waveform with its trim in and out -- the auto trim's answer (the preset's
+ `trim.padMs` either side of the speech; `trim.on: false`: the whole part), draggable, or focus one and press the
+ arrow keys (0.05 s; Shift 0.25 s); **▶ what the marks keep**; **back to the auto trim**. They are what a keyboard
+ click at the start or the end of a recording is cut off with. `keepRecording` takes them as `spans` (`[{from, to}]`
+ per part, the part's own seconds), whatever the trim says.
+- **Filter** (**f**): the character's recorded preset as ONE job of umtool's (`umtool posts narrate <p> <item>
+ --preview --events`; its three stages on the page, the time it has run, Cancel) -- **clean** (the editor's
+ voice-enhance over the parts whole), **cut** at the marks and joined, **convert** (its voice-convert to the stock
+ voice) -- into the SCRATCH DIR `<project>/narration/.record-preview/<postId>.<label>/` (`preview.json`, `raw.wav`,
+ `clean.wav`, `filtered.wav` and their parts). **No take is made.** A stage whose inputs stand is not run again: a
+ mark moved re-cuts the cleaned sound and converts; another pitch converts alone. **A wait is a state, not an
+ error**: *queued* behind the editor's other voice jobs, *waiting for memory* or *for the heavy slot* at the machine's
+ gate (the last line of the editor's job, `scripts/queue-lock.mjs`'s own) -- a short read takes two or three minutes.
+ umtool runs one job at a time: while another runs, Filter says so. **Cancel** stops umtool's job AND the editor's
+ job it waits on (its engine holds, or waits at, the heavy slot otherwise); pressed before the editor's job is known,
+ the page says so. While a post's Filter runs, Keep, Again, a part's upload and dropping the preview answer 409.
+- **▶ Raw**, **▶ Filtered**, **▶ Raw, then filtered**: the two reads at ONE loudness (the louder turned down to the
+ other's measured LUFS). With no clean engine and no character to convert to, it says nothing filtered it.
+- **Pitch** and **semitones** (a Seed-VC convert): default the preset's; **Save to character** writes them to the
+ character (`character-set`: this video's own, or the cast's -- it says which). A post read as the cast's narrator, or
+ as nobody: **Keep in this video only** (`character-keep`) gives its author a character of this video's own, converted
+ as here.
+- **Keep** (**Enter**): the takes `posts narrate --recording` makes -- the recording (cut, joined, levelled), the
+ cleaned one, the converted one, the last PICKED and awaiting approval -- made FROM THE PREVIEW's FILES, nothing
+ converted again; the page opens the next post not recorded yet. When the marks or the pitch moved since the Filter
+ the button says **Keep the recording alone** and keeps one recorded take, cut at the marks.
+- **Again** (**Backspace** or **r**): the preview dropped, the part recorded again. A part recorded over with Space
+ drops the preview too (page and server), and a filtered Keep is refused (409) unless the preview was made from the
+ session's recording as it is now -- the filtered read of an earlier recording is never kept. A held key is one press.
+- A sound file chosen for a part (and `--recording <file>`) is an upload: one that is text (a playlist, a concat
+ script) is refused before ffmpeg opens it, and ffmpeg may open local files only (`-protocol_whitelist file`).
+- Keep writes its takes one after another (an undo point each, as `--recording` does): a failure between them leaves
+ the takes already written, and the preview's files that were moved stay takes.
+- The scratch dir is removed on Keep, on Again, when the post or the page is left (unless its Filter is still running:
+ it is there when you come back), when the recording it was made from changes, and a day after a crash left one.
+- **The microphone is a secure context's** (localhost, https): opened over http from the LAN the page says so and
+ the Record button is off; **Use a sound file…** takes a recording made elsewhere for the part, and Filter, the
+ preview, the marks and Keep work as anywhere.
+- Not built: a "start on speech" level trigger. A recorder that starts at the first sound loses the start of the first
+ word, and the auto trim already cuts the silence before it; Space and the count-in start a read.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the preview -- the chain into the scratch dir, no take | **Filter** (f) | `umtool posts narrate <p> <item> --preview` (the page's session) · `--recording <file> --preview [--out <file>]` (a file; the filtered read copied to `--out`) · `--json` · `--events` (its progress, one JSON object a line) | `POST /api/report/post-narration/record {op: "filter", id, spans?, pitch?, semitones?}` → `{job}`; `GET ?project&id&job=<id>` → `{job: {state, stage, waiting, waited, stages, error}, preview?}`; `POST {op: "cancel", id, job}` → `{cancelled, editor: {job, cancelled, note?}}` |
+| the cut marks -- `[{from, to}]` per part | the waveform's two marks | `--trim-span 0.4-3.1` (the first part) · `--trim-span 2=0.2-4` | `spans` on `filter`, `keep`, `finish`; `POST {op: "prepare", id}` → each part's `seconds`, `peaks`, `auto` |
+| the pitch of this read | **pitch**, **semitones** | `--pitch target\|source\|contour` · `--semitones n` | `pitch`, `semitones` on `filter` |
+| the pitch kept on the character | **Save to character** · **Keep in this video only** | `umtool cast set <id> --convert-pitch … --convert-semitones n` · `umtool cast project <p> set <id> …` · `umtool cast project <p> keep @<handle>` | `POST /api/report/voices {op: "character-set" \| "character-keep"}` |
+| keep the preview -- its takes, the last picked | **Keep** (Enter) | `umtool posts narrate <p> <item> --keep-preview` | `POST … {op: "keep", id, filtered: true, spans?, script?}` (`filtered: false`: the recording alone) |
+| drop it | **Again** (Backspace, r), leaving the post | `umtool posts narrate <p> <item> --discard-preview` | `POST … {op: "again", id, n?}` · `{op: "discard-preview", id}` |
+| the character's synthetic voice reading the line | **▶ <voice> reads it** | — | `POST … {op: "stock", id, text}` → `{file}` or `{jobId, key}`; `GET ?project&id&stock&job&key` |
+| the preview's sounds | **▶ Raw**, **▶ Filtered**, **▶ what the marks keep** | the paths `--preview` prints | `GET ?project&id&preview&file=raw\|clean\|filtered\|part[&n]` · `GET ?project&id&preview` (who it is read as, the preview, the job) |
+
+```sh
+umtool posts narrate <p> <item> --recording savvy.wav --preview # clean, cut, convert: the paths, no take
+umtool posts narrate <p> <item> --recording savvy.wav --preview --semitones 3 # another nudge: the convert alone
+umtool posts narrate <p> <item> --recording savvy.wav --preview --trim-span 0.35-4.1 --out /tmp/savvy.wav
+umtool posts narrate <p> <item> --keep-preview # its takes, the last picked
+umtool posts narrate <p> <item> --derive 1 --op convert # take 1 converted as its character says
+```
+
### A character is a preset
The operator, 11 Nov 2026: "a preset of voice and other settings … different presets for synthetic and
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -667,7 +667,13 @@ part is written to `narration/posts/<postId>/.recording-<label>/` the moment it
(`lib/report/recordSession.mjs`: a crash loses at most the part being read, a reload
resumes at the first part not kept); when the last part is in, the parts become the post's
recorded take (below) and it is picked. Chromium and Firefox (webm or ogg opus), no network
-beyond localhost.
+beyond localhost. With **Filter before keeping** (on by itself for a post whose character has
+a stock voice to convert to) the post waits instead: its cut marks on a waveform, **Filter**
+(the character's recorded preset as one job, into a preview — no take), the raw and filtered
+reads side by side, **Keep** / **Again**
+([knobs.md](knobs.md#record-filter-preview-on-the-record-page)). The microphone needs
+localhost or https: opened over http from the LAN the page says so, and a sound file can be
+chosen for a part.
**Recorded takes** — the post bench's recording session: the mic (remembered per
browser), a level meter, a 3-2-1 count-in, the script as a teleprompter with the part
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -1441,7 +1441,9 @@ const server = http.createServer((req, res) => {
return json(res, 200, {
ok: true,
job: { id: opsJob[1], kind: j.kind ?? "tts-file", status },
- ...(tail ? { tail: ["tts: synthesizing (stub)", `${j.marker ?? "@@tts-result "}${JSON.stringify(j.result)}`] } : {}),
+ // A voice-convert that is still running is at the machine's heavy slot, and says so as the editor's job does
+ // (scripts/queue-lock.mjs): the record page's Filter shows it as a wait, not an error.
+ ...(tail ? { tail: status === "running" && j.kind === "voice-convert" ? ["heavy: waiting for memory — 4100 MB available, the floor is 6000 MB", " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)"] : ["tts: synthesizing (stub)", `${j.marker ?? "@@tts-result "}${JSON.stringify(j.result)}`] } : {}),
});
}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -38,6 +38,7 @@ import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
import { makeUiOpsFixture } from "./ui-ops-fixture.mjs";
import { makeVoicesFixture } from "./voices-fixture.mjs";
+import { makeRecordFilterFixture } from "./record-filter-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeCaseStagesFixture } from "./case-stages-fixture.mjs";
@@ -1922,6 +1923,8 @@ makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "ou
makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ff });
// The Voices page (voices.spec.ts): Host's clips (the real voice) and post items by @hostman and @guest.
makeVoicesFixture({ reports, channels: CHANNELS, manifest, ff });
+// Record -> filter -> preview on the record page (record-filter.spec.ts): three one-part post items, no cast.
+makeRecordFilterFixture({ reports, manifest });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
diff --git a/umtool/e2e/fixtures/record-filter-fixture.mjs b/umtool/e2e/fixtures/record-filter-fixture.mjs
@@ -0,0 +1,32 @@
+// RECORD -> FILTER -> PREVIEW (record-filter.spec.ts; components/projects/RecordSession.tsx, lib/report/
+// recordPreview.mjs): a posts cut of three items, each a one-part read --
+//
+// reports/record-filter-fixture/
+// p-1 @savvy "Savvy's first line, read aloud." the spec gives @savvy a character of this video's own
+// p-2 @savvy "Savvy's second line." (narration/characters.json: seed-vc, contour +2, a direction)
+// p-3 @stranger "A stranger says a thing." nobody's: no character, and the fixture has no cast
+//
+// No take, no character and no cast of its own: the spec writes this video's characters and removes what it made. The
+// editor is the suite's stub (voice-enhance: not installed; voice-convert: copies, after one poll at the heavy slot).
+// Synthetic, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const RECORD_FILTER = "record-filter-fixture";
+
+/** @param {{ reports: string, manifest: Function }} o */
+export function makeRecordFilterFixture({ reports, manifest }) {
+ const dir = path.join(reports, RECORD_FILTER);
+ mkdirSync(dir, { recursive: true });
+ const post = (id, handle, author, text) => ({
+ type: "post", id: `p-${id}`, post: `recordfilter-x/${id}`, platform: "x", author, handle, date: `2026-11-0${id}T10:00:00.000Z`, text,
+ url: `https://x.com/${handle}/status/${id}`, engagement: { likes: 1 }, section: 0, narration: { script: text },
+ });
+ const timeline = [
+ post("1", "savvy", "Madam Savvy", "Savvy's first line, read aloud."),
+ post("2", "savvy", "Madam Savvy", "Savvy's second line."),
+ post("3", "stranger", "A Stranger", "A stranger says a thing."),
+ ];
+ writeFileSync(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest(RECORD_FILTER, "The Record Filter Fixture", { siteOrigin: "https://archive.example", channelSlug: "recordfilter" }, timeline), null, 2)}\n`);
+ return dir;
+}
diff --git a/umtool/e2e/record-filter.spec.ts b/umtool/e2e/record-filter.spec.ts
@@ -0,0 +1,326 @@
+import { test, expect, type Page } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// RECORD -> FILTER -> PREVIEW on the record page (components/projects/RecordSession.tsx, RecordFilter.tsx;
+// /api/report/post-narration/record; lib/report/recordPreview.mjs). Fixture: e2e/fixtures/record-filter-fixture.mjs
+// -- p-1 and p-2 by @savvy (the spec gives her a character of this video's own: seed-vc, contour +2, a direction),
+// p-3 by @stranger (nobody's). The editor is the suite's stub: voice-enhance is not installed, voice-convert copies
+// after one poll at the heavy slot ("waiting for memory").
+//
+// Filter -> the preview (no take), the wait at the heavy slot a state, raw and filtered side by side -> another
+// pitch asks for the convert again -> Save to character -> Keep: the takes from the preview's files, the next post
+// Again; nobody's post: nothing to convert, Keep in this video only, the recording kept alone
+// the microphone off (a page opened over http from the LAN): said, and a sound file filtered and kept all the same
+//
+// RECORD_FILTER_SHOTS=<dir> screenshots there
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const P = "reports/record-filter-fixture";
+const DIR = path.join(FIXTURE, "reports", "record-filter-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const NARRATION = path.join(DIR, "narration");
+const CHARACTERS = path.join(NARRATION, "characters.json");
+const SCRATCH = (post: string) => path.join(NARRATION, ".record-preview", `${post}.operator`);
+const REQUESTS = path.join(FIXTURE, "editor-stub.requests.json");
+const SHOTS = process.env.RECORD_FILTER_SHOTS ?? null;
+/** A voice for the fake microphone (and the file chosen where there is none): a 1 kHz tone, two seconds. */
+const MIC_WAV = path.join(FIXTURE, "record-filter-mic.wav");
+
+type Take = { file: string; engine?: string; voice?: string; note?: string; seconds: number; source?: { kind: string; from?: string }; steps?: { op: string; engine?: string; voice?: string; pitch?: string; semitones?: number }[] };
+type Entry = { id: string; narration?: { script?: string; takes?: Take[]; pick?: number; approved?: boolean } };
+const narr = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline.find((e) => e.id === id)!.narration!;
+const converts = () => (JSON.parse(readFileSync(REQUESTS, "utf8")) as { route?: string; engine?: string; voice?: string; pitch?: string; semitones?: number; file?: string; out?: string }[]).filter((r) => r.route === "voice-convert");
+const characters = () => (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; handles?: string[]; recorded?: { convert?: { engine?: string; voice?: string; pitch?: string; semitones?: number } } }[] }).characters;
+const shot = async (page: Page, name: string) => {
+ if (!SHOTS) return;
+ mkdirSync(SHOTS, { recursive: true });
+ await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: true });
+};
+
+if (!existsSync(MIC_WAV)) {
+ mkdirSync(FIXTURE, { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]);
+}
+
+// A fake microphone and audio that may start without a gesture, for the whole file.
+test.use({ launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${MIC_WAV}`, "--autoplay-policy=no-user-gesture-required"] } });
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+const reset = () => {
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(NARRATION, { recursive: true, force: true });
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+};
+/** @savvy's character of this video's own: converted by seed-vc to a stock voice, contour +2, a direction to read by. */
+const giveSavvy = () => {
+ mkdirSync(NARRATION, { recursive: true });
+ writeFileSync(CHARACTERS, `${JSON.stringify({
+ format: "umtool-project-characters", version: 1,
+ characters: [{ id: "madam-savvy", name: "Madam Savvy", handles: ["savvy"], synthetic: { voice: "kokoro:af_bella" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, direction: "higher, brisk, amused" } }],
+ }, null, 2)}\n`);
+};
+test.beforeEach(async ({ page }) => {
+ test.setTimeout(180_000);
+ reset();
+ // "Filter before keeping" as the page decides it (on for a post whose character converts), whatever a test before left.
+ await page.addInitScript(() => {
+ try {
+ window.localStorage.removeItem("umtool.record.filter-first");
+ window.localStorage.setItem("umtool.record.count-in", "0");
+ } catch {
+ // no storage here
+ }
+ });
+});
+test.afterAll(reset);
+
+const s = (page: Page) => page.locator("[data-record-session]");
+/** Space, a second of the fake microphone, Space: the part is on disk. */
+const recordPart = async (page: Page) => {
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
+ await page.waitForTimeout(1200);
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
+};
+const filterDone = async (page: Page) => {
+ await expect(page.locator("[data-record-filter-job]")).toHaveAttribute("data-record-filter-job", "done", { timeout: 90_000 });
+};
+
+test("Filter runs the character's recorded preset as one job into a preview (no take); raw and filtered side by side; another pitch; Save to character; Keep makes the takes and opens the next post", async ({ page }) => {
+ giveSavvy();
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-1");
+ // Who it is read as, above the record button: the character, its direction, its stock voice to hear.
+ const who = page.locator("[data-record-character]");
+ await expect(who).toHaveAttribute("data-record-character", "madam-savvy");
+ await expect(who).toHaveAttribute("data-record-character-layer", "project");
+ await expect(page.locator("[data-record-character-name]")).toHaveText("Madam Savvy");
+ await expect(page.locator("[data-record-direction]")).toContainText("higher, brisk, amused");
+ await expect(page.locator("[data-record-stock]")).toContainText("kokoro:af_bella reads it");
+ // Her character converts: the post waits to be filtered. The microphone is here (localhost): no note.
+ await expect(page.locator("[data-record-review]")).toBeChecked();
+ await expect(page.locator("[data-record-no-mic]")).toHaveCount(0);
+ await expect(page.locator("[data-record-review-panel]")).toHaveCount(0);
+
+ // Record it: NO take is made -- the waveform with its two cut marks, the pitch from the preset.
+ await recordPart(page);
+ const panel = page.locator("[data-record-review-panel]");
+ await expect(panel).toBeVisible();
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ expect(narr("p-1").takes ?? []).toHaveLength(0);
+ await expect(page.locator("[data-record-pitch]")).toHaveValue("contour");
+ await expect(page.locator("[data-record-semitones]")).toHaveValue("2");
+ await expect(page.locator("[data-record-keep]")).toHaveAttribute("data-record-keep-what", "recording");
+ // A cut mark moved (a keyboard click at the start): four presses of the arrow, 0.2 s in.
+ const from = page.locator('[data-record-mark="from"]');
+ const markAt = async () => Number(await from.getAttribute("data-record-mark-at"));
+ const auto = await markAt();
+ await from.focus();
+ for (let i = 0; i < 4; i += 1) await page.keyboard.press("ArrowRight");
+ await expect.poll(markAt).toBeCloseTo(auto + 0.2, 2);
+ await expect(page.locator("[data-record-span-auto]")).toBeVisible();
+ await shot(page, "record-filter-marks");
+
+ // FILTER (f): one job -- the clean skipped (the stub has no enhance engine), cut, converted; its wait at the heavy
+ // slot was a state on the way, and nothing failed.
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await page.keyboard.press("f");
+ await expect(page.locator("[data-record-filter-job]")).toBeVisible({ timeout: 15_000 });
+ await filterDone(page);
+ const job = page.locator("[data-record-filter-job]");
+ await expect(job).toHaveAttribute("data-record-filter-waited", /memory/);
+ await expect(job.locator('[data-record-filter-step="clean"]')).toHaveAttribute("data-record-filter-step-state", "skipped");
+ await expect(job.locator('[data-record-filter-step="trim"]')).toHaveAttribute("data-record-filter-step-state", "done");
+ await expect(job.locator('[data-record-filter-step="convert"]')).toHaveAttribute("data-record-filter-step-state", "done");
+ await expect(page.locator("[data-record-filter-error]")).toHaveCount(0);
+ // The preview, in the scratch dir; still no take.
+ expect(existsSync(path.join(SCRATCH("1"), "raw.wav"))).toBe(true);
+ expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(true);
+ expect(narr("p-1").takes ?? []).toHaveLength(0);
+ const asked = converts().at(-1)!;
+ expect(asked).toMatchObject({ engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2 });
+ expect(asked.file).toMatch(/narration\/\.record-preview\/1\.operator\/raw\.wav$/);
+ await expect(panel).toHaveAttribute("data-record-preview-current", "1");
+ await expect(page.locator("[data-record-preview-note]").first()).toContainText("not cleaned");
+ // Raw and filtered, side by side.
+ await expect(page.locator("[data-record-compare-what]")).toContainText("converted to kokoro:af_bella by seed-vc · pitch contour +2 st · both at one loudness");
+ const player = page.locator("[data-record-player]");
+ await page.locator("[data-record-play-raw]").click();
+ await expect(player).toHaveAttribute("src", /preview&file=raw/);
+ await page.locator("[data-record-play-filtered]").click();
+ await expect(player).toHaveAttribute("src", /preview&file=filtered/);
+ await shot(page, "record-filter-preview");
+
+ // Another pitch: the preview is not of it any more; Filter again asks for the convert, at that pitch.
+ const before = converts().length;
+ await page.locator("[data-record-pitch]").selectOption("source");
+ await expect(panel).toHaveAttribute("data-record-preview-current", "0");
+ await expect(page.locator("[data-record-preview-stale]")).toBeVisible();
+ await page.locator("[data-record-filter]").click();
+ await expect(panel).toHaveAttribute("data-record-preview-current", "1", { timeout: 90_000 });
+ expect(converts()).toHaveLength(before + 1);
+ expect(converts().at(-1)).toMatchObject({ pitch: "source", semitones: 2, voice: "kokoro:af_bella" });
+ await expect(page.locator('[data-record-filter-step="trim"]')).toHaveAttribute("data-record-filter-step-state", "cached");
+ // Save to character: this video's own character keeps the pitch.
+ await page.locator("[data-record-save-character]").click();
+ await expect(page.locator("[data-record-saved]")).toContainText("saved to Madam Savvy (this video's own)");
+ expect(characters().find((c) => c.id === "madam-savvy")!.recorded!.convert).toMatchObject({ engine: "seed-vc", pitch: "source", semitones: 2 });
+ await expect(page.locator("[data-record-save-character]")).toBeDisabled();
+
+ // KEEP (Enter): the takes from the preview's files -- nothing converted again -- the last picked, awaiting approval;
+ // the scratch dir and the session are gone; the next post not recorded is open.
+ const convertsBefore = converts().length;
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await page.keyboard.press("Enter");
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-2", { timeout: 30_000 });
+ await expect(page.locator("[data-record-last-kept]")).toContainText("kept post 1: recorded (take-1.recorded-operator.wav), converted to kokoro:af_bella (pitch: source +2 st) (take-2.convert-seed-vc.wav)");
+ const n = narr("p-1");
+ expect(n.takes).toHaveLength(2);
+ expect(n.pick).toBe(1);
+ expect(n.approved).not.toBe(true);
+ expect(n.takes![0]).toMatchObject({ file: "narration/posts/1/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", note: "recorded for Madam Savvy" });
+ expect(n.takes![1]).toMatchObject({ file: "narration/posts/1/take-2.convert-seed-vc.wav", engine: "derived", voice: "af_bella", source: { kind: "take", from: "take-1.recorded-operator" } });
+ expect(n.takes![1].steps![0]).toMatchObject({ op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "source", semitones: 2 });
+ for (const t of n.takes!) expect(existsSync(path.join(DIR, t.file))).toBe(true);
+ expect(converts()).toHaveLength(convertsBefore);
+ expect(existsSync(SCRATCH("1"))).toBe(false);
+ expect(existsSync(path.join(NARRATION, "posts", "1", ".recording-operator"))).toBe(false);
+ await expect(page.locator('[data-record-jump="p-1"]')).toHaveAttribute("data-record-state", "recorded");
+ await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "1");
+ // The next post reads as her too, at the pitch just saved.
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await shot(page, "record-filter-kept");
+});
+
+test("Again drops the preview and records the part again; nobody's post has nothing to convert: Keep in this video only, and the recording kept alone", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-3" }));
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-3");
+ await expect(page.locator("[data-record-no-character]")).toContainText("no character reads @stranger");
+ // Nobody converts it: the last part would make the take at once -- until a person asks to filter first.
+ await expect(page.locator("[data-record-review]")).not.toBeChecked();
+ await page.locator("[data-record-review]").check();
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await recordPart(page);
+ const panel = page.locator("[data-record-review-panel]");
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator("[data-record-pitch-row]")).toHaveCount(0);
+ expect(existsSync(path.join(SCRATCH("3"), "p01.raw.wav"))).toBe(true);
+ // Filter: no clean engine, no character -- it says so, and nothing failed.
+ await page.locator("[data-record-filter]").click();
+ await filterDone(page);
+ await expect(page.locator('[data-record-filter-step="convert"]')).toHaveAttribute("data-record-filter-step-state", "skipped");
+ await expect(page.locator("[data-record-nothing-filtered]")).toBeVisible();
+ await expect(page.locator("[data-record-filter-error]")).toHaveCount(0);
+ const first = readFileSync(path.join(NARRATION, "posts", "3", ".recording-operator", "session.json"), "utf8");
+
+ // AGAIN (Backspace): the preview dropped, the part recorded again -- still no take.
+ await page.keyboard.press("Backspace");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
+ expect(existsSync(SCRATCH("3"))).toBe(false);
+ await page.waitForTimeout(1200);
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator("[data-record-filter-job]")).toHaveCount(0);
+ expect(readFileSync(path.join(NARRATION, "posts", "3", ".recording-operator", "session.json"), "utf8")).not.toBe(first);
+ expect(narr("p-3").takes ?? []).toHaveLength(0);
+
+ // Keep in this video only: @stranger gets a character of this video's own.
+ await page.locator("[data-record-keep-in-video]").click();
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character-layer", "project", { timeout: 20_000 });
+ const made = characters().find((c) => (c.handles ?? []).includes("stranger"));
+ expect(made).toBeTruthy();
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", made!.id);
+ await expect(page.locator("[data-record-keep-in-video]")).toHaveCount(0);
+
+ // Not filtered: Keep keeps the recording alone -- one recorded take, picked -- and moves on.
+ await expect(panel).toHaveAttribute("data-record-preview-current", "0");
+ await expect(page.locator("[data-record-keep]")).toHaveAttribute("data-record-keep-what", "recording");
+ await page.locator("[data-record-keep]").click();
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-1", { timeout: 30_000 });
+ const n = narr("p-3");
+ expect(n.takes).toHaveLength(1);
+ expect(n.takes![0]).toMatchObject({ file: "narration/posts/3/take-1.recorded-operator.wav", engine: "recorded" });
+ expect(n.pick).toBe(0);
+ expect(existsSync(SCRATCH("3"))).toBe(false);
+ expect(existsSync(path.join(NARRATION, "posts", "3", ".recording-operator"))).toBe(false);
+});
+
+test("opened over http from the LAN the microphone is off, and the page says so; a sound file is filtered and kept all the same; with the filter off the last part makes the take at once", async ({ page }) => {
+ giveSavvy();
+ // What a browser gives a page opened over plain http from another machine: no secure context, no microphone.
+ await page.addInitScript(() => Object.defineProperty(window, "isSecureContext", { get: () => false }));
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
+ await expect(page.locator("[data-record-no-mic]")).toContainText("The microphone is off on this page");
+ await expect(page.locator("[data-record-no-mic]")).toContainText("localhost");
+ await expect(page.locator("[data-record-toggle]")).toBeDisabled();
+ // Space does not try the microphone.
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle");
+ await expect(page.locator("[data-record-error]")).toHaveCount(0);
+ // A sound file for the part: filtered, previewed and kept as a recording made here would be.
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await page.locator("[data-record-file]").setInputFiles(MIC_WAV);
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await page.locator("[data-record-filter]").click();
+ await filterDone(page);
+ await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1");
+ await page.locator("[data-record-play-filtered]").click();
+ await expect(page.locator("[data-record-player]")).toHaveAttribute("src", /preview&file=filtered/);
+ await page.locator("[data-record-keep]").click();
+ await expect(s(page)).toHaveAttribute("data-record-session", "p-2", { timeout: 30_000 });
+ expect(narr("p-1").takes!.map((t) => t.engine)).toEqual(["recorded", "derived"]);
+ await shot(page, "record-filter-lan");
+
+ // "Filter before keeping" off: the last part makes the recorded take at once, as before.
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await expect(page.locator("[data-record-review]")).toBeChecked();
+ await page.locator("[data-record-review]").uncheck();
+ await page.locator("[data-record-file]").setInputFiles(MIC_WAV);
+ await expect(page.locator("[data-record-status]")).toContainText("take-1.recorded-operator.wav", { timeout: 30_000 });
+ await expect(page.locator("[data-record-review-panel]")).toHaveCount(0);
+ expect(narr("p-2").takes).toHaveLength(1);
+ expect(existsSync(path.join(NARRATION, ".record-preview", "2.operator"))).toBe(false);
+});
+
+test("a part recorded again with Space (no Again) and Enter at once: the filtered read of the EARLIER recording is never kept", async ({ page }) => {
+ giveSavvy();
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
+ await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
+ await recordPart(page);
+ await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
+ await page.locator("[data-record-filter]").click();
+ await filterDone(page);
+ await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1");
+ const before = converts().length;
+ // Space records over the part; Enter the moment it has landed.
+ await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
+ await page.keyboard.press("Space");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
+ await page.waitForTimeout(1200);
+ await page.keyboard.press("Space");
+ await page.keyboard.press("Enter");
+ await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
+ // The earlier preview is gone, on the page and on disk; whatever Enter did, no converted take was made.
+ await expect(page.locator("[data-record-compare]")).toHaveCount(0);
+ expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(false);
+ expect((narr("p-1").takes ?? []).filter((t) => t.engine === "derived")).toHaveLength(0);
+ expect(converts()).toHaveLength(before);
+ // The server holds the line too: a filtered Keep with no preview of this recording is refused.
+ const r = await page.request.post("/api/report/post-narration/record", { data: { project: P, id: "p-1", op: "keep", filtered: true } });
+ if ((narr("p-1").takes ?? []).length === 0) expect(r.status()).toBe(409);
+});
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -1032,8 +1032,8 @@ export const GROUPS = [
"**THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2**"],
["`posts voices <project> [ls] \\| set <handle\\|*> <voice> \\| remove <handle\\|*> [--json]`",
"**THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2**"],
- ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean\\|--clean] [--no-trim\\|--trim] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l]` · `<item> --derive <n> --op convert [--engine e] [--voice v] [--pitch …] [--semitones n]`",
- "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**"],
+ ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean\\|--clean] [--no-trim\\|--trim] [--no-convert] [--pitch target\\|source\\|contour] [--semitones n] [--label l]` · `<item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]… [--engine e] [--voice v] [--events]` · `<item> --keep-preview` · `<item> --discard-preview` · `<item> --derive <n> --op convert [--as <character>] [--engine e] [--voice v] [--pitch …] [--semitones n]`",
+ "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked. The character is `--as` (this video's own first, then the cast's), else the item's own, this video's for the author, the cast's, the narrator; its **recorded preset** says whether it is cleaned and its edges trimmed (and the room kept) -- `--no-clean`/`--clean`, `--no-trim`/`--trim` say otherwise for this read. **`--pitch`** is the pitch the converted read lands on ([knobs.md](knobs.md#the-pitch-a-converted-read-lands-on)): `target` the stock voice's own (the read's intonation flattened to it), `source` the pitch it was read at, `contour` the read's rises and falls moved to the stock voice's register; `--semitones` (-12…12) moves a followed one. Default: the character's `convert` entry, else the editor's `settings.voice.convert`. `source` and `contour` are seed-vc's, with its f0 model (`archilyzer voice setup --engine seed-vc --with f0`); what the editor cannot do it refuses in a sentence (**exit 1**); a value outside these, or a pitch on `--op enhance`: **exit 1**. **`--preview`** runs the same chain with NO TAKE made ([knobs.md](knobs.md#record-filter-preview-on-the-record-page); the record page's Filter): cleaned whole, cut (`--trim-span`: at these seconds of the recording instead of the auto trim's), converted, into the scratch dir `narration/.record-preview/<postId>.<label>/` -- its paths printed, `--out <file>` a copy of the filtered read; without `--recording` it is the record page's session of the item. A step whose inputs stand is not run again (another `--pitch`: the convert alone). `--keep-preview` makes its takes from those files (nothing converted again), `--discard-preview` removes it. **`--derive <n> --op convert`** is the character's too: its recorded preset's engine, stock voice, pitch and semitones, each unless its flag says otherwise (`--as` names another character); no character and no `--voice`: refused (**exit 2**) -- the editor's default voice is never asked for"],
["`posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post\\|quoted\\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\\|above\\|side]` · `add clock [--rewind auto\\|on\\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]`",
"a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**)"],
["`posts clock <project> [on\\|off\\|default] [--zone <IANA zone>] [--json]`",
diff --git a/umtool/lib/report/characters.test.mjs b/umtool/lib/report/characters.test.mjs
@@ -427,3 +427,38 @@ test("a recording made a read with its character's recorded preset: clean off, t
assert.deepEqual(r.takes.map((t) => t.step), ["recorded", "cleaned", "converted to kokoro:bm_george (pitch: contour +2 st)"]);
await posts(["character", "chars", "p-3", "--clear"]);
});
+
+test("posts narrate --derive --op convert: the character's recorded preset unless a flag says otherwise; no character and no voice is refused", async () => {
+ // p-3 is @guest's (anon-a: kokoro:am_puck); the cast's narrator `me` converts by seed-vc, contour +2.
+ const rec = path.join(ROOT, "derive-read.wav");
+ await wavOf(rec, VOICE_B, 1.5, 0.3);
+ const asked = [];
+ const ask = async (route, body) => {
+ asked.push({ op: route.split("/").at(-1), ...body });
+ await wavOf(body.out, VOICE_A, 1.5);
+ return { jobId: `d-${asked.length}`, result: { engine: body.engine ?? "openvoice", voice: body.voice ?? "zac" } };
+ };
+ const r0 = await importRecording(project, await item("p-3"), rec, { convert: false, clean: false, ask });
+ const n = (await item("p-3")).narration.takes.findIndex((t) => t.file === r0.takes[0].file) + 1;
+ // No flags: anon-a's stock voice -- never the editor's default (the stub's "zac").
+ let r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--json"], { ask });
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([asked.at(-1).op, asked.at(-1).voice, asked.at(-1).engine, asked.at(-1).pitch], ["voice-convert", "kokoro:am_puck", undefined, undefined]);
+ assert.equal(r.json().take.steps[0].voice, "kokoro:am_puck");
+ // --as: another character's whole convert entry; a flag over one key of it.
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--as", "me"], { ask });
+ assert.equal(r.code, 0, r.text());
+ assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).pitch, asked.at(-1).semitones], ["seed-vc", "kokoro:bm_george", "contour", 2]);
+ assert.match(r.text(), /as me: seed-vc -> kokoro:bm_george \(pitch: contour \+2 st\)/);
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--as", "me", "--semitones", "-1", "--voice", "kokoro:am_onyx"], { ask });
+ assert.deepEqual([asked.at(-1).engine, asked.at(-1).voice, asked.at(-1).pitch, asked.at(-1).semitones], ["seed-vc", "kokoro:am_onyx", "contour", -1]);
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "convert", "--as", "ghost"], { ask });
+ assert.equal(r.code, 2);
+ assert.match(r.text(), /--as ghost: no such character/);
+ // An enhance asks no character.
+ const before = asked.length;
+ r = await posts(["narrate", "chars", "p-3", "--derive", String(n), "--op", "enhance"], { ask });
+ assert.equal(r.code, 0, r.text());
+ assert.equal(asked.length, before + 1);
+ assert.equal("voice" in asked.at(-1), false);
+});
diff --git a/umtool/lib/report/derivePitch.mjs b/umtool/lib/report/derivePitch.mjs
@@ -4,6 +4,8 @@
// refuse alike:
//
// derivePitchOf what a derive is asked with (`pitch`, `semitones`), checked before any job
+// convertAskOf what a CONVERT derive is asked with: what the ask named, the rest from the character's recorded
+// preset -- never the editor's default voice
// stepPitchOf what the new take's step keeps: the pitch as the editor RAN it, never the target's own
// deriveRefusalOf an editor refusal read as "no engine for it" -- or passed through as it is, when it already
// names the command that fixes it
@@ -34,6 +36,49 @@ export function derivePitchOf({ pitch, semitones } = {}, op = "convert") {
}
/**
+ * WHAT A CONVERT DERIVE IS ASKED WITH (operator, 11 Nov: a derive with no flags asked the editor for ITS defaults and
+ * made a take in the wrong voice). `asked` is what the command or the body named (`engine`, `voice`, `pitch`,
+ * `semitones`: only those given); `convert` the recorded preset's convert entry of the character the read is made
+ * as (cast.mjs recordedPresetOf(character).convert -- `{engine, voice, pitch?, semitones?}`, null: no character);
+ * `who` its id, for the sentences. What was asked wins, each key by itself; the rest is the character's:
+ *
+ * engine, voice the character's convert engine and stock voice
+ * pitch the character's -- unless the ask names ANOTHER engine than the character's (a followed pitch is
+ * one engine's: the editor refuses it of another)
+ * semitones the character's, with a followed pitch; dropped with `pitch: "target"` asked for this read
+ *
+ * With no stock voice from either, `{ ok: false, error, fix }`: one sentence (and the flags that answer it), and the
+ * editor is never asked for its default voice. Else `{ ok: true, value: {engine, voice, pitch?, semitones?}, from: "asked" | "character" }` --
+ * `from` says whose voice it is.
+ *
+ * @param {{ engine?: string | null, voice?: string | null, pitch?: string | null, semitones?: number | null }} [asked]
+ * @param {{ engine?: string | null, voice?: string | null, pitch?: string, semitones?: number } | null} [convert]
+ * @param {string | null} [who]
+ * @returns {{ ok: true, value: { engine: string | null, voice: string, pitch?: string, semitones?: number }, from: "asked" | "character" } | { ok: false, error: string, fix: string }}
+ */
+export function convertAskOf(asked = {}, convert = null, who = null) {
+ const given = (v) => v !== undefined && v !== null && v !== "";
+ const cv = convert ?? {};
+ const voice = given(asked.voice) ? asked.voice : given(cv.voice) ? cv.voice : null;
+ if (!voice) {
+ // `error`: the sentence, for any surface; `fix`: the commands that answer it, for a terminal.
+ return who
+ ? { ok: false, error: `a convert needs a stock voice to convert to, and ${who} has none`, fix: `--voice <engine:voice>, or umtool cast set ${who} --convert-voice <engine:voice>` }
+ : { ok: false, error: "a convert needs a stock voice to convert to, and this post has no character with one", fix: "--voice <engine:voice>, --as <character>, or umtool cast add … for its author" };
+ }
+ const engine = given(asked.engine) ? asked.engine : given(cv.engine) ? cv.engine : null;
+ // The character's pitch is its engine's: another engine asked for this read is asked for none.
+ const own = !given(asked.engine) || !given(cv.engine) || asked.engine === cv.engine;
+ const pitch = given(asked.pitch) ? asked.pitch : own && given(cv.pitch) ? cv.pitch : undefined;
+ const semitones = given(asked.semitones) ? asked.semitones : own && pitch !== undefined && pitch !== "target" && given(cv.semitones) ? cv.semitones : undefined;
+ return {
+ ok: true,
+ value: { engine: engine ?? null, voice, ...(pitch !== undefined && pitch !== null ? { pitch } : {}), ...(semitones !== undefined && semitones !== null ? { semitones } : {}) },
+ from: given(asked.voice) ? "asked" : "character",
+ };
+}
+
+/**
* The pitch a derived take's step keeps: what the editor says it ran (its `@@voice-result`: its default when none was
* asked), else what was asked. The stock voice's own pitch is not a step's news (`{}`), and 0 semitones is none.
*/
diff --git a/umtool/lib/report/derivePitch.test.mjs b/umtool/lib/report/derivePitch.test.mjs
@@ -5,7 +5,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { validatePostNarration } from "umtool-report-to-video/post-narration";
-import { derivePitchOf, deriveRefusalOf, stepPitchOf } from "./derivePitch.mjs";
+import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "./derivePitch.mjs";
test("a derive's pitch as asked: only what was given, a body's number or a query's string, a convert's alone", () => {
assert.deepEqual(derivePitchOf({}), { ok: true, value: {} });
@@ -31,6 +31,33 @@ test("a derive's pitch as asked: only what was given, a body's number or a query
assert.deepEqual(derivePitchOf({}, "enhance"), { ok: true, value: {} });
});
+test("a convert derive is the character's: what the ask names wins, the rest is its recorded preset's, and no voice is refused", () => {
+ const savvy = { engine: "seed-vc", voice: "orpheus:mia", pitch: "contour", semitones: 2 };
+ // No flags: the character's, whole (the 11 Nov bug: the editor's default voice was asked instead).
+ assert.deepEqual(convertAskOf({}, savvy, "madam-savvy"), { ok: true, value: savvy, from: "character" });
+ assert.deepEqual(convertAskOf({ engine: null, voice: null }, savvy, "madam-savvy").value, savvy, "a flag not given is null");
+ // Each key by itself.
+ assert.deepEqual(convertAskOf({ semitones: 0 }, savvy).value, { ...savvy, semitones: 0 }, "0 is asked, not absent");
+ assert.deepEqual(convertAskOf({ pitch: "source" }, savvy).value, { ...savvy, pitch: "source" }, "the nudge goes with another followed pitch");
+ assert.deepEqual(convertAskOf({ pitch: "target" }, savvy).value, { engine: "seed-vc", voice: "orpheus:mia", pitch: "target" }, "the target's own pitch takes no semitones");
+ assert.deepEqual(convertAskOf({ voice: "orpheus:tara" }, savvy), { ok: true, value: { ...savvy, voice: "orpheus:tara" }, from: "asked" });
+ // Another engine than the character's: its pitch is not that engine's to follow.
+ assert.deepEqual(convertAskOf({ engine: "openvoice" }, savvy).value, { engine: "openvoice", voice: "orpheus:mia" });
+ assert.deepEqual(convertAskOf({ engine: "openvoice", pitch: "target" }, savvy).value, { engine: "openvoice", voice: "orpheus:mia", pitch: "target" });
+ assert.deepEqual(convertAskOf({ engine: "seed-vc" }, savvy).value, savvy, "the same engine, named");
+ // A character with only a voice (its synthetic one): the editor's engine and pitch.
+ assert.deepEqual(convertAskOf({}, { engine: null, voice: "kokoro:am_puck" }, "anon-a").value, { engine: null, voice: "kokoro:am_puck" });
+ // No character: the flags alone; none: refused in one sentence, with what answers it.
+ assert.deepEqual(convertAskOf({ voice: "zac" }, null), { ok: true, value: { engine: null, voice: "zac" }, from: "asked" });
+ const none = convertAskOf({ engine: "seed-vc", pitch: "contour" }, null);
+ assert.equal(none.ok, false);
+ assert.equal(none.error, "a convert needs a stock voice to convert to, and this post has no character with one");
+ assert.match(none.fix, /--voice <engine:voice>, --as <character>/);
+ const mute = convertAskOf({}, { engine: null, voice: null }, "ghost");
+ assert.equal(mute.error, "a convert needs a stock voice to convert to, and ghost has none");
+ assert.match(mute.fix, /umtool cast set ghost --convert-voice/);
+});
+
test("the step keeps the pitch the editor ran, else the one asked; never the target's own, never 0 semitones", () => {
assert.deepEqual(stepPitchOf({}, {}), {});
assert.deepEqual(stepPitchOf({ pitch: "target" }, {}), {});
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -26,8 +26,8 @@ import { promisify } from "node:util";
import {
NARRATION_INDEX, POST_DERIVE_OPS, POST_NARRATION_LIMITS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
-import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX } from "umtool-report-to-video/cast";
-import { stepPitchOf } from "./derivePitch.mjs";
+import { CAST_CONVERT_PITCH, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast";
+import { convertAskOf, stepPitchOf } from "./derivePitch.mjs";
import { excerptSpansOf, postItemPlan, postReadText } from "umtool-report-to-video/post-item";
import { partRoles } from "umtool-report-to-video/post-thread";
import { spokenRead } from "umtool-report-to-video/post-redact";
@@ -48,7 +48,10 @@ export const NARRATE_USAGE = [
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
" umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] [--no-convert]",
" [--pitch target|source|contour] [--semitones <n>]",
- " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v]",
+ " umtool posts narrate <project> <item> [--recording <file>] --preview [--as <character>] [--out <file>] [--trim-span [<part>=]<from>-<to>]…",
+ " [--no-clean|--clean] [--no-trim|--trim] [--no-convert] [--engine e] [--voice v] [--pitch …] [--semitones <n>] [--events]",
+ " umtool posts narrate <project> <item> --keep-preview | --discard-preview [--label operator]",
+ " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v] [--as <character>]",
" [--pitch target|source|contour] [--semitones <n>]",
" umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]",
" [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--force] [--dry-run]",
@@ -77,10 +80,20 @@ export const NARRATE_USAGE = [
" character), this video's for the post's author, the cast's, the narrator. Its RECORDED PRESET says whether the",
" read is cleaned and its edges trimmed to speech (and the room kept): --clean | --no-clean and --trim | --no-trim",
" say otherwise for this read.",
+ " --recording <file> --preview: THE SAME CHAIN, NO TAKE MADE (lib/report/recordPreview.mjs; the record page's",
+ " Filter) -- cleaned, its edges cut (--trim-span 0.4-3.1: at these seconds of the recording instead of the auto",
+ " trim's; a parted read: 2=0.2-4), converted -- into the scratch dir narration/.record-preview/<postId>.<label>/,",
+ " its paths printed; --out <file> copies the filtered read there. Without --recording: the record page's session",
+ " of the item. A step whose inputs did not change is not run again (another --pitch asks for the convert alone).",
+ " --keep-preview makes its takes (recorded, cleaned, converted; the last picked) from those files, converting",
+ " nothing again; --discard-preview removes it. --events: its progress as one JSON object a line.",
" --speed <s> (--take, --take --thread): the speed the read is asked at (0.5-2; Orpheus has none) -- default the",
" item's own, else its character's (the synthetic preset's: umtool cast set <id> --speed). A thread read: every part.",
" --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op",
" (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.",
+ " A convert is the CHARACTER's (--as, else the item's own, this video's for the author, the cast's, the narrator):",
+ " its recorded preset's engine, stock voice, pitch and semitones, each unless its flag says otherwise. With no",
+ " character and no --voice it is refused: the editor's default voice is never asked for.",
" --pitch target|source|contour [--semitones <n>] (a convert, by --derive or --recording): the PITCH the converted",
" read lands on -- target: the stock voice's own (the read's intonation is flattened to it); source: the pitch it",
" was read at (raise your voice and it rises); contour: the read's rises and falls, moved as a whole to the stock",
@@ -428,7 +441,7 @@ async function timeTakeWords(project, rel, script, { askOp = null, emit = () =>
}
/** `umtool posts narrate …` (postsCli.mjs routes it here). */
-export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [] }) {
+export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [], ask = null }) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new NarrateError(`${project.id} has no manifest`);
const render = manifest.render ?? {};
@@ -537,6 +550,68 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`);
return 0;
}
+ if (flags.has("--preview") || flags.has("--keep-preview") || flags.has("--discard-preview")) {
+ // RECORD -> FILTER -> PREVIEW (recordPreview.mjs): the chain run into the scratch dir, no take made; then kept, or dropped.
+ const { discardPreview, keepPreview, previewDirOf, runPreview } = await import("./recordPreview.mjs");
+ const label = str("--label") ?? "operator";
+ if (flags.has("--discard-preview")) {
+ await discardPreview(project.dir, e, label);
+ out(json ? JSON.stringify({ ok: true, id: e.id, discarded: previewDirOf(project.dir, e, label) }, null, 2) : `${e.id}: its preview is gone (${previewDirOf(project.dir, e, label)})`);
+ return 0;
+ }
+ if (flags.has("--keep-preview")) {
+ // A preview of the record page's session is kept only while the session is still the recording it was made from.
+ const { readPreview } = await import("./recordPreview.mjs");
+ const made = await readPreview(project.dir, e, label);
+ const parts = made?.session ? await (await import("./recordSession.mjs")).sessionParts(project.dir, e, label).catch(() => null) : null;
+ if (made?.session && !parts) throw new NarrateError(`${e.id}'s preview is of the record page's session, and that session is gone or not whole any more: --discard-preview, and Filter again`);
+ const r = await keepPreview(project, e, { label, note: str("--note"), script: str("--script"), parts });
+ // A preview of the record page's session: its parts are takes now, the session is over.
+ if (r.session) await (await import("./recordSession.mjs")).clearSession(project.dir, e, label);
+ if (json) out(JSON.stringify({ ok: true, id: e.id, takes: r.takes, picked: r.picked, notes: r.notes, disclosure: r.disclosure, character: r.character, token: r.token }, null, 2));
+ else {
+ out(`${e.id}: ${r.takes.map((t) => `${t.step} -> ${t.file}`).join(", ")}; picked ${r.picked} (from its preview: nothing converted again)`);
+ if (r.disclosure) out(` disclosure: ${r.disclosure}`);
+ }
+ return 0;
+ }
+ // The recording: the file named, else the record page's session of this post (every part of it in).
+ const file = str("--recording");
+ let parts;
+ const fromSession = file === null;
+ if (file !== null) {
+ const abs = path.resolve(file);
+ if (!(await stat(abs).catch(() => null))?.isFile()) throw new NarrateError(`--recording takes a sound file (no ${file})`);
+ parts = [{ file: abs, text: String(e.narration?.script ?? "") }];
+ } else {
+ const { sessionParts } = await import("./recordSession.mjs");
+ try {
+ parts = await sessionParts(project.dir, e, label);
+ } catch (err) {
+ throw new NarrateError(`--preview takes --recording <file>, or the record page's session of ${e.id}: ${err.message}`);
+ }
+ }
+ const events = flags.has("--events");
+ const r = await runPreview(project, e, parts, {
+ label, session: fromSession, as: str("--as"), clean: flags.has("--no-clean") ? false : flags.has("--clean") ? true : undefined,
+ ...(flags.has("--no-trim") ? { trim: { on: false, padMs: null } } : flags.has("--trim") ? { trim: { on: true, padMs: null } } : {}),
+ spans: trimSpans(multi("--trim-span"), parts.length), convert: !flags.has("--no-convert"), engine: str("--engine"), voice: str("--voice"), ...pitchFlags(str), out: str("--out"), ask,
+ // --events: one JSON object a line (the record page's job reads them); else the sentences.
+ emit: (ev, f) => (events ? out(JSON.stringify({ ev, ...f })) : !json && f?.message && out(ev === "note" ? f.message : ` ${f.message}`)),
+ });
+ if (events) out(JSON.stringify({ ev: "result", ok: true, id: e.id, ...r }));
+ else if (json) out(JSON.stringify({ ok: true, id: e.id, ...r }, null, 2));
+ else {
+ out(`${e.id}: previewed${r.character ? ` as ${r.character.name}` : ""} -- NO TAKE MADE`);
+ out(` raw ${r.raw}`);
+ if (r.clean) out(` cleaned ${r.clean}`);
+ if (r.filtered) out(` filtered ${r.filtered}${r.convert ? ` (${r.convert.engine ?? "the editor's engine"} -> ${r.convert.voice}${convertPitchLabel(r.convert) ? `, pitch: ${convertPitchLabel(r.convert)}` : ""})` : ""}`);
+ if (r.out) out(` copied to ${r.out}`);
+ for (const n of r.notes) out(` ${n}`);
+ out(` keep it: umtool posts narrate ${project.id} ${e.id} --keep-preview${label !== "operator" ? ` --label ${label}` : ""} (drop it: --discard-preview)`);
+ }
+ return 0;
+ }
if (str("--recording") !== null) {
// A RECORDING made a character's read: kept as a take (the original), cleaned, converted to its stock voice.
const r = await importRecording(project, e, str("--recording"), {
@@ -562,7 +637,21 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
try {
const pitched = pitchFlags(str);
if (op !== "convert" && (pitched.pitch !== undefined || pitched.semitones !== undefined)) throw new NarrateError("--pitch and --semitones are a convert's (--op convert): an enhance keeps the read's own pitch");
- const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), ...pitched, emit: (_ev, f) => !json && f?.message && out(f.message) });
+ let asked = { engine: str("--engine"), voice: str("--voice"), ...pitched };
+ if (op === "convert") {
+ // A convert is the CHARACTER's (cast.mjs characterForRead: --as, the item's own, this video's for the author,
+ // the cast's, the narrator): its recorded preset's engine, stock voice, pitch and semitones, each unless a flag
+ // says otherwise -- and with no character and no --voice it is refused, never the editor's default voice.
+ const { readLayers } = await import("./characterLayers.mjs");
+ const { recordedPresetOf } = await import("umtool-report-to-video/cast");
+ const who = (await readLayers(project.dir)).characterForRead(e, str("--as"));
+ if (str("--as") && !who?.character) throw new NarrateError(`--as ${str("--as")}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`);
+ const d = convertAskOf(asked, who?.character ? recordedPresetOf(who.character).convert : null, who?.character?.id ?? null);
+ if (!d.ok) throw new NarrateError(`${d.error} (${d.fix})`);
+ asked = d.value;
+ if (!json && d.from === "character") out(` as ${who.character.id}: ${asked.engine ?? "the editor's engine"} -> ${asked.voice}${convertPitchLabel(asked) ? ` (pitch: ${convertPitchLabel(asked)})` : ""}`);
+ }
+ const r = await deriveTake(project, e, { from: k - 1, op, ...asked, ask, emit: (_ev, f) => !json && f?.message && out(f.message) });
if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2));
else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`);
return 0;
@@ -745,6 +834,23 @@ function speedFlag(str) {
return n;
}
+/**
+ * `--trim-span` as the cut marks of a preview: `<from>-<to>` (the first part) or `<n>=<from>-<to>` (part n), seconds
+ * in the part as recorded, once a part. Returns `[{ from, to } | null]` per part, or null when none was given.
+ */
+export function trimSpans(specs, count) {
+ if (!specs.length) return null;
+ const out = new Array(count).fill(null);
+ for (const spec of specs) {
+ const m = /^(?:(\d+)=)?(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(spec).trim());
+ const n = m ? Number(m[1] ?? 1) : 0;
+ if (!m || n < 1 || n > count || !(Number(m[3]) - Number(m[2]) >= 0.2)) throw new NarrateError(`--trim-span is <from>-<to> or <part>=<from>-<to> in seconds, at least 0.2 s, for a part 1-${count} (got ${spec || "nothing"})`);
+ if (out[n - 1]) throw new NarrateError(`--trim-span names part ${n} twice`);
+ out[n - 1] = { from: Number(m[2]), to: Number(m[3]) };
+ }
+ return out;
+}
+
/** `--pitch` / `--semitones` as a convert takes them (only those given); a value the editor would refuse anyway is refused here, in the flag's name. */
export function pitchFlags(str) {
const out = {};
diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs
@@ -13,7 +13,7 @@
// project's synthesized takes (their measured loudness, else -21 LUFS) by one
// gain under a -1 dBFS limiter. Nothing else: no cloning, no TTS, no effects.
import { execFile } from "node:child_process";
-import { mkdir, readdir, rename, rm, stat } from "node:fs/promises";
+import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { detectSilence } from "umtool-report-to-video/cut-points";
@@ -54,56 +54,81 @@ export function targetLufsOf(manifest) {
}
/**
- * KEEP A RECORDING: `parts` `[{ file (an uploaded blob, absolute), text, para }]`
- * in reading order, made into take-<n>.recorded-<label>.wav and added to
- * `entry`'s takes (picked) through the writer. Returns the take.
- *
- * @param {{ id: string, dir: string }} project
- * @param {Record<string, any>} entry
- * @param {Array<{ file: string, text?: string, para?: number }>} parts
- * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null, trim?: { on?: boolean, padMs?: number | null } | null }} [o]
+ * A part's span as a person set it (the record page's cut marks: `{ from, to }` in the part's own seconds), kept
+ * inside `[0, seconds]`; null when it is not one (not two numbers, or under 0.2 s) -- the caller's auto trim then.
*/
-export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null } = {}) {
- // A character's recorded preset (cast.mjs recordedPresetOf): its edges left as recorded (`trim.on` false), or the
- // room kept either side of the words (`trim.padMs`); none: trimmed, RECORD_ROOM.
- const room = trim && Number.isFinite(trim.padMs) ? { head: trim.padMs / 1000, tail: trim.padMs / 1000 } : RECORD_ROOM;
- if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`);
- if (!parts.length) throw new Error("nothing was recorded");
- const pid = postIdOf(entry);
- const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
- await mkdir(dir, { recursive: true });
- const n = nextTakeNumber(entry, await readdir(dir).catch(() => []));
- const base = `take-${n}.recorded-${label}`;
- const rel = `${takesDirOf(pid)}/${base}.wav`;
- const partsRel = `${takesDirOf(pid)}/${base}.parts`;
- const partsDir = path.join(project.dir, ...partsRel.split("/"));
- await mkdir(partsDir, { recursive: true });
+export function explicitSpan(span, seconds) {
+ if (!span || !Number.isFinite(span.from) || !Number.isFinite(span.to)) return null;
+ const from = Math.max(0, Math.min(seconds, span.from));
+ const to = Math.max(0, Math.min(seconds, span.to));
+ return to - from >= 0.2 ? { from: r3(from), to: r3(to) } : null;
+}
+
+/**
+ * Is `file` TEXT where a sound should be -- a playlist, a concat script, an SDP, a manifest (m3u8, ffconcat, MPD …)?
+ * ffmpeg would follow one to OTHER files and addresses; a recording is a binary container, so its first bytes are
+ * never all text. An upload that is, is refused before ffmpeg sees it.
+ */
+export async function looksLikeText(file) {
+ const fh = await open(file, "r");
+ try {
+ const buf = Buffer.alloc(2048);
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
+ if (!bytesRead) return false;
+ for (let i = 0; i < bytesRead; i += 1) {
+ const b = buf[i];
+ if (b === 0 || (b < 9) || (b > 13 && b < 32)) return false;
+ }
+ return true;
+ } finally {
+ await fh.close();
+ }
+}
+
+/**
+ * One part as it was recorded (any sound ffmpeg reads) -> a 48 kHz mono wav, measured: `{ seconds, silences }`. The
+ * file is an UPLOAD: a text file (a playlist: looksLikeText) is refused, and ffmpeg may open local files only
+ * (`-protocol_whitelist file`: no http, no concat, no pipe).
+ */
+export async function decodePart(src, out) {
+ if (await looksLikeText(src)) throw Object.assign(new Error("that is not a sound file: it is text (a playlist or a script), and a recording is refused one"), { status: 400 });
+ await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-y", "-protocol_whitelist", "file", "-i", src, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", out]);
+ const { seconds } = await measureTake(out);
+ const silences = await detectSilence(out, { silenceMinDur: 0.15 }).catch(() => []);
+ return { seconds: r3(seconds ?? 0), silences };
+}
+
+/** The room kept either side of a part's words: a preset's `trim.padMs`, else the recorder's own. */
+export const roomOf = (trim) => (trim && Number.isFinite(trim.padMs) ? { head: trim.padMs / 1000, tail: trim.padMs / 1000 } : RECORD_ROOM);
+
+/**
+ * THE PARTS OF A RECORDING, CUT AND JOINED: `sources` `[{ wav (48 kHz mono, absolute), from, to, text?, para? }]` in
+ * reading order -> each cut to its span into `<partsDir>/pNN.wav`, joined with post-narration.mjs's pauses and
+ * brought to `target` LUFS by one gain under a -1 dBFS limiter, into `out`. Returns `{ seconds, lufs, gain, parts:
+ * [{ n, para, text?, name: "pNN.wav", start, seconds, gapBefore }] }` -- a part's `name` is its file in `partsDir`.
+ * keepRecording's and the record page's preview (recordPreview.mjs) make the same file from the same spans.
+ */
+export async function joinRecording(sources, { out, partsDir, target }) {
const ff = FFMPEG();
- // Each part: decoded, measured, trimmed of its silence at either end.
+ await mkdir(partsDir, { recursive: true });
const made = [];
- for (const [k, p] of parts.entries()) {
- const raw = path.join(partsDir, `.p${String(k + 1).padStart(2, "0")}.raw.wav`);
- await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.file, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", raw]);
- const { seconds } = await measureTake(raw);
- const sil = await detectSilence(raw, { silenceMinDur: 0.15 }).catch(() => []);
- const span = trim?.on === false ? { from: 0, to: r3(seconds ?? 0) } : trimSpan(sil, seconds ?? 0, room);
- const out = path.join(partsDir, `p${String(k + 1).padStart(2, "0")}.wav`);
- await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", raw, "-af", `atrim=${span.from}:${span.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", out]);
- await rm(raw, { force: true });
- made.push({ out, seconds: r3(span.to - span.from), text: p.text, para: Number.isInteger(p.para) ? p.para : k });
+ for (const [k, p] of sources.entries()) {
+ const name = `p${String(k + 1).padStart(2, "0")}.wav`;
+ const file = path.join(partsDir, name);
+ await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.wav, "-af", `atrim=${p.from}:${p.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", file]);
+ made.push({ file, name, seconds: r3(p.to - p.from), text: p.text, para: Number.isInteger(p.para) ? p.para : k });
}
// Joined with the pauses, then brought to the synthesized takes' level.
- const withPara = made.map((m) => ({ ...m }));
const inputs = [];
const chain = [];
let start = 0;
- const partsOut = [];
- withPara.forEach((m, k) => {
- const gap = partGapBefore(withPara, k);
+ const parts = [];
+ made.forEach((m, k) => {
+ const gap = partGapBefore(made, k);
if (gap > 0) chain.push({ silence: gap });
start += gap;
- partsOut.push({ n: k + 1, para: m.para, ...(m.text ? { text: m.text } : {}), file: `${partsRel}/p${String(k + 1).padStart(2, "0")}.wav`, start: r3(start), seconds: m.seconds, gapBefore: gap });
- chain.push({ file: m.out });
+ parts.push({ n: k + 1, para: m.para, ...(m.text ? { text: m.text } : {}), name: m.name, start: r3(start), seconds: m.seconds, gapBefore: gap });
+ chain.push({ file: m.file });
start += m.seconds;
});
const filters = [];
@@ -118,25 +143,70 @@ export async function keepRecording(project, entry, parts, { label = "operator",
}
labels.push(`[s${j}]`);
}
- const joined = path.join(dir, `.${base}.joined.wav`);
+ const joined = `${out}.joined.wav`;
await execFileP(ff, ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", `${filters.join(";")};${labels.join("")}concat=n=${labels.length}:v=0:a=1[a]`, "-map", "[a]", "-c:a", "pcm_s16le", joined]);
const measured = await measureTake(joined);
- const target = targetLufsOf(manifest ?? {});
const gain = Number.isFinite(measured.lufs) ? Math.max(-20, Math.min(30, target - measured.lufs)) : 0;
- const tmp = path.join(dir, `.${base}.tmp.wav`);
+ const tmp = `${out}.tmp.wav`;
await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", joined, "-af", `volume=${gain.toFixed(2)}dB,alimiter=limit=0.891251:level=0:latency=1`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp]);
await rm(joined, { force: true });
+ await rename(tmp, out);
+ if (!(await stat(out).catch(() => null))?.isFile()) throw new Error(`${out} was not written`);
+ const m = await measureTake(out);
+ return { seconds: m.seconds, lufs: m.lufs, gain: Math.round(gain * 100) / 100, parts };
+}
+
+/** joinRecording's parts as a take keeps them: each one's file under `relDir` (project-relative). */
+export const partsIn = (parts, relDir) => parts.map((p) => ({ n: p.n, para: p.para, ...(p.text ? { text: p.text } : {}), file: `${relDir}/${p.name}`, start: p.start, seconds: p.seconds, gapBefore: p.gapBefore }));
+
+/**
+ * KEEP A RECORDING: `parts` `[{ file (an uploaded blob, absolute), text, para }]`
+ * in reading order, made into take-<n>.recorded-<label>.wav and added to
+ * `entry`'s takes (picked) through the writer. Returns the take.
+ *
+ * `spans`: the cut marks a person set, per part in reading order (`[{ from, to } | null]`, the part's own seconds:
+ * the record page's waveform) -- a part with one is cut there, whatever `trim` says; the others are trimmed as below.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {Array<{ file: string, text?: string, para?: number }>} parts
+ * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null, trim?: { on?: boolean, padMs?: number | null } | null, spans?: Array<{ from: number, to: number } | null> | null }} [o]
+ */
+export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null, trim = null, spans = null } = {}) {
+ // A character's recorded preset (cast.mjs recordedPresetOf): its edges left as recorded (`trim.on` false), or the
+ // room kept either side of the words (`trim.padMs`); none: trimmed, RECORD_ROOM.
+ const room = roomOf(trim);
+ if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`);
+ if (!parts.length) throw new Error("nothing was recorded");
+ const pid = postIdOf(entry);
+ const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
+ await mkdir(dir, { recursive: true });
+ const n = nextTakeNumber(entry, await readdir(dir).catch(() => []));
+ const base = `take-${n}.recorded-${label}`;
+ const rel = `${takesDirOf(pid)}/${base}.wav`;
+ const partsRel = `${takesDirOf(pid)}/${base}.parts`;
+ const partsDir = path.join(project.dir, ...partsRel.split("/"));
+ await mkdir(partsDir, { recursive: true });
+ // Each part: decoded, measured, cut to its marks or trimmed of its silence at either end.
+ const sources = [];
+ for (const [k, p] of parts.entries()) {
+ const raw = path.join(partsDir, `.p${String(k + 1).padStart(2, "0")}.raw.wav`);
+ const { seconds, silences } = await decodePart(p.file, raw);
+ const span = explicitSpan(spans?.[k], seconds) ?? (trim?.on === false ? { from: 0, to: seconds } : trimSpan(silences, seconds, room));
+ sources.push({ wav: raw, ...span, text: p.text, para: p.para });
+ }
const abs = path.join(project.dir, ...rel.split("/"));
- await rename(tmp, abs);
- if (!(await stat(abs).catch(() => null))?.isFile()) throw new Error(`${rel} was not written`);
- const m = await measureTake(abs);
+ const target = targetLufsOf(manifest ?? {});
+ const j = await joinRecording(sources, { out: abs, partsDir, target });
+ for (const x of sources) await rm(x.wav, { force: true });
+ const partsOut = partsIn(j.parts, partsRel);
const take = {
- file: rel, engine: "recorded", voice: label, label, seconds: m.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""),
- at: new Date().toISOString(), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(note ? { note } : {}),
+ file: rel, engine: "recorded", voice: label, label, seconds: j.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""),
+ at: new Date().toISOString(), ...(Number.isFinite(j.lufs) ? { lufs: j.lufs } : {}), ...(note ? { note } : {}),
...(partsOut.length > 1 ? { parts: partsOut } : {}),
};
const { result, editNotes } = await withEditNotes(project, async () =>
updatePostNarration(project.dir, entry.id, { addTake: take, ...(script !== null && script !== entry.narration?.script ? { script } : {}) }, { token: await manifestToken(project.dir) }),
);
- return { take, gain: Math.round(gain * 100) / 100, target, result, editNotes };
+ return { take, gain: j.gain, target, result, editNotes };
}
diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs
@@ -109,6 +109,7 @@ export async function projectCastMap(dir) {
* A part's cache key: sha1 of `voice|text` (an engine other than Orpheus: `engine|voice|text`), and of its SPEED when
* it is read at one (`…|x1.1`: the same words at another speed are another part; none, or 1: the key as before).
*/
+/** @type {(engine: string, voice: string, text: string, speed?: number | null) => string} */
export const partKey = (engine, voice, text, speed = null) => createHash("sha1").update(`${engine === "orpheus" ? `${voice}|${text}` : `${engine}|${voice}|${text}`}${typeof speed === "number" && speed !== 1 ? `|x${speed}` : ""}`).digest("hex");
/** `--parents` as a selector: "0" (default), "all", "none", or a whole number n (parents 0..n). */
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -198,9 +198,9 @@ export const POSTS_USAGE = [
" none: the rule as it stands",
].join("\n");
-const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label"]);
+const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span"]);
/** The valued flags that may be given more than once (each value kept, in order). */
-const MULTI = new Set(["--skip-parent", "--voice-for"]);
+const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -450,7 +450,7 @@ export async function addPostFromArchive(project, { slug, postId, attach = null,
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
* @returns {Promise<number>} the exit code
*/
-export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), ask = null } = {}) {
// A TAKE-SCOPED EDIT (`--in-take <take>`, takeScope.mjs): the same command over the take's manifest, written into its patch.
let scoped;
try {
@@ -549,7 +549,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
const named = words.slice(3).find((w) => takes.has(w));
if (named) throw new CliError(`posts narrate: --take makes a NEW READ (TTS); "${named}" is a take of ${project.id} -- to edit take ${named}, say --in-take ${named}`);
}
- return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi });
+ return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi, ask });
}
if (verb === "fx") {
const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs");
diff --git a/umtool/lib/report/recordPreview.mjs b/umtool/lib/report/recordPreview.mjs
@@ -0,0 +1,445 @@
+// RECORD -> FILTER -> PREVIEW (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"): a
+// recording of a post item run through its character's RECORDED PRESET -- cleaned (the editor's voice-enhance), its
+// edges trimmed to speech (or cut at the marks a person set), converted to the character's STOCK voice (the editor's
+// voice-convert) -- WITHOUT making a take, so it can be listened to beside the raw read first. The record page's
+// Filter and `umtool posts narrate <p> <item> --recording <file> --preview` are this one chain.
+//
+// <project>/narration/.record-preview/<postId>.<label>/ the SCRATCH DIR: one per post item and voice label,
+// preview.json what is in it, and what each file was made from removed on Keep, on Again, when the
+// pNN.raw.wav each part as recorded, 48 kHz mono, UNTRIMMED page is left, and when the recording
+// pNN.clean.wav each part cleaned, untrimmed it was made from changes; one a
+// raw.wav, raw.parts/ the parts cut to their spans, joined, levelled crash left behind is removed the next
+// clean.wav, clean.parts/ the same from the cleaned parts time a preview is prepared (a day old)
+// filtered.wav[, filtered.parts/] clean.wav (else raw.wav) converted
+//
+// THE ORDER is clean -> trim -> convert: the parts are cleaned WHOLE, so moving a cut mark re-cuts the cleaned sound
+// and asks the editor for the convert alone; changing the pitch asks for the convert alone too. Each step is kept
+// with a key of what it was made from (`source`: the recording's files; `built`: + the spans; `convert`: + the
+// engine, voice, pitch and semitones) and a step whose key still answers is not run again.
+//
+// KEEP (keepPreview) makes the takes `posts narrate --recording` would -- the recorded one (the original, trimmed,
+// levelled), the cleaned one, the converted one, each a new take, the last picked -- FROM THE PREVIEW's FILES: nothing
+// is converted again. Plain ESM; the editor is asked through narrate-via-editor.mjs askEditorOp (`ask` in a test).
+import { createHash } from "node:crypto";
+import { execFile } from "node:child_process";
+import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { POST_DERIVE_ROUTES, derivedFileOf, nextTakeNumber, postIdOf, postNarrationDisclosure, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
+import { convertPitchLabel, recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
+import { readManifest } from "../projects/report.mjs";
+import { readLayers } from "./characterLayers.mjs";
+import { convertAskOf, stepPitchOf } from "./derivePitch.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updatePostNarration } from "./manifest.mjs";
+import { NarrateError, findPostItem, measureTake } from "./postNarrationCli.mjs";
+import { RECORD_LABEL_RE, decodePart, explicitSpan, joinRecording, partsIn, roomOf, targetLufsOf, trimSpan } from "./postRecord.mjs";
+
+const execFileP = promisify(execFile);
+const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
+
+/** The scratch dirs' parent, project-relative. */
+export const PREVIEW_DIR = "narration/.record-preview";
+/** How many levels a part's waveform is drawn from. */
+export const PREVIEW_PEAKS = 240;
+/** A scratch dir nobody removed (a crash, a closed laptop) is removed after this long. */
+export const PREVIEW_STALE_MS = 24 * 60 * 60 * 1000;
+
+const sha = (v) => createHash("sha1").update(typeof v === "string" ? v : JSON.stringify(v)).digest("hex");
+const pad2 = (n) => String(n).padStart(2, "0");
+const checkLabel = (label) => {
+ if (!RECORD_LABEL_RE.test(String(label))) throw Object.assign(new NarrateError(`"${label}" is not a voice label (a-z, 0-9, - and _)`), { status: 400 });
+};
+
+/** The scratch dir of post item `entry`'s preview for voice `label` (absolute). */
+export const previewDirOf = (projectDir, entry, label = "operator") => path.join(projectDir, ...PREVIEW_DIR.split("/"), `${postIdOf(entry)}.${label}`);
+
+/** The preview's record (`preview.json`), or null: none, or unreadable. */
+export async function readPreview(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ try {
+ const doc = JSON.parse(await readFile(path.join(previewDirOf(projectDir, entry, label), "preview.json"), "utf8"));
+ return doc && doc.version === 1 && Array.isArray(doc.parts) ? doc : null;
+ } catch {
+ return null;
+ }
+}
+
+async function writePreview(dir, doc) {
+ const tmp = path.join(dir, `.preview.${process.pid}.${Date.now()}.json`);
+ await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`, "utf8");
+ await rename(tmp, path.join(dir, "preview.json"));
+}
+
+/** Remove the preview of `entry` (Again, leaving the page, Keep). */
+export async function discardPreview(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ await rm(previewDirOf(projectDir, entry, label), { recursive: true, force: true });
+}
+
+/** Scratch dirs of this project nobody removed in PREVIEW_STALE_MS (not `keep`): gone. */
+async function pruneStale(projectDir, keep, now = Date.now()) {
+ const root = path.join(projectDir, ...PREVIEW_DIR.split("/"));
+ for (const name of await readdir(root).catch(() => [])) {
+ const dir = path.join(root, name);
+ if (dir === keep) continue;
+ const st = await stat(path.join(dir, "preview.json")).catch(() => null) ?? (await stat(dir).catch(() => null));
+ if (st && now - st.mtimeMs > PREVIEW_STALE_MS) await rm(dir, { recursive: true, force: true });
+ }
+}
+
+/** What a recording is, for the cache: its files, their sizes and times. */
+export async function sourceKeyOf(parts) {
+ const rows = [];
+ for (const p of parts) {
+ const st = await stat(p.file).catch(() => null);
+ if (!st?.isFile()) throw new NarrateError(`no recording at ${p.file}`);
+ rows.push([p.file, st.size, Math.round(st.mtimeMs)]);
+ }
+ return sha(rows);
+}
+
+/** A wav's levels for a waveform: PREVIEW_PEAKS values 0-1, the loudest sample of each slice. */
+export async function peaksOf(wav, count = PREVIEW_PEAKS) {
+ const { stdout } = await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-i", wav, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { encoding: "buffer", maxBuffer: 512 * 1024 * 1024 });
+ const samples = Math.floor(stdout.length / 2);
+ const out = new Array(count).fill(0);
+ if (!samples) return out;
+ for (let i = 0; i < samples; i += 1) {
+ const k = Math.min(count - 1, Math.floor((i * count) / samples));
+ const v = Math.abs(stdout.readInt16LE(i * 2)) / 32768;
+ if (v > out[k]) out[k] = v;
+ }
+ return out.map((v) => Math.round(v * 1000) / 1000);
+}
+
+/**
+ * PREPARE: the recording's parts decoded into the scratch dir (once: a recording that has not changed is not decoded
+ * again), each with its length, its waveform and the AUTO TRIM's answer -- `auto: { from, to }`, the span of its
+ * speech with the room kept (`trim.padMs`, else the recorder's own), or the whole part when `trim.on` is false. No
+ * editor, no take. Returns the preview's record.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {Array<{ file: string, text?: string, para?: number }>} parts
+ * @param {{ label?: string, trim?: { on?: boolean, padMs?: number | null } | null }} [o]
+ */
+export async function preparePreview(project, entry, parts, { label = "operator", trim = null } = {}) {
+ checkLabel(label);
+ if (!parts.length) throw new NarrateError("nothing was recorded");
+ const dir = previewDirOf(project.dir, entry, label);
+ const source = await sourceKeyOf(parts);
+ let doc = await readPreview(project.dir, entry, label);
+ if (!doc || doc.source !== source) {
+ // Another recording than the one in the scratch dir (a part re-recorded, another file): everything from it goes.
+ await rm(dir, { recursive: true, force: true });
+ await mkdir(dir, { recursive: true });
+ await pruneStale(project.dir, dir);
+ doc = { version: 1, id: entry.id, label, source, at: new Date().toISOString(), parts: [], clean: null, cleaned: null, built: null, convert: null, notes: [] };
+ for (const [k, p] of parts.entries()) {
+ const raw = `p${pad2(k + 1)}.raw.wav`;
+ const { seconds, silences } = await decodePart(p.file, path.join(dir, raw));
+ doc.parts.push({ n: k + 1, para: Number.isInteger(p.para) ? p.para : k, text: String(p.text ?? ""), raw, seconds, silences, peaks: await peaksOf(path.join(dir, raw)) });
+ }
+ }
+ const on = trim?.on !== false;
+ const room = roomOf(trim);
+ doc.trim = { on, padMs: Number.isFinite(trim?.padMs) ? trim.padMs : null };
+ for (const p of doc.parts) p.auto = on ? trimSpan(p.silences, p.seconds, room) : { from: 0, to: p.seconds };
+ await writePreview(dir, doc);
+ return doc;
+}
+
+const notInstalled = (err) => err?.name === "OpNotInstalled" || /not installed/i.test(String(err?.message));
+
+/**
+ * THE CHAIN, no take made: `parts` (`[{ file, text?, para? }]`, a recording in reading order) prepared, CLEANED
+ * (unless the character's preset or `clean` says not to; an editor with no enhance engine: said, and gone without),
+ * cut to `spans` (per part, `{ from, to }` in its own seconds; a part without one: the auto trim's) and joined,
+ * CONVERTED to the character's stock voice at `pitch` / `semitones` (each unless given: the preset's;
+ * derivePitch.mjs convertAskOf). The character is `as`, else the chain's (cast.mjs characterForRead). What the
+ * command says wins over the preset: `clean`, `trim`, `pitch`, `semitones`, `engine`, `voice`; `convert: false` stops
+ * after the clean.
+ *
+ * `emit("stage", { stage: "decode" | "clean" | "trim" | "convert" | "done", state, message })` says where it is --
+ * `state`: `running`, `cached`, `skipped`, `done`, and while the editor's job waits `queued` (behind other jobs),
+ * `memory` or `slot` (at the heavy slot: the gate working, not an error).
+ *
+ * Returns `{ dir, raw, clean, filtered, listen, notes, character, direction, convert, spans, lufs, cached }` -- the
+ * files absolute; `listen` is what to compare with `raw` (the converted read, else the cleaned one, else null).
+ * `out`: `listen` (else `raw`) copied there. `session: true`: the parts are the record page's session of the item
+ * (keepPreview says so, and its caller clears the session).
+ */
+export async function runPreview(project, entry, parts, {
+ label = "operator", as = null, clean = undefined, trim = undefined, spans = null, convert = true, pitch = undefined, semitones = undefined, engine = null, voice = null,
+ out = null, emit = () => {}, editor = null, ask = null, session = false,
+} = {}) {
+ const layers = await readLayers(project.dir);
+ const who = layers.characterForRead(entry, as);
+ const character = who?.character ?? null;
+ if (as && !character) throw new NarrateError(`--as ${as}: no such character in this video's characters or the cast (umtool cast project ${project.id}, umtool cast ls)`);
+ const preset = character ? recordedPresetOf(character) : null;
+ const doClean = clean ?? preset?.enhance ?? true;
+ const doTrim = trim ?? preset?.trim ?? null;
+ const stage = (name, state, message, more = {}) => emit("stage", { stage: name, state, message, ...more });
+ const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
+ const { opWaitOf } = await import("umtool-report-to-video/narrate-via-editor");
+ const waiting = (name, what) => {
+ let last = "";
+ return (st) => {
+ const w = opWaitOf(st);
+ const key = `${w.state}|${w.position ?? ""}`;
+ if (key === last) return;
+ last = key;
+ const say = w.state === "queued" ? `${what}: queued at the editor${w.position ? ` (position ${w.position})` : ""}`
+ : w.state === "memory" ? `${what}: waiting for memory (the heavy slot admits it when there is room -- not an error)`
+ : w.state === "slot" ? `${what}: waiting for the heavy slot (another heavy job holds it -- not an error)`
+ : `${what}: running`;
+ stage(name, w.state, say, { job: st.jobId, ...(w.line ? { line: w.line } : {}) });
+ };
+ };
+ const note = (_ev, f) => f?.message && emit("note", { message: f.message });
+
+ stage("decode", "running", "reading the recording");
+ let doc = await preparePreview(project, entry, parts, { label, trim: doTrim });
+ const dir = previewDirOf(project.dir, entry, label);
+ const abs = (name) => path.join(dir, ...String(name).split("/"));
+ const has = async (name) => !!(await stat(abs(name)).catch(() => null))?.isFile();
+ const notes = [];
+ const cached = { clean: false, convert: false };
+
+ // CLEAN: the parts whole, as recorded (one job of the editor's: one admission to the heavy slot).
+ if (!doClean) {
+ doc.cleaned = { state: "off" };
+ notes.push(clean === undefined && character ? `not cleaned: ${character.id}'s recorded preset says so (enhance off)` : "not cleaned: asked not to (--no-clean)");
+ stage("clean", "skipped", notes.at(-1));
+ } else if (doc.clean?.key === doc.source && (await Promise.all(doc.clean.files.map(has))).every(Boolean)) {
+ doc.cleaned = { state: "done" };
+ cached.clean = true;
+ stage("clean", "cached", "cleaned already (this recording, unchanged)");
+ } else {
+ stage("clean", "running", "cleaning: asking the editor (voice-enhance)");
+ const files = doc.parts.map((p) => p.raw.replace(/\.raw\.wav$/, ".clean.wav"));
+ try {
+ const { jobId, result } = await askOp(POST_DERIVE_ROUTES.enhance, {
+ file: abs(doc.parts[0].raw), out: abs(files[0]),
+ ...(doc.parts.length > 1 ? { parts: doc.parts.slice(1).map((p, k) => ({ file: abs(p.raw), out: abs(files[k + 1]) })) } : {}),
+ }, { ...(editor ? { editor } : {}), emit: note, onState: waiting("clean", "cleaning") });
+ for (const f of files) if (!(await has(f))) throw new NarrateError(`the editor's job ${jobId} finished but ${f} is not there`);
+ doc.clean = { key: doc.source, files, engine: typeof result?.engine === "string" ? result.engine : null, job: jobId, ranAt: new Date().toISOString() };
+ doc.cleaned = { state: "done" };
+ stage("clean", "done", "cleaned");
+ } catch (err) {
+ if (!notInstalled(err)) throw err;
+ doc.cleaned = { state: "skipped" };
+ notes.push(`not cleaned: ${err.message} (archilyzer voice setup --engine deepfilternet)`);
+ stage("clean", "skipped", notes.at(-1));
+ }
+ await writePreview(dir, doc);
+ }
+ const cleaned = doc.cleaned.state === "done";
+
+ // TRIM: each part cut to its span -- the marks given, else the auto trim's -- the raw read and the cleaned one alike.
+ const cut = doc.parts.map((p, k) => explicitSpan(spans?.[k], p.seconds) ?? p.auto);
+ const target = targetLufsOf((await readManifest(project.dir)) ?? {});
+ const builtKey = sha([doc.source, cut, cleaned, target]);
+ if (doc.built?.key === builtKey && (await has("raw.wav")) && (!cleaned || (await has("clean.wav")))) {
+ stage("trim", "cached", "cut and joined already (these marks)");
+ } else {
+ stage("trim", "running", `cutting ${doc.parts.length === 1 ? "it" : `its ${doc.parts.length} parts`} to ${doc.parts.length === 1 ? "its marks" : "their marks"}`);
+ const sources = (file) => doc.parts.map((p, k) => ({ wav: abs(file(p, k)), ...cut[k], text: p.text, para: p.para }));
+ for (const f of ["raw.parts", "clean.parts", "filtered.parts"]) await rm(abs(f), { recursive: true, force: true });
+ for (const f of ["clean.wav", "filtered.wav"]) await rm(abs(f), { force: true });
+ const raw = await joinRecording(sources((p) => p.raw), { out: abs("raw.wav"), partsDir: abs("raw.parts"), target });
+ const cl = cleaned ? await joinRecording(sources((_p, k) => doc.clean.files[k]), { out: abs("clean.wav"), partsDir: abs("clean.parts"), target }) : null;
+ doc.built = { key: builtKey, spans: cut, target, raw: { file: "raw.wav", ...raw }, clean: cl ? { file: "clean.wav", ...cl } : null };
+ doc.convert = null;
+ await writePreview(dir, doc);
+ stage("trim", "done", `cut: ${raw.seconds} s`);
+ }
+
+ // CONVERT: the cleaned read (else the raw one) to the character's stock voice, at the pitch asked or the preset's.
+ if (!convert) {
+ notes.push("not converted: asked not to (--no-convert)");
+ stage("convert", "skipped", notes.at(-1));
+ } else {
+ const d = convertAskOf({ engine, voice, pitch, semitones }, character ? preset.convert : null, character?.id ?? null);
+ if (!d.ok) {
+ notes.push(`not converted: ${d.error} (${d.fix})`);
+ stage("convert", "skipped", notes.at(-1));
+ } else {
+ const a = d.value;
+ const key = sha([builtKey, a.engine, a.voice, a.pitch ?? null, a.semitones ?? null]);
+ if (doc.convert?.key === key && (await has("filtered.wav"))) {
+ cached.convert = true;
+ stage("convert", "cached", `converted already (${a.voice}${convertPitchLabel(doc.convert) ? `, pitch: ${convertPitchLabel(doc.convert)}` : ""})`);
+ } else {
+ stage("convert", "running", `converting to ${a.voice}: asking the editor (voice-convert)`);
+ const src = doc.built.clean ?? doc.built.raw;
+ const srcParts = src.file.replace(/\.wav$/, ".parts");
+ await rm(abs("filtered.parts"), { recursive: true, force: true });
+ try {
+ const { jobId, result } = await askOp(POST_DERIVE_ROUTES.convert, {
+ file: abs(src.file), out: abs("filtered.wav"), ...(a.engine ? { engine: a.engine } : {}), voice: a.voice,
+ ...(a.pitch ? { pitch: a.pitch } : {}), ...(typeof a.semitones === "number" ? { semitones: a.semitones } : {}),
+ ...(src.parts.length > 1 ? { parts: src.parts.map((p) => ({ file: abs(`${srcParts}/${p.name}`), out: abs(`filtered.parts/${p.name}`) })) } : {}),
+ }, { ...(editor ? { editor } : {}), emit: note, onState: waiting("convert", "converting") });
+ if (!(await has("filtered.wav"))) throw new NarrateError(`the editor's job ${jobId} finished but filtered.wav is not there`);
+ const m = await measureTake(abs("filtered.wav"));
+ doc.convert = {
+ key, built: builtKey, file: "filtered.wav", asked: a,
+ engine: a.engine ?? (typeof result?.engine === "string" ? result.engine : null), voice: a.voice, ...stepPitchOf(a, result ?? {}),
+ job: jobId, ranAt: new Date().toISOString(), seconds: m.seconds, ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}),
+ };
+ stage("convert", "done", `converted to ${a.voice}${convertPitchLabel(doc.convert) ? ` (pitch: ${convertPitchLabel(doc.convert)})` : ""}`);
+ } catch (err) {
+ if (!notInstalled(err)) throw err;
+ doc.convert = null;
+ notes.push(`not converted: ${err.message} (archilyzer voice setup --engine ${a.engine ?? "openvoice"})`);
+ stage("convert", "skipped", notes.at(-1));
+ }
+ }
+ }
+ }
+ doc.notes = notes;
+ // Made from the record page's session (not a file): keeping it is the end of that session.
+ doc.session = session === true;
+ doc.character = character ? { id: character.id, name: shownNameOf(character), layer: who.layer } : null;
+ await writePreview(dir, doc);
+ const listen = doc.convert ? abs(doc.convert.file) : doc.built.clean ? abs(doc.built.clean.file) : null;
+ let copied = null;
+ if (out) {
+ copied = path.resolve(String(out));
+ await mkdir(path.dirname(copied), { recursive: true });
+ await copyFile(listen ?? abs("raw.wav"), copied);
+ }
+ stage("done", "done", listen ? "the preview is ready: nothing was kept" : "nothing to filter it with: the raw read alone");
+ return {
+ dir, raw: abs("raw.wav"), clean: doc.built.clean ? abs("clean.wav") : null, filtered: doc.convert ? abs(doc.convert.file) : null, listen, ...(copied ? { out: copied } : {}),
+ notes, character: doc.character, ...(preset?.direction ? { direction: preset.direction } : {}),
+ convert: doc.convert ? { engine: doc.convert.engine, voice: doc.convert.voice, ...(doc.convert.pitch ? { pitch: doc.convert.pitch } : {}), ...(typeof doc.convert.semitones === "number" ? { semitones: doc.convert.semitones } : {}) } : null,
+ spans: cut, lufs: { raw: doc.built.raw.lufs ?? null, filtered: doc.convert?.lufs ?? doc.built.clean?.lufs ?? null }, cached,
+ };
+}
+
+/**
+ * What the record page is told of a preview (`preview.json` without the silences): each part's length, waveform, auto
+ * span and the span it was cut at; what was made (`raw`, `clean`, `filtered`: seconds and loudness, so both play at one
+ * level); the convert as it ran; the notes. `null`: none.
+ */
+export function previewView(doc) {
+ if (!doc) return null;
+ const made = (x) => (x ? { seconds: x.seconds ?? null, lufs: Number.isFinite(x.lufs) ? x.lufs : null } : null);
+ return {
+ id: doc.id, label: doc.label, source: doc.source, trim: doc.trim ?? { on: true, padMs: null },
+ parts: doc.parts.map((p, k) => ({ n: p.n, text: p.text, seconds: p.seconds, auto: p.auto, peaks: p.peaks, span: doc.built?.spans?.[k] ?? null })),
+ cleaned: doc.cleaned?.state ?? null,
+ raw: made(doc.built?.raw), clean: made(doc.built?.clean),
+ filtered: doc.convert && doc.convert.built === doc.built?.key ? { ...made(doc.convert), engine: doc.convert.engine, voice: doc.convert.voice, pitch: doc.convert.pitch ?? "target", semitones: doc.convert.semitones ?? 0, asked: doc.convert.asked ?? null } : null,
+ notes: doc.notes ?? [], character: doc.character ?? null,
+ };
+}
+
+/**
+ * The absolute file of one of a preview's sounds (`raw`, `clean`, `filtered`, or `part` + n: that part as recorded), or null.
+ *
+ * @param {string} projectDir
+ * @param {Record<string, any>} entry
+ * @param {string} which
+ * @param {{ label?: string, n?: number | null }} [o]
+ */
+export async function previewFile(projectDir, entry, which, { label = "operator", n = null } = {}) {
+ const doc = await readPreview(projectDir, entry, label);
+ if (!doc) return null;
+ const dir = previewDirOf(projectDir, entry, label);
+ const name = which === "raw" ? doc.built?.raw?.file : which === "clean" ? doc.built?.clean?.file : which === "filtered" ? (doc.convert?.built === doc.built?.key ? doc.convert?.file : null)
+ : which === "part" ? doc.parts.find((p) => p.n === Number(n))?.raw : null;
+ if (!name) return null;
+ const f = path.join(dir, name);
+ return (await stat(f).catch(() => null))?.isFile() ? f : null;
+}
+
+/**
+ * KEEP THE PREVIEW: its files made the takes a recording made a read would be -- take-<n>.recorded-<label>.wav (the
+ * original: trimmed, joined, levelled), the cleaned one (`steps: [{op: "enhance"}]`), the converted one (`steps: [{op:
+ * "convert", engine, voice, pitch?, semitones?}]`) -- each a new take through the writer (an undo point each), the
+ * last one PICKED (a pick takes the approval away: it awaits approval). Nothing is asked of the editor. The scratch dir
+ * is removed. `parts`: the recording meant (the session's parts now) -- a preview of another is refused (409). Returns `{ takes: [{ step, file }], picked, notes, disclosure, character, session, entry, token }`.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {{ label?: string, script?: string | null, note?: string | null, parts?: Array<{ file: string }> | null }} [o]
+ */
+export async function keepPreview(project, entry, { label = "operator", script = null, note = null, parts: meant = null } = {}) {
+ const doc = await readPreview(project.dir, entry, label);
+ if (!doc?.built) throw Object.assign(new NarrateError(`${entry.id} has no preview to keep (Filter it first: umtool posts narrate ${project.id} ${entry.id} --recording <file> --preview)`), { status: 409 });
+ // The recording the caller means to keep (the record page's session, as it is NOW): a preview made from another
+ // one -- a part recorded again since the Filter -- is refused; its sound is not what was read last.
+ if (meant && (await sourceKeyOf(meant)) !== doc.source) throw Object.assign(new NarrateError(`${entry.id}'s preview is of an earlier recording (a part was recorded again since the Filter): Filter again, or keep the recording alone`), { status: 409 });
+ const dir = previewDirOf(project.dir, entry, label);
+ const pid = postIdOf(entry);
+ const takesDir = path.join(project.dir, ...takesDirOf(pid).split("/"));
+ await mkdir(takesDir, { recursive: true });
+ let n = nextTakeNumber(entry, await readdir(takesDir).catch(() => []));
+ const abs = (rel) => path.join(project.dir, ...rel.split("/"));
+ const multi = doc.parts.length > 1;
+ // One of the preview's sounds (and its parts) moved to a take's name.
+ const move = async (made, rel) => {
+ await rename(path.join(dir, made.file), abs(rel));
+ const partsRel = rel.replace(/\.wav$/, ".parts");
+ const from = path.join(dir, made.file.replace(/\.wav$/, ".parts"));
+ if (await stat(from).catch(() => null)) {
+ await rm(abs(partsRel), { recursive: true, force: true });
+ await rename(from, abs(partsRel));
+ }
+ return partsRel;
+ };
+ const write = async (patch) => (await withEditNotes(project, async () => updatePostNarration(project.dir, entry.id, patch, { token: await manifestToken(project.dir) }))).result;
+ const takes = [];
+ const at = () => new Date().toISOString();
+ const lufs = (x) => (Number.isFinite(x?.lufs) ? { lufs: x.lufs } : {});
+ const text = String(script ?? entry.narration?.script ?? "");
+ const who = doc.character;
+
+ // The original.
+ const rel = `${takesDirOf(pid)}/take-${n}.recorded-${label}.wav`;
+ const partsRel = await move(doc.built.raw, rel);
+ const parts = multi ? partsIn(doc.built.raw.parts, partsRel) : null;
+ const recorded = {
+ file: rel, engine: "recorded", voice: label, label, seconds: doc.built.raw.seconds, source: { kind: "recorded", voice: label }, script: text,
+ at: at(), ...lufs(doc.built.raw), note: note ?? `recorded${who ? ` for ${who.name}` : ""}`, ...(parts ? { parts } : {}),
+ };
+ let result = await write({ addTake: recorded, ...(script !== null && script !== entry.narration?.script ? { script } : {}) });
+ takes.push({ step: "recorded", file: rel });
+ let from = recorded;
+ const derived = (file, made, step, voiceOf, partsDir, job) => ({
+ file, engine: "derived", voice: voiceOf, seconds: made.seconds, source: { kind: "take", from: takeIdOf(from) }, steps: [step], script: text, at: at(), ...(job ? { jobId: job } : {}), ...lufs(made),
+ ...(parts ? { parts: parts.map((p) => ({ ...p, file: `${partsDir}/p${pad2(p.n)}.wav` })) } : {}),
+ });
+
+ // The cleaned one.
+ if (doc.built.clean) {
+ n += 1;
+ const r2 = derivedFileOf(pid, n, "enhance", "default");
+ const p2 = await move(doc.built.clean, r2);
+ const take = derived(r2, doc.built.clean, { op: "enhance", ...(doc.clean?.engine ? { engine: doc.clean.engine } : {}), ranAt: doc.clean?.ranAt ?? at(), ...(doc.clean?.job ? { job: doc.clean.job } : {}) }, label, p2, doc.clean?.job);
+ result = await write({ addTake: take });
+ takes.push({ step: "cleaned", file: r2 });
+ from = take;
+ }
+ // The converted one -- when it is of these marks (a mark moved after the Filter leaves it behind).
+ if (doc.convert && doc.convert.built === doc.built.key && (await stat(path.join(dir, doc.convert.file)).catch(() => null))?.isFile()) {
+ n += 1;
+ const c = doc.convert;
+ const r3 = derivedFileOf(pid, n, "convert", c.asked?.engine ?? c.asked?.voice ?? "default");
+ const p3 = await move(c, r3);
+ const pitched = c.pitch ? { pitch: c.pitch, ...(typeof c.semitones === "number" ? { semitones: c.semitones } : {}) } : {};
+ const take = derived(r3, c, { op: "convert", ...(c.engine ? { engine: c.engine } : {}), voice: c.voice, ...pitched, ranAt: c.ranAt ?? at(), ...(c.job ? { job: c.job } : {}) }, String(c.voice).split(":").pop(), p3, c.job);
+ result = await write({ addTake: take });
+ const how = convertPitchLabel(c);
+ takes.push({ step: `converted to ${c.voice}${how ? ` (pitch: ${how})` : ""}`, file: r3 });
+ }
+ await rm(dir, { recursive: true, force: true });
+ const now = findPostItem(await readManifest(project.dir), entry.id);
+ return { takes, picked: takes.at(-1).file, notes: doc.notes ?? [], disclosure: now ? postNarrationDisclosure(now) : null, character: who ?? null, session: doc.session === true, entry: result.entry, token: result.token };
+}
diff --git a/umtool/lib/report/recordPreview.test.mjs b/umtool/lib/report/recordPreview.test.mjs
@@ -0,0 +1,382 @@
+// RECORD -> FILTER -> PREVIEW (recordPreview.mjs; postRecord.mjs keepRecording's spans; narrate-via-editor.mjs
+// opWaitOf): the chain into a scratch dir with no take made, each step kept and not run again while what it was made
+// from stands (another pitch asks for the convert alone; a mark moved re-cuts and converts, never cleans again), the
+// heavy slot's wait read as a state, Keep making the takes from the preview's files, and the CLI twin
+// (`posts narrate --recording <file> --preview`, `--keep-preview`, `--discard-preview`). No editor: the voice ops are
+// stubs; every project is a temp dir.
+// Run: node --test umtool/lib/report/recordPreview.test.mjs
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { opWaitOf } from "umtool-report-to-video/narrate-via-editor";
+import { validatePostNarration } from "umtool-report-to-video/post-narration";
+import { castCommand } from "./castCli.mjs";
+import { measureTake, trimSpans } from "./postNarrationCli.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { decodePart, explicitSpan, keepRecording, looksLikeText } from "./postRecord.mjs";
+import { PREVIEW_PEAKS, discardPreview, keepPreview, preparePreview, previewDirOf, previewFile, previewView, readPreview, runPreview } from "./recordPreview.mjs";
+import { finishSession, savePart } from "./recordSession.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-record-preview-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const wavOf = async (file, voice, seconds = 1.5, silence = 0.3) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: silence, after: silence })));
+};
+const run = (command, key) => async (args, extra = {}) => {
+ const lines = [];
+ const code = await command(args, { [key]: ROOT, log: (s) => lines.push(s), out: (s) => lines.push(s), err: (s) => lines.push(s), ...extra });
+ return { code, lines, text: () => lines.join("\n"), json: () => JSON.parse(lines.join("\n")) };
+};
+const cast = run(castCommand, "reportsRoot");
+const posts = run(postsCommand, "root");
+
+const DIR = path.join(ROOT, "rec");
+{
+ const post = (id, handle, author, o = {}) => ({ type: "post", id: `p-${id}`, post: `hostx/${id}`, platform: "x", author, handle, date: `2026-10-30T1${id}:00:00.000Z`, text: `words of ${id} from ${handle}.`, ...o });
+ await mkdir(DIR, { recursive: true });
+ await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: "rec", title: "Record", provenance: { channelsDir: "../channels", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, postNarration: { engine: "kokoro", voice: "af_heart" } },
+ timeline: [
+ post("1", "savvy", "Madam Savvy", { narration: { script: "Savvy's line, read aloud." } }),
+ post("2", "savvy", "Madam Savvy", { narration: { script: "A first paragraph.\n\nA second one." } }),
+ post("3", "nobody", "No Body", { narration: { script: "Nobody's line." } }),
+ ],
+ }, null, 2));
+}
+const project = { id: "rec", dir: DIR };
+const manifest = async () => JSON.parse(await readFile(path.join(DIR, "video.manifest.json"), "utf8"));
+const item = async (id) => (await manifest()).timeline.find((e) => e.id === id);
+// The editor's two voice ops: each writes a voice to `out` (and to each part's), and says what it ran.
+const editor = () => {
+ const ops = [];
+ const ask = async (route, body, o = {}) => {
+ const op = route.split("/").at(-1);
+ ops.push({ op, ...body });
+ // The heavy slot's gate, then the engine: what the editor's job says while it runs.
+ o.onState?.({ jobId: `op-${ops.length}`, status: "queued", queue: { position: 2 }, tail: [] });
+ const gate = ["heavy: waiting for memory — 4100 MB available, the floor is 6000 MB", " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)"];
+ o.onState?.({ jobId: `op-${ops.length}`, status: "running", tail: gate });
+ o.onState?.({ jobId: `op-${ops.length}`, status: "running", tail: [...gate, "heavy: 6900 MB available after 40s — admitted"] });
+ const { seconds } = await measureTake(body.file);
+ await wavOf(body.out, op === "voice-convert" ? VOICE_A : VOICE_B, seconds, 0);
+ for (const p of body.parts ?? []) await wavOf(p.out, op === "voice-convert" ? VOICE_A : VOICE_B, (await measureTake(p.file)).seconds, 0);
+ return { jobId: `op-${ops.length}`, result: { engine: body.engine ?? (op === "voice-enhance" ? "deepfilternet" : "openvoice"), voice: body.voice, ...(body.pitch ? { pitch: body.pitch, semitones: body.semitones ?? 0 } : {}) } };
+ };
+ return { ops, ask, names: () => ops.map((o) => o.op) };
+};
+
+test("the heavy slot's wait is a state, not an error: queued, waiting for memory, the slot held, admitted", () => {
+ assert.deepEqual(opWaitOf({ status: "queued", queue: { position: 3 } }), { state: "queued", position: 3, line: null });
+ assert.equal(opWaitOf({ status: "queued" }).position, null);
+ // The gate's own lines (scripts/queue-lock.mjs), as the editor's job log carries them.
+ const first = [
+ "Running Seed-VC (v1, 22 kHz speech) behind the heavy slot (estimate 6500 MB)…",
+ "heavy: waiting for memory — 6706 MB available, 8000 MB promised to 2 running jobs, the floor is 6000 MB",
+ " running: lane-remote-archive (lane/remote-archive, pid 917913, 1500 MB) for 34m41s: playwright test",
+ " (HEAVY_MIN_FREE_MB=<MB> to change it; 0, or HEAVY=0, to skip it)",
+ ];
+ const mem = opWaitOf({ status: "running", tail: first });
+ assert.deepEqual([mem.state, /6706 MB available/.test(mem.line)], ["memory", true], "the continuation lines after it are still the wait");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: still waiting (memory, 30s; 6372 MB available)"] }).state, "memory");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: still waiting for memory (4200 MB available, 1m 10s)"] }).state, "memory");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: this machine has 3900 MB in all, under the 6000 MB floor — one heavy job at a time; waiting for: x"] }).state, "memory");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: still waiting (build, 1m00s; 9000 MB available)"] }).state, "slot");
+ assert.equal(opWaitOf({ status: "running", tail: ["heavy: waiting for a job that runs alone: a render"] }).state, "slot");
+ assert.equal(opWaitOf({ status: "running", tail: ["queue-lock: held for a render (umtool take p --id a, since 13:31) — waiting", " (render mode: `umtool render-mode off` ends it; RENDER_PRIORITY=0 to run anyway)"] }).state, "slot");
+ assert.equal(opWaitOf({ status: "running", tail: ["queue-lock: still waiting for the render (2m; umtool take p --id a)"] }).state, "slot");
+ // Admitted: the gate says so, or the engine has spoken since.
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: 7100 MB available after 1m10s — admitted"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: admitted beside 1 running job (1500 MB promised)"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "heavy: capped at 8192 MB (swap 2048 MB) in a scope of its own"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: ["queue-lock: the render let go after 3m — going on"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: [...first, "loading the model"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running", tail: ["Running Seed-VC behind the heavy slot (estimate 5000 MB)…"] }).state, "running");
+ assert.equal(opWaitOf({ status: "running" }).state, "running");
+});
+
+test("cut marks: a span a person set is kept inside the part, a bad one is not one; --trim-span says them", () => {
+ assert.deepEqual(explicitSpan({ from: 0.4, to: 2.1 }, 3), { from: 0.4, to: 2.1 });
+ assert.deepEqual(explicitSpan({ from: -1, to: 9 }, 3), { from: 0, to: 3 }, "clamped");
+ assert.equal(explicitSpan({ from: 1, to: 1.1 }, 3), null, "under 0.2 s");
+ assert.equal(explicitSpan(null, 3), null);
+ assert.equal(explicitSpan({ from: "a", to: 2 }, 3), null);
+ assert.equal(trimSpans([], 2), null);
+ assert.deepEqual(trimSpans(["0.4-3.1"], 1), [{ from: 0.4, to: 3.1 }]);
+ assert.deepEqual(trimSpans(["2=0.2-4"], 2), [null, { from: 0.2, to: 4 }]);
+ for (const bad of [["3=0-1"], ["1-1.1"], ["x"], ["1=0-1", "0-2"]]) assert.throws(() => trimSpans(bad, 2), /--trim-span/);
+});
+
+test("keepRecording with explicit spans: the part is cut at the marks, whatever the trim says", async () => {
+ const rec = path.join(ROOT, "spans.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6); // 3.2 s: 0.6 s of silence either side
+ const auto = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest() });
+ assert.ok(auto.take.seconds < 2.6, `auto: trimmed (${auto.take.seconds})`);
+ const marked = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest(), spans: [{ from: 1, to: 2 }] });
+ assert.ok(Math.abs(marked.take.seconds - 1) < 0.05, `the marks' second (${marked.take.seconds})`);
+ const off = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest(), trim: { on: false }, spans: [{ from: 0.5, to: 3.0 }] });
+ assert.ok(Math.abs(off.take.seconds - 2.5) < 0.05, "a mark over trim off");
+ const whole = await keepRecording(project, await item("p-3"), [{ file: rec }], { manifest: await manifest(), trim: { on: false }, spans: [null] });
+ assert.ok(whole.take.seconds > 3.1, "no mark, trim off: as recorded");
+});
+
+test("the chain into the scratch dir: no take; a step is not run again while what it was made from stands; Keep makes the takes from its files", async () => {
+ await cast(["project", "rec", "add", "madam-savvy", "--name", "Madam Savvy", "--handles", "savvy", "--voice", "orpheus:mia", "--convert-engine", "seed-vc", "--convert-pitch", "contour", "--convert-semitones", "2", "--direction", "higher, brisk, amused"]);
+ const rec = path.join(ROOT, "savvy.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ const ed = editor();
+ const stages = [];
+ const emit = (ev, f) => ev === "stage" && stages.push(`${f.stage}:${f.state}`);
+ const before = JSON.stringify((await item("p-1")).narration);
+ let r = await runPreview(project, await item("p-1"), [{ file: rec, text: "Savvy's line, read aloud." }], { ask: ed.ask, emit });
+ assert.deepEqual(ed.names(), ["voice-enhance", "voice-convert"]);
+ assert.equal(JSON.stringify((await item("p-1")).narration), before, "no take made");
+ assert.deepEqual(r.character, { id: "madam-savvy", name: "Madam Savvy", layer: "project" });
+ assert.equal(r.direction, "higher, brisk, amused");
+ assert.deepEqual(r.convert, { engine: "seed-vc", voice: "orpheus:mia", pitch: "contour", semitones: 2 });
+ assert.deepEqual([ed.ops[1].engine, ed.ops[1].voice, ed.ops[1].pitch, ed.ops[1].semitones], ["seed-vc", "orpheus:mia", "contour", 2], "the preset's convert, asked whole");
+ const dir = previewDirOf(DIR, await item("p-1"));
+ assert.equal(dir, path.join(DIR, "narration", ".record-preview", "1.operator"));
+ assert.equal(r.dir, dir);
+ for (const f of [r.raw, r.clean, r.filtered]) assert.ok(existsSync(f), f);
+ assert.equal(r.listen, r.filtered);
+ // Cleaned WHOLE (the part as recorded, 3.2 s), then cut: the convert was asked of the cut, cleaned read.
+ assert.ok(ed.ops[0].file.endsWith("p01.raw.wav"));
+ assert.ok(Math.abs((await measureTake(ed.ops[0].file)).seconds - 3.2) < 0.05);
+ assert.ok(ed.ops[1].file.endsWith("clean.wav"));
+ assert.ok((await measureTake(r.raw)).seconds < 2.6, "its edges trimmed");
+ // The wait at the heavy slot was a state on the way, never a failure.
+ assert.deepEqual(stages, ["decode:running", "clean:running", "clean:queued", "clean:memory", "clean:running", "clean:done", "trim:running", "trim:done", "convert:running", "convert:queued", "convert:memory", "convert:running", "convert:done", "done:done"]);
+ // What the page is told: the waveform, the auto trim's marks, both levels.
+ const v = previewView(await readPreview(DIR, await item("p-1")));
+ assert.equal(v.parts.length, 1);
+ assert.equal(v.parts[0].peaks.length, PREVIEW_PEAKS);
+ assert.ok(v.parts[0].auto.from > 0.3 && v.parts[0].auto.to < 2.9, JSON.stringify(v.parts[0].auto));
+ assert.deepEqual(v.parts[0].span, v.parts[0].auto);
+ assert.ok(Number.isFinite(v.raw.lufs) && Number.isFinite(v.filtered.lufs));
+ assert.deepEqual([v.filtered.pitch, v.filtered.semitones, v.cleaned], ["contour", 2, "done"]);
+ assert.equal("silences" in v.parts[0], false);
+ assert.equal(await previewFile(DIR, await item("p-1"), "filtered"), r.filtered);
+ assert.ok((await previewFile(DIR, await item("p-1"), "part", { n: 1 })).endsWith("p01.raw.wav"));
+
+ // The same again: nothing is asked.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask });
+ assert.equal(ed.ops.length, 2);
+ assert.deepEqual(r.cached, { clean: true, convert: true });
+ // Another pitch: the convert ALONE, on the cleaned sound already there.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, pitch: "source", semitones: -1 });
+ assert.deepEqual(ed.names(), ["voice-enhance", "voice-convert", "voice-convert"]);
+ assert.deepEqual([ed.ops[2].pitch, ed.ops[2].semitones, ed.ops[2].voice], ["source", -1, "orpheus:mia"]);
+ assert.deepEqual(r.cached, { clean: true, convert: false });
+ // A mark moved: re-cut and converted, never cleaned again.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, spans: [{ from: 1, to: 2.2 }] });
+ assert.deepEqual(ed.names().slice(3), ["voice-convert"]);
+ assert.deepEqual(r.spans, [{ from: 1, to: 2.2 }]);
+ assert.ok(Math.abs((await measureTake(r.raw)).seconds - 1.2) < 0.05);
+ // --out: the filtered read copied where asked.
+ const out = path.join(ROOT, "out", "savvy-filtered.wav");
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, spans: [{ from: 1, to: 2.2 }], out });
+ assert.equal(r.out, out);
+ assert.ok(existsSync(out));
+ assert.equal(ed.ops.length, 4, "a copy asks nothing");
+
+ // KEEP: three takes from the preview's files, the last picked, nothing asked of the editor; the scratch dir gone.
+ const k = await keepPreview(project, await item("p-1"));
+ assert.equal(ed.ops.length, 4);
+ assert.deepEqual(k.takes.map((t) => t.step), ["recorded", "cleaned", "converted to orpheus:mia (pitch: contour +2 st)"]);
+ assert.deepEqual(k.takes.map((t) => t.file), ["narration/posts/1/take-1.recorded-operator.wav", "narration/posts/1/take-2.enhance-default.wav", "narration/posts/1/take-3.convert-seed-vc.wav"]);
+ const n = (await item("p-1")).narration;
+ assert.equal(n.pick, 2);
+ assert.notEqual(n.approved, true, "awaiting approval");
+ assert.deepEqual(validatePostNarration(await item("p-1")), []);
+ assert.deepEqual(n.takes[0].source, { kind: "recorded", voice: "operator" });
+ assert.match(n.takes[0].note, /recorded for Madam Savvy/);
+ assert.deepEqual(n.takes[1].source, { kind: "take", from: "take-1.recorded-operator" });
+ assert.deepEqual([n.takes[1].steps[0].op, n.takes[1].steps[0].engine, n.takes[1].steps[0].job], ["enhance", "deepfilternet", "op-1"]);
+ assert.deepEqual(n.takes[2].source, { kind: "take", from: "take-2.enhance-default" });
+ assert.deepEqual([n.takes[2].voice, n.takes[2].steps[0].engine, n.takes[2].steps[0].voice, n.takes[2].steps[0].pitch, n.takes[2].steps[0].semitones], ["mia", "seed-vc", "orpheus:mia", "contour", 2]);
+ for (const t of n.takes) assert.ok(existsSync(path.join(DIR, t.file)), t.file);
+ assert.equal(k.disclosure, "Narration: voice converted to a synthetic voice (seed-vc · orpheus:mia)", "the disclosure line is what a recording made a read says");
+ assert.equal(existsSync(dir), false, "the scratch dir is removed on Keep");
+ await assert.rejects(keepPreview(project, await item("p-1")), /no preview to keep/);
+});
+
+test("the preset is honoured: enhance off, trim off; an editor with no enhance engine is said and gone without; no character converts nothing", async () => {
+ const rec = path.join(ROOT, "quiet.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ await cast(["project", "rec", "set", "madam-savvy", "--enhance", "off", "--trim", "off"]);
+ let ed = editor();
+ let r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask });
+ assert.deepEqual(ed.names(), ["voice-convert"]);
+ assert.match(r.notes[0], /not cleaned: madam-savvy's recorded preset says so/);
+ assert.equal(r.clean, null);
+ assert.ok((await measureTake(r.raw)).seconds > 3.1, "trim.on false: its edges as recorded");
+ assert.ok(ed.ops[0].file.endsWith("raw.wav"), "converted from the raw read");
+ let v = previewView(await readPreview(DIR, await item("p-1")));
+ assert.deepEqual(v.parts[0].auto, { from: 0, to: v.parts[0].seconds });
+ assert.deepEqual(v.trim, { on: false, padMs: null });
+ // The command over the preset, and a pad: the room kept either side.
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: ed.ask, trim: { on: true, padMs: 400 }, clean: true });
+ assert.deepEqual(ed.names(), ["voice-convert", "voice-enhance", "voice-convert"]);
+ const padded = (await measureTake(r.raw)).seconds;
+ assert.ok(padded > 2.6 && padded < 3.1, `the pad kept (${padded})`);
+ await discardPreview(DIR, await item("p-1"));
+ assert.equal(existsSync(previewDirOf(DIR, await item("p-1"))), false);
+ await cast(["project", "rec", "set", "madam-savvy", "--enhance", "on", "--trim", "on"]);
+ // No enhance engine: said, and the raw read converted.
+ ed = editor();
+ const noEnhance = async (route, body, o) => {
+ if (route.endsWith("voice-enhance")) throw Object.assign(new Error("the editor has no engine for /api/ops/voice-enhance yet (not installed: DeepFilterNet 3 is not installed)"), { name: "OpNotInstalled" });
+ return ed.ask(route, body, o);
+ };
+ r = await runPreview(project, await item("p-1"), [{ file: rec }], { ask: noEnhance });
+ assert.match(r.notes[0], /not cleaned: .*not installed.*archilyzer voice setup --engine deepfilternet/);
+ assert.deepEqual(ed.names(), ["voice-convert"]);
+ assert.ok(r.filtered && !r.clean);
+ const k = await keepPreview(project, await item("p-1"));
+ assert.deepEqual(k.takes.map((t) => t.step), ["recorded", "converted to orpheus:mia (pitch: contour +2 st)"]);
+ // p-3's author has no character (and there is no cast): cleaned, not converted -- the cleaned read is what to listen to.
+ ed = editor();
+ r = await runPreview(project, await item("p-3"), [{ file: rec }], { ask: ed.ask });
+ assert.deepEqual(ed.names(), ["voice-enhance"]);
+ assert.match(r.notes[0], /not converted: a convert needs a stock voice to convert to, and this post has no character with one/);
+ assert.equal(r.character, null);
+ assert.equal(r.listen, r.clean);
+ // A voice named for this read converts it all the same.
+ r = await runPreview(project, await item("p-3"), [{ file: rec }], { ask: ed.ask, voice: "kokoro:am_puck" });
+ assert.deepEqual([ed.names().at(-1), ed.ops.at(-1).voice], ["voice-convert", "kokoro:am_puck"]);
+ await assert.rejects(runPreview(project, await item("p-3"), [{ file: rec }], { ask: ed.ask, as: "ghost" }), /--as ghost: no such character/);
+ await discardPreview(DIR, await item("p-3"));
+});
+
+test("the record page's session: a parted read previewed part by part, kept from the terminal (the session over), or kept alone at its marks", async () => {
+ const e = await item("p-2");
+ const a = path.join(ROOT, "part-a.wav");
+ const b = path.join(ROOT, "part-b.wav");
+ await wavOf(a, VOICE_B, 1.5, 0.4);
+ await wavOf(b, VOICE_B, 1.0, 0.4);
+ await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" });
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" });
+ const { sessionParts } = await import("./recordSession.mjs");
+ const parts = await sessionParts(DIR, e);
+ const pre = await preparePreview(project, e, parts);
+ assert.deepEqual(pre.parts.map((p) => [p.n, p.text]), [[1, "A first paragraph."], [2, "A second one."]]);
+ const ed = editor();
+ const r = await runPreview(project, e, parts, { ask: ed.ask, spans: [null, { from: 0.3, to: 1.5 }] });
+ assert.deepEqual(ed.names(), ["voice-enhance", "voice-convert"]);
+ assert.equal(ed.ops[0].parts.length, 1, "the second part cleaned in the same job");
+ assert.equal(ed.ops[1].parts.length, 2, "each cut part converted beside the whole");
+ assert.deepEqual(r.spans[1], { from: 0.3, to: 1.5 });
+ // The CLI twin over the session: cached, so nothing is asked; --keep-preview makes parted takes.
+ let c = await posts(["narrate", "rec", "p-2", "--preview", "--trim-span", "2=0.3-1.5", "--json"], { ask: ed.ask });
+ assert.equal(c.code, 0, c.text());
+ assert.equal(ed.ops.length, 2);
+ assert.deepEqual(c.json().cached, { clean: true, convert: true });
+ c = await posts(["narrate", "rec", "p-2", "--keep-preview", "--json"]);
+ assert.equal(c.code, 0, c.text());
+ const n = (await item("p-2")).narration;
+ assert.deepEqual(n.takes.map((t) => t.parts.length), [2, 2, 2]);
+ assert.deepEqual(n.takes[2].parts.map((p) => p.file), ["narration/posts/2/take-3.convert-seed-vc.parts/p01.wav", "narration/posts/2/take-3.convert-seed-vc.parts/p02.wav"]);
+ for (const t of n.takes) for (const p of t.parts) assert.ok(existsSync(path.join(DIR, p.file)), p.file);
+ assert.ok(Math.abs(n.takes[0].parts[1].seconds - 1.2) < 0.02, "the second part at its marks");
+ assert.deepEqual(validatePostNarration(await item("p-2")), []);
+ assert.equal(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator")), false, "a session's preview kept: the session is over");
+ // finishSession with marks (Keep with no Filter): the recorded take alone, cut at them.
+ await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" });
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" });
+ const kept = await finishSession(project, await item("p-2"), { manifest: await manifest(), spans: [{ from: 0.5, to: 1.5 }, null] });
+ assert.ok(Math.abs(kept.take.parts[0].seconds - 1) < 0.02);
+ assert.equal(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator")), false);
+});
+
+test("the CLI twin: --recording <file> --preview prints the paths and makes no take; --events is one object a line; --discard-preview", async () => {
+ const rec = path.join(ROOT, "cli.wav");
+ await wavOf(rec, VOICE_B, 2, 0.6);
+ const ed = editor();
+ const takes = (await item("p-1")).narration.takes.length;
+ let c = await posts(["narrate", "rec", "p-1", "--recording", rec, "--preview", "--pitch", "source"], { ask: ed.ask });
+ assert.equal(c.code, 0, c.text());
+ assert.match(c.text(), /p-1: previewed as Madam Savvy -- NO TAKE MADE/);
+ assert.match(c.text(), /raw\s+.*narration\/\.record-preview\/1\.operator\/raw\.wav/);
+ assert.match(c.text(), /filtered\s+.*filtered\.wav \(seed-vc -> orpheus:mia, pitch: source \+2 st\)/);
+ assert.match(c.text(), /converting: waiting for memory \(the heavy slot admits it when there is room -- not an error\)/);
+ assert.match(c.text(), /keep it: umtool posts narrate rec p-1 --keep-preview/);
+ assert.equal((await item("p-1")).narration.takes.length, takes, "no take");
+ c = await posts(["narrate", "rec", "p-1", "--recording", rec, "--preview", "--as", "madam-savvy", "--pitch", "target", "--events"], { ask: ed.ask });
+ const evs = c.lines.map((l) => JSON.parse(l));
+ assert.deepEqual(evs.at(-1).ev, "result");
+ assert.ok(evs.at(-1).filtered.endsWith("filtered.wav"));
+ assert.ok(evs.some((x) => x.ev === "stage" && x.stage === "convert" && x.state === "memory"));
+ assert.equal(evs.at(-1).character.layer, "flag");
+ assert.equal(ed.ops.at(-1).semitones, undefined, "the target's own pitch takes no semitones");
+ c = await posts(["narrate", "rec", "p-1", "--recording", path.join(ROOT, "nope.wav"), "--preview"]);
+ assert.equal(c.code, 2);
+ c = await posts(["narrate", "rec", "p-3", "--preview"]);
+ assert.equal(c.code, 2);
+ assert.match(c.text(), /--preview takes --recording <file>, or the record page's session of p-3: nothing recorded yet/);
+ c = await posts(["narrate", "rec", "p-1", "--discard-preview"]);
+ assert.equal(c.code, 0);
+ assert.equal(existsSync(previewDirOf(DIR, await item("p-1"))), false);
+ c = await posts(["narrate", "rec", "p-1", "--keep-preview"]);
+ assert.notEqual(c.code, 0);
+ assert.match(c.text(), /no preview to keep/);
+});
+
+test("a preview is kept only for the recording it was made from: a part recorded again since the Filter is refused, nothing kept", async () => {
+ const e = await item("p-2");
+ const a = path.join(ROOT, "again-a.wav");
+ const b = path.join(ROOT, "again-b.wav");
+ await wavOf(a, VOICE_B, 1.5, 0.4);
+ await wavOf(b, VOICE_B, 1.0, 0.4);
+ await savePart(DIR, e, { n: 1, count: 2, text: "A first paragraph.", para: 0, bytes: await readFile(a), type: "audio/wav" });
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(b), type: "audio/wav" });
+ const { sessionParts } = await import("./recordSession.mjs");
+ const ed = editor();
+ await runPreview(project, e, await sessionParts(DIR, e), { ask: ed.ask, session: true });
+ const takes = (await item("p-2")).narration.takes.length;
+ // Part 2 recorded again (Space, with no Again): the session is another recording now.
+ await new Promise((res) => setTimeout(res, 20));
+ await savePart(DIR, e, { n: 2, count: 2, text: "A second one.", para: 1, bytes: await readFile(a), type: "audio/wav" });
+ await assert.rejects(keepPreview(project, await item("p-2"), { parts: await sessionParts(DIR, e) }), (err) => err.status === 409 && /preview is of an earlier recording/.test(err.message));
+ assert.equal((await item("p-2")).narration.takes.length, takes, "nothing kept");
+ assert.ok(existsSync(path.join(DIR, "narration", "posts", "2", ".recording-operator", "session.json")), "the new part is still there");
+ // The terminal's --keep-preview asks the same.
+ const c = await posts(["narrate", "rec", "p-2", "--keep-preview"]);
+ assert.notEqual(c.code, 0);
+ assert.match(c.text(), /preview is of an earlier recording/);
+ // The same recording: kept.
+ await runPreview(project, await item("p-2"), await sessionParts(DIR, e), { ask: ed.ask, session: true });
+ const k = await keepPreview(project, await item("p-2"), { parts: await sessionParts(DIR, e) });
+ assert.equal(k.session, true);
+ const { clearSession } = await import("./recordSession.mjs");
+ await clearSession(DIR, e);
+});
+
+test("an upload that is text (a playlist, a concat script) is refused before ffmpeg opens it; ffmpeg may open local files only", async () => {
+ const secret = path.join(ROOT, "secret.wav");
+ await wavOf(secret, VOICE_A, 1, 0);
+ const lists = {
+ "list.m3u8": `#EXTM3U\n#EXT-X-TARGETDURATION:10\n#EXTINF:10,\n${secret}\n#EXT-X-ENDLIST\n`,
+ "list.wav": `#EXTM3U\n#EXTINF:10,\nhttp://127.0.0.1:9/x.ts\n`,
+ "script.ffconcat": `ffconcat version 1.0\nfile '${secret}'\n`,
+ };
+ for (const [name, text] of Object.entries(lists)) {
+ const f = path.join(ROOT, name);
+ await writeFile(f, text);
+ assert.equal(await looksLikeText(f), true, name);
+ const out = path.join(ROOT, `${name}.out.wav`);
+ await assert.rejects(decodePart(f, out), (err) => err.status === 400 && /not a sound file: it is text/.test(err.message), name);
+ assert.equal(existsSync(out), false, `${name}: nothing decoded`);
+ await assert.rejects(keepRecording(project, await item("p-3"), [{ file: f }], { manifest: await manifest() }), /not a sound file/);
+ await assert.rejects(runPreview(project, await item("p-3"), [{ file: f }], { ask: editor().ask }), /not a sound file/);
+ }
+ assert.equal(await looksLikeText(secret), false, "a wav is binary");
+ const ok = await decodePart(secret, path.join(ROOT, "secret.out.wav"));
+ assert.ok(ok.seconds > 0.9);
+});
diff --git a/umtool/lib/report/recordSession.mjs b/umtool/lib/report/recordSession.mjs
@@ -45,7 +45,8 @@ async function writeSession(dir, doc) {
await rename(tmp, path.join(dir, "session.json"));
}
-const extOf = (type) => (/ogg/.test(type) ? "ogg" : /wav/.test(type) ? "wav" : /mp4|aac/.test(type) ? "m4a" : "webm");
+// A browser recording is webm or ogg; a sound file chosen for a part keeps what it is (ffmpeg reads it either way).
+const extOf = (type) => (/ogg/.test(type) ? "ogg" : /wav/.test(type) ? "wav" : /mp4|aac|m4a/.test(type) ? "m4a" : /mpeg|mp3/.test(type) ? "mp3" : /flac/.test(type) ? "flac" : "webm");
/**
* KEEP ONE PART: its bytes written (through a rename: never half a file), the
@@ -98,28 +99,45 @@ export async function partFile(projectDir, entry, n, label = "operator") {
}
/**
- * FINISH: every part of the post in -> one recorded take (keepRecording),
- * picked; the session cleared. Refused, naming the missing parts, otherwise.
- *
- * @param {{ id: string, dir: string }} project
- * @param {Record<string, any>} entry
- * @param {{ label?: string, manifest?: Record<string, any> | null, script?: string | null }} [o]
+ * The session's parts in reading order, as keepRecording and the preview take them (`[{ file, text, para }]`, the
+ * files absolute). Refused, naming the missing parts, when the post's read is not all in.
*/
-export async function finishSession(project, entry, { label = "operator", manifest = null, script = null } = {}) {
- const doc = await readSession(project.dir, entry, label);
+export async function sessionParts(projectDir, entry, label = "operator") {
+ const doc = await readSession(projectDir, entry, label);
const count = doc.count ?? 0;
const missing = [];
for (let n = 1; n <= count; n += 1) if (!doc.parts[String(n)]) missing.push(n);
if (!count || missing.length) throw Object.assign(new Error(count ? `parts ${missing.join(", ")} of ${count} are not recorded yet` : "nothing recorded yet"), { status: 400 });
- const dir = sessionDirOf(project.dir, entry, label);
+ const dir = sessionDirOf(projectDir, entry, label);
const parts = [];
for (let n = 1; n <= count; n += 1) {
const p = doc.parts[String(n)];
parts.push({ file: path.join(dir, p.file), text: p.text, para: p.para });
}
+ return parts;
+}
+
+/** Remove the session (its parts are a take now, or were given up). */
+export async function clearSession(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ await rm(sessionDirOf(projectDir, entry, label), { recursive: true, force: true });
+}
+
+/**
+ * FINISH: every part of the post in -> one recorded take (keepRecording),
+ * picked; the session cleared. Refused, naming the missing parts, otherwise.
+ * `spans`: the cut marks a person set on the record page, per part (`[{ from, to } | null]`); a part without one is
+ * trimmed as its character's recorded preset says.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} entry
+ * @param {{ label?: string, manifest?: Record<string, any> | null, script?: string | null, spans?: Array<{ from: number, to: number } | null> | null }} [o]
+ */
+export async function finishSession(project, entry, { label = "operator", manifest = null, script = null, spans = null } = {}) {
+ const parts = await sessionParts(project.dir, entry, label);
// Its character's recorded preset says whether its edges are trimmed, and the room kept (characterLayers.mjs).
const { recordedTrimFor } = await import("./characterLayers.mjs");
- const kept = await keepRecording(project, entry, parts, { label, manifest, script, trim: await recordedTrimFor(project.dir, entry) });
- await rm(dir, { recursive: true, force: true });
+ const kept = await keepRecording(project, entry, parts, { label, manifest, script, trim: await recordedTrimFor(project.dir, entry), spans });
+ await clearSession(project.dir, entry, label);
return kept;
}
diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs
@@ -264,7 +264,8 @@ export function opResultIn(lines) {
* `body` (its `out` the absolute file the result is written to), then its job
* followed to the end. Returns `{ jobId, result }` (result: the job's result
* line, null when the op writes none and `out` is given). An op the editor
- * has no engine for throws OpNotInstalled.
+ * has no engine for throws OpNotInstalled. `onState({ jobId, status, queue, tail })` is told each poll of a job that
+ * is queued or running (read it with `opWaitOf`).
*/
/** An op that did not finish by its deadline (`askEditorOp`'s `deadlineMs`): its job may still be in the editor's queue. */
export class OpDeadline extends Error {
@@ -275,7 +276,49 @@ export class OpDeadline extends Error {
}
}
-export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {}, deadlineMs = null } = {}) {
+/** How many of a job's last lines a caller that watches its state is handed (`askEditorOp`'s `onState`). */
+export const STATE_TAIL_LINES = 6;
+
+/**
+ * WHERE A QUEUED OR RUNNING EDITOR JOB IS, from one poll of it (`{ status, queue?, tail? }`): `queued` (behind other
+ * jobs of its queue: `position`), `memory` / `slot` (it runs, and its engine waits at the machine's heavy slot), else
+ * `running`. THE GATE WORKING, not an error. The gate speaks in the job's log (scripts/queue-lock.mjs, its stderr):
+ *
+ * heavy: waiting for memory — 6706 MB available, 8000 MB promised to 2 running jobs, the floor is 6000 MB
+ * running: … (indented lines continue the one above)
+ * (HEAVY_MIN_FREE_MB=<MB> to change it; …)
+ * heavy: still waiting (memory, 30s; 6372 MB available) memory | build | exclusive
+ * heavy: waiting for the build slot — … · heavy: waiting for a job that runs alone: …
+ * queue-lock: held for a render (…) — waiting · queue-lock: still waiting for the render (…)
+ * heavy: 7000 MB available after 1m10s — admitted · heavy: admitted beside … · heavy: capped at … · … let go after …
+ *
+ * The LAST gate line of the tail decides: a wait that has not been answered by an admission (or by a line of the
+ * engine's after it) is where the job is. Pure.
+ */
+export function opWaitOf({ status, queue = null, tail = [] } = {}) {
+ if (status === "queued") return { state: "queued", position: Number(queue?.position) > 0 ? Number(queue.position) : null, line: null };
+ const lines = (tail ?? []).map((l) => String(l)).filter((l) => l.trim());
+ const isGate = (l) => /\b(heavy|queue-lock): /.test(l);
+ const continues = (l) => /^\s+\S/.test(l) || /^\(?(running: |\(HEAVY_MIN_FREE_MB|\(render mode:|\(heavy jobs)/.test(l.trim());
+ let at = -1;
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
+ if (isGate(lines[i])) {
+ at = i;
+ break;
+ }
+ }
+ const running = { state: "running", position: null, line: lines.at(-1)?.trim() ?? null };
+ if (at < 0) return running;
+ const line = lines[at].trim();
+ // Something else was said after it (the engine's own output): it is in.
+ if (lines.slice(at + 1).some((l) => !continues(l))) return running;
+ if (/admitted|available after|capped at|let go after|running uncapped|not waiting for it|is not checked/.test(line)) return running;
+ if (/waiting for memory|still waiting \(memory|under the \d+ MB floor/.test(line)) return { state: "memory", position: null, line };
+ if (/waiting|held for a render/.test(line)) return { state: "slot", position: null, line };
+ return running;
+}
+
+export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {}, deadlineMs = null, onState = null } = {}) {
const started = Date.now();
const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" };
const reach = async (url, init) => {
@@ -299,7 +342,8 @@ export async function askEditorOp(route, body, { editor = editorFromEnv(), emit
for (;;) {
let r;
try {
- r = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}`, { headers });
+ // A caller that shows where the job is (`onState`) is handed its last lines too: the heavy slot's gate speaks there.
+ r = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}${onState ? `?tail=${STATE_TAIL_LINES}` : ""}`, { headers });
} catch (err) {
failures += 1;
if (failures >= MAX_POLL_FAILURES) throw new Error(`lost contact with the editor at ${editor.url} while job ${jobId} ran (${err?.message ?? err}); it may still be running there`);
@@ -313,6 +357,7 @@ export async function askEditorOp(route, body, { editor = editorFromEnv(), emit
if (status !== last) emit("note", { message: ` editor job ${jobId}: ${status}` });
last = status;
const q = st.job?.queue;
+ if (onState && (status === "queued" || status === "running")) onState({ jobId, status, queue: q ?? null, tail: Array.isArray(st.tail) ? st.tail : [] });
if (status === "queued" && q && Number(q.position) > 0) {
const line = `queued — position ${q.position}${Number(q.queued) > 0 ? ` of ${q.queued}` : ""}`;
if (line !== place) emit("note", { message: ` editor job ${jobId}: ${line}` });