Archilyzer · Source

archilyzer

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

commit 56dc37196f40d4f3d091899fc78219fffb855635
parent bdf8e7f84f05e137c75c082d754ce1443a6776e3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 01:20:58 -0400

umtool: report-to-video montage wall in groups, synced to the beat; tail and exclusive walls; the ramp into the wall; build-to-wall

render.montage.wall gains groups ("single" today | "double": 1, 1, 2, 4, 8 … arriving on beats whose gaps fall
evenly to half the first), sync (default with groups: each tile cut WALL_LEAD before its phrase's onset so the
onset lands on its group's beat and on the final beat -- whisper's word offsets when the corpus keeps them,
else the cue estimate refined against the sound: the sharpest loudness rise within ±0.4 s, refineOnset), clips
("spread" today | "tail": the latest `tiles` clips in date order) and exclusive (the wall's clips are tiles
only: out of the run, its counter, its ramp and its chapters). ramp.into "wall" ends the ramp on the wall's
first gap. A grouped wall composes tile by tile on the ground, each group sliding in from the right over four
frames, a group heard in unison and silent before the next beat, then every tile together. The new style
build-to-wall (whip, ramp 3.5 s into the wall, drift, tally, an exclusive tail wall of 25 in groups
1,1,2,4,8,9, synced, years); the other six styles take null for the new nested keys so that one style over
another still leaves exactly the second (their effect is unchanged). verify-build counts an exclusive wall's
clips out. Defaults render byte for byte as before (main vs branch md5 for a wall and a ramp manifest; in-suite
for the new keys spelled at their defaults).

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

Diffstat:
Mumtool/report-to-video/build-video.mjs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/report-to-video/montage-styles.mjs | 15+++++++++++++--
Mumtool/report-to-video/montage.mjs | 336++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/montage.test.mjs | 273++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/verify-build.mjs | 6++++--
5 files changed, 741 insertions(+), 52 deletions(-)

diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -179,8 +179,8 @@ import { markPng, renderThumbnail, THUMB_MAX_BYTES } from "./brand-cards.mjs"; // Every hook below runs only when render.montage is set. import { clipPhrase, cutStyleParts, locatePhrase, montageFont, montageOn, montageOverlayFilters, montagePieces, - montagePiecesGraph, montageWindow, planMontage, resolveMontage, validateMontage, wallComposeArgs, WALL_ENTRY, - wallPlan, wallTileArgs, wallTileClips, whisperWords, + montagePiecesGraph, montageSplit, montageWindow, parseClipDate, planMontage, refineOnset, resolveMontage, + validateMontage, wallComposeArgs, WALL_ENTRY, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords, } from "./montage.mjs"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; @@ -1366,7 +1366,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, await writeCutRecord(seg, mont ? { ...cutRecord, montage: mg.record } : cutRecord); if (mont) { dirs.montage.cuts.set(entry.id, { - raw, cutA, cutB, phrase: mont.phrase, year: mont.ctx.year, hasVideo: media.hasVideo, + raw, cutA, cutB, phrase: mont.phrase, via: mont.via, year: mont.ctx.year, hasVideo: media.hasVideo, }); } return seg; @@ -1422,22 +1422,10 @@ async function montageCues(entry, provenance) { async function montageCut({ entry, M, render, provenance, fetchStart, sil, wantA, wantB, win }) { const s = M.settings; const ctx = M.ctx.get(entry.id) ?? { k: 0, n: 1, number: 1, of: 1, cap: null, stutter: false, date: null, year: null, yearChange: false, platform: null, first: false, last: false }; - const text = clipPhrase(entry); const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd); - let found = null; - let via = null; - if (text && (s.tighten === "phrase" || s.punch?.mode === "snap" || ctx.stutter)) { - const near = hasCut ? (entry.cutStart + entry.cutEnd) / 2 : entry.cite ?? (entry.start + entry.end) / 2; - const span = { from: entry.start, to: entry.end, near }; - const words = await montageWords(entry, provenance, M); - found = words ? locatePhrase(text, words, span) : null; - if (found) via = "words"; - else { - found = locatePhrase(text, await montageCues(entry, provenance), span); - if (found) via = "cues"; - } - if (!found) EMIT("note", { message: `${entry.id}: montage: "${text}" is not in its cues — today's cut is kept` }); - } + const { found, via } = s.tighten === "phrase" || s.punch?.mode === "snap" || ctx.stutter + ? await findMontagePhrase(entry, M, provenance) + : { found: null, via: null }; const at = found ?? (hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end }); const phrase = { start: at.start - fetchStart, end: at.end - fetchStart }; const w = montageWindow({ @@ -1449,6 +1437,62 @@ async function montageCut({ entry, M, render, provenance, fetchStart, sil, wantA } /** + * Where a clip says its phrase, in SOURCE seconds: whisper's words first, + * then its cues. `{found: null}` (and a note) when it is not there. + */ +async function findMontagePhrase(entry, M, provenance) { + const text = clipPhrase(entry); + if (!text) return { found: null, via: null }; + const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd); + const near = hasCut ? (entry.cutStart + entry.cutEnd) / 2 : entry.cite ?? (entry.start + entry.end) / 2; + const span = { from: entry.start, to: entry.end, near }; + const words = await montageWords(entry, provenance, M); + let found = words ? locatePhrase(text, words, span) : null; + if (found) return { found, via: "words" }; + found = locatePhrase(text, await montageCues(entry, provenance), span); + if (found) return { found, via: "cues" }; + EMIT("note", { message: `${entry.id}: montage: "${text}" is not in its cues — today's cut is kept` }); + return { found: null, via: null }; +} + +/** + * A wall tile's source for a clip that has no segment (an exclusive wall's): + * its window from the cache or the corpus (fetched as any clip is, unless the + * build may not), and its phrase. The same shape montageCuts records. + */ +async function montageWallSource({ entry, M, render, provenance, local, opts }) { + const meta = await clipMeta(entry, provenance); + const { path: raw, fetchStart } = await fetchClip(entry, meta, render, local, opts); + const { found, via } = await findMontagePhrase(entry, M, provenance); + const hasCut = Number.isFinite(entry.cutStart) && Number.isFinite(entry.cutEnd); + const at = found ?? (hasCut ? { start: entry.cutStart, end: entry.cutEnd } : { start: entry.start, end: entry.end }); + const media = await probeMedia(raw); + return { + raw, cutA: entry.start - fetchStart, cutB: entry.end - fetchStart, + phrase: { start: at.start - fetchStart, end: at.end - fetchStart }, via, + year: M.ctx.get(entry.id)?.year ?? parseClipDate(entry.montage?.date)?.y ?? null, hasVideo: media.hasVideo, + }; +} + +/** + * A synced tile's onset, refined against its sound (montage.mjs + * refineOnset): the speech band (high-passed at 200 Hz, 16 kHz mono) of + * ±0.6 s around the estimate, read once with ffmpeg. The estimate when no + * clear rise is found. + */ +async function refinedOnset(raw, est) { + const from = Math.max(0, est - 0.6); + const rate = 16000; + const { stdout } = await execFileP(FFMPEG, [ + "-nostdin", "-v", "error", "-ss", from.toFixed(3), "-t", "1.2", "-i", raw, + "-vn", "-ac", "1", "-ar", String(rate), "-af", "highpass=f=200", "-f", "s16le", "-", + ], { encoding: "buffer", maxBuffer: 1 << 24 }); + const samples = new Int16Array(stdout.buffer, stdout.byteOffset, Math.floor(stdout.length / 2)); + const r = refineOnset(samples, rate, est - from, { window: 0.4 }); + return r ? { at: from + r.at, rise: r.rise } : null; +} + +/** * One montage segment's graph: the pieces (montagePiecesGraph) from the raw * cut to `mg.v` / `mg.a`, and `post(in, out)` -- the cut style and the * counter over the finished frame. `record` goes in the cut record. @@ -1493,21 +1537,60 @@ function montageSegmentGraph({ mont, render, box, hasVideo, cutA, cutB }) { * just built (montageCuts), each a small file in segments/montage-wall/, then * composed into one segment. Returns its path. */ -async function buildMontageWall({ M, entries, render, outDir }) { +async function buildMontageWall({ M, entries, render, outDir, timeline, provenance, local, opts }) { const s = M.settings; - const ids = entries.filter((e) => e.type === "clip" && M.cuts.has(e.id) && M.cuts.get(e.id).hasVideo).map((e) => e.id); - if (!ids.length) throw new Error("render.montage.wall: no clip with a picture was built, so there is nothing to tile"); - const chosen = wallTileClips(ids, s.wall.tiles); + const w = s.wall; + // Today's wall (spread, not exclusive): tiles from the clips just built. + // A tail or exclusive wall: the split's tiles, cut from their sources here + // when they have no segment. + let chosen; + if (w.clips === "spread" && !w.exclusive) { + const ids = entries.filter((e) => e.type === "clip" && M.cuts.has(e.id) && M.cuts.get(e.id).hasVideo).map((e) => e.id); + if (!ids.length) throw new Error("render.montage.wall: no clip with a picture was built, so there is nothing to tile"); + chosen = wallTileClips(ids, w.tiles); + } else { + chosen = M.split.wall; + if (!chosen.length) throw new Error("render.montage.wall: the cut has no clips to tile"); + for (const id of new Set(chosen)) { + if (M.cuts.has(id)) continue; + const entry = timeline.find((e) => e?.type === "clip" && e.id === id); + EMIT("clip", { id, i: 0, n: chosen.length, video: clipLabel(entry), wall: true }); + const src = await montageWallSource({ entry, M, render, provenance, local, opts }); + if (!src.hasVideo) throw new Error(`render.montage.wall: ${id} has no picture to tile`); + M.cuts.set(id, src); + } + } + // Synced: each tile's onset refined against its sound (unless whisper's + // words placed it), and the tile cut to start WALL_LEAD before it. + const sources = new Map(); + for (const id of new Set(chosen)) { + const c = M.cuts.get(id); + if (!w.sync) { + let from = Math.max(c.cutA, c.phrase.start - 0.12); + let to = Math.min(c.cutB, c.phrase.end + 0.25); + if (to - from < 0.4) [from, to] = [c.cutA, c.cutB]; + sources.set(id, { from, to, lead: null, sync: null }); + continue; + } + const est = c.phrase.start; + const r = c.via === "words" ? null : await refinedOnset(c.raw, est).catch(() => null); + const onset = r ? r.at : est; + const from = Math.max(c.cutA, onset - WALL_LEAD); + const to = Math.min(c.cutB, Math.max(onset + 0.4, c.phrase.end + (onset - est) + WALL_TAIL)); + sources.set(id, { + from, to, lead: onset - from, + sync: { estimate: Number(est.toFixed(3)), onset: Number(onset.toFixed(3)), via: c.via ?? null, refined: !!r, rise: r ? Number(r.rise.toFixed(1)) : null }, + }); + } const tiles = chosen.map((id) => { const c = M.cuts.get(id); - let from = Math.max(c.cutA, c.phrase.start - 0.12); - let to = Math.min(c.cutB, c.phrase.end + 0.25); - if (to - from < 0.4) [from, to] = [c.cutA, c.cutB]; - return { id, raw: c.raw, from, to, year: s.wall.year ? c.year : null }; + const 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 plan = wallPlan({ - tiles: tiles.length, build: s.wall.build, durations: tiles.map((t) => t.to - t.from), + 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 } : {}), }); const dir = path.join(outDir, "segments", "montage-wall"); await rm(dir, { recursive: true, force: true }); @@ -1529,11 +1612,16 @@ async function buildMontageWall({ M, entries, render, outDir }) { const seg = path.join(outDir, "segments", `${WALL_ENTRY.id}.mp4`); await execFileP(FFMPEG, wallComposeArgs({ tiles: files, plan, render, settings: s, - first: s.wall.at === "start", last: s.wall.at === "end", encode: encodeArgs(render), outPath: seg, + first: w.at === "start", last: w.at === "end", encode: encodeArgs(render), outPath: seg, }), { maxBuffer: 1 << 26 }); - await writeCutRecord(seg, { - version: 1, id: WALL_ENTRY.id, montageWall: { tiles: chosen, frames: plan.frames, seconds: plan.seconds, appear: plan.appear, beat: plan.beat }, - }); + const record = { tiles: chosen, frames: plan.frames, seconds: plan.seconds, appear: plan.appear, beat: plan.beat }; + if (plan.grouped) { + Object.assign(record, { groups: plan.groups, groupBeats: plan.groupBeats, restart: plan.restart, leads: plan.leads }); + } + if (w.sync) { + record.sync = tiles.map((t) => ({ id: t.id, raw: t.raw, from: Number(t.from.toFixed(3)), ...sources.get(t.id).sync })); + } + await writeCutRecord(seg, { version: 1, id: WALL_ENTRY.id, montageWall: record }); return seg; } @@ -4657,10 +4745,17 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const meta = await clipMeta(e, provenance).catch(() => null); if (meta?.uploadDate) dates.set(e.id, meta.uploadDate); } + const split = montageSplit(manifest.timeline, settings); dirs.montage = { settings, ctx: planMontage(manifest.timeline, settings, (e) => dates.get(e.id) ?? null), - cuts: new Map(), words: new Map(), channelsDir, + cuts: new Map(), words: new Map(), channelsDir, split, }; + // An exclusive wall's clips are tiles only: no segment, no chapter. + if (split.wallOnly.size) { + for (let i = entries.length - 1; i >= 0; i -= 1) { + if (entries[i].type === "clip" && split.wallOnly.has(entries[i].id) && !only) entries.splice(i, 1); + } + } } // One entry's segment, by its kind: the build's loop below, `--only`, and a @@ -4938,7 +5033,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly if (dirs.montage?.settings.wall && !failures.length) { const at = dirs.montage.settings.wall.at; EMIT("card", { id: WALL_ENTRY.id, i: at === "start" ? 0 : entries.length, n: entries.length + 1 }); - const seg = await buildMontageWall({ M: dirs.montage, entries, render, outDir }); + const seg = await buildMontageWall({ + M: dirs.montage, entries, render, outDir, timeline: manifest.timeline, provenance, local: dirs.local, opts, + }); EMIT("segment", { id: WALL_ENTRY.id, path: seg }); if (at === "start") { segments.unshift(seg); diff --git a/umtool/report-to-video/montage-styles.mjs b/umtool/report-to-video/montage-styles.mjs @@ -63,7 +63,7 @@ export const MONTAGE_STYLES = Object.freeze({ "Accelerate", "Clips get shorter toward the end, a slow zoom on each, tally marks adding up.", { - ramp: { from: 4, to: 1.4 }, + ramp: { from: 4, to: 1.4, into: null }, punch: { mode: "drift", scale: 1.08, anchor: "upper" }, counter: { style: "tally", position: "top-left", of: false, showDate: true, showSource: false }, }, @@ -80,13 +80,24 @@ 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 } }, + { counter: chip, wall: { at: "end", tiles: 16, build: 8, year: true, groups: null, sync: null, clips: null, exclusive: null } }, ), "whip-years": style( "Whip and years", "Fast sliding cuts, the year large in a corner when it changes, a small running count.", { cut: "whip", yearStamp: true, counter: { ...chip, showDate: true, showSource: false } }, ), + "build-to-wall": style( + "Build to the wall", + "Clips slide in and speed up, tally marks adding up, straight into a wall of the latest twenty-five: bigger and bigger groups each say it together, then all at once.", + { + cut: "whip", + 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 }, + }, + ), }); /** The style names, in their listed order. */ diff --git a/umtool/report-to-video/montage.mjs b/umtool/report-to-video/montage.mjs @@ -47,14 +47,19 @@ export const WALL_TILES = Object.freeze([9, 16, 25]); const COUNTER_KEYS = ["style", "position", "of", "showDate", "showSource"]; const PUNCH_KEYS = ["mode", "scale", "anchor"]; const STUTTER_KEYS = ["every", "clips", "times", "length", "step"]; -const RAMP_KEYS = ["from", "to"]; -const WALL_KEYS = ["at", "tiles", "build", "year"]; +const RAMP_KEYS = ["from", "to", "into"]; +const WALL_KEYS = ["at", "tiles", "build", "year", "groups", "sync", "clips", "exclusive"]; +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 }, + 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). */ @@ -114,8 +119,16 @@ export function resolveMontage(render) { counter, punch, stutter, - ramp: isObj(m.ramp) ? { from: m.ramp.from, to: m.ramp.to } : null, - wall: wall ? { ...wall, year: wall.year === true } : null, + 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, + 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, }; } @@ -206,7 +219,13 @@ export function validateMontage(manifest) { else { errors.push(...unknownKeys(m.ramp, RAMP_KEYS, `${W}.ramp`)); errors.push(...inRange(m.ramp.from, 0.5, 60, `${W}.ramp.from`, " seconds")); - errors.push(...inRange(m.ramp.to, 0.5, 60, `${W}.ramp.to`, " seconds")); + if (m.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"`); } } @@ -218,6 +237,19 @@ export function validateMontage(manifest) { 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.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`)); @@ -425,27 +457,39 @@ export const stutters = (stutter, k, id) => * @param {(entry) => string|null} [dateOf] a clip's date when its own fields carry none */ export function planMontage(timeline, settings, dateOf = () => null) { - const clips = timeline.filter((e) => e?.type === "clip"); + // 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)); + out.set(e.id, { wallOnly: true, 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 = timeline.indexOf(e); + 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, settings.ramp), + 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 === timeline.length - 1 && !(settings.wall && settings.wall.at === "end"), + last: i === shown.length - 1 && !(settings.wall && settings.wall.at === "end"), }); if (year != null) prevYear = year; }); @@ -828,14 +872,80 @@ export const montageFont = (render) => render.fontBold ?? render.fontRegular ?? * cut's clips, first to last (the first tile the earliest); fewer clips than * tiles go round again. */ -export function wallTileClips(ids, tiles) { +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 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 w = settings?.wall; + const wall = w ? 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 @@ -845,7 +955,7 @@ export function wallTileClips(ids, tiles) { * @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 }) { +export function wallPlan({ tiles, build, durations, fps, width, height, groups = "single", leads = 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; @@ -862,6 +972,9 @@ export function wallPlan({ tiles, build, durations, fps, width, height }) { const layout = Array.from({ length: tiles }, (_, i) => ({ x: ox + (i % cols) * (w + gap), y: oy + Math.floor(i / 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)))); @@ -878,6 +991,41 @@ export function wallPlan({ tiles, build, durations, fps, width, height }) { } /** + * 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. @@ -909,6 +1057,7 @@ export function wallTileArgs({ raw, from, to, tileW, tileH, fps, year = null, fo * 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; @@ -966,5 +1115,168 @@ export function wallComposeArgs({ tiles, plan, render, settings, first, last, en ]; } +/** 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,tpad=stop_mode=clone:stop_duration=${total},trim=end_frame=${firstF}[wv${i}c]`, + `[wv${i}b]trim=end=${exprNum(again)},setpts=PTS-STARTPTS,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,` + + `apad=whole_dur=${total},atrim=end=${total},` + + `afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(plan.seconds - DECLICK)}:d=${DECLICK}[a]`, + ); + return [ + "-nostdin", "-v", "error", "-y", + ...tiles.flatMap((t) => ["-i", t.file]), + "-filter_complex", parts.join(";"), + "-map", "[v]", "-map", "[a]", + "-frames:v", String(plan.frames), + ...encode, + outPath, + ]; +} + +// ---- 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<number>} 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 wall's place in the cut, as an entry: what the chapters call it. */ export const WALL_ENTRY = Object.freeze({ type: "montage-wall", id: "montage-wall", title: "All together" }); diff --git a/umtool/report-to-video/montage.test.mjs b/umtool/report-to-video/montage.test.mjs @@ -18,7 +18,8 @@ import { counterText, CUT_FRAMES, cutStyleParts, DECLICK, formatClipDate, locatePhrase, montageOn, montageOverlayFilters, montagePieces, montagePiecesGraph, montageWindow, normalisePhrase, parseClipDate, piecesFrames, planMontage, platformLabel, rampCap, rampCaps, resolveMontage, safeText, stutters, tallyMarks, timedText, validateMontage, - wallComposeArgs, wallPlan, wallTileClips, whisperWords, + wallComposeArgs, wallPlan, wallTileClips, whisperWords, wallGroups, wallBeats, wallFirstGap, montageSplit, + refineOnset, speechEnvelope, envelopeLag, WALL_SLIDE_FRAMES, } from "./montage.mjs"; import { applyMontageStyle, MONTAGE_STYLE_NAMES, mergePatch } from "./montage-styles.mjs"; import { buildVideo, snap } from "./build-video.mjs"; @@ -40,8 +41,10 @@ test("validateMontage: absent or null is off and says nothing; the named styles assert.equal(montageOn({}), false); assert.equal(montageOn({ montage: null }), false); assert.equal(montageOn({ montage: {} }), true); + // Thirty clips: build-to-wall's exclusive wall takes twenty-five of them. + const thirty = Array.from({ length: 30 }, (_, i) => clip(`s${i + 1}`)); for (const name of MONTAGE_STYLE_NAMES) { - assert.deepEqual(validateMontage(applyMontageStyle(manifest(undefined), name)), [], name); + assert.deepEqual(validateMontage(applyMontageStyle(manifest(undefined, thirty), name)), [], name); } }); @@ -104,7 +107,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 }); + assert.deepEqual(r.wall, { at: "end", tiles: 9, build: 6, year: false, groups: "single", sync: false, clips: "spread", exclusive: 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" }); assert.equal(r.ramp, null); assert.equal(r.yearStamp, false); assert.equal(resolveMontage({ montage: { punch: { mode: "snap" } } }).punch.scale, 1.15); @@ -764,3 +770,264 @@ test("render: dip -- two frames to black before the cut, two up from it", { skip await rm(root, { recursive: true, force: true }); } }); + +// ---- release 33 wall-sync: groups, sync, tail, exclusive, the ramp into the wall ------------- + +test("validateMontage: the wall's groups, sync, clips, exclusive; the ramp into the wall", () => { + const errs = (m, tl) => validateMontage(manifest(m, tl)); + assert.match(errs({ wall: { groups: "triple" } })[0], /wall\.groups must be "single" or "double", not "triple"/); + assert.match(errs({ wall: { clips: "head" } })[0], /wall\.clips must be "spread" or "tail", not "head"/); + assert.match(errs({ wall: { sync: 1 } })[0], /wall\.sync must be true or false/); + assert.match(errs({ wall: { exclusive: "yes" } })[0], /wall\.exclusive must be true or false/); + assert.match(errs({ tighten: "phrase", ramp: { from: 3, into: "end" }, wall: {} })[0], /ramp\.into must be "wall", not "end"/); + assert.match(errs({ tighten: "phrase", ramp: { from: 3, into: "wall" } })[0], /ramp\.into "wall" needs render\.montage\.wall/); + assert.deepEqual(errs({ tighten: "phrase", ramp: { from: 3, into: "wall" }, wall: {} }), [], "no `to` needed"); + assert.match(errs({ tighten: "phrase", ramp: { from: 3 } })[0], /ramp\.to must be a number/, "without into, `to` is needed"); + const eleven = Array.from({ length: 11 }, (_, i) => clip(`s${i + 1}`)); + assert.match( + errs({ wall: { tiles: 9, clips: "tail", exclusive: true } }, eleven.slice(0, 10))[0], + /wall\.exclusive takes the wall's 9 clip\(s\) out of the cut, leaving 1 — it needs at least 2 clips outside the wall/, + ); + assert.deepEqual(errs({ wall: { tiles: 9, clips: "tail", exclusive: true } }, eleven), []); + assert.match(errs({ wall: { tiles: 9, exclusive: true } }, eleven.slice(0, 4))[0], /leaving 0/, "fewer clips than tiles: all of them are tiles"); +}); + +test("wallGroups: 1, 1, 2, 4, 8 … and the leftover", () => { + assert.deepEqual(wallGroups(16, "double"), [1, 1, 2, 4, 8]); + assert.deepEqual(wallGroups(9, "double"), [1, 1, 2, 5]); + assert.deepEqual(wallGroups(25, "double"), [1, 1, 2, 4, 8, 9]); + assert.deepEqual(wallGroups(4, "single"), [1, 1, 1, 1]); + for (const n of [9, 16, 25]) assert.equal(wallGroups(n, "double").reduce((a, b) => a + b), n); +}); + +test("wallBeats: single is today's arrivals; double's gaps fall evenly to half the first and sum to the build", () => { + const single = wallBeats({ tiles: 16, build: 8 }); + single.beats.forEach((b, i) => assert.equal(b, 8 * (1 - (1 - i / 16) ** 2))); + const d = wallBeats({ tiles: 25, build: 7.5, groups: "double" }); + assert.deepEqual(d.sizes, [1, 1, 2, 4, 8, 9]); + assert.equal(d.beats[0], 0); + assert.ok(Math.abs(d.gaps.reduce((a, b) => a + b) - 7.5) < 1e-9); + assert.ok(Math.abs(d.gaps[0] - 7.5 / 4.5) < 1e-9); + assert.ok(Math.abs(d.gaps.at(-1) - d.gaps[0] / 2) < 1e-9); + for (let i = 1; i < d.gaps.length; i += 1) assert.ok(d.gaps[i] < d.gaps[i - 1]); + assert.equal(wallFirstGap({ tiles: 25, build: 7.5, groups: "double" }), d.gaps[0]); + assert.equal(wallFirstGap({ tiles: 16, build: 8, groups: "single" }), single.gaps[0]); + assert.deepEqual(wallBeats({ tiles: 1, build: 3, groups: "double" }).gaps, [3]); +}); + +test("montageSplit: spread or tail; an exclusive wall takes its clips out of the run, in order", () => { + const tl = [{ id: "t0", type: "card" }, ...Array.from({ length: 12 }, (_, i) => clip(`s${i + 1}`))]; + const r = (wall) => montageSplit(tl, resolveMontage({ montage: { wall } })); + const spread = r({ tiles: 9 }); + assert.equal(spread.wall.length, 9); + assert.equal(spread.wallOnly.size, 0); + assert.equal(spread.linear.length, 12); + const tail = r({ tiles: 9, clips: "tail" }); + assert.deepEqual(tail.wall, ["s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12"], "the latest nine, in date order"); + assert.equal(tail.wallOnly.size, 0); + const excl = r({ tiles: 9, clips: "tail", exclusive: true }); + assert.deepEqual(excl.linear, ["s1", "s2", "s3"]); + assert.deepEqual([...excl.wallOnly], tail.wall); + assert.deepEqual(montageSplit(tl, resolveMontage({ montage: {} })).wall, []); +}); + +test("planMontage under an exclusive tail wall: the run is numbered, ramped and edged on its own", () => { + const tl = Array.from({ length: 12 }, (_, i) => clip(`s${i + 1}`, { montage: { date: `20${10 + i}0101` } })); + const settings = resolveMontage({ + montage: { tighten: "phrase", ramp: { from: 3.5, into: "wall" }, wall: { tiles: 9, build: 4, groups: "double", clips: "tail", exclusive: true } }, + }); + const plan = planMontage(tl, settings); + const run = ["s1", "s2", "s3"].map((id) => plan.get(id)); + assert.deepEqual(run.map((p) => p.k), [0, 1, 2]); + assert.deepEqual(run.map((p) => p.n), [3, 3, 3]); + assert.deepEqual(run.map((p) => p.number), [1, 2, 3], "the counter runs to N − tiles"); + assert.deepEqual(run.map((p) => p.of), [3, 3, 3]); + assert.equal(run[0].cap, 3.5); + assert.ok(Math.abs(run[2].cap - wallFirstGap(settings.wall)) < 1e-9, "the last cut meets the wall's first gap"); + assert.equal(run[0].first, true); + assert.equal(run[2].last, false, "the wall follows"); + for (const id of ["s4", "s12"]) { + assert.equal(plan.get(id).wallOnly, true); + assert.equal(plan.get(id).k, undefined); + } + assert.equal(plan.get("s12").year, 2021); + // The clips' own montage.n still wins (a take of part of the cut). + const own = planMontage(tl.map((e, i) => ({ ...e, montage: { ...e.montage, n: i + 1 } })), settings); + assert.deepEqual(["s1", "s2", "s3"].map((id) => own.get(id).number), [1, 2, 3]); + // Not exclusive: every clip runs, and the ramp ends at `to`. + const all = planMontage(tl, resolveMontage({ montage: { tighten: "phrase", ramp: { from: 3, to: 1 }, wall: { tiles: 9, clips: "tail" } } })); + assert.equal(all.size, 12); + assert.equal(all.get("s12").cap, 1); +}); + +test("wallPlan grouped and synced: a group shows its lead before its beat, so every onset lands on it; the crowd on one frame", () => { + const leads = Array.from({ length: 9 }, (_, i) => (i === 3 ? 0.05 : 0.12)); + const p = wallPlan({ tiles: 9, build: 4, durations: Array(9).fill(1.2), fps: 30, width: 320, height: 180, groups: "double", leads }); + assert.equal(p.grouped, true); + assert.deepEqual(p.groups, [1, 1, 2, 5]); + assert.deepEqual(p.groupOf, [0, 1, 2, 2, 3, 3, 3, 3, 3]); + assert.equal(Math.min(...p.appearFrames), 0, "the earliest show is the wall's first frame"); + p.appearFrames.forEach((f, i) => { + assert.ok(Number.isInteger(f)); + assert.equal(f + Math.round(leads[i] * 30), p.groupBeatFrames[p.groupOf[i]], `tile ${i}'s onset on its group's beat`); + assert.equal(p.restartFrames[i] + Math.round(leads[i] * 30), p.beatFrames, `tile ${i}'s onset on the final beat`); + }); + assert.equal(p.groupBeatFrames[1] - p.groupBeatFrames[0], Math.round(4 / 3 * 30)); + assert.equal(p.beatFrames - p.groupBeatFrames[0], 120); + assert.equal(p.seconds, p.frames / 30); + // Unsynced groups: tiles show on the beat itself. + const u = wallPlan({ tiles: 16, build: 6, durations: Array(16).fill(1), fps: 30, width: 1920, height: 1080, groups: "double" }); + assert.deepEqual(u.appearFrames.slice(0, 4), [0, u.groupBeatFrames[1], u.groupBeatFrames[2], u.groupBeatFrames[2]]); + assert.deepEqual(u.restartFrames, Array(16).fill(u.beatFrames)); + // Single, unsynced: today's plan, field for field. + const today = wallPlan({ tiles: 9, build: 3, durations: Array(9).fill(1), fps: 30, width: 320, height: 180 }); + assert.equal(today.grouped, undefined); + assert.deepEqual(wallPlan({ tiles: 9, build: 3, durations: Array(9).fill(1), fps: 30, width: 320, height: 180, groups: "single", leads: null }), today); +}); + +test("wallComposeArgs grouped: tiles slide in on their beat, a group in unison, silent before the next beat, the crowd at the end", () => { + const plan = wallPlan({ tiles: 9, build: 4, durations: Array(9).fill(1.2), fps: 30, width: 320, height: 180, groups: "double", leads: Array(9).fill(0.12) }); + const tiles = Array.from({ length: 9 }, (_, i) => ({ file: `/t/${i}.mp4`, seconds: 2 })); + const settings = resolveMontage({ montage: { cut: "whip", wall: { tiles: 9, groups: "double" } } }); + const r4 = (v) => String(Number(v.toFixed(4))); + const args = wallComposeArgs({ tiles, plan, render: { width: 320, height: 180, fps: 30, palette: PALETTE }, settings, first: false, last: true, encode: [], outPath: "/o.mp4" }); + const graph = args[args.indexOf("-filter_complex") + 1]; + assert.match(graph, /^color=c=#15121c:s=320x180:r=30:d=[\d.]+,setsar=1\[wc0\]/); + assert.ok(graph.includes(`[wc4][wt4]overlay=x='${plan.layout[4].x}+50*pow(max(0,1-(t-${r4(plan.appear[4])})/0.1333),2)':y=${plan.layout[4].y}:enable='gte(t,${r4(plan.appear[4])})'`)); + assert.equal(WALL_SLIDE_FRAMES, 4); + // Group levels: alone 1, a pair 0.8839, five 0.559. + assert.match(graph, /\[wa0a\]atrim=end=[\d.]+,asetpts=PTS-STARTPTS,volume=1,afade=t=out/); + assert.match(graph, /\[wa2a\]atrim=end=[\d.]+,asetpts=PTS-STARTPTS,volume=0\.8839,/); + assert.match(graph, /\[wa8a\]atrim=end=[\d.]+,asetpts=PTS-STARTPTS,volume=0\.559,/); + // Tile 0 falls silent 40 ms before group 1's beat. + const once0 = Number(graph.match(/\[wa0a\]atrim=end=([\d.]+)/)[1]); + assert.ok(Math.abs(plan.appear[0] + once0 - (plan.groupBeats[1] - 0.04)) < 1e-3, `${once0}`); + assert.match(graph, new RegExp(`\\[wa8b\\]atrim=end=[\\d.]+,asetpts=PTS-STARTPTS,volume=0\\.5333,adelay=${Math.round(plan.restart[8] * 1000)}:all=1`)); + assert.match(graph, /\[wg\]split=2\[wph\]\[wpb\]|\[wg\]split=3/, "the whip in"); + assert.equal(args[args.indexOf("-frames:v") + 1], String(plan.frames)); +}); + +test("refineOnset: the sharpest rise near the estimate, to the frame; null without one", () => { + const rate = 8000; + const mk = (onset, len = 1.2) => Float64Array.from({ length: Math.round(len * rate) }, (_, i) => { + const t = i / rate; + const noise = 0.01 * Math.sin(i * 12.9898) * Math.sin(i * 78.233); + return noise + (t >= onset ? 0.5 * Math.sin(2 * Math.PI * 300 * t) : 0); + }); + const r = refineOnset(mk(0.73), rate, 0.6); + assert.ok(Math.abs(r.at - 0.73) <= 0.01, JSON.stringify(r)); + assert.ok(r.rise > 20); + assert.ok(Math.abs(refineOnset(mk(0.45), rate, 0.6).at - 0.45) <= 0.01, "earlier than the estimate"); + assert.equal(refineOnset(mk(5), rate, 0.6), null, "no rise at all"); + assert.equal(refineOnset(mk(1.1), rate, 0.6, { window: 0.3 }), null, "a rise outside the window"); + const env = speechEnvelope(mk(0.5), rate); + assert.equal(env.length, Math.floor((1.2 * rate - 160) / 40) + 1); + assert.ok(env[10] < -30 && env.at(-1) > -10); +}); + +test("envelopeLag: a shifted copy is found at its shift", () => { + const a = Array.from({ length: 200 }, (_, i) => Math.sin(i / 7) + (i > 80 && i < 120 ? 3 : 0)); + const b = [...Array(9).fill(a[0]), ...a.slice(0, 191)]; + assert.equal(envelopeLag(a, b, 20).lag, 9); + assert.equal(envelopeLag(b, a, 20).lag, -9); + assert.equal(envelopeLag(a, a, 5).lag, 0); +}); + +/** + * Twelve clips over six six-second files. Their sound: a quiet floor, a tone + * at 0.3–1.2 s, the PHRASE's tone from `onset` (2.25 s, a quarter second + * 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) { + 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) { + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=${FPS}:d=6`, + "-f", "lavfi", "-i", + `aevalsrc='0.01*sin(2*PI*97*t)*sin(2*PI*13*t)+0.5*sin(2*PI*${300 + 40 * i}*t)*(between(t,0.3,1.2)+between(t,2.25,3.2)+between(t,3.9,5.5))':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", path.join(root, "media", `c${i}.mp4`), + ]); + assert.equal(r.status, 0, String(r.stderr)); + await writeFile(path.join(root, "media", `c${i}.json`), JSON.stringify({ + cues: [ + { start: 0.2, end: 2.0, text: "well folks it is a" }, + { start: 2.0, end: 3.6, text: "slow news day again" }, + { start: 3.6, end: 5.8, text: "and here we go" }, + ], + })); + } + const timeline = Array.from({ length: 12 }, (_, k) => { + const j = (k % 6) + 1; + 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" }, + }; + }); + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ slug: "demo", title: "Demo", render: { ...RENDER, montage }, timeline })); + return { root, manifestPath }; +} + +test("render: today's wall with its new keys spelled out at their defaults is byte for byte today's", { skip: !have && "needs ffmpeg" }, async () => { + const base = { tighten: "phrase", ramp: { from: 2.6, to: 1.2 }, wall: { tiles: 9, build: 2 } }; + const a = await wallFixture(base); + const b = await wallFixture({ ...base, ramp: { ...base.ramp, into: null }, wall: { ...base.wall, groups: "single", sync: false, clips: "spread", exclusive: false } }); + try { + await buildVideo({ manifestPath: a.manifestPath, opts: { noNetwork: true } }); + await buildVideo({ manifestPath: b.manifestPath, opts: { noNetwork: true } }); + const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0]; + assert.equal(md5(path.join(a.root, "out", "demo.mp4")), md5(path.join(b.root, "out", "demo.mp4"))); + } finally { + await rm(a.root, { recursive: true, force: true }); + await rm(b.root, { recursive: true, force: true }); + } +}); + +test("render: build-to-wall over twelve clips -- three run, nine are tiles in groups, onsets synced to the beats", { skip: !have && "needs ffmpeg" }, async () => { + const montage = mergePatch(applyMontageStyle({ render: {} }, "build-to-wall").render.montage, { wall: { tiles: 9, build: 4 } }); + const { root, manifestPath } = await wallFixture(montage); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const seg = path.join(root, "out", "sourced", "segments"); + // The run: s1–s3 only; the tiles have no segment. + const p = await planned(root, ["s1", "s2", "s3"], true); + await assert.rejects(readFile(path.join(seg, "s4.cut.json"))); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1, `${framesOf(r.out)} vs ${p.total}`); + // The ramp meets the wall: the last cut is no longer than the first gap. + const gap = wallFirstGap(resolveMontage({ montage }).wall); + assert.ok(p.recs[2].end - p.recs[2].start <= gap + 0.002, `${p.recs[2].end - p.recs[2].start} vs ${gap}`); + const wall = JSON.parse(await readFile(path.join(seg, "montage-wall.cut.json"), "utf8")).montageWall; + assert.deepEqual(wall.tiles, ["s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12"]); + assert.deepEqual(wall.groups, [1, 1, 2, 5]); + // Every onset refined from the cues' 2.0 to the sound's 2.25, to within 10 ms. + for (const t of wall.sync) { + assert.equal(t.estimate, 2); + assert.equal(t.refined, true, t.id); + assert.ok(Math.abs(t.onset - 2.25) <= 0.01, `${t.id} ${t.onset}`); + } + // In each tile's own file the phrase starts its lead in (measured on the tile's sound). + for (const id of ["s4", "s8"]) { + const pcm = spawnSync("ffmpeg", ["-v", "error", "-i", path.join(seg, "montage-wall", `${id}.mp4`), "-ac", "1", "-ar", "16000", "-f", "s16le", "-"], { maxBuffer: 1 << 24 }).stdout; + const samples = new Int16Array(pcm.buffer, pcm.byteOffset, Math.floor(pcm.length / 2)); + const at = refineOnset(samples, 16000, 0.12, { window: 0.1 }).at; + assert.ok(Math.abs(at - 0.12) <= 0.03, `${id}: onset ${at} in its tile`); + } + // The last group's tiles are ground before their beat and footage on it. + const plan = wallPlan({ tiles: 9, build: 4, durations: Array(9).fill(1.2), fps: FPS, width: 320, height: 180, groups: "double", leads: Array(9).fill(0.12) }); + const start = p.total - p.wallFrames; + const l = plan.layout[8]; + const tile = `${l.w - 8}:${l.h - 24}:${l.x + 4}:${l.y + 4}`; + assert.ok(luma(r.out, start + plan.appearFrames[8] - 2, tile) < 40, "empty before its group"); + assert.ok(luma(r.out, start + plan.appearFrames[8] + 6, tile) > 100, "filled on its beat"); + // Chapters: three clips and the wall; verify-build agrees. + const ch = spawnSync("ffprobe", ["-v", "error", "-show_chapters", "-of", "json", r.out]); + assert.equal(JSON.parse(String(ch.stdout)).chapters.length, 4); + assert.deepEqual((await verifyBuild(manifestPath)).problems, []); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs @@ -22,7 +22,7 @@ import { postsRegions, selectVariant, variantPaths } from "./build-video.mjs"; import { deckGeometry, deckOn, frameCount, postsGeometry, resolveDeck, teaserSeconds, transitionOf } from "./deck.mjs"; import { statsClips } from "./stats.mjs"; import { frameKeyOf, framesOf } from "./prune-frames.mjs"; -import { resolveMontage } from "./montage.mjs"; +import { montageSplit, resolveMontage } from "./montage.mjs"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; @@ -56,7 +56,9 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n const chapters = (probe.chapters ?? []).length; // A montage's wall (`render.montage.wall`) is one more segment and chapter. const montage = resolveMontage(manifest.render ?? {}); - const entries = (manifest.timeline ?? []).length + (montage?.wall ? 1 : 0); + // An exclusive wall's clips are tiles only: no chapter of their own. + const wallOnly = montage?.wall ? montageSplit(manifest.timeline ?? [], montage).wallOnly.size : 0; + const entries = (manifest.timeline ?? []).length - wallOnly + (montage?.wall ? 1 : 0); if (!(duration > 0)) problems.push("duration is not greater than zero");