commit db859363542eab5171b8b1036e41cc3f5b962ab1
parent 9d8141d02c0fa9b40f1104342a0e189441a16643
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 14:40:13 -0400
Merge r36/clip-look: the Look panel + updateRender, loudness, speaker captions, vertical shorts, umtool build --run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# editor/CHANGELOG.md
# plans/FACTS.md
Diffstat:
32 files changed, 2793 insertions(+), 27 deletions(-)
diff --git a/common/lib/clips/reactions.d.mts b/common/lib/clips/reactions.d.mts
@@ -48,3 +48,4 @@ export function readReactions(dir: string): Promise<ReactionsDoc | null>;
export function writeReactions(dir: string, doc: ReactionsDoc): Promise<string>;
export function operatorRoles(doc: ReactionsDoc | null): Record<string, Role>;
export function setSpeakerRole(dir: string, index: number, role: Role | null, opts?: { now?: () => Date }): Promise<ReactionsDoc>;
+export function setSpeakerLabel(dir: string, index: number, label: string | null): Promise<ReactionsDoc>;
diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs
@@ -92,3 +92,26 @@ export async function setSpeakerRole(dir, index, role, { now = () => new Date()
await writeReactions(dir, doc);
return doc;
}
+
+/**
+ * A person's name for one speaker (release 36 lane C): what the speaker
+ * captions head that voice's lines with. Trimmed, up to 40 characters; null
+ * or empty gives back the default ("Host", "Subject", "Speaker N"), which the
+ * captions never print. A role change (setSpeakerRole) resets it.
+ *
+ * @param {string} dir the project
+ * @param {number} index the speaker (diarization cluster)
+ * @param {string|null} label
+ * @returns {Promise<any>} the document as written
+ */
+export async function setSpeakerLabel(dir, index, label) {
+ const doc = await readReactions(dir);
+ if (!doc) throw new Error(`no ${REACTIONS_FILE} in ${dir}`);
+ const s = doc.speakers.find((x) => isObj(x) && x.index === index);
+ if (!s) throw new Error(`no speaker ${index} in ${REACTIONS_FILE}`);
+ const text = label === null || label === undefined ? "" : String(label).replace(/\s+/g, " ").trim();
+ if (text.length > 40) throw new Error("a speaker's label is up to 40 characters");
+ s.label = text || labelOf(s.role, index);
+ await writeReactions(dir, doc);
+ return doc;
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -3,6 +3,9 @@
## [Unreleased]
- **The clip finder finds each narrated video in a reaction stream, and listens to the chat.** A stream that reacts to one video and then another no longer needs its scope read off the speakers by hand: `umtool new <slug> --seed reactions --from <channel>/<id> --scope auto` reads the narrated video the speaker turns show (`--segment s2` names one, else the longest), with the host's reaction after the video kept and the roles found for that video alone; `umtool clips segments <project>` lists them. When the stream's chat replay is on disk, the moments the chat laughs together (lol, KEKW, π, a wall of W) become proposals too, moved back by how late the chat types β found by lining the chat up against the laughs heard in the sound, else 6 seconds β and always ranked below the host's own laugh; the analysis says the delay it found. Without a chat replay nothing changes. Needs a restart of umtool.
- **Highlights of a channel that is on no site link the source and start with a clean look.** Each proposed clip links its platform page at its second (YouTube, Twitch, Rumbleβ¦), the channel's name is filled in from the video, and the cut starts with no header, no QR code, half-second fades through black and a β16 LUFS loudness target β no edits to the manifest needed. umtool's clips job also answers the editor directly (its `WORKER_TOKEN`), so the editor's Find clips makes or re-analyzes the project in one call; asking again for a video already cut analyzes that project again and leaves its cut exactly as it is, listing the new proposals (the chat's among them) for you to bring in.
+- **Set a report video's look in umtool, with captions that say who is speaking and even loudness.** The Build tab has a **Look** panel: the header, the timeline footer and the QR code on or off, the length between clips and how they join (crossfade, dip to black, dip to white, dissolve), the loudness (as recorded, β16 LUFS, or your own target) and **Speaker captions** β burned in, two to six words a line, the host's in amber on the left and the other voice's in blue on the right, broken where they pause and never across a change of speaker (from the clip finder's speakers, or the transcript's words). Voices are told apart by colour; give one a name in the panel, or beside a speaker in the clip editor's Speakers list, and its lines say it. Even loudness measures each clip and brings it to the target with a limiter, as montages already did. **Save the look** writes only what you changed; a cut with the on-screen deck keeps its own settings. A manifest without the new keys renders exactly as before. Needs a restart of umtool.
+- **Make a vertical short of any clip.** In the clip editor, **Frame the short** puts a 9:16 box on the player β drag it to the face, size it β and **Make a short** renders that clip alone at 1080Γ1920 into the project's `shorts/`: the box filling the frame, large speaker captions, no header or QR, even loudness. It runs as a job (one at a time, with Cancel) in the machine's heavy slot; a short made again sets the old one aside rather than overwriting it. The Deliver tab lists the shorts β play, download, make again, or open the clip to frame it β and says when a clip has moved since its short was made. From a terminal: `build-video.mjs <manifest> --short <clip>`. Needs a restart of umtool.
+- **`umtool build <project> --run` runs the build.** It starts the same build job the project page's button does on the running umtool (`UMTOOL_URL`, else `http://localhost:3050`, or `--url`), prints its log as it goes, and Ctrl-C cancels the job. `--replace` sets a newer deliverable aside. Without `--run` it prints the chain as before.
- **A report video's cut can dip through black between clips.** `render.transitionStyle: "fadeblack"` (or `fadewhite`, `dissolve`; default `fade`) changes how the crossfade looks, not its length β for highlights where every clip shares one layout and a plain dissolve hides the jump.
- **Hop in on an assistant's clips in umtool: trim, split, merge, keep or cut them, and comment.** A report video whose cut is not a montage has a **Clip editor** on its Cut tab (`/projects/<id>/clips`). It loops the selected clip from what is on disk, and under it shows the clip's neighbourhood (Β± 60 s, or closer): the speaker turns coloured host and subject, the laughs, the words, the other clips, and the cut with a handle at each edge. Move the edges by dragging, typing, nudging (Β±0.1, Β±0.5, Β±2 s) or **Snap to words**; **Keep** / **Cut**; **Split here** at the playhead; **Merge with next**; **Add a clip** from a span dragged on the strip; **Restore the assistant's version**; **Bring in** a proposal the assistant left out. Each clip says whether it is "by the assistant" (with its score and why) or "edited by you", with its edit history. A comment on a clip is a note anchored to it, so an agent reading `umtool notes` can act on it and its reply shows in the clip's thread. **This is the host** on a speaker's turn corrects which voice is the host. Keys: space, J/L, I/O, S, M, K, X, β/β. A keep or cut follows its clip when an edit moves the clip's start. It works on any report video; a cut without the clip finder's speakers simply has no colours.
- **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first β how many per platform, how many already on disk β then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** β the same moment in the stream's YouTube upload (or Odysee) β and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10840,3 +10840,52 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
copied (`created: true`); then ONE job `clips analyze <id>` β `{ok, jobId, job, project, created, segments,
segment (the chosen one's id), scope (the project's params.scope), href "/projects/<id>/clips", notes}`. GET
`?project=` adds `segments`, `segment`, `chat {source, lagS, lag, messages, bursts}`.
+## Release 36 lane C: the look β captions, loudness, vertical shorts (verified 2026-10-19, branch `r36/clip-look`)
+
+- **`render.captions`** `{style: "speakers", labels?: {host?: string|null, subject?: string|null}, size?: "m"|"l"}`,
+ **`render.loudness`** `{target}` (β30β¦β8 LUFS), clip **`vertical`** `{crop: [x, y, w, h], aspect?}` (fractions of the
+ source picture; 9:16 on the source within 3 %, `aspect` = source w/h, default 16/9). Absent or `null` = off and
+ byte-identical (md5 vs main 0d471989 on a two-clip fadeblack fixture). Validated by `validateLook(manifest)`
+ (`umtool/report-to-video/look.mjs`, exported `umtool-report-to-video/look`) in build-video's validators and lint's
+ `validatorErrors`; captions are refused beside `render.chrome` or `render.montage`, loudness beside `render.montage`.
+ Lane B's seed shape `loudness: {target: -16}` validates.
+- **Captions at the clip encode** (non-deck branch only): words for [cut record start, + segment seconds] from
+ `<project>/<reactions.source.words ?? "words.json">` when `reactions.json` (version 1, with `turns`) names the clip's
+ video (and channel), else corpus `transcript.json` whisper words (`whisperWords`), else cues (`fxWordsOf`); turns and
+ speakers only from that reactions.json. `captionLines`: speaker = the turn holding the word's middle, else the nearest
+ turn edge within 0.6 s, else null ("other"); a new line on a speaker change, at 6 words, or (from 2 words) on a gap
+ β₯ 0.45 s or past `maxChars`; a line ends at its last word + 0.3 s, never past the next line. Label = `labels[role]`,
+ else the speaker's label when it is not the default (`Host`/`Subject`/`Speaker N+1`), on a turn's first line only.
+ ASS: PlayRes = the frame, `WrapStyle: 2`, `YCbCr Matrix: None`, styles `host` (&H0040C8FF, align 1), `subject`
+ (&H00FFD36F, align 3), `other` (&H00E6F1F6, align 2), font "IBM Plex Sans" from `report-to-video/fonts/` (`fontsdir`),
+ size m = 0.052 Γ min(W, H), l = 0.075 Γ; marginV = footer + 7 % (20 % on a vertical frame). File
+ `out/<variant>/segments/<id>.captions.ass`; the cut record gains `captions: {lines, words: "words.json"|"transcript.json"|"cues"}`.
+ A path with `'`, `:` or `\` cannot be an `ass=` option: refused with a sentence.
+- **Loudness at the clip encode** (non-montage, deck or not): `measureLoudness(raw, cutA, cutB)` (now exported) β
+ `loudnessGain` β `[0:a]levelFilters(gain)[al]` (an `asplit` first when a poster's waveform reads `[0:a]`); the cut
+ record gains `loudness: {measured, gain, target}`. A cut under β40 LUFS (montage.mjs `SILENT_LUFS`) gets gain 0.
+- **`--short <clipId>`** (`buildVideo({opts: {short}})`): `only` = that clip, `manifest.render = shortRender(render)`
+ (1080Γ1920, header/footer 0, `qr: false`, no chrome/rail/chromeEngine/brand/montage, `captions {style, labels?, size: "l"}`,
+ `loudness {target: cut's ?? -16}`), work dir `out/shorts-work/` (dirs.dir), picture `crop=W:H:X:Y,scale=1080:1920:flags=lanczos,setsar=1,fps`
+ from `cropPixels(vertical.crop ?? centre, display w, h)` (exact 9:16, even, the box's height and centre kept, clamped).
+ Output `<manifest dir>/shorts/<id>.mp4` (tmp + rename) + `<id>.json` `{version 1, clip, video, requested {cutStart, cutEnd},
+ cut [start, end] (played), crop, width, height, loudness, captions, madeAt}`. `takesHeavySlot` is true for a short.
+- **umtool writers**: `updateRender(dir, patch, {token})` (lib/report/manifest.mjs) β keys `LOOK_KEYS` = headerHeight,
+ footerHeight (ints 0β240), qr (true removes a `false`, keeps an object; false), transition (0β3 s, 2 dp),
+ transitionStyle, loudness, captions; `null` deletes a key; `chrome` or any other key β `RenderRefused`; the merged render
+ is checked with `validateTransitionStyle` + `validateLook`; atomic, token-guarded. `lookOf(render)`. `updateClip` takes
+ `vertical` (null/"" deletes; `verticalErrors`; 4 dp). Route `GET/PUT /api/report/render`.
+- **reactions.json**: `setSpeakerLabel(dir, index, label|null)` (common/lib/clips/reactions.mjs, after setSpeakerRole):
+ trimmed, β€ 40 chars, empty β the default label; no timestamp. setSpeakerRole still resets a label to the default.
+ The clip editor's ops gain `label {speaker, label}` and `vertical {clip, crop|null, aspect?}` (an updateClip "trim"
+ edit that leaves the cut: `assist` untouched); its view gains `clips[].vertical` and `shorts {<clipId>: {mtimeMs, size, stale}}`.
+- **Shorts**: `umtool/lib/report/shorts.mjs` β `shortSteps(project, clipId)` (one step: `node build-video.mjs <manifest>
+ --out <project>/out --short <id> --progress ndjson`, 20 min), `readShorts(dir, manifest)` (newest first; a set-aside
+ `<id>.<YYYYMMDD-HHMM>.mp4` is not listed; `stale` = the requested cut or the crop differs from the clip's now; `gone`),
+ `setShortAside(dir, id, {replace})` (the replace guard: refused with `needsReplace` unless replace, then renamed aside
+ with its record). Route `/api/report/shorts`: GET `?project` `{shorts, running}`, `?project&clip&file=1[&download=1]`
+ (ranges), `?job`; POST `{project, clip, replace?}` β job kind `short <project> <clip>`; `?cancel=`.
+- **`umtool build <project> --run`** (`lib/report/buildRun.mjs` `runBuildOverHttp`): POST `/api/report/build`
+ (`?replace=1` with `--replace`) on `--url` > `UMTOOL_URL` > `http://localhost:3050`, Bearer `WORKER_TOKEN` when set;
+ polls `?job=&since=&sinceEvent=` every 1.5 s printing the log; SIGINT posts `?cancel=<job>` (a second Ctrl-C exits
+ 130); exit 0 only for `done`. Without `--run` unchanged (prints the chain).
diff --git a/plans/release-36/clip-look.md b/plans/release-36/clip-look.md
@@ -0,0 +1,100 @@
+# Release 36 lane C β `r36/clip-look`: the Look panel, loudness, speaker captions, vertical shorts (as shipped)
+
+The plan of record is [clip-finder-2.md](clip-finder-2.md), lane C. The first case's render look (no header or QR,
+fadeblack joins) was a jq edit of the manifest; it had no captions, uneven loudness (β19 LUFS) and no shareable
+shorts, and `umtool build` only printed its chain. This lane makes each of those a render key a person sets in the UI,
+renders them, and adds the short and `build --run`. Rulings followed: the UI works with no model (nothing here calls
+one); every review step a umtool surface; absent keys render byte for byte as before; redesign primitives and role
+tokens; synthetic fixtures only; the live projects read only.
+
+## What
+
+1. **The keys and their validators** (`umtool/report-to-video/look.mjs`, pure; `validateLook` in build-video's
+ validators and lint's `validatorErrors`, as `validateTransitionStyle` is):
+ - `render.captions {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"}` β refused beside
+ `render.chrome` (the deck's own words) or `render.montage`.
+ - `render.loudness {target}` β30β¦β8 LUFS β refused beside `render.montage` (which has its own). Lane B's seed shape
+ `{target: -16}` validates.
+ - clip `vertical {crop: [x, y, w, h], aspect?}` β fractions of the source, inside it, 9:16 on the source within 3 %.
+2. **Loudness** at the clip encode, deck or not, montage excepted: the cut measured (`measureLoudness`, now exported),
+ `levelFilters(loudnessGain(measured, target))` on `[0:a]` (an `asplit` first when a poster's waveform reads it);
+ the cut record carries `loudness {measured, gain, target}`.
+3. **Speaker captions** (no deck): per segment an ASS file (`segments/<id>.captions.ass`) from the project's
+ `words.json` (the recording reactions.json names), else whisper's words, else the cues; reactions.json's turns
+ colour and place each line; 2β6 words a line, broken on 0.45 s pauses, never across a speaker change; burned with
+ `ass=` (libass; ffmpeg n9.0.2 here has it). The colours (fixed, not the palette's): **host `#FFC840` amber bottom
+ left, subject `#6FD3FF` sky bottom right, other `#F6F1E6` paper bottom centre**, black outline, IBM Plex Sans from
+ `report-to-video/fonts/`. Names only when somebody gives one (`labels[role]`, else a non-default speaker label).
+ `setSpeakerLabel(dir, index, label)` added to common/lib/clips/reactions.mjs directly after setSpeakerRole (lane B's
+ file, the one export the prelude allowed); the clip editor's Speakers list edits it.
+4. **The Look panel** β the Build tab: Header, Timeline footer, QR code, Between clips (s) + Join (crossfade, dip to
+ black, dip to white, dissolve), Loudness (as recorded / β16 / custom), Speaker captions + each role's name + size;
+ Save the look writes the diff through `updateRender(dir, patch, {token})` (lib/report/manifest.mjs, modelled on
+ updateChrome: token-guarded, the build's checks, atomic; never `render.chrome`) behind `GET/PUT /api/report/render`.
+5. **Vertical shorts** β the clip editor's side column: Frame the short (a 9:16 box over the player: drag, size slider,
+ written to the clip's `vertical` through updateClip when let go; Centre it), Make a short β a job on umtool's runner
+ (`/api/report/shorts`, `lib/report/shorts.mjs`): `build-video.mjs --short <id>` β the clip alone at 1080Γ1920 from
+ its crop, captions size "l", no header/footer/QR, the cut's loudness else β16 β in the heavy slot, its work in
+ `out/shorts-work/`, the file `<project>/shorts/<id>.mp4` + `<id>.json`; a short that is there is set aside
+ (`<id>.<stamp>.mp4`), never overwritten. The Deliver tab's **Shorts** list: play, download, make again, frame it;
+ "the clip moved since" when the cut or crop changed.
+6. **`umtool build <project> --run`** (`lib/report/buildRun.mjs`): the build route's job over HTTP (`--url` >
+ `UMTOOL_URL` > `http://localhost:3050`), its log followed, Ctrl-C cancels; `--replace`. Without `--run` unchanged.
+
+## Files
+
+report-to-video: `look.mjs` (new), `look.test.mjs` (new, 15), `build-video.mjs` (imports, validator, loudness and
+captions in `buildClipSegment`, the short's framing, `probeDims` / `readLookSources` / `lookWordsFor` /
+`segmentCaptions` / `placeShort`, `--short`, `takesHeavySlot`), `lint.mjs`, `package.json` (`./look`,
+`./transition`), `README.md`. umtool: `lib/report/manifest.mjs` (`updateRender`, `lookOf`, `LOOK_KEYS`,
+`RenderRefused`, updateClip's `vertical`), `lib/report/clipEditor.mjs` (ops `label`, `vertical`; view `vertical`,
+`shorts`), `lib/report/clipEditorBridge.mjs`, `lib/report/clipEditorTypes.ts`, `lib/report/shorts.mjs` (new),
+`lib/report/buildRun.mjs` (new), `lib/report/look.test.mjs` (new, 5), `lib/report/buildRun.test.mjs` (new, 3),
+`app/api/report/render/route.ts` (new), `app/api/report/shorts/route.ts` (new),
+`components/projects/report/LookPanel.tsx` (new), `components/projects/report/ShortsList.tsx` (new), `BuildTab.tsx`,
+`DeliverTab.tsx`, `components/projects/review/ClipEditor.tsx` (CropBox, SpeakerLabel, ShortMaker), `bin/umtool.mjs`,
+`e2e/clip-look.spec.ts` (new), `e2e/fixtures/clip-editor-fixture.mjs` (a `name`), `e2e/fixtures/make-fixture.mjs`,
+`docs/report-video.md` ("The look: captions, loudness, shorts"), `docs/cli.md`. common: `lib/clips/reactions.mjs` +
+`.d.mts` (`setSpeakerLabel`). `editor/CHANGELOG.md`, `plans/FACTS.md` ("Release 36 lane C").
+
+## Commits
+
+| sha | what |
+|---|---|
+| `c8355cf2` | report-to-video: look.mjs, loudness + captions at the clip encode, `--short`; 15 tests |
+| `83304773` | umtool: updateRender + /api/report/render, a clip's vertical, setSpeakerLabel, shorts job + route; 5 tests |
+| `fe6b9968` | umtool: the Look panel, Frame the short + Make a short, the Shorts list |
+| `ebdf6ab7` | umtool: `umtool build --run`; 3 tests |
+| `5004235c` | umtool e2e: clip-look.spec.ts; the clip editor's fixture takes a name |
+| `6d796dfd` | docs, FACTS, CHANGELOG |
+| (this) | plans: this record |
+
+## Gates (all through the session lock, from the worktree root)
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit` β clean on the full tree before the commits.
+- `pnpm run test:scripts` β **1278 tests, 1274 pass, 0 fail, 4 skipped** (branch start, main 0d471989: 1255 / 1251 / 4;
+ +23: `report-to-video/look.test.mjs` 15, `lib/report/look.test.mjs` 5, `lib/report/buildRun.test.mjs` 3).
+- `pnpm --filter umtool test` β 45 / 45 (unchanged). common `lib/clips/*.test.ts` β 24 / 24 (setSpeakerLabel is
+ tested through the clip editor's `label` op in `lib/report/look.test.mjs`; lane B's test file untouched).
+- The render tests (real ffmpeg, in look.test.mjs): a caption line up on its frame (0.25 s β frame 8 of a 30 fps
+ segment, nothing on frame 6), the subject's pixels sky (mean B > R + 60) on the right only, the host's amber
+ (R > B + 80) on the left only; loudness: a β27 LUFS tone to β16 within Β±0.5 LU (segment and cut); the short
+ 1080Γ1920, its crop's bar at x 428β642 as computed, no header, β16 within Β±0.5 LU, captions at 81 px.
+- **Byte-identical without the new keys**: in-suite (absent vs `null`: final, segment, cut record); and against
+ main's build-video (`$T/r36c-scripts/bytecheck.mjs`, a two-clip fadeblack 640Γ360 fixture, the primary checkout's
+ build-video vs the branch's): final `49033bc6β¦`, segments `875fe480β¦` / `73cd16d7β¦`, cut records `ef0ece96β¦` /
+ `6cd4f047β¦` β the same both sides.
+- e2e (umtool, `E2E_MODE=dev`, no build): `clip-look.spec.ts` **1 passed** (35.8 s; wall 45 s after 3.8 min in the
+ machine's heavy queue); on the tip `6d796dfd` with `clip-editor.spec.ts`: **2 passed, 0 failed** (clip-editor 24.5 s,
+ clip-look 9.4 s; wall 43.7 s after 13 min in the heavy queue).
+- No `next build` (dev-mode e2e); no generated doc changed (umtool's CLI and env are out of COMMANDS.md /
+ ENVIRONMENT.md's scope).
+
+## Found and left
+
+- A cut quieter than β40 LUFS is not raised (montage.mjs's `SILENT_LUFS` rule, kept): a near-silent clip is a cut in
+ the wrong place, not a quiet one.
+- setSpeakerRole resets a speaker's label to the default, so a name set before a role change is lost (the analysis'
+ writer, lane B's; not changed here).
+- Words heard in no turn (or by one of the stream's small clusters) are captioned as "other", paper centre.
+- Captions are not offered under the deck (its `fx.kineticQuote` is the deck's own) or on a montage.
diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts
@@ -0,0 +1,65 @@
+import { withEditNotes } from "@/lib/report/guard";
+import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender } from "@/lib/report/manifest.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";
+
+export const dynamic = "force-dynamic";
+
+// THE LOOK (release 36 lane C): the render keys the Look panel sets --
+// headerHeight, footerHeight, qr, transition, transitionStyle, loudness,
+// captions -- never render.chrome (the deck's own route). The client sends a
+// project id, a PATCH of those keys (null removes one) and the token it read;
+// the writer (lib/report/manifest.mjs updateRender) validates with the
+// build's own checks, so a look this route accepts is one the build accepts.
+//
+// GET ?project=<id> { look, deck, montage, styles, keys, errors, token }
+// PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors }
+
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const render = (r.manifest.render ?? {}) as Record<string, unknown>;
+ return Response.json(
+ {
+ look: lookOf(render),
+ deck: deckOn(render),
+ montage: render.montage !== undefined && render.montage !== null,
+ 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)],
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function PUT(request: Request) {
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ try {
+ const { result: res, editNotes } = await withEditNotes(r.project, () =>
+ updateRender(r.project.dir, (body.patch ?? null) as Record<string, unknown>, {
+ token: body.token === undefined || body.token === null ? null : String(body.token),
+ }),
+ );
+ return Response.json({ ok: true, look: res.look, 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 });
+ }
+}
diff --git a/umtool/app/api/report/shorts/route.ts b/umtool/app/api/report/shorts/route.ts
@@ -0,0 +1,97 @@
+import { stat } from "node:fs/promises";
+import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
+import { rangeResponse } from "@/lib/report/serve.mjs";
+import { readShorts, setShortAside, shortFile, shortSteps } from "@/lib/report/shorts.mjs";
+
+export const dynamic = "force-dynamic";
+
+// VERTICAL SHORTS (release 36 lane C): `<project>/shorts/<clipId>.mp4`, one
+// clip at 1080x1920 (build-video.mjs --short, in the heavy slot), as ONE job
+// on the app's runner (lib/jobs.ts: one at a time, a log, Cancel) -- the
+// clip editor's Make a short and the Deliver tab's Shorts list.
+//
+// GET ?project=<id> { shorts, running }
+// GET ?project=<id>&clip=<id>&file=1 the mp4 (ranges; `download=1` as an attachment)
+// GET ?job=<id>[&since=&sinceEvent=] that job
+// POST { project, clip, replace? } make it; 409 { needsReplace } when one is there
+// ?cancel=<job> stop it
+const headers = { "cache-control": "no-store" };
+const isShortJob = (kind: string) => /^short /.test(kind);
+
+async function reportProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a short is made of a report video's clip" }, { status: 400, headers }) };
+ return { project };
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const jobId = url.searchParams.get("job");
+ if (jobId) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const r = await reportProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ if (url.searchParams.get("file")) {
+ const clip = url.searchParams.get("clip") ?? "";
+ const abs = shortFile(r.project.dir, clip);
+ const st = abs ? await stat(abs).catch(() => null) : null;
+ if (!abs || !st?.isFile()) return new Response(`no short of ${clip}`, { status: 404 });
+ return rangeResponse(request, {
+ abs,
+ size: st.size,
+ headers: {
+ "content-type": "video/mp4",
+ "accept-ranges": "bytes",
+ "cache-control": url.searchParams.get("v") === String(Math.round(st.mtimeMs)) ? "private, max-age=3600, immutable" : "private, no-store",
+ ...(url.searchParams.get("download") ? { "content-disposition": `attachment; filename="${clip}-short.mp4"` } : {}),
+ },
+ });
+ }
+ const manifest = await readManifest(r.project.dir);
+ const running = runningJob();
+ return Response.json(
+ {
+ shorts: await readShorts(r.project.dir, manifest),
+ running: running && running.project === r.project.id && isShortJob(running.kind) ? jobView(running) : null,
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await reportProject(body.project);
+ if ("error" in r) return r.error;
+ const manifest = await readManifest(r.project.dir);
+ if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers });
+ const clip = String(body.clip ?? "");
+ if (!clipsOf(manifest).some((e: { id: string }) => e.id === clip) || !shortFile(r.project.dir, clip)) {
+ return Response.json({ error: `no clip with id ${clip}` }, { status: 400, headers });
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ let aside: string | null = null;
+ try {
+ aside = await setShortAside(r.project.dir, clip, { replace: body.replace === true });
+ } catch (e) {
+ const needsReplace = !!(e as { needsReplace?: boolean })?.needsReplace;
+ return Response.json({ error: e instanceof Error ? e.message : String(e), needsReplace }, { status: 409, headers });
+ }
+ try {
+ const job = startJob(`short ${r.project.id} ${clip}`, shortSteps(r.project, clip), { project: r.project.id });
+ return Response.json({ ok: true, clip, aside, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -25,6 +25,7 @@
// [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent
// 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
// umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]
// [--draft-all [--model M] [--deck]]
// an iteration's pipeline: current, windows, prepare, posts, manifest,
@@ -88,6 +89,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs";
import { withEditNotes } from "../lib/report/edit-guard.mjs";
import { hms } from "umtool-report-to-video/attribution";
import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs";
+import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs";
import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs";
import { spawn } from "node:child_process";
import { openIndex, signRecord } from "../lib/projects/index-db.mjs";
@@ -698,6 +700,8 @@ function usage() {
" an empty value (--title '') deletes the field",
" 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;",
+ " Ctrl-C cancels it; --replace stamps a newer deliverable aside",
" umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
` an article iteration's pipeline, one step a process: ${CHAIN_STEP_NAMES.join(", ")}`,
" (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
@@ -1003,7 +1007,33 @@ async function cmdBuild() {
clipCount,
});
- if (json) return out({ project: p.id, preset, steps });
+ if (json && !has("--run")) return out({ project: p.id, preset, steps });
+
+ // --run (release 36): the app runs the chain -- its job runner owns the
+ // cancellation, the timeouts and the process-group kill -- and this follows it.
+ if (has("--run")) {
+ const base = umtoolBase(val("--url"));
+ let cancel = null;
+ let stopping = false;
+ process.on("SIGINT", async () => {
+ if (stopping || !cancel) process.exit(130);
+ stopping = true;
+ console.error("\ncancelling the build job (Ctrl-C again to leave it running)β¦");
+ const ok = await cancel().catch(() => false);
+ console.error(ok ? "cancel requested; waiting for the job to stop" : "the job did not take the cancel");
+ });
+ const r = await runBuildOverHttp({
+ base, project: p.id, preset, only: val("--only") ?? null, skipFetch: has("--skip-fetch"), replace: has("--replace"),
+ token: process.env.WORKER_TOKEN ?? null,
+ log: (l) => (json ? null : console.log(l)),
+ onJob: (c) => {
+ cancel = c;
+ },
+ });
+ if (json) out(r);
+ if (r.state === "done") return;
+ die(r.needsReplace ? `${r.error} (--replace)` : `build ${r.state}${r.error ? `: ${r.error}` : ""}`, 1);
+ }
// Print, never run. The app runs the chain through lib/jobs.ts, which owns the
// cancellation, the timeouts and the process-group kill; a second runner here
diff --git a/umtool/components/projects/report/BuildTab.tsx b/umtool/components/projects/report/BuildTab.tsx
@@ -2,10 +2,11 @@ import Link from "next/link";
import { fmtAgo, fmtBytes } from "@/lib/format";
import { mixHref } from "@/lib/hrefs";
import ReportBuildChain from "../ReportBuildChain";
+import LookPanel from "./LookPanel";
import type { ReportTabProps } from "./shared";
-// The Build tab: the final video and the build chain (its job on the ONE
-// JobProgress). The on-screen panel was parked here until P4b moved it to
+// The Build tab: the final video, the look (LookPanel, release 36) and the
+// build chain (its job on the ONE JobProgress). The on-screen panel was parked here until P4b moved it to
// the Media tab.
export default function BuildTab({ project, detail }: ReportTabProps) {
@@ -29,6 +30,8 @@ export default function BuildTab({ project, detail }: ReportTabProps) {
</Link>
</div>
)}
+ {/* --- the look: header, QR, joins, loudness, captions (release 36) */}
+ <LookPanel project={project.id} />
{/* --- building it ---------------------------------------------- */}
<ReportBuildChain
project={project.id}
diff --git a/umtool/components/projects/report/DeliverTab.tsx b/umtool/components/projects/report/DeliverTab.tsx
@@ -3,6 +3,7 @@ import { EXPORT_FORMATS, exportableVariants } from "@/lib/report/export.mjs";
import { podcastFor } from "@/lib/report/serve.mjs";
import DeliverSection from "../DeliverSection";
import PodcastExport from "../PodcastExport";
+import ShortsList from "./ShortsList";
import type { ReportTabProps } from "./shared";
// The Deliver tab: the deliver panel (cuts, share batches, rulings applied,
@@ -29,6 +30,9 @@ export default async function DeliverTab({ project, detail }: ReportTabProps) {
own clip files is the other, and both wait on the same walk. */}
<DeliverSection project={project} manifest={m} entries={entries} />
+ {/* --- the shorts: one clip each, 1080x1920 (release 36) ---------- */}
+ <ShortsList 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/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -0,0 +1,230 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { Field, Input, Select } from "@/components/ui/field";
+import { Panel } from "@/components/ui/panel";
+
+// THE LOOK (release 36 lane C): the render keys a person sets for a cut with
+// no deck -- the header, the timeline footer, the QR, the crossfade's length
+// and style, the loudness target, the speaker captions -- written through
+// /api/report/render (lib/report/manifest.mjs updateRender, the build's own
+// checks). Nothing here calls a model. A deck cut keeps its own settings
+// (the Media tab); a montage levels with render.montage.
+
+type Look = {
+ headerHeight?: number;
+ footerHeight?: number;
+ qr?: unknown;
+ transition?: number;
+ transitionStyle?: string;
+ loudness?: { target: number } | null;
+ captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null;
+};
+type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null };
+
+const STYLE_WORDS: Record<string, string> = { fade: "crossfade", fadeblack: "dip to black", fadewhite: "dip to white", dissolve: "dissolve" };
+
+type Draft = {
+ header: boolean;
+ footer: boolean;
+ qr: boolean;
+ transition: string;
+ style: string;
+ loudness: "off" | "-16" | "custom";
+ target: string;
+ captions: boolean;
+ host: string;
+ subject: string;
+ size: "m" | "l";
+};
+
+function draftOf(l: Look): Draft {
+ const t = l.loudness?.target;
+ return {
+ header: l.headerHeight !== 0,
+ footer: l.footerHeight !== 0,
+ qr: l.qr !== false,
+ transition: String(l.transition ?? 0.5),
+ style: l.transitionStyle ?? "fade",
+ loudness: typeof t !== "number" ? "off" : t === -16 ? "-16" : "custom",
+ target: typeof t === "number" ? String(t) : "-16",
+ captions: !!l.captions,
+ host: l.captions?.labels?.host ?? "",
+ subject: l.captions?.labels?.subject ?? "",
+ size: l.captions?.size ?? "m",
+ };
+}
+
+/** The patch that takes the saved look to the draft: only what changed, `null` to remove a key. */
+function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
+ const p: Record<string, unknown> = {};
+ if (d.header !== (was.headerHeight !== 0)) p.headerHeight = d.header ? null : 0;
+ if (d.footer !== (was.footerHeight !== 0)) p.footerHeight = d.footer ? null : 0;
+ if (d.qr !== (was.qr !== false)) p.qr = d.qr;
+ const tr = Number(d.transition);
+ if (tr !== (was.transition ?? 0.5)) p.transition = tr;
+ if (d.style !== (was.transitionStyle ?? "fade")) p.transitionStyle = d.style === "fade" ? null : d.style;
+ if (!view.montage) {
+ const target = d.loudness === "off" ? null : d.loudness === "-16" ? -16 : Number(d.target);
+ if (target !== (was.loudness?.target ?? null)) p.loudness = target === null ? null : { target };
+ }
+ if (!view.montage && !view.deck) {
+ const labels = { ...(d.host.trim() ? { host: d.host.trim() } : {}), ...(d.subject.trim() ? { subject: d.subject.trim() } : {}) };
+ const next = d.captions ? { style: "speakers", ...(Object.keys(labels).length ? { labels } : {}), ...(d.size === "l" ? { size: "l" } : {}) } : null;
+ if (JSON.stringify(next) !== JSON.stringify(was.captions ?? null)) p.captions = next;
+ }
+ return p;
+}
+
+export default function LookPanel({ project }: { project: string }) {
+ const [view, setView] = useState<View | null>(null);
+ const [draft, setDraft] = useState<Draft | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [status, setStatus] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json()) as View & { error?: string };
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ setView(j);
+ setDraft(draftOf(j.look));
+ }, [project]);
+ useEffect(() => {
+ load().catch((e) => setError(e instanceof Error ? e.message : String(e)));
+ }, [load]);
+
+ if (!view || !draft) {
+ return (
+ <Panel title="Look" data-look-panel="loading">
+ <p className="m-0 text-[12px] text-muted">{error ?? "reading the lookβ¦"}</p>
+ </Panel>
+ );
+ }
+ const set = (k: Partial<Draft>) => {
+ setDraft({ ...draft, ...k });
+ setStatus(null);
+ };
+ const patch = patchOf(view.look, draft, view);
+ const dirty = Object.keys(patch).length > 0;
+ const save = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/report/render", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token: view.token, patch }) });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean; look?: Look; token?: string };
+ if (r.status === 409) {
+ await load();
+ setError("the manifest changed since this was read β reloaded; check and save again");
+ return;
+ }
+ if (!r.ok) {
+ setError((j.errors ?? [j.error ?? `HTTP ${r.status}`]).join("; "));
+ return;
+ }
+ setView({ ...view, look: j.look ?? {}, token: j.token ?? null, errors: [] });
+ setDraft(draftOf(j.look ?? {}));
+ setStatus("Saved β the next render uses it");
+ } finally {
+ setBusy(false);
+ }
+ };
+ const check = (k: keyof Draft, label: string, attr: string, disabled = false) => (
+ <label className="inline-flex items-center gap-1.5 text-[12.5px] text-text">
+ <input type="checkbox" {...{ [attr]: "" }} checked={draft[k] as boolean} disabled={disabled || busy} onChange={(e) => set({ [k]: e.target.checked } as Partial<Draft>)} />
+ {label}
+ </label>
+ );
+
+ return (
+ <Panel title="Look" data-look-panel="" data-look-dirty={dirty ? "" : undefined}>
+ {view.errors.length > 0 && (
+ <p role="alert" data-look-errors="" className="m-0 mb-2 text-[12px] text-reject-text">
+ {view.errors.join("; ")}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
+ {check("header", "Header", "data-look-header")}
+ {check("footer", "Timeline footer", "data-look-footer")}
+ {check("qr", "QR code", "data-look-qr")}
+ </div>
+ <div className="mt-3 flex flex-wrap items-end gap-4">
+ <Field label="Between clips, s">
+ <Input data-look-transition="" type="number" min={0} max={3} step={0.1} value={draft.transition} disabled={busy} onChange={(e) => set({ transition: e.target.value })} className="w-[6em]" />
+ </Field>
+ <Field label="Join">
+ <Select data-look-style="" value={draft.style} disabled={busy || Number(draft.transition) === 0} onChange={(e) => set({ style: e.target.value })}>
+ {view.styles.map((s) => (
+ <option key={s} value={s}>
+ {STYLE_WORDS[s] ?? s}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ {!view.montage && (
+ <Field label="Loudness">
+ <span className="flex items-center gap-1.5">
+ <Select data-look-loudness="" value={draft.loudness} disabled={busy} onChange={(e) => set({ loudness: e.target.value as Draft["loudness"] })}>
+ <option value="off">as recorded</option>
+ <option value="-16">β16 LUFS (even)</option>
+ <option value="custom">custom</option>
+ </Select>
+ {draft.loudness === "custom" && (
+ <Input data-look-target="" type="number" min={-30} max={-8} step={0.5} value={draft.target} disabled={busy} onChange={(e) => set({ target: e.target.value })} className="w-[5.5em]" aria-label="Loudness target, LUFS" />
+ )}
+ </span>
+ </Field>
+ )}
+ </div>
+ <div className="mt-3 space-y-2">
+ {view.deck || view.montage ? (
+ <p className="m-0 text-[12px] text-muted" data-look-captions-off="">
+ {view.deck ? "Captions: the deck draws its own words (Media tab)." : "Captions: not for a montage."}
+ </p>
+ ) : (
+ <>
+ {check("captions", "Speaker captions", "data-look-captions")}
+ {draft.captions && (
+ <div className="flex flex-wrap items-end gap-4 pl-5">
+ <Field label="Host's name" hint="blank: told apart by colour">
+ <Input data-look-label-host="" value={draft.host} maxLength={40} disabled={busy} onChange={(e) => set({ host: e.target.value })} className="w-[12em]" />
+ </Field>
+ <Field label="Subject's name">
+ <Input data-look-label-subject="" value={draft.subject} maxLength={40} disabled={busy} onChange={(e) => set({ subject: e.target.value })} className="w-[12em]" />
+ </Field>
+ <Field label="Size">
+ <Select data-look-size="" value={draft.size} disabled={busy} onChange={(e) => set({ size: e.target.value as Draft["size"] })}>
+ <option value="m">medium</option>
+ <option value="l">large</option>
+ </Select>
+ </Field>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-3">
+ <button type="button" data-look-save="" disabled={busy || !dirty} onClick={() => void save()} className={buttonVariants({ variant: dirty ? "go" : "outline", size: "md" })}>
+ Save the look
+ </button>
+ {dirty && (
+ <button type="button" disabled={busy} onClick={() => setDraft(draftOf(view.look))} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Undo changes
+ </button>
+ )}
+ <span aria-live="polite" className="text-[12px]">
+ {error ? (
+ <span role="alert" data-look-error="" className="text-reject-text">
+ {error}
+ </span>
+ ) : status ? (
+ <span data-look-status="" className="text-muted">
+ {status}
+ </span>
+ ) : null}
+ </span>
+ </div>
+ </Panel>
+ );
+}
diff --git a/umtool/components/projects/report/ShortsList.tsx b/umtool/components/projects/report/ShortsList.tsx
@@ -0,0 +1,126 @@
+"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";
+
+// THE SHORTS (release 36 lane C): `<project>/shorts/<clipId>.mp4`, each one
+// clip at 1080x1920 (the clip editor's Make a short). Play one here, download
+// it, or make it again (the old one is set aside, never overwritten).
+
+type Short = { clip: string; size: number; mtimeMs: number; stale: boolean; gone: boolean; record: { cut?: [number, number] | null; captions?: { lines: number } | null; loudness?: { target: number } | null } | null };
+type Job = { id: string; state: string; error: string | null; kind?: string };
+
+export default function ShortsList({ project }: { project: string }) {
+ const [shorts, setShorts] = useState<Short[] | null>(null);
+ const [job, setJob] = useState<Job | null>(null);
+ const [playing, setPlaying] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/shorts?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json()) as { shorts?: Short[]; running?: Job | null; error?: string };
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ setShorts(j.shorts ?? []);
+ if (j.running) setJob(j.running);
+ }, [project]);
+ useEffect(() => {
+ load().catch((e) => setError(e instanceof Error ? e.message : String(e)));
+ }, [load]);
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/shorts?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as Job;
+ setJob(j);
+ if (j.state !== "running") await load().catch(() => {});
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, load]);
+
+ const remake = async (clip: string) => {
+ setError(null);
+ const r = await fetch("/api/report/shorts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip, replace: true }) });
+ 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) return;
+ await fetch(`/api/report/shorts?cancel=${job.id}`, { method: "POST" }).catch(() => null);
+ };
+ const file = (s: Short, extra = "") => `/api/report/shorts?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(s.clip)}&file=1&v=${s.mtimeMs}${extra}`;
+ const running = job?.state === "running";
+
+ return (
+ <Panel title={`Shorts${shorts?.length ? ` β ${shorts.length}` : ""}`} data-shorts={shorts?.length ?? 0}>
+ {shorts === null ? (
+ <p className="m-0 text-[12px] text-muted">{error ?? "reading the shortsβ¦"}</p>
+ ) : shorts.length === 0 && !running ? (
+ <p className="m-0 text-[12px] text-muted" data-shorts-empty="">
+ No shorts yet: the clip editor makes one of a clip (Make a short).{" "}
+ <Link href={clipEditorHref(project)} prefetch={false} className="ink-link">
+ Clip editor
+ </Link>
+ </p>
+ ) : (
+ <ul className="m-0 list-none space-y-2 p-0">
+ {shorts.map((s) => (
+ <li key={s.clip} data-short={s.clip} data-short-stale={s.stale ? "" : undefined} className="space-y-1">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <span className="font-mono text-[12.5px] text-text">{s.clip}</span>
+ <span className="num">
+ {fmtBytes(s.size)} Β· {fmtAgo(s.mtimeMs)}
+ {s.record?.cut ? ` Β· ${(s.record.cut[1] - s.record.cut[0]).toFixed(1)} s` : ""}
+ </span>
+ {s.stale && <span className={badgeVariants({ variant: "open", size: "sm" })}>the clip moved since</span>}
+ {s.gone && <span className={badgeVariants({ variant: "info", size: "sm" })}>no such clip now</span>}
+ <span className="ml-auto flex flex-wrap gap-1.5">
+ <button type="button" data-short-play={s.clip} onClick={() => setPlaying(playing === s.clip ? null : s.clip)} className={buttonVariants({ variant: playing === s.clip ? "pressed" : "outline", size: "sm" })}>
+ {playing === s.clip ? "Close" : "Play"}
+ </button>
+ <a href={file(s, "&download=1")} data-short-download={s.clip} className={buttonVariants({ size: "sm" })}>
+ Download
+ </a>
+ {!s.gone && (
+ <button type="button" data-short-remake={s.clip} disabled={running} onClick={() => void remake(s.clip)} className={buttonVariants({ size: "sm" })}>
+ Make again
+ </button>
+ )}
+ {!s.gone && (
+ <Link href={clipEditorHref(project, { clip: s.clip })} prefetch={false} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Frame it
+ </Link>
+ )}
+ </span>
+ </div>
+ {playing === s.clip && (
+ <video data-short-player={s.clip} src={file(s)} controls playsInline autoPlay className="max-h-[70vh] w-auto max-w-full rounded-[3px] bg-black" style={{ aspectRatio: "9 / 16" }} />
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ {job && (
+ <p data-shorts-job={job.state} className="m-0 mt-2 flex flex-wrap items-center gap-2 text-[12px] text-text-2">
+ {running ? `Making ${job.kind?.split(" ").at(-1) ?? "a short"}β¦` : job.state === "done" ? "Made." : `Failed${job.error ? `: ${job.error}` : ""}`}
+ {running && (
+ <button type="button" onClick={() => void cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ )}
+ </p>
+ )}
+ {error && shorts !== null && (
+ <p role="alert" className="m-0 mt-1 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ </Panel>
+ );
+}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -29,6 +29,9 @@ import { startTakeJob } from "../NewTakePanel";
// version, Add a clip from the selection, Bring in a proposal
// the comments a note on the clip (notes.json, anchored to it), its thread
// and an agent's replies, resolve / reopen
+// 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
//
// 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
@@ -81,6 +84,7 @@ export default function ClipEditor({
const [speakerPick, setSpeakerPick] = useState<number | null>(null);
const [rolesChanged, setRolesChanged] = useState(false);
const [busy, setBusy] = useState(false);
+ const [framing, setFraming] = useState(false);
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
const token = useRef<string | null>(initialView.token);
@@ -256,6 +260,12 @@ export default function ClipEditor({
if (j) setRolesChanged(true);
});
};
+ const setLabel = (speaker: number, label: string) => {
+ void write({ op: "label", speaker, label: label.trim() || null }, label.trim() ? `Speaker ${speaker} is β${label.trim()}β in the captions` : `Speaker ${speaker}'s name cleared`);
+ };
+ const setCrop = (crop: number[] | null, aspect?: number) => {
+ void write({ op: "vertical", clip: clip.id, crop, ...(crop && aspect ? { aspect: Math.round(aspect * 10000) / 10000 } : {}) }, crop ? "Saved the short's framing" : "The short is framed from the centre");
+ };
// Re-propose: the clip finder's proposal pass as a job (`umtool clips
// propose`, /api/report/clips); clips a person edited are never touched.
const [proposing, setProposing] = useState<{ id: string; state: string; error: string | null } | null>(null);
@@ -386,7 +396,7 @@ export default function ClipEditor({
</p>
)}
- <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} />
+ <Player ref={player} clipId={clip.id} targets={targets} cut={cut} onTime={setPlayhead} onPlaying={setPlaying} frame={framing ? { crop: clip.vertical?.crop ?? null, onChange: setCrop, busy } : null} />
{/* ---- the strip --------------------------------------------------- */}
<div className="space-y-1">
@@ -619,6 +629,7 @@ export default function ClipEditor({
{typeof s.sameAs === "number" ? ` Β· same voice as ${s.sameAs}` : ""}
</span>
<span className="num font-mono text-[11px] text-muted">{typeof s.seconds === "number" ? `${Math.round(s.seconds)} s` : ""}</span>
+ <SpeakerLabel speaker={s} busy={busy} onSave={(v) => setLabel(s.index, v)} />
{s.role !== "host" && (
<button type="button" data-speaker-host={s.index} disabled={busy} onClick={() => setRole(s.index, "host")} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}>
This is the host
@@ -632,6 +643,7 @@ export default function ClipEditor({
{view.reactionsError && <p className="m-0 text-[12px] text-reject-text">{view.reactionsError}</p>}
{view.rulingsError && <p className="m-0 text-[12px] text-reject-text">{view.rulingsError}</p>}
+ <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} />
<RenderTake project={project} render={render} takes={takes} takesHref={takesHref} />
</aside>
</div>
@@ -644,11 +656,14 @@ export default function ClipEditor({
// ---------------------------------------------------------------------------
type PlayerHandle = { toggle: () => void; seek: (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 };
-const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void }>(function Player({ clipId, targets, cut, onTime, onPlaying }, ref) {
+const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut: Cut; onTime: (t: number) => void; onPlaying: (p: boolean) => void; frame?: Frame | null }>(function Player({ clipId, targets, cut, onTime, onPlaying, frame = null }, ref) {
const [found, setFound] = useState<{ play: CitedPlay; from: number } | null | undefined>(undefined);
+ const [dims, setDims] = useState<{ w: number; h: number } | null>(null);
const media = useRef<HTMLMediaElement | null>(null);
// 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.
@@ -733,6 +748,8 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
onLoadedMetadata: (e: React.SyntheticEvent<HTMLMediaElement>) => {
ownSeek.current = true;
e.currentTarget.currentTime = fileT(cutRef.current.cutStart);
+ const v = e.currentTarget as HTMLVideoElement;
+ if (v.videoWidth > 0 && v.videoHeight > 0) setDims({ w: v.videoWidth, h: v.videoHeight });
},
onSeeked: (e: React.SyntheticEvent<HTMLMediaElement>) => {
if (ownSeek.current) ownSeek.current = false;
@@ -751,7 +768,19 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut
};
return (
<div data-editor-player={found.play.kind} className="w-full max-w-[720px]">
- {found.play.audio ? <audio {...props} className="w-full" /> : <video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" />}
+ {found.play.audio ? (
+ <audio {...props} className="w-full" />
+ ) : (
+ <div className="relative overflow-hidden rounded-[3px]">
+ <video {...props} playsInline className="aspect-video w-full rounded-[3px] bg-black" />
+ {frame && dims && <CropBox frame={frame} aspect={dims.w / dims.h} />}
+ </div>
+ )}
+ {frame && (found.play.audio || !dims) && (
+ <span data-crop-none="" className="micro block">
+ {found.play.audio ? "no picture here to frame: the short is cut from the centre" : "reading the pictureβ¦"}
+ </span>
+ )}
<span className="micro">{found.play.label}</span>
</div>
);
@@ -1081,3 +1110,203 @@ function RenderTake({ project, render, takes, takesHref }: { project: string; re
</section>
);
}
+
+// ---------------------------------------------------------------------------
+// The short (release 36): its 9:16 box on the player, its name for a voice,
+// and Make a short.
+// ---------------------------------------------------------------------------
+
+const VERTICAL = 9 / 16;
+const r4 = (n: number) => Math.round(n * 10000) / 10000;
+/** The centred, full-height 9:16 box on a source of aspect `a` (report-to-video/look.mjs defaultCrop). */
+function centreCrop(a: number): number[] {
+ let w = VERTICAL / a;
+ let h = 1;
+ if (w > 1) {
+ h = a / VERTICAL;
+ w = 1;
+ }
+ return [r4((1 - w) / 2), r4((1 - h) / 2), r4(w), r4(h)];
+}
+/** A box of height `h` (a fraction) about the centre (cx, cy), 9:16 on the source, inside the picture. */
+function boxAt(a: number, h: number, cx: number, cy: number): number[] {
+ let hh = Math.min(1, Math.max(0.2, h));
+ let w = (hh * VERTICAL) / a;
+ if (w > 1) {
+ w = 1;
+ hh = (w * a) / VERTICAL;
+ }
+ const x = Math.min(1 - w, Math.max(0, cx - w / 2));
+ const y = Math.min(1 - hh, Math.max(0, cy - hh / 2));
+ return [r4(x), r4(y), r4(w), r4(hh)];
+}
+
+/** The short's box over the picture: drag to move it, the slider sizes it; written when let go. */
+function CropBox({ frame, aspect }: { frame: Frame; aspect: number }) {
+ const [draft, setDraft] = useState<number[] | null>(null);
+ const crop = draft ?? frame.crop ?? centreCrop(aspect);
+ const area = useRef<HTMLDivElement | null>(null);
+ const drag = useRef<{ x0: number; y0: number; crop: number[]; w: number; h: number } | null>(null);
+ useEffect(() => setDraft(null), [frame.crop]);
+ // The picture inside the 16:9 player (object-fit: contain).
+ const P = 16 / 9;
+ const content = aspect >= P ? { left: 0, top: ((1 - P / aspect) / 2) * 100, width: 100, height: (P / aspect) * 100 } : { left: ((1 - aspect / P) / 2) * 100, top: 0, width: (aspect / P) * 100, height: 100 };
+ const [x, y, w, h] = crop;
+ const commit = (c: number[]) => frame.onChange(c, aspect);
+ return (
+ <>
+ <div ref={area} className="pointer-events-none absolute" style={{ left: `${content.left}%`, top: `${content.top}%`, width: `${content.width}%`, height: `${content.height}%` }}>
+ <div
+ data-crop-box={crop.join(",")}
+ role="slider"
+ aria-label="The short's framing: drag to move"
+ aria-valuenow={x}
+ tabIndex={0}
+ onPointerDown={(e) => {
+ if (e.button !== 0 || frame.busy) return;
+ e.stopPropagation();
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ const r = area.current!.getBoundingClientRect();
+ drag.current = { x0: e.clientX, y0: e.clientY, crop, w: Math.max(1, r.width), h: Math.max(1, r.height) };
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (!d) return;
+ const [dx, dy, dw, dh] = d.crop;
+ setDraft(boxAt(aspect, dh, dx + dw / 2 + (e.clientX - d.x0) / d.w, dy + dh / 2 + (e.clientY - d.y0) / d.h));
+ }}
+ onPointerUp={() => {
+ const moved = drag.current && draft;
+ drag.current = null;
+ if (moved && draft) commit(draft);
+ }}
+ className="pointer-events-auto absolute cursor-move border-2 border-signal shadow-[0_0_0_9999px_color-mix(in_srgb,black_55%,transparent)]"
+ style={{ left: `${x * 100}%`, top: `${y * 100}%`, width: `${w * 100}%`, height: `${h * 100}%` }}
+ />
+ </div>
+ <div className="absolute bottom-12 left-2 flex items-center gap-2 rounded-[3px] bg-[color-mix(in_srgb,black_70%,transparent)] px-2 py-1 text-[11.5px] text-white">
+ <label htmlFor="crop-size">Size</label>
+ <input
+ id="crop-size"
+ data-crop-size=""
+ type="range"
+ min={0.3}
+ max={1}
+ step={0.01}
+ value={h}
+ disabled={frame.busy}
+ onChange={(e) => setDraft(boxAt(aspect, Number(e.target.value), x + w / 2, y + h / 2))}
+ onPointerUp={() => draft && commit(draft)}
+ onKeyUp={() => draft && commit(draft)}
+ />
+ </div>
+ </>
+ );
+}
+
+/** A speaker's name in the captions: blank is the default (told apart by colour). */
+function SpeakerLabel({ speaker, busy, onSave }: { speaker: Speaker; busy: boolean; onSave: (v: string) => void }) {
+ const fallback = speaker.role === "host" ? "Host" : speaker.role === "subject" ? "Subject" : `Speaker ${speaker.index + 1}`;
+ const saved = speaker.label && speaker.label !== fallback ? speaker.label : "";
+ const [text, setText] = useState(saved);
+ useEffect(() => setText(saved), [saved]);
+ const commit = () => {
+ if (text.trim() !== saved) onSave(text);
+ };
+ return (
+ <input
+ data-speaker-label={speaker.index}
+ aria-label={`Speaker ${speaker.index}'s name in the captions`}
+ value={text}
+ maxLength={40}
+ disabled={busy}
+ placeholder="name"
+ onChange={(e) => setText(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") (e.target as HTMLInputElement).blur();
+ if (e.key === "Escape") {
+ setText(saved);
+ (e.target as HTMLInputElement).blur();
+ }
+ }}
+ className="w-[7.5em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text outline-none focus:border-signal"
+ />
+ );
+}
+
+/** Make a short: the clip at 1080x1920 from its box, a job; the one there is set aside, never overwritten. */
+function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy }: {
+ project: string;
+ clipId: string;
+ short: { mtimeMs: number; size: number; stale: boolean } | null;
+ framed: boolean;
+ framing: boolean;
+ onFraming: (on: boolean) => void;
+ onCentre: () => void;
+ onMade: () => void;
+ busy: boolean;
+}) {
+ const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ useEffect(() => {
+ setJob(null);
+ setErr(null);
+ }, [clipId]);
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/shorts?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { id: string; state: string; error: string | null };
+ setJob({ id: j.id, state: j.state, error: j.error });
+ if (j.state !== "running") onMade();
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, onMade]);
+ const make = async () => {
+ setErr(null);
+ const r = await fetch("/api/report/shorts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip: clipId, replace: !!short }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string; error: string | null }; error?: string };
+ if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
+ else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
+ };
+ const running = job?.state === "running";
+ return (
+ <section data-short-maker={clipId} data-short-made={short ? "" : undefined} className="space-y-1.5">
+ <h2 className="micro m-0">Short</h2>
+ <p className="m-0 text-[12px] text-text-2">
+ {framed ? "Framed by you" : "Framed from the centre"}
+ {short ? ` Β· made ${new Date(short.mtimeMs).toLocaleString()}${short.stale ? " Β· the clip moved since" : ""}` : ""}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ <button type="button" data-frame-short="" aria-pressed={framing} onClick={() => onFraming(!framing)} className={buttonVariants({ variant: framing ? "pressed" : "outline", size: "sm" })}>
+ {framing ? "Done framing" : "Frame the short"}
+ </button>
+ {framed && (
+ <button type="button" data-crop-centre="" disabled={busy} onClick={onCentre} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Centre it
+ </button>
+ )}
+ <button type="button" data-make-short={clipId} disabled={running || busy} onClick={() => void make()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {running ? "Making the shortβ¦" : short ? "Make the short again" : "Make a short"}
+ </button>
+ {short && (
+ <a href={`/api/report/shorts?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clipId)}&file=1&v=${short.mtimeMs}`} target="_blank" rel="noreferrer" data-short-open={clipId} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Play it
+ </a>
+ )}
+ </div>
+ {job && (
+ <p data-short-job={job.state} className="m-0 text-[12px] text-text-2">
+ {running ? "Rendering 1080Γ1920 in the heavy slot" : job.state === "done" ? "Made β on the Deliver tab's Shorts list" : `Failed${job.error ? `: ${job.error}` : ""}`}
+ </p>
+ )}
+ {err && (
+ <p role="alert" className="m-0 text-[12px] text-reject-text">
+ {err}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -24,6 +24,7 @@ Inbox cannot disagree about what is wrong with one.
| `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 |
| `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 |
| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` Β· `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` Β· `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold |
| `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there |
@@ -96,10 +97,11 @@ front of a twenty-minute build, and it exits non-zero so a script can gate on it
## Two deliberate limits
-**`build` prints, it does not run.** Cancellation, per-step timeouts and the
-process-group kill live in the server's job runner; a second runner here would be
-a second, worse set of those. Use **run** on the piece's Build tab, or paste the
-printed commands.
+**`build` prints, it does not run it itself.** Cancellation, per-step timeouts and
+the process-group kill live in the server's job runner; a second runner here would
+be a second, worse set of those. `build --run` asks the running app's runner to do
+it and follows the job (Ctrl-C cancels it there); otherwise use **run** on the
+piece's Build tab, or paste the printed commands.
**`check` cannot compute the song reducer.** Nine decision kinds are TypeScript
beside `readSong()`, the loudness cache and the accepted cover set. It reports how
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1204,6 +1204,56 @@ back. The writers are `lib/report/manifest.mjs` (`updateClip`, `restoreClip`,
`splitClip`, `mergeClips`, `addClip`); the editor's operations are
`lib/report/clipEditor.mjs` behind `/api/report/clip-editor`.
+## The look: captions, loudness, shorts (release 36)
+
+Three render keys and one clip key, all opt-in (absent or `null` is off, and the
+render is byte for byte what it was), validated by the build and by the lint
+(`report-to-video/look.mjs` `validateLook`, like `render.transitionStyle`):
+
+| Key | Shape | What it does |
+|---|---|---|
+| `render.captions` | `{style: "speakers", labels?: {host?, subject?}, size?: "m" \| "l"}` | Burned-in captions, 2β6 words a line, broken on pauses (0.45 s) and never across a change of speaker. Who says a word comes from `reactions.json`'s turns and roles: the **host** amber `#FFC840` bottom left, the **subject** sky `#6FD3FF` bottom right, anyone else (or a word heard in no turn) paper `#F6F1E6` bottom centre β black outline, IBM Plex Sans (vendored in `report-to-video/fonts/`). A voice is named only when somebody names it: `labels[role]`, else a speaker's own label in `reactions.json` when it is not the default ("Host", "Subject", "Speaker N"); the name heads the first line of each turn. Words: the project's `words.json` (the recording `reactions.json` describes), else the corpus's whisper words (`transcript.json`), else the cues spread by character. One ASS file per segment (`segments/<id>.captions.ass`), burned with libass (`ass=`). Not beside the deck (`render.chrome`, whose `fx.kineticQuote` is its own captions) or a montage. |
+| `render.loudness` | `{target: -16}` (β30 to β8 LUFS) | Each clip's cut measured (ffmpeg `ebur128`) and brought to the target with one gain (Β±20 dB at most) and a lookahead limiter at β1 dBFS β montage.mjs's `loudnessGain` + `levelFilters`, at the clip's encode. A cut quieter than β40 LUFS is taken for silence and left as it is. The cut record says `loudness: {measured, gain, target}`. Not with a montage (it levels with `render.montage.loudness`). |
+| clip `vertical` | `{crop: [x, y, w, h], aspect?}` | Fractions of the source picture: the box a vertical short is cut from, 9:16 on the source (`aspect` = the source's width / height, 16/9 when absent; within 3 %). Absent: the centred full-height box. |
+
+A site-less, one-video cut made by the clip finder starts with
+`headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5,
+transitionStyle: "fadeblack", loudness: {target: -16}` (lane B's seed).
+
+**The Look panel** (the Build tab, `/api/report/render`) sets them by hand:
+**Header**, **Timeline footer**, **QR code**, the length **Between clips** (0 is
+a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve),
+**Loudness** (as recorded, β16 LUFS, or a custom target) and **Speaker
+captions** with each role's name and the size. **Save the look** writes only
+what changed (`lib/report/manifest.mjs` `updateRender`: token-guarded, the
+build's own checks, atomic; `null` puts a key back to the build's default). It
+never touches `render.chrome` (the deck's own settings, the Media tab); a deck
+cut offers no captions, a montage neither captions nor loudness.
+
+**A speaker's name** is set in the clip editor's Speakers list (the box beside
+each speaker; blank is the default), written into `reactions.json` through the
+clip finder's `setSpeakerLabel` (common/lib/clips/reactions.mjs). A role change
+(This is the host) gives the default name back.
+
+**Shorts.** The clip editor's side column has **Short**: **Frame the short**
+draws the 9:16 box on the player β drag it, size it with the slider; it is
+written to the clip's `vertical` when let go (**Centre it** removes it) β and
+**Make a short** renders `<project>/shorts/<clipId>.mp4`: the clip alone at
+1080Γ1920, its box scaled to fill the frame, speaker captions at size "l" (the
+cut's names kept), no header, footer or QR, and the cut's loudness target (else
+β16). It is a job on umtool's runner (`/api/report/shorts`: one at a time, a
+log, Cancel), `build-video.mjs <manifest> --short <clipId>` inside the heavy
+slot; its work goes to `out/shorts-work/`, never the cut's segments. A short
+that is there is set aside as `shorts/<clipId>.<stamp>.mp4` before it is made
+again, never overwritten. A record beside each (`shorts/<clipId>.json`: the
+cut asked for and the one played, the crop, the size, the loudness, the
+captions, when) lets the **Shorts** list on the Deliver tab say when the clip
+moved since; there each short plays, downloads, is made again, or opens the
+clip in the editor to frame it.
+
+From a terminal: `node umtool/report-to-video/build-video.mjs
+<project>/video.manifest.json --short <clipId>`.
+
## Operator notes, timed notes and the generated-manifest guard
Notes on a project live in `<project>/notes.json` (shape and CLI:
diff --git a/umtool/e2e/clip-look.spec.ts b/umtool/e2e/clip-look.spec.ts
@@ -0,0 +1,114 @@
+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 look of a highlights cut (release 36 lane C). The Build tab's Look
+// panel saves the header, the QR, the join, the loudness and the speaker
+// captions into the manifest (and reads them back); the clip editor's
+// Speakers list names a voice for the captions (reactions.json); Frame the
+// short drags a 9:16 box on the player (the clip's vertical.crop); Make a
+// short runs the job (build-video --short) and the Deliver tab's Shorts list
+// shows it and plays it. Fixture: e2e/fixtures/clip-editor-fixture.mjs, as
+// reports/clip-look-fixture.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/clip-look-fixture";
+const DIR = path.join(FIXTURE, "reports", "clip-look-fixture");
+const json = (name: string) => {
+ try {
+ return JSON.parse(readFileSync(path.join(DIR, name), "utf8"));
+ } catch {
+ return null;
+ }
+};
+const render = () => json("video.manifest.json")?.render ?? {};
+const clip = (id: string) => (json("video.manifest.json")?.timeline ?? []).find((e: { id: string }) => e.id === id) ?? null;
+
+test("the look: the panel saves and reads back; a voice named; a short framed, made and listed", async ({ page }) => {
+ test.setTimeout(240_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+
+ // ---- the Look panel --------------------------------------------------------
+ await page.goto(urls.section(PROJECT, "build"));
+ const panel = page.locator("[data-look-panel]");
+ await expect(panel).toHaveAttribute("data-look-panel", "");
+ await expect(page.locator("[data-look-header]")).toBeChecked();
+ await expect(page.locator("[data-look-save]")).toBeDisabled();
+ await page.locator("[data-look-header]").uncheck();
+ await page.locator("[data-look-qr]").uncheck();
+ await page.locator("[data-look-transition]").fill("0.5");
+ await page.locator("[data-look-style]").selectOption("fadeblack");
+ await page.locator("[data-look-loudness]").selectOption("-16");
+ await page.locator("[data-look-captions]").check();
+ await page.locator("[data-look-label-host]").fill("The host");
+ await page.locator("[data-look-size]").selectOption("l");
+ await page.locator("[data-look-save]").click();
+ await expect(page.locator("[data-look-status]")).toHaveText("Saved β the next render uses it");
+ const r = render();
+ expect(r.headerHeight).toBe(0);
+ expect(r.qr).toBe(false);
+ expect(r.transition).toBe(0.5);
+ expect(r.transitionStyle).toBe("fadeblack");
+ expect(r.loudness).toEqual({ target: -16 });
+ expect(r.captions).toEqual({ style: "speakers", labels: { host: "The host" }, size: "l" });
+ expect(r.width).toBe(640);
+ // Read back after a reload.
+ await page.reload();
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "");
+ await expect(page.locator("[data-look-header]")).not.toBeChecked();
+ await expect(page.locator("[data-look-qr]")).not.toBeChecked();
+ await expect(page.locator("[data-look-style]")).toHaveValue("fadeblack");
+ await expect(page.locator("[data-look-loudness]")).toHaveValue("-16");
+ await expect(page.locator("[data-look-captions]")).toBeChecked();
+ await expect(page.locator("[data-look-label-host]")).toHaveValue("The host");
+
+ // ---- the clip editor: a voice named, the short framed --------------------
+ await page.goto(urls.clipEditorHref(PROJECT, { clip: "r001" }));
+ await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r001");
+ const subject = page.locator('[data-speaker-label="1"]');
+ await subject.fill("The narrator");
+ await subject.press("Enter");
+ await expect.poll(() => json("reactions.json")?.speakers?.find((s: { index: number }) => s.index === 1)?.label).toBe("The narrator");
+
+ await expect(page.locator("[data-editor-player]")).toHaveAttribute("data-editor-player", /^(?!looking|none)/, { timeout: 20_000 });
+ await page.locator("[data-frame-short]").click();
+ const box = page.locator("[data-crop-box]");
+ await expect(box).toBeVisible();
+ const at = await box.boundingBox();
+ if (!at) throw new Error("no crop box");
+ await page.mouse.move(at.x + at.width / 2, at.y + at.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(at.x + at.width / 2 + 120, at.y + at.height / 2, { steps: 6 });
+ await page.mouse.up();
+ await expect.poll(() => clip("r001")?.vertical?.crop?.[0] ?? null).toBeGreaterThan(0.36);
+ const crop = clip("r001").vertical.crop as number[];
+ expect(crop[3]).toBe(1);
+ expect(Math.abs((crop[2] * (640 / 360)) / crop[3] - 9 / 16)).toBeLessThan(0.01);
+ await expect(page.locator("[data-short-maker]")).toContainText("Framed by you");
+
+ // ---- Make a short: the job, then the file --------------------------------
+ await page.locator('[data-make-short="r001"]').click();
+ await expect(page.locator("[data-short-job]")).toHaveAttribute("data-short-job", "done", { timeout: 180_000 });
+ expect(existsSync(path.join(DIR, "shorts", "r001.mp4"))).toBe(true);
+ const rec = json("shorts/r001.json");
+ expect(rec.width).toBe(1080);
+ expect(rec.height).toBe(1920);
+ expect(rec.crop).toEqual(crop);
+ await expect(page.locator('[data-make-short="r001"]')).toHaveText("Make the short again");
+
+ // ---- the Shorts list on the Deliver tab ----------------------------------
+ await page.goto(urls.section(PROJECT, "deliver"));
+ const row = page.locator('[data-short="r001"]');
+ await expect(row).toBeVisible();
+ await expect(page.locator("[data-shorts]")).toHaveAttribute("data-shorts", "1");
+ await row.locator('[data-short-play="r001"]').click();
+ const player = page.locator('[data-short-player="r001"]');
+ await expect(player).toBeVisible();
+ await expect.poll(() => player.evaluate((v: HTMLVideoElement) => v.videoHeight)).toBe(1920);
+ await expect(row.locator('[data-short-download="r001"]')).toHaveAttribute("href", /download=1/);
+});
diff --git a/umtool/e2e/fixtures/clip-editor-fixture.mjs b/umtool/e2e/fixtures/clip-editor-fixture.mjs
@@ -20,13 +20,16 @@ const write = (dir, name, doc) => {
};
/**
- * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o
+ * `name`: another copy under another name (release 36: clip-look.spec.ts's
+ * clip-look-fixture), so two specs never edit one project.
+ *
+ * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]>, name?: string, title?: string }} o
*/
-export function makeClipEditorFixture({ reports, manifest, cachedWindow, cues }) {
- const dir = path.join(reports, "clip-editor-fixture");
+export function makeClipEditorFixture({ reports, manifest, cachedWindow, cues, name = "clip-editor-fixture", title = "The Clip Editor Fixture" }) {
+ const dir = path.join(reports, name);
const assist = (p, s, e, cs, ce, score, why) => ({ by: "assistant", proposal: p, score, why, original: { start: s, end: e, cutStart: cs, cutEnd: ce }, edits: [] });
const clip = (id, s, e, cs, ce, p, score, why, quote) => ({ type: "clip", id, video: "vid1", start: s, end: e, cutStart: cs, cutEnd: ce, quote, assist: assist(p, s, e, cs, ce, score, why) });
- const doc = manifest("clip-editor-fixture", "The Clip Editor Fixture", { siteOrigin: "https://archive.example" }, [
+ const doc = manifest(name, title, { siteOrigin: "https://archive.example" }, [
clip("r001", 0.5, 3.5, 1, 3, "p001", 0.8, "host laughs at the line", "This is a complete sentence."),
clip("r002", 4, 6, 4, 6, "p002", 0.7, "a comment", "And this one runs on"),
clip("r003", 6.5, 8.5, 6.5, 8.5, "p003", 0.6, "a short comment", "of that it finishes here."),
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1810,6 +1810,8 @@ makeClipDeckFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out",
makeMontageOpsFixture({ reports, channels: CHANNELS, manifest });
// Release 35 C2: the clip editor, an assistant's clips adjusted by hand (clip-editor.spec.ts).
makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// Release 36 lane C: the Look panel, a short's framing and Make a short (clip-look.spec.ts).
+makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-look-fixture", title: "The Clip Look Fixture" });
// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
diff --git a/umtool/lib/report/buildRun.mjs b/umtool/lib/report/buildRun.mjs
@@ -0,0 +1,63 @@
+// `umtool build <project> --run` (release 36 lane C): the build chain as the
+// project page runs it -- a job on the running umtool app's runner (POST
+// /api/report/build), followed from the terminal (its log, polled), cancelled
+// on Ctrl-C (POST ?cancel=<job>). The app owns the steps, the timeouts, the
+// process-group kill and the heavy slot; this only asks and watches. Without
+// `--run` the command prints the chain, as before.
+//
+// Plain ESM: the CLI runs under bare node.
+
+/** Where the app answers: `--url`, else UMTOOL_URL, else the local default. */
+export const umtoolBase = (url, env = process.env) => String(url || env.UMTOOL_URL || "http://localhost:3050").replace(/\/+$/, "");
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Start the build and follow it to the end.
+ *
+ * @param {{ base: string, project: string, preset?: string, only?: string | null, skipFetch?: boolean,
+ * replace?: boolean, token?: string | null, pollMs?: number, fetchImpl?: typeof fetch,
+ * log?: (line: string) => void, onJob?: (cancel: () => Promise<boolean>) => void }} o
+ * @returns {Promise<{ state: string, job: string | null, error: string | null, needsReplace?: boolean }>}
+ */
+export async function runBuildOverHttp({
+ base, project, preset = "fast", only = null, skipFetch = false, replace = false, token = null,
+ pollMs = 1500, fetchImpl = fetch, log = (l) => console.log(l), onJob = () => {},
+}) {
+ const headers = { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) };
+ const call = async (method, route, body) => {
+ try {
+ const res = await fetchImpl(`${base}${route}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
+ return { status: res.status, json: await res.json().catch(() => ({})) };
+ } catch (err) {
+ return { status: 0, json: { error: `umtool at ${base} did not answer: ${err?.message ?? err}` } };
+ }
+ };
+ const started = await call("POST", `/api/report/build${replace ? "?replace=1" : ""}`, { project, preset, ...(only ? { only } : {}), ...(skipFetch ? { skipFetch: true } : {}) });
+ if (started.status !== 200 || !started.json?.job?.id) {
+ const j = started.json ?? {};
+ return { state: "refused", job: null, error: String(j.error ?? `HTTP ${started.status}`), ...(j.needsReplace ? { needsReplace: true } : {}) };
+ }
+ const id = started.json.job.id;
+ log(`job ${id}: ${started.json.job.kind ?? "build"}`);
+ for (const s of started.json.steps ?? []) log(` step: ${s.label}`);
+ onJob(async () => (await call("POST", `/api/report/build?cancel=${encodeURIComponent(id)}`)).json?.cancelled === true);
+ let since = 0;
+ let sinceEvent = 0;
+ let misses = 0;
+ for (;;) {
+ const r = await call("GET", `/api/report/build?job=${encodeURIComponent(id)}&since=${since}&sinceEvent=${sinceEvent}`);
+ if (r.status !== 200) {
+ misses += 1;
+ if (misses >= 40) return { state: "lost", job: id, error: String(r.json?.error ?? `HTTP ${r.status}`) };
+ await sleep(pollMs);
+ continue;
+ }
+ misses = 0;
+ for (const line of r.json.log ?? []) log(line);
+ since = Number.isFinite(r.json.next) ? r.json.next : since + (r.json.log?.length ?? 0);
+ if (Number.isFinite(r.json.nextEvent)) sinceEvent = r.json.nextEvent;
+ if (r.json.state !== "running") return { state: r.json.state, job: id, error: r.json.error ?? null };
+ await sleep(pollMs);
+ }
+}
diff --git a/umtool/lib/report/buildRun.test.mjs b/umtool/lib/report/buildRun.test.mjs
@@ -0,0 +1,86 @@
+// `umtool build --run` (release 36 lane C): the build route as the CLI asks
+// it -- started, followed (the log as it grows), cancelled, refused -- against
+// a fake app on a local port. Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import http from "node:http";
+import test from "node:test";
+
+import { runBuildOverHttp, umtoolBase } from "./buildRun.mjs";
+
+/** A fake umtool: the build route's POST, GET ?job= and ?cancel=. */
+async function fakeApp(handler) {
+ const seen = [];
+ const server = http.createServer(async (req, res) => {
+ let body = "";
+ for await (const c of req) body += c;
+ const url = new URL(req.url, "http://x");
+ seen.push({ method: req.method, path: url.pathname, query: Object.fromEntries(url.searchParams), body: body ? JSON.parse(body) : null, auth: req.headers.authorization ?? null });
+ const [status, json] = handler(seen.at(-1), seen);
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(json));
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return { base, seen, close: () => new Promise((r) => server.close(r)) };
+}
+
+test("umtoolBase: --url, else UMTOOL_URL, else the local default; no trailing slash", () => {
+ assert.equal(umtoolBase("http://h:1/", {}), "http://h:1");
+ assert.equal(umtoolBase(undefined, { UMTOOL_URL: "http://u:2//" }), "http://u:2");
+ assert.equal(umtoolBase(undefined, {}), "http://localhost:3050");
+});
+
+test("runBuildOverHttp: starts the job, prints its log as it grows, ends with its state", async () => {
+ let polls = 0;
+ const app = await fakeApp((r) => {
+ if (r.method === "POST" && !r.query.cancel) return [200, { ok: true, job: { id: "j1", kind: "build reports/x (fast)" }, steps: [{ label: "check" }, { label: "build" }] }];
+ if (r.method === "GET") {
+ polls += 1;
+ const log = ["line 1", "line 2", "line 3"];
+ const since = Number(r.query.since);
+ return polls < 3
+ ? [200, { state: "running", log: log.slice(since, polls), next: polls, nextEvent: polls * 2, error: null }]
+ : [200, { state: "done", log: log.slice(since), next: 3, nextEvent: 6, error: null }];
+ }
+ return [404, {}];
+ });
+ try {
+ const lines = [];
+ const r = await runBuildOverHttp({ base: app.base, project: "reports/x", preset: "final", only: null, token: "tok", pollMs: 5, log: (l) => lines.push(l) });
+ assert.deepEqual(r, { state: "done", job: "j1", error: null });
+ assert.deepEqual(lines, ["job j1: build reports/x (fast)", " step: check", " step: build", "line 1", "line 2", "line 3"]);
+ assert.deepEqual(app.seen[0].body, { project: "reports/x", preset: "final" });
+ assert.equal(app.seen[0].auth, "Bearer tok");
+ // Each poll asks only for what it has not seen.
+ assert.deepEqual(app.seen.slice(1).map((s) => [s.query.since, s.query.sinceEvent]), [["0", "0"], ["1", "2"], ["2", "4"]]);
+ } finally {
+ await app.close();
+ }
+});
+
+test("runBuildOverHttp: a newer deliverable is refused until --replace; a running job is named; Ctrl-C cancels", async () => {
+ const app = await fakeApp((r) => {
+ if (r.method === "POST" && r.query.cancel) return [200, { cancelled: true }];
+ if (r.method === "POST" && r.query.replace !== "1") return [409, { error: "x.mp4 is newer than the manifest", needsReplace: true }];
+ if (r.method === "POST") return [200, { ok: true, job: { id: "j2", kind: "build" } }];
+ return [200, { state: "failed", log: ["** cancel requested"], next: 1, error: "cancelled" }];
+ });
+ try {
+ const refused = await runBuildOverHttp({ base: app.base, project: "reports/x", log: () => {} });
+ assert.deepEqual(refused, { state: "refused", job: null, error: "x.mp4 is newer than the manifest", needsReplace: true });
+ let cancel = null;
+ const r = await runBuildOverHttp({ base: app.base, project: "reports/x", replace: true, skipFetch: true, only: "c1", pollMs: 5, log: () => {}, onJob: (c) => (cancel = c) });
+ assert.equal(r.state, "failed");
+ assert.equal(r.error, "cancelled");
+ assert.deepEqual(app.seen[1].body, { project: "reports/x", preset: "fast", only: "c1", skipFetch: true });
+ assert.equal(await cancel(), true);
+ assert.equal(app.seen.at(-1).query.cancel, "j2");
+ } finally {
+ await app.close();
+ }
+ const gone = await runBuildOverHttp({ base: "http://127.0.0.1:9", project: "p", log: () => {} });
+ assert.equal(gone.state, "refused");
+ assert.match(gone.error, /did not answer/);
+});
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -38,7 +38,8 @@ import {
updateClip,
} from "./manifest.mjs";
import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs";
-import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs";
+import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs";
+import { readShorts } from "./shorts.mjs";
import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs";
import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
@@ -83,7 +84,8 @@ export async function readWords(dir, reactions = null) {
/**
* @typedef {{ id: string, channel: string | null, video: string, start: number, end: number,
* cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null,
- * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean }} EditorClip
+ * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean,
+ * vertical: { crop: number[], aspect?: number } | null }} EditorClip
*/
/** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */
@@ -110,8 +112,11 @@ export async function clipEditorView(project) {
key,
ruling: key ? (rulings.doc.rulings[key]?.verdict ?? null) : null,
montage: isObj(e.montage),
+ // A short's framing (release 36): fractions of the source picture.
+ vertical: isObj(e.vertical) && Array.isArray(e.vertical.crop) ? { crop: e.vertical.crop, ...(fin(e.vertical.aspect) ? { aspect: e.vertical.aspect } : {}) } : null,
};
});
+ const shorts = await readShorts(project.dir, manifest);
const doc = reactions.doc;
return {
clips,
@@ -130,6 +135,7 @@ export async function clipEditorView(project) {
}
: null,
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 }])),
};
}
@@ -229,6 +235,8 @@ const num = (v, what) => {
* bring-in { proposal } one of the clip finder's unused proposals
* ruling { clip, verdict: "keep" | "cut" | null }
* role { speaker, role | null } reactions.json, through the clip finder's writer
+ * label { speaker, label | null } a speaker's name for the captions (reactions.json)
+ * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short
* with `token` (the manifest's, from the view) on every manifest edit.
* Returns `{ op, result, carried, view }`.
*/
@@ -338,8 +346,25 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
structural = false;
break;
}
+ case "label": {
+ const index = Number(body.speaker);
+ if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index");
+ if (body.label !== null && typeof body.label !== "string") throw new OpError("label is a text, or null for the default");
+ const doc = await setSpeakerLabel(dir, index, body.label);
+ result = { speaker: doc.speakers.find((x) => x?.index === index) ?? null };
+ structural = false;
+ break;
+ }
+ case "vertical": {
+ const e = needClip();
+ const v = body.crop === null ? null : { crop: body.crop, ...(body.aspect !== undefined ? { aspect: Number(body.aspect) } : {}) };
+ // A "trim" that leaves the cut where it is: the clip's assist is not touched.
+ result = await updateClip(dir, e.id, { vertical: v }, { token, edit: "trim", now });
+ structural = false;
+ break;
+ }
default:
- throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling or role");
+ throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label or vertical");
}
let carried = null;
if (structural) {
diff --git a/umtool/lib/report/clipEditorBridge.mjs b/umtool/lib/report/clipEditorBridge.mjs
@@ -48,6 +48,13 @@ export async function readReactions(dir) {
*/
export { setSpeakerRole } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+/**
+ * A person's name for one speaker (release 36): THE CLIP FINDER'S FILE, the
+ * one other write the editor makes into it -- what the speaker captions head
+ * that voice's lines with. Empty gives the default back.
+ */
+export { setSpeakerLabel } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+
/** Re-propose is the clip finder's proposal pass: POST /api/report/clips {project, mode: "propose"} (`umtool clips propose`, a job). */
export const reproposeAvailable = true;
export const REPROPOSE_UNAVAILABLE = null;
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -25,6 +25,8 @@ export type EditorClip = {
key: string | null;
ruling: string | null;
montage: boolean;
+ /** A short's framing (release 36): `crop` = [x, y, w, h], fractions of the source picture. */
+ vertical: { crop: number[]; aspect?: number } | null;
};
export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number };
@@ -45,6 +47,8 @@ export type EditorView = {
rolesChangedAt: string | null;
} | null;
repropose: { available: boolean; why: string | null };
+ /** The shorts on disk, by clip id (release 36). */
+ shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>;
};
export type Turn = { start: number; end: number; speaker: number };
diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs
@@ -0,0 +1,187 @@
+// The look in umtool (release 36 lane C): updateRender (the Look panel's
+// writer), a clip's `vertical` through updateClip and the clip editor's
+// `vertical` / `label` operations, and the shorts on disk (readShorts, the
+// replace guard, the job's step). Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { LOOK_KEYS, MANIFEST_NAME, RenderRefused, StaleToken, lookOf, manifestToken, updateClip, updateRender } from "./manifest.mjs";
+import { clipEditorView, runClipEditorOp } from "./clipEditor.mjs";
+import { readShorts, safeClipId, setShortAside, shortFile, shortSteps } from "./shorts.mjs";
+
+const manifest = (render = {}) => ({
+ schemaVersion: 1,
+ slug: "look",
+ provenance: { channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000" }, ...render },
+ timeline: [
+ { type: "clip", id: "r001", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19, quote: "q", assist: { by: "assistant", proposal: "p001", original: { start: 10, end: 20, cutStart: 11, cutEnd: 19 }, edits: [] } },
+ { type: "clip", id: "r002", video: "v1", start: 30, end: 40 },
+ ],
+});
+const REACTIONS = {
+ version: 1,
+ source: { channel: "chan", video: "v1", duration: 80, words: null },
+ params: {},
+ speakers: [
+ { index: 0, role: "host", label: "Host", how: "auto" },
+ { index: 1, role: "subject", label: "Subject", how: "auto" },
+ ],
+ turns: [], laughs: [], moments: [], proposals: [],
+};
+
+async function project(render = {}) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-look-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(render), null, 2) + "\n");
+ await writeFile(path.join(dir, "reactions.json"), JSON.stringify(REACTIONS, null, 1) + "\n");
+ return { id: "reports/look", dir, kind: "report" };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+
+test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => {
+ const p = await project({ transition: 0.4, crf: 21 });
+ try {
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]);
+ const token = await manifestToken(p.dir);
+ const r = await updateRender(p.dir, {
+ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
+ loudness: { target: -16 }, captions: { style: "speakers", labels: { host: "Nik" } },
+ }, { token });
+ assert.deepEqual(r.look, {
+ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
+ loudness: { target: -16 }, captions: { style: "speakers", labels: { host: "Nik" } },
+ });
+ const m = await read(p.dir);
+ assert.equal(m.render.crf, 21, "the rest of the render is as it was");
+ assert.equal(m.render.width, 1920);
+ assert.deepEqual(lookOf(m.render), r.look);
+ // A stale token is refused; nothing written.
+ await assert.rejects(updateRender(p.dir, { qr: true }, { token }), StaleToken);
+ // null removes; qr: true turns the code back on (removes the false).
+ const r2 = await updateRender(p.dir, { headerHeight: null, qr: true, loudness: null, transitionStyle: null });
+ assert.equal("headerHeight" in r2.look, false);
+ assert.equal("qr" in r2.look, false);
+ assert.equal("loudness" in r2.look, false);
+ assert.equal("transitionStyle" in r2.look, false);
+ // Refusals: the build's own sentences, and nothing written.
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(updateRender(p.dir, { chrome: { engine: "hyperframes" } }), (e) => e instanceof RenderRefused && /render\.chrome is the deck's/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { crf: 18 }), (e) => e instanceof RenderRefused && /render\.crf is not a look setting/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { loudness: { target: -40 } }), (e) => e instanceof RenderRefused && /target must be a number from -30 to -8/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { captions: { style: "karaoke" } }), (e) => e instanceof RenderRefused && /captions\.style/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { transitionStyle: "spin" }), (e) => e instanceof RenderRefused);
+ await assert.rejects(updateRender(p.dir, { headerHeight: 12.5 }), (e) => e instanceof RenderRefused && /whole number of pixels/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { transition: 9 }), (e) => e instanceof RenderRefused && /from 0 \(a hard cut\) to 3/.test(e.errors[0]));
+ await assert.rejects(updateRender(p.dir, { qr: "yes" }), (e) => e instanceof RenderRefused);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("updateRender: captions beside the deck are refused (the deck draws its own words)", async () => {
+ const p = await project({ chrome: { engine: "hyperframes", layout: "deck" } });
+ try {
+ await assert.rejects(updateRender(p.dir, { captions: { style: "speakers" } }), (e) => e instanceof RenderRefused && /does not combine with render\.chrome/.test(e.errors.join(" ")));
+ // Loudness is fine under a deck.
+ const r = await updateRender(p.dir, { loudness: { target: -14 } });
+ assert.deepEqual(r.look.loudness, { target: -14 });
+ assert.deepEqual((await read(p.dir)).render.chrome, { engine: "hyperframes", layout: "deck" }, "never touches render.chrome");
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("updateClip: a clip's vertical crop, checked, rounded, removable; the assistant's clip stays the assistant's", async () => {
+ const p = await project();
+ try {
+ await updateClip(p.dir, "r001", { vertical: { crop: [0.123456, 0, 0.316406, 1], aspect: 16 / 9 } });
+ let e = (await read(p.dir)).timeline[0];
+ assert.deepEqual(e.vertical, { crop: [0.1235, 0, 0.3164, 1], aspect: 1.7778 });
+ assert.equal(e.assist.by, "assistant");
+ assert.deepEqual(e.assist.edits, []);
+ await assert.rejects(updateClip(p.dir, "r001", { vertical: { crop: [0, 0, 0.6, 1] } }), /must be 9:16 on the source/);
+ await assert.rejects(updateClip(p.dir, "r001", { vertical: { crop: [0.9, 0, 0.3164, 1] } }), /inside the picture/);
+ await updateClip(p.dir, "r001", { vertical: null });
+ e = (await read(p.dir)).timeline[0];
+ assert.equal(e.vertical, undefined);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("the clip editor: vertical and label operations; the view carries the crop and the shorts", async () => {
+ const p = await project();
+ try {
+ let view = await clipEditorView(p);
+ assert.equal(view.clips[0].vertical, null);
+ assert.deepEqual(view.shorts, {});
+ const r = await runClipEditorOp(p, { op: "vertical", clip: "r001", crop: [0.5, 0, 0.3164, 1], aspect: 1.7778, token: view.token });
+ assert.deepEqual(r.view.clips[0].vertical, { crop: [0.5, 0, 0.3164, 1], aspect: 1.7778 });
+ const r2 = await runClipEditorOp(p, { op: "vertical", clip: "r001", crop: null, token: r.view.token });
+ assert.equal(r2.view.clips[0].vertical, null);
+ // A speaker's name: the captions' label.
+ const l = await runClipEditorOp(p, { op: "label", speaker: 0, label: " Nik " });
+ assert.equal(l.result.speaker.label, "Nik");
+ assert.equal(l.result.speaker.role, "host");
+ const doc = JSON.parse(await readFile(path.join(p.dir, "reactions.json"), "utf8"));
+ assert.equal(doc.speakers[0].label, "Nik");
+ assert.equal(doc.speakers[1].label, "Subject", "only that speaker");
+ // Empty: the default again.
+ const back = await runClipEditorOp(p, { op: "label", speaker: 0, label: null });
+ assert.equal(back.result.speaker.label, "Host");
+ await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 0, label: "x".repeat(41) }), /up to 40 characters/);
+ await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 9, label: "x" }), /no speaker 9/);
+ await assert.rejects(runClipEditorOp(p, { op: "label", speaker: 0, label: 3 }), /label is a text/);
+ // A short on disk shows in the view; stale once the clip moves.
+ await mkdir(path.join(p.dir, "shorts"), { recursive: true });
+ await writeFile(path.join(p.dir, "shorts", "r001.mp4"), "mp4");
+ await writeFile(path.join(p.dir, "shorts", "r001.json"), JSON.stringify({ version: 1, clip: "r001", requested: { cutStart: 11, cutEnd: 19 }, crop: null }));
+ view = await clipEditorView(p);
+ assert.equal(view.shorts.r001.stale, false);
+ await updateClip(p.dir, "r001", { cutStart: 12 });
+ view = await clipEditorView(p);
+ assert.equal(view.shorts.r001.stale, true);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("shorts: listed newest first, a set-aside one kept and not listed, the replace guard, the job's one step", async () => {
+ const p = await project();
+ try {
+ assert.deepEqual(await readShorts(p.dir), []);
+ await mkdir(path.join(p.dir, "shorts"), { recursive: true });
+ await writeFile(path.join(p.dir, "shorts", "r002.mp4"), "two");
+ await writeFile(path.join(p.dir, "shorts", "gone1.mp4"), "old");
+ await writeFile(path.join(p.dir, "shorts", "r002.20260101-1200.mp4"), "aside");
+ const m = await read(p.dir);
+ const list = await readShorts(p.dir, m);
+ assert.deepEqual(list.map((x) => x.clip).sort(), ["gone1", "r002"]);
+ assert.equal(list.find((x) => x.clip === "gone1").gone, true);
+ assert.equal(list.find((x) => x.clip === "r002").gone, false);
+ // The guard: there is one, so it is refused unless replace.
+ await assert.rejects(setShortAside(p.dir, "r002"), (e) => e.needsReplace === true);
+ const aside = await setShortAside(p.dir, "r002", { replace: true, now: new Date(2026, 9, 19, 9, 5) });
+ assert.equal(path.basename(aside), "r002.20261019-0905.mp4");
+ assert.equal(await stat(path.join(p.dir, "shorts", "r002.mp4")).catch(() => null), null);
+ assert.equal(await setShortAside(p.dir, "r001"), null, "nothing there: nothing to set aside");
+ // Names only.
+ assert.equal(shortFile(p.dir, "../x"), null);
+ assert.equal(safeClipId("r001-2"), true);
+ assert.equal(safeClipId("a/b"), false);
+ const [step] = shortSteps(p, "r001");
+ assert.deepEqual(step.argv.slice(-4), ["--short", "r001", "--progress", "ndjson"]);
+ assert.ok(step.argv[1].endsWith(path.join("report-to-video", "build-video.mjs")));
+ assert.equal(step.argv[2], path.join(p.dir, "video.manifest.json"));
+ assert.equal(step.ndjson, true);
+ assert.throws(() => shortSteps(p, "../etc"), /not a clip id/);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -33,6 +33,8 @@ import { isCalendarDate } from "umtool-report-to-video/attribution";
import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck";
import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { validateLook, verticalErrors } from "umtool-report-to-video/look";
+import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition";
import { applySectionEnter } from "./sections.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { validateNarration } from "umtool-report-to-video/narration";
@@ -380,6 +382,23 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri
// and a row saved from the On-screen table cannot store different shapes.
if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen);
+ // ---- the vertical short's framing (release 36 lane C) --------------------
+ //
+ // `vertical: {crop: [x, y, w, h], aspect?}` -- fractions of the source
+ // picture, 9:16 on it (look.mjs verticalErrors, the build's own check).
+ // null or "" removes it: the short is cut from the centre again.
+ if (patch.vertical !== undefined) {
+ const v = patch.vertical;
+ if (v === null || v === "") delete entry.vertical;
+ else {
+ const errors = verticalErrors(v, "vertical");
+ if (errors.length) throw new Error(errors.join("; "));
+ const r4 = (n) => Number(Number(n).toFixed(4));
+ const vv = /** @type {{ crop: number[], aspect?: number }} */ (v);
+ entry.vertical = { crop: vv.crop.map(r4), ...(vv.aspect !== undefined ? { aspect: r4(vv.aspect) } : {}) };
+ }
+ }
+
// ---- an assistant's clip, edited by a person (release 35 C2) -------------
//
// A clip the clip finder proposed carries `assist`. The first human edit
@@ -893,6 +912,100 @@ export class ChromeRefused extends Error {
// ---------------------------------------------------------------------------
+// THE LOOK (release 36 lane C): the render keys a person sets for a cut that
+// has no deck -- the header and footer heights, the QR, the crossfade's length
+// and style, the loudness target, the speaker captions. Never `render.chrome`
+// (updateChrome is its writer). Token-guarded, validated with the build's own
+// checks against the render as it will be, then written atomically.
+// ---------------------------------------------------------------------------
+
+/** The render keys the Look panel writes, in its order. */
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions"]);
+
+/** The look keys of a render block as written (absent keys left out). */
+export function lookOf(render) {
+ const r = isObj(render) ? render : {};
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k];
+ return out;
+}
+
+/** The build's sentences for a refused look, thrown whole so a route can return each one. */
+export class RenderRefused extends Error {
+ /** @param {string[]} errors */
+ constructor(errors) {
+ super(`render: ${errors.join("; ")}`);
+ this.name = "RenderRefused";
+ this.errors = errors;
+ }
+}
+
+const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
+
+/**
+ * Patch the look. Each key of `patch` is one of LOOK_KEYS; `null` removes the
+ * key (the build's default again). `qr: true` turns the code back on (removes
+ * a `false`; an object of settings is kept), `qr: false` turns it off.
+ *
+ * @param {string} dir
+ * @param {Record<string, unknown>} patch
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ look: Record<string, unknown>, token: string | null }>}
+ */
+export async function updateRender(dir, patch, { token = null } = {}) {
+ if (!isObj(patch)) throw new RenderRefused(["the patch must be an object of render keys"]);
+ const errors = [];
+ for (const k of Object.keys(patch)) {
+ if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here");
+ else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`);
+ }
+ 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 : {}) };
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null) {
+ delete render[k];
+ continue;
+ }
+ switch (k) {
+ case "headerHeight":
+ case "footerHeight":
+ if (!intIn(v, 0, 240)) errors.push(`render.${k} must be a whole number of pixels from 0 to 240`);
+ else render[k] = v;
+ break;
+ case "qr":
+ if (v === false) render.qr = false;
+ else if (v === true) {
+ if (render.qr === false) delete render.qr;
+ } else errors.push("render.qr must be true (on) or false (off)");
+ break;
+ case "transition":
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 3) errors.push("render.transition must be a number of seconds from 0 (a hard cut) to 3");
+ else render.transition = round2(v);
+ break;
+ case "transitionStyle":
+ if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
+ else render.transitionStyle = v;
+ break;
+ default:
+ // loudness, captions: stored as given; the build's validators below say what is wrong.
+ render[k] = v;
+ }
+ }
+ const next = { ...manifest, render };
+ errors.push(...validateTransitionStyle(next), ...validateLook(next));
+ if (errors.length) throw new RenderRefused(errors);
+ manifest.render = render;
+ const nextToken = await writeManifestAtomic(dir, manifest);
+ return { look: lookOf(render), token: nextToken };
+ });
+}
+
+// ---------------------------------------------------------------------------
// POSTS: the two things a person decides about a post once an agent has put it
// in the manifest -- which clip it rides on, and whether it is shown at all.
//
diff --git a/umtool/lib/report/shorts.mjs b/umtool/lib/report/shorts.mjs
@@ -0,0 +1,119 @@
+// VERTICAL SHORTS (release 36 lane C): one clip of a report video as a
+// 1080x1920 file, `<project>/shorts/<clipId>.mp4`, made by build-video.mjs
+// `--short <clipId>` (report-to-video/look.mjs shortRender: the clip's
+// `vertical.crop`, large speaker captions, no header or QR, the loudness
+// target) as a job through lib/jobs.ts, which build-video's CLI runs inside
+// the machine's heavy slot. A record beside each (`<clipId>.json`) says what
+// it was made from, so the list can say when the clip has moved since.
+import { readFile, readdir, rename, stat } from "node:fs/promises";
+import path from "node:path";
+import { PIPELINE_DIR } from "./driver.mjs";
+
+export const SHORTS_DIR = "shorts";
+/** A short of a clip is minutes at most; a stuck encode is not left forever. */
+export const SHORT_TIMEOUT_MS = 20 * 60_000;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+/** A clip id as a file name: letters, digits, `.`, `_`, `-` only. */
+export const safeClipId = (id) => typeof id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/.test(id) && !id.includes("..");
+
+export const shortsDirOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SHORTS_DIR);
+
+/** `<project>/shorts/<clipId>.mp4`, or null for an id that is not a file name. */
+export function shortFile(dir, clipId) {
+ return safeClipId(clipId) ? path.join(/* turbopackIgnore: true */ shortsDirOf(dir), `${clipId}.mp4`) : null;
+}
+
+/**
+ * The job's one step: build-video `--short`, NDJSON progress, beside the
+ * build's own steps (lib/report/driver.mjs). No path or argv from a client.
+ *
+ * @param {{ dir: string }} project
+ * @param {string} clipId
+ */
+export function shortSteps(project, clipId) {
+ if (!safeClipId(clipId)) throw new Error(`not a clip id: ${clipId}`);
+ return [
+ {
+ cwd: PIPELINE_DIR,
+ env: {},
+ label: `make the short of ${clipId} (1080Γ1920)`,
+ argv: [
+ "node", path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"),
+ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
+ "--out", path.join(/* turbopackIgnore: true */ project.dir, "out"),
+ "--short", clipId, "--progress", "ndjson",
+ ],
+ ndjson: true,
+ timeoutMs: SHORT_TIMEOUT_MS,
+ },
+ ];
+}
+
+const sameNums = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => Math.abs(x - b[i]) < 0.011);
+
+/**
+ * Every short on disk, newest first: `{ clip, size, mtimeMs, record, stale,
+ * gone }`. `stale`: the clip's cut or crop moved since the short was made;
+ * `gone`: no clip has that id now.
+ *
+ * @param {string} dir the project
+ * @param {any} [manifest] the manifest as read (for stale / gone)
+ */
+export async function readShorts(dir, manifest = null) {
+ const names = await readdir(shortsDirOf(dir)).catch(() => []);
+ const clips = new Map((manifest?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => [e.id, e]));
+ const out = [];
+ for (const name of names) {
+ // A short set aside (`<id>.<stamp>.mp4`) is kept, not listed.
+ if (!name.endsWith(".mp4") || /\.\d{8}-\d{4}\.mp4$/.test(name)) continue;
+ const clip = name.slice(0, -4);
+ if (!safeClipId(clip)) continue;
+ const st = await stat(path.join(/* turbopackIgnore: true */ shortsDirOf(dir), name)).catch(() => null);
+ if (!st?.isFile()) continue;
+ const record = await readFile(path.join(/* turbopackIgnore: true */ shortsDirOf(dir), `${clip}.json`), "utf8").then(JSON.parse, () => null);
+ const e = clips.get(clip) ?? null;
+ let stale = false;
+ if (e && isObj(record)) {
+ const want = [e.cutStart ?? e.start, e.cutEnd ?? e.end];
+ const had = isObj(record.requested) ? [record.requested.cutStart, record.requested.cutEnd] : null;
+ const crop = Array.isArray(e.vertical?.crop) ? e.vertical.crop : null;
+ stale = (had !== null && had.every(fin) && !sameNums(want, had)) || JSON.stringify(crop) !== JSON.stringify(record.crop ?? null);
+ }
+ out.push({ clip, size: st.size, mtimeMs: Math.round(st.mtimeMs), record: isObj(record) ? record : null, stale, gone: manifest ? !e : false });
+ }
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
+}
+
+/** `20260817-1408`: a short set aside before it is made again. */
+function stamp(d = new Date()) {
+ const p = (n) => String(n).padStart(2, "0");
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
+}
+
+/**
+ * The replace guard: a short that is there is never overwritten unasked.
+ * With `replace`, it is moved aside to `shorts/<clipId>.<stamp>.mp4` (its
+ * record too) and the path it went to is returned; without, an error naming
+ * `replace`. No short there: null.
+ *
+ * @param {string} dir
+ * @param {string} clipId
+ * @param {{ replace?: boolean, now?: Date }} [o]
+ */
+export async function setShortAside(dir, clipId, { replace = false, now = new Date() } = {}) {
+ const file = shortFile(dir, clipId);
+ if (!file) throw new Error(`not a clip id: ${clipId}`);
+ const st = await stat(file).catch(() => null);
+ if (!st) return null;
+ if (!replace) {
+ const err = new Error(`${clipId} has a short already β make it again to set that one aside (replace)`);
+ /** @type {any} */ (err).needsReplace = true;
+ throw err;
+ }
+ const aside = file.replace(/\.mp4$/, `.${stamp(now)}.mp4`);
+ await rename(file, aside);
+ await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {});
+ return aside;
+}
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -14,6 +14,7 @@ Two scripts and a manifest:
| `brand.mjs`, `brand-cards.mjs` | stable | the opt-in brand preset (`render.brand`); see [its section](#the-archilyzer-media-preset-renderbrand). |
| `montage.mjs`, `montage-styles.mjs` | stable | montage editing (`render.montage`) and its named styles; see [its section](#rendermontage--montage-editing-release-33). |
| `montage-rulings.mjs` | stable | the clip deck's rulings (`montage-rulings.json` beside the manifest), applied at render; see [its section](#montage-rulingsjson--the-clip-decks-rulings-release-34). |
+| `look.mjs` | stable | the look of a highlights cut: `render.captions`, `render.loudness`, a clip's `vertical` and the short (`--short`); see [its section](#rendercaptions-renderloudness-a-clips-vertical-and---short-release-36). |
| `<report>/video.manifest.json` | per report | the edit decision list. **This is the regeneration source of truth**, not the report. |
```
@@ -885,6 +886,30 @@ node umtool/report-to-video/montage-styles.mjs list
node umtool/report-to-video/montage-styles.mjs apply flash-count video.manifest.json --out takes/flash/video.manifest.json
```
+### `render.captions`, `render.loudness`, a clip's `vertical` and `--short` (release 36)
+
+`look.mjs` (pure) validates and plans them; build-video's hooks run only when a
+key is set, so a manifest without them renders byte for byte as before
+(md5-checked against main on a two-clip fadeblack fixture: final, segments and
+cut records).
+
+- `render.captions: {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"}`
+ β per segment an ASS file (`segments/<id>.captions.ass`) from the project's
+ `words.json` (the recording `reactions.json` names), else whisper's words, else
+ the cues; `reactions.json`'s turns colour and place each line (host `#FFC840`
+ left, subject `#6FD3FF` right, other `#F6F1E6` centre), 2β6 words a line,
+ broken on 0.45 s pauses, never across a speaker change; burned with `ass=`
+ (libass, fonts from `fonts/`). Refused beside `render.chrome` or a montage.
+- `render.loudness: {target}` (β30β¦β8 LUFS) β each cut measured (`ebur128`) and
+ levelled with montage.mjs's `loudnessGain` + `levelFilters` at its encode; the
+ cut record carries `loudness: {measured, gain, target}`. Refused with a montage.
+- clip `vertical: {crop: [x, y, w, h], aspect?}` β fractions of the source, 9:16
+ on it (Β±3 %); `cropPixels` makes it exact and even.
+- `--short <id>` β that clip alone with `shortRender(render)` (1080Γ1920, no
+ header/footer/QR/rail/deck, captions size "l", the cut's loudness else β16)
+ into `out/shorts-work/`, then `<manifest dir>/shorts/<id>.mp4` + `<id>.json`.
+ Takes the heavy slot.
+
### `montage-rulings.json` β the clip deck's rulings (release 34)
Beside the manifest, written by umtool's clip deck (`/projects/<id>/clips`) and
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -165,6 +165,13 @@ import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage
import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { transitionStyleOf, validateTransitionStyle } from "./transition.mjs";
+// The look of a highlights cut (release 36 lane C): render.captions,
+// render.loudness, a clip's vertical crop and the short made from it -- pure,
+// in look.mjs. Every hook below runs only when its key is set.
+import {
+ assDocument, assFilter, captionGeometry, captionLines, captionsOn, loudnessTargetOf, shortRender, validateLook,
+ verticalFilters,
+} from "./look.mjs";
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
import { pruneChromeFrames } from "./prune-frames.mjs";
@@ -180,7 +187,7 @@ import {
// An opt-in brand preset (`render.brand`). Every hook below branches on the
// brand BEFORE building an argument, so a manifest without one renders exactly
// as it did -- see brand.mjs.
-import { brandHeaderGeometry, brandManifest } from "./brand.mjs";
+import { FONTS_DIR, brandHeaderGeometry, brandManifest } from "./brand.mjs";
import { markPng, renderThumbnail, THUMB_MAX_BYTES } from "./brand-cards.mjs";
// Montage editing (`render.montage`, release 33): the tight phrase cut, the
// pieces, the cut styles, the counter and the wall -- pure, in montage.mjs.
@@ -189,7 +196,7 @@ import {
clipPhrase, cutStyleParts, locatePhrase, montageFont, montageOn, montageOverlayFilters, montagePieces,
montagePiecesGraph, montageSplit, montageWindow, parseClipDate, planMontage, refineOnset, resolveMontage,
bandFeatures, consensusLags, templateOnset,
- validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
+ validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, levelFilters, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
} from "./montage.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
@@ -1218,6 +1225,23 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
start: Number((fetchStart + cutA).toFixed(3)), end: Number((fetchStart + cutB).toFixed(3)),
snapped: { start: a.snapped, end: b.snapped },
};
+ // Even loudness for a cut that is not a montage (render.loudness, release
+ // 36): the cut as it will play, measured, one gain toward the target
+ // (montage.mjs loudnessGain), in the cut record. A montage levels with its
+ // own key; absent, nothing here runs.
+ if (!mont && loudnessTargetOf(render) != null) {
+ level = await montageLevel(raw, cutA, cutB, { target: loudnessTargetOf(render) });
+ cutRecord.loudness = level;
+ }
+ // The sound's graph: `[0:a]` levelled to `[al]` (an asplit first when a
+ // poster's waveform also reads it), else nothing and `0:a` as ever.
+ const leveled = !mont && level != null;
+ const levelParts = (posterParts) => (leveled
+ ? [
+ ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${levelFilters(level.gain)}[al]`] : [`[0:a]${levelFilters(level.gain)}[al]`]),
+ ]
+ : (posterParts ?? []));
+ const audioMap = leveled ? "[al]" : "0:a";
const quotePath = path.join(outDir, "segments", `${entry.id}.quote.txt`);
const attribPath = path.join(outDir, "segments", `${entry.id}.attrib.txt`);
@@ -1264,10 +1288,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
...cutArgs(raw, cutA, cutB),
...(pst ? pst.input : []),
"-filter_complex", [
- ...(pst ? pst.parts : []),
+ ...levelParts(pst ? pst.parts : null),
`${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed" })}[v]`,
].join(";"),
- "-map", "[v]", "-map", "0:a",
+ "-map", "[v]", "-map", audioMap,
...encodeArgs(render),
seg,
],
@@ -1320,7 +1344,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
? String(fillB)
: `${fillA}+(${fillB - fillA})*clip(t/${T},0,1)`;
- const base = [
+ // A short (look.mjs): the clip's 9:16 crop scaled to fill the frame -- no
+ // letterbox, no header. A source with no picture keeps the poster's framing.
+ const shortPicture = dirs.short && media.hasVideo
+ ? verticalFilters(entry.vertical?.crop ?? null, ...(await probeDims(raw)), { width, height, fps: render.fps })
+ : null;
+ const base = shortPicture ? shortPicture.join(",") : [
`scale=${VW}:${VH}:force_original_aspect_ratio=decrease`,
`pad=${VW}:${VH}:(ow-iw)/2:(oh-ih)/2:color=${pal.bg}`,
// Widen back to the full frame, leaving the rail column (if any) as ground.
@@ -1385,7 +1414,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]");
const lead = mg
? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts]
- : (pst ? pst.parts : []);
+ : levelParts(pst ? pst.parts : null);
const parts = hasFooter
? [
@@ -1411,6 +1440,21 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
);
// A montage's cut style and its counter, over the finished frame.
if (mg) parts.push(...mg.post("[v]", "[vm]"));
+ let vOut = mg ? "[vm]" : "[v]";
+ // Speaker captions (render.captions), over the finished frame: an ASS file
+ // beside the segment, burned with libass. None when the clip has no words.
+ if (dirs.look && captionsOn(render)) {
+ const cap = await segmentCaptions({
+ entry, provenance, look: dirs.look, render, outDir,
+ from: cutRecord.start, seconds: cutB - cutA, bottom: FH,
+ });
+ if (cap) {
+ parts.push(`${vOut}${cap.filter}[vc]`);
+ vOut = "[vc]";
+ cutRecord.captions = { lines: cap.lines, words: cap.wordsFrom };
+ }
+ }
+ if (dirs.short) cutRecord.short = { crop: entry.vertical?.crop ?? null, width, height };
await execFileP(
FFMPEG,
@@ -1418,7 +1462,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-nostdin", "-v", "error", "-y",
...inputs,
"-filter_complex", parts.join(";"),
- "-map", mg ? "[vm]" : "[v]", "-map", mg ? mg.a : "0:a",
+ "-map", vOut, "-map", mg ? mg.a : audioMap,
...encodeArgs(render),
seg,
],
@@ -1434,6 +1478,141 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
return seg;
}
+// ---- the look (render.captions, a short; release 36 lane C) ---------------
+// The build's side of look.mjs: what needs the project's files, the corpus
+// and ffmpeg. Reached only when render.captions is set, or for a short.
+
+/** A picture's display size `[w, h]` (its sample aspect applied), for a short's crop. */
+async function probeDims(file) {
+ const { stdout } = await execFileP(FFPROBE, [
+ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,sample_aspect_ratio", "-of", "json", file,
+ ]);
+ const st = JSON.parse(stdout).streams?.[0] ?? {};
+ const [n, d] = String(st.sample_aspect_ratio ?? "1:1").split(":").map(Number);
+ const sar = n > 0 && d > 0 ? n / d : 1;
+ const w = Math.round(Number(st.width) * sar);
+ const h = Number(st.height);
+ if (!(w > 0 && h > 0)) throw new Error(`${path.basename(file)}: no picture size to crop a short from`);
+ return [w, h];
+}
+
+/**
+ * What the captions read beside the manifest: reactions.json (the clip
+ * finder's turns and roles, when it is version 1) and the words file it names
+ * (`source.words`, else words.json), read once.
+ */
+async function readLookSources(manifestDir) {
+ let reactions = null;
+ try {
+ const doc = JSON.parse(await readFile(path.join(manifestDir, "reactions.json"), "utf8"));
+ if (doc?.version === 1 && Array.isArray(doc.turns)) reactions = doc;
+ } catch {
+ reactions = null;
+ }
+ return { manifestDir, reactions, words: null, transcripts: new Map() };
+}
+
+/** Does reactions.json describe this clip's recording? */
+function lookMatches(entry, provenance, rx) {
+ if (!rx?.source?.video || hasLocalMedia(entry) || entry.video !== rx.source.video) return false;
+ const ch = entry.channel ?? provenance?.channelSlug ?? null;
+ return !rx.source.channel || !ch || ch === rx.source.channel;
+}
+
+const wordOf = (w) => ({ text: String(w?.w ?? w?.word ?? w?.text ?? ""), start: Number(w?.start), end: Number(w?.end) });
+
+/**
+ * A clip's words, turns and speakers in [from, to] (source seconds): the
+ * project's words file for the recording reactions.json describes, else the
+ * corpus's whisper words (transcript.json), else its cues spread by
+ * character. Turns and speakers only from reactions.json.
+ */
+async function lookWordsFor(entry, provenance, look, from, to) {
+ const inSpan = (w) => Number.isFinite(w.start) && Number.isFinite(w.end) && (w.start + w.end) / 2 >= from - 0.05 && (w.start + w.end) / 2 <= to + 0.05;
+ const rx = lookMatches(entry, provenance, look.reactions) ? look.reactions : null;
+ const turns = rx ? rx.turns.filter((t) => t.end > from && t.start < to) : [];
+ const speakers = rx?.speakers ?? [];
+ if (rx) {
+ look.words ??= readFile(path.join(look.manifestDir, typeof rx.source.words === "string" ? rx.source.words : "words.json"), "utf8")
+ .then((t) => {
+ const doc = JSON.parse(t);
+ return (Array.isArray(doc) ? doc : doc?.words ?? []).map(wordOf);
+ })
+ .catch(() => null);
+ const ws = await look.words;
+ if (ws?.length) {
+ const got = ws.filter(inSpan);
+ if (got.length) return { words: got, turns, speakers, wordsFrom: "words.json" };
+ }
+ }
+ if (!hasLocalMedia(entry) && FX_CHANNELS_DIR && entry.video) {
+ const slug = entry.channel ?? provenance?.channelSlug;
+ const key = `${slug}/${entry.video}`;
+ if (!look.transcripts.has(key)) {
+ look.transcripts.set(key, resolveVideoDir(FX_CHANNELS_DIR, slug, entry.video)
+ .then((dir) => readFile(path.join(dir, "transcript.json"), "utf8"))
+ .then((t) => whisperWords(JSON.parse(t)))
+ .catch(() => null));
+ }
+ const ws = await look.transcripts.get(key);
+ const got = (ws ?? []).map(wordOf).filter(inSpan);
+ if (got.length) return { words: got, turns, speakers, wordsFrom: "transcript.json" };
+ }
+ const cues = fxWordsOf(await montageCues(entry, provenance), from - 0.05, to + 0.05).map(wordOf);
+ return { words: cues, turns, speakers, wordsFrom: "cues" };
+}
+
+/**
+ * One segment's captions: the ASS file beside it (segments/<id>.captions.ass)
+ * and the filter that burns it in, or null (a note) when the clip has no
+ * words. `from` is the source second the segment starts at.
+ */
+async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom }) {
+ const src = await lookWordsFor(entry, provenance, look, from, from + seconds);
+ if (!src.words.length) {
+ EMIT("note", { message: `${entry.id}: no words to caption β it plays without captions` });
+ return null;
+ }
+ const rel = (x) => ({ ...x, start: x.start - from, end: x.end - from });
+ const size = render.captions?.size ?? "m";
+ const geo = captionGeometry({ width: render.width, height: render.height, size, bottom });
+ const lines = captionLines({
+ words: src.words.map(rel), turns: src.turns.map(rel), speakers: src.speakers, captions: render.captions,
+ seconds, maxChars: geo.maxChars,
+ });
+ const file = path.join(outDir, "segments", `${entry.id}.captions.ass`);
+ await writeFile(file, assDocument(lines, { width: render.width, height: render.height, size, bottom }), "utf8");
+ return { filter: assFilter(file, FONTS_DIR), lines: lines.length, wordsFrom: src.wordsFrom };
+}
+
+/**
+ * A short's segment to <project>/shorts/<id>.mp4 (tmp + rename), with a
+ * record beside it (<id>.json: the cut, the crop, the size, the loudness,
+ * the captions, when). Returns the mp4's path.
+ */
+async function placeShort(seg, manifestDir, entry, render) {
+ const dir = path.join(manifestDir, "shorts");
+ await mkdir(dir, { recursive: true });
+ const dest = path.join(dir, `${entry.id}.mp4`);
+ const tmp = `${dest}.tmp-${process.pid}`;
+ await writeFile(tmp, await readFile(seg));
+ await rename(tmp, dest);
+ const rec = await readCutRecord(seg).catch(() => null);
+ const record = {
+ version: 1, clip: entry.id, video: entry.video ?? null,
+ // What was asked for (the clip's cut, else its extent) and what played (snapped).
+ requested: { cutStart: entry.cutStart ?? entry.start, cutEnd: entry.cutEnd ?? entry.end },
+ cut: rec ? [rec.start, rec.end] : null,
+ crop: entry.vertical?.crop ?? null,
+ width: render.width, height: render.height,
+ loudness: rec?.loudness ?? null,
+ captions: rec?.captions ?? null,
+ madeAt: new Date().toISOString(),
+ };
+ await replaceFile(path.join(dir, `${entry.id}.json`), JSON.stringify(record, null, 2) + "\n");
+ return dest;
+}
+
// ---- montage (render.montage) ---------------------------------------------
// The build's side of montage.mjs: what needs the cue source, the corpus and
// ffmpeg. Reached only when render.montage is set.
@@ -1616,7 +1795,7 @@ async function montageCheckSound({ entry, mont, raw, fetchStart, M, render, prov
* A stretch of a source's integrated loudness (LUFS, ffmpeg's ebur128), or
* null when it cannot be measured.
*/
-async function measureLoudness(raw, from, to) {
+export async function measureLoudness(raw, from, to) {
const { stderr } = await execFileP(FFMPEG, [
"-nostdin", "-hide_banner", "-ss", Math.max(0, from).toFixed(3), "-to", to.toFixed(3), "-i", raw,
"-vn", "-af", "ebur128", "-f", "null", "-",
@@ -4825,6 +5004,12 @@ export async function prepareLocalMedia(timeline, manifestDir, render = {}) {
export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } = {}) {
const variant = opts.variant ?? "sourced";
+ // A vertical short (`--short <id>`, release 36 lane C) is that one clip,
+ // built as `--only` builds it, in a look of its own (look.mjs shortRender).
+ if (opts.short) {
+ if (only && only !== opts.short) throw new Error(`--short ${opts.short} and --only ${only} name different clips`);
+ only = opts.short;
+ }
const whole = JSON.parse(await readFile(manifestPath, "utf8"));
// An `image` entry's `src` is relative to the MANIFEST, which is checked in
// beside the pictures it cites -- not to the cwd the build was started from.
@@ -4839,6 +5024,12 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
? { manifest: whole, left: [], matched: [], renumbered: false }
: applyMontageRulings(whole, await readMontageRulings(manifestDir), { keep: only ? [only] : [] });
const manifest = selectVariant(ruled.manifest, variant);
+ if (opts.short) {
+ const e = (manifest.timeline ?? []).find((x) => x.id === opts.short);
+ if (!e) throw new Error(`no timeline entry with id ${opts.short}`);
+ if (e.type !== "clip") throw new Error(`${opts.short} is a ${e.type ?? "non-clip"} entry: a short is made from a clip`);
+ manifest.render = shortRender(manifest.render ?? {});
+ }
for (const message of rulingsLines(ruled)) EMIT("note", { message });
const { render, provenance } = manifest;
// A `src` clip's file and cues, checked and measured before anything else.
@@ -4855,6 +5046,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole),
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole),
+ ...validateLook(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -4912,6 +5104,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
});
const outRoot = out ?? path.join(path.dirname(path.resolve(manifestPath)), "out");
const dirs = variantPaths(outRoot, manifest.slug, variant);
+ // A short's work is its own: the cut's segments are never overwritten by one.
+ if (opts.short) dirs.dir = path.join(outRoot, "shorts-work");
const outDir = dirs.dir;
// Where media may already be on disk. The channels tree is the one the clip
// bench reads for this project (sources.mjs channelsDirFor): the manifest's
@@ -4925,6 +5119,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe,
});
FX_CHANNELS_DIR = channelsDir;
+ // Speaker captions read the project's reactions.json and words beside the
+ // manifest (readLookSources); a short is framed by its clip's crop.
+ if (captionsOn(render)) dirs.look = await readLookSources(manifestDir);
+ if (opts.short) dirs.short = { id: opts.short };
// A project's out/ first, through ensureOutDir: with UMTOOL_MEDIA_DIR set it
// is a link to the media root, and the recursive mkdirs below would
@@ -5387,6 +5585,12 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
}
if (only) {
+ // A short leaves its work dir for <project>/shorts/<id>.mp4 (placeShort).
+ if (opts.short && segments[0] && !failures.length) {
+ const placed = await placeShort(segments[0], manifestDir, entries[0], render);
+ EMIT("done", { out: placed, failures, short: opts.short });
+ return { out: placed, failures };
+ }
EMIT("done", { out: segments[0], failures });
return { out: segments[0], failures };
}
@@ -5626,6 +5830,8 @@ export function chromeFlags(argv) {
* chapters and the thumbnail do not.
*/
export function takesHeavySlot({ opts = {}, only = null, fetchOnly = null } = {}) {
+ // A short is a 1080x1920 encode of one clip: a render, in the slot.
+ if (opts.short && !fetchOnly) return true;
return !fetchOnly && !only && !opts.chaptersOnly && !opts.thumbnailOnly;
}
@@ -5647,7 +5853,7 @@ async function main() {
if (!manifestPath) {
console.error(
"usage: build-video.mjs <manifest.json> [--out <dir>] [--variant sourced|full]\n" +
- " [--only <id>] [--fetch-only <id>]\n" +
+ " [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" +
" [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" +
" [--progress ndjson] [--continue-on-error] [--no-reuse]\n" +
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
@@ -5695,6 +5901,7 @@ async function main() {
narrationUnreviewed: argv.includes("--narration-unreviewed"),
final: argv.includes("--final"),
draftsUnreviewed: argv.includes("--drafts-unreviewed"),
+ short: flag("--short") ?? null,
};
try {
Object.assign(opts, chromeFlags(argv));
@@ -5725,7 +5932,7 @@ async function main() {
process.exit(lint.errors.length ? 1 : 0);
}
- const only = flag("--only");
+ const only = flag("--only") ?? opts.short ?? undefined;
const fetchOnly = flag("--fetch-only");
const build = () => buildVideo({ manifestPath, opts, out: flag("--out"), only, fetchOnly });
const { failures } = takesHeavySlot({ opts, only, fetchOnly })
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -88,6 +88,7 @@ import { validateMontage } from "./montage.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { validateFxEntries } from "./fx.mjs";
import { validateTransitionStyle } from "./transition.mjs";
+import { validateLook } from "./look.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
@@ -240,6 +241,8 @@ export function validatorErrors(whole) {
...validateFxEntries(whole),
// Release 35: the crossfade's look between clips.
...validateTransitionStyle(whole),
+ // Release 36: render.captions, render.loudness and a clip's vertical crop.
+ ...validateLook(whole),
];
if (deckOn(whole.render)) {
errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`));
diff --git a/umtool/report-to-video/look.mjs b/umtool/report-to-video/look.mjs
@@ -0,0 +1,403 @@
+// THE LOOK of a highlights cut (release 36 lane C): three opt-in render keys
+// and one clip key, validated here (the build's validators and the lint call
+// validateLook, as they call validateTransitionStyle), and the pure pieces the
+// build draws them with.
+//
+// render.captions {style: "speakers", labels?: {host?, subject?}, size?: "m" | "l"}
+// burned-in captions, coloured and placed by who speaks
+// (reactions.json's turns and roles), 2-6 words a line
+// render.loudness {target: -16} (LUFS, -30 to -8)
+// each clip's cut measured (ebur128) and brought to the
+// target with one gain and a limiter (montage.mjs's
+// loudnessGain + levelFilters)
+// clip.vertical {crop: [x, y, w, h], aspect?} fractions of the source
+// picture: the box a vertical short (1080x1920) is cut from;
+// `aspect` is the source's width/height (16/9 when absent)
+//
+// Absent (or null) = off, and the render is byte for byte what it was.
+//
+// THE CAPTION COLOURS are fixed, not the palette's: a caption has to read on
+// any footage, and a person tells the voices apart by colour first.
+// host #FFC840 amber bottom left
+// subject #6FD3FF sky bottom right
+// other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn)
+// Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR.
+
+export const CAPTION_STYLES = Object.freeze(["speakers"]);
+export const CAPTION_SIZES = Object.freeze(["m", "l"]);
+export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]);
+export const CAPTION_COLOURS = Object.freeze({ host: "#FFC840", subject: "#6FD3FF", other: "#F6F1E6" });
+/** ASS alignment (numpad): host bottom-left, subject bottom-right, other bottom-centre. */
+export const CAPTION_ALIGN = Object.freeze({ host: 1, subject: 3, other: 2 });
+/** The font, vendored in fonts/ (IBM Plex Sans, OFL): libass is pointed at that directory. */
+export const CAPTION_FONT = "IBM Plex Sans";
+export const CAPTION_LABEL_MAX = 40;
+/** Words a line: at least (unless a speaker change or the clip's end forces fewer), at most. */
+export const CAPTION_MIN_WORDS = 2;
+export const CAPTION_MAX_WORDS = 6;
+/** A gap between two words this long (s) ends a line that has its minimum. */
+export const CAPTION_PAUSE = 0.45;
+/** How long a line stays up after its last word (s), never past the next line. */
+export const CAPTION_HOLD = 0.3;
+
+export const LOUDNESS_MIN = -30;
+export const LOUDNESS_MAX = -8;
+/** A short's target when the cut sets none. */
+export const SHORT_LOUDNESS = -16;
+
+export const SHORT_WIDTH = 1080;
+export const SHORT_HEIGHT = 1920;
+export const VERTICAL_RATIO = 9 / 16;
+/** How far a crop's shape may be from 9:16 (relative): the build fits it exactly. */
+export const VERTICAL_TOLERANCE = 0.03;
+export const DEFAULT_SOURCE_ASPECT = 16 / 9;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const q = (v) => JSON.stringify(v);
+
+export const captionsOn = (render) => isObj(render?.captions);
+export const loudnessOn = (render) => isObj(render?.loudness) && num(render.loudness.target);
+/** The target in LUFS, or null when the cut sets none. */
+export const loudnessTargetOf = (render) => (loudnessOn(render) ? render.loudness.target : null);
+
+/** `render.captions`: its keys and values, and what it does not combine with. */
+export function validateCaptions(manifest) {
+ const render = manifest?.render ?? {};
+ const c = render.captions;
+ if (c === undefined || c === null) return [];
+ if (!isObj(c)) return [`render.captions must be an object ({style: "speakers"}) or absent, not ${q(c)}`];
+ const errors = [];
+ for (const k of Object.keys(c)) {
+ if (!["style", "labels", "size"].includes(k)) errors.push(`render.captions.${k} is not a setting here (the settings are style, labels, size)`);
+ }
+ if (!CAPTION_STYLES.includes(c.style)) errors.push(`render.captions.style must be "speakers", not ${q(c.style)}`);
+ if (c.size !== undefined && !CAPTION_SIZES.includes(c.size)) errors.push(`render.captions.size must be "m" or "l", not ${q(c.size)}`);
+ if (c.labels !== undefined && c.labels !== null) {
+ if (!isObj(c.labels)) errors.push(`render.captions.labels must be an object ({host, subject}), not ${q(c.labels)}`);
+ else {
+ for (const [k, v] of Object.entries(c.labels)) {
+ if (k !== "host" && k !== "subject") errors.push(`render.captions.labels.${k} is not a role here (host, subject)`);
+ else if (v !== null && (typeof v !== "string" || v.length > CAPTION_LABEL_MAX)) {
+ errors.push(`render.captions.labels.${k} must be a short text (up to ${CAPTION_LABEL_MAX} characters), or null`);
+ }
+ }
+ }
+ }
+ if (isObj(render.chrome)) errors.push("render.captions does not combine with render.chrome (the deck draws its own words: render.chrome.fx.kineticQuote)");
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.captions does not combine with render.montage (a montage re-times its clips)");
+ return errors;
+}
+
+/** `render.loudness`: `{target}` in LUFS. */
+export function validateLoudness(manifest) {
+ const render = manifest?.render ?? {};
+ const l = render.loudness;
+ if (l === undefined || l === null) return [];
+ if (!isObj(l)) return [`render.loudness must be an object ({target: -16}) or absent, not ${q(l)}`];
+ const errors = [];
+ for (const k of Object.keys(l)) if (k !== "target") errors.push(`render.loudness.${k} is not a setting here (the setting is target)`);
+ if (!num(l.target) || l.target < LOUDNESS_MIN || l.target > LOUDNESS_MAX) {
+ errors.push(`render.loudness.target must be a number from ${LOUDNESS_MIN} to ${LOUDNESS_MAX} LUFS, not ${q(l.target)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.loudness does not combine with render.montage (a montage levels with render.montage.loudness)");
+ return errors;
+}
+
+/** One clip's `vertical` (null when it has none): its errors, prefixed by `who`. */
+export function verticalErrors(v, who = "vertical") {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect") errors.push(`${who}.${k} is not a setting here (crop, aspect)`);
+ if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) {
+ errors.push(`${who}.aspect must be the source's width / height (a number from 0.2 to 5), not ${q(v.aspect)}`);
+ }
+ const c = v.crop;
+ if (!Array.isArray(c) || c.length !== 4 || !c.every(num)) {
+ errors.push(`${who}.crop must be [x, y, w, h], four fractions of the source picture`);
+ return errors;
+ }
+ const [x, y, w, h] = c;
+ const E = 1e-3;
+ if (w <= 0 || h <= 0) errors.push(`${who}.crop's width and height must be above 0`);
+ if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${who}.crop must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`);
+ if (w > 0 && h > 0) {
+ const aspect = num(v.aspect) ? v.aspect : DEFAULT_SOURCE_ASPECT;
+ const shape = (w * aspect) / h;
+ if (Math.abs(shape / VERTICAL_RATIO - 1) > VERTICAL_TOLERANCE) {
+ errors.push(`${who}.crop must be 9:16 on the source (w Γ aspect / h β 0.5625; this one is ${shape.toFixed(4)})`);
+ }
+ }
+ return errors;
+}
+
+/** Every clip's `vertical`. */
+export function validateVertical(manifest) {
+ const errors = [];
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.vertical === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).vertical`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has a vertical crop`);
+ else errors.push(...verticalErrors(e.vertical, who));
+ });
+ return errors;
+}
+
+/** All of the look's keys: the build's validators and the lint call this. */
+export function validateLook(manifest) {
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest)];
+}
+
+// ---------------------------------------------------------------------------
+// The vertical crop.
+// ---------------------------------------------------------------------------
+
+/** The centred, full-height 9:16 box on a source of `aspect` (w/h), as fractions. */
+export function defaultCrop(aspect = DEFAULT_SOURCE_ASPECT) {
+ const a = num(aspect) && aspect > 0 ? aspect : DEFAULT_SOURCE_ASPECT;
+ let w = VERTICAL_RATIO / a;
+ let h = 1;
+ if (w > 1) {
+ h = a / VERTICAL_RATIO;
+ w = 1;
+ }
+ const r = (n) => Number(n.toFixed(4));
+ return [r((1 - w) / 2), r((1 - h) / 2), r(w), r(h)];
+}
+
+const even = (n) => Math.max(2, 2 * Math.round(n / 2));
+
+/**
+ * A crop (fractions) as pixels of a `srcW`Γ`srcH` picture, exactly 9:16 and
+ * even: the box's height kept (its width made 9/16 of it, about its centre),
+ * clamped inside the picture. `{x, y, w, h}`.
+ */
+export function cropPixels(crop, srcW, srcH) {
+ const [fx, fy, fw, fh] = Array.isArray(crop) && crop.length === 4 ? crop : defaultCrop(srcW / srcH);
+ let h = Math.min(srcH, Math.max(2, fh * srcH));
+ let w = (h * 9) / 16;
+ if (w > srcW) {
+ w = srcW;
+ h = (w * 16) / 9;
+ }
+ w = Math.min(even(w), srcW - (srcW % 2));
+ h = Math.min(even(h), srcH - (srcH % 2));
+ const cx = (fx + fw / 2) * srcW;
+ const cy = (fy + fh / 2) * srcH;
+ const x = Math.round(Math.max(0, Math.min(srcW - w, cx - w / 2)));
+ const y = Math.round(Math.max(0, Math.min(srcH - h, cy - h / 2)));
+ return { x, y, w, h };
+}
+
+/** The ffmpeg chain that cuts a short's picture: the crop, scaled to fill 1080x1920. */
+export function verticalFilters(crop, srcW, srcH, { width = SHORT_WIDTH, height = SHORT_HEIGHT, fps } = {}) {
+ const b = cropPixels(crop, srcW, srcH);
+ return [`crop=${b.w}:${b.h}:${b.x}:${b.y}`, `scale=${width}:${height}:flags=lanczos`, "setsar=1", ...(fps ? [`fps=${fps}`] : [])];
+}
+
+/**
+ * The render a short is made with: 1080x1920, no header, footer, QR, rail or
+ * deck; speaker captions at size "l" (the cut's labels kept); the cut's
+ * loudness target, else SHORT_LOUDNESS.
+ */
+export function shortRender(render = {}) {
+ const { chrome: _c, rail: _r, chromeEngine: _e, brand: _b, montage: _m, ...rest } = render;
+ const labels = isObj(render.captions?.labels) ? { labels: render.captions.labels } : {};
+ return {
+ ...rest,
+ width: SHORT_WIDTH,
+ height: SHORT_HEIGHT,
+ headerHeight: 0,
+ footerHeight: 0,
+ qr: false,
+ captions: { style: "speakers", ...labels, size: "l" },
+ loudness: { target: loudnessTargetOf(render) ?? SHORT_LOUDNESS },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The captions: words and turns to lines, lines to an ASS document.
+// ---------------------------------------------------------------------------
+
+/** The label reactions.json gives a speaker it was never told about (common/lib/clips/reactions.mjs labelOf). */
+export const defaultSpeakerLabel = (role, index) => (role === "host" ? "Host" : role === "subject" ? "Subject" : `Speaker ${Number(index) + 1}`);
+
+/**
+ * What a speaker's lines are headed with, or null: the cut's
+ * `render.captions.labels[role]` when set, else the speaker's own label when
+ * a person gave it one (anything but the default) -- voices are told apart by
+ * colour and side, and named only when somebody names them.
+ */
+export function speakerCaptionLabel(speaker, captions) {
+ const role = CAPTION_ROLES.includes(speaker?.role) ? speaker.role : "other";
+ const set = captions?.labels?.[role];
+ if (typeof set === "string" && set.trim()) return set.trim();
+ const own = typeof speaker?.label === "string" ? speaker.label.trim() : "";
+ if (own && own !== defaultSpeakerLabel(speaker?.role, speaker?.index)) return own;
+ return null;
+}
+
+/**
+ * Which speaker says a word: the turn its middle is in; else the turn whose
+ * edge is nearest, within `reach` seconds; else null.
+ */
+export function speakerAt(turns, start, end, reach = 0.6) {
+ const mid = (start + end) / 2;
+ let best = null;
+ let gap = Infinity;
+ for (const t of turns ?? []) {
+ if (mid >= t.start && mid <= t.end) return t.speaker;
+ const d = mid < t.start ? t.start - mid : mid - t.end;
+ if (d < gap) {
+ gap = d;
+ best = t.speaker;
+ }
+ }
+ return gap <= reach ? best : null;
+}
+
+/** A word as a caption shows it: no ASS override braces or backslashes, trimmed. */
+export const captionText = (w) => String(w ?? "").replace(/[{}\\]/g, "").replace(/\s+/g, " ").trim();
+
+/**
+ * The caption lines of one segment.
+ *
+ * @param {{ words: Array<{text: string, start: number, end: number}>, turns?: Array<{start: number, end: number, speaker: number}>,
+ * speakers?: Array<{index: number, role?: string, label?: string}>, captions?: object, seconds?: number,
+ * maxChars?: number }} o every time in the segment's seconds
+ * @returns {Array<{start: number, end: number, text: string, role: string, speaker: number|null, label: string|null}>}
+ */
+export function captionLines({ words, turns = [], speakers = [], captions = {}, seconds = Infinity, maxChars = 40 }) {
+ const roleOf = (sp) => {
+ const s = speakers.find((x) => x?.index === sp);
+ return CAPTION_ROLES.includes(s?.role) ? s.role : "other";
+ };
+ const used = (words ?? [])
+ .map((w) => ({ text: captionText(w.text), start: Number(w.start), end: Number(w.end) }))
+ .filter((w) => w.text && Number.isFinite(w.start) && Number.isFinite(w.end) && w.end > 0 && w.start < seconds)
+ .map((w) => ({ ...w, start: Math.max(0, w.start), end: Math.min(seconds, Math.max(w.start, w.end)) }))
+ .sort((a, b) => a.start - b.start);
+ const groups = [];
+ let cur = null;
+ for (const w of used) {
+ const speaker = speakerAt(turns, w.start, w.end);
+ const prev = cur?.words[cur.words.length - 1];
+ const chars = cur ? cur.words.reduce((n, x) => n + x.text.length + 1, 0) + w.text.length : 0;
+ const split =
+ !cur ||
+ speaker !== cur.speaker ||
+ cur.words.length >= CAPTION_MAX_WORDS ||
+ (cur.words.length >= CAPTION_MIN_WORDS && (w.start - prev.end >= CAPTION_PAUSE || chars > maxChars));
+ if (split) {
+ cur = { speaker, words: [w] };
+ groups.push(cur);
+ } else cur.words.push(w);
+ }
+ const lines = groups.map((g, i) => {
+ const sp = speakers.find((x) => x?.index === g.speaker) ?? (g.speaker == null ? null : { index: g.speaker });
+ const role = g.speaker == null ? "other" : roleOf(g.speaker);
+ // A label heads the first line of each turn (the first, or a change of voice).
+ const first = i === 0 || groups[i - 1].speaker !== g.speaker;
+ return {
+ start: g.words[0].start,
+ end: g.words[g.words.length - 1].end,
+ text: g.words.map((x) => x.text).join(" "),
+ role,
+ speaker: g.speaker ?? null,
+ label: first && sp ? speakerCaptionLabel({ ...sp, role }, captions) : null,
+ };
+ });
+ for (let i = 0; i < lines.length; i += 1) {
+ const next = lines[i + 1];
+ lines[i].end = Math.min(seconds, next ? Math.max(lines[i].end, Math.min(next.start, lines[i].end + CAPTION_HOLD)) : lines[i].end + CAPTION_HOLD);
+ if (lines[i].end - lines[i].start < 0.2) lines[i].end = Math.min(seconds, lines[i].start + 0.2);
+ }
+ return lines;
+}
+
+/** Seconds as an ASS time, h:mm:ss.cc (centiseconds, rounded). */
+export function assTime(t) {
+ const cs = Math.max(0, Math.round(t * 100));
+ const h = Math.floor(cs / 360000);
+ const m = Math.floor((cs % 360000) / 6000);
+ const s = Math.floor((cs % 6000) / 100);
+ const c = cs % 100;
+ return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(c).padStart(2, "0")}`;
+}
+
+/** `#RRGGBB` as an ASS colour, `&HAABBGGRR`. */
+export function assColour(hex, alpha = 0) {
+ const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex));
+ if (!m) throw new Error(`not a #rrggbb colour: ${hex}`);
+ const a = Math.max(0, Math.min(255, Math.round(alpha))).toString(16).padStart(2, "0");
+ return `&H${a}${m[3]}${m[2]}${m[1]}`.toUpperCase();
+}
+
+/** The caption geometry for a frame: font size, outline, margins (px). */
+export function captionGeometry({ width, height, size = "m", bottom = 0 }) {
+ const vertical = height > width;
+ const base = Math.min(width, height);
+ const fontSize = Math.round(base * (size === "l" ? 0.075 : 0.052));
+ return {
+ fontSize,
+ outline: Math.max(1, Math.round(fontSize * 0.055)),
+ shadow: Math.max(0, Math.round(fontSize * 0.03)),
+ marginH: Math.round(width * (vertical ? 0.06 : 0.05)),
+ // A short's captions sit above the bottom fifth (a phone app's own controls).
+ marginV: Math.round(bottom + height * (vertical ? 0.2 : 0.07)),
+ // Characters a line, so a line never wraps at this size (about 55 % of the width).
+ maxChars: Math.max(12, Math.floor((width * (vertical ? 0.88 : 0.55)) / (fontSize * 0.52))),
+ };
+}
+
+/**
+ * The ASS document for a segment's lines. One style per role (its colour and
+ * side); a label is the line's head, smaller. No wrapping: the lines are
+ * already short.
+ */
+export function assDocument(lines, { width, height, size = "m", bottom = 0, font = CAPTION_FONT } = {}) {
+ const g = captionGeometry({ width, height, size, bottom });
+ const style = (role) =>
+ `Style: ${role},` +
+ [
+ font, g.fontSize, assColour(CAPTION_COLOURS[role]), "&H000000FF", assColour("#000000"), assColour("#000000", 0x80),
+ -1, 0, 0, 0, 100, 100, 0, 0, 1, g.outline, g.shadow, CAPTION_ALIGN[role], g.marginH, g.marginH, g.marginV, 1,
+ ].join(",");
+ const labelSize = Math.round(g.fontSize * 0.62);
+ const events = lines.map((l) => {
+ const head = l.label ? `{\\fs${labelSize}}${captionText(l.label)}{\\fs${g.fontSize}} ` : "";
+ return `Dialogue: 0,${assTime(l.start)},${assTime(l.end)},${l.role},,0,0,0,,${head}${captionText(l.text)}`;
+ });
+ return [
+ "[Script Info]",
+ "ScriptType: v4.00+",
+ `PlayResX: ${width}`,
+ `PlayResY: ${height}`,
+ "WrapStyle: 2",
+ "ScaledBorderAndShadow: yes",
+ "YCbCr Matrix: None",
+ "",
+ "[V4+ Styles]",
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
+ ...CAPTION_ROLES.map(style),
+ "",
+ "[Events]",
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
+ ...events,
+ "",
+ ].join("\n");
+}
+
+/**
+ * A path as a filter option value, single-quoted (as the header's `fontfile`
+ * is). A path with a quote or a colon in it cannot be said this way: refused.
+ */
+export function filterPath(p) {
+ const s = String(p);
+ if (/[':\\]/.test(s)) throw new Error(`captions: ${s} has a quote, a colon or a backslash in it, which a filter option cannot carry`);
+ return `'${s}'`;
+}
+
+/** The `ass=` filter that burns a document in, its fonts from `fontsDir`. */
+export const assFilter = (file, fontsDir) => `ass=filename=${filterPath(file)}${fontsDir ? `:fontsdir=${filterPath(fontsDir)}` : ""}`;
diff --git a/umtool/report-to-video/look.test.mjs b/umtool/report-to-video/look.test.mjs
@@ -0,0 +1,391 @@
+// The look of a highlights cut (look.mjs, release 36 lane C): the validators,
+// the caption lines and their ASS document, the vertical crop -- and real
+// renders: a cut without the new keys is byte for byte what it was; loudness
+// lands within Β±0.5 LU of its target; a caption appears on its frame, in its
+// speaker's colour and side; a short is 1080x1920 and shows the crop.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+// The corpus the build reads metadata and cues from: set before build-video
+// (cues.mjs) is loaded, so it is this file's own.
+const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-look-corpus-"));
+process.env.CHANNELS_DIR = CORPUS;
+
+const {
+ CAPTION_COLOURS, SHORT_HEIGHT, SHORT_WIDTH, assColour, assDocument, assTime, captionLines, cropPixels, defaultCrop,
+ loudnessTargetOf, shortRender, speakerAt, speakerCaptionLabel, validateLook, verticalErrors, verticalFilters,
+} = await import("./look.mjs");
+const { buildVideo, measureLoudness, setProgressMode, takesHeavySlot } = await import("./build-video.mjs");
+const { lintManifest } = await import("./lint.mjs");
+const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs");
+
+test.after(() => rm(CORPUS, { recursive: true, force: true }));
+
+// ---- the validators -------------------------------------------------------------
+
+const m = (render = {}, timeline = []) => ({ render, timeline });
+
+test("validateLook: absent or null says nothing; the seed's default look validates", () => {
+ assert.deepEqual(validateLook(m()), []);
+ assert.deepEqual(validateLook(m({ captions: null, loudness: null })), []);
+ // Lane B's seed for a site-less, one-video cut.
+ assert.deepEqual(validateLook(m({ headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack", loudness: { target: -16 } })), []);
+ assert.deepEqual(validateLook(m({ captions: { style: "speakers" } })), []);
+ assert.deepEqual(validateLook(m({ captions: { style: "speakers", size: "l", labels: { host: "Nik", subject: null } } })), []);
+});
+
+test("validateLook: captions -- each problem in a sentence naming the key", () => {
+ const e = (c, extra = {}) => validateLook(m({ captions: c, ...extra }));
+ assert.match(e("on")[0], /render\.captions must be an object/);
+ assert.match(e({ style: "karaoke" })[0], /render\.captions\.style must be "speakers", not "karaoke"/);
+ assert.match(e({ style: "speakers", size: "xl" })[0], /render\.captions\.size must be "m" or "l"/);
+ assert.match(e({ style: "speakers", colour: "red" })[0], /render\.captions\.colour is not a setting here/);
+ assert.match(e({ style: "speakers", labels: { guest: "x" } })[0], /labels\.guest is not a role here/);
+ assert.match(e({ style: "speakers", labels: { host: "x".repeat(41) } })[0], /labels\.host must be a short text/);
+ assert.match(e({ style: "speakers" }, { chrome: { engine: "hyperframes" } })[0], /does not combine with render\.chrome/);
+ assert.match(e({ style: "speakers" }, { montage: {} })[0], /does not combine with render\.montage/);
+});
+
+test("validateLook: loudness is a target from -30 to -8 LUFS", () => {
+ const e = (l, extra = {}) => validateLook(m({ loudness: l, ...extra }));
+ assert.deepEqual(e({ target: -30 }), []);
+ assert.deepEqual(e({ target: -8 }), []);
+ assert.match(e({ target: -7 })[0], /render\.loudness\.target must be a number from -30 to -8 LUFS, not -7/);
+ assert.match(e({ target: "-16" })[0], /not "-16"/);
+ assert.match(e({ target: -16, lra: 7 })[0], /render\.loudness\.lra is not a setting here/);
+ assert.match(e(-16)[0], /render\.loudness must be an object/);
+ assert.match(e({ target: -16 }, { montage: {} })[0], /render\.montage\.loudness/);
+ assert.equal(loudnessTargetOf({ loudness: { target: -14 } }), -14);
+ assert.equal(loudnessTargetOf({}), null);
+});
+
+test("validateLook: a clip's vertical crop lies inside the picture and is 9:16 on the source", () => {
+ const clip = (vertical) => ({ type: "clip", id: "c1", video: "v", start: 0, end: 5, vertical });
+ const e = (v) => validateLook(m({}, [clip(v)]));
+ assert.deepEqual(e(undefined), []);
+ assert.deepEqual(e({ crop: defaultCrop() }), []);
+ assert.deepEqual(e({ crop: [0, 0, 0.3164, 1] }), []);
+ // A 4:3 source's 9:16 box is wider in fractions.
+ assert.deepEqual(e({ crop: defaultCrop(4 / 3), aspect: 4 / 3 }), []);
+ assert.match(e({ crop: [0, 0, 0.5, 1] })[0], /timeline\[0\] \(c1\)\.vertical\.crop must be 9:16 on the source/);
+ assert.match(e({ crop: [0.8, 0, 0.3164, 1] })[0], /must lie inside the picture/);
+ assert.match(e({ crop: [0, 0, 1] })[0], /must be \[x, y, w, h\]/);
+ assert.match(e({ crop: defaultCrop(), zoom: 2 })[0], /vertical\.zoom is not a setting here/);
+ assert.match(e("centre")[0], /vertical must be an object/);
+ assert.match(validateLook(m({}, [{ type: "card", id: "k", vertical: { crop: defaultCrop() } }]))[0], /only a clip has a vertical crop/);
+ assert.deepEqual(verticalErrors(null), []);
+});
+
+test("the lint says it too", () => {
+ const lint = lintManifest({ slug: "x", title: "X", render: { width: 320, height: 180, fps: 30, captions: { style: "nope" } }, timeline: [] }, { manifestDir: os.tmpdir(), exists: () => true });
+ assert.ok(lint.errors.some((x) => /render\.captions\.style/.test(x)), lint.errors.join("; "));
+});
+
+// ---- the crop -------------------------------------------------------------------
+
+test("defaultCrop / cropPixels: centred, full height, exactly 9:16 and even", () => {
+ assert.deepEqual(defaultCrop(16 / 9), [0.3418, 0, 0.3164, 1]);
+ assert.deepEqual(cropPixels(defaultCrop(16 / 9), 1920, 1080), { x: 656, y: 0, w: 608, h: 1080 });
+ assert.deepEqual(cropPixels(null, 1920, 1080), { x: 656, y: 0, w: 608, h: 1080 });
+ // Off to the right, clamped inside.
+ assert.deepEqual(cropPixels([0.7, 0, 0.3164, 1], 1920, 1080), { x: 1312, y: 0, w: 608, h: 1080 });
+ // A smaller box: its height kept, its centre kept.
+ const b = cropPixels([0.25, 0.25, 0.1582, 0.5], 1920, 1080);
+ assert.deepEqual(b, { x: 480, y: 270, w: 304, h: 540 });
+ assert.equal(b.w / b.h, 9 / 16 + (304 / 540 - 9 / 16));
+ assert.deepEqual(verticalFilters(null, 1920, 1080, { fps: 30 }), ["crop=608:1080:656:0", "scale=1080:1920:flags=lanczos", "setsar=1", "fps=30"]);
+});
+
+test("shortRender: 1080x1920, no header, footer, QR, rail or deck; large captions; the cut's loudness, else -16", () => {
+ const r = shortRender({ width: 1920, height: 1080, fps: 30, headerHeight: 56, qr: { margin: 20 }, chrome: { engine: "hyperframes" }, rail: { width: 300 }, captions: { style: "speakers", labels: { host: "Nik" } } });
+ assert.equal(r.width, SHORT_WIDTH);
+ assert.equal(r.height, SHORT_HEIGHT);
+ assert.equal(r.headerHeight, 0);
+ assert.equal(r.footerHeight, 0);
+ assert.equal(r.qr, false);
+ assert.equal(r.chrome, undefined);
+ assert.equal(r.rail, undefined);
+ assert.deepEqual(r.captions, { style: "speakers", labels: { host: "Nik" }, size: "l" });
+ assert.deepEqual(r.loudness, { target: -16 });
+ assert.deepEqual(shortRender({ loudness: { target: -14 } }).loudness, { target: -14 });
+ assert.equal(takesHeavySlot({ opts: { short: "c1" }, only: "c1" }), true);
+ assert.equal(takesHeavySlot({ only: "c1" }), false);
+});
+
+// ---- the caption lines ----------------------------------------------------------
+
+const SPEAKERS = [
+ { index: 0, role: "host", label: "Host" },
+ { index: 1, role: "subject", label: "Subject" },
+ { index: 2, role: "other", label: "Speaker 3" },
+];
+const word = (text, start, end = start + 0.3) => ({ text, start, end });
+
+test("captionLines: 2-6 words a line, broken on pauses, never across a change of speaker", () => {
+ const words = [
+ // subject, 0-4: eight words in a run, then a pause, then two
+ ...["a", "b", "c", "d", "e", "f", "g", "h"].map((w, i) => word(w, 0.1 + i * 0.35)),
+ word("i", 3.4), word("j", 3.75),
+ // host, 4-6: one word, then the subject again
+ word("wow", 4.2),
+ word("k", 6.1), word("l", 6.45),
+ ];
+ const turns = [{ start: 0, end: 4, speaker: 1 }, { start: 4, end: 6, speaker: 0 }, { start: 6, end: 8, speaker: 1 }];
+ const lines = captionLines({ words, turns, speakers: SPEAKERS, seconds: 8 });
+ assert.deepEqual(lines.map((l) => [l.text, l.role]), [
+ ["a b c d e f", "subject"],
+ ["g h", "subject"],
+ ["i j", "subject"],
+ ["wow", "host"],
+ ["k l", "subject"],
+ ]);
+ // A line starts on its first word; it holds 0.3 s, never past the next.
+ assert.equal(lines[0].start, 0.1);
+ assert.equal(lines[1].end, Math.min(lines[2].start, 0.1 + 7 * 0.35 + 0.3 + 0.3));
+ assert.equal(lines.at(-1).end, 6.45 + 0.3 + 0.3);
+ // No labels unless somebody gave one.
+ assert.ok(lines.every((l) => l.label === null));
+});
+
+test("captionLines: a label heads each turn's first line -- the cut's, else a person's", () => {
+ const words = [word("one", 0.1), word("two", 0.5), word("three", 0.9), word("four", 2.1), word("five", 2.5)];
+ const turns = [{ start: 0, end: 1.5, speaker: 0 }, { start: 2, end: 3, speaker: 1 }];
+ const set = captionLines({ words, turns, speakers: SPEAKERS, captions: { style: "speakers", labels: { host: "Nik" } }, seconds: 4 });
+ assert.deepEqual(set.map((l) => l.label), ["Nik", null]);
+ const named = captionLines({ words, turns, speakers: [{ index: 0, role: "host", label: "Host" }, { index: 1, role: "subject", label: "The narrator" }], seconds: 4 });
+ assert.deepEqual(named.map((l) => l.label), [null, "The narrator"]);
+ assert.equal(speakerCaptionLabel({ index: 2, role: "other", label: "Speaker 3" }, {}), null);
+ assert.equal(speakerCaptionLabel({ index: 2, role: "other", label: "Chat" }, {}), "Chat");
+});
+
+test("speakerAt: the turn a word's middle is in, else the nearest within 0.6 s, else none", () => {
+ const turns = [{ start: 0, end: 1, speaker: 0 }, { start: 3, end: 4, speaker: 1 }];
+ assert.equal(speakerAt(turns, 0.2, 0.5), 0);
+ assert.equal(speakerAt(turns, 1.2, 1.4), 0);
+ assert.equal(speakerAt(turns, 2.6, 2.7), 1);
+ assert.equal(speakerAt(turns, 1.8, 2.0), null);
+ assert.equal(speakerAt([], 0, 1), null);
+});
+
+test("assDocument: a style per role in its colour and side; times in centiseconds; a label smaller", () => {
+ assert.equal(assTime(0), "0:00:00.00");
+ assert.equal(assTime(61.234), "0:01:01.23");
+ assert.equal(assTime(3725.996), "1:02:06.00");
+ assert.equal(assColour("#FFC840"), "&H0040C8FF");
+ assert.equal(assColour("#000000", 0x80), "&H80000000");
+ const doc = assDocument(
+ [{ start: 1.5, end: 2.25, text: "hello {there}", role: "host", label: "Nik" }, { start: 2.5, end: 3, text: "hi", role: "subject", label: null }],
+ { width: 1920, height: 1080, size: "m" },
+ );
+ assert.match(doc, /PlayResX: 1920\nPlayResY: 1080/);
+ assert.match(doc, new RegExp(`Style: host,IBM Plex Sans,56,${assColour(CAPTION_COLOURS.host).replace("&", "&")},.*,1,\\d+,\\d+,1,96,96,76,1`));
+ assert.match(doc, /Style: subject,IBM Plex Sans,56,&H00FFD36F,.*,3,96,96,76,1/);
+ assert.match(doc, /Style: other,IBM Plex Sans,56,&H00E6F1F6,.*,2,96,96,76,1/);
+ assert.match(doc, /Dialogue: 0,0:00:01\.50,0:00:02\.25,host,,0,0,0,,\{\\fs35\}Nik\{\\fs56\} {2}hello there/);
+ assert.match(doc, /Dialogue: 0,0:00:02\.50,0:00:03\.00,subject,,0,0,0,,hi\n/);
+ const big = assDocument([], { width: 1080, height: 1920, size: "l" });
+ assert.match(big, /Style: host,IBM Plex Sans,81,/);
+});
+
+// ---- real renders ---------------------------------------------------------------
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0)
+ && /\bass\b/.test(String(spawnSync("ffmpeg", ["-hide_banner", "-filters"]).stdout));
+const FPS = 30;
+const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" };
+const RENDER = {
+ width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0,
+ headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ fetchPad: 0, snapWindow: 0.05, silenceMinDur: 0.1,
+};
+const CHANNEL = "synth";
+const VIDEO = "vid1";
+
+// The corpus record the build reads the clip's metadata from.
+{
+ const dir = path.join(CORPUS, CHANNEL, "data", VIDEO);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" }));
+ writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 12, uploadDate: "20240102", cues: [{ start: 0.2, end: 11.8, text: "filler words only" }] }));
+ writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: VIDEO, title: "Synthetic", duration: 12 }));
+}
+
+/**
+ * A project: one clip of vid1 (1-7 s), its window in out/clips-raw (12 s of a
+ * 640x360 black picture with a white bar at x 400-440, and a 440 Hz tone,
+ * lavfi sine's 1/8 times `amp`), reactions.json (the subject 0-4 s and 8-12 s, the host 4-8 s) and
+ * words.json (a word every half second).
+ */
+async function project(render = {}, { clip = {}, amp = 0.5, rx = true } = {}) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-look-"));
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", `${VIDEO}_0.00-12.00.mp4`);
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=black:s=640x360:r=${FPS}:d=12`,
+ "-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:duration=12`,
+ "-filter_complex", `[0:v]drawbox=x=400:y=0:w=40:h=360:color=white:t=fill[v];[1:a]volume=${amp}[a]`,
+ "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ if (rx) {
+ await writeFile(path.join(root, "reactions.json"), JSON.stringify({
+ version: 1,
+ source: { channel: CHANNEL, video: VIDEO, duration: 12, words: "words.json" },
+ speakers: [{ index: 0, role: "host", label: "Host", how: "auto" }, { index: 1, role: "subject", label: "Subject", how: "auto" }],
+ turns: [{ start: 0, end: 4, speaker: 1 }, { start: 4, end: 8, speaker: 0 }, { start: 8, end: 12, speaker: 1 }],
+ laughs: [], moments: [], proposals: [],
+ }));
+ const words = [];
+ for (let t = 0.25; t < 11.5; t += 0.5) words.push({ w: `w${Math.round(t * 2)}`, start: t, end: t + 0.3 });
+ await writeFile(path.join(root, "words.json"), JSON.stringify({ words }));
+ }
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "look", title: "Look",
+ provenance: { channelSlug: CHANNEL, channelsDir: CORPUS },
+ render: { ...RENDER, ...render },
+ timeline: [{ type: "clip", id: "c1", channel: CHANNEL, video: VIDEO, start: 1, end: 7, cite: 1, quote: "q", ...clip }],
+ }));
+ return { root, manifestPath, raw };
+}
+
+const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0];
+const quiet = () => setProgressMode(() => {});
+
+/** One frame of `file` as rgb24: `{ w, h, px(x, y) => [r, g, b] }`. */
+function frame(file, n) {
+ const p = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]);
+ const [w, h] = String(p.stdout).trim().split(",").map(Number);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select='eq(n,${n})'`, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 1 << 26 });
+ assert.equal(r.status, 0, String(r.stderr));
+ const buf = r.stdout;
+ return { w, h, px: (x, y) => { const i = (y * w + x) * 3; return [buf[i], buf[i + 1], buf[i + 2]]; } };
+}
+
+/** The mean colour of the bright pixels (max channel > 140) in a box, and how many. */
+function brightIn(f, x0, y0, x1, y1) {
+ let n = 0;
+ const sum = [0, 0, 0];
+ for (let y = y0; y < y1; y += 1) {
+ for (let x = x0; x < x1; x += 1) {
+ const c = f.px(x, y);
+ if (Math.max(...c) > 140) {
+ n += 1;
+ sum[0] += c[0]; sum[1] += c[1]; sum[2] += c[2];
+ }
+ }
+ }
+ return { n, mean: n ? sum.map((v) => v / n) : null };
+}
+
+test("render: without the new keys (absent or null) the cut is byte for byte the same", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const a = await project({});
+ const b = await project({ captions: null, loudness: null });
+ try {
+ await buildVideo({ manifestPath: a.manifestPath, opts: { noNetwork: true } });
+ await buildVideo({ manifestPath: b.manifestPath, opts: { noNetwork: true } });
+ for (const f of ["look.mp4", "sourced/segments/c1.mp4", "sourced/segments/c1.cut.json"]) {
+ assert.equal(md5(path.join(a.root, "out", f)), md5(path.join(b.root, "out", f)), f);
+ }
+ const rec = JSON.parse(await readFile(path.join(a.root, "out", "sourced", "segments", "c1.cut.json"), "utf8"));
+ assert.equal(rec.loudness, undefined);
+ assert.equal(rec.captions, undefined);
+ } finally {
+ await rm(a.root, { recursive: true, force: true });
+ await rm(b.root, { recursive: true, force: true });
+ }
+});
+
+test("render: render.loudness brings a quiet clip to its target within Β±0.5 LU", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const p = await project({ loudness: { target: -16 } }, { amp: 0.5 });
+ try {
+ const before = await measureLoudness(p.raw, 1, 7);
+ assert.ok(before < -24 && before > -40, `the source is quiet, not silent: ${before}`);
+ const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const seg = path.join(p.root, "out", "sourced", "segments", "c1.mp4");
+ const after = await measureLoudness(seg, 0, 6);
+ assert.ok(Math.abs(after - -16) <= 0.5, `segment ${after} LUFS`);
+ assert.ok(Math.abs((await measureLoudness(r.out, 0, 6)) - -16) <= 0.5, "the cut");
+ const rec = JSON.parse(await readFile(seg.replace(/\.mp4$/, ".cut.json"), "utf8"));
+ assert.equal(rec.loudness.target, -16);
+ assert.ok(Math.abs(rec.loudness.gain - (-16 - before)) < 0.6, JSON.stringify(rec.loudness));
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("render: speaker captions -- on their frame, the subject sky on the right, the host amber on the left", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ const p = await project({ width: 640, height: 360, captions: { style: "speakers" } });
+ try {
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } });
+ const segDir = path.join(p.root, "out", "sourced", "segments");
+ const rec = JSON.parse(await readFile(path.join(segDir, "c1.cut.json"), "utf8"));
+ assert.deepEqual([rec.start, rec.end], [1, 7]);
+ assert.equal(rec.captions.words, "words.json");
+ const ass = await readFile(path.join(segDir, "c1.captions.ass"), "utf8");
+ const events = ass.split("\n").filter((l) => l.startsWith("Dialogue:"));
+ // Source 1.25 is the first word: 0.25 s into the segment; the host's first (4.25) at 3.25.
+ assert.match(events[0], /^Dialogue: 0,0:00:00\.25,[^,]+,subject,/);
+ const host = events.find((l) => /,host,/.test(l));
+ assert.match(host, /^Dialogue: 0,0:00:03\.25,/);
+ const seg = path.join(segDir, "c1.mp4");
+ // The bar (x 400-440 of 640) is white in every frame; the captions are under y 260.
+ const box = (f, side) => (side === "left" ? brightIn(f, 0, 260, 300, 345) : brightIn(f, 445, 260, 640, 345));
+ // To the frame: nothing on frame 6 (0.2 s), the subject's line on frame 8 (0.267 s).
+ assert.equal(box(frame(seg, 6), "right").n, 0, "no caption before its first word");
+ const sub = box(frame(seg, 8), "right");
+ assert.ok(sub.n > 30, `the subject's line is up: ${sub.n} px`);
+ assert.ok(sub.mean[2] > sub.mean[0] + 60, `sky: ${sub.mean.map(Math.round)}`);
+ assert.equal(box(frame(seg, 8), "left").n, 0, "the subject is on the right only");
+ // The host from 3.25 s: frame 99 (3.3 s) amber on the left.
+ const h = box(frame(seg, 99), "left");
+ assert.ok(h.n > 30, `the host's line is up: ${h.n} px`);
+ assert.ok(h.mean[0] > h.mean[2] + 80, `amber: ${h.mean.map(Math.round)}`);
+ assert.equal(box(frame(seg, 99), "right").n, 0, "the host is on the left only");
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("render: a short -- 1080x1920, its crop, large captions, loudness, in <project>/shorts/", { skip: !have && "needs ffmpeg with libass" }, async () => {
+ quiet();
+ // The crop's centre on the bar (x 400-440 of 640): [0.5, 0, 0.3164, 1] centres at x 421.
+ const p = await project({ headerHeight: 56, qr: { margin: 10 } }, { clip: { vertical: { crop: [0.5, 0, 0.3164, 1] } } });
+ try {
+ const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, short: "c1" } });
+ const out = path.join(p.root, "shorts", "c1.mp4");
+ assert.equal(r.out, out);
+ const probe = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", out]);
+ assert.equal(String(probe.stdout).trim(), "1080,1920");
+ // The crop: 202x360 at x 320, so the bar is at 80-120 of 202 -> 428-642 of 1080.
+ const f = frame(out, 15);
+ assert.ok(Math.min(...f.px(535, 400)) > 200, `the bar in the middle: ${f.px(535, 400)}`);
+ assert.ok(Math.max(...f.px(200, 400)) < 40, "black left of it");
+ assert.ok(Math.max(...f.px(900, 400)) < 40, "black right of it");
+ // No header: the top rows are the picture (black beside the bar).
+ assert.ok(Math.max(...f.px(100, 10)) < 40, "no header");
+ const rec = JSON.parse(await readFile(path.join(p.root, "shorts", "c1.json"), "utf8"));
+ assert.deepEqual(rec.crop, [0.5, 0, 0.3164, 1]);
+ assert.equal(rec.width, 1080);
+ assert.equal(rec.loudness.target, -16);
+ assert.ok(rec.captions.lines > 0);
+ // Large captions on the subject's side.
+ const ass = await readFile(path.join(p.root, "out", "shorts-work", "segments", "c1.captions.ass"), "utf8");
+ assert.match(ass, /Style: subject,IBM Plex Sans,81,/);
+ assert.ok(Math.abs((await measureLoudness(out, 0, 6)) - -16) <= 0.5, "loudness");
+ // The cut's own segments are untouched.
+ assert.equal(spawnSync("test", ["-e", path.join(p.root, "out", "sourced", "segments", "c1.mp4")]).status, 1);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -34,6 +34,7 @@
"./montage-rulings": "./montage-rulings.mjs",
"./lint": "./lint.mjs",
"./local-media": "./local-media.mjs",
+ "./look": "./look.mjs",
"./mute": "./mute.mjs",
"./narration": "./narration.mjs",
"./narration-review": "./narration-review.mjs",
@@ -46,6 +47,7 @@
"./shoot-page": "./shoot-page.mjs",
"./social": "./social.mjs",
"./sources": "./sources.mjs",
+ "./transition": "./transition.mjs",
"./verify-build": "./verify-build.mjs",
"./youtube": "./youtube.mjs"
}