Archilyzer · Source

archilyzer

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

commit d960d321af29a5ef3f5e29c633674d40ad50c7fd
parent 4cc0e748e8bab5067644b713b7e420305577fb25
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 12:34:33 -0400

Merge lane/knobs-ui: every video knob in the UI, the CLI and an agent-token route -- Count & stamp and Audio boxes, stamp look, markers editor, Make variants and the sync table, umtool set/look/variants

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

Diffstat:
MAGENTS.md | 4+++-
Aplans/video-knobs-ui.md | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/build/route.ts | 3+++
Mumtool/app/api/report/chrome/preview/route.ts | 3++-
Mumtool/app/api/report/chrome/route.ts | 39++++++++++++++++++++++++++++++++++++++-
Mumtool/app/api/report/claim/route.ts | 3+++
Mumtool/app/api/report/clip-editor/route.ts | 3+++
Mumtool/app/api/report/cut/route.ts | 3+++
Mumtool/app/api/report/deliver/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/drafts/route.ts | 3+++
Mumtool/app/api/report/hand-fill/route.ts | 3+++
Mumtool/app/api/report/narration/route.ts | 3+++
Mumtool/app/api/report/onscreen/route.ts | 3+++
Mumtool/app/api/report/posts/route.ts | 3+++
Mumtool/app/api/report/render/route.ts | 27+++++++++++++++++++++++++--
Mumtool/app/api/report/timeline/route.ts | 6++++++
Aumtool/app/api/report/variants/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/video-assist/route.ts | 3+++
Mumtool/app/api/report/window/route.ts | 3+++
Mumtool/bin/umtool.mjs | 24+++++++++++++++++++++++-
Aumtool/components/projects/MarkersEditor.tsx | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/OnscreenSection.tsx | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/StructureEditors.tsx | 50++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/report/DeliverTab.tsx | 4++++
Aumtool/components/projects/report/VariantsPanel.tsx | 286+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/ClipEditor.tsx | 56+++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/components/projects/review/ClipKnobs.tsx | 238+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 6+++++-
Aumtool/docs/knobs.md | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/notes.md | 4++++
Mumtool/docs/report-video.md | 3+++
Aumtool/e2e/fixtures/knobs-fixture.mjs | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/variants.e2e.mjs | 26++++++++++++++++++++++++++
Aumtool/e2e/knobs.spec.ts | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/caller.ts | 13+++++++++++++
Mumtool/lib/report/clipEditor.mjs | 51++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/clipEditor.test.mjs | 26++++++++++++++++++++++++++
Mumtool/lib/report/clipEditorTypes.ts | 13+++++++++++++
Mumtool/lib/report/driver.mjs | 30++++++++++++++++++++++++++++++
Aumtool/lib/report/knobs.mjs | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/knobs.test.mjs | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/knobsCli.mjs | 377+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/knobsCli.test.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 267+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aumtool/lib/report/variantsView.mjs | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 6++++++
47 files changed, 2904 insertions(+), 23 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -196,7 +196,9 @@ beside the report's `report.json` (never published) or beside the project's anchor resolved and the **source** file to edit — a draft, not the generated `report.json` or manifest. Act, regenerate, then `umtool notes reply <id> "<what changed>" --resolve`. Never hand-edit `notes.json`. See -[umtool/docs/notes.md](umtool/docs/notes.md). +[umtool/docs/notes.md](umtool/docs/notes.md). Every report-video knob a person sets in umtool (a stamp's moment and +count, a clip's sync, markers, the encode ladder) an agent sets with `umtool set` / `umtool look` / `umtool variants`: +[umtool/docs/knobs.md](umtool/docs/knobs.md). # The runtime container diff --git a/plans/video-knobs-ui.md b/plans/video-knobs-ui.md @@ -0,0 +1,67 @@ +# Video knobs — the surfaces (lane `lane/knobs-ui`, K2) + +Asked by the operator on 2026-10-22 on the Huck seizure video: "Do we have the ability to adjust the point where +the count increments / the stamp appears per clip?", "Make quality variants … I'll want to share higher quality +ones elsewhere", and "Add any knobs you can think of, I want to allow for deep human involvement as well as AI +control for these videos." The plan (both lanes): the job's `video-knobs-plan.md`. The renderer side is +`lane/knobs-core` (K1, `plans/video-knobs-core.md`); this lane is the writers, routes, UI, CLI and agent control. +K1 merged first; this lane is rebased on it. + +## What shipped + +Every knob is a field or button in umtool and a `umtool` command, through one writer each. Absent keys are the +defaults; a knob set to its default is removed. The reference for people and agents is `umtool/docs/knobs.md`. + +| Knob | UI | CLI | Route | Writer | +|---|---|---|---|---| +| `claim.at` | clip editor, Count & stamp: **Set at playhead** (Shift+S) | `umtool set <p> <clip> claim.at=S` | `POST /api/report/clip-editor {op: "claim"}` | `updateClaimKnobs` | +| `claim.hold` / `stamp` / `count` / `label` | Count & stamp fields, Clear | `claim.hold=` … | same | same | +| `audio.offset` / `gain` / `fadeIn` / `fadeOut` | clip editor, Audio (nudges ±10/±40 ms, **listen** = 3 s around the playhead), Clear all | `umtool set <p> <clip> audio.offset=-40` | `POST /api/report/clip-editor {op: "audio"}` | `updateClip` (`audio`) | +| `factcheck.stamp.scale` / `motion` / `opacity` | Structure → fact-check labels | `umtool look <p> factcheck.stamp.scale=1.3` | `POST /api/report/timeline {op: "factcheck"}` | `updateFactcheck` | +| `factcheck.verdicts[V].stampLabel` | fact-check labels, third column | `factcheck.verdicts.V.stampLabel=…` | same | same | +| `deck.markers[]` (`align`), `deck.markerLayout` | On-screen → **markers** (add, clip picker, label ≤ 24, colour, align, ↑ ↓, remove, layout; ≤ 12) | `umtool look <p> deck.markers=<json> deck.markerLayout=…` | `PUT /api/report/chrome {markers, markerLayout}` | `updateDeckMarkers` (structural: snapshotted) | +| `render.variants` | Deliver → Variants and sync: Edit / Save ladder / Use the default | `umtool look <p> variants=<json>` | `PUT /api/report/render {variants}` | `updateVariants` | +| Make variants | Deliver → **Make variants** (project build or a take's) | `umtool variants <p> [--take t]` | `POST /api/report/deliver {action: "variants", take?}` (a job) | driver `variantsSteps` → `node report-to-video/variants.mjs <out>` | +| variants list, Sync table | Deliver: the list (size, frame, kb/s, open), sync rows (lag, flagged > 1 frame, link to the clip's Audio box) | `umtool variants <p> --list [--json]` | `GET /api/report/variants?project[&take][&file=<name>]` | `variantsView.mjs` | +| `layout` (`finale` \| `clip`) on a clip | — (the finale editor is lane/deck-finale's) | `umtool set <p> <clip> layout=finale` | — | `updateClip` (`layout`) | +| any `render.chrome.deck.<key>` as JSON | — | `umtool look <p> deck.<key>=<json>` | — | `updateDeckKeys` (structural; validateChrome) | +| all of the above, read | — | `umtool show <p>` (**knobs** block; `--json`: `knobs`) | — | `knobsCli.mjs knobsOf` | + +Rulings: + +- Every manifest-write route (`build`, `chrome`, `claim`, `clip-editor`, `cut`, `deliver`, `drafts`, `hand-fill`, + `narration`, `onscreen`, `posts`, `render`, `timeline`, `video-assist`, `window`) takes the page (no header) or + `Bearer <WORKER_TOKEN>`; any other header is 401 (`lib/report/caller.ts`, routeCaller's rule). +- The Count & stamp key is **Shift+S**: S alone stays Split here. +- `claim.at` must lie in the clip's window (`start`–`end`); a window save that would leave it outside is refused. + The box warns when it is outside the cut. +- A claim's knobs are read from the clip that stamps it (the last carrying the id); the box on another clip names it. +- The On-screen table's claim rows keep the knobs while the claim id is unchanged; a row naming knobs replaces them. +- `audio`: merged per key, a 0 or null removes a key, nothing left removes `audio`; offset rounded to the ms, + gain to 0.1 dB, fades to 0.01 s. +- The rules are the renderer's (factcheck.mjs `normalizeClaim`/`validateClaims`/`validateFactcheck`, deck.mjs + `validateChrome`/`validateDeckMarkers`, clip-audio.mjs `validateClipAudio`, variants.mjs `validateVariants`); + `lib/report/knobs.mjs` only reads a typed patch ("12.4", "false", "") into its value, drops a knob at its + default, and names the entry that stamps. +- Sync: a lag past one frame (1000 / fps ms) is flagged; the file is the build's `<out>/sourced/sync.json`. +- The On-screen preview's deck layout is asked with the schedule, so a staggered marker band matches the page; the + Count & stamp box says a new `at` previews approximately until the next build. + +Built on main after lane/knobs-core merged (44c31791): this lane ships no copy of the renderer's modules. + +## Files + +- `umtool/lib/report/knobs.mjs` (+ `knobs.test.mjs`), `knobsCli.mjs` (+ `knobsCli.test.mjs`), `variantsView.mjs`, + `caller.ts`; `manifest.mjs` (`updateClaimKnobs`, `updateDeckMarkers`, `updateVariants`, `normalizeMarkers`, + `updateClip` audio and the `claim.at` window rule, `updateOnscreen` knob carry, knob-aware validation); + `clipEditor.mjs` (ops `claim`, `audio`; the view's `claim`, `stampsOn`, `audio`, `knobs`), `clipEditorTypes.ts`; + `driver.mjs` (`variantsSteps`). +- Routes: `app/api/report/variants/route.ts` (new); `chrome`, `render`, `deliver`, `timeline`, `clip-editor`, + `still`, `chrome/preview` and the guard on every write route above. +- UI: `components/projects/review/ClipKnobs.tsx` (Count & stamp, Audio) in `ClipEditor.tsx`; + `components/projects/MarkersEditor.tsx` in `OnscreenSection.tsx`; `StructureEditors.tsx` (FactcheckEditor); + `components/projects/report/VariantsPanel.tsx` in `DeliverTab.tsx`. +- CLI: `umtool/bin/umtool.mjs` (`set`, `look`, `variants`, `show`'s knobs). +- e2e: `e2e/knobs.spec.ts`, `e2e/fixtures/knobs-fixture.mjs`, `e2e/fixtures/variants.e2e.mjs` + (`E2E_UMTOOL_VARIANTS_SCRIPT` in `playwright.config.ts`). +- Docs: `umtool/docs/knobs.md` (new); pointers in `notes.md`, `report-video.md`, `cli.md`, `AGENTS.md`. diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -6,6 +6,7 @@ import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; import { projectRef } from "@/lib/projects"; import { recordBuildSnapshot } from "@/lib/report/snapshots.mjs"; import { DEFAULT_VARIANT, VARIANTS, variantPaths } from "umtool-report-to-video/build-video"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -49,6 +50,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/build"); + if (refused) return refused; const url = new URL(request.url); const dry = url.searchParams.get("dry") === "1"; const replace = url.searchParams.get("replace") === "1"; diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts @@ -149,7 +149,8 @@ export async function POST(request: Request) { geometry: deckGeometry(render), // The ground a footage moved aside for the posts (schedule.moves) leaves showing. background: typeof (render.palette as { bg?: unknown } | undefined)?.bg === "string" ? (render.palette as { bg: string }).bg : null, - layout: deckLayout(render, { tally: tallyOf(schedule, render) }), + // With the schedule: a staggered marker band (deck.markerLayout) is a second row deep. + layout: deckLayout(render, { tally: tallyOf(schedule, render), schedule }), schedule, posts: { geometry: postsGeometry(render), diff --git a/umtool/app/api/report/chrome/route.ts b/umtool/app/api/report/chrome/route.ts @@ -1,7 +1,10 @@ import { withEditNotes } from "@/lib/report/guard"; -import { ChromeRefused, StaleToken, manifestToken, updateChrome } from "@/lib/report/manifest.mjs"; +import { ChromeRefused, StaleToken, StructureRefused, manifestToken, updateChrome, updateDeckMarkers } from "@/lib/report/manifest.mjs"; +import { MARKER_ALIGNS, MARKER_LAYOUTS } from "@/lib/report/knobs.mjs"; +import { invalidateProjects } from "@/lib/projects"; import { resolveReport } from "@/lib/report/serve.mjs"; import { DECK_DEFAULTS, deckOn, resolveDeck, validateChrome } from "umtool-report-to-video/deck"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -12,6 +15,11 @@ export const dynamic = "force-dynamic"; // sends a path. Validation is deck.mjs's validateChrome, run by the writer, so // a block this route accepts is one the build accepts; a refusal comes back // as the same sentences the build would print, one per problem. +// +// PUT { project, token, markers?, markerLayout? } (no `chrome`) sets only the +// deck's markers and/or their layout (video knobs: the Markers editor, `umtool +// look deck.markers=…`), leaving the rest of the deck as it is -- a +// structural edit, snapshotted first (lib/report/manifest.mjs updateDeckMarkers). type Body = Record<string, unknown>; @@ -33,6 +41,9 @@ export async function GET(request: Request) { // A block somebody hand-edited into a state the build would refuse. The // form shows these rather than pretending the saved settings are fine. errors: chrome ? validateChrome(chrome, rest) : [], + // The Markers editor's choices (video knobs). + markerAligns: MARKER_ALIGNS, + markerLayouts: MARKER_LAYOUTS, token: await manifestToken(r.project.dir), }, { headers: noStore }, @@ -40,12 +51,15 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/chrome"); + if (refused) return refused; let body: Body; try { body = await request.json(); } catch { return Response.json({ error: "expected JSON" }, { status: 400 }); } + if (!("chrome" in body) && ("markers" in body || "markerLayout" in body)) return putMarkers(body); if (!("chrome" in body)) { return Response.json({ error: "chrome is required — an object, or null to turn the deck off" }, { status: 400 }); } @@ -82,3 +96,26 @@ export async function PUT(request: Request) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); } } + +/** The Markers editor's save: `deck.markers` and/or `deck.markerLayout`, nothing else. */ +async function putMarkers(body: Body) { + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const patch: { markers?: unknown[] | null; markerLayout?: string | null } = {}; + if ("markers" in body) patch.markers = (body.markers ?? null) as unknown[] | null; + if ("markerLayout" in body) patch.markerLayout = (body.markerLayout ?? null) as string | null; + try { + const { result: res, editNotes } = await withEditNotes(r.project, () => + updateDeckMarkers(r.project.dir, patch, { token: typeof body.token === "string" ? body.token : null }), + ); + // revisions/ changed: the project page lists them. + invalidateProjects(); + return Response.json({ ok: true, ...res, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) { + return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); + } + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/claim/route.ts b/umtool/app/api/report/claim/route.ts @@ -2,6 +2,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, manifestToken, updateClaim } from "@/lib/report/manifest.mjs"; import { resolveClaim } from "@/lib/report/serve.mjs"; import { readClaimDetail } from "@/lib/projects/report.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -35,6 +36,8 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/claim"); + if (refused) return refused; const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; const projectId = String(body.project ?? ""); const claimId = String(body.claim ?? ""); diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts @@ -1,6 +1,7 @@ import { projectRef } from "@/lib/projects"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { OpError, StaleToken, StructureRefused, clipEditorView, clipNeighbourhood, runClipEditorOp } from "@/lib/report/clipEditor.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -46,6 +47,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/clip-editor"); + if (refused) return refused; 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 editorProject(body.project); diff --git a/umtool/app/api/report/cut/route.ts b/umtool/app/api/report/cut/route.ts @@ -4,6 +4,7 @@ import { cleanRespellings } from "yt-dlp-transcript-common/lib/citations/respell import { cuesInWindow } from "@/lib/projects/report.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; import { cutToQuote } from "umtool-report-to-video/resolve-windows"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -22,6 +23,8 @@ export const dynamic = "force-dynamic"; const LOOK = 30; export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/cut"); + if (refused) return refused; const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; const projectId = String(body.project ?? ""); const clipId = String(body.clip ?? ""); diff --git a/umtool/app/api/report/deliver/route.ts b/umtool/app/api/report/deliver/route.ts @@ -5,12 +5,17 @@ import { moveDeliverablesSteps, rebuildReportSteps, shareBatchSteps, + variantsSteps, } from "@/lib/report/driver.mjs"; import { SHARE_PREFIX, deliverStateOf } from "@/lib/report/deliver.mjs"; import { deliverablesProblems, isDeliverableName } from "@/lib/report/storage.mjs"; import { readClipDetail } from "@/lib/projects/report.mjs"; import { projectRef } from "@/lib/projects"; import type { Step } from "@/lib/trim"; +import { refuseCaller } from "@/lib/report/caller"; +import { outDirOf, variantsState } from "@/lib/report/variantsView.mjs"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; export const dynamic = "force-dynamic"; @@ -24,6 +29,9 @@ export const dynamic = "force-dynamic"; // move the deliverables (clips/, every share-*) to the media root or // back, then the manifest's storage.deliverables (release 17) -- // a job like the others, so nothing cuts or shares while it moves +// variants (a report video, video knobs) the build's encode ladder, +// render.variants -- `{ action: "variants", take? }`; read back +// through /api/report/variants // // Each is a JOB, and jobs.ts allows exactly one at a time. That is not a // limitation to work around here: every one of these reads or writes the same @@ -74,6 +82,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/deliver"); + if (refused) return refused; const url = new URL(request.url); const cancel = url.searchParams.get("cancel"); // Stop ABANDONS THE REST, it does not undo what finished. Every artefact @@ -82,6 +92,9 @@ export async function POST(request: Request) { if (cancel) return Response.json({ cancelled: cancelJob(cancel) }); const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; + // Make variants (video knobs): a report video's built cut, or a take's, in + // the ladder render.variants names. No walk state is read for it. + if (body.action === "variants") return startVariants(body); const action = String(body.action ?? "") as Action; if (!ACTIONS.includes(action)) { return Response.json({ error: `action must be one of ${ACTIONS.join(", ")}` }, { status: 400 }); @@ -205,3 +218,36 @@ export async function POST(request: Request) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); } } + +/** + * `action: "variants"`, `take?`: the encode ladder of the project's build (or + * of that take's), as one job (driver.mjs variantsSteps; the encoder takes the + * heavy slot). Refused with no build to encode, or while another job runs. + */ +async function startVariants(body: Record<string, unknown>) { + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "variants are made of a report video's build" }, { status: 400 }); + const manifest = await readManifest(project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400 }); + const take = typeof body.take === "string" && body.take ? body.take : null; + let state: Awaited<ReturnType<typeof variantsState>>; + try { + state = await variantsState(project, manifest, take); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + if (!state.built) { + return Response.json({ error: take ? `take ${take} has no build to make variants of` : "this cut has not been built yet — build it first" }, { status: 409 }); + } + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + try { + const job = startJob(`variants ${project.id}${take ? ` (take ${take})` : ""}`, variantsSteps(project, outDirOf(project, take)), { project: project.id }); + return Response.json({ ok: true, action: "variants", take, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/app/api/report/drafts/route.ts b/umtool/app/api/report/drafts/route.ts @@ -6,6 +6,7 @@ import { currentFieldValue, valueFromEdit } from "@/lib/report/draftEdit.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { draftsReviewRows, readDraftsReview, setDraftReview } from "umtool-report-to-video/drafts-review"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -41,6 +42,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/drafts"); + if (refused) return refused; let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/hand-fill/route.ts b/umtool/app/api/report/hand-fill/route.ts @@ -5,6 +5,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { MANIFEST_NAME, StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; import { applyHandFill, handFillView } from "@/lib/report/hand-fill.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -31,6 +32,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/hand-fill"); + if (refused) return refused; const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; if (!body) return Response.json({ error: "expected JSON" }, { status: 400, headers: noStore }); const r = await resolveReport(String(body.project ?? "")); diff --git a/umtool/app/api/report/narration/route.ts b/umtool/app/api/report/narration/route.ts @@ -5,6 +5,7 @@ import { narrationReviewView } from "@/lib/report/narration-review.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { narrationsOf } from "umtool-report-to-video/narration"; import { setNarrationReview } from "umtool-report-to-video/narration-review"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -41,6 +42,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/narration"); + if (refused) return refused; let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/onscreen/route.ts b/umtool/app/api/report/onscreen/route.ts @@ -3,6 +3,7 @@ import { StaleToken, manifestToken, updateOnscreen } from "@/lib/report/manifest import { postRows, scheduleForPreview } from "@/lib/report/onscreen.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { deckText, isMultiChannel, resolveDeck } from "umtool-report-to-video/deck"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -76,6 +77,8 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/onscreen"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/app/api/report/posts/route.ts b/umtool/app/api/report/posts/route.ts @@ -1,6 +1,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { PostsRefused, StaleToken, updatePosts } from "@/lib/report/manifest.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -18,6 +19,8 @@ export const dynamic = "force-dynamic"; const noStore = { "cache-control": "no-store" }; export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/posts"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts @@ -1,9 +1,11 @@ import { withEditNotes } from "@/lib/report/guard"; -import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender } from "@/lib/report/manifest.mjs"; +import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender, updateVariants } from "@/lib/report/manifest.mjs"; +import { VARIANTS_DEFAULT, variantsProblems } from "@/lib/report/knobs.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { deckOn } from "umtool-report-to-video/deck"; import { validateLook } from "umtool-report-to-video/look"; import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -16,6 +18,8 @@ export const dynamic = "force-dynamic"; // // GET ?project=<id> { look, deck, montage, styles, keys, errors, token } // PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors } +// PUT { project, token, variants } render.variants, the ladder Make variants encodes +// (null: the default ladder) → { ok, variants, token } const noStore = { "cache-control": "no-store" }; @@ -32,7 +36,10 @@ export async function GET(request: Request) { styles: TRANSITION_STYLES, keys: LOOK_KEYS, // A look somebody hand-edited into a state the build would refuse. - errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest)], + errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest), ...variantsProblems(render.variants)], + // The encode ladder (video knobs): as written, and the default when it is absent. + variants: render.variants ?? null, + variantsDefault: VARIANTS_DEFAULT, token: await manifestToken(r.project.dir), }, { headers: noStore }, @@ -40,6 +47,8 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/render"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); @@ -48,6 +57,20 @@ export async function PUT(request: Request) { } const r = await resolveReport(String(body.project ?? "")); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + if ("variants" in body && !("patch" in body)) { + try { + const { result: res, editNotes } = await withEditNotes(r.project, () => + updateVariants(r.project.dir, (body.variants ?? null) as unknown[] | null, { + token: body.token === undefined || body.token === null ? null : String(body.token), + }), + ); + return Response.json({ ok: true, variants: res.variants, token: res.token, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); + if (e instanceof RenderRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + } try { const { result: res, editNotes } = await withEditNotes(r.project, () => updateRender(r.project.dir, (body.patch ?? null) as Record<string, unknown>, { diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -17,6 +17,8 @@ import { import { resolveReport } from "@/lib/report/serve.mjs"; import { deckOn } from "umtool-report-to-video/deck"; import { VERDICTS, resolveFactcheck } from "umtool-report-to-video/factcheck"; +import { STAMP_KNOB_DEFAULTS, STAMP_KNOB_LIMITS, STAMP_MOTIONS } from "@/lib/report/knobs.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -66,6 +68,8 @@ export async function GET(request: Request) { deckOn: deckOn(render), factcheck: (render.chrome as { factcheck?: unknown } | undefined)?.factcheck ?? null, factcheckResolved: resolveFactcheck(render), + // The stamp's knobs (video knobs): their defaults, bounds and motions, the form's placeholders. + stampKnobs: { defaults: STAMP_KNOB_DEFAULTS, limits: STAMP_KNOB_LIMITS, motions: STAMP_MOTIONS }, verdicts: VERDICTS, generatedBy: r.manifest.generatedBy ?? null, token: await manifestToken(r.project.dir), @@ -77,6 +81,8 @@ export async function GET(request: Request) { const atOf = (v: unknown) => (v === undefined || v === null || v === "" ? null : Number(v)); export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/timeline"); + if (refused) return refused; let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/variants/route.ts b/umtool/app/api/report/variants/route.ts @@ -0,0 +1,46 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; +import { variantFile, variantsState } from "@/lib/report/variantsView.mjs"; + +export const dynamic = "force-dynamic"; + +// MAKE VARIANTS and SYNC, read back (video knobs, plans/video-knobs-ui.md). +// "Make variants" itself is a job: POST /api/report/deliver +// { action: "variants", take? }. +// +// GET ?project=<id>[&take=<id>] { take, slug, built, ladder, made, stale, sync, takes } +// GET ?project=<id>[&take=<id>]&file=<name> that variant's mp4 (a name from the ladder, never a path) + +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers: noStore }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "variants are a report video's" }, { status: 400, headers: noStore }); + const manifest = await readManifest(project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers: noStore }); + const take = url.searchParams.get("take") || null; + const name = url.searchParams.get("file"); + try { + if (name !== null) { + const f = await variantFile(project, manifest, name, take); + if (!f) return new Response("that variant has not been made", { status: 404 }); + return rangeResponse(request, { + abs: f.abs, + size: f.size, + headers: { + "content-type": "video/mp4", + "accept-ranges": "bytes", + "cache-control": "private, no-store", + "content-disposition": `inline; filename="${f.rel}"`, + }, + }); + } + return Response.json(await variantsState(project, manifest, take), { headers: noStore }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers: noStore }); + } +} diff --git a/umtool/app/api/report/video-assist/route.ts b/umtool/app/api/report/video-assist/route.ts @@ -16,6 +16,7 @@ import { readAssistJob, writeAssistJob, } from "@/lib/report/videoAssist.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -94,6 +95,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/video-assist"); + if (refused) return refused; const url = new URL(request.url); const cancel = url.searchParams.get("cancel"); if (cancel) { diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -1,6 +1,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, updateClip } from "@/lib/report/manifest.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -15,6 +16,8 @@ export const dynamic = "force-dynamic"; // writer is usually `resolve-windows --write` or an agent running `umtool`, and // what it wrote is somebody's judgement. export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/window"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -23,6 +23,11 @@ // [--title T] [--date YYYY-MM-DD] [--cite S] [--cite-url U] [--quote Q] // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent +// umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label, +// audio.offset|gain|fadeIn|fadeOut (`key=` clears) (docs/knobs.md) +// umtool look <project> key=value … the cut's knobs: factcheck.stamp.*, factcheck.verdicts.<V>.*, +// deck.markers=<json>, deck.markerLayout, variants=<json>, the look's keys +// umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder; the sync report // umtool corrections <project> what the report got wrong, as markdown for the next pass // umtool build <project> [--preset preview|fast|final] [--only ID] [--dry] // [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels @@ -229,7 +234,8 @@ async function cmdShow() { if (json) { const src = detail ? await sourcesOf(p.dir, { manifest: detail.manifest }) : null; const snapshots = detail ? await listSnapshots(p.dir) : null; - return out({ ...s, decisions: ds, entries: detail?.entries ?? null, sources: src?.rows ?? null, snapshots }); + const knobs = detail ? (await import("../lib/report/knobsCli.mjs")).knobsOf(detail.manifest) : null; + return out({ ...s, decisions: ds, entries: detail?.entries ?? null, sources: src?.rows ?? null, snapshots, knobs }); } console.log(`${s.title}`); @@ -294,6 +300,10 @@ async function cmdShow() { ].filter(Boolean); console.log(` ${r.key.padEnd(w)} ${r.clips.join(",").padEnd(12)} ${marks.join(" · ")}`); } + // The video knobs (umtool set / umtool look): what this cut sets beyond the defaults. + const { knobsLines } = await import("../lib/report/knobsCli.mjs"); + console.log(`\nknobs:`); + for (const line of knobsLines(detail.manifest)) console.log(line); const snaps = await listSnapshots(p.dir); if (snaps.length) { console.log(`\nsnapshots (${snaps.length}):`); @@ -698,6 +708,14 @@ function usage() { " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --cut-start S --cut-end E --lock-cut the cut the video renders", " an empty value (--title '') deletes the field", + " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):", + " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp", + " claim.count claim.label · audio.offset (ms, + later) audio.gain (dB) audio.fadeIn audio.fadeOut", + " umtool look <project> key=value … the cut's knobs: factcheck.stamp.scale|motion|opacity|seconds,", + " factcheck.verdicts.<V>.stampLabel|label|color, deck.markers=<json>, deck.markerLayout,", + " variants=<json>, and the look's keys (transition=0.3, …)", + " umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (render.variants);", + " --list: what was made, and the build's sync report (each clip's lag, past a frame flagged)", " umtool corrections <project> what the report got wrong + the walk's coverage", " umtool build <project> [--preset preview|fast|final] [--only ID]", " --run: the app's build job (UMTOOL_URL, else http://localhost:3050; --url), followed here;", @@ -770,6 +788,10 @@ function usage() { const COMMANDS = { ls: cmdLs, window: cmdWindow, + // The video knobs (plans/video-knobs-ui.md): lib/report/knobsCli.mjs. + set: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).setCommand(argv.slice(argv.indexOf("set") + 1))), + look: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).lookCommand(argv.slice(argv.indexOf("look") + 1))), + variants: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).variantsCommand(argv.slice(argv.indexOf("variants") + 1))), corrections: cmdCorrections, build: cmdBuild, chain: cmdChain, diff --git a/umtool/components/projects/MarkersEditor.tsx b/umtool/components/projects/MarkersEditor.tsx @@ -0,0 +1,188 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// THE DECK'S MARKERS (video knobs, plans/video-knobs-ui.md): the flags on the +// pip track, `render.chrome.deck.markers` -- each after a clip (a picker of the +// cut's clips), a label of at most 24 characters, a colour (a palette key or +// #hex), an alignment -- at most 12, added, removed and re-ordered here; and +// `deck.markerLayout`, what the deck does when labels crowd: stagger them on a +// second row, or truncate. One save writes the list and the layout and nothing +// else of the deck (PUT /api/report/chrome { markers, markerLayout }), the +// writer `umtool look deck.markers=…` uses. + +export type Marker = { after: string; label: string; color?: string; align?: string }; +type Row = { after: string; label: string; color: string; align: string }; + +export const MARKER_MAX = 12; +export const MARKER_LABEL_MAX = 24; +const PALETTE = ["amber", "accent", "fg", "muted", "dim"]; + +const input = + "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"; + +const rowOf = (m: Marker): Row => ({ after: m.after, label: m.label, color: m.color ?? "", align: m.align ?? "auto" }); +const markerOf = (r: Row): Marker => ({ + after: r.after, + label: r.label.trim(), + ...(r.color.trim() ? { color: r.color.trim() } : {}), + ...(r.align && r.align !== "auto" ? { align: r.align } : {}), +}); + +export default function MarkersEditor({ + markers, + markerLayout, + clips, + aligns, + layouts, + busy, + save, +}: { + markers: Marker[]; + markerLayout: string | null; + clips: { id: string; label: string }[]; + aligns: string[]; + layouts: string[]; + busy: boolean; + save: (patch: { markers: Marker[]; markerLayout: string | null }) => Promise<boolean>; +}) { + const savedKey = JSON.stringify([markers, markerLayout]); + const [rows, setRows] = useState<Row[]>(() => markers.map(rowOf)); + const [layout, setLayout] = useState(markerLayout ?? ""); + const [dirty, setDirty] = useState(false); + useEffect(() => { + setRows(markers.map(rowOf)); + setLayout(markerLayout ?? ""); + setDirty(false); + // The saved value, by its text: a re-read with the same markers keeps the edits. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [savedKey]); + + const change = (next: Row[]) => { + setRows(next); + setDirty(true); + }; + const put = (i: number, patch: Partial<Row>) => change(rows.map((r, j) => (j === i ? { ...r, ...patch } : r))); + const move = (i: number, d: number) => { + const j = i + d; + if (j < 0 || j >= rows.length) return; + const next = [...rows]; + [next[i], next[j]] = [next[j], next[i]]; + change(next); + }; + const add = () => { + const used = new Set(rows.map((r) => r.after)); + const after = clips.find((c) => !used.has(c.id))?.id ?? clips[0]?.id ?? ""; + change([...rows, { after, label: "", color: "", align: "auto" }]); + }; + const labelLong = rows.some((r) => [...r.label.trim()].length > MARKER_LABEL_MAX); + + return ( + <div data-testid="markers-editor" className="space-y-1.5"> + <div className="flex flex-wrap items-center gap-2"> + <span className="micro">markers</span> + <span className="text-[11px] text-[var(--color-dim)]"> + {rows.length} of {MARKER_MAX} + </span> + {dirty && <span className="text-[11px] text-[var(--color-dirty)]">unsaved</span>} + <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title="when labels crowd: stagger puts every other one on a second row (truncating only if that still collides); truncate shortens them in place"> + layout + <select + data-testid="markers-layout" + value={layout} + onChange={(e) => { + setLayout(e.target.value); + setDirty(true); + }} + className={input} + > + <option value="">default (stagger when a label would truncate)</option> + {layouts.map((l) => ( + <option key={l} value={l}> + {l} + </option> + ))} + </select> + </label> + <button type="button" data-testid="markers-add" disabled={busy || rows.length >= MARKER_MAX || !clips.length} onClick={add} className={buttonVariants({ size: "sm" })}> + add a marker + </button> + <button + type="button" + data-testid="markers-save" + disabled={busy || !dirty || labelLong || rows.some((r) => !r.label.trim() || !r.after)} + onClick={() => void save({ markers: rows.map(markerOf), markerLayout: layout || null }).then((ok) => ok && setDirty(false))} + className={`${buttonVariants({ variant: "outline", size: "sm" })} ml-auto`} + > + save markers + </button> + </div> + {rows.length === 0 ? ( + <p className="text-[11px] text-[var(--color-dim)]">No markers: the pip track has no flags.</p> + ) : ( + <ol className="m-0 list-none space-y-1 p-0"> + {rows.map((r, i) => { + const n = [...r.label.trim()].length; + return ( + <li key={i} data-testid={`marker-row-${i}`} className="flex flex-wrap items-center gap-1.5 text-[11px] text-[var(--color-dim)]"> + <span className="num w-4 text-right font-mono">{i + 1}</span> + <label className="flex items-center gap-1"> + after + <select data-testid={`marker-after-${i}`} value={r.after} onChange={(e) => put(i, { after: e.target.value })} className={`${input} max-w-[16em]`}> + {!clips.some((c) => c.id === r.after) && <option value={r.after}>{r.after || "(pick a clip)"}</option>} + {clips.map((c) => ( + <option key={c.id} value={c.id}> + {c.id} — {c.label} + </option> + ))} + </select> + </label> + <input + data-testid={`marker-label-${i}`} + value={r.label} + placeholder="label" + onChange={(e) => put(i, { label: e.target.value })} + className={`${input} w-44`} + /> + <span className={`num font-mono ${n > MARKER_LABEL_MAX ? "text-[var(--color-bad)]" : ""}`}> + {n}/{MARKER_LABEL_MAX} + </span> + <input + data-testid={`marker-color-${i}`} + list="marker-palette" + value={r.color} + placeholder="amber" + title="a palette key (amber, accent, fg, muted, dim) or #hex" + onChange={(e) => put(i, { color: e.target.value })} + className={`${input} w-20 font-mono`} + /> + <select data-testid={`marker-align-${i}`} value={r.align} onChange={(e) => put(i, { align: e.target.value })} className={input} title="where the label sits against its flag"> + {aligns.map((a) => ( + <option key={a} value={a}> + {a} + </option> + ))} + </select> + <button type="button" data-testid={`marker-up-${i}`} disabled={i === 0} onClick={() => move(i, -1)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="move up"> + ↑ + </button> + <button type="button" data-testid={`marker-down-${i}`} disabled={i === rows.length - 1} onClick={() => move(i, 1)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="move down"> + ↓ + </button> + <button type="button" data-testid={`marker-remove-${i}`} onClick={() => change(rows.filter((_, j) => j !== i))} className={buttonVariants({ variant: "quiet", size: "sm" })}> + remove + </button> + </li> + ); + })} + </ol> + )} + <datalist id="marker-palette"> + {PALETTE.map((p) => ( + <option key={p} value={p} /> + ))} + </datalist> + </div> + ); +} diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -3,6 +3,7 @@ import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { TimedVideo } from "@/components/notes/TimedNotes"; import StructureEditors from "./StructureEditors"; +import MarkersEditor, { type Marker } from "./MarkersEditor"; import { MANIFEST_CHANGED } from "./timelineApi"; import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts"; import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider"; @@ -540,8 +541,10 @@ type DeckSettings = { shift: false | { scale: number; seconds: number }; qr: boolean; }; - /** Flags on the pip track (`deck.markers`): written in the manifest, carried through every save here. */ - markers?: { after: string; label: string; color?: string }[]; + /** Flags on the pip track (`deck.markers`): the Markers editor's; carried through every settings save. */ + markers?: { after: string; label: string; color?: string; align?: string }[]; + /** What the deck does when marker labels crowd (`deck.markerLayout`): the Markers editor's. */ + markerLayout?: string; }; /** `when`: the bool field that must be on for this one to apply (and be shown). */ @@ -705,6 +708,9 @@ type ChromeDoc = { deck: DeckSettings | null; defaults: DeckSettings; errors: string[]; + /** The Markers editor's choices (video knobs). */ + markerAligns?: string[]; + markerLayouts?: string[]; token: string | null; }; type Row = { @@ -1042,6 +1048,41 @@ export default function OnscreenSection({ [project, queued], ); + /** The Markers editor's save: `deck.markers` and `deck.markerLayout`, nothing else of the deck. */ + const putMarkers = useCallback( + (patch: { markers: Marker[]; markerLayout: string | null }) => + queued(async () => { + setBusy("saving…"); + setNote(null); + const r = await fetch("/api/report/chrome", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, ...patch, token: token.current }), + }); + const j = (await r.json()) as Record<string, unknown>; + if (wroteNotes(j)) announceNotesChanged(project); + setBusy(null); + if (!r.ok) { + if (j.stale) { + setStale(true); + setNote(STALE); + } else { + setErrors((j.errors as string[]) ?? []); + setNote(`could not save the markers: ${String(j.error ?? r.status)}`); + } + return false; + } + token.current = String(j.token ?? ""); + setErrors([]); + setStale(false); + await loadChrome(); + await recompose(); + setNote(`saved ${patch.markers.length} marker${patch.markers.length === 1 ? "" : "s"}`); + return true; + }), + [project, queued, loadChrome, recompose], + ); + const toggle = useCallback( async (on: boolean) => { if (!doc) return; @@ -1090,13 +1131,15 @@ export default function OnscreenSection({ // Everything this form does not edit is the manifest's, carried through // as saved, never dropped by a deck save: the fact-check settings and the // other regions (threads, flips, stats, fx) beside the deck, and the - // deck's markers (`deck.markers`, written in the manifest). + // deck's markers and their layout (`deck.markers`, `deck.markerLayout`: + // the Markers editor's). const { engine: _e, layout: _l, deck: savedDeck, ...others } = doc.chrome ?? {}; const markers = (savedDeck as { markers?: unknown } | undefined)?.markers; + const markerLayout = (savedDeck as { markerLayout?: unknown } | undefined)?.markerLayout; const chrome = { engine: (doc.chrome?.engine as string) ?? "hyperframes", layout: (doc.chrome?.layout as string) ?? "deck", - deck: { ...deckOf(form, doc.defaults), ...(markers !== undefined ? { markers } : {}) }, + deck: { ...deckOf(form, doc.defaults), ...(markers !== undefined ? { markers } : {}), ...(markerLayout !== undefined ? { markerLayout } : {}) }, ...others, }; const ok = await putChrome(chrome); @@ -2103,6 +2146,16 @@ export default function OnscreenSection({ </p> </div> + <MarkersEditor + markers={((doc.chrome?.deck as { markers?: Marker[] } | undefined)?.markers ?? []) as Marker[]} + markerLayout={((doc.chrome?.deck as { markerLayout?: string } | undefined)?.markerLayout ?? null) as string | null} + clips={clips.map((c) => ({ id: c.id, label: c.label }))} + aligns={doc.markerAligns ?? ["auto", "left", "right", "center"]} + layouts={doc.markerLayouts ?? ["stagger", "truncate"]} + busy={!!busy} + save={putMarkers} + /> + <div className="space-y-1"> <span className="micro">the built video</span> {typeof finalV === "number" ? ( diff --git a/umtool/components/projects/StructureEditors.tsx b/umtool/components/projects/StructureEditors.tsx @@ -15,7 +15,7 @@ import { DraftAlternatives, DraftBadge, useDrafts, type DraftAct, type DraftsVie type Teaser = { at: number; id: string; lines: unknown[]; beat: number | null; dip: { fade: number; black: number } | null; tail: string | null; tailWait: number | null }; type Post = Record<string, unknown> & { id: string }; -type Verdict = { label: string; color: string }; +type Verdict = { label: string; color: string; stampLabel?: string }; type Doc = { teasers: Teaser[]; posts: Post[]; @@ -23,6 +23,8 @@ type Doc = { factcheck: { verdicts?: Record<string, Partial<Verdict>>; stamp?: Record<string, unknown>; tally?: Record<string, unknown> } | null; factcheckResolved: { verdicts: Record<string, Verdict>; stamp: { show: boolean; seconds: number; position: string }; tally: { show: boolean; position: string } }; verdicts: string[]; + /** The stamp's knobs (video knobs): defaults, bounds, the motions. */ + stampKnobs?: { defaults: { scale: number; motion: string; opacity: number }; limits: { scale: number[]; opacity: number[] }; motions: string[] }; token: string | null; }; @@ -258,9 +260,16 @@ function PostRow({ post, fresh = false, busy, save, remove }: { post: Post; fres function FactcheckEditor({ doc, busy, save }: { doc: Doc; busy: boolean; save: (f: Record<string, unknown> | null) => Promise<boolean> }) { const given = doc.factcheck ?? {}; - const [v, setV] = useState<Record<string, { label: string; color: string }>>(() => - Object.fromEntries(doc.verdicts.map((k) => [k, { label: String(given.verdicts?.[k]?.label ?? ""), color: String(given.verdicts?.[k]?.color ?? "") }])), + const [v, setV] = useState<Record<string, { label: string; color: string; stampLabel: string }>>(() => + Object.fromEntries( + doc.verdicts.map((k) => [k, { label: String(given.verdicts?.[k]?.label ?? ""), color: String(given.verdicts?.[k]?.color ?? ""), stampLabel: String(given.verdicts?.[k]?.stampLabel ?? "") }]), + ), ); + // The stamp's knobs (video knobs): its size, how it comes in, how solid it is. Blank = the default. + const sk = doc.stampKnobs; + const [scale, setScale] = useState(given.stamp?.scale == null ? "" : String(given.stamp.scale)); + const [motion, setMotion] = useState(given.stamp?.motion == null ? "" : String(given.stamp.motion)); + const [opacity, setOpacity] = useState(given.stamp?.opacity == null ? "" : String(given.stamp.opacity)); const [seconds, setSeconds] = useState(given.stamp?.seconds == null ? "" : String(given.stamp.seconds)); // `stamp.show`: off draws no stamp over the footage; the tally still counts. const [stampOn, setStampOn] = useState(given.stamp?.show !== false); @@ -270,6 +279,7 @@ function FactcheckEditor({ doc, busy, save }: { doc: Doc; busy: boolean; save: ( const one: Record<string, string> = {}; if (o.label.trim()) one.label = o.label.trim(); if (o.color.trim()) one.color = o.color.trim(); + if (o.stampLabel.trim()) one.stampLabel = o.stampLabel.trim(); if (Object.keys(one).length) verdicts[k] = one; } // Only what differs from the defaults is written, as the deck's settings are. @@ -281,6 +291,12 @@ function FactcheckEditor({ doc, busy, save }: { doc: Doc; busy: boolean; save: ( else delete stamp.seconds; if (stampOn) delete stamp.show; else stamp.show = false; + for (const [k, raw] of [["scale", scale], ["opacity", opacity]] as const) { + if (raw.trim()) stamp[k] = Number.isFinite(Number(raw)) ? Number(raw) : raw; + else delete stamp[k]; + } + if (motion) stamp.motion = motion; + else delete stamp.motion; if (Object.keys(stamp).length) out.stamp = stamp; else delete out.stamp; void save(Object.keys(out).length ? out : null); @@ -288,7 +304,7 @@ function FactcheckEditor({ doc, busy, save }: { doc: Doc; busy: boolean; save: ( return ( <div data-testid="factcheck-editor" className="space-y-1 rounded border border-[var(--color-line)] p-2 text-[11px]"> <div className="micro">fact-check labels</div> - <div className="grid grid-cols-[max-content_1fr_max-content] items-center gap-x-2 gap-y-1"> + <div className="grid grid-cols-[max-content_1fr_max-content_max-content] items-center gap-x-2 gap-y-1"> {doc.verdicts.map((k) => { const def = doc.factcheckResolved.verdicts[k]; return ( @@ -299,6 +315,15 @@ function FactcheckEditor({ doc, busy, save }: { doc: Doc; busy: boolean; save: ( <input data-testid={`fc-color-${k}`} placeholder={def?.color} value={v[k]?.color ?? ""} onChange={(e) => setV((x) => ({ ...x, [k]: { ...x[k], color: e.target.value } }))} className={`${input} w-20 font-mono`} /> <span className="inline-block h-3 w-3 rounded" style={{ background: v[k]?.color || def?.color }} /> </span> + <input + data-testid={`fc-stamp-label-${k}`} + title="the stamp's word for this verdict (singular, e.g. SEIZURE); blank: the label" + placeholder={v[k]?.label || def?.label} + maxLength={24} + value={v[k]?.stampLabel ?? ""} + onChange={(e) => setV((x) => ({ ...x, [k]: { ...x[k], stampLabel: e.target.value } }))} + className={`${input} w-28`} + /> </div> ); })} @@ -308,6 +333,23 @@ function FactcheckEditor({ doc, busy, save }: { doc: Doc; busy: boolean; save: ( <input type="checkbox" data-testid="fc-stamp-show" checked={stampOn} onChange={(e) => setStampOn(e.target.checked)} /> stamp effect </label> <label>stamp seconds <input value={seconds} placeholder={String(doc.factcheckResolved.stamp.seconds)} disabled={!stampOn} onChange={(e) => setSeconds(e.target.value)} className={`${input} w-14`} /></label> + <label title={sk ? `${sk.limits.scale[0]}–${sk.limits.scale[1]}` : undefined}> + scale <input data-testid="fc-stamp-scale" value={scale} placeholder={String(sk?.defaults.scale ?? 1)} disabled={!stampOn} onChange={(e) => setScale(e.target.value)} className={`${input} w-12`} /> + </label> + <label> + motion{" "} + <select data-testid="fc-stamp-motion" value={motion} disabled={!stampOn} onChange={(e) => setMotion(e.target.value)} className={input}> + <option value="">{sk?.defaults.motion ?? "slam"} (default)</option> + {(sk?.motions ?? []).map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + </label> + <label title={sk ? `${sk.limits.opacity[0]}–${sk.limits.opacity[1]}` : undefined}> + opacity <input data-testid="fc-stamp-opacity" value={opacity} placeholder={String(sk?.defaults.opacity ?? 1)} disabled={!stampOn} onChange={(e) => setOpacity(e.target.value)} className={`${input} w-12`} /> + </label> <button type="button" data-testid="fc-save" disabled={busy} onClick={submit} className={buttonVariants({ variant: "outline", size: "sm" })}> Save labels </button> diff --git a/umtool/components/projects/report/DeliverTab.tsx b/umtool/components/projects/report/DeliverTab.tsx @@ -4,6 +4,7 @@ import { podcastFor } from "@/lib/report/serve.mjs"; import DeliverSection from "../DeliverSection"; import PodcastExport from "../PodcastExport"; import ShortsList from "./ShortsList"; +import VariantsPanel from "./VariantsPanel"; import type { ReportTabProps } from "./shared"; // The Deliver tab: the deliver panel (cuts, share batches, rulings applied, @@ -33,6 +34,9 @@ export default async function DeliverTab({ project, detail }: ReportTabProps) { {/* --- the shorts: one clip each, 1080x1920 (release 36) ---------- */} <ShortsList project={project.id} /> + {/* --- variants and sync (video knobs): the encode ladder of a build, and its A/V sync report --- */} + <VariantsPanel project={project.id} /> + {/* --- exports --------------------------------------------------- */} <section data-exports="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> <h2 className="micro mb-1">export</h2> diff --git a/umtool/components/projects/report/VariantsPanel.tsx b/umtool/components/projects/report/VariantsPanel.tsx @@ -0,0 +1,286 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { Panel } from "@/components/ui/panel"; +import { fmtAgo, fmtBytes } from "@/lib/format"; +import { clipEditorHref } from "@/lib/hrefs"; + +// MAKE VARIANTS and SYNC (video knobs, plans/video-knobs-ui.md), on Deliver: +// +// the ladder render.variants -- each a name and a height + crf, or a size +// cap (maxMiB); `master` is the build itself. Absent: the +// default ladder. Saved through PUT /api/report/render. +// Make variants one job (POST /api/report/deliver { action: "variants", +// take? }), of the project's build or a take's; the encoder +// takes the heavy slot +// the list what variants.json says was made: size, frame, bitrate, a link +// Sync the build's sync report (<out>/sourced/sync.json): each +// clip's sound against its picture, a lag past one frame +// flagged, each linking to that clip's Audio box +// +// `umtool variants <project> [--take t]` and `umtool look <project> variants=…` +// do the same from a terminal. + +type Variant = { name: string; height?: number; crf?: number; maxMiB?: number; preset?: string }; +type Made = { name: string; width: number | null; height: number | null; bytes: number | null; kbps: number | null; exists: boolean; mtimeMs: number | null }; +type SyncItem = { id: string; start: number | null; lagMs: number | null; peak: number | null; flagged: boolean; clip: boolean }; +type State = { + take: string | null; + slug: string; + built: { size: number; mtimeMs: number } | null; + ladder: Variant[]; + ladderIsDefault: boolean; + ladderDefault: Variant[]; + made: { at: string | null; items: Made[] } | null; + stale: boolean; + sync: { fps: number | null; frameMs: number; items: SyncItem[] } | null; + takes: string[]; +}; +type Job = { id: string; state: string; error: string | null; kind?: string; log?: string[]; next?: number }; +type LadderRow = { name: string; height: string; crf: string; maxMiB: string; preset: string }; + +const input = + "num rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"; +const rowOf = (v: Variant): LadderRow => ({ name: v.name, height: v.height == null ? "" : String(v.height), crf: v.crf == null ? "" : String(v.crf), maxMiB: v.maxMiB == null ? "" : String(v.maxMiB), preset: v.preset ?? "" }); +const variantOf = (r: LadderRow): Variant => { + const n = (s: string) => (s.trim() === "" ? undefined : Number(s)); + const out: Variant = { name: r.name.trim() }; + for (const k of ["height", "crf", "maxMiB"] as const) { + const v = n(r[k]); + if (v !== undefined) out[k] = v; + } + if (r.preset.trim()) out.preset = r.preset.trim(); + return out; +}; +const what = (v: Variant) => + (v.name === "master" ? "the build as it is" : v.maxMiB ? `at most ${v.maxMiB} MiB${v.height ? `, up to ${v.height}p` : ""}` : `${v.height ? `${v.height}p` : "the build's height"}, crf ${v.crf ?? 23}`) + (v.preset ? ` · ${v.preset}` : ""); + +export default function VariantsPanel({ project }: { project: string }) { + const [take, setTake] = useState<string>(""); + const [state, setState] = useState<State | null>(null); + const [job, setJob] = useState<Job | null>(null); + const [log, setLog] = useState<string[]>([]); + const [error, setError] = useState<string | null>(null); + const [ladder, setLadder] = useState<LadderRow[] | null>(null); + + const q = `project=${encodeURIComponent(project)}${take ? `&take=${encodeURIComponent(take)}` : ""}`; + const load = useCallback(async () => { + const r = await fetch(`/api/report/variants?${q}`, { cache: "no-store" }); + const j = (await r.json()) as State & { error?: string }; + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + setState(j); + }, [q]); + useEffect(() => { + load().catch((e) => setError(e instanceof Error ? e.message : String(e))); + }, [load]); + useEffect(() => { + if (!job || job.state !== "running") return; + let since = 0; + const t = setInterval(async () => { + const r = await fetch(`/api/report/deliver?job=${job.id}&since=${since}`, { cache: "no-store" }).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as Job; + since = j.next ?? since; + if (j.log?.length) setLog((l) => [...l, ...(j.log ?? [])].slice(-40)); + if (j.state !== "running") { + setJob(j); + await load().catch(() => {}); + } + }, 1200); + return () => clearInterval(t); + }, [job, load]); + + const make = async () => { + setError(null); + setLog([]); + const r = await fetch("/api/report/deliver", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, action: "variants", ...(take ? { take } : {}) }) }); + const j = (await r.json().catch(() => ({}))) as { job?: Job; error?: string }; + if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`); + else setJob(j.job); + }; + const cancel = async () => { + if (job) await fetch(`/api/report/deliver?cancel=${job.id}`, { method: "POST" }).catch(() => null); + }; + const saveLadder = async (variants: Variant[] | null) => { + setError(null); + const t = (await (await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" })).json()) as { token?: string }; + const r = await fetch("/api/report/render", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token: t.token ?? null, variants }) }); + const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[] }; + if (!r.ok) { + setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${r.status}`); + return; + } + setLadder(null); + await load(); + }; + + const running = job?.state === "running"; + const file = (name: string) => `/api/report/variants?${q}&file=${encodeURIComponent(name)}`; + return ( + <Panel title="Variants and sync" data-variants-panel={state?.made?.items.length ?? 0}> + <div className="space-y-2 text-[12px] text-text-2"> + <div className="flex flex-wrap items-center gap-2"> + <label className="flex items-center gap-1"> + <span className="micro">of</span> + <select data-variants-take="" value={take} onChange={(e) => setTake(e.target.value)} className={input}> + <option value="">the project&rsquo;s build</option> + {(state?.takes ?? []).map((t) => ( + <option key={t} value={t}> + take {t} + </option> + ))} + </select> + </label> + <span className="num">{state?.built ? `${fmtBytes(state.built.size)} · built ${fmtAgo(state.built.mtimeMs)}` : state ? "not built yet" : "…"}</span> + <button type="button" data-variants-make="" disabled={!state?.built || running} onClick={() => void make()} className={`${buttonVariants({ variant: "go", size: "sm" })} ml-auto`}> + {running ? "Making variants…" : "Make variants"} + </button> + {running && ( + <button type="button" onClick={() => void cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + )} + </div> + + {/* ---- the ladder ---- */} + <div data-variants-ladder={state?.ladderIsDefault ? "default" : "custom"} className="space-y-1"> + <div className="flex flex-wrap items-center gap-2"> + <span className="micro">ladder</span> + <span className="text-muted">{state?.ladderIsDefault ? "the default" : "this cut's own"}</span> + {ladder === null ? ( + <button type="button" data-variants-edit="" disabled={!state} onClick={() => state && setLadder(state.ladder.map(rowOf))} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Edit + </button> + ) : ( + <> + <button type="button" data-variants-add="" disabled={ladder.length >= 12} onClick={() => setLadder([...ladder, { name: "", height: "", crf: "", maxMiB: "", preset: "" }])} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Add + </button> + <button type="button" data-variants-save="" onClick={() => void saveLadder(ladder.map(variantOf))} className={buttonVariants({ variant: "outline", size: "sm" })}> + Save ladder + </button> + <button type="button" onClick={() => setLadder(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + </> + )} + {!state?.ladderIsDefault && ladder === null && ( + <button type="button" data-variants-default="" onClick={() => void saveLadder(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Use the default + </button> + )} + </div> + {ladder === null ? ( + <ul className="m-0 flex list-none flex-wrap gap-x-4 gap-y-0.5 p-0"> + {(state?.ladder ?? []).map((v) => ( + <li key={v.name} data-variant-rung={v.name}> + <span className="font-mono text-text">{v.name}</span> <span className="text-muted">{what(v)}</span> + </li> + ))} + </ul> + ) : ( + <ol className="m-0 list-none space-y-1 p-0"> + {ladder.map((r, i) => ( + <li key={i} className="flex flex-wrap items-center gap-1.5"> + {(["name", "height", "crf", "maxMiB", "preset"] as const).map((k) => ( + <label key={k} className="flex items-center gap-1 text-[11px]"> + {k} + <input data-variant-field={`${i}:${k}`} value={r[k]} onChange={(e) => setLadder(ladder.map((x, j) => (j === i ? { ...x, [k]: e.target.value } : x)))} className={`${input} ${k === "name" || k === "preset" ? "w-20" : "w-14"}`} /> + </label> + ))} + <button type="button" onClick={() => setLadder(ladder.filter((_, j) => j !== i))} className={buttonVariants({ variant: "quiet", size: "sm" })}> + remove + </button> + </li> + ))} + </ol> + )} + </div> + + {/* ---- what was made ---- */} + {state?.made && ( + <div className="space-y-1"> + <span className="micro">made {state.made.at ? fmtAgo(Date.parse(state.made.at)) : ""}</span> + {state.stale && <span className={`${badgeVariants({ variant: "open", size: "sm" })} ml-2`}>made from an older build</span>} + <table data-variants-list="" className="w-full text-[11.5px]"> + <tbody> + {state.made.items.map((m) => ( + <tr key={m.name} data-variant={m.name} className="border-t border-seam"> + <td className="py-0.5 font-mono text-text">{m.name}</td> + <td className="num">{m.width && m.height ? `${m.width}×${m.height}` : "–"}</td> + <td className="num">{m.bytes ? fmtBytes(m.bytes) : "–"}</td> + <td className="num">{m.kbps ? `${m.kbps} kb/s` : ""}</td> + <td className="text-right"> + {m.exists ? ( + <a href={file(m.name)} data-variant-link={m.name} target="_blank" rel="noreferrer" className="ink-link"> + open + </a> + ) : ( + <span className="text-muted">gone</span> + )} + </td> + </tr> + ))} + </tbody> + </table> + </div> + )} + + {job && ( + <div data-variants-job={job.state} className="space-y-1"> + <span>{running ? "Making the variants…" : job.state === "done" ? "Variants made." : `Variants ${job.state}${job.error ? `: ${job.error}` : ""}`}</span> + {log.length > 0 && <pre className="max-h-32 overflow-auto rounded border border-seam bg-ground p-1.5 font-mono text-[10.5px] text-muted">{log.join("\n")}</pre>} + </div> + )} + + {/* ---- sync ---- */} + <div className="space-y-1"> + <span className="micro">sync</span> + {!state?.sync ? ( + <p data-sync-none="" className="m-0 text-muted"> + No sync report for this build: the build writes one (sourced/sync.json) as it finishes. + </p> + ) : ( + <> + <span className="ml-2 text-muted"> + each clip&rsquo;s sound against its picture; past one frame ({state.sync.frameMs} ms) is flagged ·{" "} + {state.sync.items.filter((x) => x.flagged).length} flagged + </span> + <table data-sync-table="" className="w-full text-[11.5px]"> + <tbody> + {state.sync.items.map((x) => ( + <tr key={x.id} data-sync-row={x.id} data-sync-flagged={x.flagged ? "" : undefined} className={`border-t border-seam ${x.flagged ? "text-reject-text" : ""}`}> + <td className="py-0.5 font-mono"> + {x.clip ? ( + <Link href={`${clipEditorHref(project, { clip: x.id, mode: "edit" })}#clip-audio`} prefetch={false} data-sync-link={x.id} className="ink-link"> + {x.id} + </Link> + ) : ( + x.id + )} + </td> + <td className="num">{x.start != null ? `${x.start.toFixed(2)} s` : ""}</td> + <td className="num" data-sync-lag={x.lagMs ?? ""}> + {x.lagMs != null ? `${x.lagMs > 0 ? "+" : ""}${Math.round(x.lagMs)} ms` : "–"} + </td> + <td className="text-right">{x.flagged ? (x.lagMs != null && x.lagMs < 0 ? "sound early" : "sound late") : ""}</td> + </tr> + ))} + </tbody> + </table> + </> + )} + </div> + + {error && ( + <p role="alert" data-variants-error="" className="m-0 text-reject-text"> + {error} + </p> + )} + </div> + </Panel> + ); +} diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -14,6 +14,7 @@ import { cn } from "@/lib/utils"; import { ROOM, roomShade } from "umtool-report-to-video/room"; import { startTakeJob } from "../NewTakePanel"; import AssistBox from "../report/AssistBox"; +import { AudioBox, CountStampBox } from "./ClipKnobs"; // 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"; @@ -37,6 +38,9 @@ import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy // the short (release 36) a 9:16 box dragged on the player (the clip's // `vertical.crop`), Make a short (a job: shorts/<clip>.mp4); // a speaker's name for the captions in the Speakers list +// the knobs (video knobs) Count & stamp on a claimed clip -- the stamp's +// second (Set at playhead, Shift+S), hold, on/off, count, +// label -- and Audio: sync nudge, gain, fades (./ClipKnobs.tsx) // // Every write is one POST to /api/report/clip-editor; the answer is the whole // view again, so the page never guesses what the server did. Edge edits are @@ -351,6 +355,18 @@ export default function ClipEditor({ setPlayhead(t); player.current?.seek(t); }; + // The video knobs: the claim's stamp at the playhead (Shift+S), and the 3 s around it, heard. + const stampAtPlayhead = () => { + if (playhead === null) { + setError("put the playhead where the stamp should land first"); + return; + } + void flush().then(() => write({ op: "claim", clip: clip.id, knobs: { at: r2(playhead) } }, `The stamp lands at ${edgeClock(playhead)}`)); + }; + const listen = () => { + if (playhead === null) return; + player.current?.listen(playhead); + }; // ---- keys ----------------------------------------------------------------- const keyRef = useRef<(e: KeyboardEvent) => void>(() => {}); @@ -358,6 +374,13 @@ export default function ClipEditor({ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as HTMLElement | null; if (t?.closest?.(TYPING) || t?.closest?.("dialog[open]")) return; + // Shift+S: the claim's stamp lands at the playhead (S alone splits). + if (e.shiftKey && e.key.toLowerCase() === "s") { + if (!clip.claim) return; + e.preventDefault(); + stampAtPlayhead(); + return; + } const k = e.key.length === 1 ? e.key.toLowerCase() : e.key; const act: Record<string, () => void> = { " ": () => player.current?.toggle(), @@ -572,6 +595,22 @@ export default function ClipEditor({ </div> )} + {/* ---- the knobs (video knobs) -------------------------------------- */} + {clip.claim && ( + <CountStampBox + clipId={clip.id} + claim={clip.claim} + stampsOn={clip.stampsOn ?? null} + defaults={view.knobs} + playhead={playhead} + span={{ start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd }} + busy={busy} + write={write} + onGo={choose} + /> + )} + <AudioBox clipId={clip.id} audio={clip.audio ?? null} busy={busy} write={write} canListen={playhead !== null} onListen={listen} /> + {/* ---- the decisions ----------------------------------------------- */} <div className="flex flex-wrap items-center gap-2" data-editor-actions=""> <button type="button" data-rule="keep" aria-pressed={clip.ruling === "keep"} disabled={busy} onClick={() => rule(clip.ruling === "keep" ? null : "keep")} className={buttonVariants({ variant: clip.ruling === "keep" ? "pressed" : "outline", size: "md" })}> @@ -747,7 +786,7 @@ export default function ClipEditor({ // clip's extent, else its cut; loops the cut. // --------------------------------------------------------------------------- -type PlayerHandle = { toggle: () => void; seek: (t: number) => void }; +type PlayerHandle = { toggle: () => void; seek: (t: number) => void; listen: (t: number) => void }; /** 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 }; @@ -760,6 +799,7 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut // The seek to the cut on load is the player's own, not a person's: it must // not move the playhead somebody just set by clicking a word. const ownSeek = useRef(false); + const listenTimer = useRef<ReturnType<typeof setTimeout> | null>(null); const cutRef = useRef(cut); cutRef.current = cut; const key = targets.map((t) => `${t.clip}|${t.from}|${t.to}`).join(","); @@ -818,6 +858,20 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut ownSeek.current = true; m.currentTime = fileT(t); }, + // The 3 s around a second, then stop where it started (the Audio box's "listen"). + listen: (t: number) => { + const m = media.current; + if (!m) return; + if (listenTimer.current) clearTimeout(listenTimer.current); + ownSeek.current = true; + m.currentTime = fileT(Math.max(0, t - 1.5)); + void m.play().catch(() => {}); + listenTimer.current = setTimeout(() => { + m.pause(); + ownSeek.current = true; + m.currentTime = fileT(t); + }, 3000); + }, })); if (found === undefined) return <div data-editor-player="looking" className="flex aspect-video w-full max-w-[720px] items-center justify-center rounded-[3px] bg-panel-2 text-[12px] text-muted">looking for the clip…</div>; diff --git a/umtool/components/projects/review/ClipKnobs.tsx b/umtool/components/projects/review/ClipKnobs.tsx @@ -0,0 +1,238 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { edgeClock } from "@/lib/report/clipEditorModel.mjs"; +import type { ClaimKnobs, ClipAudio, KnobDefaults } from "@/lib/report/clipEditorTypes"; + +// THE CLIP'S KNOBS (video knobs, plans/video-knobs-ui.md), in the clip editor: +// +// Count & stamp on a clip that carries a claim: the source second its stamp +// lands and the tally steps (`claim.at`, Set at playhead, +// Shift+S), how long it stays (`hold`), whether it is drawn +// (`stamp`), how much it counts (`count`), what it says +// (`label`) +// Audio the clip's sound at the encode: a sync nudge in ms (+ = +// later), gain in dB, fades in s; "listen" replays the 3 s +// around the playhead +// +// Every field shows the default it gets when its key is absent; Clear removes +// the key (the default again). Each change is one write through the clip +// editor's route (op claim / op audio), the same writer `umtool set` uses. + +const input = "num w-[6em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 font-mono text-[12px] text-text outline-none focus:border-signal"; +const box = "space-y-1.5 rounded-[3px] border border-seam bg-panel p-2 text-[12px] text-text-2"; + +type Write = (body: Record<string, unknown>, done?: string) => Promise<unknown>; + +/** A field that writes on Enter or blur; empty clears it. */ +function KnobField({ + name, + label, + value, + placeholder, + unit, + kind = "number", + step, + maxLength, + busy, + onSave, +}: { + name: string; + label: string; + value: number | string | undefined; + placeholder: string; + unit?: string; + kind?: "number" | "text"; + step?: number; + maxLength?: number; + busy: boolean; + onSave: (v: string) => void; +}) { + const shown = value === undefined ? "" : String(value); + const [text, setText] = useState(shown); + useEffect(() => setText(shown), [shown]); + const commit = () => { + if (text.trim() === shown) return; + onSave(text.trim()); + }; + return ( + <label className="inline-flex items-center gap-1.5"> + <span className="micro">{label}</span> + <input + data-knob={name} + type={kind} + step={step} + maxLength={maxLength} + value={text} + placeholder={placeholder} + disabled={busy} + onChange={(e) => setText(e.target.value)} + onBlur={commit} + onKeyDown={(e) => { + if (e.key === "Enter") { + commit(); + (e.target as HTMLInputElement).blur(); + } + if (e.key === "Escape") { + setText(shown); + (e.target as HTMLInputElement).blur(); + } + }} + className={kind === "text" ? input.replace("w-[6em]", "w-[11em]") : input} + /> + {unit && <span className="text-muted">{unit}</span>} + {value !== undefined && ( + <button type="button" data-knob-clear={name} disabled={busy} onMouseDown={(e) => e.preventDefault()} onClick={() => onSave("")} className={buttonVariants({ variant: "quiet", size: "sm" })} title="back to the default"> + Clear + </button> + )} + </label> + ); +} + +const numOrNull = (s: string) => (s === "" ? null : Number(s)); + +export function CountStampBox({ + clipId, + claim, + stampsOn, + defaults, + playhead, + span, + busy, + write, + onGo, +}: { + clipId: string; + claim: ClaimKnobs; + stampsOn: string | null; + defaults: KnobDefaults | undefined; + playhead: number | null; + span: { start: number; end: number; cutStart: number; cutEnd: number }; + busy: boolean; + write: Write; + onGo: (id: string) => void; +}) { + const set = (knobs: Record<string, unknown>, done: string) => void write({ op: "claim", clip: clipId, knobs }, done); + const hold = defaults?.hold ?? 3; + const word = defaults?.labels?.[claim.verdict] ?? claim.verdict; + // The box shows the choice at once (stampDraft) until the view comes back with it. + const [stampDraft, setStampDraft] = useState<boolean | null>(null); + useEffect(() => setStampDraft(null), [claim.stamp, clipId]); + const stampOn = stampDraft ?? claim.stamp !== false; + const outsideCut = typeof claim.at === "number" && (claim.at < span.cutStart || claim.at > span.cutEnd); + return ( + <section id="clip-stamp" data-count-stamp={clipId} data-claim-id={claim.id} className={box}> + <div className="flex flex-wrap items-baseline gap-2"> + <h2 className="micro m-0">Count &amp; stamp</h2> + <span className="font-mono text-[11.5px]"> + {claim.id} · {claim.verdict} + </span> + {stampsOn && stampsOn !== clipId && ( + <span data-stamps-on={stampsOn} className="text-muted"> + this claim stamps on{" "} + <button type="button" onClick={() => onGo(stampsOn)} className="underline"> + {stampsOn} + </button>{" "} + (the last clip carrying it) — its knobs are read there + </span> + )} + </div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> + <span className="inline-flex items-center gap-1.5" data-knob-at={claim.at ?? ""}> + <span className="micro">lands at</span> + <span className="num font-mono">{typeof claim.at === "number" ? edgeClock(claim.at) : "default (before the clip leaves)"}</span> + <button + type="button" + data-claim-at-playhead="" + disabled={busy || playhead === null} + onMouseDown={(e) => e.preventDefault()} + onClick={() => playhead !== null && set({ at: Math.round(playhead * 100) / 100 }, `The stamp lands at ${edgeClock(playhead)}`)} + className={buttonVariants({ size: "sm" })} + title="the stamp lands and the count steps at the playhead (a source second inside the clip)" + > + Set at playhead <kbd>⇧S</kbd> + </button> + {typeof claim.at === "number" && ( + <button type="button" data-knob-clear="at" disabled={busy} onClick={() => set({ at: null }, "The stamp lands at its default")} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Clear + </button> + )} + </span> + <KnobField name="hold" label="hold" unit="s" step={0.5} value={claim.hold} placeholder={String(hold)} busy={busy} onSave={(v) => set({ hold: numOrNull(v) }, v ? `The stamp stays ${v} s` : "The stamp stays the cut's default")} /> + <label className="inline-flex items-center gap-1.5 text-text"> + <input type="checkbox" data-knob="stamp" checked={stampOn} disabled={busy} onChange={(e) => { + const on = e.target.checked; + setStampDraft(on); + void write({ op: "claim", clip: clipId, knobs: { stamp: on ? null : false } }, on ? "Stamp drawn" : "Counts, no stamp").finally(() => setStampDraft(null)); + }} + /> + draw the stamp + </label> + <KnobField name="count" label="count" step={1} value={claim.count} placeholder={String(defaults?.count ?? 1)} busy={busy} onSave={(v) => set({ count: numOrNull(v) }, v ? `Counts ${v}` : "Counts 1")} /> + <KnobField name="label" label="label" kind="text" maxLength={20} value={claim.label} placeholder={word} busy={busy} onSave={(v) => set({ label: v || null }, v ? `The stamp says “${v}”` : "The stamp says the verdict's word")} /> + </div> + {typeof claim.at === "number" && ( + <p data-knob-at-hint="" className="m-0 text-muted"> + The On-screen preview places this second from the last build&rsquo;s cut of the clip: it is approximate until the next build. + </p> + )} + {defaults && !defaults.stampShown && <p className="m-0 text-muted">The cut draws no stamps (the fact-check's stamp effect is off): the count still steps here.</p>} + {outsideCut && ( + <p data-knob-warning="" className="m-0 text-reject-text"> + {edgeClock(claim.at as number)} is outside the cut ({edgeClock(span.cutStart)}–{edgeClock(span.cutEnd)}): the stamp would land on footage the cut does not play. + </p> + )} + </section> + ); +} + +const AUDIO_NUDGES = [-40, -10, 10, 40] as const; + +export function AudioBox({ + clipId, + audio, + busy, + write, + canListen, + onListen, +}: { + clipId: string; + audio: ClipAudio | null; + busy: boolean; + write: Write; + canListen: boolean; + onListen: () => void; +}) { + const a = audio ?? {}; + const set = (patch: Record<string, unknown> | null, done: string) => void write({ op: "audio", clip: clipId, audio: patch }, done); + const offset = a.offset ?? 0; + return ( + <section id="clip-audio" data-audio-box={clipId} data-audio={JSON.stringify(a)} className={box}> + <div className="flex flex-wrap items-baseline gap-2"> + <h2 className="micro m-0">Audio</h2> + <span className="text-muted">applied when the clip is encoded; the player plays the source as it is</span> + {audio && ( + <button type="button" data-audio-clear-all="" disabled={busy} onClick={() => set(null, "The clip's sound is as recorded")} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Clear all + </button> + )} + </div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> + <KnobField name="offset" label="sync" unit="ms (+ later)" step={1} value={a.offset} placeholder="0" busy={busy} onSave={(v) => set({ offset: numOrNull(v) }, v ? `Sound moved ${v} ms` : "Sound in sync as recorded")} /> + {AUDIO_NUDGES.map((d) => ( + <button key={d} type="button" data-audio-nudge={d} disabled={busy} onMouseDown={(e) => e.preventDefault()} onClick={() => set({ offset: Math.max(-2000, Math.min(2000, offset + d)) }, `Sound moved ${offset + d} ms`)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + {d > 0 ? `+${d}` : `−${Math.abs(d)}`} + </button> + ))} + <button type="button" data-audio-listen="" disabled={!canListen} onMouseDown={(e) => e.preventDefault()} onClick={onListen} className={buttonVariants({ size: "sm" })} title="play the 3 s around the playhead"> + listen + </button> + <KnobField name="gain" label="gain" unit="dB" step={0.5} value={a.gain} placeholder="0" busy={busy} onSave={(v) => set({ gain: numOrNull(v) }, v ? `Gain ${v} dB` : "Gain as recorded")} /> + <KnobField name="fadeIn" label="fade in" unit="s" step={0.05} value={a.fadeIn} placeholder="0" busy={busy} onSave={(v) => set({ fadeIn: numOrNull(v) }, v ? `Fades in over ${v} s` : "No fade in")} /> + <KnobField name="fadeOut" label="fade out" unit="s" step={0.05} value={a.fadeOut} placeholder="0" busy={busy} onSave={(v) => set({ fadeOut: numOrNull(v) }, v ? `Fades out over ${v} s` : "No fade out")} /> + </div> + </section> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -23,6 +23,9 @@ Inbox cannot disagree about what is wrong with one. | `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx | | `folders [--json]` · `kinds [--json]` | the tree, the registry | | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | +| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`; `key=` clears one ([knobs.md](knobs.md)) | +| `look <project> key=value …` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) | +| `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | | `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) | | `index [--rebuild] [--prune] [--since MS] [--json]` | the cache | @@ -59,7 +62,8 @@ projects answering to one name is reported, never resolved by picking one. `UMTOOL_CACHE_DIR`, `UMTOOL_MEDIA_DIR`, `UMTOOL_PHRASE_CANDIDATES` (the phrase finder's suggestion files) — which is how it is tested against the e2e fixture (which also sets `E2E_UMTOOL_MONTAGE_STYLES`, the montage styles module `take`/`takes` read in place of -`report-to-video/montage-styles.mjs`). The path defaults +`report-to-video/montage-styles.mjs`, and `E2E_UMTOOL_VARIANTS_SCRIPT`, the encoder `variants` and Make variants +run in place of `report-to-video/variants.mjs`). The path defaults (`lib/paths.mjs`, `song/paths.mjs`): | Variable | Default | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -0,0 +1,63 @@ +# Knobs: every setting of a report video, by hand or by an agent + +Each knob below is a field or a button in umtool **and** a `umtool` command an agent runs, and both go through the +same writer (`lib/report/manifest.mjs`), checked by the renderer's own validators (the +build refuses exactly what the writer refuses). An absent key is the default: the video renders as it did before the knob existed. A knob set to its +default is removed, never written. + +Every manifest-write route takes the app's page (no `Authorization` header) or an agent's +`Authorization: Bearer <umtool's WORKER_TOKEN>`; any other header is a 401. Each write carries the manifest's +token (`GET` the route first, or let the CLI read it from the file): a write over a newer manifest is a 409, never +a silent overwrite. On a generated manifest (`generatedBy`) every knob change is also an `edit` note for the agent +that generates it ([notes.md](notes.md)). + +## A clip + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `claim.at` — the SOURCE second the stamp lands and the tally steps; inside the clip's window | clip editor, **Count & stamp**: **Set at playhead** (Shift+S) | `umtool set <p> <clip> claim.at=12.4` | `POST /api/report/clip-editor {op: "claim", clip, knobs: {at}}` | +| `claim.hold` — seconds the stamp stays (0.5–10; default the cut's `factcheck.stamp.seconds`) | Count & stamp, **hold** | `claim.hold=4` | same | +| `claim.stamp` — `false`: the claim counts, no stamp is drawn | Count & stamp, **draw the stamp** | `claim.stamp=false` | same | +| `claim.count` — how much the tally steps (1–99; default 1) | Count & stamp, **count** | `claim.count=2` | same | +| `claim.label` — this stamp's text (≤ 20; default the verdict's stamp word) | Count & stamp, **label** | `claim.label="2 SEIZURES"` | same | +| `audio.offset` — ms, + = the sound later (−2000…2000) | clip editor, **Audio**: **sync**, the ±10/±40 nudges, **listen** (the 3 s around the playhead) | `umtool set <p> <clip> audio.offset=-40` | `POST /api/report/clip-editor {op: "audio", clip, audio: {offset}}` | +| `audio.gain` — dB (−20…20) | Audio, **gain** | `audio.gain=-3` | same | +| `audio.fadeIn`, `audio.fadeOut` — seconds (0–5) | Audio, **fade in / fade out** | `audio.fadeIn=0.3` | same | +| `layout` — `finale`: the deck's finale layout for this clip (`render.chrome.deck.finale`); `clip` is the default | — | `umtool set <p> <clip> layout=finale` | — | + +`key=` (nothing after the `=`) clears a knob; in umtool, **Clear** beside a field (Audio: **Clear all**). A +claim's knobs are read from the clip that **stamps** it — the last clip carrying the claim id; the box on any other +clip says which one that is, and `umtool set` prints a NOTE. A window save that would leave `claim.at` outside the +clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the +claim's id and verdict and keeps its knobs while the id stays the same. + +## The cut + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `render.chrome.factcheck.stamp.scale` (0.5–2), `.motion` (`slam` `pop` `fade` `none`), `.opacity` (0.3–1) | Structure, **fact-check labels**: scale, motion, opacity | `umtool look <p> factcheck.stamp.scale=1.3 factcheck.stamp.motion=pop` | `POST /api/report/timeline {op: "factcheck", factcheck}` | +| `render.chrome.factcheck.verdicts.<V>.stampLabel` — the stamp's word (singular, `SEIZURE`) beside `label` (the tally's, `SEIZURES`) | fact-check labels, the third column | `factcheck.verdicts.CONTRADICTED.stampLabel=SEIZURE` | same | +| `render.chrome.deck.markers[]` — `{after, label ≤ 24, color?, align?}`, at most 12; `align` `auto` `left` `right` `center` | On-screen, **markers**: add, the clip picker, label, colour, align, ↑ ↓, remove | `umtool look <p> deck.markers='[{"after":"c03","label":"Rescue","align":"right"}]'` | `PUT /api/report/chrome {project, token, markers}` | +| `render.chrome.deck.<key>` — any of the deck's own keys (`finale`, `pip`, …), as JSON; refused in the build's words when it does not know the key or the value | On-screen settings (the ones it has a field for) | `umtool look <p> deck.finale='{…}'` | — | +| `render.chrome.deck.markerLayout` — `stagger` or `truncate` when labels crowd (default: stagger only when a label would truncate) | markers, **layout** | `deck.markerLayout=truncate` | `PUT /api/report/chrome {project, token, markerLayout}` | +| `render.variants` — the ladder **Make variants** encodes: `{name, height?, crf?, maxMiB?, preset?}` (at most 12; a `maxMiB` rung takes no crf, a height there caps it); `master` is the build itself | Deliver, **Variants and sync**: Edit, Save ladder, Use the default | `umtool look <p> variants='[{"name":"master"},{"name":"720p","height":720,"crf":23}]'` | `PUT /api/report/render {project, token, variants}` | + +The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets +the look's keys (`transition=0.3`, …: [report-video.md](report-video.md#the-look-captions-loudness-shorts-release-36)). + +## Make variants, and the sync report + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| encode the ladder of the build (or of a take's) | Deliver, **Make variants** (one job; the encoder takes the heavy slot) | `umtool variants <p> [--take <t>]` | `POST /api/report/deliver {action: "variants", take?}` | +| what was made: name, frame, size, bitrate, a link | Deliver, the list | `umtool variants <p> --list [--json]` | `GET /api/report/variants?project=<p>[&take=<t>]`, a file: `&file=<name>` | +| each clip's sound against its picture (`<out>/sourced/sync.json`, written by the build); past one frame flagged | Deliver, **sync**: each clip links to its Audio box | `umtool variants <p> --list` | same `GET` | + +The files: `<out>/<slug>.<name>.mp4` and `<out>/variants.json`; `<out>` is the project's `out/`, or +`takes/<t>/out/`. A flagged clip is fixed with its `audio.offset` (the sign: a clip whose sound is early, a +negative lag, needs a positive offset), then a build. + +## Reading them back + +`umtool show <p>` prints a **knobs** block — each clip's claim knobs and audio (which clip stamps), the stamp's +knobs and words, the markers and their layout, the ladder — and `umtool show <p> --json` carries it as `knobs`. diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md @@ -27,6 +27,10 @@ from the working directory to the checkout. ## The agent loop +A note that asks for a different look, timing or sound is usually a **knob**: when a stamp lands and how much it +counts, a clip's sync, the markers, the encode ladder. Every knob a person sets in umtool an agent sets with +`umtool set` / `umtool look` / `umtool variants`, through the same writers ([knobs.md](knobs.md)). + 1. `umtool notes --all --open` — what is waiting. 2. `umtool notes <target>` — each open note with its anchor resolved against what is on disk now, and the **Source** line naming the file to edit. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -318,6 +318,9 @@ wrong place is worse than no code — so only an explicit `citeUrl` draws one. ## The on-screen deck (`render.chrome`) +Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and +level, the encode ladder — are each a field in umtool and a `umtool set` / `umtool look` command: [knobs.md](knobs.md). + Opt-in, and it **replaces** the header, the footer's progress track and the corner QR described above — a deck manifest draws none of them, because the panel carries the citation itself. The full contract (every setting, the diff --git a/umtool/e2e/fixtures/knobs-fixture.mjs b/umtool/e2e/fixtures/knobs-fixture.mjs @@ -0,0 +1,48 @@ +// What knobs.spec.ts edits (video knobs, plans/video-knobs-ui.md): +// +// knobs-fixture the clip editor's three clips (clip-editor-fixture.mjs, +// its own copy) with a claim on r002 and r003 (k1, r003 +// stamps it), a "build" in out/ (the cached window, as +// out/knobs-fixture.mp4) and the build's sync report +// (out/sourced/sync.json: r002 -469 ms, the rest in sync) +// -- the Count & stamp box, the Audio box, Make variants +// (the encoder stubbed: variants.e2e.mjs) and the Sync table +// knobs-deck-fixture the deck on (make-fixture.mjs deckManifest), two clips +// -- the Markers editor +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; + +/** + * @param {{ reports: string, manifest: Function, deckManifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o + */ +export function makeKnobsFixture({ reports, manifest, deckManifest, cachedWindow, cues }) { + const { dir } = makeClipEditorFixture({ reports, manifest, cachedWindow, cues, name: "knobs-fixture", title: "The Knobs Fixture" }); + const file = path.join(dir, "video.manifest.json"); + const m = JSON.parse(readFileSync(file, "utf8")); + for (const e of m.timeline) if (e.id === "r002" || e.id === "r003") e.claim = { id: "k1", verdict: "CONTRADICTED" }; + writeFileSync(file, JSON.stringify(m, null, 2) + "\n"); + mkdirSync(path.join(dir, "out", "sourced"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "knobs-fixture.mp4")); + writeFileSync( + path.join(dir, "out", "sourced", "sync.json"), + JSON.stringify({ fps: 15, items: [{ id: "r001", start: 0, lagMs: 0, peak: 0.92 }, { id: "r002", start: 2.1, lagMs: -469, peak: 0.81 }, { id: "r003", start: 4.2, lagMs: 12, peak: 0.88 }] }, null, 2) + "\n", + ); + + const deckDir = path.join(reports, "knobs-deck-fixture"); + mkdirSync(deckDir, { recursive: true }); + writeFileSync( + path.join(deckDir, "video.manifest.json"), + JSON.stringify( + deckManifest("knobs-deck-fixture", "The Knobs Deck Fixture", [ + { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because" }, + { type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence" }, + ]), + null, + 2, + ) + "\n", + ); + return { dir, deckDir }; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -38,6 +38,7 @@ import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; import { makeVideoAssistFixture } from "./video-assist-fixture.mjs"; +import { makeKnobsFixture } from "./knobs-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")); @@ -1822,6 +1823,8 @@ makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", " makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // Release 38 lane E: the video assistant's Ask box, Apply and Dismiss on the Look panel (video-assist.spec.ts). makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); +// Video knobs (plans/video-knobs-ui.md): Count & stamp, Audio, Make variants, Sync and the Markers editor (knobs.spec.ts). +makeKnobsFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. diff --git a/umtool/e2e/fixtures/variants.e2e.mjs b/umtool/e2e/fixtures/variants.e2e.mjs @@ -0,0 +1,26 @@ +#!/usr/bin/env node +// The variants encoder, STUBBED (E2E_UMTOOL_VARIANTS_SCRIPT, set in +// playwright.config.ts): the command line of report-to-video/variants.mjs +// (`node variants.mjs <out dir>`, the manifest beside the out dir), and its +// outputs -- `<out>/<slug>.<name>.mp4` per rung and variants.json -- with no +// ffmpeg: each "variant" is a copy of the first bytes of the build. The suite +// tests the button, the job and the list, not an encode. +import { readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; + +const outDir = path.resolve(process.argv[2] ?? ""); +const manifest = JSON.parse(await readFile(path.join(path.dirname(outDir), "video.manifest.json"), "utf8")); +const slug = manifest.slug; +const ladder = Array.isArray(manifest.render?.variants) + ? manifest.render.variants + : [{ name: "master" }, { name: "1080p", height: 1080, crf: 22 }, { name: "720p", height: 720, crf: 23 }, { name: "fit24", maxMiB: 24 }]; +const source = await readFile(path.join(outDir, `${slug}.mp4`)); +const items = []; +for (const [i, v] of ladder.entries()) { + const bytes = v.name === "master" ? source : source.subarray(0, Math.max(1, Math.floor(source.length / (i + 1)))); + await writeFile(path.join(outDir, `${slug}.${v.name}.mp4`), bytes); + const height = v.height ?? (v.maxMiB ? 480 : 1080); + items.push({ name: v.name, path: `${slug}.${v.name}.mp4`, width: Math.round((height * 16) / 9), height, bytes: bytes.length, kbps: 1000 }); + console.log(`variant ${v.name}: ${bytes.length} bytes (stub)`); +} +await writeFile(path.join(outDir, "variants.json"), JSON.stringify({ at: new Date().toISOString(), source: `${slug}.mp4`, items }, null, 2) + "\n"); diff --git a/umtool/e2e/knobs.spec.ts b/umtool/e2e/knobs.spec.ts @@ -0,0 +1,168 @@ +import { test, expect } 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 video knobs (plans/video-knobs-ui.md): +// - the clip editor's Count & stamp box: Set at playhead (and Shift+S) writes +// claim.at, count / label / stamp on-off write and Clear removes; a clip +// that carries the claim but does not stamp it says where it stamps +// - the Audio box: a sync nudge, the gain, Clear all +// - an agent's token on a manifest-write route: right one writes, a wrong one is 401 +// - the On-screen Markers editor: add, label, colour, align, re-order, the +// layout -> render.chrome.deck.markers / markerLayout +// - Deliver's Make variants (the encoder stubbed: e2e/fixtures/variants.e2e.mjs) +// and the Sync table, its flagged clip linking to that clip's Audio box +// Fixture: e2e/fixtures/knobs-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/knobs-fixture"; +const DIR = path.join(FIXTURE, "reports", "knobs-fixture"); +const DECK_PROJECT = "reports/knobs-deck-fixture"; +const DECK_DIR = path.join(FIXTURE, "reports", "knobs-deck-fixture"); + +type Entry = { id: string; type: string; claim?: Record<string, unknown>; audio?: Record<string, number> }; +type Manifest = { render: Record<string, unknown> & { chrome?: { deck?: Record<string, unknown> }; variants?: unknown }; timeline: Entry[] }; +const readManifest = (dir = DIR): Manifest => JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")); +const entry = (id: string, dir = DIR) => readManifest(dir).timeline.find((e) => e.id === id) ?? null; + +test("Count & stamp and Audio in the clip editor; an agent's token on the route", async ({ page, request }) => { + test.setTimeout(150_000); + await page.setViewportSize({ width: 1366, height: 900 }); + await page.goto(urls.clipEditorHref(PROJECT, { clip: "r003", mode: "edit" })); + await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r003"); + await expect(page.locator("[data-editor-player]")).not.toHaveAttribute("data-editor-player", "looking", { timeout: 15_000 }); + + const box = page.locator('[data-count-stamp="r003"]'); + await expect(box).toBeVisible(); + // The defaults show where a key is absent: the cut's stamp seconds, a count of 1. + await expect(box.locator('[data-knob="hold"]')).toHaveAttribute("placeholder", "3"); + await expect(box.locator('[data-knob="count"]')).toHaveAttribute("placeholder", "1"); + await expect(box.locator("[data-stamps-on]")).toHaveCount(0); + + // A word puts the playhead there; Set at playhead writes the source second. + await page.locator('[data-word-t="7.2"]').click(); + await box.locator("[data-claim-at-playhead]").click(); + await expect.poll(() => entry("r003")?.claim?.at).toBe(7.2); + // Shift+S does the same (S alone is Split here). + await page.locator('[data-word-t="7.8"]').click(); + await page.keyboard.press("Shift+S"); + await expect.poll(() => entry("r003")?.claim?.at).toBe(7.8); + expect(readManifest().timeline.filter((e) => e.type === "clip").map((e) => e.id)).toEqual(["r001", "r002", "r003"]); + + const count = box.locator('[data-knob="count"]'); + await expect(async () => { + await count.fill("2"); + await count.press("Enter"); + await expect.poll(() => entry("r003")?.claim?.count, { timeout: 2000 }).toBe(2); + }).toPass({ timeout: 15_000 }); + const label = box.locator('[data-knob="label"]'); + await label.fill("2 SEIZURES"); + await label.press("Enter"); + await expect.poll(() => entry("r003")?.claim?.label).toBe("2 SEIZURES"); + await box.locator('[data-knob="stamp"]').uncheck(); + await expect.poll(() => entry("r003")?.claim?.stamp).toBe(false); + await box.locator('[data-knob-clear="count"]').click(); + await expect.poll(() => entry("r003")?.claim).toEqual({ id: "k1", verdict: "CONTRADICTED", at: 7.8, stamp: false, label: "2 SEIZURES" }); + + // Audio: a nudge, the gain, Clear all. + const audio = page.locator('[data-audio-box="r003"]'); + await audio.locator('[data-audio-nudge="-40"]').click(); + await expect.poll(() => entry("r003")?.audio).toEqual({ offset: -40 }); + const gain = audio.locator('[data-knob="gain"]'); + await gain.fill("-3"); + await gain.press("Enter"); + await expect.poll(() => entry("r003")?.audio).toEqual({ offset: -40, gain: -3 }); + await audio.locator("[data-audio-clear-all]").click(); + await expect.poll(() => entry("r003")?.audio).toBeUndefined(); + + // r002 carries the claim but r003 stamps it: the box says so; r001 has none. + await page.locator('[data-editor-row="r002"]').click(); + await expect(page.locator('[data-count-stamp="r002"] [data-stamps-on="r003"]')).toBeVisible(); + await page.locator('[data-editor-row="r001"]').click(); + await expect(page.locator("[data-count-stamp]")).toHaveCount(0); + + // An agent's token writes through the same route; a wrong one is refused. + const view = await (await request.get(`/api/report/clip-editor?project=${encodeURIComponent(PROJECT)}`)).json(); + const wrong = await request.post("/api/report/clip-editor", { headers: { authorization: "Bearer nope" }, data: { project: PROJECT, op: "claim", clip: "r003", knobs: { count: 3 }, token: view.token } }); + expect(wrong.status()).toBe(401); + const right = await request.post("/api/report/clip-editor", { headers: { authorization: "Bearer umtool-e2e-token" }, data: { project: PROJECT, op: "claim", clip: "r003", knobs: { count: 3 }, token: view.token } }); + expect(right.ok(), await right.text()).toBe(true); + expect(entry("r003")?.claim?.count).toBe(3); +}); + +test("the Markers editor: add, label, colour, align, re-order, layout", async ({ page, request }) => { + test.setTimeout(120_000); + test.skip(!readManifest(DECK_DIR).render.fontRegular, "the deck refuses to draw without render.fontRegular/fontBold, and make-fixture.mjs found no font on this machine"); + // From no markers, whatever an earlier run left. + const token = (await (await request.get(`/api/report/chrome?project=${encodeURIComponent(DECK_PROJECT)}`)).json()).token; + const reset = await request.put("/api/report/chrome", { data: { project: DECK_PROJECT, token, markers: [], markerLayout: null } }); + expect(reset.ok(), await reset.text()).toBe(true); + await page.goto(urls.section(DECK_PROJECT, "onscreen")); + const ed = page.getByTestId("markers-editor"); + await expect(ed).toBeVisible({ timeout: 30_000 }); + await ed.getByTestId("markers-add").click(); + await ed.getByTestId("markers-add").click(); + await ed.getByTestId("marker-after-0").selectOption("c01"); + await ed.getByTestId("marker-label-0").fill("Arrival"); + await ed.getByTestId("marker-align-0").selectOption("left"); + await ed.getByTestId("marker-after-1").selectOption("c02"); + await ed.getByTestId("marker-label-1").fill("Rescue"); + await ed.getByTestId("marker-color-1").fill("accent"); + await ed.getByTestId("marker-down-0").click(); + await ed.getByTestId("markers-layout").selectOption("truncate"); + await ed.getByTestId("markers-save").click(); + await expect.poll(() => readManifest(DECK_DIR).render.chrome?.deck?.markers).toEqual([ + { after: "c02", label: "Rescue", color: "accent" }, + { after: "c01", label: "Arrival", align: "left" }, + ]); + expect(readManifest(DECK_DIR).render.chrome?.deck?.markerLayout).toBe("truncate"); + + await page.reload(); + await expect(page.getByTestId("marker-label-0")).toHaveValue("Rescue", { timeout: 30_000 }); + await page.getByTestId("marker-remove-0").click(); + await page.getByTestId("markers-layout").selectOption(""); + await page.getByTestId("markers-save").click(); + await expect.poll(() => readManifest(DECK_DIR).render.chrome?.deck?.markers).toEqual([{ after: "c01", label: "Arrival", align: "left" }]); + expect(readManifest(DECK_DIR).render.chrome?.deck && "markerLayout" in readManifest(DECK_DIR).render.chrome!.deck!).toBe(false); +}); + +test("Deliver: Make variants (stub encoder) lists them; Sync flags a clip and links to its Audio box", async ({ page, request }) => { + test.setTimeout(120_000); + // From the default ladder, whatever an earlier run left. + const token = (await (await request.get(`/api/report/render?project=${encodeURIComponent(PROJECT)}`)).json()).token; + const reset = await request.put("/api/report/render", { data: { project: PROJECT, token, variants: null } }); + expect(reset.ok(), await reset.text()).toBe(true); + await page.goto(urls.section(PROJECT, "deliver")); + const panel = page.locator("[data-variants-panel]"); + await expect(panel).toBeVisible({ timeout: 30_000 }); + await expect(panel.locator('[data-variants-ladder="default"]')).toBeVisible(); + + // The ladder is a knob: one rung less, saved to render.variants. + await panel.locator("[data-variants-edit]").click(); + await panel.locator('[data-variant-field="3:name"]').locator("xpath=../..").getByRole("button", { name: "remove" }).click(); + await panel.locator("[data-variants-save]").click(); + await expect.poll(() => readManifest().render.variants).toEqual([{ name: "master" }, { name: "1080p", height: 1080, crf: 22 }, { name: "720p", height: 720, crf: 23 }]); + + await panel.locator("[data-variants-make]").click(); + await expect(panel.locator('[data-variants-job="done"]')).toBeVisible({ timeout: 60_000 }); + await expect(panel.locator("[data-variant]")).toHaveCount(3); + expect(existsSync(path.join(DIR, "out", "knobs-fixture.720p.mp4"))).toBe(true); + const href = await panel.locator('[data-variant-link="720p"]').getAttribute("href"); + const got = await request.get(href!); + expect(got.ok()).toBe(true); + expect(got.headers()["content-type"]).toBe("video/mp4"); + + // Sync: r002's sound is 469 ms early, flagged; its link opens its Audio box. + const row = panel.locator('[data-sync-row="r002"]'); + await expect(row).toHaveAttribute("data-sync-flagged", ""); + await expect(panel.locator('[data-sync-row="r001"]')).not.toHaveAttribute("data-sync-flagged", ""); + await expect(row.locator("[data-sync-link]")).toHaveAttribute("href", `${urls.clipEditorHref(PROJECT, { clip: "r002", mode: "edit" })}#clip-audio`); + await row.locator("[data-sync-link]").click(); + await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r002", { timeout: 30_000 }); + await expect(page.locator('[data-audio-box="r002"]')).toBeVisible(); +}); diff --git a/umtool/lib/report/caller.ts b/umtool/lib/report/caller.ts @@ -0,0 +1,13 @@ +import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs"; + +// WHO MAY WRITE A MANIFEST (video knobs, plans/video-knobs-ui.md): every +// manifest-write route takes the app's own page (no Authorization header, as +// before) and an agent or the editor carrying `Bearer <umtool's WORKER_TOKEN>` +// -- routeCaller's rule (lib/annotations/agentAuth.mjs). Any other header is a +// 401, so a wrong token is refused rather than read as the page. + +/** null when the caller may write; else the 401 to send. */ +export function refuseCaller(request: Request, what: string): Response | null { + const who = routeCaller(request.headers.get("authorization"), agentToken(), what); + return who.ok ? null : Response.json({ error: who.error }, { status: who.status }); +} diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -35,8 +35,11 @@ import { mergeClips, restoreClip, splitClip, + updateClaimKnobs, updateClip, } from "./manifest.mjs"; +import { CLAIM_KNOB_DEFAULTS, stampingEntryId } from "./knobs.mjs"; +import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; import { readShorts } from "./shorts.mjs"; @@ -120,6 +123,11 @@ export async function clipEditorView(project) { // written, and the edges it gets with the cut's render.room. room: e.room === false ? false : isObj(e.room) ? e.room : null, roomEdges: roomEdgesOf(e, manifest.render), + // The video knobs: the claim as written (its id, verdict and knobs), + // the entry that stamps it (the last carrying its id), and the sound. + claim: isObj(e.claim) && typeof e.claim.id === "string" ? e.claim : null, + stampsOn: isObj(e.claim) && typeof e.claim.id === "string" ? stampingEntryId(manifest, e.claim.id) : null, + audio: isObj(e.audio) ? e.audio : null, }; }); const shorts = await readShorts(project.dir, manifest); @@ -143,9 +151,27 @@ export async function clipEditorView(project) { repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])), room: roomViewOf(manifest.render), + knobs: knobDefaultsOf(manifest.render), }; } +/** + * What a claim knob is when the claim does not set it (the Count & stamp box's + * placeholders): the cut's stamp seconds, whether the cut draws stamps at all, + * the default count, and each verdict's stamp word (its `stampLabel`, else its + * label). + */ +function knobDefaultsOf(render) { + const fc = resolveFactcheck(render); + const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {}; + const labels = {}; + for (const [v, x] of Object.entries(fc.verdicts)) { + const own = isObj(given[v]) && typeof given[v].stampLabel === "string" && given[v].stampLabel.trim() ? given[v].stampLabel.trim() : null; + labels[v] = own ?? x.label; + } + return { hold: fc.stamp.seconds, stampShown: fc.stamp.show !== false, count: CLAIM_KNOB_DEFAULTS.count, labels }; +} + /** A clip's room edges (room.mjs clipRoom), or null when it has none. */ function roomEdgesOf(entry, render) { const r = clipRoom(entry, render); @@ -271,6 +297,10 @@ const num = (v, what) => { * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short * room { clip, room: false | {tail?, head?} | null } room at this clip's edges * (null: the cut's render.room again) + * claim { clip, knobs: { at?, hold?, stamp?, count?, label? } } the claim's stamp and + * count (null on a knob: its default again) + * audio { clip, audio: { offset?, gain?, fadeIn?, fadeOut? } | null } the clip's sound + * (null on a key, or the whole: the default) * with `token` (the manifest's, from the view) on every manifest edit. * Returns `{ op, result, carried, view }`. */ @@ -405,8 +435,25 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { structural = false; break; } + case "claim": { + // The video knobs (plans/video-knobs-ui.md): when the stamp lands and the count steps, how long it stays, + // whether it is drawn, how much it counts, what it says. Not structural: no clip moves. + const e = needClip(); + if (!isObj(body.knobs)) throw new OpError("claim needs knobs: { at?, hold?, stamp?, count?, label? }"); + result = await updateClaimKnobs(dir, e.id, body.knobs, { token }); + structural = false; + break; + } + case "audio": { + const e = needClip(); + if (body.audio !== null && !isObj(body.audio)) throw new OpError("audio is { offset?, gain?, fadeIn?, fadeOut? }, or null for none"); + // A "trim" that leaves the cut where it is, as `vertical` is. + result = await updateClip(dir, e.id, { audio: body.audio }, { token, edit: "trim", now }); + structural = false; + break; + } default: - throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical or room"); + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim or audio"); } let carried = null; if (structural) { @@ -423,6 +470,8 @@ function summarise(r) { for (const k of ["id", "second", "absorbed", "at"]) if (r[k] !== undefined) out[k] = r[k]; if (isObj(r.entry) && typeof r.entry.id === "string") out.id ??= r.entry.id; if (isObj(r.speaker)) out.speaker = r.speaker; + if (isObj(r.claim)) out.claim = r.claim; + if (typeof r.stamps === "boolean") out.stamps = r.stamps; if (r.ruling !== undefined) out.ruling = r.ruling; return out; } diff --git a/umtool/lib/report/clipEditor.test.mjs b/umtool/lib/report/clipEditor.test.mjs @@ -341,3 +341,29 @@ test("manifestToken changes with every operation (the page's next write carries await rm(p.dir, { recursive: true, force: true }); } }); + +test("runClipEditorOp: the video knobs -- claim (Count & stamp) and audio; the view carries them and their defaults", async () => { + const p = await project({ withReactions: false }); + try { + const m = JSON.parse(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8")); + m.timeline[3].claim = { id: "k7", verdict: "CONTRADICTED" }; + m.render.chrome = { engine: "hyperframes", layout: "deck", factcheck: { stamp: { seconds: 4 }, verdicts: { CONTRADICTED: { label: "Seizures", stampLabel: "SEIZURE" } } } }; + await writeFile(path.join(p.dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + const v0 = await clipEditorView(p); + assert.deepEqual(v0.knobs, { hold: 4, stampShown: true, count: 1, labels: { ...v0.knobs.labels, CONTRADICTED: "SEIZURE" } }); + assert.equal(v0.knobs.labels.PARTLY, "Partly true"); + const r = await runClipEditorOp(p, { op: "claim", clip: "r003", token: v0.token, knobs: { at: 55.5, count: 2 } }); + assert.deepEqual(r.result.claim, { id: "k7", verdict: "CONTRADICTED", at: 55.5, count: 2 }); + assert.equal(r.result.stamps, true); + const c = r.view.clips.find((x) => x.id === "r003"); + assert.equal(c.stampsOn, "r003"); + assert.equal(c.claim.at, 55.5); + const a = await runClipEditorOp(p, { op: "audio", clip: "r003", token: r.view.token, audio: { offset: 120, gain: -3 } }); + assert.deepEqual(a.view.clips.find((x) => x.id === "r003").audio, { offset: 120, gain: -3 }); + await assert.rejects(runClipEditorOp(p, { op: "claim", clip: "r001", knobs: { count: 2 } }), /carries no claim/); + await assert.rejects(runClipEditorOp(p, { op: "audio", clip: "r003", audio: 5 }), /audio is/); + await assert.rejects(runClipEditorOp(p, { op: "claim", clip: "r003", token: "stale", knobs: { count: 2 } }), StaleToken); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -30,8 +30,19 @@ export type EditorClip = { /** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */ room?: false | { tail?: boolean; head?: boolean } | null; roomEdges?: { tail: boolean; head: boolean } | null; + /** The video knobs: the claim as written (id, verdict, and its stamp's knobs), the entry that stamps it, the sound. */ + claim?: ClaimKnobs | null; + stampsOn?: string | null; + audio?: ClipAudio | null; }; +/** A claim with its knobs (plans/video-knobs-plan.md): `at` is a source second. */ +export type ClaimKnobs = { id: string; verdict: string; at?: number; hold?: number; stamp?: boolean; count?: number; label?: string }; +/** A clip's sound at the encode: offset in ms (+ = later), gain in dB, fades in s. */ +export type ClipAudio = { offset?: number; gain?: number; fadeIn?: number; fadeOut?: number }; +/** What a claim knob is when absent: the cut's stamp seconds, whether stamps are drawn, the count, each verdict's stamp word. */ +export type KnobDefaults = { hold: number; stampShown: boolean; count: number; labels: Record<string, string> }; + export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number }; export type Proposal = { id: string; start: number; end: number; score?: number; why?: string; moments?: string[]; used?: boolean; clipId?: string | null }; @@ -54,6 +65,8 @@ export type EditorView = { shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>; /** The cut's render.room and its join's length (release 36 lane E). */ room?: { tail: boolean; head: boolean; minGap: number | null; maxS: number | null; join: number }; + /** The claim knobs' defaults (video knobs). */ + knobs?: KnobDefaults; }; export type Turn = { start: number; end: number; speaker: number }; diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -584,3 +584,33 @@ export function rebuildReportSteps(project, variants) { timeoutMs: 15 * 60_000, })); } + +/** + * MAKE VARIANTS (video knobs, plans/video-knobs-ui.md): the encode ladder of a + * built cut -- the project's out/ or a take's -- as one step: + * `node report-to-video/variants.mjs <out dir>`, which reads the manifest + * beside the out/ for the slug and `render.variants` and takes the heavy slot + * itself (heavy-gate.mjs), as build-video does. The out dir is computed from + * the project and a take id by the caller, never sent by a client. + * + * E2E_UMTOOL_VARIANTS_SCRIPT (test-only, playwright.config.ts) names a stub + * encoder with the same command line. + * + * @param {{ dir: string }} project + * @param {string} outDir + * @param {Record<string, string | undefined>} [env] + * @returns {import("../trim").Step[]} + */ +export function variantsSteps(project, outDir, env = process.env) { + const bin = env.E2E_UMTOOL_VARIANTS_SCRIPT || script("variants.mjs"); + return [ + { + cwd: PIPELINE_DIR, + env: {}, + label: `make the variants of ${path.relative(project.dir, outDir) || "out"}`, + argv: ["node", bin, outDir], + // A size-capped variant is two passes over the whole cut, per variant. + timeoutMs: 90 * 60_000, + }, + ]; +} diff --git a/umtool/lib/report/knobs.mjs b/umtool/lib/report/knobs.mjs @@ -0,0 +1,162 @@ +// THE VIDEO KNOBS, writer side (plans/video-knobs-ui.md): what a person sets +// in the clip editor, the fact-check editor, the markers editor or Deliver -- +// and an agent sets with `umtool set` / `umtool look` -- before manifest.mjs +// writes it. +// +// a claimed entry claim.at / hold / stamp / count / label (factcheck.mjs normalizeClaim, validateClaims) +// a clip audio: { offset, gain, fadeIn, fadeOut } (clip-audio.mjs validateClipAudio) +// the fact-check render.chrome.factcheck.stamp.scale / motion / opacity, +// verdicts[V].stampLabel (factcheck.mjs validateFactcheck) +// the deck render.chrome.deck.markers[].align, deck.markerLayout (deck.mjs validateChrome) +// the encode ladder render.variants (variants.mjs validateVariants) +// +// The RULES are the renderer's (report-to-video, plans/video-knobs-core.md): +// a value the writer accepts is one the build accepts. What is here is the +// writer's side of them: a patch typed by a person or an agent ("12.4", +// "false", "") read into the value it means, a knob at its default removed, +// and which entry's knobs the build reads. +// +// PURE: no fs. Plain ESM so `umtool set` runs it under bare node. +import { CLAIM_KEYS, CLAIM_LIMITS, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, STAMP_MOTIONS } from "umtool-report-to-video/factcheck"; +import { MARKER_ALIGNS, MARKER_LAYOUTS } from "umtool-report-to-video/deck"; +import { DEFAULT_VARIANTS, validateVariants, variantsOf } from "umtool-report-to-video/variants"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const num = (v) => typeof v === "number" && Number.isFinite(v); +const numIn = (v, lo, hi) => num(v) && v >= lo && v <= hi; +const q = (v) => JSON.stringify(v); +const round = (n, dp) => Number(Number(n).toFixed(dp)); + +export { MARKER_ALIGNS, MARKER_LAYOUTS, STAMP_MOTIONS, variantsOf }; + +// --------------------------------------------------------------------------- +// A claim's knobs (per entry). +// --------------------------------------------------------------------------- + +/** The knobs a claim may carry beside its id and verdict, in the editor's order. */ +export const CLAIM_KNOBS = Object.freeze(CLAIM_KEYS.filter((k) => k !== "id" && k !== "verdict")); + +/** Their limits: the renderer's. */ +export const CLAIM_KNOB_LIMITS = CLAIM_LIMITS; + +/** The defaults a claim with no knob gets (hold's is the cut's `factcheck.stamp.seconds`). */ +export const CLAIM_KNOB_DEFAULTS = Object.freeze({ stamp: true, count: 1 }); + +/** + * One knob's value as typed, read and checked. `null` (or "") = clear the + * knob. Throws a sentence naming `claim.<key>`. That `at` lies in the entry's + * window is validateClaims' (it has the entry). + * + * @param {string} key + * @param {unknown} v + * @returns {unknown} + */ +export function claimKnobValue(key, v) { + if (v === null || v === undefined || v === "") return null; + switch (key) { + case "at": { + const x = typeof v === "string" ? Number(v) : v; + if (!num(x) || x < 0) throw new Error(`claim.at must be a source second, 0 or more (got ${q(v)})`); + return round(x, 2); + } + case "hold": { + const x = typeof v === "string" ? Number(v) : v; + const [lo, hi] = CLAIM_LIMITS.hold; + if (!numIn(x, lo, hi)) throw new Error(`claim.hold must be from ${lo} to ${hi} seconds (got ${q(v)})`); + return round(x, 2); + } + case "stamp": { + const x = v === "true" ? true : v === "false" ? false : v; + if (typeof x !== "boolean") throw new Error(`claim.stamp must be true or false (got ${q(v)})`); + return x; + } + case "count": { + const x = typeof v === "string" ? Number(v) : v; + const [lo, hi] = CLAIM_LIMITS.count; + if (!(Number.isInteger(x) && x >= lo && x <= hi)) throw new Error(`claim.count must be a whole number from ${lo} to ${hi} (got ${q(v)})`); + return x; + } + case "label": { + if (typeof v !== "string") throw new Error(`claim.label must be words (got ${q(v)})`); + const s = v.trim(); + if (!s) return null; + if (/[\r\n]/.test(s)) throw new Error("claim.label must be one line"); + if (s.length > CLAIM_LIMITS.label) throw new Error(`claim.label is ${s.length} characters (at most ${CLAIM_LIMITS.label})`); + return s; + } + default: + throw new Error(`claim.${key} is not a claim knob (${CLAIM_KNOBS.join(", ")})`); + } +} + +/** + * A patch of claim knobs: `{ at?, hold?, stamp?, count?, label? }`, each a + * value or null (clear). A knob set to its default is CLEARED -- `stamp: true` + * and `count: 1` are what an absent key already says. + * + * @param {unknown} patch + * @returns {Record<string, unknown>} key -> value, or null to remove + */ +export function normalizeClaimKnobPatch(patch) { + if (!isObj(patch)) throw new Error("the claim knobs are an object of at, hold, stamp, count, label"); + const keys = Object.keys(patch); + if (!keys.length) throw new Error("nothing to change"); + /** @type {Record<string, unknown>} */ + const out = {}; + for (const k of keys) { + if (!CLAIM_KNOBS.includes(k)) throw new Error(`claim.${k} is not a claim knob (${CLAIM_KNOBS.join(", ")})`); + const v = claimKnobValue(k, /** @type {Record<string, unknown>} */ (patch)[k]); + out[k] = v !== null && k in CLAIM_KNOB_DEFAULTS && v === CLAIM_KNOB_DEFAULTS[/** @type {"stamp"|"count"} */ (k)] ? null : v; + } + return out; +} + +/** The knobs of a claim as written (absent keys left out). */ +export function claimKnobsOf(claim) { + /** @type {Record<string, unknown>} */ + const out = {}; + if (!isObj(claim)) return out; + for (const k of CLAIM_KNOBS) if (claim[k] !== undefined) out[k] = claim[k]; + return out; +} + +/** + * The entry that STAMPS a claim: the last in the timeline carrying its id + * (per variant: an entry with `variant` set counts only in that cut, one with + * none in every cut). Its knobs are the ones the build reads. + * + * @param {{ timeline?: unknown[] }} manifest + * @param {string} claimId + * @param {string | null} [variant] null: the last in the whole timeline + */ +export function stampingEntryId(manifest, claimId, variant = null) { + let last = null; + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (!isObj(e) || !isObj(e.claim) || e.claim.id !== claimId) continue; + if (variant && e.variant && e.variant !== variant) continue; + last = e.id; + } + return last; +} + +// --------------------------------------------------------------------------- +// The fact-check's stamp knobs, for the editor's placeholders. +// --------------------------------------------------------------------------- + +/** The stamp knobs `render.chrome.factcheck.stamp` carries beside show/seconds/position. */ +export const STAMP_KNOBS = Object.freeze(["scale", "motion", "opacity"]); +export const STAMP_KNOB_DEFAULTS = Object.freeze(Object.fromEntries(STAMP_KNOBS.map((k) => [k, FACTCHECK_DEFAULTS.stamp[k]]))); +export const STAMP_KNOB_LIMITS = Object.freeze({ scale: FACTCHECK_LIMITS.scale, opacity: FACTCHECK_LIMITS.opacity }); + +// --------------------------------------------------------------------------- +// The encode ladder (render.variants). +// --------------------------------------------------------------------------- + +/** The ladder "Make variants" encodes when the manifest names none. */ +export const VARIANTS_DEFAULT = DEFAULT_VARIANTS; + +/** A variant's name, as the encoder's rule: what a file may be served by. */ +export const VARIANT_NAME_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; + +/** `render.variants`' problems: the encoder's validateVariants; null (remove it) has none. */ +export const variantsProblems = (v) => (v === null ? [] : validateVariants(v)); diff --git a/umtool/lib/report/knobs.test.mjs b/umtool/lib/report/knobs.test.mjs @@ -0,0 +1,211 @@ +// The video knobs' writers (plans/video-knobs-ui.md): a claim's stamp and +// count, a clip's sound, the fact-check's stamp, the deck's markers, the +// encode ladder -- each token-guarded, each refusal leaving the file as it was, +// and the variants/sync read-back. +// +// 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"; + +// The read-back resolves files inside the reports root: this suite's own. +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-knobs-")); +process.env.REPORTS_DIR = ROOT; + +const { + MANIFEST_NAME, + StaleToken, + StructureRefused, + manifestToken, + moveEntry, + updateClaimKnobs, + updateClip, + updateDeckMarkers, + updateFactcheck, + updateOnscreen, + updateVariants, +} = await import("./manifest.mjs"); +const knobs = await import("./knobs.mjs"); +const { variantsState, variantFile } = await import("./variantsView.mjs"); + +const base = () => ({ + slug: "t", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, transition: 0.5, chrome: { engine: "hyperframes", layout: "deck" } }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 20, claim: { id: "k1", verdict: "CONTRADICTED" } }, + { type: "clip", id: "c02", video: "v2", start: 30, end: 41, claim: { id: "k1", verdict: "CONTRADICTED" } }, + { type: "clip", id: "c03", video: "v3", start: 50, end: 55 }, + ], +}); + +let n = 0; +async function project(manifest = base()) { + const dir = path.join(ROOT, `p${(n += 1)}`); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return dir; +} +const readRaw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8"); +const read = async (dir) => JSON.parse(await readRaw(dir)); +const clip = (m, id) => m.timeline.find((e) => e.id === id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("updateClaimKnobs: sets each knob, says which entry stamps, clears with null and with the default", async () => { + const dir = await project(); + const r = await updateClaimKnobs(dir, "c02", { at: 35.123, hold: 4, stamp: false, count: 2, label: " 2 SEIZURES " }, { token: await manifestToken(dir) }); + assert.equal(r.stamps, true); + assert.equal(r.stampsOn, "c02"); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k1", verdict: "CONTRADICTED", at: 35.12, hold: 4, stamp: false, count: 2, label: "2 SEIZURES" }); + const r2 = await updateClaimKnobs(dir, "c02", { at: null, stamp: true, count: 1, label: "" }); + assert.deepEqual(r2.claim, { id: "k1", verdict: "CONTRADICTED", hold: 4 }); + // c01 carries the claim but does not stamp it: its knobs are inert, and the answer says so. + const r3 = await updateClaimKnobs(dir, "c01", { count: 3 }); + assert.equal(r3.stamps, false); + assert.equal(r3.stampsOn, "c02"); +}); + +test("updateClaimKnobs: refuses a bad value, an at outside the window, an entry with no claim, a stale token", async () => { + const dir = await project(); + const before = await readRaw(dir); + await assert.rejects(updateClaimKnobs(dir, "c02", { at: 50 }), /claim\.at 50 is outside the clip's window 30–41/); + await assert.rejects(updateClaimKnobs(dir, "c02", { hold: 0.2 }), /claim\.hold must be from 0\.5 to 10 seconds/); + await assert.rejects(updateClaimKnobs(dir, "c02", { count: 1.5 }), /whole number from 1 to 99/); + await assert.rejects(updateClaimKnobs(dir, "c02", { label: "x".repeat(21) }), /at most 20/); + await assert.rejects(updateClaimKnobs(dir, "c02", { colour: 1 }), /not a claim knob/); + await assert.rejects(updateClaimKnobs(dir, "c03", { count: 2 }), /carries no claim/); + await assert.rejects(updateClaimKnobs(dir, "nope", { count: 2 }), /no timeline entry/); + await assert.rejects(updateClaimKnobs(dir, "c02", { count: 2 }, { token: "1" }), StaleToken); + assert.equal(await readRaw(dir), before); +}); + +test("updateClaimKnobs: a variant's twin gets the same knobs", async () => { + const m = base(); + m.timeline.push({ type: "clip", id: "c02", variant: "full", video: "v2", start: 30, end: 41, claim: { id: "k1", verdict: "CONTRADICTED" } }); + const dir = await project(m); + await updateClaimKnobs(dir, "c02", { count: 2 }); + assert.deepEqual((await read(dir)).timeline.filter((e) => e.id === "c02").map((e) => e.claim.count), [2, 2]); +}); + +test("updateOnscreen: a row naming only id and verdict keeps the knobs; a new claim id drops them; a row with knobs replaces them", async () => { + const dir = await project(); + await updateClaimKnobs(dir, "c02", { count: 2, at: 33 }); + await updateOnscreen(dir, { c02: { title: "T", claim: { id: "k1", verdict: "CONTRADICTED" } } }); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k1", verdict: "CONTRADICTED", count: 2, at: 33 }); + await updateOnscreen(dir, { c02: { title: "T", claim: { id: "k1", verdict: "CONTRADICTED", hold: 2 } } }); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k1", verdict: "CONTRADICTED", hold: 2 }); + await updateOnscreen(dir, { c01: { claim: { id: "k9", verdict: "CONTRADICTED" } }, c02: { title: "T", claim: { id: "k9", verdict: "CONTRADICTED" } } }); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k9", verdict: "CONTRADICTED" }); + await assert.rejects(updateOnscreen(dir, { c02: { claim: { id: "k9", verdict: "CONTRADICTED", count: 0 } } }), /claim\.count/); +}); + +test("updateClip audio: merged per key, rounded, a 0 or null removes a key, null removes all; out of range is refused", async () => { + const dir = await project(); + await updateClip(dir, "c03", { audio: { offset: -68.4, gain: 1.26 } }); + assert.deepEqual(clip(await read(dir), "c03").audio, { offset: -68, gain: 1.3 }); + await updateClip(dir, "c03", { audio: { fadeIn: 0.333, gain: null } }); + assert.deepEqual(clip(await read(dir), "c03").audio, { offset: -68, fadeIn: 0.33 }); + await updateClip(dir, "c03", { audio: { offset: 0, fadeIn: 0 } }); + assert.equal("audio" in clip(await read(dir), "c03"), false); + await updateClip(dir, "c03", { audio: { offset: 40 } }); + await updateClip(dir, "c03", { audio: null }); + assert.equal("audio" in clip(await read(dir), "c03"), false); + const before = await readRaw(dir); + await assert.rejects(updateClip(dir, "c03", { audio: { offset: 2500 } }), /offset must be a number from -2000 to 2000/); + await assert.rejects(updateClip(dir, "c03", { audio: { pan: 1 } }), /not an audio setting/); + await assert.rejects(updateClip(dir, "c03", { audio: 3 }), /audio must be/); + assert.equal(await readRaw(dir), before); +}); + +test("updateClip: a window that leaves claim.at outside is refused", async () => { + const dir = await project(); + await updateClaimKnobs(dir, "c02", { at: 31 }); + await assert.rejects(updateClip(dir, "c02", { start: 32 }), /claim\.at 31\) must lie inside the window 32–41/); + await updateClip(dir, "c02", { start: 30.5 }); +}); + +test("updateFactcheck: stamp scale, motion, opacity and a verdict's stampLabel; refused out of range", async () => { + const dir = await project(); + const r = await updateFactcheck(dir, { stamp: { scale: 1.4, motion: "pop", opacity: 0.8 }, verdicts: { CONTRADICTED: { label: "Seizures", stampLabel: "SEIZURE" } } }, { token: await manifestToken(dir) }); + assert.deepEqual(r.factcheck.stamp, { scale: 1.4, motion: "pop", opacity: 0.8 }); + assert.equal((await read(dir)).render.chrome.factcheck.verdicts.CONTRADICTED.stampLabel, "SEIZURE"); + const before = await readRaw(dir); + await assert.rejects(updateFactcheck(dir, { stamp: { motion: "spin" } }), (e) => e instanceof StructureRefused && /stamp\.motion/.test(e.message)); + await assert.rejects(updateFactcheck(dir, { stamp: { scale: 3 } }), /stamp\.scale must be from 0\.5 to 2/); + await assert.rejects(updateFactcheck(dir, { stamp: { opacity: 0.1 } }), /stamp\.opacity must be from 0\.3 to 1/); + await assert.rejects(updateFactcheck(dir, { verdicts: { CONTRADICTED: { stampLabel: "x".repeat(30) } } }), /stampLabel is 30 characters/); + assert.equal(await readRaw(dir), before); +}); + +test("updateDeckMarkers: sets the list (align auto dropped) and the layout, leaves the rest of the deck, refuses bad ones", async () => { + const m = base(); + m.render.chrome.deck = { height: 300 }; + const dir = await project(m); + const r = await updateDeckMarkers(dir, { markers: [{ after: "c01", label: " Arrival ", color: "", align: "auto" }, { after: "c02", label: "Rescue", color: "accent", align: "right" }], markerLayout: "truncate" }, { token: await manifestToken(dir) }); + assert.deepEqual(r.markers, [{ after: "c01", label: "Arrival" }, { after: "c02", label: "Rescue", color: "accent", align: "right" }]); + const deck = (await read(dir)).render.chrome.deck; + assert.equal(deck.height, 300); + assert.equal(deck.markerLayout, "truncate"); + const before = await readRaw(dir); + await assert.rejects(updateDeckMarkers(dir, { markers: [{ after: "c01", label: "x", align: "middle" }] }), /align must be/); + await assert.rejects(updateDeckMarkers(dir, { markerLayout: "wrap" }), /markerLayout must be/); + await assert.rejects(updateDeckMarkers(dir, { markers: [{ after: "zz", label: "x" }] }), /zz/); + await assert.rejects(updateDeckMarkers(dir, { markers: [{ after: "c01", label: "x".repeat(25) }] }), /at most 24/); + await assert.rejects(updateDeckMarkers(dir, { markers: Array.from({ length: 13 }, () => ({ after: "c01", label: "x" })) }), /at most 12/); + assert.equal(await readRaw(dir), before); + await updateDeckMarkers(dir, { markers: [], markerLayout: null }); + const after = (await read(dir)).render.chrome.deck; + assert.equal("markers" in after, false); + assert.equal("markerLayout" in after, false); +}); + +test("a structural edit works on a manifest carrying knobs", async () => { + const m = base(); + m.render.chrome.deck = { markers: [{ after: "c01", label: "A", align: "left" }], markerLayout: "stagger" }; + m.timeline[1].claim = { id: "k1", verdict: "CONTRADICTED", count: 2, at: 33 }; + const dir = await project(m); + await moveEntry(dir, "c03", 0, { token: await manifestToken(dir) }); + assert.deepEqual((await read(dir)).timeline.map((e) => e.id), ["c03", "c01", "c02"]); +}); + +test("updateVariants: sets the ladder, null restores the default, a bad ladder is refused", async () => { + const dir = await project(); + await updateVariants(dir, [{ name: "master" }, { name: "4k", height: 2160, crf: 18 }, { name: "fit8", maxMiB: 8 }]); + assert.equal((await read(dir)).render.variants.length, 3); + await assert.rejects(updateVariants(dir, [{ name: "x", maxMiB: 8, crf: 20 }]), /takes no crf/); + await assert.rejects(updateVariants(dir, [{ name: "a", height: 720 }, { name: "a", height: 480 }]), /used twice/); + await assert.rejects(updateVariants(dir, [{ name: "A b" }]), /name must be/); + await assert.rejects(updateVariants(dir, [{ name: "master", crf: 20 }]), /master/); + await updateVariants(dir, null); + assert.equal("variants" in (await read(dir)).render, false); +}); + +test("knobs: normalizeClaimKnobPatch and the problems lists", () => { + assert.deepEqual(knobs.normalizeClaimKnobPatch({ at: "12.345", stamp: "false", count: "2" }), { at: 12.35, stamp: false, count: 2 }); + assert.deepEqual(knobs.normalizeClaimKnobPatch({ stamp: true, count: 1 }), { stamp: null, count: null }); + assert.throws(() => knobs.normalizeClaimKnobPatch({}), /nothing to change/); + assert.deepEqual(knobs.variantsProblems(knobs.VARIANTS_DEFAULT), []); + assert.equal(knobs.stampingEntryId({ timeline: [{ id: "a", claim: { id: "k" } }, { id: "b", claim: { id: "k" } }, { id: "c", variant: "full", claim: { id: "k" } }] }, "k", "sourced"), "b"); +}); + +test("variantsState: the build, the variants made, the sync report with the lags past a frame flagged", async () => { + const dir = await project(); + const out = path.join(dir, "out"); + await mkdir(path.join(out, "sourced"), { recursive: true }); + await writeFile(path.join(out, "t.mp4"), "x".repeat(100)); + await writeFile(path.join(out, "t.720p.mp4"), "x".repeat(40)); + await writeFile(path.join(out, "variants.json"), JSON.stringify({ at: new Date(Date.now() + 5000).toISOString(), source: "t.mp4", items: [{ name: "720p", path: "t.720p.mp4", width: 1280, height: 720, bytes: 40, kbps: 900 }, { name: "../evil", path: "x" }] })); + await writeFile(path.join(out, "sourced", "sync.json"), JSON.stringify({ fps: 30, items: [{ id: "c01", start: 0, lagMs: 0, peak: 0.9 }, { id: "c02", start: 9.5, lagMs: -469, peak: 0.8 }] })); + const s = await variantsState({ id: "p", dir }, await read(dir)); + assert.equal(s.built.size, 100); + assert.equal(s.ladderIsDefault, true); + assert.deepEqual(s.made.items.map((i) => [i.name, i.exists, i.bytes]), [["720p", true, 40]]); + assert.equal(s.stale, false); + assert.deepEqual(s.sync.items.map((i) => [i.id, i.flagged, i.clip]), [["c01", false, true], ["c02", true, true]]); + assert.equal((await variantFile({ dir }, { slug: "t" }, "720p"))?.size, 40); + assert.equal(await variantFile({ dir }, { slug: "t" }, "../t"), null); + await assert.rejects(variantsState({ id: "p", dir }, await read(dir), "../x"), /not a take id/); +}); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -0,0 +1,377 @@ +// THE VIDEO KNOBS FROM A TERMINAL (plans/video-knobs-ui.md): every knob a +// person sets in umtool, an agent sets here -- through the SAME writers +// (lib/report/manifest.mjs) and the same generated-manifest guard +// (edit-guard.mjs), each write carrying the token read from the file just +// before it, so a write here beside an open page is refused rather than lost. +// +// umtool set <project> <clip> key=value … claim.at claim.hold claim.stamp claim.count claim.label +// audio.offset audio.gain audio.fadeIn audio.fadeOut +// umtool look <project> key=value … factcheck.stamp.<k>, factcheck.verdicts.<V>.<k>, +// deck.markers=<json>, deck.markerLayout=…, variants=<json>, +// and the look's keys (transition=0.3, …) +// umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder (or list it) +// +// `key=` (nothing after the =) clears the key: the default again. A value is +// read as JSON when it parses (2, true, [..], {..}), else as text. +// +// Plain ESM: the CLI runs under bare node. +import { spawn } from "node:child_process"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { + LOOK_KEYS, + manifestToken, + updateClaimKnobs, + updateClip, + updateDeckKeys, + updateFactcheck, + updateRender, + updateVariants, +} from "./manifest.mjs"; +import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, stampingEntryId, variantsOf } from "./knobs.mjs"; +import { variantsSteps } from "./driver.mjs"; +import { outDirOf, variantsState } from "./variantsView.mjs"; + +export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]); +const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...AUDIO_KNOBS.map((k) => `audio.${k}`), "layout"]; + +export const SET_USAGE = [ + "usage: umtool set <project> <clip> key=value … [--json]", + ` keys: ${SET_KEYS.join(" ")}`, + " claim.at is a SOURCE second inside the clip's window: the stamp lands and the count steps there", + " (read from the last clip carrying the claim); claim.hold s (0.5–10); claim.stamp true|false;", + " claim.count 1–99; claim.label ≤ 20 chars. audio.offset ms (-2000…2000, + = sound later),", + " audio.gain dB (-20…20), audio.fadeIn / audio.fadeOut s (0–5). layout=finale|clip (the deck's finale", + " layout for this clip; clip is the default). `key=` clears it (the default).", +].join("\n"); + +export const LOOK_USAGE = [ + "usage: umtool look <project> key=value … [--json]", + " factcheck.stamp.scale (0.5–2) .motion (slam|pop|fade|none) .opacity (0.3–1) .seconds .show .position", + " factcheck.verdicts.<VERDICT>.stampLabel | .label | .color", + " deck.markers='[{\"after\":\"c01\",\"label\":\"Arrival\",\"align\":\"left\"}]' deck.markerLayout=stagger|truncate", + " deck.<key>=<json>: any of the deck's own keys (deck.finale='{…}', deck.pip='{…}', …), checked by the build's rules", + " variants='[{\"name\":\"master\"},{\"name\":\"720p\",\"height\":720,\"crf\":23},{\"name\":\"fit24\",\"maxMiB\":24}]'", + ` the look: ${LOOK_KEYS.join(", ")} (a JSON value each)`, + " `key=` clears it (the default).", +].join("\n"); + +class CliError extends Error {} + +/** `a=b` words into [key, value]: JSON when it parses, else the text; `a=` is null (clear). */ +export function parseAssignments(words) { + return words.map((w) => { + const i = w.indexOf("="); + if (i <= 0) throw new CliError(`not key=value: ${w}`); + const key = w.slice(0, i); + const raw = w.slice(i + 1); + if (raw === "") return [key, null]; + try { + return [key, JSON.parse(raw)]; + } catch { + return [key, raw]; + } + }); +} + +async function projectOf(arg, root) { + if (!arg) throw new CliError("which project?"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${arg}"`); + return r.project; +} + +const splitArgs = (args) => { + const words = []; + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--take") { + flags.set(a, args[i + 1] ?? ""); + i += 1; + } else if (a.startsWith("--")) flags.set(a, true); + else words.push(a); + } + return { words, flags }; +}; + +const noted = (editNotes) => + !editNotes + ? "" + : editNotes.errors.length + ? ` edit NOT noted (${editNotes.errors.join("; ")}) — ${editNotes.generatedBy} will overwrite it on the next rebuild` + : ` edit noted for ${editNotes.generatedBy} — port it into the generator's inputs`; + +/** + * `umtool set <project> <clip> key=value …` + * @param {string[]} args the words after `set` + * @returns {Promise<number>} + */ +export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + const { words, flags } = splitArgs(args); + const json = flags.has("--json"); + try { + const [projectArg, clipId, ...rest] = words; + if (!projectArg || !clipId || !rest.length || flags.has("--help")) { + err(SET_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + const claim = {}; + const audio = {}; + /** @type {Record<string, unknown>} */ + const entryPatch = {}; + for (const [key, value] of parseAssignments(rest)) { + if (!SET_KEYS.includes(key)) throw new CliError(`${key} is not a clip knob (${SET_KEYS.join(", ")})`); + if (key === "layout") { + entryPatch.layout = value; + continue; + } + const [group, k] = key.split("."); + (group === "claim" ? claim : audio)[k] = value; + } + if (Object.keys(audio).length) entryPatch.audio = audio; + const results = {}; + let notes = null; + if (Object.keys(claim).length) { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => updateClaimKnobs(project.dir, clipId, claim, { token })); + results.claim = result.claim; + results.stamps = result.stamps; + results.stampsOn = result.stampsOn; + notes = editNotes; + } + if (Object.keys(entryPatch).length) { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => updateClip(project.dir, clipId, entryPatch, { token, edit: "trim" })); + if ("audio" in entryPatch) results.audio = result.entry.audio ?? null; + if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip"; + notes = editNotes ?? notes; + } + if (json) { + out(JSON.stringify({ ok: true, clip: clipId, ...results, editNotes: notes }, null, 2)); + return 0; + } + if (results.claim) { + out(`${clipId}: claim ${JSON.stringify(results.claim)}`); + if (!results.stamps) out(` NOTE: ${results.claim.id} stamps on ${results.stampsOn} (the last clip carrying it) — these knobs are read there, not here`); + } + if ("audio" in results) out(`${clipId}: audio ${results.audio ? JSON.stringify(results.audio) : "as recorded"}`); + if ("layout" in results) out(`${clipId}: layout ${results.layout}`); + const n = noted(notes); + if (n) out(n); + return 0; + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** Set (or with null, remove) `a.b.c` in a copy of `obj`, pruning objects left empty. */ +function setPath(obj, keys, value) { + const root = structuredClone(isObj(obj) ? obj : {}); + const stack = [root]; + let at = root; + for (const k of keys.slice(0, -1)) { + if (!isObj(at[k])) at[k] = {}; + at = at[k]; + stack.push(at); + } + const last = keys[keys.length - 1]; + if (value === null) delete at[last]; + else at[last] = value; + for (let i = keys.length - 1; i > 0; i -= 1) { + if (Object.keys(stack[i]).length) break; + delete stack[i - 1][keys[i - 1]]; + } + return root; +} + +/** + * `umtool look <project> key=value …` + * @param {string[]} args the words after `look` + * @returns {Promise<number>} + */ +export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + const { words, flags } = splitArgs(args); + const json = flags.has("--json"); + try { + const [projectArg, ...rest] = words; + if (!projectArg || !rest.length || flags.has("--help")) { + err(LOOK_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + const pairs = parseAssignments(rest); + const fc = pairs.filter(([k]) => k.startsWith("factcheck.")); + const deck = pairs.filter(([k]) => k.startsWith("deck.")); + const variants = pairs.filter(([k]) => k === "variants"); + const look = pairs.filter(([k]) => LOOK_KEYS.includes(k)); + const unknown = pairs.filter(([k]) => !k.startsWith("factcheck.") && !k.startsWith("deck.") && k !== "variants" && !LOOK_KEYS.includes(k)); + if (unknown.length) throw new CliError(`not a knob here: ${unknown.map(([k]) => k).join(", ")}\n\n${LOOK_USAGE}`); + for (const [k] of deck) if (k.split(".").length !== 2 || !k.split(".")[1]) throw new CliError(`${k}: name one of the deck's own keys (deck.<key>=<json>)`); + const done = {}; + let notes = null; + const write = async (fn) => { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => fn(token)); + notes = editNotes ?? notes; + return result; + }; + if (fc.length) { + const m = await readManifest(project.dir); + let next = m?.render?.chrome?.factcheck ?? {}; + for (const [k, v] of fc) next = setPath(next, k.split(".").slice(1), v); + const r = await write((token) => updateFactcheck(project.dir, Object.keys(next).length ? next : null, { token })); + done.factcheck = r.factcheck; + } + if (deck.length) { + const patch = {}; + for (const [k, v] of deck) patch[k.slice("deck.".length)] = v; + const r = await write((token) => updateDeckKeys(project.dir, patch, { token })); + for (const k of Object.keys(patch)) done[`deck.${k}`] = r.deck[k] ?? null; + } + if (variants.length) { + const r = await write((token) => updateVariants(project.dir, variants[0][1], { token })); + done.variants = r.variants; + } + if (look.length) { + const r = await write((token) => updateRender(project.dir, Object.fromEntries(look), { token })); + done.look = r.look; + } + if (json) out(JSON.stringify({ ok: true, ...done, editNotes: notes }, null, 2)); + else { + for (const [k, v] of Object.entries(done)) out(`${k}: ${v === null || v === undefined ? "(default)" : JSON.stringify(v)}`); + const n = noted(notes); + if (n) out(n); + } + return 0; + } catch (e) { + err(e instanceof Error ? (e.errors ? e.errors.join("\n") : e.message) : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +const mib = (b) => (typeof b === "number" ? `${(b / 1048576).toFixed(1)} MiB` : "–"); + +function printState(s, out) { + out(`${s.take ? `take ${s.take}` : "the project's build"}: ${s.built ? `${mib(s.built.size)}, built ${new Date(s.built.mtimeMs).toISOString()}` : "NOT BUILT"}`); + out(`ladder (${s.ladderIsDefault ? "default" : "render.variants"}): ${s.ladder.map((v) => v.name).join(", ")}`); + if (s.made) { + out(`made ${s.made.at ?? ""}${s.stale ? " (from an OLDER build — make them again)" : ""}`); + for (const m of s.made.items) out(` ${m.name.padEnd(10)} ${m.width ?? "?"}x${m.height ?? "?"} ${mib(m.bytes).padStart(10)} ${m.kbps ?? "?"} kb/s${m.exists ? "" : " GONE"}`); + } + if (s.sync) { + const bad = s.sync.items.filter((x) => x.flagged); + out(`sync (${s.sync.items.length} clips, one frame = ${s.sync.frameMs} ms): ${bad.length ? `${bad.length} past a frame` : "every clip within a frame"}`); + for (const x of bad) out(` ${x.id.padEnd(10)} ${x.lagMs > 0 ? "+" : ""}${Math.round(x.lagMs)} ms → umtool set <project> ${x.id} audio.offset=…`); + } else out("sync: no report (the build writes sourced/sync.json)"); +} + +/** + * `umtool variants <project> [--take <t>] [--list] [--json]` + * @param {string[]} args the words after `variants` + * @returns {Promise<number>} + */ +export async function variantsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), env = process.env } = {}) { + const { words, flags } = splitArgs(args); + const json = flags.has("--json"); + try { + const [projectArg] = words; + if (!projectArg || flags.has("--help")) { + err("usage: umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (--list: what was made, and the sync report)"); + return 2; + } + const project = await projectOf(projectArg, root); + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError("no manifest"); + const take = typeof flags.get("--take") === "string" && flags.get("--take") ? String(flags.get("--take")) : null; + const before = await variantsState(project, manifest, take); + if (!flags.has("--list")) { + if (!before.built) throw new CliError(take ? `take ${take} has no build to make variants of` : "this cut has not been built yet — build it first"); + const [step] = variantsSteps(project, outDirOf(project, take), env); + const log = json ? (s) => err(s) : out; + log(`$ ${step.argv.join(" ")}`); + const code = await new Promise((resolve) => { + const child = spawn(process.execPath, step.argv.slice(1), { cwd: step.cwd, stdio: ["ignore", json ? "pipe" : "inherit", "inherit"] }); + if (json) child.stdout?.on("data", (b) => err(String(b).trimEnd())); + child.on("error", () => resolve(1)); + child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); + }); + if (code !== 0) { + err(`the encoder exited ${code}`); + return 1; + } + } + const s = await variantsState(project, manifest, take); + if (json) out(JSON.stringify(s, null, 2)); + else printState(s, out); + return 0; + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +/** + * The knobs a manifest sets, for `umtool show`: per clip (claim knobs, audio), + * the fact-check's stamp, the deck's markers, the ladder. + * @param {Record<string, any>} manifest + */ +export function knobsOf(manifest) { + const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const clips = []; + for (const e of timeline) { + if (!isObj(e)) continue; + const claim = isObj(e.claim) ? Object.fromEntries(CLAIM_KNOBS.filter((k) => e.claim[k] !== undefined).map((k) => [k, e.claim[k]])) : null; + const audio = isObj(e.audio) ? e.audio : null; + if ((claim && Object.keys(claim).length) || audio || isObj(e.claim) || typeof e.layout === "string") { + clips.push({ + id: e.id, + ...(e.variant ? { variant: e.variant } : {}), + ...(isObj(e.claim) ? { claimId: e.claim.id, verdict: e.claim.verdict, stamps: stampingEntryId(manifest, e.claim.id) === e.id } : {}), + ...(claim && Object.keys(claim).length ? { claim } : {}), + ...(audio ? { audio } : {}), + ...(typeof e.layout === "string" ? { layout: e.layout } : {}), + }); + } + } + const fc = manifest?.render?.chrome?.factcheck; + const stamp = isObj(fc?.stamp) ? Object.fromEntries(Object.entries(fc.stamp).filter(([k]) => k in STAMP_KNOB_DEFAULTS)) : {}; + const stampLabels = isObj(fc?.verdicts) ? Object.fromEntries(Object.entries(fc.verdicts).filter(([, v]) => isObj(v) && typeof v.stampLabel === "string").map(([k, v]) => [k, v.stampLabel])) : {}; + const deck = manifest?.render?.chrome?.deck; + return { + clips, + stamp, + stampLabels, + markers: Array.isArray(deck?.markers) ? deck.markers : [], + markerLayout: deck?.markerLayout ?? null, + variants: variantsOf(manifest?.render), + variantsDefault: !Array.isArray(manifest?.render?.variants), + }; +} + +/** `umtool show`'s knobs block, as lines. */ +export function knobsLines(manifest) { + const k = knobsOf(manifest); + const lines = []; + for (const c of k.clips) { + const bits = []; + if (c.claimId) bits.push(`claim ${c.claimId} ${c.verdict}${c.stamps ? " (stamps here)" : ""}`); + if (c.claim) bits.push(Object.entries(c.claim).map(([a, b]) => `${a}=${JSON.stringify(b)}`).join(" ")); + if (c.layout) bits.push(`layout ${c.layout}`); + if (c.audio) bits.push(`audio ${Object.entries(c.audio).map(([a, b]) => `${a}=${b}`).join(" ")}`); + lines.push(` ${String(c.id).padEnd(8)} ${bits.join(" · ")}`); + } + if (Object.keys(k.stamp).length) lines.push(` stamp ${Object.entries(k.stamp).map(([a, b]) => `${a}=${b}`).join(" ")}`); + if (Object.keys(k.stampLabels).length) lines.push(` stamp word ${Object.entries(k.stampLabels).map(([a, b]) => `${a}=${b}`).join(" ")}`); + if (k.markers.length) lines.push(` markers ${k.markers.map((m) => `${m.after}:"${m.label}"${m.align ? `(${m.align})` : ""}`).join(" ")}${k.markerLayout ? ` · layout ${k.markerLayout}` : ""}`); + lines.push(` variants ${k.variants.map((v) => v.name).join(", ")}${k.variantsDefault ? " (default)" : ""}`); + return lines; +} + +export { VARIANTS_DEFAULT }; diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs @@ -0,0 +1,126 @@ +// `umtool set`, `umtool look`, `umtool variants` and the knobs `umtool show` +// prints (plans/video-knobs-ui.md): the same writers the UI uses, from a +// terminal; the encoder stubbed (e2e/fixtures/variants.e2e.mjs). +// +// 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 { fileURLToPath } from "node:url"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-knobs-cli-")); +process.env.REPORTS_DIR = ROOT; +const { knobsLines, knobsOf, lookCommand, parseAssignments, setCommand, variantsCommand } = await import("./knobsCli.mjs"); + +const STUB = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "e2e", "fixtures", "variants.e2e.mjs"); + +const MANIFEST = { + schemaVersion: 1, + slug: "huck", + title: "Huck", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, chrome: { engine: "hyperframes", layout: "deck" } }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 20, claim: { id: "k1", verdict: "CONTRADICTED" } }, + { type: "clip", id: "c02", video: "v2", start: 30, end: 41 }, + ], +}; + +async function project(name) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n"); + return dir; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); +const runner = (fn) => { + const lines = []; + return { lines, run: (...args) => fn(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }) }; +}; + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("parseAssignments: JSON when it parses, text otherwise, empty clears", () => { + assert.deepEqual(parseAssignments(["a=2", "b=true", "c=SEIZURE", "d=", 'e=[{"x":1}]']), [["a", 2], ["b", true], ["c", "SEIZURE"], ["d", null], ["e", [{ x: 1 }]]]); + assert.throws(() => parseAssignments(["nope"]), /not key=value/); +}); + +test("umtool set: claim and audio knobs through the writers; key= clears; a bad key or value is refused", async () => { + const dir = await project("set"); + const { lines, run } = runner(setCommand); + assert.equal(await run("set", "c01", "claim.at=15.5", "claim.count=2", "claim.label=2 SEIZURES", "audio.offset=-40"), 0); + let c = (await read(dir)).timeline[0]; + assert.deepEqual(c.claim, { id: "k1", verdict: "CONTRADICTED", at: 15.5, count: 2, label: "2 SEIZURES" }); + assert.deepEqual(c.audio, { offset: -40 }); + assert.equal(await run("set", "c01", "claim.count=", "audio.offset="), 0); + c = (await read(dir)).timeline[0]; + assert.deepEqual(c.claim, { id: "k1", verdict: "CONTRADICTED", at: 15.5, label: "2 SEIZURES" }); + assert.equal("audio" in c, false); + assert.equal(await run("set", "c01", "claim.colour=1"), 2); + assert.match(lines.at(-1), /not a clip knob/); + assert.equal(await run("set", "c01", "claim.at=99"), 1); + assert.match(lines.at(-1), /is outside the clip's window/); + assert.equal(await run("set", "c02", "claim.count=2"), 1); + assert.match(lines.at(-1), /carries no claim/); + assert.equal(await run("set"), 2); + // The deck's finale layout for a clip: finale, or clip (the default: the key removed). + assert.equal(await run("set", "c02", "layout=finale"), 0); + assert.equal((await read(dir)).timeline[1].layout, "finale"); + assert.equal(await run("set", "c02", "layout=clip"), 0); + assert.equal("layout" in (await read(dir)).timeline[1], false); + assert.equal(await run("set", "c02", "layout=wide"), 1); + assert.match(lines.at(-1), /layout must be/); +}); + +test("umtool look: the fact-check's stamp, a verdict's stamp word, markers, layout, the ladder, a look key", async () => { + const dir = await project("look"); + const { lines, run } = runner(lookCommand); + assert.equal(await run("look", "factcheck.stamp.scale=1.3", "factcheck.stamp.motion=pop", "factcheck.verdicts.CONTRADICTED.stampLabel=SEIZURE"), 0); + let m = await read(dir); + assert.deepEqual(m.render.chrome.factcheck, { stamp: { scale: 1.3, motion: "pop" }, verdicts: { CONTRADICTED: { stampLabel: "SEIZURE" } } }); + assert.equal(await run("look", "factcheck.stamp.scale=", "factcheck.stamp.motion="), 0); + m = await read(dir); + assert.deepEqual(m.render.chrome.factcheck, { verdicts: { CONTRADICTED: { stampLabel: "SEIZURE" } } }); + assert.equal(await run("look", 'deck.markers=[{"after":"c01","label":"Arrival","align":"left"}]', "deck.markerLayout=truncate"), 0); + m = await read(dir); + assert.deepEqual(m.render.chrome.deck, { markers: [{ after: "c01", label: "Arrival", align: "left" }], markerLayout: "truncate" }); + assert.equal(await run("look", 'variants=[{"name":"master"},{"name":"480p","height":480,"crf":26}]', "transition=0.3"), 0); + m = await read(dir); + assert.deepEqual(m.render.variants, [{ name: "master" }, { name: "480p", height: 480, crf: 26 }]); + assert.equal(m.render.transition, 0.3); + assert.equal(await run("look", "factcheck.stamp.motion=spin"), 1); + assert.match(lines.at(-1), /stamp\.motion/); + // Any of the deck's own keys, checked by the build's rules (an unknown one is refused in its words). + assert.equal(await run("look", 'deck.pip={"color":"verdict"}'), 0, lines.join("\n")); + assert.deepEqual((await read(dir)).render.chrome.deck.pip, { color: "verdict" }); + assert.equal(await run("look", "deck.nope=1"), 1); + assert.match(lines.at(-1), /nope/); + assert.equal(await run("look", "deck=1"), 2); + assert.equal(await run("look", "nope=1"), 2); + // what `umtool show` prints + const k = knobsOf(m); + assert.equal(k.markers.length, 1); + assert.deepEqual(k.stampLabels, { CONTRADICTED: "SEIZURE" }); + assert.ok(knobsLines(m).some((l) => /variants\s+master, 480p$/.test(l))); +}); + +test("umtool variants: refuses an unbuilt cut; makes the ladder (stub encoder) and lists it with the sync report", async () => { + const dir = await project("vars"); + const { lines, run } = runner((args, o) => variantsCommand(args, { ...o, env: { ...process.env, E2E_UMTOOL_VARIANTS_SCRIPT: STUB } })); + assert.equal(await run("vars"), 2); + assert.match(lines.at(-1), /not been built/); + await mkdir(path.join(dir, "out", "sourced"), { recursive: true }); + await writeFile(path.join(dir, "out", "huck.mp4"), Buffer.alloc(4096, 1)); + await writeFile(path.join(dir, "out", "sourced", "sync.json"), JSON.stringify({ fps: 30, items: [{ id: "c01", start: 0, lagMs: -68, peak: 0.9 }] })); + lines.length = 0; + assert.equal(await run("vars"), 0); + assert.ok(lines.some((l) => /^ {2}fit24 /.test(l)), lines.join("\n")); + assert.ok(lines.some((l) => /c01 +-68 ms/.test(l)), lines.join("\n")); + lines.length = 0; + assert.equal(await run("vars", "--list", "--json"), 0); + const s = JSON.parse(lines.join("\n")); + assert.deepEqual(s.made.items.map((i) => i.name), ["master", "1080p", "720p", "fit24"]); + assert.equal(s.sync.items[0].flagged, true); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -38,6 +38,8 @@ import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/ import { validateRoom } from "umtool-report-to-video/room"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; +import { validateClipAudio } from "umtool-report-to-video/clip-audio"; +import { CLAIM_KNOBS, claimKnobsOf, claimKnobValue, normalizeClaimKnobPatch, stampingEntryId, variantsProblems } from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; import { parseMuteFrom } from "./playback.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; @@ -339,6 +341,61 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri } } + // ---- a claim's `at` stays inside the window (video knobs) --------------- + // + // The source second its stamp lands, on the entry's clock: a window save + // that leaves it outside is refused, as the mute mark's is, rather than + // keeping a mark that no longer says anything about the clip. + if ((patch.start !== undefined || patch.end !== undefined) && isObj(entry.claim) && typeof entry.claim.at === "number") { + if (entry.claim.at < entry.start || entry.claim.at > entry.end) { + throw new Error( + `the stamp's second (claim.at ${entry.claim.at}) must lie inside the window ` + + `${entry.start}–${entry.end} — widen the window, or clear claim.at`, + ); + } + } + + // ---- the clip's sound (video knobs) ------------------------------------- + // + // `audio: { offset, gain, fadeIn, fadeOut }` -- applied at the segment + // encode (report-to-video clip-audio.mjs, whose validateClipAudio is the + // check). Each key is merged into what the clip has; a key set to null + // removes it, and `audio: null` (or "") removes them all. A key at 0 is + // removed (0 is what absent says), and nothing left removes `audio`: + // absent is the build as it always was. + if (patch.audio !== undefined) { + const v = patch.audio; + if (v === null || v === "") delete entry.audio; + else { + if (!isObj(v)) throw new Error("audio must be { offset?, gain?, fadeIn?, fadeOut? }, or null to clear it"); + const next = { ...(isObj(entry.audio) ? entry.audio : {}) }; + for (const [k, x] of Object.entries(v)) { + if (x === null || x === "") delete next[k]; + else next[k] = typeof x === "string" ? Number(x) : x; + } + const errors = validateClipAudio(next); + if (errors.length) throw new Error(errors.join("; ")); + if (typeof next.offset === "number") next.offset = Math.round(next.offset); + if (typeof next.gain === "number") next.gain = Number(next.gain.toFixed(1)); + for (const k of ["fadeIn", "fadeOut"]) if (typeof next[k] === "number") next[k] = round2(next[k]); + for (const k of Object.keys(next)) if (next[k] === 0) delete next[k]; + if (Object.keys(next).length) entry.audio = next; + else delete entry.audio; + } + } + + // ---- how the deck lays this entry out ----------------------------------- + // + // `layout: "finale"` (the deck's finale layout, render.chrome.deck.finale); + // "clip" -- the default -- or null/"" removes the key. Only these two: a + // layout the deck does not draw is refused here, not at the build. + if (patch.layout !== undefined) { + const v = patch.layout; + if (v === null || v === "" || v === "clip") delete entry.layout; + else if (v === "finale") entry.layout = "finale"; + else throw new Error(`layout must be "finale" or "clip" (the default), not ${JSON.stringify(v)}`); + } + // ---- the walk's verdict ------------------------------------------------- // // Whether somebody has LOOKED at this clip and said the description is what @@ -762,6 +819,12 @@ function setOnscreen(entry, value) { } /** + * An entry's fact-check claim (factcheck.mjs normalizeClaim): its id and + * verdict, and the stamp's knobs on the entry that stamps it (video knobs). + * @typedef {{ id: string, verdict: string, at?: number, hold?: number, stamp?: false, count?: number, label?: string }} Claim + */ + +/** * A row of the On-screen table split into its two keys: the entry's * `onscreen` text, normalised (null: delete it), and -- only when the row * names one -- its fact-check `claim` (`{ id, verdict }`, or null to delete @@ -769,13 +832,29 @@ function setOnscreen(entry, value) { * alone. Throws on a value either normaliser refuses. * * @param {unknown} row - * @returns {{ onscreen: { title?: string, subtitle?: string } | null, claim?: { id: string, verdict: string } | null }} + * @returns {{ onscreen: { title?: string, subtitle?: string } | null, claim?: Claim | null }} */ export function splitOnscreenRow(row) { if (row === null || row === undefined || typeof row !== "object" || Array.isArray(row) || !("claim" in row)) { return { onscreen: normalizeOnscreen(row) }; } const { claim, ...text } = /** @type {Record<string, unknown>} */ (row); + // A claim's knobs (at, hold, stamp, count, label) may ride on the row: each + // checked here (knobs.mjs), the id and verdict by the renderer's normalizeClaim. + // Such a row REPLACES the entry's knobs; a row without them keeps them. + if (isObj(claim) && CLAIM_KNOBS.some((k) => k in claim)) { + const base = { ...claim }; + /** @type {Record<string, unknown>} */ + const knobs = {}; + for (const k of CLAIM_KNOBS) { + if (!(k in base)) continue; + const v = claimKnobValue(k, base[k]); + delete base[k]; + if (v !== null && !(k === "stamp" && v === true) && !(k === "count" && v === 1)) knobs[k] = v; + } + const c = normalizeClaim(base); + return { onscreen: normalizeOnscreen(text), claim: c ? { ...c, ...knobs } : c, knobs: true }; + } return { onscreen: normalizeOnscreen(text), claim: normalizeClaim(claim) }; } @@ -797,10 +876,10 @@ export function splitOnscreenRow(row) { * included: an entry only the `full` cut shows still has a title. * * @param {string} dir - * @param {Record<string, { title?: string, subtitle?: string, claim?: { id: string, verdict: string } | null } | null>} onscreen + * @param {Record<string, { title?: string, subtitle?: string, claim?: Claim | null } | null>} onscreen * @param {{ token?: string | null }} [opts] * @returns {Promise<{ onscreen: Record<string, { title?: string, subtitle?: string } | null>, - * claims: Record<string, { id: string, verdict: string } | null>, token: string | null }>} + * claims: Record<string, Claim | null>, token: string | null }>} */ export async function updateOnscreen(dir, onscreen, { token = null } = {}) { if (!onscreen || typeof onscreen !== "object" || Array.isArray(onscreen)) { @@ -812,13 +891,16 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) { // file says, and refusing it needs no read. /** @type {Record<string, { title?: string, subtitle?: string } | null>} */ const next = {}; - /** @type {Record<string, { id: string, verdict: string } | null>} */ + /** @type {Record<string, Claim | null>} */ const claims = {}; + /** The rows whose claim names its knobs: those REPLACE the entry's; any other keeps them. */ + const withKnobs = new Set(); for (const id of ids) { try { const row = splitOnscreenRow(onscreen[id]); next[id] = row.onscreen; if (row.claim !== undefined) claims[id] = row.claim; + if (row.knobs) withKnobs.add(id); } catch (e) { throw new Error(`${id}: ${e instanceof Error ? e.message : String(e)}`); } @@ -840,12 +922,18 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) { for (const e of manifest.timeline) { if (e.id in next) setOnscreen(e, next[e.id]); if (e.id in claims) { - if (claims[e.id]) e.claim = claims[e.id]; + const c = claims[e.id]; + // A row that does not name the knobs keeps the entry's while the claim + // stays the same claim: the On-screen table edits the id and verdict, + // the clip editor the knobs, and neither may drop the other's work. + const keep = c && !withKnobs.has(e.id) && isObj(e.claim) && e.claim.id === c.id ? claimKnobsOf(e.claim) : {}; + if (c) e.claim = { ...c, ...keep }; else delete e.claim; } } // The claims as the build will read them: one verdict per claim id, none - // on a teaser. Refused before the write, so the file is as it was. + // on a teaser, each knob in range. Refused before the write, so the file + // is as it was. const bad = validateClaims(manifest); if (bad.length) throw new Error(`claim: ${bad.join("; ")} — nothing was written`); @@ -1624,6 +1712,173 @@ export async function updateFactcheck(dir, factcheck, { token = null } = {}) { }); } +// --------------------------------------------------------------------------- +// THE VIDEO KNOBS (plans/video-knobs-ui.md): a claim's stamp and count, the +// deck's markers, the encode ladder. Read by ./knobs.mjs, checked by the +// renderer's own validators (validateClaims, validateChrome, validateVariants). +// A clip's `audio` is updateClip's. +// --------------------------------------------------------------------------- + +/** + * Patch the knobs of ONE claimed entry's `claim`: `{ at?, hold?, stamp?, + * count?, label? }`, each a value or null (back to the default: the key is + * removed). Every entry carrying the id (a variant's twin) gets the same + * knobs. The entry must carry a claim; `at` must lie in its window. + * + * The build reads the knobs of the entry that STAMPS the claim -- the last + * carrying its id -- so `stamps` in the answer says whether this one does. + * + * @param {string} dir + * @param {string} entryId + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ claim: Record<string, unknown>, stamps: boolean, stampsOn: string | null, token: string | null }>} + */ +export async function updateClaimKnobs(dir, entryId, patch, { token = null } = {}) { + const next = normalizeClaimKnobPatch(patch); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const entries = (manifest.timeline ?? []).filter((e) => isObj(e) && e.id === entryId); + if (!entries.length) throw new Error(`no timeline entry with id ${entryId}`); + if (!isObj(entries[0].claim)) throw new Error(`${entryId} carries no claim — give it one (the On-screen table's claim column) before its stamp's knobs`); + for (const e of entries) { + if (!isObj(e.claim)) continue; + for (const [k, v] of Object.entries(next)) { + if (v === null) delete e.claim[k]; + else e.claim[k] = v; + } + } + // The renderer's own check -- each knob, and `at` inside the entry's window -- on this entry's rows. + const bad = validateClaims(manifest).filter((e) => e.includes(`(${entryId})`)); + if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + const nextToken = await writeManifestAtomic(dir, manifest); + const stampsOn = stampingEntryId(manifest, entries[0].claim.id); + return { claim: entries[0].claim, stamps: stampsOn === entryId, stampsOn, token: nextToken }; + }); +} + +/** + * Normalise a list of deck markers as the editor sends them: each `{ after, + * label, color?, align? }`, the label trimmed, an empty colour and `align: + * "auto"` (the default) left out. + * + * @param {unknown} markers + */ +export function normalizeMarkers(markers) { + if (!Array.isArray(markers)) throw new Error("markers must be a list of { after, label, color?, align? }"); + return markers.map((m, i) => { + if (!isObj(m)) throw new Error(`markers[${i}] must be { after, label, color?, align? }`); + const out = { after: String(m.after ?? "").trim(), label: String(m.label ?? "").trim() }; + const color = typeof m.color === "string" ? m.color.trim() : ""; + if (color) out.color = color; + if (m.align !== undefined && m.align !== null && m.align !== "" && m.align !== "auto") out.align = m.align; + for (const k of Object.keys(m)) if (!["after", "label", "color", "align"].includes(k)) out[k] = m[k]; + return out; + }); +} + +/** + * Set the deck's markers (`render.chrome.deck.markers`) and/or their layout + * (`deck.markerLayout`), leaving the rest of the deck as it is. `markers: []` + * or null removes the list; `markerLayout: null` (or "") removes the key. + * Only on a cut whose deck is on. A structural edit: snapshotted first (Undo + * takes it back), checked by the build's validateChrome and validateDeckMarkers. + * + * @param {string} dir + * @param {{ markers?: unknown[] | null, markerLayout?: string | null }} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updateDeckMarkers(dir, patch, { token = null } = {}) { + if (!isObj(patch) || (!("markers" in patch) && !("markerLayout" in patch))) { + throw new Error("send markers and/or markerLayout"); + } + const markers = patch.markers === undefined || patch.markers === null ? patch.markers : normalizeMarkers(patch.markers); + return structural(dir, "markers", token, (m) => { + const render = m.render ?? {}; + if (!isObj(render.chrome)) throw new Error("markers are drawn by the on-screen deck, and this manifest has none — turn the deck on first"); + const deck = { ...(isObj(render.chrome.deck) ? render.chrome.deck : {}) }; + if (markers !== undefined) { + if (markers === null || !markers.length) delete deck.markers; + else deck.markers = markers; + } + if ("markerLayout" in patch) { + const v = patch.markerLayout; + if (v === null || v === undefined || v === "") delete deck.markerLayout; + else deck.markerLayout = v; + } + const chrome = { ...render.chrome, deck }; + const { chrome: _old, ...rest } = render; + const already = new Set(validateChrome(render.chrome, rest)); + const errors = validateChrome(chrome, rest).filter((e) => !already.has(e)); + if (errors.length) throw new StructureRefused(errors); + m.render = { ...render, chrome }; + return { markers: deck.markers ?? [], markerLayout: deck.markerLayout ?? null }; + }); +} + +/** + * Set any of the deck's own keys (`render.chrome.deck.<key>`), leaving the + * rest of the deck as it is: `umtool look <p> deck.<key>=<json>`, the + * agent's way to every deck setting the build knows (`markers`, `markerLayout`, + * `finale`, `pip`, …). null or "" removes a key (its default again); `markers` + * is normalised as the Markers editor's. Only on a cut whose deck is on; a + * structural edit, checked by the build's validateChrome -- a key the build + * does not know is refused there, in its words. + * + * @param {string} dir + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ deck: Record<string, unknown>, token: string | null }>} + */ +export async function updateDeckKeys(dir, patch, { token = null } = {}) { + if (!isObj(patch) || !Object.keys(patch).length) throw new Error("send one or more deck keys"); + const next = { ...patch }; + if (Array.isArray(next.markers)) next.markers = normalizeMarkers(next.markers); + return structural(dir, "deck", token, (m) => { + const render = m.render ?? {}; + if (!isObj(render.chrome)) throw new Error("the deck's settings need the on-screen deck, and this manifest has none — turn the deck on first"); + const deck = { ...(isObj(render.chrome.deck) ? render.chrome.deck : {}) }; + for (const [k, v] of Object.entries(next)) { + if (v === null || v === undefined || v === "" || (k === "markers" && Array.isArray(v) && !v.length)) delete deck[k]; + else deck[k] = v; + } + const chrome = { ...render.chrome, deck }; + const { chrome: _old, ...rest } = render; + const already = new Set(validateChrome(render.chrome, rest)); + const errors = validateChrome(chrome, rest).filter((e) => !already.has(e)); + if (errors.length) throw new StructureRefused(errors); + m.render = { ...render, chrome }; + return { deck }; + }); +} + +/** + * Set or remove `render.variants`, the ladder "Make variants" encodes + * (knobs.mjs VARIANTS_DEFAULT when absent). null removes it. + * + * @param {string} dir + * @param {unknown[] | null} variants + * @param {{ token?: string | null }} [opts] + */ +export async function updateVariants(dir, variants, { token = null } = {}) { + if (variants === undefined) throw new Error("variants must be a list, or null for the default ladder"); + const errors = variantsProblems(variants); + if (errors.length) throw new RenderRefused(errors); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const render = { ...(isObj(manifest.render) ? manifest.render : {}) }; + if (variants === null) delete render.variants; + else render.variants = variants; + manifest.render = render; + const nextToken = await writeManifestAtomic(dir, manifest); + return { variants: render.variants ?? null, token: nextToken }; + }); +} + /** * Replace the WHOLE manifest with `manifest` (release 33: "Use this take" puts * a take's video.manifest.json in the project's place). The same path as a diff --git a/umtool/lib/report/variantsView.mjs b/umtool/lib/report/variantsView.mjs @@ -0,0 +1,146 @@ +// MAKE VARIANTS and the SYNC report, read back for Deliver (video knobs, +// plans/video-knobs-ui.md). The encode is the renderer's (report-to-video +// variants.mjs encodeVariants, run as a job by driver.mjs variantsSteps); the +// sync report is the build's (`<out>/<variant>/sync.json`). This only reads +// what they wrote, by NAME -- a variant's name, a take's id -- never a path. +// +// <out>/<slug>.mp4 the build (the `master` variant is this file) +// <out>/<slug>.<name>.mp4 one variant +// <out>/variants.json { at, source, items: [{ name, path, width, height, bytes, kbps }] } +// <out>/sourced/sync.json { fps, items: [{ id, start, lagMs, peak }] } +// +// `<out>` is the project's out/, or a take's (takes/<id>/out). +// +// Plain ESM: `umtool variants` runs it under bare node. +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_VARIANT, variantPaths } from "umtool-report-to-video/build-video"; +import { resolveInRoots } from "../paths.mjs"; +import { VARIANT_NAME_RE, VARIANTS_DEFAULT, variantsOf } from "./knobs.mjs"; +import { isTakeId, takesDirOf } from "./takes.mjs"; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** A lag past one frame is flagged (the plan's acceptance: every clip within ±1 frame). */ +export const frameMs = (fps) => 1000 / (fin(fps) && fps > 0 ? fps : 30); + +/** + * The out/ a take or the project builds into. Throws on a take id that is not one. + * @param {{ dir: string }} project + * @param {string | null} [take] + */ +export function outDirOf(project, take = null) { + if (take === null || take === undefined || take === "") return path.join(project.dir, "out"); + if (!isTakeId(take)) throw new Error(`not a take id: ${take}`); + return path.join(takesDirOf(project.dir), take, "out"); +} + +async function fileInfo(file) { + const abs = resolveInRoots(file); + if (!abs) return null; + const st = await stat(abs).catch(() => null); + return st?.isFile() ? { abs, size: st.size, mtimeMs: Math.round(st.mtimeMs) } : null; +} + +async function readJson(file) { + const abs = resolveInRoots(file); + if (!abs) return null; + try { + return JSON.parse(await readFile(abs, "utf8")); + } catch { + return null; + } +} + +/** The takes with a build in their out/ (their `<slug>.mp4`), by id. */ +export async function builtTakes(project, slug) { + const dirs = await readdir(takesDirOf(project.dir), { withFileTypes: true }).catch(() => []); + const out = []; + for (const d of dirs) { + if (!isTakeId(d.name)) continue; + const got = await fileInfo(variantPaths(outDirOf(project, d.name), slug, DEFAULT_VARIANT).final); + if (got) out.push(d.name); + } + return out.sort(); +} + +/** + * What Deliver shows for one out/: the build, the ladder, the variants made, + * the sync report. + * + * @param {{ id: string, dir: string }} project + * @param {{ slug?: string, render?: Record<string, unknown>, timeline?: unknown[] }} manifest + * @param {string | null} [take] + */ +export async function variantsState(project, manifest, take = null) { + const slug = manifest.slug ?? path.basename(project.dir); + const outDir = outDirOf(project, take); + const built = await fileInfo(variantPaths(outDir, slug, DEFAULT_VARIANT).final); + const doc = await readJson(path.join(outDir, "variants.json")); + const items = []; + if (isObj(doc) && Array.isArray(doc.items)) { + for (const it of doc.items) { + if (!isObj(it) || typeof it.name !== "string" || !VARIANT_NAME_RE.test(it.name)) continue; + const f = await fileInfo(path.join(outDir, `${slug}.${it.name}.mp4`)); + items.push({ + name: it.name, + width: fin(it.width) ? it.width : null, + height: fin(it.height) ? it.height : null, + bytes: f?.size ?? (fin(it.bytes) ? it.bytes : null), + kbps: fin(it.kbps) ? it.kbps : null, + exists: !!f, + mtimeMs: f?.mtimeMs ?? null, + }); + } + } + const syncDoc = await readJson(path.join(outDir, DEFAULT_VARIANT, "sync.json")); + const fps = isObj(syncDoc) && fin(syncDoc.fps) ? syncDoc.fps : null; + const limit = frameMs(fps); + const clipIds = new Set((manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip").map((e) => e.id)); + const sync = isObj(syncDoc) && Array.isArray(syncDoc.items) + ? { + fps, + frameMs: Math.round(limit * 10) / 10, + items: syncDoc.items + .filter((x) => isObj(x) && typeof x.id === "string") + .map((x) => ({ + id: x.id, + start: fin(x.start) ? x.start : null, + lagMs: fin(x.lagMs) ? x.lagMs : null, + peak: fin(x.peak) ? x.peak : null, + flagged: fin(x.lagMs) && Math.abs(x.lagMs) > limit, + clip: clipIds.has(x.id), + })), + } + : null; + const render = isObj(manifest.render) ? manifest.render : {}; + return { + take: take || null, + slug, + built: built ? { size: built.size, mtimeMs: built.mtimeMs } : null, + ladder: variantsOf(render), + ladderIsDefault: !Array.isArray(render.variants), + ladderDefault: VARIANTS_DEFAULT, + made: isObj(doc) ? { at: typeof doc.at === "string" ? doc.at : null, items } : null, + // A variants.json older than the build was made from another build. + stale: !!(built && isObj(doc) && typeof doc.at === "string" && Date.parse(doc.at) < built.mtimeMs), + sync, + takes: await builtTakes(project, slug), + }; +} + +/** + * One variant's file, by name, for the route that serves it. + * @param {{ dir: string }} project + * @param {{ slug?: string }} manifest + * @param {string} name + * @param {string | null} [take] + * @returns {Promise<{ abs: string, size: number, mtimeMs: number, rel: string } | null>} + */ +export async function variantFile(project, manifest, name, take = null) { + if (typeof name !== "string" || !VARIANT_NAME_RE.test(name)) return null; + const slug = manifest.slug ?? path.basename(project.dir); + const f = await fileInfo(path.join(outDirOf(project, take), `${slug}.${name}.mp4`)); + return f ? { ...f, rel: `${slug}.${name}.mp4` } : null; +} diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -24,6 +24,9 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // worker's load of this config does not check again // E2E_UMTOOL_MONTAGE_STYLES set below on the app server: the montage styles // module the take maker reads (release 33) +// E2E_UMTOOL_VARIANTS_SCRIPT set below on the app server: the variants +// encoder Make variants runs (video knobs; +// lib/report/driver.mjs variantsSteps), 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"); @@ -164,6 +167,9 @@ export default defineConfig({ // report-to-video/montage-styles.mjs's shape, so takes.spec makes a take // with a style whatever the real styles do. Read by lib/report/takeMaker.mjs. `E2E_UMTOOL_MONTAGE_STYLES=${path.join(path.dirname(fileURLToPath(import.meta.url)), "e2e", "fixtures", "montage-styles.e2e.mjs")} ` + + // 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")} ` + // 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.