Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 30ec2713594a25dd94b8026eeb5477b5a1d1b194
parent e2e39454f607bec80f2efd1e4af04b3555b967b2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 23:01:12 -0500

umtool: the post bench's narration -- the recording session, the lanes, takes and re-takes, the mix; e2e

The post bench (/projects/<p>/post/<id>) gains PostNarrationPanel: the cut's reading
progress (recorded n of N, the next to record) and N / P through the cut's posts; the
lanes -- the attachment's whole waveform with the window that plays (its handles are
the in and out; Re-pick best runs posts fit's scan; Play whole attachment) and the read
on the item's clock (the take's waveform from its lead, dragged to move it, the muffle
under it, the ramp back, its parts); THE RECORDING SESSION -- the mic (remembered),
a level meter, a 3-2-1 count-in, the script as a teleprompter part by part (Record /
Stop / Redo part / Next part, auto-advancing), play back, Keep (a recorded take,
picked) or Discard; the takes (each plays, its parts, Pick, its note), Approve,
narrated on/off, Undo; the script and Re-take with direction (the editor's tts op as a
job, kept when done); and this post's mix knobs. Play and the bench draw the plan with
the cut's render (its postNarration). The suite's editor stub writes a tts result where
`out` says. post-narration.spec.ts (a fake microphone for the recording); post-items
.spec.ts follows the one layout and the pacing rule.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/components/projects/PostBench.tsx | 38++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/PostBenchPage.tsx | 3++-
Aumtool/components/projects/PostNarrationPanel.tsx | 635+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/benchMedia.ts | 26++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 9+++++++--
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/post-narration-fixture.mjs | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/post-items.spec.ts | 31+++++++++++++++++--------------
Aumtool/e2e/post-narration.spec.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postNarration.test.mjs | 26++++++++++++++++++++++++++
10 files changed, 981 insertions(+), 21 deletions(-)

diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -8,6 +8,7 @@ import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; import { POST_HOLD, POST_MEDIA_MIN_SPAN, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item"; import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; +import PostNarrationPanel from "./PostNarrationPanel"; // --------------------------------------------------------------------------- // THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its @@ -36,7 +37,7 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [ ]; export default function PostBench({ - project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, + project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, }: { project: string; entry: Entry; @@ -47,6 +48,8 @@ export default function PostBench({ prev: string | null; next: string | null; fromPlay: boolean; + /** The cut's render block (its `postNarration` knobs). */ + render?: Record<string, unknown>; }) { const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); @@ -54,7 +57,7 @@ export default function PostBench({ const [token, setToken] = useState(initialToken); const [status, setStatus] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); - const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry) as PostPlan)), [entry, initial, initialPlan]); + const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render) as PostPlan)), [entry, initial, initialPlan, render]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -86,10 +89,18 @@ export default function PostBench({ ev.preventDefault(); setPlaying((p) => (s >= total ? (setS(0), true) : !p)); } + // N / P: the next or previous post of the cut (the recording session walks the cut). + if ((ev.key === "n" || ev.key === "p") && !ev.metaKey && !ev.ctrlKey && !ev.altKey) { + const to = ev.key === "n" ? next : prev; + if (to) { + ev.preventDefault(); + router.push(postBenchHref(project, to, fromPlay ? { play: { at: 0 } } : {})); + } + } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [s, total]); + }, [s, total, next, prev, project, fromPlay, router]); const dirty = JSON.stringify(entry) !== JSON.stringify(saved); const media = entry.media ?? []; @@ -225,13 +236,32 @@ export default function PostBench({ ))} <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} /> </div> + <PostNarrationPanel + project={project} + entry={entry} + token={token} + plan={plan} + render={render} + onEntry={(e, t) => { + setEntry(e); + setSaved(e); + setToken(t); + }} + s={s} + setS={setS} + setPlaying={setPlaying} + prev={prev} + next={next} + fromPlay={fromPlay} + /> </section> <aside className="space-y-3 text-[12.5px]"> <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> <h2 className="micro mb-2">length</h2> <p className="m-0 text-text-2"> - the rule: {reading.toFixed(1)} s to read{media.length ? ` + the attachments` : ""} = <b data-post-bench-rule="">{ruleSeconds(entry).toFixed(1)} s</b> + {plan.narration ? `the read (${plan.narration.seconds.toFixed(1)} s) and its linger` : `${reading.toFixed(1)} s to read`} + {media.length ? `, the attachments beside it` : ""} = <b data-post-bench-rule="">{ruleSeconds(entry, render).toFixed(1)} s</b> </p> <label className="mt-2 flex items-center gap-2"> hold diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -44,7 +44,8 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj entry={entry} token={await manifestToken(project.dir)} box={{ width: box.width, height: box.height }} - plan={postItemPlan(entry) as unknown as PostPlan} + plan={postItemPlan(entry, render) as unknown as PostPlan} + render={render} back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }} prev={k > 0 ? neighbours[k - 1] : null} next={k < neighbours.length - 1 ? neighbours[k + 1] : null} diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -0,0 +1,635 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import Waveform from "@/components/Waveform"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { postBenchHref } from "@/lib/hrefs"; +import { POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts } from "umtool-report-to-video/post-narration"; +import { projectFileMedia } from "./bench/benchMedia"; +import { usePeaks } from "./bench/usePeaks"; +import type { PostPlan } from "./review/PostItemPlayer"; + +// --------------------------------------------------------------------------- +// A POST's NARRATION ON THE BENCH (report-to-video/post-narration.mjs; +// knobs.md, "A narrated post item"), beside the post bench's player: +// +// the lanes the attachment's whole waveform with its window (the in/out +// handles; Re-pick best: posts fit's scan), and the read on the +// item's clock -- the take's waveform from its lead (drag it), +// the muffle under it, the ramp back to clean +// record THE RECORDING SESSION (operator, 2 Nov: "I think I'll record my +// voice"): the mic, a level meter, a 3-2-1 count-in, the script as +// a teleprompter PART BY PART (Record / Stop / Redo part / Next +// part), play back, Keep -- saved as a recorded take and picked +// takes each take (play it, its parts, Pick, its note), Approve, the +// script, Re-take with direction (the EDITOR's tts op, a job) +// the mix wet, lead, tail, ramp, linger, short, attach, clip, duck +// +// Every change is one write (POST /api/report/post-narration), the writer +// `umtool posts narrate` runs; the bench takes the entry it returns. +// --------------------------------------------------------------------------- + +type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }> }; +type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>; +type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> }; +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, +}: { + project: string; + entry: Entry; + token: string | null; + plan: PostPlan; + render: Record<string, unknown>; + /** The writer's answer: the entry as it is now, and the manifest's token. */ + onEntry: (e: Entry, token: string | null) => void; + s: number; + setS: (s: number) => void; + setPlaying: (p: boolean) => void; + prev: string | null; + next: string | null; + fromPlay: boolean; +}) { + const n = entry.narration ?? {}; + const takes = n.takes ?? []; + const picked = pickedTake(entry) as (Take & { index: number }) | null; + const k = postNarrationKnobs(entry, render) as typeof POST_NARRATION_DEFAULTS & Record<string, unknown>; + const [error, setError] = useState<string | null>(null); + const [status, setStatus] = useState<string | null>(null); + const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); + + const post = useCallback( + async (body: Record<string, unknown>) => { + setError(null); + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body }) }); + const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[]; jobId?: string; file?: string; untouched?: boolean; why?: string; window?: Narration["window"] }; + if (!res.ok) { + setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); + return null; + } + if (j.entry) onEntry(j.entry, j.token ?? null); + return j; + }, + [project, entry.id, token, onEntry], + ); + const set = (patch: Record<string, unknown>) => post({ op: "set", patch }).then((j) => j && setStatus("saved")); + + // ---- the cut's reading progress ------------------------------------------- + const [progress, setProgress] = useState<Progress | null>(null); + useEffect(() => { + let live = true; + fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : null)) + .then((j) => live && j && setProgress(j as Progress)) + .catch(() => {}); + return () => { + live = false; + }; + }, [project, entry]); + const nextToRecord = progress?.items.find((x) => x.plays !== "recorded" && x.id !== entry.id) ?? null; + + // ---- the recording session -------------------------------------------------- + const mic = useMic(); + const [label, setLabel] = useState("operator"); + useEffect(() => setLabel(ls.get(LABEL_KEY) ?? "operator"), []); + const [script, setScript] = useState(n.script ?? ""); + useEffect(() => setScript(entry.narration?.script ?? ""), [entry.id, entry.narration?.script]); + const parts = useMemo(() => scriptParts(script), [script]); + const [part, setPart] = useState(0); + const [blobs, setBlobs] = useState<Array<{ blob: Blob; url: string } | null>>([]); + const [phase, setPhase] = useState<"idle" | "count" | "recording" | "saving">("idle"); + const [count, setCount] = useState(0); + useEffect(() => { + setPart(0); + setBlobs([]); + setPhase("idle"); + }, [entry.id]); + const record = async () => { + if (phase !== "idle" || !parts.length) return; + setPhase("count"); + for (const c of [3, 2, 1]) { + setCount(c); + await new Promise((r) => setTimeout(r, 700)); + } + setCount(0); + if (!(await mic.start())) { + setPhase("idle"); + return; + } + setPhase("recording"); + }; + const stop = async () => { + if (phase !== "recording") return; + const blob = await mic.stop(); + setPhase("idle"); + if (!blob) return; + setBlobs((b) => { + const out = [...b]; + if (out[part]) URL.revokeObjectURL(out[part]!.url); + out[part] = { blob, url: URL.createObjectURL(blob) }; + return out; + }); + // Auto-advance to the next part not yet recorded. + setPart((p) => (p < parts.length - 1 ? p + 1 : p)); + }; + const allIn = parts.length > 0 && parts.every((_, i) => !!blobs[i]); + const keep = async () => { + if (!allIn) return; + setPhase("saving"); + setError(null); + const fd = new FormData(); + fd.set("project", project); + fd.set("id", entry.id); + fd.set("label", label); + if (script !== (n.script ?? "")) fd.set("script", script); + parts.forEach((p, i) => { + fd.append("part", blobs[i]!.blob, `p${i + 1}.webm`); + fd.append("text", p.text); + fd.append("para", String(p.para)); + }); + const res = await fetch("/api/report/post-narration", { method: "POST", body: fd }); + const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; take?: Take }; + setPhase("idle"); + if (!res.ok || !j.entry) { + setError(j.error ?? `HTTP ${res.status}`); + return; + } + onEntry(j.entry, j.token ?? null); + setBlobs([]); + setPart(0); + setStatus(`kept ${j.take?.file ?? "the recording"} (picked)`); + }; + // R records, S stops (Space is the bench's play). + useEffect(() => { + const onKey = (ev: KeyboardEvent) => { + const tgt = ev.target as HTMLElement | null; + if (tgt?.closest("input, textarea, select")) return; + if (ev.key === "r" && !ev.metaKey && !ev.ctrlKey) { + ev.preventDefault(); + void record(); + } else if (ev.key === "s" && !ev.metaKey && !ev.ctrlKey) { + ev.preventDefault(); + void stop(); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }); + + // ---- a re-take with direction (the editor's tts op) -------------------------- + const [dir, setDir] = useState({ note: "", voice: "", speed: "" }); + const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string } | null>(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 }); + if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: dir.note, script, state: "running" }); + }; + useEffect(() => { + if (!job || job.state !== "running") return; + const t = setTimeout(async () => { + const q = new URLSearchParams({ project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}) }); + const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string }; + if (j.state === "done") { + setJob({ ...job, state: "done" }); + setStatus(`new take ${job.file} (picked)`); + window.location.reload(); + } else if (j.state === "failed" || !r.ok) setJob({ ...job, state: "failed", error: j.error ?? `HTTP ${r.status}` }); + }, 1500); + return () => clearTimeout(t); + }, [job, project, entry.id]); + + // ---- the lanes ------------------------------------------------------------------ + const vi = (entry.media ?? []).findIndex((m) => m.kind === "video"); + const video = vi >= 0 ? entry.media![vi] : null; + const vSecs = Number(video?.seconds ?? 0); + const step = vi >= 0 ? plan.steps.find((st) => st.items.some((m) => m.i === vi)) ?? null : null; + const win = step ? { from: step.srcFrom ?? 0, to: (step.srcFrom ?? 0) + step.seconds } : { from: 0, to: vSecs }; + const vMedia = useMemo(() => projectFileMedia({ project, path: video?.src ?? "", seconds: vSecs || 1 }), [project, video?.src, vSecs]); + const vPeaks = usePeaks(video ? vMedia : { ...vMedia, peaksUrl: null }); + const tMedia = useMemo(() => projectFileMedia({ project, path: picked?.file ?? "", seconds: picked?.seconds || 1 }), [project, picked?.file, picked?.seconds]); + const tPeaks = usePeaks(picked ? tMedia : { ...tMedia, peaksUrl: null }); + const [showWhole, setShowWhole] = useState(false); + const sch = plan.narration ?? null; + const total = plan.total; + const pct = (v: number) => `${(v / Math.max(0.1, total)) * 100}%`; + const drag = useRef<{ x: number; lead: number; w: number } | null>(null); + const [leadDraft, setLeadDraft] = useState<number | null>(null); + const lead = leadDraft ?? Number(k.lead); + + const mixKnob = (key: string, labelText: string, o: { step?: number; min?: number; max?: number; options?: string[] }) => ( + <label className="flex items-center gap-1.5" key={key}> + {labelText} + {o.options ? ( + <select value={String(k[key as keyof typeof k])} onChange={(e) => void set({ [key]: e.target.value === String(POST_NARRATION_DEFAULTS[key as keyof typeof POST_NARRATION_DEFAULTS]) ? null : e.target.value })} data-post-mix={key}> + {o.options.map((x) => ( + <option key={x} value={x}> + {x} + </option> + ))} + </select> + ) : ( + <input + type="number" + step={o.step ?? 0.1} + min={o.min} + max={o.max} + defaultValue={Number(k[key as keyof typeof k])} + key={`${entry.id}:${key}:${String(k[key as keyof typeof k])}`} + onBlur={(e) => { + const v = Number(e.target.value); + if (Number.isFinite(v) && v !== Number(k[key as keyof typeof k])) void set({ [key]: v }); + }} + className="w-16 rounded border border-seam bg-ground px-1 py-0.5" + data-post-mix={key} + /> + )} + </label> + ); + + return ( + <div className="space-y-3 text-[12.5px]" data-post-narration={entry.id} data-post-narration-plays={picked ? (picked.engine === "recorded" ? "recorded" : "synthesized") : "none"}> + {/* The cut's reading: how far along, and where next. */} + <section className="flex flex-wrap items-center gap-3 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" data-post-progress=""> + {progress ? ( + <span> + recorded <b data-post-progress-recorded="">{progress.counts.recorded}</b> of {progress.counts.posts} · placeholder (synthesized) {progress.counts.synthesized} · none {progress.counts.none} · approved {progress.counts.approved} + </span> + ) : ( + <span className="text-text-2">reading the cut…</span> + )} + {nextToRecord && ( + <Link href={postBenchHref(project, nextToRecord.id, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-next-unrecorded={nextToRecord.id}> + next to record: #{nextToRecord.n} › + </Link> + )} + <span className="ml-auto text-text-2">N / P: next / previous post · R record · S stop · Space play</span> + {prev && <Link href={postBenchHref(project, prev, fromPlay ? { play: { at: 0 } } : {})} className="hidden" data-post-walk="prev" />} + {next && <Link href={postBenchHref(project, next, fromPlay ? { play: { at: 0 } } : {})} className="hidden" data-post-walk="next" />} + </section> + + {/* THE LANES: the attachment's window, the read on the item's clock. */} + <section className="space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-lanes=""> + {video && ( + <div data-post-lane="attachment"> + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="micro">attachment · {vSecs.toFixed(1)} s · plays {win.from.toFixed(1)}–{win.to.toFixed(1)} s</span> + <button type="button" className={btn} onClick={() => void post({ op: "fit" }).then((j) => j && setStatus(j.untouched ? `nothing to fit: ${j.why}` : `best part: ${j.window?.start}–${j.window?.end} s`))} data-post-repick=""> + Re-pick best + </button> + <button type="button" className={btn} onClick={() => setShowWhole((x) => !x)} data-post-play-whole=""> + {showWhole ? "Hide whole attachment" : "Play whole attachment"} + </button> + </div> + <Waveform + view={{ from: 0, to: vSecs || 1 }} + sel={win} + cand={n.window ? { from: n.window.start, to: n.window.end } : win} + words={[]} + peaks={vPeaks} + playhead={step && s >= step.at ? (step.srcFrom ?? 0) + Math.min(step.seconds, s - step.at) : null} + onSel={(next2, dragging) => { + if (dragging) return; + const media = { [vi]: { start: next2.from > 0.02 ? Math.round(next2.from * 100) / 100 : null, end: next2.to < vSecs - 0.02 ? Math.round(next2.to * 100) / 100 : null } }; + void fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "set", id: entry.id, patch: { media }, token }) }) + .then((r) => r.json()) + .then((j: { entry?: Entry; token?: string; error?: string }) => (j.entry ? onEntry(j.entry, j.token ?? null) : setError(j.error ?? "not saved"))); + }} + onReachEdge={() => {}} + height={72} + /> + {n.window?.reason && ( + <p className="m-0 mt-1 text-text-2" data-post-window-reason=""> + chosen: {n.window.reason} + </p> + )} + {showWhole && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <video src={fileUrl(project, video.src)} controls className="mt-1 max-h-48" data-post-whole-video="" /> + )} + </div> + )} + {sch && picked && ( + <div data-post-lane="read"> + <div className="micro mb-1"> + the read · {picked.file.split("/").pop()} · {picked.seconds.toFixed(1)} s from {lead.toFixed(2)} s · muffled to {sch.voiceEnd.toFixed(1)} s, clean from {sch.rampEnd.toFixed(1)} s · {mixPhaseAt(sch, s)} + </div> + <div + className="relative h-16 w-full overflow-hidden rounded bg-black/30" + onPointerMove={(e) => { + if (!drag.current) return; + const dt = ((e.clientX - drag.current.x) / drag.current.w) * total; + setLeadDraft(Math.max(0, Math.min(5, Math.round((drag.current.lead + dt) * 20) / 20))); + }} + onPointerUp={() => { + if (!drag.current) return; + drag.current = null; + if (leadDraft !== null && leadDraft !== Number(k.lead)) void set({ lead: leadDraft }).then(() => setLeadDraft(null)); + else setLeadDraft(null); + }} + onClick={(e) => { + const r = e.currentTarget.getBoundingClientRect(); + setS(((e.clientX - r.left) / r.width) * total); + }} + > + {/* The muffle under the read, the ramp back to clean. */} + {sch.duck && <div className="absolute inset-y-0 left-0 bg-sky-500/15" style={{ width: pct(sch.voiceEnd) }} data-post-lane-muffle="" />} + {sch.duck && <div className="absolute inset-y-0 bg-gradient-to-r from-sky-500/15 to-transparent" style={{ left: pct(sch.voiceEnd), width: pct(sch.rampEnd - sch.voiceEnd) }} data-post-lane-ramp="" />} + {plan.steps.map((st, j) => ( + <div key={j} className="absolute bottom-0 h-2 border-l border-black/50 bg-[var(--color-sel)]/40" style={{ left: pct(st.at), width: pct(st.seconds) }} title={`${st.kind} ${st.seconds.toFixed(1)} s`} /> + ))} + <div + className="absolute inset-y-1 cursor-grab rounded bg-amber-400/20 ring-1 ring-amber-400/60" + style={{ left: pct(lead), width: pct(picked.seconds) }} + onPointerDown={(e) => { + e.stopPropagation(); + (e.currentTarget.parentElement as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { x: e.clientX, lead, w: (e.currentTarget.parentElement as HTMLElement).getBoundingClientRect().width }; + }} + data-post-lane-voice="" + > + {tPeaks && ( + <Waveform view={{ from: 0, to: picked.seconds }} sel={{ from: 0, to: 0 }} cand={{ from: 0, to: 0 }} words={[]} peaks={tPeaks} playhead={null} onSel={() => {}} onReachEdge={() => {}} height={52} /> + )} + {(picked.parts ?? []).map((p) => ( + <span key={p.n} className="absolute inset-y-0 w-px bg-amber-200/70" style={{ left: `${(p.start / picked.seconds) * 100}%` }} title={`part ${p.n}`} /> + ))} + </div> + <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: pct(s) }} /> + </div> + </div> + )} + </section> + + {/* THE RECORDING SESSION. */} + <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-record="" data-post-record-phase={phase}> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">record your read</h2> + <select + value={mic.device} + onChange={(e) => void mic.open(e.target.value)} + onFocus={() => !mic.devices.length && void mic.open(ls.get(MIC_KEY) ?? undefined)} + data-post-record-mic="" + aria-label="microphone" + > + {!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 w-28 overflow-hidden rounded bg-black/40" aria-label="level" data-post-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"> + voice + <input + value={label} + onChange={(e) => { + setLabel(e.target.value.toLowerCase()); + ls.set(LABEL_KEY, e.target.value.toLowerCase()); + }} + className="w-24 rounded border border-seam bg-ground px-1 py-0.5" + data-post-record-label="" + /> + </label> + {mic.error && <span className="text-[var(--color-blocking,#c33)]">{mic.error}</span>} + </div> + {/* The teleprompter: every part, the one being read large. */} + <ol className="m-0 max-h-64 list-none space-y-1 overflow-auto p-0" data-post-teleprompter=""> + {parts.map((p, i) => ( + <li + key={p.n} + className={cn("cursor-pointer rounded px-2 py-1", i === part ? "bg-amber-400/15 text-[15px] leading-snug text-text" : "text-text-2", blobs[i] && "border-l-2 border-emerald-500")} + onClick={() => phase === "idle" && setPart(i)} + data-post-part={p.n} + data-post-part-current={i === part ? "1" : undefined} + data-post-part-recorded={blobs[i] ? "1" : undefined} + > + {parts.length > 1 && <span className="micro mr-1">{p.n}.</span>} + {p.text} + </li> + ))} + {!parts.length && <li className="text-text-2">no script yet — write it under “script” below</li>} + </ol> + <div className="flex flex-wrap items-center gap-1.5"> + {phase === "count" && ( + <span className="text-[18px] font-bold tabular-nums" data-post-record-count={count}> + {count} + </span> + )} + <button type="button" className={cn(buttonVariants({ variant: "go", size: "sm" }))} disabled={phase !== "idle" || !parts.length} onClick={() => void record()} data-post-record-start=""> + {blobs[part] ? "Redo part" : parts.length > 1 ? `Record part ${part + 1}` : "Record"} + </button> + <button type="button" className={btn} disabled={phase !== "recording"} onClick={() => void stop()} data-post-record-stop=""> + Stop + </button> + {parts.length > 1 && ( + <button type="button" className={btn} disabled={phase !== "idle" || part >= parts.length - 1} onClick={() => setPart((p) => p + 1)} data-post-record-next-part=""> + Next part + </button> + )} + {blobs[part] && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <audio src={blobs[part]!.url} controls className="h-7" data-post-record-playback={part + 1} /> + )} + <button type="button" className={cn(buttonVariants({ variant: "go", size: "sm" }))} disabled={!allIn || phase !== "idle"} onClick={() => void keep()} data-post-record-keep=""> + {phase === "saving" ? "Saving…" : "Keep"} + </button> + <button + type="button" + className={btn} + disabled={!blobs.some(Boolean) || phase !== "idle"} + onClick={() => { + blobs.forEach((b) => b && URL.revokeObjectURL(b.url)); + setBlobs([]); + setPart(0); + }} + data-post-record-discard="" + > + Discard + </button> + {phase === "recording" && <span className="text-red-400" data-post-recording="">● recording part {part + 1}</span>} + </div> + </section> + + {/* TAKES, THE SCRIPT, A RE-TAKE WITH DIRECTION. */} + <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-takes=""> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">takes</h2> + <label className="flex items-center gap-1"> + <input type="checkbox" checked={n.approved === true} disabled={!picked} onChange={(e) => void set({ approved: e.target.checked ? true : null })} data-post-approve="" /> + approved + </label> + <label className="flex items-center gap-1"> + <input type="checkbox" checked={n.off !== true} disabled={!takes.length} onChange={(e) => void set({ off: e.target.checked ? null : true })} data-post-narrated="" /> + narrated + </label> + <button type="button" className={btn} onClick={() => void post({ op: "undo" }).then((j) => j && window.location.reload())} data-post-undo=""> + Undo last change + </button> + </div> + <ul className="m-0 list-none space-y-1 p-0"> + {takes.map((t, i) => ( + <li key={t.file} className={cn("rounded px-2 py-1", picked?.index === i && "bg-[var(--color-sel)]/15")} data-post-take={i + 1} data-post-take-picked={picked?.index === i ? "1" : undefined} data-post-take-engine={t.engine}> + <div className="flex flex-wrap items-center gap-2"> + <span className="font-mono">#{i + 1}</span> + <span>{t.engine === "recorded" ? `recorded · ${t.voice ?? t.label ?? "?"}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`}</span> + <span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span> + {/* eslint-disable-next-line jsx-a11y/media-has-caption */} + <audio src={fileUrl(project, t.file)} controls preload="none" className="h-7" data-post-take-audio={i + 1} /> + <button type="button" className={btn} disabled={picked?.index === i} onClick={() => void set({ pick: i })} data-post-take-pick={i + 1}> + Pick + </button> + {t.note && <span className="text-text-2">“{t.note}”</span>} + </div> + {(t.parts?.length ?? 0) > 1 && ( + <ol className="m-0 mt-1 list-none space-y-0.5 pl-6 text-text-2" data-post-take-parts={i + 1}> + {t.parts!.map((p) => ( + <li key={p.n} className="flex items-center gap-2"> + <span className="font-mono">{p.n}.</span> + <span className="truncate">{p.text ?? ""}</span> + <span className="tabular-nums">{p.start.toFixed(1)}+{p.seconds.toFixed(1)} s</span> + {p.file && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <audio src={fileUrl(project, p.file)} controls preload="none" className="h-6" /> + )} + </li> + ))} + </ol> + )} + </li> + ))} + {!takes.length && <li className="text-text-2">no take yet: record one above, or ask the editor for a placeholder below</li>} + </ul> + <label className="block"> + <span className="micro">script — the post, verbatim; add emotion with &lt;sigh&gt; &lt;laugh&gt; &lt;chuckle&gt; &lt;groan&gt; &lt;gasp&gt;</span> + <textarea value={script} onChange={(e) => setScript(e.target.value)} rows={4} className="mt-1 w-full rounded border border-seam bg-ground px-2 py-1" data-post-script="" /> + </label> + <div className="flex flex-wrap items-center gap-1.5"> + <button type="button" className={btn} disabled={script === (n.script ?? "")} onClick={() => void set({ script })} data-post-script-save=""> + Save script + </button> + <input value={dir.note} onChange={(e) => setDir({ ...dir, note: e.target.value })} placeholder="direction (kept with the take)" className="min-w-0 flex-1 rounded border border-seam bg-ground px-1.5 py-0.5" data-post-retake-note="" /> + <input value={dir.voice} onChange={(e) => setDir({ ...dir, voice: e.target.value })} placeholder={String(k.voice)} className="w-16 rounded border border-seam bg-ground px-1 py-0.5" aria-label="voice" data-post-retake-voice="" /> + <button type="button" className={btn} disabled={!script.trim() || job?.state === "running"} onClick={() => void retake()} data-post-retake=""> + {job?.state === "running" ? "Synthesizing on the editor…" : "Re-take with direction"} + </button> + {job?.state === "failed" && <span className="text-[var(--color-blocking,#c33)]">{job.error}</span>} + </div> + </section> + + {/* THE MIX, this post's. */} + <section className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-mix-knobs=""> + <h2 className="micro m-0 w-full">the mix (this post; absent: the cut's)</h2> + {mixKnob("wet", "wet", { step: 0.05, min: 0, max: 1 })} + {mixKnob("lead", "lead", { step: 0.05, min: 0, max: 5 })} + {mixKnob("tail", "tail", { step: 0.05, min: 0, max: 5 })} + {mixKnob("ramp", "ramp", { step: 0.1, min: 0, max: 5 })} + {mixKnob("linger", "linger", { step: 0.1, min: 0, max: 30 })} + {mixKnob("short", "short clip", { options: ["hold", "loop"] })} + {mixKnob("attach", "attachment", { options: ["under", "after"] })} + {mixKnob("clip", "clip", { options: ["read", "full"] })} + </section> + {status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>} + {error && ( + <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-narration-error=""> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/components/projects/bench/benchMedia.ts b/umtool/components/projects/bench/benchMedia.ts @@ -123,3 +123,29 @@ export function renderedFileMedia({ peaksOnSource: (p) => peaksOnSource(p, span, map), }; } + +/** + * A FILE OF THE PROJECT on its own clock (the post bench, lane/post-narration): + * a post item's attachment or a narration take -- its seconds are its own, so + * every mapping is the identity. `seconds` its length. + */ +export function projectFileMedia({ project, path, seconds, v = null }: { project: string; path: string; seconds: number; v?: string | number | null }): BenchMedia { + const q = `project=${enc(project)}&path=${enc(path)}${v ? `&v=${enc(String(v))}` : ""}`; + const id = (t: number) => t; + const span = { from: 0, to: seconds }; + return { + kind: "file", + key: `${path}|${v ?? ""}`, + src: `/api/report/file?${q}`, + span, + clock: span, + clockOf: id, + sourceOfClock: id, + elOf: id, + clockOfEl: id, + clockGaps: (gaps) => gaps, + audioUrl: (s) => `/api/report/audio?${q}&from=${s.from}&to=${s.to}`, + peaksUrl: `/api/report/peaks?${q}&from=0&to=${seconds}`, + peaksOnSource: (p) => p, + }; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -18,7 +18,7 @@ import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; import path from "node:path"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; @@ -1357,10 +1357,15 @@ const server = http.createServer((req, res) => { "-ac", "1", "-c:a", "pcm_s16le", wav, ], { stdio: "inherit" }); if (r.status !== 0) return json(res, 500, { ok: false, error: "ffmpeg failed writing the stub's voice" }); + // `out`: the editor copies its result there (a post item's take, lane/post-narration). + if (typeof body.out === "string" && path.isAbsolute(body.out)) { + mkdirSync(path.dirname(body.out), { recursive: true }); + copyFileSync(wav, body.out); + } ttsJobs.set(id, { polls: 0, result: { - wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0, + wav: typeof body.out === "string" && path.isAbsolute(body.out) ? body.out : wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0, sha: id, sampleRate: 48000, speed: body.speed ?? 1, // The editor's own line, which umtool uses verbatim. disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice ?? "af_heart"})`, diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -54,6 +54,7 @@ import { makeCutEditingFixture } from "./cut-editing-fixture.mjs"; import { makeReelFixture } from "./reel-fixture.mjs"; import { makeIntakeFixture } from "./intake-fixture.mjs"; import { makePostItemsFixture } from "./post-items-fixture.mjs"; +import { makePostNarrationFixture } from "./post-narration-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1910,6 +1911,8 @@ makeReelFixture({ reports, deckManifest }); makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Post items (report-to-video/post-item.mjs): a cut mixing a clip and posts played as items, a synthesized posts archive (post-items.spec.ts). makePostItemsFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Narrated post items (report-to-video/post-narration.mjs): a take read over a video, four pictures cycling (post-narration.spec.ts). +makePostNarrationFixture({ reports, deckManifest }); // Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut, // undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1 // window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it). diff --git a/umtool/e2e/fixtures/post-narration-fixture.mjs b/umtool/e2e/fixtures/post-narration-fixture.mjs @@ -0,0 +1,66 @@ +// NARRATED POST ITEMS (report-to-video/post-narration.mjs): a posts cut whose +// first item reads a take over its video (post-narration.spec.ts). +// +// post-narration-fixture p-vid a 4 s video with a 440 Hz tone, narrated +// by a 2 s take (a 262 Hz tone): the muffle +// from 0 to lead + 2 + tail = 2.7 s, the ramp +// to 3.5 s, clean after; a long script of two +// paragraphs (two parts to record) +// p-pics four pictures, un-narrated: one card, the +// pictures cycling beside it +// p-txt words only, a script and no take +// the deck on. WRITES its manifest: the spec puts +// it back before each test. +// +// Synthetic, like every fixture. +import { mkdirSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +const ff = (args) => { + const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]); + if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`); +}; + +/** @param {{ reports: string, deckManifest: Function }} o */ +export function makePostNarrationFixture({ reports, deckManifest }) { + const name = "post-narration-fixture"; + const dir = path.join(reports, name); + const media = path.join(dir, "posts-media", "narrchan-x"); + for (const id of ["11", "12"]) mkdirSync(path.join(media, id), { recursive: true }); + ff([ + "-f", "lavfi", "-i", "testsrc=size=320x180:rate=30:duration=4", + "-f", "lavfi", "-i", "sine=frequency=440:duration=4", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", "-shortest", path.join(media, "11", "11_1.mp4"), + ]); + for (const [k, c] of ["red", "green", "blue", "yellow"].entries()) { + ff(["-f", "lavfi", "-i", `color=c=${c}:size=320x180`, "-frames:v", "1", path.join(media, "12", `12_${k + 1}.png`)]); + } + const takes = path.join(dir, "narration", "posts", "11"); + mkdirSync(takes, { recursive: true }); + ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", path.join(takes, "take-1.orpheus-zac.wav")]); + const base = (id, text, o = {}) => ({ + type: "post", id, post: `narrchan-x/${id.slice(2)}`, platform: "x", author: "Narr Subject", handle: "narrsubject", + date: "2026-10-30T10:00:00.000Z", text, url: `https://x.com/narrsubject/status/${id}`, engagement: { likes: 4 }, subjects: ["narrsubject"], ...o, + }); + const timeline = [ + base("p-11", "The video speaks for itself.", { + post: "narrchan-x/11", + media: [{ src: "posts-media/narrchan-x/11/11_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true }], + narration: { + script: "The video speaks for itself.\n\nAnd a second paragraph, read as its own part.", + takes: [{ file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 2, script: "The video speaks for itself.", at: "2026-11-02T00:00:00.000Z" }], + pick: 0, + }, + }), + base("p-12", "Four pictures of the thing, one after another, while this is read.", { + post: "narrchan-x/12", + media: [1, 2, 3, 4].map((k) => ({ src: `posts-media/narrchan-x/12/12_${k}.png`, kind: "image", width: 320, height: 180 })), + }), + base("p-13", "Words only, waiting for a voice.", { post: "narrchan-x/13", narration: { script: "Words only, waiting for a voice." } }), + ]; + const m = deckManifest(name, "The Post Narration Fixture", timeline); + m.provenance = { ...m.provenance, channelSlug: "narrchan-x" }; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { dir }; +} diff --git a/umtool/e2e/post-items.spec.ts b/umtool/e2e/post-items.spec.ts @@ -12,10 +12,12 @@ import * as urls from "./urls"; // self-reply under its parent), p-img (a picture), p-vid (a 4 s video with a // tone, a reply to a private account) from the synthesized archive postchan-x. // -// The rule's seconds (reading 1 s + words / 3, at least 3; a parent 1-4 s; -// then the attachments): p-txt 12 words + a 7-word parent = 5 + 2.33 = 7.33; -// p-img 5 words = 3 + a picture 3.5 = 6.5; p-vid 7 words + a 4-word parent = -// 3.33 + 1.33 = 4.67 to read, then the video's 4 s = 8.67. +// The rule's seconds (the pacing rule, 2 Nov: the item is its reading time -- +// 1 s + words / 3, at least 3; a parent 1-4 s -- the attachments playing +// beside the words, not after them): p-txt 12 words + a 7-word parent = 5 + +// 2.33 = 7.33; p-img 5 words = 3 (its picture up the whole time); p-vid 7 +// words + a 4-word parent = 3.33 + 1.33 = 4.67, its 4 s video from the first +// frame, the last frame held. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -59,8 +61,8 @@ test("the Cut tab lists the mixed cut: the clip, then post rows with their glyph await expect(page.locator('[data-entry="p-img"] [data-post-carries]')).toHaveText("image"); await expect(page.locator('[data-entry="p-vid"] [data-post-carries]')).toHaveText("video"); await expect(page.locator('[data-entry="p-txt"] [data-post-seconds]')).toHaveText("7.3s"); - await expect(page.locator('[data-entry="p-img"] [data-post-seconds]')).toHaveText("6.5s"); - await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("8.7s"); + await expect(page.locator('[data-entry="p-img"] [data-post-seconds]')).toHaveText("3.0s"); + await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("4.7s"); await expect(page.locator('[data-entry="p-vid"]')).toContainText("Yes, and here is the video."); // A post item takes a section's place like a clip: the bar after c01 opens on p-txt. await expect(page.locator('[data-entry="p-vid"] [data-post-bench-link]')).toHaveAttribute("href", urls.postBenchHref(PROJECT, "p-vid")); @@ -75,7 +77,8 @@ test("Play plays a post item: its card, the private parent blurred, its video pl const player = page.locator('[data-post-play="p-vid"]'); await expect(player).toBeVisible(); await expect(player).toHaveAttribute("data-post-layout", "side"); - await expect(player).toHaveAttribute("data-post-step", "read"); + // One layout: the video beside the card from the item's first frame (not after a reading beat). + await expect(player).toHaveAttribute("data-post-step", "video"); // The card is the build's page: the post's words, its counts, the parent above it blurred. const card = page.frameLocator('[data-post-card-frame="read"]'); await expect(card.locator('[data-post-card="p-vid"]')).toBeVisible(); @@ -83,16 +86,15 @@ test("Play plays a post item: its card, the private parent blurred, its video pl await expect(card.locator('[data-post-parent="0"][data-redacted]')).toHaveCount(1); await expect(card.locator("body")).not.toContainText("someone_private"); await expect(card.locator("body")).not.toContainText("Private Person"); - // Its first frame is up beside the card while the words are read. + // Paused: its first frame is up beside the card. await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "0"); const t0 = Number(await root(page).getAttribute("data-play-t")); await page.locator("[data-play-toggle]").click(); - await expect(player).toHaveAttribute("data-post-step", "video", { timeout: 15_000 }); - await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "1"); + await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "1", { timeout: 15_000 }); await expect.poll(async () => page.locator('[data-post-video="0"]').evaluate((v: HTMLVideoElement) => v.currentTime), { timeout: 10_000 }).toBeGreaterThan(0.5); expect(await page.locator('[data-post-video="0"]').evaluate((v: HTMLVideoElement) => v.muted)).toBe(false); const t1 = Number(await root(page).getAttribute("data-play-t")); - expect(t1).toBeGreaterThan(t0 + 4); + expect(t1).toBeGreaterThan(t0); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-play.png") }); await page.locator("[data-play-toggle]").click(); // Edit this post opens its bench, and Back to the cut returns to it. @@ -106,10 +108,11 @@ test("the post bench trims the video attachment and saves it; the cut's seconds await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.postBenchHref(PROJECT, "p-vid")); await expect(page.locator('[data-post-bench="p-vid"]')).toBeVisible(); - await expect(page.locator("[data-post-bench-rule]")).toHaveText("8.7 s"); + await expect(page.locator("[data-post-bench-rule]")).toHaveText("4.7 s"); await page.locator('[data-post-bench-start="0"]').fill("1"); await page.locator('[data-post-bench-end="0"]').fill("3"); - await expect(page.locator("[data-post-bench-rule]")).toHaveText("6.7 s"); + // The item is its read: a shorter clip holds its last frame, the length stays. + await expect(page.locator("[data-post-bench-rule]")).toHaveText("4.7 s"); await expect(page.locator('[data-post-bench-step="video"]')).toContainText("video 2.0 s"); await page.locator('[data-post-bench-sound="0"]').uncheck(); await page.locator("[data-post-bench-save]").click(); @@ -123,7 +126,7 @@ test("the post bench trims the video attachment and saves it; the cut's seconds expect(timeline().find((e) => e.id === "p-vid")!.media?.[0]?.end).toBe(3); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-bench.png") }); await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); - await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("6.7s"); + await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("4.7s"); }); test("umtool posts reel adds only what the cut does not play yet, in one write", async () => { diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -0,0 +1,165 @@ +import { test, expect, type Page } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// NARRATED POST ITEMS (report-to-video/post-narration.mjs; knobs.md, "A narrated +// post item"). Fixture: e2e/fixtures/post-narration-fixture.mjs -- p-11 a 4 s +// video narrated by a 2 s take (muffled 0-2.7 s, the ramp to 3.5 s, clean after; +// the item 0.4 + 2 + 0.3 + 1.8 = 4.5 s), p-12 four pictures un-narrated, p-13 +// words and a script, no take. The editor is the suite's stub (its tts op +// writes a tone where `out` says). +// +// POST_NARRATION_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const DIR = path.join(FIXTURE, "reports", "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.POST_NARRATION_SHOTS ?? null; +/** A voice for the fake microphone: a 1 kHz tone, two seconds. */ +const MIC_WAV = path.join(FIXTURE, "post-narration-mic.wav"); + +type Take = { file: string; engine?: string; voice?: string; note?: string; seconds: number }; +type Entry = { id: string; narration?: { script?: string; takes?: Take[]; pick?: number; approved?: boolean } }; +const timeline = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline; +const narr = (id: string) => timeline().find((e) => e.id === id)!.narration!; + +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]); +} + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + 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 }); +}); + +const root = (page: Page) => page.locator("[data-play-cut]"); + +test("Play plays the take over the attachment, muffled under the read, then opens up clean", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); + await expect(root(page)).toHaveAttribute("data-play-item", "p-11"); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-narrated", "1"); + // The video beside the card from the item's first frame; the muffle on. + await expect(player).toHaveAttribute("data-post-step", "video"); + await expect(player).toHaveAttribute("data-post-mix-phase", "muffled"); + await expect(player).toHaveAttribute("data-post-wet", "0.3"); + await expect(player).toHaveAttribute("data-post-dry", "0"); + await expect(page.locator("[data-post-narration-audio]")).toHaveAttribute("data-post-narration-audio", "narration/posts/11/take-1.orpheus-zac.wav"); + await page.locator("[data-play-toggle]").click(); + await expect(player).toHaveAttribute("data-post-narration-playing", "1", { timeout: 15_000 }); + await expect.poll(async () => page.locator("[data-post-narration-audio]").evaluate((a: HTMLAudioElement) => a.currentTime), { timeout: 10_000 }).toBeGreaterThan(0.3); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-play-muffled.png") }); + // Past the words and the tail: the ramp, then clean. + await expect(player).toHaveAttribute("data-post-mix-phase", /ramp|clean/, { timeout: 15_000 }); + await expect(player).toHaveAttribute("data-post-narration-playing", "0"); + await page.locator("[data-play-toggle]").click(); +}); + +test("four pictures cycle beside the card while it is read; the words stay up the whole item", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.postBenchHref(PROJECT, "p-12")); + await expect(page.locator('[data-post-bench="p-12"]')).toBeVisible(); + const player = page.locator('[data-post-play="p-12"]'); + await expect(player).toHaveAttribute("data-post-layout", "side"); + const scrub = page.locator("[data-post-bench-scrub]"); + const seen: string[] = []; + for (const [k, at] of [0.2, 2, 4.5].entries()) { + await scrub.fill(String(at)); + await expect(player).toHaveAttribute("data-post-step", "image"); + await expect(page.frameLocator('[data-post-card-frame="read"]').locator("[data-post-words]")).toContainText("Four pictures of the thing"); + seen.push(String(await page.locator("[data-post-image]").first().getAttribute("src"))); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `post-narration-pictures-${k + 1}.png`) }); + } + expect(new Set(seen).size).toBe(3); +}); + +test("the post bench: the lanes, a re-take with direction (the editor's tts job), Pick and Approve", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1400 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const panel = page.locator('[data-post-narration="p-11"]'); + await expect(panel).toBeVisible(); + await expect(panel.locator('[data-post-lane="attachment"]')).toBeVisible(); + await expect(panel.locator('[data-post-lane="read"]')).toBeVisible(); + await expect(panel.locator("[data-post-lane-muffle]")).toBeVisible(); + await expect(panel.locator("[data-post-take]")).toHaveCount(1); + await expect(panel.locator('[data-post-take="1"]')).toHaveAttribute("data-post-take-picked", "1"); + // A take plays: its file is served as audio. + const res = await page.request.get(`/api/report/file?project=${encodeURIComponent(PROJECT)}&path=${encodeURIComponent("narration/posts/11/take-1.orpheus-zac.wav")}`); + expect(res.status()).toBe(200); + expect(res.headers()["content-type"]).toBe("audio/wav"); + await expect(panel.locator("[data-post-progress-recorded]")).toHaveText("0"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench.png"), fullPage: true }); + // Re-take with direction: queued on the editor, kept when done, picked, its note with it. + await panel.locator("[data-post-retake-note]").fill("slower, a sigh first"); + await panel.locator("[data-post-script]").fill("<sigh> The video speaks for itself."); + await panel.locator("[data-post-retake]").click(); + await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 20_000 }); + const n = narr("p-11"); + expect(n.takes![1]).toMatchObject({ file: "narration/posts/11/take-2.orpheus-zac.wav", engine: "orpheus", voice: "zac", note: "slower, a sigh first" }); + expect(n.pick).toBe(1); + expect(n.script).toBe("<sigh> The video speaks for itself."); + await expect(page.locator('[data-post-narration="p-11"] [data-post-take="2"]')).toHaveAttribute("data-post-take-picked", "1"); + // Pick the first back; approve it. + await page.locator('[data-post-take-pick="1"]').click(); + await expect(page.locator('[data-post-take="1"]')).toHaveAttribute("data-post-take-picked", "1"); + expect(narr("p-11").pick).toBe(0); + await page.locator("[data-post-approve]").check(); + await expect.poll(() => narr("p-11").approved).toBe(true); + // The mix: a knob is one write. + await page.locator('[data-post-mix="wet"]').fill("0.2"); + await page.locator('[data-post-mix="wet"]').blur(); + await expect.poll(() => (timeline().find((e) => e.id === "p-11")!.narration as Record<string, unknown>).wet).toBe(0.2); +}); + +test.describe("the recording session", () => { + 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("record a long script part by part, play it back, Keep: a recorded take, picked, and it plays", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1400 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const rec = page.locator("[data-post-record]"); + await expect(rec.locator("[data-post-part]")).toHaveCount(2); + await expect(rec.locator('[data-post-part="1"]')).toHaveAttribute("data-post-part-current", "1"); + await rec.locator("[data-post-record-start]").click(); + await expect(rec).toHaveAttribute("data-post-record-phase", "recording", { timeout: 10_000 }); + await expect(rec.locator("[data-post-recording]")).toBeVisible(); + await page.waitForTimeout(1200); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-recording.png"), fullPage: true }); + await rec.locator("[data-post-record-stop]").click(); + // Auto-advanced to the second part; the first is recorded and plays back. + await expect(rec.locator('[data-post-part="2"]')).toHaveAttribute("data-post-part-current", "1"); + await expect(rec.locator('[data-post-part="1"]')).toHaveAttribute("data-post-part-recorded", "1"); + await rec.locator("[data-post-record-start]").click(); + await expect(rec).toHaveAttribute("data-post-record-phase", "recording", { timeout: 10_000 }); + await page.waitForTimeout(1000); + await rec.locator("[data-post-record-stop]").click(); + await expect(rec.locator('[data-post-part="2"]')).toHaveAttribute("data-post-part-recorded", "1"); + await rec.locator("[data-post-record-keep]").click(); + const panel = page.locator('[data-post-narration="p-11"]'); + await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 }); + await expect(panel.locator('[data-post-take="2"]')).toHaveAttribute("data-post-take-engine", "recorded"); + await expect(panel.locator('[data-post-take="2"]')).toHaveAttribute("data-post-take-picked", "1"); + await expect(panel).toHaveAttribute("data-post-narration-plays", "recorded"); + const n = narr("p-11"); + 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); + // The bench's player plays it, as the render will. + await expect(page.locator("[data-post-narration-audio]")).toHaveAttribute("data-post-narration-audio", "narration/posts/11/take-2.recorded-operator.wav"); + await expect(panel.locator("[data-post-progress-recorded]")).toHaveText("1"); + }); +}); diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs @@ -221,3 +221,29 @@ test("the authors' pictures: posts avatar sets one (copied in), posts avatars co assert.equal((await cli(["avatar", "av", "BigOrg", "off"])).code, 0); assert.equal((await manifest(p)).postAvatars.BigOrg, undefined); }); + +test("a RECORDING kept part by part: each trimmed of its silence, joined with the pauses, levelled, picked", async () => { + const { keepRecording, trimSpan } = await import("./postRecord.mjs"); + assert.deepEqual(trimSpan([{ s: 0, e: 0.5 }, { s: 1.5, e: 2 }], 2), { from: 0.42, to: 1.65 }); + assert.deepEqual(trimSpan([], 2), { from: 0, to: 2 }); + const p = await project("rec", [item("1", { narration: { script: "one.\n\ntwo.", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 2, lufs: -21.3 }] } })]); + const parts = []; + for (const k of [1, 2]) { + const f = path.join(ROOT, `rec-${k}.wav`); + ff(["-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono:d=0.6", "-f", "lavfi", "-i", "sine=f=300:d=1:r=44100", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono:d=0.6", "-filter_complex", "[1:a]volume=0.1[s];[0:a][s][2:a]concat=n=3:v=0:a=1", f]); + parts.push({ file: f, text: k === 1 ? "one." : "two.", para: k - 1 }); + } + const r = await keepRecording(p, (await manifest(p)).timeline[0], parts, { manifest: await manifest(p) }); + assert.equal(r.take.file, "narration/posts/1/take-2.recorded-operator.wav"); + assert.equal(r.take.engine, "recorded"); + assert.equal(r.target, -21.3); + assert.equal(r.take.parts.length, 2); + assert.equal(r.take.parts[1].gapBefore, 0.6); + // Two 1 s words with a breath of room each, and the paragraph's pause. + assert.ok(r.take.seconds > 2.6 && r.take.seconds < 3.1, String(r.take.seconds)); + assert.ok(Math.abs(r.take.lufs - -21.3) < 1.5, String(r.take.lufs)); + const n = (await manifest(p)).timeline[0].narration; + assert.equal(n.pick, 1); + assert.equal(n.takes[1].voice, "operator"); + assert.equal(postItemPlan((await manifest(p)).timeline[0]).narration.seconds, r.take.seconds); +});