commit 9f1457fbe5f815b199234e458a143aedbe452025
parent bb1762931273bdfc882bd5e78cb8c54682d20334
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 00:07:01 -0500
umtool: THE RECORDING SESSION -- /projects/<p>/narration/record walks the cut's posts, a teleprompter in parts, each part on disk as it is kept, the recorded take made and picked
The operator reads the cut aloud (3 Nov: "I need to do a dramatic reading of this
starting tomorrow"). The session page walks the post items in order -- a jump list
(recorded / placeholder, n of N), the post's card and attachment, the script as a
teleprompter in its PARTS (the placeholder's parts.json, else scriptParts), the part
being read large -- with the mic (remembered), a level meter and a count-in toggle;
Space records / stops, r redoes the part, Enter goes on, n / p walk the posts; Play it
back, Play the placeholder. Every part is written the moment it is stopped
(lib/report/recordSession.mjs: narration/posts/<postId>/.recording-<label>/, a reload
resumes at the first part not kept; a re-split script starts over); the last part in,
the parts become the post's recorded take (trimmed, joined with the parts' pauses,
levelled to the placeholder's) and it is picked. POST/GET
/api/report/post-narration/record. useMic is its own module (the bench uses it too).
The Cut tab links it (Record the narration). Unit tests for the store; e2e: two parts,
a reload, a redo, the take kept and picked, on to the next post.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
14 files changed, 913 insertions(+), 88 deletions(-)
diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts
@@ -0,0 +1,104 @@
+import { readFile, stat } from "node:fs/promises";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
+import { discardPart, finishSession, partFile, readSession, savePart } from "@/lib/report/recordSession.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE RECORDING SESSION (lib/report/recordSession.mjs; /projects/<p>/narration/record):
+// a person's read of one post item, part by part, each part on disk the moment it is kept.
+//
+// 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 {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
+
+const noStore = { "cache-control": "no-store" };
+type Entry = Record<string, unknown> & { id: string; type?: string };
+
+const fail = (e: unknown) => {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ const status = (e as { status?: number }).status ?? 400;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+};
+
+function itemOf(manifest: Record<string, unknown>, id: string): Entry | null {
+ const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[];
+ 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" };
+
+export async function GET(request: Request) {
+ const q = new URL(request.url).searchParams;
+ const r = await resolveReport(q.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const e = itemOf(r.manifest as Record<string, unknown>, q.get("id") ?? "");
+ if (!e) return Response.json({ error: `no post item ${q.get("id")}` }, { status: 404 });
+ const label = q.get("label") ?? "operator";
+ try {
+ const n = q.get("n");
+ if (n !== null) {
+ const f = await partFile(r.project.dir, e, Number(n), label);
+ if (!f || !(await stat(f).catch(() => null))) return new Response("no such part", { status: 404 });
+ const body = await readFile(f);
+ return new Response(new Uint8Array(body), { headers: { "content-type": TYPES[f.split(".").pop() ?? ""] ?? "application/octet-stream", ...noStore } });
+ }
+ return Response.json({ ok: true, session: await readSession(r.project.dir, e, label) }, { headers: noStore });
+ } catch (err) {
+ return fail(err);
+ }
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/post-narration/record");
+ if (refused) return refused;
+ if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) {
+ let form: FormData;
+ try {
+ form = await request.formData();
+ } catch {
+ return Response.json({ error: "expected a multipart part" }, { status: 400 });
+ }
+ const r = await resolveReport(String(form.get("project") ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const e = itemOf(r.manifest as Record<string, unknown>, String(form.get("id") ?? ""));
+ 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 });
+ 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(),
+ });
+ return Response.json({ ok: true, session }, { headers: noStore });
+ } catch (err) {
+ return fail(err);
+ }
+ }
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON or a part" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const e = itemOf(r.manifest as Record<string, unknown>, String(body.id ?? ""));
+ if (!e) return Response.json({ error: `no post item ${String(body.id)}` }, { status: 404 });
+ 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 });
+ 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 });
+ 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 });
+ } catch (err) {
+ return fail(err);
+ }
+}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -10,6 +10,7 @@ import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postN
import { projectFileMedia } from "./bench/benchMedia";
import { usePeaks } from "./bench/usePeaks";
import { useNotes } from "@/lib/annotations/useNotes";
+import { MIC_KEY, ls, useMic } from "./useMic";
import type { PostPlan } from "./review/PostItemPlayer";
// ---------------------------------------------------------------------------
@@ -39,94 +40,7 @@ type Entry = Record<string, unknown> & { id: string; narration?: Narration; medi
type Progress = { items: Array<{ id: string; n: number; plays: string; approved: boolean }>; counts: { posts: number; recorded: number; synthesized: number; none: number; approved: number } };
const fileUrl = (project: string, rel: string) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`;
-const MIC_KEY = "umtool.post-narration.mic";
const LABEL_KEY = "umtool.post-narration.label";
-const ls = {
- get: (k: string) => {
- try {
- return window.localStorage.getItem(k);
- } catch {
- return null;
- }
- },
- set: (k: string, v: string) => {
- try {
- window.localStorage.setItem(k, v);
- } catch {
- // private mode: not remembered
- }
- },
-};
-
-/** The microphone: its devices, the one chosen (remembered), a level, a recorder. */
-function useMic() {
- const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
- const [device, setDevice] = useState<string>("");
- const [level, setLevel] = useState(0);
- const [error, setError] = useState<string | null>(null);
- const stream = useRef<MediaStream | null>(null);
- const rec = useRef<MediaRecorder | null>(null);
- const chunks = useRef<Blob[]>([]);
- const raf = useRef(0);
- const ctx = useRef<AudioContext | null>(null);
- const open = useCallback(async (id?: string) => {
- setError(null);
- try {
- stream.current?.getTracks().forEach((t) => t.stop());
- const s = await navigator.mediaDevices.getUserMedia({ audio: id ? { deviceId: { exact: id }, echoCancellation: false, noiseSuppression: false, autoGainControl: false } : { echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
- stream.current = s;
- const list = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput");
- setDevices(list);
- const now = s.getAudioTracks()[0]?.getSettings().deviceId ?? id ?? "";
- setDevice(now);
- if (now) ls.set(MIC_KEY, now);
- ctx.current ??= new AudioContext();
- const an = ctx.current.createAnalyser();
- an.fftSize = 1024;
- ctx.current.createMediaStreamSource(s).connect(an);
- const buf = new Float32Array(an.fftSize);
- cancelAnimationFrame(raf.current);
- const tick = () => {
- an.getFloatTimeDomainData(buf);
- let acc = 0;
- for (const v of buf) acc += v * v;
- setLevel(Math.min(1, Math.sqrt(acc / buf.length) * 4));
- raf.current = requestAnimationFrame(tick);
- };
- tick();
- return s;
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- return null;
- }
- }, []);
- useEffect(() => () => {
- cancelAnimationFrame(raf.current);
- stream.current?.getTracks().forEach((t) => t.stop());
- }, []);
- const start = useCallback(async () => {
- const s = stream.current ?? (await open(ls.get(MIC_KEY) ?? undefined));
- if (!s) return false;
- chunks.current = [];
- const type = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/webm"].find((t) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(t));
- const r = new MediaRecorder(s, type ? { mimeType: type } : undefined);
- r.ondataavailable = (ev) => ev.data.size && chunks.current.push(ev.data);
- r.start(250);
- rec.current = r;
- return true;
- }, [open]);
- const stop = useCallback(
- () =>
- new Promise<Blob | null>((resolve) => {
- const r = rec.current;
- if (!r || r.state === "inactive") return resolve(null);
- r.onstop = () => resolve(new Blob(chunks.current, { type: r.mimeType || "audio/webm" }));
- r.stop();
- }),
- [],
- );
- return { devices, device, level, error, open, start, stop };
-}
export default function PostNarrationPanel({
project, entry, token, plan, render, onEntry, s, setS, setPlaying, prev, next, fromPlay,
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -10,6 +10,7 @@ import SweepProject from "./SweepProject";
import TakesPage from "./TakesPage";
import TakesComparePage from "./TakesComparePage";
import NarrationPage from "./NarrationPage";
+import RecordPage from "./RecordPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
import PlayCutPage from "./PlayCutPage";
@@ -81,6 +82,8 @@ export default async function ProjectView({
// `/browse/<project>/narration` -- the narration script, card by card,
// approved / edited / rejected before synthesis.
if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />;
+ // `/projects/<project>/narration/record` -- the recording session: the cut's posts read aloud, part by part.
+ if (rest.length === 2 && rest[0] === "narration" && rest[1] === "record") return <RecordPage project={project} search={search} />;
// `/browse/<project>/review` -- every drafted field, approved / rejected
// before a final build, and the alternatives a draft task kept.
if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />;
diff --git a/umtool/components/projects/RecordPage.tsx b/umtool/components/projects/RecordPage.tsx
@@ -0,0 +1,69 @@
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { notFound } from "next/navigation";
+import AppShell from "@/components/shell/AppShell";
+import RecordSession, { type RecordItem } from "./RecordSession";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { projectHref } from "@/lib/hrefs";
+import { deckGeometry, deckOn } from "umtool-report-to-video/deck";
+import { draftScript, pickedTake, takeSourceOf } from "umtool-report-to-video/post-narration";
+import { normalizeParts, partsFileOf } from "@/lib/report/postNarrationCli.mjs";
+import { avatarEntryOf } from "umtool-report-to-video/post-avatars";
+import type { ProjectRef } from "@/lib/project-types";
+
+// THE RECORDING SESSION (operator, 3 Nov: "I need to do a dramatic reading of
+// this starting tomorrow"): /projects/<p>/narration/record walks the cut's
+// post items in order -- each post's card and attachment, its SCRIPT as a
+// teleprompter in its PARTS (the placeholder take's parts.json when there is
+// one, else the script split the same way), recorded part by part, every part
+// on disk as soon as it is kept (lib/report/recordSession.mjs), the post's
+// recorded take made and picked when the last part is in.
+
+type Take = { file: string; engine?: string; voice?: string; seconds: number; parts?: unknown; source?: { kind?: string } };
+type Entry = Record<string, unknown> & { id: string; type?: string; text?: string; author?: string; handle?: string; date?: string; media?: Array<{ src: string; kind: string }>; narration?: { script?: string; takes?: Take[] } };
+
+export default async function RecordPage({ project, search = {} }: { project: ProjectRef; search?: Record<string, string | undefined> }) {
+ const m = (await readManifest(project.dir)) as Record<string, unknown> | null;
+ if (!m) notFound();
+ const render = (m.render ?? {}) as Record<string, unknown>;
+ const posts = ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).filter((e) => e?.type === "post");
+ if (!posts.length) notFound();
+ const items: RecordItem[] = [];
+ for (const [i, e] of posts.entries()) {
+ const takes = e.narration?.takes ?? [];
+ const picked = pickedTake(e) as (Take & { index: number }) | null;
+ // The placeholder: the newest synthesized take (its parts the teleprompter's).
+ const placeholder = [...takes].reverse().find((t) => (takeSourceOf(t) as { kind: string }).kind === "tts") ?? null;
+ let parts = placeholder ? normalizeParts(placeholder.parts) : null;
+ if (placeholder && !parts) {
+ parts = normalizeParts(await readFile(path.join(project.dir, ...partsFileOf(placeholder.file).split("/")), "utf8").then((t) => JSON.parse(t), () => null));
+ }
+ const recorded = takes.some((t) => (takeSourceOf(t) as { kind: string }).kind === "recorded");
+ const av = e.handle ? avatarEntryOf(m, e.handle) : null;
+ items.push({
+ id: e.id, n: i + 1, author: String(e.author ?? ""), handle: String(e.handle ?? ""), date: String(e.date ?? ""),
+ text: String(e.text ?? ""),
+ script: String(e.narration?.script ?? draftScript(e.text ?? "").script),
+ plays: !picked ? "none" : (takeSourceOf(picked) as { kind: string }).kind === "recorded" ? "recorded" : "placeholder",
+ recorded,
+ placeholder: placeholder ? { file: placeholder.file, seconds: placeholder.seconds, parts: (parts ?? []).map((p) => ({ n: p.n, para: p.para ?? 0, text: p.text ?? "", start: p.start, seconds: p.seconds, ...(p.file ? { file: p.file } : {}) })) } : null,
+ media: (e.media ?? []).slice(0, 1).map((x) => ({ src: x.src, kind: x.kind }))[0] ?? null,
+ avatar: av ? String((av[1] as { src?: string }).src ?? "") || null : null,
+ });
+ }
+ const box = deckOn(render) ? deckGeometry(render).footage : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) };
+ const want = search.post ? items.findIndex((x) => x.id === search.post) : -1;
+ const start = want >= 0 ? want : Math.max(0, items.findIndex((x) => !x.recorded));
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="projects"
+ crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id), label: project.name }, { label: "record the narration" }]}
+ note={`${items.filter((x) => x.recorded).length} of ${items.length} posts recorded`}
+ />
+ <main className="deck-main flex-1 overflow-auto p-4">
+ <RecordSession project={project.id} items={items} start={start} box={{ width: box.width, height: box.height }} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx
@@ -0,0 +1,398 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { postBenchHref } from "@/lib/hrefs";
+import { scriptParts } from "umtool-report-to-video/post-narration";
+import { MIC_KEY, ls, useMic } from "./useMic";
+
+// ---------------------------------------------------------------------------
+// THE RECORDING SESSION, the client half (RecordPage.tsx): one post at a time,
+// in the cut's order -- its card and attachment, the script as a teleprompter
+// in its parts, the current part large -- recorded PART BY PART:
+//
+// Space Record / Stop (a count-in first, when it is on)
+// r Redo the current part
+// Enter the next part (or, the post done, the next post)
+// n / p the next / previous post
+//
+// Each part is uploaded the moment it is stopped (POST /api/report/post-
+// narration/record) -- on disk, so a crash loses at most the part being read
+// 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.
+// ---------------------------------------------------------------------------
+
+type Part = { n: number; para: number; text: string; start?: number; seconds?: number; file?: string };
+export type RecordItem = {
+ id: string;
+ n: number;
+ author: string;
+ handle: string;
+ date: string;
+ text: string;
+ script: string;
+ plays: "recorded" | "placeholder" | "none";
+ recorded: boolean;
+ placeholder: { file: string; seconds: number; parts: Part[] } | null;
+ media: { src: string; kind: string } | null;
+ avatar: string | null;
+};
+type Session = { count: number | null; parts: Record<string, { file: string; text: string; at: string }> };
+
+const COUNT_KEY = "umtool.record.count-in";
+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)}`;
+
+export default function RecordSession({ project, items: initial, start, box }: { project: string; items: RecordItem[]; start: number; box: { width: number; height: number } }) {
+ const [items, setItems] = useState(initial);
+ const [at, setAt] = useState(start);
+ const item = items[at];
+ const parts: Part[] = useMemo(() => {
+ const ph = item.placeholder?.parts ?? [];
+ return ph.length ? ph : scriptParts(item.script).map((p) => ({ n: p.n, para: p.para, text: p.text }));
+ }, [item]);
+ const [session, setSession] = useState<Session>({ count: null, parts: {} });
+ const [cur, setCur] = useState(0);
+ const [phase, setPhase] = useState<"idle" | "count" | "recording" | "saving" | "finishing">("idle");
+ const [count, setCount] = useState(0);
+ const [countIn, setCountIn] = useState(true);
+ const [status, setStatus] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const mic = useMic();
+ const kept = (n: number) => !!session.parts[String(n)] && session.count === parts.length;
+
+ useEffect(() => setCountIn(ls.get(COUNT_KEY) !== "0"), []);
+ // 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" });
+ const j = (await r.json().catch(() => ({}))) as { session?: Session };
+ const s = j.session ?? { count: null, parts: {} };
+ setSession(s);
+ const firstOpen = parts.findIndex((p) => !(s.parts[String(p.n)] && s.count === parts.length));
+ setCur(firstOpen < 0 ? Math.max(0, parts.length - 1) : firstOpen);
+ }, [project, item.id, parts]);
+ useEffect(() => {
+ setStatus(null);
+ setError(null);
+ void loadSession();
+ try {
+ window.history.replaceState(null, "", `?post=${enc(item.id)}`);
+ } catch {
+ // not in a browser history
+ }
+ }, [loadSession, item.id]);
+
+ const done = parts.length > 0 && parts.every((p) => kept(p.n));
+
+ const finish = useCallback(async () => {
+ setPhase("finishing");
+ const r = await fetch("/api/report/post-narration/record", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "finish", id: item.id, script: item.script }) });
+ const j = (await r.json().catch(() => ({}))) as { take?: { file: string; seconds: number }; error?: string };
+ setPhase("idle");
+ if (!r.ok || !j.take) {
+ setError(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setItems((xs) => xs.map((x) => (x.id === item.id ? { ...x, recorded: true, plays: "recorded" } : x)));
+ setSession({ count: null, parts: {} });
+ setStatus(`kept: ${j.take.file.split("/").pop()} (${j.take.seconds.toFixed(1)} s), picked — Enter for the next post`);
+ }, [project, item.id, item.script]);
+
+ const record = useCallback(async () => {
+ if (phase !== "idle" || !parts.length) return;
+ setError(null);
+ if (countIn) {
+ setPhase("count");
+ for (const c of [3, 2, 1]) {
+ setCount(c);
+ await new Promise((res) => setTimeout(res, 650));
+ }
+ setCount(0);
+ }
+ if (!(await mic.start())) {
+ setPhase("idle");
+ setError(mic.error ?? "the microphone did not open");
+ return;
+ }
+ setPhase("recording");
+ }, [phase, parts.length, countIn, mic]);
+
+ const stop = useCallback(async () => {
+ if (phase !== "recording") return;
+ const blob = await mic.stop();
+ if (!blob || !blob.size) {
+ setPhase("idle");
+ return;
+ }
+ 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", blob, `p${p.n}.${/ogg/.test(blob.type) ? "ogg" : "webm"}`);
+ const r = await fetch("/api/report/post-narration/record", { method: "POST", body: fd });
+ const j = (await r.json().catch(() => ({}))) as { session?: Session; error?: string };
+ setPhase("idle");
+ if (!r.ok || !j.session) {
+ setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`} — record it again`);
+ return;
+ }
+ 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]);
+
+ const redo = useCallback(async () => {
+ if (phase !== "idle") return;
+ const p = parts[cur];
+ if (p && kept(p.n)) {
+ const r = await fetch("/api/report/post-narration/record", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "discard", id: item.id, n: p.n }) });
+ const j = (await r.json().catch(() => ({}))) as { session?: Session };
+ if (j.session) setSession(j.session);
+ }
+ await record();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [phase, parts, cur, project, item.id, record, session]);
+
+ const go = useCallback((k: number) => {
+ if (phase !== "idle") return;
+ setAt((x) => Math.max(0, Math.min(items.length - 1, x + k)));
+ }, [phase, items.length]);
+
+ // The keys of a reading session.
+ useEffect(() => {
+ const onKey = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (tgt?.closest("input, textarea, select")) return;
+ if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
+ if (ev.key === " ") {
+ ev.preventDefault();
+ if (phase === "recording") void stop();
+ else void record();
+ } else if (ev.key === "r") {
+ ev.preventDefault();
+ void redo();
+ } else if (ev.key === "Enter") {
+ ev.preventDefault();
+ 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]);
+
+ // 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 a = player.current;
+ if (!a) return;
+ a.src = src;
+ a.currentTime = 0;
+ const go2 = () => {
+ try {
+ a.currentTime = from;
+ } catch {
+ // seeks once it can
+ }
+ stopAt.current = seconds ? from + seconds : null;
+ void a.play().catch(() => {});
+ };
+ if (a.readyState >= 1) go2();
+ else a.addEventListener("loadedmetadata", go2, { once: true });
+ };
+ const playPlaceholderPart = (p: Part) => {
+ const ph = item.placeholder;
+ if (!ph) return;
+ if (p.file) play(fileUrl(project, p.file));
+ else if (typeof p.start === "number") play(fileUrl(project, ph.file), p.start, p.seconds ?? null);
+ else play(fileUrl(project, ph.file));
+ };
+
+ const recordedCount = items.filter((x) => x.recorded).length;
+ const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
+ const scale = 0.42;
+
+ return (
+ <div className="mx-auto grid max-w-[1500px] grid-cols-1 gap-4 min-[1100px]:grid-cols-[260px_minmax(0,1fr)]" data-record-session={item.id} data-record-phase={phase} data-record-part={parts[cur]?.n ?? 0}>
+ {/* The jump list: every post, recorded or on its placeholder. */}
+ <nav className="max-h-[80vh] overflow-auto rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12px]" data-record-list="">
+ <div className="micro mb-1" data-record-progress={recordedCount}>
+ recorded {recordedCount} of {items.length}
+ </div>
+ <ol className="m-0 list-none space-y-0.5 p-0">
+ {items.map((x, i) => (
+ <li key={x.id}>
+ <button
+ type="button"
+ onClick={() => phase === "idle" && setAt(i)}
+ className={cn("flex w-full items-center gap-1.5 rounded px-1.5 py-0.5 text-left", i === at ? "bg-[var(--color-sel)]/20" : "hover:bg-white/5")}
+ data-record-jump={x.id}
+ data-record-state={x.recorded ? "recorded" : x.placeholder ? "placeholder" : "none"}
+ >
+ <span className={cn("inline-block h-2 w-2 shrink-0 rounded-full", x.recorded ? "bg-emerald-500" : x.placeholder ? "bg-amber-400" : "bg-white/20")} />
+ <span className="font-mono tabular-nums">{x.n}</span>
+ <span className="truncate text-text-2">{x.date.slice(5, 10)} {x.text.replace(/\s+/g, " ").slice(0, 40)}</span>
+ </button>
+ </li>
+ ))}
+ </ol>
+ </nav>
+
+ <section className="min-w-0 space-y-3">
+ <div className="flex flex-wrap items-center gap-2 text-[12.5px]">
+ <button type="button" className={btn} disabled={at === 0 || phase !== "idle"} onClick={() => go(-1)} data-record-prev="">
+ ‹ P
+ </button>
+ <span className="font-mono">
+ post {item.n} of {items.length}
+ </span>
+ <button type="button" className={btn} disabled={at === items.length - 1 || phase !== "idle"} onClick={() => go(1)} data-record-next="">
+ N ›
+ </button>
+ <span className={cn("rounded px-1.5", item.recorded ? "bg-emerald-500/20" : "bg-amber-400/20")} data-record-item-state={item.recorded ? "recorded" : "placeholder"}>
+ {item.recorded ? "recorded" : item.placeholder ? "on its placeholder" : "no take yet"}
+ </span>
+ <a href={postBenchHref(project, item.id)} className="ink-link ml-auto">
+ its bench ›
+ </a>
+ </div>
+
+ {/* The post: its card (the render's own page) and its attachment. */}
+ <div className="flex flex-wrap items-start gap-3">
+ <div className="relative overflow-hidden rounded border border-seam bg-black" style={{ width: box.width * scale, height: box.height * scale }}>
+ <iframe
+ title={`post ${item.id}`}
+ src={`/api/report/post-item?project=${enc(project)}&id=${enc(item.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}`}
+ className="absolute left-0 top-0 border-0"
+ style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}
+ data-record-card=""
+ />
+ </div>
+ {item.media && (
+ <div className="w-56" data-record-media={item.media.kind}>
+ {item.media.kind === "image" ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={postFileUrl(project, item.media.src)} alt="" className="w-full rounded" />
+ ) : (
+ <video src={postFileUrl(project, item.media.src)} muted controls preload="metadata" className="w-full rounded" />
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* The mic. */}
+ <div className="flex flex-wrap items-center gap-2 text-[12.5px]">
+ <select value={mic.device} onChange={(e) => void mic.open(e.target.value)} onFocus={() => !mic.devices.length && void mic.open(ls.get(MIC_KEY) ?? undefined)} aria-label="microphone" data-record-mic="">
+ {!mic.devices.length && <option value="">microphone…</option>}
+ {mic.devices.map((d) => (
+ <option key={d.deviceId} value={d.deviceId}>
+ {d.label || d.deviceId.slice(0, 8)}
+ </option>
+ ))}
+ </select>
+ <div className="h-2.5 w-40 overflow-hidden rounded bg-black/40" aria-label="level" data-record-level={Math.round(mic.level * 100)}>
+ <div className={cn("h-full", mic.level > 0.85 ? "bg-red-500" : "bg-emerald-500")} style={{ width: `${mic.level * 100}%` }} />
+ </div>
+ <label className="flex items-center gap-1">
+ <input
+ type="checkbox"
+ checked={countIn}
+ onChange={(e) => {
+ setCountIn(e.target.checked);
+ ls.set(COUNT_KEY, e.target.checked ? "1" : "0");
+ }}
+ data-record-count-in=""
+ />
+ count-in
+ </label>
+ <span className="text-text-2">Space record / stop · r redo the part · Enter next part · n / p next / previous post</span>
+ </div>
+
+ {/* The teleprompter: every part, the current one large. */}
+ <ol className="m-0 list-none space-y-2 p-0" data-record-teleprompter="">
+ {parts.map((p, i) => (
+ <li
+ key={p.n}
+ className={cn(
+ "rounded border-l-4 px-3 py-2 leading-snug",
+ i === cur ? "border-amber-400 bg-amber-400/10 text-[26px] text-text" : "border-transparent text-[15px] text-text-2",
+ kept(p.n) && i !== cur && "border-emerald-500/70",
+ )}
+ onClick={() => phase === "idle" && setCur(i)}
+ data-record-prompt={p.n}
+ data-record-prompt-current={i === cur ? "1" : undefined}
+ data-record-prompt-kept={kept(p.n) ? "1" : undefined}
+ >
+ {parts.length > 1 && <span className="micro mr-2 align-middle">{p.n}/{parts.length}</span>}
+ {p.text}
+ {i === cur && (
+ <span className="mt-1 flex flex-wrap gap-1.5 text-[12px]">
+ {kept(p.n) && (
+ <button type="button" className={btn} onClick={() => play(`/api/report/post-narration/record?project=${enc(project)}&id=${enc(item.id)}&n=${p.n}&v=${enc(session.parts[String(p.n)]?.at ?? "")}`)} data-record-play-part={p.n}>
+ Play it back
+ </button>
+ )}
+ {item.placeholder && (
+ <button type="button" className={btn} onClick={() => playPlaceholderPart(p)} data-record-play-placeholder={p.n}>
+ Play the placeholder
+ </button>
+ )}
+ </span>
+ )}
+ </li>
+ ))}
+ {!parts.length && <li className="text-text-2">no script yet — write one on its bench</li>}
+ </ol>
+
+ <div className="flex flex-wrap items-center gap-2">
+ {phase === "count" && (
+ <span className="text-[28px] font-bold tabular-nums" data-record-count={count}>
+ {count}
+ </span>
+ )}
+ <button
+ type="button"
+ className={cn(buttonVariants({ variant: phase === "recording" ? "outline" : "go", size: "sm" }))}
+ disabled={(phase !== "idle" && phase !== "recording") || !parts.length}
+ 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="">
+ 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>
+ {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>}
+ {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>
+ {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
+ <audio
+ ref={player}
+ className="hidden"
+ onTimeUpdate={(e) => {
+ if (stopAt.current !== null && e.currentTarget.currentTime >= stopAt.current) e.currentTarget.pause();
+ }}
+ data-record-player=""
+ />
+ </section>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -8,7 +8,7 @@ import {
} from "@/lib/projects/report.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { buttonVariants } from "@/components/ui/button";
-import { postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
+import { narrationRecordHref, postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs";
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
@@ -363,6 +363,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
return (
<>
<div className="flex flex-wrap items-start gap-3">
+ {/* A cut of posts is read aloud: its recording session (lane/post-narration). */}
+ {entries.some((x) => x.kind === "post") && (
+ <Link href={narrationRecordHref(project.id)} className={buttonVariants({ variant: "go", size: "sm" })} data-record-narration-link="">
+ Record the narration ›
+ </Link>
+ )}
{/* ---- the way in ----
Every clip row carries a bench link, which is the right control for
"go to that one" and the wrong one for "start". Reviewing a cut is
diff --git a/umtool/components/projects/useMic.ts b/umtool/components/projects/useMic.ts
@@ -0,0 +1,98 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+// THE MICROPHONE for a recording (the post bench, the recording session):
+// its devices, the one chosen (remembered per browser), a live level, and a
+// MediaRecorder -- opus in webm (Chromium) or ogg (Firefox). Localhost is a
+// secure context, so getUserMedia works with no network beyond it.
+
+export const MIC_KEY = "umtool.post-narration.mic";
+
+export const ls = {
+ get: (k: string) => {
+ try {
+ return window.localStorage.getItem(k);
+ } catch {
+ return null;
+ }
+ },
+ set: (k: string, v: string) => {
+ try {
+ window.localStorage.setItem(k, v);
+ } catch {
+ // private mode: not remembered
+ }
+ },
+};
+
+/** The microphone: its devices, the one chosen (remembered), a level, a recorder. */
+export function useMic() {
+ const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
+ const [device, setDevice] = useState<string>("");
+ const [level, setLevel] = useState(0);
+ const [error, setError] = useState<string | null>(null);
+ const stream = useRef<MediaStream | null>(null);
+ const rec = useRef<MediaRecorder | null>(null);
+ const chunks = useRef<Blob[]>([]);
+ const raf = useRef(0);
+ const ctx = useRef<AudioContext | null>(null);
+ const open = useCallback(async (id?: string) => {
+ setError(null);
+ try {
+ stream.current?.getTracks().forEach((t) => t.stop());
+ const s = await navigator.mediaDevices.getUserMedia({ audio: id ? { deviceId: { exact: id }, echoCancellation: false, noiseSuppression: false, autoGainControl: false } : { echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
+ stream.current = s;
+ const list = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput");
+ setDevices(list);
+ const now = s.getAudioTracks()[0]?.getSettings().deviceId ?? id ?? "";
+ setDevice(now);
+ if (now) ls.set(MIC_KEY, now);
+ ctx.current ??= new AudioContext();
+ const an = ctx.current.createAnalyser();
+ an.fftSize = 1024;
+ ctx.current.createMediaStreamSource(s).connect(an);
+ const buf = new Float32Array(an.fftSize);
+ cancelAnimationFrame(raf.current);
+ const tick = () => {
+ an.getFloatTimeDomainData(buf);
+ let acc = 0;
+ for (const v of buf) acc += v * v;
+ setLevel(Math.min(1, Math.sqrt(acc / buf.length) * 4));
+ raf.current = requestAnimationFrame(tick);
+ };
+ tick();
+ return s;
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ return null;
+ }
+ }, []);
+ useEffect(() => () => {
+ cancelAnimationFrame(raf.current);
+ stream.current?.getTracks().forEach((t) => t.stop());
+ }, []);
+ const start = useCallback(async () => {
+ const s = stream.current ?? (await open(ls.get(MIC_KEY) ?? undefined));
+ if (!s) return false;
+ chunks.current = [];
+ const type = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/webm"].find((t) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(t));
+ const r = new MediaRecorder(s, type ? { mimeType: type } : undefined);
+ r.ondataavailable = (ev) => ev.data.size && chunks.current.push(ev.data);
+ r.start(250);
+ rec.current = r;
+ return true;
+ }, [open]);
+ const stop = useCallback(
+ () =>
+ new Promise<Blob | null>((resolve) => {
+ const r = rec.current;
+ if (!r || r.state === "inactive") return resolve(null);
+ r.onstop = () => resolve(new Blob(chunks.current, { type: r.mimeType || "audio/webm" }));
+ r.stop();
+ }),
+ [],
+ );
+ return { devices, device, level, error, open, start, stop };
+}
+
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -671,6 +671,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}` |
| 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 derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice) into a NEW take, the original kept; "not installed" until the editor has the engine | post bench, **run AI on take #n** (the op, an engine, a stock voice) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` | `op: "derive", from, op2, engine?, voice?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -581,6 +581,21 @@ words split at its sentence ends): a take may be COMPOSED OF PARTS, joined with
between paragraphs and 0.25 s inside one (`POST_PART_GAP`); `--import` reads a take's
`take-<n>.parts.json`, and a recording is recorded part by part.
+**The recording session** — `/projects/<p>/narration/record` (the Cut tab's **Record the
+narration**), made for reading a whole cut (operator, 3 Nov: "I need to do a dramatic reading
+of this starting tomorrow"): it walks the cut's posts in order — a jump list with each post
+recorded or still on its placeholder, n of N — showing the post's card (the render's own
+page: text, avatar, date) and its attachment, and the SCRIPT as a teleprompter in its PARTS
+(the placeholder take's `parts.json`, else the script split by `scriptParts`), the part being
+read large. **Space** records and stops (a 3-2-1 count-in first, a toggle), **r** redoes the
+part, **Enter** goes on (the post done: to the next post), **n** / **p** walk the posts;
+**Play it back** and **Play the placeholder** (the synthesized part, for reference). Each
+part is written to `narration/posts/<postId>/.recording-<label>/` the moment it is stopped
+(`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.
+
**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
being read large, **Record / Stop / Redo part / Next part** (auto-advancing; R and S),
diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -49,6 +49,7 @@ test.beforeEach(() => {
for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true });
rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true });
rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true });
+ rmSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"), { recursive: true, force: true });
});
const root = (page: Page) => page.locator("[data-play-cut]");
@@ -188,3 +189,59 @@ test.describe("the recording session", () => {
await expect(panel.locator("[data-post-progress-recorded]")).toHaveText("1");
});
});
+
+test("THE RECORDING SESSION: part by part, a reload resumes, redo one, the last part makes the recorded take and picks it", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1200 });
+ await page.goto(urls.projectHref(PROJECT, { tab: "cut" }));
+ await expect(page.locator("[data-record-narration-link]")).toHaveAttribute("href", urls.narrationRecordHref(PROJECT));
+ await page.goto(urls.narrationRecordHref(PROJECT, { post: "p-11" }));
+ const s = page.locator("[data-record-session]");
+ await expect(s).toHaveAttribute("data-record-session", "p-11");
+ await expect(page.locator("[data-record-jump]")).toHaveCount(3);
+ await expect(page.locator('[data-record-jump="p-11"]')).toHaveAttribute("data-record-state", "placeholder");
+ await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "0");
+ // Two paragraphs: two parts, the first current.
+ await expect(page.locator("[data-record-prompt]")).toHaveCount(2);
+ await expect(page.locator('[data-record-prompt="1"]')).toHaveAttribute("data-record-prompt-current", "1");
+ await page.locator("[data-record-count-in]").uncheck();
+ // Space records, Space stops: part 1 is on disk, part 2 is next.
+ await page.keyboard.press("Space");
+ await expect(s).toHaveAttribute("data-record-phase", "recording", { timeout: 10_000 });
+ await page.waitForTimeout(900);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "record-session-recording.png"), fullPage: true });
+ await page.keyboard.press("Space");
+ await expect(page.locator('[data-record-prompt="1"]')).toHaveAttribute("data-record-prompt-kept", "1");
+ await expect(page.locator('[data-record-prompt="2"]')).toHaveAttribute("data-record-prompt-current", "1");
+ expect(existsSync(path.join(DIR, "narration", "posts", "11", ".recording-operator", "session.json"))).toBe(true);
+ // A reload resumes: part 1 kept, part 2 current.
+ await page.reload();
+ await expect(page.locator('[data-record-prompt="1"]')).toHaveAttribute("data-record-prompt-kept", "1");
+ await expect(page.locator('[data-record-prompt="2"]')).toHaveAttribute("data-record-prompt-current", "1");
+ await expect(page.locator('[data-record-play-placeholder="2"]')).toBeVisible();
+ // Redo part 1 (r): recorded again, still kept; the next unkept part is current.
+ await page.locator('[data-record-prompt="1"]').click();
+ await page.locator("[data-record-count-in]").uncheck();
+ await page.keyboard.press("r");
+ await expect(s).toHaveAttribute("data-record-phase", "recording", { timeout: 10_000 });
+ await page.waitForTimeout(700);
+ await page.keyboard.press("Space");
+ await expect(page.locator('[data-record-prompt="2"]')).toHaveAttribute("data-record-prompt-current", "1");
+ await expect(page.locator('[data-record-play-part="1"]')).toHaveCount(0);
+ // The last part: the take is made, picked, and the post is recorded.
+ await page.keyboard.press("Space");
+ await expect(s).toHaveAttribute("data-record-phase", "recording", { timeout: 10_000 });
+ await page.waitForTimeout(700);
+ await page.keyboard.press("Space");
+ await expect(page.locator("[data-record-status]")).toContainText("take-2.recorded-operator.wav", { timeout: 30_000 });
+ await expect(page.locator('[data-record-jump="p-11"]')).toHaveAttribute("data-record-state", "recorded");
+ await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "1");
+ const n = narr("p-11");
+ expect(n.pick).toBe(1);
+ expect(n.takes![1]).toMatchObject({ file: "narration/posts/11/take-2.recorded-operator.wav", engine: "recorded", voice: "operator" });
+ expect((n.takes![1] as unknown as { parts: unknown[] }).parts).toHaveLength(2);
+ expect(existsSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"))).toBe(false);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "record-session-done.png"), fullPage: true });
+ // Enter: on to the next post.
+ await page.keyboard.press("Enter");
+ await expect(s).toHaveAttribute("data-record-session", "p-12");
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -407,6 +407,11 @@ export function narrationHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note);
}
+/** The recording session: a person reads the cut's post items aloud, part by part (lane/post-narration). */
+export function narrationRecordHref(project: string, q: { post?: string | null } = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/narration/record`, q.post ? { post: q.post } : {});
+}
+
/** The drafts review (release 28). */
export function reviewHref(project: string, q: NoteOpt & { view?: "list" } = {}): string {
return withQuery(`/projects/${encodePath(project)}/review`, q.view ? { view: q.view } : {}, q.note);
diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs
@@ -286,3 +286,35 @@ test("a DERIVED take: run through the editor's op into a new take, the original
const trash = await readdir(path.join(p.dir, "narration", "posts", "1", ".trash"));
assert.ok(trash.some((f) => f.endsWith("take-2.convert-rvc.wav")));
});
+
+test("the recording session's store: each part on disk as it is kept, a re-split starts over, finish makes the take and clears it", async () => {
+ const { savePart, discardPart, readSession, finishSession, sessionDirOf } = await import("./recordSession.mjs");
+ const p = await project("sess", [item("1", { narration: { script: "one.\n\ntwo." } })]);
+ const e = () => manifest(p).then((m) => m.timeline[0]);
+ const bytes = async (k) => {
+ const f = path.join(ROOT, `sess-${k}.wav`);
+ ff(["-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono:d=0.3", "-f", "lavfi", "-i", "sine=f=300:d=0.8:r=48000", "-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1", f]);
+ return new Uint8Array(await readFile(f));
+ };
+ await assert.rejects(finishSession(p, await e()), /nothing recorded yet/);
+ let s = await savePart(p.dir, await e(), { n: 1, count: 2, text: "one.", para: 0, bytes: await bytes(1), type: "audio/wav" });
+ assert.deepEqual(Object.keys(s.parts), ["1"]);
+ assert.equal((await readSession(p.dir, await e())).parts["1"].file, "p01.wav");
+ await assert.rejects(finishSession(p, await e()), /parts 2 of 2 are not recorded yet/);
+ // Redo: dropped, then kept again.
+ s = await discardPart(p.dir, await e(), 1);
+ assert.deepEqual(s.parts, {});
+ await savePart(p.dir, await e(), { n: 1, count: 2, text: "one.", para: 0, bytes: await bytes(1), type: "audio/wav" });
+ await savePart(p.dir, await e(), { n: 2, count: 2, text: "two.", para: 1, bytes: await bytes(2), type: "audio/wav" });
+ const kept = await finishSession(p, await e(), { manifest: await manifest(p) });
+ assert.equal(kept.take.file, "narration/posts/1/take-1.recorded-operator.wav");
+ assert.equal(kept.take.parts.length, 2);
+ assert.equal((await manifest(p)).timeline[0].narration.pick, 0);
+ await assert.rejects(readdir(sessionDirOf(p.dir, await e(), "operator")));
+ // A different split (the script was edited): the parts kept before no longer line up.
+ await savePart(p.dir, await e(), { n: 1, count: 2, text: "a", para: 0, bytes: await bytes(1), type: "audio/wav" });
+ s = await savePart(p.dir, await e(), { n: 1, count: 3, text: "a", para: 0, bytes: await bytes(1), type: "audio/wav" });
+ assert.equal(s.count, 3);
+ assert.deepEqual(Object.keys(s.parts), ["1"]);
+ await assert.rejects(savePart(p.dir, await e(), { n: 4, count: 3, text: "", para: 0, bytes: await bytes(1) }), /n of count/);
+});
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -151,6 +151,7 @@ export async function importPatches(manifest, rows, measure) {
const fmtKnob = (k, v) => `${k}=${typeof v === "boolean" ? (v ? "on" : "off") : v}`;
/**
+ * @returns {Array<{ n: number, para?: number, text?: string, file?: string, start: number, seconds: number, gapBefore?: number }> | null}
* A take's PARTS as the batch writes them (`take-<n>.parts.json`: a list, or
* `{ parts: [...] }`), each `{ n, para, text, file, start, seconds, gapBefore }`
* -- only those keys, numbers rounded; null when there are none.
diff --git a/umtool/lib/report/recordSession.mjs b/umtool/lib/report/recordSession.mjs
@@ -0,0 +1,122 @@
+// THE RECORDING SESSION's store (operator, 3 Nov: "I need to do a dramatic
+// reading of this starting tomorrow"): a person reading a cut's posts aloud,
+// PART BY PART, on /projects/<p>/narration/record. Every part is written to
+// disk the moment it is kept, so nothing is lost on a crash and a reload
+// resumes where the reading stopped:
+//
+// narration/posts/<postId>/.recording-<label>/
+// session.json { version, id, label, count, parts: { "<n>": { file, text, para, at, bytes, type } } }
+// p01.webm … each part as the browser recorded it (webm/opus, ogg/opus)
+//
+// When every part of the post is in, `finishSession` makes them one recorded
+// take (postRecord.mjs keepRecording: each part trimmed of its silence, joined
+// with the parts' pauses, levelled to the synthesized takes), PICKED, and
+// clears the session. Plain ESM.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
+import { RECORD_LABEL_RE, keepRecording } from "./postRecord.mjs";
+
+/** A part is at most this large (a minute of opus is well under 1 MB). */
+export const SESSION_PART_MAX = 100 * 1024 * 1024;
+
+export const sessionDirOf = (projectDir, entry, label) => path.join(projectDir, ...takesDirOf(postIdOf(entry)).split("/"), `.recording-${label}`);
+
+const checkLabel = (label) => {
+ if (!RECORD_LABEL_RE.test(String(label))) throw Object.assign(new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`), { status: 400 });
+};
+
+/** The session of `entry` for voice `label` ({ parts: {} } when none). */
+export async function readSession(projectDir, entry, label = "operator") {
+ checkLabel(label);
+ const dir = sessionDirOf(projectDir, entry, label);
+ try {
+ const doc = JSON.parse(await readFile(path.join(dir, "session.json"), "utf8"));
+ return { version: 1, id: entry.id, label, count: null, parts: {}, ...doc };
+ } catch {
+ return { version: 1, id: entry.id, label, count: null, parts: {} };
+ }
+}
+
+async function writeSession(dir, doc) {
+ const tmp = path.join(dir, `.session.${process.pid}.${Date.now()}.json`);
+ await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ 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");
+
+/**
+ * KEEP ONE PART: its bytes written (through a rename: never half a file), the
+ * session updated. `n` from 1; `count` how many parts the post's read has.
+ *
+ * @param {string} projectDir
+ * @param {Record<string, any>} entry
+ * @param {{ n: number, count: number, text: string, para: number, bytes: Uint8Array, type?: string, label?: string }} part
+ */
+export async function savePart(projectDir, entry, { n, count, text, para, bytes, type = "audio/webm", label = "operator" }) {
+ checkLabel(label);
+ if (!Number.isInteger(n) || n < 1 || !Number.isInteger(count) || count < 1 || n > count || count > 200) throw Object.assign(new Error("a part is n of count (1 ≤ n ≤ count ≤ 200)"), { status: 400 });
+ if (!bytes?.byteLength) throw Object.assign(new Error("the part is empty"), { status: 400 });
+ if (bytes.byteLength > SESSION_PART_MAX) throw Object.assign(new Error("the part is too large"), { status: 413 });
+ const dir = sessionDirOf(projectDir, entry, label);
+ await mkdir(dir, { recursive: true });
+ const doc = await readSession(projectDir, entry, label);
+ // A different split of the script (it was edited): the parts kept so far no longer line up.
+ if (doc.count !== null && doc.count !== count) doc.parts = {};
+ const name = `p${String(n).padStart(2, "0")}.${extOf(type)}`;
+ const tmp = path.join(dir, `.${name}.${process.pid}.tmp`);
+ await writeFile(tmp, bytes);
+ const old = doc.parts[String(n)];
+ await rename(tmp, path.join(dir, name));
+ if (old && old.file !== name) await rm(path.join(dir, old.file), { force: true });
+ doc.count = count;
+ doc.parts[String(n)] = { file: name, text: String(text ?? ""), para: Number.isInteger(para) ? para : n - 1, at: new Date().toISOString(), bytes: bytes.byteLength, type };
+ await writeSession(dir, doc);
+ return doc;
+}
+
+/** Drop one part of the session (redo it). */
+export async function discardPart(projectDir, entry, n, label = "operator") {
+ const dir = sessionDirOf(projectDir, entry, label);
+ const doc = await readSession(projectDir, entry, label);
+ const p = doc.parts[String(n)];
+ if (p) {
+ await rm(path.join(dir, p.file), { force: true });
+ delete doc.parts[String(n)];
+ await writeSession(dir, doc);
+ }
+ return doc;
+}
+
+/** The absolute file of a session part, or null. */
+export async function partFile(projectDir, entry, n, label = "operator") {
+ const doc = await readSession(projectDir, entry, label);
+ const p = doc.parts[String(n)];
+ return p ? path.join(sessionDirOf(projectDir, entry, label), p.file) : null;
+}
+
+/**
+ * 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]
+ */
+export async function finishSession(project, entry, { label = "operator", manifest = null, script = null } = {}) {
+ const doc = await readSession(project.dir, 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 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 });
+ }
+ const kept = await keepRecording(project, entry, parts, { label, manifest, script });
+ await rm(dir, { recursive: true, force: true });
+ return kept;
+}