commit 23e0a8393f041ee46c05a68674ddb4ea34f44918
parent 74e1deff799b28f6c2d3f41094c727419754cde8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 04:06:10 -0400
Merge r35/hyperframes-fx: render.chrome.fx -- ten opt-in overlay effects incl. reaction captions, punch-in, whip; the Takes page's Effect list and umtool take --effect
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# editor/CHANGELOG.md
# plans/FACTS.md
# umtool/report-to-video/build-video.mjs
# umtool/report-to-video/lint.mjs
Diffstat:
21 files changed, 3292 insertions(+), 23 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -4,6 +4,7 @@
- **Fetch a montage's windows from umtool, and swap in another upload when Rumble refuses one.** A report video's Cut tab and its clip deck have **Fetch windows**: one button asks the editor for every clip's window (a dry run first — how many per platform, how many already on disk — then Start, with each job followed to its end and each refused window named); `umtool fetch <project>` does the same from a terminal. When a window is refused for good (a Rumble video whose lookup answers 403 every time, a deleted recording), the clip deck offers a **stand-in** — the same moment in the stream's YouTube upload (or Odysee) — and **Use stand-in** switches the clip, noting where it came from; **Restore** puts it back. `umtool fallback <project>` is the terminal form. Every run is kept in the project's `fetch-runs.json`.
- **Cap a phrase montage at N clips, spread across the years.** `umtool new … --seed phrase --max N`, the New project form's **Max** and the phrase finder's **Max clips** keep N instances, each year's share in proportion to how often it was said there (at least one per year), preferring clips with no speaker change in the captions and spread through each year. The rest are listed in `phrase-scan.json`.
- **umtool proposes highlights from a long recording.** Create → **Highlights from a recording** (or the new-project form's seed "highlights", or `umtool new <slug> --seed reactions --from <channel>/<id> --target 600`) takes a stream or podcast whose speakers the editor has found (its diarization) and proposes clips: each runs from the line that set it up, through the host's laugh or comment, to the next pause. The host is the speaker who interjects all the way through (you can say otherwise: `--host N`, or the clip editor's "This is the host"). Laughs are heard by a small local sound model (CED-mini, installed under `.diarize/models/`), and without it read from the transcript ("[laughter]", "haha") and the host's loud wordless moments. The clips are ranked into the target length, put in the video manifest in time order with hard cuts, and each is marked as proposed by the assistant, with its score and why; the rest stay listed in `reactions.json` beside the manifest to bring in by hand. `umtool clips analyze <project>` runs the scans on the recording's sound (a few minutes for a 2.5-hour stream, kept for the next run) and proposes again; `umtool clips propose` proposes again after a change of host or length, and never moves or removes a clip you edited, ruled, locked or added. Each laugh is also checked against the host's and the narrator's voices, so a laugh voice-acted in the video he is watching is not taken for his. `--scope FROM:TO` (or the form's From/To) reads only part of a recording — a stream that reacts to two videos, one at a time — and the laugh bar is `--laugh-min` (the form's **Laugh min**). Proposals under five seconds or with a low score are listed but never put in the cut. A recording with no diarization is refused with the command that makes it. Nothing calls an AI model, and nothing leaves the machine. Needs a restart of umtool.
+- **Ten effects for report videos with the on-screen deck, each auditioned as a take.** Under `render.chrome.fx`, each one opt-in and drawn over the picture, never as a card: **kinetic captions** — the clip's line word by word as it is said, the key phrase punched in the accent; when the captions mark a change of speaker (`>>` or a dash), or the manifest says who speaks when (`fx.speakers`), each voice gets its own side and colour, with a label only if you give one (it tells two voices apart, never says whose they are); a **redaction reveal** (the line under black bars that lift as each word is said); an **odometer** (a count rolling up on each clip); a **punch-in** (the picture snaps in on seconds you mark, and on laughs the captions write, with a flash and corner brackets); a **whip cut** (the cut slides like a whip pan, streaks across it); a **VHS glitch** at each cut between years; a **timeline scrubber** (a date rail, the playhead sliding to each clip's day with its picture); a **THEN/NOW wipe** (the cut between a pair of clips wipes across, the two dates on its edge); **receipts** (a clip's screenshots fan in and a marker swipes the cited line); and a **zoom** that pushes in on a screenshot's detail. The Takes page's **New take** has an **Effect** list — one preset per effect the cut can show, **Reaction highlights** (two-voice captions, punch-ins, whip cuts and a count) and **Everything** — that fills the patch box for you to edit; from a terminal, `umtool takes effects <project>` and `umtool take <project> --id … --effect <name>`. Nothing calls a model. A manifest without `render.chrome.fx` renders exactly as before. Needs a restart of umtool.
- **The report-video test suite passes in the Docker image.** Run inside `archilyzer:r33-umtool` (Debian's ffmpeg 7.1), six report-to-video tests failed that pass on a newer ffmpeg. Four came from how the tests drove ffmpeg, not from the videos it renders: they now run the graphs the way a build does. One compared against an older ffmpeg's timing drift, which 7.1 does not show; it is now only checked where the drift happens. The sixth needs a git checkout, which an image does not include, and now says so and skips. Nothing a build renders changed.
- **umtool scores who is speaking in each montage clip.** A montage's clip deck and its Cut tab have **Score the voices**: each clip's phrase (and a second either side, its speech only) is compared with the host's voice, and every Cut-tab row then reads `voice 0.43 · unsure` — likely, unsure or unlikely him — and the deck puts the doubtful clips first with their scores. The host's voice is the clips you ruled keep in the audition deck once there are three, or before that solo uploads of the channel found on disk (captioned, no speaker change in the captions, not a stream, no guest in the title, spread over the years); the picker beside the button chooses. It runs on this machine with the speaker model the diarization lane already uses — no network, no AI model — and takes about half a minute for 73 clips. It sorts and flags; whether it is him is still decided by ear. The scores are kept in `voice-match.json` beside the manifest, by the source moment, so a re-seeded montage keeps them. The same from a terminal: `umtool voice-match <project>`. Needs a restart of umtool.
- **A montage's closing wall is the right length on older ffmpeg.** With ffmpeg 7.1 (the umtool Docker image), a tile did not hold its last frame after saying its phrase and did not wait for its turn, so the wall came out short of the length its plan gives (23 frames on the test cut) and, with groups, tiles vanished instead of freezing. The tiles now hold and wait on ffmpeg 7.1 as they do on newer versions; renders on the newer ffmpeg are unchanged.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10712,3 +10712,42 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
≥ 2 s (else the longest at all), 24 for the two clusters with the most seconds, 6 for the rest, each the middle ≤ 8 s.
- **The floor**: a proposal under CLIP_MIN_S (5 s) is widened to 5 s about its middle (`widenTo`, snapped outward)
before ranking; `rankIntoTarget` never uses one under 5 s or scoring under USE_MIN_SCORE (0.2) — it stays listed.
+
+## Release 35 lane O2: the effects region (verified 2026-10-19, branch `r35/hyperframes-fx`)
+
+- **`render.chrome.fx`** (object; absent, `null`, `{}` or every key `null` = off — schedule, joins, graphs and files
+ unchanged, md5-checked against main on a synthetic 4-clip deck fixture) is read only by
+ `umtool/report-to-video/fx.mjs` (pure; deck.mjs imports it, it imports nothing of the montage's), `chrome-fx.mjs` (the
+ page, region `fx`), compose-chrome's `fx` branch and build-video's hooks. Keys (`FX_KEYS`, page order): `scrubber`,
+ `receipts`, `zoom`, `kineticQuote`, `redact`, `odometer`, `punchIn`, `thenNow`, `whip`, `glitch`; each an object of
+ settings (`FX_DEFAULTS`) or null. `validateFx` is called by `validateChrome`; `validateFxEntries(manifest)` by the
+ build's validators and lint's `validatorErrors`.
+- **Entry `fx`** (clip or image; inert until its effect is on): `punch` (words; else `montage.match`), `quote: false`,
+ `punchIn: [source s]` (1–8, inside the extent), `speakers: [{at: source s, who: 0|1}]`, `receipts: [{shot, mark?}]`
+ (1–4; png/jpg/jpeg/webp beside the manifest; `mark`/`focus` = [left, top, right, bottom] fractions of the shot),
+ `zoom: {shot, focus, at?}`.
+- **`schedule.fx`** (only when on): `{keys, box (fxGeometry: the footage box, the feed's under the feed), quotes?,
+ quoteStyle? {kinetic?, redact?, voices?}, odometer?, scrubber?, glitch?, thenNow? {wipes}, whip? {cuts}, punchIn?
+ {punches}, receipts?, zoom?}`, every time in cut seconds; a clip is drawn from its mid-dissolve in to its
+ mid-dissolve out (`in`/`out`), never over a hidden segment. Words: `fxClipWords` (build-video) — the captions when
+ `kineticQuote.speakers` is "auto" and they mark a turn (`>>`, a lone dash), else whisper.cpp's `transcript.json` words,
+ else the cues split by character (`fxWordsOf`), in `fxQuoteSpan` (cutStart–cutEnd, else extent), mapped by the cut
+ record's `start` (`fxClock`); without words, `entry.quote` spread over the span (`fxQuoteFallback`, also the estimate's).
+- **Joins** (`segmentJoins`): a real THEN/NOW pair (D > 0) puts `wipe: true` on the THEN segment's join → `xfadeGraph`
+ `transition=wipeleft` (edge at frame x = W·(1 − p)); a whip cut `whip: true` → `slideleft` (a wipe wins);
+ `punchIn` puts `zoom: [{at, until, scale, anchor, box}]` (segment seconds) → `punchInParts`: split, crop the box's
+ 1/scale (centre, or 1/4 down for "upper"), scale back, `overlay=…:enable='between(t,at,until)'`, before hold/move.
+ `xfadeBatchJoins` carries `wipe`/`whip`; `concatRecordText` records `zoom` (only when present).
+- **Render**: `compose-chrome --region fx` → `chrome/fx/`, `chrome/fx-frames/` (+ `.key`), windowed `fx-from<s>`; assets
+ `DeckSans`/`DeckSansBold`, `FxMono.ttf` (vendored IBM Plex Mono Bold, `FX_MONO_FILE` in the page module, reached by a
+ dynamic import like the teaser's), `fxshotNN.<ext>` with sizes read by `magick identify`, `thumb-<id>.png` (the
+ segment's middle frame cropped to the box, ffmpeg `-flags +bitexact`; none without a segment). The overlay is laid
+ like the deck's (whole cut, `-reinit_filter 0`, rgba, `shortest=1`) after the stats; `verify-build` checks
+ `chrome/fx-frames` = the deck's frame count.
+- **Presets** (`fxPresetsFor(manifest)`, exported `umtool-report-to-video/fx`): kinetic-quote, redaction, odometer,
+ scrubber, glitch, punch-in, whip, reaction, then-now (pairs from `fxSuggestPairs`: neighbouring clips years apart,
+ widest first, ≤ 2), receipts / zoom (only when a clip carries them), everything; each `{render: {transition (the cut's,
+ 0.4 when 0), chrome: {engine, layout, fx}}}`. The Takes page's Effect list (`data-take-effect`) and `umtool take
+ --effect` / `umtool takes effects` read it.
+- A montage still refuses `render.chrome` (and so the effects).
+
diff --git a/plans/release-35/hyperframes-fx.md b/plans/release-35/hyperframes-fx.md
@@ -0,0 +1,68 @@
+# Release 35 lane O2 — `r35/hyperframes-fx`: the effects region (as shipped)
+
+Ten opt-in overlay effects for report videos with the on-screen deck, under `render.chrome.fx`, drawn by ONE
+HyperFrames page for the whole cut over exactly the footage box (`chrome-fx.mjs`, region `fx`), scheduled by `fx.mjs`
+from the build's own clock. Overlays on the evidence, never cards. Mid-lane the orchestrator re-prioritised to
+reaction-highlight clipping; the reaction effects (two-voice captions, punch-in, whip) and a Reaction preset were added.
+
+## What
+
+| Effect (`render.chrome.fx.<key>`) | Draws | Reaction-ready |
+|---|---|---|
+| `kineticQuote` | the clip's line word by word as said, the punch phrase popped in the accent; two speakers on their own sides and colours (captions' `>>` / dash turns, or the entry's `fx.speakers`), labels only from `voices` | yes |
+| `punchIn` | the footage snaps in (crop of the box at the join, `punchInParts`) on marked seconds (`fx.punchIn`) and captioned laughs, with a flash and viewfinder corners | yes |
+| `whip` | the cut slides (`xfade=slideleft` on that join) with streaks; a hard cut streaks only | yes |
+| `odometer` | a rolling count per clip (`montage.n`, else place) at the punch phrase | yes |
+| `glitch` | a seeded VHS tear, the new year and a PLAY stamp at cuts between years (`on: "every"`: every cut) | yes (`on: "every"`) |
+| `redact` | the line under black bars that lift as each word is said | — |
+| `scrubber` | a date rail, the playhead sliding to each clip's day with its thumbnail | — |
+| `thenNow` | a pair's cut becomes a `wipeleft` crossfade, the divider riding its edge with both dates | — |
+| `receipts` | a clip's screenshots fan in, a marker swipes each `mark` | — |
+| `zoom` | a screenshot locks on to `focus` and pushes in | — |
+
+- **Files:** `umtool/report-to-video/fx.mjs` (new: validation, schedule, presets, cue compiler), `chrome-fx.mjs` (new:
+ the page), `deck.mjs` (`fxGeometry`, `validateChrome` knows `fx`, `deckSchedule` writes `fx` only when on),
+ `compose-chrome.mjs` (`--region fx`, `copyFxShots`, `fxThumbs`), `build-video.mjs` (`fxClipWords`, `fxRegion`, the
+ fx render in `renderDeck`, `segmentJoins` wipe/whip/zoom, `punchInParts`, `xfadeGraph` wipeleft/slideleft,
+ `xfadeBatchJoins`, `concatRecordText` zoom, `validateFxEntries` in the validators), `lint.mjs`, `verify-build.mjs`
+ (fx frames), `package.json` (`./fx` export); umtool: `TakesPage.tsx` + `NewTakePanel.tsx` (the **Effect** list,
+ `data-take-effect`), `lib/report/takeCli.mjs` (`umtool take --effect`, `umtool takes effects`); tests `fx.test.mjs`,
+ `chrome-fx.test.mjs`, `takeMaker.test.mjs` (+1), `e2e/takes.spec.ts` (+1); docs README, `docs/report-video.md`,
+ `docs/cli.md`, FACTS, CHANGELOG.
+- **Interfaces:** `fxSchedule`, `fxPresetsFor(manifest)`, `fxSuggestPairs`, `validateFx`, `validateFxEntries`,
+ `fxWordsOf`, `fxWipeJoins` / `fxWhipJoins` / `fxZoomJoins`, `speakersOf`, `compileCues` (fx.mjs); `fxHtml`, `fxPlan`
+ (chrome-fx.mjs); `fxGeometry` (deck.mjs); `fxClipWords`, `fxRegion`, `punchInParts` (build-video.mjs).
+
+## Rulings followed
+
+- Absent = byte-identical: a synthetic 4-clip deck fixture (clips carrying inert entry `fx`) built by main's code
+ (6fda0f58) and the branch's: identical md5 for the final, all four segments and `schedule.json`.
+- Nothing calls a model; every effect is a manifest key a person sets, and the Takes page offers each as a preset patch
+ a person edits (operator rule 2026-10-16). Speakers are told apart, never named: no label unless the manifest gives one.
+- The demo used only windows already on disk (`provenance.channelsDir`, `CHANNELS_DIR`, no `siteOrigin`, takes'
+ `--skip-fetch`), the cached hyperframes 0.8.24 (`HYPERFRAMES_BIN`), telemetry off.
+- A montage still refuses `render.chrome`; the effects are for deck cuts (any report-video clip entry).
+
+## Gates
+
+- tsc (`pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`): clean before every commit.
+- `pnpm run test:scripts`: 1169 (1165 pass, 4 skipped) at the branch's start → **1218 (1214 pass, 0 fail, 4 skipped)**:
+ `fx.test.mjs` 30, `chrome-fx.test.mjs` 19 (±1-frame cue times for every effect; Chromium-still pixel checks for the
+ kinetic line, redaction, receipts' marker, zoom push, odometer, glitch, scrubber playhead, punch-in flash, whip
+ streaks; ffmpeg checks that the divider rides `xfade wipeleft`'s edge and that the punch-in graph changes only the box
+ between its seconds; compose-chrome's fx region through a stub renderer and its cache), `takeMaker.test.mjs` +1.
+- umtool unit (`pnpm --filter umtool test`): 45/45.
+- umtool e2e `takes.spec.ts` (its prebuild is the capped umtool build): **8 passed**, 0 failed, 19.4 s (+1: the Effect list).
+- Byte-identical without fx: main 6fda0f58 vs the branch on the synthetic fixture — final `857cfa3d…`, segments
+ `8c2c83e6…`, `59b091c9…`, `1fab1f60…`, `ba32f163…`, schedule `ac9618b3…`, the same both sides.
+- The fx fixture (all eight first effects on) built end to end: 23.3 s, `fx-frames` 699 frames rendered in 42.5 s.
+
+## Demo
+
+`~/reports/hyperframes-fx-demo/` (not committed): six clips whose windows were already on disk — four slow-news clips
+(2019, 2021, 2024 with a dash-marked second voice, 2026; whole extents, a person-marked punch-in second each) and two
+polemic-deleted clips with the X screenshots they cite (receipts, zoom). Eleven quick takes in group `effects`, made by
+`umtool take … --effect <name> --quick` in one heavy-slot admission (≈ 1 min each): fx-reaction, fx-kinetic,
+fx-punch-in, fx-whip, fx-odometer, fx-glitch, fx-then-now, fx-redact, fx-scrubber (26.83 s, `--at 0 --dur 26`),
+fx-receipts, fx-zoom (28.07 s, `--at 27 --dur 20`). fx-receipts was made again after its marker was moved onto the
+cited line, so the other ten say "the project changed since this take was made" (only `fx.receipts[0].mark` changed).
diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx
@@ -14,6 +14,8 @@ import { JobProgress, type JobStepState } from "@/components/ui/job-progress";
// calls a model.
export type MontageStyle = { name: string; label: string; summary: string };
+/** An effect preset (report-to-video/fx.mjs `fxPresetsFor`): a merge patch the patch box takes. */
+export type EffectPreset = { name: string; label: string; summary: string; patch: Record<string, unknown> };
type StepView = { label: string; argv: string[] };
type Ev = Record<string, unknown> & { ev: string; id?: string; phase?: string };
@@ -66,18 +68,21 @@ export default function NewTakePanel({
project,
styles,
stylesError,
+ effects = [],
group: initialGroup,
window: initialWindow = { at: 0, dur: 60 },
}: {
project: string;
styles: MontageStyle[];
stylesError?: string | null;
+ effects?: EffectPreset[];
group: string;
window?: { at: number; dur: number };
}) {
const router = useRouter();
const [ready, setReady] = useState(false);
const [style, setStyle] = useState("");
+ const [effect, setEffect] = useState("");
const [label, setLabel] = useState("");
const [labelTouched, setLabelTouched] = useState(false);
const [group, setGroup] = useState(initialGroup);
@@ -129,6 +134,7 @@ export default function NewTakePanel({
}, [job, router]);
const picked = styles.find((s) => s.name === style) ?? null;
+ const pickedEffect = effects.find((x) => x.name === effect) ?? null;
const { patch, error: patchError } = readPatch(patchText);
const windowOf = () => (full ? "full" : { at: Number(at), dur: Number(dur) });
const windowBad = !full && !(Number(at) >= 0 && Number(dur) > 0);
@@ -181,6 +187,28 @@ export default function NewTakePanel({
))}
</Select>
</Field>
+ {effects.length ? (
+ <Field label="Effect" hint={pickedEffect?.summary ?? "Fills the patch below; edit it there."}>
+ <Select
+ data-take-effect=""
+ value={effect}
+ disabled={!ready}
+ onChange={(e) => {
+ const next = effects.find((x) => x.name === e.target.value) ?? null;
+ setEffect(e.target.value);
+ setPatchText(next ? JSON.stringify(next.patch, null, 2) : "");
+ if (!labelTouched) setLabel(next?.label ?? picked?.label ?? "");
+ }}
+ >
+ <option value="">None</option>
+ {effects.map((x) => (
+ <option key={x.name} value={x.name}>
+ {x.label}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ ) : null}
<Field label="Label">
<Input
data-take-label=""
diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx
@@ -7,6 +7,7 @@ import { listTakes, readVerdicts } from "@/lib/report/takes.mjs";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import type { ProjectRef } from "@/lib/project-types";
import { hashText, lastGroup, loadMontageStyles } from "@/lib/report/takeMaker.mjs";
+import { fxPresetsFor } from "umtool-report-to-video/fx";
import NewTakePanel from "./NewTakePanel";
import TakesBench, { type Take, type TakeVerdict } from "./TakesBench";
@@ -27,6 +28,13 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
readFile(path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null),
]);
const current = manifestText === null ? null : hashText(manifestText);
+ // The effect presets this cut can show (release 35: report-to-video/fx.mjs), from its own manifest.
+ let effects: ReturnType<typeof fxPresetsFor> = [];
+ try {
+ effects = manifestText === null ? [] : fxPresetsFor(JSON.parse(manifestText));
+ } catch {
+ effects = [];
+ }
const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null }));
const byId = new Map(takes.map((t) => [t.id, t]));
const panel =
@@ -35,6 +43,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
project={project.id}
styles={Object.entries(styles.styles).map(([name, s]) => ({ name, label: s.label, summary: s.summary }))}
stylesError={styles.error}
+ effects={effects}
group={lastGroup(takes)}
/>
) : null;
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -39,9 +39,9 @@ Inbox cannot disagree about what is wrong with one.
| `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) |
| `schedule list \| show <id> [--json]` | the recurring reports, read-only ([recurring.md](recurring.md)) |
| `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) |
-| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
+| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
-| `takes styles [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
+| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. Every run is recorded in `<project>/fetch-runs.json`. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
| `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -400,6 +400,37 @@ and the pipeline call it the deck (`render.chrome.layout: "deck"`), but "deck"
is already the song kind's name in umtool, and one word meaning two things two
pages apart is how somebody edits the wrong one.
+### Effects (`render.chrome.fx`, release 35)
+
+Ten effects for a deck cut, drawn over its footage box — a kinetic quote (two
+speakers on their own sides and colours), a redaction reveal, an odometer, a
+timeline scrubber, a VHS glitch at a cut between years, a THEN/NOW wipe, a whip
+cut, a punch-in on a laugh, receipts (screenshots fanned in with a marker on
+the cited line) and a zoom to detail. **Reaction highlights** (a host reacting
+to a video) have their own preset: the two-voice captions, punch-ins on the
+laughs the captions write and on seconds a person marks (`fx.punchIn`), whip
+cuts and a running count. Every key, its defaults and
+what it draws are the pipeline's README
+([`render.chrome.fx`](../report-to-video/README.md#renderchromefx--the-effects-release-35));
+umtool's part is auditioning them as takes:
+
+- The Takes page's **New take** has an **Effect** list (`data-take-effect`):
+ one preset per effect this cut can show and **Everything**, from
+ `fxPresetsFor` (`report-to-video/fx.mjs`, pure: the same manifest, the same
+ presets). Picking one fills the patch box with its merge patch — the
+ effect under `render.chrome.fx`, the deck's engine and layout (a merge keeps
+ the deck's settings), and the cut's transition (0.4 s when it cuts hard, so
+ the THEN/NOW wipe has a crossfade to ride). Edit it there, or not.
+- **THEN/NOW** pairs are suggested from the cut: neighbouring clips whose dates
+ are years apart, the widest gaps first, at most two. **Receipts** and
+ **Zoom** are offered only when a clip carries them (`fx.receipts`,
+ `fx.zoom`: screenshots beside the manifest, with the mark or focus box as
+ fractions of the shot) — an entry's `fx` draws nothing until its effect is
+ on, so a project can carry the screenshots while takes audition the effects.
+- From a terminal: `umtool takes effects <project>` lists them,
+ `umtool take <project> --id fx-glitch --label "VHS glitch" --effect glitch --at 0 --dur 34 --quick`
+ makes one ([cli.md](cli.md)).
+
## The three-stage window model
A clip's window passes through three different notions of "where the cut is", and
diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts
@@ -156,6 +156,23 @@ const MAKE_DIR = path.join(HERE, "..", ".e2e-song", "reports", "takes-make-fixtu
const MAKE_PAGE = urls.takesHref("reports/takes-make-fixture");
const readText = (rel: string) => readFileSync(path.join(MAKE_DIR, rel), "utf8");
+test("New take's Effect list fills the patch with an effect's preset, and None empties it (release 35)", async ({ page }) => {
+ await page.goto(MAKE_PAGE);
+ await page.locator("[data-action='new-take-open']").click();
+ const effect = page.locator("[data-take-effect]");
+ await expect(effect).toBeEnabled();
+ await expect(effect.locator("option[value='glitch']")).toHaveCount(1);
+ await expect(effect.locator("option[value='everything']")).toHaveCount(1);
+ await effect.selectOption("glitch");
+ await expect(page.locator("[data-take-label]")).toHaveValue("VHS glitch");
+ const patch = JSON.parse(await page.locator("[data-take-patch]").inputValue());
+ expect(patch.render.chrome.fx).toEqual({ glitch: {} });
+ expect(patch.render.chrome.layout).toBe("deck");
+ await expect(page.locator("[data-action='make-take']")).toBeEnabled();
+ await effect.selectOption("");
+ await expect(page.locator("[data-take-patch]")).toHaveValue("");
+});
+
test("the take maker: New take with a style, the take appears, Use this take makes it the project's manifest", async ({ page, request }) => {
test.setTimeout(240_000);
await page.goto(MAKE_PAGE);
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -4,8 +4,9 @@
//
// umtool take <project> --id <id> --label "<l>" [--group G] [--kind K] [--summary S]
// [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]
-// [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]
+// [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]
// umtool take <project> --id <id> --rebuild made again from its own take.json
+// umtool takes effects <project> [--json] the effect presets this cut offers (report-to-video/fx.mjs)
// umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson]
// umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force]
// umtool takes styles [--json]
@@ -28,17 +29,20 @@ import {
pickTake,
} from "./takeMaker.mjs";
import { TAKE_FILE, takesDirOf } from "./takes.mjs";
+import { fxPresetsFor } from "umtool-report-to-video/fx";
+import { mergePatch } from "umtool-report-to-video/montage-styles";
export const TAKE_USAGE = [
"usage: umtool take <project> --id <id> --label \"<label>\" [--group G] [--kind similar|different]",
" [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]",
- " [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]",
+ " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]",
" umtool take <project> --id <id> --rebuild made again from its own take.json",
"",
"A take is the project's manifest with a style's patch, then the take's own, applied (JSON merge",
"patches), rendered into takes/<id>/. The window renders the entries it covers; --full the whole",
`cut. Default window: --at ${DEFAULT_WINDOW.at} --dur ${DEFAULT_WINDOW.dur}. Nothing is fetched. --quick encodes`,
"the render with x264 veryfast (the render only: the take's manifest, what a pick uses, keeps its own).",
+ "--effect NAME is one of `umtool takes effects <project>` (an overlay effect's patch, before --patch's).",
].join("\n");
export const TAKES_USAGE = [
@@ -49,6 +53,7 @@ export const TAKES_USAGE = [
` one take per montage style (writes takes/${ALL_STYLES_RECIPE})`,
" umtool takes styles [--json] the montage styles: name, label, summary",
" umtool takes pick <project> <take> [--anyway] use this take: its manifest over the project's",
+ " umtool takes effects <project> [--json] the overlay effects this cut offers, for --effect",
].join("\n");
class CliError extends Error {}
@@ -56,7 +61,7 @@ class CliError extends Error {}
/** The flags of one command line. */
function parse(args) {
const valued = new Set([
- "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set",
+ "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect",
"--at", "--dur", "--recipe", "--only", "--progress",
]);
/** @type {Record<string, string[]>} */
@@ -126,6 +131,23 @@ async function patchOf(p) {
return patch;
}
+/** The effect presets a project's manifest offers (report-to-video/fx.mjs `fxPresetsFor`). */
+async function effectsOf(project) {
+ const text = await readFile(path.join(project.dir, "video.manifest.json"), "utf8").catch(() => null);
+ if (text === null) throw new CliError(`${project.id} has no video.manifest.json`);
+ return fxPresetsFor(JSON.parse(text));
+}
+
+/** --effect NAME's patch, with --patch's (if any) merged over it. */
+async function withEffect(p, project, patch) {
+ const name = p.one("--effect");
+ if (!name) return patch;
+ const effects = await effectsOf(project);
+ const fx = effects.find((x) => x.name === name);
+ if (!fx) throw new CliError(`unknown effect "${name}" — this cut offers ${effects.map((x) => x.name).join(", ")}`);
+ return patch ? mergePatch(fx.patch, patch) : fx.patch;
+}
+
/** The output side: NDJSON on stdout under --progress ndjson, else lines. */
function reporter(p, log, err) {
const ndjson = p.one("--progress") === "ndjson";
@@ -189,7 +211,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
kind: p.one("--kind"),
summary: p.one("--summary"),
style: p.one("--style") ?? null,
- patch: await patchOf(p),
+ patch: await withEffect(p, project, await patchOf(p)),
window: windowOf(p),
quick: p.has("--quick"),
};
@@ -239,6 +261,13 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
if (skipped.length) err(`not the shape { label, summary, patch }: ${skipped.join(", ")}`);
return error ? 1 : 0;
}
+ if (sub === "effects") {
+ const project = await pickProject(rest[0], reportsRoot);
+ const effects = await effectsOf(project);
+ if (p.has("--json")) log(JSON.stringify({ effects }, null, 2));
+ else for (const x of effects) log(`${x.name.padEnd(16)} ${x.label} — ${x.summary}`);
+ return 0;
+ }
if (sub === "pick") {
const project = await pickProject(rest[0], reportsRoot);
const take = rest[1];
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -432,6 +432,33 @@ test("the CLI: umtool take with --set, umtool takes make with a recipe, umtool t
}
});
+test("the CLI: umtool takes effects lists the cut's effect presets; umtool take --effect applies one before --set", async () => {
+ const { root, dir, reportsRoot } = await project();
+ const r = stubRender();
+ const out = [];
+ const err = [];
+ const io = { reportsRoot, log: (s) => out.push(s), err: (s) => err.push(s), deps: { render: r.render, styles: STYLES, probe: async () => 1 } };
+ try {
+ assert.equal(await takesCommand(["effects", "proj", "--json"], io), 0, err.join("\n"));
+ const { effects } = JSON.parse(out.join("\n"));
+ const names = effects.map((x) => x.name);
+ for (const n of ["kinetic-quote", "redaction", "odometer", "scrubber", "glitch", "everything"]) assert.ok(names.includes(n), n);
+ assert.ok(!names.includes("receipts") && !names.includes("zoom"), "no clip carries a screenshot");
+ assert.equal(await takeCommand(["proj", "--id", "glitchy", "--label", "Glitch", "--effect", "glitch", "--set", "render.crf=31", "--full"], io), 0, err.join("\n"));
+ const doc = r.calls.at(-1).doc;
+ assert.deepEqual(doc.render.chrome.fx, { glitch: {} });
+ assert.equal(doc.render.chrome.engine, "hyperframes");
+ assert.equal(doc.render.crf, 31, "--set merges over the effect's patch");
+ const t = JSON.parse(await readFile(path.join(dir, "takes", "glitchy", "take.json"), "utf8"));
+ assert.ok(t.changes.some((c) => c.startsWith("render.chrome")), t.changes.join("; "));
+ err.length = 0;
+ assert.equal(await takeCommand(["proj", "--id", "x", "--label", "X", "--effect", "sparkle"], io), 2);
+ assert.match(err.join("\n"), /unknown effect "sparkle" — this cut offers kinetic-quote/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
test("takeSteps: each button is one job running the CLI, checked before it starts", () => {
const proj = { id: "reports/proj" };
const ctx = { styles: STYLES, existing: [{ id: "flash", window: "full" }], clipCount: 75 };
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -734,6 +734,80 @@ 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.chrome.fx` — the effects (release 35)
+
+Ten effects for a deck cut, each opt-in under `render.chrome.fx`
+and drawn by ONE HyperFrames page for the whole cut over exactly the footage
+box (`fxGeometry`): overlays on the evidence, never cards. Absent (or `null`,
+or `{}`, or every effect `null`) nothing here runs and every schedule, graph
+and file is byte for byte what it was. `{}` turns an effect on with its
+defaults.
+
+```jsonc
+"render": { "transition": 0.4, "chrome": { …, "fx": {
+ "kineticQuote": { "position": "bottom", "size": 54, "maxWords": 12, "clips": ["c01", "c03"],
+ "speakers": "auto", "voices": [{ "label": "Host" }, { "label": "Video", "color": "#22ab83" }] },
+ "redact": { "position": "bottom", "size": 44, "maxWords": 14, "clips": ["c02"] },
+ "odometer": { "position": "top-right", "label": "times", "at": "phrase" },
+ "scrubber": { "position": "top", "thumbs": true },
+ "glitch": { "on": "year", "seconds": 0.5, "stamp": true },
+ "thenNow": { "pairs": [{ "then": "c03", "now": "c04" }], "seconds": 0.6, "dates": "date" },
+ "receipts": { "position": "right", "width": 0.36 },
+ "zoom": { "width": 0.56 },
+ "punchIn": { "scale": 1.2, "hold": 1.4, "anchor": "upper", "auto": true },
+ "whip": { "on": "every" }
+} } }
+{ "type": "clip", "id": "c02", …, "fx": {
+ "punch": "slow news week", // the words to punch (else montage.match)
+ "punchIn": [1834.2], // source seconds the picture snaps in on
+ "speakers": [{ "at": 1830.0, "who": 1 }, { "at": 1833.1, "who": 0 }], // which of two voices, from each second
+ "quote": false, // this clip draws no line
+ "receipts": [{ "shot": "shots/a.png", "mark": [0.02, 0.35, 0.86, 0.41] }], // 1–4 screenshots
+ "zoom": { "shot": "shots/b.png", "focus": [0.02, 0.40, 0.93, 0.52], "at": 1.5 } } }
+```
+
+| effect | what it draws |
+|---|---|
+| `kineticQuote` | The clip's line, word by word as it is said, on a band of the ground at the box's foot (or head). The punch phrase (`fx.punch`, else `montage.match`) pops in at 1.8× in the accent with an underline sweeping under it. Pages of at most `maxWords`, broken after a clause once half full. |
+| (two voices) | With `speakers: "auto"` (the default) a kinetic line that has two speakers gives each its own pages, side and colour — the first voice on the left in `fg`, the second on the right in THEN's blue, or `voices[i].color` — with `voices[i].label` over its words when the manifest names one. Who speaks is the clip's `fx.speakers` (source seconds, each holding until the next), else the captions' own turn marks (`>>`, a dash before the words), each turn handing over to the other voice; when the captions mark turns the build reads the words from them rather than whisper.cpp's (which carry none). It says WHICH of two voices, never whose: no label is drawn unless the manifest gives one. `speakers: false` keeps one voice. |
+| `redact` | The same line as a page of transcript, every word under a black bar; each bar lifts off as its word is said, the punch phrase highlighted in amber when it is revealed. `kineticQuote` and `redact` are one treatment a clip: when both are on, give one of them `clips` (a clip named by neither falls to the one without a list). |
+| `odometer` | A counter in a corner: rolling digits, the count going up on each clip — `montage.n` when the clip has it, else its place — at the punch phrase (`at: "phrase"`, else a quarter second in), a 9 rolling on to the next 0. `label` under it ("times"; "" for none). |
+| `scrubber` | A date rail across the box: a year mark per new year, a tick per dated clip, a playhead that slides to each clip's day as it comes in, with a thumbnail of the clip (its segment's middle frame, `thumbs`) and its date riding under it. The rail keeps clear of an odometer in a corner on its edge. |
+| `glitch` | A VHS tear at each cut between two years (`on: "every"`: every cut between clips): scanlines, torn bars in two channels and noise for `seconds` centred on the cut, the new year big with its colours split, and a `PLAY ▶` date stamp in the corner (`stamp`). Seeded, so every frame is the same tear on every render. |
+| `thenNow` | For each pair — a clip and the very next one — a divider sweeps across the box with the THEN clip's date riding its left and the NOW clip's its right, a scrim on the THEN side. With a crossfade (`transition` > 0) the cut itself becomes a wipe (`xfade=transition=wipeleft`, on that join only) and the divider rides its edge, x = W·(1 − p), over the transition; on a hard cut the divider sweeps alone over `seconds`, centred on the cut. `dates: "year"` shows years only. |
+| `receipts` | A clip's screenshots (`fx.receipts`, beside the manifest: png/jpg/webp) fly in one after another and fan on one side of the box (`width` of it), then a marker swipes amber over each card's `mark` (fractions of the shot: left, top, right, bottom). They fly out before the clip leaves. |
+| `punchIn` | The picture snaps in to `scale` (1.2) on each of a clip's `fx.punchIn` seconds — and, with `auto`, on each laugh its captions write ("haha", "lol", "lmao") — for `hold` seconds, about the upper third (`anchor: "upper"`) or the middle, with a white flash and a viewfinder's corners closing on it. Made where the cut is joined (`punchInParts`: the box cropped and scaled back over itself, between those seconds of the segment's clock), so no segment file changes; the hard-cut record names it. |
+| `whip` | Every cut between two clips (`on: "year"`: between years) slides like a whip pan — `xfade=transition=slideleft` on that join over the transition — with streaks of light raking across the box; on a hard cut the streaks alone flash across it. A THEN/NOW pair's cut stays a wipe. |
+| `zoom` | A clip's screenshot (`fx.zoom`) drops in at the middle of the box, a focus box locks on to `focus`, then the card pushes in until the focus fills it (at the clip's `at` seconds when set) and drifts on the detail until the clip leaves. |
+
+- **The schedule.** `schedule.json` gains `fx: { keys, box, quotes?, quoteStyle?,
+ odometer?, scrubber?, glitch?, thenNow?, whip?, punchIn?, receipts?, zoom? }` (`fxSchedule`,
+ fx.mjs) — only when an effect is on. Every time is in the cut's seconds: a
+ clip is drawn on from its mid-dissolve in to its mid-dissolve out, never
+ over a segment the deck hides (a card, a teaser). The words are the build's:
+ whisper.cpp's when the corpus keeps them (`transcript.json`), else the
+ clip's cues split into words by character position, in its cited span
+ (`cutStart`–`cutEnd`, else the extent), mapped through the segment's cut
+ record (`fxClipWords`). Without timed words (an estimate, a clip whose cues
+ cannot be read) a clip's `quote` is spread evenly over its cited span.
+- **The render.** `chrome-fx.mjs` is the page (pure; every cue states its
+ from, so a seek lands on the same pixels either way; nothing measures the
+ page — compose-chrome reads each screenshot's size first). `compose-chrome.mjs
+ --region fx` composes and renders it (`chrome/fx/`, `chrome/fx-frames/`,
+ cached by its key, windowed as the stamps' are); the build lays it over the
+ stats. `verify-build.mjs` fails when the schedule says an effect is on and
+ the frames are missing or short.
+- **Checks.** `validateFx()` (via `validateChrome()`) refuses unknown keys and
+ bad values; `validateFxEntries()` (the build's validators and `--lint`)
+ refuses a bad entry `fx`, a clip list naming no clip, a pair that is not a
+ clip and the very next entry, and the popup posts' `shift` (it moves the
+ footage the effects are drawn over: set `posts.shift: false`, or use the
+ feed). An entry's `fx` is inert until its effect is on, so a manifest can
+ carry the screenshots while takes audition the effects.
+- **Not with a montage.** A montage still refuses `render.chrome`; its
+ segments are cut inside each clip and joined by stream copy, so there is no
+ overlay pass to lay the page in. The effects are for deck cuts.
+
### `render.montage` — montage editing (release 33)
A montage is one phrase said many times: dozens of short clips, cut tight, run
@@ -2090,10 +2164,11 @@ implementation of the arithmetic to drift.
`compose-chrome.mjs --region deck` is `--region chart`'s sibling: the same
CLI, the same render cache, the same vendored GSAP, a different composition
(`chrome-deck.mjs` instead of the chart band's SVG). `--region feed`, `stamp`,
-`posts` and `teaser` are the deck's other regions (below).
+`posts` and `teaser` are the deck's other regions (below); `stats`, `threads`,
+`flips` and `fx` are documented with their keys above.
```
-node umtool/report-to-video/compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|posts|teaser] [--variant sourced|full]
+node umtool/report-to-video/compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|stats|threads|flips|fx|posts|teaser] [--variant sourced|full]
[--from <s>] [--duration <s>] [--out <dir>] [--preview]
[--still <s> --png <path>]
[--render] [--workers 4] [--quality high] [--format png-sequence] [--fps 30]
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -141,8 +141,10 @@ import {
assertChrome, deckGeometry, deckOn, deckSchedule, endFadeOf, feedGeometry, feedOn, frameCount, hidesDeck, MUTE_FADE,
dipOf, muteSegmentSeconds, playWindow, postsGeometry, postWindows, resolveDeck, scheduleFrom, snapWindow, stampGeometry,
statsGeometry, teaserHits, teaserSeconds, teaserTitle, threadsGeometry,
- validateCutEdits, validatePosts, validateTeasers,
+ validateCutEdits, validatePosts, validateTeasers, fxGeometry, even as evenPx,
} from "./deck.mjs";
+// The effects region (`render.chrome.fx`, release 35): pure, in fx.mjs.
+import { fxOn, fxQuoteSpan, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs";
import { validateClaims } from "./factcheck.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
@@ -210,6 +212,9 @@ export { FFMPEG as FFMPEG_BIN, FFPROBE as FFPROBE_BIN };
let CUES = null;
// The manifest's own media (`src` clips): set by buildVideo() beside CUES.
let LOCAL = null;
+// The channels tree the build reads local media from (sources.mjs
+// channelsDirFor), for the effects' words: set by buildVideo() beside CUES.
+let FX_CHANNELS_DIR = null;
const exists = (p) => access(p).then(() => true, () => false);
@@ -2990,8 +2995,9 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts
// "stamp"`) are whole-cut sequences like the deck's, laid exactly as the
// deck's is.
// The stats region (`name: "stats"`) likewise.
+ // The effects region (`name: "fx"`) likewise.
const deck = r.name === "deck" || r.name === "feed" || r.name === "stamp" || r.name === "threads" || r.name === "flips" ||
- r.name === "stats";
+ r.name === "stats" || r.name === "fx";
const posts = r.name === "posts";
inputs.push(
...(deck || posts ? ["-reinit_filter", "0"] : []),
@@ -3072,6 +3078,11 @@ export function statsRegion(render, frames, schedule) {
return { name: "stats", frames, ...statsGeometry(render, { feed: schedule.layout === "feed" }) };
}
+/** The effects region as an overlay region: its frames over the footage box (fxGeometry). */
+export function fxRegion(render, frames, schedule) {
+ return { name: "fx", frames, ...fxGeometry(render, { feed: schedule.layout === "feed" }) };
+}
+
/**
* Where each rendered chrome region sits in the frame.
*
@@ -3400,10 +3411,21 @@ async function buildChartSegment(card, render, outDir, ledger) {
export function segmentJoins(schedule) {
if (!schedule?.segments) return null;
const moves = new Map((schedule.moves ?? []).map((m) => [m.segment, m]));
- const joins = schedule.segments.map((s) => {
+ // A THEN/NOW pair's cut is a wipe (fx.mjs `thenNow`): on the THEN segment's
+ // join, for the transition out of it. Only when a pair asks.
+ // A whip cut (fx.mjs `whip`) likewise, where no wipe is; a punch-in
+ // (`punchIn`) on the segment it zooms. Only when the effects ask.
+ const wipes = fxWipeJoins(schedule);
+ const whips = fxWhipJoins(schedule);
+ const zooms = fxZoomJoins(schedule);
+ const joins = schedule.segments.map((s, i) => {
const hold = s.hold > 0 ? s.hold : 0;
const move = moves.get(s.id) ?? null;
- return hold || move ? { hold, move } : null;
+ let j = hold || move ? { hold, move } : null;
+ if (wipes.has(i)) j = { hold: 0, move: null, ...(j ?? {}), wipe: true };
+ else if (whips.has(i)) j = { hold: 0, move: null, ...(j ?? {}), whip: true };
+ if (zooms.has(i)) j = { hold: 0, move: null, ...(j ?? {}), zoom: zooms.get(i) };
+ return j;
});
return joins.some(Boolean) ? joins : null;
}
@@ -3546,6 +3568,14 @@ export const endFadeAudioFilter = (fade, render) => {
export function joinInputChain(i, join, render) {
if (!join) return { parts: [], v: `[${i}:v]`, a: `[${i}:a]` };
const parts = [];
+ // The punch-ins first, in the segment's own clock (before a hold clones
+ // its last frame): each a crop of the footage box scaled back over it.
+ let vin = `[${i}:v]`;
+ if (join.zoom?.length) {
+ const z = punchInParts(i, join.zoom, render, vin);
+ parts.push(...z.parts);
+ vin = z.v;
+ }
// Picture: hold, move, end fade. Sound: mute, hold, end fade, dip -- the
// mute is in the clip's own clock and the hold is silence anyway; the end
// fade (the last segment) and the dip (one before a teaser that dips) are
@@ -3555,8 +3585,8 @@ export function joinInputChain(i, join, render) {
join.move ? moveFilter(join.move, render) : null,
join.fade ? endFadeVideoFilter(join.fade, render) : null,
].filter(Boolean);
- const v = vf.length ? `[j${i}v]` : `[${i}:v]`;
- if (vf.length) parts.push(`[${i}:v]${vf.join(",")}${v}`);
+ const v = vf.length ? `[j${i}v]` : vin;
+ if (vf.length) parts.push(`${vin}${vf.join(",")}${v}`);
const af = [
join.mute != null ? muteAudioFilter(join.mute) : null,
join.hold > 0 ? holdAudioFilter(join.hold) : null,
@@ -3571,6 +3601,35 @@ export function joinInputChain(i, join, render) {
}
/**
+ * A segment's punch-ins (fx.mjs `punchIn`) as graph parts on input `vin`:
+ * for each, the footage box's central (or upper-third) 1/scale cropped and
+ * scaled back to the box, laid over it from `at` to `until` (segment
+ * seconds). A snap, whole frames either side; everything outside the box --
+ * the ground the deck framing left -- is untouched.
+ *
+ * @returns {{ parts: string[], v: string }}
+ */
+export function punchInParts(i, zooms, render, vin) {
+ const parts = [];
+ let lab = vin;
+ zooms.forEach((z, k) => {
+ // The box the schedule drew the effects over (the feed's, the rail's), else the deck's.
+ const b = z.box ?? deckGeometry(render).footage;
+ const w = evenPx(b.width / z.scale), h = evenPx(b.height / z.scale);
+ const x = b.x + Math.round((b.width - w) / 2);
+ const y = b.y + Math.round((b.height - h) * (z.anchor === "center" ? 0.5 : 0.25));
+ const out = `[j${i}z${k}]`;
+ parts.push(
+ `${lab}split=2[j${i}z${k}a][j${i}z${k}b]`,
+ `[j${i}z${k}b]crop=${w}:${h}:${x}:${y},scale=${b.width}:${b.height}:flags=lanczos,setsar=1[j${i}z${k}c]`,
+ `[j${i}z${k}a][j${i}z${k}c]overlay=${b.x}:${b.y}:enable='between(t,${exprNum(z.at)},${exprNum(z.until)})'${out}`,
+ );
+ lab = out;
+ });
+ return { parts, v: lab };
+}
+
+/**
* The joins with the cut's edits merged in: a `muteFrom` (`mutes`: segment
* index → segment seconds), the end fade on the LAST segment
* (`fade`: `{ seconds, lastFrame }`) and a dip on the segment BEFORE a teaser
@@ -3751,7 +3810,12 @@ export function xfadeGraph(durs, D, joins = null, render = null, { joined = fals
// would blend the footage with the teaser's black lead and darken it
// faster than the deck and feed drawn over it, which only the dip fades.
const dip = !!joins?.[i - 1]?.dip;
- const vx = dip ? "transition=custom:expr='A'" : "transition=fade";
+ // A THEN/NOW pair's cut (fx.mjs `thenNow`): the NOW clip wipes in from the
+ // right, its edge at x = W·(1 − p) -- where the effects' divider rides.
+ const wipe = !dip && !!joins?.[i - 1]?.wipe;
+ // A whip cut (fx.mjs `whip`): the NOW clip slides in as the last slides out.
+ const whip = !dip && !wipe && !!joins?.[i - 1]?.whip;
+ const vx = dip ? "transition=custom:expr='A'" : wipe ? "transition=wipeleft" : whip ? "transition=slideleft" : "transition=fade";
const ax = dip ? "c1=nofade:c2=nofade" : "c1=tri:c2=tri";
parts.push(`${vlab}${ins[i].v}xfade=${vx}:duration=${D}:offset=${off.toFixed(3)}[v${i}]`);
parts.push(`${alab}${ins[i].a}acrossfade=d=${D}:${ax}[a${i}]`);
@@ -3871,7 +3935,11 @@ export function xfadeBatchLengths(durs, D, batches) {
* untouched); the segments' own chains were applied inside the batch.
*/
export function xfadeBatchJoins(joins, batches) {
- const out = batches.map(({ to }) => (joins?.[to - 1]?.dip ? { dip: joins[to - 1].dip } : null));
+ const out = batches.map(({ to }) => {
+ const j = joins?.[to - 1];
+ if (!j?.dip && !j?.wipe && !j?.whip) return null;
+ return { ...(j.dip ? { dip: j.dip } : {}), ...(j.wipe ? { wipe: true } : {}), ...(j.whip ? { whip: true } : {}) };
+ });
return out.some(Boolean) ? out : null;
}
@@ -4312,6 +4380,28 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
regions.push(statsRegion(render, sr.frames, schedule));
}
+ // The effects (a schedule with `fx`, fx.mjs): one sequence for the whole cut
+ // -- or the deck's window -- exactly over the footage box, laid over the
+ // stats.
+ if (schedule.fx) {
+ EMIT("chrome", { phase: "compose", region: "fx", ...(duration != null ? { from, duration } : {}) });
+ const t1 = Date.now();
+ const fr = await composeChrome({
+ manifestPath, outDir, variant, region: "fx", doRender: true,
+ fps: render.fps, workers: 4, quality: "high", format: "png-sequence",
+ ...(duration != null ? { from, duration } : {}),
+ });
+ if (fr.frameCount !== want) {
+ throw new Error(`the effects' sequence is ${fr.frameCount} frames but the deck's is ${want}`);
+ }
+ EMIT("chrome", {
+ phase: fr.cached ? "cached" : "render", region: "fx",
+ frames: fr.frameCount, key: fr.key, dir: fr.frames,
+ seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ });
+ regions.push(fxRegion(render, fr.frames, schedule));
+ }
+
// The thread rail (a schedule with `threads`): one sequence for the whole
// cut -- or the deck's window -- beside the footage, laid like the deck's.
if (schedule.threads?.threads?.length) {
@@ -4473,9 +4563,55 @@ export async function measureChromeSchedule({ manifest, entries, segments, D })
}
metas.push(await clipMeta(e, provenance).catch(() => null));
}
+ // The effects' words (render.chrome.fx): read only when an effect is on, so
+ // a cut without them measures exactly what it did.
+ const fx = fxOn(render) ? await fxClipWords({ entries, segments, provenance, render }) : null;
// The variant's posts, placed on the clips this cut plays with their real
// upload dates. A manifest without posts writes the schedule it always did.
- return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null });
+ return deckSchedule({
+ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null,
+ ...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}),
+ });
+}
+
+/**
+ * Each clip's timed words for the effects (fx.mjs), in its SEGMENT's seconds:
+ * whisper.cpp's words when the corpus keeps them (transcript.json), else its
+ * cues split into words by character position -- the words said in its cited
+ * span (fxQuoteSpan). `clock` is the source second each clip's segment starts
+ * at: its cut record's (the build snaps the cut to a silence), else the play
+ * window's. A clip whose words cannot be read has none: its quote falls back
+ * to its `quote` (fxQuoteFallback).
+ */
+export async function fxClipWords({ entries, segments, provenance = {}, render }) {
+ const words = new Map();
+ const clock = new Map();
+ for (let i = 0; i < entries.length; i += 1) {
+ const e = entries[i];
+ if (e.type !== "clip") continue;
+ const rec = segments[i] ? await readCutRecord(segments[i]).catch(() => null) : null;
+ const from = Number.isFinite(rec?.start) ? rec.start : playWindow(e, render).from;
+ clock.set(e.id, from);
+ const span = fxQuoteSpan(e);
+ let got = null;
+ // The captions first when they mark who speaks (">>", a dash) and the
+ // kinetic line tells the voices apart: whisper.cpp's words carry no turns.
+ const cueWords = fxWordsOf(await montageCues(e, provenance), span.from - 0.05, span.to + 0.05);
+ if (resolveFx(render, "kineticQuote")?.speakers === "auto" && cueWords.some((w) => w.turn)) got = cueWords;
+ if (!got && !hasLocalMedia(e) && FX_CHANNELS_DIR && e.video) {
+ try {
+ const dir = await resolveVideoDir(FX_CHANNELS_DIR, e.channel ?? provenance.channelSlug, e.video);
+ const doc = JSON.parse(await readFile(path.join(dir, "transcript.json"), "utf8"));
+ const ws = whisperWords(doc, span.from, span.to);
+ if (ws) got = fxWordsOf(ws, span.from - 0.05, span.to + 0.05);
+ } catch {
+ got = null;
+ }
+ }
+ if (!got?.length) got = cueWords;
+ if (got.length) words.set(e.id, got.map((w) => ({ text: w.text, start: w.start - from, end: w.end - from, ...(w.turn ? { turn: true } : {}) })));
+ }
+ return { words, clock };
}
// Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`,
@@ -4593,6 +4729,7 @@ export function concatRecordText(segments, joins = null) {
...(joins[i].mute != null ? { mute: joins[i].mute } : {}),
...(joins[i].fade ? { fade: joins[i].fade } : {}),
...(joins[i].dip ? { dip: joins[i].dip } : {}),
+ ...(joins[i].zoom ? { zoom: joins[i].zoom } : {}),
})}`]
: []));
return list + lines.join("\n") + "\n";
@@ -4716,7 +4853,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), ...validateMontage(whole), ...validateAssist(whole),
+ ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -4786,6 +4923,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
dirs.local = localSources({
rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe,
});
+ FX_CHANNELS_DIR = channelsDir;
// A project's out/ first, through ensureOutDir: with UMTOOL_MEDIA_DIR set it
// is a link to the media root, and the recursive mkdirs below would
diff --git a/umtool/report-to-video/chrome-fx.mjs b/umtool/report-to-video/chrome-fx.mjs
@@ -0,0 +1,744 @@
+// The EFFECTS region's composition (release 35, lane O2): one HyperFrames page
+// for a whole report cut, exactly the footage box (deck.mjs fxGeometry),
+// transparent but for the effects fx.mjs schedules -- the kinetic quote, the
+// redaction, the odometer, the scrubber, the glitch, the THEN/NOW wipe, the
+// receipts and the zoom. Overlays on the evidence, never cards: nothing here
+// covers the whole picture for longer than a glitch's half second.
+//
+// PURE, like chrome-stats.mjs: a schedule and a render block in, an HTML string
+// out. compose-chrome.mjs copies the assets in beside it (the faces, the
+// screenshots, the scrubber's thumbnails), writes it and renders it
+// (`region: "fx"`); the build lays the frames over the cut after the stats.
+//
+// SEEK-SAFE. A render is a seek per frame from parallel workers in any order,
+// so the timeline is a list of cues computed here (fx.mjs compileCues), each
+// stating its `from`; nothing is rewritten by a callback and nothing measures
+// the page: every size is in the data (a screenshot's pixels are read by
+// compose-chrome before the page is written). The glitch's noise is a seeded
+// generator's (fxRandom), so frame 412 is the same tear on every worker.
+import { fileURLToPath } from "node:url";
+
+import { fxGeometry, pageDuration } from "./deck.mjs";
+import { mix, rgba } from "./chrome-deck.mjs";
+import { FX_MOTION, INSTANT, compileCues, fxRandom, noNegZero } from "./fx.mjs";
+
+const esc = (s) =>
+ String(s ?? "")
+ .replace(/&/g, "&")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, """);
+
+// `|| 0`: no -0 in the data (a JSON round trip makes it 0, and a cue list must survive one).
+const r2 = (v) => Math.round(v * 100) / 100 || 0;
+const r4 = (v) => Math.round(v * 10000) / 10000 || 0;
+
+/** The VHS stamp's mono, vendored beside the brand's faces; copied in as `assets/FxMono.ttf`. */
+export const FX_MONO_FILE = fileURLToPath(new URL("./fonts/IBMPlexMono-Bold.ttf", import.meta.url));
+
+/** THEN's colour when the palette names none (`palette.then`), as the flips panel's. */
+export const FX_THEN_COLOR = "#6fa8dc";
+
+/** The glitch's colours: a red and a cyan channel, and the tear's white. */
+export const FX_GLITCH_COLORS = Object.freeze(["rgba(255, 40, 70, 0.62)", "rgba(40, 230, 255, 0.58)", "rgba(255, 255, 255, 0.5)", "rgba(0, 0, 0, 0.55)"]);
+
+/** The receipts' resting tilt, card by card (degrees). */
+export const FX_FAN = Object.freeze([-4, 3, -2, 5]);
+
+/**
+ * Where a scrubber tick sits: its day on the rail, x0..x1 (region pixels).
+ */
+export const railX = (day, from, to, x0, x1) => x0 + ((day - from) / Math.max(1e-9, to - from)) * (x1 - x0);
+
+/**
+ * The odometer's cell for one column: cell 0 is blank (a leading column the
+ * number does not reach), cell d+1 is digit d, cell 11 is the 0 a 9 rolls on to.
+ */
+export function odoCells(value, digits) {
+ const s = String(value).padStart(digits, " ");
+ return [...s.slice(-digits)].map((ch) => (ch === " " ? 0 : Number(ch) + 1));
+}
+
+/**
+ * The zoom's push: the scale and offset (transform-origin top-left) that put
+ * the focus box's centre in the card's centre at `fill` of the card.
+ */
+export function zoomPush(focus, cardW, cardH, fill = 0.86) {
+ const fw = (focus[2] - focus[0]) * cardW, fh = (focus[3] - focus[1]) * cardH;
+ const s = Math.max(1, fill * Math.min(cardW / fw, cardH / fh));
+ const cx = ((focus[0] + focus[2]) / 2) * cardW, cy = ((focus[1] + focus[3]) / 2) * cardH;
+ return { scale: r4(s), x: r2(cardW / 2 - s * cx), y: r2(cardH / 2 - s * cy) };
+}
+
+/** A card's size in the region: `width` wide by the shot's aspect, no taller than `maxH`. */
+export function cardSize(dims, width, maxH) {
+ const aspect = dims && dims.w > 0 && dims.h > 0 ? dims.h / dims.w : 0.75;
+ let w = Math.round(width), h = Math.round(width * aspect);
+ if (h > maxH) {
+ h = Math.round(maxH);
+ w = Math.round(maxH / aspect);
+ }
+ return { w, h };
+}
+
+/**
+ * Everything the effects do, as elements and events. Returns the page's body
+ * markup, its init states and its cues. `assets` = `{ shots: {[path]: {src, w, h}},
+ * thumbs: {[segment]: src} }`.
+ */
+export function fxPlan(schedule, render, assets = {}) {
+ const fx = schedule.fx;
+ if (!fx) throw new Error("fx: the schedule draws no effects");
+ const geo = fxGeometry(render, { feed: schedule.layout === "feed" });
+ const W = geo.width, H = geo.height;
+ const pal = render.palette;
+ const k = W / 1574;
+ const px = (v) => Math.max(1, Math.round(v * k));
+ const fps = schedule.fps ?? render.fps ?? 30;
+ const frame = 1 / fps;
+ const init = {};
+ const ev = [];
+ const html = [];
+ const add = (key, at, dur, to, ease = "none") => ev.push({ k: key, at, dur, to, ease });
+ const set = (key, at, to) => add(key, at, INSTANT, to);
+ const shots = assets.shots ?? {};
+ const thumbs = assets.thumbs ?? {};
+ const thenC = /^#[0-9a-fA-F]{6}$/.test(pal.then ?? "") ? pal.then : FX_THEN_COLOR;
+
+ // ---- the scrubber (drawn first: under everything) -----------------------
+ if (fx.scrubber) {
+ const s = fx.scrubber;
+ const top = s.position === "top";
+ // The rail keeps clear of the odometer when it sits in a corner on the
+ // rail's edge of the box.
+ const odo = fx.odometer;
+ const odoW = odo ? px(36) + odo.digits * px(58) + px(28) + px(24) : 0;
+ const odoSide = odo && odo.position.startsWith(top ? "top" : "bottom") ? odo.position.split("-")[1] : null;
+ const x0 = odoSide === "left" ? odoW + px(24) : px(64);
+ const x1 = odoSide === "right" ? W - odoW - px(24) : W - px(64);
+ const railY = top ? px(38) : H - px(38);
+ const X = (day) => r2(railX(day, s.from, s.to, x0, x1));
+ const thumbW = px(196), thumbH = Math.round((thumbW * 9) / 16);
+ init.scr = { autoAlpha: 0 };
+ for (const sp of s.spans) {
+ add("scr", sp.in, Math.min(0.35, (sp.out - sp.in) / 2), { autoAlpha: 1 }, "power2.out");
+ add("scr", Math.max(sp.in, sp.out - 0.3), Math.min(0.3, (sp.out - sp.in) / 2), { autoAlpha: 0 }, "power1.in");
+ }
+ const years = s.years.map((y) =>
+ `<div class="sc-year" style="left:${X(y.day)}px"><span>${y.year}</span></div>`).join("");
+ const ticks = s.ticks.map((t, n) => {
+ const key = `sct${n}`;
+ init[key] = { autoAlpha: 0.4, scale: 1 };
+ add(key, t.in, 0.25, { autoAlpha: 1, scale: 1.7 }, "back.out(3)");
+ add(key, Math.max(t.in + 0.25, t.out - 0.2), 0.2, { autoAlpha: 0.85, scale: 1 }, "power1.out");
+ return `<div class="sc-tick" data-k="${key}" style="left:${X(t.day)}px"></div>`;
+ }).join("");
+ // The playhead and its thumbnail ride together; each clip's picture and
+ // date hand over at the clip's in.
+ init.sch = { x: X(s.ticks[0].day) };
+ s.ticks.forEach((t, n) => {
+ if (n === 0) return;
+ add("sch", t.in - FX_MOTION.rail / 2, FX_MOTION.rail, { x: X(t.day) }, "power3.inOut");
+ });
+ const cards = s.ticks.map((t, n) => {
+ const key = `scc${n}`;
+ init[key] = { autoAlpha: 0, y: top ? -10 : 10 };
+ add(key, t.in, FX_MOTION.thumb, { autoAlpha: 1, y: 0 }, "power2.out");
+ add(key, Math.max(t.in + FX_MOTION.thumb, t.out - FX_MOTION.thumb), FX_MOTION.thumb, { autoAlpha: 0, y: top ? -6 : 6 }, "power1.in");
+ const img = s.thumbs && thumbs[t.segment]
+ ? `<img src="${esc(thumbs[t.segment])}" width="${thumbW}" height="${thumbH}" alt="">` : "";
+ return `<div class="sc-card${img ? "" : " bare"}" data-k="${key}" data-segment="${esc(t.segment)}">${img}<div class="sc-date">${esc(t.label)}</div></div>`;
+ }).join("");
+ html.push(
+ `<div class="fx-scrubber ${top ? "top" : "bottom"}" data-k="scr">` +
+ `<div class="sc-band"></div><div class="sc-rail" style="left:${x0}px; width:${x1 - x0}px; top:${railY}px"></div>` +
+ `<div class="sc-marks" style="top:${railY}px">${years}${ticks}</div>` +
+ `<div class="sc-head" data-k="sch" style="top:${railY}px"><div class="sc-diamond"></div>` +
+ `<div class="sc-cards ${top ? "below" : "above"}">${cards}</div></div>` +
+ `</div>`,
+ );
+ }
+
+ // ---- receipts ------------------------------------------------------------------
+ if (fx.receipts) {
+ const rc = fx.receipts;
+ const right = rc.position !== "left";
+ const baseW = rc.width * W;
+ rc.clips.forEach((row, r) => {
+ const n = row.cards.length;
+ const cardsHtml = row.cards.map((c, j) => {
+ const key = `rc${r}_${j}`;
+ const dims = shots[c.shot] ?? null;
+ const { w, h } = cardSize(dims, baseW, H * 0.74);
+ const rot = FX_FAN[j % FX_FAN.length];
+ const restX = (right ? -1 : 1) * j * px(22);
+ const restY = j * px(26) - ((n - 1) * px(26)) / 2;
+ const left = right ? W - px(48) - w : px(48);
+ const top = Math.round((H - h) / 2);
+ const off = (right ? 1 : -1) * (w + px(140) + (right ? W - left - w : left));
+ init[key] = { x: r2(restX + off), y: r2(restY + px(40)), rotation: rot + (right ? 14 : -14), autoAlpha: 1 };
+ add(key, c.at, FX_MOTION.fan, { x: r2(restX), y: r2(restY), rotation: rot }, "power3.out");
+ add(key, row.out - 0.38 + (n - 1 - j) * 0.06, 0.32, { x: r2(restX + off), rotation: rot + (right ? 10 : -10) }, "power2.in");
+ let marker = "";
+ if (c.mark) {
+ const mk = `rcm${r}_${j}`;
+ const [a, b, cc, d] = c.mark;
+ init[mk] = { scaleX: 0 };
+ add(mk, row.markAt + j * 0.12, FX_MOTION.marker, { scaleX: 1 }, "power2.inOut");
+ marker = `<div class="rc-mark" data-k="${mk}" style="left:${r2(a * 100)}%; top:${r2(b * 100)}%; width:${r2((cc - a) * 100)}%; height:${r2((d - b) * 100)}%"></div>`;
+ }
+ const src = dims?.src ?? "";
+ return `<div class="rc-card" data-k="${key}" style="left:${left}px; top:${top}px; width:${w}px; height:${h}px">` +
+ (src ? `<img src="${esc(src)}" width="${w}" height="${h}" alt="">` : "") + marker + `</div>`;
+ }).join("");
+ html.push(`<div class="fx-receipts" data-segment="${esc(row.segment)}">${cardsHtml}</div>`);
+ });
+ }
+
+ // ---- the zoom -----------------------------------------------------------------
+ if (fx.zoom) {
+ fx.zoom.clips.forEach((row, z) => {
+ const dims = shots[row.shot] ?? null;
+ const { w, h } = cardSize(dims, fx.zoom.width * W, H * 0.84);
+ const left = Math.round((W - w) / 2), top = Math.round((H - h) / 2);
+ const card = `zc${z}`, inner = `zi${z}`, box = `zo${z}`;
+ init[card] = { autoAlpha: 0, y: px(36), scale: 0.94 };
+ add(card, row.in, 0.38, { autoAlpha: 1, y: 0, scale: 1 }, "back.out(1.4)");
+ add(card, row.out - 0.3, 0.3, { autoAlpha: 0, scale: 0.97 }, "power1.in");
+ init[box] = { autoAlpha: 0, scale: 1.35 };
+ add(box, row.outline, FX_MOTION.outline, { autoAlpha: 1, scale: 1 }, "power3.out");
+ const p = zoomPush(row.focus, w, h);
+ init[inner] = { x: 0, y: 0, scale: 1 };
+ add(inner, row.push, FX_MOTION.push, { x: p.x, y: p.y, scale: p.scale }, "power2.inOut");
+ // Then a slow drift on the detail until it leaves, so the held frame
+ // still breathes. About the focus centre: the offsets move with the scale.
+ const drift = Math.max(0, row.out - 0.3 - (row.push + FX_MOTION.push));
+ if (drift > 0.4) {
+ const s2 = r4(p.scale * 1.04);
+ const cx = ((row.focus[0] + row.focus[2]) / 2) * w, cy = ((row.focus[1] + row.focus[3]) / 2) * h;
+ add(inner, row.push + FX_MOTION.push, drift, { x: r2(w / 2 - s2 * cx), y: r2(h / 2 - s2 * cy), scale: s2 }, "none");
+ }
+ const [a, b, c, d] = row.focus;
+ const src = dims?.src ?? "";
+ html.push(
+ `<div class="fx-zoom" data-k="${card}" data-segment="${esc(row.segment)}" style="left:${left}px; top:${top}px; width:${w}px; height:${h}px">` +
+ `<div class="zm-inner" data-k="${inner}" style="width:${w}px; height:${h}px">` +
+ (src ? `<img src="${esc(src)}" width="${w}" height="${h}" alt="">` : "") +
+ `<div class="zm-box" data-k="${box}" style="left:${r2(a * 100)}%; top:${r2(b * 100)}%; width:${r2((c - a) * 100)}%; height:${r2((d - b) * 100)}%"></div>` +
+ `</div>` +
+ `</div>`,
+ );
+ });
+ }
+
+ // ---- the line: kinetic or redacted --------------------------------------------
+ for (const [qi, q] of (fx.quotes ?? []).entries()) {
+ const kinetic = q.style === "kinetic";
+ const cfg = kinetic ? schedule.fx.quoteStyle?.kinetic : schedule.fx.quoteStyle?.redact;
+ const size = px(cfg?.size ?? (kinetic ? 54 : 44));
+ const posTop = (cfg?.position ?? "bottom") === "top";
+ q.pages.forEach((pg, p) => {
+ const pk = `qp${qi}_${p}`;
+ if (kinetic) {
+ init[pk] = { autoAlpha: 0, y: px(14) };
+ add(pk, pg.in, FX_MOTION.page, { autoAlpha: 1, y: 0 }, "power2.out");
+ add(pk, Math.max(pg.in + FX_MOTION.page, pg.out - FX_MOTION.page), FX_MOTION.page, { autoAlpha: 0, y: -px(10) }, "power1.in");
+ } else {
+ init[pk] = { autoAlpha: 0, rotation: -3, scale: 0.94 };
+ add(pk, pg.in, 0.3, { autoAlpha: 1, rotation: -1.2, scale: 1 }, "back.out(1.6)");
+ add(pk, Math.max(pg.in + 0.3, pg.out - FX_MOTION.page), FX_MOTION.page, { autoAlpha: 0, rotation: -0.6, scale: 0.98 }, "power1.in");
+ }
+ const words = pg.words.map((w, j) => {
+ const wk = `qw${qi}_${p}_${j}`;
+ if (kinetic) {
+ if (w.punch) {
+ init[wk] = { autoAlpha: 0, scale: 1.8, y: 0 };
+ add(wk, w.at, FX_MOTION.punch, { autoAlpha: 1, scale: 1 }, "back.out(2.6)");
+ const uk = `qu${qi}_${p}_${j}`;
+ init[uk] = { scaleX: 0 };
+ add(uk, w.at + 0.06, 0.22, { scaleX: 1 }, "power3.out");
+ return `<span class="w punch" data-k="${wk}">${esc(w.text)}<i class="u" data-k="${uk}"></i></span>`;
+ }
+ init[wk] = { autoAlpha: 0, y: Math.round(size * 0.45), scale: 1 };
+ add(wk, w.at, FX_MOTION.word, { autoAlpha: 1, y: 0 }, "power3.out");
+ return `<span class="w" data-k="${wk}">${esc(w.text)}</span>`;
+ }
+ const bk = `qb${qi}_${p}_${j}`;
+ init[bk] = { autoAlpha: 1, x: 0, y: 0, rotation: 0 };
+ add(bk, w.at, FX_MOTION.bar, { autoAlpha: 0, x: px(8), y: -px(20), rotation: -7 }, "power2.in");
+ let hl = "";
+ if (w.punch) {
+ const hk = `qh${qi}_${p}_${j}`;
+ init[hk] = { scaleX: 0 };
+ add(hk, w.at + 0.12, 0.26, { scaleX: 1 }, "power2.out");
+ hl = `<i class="hl" data-k="${hk}"></i>`;
+ }
+ return `<span class="w${w.punch ? " punch" : ""}">${hl}<span class="t">${esc(w.text)}</span><i class="bar" data-k="${bk}"></i></span>`;
+ }).join(" ");
+ // Two voices: each on its own side, in its own colour, with its label
+ // (the manifest's; none by default -- which voice, never whose).
+ const voices = schedule.fx.quoteStyle?.voices;
+ const vi = kinetic && voices && Number.isInteger(pg.speaker) ? pg.speaker : null;
+ const voice = vi != null ? voices[vi] : null;
+ const vstyle = voice?.color ? ` --vc:${voice.color};` : "";
+ const vlabel = voice?.label ? `<div class="q-voice">${esc(voice.label)}</div>` : "";
+ html.push(
+ `<div class="fx-quote ${kinetic ? "kinetic" : "redact"} ${posTop ? "top" : "bottom"}${vi != null ? ` voice v${vi}` : ""}" data-k="${pk}" data-segment="${esc(q.segment)}"${vi != null ? ` data-voice="${vi}"` : ""} style="font-size:${size}px;${vstyle}">` +
+ `<div class="q-inner">${vlabel}${words}</div></div>`,
+ );
+ });
+ }
+
+ // ---- the odometer ----------------------------------------------------------------
+ if (fx.odometer) {
+ const o = fx.odometer;
+ const digits = o.digits;
+ const cellH = px(92);
+ init.odc = { autoAlpha: 0, scale: 0.9 };
+ for (const sp of o.spans) {
+ add("odc", sp.in, Math.min(0.35, (sp.out - sp.in) / 2), { autoAlpha: 1, scale: 1 }, "back.out(1.8)");
+ add("odc", Math.max(sp.in, sp.out - 0.3), Math.min(0.3, (sp.out - sp.in) / 2), { autoAlpha: 0, scale: 0.94 }, "power1.in");
+ }
+ const first = odoCells(o.counts[0]?.prev ?? 0, digits);
+ const cols = first.map((cell, c) => {
+ const key = `odd${c}`;
+ init[key] = { y: -cell * cellH };
+ return key;
+ });
+ init.odp = { autoAlpha: 0, scale: 1 };
+ for (const cnt of o.counts) {
+ if (cnt.value === cnt.prev) continue;
+ const from = odoCells(cnt.prev, digits), to = odoCells(cnt.value, digits);
+ cols.forEach((key, c) => {
+ if (from[c] === to[c]) return;
+ if (to[c] < from[c] && to[c] === 1) {
+ // 9 → 0 rolls on to the second 0, then snaps back to the first.
+ add(key, cnt.at, FX_MOTION.roll, { y: -11 * cellH }, "back.out(1.3)");
+ set(key, cnt.at + FX_MOTION.roll + frame, { y: -1 * cellH });
+ } else {
+ add(key, cnt.at, FX_MOTION.roll, { y: -to[c] * cellH }, "back.out(1.3)");
+ }
+ });
+ set("odp", cnt.at, { autoAlpha: 0.9, scale: 1 });
+ add("odp", cnt.at + frame, 0.5, { autoAlpha: 0, scale: 1.35 }, "power2.out");
+ }
+ const cells = Array.from({ length: 12 }, (_, i) =>
+ `<span class="od-cell">${i === 0 ? " " : i === 11 ? "0" : String(i - 1)}</span>`).join("");
+ const [v, hpos] = o.position.split("-");
+ html.push(
+ `<div class="fx-odo ${v} ${hpos}" data-k="odc"><div class="od-pulse" data-k="odp"></div>` +
+ `<div class="od-digits" style="height:${cellH}px">${cols.map((key) => `<span class="od-col"><span class="od-strip" data-k="${key}">${cells}</span></span>`).join("")}</div>` +
+ (o.label ? `<div class="od-label">${esc(o.label)}</div>` : "") +
+ `</div>`,
+ );
+ }
+
+ // ---- the punch-in: a flash and a viewfinder as the footage snaps in -------------
+ if (fx.punchIn) {
+ fx.punchIn.punches.forEach((pn, n) => {
+ const fk = `pf${n}`, bk = `pb${n}`;
+ init[fk] = { autoAlpha: 0 };
+ set(fk, pn.at, { autoAlpha: 0.32 });
+ add(fk, pn.at + frame, 0.14, { autoAlpha: 0 }, "power2.out");
+ init[bk] = { autoAlpha: 0, scale: 1.12 };
+ set(bk, pn.at, { autoAlpha: 1, scale: 1.12 });
+ add(bk, pn.at + frame, 0.22, { scale: 1 }, "power3.out");
+ add(bk, Math.max(pn.at + 0.3, pn.until - 0.2), 0.2, { autoAlpha: 0 }, "power1.in");
+ html.push(
+ `<div class="fx-punch" data-segment="${esc(pn.segment)}"><div class="pi-flash" data-k="${fk}"></div>` +
+ `<div class="pi-frame" data-k="${bk}"><i class="tl"></i><i class="tr"></i><i class="bl"></i><i class="br"></i></div></div>`,
+ );
+ });
+ }
+
+ // ---- the whip: speed streaks across the cut ------------------------------------
+ if (fx.whip) {
+ fx.whip.cuts.forEach((wc, n) => {
+ const rnd = fxRandom(7919 * (n + 3));
+ const streaks = [];
+ for (let j = 0; j < 9; j += 1) {
+ const key = `ws${n}_${j}`;
+ const y = Math.round(rnd() * (H - px(20)));
+ const h = Math.round(px(3) + rnd() * px(16));
+ const len = Math.round(W * (0.35 + rnd() * 0.5));
+ const delay = rnd() * wc.seconds * 0.3;
+ // Each streak enters a third of the way in and rakes off the left,
+ // fastest at the middle of the cut.
+ const x0 = Math.round(W - len * 0.35);
+ init[key] = { autoAlpha: 0, x: x0 };
+ set(key, wc.at + delay, { autoAlpha: 0.9 });
+ add(key, wc.at + delay + frame / 4, Math.max(frame, wc.seconds - delay), { x: -len - px(40) }, "sine.inOut");
+ set(key, wc.at + wc.seconds + frame, { autoAlpha: 0, x: x0 });
+ streaks.push(`<div class="wh-streak" data-k="${key}" style="top:${y}px; height:${h}px; width:${len}px"></div>`);
+ }
+ html.push(`<div class="fx-whip" data-segment="${esc(wc.segment)}">${streaks.join("")}</div>`);
+ });
+ }
+
+ // ---- THEN / NOW ----------------------------------------------------------------
+ if (fx.thenNow) {
+ const fw = render.width ?? 1920;
+ fx.thenNow.wipes.forEach((wp, n) => {
+ // With the cut's own wipe the divider rides xfade's edge, x = W(1 − p)
+ // in the FRAME, linear; else it sweeps the box from just past its right
+ // edge to just past its left.
+ const x0 = wp.real ? fw - geo.x : W + px(20);
+ const x1 = wp.real ? -geo.x : -px(20);
+ const a = wp.at, d = wp.seconds;
+ const xAt = (t) => x0 + ((x1 - x0) * (t - a)) / d;
+ const tAt = (x) => a + (d * (x0 - x)) / (x0 - x1);
+ const edge = px(28);
+ const scrim = `tns${n}`, div = `tnd${n}`, tw = `tnt${n}`, nw = `tnn${n}`;
+ init[scrim] = { autoAlpha: 0, width: W };
+ add(scrim, a - 0.35, 0.35, { autoAlpha: 1 }, "power1.out");
+ // The scrim is the box left of the divider: whole until the divider
+ // enters the box, nothing once it has left.
+ const tIn = x0 > W ? tAt(W) : a;
+ const tOut = x1 < 0 ? tAt(0) : a + d;
+ add(scrim, tIn, Math.max(INSTANT, tOut - tIn), { width: 0 }, "none");
+ set(scrim, a + d + frame, { autoAlpha: 0, width: W });
+ init[div] = { autoAlpha: 0, x: r2(x0) };
+ set(div, a, { autoAlpha: 1 });
+ add(div, a + frame / 4, d - frame / 4, { x: r2(x1) }, "none");
+ set(div, a + d + frame, { autoAlpha: 0 });
+ // THEN rides the divider's left, held inside the box until the divider
+ // reaches it; NOW rides its right until the box's left edge stops it.
+ const tHold = W - edge;
+ init[tw] = { autoAlpha: 0, x: r2(Math.min(tHold, x0)) };
+ add(tw, a - 0.5, FX_MOTION.tag, { autoAlpha: 1 }, "power2.out");
+ const tStart = x0 > tHold ? tAt(tHold) : a;
+ add(tw, tStart, Math.max(INSTANT, a + d - tStart), { x: r2(x1) }, "none");
+ set(tw, a + d + frame, { autoAlpha: 0 });
+ const nStop = edge;
+ init[nw] = { autoAlpha: 0, x: r2(x0) };
+ set(nw, a, { autoAlpha: 1 });
+ const tStop = Math.min(a + d, tAt(nStop));
+ add(nw, a + frame / 4, Math.max(INSTANT, tStop - a - frame / 4), { x: r2(Math.max(nStop, xAt(tStop))) }, "none");
+ add(nw, a + d + FX_MOTION.hold, FX_MOTION.tag, { autoAlpha: 0 }, "power1.in");
+ html.push(
+ `<div class="fx-wipe" data-then="${esc(wp.then)}" data-now="${esc(wp.now)}">` +
+ `<div class="tn-scrim" data-k="${scrim}"></div>` +
+ `<div class="tn-div" data-k="${div}"></div>` +
+ `<div class="tn-tagw" data-k="${tw}"><div class="tn-tag then" style="--c:${thenC}"><b>THEN</b>${wp.thenDate ? `<span>${esc(wp.thenDate)}</span>` : ""}</div></div>` +
+ `<div class="tn-tagw" data-k="${nw}"><div class="tn-tag now" style="--c:${pal.accent}"><b>NOW</b>${wp.nowDate ? `<span>${esc(wp.nowDate)}</span>` : ""}</div></div>` +
+ `</div>`,
+ );
+ });
+ }
+
+ // ---- the glitch (drawn last: over everything) ------------------------------------
+ if (fx.glitch) {
+ fx.glitch.bursts.forEach((b, n) => {
+ const a = b.at - b.seconds / 2;
+ const steps = Math.max(3, Math.round((b.seconds * fps) / 2));
+ const stepDur = b.seconds / steps;
+ const rnd = fxRandom(9301 * (b.seed + 1));
+ const SL = 7;
+ const sk = `gs${n}`;
+ init[sk] = { autoAlpha: 0 };
+ const slices = [];
+ for (let j = 0; j < SL; j += 1) {
+ const key = `gl${n}_${j}`;
+ init[key] = { autoAlpha: 0, y: 0, x: 0, height: px(10) };
+ slices.push(`<div class="gl-slice" data-k="${key}" style="background:${FX_GLITCH_COLORS[j % FX_GLITCH_COLORS.length]}"></div>`);
+ }
+ const noise = [0, 1, 2].map((v) => {
+ const key = `gn${n}_${v}`;
+ init[key] = { autoAlpha: 0 };
+ return `<svg class="gl-noise" data-k="${key}" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg">` +
+ `<filter id="gnf${n}_${v}"><feTurbulence type="fractalNoise" baseFrequency="0.85 0.04" numOctaves="2" seed="${b.seed * 7 + v}"/>` +
+ `<feColorMatrix type="saturate" values="0"/></filter><rect width="100%" height="100%" filter="url(#gnf${n}_${v})"/></svg>`;
+ });
+ for (let s = 0; s < steps; s += 1) {
+ const t = a + s * stepDur;
+ // The tear is worst at the cut and settles either side of it.
+ const env = 1 - Math.abs((s + 0.5) / steps - 0.5) * 1.4;
+ set(sk, t, { autoAlpha: r2(0.35 + 0.5 * env) });
+ for (let v = 0; v < 3; v += 1) set(`gn${n}_${v}`, t, { autoAlpha: v === s % 3 ? r2(0.12 + 0.2 * env) : 0 });
+ for (let j = 0; j < SL; j += 1) {
+ const on = rnd() < 0.35 + 0.55 * env;
+ const hgt = Math.round(px(4) + rnd() * px(70) * env);
+ set(`gl${n}_${j}`, t, on
+ ? { autoAlpha: 1, y: Math.round(rnd() * (H - hgt)), x: Math.round((rnd() - 0.5) * px(160) * env), height: hgt }
+ : { autoAlpha: 0, y: 0, x: 0, height: px(10) });
+ }
+ }
+ const end = a + b.seconds;
+ set(sk, end, { autoAlpha: 0 });
+ for (let v = 0; v < 3; v += 1) set(`gn${n}_${v}`, end, { autoAlpha: 0 });
+ for (let j = 0; j < SL; j += 1) set(`gl${n}_${j}`, end, { autoAlpha: 0, y: 0, x: 0, height: px(10) });
+ let year = "";
+ if (b.year != null) {
+ const yk = `gy${n}`;
+ init[yk] = { autoAlpha: 0, x: 0, scale: 1.25 };
+ set(yk, b.at - stepDur, { autoAlpha: 1, x: px(-22), scale: 1.25 });
+ set(yk, b.at, { autoAlpha: 0.85, x: px(18), scale: 1.1 });
+ add(yk, b.at + stepDur, 0.18, { autoAlpha: 1, x: 0, scale: 1 }, "power3.out");
+ add(yk, end + 0.45, 0.25, { autoAlpha: 0, scale: 0.96 }, "power1.in");
+ year = `<div class="gl-year" data-k="${yk}">${b.year}</div>`;
+ }
+ let stamp = "";
+ if (fx.glitch.stamp && b.date) {
+ const vk = `gv${n}`;
+ init[vk] = { autoAlpha: 0 };
+ set(vk, b.at, { autoAlpha: 1 });
+ set(vk, b.at + 1.8, { autoAlpha: 0 });
+ stamp = `<div class="gl-vhs" data-k="${vk}"><span class="play">PLAY ▶</span><span>${esc(b.date.toUpperCase())}</span></div>`;
+ }
+ html.push(
+ `<div class="fx-glitch" data-segment="${esc(b.segment)}">${noise.join("")}<div class="gl-scan" data-k="${sk}"></div>${slices.join("")}${year}${stamp}</div>`,
+ );
+ });
+ }
+
+ const cues = compileCues(init, ev);
+ for (const key of Object.keys(init)) init[key] = noNegZero(init[key]);
+ return { W, H, k, init, cues, body: html.join("\n "), thenC };
+}
+
+/**
+ * The effects composition's HTML, for the whole cut -- or a window of it
+ * (`from`/`duration`, as the deck's). `fonts` = `{ regular, bold, mono }`;
+ * `assets` as `fxPlan`'s. `?still=<t>` and the preview's `deck:seek` take CUT
+ * seconds.
+ */
+export function fxHtml(schedule, render, opts = {}) {
+ const plan = fxPlan(schedule, render, opts.assets ?? {});
+ const { W, H, k } = plan;
+ const px = (v) => Math.max(1, Math.round(v * k));
+ const pal = render.palette;
+ const fonts = opts.fonts ?? {};
+ const gsapSrc = opts.gsap ?? "assets/gsap.min.js";
+ const total = schedule.total;
+ const from = Number(opts.from ?? 0);
+ const dur = opts.duration != null ? r4(Number(opts.duration)) : r4(total - from);
+ if (!(dur > 0)) throw new Error(`fx: nothing to render from ${from}s of a ${total}s cut`);
+ const windowed = from > 0 || Math.abs(dur - total) > 1e-6;
+ const fps = schedule.fps ?? render.fps ?? 30;
+ const data = {
+ total: r4(total),
+ window: windowed ? { from: r4(from), dur } : null,
+ keys: schedule.fx.keys,
+ init: plan.init,
+ cues: plan.cues,
+ };
+ const json = JSON.stringify(data).replace(/</g, "\\u003c");
+ const amber = pal.amber ?? "#ffc860";
+ const paper = "#f3efe4";
+ const ink = "#16130e";
+
+ return `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=${W}, height=${H}" />
+ <script src="${esc(gsapSrc)}"></script>
+ <style>
+ /* The deck's faces under the deck's private names, and a mono -- docs/quirks.md. */
+ @font-face { font-family: 'DeckSans'; font-weight: 400; font-style: normal; src: url('${esc(fonts.regular ?? "")}'); }
+ @font-face { font-family: 'DeckSansBold'; font-weight: 400; font-style: normal; src: url('${esc(fonts.bold ?? "")}'); }
+ @font-face { font-family: 'FxMono'; font-weight: 400; font-style: normal; src: url('${esc(fonts.mono ?? "")}'); }
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: transparent; }
+ body { font-family: 'DeckSans', sans-serif; font-synthesis: none; color: ${pal.fg};
+ -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; }
+ #root { position: relative; width: ${W}px; height: ${H}px; overflow: hidden; }
+ #fx-clip { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px; overflow: hidden; }
+ [data-k] { will-change: transform, opacity; }
+
+ /* The scrubber: a rail of days, a tick per clip, the playhead and its picture. */
+ .fx-scrubber { position: absolute; inset: 0; visibility: hidden; opacity: 0; }
+ .fx-scrubber .sc-band { position: absolute; left: 0; right: 0; height: ${px(150)}px; }
+ .fx-scrubber.top .sc-band { top: 0; background: linear-gradient(${rgba(pal.bg, 0.72)}, ${rgba(pal.bg, 0)}); }
+ .fx-scrubber.bottom .sc-band { bottom: 0; background: linear-gradient(${rgba(pal.bg, 0)}, ${rgba(pal.bg, 0.72)}); }
+ .sc-rail { position: absolute; height: ${px(3)}px; margin-top: -${px(1.5)}px; border-radius: 2px; background: ${rgba(pal.fg, 0.38)}; }
+ .sc-marks { position: absolute; left: 0; right: 0; height: 0; }
+ .sc-year { position: absolute; top: -${px(9)}px; width: 0; height: ${px(18)}px; border-left: ${px(2)}px solid ${rgba(pal.fg, 0.55)}; }
+ .sc-year span { position: absolute; left: ${px(6)}px; top: -${px(22)}px; font-family: 'DeckSansBold', sans-serif; font-size: ${px(17)}px;
+ letter-spacing: 0.08em; color: ${rgba(pal.fg, 0.75)}; font-variant-numeric: tabular-nums; }
+ .sc-tick { position: absolute; top: -${px(5)}px; width: ${px(10)}px; height: ${px(10)}px; margin-left: -${px(5)}px; border-radius: 50%;
+ background: ${pal.accent}; box-shadow: 0 0 ${px(8)}px ${rgba(pal.accent, 0.7)}; }
+ .sc-head { position: absolute; left: 0; width: 0; height: 0; }
+ .sc-diamond { position: absolute; left: -${px(9)}px; top: -${px(9)}px; width: ${px(18)}px; height: ${px(18)}px; transform: rotate(45deg);
+ background: ${pal.fg}; box-shadow: 0 0 0 ${px(3)}px ${pal.accent}, 0 0 ${px(18)}px ${rgba(pal.accent, 0.8)}; }
+ .sc-cards { position: absolute; left: -${px(98)}px; width: ${px(196)}px; }
+ .sc-cards.below { top: ${px(20)}px; }
+ .sc-cards.above { bottom: ${px(20)}px; }
+ .sc-card { position: absolute; left: 0; top: 0; width: ${px(196)}px; visibility: hidden; opacity: 0;
+ border-radius: ${px(8)}px; overflow: hidden; background: ${rgba(pal.bg, 0.9)};
+ box-shadow: 0 0 0 ${px(2)}px ${pal.accent}, 0 ${px(10)}px ${px(26)}px rgba(0, 0, 0, 0.5); }
+ .sc-cards.above .sc-card { top: auto; bottom: 0; }
+ .sc-card img { display: block; width: ${px(196)}px; height: auto; }
+ .sc-date { padding: ${px(5)}px ${px(10)}px ${px(6)}px; font-family: 'DeckSansBold', sans-serif; font-size: ${px(19)}px;
+ line-height: ${px(24)}px; color: ${pal.fg}; text-align: center; white-space: nowrap; font-variant-numeric: tabular-nums; }
+
+ /* Receipts: screenshots fanned on one side, a marker on the cited line. */
+ .fx-receipts { position: absolute; inset: 0; }
+ .rc-card { position: absolute; border-radius: ${px(10)}px; overflow: hidden; background: #fff;
+ box-shadow: 0 0 0 ${px(3)}px ${rgba("#ffffff", 0.95)}, 0 ${px(18)}px ${px(40)}px rgba(0, 0, 0, 0.55); }
+ .rc-card img { display: block; }
+ .rc-mark { position: absolute; transform-origin: 0 50%; border-radius: ${px(4)}px; background: ${amber};
+ mix-blend-mode: multiply; opacity: 0.9; }
+
+ /* The zoom: a screenshot that locks on to its detail and pushes in. */
+ .fx-zoom { position: absolute; border-radius: ${px(12)}px; overflow: hidden; background: #fff; visibility: hidden; opacity: 0;
+ box-shadow: 0 0 0 ${px(4)}px ${rgba("#ffffff", 0.95)}, 0 ${px(22)}px ${px(50)}px rgba(0, 0, 0, 0.6); }
+ .zm-inner { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
+ .zm-inner img { display: block; }
+ .zm-box { position: absolute; border: ${px(4)}px solid ${pal.accent}; border-radius: ${px(6)}px;
+ box-shadow: 0 0 0 ${px(9999)}px ${rgba("#000000", 0.28)}, 0 0 ${px(18)}px ${rgba(pal.accent, 0.8)}; }
+
+ /* The line. Kinetic: words land as they are said, the key phrase punched. */
+ .fx-quote { position: absolute; left: 0; right: 0; display: flex; justify-content: center; visibility: hidden; opacity: 0; }
+ .fx-quote.redact { padding: 0 9%; }
+ .fx-quote.redact.bottom { bottom: 7%; }
+ .fx-quote.redact.top { top: 27%; }
+ /* Kinetic: no plate (a plate sized for the whole page shows its empty
+ end before the words reach it); a band of the ground behind the
+ words' edge of the box, and an outline on every word. */
+ .fx-quote.kinetic { padding: 0.55em 8% 0.6em; }
+ .fx-quote.kinetic.bottom { bottom: 0; padding-bottom: 6%; background: linear-gradient(${rgba(pal.bg, 0)}, ${rgba(pal.bg, 0.66)}); }
+ .fx-quote.kinetic.top { top: 0; padding-top: 6%; background: linear-gradient(${rgba(pal.bg, 0.66)}, ${rgba(pal.bg, 0)}); }
+ .fx-quote .q-inner { text-align: center; font-family: 'DeckSansBold', sans-serif; line-height: 1.2; }
+ .fx-quote.kinetic .q-inner { color: ${pal.fg};
+ text-shadow: 0 0 ${px(2)}px rgba(0, 0, 0, 0.9), 0 ${px(2)}px ${px(3)}px rgba(0, 0, 0, 0.8), 0 ${px(4)}px ${px(18)}px rgba(0, 0, 0, 0.6); }
+ .fx-quote .w { position: relative; display: inline-block; }
+ /* Two voices: the first on the left, the second on the right, each its colour. */
+ .fx-quote.kinetic.voice .q-inner { color: var(--vc, ${pal.fg}); max-width: 74%; }
+ .fx-quote.kinetic.v0 { justify-content: flex-start; }
+ .fx-quote.kinetic.v0 .q-inner { text-align: left; }
+ .fx-quote.kinetic.v1 { justify-content: flex-end; }
+ .fx-quote.kinetic.v1 .q-inner { text-align: right; }
+ .fx-quote .q-voice { font-family: 'DeckSansBold', sans-serif; font-size: 0.42em; letter-spacing: 0.16em; text-transform: uppercase;
+ color: var(--vc, ${pal.accent}); margin-bottom: 0.1em; }
+ .fx-quote.kinetic .w { visibility: hidden; opacity: 0; }
+ .fx-quote.kinetic .w.punch { color: ${mix(pal.accent, "#ffffff", 0.12)};
+ text-shadow: 0 0 ${px(2)}px rgba(0, 0, 0, 0.9), 0 0 ${px(22)}px ${rgba(pal.accent, 0.7)}, 0 ${px(3)}px ${px(10)}px rgba(0, 0, 0, 0.7); }
+ .fx-quote.kinetic .u { position: absolute; left: 0; right: 0; bottom: 0.02em; height: 0.09em; border-radius: 0.05em;
+ background: ${pal.accent}; transform-origin: 0 50%; }
+ /* Redacted: a page of the transcript, every word under a bar until it is said. */
+ .fx-quote.redact .q-inner { padding: 0.5em 0.75em 0.55em; border-radius: ${px(6)}px; background: ${paper}; color: ${ink};
+ text-align: left; box-shadow: 0 ${px(18)}px ${px(44)}px rgba(0, 0, 0, 0.55); }
+ .fx-quote.redact .t { position: relative; }
+ .fx-quote.redact .bar { position: absolute; left: -0.08em; right: -0.08em; top: 0.12em; bottom: 0.06em; background: #0b0a08;
+ border-radius: 0.06em; transform-origin: 100% 50%; }
+ .fx-quote.redact .hl { position: absolute; left: -0.1em; right: -0.1em; top: 0.18em; bottom: 0.04em; background: ${amber};
+ transform-origin: 0 50%; opacity: 0.85; }
+
+ /* The odometer: the count rolls up, digit by digit. */
+ .fx-odo { position: absolute; display: flex; flex-direction: column; align-items: center; visibility: hidden; opacity: 0;
+ padding: ${px(10)}px ${px(18)}px ${px(10)}px; border-radius: ${px(14)}px; background: ${rgba(pal.bg, 0.78)};
+ box-shadow: inset 0 0 0 ${px(2)}px ${rgba(pal.accent, 0.8)}, 0 ${px(10)}px ${px(30)}px rgba(0, 0, 0, 0.45); }
+ .fx-odo.top { top: ${px(28)}px; } .fx-odo.bottom { bottom: ${px(28)}px; }
+ .fx-odo.left { left: ${px(28)}px; } .fx-odo.right { right: ${px(28)}px; }
+ .od-digits { display: flex; overflow: hidden; }
+ .od-col { display: block; width: ${px(58)}px; overflow: hidden; }
+ .od-strip { display: flex; flex-direction: column; }
+ .od-cell { display: block; height: ${px(92)}px; font-family: 'DeckSansBold', sans-serif; font-size: ${px(86)}px; line-height: ${px(92)}px;
+ text-align: center; color: ${pal.fg}; font-variant-numeric: tabular-nums; }
+ .od-label { margin-top: -${px(4)}px; font-family: 'DeckSansBold', sans-serif; font-size: ${px(20)}px; letter-spacing: 0.18em;
+ text-transform: uppercase; color: ${pal.accent}; }
+ .od-pulse { position: absolute; inset: -${px(4)}px; border-radius: ${px(16)}px; box-shadow: 0 0 0 ${px(4)}px ${pal.accent}, 0 0 ${px(30)}px ${rgba(pal.accent, 0.8)}; }
+
+ /* The punch-in: a flash, and corner brackets closing on the picture. */
+ .fx-punch { position: absolute; inset: 0; }
+ .pi-flash { position: absolute; inset: 0; background: #ffffff; visibility: hidden; opacity: 0; }
+ .pi-frame { position: absolute; inset: ${px(26)}px; visibility: hidden; opacity: 0; }
+ .pi-frame i { position: absolute; width: ${px(64)}px; height: ${px(64)}px; border: 0 solid ${pal.fg};
+ filter: drop-shadow(0 0 ${px(6)}px rgba(0, 0, 0, 0.7)); }
+ .pi-frame .tl { left: 0; top: 0; border-left-width: ${px(6)}px; border-top-width: ${px(6)}px; }
+ .pi-frame .tr { right: 0; top: 0; border-right-width: ${px(6)}px; border-top-width: ${px(6)}px; }
+ .pi-frame .bl { left: 0; bottom: 0; border-left-width: ${px(6)}px; border-bottom-width: ${px(6)}px; }
+ .pi-frame .br { right: 0; bottom: 0; border-right-width: ${px(6)}px; border-bottom-width: ${px(6)}px; }
+ /* The whip: streaks of light raking across the cut. */
+ .fx-whip { position: absolute; inset: 0; }
+ .wh-streak { position: absolute; left: 0; border-radius: ${px(10)}px; visibility: hidden; opacity: 0;
+ background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.9) 70%, rgba(255, 255, 255, 0)); }
+ /* THEN / NOW: the divider, a scrim on the side that is THEN, and the two dates on its edges. */
+ .fx-wipe { position: absolute; inset: 0; }
+ .tn-scrim { position: absolute; left: 0; top: 0; height: ${H}px; background: ${rgba("#000000", 0.4)}; }
+ .tn-div { position: absolute; left: 0; top: 0; width: ${px(6)}px; height: ${H}px; margin-left: -${px(3)}px; background: ${pal.fg};
+ box-shadow: 0 0 ${px(16)}px ${px(3)}px ${rgba(pal.fg, 0.75)}, 0 0 ${px(44)}px ${px(8)}px ${rgba(pal.accent, 0.55)}; }
+ .tn-tagw { position: absolute; left: 0; top: 27%; width: 0; height: 0; }
+ .tn-tag { position: absolute; top: 0; display: flex; align-items: baseline; gap: ${px(12)}px; white-space: nowrap;
+ padding: ${px(8)}px ${px(16)}px ${px(10)}px; border-radius: ${px(10)}px; background: ${rgba(pal.bg, 0.86)};
+ border: ${px(3)}px solid var(--c); box-shadow: 0 ${px(10)}px ${px(26)}px rgba(0, 0, 0, 0.45); }
+ .tn-tag.then { right: ${px(18)}px; }
+ .tn-tag.now { left: ${px(18)}px; }
+ .tn-tag b { font-family: 'DeckSansBold', sans-serif; font-weight: 400; font-size: ${px(22)}px; letter-spacing: 0.16em; color: var(--c); }
+ .tn-tag span { font-family: 'DeckSansBold', sans-serif; font-size: ${px(34)}px; color: ${pal.fg}; font-variant-numeric: tabular-nums; }
+
+ /* The glitch: scanlines, torn bars in two channels, noise, the new year. */
+ .fx-glitch { position: absolute; inset: 0; }
+ .gl-noise { position: absolute; left: 0; top: 0; visibility: hidden; opacity: 0; }
+ .gl-scan { position: absolute; inset: 0; visibility: hidden; opacity: 0;
+ background: repeating-linear-gradient(to bottom, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.5) ${px(2)}px, rgba(0, 0, 0, 0) ${px(2)}px, rgba(0, 0, 0, 0) ${px(4)}px); }
+ .gl-slice { position: absolute; left: -${px(80)}px; right: -${px(80)}px; top: 0; visibility: hidden; opacity: 0; }
+ .gl-year { position: absolute; left: 0; right: 0; top: 50%; margin-top: -${px(130)}px; height: ${px(260)}px; text-align: center;
+ font-family: 'DeckSansBold', sans-serif; font-size: ${px(240)}px; line-height: ${px(260)}px; color: ${pal.fg};
+ letter-spacing: 0.02em; font-variant-numeric: tabular-nums; visibility: hidden; opacity: 0;
+ text-shadow: -${px(7)}px 0 rgba(255, 40, 70, 0.85), ${px(7)}px 0 rgba(40, 230, 255, 0.85), 0 ${px(6)}px ${px(30)}px rgba(0, 0, 0, 0.6); }
+ .gl-vhs { position: absolute; left: ${px(34)}px; bottom: ${px(30)}px; display: flex; flex-direction: column; gap: ${px(2)}px;
+ font-family: 'FxMono', monospace; font-size: ${px(34)}px; line-height: ${px(40)}px; color: #f4f4f4; letter-spacing: 0.06em;
+ text-shadow: ${px(2)}px 0 rgba(255, 40, 70, 0.8), -${px(2)}px 0 rgba(40, 230, 255, 0.8), 0 0 ${px(6)}px rgba(0, 0, 0, 0.9);
+ visibility: hidden; opacity: 0; }
+ </style>
+ </head>
+ <body>
+ <div id="root" data-composition-id="fx" data-start="0" data-duration="${pageDuration(dur, fps)}"
+ data-width="${W}" data-height="${H}">
+ <div id="fx-clip" class="clip" data-start="0" data-duration="${pageDuration(dur, fps)}" data-track-index="1">
+ ${plan.body}
+ </div>
+ </div>
+
+ <script id="fx-data" type="application/json">${json}</script>
+ <script>
+ const S = JSON.parse(document.getElementById("fx-data").textContent);
+ const byK = {};
+ for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el;
+
+ // t = 0, then the cues. Every cue states its from, so a seek from
+ // anywhere to anywhere lands on the same pixels.
+ for (const k of Object.keys(S.init)) if (byK[k]) gsap.set(byK[k], S.init[k]);
+ const inner = gsap.timeline({ paused: true });
+ for (const c of S.cues) {
+ const el = byK[c.k];
+ if (!el) continue;
+ inner.fromTo(el, c.from, { ...c.to, duration: c.dur, ease: c.ease, immediateRender: false }, c.at);
+ }
+ inner.set({}, {}, S.total);
+ let tl = inner;
+ if (S.window) {
+ tl = gsap.timeline({ paused: true });
+ tl.add(inner.tweenFromTo(S.window.from, S.window.from + S.window.dur, { duration: S.window.dur, ease: "none" }), 0);
+ }
+ window.__timelines = window.__timelines || {};
+ window.__timelines["fx"] = tl;
+
+ const imgs = Array.from(document.images).map((im) => (im.complete ? Promise.resolve() : new Promise((r) => { im.onload = im.onerror = r; })));
+ const ready = Promise.all([document.fonts.ready.catch(() => {}), ...imgs]).then(() => { document.documentElement.dataset.fit = "1"; });
+ const params = new URLSearchParams(location.search);
+ const local = (t) => {
+ const v = Number(t) || 0;
+ return S.window ? Math.max(0, Math.min(S.window.dur, v - S.window.from)) : Math.max(0, v);
+ };
+ const still = params.get("still");
+ if (still !== null) {
+ tl.seek(local(still), false);
+ ready.then(() => tl.seek(local(still), false));
+ }
+ if (params.get("preview") === "1") {
+ window.addEventListener("message", (e) => {
+ const m = e.data || {};
+ if (m.type === "deck:seek") tl.seek(local(m.t), false);
+ });
+ ready.then(() => {
+ if (window.parent !== window) window.parent.postMessage({ type: "fx:ready", total: S.total, keys: S.keys }, "*");
+ });
+ }
+ </script>
+ </body>
+</html>
+`;
+}
diff --git a/umtool/report-to-video/chrome-fx.test.mjs b/umtool/report-to-video/chrome-fx.test.mjs
@@ -0,0 +1,515 @@
+// Tests for the effects region's page (chrome-fx.mjs, release 35 O2) and
+// compose-chrome's `fx` region: the page's nodes and its contract, escaping,
+// nothing fetched, the cues the page plays are the schedule's to the frame,
+// and -- through a headless Chromium still, the same seek the renderer makes
+// -- the pixels each effect puts where it says, when it says. One more test
+// runs ffmpeg's own `wipeleft` and finds the THEN/NOW divider on its edge.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { chmodSync, mkdirSync, 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 { cardSize, fxHtml, fxPlan, odoCells, railX, zoomPush } from "./chrome-fx.mjs";
+import { deckSchedule, fxGeometry } from "./deck.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PALETTE = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", amber: "#ffc860" };
+const FPS = 30;
+const FRAME = 1 / FPS;
+const FONT_R = path.join(HERE, "fonts", "IBMPlexMono-Regular.ttf");
+const FONT_B = path.join(HERE, "fonts", "IBMPlexMono-Bold.ttf");
+const render = (fx, D = 0.5) => ({
+ width: 1920, height: 1080, fps: FPS, transition: D, palette: PALETTE, fontRegular: FONT_R, fontBold: FONT_B,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } }, fx },
+});
+const clip = (id, date, extra = {}) => ({
+ type: "clip", id, channel: "ch", video: `v${id}`, start: 10, end: 18, cutStart: 11, cutEnd: 17, date,
+ quote: "it must be an exceedingly slow news week as we have what appears to be collusion",
+ montage: { match: "slow news week", n: Number(id.slice(1)) * 9 }, ...extra,
+});
+const TIMELINE = [
+ clip("c1", "2019-05-02"),
+ clip("c2", "2020-06-11", { fx: { receipts: [{ shot: "shots/b.png", mark: [0.04, 0.3, 0.9, 0.5] }, { shot: "shots/a.png", mark: [0.05, 0.25, 0.9, 0.45] }] } }),
+ clip("c3", "2021-01-01"),
+ clip("c4", "2026-01-01", { fx: { zoom: { shot: "shots/a.png", focus: [0.1, 0.2, 0.6, 0.4] } } }),
+];
+const ALL = {
+ kineticQuote: { clips: ["c1", "c3", "c4"] }, redact: { clips: ["c2"] }, odometer: {}, scrubber: {}, glitch: {},
+ thenNow: { pairs: [{ then: "c3", now: "c4" }] }, receipts: {}, zoom: {},
+};
+const WORDS = new Map(["c1", "c2", "c3", "c4"].map((id) => [id, [
+ { text: "it", start: 1.0, end: 1.2 }, { text: "was", start: 1.2, end: 1.5 }, { text: "a", start: 1.5, end: 1.6 },
+ { text: "slow", start: 1.7, end: 2.0 }, { text: "news", start: 2.0, end: 2.3 }, { text: "week.", start: 2.3, end: 2.7 },
+ { text: "<b>really</b>", start: 3.1, end: 3.6 },
+]]));
+const schedule = (fx = ALL, D = 0.5) =>
+ deckSchedule({ entries: TIMELINE, durs: [6.4, 6.4, 6.4, 6.4], D, render: render(fx, D), fxWords: WORDS });
+const FONTS = { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf", mono: "assets/FxMono.ttf" };
+const SHOTS = { "shots/a.png": { src: "assets/fxshot00.png", w: 600, h: 480 }, "shots/b.png": { src: "assets/fxshot01.png", w: 600, h: 360 } };
+const near = (a, b, tol, msg) => assert.ok(Math.abs(a - b) <= tol + 1e-9, `${msg}: ${a} vs ${b} (±${tol})`);
+const dataOf = (html) => JSON.parse(/<script id="fx-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+const cueOf = (cues, k, pred = () => true) => cues.filter((c) => c.k === k).find(pred);
+
+// ---------------------------------------------------------------------------
+
+test("the page: the footage box, its contract, every effect's nodes", () => {
+ const s = schedule();
+ const html = fxHtml(s, render(ALL), { fonts: FONTS, assets: { shots: SHOTS, thumbs: { c1: "assets/thumb-c1.png" } } });
+ const g = fxGeometry(render(ALL));
+ assert.match(html, new RegExp(`data-composition-id="fx" data-start="0" data-duration="[\\d.]+"\\s+data-width="${g.width}" data-height="${g.height}"`));
+ assert.match(html, /window\.__timelines\["fx"\] = tl/);
+ for (const cls of ["fx-scrubber", "fx-receipts", "fx-zoom", "fx-quote kinetic", "fx-quote redact", "fx-odo", "fx-wipe", "fx-glitch"]) {
+ assert.ok(html.includes(`class="${cls}`), cls);
+ }
+ assert.ok(html.includes('src="assets/thumb-c1.png"'));
+ assert.ok(html.includes('src="assets/fxshot00.png"') && html.includes('src="assets/fxshot01.png"'));
+ assert.ok(html.includes("url('assets/FxMono.ttf')"));
+ assert.ok(html.includes("<b>THEN</b><span>1 Jan 2021</span>") && html.includes("<b>NOW</b><span>1 Jan 2026</span>"));
+ assert.ok(html.includes("PLAY ▶</span><span>11 JUN 2020</span>"));
+});
+
+test("the page: words are text, escaped; the JSON carries none of them; nothing leaves the machine", () => {
+ const html = fxHtml(schedule(), render(ALL), { fonts: FONTS, assets: { shots: SHOTS } });
+ assert.ok(html.includes("<b>really</b>"));
+ assert.doesNotMatch(html, /<b>really/);
+ const json = /<script id="fx-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1];
+ assert.doesNotMatch(json, /really|exceedingly/);
+ assert.doesNotMatch(json, /</);
+ // gsap, the data, the runtime -- and no fourth script; no URL but the
+ // SVG namespace and the page's own assets.
+ assert.equal((html.match(/<script/g) ?? []).length, 3);
+ const urls = (html.match(/https?:\/\/[^\s"')]+/g) ?? []).filter((u) => u !== "http://www.w3.org/2000/svg");
+ assert.deepEqual(urls, []);
+});
+
+test("the page plays fxPlan's cues, every from stated and none overlapping on one element", () => {
+ const s = schedule();
+ const plan = fxPlan(s, render(ALL), { shots: SHOTS });
+ const html = fxHtml(s, render(ALL), { fonts: FONTS, assets: { shots: SHOTS } });
+ assert.deepEqual(dataOf(html).cues, plan.cues);
+ const free = new Map();
+ for (const c of plan.cues) {
+ assert.ok(c.at >= (free.get(c.k) ?? 0) - 1e-9, `${c.k} at ${c.at} overlaps the cue before it`);
+ free.set(c.k, c.at + c.dur);
+ for (const p of Object.keys(c.to)) assert.ok(p in c.from, `${c.k}.${p} has no from`);
+ }
+});
+
+test("the cues land on the schedule's times, to the frame", () => {
+ const s = schedule();
+ const { cues } = fxPlan(s, render(ALL), { shots: SHOTS });
+ // Kinetic: each word comes in at its time; the punch pops then.
+ const q = s.fx.quotes[0];
+ q.pages[0].words.forEach((w, j) => near(cueOf(cues, `qw0_0_${j}`).at, w.at, FRAME, `word ${j}`));
+ // Redacted: each bar lifts on its word.
+ const qi = s.fx.quotes.findIndex((x) => x.style === "redact");
+ s.fx.quotes[qi].pages[0].words.forEach((w, j) => near(cueOf(cues, `qb${qi}_0_${j}`).at, w.at, FRAME, `bar ${j}`));
+ // The odometer's units roll on each count.
+ for (const c of s.fx.odometer.counts) near(cueOf(cues, "odd1", (x) => Math.abs(x.at - c.at) < 0.5).at, c.at, FRAME, `roll ${c.segment}`);
+ // The scrubber's playhead is centred on each clip's in.
+ s.fx.scrubber.ticks.slice(1).forEach((t, n) => {
+ const cue = cues.filter((x) => x.k === "sch")[n];
+ near(cue.at + cue.dur / 2, t.in, FRAME, `playhead to ${t.segment}`);
+ });
+ // The glitch is at its burst, and the divider sweeps the wipe's span.
+ const b = s.fx.glitch.bursts[0];
+ near(cueOf(cues, "gs0").at, b.at - b.seconds / 2, FRAME, "the tear starts half a burst before the cut");
+ const w = s.fx.thenNow.wipes[0];
+ const sweep = cueOf(cues, "tnd0", (x) => "x" in x.to);
+ near(sweep.at, w.at, FRAME, "the divider starts with the wipe");
+ near(sweep.at + sweep.dur, w.at + w.seconds, FRAME, "and ends with it");
+ // Receipts land one after another; the marker swipes after.
+ const r = s.fx.receipts.clips[0];
+ r.cards.forEach((c, j) => near(cueOf(cues, `rc0_${j}`).at, c.at, FRAME, `card ${j}`));
+ near(cueOf(cues, "rcm0_0").at, r.markAt, FRAME, "marker");
+ // The zoom: the box locks on, then the push.
+ const z = s.fx.zoom.clips[0];
+ near(cueOf(cues, "zo0").at, z.outline, FRAME, "outline");
+ near(cueOf(cues, "zi0").at, z.push, FRAME, "push");
+});
+
+test("odoCells, railX, zoomPush, cardSize", () => {
+ assert.deepEqual(odoCells(7, 2), [0, 8]);
+ assert.deepEqual(odoCells(19, 2), [2, 10]);
+ assert.deepEqual(odoCells(0, 1), [1]);
+ assert.equal(railX(5, 0, 10, 100, 200), 150);
+ // The focus box's centre lands in the card's centre, filling 86% of its tighter side.
+ const p = zoomPush([0.25, 0.25, 0.75, 0.5], 400, 300);
+ const fw = 0.5 * 400 * p.scale, fh = 0.25 * 300 * p.scale;
+ near(Math.max(fw / 400, fh / 300), 0.86, 1e-3, "fill");
+ near(p.x + p.scale * 0.5 * 400, 200, 0.01, "centre x");
+ near(p.y + p.scale * 0.375 * 300, 150, 0.01, "centre y");
+ assert.deepEqual(cardSize({ w: 600, h: 1200 }, 500, 600), { w: 300, h: 600 });
+ assert.deepEqual(cardSize({ w: 600, h: 300 }, 500, 600), { w: 500, h: 250 });
+});
+
+test("a window plays the cut's own clock from `from`", () => {
+ const html = fxHtml(schedule(), render(ALL), { fonts: FONTS, assets: { shots: SHOTS }, from: 5, duration: 4 });
+ assert.deepEqual(dataOf(html).window, { from: 5, dur: 4 });
+ assert.match(html, /data-duration="4"/);
+});
+
+// ---------------------------------------------------------------------------
+// The pixels: a headless Chromium still is the seek the renderer makes.
+// ---------------------------------------------------------------------------
+
+const have = (b, a) => spawnSync(b, a, { stdio: "ignore" }).status === 0;
+const haveTools = have("qrencode", ["-V"]) && have("magick", ["-version"]);
+const haveChromium = haveTools && have(process.env.CHROME ?? "/usr/bin/chromium", ["--version"]);
+const haveFfmpeg = have("ffmpeg", ["-version"]);
+
+/** RGBA bytes of a crop of a PNG. */
+function crop(png, x, y, w, h) {
+ const r = spawnSync("magick", [png, "-crop", `${w}x${h}+${x}+${y}`, "+repage", "-depth", "8", "rgba:-"], { maxBuffer: 1 << 26 });
+ return r.stdout;
+}
+/** The share of a crop's pixels that are opaque-ish (alpha > 128). */
+function inked(png, x, y, w, h) {
+ const b = crop(png, x, y, w, h);
+ let n = 0;
+ for (let i = 3; i < b.length; i += 4) if (b[i] > 128) n += 1;
+ return n / (b.length / 4);
+}
+/** Pixels in a crop near a colour (RGB within `tol` each, alpha > 128). */
+function nearColour(png, x, y, w, h, [R, G, B], tol = 40) {
+ const b = crop(png, x, y, w, h);
+ let n = 0;
+ for (let i = 0; i < b.length; i += 4) {
+ if (b[i + 3] > 128 && Math.abs(b[i] - R) <= tol && Math.abs(b[i + 1] - G) <= tol && Math.abs(b[i + 2] - B) <= tol) n += 1;
+ }
+ return n;
+}
+const hex = (h) => [1, 3, 5].map((i) => Number.parseInt(h.slice(i, i + 2), 16));
+
+/** A project with the shots, the manifest and a composed fx page; `still(t)` screenshots it. */
+async function project(fx = ALL, D = 0.5) {
+ const { composeChrome } = await import("./compose-chrome.mjs");
+ const dir = mkdtempSync(path.join(tmpdir(), "fx-px-"));
+ mkdirSync(path.join(dir, "shots"));
+ // Synthetic shots: white pages with grey lines (a "document").
+ for (const [name, w, h] of [["a.png", 600, 480], ["b.png", 600, 360]]) {
+ spawnSync("magick", ["-size", `${w}x${h}`, "xc:white", "-fill", "#444444",
+ ...[0.3, 0.45, 0.6].flatMap((f) => ["-draw", `rectangle 30,${Math.round(f * h)} ${w - 30},${Math.round(f * h) + 14}`]), "-strip", path.join(dir, "shots", name)]);
+ }
+ const manifest = { slug: "t", title: "t", provenance: {}, render: render(fx, D), timeline: TIMELINE };
+ const manifestPath = path.join(dir, "video.manifest.json");
+ writeFileSync(manifestPath, JSON.stringify(manifest));
+ const sched = schedule(fx, D);
+ const still = async (t) => {
+ const png = path.join(dir, `still-${t}.png`);
+ await composeChrome({ manifestPath, region: "fx", schedule: sched, still: t, png });
+ return png;
+ };
+ return { dir, sched, still, composeChrome, manifestPath };
+}
+
+test("pixels: the kinetic line is empty before its first word and inked after; the punch wears the accent",
+ { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ kineticQuote: {} });
+ try {
+ const g = fxGeometry(render(ALL));
+ const q = sched.fx.quotes[0];
+ const band = [0, Math.round(g.height * 0.62), g.width, Math.round(g.height * 0.38)];
+ const before = await still(q.pages[0].in - 0.2);
+ // Before the page there is nothing but the scrubber's and odometer's corners.
+ assert.ok(inked(before, ...band) < 0.002, `ink before the line: ${inked(before, ...band)}`);
+ const punchAt = q.pages[0].words.find((w) => w.punch).at;
+ const after = await still(punchAt + 0.9);
+ assert.ok(inked(after, ...band) > 0.01, "the line is drawn");
+ assert.ok(nearColour(after, ...band, hex(PALETTE.accent), 60) > 200, "the punched words are in the accent");
+ const early = await still(punchAt - FRAME * 2);
+ assert.ok(nearColour(early, ...band, hex(PALETTE.accent), 60) < 20, "and not before they are said");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+test("pixels: a redaction bar is black until its word is said, then the paper shows", { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ redact: {} });
+ try {
+ const g = fxGeometry(render(ALL));
+ const qi = sched.fx.quotes.findIndex((x) => x.style === "redact");
+ const pg = sched.fx.quotes[qi].pages[0];
+ const band = [0, Math.round(g.height * 0.55), g.width, Math.round(g.height * 0.45)];
+ const blackOf = (png) => nearColour(png, ...band, [11, 10, 8], 14);
+ const paperOf = (png) => nearColour(png, ...band, [243, 239, 228], 14);
+ const t0 = await still(pg.words[0].at - FRAME);
+ const t1 = await still(pg.words[pg.words.length - 1].at + 0.6);
+ assert.ok(blackOf(t0) > 5000, "the bars are down");
+ assert.ok(blackOf(t1) < blackOf(t0) * 0.2, `the bars have lifted: ${blackOf(t1)} of ${blackOf(t0)}`);
+ assert.ok(paperOf(t1) > paperOf(t0), "and the paper shows where they were");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels: the receipts fly in to the right side and the marker paints the cited line amber", { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ receipts: {} });
+ try {
+ const g = fxGeometry(render(ALL));
+ const r = sched.fx.receipts.clips[0];
+ const right = [Math.round(g.width * 0.55), 0, Math.round(g.width * 0.45), g.height];
+ const before = await still(r.in - 0.1);
+ assert.ok(nearColour(before, ...right, [255, 255, 255], 6) < 50, "no card before");
+ const landed = await still(r.markAt - FRAME);
+ assert.ok(nearColour(landed, ...right, [255, 255, 255], 6) > 20000, "the cards are in");
+ assert.ok(nearColour(landed, ...right, hex(PALETTE.amber), 30) < 50, "the marker has not swiped yet");
+ const marked = await still(r.markAt + 0.9);
+ assert.ok(nearColour(marked, ...right, hex(PALETTE.amber), 30) > 2000, "the marker is down");
+ const left = [0, 0, Math.round(g.width * 0.4), g.height];
+ assert.ok(nearColour(marked, ...left, [255, 255, 255], 6) < 50, "nothing on the left");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels: the zoom's focus box locks on, then the push fills the card with the detail", { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ zoom: {} });
+ try {
+ const z = sched.fx.zoom.clips[0];
+ const g = fxGeometry(render(ALL));
+ const { w, h } = cardSize({ w: 600, h: 480 }, 0.56 * g.width, g.height * 0.84);
+ const card = [Math.round((g.width - w) / 2), Math.round((g.height - h) / 2), w, h];
+ const pre = await still(z.outline + 0.6);
+ const pushed = await still(z.push + 1.2);
+ const accent = hex(PALETTE.accent);
+ const boxPre = nearColour(pre, ...card, accent, 50);
+ const boxPushed = nearColour(pushed, ...card, accent, 50);
+ assert.ok(boxPre > 500, "the focus box is drawn");
+ assert.ok(boxPushed > boxPre * 1.4, `the box grew with the push: ${boxPre} → ${boxPushed}`);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels: the odometer's digits change on the roll and nowhere else", { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ odometer: {} });
+ try {
+ const c = sched.fx.odometer.counts[1];
+ const a = await still(c.at - FRAME);
+ const b = await still(c.at + 0.8);
+ const g = fxGeometry(render({ odometer: {} }));
+ const corner = [g.width - 260, 0, 260, 200];
+ const rest = [0, 220, g.width, g.height - 220];
+ assert.ok(inked(a, ...corner) > 0.1, "the counter is up");
+ assert.notDeepEqual(crop(a, ...corner), crop(b, ...corner), "the digits rolled");
+ assert.deepEqual(crop(a, ...rest), crop(b, ...rest), "nothing else moved");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels: the glitch tears only around its cut", { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ glitch: {} });
+ try {
+ const b = sched.fx.glitch.bursts[0];
+ const g = fxGeometry(render({ glitch: {} }));
+ const whole = [0, 0, g.width, g.height];
+ assert.ok(inked(await still(b.at - b.seconds / 2 - 2 * FRAME), ...whole) < 0.001, "clean before");
+ assert.ok(inked(await still(b.at), ...whole) > 0.2, "torn at the cut");
+ // After the burst only the year (fading) and the VHS stamp remain.
+ assert.ok(inked(await still(b.at + 2.5), ...whole) < 0.001, "clean after");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels: the scrubber's playhead sits on its clip's day", { skip: !haveChromium }, async () => {
+ const { dir, sched, still } = await project({ scrubber: {} });
+ try {
+ const sc = sched.fx.scrubber;
+ const g = fxGeometry(render({ scrubber: {} }));
+ const k = g.width / 1574;
+ const x0 = Math.round(64 * k), x1 = g.width - Math.round(64 * k);
+ for (const t of [sc.ticks[1], sc.ticks[3]]) {
+ const png = await still(t.in + 0.7);
+ // The diamond is the palette's fg, on the rail's row.
+ const row = crop(png, 0, Math.round(38 * k) - 2, g.width, 4);
+ const xs = [];
+ for (let x = 0; x < g.width; x += 1) {
+ const i = (2 * g.width + x) * 4;
+ if (row[i + 3] > 200 && row[i] > 230 && row[i + 1] > 225) xs.push(x);
+ }
+ assert.ok(xs.length, `no playhead for ${t.segment}`);
+ const mid = (Math.min(...xs) + Math.max(...xs)) / 2;
+ near(mid, railX(t.day, sc.from, sc.to, x0, x1), 3, `playhead on ${t.segment}'s day`);
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels + ffmpeg: the THEN/NOW divider rides xfade wipeleft's edge, frame by frame", { skip: !(haveChromium && haveFfmpeg) }, async () => {
+ const fx = { thenNow: { pairs: [{ then: "c3", now: "c4" }] } };
+ const { dir, sched, still } = await project(fx);
+ try {
+ const w = sched.fx.thenNow.wipes[0];
+ const g = fxGeometry(render(fx));
+ // ffmpeg's own wipe: red into blue over D at the wipe's frames.
+ const D = w.seconds;
+ const n = Math.round(D * FPS);
+ const out = path.join(dir, "wipe.rgb");
+ const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", `color=c=red:s=1920x8:r=${FPS}:d=2`, "-f", "lavfi", "-i", `color=c=blue:s=1920x8:r=${FPS}:d=2`,
+ "-filter_complex", `[0:v][1:v]xfade=transition=wipeleft:duration=${D}:offset=1,format=rgb24`, "-f", "rawvideo", out]);
+ assert.equal(r.status, 0, String(r.stderr));
+ const raw = readFileSync(out);
+ const frameBytes = 1920 * 8 * 3;
+ for (const j of [Math.round(n * 0.3), Math.round(n * 0.5), Math.round(n * 0.7)]) {
+ // Frame (offset + j): the first blue column on its middle row.
+ const f = Math.round(1 * FPS) + j;
+ const row = raw.subarray(f * frameBytes + 4 * 1920 * 3, f * frameBytes + 5 * 1920 * 3);
+ let edge = -1;
+ for (let x = 0; x < 1920; x += 1) if (row[x * 3 + 2] > 128 && row[x * 3] < 128) { edge = x; break; }
+ assert.ok(edge >= 0, `no blue in frame ${f}`);
+ // The page at the same frame of the cut: its divider's bright column, in frame x.
+ const png = await still(w.at + j / FPS);
+ const line = crop(png, 0, Math.round(g.height / 2), g.width, 1);
+ const xs = [];
+ for (let x = 0; x < g.width; x += 1) if (line[x * 4 + 3] > 230 && line[x * 4] > 235 && line[x * 4 + 1] > 230 && line[x * 4 + 2] > 220) xs.push(x);
+ assert.ok(xs.length, `no divider at frame ${j}`);
+ const divider = g.x + (Math.min(...xs) + Math.max(...xs)) / 2;
+ // Within a frame's travel (W / (D · fps) px) of ffmpeg's edge.
+ near(divider, edge, 1920 / (D * FPS), `frame ${j}: divider vs ffmpeg's edge`);
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("composeChrome(fx): assets in, project, frames through a stub renderer, cached by its key", { skip: !haveTools }, async () => {
+ const { dir, manifestPath, composeChrome, sched } = await project();
+ const prevBin = process.env.HYPERFRAMES_BIN;
+ try {
+ const stub = path.join(dir, "hf-stub.mjs");
+ writeFileSync(stub, `#!/usr/bin/env node
+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+const a = process.argv.slice(2);
+const out = a[a.indexOf("--output") + 1], fps = Number(a[a.indexOf("--fps") + 1]), proj = a[a.length - 1];
+const dur = Number(/data-duration="([\\d.]+)"/.exec(readFileSync(path.join(proj, "index.html"), "utf8"))[1]);
+mkdirSync(out, { recursive: true });
+for (let i = 1; i <= Math.round(dur * fps); i += 1) writeFileSync(path.join(out, "frame_" + String(i).padStart(6, "0") + ".png"), "");
+appendFileSync(${JSON.stringify(path.join(dir, "runs.log"))}, a.join(" ") + "\\n");
+`);
+ chmodSync(stub, 0o755);
+ process.env.HYPERFRAMES_BIN = stub;
+ const first = await composeChrome({ manifestPath, region: "fx", schedule: sched, doRender: true, workers: 2 });
+ assert.equal(first.projDir, path.join(dir, "out", "sourced", "chrome", "fx"));
+ assert.equal(first.frames, path.join(dir, "out", "sourced", "chrome", "fx-frames"));
+ assert.equal(first.frameCount, Math.round(sched.total * FPS));
+ const assets = spawnSync("ls", [path.join(first.projDir, "assets")]).stdout.toString().trim().split("\n");
+ assert.deepEqual(assets.sort(), ["DeckSans.ttf", "DeckSansBold.ttf", "FxMono.ttf", "fxshot00.png", "fxshot01.png", "gsap.min.js"]);
+ const html = readFileSync(path.join(first.projDir, "index.html"), "utf8");
+ // The shots' sizes were read before the page was written: b is 600×360, laid at the receipts' width.
+ assert.match(html, /src="assets\/fxshot00\.png" width="\d+" height="\d+"/);
+ const again = await composeChrome({ manifestPath, region: "fx", schedule: sched, doRender: true, workers: 2 });
+ assert.equal(again.cached, true);
+ assert.equal(again.key, first.key);
+ // A schedule without fx is refused for the region.
+ const { fx: _f, ...bare } = sched;
+ await assert.rejects(composeChrome({ manifestPath, region: "fx", schedule: bare }), /needs a schedule with an effect on/);
+ } finally {
+ if (prevBin === undefined) delete process.env.HYPERFRAMES_BIN;
+ else process.env.HYPERFRAMES_BIN = prevBin;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// ---- reaction highlights -------------------------------------------------------------
+
+test("the page: two voices on their own sides and colours, with the manifest's labels", () => {
+ const ws = new Map([["c1", [
+ { text: "what", start: 1, end: 1.3 }, { text: "is", start: 1.3, end: 1.5 }, { text: "this", start: 1.5, end: 1.8 },
+ { text: "it's", start: 2.2, end: 2.5, turn: true }, { text: "news", start: 2.5, end: 2.9 },
+ ]]]);
+ const fx = { kineticQuote: { voices: [{ label: "Host" }, { label: "Video", color: "#22ab83" }] } };
+ const s = deckSchedule({ entries: [TIMELINE[0]], durs: [6.4], D: 0.5, render: render(fx), fxWords: ws });
+ const html = fxHtml(s, render(fx), { fonts: FONTS });
+ assert.match(html, /class="fx-quote kinetic bottom voice v0" data-k="qp0_0"[^>]*data-voice="0"/);
+ assert.match(html, /class="fx-quote kinetic bottom voice v1" data-k="qp0_1"[^>]*data-voice="1" style="font-size:\d+px; --vc:#22ab83;"/);
+ assert.ok(html.includes('<div class="q-voice">Host</div>') && html.includes('<div class="q-voice">Video</div>'));
+});
+
+test("pixels: the punch-in flashes the box white on its frame and is gone a fifth of a second on", { skip: !haveChromium }, async () => {
+ const fx = { punchIn: {} };
+ const { composeChrome } = await import("./compose-chrome.mjs");
+ const dir = mkdtempSync(path.join(tmpdir(), "fx-pi-"));
+ try {
+ const c1 = { ...TIMELINE[0], fx: { punchIn: [13] } };
+ const manifestPath = path.join(dir, "video.manifest.json");
+ writeFileSync(manifestPath, JSON.stringify({ slug: "t", title: "t", provenance: {}, render: render(fx), timeline: [c1] }));
+ const s = deckSchedule({ entries: [c1], durs: [6.4], D: 0.5, render: render(fx) });
+ const p = s.fx.punchIn.punches[0];
+ const still = async (t) => {
+ const png = path.join(dir, `pi-${t}.png`);
+ await composeChrome({ manifestPath, region: "fx", schedule: s, still: t, png });
+ return png;
+ };
+ const g = fxGeometry(render(fx));
+ const mid = [Math.round(g.width / 2) - 50, Math.round(g.height / 2) - 50, 100, 100];
+ assert.ok(inked(await still(p.at - FRAME), ...mid) < 0.01, "nothing before");
+ // The flash is white at a third: alpha ~82 of 255 over every pixel of the box.
+ const flash = crop(await still(p.at + FRAME / 2), ...mid);
+ let lit = 0;
+ for (let i = 0; i < flash.length; i += 4) if (flash[i + 3] > 60 && flash[i] > 240 && flash[i + 1] > 240 && flash[i + 2] > 240) lit += 1;
+ assert.ok(lit / (flash.length / 4) > 0.95, `the flash covers the box: ${lit}`);
+ assert.ok(inked(await still(p.at + 0.25), ...mid) < 0.01, "and is gone");
+ // The viewfinder's corners stay while the footage is in.
+ assert.ok(inked(await still(p.at + 0.5), 0, 0, 120, 120) > 0.05, "corner bracket");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("pixels: the whip's streaks rake across only during its cut", { skip: !haveChromium }, async () => {
+ const fx = { whip: {} };
+ const { dir, sched, still } = await project(fx);
+ try {
+ const w = sched.fx.whip.cuts[0];
+ const g = fxGeometry(render(fx));
+ const all = [0, 0, g.width, g.height];
+ assert.ok(inked(await still(w.at - FRAME), ...all) < 0.001, "clean before");
+ assert.ok(inked(await still(w.at + w.seconds / 2), ...all) > 0.005, "streaks mid-cut");
+ assert.ok(inked(await still(w.at + w.seconds + 2 * FRAME), ...all) < 0.001, "clean after");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("ffmpeg: the punch-in's graph changes the box between its seconds and nothing else", { skip: !haveFfmpeg }, async () => {
+ const { joinInputChain } = await import("./build-video.mjs");
+ const dir = mkdtempSync(path.join(tmpdir(), "fx-pi-ff-"));
+ try {
+ const r = render({});
+ const c = joinInputChain(0, { hold: 0, move: null, zoom: [{ at: 1, until: 1.5, scale: 1.25, anchor: "center" }] }, r);
+ const out = path.join(dir, "o.rgb");
+ const res = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=1920x1080:r=30:d=2",
+ "-filter_complex", `${c.parts.join(";")};${c.v}format=rgb24[o]`, "-map", "[o]", "-f", "rawvideo", out], { maxBuffer: 1 << 28 });
+ assert.equal(res.status, 0, String(res.stderr));
+ const plain = path.join(dir, "p.rgb");
+ spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=1920x1080:r=30:d=2", "-vf", "format=rgb24", "-f", "rawvideo", plain]);
+ const a = readFileSync(out), b = readFileSync(plain);
+ const F = 1920 * 1080 * 3;
+ const frame = (buf, n) => buf.subarray(n * F, (n + 1) * F);
+ const region = (buf, n, x, y, w, h) => {
+ const f = frame(buf, n);
+ const rows = [];
+ for (let j = y; j < y + h; j += 1) rows.push(f.subarray((j * 1920 + x) * 3, (j * 1920 + x + w) * 3));
+ return Buffer.concat(rows);
+ };
+ // Frame 15 (0.5 s): untouched. Frame 36 (1.2 s): the box differs, the ground beside it does not.
+ assert.ok(frame(a, 15).equals(frame(b, 15)), "before the punch the frame is the input's");
+ assert.ok(!region(a, 36, 173, 2, 1574, 886).equals(region(b, 36, 173, 2, 1574, 886)), "the box is zoomed");
+ assert.ok(region(a, 36, 0, 0, 170, 1080).equals(region(b, 36, 0, 0, 170, 1080)), "left of the box untouched");
+ assert.ok(region(a, 36, 0, 900, 1920, 180).equals(region(b, 36, 0, 900, 1920, 180)), "below the box untouched");
+ assert.ok(frame(a, 50).equals(frame(b, 50)), "after it, the input's again");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -50,6 +50,7 @@ import { stampHtml } from "./chrome-stamp.mjs";
import { threadsHtml } from "./chrome-threads.mjs";
import { flipsHtml } from "./chrome-flips.mjs";
import { statsHtml } from "./chrome-stats.mjs";
+import { fxGeometry } from "./deck.mjs";
const run = promisify(execFile);
@@ -57,6 +58,7 @@ const run = promisify(execFile);
const CHROME = process.env.CHROME ?? "/usr/bin/chromium";
const QRENCODE = process.env.QRENCODE_BIN ?? "qrencode";
const MAGICK = process.env.MAGICK_BIN ?? "magick";
+const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg";
const esc = (s) =>
String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
@@ -644,11 +646,98 @@ async function copyShots(posts, manifestDir, assetsDir, key = "shot") {
}
/**
+ * The effects' screenshots (a clip's `fx.receipts[].shot`, `fx.zoom.shot`,
+ * relative to the manifest), copied in beside the page as `fxshotNN<ext>`, one
+ * per distinct file, with their pixel sizes read once here -- so the page lays
+ * every card out from its data and never measures. Returns `{ [shot as
+ * written]: { src, w, h } }`. A shot that cannot be read refuses the region,
+ * as a post's does.
+ */
+export async function copyFxShots(fx, manifestDir, assetsDir) {
+ const wanted = [
+ ...(fx?.receipts?.clips ?? []).flatMap((r) => r.cards.map((c) => c.shot)),
+ ...(fx?.zoom?.clips ?? []).map((z) => z.shot),
+ ];
+ const out = {};
+ const byFile = new Map();
+ for (const shot of wanted) {
+ if (out[shot]) continue;
+ const file = path.resolve(manifestDir, shot);
+ if (!byFile.has(file)) {
+ const name = `fxshot${String(byFile.size).padStart(2, "0")}${path.extname(file).toLowerCase()}`;
+ try {
+ await copyFile(file, path.join(assetsDir, name));
+ } catch (e) {
+ throw new Error(`fx: the screenshot ${shot} cannot be copied: ${e.message}`);
+ }
+ let w = 0, h = 0;
+ try {
+ const { stdout } = await run(MAGICK, ["identify", "-format", "%w %h\\n", file]);
+ [w, h] = stdout.trim().split(/\s+/).map(Number);
+ } catch (e) {
+ throw new Error(`fx: the screenshot ${shot} cannot be read: ${e.message}`);
+ }
+ byFile.set(file, { src: `assets/${name}`, w, h });
+ }
+ out[shot] = byFile.get(file);
+ }
+ return out;
+}
+
+/**
+ * The scrubber's thumbnails: one still per clip it ticks, from the build's
+ * own segment (`<base>/segments/<id>.mp4`) at the middle of the clip's clean
+ * span, cropped to the footage box (a deck segment is framed into it) and
+ * scaled to 392 px wide -- `assets/thumb-<id>.png`. A segment not on disk (a
+ * preview, a compose before the build) has none, and the card shows its date
+ * alone. `-flags +bitexact`: the same frame is the same bytes, so the render
+ * cache keeps hitting.
+ */
+export async function fxThumbs(schedule, base, render, assetsDir) {
+ const out = {};
+ const g = fxGeometry(render, { feed: schedule.layout === "feed" });
+ const segs = new Map((schedule.segments ?? []).map((x) => [x.id, x]));
+ for (const t of schedule.fx?.scrubber?.ticks ?? []) {
+ if (!/^[A-Za-z0-9_-]+$/.test(t.segment)) continue;
+ const seg = segs.get(t.segment);
+ const file = path.join(base, "segments", `${t.segment}.mp4`);
+ if (!seg) continue;
+ const at = Math.max(0, (t.in + t.out) / 2 - seg.start);
+ const name = `thumb-${t.segment}.png`;
+ try {
+ await run(FFMPEG, [
+ "-nostdin", "-v", "error", "-y", "-ss", at.toFixed(3), "-i", file, "-frames:v", "1",
+ "-vf", `crop=${g.width}:${g.height}:${g.x}:${g.y},scale=392:-2`, "-flags", "+bitexact", "-f", "image2", "-c:v", "png",
+ path.join(assetsDir, name),
+ ]);
+ out[t.segment] = `assets/${name}`;
+ } catch {
+ // No segment yet: the card is its date alone.
+ }
+ }
+ return out;
+}
+
+/**
* Which HTML each chrome region is, with the assets it needs written into
* `projDir/assets`. The chart's branch is the band as it shipped; only where
* its GSAP comes from has changed.
*/
async function regionHtml(region, { manifest, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, teaser, transition }) {
+ if (region === "fx") {
+ // The effects (chrome-fx.mjs): the deck's faces, a mono, the screenshots
+ // the receipts and the zoom show, and the scrubber's thumbnails.
+ // A page module reached by a dynamic import, as the teaser's: it carries
+ // its mono as an asset URL (docs/quirks.md).
+ const { fxHtml, FX_MONO_FILE } = await import("./chrome-fx.mjs");
+ const render = manifest.render;
+ const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true });
+ await copyFile(FX_MONO_FILE, path.join(assetsDir, "FxMono.ttf"));
+ fonts.mono = "assets/FxMono.ttf";
+ const shots = await copyFxShots(schedule.fx, manifestDir, assetsDir);
+ const thumbs = schedule.fx.scrubber?.thumbs ? await fxThumbs(schedule, base, render, assetsDir) : {};
+ return fxHtml(schedule, render, { fonts, assets: { shots, thumbs }, from, duration });
+ }
if (region === "chart") {
const sched = schedule ?? JSON.parse(await readFile(path.join(base, "schedule.json"), "utf8"));
const fonts = await copyFonts(manifest.render, assetsDir, { regular: "regular", bold: "bold" }, { strict: false });
@@ -848,10 +937,10 @@ export async function composeChrome({
// The regions keyed by the render cache: the two drawn from the deck's
// schedule, and a teaser, drawn from its own timeline entry.
const keyed = region === "deck" || region === "feed" || region === "posts" || region === "teaser" || region === "stamp" ||
- region === "threads" || region === "flips" || region === "stats";
+ region === "threads" || region === "flips" || region === "stats" || region === "fx";
// The regions drawn over the whole cut from its schedule, windowable alike.
const wholeCut = region === "deck" || region === "feed" || region === "stamp" || region === "threads" || region === "flips" ||
- region === "stats";
+ region === "stats" || region === "fx";
let teaser = null;
if (region === "teaser") {
teaser = (manifest.timeline ?? []).find((e) => e.id === segment && e.type === "teaser") ?? null;
@@ -881,6 +970,9 @@ export async function composeChrome({
if (region === "stats" && !sched.stats?.clips?.length) {
throw new Error("the stats region needs a schedule with a clip that declares it (render.chrome.stats or a clip's stats, and frameScan.overlay points)");
}
+ if (region === "fx" && !sched.fx) {
+ throw new Error("the fx region needs a schedule with an effect on (render.chrome.fx)");
+ }
if (region === "stamp" && !sched.factcheck?.stamps?.length) {
throw new Error("the stamp region needs a schedule that stamps a claim (an entry with a `claim`)");
}
@@ -1009,7 +1101,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
const manifestPath = argv.find((a, i) => !a.startsWith("--") && !VALUED.has(argv[i - 1]));
if (!manifestPath) {
console.error(
- "usage: compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|stats|threads|flips|posts|teaser] [--variant sourced|full]\n" +
+ "usage: compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|stats|threads|flips|fx|posts|teaser] [--variant sourced|full]\n" +
" [--segment <id>] (posts: the clip whose window to compose; teaser: its entry)\n" +
" [--from <s>] [--duration <s>] [--out <dir>] [--preview]\n" +
" [--still <s> --png <path>]\n" +
@@ -1032,7 +1124,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
still: num("--still"),
png: flag("--png"),
// The deck renders four-wide by default; the band keeps the renderer's own default.
- workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" ? 4 : region === "posts" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null),
+ workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" || region === "fx" ? 4 : region === "posts" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null),
quality: flag("--quality") ?? "high",
format: flag("--format") ?? "png-sequence",
fps: num("--fps"),
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -23,6 +23,7 @@ import {
import { threadOf, threadSchedule, threadsOn, validateThreads } from "./threads.mjs";
import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs";
import { overlayPointsOf, resolveStats, statsSchedule, statsWanted, validateStats } from "./stats.mjs";
+import { fxOn, fxSchedule, validateFx } from "./fx.mjs";
import { estimatedNarratedCardSeconds, hasNarration } from "./narration.mjs";
/** Is the left panel on: the thread rail (threads.mjs) or the flips panel (flips.mjs) -- one region, one or the other. */
@@ -139,7 +140,7 @@ export function validateChrome(chrome, render = {}) {
const errors = [];
if (chrome === undefined || chrome === null) return errors;
if (!isObj(chrome)) return ["render.chrome must be an object"];
- unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats"], "render.chrome", errors);
+ unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats", "fx"], "render.chrome", errors);
if (chrome.engine !== "hyperframes") errors.push('render.chrome.engine must be "hyperframes"');
if (chrome.layout !== "deck") errors.push('render.chrome.layout must be "deck"');
if (render.rail) errors.push("render.chrome (the deck) and render.rail cannot both be set");
@@ -157,6 +158,8 @@ export function validateChrome(chrome, render = {}) {
errors.push(...validateFlips(chrome.flips));
// The stats region (stats.mjs): a frame scan's running numbers over the footage.
errors.push(...validateStats(chrome.stats));
+ // The effects region (fx.mjs): overlays drawn over the footage box.
+ errors.push(...validateFx(chrome.fx));
if (threadsOn({ chrome }) && flipsOn({ chrome })) errors.push("render.chrome.threads and render.chrome.flips share the left panel: set one");
const d = chrome.deck ?? {};
if (!isObj(d)) return [...errors, "render.chrome.deck must be an object"];
@@ -634,6 +637,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin
*/
export function deckSchedule({
entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null,
+ fxWords = null, fxClock = null,
}) {
const deck = resolveDeck(render);
const fps = render.fps ?? 30;
@@ -668,6 +672,17 @@ export function deckSchedule({
}),
D, total, render,
});
+ // The effects (fx.mjs): only when one is on, so a cut without them writes
+ // the schedule it always did. `fxWords` are each clip's timed words in its
+ // segment's seconds (the build reads them); `fxClock` the source second each
+ // clip's segment starts at (its cut record), for the words a clip falls back to.
+ const fx = fxOn(render)
+ ? fxSchedule({
+ segments: segs, entries, metas, render, D, total, words: fxWords, fps,
+ sourceFrom: (e) => fxClock?.get(e.id) ?? playWindow(e, render).from,
+ hidden: (e) => hidesDeck(e, deck),
+ })
+ : null;
return {
version: 1,
kind: "deck",
@@ -705,6 +720,8 @@ export function deckSchedule({
...(flips ? { flips } : {}),
// The stats region: present only when a clip declares it.
...(stats ? { stats } : {}),
+ // The effects region: present only when an effect is on, with the box it is drawn over.
+ ...(fx ? { fx: { ...fx, box: fxGeometry(render, { feed }) } } : {}),
// Present only when there are posts to draw, so a cut without them writes
// the schedule it always did.
...(placed.length ? { posts: roundPosts(placed) } : {}),
@@ -1303,6 +1320,21 @@ export function statsGeometry(render, { feed = false } = {}) {
}
/**
+ * Where the effects region sits in the frame (chrome-fx.mjs, fx.mjs): exactly
+ * the footage box -- the feed's when `feed`, else the deck's (beside the rail
+ * when the rail is on). The effects are overlays on the picture, so the
+ * region is the picture.
+ *
+ * @param {any} render
+ * @param {{ feed?: boolean }} [opts]
+ * @returns {{ x: number, y: number, width: number, height: number }}
+ */
+export function fxGeometry(render, { feed = false } = {}) {
+ const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage;
+ return { x: f.x, y: f.y, width: f.width, height: f.height };
+}
+
+/**
* Is this cut a FEED: the deck on, its posts shown in the `feed` layout, and
* at least one post to draw on a clip of `entries` (the cut's whole timeline,
* never an `--only` slice of it)? The build frames its footage into
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -0,0 +1,963 @@
+// THE EFFECTS region for the deck (release 35, lane O2): eight opt-in overlay
+// effects drawn over the footage box by ONE HyperFrames page for the whole cut
+// (chrome-fx.mjs), laid over the cut like the stamps and the stats.
+//
+// render.chrome.fx: {
+// kineticQuote: { position, size, maxWords, clips? } the cited line word by word, the key phrase punched
+// redact: { position, size, maxWords, clips? } the cited line under black bars that lift as it is said
+// odometer: { position, label, at } rolling digits: the count goes up on each clip
+// scrubber: { position, thumbs } a date rail, the playhead sliding to each clip's day
+// glitch: { on, seconds, stamp } a VHS tear at each cut between years
+// thenNow: { pairs: [{ then, now }], seconds, dates } a moving divider between a THEN clip and its NOW
+// receipts: { position, width } a clip's screenshots fan in, a marker swipes the cited line
+// zoom: { width } a screenshot pushed in on its focus box
+// punchIn: { scale, hold, anchor, auto } the footage snaps in on a moment (a laugh), then back
+// whip: { on } the cut between two clips slides like a whip pan
+// }
+// timeline entry: "fx": { "punch": "…", "quote": false, "punchIn": [<source s>, …],
+// "speakers": [{ "at": <source s>, "who": 0 | 1 }],
+// "receipts": [{ "shot": "shots/a.png", "mark": [x0, y0, x1, y1] }],
+// "zoom": { "shot": "shots/b.png", "focus": [x0, y0, x1, y1], "at": 1.2 } }
+//
+// Every key is opt-in; `render.chrome.fx` absent (or null, or {}) draws nothing
+// and every schedule, graph and file is byte for byte what it was. An entry's
+// `fx` is inert until its effect is on. `mark` and `focus` are fractions of the
+// screenshot (0..1, left, top, right, bottom).
+//
+// PURE, like stats.mjs: validation, the defaults, the schedule, the geometry and
+// the cue list. No fs, no ffmpeg. deck.mjs imports this file -- never the other
+// way round -- and it imports nothing of the montage's (montage.mjs imports
+// deck.mjs), so the few date and phrase helpers it needs are its own.
+
+/** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */
+export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]);
+
+export const FX_CORNERS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]);
+export const FX_QUOTE_POSITIONS = Object.freeze(["bottom", "top"]);
+export const FX_RAIL_POSITIONS = Object.freeze(["top", "bottom"]);
+export const FX_SIDES = Object.freeze(["right", "left"]);
+export const FX_GLITCH_ON = Object.freeze(["year", "every"]);
+export const FX_DATES = Object.freeze(["date", "year"]);
+export const FX_ODOMETER_AT = Object.freeze(["phrase", "start"]);
+export const FX_SHOT_EXTS = Object.freeze([".png", ".jpg", ".jpeg", ".webp"]);
+export const FX_RECEIPTS_MAX = 4;
+export const FX_ANCHORS = Object.freeze(["upper", "center"]);
+export const FX_WHIP_ON = Object.freeze(["every", "year"]);
+/** A kinetic line's two voices when the manifest names none: the palette's fg, then THEN's blue. */
+export const FX_VOICE_COLORS = Object.freeze([null, "#6fa8dc"]);
+/** The words a laugh is written as in captions (`punchIn.auto`). */
+export const FX_LAUGH_RE = /^(?:(?:ha){2,}h?|(?:he){2,}|lol|lmao|lmfao|rofl|laughs?|laughing|laughter)$/i;
+
+/** Every effect's settings and their defaults. A manifest names only what it changes. */
+export const FX_DEFAULTS = Object.freeze({
+ kineticQuote: Object.freeze({ position: "bottom", size: 54, maxWords: 12, clips: null, speakers: "auto", voices: null }),
+ redact: Object.freeze({ position: "bottom", size: 44, maxWords: 14, clips: null }),
+ odometer: Object.freeze({ position: "top-right", label: "times", at: "phrase" }),
+ scrubber: Object.freeze({ position: "top", thumbs: true }),
+ glitch: Object.freeze({ on: "year", seconds: 0.5, stamp: true }),
+ thenNow: Object.freeze({ pairs: Object.freeze([]), seconds: 0.6, dates: "date" }),
+ receipts: Object.freeze({ position: "right", width: 0.36 }),
+ zoom: Object.freeze({ width: 0.56 }),
+ punchIn: Object.freeze({ scale: 1.2, hold: 1.4, anchor: "upper", auto: true }),
+ whip: Object.freeze({ on: "every" }),
+});
+
+/** The motion every effect shares, in seconds. */
+export const FX_MOTION = Object.freeze({
+ word: 0.14, // a word coming in
+ punch: 0.32, // the key phrase's pop
+ bar: 0.22, // a redaction bar lifting
+ page: 0.22, // a page of words in and out
+ roll: 0.55, // the odometer's digits
+ rail: 0.6, // the scrubber's playhead travelling to the next day
+ thumb: 0.25, // its thumbnail handing over
+ fan: 0.42, // one receipt flying in
+ fanGap: 0.18, // between two receipts
+ marker: 0.55, // the marker swiping
+ push: 1.0, // the zoom's push in
+ outline: 0.45, // the zoom's focus box drawing
+ tag: 0.3, // a THEN/NOW tag in or out
+ hold: 1.2, // a NOW tag resting after the wipe
+});
+
+/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */
+export const INSTANT = 0.001;
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const r4 = (v) => Math.round(v * 10000) / 10000;
+
+/** The effects that are on: their keys, each with an object (not null) under `render.chrome.fx`. */
+export function fxKeysOn(render) {
+ const fx = render?.chrome?.fx;
+ if (!isObj(fx)) return [];
+ return FX_KEYS.filter((k) => isObj(fx[k]));
+}
+
+/** Is any effect on? Absent, nothing in this file runs and nothing is drawn. */
+export const fxOn = (render) => fxKeysOn(render).length > 0;
+
+/** One effect's settings with every default filled in, or null when it is off. */
+export function resolveFx(render, key) {
+ const v = render?.chrome?.fx?.[key];
+ if (!isObj(v)) return null;
+ return { ...FX_DEFAULTS[key], ...v };
+}
+
+// ---------------------------------------------------------------------------
+// Validation: one validator, called by validateChrome (the render keys) and by
+// the build and the lint (the entries, against the whole manifest).
+// ---------------------------------------------------------------------------
+
+const ALLOWED = {
+ kineticQuote: ["position", "size", "maxWords", "clips", "speakers", "voices"],
+ redact: ["position", "size", "maxWords", "clips"],
+ odometer: ["position", "label", "at"],
+ scrubber: ["position", "thumbs"],
+ glitch: ["on", "seconds", "stamp"],
+ thenNow: ["pairs", "seconds", "dates"],
+ receipts: ["position", "width"],
+ zoom: ["width"],
+ punchIn: ["scale", "hold", "anchor", "auto"],
+ whip: ["on"],
+};
+
+const oneOf = (list) => list.map((x) => `"${x}"`).join(", ");
+
+/**
+ * Every reason `render.chrome.fx` cannot be built, as sentences (empty: it
+ * can). Unknown keys are refused, as the deck's are. validateChrome calls it.
+ *
+ * @returns {string[]}
+ */
+export function validateFx(fx, where = "render.chrome.fx") {
+ if (fx === undefined || fx === null) return [];
+ if (!isObj(fx)) return [`${where} must be an object`];
+ const errors = [];
+ for (const k of Object.keys(fx)) {
+ if (!FX_KEYS.includes(k)) {
+ errors.push(`${where}.${k} is not an effect (${FX_KEYS.join(", ")})`);
+ continue;
+ }
+ const v = fx[k];
+ if (v === null) continue;
+ if (!isObj(v)) {
+ errors.push(`${where}.${k} must be an object ({} for the defaults) or null`);
+ continue;
+ }
+ const w = `${where}.${k}`;
+ for (const key of Object.keys(v)) if (!ALLOWED[k].includes(key)) errors.push(`${w}.${key} is not a ${k} setting`);
+ if (k === "kineticQuote" || k === "redact") {
+ if (v.position !== undefined && !FX_QUOTE_POSITIONS.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_QUOTE_POSITIONS)}`);
+ if (v.size !== undefined && !numIn(v.size, 24, 96)) errors.push(`${w}.size must be from 24 to 96`);
+ if (v.maxWords !== undefined && !(Number.isInteger(v.maxWords) && numIn(v.maxWords, 3, 30))) {
+ errors.push(`${w}.maxWords must be a whole number from 3 to 30`);
+ }
+ if (v.clips !== undefined && v.clips !== null) {
+ if (!Array.isArray(v.clips) || !v.clips.length || !v.clips.every((c) => typeof c === "string" && c)) {
+ errors.push(`${w}.clips must be a list of clip ids, or null for every clip`);
+ }
+ }
+ }
+ if (k === "kineticQuote") {
+ if (v.speakers !== undefined && v.speakers !== "auto" && v.speakers !== false) errors.push(`${w}.speakers must be "auto" or false`);
+ if (v.voices !== undefined && v.voices !== null) {
+ if (!Array.isArray(v.voices) || v.voices.length < 1 || v.voices.length > 2) errors.push(`${w}.voices must be a list of one or two { label?, color? }`);
+ else {
+ v.voices.forEach((x, i) => {
+ if (!isObj(x) || Object.keys(x).some((kk) => kk !== "label" && kk !== "color")) errors.push(`${w}.voices[${i}] must be { label?, color? }`);
+ else {
+ if (x.label !== undefined && !(typeof x.label === "string" && x.label.trim().length <= 20)) errors.push(`${w}.voices[${i}].label must be at most 20 characters`);
+ if (x.color !== undefined && !/^#[0-9a-fA-F]{6}$/.test(String(x.color))) errors.push(`${w}.voices[${i}].color must be a #rrggbb colour`);
+ }
+ });
+ }
+ }
+ }
+ if (k === "punchIn") {
+ if (v.scale !== undefined && !numIn(v.scale, 1.05, 2)) errors.push(`${w}.scale must be from 1.05 to 2`);
+ if (v.hold !== undefined && !numIn(v.hold, 0.2, 6)) errors.push(`${w}.hold must be from 0.2 to 6 seconds`);
+ if (v.anchor !== undefined && !FX_ANCHORS.includes(v.anchor)) errors.push(`${w}.anchor must be ${oneOf(FX_ANCHORS)}`);
+ if (v.auto !== undefined && typeof v.auto !== "boolean") errors.push(`${w}.auto must be true or false`);
+ }
+ if (k === "whip") {
+ if (v.on !== undefined && !FX_WHIP_ON.includes(v.on)) errors.push(`${w}.on must be ${oneOf(FX_WHIP_ON)}`);
+ }
+ if (k === "odometer") {
+ if (v.position !== undefined && !FX_CORNERS.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_CORNERS)}`);
+ if (v.label !== undefined && !(typeof v.label === "string" && v.label.trim().length <= 24)) {
+ errors.push(`${w}.label must be text of at most 24 characters ("" for none)`);
+ }
+ if (v.at !== undefined && !FX_ODOMETER_AT.includes(v.at)) errors.push(`${w}.at must be ${oneOf(FX_ODOMETER_AT)}`);
+ }
+ if (k === "scrubber") {
+ if (v.position !== undefined && !FX_RAIL_POSITIONS.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_RAIL_POSITIONS)}`);
+ if (v.thumbs !== undefined && typeof v.thumbs !== "boolean") errors.push(`${w}.thumbs must be true or false`);
+ }
+ if (k === "glitch") {
+ if (v.on !== undefined && !FX_GLITCH_ON.includes(v.on)) errors.push(`${w}.on must be ${oneOf(FX_GLITCH_ON)}`);
+ if (v.seconds !== undefined && !numIn(v.seconds, 0.2, 1.5)) errors.push(`${w}.seconds must be from 0.2 to 1.5`);
+ if (v.stamp !== undefined && typeof v.stamp !== "boolean") errors.push(`${w}.stamp must be true or false`);
+ }
+ if (k === "thenNow") {
+ if (v.seconds !== undefined && !numIn(v.seconds, 0.3, 2)) errors.push(`${w}.seconds must be from 0.3 to 2`);
+ if (v.dates !== undefined && !FX_DATES.includes(v.dates)) errors.push(`${w}.dates must be ${oneOf(FX_DATES)}`);
+ if (v.pairs !== undefined) {
+ if (!Array.isArray(v.pairs) || !v.pairs.length) errors.push(`${w}.pairs must be a list of { then, now } clip ids`);
+ else {
+ v.pairs.forEach((p, i) => {
+ if (!isObj(p) || typeof p.then !== "string" || !p.then || typeof p.now !== "string" || !p.now ||
+ Object.keys(p).some((x) => x !== "then" && x !== "now")) {
+ errors.push(`${w}.pairs[${i}] must be { "then": <clip id>, "now": <clip id> }`);
+ }
+ });
+ }
+ } else errors.push(`${w}.pairs is needed: which THEN clip hands over to which NOW clip`);
+ }
+ if (k === "receipts") {
+ if (v.position !== undefined && !FX_SIDES.includes(v.position)) errors.push(`${w}.position must be ${oneOf(FX_SIDES)}`);
+ if (v.width !== undefined && !numIn(v.width, 0.2, 0.6)) errors.push(`${w}.width must be from 0.2 to 0.6 (of the footage box)`);
+ }
+ if (k === "zoom") {
+ if (v.width !== undefined && !numIn(v.width, 0.3, 0.9)) errors.push(`${w}.width must be from 0.3 to 0.9 (of the footage box)`);
+ }
+ }
+ const kq = fx.kineticQuote, rd = fx.redact;
+ if (isObj(kq) && isObj(rd)) {
+ const a = Array.isArray(kq.clips) ? kq.clips : null;
+ const b = Array.isArray(rd.clips) ? rd.clips : null;
+ if (!a && !b) errors.push(`${where}.kineticQuote and ${where}.redact both draw every clip's line: give one of them clips`);
+ else if (a && b && a.some((c) => b.includes(c))) {
+ errors.push(`${where}.kineticQuote and ${where}.redact both name ${a.filter((c) => b.includes(c)).join(", ")}: one treatment a clip`);
+ }
+ }
+ return errors;
+}
+
+const rect01 = (r) => Array.isArray(r) && r.length === 4 && r.every((v) => numIn(v, 0, 1)) && r[2] > r[0] && r[3] > r[1];
+
+function shotError(shot, what) {
+ if (typeof shot !== "string" || !shot.trim()) return `${what} must be a path beside the manifest`;
+ if (/^[a-z]+:\/\//i.test(shot)) return `${what} must be a file beside the manifest, not a URL`;
+ const ext = shot.slice(shot.lastIndexOf(".")).toLowerCase();
+ if (!FX_SHOT_EXTS.includes(ext)) return `${what} must be ${FX_SHOT_EXTS.join(", ")}`;
+ return null;
+}
+
+/**
+ * Every reason the entries' `fx` and the effects' clip lists cannot be built,
+ * against the whole manifest: a bad entry `fx`, a clip list naming no clip, a
+ * THEN/NOW pair that is not a clip and the very next entry, and the popup
+ * posts moving the footage the effects are drawn over.
+ *
+ * @returns {string[]}
+ */
+export function validateFxEntries(manifest) {
+ const errors = [];
+ const timeline = manifest?.timeline ?? [];
+ const render = manifest?.render ?? {};
+ for (const e of timeline) {
+ if (e?.fx === undefined) continue;
+ const w = `timeline entry ${e.id ?? "?"}: fx`;
+ if (!isObj(e.fx)) { errors.push(`${w} must be an object`); continue; }
+ if (e.type !== "clip" && e.type !== "image") errors.push(`${w} is for a clip or an image`);
+ for (const k of Object.keys(e.fx)) {
+ if (!["punch", "quote", "receipts", "zoom", "punchIn", "speakers"].includes(k)) errors.push(`${w}.${k} is not an effect field`);
+ }
+ if (e.fx.punch !== undefined && !(typeof e.fx.punch === "string" && e.fx.punch.trim() && e.fx.punch.length <= 120)) {
+ errors.push(`${w}.punch must be the words to punch (at most 120 characters)`);
+ }
+ if (e.fx.quote !== undefined && typeof e.fx.quote !== "boolean") errors.push(`${w}.quote must be true or false`);
+ if (e.fx.punchIn !== undefined) {
+ const ok = Array.isArray(e.fx.punchIn) && e.fx.punchIn.length > 0 && e.fx.punchIn.length <= 8 &&
+ e.fx.punchIn.every((t) => typeof t === "number" && Number.isFinite(t) && t >= 0);
+ if (!ok) errors.push(`${w}.punchIn must be a list of 1 to 8 source seconds`);
+ else if (e.type === "clip" && Number.isFinite(e.start) && Number.isFinite(e.end) && e.fx.punchIn.some((t) => t < e.start || t > e.end)) {
+ errors.push(`${w}.punchIn has a second outside the clip (${e.start}–${e.end})`);
+ }
+ }
+ if (e.fx.speakers !== undefined) {
+ const ok = Array.isArray(e.fx.speakers) && e.fx.speakers.length > 0 &&
+ e.fx.speakers.every((x) => isObj(x) && Number.isFinite(x.at) && (x.who === 0 || x.who === 1) && Object.keys(x).every((kk) => kk === "at" || kk === "who"));
+ if (!ok) errors.push(`${w}.speakers must be a list of { at: <source s>, who: 0 | 1 }`);
+ }
+ if (e.fx.receipts !== undefined) {
+ const r = e.fx.receipts;
+ if (!Array.isArray(r) || !r.length || r.length > FX_RECEIPTS_MAX) {
+ errors.push(`${w}.receipts must be a list of 1 to ${FX_RECEIPTS_MAX} screenshots`);
+ } else {
+ r.forEach((c, i) => {
+ if (!isObj(c)) { errors.push(`${w}.receipts[${i}] must be { shot, mark? }`); return; }
+ for (const k of Object.keys(c)) if (k !== "shot" && k !== "mark") errors.push(`${w}.receipts[${i}].${k} is not a receipt field`);
+ const se = shotError(c.shot, `${w}.receipts[${i}].shot`);
+ if (se) errors.push(se);
+ if (c.mark !== undefined && !rect01(c.mark)) errors.push(`${w}.receipts[${i}].mark must be [left, top, right, bottom], fractions of the shot`);
+ });
+ }
+ }
+ if (e.fx.zoom !== undefined) {
+ const z = e.fx.zoom;
+ if (!isObj(z)) errors.push(`${w}.zoom must be { shot, focus, at? }`);
+ else {
+ for (const k of Object.keys(z)) if (!["shot", "focus", "at"].includes(k)) errors.push(`${w}.zoom.${k} is not a zoom field`);
+ const se = shotError(z.shot, `${w}.zoom.shot`);
+ if (se) errors.push(se);
+ if (!rect01(z.focus)) errors.push(`${w}.zoom.focus must be [left, top, right, bottom], fractions of the shot`);
+ if (z.at !== undefined && !numIn(z.at, 0, 600)) errors.push(`${w}.zoom.at must be seconds into the clip`);
+ }
+ }
+ }
+ const fx = render?.chrome?.fx;
+ if (!isObj(fx)) return errors;
+ const clipIds = new Set(timeline.filter((e) => e?.type === "clip").map((e) => e.id));
+ for (const k of ["kineticQuote", "redact"]) {
+ for (const id of Array.isArray(fx[k]?.clips) ? fx[k].clips : []) {
+ if (!clipIds.has(id)) errors.push(`render.chrome.fx.${k}.clips names ${id}, which is not a clip of the cut`);
+ }
+ }
+ if (isObj(fx.thenNow) && Array.isArray(fx.thenNow.pairs)) {
+ const at = new Map(timeline.map((e, i) => [e?.id, i]));
+ const used = new Set();
+ fx.thenNow.pairs.forEach((p, i) => {
+ if (!isObj(p)) return;
+ const a = at.get(p.then), b = at.get(p.now);
+ const w = `render.chrome.fx.thenNow.pairs[${i}]`;
+ if (a === undefined || timeline[a].type !== "clip") errors.push(`${w}.then names ${p.then}, which is not a clip of the cut`);
+ if (b === undefined || timeline[b].type !== "clip") errors.push(`${w}.now names ${p.now}, which is not a clip of the cut`);
+ if (a !== undefined && b !== undefined && b !== a + 1) errors.push(`${w}: ${p.now} must be the entry right after ${p.then} (the wipe is their cut)`);
+ for (const id of [p.then, p.now]) {
+ if (used.has(id)) errors.push(`${w}: ${id} is in another pair's cut`);
+ }
+ used.add(p.then);
+ used.add(p.now);
+ });
+ }
+ // The effects are drawn over the footage box where it STAYS: the popup posts'
+ // shift moves it aside while they are up, and an effect would be drawn over
+ // the ground it left.
+ const deck = render?.chrome?.deck ?? {};
+ const posts = (manifest?.posts ?? []).filter((p) => !p?.hide);
+ const layout = deck.posts?.layout ?? "popup";
+ const show = deck.posts?.show ?? true;
+ const shift = deck.posts?.shift ?? {};
+ if (fxOn(render) && posts.length && show && layout === "popup" && shift !== false) {
+ errors.push("render.chrome.fx is drawn over the footage box, which the popup posts move aside: set render.chrome.deck.posts.shift to false, or use the feed");
+ }
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// Dates, words and phrases.
+// ---------------------------------------------------------------------------
+
+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 fxDate(v) {
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(v ?? "").trim());
+ 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 fxDateLabel = (dt) => (dt ? `${dt.d} ${MONTHS[dt.m - 1]} ${dt.y}` : "");
+
+/** Days since the epoch, so a rail is linear in real time. */
+export const fxDay = (dt) => Date.UTC(dt.y, dt.m - 1, dt.d) / 86400000;
+
+/** The day a clip's recording is dated by: `montage.date`, the clip's `date`, else its record's upload date. */
+export function fxClipDate(entry, meta) {
+ return fxDate(entry?.montage?.date) ?? fxDate(entry?.date) ?? fxDate(meta?.uploadDate);
+}
+
+/** A word as it is matched: lower case letters and digits only. */
+export const fxNorm = (w) => String(w ?? "").toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}]+/gu, "");
+
+/** A word as it is shown: no caption furniture (">>", "[Music]"), trimmed. */
+export const fxShown = (w) => String(w ?? "").replace(/>>+/g, "").replace(/\[[^\]]*\]/g, "").trim();
+
+/**
+ * Timed spans (cues: a line each; whisper's words: a word each) as words, in
+ * the spans' seconds: each word of a span takes its share of the span by its
+ * characters, so a long word takes longer than a short one. Only the words
+ * whose middle is in [from, to]; caption furniture dropped.
+ *
+ * @param {Array<{start: number, end: number, text: string}>} spans
+ * @returns {Array<{text: string, start: number, end: number}>}
+ */
+export function fxWordsOf(spans, from = -Infinity, to = Infinity) {
+ const out = [];
+ const used = (spans ?? []).filter((s) => Number.isFinite(s?.start) && Number.isFinite(s?.end) && s.end >= s.start)
+ .slice().sort((a, b) => a.start - b.start);
+ for (const s of used) {
+ // A speaker's turn is marked in captions as ">>" or a dash before the
+ // words ("- Oh god, it is. - Sometimes…"): the next word carries `turn`.
+ const words = [];
+ let turn = false;
+ for (const raw of String(s.text ?? "").replace(/\[[^\]]*\]/g, " ").split(/\s+/)) {
+ if (/^(?:>>+|-|–|—)$/.test(raw)) { turn = true; continue; }
+ if (/^>>/.test(raw)) turn = true;
+ const w = fxShown(raw);
+ if (!w || !fxNorm(w)) continue;
+ words.push({ w, turn });
+ turn = false;
+ }
+ if (!words.length) continue;
+ const chars = words.reduce((n, x) => n + x.w.length + 1, 0);
+ let c = 0;
+ for (const { w, turn: t } of words) {
+ const a = s.start + ((s.end - s.start) * c) / chars;
+ c += w.length + 1;
+ const b = s.start + ((s.end - s.start) * (c - 1)) / chars;
+ const mid = (a + b) / 2;
+ if (mid >= from && mid <= to) out.push({ text: w, start: a, end: Math.max(a, b), ...(t ? { turn: true } : {}) });
+ }
+ }
+ return out;
+}
+
+/**
+ * A clip's quote with no timed words: its `quote` (else its on-screen title)
+ * spread evenly over the cited span [cutStart, cutEnd] (else the extent), in
+ * SOURCE seconds. What an estimated schedule draws, and what a build falls
+ * back to when the clip's words cannot be read.
+ */
+export function fxQuoteFallback(entry) {
+ const text = typeof entry?.quote === "string" && entry.quote.trim() ? entry.quote : entry?.onscreen?.title ?? "";
+ const hasCut = Number.isFinite(entry?.cutStart) && Number.isFinite(entry?.cutEnd);
+ const a = hasCut ? entry.cutStart : entry?.start, b = hasCut ? entry.cutEnd : entry?.end;
+ if (!String(text).trim() || !Number.isFinite(a) || !Number.isFinite(b) || b <= a) return [];
+ return fxWordsOf([{ start: a, end: b, text }]);
+}
+
+/** The span a clip's quote is cut from, in SOURCE seconds: the cited cut, else the extent. */
+export function fxQuoteSpan(entry) {
+ const hasCut = Number.isFinite(entry?.cutStart) && Number.isFinite(entry?.cutEnd);
+ return hasCut ? { from: entry.cutStart, to: entry.cutEnd } : { from: entry?.start, to: entry?.end };
+}
+
+/** The words a clip punches: its `fx.punch`, else its `montage.match`; null for none. */
+export function fxPunchOf(entry) {
+ const p = entry?.fx?.punch ?? entry?.montage?.match ?? null;
+ return typeof p === "string" && p.trim() ? p : null;
+}
+
+/** Which of `words` are the punch phrase, every time it is said: a boolean per word. */
+export function punchMask(words, phrase) {
+ const mask = words.map(() => false);
+ const needle = String(phrase ?? "").split(/\s+/).map(fxNorm).filter(Boolean);
+ if (!needle.length) return mask;
+ const hay = words.map((w) => fxNorm(w.text));
+ for (let i = 0; i + needle.length <= hay.length; i += 1) {
+ let ok = true;
+ for (let j = 0; j < needle.length && ok; j += 1) {
+ // The last word may run on ("news" in "newsday"? no: "day" in "days").
+ ok = j === needle.length - 1 ? hay[i + j].startsWith(needle[j]) : hay[i + j] === needle[j];
+ }
+ if (ok) for (let j = 0; j < needle.length; j += 1) mask[i + j] = true;
+ }
+ return mask;
+}
+
+/**
+ * Words split into pages of at most `max`, preferring to break after a word
+ * that ends a sentence or a clause once a page is half full.
+ */
+export function quotePages(words, max) {
+ const pages = [];
+ let cur = [];
+ for (const w of words) {
+ cur.push(w);
+ const ends = /[.!?;:,]$/.test(w.text);
+ if (cur.length >= max || (ends && cur.length >= Math.ceil(max / 2))) {
+ pages.push(cur);
+ cur = [];
+ }
+ }
+ if (cur.length) {
+ // A last page of one or two words joins the one before when it fits.
+ const prev = pages[pages.length - 1];
+ if (prev && cur.length <= 2 && prev.length + cur.length <= max + 2) prev.push(...cur);
+ else pages.push(cur);
+ }
+ return pages;
+}
+
+// ---------------------------------------------------------------------------
+// The schedule: `schedule.fx`, in the cut's seconds, written by deckSchedule
+// only when an effect is on.
+// ---------------------------------------------------------------------------
+
+/**
+ * The effects' times. `segments` are deckSchedule's (`{id, start, duration}`,
+ * holds included), `entries` the timeline, `metas` each entry's source
+ * metadata (or null), `words` a Map of clip id → the clip's timed words in its
+ * SEGMENT's seconds (second 0 = the segment's first frame) or null -- without
+ * a clip's words its quote falls back to `fxQuoteFallback` placed by
+ * `playWindow` (the caller passes `sourceFrom`). `hidden` says which segments
+ * the deck slides away over (a card, the teaser): no effect is drawn there.
+ *
+ * @param {{ segments: Array<{id: string, start: number, duration: number}>, entries: any[], metas?: any[],
+ * render: any, D: number, total: number, words?: Map<string, Array<{text: string, start: number, end: number}>> | null,
+ * sourceFrom: (entry: any) => number, hidden: (entry: any) => boolean, fps?: number }} args
+ */
+export function fxSchedule({ segments, entries, metas = [], render, D, total, words = null, sourceFrom, hidden, fps = 30 }) {
+ const keys = fxKeysOn(render);
+ if (!keys.length) return null;
+ const out = { keys };
+ const clips = [];
+ segments.forEach((s, i) => {
+ const e = entries[i];
+ if (e?.type !== "clip" && e?.type !== "image") return;
+ if (hidden(e)) return;
+ // The span the clip is clean on screen: from its mid-dissolve in to its
+ // mid-dissolve out (the deck's own handover instants).
+ const first = i === 0, last = i === segments.length - 1;
+ const inn = first ? s.start : s.start + D / 2;
+ const outT = last ? Math.min(total, s.start + s.duration) : s.start + s.duration - D / 2;
+ clips.push({ i, id: e.id, type: e.type, entry: e, meta: metas[i] ?? null, start: s.start, duration: s.duration, in: inn, out: outT });
+ });
+ const vclips = clips.filter((c) => c.type === "clip");
+ const spans = joinedSpans(vclips);
+
+ // Each clip's words in the CUT's seconds (null: none).
+ const cutWords = new Map();
+ const wordsOf = (c) => {
+ if (cutWords.has(c.id)) return cutWords.get(c.id);
+ let ws = words?.get(c.id) ?? null;
+ if (!ws || !ws.length) {
+ const fb = fxQuoteFallback(c.entry);
+ const f0 = sourceFrom(c.entry);
+ ws = fb.map((w) => ({ ...w, start: w.start - f0, end: w.end - f0 }));
+ }
+ const placed = (ws ?? [])
+ .map((w) => ({ text: w.text, at: r3(c.start + w.start), end: r3(c.start + w.end), ...(w.turn ? { turn: true } : {}) }))
+ .filter((w) => w.at < c.out - 0.05 && w.end > c.in - 0.3)
+ .map((w) => ({ ...w, at: r3(Math.max(c.in, w.at)) }));
+ cutWords.set(c.id, placed.length ? placed : null);
+ return cutWords.get(c.id);
+ };
+
+ // ---- the line: kinetic or redacted ----------------------------------------
+ const quoteOf = (key, style) => {
+ const cfg = resolveFx(render, key);
+ if (!cfg) return [];
+ const names = Array.isArray(cfg.clips) ? new Set(cfg.clips) : null;
+ const otherCfg = resolveFx(render, key === "kineticQuote" ? "redact" : "kineticQuote");
+ const otherNames = otherCfg && Array.isArray(otherCfg.clips) ? new Set(otherCfg.clips) : null;
+ const res = [];
+ for (const c of vclips) {
+ if (c.entry.fx?.quote === false) continue;
+ // Named, or (no list) every clip the other treatment does not name.
+ if (names ? !names.has(c.id) : otherNames?.has(c.id)) continue;
+ const ws = wordsOf(c);
+ if (!ws) continue;
+ const mask = punchMask(ws, fxPunchOf(c.entry));
+ const who = style === "kinetic" && cfg.speakers === "auto" ? speakersOf(ws, c, sourceFrom) : null;
+ const marked = ws.map((w, j) => ({ ...w, punch: mask[j], ...(who ? { speaker: who[j] } : {}) }));
+ // A page holds one speaker's words: a turn starts a new page.
+ const runs = [];
+ for (const w of marked) {
+ const last = runs[runs.length - 1];
+ if (last && last[0].speaker === w.speaker) last.push(w);
+ else runs.push([w]);
+ }
+ const pages = runs.flatMap((run) => quotePages(run, cfg.maxWords)).map((pw, p, all) => {
+ const pin = r3(Math.max(c.in, pw[0].at - FX_MOTION.page));
+ const next = all[p + 1];
+ const pout = r3(next ? Math.max(pin + 0.3, next[0].at - FX_MOTION.page) : c.out);
+ return {
+ in: pin, out: pout,
+ ...(who ? { speaker: pw[0].speaker } : {}),
+ words: pw.map((w) => ({ text: w.text, at: r3(Math.min(Math.max(w.at, pin), pout - 0.05)), punch: w.punch })),
+ };
+ });
+ res.push({ segment: c.id, style, in: r3(c.in), out: r3(c.out), pages });
+ }
+ return res;
+ };
+ const quotes = [...quoteOf("kineticQuote", "kinetic"), ...quoteOf("redact", "redact")]
+ .sort((a, b) => a.in - b.in);
+ if (keys.includes("kineticQuote") || keys.includes("redact")) {
+ out.quotes = quotes;
+ const style = (key) => {
+ const c = resolveFx(render, key);
+ return c ? { position: c.position, size: c.size } : null;
+ };
+ out.quoteStyle = { ...(style("kineticQuote") ? { kinetic: style("kineticQuote") } : {}), ...(style("redact") ? { redact: style("redact") } : {}) };
+ // The two voices, only when a line has more than one speaker.
+ const kq = resolveFx(render, "kineticQuote");
+ if (kq && quotes.some((q) => q.pages.some((p) => p.speaker === 1))) {
+ out.quoteStyle.voices = [0, 1].map((i) => ({
+ label: String(kq.voices?.[i]?.label ?? "").trim(),
+ color: kq.voices?.[i]?.color ?? FX_VOICE_COLORS[i],
+ }));
+ }
+ }
+
+ // ---- the odometer ----------------------------------------------------------
+ const odo = resolveFx(render, "odometer");
+ if (odo) {
+ let prev = 0;
+ const counts = vclips.map((c, k) => {
+ const value = Number.isInteger(c.entry.montage?.n) && c.entry.montage.n > 0 ? c.entry.montage.n : k + 1;
+ let at = c.in + 0.25;
+ if (odo.at === "phrase") {
+ const ws = wordsOf(c);
+ const mask = ws ? punchMask(ws, fxPunchOf(c.entry)) : [];
+ const j = mask.indexOf(true);
+ if (j >= 0) at = ws[j].at;
+ }
+ const row = { segment: c.id, value, prev, at: r3(Math.min(Math.max(at, c.in), c.out - 0.1)) };
+ prev = value;
+ return row;
+ });
+ out.odometer = {
+ position: odo.position, label: String(odo.label ?? "").trim(),
+ digits: Math.max(1, ...counts.map((c) => String(c.value).length)),
+ counts, spans,
+ };
+ }
+
+ // ---- the scrubber ------------------------------------------------------------
+ const scr = resolveFx(render, "scrubber");
+ if (scr) {
+ const ticks = vclips
+ .map((c) => ({ c, dt: fxClipDate(c.entry, c.meta) }))
+ .filter((t) => t.dt)
+ .map(({ c, dt }) => ({ segment: c.id, day: fxDay(dt), label: fxDateLabel(dt), year: dt.y, in: r3(c.in), out: r3(c.out) }));
+ if (ticks.length) {
+ const d0 = Math.min(...ticks.map((t) => t.day)), d1 = Math.max(...ticks.map((t) => t.day));
+ const pad = Math.max(1, (d1 - d0) * 0.04);
+ const years = [];
+ for (let y = new Date((d0 - pad) * 86400000).getUTCFullYear() + 1; fxDay({ y, m: 1, d: 1 }) <= d1 + pad; y += 1) {
+ years.push({ year: y, day: fxDay({ y, m: 1, d: 1 }) });
+ }
+ out.scrubber = {
+ position: scr.position, thumbs: scr.thumbs, from: d0 - pad, to: d1 + pad, years,
+ ticks: ticks.map((t) => ({ ...t })), spans,
+ };
+ }
+ }
+
+ // ---- the glitch: a tear at a cut between years -------------------------------
+ const gl = resolveFx(render, "glitch");
+ if (gl) {
+ const bursts = [];
+ for (let k = 1; k < vclips.length; k += 1) {
+ const a = vclips[k - 1], b = vclips[k];
+ // Consecutive in the cut: a card between them is its own break.
+ if (b.i !== a.i + 1) continue;
+ const da = fxClipDate(a.entry, a.meta), db = fxClipDate(b.entry, b.meta);
+ if (gl.on === "year" && !(da && db && da.y !== db.y)) continue;
+ const m = segments[b.i].start + D / 2;
+ bursts.push({
+ segment: b.id, at: r3(m), seconds: gl.seconds,
+ year: db ? db.y : null, date: db ? fxDateLabel(db) : "", seed: k,
+ });
+ }
+ out.glitch = { stamp: gl.stamp, bursts };
+ }
+
+ // ---- THEN / NOW ---------------------------------------------------------------
+ const tn = resolveFx(render, "thenNow");
+ if (tn) {
+ const wipes = [];
+ for (const p of tn.pairs ?? []) {
+ const a = clips.find((c) => c.id === p.then), b = clips.find((c) => c.id === p.now);
+ if (!a || !b || b.i !== a.i + 1) continue;
+ const fmt = (c) => {
+ const dt = fxClipDate(c.entry, c.meta);
+ return dt ? (tn.dates === "year" ? String(dt.y) : fxDateLabel(dt)) : "";
+ };
+ // With a crossfade the cut itself is a wipe (`wipeleft`, build-video's
+ // xfadeGraph) over [start, start + D], the divider riding its edge; on a
+ // hard cut the divider alone sweeps over `seconds` centred on the cut.
+ const start = segments[b.i].start;
+ const real = D > 0;
+ const from = real ? start : start - tn.seconds / 2;
+ const seconds = real ? D : tn.seconds;
+ wipes.push({ then: a.id, now: b.id, at: r3(from), seconds: r4(seconds), real, thenDate: fmt(a), nowDate: fmt(b), index: b.i });
+ }
+ out.thenNow = { wipes };
+ }
+
+ // ---- the punch-in: the footage snaps in on a moment ---------------------------
+ const pi = resolveFx(render, "punchIn");
+ if (pi) {
+ const rows = [];
+ for (const c of vclips) {
+ const f0 = sourceFrom(c.entry);
+ const seconds = new Set((Array.isArray(c.entry.fx?.punchIn) ? c.entry.fx.punchIn : []).map((t) => r3(t - f0)));
+ // A laugh written in the captions, when `auto`: the word's start.
+ if (pi.auto) for (const w of wordsOf(c) ?? []) if (FX_LAUGH_RE.test(fxNorm(w.text))) seconds.add(r3(w.at - c.start));
+ // In the segment's clock, inside the clip's clean span; two closer than
+ // the hold are one.
+ const lo = c.in - c.start, hi = c.out - c.start - 0.1;
+ let last = -Infinity;
+ for (const t of [...seconds].sort((a, b) => a - b)) {
+ if (t < lo || t > hi - 0.2 || t < last + pi.hold) continue;
+ const until = Math.min(hi, t + pi.hold);
+ rows.push({
+ segment: c.id, index: c.i, at: r3(c.start + t), until: r3(c.start + until),
+ segmentAt: r3(t), segmentUntil: r3(until), scale: pi.scale, anchor: pi.anchor,
+ });
+ last = t;
+ }
+ }
+ out.punchIn = { punches: rows };
+ }
+
+ // ---- the whip: a cut that slides like a whip pan --------------------------------
+ const wh = resolveFx(render, "whip");
+ if (wh) {
+ const wipeAt = new Set((out.thenNow?.wipes ?? []).map((w) => w.index));
+ const cuts = [];
+ for (let k = 1; k < vclips.length; k += 1) {
+ const a = vclips[k - 1], b = vclips[k];
+ if (b.i !== a.i + 1 || wipeAt.has(b.i)) continue;
+ if (wh.on === "year") {
+ const da = fxClipDate(a.entry, a.meta), db = fxClipDate(b.entry, b.meta);
+ if (!(da && db && da.y !== db.y)) continue;
+ }
+ const start = segments[b.i].start;
+ // With a crossfade the cut slides (`slideleft`) over [start, start + D];
+ // on a hard cut the streaks alone flash across it.
+ const real = D > 0;
+ cuts.push({ segment: b.id, index: b.i, at: r3(real ? start : start - 0.12), seconds: r4(real ? D : 0.24), real });
+ }
+ out.whip = { cuts };
+ }
+
+ // ---- receipts and the zoom -----------------------------------------------------
+ const rc = resolveFx(render, "receipts");
+ if (rc) {
+ const rows = [];
+ for (const c of clips) {
+ const list = c.entry.fx?.receipts;
+ if (!Array.isArray(list) || !list.length) continue;
+ const inn = c.in + 0.3, outT = c.out - 0.25;
+ if (outT - inn < 1) continue;
+ rows.push({
+ segment: c.id, in: r3(inn), out: r3(outT),
+ cards: list.map((x, j) => ({ shot: x.shot, mark: x.mark ?? null, at: r3(inn + j * FX_MOTION.fanGap) })),
+ markAt: r3(Math.min(outT - FX_MOTION.marker - 0.2, inn + list.length * FX_MOTION.fanGap + FX_MOTION.fan + 0.15)),
+ });
+ }
+ out.receipts = { position: rc.position, width: rc.width, clips: rows };
+ }
+ const zm = resolveFx(render, "zoom");
+ if (zm) {
+ const rows = [];
+ for (const c of clips) {
+ const z = c.entry.fx?.zoom;
+ if (!isObj(z)) continue;
+ const inn = c.in + 0.2, outT = c.out - 0.3;
+ if (outT - inn < 2) continue;
+ const outline = inn + 0.55;
+ const push = Math.min(outT - FX_MOTION.push - 0.3, Math.max(outline + FX_MOTION.outline + 0.2, Number.isFinite(z.at) ? c.start + z.at : 0));
+ rows.push({ segment: c.id, in: r3(inn), out: r3(outT), shot: z.shot, focus: z.focus, outline: r3(outline), push: r3(push) });
+ }
+ out.zoom = { width: zm.width, clips: rows };
+ }
+ return out;
+}
+
+/** The clips' clean spans, with clips that follow each other joined. */
+function joinedSpans(clips) {
+ const out = [];
+ for (const c of clips) {
+ const last = out[out.length - 1];
+ if (last && last.i === c.i - 1) {
+ last.out = r3(c.out);
+ last.i = c.i;
+ } else out.push({ in: r3(c.in), out: r3(c.out), i: c.i });
+ }
+ return out.map(({ i: _i, ...s }) => s);
+}
+
+/** Which segments a THEN/NOW pair turns into a wipe: the THEN segment's index, for its join. */
+export function fxWipeJoins(schedule) {
+ return new Set((schedule?.fx?.thenNow?.wipes ?? []).filter((w) => w.real).map((w) => w.index - 1));
+}
+
+/** Which segments' cut out of them is a whip (`slideleft`): the outgoing segment's index, for its join. */
+export function fxWhipJoins(schedule) {
+ return new Set((schedule?.fx?.whip?.cuts ?? []).filter((w) => w.real).map((w) => w.index - 1));
+}
+
+/** Each segment's punch-ins in its own clock, for its join: index → [{at, until, scale, anchor}]. */
+export function fxZoomJoins(schedule) {
+ const out = new Map();
+ for (const p of schedule?.fx?.punchIn?.punches ?? []) {
+ if (!out.has(p.index)) out.set(p.index, []);
+ out.get(p.index).push({ at: p.segmentAt, until: p.segmentUntil, scale: p.scale, anchor: p.anchor, ...(schedule.fx.box ? { box: schedule.fx.box } : {}) });
+ }
+ return out;
+}
+
+/**
+ * Who says each word of a clip's line: 0 or 1. The clip's `fx.speakers`
+ * (source seconds; each holds until the next) when it has them, else the
+ * captions' own turn marks (">>", a dash), each turn handing over to the
+ * other voice; the first voice is whoever speaks first in the line. Null when
+ * the line has one voice. It says WHICH of two voices, never whose: the
+ * labels are the manifest's (`kineticQuote.voices`).
+ */
+export function speakersOf(words, c, sourceFrom) {
+ const marks = Array.isArray(c.entry?.fx?.speakers) ? [...c.entry.fx.speakers].sort((a, b) => a.at - b.at) : null;
+ let who;
+ if (marks?.length) {
+ const f0 = sourceFrom(c.entry);
+ who = words.map((w) => {
+ const src = w.at - c.start + f0;
+ let v = marks[0].who;
+ for (const m of marks) if (m.at <= src + 1e-6) v = m.who;
+ return v;
+ });
+ } else {
+ let v = 0;
+ who = words.map((w, j) => {
+ if (j > 0 && w.turn) v = 1 - v;
+ return v;
+ });
+ }
+ return who.some((v) => v === 1) ? who : null;
+}
+
+// ---------------------------------------------------------------------------
+// The geometry and the cue list.
+// ---------------------------------------------------------------------------
+
+/**
+ * Seeded and stateless: the same seed gives the same numbers, on any worker,
+ * in any order (mulberry32).
+ */
+export function fxRandom(seed) {
+ let a = (seed >>> 0) || 1;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/**
+ * Events in, seek-safe cues out: ordered by time, clamped so a cue never starts
+ * before the last on its element ends, every `from` stated (the last `to` on
+ * that element, or its `init`). The page plays these with `fromTo` and
+ * `immediateRender: false`, so a seek from anywhere to anywhere lands on the
+ * same pixels.
+ *
+ * @param {Record<string, object>} init
+ * @param {Array<{k: string, at: number, dur: number, to: object, ease?: string}>} events
+ */
+export function compileCues(init, events) {
+ const ev = events.map((e, n) => ({ ...e, to: noNegZero(e.to), at: r4(e.at), dur: r4(Math.max(INSTANT, e.dur)), ease: e.ease ?? "none", n }));
+ ev.sort((a, b) => a.at - b.at || a.n - b.n);
+ const state = Object.fromEntries(Object.entries(init).map(([k, v]) => [k, noNegZero(v)]));
+ const freeAt = new Map();
+ const cues = [];
+ for (const e of ev) {
+ let { at, dur } = e;
+ const free = freeAt.get(e.k) ?? 0;
+ if (at < free) {
+ const end = at + dur;
+ at = r4(free);
+ dur = r4(Math.max(INSTANT, end - at));
+ }
+ const cur = state[e.k] ?? (state[e.k] = {});
+ const from = {};
+ for (const p of Object.keys(e.to)) from[p] = cur[p] ?? defaultOf(p);
+ Object.assign(cur, e.to);
+ freeAt.set(e.k, r4(at + dur));
+ cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease });
+ }
+ return cues;
+}
+
+/** An object's numbers with -0 as 0: the cue list is data, and JSON has no -0. */
+export function noNegZero(o) {
+ const out = {};
+ for (const [k, v] of Object.entries(o ?? {})) out[k] = typeof v === "number" && Object.is(v, -0) ? 0 : v;
+ return out;
+}
+
+const defaultOf = (p) => (p === "scale" || p === "scaleX" || p === "scaleY" || p === "opacity" || p === "autoAlpha" ? 1 : 0);
+
+// ---------------------------------------------------------------------------
+// Presets: what the Takes page's Effect list and `umtool take --effect` offer.
+// ---------------------------------------------------------------------------
+
+/**
+ * THEN/NOW pairs a cut offers by itself: neighbouring clips whose dates are
+ * years apart, the widest gaps first, no clip in two pairs, at most `max`.
+ */
+export function fxSuggestPairs(manifest, max = 2) {
+ const tl = manifest?.timeline ?? [];
+ const cands = [];
+ for (let i = 1; i < tl.length; i += 1) {
+ const a = tl[i - 1], b = tl[i];
+ if (a?.type !== "clip" || b?.type !== "clip") continue;
+ const da = fxClipDate(a, null), db = fxClipDate(b, null);
+ if (!da || !db || da.y === db.y) continue;
+ cands.push({ then: a.id, now: b.id, gap: Math.abs(fxDay(db) - fxDay(da)), i });
+ }
+ cands.sort((x, y) => y.gap - x.gap || x.i - y.i);
+ const used = new Set();
+ const out = [];
+ for (const c of cands) {
+ if (out.length >= max || used.has(c.then) || used.has(c.now)) continue;
+ used.add(c.then);
+ used.add(c.now);
+ out.push(c);
+ }
+ return out.sort((x, y) => x.i - y.i).map(({ then, now }) => ({ then, now }));
+}
+
+/**
+ * The effect presets for one manifest, each a merge patch a take applies
+ * (`{render: {transition, chrome: {engine, layout, fx}}}`): one per effect the
+ * cut can show, and "everything" -- the line, the rail, the tears, the wipes,
+ * the receipts and the zoom together. The transition is the cut's own when it
+ * has one (0.4 s when it cuts hard), so the THEN/NOW wipe has a crossfade to
+ * ride; the deck's settings are left as they are (a merge patch keeps them).
+ * Pure, deterministic: the same manifest, the same presets.
+ *
+ * @returns {Array<{ name: string, label: string, summary: string, patch: Record<string, any> }>}
+ */
+export function fxPresetsFor(manifest) {
+ const tl = manifest?.timeline ?? [];
+ const t = Number(manifest?.render?.transition ?? 0);
+ const transition = t > 0 ? t : 0.4;
+ const patch = (fx) => ({ render: { transition, chrome: { engine: "hyperframes", layout: "deck", fx } } });
+ const pairs = fxSuggestPairs(manifest);
+ const hasReceipts = tl.some((e) => Array.isArray(e?.fx?.receipts) && e.fx.receipts.length);
+ const hasZoom = tl.some((e) => isObj(e?.fx?.zoom));
+ const out = [
+ { name: "kinetic-quote", label: "Kinetic quote", summary: "Each clip's line word by word as it is said, the key phrase punched", fx: { kineticQuote: {} } },
+ { name: "redaction", label: "Redaction reveal", summary: "Each clip's line under black bars that lift as it is said", fx: { redact: {} } },
+ { name: "odometer", label: "Odometer", summary: "A counter that rolls up on each clip", fx: { odometer: {} } },
+ { name: "scrubber", label: "Timeline scrubber", summary: "A date rail, the playhead sliding to each clip's day with its picture", fx: { scrubber: {} } },
+ { name: "glitch", label: "VHS glitch", summary: "A tape tear and the new year at each cut between years", fx: { glitch: {} } },
+ { name: "punch-in", label: "Punch-in", summary: "The picture snaps in on each marked second and each laugh in the captions", fx: { punchIn: {} } },
+ { name: "whip", label: "Whip cut", summary: "Every cut between clips slides like a whip pan, streaks across it", fx: { whip: {} } },
+ { name: "reaction", label: "Reaction highlights", summary: "Captions in each speaker's colour, punch-ins on laughs, whip cuts, a running count", fx: { kineticQuote: {}, punchIn: {}, whip: {}, odometer: {} } },
+ ];
+ if (pairs.length) {
+ out.push({ name: "then-now", label: "THEN / NOW wipe", summary: `The cut from THEN to NOW wipes, the two dates on its edge (${pairs.map((p) => `${p.then} → ${p.now}`).join(", ")})`, fx: { thenNow: { pairs } } });
+ }
+ if (hasReceipts) out.push({ name: "receipts", label: "Receipts", summary: "The clips' screenshots fan in and a marker swipes the cited line", fx: { receipts: {} } });
+ if (hasZoom) out.push({ name: "zoom", label: "Zoom to detail", summary: "A screenshot pushed in on its detail", fx: { zoom: {} } });
+ const all = { kineticQuote: {}, scrubber: {}, glitch: {} };
+ if (pairs.length) all.thenNow = { pairs };
+ if (hasReceipts) all.receipts = {};
+ if (hasZoom) all.zoom = {};
+ out.push({ name: "everything", label: "Everything", summary: `Together: ${Object.keys(all).map((k) => out.find((o) => o.fx[k])?.label).filter(Boolean).join(", ")}`, fx: all });
+ return out.map(({ fx, ...p }) => ({ ...p, patch: patch(fx) }));
+}
diff --git a/umtool/report-to-video/fx.test.mjs b/umtool/report-to-video/fx.test.mjs
@@ -0,0 +1,446 @@
+// Tests for the effects region's pure half (fx.mjs, release 35 O2): the
+// validators, the schedule's times (each to the frame), the cue compiler, and
+// the promise that a cut without `render.chrome.fx` schedules, joins and
+// crossfades exactly as it did.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ FX_KEYS, compileCues, fxClipDate, fxKeysOn, fxOn, fxQuoteFallback, fxRandom, fxSchedule, fxWipeJoins, fxWordsOf,
+ punchMask, quotePages, resolveFx, validateFx, validateFxEntries,
+} from "./fx.mjs";
+import { deckSchedule, estimateSchedule, fxGeometry, deckGeometry, feedGeometry, validateChrome, hidesDeck, resolveDeck, playWindow } from "./deck.mjs";
+import { segmentJoins, xfadeBatchJoins, xfadeGraph, chromeOverlayChain, fxRegion } from "./build-video.mjs";
+
+const PALETTE = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", amber: "#ffc860" };
+const FPS = 30;
+const FRAME = 1 / FPS;
+const render = (fx, extra = {}) => ({
+ width: 1920, height: 1080, fps: FPS, transition: 0.5, palette: PALETTE,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } }, ...(fx === undefined ? {} : { fx }) },
+ ...extra,
+});
+const clip = (id, date, extra = {}) => ({
+ type: "clip", id, channel: "ch", video: `v${id}`, start: 10, end: 18, cutStart: 11, cutEnd: 17, date,
+ quote: "it must be an exceedingly slow news week as we have what appears to be collusion",
+ montage: { match: "slow news week", n: Number(id.slice(1)) * 9 }, ...extra,
+});
+const TIMELINE = [
+ clip("c1", "2019-05-02"),
+ clip("c2", "2020-06-11", { fx: { receipts: [{ shot: "shots/b.png", mark: [0.04, 0.3, 0.9, 0.5] }, { shot: "shots/a.png" }] } }),
+ clip("c3", "2021-01-01"),
+ clip("c4", "2026-01-01", { fx: { zoom: { shot: "shots/a.png", focus: [0.1, 0.2, 0.6, 0.4] } } }),
+];
+const ALL = {
+ kineticQuote: { clips: ["c1", "c3", "c4"] }, redact: { clips: ["c2"] }, odometer: {}, scrubber: {}, glitch: {},
+ thenNow: { pairs: [{ then: "c3", now: "c4" }] }, receipts: {}, zoom: {},
+};
+const near = (a, b, tol, msg) => assert.ok(Math.abs(a - b) <= tol + 1e-9, `${msg}: ${a} vs ${b} (±${tol})`);
+
+/** The schedule as the build would write it, from fixed durations and the words given. */
+function sched(fx, { words = null, timeline = TIMELINE, durs = [6.4, 6.4, 6.4, 6.4], D = 0.5 } = {}) {
+ const r = render(fx, { transition: D });
+ return deckSchedule({ entries: timeline, durs, D, render: r, fxWords: words });
+}
+
+// ---------------------------------------------------------------------------
+
+test("validateFx: every effect accepts {} and null; unknown keys and bad values are sentences", () => {
+ assert.deepEqual(validateFx(undefined), []);
+ assert.deepEqual(validateFx(null), []);
+ assert.deepEqual(validateFx({}), []);
+ for (const k of FX_KEYS) {
+ const v = k === "thenNow" ? { pairs: [{ then: "a", now: "b" }] } : {};
+ assert.deepEqual(validateFx({ [k]: v }), [], k);
+ assert.deepEqual(validateFx({ [k]: null }), [], `${k}: null`);
+ }
+ assert.match(validateFx({ sparkle: {} }).join(), /sparkle is not an effect/);
+ assert.match(validateFx({ odometer: { positon: "top-left" } }).join(), /positon is not a odometer setting/);
+ assert.match(validateFx({ odometer: { position: "middle" } }).join(), /position must be/);
+ assert.match(validateFx({ kineticQuote: { maxWords: 2 } }).join(), /maxWords must be a whole number from 3 to 30/);
+ assert.match(validateFx({ glitch: { seconds: 3 } }).join(), /seconds must be from 0.2 to 1.5/);
+ assert.match(validateFx({ thenNow: {} }).join(), /pairs is needed/);
+ assert.match(validateFx({ thenNow: { pairs: [{ then: "a" }] } }).join(), /pairs\[0\] must be/);
+ assert.match(validateFx({ receipts: { width: 0.9 } }).join(), /width must be from 0.2 to 0.6/);
+ assert.match(validateFx({ zoom: [] }).join(), /must be an object/);
+ // The two treatments of a clip's line are one or the other.
+ assert.match(validateFx({ kineticQuote: {}, redact: {} }).join(), /give one of them clips/);
+ assert.match(validateFx({ kineticQuote: { clips: ["c1", "c2"] }, redact: { clips: ["c2"] } }).join(), /both name c2/);
+ assert.deepEqual(validateFx({ kineticQuote: {}, redact: { clips: ["c2"] } }), []);
+});
+
+test("validateChrome knows fx, and refuses through it", () => {
+ assert.deepEqual(validateChrome(render(ALL).chrome, render(ALL)), []);
+ assert.match(validateChrome(render({ wobble: {} }).chrome, render({})).join(), /wobble is not an effect/);
+});
+
+test("validateFxEntries: entry fields, clip lists, the pair's adjacency, and the posts' shift", () => {
+ const m = (fx, timeline = TIMELINE, extra = {}) => ({ render: render(fx), timeline, ...extra });
+ assert.deepEqual(validateFxEntries(m(ALL)), []);
+ // An entry's fx is inert without the effect, but still checked.
+ const bad = [clip("c1", "2019-05-02", { fx: { recipts: [], receipts: [{ shot: "https://x/y.png" }], zoom: { shot: "a.gif", focus: [0.5, 0.5, 0.4, 0.6] } } })];
+ const errs = validateFxEntries(m(undefined, bad)).join("\n");
+ assert.match(errs, /recipts is not an effect field/);
+ assert.match(errs, /not a URL/);
+ assert.match(errs, /\.png, \.jpg, \.jpeg, \.webp/);
+ assert.match(errs, /focus must be \[left, top, right, bottom\]/);
+ assert.match(validateFxEntries(m({ kineticQuote: { clips: ["c9"] } })).join(), /names c9, which is not a clip/);
+ assert.match(validateFxEntries(m({ thenNow: { pairs: [{ then: "c1", now: "c3" }] } })).join(), /c3 must be the entry right after c1/);
+ assert.match(validateFxEntries(m({ thenNow: { pairs: [{ then: "c1", now: "c2" }, { then: "c2", now: "c3" }] } })).join(), /c2 is in another pair's cut/);
+ const posts = [{ id: "p1", platform: "x", text: "t", date: "2020-01-01" }];
+ assert.match(validateFxEntries(m(ALL, TIMELINE, { posts })).join(), /popup posts move aside/);
+ const noShift = render(ALL);
+ noShift.chrome.deck.posts = { shift: false };
+ assert.deepEqual(validateFxEntries({ render: noShift, timeline: TIMELINE, posts }), []);
+});
+
+test("fxOn / fxKeysOn / resolveFx: an effect is on when it is an object", () => {
+ assert.equal(fxOn(render(undefined)), false);
+ assert.equal(fxOn(render(null)), false);
+ assert.equal(fxOn(render({})), false);
+ assert.equal(fxOn(render({ glitch: null })), false);
+ assert.deepEqual(fxKeysOn(render({ glitch: {}, odometer: null, scrubber: {} })), ["scrubber", "glitch"]);
+ assert.deepEqual(resolveFx(render({ glitch: { seconds: 0.8 } }), "glitch"), { on: "year", seconds: 0.8, stamp: true });
+ assert.equal(resolveFx(render({}), "glitch"), null);
+});
+
+test("byte for byte: without an effect on, the schedule is the one it always was", () => {
+ const base = sched(undefined);
+ assert.equal("fx" in base, false);
+ for (const off of [null, {}, { glitch: null, odometer: null }]) {
+ assert.deepEqual(sched(off), base, JSON.stringify(off));
+ assert.equal(JSON.stringify(sched(off)), JSON.stringify(base));
+ }
+ // An entry's fx alone changes nothing either.
+ const bare = TIMELINE.map(({ fx: _f, ...e }) => e);
+ assert.equal(JSON.stringify(sched(undefined, { timeline: bare })), JSON.stringify(base));
+ // And the estimate.
+ const est = (fx) => estimateSchedule({ render: render(fx), timeline: TIMELINE });
+ assert.equal(JSON.stringify(est({})), JSON.stringify(est(undefined)));
+});
+
+test("byte for byte: without a wipe the joins, the crossfade graph and the overlay chain are unchanged", () => {
+ const s = sched(undefined);
+ assert.equal(segmentJoins(s), null);
+ const durs = [6.4, 6.4, 6.4, 6.4];
+ const plain = xfadeGraph(durs, 0.5, null);
+ assert.ok(plain.parts.every((p) => !/wipeleft/.test(p)));
+ assert.equal(JSON.stringify(xfadeGraph(durs, 0.5, [null, null, null, null])), JSON.stringify(plain));
+ assert.equal(xfadeBatchJoins(null, [{ from: 0, to: 2 }, { from: 2, to: 4 }]), null);
+ const dip = { seconds: 1, lastFrame: 10, black: 0 };
+ assert.deepEqual(xfadeBatchJoins([null, { dip }, null, null], [{ from: 0, to: 2 }, { from: 2, to: 4 }]), [{ dip }, null]);
+ const r = render(undefined);
+ const regions = [{ name: "deck", frames: "/o/chrome/deck-frames", x: 0, y: 890, width: 1920, height: 190 }];
+ assert.deepEqual(chromeOverlayChain(r, regions, "[v3]", 4), chromeOverlayChain(r, regions, "[v3]", 4));
+});
+
+test("thenNow: the pair's cut is a wipe on the THEN join; the crossfade wipes left there and only there", () => {
+ const s = sched({ thenNow: { pairs: [{ then: "c3", now: "c4" }] } });
+ assert.deepEqual([...fxWipeJoins(s)], [2]);
+ const joins = segmentJoins(s);
+ assert.deepEqual(joins, [null, null, { hold: 0, move: null, wipe: true }, null]);
+ const g = xfadeGraph([6.4, 6.4, 6.4, 6.4], 0.5, joins);
+ const xf = g.parts.filter((p) => /xfade=/.test(p));
+ assert.equal(xf.length, 3);
+ assert.match(xf[0], /transition=fade/);
+ assert.match(xf[1], /transition=fade/);
+ assert.match(xf[2], /transition=wipeleft:duration=0\.5:offset=17\.700/);
+ // The batched join pass carries it across a batch boundary too.
+ assert.deepEqual(xfadeBatchJoins(joins, [{ from: 0, to: 3 }, { from: 3, to: 4 }]), [{ wipe: true }, null]);
+ // A hard cut has no wipe to make: the divider sweeps alone.
+ const hard = sched({ thenNow: { pairs: [{ then: "c3", now: "c4" }], seconds: 0.8 } }, { D: 0 });
+ assert.equal(hard.fx.thenNow.wipes[0].real, false);
+ assert.equal(segmentJoins(hard), null);
+});
+
+test("thenNow: the divider's sweep is the crossfade's own span, to the frame", () => {
+ const s = sched(ALL);
+ const w = s.fx.thenNow.wipes[0];
+ const now = s.segments.find((x) => x.id === "c4");
+ near(w.at, now.start, FRAME, "the wipe starts where the NOW segment starts (the xfade's offset)");
+ near(w.seconds, 0.5, 0, "it lasts the transition");
+ assert.deepEqual([w.thenDate, w.nowDate], ["1 Jan 2021", "1 Jan 2026"]);
+ const hard = sched({ thenNow: { pairs: [{ then: "c3", now: "c4" }], seconds: 0.8 } }, { D: 0 });
+ const h = hard.fx.thenNow.wipes[0];
+ const s4 = hard.segments.find((x) => x.id === "c4").start;
+ near(h.at + h.seconds / 2, s4, FRAME, "a hard cut's sweep is centred on the cut");
+});
+
+test("kinetic and redacted lines: each word lands on its own time, to the frame; the punch is the phrase", () => {
+ // Timed words in each clip's SEGMENT seconds, as the build reads them.
+ const words = new Map(["c1", "c2", "c3", "c4"].map((id) => [id, [
+ { text: "it", start: 1.0, end: 1.2 }, { text: "was", start: 1.2, end: 1.5 }, { text: "a", start: 1.5, end: 1.6 },
+ { text: "slow", start: 1.7, end: 2.0 }, { text: "news", start: 2.0, end: 2.3 }, { text: "week.", start: 2.3, end: 2.7 },
+ { text: "really", start: 3.1, end: 3.6 },
+ ]]));
+ const s = sched(ALL, { words });
+ assert.deepEqual(s.fx.quotes.map((q) => [q.segment, q.style]), [["c1", "kinetic"], ["c2", "redact"], ["c3", "kinetic"], ["c4", "kinetic"]]);
+ for (const q of s.fx.quotes) {
+ const seg = s.segments.find((x) => x.id === q.segment);
+ const flat = q.pages.flatMap((p) => p.words);
+ assert.deepEqual(flat.map((w) => w.text), ["it", "was", "a", "slow", "news", "week.", "really"]);
+ flat.forEach((w, j) => near(w.at, seg.start + words.get(q.segment)[j].start, FRAME, `${q.segment} word ${j}`));
+ assert.deepEqual(flat.map((w) => w.punch), [false, false, false, true, true, true, false]);
+ }
+ // An entry's own punch wins over the montage's match.
+ const t2 = TIMELINE.map((e) => (e.id === "c1" ? { ...e, fx: { punch: "it was" } } : e));
+ const s2 = sched(ALL, { words, timeline: t2 });
+ assert.deepEqual(s2.fx.quotes[0].pages.flatMap((p) => p.words).map((w) => w.punch), [true, true, false, false, false, false, false]);
+ // A clip that opts out draws no line.
+ const t3 = TIMELINE.map((e) => (e.id === "c3" ? { ...e, fx: { quote: false } } : e));
+ assert.deepEqual(sched(ALL, { words, timeline: t3 }).fx.quotes.map((q) => q.segment), ["c1", "c2", "c4"]);
+});
+
+test("without timed words a clip's quote is spread over its cited span (the estimate, and a build's fallback)", () => {
+ const s = sched({ kineticQuote: {} });
+ const q = s.fx.quotes[0];
+ const flat = q.pages.flatMap((p) => p.words);
+ assert.equal(flat.length, 16);
+ const pw = playWindow(TIMELINE[0], render({}));
+ // The first word starts at cutStart, in the cut's clock.
+ near(flat[0].at, s.segments[0].start + (TIMELINE[0].cutStart - pw.from), FRAME, "first word");
+ assert.ok(flat.every((w, j) => j === 0 || w.at >= flat[j - 1].at), "in order");
+ assert.deepEqual(fxQuoteFallback({ quote: " ", start: 1, end: 2 }), []);
+});
+
+test("quotePages: at most maxWords, a break after a clause once half full, no orphan", () => {
+ const w = (t) => ({ text: t });
+ const pages = quotePages("one two three, four five six seven eight nine ten eleven twelve thirteen".split(" ").map(w), 6);
+ assert.deepEqual(pages.map((p) => p.map((x) => x.text).join(" ")), ["one two three,", "four five six seven eight nine", "ten eleven twelve thirteen"]);
+ assert.deepEqual(quotePages(["a", "b", "c", "d", "e", "f", "g"].map(w), 6).map((p) => p.length), [7]);
+});
+
+test("punchMask: every time the phrase is said; the last word may run on", () => {
+ const ws = "slow news days and a slow news week".split(" ").map((text) => ({ text }));
+ assert.deepEqual(punchMask(ws, "slow news day"), [true, true, true, false, false, false, false, false]);
+ assert.deepEqual(punchMask(ws, "slow news"), [true, true, false, false, false, true, true, false]);
+ assert.deepEqual(punchMask(ws, ""), ws.map(() => false));
+});
+
+test("fxWordsOf: a span's words share it by their characters; furniture goes", () => {
+ const ws = fxWordsOf([{ start: 0, end: 2, text: ">> ab [Music] abcd" }]);
+ assert.deepEqual(ws.map((w) => w.text), ["ab", "abcd"]);
+ near(ws[0].start, 0, 1e-9, "first");
+ near(ws[1].start, (2 * 3) / 8, 1e-9, "second starts after ab and a space");
+ assert.deepEqual(fxWordsOf([{ start: 0, end: 2, text: "a b" }], 1, 2).map((w) => w.text), ["b"]);
+});
+
+test("the odometer rolls on each clip's punch, to the frame, from the count before", () => {
+ const words = new Map([["c1", [{ text: "slow", start: 1.7, end: 2 }, { text: "news", start: 2, end: 2.3 }, { text: "week", start: 2.3, end: 2.6 }]]]);
+ const s = sched({ odometer: {} }, { words });
+ const o = s.fx.odometer;
+ assert.deepEqual(o.counts.map((c) => [c.segment, c.prev, c.value]), [["c1", 0, 9], ["c2", 9, 18], ["c3", 18, 27], ["c4", 27, 36]]);
+ near(o.counts[0].at, s.segments[0].start + 1.7, FRAME, "c1 rolls on 'slow'");
+ assert.equal(o.digits, 2);
+ // `at: "start"`: a quarter second after the clip is clean on screen.
+ const st = sched({ odometer: { at: "start" } }, { words });
+ near(st.fx.odometer.counts[1].at, s.segments[1].start + 0.25 + 0.25, FRAME, "c2 at its in + 0.25");
+ // No montage numbers: places.
+ const bare = TIMELINE.map(({ montage: _m, ...e }) => e);
+ assert.deepEqual(sched({ odometer: {} }, { timeline: bare }).fx.odometer.counts.map((c) => c.value), [1, 2, 3, 4]);
+ // The panel's span runs across consecutive clips.
+ assert.deepEqual(o.spans, [{ in: 0, out: s.total }]);
+});
+
+test("the glitch tears at each cut between years, centred on the mid-dissolve", () => {
+ const timeline = [clip("c1", "2019-05-02"), clip("c2", "2019-08-02"), clip("c3", "2021-01-01"), clip("c4", "2026-01-01")];
+ const s = sched({ glitch: {} }, { timeline });
+ assert.deepEqual(s.fx.glitch.bursts.map((b) => [b.segment, b.year]), [["c3", 2021], ["c4", 2026]]);
+ for (const b of s.fx.glitch.bursts) {
+ const seg = s.segments.find((x) => x.id === b.segment);
+ near(b.at, seg.start + 0.25, FRAME, `${b.segment} burst at the mid-dissolve`);
+ }
+ assert.equal(sched({ glitch: { on: "every" } }, { timeline }).fx.glitch.bursts.length, 3);
+});
+
+test("the scrubber: a tick per dated clip, the rail padded, a year mark per new year", () => {
+ const s = sched({ scrubber: {} });
+ const sc = s.fx.scrubber;
+ assert.deepEqual(sc.ticks.map((t) => t.label), ["2 May 2019", "11 Jun 2020", "1 Jan 2021", "1 Jan 2026"]);
+ assert.ok(sc.from < sc.ticks[0].day && sc.to > sc.ticks[3].day);
+ assert.deepEqual(sc.years.map((y) => y.year), [2020, 2021, 2022, 2023, 2024, 2025, 2026]);
+ // A clip's date: montage.date first, then its date, then the record's.
+ assert.deepEqual(fxClipDate({ montage: { date: "20190502" }, date: "2020-01-01" }, { uploadDate: "20210101" }), { y: 2019, m: 5, d: 2 });
+ assert.deepEqual(fxClipDate({}, { uploadDate: "20210101" }), { y: 2021, m: 1, d: 1 });
+});
+
+test("receipts and the zoom: placed inside the clip, the marker after the cards land", () => {
+ const s = sched(ALL);
+ const r = s.fx.receipts.clips[0];
+ const seg = s.segments.find((x) => x.id === "c2");
+ assert.equal(r.segment, "c2");
+ near(r.in, seg.start + 0.25 + 0.3, 1e-9, "after the clip is clean on screen");
+ assert.deepEqual(r.cards.map((c) => c.shot), ["shots/b.png", "shots/a.png"]);
+ assert.ok(r.markAt >= r.cards[1].at + 0.4, "the marker waits for the last card");
+ const z = s.fx.zoom.clips[0];
+ assert.equal(z.segment, "c4");
+ assert.ok(z.in < z.outline && z.outline < z.push && z.push + 1 < z.out);
+});
+
+test("no effect is drawn over a segment the deck hides (a card)", () => {
+ const timeline = [clip("c1", "2019-05-02"), { type: "card", id: "k1", seconds: 4, heading: "x" }, clip("c2", "2021-01-01")];
+ const s = sched({ glitch: { on: "every" }, odometer: {}, kineticQuote: {} }, { timeline, durs: [6.4, 4, 6.4] });
+ assert.deepEqual(s.fx.quotes.map((q) => q.segment), ["c1", "c2"]);
+ assert.equal(s.fx.glitch.bursts.length, 0, "a card between two clips is its own break");
+ assert.equal(s.fx.odometer.spans.length, 2, "the counter steps aside over the card");
+ assert.ok(hidesDeck(timeline[1], resolveDeck(render({}))));
+});
+
+test("compileCues: ordered, clamped per element, every from stated", () => {
+ const cues = compileCues({ a: { x: 0, autoAlpha: 0 } }, [
+ { k: "a", at: 2, dur: 1, to: { x: 10 } },
+ { k: "a", at: 1, dur: 0.5, to: { autoAlpha: 1 } },
+ { k: "a", at: 2.5, dur: 1, to: { x: 20 } },
+ ]);
+ assert.deepEqual(cues.map((c) => [c.at, c.dur, c.from, c.to]), [
+ [1, 0.5, { autoAlpha: 0 }, { autoAlpha: 1 }],
+ [2, 1, { x: 0 }, { x: 10 }],
+ [3, 0.5, { x: 10 }, { x: 20 }],
+ ]);
+});
+
+test("fxRandom: the same seed, the same numbers", () => {
+ const a = fxRandom(7), b = fxRandom(7), c = fxRandom(8);
+ const xs = [a(), a(), a()];
+ assert.deepEqual(xs, [b(), b(), b()]);
+ assert.notDeepEqual(xs, [c(), c(), c()]);
+ assert.ok(xs.every((x) => x >= 0 && x < 1));
+});
+
+test("fxGeometry is the footage box: the deck's, the feed's, beside the rail", () => {
+ assert.deepEqual(fxGeometry(render({})), deckGeometry(render({})).footage);
+ assert.deepEqual(fxGeometry(render({}), { feed: true }), feedGeometry(render({})).footage);
+ assert.deepEqual(fxRegion(render({}), "/o/chrome/fx-frames", { layout: undefined }),
+ { name: "fx", frames: "/o/chrome/fx-frames", x: 173, y: 2, width: 1574, height: 886 });
+});
+
+test("the overlay lays the effects like the deck: whole cut, reinit off, rgba, shortest", () => {
+ const r = render(ALL);
+ const regions = [
+ { name: "deck", frames: "/o/chrome/deck-frames", x: 0, y: 890, width: 1920, height: 190 },
+ fxRegion(r, "/o/chrome/fx-frames", {}),
+ ];
+ const c = chromeOverlayChain(r, regions, "[v3]", 4);
+ assert.ok(c.inputs.join(" ").includes("-reinit_filter 0 -framerate 30 -start_number 1 -i /o/chrome/fx-frames/frame_%06d.png"));
+ assert.match(c.chain, /\[5:v\]format=rgba\[hfa1\];\[hf0\]\[hfa1\]overlay=x=173:y=2:format=yuv444:shortest=1/);
+});
+
+test("fxSuggestPairs: neighbouring clips years apart, widest gaps first, none twice, in cut order", async () => {
+ const { fxSuggestPairs } = await import("./fx.mjs");
+ const tl = [clip("a", "2019-01-01"), clip("b", "2019-06-01"), clip("c", "2024-01-01"), clip("d", "2025-01-01"),
+ { type: "card", id: "k", seconds: 3 }, clip("e", "2010-01-01")];
+ // b→c (4.6 years) is the widest; c→d (1 year) would reuse c; a→b is the same year; the card breaks d→e.
+ assert.deepEqual(fxSuggestPairs({ timeline: tl }), [{ then: "b", now: "c" }]);
+ assert.deepEqual(fxSuggestPairs({ timeline: tl }, 1), [{ then: "b", now: "c" }]);
+ assert.deepEqual(fxSuggestPairs({ timeline: [clip("a", "2019-01-01"), clip("b", "2019-02-01")] }), []);
+});
+
+test("fxPresetsFor: one preset per effect the cut can show, each a patch the validators accept", async () => {
+ const { fxPresetsFor } = await import("./fx.mjs");
+ const m = { render: render(undefined, { transition: 0 }), timeline: TIMELINE };
+ const presets = fxPresetsFor(m);
+ assert.deepEqual(presets.map((p) => p.name), ["kinetic-quote", "redaction", "odometer", "scrubber", "glitch", "punch-in", "whip", "reaction", "then-now", "receipts", "zoom", "everything"]);
+ for (const p of presets) {
+ assert.equal(p.patch.render.transition, 0.4, `${p.name}: a hard-cut project gets a crossfade to wipe on`);
+ const chrome = { ...m.render.chrome, ...p.patch.render.chrome };
+ assert.deepEqual(validateChrome(chrome, { ...m.render, transition: 0.4 }), [], p.name);
+ assert.deepEqual(validateFxEntries({ render: { ...m.render, chrome }, timeline: TIMELINE }), [], p.name);
+ }
+ // Without screenshots on any clip there is no receipts or zoom preset.
+ const bare = TIMELINE.map(({ fx: _f, ...e }) => e);
+ assert.deepEqual(fxPresetsFor({ render: render(undefined), timeline: bare }).map((p) => p.name).filter((n) => n === "receipts" || n === "zoom"), []);
+ // The cut's own transition is kept.
+ assert.equal(fxPresetsFor({ render: render(undefined, { transition: 0.25 }), timeline: TIMELINE })[0].patch.render.transition, 0.25);
+});
+
+// ---- reaction highlights: two voices, the punch-in, the whip ----------------------
+
+test("fxWordsOf marks a speaker's turn at '>>' and a dash; the kinetic line gives each voice its own pages", () => {
+ const ws = fxWordsOf([{ start: 0, end: 4, text: "- Oh god, it is. - Sometimes it's a slow news day. >> Yeah" }]);
+ assert.deepEqual(ws.filter((w) => w.turn).map((w) => w.text), ["Oh", "Sometimes", "Yeah"]);
+ const words = new Map([["c1", ws.map((w) => ({ ...w, start: w.start + 1, end: w.end + 1 }))]]);
+ const s = sched({ kineticQuote: {} }, { words, timeline: [clip("c1", "2024-05-22")], durs: [6.4] });
+ const q = s.fx.quotes[0];
+ assert.deepEqual(q.pages.map((p) => [p.speaker, p.words.map((w) => w.text).join(" ")]), [
+ [0, "Oh god, it is."], [1, "Sometimes it's a slow news day."], [0, "Yeah"],
+ ]);
+ assert.deepEqual(s.fx.quoteStyle.voices, [{ label: "", color: null }, { label: "", color: "#6fa8dc" }]);
+ // speakers: false keeps one voice and no voices block.
+ const off = sched({ kineticQuote: { speakers: false } }, { words, timeline: [clip("c1", "2024-05-22")], durs: [6.4] });
+ assert.ok(off.fx.quotes[0].pages.every((p) => !("speaker" in p)));
+ assert.equal(off.fx.quoteStyle.voices, undefined);
+ // A line with one voice has no speaker marks at all (the schedule it was).
+ const one = sched({ kineticQuote: {} }, { words: new Map([["c1", [{ text: "solo", start: 1, end: 1.4 }]]]), timeline: [clip("c1", "2024-05-22")], durs: [6.4] });
+ assert.ok(one.fx.quotes[0].pages.every((p) => !("speaker" in p)));
+});
+
+test("a clip's fx.speakers (source seconds) name the voices over the captions' turns; labels are the manifest's", () => {
+ const words = new Map([["c1", [{ text: "a", start: 1, end: 1.2 }, { text: "b", start: 2, end: 2.2 }, { text: "c", start: 3, end: 3.2 }]]]);
+ const c1 = clip("c1", "2024-05-22", { fx: { speakers: [{ at: 11.5, who: 1 }, { at: 12.5, who: 0 }] } });
+ const r = { kineticQuote: { voices: [{ label: "Host" }, { label: "Video", color: "#22ab83" }] } };
+ // The clip's segment starts at its play window's from (cutStart − lead-in = 10.6).
+ const s = sched(r, { words, timeline: [c1], durs: [6.4] });
+ assert.deepEqual(s.fx.quotes[0].pages.map((p) => [p.speaker, p.words.map((w) => w.text).join(" ")]), [[1, "a"], [0, "b c"]]);
+ const who = s.fx.quotes[0].pages.flatMap((p) => p.words.map(() => p.speaker));
+ // a at source 11.6 (≥ 11.5 → 1), b at 12.6 (≥ 12.5 → 0), c 13.6 → 0.
+ assert.deepEqual(who, [1, 0, 0]);
+ assert.deepEqual(s.fx.quoteStyle.voices, [{ label: "Host", color: null }, { label: "Video", color: "#22ab83" }]);
+ assert.match(validateFxEntries({ render: render({}), timeline: [clip("c1", "2024-05-22", { fx: { speakers: [{ at: 1, who: 2 }] } })] }).join(), /speakers must be a list/);
+ assert.match(validateFx({ kineticQuote: { voices: [{ color: "red" }] } }).join(), /#rrggbb/);
+});
+
+test("the punch-in: on a clip's marked seconds and its captions' laughs, inside the clip, in the segment's clock", async () => {
+ const words = new Map([["c1", [{ text: "that's", start: 1, end: 1.3 }, { text: "hahaha", start: 2.5, end: 3 }, { text: "lol", start: 2.9, end: 3.1 }]]]);
+ const c1 = clip("c1", "2024-05-22", { fx: { punchIn: [14.6] } });
+ const s = sched({ punchIn: {} }, { words, timeline: [c1, clip("c2", "2024-05-23")], durs: [6.4, 6.4] });
+ const p = s.fx.punchIn.punches;
+ // 2.5 (the laugh) and 14.6 − 10.6 = 4.0 (the mark); "lol" is inside the first's hold.
+ assert.deepEqual(p.map((x) => [x.segment, x.segmentAt, x.segmentUntil]), [["c1", 2.5, 3.9], ["c1", 4, 5.4]]);
+ near(p[0].at, s.segments[0].start + 2.5, FRAME, "cut time");
+ const { fxZoomJoins } = await import("./fx.mjs");
+ const zj = fxZoomJoins(s);
+ assert.deepEqual([...zj.keys()], [0]);
+ const joins = segmentJoins(s);
+ assert.equal(joins[0].zoom.length, 2);
+ assert.deepEqual(joins[0].zoom[0].box, { x: 173, y: 2, width: 1574, height: 886 });
+ assert.equal(joins[1], null);
+ // auto: false keeps only the marks.
+ assert.deepEqual(sched({ punchIn: { auto: false } }, { words, timeline: [c1], durs: [6.4] }).fx.punchIn.punches.map((x) => x.segmentAt), [4]);
+ assert.match(validateFxEntries({ render: render({}), timeline: [clip("c1", "2024-05-22", { fx: { punchIn: [99] } })] }).join(), /outside the clip/);
+});
+
+test("the punch-in's graph crops the box and lays it back over itself between its seconds; the record names it", async () => {
+ const { joinInputChain, concatRecordText, punchInParts } = await import("./build-video.mjs");
+ const r = render({});
+ const c = joinInputChain(0, { hold: 0, move: null, zoom: [{ at: 2.5, until: 3.9, scale: 1.2, anchor: "upper" }] }, r);
+ assert.deepEqual(c.parts, [
+ "[0:v]split=2[j0z0a][j0z0b]",
+ "[j0z0b]crop=1312:738:304:39,scale=1574:886:flags=lanczos,setsar=1[j0z0c]",
+ "[j0z0a][j0z0c]overlay=173:2:enable='between(t,2.5,3.9)'[j0z0]",
+ ]);
+ assert.equal(c.v, "[j0z0]");
+ // With a hold too, the hold clones the zoomed stream.
+ const h = joinInputChain(0, { hold: 1, move: null, zoom: [{ at: 1, until: 2, scale: 1.2, anchor: "center" }] }, r);
+ assert.match(h.parts.at(-2) ?? "", /^\[j0z0\]tpad=/);
+ assert.equal(punchInParts(3, [], r, "[3:v]").v, "[3:v]");
+ const rec = concatRecordText(["a.mp4"], [{ hold: 0, move: null, zoom: [{ at: 1, until: 2, scale: 1.2, anchor: "upper" }] }]);
+ assert.match(rec, /# join 0 \{"hold":0,"move":null,"zoom":\[/);
+ assert.equal(concatRecordText(["a.mp4"], [{ hold: 1, move: null }]).includes("zoom"), false);
+});
+
+test("the whip: every cut between clips slides (slideleft), but never one that wipes; a hard cut only streaks", () => {
+ const tn = { thenNow: { pairs: [{ then: "c3", now: "c4" }] }, whip: {} };
+ const s = sched(tn);
+ assert.deepEqual(s.fx.whip.cuts.map((c) => c.segment), ["c2", "c3"]);
+ const joins = segmentJoins(s);
+ assert.deepEqual(joins.map((j) => (j?.wipe ? "wipe" : j?.whip ? "whip" : null)), ["whip", "whip", "wipe", null]);
+ const xf = xfadeGraph([6.4, 6.4, 6.4, 6.4], 0.5, joins).parts.filter((p) => /xfade=/.test(p));
+ assert.deepEqual(xf.map((p) => /transition=(\w+)/.exec(p)[1]), ["slideleft", "slideleft", "wipeleft"]);
+ assert.deepEqual(xfadeBatchJoins(joins, [{ from: 0, to: 1 }, { from: 1, to: 4 }]), [{ whip: true }, null]);
+ const hard = sched({ whip: {} }, { D: 0 });
+ assert.ok(hard.fx.whip.cuts.every((c) => !c.real && c.seconds === 0.24));
+ assert.equal(segmentJoins(hard), null);
+ assert.deepEqual(sched({ whip: { on: "year" } }, { timeline: [clip("c1", "2019-01-01"), clip("c2", "2019-02-01"), clip("c3", "2020-01-01")], durs: [6.4, 6.4, 6.4] }).fx.whip.cuts.map((c) => c.segment), ["c3"]);
+});
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -86,6 +86,7 @@ import { validateFlipEntries } from "./flips.mjs";
import { validateStatsEntries } from "./stats.mjs";
import { validateMontage } from "./montage.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { validateFxEntries } from "./fx.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
@@ -234,6 +235,8 @@ export function validatorErrors(whole) {
...validateMontage(whole),
// Release 35: a clip's `assist` (the clip finder's provenance; the render ignores it).
...validateAssist(whole),
+ // Release 35: the effects' entry fields, clip lists and THEN/NOW pairs.
+ ...validateFxEntries(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/package.json b/umtool/report-to-video/package.json
@@ -27,6 +27,7 @@
"./drafts-review": "./drafts-review.mjs",
"./factcheck": "./factcheck.mjs",
"./frames-cut": "./frames-cut.mjs",
+ "./fx": "./fx.mjs",
"./ledger-totals": "./ledger-totals.mjs",
"./montage": "./montage.mjs",
"./montage-styles": "./montage-styles.mjs",
diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs
@@ -195,6 +195,16 @@ export async function verifyDeck(variantDir, render, file, problems, manifest =
if (got === 0) problems.push(`the stats region is declared but ${dir} has no frames — built with --no-chrome, or the region never rendered`);
else if (got !== want) problems.push(`${dir} holds ${got} frames; the stats region runs the whole cut, ${want}`);
}
+ // The effects region (fx.mjs): one sequence for the whole cut, as long as
+ // the deck's, whenever the schedule says an effect is on.
+ let fx = null;
+ if (schedule.fx) {
+ const dir = path.join(variantDir, "chrome", "fx-frames");
+ const got = await countFrames(dir);
+ fx = { frames: got, expectedFrames: want, keys: schedule.fx.keys ?? [] };
+ if (got === 0) problems.push(`the effects are on but ${dir} has no frames — built with --no-chrome, or the region never rendered`);
+ else if (got !== want) problems.push(`${dir} holds ${got} frames; the effects run the whole cut, ${want}`);
+ }
// The posts windows: each laid at its own second, each as long as snapWindow says.
const posts = [];
for (const r of postsRegions(render, variantDir, schedule)) {
@@ -210,6 +220,7 @@ export async function verifyDeck(variantDir, render, file, problems, manifest =
...(feed ? { feed } : {}),
...(stamp ? { stamp } : {}),
...(stats ? { stats } : {}),
+ ...(fx ? { fx } : {}),
...(posts.length ? { posts } : {}),
...(holds.length ? { holds } : {}),
};