commit ee45c99a8e2ced0f0e0dd54fa4338f4045bbf4f2
parent f38de8ea7163d611bc7e0e07da5d5894043e6dde
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 02:50:44 -0400
Merge r33/montage-polish: even loudness per clip and tile (fixed measured gain to -16 LUFS), wall repeats kept apart (spread: stream), tile labels (year/number/both)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 527 insertions(+), 34 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **Montages are level, and their walls don't repeat themselves side by side.** With `render.montage.loudness` (every montage style has it, at −16 LUFS), each clip and each wall tile is measured and brought to the same loudness, with a limiter so a quiet clip raised up cannot clip — an old upload and a recent stream no longer jump in level at the cut. `wall.spread: "stream"` keeps two clips of one stream, or a stream and its mirror on another platform, from touching in the wall's grid, and `wall.distinct` takes one clip per stream when there are enough. `wall.label` puts each tile's year, its number or both in its corner. Build to the wall uses all three. Manifests without them render exactly as before.
- **A montage can build to its wall.** The closing wall can fill in groups of 1, 1, 2, 4, 8 … tiles, each group sliding in on a beat that comes a little sooner than the last; a group says the phrase together, with every tile's first syllable placed on the beat (from whisper's word timings, or from the captions checked against the sound), and at the end every tile says it on the same frame. The wall can take the latest clips instead of a spread (`wall.clips: "tail"`) and take them out of the run before it (`wall.exclusive`), so it condenses the repetition instead of repeating it; the count before it then stops where the wall begins. A ramp can end at the wall's first beat (`ramp.into: "wall"`), so the cuts speed straight into it. A seventh style, **Build to the wall**, puts these together: whip cuts getting shorter, tally marks, then the latest twenty-five in synced groups. Manifests without the new keys render exactly as before.
- **Variant auditions: make takes on umtool's Takes page, and use one.** A report video's Takes page (the Cut tab's **Takes — N**, or **Make takes** when there are none yet) has **New take**: a montage style or none, a label, a group, the window (from S seconds for D seconds, or the full cut), an optional patch (JSON, checked before it is sent) and **quick render**. **Make all styles** makes one take per montage style with the same window. A take is rendered beside the project from the media the project already has — nothing is fetched — and appears when it is built, its changes listed in plain lines (`render.montage.cut: flash`, `render.crf: 34 (was 30)`); **Rebuild** makes it again against the cut as it is now. **Use this take** makes the take's manifest the project's and marks it **picked**, one per group; the Cut tab's **Undo last edit** takes it back. When the cut changed since the take was made, the card says so and waits for **Use anyway**. The same from a terminal: `umtool take`, `umtool takes make` (a recipe, or `--all-styles`), `umtool takes styles`, `umtool takes pick`. Nothing calls a model. Needs a restart of umtool.
- **A montage from a phrase.** umtool's new project can be seeded from a phrase said across channels: `umtool new <slug> --seed phrase --phrase '<regex>' --channels a,b --prefer <channel>`, or the new-project form's seed "a phrase across channels" when no source is given. Every place the transcripts say it becomes a clip, in date order, found even where a caption line split the phrase in two; a stream that the preferred channel also holds (a Rumble copy, say) is cut from that copy; a stream and its clip upload are one clip; `--exclude` leaves out lines that match (a chat line read out), and a caption speaker change is noted for a voice check. The scan is kept beside the manifest as `phrase-scan.json`.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10468,3 +10468,16 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
on the template's rise (`templateOnset`); on synthetic takes both are exact to the 5 ms hop.
- Of the slow-news project's 73 clips (2026-10-18): 40 have whisper.cpp token offsets in `transcript.json`, 16 a
parakeet `chunk_data`, 17 no `transcript.json` (YouTube captions only).
+
+## Release 33 lane M3c: montage polish (verified 2026-10-18, branch `r33/montage-polish`)
+
+- `render.montage.loudness {target (−40…−5 LUFS, default −16), mode "clip"}`: one ebur128 integrated measurement per
+ clip cut (raw `cutA`–`cutB`) and per wall tile (`from`–`to`), gain = target − measured held to ±20 dB (0 under −60
+ LUFS), applied as `volume=…dB,alimiter=limit=0.891:level=0:latency=1` (`levelFilters`). Records:
+ `<id>.cut.json` `montage.loudness`, `montage-wall.cut.json` `montageWall.loudness[id]`.
+- `clipStream(entry)`: `montage.stream` → the clip's day → its video. Same-day clips count as one stream (on the
+ slow-news project the YouTube/Rumble mirrors of one day share it).
+- `wall.spread "stream"` → `wallCells` (cell per tile, row-major), recorded as `montageWall.cells`; `wallPlan({cells})`
+ lays tile i in `cells[i]`, and the single-tile compose's grid origin is the top-left of all tiles. `wall.distinct`
+ (`distinctTileClips`) is refused with `exclusive`.
+- `wall.label "year" | "number" | "both"`; `year: true` resolves to "year" with today's drawtext unchanged.
diff --git a/plans/release-33/montage-polish.md b/plans/release-33/montage-polish.md
@@ -0,0 +1,62 @@
+# Release 33 lane M3c — montage polish (as shipped)
+
+After the build-to-wall audition (2026-10-18), three fixes to a montage, on `main` `2be6f0b7`:
+
+1. **The wall keeps a stream's repeats apart.** In the auditioned take, five pairs of tiles from one video sat side by
+ side (v6ss2d5, v70yc82, v7arhpy — the crumbl pair — v7fucc4, v7gh5pq), and so did one day's Rumble/YouTube mirror pair
+ (s59/s60).
+ - **`wall.spread: "stream"`**: `wallCells` is a deterministic descent over swaps of two tiles' cells, scored as 100
+ per touching pair (row or column) plus each tile's grid distance from its own cell. The groups keep their
+ membership and date order; only cells move. A clip's stream (`clipStream`) is its `montage.stream`, else its day,
+ else its video.
+ - **`wall.distinct`** (one tile per stream; a tail takes the latest of each stream) works with spread or tail but is
+ **refused with `exclusive`**. Trading a repeat for an earlier clip would put the later clip back in the run before
+ the wall, so it would no longer be chronological. Build-to-wall uses `spread: "stream"` without it.
+2. **Even loudness** (`render.montage.loudness {target −16, mode "clip"}`). Each clip's cut and each wall tile is
+ measured once (ebur128, integrated) and given one gain to the target. The gain is held to ±20 dB, with none under
+ −60 LUFS. Then a −1 dBFS lookahead limiter (`level=0`, `latency=1`). The crowd beat is limited as before. Every style
+ now carries it.
+3. **Tile labels** (`wall.label "year" | "number" | "both"`). `year: true` means "year" and draws the same drawtext as
+ before. Wall-only clips get their `number` from `montage.n` (else their place among the clips) in `planMontage`.
+ Build-to-wall uses "both" ("#52 · 2025").
+
+## Files
+
+`umtool/report-to-video/montage.mjs`, `montage-styles.mjs`, `build-video.mjs` (`measureLoudness`, `montageLevel`, the
+segment gain, the wall's cells / labels / levels and its record), `montage.test.mjs`, `README.md`,
+`umtool/docs/report-video.md`, `editor/CHANGELOG.md`, `plans/FACTS.md`.
+
+| Commit | What |
+| --- | --- |
+| `307634e7` | wall.spread "stream", wall.distinct, render.montage.loudness, wall.label; every style levels; tests |
+| `3c6933b4` | README, docs/report-video.md, FACTS, CHANGELOG |
+| (this commit) | this record |
+
+## Gates
+
+- tsc clean before each commit.
+- test:scripts: 1125 (1121 pass, 4 skipped) at `main` `2be6f0b7` → **1136 (1132 pass, 0 fail, 4 skipped)**. The montage
+ files ran 61/61, with real renders of:
+ - four clips 26 dB apart, each brought within 1 LU of the target;
+ - a tail wall with three streams' repeats: none touch, every tile measured, a tile within 1.5 LU, verifyBuild clean.
+- **Byte-identical:** main's own style patches (wall-finale, accelerate, build-to-wall: no new keys) rendered by main's
+ and by the branch's build-video give identical md5s.
+
+## Smoke
+
+A fresh copy of the project (73 clips) with build-to-wall, rendered whole: `$T/r33m3-smoke3/build-to-wall.mp4`,
+116.9 s, 49 chapters, verify-build ok, 405 s (with loudness passes). No chrome frame directories were made.
+
+**Loudness, integrated, per run clip (48 clips):**
+
+| | range | p10–p90 | std |
+|---|---|---|---|
+| The raw cuts | −38.6 … −11.9 LUFS = 26.7 LU | 10.6 LU | 4.8 |
+| The auditioned take's segments | 28.2 LU | 10.6 LU | 5.0 |
+| Leveled | −20.1 … −16.0 = 4.1 LU | 0.5 LU | 0.6 |
+
+The one outlier is s38: −38.6 LUFS raw, at the +20 dB cap. Wall tiles went from a 39.3 LU range (take) to 17.8; that
+remainder is s70 (raw −53.7 LUFS, near silent, capped). Without s70 the tiles are within 0.5 LU.
+
+The wall's cells moved 8 tiles; no same-stream pair touches. `wall-final.png` (the final wall, "#n · year" labels) and
+`wall-groups.jpg` are beside the mp4.
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -808,6 +808,11 @@ The named styles (`report-to-video/montage-styles.mjs`) are the ones worth
auditioning as takes: **Straight**, **Flash and count**, **Accelerate**,
**Stutter**, **Wall finale**, **Whip and years**. Each is a merge patch that
sets every montage key, so applying one over another leaves exactly the second.
+Every style levels its clips to −16 LUFS (`render.montage.loudness`): a 2019
+upload and a 2026 stream no longer jump in level at the cut. A wall's tiles can
+say their year, their number or both (`wall.label`), and `wall.spread: "stream"`
+keeps two clips of one stream (or a stream and its mirror, which share a day)
+from sitting side by side.
**Build to the wall** runs the clips with whip cuts, faster and faster, straight
into a wall of the latest 25: they are taken out of the run (`wall.exclusive`,
`wall.clips: "tail"`), arrive in groups of 1, 1, 2, 4, 8 and 9 on accelerating
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -749,7 +749,8 @@ stutter's `every` counts the same number; the ramp counts places.
"stutter": { "every": 5, "clips": ["s12"], "times": 3, "length": 0.35, "step": 0.04 },
"ramp": { "from": 4, "to": 1.4 }, // or { "from": 3.5, "into": "wall" }
"wall": { "at": "end", "tiles": 16, "build": 8, "year": true,
- "groups": "double", "sync": true, "clips": "tail", "exclusive": true },
+ "groups": "double", "sync": true, "clips": "tail", "exclusive": true,
+ "label": "both", "spread": "stream", "distinct": false },
"yearStamp": true
} }
```
@@ -767,6 +768,10 @@ stutter's `every` counts the same number; the ramp counts places.
| `wall.sync` | Default `true` with `"double"` groups, else `false`. Each tile is cut to start 0.12 s before its phrase's onset and end 0.25 s after the phrase, and is shown that 0.12 s before its beat, so the onset lands exactly on its group's beat and on the final beat: the crowd says it on one frame. The estimate is whisper's word offset when the corpus's `transcript.json` keeps them, else the cue estimate (character position). Neither is good to better than a few hundred milliseconds, and the loudness of one clip cannot tell "slow" from the word before it, so the tiles are aligned to EACH OTHER: each tile's speech-band spectrum (8 bands, 5 ms frames) over its phrase is matched to the mean of the others' within ±0.4 s of its estimate, four rounds, the median shift kept at zero (`consensusLags`); then all of them move together onto where their mean loudness rises (`templateOnset`, within ±0.3 s). Under three tiles: the sharpest loudness rise near each estimate (`refineOnset`). The wall's `.cut.json` records each tile's estimate, onset, `by` and its correlation with the rest (`r`), and the common `syncAnchor`. |
| `wall.clips` | `"spread"` (default): tiles from clips spread first to last. `"tail"`: the last `tiles` clips of the cut, in date order — group 1 is the earliest of them, the last group the latest. |
| `wall.exclusive` | `true`: the wall's clips are tiles only. They leave the run of clips (no segment, no chapter), so the counter, the tally and the ramp count the clips before the wall, and the wall condenses the repetition rather than repeating it. With fewer than 2 clips left outside the wall it is an error. A tile clip with no segment is cut from its window like any clip (`--no-network` holds). |
+| `wall.label` | What each tile says in its corner: `"year"` (what `year: true` means), `"number"` (its count, "#52": `montage.n`, else its place among the cut's clips) or `"both"` ("#52 · 2025"). |
+| `wall.spread` | `"stream"`: no two tiles from one stream touch across a row or a column where that can be avoided — the tiles keep their groups and their order, and as few move as far as they must (`wallCells`, a deterministic swap descent). A clip's stream is its `montage.stream`, else its DAY (a stream and its mirror on another platform have different ids but one date), else its video. The wall's `.cut.json` records the `cells`. |
+| `wall.distinct` | `true`: one tile per stream where the cut has enough — a tail takes the latest clip of each stream, then the latest of the rest; a spread spreads over each stream's first clip. Not with `exclusive`: trading a repeat for an earlier clip would put a later clip back in the run before the wall (an error; use `spread: "stream"`). |
+| `loudness` | `{ "target": -16, "mode": "clip" }` (LUFS): each clip's cut, and each wall tile, is measured once (ffmpeg `ebur128`, integrated) and given one gain to the target — at most ±20 dB, none for a stretch under −60 LUFS — then a lookahead limiter at −1 dBFS with no auto-level, so a raised quiet clip cannot clip. Deterministic: a measured gain, not an adaptive normaliser. The wall's crowd is limited as before. The cut record keeps `montage.loudness: {measured, gain, target}`; the wall's, each tile's. |
| `yearStamp` | On the first clip of each year, the year large in the corner across from the counter for about a second. |
**Where it is made.** Everything except the wall is inside each clip's own
@@ -785,6 +790,8 @@ values in words that say which, and a montage beside `render.chrome` (the deck),
**Named styles.** `montage-styles.mjs` holds the styles worth auditioning as
merge patches (RFC 7386) on the manifest: `straight`, `flash-count`,
`accelerate`, `stutter`, `wall-finale`, `whip-years`, and `build-to-wall`
+(every style levels its clips, `loudness` −16 LUFS; build-to-wall's tiles say
+"#n · year" and keep one stream's repeats apart)
(whip cuts, a ramp from 3.5 s into the wall, a slow zoom, the tally, then an
exclusive tail wall of the latest 25 in synced groups 1,1,2,4,8,9 with years). Each sets every montage
key, so one over another leaves exactly the second. umtool's take form lists
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 });
+ }
+});