commit ba9d84cdceac9abacc2181eec4e4291a0006ce91
parent 3656ae4747a9bb1794418af389bce9a0d3c5396b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 02:22:37 -0400
Merge lane/live-preview: the deck composed live over the playing clip in the clip editor, Render this clip, a deck cut's build budget sized to the cut
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
28 files changed, 1965 insertions(+), 31 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -2,6 +2,8 @@
## [Unreleased]
- **A clip in a fact-check video can stamp and count more than once.** The clip editor's **Count & stamp** box is now **Marks**, on every clip: a list of the clip's marks, each its own stamp and its own step of the tally at its own second — its verdict picked by this cut's words (Episodes, Grift…), when it lands (**Set at playhead**, Shift+S for the selected mark), how long it stays, whether it is drawn, how much it counts, what it says, **Remove**. **Add mark at playhead** (Shift+M) adds one under a new id; **Clear** removes them all. Two stamps on one clip that would sit on each other are refused, saying where the second may land. From a terminal: `umtool set <project> <clip> mark.add=Episodes@190.2`, `mark.remove=<id>`, `mark.verdict=…`, `marks=<json>`; `umtool show` lists them. A clip with one mark is written as before, so an existing video renders the same.
+- **Walk a report video's clips in umtool's clip editor with the on-screen chrome drawn over them, no build.** Under the clip editor's player, **Live preview** draws the cut's deck over the playing clip, in step with the playhead: the clip's date title and subtitle, the timeline with its pip and flags, the tally as it stands at that moment (stepping when a stamp lands), the stamp, the posts, the QR, and the finale's page on the last clip. A trimmed edge, a moved stamp or new words show about a second after they are saved; an unsaved nudge moves the picture at once. **Title** and **Subtitle** under the picture edit the clip's on-screen words, shown as they are typed. A line under the picture says what the preview does not do (the build snaps each edge to a silence and crossfades the clips). **Render this clip** makes the clip with its chrome exactly as the build would, in a minute or two, and plays it in place (`node umtool/report-to-video/build-video.mjs <manifest> --skip-fetch --clip-preview <id>`). The On-screen preview now draws the finale too. Needs a restart of umtool.
+- **A long report video with on-screen chrome is no longer stopped partway through its build.** umtool gave a build two minutes per clip (a whole-cut take one minute), which a 36-clip, 25-minute cut with its panel, posts column and stamps outruns: drawing those alone takes over half an hour. A build or take of a cut with on-screen chrome now gets five times the cut's length when that is longer. Needs a restart of umtool.
- **A video attached from a local archive gets its date when the archive writes it as 2019-10-31.** `attach-media` with `createRecords` read a folder's "Published on …" line only as "July 13th 2018" or "March 1, 2019"; it now reads "2019-10-31" and "2019/10/31" too, and a date that is not on the calendar is no date. Records it made before without a date can be dated now: `"fillDates": true` on `pnpm ops attach-media` (`--fill-dates` on `archilyzer media attach`) gives a held record that attach-media made, and that has no upload date, the date from its folder's description.txt — recorded in its metadata history. A record that has a date, or that attach-media did not make, is never touched. The log and the summary list them as "dated"; with `"dryRun": true` it only lists them.
- **A report video's sound stays with its picture from the first clip to the last.** A clip whose sound started late (its cut reached back before the fetched window's media) or had a gap in it (a seam in the source's stream) used to pull that clip's sound, and every later clip's, early — on a 20-minute cut by half a second from the 13th minute on. Each clip's sound is now laid on its own clock before the clips are joined, and every build writes `sync.json` beside its schedule saying where each clip's sound landed against its picture; the build log names any clip more than a frame off. A video's manifest can now also set when a fact-check stamp lands and the count steps (`claim.at`, a second of the source), how long it stays, a count of more than one, a stamp that counts without showing, the stamp's words, size, entrance and opacity; nudge a clip's sound against its picture, its volume and fades (`audio`); align a timeline flag's label and lay crowded labels in two rows; and `node umtool/report-to-video/variants.mjs <take out dir>` makes smaller copies of a finished cut — 1080p, 720p and one under 24 MiB by default (`render.variants`). Needs a rebuild of the video.
- **A fact-check video can count without the stamp, colour its timeline by verdict, flag the moments time passes, and leave the QR off posts.** In umtool's fact-check form, **stamp effect** off draws no verdict stamp over the footage, while the tally in the panel still counts each claim at the second its stamp would have landed. The On-screen settings have **colour** under timeline: **verdict** lights each clip that carries a claim in its verdict's colour — the tally's colour — with a shape per verdict (circle, diamond, square, triangle, ring), and the tally's cells carry the same shapes. **qr codes** under posts off leaves the QR off every post card, popup or feed, and the words take its width; each clip's own QR stays. A video's manifest can flag moments on the timeline (`render.chrome.deck.markers`: "3 to 5 weeks pass" after a clip), each popping in as the timeline reaches it and staying lit. Needs a restart of umtool.
diff --git a/plans/live-preview.md b/plans/live-preview.md
@@ -0,0 +1,84 @@
+# Live preview — walk a deck cut in the clip editor (lane `lane/live-preview`, P)
+
+Asked by the operator on 2026-10-23 for the Huck video's final pass: walk the clips in umtool and adjust windows
+and words there, "rather than waiting for and watching a rendered file each time". A full build of the Huck cut is
+about an hour; this lane is the loop without it.
+
+## Rulings
+
+- The live preview is mounted in the clip editor by one line (`LiveDeckPreview` under the player); the player's
+ handle gives it the media element and the source second (`media()`, `sourceTime()`), nothing else changes there.
+- The composition is the build's own pages (chrome-deck, chrome-feed, chrome-posts, chrome-stamp, chrome-finale),
+ composed by `POST /api/report/chrome/preview` and loaded in iframes at their rects, seeked in cut seconds
+ (`deck:seek`). No second implementation of any page.
+- The preview's schedule is the manifest's ESTIMATE (`estimate: true` → `scheduleForPreview({ estimate })`), even
+ when a build's schedule exists: the playhead is mapped through the play window (`liveClock.mjs`, deck.mjs's
+ `playWindow` rule), which is what the estimate and a stamp's `claim.at` use, so the two always agree and a moved
+ window is placed where it is now.
+- source second → cut second: `seg.start + (t − playWindow.from)`; before the window the clip's first frame,
+ after it the last (`cutTimeAt`). An unsaved edge nudge moves the clock at once (the draft cut is passed).
+- The tally at t counts every stamp `landed ≤ t` by its `count`; the stamp on screen is a drawn, non-finale stamp
+ with `at ≤ t < out[1]` (`stampAt`); the finale is up over `finale.from`–`to`. These drive the readout and the
+ `data-live-*` attributes; the pages draw themselves from the same schedule.
+- Marks (lane/clip-marks): every stamp a clip carries is its own (`clipStamps`, one per mark, landing order),
+ listed under the picture as "stamps|counts <mark> at <source s>", each a seek to a second before it lands;
+ each lands and steps the tally at its own second (the schedule's, through the same play-window clock).
+- The footage is the editor's `<video>` drawn into a canvas at the footage box (the feed's box on a feed cut)
+ every animation frame: fitted and padded in the palette's ground (`deckFraming`'s fit), carried along
+ `footageAt`'s moves. No second decode.
+- A save through the editor (window, claim, words) changes the manifest token; the pages are composed again
+ (debounced 250 ms). Typed words are patched into the deck page by `deck:text` before the save.
+- The deck's words for a clip are saved through the clip editor's new op `onscreen` (the On-screen table's writer,
+ `updateOnscreen`, with the editor's token); the clip view carries `onscreen`.
+- The finale page answers `?preview=1` (`finale:ready`, seeked in cut seconds); the preview route composes it
+ (`finale-preview/`, served by the files route) and returns `finale {geometry, from, to, src}`; it is laid last,
+ over the deck's page, while t is inside its window — in the clip editor and in the On-screen section.
+- The route also returns `leadIn` (render.leadIn) and `verdictLabels` (the tally's words).
+- A cut without the deck shows one line ("no on-screen deck") and no Render this clip.
+- "preview: approximate" lists: the edge snap, no joins, no room mute or Audio knobs, this browser's drawing.
+- Render this clip = `build-video.mjs --clip-preview <id>` (`--skip-fetch`), one job (`POST /api/report/clip-render`,
+ `clip render <project> <clip>`), in the heavy slot (`takesHeavySlot`: true). It builds the clip's segment as the
+ full build does (into `segments/`, reused by the next build), measures the other segments on disk and
+ estimates the missing ones (`measureChromeSchedule({ durs, estimated })`), renders every chrome region over the
+ segment's window into `out/<variant>/clip-preview/` (its own `schedule.json` and `chrome/`, never the build's),
+ lays them over the one segment with its own join (`clipPreviewJoin`: the hold, the footage move, `muteFrom`, the
+ end fade when last; no crossfade, no dip), writes `<id>.mp4` and `<id>.json` (the window it was made from), and
+ prunes its frame sequences. The editor shows the file and says when the window has moved since.
+- "Render from here" was not built.
+- A build's job budget (`buildTimeoutMs`) and a whole-cut take's (`takeTimeoutMs`) are at least `RENDER_BUDGET`
+ (5) × the cut's estimated seconds when the deck is on (`renderSeconds`, from the build and take routes); the
+ per-clip budgets stay the floor.
+
+## Proven on a copy of the Huck cut
+
+`~/reports/quartering-huck/polemic-huck` copied (read only) to the lane's scratch dir: `--lint` and `--lint
+--final` 0 errors, 0 warnings; resolve-windows dry: 0 windows would change; `--clip-preview first`: the
+segment from its corpus window (snapped as v7's: sourceFrom 170.928), deck 22 s, feed 20 s, stamps 28 s over
+its 41.4 s window, ~2.5 min in the heavy slot once admitted; its frame at the stamp matches v7's
+(`takes/timeline/out/polemic-huck.mp4` at 86.25 s). The live preview on the copy (a scratch dev server) draws
+the same frame for `first`, and the finale (rail, totals, stats, the clip in the side box) for `heartstrings`.
+The preview's compose is ~0.8 s in node, ~3.5 s through a dev server.
+
+## Notes for the morning
+
+- The Huck project's root has no `out/` (v7 lives in `takes/timeline/out/`): the Build tab's **final** builds the
+ root's `out/` from the corpus windows (no download), about an hour; then Deliver → **Make variants**. Before
+ this lane its job budget was 72 minutes (36 clips × 2 min); v7's chrome alone rendered for 36 minutes (deck
+ 11.8, feed 10.6, stamps 13.4, finale 0.7). Now 5 × ~1515 s ≈ 2 h 6 min.
+- The final preset's first step is the availability check (`check-availability.mjs`, a `yt-dlp --simulate` per
+ source); a source it cannot reach stops the chain before the build. It last answered for Rumble on 2026-10-16.
+- A build run from a checkout without `transcripts/` (a worktree) reads cues from the published archive, where a
+ Rumble slug misses; the app's own builds run from the primary checkout and read the local corpus.
+
+## Files
+
+`umtool/lib/report/liveClock.mjs` (+ test), `clipRender.mjs`, `livePreview.test.mjs`; `onscreen.mjs`
+(`estimate`, `composeFinalePreview`, `renderSeconds`), `driver.mjs` (`RENDER_BUDGET`, `buildTimeoutMs`),
+`takeMaker.mjs` (`takeTimeoutMs`), routes `build` and `takes/make` (pass `seconds`), `serve.mjs` (`finale-preview`), `clipEditor.mjs` (op `onscreen`, the view's
+`onscreen`), `clipEditorTypes.ts`. Routes: `app/api/report/chrome/preview` (estimate, finale, leadIn,
+verdictLabels), `app/api/report/clip-render` (new). UI: `components/projects/review/LiveDeckPreview.tsx` (new),
+`ClipEditor.tsx` (the mount, the player's handle), `OnscreenSection.tsx` (the finale overlay, `DeckPreviewDoc.finale`).
+`umtool/report-to-video/`: `build-video.mjs` (`--clip-preview`, `clipPreviewJoin`, `measureChromeSchedule` durs),
+`chrome-finale.mjs` (the preview hook), `clip-preview.test.mjs`. e2e: `e2e/live-preview.spec.ts`,
+`e2e/fixtures/live-preview-fixture.mjs`, `e2e/fixtures/clip-render.e2e.mjs` (`E2E_UMTOOL_CLIP_RENDER_SCRIPT`).
+Docs: `umtool/docs/knobs.md` ("Walk and preview"), `editor/CHANGELOG.md`.
diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts
@@ -5,6 +5,7 @@ import { PRESETS, buildSteps } from "@/lib/report/driver.mjs";
import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
import { projectRef } from "@/lib/projects";
import { recordBuildSnapshot } from "@/lib/report/snapshots.mjs";
+import { renderSeconds } from "@/lib/report/onscreen.mjs";
import { DEFAULT_VARIANT, VARIANTS, variantPaths } from "umtool-report-to-video/build-video";
import { refuseCaller } from "@/lib/report/caller";
@@ -134,7 +135,9 @@ export async function POST(request: Request) {
if (!options.podcast && manifest.timeline?.some((e: { type?: string; narration?: unknown }) => e?.type === "card" && e.narration)) {
options.narrate = true;
}
- const steps = buildSteps(project, { preset, only, skipFetch, clipCount, options });
+ // A cut that renders its on-screen chrome is budgeted by its length too (driver.mjs buildTimeoutMs).
+ const seconds = renderSeconds(manifest, options.variant ?? null);
+ const steps = buildSteps(project, { preset, only, skipFetch, clipCount, seconds, options });
const view = {
project: project.id,
preset,
diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts
@@ -1,6 +1,7 @@
import {
composeDeckPreview,
composeFeedPreview,
+ composeFinalePreview,
composePostsPreviews,
composeStampPreview,
normalizeClaimsDraft,
@@ -9,11 +10,13 @@ import {
scheduleForPreview,
segmentBoxes,
} from "@/lib/report/onscreen.mjs";
-import { deckPreviewSrc, feedPreviewSrc, postsPreviewSrc, resolveReport, stampPreviewSrc } from "@/lib/report/serve.mjs";
+import {
+ deckPreviewSrc, feedPreviewSrc, finalePreviewSrc, postsPreviewSrc, resolveReport, stampPreviewSrc,
+} from "@/lib/report/serve.mjs";
import {
deckGeometry, deckLayout, deckOn, feedGeometry, postsGeometry, stampGeometry, validateChrome,
} from "umtool-report-to-video/deck";
-import { stampsDrawn, tallyOf } from "umtool-report-to-video/factcheck";
+import { resolveFactcheck, stampsDrawn, tallyOf } from "umtool-report-to-video/factcheck";
export const dynamic = "force-dynamic";
@@ -55,6 +58,13 @@ export const dynamic = "force-dynamic";
// `stamp.src`, loaded at `stamp.geometry` over the footage for the whole
// scrub; the deck's own page draws the tally, and `layout` makes room for it.
//
+// The FINALE (`finale`, a cut whose last clips are `layout: "finale"`) is one
+// more: a full-frame page for its window (`from`–`to`, cut seconds), laid
+// last while the scrubber is inside it.
+//
+// `estimate: true` -- the clip editor's live preview -- draws the manifest's
+// estimate even when a build's schedule exists (scheduleForPreview).
+//
// The client sends a project id, a variant and the drafts. Never a path.
export async function POST(request: Request) {
let body: Record<string, unknown>;
@@ -83,7 +93,11 @@ export async function POST(request: Request) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
- const { variantManifest, schedule } = await scheduleForPreview(r.project, r.manifest, r.variant, draft, postsDraft, { claimsDraft });
+ // `estimate: true` (the clip editor's live preview): the manifest's
+ // estimate even when a build's schedule exists, so a moved window is
+ // placed where it is now.
+ const estimate = body.estimate === true;
+ const { variantManifest, schedule } = await scheduleForPreview(r.project, r.manifest, r.variant, draft, postsDraft, { claimsDraft, estimate });
const render = (variantManifest.render ?? {}) as Record<string, unknown>;
if (!deckOn(render)) {
return Response.json(
@@ -140,6 +154,27 @@ export async function POST(request: Request) {
};
}
+ // The FINALE (a schedule with `finale`): one full-frame composition for its
+ // window, laid last, as the build lays it -- seeked in the cut's seconds.
+ // Not on the bench's strip either.
+ const fin = (schedule as { finale?: { from: number; to: number } }).finale ?? null;
+ let finale: Record<string, unknown> | null = null;
+ if (body.posts !== false && fin) {
+ let error: string | null = null;
+ try {
+ await composeFinalePreview(r.project, r.variant, schedule);
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ }
+ const g = deckGeometry(render);
+ finale = {
+ geometry: { x: 0, y: 0, width: g.W, height: g.H },
+ from: fin.from,
+ to: fin.to,
+ ...(error ? { error } : { src: `${finalePreviewSrc(r.project.id, r.variant)}?v=${stamp}` }),
+ };
+ }
+
return Response.json(
{
// `v` so the iframe reloads a recomposed preview; the files themselves
@@ -163,6 +198,14 @@ export async function POST(request: Request) {
},
...(feed ? { feed } : {}),
...(stampDoc ? { stamp: stampDoc } : {}),
+ ...(finale ? { finale } : {}),
+ // The lead-in breath before a clip's cut (render.leadIn): the play
+ // window's start, which the live preview maps the source through.
+ leadIn: typeof render.leadIn === "number" ? render.leadIn : 0.4,
+ // Each verdict's word as the tally prints it (relabels included), for a readout beside the picture.
+ verdictLabels: Object.fromEntries(
+ Object.entries(resolveFactcheck(render).verdicts as Record<string, { label: string }>).map(([k, v]) => [k, v.label]),
+ ),
},
{ headers: { "cache-control": "no-store" } },
);
diff --git a/umtool/app/api/report/clip-render/route.ts b/umtool/app/api/report/clip-render/route.ts
@@ -0,0 +1,107 @@
+import { stat } from "node:fs/promises";
+import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { clipRenderFile, clipRenderSteps, readClipRender } from "@/lib/report/clipRender.mjs";
+import { rangeResponse } from "@/lib/report/serve.mjs";
+import { DEFAULT_VARIANT, VARIANTS } from "umtool-report-to-video/build-video";
+
+export const dynamic = "force-dynamic";
+
+// RENDER THIS CLIP (the clip editor's live preview, plans/live-preview.md):
+// one clip's segment with its on-screen chrome, pixel-true --
+// build-video.mjs --clip-preview, from what is on disk, as ONE job on the
+// app's runner (lib/jobs.ts: one at a time, a log, Cancel), in the heavy slot.
+//
+// GET ?project=<id>&clip=<id>[&variant=] { render, running }
+// GET ?project=<id>&clip=<id>&file=1[&variant=] the mp4 (ranges)
+// GET ?job=<id>[&since=&sinceEvent=] that job
+// POST { project, clip, variant? } render it
+// ?cancel=<job> stop it
+//
+// Names, never paths: a project of the scan, a clip of its timeline, a
+// variant of the pipeline's list.
+const headers = { "cache-control": "no-store" };
+const isClipRenderJob = (kind: string) => /^clip render /.test(kind);
+
+async function reportProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a clip render is made of a report video's clip" }, { status: 400, headers }) };
+ return { project };
+}
+
+const variantOf = (v: unknown): string | null => {
+ const s = v === null || v === undefined || v === "" ? DEFAULT_VARIANT : String(v);
+ return (VARIANTS as string[]).includes(s) ? s : null;
+};
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const jobId = url.searchParams.get("job");
+ if (jobId) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const r = await reportProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ const variant = variantOf(url.searchParams.get("variant"));
+ if (!variant) return Response.json({ error: `variant must be one of ${VARIANTS.join(", ")}` }, { status: 400, headers });
+ const clip = url.searchParams.get("clip") ?? "";
+ if (url.searchParams.get("file")) {
+ const abs = clipRenderFile(r.project.dir, variant, clip);
+ const st = abs ? await stat(abs).catch(() => null) : null;
+ if (!abs || !st?.isFile()) return new Response(`no render of ${clip}`, { status: 404 });
+ return rangeResponse(request, {
+ abs,
+ size: st.size,
+ headers: {
+ "content-type": "video/mp4",
+ "accept-ranges": "bytes",
+ "cache-control": url.searchParams.get("v") === String(Math.round(st.mtimeMs)) ? "private, max-age=3600, immutable" : "private, no-store",
+ },
+ });
+ }
+ const manifest = await readManifest(r.project.dir);
+ const entry = (manifest ? clipsOf(manifest) : []).find((e: { id: string }) => e.id === clip) ?? null;
+ const running = runningJob();
+ return Response.json(
+ {
+ render: await readClipRender(r.project.dir, variant, clip, entry),
+ running: running && running.project === r.project.id && isClipRenderJob(running.kind) ? jobView(running) : null,
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/clip-render");
+ if (refused) return refused;
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await reportProject(body.project);
+ if ("error" in r) return r.error;
+ const variant = variantOf(body.variant);
+ if (!variant) return Response.json({ error: `variant must be one of ${VARIANTS.join(", ")}` }, { status: 400, headers });
+ const manifest = await readManifest(r.project.dir);
+ if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers });
+ const clip = String(body.clip ?? "");
+ if (!clipsOf(manifest).some((e: { id: string }) => e.id === clip) || !clipRenderFile(r.project.dir, variant, clip)) {
+ return Response.json({ error: `no clip with id ${clip}` }, { status: 400, headers });
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ try {
+ const steps = clipRenderSteps(r.project, clip, { variant: variant === DEFAULT_VARIANT ? null : variant });
+ const job = startJob(`clip render ${r.project.id} ${clip}`, steps, { project: r.project.id });
+ return Response.json({ ok: true, clip, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers });
+ }
+}
diff --git a/umtool/app/api/report/takes/make/route.ts b/umtool/app/api/report/takes/make/route.ts
@@ -2,6 +2,7 @@ import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { projectRef } from "@/lib/projects";
import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
import { loadMontageStyles, takeSteps } from "@/lib/report/takeMaker.mjs";
+import { renderSeconds } from "@/lib/report/onscreen.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
@@ -62,6 +63,7 @@ export async function POST(request: Request) {
styles,
existing: listing.takes,
clipCount: clipsOf(manifest).length,
+ seconds: renderSeconds(manifest),
});
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx
@@ -102,6 +102,8 @@ export type DeckPreviewDoc = {
feed?: FeedPreview;
/** The fact-check stamps, when the cut stamps a claim: one composition for the whole cut, over the footage. */
stamp?: { geometry: Rect; src?: string; error?: string };
+ /** The finale, when the cut has one: a full-frame composition for its window (`from`–`to`, cut seconds), laid last. */
+ finale?: { geometry: Rect; from: number; to: number; src?: string; error?: string };
};
/** An unsaved change to a post, as PUT /api/report/posts takes it. */
export type PostPatch = { attachTo?: string | null; hide?: boolean };
@@ -1837,6 +1839,20 @@ export default function OnscreenSection({
name="fact-check stamps"
/>
)}
+ {preview.finale && t >= preview.finale.from && t <= preview.finale.to && (
+ // The finale's page, laid last -- over the deck's own -- while the scrubber is in its window.
+ <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }}>
+ <FeedOverlay
+ key={`finale:${preview.finale.src ?? "none"}`}
+ feed={preview.finale}
+ frame={preview.geometry}
+ t={t}
+ ready="finale:ready"
+ testid="onscreen-finale-preview"
+ name="finale"
+ />
+ </div>
+ )}
</DeckFrame>
) : (
<div className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)]">
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -15,6 +15,7 @@ import { ROOM, roomShade } from "umtool-report-to-video/room";
import { startTakeJob } from "../NewTakePanel";
import AssistBox from "../report/AssistBox";
import { AudioBox, MarksBox } from "./ClipKnobs";
+import LiveDeckPreview from "./LiveDeckPreview";
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional).
import type { ReplyProposal } from "@/lib/annotations/types";
import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest";
@@ -463,6 +464,7 @@ export default function ClipEditor({
)}
<Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} />
+ <LiveDeckPreview project={project} clip={clip} cut={cut} token={view.token} player={player} write={write} busy={busy} />
{/* ---- the strip --------------------------------------------------- */}
<div className="space-y-1">
@@ -773,7 +775,14 @@ export default function ClipEditor({
// clip's extent, else its cut; loops the cut.
// ---------------------------------------------------------------------------
-type PlayerHandle = { toggle: () => void; seek: (t: number) => void; listen: (t: number) => void };
+type PlayerHandle = {
+ toggle: () => void;
+ seek: (t: number) => void;
+ listen: (t: number) => void;
+ /** The media element and the source second it is at: the live preview draws and clocks from them. */
+ media: () => HTMLMediaElement | null;
+ sourceTime: () => number | null;
+};
/** The short's framing on the player: the clip's crop (null = the centre) and its writer. */
type Frame = { crop: number[] | null; onChange: (crop: number[] | null, aspect?: number) => void; busy: boolean };
type Target = { channel: string; video: string; from: number; to: number; project: string; clip: string };
@@ -831,6 +840,8 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
const sourceT = (ft: number) => (found ? ft - found.play.offset + found.from : 0);
useImperativeHandle(ref, () => ({
+ media: () => media.current,
+ sourceTime: () => (found && media.current ? sourceT(media.current.currentTime) : null),
toggle: () => {
const m = media.current;
if (!m) return;
diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx
@@ -0,0 +1,532 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { edgeClock } from "@/lib/report/clipEditorModel.mjs";
+import type { EditorClip } from "@/lib/report/clipEditorTypes";
+import { footageAt } from "@/lib/report/footage-move.mjs";
+import { clipStamps, clockText, cutTimeAt, finaleUp, liveClock, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
+import { tallyVerdicts } from "umtool-report-to-video/factcheck";
+import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection";
+
+// ---------------------------------------------------------------------------
+// THE LIVE PREVIEW (plans/live-preview.md): the clip editor's playing source
+// with the cut's on-screen chrome composited over it, in this browser, in step
+// with the playhead -- so a clip is walked in its final look without waiting
+// on a build.
+//
+// THE COMPOSITION IS THE BUILD'S OWN PAGES, as the On-screen section's preview
+// is (OnscreenSection.tsx DeckFrame, FeedOverlay, PostsOverlay): the deck
+// (date title, subtitle, the rail with this clip's pip and the markers, the
+// tally, the QR), the posts feed or popups, the fact-check stamps and the
+// finale, each composed by compose-chrome from the manifest's ESTIMATED
+// schedule (POST /api/report/chrome/preview with `estimate: true`) and seeked
+// in the cut's seconds. The cut second is the source playhead mapped through
+// the clip's play window (lib/report/liveClock.mjs) -- the rule the estimate
+// and a stamp's `claim.at` both use, so the stamp lands on its source second
+// here as in the render.
+//
+// The footage is the editor's own <video>, drawn into a canvas at the
+// footage's box every frame (no second decode, never out of step), fitted and
+// padded in the palette's ground as the build frames it, and carried along
+// the schedule's footage moves (the finale's grow, posts making room).
+//
+// Instant on an edit: a window, a claim, a mark or the words saved through the
+// editor change the manifest's token, and the pages are composed again (a
+// second, no build); an unsaved nudge moves the clock at once, and typed
+// words are patched into the deck page as they are typed.
+//
+// "Render this clip" is the pixel-true check: build-video --clip-preview as a
+// job (POST /api/report/clip-render), its file shown here when done.
+// ---------------------------------------------------------------------------
+
+/** What the editor's player gives this: its media element and the source second it is at. */
+export type LivePlayer = {
+ media: () => HTMLMediaElement | null;
+ sourceTime: () => number | null;
+ seek: (t: number) => void;
+};
+
+type Write = (body: Record<string, unknown>, done?: string) => Promise<unknown>;
+type LiveDoc = DeckPreviewDoc & {
+ leadIn?: number;
+ verdictLabels?: Record<string, string>;
+ schedule: DeckPreviewDoc["schedule"] & { finale?: { from: number; to: number } };
+};
+type JobLite = { id: string; state: string; error: string | null; log?: string[]; events?: Record<string, unknown>[] };
+type ClipRender = { mtimeMs: number; size: number; stale: boolean; record: { builtAt?: string; estimated?: boolean } | null };
+
+const STORE = "umtool.livePreview";
+const COMPOSE_DEBOUNCE_MS = 250;
+
+/** What the preview is not, said once (the "approximate" list). */
+const APPROXIMATE = [
+ "the build snaps each edge of the cut to a nearby silence, so the deck's handover can land up to the snap window off; the stamp lands on its source second either way",
+ "the joins (crossfades) to the neighbouring clips are not drawn: the clip plays alone",
+ "the sound is the source's: room's muted edges and the clip's Audio knobs are applied by the build",
+ "the pages are drawn by this browser, not the render's; Render this clip is the pixel-true check",
+];
+
+export default function LiveDeckPreview({
+ project,
+ clip,
+ cut,
+ token,
+ player,
+ write,
+ busy,
+}: {
+ project: string;
+ clip: EditorClip;
+ cut: { cutStart: number; cutEnd: number };
+ token: string | null;
+ player: React.RefObject<LivePlayer | null>;
+ write: Write;
+ busy: boolean;
+}) {
+ const [on, setOn] = useState(true);
+ useEffect(() => {
+ try {
+ if (window.localStorage.getItem(STORE) === "off") setOn(false);
+ } catch {
+ // No storage: on, the default.
+ }
+ }, []);
+ const toggle = (next: boolean) => {
+ setOn(next);
+ try {
+ window.localStorage.setItem(STORE, next ? "on" : "off");
+ } catch {
+ // A preference, not state.
+ }
+ };
+
+ // ---- the composition -------------------------------------------------------
+ const [doc, setDoc] = useState<LiveDoc | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // The cut has no deck (render.chrome off): nothing to composite, nothing to render with it.
+ const [noDeck, setNoDeck] = useState(false);
+ const [composing, setComposing] = useState(false);
+ const seq = useRef(0);
+ const compose = useCallback(async () => {
+ const mine = ++seq.current;
+ setComposing(true);
+ try {
+ const r = await fetch("/api/report/chrome/preview", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, estimate: true }),
+ });
+ const j = (await r.json().catch(() => ({}))) as LiveDoc & { error?: string; deckOn?: boolean };
+ if (mine !== seq.current) return;
+ if (!r.ok) {
+ setNoDeck(j.deckOn === false);
+ setError(j.deckOn === false ? null : String(j.error ?? `HTTP ${r.status}`));
+ setDoc(null);
+ } else {
+ setNoDeck(false);
+ setError(null);
+ setDoc(j);
+ }
+ } catch (e) {
+ if (mine === seq.current) setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ if (mine === seq.current) setComposing(false);
+ }
+ }, [project]);
+ // Composed again whenever the manifest changes (its token): a saved window,
+ // claim, mark or words is in the next picture a second later.
+ useEffect(() => {
+ if (!on) return;
+ const t = setTimeout(() => void compose(), COMPOSE_DEBOUNCE_MS);
+ return () => clearTimeout(t);
+ }, [on, compose, token]);
+
+ // ---- the clock ---------------------------------------------------------------
+ const schedule = doc?.schedule ?? null;
+ const clock = useMemo(
+ () => (schedule ? liveClock(schedule, { id: clip.id, start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd }, { leadIn: doc?.leadIn ?? 0.4 }) : null),
+ [schedule, clip.id, clip.start, clip.end, cut.cutStart, cut.cutEnd, doc?.leadIn],
+ );
+ const clockRef = useRef(clock);
+ clockRef.current = clock;
+ const [now, setNow] = useState<{ t: number; where: "before" | "inside" | "after"; src: number | null }>({ t: 0, where: "before", src: null });
+ const canvas = useRef<HTMLCanvasElement | null>(null);
+ const bg = doc?.background ?? "#000";
+ const bgRef = useRef(bg);
+ bgRef.current = bg;
+ const lastDraw = useRef<{ el: HTMLCanvasElement | null; media: HTMLMediaElement | null; t: number; bg: string; size: string }>({ el: null, media: null, t: NaN, bg: "", size: "" });
+
+ // Every animation frame while on: the playhead's cut second, and the
+ // editor's picture drawn into the footage box when it moved.
+ useEffect(() => {
+ if (!on) return;
+ let raf = 0;
+ let last = { t: NaN, where: "", src: NaN as number | null };
+ const tick = () => {
+ raf = requestAnimationFrame(tick);
+ const h = player.current;
+ const src = h?.sourceTime() ?? null;
+ const c = clockRef.current;
+ if (c) {
+ const at = src === null ? { t: c.start, where: "before" as const } : cutTimeAt(c, src);
+ if (Math.abs(at.t - last.t) > 1 / 120 || at.where !== last.where || (src === null) !== (last.src === null)) {
+ last = { t: at.t, where: at.where, src };
+ setNow({ t: at.t, where: at.where, src });
+ }
+ }
+ const el = canvas.current;
+ const m = h?.media() ?? null;
+ if (!el) return;
+ const ld = lastDraw.current;
+ const video = m instanceof HTMLVideoElement && m.readyState >= 2 && m.videoWidth > 0 ? m : null;
+ if (ld.el === el && ld.media === video && ld.t === (video?.currentTime ?? -1) && ld.bg === bgRef.current && ld.size === `${el.width}x${el.height}`) return;
+ lastDraw.current = { el, media: video, t: video?.currentTime ?? -1, bg: bgRef.current, size: `${el.width}x${el.height}` };
+ const ctx = el.getContext("2d");
+ if (!ctx) return;
+ ctx.fillStyle = bgRef.current;
+ ctx.fillRect(0, 0, el.width, el.height);
+ if (!video) return;
+ // Fitted into the box, keeping its aspect, padded in the ground (deckFraming's `fit`).
+ const k = Math.min(el.width / video.videoWidth, el.height / video.videoHeight);
+ const w = video.videoWidth * k;
+ const hh = video.videoHeight * k;
+ ctx.drawImage(video, (el.width - w) / 2, (el.height - hh) / 2, w, hh);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [on, player]);
+
+ const t = now.t;
+ const g = doc?.geometry ?? null;
+ const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
+ const move = schedule ? footageAt(schedule, t) : null;
+ const rect: Rect | null = move?.rect ?? box;
+ const order = useMemo(() => (schedule?.factcheck ? tallyVerdicts(schedule.factcheck.stamps) : []), [schedule]);
+ const tally = schedule?.factcheck ? tallyAt(schedule, t, order) : [];
+ const stamp = schedule ? stampAt(schedule, t) : null;
+ const mine = schedule && clock ? clipStamps(schedule, clock) : [];
+ const finaleNow = !!schedule && finaleUp(schedule, t);
+ const seg = schedule?.segments.find((s) => s.id === clip.id) ?? null;
+ const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, t) : null;
+
+ // ---- the words -----------------------------------------------------------------
+ // null = untouched (the field shows what is written); a string = typed, unsaved.
+ const [titleDraft, setTitleDraft] = useState<string | null>(null);
+ const [subDraft, setSubDraft] = useState<string | null>(null);
+ useEffect(() => {
+ setTitleDraft(null);
+ setSubDraft(null);
+ }, [clip.id, clip.onscreen?.title, clip.onscreen?.subtitle]);
+ const savedTitle = clip.onscreen?.title ?? "";
+ const savedSub = clip.onscreen?.subtitle ?? "";
+ const texts = useMemo<DeckTexts>(() => {
+ if (!seg || (titleDraft === null && subDraft === null)) return {};
+ return {
+ [clip.id]: {
+ title: titleDraft !== null ? titleDraft.trim() : seg.title,
+ // An emptied subtitle is the automatic one: the page keeps what it has until the save recomposes it.
+ subtitle: subDraft !== null && subDraft.trim() ? subDraft.trim() : seg.subtitle,
+ },
+ };
+ }, [seg, clip.id, titleDraft, subDraft]);
+ const saveWords = () => {
+ if (titleDraft === null && subDraft === null) return;
+ const title = (titleDraft ?? savedTitle).trim();
+ const subtitle = (subDraft ?? savedSub).trim();
+ if (title === savedTitle.trim() && subtitle === savedSub.trim()) {
+ setTitleDraft(null);
+ setSubDraft(null);
+ return;
+ }
+ const onscreen = title || subtitle ? { ...(title ? { title } : {}), ...(subtitle ? { subtitle } : {}) } : null;
+ void write({ op: "onscreen", clip: clip.id, onscreen }, onscreen ? "Saved the on-screen words" : "The on-screen words are automatic again");
+ };
+ const wordKeys = (reset: () => void) => (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Enter") (e.target as HTMLInputElement).blur();
+ if (e.key === "Escape") {
+ reset();
+ (e.target as HTMLInputElement).blur();
+ }
+ };
+
+ const pct = (n: number, of: number) => `${(n / of) * 100}%`;
+ const state = !on ? "off" : noDeck ? "no-deck" : error ? "error" : doc ? (composing ? "composing" : "ready") : "composing";
+ if (noDeck) {
+ return (
+ <p data-live-preview={clip.id} data-live-state="no-deck" className="micro m-0">
+ no on-screen deck in this cut (render.chrome): the clip plays as it is
+ </p>
+ );
+ }
+
+ return (
+ <section
+ data-live-preview={clip.id}
+ data-live-state={state}
+ data-live-t={on && doc ? String(Math.round(t * 1000) / 1000) : ""}
+ data-live-where={on && doc ? now.where : ""}
+ className="w-full max-w-[720px] space-y-1.5"
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <label className="inline-flex items-center gap-1.5 text-text">
+ <input type="checkbox" data-live-toggle="" checked={on} onChange={(e) => toggle(e.target.checked)} />
+ Live preview
+ </label>
+ {on && doc && clock && (
+ <span className="num font-mono text-[11.5px] text-muted" data-live-readout="">
+ cut {clockText(t)} · clip {clock.index + 1} of {clock.of}
+ {seg?.title ? ` · ${seg.title}` : ""}
+ </span>
+ )}
+ {on && composing && <span className="micro" data-live-composing="">composing…</span>}
+ {on && doc && (
+ <button type="button" className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")} onClick={() => void compose()} title="compose the pages again from the manifest">
+ Refresh
+ </button>
+ )}
+ </div>
+
+ {on && error && (
+ <p role="alert" data-live-error="" className="m-0 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+
+ {on && doc && g && box && (
+ <>
+ {!clock && (
+ <p data-live-not-in-cut="" className="m-0 text-[12px] text-muted">
+ {clip.id} is not in this cut’s timeline: nothing to preview it in.
+ </p>
+ )}
+ {clock && (
+ <DeckFrame preview={doc} t={t} texts={texts} testid="live-preview">
+ <div className="absolute inset-0" style={{ background: bg }} />
+ <canvas
+ ref={canvas}
+ data-live-footage=""
+ data-live-move={move ? move.segment : ""}
+ width={box.width}
+ height={box.height}
+ className="absolute"
+ style={rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined}
+ />
+ {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={t} testid="live-feed" />}
+ {postsWin && doc.posts && (
+ <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={t} />
+ )}
+ {doc.stamp && (
+ <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={t} ready="stamp:ready" testid="live-stamp" name="fact-check stamps" />
+ )}
+ {doc.finale && finaleNow && (
+ // Laid last, over the deck's own page, as the build lays it.
+ <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-live-finale="">
+ <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={t} ready="finale:ready" testid="live-finale" name="finale" />
+ </div>
+ )}
+ {now.where !== "inside" && (
+ <div
+ data-live-outside={now.where}
+ className="pointer-events-none absolute inset-x-0 top-0 flex justify-center p-1"
+ style={{ zIndex: 3 }}
+ >
+ <span className="rounded bg-black/70 px-1.5 py-0.5 text-[11px] text-white">
+ {now.src === null ? "press play: the cut starts at " : now.where === "before" ? "before the cut — it starts at " : "past the cut — it ended at "}
+ {edgeClock(now.where === "after" ? clock.sourceTo : clock.sourceFrom)}
+ </span>
+ </div>
+ )}
+ </DeckFrame>
+ )}
+
+ {clock && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-text-2" data-live-hud="">
+ {tally.length > 0 && (
+ <span data-live-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")}>
+ tally {tally.map((r) => `${labelOf(doc, r.verdict)} ${r.count}`).join(" · ")}
+ </span>
+ )}
+ <span data-live-stamp={stamp ? `${stamp.claim}:${stamp.phase}` : ""}>
+ {stamp ? `stamp ${stamp.claim} (${stamp.phase})` : "no stamp on screen"}
+ </span>
+ {mine.map((m) => (
+ <button
+ key={m.claim}
+ type="button"
+ data-live-goto-stamp={m.sourceLanded}
+ data-live-goto-mark={m.claim}
+ className="ink-link"
+ title="put the playhead a second before this mark's stamp lands"
+ onClick={() => player.current?.seek(Math.max(clock.sourceFrom, m.sourceLanded - 1))}
+ >
+ {m.drawn ? "stamps" : "counts"} {m.claim} at {edgeClock(m.sourceLanded)}
+ </button>
+ ))}
+ {finaleNow && <span data-live-finale-up="">finale</span>}
+ {schedule?.estimated && (
+ <details className="w-full text-[11px] text-muted" data-live-approximate="">
+ <summary className="cursor-pointer">preview: approximate — what the build does that this does not</summary>
+ <ul className="m-0 mt-1 list-disc space-y-0.5 pl-5">
+ {APPROXIMATE.map((a) => (
+ <li key={a}>{a}</li>
+ ))}
+ {doc.finale?.error && <li>the finale did not compose: {doc.finale.error}</li>}
+ </ul>
+ </details>
+ )}
+ </div>
+ )}
+
+ {clock && seg && (
+ <div className="grid gap-1.5 sm:grid-cols-2" data-live-words="">
+ <label className="flex items-center gap-1.5 text-[12px] text-text-2">
+ <span className="micro shrink-0">Title</span>
+ <input
+ data-live-title=""
+ value={titleDraft ?? savedTitle}
+ placeholder="none"
+ maxLength={120}
+ disabled={busy}
+ onChange={(e) => setTitleDraft(e.target.value)}
+ onBlur={saveWords}
+ onKeyDown={wordKeys(() => setTitleDraft(null))}
+ className="min-w-0 flex-1 rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[12px] text-text outline-none focus:border-signal"
+ />
+ </label>
+ <label className="flex items-center gap-1.5 text-[12px] text-text-2">
+ <span className="micro shrink-0">Subtitle</span>
+ <input
+ data-live-subtitle=""
+ value={subDraft ?? savedSub}
+ placeholder={savedSub ? "automatic" : seg.subtitle || "automatic"}
+ maxLength={200}
+ disabled={busy}
+ onChange={(e) => setSubDraft(e.target.value)}
+ onBlur={saveWords}
+ onKeyDown={wordKeys(() => setSubDraft(null))}
+ className="min-w-0 flex-1 rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[12px] text-text outline-none focus:border-signal"
+ />
+ </label>
+ </div>
+ )}
+ </>
+ )}
+
+ <RenderThisClip project={project} clip={clip} />
+ </section>
+ );
+}
+
+/** A verdict's word as the tally prints it (the preview's `verdictLabels`), else its id. */
+function labelOf(doc: LiveDoc, verdict: string): string {
+ return doc.verdictLabels?.[verdict] ?? verdict;
+}
+
+// ---------------------------------------------------------------------------
+// Render this clip: build-video --clip-preview as a job; its file played here.
+// ---------------------------------------------------------------------------
+
+function RenderThisClip({ project, clip }: { project: string; clip: EditorClip }) {
+ const [render, setRender] = useState<ClipRender | null>(null);
+ const [job, setJob] = useState<JobLite | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ const q = useMemo(() => new URLSearchParams({ project, clip: clip.id }).toString(), [project, clip.id]);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/clip-render?${q}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { render: ClipRender | null; running: JobLite | null };
+ setRender(j.render);
+ if (j.running) setJob(j.running);
+ }, [q]);
+ useEffect(() => {
+ setRender(null);
+ setJob(null);
+ setErr(null);
+ void load();
+ }, [load]);
+ // The clip's window moving makes the file on disk stale: asked again on each edit.
+ useEffect(() => {
+ void load();
+ }, [load, clip.start, clip.end, clip.cutStart, clip.cutEnd]);
+
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/clip-render?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as JobLite;
+ setJob({ id: j.id, state: j.state, error: j.error, log: j.log, events: j.events });
+ if (j.state !== "running") void load();
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, load]);
+
+ const start = async () => {
+ setErr(null);
+ const r = await fetch("/api/report/clip-render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip: clip.id }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: JobLite; error?: string };
+ if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
+ else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
+ };
+ const cancel = async () => {
+ if (job) await fetch(`/api/report/clip-render?cancel=${job.id}`, { method: "POST" }).catch(() => null);
+ };
+ const running = job?.state === "running";
+ // Waiting on the heavy slot is the log's (queue-lock); the build's own steps are its events.
+ const lastLog = job?.log?.length ? job.log[job.log.length - 1] : null;
+ const ev = job?.events?.length ? job.events[job.events.length - 1] : null;
+ const lastLine = lastLog && /queue-lock|heavy/.test(lastLog)
+ ? lastLog.replace(/^queue-lock: /, "").slice(0, 160)
+ : ev
+ ? [ev.ev, ev.phase, ev.region, ev.id].filter((x) => typeof x === "string").join(" ")
+ : null;
+
+ return (
+ <div data-clip-render={clip.id} data-clip-render-made={render ? "" : undefined} className="space-y-1.5 rounded-[3px] border border-seam bg-panel p-2 text-[12px] text-text-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" data-clip-render-start="" disabled={running} onClick={() => void start()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {running ? "Rendering…" : render ? "Render this clip again" : "Render this clip"}
+ </button>
+ {running && (
+ <button type="button" data-clip-render-cancel="" onClick={() => void cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Stop
+ </button>
+ )}
+ <span className="text-muted">
+ as the build renders it · heavy slot, a minute or two
+ </span>
+ </div>
+ {job && (
+ <p data-clip-render-job={job.state} className="m-0 text-[11.5px]">
+ {running ? `Rendering${lastLine ? ` — ${lastLine}` : ""}` : job.state === "done" ? "Rendered" : `Failed${job.error ? `: ${job.error}` : ""}`}
+ </p>
+ )}
+ {err && (
+ <p role="alert" className="m-0 text-[12px] text-reject-text">
+ {err}
+ </p>
+ )}
+ {render && (
+ <div className="space-y-1">
+ <video
+ key={render.mtimeMs}
+ data-clip-render-video=""
+ src={`/api/report/clip-render?${q}&file=1&v=${render.mtimeMs}`}
+ controls
+ playsInline
+ preload="metadata"
+ className="aspect-video w-full rounded-[3px] bg-black"
+ />
+ <p className="m-0 text-[11px] text-muted" data-clip-render-stale={render.stale ? "" : undefined}>
+ rendered {new Date(render.mtimeMs).toLocaleString()}
+ {render.record?.estimated ? " · some segments estimated (not built yet): the cut's clock, not this clip's, is approximate" : ""}
+ {render.stale ? " · the clip's window moved since — render it again" : ""}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -113,6 +113,33 @@ would land inside the finale counts as the finale opens and is not drawn. Withou
bytes it was, `deck.finale` set or not. The render: `<out>/<variant>/chrome/finale-frames/` (a full-frame window
over the run, laid last); a still: `compose-chrome.mjs <manifest> --region finale --still <cut s> --png <file>`.
+## Walk and preview (the clip editor)
+
+The clip editor (`/projects/<p>/clips`, a clip with **Edit**) is where a deck cut is walked: under the player,
+**Live preview** draws the cut's on-screen chrome over the playing clip, in step with the playhead — the deck's
+title and subtitle, the rail with this clip's pip and the markers, the tally as of that moment (it steps when a
+stamp lands), the stamp, the posts feed or popups, the QR, and the finale's page on a finale clip. No build: the
+pages are the build's own (compose-chrome, as the On-screen preview's), composed from the manifest's estimate and
+seeked in the cut's second the playhead plays at. The clip's footage is the editor's own picture, fitted into the
+footage box and carried along the footage's moves.
+
+| | In umtool | Route |
+|---|---|---|
+| the picture, the cut clock (`cut 1:23.4 · clip 3 of 36`), the tally and the stamp on screen | clip editor, **Live preview** (on by default; the checkbox turns it off, remembered in this browser) | `POST /api/report/chrome/preview {project, estimate: true}` |
+| put the playhead a second before this clip's stamp lands | the HUD's **this clip stamps k1 at …** | — |
+| the deck's title / subtitle for this clip: patched into the page as typed, saved on Enter or leaving the field; empty is automatic | Live preview, **Title**, **Subtitle** | `POST /api/report/clip-editor {op: "onscreen", clip, onscreen: {title?, subtitle?} \| null}` |
+| the clip with its chrome, rendered as the build renders it (its segment built from what is on disk, the deck/feed/posts/stamps/finale over its window, in the heavy slot): a minute or two | **Render this clip** (again), Stop; the file plays inline, and says when the clip's window has moved since | `POST /api/report/clip-render {project, clip}`; `GET …?project&clip[&file=1]`; CLI: `node umtool/report-to-video/build-video.mjs <manifest> --skip-fetch --clip-preview <id>` → `out/<variant>/clip-preview/<id>.mp4` |
+
+Every save in the editor (a window, a claim knob, the words) is in the next picture about a second later; an
+unsaved nudge of an edge moves the clock at once. **preview: approximate** under the picture lists what the
+build does that the preview does not: it snaps each edge to a silence (the deck's handover can land up to
+`render.snapWindow` off; a stamp lands on its source second either way), it joins the clips with their crossfades
+(here the clip plays alone), it applies room's muted edges and the clip's Audio knobs, and it draws in the render's
+browser. **Render this clip** is the pixel-true check of all of that but the joins.
+
+Then the cut: the Build tab's **final** preset (a full build, about an hour for a 36-clip cut), and Deliver's
+**Make variants**.
+
## Make variants, and the sync report
| | In umtool | From a terminal | Route |
diff --git a/umtool/e2e/fixtures/clip-render.e2e.mjs b/umtool/e2e/fixtures/clip-render.e2e.mjs
@@ -0,0 +1,44 @@
+#!/usr/bin/env node
+// Render this clip, STUBBED (E2E_UMTOOL_CLIP_RENDER_SCRIPT, set in
+// playwright.config.ts): the command line of build-video.mjs --clip-preview
+// (`node build-video.mjs <manifest> --out <dir> [--variant v] --skip-fetch
+// --clip-preview <id> --progress ndjson`) and its outputs --
+// `<out>/<variant>/clip-preview/<id>.mp4` and the record beside it -- with no
+// render: the "render" is a copy of the project's cached window. The suite
+// tests the button, the job and the file shown, not a render (the real run is
+// report-to-video's, proven on a copy of a real cut: plans/live-preview.md).
+import { copyFile, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+const argv = process.argv.slice(2);
+const flag = (n) => {
+ const i = argv.indexOf(n);
+ return i < 0 ? null : argv[i + 1];
+};
+const manifestPath = argv[0];
+const id = flag("--clip-preview");
+const variant = flag("--variant") ?? "sourced";
+const out = flag("--out");
+if (!manifestPath || !id || !out || !argv.includes("--skip-fetch")) {
+ console.error("stub: expected <manifest> --out <dir> --skip-fetch --clip-preview <id>");
+ process.exit(2);
+}
+const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+const entry = (manifest.timeline ?? []).find((e) => e.id === id);
+if (!entry) {
+ console.log(JSON.stringify({ ev: "error", message: `no entry ${id}` }));
+ process.exit(1);
+}
+const emit = (ev, f = {}) => console.log(JSON.stringify({ ev, ...f }));
+emit("clip", { id, i: 0, n: 1 });
+const raw = path.join(out, "clips-raw");
+const name = (await readdir(raw)).find((f) => f.endsWith(".mp4"));
+const dir = path.join(out, variant, "clip-preview");
+await mkdir(dir, { recursive: true });
+emit("chrome", { phase: "render", region: "deck" });
+await copyFile(path.join(raw, name), path.join(dir, `${id}.mp4`));
+await writeFile(path.join(dir, `${id}.json`), JSON.stringify({
+ version: 1, id, builtAt: new Date().toISOString(), start: 0, duration: entry.end - entry.start, estimated: true,
+ window: { start: entry.start, end: entry.end, cutStart: entry.cutStart ?? null, cutEnd: entry.cutEnd ?? null },
+}, null, 2) + "\n");
+emit("done", { out: path.join(dir, `${id}.mp4`), failures: [] });
diff --git a/umtool/e2e/fixtures/live-preview-fixture.mjs b/umtool/e2e/fixtures/live-preview-fixture.mjs
@@ -0,0 +1,47 @@
+// What live-preview.spec.ts walks (plans/live-preview.md): a deck cut of three
+// clips on vid1 (the fixture corpus's synthetic source, its 0-9 s window
+// cached in out/clips-raw) in the Huck video's shape -- a date as each clip's
+// deck title, verdict-coloured pips, a tally relabelled Episodes / Grift, a
+// claim stamped at a source second, the last clip the finale -- and never
+// built: the live preview draws the manifest's estimate.
+//
+// c01 1.0-3.5 "24 Oct 2020"
+// c02 4.0-6.5 marks k1 Grift at 5.0, k1b Episodes at 6.0 "2 Dec 2024"
+// c03 6.5-8.8 claim k2 Episodes, finale "27 Feb 2025"
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+/**
+ * @param {{ reports: string, deckManifest: Function, cachedWindow: string }} o
+ */
+export function makeLivePreviewFixture({ reports, deckManifest, cachedWindow }) {
+ const dir = path.join(reports, "live-preview-fixture");
+ mkdirSync(dir, { recursive: true });
+ const m = deckManifest("live-preview-fixture", "The Live Preview Fixture", [
+ { type: "clip", id: "c01", video: "vid1", start: 1.0, end: 3.5, cite: 1, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } },
+ {
+ type: "clip", id: "c02", video: "vid1", start: 4.0, end: 6.5, cite: 4, lock: true, quote: "And this one runs on",
+ onscreen: { title: "2 Dec 2024" },
+ claims: [{ id: "k1", verdict: "CONTRADICTED", at: 5.0, hold: 0.8 }, { id: "k1b", verdict: "CORROBORATED", at: 6.0 }],
+ },
+ {
+ type: "clip", id: "c03", video: "vid1", start: 6.5, end: 8.8, cite: 6, lock: true, quote: "of that it finishes here.",
+ onscreen: { title: "27 Feb 2025" }, claim: { id: "k2", verdict: "CORROBORATED" }, layout: "finale",
+ },
+ ]);
+ m.render.fetchPad = 0;
+ m.render.chrome = {
+ ...m.render.chrome,
+ deck: { pip: { color: "verdict" }, finale: { statsTitle: "Seizures he reported", stats: [{ label: "2025", value: "5+" }] } },
+ factcheck: {
+ verdicts: { CONTRADICTED: { label: "Grift", color: "#e3b23c" }, CORROBORATED: { label: "Episodes", color: "#6fa8dc", stampLabel: "Seizure" } },
+ stamp: { seconds: 1.5 },
+ },
+ };
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ return { dir };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -40,6 +40,7 @@ import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs";
import { makeVideoAssistFixture } from "./video-assist-fixture.mjs";
import { makeKnobsFixture } from "./knobs-fixture.mjs";
import { makeMarksFixture } from "./marks-fixture.mjs";
+import { makeLivePreviewFixture } from "./live-preview-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1828,6 +1829,8 @@ makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out
makeKnobsFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// Marks (plans/clip-marks.md): the clip editor's Marks box -- add at the playhead, verdict, Shift+S/M, remove (marks.spec.ts).
makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// The clip editor's live preview and Render this clip (plans/live-preview.md, live-preview.spec.ts).
+makeLivePreviewFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
diff --git a/umtool/e2e/live-preview.spec.ts b/umtool/e2e/live-preview.spec.ts
@@ -0,0 +1,148 @@
+import { test, expect, type Frame, type Page } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The clip editor's live preview (plans/live-preview.md): the cut's on-screen
+// chrome composited over the playing clip, in step with the playhead -- the
+// deck's date title, the tally as of the playhead (stepping when the stamp
+// lands), the stamp, the finale on the last clip -- the deck's words edited
+// and patched in as typed, then saved; and Render this clip as a job (the
+// renderer stubbed: e2e/fixtures/clip-render.e2e.mjs), its file shown inline.
+// Fixture: e2e/fixtures/live-preview-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/live-preview-fixture";
+const DIR = path.join(FIXTURE, "reports", "live-preview-fixture");
+
+type Entry = { id: string; onscreen?: { title?: string; subtitle?: string } };
+const readManifest = (): { render: Record<string, unknown>; timeline: Entry[] } =>
+ JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8"));
+const entry = (id: string) => readManifest().timeline.find((e) => e.id === id) ?? null;
+
+/** Move the editor's player by `d` seconds (file seconds are source seconds, shifted), paused. */
+async function nudgePlayer(page: Page, d: number) {
+ await page.locator("[data-editor-player] video[data-player]").evaluate(async (v: HTMLVideoElement, by: number) => {
+ v.pause();
+ const want = v.currentTime + by;
+ await new Promise<void>((resolve) => {
+ v.addEventListener("seeked", () => resolve(), { once: true });
+ v.currentTime = want;
+ });
+ }, d);
+}
+
+/** The editor's player has loaded `clip`'s media (it loads each clip's own, then seeks to its cut). */
+async function playerOn(page: Page, clip: string) {
+ await expect
+ .poll(() => page.locator("[data-editor-player] video[data-player]").evaluate((v: HTMLVideoElement) => `${v.currentSrc.includes(`clip=`) ? new URL(v.currentSrc).searchParams.get("clip") : "?"}:${v.readyState >= 2}`), { timeout: 20_000 })
+ .toBe(`${clip}:true`);
+}
+
+/** The opacity a composition's element has right now (gsap's autoAlpha), inside its frame. */
+const opacityIn = (frame: Frame, selector: string) =>
+ frame.locator(selector).evaluate((el) => Number(getComputedStyle(el).opacity) * (getComputedStyle(el).visibility === "hidden" ? 0 : 1));
+
+const frameOf = (page: Page, part: RegExp) => {
+ const f = page.frames().find((x) => part.test(x.url()));
+ if (!f) throw new Error(`no frame ${part}`);
+ return f;
+};
+
+test.beforeEach(() => {
+ test.setTimeout(150_000);
+ test.skip(
+ !readManifest().render.fontRegular,
+ "the deck refuses to draw without render.fontRegular/fontBold, and make-fixture.mjs found no font on this machine",
+ );
+});
+
+test("the live preview: the deck over the clip, the tally and the stamp at the playhead, the finale, words, Render this clip", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.clipEditorHref(PROJECT, { clip: "c02", mode: "edit" }));
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "c02");
+ await expect(page.locator("[data-editor-player]")).not.toHaveAttribute("data-editor-player", "looking", { timeout: 15_000 });
+
+ const live = page.locator('[data-live-preview="c02"]');
+ await expect(live).toHaveAttribute("data-live-state", "ready", { timeout: 60_000 });
+ await expect(page.getByTestId("live-preview")).toHaveAttribute("data-deck-ready", "1", { timeout: 60_000 });
+ // Never built: the estimate, and the preview says what it does not do.
+ await expect(page.locator("[data-live-approximate]")).toBeVisible();
+ const deck = page.frameLocator('[data-testid="live-preview-iframe"]');
+ await expect(deck.locator('[data-seg="c02"] .deck-title')).toHaveText("2 Dec 2024");
+ await expect(page.locator("[data-live-readout]")).toContainText("clip 2 of 3");
+
+ // The clip's two marks, each its own stamp and tally step. The first's button puts the playhead a second
+ // before it lands (source 4.0, the clip's first second).
+ await playerOn(page, "c02");
+ await expect(page.locator("[data-live-goto-mark]")).toHaveCount(2);
+ await expect(page.locator('[data-live-goto-mark="k1b"]')).toHaveAttribute("data-live-goto-stamp", "6");
+ const go = page.locator('[data-live-goto-mark="k1"]');
+ await expect(go).toHaveAttribute("data-live-goto-stamp", "5");
+ await go.click();
+ await expect(live).toHaveAttribute("data-live-where", "inside");
+ const t0 = Number(await live.getAttribute("data-live-t"));
+ await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:0,CONTRADICTED:0");
+ await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "");
+
+ // 1.4 s on (source 5.4): the stamp has landed on its source second, the tally has stepped.
+ await nudgePlayer(page, 1.4);
+ await expect.poll(async () => Number(await live.getAttribute("data-live-t"))).toBeCloseTo(t0 + 1.4, 1);
+ await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "k1:on");
+ await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:0,CONTRADICTED:1");
+ // And the pages say the same: the stamp's page shows k1, the deck's tally shows Grift 1.
+ await expect(page.getByTestId("live-stamp")).toHaveAttribute("data-feed-ready", "1", { timeout: 15_000 });
+ await expect.poll(() => opacityIn(frameOf(page, /stamp-preview/), '.stamp[data-claim="k1"]')).toBeGreaterThan(0.9);
+ await expect.poll(() => opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CONTRADICTED.n1"]')).toBeGreaterThan(0.9);
+ expect(await opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CONTRADICTED.n0"]')).toBeLessThan(0.1);
+
+ // 0.8 s more (source 6.2): the clip's second mark, its own stamp and step.
+ await nudgePlayer(page, 0.8);
+ await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "k1b:on");
+ await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:1,CONTRADICTED:1");
+ await expect.poll(() => opacityIn(frameOf(page, /stamp-preview/), '.stamp[data-claim="k1b"]')).toBeGreaterThan(0.9);
+ await expect.poll(() => opacityIn(frameOf(page, /\/sourced\/index\.html/), '[data-k="ty.CORROBORATED.n1"]')).toBeGreaterThan(0.9);
+
+ // Back before both (source 4.6): no stamp, nothing counted -- the pages are seeked back too.
+ await nudgePlayer(page, -1.6);
+ await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "");
+ await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:0,CONTRADICTED:0");
+ await expect.poll(() => opacityIn(frameOf(page, /stamp-preview/), '.stamp[data-claim="k1"]')).toBeLessThan(0.1);
+
+ // The deck's words: patched into the page as typed, saved on Enter, composed again.
+ const title = page.locator("[data-live-title]");
+ await title.fill("3 Dec 2024");
+ await expect(deck.locator('[data-seg="c02"] .deck-title')).toHaveText("3 Dec 2024");
+ expect(entry("c02")?.onscreen?.title).toBe("2 Dec 2024");
+ await title.press("Enter");
+ await expect.poll(() => entry("c02")?.onscreen?.title).toBe("3 Dec 2024");
+ await expect(page.locator("[data-editor-status]")).toHaveText("Saved the on-screen words");
+ await expect(page.getByTestId("live-preview")).toHaveAttribute("data-deck-ready", "1", { timeout: 60_000 });
+ await expect(deck.locator('[data-seg="c02"] .deck-title')).toHaveText("3 Dec 2024");
+
+ // The last clip is the finale: its page is laid over the deck once it opens; its claim counts there, undrawn.
+ await page.locator('[data-editor-row="c03"]').click();
+ await playerOn(page, "c03");
+ const fin = page.locator('[data-live-preview="c03"]');
+ await expect(fin).toHaveAttribute("data-live-state", "ready");
+ await expect(page.locator('[data-live-goto-mark="k2"]')).toContainText("counts k2");
+ await page.locator('[data-live-goto-mark="k2"]').click();
+ await expect(fin).toHaveAttribute("data-live-where", "inside");
+ await nudgePlayer(page, 1.0);
+ await expect(page.locator("[data-live-finale-up]")).toBeVisible();
+ await expect(page.getByTestId("live-finale")).toHaveAttribute("data-feed-ready", "1", { timeout: 30_000 });
+ await expect(page.locator("[data-live-tally]")).toHaveAttribute("data-live-tally", "CORROBORATED:2,CONTRADICTED:1");
+ await expect(page.locator("[data-live-stamp]")).toHaveAttribute("data-live-stamp", "");
+
+ // Render this clip: a job (stubbed), the file shown inline when done.
+ const render = page.locator('[data-clip-render="c03"]');
+ await render.locator("[data-clip-render-start]").click();
+ await expect(render.locator("[data-clip-render-job]")).toHaveAttribute("data-clip-render-job", "done", { timeout: 30_000 });
+ await expect(render.locator("[data-clip-render-video]")).toBeVisible();
+ expect(existsSync(path.join(DIR, "out", "sourced", "clip-preview", "c03.mp4"))).toBe(true);
+ await expect(render.locator("[data-clip-render-start]")).toHaveText("Render this clip again");
+});
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -38,6 +38,7 @@ import {
updateClaimKnobs,
updateMarks,
updateClip,
+ updateOnscreen,
} from "./manifest.mjs";
import { CLAIM_KNOB_DEFAULTS, markVerdictsOf, rawMarksOf, stampingEntryId } from "./knobs.mjs";
import { resolveFactcheck } from "umtool-report-to-video/factcheck";
@@ -130,6 +131,8 @@ export async function clipEditorView(project) {
// with the entry that stamps it (plans/clip-marks.md).
...marksView(manifest, e),
audio: isObj(e.audio) ? e.audio : null,
+ // The deck's words for it as written (the live preview's fields): absent keys are automatic.
+ onscreen: isObj(e.onscreen) ? e.onscreen : null,
};
});
const shorts = await readShorts(project.dir, manifest);
@@ -323,6 +326,8 @@ const num = (v, what) => {
* { clip, set: [mark, …] | null } all of them (manifest.mjs updateMarks)
* audio { clip, audio: { offset?, gain?, fadeIn?, fadeOut? } | null } the clip's sound
* (null on a key, or the whole: the default)
+ * onscreen { clip, onscreen: { title?, subtitle? } | null } the deck's words for it
+ * (the live preview's fields; null: automatic)
* with `token` (the manifest's, from the view) on every manifest edit.
* Returns `{ op, result, carried, view }`.
*/
@@ -484,8 +489,18 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
structural = false;
break;
}
+ case "onscreen": {
+ // The deck's title and subtitle for this clip (the live preview's
+ // fields), through the On-screen table's writer: a row replaces the
+ // clip's whole `onscreen`, null removes it. Not structural.
+ const e = needClip();
+ if (body.onscreen !== null && !isObj(body.onscreen)) throw new OpError("onscreen is { title?, subtitle? }, or null for the automatic words");
+ result = await updateOnscreen(dir, { [e.id]: body.onscreen }, { token });
+ structural = false;
+ break;
+ }
default:
- throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks or audio");
+ throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio or onscreen");
}
let carried = null;
if (structural) {
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -36,6 +36,8 @@ export type EditorClip = {
/** Every mark (plans/clip-marks.md), in order, each with the entry that stamps it; `claim` is the first. */
marks?: MarkView[];
audio?: ClipAudio | null;
+ /** The deck's words for the clip as written (absent keys are automatic): the live preview's fields. */
+ onscreen?: { title?: string; subtitle?: string } | null;
};
/** A claim with its knobs (plans/video-knobs-plan.md): `at` is a source second. */
diff --git a/umtool/lib/report/clipRender.mjs b/umtool/lib/report/clipRender.mjs
@@ -0,0 +1,85 @@
+// RENDER THIS CLIP (the clip editor's live preview, plans/live-preview.md):
+// one clip's segment with its on-screen chrome, pixel-true, in a minute or
+// two -- build-video.mjs `--clip-preview <id>` as one job on the app's runner
+// (lib/jobs.ts: one at a time, a log, Cancel), which build-video's CLI runs
+// inside the machine's heavy slot. The file is
+// `<project>/out/<variant>/clip-preview/<id>.mp4`, with a record beside it
+// (`<id>.json`: when, the clip's window then, the cut seconds it was laid at)
+// so the editor can say when the clip has moved since.
+//
+// Built from what is on disk (`--skip-fetch`): the editor's player already
+// plays that window, and a preview must never spend a fetch.
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { PIPELINE_DIR } from "./driver.mjs";
+import { safeClipId } from "./shorts.mjs";
+
+/** A clip's render is a minute or two; a stuck render is not left forever. */
+export const CLIP_RENDER_TIMEOUT_MS = 20 * 60_000;
+/** build-video.mjs's CLIP_PREVIEW_DIR, under a variant's out dir. */
+export const CLIP_RENDER_DIR = "clip-preview";
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** `<project>/out/<variant>/clip-preview/<id>.mp4`, or null for an id that is not a file name. */
+export function clipRenderFile(dir, variant, clipId) {
+ if (!safeClipId(clipId) || !/^[a-z]+$/.test(String(variant))) return null;
+ return path.join(/* turbopackIgnore: true */ dir, "out", variant, CLIP_RENDER_DIR, `${clipId}.mp4`);
+}
+
+/**
+ * The job's one step: build-video `--clip-preview`, NDJSON progress, from
+ * what is on disk. No path or argv from a client. E2E_UMTOOL_CLIP_RENDER_SCRIPT
+ * (test-only, playwright.config.ts) names a stub with the same command line.
+ *
+ * @param {{ dir: string }} project
+ * @param {string} clipId
+ * @param {{ variant?: string | null, env?: Record<string, string | undefined> }} [opts]
+ */
+export function clipRenderSteps(project, clipId, { variant = null, env = process.env } = {}) {
+ if (!safeClipId(clipId)) throw new Error(`not a clip id: ${clipId}`);
+ const bin = env.E2E_UMTOOL_CLIP_RENDER_SCRIPT || path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs");
+ return [
+ {
+ cwd: PIPELINE_DIR,
+ env: {},
+ label: `render ${clipId} with its on-screen chrome`,
+ argv: [
+ "node", bin,
+ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
+ "--out", path.join(/* turbopackIgnore: true */ project.dir, "out"),
+ ...(variant ? ["--variant", variant] : []),
+ "--skip-fetch", "--clip-preview", clipId, "--progress", "ndjson",
+ ],
+ ndjson: true,
+ timeoutMs: CLIP_RENDER_TIMEOUT_MS,
+ },
+ ];
+}
+
+/**
+ * The render of one clip on disk, or null: `{ mtimeMs, size, record, stale }`.
+ * `stale`: the clip's window (start, end, cut) moved since it was rendered.
+ *
+ * @param {string} dir the project
+ * @param {string} variant
+ * @param {string} clipId
+ * @param {Record<string, any> | null} [entry] the clip as the manifest has it now
+ */
+export async function readClipRender(dir, variant, clipId, entry = null) {
+ const abs = clipRenderFile(dir, variant, clipId);
+ if (!abs) return null;
+ const st = await stat(abs).catch(() => null);
+ if (!st?.isFile()) return null;
+ const record = await readFile(abs.replace(/\.mp4$/, ".json"), "utf8").then(JSON.parse, () => null);
+ return { mtimeMs: Math.round(st.mtimeMs), size: st.size, record: isObj(record) ? record : null, stale: windowMoved(record, entry) };
+}
+
+/** Has the clip's window moved since `record` was made? Unknown (no record or entry) is not "moved". */
+export function windowMoved(record, entry) {
+ if (!isObj(record) || !isObj(record.window) || !isObj(entry)) return false;
+ const w = record.window;
+ const same = (a, b) => (fin(a) && fin(b) ? Math.abs(a - b) < 0.011 : (a ?? null) === (b ?? null));
+ return !(same(w.start, entry.start) && same(w.end, entry.end) && same(w.cutStart, entry.cutStart) && same(w.cutEnd, entry.cutEnd));
+}
diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs
@@ -57,9 +57,17 @@ export const PRESETS = {
final: { label: "final", xfade: true, chapters: true, only: false, final: true },
};
-/** A build's timeout, scaled to the work rather than to a global guess. */
-export const buildTimeoutMs = (clipCount, xfade) =>
- Math.max(15 * 60_000, clipCount * (xfade ? 120_000 : 60_000));
+/**
+ * A build's timeout, scaled to the work rather than to a global guess: per
+ * clip, and -- for a cut that renders its on-screen chrome (`seconds`, the
+ * cut's estimated length; onscreen.mjs renderSeconds) -- RENDER_BUDGET
+ * seconds of job per second of cut. A 36-clip deck cut of 25 minutes renders
+ * its deck, feed and stamps for about 36 minutes before its segments and
+ * crossfades are made; the per-clip budget alone (72 minutes) would stop it.
+ */
+export const RENDER_BUDGET = 5;
+export const buildTimeoutMs = (clipCount, xfade, seconds = 0) =>
+ Math.max(15 * 60_000, clipCount * (xfade ? 120_000 : 60_000), Math.round(seconds * RENDER_BUDGET * 1000));
/**
* The chain.
@@ -117,10 +125,10 @@ export function availabilityStep(project, env = {}) {
/**
* @param {{ id: string, dir: string }} project
- * @param {{ preset?: string, only?: string | null, skipFetch?: boolean, env?: Record<string,string>, clipCount?: number, options?: BuildOptions }} [opts]
+ * @param {{ preset?: string, only?: string | null, skipFetch?: boolean, env?: Record<string,string>, clipCount?: number, seconds?: number, options?: BuildOptions }} [opts]
* @returns {import("../trim").Step[]}
*/
-export function buildSteps(project, { preset = "fast", only = null, skipFetch = false, env = {}, clipCount = 20, options = {} } = {}) {
+export function buildSteps(project, { preset = "fast", only = null, skipFetch = false, env = {}, clipCount = 20, seconds = 0, options = {} } = {}) {
const p = PRESETS[preset] ?? PRESETS.fast;
const manifest = path.join(project.dir, "video.manifest.json");
const outDir = path.join(project.dir, "out");
@@ -197,7 +205,7 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch =
: p.label,
argv: buildArgv,
ndjson: true,
- timeoutMs: quick ? 5 * 60_000 : buildTimeoutMs(clipCount, p.xfade),
+ timeoutMs: quick ? 5 * 60_000 : buildTimeoutMs(clipCount, p.xfade, p.only && only ? 0 : seconds),
});
// A build can exit 0 and still be wrong: a concat that produced nothing, a
diff --git a/umtool/lib/report/liveClock.mjs b/umtool/lib/report/liveClock.mjs
@@ -0,0 +1,182 @@
+// The clip editor's live preview clock (LiveDeckPreview.tsx): from the
+// SOURCE second the editor's player is at, the CUT second the composition is
+// seeked to, and what the cut shows then -- the tally's counts, the stamp on
+// screen, whether the finale is up. Pure: no DOM, no React, so the arithmetic
+// is unit-tested (liveClock.test.mjs) and the page only applies it.
+//
+// The rule is the estimate's (deck.mjs estimateSchedule, playWindow): a clip's
+// segment starts at its play window's `from` -- the cut with the lead-in
+// breath before it, clamped into the extent -- and plays the source second for
+// second from there; a claim stamped at a source second (`claim.at`) lands
+// through the same `from` (factcheck.mjs stampSchedule). So the stamp lands on
+// its source second in the preview exactly as in the render. What the build
+// does that this does not: it snaps each edge to a nearby silence (up to
+// `render.snapWindow`), so the deck's handover at a join can land that much
+// off; the preview says so.
+
+/** @typedef {{ start: number, end: number, cutStart?: number | null, cutEnd?: number | null }} ClipSpan */
+/** @typedef {{ id: string, start: number, duration: number, end?: number, hold?: number }} Segment */
+/**
+ * @typedef {{ claim: string, verdict: string, segment: string, at: number, landed: number,
+ * out: [number, number], count?: number, stamp?: false, label?: string, finale?: boolean }} Stamp
+ */
+/** @typedef {{ segments: Segment[], factcheck?: { stamps: Stamp[] }, finale?: { from: number, to: number, segments?: string[] } }} Schedule */
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/**
+ * The source seconds a clip plays (deck.mjs playWindow): the cut with the
+ * lead-in before it, clamped into the extent, when it has a cut; else the
+ * extent. The clip editor's draft cut is passed as `cutStart`/`cutEnd`, so an
+ * unsaved nudge moves the clock at once.
+ *
+ * @param {ClipSpan} clip
+ * @param {number} [leadIn] render.leadIn (0.4)
+ */
+export function livePlayWindow(clip, leadIn = 0.4) {
+ const hasCut = fin(clip.cutStart) && fin(clip.cutEnd);
+ return {
+ from: hasCut ? Math.max(clip.start, /** @type {number} */ (clip.cutStart) - leadIn) : clip.start,
+ to: hasCut ? Math.min(clip.end, /** @type {number} */ (clip.cutEnd)) : clip.end,
+ };
+}
+
+/**
+ * Where a clip sits in the cut, for the live preview: its segment's start in
+ * the cut's clock, the source second that start plays (`sourceFrom`), the
+ * source second its footage ends (`sourceTo`), the cut second that last
+ * frame plays at (`playEnd`), and its hold (a carrying clip's last frame
+ * held for its posts, part of the segment). null when the schedule has no
+ * segment for the clip (it is not in this cut).
+ *
+ * @param {Schedule} schedule
+ * @param {ClipSpan & { id: string }} clip
+ * @param {{ leadIn?: number }} [opts]
+ */
+export function liveClock(schedule, clip, { leadIn = 0.4 } = {}) {
+ const i = (schedule?.segments ?? []).findIndex((s) => s.id === clip.id);
+ if (i < 0) return null;
+ const seg = schedule.segments[i];
+ const pw = livePlayWindow(clip, leadIn);
+ const hold = fin(seg.hold) && /** @type {number} */ (seg.hold) > 0 ? /** @type {number} */ (seg.hold) : 0;
+ const playEnd = seg.start + Math.max(0, pw.to - pw.from);
+ return {
+ id: clip.id,
+ index: i,
+ of: schedule.segments.length,
+ start: seg.start,
+ sourceFrom: pw.from,
+ sourceTo: pw.to,
+ playEnd: round(playEnd),
+ hold,
+ end: round(playEnd + hold),
+ };
+}
+
+const round = (v) => Math.round(v * 1000) / 1000;
+
+/**
+ * The cut second a source second plays at. Before the play window the clip's
+ * first frame (`before`), after it its last (`after`): the preview holds
+ * there, as the cut does not show those seconds.
+ *
+ * @param {ReturnType<typeof liveClock>} clock
+ * @param {number} sourceT
+ * @returns {{ t: number, where: "before" | "inside" | "after" }}
+ */
+export function cutTimeAt(clock, sourceT) {
+ if (!clock || !fin(sourceT)) return { t: clock?.start ?? 0, where: "before" };
+ if (sourceT < clock.sourceFrom) return { t: clock.start, where: "before" };
+ if (sourceT > clock.sourceTo) return { t: clock.playEnd, where: "after" };
+ return { t: round(clock.start + (sourceT - clock.sourceFrom)), where: "inside" };
+}
+
+/**
+ * The source second a cut second plays (the inverse, inside the clip): for a
+ * "play the hold" or a seek from the cut's clock. null outside the footage.
+ *
+ * @param {ReturnType<typeof liveClock>} clock
+ * @param {number} t
+ */
+export function sourceTimeAt(clock, t) {
+ if (!clock || !fin(t) || t < clock.start || t > clock.playEnd) return null;
+ return round(clock.sourceFrom + (t - clock.start));
+}
+
+/**
+ * The tally's counts at cut second `t`: every stamp that has LANDED by then
+ * counts its `count` (1 unless the claim says) -- the deck's tallySteps rule.
+ * One row per verdict the cut stamps, in the stamps' verdict order (the
+ * order `order` gives, else first appearance).
+ *
+ * @param {Schedule} schedule
+ * @param {number} t
+ * @param {string[] | null} [order] the tally's cells (factcheck.mjs tallyVerdicts)
+ * @returns {Array<{ verdict: string, count: number }>}
+ */
+export function tallyAt(schedule, t, order = null) {
+ const stamps = schedule?.factcheck?.stamps ?? [];
+ const verdicts = order ?? [...new Set(stamps.map((s) => s.verdict))];
+ const counts = new Map(verdicts.map((v) => [v, 0]));
+ for (const s of stamps) {
+ if (!counts.has(s.verdict) || !(s.landed <= t)) continue;
+ counts.set(s.verdict, /** @type {number} */ (counts.get(s.verdict)) + (s.count ?? 1));
+ }
+ return verdicts.map((v) => ({ verdict: v, count: /** @type {number} */ (counts.get(v)) }));
+}
+
+/**
+ * The stamp on screen at cut second `t`, or null: a DRAWN stamp (not `stamp:
+ * false`, not a finale's) from its `at` -- it slams in until `landed` -- until
+ * the end of its leave (`out[1]`). `phase`: "in" (slamming), "on", "out"
+ * (leaving).
+ *
+ * @param {Schedule} schedule
+ * @param {number} t
+ */
+export function stampAt(schedule, t) {
+ for (const s of schedule?.factcheck?.stamps ?? []) {
+ if (s.stamp === false || s.finale) continue;
+ if (!(t >= s.at && t < s.out[1])) continue;
+ const phase = t < s.landed ? "in" : t < s.out[0] ? "on" : "out";
+ return { claim: s.claim, verdict: s.verdict, segment: s.segment, label: s.label ?? null, at: s.at, landed: s.landed, phase };
+ }
+ return null;
+}
+
+/**
+ * The stamps a clip carries -- one per mark it stamps (a clip may carry
+ * several, `claims`) -- in landing order, each with its landing second in the
+ * SOURCE's clock (where the editor's playhead would have to be), for the
+ * readout and a "go to the stamp" seek. Empty when the clip stamps nothing in
+ * this schedule.
+ *
+ * @param {Schedule} schedule
+ * @param {ReturnType<typeof liveClock>} clock
+ */
+export function clipStamps(schedule, clock) {
+ if (!clock) return [];
+ return (schedule?.factcheck?.stamps ?? [])
+ .filter((x) => x.segment === clock.id)
+ .sort((a, b) => a.landed - b.landed)
+ .map((s) => ({
+ claim: s.claim,
+ verdict: s.verdict,
+ drawn: s.stamp !== false && !s.finale,
+ landed: s.landed,
+ sourceLanded: round(clock.sourceFrom + (s.landed - clock.start)),
+ }));
+}
+
+/** Is the finale's page up at cut second `t` (its window, `from`–`to`)? */
+export function finaleUp(schedule, t) {
+ const f = schedule?.finale;
+ return !!f && fin(f.from) && fin(f.to) && t >= f.from && t <= f.to;
+}
+
+/** `m:ss.s` for a readout. */
+export function clockText(t) {
+ const s = Math.max(0, fin(t) ? t : 0);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`;
+}
diff --git a/umtool/lib/report/liveClock.test.mjs b/umtool/lib/report/liveClock.test.mjs
@@ -0,0 +1,151 @@
+// The clip editor's live preview clock (liveClock.mjs): source playhead → cut
+// clock, the tally at a moment, the stamp on screen, the finale.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { estimateSchedule } from "umtool-report-to-video/deck";
+import { tallyVerdicts } from "umtool-report-to-video/factcheck";
+import {
+ clipStamps, clockText, cutTimeAt, finaleUp, liveClock, livePlayWindow, sourceTimeAt, stampAt, tallyAt,
+} from "./liveClock.mjs";
+
+/** A deck cut of four clips: two claims (one stamped at a source second), a finale last. */
+const manifest = () => ({
+ slug: "t",
+ provenance: { channelSlug: "c", siteOrigin: "https://archive.example" },
+ render: {
+ width: 1920, height: 1080, fps: 30, transition: 0.5,
+ palette: { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" },
+ chrome: {
+ engine: "hyperframes", layout: "deck", deck: {},
+ factcheck: { verdicts: { CONTRADICTED: { label: "Grift" }, CORROBORATED: { label: "Episodes" } }, stamp: { seconds: 3 } },
+ },
+ },
+ timeline: [
+ { type: "clip", id: "a", video: "v1", start: 10, end: 30 },
+ // Cut 104–120 inside its extent: the play window starts 0.4 s before the cut.
+ { type: "clip", id: "b", video: "v2", start: 100, end: 130, cutStart: 104, cutEnd: 120, claim: { id: "k1", verdict: "CORROBORATED", at: 110 } },
+ { type: "clip", id: "c", video: "v3", start: 50, end: 62, claim: { id: "k2", verdict: "CONTRADICTED", count: 2 } },
+ { type: "clip", id: "d", video: "v4", start: 0, end: 20, layout: "finale" },
+ ],
+});
+
+test("livePlayWindow: the cut with its lead-in, clamped into the extent; else the extent", () => {
+ assert.deepEqual(livePlayWindow({ start: 100, end: 130, cutStart: 104, cutEnd: 120 }), { from: 103.6, to: 120 });
+ assert.deepEqual(livePlayWindow({ start: 100, end: 130, cutStart: 100.1, cutEnd: 140 }), { from: 100, to: 130 });
+ assert.deepEqual(livePlayWindow({ start: 10, end: 30 }), { from: 10, to: 30 });
+ assert.deepEqual(livePlayWindow({ start: 10, end: 30, cutStart: 12, cutEnd: 20 }, 1), { from: 11, to: 20 });
+});
+
+test("source playhead → cut clock: the segment's start plays the play window's first second", () => {
+ const m = manifest();
+ const s = estimateSchedule(m);
+ const b = m.timeline[1];
+ const clock = liveClock(s, b);
+ const seg = s.segments.find((x) => x.id === "b");
+ assert.equal(clock.start, seg.start);
+ assert.equal(clock.sourceFrom, 103.6);
+ assert.equal(clock.sourceTo, 120);
+ assert.equal(clock.index, 1);
+ assert.equal(clock.of, 4);
+ // Second for second inside the window; the clip's own frames outside it.
+ assert.deepEqual(cutTimeAt(clock, 103.6), { t: seg.start, where: "inside" });
+ assert.deepEqual(cutTimeAt(clock, 110), { t: Math.round((seg.start + 6.4) * 1000) / 1000, where: "inside" });
+ assert.deepEqual(cutTimeAt(clock, 90), { t: seg.start, where: "before" });
+ assert.equal(cutTimeAt(clock, 125).where, "after");
+ assert.equal(cutTimeAt(clock, 125).t, clock.playEnd);
+ // The estimate's segment is the play window long: its end is the playEnd.
+ assert.equal(clock.playEnd, Math.round((seg.start + seg.duration) * 1000) / 1000);
+ assert.equal(sourceTimeAt(clock, cutTimeAt(clock, 111.25).t), 111.25);
+ assert.equal(sourceTimeAt(clock, clock.start - 1), null);
+ // A draft cut moves the clock at once (the schedule is the saved one).
+ const nudged = liveClock(s, { ...b, cutStart: 105 });
+ assert.equal(nudged.sourceFrom, 104.6);
+ assert.equal(cutTimeAt(nudged, 104.6).t, seg.start);
+ // A clip the cut does not play has no clock.
+ assert.equal(liveClock(s, { id: "nope", start: 0, end: 1 }), null);
+});
+
+test("the stamp lands on its source second, and the tally steps there", () => {
+ const m = manifest();
+ const s = estimateSchedule(m);
+ const order = tallyVerdicts(s.factcheck.stamps);
+ const clock = liveClock(s, m.timeline[1]);
+ const landing = cutTimeAt(clock, 110).t;
+ const st = s.factcheck.stamps.find((x) => x.claim === "k1");
+ assert.ok(Math.abs(st.landed - landing) < 0.002, `landed ${st.landed} vs the source's 110 at ${landing}`);
+ const [cs] = clipStamps(s, clock);
+ assert.equal(cs.claim, "k1");
+ assert.ok(Math.abs(cs.sourceLanded - 110) < 0.002);
+ assert.equal(cs.drawn, true);
+
+ // Just before it lands: slamming in, not counted; once landed: counted, on.
+ assert.equal(stampAt(s, landing - 0.1)?.phase, "in");
+ assert.deepEqual(tallyAt(s, landing - 0.01, order), [{ verdict: "CORROBORATED", count: 0 }, { verdict: "CONTRADICTED", count: 0 }]);
+ assert.equal(stampAt(s, landing + 0.5)?.phase, "on");
+ assert.equal(stampAt(s, landing + 0.5)?.claim, "k1");
+ assert.deepEqual(tallyAt(s, landing, order), [{ verdict: "CORROBORATED", count: 1 }, { verdict: "CONTRADICTED", count: 0 }]);
+ // Gone after its hold and leave; still counted.
+ assert.equal(stampAt(s, st.out[1] + 0.01), null);
+ assert.equal(stampAt(s, st.at - 0.01), null);
+ // The next claim counts 2 at once (its `count`).
+ const k2 = s.factcheck.stamps.find((x) => x.claim === "k2");
+ assert.deepEqual(tallyAt(s, k2.landed, order), [{ verdict: "CORROBORATED", count: 1 }, { verdict: "CONTRADICTED", count: 2 }]);
+ // No order given: the stamps' own.
+ assert.deepEqual(tallyAt(s, 0).map((r) => r.verdict), ["CORROBORATED", "CONTRADICTED"]);
+});
+
+test("the finale: up over its window; a stamp there is counted, not drawn", () => {
+ const m = manifest();
+ m.timeline[3].claim = { id: "k3", verdict: "CONTRADICTED" };
+ const s = estimateSchedule(m);
+ assert.ok(s.finale, "the cut has a finale");
+ assert.equal(finaleUp(s, s.finale.from - 0.01), false);
+ assert.equal(finaleUp(s, s.finale.from), true);
+ assert.equal(finaleUp(s, s.total), true);
+ const k3 = s.factcheck.stamps.find((x) => x.claim === "k3");
+ // The clip before it may still be leaving its own stamp; the finale's is never drawn.
+ for (const t of [k3.at, k3.at + 0.5, s.total - 0.01]) assert.notEqual(stampAt(s, t)?.claim, "k3");
+ assert.equal(stampAt(s, s.total - 0.01), null);
+ assert.equal(clipStamps(s, liveClock(s, m.timeline[3]))[0].drawn, false);
+ assert.equal(tallyAt(s, s.total).find((r) => r.verdict === "CONTRADICTED").count, 3);
+ assert.equal(finaleUp(estimateSchedule(manifest()), 0), false);
+});
+
+test("a clip with two marks: each its own stamp at its own source second, each its own step of the tally", () => {
+ const m = manifest();
+ m.timeline[1] = {
+ ...m.timeline[1],
+ claim: undefined,
+ claims: [{ id: "k1", verdict: "CORROBORATED", at: 106, hold: 2 }, { id: "k1b", verdict: "CONTRADICTED", at: 112 }],
+ };
+ delete m.timeline[1].claim;
+ const s = estimateSchedule(m);
+ const order = tallyVerdicts(s.factcheck.stamps);
+ const clock = liveClock(s, m.timeline[1]);
+ const marks = clipStamps(s, clock);
+ assert.deepEqual(marks.map((x) => x.claim), ["k1", "k1b"]);
+ assert.ok(Math.abs(marks[0].sourceLanded - 106) < 0.002);
+ assert.ok(Math.abs(marks[1].sourceLanded - 112) < 0.002);
+ const at = (src) => cutTimeAt(clock, src).t;
+ assert.equal(stampAt(s, at(106.5))?.claim, "k1");
+ assert.equal(stampAt(s, at(112.5))?.claim, "k1b");
+ const count = (src, v) => tallyAt(s, at(src), order).find((r) => r.verdict === v).count;
+ assert.deepEqual([count(105.9, "CORROBORATED"), count(106, "CORROBORATED"), count(111.9, "CONTRADICTED"), count(112, "CONTRADICTED")], [0, 1, 0, 1]);
+});
+
+test("a held clip: its hold after its footage's last frame", () => {
+ const s = { segments: [{ id: "a", start: 0, duration: 12, hold: 2 }] };
+ const clock = liveClock(s, { id: "a", start: 0, end: 10 });
+ assert.equal(clock.playEnd, 10);
+ assert.equal(clock.end, 12);
+ assert.equal(clock.hold, 2);
+});
+
+test("clockText", () => {
+ assert.equal(clockText(0), "0:00.0");
+ assert.equal(clockText(83.87), "1:23.9");
+ assert.equal(clockText(-3), "0:00.0");
+});
diff --git a/umtool/lib/report/livePreview.test.mjs b/umtool/lib/report/livePreview.test.mjs
@@ -0,0 +1,175 @@
+// The clip editor's live preview, server side (plans/live-preview.md): the
+// preview's estimate on demand, the finale's preview composition and where it
+// is served from, the editor's `onscreen` op, and Render this clip's job step
+// and file.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { MANIFEST_NAME, StaleToken } from "./manifest.mjs";
+import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs";
+import { clipRenderFile, clipRenderSteps, readClipRender, windowMoved } from "./clipRender.mjs";
+import { composeFinalePreview, renderSeconds, scheduleForPreview } from "./onscreen.mjs";
+import { finalePreviewDir, finalePreviewSrc, previewDirFor } from "./serve.mjs";
+import { PIPELINE_DIR, RENDER_BUDGET, buildSteps, buildTimeoutMs } from "./driver.mjs";
+import { takeTimeoutMs } from "./takeMaker.mjs";
+
+const manifest = () => ({
+ schemaVersion: 1,
+ slug: "lp",
+ provenance: { channelSlug: "chan", siteOrigin: "https://example.test" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" }, chrome: { engine: "hyperframes", layout: "deck", deck: {} } },
+ timeline: [
+ { type: "clip", id: "a", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19 },
+ { type: "clip", id: "b", video: "v1", start: 30, end: 40, onscreen: { title: "1 Oct 2026" }, layout: "finale" },
+ ],
+});
+
+async function project() {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-live-preview-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n");
+ return { id: "reports/lp", dir };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+const noLinks = { find: async () => null };
+
+test("scheduleForPreview: `estimate: true` never reads the build's schedule", async () => {
+ const p = await project();
+ try {
+ const m = await read(p.dir);
+ // A build's schedule that still matches the cut, with seconds the estimate would never give.
+ const built = {
+ version: 1, kind: "deck", estimated: false, fps: 30, transition: 0.5, total: 99, multiChannel: false,
+ segments: [
+ { id: "a", type: "clip", start: 0, duration: 50, end: 50, title: "", subtitle: "built", qrUrl: null, hideDeck: false },
+ { id: "b", type: "clip", start: 49.5, duration: 49.5, end: 99, title: "1 Oct 2026", subtitle: "built", qrUrl: null, hideDeck: false },
+ ],
+ };
+ await mkdir(path.join(p.dir, "out", "sourced"), { recursive: true });
+ await writeFile(path.join(p.dir, "out", "sourced", "schedule.json"), JSON.stringify(built));
+ const asBuilt = await scheduleForPreview(p, m, "sourced", new Map(), {}, { resolver: noLinks });
+ assert.equal(asBuilt.schedule.total, 99);
+ const est = await scheduleForPreview(p, m, "sourced", new Map(), {}, { resolver: noLinks, estimate: true });
+ assert.equal(est.schedule.estimated, true);
+ // a: its cut with the 0.4 s lead-in (10.6–19), b: its extent; one 0.5 s join.
+ assert.equal(est.schedule.segments[0].duration, 8.4);
+ assert.equal(est.schedule.total, 8.4 + 10 - 0.5);
+ assert.ok(est.schedule.finale, "the finale is placed");
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("composeFinalePreview: compose-chrome's finale region, into finale-preview, refused anywhere else", async () => {
+ const calls = [];
+ const proj = { dir: "/proj" };
+ const schedule = { finale: { from: 1, to: 2 } };
+ await composeFinalePreview(proj, "sourced", schedule, {
+ compose: async (args) => (calls.push(args), { projDir: path.join(args.outDir, "chrome", "finale-preview") }),
+ });
+ assert.deepEqual(calls[0], {
+ manifestPath: path.join("/proj", "video.manifest.json"),
+ outDir: path.join("/proj", "out", "sourced"),
+ variant: "sourced",
+ region: "finale",
+ schedule,
+ preview: true,
+ });
+ await assert.rejects(
+ composeFinalePreview(proj, "sourced", schedule, { compose: async () => ({ projDir: "/elsewhere" }) }),
+ /not \/proj\/out\/sourced\/chrome\/finale-preview/,
+ );
+});
+
+test("the finale's preview is served from finale-preview/ under the files route", () => {
+ assert.equal(finalePreviewDir("/p", "sourced"), path.join("/p", "out", "sourced", "chrome", "finale-preview"));
+ assert.match(finalePreviewSrc("reports/x", "sourced"), /^\/api\/report\/chrome\/files\/[A-Za-z0-9_-]+\/sourced\/finale-preview\/index\.html$/);
+ assert.deepEqual(previewDirFor("/p", "sourced", ["finale-preview", "assets", "qr00.png"], []), {
+ dir: path.join("/p", "out", "sourced", "chrome", "finale-preview"),
+ rest: ["assets", "qr00.png"],
+ });
+});
+
+test("the editor's `onscreen` op: the clip's deck words through the On-screen writer; null is automatic; the view carries them", async () => {
+ const p = await project();
+ try {
+ const v0 = await clipEditorView(p);
+ assert.equal(v0.clips.find((c) => c.id === "a").onscreen, null);
+ assert.deepEqual(v0.clips.find((c) => c.id === "b").onscreen, { title: "1 Oct 2026" });
+ const r = await runClipEditorOp(p, { op: "onscreen", clip: "a", token: v0.token, onscreen: { title: "24 Oct 2020", subtitle: "a line" } });
+ assert.deepEqual((await read(p.dir)).timeline[0].onscreen, { title: "24 Oct 2020", subtitle: "a line" });
+ assert.deepEqual(r.view.clips.find((c) => c.id === "a").onscreen, { title: "24 Oct 2020", subtitle: "a line" });
+ await runClipEditorOp(p, { op: "onscreen", clip: "a", token: r.view.token, onscreen: null });
+ assert.equal("onscreen" in (await read(p.dir)).timeline[0], false);
+ await assert.rejects(runClipEditorOp(p, { op: "onscreen", clip: "a", onscreen: "words" }), /onscreen is/);
+ await assert.rejects(runClipEditorOp(p, { op: "onscreen", clip: "a", token: "stale", onscreen: null }), StaleToken);
+ await assert.rejects(runClipEditorOp(p, { op: "onscreen", clip: "zz", onscreen: null }), /no clip zz/);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("Render this clip: one step, build-video --clip-preview from what is on disk; a stub by env; ids only", () => {
+ const p = { dir: "/proj" };
+ const [step] = clipRenderSteps(p, "fed", { env: {} });
+ assert.equal(step.cwd, PIPELINE_DIR);
+ assert.deepEqual(step.env, {});
+ assert.deepEqual(step.argv, [
+ "node", path.join(PIPELINE_DIR, "build-video.mjs"), path.join("/proj", "video.manifest.json"),
+ "--out", path.join("/proj", "out"), "--skip-fetch", "--clip-preview", "fed", "--progress", "ndjson",
+ ]);
+ assert.equal(step.ndjson, true);
+ assert.deepEqual(clipRenderSteps(p, "fed", { env: {}, variant: "full" })[0].argv.slice(5, 7), ["--variant", "full"]);
+ assert.equal(clipRenderSteps(p, "fed", { env: { E2E_UMTOOL_CLIP_RENDER_SCRIPT: "/stub.mjs" } })[0].argv[1], "/stub.mjs");
+ assert.throws(() => clipRenderSteps(p, "../x", { env: {} }), /not a clip id/);
+ assert.equal(clipRenderFile("/proj", "sourced", "fed"), path.join("/proj", "out", "sourced", "clip-preview", "fed.mp4"));
+ assert.equal(clipRenderFile("/proj", "sourced", "../fed"), null);
+ assert.equal(clipRenderFile("/proj", "../x", "fed"), null);
+});
+
+test("a deck cut's build is budgeted by its length too: the Huck cut's final is not stopped at 72 minutes", () => {
+ const m = manifest();
+ assert.equal(renderSeconds(m), Math.round(8.4 + 10));
+ assert.equal(renderSeconds({ ...m, render: { ...m.render, chrome: undefined } }), 0);
+ assert.equal(renderSeconds(null), 0);
+ // 36 clips, 25 minutes of cut: the per-clip budget alone was 72 minutes.
+ assert.equal(buildTimeoutMs(36, true), 72 * 60_000);
+ assert.equal(buildTimeoutMs(36, true, 1515), 1515 * RENDER_BUDGET * 1000);
+ assert.ok(buildTimeoutMs(36, true, 1515) > 2 * 60 * 60_000);
+ assert.equal(buildTimeoutMs(3, false, 0), 15 * 60_000);
+ const final = buildSteps({ id: "p", dir: "/p" }, { preset: "final", clipCount: 36, seconds: 1515 });
+ assert.equal(final.find((s) => s.label === "final").timeoutMs, 1515 * RENDER_BUDGET * 1000);
+ // One clip's preview build is not the cut's.
+ const one = buildSteps({ id: "p", dir: "/p" }, { preset: "preview", only: "c1", clipCount: 36, seconds: 1515 });
+ assert.equal(one.at(-1).timeoutMs, 36 * 60_000);
+ assert.equal(takeTimeoutMs(true, 36, 1515), 1515 * RENDER_BUDGET * 1000);
+ assert.equal(takeTimeoutMs(true, 36), 36 * 60_000);
+ assert.equal(takeTimeoutMs(false, 36, 1515), 15 * 60_000);
+});
+
+test("a clip's render on disk, and whether its window moved since", async () => {
+ const p = await project();
+ try {
+ assert.equal(await readClipRender(p.dir, "sourced", "a"), null);
+ const dir = path.join(p.dir, "out", "sourced", "clip-preview");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "a.mp4"), "mp4");
+ const window = { start: 10, end: 20, cutStart: 11, cutEnd: 19 };
+ await writeFile(path.join(dir, "a.json"), JSON.stringify({ version: 1, id: "a", window }));
+ const entry = (await read(p.dir)).timeline[0];
+ const r = await readClipRender(p.dir, "sourced", "a", entry);
+ assert.equal(r.size, 3);
+ assert.equal(r.stale, false);
+ assert.deepEqual(r.record.window, window);
+ assert.equal((await readClipRender(p.dir, "sourced", "a", { ...entry, cutEnd: 18.5 })).stale, true);
+ assert.equal(windowMoved(null, entry), false);
+ assert.equal(windowMoved({ window: { start: 30, end: 40, cutStart: null, cutEnd: null } }, { start: 30, end: 40 }), false);
+ assert.equal(windowMoved({ window: { start: 30, end: 40, cutStart: null, cutEnd: null } }, { start: 30, end: 40, cutStart: 31, cutEnd: 39 }), true);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -24,7 +24,9 @@ import {
attachPosts,
clipDay,
deckGeometry,
+ deckOn,
deckText,
+ estimatedDuration,
estimateSchedule,
footageMoves,
playWindow,
@@ -33,6 +35,7 @@ import {
postWindows,
resolveDeck,
roundPosts,
+ transitionOf,
} from "umtool-report-to-video/deck";
import { marksOf, rawMarksOf, roundStamps, stampSchedule } from "umtool-report-to-video/factcheck";
import { setMarks } from "./knobs.mjs";
@@ -44,7 +47,7 @@ import {
readCues,
} from "../projects/report.mjs";
import { normalizePostPatches, splitOnscreenRow } from "./manifest.mjs";
-import { deckPreviewDir, feedPreviewDir, postsPreviewDir, stampPreviewDir } from "./serve.mjs";
+import { deckPreviewDir, feedPreviewDir, finalePreviewDir, postsPreviewDir, stampPreviewDir } from "./serve.mjs";
import { ensureWriteDir } from "./storage.mjs";
/** The schedule document deck.mjs defines, built or estimated. */
@@ -389,15 +392,22 @@ async function readBuiltSchedule(dir, variant) {
* @param {Record<string, any>} manifest
* @param {string} variant
* @param {Map<string, { title?: string, subtitle?: string } | null>} draft
+ *
+ * `estimate: true` never reads the build's schedule: the clip editor's live
+ * preview (LiveDeckPreview) maps the playing source through the play window,
+ * as an estimate does, so its clock and the schedule's agree on every clip --
+ * a window moved since the build is placed where it is now, not where the
+ * build cut it.
*/
export async function scheduleForPreview(
- project, manifest, variant, draft = new Map(), postsDraft = {}, { resolver = previewPostResolver(), claimsDraft = new Map() } = {},
+ project, manifest, variant, draft = new Map(), postsDraft = {},
+ { resolver = previewPostResolver(), claimsDraft = new Map(), estimate = false } = {},
) {
const selected = selectVariant(manifest, variant);
const entries = selected.timeline ?? [];
const posts = Array.isArray(selected.posts) ? selected.posts : [];
const [built, metas, linked] = await Promise.all([
- readBuiltSchedule(project.dir, variant),
+ estimate ? null : readBuiltSchedule(project.dir, variant),
deckMetas(project.dir, manifest, entries),
// The posts as the draft leaves them, so a post the draft un-hides is
// linked too (a hidden one is not looked up).
@@ -419,6 +429,24 @@ export async function scheduleForPreview(
return { variantManifest, metas, schedule: previewSchedule({ variantManifest, built, draft, metas, postsDraft, claimsDraft }) };
}
+/**
+ * How long a cut is, estimated from the manifest, when its build renders the
+ * on-screen chrome (the deck on): the seconds a build's job budget scales with
+ * (driver.mjs buildTimeoutMs, takeMaker.mjs takeTimeoutMs). 0 without the deck.
+ *
+ * @param {Record<string, any> | null} manifest
+ * @param {string | null} [variant]
+ */
+export function renderSeconds(manifest, variant = null) {
+ if (!manifest) return 0;
+ const selected = selectVariant(manifest, variant || "sourced");
+ const render = selected.render ?? {};
+ if (!deckOn(render)) return 0;
+ const D = transitionOf(render);
+ const entries = selected.timeline ?? [];
+ return Math.round(entries.reduce((sum, e) => sum + estimatedDuration(e, render, D), 0));
+}
+
/** The most a preview request waits on the archive for its posts' links, all of them together. */
const PREVIEW_LINK_DEADLINE_MS = 10000;
@@ -537,6 +565,32 @@ export async function composeStampPreview(project, variant, schedule, { compose
}
/**
+ * Compose the PREVIEW of the finale (a schedule with `finale`): compose-chrome's
+ * `finale` region, one project for its window under
+ * out/<variant>/chrome/finale-preview/. No render. The page is seeked in the
+ * cut's seconds (chrome-finale.mjs, `finale:ready`). `compose` is injectable
+ * for the unit test; the routes never pass it.
+ *
+ * @param {{ dir: string }} project
+ * @param {string} variant
+ * @param {Record<string, any>} schedule
+ * @param {{ compose?: (args: Record<string, unknown>) => Promise<any> }} [opts]
+ */
+export async function composeFinalePreview(project, variant, schedule, { compose = composeChrome } = {}) {
+ const outDir = path.join(project.dir, "out", variant);
+ const want = finalePreviewDir(project.dir, variant);
+ return serialised(want, async () => {
+ /** @type {Record<string, unknown>} */
+ const args = { manifestPath: manifestPath(project.dir), outDir, variant, region: "finale", schedule, preview: true };
+ const r = await compose(/** @type {any} */ (args));
+ if (r?.projDir && path.resolve(r.projDir) !== path.resolve(want)) {
+ throw new Error(`compose-chrome wrote the finale preview to ${r.projDir}, not ${want}`);
+ }
+ return r;
+ });
+}
+
+/**
* The box each built segment's footage was framed into, by entry id: the
* `framing` its cut record names (build-video's segmentFraming), else -- a
* segment built before records named it, or none built yet -- the deck's own
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -386,6 +386,20 @@ export const stampPreviewDir = (projectDir, variant) =>
export const stampPreviewSrc = (projectId, variant) =>
`/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/${STAMP_PREVIEW}/index.html`;
+// The FINALE's preview composition (a schedule with `finale`): one project
+// for its window, out/<variant>/chrome/finale-preview/ (compose-chrome names
+// it), served as the stamps' are, `finale-preview/…`. The page is seeked in
+// the cut's seconds; the window is in the preview's answer.
+const FINALE_PREVIEW = "finale-preview";
+
+/** The preview project of a cut's finale. */
+export const finalePreviewDir = (projectDir, variant) =>
+ path.join(projectDir, "out", variant, "chrome", FINALE_PREVIEW);
+
+/** The iframe src for a cut's finale preview composition. */
+export const finalePreviewSrc = (projectId, variant) =>
+ `/api/report/chrome/files/${encodeProjectSegment(projectId)}/${variant}/${FINALE_PREVIEW}/index.html`;
+
/** The preview project of the posts window on one segment. */
export const postsPreviewDir = (projectDir, variant, segment) =>
path.join(projectDir, "out", variant, "chrome", `${POSTS_PREVIEW_PREFIX}${segment}`);
@@ -398,8 +412,9 @@ export const postsPreviewSrc = (projectId, variant, segment) =>
* Which preview directory a files request is for, and the segments left to
* resolve inside it.
*
- * `feed-preview/…` is the posts feed's project (one per cut), and
- * `stamp-preview/…` the fact-check stamps' (one per cut).
+ * `feed-preview/…` is the posts feed's project (one per cut),
+ * `stamp-preview/…` the fact-check stamps' (one per cut) and
+ * `finale-preview/…` the finale's (one per cut).
* `posts-preview-<segment>/…` is a posts window's project when `<segment>` is
* one of `segmentIds` -- the cut's own entry ids, which the caller reads from
* the manifest, so a name the client made up is not a directory this serves.
@@ -419,6 +434,7 @@ export function previewDirFor(projectDir, variant, rest, segmentIds) {
const head = rest[0];
if (head === FEED_PREVIEW) return { dir: feedPreviewDir(projectDir, variant), rest: rest.slice(1) };
if (head === STAMP_PREVIEW) return { dir: stampPreviewDir(projectDir, variant), rest: rest.slice(1) };
+ if (head === FINALE_PREVIEW) return { dir: finalePreviewDir(projectDir, variant), rest: rest.slice(1) };
if (typeof head === "string" && head.startsWith(POSTS_PREVIEW_PREFIX)) {
const seg = head.slice(POSTS_PREVIEW_PREFIX.length);
if (!seg || /[\/\\\0]/.test(seg) || seg === "." || seg === "..") return null;
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -43,7 +43,7 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
import { mergePatch } from "umtool-report-to-video/montage-styles";
import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings";
-import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs";
+import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs";
import { replaceManifest } from "./manifest.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { isTakeId, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs";
@@ -693,8 +693,13 @@ export async function pickTake(project, takeId, { anyway = false, token = null,
// The app's jobs: the CLI above, as job steps (lib/jobs.ts runs them).
// ---------------------------------------------------------------------------
-/** A take render's timeout: a window is minutes; the whole cut is the fast build's own budget. */
-export const takeTimeoutMs = (full, clipCount) => (full ? Math.max(15 * 60_000, clipCount * 60_000) : 15 * 60_000);
+/**
+ * A take render's timeout: a window is minutes; the whole cut is the fast
+ * build's own budget, and a cut that renders its on-screen chrome (`seconds`,
+ * its estimated length) RENDER_BUDGET seconds of job per second of cut.
+ */
+export const takeTimeoutMs = (full, clipCount, seconds = 0) =>
+ (full ? Math.max(15 * 60_000, clipCount * 60_000, Math.round(seconds * RENDER_BUDGET * 1000)) : 15 * 60_000);
const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
@@ -710,10 +715,10 @@ const windowArgs = (w) => (w === "full" ? ["--full"] : ["--at", String(w.at), "-
*
* @param {{ id: string }} project
* @param {Record<string, any>} req
- * @param {{ styles: Record<string, { label: string }>, existing: Array<{ id: string, window?: unknown }>, clipCount: number }} ctx
+ * @param {{ styles: Record<string, { label: string }>, existing: Array<{ id: string, window?: unknown }>, clipCount: number, seconds?: number }} ctx
* @returns {{ kind: string, takes: string[], steps: Array<{ label: string, argv: string[], cwd: string, env: Record<string, string>, ndjson: true, timeoutMs: number }> }}
*/
-export function takeSteps(project, req, { styles, existing, clipCount }) {
+export function takeSteps(project, req, { styles, existing, clipCount, seconds = 0 }) {
const ids = new Set(existing.map((t) => t.id));
const base = { cwd: UMTOOL_DIR, env: {}, ndjson: /** @type {const} */ (true) };
const cli = ["node", umtoolCli()];
@@ -724,7 +729,7 @@ export function takeSteps(project, req, { styles, existing, clipCount }) {
return {
kind: `take ${project.id} ${t.id} (rebuild)`,
takes: [t.id],
- steps: [{ ...base, label: `rebuild take ${t.id}`, argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", "--progress", "ndjson"], timeoutMs: takeTimeoutMs(t.window === "full", clipCount) }],
+ steps: [{ ...base, label: `rebuild take ${t.id}`, argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", "--progress", "ndjson"], timeoutMs: takeTimeoutMs(t.window === "full", clipCount, seconds) }],
};
}
if (isObj(req.allStyles)) {
@@ -741,7 +746,7 @@ export function takeSteps(project, req, { styles, existing, clipCount }) {
...base,
label: `make ${recipe.takes.length} take(s), one per style`,
argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...(recipe.quick ? ["--quick"] : []), ...force, "--progress", "ndjson"],
- timeoutMs: recipe.takes.length * takeTimeoutMs(recipe.window === "full", clipCount),
+ timeoutMs: recipe.takes.length * takeTimeoutMs(recipe.window === "full", clipCount, seconds),
}],
};
}
@@ -762,7 +767,7 @@ export function takeSteps(project, req, { styles, existing, clipCount }) {
return {
kind: `take ${project.id} ${spec.id}`,
takes: [spec.id],
- steps: [{ ...base, label: `make take ${spec.id}`, argv, timeoutMs: takeTimeoutMs(spec.window === "full", clipCount) }],
+ steps: [{ ...base, label: `make take ${spec.id}`, argv, timeoutMs: takeTimeoutMs(spec.window === "full", clipCount, seconds) }],
};
}
throw new Error("say what to make: take, allStyles or rebuild");
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -27,6 +27,9 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
// E2E_UMTOOL_VARIANTS_SCRIPT set below on the app server: the variants
// encoder Make variants runs (video knobs;
// lib/report/driver.mjs variantsSteps), stubbed
+// E2E_UMTOOL_CLIP_RENDER_SCRIPT set below on the app server: Render this
+// clip's renderer (the live preview;
+// lib/report/clipRender.mjs), stubbed
// The ports are common/lib/ports.mjs's (offset per worktree by
// scripts/worktree.mjs), not test-only, and keep their names.
const PORT = portFor("UMTOOL_E2E_PORT");
@@ -170,6 +173,10 @@ export default defineConfig({
// Make variants' encoder (video knobs): a stub of report-to-video/variants.mjs's
// command line that copies bytes instead of encoding. Read by lib/report/driver.mjs.
`E2E_UMTOOL_VARIANTS_SCRIPT=${path.join(path.dirname(fileURLToPath(import.meta.url)), "e2e", "fixtures", "variants.e2e.mjs")} ` +
+ // Render this clip's renderer (the live preview): a stub of build-video.mjs
+ // --clip-preview's command line that copies the cached window. Read by
+ // lib/report/clipRender.mjs.
+ `E2E_UMTOOL_CLIP_RENDER_SCRIPT=${path.join(path.dirname(fileURLToPath(import.meta.url)), "e2e", "fixtures", "clip-render.e2e.mjs")} ` +
// Where a clip window is fetched FROM, and the shared secret it is asked
// with. Set here rather than in a step's env: jobView() echoes a step's
// env back to the browser, and this is a token.
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -49,6 +49,12 @@
// --audio-fallback With --no-network or --skip-fetch: play such a clip from
// its sound under a poster instead (logged audio-fallback)
// --only <id> Build a single entry's segment and stop (for iterating)
+// --clip-preview <id> One clip's segment WITH its deck: the segment built as
+// --only builds it, the deck/feed/posts/stamps/finale
+// rendered over its window alone (the other segments'
+// lengths measured on disk, else estimated) and laid over
+// it, in out/<variant>/clip-preview/<id>.mp4. Takes the
+// heavy slot; never touches the build's chrome/ or schedule.
// --lint Lint the manifest (lint.mjs) and stop: every warning and
// error, exit 1 on an error. Every build runs the same lint
// after its validators and before it renders anything: an
@@ -139,7 +145,7 @@ import { ensureWriteDir } from "../lib/report/storage.mjs";
// the schedule down -- it never has a copy of the arithmetic.
import {
assertChrome, deckGeometry, deckOn, deckSchedule, endFadeOf, feedGeometry, feedOn, frameCount, hidesDeck, MUTE_FADE,
- dipOf, muteSegmentSeconds, playWindow, postsGeometry, postWindows, resolveDeck, scheduleFrom, snapWindow, stampGeometry,
+ dipOf, estimatedDuration, muteSegmentSeconds, playWindow, postsGeometry, postWindows, resolveDeck, scheduleFrom, snapWindow, stampGeometry,
statsGeometry, teaserHits, teaserSeconds, teaserTitle, threadsGeometry,
validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, fxGeometry, even as evenPx,
} from "./deck.mjs";
@@ -4047,6 +4053,28 @@ export async function cutJoins({ schedule = null, entries, segments, render }) {
return withCutEdits(base, segments.length, { mutes, fade, dips });
}
+/** `--clip-preview`'s own directory under a variant's out dir: its schedule, chrome and `<id>.mp4`s. */
+export const CLIP_PREVIEW_DIR = "clip-preview";
+export const clipPreviewDir = (outDir) => path.join(outDir, CLIP_PREVIEW_DIR);
+
+/**
+ * The join `--clip-preview` makes on its one segment (entry `i` of the cut):
+ * the deck's hold and footage move for it (`segmentJoins` of the cut's
+ * schedule), its `muteFrom`, and the end fade when it is the cut's last.
+ * Never a dip or a crossfade: it plays alone. null when there is nothing.
+ */
+export async function clipPreviewJoin({ schedule, entries, i, seg, render }) {
+ const base = segmentJoins(schedule)?.[i] ?? null;
+ const last = i === entries.length - 1;
+ const edits = await cutJoins({ entries: [entries[i]], segments: [seg], render: last ? render : { ...render, endFade: 0 } });
+ const own = edits?.[0] ?? null;
+ if (!base && !own) return null;
+ const join = { hold: 0, move: null, ...(own ?? {}), ...(base ?? {}) };
+ // The end fade's last frame counts the hold's clones (cutJoins' own rule).
+ if (join.fade && join.hold > 0) join.fade = { ...join.fade, lastFrame: join.fade.lastFrame + Math.round(join.hold * render.fps) };
+ return join;
+}
+
/**
* Where the cut dips to black, from its joins (`withCutEdits`' `dip`s) and its
* segments' lengths in the cut (`cutOffsets`' `durs`, holds included), in the
@@ -4950,10 +4978,15 @@ export async function writeChromeSchedule({ manifest, entries, segments, D, outD
return doc;
}
-/** writeChromeSchedule's document, not written: what `--chapters-only` measures the cut by. */
-export async function measureChromeSchedule({ manifest, entries, segments, D }) {
+/**
+ * writeChromeSchedule's document, not written: what `--chapters-only` measures the cut by.
+ * `durs` given (`--clip-preview`: the segments on disk measured, the missing
+ * ones estimated) are used instead of probing every segment; `estimated` says
+ * so in the document.
+ */
+export async function measureChromeSchedule({ manifest, entries, segments, D, durs: given = null, estimated = false }) {
const { render, provenance = {} } = manifest;
- const { durs } = await segmentOffsets(segments, D, render.fps);
+ const durs = given ?? (await segmentOffsets(segments, D, render.fps)).durs;
const metas = [];
for (const e of entries) {
if (e.type !== "clip") {
@@ -4984,6 +5017,7 @@ export async function measureChromeSchedule({ manifest, entries, segments, D })
entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null,
...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}),
...(clipClock ? { clipClock } : {}),
+ ...(estimated ? { estimated: true } : {}),
});
}
@@ -5489,7 +5523,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const narration = new Map(); // card id -> its record
const wantNarration = narrationsOf(manifest).filter((n) => !only || n.id === only);
const narrationStore = narrationDir(outRoot);
- if (wantNarration.length && !opts.chaptersOnly && !opts.railOnly && !opts.chromePreview) {
+ if (wantNarration.length && !opts.chaptersOnly && !opts.railOnly && !opts.chromePreview && !opts.clipPreview) {
for (const [id, rec] of await readNarrationRecords(narrationStore, wantNarration)) narration.set(id, rec);
const missing = wantNarration.filter((n) => !narration.has(n.id));
if (missing.length && !opts.skipFetch && !opts.chromeOnly) {
@@ -5743,6 +5777,66 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
return { out, failures: [] };
}
+ // ONE CLIP WITH ITS CHROME (`--clip-preview <id>`, umtool's "Render this
+ // clip"): a pixel-true check of one clip without the cut. Its segment is
+ // built as the full build builds it (the same snap, room, framing and sound;
+ // into segments/, which a later build reuses), the schedule is measured from
+ // the segments on disk with each missing one ESTIMATED (only the starts
+ // move; this clip's own seconds are measured), and the deck, feed, posts,
+ // stamps and finale are rendered over this segment's window alone -- in
+ // out/<variant>/clip-preview/, never the build's chrome/ or schedule.json --
+ // and laid over it: out/<variant>/clip-preview/<id>.mp4. The joins to its
+ // neighbours are not made (it plays alone); its hold, its footage moves, its
+ // mute and, when it is the last clip, the end fade are.
+ if (opts.clipPreview) {
+ const id = opts.clipPreview;
+ if (!deck) throw new Error("--clip-preview lays the deck over one clip: render.chrome is not set in the manifest");
+ if (montage) throw new Error("--clip-preview: a montage makes its cuts inside its segments — preview it with the Build tab");
+ const i = entries.findIndex((e) => e.id === id);
+ if (i < 0) throw new Error(`--clip-preview: no entry ${id} in the ${variant} cut`);
+ const entry = entries[i];
+ if (entry.type !== "clip") throw new Error(`--clip-preview: ${id} is a ${entry.type ?? "non-clip"} entry, not a clip`);
+ const segs = entries.map((e) => path.join(outDir, "segments", `${e.id}.mp4`));
+ const seg = await buildEntrySegment(entry, i);
+ EMIT("segment", { id, path: seg });
+ await linkPosts();
+ const durs = [];
+ let estimated = false;
+ for (const [j, e] of entries.entries()) {
+ if (j === i || (await exists(segs[j]))) durs.push(await probeDuration(j === i ? seg : segs[j], render.fps));
+ else {
+ durs.push(estimatedDuration(e, render, D));
+ estimated = true;
+ }
+ }
+ const schedule = await measureChromeSchedule({ manifest, entries, segments: segs, D, durs, estimated });
+ const s = schedule.segments[i];
+ const pv = clipPreviewDir(outDir);
+ await mkdir(pv, { recursive: true });
+ await writeFile(path.join(pv, "schedule.json"), JSON.stringify(schedule, null, 2) + "\n");
+ EMIT("chrome", { phase: "schedule", total: schedule.total, segments: schedule.segments.length, estimated });
+ const plan = await renderDeck({ manifestPath, render, outDir: pv, variant, schedule, from: s.start, duration: s.duration });
+ const join = await clipPreviewJoin({ schedule, entries, i, seg, render });
+ const out = path.join(pv, `${id}.mp4`);
+ const tmp = path.join(pv, `${id}.partial.mp4`);
+ EMIT("chrome", { phase: "overlay", base: path.basename(seg) });
+ await execFileP(FFMPEG, previewFromSegmentsArgs({
+ segments: [seg], durs: [s.duration], starts: [s.start], D, at: s.start, dur: s.duration, render,
+ chromePlan: plan, outPath: tmp, joins: join ? [join] : null,
+ }), { maxBuffer: 1 << 26 });
+ await rename(tmp, out);
+ const rec = await readCutRecord(seg);
+ await writeFile(path.join(pv, `${id}.json`), JSON.stringify({
+ version: 1, id, builtAt: new Date().toISOString(), start: s.start, duration: s.duration, estimated,
+ window: { start: entry.start, end: entry.end, cutStart: entry.cutStart ?? null, cutEnd: entry.cutEnd ?? null },
+ ...(Number.isFinite(rec?.start) ? { sourceFrom: rec.start } : {}),
+ }, null, 2) + "\n");
+ // The window's frame sequences are a cache of one look: gone once laid (--keep-frames keeps them).
+ if (!opts.keepFrames) await pruneChromeFrames(pv);
+ EMIT("done", { out, failures: [] });
+ return { out, failures: [] };
+ }
+
// The deck again, over the segments already on disk: `--chrome-only` re-lays
// it on the whole cut, `--chrome-preview <at> <dur>` on a window of it. No
// segment is rebuilt and nothing is fetched; the schedule is re-measured from
@@ -6123,7 +6217,7 @@ export function chromeFlags(argv) {
/**
* Does this run take the machine's heavy slot (heavy-gate.mjs)? Every run that
* renders the cut does -- a full build, --chrome-only, --chrome-preview,
- * --rail-only, a --no-chrome build. A fetch, one `--only` segment, the
+ * --rail-only, a --no-chrome build, one clip's --clip-preview. A fetch, one `--only` segment, the
* chapters and the thumbnail do not.
*/
export function takesHeavySlot({ opts = {}, only = null, fetchOnly = null } = {}) {
@@ -6156,6 +6250,7 @@ async function main() {
" [--progress ndjson] [--continue-on-error] [--no-reuse]\n" +
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
" [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" +
+ " [--clip-preview <id>] (one clip's segment with its deck: out/<variant>/clip-preview/<id>.mp4)\n" +
" [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" +
" [--no-rulings] (build as if there were no montage-rulings.json beside the manifest)\n" +
" [--narration-unreviewed] (build narrated cards the review has not approved; never a rejected one)\n" +
@@ -6200,6 +6295,7 @@ async function main() {
final: argv.includes("--final"),
draftsUnreviewed: argv.includes("--drafts-unreviewed"),
short: flag("--short") ?? null,
+ clipPreview: flag("--clip-preview") ?? null,
joinPreview: argv.includes("--join-preview") ? { from: flag("--join-from") ?? null } : null,
};
try {
diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs
@@ -600,6 +600,16 @@ export function finaleHtml(schedule, render, window, opts = {}) {
tl.seek(at, false);
ready.then(() => tl.seek(at, false));
}
+ // umtool's live preview: the parent seeks in CUT seconds, as it seeks the deck.
+ if (params.get("preview") === "1") {
+ window.addEventListener("message", (e) => {
+ const m = e.data || {};
+ if (m.type === "deck:seek") tl.seek(Math.max(0, Math.min(F.dur, (Number(m.t) || 0) - F.from)), false);
+ });
+ ready.then(() => {
+ if (window.parent !== window) window.parent.postMessage({ type: "finale:ready", from: F.from, dur: F.dur }, "*");
+ });
+ }
</script>
</body>
</html>
diff --git a/umtool/report-to-video/clip-preview.test.mjs b/umtool/report-to-video/clip-preview.test.mjs
@@ -0,0 +1,59 @@
+// `--clip-preview <id>` (umtool's "Render this clip", plans/live-preview.md):
+// the heavy slot, the one segment's join, its own directory, and the finale
+// page's live-preview hook (the clip editor seeks it in the cut's seconds).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import path from "node:path";
+import test from "node:test";
+
+import { CLIP_PREVIEW_DIR, clipPreviewDir, clipPreviewJoin, finaleRegions, takesHeavySlot } from "./build-video.mjs";
+import { finaleHtml } from "./chrome-finale.mjs";
+import { deckSchedule } from "./deck.mjs";
+
+const PALETTE = { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" };
+const render = (deck = {}, extra = {}) => ({
+ width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE,
+ chrome: { engine: "hyperframes", layout: "deck", deck, factcheck: { verdicts: { CONTRADICTED: { label: "Grift" } } } },
+ ...extra,
+});
+const PROV = { siteOrigin: "https://example.test", channelSlug: "chan" };
+const clips = (n, { finale = null } = {}) => Array.from({ length: n }, (_, i) => ({
+ id: `c${i}`, type: "clip", video: `v${i}`, start: 100, end: 130,
+ ...(i === 1 ? { claim: { id: "k1", verdict: "CONTRADICTED" } } : {}),
+ ...(finale === i ? { layout: "finale" } : {}),
+}));
+
+test("--clip-preview renders, so it takes the heavy slot; --only does not", () => {
+ assert.equal(takesHeavySlot({ opts: { clipPreview: "c1" } }), true);
+ assert.equal(takesHeavySlot({ opts: {}, only: "c1" }), false);
+});
+
+test("its own directory under the variant's out dir, never the build's chrome/", () => {
+ assert.equal(CLIP_PREVIEW_DIR, "clip-preview");
+ assert.equal(clipPreviewDir("/p/out/sourced"), path.join("/p/out/sourced", "clip-preview"));
+});
+
+test("clipPreviewJoin: the schedule's hold and footage move for that one segment; nothing else to join is null", async () => {
+ const r = render();
+ const entries = clips(3);
+ const s = deckSchedule({ entries, durs: [30, 30, 30], D: 0.5, render: r, provenance: PROV });
+ // No hold, no move, no mute, not the last with an end fade: nothing.
+ assert.equal(await clipPreviewJoin({ schedule: s, entries, i: 1, seg: "/nope.mp4", render: r }), null);
+ // A hold and a move on the segment (a carrying clip's posts) are this join's.
+ const move = { segment: "c1", at: 50, segmentAt: 20, seconds: 0.8, from: { x: 0, y: 0, width: 100, height: 50 }, to: { x: 10, y: 10, width: 50, height: 25 } };
+ const held = { ...s, segments: s.segments.map((x) => (x.id === "c1" ? { ...x, hold: 2 } : x)), moves: [move] };
+ assert.deepEqual(await clipPreviewJoin({ schedule: held, entries, i: 1, seg: "/nope.mp4", render: r }), { hold: 2, move });
+ assert.equal(await clipPreviewJoin({ schedule: held, entries, i: 0, seg: "/nope.mp4", render: r }), null);
+});
+
+test("the finale page answers the live preview: `finale:ready`, seeked in the cut's seconds", () => {
+ const r = render({ finale: {} });
+ const entries = clips(4, { finale: 3 });
+ const s = deckSchedule({ entries, durs: [30, 30, 30, 30], D: 0.5, render: r, provenance: PROV });
+ const win = finaleRegions(r, "/tmp/x", s)[0].window;
+ const html = finaleHtml(s, r, win, {});
+ assert.match(html, /params\.get\("preview"\) === "1"/);
+ assert.match(html, /type: "finale:ready"/);
+ assert.match(html, /m\.type === "deck:seek"\) tl\.seek\(Math\.max\(0, Math\.min\(F\.dur, \(Number\(m\.t\) \|\| 0\) - F\.from\)\), false\)/);
+});