// MONTAGE EDITING — `render.montage` (release 33 M3). // // A montage is one phrase said many times: dozens of short clips, cut tight, // run in order. Everything here is opt-in under `render.montage`; a manifest // without it renders exactly as before (build-video.mjs never reaches this // module's graph builders). // // WHERE EACH FEATURE LIVES. Every technique is made inside the clip's own // segment encode, which the build pays for anyway: the tight cut moves the // trim points, the punch-in, stutter and drift are the picture's pieces, the // counter and the year stamp are drawtext/drawbox over the finished frame, // and the cut styles (flash, whip, dip) are the first and last frames of // each segment -- each segment knows whether it opens or closes the cut. So // the concat stays the stream copy of hard cuts, no chrome layer is rendered, // and a segment's length is known to the frame before it is encoded. The one // composited pass is the wall: its own segment, made from small tiles. // // tighten "phrase" | "sentence" | null cut each clip to the phrase said ± phrasePad // phrasePad seconds (0.6) kept either side of the phrase // cut "hard" | "flash" | "whip" | "dip" // flashColor "white" | "accent" | "#rrggbb" // counter { style: chip|big|tally, position, of, showDate, showSource } | null // punch { mode: snap|drift, scale, anchor: upper|center } | null // stutter { every?, clips?, times: 2..4, length: 0.35, step: 0.04 } | null // ramp { from, to } seconds -- clip k's cut <= lerp(from, to, k/(N-1)) // wall { at: end|start, tiles: 9|16|25, build: seconds, year } | null // yearStamp true: the year, large, over the first clip of each year // // Pure functions only, but for nothing: the build (build-video.mjs) runs the // ffmpeg argv these return. README "Manifest shape", `render.montage`. import { deckOn } from "./deck.mjs"; import { MONO_BOLD_FONT_FILE } from "./brand.mjs"; // ---- the settings ----------------------------------------------------------- export const MONTAGE_KEYS = Object.freeze([ "tighten", "phrasePad", "cut", "flashColor", "counter", "punch", "stutter", "ramp", "wall", "yearStamp", "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"]); export const POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]); export const PUNCH_MODES = Object.freeze(["snap", "drift"]); export const ANCHORS = Object.freeze(["upper", "center"]); export const WALL_TILES = Object.freeze([9, 16, 25]); const COUNTER_KEYS = ["style", "position", "of", "showDate", "showSource"]; const PUNCH_KEYS = ["mode", "scale", "anchor"]; const STUTTER_KEYS = ["every", "clips", "times", "length", "step"]; const RAMP_KEYS = ["from", "to", "into"]; 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. */ export const WALL_LEAD = 0.12; export const WALL_TAIL = 0.25; export const MONTAGE_DEFAULTS = Object.freeze({ phrasePad: 0.6, punchScale: { snap: 1.15, drift: 1.08 }, stutter: { times: 3, length: 0.35, step: 0.04 }, wall: { at: "end", tiles: 16, build: 6, year: false, groups: "single", clips: "spread", exclusive: false }, }); /** The frames of each cut style (a whip's are each side of the cut). */ export const CUT_FRAMES = Object.freeze({ flash: 3, whip: 4, dip: 2 }); /** Each segment's sound starts and ends on a fade this long: no click at a hard cut. */ export const DECLICK = 0.015; /** A stutter's own pieces fade this much at each joint. */ const JOINT_FADE = 0.005; /** Is `render.montage` on? (An object; null or absent is off.) */ export const montageOn = (render) => render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage); const isObj = (v) => v != null && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); /** * `render.montage` with every default filled in, or null when it is off. * Assumes validateMontage passed; `palette` resolves an accent flash. */ export function resolveMontage(render) { if (!montageOn(render)) return null; const m = render.montage; const pal = render.palette ?? {}; const flash = m.flashColor == null || m.flashColor === "white" ? "#ffffff" : m.flashColor === "accent" ? pal.accent ?? "#ffffff" : m.flashColor; const counter = isObj(m.counter) ? { style: m.counter.style ?? "chip", position: m.counter.position ?? "top-left", of: m.counter.of === true, showDate: m.counter.showDate !== false, showSource: m.counter.showSource === true, } : null; const punch = isObj(m.punch) ? { mode: m.punch.mode, scale: m.punch.scale ?? MONTAGE_DEFAULTS.punchScale[m.punch.mode], anchor: m.punch.anchor ?? "upper", } : null; const stutter = isObj(m.stutter) ? { every: m.stutter.every ?? null, clips: Array.isArray(m.stutter.clips) ? [...m.stutter.clips] : [], times: m.stutter.times ?? MONTAGE_DEFAULTS.stutter.times, length: m.stutter.length ?? MONTAGE_DEFAULTS.stutter.length, step: m.stutter.step ?? MONTAGE_DEFAULTS.stutter.step, } : null; const wall = isObj(m.wall) ? { ...MONTAGE_DEFAULTS.wall, ...pick(m.wall, WALL_KEYS) } : null; return { tighten: m.tighten ?? null, phrasePad: m.phrasePad ?? MONTAGE_DEFAULTS.phrasePad, cut: m.cut ?? "hard", flashColor: flash, counter, punch, stutter, ramp: isObj(m.ramp) ? { from: m.ramp.from, to: m.ramp.to, into: m.ramp.into ?? null } : null, wall: wall ? { ...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, }; } function pick(o, keys) { const out = {}; for (const k of keys) if (o[k] !== undefined && o[k] !== null) out[k] = o[k]; return out; } function unknownKeys(obj, keys, where) { return Object.keys(obj) .filter((k) => !keys.includes(k)) .map((k) => `${where}.${k} is not a setting here (the settings are ${keys.join(", ")})`); } const oneOf = (v, list, where) => list.includes(v) ? [] : [`${where} must be ${list.map((x) => JSON.stringify(x)).join(" or ")}, not ${JSON.stringify(v)}`]; const inRange = (v, lo, hi, where, unit = "") => num(v) && v >= lo && v <= hi ? [] : [`${where} must be a number from ${lo} to ${hi}${unit}, not ${JSON.stringify(v)}`]; const bool = (v, where) => (v === undefined || v === null || typeof v === "boolean" ? [] : [`${where} must be true or false, not ${JSON.stringify(v)}`]); /** * What is wrong with a manifest's `render.montage`, as sentences that say so. * Nothing when it is absent or null. Unknown keys and bad values are errors; * so is a montage beside what it does not combine with (the deck, the rail, * the chart band, a clip's `muteFrom`). */ export function validateMontage(manifest) { const render = manifest?.render ?? {}; const m = render.montage; if (m === undefined || m === null) return []; if (!isObj(m)) return [`render.montage must be an object of montage settings, not ${JSON.stringify(m)}`]; const errors = [...unknownKeys(m, MONTAGE_KEYS, "render.montage")]; const W = "render.montage"; if (m.tighten != null) errors.push(...oneOf(m.tighten, TIGHTEN, `${W}.tighten`)); if (m.phrasePad != null) errors.push(...inRange(m.phrasePad, 0, 5, `${W}.phrasePad`, " seconds")); if (m.cut != null) errors.push(...oneOf(m.cut, CUTS, `${W}.cut`)); if (m.flashColor != null && m.flashColor !== "white" && m.flashColor !== "accent" && !/^#[0-9a-fA-F]{6}$/.test(String(m.flashColor))) { errors.push(`${W}.flashColor must be "white", "accent" or a #rrggbb colour, not ${JSON.stringify(m.flashColor)}`); } if (m.counter != null) { if (!isObj(m.counter)) errors.push(`${W}.counter must be an object ({ style, position, of, showDate, showSource }) or null`); else { errors.push(...unknownKeys(m.counter, COUNTER_KEYS, `${W}.counter`)); if (m.counter.style != null) errors.push(...oneOf(m.counter.style, COUNTER_STYLES, `${W}.counter.style`)); if (m.counter.position != null) errors.push(...oneOf(m.counter.position, POSITIONS, `${W}.counter.position`)); for (const k of ["of", "showDate", "showSource"]) errors.push(...bool(m.counter[k], `${W}.counter.${k}`)); } } if (m.punch != null) { if (!isObj(m.punch)) errors.push(`${W}.punch must be an object ({ mode, scale, anchor }) or null`); else { errors.push(...unknownKeys(m.punch, PUNCH_KEYS, `${W}.punch`)); errors.push(...oneOf(m.punch.mode, PUNCH_MODES, `${W}.punch.mode`)); if (m.punch.scale != null) errors.push(...inRange(m.punch.scale, 1, 2, `${W}.punch.scale`, " (1 is no zoom)")); if (m.punch.anchor != null) errors.push(...oneOf(m.punch.anchor, ANCHORS, `${W}.punch.anchor`)); } } if (m.stutter != null) { if (!isObj(m.stutter)) errors.push(`${W}.stutter must be an object ({ every, clips, times, length, step }) or null`); else { const s = m.stutter; errors.push(...unknownKeys(s, STUTTER_KEYS, `${W}.stutter`)); if (s.every == null && s.clips == null) errors.push(`${W}.stutter needs \`every\` (every Nth clip) or \`clips\` (their ids)`); if (s.every != null && !(Number.isInteger(s.every) && s.every >= 1)) { errors.push(`${W}.stutter.every must be a whole number from 1 (every clip), not ${JSON.stringify(s.every)}`); } if (s.clips != null) { if (!Array.isArray(s.clips) || !s.clips.every((c) => typeof c === "string" && c)) { errors.push(`${W}.stutter.clips must be a list of clip ids`); } else { const clipIds = new Set((manifest.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id)); for (const id of s.clips) if (!clipIds.has(id)) errors.push(`${W}.stutter.clips names "${id}", which is not a clip in the timeline`); } } if (s.times != null && !(Number.isInteger(s.times) && s.times >= 2 && s.times <= 4)) { errors.push(`${W}.stutter.times must be 2, 3 or 4 (how many times the end of the phrase is heard), not ${JSON.stringify(s.times)}`); } if (s.length != null) errors.push(...inRange(s.length, 0.1, 1, `${W}.stutter.length`, " seconds")); if (s.step != null) errors.push(...inRange(s.step, 0, 0.2, `${W}.stutter.step`, " (the zoom added per repeat)")); } } if (m.ramp != null) { if (!isObj(m.ramp)) errors.push(`${W}.ramp must be an object ({ from, to } in seconds) or null`); else { errors.push(...unknownKeys(m.ramp, RAMP_KEYS, `${W}.ramp`)); errors.push(...inRange(m.ramp.from, 0.5, 60, `${W}.ramp.from`, " seconds")); if (m.ramp.into != null) { errors.push(...oneOf(m.ramp.into, ["wall"], `${W}.ramp.into`)); if (m.ramp.into === "wall" && !isObj(m.wall)) errors.push(`${W}.ramp.into "wall" needs ${W}.wall: the ramp ends at the wall's first beat`); if (m.ramp.to != null) errors.push(...inRange(m.ramp.to, 0.5, 60, `${W}.ramp.to`, " seconds")); } else { errors.push(...inRange(m.ramp.to, 0.5, 60, `${W}.ramp.to`, " seconds")); } if (m.tighten !== "phrase") errors.push(`${W}.ramp trims around the phrase, so it needs ${W}.tighten "phrase"`); } } if (m.wall != null) { if (!isObj(m.wall)) errors.push(`${W}.wall must be an object ({ at, tiles, build, year }) or null`); else { errors.push(...unknownKeys(m.wall, WALL_KEYS, `${W}.wall`)); if (m.wall.at != null) errors.push(...oneOf(m.wall.at, ["end", "start"], `${W}.wall.at`)); if (m.wall.tiles != null) errors.push(...oneOf(m.wall.tiles, WALL_TILES, `${W}.wall.tiles`)); if (m.wall.build != null) errors.push(...inRange(m.wall.build, 1, 60, `${W}.wall.build`, " seconds")); errors.push(...bool(m.wall.year, `${W}.wall.year`)); if (m.wall.groups != null) errors.push(...oneOf(m.wall.groups, WALL_GROUPS, `${W}.wall.groups`)); 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) { errors.push( `${W}.wall.exclusive takes the wall's ${split.wallOnly.size} clip(s) out of the cut, leaving ` + `${split.linear.length} — it needs at least 2 clips outside the wall (fewer tiles, or not exclusive)`, ); } } } } 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`); if (render.chromeEngine === "hyperframes") errors.push(`${W} does not combine with render.chromeEngine "hyperframes"`); (manifest.timeline ?? []).forEach((e, i) => { if (e?.type === "clip" && e.muteFrom != null) { errors.push(`timeline[${i}] (${e.id}).muteFrom is not supported under ${W}: cut the clip shorter instead`); } }); return errors; } // ---- dates, sources, the counter's words ------------------------------------ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** "20190502", "2019-05-02" (or a longer ISO stamp) → {y, m, d}; anything else → null. */ export function parseClipDate(v) { const s = String(v ?? "").trim(); const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(s); if (!m) return null; const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]; if (mo < 1 || mo > 12 || d < 1 || d > 31) return null; return { y, m: mo, d }; } /** {y, m, d} → "2 May 2019". */ export const formatClipDate = (dt) => (dt ? `${dt.d} ${MONTHS[dt.m - 1]} ${dt.y}` : ""); const PLATFORMS = { youtube: "YouTube", rumble: "Rumble", twitch: "Twitch", kick: "Kick", odysee: "Odysee", x: "X", twitter: "X", bitchute: "BitChute", "archive.org": "archive.org", archiveorg: "archive.org", internetarchive: "archive.org", podcast: "Podcast", tiktok: "TikTok", instagram: "Instagram", facebook: "Facebook", bluesky: "Bluesky", }; /** A platform id as people write it: "youtube" → "YouTube"; unknown → itself, capitalised. */ export function platformLabel(p) { const s = String(p ?? "").trim(); if (!s) return ""; return PLATFORMS[s.toLowerCase()] ?? s[0].toUpperCase() + s.slice(1); } /** * Text safe to put in a drawtext `text='…'`: letters, digits, spaces and * `# · . / -` only, so nothing needs escaping through two parsers. */ export const safeText = (s) => String(s ?? "").replace(/[^\p{L}\p{N} #·./-]/gu, "").replace(/\s+/g, " ").trim(); /** * The counter's words for one clip: `number` ("#12", "#12 of 75") and `line` * (the date and the source the counter shows, joined), each already safeText. */ export function counterText({ n, of = null, date = null, platform = null, showDate = true, showSource = false }) { const number = `#${n}${of ? ` of ${of}` : ""}`; const line = [showDate ? formatClipDate(date) : "", showSource ? platformLabel(platform) : ""].filter(Boolean).join(" · "); return { number: safeText(number), line: safeText(line) }; } // ---- where the phrase is said ------------------------------------------------- const normChar = (ch) => (/[\p{L}\p{N}]/u.test(ch) ? ch.toLowerCase() : ch === "'" || ch === "’" ? "" : " "); /** A phrase as it is matched: lower case, letters and digits, single spaces. */ export const normalisePhrase = (p) => [...String(p ?? "")].map(normChar).join("").replace(/\s+/g, " ").trim(); /** * Timed text: the spans' words (cues, or whisper's words) joined, each kept * character carrying the seconds it is spoken -- a span's characters spread * evenly over the span, so a long word takes longer than a short one. * * @param {Array<{start: number, end: number, text: string}>} spans sorted by start * @returns {{ text: string, t0: number[], t1: number[] }} */ export function timedText(spans) { let text = ""; const t0 = []; const t1 = []; const push = (c, a, b) => { if (c === " " && (text === "" || text.endsWith(" "))) return; text += c; t0.push(a); t1.push(b); }; for (const s of spans) { const chars = [...String(s.text ?? "")]; const L = chars.length; const dur = Math.max(0, s.end - s.start); chars.forEach((ch, i) => { const c = normChar(ch); if (c) push(c, s.start + (dur * i) / L, s.start + (dur * (i + 1)) / L); }); push(" ", s.end, s.end); } return { text, t0, t1 }; } /** * Where a phrase is said: its first character's start and its last * character's end, in the spans' seconds -- the occurrence that overlaps * [from, to] nearest `near` (whole words first, then a phrase that runs on * into a longer word: "slow news days"). Null when it is not there. */ export function locatePhrase(phrase, spans, { from = -Infinity, to = Infinity, near = null } = {}) { const needle = normalisePhrase(phrase); if (!needle) return null; const used = (spans ?? []) .filter((s) => num(s?.start) && num(s?.end) && s.end >= from - 0.5 && s.start <= to + 0.5) .sort((a, b) => a.start - b.start); if (!used.length) return null; const tt = timedText(used); const at = num(near) ? near : (Math.max(from, used[0].start) + Math.min(to, used[used.length - 1].end)) / 2; for (const tail of [true, false]) { let best = null; for (let i = tt.text.indexOf(needle); i >= 0; i = tt.text.indexOf(needle, i + 1)) { const before = i === 0 || tt.text[i - 1] === " "; const j = i + needle.length; const after = j >= tt.text.length || tt.text[j] === " "; if (!before || (tail && !after)) continue; const start = tt.t0[i]; const end = tt.t1[j - 1]; if (end < from || start > to) continue; const d = Math.abs((start + end) / 2 - at); if (!best || d < best.d) best = { d, start, end }; } if (best) return { start: best.start, end: best.end }; } return null; } /** * whisper.cpp's full JSON (`transcription[].tokens[].offsets`, in ms) as * words: a token that starts with a space starts a word, any other continues * the one before; special tokens (`[_BEG_]`, …) are skipped. Only the words in * [from − 2, to + 2]. Null when the document carries no token offsets (a * parakeet `chunk_data`, a cue file). */ export function whisperWords(doc, from = -Infinity, to = Infinity) { if (!Array.isArray(doc?.transcription)) return null; const words = []; let any = false; for (const seg of doc.transcription) { let open = false; for (const tok of seg?.tokens ?? []) { const text = String(tok?.text ?? ""); const off = tok?.offsets; if (!text || /^\s*\[_/.test(text) || !off || !num(off.from) || !num(off.to)) continue; any = true; const s = off.from / 1000; const e = off.to / 1000; if (e < from - 2 || s > to + 2) { open = false; continue; } if (!open || /^\s/.test(text)) { words.push({ start: s, end: e, text: text.trim() }); open = true; } else { const w = words[words.length - 1]; w.text += text; w.end = Math.max(w.end, e); } } } return any && words.length ? words : null; } /** The phrase a clip says: its `montage.match`, else its on-screen title. */ export const clipPhrase = (entry) => { const p = entry?.montage?.match ?? entry?.onscreen?.title ?? null; return typeof p === "string" && p.trim() ? p : null; }; // ---- the plan across the cut ---------------------------------------------------- /** The ramp's cap for clip k of n: lerp(from, to, k/(n−1)), the first `from`, the last `to`. */ export function rampCap(k, n, ramp) { if (!ramp) return null; const f = n > 1 ? k / (n - 1) : 0; return ramp.from + (ramp.to - ramp.from) * f; } /** Every clip's cap under a ramp, in order. */ export const rampCaps = (n, ramp) => Array.from({ length: n }, (_, k) => rampCap(k, n, ramp)); /** Is clip k (0-based, id `id`) stuttered? Every Nth counts from the Nth clip. */ export const stutters = (stutter, k, id) => !!stutter && ((stutter.every != null && (k + 1) % stutter.every === 0) || stutter.clips.includes(id)); /** * The per-clip facts a montage needs from the whole cut, by clip id: k (its * place among the clips), n (how many), `number` and `of` (what the counter * says: the clip's own `montage.n` / `montage.of` when it carries them — so a * take of part of the cut still counts #31 of 75 — else k + 1 and n), its cap * under the ramp, whether it * stutters, its date and year, whether its year differs from the clip * before's, its source, and whether its segment opens or closes the cut * (`first`/`last`: a cut style has nothing to cut from or to there; a wall * at that end takes the edge). * * @param {object[]} timeline the cut's timeline (every entry, in order) * @param {object} settings resolveMontage's * @param {(entry) => string|null} [dateOf] a clip's date when its own fields carry none */ export function planMontage(timeline, settings, dateOf = () => null) { // A wall that is `exclusive` takes its clips out of the run of clips: they // are numbered, ramped and cut only as tiles. What remains is the run. const split = montageSplit(timeline, settings); const shown = split.wallOnly.size ? timeline.filter((e) => !(e?.type === "clip" && split.wallOnly.has(e.id))) : timeline; const clips = shown.filter((e) => e?.type === "clip"); const n = clips.length; const out = new Map(); const ramp = settings.ramp?.into === "wall" && settings.wall ? { from: settings.ramp.from, to: wallFirstGap(settings.wall) } : settings.ramp; 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)); 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) => { const date = parseClipDate(e.montage?.date) ?? parseClipDate(e.date) ?? parseClipDate(dateOf(e)); const year = date?.y ?? null; const i = shown.indexOf(e); const own = Number(e.montage?.n); const number = Number.isInteger(own) && own > 0 ? own : k + 1; const ownOf = Number(e.montage?.of); out.set(e.id, { k, n, number, of: Number.isInteger(ownOf) && ownOf >= number ? ownOf : n, cap: rampCap(k, n, ramp), stutter: stutters(settings.stutter, number - 1, e.id), date, year, yearChange: year != null && year !== prevYear, platform: e.montage?.platform ?? null, first: i === 0 && settings.wall?.at !== "start", last: i === shown.length - 1 && !(settings.wall && settings.wall.at === "end"), }); if (year != null) prevYear = year; }); return out; } // ---- one clip's cut ------------------------------------------------------------------- /** * Where a montage clip is cut, on the fetched file's clock. * * `tighten: "phrase"` with a located phrase: the phrase ± `pad`, inside the * extent; under a ramp, the pads are trimmed (evenly, then whatever one side * lacks from the other) until the cut is no longer than `cap`, never into the * phrase. Then each edge snaps to the nearest silence within `snapWindow` * (build-video's own `snap`), kept only when it stays outside the phrase, * inside the extent and under the cap. Otherwise -- "sentence", null, or no * phrase found -- today's cut: the play window, snapped as every clip is. * * @param {{ extent: [number, number], play: [number, number], phrase: {start: number, end: number}|null, * tighten: string|null, pad: number, cap: number|null, silences: Array<{s: number, e: number}>, * snapWindow: number, render: object, snap: Function }} o * @returns {{ cutA: number, cutB: number, start: {at: number, snapped: boolean}, end: {at: number, snapped: boolean}, tight: boolean }} */ export function montageWindow({ extent, play, phrase, tighten, pad, cap, silences, snapWindow, render, snap }) { const [e0, e1] = extent; const usable = phrase && phrase.end > e0 && phrase.start < e1 && phrase.end > phrase.start; if (tighten !== "phrase" || !usable) { const [w0, w1] = play; const a = snap(w0, silences, "start", snapWindow, render); const b = snap(w1, silences, "end", snapWindow, render); const cutA = Math.min(a.at, w1 - 1); const cutB = Math.max(b.at, cutA + 1); return { cutA, cutB, start: a, end: b, tight: false }; } const p0 = Math.max(e0, phrase.start); const p1 = Math.min(e1, phrase.end); let w0 = Math.max(e0, p0 - pad); let w1 = Math.min(e1, p1 + pad); if (num(cap) && w1 - w0 > cap) { const room = Math.max(0, cap - (p1 - p0)); let before = Math.min(p0 - w0, room / 2); const after = Math.min(w1 - p1, room - before); before = Math.min(p0 - w0, room - after); w0 = p0 - before; w1 = p1 + after; } const limit = num(cap) ? Math.max(cap, w1 - w0) + 1e-6 : Infinity; const s = snap(w0, silences, "start", snapWindow, render); const start = s.snapped && s.at >= e0 - 1e-6 && s.at <= p0 - 0.04 && w1 - s.at <= limit ? s : { at: w0, snapped: false }; const t = snap(w1, silences, "end", snapWindow, render); const end = t.snapped && t.at <= e1 + 1e-6 && t.at >= p1 + 0.04 && t.at - start.at <= limit ? t : { at: w1, snapped: false }; let cutB = end.at; if (cutB - start.at < 0.5) cutB = Math.min(e1, start.at + 0.5); return { cutA: start.at, cutB, start, end, tight: true }; } /** * The segment's picture as pieces of the cut, in FRAMES of the cut's own * clock (frame 0 is the cut's start): `[{ f0, f1, zoom }]`, played in order. * * - a snap punch-in changes the zoom at the phrase's onset (`onset`); * - a stutter plays the phrase's last `length` seconds `times` times in all * ("…news day-day-day"), each repeat `step` more zoomed than the one before. * * @param {{ frames: number, fps: number, onset: number|null, phraseEnd: number|null, * punch: object|null, stutter: object|null }} o onset/phraseEnd in seconds of the cut */ export function montagePieces({ frames, fps, onset = null, phraseEnd = null, punch = null, stutter = null }) { const NF = Math.max(1, frames); const fr = (s) => Math.max(0, Math.min(NF, Math.round(s * fps))); const snapAt = punch?.mode === "snap" && num(onset) ? fr(onset) : null; const zoomAt = (f) => (snapAt != null && f >= snapAt ? punch.scale : 1); let s0 = null; let s1 = null; if (stutter && num(phraseEnd)) { s1 = fr(phraseEnd); s0 = Math.max(0, s1 - Math.round(stutter.length * fps)); if (s1 - s0 < 3) s0 = s1 = null; } const marks = [...new Set([0, NF, ...(snapAt != null && snapAt > 0 && snapAt < NF ? [snapAt] : []), ...(s0 != null ? [s0, s1] : [])])] .sort((a, b) => a - b); const pieces = []; for (let i = 0; i + 1 < marks.length; i += 1) { const f0 = marks[i]; const f1 = marks[i + 1]; if (f1 <= f0) continue; pieces.push({ f0, f1, zoom: zoomAt(f0) }); if (s1 != null && f1 === s1) { const z = zoomAt(s1 - 1); for (let r = 1; r < stutter.times; r += 1) { pieces.push({ f0: s0, f1: s1, zoom: Number((z * (1 + stutter.step * r)).toFixed(4)), repeat: r }); } } } return pieces; } /** The pieces' length in frames. */ export const piecesFrames = (pieces) => pieces.reduce((n, p) => n + (p.f1 - p.f0), 0); // ---- the filtergraph of one montage segment ----------------------------------------- const exprNum = (v) => String(Number(v.toFixed(4))); /** A crop to 1/zoom of the picture, centred across, at the anchor's height. */ const zoomCrop = (zoom, anchor) => `crop=w='floor(iw/${zoom}/2)*2':h='floor(ih/${zoom}/2)*2':x='(iw-ow)/2':y='(ih-oh)*${anchor === "center" ? 0.5 : 0.35}'`; /** * The pieces as a graph: from the cut's raw picture and sound to the * segment's picture, fitted to `box` (letterboxed in `bg`), and its sound, * exactly `frames` long. A drift punch-in zooms the whole thing, 1 → scale. * Each joint of a stutter fades 5 ms; the segment's own edges fade * DECLICK, always. * * @returns {{ parts: string[], v: string, a: string, frames: number, seconds: number }} */ export function montagePiecesGraph({ pieces, fps, box, bg, punch = null, inV = "[0:v]", inA = "[0:a]", hasVideo = true, gainDb = null }) { const frames = piecesFrames(pieces); const seconds = frames / fps; const parts = []; const anchor = punch?.anchor ?? "upper"; const fit = `scale=${box.w}:${box.h}:force_original_aspect_ratio=decrease,pad=${box.w}:${box.h}:(ow-iw)/2:(oh-ih)/2:color=${bg},setsar=1`; const P = pieces.length; const vLabels = []; const aLabels = []; if (hasVideo) { if (P === 1) parts.push(`${inV}fps=${fps}[mvs0]`); else parts.push(`${inV}fps=${fps},split=${P}${pieces.map((_, i) => `[mvs${i}]`).join("")}`); } parts.push(P === 1 ? `${inA}anull[mas0]` : `${inA}asplit=${P}${pieces.map((_, i) => `[mas${i}]`).join("")}`); pieces.forEach((p, i) => { if (hasVideo) { const z = p.zoom !== 1 ? `,${zoomCrop(p.zoom, anchor)}` : ""; parts.push(`[mvs${i}]trim=start_frame=${p.f0}:end_frame=${p.f1},setpts=PTS-STARTPTS${z},${fit}[mv${i}]`); vLabels.push(`[mv${i}]`); } const a0 = p.f0 / fps; const a1 = p.f1 / fps; const len = a1 - a0; const joint = P > 1 && len > 4 * JOINT_FADE ? `,afade=t=in:d=${JOINT_FADE},afade=t=out:st=${exprNum(len - JOINT_FADE)}:d=${JOINT_FADE}` : ""; parts.push(`[mas${i}]atrim=start=${exprNum(a0)}:end=${exprNum(a1)},asetpts=PTS-STARTPTS${joint}[ma${i}]`); aLabels.push(`[ma${i}]`); }); if (hasVideo) { if (P === 1) parts.push(`${vLabels[0]}null[mvc]`, `${aLabels[0]}anull[mac]`); else parts.push(`${pieces.map((_, i) => `${vLabels[i]}${aLabels[i]}`).join("")}concat=n=${P}:v=1:a=1[mvc][mac]`); } else { parts.push(P === 1 ? `${aLabels[0]}anull[mac]` : `${aLabels.join("")}concat=n=${P}:v=0:a=1[mac]`); } if (hasVideo) { // Never a frame more or less than the plan: a short source is held on its // last frame, a long one cut. const exact = `tpad=stop_mode=clone:stop_duration=1,trim=end_frame=${frames},setpts=PTS-STARTPTS`; if (punch?.mode === "drift") { const ay = anchor === "center" ? 0.5 : 0.35; parts.push( `[mvc]${exact},scale=${box.w * 2}:${box.h * 2},` + `zoompan=z='1+${exprNum(punch.scale - 1)}*on/${Math.max(1, frames - 1)}':x='iw/2-iw/zoom/2':y='(ih-ih/zoom)*${ay}':d=1:s=${box.w}x${box.h}:fps=${fps},setsar=1[mv]`, ); } else { parts.push(`[mvc]${exact}[mv]`); } } const D = exprNum(seconds); const declick = seconds > 4 * DECLICK ? `,afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(seconds - DECLICK)}:d=${DECLICK}` : ""; 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 }; } /** * The cut style, on one segment's finished picture: its first frames (unless * it opens the cut) and its last (unless it closes it). Flash: the first * CUT_FRAMES.flash frames fade from the flash colour. Dip: the last two fade * to black, the first two up from it. Whip: the last four slide out to the * left and the first four in from the right, wrapped and blurred along the * move. Hard: nothing. * * @returns {string[]} parts from `inLabel` to `outLabel` */ export function cutStyleParts({ cut, first, last, frames, fps, w, h, flashColor = "#ffffff", inLabel, outLabel }) { const f = (n) => exprNum(n / fps); if (cut === "flash" && !first && frames > CUT_FRAMES.flash) { return [`${inLabel}fade=t=in:st=0:d=${f(CUT_FRAMES.flash)}:color=${flashColor}${outLabel}`]; } if (cut === "dip") { const n = CUT_FRAMES.dip; const chain = []; if (!first && frames > n) chain.push(`fade=t=in:st=0:d=${f(n)}`); if (!last && frames > 2 * n + 1) chain.push(`fade=t=out:st=${f(frames - n - 1)}:d=${f(n)}`); if (chain.length) return [`${inLabel}${chain.join(",")}${outLabel}`]; } if (cut === "whip") { const n = CUT_FRAMES.whip; const head = !first; const tail = !last; if ((head || tail) && frames > 2 * n + 1) { // The picture beside a copy of itself, cropped at x: shifted left by x, // wrapped -- under the blur, a whip pan. `n` inside the quotes is crop's // own frame number. const blur = `avgblur=sizeX=${Math.max(2, Math.round(w * 0.035))}:sizeY=1`; const slide = (x) => `hstack,crop=w=${w}:h=${h}:x='${x}':y=0,${blur}`; const parts = []; const segs = []; const take = [head ? "[wph]" : null, "[wpb]", tail ? "[wpt]" : null].filter(Boolean); parts.push(`${inLabel}split=${take.length}${take.join("")}`); if (head) { // In from the right: shifted right by d·w, d easing 0.58 → 0.04. parts.push( `[wph]trim=end_frame=${n},setpts=PTS-STARTPTS,split[wh1][wh2]`, `[wh1][wh2]${slide(`${w}*(1-0.9*pow(1-(n+1)/${n + 1},2))`)}[wh]`, ); segs.push("[wh]"); } parts.push(`[wpb]trim=start_frame=${head ? n : 0}:end_frame=${tail ? frames - n : frames},setpts=PTS-STARTPTS[wb]`); segs.push("[wb]"); if (tail) { // Out to the left: shifted left by d·w, d easing 0.04 → 0.58. parts.push( `[wpt]trim=start_frame=${frames - n},setpts=PTS-STARTPTS,split[wt1][wt2]`, `[wt1][wt2]${slide(`${w}*0.9*pow((n+1)/${n + 1},2)`)}[wt]`, ); segs.push("[wt]"); } parts.push(`${segs.join("")}concat=n=${segs.length}:v=1:a=0${outLabel}`); return parts; } } return [`${inLabel}null${outLabel}`]; } /** Where a corner overlay sits: drawtext/drawbox x and y for a block w×h, `m` from the edges. */ function corner(position, m) { const right = position.endsWith("right"); const bottom = position.startsWith("bottom"); return { right, bottom, x: (w) => (right ? `W-${m}-${w}` : String(m)), y: (h) => (bottom ? `H-${m}-${h}` : String(m)), }; } /** * Tally marks for a count: groups of five, four uprights struck through by * the fifth, ten groups a row. Boxes relative to the tally's top-left, and * its bounds; the LAST box is the newest mark. * * @returns {{ marks: Array<{x: number, y: number, w: number, h: number, strike: boolean}>, width: number, height: number }} */ export function tallyMarks(count, H) { const mw = Math.max(2, Math.round(H * 0.0055)); const mh = Math.round(H * 0.05); const gap = Math.round(H * 0.012); const groupGap = Math.round(H * 0.026); const rowGap = Math.round(H * 0.022); const gw = 4 * mw + 3 * gap; const perRow = 10; const over = Math.round(gap * 0.7); const marks = []; for (let i = 0; i < count; i += 1) { const g = Math.floor(i / 5); const r = i % 5; const gx = over + (g % perRow) * (gw + groupGap); const gy = Math.floor(g / perRow) * (mh + rowGap); if (r < 4) marks.push({ x: gx + r * (mw + gap), y: gy, w: mw, h: mh, strike: false }); else marks.push({ x: gx - over, y: gy + Math.round(mh * 0.45), w: gw + 2 * over, h: mw, strike: true }); } const groups = Math.ceil(count / 5); const cols = Math.min(perRow, Math.max(1, groups)); const rows = Math.max(1, Math.ceil(groups / perRow)); return { marks, width: 2 * over + cols * gw + (cols - 1) * groupGap, height: rows * mh + (rows - 1) * rowGap }; } /** * The counter and the year stamp over one segment's finished picture: drawtext * and drawbox only, timed on the segment's own clock. * * - chip: "#12 · 2 May 2019 · YouTube" on a translucent ground, the whole clip; * - big: the number, large, slamming in (1.9× → 1× over 0.18 s), held, gone by * 1.5 s, with the date line under it; * - tally: the marks so far, the newest landing at 0.12 s in the accent; * - the year stamp: the year, large, in the corner across from the counter, * for about a second, on a clip whose year differs from the one before. * * @returns {string[]} filters, to join with "," (empty: nothing to draw) */ export function montageOverlayFilters({ settings, ctx, render, font }) { const { width: W, height: H } = render; const pal = render.palette ?? {}; const fg = pal.fg ?? "#ffffff"; const bg = pal.bg ?? "#000000"; const accent = pal.accent ?? fg; const m = Math.round(H * 0.035); const out = []; const dt = (o) => ["drawtext=" + `fontfile='${font}'`, "expansion=none", ...Object.entries(o).map(([k, v]) => `${k}=${v}`)].join(":"); const c = settings.counter; if (c) { const words = counterText({ n: ctx.number ?? ctx.k + 1, of: c.of ? (ctx.of ?? ctx.n) : null, date: ctx.date, platform: ctx.platform, showDate: c.showDate, showSource: c.showSource, }); const at = corner(c.position, m); if (c.style === "chip") { const fs = Math.round(H * 0.034); const text = [words.number, words.line].filter(Boolean).join(" · "); const pad = Math.round(fs * 0.45); // The ground reaches `pad` past the text on every side; the ground is `m` from the edges. out.push(dt({ text: `'${text}'`, fontsize: fs, fontcolor: fg, box: 1, boxcolor: `${bg}@0.72`, boxborderw: pad, x: at.right ? `W-${m + pad}-text_w` : String(m + pad), y: at.bottom ? `H-${m + pad}-text_h` : String(m + pad), })); } else if (c.style === "big") { const fs = Math.round(H * 0.24); const small = Math.round(H * 0.036); const alpha = `'min(1,t/0.04)*if(lt(t,1.2),1,max(0,1-(t-1.2)/0.3))'`; const lineH = words.line ? Math.round(small * 1.5) : 0; out.push(dt({ text: `'${words.number.replace(/^#/, "")}'`, fontsize: `'${fs}*(1+0.9*max(0,1-t/0.18))'`, fontcolor: accent, borderw: Math.max(2, Math.round(fs * 0.025)), bordercolor: bg, alpha, x: at.x("text_w"), y: at.bottom ? `H-${m + lineH}-text_h` : String(m), })); if (words.line) { out.push(dt({ text: `'${words.line}'`, fontsize: small, fontcolor: fg, borderw: 2, bordercolor: bg, alpha, x: at.x("text_w"), y: at.bottom ? `H-${m}-text_h` : String(m + Math.round(fs * 1.05)), })); } } else if (c.style === "tally") { const t = tallyMarks(ctx.number ?? ctx.k + 1, H); const pad = Math.round(H * 0.012); const small = Math.round(H * 0.03); const lineH = words.line ? Math.round(small * 1.6) : 0; const bw = t.width + 2 * pad; const bh = t.height + 2 * pad + lineH; const x0 = at.right ? W - m - bw : m; const y0 = at.bottom ? H - m - bh : m; out.push(`drawbox=x=${x0}:y=${y0}:w=${bw}:h=${bh}:color=${bg}@0.6:t=fill`); t.marks.forEach((mk, i) => { const newest = i === t.marks.length - 1; out.push( `drawbox=x=${x0 + pad + mk.x}:y=${y0 + pad + mk.y}:w=${mk.w}:h=${mk.h}:color=${newest ? accent : fg}:t=fill` + (newest ? ":enable='gte(t,0.12)'" : ""), ); }); if (words.line) { // On a ground of its own: the line is wider than a short tally. out.push(dt({ text: `'${words.line}'`, fontsize: small, fontcolor: fg, box: 1, boxcolor: `${bg}@0.6`, boxborderw: pad, x: x0 + pad, y: y0 + pad + t.height + Math.round(small * 0.35), })); } } } if (settings.yearStamp && ctx.yearChange && ctx.year != null) { const across = c ? (c.position.endsWith("left") ? c.position.replace("left", "right") : c.position.replace("right", "left")) : "top-right"; const at = corner(across, m); const fs = Math.round(H * 0.16); out.push(dt({ text: `'${ctx.year}'`, fontsize: fs, fontcolor: fg, borderw: Math.max(2, Math.round(fs * 0.03)), bordercolor: bg, alpha: `'if(lt(t,0.08),t/0.08,if(lt(t,1),1,max(0,1-(t-1)/0.25)))'`, x: at.x("text_w"), y: at.y("text_h"), })); } return out; } /** The font a montage's words are drawn in: the render's bold, else its regular, else Plex Mono Bold. */ export const montageFont = (render) => render.fontBold ?? render.fontRegular ?? MONO_BOLD_FONT_FILE; // ---- the wall --------------------------------------------------------------------------- /** * Which clips the wall's tiles play, in order: `tiles` spread evenly over the * cut's clips, first to last (the first tile the earliest); fewer clips than * tiles go round again. */ export function wallTileClips(ids, tiles, clips = "spread") { const n = ids.length; if (!n) return []; // "tail": the LAST `tiles` clips, in order -- the most recent instances. if (clips === "tail" && n >= tiles) return ids.slice(n - tiles); if (n >= tiles) return Array.from({ length: tiles }, (_, j) => ids[tiles > 1 ? Math.round((j * (n - 1)) / (tiles - 1)) : 0]); return Array.from({ length: tiles }, (_, j) => ids[j % n]); } /** * 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 clips = (timeline ?? []).filter((e) => e?.type === "clip"); const ids = clips.map((e) => e.id); const w = settings?.wall; 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)) }; } /** * The sizes of the wall's groups, in order of arrival. "single": one tile at * a time. "double": 1, 1, 2, 4, 8 … -- each group twice the one before -- and * what is left over that a doubling would overrun is a last group of its own * when it is at least as big as the group before it, else joins that group: * 9 → 1,1,2,5; 16 → 1,1,2,4,8; 25 → 1,1,2,4,8,9. */ export function wallGroups(tiles, mode = "single") { if (mode !== "double") return Array(tiles).fill(1); const sizes = []; let left = tiles; for (let k = 0; left > 0; k += 1) { const size = k < 2 ? 1 : 2 ** (k - 1); if (left >= size) { sizes.push(size); left -= size; } else { if (left >= sizes[sizes.length - 1]) sizes.push(left); else sizes[sizes.length - 1] += left; left = 0; } } return sizes; } /** * When each of the wall's groups arrives, in seconds from its first, and the * gap after each (the last gap runs to the final beat; they sum to `build`). * "single": tile i at build·(1 − (1 − i/tiles)²). "double": the gaps fall * evenly from the first to half of it -- each beat a little sooner than the * one before. */ export function wallBeats({ tiles, build, groups = "single" }) { const sizes = wallGroups(tiles, groups); const G = sizes.length; let beats; if (groups !== "double") { beats = sizes.map((_, i) => build * (1 - (1 - i / tiles) ** 2)); } else { const g0 = G > 1 ? build / (0.75 * G) : build; beats = [0]; for (let i = 1; i < G; i += 1) beats.push(beats[i - 1] + g0 * (1 - (0.5 * (i - 1)) / (G - 1))); } const gaps = beats.map((b, i) => (i + 1 < G ? beats[i + 1] : build) - b); return { sizes, beats, gaps }; } /** The wall's first gap: how long its first group (or tile) has before the next -- what `ramp.into: "wall"` ends on. */ export const wallFirstGap = (wall) => wallBeats({ tiles: wall.tiles, build: wall.build, groups: wall.groups }).gaps[0]; /** * The wall, laid out and timed. A √tiles grid of frame-shaped tiles, centred, * `gap` apart. Tile i appears at build·(1 − (1 − i/tiles)²) -- the gaps * between appearances shrink, so the last tiles come fastest -- and plays its * phrase; at `build` every tile plays its phrase again, together, for the * longest phrase (0.8–2.5 s) and a quarter second; then the cut. All on frames. * * @param {{ tiles: number, build: number, durations: number[], fps: number, width: number, height: number }} o * `durations` each tile's phrase seconds */ export function wallPlan({ tiles, build, durations, fps, width, height, 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; const maxH = (height - gap * (cols + 1)) / cols; let w = Math.floor(Math.min(maxW, (maxH * width) / height)); w -= w % 2; let h = Math.floor((w * height) / width); h -= h % 2; const gridW = cols * w + (cols - 1) * gap; const gridH = cols * h + (cols - 1) * gap; const ox = Math.floor((width - gridW) / 2); const oy = Math.floor((height - gridH) / 2); const q = (s) => Math.round(s * fps); // 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 } }); } const appearF = Array.from({ length: tiles }, (_, i) => q(build * (1 - (1 - i / tiles) ** 2))); const beatF = q(build); const longest = Math.max(0.8, Math.min(2.5, ...durations.map((d) => (num(d) ? d : 0.8)))); const beatLenF = q(longest + 0.25); return { cols, gap, layout, tileW: w, tileH: h, appear: appearF.map((f) => f / fps), appearFrames: appearF, beat: beatF / fps, beatFrames: beatF, beatLen: beatLenF / fps, frames: beatF + beatLenF, seconds: (beatF + beatLenF) / fps, }; } /** * The wall timed by GROUPS (`groups: "double"`) and/or SYNCED (`leads`: each * tile's seconds from its first frame to its phrase's onset). A group's * tiles arrive on its beat; a synced tile shows `lead` before it, so its * onset lands ON the beat, and restarts `lead` before the final beat, so * the crowd's onsets land on one frame. The beats start late enough that * the earliest show is the wall's first frame. All on frames. */ function groupedWallPlan({ tiles, build, durations, fps, groups, leads, q, base }) { const { sizes, beats, gaps } = wallBeats({ tiles, build, groups }); const groupOf = sizes.flatMap((n, g) => Array(n).fill(g)); const leadF = Array.from({ length: tiles }, (_, i) => (leads ? q(Math.max(0, leads[i] ?? 0)) : 0)); const t0 = Math.max(0, ...leadF); const groupBeatF = beats.map((b) => t0 + q(b)); const finalF = t0 + q(build); const appearF = groupOf.map((g, i) => groupBeatF[g] - leadF[i]); const restartF = leadF.map((l) => finalF - l); const after = durations.map((d, i) => (num(d) ? d : 0.8) - leadF[i] / fps); const longest = Math.max(0.8, Math.min(2.5, ...after)); const frames = finalF + q(longest + 0.25); return { ...base, grouped: true, groups: sizes, groupOf, gaps, groupBeats: groupBeatF.map((f) => f / fps), groupBeatFrames: groupBeatF, appear: appearF.map((f) => f / fps), appearFrames: appearF, restart: restartF.map((f) => f / fps), restartFrames: restartF, leads: leadF.map((f) => f / fps), beat: finalF / fps, beatFrames: finalF, beatLen: (frames - finalF) / fps, frames, seconds: frames / fps, }; } /** * One wall tile: the clip's phrase (from–to on the fetched file's clock), * filled into the tile (cropped, never letterboxed), its year at the foot * when the wall says so. */ export function wallTileArgs({ raw, from, to, tileW, tileH, fps, year = null, text = null, gainDb = null, font, render, encode, outPath }) { const fs = Math.max(10, Math.round(tileH * 0.11)); // `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]` + (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`) --------------------------------------- /** Integrated loudness under this (LUFS) is near-silence: the phrase is not where it was looked for. */ export const SILENT_LUFS = -40; /** …and so is a stretch this far (LU) under the run's median so far. */ export const SILENT_UNDER_MEDIAN = 15; /** * Is a measured stretch near-silent: under SILENT_LUFS, unmeasurable, or * SILENT_UNDER_MEDIAN under `median` (the run's so far, when known)? */ export function nearSilent(measured, median = null) { if (!num(measured)) return true; return measured < SILENT_LUFS || (num(median) && measured < median - SILENT_UNDER_MEDIAN); } /** The median of the numbers given, or null. */ export function median(values) { const v = values.filter(num).sort((a, b) => a - b); if (!v.length) return null; return v.length % 2 ? v[(v.length - 1) / 2] : (v[v.length / 2 - 1] + v[v.length / 2]) / 2; } /** * Where a mislocated phrase really is, by the sound: of every `len`-second * stretch of the excerpt (`env`, speechEnvelope dBFS frames every `hop` s from * `start`) that is speech (`share` of its frames at ≥ `speechDb`), the one starting * nearest `est` -- a phrase estimated into the silence after a long cue * lands on the speech that ends there. Ties go to the later. Null when the * excerpt holds no speech. */ export function relocateBySound(env, { hop = 0.005, start = 0, est, len, speechDb = -40, share = 0.75 }) { const n = Math.max(1, Math.round(len / hop)); if (env.length < n) return null; // Frames at speech level, counted over a sliding window: a stretch is // speech when `share` of it is. let sum = 0; for (let k = 0; k < n; k += 1) sum += env[k] >= speechDb ? 1 : 0; let best = null; for (let k = 0; k + n <= env.length; k += 1) { if (k > 0) sum += (env[k + n - 1] >= speechDb ? 1 : 0) - (env[k - 1] >= speechDb ? 1 : 0); if (sum < share * n) continue; const t = start + k * hop; const d = Math.abs(t - est); if (!best || d < best.d - 1e-9 || Math.abs(d - best.d) <= 1e-9) best = { d, t }; } return best ? Number(best.t.toFixed(3)) : null; } /** * Whether a consensus shift may stand: the `span` seconds after the shifted * onset may be no more than `maxDrop` dB quieter (mean of `env`, dB frames * every `hop` from the excerpt's start) than the span after the estimate, * which sits `pre` seconds in. A shift into a pause is refused. */ export function shiftAllowed(env, { hop = 0.005, pre, shift, span = 0.4, maxDrop = 10 }) { const mean = (t) => { const a = Math.max(0, Math.round(t / hop)); const b = Math.min(env.length, a + Math.max(1, Math.round(span / hop))); if (b <= a) return -100; let s = 0; for (let k = a; k < b; k += 1) s += env[k]; return s / (b - a); }; return mean(pre + shift) >= mean(pre) - maxDrop; } /** 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) { // Near-silence is a phrase in the wrong place, never a quiet clip to raise. if (!num(measured) || measured <= LOUDNESS_FLOOR || measured < SILENT_LUFS) 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. * Sound: each tile at full level until the next one appears, then ducked; * the beat's tiles all together (a crowd), limited. Then the cut style and * the de-click, as any segment. * * @param {{ tiles: Array<{ file: string, seconds: number }>, plan: object, render: object, * settings: object, first: boolean, last: boolean, encode: string[], outPath: string }} o */ export function wallComposeArgs({ tiles, plan, render, settings, first, last, encode, outPath }) { if (plan.grouped) return groupedWallComposeArgs({ tiles, plan, render, settings, first, last, encode, outPath }); const { fps } = render; const bg = render.palette?.bg ?? "#000000"; const T = tiles.length; const beat = exprNum(plan.beat); const parts = []; const vs = []; const as = []; const crowd = exprNum(Math.min(1, 1.6 / Math.sqrt(T))); tiles.forEach((t, i) => { const at = plan.appear[i]; const once = Math.max(1 / fps, Math.min(t.seconds, plan.beat - at)); const again = Math.min(t.seconds, plan.beatLen); parts.push( `[${i}:v]split[wv${i}a][wv${i}b]`, `[wv${i}a]trim=end=${exprNum(once)},setpts=PTS-STARTPTS,fps=${fps},` + `tpad=start_duration=${exprNum(at)}:start_mode=add:color=${bg}:stop_mode=clone:stop_duration=${beat},trim=end_frame=${plan.beatFrames}[wv${i}c]`, `[wv${i}b]trim=end=${exprNum(again)},setpts=PTS-STARTPTS,fps=${fps},tpad=stop_mode=clone:stop_duration=${exprNum(plan.beatLen)},` + `trim=end_frame=${plan.frames - plan.beatFrames}[wv${i}d]`, `[wv${i}c][wv${i}d]concat=n=2:v=1:a=0[wt${i}]`, ); vs.push(`[wt${i}]`); const next = i + 1 < T ? plan.appear[i + 1] - at : Infinity; const duck = Number.isFinite(next) ? `,volume='if(lt(t,${exprNum(next)}),1,0.22)':eval=frame` : ""; const delay = (s) => Math.round(s * 1000); parts.push( `[${i}:a]asplit[wa${i}a][wa${i}b]`, `[wa${i}a]atrim=end=${exprNum(once)},asetpts=PTS-STARTPTS${duck},adelay=${delay(at)}:all=1[wa${i}c]`, `[wa${i}b]atrim=end=${exprNum(again)},asetpts=PTS-STARTPTS,volume=${crowd},adelay=${delay(plan.beat)}:all=1[wa${i}d]`, ); as.push(`[wa${i}c]`, `[wa${i}d]`); }); // 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}:${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, flashColor: settings.flashColor, inLabel: "[wg]", outLabel: "[v]", })); parts.push( `${as.join("")}amix=inputs=${as.length}:normalize=0:duration=longest,alimiter=limit=0.9,` + wallAudioLength(plan, render) + `afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(plan.seconds - DECLICK)}:d=${DECLICK}[a]`, ); return [ "-nostdin", "-v", "error", "-y", ...tiles.flatMap((t) => ["-i", t.file]), "-filter_complex", parts.join(";"), "-map", "[v]", "-map", "[a]", "-frames:v", String(plan.frames), ...encode, outPath, ]; } /** How long a group's tiles take to slide into place, in frames. */ export const WALL_SLIDE_FRAMES = 4; /** * The grouped (and/or synced) wall's compose. Each tile is laid on the * ground at its own time, sliding in from the right over WALL_SLIDE_FRAMES * (a short whip of the group into place); it plays its phrase once and * freezes, and plays it again from its restart. Sound: a group's tiles in * unison, each at min(1, 1.25/√size); a tile falls silent (a 40 ms fade) just * before the next group's beat, so each group is heard alone; at the final * beat every tile together (the crowd), limited. Then the cut style and the * de-click, as any segment. */ function groupedWallComposeArgs({ tiles, plan, render, settings, first, last, encode, outPath }) { const { fps } = render; const bg = render.palette?.bg ?? "#000000"; const T = tiles.length; const total = exprNum(plan.seconds); const parts = [`color=c=${bg}:s=${render.width}x${render.height}:r=${fps}:d=${total},setsar=1[wc0]`]; const as = []; const crowd = exprNum(Math.min(1, 1.6 / Math.sqrt(T))); const slide = WALL_SLIDE_FRAMES / fps; const delay = (sec) => Math.round(sec * 1000); tiles.forEach((t, i) => { const g = plan.groupOf[i]; const at = plan.appear[i]; const restart = plan.restart[i]; // Silent from just before the next group's beat (or the final one). const next = (g + 1 < plan.groups.length ? plan.groupBeats[g + 1] : plan.beat) - 0.04; const once = Math.max(1 / fps, Math.min(t.seconds, next - at, restart - at)); const again = Math.max(1 / fps, Math.min(t.seconds, plan.seconds - restart)); const firstF = plan.restartFrames[i] - plan.appearFrames[i]; const secondF = plan.frames - plan.restartFrames[i]; parts.push( `[${i}:v]split[wv${i}a][wv${i}b]`, `[wv${i}a]trim=end=${exprNum(once)},setpts=PTS-STARTPTS,fps=${fps},tpad=stop_mode=clone:stop_duration=${total},trim=end_frame=${firstF}[wv${i}c]`, `[wv${i}b]trim=end=${exprNum(again)},setpts=PTS-STARTPTS,fps=${fps},tpad=stop_mode=clone:stop_duration=${total},trim=end_frame=${secondF}[wv${i}d]`, `[wv${i}c][wv${i}d]concat=n=2:v=1:a=0,setpts=PTS-STARTPTS+${exprNum(at)}/TB[wt${i}]`, ); const l = plan.layout[i]; const D = Math.round(plan.tileW * 0.5); parts.push( `[wc${i}][wt${i}]overlay=x='${l.x}+${D}*pow(max(0,1-(t-${exprNum(at)})/${exprNum(slide)}),2)':y=${l.y}:` + `enable='gte(t,${exprNum(at)})':eof_action=pass[wc${i + 1}]`, ); const level = exprNum(Math.min(1, 1.25 / Math.sqrt(plan.groups[g]))); const fade = Math.min(0.04, once / 2); parts.push( `[${i}:a]asplit[wa${i}a][wa${i}b]`, `[wa${i}a]atrim=end=${exprNum(once)},asetpts=PTS-STARTPTS,volume=${level},` + `afade=t=out:st=${exprNum(once - fade)}:d=${exprNum(fade)},adelay=${delay(at)}:all=1[wa${i}c]`, `[wa${i}b]atrim=end=${exprNum(again)},asetpts=PTS-STARTPTS,volume=${crowd},adelay=${delay(restart)}:all=1[wa${i}d]`, ); as.push(`[wa${i}c]`, `[wa${i}d]`); }); parts.push(`[wc${T}]fps=${fps}[wg]`); parts.push(...cutStyleParts({ cut: settings.cut, first, last, frames: plan.frames, fps, w: render.width, h: render.height, flashColor: settings.flashColor, inLabel: "[wg]", outLabel: "[v]", })); parts.push( `${as.join("")}amix=inputs=${as.length}:normalize=0:duration=longest,alimiter=limit=0.9,` + wallAudioLength(plan, render) + `afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(plan.seconds - DECLICK)}:d=${DECLICK}[a]`, ); return [ "-nostdin", "-v", "error", "-y", ...tiles.flatMap((t) => ["-i", t.file]), "-filter_complex", parts.join(";"), "-map", "[v]", "-map", "[a]", "-frames:v", String(plan.frames), ...encode, outPath, ]; } // ---- where a phrase starts, in the sound ------------------------------------------------ /** * The sound's loudness over time: RMS in dB (floor −100) over `win`-second * windows every `hop` seconds. Frame k covers [k·hop, k·hop + win). * * @param {ArrayLike} samples mono, any scale */ export function speechEnvelope(samples, rate, { win = 0.02, hop = 0.005 } = {}) { const W = Math.max(1, Math.round(win * rate)); const H = Math.max(1, Math.round(hop * rate)); const n = Math.max(0, Math.floor((samples.length - W) / H) + 1); const out = new Float64Array(n); for (let k = 0; k < n; k += 1) { let acc = 0; for (let j = k * H; j < k * H + W; j += 1) acc += samples[j] * samples[j]; out[k] = Math.max(-100, 10 * Math.log10(acc / W + 1e-12)); } return out; } /** * A phrase's onset, refined against its sound: near `est` (seconds into * `samples`), the moment the loudness rises most sharply -- the mean over * the next `after` seconds less the mean over the `before` seconds before it * -- scored as that rise less `penalty` dB per second away from `est`, within * ±`window`. Null when no rise reaches `minRise` dB (keep the estimate). * The caller feeds speech-band sound (build-video high-passes it at 200 Hz). * * @returns {{ at: number, rise: number } | null} */ export function refineOnset(samples, rate, est, { window = 0.4, before = 0.06, after = 0.05, minRise = 6, penalty = 6, hop = 0.005, win = 0.02 } = {}) { const env = speechEnvelope(samples, rate, { win, hop }); if (!env.length) return null; const nb = Math.max(1, Math.round(before / hop)); const na = Math.max(1, Math.round(after / hop)); const mean = (a, b) => { let s = 0; for (let k = a; k < b; k += 1) s += env[k]; return s / (b - a); }; let best = null; const lo = Math.max(nb, Math.ceil((est - window - win + hop) / hop)); const hi = Math.min(env.length - na, Math.floor((est + window - win + hop) / hop)); for (let k = lo; k <= hi; k += 1) { // Frame k starts at k·hop: the boundary between the quiet and the loud. // The largest rise has the last quiet window ending just before the // sound starts: its start plus a window, less a hop. const t = k * hop + win - hop; const rise = mean(k, k + na) - mean(k - nb, k); if (rise < minRise) continue; const score = rise - penalty * Math.abs(t - est); if (!best || score > best.score) best = { at: t, rise, score }; } return best ? { at: best.at, rise: best.rise } : null; } /** * How far `b` is shifted against `a` (frames of the envelope; positive: `b` * comes later), by the normalised cross-correlation over ±maxLag -- a check * of alignment that does not use the onset finder. */ export function envelopeLag(a, b, maxLag) { const z = (x) => { const m = x.reduce((s, v) => s + v, 0) / x.length; return Array.from(x, (v) => v - m); }; const A = z(a); const B = z(b); let best = { lag: 0, r: -Infinity }; for (let lag = -maxLag; lag <= maxLag; lag += 1) { let num = 0; let da = 0; let db = 0; for (let i = 0; i < A.length; i += 1) { const j = i + lag; if (j < 0 || j >= B.length) continue; num += A[i] * B[j]; da += A[i] * A[i]; db += B[j] * B[j]; } const r = da && db ? num / Math.sqrt(da * db) : -Infinity; if (r > best.r) best = { lag, r }; } return best; } // ---- the crowd in unison: aligning every tile's phrase to the others' -------------------- /** In-place radix-2 FFT of `re`/`im` (length a power of two). */ function fft(re, im) { const n = re.length; for (let i = 1, j = 0; i < n; i += 1) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } } for (let len = 2; len <= n; len <<= 1) { const ang = (-2 * Math.PI) / len; for (let i = 0; i < n; i += len) { for (let k = 0; k < len / 2; k += 1) { const wr = Math.cos(ang * k); const wi = Math.sin(ang * k); const ar = re[i + k + len / 2]; const ai = im[i + k + len / 2]; const xr = ar * wr - ai * wi; const xi = ar * wi + ai * wr; re[i + k + len / 2] = re[i + k] - xr; im[i + k + len / 2] = im[i + k] - xi; re[i + k] += xr; im[i + k] += xi; } } } } /** The bands a phrase's sound is compared in, Hz: low voice to sibilants. */ export const SPEECH_BANDS = Object.freeze([200, 400, 700, 1100, 1700, 2600, 4000, 6000, 8000]); /** * The sound as log energy per speech band, every `hop` seconds over a * 512-sample Hann window (32 ms at 16 kHz): frames × bands, each band less * its own mean over the excerpt (so a louder or duller source compares the * same). Frame k is centred at k·hop + 256/rate. */ export function bandFeatures(samples, rate, { hop = 0.005, size = 512, bands = SPEECH_BANDS } = {}) { const H = Math.max(1, Math.round(hop * rate)); const n = Math.max(0, Math.floor((samples.length - size) / H) + 1); const hann = Float64Array.from({ length: size }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (size - 1))); const edges = bands.map((f) => Math.min(size / 2, Math.round((f * size) / rate))); const out = []; const re = new Float64Array(size); const im = new Float64Array(size); for (let k = 0; k < n; k += 1) { for (let i = 0; i < size; i += 1) { re[i] = (samples[k * H + i] / 32768) * hann[i]; im[i] = 0; } fft(re, im); const row = new Float64Array(edges.length - 1); for (let b = 0; b + 1 < edges.length; b += 1) { let e = 0; for (let j = edges[b]; j < Math.max(edges[b] + 1, edges[b + 1]); j += 1) e += re[j] * re[j] + im[j] * im[j]; row[b] = Math.log10(e + 1e-10); } out.push(row); } const B = edges.length - 1; for (let b = 0; b < B; b += 1) { const m = out.reduce((acc, r) => acc + r[b], 0) / Math.max(1, out.length); for (const r of out) r[b] -= m; } return out; } /** Pearson correlation of two blocks of frames (rows of equal width). */ function blockCorr(A, a0, B, b0, len) { let sa = 0, sb = 0, saa = 0, sbb = 0, sab = 0, n = 0; for (let f = 0; f < len; f += 1) { const ra = A[a0 + f]; const rb = B[b0 + f]; if (!ra || !rb) continue; for (let b = 0; b < ra.length; b += 1) { const x = ra[b]; const y = rb[b]; sa += x; sb += y; saa += x * x; sbb += y * y; sab += x * y; n += 1; } } if (!n) return -Infinity; const cov = sab - (sa * sb) / n; const va = saa - (sa * sa) / n; const vb = sbb - (sb * sb) / n; return va > 0 && vb > 0 ? cov / Math.sqrt(va * vb) : -Infinity; } /** * Every tile's phrase aligned to all the others' (a consensus, no reference * needed): `feats[i]` are tile i's band frames with its estimated onset at * frame `origin`; the template is the mean of the others as currently * aligned, compared over `span` frames from `origin − pre`, and each tile's * shift is searched within ±`search` frames; repeated `iterations` times. * The common shift is then taken out (the median is 0), so on the whole the * estimates' clock is kept and only the tiles' disagreement is removed. * * @returns {{ lags: number[], r: number[] }} frames, and each tile's correlation with the rest at its lag */ export function consensusLags(feats, { origin, pre = 10, span = 160, search = 60, iterations = 4 } = {}) { const N = feats.length; let lags = Array(N).fill(0); let r = Array(N).fill(0); if (N < 3) return { lags, r }; const width = feats[0][0]?.length ?? 0; const start = origin - pre; const template = (skip) => { const T = Array.from({ length: span }, () => new Float64Array(width)); let n = 0; feats.forEach((F, j) => { if (j === skip) return; n += 1; for (let f = 0; f < span; f += 1) { const row = F[start + lags[j] + f]; if (row) for (let b = 0; b < width; b += 1) T[f][b] += row[b]; } }); for (const row of T) for (let b = 0; b < width; b += 1) row[b] /= Math.max(1, n); return T; }; for (let it = 0; it < iterations; it += 1) { const next = []; const rs = []; for (let i = 0; i < N; i += 1) { const T = template(i); let best = { lag: lags[i], r: -Infinity }; for (let L = -search; L <= search; L += 1) { if (start + L < 0 || start + L + span > feats[i].length) continue; const c = blockCorr(T, 0, feats[i], start + L, span); if (c > best.r) best = { lag: L, r: c }; } next.push(best.lag); rs.push(best.r); } const sorted = [...next].sort((a, b) => a - b); const med = sorted[Math.floor(N / 2)]; lags = next.map((l) => l - med); r = rs; } return { lags, r }; } /** * Where the aligned tiles' phrase starts, in seconds from `origin`: the * sharpest rise of their MEAN loudness (all bands, all tiles at their * consensus lags) within ±`window` -- the mean of many takes of one phrase is * a cleaner onset than any one of them. */ export function templateOnset(feats, lags, { origin, window = 0.3, hop = 0.005, before = 12, after = 10 } = {}) { const N = feats.length; const reach = Math.round(window / hop); const loud = (f) => { let acc = 0; let n = 0; feats.forEach((F, i) => { const row = F[f + lags[i]]; if (row) { for (const v of row) acc += v; n += 1; } }); return n ? acc / n : 0; }; const env = new Map(); const at = (f) => (env.has(f) ? env.get(f) : env.set(f, loud(f)).get(f)); let best = null; for (let f = origin - reach; f <= origin + reach; f += 1) { let a = 0; let b = 0; for (let k = 1; k <= before; k += 1) a += at(f - k); for (let k = 0; k < after; k += 1) b += at(f + k); const rise = b / after - a / before; if (!best || rise > best.rise) best = { f, rise }; } void N; // `origin` is the frame CENTRED on the estimate; the rise peaks two hops // before the frame centred on the onset (measured on synthetic takes, to // the 5 ms hop). return best ? { shift: (best.f - origin) * hop + 2 * hop, rise: best.rise } : null; } /** * The wall's sound, made exactly the wall's length, in SAMPLES. amix's output * clock can run ahead of its samples when its inputs start late (an asplit * feeding a long adelay): a pad or trim timed on that clock came out a frame * short under load (1 of 3 parallel builds, 2026-10-18), and a fade timed on it * silenced the grouped wall. So: one rate, re-stamped by sample count, then * padded and trimmed to the sample. */ export function wallAudioLength(plan, render) { const rate = Number(render.audioRate) > 0 ? Number(render.audioRate) : 48000; const samples = Math.round(plan.seconds * rate); return `aresample=${rate},asetpts=N/SR/TB,apad=whole_len=${samples},atrim=end_sample=${samples},asetpts=N/SR/TB,`; } /** The wall's place in the cut, as an entry: what the chapters call it. */ export const WALL_ENTRY = Object.freeze({ type: "montage-wall", id: "montage-wall", title: "All together" });