Archilyzer · Source

archilyzer

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

commit 8ef4e347bd21709ff0770608dcd6f03694758740
parent f38de8ea7163d611bc7e0e07da5d5894043e6dde
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 02:37:09 -0400

umtool: montage polish — a wall's repeats kept apart (wall.spread "stream", wall.distinct), even loudness (render.montage.loudness), tile labels (wall.label)

wall.spread "stream": a deterministic swap descent places the tiles so no two of one stream touch across a
row or a column where avoidable, moving few tiles from their cells (the groups keep their membership and date
order). A clip's stream is its montage.stream, else its day (a stream and its mirror share a date, not an id),
else its video. wall.distinct: one tile per stream (a tail takes the latest of each stream, then the latest of
the rest); refused beside exclusive, where it would put a later clip back in the run before the wall.
render.montage.loudness {target, mode: "clip"}: each clip's cut and each wall tile measured once (ebur128
integrated) and given one gain to the target (±20 dB, none below −60 LUFS), then a −1 dBFS lookahead limiter
with no auto-level; the crowd beat limited as before. wall.label "year" | "number" | "both" (year: true is
"year"). Every style now levels (loudness −16); build-to-wall labels "#n · year" and spreads by stream.
Manifests without the new keys render byte for byte as main's (wall-finale, accelerate, build-to-wall as main
wrote them).

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

Diffstat:
Mumtool/report-to-video/build-video.mjs | 49++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/report-to-video/montage-styles.mjs | 13++++++++++---
Mumtool/report-to-video/montage.mjs | 210++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/report-to-video/montage.test.mjs | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
4 files changed, 438 insertions(+), 33 deletions(-)

diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -181,7 +181,7 @@ import { clipPhrase, cutStyleParts, locatePhrase, montageFont, montageOn, montageOverlayFilters, montagePieces, montagePiecesGraph, montageSplit, montageWindow, parseClipDate, planMontage, refineOnset, resolveMontage, bandFeatures, consensusLags, templateOnset, - validateMontage, wallComposeArgs, WALL_ENTRY, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords, + validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, loudnessGain, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords, } from "./montage.mjs"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; @@ -1321,7 +1321,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // 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; + // Even loudness (render.montage.loudness): the cut's sound measured, one gain. + const level = mont?.settings.loudness ? await montageLevel(raw, cutA, cutB, mont.settings.loudness) : null; + const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB, gainDb: level?.gain ?? null }) : 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] @@ -1364,7 +1366,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ], { maxBuffer: 1 << 24 }, ); - await writeCutRecord(seg, mont ? { ...cutRecord, montage: mg.record } : cutRecord); + await writeCutRecord(seg, mont ? { ...cutRecord, montage: level ? { ...mg.record, loudness: level } : mg.record } : cutRecord); if (mont) { dirs.montage.cuts.set(entry.id, { raw, cutA, cutB, phrase: mont.phrase, via: mont.via, year: mont.ctx.year, hasVideo: media.hasVideo, @@ -1476,6 +1478,24 @@ async function montageWallSource({ entry, M, render, provenance, local, opts }) } /** + * A stretch of a source's integrated loudness (LUFS, ffmpeg's ebur128), or + * null when it cannot be measured. + */ +async function measureLoudness(raw, from, to) { + const { stderr } = await execFileP(FFMPEG, [ + "-nostdin", "-hide_banner", "-ss", Math.max(0, from).toFixed(3), "-to", to.toFixed(3), "-i", raw, + "-vn", "-af", "ebur128", "-f", "null", "-", + ], { maxBuffer: 1 << 26 }).catch((e) => ({ stderr: e.stderr ?? "" })); + return parseIntegratedLoudness(stderr); +} + +/** The gain that brings a stretch of a source to the montage's loudness target: `{ measured, gain, target }`. */ +async function montageLevel(raw, from, to, loudness) { + const measured = await measureLoudness(raw, from, to); + return { measured, gain: loudnessGain(measured, loudness.target), target: loudness.target }; +} + +/** * `seconds` of a source's sound from `from` (raw-file seconds, may be * negative), speech band (high-passed at 200 Hz), 16 kHz mono, as samples; * silence where the file has none, so the excerpt is always that long. @@ -1537,7 +1557,7 @@ async function wallOnsets(tiles) { * 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 }) { +function montageSegmentGraph({ mont, render, box, hasVideo, cutA, cutB, gainDb = null }) { const { settings: s, ctx } = mont; const fps = render.fps; const frames = Math.max(1, Math.floor((cutB - cutA) * fps + 1e-6)); @@ -1549,7 +1569,7 @@ function montageSegmentGraph({ mont, render, box, hasVideo, cutA, cutB }) { }); const g = montagePiecesGraph({ pieces, fps, box, bg: render.palette.bg, punch: hasVideo ? s.punch : null, - inA: hasVideo ? "[0:a]" : "[mpa]", hasVideo, + inA: hasVideo ? "[0:a]" : "[mpa]", hasVideo, gainDb, }); const overlays = montageOverlayFilters({ settings: s, ctx, render, font: montageFont(render) }); return { @@ -1626,13 +1646,23 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan const tiles = chosen.map((id) => { const c = M.cuts.get(id); const t = sources.get(id); - return { id, raw: c.raw, from: t.from, to: t.to, lead: t.lead, year: w.year ? c.year : null }; + const number = M.ctx.get(id)?.number ?? null; + return { + id, raw: c.raw, from: t.from, to: t.to, lead: t.lead, + // Today's `year: true` labels each tile with its year; `label` says what. + ...(w.label && w.label !== "year" ? { text: wallTileLabel(w.label, { number, year: c.year }) } : { year: w.label === "year" ? c.year : null }), + }; }); + // Repeats of one stream kept apart in the grid (wall.spread "stream"). + const byId = new Map((timeline ?? []).filter((e) => e?.type === "clip").map((e) => [e.id, e])); + const cells = w.spread === "stream" ? wallCells(chosen.map((id) => clipStream(byId.get(id))), Math.round(Math.sqrt(chosen.length))) : null; const plan = wallPlan({ tiles: tiles.length, build: w.build, durations: tiles.map((t) => t.to - t.from), fps: render.fps, width: render.width, height: render.height, ...(w.groups === "double" || w.sync ? { groups: w.groups, leads: w.sync ? tiles.map((t) => t.lead) : null } : {}), + ...(cells ? { cells } : {}), }); + const levels = new Map(); const dir = path.join(outDir, "segments", "montage-wall"); await rm(dir, { recursive: true, force: true }); await mkdir(dir, { recursive: true }); @@ -1641,9 +1671,12 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan for (const t of tiles) { if (!made.has(t.id)) { const file = path.join(dir, `${t.id}.mp4`); + const level = s.loudness ? await montageLevel(t.raw, t.from, t.to, s.loudness) : null; + if (level) levels.set(t.id, level); 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, + year: t.year ?? null, ...(t.text !== undefined ? { text: t.text } : {}), ...(level ? { gainDb: level.gain } : {}), + font: montageFont(render), render, encode: encodeArgs(render), outPath: file, }), { maxBuffer: 1 << 24 }); made.set(t.id, file); } @@ -1659,6 +1692,8 @@ async function buildMontageWall({ M, entries, render, outDir, timeline, provenan if (plan.grouped) { Object.assign(record, { groups: plan.groups, groupBeats: plan.groupBeats, restart: plan.restart, leads: plan.leads }); } + if (cells) record.cells = cells; + if (levels.size) record.loudness = Object.fromEntries(levels); if (w.sync) { if (onsets?.anchor != null) record.syncAnchor = onsets.anchor; record.sync = tiles.map((t) => ({ id: t.id, raw: t.raw, from: Number(t.from.toFixed(3)), ...sources.get(t.id).sync })); diff --git a/umtool/report-to-video/montage-styles.mjs b/umtool/report-to-video/montage-styles.mjs @@ -34,14 +34,18 @@ const OFF = Object.freeze({ ramp: null, wall: null, yearStamp: false, + loudness: null, }); +/** Every style levels its clips: uneven loudness is a fault, not a look. */ +const EVEN = { target: -16, mode: "clip" }; + const chip = { style: "chip", position: "top-left", of: false, showDate: true, showSource: true }; const style = (label, summary, montage) => ({ label, summary, - patch: { render: { montage: { ...OFF, tighten: "phrase", ...montage } } }, + patch: { render: { montage: { ...OFF, tighten: "phrase", loudness: EVEN, ...montage } } }, }); /** @@ -80,7 +84,7 @@ export const MONTAGE_STYLES = Object.freeze({ "wall-finale": style( "Wall finale", "Straight cuts, then a wall of sixteen clips filling in, all saying it together at the end.", - { counter: chip, wall: { at: "end", tiles: 16, build: 8, year: true, groups: null, sync: null, clips: null, exclusive: null } }, + { counter: chip, wall: { at: "end", tiles: 16, build: 8, year: true, groups: null, sync: null, clips: null, exclusive: null, label: null, spread: null, distinct: null } }, ), "whip-years": style( "Whip and years", @@ -95,7 +99,10 @@ export const MONTAGE_STYLES = Object.freeze({ ramp: { from: 3.5, to: null, into: "wall" }, punch: { mode: "drift", scale: 1.08, anchor: "upper" }, counter: { style: "tally", position: "top-left", of: false, showDate: true, showSource: false }, - wall: { at: "end", tiles: 25, build: 7.5, year: true, groups: "double", sync: true, clips: "tail", exclusive: true }, + wall: { + at: "end", tiles: 25, build: 7.5, year: true, groups: "double", sync: true, clips: "tail", exclusive: true, + label: "both", spread: "stream", distinct: null, + }, }, ), }); diff --git a/umtool/report-to-video/montage.mjs b/umtool/report-to-video/montage.mjs @@ -35,8 +35,11 @@ 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", + "tighten", "phrasePad", "cut", "flashColor", "counter", "punch", "stutter", "ramp", "wall", "yearStamp", "loudness", ]); +const LOUDNESS_KEYS = ["target", "mode"]; +export const WALL_LABELS = Object.freeze(["year", "number", "both"]); +export const WALL_SPREADS = Object.freeze(["stream"]); 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"]); @@ -48,7 +51,7 @@ 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", "into"]; -const WALL_KEYS = ["at", "tiles", "build", "year", "groups", "sync", "clips", "exclusive"]; +const WALL_KEYS = ["at", "tiles", "build", "year", "groups", "sync", "clips", "exclusive", "label", "spread", "distinct"]; export const WALL_GROUPS = Object.freeze(["single", "double"]); export const WALL_CLIPS = Object.freeze(["spread", "tail"]); /** A synced tile starts this long before its phrase's onset, and runs this long past its end. */ @@ -124,12 +127,17 @@ export function resolveMontage(render) { ? { ...wall, year: wall.year === true, + // What a tile is labelled with: `label`, else today's `year: true`. + label: wall.label ?? (wall.year === true ? "year" : null), + spread: wall.spread ?? null, + distinct: wall.distinct === true, exclusive: wall.exclusive === true, // Synced by default when the tiles come in groups: a group says it in unison. sync: typeof wall.sync === "boolean" ? wall.sync : wall.groups === "double", } : null, yearStamp: m.yearStamp === true, + loudness: isObj(m.loudness) ? { target: m.loudness.target ?? -16, mode: m.loudness.mode ?? "clip" } : null, }; } @@ -241,6 +249,15 @@ export function validateMontage(manifest) { if (m.wall.clips != null) errors.push(...oneOf(m.wall.clips, WALL_CLIPS, `${W}.wall.clips`)); errors.push(...bool(m.wall.sync, `${W}.wall.sync`)); errors.push(...bool(m.wall.exclusive, `${W}.wall.exclusive`)); + if (m.wall.label != null) errors.push(...oneOf(m.wall.label, WALL_LABELS, `${W}.wall.label`)); + if (m.wall.spread != null) errors.push(...oneOf(m.wall.spread, WALL_SPREADS, `${W}.wall.spread`)); + errors.push(...bool(m.wall.distinct, `${W}.wall.distinct`)); + if (m.wall.distinct === true && m.wall.exclusive === true) { + errors.push( + `${W}.wall.distinct does not combine with ${W}.wall.exclusive: trading a repeat for an earlier clip ` + + `would put a later clip back in the run before the wall — use wall.spread "stream" to keep repeats apart instead`, + ); + } if (m.wall.exclusive === true && errors.length === 0) { const split = montageSplit(manifest.timeline ?? [], resolveMontage(render)); if (split.linear.length < 2) { @@ -253,6 +270,14 @@ export function validateMontage(manifest) { } } errors.push(...bool(m.yearStamp, `${W}.yearStamp`)); + if (m.loudness != null) { + if (!isObj(m.loudness)) errors.push(`${W}.loudness must be an object ({ target, mode }) or null`); + else { + errors.push(...unknownKeys(m.loudness, LOUDNESS_KEYS, `${W}.loudness`)); + if (m.loudness.target != null) errors.push(...inRange(m.loudness.target, -40, -5, `${W}.loudness.target`, " LUFS")); + if (m.loudness.mode != null) errors.push(...oneOf(m.loudness.mode, ["clip"], `${W}.loudness.mode`)); + } + } // 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`); @@ -470,7 +495,9 @@ export function planMontage(timeline, settings, dateOf = () => null) { for (const e of timeline) { if (e?.type !== "clip" || !split.wallOnly.has(e.id)) continue; const date = parseClipDate(e.montage?.date) ?? parseClipDate(e.date) ?? parseClipDate(dateOf(e)); - out.set(e.id, { wallOnly: true, date, year: date?.y ?? null, platform: e.montage?.platform ?? null }); + const own = Number(e.montage?.n); + const number = Number.isInteger(own) && own > 0 ? own : timeline.filter((x) => x?.type === "clip").indexOf(e) + 1; + out.set(e.id, { wallOnly: true, number, date, year: date?.y ?? null, platform: e.montage?.platform ?? null }); } let prevYear = null; clips.forEach((e, k) => { @@ -608,7 +635,7 @@ const zoomCrop = (zoom, anchor) => * * @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 }) { +export function montagePiecesGraph({ pieces, fps, box, bg, punch = null, inV = "[0:v]", inA = "[0:a]", hasVideo = true, gainDb = null }) { const frames = piecesFrames(pieces); const seconds = frames / fps; const parts = []; @@ -661,7 +688,8 @@ export function montagePiecesGraph({ pieces, fps, box, bg, punch = null, inV = " 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]`); + const level = gainDb != null ? `,${levelFilters(gainDb)}` : ""; + parts.push(`[mac]apad=whole_dur=${D},atrim=end=${D}${level}${declick}[ma]`); return { parts, v: hasVideo ? "[mv]" : null, a: "[ma]", frames, seconds }; } @@ -882,15 +910,109 @@ export function wallTileClips(ids, tiles, clips = "spread") { } /** + * Which recording a clip comes from, for keeping a wall's repeats apart: its + * `montage.stream` when it names one, else its DAY -- a stream and its mirror + * on another platform have different ids but one date -- else its video. + */ +export function clipStream(entry) { + if (entry?.montage?.stream) return String(entry.montage.stream); + const d = parseClipDate(entry?.montage?.date) ?? parseClipDate(entry?.date); + if (d) return `${d.y}-${d.m}-${d.d}`; + return String(entry?.video ?? entry?.src ?? entry?.id); +} + +/** + * `wall.distinct`: one tile per stream where the cut allows. "tail": walking + * back from the last clip, the latest clip of each stream not yet taken, + * then (when there are fewer streams than tiles) the latest of the rest; + * "spread": spread over each stream's first clip. Returned in cut order. + */ +export function distinctTileClips(ids, tiles, clips, streamOf) { + const order = new Map(ids.map((id, i) => [id, i])); + if (clips === "tail") { + const taken = []; + const seen = new Set(); + for (let i = ids.length - 1; i >= 0 && taken.length < tiles; i -= 1) { + const s = streamOf.get(ids[i]); + if (seen.has(s)) continue; + seen.add(s); + taken.push(ids[i]); + } + for (let i = ids.length - 1; i >= 0 && taken.length < tiles; i -= 1) if (!taken.includes(ids[i])) taken.push(ids[i]); + return taken.sort((a, b) => order.get(a) - order.get(b)); + } + const firsts = []; + const seen = new Set(); + for (const id of ids) { + const s = streamOf.get(id); + if (!seen.has(s)) { + seen.add(s); + firsts.push(id); + } + } + return wallTileClips(firsts.length >= tiles ? firsts : ids, tiles, "spread"); +} + +/** + * `wall.spread: "stream"`: which grid cell each tile takes (row-major cell + * numbers), so that no two tiles of one stream touch across a row or a + * column where that can be avoided, moving as few tiles as far as possible + * from their own cell (cell i for tile i: the groups still fill in order). + * A deterministic descent: the best swap of two tiles' cells, repeated, + * scored as 100 per touching pair plus each tile's grid distance from home. + */ +export function wallCells(streams, cols) { + const n = streams.length; + const cell = Array.from({ length: n }, (_, i) => i); + const at = (c) => [Math.floor(c / cols), c % cols]; + const touching = (a, b) => { + const [ra, ca] = at(a); + const [rb, cb] = at(b); + return Math.abs(ra - rb) + Math.abs(ca - cb) === 1; + }; + const cost = () => { + let c = 0; + for (let i = 0; i < n; i += 1) { + const [r, k] = at(cell[i]); + const [r0, k0] = at(i); + c += Math.abs(r - r0) + Math.abs(k - k0); + for (let j = i + 1; j < n; j += 1) if (streams[i] === streams[j] && touching(cell[i], cell[j])) c += 100; + } + return c; + }; + let now = cost(); + for (let round = 0; round < 200; round += 1) { + let best = null; + for (let a = 0; a < n; a += 1) { + for (let b = a + 1; b < n; b += 1) { + [cell[a], cell[b]] = [cell[b], cell[a]]; + const c = cost(); + [cell[a], cell[b]] = [cell[b], cell[a]]; + if (c < now && (!best || c < best.c)) best = { a, b, c }; + } + } + if (!best) break; + [cell[best.a], cell[best.b]] = [cell[best.b], cell[best.a]]; + now = best.c; + } + return cell; +} + +/** * Which clips the wall takes, and which run before it: `wall` the tile clips * in tile order (wallTileClips over the cut's clips), `wallOnly` the ids an * `exclusive` wall takes out of the run (empty otherwise), `linear` the clip * ids that run as clips, in order. */ export function montageSplit(timeline, settings) { - const ids = (timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id); + const clips = (timeline ?? []).filter((e) => e?.type === "clip"); + const ids = clips.map((e) => e.id); const w = settings?.wall; - const wall = w ? wallTileClips(ids, w.tiles, w.clips) : []; + const wall = !w + ? [] + : w.distinct + ? distinctTileClips(ids, w.tiles, w.clips, new Map(clips.map((e) => [e.id, clipStream(e)]))) + : wallTileClips(ids, w.tiles, w.clips); const wallOnly = new Set(w?.exclusive ? wall : []); return { wall, wallOnly, linear: ids.filter((id) => !wallOnly.has(id)) }; } @@ -955,7 +1077,7 @@ export const wallFirstGap = (wall) => wallBeats({ tiles: wall.tiles, build: wall * @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, groups = "single", leads = null }) { +export function wallPlan({ tiles, build, durations, fps, width, height, groups = "single", leads = null, cells = null }) { 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; @@ -969,9 +1091,11 @@ export function wallPlan({ tiles, build, durations, fps, width, height, groups = 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, - })); + // Tile i sits in cell i, or in `cells[i]` (wallCells: repeats kept apart). + const layout = Array.from({ length: tiles }, (_, i) => { + const c = cells ? cells[i] : i; + return { x: ox + (c % cols) * (w + gap), y: oy + Math.floor(c / cols) * (h + gap), w, h }; + }); if (groups === "double" || leads) { return groupedWallPlan({ tiles, build, durations, fps, groups, leads, q, base: { cols, gap, layout, tileW: w, tileH: h } }); } @@ -1030,22 +1154,69 @@ function groupedWallPlan({ tiles, build, durations, fps, groups, leads, q, base * 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 }) { +export function wallTileArgs({ raw, from, to, tileW, tileH, fps, year = null, text = null, gainDb = 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` + // `text` (wallTileLabel's) or, as before, the `year`. + const words = text ?? (year != null ? String(year) : null); + const label = words != null + ? `,drawtext=fontfile='${font}':expansion=none:text='${safeText(words)}':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` : ""; + const leveled = gainDb != null; 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", + `[0:v]fps=${fps},scale=${tileW}:${tileH}:force_original_aspect_ratio=increase,crop=${tileW}:${tileH},setsar=1${label}[v]` + + (leveled ? `;[0:a]${levelFilters(gainDb)}[a]` : ""), + "-map", "[v]", "-map", leveled ? "[a]" : "0:a", ...encode, outPath, ]; } +/** A tile's label (`wall.label`): "2025", "#52", or "#52 · 2025"; null without one. */ +export function wallTileLabel(label, { number = null, year = null } = {}) { + const n = number != null ? `#${number}` : null; + const y = year != null ? String(year) : null; + if (label === "year") return y; + if (label === "number") return n; + if (label === "both") return [n, y].filter(Boolean).join(" · ") || null; + return null; +} + +// ---- even loudness (`render.montage.loudness`) --------------------------------------- + +/** No clip is raised or lowered by more than this, dB. */ +export const LOUDNESS_MAX_GAIN = 20; +/** Below this a measurement is silence or too short to trust: no gain. */ +export const LOUDNESS_FLOOR = -60; + +/** + * The gain (dB) that brings a measured integrated loudness to the target, + * held to ±LOUDNESS_MAX_GAIN; 0 for a silence or an unmeasurable clip. + */ +export function loudnessGain(measured, target) { + if (!num(measured) || measured <= LOUDNESS_FLOOR) return 0; + return Number(Math.max(-LOUDNESS_MAX_GAIN, Math.min(LOUDNESS_MAX_GAIN, target - measured)).toFixed(2)); +} + +/** + * The integrated loudness (LUFS) in ffmpeg's ebur128 summary, or null. + */ +export function parseIntegratedLoudness(log) { + const summary = String(log ?? "").split("Summary:").pop(); + const m = summary.match(/\bI:\s*(-?[\d.]+|-inf)\s*LUFS/); + if (!m || m[1] === "-inf") return null; + return Number(m[1]); +} + +/** + * A clip's sound brought to the target: the gain, then a lookahead limiter + * at −1 dBFS (no auto-level, its delay compensated) so a raised quiet clip + * cannot clip. Deterministic: one measured gain, no adaptive normaliser. + */ +export const levelFilters = (gainDb) => `volume=${gainDb}dB,alimiter=limit=0.891:level=0:latency=1`; + /** * 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. @@ -1089,10 +1260,13 @@ export function wallComposeArgs({ tiles, plan, render, settings, first, last, en ); 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("|"); + // The grid's top-left: the first tile's cell, unless the tiles were moved (wallCells). + const gx = Math.min(...plan.layout.map((l) => l.x)); + const gy = Math.min(...plan.layout.map((l) => l.y)); + const layout = plan.layout.map((l) => `${l.x - gx}_${l.y - gy}`).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]`, + `pad=${render.width}:${render.height}:${gx}:${gy}: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, diff --git a/umtool/report-to-video/montage.test.mjs b/umtool/report-to-video/montage.test.mjs @@ -20,6 +20,7 @@ import { platformLabel, rampCap, rampCaps, resolveMontage, safeText, stutters, tallyMarks, timedText, validateMontage, wallComposeArgs, wallPlan, wallTileClips, whisperWords, wallGroups, wallBeats, wallFirstGap, montageSplit, refineOnset, speechEnvelope, envelopeLag, WALL_SLIDE_FRAMES, bandFeatures, consensusLags, templateOnset, + clipStream, distinctTileClips, wallCells, wallTileLabel, wallTileArgs, loudnessGain, parseIntegratedLoudness, levelFilters, } from "./montage.mjs"; import { applyMontageStyle, MONTAGE_STYLE_NAMES, mergePatch } from "./montage-styles.mjs"; import { buildVideo, snap } from "./build-video.mjs"; @@ -107,7 +108,10 @@ test("resolveMontage: every default filled in; the accent flash is the palette's 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, groups: "single", sync: false, clips: "spread", exclusive: false }); + assert.deepEqual(r.wall, { + at: "end", tiles: 9, build: 6, year: false, groups: "single", sync: false, clips: "spread", exclusive: false, + label: null, spread: null, distinct: false, + }); assert.equal(resolveMontage({ montage: { wall: { groups: "double" } } }).wall.sync, true, "groups sync by default"); assert.equal(resolveMontage({ montage: { wall: { groups: "double", sync: false } } }).wall.sync, false); assert.deepEqual(resolveMontage({ montage: { ramp: { from: 3, into: "wall" } } }).ramp, { from: 3, to: undefined, into: "wall" }); @@ -523,7 +527,7 @@ const RENDER = { * 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 = {} } = {}) { +async function fixture(montage, { extraRender = {}, amp = () => 0.5 } = {}) { const root = await mkdtemp(path.join(os.tmpdir(), "rtv-montage-")); await mkdir(path.join(root, "media"), { recursive: true }); const timeline = []; @@ -531,7 +535,7 @@ async function fixture(montage, { extraRender = {} } = {}) { 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`, + "-f", "lavfi", "-i", `aevalsrc='${amp(i)}*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, ]); @@ -962,7 +966,7 @@ test("envelopeLag: a shifted copy is found at its shift", () => { * after the cues say 2.0), and another from 3.9 s. Years 2019 on, three a * year; montage.n 1–12. */ -async function wallFixture(montage) { +async function wallFixture(montage, { stream = null } = {}) { const root = await mkdtemp(path.join(os.tmpdir(), "rtv-wallsync-")); await mkdir(path.join(root, "media"), { recursive: true }); for (let i = 1; i <= 6; i += 1) { @@ -987,7 +991,10 @@ async function wallFixture(montage) { return { id: `s${k + 1}`, type: "clip", src: `media/c${j}.mp4`, cues: `media/c${j}.json`, start: 0.2, end: 5.8, title: `Clip ${k + 1}`, channelTitle: "Demo", - montage: { n: k + 1, date: `${2019 + Math.floor(k / 3)}0${(k % 9) + 1}01`, platform: "youtube", match: "slow news day" }, + montage: { + n: k + 1, date: `${2019 + Math.floor(k / 3)}0${(k % 9) + 1}01`, platform: "youtube", match: "slow news day", + ...(stream ? { stream: stream(k) } : {}), + }, }; }); const manifestPath = path.join(root, "video.manifest.json"); @@ -1062,3 +1069,185 @@ test("render: build-to-wall over twelve clips -- three run, nine are tiles in gr await rm(root, { recursive: true, force: true }); } }); + +// ---- release 33 montage-polish: repeats apart, even loudness, tile labels --------------------- + +test("validateMontage: wall label, spread, distinct; loudness", () => { + const errs = (m, tl) => validateMontage(manifest(m, tl)); + assert.match(errs({ wall: { label: "date" } })[0], /wall\.label must be "year" or "number" or "both", not "date"/); + assert.match(errs({ wall: { spread: "even" } })[0], /wall\.spread must be "stream", not "even"/); + assert.match(errs({ wall: { distinct: 1 } })[0], /wall\.distinct must be true or false/); + const eleven = Array.from({ length: 11 }, (_, i) => clip(`s${i + 1}`)); + assert.match(errs({ wall: { tiles: 9, clips: "tail", exclusive: true, distinct: true } }, eleven)[0], /wall\.distinct does not combine with render\.montage\.wall\.exclusive/); + assert.deepEqual(errs({ wall: { tiles: 9, clips: "tail", distinct: true, spread: "stream", label: "both" } }, eleven), []); + assert.match(errs({ loudness: { target: -3 } })[0], /loudness\.target must be a number from -40 to -5 LUFS/); + assert.match(errs({ loudness: { mode: "stream" } })[0], /loudness\.mode must be "clip"/); + assert.match(errs({ loudness: { gain: 2 } })[0], /loudness\.gain is not a setting here/); + assert.match(errs({ loudness: -16 })[0], /loudness must be an object/); + assert.deepEqual(errs({ loudness: {} }), []); +}); + +test("resolveMontage: a label from today's year; loudness defaults", () => { + assert.equal(resolveMontage({ montage: { wall: { year: true } } }).wall.label, "year"); + assert.equal(resolveMontage({ montage: { wall: { year: true, label: "both" } } }).wall.label, "both"); + assert.equal(resolveMontage({ montage: { wall: {} } }).wall.label, null); + assert.deepEqual(resolveMontage({ montage: { loudness: {} } }).loudness, { target: -16, mode: "clip" }); + assert.equal(resolveMontage({ montage: {} }).loudness, null); +}); + +test("clipStream: its own stream, else its day (a mirror shares the day), else its video", () => { + assert.equal(clipStream({ montage: { stream: "x", date: "20260507" }, video: "v" }), "x"); + assert.equal(clipStream({ montage: { date: "20260507" }, video: "v1" }), clipStream({ date: "2026-05-07", video: "Gu2" })); + assert.equal(clipStream({ video: "v9" }), "v9"); + assert.equal(clipStream({ src: "media/a.mp4" }), "media/a.mp4"); +}); + +test("distinctTileClips: one tile per stream, latest first for a tail, in cut order", () => { + const ids = ["a1", "b1", "c1", "c2", "d1", "e1", "e2"]; + const streamOf = new Map(ids.map((id) => [id, id[0]])); + assert.deepEqual(distinctTileClips(ids, 4, "tail", streamOf), ["b1", "c2", "d1", "e2"]); + assert.deepEqual(distinctTileClips(ids, 6, "tail", streamOf), ["a1", "b1", "c2", "d1", "e1", "e2"], "fewer streams than tiles: the latest of the rest"); + assert.deepEqual(distinctTileClips(ids, 4, "spread", streamOf), wallTileClips(["a1", "b1", "c1", "d1", "e1"], 4)); + const tl = ids.map((id) => clip(id, { montage: { stream: id[0] } })); + assert.deepEqual(montageSplit(tl, resolveMontage({ montage: { wall: { tiles: 4, clips: "tail", distinct: true } } })).wall, ["b1", "c2", "d1", "e2"]); +}); + +test("wallCells: repeats of one stream never touch across a row or a column; nothing moves without a repeat", () => { + // The auditioned take's tail: five same-stream pairs side by side, and a same-day mirror pair. + const streams = ["a", "b", "c", "c", "d", "e", "f", "f", "g", "h", "i", "i", "j", "k", "l", "l", "m", "n", "o", "p", "q", "q", "r", "s", "s"]; + const cells = wallCells(streams, 5); + assert.deepEqual([...cells].sort((x, y) => x - y), Array.from({ length: 25 }, (_, i) => i), "a permutation"); + const at = (c) => [Math.floor(c / 5), c % 5]; + for (let i = 0; i < 25; i += 1) { + for (let j = i + 1; j < 25; j += 1) { + if (streams[i] !== streams[j]) continue; + const [a, b] = at(cells[i]); + const [c, d] = at(cells[j]); + assert.notEqual(Math.abs(a - c) + Math.abs(b - d), 1, `${i} and ${j} touch`); + } + } + assert.ok(cells.filter((c, i) => c !== i).length <= 12, "few tiles move"); + assert.deepEqual(wallCells(streams, 5), cells, "deterministic"); + assert.deepEqual(wallCells(Array.from({ length: 9 }, (_, i) => `s${i}`), 3), Array.from({ length: 9 }, (_, i) => i)); + // Unavoidable: one stream on every tile. + assert.equal(wallCells(Array(4).fill("x"), 2).length, 4); +}); + +test("wallPlan cells: tile i is laid in its cell; the single compose's grid origin is the top-left cell", () => { + const base = { tiles: 9, build: 3, durations: Array(9).fill(1), fps: 30, width: 320, height: 180 }; + const plain = wallPlan(base); + const cells = [4, 1, 2, 3, 0, 5, 6, 7, 8]; + const moved = wallPlan({ ...base, cells }); + assert.deepEqual(moved.layout[0], plain.layout[4]); + assert.deepEqual(moved.layout[4], plain.layout[0]); + assert.deepEqual(wallPlan({ ...base, cells: null }), plain); + const tiles = Array.from({ length: 9 }, (_, i) => ({ file: `/t/${i}.mp4`, seconds: 1 })); + const settings = resolveMontage({ montage: { wall: { tiles: 9 } } }); + const g = (plan) => { const a = wallComposeArgs({ tiles, plan, render: { width: 320, height: 180, fps: 30, palette: PALETTE }, settings, first: false, last: true, encode: [], outPath: "/o" }); return a[a.indexOf("-filter_complex") + 1]; }; + const pad = (graph) => graph.match(/xstack=inputs=9:layout=([^:]+):fill=[^,]+,pad=320:180:(\d+):(\d+)/); + const [, l0, x0, y0] = pad(g(plain)); + const [, l1, x1, y1] = pad(g(moved)); + assert.deepEqual([x1, y1], [x0, y0]); + assert.equal(l1.split("|")[0], l0.split("|")[4]); +}); + +test("wallTileLabel and wallTileArgs: year, number or both; today's year label unchanged; a gain on the tile's sound", () => { + assert.equal(wallTileLabel("year", { number: 52, year: 2025 }), "2025"); + assert.equal(wallTileLabel("number", { number: 52, year: 2025 }), "#52"); + assert.equal(wallTileLabel("both", { number: 52, year: 2025 }), "#52 · 2025"); + assert.equal(wallTileLabel("both", { number: null, year: 2025 }), "2025"); + assert.equal(wallTileLabel(null, { number: 1, year: 2025 }), null); + const base = { raw: "/r.mp4", from: 1, to: 2, tileW: 100, tileH: 56, fps: 30, font: "/f.ttf", render: { palette: PALETTE }, encode: ["-c:v", "x"], outPath: "/o.mp4" }; + const byYear = wallTileArgs({ ...base, year: 2025 }); + assert.deepEqual(wallTileArgs({ ...base, text: "2025" }), byYear); + assert.match(byYear.join(" "), /text='2025'.*\[v\] -map \[v\] -map 0:a/); + const both = wallTileArgs({ ...base, text: "#52 · 2025", gainDb: 4.5 }); + const graph = both[both.indexOf("-filter_complex") + 1]; + assert.match(graph, /text='#52 · 2025'/); + assert.match(graph, /;\[0:a\]volume=4\.5dB,alimiter=limit=0\.891:level=0:latency=1\[a\]$/); + assert.equal(both[both.indexOf("-map", both.indexOf("-map") + 1) + 1], "[a]"); +}); + +test("loudness: the gain to the target, held to ±20 dB, none for silence; ebur128's summary read; a leveled segment's chain", () => { + assert.equal(loudnessGain(-30, -16), 14); + assert.equal(loudnessGain(-8.5, -16), -7.5); + assert.equal(loudnessGain(-50, -16), 20); + assert.equal(loudnessGain(-70, -16), 0); + assert.equal(loudnessGain(null, -16), 0); + const log = "[Parsed_ebur128_0 @ 0x1] t: 1.9 M: -20 S: -21 I: -25.0 LUFS\n[Parsed_ebur128_0 @ 0x1] Summary:\n\n Integrated loudness:\n I: -21.8 LUFS\n Threshold: -31.8 LUFS\n"; + assert.equal(parseIntegratedLoudness(log), -21.8); + assert.equal(parseIntegratedLoudness("Summary:\n I: -inf LUFS"), null); + assert.equal(parseIntegratedLoudness("nothing"), null); + assert.equal(levelFilters(-3.25), "volume=-3.25dB,alimiter=limit=0.891:level=0:latency=1"); + const g = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box: { w: 320, h: 180 }, bg: "#000000", gainDb: 6 }); + assert.equal(g.parts.at(-1), `[mac]apad=whole_dur=3,atrim=end=3,volume=6dB,alimiter=limit=0.891:level=0:latency=1,afade=t=in:d=${DECLICK},afade=t=out:st=2.985:d=${DECLICK}[ma]`); + const plain = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box: { w: 320, h: 180 }, bg: "#000000" }); + assert.equal(plain.parts.at(-1), `[mac]apad=whole_dur=3,atrim=end=3,afade=t=in:d=${DECLICK},afade=t=out:st=2.985:d=${DECLICK}[ma]`); +}); + +test("planMontage: an exclusive wall's clips keep their number for their label", () => { + const tl = Array.from({ length: 12 }, (_, i) => clip(`s${i + 1}`, { montage: { n: i + 41 } })); + const plan = planMontage(tl, resolveMontage({ montage: { wall: { tiles: 9, clips: "tail", exclusive: true } } })); + assert.equal(plan.get("s12").number, 52); + assert.equal(planMontage(tl.map((e) => ({ ...e, montage: {} })), resolveMontage({ montage: { wall: { tiles: 9, clips: "tail", exclusive: true } } })).get("s12").number, 12); +}); + +/** A segment's integrated loudness, LUFS. */ +function lufs(file) { + const r = spawnSync("ffmpeg", ["-nostdin", "-hide_banner", "-i", file, "-vn", "-af", "ebur128", "-f", "null", "-"]); + return parseIntegratedLoudness(String(r.stderr)); +} + +test("render: loudness -- four clips 26 dB apart come out within 1 LU of the target", { skip: !have && "needs ffmpeg" }, async () => { + const amps = [0.03, 0.1, 0.3, 0.6]; + const { root, manifestPath } = await fixture({ tighten: "phrase", loudness: { target: -18 } }, { amp: (i) => amps[i - 1] }); + try { + await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const seg = path.join(root, "out", "sourced", "segments"); + const before = []; + for (const id of IDS) { + const rec = JSON.parse(await readFile(path.join(seg, `${id}.cut.json`), "utf8")).montage.loudness; + before.push(rec.measured); + assert.equal(rec.target, -18); + assert.ok(Math.abs(rec.measured + rec.gain + 18) < 0.01, JSON.stringify(rec)); + const got = lufs(path.join(seg, `${id}.mp4`)); + assert.ok(Math.abs(got + 18) <= 1, `${id}: ${got} LUFS`); + } + assert.ok(Math.max(...before) - Math.min(...before) > 20, `the sources spread ${before}`); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: a tail wall keeps one stream's repeats apart, labels its tiles, levels them", { skip: !have && "needs ffmpeg" }, async () => { + const montage = { + tighten: "phrase", loudness: { target: -18 }, + wall: { tiles: 9, build: 2, clips: "tail", label: "both", spread: "stream" }, + }; + // s4–s12 are the tiles; s5/s6, s8/s9 and s11/s12 are three streams' repeats. + const { root, manifestPath } = await wallFixture(montage, { stream: (k) => (k >= 4 ? `st${Math.floor((k - 1) / 3)}-${(k - 1) % 3 === 0 ? "a" : "b"}` : `solo${k}`) }); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const seg = path.join(root, "out", "sourced", "segments"); + const wall = JSON.parse(await readFile(path.join(seg, "montage-wall.cut.json"), "utf8")).montageWall; + const m = JSON.parse(await readFile(manifestPath, "utf8")); + const streamOf = new Map(m.timeline.map((e) => [e.id, clipStream(e)])); + const at = (c) => [Math.floor(c / 3), c % 3]; + for (let i = 0; i < 9; i += 1) { + for (let j = i + 1; j < 9; j += 1) { + if (streamOf.get(wall.tiles[i]) !== streamOf.get(wall.tiles[j])) continue; + const [a, b] = at(wall.cells[i]); + const [c, d] = at(wall.cells[j]); + assert.notEqual(Math.abs(a - c) + Math.abs(b - d), 1, `${wall.tiles[i]} and ${wall.tiles[j]} touch`); + } + } + assert.deepEqual(Object.keys(wall.loudness).sort(), [...wall.tiles].sort(), "each tile clip measured once"); + for (const v of Object.values(wall.loudness)) assert.equal(v.target, -18); + const tile = path.join(seg, "montage-wall", "s12.mp4"); + assert.ok(Math.abs(lufs(tile) + 18) <= 1.5, `tile ${lufs(tile)}`); + assert.deepEqual((await verifyBuild(manifestPath)).problems, []); + assert.ok(r.out); + } finally { + await rm(root, { recursive: true, force: true }); + } +});