commit 796eecebe9c1ab91f6b5aa78695c26d3ae1210fc
parent ce730189ca56b8931abcdddfb3893ce28a2cc4ff
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 17 Oct 2026 17:07:44 -0400
umtool: report-to-video render.montage — tight phrase cuts, cut styles, counters, punch-in, stutter, ramp, wall, year stamps
All opt-in under render.montage (montage.mjs, pure; build-video runs it only when set): tighten "phrase"
finds the phrase in its cues by character position (whisper token offsets in transcript.json first, when the
corpus keeps them) and cuts it ± phrasePad inside the extent, snapped to silence outside the phrase; the cut
styles (flash, whip, dip) are each segment's own first and last frames, so the concat stays a stream copy of
hard cuts and a segment's length is known to the frame; a 15 ms de-click on every segment edge; counter
chip/big/tally and the year stamp are drawtext/drawbox over the frame; punch snap/drift, stutter (the phrase's
end heard 2-4 times, a zoom step each) and the ramp (cut k <= lerp(from, to, k/(N-1))) are the segment's
pieces; the wall is one more segment of 9/16/25 tiles filling in, the newest up and the rest ducked, then all
together. validateMontage in the build's validators and the lint (unknown keys, bad values, the deck, the
rail, muteFrom). A manifest without render.montage renders byte for byte as before. 32 tests, real renders of
each style over lavfi clips.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 1966 insertions(+), 13 deletions(-)
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -174,6 +174,15 @@ import {
// as it did -- see brand.mjs.
import { 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.
+// Every hook below runs only when render.montage is set.
+import {
+ clipPhrase, cutStyleParts, locatePhrase, montageFont, montageOn, montageOverlayFilters, montagePieces,
+ montagePiecesGraph, montageWindow, planMontage, resolveMontage, validateMontage, wallComposeArgs, WALL_ENTRY,
+ wallPlan, wallTileArgs, wallTileClips, whisperWords,
+} from "./montage.mjs";
+import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
const execFileP = promisify(execFile);
@@ -1131,11 +1140,15 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
const win = render.snapWindow ?? 1.6;
const sil = await detectSilence(raw, render, scan);
- const a = snap(wantA, sil, "start", win, render);
- const b = snap(wantB, sil, "end", win, render);
+ // A montage cuts to the phrase (montageCut); every other clip as it always was.
+ const mont = dirs.montage
+ ? await montageCut({ entry, M: dirs.montage, render, provenance, fetchStart, sil, wantA, wantB, win, raw })
+ : null;
+ const a = mont ? mont.win.start : snap(wantA, sil, "start", win, render);
+ const b = mont ? mont.win.end : snap(wantB, sil, "end", win, render);
// Never let snapping invert or collapse the window.
- const cutA = Math.min(a.at, wantB - 1);
- const cutB = Math.max(b.at, cutA + 1);
+ const cutA = mont ? mont.win.cutA : Math.min(a.at, wantB - 1);
+ const cutB = mont ? mont.win.cutB : Math.max(b.at, cutA + 1);
EMIT("snap", { id: entry.id, start: a.snapped, end: b.snapped, seconds: cutB - cutA });
// Where in the SOURCE this segment really starts and ends, snapped: what a
// `muteFrom` (source seconds) is measured from at the join, long after this
@@ -1303,18 +1316,26 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
nextIdx += 1;
inputs.push(...pst.input);
}
- const pic = pst ? "[pic]" : "[0:v]";
+ // A montage's pieces come first: the picture and the sound of the cut,
+ // re-timed (a stutter), zoomed (a punch-in) and fitted to the box, which the
+ // framing below then leaves as it is. Its sound replaces `0:a`; a poster
+ // shares it through an asplit.
+ const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB }) : null;
+ 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 : []);
const parts = hasFooter
? [
- ...(pst ? pst.parts : []),
+ ...lead,
`${pic}${base}[b]`,
`[b][${footerIdx}:v]overlay=0:${height - FH}[f]`,
`[${barIdx}:v]crop=w=${chrome.trackLen}:h=3:x='${chrome.trackLen}-(${fillExpr})':y=0[bar]`,
`[f][bar]overlay=x=${chrome.x0}:y=${trackAbsY - 1}[g]`,
`[g][${markerIdx}:v]overlay=x=${markX}:y=${trackAbsY - chrome.markerRadius}[q]`,
]
- : [...(pst ? pst.parts : []), `${pic}${base}[q]`];
+ : [...lead, `${pic}${base}[q]`];
let q = "q";
if (brandMark) {
@@ -1327,6 +1348,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
? `[${q}][${qrIdx}:v]overlay=x=${VW}-w-${qrM}:y=H-h-${FH + qrM}[v]`
: `[${q}]null[v]`,
);
+ // A montage's cut style and its counter, over the finished frame.
+ if (mg) parts.push(...mg.post("[v]", "[vm]"));
await execFileP(
FFMPEG,
@@ -1334,13 +1357,183 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
"-nostdin", "-v", "error", "-y",
...inputs,
"-filter_complex", parts.join(";"),
- "-map", "[v]", "-map", "0:a",
+ "-map", mg ? "[vm]" : "[v]", "-map", mg ? mg.a : "0:a",
...encodeArgs(render),
seg,
],
{ maxBuffer: 1 << 24 },
);
- await writeCutRecord(seg, cutRecord);
+ await writeCutRecord(seg, mont ? { ...cutRecord, montage: mg.record } : cutRecord);
+ if (mont) {
+ dirs.montage.cuts.set(entry.id, {
+ raw, cutA, cutB, phrase: mont.phrase, year: mont.ctx.year, hasVideo: media.hasVideo,
+ });
+ }
+ return seg;
+}
+
+// ---- 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.
+
+/**
+ * A corpus video's whisper words (transcript.json's token offsets), when the
+ * corpus is on disk and keeps them; null otherwise. Read once per video.
+ */
+async function montageWords(entry, provenance, M) {
+ if (hasLocalMedia(entry) || !M.channelsDir) return null;
+ const slug = entry.channel ?? provenance?.channelSlug;
+ if (!slug || !entry.video) return null;
+ const key = `${slug}/${entry.video}`;
+ if (!M.words.has(key)) {
+ M.words.set(key, (async () => {
+ try {
+ const dir = await resolveVideoDir(M.channelsDir, slug, entry.video);
+ const doc = JSON.parse(await readFile(path.join(dir, "transcript.json"), "utf8"));
+ return whisperWords(doc);
+ } catch {
+ return null;
+ }
+ })());
+ }
+ return M.words.get(key);
+}
+
+/** A clip's cues, wherever they live; [] when none can be read. */
+async function montageCues(entry, provenance) {
+ try {
+ if (hasLocalMedia(entry)) return LOCAL ? await LOCAL.cues(entry) : [];
+ const d = await CUES.load(entry.channel ?? provenance?.channelSlug, entry.video, {
+ siteChannel: entry.siteChannel, siteVideo: entry.siteVideo,
+ });
+ return Array.isArray(d?.cues) ? d.cues : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Where a montage clip is cut, on the fetched file's clock: its phrase found
+ * (whisper's words first, then the cues), then montageWindow. A phrase that
+ * cannot be found is said, and the clip keeps today's cut; its cut window
+ * (`cutStart`/`cutEnd`, else the extent) stands in for the phrase where a
+ * punch-in or a stutter needs one.
+ */
+async function montageCut({ entry, M, render, provenance, fetchStart, sil, wantA, wantB, win }) {
+ const s = M.settings;
+ const ctx = M.ctx.get(entry.id) ?? { k: 0, n: 1, cap: null, stutter: false, date: null, year: null, yearChange: false, platform: null, first: false, last: false };
+ const text = clipPhrase(entry);
+ const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd);
+ let found = null;
+ let via = null;
+ if (text && (s.tighten === "phrase" || s.punch?.mode === "snap" || ctx.stutter)) {
+ const near = hasCut ? (entry.cutStart + entry.cutEnd) / 2 : entry.cite ?? (entry.start + entry.end) / 2;
+ const span = { from: entry.start, to: entry.end, near };
+ const words = await montageWords(entry, provenance, M);
+ found = words ? locatePhrase(text, words, span) : null;
+ if (found) via = "words";
+ else {
+ found = locatePhrase(text, await montageCues(entry, provenance), span);
+ if (found) via = "cues";
+ }
+ if (!found) EMIT("note", { message: `${entry.id}: montage: "${text}" is not in its cues — today's cut is kept` });
+ }
+ const at = found ?? (hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end });
+ const phrase = { start: at.start - fetchStart, end: at.end - fetchStart };
+ const w = montageWindow({
+ extent: [entry.start - fetchStart, entry.end - fetchStart], play: [wantA, wantB],
+ phrase: found ? phrase : null, tighten: s.tighten, pad: s.phrasePad, cap: ctx.cap,
+ silences: sil, snapWindow: win, render, snap,
+ });
+ return { win: w, phrase, via, ctx, settings: s, source: { start: at.start, end: at.end } };
+}
+
+/**
+ * One montage segment's graph: the pieces (montagePiecesGraph) from the raw
+ * cut to `mg.v` / `mg.a`, and `post(in, out)` -- the cut style and the
+ * counter over the finished frame. `record` goes in the cut record.
+ */
+function montageSegmentGraph({ mont, render, box, hasVideo, cutA, cutB }) {
+ const { settings: s, ctx } = mont;
+ const fps = render.fps;
+ const frames = Math.max(1, Math.floor((cutB - cutA) * fps + 1e-6));
+ const pieces = montagePieces({
+ frames, fps,
+ onset: mont.phrase.start - cutA, phraseEnd: mont.phrase.end - cutA,
+ punch: hasVideo ? s.punch : null,
+ stutter: hasVideo && ctx.stutter ? s.stutter : null,
+ });
+ const g = montagePiecesGraph({
+ pieces, fps, box, bg: render.palette.bg, punch: hasVideo ? s.punch : null,
+ inA: hasVideo ? "[0:a]" : "[mpa]", hasVideo,
+ });
+ const overlays = montageOverlayFilters({ settings: s, ctx, render, font: montageFont(render) });
+ return {
+ parts: g.parts, v: g.v, a: g.a,
+ post: (inLabel, outLabel) => {
+ const mid = overlays.length ? "[mvx]" : outLabel;
+ return [
+ ...cutStyleParts({
+ cut: s.cut, first: ctx.first, last: ctx.last, frames: g.frames, fps, w: render.width, h: render.height,
+ flashColor: s.flashColor, inLabel, outLabel: mid,
+ }),
+ ...(overlays.length ? [`[mvx]${overlays.join(",")}${outLabel}`] : []),
+ ];
+ },
+ record: {
+ phrase: [Number(mont.source.start.toFixed(3)), Number(mont.source.end.toFixed(3))],
+ found: mont.via, tight: mont.win.tight, frames: g.frames, seconds: Number(g.seconds.toFixed(4)),
+ pieces,
+ },
+ };
+}
+
+/**
+ * The montage's wall (`render.montage.wall`): its tiles cut from the clips
+ * just built (montageCuts), each a small file in segments/montage-wall/, then
+ * composed into one segment. Returns its path.
+ */
+async function buildMontageWall({ M, entries, render, outDir }) {
+ const s = M.settings;
+ const ids = entries.filter((e) => e.type === "clip" && M.cuts.has(e.id) && M.cuts.get(e.id).hasVideo).map((e) => e.id);
+ if (!ids.length) throw new Error("render.montage.wall: no clip with a picture was built, so there is nothing to tile");
+ const chosen = wallTileClips(ids, s.wall.tiles);
+ const tiles = chosen.map((id) => {
+ const c = M.cuts.get(id);
+ let from = Math.max(c.cutA, c.phrase.start - 0.12);
+ let to = Math.min(c.cutB, c.phrase.end + 0.25);
+ if (to - from < 0.4) [from, to] = [c.cutA, c.cutB];
+ return { id, raw: c.raw, from, to, year: s.wall.year ? c.year : null };
+ });
+ const plan = wallPlan({
+ tiles: tiles.length, build: s.wall.build, durations: tiles.map((t) => t.to - t.from),
+ fps: render.fps, width: render.width, height: render.height,
+ });
+ const dir = path.join(outDir, "segments", "montage-wall");
+ await rm(dir, { recursive: true, force: true });
+ await mkdir(dir, { recursive: true });
+ const made = new Map();
+ const files = [];
+ for (const t of tiles) {
+ if (!made.has(t.id)) {
+ const file = path.join(dir, `${t.id}.mp4`);
+ await execFileP(FFMPEG, wallTileArgs({
+ raw: t.raw, from: t.from, to: t.to, tileW: plan.tileW, tileH: plan.tileH, fps: render.fps,
+ year: t.year, font: montageFont(render), render, encode: encodeArgs(render), outPath: file,
+ }), { maxBuffer: 1 << 24 });
+ made.set(t.id, file);
+ }
+ files.push({ file: made.get(t.id), seconds: t.to - t.from });
+ }
+ await detachSegmentFiles(path.join(outDir, "segments"), WALL_ENTRY.id);
+ const seg = path.join(outDir, "segments", `${WALL_ENTRY.id}.mp4`);
+ await execFileP(FFMPEG, wallComposeArgs({
+ tiles: files, plan, render, settings: s,
+ first: s.wall.at === "start", last: s.wall.at === "end", encode: encodeArgs(render), outPath: seg,
+ }), { maxBuffer: 1 << 26 });
+ await writeCutRecord(seg, {
+ version: 1, id: WALL_ENTRY.id, montageWall: { tiles: chosen, frames: plan.frames, seconds: plan.seconds, appear: plan.appear, beat: plan.beat },
+ });
return seg;
}
@@ -4211,7 +4404,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const errors = [
...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole),
...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
- ...validateStatsEntries(whole),
+ ...validateStatsEntries(whole), ...validateMontage(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -4446,7 +4639,29 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const segments = [];
const failures = [];
- const D = opts.noXfade || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5;
+ // A montage makes its cuts inside its segments (montage.mjs), so they are
+ // joined hard, whatever `transition` says.
+ const montage = montageOn(render);
+ if (montage && (render.transition ?? 0.5) !== 0 && !opts.noXfade && !only) {
+ EMIT("note", { message: "render.montage: the cut styles are in the segments, so they are joined with hard cuts (render.transition is not used)" });
+ }
+ const D = opts.noXfade || montage || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5;
+ // The montage's plan across the WHOLE cut (a clip's place, its year, its
+ // ramp cap), so an `--only` rebuild cuts a clip as the full build would.
+ // A clip with no date of its own takes its record's upload date.
+ if (montage) {
+ const settings = resolveMontage(render);
+ const dates = new Map();
+ for (const e of manifest.timeline) {
+ if (e?.type !== "clip" || e.montage?.date || e.date) continue;
+ const meta = await clipMeta(e, provenance).catch(() => null);
+ if (meta?.uploadDate) dates.set(e.id, meta.uploadDate);
+ }
+ dirs.montage = {
+ settings, ctx: planMontage(manifest.timeline, settings, (e) => dates.get(e.id) ?? null),
+ cuts: new Map(), words: new Map(), channelsDir,
+ };
+ }
// One entry's segment, by its kind: the build's loop below, `--only`, and a
// segment `--chrome-only` finds MISSING (with `o` = skipFetch). Before an
@@ -4531,6 +4746,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// per-clip segments are still on disk, which is all the offsets need.
if (opts.chaptersOnly) {
const finalPath = dirs.final;
+ // A montage's wall is a segment of the cut too.
+ if (dirs.montage?.settings.wall) {
+ if (dirs.montage.settings.wall.at === "start") entries.unshift({ ...WALL_ENTRY });
+ else entries.push({ ...WALL_ENTRY });
+ }
const segs = entries.map((e) => path.join(outDir, "segments", `${e.id}.mp4`));
for (const seg of segs) {
if (!(await exists(seg)))
@@ -4713,6 +4933,22 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
return { out: segments[0], failures };
}
+ // The montage's wall, from the clips just cut: one more segment, at the
+ // end (or the start) of the cut, named in the chapters like any entry.
+ if (dirs.montage?.settings.wall && !failures.length) {
+ const at = dirs.montage.settings.wall.at;
+ EMIT("card", { id: WALL_ENTRY.id, i: at === "start" ? 0 : entries.length, n: entries.length + 1 });
+ const seg = await buildMontageWall({ M: dirs.montage, entries, render, outDir });
+ EMIT("segment", { id: WALL_ENTRY.id, path: seg });
+ if (at === "start") {
+ segments.unshift(seg);
+ entries.unshift({ ...WALL_ENTRY });
+ } else {
+ segments.push(seg);
+ entries.push({ ...WALL_ENTRY });
+ }
+ }
+
// A timeline that silently lost a clip is a worse outcome than no file at all:
// the finished video would look complete and be missing a citation. So the
// segments are kept (they cost the fetches) and the concat is refused.
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -20,8 +20,8 @@
// - a QR below MIN_QR_PX_PER_MODULE_720P pixels per module once the cut is
// watched at 720p, or a link too long for a QR at all;
// - everything the manifest validators say -- validateThreadEntries,
-// validateFlipEntries and validateStatsEntries (threads.mjs, flips.mjs,
-// stats.mjs), validateNarration
+// validateFlipEntries, validateStatsEntries and validateMontage (threads.mjs,
+// flips.mjs, stats.mjs, montage.mjs), validateNarration
// (narration.mjs), validatePodcast (build-podcast.mjs), and the cut edits, teasers, claims and posts validators
// a build runs first -- so `--lint` alone reports what a build would
// refuse, all at once;
@@ -84,6 +84,7 @@ import { validateClaims } from "./factcheck.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
+import { validateMontage } from "./montage.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
@@ -228,6 +229,8 @@ export function validatorErrors(whole) {
...validateDrafted(whole), ...validatePublish(whole),
// Release 31: the stats region's `stats` keys and render.chrome.stats.
...validateStatsEntries(whole),
+ // Release 33: render.montage, its keys and what it does not combine with.
+ ...validateMontage(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/montage.mjs b/umtool/report-to-video/montage.mjs
@@ -0,0 +1,959 @@
+// MONTAGE EDITING — `render.montage` (release 33 M3).
+//
+// A montage is one phrase said many times: dozens of short clips, cut tight,
+// run in order. Everything here is opt-in under `render.montage`; a manifest
+// without it renders exactly as before (build-video.mjs never reaches this
+// module's graph builders).
+//
+// WHERE EACH FEATURE LIVES. Every technique is made inside the clip's own
+// segment encode, which the build pays for anyway: the tight cut moves the
+// trim points, the punch-in, stutter and drift are the picture's pieces, the
+// counter and the year stamp are drawtext/drawbox over the finished frame,
+// and the cut styles (flash, whip, dip) are the first and last frames of
+// each segment -- each segment knows whether it opens or closes the cut. So
+// the concat stays the stream copy of hard cuts, no chrome layer is rendered,
+// and a segment's length is known to the frame before it is encoded. The one
+// composited pass is the wall: its own segment, made from small tiles.
+//
+// tighten "phrase" | "sentence" | null cut each clip to the phrase said ± phrasePad
+// phrasePad seconds (0.6) kept either side of the phrase
+// cut "hard" | "flash" | "whip" | "dip"
+// flashColor "white" | "accent" | "#rrggbb"
+// counter { style: chip|big|tally, position, of, showDate, showSource } | null
+// punch { mode: snap|drift, scale, anchor: upper|center } | null
+// stutter { every?, clips?, times: 2..4, length: 0.35, step: 0.04 } | null
+// ramp { from, to } seconds -- clip k's cut <= lerp(from, to, k/(N-1))
+// wall { at: end|start, tiles: 9|16|25, build: seconds, year } | null
+// yearStamp true: the year, large, over the first clip of each year
+//
+// Pure functions only, but for nothing: the build (build-video.mjs) runs the
+// ffmpeg argv these return. README "Manifest shape", `render.montage`.
+
+import { deckOn } from "./deck.mjs";
+import { MONO_BOLD_FONT_FILE } from "./brand.mjs";
+
+// ---- the settings -----------------------------------------------------------
+
+export const MONTAGE_KEYS = Object.freeze([
+ "tighten", "phrasePad", "cut", "flashColor", "counter", "punch", "stutter", "ramp", "wall", "yearStamp",
+]);
+export const TIGHTEN = Object.freeze(["phrase", "sentence"]);
+export const CUTS = Object.freeze(["hard", "flash", "whip", "dip"]);
+export const COUNTER_STYLES = Object.freeze(["chip", "big", "tally"]);
+export const POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]);
+export const PUNCH_MODES = Object.freeze(["snap", "drift"]);
+export const ANCHORS = Object.freeze(["upper", "center"]);
+export const WALL_TILES = Object.freeze([9, 16, 25]);
+const COUNTER_KEYS = ["style", "position", "of", "showDate", "showSource"];
+const PUNCH_KEYS = ["mode", "scale", "anchor"];
+const STUTTER_KEYS = ["every", "clips", "times", "length", "step"];
+const RAMP_KEYS = ["from", "to"];
+const WALL_KEYS = ["at", "tiles", "build", "year"];
+
+export const MONTAGE_DEFAULTS = Object.freeze({
+ phrasePad: 0.6,
+ punchScale: { snap: 1.15, drift: 1.08 },
+ stutter: { times: 3, length: 0.35, step: 0.04 },
+ wall: { at: "end", tiles: 16, build: 6, year: false },
+});
+
+/** The frames of each cut style (a whip's are each side of the cut). */
+export const CUT_FRAMES = Object.freeze({ flash: 3, whip: 4, dip: 2 });
+/** Each segment's sound starts and ends on a fade this long: no click at a hard cut. */
+export const DECLICK = 0.015;
+/** A stutter's own pieces fade this much at each joint. */
+const JOINT_FADE = 0.005;
+
+/** Is `render.montage` on? (An object; null or absent is off.) */
+export const montageOn = (render) =>
+ render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage);
+
+const isObj = (v) => v != null && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+
+/**
+ * `render.montage` with every default filled in, or null when it is off.
+ * Assumes validateMontage passed; `palette` resolves an accent flash.
+ */
+export function resolveMontage(render) {
+ if (!montageOn(render)) return null;
+ const m = render.montage;
+ const pal = render.palette ?? {};
+ const flash = m.flashColor == null || m.flashColor === "white" ? "#ffffff" : m.flashColor === "accent" ? pal.accent ?? "#ffffff" : m.flashColor;
+ const counter = isObj(m.counter)
+ ? {
+ style: m.counter.style ?? "chip",
+ position: m.counter.position ?? "top-left",
+ of: m.counter.of === true,
+ showDate: m.counter.showDate !== false,
+ showSource: m.counter.showSource === true,
+ }
+ : null;
+ const punch = isObj(m.punch)
+ ? {
+ mode: m.punch.mode,
+ scale: m.punch.scale ?? MONTAGE_DEFAULTS.punchScale[m.punch.mode],
+ anchor: m.punch.anchor ?? "upper",
+ }
+ : null;
+ const stutter = isObj(m.stutter)
+ ? {
+ every: m.stutter.every ?? null,
+ clips: Array.isArray(m.stutter.clips) ? [...m.stutter.clips] : [],
+ times: m.stutter.times ?? MONTAGE_DEFAULTS.stutter.times,
+ length: m.stutter.length ?? MONTAGE_DEFAULTS.stutter.length,
+ step: m.stutter.step ?? MONTAGE_DEFAULTS.stutter.step,
+ }
+ : null;
+ const wall = isObj(m.wall) ? { ...MONTAGE_DEFAULTS.wall, ...pick(m.wall, WALL_KEYS) } : null;
+ return {
+ tighten: m.tighten ?? null,
+ phrasePad: m.phrasePad ?? MONTAGE_DEFAULTS.phrasePad,
+ cut: m.cut ?? "hard",
+ flashColor: flash,
+ counter,
+ punch,
+ stutter,
+ ramp: isObj(m.ramp) ? { from: m.ramp.from, to: m.ramp.to } : null,
+ wall: wall ? { ...wall, year: wall.year === true } : null,
+ yearStamp: m.yearStamp === true,
+ };
+}
+
+function pick(o, keys) {
+ const out = {};
+ for (const k of keys) if (o[k] !== undefined && o[k] !== null) out[k] = o[k];
+ return out;
+}
+
+function unknownKeys(obj, keys, where) {
+ return Object.keys(obj)
+ .filter((k) => !keys.includes(k))
+ .map((k) => `${where}.${k} is not a setting here (the settings are ${keys.join(", ")})`);
+}
+
+const oneOf = (v, list, where) =>
+ list.includes(v) ? [] : [`${where} must be ${list.map((x) => JSON.stringify(x)).join(" or ")}, not ${JSON.stringify(v)}`];
+
+const inRange = (v, lo, hi, where, unit = "") =>
+ num(v) && v >= lo && v <= hi ? [] : [`${where} must be a number from ${lo} to ${hi}${unit}, not ${JSON.stringify(v)}`];
+
+const bool = (v, where) => (v === undefined || v === null || typeof v === "boolean" ? [] : [`${where} must be true or false, not ${JSON.stringify(v)}`]);
+
+/**
+ * What is wrong with a manifest's `render.montage`, as sentences that say so.
+ * Nothing when it is absent or null. Unknown keys and bad values are errors;
+ * so is a montage beside what it does not combine with (the deck, the rail,
+ * the chart band, a clip's `muteFrom`).
+ */
+export function validateMontage(manifest) {
+ const render = manifest?.render ?? {};
+ const m = render.montage;
+ if (m === undefined || m === null) return [];
+ if (!isObj(m)) return [`render.montage must be an object of montage settings, not ${JSON.stringify(m)}`];
+ const errors = [...unknownKeys(m, MONTAGE_KEYS, "render.montage")];
+ const W = "render.montage";
+ if (m.tighten != null) errors.push(...oneOf(m.tighten, TIGHTEN, `${W}.tighten`));
+ if (m.phrasePad != null) errors.push(...inRange(m.phrasePad, 0, 5, `${W}.phrasePad`, " seconds"));
+ if (m.cut != null) errors.push(...oneOf(m.cut, CUTS, `${W}.cut`));
+ if (m.flashColor != null && m.flashColor !== "white" && m.flashColor !== "accent" && !/^#[0-9a-fA-F]{6}$/.test(String(m.flashColor))) {
+ errors.push(`${W}.flashColor must be "white", "accent" or a #rrggbb colour, not ${JSON.stringify(m.flashColor)}`);
+ }
+ if (m.counter != null) {
+ if (!isObj(m.counter)) errors.push(`${W}.counter must be an object ({ style, position, of, showDate, showSource }) or null`);
+ else {
+ errors.push(...unknownKeys(m.counter, COUNTER_KEYS, `${W}.counter`));
+ if (m.counter.style != null) errors.push(...oneOf(m.counter.style, COUNTER_STYLES, `${W}.counter.style`));
+ if (m.counter.position != null) errors.push(...oneOf(m.counter.position, POSITIONS, `${W}.counter.position`));
+ for (const k of ["of", "showDate", "showSource"]) errors.push(...bool(m.counter[k], `${W}.counter.${k}`));
+ }
+ }
+ if (m.punch != null) {
+ if (!isObj(m.punch)) errors.push(`${W}.punch must be an object ({ mode, scale, anchor }) or null`);
+ else {
+ errors.push(...unknownKeys(m.punch, PUNCH_KEYS, `${W}.punch`));
+ errors.push(...oneOf(m.punch.mode, PUNCH_MODES, `${W}.punch.mode`));
+ if (m.punch.scale != null) errors.push(...inRange(m.punch.scale, 1, 2, `${W}.punch.scale`, " (1 is no zoom)"));
+ if (m.punch.anchor != null) errors.push(...oneOf(m.punch.anchor, ANCHORS, `${W}.punch.anchor`));
+ }
+ }
+ if (m.stutter != null) {
+ if (!isObj(m.stutter)) errors.push(`${W}.stutter must be an object ({ every, clips, times, length, step }) or null`);
+ else {
+ const s = m.stutter;
+ errors.push(...unknownKeys(s, STUTTER_KEYS, `${W}.stutter`));
+ if (s.every == null && s.clips == null) errors.push(`${W}.stutter needs \`every\` (every Nth clip) or \`clips\` (their ids)`);
+ if (s.every != null && !(Number.isInteger(s.every) && s.every >= 1)) {
+ errors.push(`${W}.stutter.every must be a whole number from 1 (every clip), not ${JSON.stringify(s.every)}`);
+ }
+ if (s.clips != null) {
+ if (!Array.isArray(s.clips) || !s.clips.every((c) => typeof c === "string" && c)) {
+ errors.push(`${W}.stutter.clips must be a list of clip ids`);
+ } else {
+ const clipIds = new Set((manifest.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id));
+ for (const id of s.clips) if (!clipIds.has(id)) errors.push(`${W}.stutter.clips names "${id}", which is not a clip in the timeline`);
+ }
+ }
+ if (s.times != null && !(Number.isInteger(s.times) && s.times >= 2 && s.times <= 4)) {
+ errors.push(`${W}.stutter.times must be 2, 3 or 4 (how many times the end of the phrase is heard), not ${JSON.stringify(s.times)}`);
+ }
+ if (s.length != null) errors.push(...inRange(s.length, 0.1, 1, `${W}.stutter.length`, " seconds"));
+ if (s.step != null) errors.push(...inRange(s.step, 0, 0.2, `${W}.stutter.step`, " (the zoom added per repeat)"));
+ }
+ }
+ if (m.ramp != null) {
+ if (!isObj(m.ramp)) errors.push(`${W}.ramp must be an object ({ from, to } in seconds) or null`);
+ else {
+ errors.push(...unknownKeys(m.ramp, RAMP_KEYS, `${W}.ramp`));
+ errors.push(...inRange(m.ramp.from, 0.5, 60, `${W}.ramp.from`, " seconds"));
+ errors.push(...inRange(m.ramp.to, 0.5, 60, `${W}.ramp.to`, " seconds"));
+ if (m.tighten !== "phrase") errors.push(`${W}.ramp trims around the phrase, so it needs ${W}.tighten "phrase"`);
+ }
+ }
+ if (m.wall != null) {
+ if (!isObj(m.wall)) errors.push(`${W}.wall must be an object ({ at, tiles, build, year }) or null`);
+ else {
+ errors.push(...unknownKeys(m.wall, WALL_KEYS, `${W}.wall`));
+ if (m.wall.at != null) errors.push(...oneOf(m.wall.at, ["end", "start"], `${W}.wall.at`));
+ if (m.wall.tiles != null) errors.push(...oneOf(m.wall.tiles, WALL_TILES, `${W}.wall.tiles`));
+ if (m.wall.build != null) errors.push(...inRange(m.wall.build, 1, 60, `${W}.wall.build`, " seconds"));
+ errors.push(...bool(m.wall.year, `${W}.wall.year`));
+ }
+ }
+ errors.push(...bool(m.yearStamp, `${W}.yearStamp`));
+ // What a montage does not combine with.
+ if (deckOn(render)) errors.push(`${W} does not combine with render.chrome (the deck): drop one of them`);
+ if (render.rail) errors.push(`${W} does not combine with render.rail: drop one of them`);
+ if (render.chromeEngine === "hyperframes") errors.push(`${W} does not combine with render.chromeEngine "hyperframes"`);
+ (manifest.timeline ?? []).forEach((e, i) => {
+ if (e?.type === "clip" && e.muteFrom != null) {
+ errors.push(`timeline[${i}] (${e.id}).muteFrom is not supported under ${W}: cut the clip shorter instead`);
+ }
+ });
+ return errors;
+}
+
+// ---- dates, sources, the counter's words ------------------------------------
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+/** "20190502", "2019-05-02" (or a longer ISO stamp) → {y, m, d}; anything else → null. */
+export function parseClipDate(v) {
+ const s = String(v ?? "").trim();
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(s);
+ if (!m) return null;
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
+ if (mo < 1 || mo > 12 || d < 1 || d > 31) return null;
+ return { y, m: mo, d };
+}
+
+/** {y, m, d} → "2 May 2019". */
+export const formatClipDate = (dt) => (dt ? `${dt.d} ${MONTHS[dt.m - 1]} ${dt.y}` : "");
+
+const PLATFORMS = {
+ youtube: "YouTube", rumble: "Rumble", twitch: "Twitch", kick: "Kick", odysee: "Odysee", x: "X", twitter: "X",
+ bitchute: "BitChute", "archive.org": "archive.org", archiveorg: "archive.org", internetarchive: "archive.org",
+ podcast: "Podcast", tiktok: "TikTok", instagram: "Instagram", facebook: "Facebook", bluesky: "Bluesky",
+};
+
+/** A platform id as people write it: "youtube" → "YouTube"; unknown → itself, capitalised. */
+export function platformLabel(p) {
+ const s = String(p ?? "").trim();
+ if (!s) return "";
+ return PLATFORMS[s.toLowerCase()] ?? s[0].toUpperCase() + s.slice(1);
+}
+
+/**
+ * Text safe to put in a drawtext `text='…'`: letters, digits, spaces and
+ * `# · . / -` only, so nothing needs escaping through two parsers.
+ */
+export const safeText = (s) => String(s ?? "").replace(/[^\p{L}\p{N} #·./-]/gu, "").replace(/\s+/g, " ").trim();
+
+/**
+ * The counter's words for one clip: `number` ("#12", "#12 of 75") and `line`
+ * (the date and the source the counter shows, joined), each already safeText.
+ */
+export function counterText({ n, of = null, date = null, platform = null, showDate = true, showSource = false }) {
+ const number = `#${n}${of ? ` of ${of}` : ""}`;
+ const line = [showDate ? formatClipDate(date) : "", showSource ? platformLabel(platform) : ""].filter(Boolean).join(" · ");
+ return { number: safeText(number), line: safeText(line) };
+}
+
+// ---- where the phrase is said -------------------------------------------------
+
+const normChar = (ch) => (/[\p{L}\p{N}]/u.test(ch) ? ch.toLowerCase() : ch === "'" || ch === "’" ? "" : " ");
+
+/** A phrase as it is matched: lower case, letters and digits, single spaces. */
+export const normalisePhrase = (p) => [...String(p ?? "")].map(normChar).join("").replace(/\s+/g, " ").trim();
+
+/**
+ * Timed text: the spans' words (cues, or whisper's words) joined, each kept
+ * character carrying the seconds it is spoken -- a span's characters spread
+ * evenly over the span, so a long word takes longer than a short one.
+ *
+ * @param {Array<{start: number, end: number, text: string}>} spans sorted by start
+ * @returns {{ text: string, t0: number[], t1: number[] }}
+ */
+export function timedText(spans) {
+ let text = "";
+ const t0 = [];
+ const t1 = [];
+ const push = (c, a, b) => {
+ if (c === " " && (text === "" || text.endsWith(" "))) return;
+ text += c;
+ t0.push(a);
+ t1.push(b);
+ };
+ for (const s of spans) {
+ const chars = [...String(s.text ?? "")];
+ const L = chars.length;
+ const dur = Math.max(0, s.end - s.start);
+ chars.forEach((ch, i) => {
+ const c = normChar(ch);
+ if (c) push(c, s.start + (dur * i) / L, s.start + (dur * (i + 1)) / L);
+ });
+ push(" ", s.end, s.end);
+ }
+ return { text, t0, t1 };
+}
+
+/**
+ * Where a phrase is said: its first character's start and its last
+ * character's end, in the spans' seconds -- the occurrence that overlaps
+ * [from, to] nearest `near` (whole words first, then a phrase that runs on
+ * into a longer word: "slow news days"). Null when it is not there.
+ */
+export function locatePhrase(phrase, spans, { from = -Infinity, to = Infinity, near = null } = {}) {
+ const needle = normalisePhrase(phrase);
+ if (!needle) return null;
+ const used = (spans ?? [])
+ .filter((s) => num(s?.start) && num(s?.end) && s.end >= from - 0.5 && s.start <= to + 0.5)
+ .sort((a, b) => a.start - b.start);
+ if (!used.length) return null;
+ const tt = timedText(used);
+ const at = num(near) ? near : (Math.max(from, used[0].start) + Math.min(to, used[used.length - 1].end)) / 2;
+ for (const tail of [true, false]) {
+ let best = null;
+ for (let i = tt.text.indexOf(needle); i >= 0; i = tt.text.indexOf(needle, i + 1)) {
+ const before = i === 0 || tt.text[i - 1] === " ";
+ const j = i + needle.length;
+ const after = j >= tt.text.length || tt.text[j] === " ";
+ if (!before || (tail && !after)) continue;
+ const start = tt.t0[i];
+ const end = tt.t1[j - 1];
+ if (end < from || start > to) continue;
+ const d = Math.abs((start + end) / 2 - at);
+ if (!best || d < best.d) best = { d, start, end };
+ }
+ if (best) return { start: best.start, end: best.end };
+ }
+ return null;
+}
+
+/**
+ * whisper.cpp's full JSON (`transcription[].tokens[].offsets`, in ms) as
+ * words: a token that starts with a space starts a word, any other continues
+ * the one before; special tokens (`[_BEG_]`, …) are skipped. Only the words in
+ * [from − 2, to + 2]. Null when the document carries no token offsets (a
+ * parakeet `chunk_data`, a cue file).
+ */
+export function whisperWords(doc, from = -Infinity, to = Infinity) {
+ if (!Array.isArray(doc?.transcription)) return null;
+ const words = [];
+ let any = false;
+ for (const seg of doc.transcription) {
+ let open = false;
+ for (const tok of seg?.tokens ?? []) {
+ const text = String(tok?.text ?? "");
+ const off = tok?.offsets;
+ if (!text || /^\s*\[_/.test(text) || !off || !num(off.from) || !num(off.to)) continue;
+ any = true;
+ const s = off.from / 1000;
+ const e = off.to / 1000;
+ if (e < from - 2 || s > to + 2) {
+ open = false;
+ continue;
+ }
+ if (!open || /^\s/.test(text)) {
+ words.push({ start: s, end: e, text: text.trim() });
+ open = true;
+ } else {
+ const w = words[words.length - 1];
+ w.text += text;
+ w.end = Math.max(w.end, e);
+ }
+ }
+ }
+ return any && words.length ? words : null;
+}
+
+/** The phrase a clip says: its `montage.match`, else its on-screen title. */
+export const clipPhrase = (entry) => {
+ const p = entry?.montage?.match ?? entry?.onscreen?.title ?? null;
+ return typeof p === "string" && p.trim() ? p : null;
+};
+
+// ---- the plan across the cut ----------------------------------------------------
+
+/** The ramp's cap for clip k of n: lerp(from, to, k/(n−1)), the first `from`, the last `to`. */
+export function rampCap(k, n, ramp) {
+ if (!ramp) return null;
+ const f = n > 1 ? k / (n - 1) : 0;
+ return ramp.from + (ramp.to - ramp.from) * f;
+}
+
+/** Every clip's cap under a ramp, in order. */
+export const rampCaps = (n, ramp) => Array.from({ length: n }, (_, k) => rampCap(k, n, ramp));
+
+/** Is clip k (0-based, id `id`) stuttered? Every Nth counts from the Nth clip. */
+export const stutters = (stutter, k, id) =>
+ !!stutter && ((stutter.every != null && (k + 1) % stutter.every === 0) || stutter.clips.includes(id));
+
+/**
+ * The per-clip facts a montage needs from the whole cut, by clip id: k (its
+ * place among the clips), n (how many), its cap under the ramp, whether it
+ * stutters, its date and year, whether its year differs from the clip
+ * before's, its source, and whether its segment opens or closes the cut
+ * (`first`/`last`: a cut style has nothing to cut from or to there; a wall
+ * at that end takes the edge).
+ *
+ * @param {object[]} timeline the cut's timeline (every entry, in order)
+ * @param {object} settings resolveMontage's
+ * @param {(entry) => string|null} [dateOf] a clip's date when its own fields carry none
+ */
+export function planMontage(timeline, settings, dateOf = () => null) {
+ const clips = timeline.filter((e) => e?.type === "clip");
+ const n = clips.length;
+ const out = new Map();
+ let prevYear = null;
+ clips.forEach((e, k) => {
+ const date = parseClipDate(e.montage?.date) ?? parseClipDate(e.date) ?? parseClipDate(dateOf(e));
+ const year = date?.y ?? null;
+ const i = timeline.indexOf(e);
+ out.set(e.id, {
+ k, n,
+ cap: rampCap(k, n, settings.ramp),
+ stutter: stutters(settings.stutter, k, e.id),
+ date, year,
+ yearChange: year != null && year !== prevYear,
+ platform: e.montage?.platform ?? null,
+ first: i === 0 && settings.wall?.at !== "start",
+ last: i === timeline.length - 1 && !(settings.wall && settings.wall.at === "end"),
+ });
+ if (year != null) prevYear = year;
+ });
+ return out;
+}
+
+// ---- one clip's cut -------------------------------------------------------------------
+
+/**
+ * Where a montage clip is cut, on the fetched file's clock.
+ *
+ * `tighten: "phrase"` with a located phrase: the phrase ± `pad`, inside the
+ * extent; under a ramp, the pads are trimmed (evenly, then whatever one side
+ * lacks from the other) until the cut is no longer than `cap`, never into the
+ * phrase. Then each edge snaps to the nearest silence within `snapWindow`
+ * (build-video's own `snap`), kept only when it stays outside the phrase,
+ * inside the extent and under the cap. Otherwise -- "sentence", null, or no
+ * phrase found -- today's cut: the play window, snapped as every clip is.
+ *
+ * @param {{ extent: [number, number], play: [number, number], phrase: {start: number, end: number}|null,
+ * tighten: string|null, pad: number, cap: number|null, silences: Array<{s: number, e: number}>,
+ * snapWindow: number, render: object, snap: Function }} o
+ * @returns {{ cutA: number, cutB: number, start: {at: number, snapped: boolean}, end: {at: number, snapped: boolean}, tight: boolean }}
+ */
+export function montageWindow({ extent, play, phrase, tighten, pad, cap, silences, snapWindow, render, snap }) {
+ const [e0, e1] = extent;
+ const usable = phrase && phrase.end > e0 && phrase.start < e1 && phrase.end > phrase.start;
+ if (tighten !== "phrase" || !usable) {
+ const [w0, w1] = play;
+ const a = snap(w0, silences, "start", snapWindow, render);
+ const b = snap(w1, silences, "end", snapWindow, render);
+ const cutA = Math.min(a.at, w1 - 1);
+ const cutB = Math.max(b.at, cutA + 1);
+ return { cutA, cutB, start: a, end: b, tight: false };
+ }
+ const p0 = Math.max(e0, phrase.start);
+ const p1 = Math.min(e1, phrase.end);
+ let w0 = Math.max(e0, p0 - pad);
+ let w1 = Math.min(e1, p1 + pad);
+ if (num(cap) && w1 - w0 > cap) {
+ const room = Math.max(0, cap - (p1 - p0));
+ let before = Math.min(p0 - w0, room / 2);
+ const after = Math.min(w1 - p1, room - before);
+ before = Math.min(p0 - w0, room - after);
+ w0 = p0 - before;
+ w1 = p1 + after;
+ }
+ const limit = num(cap) ? Math.max(cap, w1 - w0) + 1e-6 : Infinity;
+ const s = snap(w0, silences, "start", snapWindow, render);
+ const start = s.snapped && s.at >= e0 - 1e-6 && s.at <= p0 - 0.04 && w1 - s.at <= limit ? s : { at: w0, snapped: false };
+ const t = snap(w1, silences, "end", snapWindow, render);
+ const end = t.snapped && t.at <= e1 + 1e-6 && t.at >= p1 + 0.04 && t.at - start.at <= limit ? t : { at: w1, snapped: false };
+ let cutB = end.at;
+ if (cutB - start.at < 0.5) cutB = Math.min(e1, start.at + 0.5);
+ return { cutA: start.at, cutB, start, end, tight: true };
+}
+
+/**
+ * The segment's picture as pieces of the cut, in FRAMES of the cut's own
+ * clock (frame 0 is the cut's start): `[{ f0, f1, zoom }]`, played in order.
+ *
+ * - a snap punch-in changes the zoom at the phrase's onset (`onset`);
+ * - a stutter plays the phrase's last `length` seconds `times` times in all
+ * ("…news day-day-day"), each repeat `step` more zoomed than the one before.
+ *
+ * @param {{ frames: number, fps: number, onset: number|null, phraseEnd: number|null,
+ * punch: object|null, stutter: object|null }} o onset/phraseEnd in seconds of the cut
+ */
+export function montagePieces({ frames, fps, onset = null, phraseEnd = null, punch = null, stutter = null }) {
+ const NF = Math.max(1, frames);
+ const fr = (s) => Math.max(0, Math.min(NF, Math.round(s * fps)));
+ const snapAt = punch?.mode === "snap" && num(onset) ? fr(onset) : null;
+ const zoomAt = (f) => (snapAt != null && f >= snapAt ? punch.scale : 1);
+ let s0 = null;
+ let s1 = null;
+ if (stutter && num(phraseEnd)) {
+ s1 = fr(phraseEnd);
+ s0 = Math.max(0, s1 - Math.round(stutter.length * fps));
+ if (s1 - s0 < 3) s0 = s1 = null;
+ }
+ const marks = [...new Set([0, NF, ...(snapAt != null && snapAt > 0 && snapAt < NF ? [snapAt] : []), ...(s0 != null ? [s0, s1] : [])])]
+ .sort((a, b) => a - b);
+ const pieces = [];
+ for (let i = 0; i + 1 < marks.length; i += 1) {
+ const f0 = marks[i];
+ const f1 = marks[i + 1];
+ if (f1 <= f0) continue;
+ pieces.push({ f0, f1, zoom: zoomAt(f0) });
+ if (s1 != null && f1 === s1) {
+ const z = zoomAt(s1 - 1);
+ for (let r = 1; r < stutter.times; r += 1) {
+ pieces.push({ f0: s0, f1: s1, zoom: Number((z * (1 + stutter.step * r)).toFixed(4)), repeat: r });
+ }
+ }
+ }
+ return pieces;
+}
+
+/** The pieces' length in frames. */
+export const piecesFrames = (pieces) => pieces.reduce((n, p) => n + (p.f1 - p.f0), 0);
+
+// ---- the filtergraph of one montage segment -----------------------------------------
+
+const exprNum = (v) => String(Number(v.toFixed(4)));
+
+/** A crop to 1/zoom of the picture, centred across, at the anchor's height. */
+const zoomCrop = (zoom, anchor) =>
+ `crop=w='floor(iw/${zoom}/2)*2':h='floor(ih/${zoom}/2)*2':x='(iw-ow)/2':y='(ih-oh)*${anchor === "center" ? 0.5 : 0.35}'`;
+
+/**
+ * The pieces as a graph: from the cut's raw picture and sound to the
+ * segment's picture, fitted to `box` (letterboxed in `bg`), and its sound,
+ * exactly `frames` long. A drift punch-in zooms the whole thing, 1 → scale.
+ * Each joint of a stutter fades 5 ms; the segment's own edges fade
+ * DECLICK, always.
+ *
+ * @returns {{ parts: string[], v: string, a: string, frames: number, seconds: number }}
+ */
+export function montagePiecesGraph({ pieces, fps, box, bg, punch = null, inV = "[0:v]", inA = "[0:a]", hasVideo = true }) {
+ const frames = piecesFrames(pieces);
+ const seconds = frames / fps;
+ const parts = [];
+ const anchor = punch?.anchor ?? "upper";
+ const fit = `scale=${box.w}:${box.h}:force_original_aspect_ratio=decrease,pad=${box.w}:${box.h}:(ow-iw)/2:(oh-ih)/2:color=${bg},setsar=1`;
+ const P = pieces.length;
+ const vLabels = [];
+ const aLabels = [];
+ if (hasVideo) {
+ if (P === 1) parts.push(`${inV}fps=${fps}[mvs0]`);
+ else parts.push(`${inV}fps=${fps},split=${P}${pieces.map((_, i) => `[mvs${i}]`).join("")}`);
+ }
+ parts.push(P === 1 ? `${inA}anull[mas0]` : `${inA}asplit=${P}${pieces.map((_, i) => `[mas${i}]`).join("")}`);
+ pieces.forEach((p, i) => {
+ if (hasVideo) {
+ const z = p.zoom !== 1 ? `,${zoomCrop(p.zoom, anchor)}` : "";
+ parts.push(`[mvs${i}]trim=start_frame=${p.f0}:end_frame=${p.f1},setpts=PTS-STARTPTS${z},${fit}[mv${i}]`);
+ vLabels.push(`[mv${i}]`);
+ }
+ const a0 = p.f0 / fps;
+ const a1 = p.f1 / fps;
+ const len = a1 - a0;
+ const joint = P > 1 && len > 4 * JOINT_FADE
+ ? `,afade=t=in:d=${JOINT_FADE},afade=t=out:st=${exprNum(len - JOINT_FADE)}:d=${JOINT_FADE}`
+ : "";
+ parts.push(`[mas${i}]atrim=start=${exprNum(a0)}:end=${exprNum(a1)},asetpts=PTS-STARTPTS${joint}[ma${i}]`);
+ aLabels.push(`[ma${i}]`);
+ });
+ if (hasVideo) {
+ if (P === 1) parts.push(`${vLabels[0]}null[mvc]`, `${aLabels[0]}anull[mac]`);
+ else parts.push(`${pieces.map((_, i) => `${vLabels[i]}${aLabels[i]}`).join("")}concat=n=${P}:v=1:a=1[mvc][mac]`);
+ } else {
+ parts.push(P === 1 ? `${aLabels[0]}anull[mac]` : `${aLabels.join("")}concat=n=${P}:v=0:a=1[mac]`);
+ }
+ if (hasVideo) {
+ // Never a frame more or less than the plan: a short source is held on its
+ // last frame, a long one cut.
+ const exact = `tpad=stop_mode=clone:stop_duration=1,trim=end_frame=${frames},setpts=PTS-STARTPTS`;
+ if (punch?.mode === "drift") {
+ const ay = anchor === "center" ? 0.5 : 0.35;
+ parts.push(
+ `[mvc]${exact},scale=${box.w * 2}:${box.h * 2},` +
+ `zoompan=z='1+${exprNum(punch.scale - 1)}*on/${Math.max(1, frames - 1)}':x='iw/2-iw/zoom/2':y='(ih-ih/zoom)*${ay}':d=1:s=${box.w}x${box.h}:fps=${fps},setsar=1[mv]`,
+ );
+ } else {
+ parts.push(`[mvc]${exact}[mv]`);
+ }
+ }
+ const D = exprNum(seconds);
+ const declick = seconds > 4 * DECLICK
+ ? `,afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(seconds - DECLICK)}:d=${DECLICK}`
+ : "";
+ parts.push(`[mac]apad=whole_dur=${D},atrim=end=${D}${declick}[ma]`);
+ return { parts, v: hasVideo ? "[mv]" : null, a: "[ma]", frames, seconds };
+}
+
+/**
+ * The cut style, on one segment's finished picture: its first frames (unless
+ * it opens the cut) and its last (unless it closes it). Flash: the first
+ * CUT_FRAMES.flash frames fade from the flash colour. Dip: the last two fade
+ * to black, the first two up from it. Whip: the last four slide out to the
+ * left and the first four in from the right, wrapped and blurred along the
+ * move. Hard: nothing.
+ *
+ * @returns {string[]} parts from `inLabel` to `outLabel`
+ */
+export function cutStyleParts({ cut, first, last, frames, fps, w, h, flashColor = "#ffffff", inLabel, outLabel }) {
+ const f = (n) => exprNum(n / fps);
+ if (cut === "flash" && !first && frames > CUT_FRAMES.flash) {
+ return [`${inLabel}fade=t=in:st=0:d=${f(CUT_FRAMES.flash)}:color=${flashColor}${outLabel}`];
+ }
+ if (cut === "dip") {
+ const n = CUT_FRAMES.dip;
+ const chain = [];
+ if (!first && frames > n) chain.push(`fade=t=in:st=0:d=${f(n)}`);
+ if (!last && frames > 2 * n + 1) chain.push(`fade=t=out:st=${f(frames - n - 1)}:d=${f(n)}`);
+ if (chain.length) return [`${inLabel}${chain.join(",")}${outLabel}`];
+ }
+ if (cut === "whip") {
+ const n = CUT_FRAMES.whip;
+ const head = !first;
+ const tail = !last;
+ if ((head || tail) && frames > 2 * n + 1) {
+ // The picture beside a copy of itself, cropped at x: shifted left by x,
+ // wrapped -- under the blur, a whip pan. `n` inside the quotes is crop's
+ // own frame number.
+ const blur = `avgblur=sizeX=${Math.max(2, Math.round(w * 0.035))}:sizeY=1`;
+ const slide = (x) => `hstack,crop=w=${w}:h=${h}:x='${x}':y=0,${blur}`;
+ const parts = [];
+ const segs = [];
+ const take = [head ? "[wph]" : null, "[wpb]", tail ? "[wpt]" : null].filter(Boolean);
+ parts.push(`${inLabel}split=${take.length}${take.join("")}`);
+ if (head) {
+ // In from the right: shifted right by d·w, d easing 0.58 → 0.04.
+ parts.push(
+ `[wph]trim=end_frame=${n},setpts=PTS-STARTPTS,split[wh1][wh2]`,
+ `[wh1][wh2]${slide(`${w}*(1-0.9*pow(1-(n+1)/${n + 1},2))`)}[wh]`,
+ );
+ segs.push("[wh]");
+ }
+ parts.push(`[wpb]trim=start_frame=${head ? n : 0}:end_frame=${tail ? frames - n : frames},setpts=PTS-STARTPTS[wb]`);
+ segs.push("[wb]");
+ if (tail) {
+ // Out to the left: shifted left by d·w, d easing 0.04 → 0.58.
+ parts.push(
+ `[wpt]trim=start_frame=${frames - n},setpts=PTS-STARTPTS,split[wt1][wt2]`,
+ `[wt1][wt2]${slide(`${w}*0.9*pow((n+1)/${n + 1},2)`)}[wt]`,
+ );
+ segs.push("[wt]");
+ }
+ parts.push(`${segs.join("")}concat=n=${segs.length}:v=1:a=0${outLabel}`);
+ return parts;
+ }
+ }
+ return [`${inLabel}null${outLabel}`];
+}
+
+/** Where a corner overlay sits: drawtext/drawbox x and y for a block w×h, `m` from the edges. */
+function corner(position, m) {
+ const right = position.endsWith("right");
+ const bottom = position.startsWith("bottom");
+ return {
+ right, bottom,
+ x: (w) => (right ? `W-${m}-${w}` : String(m)),
+ y: (h) => (bottom ? `H-${m}-${h}` : String(m)),
+ };
+}
+
+/**
+ * Tally marks for a count: groups of five, four uprights struck through by
+ * the fifth, ten groups a row. Boxes relative to the tally's top-left, and
+ * its bounds; the LAST box is the newest mark.
+ *
+ * @returns {{ marks: Array<{x: number, y: number, w: number, h: number, strike: boolean}>, width: number, height: number }}
+ */
+export function tallyMarks(count, H) {
+ const mw = Math.max(2, Math.round(H * 0.0055));
+ const mh = Math.round(H * 0.05);
+ const gap = Math.round(H * 0.012);
+ const groupGap = Math.round(H * 0.026);
+ const rowGap = Math.round(H * 0.022);
+ const gw = 4 * mw + 3 * gap;
+ const perRow = 10;
+ const over = Math.round(gap * 0.7);
+ const marks = [];
+ for (let i = 0; i < count; i += 1) {
+ const g = Math.floor(i / 5);
+ const r = i % 5;
+ const gx = over + (g % perRow) * (gw + groupGap);
+ const gy = Math.floor(g / perRow) * (mh + rowGap);
+ if (r < 4) marks.push({ x: gx + r * (mw + gap), y: gy, w: mw, h: mh, strike: false });
+ else marks.push({ x: gx - over, y: gy + Math.round(mh * 0.45), w: gw + 2 * over, h: mw, strike: true });
+ }
+ const groups = Math.ceil(count / 5);
+ const cols = Math.min(perRow, Math.max(1, groups));
+ const rows = Math.max(1, Math.ceil(groups / perRow));
+ return { marks, width: 2 * over + cols * gw + (cols - 1) * groupGap, height: rows * mh + (rows - 1) * rowGap };
+}
+
+/**
+ * The counter and the year stamp over one segment's finished picture: drawtext
+ * and drawbox only, timed on the segment's own clock.
+ *
+ * - chip: "#12 · 2 May 2019 · YouTube" on a translucent ground, the whole clip;
+ * - big: the number, large, slamming in (1.9× → 1× over 0.18 s), held, gone by
+ * 1.5 s, with the date line under it;
+ * - tally: the marks so far, the newest landing at 0.12 s in the accent;
+ * - the year stamp: the year, large, in the corner across from the counter,
+ * for about a second, on a clip whose year differs from the one before.
+ *
+ * @returns {string[]} filters, to join with "," (empty: nothing to draw)
+ */
+export function montageOverlayFilters({ settings, ctx, render, font }) {
+ const { width: W, height: H } = render;
+ const pal = render.palette ?? {};
+ const fg = pal.fg ?? "#ffffff";
+ const bg = pal.bg ?? "#000000";
+ const accent = pal.accent ?? fg;
+ const m = Math.round(H * 0.035);
+ const out = [];
+ const dt = (o) => ["drawtext=" + `fontfile='${font}'`, "expansion=none", ...Object.entries(o).map(([k, v]) => `${k}=${v}`)].join(":");
+ const c = settings.counter;
+ if (c) {
+ const words = counterText({
+ n: ctx.k + 1, of: c.of ? ctx.n : null, date: ctx.date, platform: ctx.platform,
+ showDate: c.showDate, showSource: c.showSource,
+ });
+ const at = corner(c.position, m);
+ if (c.style === "chip") {
+ const fs = Math.round(H * 0.034);
+ const text = [words.number, words.line].filter(Boolean).join(" · ");
+ const pad = Math.round(fs * 0.45);
+ // The ground reaches `pad` past the text on every side; the ground is `m` from the edges.
+ out.push(dt({
+ text: `'${text}'`, fontsize: fs, fontcolor: fg, box: 1, boxcolor: `${bg}@0.72`, boxborderw: pad,
+ x: at.right ? `W-${m + pad}-text_w` : String(m + pad),
+ y: at.bottom ? `H-${m + pad}-text_h` : String(m + pad),
+ }));
+ } else if (c.style === "big") {
+ const fs = Math.round(H * 0.24);
+ const small = Math.round(H * 0.036);
+ const alpha = `'min(1,t/0.04)*if(lt(t,1.2),1,max(0,1-(t-1.2)/0.3))'`;
+ const lineH = words.line ? Math.round(small * 1.5) : 0;
+ out.push(dt({
+ text: `'${words.number.replace(/^#/, "")}'`, fontsize: `'${fs}*(1+0.9*max(0,1-t/0.18))'`, fontcolor: accent,
+ borderw: Math.max(2, Math.round(fs * 0.025)), bordercolor: bg, alpha,
+ x: at.x("text_w"), y: at.bottom ? `H-${m + lineH}-text_h` : String(m),
+ }));
+ if (words.line) {
+ out.push(dt({
+ text: `'${words.line}'`, fontsize: small, fontcolor: fg, borderw: 2, bordercolor: bg, alpha,
+ x: at.x("text_w"), y: at.bottom ? `H-${m}-text_h` : String(m + Math.round(fs * 1.05)),
+ }));
+ }
+ } else if (c.style === "tally") {
+ const t = tallyMarks(ctx.k + 1, H);
+ const pad = Math.round(H * 0.012);
+ const small = Math.round(H * 0.03);
+ const lineH = words.line ? Math.round(small * 1.6) : 0;
+ const bw = t.width + 2 * pad;
+ const bh = t.height + 2 * pad + lineH;
+ const x0 = at.right ? W - m - bw : m;
+ const y0 = at.bottom ? H - m - bh : m;
+ out.push(`drawbox=x=${x0}:y=${y0}:w=${bw}:h=${bh}:color=${bg}@0.6:t=fill`);
+ t.marks.forEach((mk, i) => {
+ const newest = i === t.marks.length - 1;
+ out.push(
+ `drawbox=x=${x0 + pad + mk.x}:y=${y0 + pad + mk.y}:w=${mk.w}:h=${mk.h}:color=${newest ? accent : fg}:t=fill` +
+ (newest ? ":enable='gte(t,0.12)'" : ""),
+ );
+ });
+ if (words.line) {
+ out.push(dt({ text: `'${words.line}'`, fontsize: small, fontcolor: fg, x: x0 + pad, y: y0 + pad + t.height + Math.round(small * 0.35) }));
+ }
+ }
+ }
+ if (settings.yearStamp && ctx.yearChange && ctx.year != null) {
+ const across = c ? (c.position.endsWith("left") ? c.position.replace("left", "right") : c.position.replace("right", "left")) : "top-right";
+ const at = corner(across, m);
+ const fs = Math.round(H * 0.16);
+ out.push(dt({
+ text: `'${ctx.year}'`, fontsize: fs, fontcolor: fg, borderw: Math.max(2, Math.round(fs * 0.03)), bordercolor: bg,
+ alpha: `'if(lt(t,0.08),t/0.08,if(lt(t,1),1,max(0,1-(t-1)/0.25)))'`,
+ x: at.x("text_w"), y: at.y("text_h"),
+ }));
+ }
+ return out;
+}
+
+/** The font a montage's words are drawn in: the render's bold, else its regular, else Plex Mono Bold. */
+export const montageFont = (render) => render.fontBold ?? render.fontRegular ?? MONO_BOLD_FONT_FILE;
+
+// ---- the wall ---------------------------------------------------------------------------
+
+/**
+ * Which clips the wall's tiles play, in order: `tiles` spread evenly over the
+ * cut's clips, first to last (the first tile the earliest); fewer clips than
+ * tiles go round again.
+ */
+export function wallTileClips(ids, tiles) {
+ const n = ids.length;
+ if (!n) return [];
+ if (n >= tiles) return Array.from({ length: tiles }, (_, j) => ids[tiles > 1 ? Math.round((j * (n - 1)) / (tiles - 1)) : 0]);
+ return Array.from({ length: tiles }, (_, j) => ids[j % n]);
+}
+
+/**
+ * The wall, laid out and timed. A √tiles grid of frame-shaped tiles, centred,
+ * `gap` apart. Tile i appears at build·(1 − (1 − i/tiles)²) -- the gaps
+ * between appearances shrink, so the last tiles come fastest -- and plays its
+ * phrase; at `build` every tile plays its phrase again, together, for the
+ * longest phrase (0.8–2.5 s) and a quarter second; then the cut. All on frames.
+ *
+ * @param {{ tiles: number, build: number, durations: number[], fps: number, width: number, height: number }} o
+ * `durations` each tile's phrase seconds
+ */
+export function wallPlan({ tiles, build, durations, fps, width, height }) {
+ const cols = Math.round(Math.sqrt(tiles));
+ const gap = Math.max(2, Math.round(height * 0.008) & ~1);
+ const maxW = (width - gap * (cols + 1)) / cols;
+ const maxH = (height - gap * (cols + 1)) / cols;
+ let w = Math.floor(Math.min(maxW, (maxH * width) / height));
+ w -= w % 2;
+ let h = Math.floor((w * height) / width);
+ h -= h % 2;
+ const gridW = cols * w + (cols - 1) * gap;
+ const gridH = cols * h + (cols - 1) * gap;
+ const ox = Math.floor((width - gridW) / 2);
+ const oy = Math.floor((height - gridH) / 2);
+ const q = (s) => Math.round(s * fps);
+ const layout = Array.from({ length: tiles }, (_, i) => ({
+ x: ox + (i % cols) * (w + gap), y: oy + Math.floor(i / cols) * (h + gap), w, h,
+ }));
+ const appearF = Array.from({ length: tiles }, (_, i) => q(build * (1 - (1 - i / tiles) ** 2)));
+ const beatF = q(build);
+ const longest = Math.max(0.8, Math.min(2.5, ...durations.map((d) => (num(d) ? d : 0.8))));
+ const beatLenF = q(longest + 0.25);
+ return {
+ cols, gap, layout, tileW: w, tileH: h,
+ appear: appearF.map((f) => f / fps),
+ appearFrames: appearF,
+ beat: beatF / fps, beatFrames: beatF,
+ beatLen: beatLenF / fps,
+ frames: beatF + beatLenF,
+ seconds: (beatF + beatLenF) / fps,
+ };
+}
+
+/**
+ * One wall tile: the clip's phrase (from–to on the fetched file's clock),
+ * filled into the tile (cropped, never letterboxed), its year at the foot
+ * when the wall says so.
+ */
+export function wallTileArgs({ raw, from, to, tileW, tileH, fps, year = null, font, render, encode, outPath }) {
+ const fs = Math.max(10, Math.round(tileH * 0.11));
+ const label = year != null
+ ? `,drawtext=fontfile='${font}':expansion=none:text='${safeText(String(year))}':fontsize=${fs}:fontcolor=${render.palette?.fg ?? "#ffffff"}:borderw=2:bordercolor=${render.palette?.bg ?? "#000000"}:x=${Math.round(fs * 0.6)}:y=h-${Math.round(fs * 0.5)}-text_h`
+ : "";
+ return [
+ "-nostdin", "-v", "error", "-y",
+ "-ss", from.toFixed(3), "-to", to.toFixed(3), "-i", raw,
+ "-filter_complex",
+ `[0:v]fps=${fps},scale=${tileW}:${tileH}:force_original_aspect_ratio=increase,crop=${tileW}:${tileH},setsar=1${label}[v]`,
+ "-map", "[v]", "-map", "0:a",
+ ...encode,
+ outPath,
+ ];
+}
+
+/**
+ * The wall's compose: every tile laid on the grid, each appearing at its
+ * time and playing once, then frozen; at the beat all play again, together.
+ * Sound: each tile at full level until the next one appears, then ducked;
+ * the beat's tiles all together (a crowd), limited. Then the cut style and
+ * the de-click, as any segment.
+ *
+ * @param {{ tiles: Array<{ file: string, seconds: number }>, plan: object, render: object,
+ * settings: object, first: boolean, last: boolean, encode: string[], outPath: string }} o
+ */
+export function wallComposeArgs({ tiles, plan, render, settings, first, last, encode, outPath }) {
+ const { fps } = render;
+ const bg = render.palette?.bg ?? "#000000";
+ const T = tiles.length;
+ const total = exprNum(plan.seconds);
+ const beat = exprNum(plan.beat);
+ const parts = [];
+ const vs = [];
+ const as = [];
+ const crowd = exprNum(Math.min(1, 1.6 / Math.sqrt(T)));
+ tiles.forEach((t, i) => {
+ const at = plan.appear[i];
+ const once = Math.max(1 / fps, Math.min(t.seconds, plan.beat - at));
+ const again = Math.min(t.seconds, plan.beatLen);
+ parts.push(
+ `[${i}:v]split[wv${i}a][wv${i}b]`,
+ `[wv${i}a]trim=end=${exprNum(once)},setpts=PTS-STARTPTS,` +
+ `tpad=start_duration=${exprNum(at)}:start_mode=add:color=${bg}:stop_mode=clone:stop_duration=${beat},trim=end_frame=${plan.beatFrames}[wv${i}c]`,
+ `[wv${i}b]trim=end=${exprNum(again)},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration=${exprNum(plan.beatLen)},` +
+ `trim=end_frame=${plan.frames - plan.beatFrames}[wv${i}d]`,
+ `[wv${i}c][wv${i}d]concat=n=2:v=1:a=0[wt${i}]`,
+ );
+ vs.push(`[wt${i}]`);
+ const next = i + 1 < T ? plan.appear[i + 1] - at : Infinity;
+ const duck = Number.isFinite(next) ? `,volume='if(lt(t,${exprNum(next)}),1,0.22)':eval=frame` : "";
+ const delay = (s) => Math.round(s * 1000);
+ parts.push(
+ `[${i}:a]asplit[wa${i}a][wa${i}b]`,
+ `[wa${i}a]atrim=end=${exprNum(once)},asetpts=PTS-STARTPTS${duck},adelay=${delay(at)}:all=1[wa${i}c]`,
+ `[wa${i}b]atrim=end=${exprNum(again)},asetpts=PTS-STARTPTS,volume=${crowd},adelay=${delay(plan.beat)}:all=1[wa${i}d]`,
+ );
+ as.push(`[wa${i}c]`, `[wa${i}d]`);
+ });
+ const layout = plan.layout.map((l) => `${l.x - plan.layout[0].x}_${l.y - plan.layout[0].y}`).join("|");
+ parts.push(
+ `${vs.join("")}xstack=inputs=${T}:layout=${layout}:fill=${bg},` +
+ `pad=${render.width}:${render.height}:${plan.layout[0].x}:${plan.layout[0].y}:color=${bg},setsar=1,fps=${fps}[wg]`,
+ );
+ parts.push(...cutStyleParts({
+ cut: settings.cut, first, last, frames: plan.frames, fps, w: render.width, h: render.height,
+ flashColor: settings.flashColor, inLabel: "[wg]", outLabel: "[v]",
+ }));
+ parts.push(
+ `${as.join("")}amix=inputs=${as.length}:normalize=0:duration=longest,alimiter=limit=0.9,` +
+ `apad=whole_dur=${total},atrim=end=${total},` +
+ `afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(plan.seconds - DECLICK)}:d=${DECLICK}[a]`,
+ );
+ return [
+ "-nostdin", "-v", "error", "-y",
+ ...tiles.flatMap((t) => ["-i", t.file]),
+ "-filter_complex", parts.join(";"),
+ "-map", "[v]", "-map", "[a]",
+ "-frames:v", String(plan.frames),
+ ...encode,
+ outPath,
+ ];
+}
+
+/** The wall's place in the cut, as an entry: what the chapters call it. */
+export const WALL_ENTRY = Object.freeze({ type: "montage-wall", id: "montage-wall", title: "All together" });
diff --git a/umtool/report-to-video/montage.test.mjs b/umtool/report-to-video/montage.test.mjs
@@ -0,0 +1,755 @@
+// Montage editing (`render.montage`, release 33 M3): the pure parts -- the
+// settings and their validation, where a phrase is said, the ramp, the cut
+// window, the pieces (punch-in, stutter), the cut styles, the counter, the
+// wall's layout and timing -- and real renders of a four-clip montage per
+// named style over synthetic lavfi clips: the length the plan says, to the
+// frame, and the flash, the counter, the year stamp, the whip and the wall
+// where they should be.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ counterText, CUT_FRAMES, cutStyleParts, DECLICK, formatClipDate, locatePhrase, montageOn, montageOverlayFilters,
+ montagePieces, montagePiecesGraph, montageWindow, normalisePhrase, parseClipDate, piecesFrames, planMontage,
+ platformLabel, rampCap, rampCaps, resolveMontage, safeText, stutters, tallyMarks, timedText, validateMontage,
+ wallComposeArgs, wallPlan, wallTileClips, whisperWords,
+} from "./montage.mjs";
+import { applyMontageStyle, MONTAGE_STYLE_NAMES, mergePatch } from "./montage-styles.mjs";
+import { buildVideo, snap } from "./build-video.mjs";
+import { lintManifest } from "./lint.mjs";
+import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs";
+
+const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" };
+const clip = (id, extra = {}) => ({ id, type: "clip", video: `v-${id}`, start: 10, end: 20, ...extra });
+const manifest = (montage, timeline = [clip("c1"), clip("c2")], render = {}) => ({
+ render: { width: 1920, height: 1080, fps: 30, palette: PALETTE, ...render, montage }, timeline,
+});
+
+// ---- settings and validation ---------------------------------------------------
+
+test("validateMontage: absent or null is off and says nothing; the named styles all validate", () => {
+ assert.deepEqual(validateMontage({ render: {}, timeline: [] }), []);
+ assert.deepEqual(validateMontage(manifest(null)), []);
+ assert.equal(montageOn({}), false);
+ assert.equal(montageOn({ montage: null }), false);
+ assert.equal(montageOn({ montage: {} }), true);
+ for (const name of MONTAGE_STYLE_NAMES) {
+ assert.deepEqual(validateMontage(applyMontageStyle(manifest(undefined), name)), [], name);
+ }
+});
+
+test("validateMontage: unknown keys and bad values are errors that say what is wrong", () => {
+ const errs = (m, tl) => validateMontage(manifest(m, tl));
+ assert.match(errs([])[0], /render\.montage must be an object/);
+ assert.match(errs({ tightn: "phrase" })[0], /render\.montage\.tightn is not a setting here \(the settings are tighten, phrasePad, /);
+ assert.match(errs({ tighten: "word" })[0], /render\.montage\.tighten must be "phrase" or "sentence", not "word"/);
+ assert.match(errs({ phrasePad: -1 })[0], /phrasePad must be a number from 0 to 5 seconds/);
+ assert.match(errs({ cut: "wipe" })[0], /render\.montage\.cut must be "hard" or "flash" or "whip" or "dip", not "wipe"/);
+ assert.match(errs({ flashColor: "red" })[0], /flashColor must be "white", "accent" or a #rrggbb colour/);
+ assert.deepEqual(errs({ flashColor: "#ff8800" }), []);
+ assert.match(errs({ counter: { style: "dial" } })[0], /counter\.style must be "chip" or "big" or "tally"/);
+ assert.match(errs({ counter: { position: "middle" } })[0], /counter\.position must be "top-left"/);
+ assert.match(errs({ counter: { of: "yes" } })[0], /counter\.of must be true or false/);
+ assert.match(errs({ counter: { colour: 1 } })[0], /counter\.colour is not a setting here/);
+ assert.match(errs({ counter: 3 })[0], /counter must be an object/);
+ assert.match(errs({ punch: { scale: 1.2 } })[0], /punch\.mode must be "snap" or "drift", not undefined/);
+ assert.match(errs({ punch: { mode: "snap", scale: 3 } })[0], /punch\.scale must be a number from 1 to 2/);
+ assert.match(errs({ punch: { mode: "snap", anchor: "face" } })[0], /punch\.anchor must be "upper" or "center"/);
+ assert.match(errs({ stutter: { times: 3 } })[0], /stutter needs `every` \(every Nth clip\) or `clips`/);
+ assert.match(errs({ stutter: { every: 0 } })[0], /stutter\.every must be a whole number from 1/);
+ assert.match(errs({ stutter: { every: 2, times: 5 } })[0], /stutter\.times must be 2, 3 or 4/);
+ assert.match(errs({ stutter: { clips: ["c9"] } })[0], /stutter\.clips names "c9", which is not a clip in the timeline/);
+ assert.deepEqual(errs({ stutter: { clips: ["c2"] } }), []);
+ assert.match(errs({ stutter: { every: 2, length: 3 } })[0], /stutter\.length must be a number from 0\.1 to 1 seconds/);
+ assert.match(errs({ ramp: { from: 4, to: 1 } })[0], /ramp trims around the phrase, so it needs render\.montage\.tighten "phrase"/);
+ assert.match(errs({ tighten: "phrase", ramp: { from: 4 } })[0], /ramp\.to must be a number from 0\.5 to 60 seconds, not undefined/);
+ assert.deepEqual(errs({ tighten: "phrase", ramp: { from: 4, to: 1 } }), []);
+ assert.match(errs({ wall: { tiles: 12 } })[0], /wall\.tiles must be 9 or 16 or 25, not 12/);
+ assert.match(errs({ wall: { at: "middle" } })[0], /wall\.at must be "end" or "start"/);
+ assert.match(errs({ wall: { build: 0 } })[0], /wall\.build must be a number from 1 to 60/);
+ assert.match(errs({ yearStamp: "yes" })[0], /yearStamp must be true or false/);
+});
+
+test("validateMontage: what a montage does not combine with", () => {
+ const deck = validateMontage(manifest({}, undefined, { chrome: { engine: "hyperframes", layout: "deck", deck: {} } }));
+ assert.ok(deck.some((e) => /does not combine with render\.chrome \(the deck\)/.test(e)), deck.join("; "));
+ assert.match(validateMontage(manifest({}, undefined, { rail: { width: 300 } }))[0], /does not combine with render\.rail/);
+ assert.match(validateMontage(manifest({}, undefined, { chromeEngine: "hyperframes" }))[0], /chromeEngine "hyperframes"/);
+ assert.match(
+ validateMontage(manifest({}, [clip("c1"), clip("c2", { muteFrom: 12 })]))[0],
+ /^timeline\[1\] \(c2\)\.muteFrom is not supported under render\.montage/,
+ );
+});
+
+test("the lint and a build's validators say it too", () => {
+ const m = { slug: "x", title: "X", ...manifest({ cut: "wipe" }) };
+ const lint = lintManifest(m, { manifestDir: os.tmpdir(), exists: () => true });
+ assert.ok(lint.errors.some((e) => /render\.montage\.cut must be/.test(e)), lint.errors.join("; "));
+});
+
+test("resolveMontage: every default filled in; the accent flash is the palette's", () => {
+ assert.equal(resolveMontage({}), null);
+ const r = resolveMontage({ palette: PALETTE, montage: { flashColor: "accent", punch: { mode: "drift" }, stutter: { every: 3 }, wall: { tiles: 9 }, counter: {} } });
+ assert.equal(r.tighten, null);
+ assert.equal(r.phrasePad, 0.6);
+ assert.equal(r.cut, "hard");
+ assert.equal(r.flashColor, "#7c5cff");
+ assert.deepEqual(r.counter, { style: "chip", position: "top-left", of: false, showDate: true, showSource: false });
+ assert.deepEqual(r.punch, { mode: "drift", scale: 1.08, anchor: "upper" });
+ assert.deepEqual(r.stutter, { every: 3, clips: [], times: 3, length: 0.35, step: 0.04 });
+ assert.deepEqual(r.wall, { at: "end", tiles: 9, build: 6, year: false });
+ assert.equal(r.ramp, null);
+ assert.equal(r.yearStamp, false);
+ assert.equal(resolveMontage({ montage: { punch: { mode: "snap" } } }).punch.scale, 1.15);
+ assert.equal(resolveMontage({ montage: {} }).flashColor, "#ffffff");
+});
+
+// ---- the counter's words ----------------------------------------------------------
+
+test("dates, sources and the counter text", () => {
+ assert.deepEqual(parseClipDate("20190502"), { y: 2019, m: 5, d: 2 });
+ assert.deepEqual(parseClipDate("2019-05-02"), { y: 2019, m: 5, d: 2 });
+ assert.deepEqual(parseClipDate("2019-05-02T10:00:00Z"), { y: 2019, m: 5, d: 2 });
+ assert.equal(parseClipDate("May 2019"), null);
+ assert.equal(parseClipDate("20191302"), null);
+ assert.equal(parseClipDate(null), null);
+ assert.equal(formatClipDate({ y: 2019, m: 5, d: 2 }), "2 May 2019");
+ assert.equal(formatClipDate(null), "");
+ assert.equal(platformLabel("youtube"), "YouTube");
+ assert.equal(platformLabel("RUMBLE"), "Rumble");
+ assert.equal(platformLabel("mystream"), "Mystream");
+ assert.equal(platformLabel(null), "");
+ assert.equal(safeText("it's 50% off: [now], ok?"), "its 50 off now ok");
+ assert.equal(safeText("#12 · 2 May 2019"), "#12 · 2 May 2019");
+ const date = { y: 2019, m: 5, d: 2 };
+ assert.deepEqual(counterText({ n: 12, date, platform: "youtube" }), { number: "#12", line: "2 May 2019" });
+ assert.deepEqual(counterText({ n: 12, of: 75, date, platform: "youtube", showSource: true }), { number: "#12 of 75", line: "2 May 2019 · YouTube" });
+ assert.deepEqual(counterText({ n: 3, date, showDate: false }), { number: "#3", line: "" });
+});
+
+// ---- where the phrase is said ------------------------------------------------------
+
+const CUES = [
+ { start: 10, end: 12, text: "well folks it is a" },
+ { start: 12, end: 13.6, text: "slow news day again" },
+ { start: 13.6, end: 16, text: "and a slow news week" },
+];
+
+test("timedText: the spans' characters spread over their spans, normalised, one space between", () => {
+ const tt = timedText([{ start: 0, end: 1, text: "It's A" }, { start: 1, end: 2, text: "b,c" }]);
+ assert.equal(tt.text, "its a b c ");
+ assert.equal(tt.t0.length, tt.text.length);
+ assert.equal(tt.t0[0], 0);
+ assert.ok(Math.abs(tt.t0[4] - 5 / 6) < 1e-9, "the a is the 6th of the cue's 6 characters");
+ assert.equal(tt.t0[6], 1);
+ assert.equal(normalisePhrase(" Slow News-Day! "), "slow news day");
+});
+
+test("locatePhrase: by character position inside its cue; across cues; the occurrence nearest `near`", () => {
+ const a = locatePhrase("slow news day", CUES, { from: 10, to: 16 });
+ assert.equal(a.start, 12);
+ assert.ok(Math.abs(a.end - (12 + (1.6 * 13) / 19)) < 1e-9, `end ${a.end}`);
+ // Across a cue boundary: "it is a slow" spans cues one and two.
+ const b = locatePhrase("it is a slow", CUES, { from: 10, to: 16 });
+ assert.ok(b.start > 10 && b.start < 12 && b.end > 12 && b.end < 13, JSON.stringify(b));
+ // Two occurrences of "slow news": the one nearest `near` wins.
+ assert.equal(locatePhrase("slow news", CUES, { from: 10, to: 16, near: 12.5 }).start, 12);
+ assert.ok(locatePhrase("slow news", CUES, { from: 10, to: 16, near: 15 }).start > 13.6);
+ // Outside the window, or not said: null.
+ assert.equal(locatePhrase("slow news day", CUES, { from: 0, to: 9 }), null);
+ assert.equal(locatePhrase("fast news day", CUES, { from: 10, to: 16 }), null);
+ assert.equal(locatePhrase("", CUES), null);
+ // A whole-word match first; a phrase running on into a longer word only when there is none.
+ const runOn = [{ start: 0, end: 2, text: "slow news days" }];
+ assert.ok(locatePhrase("slow news day", runOn));
+ assert.equal(locatePhrase("slow new", CUES, { from: 10, to: 16 }).start, 12, "a prefix of news");
+ assert.equal(locatePhrase("low news", CUES, { from: 10, to: 16 }), null, "never mid-word at the start");
+});
+
+test("whisperWords: whisper.cpp's token offsets as words; null for any other shape", () => {
+ const doc = {
+ transcription: [
+ {
+ offsets: { from: 9000, to: 12000 },
+ tokens: [
+ { text: "[_BEG_]", offsets: { from: 9000, to: 9000 } },
+ { text: " slow", offsets: { from: 9100, to: 9400 } },
+ { text: " ne", offsets: { from: 9400, to: 9550 } },
+ { text: "ws", offsets: { from: 9550, to: 9700 } },
+ { text: " day", offsets: { from: 9700, to: 10100 } },
+ { text: "[_TT_500]", offsets: { from: 10100, to: 10100 } },
+ ],
+ },
+ { tokens: [{ text: " far", offsets: { from: 90000, to: 90400 } }] },
+ ],
+ };
+ assert.deepEqual(whisperWords(doc, 9, 11), [
+ { start: 9.1, end: 9.4, text: "slow" },
+ { start: 9.4, end: 9.7, text: "news" },
+ { start: 9.7, end: 10.1, text: "day" },
+ ]);
+ assert.equal(whisperWords(doc).length, 4);
+ assert.equal(whisperWords({ chunk_data: [] }), null);
+ assert.equal(whisperWords({ cues: [] }), null);
+ assert.equal(whisperWords(null), null);
+ const words = whisperWords(doc, 9, 11);
+ const hit = locatePhrase("slow news day", words, { from: 9, to: 11 });
+ assert.deepEqual({ start: hit.start, end: Number(hit.end.toFixed(6)) }, { start: 9.1, end: 10.1 });
+});
+
+// ---- the plan across the cut -----------------------------------------------------
+
+test("rampCap: lerp(from, to, k/(n−1)) -- the first clip `from`, the last `to`, linear between", () => {
+ const ramp = { from: 4, to: 1 };
+ assert.deepEqual(rampCaps(4, ramp), [4, 3, 2, 1]);
+ assert.equal(rampCap(0, 1, ramp), 4);
+ assert.equal(rampCap(3, 7, ramp), 2.5);
+ assert.equal(rampCap(2, 4, null), null);
+});
+
+test("planMontage: each clip's place, year change, stutter and edges; cards count as entries, not clips", () => {
+ const timeline = [
+ { id: "t0", type: "card", seconds: 2 },
+ clip("a", { montage: { date: "20190102", platform: "youtube" } }),
+ clip("b", { date: "2019-06-01" }),
+ clip("c"),
+ clip("d", { montage: { date: "20210101" } }),
+ ];
+ const settings = resolveMontage({ montage: { tighten: "phrase", ramp: { from: 4, to: 1 }, stutter: { every: 2, clips: ["a"] } } });
+ const plan = planMontage(timeline, settings, (e) => (e.id === "c" ? "20200303" : null));
+ assert.deepEqual([...plan.keys()], ["a", "b", "c", "d"]);
+ assert.deepEqual([...plan.values()].map((p) => p.k), [0, 1, 2, 3]);
+ assert.deepEqual([...plan.values()].map((p) => p.n), [4, 4, 4, 4]);
+ assert.deepEqual([...plan.values()].map((p) => p.cap), [4, 3, 2, 1]);
+ assert.deepEqual([...plan.values()].map((p) => p.stutter), [true, true, false, true]);
+ assert.deepEqual([...plan.values()].map((p) => p.year), [2019, 2019, 2020, 2021]);
+ assert.deepEqual([...plan.values()].map((p) => p.yearChange), [true, false, true, true]);
+ assert.equal(plan.get("a").platform, "youtube");
+ assert.equal(plan.get("a").first, false, "a card opens the cut");
+ assert.equal(plan.get("d").last, true);
+ const walled = planMontage(timeline.slice(1), resolveMontage({ montage: { wall: { at: "end" } } }));
+ assert.equal(walled.get("a").first, true);
+ assert.equal(walled.get("d").last, false, "the wall closes the cut");
+ const atStart = planMontage(timeline.slice(1), resolveMontage({ montage: { wall: { at: "start" } } }));
+ assert.equal(atStart.get("a").first, false);
+ assert.equal(atStart.get("d").last, true);
+ assert.equal(stutters({ every: 5, clips: [] }, 4, "x"), true);
+ assert.equal(stutters({ every: 5, clips: [] }, 5, "x"), false);
+ assert.equal(stutters(null, 4, "x"), false);
+});
+
+// ---- one clip's cut -------------------------------------------------------------------
+
+const noSnap = () => ({ at: NaN, snapped: false });
+
+test("montageWindow: the phrase ± pad, inside the extent; snapped edges kept only outside the phrase", () => {
+ const sil = [{ s: 1.0, e: 1.5 }, { s: 4.0, e: 4.5 }];
+ const base = { extent: [0, 8], play: [0.5, 7], tighten: "phrase", pad: 0.6, cap: null, silences: sil, snapWindow: 0.4, render: {}, snap };
+ const w = montageWindow({ ...base, phrase: { start: 2, end: 3.1 } });
+ assert.equal(w.tight, true);
+ assert.deepEqual(w.start, { at: 1.4, snapped: true }, "the silence's end, less the 0.10 s lead");
+ assert.deepEqual(w.end, { at: 4.18, snapped: true }, "the silence's start, plus 0.18 s");
+ assert.equal(w.cutA, 1.4);
+ assert.equal(w.cutB, 4.18);
+ // No silence near: the exact pads.
+ const bare = montageWindow({ ...base, silences: [], phrase: { start: 2, end: 3.1 } });
+ assert.equal(bare.cutA, 1.4);
+ assert.ok(Math.abs(bare.cutB - 3.7) < 1e-9);
+ assert.equal(bare.start.snapped, false);
+ // A snap that would land inside the phrase is refused.
+ const inside = montageWindow({ ...base, pad: 0.1, silences: [{ s: 2.2, e: 2.6 }], phrase: { start: 2.5, end: 3.1 } });
+ assert.equal(inside.start.snapped, false);
+ assert.equal(inside.cutA, 2.4);
+ // Never past the extent.
+ const edge = montageWindow({ ...base, extent: [1.8, 3.3], silences: [], phrase: { start: 2, end: 3.1 } });
+ assert.equal(edge.cutA, 1.8);
+ assert.equal(edge.cutB, 3.3);
+});
+
+test("montageWindow: under a ramp the pads are trimmed to the cap, never into the phrase", () => {
+ const base = { extent: [0, 10], play: [0, 10], tighten: "phrase", pad: 2, silences: [], snapWindow: 0.4, render: {}, snap };
+ const w = montageWindow({ ...base, cap: 2, phrase: { start: 4, end: 5 } });
+ assert.ok(Math.abs(w.cutA - 3.5) < 1e-9 && Math.abs(w.cutB - 5.5) < 1e-9, JSON.stringify(w));
+ // One side short of pad: the other takes the room.
+ const lop = montageWindow({ ...base, cap: 2, phrase: { start: 0.2, end: 1.2 } });
+ assert.ok(Math.abs(lop.cutA - 0) < 1e-9 && Math.abs(lop.cutB - 2) < 1e-9, JSON.stringify(lop));
+ // A phrase longer than the cap keeps the phrase.
+ const long = montageWindow({ ...base, cap: 1, phrase: { start: 4, end: 6 } });
+ assert.equal(long.cutA, 4);
+ assert.equal(long.cutB, 6);
+ // A snap that would break the cap is refused.
+ const snapped = montageWindow({ ...base, cap: 2, silences: [{ s: 6, e: 7 }], snapWindow: 1, phrase: { start: 4, end: 5 } });
+ assert.equal(snapped.end.snapped, false);
+ assert.ok(snapped.cutB - snapped.cutA <= 2 + 1e-9);
+});
+
+test("montageWindow: not tightening, or no phrase -- today's play window, snapped as every clip is", () => {
+ const sil = [{ s: 1.0, e: 1.5 }, { s: 4.0, e: 4.5 }];
+ const want = (w0, w1) => {
+ const a = snap(w0, sil, "start", 0.4, {});
+ const b = snap(w1, sil, "end", 0.4, {});
+ const cutA = Math.min(a.at, w1 - 1);
+ return { cutA, cutB: Math.max(b.at, cutA + 1), start: a, end: b, tight: false };
+ };
+ const base = { extent: [0, 8], play: [1.3, 4.1], pad: 0.6, cap: null, silences: sil, snapWindow: 0.4, render: {}, snap };
+ assert.deepEqual(montageWindow({ ...base, tighten: "sentence", phrase: { start: 2, end: 3 } }), want(1.3, 4.1));
+ assert.deepEqual(montageWindow({ ...base, tighten: null, phrase: { start: 2, end: 3 } }), want(1.3, 4.1));
+ assert.deepEqual(montageWindow({ ...base, tighten: "phrase", phrase: null }), want(1.3, 4.1));
+ assert.deepEqual(montageWindow({ ...base, tighten: "phrase", phrase: { start: 9, end: 10 } }), want(1.3, 4.1), "outside the extent");
+ void noSnap;
+});
+
+// ---- the pieces ------------------------------------------------------------------
+
+test("montagePieces: one piece; a snap punch-in at the onset; a stutter of the phrase's end", () => {
+ assert.deepEqual(montagePieces({ frames: 90, fps: 30 }), [{ f0: 0, f1: 90, zoom: 1 }]);
+ const snapIn = montagePieces({ frames: 90, fps: 30, onset: 1, punch: { mode: "snap", scale: 1.15 } });
+ assert.deepEqual(snapIn, [{ f0: 0, f1: 30, zoom: 1 }, { f0: 30, f1: 90, zoom: 1.15 }]);
+ // A drift has no pieces of its own (it zooms the whole segment).
+ assert.deepEqual(montagePieces({ frames: 90, fps: 30, onset: 1, punch: { mode: "drift", scale: 1.08 } }), [{ f0: 0, f1: 90, zoom: 1 }]);
+ const st = montagePieces({
+ frames: 90, fps: 30, onset: 1, phraseEnd: 2, punch: { mode: "snap", scale: 1.15 },
+ stutter: { times: 3, length: 0.35, step: 0.04 },
+ });
+ // Fragment = frames 49..60 (0.35 s = 10.5 → 11 frames) heard three times, each a step more zoomed.
+ assert.deepEqual(st, [
+ { f0: 0, f1: 30, zoom: 1 },
+ { f0: 30, f1: 49, zoom: 1.15 },
+ { f0: 49, f1: 60, zoom: 1.15 },
+ { f0: 49, f1: 60, zoom: 1.196, repeat: 1 },
+ { f0: 49, f1: 60, zoom: 1.242, repeat: 2 },
+ { f0: 60, f1: 90, zoom: 1.15 },
+ ]);
+ assert.equal(piecesFrames(st), 112);
+ // No room for a fragment: no stutter.
+ assert.deepEqual(montagePieces({ frames: 90, fps: 30, phraseEnd: 0.05, stutter: { times: 3, length: 0.35, step: 0 } }).length, 1);
+ // Never outside the cut.
+ assert.deepEqual(montagePieces({ frames: 30, fps: 30, phraseEnd: 5, stutter: { times: 2, length: 0.2, step: 0 } }), [
+ { f0: 0, f1: 24, zoom: 1 }, { f0: 24, f1: 30, zoom: 1 }, { f0: 24, f1: 30, zoom: 1, repeat: 1 },
+ ]);
+});
+
+test("montagePiecesGraph: one piece is a straight run; pieces are split, trimmed, zoomed, joined; drift is a zoompan", () => {
+ const box = { w: 320, h: 180 };
+ const one = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box, bg: "#000000" });
+ assert.equal(one.frames, 90);
+ assert.equal(one.seconds, 3);
+ assert.equal(one.v, "[mv]");
+ assert.equal(one.a, "[ma]");
+ assert.deepEqual(one.parts, [
+ "[0:v]fps=30[mvs0]",
+ "[0:a]anull[mas0]",
+ "[mvs0]trim=start_frame=0:end_frame=90,setpts=PTS-STARTPTS,scale=320:180:force_original_aspect_ratio=decrease,pad=320:180:(ow-iw)/2:(oh-ih)/2:color=#000000,setsar=1[mv0]",
+ "[mas0]atrim=start=0:end=3,asetpts=PTS-STARTPTS[ma0]",
+ "[mv0]null[mvc]",
+ "[ma0]anull[mac]",
+ "[mvc]tpad=stop_mode=clone:stop_duration=1,trim=end_frame=90,setpts=PTS-STARTPTS[mv]",
+ `[mac]apad=whole_dur=3,atrim=end=3,afade=t=in:d=${DECLICK},afade=t=out:st=2.985:d=${DECLICK}[ma]`,
+ ]);
+ const two = montagePiecesGraph({ pieces: [{ f0: 0, f1: 30, zoom: 1 }, { f0: 30, f1: 90, zoom: 1.15 }], fps: 30, box, bg: "#000000" });
+ assert.equal(two.parts[0], "[0:v]fps=30,split=2[mvs0][mvs1]");
+ assert.equal(two.parts[1], "[0:a]asplit=2[mas0][mas1]");
+ assert.match(two.parts[4], /^\[mvs1\]trim=start_frame=30:end_frame=90,setpts=PTS-STARTPTS,crop=w='floor\(iw\/1\.15\/2\)\*2':h='floor\(ih\/1\.15\/2\)\*2':x='\(iw-ow\)\/2':y='\(ih-oh\)\*0\.35',scale=320:180/);
+ assert.match(two.parts[5], /^\[mas1\]atrim=start=1:end=3,asetpts=PTS-STARTPTS,afade=t=in:d=0\.005,afade=t=out:st=1\.995:d=0\.005\[ma1\]$/);
+ assert.equal(two.parts[6], "[mv0][ma0][mv1][ma1]concat=n=2:v=1:a=1[mvc][mac]");
+ const drift = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box, bg: "#000000", punch: { mode: "drift", scale: 1.08, anchor: "center" } });
+ assert.match(drift.parts.at(-2), /scale=640:360,zoompan=z='1\+0\.08\*on\/89':x='iw\/2-iw\/zoom\/2':y='\(ih-ih\/zoom\)\*0\.5':d=1:s=320x180:fps=30,setsar=1\[mv\]$/);
+ const deaf = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box, bg: "#000000", inA: "[mpa]", hasVideo: false });
+ assert.equal(deaf.v, null);
+ assert.ok(deaf.parts.every((p) => !p.includes("[0:v]")));
+ assert.equal(deaf.parts[0], "[mpa]anull[mas0]");
+});
+
+// ---- the cut styles ----------------------------------------------------------------
+
+test("cutStyleParts: hard is nothing; flash fades in from the colour; dip to black and up; edges of the cut left alone", () => {
+ const base = { frames: 90, fps: 30, w: 320, h: 180, inLabel: "[v]", outLabel: "[o]" };
+ assert.deepEqual(cutStyleParts({ ...base, cut: "hard", first: false, last: false }), ["[v]null[o]"]);
+ assert.deepEqual(cutStyleParts({ ...base, cut: "flash", first: false, last: false, flashColor: "#ffffff" }), ["[v]fade=t=in:st=0:d=0.1:color=#ffffff[o]"]);
+ assert.equal(CUT_FRAMES.flash, 3);
+ assert.deepEqual(cutStyleParts({ ...base, cut: "flash", first: true, last: false }), ["[v]null[o]"], "nothing to cut from");
+ assert.deepEqual(cutStyleParts({ ...base, cut: "dip", first: false, last: false }), ["[v]fade=t=in:st=0:d=0.0667,fade=t=out:st=2.9:d=0.0667[o]"]);
+ assert.deepEqual(cutStyleParts({ ...base, cut: "dip", first: true, last: false }), ["[v]fade=t=out:st=2.9:d=0.0667[o]"]);
+ assert.deepEqual(cutStyleParts({ ...base, cut: "dip", first: true, last: true }), ["[v]null[o]"]);
+});
+
+test("cutStyleParts: whip slides the first four frames in and the last four out, blurred along the move", () => {
+ const base = { frames: 90, fps: 30, w: 320, h: 180, inLabel: "[v]", outLabel: "[o]", cut: "whip" };
+ const both = cutStyleParts({ ...base, first: false, last: false });
+ assert.equal(both[0], "[v]split=3[wph][wpb][wpt]");
+ assert.equal(both[1], "[wph]trim=end_frame=4,setpts=PTS-STARTPTS,split[wh1][wh2]");
+ assert.equal(both[2], "[wh1][wh2]hstack,crop=w=320:h=180:x='320*(1-0.9*pow(1-(n+1)/5,2))':y=0,avgblur=sizeX=11:sizeY=1[wh]");
+ assert.equal(both[3], "[wpb]trim=start_frame=4:end_frame=86,setpts=PTS-STARTPTS[wb]");
+ assert.equal(both[4], "[wpt]trim=start_frame=86,setpts=PTS-STARTPTS,split[wt1][wt2]");
+ assert.equal(both[5], "[wt1][wt2]hstack,crop=w=320:h=180:x='320*0.9*pow((n+1)/5,2)':y=0,avgblur=sizeX=11:sizeY=1[wt]");
+ assert.equal(both[6], "[wh][wb][wt]concat=n=3:v=1:a=0[o]");
+ const opening = cutStyleParts({ ...base, first: true, last: false });
+ assert.equal(opening[0], "[v]split=2[wpb][wpt]");
+ assert.equal(opening.at(-1), "[wb][wt]concat=n=2:v=1:a=0[o]");
+ assert.deepEqual(cutStyleParts({ ...base, first: true, last: true }), ["[v]null[o]"]);
+ assert.deepEqual(cutStyleParts({ ...base, frames: 8, first: false, last: false }), ["[v]null[o]"], "too short to whip");
+});
+
+// ---- the counter and the year stamp ----------------------------------------------------
+
+test("tallyMarks: four uprights struck through by the fifth, ten groups a row; the last mark is the newest", () => {
+ const t = tallyMarks(7, 1080);
+ assert.equal(t.marks.length, 7);
+ assert.deepEqual(t.marks.map((m) => m.strike), [false, false, false, false, true, false, false]);
+ assert.ok(t.marks[4].w > t.marks[4].h, "the strike lies across");
+ assert.ok(t.marks[5].x > t.marks[3].x, "the second group starts right of the first");
+ const many = tallyMarks(55, 1080);
+ assert.ok(many.marks[50].y > many.marks[0].y, "the eleventh group starts a second row");
+ assert.ok(many.height > t.height);
+ for (const m of many.marks) assert.ok(m.x >= 0 && m.x + m.w <= many.width && m.y + m.h <= many.height, JSON.stringify(m));
+});
+
+const RENDER_1080 = { width: 1920, height: 1080, fps: 30, palette: PALETTE };
+const CTX = { k: 11, n: 75, date: { y: 2019, m: 5, d: 2 }, platform: "youtube", year: 2019, yearChange: true };
+
+test("montageOverlayFilters: the chip -- one drawtext on its ground, in its corner", () => {
+ const settings = resolveMontage({ montage: { counter: { style: "chip", of: true, showSource: true } } });
+ const f = montageOverlayFilters({ settings, ctx: CTX, render: RENDER_1080, font: "/f.ttf" });
+ assert.equal(f.length, 1);
+ assert.match(f[0], /^drawtext=fontfile='\/f\.ttf':expansion=none:text='#12 of 75 · 2 May 2019 · YouTube':fontsize=37:fontcolor=#ece8f4:box=1:boxcolor=#15121c@0\.72:boxborderw=17:x=55:y=55$/);
+ const br = montageOverlayFilters({ settings: resolveMontage({ montage: { counter: { position: "bottom-right" } } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" });
+ assert.match(br[0], /:x=W-55-text_w:y=H-55-text_h$/);
+});
+
+test("montageOverlayFilters: big slams in and goes; tally draws k+1 marks, the newest late; the year stamp across from the counter", () => {
+ const big = montageOverlayFilters({ settings: resolveMontage({ montage: { counter: { style: "big", position: "bottom-left" } } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" });
+ assert.equal(big.length, 2);
+ assert.match(big[0], /text='12':fontsize='259\*\(1\+0\.9\*max\(0,1-t\/0\.18\)\)':fontcolor=#7c5cff/);
+ assert.match(big[0], /alpha='min\(1,t\/0\.04\)\*if\(lt\(t,1\.2\),1,max\(0,1-\(t-1\.2\)\/0\.3\)\)'/);
+ assert.match(big[1], /text='2 May 2019'/);
+ const tally = montageOverlayFilters({ settings: resolveMontage({ montage: { counter: { style: "tally", showDate: false } } }), ctx: { ...CTX, k: 6 }, render: RENDER_1080, font: "/f.ttf" });
+ assert.equal(tally.length, 1 + 7, "the ground and seven marks");
+ assert.match(tally[0], /^drawbox=.*:color=#15121c@0\.6:t=fill$/);
+ assert.ok(tally.slice(1, -1).every((d) => /color=#ece8f4:t=fill$/.test(d)));
+ assert.match(tally.at(-1), /color=#7c5cff:t=fill:enable='gte\(t,0\.12\)'$/);
+ const year = montageOverlayFilters({ settings: resolveMontage({ montage: { yearStamp: true, counter: { position: "top-left" } } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" });
+ assert.equal(year.length, 2);
+ assert.match(year[1], /text='2019':fontsize=173:.*:x=W-38-text_w:y=38$/);
+ assert.deepEqual(montageOverlayFilters({ settings: resolveMontage({ montage: { yearStamp: true } }), ctx: { ...CTX, yearChange: false }, render: RENDER_1080, font: "/f.ttf" }), []);
+ assert.match(montageOverlayFilters({ settings: resolveMontage({ montage: { yearStamp: true } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" })[0], /x=W-38-text_w:y=38$/, "no counter: top right");
+ assert.deepEqual(montageOverlayFilters({ settings: resolveMontage({ montage: {} }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" }), []);
+});
+
+// ---- the wall -------------------------------------------------------------------------
+
+test("wallTileClips: spread evenly first to last; fewer clips go round again", () => {
+ assert.deepEqual(wallTileClips(["a", "b", "c", "d", "e", "f", "g", "h", "i"], 9), ["a", "b", "c", "d", "e", "f", "g", "h", "i"]);
+ const ids = Array.from({ length: 75 }, (_, i) => `s${i + 1}`);
+ const t = wallTileClips(ids, 16);
+ assert.equal(t.length, 16);
+ assert.equal(t[0], "s1");
+ assert.equal(t[15], "s75");
+ assert.equal(new Set(t).size, 16);
+ assert.deepEqual(wallTileClips(["a", "b", "c"], 9), ["a", "b", "c", "a", "b", "c", "a", "b", "c"]);
+ assert.deepEqual(wallTileClips([], 9), []);
+});
+
+test("wallPlan: a centred grid inside the frame; tiles come faster and faster; the beat; all on frames", () => {
+ const p = wallPlan({ tiles: 16, build: 8, durations: Array(16).fill(1.2), fps: 30, width: 1920, height: 1080 });
+ assert.equal(p.cols, 4);
+ assert.equal(p.layout.length, 16);
+ for (const l of p.layout) assert.ok(l.x >= 0 && l.y >= 0 && l.x + l.w <= 1920 && l.y + l.h <= 1080, JSON.stringify(l));
+ assert.equal(p.tileW % 2, 0);
+ assert.equal(p.tileH % 2, 0);
+ assert.ok(Math.abs(p.tileW / p.tileH - 16 / 9) < 0.02);
+ assert.equal(p.layout[1].x - p.layout[0].x, p.tileW + p.gap);
+ assert.equal(p.appear[0], 0);
+ const gaps = p.appear.slice(1).map((t, i) => t - p.appear[i]);
+ for (let i = 1; i < gaps.length; i += 1) assert.ok(gaps[i] <= gaps[i - 1] + 1e-9, `gaps shrink: ${gaps}`);
+ assert.ok(p.appear.at(-1) < p.beat);
+ assert.equal(p.beat, 8);
+ assert.equal(p.beatLen, Math.round((1.2 + 0.25) * 30) / 30);
+ assert.equal(p.frames, 240 + Math.round(1.45 * 30));
+ assert.equal(p.seconds, p.frames / 30);
+ for (const f of p.appearFrames) assert.ok(Number.isInteger(f));
+ // The beat is the longest phrase, held to 0.8–2.5 s.
+ assert.equal(wallPlan({ tiles: 9, build: 4, durations: [9], fps: 30, width: 1920, height: 1080 }).beatLen, Math.round(2.75 * 30) / 30);
+ assert.equal(wallPlan({ tiles: 25, build: 4, durations: [0.1], fps: 30, width: 1920, height: 1080 }).cols, 5);
+});
+
+test("wallComposeArgs: each tile appears, plays, freezes and plays again at the beat; the newest up, the rest ducked; exactly its frames", () => {
+ const plan = wallPlan({ tiles: 9, build: 3, durations: Array(9).fill(1), fps: 30, width: 320, height: 180 });
+ const tiles = Array.from({ length: 9 }, (_, i) => ({ file: `/t/${i}.mp4`, seconds: 1 }));
+ const settings = resolveMontage({ montage: { cut: "flash", wall: { tiles: 9 } } });
+ const args = wallComposeArgs({ tiles, plan, render: { width: 320, height: 180, fps: 30, palette: PALETTE }, settings, first: false, last: true, encode: ["-c:v", "libx264"], outPath: "/o.mp4" });
+ const graph = args[args.indexOf("-filter_complex") + 1];
+ assert.equal(args.filter((a) => a === "-i").length, 9);
+ assert.match(graph, /\[0:v\]split\[wv0a\]\[wv0b\]/);
+ assert.match(graph, new RegExp(`tpad=start_duration=${plan.appear[4].toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}:start_mode=add:color=#15121c`));
+ assert.match(graph, /xstack=inputs=9:layout=0_0\|/);
+ assert.match(graph, /volume='if\(lt\(t,[\d.]+\),1,0\.22\)':eval=frame/);
+ assert.match(graph, /amix=inputs=18:normalize=0:duration=longest,alimiter=limit=0\.9/);
+ assert.match(graph, /fade=t=in:st=0:d=0\.1:color=#ffffff\[v\]/, "the cut into the wall flashes");
+ assert.equal(args[args.indexOf("-frames:v") + 1], String(plan.frames));
+});
+
+// ---- real renders ---------------------------------------------------------------------
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const FPS = 30;
+const RENDER = {
+ width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0,
+ headerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ snapWindow: 0.4, silenceMinDur: 0.1,
+};
+
+/**
+ * Four six-second clips: mid grey with a white bar at x 40–60 (something for
+ * a whip to move), and a tone that sounds 1 s in every 1.5 (silences to snap
+ * to). Their cues say "slow news day" from 2.0 s; the years run 2019–2022.
+ */
+async function fixture(montage, { extraRender = {} } = {}) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "rtv-montage-"));
+ await mkdir(path.join(root, "media"), { recursive: true });
+ const timeline = [];
+ for (let i = 1; i <= 4; i += 1) {
+ const file = path.join(root, "media", `c${i}.mp4`);
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=${FPS}:d=6`,
+ "-f", "lavfi", "-i", `aevalsrc='0.5*sin(2*PI*${300 + 40 * i}*t)*between(mod(t,1.5),0,1.0)':s=48000:d=6`,
+ "-vf", "drawbox=x=40:y=0:w=20:h=180:color=white:t=fill", "-c:v", "libx264", "-preset", "ultrafast",
+ "-c:a", "aac", "-shortest", file,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ await writeFile(path.join(root, "media", `c${i}.json`), JSON.stringify({
+ cues: [
+ { start: 0.2, end: 2.0, text: "well folks it is a" },
+ { start: 2.0, end: 3.6, text: "slow news day again" },
+ { start: 3.6, end: 5.8, text: "and here we go" },
+ ],
+ }));
+ timeline.push({
+ id: `c${i}`, type: "clip", src: `media/c${i}.mp4`, cues: `media/c${i}.json`, start: 0.2, end: 5.8,
+ title: `Clip ${i}`, channelTitle: "Demo",
+ montage: { n: i, date: `20${18 + i}0${i}0${i}`, platform: "youtube", match: "slow news day", speakerCheck: false },
+ });
+ }
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "demo", title: "Demo", render: { ...RENDER, ...extraRender, montage }, timeline,
+ }));
+ return { root, manifestPath };
+}
+
+function framesOf(file) {
+ const r = spawnSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return Number(String(r.stdout).trim());
+}
+
+/** A signalstats value (YAVG: mean luma 0–255; YHIGH: its 90th percentile) of frame `n` of `file` inside a crop `w:h:x:y`. */
+function luma(file, n, crop, key = "YAVG") {
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-i", file, "-vf", `select='eq(n,${n})',crop=${crop},signalstats,metadata=print:key=lavfi.signalstats.${key}:file=-`,
+ "-frames:v", "1", "-f", "null", "-",
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ const m = String(r.stdout).match(new RegExp(`${key}=([\\d.]+)`));
+ assert.ok(m, `no ${key} for frame ${n}`);
+ return Number(m[1]);
+}
+
+/** Mean U (chroma blue, 128 neutral) of frame `n` inside a crop. */
+function chromaU(file, n, crop) {
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-i", file, "-vf", `select='eq(n,${n})',crop=${crop},signalstats,metadata=print:key=lavfi.signalstats.UAVG:file=-`,
+ "-frames:v", "1", "-f", "null", "-",
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return Number(String(r.stdout).match(/UAVG=([\d.]+)/)[1]);
+}
+
+/** The cut records' planned frames, per clip in order, and their sum (+ the wall's). */
+async function planned(root, ids, wall = false) {
+ const seg = path.join(root, "out", "sourced", "segments");
+ const recs = await Promise.all(ids.map(async (id) => JSON.parse(await readFile(path.join(seg, `${id}.cut.json`), "utf8"))));
+ const frames = recs.map((r) => r.montage.frames);
+ const wallFrames = wall ? JSON.parse(await readFile(path.join(seg, "montage-wall.cut.json"), "utf8")).montageWall.frames : 0;
+ return { recs, frames, total: frames.reduce((a, b) => a + b, 0) + wallFrames, wallFrames };
+}
+
+const IDS = ["c1", "c2", "c3", "c4"];
+const styled = (name, patch = {}) => mergePatch(applyMontageStyle({ render: {} }, name).render.montage, patch);
+
+test("render: without render.montage (absent or null) the cut is byte for byte the same", { skip: !have && "needs ffmpeg" }, async () => {
+ const a = await fixture(undefined);
+ const b = await fixture(null);
+ try {
+ await buildVideo({ manifestPath: a.manifestPath, opts: { noNetwork: true } });
+ await buildVideo({ manifestPath: b.manifestPath, opts: { noNetwork: true } });
+ const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0];
+ for (const f of ["demo.mp4", "sourced/segments/c2.mp4"]) {
+ 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.montage, undefined, "no montage in the cut record");
+ } finally {
+ await rm(a.root, { recursive: true, force: true });
+ await rm(b.root, { recursive: true, force: true });
+ }
+});
+
+test("render: straight -- each clip cut to its phrase, the length the plan says to the frame, the chip on the picture", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture(styled("straight"));
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS);
+ for (const rec of p.recs) {
+ assert.equal(rec.montage.found, "cues");
+ assert.equal(rec.montage.tight, true);
+ // Phrase 2.0–3.095 ± 0.6, snapped to the silences at 1.5 and 4.0.
+ assert.deepEqual([rec.start, rec.end], [1.4, 4.18]);
+ assert.deepEqual(rec.montage.phrase, [2, 3.095]);
+ assert.equal(rec.montage.frames, 83);
+ }
+ for (const id of IDS) assert.equal(framesOf(path.join(root, "out", "sourced", "segments", `${id}.mp4`)), 83, id);
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1, `${framesOf(r.out)} vs ${p.total}`);
+ // The chip's ground darkens the grey top-left; the bottom-left is untouched.
+ assert.ok(luma(r.out, 100, "40:8:8:8") < 110, "chip ground");
+ assert.ok(Math.abs(luma(r.out, 100, "60:20:200:150") - 128) < 8, "plain grey elsewhere");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: flash-count -- a white flash on the cut, not before; the big number slams in in the accent", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture(styled("flash-count"));
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS);
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1);
+ const cut = p.frames[0];
+ assert.ok(luma(r.out, cut, "100:60:200:20") > 225, "the first frame of clip 2 is the flash");
+ assert.ok(luma(r.out, cut - 1, "100:60:200:20") < 140, "the frame before the cut is not");
+ assert.ok(luma(r.out, cut + 4, "100:60:200:20") < 140, "and it is gone by the fourth frame");
+ assert.ok(luma(r.out, 0, "100:60:200:20") < 140, "the cut's first clip opens without one");
+ // The number, in the accent (blue-heavy), bottom-left early in the clip -- gone by 1.6 s.
+ assert.ok(chromaU(r.out, cut + 12, "40:40:6:130") > 134, "the accent number");
+ assert.ok(Math.abs(chromaU(r.out, cut + 60, "40:40:6:130") - 128) < 3, "gone");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: accelerate -- the cuts shorten along the ramp, drift, tally marks; length to the frame", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture(styled("accelerate", { ramp: { from: 2.6, to: 1.2 } }));
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS);
+ const caps = rampCaps(4, { from: 2.6, to: 1.2 });
+ p.recs.forEach((rec, k) => {
+ assert.ok(rec.end - rec.start <= caps[k] + 0.002, `${rec.id}: ${rec.end - rec.start} > ${caps[k]}`);
+ assert.ok(rec.start <= 2.0 && rec.end >= 3.095, `${rec.id} keeps the phrase`);
+ });
+ for (let k = 1; k < 4; k += 1) assert.ok(p.frames[k] < p.frames[k - 1], `shorter: ${p.frames}`);
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1);
+ // The fourth clip's tally: its newest mark lands at 0.12 s.
+ const at = p.frames[0] + p.frames[1] + p.frames[2];
+ const t = tallyMarks(4, 180);
+ const pad = Math.round(180 * 0.012);
+ const m = Math.round(180 * 0.035);
+ const nm = t.marks[3];
+ const crop = `${nm.w}:${nm.h}:${m + pad + nm.x}:${m + pad + nm.y}`;
+ assert.ok(luma(r.out, at + 8, crop) > luma(r.out, at, crop) + 15, "the newest mark is drawn at 0.12 s");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: stutter -- the stuttered clip is longer by its repeats; snap punch-in at the onset", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture(styled("stutter", { stutter: { every: null, clips: ["c2"] } }));
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS);
+ const c2 = p.recs[1].montage;
+ const repeats = c2.pieces.filter((x) => x.repeat);
+ assert.equal(repeats.length, 2, "heard three times");
+ const frag = repeats[0].f1 - repeats[0].f0;
+ assert.equal(frag, Math.round(0.35 * FPS));
+ assert.equal(c2.frames, 83 + 2 * frag);
+ assert.equal(p.recs[0].montage.pieces.filter((x) => x.repeat).length, 0);
+ assert.equal(framesOf(path.join(root, "out", "sourced", "segments", "c2.mp4")), c2.frames);
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1);
+ // The punch-in: the bar (x 40–60) moves outward and widens at the onset (0.6 s in).
+ const seg = path.join(root, "out", "sourced", "segments", "c1.mp4");
+ assert.ok(luma(seg, 5, "12:120:44:50") > 230, "before the onset the bar is where it was");
+ assert.ok(luma(seg, 40, "6:120:30:50") > 200, "after it the bar has moved left, as a zoom from the centre moves it");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: wall-finale -- a wall segment after the clips, every tile filled at the end; length to the frame", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture(styled("wall-finale", { wall: { tiles: 9, build: 2 } }));
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS, true);
+ assert.ok(p.wallFrames > 60);
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1, `${framesOf(r.out)} vs ${p.total}`);
+ const plan = wallPlan({ tiles: 9, build: 2, durations: [1], fps: FPS, width: 320, height: 180 });
+ const start = p.total - p.wallFrames;
+ const last = plan.layout[8];
+ const tile = `${last.w - 4}:${last.h - 4}:${last.x + 2}:${last.y + 2}`;
+ // The last tile is ground at the wall's start and footage (grey, with the
+ // year) by the beat.
+ assert.ok(luma(r.out, start + 2, tile) < 40, "empty at first");
+ assert.ok(luma(r.out, p.total - 3, tile) > 100, "filled by the end");
+ const wall = JSON.parse(await readFile(path.join(root, "out", "sourced", "segments", "montage-wall.cut.json"), "utf8"));
+ assert.deepEqual(wall.montageWall.tiles, ["c1", "c2", "c3", "c4", "c1", "c2", "c3", "c4", "c1"]);
+ // The chapters name it.
+ const ch = spawnSync("ffprobe", ["-v", "error", "-show_chapters", "-of", "json", r.out]);
+ const titles = JSON.parse(String(ch.stdout)).chapters.map((c) => c.tags?.title);
+ assert.equal(titles.length, 5);
+ assert.equal(titles.at(-1), "All together");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: whip-years -- the bar slides at the cut; the year large across from the chip", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture(styled("whip-years"));
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS);
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1);
+ const cut = p.frames[0];
+ // Mid-clip the bar is at x 40–60; on the incoming whip's first frame it has
+ // been carried right (shifted ~0.58 of the width), blurred.
+ assert.ok(luma(r.out, cut - 30, "16:40:42:120") > 230, "the bar where it is");
+ assert.ok(luma(r.out, cut, "16:40:42:120") < 200, "gone from there on the whip");
+ assert.ok(luma(r.out, cut, "60:40:200:120") > luma(r.out, cut - 30, "60:40:200:120") + 4, "carried right, smeared");
+ // The year stamp: top right, early in each clip (every clip is a new year), gone by 1.4 s.
+ assert.ok(luma(r.out, cut + 10, "80:30:236:6", "YHIGH") > 200, "the year");
+ assert.ok(luma(r.out, cut + 45, "80:30:236:6", "YHIGH") < 140, "then not");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("render: dip -- two frames to black before the cut, two up from it", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture({ tighten: "phrase", cut: "dip" });
+ try {
+ const r = await buildVideo({ manifestPath, opts: { noNetwork: true } });
+ const p = await planned(root, IDS);
+ const cut = p.frames[0];
+ const box = "100:60:200:20";
+ assert.ok(luma(r.out, cut - 1, box) < 30, "the last frame before the cut is black");
+ assert.ok(luma(r.out, cut, box) < 30, "and the first after it");
+ assert.ok(luma(r.out, cut + 3, box) > 110, "then the picture");
+ assert.ok(luma(r.out, cut - 4, box) > 110, "and before the dip");
+ assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});