Archilyzer · Source

archilyzer

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

commit b2426a8a6ef031b148020ae79235a3ef074c1e08
parent 35313baec6513a4df0859e2a5d33fe95a8f052bd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 17:20:17 -0400

Merge r33/montage: render.montage (phrase-tight cuts, flash/whip/dip, counter chip/big/tally, punch-ins, stutter, ramp, the wall, year stamps) and six montage styles

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 22++++++++++++++++++++++
Aplans/release-33/montage.md | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 22++++++++++++++++++++++
Mumtool/report-to-video/README.md | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/lint.mjs | 7+++++--
Aumtool/report-to-video/montage-styles.mjs | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/montage-styles.test.mjs | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/montage.mjs | 963+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/montage.test.mjs | 759+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/verify-build.mjs | 11+++++++++--
12 files changed, 2450 insertions(+), 15 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased] - **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. - **`pnpm heavy` caps what it runs.** A command admitted to the heavy slot through `pnpm heavy -- <cmd>` (or `scripts/queue-lock.mjs --heavy`) now runs in a memory-capped systemd user scope of its own — 8 GB, 2 GB of swap — so a runaway render or build is stopped in its scope instead of taking the desktop session down. A command that sets its own `MemoryMax=`, or one started from inside a capped unit or scope (the live editor and umtool, a publish stage's build), is run as before. `HEAVY_CAP=0` turns it off; `HEAVY_CAP_MB` and `HEAVY_CAP_SWAP_MB` size it. - **A media move says how far its copy got again with the newer rsync.** rsync 3.5.1 as packaged since mid-October writes its progress with a unit on the byte count and an unscaled rate, which the move did not read: the job showed no progress bar and no "Copying… · N % ·" lines, and the log filled with rsync's raw redraws. Both forms are read now, and the rate reads as before (for example 1.16GB/s). Needs a restart of the editor. - **A full download from Odysee's stored media URL survives a dropped connection.** When the connection to the file's server drops mid-file (`fetch failed`, a reset, a timeout, a body cut short), the same download now checks what came down, pauses 45 seconds, opens the video's page again and goes on from the last clean byte — it no longer ends the job. Each one is in the job log as "Connection dropped at <bytes> — reopening the page and resuming (k of 6)". After six drops in a row with no progress the download stops and keeps what it has for the next run, as before. A refusal that follows bytes the server served is handled the same way; a refusal straight after the page was opened still stops at once. A continuation is not a new file: it does not wait the 20-minute rest between files, and the whole run is still one attempt on the video's record (one of the two full-audio attempts before a salvage). The attempt records how many continuations it took. Needs a restart of the editor. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10387,3 +10387,25 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `dropGapBytes` (default `dropAfterBytes`; 0 = every later request cut before its first byte): the cut is mid-body (headers + part of the body, then the socket destroyed) or, on a request's first byte, before any response; a cut request is `dropped: true` with the bytes it sent. `cdn.lock()` takes an unlock back. + +## Release 33 lane M3: montage editing in report-to-video (verified 2026-10-17, branch `r33/montage`) + +- `render.montage` (object; absent or `null` = off) is read only by `umtool/report-to-video/montage.mjs` (pure) and + the montage hooks in `build-video.mjs`; without it every argv is unchanged (a 4-clip render on `main` and on the + branch: identical md5 for the final and every segment). Keys: `tighten`, `phrasePad`, `cut`, `flashColor`, + `counter`, `punch`, `stutter`, `ramp`, `wall`, `yearStamp` (`MONTAGE_KEYS`; README "`render.montage`"). + `validateMontage` is in the build's validators and `lint.mjs` `validatorErrors`. +- A clip's phrase is `montage.match`, else `onscreen.title`; its date `montage.date` (YYYYMMDD) → `date` → the + record's `uploadDate`; its source `montage.platform`. Word timing: whisper.cpp full JSON in the corpus's + `transcript.json` (`transcription[].tokens[].offsets` in ms) first, else the cues by character position. Parakeet's + `chunk_data` and YouTube cue files carry no word offsets. +- Montage cuts are made inside each clip segment, so a montage's concat is always the hard-cut stream copy (`D = 0` + whatever `render.transition` says). A segment's frames are planned exactly (`floor((cutB−cutA)·fps)` plus stutter + repeats) and recorded in `<id>.cut.json` `montage: {phrase, found, tight, frames, seconds, pieces}`. +- The wall is a segment with no timeline entry: `segments/montage-wall.mp4` (+ `.cut.json` `montageWall`), tiles in + `segments/montage-wall/<clipId>.mp4`; the build appends `{type: "montage-wall", id: "montage-wall", title: "All + together"}` to its entries (chapters, `--chapters-only`), and `verify-build` counts it as one more chapter. +- `montage-styles.mjs` is the interface umtool's take maker reads: `MONTAGE_STYLES: Record<name, {label, summary, + 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`. diff --git a/plans/release-33/montage.md b/plans/release-33/montage.md @@ -0,0 +1,74 @@ +# Release 33 lane M3 — montage editing in report-to-video (as shipped) + +The operator asked (2026-10-17) for a montage of every time TheQuartering said "slow news day/week/cycle", kept +chronological, with editing techniques worth auditioning as variants. This lane is the renderer half: +`render.montage` in report-to-video and the named styles umtool's take maker (lane M1) lists. + +## What + +1. **`render.montage`** (`umtool/report-to-video/montage.mjs`, pure; build-video's hooks run only when it is set): + - `tighten: "phrase"` cuts each clip to the phrase ± `phrasePad` (0.6 s) inside its extent. The phrase is the clip's + `montage.match` (else `onscreen.title`), found by character position in the clip's cues, or by whisper.cpp's token + offsets in the corpus's `transcript.json` when present. Edges snap to silence (the existing `snap`) only where the + snap stays outside the phrase, inside the extent and under the ramp's cap. Not found: today's cut, and a note. + - `cut: hard | flash | whip | dip` — made on each segment's own first/last frames (flash 3 frames from the colour; + dip 2+2 frames through black; whip 4+4 frames sliding, wrapped, blurred along the move). Every segment's sound + fades 15 ms at each edge. + - `counter: {style: chip | big | tally, position, of, showDate, showSource}` and `yearStamp` — drawtext/drawbox over + the frame. + - `punch: {mode: snap | drift, scale, anchor: upper | center}`, `stutter: {every, clips, times 2–4, length, step}`, + `ramp: {from, to}` (cut k ≤ lerp(from, to, k/(N−1))) — the segment's pieces (trim/crop/concat) and a zoompan. + - `wall: {at: end | start, tiles: 9 | 16 | 25, build, year}` — one more segment: tiles appear at + build·(1−(1−i/T)²), the newest heard and the rest ducked, then all together at the beat. + - A montage's concat is always hard (the cuts are in the segments), so a segment's length is planned to the frame + and recorded (`<id>.cut.json` `montage.frames`). +2. **`montage-styles.mjs`** — the shared interface with M1: `MONTAGE_STYLES` (`straight`, `flash-count`, + `accelerate`, `stutter`, `wall-finale`, `whip-years`; plain-words label and summary; an RFC 7386 merge patch under + `render.montage` that sets every key), `montageStyle(name)` (deep copy), `mergePatch`, `applyMontageStyle`, and a + `list` / `apply` CLI. Landed first (`dae55bc7`). +3. **Validation** — `validateMontage` in the build's validators and the lint: unknown keys, bad values, a ramp without + `tighten: "phrase"`, stutter ids not in the timeline, and a montage beside the deck, the rail, the chart band or a + clip `muteFrom`, each in a sentence naming the key. +4. **verify-build** counts the wall's chapter, and a phrase-cut clip's floor is 0.5 s. + +## Files + +`umtool/report-to-video/montage.mjs` (new), `montage-styles.mjs` (new), `montage.test.mjs` (new, 32 tests), +`montage-styles.test.mjs` (new, 6 tests), `build-video.mjs` (imports, the validator, `montageCut` / +`montageSegmentGraph` / `buildMontageWall`, the forced hard join, the wall in the entries and `--chapters-only`), +`lint.mjs` (one validator), `verify-build.mjs`, `README.md` ("`render.montage` — montage editing"), +`umtool/docs/report-video.md` ("Montages"), `editor/CHANGELOG.md`, `plans/FACTS.md`. + +| Commit | What | +| --- | --- | +| `dae55bc7` | montage-styles.mjs — the named styles (the shared interface), merge patch, CLI; 6 tests | +| `bf3a0553` | render.montage in the renderer (montage.mjs + build-video hooks + lint); 32 tests incl. a render per style | +| `6ec868a4` | verify-build knows the wall and the phrase-cut floor | +| `b66e5399` | docs (README, docs/report-video.md, FACTS, CHANGELOG); the tally's date line on its own ground (found by the smoke) | +| (this commit) | this record | + +## Gates + +All through the shared heavy lock, from the worktree root: +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before each commit. +- `pnpm run test:scripts`: **1056 (1052 pass, 4 skipped) at `main` `643434f7` → 1094 (1090 pass, 0 fail, 4 skipped)**. + `montage.test.mjs` alone 32/32 (~33 s, real 320×180 renders of each style over lavfi clips: length to ±1 frame of + the cut records' plan, pixel checks for the flash, the chip, the big number, the tally's newest mark, the punch-in, + the whip, the dip, the year stamp, the wall's last tile, and verifyBuild on the wall). +- Byte-identical: the same 4-clip manifest without `render.montage` rendered by `main`'s and the branch's + build-video — identical md5 for the final and all four segments; in-suite, absent vs `null` identical. +- Not touched, not run: common, editor unit, mcp, umtool TS (`pnpm --filter umtool test`), e2e (no UI in this lane), + builds. No CLI row, env var, settings or file schema in the generated docs changed. + +## Live smoke (read-only on the project) + +`~/reports/quartering-slow-news/video.manifest.json` copied to the job's scratch. With the project's `fetchPad: 3` +no clip was on disk for `--no-network`: the editor's windows are exactly each clip's extent. With `fetchPad: 0` on the +copy, 17 of 75 were; 12 of them (2019–2026) were rendered with each style, `--no-network --cue-source local`, preset +veryfast: straight 30.1 s, flash-count 30.1 s, accelerate 26.0 s, stutter 31.6 s, wall-finale 39.3 s (16 tiles +over 12 clips), whip-years 30.1 s; every phrase found in the cues, verify-build ok on all six. + +## Rulings followed + +No cards (the wall and the counter are footage and overlays); plain words in labels and summaries; nothing calls a +model; synthetic fixtures only; the project read only. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -724,6 +724,28 @@ anyway**; a umtool job working in the project refuses. Its verdict row and the notes on it are kept: the agent reads them back, and a verdict on a take that is gone shows as missing. +## Montages (`render.montage`) + +A cut of one phrase said many times — every "slow news day" — is a montage, and +`render.montage` gives it its editing: each clip cut tight to the phrase +(`tighten: "phrase"`, ± `phrasePad`), a cut style (`flash`, `whip`, `dip` or +`hard`), a running counter (`chip`, `big` or `tally`, with the date and the +source), a punch-in (`snap` at the phrase, or a slow `drift`), a `stutter` on +chosen clips, a `ramp` that shortens the clips toward the end, a `wall` of 9, 16 +or 25 tiles saying it together, and a `yearStamp` when the year changes. All are +overlays on the footage or the footage itself — never a card. A clip's phrase is +its `montage.match` (else `onscreen.title`), its date `montage.date`. + +Every key, its values and where each is made: [report-to-video +README](../report-to-video/README.md#rendermontage--montage-editing-release-33). +The build and `--lint` refuse an unknown key or a bad value, saying which, and a +montage beside the deck, the rail or a clip's `muteFrom`. + +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. + ## Operator notes, timed notes and the generated-manifest guard Notes on a project live in `<project>/notes.json` (shape and CLI: diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -12,6 +12,7 @@ Two scripts and a manifest: | `render-cards.mjs` | stable | draws the timeline footer and marker, plus optional card stills. Imported by `build-video.mjs`. | | `resolve-windows.mjs` | stable | widens clip windows from cue spans to whole sentences. Run once after authoring a manifest. | | `brand.mjs`, `brand-cards.mjs` | stable | the opt-in brand preset (`render.brand`); see [its section](#the-archilyzer-media-preset-renderbrand). | +| `montage.mjs`, `montage-styles.mjs` | stable | montage editing (`render.montage`) and its named styles; see [its section](#rendermontage--montage-editing-release-33). | | `<report>/video.manifest.json` | per report | the edit decision list. **This is the regeneration source of truth**, not the report. | ``` @@ -725,6 +726,66 @@ recordings' dates; the quote, verbatim); a thread's outcome is its last clip's `claim.verdict`. Each task refuses a cut that has the other panel, unless forced over a draft of it, which it then replaces. +### `render.montage` — montage editing (release 33) + +A montage is one phrase said many times: dozens of short clips, cut tight, run +in order. `render.montage` turns on the techniques for it. All of it is opt-in; +a manifest without `render.montage` (or with `null`) renders byte for byte as +before. Each clip's phrase is its `montage.match` (what +the phrase seed writes), else its `onscreen.title`; its date is +`montage.date` (`YYYYMMDD`), else `date`, else the record's upload date; its +source is `montage.platform`. + +```jsonc +"render": { "montage": { + "tighten": "phrase", // "phrase" | "sentence" | null (null and "sentence": today's cut) + "phrasePad": 0.6, // seconds kept either side of the phrase + "cut": "flash", // "hard" | "flash" | "whip" | "dip" + "flashColor": "white", // "white" | "accent" | "#rrggbb" + "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 }, + "yearStamp": true +} } +``` + +| key | what it does | +|---|---| +| `tighten: "phrase"` | Cuts each clip to the phrase ± `phrasePad`, never outside the clip's `start`/`end`. The phrase is found in the clip's cues by character position (a cue's characters spread evenly over it), or by whisper.cpp's token offsets in the corpus's `transcript.json` when it keeps them. Each edge then snaps to the nearest silence within `snapWindow`, as every cut does, but only where the snap stays outside the phrase. A phrase not found keeps today's cut and says so (`note`). | +| `cut` | `flash`: the first 3 frames of each clip fade from the flash colour. `dip`: 2 frames to black before the cut and 2 up from it. `whip`: the last 4 frames slide out left and the first 4 slide in from the right, blurred along the move. `hard`: none. The cut's first and last segments have nothing to cut from or to. Every segment's sound fades in and out over 15 ms (no click). | +| `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"`. | +| `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". | +| `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 +segment encode: the trim points, the pieces (punch-in, stutter, drift), the cut +style on the segment's first and last frames, the drawtext/drawbox overlays. +So the concat stays the stream copy of hard cuts — a montage is joined hard +whatever `transition` says — no chrome layer is rendered, and each segment's +length is known to the frame before it is encoded (`<id>.cut.json`'s +`montage.frames`). The wall's tiles are small files in +`segments/montage-wall/`, composited into `segments/montage-wall.mp4`. + +**Validation.** The build's validators and `--lint` refuse unknown keys and bad +values in words that say which, and a montage beside `render.chrome` (the deck), +`render.rail`, `chromeEngine: "hyperframes"` or a clip's `muteFrom`. + +**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 +key, so one over another leaves exactly the second. umtool's take form lists +them; from the terminal: + +``` +node umtool/report-to-video/montage-styles.mjs list +node umtool/report-to-video/montage-styles.mjs apply flash-count video.manifest.json --out takes/flash/video.manifest.json +``` + ### `publish.youtube` — the upload's text (`out/youtube.txt`) ```jsonc diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -174,6 +174,15 @@ import { // as it did -- see brand.mjs. import { brandHeaderGeometry, brandManifest } from "./brand.mjs"; import { markPng, renderThumbnail, THUMB_MAX_BYTES } from "./brand-cards.mjs"; +// Montage editing (`render.montage`, release 33): the tight phrase cut, the +// pieces, the cut styles, the counter and the wall -- pure, in montage.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, +} from "./montage.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; const execFileP = promisify(execFile); @@ -1131,11 +1140,15 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const win = render.snapWindow ?? 1.6; const sil = await detectSilence(raw, render, scan); - const a = snap(wantA, sil, "start", win, render); - const b = snap(wantB, sil, "end", win, render); + // A montage cuts to the phrase (montageCut); every other clip as it always was. + const mont = dirs.montage + ? await montageCut({ entry, M: dirs.montage, render, provenance, fetchStart, sil, wantA, wantB, win, raw }) + : null; + const a = mont ? mont.win.start : snap(wantA, sil, "start", win, render); + const b = mont ? mont.win.end : snap(wantB, sil, "end", win, render); // Never let snapping invert or collapse the window. - const cutA = Math.min(a.at, wantB - 1); - const cutB = Math.max(b.at, cutA + 1); + const cutA = mont ? mont.win.cutA : Math.min(a.at, wantB - 1); + const cutB = mont ? mont.win.cutB : Math.max(b.at, cutA + 1); EMIT("snap", { id: entry.id, start: a.snapped, end: b.snapped, seconds: cutB - cutA }); // Where in the SOURCE this segment really starts and ends, snapped: what a // `muteFrom` (source seconds) is measured from at the join, long after this @@ -1303,18 +1316,26 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, nextIdx += 1; inputs.push(...pst.input); } - const pic = pst ? "[pic]" : "[0:v]"; + // A montage's pieces come first: the picture and the sound of the cut, + // re-timed (a stutter), zoomed (a punch-in) and fitted to the box, which the + // framing below then leaves as it is. Its sound replaces `0:a`; a poster + // shares it through an asplit. + const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB }) : null; + const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]"); + const lead = mg + ? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts] + : (pst ? pst.parts : []); const parts = hasFooter ? [ - ...(pst ? pst.parts : []), + ...lead, `${pic}${base}[b]`, `[b][${footerIdx}:v]overlay=0:${height - FH}[f]`, `[${barIdx}:v]crop=w=${chrome.trackLen}:h=3:x='${chrome.trackLen}-(${fillExpr})':y=0[bar]`, `[f][bar]overlay=x=${chrome.x0}:y=${trackAbsY - 1}[g]`, `[g][${markerIdx}:v]overlay=x=${markX}:y=${trackAbsY - chrome.markerRadius}[q]`, ] - : [...(pst ? pst.parts : []), `${pic}${base}[q]`]; + : [...lead, `${pic}${base}[q]`]; let q = "q"; if (brandMark) { @@ -1327,6 +1348,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ? `[${q}][${qrIdx}:v]overlay=x=${VW}-w-${qrM}:y=H-h-${FH + qrM}[v]` : `[${q}]null[v]`, ); + // A montage's cut style and its counter, over the finished frame. + if (mg) parts.push(...mg.post("[v]", "[vm]")); await execFileP( FFMPEG, @@ -1334,13 +1357,183 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, "-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", parts.join(";"), - "-map", "[v]", "-map", "0:a", + "-map", mg ? "[vm]" : "[v]", "-map", mg ? mg.a : "0:a", ...encodeArgs(render), seg, ], { maxBuffer: 1 << 24 }, ); - await writeCutRecord(seg, cutRecord); + 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, + }); + } + return seg; +} + +// ---- montage (render.montage) --------------------------------------------- +// The build's side of montage.mjs: what needs the cue source, the corpus and +// ffmpeg. Reached only when render.montage is set. + +/** + * A corpus video's whisper words (transcript.json's token offsets), when the + * corpus is on disk and keeps them; null otherwise. Read once per video. + */ +async function montageWords(entry, provenance, M) { + if (hasLocalMedia(entry) || !M.channelsDir) return null; + const slug = entry.channel ?? provenance?.channelSlug; + if (!slug || !entry.video) return null; + const key = `${slug}/${entry.video}`; + if (!M.words.has(key)) { + M.words.set(key, (async () => { + try { + const dir = await resolveVideoDir(M.channelsDir, slug, entry.video); + const doc = JSON.parse(await readFile(path.join(dir, "transcript.json"), "utf8")); + return whisperWords(doc); + } catch { + return null; + } + })()); + } + return M.words.get(key); +} + +/** A clip's cues, wherever they live; [] when none can be read. */ +async function montageCues(entry, provenance) { + try { + if (hasLocalMedia(entry)) return LOCAL ? await LOCAL.cues(entry) : []; + const d = await CUES.load(entry.channel ?? provenance?.channelSlug, entry.video, { + siteChannel: entry.siteChannel, siteVideo: entry.siteVideo, + }); + return Array.isArray(d?.cues) ? d.cues : []; + } catch { + return []; + } +} + +/** + * Where a montage clip is cut, on the fetched file's clock: its phrase found + * (whisper's words first, then the cues), then montageWindow. A phrase that + * cannot be found is said, and the clip keeps today's cut; its cut window + * (`cutStart`/`cutEnd`, else the extent) stands in for the phrase where a + * punch-in or a stutter needs one. + */ +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, 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 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({ + extent: [entry.start - fetchStart, entry.end - fetchStart], play: [wantA, wantB], + phrase: found ? phrase : null, tighten: s.tighten, pad: s.phrasePad, cap: ctx.cap, + silences: sil, snapWindow: win, render, snap, + }); + return { win: w, phrase, via, ctx, settings: s, source: { start: at.start, end: at.end } }; +} + +/** + * 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. + */ +function montageSegmentGraph({ mont, render, box, hasVideo, cutA, cutB }) { + const { settings: s, ctx } = mont; + const fps = render.fps; + const frames = Math.max(1, Math.floor((cutB - cutA) * fps + 1e-6)); + const pieces = montagePieces({ + frames, fps, + onset: mont.phrase.start - cutA, phraseEnd: mont.phrase.end - cutA, + punch: hasVideo ? s.punch : null, + stutter: hasVideo && ctx.stutter ? s.stutter : null, + }); + const g = montagePiecesGraph({ + pieces, fps, box, bg: render.palette.bg, punch: hasVideo ? s.punch : null, + inA: hasVideo ? "[0:a]" : "[mpa]", hasVideo, + }); + const overlays = montageOverlayFilters({ settings: s, ctx, render, font: montageFont(render) }); + return { + parts: g.parts, v: g.v, a: g.a, + post: (inLabel, outLabel) => { + const mid = overlays.length ? "[mvx]" : outLabel; + return [ + ...cutStyleParts({ + cut: s.cut, first: ctx.first, last: ctx.last, frames: g.frames, fps, w: render.width, h: render.height, + flashColor: s.flashColor, inLabel, outLabel: mid, + }), + ...(overlays.length ? [`[mvx]${overlays.join(",")}${outLabel}`] : []), + ]; + }, + record: { + phrase: [Number(mont.source.start.toFixed(3)), Number(mont.source.end.toFixed(3))], + found: mont.via, tight: mont.win.tight, frames: g.frames, seconds: Number(g.seconds.toFixed(4)), + pieces, + }, + }; +} + +/** + * The montage's wall (`render.montage.wall`): its tiles cut from the clips + * 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 }) { + 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 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 plan = wallPlan({ + tiles: tiles.length, build: s.wall.build, durations: tiles.map((t) => t.to - t.from), + fps: render.fps, width: render.width, height: render.height, + }); + const dir = path.join(outDir, "segments", "montage-wall"); + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + const made = new Map(); + const files = []; + for (const t of tiles) { + if (!made.has(t.id)) { + const file = path.join(dir, `${t.id}.mp4`); + await execFileP(FFMPEG, wallTileArgs({ + raw: t.raw, from: t.from, to: t.to, tileW: plan.tileW, tileH: plan.tileH, fps: render.fps, + year: t.year, font: montageFont(render), render, encode: encodeArgs(render), outPath: file, + }), { maxBuffer: 1 << 24 }); + made.set(t.id, file); + } + files.push({ file: made.get(t.id), seconds: t.to - t.from }); + } + await detachSegmentFiles(path.join(outDir, "segments"), WALL_ENTRY.id); + 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, + }), { 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 }, + }); return seg; } @@ -4211,7 +4404,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), - ...validateStatsEntries(whole), + ...validateStatsEntries(whole), ...validateMontage(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } @@ -4446,7 +4639,29 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const segments = []; const failures = []; - const D = opts.noXfade || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5; + // A montage makes its cuts inside its segments (montage.mjs), so they are + // joined hard, whatever `transition` says. + const montage = montageOn(render); + if (montage && (render.transition ?? 0.5) !== 0 && !opts.noXfade && !only) { + EMIT("note", { message: "render.montage: the cut styles are in the segments, so they are joined with hard cuts (render.transition is not used)" }); + } + const D = opts.noXfade || montage || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5; + // The montage's plan across the WHOLE cut (a clip's place, its year, its + // ramp cap), so an `--only` rebuild cuts a clip as the full build would. + // A clip with no date of its own takes its record's upload date. + if (montage) { + const settings = resolveMontage(render); + const dates = new Map(); + for (const e of manifest.timeline) { + if (e?.type !== "clip" || e.montage?.date || e.date) continue; + const meta = await clipMeta(e, provenance).catch(() => null); + if (meta?.uploadDate) dates.set(e.id, meta.uploadDate); + } + dirs.montage = { + settings, ctx: planMontage(manifest.timeline, settings, (e) => dates.get(e.id) ?? null), + cuts: new Map(), words: new Map(), channelsDir, + }; + } // One entry's segment, by its kind: the build's loop below, `--only`, and a // segment `--chrome-only` finds MISSING (with `o` = skipFetch). Before an @@ -4531,6 +4746,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // per-clip segments are still on disk, which is all the offsets need. if (opts.chaptersOnly) { const finalPath = dirs.final; + // A montage's wall is a segment of the cut too. + if (dirs.montage?.settings.wall) { + if (dirs.montage.settings.wall.at === "start") entries.unshift({ ...WALL_ENTRY }); + else entries.push({ ...WALL_ENTRY }); + } const segs = entries.map((e) => path.join(outDir, "segments", `${e.id}.mp4`)); for (const seg of segs) { if (!(await exists(seg))) @@ -4713,6 +4933,22 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly return { out: segments[0], failures }; } + // The montage's wall, from the clips just cut: one more segment, at the + // end (or the start) of the cut, named in the chapters like any entry. + 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 }); + EMIT("segment", { id: WALL_ENTRY.id, path: seg }); + if (at === "start") { + segments.unshift(seg); + entries.unshift({ ...WALL_ENTRY }); + } else { + segments.push(seg); + entries.push({ ...WALL_ENTRY }); + } + } + // A timeline that silently lost a clip is a worse outcome than no file at all: // the finished video would look complete and be missing a citation. So the // segments are kept (they cost the fetches) and the concat is refused. diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -20,8 +20,8 @@ // - a QR below MIN_QR_PX_PER_MODULE_720P pixels per module once the cut is // watched at 720p, or a link too long for a QR at all; // - everything the manifest validators say -- validateThreadEntries, -// validateFlipEntries and validateStatsEntries (threads.mjs, flips.mjs, -// stats.mjs), validateNarration +// validateFlipEntries, validateStatsEntries and validateMontage (threads.mjs, +// flips.mjs, stats.mjs, montage.mjs), validateNarration // (narration.mjs), validatePodcast (build-podcast.mjs), and the cut edits, teasers, claims and posts validators // a build runs first -- so `--lint` alone reports what a build would // refuse, all at once; @@ -84,6 +84,7 @@ import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; +import { validateMontage } from "./montage.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; @@ -228,6 +229,8 @@ export function validatorErrors(whole) { ...validateDrafted(whole), ...validatePublish(whole), // Release 31: the stats region's `stats` keys and render.chrome.stats. ...validateStatsEntries(whole), + // Release 33: render.montage, its keys and what it does not combine with. + ...validateMontage(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); diff --git a/umtool/report-to-video/montage-styles.mjs b/umtool/report-to-video/montage-styles.mjs @@ -0,0 +1,164 @@ +#!/usr/bin/env node +// THE NAMED MONTAGE STYLES — `render.montage` settings worth auditioning, by name. +// +// node umtool/report-to-video/montage-styles.mjs list [--json] +// node umtool/report-to-video/montage-styles.mjs apply <style> <manifest.json> [--out <file>] +// +// Each style is an RFC 7386 JSON merge patch on `video.manifest.json`. Every +// style sets EVERY `render.montage` key (a feature it does not use is `null` +// or `false`), so applying one style over another leaves exactly the second: +// a merge patch keeps any key it does not name, and a stale `stutter` from the +// last audition would otherwise ride along. Nothing else in the manifest is +// touched. +// +// The shared interface with umtool's take maker (release 33 M1), which reads it +// through a dynamic import and works without it: +// +// MONTAGE_STYLES: Record<string, { label: string, summary: string, patch: object }> +// montageStyle(name) -> a deep copy of one style, or null +// +// The keys themselves are `montage.mjs` (validateMontage says what each takes) +// and README "Manifest shape", `render.montage`. + +import { readFile, writeFile } from "node:fs/promises"; + +/** Every `render.montage` key, off: the base each style patches over. */ +const OFF = Object.freeze({ + tighten: null, + phrasePad: null, + cut: "hard", + flashColor: null, + counter: null, + punch: null, + stutter: null, + ramp: null, + wall: null, + yearStamp: false, +}); + +const chip = { style: "chip", position: "top-left", of: false, showDate: true, showSource: true }; + +const style = (label, summary, montage) => ({ + label, + summary, + patch: { render: { montage: { ...OFF, tighten: "phrase", ...montage } } }, +}); + +/** + * The styles, in the order a take form lists them. Labels and summaries are + * plain words: they are what a person reads when choosing one. + */ +export const MONTAGE_STYLES = Object.freeze({ + straight: style( + "Straight", + "Each clip cut to the phrase, hard cuts, a small running count with the date and the source.", + { counter: chip }, + ), + "flash-count": style( + "Flash and count", + "A white flash on every cut and a big number that slams in on each clip.", + { cut: "flash", counter: { style: "big", position: "bottom-left", of: false, showDate: true, showSource: false } }, + ), + accelerate: style( + "Accelerate", + "Clips get shorter toward the end, a slow zoom on each, tally marks adding up.", + { + ramp: { from: 4, to: 1.4 }, + punch: { mode: "drift", scale: 1.08, anchor: "upper" }, + counter: { style: "tally", position: "top-left", of: false, showDate: true, showSource: false }, + }, + ), + stutter: style( + "Stutter", + "Every fifth clip repeats the end of the phrase, and each clip punches in as the phrase starts.", + { + stutter: { every: 5, times: 3, length: 0.35, step: 0.04 }, + punch: { mode: "snap", scale: 1.15, anchor: "upper" }, + counter: chip, + }, + ), + "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 } }, + ), + "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 } }, + ), +}); + +/** The style names, in their listed order. */ +export const MONTAGE_STYLE_NAMES = Object.freeze(Object.keys(MONTAGE_STYLES)); + +/** One style, as a deep copy (a caller may change it freely), or null. */ +export function montageStyle(name) { + const s = Object.hasOwn(MONTAGE_STYLES, name) ? MONTAGE_STYLES[name] : null; + return s ? structuredClone(s) : null; +} + +const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** + * RFC 7386 JSON merge patch: `patch` applied to `target`, as a new value + * (neither argument is changed). An object patch merges key by key, `null` + * removes a key, and anything else replaces the target outright. + */ +export function mergePatch(target, patch) { + if (!isObject(patch)) return structuredClone(patch); + const out = isObject(target) ? structuredClone(target) : {}; + for (const [k, v] of Object.entries(patch)) { + if (v === null) delete out[k]; + else out[k] = mergePatch(out[k], v); + } + return out; +} + +/** A manifest with one named style applied. Throws, naming the styles, on an unknown name. */ +export function applyMontageStyle(manifest, name) { + const s = montageStyle(name); + if (!s) throw new Error(`no montage style "${name}" — the styles are ${MONTAGE_STYLE_NAMES.join(", ")}`); + return mergePatch(manifest, s.patch); +} + +async function main(argv) { + const [cmd, ...rest] = argv; + if (cmd === "list") { + if (rest.includes("--json")) { + process.stdout.write(`${JSON.stringify(MONTAGE_STYLES, null, 2)}\n`); + return 0; + } + for (const [name, s] of Object.entries(MONTAGE_STYLES)) process.stdout.write(`${name.padEnd(12)} ${s.label} — ${s.summary}\n`); + return 0; + } + if (cmd === "apply") { + const [name, manifestPath] = rest.filter((a, i) => !a.startsWith("--") && rest[i - 1] !== "--out"); + const oi = rest.indexOf("--out"); + const out = oi >= 0 ? rest[oi + 1] : null; + if (!name || !manifestPath) { + process.stderr.write("usage: montage-styles.mjs apply <style> <manifest.json> [--out <file>]\n"); + return 2; + } + const next = applyMontageStyle(JSON.parse(await readFile(manifestPath, "utf8")), name); + const text = `${JSON.stringify(next, null, 2)}\n`; + if (out) await writeFile(out, text, "utf8"); + else process.stdout.write(text); + return 0; + } + process.stderr.write( + "usage: montage-styles.mjs list [--json]\n" + + " montage-styles.mjs apply <style> <manifest.json> [--out <file>]\n", + ); + return 2; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main(process.argv.slice(2)).then( + (code) => process.exit(code), + (err) => { + process.stderr.write(`${err?.message ?? err}\n`); + process.exit(1); + }, + ); +} diff --git a/umtool/report-to-video/montage-styles.test.mjs b/umtool/report-to-video/montage-styles.test.mjs @@ -0,0 +1,123 @@ +// The named montage styles (release 33 M3): the shared interface with umtool's +// take maker -- names, plain-words labels, merge patches under render.montage, +// deep copies -- and RFC 7386 merge patching. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { applyMontageStyle, mergePatch, MONTAGE_STYLE_NAMES, MONTAGE_STYLES, montageStyle } from "./montage-styles.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +test("MONTAGE_STYLES: at least the six named styles, each a label, a summary and a patch under render.montage", () => { + for (const name of ["straight", "flash-count", "accelerate", "stutter", "wall-finale", "whip-years"]) { + assert.ok(MONTAGE_STYLES[name], name); + } + assert.ok(MONTAGE_STYLE_NAMES.length >= 6); + for (const [name, s] of Object.entries(MONTAGE_STYLES)) { + assert.equal(typeof s.label, "string", name); + assert.ok(s.label.length > 0 && s.label.length <= 40, name); + assert.ok(s.summary.length > 10 && !/[{}`]/.test(s.summary), `${name}: plain words`); + assert.deepEqual(Object.keys(s.patch), ["render"], name); + assert.deepEqual(Object.keys(s.patch.render), ["montage"], name); + assert.equal(s.patch.render.montage.tighten, "phrase", name); + } +}); + +test("every style names every montage key, so one style over another leaves exactly the second", () => { + const keys = (s) => Object.keys(s.patch.render.montage).sort(); + const first = keys(MONTAGE_STYLES.straight); + for (const s of Object.values(MONTAGE_STYLES)) assert.deepEqual(keys(s), first); + const base = { slug: "x", render: { fps: 30, montage: { stutter: { every: 2, times: 4 }, junkKeepsNothing: 1 } }, timeline: [] }; + for (const a of MONTAGE_STYLE_NAMES) { + for (const b of MONTAGE_STYLE_NAMES) { + assert.deepEqual( + applyMontageStyle(applyMontageStyle(base, a), b).render.montage, + { ...applyMontageStyle({ render: {} }, b).render.montage, junkKeepsNothing: 1 }, + `${a} then ${b}`, + ); + } + } +}); + +test("the styles say what the brief asks of each", () => { + const m = (n) => applyMontageStyle({}, n).render.montage; + assert.equal(m("straight").cut, "hard"); + assert.equal(m("straight").counter.style, "chip"); + assert.equal(m("flash-count").cut, "flash"); + assert.equal(m("flash-count").counter.style, "big"); + assert.deepEqual(m("accelerate").ramp, { from: 4, to: 1.4 }); + assert.equal(m("accelerate").punch.mode, "drift"); + assert.equal(m("accelerate").counter.style, "tally"); + assert.equal(m("stutter").stutter.every, 5); + assert.equal(m("stutter").punch.mode, "snap"); + assert.equal(m("wall-finale").wall.at, "end"); + assert.equal(m("wall-finale").wall.tiles, 16); + assert.equal(m("wall-finale").counter.style, "chip"); + assert.equal(m("whip-years").cut, "whip"); + assert.equal(m("whip-years").yearStamp, true); + assert.equal(m("whip-years").counter.style, "chip"); + // Off is absent (null removed the key) or false. + assert.equal("wall" in m("straight"), false); + assert.equal(m("straight").yearStamp, false); +}); + +test("montageStyle: a deep copy, or null", () => { + const a = montageStyle("straight"); + a.patch.render.montage.cut = "whip"; + a.label = "changed"; + assert.equal(MONTAGE_STYLES.straight.patch.render.montage.cut, "hard"); + assert.equal(MONTAGE_STYLES.straight.label, "Straight"); + assert.equal(montageStyle("nope"), null); + assert.equal(montageStyle("toString"), null, "not an inherited key"); + assert.throws(() => applyMontageStyle({}, "nope"), /no montage style "nope" — the styles are straight, /); +}); + +test("mergePatch: RFC 7386 -- objects merge, null removes, anything else replaces; inputs untouched", () => { + const target = { a: "b", c: { d: "e", f: "g" }, list: [1, 2] }; + const patch = { a: "z", c: { f: null, h: 1 }, list: [3], n: { deep: { x: 1 } } }; + assert.deepEqual(mergePatch(target, patch), { a: "z", c: { d: "e", h: 1 }, list: [3], n: { deep: { x: 1 } } }); + assert.deepEqual(target, { a: "b", c: { d: "e", f: "g" }, list: [1, 2] }); + // The RFC's own examples. + assert.deepEqual(mergePatch({ a: "b" }, { a: "c" }), { a: "c" }); + assert.deepEqual(mergePatch({ a: "b" }, { b: "c" }), { a: "b", b: "c" }); + assert.deepEqual(mergePatch({ a: "b" }, { a: null }), {}); + assert.deepEqual(mergePatch({ a: ["b"] }, { a: "c" }), { a: "c" }); + assert.deepEqual(mergePatch({ a: "c" }, { a: ["b"] }), { a: ["b"] }); + assert.deepEqual(mergePatch({ a: { b: "c" } }, { a: { b: "d", c: null } }), { a: { b: "d" } }); + assert.deepEqual(mergePatch(["a", "b"], ["c", "d"]), ["c", "d"]); + assert.deepEqual(mergePatch({ a: "b" }, ["c"]), ["c"]); + assert.equal(mergePatch({ a: "foo" }, null), null); + assert.deepEqual(mergePatch([1, 2], { a: "b", c: null }), { a: "b" }); +}); + +test("the CLI: list, and apply to a file", () => { + const list = spawnSync(process.execPath, [path.join(HERE, "montage-styles.mjs"), "list"]); + assert.equal(list.status, 0, String(list.stderr)); + assert.match(String(list.stdout), /^straight\s+Straight — /m); + const json = spawnSync(process.execPath, [path.join(HERE, "montage-styles.mjs"), "list", "--json"]); + assert.deepEqual(JSON.parse(String(json.stdout)), JSON.parse(JSON.stringify(MONTAGE_STYLES))); + const dir = mkdtempSync(path.join(tmpdir(), "montage-styles-")); + try { + const src = path.join(dir, "video.manifest.json"); + const out = path.join(dir, "styled.json"); + writeFileSync(src, JSON.stringify({ slug: "x", render: { fps: 30 }, timeline: [] })); + const r = spawnSync(process.execPath, [path.join(HERE, "montage-styles.mjs"), "apply", "flash-count", src, "--out", out]); + assert.equal(r.status, 0, String(r.stderr)); + const got = JSON.parse(readFileSync(out, "utf8")); + assert.equal(got.render.fps, 30); + assert.equal(got.render.montage.cut, "flash"); + assert.equal(JSON.parse(readFileSync(src, "utf8")).render.montage, undefined, "the source is untouched"); + const bad = spawnSync(process.execPath, [path.join(HERE, "montage-styles.mjs"), "apply", "nope", src]); + assert.equal(bad.status, 1); + assert.match(String(bad.stderr), /no montage style "nope"/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/montage.mjs b/umtool/report-to-video/montage.mjs @@ -0,0 +1,963 @@ +// MONTAGE EDITING — `render.montage` (release 33 M3). +// +// A montage is one phrase said many times: dozens of short clips, cut tight, +// run in order. Everything here is opt-in under `render.montage`; a manifest +// without it renders exactly as before (build-video.mjs never reaches this +// module's graph builders). +// +// WHERE EACH FEATURE LIVES. Every technique is made inside the clip's own +// segment encode, which the build pays for anyway: the tight cut moves the +// trim points, the punch-in, stutter and drift are the picture's pieces, the +// counter and the year stamp are drawtext/drawbox over the finished frame, +// and the cut styles (flash, whip, dip) are the first and last frames of +// each segment -- each segment knows whether it opens or closes the cut. So +// the concat stays the stream copy of hard cuts, no chrome layer is rendered, +// and a segment's length is known to the frame before it is encoded. The one +// composited pass is the wall: its own segment, made from small tiles. +// +// tighten "phrase" | "sentence" | null cut each clip to the phrase said ± phrasePad +// phrasePad seconds (0.6) kept either side of the phrase +// cut "hard" | "flash" | "whip" | "dip" +// flashColor "white" | "accent" | "#rrggbb" +// counter { style: chip|big|tally, position, of, showDate, showSource } | null +// punch { mode: snap|drift, scale, anchor: upper|center } | null +// stutter { every?, clips?, times: 2..4, length: 0.35, step: 0.04 } | null +// ramp { from, to } seconds -- clip k's cut <= lerp(from, to, k/(N-1)) +// wall { at: end|start, tiles: 9|16|25, build: seconds, year } | null +// yearStamp true: the year, large, over the first clip of each year +// +// Pure functions only, but for nothing: the build (build-video.mjs) runs the +// ffmpeg argv these return. README "Manifest shape", `render.montage`. + +import { deckOn } from "./deck.mjs"; +import { MONO_BOLD_FONT_FILE } from "./brand.mjs"; + +// ---- the settings ----------------------------------------------------------- + +export const MONTAGE_KEYS = Object.freeze([ + "tighten", "phrasePad", "cut", "flashColor", "counter", "punch", "stutter", "ramp", "wall", "yearStamp", +]); +export const TIGHTEN = Object.freeze(["phrase", "sentence"]); +export const CUTS = Object.freeze(["hard", "flash", "whip", "dip"]); +export const COUNTER_STYLES = Object.freeze(["chip", "big", "tally"]); +export const POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]); +export const PUNCH_MODES = Object.freeze(["snap", "drift"]); +export const ANCHORS = Object.freeze(["upper", "center"]); +export const WALL_TILES = Object.freeze([9, 16, 25]); +const COUNTER_KEYS = ["style", "position", "of", "showDate", "showSource"]; +const PUNCH_KEYS = ["mode", "scale", "anchor"]; +const STUTTER_KEYS = ["every", "clips", "times", "length", "step"]; +const RAMP_KEYS = ["from", "to"]; +const WALL_KEYS = ["at", "tiles", "build", "year"]; + +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 }, +}); + +/** The frames of each cut style (a whip's are each side of the cut). */ +export const CUT_FRAMES = Object.freeze({ flash: 3, whip: 4, dip: 2 }); +/** Each segment's sound starts and ends on a fade this long: no click at a hard cut. */ +export const DECLICK = 0.015; +/** A stutter's own pieces fade this much at each joint. */ +const JOINT_FADE = 0.005; + +/** Is `render.montage` on? (An object; null or absent is off.) */ +export const montageOn = (render) => + render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage); + +const isObj = (v) => v != null && typeof v === "object" && !Array.isArray(v); +const num = (v) => typeof v === "number" && Number.isFinite(v); + +/** + * `render.montage` with every default filled in, or null when it is off. + * Assumes validateMontage passed; `palette` resolves an accent flash. + */ +export function resolveMontage(render) { + if (!montageOn(render)) return null; + const m = render.montage; + const pal = render.palette ?? {}; + const flash = m.flashColor == null || m.flashColor === "white" ? "#ffffff" : m.flashColor === "accent" ? pal.accent ?? "#ffffff" : m.flashColor; + const counter = isObj(m.counter) + ? { + style: m.counter.style ?? "chip", + position: m.counter.position ?? "top-left", + of: m.counter.of === true, + showDate: m.counter.showDate !== false, + showSource: m.counter.showSource === true, + } + : null; + const punch = isObj(m.punch) + ? { + mode: m.punch.mode, + scale: m.punch.scale ?? MONTAGE_DEFAULTS.punchScale[m.punch.mode], + anchor: m.punch.anchor ?? "upper", + } + : null; + const stutter = isObj(m.stutter) + ? { + every: m.stutter.every ?? null, + clips: Array.isArray(m.stutter.clips) ? [...m.stutter.clips] : [], + times: m.stutter.times ?? MONTAGE_DEFAULTS.stutter.times, + length: m.stutter.length ?? MONTAGE_DEFAULTS.stutter.length, + step: m.stutter.step ?? MONTAGE_DEFAULTS.stutter.step, + } + : null; + const wall = isObj(m.wall) ? { ...MONTAGE_DEFAULTS.wall, ...pick(m.wall, WALL_KEYS) } : null; + return { + tighten: m.tighten ?? null, + phrasePad: m.phrasePad ?? MONTAGE_DEFAULTS.phrasePad, + cut: m.cut ?? "hard", + flashColor: flash, + counter, + punch, + stutter, + ramp: isObj(m.ramp) ? { from: m.ramp.from, to: m.ramp.to } : null, + wall: wall ? { ...wall, year: wall.year === true } : null, + yearStamp: m.yearStamp === true, + }; +} + +function pick(o, keys) { + const out = {}; + for (const k of keys) if (o[k] !== undefined && o[k] !== null) out[k] = o[k]; + return out; +} + +function unknownKeys(obj, keys, where) { + return Object.keys(obj) + .filter((k) => !keys.includes(k)) + .map((k) => `${where}.${k} is not a setting here (the settings are ${keys.join(", ")})`); +} + +const oneOf = (v, list, where) => + list.includes(v) ? [] : [`${where} must be ${list.map((x) => JSON.stringify(x)).join(" or ")}, not ${JSON.stringify(v)}`]; + +const inRange = (v, lo, hi, where, unit = "") => + num(v) && v >= lo && v <= hi ? [] : [`${where} must be a number from ${lo} to ${hi}${unit}, not ${JSON.stringify(v)}`]; + +const bool = (v, where) => (v === undefined || v === null || typeof v === "boolean" ? [] : [`${where} must be true or false, not ${JSON.stringify(v)}`]); + +/** + * What is wrong with a manifest's `render.montage`, as sentences that say so. + * Nothing when it is absent or null. Unknown keys and bad values are errors; + * so is a montage beside what it does not combine with (the deck, the rail, + * the chart band, a clip's `muteFrom`). + */ +export function validateMontage(manifest) { + const render = manifest?.render ?? {}; + const m = render.montage; + if (m === undefined || m === null) return []; + if (!isObj(m)) return [`render.montage must be an object of montage settings, not ${JSON.stringify(m)}`]; + const errors = [...unknownKeys(m, MONTAGE_KEYS, "render.montage")]; + const W = "render.montage"; + if (m.tighten != null) errors.push(...oneOf(m.tighten, TIGHTEN, `${W}.tighten`)); + if (m.phrasePad != null) errors.push(...inRange(m.phrasePad, 0, 5, `${W}.phrasePad`, " seconds")); + if (m.cut != null) errors.push(...oneOf(m.cut, CUTS, `${W}.cut`)); + if (m.flashColor != null && m.flashColor !== "white" && m.flashColor !== "accent" && !/^#[0-9a-fA-F]{6}$/.test(String(m.flashColor))) { + errors.push(`${W}.flashColor must be "white", "accent" or a #rrggbb colour, not ${JSON.stringify(m.flashColor)}`); + } + if (m.counter != null) { + if (!isObj(m.counter)) errors.push(`${W}.counter must be an object ({ style, position, of, showDate, showSource }) or null`); + else { + errors.push(...unknownKeys(m.counter, COUNTER_KEYS, `${W}.counter`)); + if (m.counter.style != null) errors.push(...oneOf(m.counter.style, COUNTER_STYLES, `${W}.counter.style`)); + if (m.counter.position != null) errors.push(...oneOf(m.counter.position, POSITIONS, `${W}.counter.position`)); + for (const k of ["of", "showDate", "showSource"]) errors.push(...bool(m.counter[k], `${W}.counter.${k}`)); + } + } + if (m.punch != null) { + if (!isObj(m.punch)) errors.push(`${W}.punch must be an object ({ mode, scale, anchor }) or null`); + else { + errors.push(...unknownKeys(m.punch, PUNCH_KEYS, `${W}.punch`)); + errors.push(...oneOf(m.punch.mode, PUNCH_MODES, `${W}.punch.mode`)); + if (m.punch.scale != null) errors.push(...inRange(m.punch.scale, 1, 2, `${W}.punch.scale`, " (1 is no zoom)")); + if (m.punch.anchor != null) errors.push(...oneOf(m.punch.anchor, ANCHORS, `${W}.punch.anchor`)); + } + } + if (m.stutter != null) { + if (!isObj(m.stutter)) errors.push(`${W}.stutter must be an object ({ every, clips, times, length, step }) or null`); + else { + const s = m.stutter; + errors.push(...unknownKeys(s, STUTTER_KEYS, `${W}.stutter`)); + if (s.every == null && s.clips == null) errors.push(`${W}.stutter needs \`every\` (every Nth clip) or \`clips\` (their ids)`); + if (s.every != null && !(Number.isInteger(s.every) && s.every >= 1)) { + errors.push(`${W}.stutter.every must be a whole number from 1 (every clip), not ${JSON.stringify(s.every)}`); + } + if (s.clips != null) { + if (!Array.isArray(s.clips) || !s.clips.every((c) => typeof c === "string" && c)) { + errors.push(`${W}.stutter.clips must be a list of clip ids`); + } else { + const clipIds = new Set((manifest.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id)); + for (const id of s.clips) if (!clipIds.has(id)) errors.push(`${W}.stutter.clips names "${id}", which is not a clip in the timeline`); + } + } + if (s.times != null && !(Number.isInteger(s.times) && s.times >= 2 && s.times <= 4)) { + errors.push(`${W}.stutter.times must be 2, 3 or 4 (how many times the end of the phrase is heard), not ${JSON.stringify(s.times)}`); + } + if (s.length != null) errors.push(...inRange(s.length, 0.1, 1, `${W}.stutter.length`, " seconds")); + if (s.step != null) errors.push(...inRange(s.step, 0, 0.2, `${W}.stutter.step`, " (the zoom added per repeat)")); + } + } + if (m.ramp != null) { + if (!isObj(m.ramp)) errors.push(`${W}.ramp must be an object ({ from, to } in seconds) or null`); + else { + errors.push(...unknownKeys(m.ramp, RAMP_KEYS, `${W}.ramp`)); + errors.push(...inRange(m.ramp.from, 0.5, 60, `${W}.ramp.from`, " seconds")); + errors.push(...inRange(m.ramp.to, 0.5, 60, `${W}.ramp.to`, " seconds")); + if (m.tighten !== "phrase") errors.push(`${W}.ramp trims around the phrase, so it needs ${W}.tighten "phrase"`); + } + } + if (m.wall != null) { + if (!isObj(m.wall)) errors.push(`${W}.wall must be an object ({ at, tiles, build, year }) or null`); + else { + errors.push(...unknownKeys(m.wall, WALL_KEYS, `${W}.wall`)); + if (m.wall.at != null) errors.push(...oneOf(m.wall.at, ["end", "start"], `${W}.wall.at`)); + if (m.wall.tiles != null) errors.push(...oneOf(m.wall.tiles, WALL_TILES, `${W}.wall.tiles`)); + if (m.wall.build != null) errors.push(...inRange(m.wall.build, 1, 60, `${W}.wall.build`, " seconds")); + errors.push(...bool(m.wall.year, `${W}.wall.year`)); + } + } + errors.push(...bool(m.yearStamp, `${W}.yearStamp`)); + // What a montage does not combine with. + if (deckOn(render)) errors.push(`${W} does not combine with render.chrome (the deck): drop one of them`); + if (render.rail) errors.push(`${W} does not combine with render.rail: drop one of them`); + if (render.chromeEngine === "hyperframes") errors.push(`${W} does not combine with render.chromeEngine "hyperframes"`); + (manifest.timeline ?? []).forEach((e, i) => { + if (e?.type === "clip" && e.muteFrom != null) { + errors.push(`timeline[${i}] (${e.id}).muteFrom is not supported under ${W}: cut the clip shorter instead`); + } + }); + return errors; +} + +// ---- dates, sources, the counter's words ------------------------------------ + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** "20190502", "2019-05-02" (or a longer ISO stamp) → {y, m, d}; anything else → null. */ +export function parseClipDate(v) { + const s = String(v ?? "").trim(); + const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(s); + if (!m) return null; + const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]; + if (mo < 1 || mo > 12 || d < 1 || d > 31) return null; + return { y, m: mo, d }; +} + +/** {y, m, d} → "2 May 2019". */ +export const formatClipDate = (dt) => (dt ? `${dt.d} ${MONTHS[dt.m - 1]} ${dt.y}` : ""); + +const PLATFORMS = { + youtube: "YouTube", rumble: "Rumble", twitch: "Twitch", kick: "Kick", odysee: "Odysee", x: "X", twitter: "X", + bitchute: "BitChute", "archive.org": "archive.org", archiveorg: "archive.org", internetarchive: "archive.org", + podcast: "Podcast", tiktok: "TikTok", instagram: "Instagram", facebook: "Facebook", bluesky: "Bluesky", +}; + +/** A platform id as people write it: "youtube" → "YouTube"; unknown → itself, capitalised. */ +export function platformLabel(p) { + const s = String(p ?? "").trim(); + if (!s) return ""; + return PLATFORMS[s.toLowerCase()] ?? s[0].toUpperCase() + s.slice(1); +} + +/** + * Text safe to put in a drawtext `text='…'`: letters, digits, spaces and + * `# · . / -` only, so nothing needs escaping through two parsers. + */ +export const safeText = (s) => String(s ?? "").replace(/[^\p{L}\p{N} #·./-]/gu, "").replace(/\s+/g, " ").trim(); + +/** + * The counter's words for one clip: `number` ("#12", "#12 of 75") and `line` + * (the date and the source the counter shows, joined), each already safeText. + */ +export function counterText({ n, of = null, date = null, platform = null, showDate = true, showSource = false }) { + const number = `#${n}${of ? ` of ${of}` : ""}`; + const line = [showDate ? formatClipDate(date) : "", showSource ? platformLabel(platform) : ""].filter(Boolean).join(" · "); + return { number: safeText(number), line: safeText(line) }; +} + +// ---- where the phrase is said ------------------------------------------------- + +const normChar = (ch) => (/[\p{L}\p{N}]/u.test(ch) ? ch.toLowerCase() : ch === "'" || ch === "’" ? "" : " "); + +/** A phrase as it is matched: lower case, letters and digits, single spaces. */ +export const normalisePhrase = (p) => [...String(p ?? "")].map(normChar).join("").replace(/\s+/g, " ").trim(); + +/** + * Timed text: the spans' words (cues, or whisper's words) joined, each kept + * character carrying the seconds it is spoken -- a span's characters spread + * evenly over the span, so a long word takes longer than a short one. + * + * @param {Array<{start: number, end: number, text: string}>} spans sorted by start + * @returns {{ text: string, t0: number[], t1: number[] }} + */ +export function timedText(spans) { + let text = ""; + const t0 = []; + const t1 = []; + const push = (c, a, b) => { + if (c === " " && (text === "" || text.endsWith(" "))) return; + text += c; + t0.push(a); + t1.push(b); + }; + for (const s of spans) { + const chars = [...String(s.text ?? "")]; + const L = chars.length; + const dur = Math.max(0, s.end - s.start); + chars.forEach((ch, i) => { + const c = normChar(ch); + if (c) push(c, s.start + (dur * i) / L, s.start + (dur * (i + 1)) / L); + }); + push(" ", s.end, s.end); + } + return { text, t0, t1 }; +} + +/** + * Where a phrase is said: its first character's start and its last + * character's end, in the spans' seconds -- the occurrence that overlaps + * [from, to] nearest `near` (whole words first, then a phrase that runs on + * into a longer word: "slow news days"). Null when it is not there. + */ +export function locatePhrase(phrase, spans, { from = -Infinity, to = Infinity, near = null } = {}) { + const needle = normalisePhrase(phrase); + if (!needle) return null; + const used = (spans ?? []) + .filter((s) => num(s?.start) && num(s?.end) && s.end >= from - 0.5 && s.start <= to + 0.5) + .sort((a, b) => a.start - b.start); + if (!used.length) return null; + const tt = timedText(used); + const at = num(near) ? near : (Math.max(from, used[0].start) + Math.min(to, used[used.length - 1].end)) / 2; + for (const tail of [true, false]) { + let best = null; + for (let i = tt.text.indexOf(needle); i >= 0; i = tt.text.indexOf(needle, i + 1)) { + const before = i === 0 || tt.text[i - 1] === " "; + const j = i + needle.length; + const after = j >= tt.text.length || tt.text[j] === " "; + if (!before || (tail && !after)) continue; + const start = tt.t0[i]; + const end = tt.t1[j - 1]; + if (end < from || start > to) continue; + const d = Math.abs((start + end) / 2 - at); + if (!best || d < best.d) best = { d, start, end }; + } + if (best) return { start: best.start, end: best.end }; + } + return null; +} + +/** + * whisper.cpp's full JSON (`transcription[].tokens[].offsets`, in ms) as + * words: a token that starts with a space starts a word, any other continues + * the one before; special tokens (`[_BEG_]`, …) are skipped. Only the words in + * [from − 2, to + 2]. Null when the document carries no token offsets (a + * parakeet `chunk_data`, a cue file). + */ +export function whisperWords(doc, from = -Infinity, to = Infinity) { + if (!Array.isArray(doc?.transcription)) return null; + const words = []; + let any = false; + for (const seg of doc.transcription) { + let open = false; + for (const tok of seg?.tokens ?? []) { + const text = String(tok?.text ?? ""); + const off = tok?.offsets; + if (!text || /^\s*\[_/.test(text) || !off || !num(off.from) || !num(off.to)) continue; + any = true; + const s = off.from / 1000; + const e = off.to / 1000; + if (e < from - 2 || s > to + 2) { + open = false; + continue; + } + if (!open || /^\s/.test(text)) { + words.push({ start: s, end: e, text: text.trim() }); + open = true; + } else { + const w = words[words.length - 1]; + w.text += text; + w.end = Math.max(w.end, e); + } + } + } + return any && words.length ? words : null; +} + +/** The phrase a clip says: its `montage.match`, else its on-screen title. */ +export const clipPhrase = (entry) => { + const p = entry?.montage?.match ?? entry?.onscreen?.title ?? null; + return typeof p === "string" && p.trim() ? p : null; +}; + +// ---- the plan across the cut ---------------------------------------------------- + +/** The ramp's cap for clip k of n: lerp(from, to, k/(n−1)), the first `from`, the last `to`. */ +export function rampCap(k, n, ramp) { + if (!ramp) return null; + const f = n > 1 ? k / (n - 1) : 0; + return ramp.from + (ramp.to - ramp.from) * f; +} + +/** Every clip's cap under a ramp, in order. */ +export const rampCaps = (n, ramp) => Array.from({ length: n }, (_, k) => rampCap(k, n, ramp)); + +/** Is clip k (0-based, id `id`) stuttered? Every Nth counts from the Nth clip. */ +export const stutters = (stutter, k, id) => + !!stutter && ((stutter.every != null && (k + 1) % stutter.every === 0) || stutter.clips.includes(id)); + +/** + * The per-clip facts a montage needs from the whole cut, by clip id: k (its + * place among the clips), n (how many), its cap under the ramp, whether it + * stutters, its date and year, whether its year differs from the clip + * before's, its source, and whether its segment opens or closes the cut + * (`first`/`last`: a cut style has nothing to cut from or to there; a wall + * at that end takes the edge). + * + * @param {object[]} timeline the cut's timeline (every entry, in order) + * @param {object} settings resolveMontage's + * @param {(entry) => string|null} [dateOf] a clip's date when its own fields carry none + */ +export function planMontage(timeline, settings, dateOf = () => null) { + const clips = timeline.filter((e) => e?.type === "clip"); + const n = clips.length; + const out = new Map(); + 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); + out.set(e.id, { + k, n, + cap: rampCap(k, n, settings.ramp), + stutter: stutters(settings.stutter, k, 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"), + }); + if (year != null) prevYear = year; + }); + return out; +} + +// ---- one clip's cut ------------------------------------------------------------------- + +/** + * Where a montage clip is cut, on the fetched file's clock. + * + * `tighten: "phrase"` with a located phrase: the phrase ± `pad`, inside the + * extent; under a ramp, the pads are trimmed (evenly, then whatever one side + * lacks from the other) until the cut is no longer than `cap`, never into the + * phrase. Then each edge snaps to the nearest silence within `snapWindow` + * (build-video's own `snap`), kept only when it stays outside the phrase, + * inside the extent and under the cap. Otherwise -- "sentence", null, or no + * phrase found -- today's cut: the play window, snapped as every clip is. + * + * @param {{ extent: [number, number], play: [number, number], phrase: {start: number, end: number}|null, + * tighten: string|null, pad: number, cap: number|null, silences: Array<{s: number, e: number}>, + * snapWindow: number, render: object, snap: Function }} o + * @returns {{ cutA: number, cutB: number, start: {at: number, snapped: boolean}, end: {at: number, snapped: boolean}, tight: boolean }} + */ +export function montageWindow({ extent, play, phrase, tighten, pad, cap, silences, snapWindow, render, snap }) { + const [e0, e1] = extent; + const usable = phrase && phrase.end > e0 && phrase.start < e1 && phrase.end > phrase.start; + if (tighten !== "phrase" || !usable) { + const [w0, w1] = play; + const a = snap(w0, silences, "start", snapWindow, render); + const b = snap(w1, silences, "end", snapWindow, render); + const cutA = Math.min(a.at, w1 - 1); + const cutB = Math.max(b.at, cutA + 1); + return { cutA, cutB, start: a, end: b, tight: false }; + } + const p0 = Math.max(e0, phrase.start); + const p1 = Math.min(e1, phrase.end); + let w0 = Math.max(e0, p0 - pad); + let w1 = Math.min(e1, p1 + pad); + if (num(cap) && w1 - w0 > cap) { + const room = Math.max(0, cap - (p1 - p0)); + let before = Math.min(p0 - w0, room / 2); + const after = Math.min(w1 - p1, room - before); + before = Math.min(p0 - w0, room - after); + w0 = p0 - before; + w1 = p1 + after; + } + const limit = num(cap) ? Math.max(cap, w1 - w0) + 1e-6 : Infinity; + const s = snap(w0, silences, "start", snapWindow, render); + const start = s.snapped && s.at >= e0 - 1e-6 && s.at <= p0 - 0.04 && w1 - s.at <= limit ? s : { at: w0, snapped: false }; + const t = snap(w1, silences, "end", snapWindow, render); + const end = t.snapped && t.at <= e1 + 1e-6 && t.at >= p1 + 0.04 && t.at - start.at <= limit ? t : { at: w1, snapped: false }; + let cutB = end.at; + if (cutB - start.at < 0.5) cutB = Math.min(e1, start.at + 0.5); + return { cutA: start.at, cutB, start, end, tight: true }; +} + +/** + * The segment's picture as pieces of the cut, in FRAMES of the cut's own + * clock (frame 0 is the cut's start): `[{ f0, f1, zoom }]`, played in order. + * + * - a snap punch-in changes the zoom at the phrase's onset (`onset`); + * - a stutter plays the phrase's last `length` seconds `times` times in all + * ("…news day-day-day"), each repeat `step` more zoomed than the one before. + * + * @param {{ frames: number, fps: number, onset: number|null, phraseEnd: number|null, + * punch: object|null, stutter: object|null }} o onset/phraseEnd in seconds of the cut + */ +export function montagePieces({ frames, fps, onset = null, phraseEnd = null, punch = null, stutter = null }) { + const NF = Math.max(1, frames); + const fr = (s) => Math.max(0, Math.min(NF, Math.round(s * fps))); + const snapAt = punch?.mode === "snap" && num(onset) ? fr(onset) : null; + const zoomAt = (f) => (snapAt != null && f >= snapAt ? punch.scale : 1); + let s0 = null; + let s1 = null; + if (stutter && num(phraseEnd)) { + s1 = fr(phraseEnd); + s0 = Math.max(0, s1 - Math.round(stutter.length * fps)); + if (s1 - s0 < 3) s0 = s1 = null; + } + const marks = [...new Set([0, NF, ...(snapAt != null && snapAt > 0 && snapAt < NF ? [snapAt] : []), ...(s0 != null ? [s0, s1] : [])])] + .sort((a, b) => a - b); + const pieces = []; + for (let i = 0; i + 1 < marks.length; i += 1) { + const f0 = marks[i]; + const f1 = marks[i + 1]; + if (f1 <= f0) continue; + pieces.push({ f0, f1, zoom: zoomAt(f0) }); + if (s1 != null && f1 === s1) { + const z = zoomAt(s1 - 1); + for (let r = 1; r < stutter.times; r += 1) { + pieces.push({ f0: s0, f1: s1, zoom: Number((z * (1 + stutter.step * r)).toFixed(4)), repeat: r }); + } + } + } + return pieces; +} + +/** The pieces' length in frames. */ +export const piecesFrames = (pieces) => pieces.reduce((n, p) => n + (p.f1 - p.f0), 0); + +// ---- the filtergraph of one montage segment ----------------------------------------- + +const exprNum = (v) => String(Number(v.toFixed(4))); + +/** A crop to 1/zoom of the picture, centred across, at the anchor's height. */ +const zoomCrop = (zoom, anchor) => + `crop=w='floor(iw/${zoom}/2)*2':h='floor(ih/${zoom}/2)*2':x='(iw-ow)/2':y='(ih-oh)*${anchor === "center" ? 0.5 : 0.35}'`; + +/** + * The pieces as a graph: from the cut's raw picture and sound to the + * segment's picture, fitted to `box` (letterboxed in `bg`), and its sound, + * exactly `frames` long. A drift punch-in zooms the whole thing, 1 → scale. + * Each joint of a stutter fades 5 ms; the segment's own edges fade + * DECLICK, always. + * + * @returns {{ parts: string[], v: string, a: string, frames: number, seconds: number }} + */ +export function montagePiecesGraph({ pieces, fps, box, bg, punch = null, inV = "[0:v]", inA = "[0:a]", hasVideo = true }) { + const frames = piecesFrames(pieces); + const seconds = frames / fps; + const parts = []; + const anchor = punch?.anchor ?? "upper"; + const fit = `scale=${box.w}:${box.h}:force_original_aspect_ratio=decrease,pad=${box.w}:${box.h}:(ow-iw)/2:(oh-ih)/2:color=${bg},setsar=1`; + const P = pieces.length; + const vLabels = []; + const aLabels = []; + if (hasVideo) { + if (P === 1) parts.push(`${inV}fps=${fps}[mvs0]`); + else parts.push(`${inV}fps=${fps},split=${P}${pieces.map((_, i) => `[mvs${i}]`).join("")}`); + } + parts.push(P === 1 ? `${inA}anull[mas0]` : `${inA}asplit=${P}${pieces.map((_, i) => `[mas${i}]`).join("")}`); + pieces.forEach((p, i) => { + if (hasVideo) { + const z = p.zoom !== 1 ? `,${zoomCrop(p.zoom, anchor)}` : ""; + parts.push(`[mvs${i}]trim=start_frame=${p.f0}:end_frame=${p.f1},setpts=PTS-STARTPTS${z},${fit}[mv${i}]`); + vLabels.push(`[mv${i}]`); + } + const a0 = p.f0 / fps; + const a1 = p.f1 / fps; + const len = a1 - a0; + const joint = P > 1 && len > 4 * JOINT_FADE + ? `,afade=t=in:d=${JOINT_FADE},afade=t=out:st=${exprNum(len - JOINT_FADE)}:d=${JOINT_FADE}` + : ""; + parts.push(`[mas${i}]atrim=start=${exprNum(a0)}:end=${exprNum(a1)},asetpts=PTS-STARTPTS${joint}[ma${i}]`); + aLabels.push(`[ma${i}]`); + }); + if (hasVideo) { + if (P === 1) parts.push(`${vLabels[0]}null[mvc]`, `${aLabels[0]}anull[mac]`); + else parts.push(`${pieces.map((_, i) => `${vLabels[i]}${aLabels[i]}`).join("")}concat=n=${P}:v=1:a=1[mvc][mac]`); + } else { + parts.push(P === 1 ? `${aLabels[0]}anull[mac]` : `${aLabels.join("")}concat=n=${P}:v=0:a=1[mac]`); + } + if (hasVideo) { + // Never a frame more or less than the plan: a short source is held on its + // last frame, a long one cut. + const exact = `tpad=stop_mode=clone:stop_duration=1,trim=end_frame=${frames},setpts=PTS-STARTPTS`; + if (punch?.mode === "drift") { + const ay = anchor === "center" ? 0.5 : 0.35; + parts.push( + `[mvc]${exact},scale=${box.w * 2}:${box.h * 2},` + + `zoompan=z='1+${exprNum(punch.scale - 1)}*on/${Math.max(1, frames - 1)}':x='iw/2-iw/zoom/2':y='(ih-ih/zoom)*${ay}':d=1:s=${box.w}x${box.h}:fps=${fps},setsar=1[mv]`, + ); + } else { + parts.push(`[mvc]${exact}[mv]`); + } + } + const D = exprNum(seconds); + const declick = seconds > 4 * DECLICK + ? `,afade=t=in:d=${DECLICK},afade=t=out:st=${exprNum(seconds - DECLICK)}:d=${DECLICK}` + : ""; + parts.push(`[mac]apad=whole_dur=${D},atrim=end=${D}${declick}[ma]`); + return { parts, v: hasVideo ? "[mv]" : null, a: "[ma]", frames, seconds }; +} + +/** + * The cut style, on one segment's finished picture: its first frames (unless + * it opens the cut) and its last (unless it closes it). Flash: the first + * CUT_FRAMES.flash frames fade from the flash colour. Dip: the last two fade + * to black, the first two up from it. Whip: the last four slide out to the + * left and the first four in from the right, wrapped and blurred along the + * move. Hard: nothing. + * + * @returns {string[]} parts from `inLabel` to `outLabel` + */ +export function cutStyleParts({ cut, first, last, frames, fps, w, h, flashColor = "#ffffff", inLabel, outLabel }) { + const f = (n) => exprNum(n / fps); + if (cut === "flash" && !first && frames > CUT_FRAMES.flash) { + return [`${inLabel}fade=t=in:st=0:d=${f(CUT_FRAMES.flash)}:color=${flashColor}${outLabel}`]; + } + if (cut === "dip") { + const n = CUT_FRAMES.dip; + const chain = []; + if (!first && frames > n) chain.push(`fade=t=in:st=0:d=${f(n)}`); + if (!last && frames > 2 * n + 1) chain.push(`fade=t=out:st=${f(frames - n - 1)}:d=${f(n)}`); + if (chain.length) return [`${inLabel}${chain.join(",")}${outLabel}`]; + } + if (cut === "whip") { + const n = CUT_FRAMES.whip; + const head = !first; + const tail = !last; + if ((head || tail) && frames > 2 * n + 1) { + // The picture beside a copy of itself, cropped at x: shifted left by x, + // wrapped -- under the blur, a whip pan. `n` inside the quotes is crop's + // own frame number. + const blur = `avgblur=sizeX=${Math.max(2, Math.round(w * 0.035))}:sizeY=1`; + const slide = (x) => `hstack,crop=w=${w}:h=${h}:x='${x}':y=0,${blur}`; + const parts = []; + const segs = []; + const take = [head ? "[wph]" : null, "[wpb]", tail ? "[wpt]" : null].filter(Boolean); + parts.push(`${inLabel}split=${take.length}${take.join("")}`); + if (head) { + // In from the right: shifted right by d·w, d easing 0.58 → 0.04. + parts.push( + `[wph]trim=end_frame=${n},setpts=PTS-STARTPTS,split[wh1][wh2]`, + `[wh1][wh2]${slide(`${w}*(1-0.9*pow(1-(n+1)/${n + 1},2))`)}[wh]`, + ); + segs.push("[wh]"); + } + parts.push(`[wpb]trim=start_frame=${head ? n : 0}:end_frame=${tail ? frames - n : frames},setpts=PTS-STARTPTS[wb]`); + segs.push("[wb]"); + if (tail) { + // Out to the left: shifted left by d·w, d easing 0.04 → 0.58. + parts.push( + `[wpt]trim=start_frame=${frames - n},setpts=PTS-STARTPTS,split[wt1][wt2]`, + `[wt1][wt2]${slide(`${w}*0.9*pow((n+1)/${n + 1},2)`)}[wt]`, + ); + segs.push("[wt]"); + } + parts.push(`${segs.join("")}concat=n=${segs.length}:v=1:a=0${outLabel}`); + return parts; + } + } + return [`${inLabel}null${outLabel}`]; +} + +/** Where a corner overlay sits: drawtext/drawbox x and y for a block w×h, `m` from the edges. */ +function corner(position, m) { + const right = position.endsWith("right"); + const bottom = position.startsWith("bottom"); + return { + right, bottom, + x: (w) => (right ? `W-${m}-${w}` : String(m)), + y: (h) => (bottom ? `H-${m}-${h}` : String(m)), + }; +} + +/** + * Tally marks for a count: groups of five, four uprights struck through by + * the fifth, ten groups a row. Boxes relative to the tally's top-left, and + * its bounds; the LAST box is the newest mark. + * + * @returns {{ marks: Array<{x: number, y: number, w: number, h: number, strike: boolean}>, width: number, height: number }} + */ +export function tallyMarks(count, H) { + const mw = Math.max(2, Math.round(H * 0.0055)); + const mh = Math.round(H * 0.05); + const gap = Math.round(H * 0.012); + const groupGap = Math.round(H * 0.026); + const rowGap = Math.round(H * 0.022); + const gw = 4 * mw + 3 * gap; + const perRow = 10; + const over = Math.round(gap * 0.7); + const marks = []; + for (let i = 0; i < count; i += 1) { + const g = Math.floor(i / 5); + const r = i % 5; + const gx = over + (g % perRow) * (gw + groupGap); + const gy = Math.floor(g / perRow) * (mh + rowGap); + if (r < 4) marks.push({ x: gx + r * (mw + gap), y: gy, w: mw, h: mh, strike: false }); + else marks.push({ x: gx - over, y: gy + Math.round(mh * 0.45), w: gw + 2 * over, h: mw, strike: true }); + } + const groups = Math.ceil(count / 5); + const cols = Math.min(perRow, Math.max(1, groups)); + const rows = Math.max(1, Math.ceil(groups / perRow)); + return { marks, width: 2 * over + cols * gw + (cols - 1) * groupGap, height: rows * mh + (rows - 1) * rowGap }; +} + +/** + * The counter and the year stamp over one segment's finished picture: drawtext + * and drawbox only, timed on the segment's own clock. + * + * - chip: "#12 · 2 May 2019 · YouTube" on a translucent ground, the whole clip; + * - big: the number, large, slamming in (1.9× → 1× over 0.18 s), held, gone by + * 1.5 s, with the date line under it; + * - tally: the marks so far, the newest landing at 0.12 s in the accent; + * - the year stamp: the year, large, in the corner across from the counter, + * for about a second, on a clip whose year differs from the one before. + * + * @returns {string[]} filters, to join with "," (empty: nothing to draw) + */ +export function montageOverlayFilters({ settings, ctx, render, font }) { + const { width: W, height: H } = render; + const pal = render.palette ?? {}; + const fg = pal.fg ?? "#ffffff"; + const bg = pal.bg ?? "#000000"; + const accent = pal.accent ?? fg; + const m = Math.round(H * 0.035); + const out = []; + const dt = (o) => ["drawtext=" + `fontfile='${font}'`, "expansion=none", ...Object.entries(o).map(([k, v]) => `${k}=${v}`)].join(":"); + const c = settings.counter; + if (c) { + const words = counterText({ + n: ctx.k + 1, of: c.of ? ctx.n : null, date: ctx.date, platform: ctx.platform, + showDate: c.showDate, showSource: c.showSource, + }); + const at = corner(c.position, m); + if (c.style === "chip") { + const fs = Math.round(H * 0.034); + const text = [words.number, words.line].filter(Boolean).join(" · "); + const pad = Math.round(fs * 0.45); + // The ground reaches `pad` past the text on every side; the ground is `m` from the edges. + out.push(dt({ + text: `'${text}'`, fontsize: fs, fontcolor: fg, box: 1, boxcolor: `${bg}@0.72`, boxborderw: pad, + x: at.right ? `W-${m + pad}-text_w` : String(m + pad), + y: at.bottom ? `H-${m + pad}-text_h` : String(m + pad), + })); + } else if (c.style === "big") { + const fs = Math.round(H * 0.24); + const small = Math.round(H * 0.036); + const alpha = `'min(1,t/0.04)*if(lt(t,1.2),1,max(0,1-(t-1.2)/0.3))'`; + const lineH = words.line ? Math.round(small * 1.5) : 0; + out.push(dt({ + text: `'${words.number.replace(/^#/, "")}'`, fontsize: `'${fs}*(1+0.9*max(0,1-t/0.18))'`, fontcolor: accent, + borderw: Math.max(2, Math.round(fs * 0.025)), bordercolor: bg, alpha, + x: at.x("text_w"), y: at.bottom ? `H-${m + lineH}-text_h` : String(m), + })); + if (words.line) { + out.push(dt({ + text: `'${words.line}'`, fontsize: small, fontcolor: fg, borderw: 2, bordercolor: bg, alpha, + x: at.x("text_w"), y: at.bottom ? `H-${m}-text_h` : String(m + Math.round(fs * 1.05)), + })); + } + } else if (c.style === "tally") { + const t = tallyMarks(ctx.k + 1, H); + const pad = Math.round(H * 0.012); + const small = Math.round(H * 0.03); + const lineH = words.line ? Math.round(small * 1.6) : 0; + const bw = t.width + 2 * pad; + const bh = t.height + 2 * pad + lineH; + const x0 = at.right ? W - m - bw : m; + const y0 = at.bottom ? H - m - bh : m; + out.push(`drawbox=x=${x0}:y=${y0}:w=${bw}:h=${bh}:color=${bg}@0.6:t=fill`); + t.marks.forEach((mk, i) => { + const newest = i === t.marks.length - 1; + out.push( + `drawbox=x=${x0 + pad + mk.x}:y=${y0 + pad + mk.y}:w=${mk.w}:h=${mk.h}:color=${newest ? accent : fg}:t=fill` + + (newest ? ":enable='gte(t,0.12)'" : ""), + ); + }); + if (words.line) { + // On a ground of its own: the line is wider than a short tally. + out.push(dt({ + text: `'${words.line}'`, fontsize: small, fontcolor: fg, box: 1, boxcolor: `${bg}@0.6`, boxborderw: pad, + x: x0 + pad, y: y0 + pad + t.height + Math.round(small * 0.35), + })); + } + } + } + if (settings.yearStamp && ctx.yearChange && ctx.year != null) { + const across = c ? (c.position.endsWith("left") ? c.position.replace("left", "right") : c.position.replace("right", "left")) : "top-right"; + const at = corner(across, m); + const fs = Math.round(H * 0.16); + out.push(dt({ + text: `'${ctx.year}'`, fontsize: fs, fontcolor: fg, borderw: Math.max(2, Math.round(fs * 0.03)), bordercolor: bg, + alpha: `'if(lt(t,0.08),t/0.08,if(lt(t,1),1,max(0,1-(t-1)/0.25)))'`, + x: at.x("text_w"), y: at.y("text_h"), + })); + } + return out; +} + +/** The font a montage's words are drawn in: the render's bold, else its regular, else Plex Mono Bold. */ +export const montageFont = (render) => render.fontBold ?? render.fontRegular ?? MONO_BOLD_FONT_FILE; + +// ---- the wall --------------------------------------------------------------------------- + +/** + * Which clips the wall's tiles play, in order: `tiles` spread evenly over the + * cut's clips, first to last (the first tile the earliest); fewer clips than + * tiles go round again. + */ +export function wallTileClips(ids, tiles) { + const n = ids.length; + if (!n) return []; + 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]); +} + +/** + * The wall, laid out and timed. A √tiles grid of frame-shaped tiles, centred, + * `gap` apart. Tile i appears at build·(1 − (1 − i/tiles)²) -- the gaps + * between appearances shrink, so the last tiles come fastest -- and plays its + * phrase; at `build` every tile plays its phrase again, together, for the + * longest phrase (0.8–2.5 s) and a quarter second; then the cut. All on frames. + * + * @param {{ tiles: number, build: number, durations: number[], fps: number, width: number, height: number }} o + * `durations` each tile's phrase seconds + */ +export function wallPlan({ tiles, build, durations, fps, width, height }) { + const cols = Math.round(Math.sqrt(tiles)); + const gap = Math.max(2, Math.round(height * 0.008) & ~1); + const maxW = (width - gap * (cols + 1)) / cols; + const maxH = (height - gap * (cols + 1)) / cols; + let w = Math.floor(Math.min(maxW, (maxH * width) / height)); + w -= w % 2; + let h = Math.floor((w * height) / width); + h -= h % 2; + const gridW = cols * w + (cols - 1) * gap; + const gridH = cols * h + (cols - 1) * gap; + const ox = Math.floor((width - gridW) / 2); + const oy = Math.floor((height - gridH) / 2); + const q = (s) => Math.round(s * fps); + const layout = Array.from({ length: tiles }, (_, i) => ({ + x: ox + (i % cols) * (w + gap), y: oy + Math.floor(i / cols) * (h + gap), w, h, + })); + const appearF = Array.from({ length: tiles }, (_, i) => q(build * (1 - (1 - i / tiles) ** 2))); + const beatF = q(build); + const longest = Math.max(0.8, Math.min(2.5, ...durations.map((d) => (num(d) ? d : 0.8)))); + const beatLenF = q(longest + 0.25); + return { + cols, gap, layout, tileW: w, tileH: h, + appear: appearF.map((f) => f / fps), + appearFrames: appearF, + beat: beatF / fps, beatFrames: beatF, + beatLen: beatLenF / fps, + frames: beatF + beatLenF, + seconds: (beatF + beatLenF) / fps, + }; +} + +/** + * One wall tile: the clip's phrase (from–to on the fetched file's clock), + * filled into the tile (cropped, never letterboxed), its year at the foot + * when the wall says so. + */ +export function wallTileArgs({ raw, from, to, tileW, tileH, fps, year = null, font, render, encode, outPath }) { + const fs = Math.max(10, Math.round(tileH * 0.11)); + const label = year != null + ? `,drawtext=fontfile='${font}':expansion=none:text='${safeText(String(year))}':fontsize=${fs}:fontcolor=${render.palette?.fg ?? "#ffffff"}:borderw=2:bordercolor=${render.palette?.bg ?? "#000000"}:x=${Math.round(fs * 0.6)}:y=h-${Math.round(fs * 0.5)}-text_h` + : ""; + return [ + "-nostdin", "-v", "error", "-y", + "-ss", from.toFixed(3), "-to", to.toFixed(3), "-i", raw, + "-filter_complex", + `[0:v]fps=${fps},scale=${tileW}:${tileH}:force_original_aspect_ratio=increase,crop=${tileW}:${tileH},setsar=1${label}[v]`, + "-map", "[v]", "-map", "0:a", + ...encode, + outPath, + ]; +} + +/** + * The wall's compose: every tile laid on the grid, each appearing at its + * time and playing once, then frozen; at the beat all play again, together. + * Sound: each tile at full level until the next one appears, then ducked; + * the beat's tiles all together (a crowd), limited. Then the cut style and + * the de-click, as any segment. + * + * @param {{ tiles: Array<{ file: string, seconds: number }>, plan: object, render: object, + * settings: object, first: boolean, last: boolean, encode: string[], outPath: string }} o + */ +export function wallComposeArgs({ tiles, plan, render, settings, first, last, encode, outPath }) { + const { fps } = render; + const bg = render.palette?.bg ?? "#000000"; + const T = tiles.length; + const total = exprNum(plan.seconds); + const beat = exprNum(plan.beat); + const parts = []; + const vs = []; + const as = []; + const crowd = exprNum(Math.min(1, 1.6 / Math.sqrt(T))); + tiles.forEach((t, i) => { + const at = plan.appear[i]; + const once = Math.max(1 / fps, Math.min(t.seconds, plan.beat - at)); + const again = Math.min(t.seconds, plan.beatLen); + parts.push( + `[${i}:v]split[wv${i}a][wv${i}b]`, + `[wv${i}a]trim=end=${exprNum(once)},setpts=PTS-STARTPTS,` + + `tpad=start_duration=${exprNum(at)}:start_mode=add:color=${bg}:stop_mode=clone:stop_duration=${beat},trim=end_frame=${plan.beatFrames}[wv${i}c]`, + `[wv${i}b]trim=end=${exprNum(again)},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration=${exprNum(plan.beatLen)},` + + `trim=end_frame=${plan.frames - plan.beatFrames}[wv${i}d]`, + `[wv${i}c][wv${i}d]concat=n=2:v=1:a=0[wt${i}]`, + ); + vs.push(`[wt${i}]`); + const next = i + 1 < T ? plan.appear[i + 1] - at : Infinity; + const duck = Number.isFinite(next) ? `,volume='if(lt(t,${exprNum(next)}),1,0.22)':eval=frame` : ""; + const delay = (s) => Math.round(s * 1000); + parts.push( + `[${i}:a]asplit[wa${i}a][wa${i}b]`, + `[wa${i}a]atrim=end=${exprNum(once)},asetpts=PTS-STARTPTS${duck},adelay=${delay(at)}:all=1[wa${i}c]`, + `[wa${i}b]atrim=end=${exprNum(again)},asetpts=PTS-STARTPTS,volume=${crowd},adelay=${delay(plan.beat)}:all=1[wa${i}d]`, + ); + as.push(`[wa${i}c]`, `[wa${i}d]`); + }); + const layout = plan.layout.map((l) => `${l.x - plan.layout[0].x}_${l.y - plan.layout[0].y}`).join("|"); + parts.push( + `${vs.join("")}xstack=inputs=${T}:layout=${layout}:fill=${bg},` + + `pad=${render.width}:${render.height}:${plan.layout[0].x}:${plan.layout[0].y}:color=${bg},setsar=1,fps=${fps}[wg]`, + ); + 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, + ]; +} + +/** 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 @@ -0,0 +1,759 @@ +// Montage editing (`render.montage`, release 33 M3): the pure parts -- the +// settings and their validation, where a phrase is said, the ramp, the cut +// window, the pieces (punch-in, stutter), the cut styles, the counter, the +// wall's layout and timing -- and real renders of a four-clip montage per +// named style over synthetic lavfi clips: the length the plan says, to the +// frame, and the flash, the counter, the year stamp, the whip and the wall +// where they should be. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +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, +} from "./montage.mjs"; +import { applyMontageStyle, MONTAGE_STYLE_NAMES, mergePatch } from "./montage-styles.mjs"; +import { buildVideo, snap } from "./build-video.mjs"; +import { lintManifest } from "./lint.mjs"; +import { verifyBuild } from "./verify-build.mjs"; +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; + +const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" }; +const clip = (id, extra = {}) => ({ id, type: "clip", video: `v-${id}`, start: 10, end: 20, ...extra }); +const manifest = (montage, timeline = [clip("c1"), clip("c2")], render = {}) => ({ + render: { width: 1920, height: 1080, fps: 30, palette: PALETTE, ...render, montage }, timeline, +}); + +// ---- settings and validation --------------------------------------------------- + +test("validateMontage: absent or null is off and says nothing; the named styles all validate", () => { + assert.deepEqual(validateMontage({ render: {}, timeline: [] }), []); + assert.deepEqual(validateMontage(manifest(null)), []); + assert.equal(montageOn({}), false); + assert.equal(montageOn({ montage: null }), false); + assert.equal(montageOn({ montage: {} }), true); + for (const name of MONTAGE_STYLE_NAMES) { + assert.deepEqual(validateMontage(applyMontageStyle(manifest(undefined), name)), [], name); + } +}); + +test("validateMontage: unknown keys and bad values are errors that say what is wrong", () => { + const errs = (m, tl) => validateMontage(manifest(m, tl)); + assert.match(errs([])[0], /render\.montage must be an object/); + assert.match(errs({ tightn: "phrase" })[0], /render\.montage\.tightn is not a setting here \(the settings are tighten, phrasePad, /); + assert.match(errs({ tighten: "word" })[0], /render\.montage\.tighten must be "phrase" or "sentence", not "word"/); + assert.match(errs({ phrasePad: -1 })[0], /phrasePad must be a number from 0 to 5 seconds/); + assert.match(errs({ cut: "wipe" })[0], /render\.montage\.cut must be "hard" or "flash" or "whip" or "dip", not "wipe"/); + assert.match(errs({ flashColor: "red" })[0], /flashColor must be "white", "accent" or a #rrggbb colour/); + assert.deepEqual(errs({ flashColor: "#ff8800" }), []); + assert.match(errs({ counter: { style: "dial" } })[0], /counter\.style must be "chip" or "big" or "tally"/); + assert.match(errs({ counter: { position: "middle" } })[0], /counter\.position must be "top-left"/); + assert.match(errs({ counter: { of: "yes" } })[0], /counter\.of must be true or false/); + assert.match(errs({ counter: { colour: 1 } })[0], /counter\.colour is not a setting here/); + assert.match(errs({ counter: 3 })[0], /counter must be an object/); + assert.match(errs({ punch: { scale: 1.2 } })[0], /punch\.mode must be "snap" or "drift", not undefined/); + assert.match(errs({ punch: { mode: "snap", scale: 3 } })[0], /punch\.scale must be a number from 1 to 2/); + assert.match(errs({ punch: { mode: "snap", anchor: "face" } })[0], /punch\.anchor must be "upper" or "center"/); + assert.match(errs({ stutter: { times: 3 } })[0], /stutter needs `every` \(every Nth clip\) or `clips`/); + assert.match(errs({ stutter: { every: 0 } })[0], /stutter\.every must be a whole number from 1/); + assert.match(errs({ stutter: { every: 2, times: 5 } })[0], /stutter\.times must be 2, 3 or 4/); + assert.match(errs({ stutter: { clips: ["c9"] } })[0], /stutter\.clips names "c9", which is not a clip in the timeline/); + assert.deepEqual(errs({ stutter: { clips: ["c2"] } }), []); + assert.match(errs({ stutter: { every: 2, length: 3 } })[0], /stutter\.length must be a number from 0\.1 to 1 seconds/); + assert.match(errs({ ramp: { from: 4, to: 1 } })[0], /ramp trims around the phrase, so it needs render\.montage\.tighten "phrase"/); + assert.match(errs({ tighten: "phrase", ramp: { from: 4 } })[0], /ramp\.to must be a number from 0\.5 to 60 seconds, not undefined/); + assert.deepEqual(errs({ tighten: "phrase", ramp: { from: 4, to: 1 } }), []); + assert.match(errs({ wall: { tiles: 12 } })[0], /wall\.tiles must be 9 or 16 or 25, not 12/); + assert.match(errs({ wall: { at: "middle" } })[0], /wall\.at must be "end" or "start"/); + assert.match(errs({ wall: { build: 0 } })[0], /wall\.build must be a number from 1 to 60/); + assert.match(errs({ yearStamp: "yes" })[0], /yearStamp must be true or false/); +}); + +test("validateMontage: what a montage does not combine with", () => { + const deck = validateMontage(manifest({}, undefined, { chrome: { engine: "hyperframes", layout: "deck", deck: {} } })); + assert.ok(deck.some((e) => /does not combine with render\.chrome \(the deck\)/.test(e)), deck.join("; ")); + assert.match(validateMontage(manifest({}, undefined, { rail: { width: 300 } }))[0], /does not combine with render\.rail/); + assert.match(validateMontage(manifest({}, undefined, { chromeEngine: "hyperframes" }))[0], /chromeEngine "hyperframes"/); + assert.match( + validateMontage(manifest({}, [clip("c1"), clip("c2", { muteFrom: 12 })]))[0], + /^timeline\[1\] \(c2\)\.muteFrom is not supported under render\.montage/, + ); +}); + +test("the lint and a build's validators say it too", () => { + const m = { slug: "x", title: "X", ...manifest({ cut: "wipe" }) }; + const lint = lintManifest(m, { manifestDir: os.tmpdir(), exists: () => true }); + assert.ok(lint.errors.some((e) => /render\.montage\.cut must be/.test(e)), lint.errors.join("; ")); +}); + +test("resolveMontage: every default filled in; the accent flash is the palette's", () => { + assert.equal(resolveMontage({}), null); + const r = resolveMontage({ palette: PALETTE, montage: { flashColor: "accent", punch: { mode: "drift" }, stutter: { every: 3 }, wall: { tiles: 9 }, counter: {} } }); + assert.equal(r.tighten, null); + assert.equal(r.phrasePad, 0.6); + assert.equal(r.cut, "hard"); + assert.equal(r.flashColor, "#7c5cff"); + 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.equal(r.ramp, null); + assert.equal(r.yearStamp, false); + assert.equal(resolveMontage({ montage: { punch: { mode: "snap" } } }).punch.scale, 1.15); + assert.equal(resolveMontage({ montage: {} }).flashColor, "#ffffff"); +}); + +// ---- the counter's words ---------------------------------------------------------- + +test("dates, sources and the counter text", () => { + assert.deepEqual(parseClipDate("20190502"), { y: 2019, m: 5, d: 2 }); + assert.deepEqual(parseClipDate("2019-05-02"), { y: 2019, m: 5, d: 2 }); + assert.deepEqual(parseClipDate("2019-05-02T10:00:00Z"), { y: 2019, m: 5, d: 2 }); + assert.equal(parseClipDate("May 2019"), null); + assert.equal(parseClipDate("20191302"), null); + assert.equal(parseClipDate(null), null); + assert.equal(formatClipDate({ y: 2019, m: 5, d: 2 }), "2 May 2019"); + assert.equal(formatClipDate(null), ""); + assert.equal(platformLabel("youtube"), "YouTube"); + assert.equal(platformLabel("RUMBLE"), "Rumble"); + assert.equal(platformLabel("mystream"), "Mystream"); + assert.equal(platformLabel(null), ""); + assert.equal(safeText("it's 50% off: [now], ok?"), "its 50 off now ok"); + assert.equal(safeText("#12 · 2 May 2019"), "#12 · 2 May 2019"); + const date = { y: 2019, m: 5, d: 2 }; + assert.deepEqual(counterText({ n: 12, date, platform: "youtube" }), { number: "#12", line: "2 May 2019" }); + assert.deepEqual(counterText({ n: 12, of: 75, date, platform: "youtube", showSource: true }), { number: "#12 of 75", line: "2 May 2019 · YouTube" }); + assert.deepEqual(counterText({ n: 3, date, showDate: false }), { number: "#3", line: "" }); +}); + +// ---- where the phrase is said ------------------------------------------------------ + +const CUES = [ + { start: 10, end: 12, text: "well folks it is a" }, + { start: 12, end: 13.6, text: "slow news day again" }, + { start: 13.6, end: 16, text: "and a slow news week" }, +]; + +test("timedText: the spans' characters spread over their spans, normalised, one space between", () => { + const tt = timedText([{ start: 0, end: 1, text: "It's A" }, { start: 1, end: 2, text: "b,c" }]); + assert.equal(tt.text, "its a b c "); + assert.equal(tt.t0.length, tt.text.length); + assert.equal(tt.t0[0], 0); + assert.ok(Math.abs(tt.t0[4] - 5 / 6) < 1e-9, "the a is the 6th of the cue's 6 characters"); + assert.equal(tt.t0[6], 1); + assert.equal(normalisePhrase(" Slow News-Day! "), "slow news day"); +}); + +test("locatePhrase: by character position inside its cue; across cues; the occurrence nearest `near`", () => { + const a = locatePhrase("slow news day", CUES, { from: 10, to: 16 }); + assert.equal(a.start, 12); + assert.ok(Math.abs(a.end - (12 + (1.6 * 13) / 19)) < 1e-9, `end ${a.end}`); + // Across a cue boundary: "it is a slow" spans cues one and two. + const b = locatePhrase("it is a slow", CUES, { from: 10, to: 16 }); + assert.ok(b.start > 10 && b.start < 12 && b.end > 12 && b.end < 13, JSON.stringify(b)); + // Two occurrences of "slow news": the one nearest `near` wins. + assert.equal(locatePhrase("slow news", CUES, { from: 10, to: 16, near: 12.5 }).start, 12); + assert.ok(locatePhrase("slow news", CUES, { from: 10, to: 16, near: 15 }).start > 13.6); + // Outside the window, or not said: null. + assert.equal(locatePhrase("slow news day", CUES, { from: 0, to: 9 }), null); + assert.equal(locatePhrase("fast news day", CUES, { from: 10, to: 16 }), null); + assert.equal(locatePhrase("", CUES), null); + // A whole-word match first; a phrase running on into a longer word only when there is none. + const runOn = [{ start: 0, end: 2, text: "slow news days" }]; + assert.ok(locatePhrase("slow news day", runOn)); + assert.equal(locatePhrase("slow new", CUES, { from: 10, to: 16 }).start, 12, "a prefix of news"); + assert.equal(locatePhrase("low news", CUES, { from: 10, to: 16 }), null, "never mid-word at the start"); +}); + +test("whisperWords: whisper.cpp's token offsets as words; null for any other shape", () => { + const doc = { + transcription: [ + { + offsets: { from: 9000, to: 12000 }, + tokens: [ + { text: "[_BEG_]", offsets: { from: 9000, to: 9000 } }, + { text: " slow", offsets: { from: 9100, to: 9400 } }, + { text: " ne", offsets: { from: 9400, to: 9550 } }, + { text: "ws", offsets: { from: 9550, to: 9700 } }, + { text: " day", offsets: { from: 9700, to: 10100 } }, + { text: "[_TT_500]", offsets: { from: 10100, to: 10100 } }, + ], + }, + { tokens: [{ text: " far", offsets: { from: 90000, to: 90400 } }] }, + ], + }; + assert.deepEqual(whisperWords(doc, 9, 11), [ + { start: 9.1, end: 9.4, text: "slow" }, + { start: 9.4, end: 9.7, text: "news" }, + { start: 9.7, end: 10.1, text: "day" }, + ]); + assert.equal(whisperWords(doc).length, 4); + assert.equal(whisperWords({ chunk_data: [] }), null); + assert.equal(whisperWords({ cues: [] }), null); + assert.equal(whisperWords(null), null); + const words = whisperWords(doc, 9, 11); + const hit = locatePhrase("slow news day", words, { from: 9, to: 11 }); + assert.deepEqual({ start: hit.start, end: Number(hit.end.toFixed(6)) }, { start: 9.1, end: 10.1 }); +}); + +// ---- the plan across the cut ----------------------------------------------------- + +test("rampCap: lerp(from, to, k/(n−1)) -- the first clip `from`, the last `to`, linear between", () => { + const ramp = { from: 4, to: 1 }; + assert.deepEqual(rampCaps(4, ramp), [4, 3, 2, 1]); + assert.equal(rampCap(0, 1, ramp), 4); + assert.equal(rampCap(3, 7, ramp), 2.5); + assert.equal(rampCap(2, 4, null), null); +}); + +test("planMontage: each clip's place, year change, stutter and edges; cards count as entries, not clips", () => { + const timeline = [ + { id: "t0", type: "card", seconds: 2 }, + clip("a", { montage: { date: "20190102", platform: "youtube" } }), + clip("b", { date: "2019-06-01" }), + clip("c"), + clip("d", { montage: { date: "20210101" } }), + ]; + const settings = resolveMontage({ montage: { tighten: "phrase", ramp: { from: 4, to: 1 }, stutter: { every: 2, clips: ["a"] } } }); + const plan = planMontage(timeline, settings, (e) => (e.id === "c" ? "20200303" : null)); + assert.deepEqual([...plan.keys()], ["a", "b", "c", "d"]); + assert.deepEqual([...plan.values()].map((p) => p.k), [0, 1, 2, 3]); + assert.deepEqual([...plan.values()].map((p) => p.n), [4, 4, 4, 4]); + assert.deepEqual([...plan.values()].map((p) => p.cap), [4, 3, 2, 1]); + assert.deepEqual([...plan.values()].map((p) => p.stutter), [true, true, false, true]); + assert.deepEqual([...plan.values()].map((p) => p.year), [2019, 2019, 2020, 2021]); + assert.deepEqual([...plan.values()].map((p) => p.yearChange), [true, false, true, true]); + assert.equal(plan.get("a").platform, "youtube"); + assert.equal(plan.get("a").first, false, "a card opens the cut"); + assert.equal(plan.get("d").last, true); + const walled = planMontage(timeline.slice(1), resolveMontage({ montage: { wall: { at: "end" } } })); + assert.equal(walled.get("a").first, true); + assert.equal(walled.get("d").last, false, "the wall closes the cut"); + const atStart = planMontage(timeline.slice(1), resolveMontage({ montage: { wall: { at: "start" } } })); + assert.equal(atStart.get("a").first, false); + assert.equal(atStart.get("d").last, true); + assert.equal(stutters({ every: 5, clips: [] }, 4, "x"), true); + assert.equal(stutters({ every: 5, clips: [] }, 5, "x"), false); + assert.equal(stutters(null, 4, "x"), false); +}); + +// ---- one clip's cut ------------------------------------------------------------------- + +const noSnap = () => ({ at: NaN, snapped: false }); + +test("montageWindow: the phrase ± pad, inside the extent; snapped edges kept only outside the phrase", () => { + const sil = [{ s: 1.0, e: 1.5 }, { s: 4.0, e: 4.5 }]; + const base = { extent: [0, 8], play: [0.5, 7], tighten: "phrase", pad: 0.6, cap: null, silences: sil, snapWindow: 0.4, render: {}, snap }; + const w = montageWindow({ ...base, phrase: { start: 2, end: 3.1 } }); + assert.equal(w.tight, true); + assert.deepEqual(w.start, { at: 1.4, snapped: true }, "the silence's end, less the 0.10 s lead"); + assert.deepEqual(w.end, { at: 4.18, snapped: true }, "the silence's start, plus 0.18 s"); + assert.equal(w.cutA, 1.4); + assert.equal(w.cutB, 4.18); + // No silence near: the exact pads. + const bare = montageWindow({ ...base, silences: [], phrase: { start: 2, end: 3.1 } }); + assert.equal(bare.cutA, 1.4); + assert.ok(Math.abs(bare.cutB - 3.7) < 1e-9); + assert.equal(bare.start.snapped, false); + // A snap that would land inside the phrase is refused. + const inside = montageWindow({ ...base, pad: 0.1, silences: [{ s: 2.2, e: 2.6 }], phrase: { start: 2.5, end: 3.1 } }); + assert.equal(inside.start.snapped, false); + assert.equal(inside.cutA, 2.4); + // Never past the extent. + const edge = montageWindow({ ...base, extent: [1.8, 3.3], silences: [], phrase: { start: 2, end: 3.1 } }); + assert.equal(edge.cutA, 1.8); + assert.equal(edge.cutB, 3.3); +}); + +test("montageWindow: under a ramp the pads are trimmed to the cap, never into the phrase", () => { + const base = { extent: [0, 10], play: [0, 10], tighten: "phrase", pad: 2, silences: [], snapWindow: 0.4, render: {}, snap }; + const w = montageWindow({ ...base, cap: 2, phrase: { start: 4, end: 5 } }); + assert.ok(Math.abs(w.cutA - 3.5) < 1e-9 && Math.abs(w.cutB - 5.5) < 1e-9, JSON.stringify(w)); + // One side short of pad: the other takes the room. + const lop = montageWindow({ ...base, cap: 2, phrase: { start: 0.2, end: 1.2 } }); + assert.ok(Math.abs(lop.cutA - 0) < 1e-9 && Math.abs(lop.cutB - 2) < 1e-9, JSON.stringify(lop)); + // A phrase longer than the cap keeps the phrase. + const long = montageWindow({ ...base, cap: 1, phrase: { start: 4, end: 6 } }); + assert.equal(long.cutA, 4); + assert.equal(long.cutB, 6); + // A snap that would break the cap is refused. + const snapped = montageWindow({ ...base, cap: 2, silences: [{ s: 6, e: 7 }], snapWindow: 1, phrase: { start: 4, end: 5 } }); + assert.equal(snapped.end.snapped, false); + assert.ok(snapped.cutB - snapped.cutA <= 2 + 1e-9); +}); + +test("montageWindow: not tightening, or no phrase -- today's play window, snapped as every clip is", () => { + const sil = [{ s: 1.0, e: 1.5 }, { s: 4.0, e: 4.5 }]; + const want = (w0, w1) => { + const a = snap(w0, sil, "start", 0.4, {}); + const b = snap(w1, sil, "end", 0.4, {}); + const cutA = Math.min(a.at, w1 - 1); + return { cutA, cutB: Math.max(b.at, cutA + 1), start: a, end: b, tight: false }; + }; + const base = { extent: [0, 8], play: [1.3, 4.1], pad: 0.6, cap: null, silences: sil, snapWindow: 0.4, render: {}, snap }; + assert.deepEqual(montageWindow({ ...base, tighten: "sentence", phrase: { start: 2, end: 3 } }), want(1.3, 4.1)); + assert.deepEqual(montageWindow({ ...base, tighten: null, phrase: { start: 2, end: 3 } }), want(1.3, 4.1)); + assert.deepEqual(montageWindow({ ...base, tighten: "phrase", phrase: null }), want(1.3, 4.1)); + assert.deepEqual(montageWindow({ ...base, tighten: "phrase", phrase: { start: 9, end: 10 } }), want(1.3, 4.1), "outside the extent"); + void noSnap; +}); + +// ---- the pieces ------------------------------------------------------------------ + +test("montagePieces: one piece; a snap punch-in at the onset; a stutter of the phrase's end", () => { + assert.deepEqual(montagePieces({ frames: 90, fps: 30 }), [{ f0: 0, f1: 90, zoom: 1 }]); + const snapIn = montagePieces({ frames: 90, fps: 30, onset: 1, punch: { mode: "snap", scale: 1.15 } }); + assert.deepEqual(snapIn, [{ f0: 0, f1: 30, zoom: 1 }, { f0: 30, f1: 90, zoom: 1.15 }]); + // A drift has no pieces of its own (it zooms the whole segment). + assert.deepEqual(montagePieces({ frames: 90, fps: 30, onset: 1, punch: { mode: "drift", scale: 1.08 } }), [{ f0: 0, f1: 90, zoom: 1 }]); + const st = montagePieces({ + frames: 90, fps: 30, onset: 1, phraseEnd: 2, punch: { mode: "snap", scale: 1.15 }, + stutter: { times: 3, length: 0.35, step: 0.04 }, + }); + // Fragment = frames 49..60 (0.35 s = 10.5 → 11 frames) heard three times, each a step more zoomed. + assert.deepEqual(st, [ + { f0: 0, f1: 30, zoom: 1 }, + { f0: 30, f1: 49, zoom: 1.15 }, + { f0: 49, f1: 60, zoom: 1.15 }, + { f0: 49, f1: 60, zoom: 1.196, repeat: 1 }, + { f0: 49, f1: 60, zoom: 1.242, repeat: 2 }, + { f0: 60, f1: 90, zoom: 1.15 }, + ]); + assert.equal(piecesFrames(st), 112); + // No room for a fragment: no stutter. + assert.deepEqual(montagePieces({ frames: 90, fps: 30, phraseEnd: 0.05, stutter: { times: 3, length: 0.35, step: 0 } }).length, 1); + // Never outside the cut. + assert.deepEqual(montagePieces({ frames: 30, fps: 30, phraseEnd: 5, stutter: { times: 2, length: 0.2, step: 0 } }), [ + { f0: 0, f1: 24, zoom: 1 }, { f0: 24, f1: 30, zoom: 1 }, { f0: 24, f1: 30, zoom: 1, repeat: 1 }, + ]); +}); + +test("montagePiecesGraph: one piece is a straight run; pieces are split, trimmed, zoomed, joined; drift is a zoompan", () => { + const box = { w: 320, h: 180 }; + const one = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box, bg: "#000000" }); + assert.equal(one.frames, 90); + assert.equal(one.seconds, 3); + assert.equal(one.v, "[mv]"); + assert.equal(one.a, "[ma]"); + assert.deepEqual(one.parts, [ + "[0:v]fps=30[mvs0]", + "[0:a]anull[mas0]", + "[mvs0]trim=start_frame=0:end_frame=90,setpts=PTS-STARTPTS,scale=320:180:force_original_aspect_ratio=decrease,pad=320:180:(ow-iw)/2:(oh-ih)/2:color=#000000,setsar=1[mv0]", + "[mas0]atrim=start=0:end=3,asetpts=PTS-STARTPTS[ma0]", + "[mv0]null[mvc]", + "[ma0]anull[mac]", + "[mvc]tpad=stop_mode=clone:stop_duration=1,trim=end_frame=90,setpts=PTS-STARTPTS[mv]", + `[mac]apad=whole_dur=3,atrim=end=3,afade=t=in:d=${DECLICK},afade=t=out:st=2.985:d=${DECLICK}[ma]`, + ]); + const two = montagePiecesGraph({ pieces: [{ f0: 0, f1: 30, zoom: 1 }, { f0: 30, f1: 90, zoom: 1.15 }], fps: 30, box, bg: "#000000" }); + assert.equal(two.parts[0], "[0:v]fps=30,split=2[mvs0][mvs1]"); + assert.equal(two.parts[1], "[0:a]asplit=2[mas0][mas1]"); + assert.match(two.parts[4], /^\[mvs1\]trim=start_frame=30:end_frame=90,setpts=PTS-STARTPTS,crop=w='floor\(iw\/1\.15\/2\)\*2':h='floor\(ih\/1\.15\/2\)\*2':x='\(iw-ow\)\/2':y='\(ih-oh\)\*0\.35',scale=320:180/); + assert.match(two.parts[5], /^\[mas1\]atrim=start=1:end=3,asetpts=PTS-STARTPTS,afade=t=in:d=0\.005,afade=t=out:st=1\.995:d=0\.005\[ma1\]$/); + assert.equal(two.parts[6], "[mv0][ma0][mv1][ma1]concat=n=2:v=1:a=1[mvc][mac]"); + const drift = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box, bg: "#000000", punch: { mode: "drift", scale: 1.08, anchor: "center" } }); + assert.match(drift.parts.at(-2), /scale=640:360,zoompan=z='1\+0\.08\*on\/89':x='iw\/2-iw\/zoom\/2':y='\(ih-ih\/zoom\)\*0\.5':d=1:s=320x180:fps=30,setsar=1\[mv\]$/); + const deaf = montagePiecesGraph({ pieces: [{ f0: 0, f1: 90, zoom: 1 }], fps: 30, box, bg: "#000000", inA: "[mpa]", hasVideo: false }); + assert.equal(deaf.v, null); + assert.ok(deaf.parts.every((p) => !p.includes("[0:v]"))); + assert.equal(deaf.parts[0], "[mpa]anull[mas0]"); +}); + +// ---- the cut styles ---------------------------------------------------------------- + +test("cutStyleParts: hard is nothing; flash fades in from the colour; dip to black and up; edges of the cut left alone", () => { + const base = { frames: 90, fps: 30, w: 320, h: 180, inLabel: "[v]", outLabel: "[o]" }; + assert.deepEqual(cutStyleParts({ ...base, cut: "hard", first: false, last: false }), ["[v]null[o]"]); + assert.deepEqual(cutStyleParts({ ...base, cut: "flash", first: false, last: false, flashColor: "#ffffff" }), ["[v]fade=t=in:st=0:d=0.1:color=#ffffff[o]"]); + assert.equal(CUT_FRAMES.flash, 3); + assert.deepEqual(cutStyleParts({ ...base, cut: "flash", first: true, last: false }), ["[v]null[o]"], "nothing to cut from"); + assert.deepEqual(cutStyleParts({ ...base, cut: "dip", first: false, last: false }), ["[v]fade=t=in:st=0:d=0.0667,fade=t=out:st=2.9:d=0.0667[o]"]); + assert.deepEqual(cutStyleParts({ ...base, cut: "dip", first: true, last: false }), ["[v]fade=t=out:st=2.9:d=0.0667[o]"]); + assert.deepEqual(cutStyleParts({ ...base, cut: "dip", first: true, last: true }), ["[v]null[o]"]); +}); + +test("cutStyleParts: whip slides the first four frames in and the last four out, blurred along the move", () => { + const base = { frames: 90, fps: 30, w: 320, h: 180, inLabel: "[v]", outLabel: "[o]", cut: "whip" }; + const both = cutStyleParts({ ...base, first: false, last: false }); + assert.equal(both[0], "[v]split=3[wph][wpb][wpt]"); + assert.equal(both[1], "[wph]trim=end_frame=4,setpts=PTS-STARTPTS,split[wh1][wh2]"); + assert.equal(both[2], "[wh1][wh2]hstack,crop=w=320:h=180:x='320*(1-0.9*pow(1-(n+1)/5,2))':y=0,avgblur=sizeX=11:sizeY=1[wh]"); + assert.equal(both[3], "[wpb]trim=start_frame=4:end_frame=86,setpts=PTS-STARTPTS[wb]"); + assert.equal(both[4], "[wpt]trim=start_frame=86,setpts=PTS-STARTPTS,split[wt1][wt2]"); + assert.equal(both[5], "[wt1][wt2]hstack,crop=w=320:h=180:x='320*0.9*pow((n+1)/5,2)':y=0,avgblur=sizeX=11:sizeY=1[wt]"); + assert.equal(both[6], "[wh][wb][wt]concat=n=3:v=1:a=0[o]"); + const opening = cutStyleParts({ ...base, first: true, last: false }); + assert.equal(opening[0], "[v]split=2[wpb][wpt]"); + assert.equal(opening.at(-1), "[wb][wt]concat=n=2:v=1:a=0[o]"); + assert.deepEqual(cutStyleParts({ ...base, first: true, last: true }), ["[v]null[o]"]); + assert.deepEqual(cutStyleParts({ ...base, frames: 8, first: false, last: false }), ["[v]null[o]"], "too short to whip"); +}); + +// ---- the counter and the year stamp ---------------------------------------------------- + +test("tallyMarks: four uprights struck through by the fifth, ten groups a row; the last mark is the newest", () => { + const t = tallyMarks(7, 1080); + assert.equal(t.marks.length, 7); + assert.deepEqual(t.marks.map((m) => m.strike), [false, false, false, false, true, false, false]); + assert.ok(t.marks[4].w > t.marks[4].h, "the strike lies across"); + assert.ok(t.marks[5].x > t.marks[3].x, "the second group starts right of the first"); + const many = tallyMarks(55, 1080); + assert.ok(many.marks[50].y > many.marks[0].y, "the eleventh group starts a second row"); + assert.ok(many.height > t.height); + for (const m of many.marks) assert.ok(m.x >= 0 && m.x + m.w <= many.width && m.y + m.h <= many.height, JSON.stringify(m)); +}); + +const RENDER_1080 = { width: 1920, height: 1080, fps: 30, palette: PALETTE }; +const CTX = { k: 11, n: 75, date: { y: 2019, m: 5, d: 2 }, platform: "youtube", year: 2019, yearChange: true }; + +test("montageOverlayFilters: the chip -- one drawtext on its ground, in its corner", () => { + const settings = resolveMontage({ montage: { counter: { style: "chip", of: true, showSource: true } } }); + const f = montageOverlayFilters({ settings, ctx: CTX, render: RENDER_1080, font: "/f.ttf" }); + assert.equal(f.length, 1); + assert.match(f[0], /^drawtext=fontfile='\/f\.ttf':expansion=none:text='#12 of 75 · 2 May 2019 · YouTube':fontsize=37:fontcolor=#ece8f4:box=1:boxcolor=#15121c@0\.72:boxborderw=17:x=55:y=55$/); + const br = montageOverlayFilters({ settings: resolveMontage({ montage: { counter: { position: "bottom-right" } } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" }); + assert.match(br[0], /:x=W-55-text_w:y=H-55-text_h$/); +}); + +test("montageOverlayFilters: big slams in and goes; tally draws k+1 marks, the newest late; the year stamp across from the counter", () => { + const big = montageOverlayFilters({ settings: resolveMontage({ montage: { counter: { style: "big", position: "bottom-left" } } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" }); + assert.equal(big.length, 2); + assert.match(big[0], /text='12':fontsize='259\*\(1\+0\.9\*max\(0,1-t\/0\.18\)\)':fontcolor=#7c5cff/); + assert.match(big[0], /alpha='min\(1,t\/0\.04\)\*if\(lt\(t,1\.2\),1,max\(0,1-\(t-1\.2\)\/0\.3\)\)'/); + assert.match(big[1], /text='2 May 2019'/); + const tally = montageOverlayFilters({ settings: resolveMontage({ montage: { counter: { style: "tally", showDate: false } } }), ctx: { ...CTX, k: 6 }, render: RENDER_1080, font: "/f.ttf" }); + assert.equal(tally.length, 1 + 7, "the ground and seven marks"); + assert.match(tally[0], /^drawbox=.*:color=#15121c@0\.6:t=fill$/); + assert.ok(tally.slice(1, -1).every((d) => /color=#ece8f4:t=fill$/.test(d))); + assert.match(tally.at(-1), /color=#7c5cff:t=fill:enable='gte\(t,0\.12\)'$/); + const year = montageOverlayFilters({ settings: resolveMontage({ montage: { yearStamp: true, counter: { position: "top-left" } } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" }); + assert.equal(year.length, 2); + assert.match(year[1], /text='2019':fontsize=173:.*:x=W-38-text_w:y=38$/); + assert.deepEqual(montageOverlayFilters({ settings: resolveMontage({ montage: { yearStamp: true } }), ctx: { ...CTX, yearChange: false }, render: RENDER_1080, font: "/f.ttf" }), []); + assert.match(montageOverlayFilters({ settings: resolveMontage({ montage: { yearStamp: true } }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" })[0], /x=W-38-text_w:y=38$/, "no counter: top right"); + assert.deepEqual(montageOverlayFilters({ settings: resolveMontage({ montage: {} }), ctx: CTX, render: RENDER_1080, font: "/f.ttf" }), []); +}); + +// ---- the wall ------------------------------------------------------------------------- + +test("wallTileClips: spread evenly first to last; fewer clips go round again", () => { + assert.deepEqual(wallTileClips(["a", "b", "c", "d", "e", "f", "g", "h", "i"], 9), ["a", "b", "c", "d", "e", "f", "g", "h", "i"]); + const ids = Array.from({ length: 75 }, (_, i) => `s${i + 1}`); + const t = wallTileClips(ids, 16); + assert.equal(t.length, 16); + assert.equal(t[0], "s1"); + assert.equal(t[15], "s75"); + assert.equal(new Set(t).size, 16); + assert.deepEqual(wallTileClips(["a", "b", "c"], 9), ["a", "b", "c", "a", "b", "c", "a", "b", "c"]); + assert.deepEqual(wallTileClips([], 9), []); +}); + +test("wallPlan: a centred grid inside the frame; tiles come faster and faster; the beat; all on frames", () => { + const p = wallPlan({ tiles: 16, build: 8, durations: Array(16).fill(1.2), fps: 30, width: 1920, height: 1080 }); + assert.equal(p.cols, 4); + assert.equal(p.layout.length, 16); + for (const l of p.layout) assert.ok(l.x >= 0 && l.y >= 0 && l.x + l.w <= 1920 && l.y + l.h <= 1080, JSON.stringify(l)); + assert.equal(p.tileW % 2, 0); + assert.equal(p.tileH % 2, 0); + assert.ok(Math.abs(p.tileW / p.tileH - 16 / 9) < 0.02); + assert.equal(p.layout[1].x - p.layout[0].x, p.tileW + p.gap); + assert.equal(p.appear[0], 0); + const gaps = p.appear.slice(1).map((t, i) => t - p.appear[i]); + for (let i = 1; i < gaps.length; i += 1) assert.ok(gaps[i] <= gaps[i - 1] + 1e-9, `gaps shrink: ${gaps}`); + assert.ok(p.appear.at(-1) < p.beat); + assert.equal(p.beat, 8); + assert.equal(p.beatLen, Math.round((1.2 + 0.25) * 30) / 30); + assert.equal(p.frames, 240 + Math.round(1.45 * 30)); + assert.equal(p.seconds, p.frames / 30); + for (const f of p.appearFrames) assert.ok(Number.isInteger(f)); + // The beat is the longest phrase, held to 0.8–2.5 s. + assert.equal(wallPlan({ tiles: 9, build: 4, durations: [9], fps: 30, width: 1920, height: 1080 }).beatLen, Math.round(2.75 * 30) / 30); + assert.equal(wallPlan({ tiles: 25, build: 4, durations: [0.1], fps: 30, width: 1920, height: 1080 }).cols, 5); +}); + +test("wallComposeArgs: each tile appears, plays, freezes and plays again at the beat; the newest up, the rest ducked; exactly its frames", () => { + const plan = wallPlan({ tiles: 9, build: 3, durations: Array(9).fill(1), fps: 30, width: 320, height: 180 }); + const tiles = Array.from({ length: 9 }, (_, i) => ({ file: `/t/${i}.mp4`, seconds: 1 })); + const settings = resolveMontage({ montage: { cut: "flash", wall: { tiles: 9 } } }); + const args = wallComposeArgs({ tiles, plan, render: { width: 320, height: 180, fps: 30, palette: PALETTE }, settings, first: false, last: true, encode: ["-c:v", "libx264"], outPath: "/o.mp4" }); + const graph = args[args.indexOf("-filter_complex") + 1]; + assert.equal(args.filter((a) => a === "-i").length, 9); + assert.match(graph, /\[0:v\]split\[wv0a\]\[wv0b\]/); + assert.match(graph, new RegExp(`tpad=start_duration=${plan.appear[4].toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}:start_mode=add:color=#15121c`)); + assert.match(graph, /xstack=inputs=9:layout=0_0\|/); + assert.match(graph, /volume='if\(lt\(t,[\d.]+\),1,0\.22\)':eval=frame/); + assert.match(graph, /amix=inputs=18:normalize=0:duration=longest,alimiter=limit=0\.9/); + assert.match(graph, /fade=t=in:st=0:d=0\.1:color=#ffffff\[v\]/, "the cut into the wall flashes"); + assert.equal(args[args.indexOf("-frames:v") + 1], String(plan.frames)); +}); + +// ---- real renders --------------------------------------------------------------------- + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const FPS = 30; +const RENDER = { + width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0, + headerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + snapWindow: 0.4, silenceMinDur: 0.1, +}; + +/** + * Four six-second clips: mid grey with a white bar at x 40–60 (something for + * a whip to move), and a tone that sounds 1 s in every 1.5 (silences to snap + * to). Their cues say "slow news day" from 2.0 s; the years run 2019–2022. + */ +async function fixture(montage, { extraRender = {} } = {}) { + const root = await mkdtemp(path.join(os.tmpdir(), "rtv-montage-")); + await mkdir(path.join(root, "media"), { recursive: true }); + const timeline = []; + for (let i = 1; i <= 4; i += 1) { + const file = path.join(root, "media", `c${i}.mp4`); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=${FPS}:d=6`, + "-f", "lavfi", "-i", `aevalsrc='0.5*sin(2*PI*${300 + 40 * i}*t)*between(mod(t,1.5),0,1.0)':s=48000:d=6`, + "-vf", "drawbox=x=40:y=0:w=20:h=180:color=white:t=fill", "-c:v", "libx264", "-preset", "ultrafast", + "-c:a", "aac", "-shortest", file, + ]); + 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" }, + ], + })); + timeline.push({ + id: `c${i}`, type: "clip", src: `media/c${i}.mp4`, cues: `media/c${i}.json`, start: 0.2, end: 5.8, + title: `Clip ${i}`, channelTitle: "Demo", + montage: { n: i, date: `20${18 + i}0${i}0${i}`, platform: "youtube", match: "slow news day", speakerCheck: false }, + }); + } + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "demo", title: "Demo", render: { ...RENDER, ...extraRender, montage }, timeline, + })); + return { root, manifestPath }; +} + +function framesOf(file) { + const r = spawnSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]); + assert.equal(r.status, 0, String(r.stderr)); + return Number(String(r.stdout).trim()); +} + +/** A signalstats value (YAVG: mean luma 0–255; YHIGH: its 90th percentile) of frame `n` of `file` inside a crop `w:h:x:y`. */ +function luma(file, n, crop, key = "YAVG") { + const r = spawnSync("ffmpeg", [ + "-v", "error", "-i", file, "-vf", `select='eq(n,${n})',crop=${crop},signalstats,metadata=print:key=lavfi.signalstats.${key}:file=-`, + "-frames:v", "1", "-f", "null", "-", + ]); + assert.equal(r.status, 0, String(r.stderr)); + const m = String(r.stdout).match(new RegExp(`${key}=([\\d.]+)`)); + assert.ok(m, `no ${key} for frame ${n}`); + return Number(m[1]); +} + +/** Mean U (chroma blue, 128 neutral) of frame `n` inside a crop. */ +function chromaU(file, n, crop) { + const r = spawnSync("ffmpeg", [ + "-v", "error", "-i", file, "-vf", `select='eq(n,${n})',crop=${crop},signalstats,metadata=print:key=lavfi.signalstats.UAVG:file=-`, + "-frames:v", "1", "-f", "null", "-", + ]); + assert.equal(r.status, 0, String(r.stderr)); + return Number(String(r.stdout).match(/UAVG=([\d.]+)/)[1]); +} + +/** The cut records' planned frames, per clip in order, and their sum (+ the wall's). */ +async function planned(root, ids, wall = false) { + const seg = path.join(root, "out", "sourced", "segments"); + const recs = await Promise.all(ids.map(async (id) => JSON.parse(await readFile(path.join(seg, `${id}.cut.json`), "utf8")))); + const frames = recs.map((r) => r.montage.frames); + const wallFrames = wall ? JSON.parse(await readFile(path.join(seg, "montage-wall.cut.json"), "utf8")).montageWall.frames : 0; + return { recs, frames, total: frames.reduce((a, b) => a + b, 0) + wallFrames, wallFrames }; +} + +const IDS = ["c1", "c2", "c3", "c4"]; +const styled = (name, patch = {}) => mergePatch(applyMontageStyle({ render: {} }, name).render.montage, patch); + +test("render: without render.montage (absent or null) the cut is byte for byte the same", { skip: !have && "needs ffmpeg" }, async () => { + const a = await fixture(undefined); + const b = await fixture(null); + 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]; + for (const f of ["demo.mp4", "sourced/segments/c2.mp4"]) { + assert.equal(md5(path.join(a.root, "out", f)), md5(path.join(b.root, "out", f)), f); + } + const rec = JSON.parse(await readFile(path.join(a.root, "out", "sourced", "segments", "c1.cut.json"), "utf8")); + assert.equal(rec.montage, undefined, "no montage in the cut record"); + } finally { + await rm(a.root, { recursive: true, force: true }); + await rm(b.root, { recursive: true, force: true }); + } +}); + +test("render: straight -- each clip cut to its phrase, the length the plan says to the frame, the chip on the picture", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture(styled("straight")); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS); + for (const rec of p.recs) { + assert.equal(rec.montage.found, "cues"); + assert.equal(rec.montage.tight, true); + // Phrase 2.0–3.095 ± 0.6, snapped to the silences at 1.5 and 4.0. + assert.deepEqual([rec.start, rec.end], [1.4, 4.18]); + assert.deepEqual(rec.montage.phrase, [2, 3.095]); + assert.equal(rec.montage.frames, 83); + } + for (const id of IDS) assert.equal(framesOf(path.join(root, "out", "sourced", "segments", `${id}.mp4`)), 83, id); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1, `${framesOf(r.out)} vs ${p.total}`); + // The chip's ground darkens the grey top-left; the bottom-left is untouched. + assert.ok(luma(r.out, 100, "40:8:8:8") < 110, "chip ground"); + assert.ok(Math.abs(luma(r.out, 100, "60:20:200:150") - 128) < 8, "plain grey elsewhere"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: flash-count -- a white flash on the cut, not before; the big number slams in in the accent", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture(styled("flash-count")); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1); + const cut = p.frames[0]; + assert.ok(luma(r.out, cut, "100:60:200:20") > 225, "the first frame of clip 2 is the flash"); + assert.ok(luma(r.out, cut - 1, "100:60:200:20") < 140, "the frame before the cut is not"); + assert.ok(luma(r.out, cut + 4, "100:60:200:20") < 140, "and it is gone by the fourth frame"); + assert.ok(luma(r.out, 0, "100:60:200:20") < 140, "the cut's first clip opens without one"); + // The number, in the accent (blue-heavy), bottom-left early in the clip -- gone by 1.6 s. + assert.ok(chromaU(r.out, cut + 12, "40:40:6:130") > 134, "the accent number"); + assert.ok(Math.abs(chromaU(r.out, cut + 60, "40:40:6:130") - 128) < 3, "gone"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: accelerate -- the cuts shorten along the ramp, drift, tally marks; length to the frame", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture(styled("accelerate", { ramp: { from: 2.6, to: 1.2 } })); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS); + const caps = rampCaps(4, { from: 2.6, to: 1.2 }); + p.recs.forEach((rec, k) => { + assert.ok(rec.end - rec.start <= caps[k] + 0.002, `${rec.id}: ${rec.end - rec.start} > ${caps[k]}`); + assert.ok(rec.start <= 2.0 && rec.end >= 3.095, `${rec.id} keeps the phrase`); + }); + for (let k = 1; k < 4; k += 1) assert.ok(p.frames[k] < p.frames[k - 1], `shorter: ${p.frames}`); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1); + // The fourth clip's tally: its newest mark lands at 0.12 s. + const at = p.frames[0] + p.frames[1] + p.frames[2]; + const t = tallyMarks(4, 180); + const pad = Math.round(180 * 0.012); + const m = Math.round(180 * 0.035); + const nm = t.marks[3]; + const crop = `${nm.w}:${nm.h}:${m + pad + nm.x}:${m + pad + nm.y}`; + assert.ok(luma(r.out, at + 8, crop) > luma(r.out, at, crop) + 15, "the newest mark is drawn at 0.12 s"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: stutter -- the stuttered clip is longer by its repeats; snap punch-in at the onset", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture(styled("stutter", { stutter: { every: null, clips: ["c2"] } })); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS); + const c2 = p.recs[1].montage; + const repeats = c2.pieces.filter((x) => x.repeat); + assert.equal(repeats.length, 2, "heard three times"); + const frag = repeats[0].f1 - repeats[0].f0; + assert.equal(frag, Math.round(0.35 * FPS)); + assert.equal(c2.frames, 83 + 2 * frag); + assert.equal(p.recs[0].montage.pieces.filter((x) => x.repeat).length, 0); + assert.equal(framesOf(path.join(root, "out", "sourced", "segments", "c2.mp4")), c2.frames); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1); + // The punch-in: the bar (x 40–60) moves outward and widens at the onset (0.6 s in). + const seg = path.join(root, "out", "sourced", "segments", "c1.mp4"); + assert.ok(luma(seg, 5, "12:120:44:50") > 230, "before the onset the bar is where it was"); + assert.ok(luma(seg, 40, "6:120:30:50") > 200, "after it the bar has moved left, as a zoom from the centre moves it"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: wall-finale -- a wall segment after the clips, every tile filled at the end; length to the frame", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture(styled("wall-finale", { wall: { tiles: 9, build: 2 } })); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS, true); + assert.ok(p.wallFrames > 60); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1, `${framesOf(r.out)} vs ${p.total}`); + const plan = wallPlan({ tiles: 9, build: 2, durations: [1], fps: FPS, width: 320, height: 180 }); + const start = p.total - p.wallFrames; + const last = plan.layout[8]; + const tile = `${last.w - 4}:${last.h - 4}:${last.x + 2}:${last.y + 2}`; + // The last tile is ground at the wall's start and footage (grey, with the + // year) by the beat. + assert.ok(luma(r.out, start + 2, tile) < 40, "empty at first"); + assert.ok(luma(r.out, p.total - 3, tile) > 100, "filled by the end"); + const wall = JSON.parse(await readFile(path.join(root, "out", "sourced", "segments", "montage-wall.cut.json"), "utf8")); + assert.deepEqual(wall.montageWall.tiles, ["c1", "c2", "c3", "c4", "c1", "c2", "c3", "c4", "c1"]); + // The chapters name it. + const ch = spawnSync("ffprobe", ["-v", "error", "-show_chapters", "-of", "json", r.out]); + const titles = JSON.parse(String(ch.stdout)).chapters.map((c) => c.tags?.title); + assert.equal(titles.length, 5); + assert.equal(titles.at(-1), "All together"); + // verify-build counts the wall's chapter, and a phrase cut's length is no shortfall. + const v = await verifyBuild(manifestPath); + assert.deepEqual(v.problems, []); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: whip-years -- the bar slides at the cut; the year large across from the chip", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture(styled("whip-years")); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1); + const cut = p.frames[0]; + // Mid-clip the bar is at x 40–60; on the incoming whip's first frame it has + // been carried right (shifted ~0.58 of the width), blurred. + assert.ok(luma(r.out, cut - 30, "16:40:42:120") > 230, "the bar where it is"); + assert.ok(luma(r.out, cut, "16:40:42:120") < 200, "gone from there on the whip"); + assert.ok(luma(r.out, cut, "60:40:200:120") > luma(r.out, cut - 30, "60:40:200:120") + 4, "carried right, smeared"); + // The year stamp: top right, early in each clip (every clip is a new year), gone by 1.4 s. + assert.ok(luma(r.out, cut + 10, "80:30:236:6", "YHIGH") > 200, "the year"); + assert.ok(luma(r.out, cut + 45, "80:30:236:6", "YHIGH") < 140, "then not"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("render: dip -- two frames to black before the cut, two up from it", { skip: !have && "needs ffmpeg" }, async () => { + const { root, manifestPath } = await fixture({ tighten: "phrase", cut: "dip" }); + try { + const r = await buildVideo({ manifestPath, opts: { noNetwork: true } }); + const p = await planned(root, IDS); + const cut = p.frames[0]; + const box = "100:60:200:20"; + assert.ok(luma(r.out, cut - 1, box) < 30, "the last frame before the cut is black"); + assert.ok(luma(r.out, cut, box) < 30, "and the first after it"); + assert.ok(luma(r.out, cut + 3, box) > 110, "then the picture"); + assert.ok(luma(r.out, cut - 4, box) > 110, "and before the dip"); + assert.ok(Math.abs(framesOf(r.out) - p.total) <= 1); + } 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,6 +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"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; @@ -53,7 +54,9 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n const probe = JSON.parse(stdout); const duration = Number(probe.format?.duration ?? 0); const chapters = (probe.chapters ?? []).length; - const entries = (manifest.timeline ?? []).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); if (!(duration > 0)) problems.push("duration is not greater than zero"); @@ -73,10 +76,14 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n // CUT when it has one, because that is what was rendered. Measuring a cut // clip against its whole extent would fire this floor on a build that did // exactly what the manifest asked for. + // A montage cut to the phrase plays far less than its window: half a + // second a clip is its floor. (n, e) => n + (e.type === "clip" - ? Math.max(0, (e.cutEnd ?? e.end ?? 0) - (e.cutStart ?? e.start ?? 0)) + ? montage?.tighten === "phrase" + ? 0.5 + : Math.max(0, (e.cutEnd ?? e.end ?? 0) - (e.cutStart ?? e.start ?? 0)) // A narrated card's "auto" is measured by the build: no floor from it here. : (typeof e.seconds === "number" ? e.seconds : 0)), 0,