Archilyzer · Source

archilyzer

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

commit e87982fb2db55c5f873b1b4b9dc6cfa152449bb4
parent 238df6e40ae7b649815349dddce07e4e7791cd54
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 18:05:14 -0500

Merge lane/preview-render: fast feedback renders -- take --preview (the same 1920x1080 composition, the final picture at a 1280x720 veryfast tier, chunks keyed apart in out/preview/, everything else shared) and take --changes (only the items changed since the take it came from, with context, labelled with their full-cut times, into <slug>.changes.mp4 + changes.json); queue steps, take-card and Play buttons, take status (operator, 5 Nov: "make fast preview render a first class feature because these huge feedback loops are a nightmare")

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Aumtool/app/api/report/takes/fast/route.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/FastRenders.tsx | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakesBench.tsx | 3+++
Mumtool/components/projects/review/PlayCut.tsx | 10++++++++++
Mumtool/docs/cli.md | 4+++-
Mumtool/docs/knobs.md | 30++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 17+++++++++++++++++
Aumtool/e2e/preview-render.spec.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/queue/cli.mjs | 42+++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/takeCli.mjs | 48++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/takeFrom.mjs | 18+++++++++++++++---
Mumtool/lib/report/takeMaker.mjs | 54++++++++++++++++++++++++++++++++++++------------------
Aumtool/lib/report/takePreview.mjs | 819+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takePreview.test.mjs | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
17 files changed, 1723 insertions(+), 35 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool: a take can be previewed fast, and only what changed can be rendered.** A re-render of a 40-minute cut took 5–40 minutes even reusing everything it could, because its picture is encoded at 1920×1080 on a slow preset, and the operator walked each render and waited for the next. `umtool take <p> --id <t> --preview` renders the take (a draft too) composed exactly as its full render -- the same layout, segments, chrome and sound, so timing and levels judged on it hold -- with only the final picture at 1280×720, x264 veryfast, crf 26 (`render.preview`), into `takes/<t>/out/<slug>.preview.mp4`; the take's full render and its records are never touched, and a preview's encoded chunks are keyed apart and never stand in for a full render's. `umtool take <p> --id <t> --changes [--from <t0>] [--pad 3]` renders a reel of ONLY the items that changed against the take it was made from (added, re-read, re-picked, re-voiced, trimmed, held, fx, …), each with its neighbours, cut to the item ± 3 s and labelled with its time in the full cut ("21:19 · p-… · re-voiced"), into `takes/<t>/out/<slug>.changes.mp4`, and lists them in `takes/<t>/changes.json`. Both run through the queue (`umtool queue add -- take … --preview`), the take card's **Preview render** and **Render changes** (and Play's **Fast render**) queue them and show their state, the file's path with Copy and the file itself, and `umtool take status … --json` reports them. umtool/docs/report-video.md, knobs.md, cli.md. - **umtool: a reel can end on an outro card, and open on an intro its master does not have.** A trailer stopped on its last beat, and a reel with "open on the brand intro" was refused when the take had been rendered without one (the Mr. Obvious X trailer). `umtool trailer-beats <p> --reel <r> outro '{"title":"…","image":"promo/thumbnail.jpg"}'` (`on`, `off`, `none`) ends the reel on a card: the full video's title large (default the reel's title, else the project's), "Full video on the channel" under it (`text`), the site's name small in its accent, over the image blurred and darkened (or the dark ground), 3.5 s (`seconds`) with a 0.5 s fade in from the last beat while its sound fades out, then held to the end; `ls` says `· outro 3.5 s` and the length against the limit counts it. With `intro on` and no intro in the master, the take's `render.intro` (else the dark boot with the mark on the chime) is rendered for the reel; `intro '{"style":"boot-dark","mark":"chime","site":"anilyzer"}'` gives a reel an intro of its own. `umtool trailer --reel` cuts both in; a reel with neither is cut exactly as before. - **umtool: the background no longer changes shade between post items.** In a render, the page behind a post's card brightened at the cut from a post with a JPEG picture to a plain text post (the Mr. Obvious cut, at 37:00). ffmpeg had encoded the item with the picture in full range, every other item in limited range, and a player reads one range for the whole video. Every post item and combo badge is now encoded in limited range, so the page is the palette's background in every item; the items built full range before are rebuilt on the next render, and nothing else is. - **umtool: a report video can end on a video of the project, full frame, with its own sound.** A meme the subject posted (the Puss in Boots clip of the Mr. Obvious cut) could not be played as itself: `image` is a still and a clip is a corpus window inside the deck. A `video` timeline entry plays a project file's span (`from`, `to`; absent: the file's end) as the whole frame (`fit: contain`, pillarboxed on black, or `cover`), with NOTHING drawn over it -- no deck, header, QR, rail, counters, captions or any overlay layer, in the render and in Play. The item before it (its chrome too) fades to black and the video fades up (`enter`, 0.5 s each; `"cut"` opts out), without shortening the video; as the last entry the cut ends on its final frame (no end fade). Its sound is levelled like a clip's, with an optional bass boost before the level (`audio.bass`, dB). `umtool timeline <p> [--take <t>] add-video <src> --from 32.26 --bass 8` adds one; `set-video <id> key=value` sets its knobs. diff --git a/umtool/app/api/report/takes/fast/route.ts b/umtool/app/api/report/takes/fast/route.ts @@ -0,0 +1,87 @@ +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { projectRef } from "@/lib/projects"; +import { kickQueue, queueDir } from "@/lib/queue/runner"; +import { addStep, listSteps, resolveStep } from "@/lib/queue/store.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; +import { fastKindOf, fastRenders, previewPaths } from "@/lib/report/takePreview.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; + +export const dynamic = "force-dynamic"; + +// A TAKE'S FAST-FEEDBACK RENDERS (lib/report/takePreview.mjs): its preview at the preview tier and its +// changes reel, never its deliverable. +// +// GET ?project&take { preview, changes, from, steps }: each one's record and output +// (local path), the queue step still to run one, the take the +// reel compares with by default +// GET ?project&take&file=preview|changes the mp4, range-served (to a <video>) +// POST { project, take, kind: "preview" | "changes", from? } +// a queue step of the FIXED command (lib/queue/store.mjs addStep): +// umtool take <p> --id <t> --preview [--from <t0>] +// umtool take <p> --id <t> --changes [--from <t0>] +// built here from names, never a command line sent by the page +const noStore = { "cache-control": "no-store" }; + +async function slugOf(dir: string) { + return readFile(/* turbopackIgnore: true */ path.join(dir, "video.manifest.json"), "utf8").then((t) => String(JSON.parse(t).slug ?? ""), () => ""); +} + +async function takeDoc(dir: string, take: string) { + return readFile(/* turbopackIgnore: true */ path.join(dir, "takes", take, "take.json"), "utf8").then((t) => JSON.parse(t) as Record<string, unknown>, () => null); +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const take = url.searchParams.get("take"); + if (!isTakeId(take)) return Response.json({ error: "not a take id" }, { status: 400 }); + const doc = await takeDoc(project.dir, take); + if (!doc) return Response.json({ error: `no take ${take}` }, { status: 404 }); + const slug = await slugOf(project.dir); + const file = url.searchParams.get("file"); + if (file) { + if (file !== "preview" && file !== "changes") return new Response("file is preview or changes", { status: 400 }); + const p = previewPaths(path.join(project.dir, "takes", take), slug); + const abs = file === "preview" ? p.previewMp4 : p.changesMp4; + const st = await stat(/* turbopackIgnore: true */ abs).catch(() => null); + if (!st?.isFile()) return new Response(`take ${take} has no ${file} render`, { status: 404 }); + return rangeResponse(request, { abs, size: st.size, headers: { "content-type": "video/mp4", "accept-ranges": "bytes", "cache-control": "private, no-store", "x-video-mtime": String(st.mtimeMs) } }); + } + const got = await fastRenders(path.join(project.dir, "takes", take), slug); + type Step = { qid: string; state: string; argv: string[]; error?: string | null; target?: { project?: string | null; take?: string | null } | null }; + const all = ((await listSteps(queueDir()).catch(() => [])) as Record<string, unknown>[]).map((s) => resolveStep(s) as unknown as Step); + const steps = all + .filter((s) => s.target?.project === project.id && s.target?.take === take && fastKindOf(s.argv)) + .map((s) => ({ qid: s.qid, state: s.state, kind: fastKindOf(s.argv), error: s.error ?? null })); + const from = typeof doc.from === "string" ? doc.from : typeof doc.draftedFrom === "string" ? doc.draftedFrom : null; + return Response.json({ take, from, ...got, steps }, { headers: noStore }); +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; kind?: unknown; from?: unknown } | null; + const project = await projectRef(typeof body?.project === "string" ? body.project : ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const take = body?.take; + if (!isTakeId(take)) return Response.json({ error: "not a take id" }, { status: 400 }); + const kind = body?.kind; + if (kind !== "preview" && kind !== "changes") return Response.json({ error: "kind is preview or changes" }, { status: 400 }); + const from = body?.from ?? null; + if (from !== null && (!isTakeId(from) || from === take)) return Response.json({ error: "from is another take's id" }, { status: 400 }); + if (!(await takeDoc(project.dir, take))) return Response.json({ error: `no take ${take}` }, { status: 404 }); + if (from && !(await takeDoc(project.dir, from))) return Response.json({ error: `no take ${from}` }, { status: 404 }); + const argv = ["take", project.id, "--id", take, kind === "preview" ? "--preview" : "--changes", ...(from ? ["--from", from] : [])]; + try { + const step = await addStep(queueDir(), { + argv, + label: `${kind === "preview" ? "preview" : "changes reel"} of ${take}${from ? ` (against ${from})` : ""}`, + target: { project: project.id, take }, + by: "the umtool app (Takes)", + }); + kickQueue(); + return Response.json({ ok: true, qid: step.qid, argv }, { headers: noStore }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/components/projects/FastRenders.tsx b/umtool/components/projects/FastRenders.tsx @@ -0,0 +1,158 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// FAST FEEDBACK (lib/report/takePreview.mjs; operator, 5 Nov 2026): a take's two quick renders, each a +// step of the durable queue (POST /api/report/takes/fast, the fixed command `umtool take <p> --id <t> +// --preview | --changes [--from <t0>]`), their state inline, each output's local path with Copy, and the +// file itself played here. +// +// Preview render the whole take at the preview tier (1280×720, veryfast): out/<slug>.preview.mp4 +// Render changes only what changed against the take it was made from, each item ± 3 s, labelled +// with its time in the full cut: out/<slug>.changes.mp4 and changes.json +// +// Polls GET /api/report/takes/fast every 3 s only while a step is queued or a render runs. + +type Fast = { + state: string | null; + mp4: string | null; + mp4Bytes?: number | null; + seconds: number | null; + endedAt?: string | null; + error?: string | null; + log?: string | null; + list?: string | null; + items?: number | null; + from?: string | null; +} | null; + +type View = { take: string; from: string | null; preview: Fast; changes: Fast; steps: { qid: string; state: string; kind: "preview" | "changes"; error: string | null }[] }; + +const LIVE = new Set(["queued", "running", "waiting"]); + +function stateOf(kind: "preview" | "changes", v: View | null) { + const step = v?.steps.filter((s) => s.kind === kind).at(-1) ?? null; + const rec = v?.[kind] ?? null; + if (rec && (rec.state === "running" || rec.state === "waiting")) return { state: rec.state, step, rec }; + if (step && (step.state === "queued" || step.state === "running" || step.state === "blocked")) return { state: step.state, step, rec }; + return { state: rec?.state ?? null, step, rec }; +} + +function Copy({ text }: { text: string }) { + const [done, setDone] = useState(false); + return ( + <button + type="button" + data-action="copy-path" + className="ink-link text-[11px]" + onClick={() => { + void navigator.clipboard?.writeText(text).then(() => { + setDone(true); + setTimeout(() => setDone(false), 1500); + }, () => {}); + }} + > + {done ? "copied" : "Copy"} + </button> + ); +} + +export default function FastRenders({ project, take, compact = false }: { project: string; take: string; compact?: boolean }) { + const [view, setView] = useState<View | null>(null); + const [busy, setBusy] = useState<"preview" | "changes" | null>(null); + const [said, setSaid] = useState<string | null>(null); + const [playing, setPlaying] = useState<"preview" | "changes" | null>(null); + const [tick, setTick] = useState(0); + const load = useCallback(async () => { + const r = await fetch(`/api/report/takes/fast?${new URLSearchParams({ project, take })}`, { cache: "no-store" }).catch(() => null); + if (r?.ok) setView((await r.json()) as View); + }, [project, take]); + useEffect(() => { + void load(); + }, [load, tick]); + const live = (["preview", "changes"] as const).some((k) => LIVE.has(String(stateOf(k, view).state))); + useEffect(() => { + if (!live) return; + const t = setInterval(() => setTick((n) => n + 1), 3000); + return () => clearInterval(t); + }, [live]); + + const start = async (kind: "preview" | "changes") => { + setBusy(kind); + setSaid(null); + try { + const r = await fetch("/api/report/takes/fast", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, take, kind, ...(kind === "changes" && view?.from ? { from: view.from } : {}) }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; qid?: string }; + setSaid(r.ok ? `queued as ${j.qid}` : (j.error ?? `HTTP ${r.status}`)); + await load(); + } finally { + setBusy(null); + } + }; + + const row = (kind: "preview" | "changes", label: string, title: string) => { + const s = stateOf(kind, view); + const running = LIVE.has(String(s.state)); + const disabled = !!busy || running || (kind === "changes" && !view?.from); + return ( + <div key={kind} data-fast={kind} data-fast-state={s.state ?? "none"} className="flex flex-wrap items-center gap-1.5 text-[11px] text-[var(--color-dim)]"> + <button + type="button" + data-action={kind === "preview" ? "preview-render" : "render-changes"} + disabled={disabled} + title={kind === "changes" && !view?.from ? "this take does not record the take it was made from" : title} + onClick={() => void start(kind)} + className={buttonVariants({ size: "sm" })} + > + {label} + </button> + {s.state && ( + <span data-fast-said=""> + {s.step && running && s.step.state !== "running" ? `${s.state} (${s.step.qid})` : s.state} + {s.state === "failed" && s.rec?.error ? ` — ${s.rec.error}` : ""} + {s.state === "blocked" && s.step?.error ? ` — ${s.step.error}` : ""} + {s.state === "done" && s.rec?.seconds != null ? ` · ${Math.round(s.rec.seconds)} s` : ""} + {kind === "changes" && s.state === "done" && s.rec?.items != null ? ` · ${s.rec.items} piece(s) against ${s.rec.from}` : ""} + </span> + )} + {s.rec?.mp4 && !running && ( + <> + <code data-fast-path="" className="max-w-[28ch] truncate font-mono text-[10.5px]" title={s.rec.mp4}> + {s.rec.mp4} + </code> + <Copy text={s.rec.mp4} /> + <button type="button" data-action={`play-${kind}`} className="ink-link text-[11px]" onClick={() => setPlaying((p) => (p === kind ? null : kind))}> + {playing === kind ? "Hide" : "Play"} + </button> + </> + )} + </div> + ); + }; + + return ( + <div data-fast-renders={take} className={compact ? "flex flex-col gap-1" : "flex flex-col gap-1 border-t border-[var(--color-line)] pt-1.5"}> + {row("preview", "Preview render", "the whole take at 1280×720, fast: its full render untouched (umtool take … --preview)")} + {row("changes", "Render changes", `only what changed against ${view?.from ?? "its base"}, each item ± 3 s, labelled (umtool take … --changes)`)} + {said && <p data-fast-queued="" className="text-[11px] text-[var(--color-dim)]">{said}</p>} + {playing && view?.[playing]?.mp4 && ( + <video + data-fast-video={playing} + key={`${playing}-${view[playing]?.endedAt ?? ""}`} + src={`/api/report/takes/fast?${new URLSearchParams({ project, take, file: playing, v: String(view[playing]?.endedAt ?? "") })}`} + controls + autoPlay + preload="metadata" + playsInline + className="aspect-video w-full bg-black" + /> + )} + </div> + ); +} diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -17,6 +17,7 @@ import type { RenderView } from "@/lib/queue/view"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import { startTakeJob } from "./NewTakePanel"; import TakeActions from "./TakeActions"; +import FastRenders from "./FastRenders"; import TakeTools from "./TakeTools"; import { Advanced, Options, PanelSlot } from "@/components/ui/disclosure"; import { CancelRender, CancelSaidLine, CompareWith, ForkVariant, TakeWorkDirs, type CancelSaid, type CompareOption, type WorkDirs } from "./TakeVariants"; @@ -832,6 +833,8 @@ function TakeCard({ compact /> )} + {/* Fast feedback (takePreview.mjs): a preview of the whole take, a reel of what changed -- queue steps. */} + <FastRenders project={project} take={t.id} /> {(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && <CancelRender project={project} take={t.id} ready={ready} onSaid={setCancelSaid} />} <CancelSaidLine said={cancelSaid} /> {pickState?.stale && ( diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -25,6 +25,7 @@ import { useWaveZoom, ZoomControls } from "../bench/GapsZoom"; import { followVis, itemSections } from "@/lib/report/stripDrag.mjs"; import RejectClip from "./RejectClip"; import WhatPlays, { type WorkingCut } from "./WhatPlays"; +import FastRenders from "../FastRenders"; import { useCutApp } from "../cutApp/CutApp"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; import AddPost from "./AddPost"; @@ -1106,6 +1107,15 @@ export default function PlayCut({ <header className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-b border-seam px-4 py-2 max-md:-mx-4"> <h1 className="m-0 min-w-0 truncate font-display text-[17px] font-semibold tracking-[-0.01em] text-text">{view.title}</h1> <WhatPlays project={project} take={view.take} takes={view.takes} working={view.working ?? null} onNavigate={onNavigate} /> + {/* Fast feedback on the take playing (takePreview.mjs): its preview render and its changes reel, queued. */} + {view.take && ( + <details data-play-fast="" className="relative text-[11.5px]"> + <summary className="cursor-pointer text-muted hover:text-text">Fast render</summary> + <div className="absolute left-0 top-full z-30 mt-1 w-[min(420px,90vw)] rounded border border-seam bg-[var(--color-panel)] p-2 shadow-lg"> + <FastRenders project={project} take={view.take.id} compact /> + </div> + </details> + )} <span className="ml-auto font-mono text-[15px] tabular-nums text-text" data-play-clock=""> {runningTime(t)} <span className="text-muted">/ {runningTime(plan.total)}</span> </span> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -58,6 +58,8 @@ Inbox cannot disagree about what is wrong with one. | `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) | | `take <project> --id <id> … --uncensored` · build-video `--uncensored` | the **uncensored cut** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): the same cut with the post items' slur filter off -- `render.posts.slurs.on: false` in the take's patch (a `--rebuild` keeps it; a censored take is not rebuilt uncensored, **exit 2**: make a take of its own), its label gains "(uncensored)", take.json's `slurs` records `censored` or `uncensored`. The redaction of private words and censored attachments stay on | | `take <project> --id <id> --draft --from <take> [--label L] [--patch F \| --patch-json J \| --set p=v …]` | a **draft made from another take**: that take's style and patch (a `--patch` merged over it), its label "<that label> (from <take>)" unless `--label`, nothing rendered; its timeline is its own from then on, and its render's `--from` (segments reused) is a separate flag of the render ([take-scoped edits](#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits)) | +| `take <project> --id <id> --preview [--from <take>] [--at S --dur S \| --full] [--priority] [--json]` | the take's **preview**: the take as stored (a draft too, from its walked patch) composed exactly as its render is -- the same 1920×1080 layout, segments, chrome frames and sound -- with only its final picture encoded smaller and faster (`render.preview`: 1280×720, x264 veryfast, crf 26) into `takes/<id>/out/<slug>.preview.mp4`; its build, schedule and record (`render.json`, `render.log`) in `takes/<id>/out/preview/`. The full render (`preview.mp4`, `out/<slug>.mp4`, `out/sourced/`, `take.json`, `render.json`) is never touched. Reuses this take's own full render, and `--from`'s full render and preview ([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders), [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes)) | +| `take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]` | the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so | | `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** | | `lint <project> [--take <take>] [--variant sourced\|full] [--final] [--json]` | **the manifest lint** (`report-to-video/lint.mjs`, what a build runs before it renders a frame) from umtool: the project's manifest, or with `--take` the take's (its patches applied, written beside the project's manifest for the lint as its render's is, then removed) -- plus the **files its post items name**: a picked read, an attachment or a context post's media not in the project is an ERROR, another kept take a warning. Run it after an import and before queueing the render. `--json`: `{ok, entries, errors, warnings}`. **Exit 0 no error · 1 an error · 2 usage** | | `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") | @@ -120,7 +122,7 @@ Inbox cannot disagree about what is wrong with one. | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | | `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) | -| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)) | +| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render | | `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself | | `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own | | `jobs [--json]` | every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (the rail's *Running* links it) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1219,6 +1219,36 @@ clip); **not anchored** (written before anchors). Every write and undo is append | clamp a clipped beat; remove or re-point an orphan; anchor a beat that has been looked at | the beat's **Clamp to …**, **Remove the beat**, **Re-point**, **Looked at — anchor to <take>** (an edit or a confirm in the walk re-anchors too) | `trailer-beats <p> --reel R clamp <n>` · `repoint <n> <clip>` · `remove <n>` · `anchor [<n>…] --take <t>` · `--take <t>` on any edit | `{op: "set", index, patch, take}` · `{op: "anchor", only?, take}` | | what changed, when, against which take | -- | `trailer-beats <p> --reel R history [--json]` | `promo/<name>-beats.history.json` | +## Fast feedback: a preview, and a reel of the changes + +A full render of a long cut re-encodes its picture at 1920×1080, x264 `medium`, crf 20 -- the Mr. Obvious +cut's mid-22 took 40 minutes for 117 chunks. Two renders give the feedback without it +([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders)): a **preview** (the whole take, +small and fast) and a **changes reel** (only what changed against the take it was made from, each piece +labelled with its time in the full cut). Neither touches the take's full render or its records. + +| | From a terminal | In umtool | Route | +|---|---|---|---| +| a preview of the whole take | `umtool take <p> --id <t> --preview [--from <t0>]` → `takes/<t>/out/<slug>.preview.mp4` | the take card's **Preview render**; Play's **Fast render** | `POST /api/report/takes/fast {project, take, kind: "preview"}` (a queue step) | +| a reel of what changed | `umtool take <p> --id <t> --changes [--from <t0>] [--pad 3] [--no-preview]` → `takes/<t>/out/<slug>.changes.mp4`, `takes/<t>/changes.json` | **Render changes** (against the take's own base) | `… kind: "changes"` | +| queued, then polled | `umtool queue add -- take <p> --id <t> --preview` · `umtool take status <p> --id <t> [--json]` (`preview`, `changes`) | the state inline, the local path with **Copy**, **Play** of the file | `GET /api/report/takes/fast?project&take` (`&file=preview\|changes`: the mp4) | + +`render.preview` (on the manifest; absent: the defaults) sets the tier: + +| key | range · default | what | +|---|---|---| +| `width`, `height` | pixels · 1280, 720 | the preview's frame; never larger than the cut's (a 640×360 cut previews at its own size) | +| `preset` | an x264 preset · `veryfast` | the final encode's preset | +| `crf` | 0–51 · 26 | the final encode's quality | +| `segments` | `shared` / `preview` · `shared` | `preview` also encodes the segments a preview has to BUILD at the tier's preset and crf (keyed apart, never a full render's) -- at the cost of reusing none of the full render's | + +The cut's fps is kept (the chrome frames are shared with the full render at its own rate), and so are the +layout (the deck, the cards and the posts are composed at 1920×1080 as for the full render, then scaled), +the segments and the sound (the same mix and loudness: a timing or a level judged on a preview holds). +A preview's chunks key apart from the full render's (the tier's scale, preset and crf are in their argv) and +live in `out/preview/`: they never stand in for a full render's. `render.preview` itself changes no frame of +the full cut, and a changes reel does not count it as a change. + ## Queue a chain of renders, then poll (no shell scripts) Every take render writes its own record, whoever started it: `takes/<take>/render.json` (its diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -2251,6 +2251,81 @@ auto-picked over it (`--unpin`, or picking another, lets go). The gate this remo takes and none picked, Re-render the take had no target and the only way on was to pick one. +### Fast feedback: preview and changes renders + +The operator, 5 Nov 2026: "make fast preview render a first class feature because these huge feedback loops +are a nightmare". A full render of the 40-minute Mr. Obvious cut took 5–40 minutes even with `--from` reuse: +its final picture is encoded at 1920×1080, x264 `medium`, crf 20, in 117 chunks two at a time, on a CPU that +is already saturated (more workers do not help). Two renders of a take that are NOT its deliverable +(`lib/report/takePreview.mjs`): + +``` +umtool take <p> --id <t> --preview [--from <t0>] # the whole take, small and fast +umtool take <p> --id <t> --changes [--from <t0>] [--pad 3] # only what changed, labelled +umtool queue add -- take <p> --id <t> --changes # or queued (the Takes card's buttons) +umtool take status <p> --id <t> --json # .preview, .changes +``` + +**The preview** is the take as stored -- a draft from its walked patch, as its render would be -- composed +exactly as its full render is (the same 1920×1080 layout, the same segments, chrome frames and sound: the +same mix and loudness, so timing and audio judgements made on it hold), with only the final picture encoded +at the preview tier (`render.preview`, [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes): +1280×720, `veryfast`, crf 26). build-video reads the tier from the render manifest's `render.tier` +(`outputTier`): each chunk of the final encode gets a last `scale` and the tier's preset and crf; a cut whose +final is not chunk-encoded (a stream-copied hard cut with no deck) is scaled once at the end. Without a +tier nothing changes, byte for byte (an md5 of a full render of a fixture, deck and chunked encode included, +matches main's). + +``` +takes/<t>/out/<slug>.preview.mp4 the preview +takes/<t>/out/preview/ its build's own out/: sourced/schedule.json, segments, chunks …, + render.json and render.log (its record; the take's render.json is the + full render's) +takes/<t>/out/<slug>.changes.mp4 the changes reel +takes/<t>/out/changes/ its build, and its record +takes/<t>/changes.json the reel's pieces: id, kinds, label, `at`/`end` in the FULL cut, `exact`, + the piece's span in the reel; `times` (how the full-cut times were worked + out), `render` (what changed outside the timeline) +``` + +**What it shares, and what it never feeds.** A clip or post segment, a chrome frame and the cut's sound +are the same bytes whichever tier they end up in, and are keyed by what makes them, so a preview links +this take's own full render's, the `--from` take's full render's and its previews' (`takeFrom.mjs` +`linkVariantDir`) and finds the rest in the render pool. A preview's final-encode chunks key apart (the +tier's scale, preset and crf are in each chunk's argv, so in its key) and live in `out/preview/`: a +preview chunk never stands in for a full render's, and a full render's chunks are not linked into a +preview. So a preview of a take whose base was rendered re-encodes only its chunks, at a fifth of the +pixels on a fast preset. `render.preview.segments: "preview"` also encodes the segments it has to build at +the tier (keyed apart; never a full render's). + +**The changes reel** works out what changed between this take's timeline and `--from`'s (default: the +take's own `from`, or `draftedFrom`, the take a `--draft --from` was made from): the manifest the base +RENDERED (`takes/<t0>/video.manifest.json`), else its composition now, against this take's, entry by id -- +added, removed, moved, and per changed entry its kinds by the keys that differ: `re-read`, `re-picked` (an +older take picked again), `re-voiced` (the picked take's steps revoice), `paused`, `read knobs`, `fx`, +`media trim`, `hold`, `panel`, `picture only`, `thread`, `slurs`, `text`, `sound`, `blur`, `edited`. +What changed outside the timeline (`render.*` leaves) is listed, not rendered: a `--preview` judges it. Each +change is rendered with one neighbour either side (a removal: the two entries now either side of it), the +runs merged into ONE build of those entries (a window of the cut, as a window take renders), then each change +is cut from it as the item ± `--pad` seconds (default 3) with its label burned in -- `21:19 · +p-2116831815466193102 · re-voiced` -- and the pieces joined. + +**Measured** (5 Nov, on a copy of the Mr. Obvious project, the machine busy with another render and an e2e +build): the changes reel of a draft of mid-22 against mid-21 -- the re-voiced DM read (88 s) and the finale's +video entry, 5 entries in 2 runs -- took 4 min 57 s and labelled them 20:21 and 39:55, exactly where mid-22's +own render put them (1221.4 s, 2395.767 s); mid-22's full render re-encoded 117 chunks (40 min). A preview +window whose base preview existed took 89 s (its segments, 8,626 chrome frames, 6 of 6 chunks and the sound +all reused). A preview chunk is bound by its decode and overlay of the 1920×1080 segments and chrome frames, +not by x264: a 60 s chunk took 70 s at 4 at a time against 58–70 s at 2 at a time for the full render's +`medium` -- about 1.7× the throughput. The reuse, and rendering only what changed, are the speed. + +**The full-cut times.** With the base's MEASURED schedule (its render's `out/sourced/schedule.json`, or -- a +cut without the deck writes none -- its segments' probed lengths end to end), an unchanged entry keeps its +measured place, moved by what changed before it: each changed or added entry's length as the reel's build +measured it, less each changed or removed entry's old length (`times.basis: "measured"`). That is exact to +within what a change moves in its neighbours (a clock's rewind, a hold). Without it every length is the +estimate, the changed ones measured (`"estimate"`), and changes.json says so in `times.how`. + ### The render pool Every unit a build makes is filed in ONE pool shared by every take of every project, under the hash diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -2315,6 +2315,23 @@ copyFileSync( copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4")); } +// preview-render-fixture: fast feedback (lib/report/takePreview.mjs; preview-render.spec.ts, 5 Nov 2026). +// A 1920x1080 cut of three clips of vid1 (its window cached, so a take renders), no takes/ yet: the spec +// renders t0 whole, drafts t1 from it with one clip trimmed and one added, renders t1's changes reel +// against t0 (two labelled pieces) and t0's preview (1280x720, its full render untouched). +{ + const m = manifest("preview-render-fixture", "The Preview Render Fixture", { siteOrigin: "https://archive.example" }, [ + // Every clip inside 3–6 s: its window ± the fetch pad (3 s) is the cached 0–9 s one. + { type: "clip", id: "m01", video: "vid1", start: 3, end: 4, cite: 3, section: 0, lock: true, quote: "the first" }, + { type: "clip", id: "m02", video: "vid1", start: 4, end: 6, cite: 4, section: 0, lock: true, quote: "and because" }, + { type: "clip", id: "m03", video: "vid1", start: 3.5, end: 5, cite: 3, section: 0, lock: true, quote: "the last" }, + ]); + m.render = { ...m.render, width: 1920, height: 1080 }; + const dir = writeProject("preview-render-fixture", m); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4")); +} + // -- THE VIDEO-NOTES AND TIMELINE FIXTURES ------------------------------------ // // video-notes-fixture is a GENERATED manifest (`generatedBy`) with a built cut diff --git a/umtool/e2e/preview-render.spec.ts b/umtool/e2e/preview-render.spec.ts @@ -0,0 +1,120 @@ +import { test, expect } from "@playwright/test"; +import { spawnSync } from "node:child_process"; +import { readFileSync, statSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// FAST FEEDBACK (lib/report/takePreview.mjs; umtool/docs/report-video.md, "Fast feedback: preview and +// changes renders"): a take's PREVIEW (the whole take at 1280x720, veryfast) and its CHANGES REEL (only +// what changed against the take it was made from, each piece labelled with its time in the full cut). +// +// 1. the CLI: t0 rendered whole; t1 drafted from it (m02 trimmed, m04 added); t1's changes reel has two +// labelled pieces and changes.json lists them; t0's preview is 1280x720 and its full render's files +// (preview.mp4, out/<slug>.mp4, render.json, take.json, out/sourced/schedule…) are untouched; +// `take status --json` reports both +// 2. the Takes page: the card's Preview render / Render changes, a queue step the app runs, the state +// inline, the output's local path, Play of the file +// +// Fixture: preview-render-fixture (make-fixture.mjs), which this spec WRITES (takes/). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/preview-render-fixture"; +const DIR = path.join(FIXTURE, "reports", "preview-render-fixture"); +const SLUG = "preview-render-fixture"; + +function cli(args: string[], base = "") { + const r = spawnSync("node", ["bin/umtool.mjs", ...args], { + cwd: path.join(HERE, ".."), + encoding: "utf8", + env: { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_MEDIA_DIR: "", ...(base ? { UMTOOL_URL: base } : {}) }, + timeout: 240_000, + }); + return { code: r.status, out: r.stdout, err: r.stderr }; +} + +function size(file: string) { + const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file], { encoding: "utf8" }); + return r.stdout.trim(); +} + +const clip = (id: string, start: number, end: number, quote: string) => ({ type: "clip", id, video: "vid1", start, end, cite: Math.floor(start), section: 0, lock: true, quote }); + +test.describe.configure({ mode: "serial" }); + +test("the CLI: a changes reel of two labelled pieces with changes.json; a 1280x720 preview beside the untouched full render", async () => { + test.setTimeout(400_000); + const t0 = cli(["take", PROJECT, "--id", "t0", "--label", "T0", "--full", "--force"]); + expect(t0.code, t0.err + t0.out).toBe(0); + const patch = { timeline: [clip("m01", 3, 4, "the first"), clip("m02", 4, 5.5, "and because"), clip("m03", 3.5, 5, "the last"), clip("m04", 5, 6, "one more")] }; + const d = cli(["take", PROJECT, "--id", "t1", "--draft", "--from", "t0", "--force", "--patch-json", JSON.stringify(patch)]); + expect(d.code, d.err).toBe(0); + expect(JSON.parse(readFileSync(path.join(DIR, "takes", "t1", "take.json"), "utf8")).draftedFrom).toBe("t0"); + + // The changes reel: against t0 (the draft's own from), two pieces, each labelled with its full-cut time. + const c = cli(["take", PROJECT, "--id", "t1", "--changes", "--json"]); + expect(c.code, c.err + c.out).toBe(0); + const list = JSON.parse(readFileSync(path.join(DIR, "takes", "t1", "changes.json"), "utf8")); + expect(list.from).toBe("t0"); + expect(list.tier).toBe("preview"); + expect(list.items.map((x: { id: string; kinds: string[] }) => [x.id, x.kinds])).toEqual([["m02", ["media trim"]], ["m04", ["added clip"]]]); + for (const it of list.items) expect(it.label).toMatch(new RegExp(`^\\d+:\\d\\d · ${it.id} · `)); + // t0's segments measured its clock: the times are its, moved by m02's new length. + expect(list.times.basis).toBe("measured"); + expect(list.items[0].at).toBeGreaterThan(0.5); + expect(list.items[1].at).toBeGreaterThan(list.items[0].at); + const reel = path.join(DIR, "takes", "t1", "out", `${SLUG}.changes.mp4`); + expect(size(reel)).toBe("1280,720"); + expect(list.items[1].reel.to).toBeGreaterThan(list.items[0].reel.to); + // The draft is still a draft: nothing of a full render was made for it. + expect(() => statSync(path.join(DIR, "takes", "t1", "preview.mp4"))).toThrow(); + + // The preview of t0: 1280x720, its full render's files untouched. + const full = ["preview.mp4", `out/${SLUG}.mp4`, "render.json", "take.json", "video.manifest.json", "out/sourced/segments/m02.mp4"].map((f) => path.join(DIR, "takes", "t0", f)); + const before = full.map((f) => { const s = statSync(f); return `${s.size}:${s.mtimeMs}:${s.ino}`; }); + const p = cli(["take", PROJECT, "--id", "t0", "--preview"]); + expect(p.code, p.err + p.out).toBe(0); + expect(size(path.join(DIR, "takes", "t0", "out", `${SLUG}.preview.mp4`))).toBe("1280,720"); + expect(size(path.join(DIR, "takes", "t0", "preview.mp4"))).toBe("1920,1080"); + expect(full.map((f) => { const s = statSync(f); return `${s.size}:${s.mtimeMs}:${s.ino}`; })).toEqual(before); + // Its own record, in its own dir; the take's render record still the full render's. + expect(JSON.parse(readFileSync(path.join(DIR, "takes", "t0", "out", "preview", "render.json"), "utf8")).state).toBe("done"); + expect(JSON.parse(readFileSync(path.join(DIR, "takes", "t0", "render.json"), "utf8")).mp4).toBe("preview.mp4"); + + const s0 = cli(["take", "status", PROJECT, "--id", "t0", "--json"]); + expect(s0.code).toBe(0); + const j0 = JSON.parse(s0.out); + expect(j0.state).toBe("done"); + expect(j0.preview.state).toBe("done"); + expect(j0.preview.mp4).toContain(`${SLUG}.preview.mp4`); + const j1 = JSON.parse(cli(["take", "status", PROJECT, "--id", "t1", "--json"]).out); + expect(j1.changes.items).toBe(2); + expect(j1.changes.from).toBe("t0"); +}); + +test("the Takes page: Preview render and Render changes are queue steps, their state and path inline, the file played", async ({ page, baseURL }) => { + test.setTimeout(300_000); + await page.goto(urls.takesHref(PROJECT)); + const card0 = page.locator("[data-fast-renders='t0']"); + await expect(card0.locator("[data-fast='preview']")).toHaveAttribute("data-fast-state", "done", { timeout: 30_000 }); + await expect(card0.locator("[data-fast='preview'] [data-fast-path]")).toContainText(`${SLUG}.preview.mp4`); + await card0.locator("[data-action='play-preview']").click(); + await expect(card0.locator("[data-fast-video='preview']")).toBeVisible(); + const served = await page.request.get(`/api/report/takes/fast?project=${encodeURIComponent(PROJECT)}&take=t0&file=preview`, { headers: { range: "bytes=0-99" } }); + expect(served.status()).toBe(206); + + // Render changes on the draft: a step of the app's queue, run, its state inline. + const card1 = page.locator("[data-fast-renders='t1']"); + const before = statSync(path.join(DIR, "takes", "t1", "changes.json")).mtimeMs; + await card1.locator("[data-action='render-changes']").click(); + await expect(card1.locator("[data-fast-queued]")).toContainText(/queued as q\d+/); + const qid = ((await card1.locator("[data-fast-queued]").textContent()) ?? "").match(/q\d+/)?.[0] ?? ""; + const st = cli(["queue", "status", qid, "--json"], String(baseURL)); + expect(JSON.parse(st.out).step?.argv ?? JSON.parse(st.out).argv).toEqual(["take", PROJECT, "--id", "t1", "--changes", "--from", "t0"]); + await expect(card1.locator("[data-fast='changes']")).toHaveAttribute("data-fast-state", "done", { timeout: 240_000 }); + expect(statSync(path.join(DIR, "takes", "t1", "changes.json")).mtimeMs).toBeGreaterThan(before); + await expect(card1.locator("[data-fast='changes'] [data-fast-said]")).toContainText("2 piece(s) against t0"); +}); diff --git a/umtool/lib/queue/cli.mjs b/umtool/lib/queue/cli.mjs @@ -14,6 +14,7 @@ import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readRenderRecord, recordLines, renderPointerFile } from "../report/renderRecord.mjs"; +import { fastKindOf } from "../report/takePreview.mjs"; import { addStep, cancelStep, @@ -337,11 +338,36 @@ export async function jobsCommand(args, { reportsRoot = REPORTS_ROOT, log = cons * @param {{ take: string | null, json: boolean, showLog: boolean, tail: number | null, reportsRoot?: string, env?: Record<string, string | undefined>, * log: (s: string) => void, err: (s: string) => void }} o */ +export { fastKindOf }; + +/** + * A take's preview and changes renders, for `take status`: each one's record and output (takePreview.mjs + * fastRenders), or the queue step still to run it. + */ +async function fastStatus(project, id, steps) { + const { fastRenders } = await import("../report/takePreview.mjs"); + const slug = await readFile(path.join(project.dir, "video.manifest.json"), "utf8").then((t) => String(JSON.parse(t).slug ?? ""), () => ""); + const got = await fastRenders(path.join(project.dir, "takes", id), slug); + /** @type {Record<string, any>} */ + const out = {}; + for (const kind of ["preview", "changes"]) { + const step = steps.filter((s) => s.target.take === id && fastKindOf(s.argv) === kind).at(-1) ?? null; + const rec = got[/** @type {"preview" | "changes"} */ (kind)]; + const live = rec && (rec.state === "running" || rec.state === "waiting"); + if (step && !live && (step.state === "queued" || step.state === "blocked" || (step.state === "running" && !(rec?.endedAt === null)))) { + out[kind] = { ...(rec ?? {}), state: step.state === "running" ? "running" : step.state, queue: { qid: step.qid, state: step.state, after: step.after, error: step.error } }; + } else if (rec) out[kind] = rec; + } + return out; +} + export async function takeStatus(project, { take, json, showLog, tail, reportsRoot = REPORTS_ROOT, env = process.env, log, err }) { const { statusExitCode } = await import("../report/renderRecord.mjs"); const takesRoot = path.join(project.dir, "takes"); const dir = queueDirOf({ reportsRoot, env }); - const steps = (await listSteps(dir)).map((s) => resolveStep(s)).filter((s) => s.target?.project === project.id && s.target?.take); + const allSteps = (await listSteps(dir)).map((s) => resolveStep(s)).filter((s) => s.target?.project === project.id && s.target?.take); + // A preview or a changes reel is not the take's render: its steps are reported beside it (fastStatus). + const steps = allSteps.filter((s) => !fastKindOf(s.argv)); const ids = take ? [take] : (await readdir(takesRoot).catch(() => [])).filter((n) => !n.startsWith(".")); const rows = []; for (const id of ids) { @@ -376,6 +402,9 @@ export async function takeStatus(project, { take, json, showLog, tail, reportsRo if (doc?.builtAt && !doc.draft) row = { project: project.id, take: id, state: "done", recorded: false, builtAt: doc.builtAt, seconds: doc.seconds ?? null, mp4: doc.preview ?? "preview.mp4", exit: 0 }; else row = { project: project.id, take: id, state: "none", error: doc?.draft ? "a draft: never rendered" : `no render of take ${id} is recorded`, exit: 1 }; } + const fast = await fastStatus(project, id, allSteps); + if (row && Object.keys(fast).length) Object.assign(row, fast); + else if (!row && Object.keys(fast).length) row = { project: project.id, take: id, state: "none", error: "never rendered at full quality", exit: 1, ...fast }; if (row) rows.push(row); } rows.sort((a, b) => String(b.startedAt ?? b.queue?.qid ?? "").localeCompare(String(a.startedAt ?? a.queue?.qid ?? ""))); @@ -389,17 +418,28 @@ export async function takeStatus(project, { take, json, showLog, tail, reportsRo log(JSON.stringify(take ? { ...rows[0], logPath: path.join(takesRoot, take, "render.log") } : { project: project.id, takes: rows }, null, 2)); return code; } + const fastLines = (r) => { + for (const kind of ["preview", "changes"]) { + const f = r[kind]; + if (!f) continue; + const what = f.queue ? `${String(f.state).toUpperCase()} in the queue as ${f.queue.qid}` : String(f.state ?? "?").toUpperCase(); + log(` ${kind}: ${what}${f.mp4 ? ` — ${f.mp4}${f.seconds != null ? ` (${f.seconds} s)` : ""}` : ""}${f.items != null ? `, ${f.items} piece(s) against ${f.from}, list ${f.list}` : ""}${f.error ? ` — ${f.error}` : ""}`); + } + }; for (const r of rows) { if (r.queue) { log(`${project.id} take ${r.take}: ${r.state.toUpperCase()} in the queue as ${r.queue.qid}${r.queue.after ? ` (after ${r.queue.after})` : ""}${r.error ? ` — ${r.error}` : ""}`); log(` poll: umtool queue status ${r.queue.qid}`); + fastLines(r); continue; } if (r.recorded === false || r.state === "none") { log(`${project.id} take ${r.take}: ${r.state.toUpperCase()}${r.recorded === false ? ` (made ${fmtTime(r.builtAt)}, before renders recorded themselves)` : ` — ${r.error}`}`); + fastLines(r); continue; } for (const l of recordLines(r, { logPath: path.join(takesRoot, r.take, r.log ?? "render.log"), tail: take ? (tail ?? 12) : 0 })) log(l); + fastLines(r); } if (showLog && take) { const file = path.join(takesRoot, take, "render.log"); diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -44,6 +44,14 @@ export const TAKE_USAGE = [ " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]", " [--from TAKE] [--keep-frames] [--priority] [--uncensored]", " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames] [--priority]", + " umtool take <project> --id <id> --preview [--from TAKE] [--at S --dur S | --full] [--priority] [--json]", + " the take as stored (a draft too) at the PREVIEW tier (render.preview: 1280x720, veryfast,", + " crf 26; the same layout, segments, chrome and sound): takes/<id>/out/<slug>.preview.mp4,", + " its build and record in out/preview/; the take's full render untouched", + " umtool take <project> --id <id> --changes [--from TAKE] [--pad 3] [--no-preview] [--priority] [--json]", + " a reel of only what changed against TAKE (default: the take's own from): each changed item", + " ± pad s, labelled with its time in the full cut: takes/<id>/out/<slug>.changes.mp4 and", + " takes/<id>/changes.json", " made again from its own take.json (its stored patch, walked edits included); a window", " flag renders it over that window instead of its own", " umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,", @@ -131,7 +139,7 @@ function parse(args) { const valued = new Set([ "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect", "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name", "--tail", - "--import-item", "--after", "--before", "--as", + "--import-item", "--after", "--before", "--as", "--pad", ]); /** @type {Record<string, string[]>} */ const flags = {}; @@ -265,6 +273,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons if (!id) throw new CliError("--id <id>: the take's directory name (lower-case letters, digits, dashes)"); if (p.has("--promote")) return await promote(project, id, p, log, err); if (p.has("--import-item")) return await importItems(project, id, p, { reportsRoot, log, err }); + if (p.has("--preview") || p.has("--changes")) return await fastRender(project, id, p, out, { args, log, deps, renderMode }); const draft = p.has("--draft") || p.has("--no-render"); const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null); // A DRAFT named with no patch of its own is rendered from what it stores -- @@ -320,7 +329,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons if (spec.label && !/uncensored/i.test(spec.label)) spec.label = `${spec.label} (uncensored)`; } if (draft) { - const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) }); + const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(p.has("--from") ? { draftedFrom: p.one("--from") } : {}), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) }); if (p.has("--json")) { log(JSON.stringify({ ok: true, draft: true, ...d }, null, 2)); return 0; @@ -360,6 +369,41 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons } /** + * `umtool take <p> --id <t> --preview [--from <t0>] [--at S --dur S | --full]` · `--changes [--from <t0>] [--pad S] + * [--no-preview]`: the take's fast-feedback renders (takePreview.mjs), never its deliverable. + */ +async function fastRender(project, id, p, out, { args, log, deps, renderMode }) { + if (p.has("--preview") && p.has("--changes")) { + // `--changes --preview` is the default reel (preview quality), said both ways. + if (p.has("--no-preview")) throw new CliError("--changes --preview and --no-preview: one or the other"); + } + for (const n of ["--draft", "--no-render", "--rebuild", "--promote", "--patch", "--patch-json", "--set", "--style", "--effect", "--uncensored", "--keep-frames"]) { + if (p.has(n)) throw new CliError(`${n} is not for a ${p.has("--changes") ? "changes reel" : "preview"}: it renders the take as it is stored (make or edit the take first)`); + } + const tp = await import("./takePreview.mjs"); + const common = { + from: p.one("--from") ?? null, + log: out.log, + emit: out.emit, + projectId: project.id, + argv: ["take", ...args], + ...(deps?.render ? { render: /** @type {any} */ (deps.render) } : {}), + }; + const run = async () => { + if (p.has("--changes")) { + const pad = p.has("--pad") ? Number(p.one("--pad")) : undefined; + if (pad !== undefined && !(Number.isFinite(pad) && pad >= 0 && pad <= 30)) throw new CliError("--pad is 0–30 seconds"); + if (p.has("--at") || p.has("--dur") || p.has("--full")) throw new CliError("a changes reel is of the whole cut: no --at/--dur/--full"); + return tp.changesTake(project.dir, id, { ...common, ...(pad !== undefined ? { pad } : {}), preview: !p.has("--no-preview") }); + } + return tp.previewTake(project.dir, id, { ...common, window: windowOf(p) ?? undefined }); + }; + const r = await withTakePriority({ priority: p.has("--priority"), project: project.id, take: id, log: out.log, ...(renderMode ?? {}) }, run); + if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); + return 0; +} + +/** * `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <id> | --before <id>] * [--as <id>] [--dry-run] [--json]`: items of other projects cloned into the take, their files linked in (takeImport.mjs). */ diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -159,8 +159,20 @@ export async function linkFromTake(projectDir, id, from, takeOut) { return out; } +/** + * One built variant directory's files linked into another (linkVariant), for a preview or a changes reel + * (takePreview.mjs): `src` a take's out/sourced or out/preview/sourced, `dst` the preview's own. `chunks: + * false` leaves the final encode's chunks and their record out -- a full render's are never a preview's. + * @param {{ src: string, dst: string, kept?: string | null, from: string, chunks?: boolean }} o + */ +export async function linkVariantDir({ src, dst, kept = null, from, chunks = true }) { + if (!(await isDir(src))) return null; + if (path.resolve(src) === path.resolve(dst)) return null; + return linkVariant({ src, dst, kept: kept ?? keptFramesDir(path.dirname(src), path.basename(src)), from, chunks }); +} + /** One variant's files, `src` (the other take's out/<variant>) into `dst`; `kept` its set-aside layers. */ -async function linkVariant({ src, dst, kept, from }) { +async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) { const out = { segments: 0, frames: [], batches: 0, chunks: 0, records: 0, keptOwn: [], keptOwnFrames: [] }; const segs = path.join(src, "segments"); @@ -242,13 +254,13 @@ async function linkVariant({ src, dst, kept, from }) { // The final encode's chunks and sound, by content key: theirs beside ours. const chunks = path.join(src, CHUNKS_DIR); const chunksOut = path.join(dst, CHUNKS_DIR); - for (const f of await names(chunks)) { + for (const f of withChunks ? await names(chunks) : []) { if (!/^(chunk|audio)-[0-9a-f]+\.(mp4|m4a)$/.test(f) || !(await isFile(path.join(chunks, f)))) continue; await mkdir(chunksOut, { recursive: true }); if (!(await isFile(path.join(chunksOut, f))) && (await linkFile(path.join(chunks, f), path.join(chunksOut, f)))) out.chunks += 1; } // Their record of the chunks, unless ours is newer: what "why re-encoded" compares with. - const theirRecord = await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null); + const theirRecord = withChunks ? await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null) : null; if (theirRecord?.isFile()) { const ownRecord = await lstat(path.join(chunksOut, CHUNKS_RECORD)).catch(() => null); if (!ownRecord?.isFile() || ownRecord.mtimeMs < theirRecord.mtimeMs) { diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -595,24 +595,17 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { return r; } -/** makeTake's body; `onTakeDir` is called once the take's directory exists, before anything is linked or rendered. */ -async function makeTakeLocked(projectDir, rawSpec, opts) { - const spec = checkSpec(rawSpec); - const emit = opts.emit ?? (() => {}); +/** + * What a take renders, composed and not written: the project's manifest with the take's style and patch + * (preset → manifest → style → take patch), the clip deck's rulings applied, windowed when the take has a + * window. makeTake renders it; a preview or a changes reel (takePreview.mjs) renders the same. + * + * @param {string} projectDir + * @param {ReturnType<typeof checkSpec>} spec + * @param {{ styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, log?: (line: string) => void }} [opts] + */ +export async function composeTake(projectDir, spec, opts = {}) { const log = opts.log ?? (() => {}); - const now = opts.now ?? (() => new Date()); - const takeDir = path.join(takesDirOf(projectDir), spec.id); - const takeFile = path.join(takeDir, TAKE_FILE); - const previous = await readJson(takeFile); - if (previous && !opts.force) { - emit({ ev: "take", id: spec.id, phase: "skipped" }); - return { id: spec.id, skipped: true }; - } - - // --from is checked before anything is written: a bad name leaves no work dir. - const fromTake = opts.from ? await import("./takeFrom.mjs") : null; - if (fromTake) await fromTake.fromTakeSourced(projectDir, spec.id, opts.from); - const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8"); const base = JSON.parse(baseText); const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); @@ -668,6 +661,29 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`); renderDoc = windowManifest(ruled.manifest, ids); } + return { baseText, base, styles, manifest, changes, kind, patches, ruled, renderDoc, covered }; +} + +/** makeTake's body; `onTakeDir` is called once the take's directory exists, before anything is linked or rendered. */ +async function makeTakeLocked(projectDir, rawSpec, opts) { + const spec = checkSpec(rawSpec); + const emit = opts.emit ?? (() => {}); + const log = opts.log ?? (() => {}); + const now = opts.now ?? (() => new Date()); + const takeDir = path.join(takesDirOf(projectDir), spec.id); + const takeFile = path.join(takeDir, TAKE_FILE); + const previous = await readJson(takeFile); + if (previous && !opts.force) { + emit({ ev: "take", id: spec.id, phase: "skipped" }); + return { id: spec.id, skipped: true }; + } + + // --from is checked before anything is written: a bad name leaves no work dir. + const fromTake = opts.from ? await import("./takeFrom.mjs") : null; + if (fromTake) await fromTake.fromTakeSourced(projectDir, spec.id, opts.from); + + const { baseText, styles, manifest, changes, kind, patches, renderDoc: composed, covered } = await composeTake(projectDir, spec, { styles: opts.styles, log }); + let renderDoc = composed; if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER)); // A clip ruled incorrect (the walk's verdict) still in what would render: // refused, by name, before anything is written -- `umtool check` calls it @@ -828,7 +844,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { * * @param {string} projectDir * @param {TakeSpec} rawSpec `window` absent: the render's window is said when it is rendered - * @param {{ force?: boolean, styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, now?: () => Date }} [opts] + * @param {{ force?: boolean, styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, now?: () => Date, draftedFrom?: string }} [opts] */ export async function draftTake(projectDir, rawSpec, opts = {}) { const spec = checkSpec(rawSpec); @@ -875,6 +891,8 @@ export async function draftTake(projectDir, rawSpec, opts = {}) { patch: spec.patch, window, ...(spec.quick ? { quick: true } : {}), + // A draft made FROM another take (`--draft --from <t>`): what a changes reel compares it with by default (takePreview.mjs). + ...(typeof opts.draftedFrom === "string" && opts.draftedFrom ? { draftedFrom: opts.draftedFrom } : {}), draft: true, draftedAt: now().toISOString(), baseHash: hashText(baseText), diff --git a/umtool/lib/report/takePreview.mjs b/umtool/lib/report/takePreview.mjs @@ -0,0 +1,819 @@ +// FAST FEEDBACK (operator, 5 Nov 2026: "make fast preview render a first class feature because these huge +// feedback loops are a nightmare"): two renders of a take that are not its deliverable. +// +// umtool take <p> --id <t> --preview [--from <t0>] +// the WHOLE take at the preview tier -- the same cut, composed exactly as its full render composes it +// (the 1920×1080 layout, its segments, its chrome frames, its sound: the same mix and loudness, so a +// timing or an audio judgement made on it holds), only its final picture encoded smaller and faster +// (render.preview: 1280×720, x264 veryfast, crf 26; build-video outputTier). Into +// takes/<t>/out/<slug>.preview.mp4 +// takes/<t>/out/preview/ the build's own out/: its schedule, segments, chunks, and +// its record (render.json, render.log) +// The take's full render -- preview.mp4, out/<slug>.mp4, out/sourced/, take.json, render.json -- is +// never touched. A draft is previewed from its stored patch, as its render would be. +// +// umtool take <p> --id <t> --changes [--from <t0>] [--pad 3] [--no-preview] +// a REEL of only what changed against <t0> (default: the take's own `from`): each changed item -- added, +// re-read, re-picked, re-voiced, fx, a trim, a hold, a panel, … -- with one neighbour each side +// rendered in one build (takes/<t>/out/changes/), then cut to the item ± pad seconds, each piece with +// a label burned in ("21:19 · p-2116831815466193102 · re-voiced") giving its time in the FULL cut, +// joined into takes/<t>/out/<slug>.changes.mp4. takes/<t>/changes.json lists the same: the input the +// render-verify view reads. A removed item is shown as the join it leaves. +// +// WHAT A PREVIEW SHARES, AND WHAT IT NEVER FEEDS. Its final encode's chunks key apart from the full render's +// (the tier's scale, preset and crf are in each chunk's argv, so in its key: chunked-encode.mjs), and live +// in out/preview/, so a preview chunk never stands in for a full one -- and a full render's chunks are not +// linked into a preview. What is NOT tier-dependent is shared both ways: a clip or post segment, a chrome +// frame and the cut's sound are the same bytes whichever tier they end up in, keyed by what makes them +// (segment-cache.mjs, post-render.mjs, frame-keys.mjs), so a preview reuses a full render's and the render +// pool's. That is the speed: a preview of a take whose base was rendered re-encodes nothing but its +// chunks, at a fifth of the pixels and a fast preset. `render.preview.segments: "preview"` encodes the +// segments a preview has to BUILD at the tier's preset and crf too (keyed apart, never a full render's); +// off by default, because it forfeits reusing the full render's. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { applyMontageRulings, readMontageRulings } from "umtool-report-to-video/montage-rulings"; +import { composeTake, checkSpec, estimatedSeconds, getPath, linkSharedOut, MANIFEST, mergePatch, QUICK_RENDER, sourcedEntries, windowManifest } from "./takeMaker.mjs"; +import { takesDirOf, TAKE_FILE } from "./takes.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; + +/** The preview tier's defaults (render.preview overrides each). */ +export const PREVIEW_DEFAULTS = Object.freeze({ width: 1280, height: 720, preset: "veryfast", crf: 26, segments: "shared" }); +/** The build dirs under takes/<t>/out/. */ +export const PREVIEW_DIR = "preview"; +export const CHANGES_DIR = "changes"; +/** The changes reel's list, beside take.json. */ +export const CHANGES_FILE = "changes.json"; +/** Seconds of context either side of a changed item in the reel. */ +export const DEFAULT_PAD = 3; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const X264_PRESETS = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"]; + +/** + * The preview tier a manifest asks for: `render.preview` over PREVIEW_DEFAULTS, checked. The cut's own fps + * is kept (a frame-keyed chrome frame is shared with the full render only at the cut's own rate), and the + * tier is never larger than the cut: a 640×360 cut previews at 640×360. Pure. + * + * @param {Record<string, any>} [render] + * @returns {{ width: number, height: number, preset: string, crf: number, segments: "shared" | "preview" }} + */ +export function previewKnobs(render = {}) { + const raw = render?.preview; + if (raw !== undefined && raw !== null && !isObj(raw)) throw new Error("render.preview is an object: { width, height, preset, crf, segments }"); + const k = { ...PREVIEW_DEFAULTS, ...(isObj(raw) ? raw : {}) }; + const W = Number(render?.width ?? 1920); + const H = Number(render?.height ?? 1080); + let width = Math.round(Number(k.width)); + let height = Math.round(Number(k.height)); + if (!Number.isFinite(width) || width < 16 || !Number.isFinite(height) || height < 16) throw new Error(`render.preview: width and height are pixels (≥ 16), got ${JSON.stringify(raw)}`); + if (width > W || height > H) { + // Never larger than the cut: its own size, its aspect kept. + const f = Math.min(W / width, H / height); + width = Math.round(width * f); + height = Math.round(height * f); + } + width -= width % 2; + height -= height % 2; + const crf = Number(k.crf); + if (!Number.isFinite(crf) || crf < 0 || crf > 51) throw new Error(`render.preview.crf is 0–51, got ${JSON.stringify(k.crf)}`); + const preset = String(k.preset); + if (!X264_PRESETS.includes(preset)) throw new Error(`render.preview.preset is an x264 preset (${X264_PRESETS.join(", ")}), got ${JSON.stringify(k.preset)}`); + if (k.segments !== "shared" && k.segments !== "preview") throw new Error(`render.preview.segments is "shared" or "preview", got ${JSON.stringify(k.segments)}`); + return { width, height, preset, crf, segments: k.segments }; +} + +/** + * A render manifest at the preview tier: `render.tier` (build-video outputTier), and with `segments: + * "preview"` the cut's own preset and crf too (the segments it builds). The manifest is copied. Pure. + * `segments`: the caller's default for that knob when the manifest does not set it. + * @param {Record<string, any>} doc + * @param {{ segments?: "shared" | "preview" | null }} [o] + */ +export function atPreviewTier(doc, { segments = null } = {}) { + const k = previewKnobs(doc.render ?? {}); + // A caller's default (a changes reel's: "preview") gives way to a manifest that says. + if (segments && !(isObj(doc.render?.preview) && doc.render.preview.segments !== undefined)) k.segments = segments; + const render = { ...(doc.render ?? {}), tier: { name: "preview", width: k.width, height: k.height, preset: k.preset, crf: k.crf } }; + if (k.segments === "preview") Object.assign(render, { preset: k.preset, crf: k.crf }); + return { ...doc, render }; +} + +/** Where a take's preview and changes renders go. Pure. */ +export function previewPaths(takeDir, slug) { + const out = path.join(takeDir, "out"); + return { + previewOut: path.join(out, PREVIEW_DIR), + previewMp4: path.join(out, `${slug}.preview.mp4`), + changesOut: path.join(out, CHANGES_DIR), + changesMp4: path.join(out, `${slug}.changes.mp4`), + changesFile: path.join(takeDir, CHANGES_FILE), + }; +} + +// --------------------------------------------------------------------------- +// What changed: one take's timeline against another's. +// --------------------------------------------------------------------------- + +const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); + +/** The narration's change, in a word: re-picked (an older take), re-voiced / re-read (a new one), read knobs. */ +function narrationKind(a, b) { + const A = isObj(a) ? a : {}; + const B = isObj(b) ? b : {}; + const takesA = Array.isArray(A.takes) ? A.takes : []; + const takesB = Array.isArray(B.takes) ? B.takes : []; + const pickedB = Number.isInteger(B.pick) ? takesB[B.pick] : null; + if (A.pick !== B.pick || !same(takesA[A.pick], pickedB)) { + if (!pickedB) return "re-read"; + const before = takesA.some((t) => same(t?.file, pickedB.file)); + if (before) return "re-picked"; + const ops = new Set((Array.isArray(pickedB.steps) ? pickedB.steps : []).map((s) => s?.op).filter(Boolean)); + if (ops.has("revoice")) return "re-voiced"; + if (ops.has("pause")) return "paused"; + if (ops.has("rejoin") || ops.has("join")) return "re-joined"; + if (ops.has("tempo")) return "tempo"; + return "re-read"; + } + if (!same(A.script, B.script)) return "re-read"; + return "read knobs"; +} + +/** Keys of an entry, by the kind of change a person checks for. */ +const KEY_KINDS = [ + [["fx"], "fx"], + [["cutStart", "cutEnd", "start", "end", "from", "to", "media", "clip", "full", "gaps", "room"], "media trim"], + [["hold", "lead"], "hold"], + [["panel", "layout"], "panel"], + [["pictureOnly"], "picture only"], + [["thread", "parents", "conversation", "quoted", "replyingTo"], "thread"], + [["redact", "slurs"], "slurs"], + [["text", "heading", "title", "subtitle", "onscreen", "quote", "cite", "citeUrl", "channelTitle", "date"], "text"], + [["audio", "mute", "muteFrom", "loudness"], "sound"], + [["blur"], "blur"], +]; + +/** + * The kinds of one entry's change (a → b): a sorted list of words, `narration` read closely. Pure. + * @param {Record<string, any>} a + * @param {Record<string, any>} b + * @returns {{ kinds: string[], keys: string[] }} + */ +export function entryChangeKinds(a, b) { + const keys = [...new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])].filter((k) => !same(a?.[k], b?.[k])).sort(); + const kinds = new Set(); + for (const k of keys) { + if (k === "narration") { + kinds.add(narrationKind(a?.narration, b?.narration)); + continue; + } + const hit = KEY_KINDS.find(([ks]) => ks.includes(k)); + kinds.add(hit ? hit[1] : "edited"); + } + return { kinds: [...kinds].sort(), keys }; +} + +/** + * Lines for what changed outside the timeline: `render.<path>` leaves and top-level keys. Pure. + * @returns {string[]} + */ +export function renderLevelChanges(a, b) { + const out = []; + const walk = (x, y, prefix) => { + if (isObj(x) && isObj(y)) { + for (const k of [...new Set([...Object.keys(x), ...Object.keys(y)])].sort()) walk(x[k], y[k], prefix ? `${prefix}.${k}` : k); + return; + } + if (!same(x, y)) out.push(prefix); + }; + for (const k of [...new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])].sort()) { + if (k === "timeline" || k === "generatedOn") continue; + if (k === "render") { + // The preview's own knobs change no frame of the full cut. + const ra = { ...(a?.render ?? {}) }; + const rb = { ...(b?.render ?? {}) }; + delete ra.preview; + delete rb.preview; + walk(ra, rb, "render"); + } else if (!same(a?.[k], b?.[k])) out.push(k); + } + return out; +} + +/** + * The changes of one timeline against another's, by entry id, in the NEW timeline's order. Pure. + * + * changed { id, index, kind: "changed" | "added" | "moved", kinds, keys } one per entry of `after` + * that is new, edited or moved (its predecessor among the shared ids is another) + * removed { id, after, before } an entry of `before` gone: the ids now either side of where it was + * + * @param {Array<Record<string, any>>} beforeTimeline + * @param {Array<Record<string, any>>} afterTimeline + */ +export function diffTimelines(beforeTimeline, afterTimeline) { + const A = sourcedEntries(beforeTimeline); + const B = sourcedEntries(afterTimeline); + const byA = new Map(A.map((e) => [e.id, e])); + const byB = new Map(B.map((e) => [e.id, e])); + const sharedA = A.filter((e) => byB.has(e.id)).map((e) => e.id); + const sharedB = B.filter((e) => byA.has(e.id)).map((e) => e.id); + const prevA = new Map(sharedA.map((id, i) => [id, i ? sharedA[i - 1] : null])); + const prevB = new Map(sharedB.map((id, i) => [id, i ? sharedB[i - 1] : null])); + const changed = []; + B.forEach((e, index) => { + const old = byA.get(e.id); + if (!old) { + changed.push({ id: e.id, index, kind: "added", kinds: [`added ${e.type ?? "entry"}`], keys: [] }); + return; + } + const { kinds, keys } = entryChangeKinds(old, e); + const moved = prevA.get(e.id) !== prevB.get(e.id) && !(prevA.get(e.id) && !byB.has(prevA.get(e.id))); + if (moved) kinds.unshift("moved"); + if (kinds.length) changed.push({ id: e.id, index, kind: keys.length ? "changed" : "moved", kinds, keys }); + }); + const removed = []; + A.forEach((e, i) => { + if (byB.has(e.id)) return; + // The nearest survivors either side, as they stand in the new timeline. + let after = null; + for (let k = i - 1; k >= 0 && after === null; k -= 1) if (byB.has(A[k].id)) after = A[k].id; + let before = null; + for (let k = i + 1; k < A.length && before === null; k += 1) if (byB.has(A[k].id)) before = A[k].id; + removed.push({ id: e.id, after, before, type: e.type ?? null }); + }); + return { changed, removed }; +} + +/** + * The runs a changes reel renders: each change with one neighbour either side (a removal: the two entries + * now either side of it), overlapping or touching ranges merged. Each run lists its ids (in the new + * timeline's order) and its FOCI -- one per change, each a labelled piece of the reel. Pure. + * + * @param {string[]} ids the new timeline's ids, in order + * @param {ReturnType<typeof diffTimelines>} diff + * @param {{ neighbours?: number }} [o] + */ +export function planRuns(ids, diff, { neighbours = 1 } = {}) { + const at = new Map(ids.map((id, i) => [id, i])); + /** @type {Array<{ lo: number, hi: number, focus: Array<Record<string, any>> }>} */ + const ranges = []; + for (const c of diff.changed) { + const i = at.get(c.id); + if (i === undefined) continue; + ranges.push({ lo: Math.max(0, i - neighbours), hi: Math.min(ids.length - 1, i + neighbours), focus: [{ type: "item", id: c.id, index: i, kind: c.kind, kinds: c.kinds }] }); + } + for (const r of diff.removed) { + const a = r.after !== null ? at.get(r.after) : undefined; + const b = r.before !== null ? at.get(r.before) : undefined; + if (a === undefined && b === undefined) continue; + const lo = a ?? b; + const hi = b ?? a; + ranges.push({ lo: /** @type {number} */ (lo), hi: /** @type {number} */ (hi), focus: [{ type: "join", id: r.id, after: r.after, before: r.before, index: lo, kind: "removed", kinds: [`removed ${r.type ?? "entry"}`] }] }); + } + ranges.sort((x, y) => x.lo - y.lo || x.hi - y.hi); + const merged = []; + for (const r of ranges) { + const last = merged[merged.length - 1]; + if (last && r.lo <= last.hi + 1) { + last.hi = Math.max(last.hi, r.hi); + last.focus.push(...r.focus); + } else merged.push({ ...r, focus: [...r.focus] }); + } + return merged.map((r) => ({ + ids: ids.slice(r.lo, r.hi + 1), + focus: r.focus.sort((x, y) => x.index - y.index || (x.type === "join" ? 1 : -1)), + })); +} + +// --------------------------------------------------------------------------- +// Times: in the reel's build, and in the FULL cut. +// --------------------------------------------------------------------------- + +/** + * Each entry's place in the FULL cut of the new timeline, and how it was worked out. Pure. + * + * With the base take's MEASURED schedule (its render's out/sourced/schedule.json, `estimated: false`): an + * entry that did not change keeps its measured length, moved by what changed before it -- each changed or + * added entry's length as the reel's build measured it, less each changed or removed entry's old length. + * That is exact when every changed entry was measured (basis "measured": the base's schedule + the reel's + * measured lengths), to within what a change moves in its neighbours (a clock's rewind, a hold). Without + * the base's schedule every length is the estimate (estimatedSeconds), the changed ones measured (basis + * "estimate"). + * + * @param {{ timeline: Array<Record<string, any>>, changedIds: Set<string>, base: { segments: Array<{ id: string, start: number, duration: number }>, transition?: number, estimated?: boolean } | null, + * measured: Map<string, number>, estimate?: (e: Record<string, any>) => number }} o + * @returns {{ basis: "measured" | "estimate", times: Map<string, { start: number, end: number, exact: boolean }> }} + */ +export function fullCutTimes({ timeline, changedIds, base, measured, estimate = estimatedSeconds }) { + const entries = sourcedEntries(timeline); + const times = new Map(); + const exactBase = !!base && base.estimated !== true && Array.isArray(base.segments) && base.segments.length > 0; + if (!exactBase) { + let t = 0; + let exact = true; + for (const e of entries) { + const m = measured.get(e.id); + const d = m ?? estimate(e); + if (m === undefined) exact = false; + times.set(e.id, { start: t, end: t + d, exact }); + t += d; + } + return { basis: "estimate", times }; + } + const D = Number(base?.transition ?? 0) || 0; + const old = new Map(base.segments.map((s) => [s.id, { start: Number(s.start), duration: Number(s.duration ?? (Number(s.end) - Number(s.start))) }])); + const newIds = new Set(entries.map((e) => e.id)); + // The old segments a change took out of the clock: a changed entry's old length, a removed one's. + const outOld = base.segments.filter((s) => (changedIds.has(s.id) && old.has(s.id)) || !newIds.has(s.id)).map((s) => old.get(s.id)); + let prevEnd = 0; + let addedSoFar = 0; + let exactSoFar = true; + for (const e of entries) { + const o = old.get(e.id); + if (!changedIds.has(e.id) && o) { + const lost = outOld.filter((x) => x && x.start < o.start).reduce((n, x) => n + x.duration - D, 0); + const start = o.start + addedSoFar - lost; + times.set(e.id, { start, end: start + o.duration, exact: exactSoFar }); + prevEnd = start + o.duration; + continue; + } + const m = measured.get(e.id); + const d = m ?? estimate(e); + if (m === undefined) exactSoFar = false; + const start = Math.max(0, prevEnd - (times.size ? D : 0)); + times.set(e.id, { start, end: start + d, exact: exactSoFar }); + addedSoFar += d - (times.size > 1 ? D : 0); + prevEnd = start + d; + } + return { basis: exactSoFar ? "measured" : "estimate", times }; +} + +/** Seconds as m:ss (h:mm:ss past an hour). Pure. */ +export function clockOf(s) { + const t = Math.max(0, Math.floor(Number(s) || 0)); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const sec = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`; +} + +/** A reel piece's label: "21:19 · p-… · re-voiced". Pure. */ +export function pieceLabel(focus, fullStart) { + const what = focus.type === "join" ? `${focus.id} removed — the join` : focus.id; + return `${clockOf(fullStart)} · ${what} · ${focus.kinds.join(", ")}`; +} + +/** + * The pieces of the reel: per focus, its span in the reel BUILD (the item ± pad, clamped to its run's + * entries; a removal's: the join ± pad) and in the full cut. Pure. + * + * @param {ReturnType<typeof planRuns>} runs + * @param {Map<string, { start: number, duration: number }>} build each id's place in the reel's build + * @param {Map<string, { start: number, end: number, exact: boolean }>} full + * @param {number} pad + */ +export function reelPieces(runs, build, full, pad) { + const pieces = []; + for (const run of runs) { + const first = build.get(run.ids[0]); + const last = build.get(run.ids[run.ids.length - 1]); + if (!first || !last) throw new Error(`the changes build has no place for ${run.ids.join(", ")}`); + const lo = first.start; + const hi = last.start + last.duration; + for (const f of run.focus) { + let a; + let b; + let fa; + let fb; + let exact; + if (f.type === "join") { + const anchor = f.after !== null ? build.get(f.after) : null; + const at = anchor ? anchor.start + anchor.duration : /** @type {any} */ (build.get(f.before)).start; + a = at - pad; + b = at + pad; + const fe = f.after !== null ? full.get(f.after) : null; + fa = fe ? fe.end : full.get(f.before)?.start ?? 0; + fb = fa; + exact = fe ? fe.exact : full.get(f.before)?.exact ?? false; + } else { + const s = /** @type {{ start: number, duration: number }} */ (build.get(f.id)); + a = s.start - pad; + b = s.start + s.duration + pad; + const fe = full.get(f.id); + fa = fe?.start ?? 0; + fb = fe?.end ?? fa + s.duration; + exact = fe?.exact ?? false; + } + const from = Math.max(lo, a); + const to = Math.min(hi, b); + pieces.push({ ...f, from: round3(from), to: round3(to), fullStart: round3(fa), fullEnd: round3(fb), exact, label: pieceLabel(f, fa) }); + } + } + return pieces; +} + +const round3 = (v) => Math.round(v * 1000) / 1000; + +// --------------------------------------------------------------------------- +// The renders. +// --------------------------------------------------------------------------- + +async function readJson(file) { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch { + return null; + } +} + +const isDir = (p) => stat(/* turbopackIgnore: true */ p).then((s) => s.isDirectory(), () => false); + +/** A take's stored spec (take.json), checked: what its preview renders, as its render would. */ +async function storedSpec(projectDir, id) { + const take = await readJson(path.join(takesDirOf(projectDir), id, TAKE_FILE)); + if (!take) throw new Error(`no take ${id} in ${path.basename(projectDir)} (make it first: umtool take <p> --id ${id} --draft …)`); + return { + take, + spec: checkSpec({ + id, + label: take.label || id, + group: take.group, + kind: take.kind === "similar" ? "similar" : undefined, + summary: take.summary, + style: take.style ?? null, + patch: take.patch ?? null, + window: take.window ?? "full", + quick: take.quick === true, + }), + }; +} + +/** As makeTake decides: a take crossfades only when its own patches set a transition (else its hard cuts). */ +const takeXfade = (c) => Number(c.manifest.render?.transition ?? 0) > 0 && c.patches.some((p) => getPath(p, "render.transition") !== undefined); + +/** The manifest a base take rendered (its video.manifest.json), else its composition now (a draft). */ +async function baseManifest(projectDir, from) { + const dir = path.join(takesDirOf(projectDir), from); + const rendered = await readJson(path.join(dir, MANIFEST)); + if (rendered) return { manifest: rendered, rendered: true }; + const { spec } = await storedSpec(projectDir, from); + const c = await composeTake(projectDir, { ...spec, window: "full" }); + return { manifest: c.manifest, rendered: false }; +} + +/** + * The built dirs a preview links from (takeFrom.mjs linkVariantDir), in order: this take's own full + * render's (no chunks: a full render's are never a preview's), the base take's full render's (the same), + * then the base take's preview or changes builds (with their chunks: the same tier's). + */ +async function linkSources(projectDir, id, from, dst, { tierDir }) { + const { linkVariantDir } = await import("./takeFrom.mjs"); + const takes = takesDirOf(projectDir); + const sources = [{ src: path.join(takes, id, "out", "sourced"), from: id, chunks: false }]; + if (from) { + sources.push({ src: path.join(takes, from, "out", "sourced"), from, chunks: false }); + for (const d of [PREVIEW_DIR, CHANGES_DIR]) sources.push({ src: path.join(takes, from, "out", d, "sourced"), from, chunks: true }); + } + if (tierDir) for (const d of [PREVIEW_DIR, CHANGES_DIR]) if (d !== tierDir) sources.push({ src: path.join(takes, id, "out", d, "sourced"), from: id, chunks: true }); + const got = []; + for (const s of sources) { + const r = await linkVariantDir({ src: s.src, dst, from: s.from, chunks: s.chunks }).catch((e) => { + throw new Error(`linking ${path.relative(takes, s.src)}: ${e instanceof Error ? e.message : e}`); + }); + if (r) got.push(`${path.relative(takes, s.src)}: ${r.segments} segment file(s)${r.frames.length ? `, ${r.frames.join(", ")}` : ""}${r.chunks ? `, ${r.chunks} chunk(s)` : ""}`); + } + return got; +} + +/** + * One build of a render manifest into `outDir` (the take's preview or changes dir): through renderTake, + * the heavy slot and all, recorded in outDir/render.json and render.log. Resolves to the build's mp4. + */ +async function buildInto(projectDir, { id, label, kind, renderDoc, outDir, from, xfade, opts }) { + const recordMod = await import("./renderRecord.mjs"); + await mkdir(outDir, { recursive: true }); + const rec = await recordMod + .openRenderRecord(outDir, { take: id, projectDir, project: opts.projectId ?? null, label: `${label} (${kind})`, argv: opts.argv, reportsRoot: null }) + .catch(() => null); + const log = (line) => { + rec?.line(line); + (opts.log ?? (() => {}))(line); + }; + const emit = (ev) => { + rec?.event(ev); + (opts.emit ?? (() => {}))(ev); + }; + const renderPath = path.join(projectDir, `.take-${id}.${kind}.render.json`); + try { + const linked = await linkSharedOut(projectDir, outDir); + if (linked.length) log(`${id}: ${kind}: reusing the project's ${linked.join(" and ")}`); + const got = await linkSources(projectDir, id, from, path.join(outDir, "sourced"), { tierDir: path.basename(outDir) }); + for (const g of got) log(`${id}: ${kind}: linked ${g}`); + await writeFile(renderPath, JSON.stringify(renderDoc, null, 2) + "\n", "utf8"); + const render = opts.render ?? (await import("./takeRender.mjs")).renderTake; + const t0 = Date.now(); + const { file } = await render({ manifestPath: renderPath, outDir, slug: String(renderDoc.slug ?? ""), full: false, xfade: xfade === true, keepFrames: false, emit, log, ...(opts.signal ? { signal: opts.signal } : {}) }); + const made = await stat(file).catch(() => null); + if (!made?.isFile() || made.size === 0) throw new Error(`${id}: the ${kind} render wrote no mp4 (${file})`); + return { file, rec, log, renderSeconds: Math.round((Date.now() - t0) / 100) / 10 }; + } catch (e) { + await rec?.fail(e); + throw e; + } finally { + await rm(renderPath, { force: true }); + } +} + +async function probeSeconds(file) { + const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]).catch(() => ({ stdout: "" })); + const n = Number(String(stdout).trim()); + return Number.isFinite(n) ? n : null; +} + +/** A video's frame size, `[w, h]`, or null. */ +export async function probeSize(file) { + const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]).catch(() => ({ stdout: "" })); + const [w, h] = String(stdout).trim().split(",").map(Number); + return Number.isFinite(w) && Number.isFinite(h) ? [w, h] : null; +} + +/** + * `umtool take <p> --id <t> --preview [--from <t0>]`: the whole take (or its window) at the preview tier. + * + * @param {string} projectDir + * @param {string} id + * @param {{ from?: string | null, window?: "full" | { at: number, dur: number } | null, log?: (l: string) => void, emit?: (ev: any) => void, + * render?: Function, projectId?: string, argv?: string[], signal?: AbortSignal }} [opts] + */ +export async function previewTake(projectDir, id, opts = {}) { + const { take, spec } = await storedSpec(projectDir, id); + const from = opts.from ?? null; + if (from) await checkFrom(projectDir, id, from); + const log = opts.log ?? (() => {}); + const c = await composeTake(projectDir, { ...spec, window: opts.window ?? spec.window ?? "full" }, { log }); + // A quick take's render is encoded veryfast (makeTake's QUICK_RENDER): its preview builds what it built. + const renderDoc = atPreviewTier(spec.quick ? /** @type {Record<string, any>} */ (mergePatch(c.renderDoc, QUICK_RENDER)) : c.renderDoc); + const takeDir = path.join(takesDirOf(projectDir), id); + const slug = String(c.manifest.slug ?? ""); + const p = previewPaths(takeDir, slug); + const t = renderDoc.render.tier; + log(`${id}: a preview — ${t.width}x${t.height}, ${t.preset}, crf ${t.crf}${previewKnobs(c.renderDoc.render).segments === "preview" ? ", its segments at the tier too" : ""}; the full render's files untouched${from ? `; reusing ${from}'s` : ""}${take.draft ? " (a draft: its stored patch)" : ""}`); + const b = await buildInto(projectDir, { id, label: spec.label, kind: PREVIEW_DIR, renderDoc, outDir: p.previewOut, from, xfade: takeXfade(c), opts }); + try { + await rename(b.file, p.previewMp4); + } catch (e) { + await b.rec?.fail(e); + throw e; + } + const seconds = await probeSeconds(p.previewMp4); + const doc = await b.rec?.done({ mp4: p.previewMp4, seconds }); + if (doc && doc.state !== "done") throw new Error(doc.error ?? `${id}: the preview left no mp4`); + b.log(`${id}: preview ${path.relative(takeDir, p.previewMp4)} — ${seconds ?? "?"} s, rendered in ${b.renderSeconds} s`); + return { id, mp4: p.previewMp4, seconds, renderSeconds: b.renderSeconds, tier: t }; +} + +async function checkFrom(projectDir, id, from) { + if (from === id) throw new Error(`--from ${from}: that is this take — name another take`); + const dir = path.join(takesDirOf(projectDir), from); + if (!(await isDir(dir))) throw new Error(`--from ${from}: no such take in ${path.basename(projectDir)}`); +} + +/** + * Where each entry sits in a build: its own schedule (out/<v>/sourced/schedule.json, when written by this + * build and naming every id), else the probed lengths of its segments end to end. + */ +async function buildPlaces(variantDir, ids, since) { + const sched = await readJson(path.join(variantDir, "schedule.json")); + const st = await stat(path.join(variantDir, "schedule.json")).catch(() => null); + const places = new Map(); + if (sched && st && st.mtimeMs >= since - 1000 && Array.isArray(sched.segments)) { + for (const s of sched.segments) places.set(s.id, { start: Number(s.start), duration: Number(s.duration ?? Number(s.end) - Number(s.start)) }); + if (ids.every((id) => places.has(id))) return { places, basis: "schedule" }; + } + places.clear(); + let t = 0; + for (const id of ids) { + const d = await probeSeconds(path.join(variantDir, "segments", `${id}.mp4`)); + if (d === null) throw new Error(`the changes build left no segment for ${id} (and no schedule naming it)`); + places.set(id, { start: t, duration: d }); + t += d; + } + return { places, basis: "segments" }; +} + +/** + * The base take's MEASURED schedule: its render's schedule.json (a deck cut's), else -- a cut without the + * deck writes none -- its segments' probed lengths end to end, when every entry of its timeline has one + * (a take's hard cuts). Null when neither: the full-cut times are then estimates. + */ +async function baseScheduleOf(variantDir, manifest) { + const sched = await readJson(path.join(variantDir, "schedule.json")); + if (sched && sched.estimated !== true && Array.isArray(sched.segments) && sched.segments.length) return sched; + const ids = sourcedEntries(manifest?.timeline).map((e) => e.id); + if (!ids.length) return null; + const segments = []; + let t = 0; + for (const id of ids) { + const d = await probeSeconds(path.join(variantDir, "segments", `${id}.mp4`)); + if (d === null) return null; + segments.push({ id, start: t, duration: d }); + t += d; + } + return { estimated: false, transition: 0, segments, from: "segments" }; +} + +/** The font a reel's labels are drawn in: the cut's bold, its regular, else a common one on this machine. */ +async function labelFont(render) { + const candidates = [render?.fontBold, render?.fontRegular, "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/liberation/LiberationSans-Bold.ttf"]; + for (const f of candidates) if (typeof f === "string" && f && (await stat(f).then((s) => s.isFile(), () => false))) return f; + return null; +} + +/** The ffmpeg drawtext filter of a reel piece's label (the text from a file: nothing to escape). Pure. */ +export function labelFilter({ textFile, font, height }) { + const size = Math.max(12, Math.round(height * 0.034)); + const esc = (p) => p.replace(/\\/g, "\\\\").replace(/:/g, "\\:").replace(/'/g, "\\'"); + return [ + `drawtext=textfile='${esc(textFile)}'`, + ...(font ? [`fontfile='${esc(font)}'`] : []), + `fontsize=${size}`, "fontcolor=white", "box=1", "boxcolor=black@0.66", `boxborderw=${Math.round(size * 0.45)}`, + `x=${Math.round(size * 0.9)}`, `y=${Math.round(size * 0.9)}`, + ].join(":"); +} + +/** + * `umtool take <p> --id <t> --changes [--from <t0>] [--pad 3] [--no-preview]`: the reel of what changed. + * + * @param {string} projectDir + * @param {string} id + * @param {{ from?: string | null, pad?: number, preview?: boolean, log?: (l: string) => void, emit?: (ev: any) => void, + * render?: Function, projectId?: string, argv?: string[], signal?: AbortSignal, now?: () => Date }} [opts] + */ +export async function changesTake(projectDir, id, opts = {}) { + const { take, spec } = await storedSpec(projectDir, id); + const from = opts.from ?? (typeof take.from === "string" ? take.from : null) ?? (typeof take.draftedFrom === "string" ? take.draftedFrom : null); + if (!from) throw new Error(`${id}: --from <take>: the take to compare with (this take does not record one)`); + await checkFrom(projectDir, id, from); + const pad = opts.pad ?? DEFAULT_PAD; + if (!Number.isFinite(pad) || pad < 0 || pad > 30) throw new Error("--pad is 0–30 seconds"); + const log = opts.log ?? (() => {}); + const takeDir = path.join(takesDirOf(projectDir), id); + const c = await composeTake(projectDir, { ...spec, window: "full" }, { log }); + const base = await baseManifest(projectDir, from); + const diff = diffTimelines(base.manifest.timeline, c.manifest.timeline); + const renderLines = renderLevelChanges(base.manifest, c.manifest); + // What renders: the ruled cut (its clip rulings applied, as the render's), so ids are the rendered ones. + const ruled = applyMontageRulings(c.manifest, await readMontageRulings(projectDir)).manifest; + const ids = sourcedEntries(ruled.timeline).map((e) => e.id); + const runs = planRuns(ids, diff); + const slug = String(c.manifest.slug ?? ""); + const p = previewPaths(takeDir, slug); + const preview = opts.preview !== false; + const baseSchedule = base.rendered ? await baseScheduleOf(path.join(takesDirOf(projectDir), from, "out", "sourced"), base.manifest) : null; + const changedIds = new Set(diff.changed.map((x) => x.id)); + log( + `${id}: changes against ${from}${base.rendered ? "" : " (a draft: its stored patch, as it would render now)"} — ` + + `${diff.changed.length} item(s) changed or added, ${diff.removed.length} removed` + + `${renderLines.length ? `; outside the timeline: ${renderLines.slice(0, 6).join(", ")}${renderLines.length > 6 ? ", …" : ""}` : ""}`, + ); + const doc = { + version: 1, + take: id, + from, + madeAt: (opts.now ?? (() => new Date()))().toISOString(), + pad, + tier: preview ? "preview" : "full", + reel: null, + times: null, + render: renderLines, + items: /** @type {any[]} */ ([]), + }; + if (!runs.length) { + log(`${id}: no item changed against ${from}${renderLines.length ? " — only render-level knobs: render a --preview to judge them" : ""}; no reel`); + await writeAtomic(p.changesFile, doc); + return { id, mp4: null, changes: doc }; + } + const want = new Set(runs.flatMap((r) => r.ids)); + let renderDoc = windowManifest(ruled, ids.filter((x) => want.has(x))); + // Its segments at the tier too, unless render.preview.segments says otherwise: a changes build is a + // window of the cut, whose post items key by their window's plan (a clock's, a progress bar's) and are + // built again whatever the base had -- so a fast encode of them forfeits no reuse. + if (preview) renderDoc = atPreviewTier(renderDoc, { segments: "preview" }); + log(`${id}: rendering ${want.size} entr${want.size === 1 ? "y" : "ies"} in ${runs.length} run(s): ${runs.map((r) => r.ids.join(" ")).join(" | ")}`); + const since = Date.now(); + const b = await buildInto(projectDir, { id, label: spec.label, kind: CHANGES_DIR, renderDoc, outDir: p.changesOut, from, xfade: takeXfade(c), opts }); + try { + const built = await buildPlaces(path.join(p.changesOut, "sourced"), [...want].sort((x, y) => ids.indexOf(x) - ids.indexOf(y)), since); + const measured = new Map([...changedIds].filter((x) => built.places.has(x)).map((x) => [x, built.places.get(x).duration])); + const full = fullCutTimes({ timeline: ruled.timeline, changedIds, base: baseSchedule, measured }); + const pieces = reelPieces(runs, built.places, full.times, pad); + // Cut, labelled, joined. + const work = path.join(p.changesOut, "reel-work"); + await rm(work, { recursive: true, force: true }); + await mkdir(work, { recursive: true }); + const font = await labelFont(renderDoc.render); + const size = (await probeSize(b.file)) ?? [Number(renderDoc.render?.width ?? 1920), Number(renderDoc.render?.height ?? 1080)]; + const tier = renderDoc.render?.tier; + const enc = ["-c:v", "libx264", "-preset", String(tier?.preset ?? renderDoc.render?.preset ?? "medium"), "-crf", String(tier?.crf ?? renderDoc.render?.crf ?? 20), "-pix_fmt", "yuv420p", "-r", String(renderDoc.render?.fps ?? 30), + "-c:a", "aac", "-b:a", String(renderDoc.render?.audioBitrate ?? "160k"), "-ar", String(renderDoc.render?.audioRate ?? 48000), "-ac", String(renderDoc.render?.audioChannels ?? 2)]; + const files = []; + let reelAt = 0; + for (const [k, piece] of pieces.entries()) { + const text = path.join(work, `label-${k}.txt`); + await writeFile(text, piece.label, "utf8"); + const out = path.join(work, `piece-${String(k).padStart(3, "0")}.mp4`); + const dur = Math.max(0.1, piece.to - piece.from); + await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-ss", piece.from.toFixed(3), "-i", b.file, "-t", dur.toFixed(3), "-vf", labelFilter({ textFile: text, font, height: size[1] }), ...enc, out], { maxBuffer: 1 << 26 }); + const got = (await probeSeconds(out)) ?? dur; + piece.reelStart = round3(reelAt); + piece.reelEnd = round3(reelAt + got); + reelAt += got; + files.push(out); + } + const list = path.join(work, "pieces.txt"); + await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n", "utf8"); + const tmp = p.changesMp4.replace(/\.mp4$/, `.${process.pid}.tmp.mp4`); + await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-c", "copy", "-movflags", "+faststart", tmp], { maxBuffer: 1 << 26 }); + await rename(tmp, p.changesMp4); + await rm(work, { recursive: true, force: true }); + const seconds = await probeSeconds(p.changesMp4); + doc.reel = path.relative(takeDir, p.changesMp4); + doc.times = { + basis: full.basis, + how: full.basis === "measured" + ? `${from}'s measured ${baseSchedule?.from === "segments" ? "segment lengths (its out/sourced/segments, end to end)" : "schedule (out/sourced/schedule.json)"}, each changed item's length as the changes build measured it` + : baseSchedule + ? `estimates: a changed item was not measured` + : `estimates: ${from} ${base.rendered ? "left no schedule or segments to measure" : "was never rendered"} — each unchanged item's length estimated, the changed ones measured`, + build: built.basis, + }; + doc.items = pieces.map((x) => ({ + id: x.id, type: x.type, kind: x.kind, kinds: x.kinds, label: x.label, + at: x.fullStart, end: x.fullEnd, exact: x.exact, + reel: { from: x.reelStart, to: x.reelEnd }, + ...(x.type === "join" ? { after: x.after, before: x.before } : {}), + })); + await writeAtomic(p.changesFile, doc); + const rd = await b.rec?.done({ mp4: p.changesMp4, seconds }); + if (rd && rd.state !== "done") throw new Error(rd.error ?? `${id}: the changes reel left no mp4`); + for (const it of doc.items) b.log(` ${it.label} (reel ${clockOf(it.reel.from)})`); + b.log(`${id}: changes reel ${doc.reel} — ${doc.items.length} piece(s), ${seconds ?? "?"} s; full-cut times: ${doc.times.basis} (${doc.times.how}); list: ${CHANGES_FILE}`); + return { id, mp4: p.changesMp4, seconds, changes: doc, renderSeconds: b.renderSeconds }; + } catch (e) { + await b.rec?.fail(e); + throw e; + } +} + +async function writeAtomic(file, doc) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, file); +} + +/** A take step's fast-feedback kind: "preview", "changes", or null for the take's own render (lib/queue). Pure. */ +export function fastKindOf(argv) { + const a = Array.isArray(argv) ? argv : []; + if (a[0] !== "take") return null; + if (a.includes("--changes")) return "changes"; + if (a.includes("--preview")) return "preview"; + return null; +} + +/** + * What `umtool take status` says of a take's fast-feedback renders: each one's record (out/preview/render.json, + * out/changes/render.json, resolved) and its output, when there. + * @param {string} takeDir + * @param {string} slug + */ +export async function fastRenders(takeDir, slug) { + const { readRenderRecord } = await import("./renderRecord.mjs"); + const p = previewPaths(takeDir, slug); + const one = async (dir, mp4) => { + const rec = await readRenderRecord(dir); + const st = await stat(mp4).catch(() => null); + if (!rec && !st) return null; + return { + state: rec?.state ?? (st ? "done" : null), + mp4: st?.isFile() ? mp4 : null, + mp4Bytes: st?.size ?? null, + seconds: rec?.seconds ?? null, + endedAt: rec?.endedAt ?? null, + error: rec?.error ?? null, + log: rec ? path.join(dir, "render.log") : null, + }; + }; + const [preview, changes, list] = await Promise.all([one(p.previewOut, p.previewMp4), one(p.changesOut, p.changesMp4), readJson(p.changesFile)]); + return { + preview, + changes: changes || list ? { ...(changes ?? { state: null, mp4: null }), list: list ? p.changesFile : null, items: Array.isArray(list?.items) ? list.items.length : null, from: list?.from ?? null } : null, + }; +} diff --git a/umtool/lib/report/takePreview.test.mjs b/umtool/lib/report/takePreview.test.mjs @@ -0,0 +1,181 @@ +// takePreview.mjs: the preview tier's knobs, the tier keyed apart from the full render's chunks, what +// changed between two takes (per kind), the reel's runs and pieces, and the full-cut time math. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + PREVIEW_DEFAULTS, atPreviewTier, clockOf, diffTimelines, entryChangeKinds, fullCutTimes, labelFilter, pieceLabel, planRuns, + previewKnobs, previewPaths, reelPieces, renderLevelChanges, +} from "./takePreview.mjs"; +import { fastKindOf } from "../queue/cli.mjs"; +import { chunkJobs, chunkVideoArgs, outputTier, tierFinalArgs } from "umtool-report-to-video/build-video"; + +const R = { width: 1920, height: 1080, fps: 30, preset: "medium", crf: 20, audioRate: 48000, audioChannels: 2 }; + +test("previewKnobs: the defaults, a knob over them, never larger than the cut, checked", () => { + assert.deepEqual(previewKnobs(R), { ...PREVIEW_DEFAULTS }); + assert.deepEqual(previewKnobs({ ...R, preview: { width: 960, height: 540, crf: 30 } }), { width: 960, height: 540, preset: "veryfast", crf: 30, segments: "shared" }); + // A 640x360 cut previews at its own size. + assert.deepEqual(previewKnobs({ ...R, width: 640, height: 360 }).width, 640); + assert.deepEqual(previewKnobs({ ...R, width: 640, height: 360 }).height, 360); + assert.throws(() => previewKnobs({ ...R, preview: { preset: "warp" } }), /x264 preset/); + assert.throws(() => previewKnobs({ ...R, preview: { crf: 99 } }), /0–51/); + assert.throws(() => previewKnobs({ ...R, preview: { segments: "half" } }), /shared/); + assert.throws(() => previewKnobs({ ...R, preview: "yes" }), /an object/); +}); + +test("atPreviewTier: render.tier set, the cut's own encode kept unless segments: preview", () => { + const doc = { slug: "s", render: R, timeline: [] }; + const t = atPreviewTier(doc); + assert.deepEqual(t.render.tier, { name: "preview", width: 1280, height: 720, preset: "veryfast", crf: 26 }); + assert.equal(t.render.preset, "medium"); + assert.equal(t.render.crf, 20); + assert.equal(doc.render.tier, undefined, "the manifest is copied"); + const s = atPreviewTier({ ...doc, render: { ...R, preview: { segments: "preview" } } }); + assert.equal(s.render.preset, "veryfast"); + assert.equal(s.render.crf, 26); + // A changes reel's default (segments at the tier), unless the manifest says. + assert.equal(atPreviewTier(doc, { segments: "preview" }).render.preset, "veryfast"); + assert.equal(atPreviewTier({ ...doc, render: { ...R, preview: { segments: "shared" } } }, { segments: "preview" }).render.preset, "medium"); + assert.deepEqual(outputTier(t.render), t.render.tier); + assert.equal(outputTier(R), null); +}); + +test("a preview's chunk keys are never a full render's: the tier's scale, preset and crf are in the key", () => { + const job = { + segments: ["/w/a.mp4", "/w/b.mp4"], durs: [2, 2], starts: [0, 2], span: { a: 0, b: 60 }, D: 0, totalFrames: 120, outPath: "/w/c.mp4", + }; + const full = chunkVideoArgs({ ...job, render: R }); + const prev = chunkVideoArgs({ ...job, render: atPreviewTier({ render: R }).render }); + assert.notDeepEqual(full.keyArgv, prev.keyArgv); + assert.ok(prev.keyArgv.join(" ").includes("scale=1280:720")); + assert.ok(prev.argv.includes("veryfast") && prev.argv.includes("26")); + // The full render's argv is what it always was: no scale, its own preset and crf. + assert.ok(!full.keyArgv.join(" ").includes("scale=1280")); + assert.ok(full.argv.includes("medium") && full.argv.includes("20")); + assert.equal(tierFinalArgs(R, "a", "b"), null); + // A preview encodes more chunks at once (its fast encode leaves the decode the bottleneck); the env still wins. + assert.equal(chunkJobs({}, R), 2); + assert.equal(chunkJobs({}, atPreviewTier({ render: R }).render), 4); + assert.equal(chunkJobs({ REPORT_VIDEO_CHUNK_JOBS: "3" }, atPreviewTier({ render: R }).render), 3); + assert.ok(tierFinalArgs(atPreviewTier({ render: R }).render, "a", "b")?.join(" ").includes("scale=1280:720")); +}); + +test("previewPaths: the outputs beside the full render's, the builds in their own dirs", () => { + const p = previewPaths("/r/p/takes/t", "slug"); + assert.equal(p.previewMp4, "/r/p/takes/t/out/slug.preview.mp4"); + assert.equal(p.previewOut, "/r/p/takes/t/out/preview"); + assert.equal(p.changesMp4, "/r/p/takes/t/out/slug.changes.mp4"); + assert.equal(p.changesFile, "/r/p/takes/t/changes.json"); +}); + +const post = (id, o = {}) => ({ type: "post", id, text: "words", narration: { script: "words", pick: 0, takes: [{ file: `n/${id}/take-1.wav` }] }, ...o }); + +test("entryChangeKinds: each kind of change by its keys, the narration read closely", () => { + const a = post("p1"); + const k = (b) => entryChangeKinds(a, b).kinds; + assert.deepEqual(k(a), []); + // A new take picked: re-read; one with a revoice step: re-voiced; an older one picked again: re-picked. + assert.deepEqual(k({ ...a, narration: { ...a.narration, pick: 1, takes: [...a.narration.takes, { file: "n/p1/take-2.wav" }] } }), ["re-read"]); + assert.deepEqual(k({ ...a, narration: { ...a.narration, pick: 1, takes: [...a.narration.takes, { file: "n/p1/take-2.revoice.wav", steps: [{ op: "revoice" }] }] } }), ["re-voiced"]); + const two = { ...a, narration: { ...a.narration, takes: [...a.narration.takes, { file: "n/p1/take-2.wav" }] } }; + assert.deepEqual(entryChangeKinds(two, { ...two, narration: { ...two.narration, pick: 1 } }).kinds, ["re-picked"]); + assert.deepEqual(k({ ...a, narration: { ...a.narration, rate: 1.1 } }), ["read knobs"]); + assert.deepEqual(k({ ...a, fx: [{ kind: "caption" }] }), ["fx"]); + assert.deepEqual(k({ ...a, hold: 2 }), ["hold"]); + assert.deepEqual(k({ ...a, panel: "side" }), ["panel"]); + assert.deepEqual(k({ ...a, pictureOnly: true }), ["picture only"]); + assert.deepEqual(k({ ...a, thread: { read: true } }), ["thread"]); + assert.deepEqual(k({ ...a, redact: ["x"] }), ["slurs"]); + assert.deepEqual(k({ ...a, media: [{ start: 2, end: 9 }] }), ["media trim"]); + assert.deepEqual(k({ ...a, wibble: 1 }), ["edited"]); + const clip = { type: "clip", id: "c1", start: 1, end: 4 }; + assert.deepEqual(entryChangeKinds(clip, { ...clip, cutEnd: 3.5 }).kinds, ["media trim"]); +}); + +test("diffTimelines: added, changed, moved and removed, in the new timeline's order", () => { + const A = [post("a"), post("b"), post("c"), post("d")]; + const B = [post("a"), post("c"), post("b", { hold: 1 }), { type: "video", id: "v", src: "x.mp4" }]; + const d = diffTimelines(A, B); + assert.deepEqual(d.changed.map((c) => [c.id, c.kind, c.kinds]), [ + ["c", "moved", ["moved"]], + ["b", "changed", ["moved", "hold"]], + ["v", "added", ["added video"]], + ]); + assert.deepEqual(d.removed, [{ id: "d", after: "c", before: null, type: "post" }]); + assert.deepEqual(diffTimelines(A, A), { changed: [], removed: [] }); +}); + +test("renderLevelChanges: render leaves and top-level keys, not the timeline nor render.preview", () => { + const a = { slug: "s", timeline: [post("a")], render: { crf: 20, chrome: { deck: { x: 1 } } } }; + const b = { slug: "s", timeline: [post("b")], render: { crf: 20, chrome: { deck: { x: 2 } }, preview: { crf: 30 } }, title: "T" }; + assert.deepEqual(renderLevelChanges(a, b), ["render.chrome.deck.x", "title"]); +}); + +test("planRuns: a change with a neighbour each side, a removal as its join, touching runs merged", () => { + const ids = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; + const diff = { + changed: [{ id: "b", kind: "changed", kinds: ["re-read"] }, { id: "c", kind: "changed", kinds: ["fx"] }, { id: "i", kind: "added", kinds: ["added video"] }], + removed: [{ id: "x", after: "e", before: "f", type: "post" }], + }; + const runs = planRuns(ids, diff); + assert.deepEqual(runs.map((r) => r.ids), [["a", "b", "c", "d", "e", "f"], ["h", "i", "j"]]); + assert.deepEqual(runs[0].focus.map((f) => [f.type, f.id]), [["item", "b"], ["item", "c"], ["join", "x"]]); + assert.deepEqual(planRuns(ids, { changed: [{ id: "a", kind: "changed", kinds: ["fx"] }], removed: [] }).map((r) => r.ids), [["a", "b"]]); +}); + +test("fullCutTimes: the base's measured schedule moved by the changed items' measured lengths", () => { + // Base: a 10, b 20, c 5, d 7 (an intro-less hard-cut cut). New: b re-read to 25 s, x (6 s) added after c, d removed. + const base = { estimated: false, transition: 0, segments: [ + { id: "a", start: 0, duration: 10 }, { id: "b", start: 10, duration: 20 }, { id: "c", start: 30, duration: 5 }, { id: "d", start: 35, duration: 7 }, { id: "e", start: 42, duration: 3 }, + ] }; + const timeline = [post("a"), post("b"), post("c"), post("x"), post("e")]; + const measured = new Map([["b", 25], ["x", 6]]); + const r = fullCutTimes({ timeline, changedIds: new Set(["b", "x"]), base, measured }); + assert.equal(r.basis, "measured"); + const at = (id) => [r.times.get(id)?.start, r.times.get(id)?.end]; + assert.deepEqual(at("a"), [0, 10]); + assert.deepEqual(at("b"), [10, 35]); + assert.deepEqual(at("c"), [35, 40]); + assert.deepEqual(at("x"), [40, 46]); + // e: 42 in the base; +25 +6 for b and x, −20 (b's old) −7 (d removed) = 46. + assert.deepEqual(at("e"), [46, 49]); + // A changed item not measured: from then on an estimate. + const est = fullCutTimes({ timeline, changedIds: new Set(["b", "x"]), base, measured: new Map([["b", 25]]), estimate: () => 4 }); + assert.equal(est.basis, "estimate"); + assert.equal(est.times.get("a")?.exact, true); + assert.equal(est.times.get("e")?.exact, false); + // No base schedule: every length estimated but the measured ones. + const none = fullCutTimes({ timeline, changedIds: new Set(["b"]), base: null, measured: new Map([["b", 25]]), estimate: () => 4 }); + assert.equal(none.basis, "estimate"); + assert.deepEqual([none.times.get("c")?.start, none.times.get("e")?.start], [29, 37]); +}); + +test("reelPieces: the item ± pad within its run, a removal's join, labelled with the full cut's time", () => { + const runs = [{ ids: ["a", "b", "c"], focus: [{ type: "item", id: "b", index: 1, kind: "changed", kinds: ["re-voiced"] }] }, + { ids: ["d", "e"], focus: [{ type: "join", id: "x", after: "d", before: "e", index: 3, kind: "removed", kinds: ["removed post"] }] }]; + const build = new Map([["a", { start: 0, duration: 2 }], ["b", { start: 2, duration: 10 }], ["c", { start: 12, duration: 1 }], ["d", { start: 13, duration: 4 }], ["e", { start: 17, duration: 5 }]]); + const full = new Map([["b", { start: 1279.5, end: 1289.5, exact: true }], ["d", { start: 1500, end: 1504, exact: false }], ["e", { start: 1504, end: 1509, exact: false }]]); + const p = reelPieces(runs, build, full, 3); + assert.deepEqual([p[0].from, p[0].to], [0, 13]); + assert.equal(p[0].label, "21:19 · b · re-voiced"); + assert.deepEqual([p[1].from, p[1].to], [14, 20]); + assert.equal(p[1].label, "25:04 · x removed — the join · removed post"); + assert.equal(p[1].exact, false); +}); + +test("clockOf, pieceLabel and the label's filter", () => { + assert.equal(clockOf(1279.9), "21:19"); + assert.equal(clockOf(3725), "1:02:05"); + assert.equal(pieceLabel({ type: "item", id: "k", kinds: ["fx", "hold"] }, 61), "1:01 · k · fx, hold"); + const f = labelFilter({ textFile: "/w/label 1.txt", font: "/f/a:b.ttf", height: 720 }); + assert.ok(f.startsWith("drawtext=textfile='/w/label 1.txt'")); + assert.ok(f.includes("fontfile='/f/a\\:b.ttf'")); + assert.ok(f.includes("fontsize=24")); +}); + +test("fastKindOf: a take step's preview or changes, never the take's own render", () => { + assert.equal(fastKindOf(["take", "p", "--id", "t", "--preview"]), "preview"); + assert.equal(fastKindOf(["take", "p", "--id", "t", "--changes", "--preview"]), "changes"); + assert.equal(fastKindOf(["take", "p", "--id", "t", "--full"]), null); + assert.equal(fastKindOf(["takes", "ls", "p"]), null); +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -4934,6 +4934,33 @@ export function xfadeConcatArgs({ segments, durs, render, outPath, railPlan = nu ]; } +/** The argv that brings a finished cut to its tier's size and encode, the sound copied. Pure. */ +export function tierFinalArgs(render, inPath, outPath) { + const t = outputTier(render); + if (!t) return null; + return [ + "-nostdin", "-v", "error", "-y", "-i", inPath, + "-map", "0:v:0", "-map", "0:a?", + "-vf", `scale=${t.width}:${t.height}:flags=bicubic,setsar=1`, + "-c:v", "libx264", "-preset", t.preset, "-crf", String(t.crf), "-pix_fmt", "yuv420p", + "-c:a", "copy", "-movflags", "+faststart", + outPath, + ]; +} + +/** A final not yet at its tier's size (outputTier) is encoded to it, through a rename. Nothing without a tier. */ +async function tierFinalPass(final, render) { + const t = outputTier(render); + if (!t) return; + const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", final]); + const [w, h] = String(stdout).trim().split(",").map(Number); + if (w === t.width && h === t.height) return; + const tmp = final.replace(/\.mp4$/, `.${process.pid}.tier.mp4`); + await execFileP(FFMPEG, /** @type {string[]} */ (tierFinalArgs(render, final, tmp)), { maxBuffer: 1 << 26 }); + await rename(tmp, final); + EMIT("note", { message: `${t.name}: the cut ${w}x${h} → ${t.width}x${t.height} (${t.preset}, crf ${t.crf})` }); +} + // ---- the chunked final encode (chunked-encode.mjs) --------------------------- /** Is the final encode chunked? `REPORT_VIDEO_CHUNKED=0` or `render.chunkedEncode: false` say no. */ @@ -4942,17 +4969,54 @@ export function chunkedEncodeOn(render = {}, env = process.env) { return render?.chunkedEncode !== false; } -/** How many chunks are encoded at once: `REPORT_VIDEO_CHUNK_JOBS`, else 2. */ -export function chunkJobs(env = process.env) { +/** + * How many chunks are encoded at once: `REPORT_VIDEO_CHUNK_JOBS`, else 2 -- 4 at a preview's tier + * (outputTier), whose fast encode leaves each chunk's single-threaded decode and overlay the bottleneck. + */ +export function chunkJobs(env = process.env, render = null) { const n = Number(env.REPORT_VIDEO_CHUNK_JOBS); - return Number.isInteger(n) && n >= 1 ? Math.min(n, 8) : 2; + if (Number.isInteger(n) && n >= 1) return Math.min(n, 8); + return outputTier(render) ? 4 : 2; } -/** A chunk's picture encode: the cut's own settings, no sound. */ +/** + * THE OUTPUT TIER (umtool take … --preview / --changes; lib/report/takePreview.mjs): `render.tier`, which + * only a preview's render manifest carries -- `{ name: "preview", width, height, preset, crf }`. The cut is + * composed exactly as the full render composes it (the same 1920×1080 layout, segments, chrome frames and + * sound); only its FINAL picture is encoded smaller and faster: each chunk of the final encode scaled to + * `width`×`height` at the tier's preset and crf. Those are in the chunk's argv, so in its key: a preview's + * chunks key apart from the full render's and never stand in for them. Null (every full render): nothing + * changes, byte for byte. Pure. + * + * @returns {{ name: string, width: number, height: number, preset: string, crf: number } | null} + */ +export function outputTier(render) { + const t = render?.tier; + if (!t || typeof t !== "object" || Array.isArray(t)) return null; + const even = (v, d) => { + const n = Math.round(Number(v ?? d)); + if (!Number.isFinite(n) || n < 16 || n > 7680) throw new Error(`render.tier: width/height must be 16–7680, got ${JSON.stringify(v)}`); + return n - (n % 2); + }; + const crf = Number(t.crf ?? 26); + if (!Number.isFinite(crf) || crf < 0 || crf > 51) throw new Error(`render.tier.crf must be 0–51, got ${JSON.stringify(t.crf)}`); + const preset = String(t.preset ?? "veryfast"); + if (!/^(ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow)$/.test(preset)) throw new Error(`render.tier.preset: an x264 preset, got ${JSON.stringify(t.preset)}`); + return { name: String(t.name ?? "preview"), width: even(t.width, 1280), height: even(t.height, 720), preset, crf }; +} + +/** The scale filter a tier lays on the final picture (`[in]…[out]`), or null without one. Pure. */ +export function tierScaleFilter(render, inLabel, outLabel = "[vtier]") { + const t = outputTier(render); + if (!t) return null; + return `${inLabel}scale=${t.width}:${t.height}:flags=bicubic,setsar=1${outLabel}`; +} + +/** A chunk's picture encode: the cut's own settings (a tier's, when it has one), no sound. */ const chunkEncodeArgs = (render) => [ "-c:v", "libx264", - "-preset", render.preset ?? "medium", - "-crf", String(render.crf ?? 20), + "-preset", outputTier(render)?.preset ?? render.preset ?? "medium", + "-crf", String(outputTier(render)?.crf ?? render.crf ?? 20), "-pix_fmt", "yuv420p", "-r", String(render.fps), "-an", @@ -5041,6 +5105,10 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins // Nothing laid over and no dip: -map cannot name a trim's output twice, so // the label is used as is (it is a filter output, which -map can name). } + // A preview's tier (outputTier): the picture scaled last -- in the graph, so in the key. + const scaled = tierScaleFilter(render, dp.label); + if (scaled) parts.push(scaled); + const outLabel = scaled ? "[vtier]" : dp.label; const graph = parts.join(";"); const keyGraph = hk ? graph.replace(hf.chain, hk.chain) : graph; const head = ["-nostdin", "-v", "error", "-y"]; @@ -5049,7 +5117,7 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins ...segs.flatMap((s) => ["-i", s]), ...(hf ? hf.inputs : []), "-filter_complex", graph, - "-map", dp.label, + "-map", outLabel, ...chunkEncodeArgs(render), outPath, ]; @@ -5058,7 +5126,7 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins ...segs.flatMap((_, k) => ["-i", `<in:${k}>`]), ...(hk ? hk.inputs : []), "-filter_complex", keyGraph, - "-map", dp.label, + "-map", outLabel, ...chunkEncodeArgs(render), ]; return { argv, keyArgv, inputs, first, last }; @@ -5459,7 +5527,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, EMIT("note", { message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused` + `${plan.some((p) => p.pooled) ? `, ${plan.filter((p) => p.pooled).length} from the render pool` : ""}), ` + - `${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs()} at a time)`, + `${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs(process.env, render)} at a time)`, }); // Why, grouped, so a line says what changed rather than listing 80 chunks. const byWhy = new Map(); @@ -5515,7 +5583,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, }); }); const tEnc = Date.now(); - await runPool([audioJob, ...jobs], chunkJobs()); + await runPool([audioJob, ...jobs], chunkJobs(process.env, render)); const encSeconds = (Date.now() - tEnc) / 1000; // Joined: the concat demuxer over the chunks in order, the sound beside. @@ -7331,6 +7399,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ); } await pruneFrames(); + // A preview's tier (outputTier) on a final that did not pass the chunked encode (a stream-copied hard + // cut with no deck, a rail's pass): scaled once here, the sound copied. + await tierFinalPass(final, render); const { stdout } = await execFileP(FFPROBE, [ "-v", "error", "-show_entries", "format=duration,size",