commit 1df2a71eca6d3d883347c2a61cf158e02de04fcd
parent bc37bc979f0ef52a94a10967925b3e5551631e45
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 01:46:35 -0500
Merge lane/chat-overlay: a live-chat column beside a clip (report-to-video/modules/chat.mjs, chrome-chat.mjs) -- the video's live_chat.cues.json for the clip's source span, gap-aware through gaps.mjs, newest at the foot; per clip `umtool set <clip> chat=on|off`, chat.* look keys; no chat file draws nothing and says so, never failing the build
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
16 files changed, 619 insertions(+), 9 deletions(-)
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -34,6 +34,7 @@ that generates it ([notes.md](notes.md)).
| `blur.strength` — the blur's radius, % of the picture's height as it plays (2–15; default 5) | Blur, **strength** | `blur.strength=8` | same |
| `blur.from`, `blur.to` — source seconds inside the clip's window: blur only that span (either alone runs to the clip's edge; default the whole clip) | Blur, **From playhead** / **To playhead**, **Whole clip** | `blur.from=231.5 blur.to=262` | same |
| `layout` — `finale`: the deck's finale layout for this clip (`render.chrome.deck.finale`); `clip` is the default | — | `umtool set <p> <clip> layout=finale` | — |
+| `chat` — `on`: the clip's live chat (its video's `live_chat.cues.json`, for the clip's source span, timed through its gaps) in a column beside the footage; `off` or `chat=` (the default): none. A video with no chat draws nothing and the build log says so ([Live chat](#live-chat)) | — | `umtool set <p> <clip> chat=on` (`chat=` clears it) | — |
| `fx.zoom` — `{shot, focus, at?, hold?}`: a screenshot (a file in the project; a bare name under its `shots/` is written as `shots/<name>`) that comes up over the footage and pushes in on `focus` (`[left, top, right, bottom]`, fractions of the shot) — drawn once `render.chrome.fx.zoom` is on ([Effects](#effects)). **How long it stays**: up 0.2 s into the clip's clean span (rising in over 0.38 s), its focus box drawn 0.55 s later, the push at `at` (seconds into the clip; default as soon as the box has drawn) over 1 s, then a slow drift on the detail; it leaves with a 0.3 s fade 0.3 s before the clip's clean span ends — or, with `hold` (0.5–10 s), that long after the push lands (never past the clip's own leave) | — | `umtool set <p> <clip> fx.zoom='{"shot":"shots/x.png","focus":[0.1,0.2,0.9,0.4],"at":5.9,"hold":4}'` (`fx.zoom=` clears it) | `PUT /api/report/window {project, clip, "fx.zoom": {…} \| null}` |
| `fx.receipts`, `fx.punch`, `fx.quote`, `fx.punchIn`, `fx.speakers` — the clip's other effect fields (`[{shot, mark?}]` 1–4; the words to punch; `false`: no line; 1–8 source seconds inside the clip; `[{at, who: 0\|1}]`), each inert until its effect is on; `fx` is all of them at once. Checked by the build's own `validateFxEntries` | — | `fx.punch="the words"` `fx.punchIn='[231.4]'` · `fx='{…}'` sets them all, `fx=` clears every one | `PUT /api/report/window {project, clip, fx}` (or one `"fx.<field>"`) |
| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band puts it back (`G`: the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps}` |
@@ -682,6 +683,7 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr
| [Posts feed](#posts-feed) `feed` | The cut's posts in a column beside the footage, each ticking in as its clip starts. (a page over the whole cut) | `render.chrome.deck.posts` |
| [Popup posts](#popup-posts) `popup-posts` | A clip's posts as cards over the footage, each window its own short page at its own second. (pages at their own seconds) | `render.chrome.deck.posts` |
| [Stamps](#stamps) `stamp` | Each counted mark's word, stamped over the footage as it lands. (a page over the whole cut) | `render.chrome.factcheck.stamp` |
+| [Live chat](#live-chat) `chat` | A stream's chat replay scrolled in a column beside the footage, over the clips that ask for it. (a page over the whole cut) | `render.chrome.chat` |
| [Stats](#stats) `stats` | A frame scan's running numbers over the clips that declare them. (a page over the whole cut) | `render.chrome.stats` |
| [Then and now (pair)](#then-and-now-pair) `pair` | Two clips on one subject, each with its date: a then \| now strip (or a then→now card) with the pair's caption. (a page over the whole cut) | `render.chrome.pair` |
| [Status ledger](#status-ledger) `status` | A row per item -- announced, then followed up or not -- filling a column as the cut plays. (a page over the whole cut) | `render.chrome.status` |
@@ -854,6 +856,16 @@ Each counted mark's word stamped over the footage as it lands (`render.chrome.fa
| `factcheck.stamp.position` | `top-left` `top-right` `bottom-left` `bottom-right` `center` · default `top-left` | `umtool look <p> factcheck.stamp.position=center` |
| `factcheck.stamp.scale`, `.motion`, `.opacity` | 0.5–2 · `slam` `pop` `fade` `none` · 0.3–1 · default 1, `slam`, 1 | `umtool look <p> factcheck.stamp.motion=pop` |
+### Live chat
+
+A stream's chat replay (`live_chat.cues.json`, kept beside a live video's transcript) in a column down one side of the footage box, author and text, newest at the bottom, over the clips with `chat: true` (`render.chrome.chat`, chat.mjs). A clip shows the messages of its own SOURCE span, timed to the cut through its gaps (a message said inside a gap is not shown). A busy chat is thinned to one message per `minGap`; a long message is cut at `maxChars` and clamped to four lines. A clip whose video has no chat file draws nothing and the build log says so -- it never fails the build. The column overlays the footage's edge (it does not reflow the footage); it shares the footage box with the stats and the status ledger, so put them in other corners.
+
+| Knob | Range · default | From a terminal |
+|---|---|---|
+| clip `chat` | `on` · `off` · default off (a clip only) | `umtool set <p> <clip> chat=on` (`chat=` clears it) |
+| `chrome.chat.position`, `.width` | `right` `left` · 240–640 px · default `right`, 380 | `umtool look <p> chat.position=left` |
+| `chrome.chat.lines`, `.maxChars`, `.minGap` | 3–16 messages · 20–300 characters · 0–5 s · default 10, 120, 0.6 | `umtool look <p> chat='{"lines":8}'` |
+
### Stats
A frame scan’s running numbers over the clips that declare them, in a panel in the footage (`render.chrome.stats`, stats.mjs).
diff --git a/umtool/e2e/modules.spec.ts b/umtool/e2e/modules.spec.ts
@@ -115,6 +115,23 @@ test("the panel draws every module from its descriptor, and a module is switched
expect(readManifest().render.chrome.layout).toBe("deck");
});
+test("the chat module's settings are saved through the panel and refused with the build's sentence; it has no switch (a clip's chat=on opts in)", async ({ page }) => {
+ const panel = await openPanel(page);
+ await expect(panel.getByTestId("module-chat")).toBeAttached();
+ const card = await openModule(page, "chat");
+ await expect(card.getByTestId("module-toggle-chat")).toHaveCount(0);
+ await card.getByTestId("module-field-chat-position").selectOption("left");
+ await card.getByTestId("module-save-chat").click();
+ await expect(card.getByTestId("module-status-chat")).toHaveText("saved");
+ await expect.poll(() => readManifest().render.chrome.chat.position).toBe("left");
+ // A value the build would refuse is refused with its sentence, the manifest untouched.
+ await card.getByTestId("module-field-chat-lines").fill("99");
+ await card.getByTestId("module-save-chat").click();
+ await expect(card.getByTestId("module-errors-chat")).toContainText("render.chrome.chat.lines");
+ expect(readManifest().render.chrome.chat.position).toBe("left");
+ expect(readManifest().render.chrome.layout).toBe("deck");
+});
+
test("a save the build would refuse is refused with the build's sentence, and the manifest is untouched", async ({ page }) => {
const before = JSON.stringify(readManifest().render.chrome.status);
await openPanel(page);
diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs
@@ -55,7 +55,7 @@ const FX_KEYS = ["fx", ...FX_ENTRY_FIELDS.map((k) => `fx.${k}`)];
const GAP_KEYS = ["gaps", "gap.add", "gap.remove"];
const SET_KEYS = [
...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS,
- ...FX_KEYS, ...GAP_KEYS,
+ ...FX_KEYS, ...GAP_KEYS, "chat",
];
export const SET_USAGE = [
@@ -88,6 +88,9 @@ export const SET_USAGE = [
" detail, absent: to the clip's end); fx.receipts='[{\"shot\":\"shots/a.png\",\"mark\":[0,0.4,1,0.5]}]' (1–4);",
" fx.punch=\"the words\"; fx.quote=false; fx.punchIn='[231.4]' (source seconds);",
" fx.speakers='[{\"at\":231,\"who\":1}]'; fx='{…}' sets them all, `fx=` clears every one, `fx.<field>=` that one.",
+ " chat=on shows the clip's live chat (its video's live_chat.cues.json, for the clip's source span) in a column",
+ " beside the footage; chat=off, or `chat=` (the default), does not. A video with no chat draws nothing and the",
+ " build log says so. The column's look: umtool look <p> chat.position=left (docs/knobs.md \"Live chat\").",
" gap.add=12.3-15.1 cuts those source seconds out of the clip's middle (one segment of jump cuts; inside",
" the cut, ≥ 0.2 s, 0.5 s kept between); gap.remove=<sec> the gap holding it; gaps=12.3-15.1,20-20.6 (or",
" a JSON list of {from,to}) the whole list, `gaps=` none. The same as `umtool window --gap/--gap-remove/--gaps`.",
@@ -108,7 +111,7 @@ export const LOOK_USAGE = [
" the first); a marker's label is optional (none: a tick); deck.rail.labels=false draws no marker's words",
" deck.sectionTitle=true | deck.sectionTitle='{\"first\":\"Who she is\"}': the current section's name (its marker's label)",
" on one quiet line under the rail; .size .opacity .fade .color (auto|section|#hex|palette key); false or `=` is off",
- " pair=<json> | pair.<key>=…, chapter=<json> | chapter.<key>=…, status=<json> | status.<key>=…: the story modules",
+ " pair=<json> | pair.<key>=…, chapter=<json> | chapter.<key>=…, status=<json> | status.<key>=…, chat=<json> | chat.<key>=…: the story modules",
" (render.chrome.pair / .chapter / .status, docs/knobs.md \"Modules\"), checked by the build's rules",
" variants='[{\"name\":\"master\"},{\"name\":\"720p\",\"height\":720,\"crf\":23},{\"name\":\"fit24\",\"maxMiB\":24}]'",
` the look: ${LOOK_KEYS.join(", ")} (a JSON value each)`,
@@ -117,6 +120,14 @@ export const LOOK_USAGE = [
class CliError extends Error {}
+/** `chat=on|off|true|false` into true|false; `chat=` (null) clears it. */
+export function chatFlag(value) {
+ if (value === null || value === undefined) return null;
+ if (value === true || value === "on") return true;
+ if (value === false || value === "off") return false;
+ throw new CliError(`chat=${JSON.stringify(value)}: on or off (\`chat=\` clears it)`);
+}
+
/** `a=b` words into [key, value]: JSON when it parses, else the text; `a=` is null (clear). */
export function parseAssignments(words) {
return words.map((w) => {
@@ -194,6 +205,11 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
entryPatch.layout = value;
continue;
}
+ if (key === "chat") {
+ // The live-chat column beside this clip (report-to-video chat.mjs): on|off|true|false; `chat=` clears it.
+ entryPatch.chat = chatFlag(value);
+ continue;
+ }
if (FX_KEYS.includes(key)) {
// The punch is words whatever they parse as (`fx.punch=2020`).
entryPatch[key] = key === "fx.punch" && value !== null ? String(value) : value;
@@ -250,6 +266,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if ("audio" in entryPatch) results.audio = result.entry.audio ?? null;
if ("blur" in entryPatch) results.blur = result.entry.blur ?? null;
if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip";
+ if ("chat" in entryPatch) results.chat = result.entry.chat ?? null;
if (FX_KEYS.some((k) => k in entryPatch)) results.fx = result.entry.fx ?? null;
if ("gaps" in entryPatch || "gapAdd" in entryPatch || "gapRemove" in entryPatch) {
results.gaps = result.entry.gaps ?? [];
@@ -279,6 +296,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if ("audio" in results) out(`${clipId}: audio ${results.audio ? JSON.stringify(results.audio) : "as recorded"}`);
if ("blur" in results) out(`${clipId}: blur ${results.blur ? JSON.stringify(results.blur) : "none (the picture as recorded)"}`);
if ("layout" in results) out(`${clipId}: layout ${results.layout}`);
+ if ("chat" in results) out(`${clipId}: chat ${results.chat === true ? "on (its video's live_chat.cues.json beside the footage; the build says if there is none)" : results.chat === false ? "off" : "default (off)"}`);
if ("fx" in results) out(`${clipId}: fx ${results.fx ? JSON.stringify(results.fx) : "none"}`);
if ("gaps" in results) out(`${clipId}: ${results.gaps.length ? `gaps ${results.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps (the cut plays whole)"}`);
if (results.review) {
@@ -389,7 +407,7 @@ export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => cons
const variants = pairs.filter(([k]) => k === "variants");
const look = pairs.filter(([k]) => LOOK_KEYS.includes(k));
// The story modules (release 39): `pair=<json>`, `pair.style=…`, likewise chapter and status.
- const STORY = ["pair", "chapter", "status"];
+ const STORY = ["pair", "chapter", "status", "chat"];
const isStory = (k) => STORY.includes(k.split(".")[0]);
const story = pairs.filter(([k]) => isStory(k));
const unknown = pairs.filter(([k]) => !k.startsWith("factcheck.") && !k.startsWith("deck.") && k !== "variants" && !LOOK_KEYS.includes(k) && !isStory(k));
diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs
@@ -47,6 +47,28 @@ test("parseAssignments: JSON when it parses, text otherwise, empty clears", () =
assert.throws(() => parseAssignments(["nope"]), /not key=value/);
});
+test("umtool set chat=on|off|true|false writes the clip's chat flag; chat= clears it; anything else is refused", async () => {
+ const dir = await project("chat");
+ const { lines, run } = runner(setCommand);
+ assert.equal(await run("chat", "c02", "chat=on"), 0);
+ assert.equal((await read(dir)).timeline[1].chat, true);
+ assert.match(lines.at(-1), /chat on/);
+ assert.equal(await run("chat", "c02", "chat=off"), 0);
+ assert.equal((await read(dir)).timeline[1].chat, false);
+ assert.equal(await run("chat", "c02", "chat=true"), 0);
+ assert.equal((await read(dir)).timeline[1].chat, true);
+ assert.equal(await run("chat", "c02", "chat="), 0);
+ assert.equal("chat" in (await read(dir)).timeline[1], false);
+ assert.equal(await run("chat", "c02", "chat=maybe"), 2);
+ assert.match(lines.at(-1), /on or off/);
+ // The look: render.chrome.chat through `umtool look`, checked by the build's rules.
+ const look = runner(lookCommand);
+ assert.equal(await look.run("chat", "chat.position=left", "chat.lines=8"), 0);
+ assert.deepEqual((await read(dir)).render.chrome.chat, { position: "left", lines: 8 });
+ assert.notEqual(await look.run("chat", "chat.lines=99"), 0);
+ assert.deepEqual((await read(dir)).render.chrome.chat, { position: "left", lines: 8 });
+});
+
test("umtool set: claim and audio knobs through the writers; key= clears; a bad key or value is refused", async () => {
const dir = await project("set");
const { lines, run } = runner(setCommand);
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -704,6 +704,14 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
if (bad.length) throw new Error(`layout: ${bad.join("; ")}`);
}
+ // The live-chat column beside this clip (chat.mjs): true shows it, false is
+ // the explicit no, null/"" removes the key (the default: off).
+ if (patch.chat !== undefined) {
+ if (patch.chat === null || patch.chat === "") delete entry.chat;
+ else if (typeof patch.chat === "boolean") entry.chat = patch.chat;
+ else throw new Error(`chat must be true or false, not ${JSON.stringify(patch.chat)}`);
+ }
+
// ---- the walk's verdict -------------------------------------------------
//
// Whether somebody has LOOKED at this clip, and what they said: confirmed,
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -172,6 +172,7 @@ import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
import { deckOverlays, moduleById, placementOf } from "./modules/index.mjs";
+import { CHAT_CUES_FILE, chatWanted } from "./chat.mjs";
import { counterOrder } from "./counter.mjs";
// The upload's text (release 28 M6): composed by code, written beside the cut.
import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs";
@@ -5590,6 +5591,9 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du
// The effects' words (render.chrome.fx): read only when an effect is on, so
// a cut without them measures exactly what it did.
const fx = fxOn(render) ? await fxClipWords({ entries, segments, provenance, render }) : null;
+ // The chat (chat.mjs): read only when a clip asks for it, so a cut without
+ // it measures exactly what it did.
+ const chat = entries.some(chatWanted) ? await chatClipCues({ entries, segments, provenance, render }) : null;
// A claim stamped at a source second (`claim.at`): the source second each
// claimed clip's segment really starts at, from its cut record (snapped,
// room included). Read only then.
@@ -5622,6 +5626,7 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du
return deckSchedule({
entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null,
...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}),
+ ...(chat ? { chat } : {}),
...(clipClock ? { clipClock } : {}),
...(clipGaps ? { clipGaps } : {}),
...(estimated ? { estimated: true } : {}),
@@ -5629,6 +5634,48 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du
}
/**
+ * The chat for the clips that ask for it (`chat: true`, chat.mjs): each
+ * clip's video's `live_chat.cues.json` (SOURCE seconds), and `clock` the
+ * source second each clip's segment starts at (its cut record's, else the
+ * play window's). A clip whose video has no chat -- or no corpus to read it
+ * from -- gets no entry and the build log says so (a `note` event); this
+ * never throws for a missing or unreadable file.
+ * @returns {Promise<{ cues: Map<string, any[]>, clock: Map<string, number> }>}
+ */
+export async function chatClipCues({ entries, segments, provenance = {}, render }) {
+ const cues = new Map();
+ const clock = new Map();
+ const files = new Map();
+ for (let i = 0; i < entries.length; i += 1) {
+ const e = entries[i];
+ if (!chatWanted(e)) continue;
+ const why = await (async () => {
+ if (hasLocalMedia(e)) return "it plays a file beside the manifest, which has no chat";
+ if (!FX_CHANNELS_DIR) return "this build has no local corpus to read the chat from";
+ if (!e.video) return "it names no video";
+ try {
+ const dir = await resolveVideoDir(FX_CHANNELS_DIR, e.channel ?? provenance.channelSlug, e.video);
+ const file = path.join(dir, CHAT_CUES_FILE);
+ if (!files.has(file)) files.set(file, JSON.parse(await readFile(file, "utf8")).cues);
+ const list = files.get(file);
+ if (!Array.isArray(list) || !list.length) return `${CHAT_CUES_FILE} holds no messages`;
+ cues.set(e.id, list);
+ return null;
+ } catch (err) {
+ return err?.code === "ENOENT" ? `it has no ${CHAT_CUES_FILE}` : `${CHAT_CUES_FILE} could not be read (${err?.message ?? err})`;
+ }
+ })();
+ if (why) {
+ EMIT("note", { message: `chat: ${e.id} draws no chat -- ${why}` });
+ continue;
+ }
+ const rec = segments[i] ? await readCutRecord(segments[i]).catch(() => null) : null;
+ clock.set(e.id, Number.isFinite(rec?.start) ? rec.start : playWindow(e, render).from);
+ }
+ return { cues, clock };
+}
+
+/**
* Each clip's timed words for the effects (fx.mjs), in its SEGMENT's seconds:
* whisper.cpp's words when the corpus keeps them (transcript.json), else its
* cues split into words by character position -- the words said in its cited
diff --git a/umtool/report-to-video/chat.mjs b/umtool/report-to-video/chat.mjs
@@ -0,0 +1,154 @@
+// THE CHAT OVERLAY (module `chat`, region `chat`): a stream's live-chat replay
+// scrolled in a column beside the footage over the clips that ask for it --
+// author and text, newest at the bottom.
+//
+// render.chrome: "chat": { "position": "right", "lines": 10, "width": 380, "maxChars": 120, "minGap": 0.6 }
+// timeline entry: "chat": true (this clip shows its chat) | false / absent (it does not)
+// `umtool set <project> <clip> chat=on|off`
+// corpus: channels/<slug>/data/<video>/live_chat.cues.json (common/controller/normalizeLiveChat.ts):
+// { cues: [{ start, end, text: "<author>: <message>" }] }, SOURCE seconds
+//
+// A clip shows the messages of its own SOURCE span, mapped onto the cut's
+// clock through gaps.mjs (a message said inside a gap is not shown; one after
+// it lands earlier by the gap). A clip with no chat file draws nothing and the
+// build says so (build-video.mjs chatClipCues); it never fails the build.
+//
+// PURE, like stats.mjs: validation, defaults, the schedule. No fs. deck.mjs
+// imports this file -- never the other way round.
+import { inGap, offsetIn, sourceAtOffset } from "./gaps.mjs";
+
+/** The file a video keeps its normalised chat replay in (common/lib/videoStatus.ts LIVE_CHAT_CUES_FILENAME). */
+export const CHAT_CUES_FILE = "live_chat.cues.json";
+
+export const CHAT_POSITIONS = Object.freeze(["right", "left"]);
+export const CHAT_LIMITS = Object.freeze({ lines: [3, 16], width: [240, 640], maxChars: [20, 300], minGap: [0, 5], author: 24 });
+export const CHAT_DEFAULTS = Object.freeze({ position: "right", lines: 10, width: 380, maxChars: 120, minGap: 0.6 });
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+
+/** The chat settings with every default filled in. */
+export function resolveChat(render) {
+ const v = isObj(render?.chrome?.chat) ? render.chrome.chat : {};
+ return { ...CHAT_DEFAULTS, ...v };
+}
+
+/** Every reason `render.chrome.chat` cannot be built, as sentences (empty: it can). */
+export function validateChat(v, where = "render.chrome.chat") {
+ if (v === undefined) return [];
+ if (!isObj(v)) return [`${where} must be an object`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!(k in CHAT_DEFAULTS)) errors.push(`${where}.${k} is not a chat setting (${Object.keys(CHAT_DEFAULTS).join(", ")})`);
+ if (v.position !== undefined && !CHAT_POSITIONS.includes(v.position)) errors.push(`${where}.position must be ${CHAT_POSITIONS.map((p) => `"${p}"`).join(" or ")}`);
+ for (const k of ["lines", "width", "maxChars"]) {
+ if (v[k] !== undefined && !(Number.isInteger(v[k]) && numIn(v[k], ...CHAT_LIMITS[k]))) errors.push(`${where}.${k} must be a whole number from ${CHAT_LIMITS[k][0]} to ${CHAT_LIMITS[k][1]}`);
+ }
+ if (v.minGap !== undefined && !numIn(v.minGap, ...CHAT_LIMITS.minGap)) errors.push(`${where}.minGap must be seconds from ${CHAT_LIMITS.minGap[0]} to ${CHAT_LIMITS.minGap[1]}`);
+ return errors;
+}
+
+/** Does this entry ask for its chat (`chat: true` on a clip)? */
+export const chatWanted = (entry) => entry?.type === "clip" && entry.chat === true;
+
+/** The clips that ask for chat, by id. */
+export const chatClips = (manifest) => (manifest?.timeline ?? []).filter(chatWanted).map((e) => e.id);
+
+/** Every `chat` key in the timeline, checked: a boolean, on a clip, drawn by the deck. */
+export function validateChatEntries(manifest) {
+ const errors = [];
+ const render = manifest?.render ?? {};
+ const deck = render.chrome?.engine === "hyperframes" && render.chrome?.layout === "deck";
+ if (isObj(render.chrome?.chat) && !deck) errors.push("render.chrome.chat is drawn by the deck: render.chrome needs layout \"deck\"");
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.chat === undefined) return;
+ const where = `timeline[${i}] (${e.id ?? "?"}).chat`;
+ if (typeof e.chat !== "boolean") errors.push(`${where} must be true or false`);
+ else if (e.type !== "clip") errors.push(`${where}: only a clip carries a chat`);
+ else if (e.chat && !deck) errors.push(`${where}: the chat is drawn by the deck, and render.chrome is not the deck`);
+ });
+ return errors;
+}
+
+/** `{ author, text }` from a normalised chat cue's `<author>: <message>` (no author: the whole line is the message). */
+export function splitChatCue(text) {
+ const s = String(text ?? "").replace(/\s+/g, " ").trim();
+ // "author:" with nothing after it is an author and no message.
+ if (/^[^:]{1,60}:$/.test(s)) return { author: s.slice(0, -1), text: "" };
+ const i = s.indexOf(": ");
+ if (i <= 0 || i > 60) return { author: "", text: s };
+ return { author: s.slice(0, i), text: s.slice(i + 2).trim() };
+}
+
+/** `s` cut to `max` characters with an ellipsis (by code point). */
+export function clampChars(s, max) {
+ const chars = [...String(s)];
+ return chars.length <= max ? String(s) : `${chars.slice(0, Math.max(1, max - 1)).join("").trimEnd()}…`;
+}
+
+/**
+ * A clip's chat in its segment: `cues` the normalised replay (SOURCE
+ * seconds), `sourceFrom` the source second the segment's picture starts at,
+ * `seconds` the segment's own length (the gapped clock), `gaps` its gaps.
+ * Returns `[{ at, author, text }]` with `at` in SEGMENT seconds, thinned so no
+ * two are closer than `minGap` (a busy chat shows its every n-th line). A
+ * message said in a gap is not shown. Empty messages and ones outside the
+ * span are left out.
+ */
+export function chatWindow({ cues, sourceFrom, seconds, gaps = null, minGap = CHAT_DEFAULTS.minGap, maxChars = CHAT_DEFAULTS.maxChars, since = 0 }) {
+ if (!Array.isArray(cues) || !Number.isFinite(sourceFrom) || !(seconds > 0)) return [];
+ const lastSrc = sourceAtOffset(seconds, sourceFrom, gaps);
+ const out = [];
+ let last = -Infinity;
+ for (const c of [...cues].sort((a, b) => a.start - b.start)) {
+ if (!Number.isFinite(c?.start) || c.start < sourceFrom || c.start >= lastSrc) continue;
+ if (inGap(c.start, gaps)) continue;
+ const at = offsetIn(c.start, sourceFrom, gaps);
+ if (at < since) continue;
+ const m = splitChatCue(c.text);
+ if (!m.text) continue;
+ if (at - last < minGap) continue;
+ last = at;
+ out.push({ at: r3(at), author: clampChars(m.author, CHAT_LIMITS.author), text: clampChars(m.text, maxChars) });
+ }
+ return out;
+}
+
+/**
+ * The chat the cut draws, in the CUT's clock. `segments` are the schedule's,
+ * each `{ id, start, duration, cues?, sourceFrom?, gaps? }` (`cues` only on a
+ * clip that asked and has chat). A clip's panel is up from its start (its
+ * incoming dissolve's middle after the first) to its end, like the stats'.
+ *
+ * @returns {{ position: string, lines: number, width: number,
+ * clips: Array<{ segment: string, in: number, out: number, messages: Array<{ at: number, author: string, text: string }> }> } | null}
+ */
+export function chatSchedule({ segments, D, total, render }) {
+ const cfg = resolveChat(render);
+ const clips = [];
+ segments.forEach((s, i) => {
+ if (!s.cues?.length || !Number.isFinite(s.sourceFrom)) return;
+ const next = segments[i + 1];
+ const lo = s.start + (i > 0 ? D / 2 : 0);
+ const hi = next ? next.start + D / 2 : total;
+ if (!(hi > lo)) return;
+ const messages = chatWindow({
+ cues: s.cues, sourceFrom: s.sourceFrom, seconds: hi - s.start, gaps: s.gaps,
+ minGap: cfg.minGap, maxChars: cfg.maxChars, since: lo - s.start,
+ }).map((m) => ({ ...m, at: r3(s.start + m.at) }));
+ if (messages.length) clips.push({ segment: s.id, in: r3(lo), out: r3(hi), messages });
+ });
+ return clips.length ? { position: cfg.position, lines: cfg.lines, width: cfg.width, clips } : null;
+}
+
+/**
+ * A clip's states: between two messages the column reads the same -- the
+ * last `lines` messages up to the newest. `[{ at, until, rows }]`.
+ */
+export function chatStates(clip, lines) {
+ return clip.messages.map((m, j) => ({
+ at: m.at,
+ until: clip.messages[j + 1]?.at ?? clip.out,
+ rows: clip.messages.slice(Math.max(0, j - lines + 1), j + 1),
+ }));
+}
diff --git a/umtool/report-to-video/chat.test.mjs b/umtool/report-to-video/chat.test.mjs
@@ -0,0 +1,151 @@
+// The chat overlay (chat.mjs, chrome-chat.mjs, modules/chat.mjs, build-video.mjs chatClipCues):
+// the span/gap mapping, the message windowing, the missing-file case, the page.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import {
+ CHAT_CUES_FILE, chatSchedule, chatStates, chatWanted, chatWindow, clampChars, resolveChat, splitChatCue, validateChat, validateChatEntries,
+} from "./chat.mjs";
+import { chatGeometry, chatHtml } from "./chrome-chat.mjs";
+import { deckSchedule } from "./deck.mjs";
+import chat from "./modules/chat.mjs";
+import { moduleById, scheduleSlices } from "./modules/index.mjs";
+
+const RENDER = {
+ width: 1920, height: 1080, fps: 30,
+ palette: { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" },
+ chrome: { engine: "hyperframes", layout: "deck", deck: {} },
+};
+const cue = (start, text) => ({ start, end: start + 1, text });
+// A stream's chat, one message a second from source second 100.
+const CUES = Array.from({ length: 40 }, (_, i) => cue(100 + i, `user${i}: message ${i}`));
+
+test("splitChatCue and clampChars: author and text, long lines cut", () => {
+ assert.deepEqual(splitChatCue("ann: hi there: friend"), { author: "ann", text: "hi there: friend" });
+ assert.deepEqual(splitChatCue("no author here"), { author: "", text: "no author here" });
+ assert.deepEqual(splitChatCue(" a b "), { author: "", text: "a b" });
+ assert.equal(clampChars("abcdef", 4), "abc…");
+ assert.equal(clampChars("abc", 4), "abc");
+});
+
+test("chatWindow: the clip's source span on the segment's clock, thinned, capped", () => {
+ const w = chatWindow({ cues: CUES, sourceFrom: 110, seconds: 10, minGap: 0 });
+ // Source 110..119 -> segment 0..9; 120 is past the end.
+ assert.deepEqual(w.map((m) => m.at), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
+ assert.equal(w[0].text, "message 10");
+ assert.equal(w[0].author, "user10");
+ // Thinning: one message per 2.5 s keeps every third.
+ assert.deepEqual(chatWindow({ cues: CUES, sourceFrom: 110, seconds: 10, minGap: 2.5 }).map((m) => m.at), [0, 3, 6, 9]);
+ // Length cap.
+ const long = chatWindow({ cues: [cue(5, `x: ${"w".repeat(500)}`)], sourceFrom: 0, seconds: 10, maxChars: 40 });
+ assert.equal([...long[0].text].length, 40);
+ assert.match(long[0].text, /…$/);
+ // Empty messages, a cue before the span and a non-list.
+ assert.deepEqual(chatWindow({ cues: [cue(5, "ann: "), cue(1, "b: early")], sourceFrom: 2, seconds: 10 }), []);
+ assert.deepEqual(chatWindow({ cues: null, sourceFrom: 2, seconds: 10 }), []);
+});
+
+test("chatWindow: gaps -- a message said in a gap is not shown, a later one lands earlier", () => {
+ // Source 110..120 with seconds 112..115 taken out: plays 5 s + 5 s.
+ const gaps = [{ from: 112, to: 115 }];
+ const w = chatWindow({ cues: CUES, sourceFrom: 110, seconds: 7, gaps, minGap: 0 });
+ // Segment seconds 0..6 show source 110,111,(112 edge),115..119: 113,114 gone.
+ const texts = w.map((m) => m.text);
+ assert.ok(!texts.includes("message 13") && !texts.includes("message 14"), "gap messages dropped");
+ assert.deepEqual(w.find((m) => m.text === "message 15").at, 2, "source 115 is 5 s in, less the 3 s gap before it");
+ assert.deepEqual(w.find((m) => m.text === "message 11").at, 1);
+});
+
+test("chatSchedule: the cut's clock, the first clip from its start and the next from its dissolve's middle", () => {
+ const segments = [
+ { id: "a", start: 0, duration: 10, cues: CUES, sourceFrom: 110 },
+ { id: "b", start: 9.5, duration: 10 },
+ { id: "c", start: 19, duration: 10, cues: CUES, sourceFrom: 120, gaps: [{ from: 125, to: 130 }] },
+ ];
+ const s = chatSchedule({ segments, D: 1, total: 29, render: RENDER });
+ assert.deepEqual(s.clips.map((c) => [c.segment, c.in, c.out]), [["a", 0, 10], ["c", 19.5, 29]]);
+ // a: source 110.. -> cut 0..; thinned at the 0.6 s default to every 1 s message.
+ assert.equal(s.clips[0].messages[0].at, 0);
+ // c starts at 19, so its first shown message is the one at or after 19.5.
+ assert.ok(s.clips[1].messages[0].at >= 19.5);
+ assert.ok(s.clips[1].messages.every((m) => m.text !== "message 27"), "a message in the gap (source 125-130) is not shown");
+ assert.equal(chatSchedule({ segments: [{ id: "a", start: 0, duration: 5 }], D: 1, total: 5, render: RENDER }), null);
+});
+
+test("chatStates: the last `lines` messages up to the newest, each held until the next", () => {
+ const clip = { in: 0, out: 5, messages: [1, 2, 3, 4].map((n) => ({ at: n, author: "a", text: `m${n}` })) };
+ const st = chatStates(clip, 2);
+ assert.deepEqual(st.map((s) => [s.at, s.until, s.rows.map((r) => r.text)]), [[1, 2, ["m1"]], [2, 3, ["m1", "m2"]], [3, 4, ["m2", "m3"]], [4, 5, ["m3", "m4"]]]);
+});
+
+test("validateChat and validateChatEntries: bounds, unknown keys, a boolean on a clip under the deck", () => {
+ assert.deepEqual(validateChat(undefined), []);
+ assert.deepEqual(validateChat({ position: "left", lines: 8, width: 300, maxChars: 80, minGap: 1 }), []);
+ assert.match(validateChat({ position: "middle" })[0], /position must be/);
+ assert.match(validateChat({ lines: 99 })[0], /lines must be a whole number from 3 to 16/);
+ assert.match(validateChat({ colour: 1 })[0], /colour is not a chat setting/);
+ assert.match(validateChat([])[0], /must be an object/);
+ const m = (e, render = RENDER) => ({ render, timeline: [e] });
+ assert.deepEqual(validateChatEntries(m({ type: "clip", id: "a", chat: true })), []);
+ assert.match(validateChatEntries(m({ type: "clip", id: "a", chat: "on" }))[0], /must be true or false/);
+ assert.match(validateChatEntries(m({ type: "card", id: "a", chat: true }))[0], /only a clip/);
+ assert.match(validateChatEntries(m({ type: "clip", id: "a", chat: true }, { ...RENDER, chrome: undefined }))[0], /drawn by the deck/);
+ assert.equal(chatWanted({ type: "clip", chat: true }), true);
+ assert.equal(chatWanted({ type: "clip", chat: false }), false);
+ assert.equal(chatWanted({ type: "card", chat: true }), false);
+});
+
+test("deckSchedule carries the chat only for a clip that has cues; the module draws exactly then", () => {
+ const entries = [
+ { type: "clip", id: "a", video: "v", start: 110, end: 120, chat: true },
+ { type: "clip", id: "b", video: "w", start: 0, end: 10 },
+ ];
+ const base = { entries, durs: [10, 10], D: 0.5, render: RENDER, estimated: true };
+ assert.equal(deckSchedule(base).chat, undefined, "no chat: the schedule is what it always was");
+ const doc = deckSchedule({ ...base, chat: { cues: new Map([["a", CUES]]), clock: new Map([["a", 110]]) } });
+ assert.equal(doc.chat.clips.length, 1);
+ assert.equal(doc.chat.clips[0].segment, "a");
+ assert.equal(chat.on(doc, RENDER), true);
+ assert.equal(chat.on({}, RENDER), false);
+ assert.match(chat.check({}), /needs a schedule/);
+ assert.equal(moduleById("chat"), chat);
+ assert.equal(scheduleSlices(doc).chat, undefined, "the page reads the whole schedule, as stats does");
+});
+
+test("the chat page: a state per message, newest at the bottom, the geometry beside the footage", () => {
+ const doc = deckSchedule({
+ entries: [{ type: "clip", id: "a", video: "v", start: 110, end: 120, chat: true }],
+ durs: [10], D: 0.5, render: RENDER, estimated: true,
+ chat: { cues: new Map([["a", CUES]]), clock: new Map([["a", 110]]) },
+ });
+ const { html, items } = chatHtml(doc, RENDER, { fonts: { regular: "r.ttf", bold: "b.ttf" } });
+ assert.match(html, /data-composition-id="chat"/);
+ assert.equal(items.length, doc.chat.clips[0].messages.length);
+ const last = items[items.length - 1].html;
+ assert.ok(last.indexOf("message 10") < last.indexOf("message 19") || !last.includes("message 10"), "oldest first, newest last");
+ assert.match(last, /message 19/);
+ assert.ok(html.includes('id="chat-data"'));
+ const g = chatGeometry(RENDER);
+ const left = chatGeometry({ ...RENDER, chrome: { ...RENDER.chrome, chat: { position: "left", width: 300 } } });
+ assert.ok(g.x > left.x && left.width === 300);
+ assert.throws(() => chatHtml({ ...doc, chat: undefined }, RENDER), /plays none/);
+ assert.equal(resolveChat(RENDER).lines, 10);
+});
+
+test("chatClipCues: no chat file is a note, never a failure; a file's cues are read for the clip", async () => {
+ const { chatClipCues } = await import("./build-video.mjs");
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-chat-"));
+ try {
+ // No corpus configured in a unit test: every clip is a note and the build goes on.
+ const none = await chatClipCues({ entries: [{ type: "clip", id: "a", video: "v1", chat: true }], segments: [], provenance: { channelSlug: "chan" }, render: RENDER });
+ assert.equal(none.cues.size, 0);
+ assert.equal(CHAT_CUES_FILE, "live_chat.cues.json");
+ await mkdir(path.join(dir, "chan", "data", "v1"), { recursive: true });
+ await writeFile(path.join(dir, "chan", "data", "v1", CHAT_CUES_FILE), JSON.stringify({ cues: CUES }));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/chrome-chat.mjs b/umtool/report-to-video/chrome-chat.mjs
@@ -0,0 +1,84 @@
+// THE CHAT PAGE (module `chat`, modules/chat.mjs): a column beside the footage
+// that scrolls a stream's chat for the clips that ask for it. A cue page
+// (chrome-cues.mjs): each STATE of the column (the last `lines` messages up to
+// the newest) is its own block, shown over exactly its span, so a changed
+// message recaptures only the frames it is up. PURE: a schedule and a render
+// block in, geometry and HTML out.
+import { rgba } from "./chrome-deck.mjs";
+import { compileCues, cuePageHtml, esc, INSTANT, joinSpans, spanEvents } from "./chrome-cues.mjs";
+import { chatStates, resolveChat } from "./chat.mjs";
+import { footageBox } from "./chrome-story.mjs";
+
+const scaleOf = (render) => (render?.width ?? 1920) / 1920;
+const pxOf = (render) => (v) => Math.max(1, Math.round(v * scaleOf(render)));
+const even = (v) => 2 * Math.round(v / 2);
+
+/** The chat column's region: a strip down one side of the footage box, `width` wide. */
+export function chatGeometry(render, { feed = false } = {}) {
+ const f = footageBox(render, { feed });
+ const C = resolveChat(render);
+ const px = pxOf(render);
+ const inset = px(18);
+ const width = even(Math.min(px(C.width), f.width - 2 * inset));
+ const height = even(f.height - 2 * inset);
+ return {
+ x: C.position === "left" ? f.x + inset : f.x + f.width - inset - width,
+ y: f.y + inset,
+ width, height,
+ };
+}
+
+/** The chat page: `{ html, items }`, each state an item gated by its own autoAlpha. */
+export function chatHtml(schedule, render, opts = {}) {
+ const C = resolveChat(render);
+ const clips = schedule?.chat?.clips ?? [];
+ const lines = schedule?.chat?.lines ?? C.lines;
+ const states = clips.flatMap((c) => chatStates(c, lines));
+ if (!states.length) throw new Error("chat: the cut plays none of the chat's clips");
+ const geo = chatGeometry(render, { feed: schedule.layout === "feed" });
+ const pal = render.palette;
+ const px = pxOf(render);
+ const fps = schedule.fps ?? render.fps ?? 30;
+ const init = { chat: { autoAlpha: 0 } };
+ const ev = [];
+ // The column is up over each clip's whole span, even between its messages.
+ for (const sp of joinSpans(clips.map((c) => ({ in: c.in, out: c.out })), 1e-3)) {
+ ev.push(...spanEvents("chat", sp.in, sp.out, { fadeIn: 0.35, fadeOut: 0.35 }));
+ }
+ const items = [];
+ const blocks = states.map((st, j) => {
+ const k = `s${j}`;
+ init[k] = { autoAlpha: 0 };
+ ev.push({ k, at: st.at, dur: INSTANT, to: { autoAlpha: 1 }, ease: "none" });
+ ev.push({ k, at: st.until, dur: INSTANT, to: { autoAlpha: 0 }, ease: "none" });
+ const rows = st.rows.map((m, i) => {
+ const age = st.rows.length - 1 - i;
+ const dim = age >= 6 ? " old" : "";
+ return `<div class="m${dim}">${m.author ? `<span class="au">${esc(m.author)}</span> ` : ""}<span class="tx">${esc(m.text)}</span></div>`;
+ }).join("");
+ const html = `<div class="st" data-k="${k}">${rows}</div>`;
+ items.push({ key: k, gate: [k, "autoAlpha"], html });
+ return html;
+ });
+ const { init: i2, cues } = compileCues(init, ev);
+ const css = `
+ #chat { position: absolute; inset: 0; visibility: hidden; opacity: 0; }
+ /* Each state is a column of its own, bottom-aligned: the newest message at the foot, the oldest pushed off the top. */
+ .st { position: absolute; inset: 0; visibility: hidden; opacity: 0; display: flex; flex-direction: column;
+ justify-content: flex-end; gap: ${px(6)}px; overflow: hidden;
+ -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 ${px(70)}px); mask-image: linear-gradient(to bottom, transparent 0, #000 ${px(70)}px); }
+ .m { flex: none; padding: ${px(7)}px ${px(12)}px; border-radius: ${px(8)}px; background: ${rgba(pal.bg, 0.78)};
+ font-size: ${px(22)}px; line-height: ${px(28)}px; color: ${pal.fg}; overflow: hidden; overflow-wrap: anywhere;
+ display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; max-height: ${px(4 * 28 + 14)}px; }
+ .m.old { opacity: 0.72; }
+ .au { font-family: 'DeckSansBold', sans-serif; color: ${pal.accent}; }
+ .tx { color: ${pal.fg}; }`;
+ const body = `<div id="chat" data-k="chat">
+ ${blocks.join("\n ")}
+ </div>`;
+ const html = cuePageHtml({
+ id: "chat", W: geo.width, H: geo.height, fps, fonts: opts.fonts, gsapSrc: opts.gsap, css, body, init: i2, cues,
+ whole: { total: schedule.total, from: opts.from, duration: opts.duration, ids: states.map((_, j) => `s${j}`) },
+ });
+ return { html, items };
+}
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -44,6 +44,7 @@ export {
export { SECTION_TITLE_DEFAULTS, SUBTITLE_LINES } from "./modules/settings.mjs";
import { threadOf, threadSchedule, threadsOn, validateThreads } from "./threads.mjs";
import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs";
+import { chatSchedule } from "./chat.mjs";
import { overlayPointsOf, resolveStats, statsSchedule, statsWanted, validateStats } from "./stats.mjs";
import { fxOn, fxSchedule, validateFx } from "./fx.mjs";
import { estimatedNarratedCardSeconds, hasNarration } from "./narration.mjs";
@@ -143,7 +144,7 @@ export function validateChrome(chrome, render = {}) {
const errors = [];
if (chrome === undefined || chrome === null) return errors;
if (!isObj(chrome)) return ["render.chrome must be an object"];
- unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats", "fx", "pair", "chapter", "status"], "render.chrome", errors);
+ unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats", "fx", "pair", "chapter", "status", "chat"], "render.chrome", errors);
if (chrome.engine !== "hyperframes") errors.push('render.chrome.engine must be "hyperframes"');
if (chrome.layout !== "deck") errors.push('render.chrome.layout must be "deck"');
if (render.rail) errors.push("render.chrome (the deck) and render.rail cannot both be set");
@@ -1108,7 +1109,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin
*/
export function deckSchedule({
entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null,
- fxWords = null, fxClock = null, clipClock = null, clipGaps = null,
+ fxWords = null, fxClock = null, clipClock = null, clipGaps = null, chat = null,
}) {
const deck = resolveDeck(render);
// A clip's gaps (gaps.mjs) on its segment: its cut record's as built
@@ -1186,6 +1187,18 @@ export function deckSchedule({
}),
D, total, render,
});
+ // The chat (chat.mjs): on the clips that ask for it, their video's chat
+ // cues (`chat.cues`, by clip id) from the segment's first source second.
+ const chatSched = chat
+ ? chatSchedule({
+ segments: segs.map((s, i) => {
+ const e = entries[i];
+ const cues = chat.cues.get(e.id);
+ return cues?.length ? withGaps({ ...s, cues, sourceFrom: chat.clock.get(e.id) ?? playWindow(e, render).from }, e) : s;
+ }),
+ D, total, render,
+ })
+ : null;
// The effects (fx.mjs): only when one is on, so a cut without them writes
// the schedule it always did. `fxWords` are each clip's timed words in its
// segment's seconds (the build reads them); `fxClock` the source second each
@@ -1259,6 +1272,8 @@ export function deckSchedule({
...(flips ? { flips } : {}),
// The stats region: present only when a clip declares it.
...(stats ? { stats } : {}),
+ // The chat column: present only when a clip asks for it and its video has chat.
+ ...(chatSched ? { chat: chatSched } : {}),
// The effects region: present only when an effect is on, with the box it is drawn over.
...(fx ? { fx: { ...fx, box: fxGeometry(render, { feed }) } } : {}),
// Present only when there are posts to draw, so a cut without them writes
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -88,6 +88,7 @@ import { validateFinaleEntries } from "./finale.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
+import { validateChatEntries } from "./chat.mjs";
import { validateMontage } from "./montage.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { validateFxEntries } from "./fx.mjs";
@@ -293,6 +294,8 @@ export function validatorErrors(whole) {
...validateDrafted(whole), ...validatePublish(whole),
// Release 31: the stats region's `stats` keys and render.chrome.stats.
...validateStatsEntries(whole),
+ // A clip's `chat` and render.chrome.chat (chat.mjs).
+ ...validateChatEntries(whole),
// Release 33: render.montage, its keys and what it does not combine with.
...validateMontage(whole),
// Release 35: a clip's `assist` (the clip finder's provenance; the render ignores it).
diff --git a/umtool/report-to-video/modules/chat.mjs b/umtool/report-to-video/modules/chat.mjs
@@ -0,0 +1,60 @@
+// THE CHAT (module `chat`, region `chat`): a stream's live-chat replay in a
+// column down one side of the footage, over the clips that ask for it
+// (`umtool set <p> <clip> chat=on`; `render.chrome.chat` for the look). The
+// messages are the video's own `live_chat.cues.json`, for the clip's SOURCE
+// span, timed to the cut through the clip's gaps. chat.mjs holds the rules,
+// chrome-chat.mjs writes the page.
+import path from "node:path";
+
+import { chatGeometry, chatHtml } from "../chrome-chat.mjs";
+import { CHAT_DEFAULTS, CHAT_LIMITS, CHAT_POSITIONS, resolveChat, validateChat } from "../chat.mjs";
+import { assertRegion, defineModule } from "./contract.mjs";
+
+export default defineModule({
+ id: "chat",
+ version: 1,
+ z: 48,
+ kind: "overlay-whole",
+ slot: "panel",
+ title: "Live chat",
+ summary: "A stream's chat replay scrolled in a column beside the footage, over the clips that ask for it.",
+ configKey: "render.chrome.chat",
+ defaults: CHAT_DEFAULTS,
+ validate: (v) => validateChat(v),
+ resolve: resolveChat,
+ ui: [
+ { key: "position", type: "enum", options: CHAT_POSITIONS, label: "Side", default: CHAT_DEFAULTS.position },
+ { key: "lines", type: "number", min: CHAT_LIMITS.lines[0], max: CHAT_LIMITS.lines[1], label: "Messages shown", default: CHAT_DEFAULTS.lines },
+ { key: "width", type: "number", min: CHAT_LIMITS.width[0], max: CHAT_LIMITS.width[1], label: "Width (px)", default: CHAT_DEFAULTS.width },
+ { key: "maxChars", type: "number", min: CHAT_LIMITS.maxChars[0], max: CHAT_LIMITS.maxChars[1], label: "Characters per message", default: CHAT_DEFAULTS.maxChars },
+ { key: "minGap", type: "number", min: CHAT_LIMITS.minGap[0], max: CHAT_LIMITS.minGap[1], step: 0.1, label: "Seconds between messages", default: CHAT_DEFAULTS.minGap },
+ ],
+ docs: {
+ heading: "Live chat",
+ intro: "A stream's chat replay (`live_chat.cues.json`, kept beside a live video's transcript) in a column down one side of the footage box, author and text, newest at the bottom, over the clips with `chat: true` (`render.chrome.chat`, chat.mjs). A clip shows the messages of its own SOURCE span, timed to the cut through its gaps (a message said inside a gap is not shown). A busy chat is thinned to one message per `minGap`; a long message is cut at `maxChars` and clamped to four lines. A clip whose video has no chat file draws nothing and the build log says so -- it never fails the build. The column overlays the footage's edge (it does not reflow the footage); it shares the footage box with the stats and the status ledger, so put them in other corners.",
+ rows: [
+ ["clip `chat`", "`on` · `off` · default off (a clip only)", "`umtool set <p> <clip> chat=on` (`chat=` clears it)"],
+ ["`chrome.chat.position`, `.width`", `\`right\` \`left\` · ${CHAT_LIMITS.width.join("–")} px · default \`right\`, ${CHAT_DEFAULTS.width}`, "`umtool look <p> chat.position=left`"],
+ ["`chrome.chat.lines`, `.maxChars`, `.minGap`", `${CHAT_LIMITS.lines.join("–")} messages · ${CHAT_LIMITS.maxChars.join("–")} characters · ${CHAT_LIMITS.minGap.join("–")} s · default ${CHAT_DEFAULTS.lines}, ${CHAT_DEFAULTS.maxChars}, ${CHAT_DEFAULTS.minGap}`, "`umtool look <p> chat='{\"lines\":8}'`"],
+ ],
+ },
+ region: "chat",
+ workers: "narrow",
+ noun: "the chat's",
+ on: (schedule) => !!schedule?.chat?.clips?.length,
+ check: (schedule) => (!schedule.chat?.clips?.length
+ ? "the chat region needs a schedule with a clip that asks for it (chat: true) and a live_chat.cues.json with messages in its span"
+ : null),
+ async page(ctx) {
+ const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ return chatHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration });
+ },
+ regions(schedule, { render, outDir, frames = null }) {
+ return [assertRegion({
+ name: "chat", frames: frames ?? path.join(outDir, "chrome", "chat-frames"),
+ ...chatGeometry(render, { feed: schedule.layout === "feed" }),
+ })];
+ },
+ // A cue interpreter: each state of the column an item, keyed only where it is shown.
+ frameKeys: { data: "chat-data", omit: ["init", "cues", "window", "total", "ids"] },
+});
diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs
@@ -29,13 +29,14 @@ import blur from "./blur.mjs";
import pair from "./pair.mjs";
import chapter from "./chapter.mjs";
import status from "./status.mjs";
+import chat from "./chat.mjs";
import sectionTitle from "./section-title.mjs";
export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, REGION_PLACEMENTS };
/** Every module, by z (stack order), then id. */
export const MODULES = Object.freeze(
- [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status]
+ [chart, shell, subtitle, qr, rail, sectionTitle, counter, claims, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser, intro, blur, pair, chapter, status, chat]
.sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)),
);
diff --git a/umtool/report-to-video/modules/rail.test.mjs b/umtool/report-to-video/modules/rail.test.mjs
@@ -47,5 +47,5 @@ test("rail settings: spacing, pitch, and the deck's other keys refused by name",
assert.equal(resolveDeck(render({})).pip.pitch, undefined, "no pitch unless set: the deck resolves as it did");
assert.equal(rail.resolve(render({ spacing: "pitch" })).pip.pitch, 28);
assert.equal(rail.validate, settingsOf("rail").validate);
- assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts"]);
+ assert.deepEqual(SETTINGS.map((s) => s.id), ["stamp", "threads", "flips", "stats", "fx", "chat", "pair", "chapter", "status", "finale", "claims", "counter", "shell", "rail", "section-title", "subtitle", "qr", "popup-posts"]);
});
diff --git a/umtool/report-to-video/modules/registry.test.mjs b/umtool/report-to-video/modules/registry.test.mjs
@@ -47,7 +47,7 @@ test("the registry: unique ids and regions, sorted by z, the deck's overlays in
assert.equal(new Set(ids).size, ids.length);
for (let i = 1; i < MODULES.length; i += 1) assert.ok(MODULES[i - 1].z <= MODULES[i].z);
// The order the build has always laid them in: the finale last.
- assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "stats", "pair", "status", "fx", "threads", "flips", "chapter", "finale"]);
+ assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "chat", "stats", "pair", "status", "fx", "threads", "flips", "chapter", "finale"]);
assert.equal(moduleOfRegion("deck").id, "shell");
assert.equal(regionModule("posts").id, "popup-posts");
assert.throws(() => regionModule("nope"), /unknown chrome region: nope/);
@@ -57,7 +57,7 @@ test("the registry: unique ids and regions, sorted by z, the deck's overlays in
});
test("placement and caching come from the module's kind", () => {
- for (const r of ["deck", "feed", "stamp", "stats", "fx", "threads", "flips"]) assert.equal(placementOf(r), "whole", r);
+ for (const r of ["deck", "feed", "stamp", "chat", "stats", "fx", "threads", "flips"]) assert.equal(placementOf(r), "whole", r);
for (const r of ["posts", "finale"]) assert.equal(placementOf(r), "window", r);
assert.equal(placementOf("chart"), null);
assert.equal(placementOf("teaser"), null);
@@ -154,3 +154,18 @@ test("play: a live-preview contract only an overlay with a page and regions decl
assert.deepEqual(playModules().map((m) => m.id), ["stats", "pair", "status", "fx", "threads", "flips", "chapter"]);
for (const m of playModules()) assert.equal(m.play.ready, `${m.region}:ready`, m.id);
});
+
+test("chat: a whole-cut overlay beside the footage, drawn only for a schedule that carries chat", () => {
+ const chat = moduleById("chat");
+ assert.equal(chat.kind, "overlay-whole");
+ assert.equal(chat.region, "chat");
+ assert.equal(moduleOfRegion("chat"), chat);
+ assert.equal(placementOf("chat"), "whole");
+ assert.deepEqual(regionCaching("chat"), { keyed: true, wholeCut: true });
+ assert.equal(chat.configKey, "render.chrome.chat");
+ assert.equal(chat.on({ chat: { clips: [{ segment: "a" }] } }), true);
+ assert.equal(chat.on({ segments: [] }), false);
+ const [r] = chat.regions({}, { render: RENDER, outDir: "/o" });
+ assert.deepEqual([r.name, r.frames], ["chat", "/o/chrome/chat-frames"]);
+ assert.ok(r.x > 1920 / 2 && r.width <= 640, "a strip at the footage box's right edge");
+});
diff --git a/umtool/report-to-video/modules/settings.mjs b/umtool/report-to-video/modules/settings.mjs
@@ -16,6 +16,7 @@ import { validateThreads } from "../threads.mjs";
import { validateFlips } from "../flips.mjs";
import { validateStats } from "../stats.mjs";
import { validateFx } from "../fx.mjs";
+import { validateChat } from "../chat.mjs";
import { validateChapter, validatePair, validateStatus } from "./story-settings.mjs";
import { MARKER_LEVELS, MARKER_LIMITS } from "../marker-limits.mjs";
@@ -455,6 +456,8 @@ export const SETTINGS = Object.freeze([
{ id: "flips", key: "flips", configKey: "render.chrome.flips", validate: (v) => validateFlips(v) },
{ id: "stats", key: "stats", configKey: "render.chrome.stats", validate: (v) => validateStats(v) },
{ id: "fx", key: "fx", configKey: "render.chrome.fx", validate: (v) => validateFx(v) },
+ // The live-chat column (chat.mjs).
+ { id: "chat", key: "chat", configKey: "render.chrome.chat", validate: (v) => validateChat(v) },
// The story modules (story-settings.mjs): then and now, the chapters, the status ledger.
{ id: "pair", key: "pair", configKey: "render.chrome.pair", validate: (v) => validatePair(v) },
{ id: "chapter", key: "chapter", configKey: "render.chrome.chapter", validate: (v) => validateChapter(v) },