commit e74358bd3f0d054cddf14fc25ce283aac41c381f
parent f3796b3c4ad879c278a888deda02076690a17b0c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 12:26:32 -0400
report-to-video: the look — render.captions (speaker captions), render.loudness, a clip's vertical crop, --short
look.mjs (pure): validateLook (captions / loudness / vertical, in the build's validators and the lint, like
validateTransitionStyle), captionLines (2-6 words a line, broken on pauses, never across a speaker change),
assDocument (a style per role: host amber left, subject sky right, other paper centre), cropPixels /
verticalFilters / shortRender. build-video: each cut levelled toward render.loudness.target at its encode
(measureLoudness, now exported, + montage.mjs loudnessGain/levelFilters); an ASS file per segment from the
project's words.json + reactions.json turns, burned with ass=; --short <id> renders that clip alone at
1080x1920 from its crop into <project>/shorts/<id>.mp4 (+ a record), in the heavy slot. Absent keys:
byte-identical (md5 vs main on a two-clip fadeblack fixture). look.test.mjs: 15 tests incl. real renders
(caption frame and colour by pixel, loudness within 0.5 LU, the short's size and crop).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
5 files changed, 1016 insertions(+), 10 deletions(-)
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"
}