Archilyzer · Source

archilyzer

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

commit b3a9aa8f5019f62f8eddcd021f5666a317c8e778
parent bdf8e7f84f05e137c75c082d754ce1443a6776e3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 01:50:19 -0400

Merge r33/wall-sync: the wall in synced groups (1,1,2,4,8…, onsets matched on the sound), tail + exclusive walls that condense instead of repeat, ramp into the wall, slide-in groups, the build-to-wall style

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 18++++++++++++++++++
Aplans/release-33/wall-sync.md | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 5+++++
Mumtool/report-to-video/README.md | 15+++++++++++----
Mumtool/report-to-video/build-video.mjs | 205++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/montage-styles.mjs | 15+++++++++++++--
Mumtool/report-to-video/montage.mjs | 524+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/montage.test.mjs | 304++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/verify-build.mjs | 6++++--
10 files changed, 1123 insertions(+), 56 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A montage can build to its wall.** The closing wall can fill in groups of 1, 1, 2, 4, 8 … tiles, each group sliding in on a beat that comes a little sooner than the last; a group says the phrase together, with every tile's first syllable placed on the beat (from whisper's word timings, or from the captions checked against the sound), and at the end every tile says it on the same frame. The wall can take the latest clips instead of a spread (`wall.clips: "tail"`) and take them out of the run before it (`wall.exclusive`), so it condenses the repetition instead of repeating it; the count before it then stops where the wall begins. A ramp can end at the wall's first beat (`ramp.into: "wall"`), so the cuts speed straight into it. A seventh style, **Build to the wall**, puts these together: whip cuts getting shorter, tally marks, then the latest twenty-five in synced groups. Manifests without the new keys render exactly as before. - **Variant auditions: make takes on umtool's Takes page, and use one.** A report video's Takes page (the Cut tab's **Takes — N**, or **Make takes** when there are none yet) has **New take**: a montage style or none, a label, a group, the window (from S seconds for D seconds, or the full cut), an optional patch (JSON, checked before it is sent) and **quick render**. **Make all styles** makes one take per montage style with the same window. A take is rendered beside the project from the media the project already has — nothing is fetched — and appears when it is built, its changes listed in plain lines (`render.montage.cut: flash`, `render.crf: 34 (was 30)`); **Rebuild** makes it again against the cut as it is now. **Use this take** makes the take's manifest the project's and marks it **picked**, one per group; the Cut tab's **Undo last edit** takes it back. When the cut changed since the take was made, the card says so and waits for **Use anyway**. The same from a terminal: `umtool take`, `umtool takes make` (a recipe, or `--all-styles`), `umtool takes styles`, `umtool takes pick`. Nothing calls a model. Needs a restart of umtool. - **A montage from a phrase.** umtool's new project can be seeded from a phrase said across channels: `umtool new <slug> --seed phrase --phrase '<regex>' --channels a,b --prefer <channel>`, or the new-project form's seed "a phrase across channels" when no source is given. Every place the transcripts say it becomes a clip, in date order, found even where a caption line split the phrase in two; a stream that the preferred channel also holds (a Rumble copy, say) is cut from that copy; a stream and its clip upload are one clip; `--exclude` leaves out lines that match (a chat line read out), and a caption speaker change is noted for a voice check. The scan is kept beside the manifest as `phrase-scan.json`. - **Report videos can be montages.** A cut of one phrase said many times can now be edited as one: each clip cut tight to the phrase as said (found in its captions, or in whisper's word timings when the corpus keeps them) and snapped to the pauses around it; a white flash, a whip or a dip to black on every cut; a running count on the picture (a small "#12 · 2 May 2019 · YouTube", a big number that slams in, or tally marks), the year large in a corner when it changes; a punch-in as the phrase starts or a slow zoom; the end of the phrase repeated on chosen clips ("…news day-day-day"); clips that get shorter toward the end; and a closing wall of 9, 16 or 25 clips filling in and then all saying it together. All of it is set under `render.montage` in the video manifest, and none of it is a card. Six named styles to audition — Straight, Flash and count, Accelerate, Stutter, Wall finale, Whip and years — are listed by `node umtool/report-to-video/montage-styles.mjs list`, and `apply <style> <manifest> --out <file>` writes a manifest with one applied. A manifest without `render.montage` renders exactly as before. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10450,3 +10450,21 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri patch}>` (patch = RFC 7386 merge patch, `{render: {montage: {…every key…}}}`), `montageStyle(name)` (deep copy or null), `mergePatch`, `applyMontageStyle`; CLI `list [--json]` / `apply <style> <manifest> [--out]`. - A montage refuses `render.chrome` (the deck), `render.rail`, `chromeEngine: "hyperframes"` and any clip `muteFrom`. + +## Release 33 lane M3b: the montage wall in synced groups (verified 2026-10-18, branch `r33/wall-sync`) + +- `render.montage.wall` gains `groups` ("single" | "double"), `sync` (default `groups === "double"`), `clips` + ("spread" | "tail") and `exclusive`; `ramp.into: "wall"` (then `ramp.to` is optional). Defaults keep today's argv + (main vs branch md5 identical for a wall and a ramp manifest). `montageSplit(timeline, settings)` → + `{wall, wallOnly, linear}` is the one place that says which clips are tiles; `planMontage`, the build (it drops + `wallOnly` ids from its entries) and `verify-build` (chapters = timeline − wallOnly + 1) all read it. +- A grouped or synced wall plan (`groupedWallPlan`) has per-tile `appear`/`restart` and `groupBeats`; a synced + tile's onset is at `appear + lead` = its group's beat (and `restart + lead` = the final beat), to the frame. The wall's + `.cut.json` `montageWall.sync[]` keeps each tile's raw file, `from`, `estimate`, `onset`, `via`, `by` + ("consensus" | "rise" | "estimate"), `r` (raw-file seconds), and `syncAnchor` (the common shift). +- Onsets: whisper.cpp token offsets (no DTW) and cue character estimates both disagree with the sound by up to + ~±0.4 s on this corpus, and a single clip's loudness rise cannot tell "slow" from the word before it (measured on the + slow-news tail). The wall aligns tiles to each other (`consensusLags`, 8 speech bands) and then anchors the group + on the template's rise (`templateOnset`); on synthetic takes both are exact to the 5 ms hop. +- Of the slow-news project's 73 clips (2026-10-18): 40 have whisper.cpp token offsets in `transcript.json`, 16 a + parakeet `chunk_data`, 17 no `transcript.json` (YouTube captions only). diff --git a/plans/release-33/wall-sync.md b/plans/release-33/wall-sync.md @@ -0,0 +1,86 @@ +# Release 33 lane M3b — the montage wall in synced groups (as shipped) + +The operator auditioned the slow-news takes (2026-10-17/18): "I really like the wall finale … something with elements +from accelerate with a wall finale … really sync up those wall groups and speeding up the pacing toward the end — the +slide transition was cool too". Addendum: "if we do the unison wall finale it shouldn't have had those same clips +appear earlier, use it as a way to condense the repetition." + +## What + +1. **`wall.groups: "single" | "double"`** — "double": groups of 1, 1, 2, 4, 8 … (`wallGroups`; a leftover smaller than + the group before joins it: 9 → 1,1,2,5; 16 → 1,1,2,4,8; 25 → 1,1,2,4,8,9). Each group arrives together on a beat. The + gaps between beats fall evenly from the first to half of it across `build` (`wallBeats`). The tiles slide in from the + right over 4 frames. A group is heard in unison at min(1, 1.25/√size) and falls silent with a 40 ms fade just before + the next group's beat (ruled: silent, not ducked, so each group's unison reads alone). Earlier tiles freeze. Then + every tile together, the crowd at 1.6/√tiles, limited. +2. **`wall.sync`** (default on with "double") — each tile is cut 0.12 s before its phrase onset and runs to 0.25 s past + the phrase. It shows 0.12 s before its beat, so the onset lands on its group's beat and on the final beat, to the + frame (`groupedWallPlan`). + - **Onsets.** The estimate is whisper's token offset (the corpus's `transcript.json`) or the cue character estimate. + Neither is good to better than a few hundred ms here, and one clip's loudness rise picks the wrong syllable in + connected speech. So with 3+ tiles they are aligned to each other: `consensusLags`, an 8-band speech spectrum, + ±0.4 s, median shift zero. The group is then anchored on its mean loudness's rise (`templateOnset`, ±0.3 s). + - Fewer tiles keep `refineOnset`. +3. **`wall.clips: "spread" | "tail"`, `wall.exclusive`** — "tail": the last `tiles` clips in date order. `exclusive`: the + wall's clips are tiles only, outside the run (no segment, no chapter). `montageSplit` is the one place that says which + clips are tiles; `planMontage`, the build and verify-build all read it. Fewer than 2 run clips is a lint error. +4. **`ramp.into: "wall"`** — the ramp ends on the wall's first gap (`wallFirstGap`), `to` optional. +5. **Whip into the wall** — the wall already enters with the cut style (`cutStyleParts` on the wall segment). With + groups, each group slides in (above): cheap and clean, so no hard pop. +6. **`build-to-wall`** (label "Build to the wall") — whip, ramp from 3.5 s into the wall, drift, tally (as accelerate; it + reads over the whips because the counter is drawn after the cut style), and an exclusive tail wall of 25 in synced + double groups (1,1,2,4,8,9) with years, build 7.5 s (first gap 1.67 s). The other six styles take `null` for the new + nested keys (`ramp.into`, the four wall keys), so one style over another still leaves exactly the second. Their effect + is unchanged. +7. The grouped compose re-stamps its mix by sample count before the fades. On real tiles amix's clock ran ahead and the + end fade silenced everything after the first tile (found by the smoke; today's single wall is left byte for byte as + it was). + +## Files + +`umtool/report-to-video/montage.mjs`, `montage-styles.mjs`, `build-video.mjs` (`findMontagePhrase`, +`montageWallSource`, `speechExcerpt`, `wallOnsets`, `buildMontageWall`, the exclusive split in the entries), +`verify-build.mjs`, `montage.test.mjs`, `README.md`, `umtool/docs/report-video.md`, `editor/CHANGELOG.md`, +`plans/FACTS.md`. + +| Commit | What | +| --- | --- | +| `9454a027` | groups, sync, tail, exclusive, ramp into the wall, build-to-wall, validation; tests | +| `8acbc01b` | consensus alignment + template anchor; the grouped mix re-stamped; README | +| `2075a5e7` | docs (docs/report-video.md, FACTS, CHANGELOG) | +| (this commit) | this record | + +## Gates + +- tsc clean before each commit. +- test:scripts 1113 (1109 pass, 4 skipped) at `main` `00f6da06` → **1125 (1121 pass, 0 fail, 4 skipped)**. +- Byte-identical defaults: a wall-finale and an accelerate manifest built by main's and the branch's build-video → + identical md5. In the suite, a wall + ramp manifest with the new keys spelled at their defaults matches the bare one. + That test failed once in one run of the suite and passed in 5 runs after; it now names the differing segment on a + mismatch. Main's wall built 4× concurrently was bit-identical, so the one-off mismatch was not reproduced. +- Real render tests: build-to-wall over 12 synthetic clips. Three clips run and nine are tiles. Length is right to ±1 + frame. The last cut is no longer than the first gap. Every onset moved 2.0 → 2.25 s (the sound) within 15 ms. Each + tile's own phrase starts at its 0.12 s lead. Groups are empty before their beat and filled on it. The wall is audible + on every beat. 4 chapters; verifyBuild clean. + +## Smoke (the project read only; copied fresh after the operator's edits: 73 clips) + +`$T/r33m3-smoke2/build-to-wall.mp4`: 116.9 s, 49 chapters (48 run clips + the wall), verify-build ok, rendered in 198 s. + +- **Wall:** 8.7 s; tiles s49–s73; group beats 0.13, 1.80, 3.30, 4.63, 5.80, 6.80 s; final beat 7.63 s; anchor +175 ms. +- **Run cuts near the wall:** s45 1.78, s46 1.66, s47 1.71 (cap 1.71), s48 1.56 s; first gap 1.67 s. +- **Onset sources:** of the 73 clips, 40 have whisper token offsets, 16 a parakeet `chunk_data`, 17 neither. Of the 25 + tiles, 13 used whisper's words and 12 the cues. +- **Onset spread:** each tile's broadband loudness envelope cross-correlated with the mean of the others' (±250 ms): + + | Alignment | median | p90 | within 50 ms | + |---|---|---|---| + | estimates | 155 ms | 345 ms | 4/25 | + | per-clip loudness rise | 150 ms | 245 ms | 9/25 | + | consensus (shipped) | 185 ms | 255 ms | 10/25 | + + This measure has a floor of its own: syllable ambiguity. +- **Crowd sharpness:** the steepest 50 ms rise of all 25 tiles summed at their alignment points goes from 1.6 dB + (estimates) to 9.4 dB (shipped). In the rendered wall, the crowd's sharpest rise is 8.6 dB at −10 ms from the final + beat. +- `wall-groups.jpg` (each group's arrival and the final beat), `wall-slide.jpg` (a group sliding in), `contact.jpg`. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -808,6 +808,11 @@ The named styles (`report-to-video/montage-styles.mjs`) are the ones worth auditioning as takes: **Straight**, **Flash and count**, **Accelerate**, **Stutter**, **Wall finale**, **Whip and years**. Each is a merge patch that sets every montage key, so applying one over another leaves exactly the second. +**Build to the wall** runs the clips with whip cuts, faster and faster, straight +into a wall of the latest 25: they are taken out of the run (`wall.exclusive`, +`wall.clips: "tail"`), arrive in groups of 1, 1, 2, 4, 8 and 9 on accelerating +beats, each group saying it in unison with its onsets synced to the beat, then +all 25 at once. ## Operator notes, timed notes and the generated-manifest guard diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -747,8 +747,9 @@ stutter's `every` counts the same number; the ramp counts places. "counter": { "style": "chip", "position": "top-left", "of": false, "showDate": true, "showSource": true }, "punch": { "mode": "snap", "scale": 1.15, "anchor": "upper" }, "stutter": { "every": 5, "clips": ["s12"], "times": 3, "length": 0.35, "step": 0.04 }, - "ramp": { "from": 4, "to": 1.4 }, - "wall": { "at": "end", "tiles": 16, "build": 8, "year": true }, + "ramp": { "from": 4, "to": 1.4 }, // or { "from": 3.5, "into": "wall" } + "wall": { "at": "end", "tiles": 16, "build": 8, "year": true, + "groups": "double", "sync": true, "clips": "tail", "exclusive": true }, "yearStamp": true } } ``` @@ -760,8 +761,12 @@ stutter's `every` counts the same number; the ramp counts places. | `counter` | An overlay, never a card. `chip`: "#12 · 2 May 2019 · YouTube" on a translucent ground, the whole clip. `big`: the number, large in the accent colour, slamming in on each cut and gone by 1.5 s, the date under it. `tally`: tick marks in fives, the newest landing in the accent. `of: true` adds "of N". Corners: `top-left`, `top-right`, `bottom-left`, `bottom-right`. | | `punch` | `snap`: the picture jumps to `scale` (1.15) at the phrase's onset. `drift`: a slow zoom from 1 to `scale` (1.08) over the clip. `anchor: "upper"` holds the upper third (where a face usually is); `"center"` the middle. | | `stutter` | On every `every`th clip and on the clips named in `clips`: the phrase's last `length` seconds are heard `times` times in all (2–4), each repeat `step` more zoomed — "…news day-day-day". The clip is that much longer. | -| `ramp` | Clip k's cut is at most lerp(`from`, `to`, k/(N−1)) seconds — the first `from`, the last `to` — trimmed evenly around the phrase, never into it. Needs `tighten: "phrase"`. | +| `ramp` | Clip k's cut is at most lerp(`from`, `to`, k/(N−1)) seconds — the first `from`, the last `to` — trimmed evenly around the phrase, never into it. Needs `tighten: "phrase"`. `into: "wall"` (with a `wall`) ends the ramp on the wall's first gap instead of `to`, so the cut runs straight into the wall at its pace. | | `wall` | One more segment at the `end` (or `start`): a grid of 9, 16 or 25 tiles, each playing a clip's phrase (clips spread first to last; fewer clips than tiles go round again). Tile i appears at build·(1−(1−i/tiles)²) seconds, so the last come fastest; the newest tile is heard, the rest ducked; at `build` every tile says it together, then the cut. `year: true` labels each tile with its year. Its chapter is "All together". | +| `wall.groups` | `"single"` (default): the tiles one at a time, as above. `"double"`: in groups of 1, 1, 2, 4, 8 … (9 tiles: 1,1,2,5; 16: 1,1,2,4,8; 25: 1,1,2,4,8,9 — a leftover smaller than the group before joins it). Each group arrives together on a beat, sliding in from the right over four frames; the gaps between beats fall evenly from the first to half of it across `build`. A group's tiles say their phrase in unison and fall silent (a 40 ms fade) just before the next group's beat; then every tile together. | +| `wall.sync` | Default `true` with `"double"` groups, else `false`. Each tile is cut to start 0.12 s before its phrase's onset and end 0.25 s after the phrase, and is shown that 0.12 s before its beat, so the onset lands exactly on its group's beat and on the final beat: the crowd says it on one frame. The estimate is whisper's word offset when the corpus's `transcript.json` keeps them, else the cue estimate (character position). Neither is good to better than a few hundred milliseconds, and the loudness of one clip cannot tell "slow" from the word before it, so the tiles are aligned to EACH OTHER: each tile's speech-band spectrum (8 bands, 5 ms frames) over its phrase is matched to the mean of the others' within ±0.4 s of its estimate, four rounds, the median shift kept at zero (`consensusLags`); then all of them move together onto where their mean loudness rises (`templateOnset`, within ±0.3 s). Under three tiles: the sharpest loudness rise near each estimate (`refineOnset`). The wall's `.cut.json` records each tile's estimate, onset, `by` and its correlation with the rest (`r`), and the common `syncAnchor`. | +| `wall.clips` | `"spread"` (default): tiles from clips spread first to last. `"tail"`: the last `tiles` clips of the cut, in date order — group 1 is the earliest of them, the last group the latest. | +| `wall.exclusive` | `true`: the wall's clips are tiles only. They leave the run of clips (no segment, no chapter), so the counter, the tally and the ramp count the clips before the wall, and the wall condenses the repetition rather than repeating it. With fewer than 2 clips left outside the wall it is an error. A tile clip with no segment is cut from its window like any clip (`--no-network` holds). | | `yearStamp` | On the first clip of each year, the year large in the corner across from the counter for about a second. | **Where it is made.** Everything except the wall is inside each clip's own @@ -779,7 +784,9 @@ values in words that say which, and a montage beside `render.chrome` (the deck), **Named styles.** `montage-styles.mjs` holds the styles worth auditioning as merge patches (RFC 7386) on the manifest: `straight`, `flash-count`, -`accelerate`, `stutter`, `wall-finale`, `whip-years`. Each sets every montage +`accelerate`, `stutter`, `wall-finale`, `whip-years`, and `build-to-wall` +(whip cuts, a ramp from 3.5 s into the wall, a slow zoom, the tally, then an +exclusive tail wall of the latest 25 in synced groups 1,1,2,4,8,9 with years). Each sets every montage key, so one over another leaves exactly the second. umtool's take form lists them; from the terminal: diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -179,8 +179,9 @@ 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, + bandFeatures, consensusLags, templateOnset, + 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 +1367,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 +1423,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 +1438,101 @@ 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, + }; +} + +/** + * `seconds` of a source's sound from `from` (raw-file seconds, may be + * negative), speech band (high-passed at 200 Hz), 16 kHz mono, as samples; + * silence where the file has none, so the excerpt is always that long. + */ +async function speechExcerpt(raw, from, seconds, rate = 16000) { + const at = Math.max(0, from); + const { stdout } = await execFileP(FFMPEG, [ + "-nostdin", "-v", "error", "-ss", at.toFixed(3), "-t", (seconds - (at - from)).toFixed(3), "-i", raw, + "-vn", "-ac", "1", "-ar", String(rate), "-af", "highpass=f=200", "-f", "s16le", "-", + ], { encoding: "buffer", maxBuffer: 1 << 24 }); + const got = new Int16Array(stdout.buffer, stdout.byteOffset, Math.floor(stdout.length / 2)); + const out = new Int16Array(Math.round(seconds * rate)); + out.set(got.subarray(0, out.length - Math.round((at - from) * rate)), Math.round((at - from) * rate)); + return out; +} + +/** How far before and after its estimate a tile's sound is compared, seconds. */ +const ONSET_PRE = 0.8; +const ONSET_LEN = 2.4; +const ONSET_HOP = 0.005; + +/** + * Every synced tile's phrase onset, by id, on its raw file's clock. With + * three tiles or more: aligned to one another (montage.mjs consensusLags -- + * each tile's speech-band spectrum over its phrase matched to the mean of the + * others', within ±0.4 s of its estimate, the median shift kept at zero), so + * the crowd says it together; `by: "consensus"`, with the tile's correlation + * `r`. With fewer: the sharpest rise of loudness within ±0.4 s + * (refineOnset), `by: "rise"`, else the estimate, `by: "estimate"`. The + * estimate is whisper's word offset or the cue estimate (`via`). + */ +async function wallOnsets(tiles) { + const rate = 16000; + const out = new Map(); + const ex = []; + for (const t of tiles) ex.push(await speechExcerpt(t.raw, t.phrase.start - ONSET_PRE, ONSET_LEN, rate).catch(() => null)); + if (tiles.length >= 3 && ex.every(Boolean)) { + const feats = ex.map((x) => bandFeatures(x, rate, { hop: ONSET_HOP })); + const origin = Math.round((ONSET_PRE - 256 / rate) / ONSET_HOP); + const { lags, r } = consensusLags(feats, { origin, pre: 10, span: 160, search: Math.round(0.4 / ONSET_HOP) }); + // Then all of them together onto where their mean loudness rises. + const anchor = templateOnset(feats, lags, { origin, window: 0.3, hop: ONSET_HOP }); + const shift = anchor?.shift ?? 0; + tiles.forEach((t, i) => out.set(t.id, { + at: t.phrase.start + lags[i] * ONSET_HOP + shift, by: "consensus", r: Number(r[i].toFixed(2)), + })); + out.anchor = Number(shift.toFixed(3)); + return out; + } + tiles.forEach((t, i) => { + const r = ex[i] ? refineOnset(ex[i], rate, ONSET_PRE, { window: 0.4 }) : null; + out.set(t.id, r ? { at: t.phrase.start - ONSET_PRE + r.at, by: "rise" } : { at: t.phrase.start, by: "estimate" }); + }); + return out; +} + +/** * 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 +1577,61 @@ 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 aligned to the others' (wallOnsets), and the + // tile cut to start WALL_LEAD before it. + const sources = new Map(); + const onsets = w.sync ? await wallOnsets([...new Set(chosen)].map((id) => ({ id, ...M.cuts.get(id) }))) : null; + 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 o = onsets.get(id); + const onset = Math.min(c.cutB - 0.4, Math.max(c.cutA, o.at)); + 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, by: o.by, r: o.r ?? 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 +1653,17 @@ 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) { + if (onsets?.anchor != null) record.syncAnchor = onsets.anchor; + record.sync = tiles.map((t) => ({ id: t.id, raw: t.raw, from: Number(t.from.toFixed(3)), ...sources.get(t.id).sync })); + } + await writeCutRecord(seg, { version: 1, id: WALL_ENTRY.id, montageWall: record }); return seg; } @@ -4657,10 +4787,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 +5075,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,356 @@ 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,` + + // Re-stamped by sample count before the fades: amix's output clock can + // run ahead of its samples when its inputs start late (an asplit feeding + // a long adelay), and a fade timed on that clock silences the wall. + `apad=whole_dur=${total},atrim=end=${total},asetpts=N/SR/TB,` + + `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 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 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, bandFeatures, consensusLags, templateOnset, } 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,295 @@ 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("consensusLags + templateOnset: takes of one phrase at different times line up, and land on its onset", () => { + const rate = 16000; + // A floor of noise, then two "syllables" (500 Hz, 900 Hz) from `on`; every estimate says 0.8 s. + const take = (on) => Int16Array.from({ length: 2.4 * rate }, (_, i) => { + const t = i / rate; + const noise = 300 * ((Math.sin(i * 12.9898) * 43758.5453) % 1); + const syl = (t >= on && t < on + 0.25) || (t >= on + 0.35 && t < on + 0.6); + return Math.round(noise + (syl ? 9000 * Math.sin(2 * Math.PI * (t < on + 0.3 ? 500 : 900) * t) : 0)); + }); + const origin = Math.round((0.8 - 256 / rate) / 0.005); + for (const ons of [[1.05, 1.0, 1.12, 0.98, 1.07], [0.6, 0.65, 0.7, 0.62, 0.66], [0.9, 0.93, 0.95, 0.87, 1.1, 0.91]]) { + const feats = ons.map((o) => bandFeatures(take(o), rate)); + assert.equal(feats[0][0].length, 8); + const { lags, r } = consensusLags(feats, { origin, pre: 10, span: 160, search: 80 }); + assert.equal([...lags].sort((a, b) => a - b)[Math.floor(lags.length / 2)], 0, "the median shift is zero"); + for (const x of r) assert.ok(x > 0.9, `r ${x}`); + const a = templateOnset(feats, lags, { origin }); + ons.forEach((o, i) => assert.ok(Math.abs(0.8 + lags[i] * 0.005 + a.shift - o) <= 0.0051, `${ons}: take ${i}`)); + } + // Two takes: no consensus, no shift. + assert.deepEqual(consensusLags([[], []], { origin: 0 }).lags, [0, 0]); +}); + +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]; + // On a mismatch, say which segment differs. + const segs = ["s1", "s2", "s3", "s12", "montage-wall"].map((id) => `sourced/segments/${id}.mp4`); + const which = segs.filter((f) => md5(path.join(a.root, "out", f)) !== md5(path.join(b.root, "out", f))); + assert.equal(md5(path.join(a.root, "out", "demo.mp4")), md5(path.join(b.root, "out", "demo.mp4")), `differs: ${which.join(", ") || "only the final"}`); + } 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 moved from the cues' 2.0 to the sound's 2.25 (the tiles agree, and their + // mean loudness rises there), to within 15 ms. + for (const t of wall.sync) { + assert.equal(t.estimate, 2); + assert.equal(t.by, "consensus", t.id); + assert.ok(Math.abs(t.onset - 2.25) <= 0.015, `${t.id} ${t.onset}`); + } + assert.ok(Math.abs(wall.syncAnchor - 0.25) <= 0.015, `anchor ${wall.syncAnchor}`); + // 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"); + // Heard all through: on each group's beat and at the final one. + const level = (from) => Number(String(spawnSync("ffmpeg", ["-nostdin", "-ss", from.toFixed(3), "-t", "0.3", "-i", path.join(seg, "montage-wall.mp4"), "-vn", "-af", "volumedetect", "-f", "null", "-"]).stderr).match(/mean_volume: (-?[\d.]+)/)[1]); + for (const b of [...wall.groupBeats, wall.beat]) assert.ok(level(b) > -40, `silent at ${b}`); + // 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");