Archilyzer · Source

archilyzer

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

commit 4cc0e748e8bab5067644b713b7e420305577fb25
parent 08579f87c51342e188f8fa4eef5c35ada8f2a98f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 11:05:53 -0400

Merge lane/knobs-core: every clip's sound on its own clock (the Huck desync), sync.json, claim at/hold/stamp/count/label, stamp look, clip audio, marker stagger, quality variants

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Aplans/video-knobs-core.md | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 37+++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/onscreen.mjs | 10+++++++++-
Mumtool/report-to-video/README.md | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/report-to-video/av-clock.test.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 121++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/chrome-deck.mjs | 27+++++++++++++++++----------
Mumtool/report-to-video/chrome-stamp.mjs | 52++++++++++++++++++++++++++++++++++++++--------------
Aumtool/report-to-video/claim-knobs.test.mjs | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/clip-audio.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/clip-audio.test.mjs | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/compose-chrome.mjs | 3++-
Mumtool/report-to-video/cut-edits.test.mjs | 8+++++---
Aumtool/report-to-video/deck-markers-layout.test.mjs | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck-overlay.test.mjs | 8++++----
Mumtool/report-to-video/deck-room.test.mjs | 22++++++++++++----------
Mumtool/report-to-video/deck.mjs | 219++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/report-to-video/factcheck.mjs | 179++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/report-to-video/factcheck.test.mjs | 4++--
Mumtool/report-to-video/lint.mjs | 3++-
Mumtool/report-to-video/package.json | 6+++++-
Aumtool/report-to-video/sync-report.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/sync-report.test.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/variants.mjs | 301+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/variants.test.mjs | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
26 files changed, 2302 insertions(+), 121 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A report video's sound stays with its picture from the first clip to the last.** A clip whose sound started late (its cut reached back before the fetched window's media) or had a gap in it (a seam in the source's stream) used to pull that clip's sound, and every later clip's, early — on a 20-minute cut by half a second from the 13th minute on. Each clip's sound is now laid on its own clock before the clips are joined, and every build writes `sync.json` beside its schedule saying where each clip's sound landed against its picture; the build log names any clip more than a frame off. A video's manifest can now also set when a fact-check stamp lands and the count steps (`claim.at`, a second of the source), how long it stays, a count of more than one, a stamp that counts without showing, the stamp's words, size, entrance and opacity; nudge a clip's sound against its picture, its volume and fades (`audio`); align a timeline flag's label and lay crowded labels in two rows; and `node umtool/report-to-video/variants.mjs <take out dir>` makes smaller copies of a finished cut — 1080p, 720p and one under 24 MiB by default (`render.variants`). Needs a rebuild of the video. - **A fact-check video can count without the stamp, colour its timeline by verdict, flag the moments time passes, and leave the QR off posts.** In umtool's fact-check form, **stamp effect** off draws no verdict stamp over the footage, while the tally in the panel still counts each claim at the second its stamp would have landed. The On-screen settings have **colour** under timeline: **verdict** lights each clip that carries a claim in its verdict's colour — the tally's colour — with a shape per verdict (circle, diamond, square, triangle, ring), and the tally's cells carry the same shapes. **qr codes** under posts off leaves the QR off every post card, popup or feed, and the words take its width; each clip's own QR stays. A video's manifest can flag moments on the timeline (`render.chrome.deck.markers`: "3 to 5 weeks pass" after a clip), each popping in as the timeline reaches it and staying lit. Needs a restart of umtool. - **The dashboard says when a service's cookies have gone stale, and what to do.** When Rumble refuses its embeds with a 403 on two different videos in a row (one is not enough — a removed video answers 403 too), when YouTube asks to confirm you're not a bot, when Odysee answers with Cloudflare's check, when a forum's browser check or login wall stops a thread, or when archive.today answers with its check page, a banner at the top of the dashboard says so — "Rumble needs fresh cookies: open rumble.com in firefox" — with the jobs it happened in. **Recheck** asks the service once, through the same path and cookies the jobs use, and clears the banner when it answers; the next clean request clears it by itself too, and **Dismiss** clears it by hand. Once it is clear the banner says "OK again" and offers **Re-run stopped jobs**, which retries the jobs it stopped. The stopped job's log ends with the cause and the fix, `archilyzer doctor` lists it under "service cookies", and a Connect forum session or Connect archive session that ends on a cleared page clears the matching banner. From a terminal: `pnpm ops get services`, `recheck-service`, `rerun-service-jobs` and `dismiss-service`. Odysee's check is recognised by Cloudflare's own words beside a 403; no real Odysee sample has been seen yet. Needs a restart of the editor. - **archive.today copies are page records too, like Wayback captures.** The channel kind is now **Archived pages** on the New channel form (paste an archive.today copy's URL, `archive.ph/newest/<page>`, and the channel's target is that page on archive.today), and each target says where its copies are looked for: the Wayback Machine, archive.today, or both. The channel page's **Import a capture** takes an archive.today copy's URL (`archive.ph/<id>`, or any of its other names), or the page's own URL, a date and **on archive.today** for the copy nearest that date; the copy is kept as archive.today served it and read without its header bar, links back to the pages they pointed at, so a tweet, a Tumblr post or an article gives the same records it would from the Wayback Machine — each saying it came from archive.today and linking that copy, its images archive.today's own copies. archive.today is asked one request at a time, eight seconds apart; when it says "too many requests" the import stops with a sentence and nothing more is asked of it for half an hour. When it answers with a CAPTCHA instead of the copy, the import is refused and never reads the CAPTCHA as a page: **Connect archive session** (on the channel page, and in Settings → Archive sources) opens a window on the editor's machine to pass the check once, and the next import reads through it; nothing is ever solved for you. **Look up a page** lists every copy each archive holds of a page, with an Import button on each. From a terminal: `pnpm ops import-page` takes `"source": "archive.today"`, `pnpm ops archive-lookup` lists the copies, and `pnpm archilyzer archive lookup <url>` runs without the editor. Needs a restart of the editor. diff --git a/plans/video-knobs-core.md b/plans/video-knobs-core.md @@ -0,0 +1,121 @@ +# Video knobs — the core (lane `lane/knobs-core`, K1) + +Asked by the operator on 2026-10-22 on the Huck seizure video: count seizures, bring the stamps back for the +clip that steps a count and set where it lands per clip, fix the sound drifting toward 16 minutes, make +quality variants to share elsewhere, and "add any knobs you can think of … deep human involvement as well as +AI control". The plan is `video-knobs-plan.md` (the orchestrator's); this lane is its "desync", "Shared +shapes" and "K1 core". K2 (`lane/knobs-ui`) builds the writers, routes, UI and CLI against the same shapes. + +## The desync + +Measured on `polemic-huck` (26 clips, xfade 0.5 s, two crossfade batches): `first … ten-k` sound 68 ms early, +`rescue … blend` 469 ms early. + +Causes: + +- **rescue (469 ms).** The cut starts at source 2567.04; the editor's window file + (`2563.74-2594.40.mp4`) has no media before 3.79 s of its own clock (audio 3.7905, video 3.8333), so + `fetchStart` moves to 2567.53 and the segment's cut starts 0.49 s before the media. The segment encode + keeps timestamps: its picture holds the first frame from 0, its sound starts at 0.4687 s. In sync by + timestamps — but `xfadeGraph`'s pin (`apad`, `atrim`, `asetpts=PTS-STARTPTS`) and `acrossfade` count + samples, so the sound moved 469 ms early, and every later clip in the batch with it. +- **first … ten-k (68 ms).** `fed`'s source window (`6112.50-6159.50.mp4`) has two holes in its audio + timestamps at 42.69 s (51 ms + 17 ms, an HLS seam), carried into `fed.mp4` at 38.21 s. Decoded, fed's + sound is 67.7 ms short of its timeline; the pinned graph pads that at fed's END, so everything after the + hole — the rest of fed, then every later clip in batch 1 — plays 68 ms early. Batch 1's sound is 67.7 ms + shorter than its picture (612.366 vs 612.433), batch 2's 469 ms; the join pass re-pins per batch, which + is why each batch reset it. + +Fix: `AUDIO_ON_CLOCK` (`clip-audio.mjs`) = `aresample=async=1:min_hard_comp=0.01:first_pts=0` — silence +where a sound starts late or a hole opens, samples dropped where two overlap, anything over 10 ms; a +sound with neither passes sample for sample (checked: identical PCM). Applied: + +- at the segment encode (every non-montage clip's sound), so new segments are continuous from 0; the + build notes a cut that starts before its source's media; +- in `xfadeGraph`'s pin (one pass, each batch, the join pass); +- in `hardCutFilterArgs` (the concat filter) and `previewFromSegmentsArgs`' concat. + +Proof: the Huck cut's SOUND re-assembled from its real segments with the fixed graph, batched as the build +batches it (audio only, no render), measured with `lag.py` — every clip 0 ms: + +| clips | before | after | +|---|---|---| +| arrive, fed | 0 | 0 | +| first … ten-k (11) | −68 / −67 ms | 0 | +| gold, post-results, offset | 0 | 0 | +| rescue … blend (10) | −469 / −468 ms | 0 | + +`sync-report.mjs` reads the current final exactly as `lag.py` did (0, −68, −469). +`av-clock.test.mjs`: a segment whose audio starts 0.5 s late and one with a 60 ms hole, through one +crossfade pass, a batched pass and the hard cut: every burst within a frame; with the align swapped for +`anull` it fails (the late one 400+ ms early). + +## The sync report + +After every build and `--chrome-only`: `<out>/<variant>/sync.json` `{ at, fps, items: [{ id, start, lagMs, +peak }] }`, clips only; the build log names each clip more than a frame off. lag.py's method in node: +mono 4 kHz, the segment's sound over a window past its joins (≤ 6 s from 3 s in) found in the final within +±2.5 s, coarse at 1 kHz then fine (~6 s for the 26-clip cut). `REPORT_VIDEO_SYNC=0` skips it; it never +fails a build. + +## The knobs + +All optional; absent, the schedule, the pages and the segments are the bytes they were (the existing +byte-identity tests pass unchanged). + +| Key | Range · default | What | +|---|---|---| +| `claim.at` | a source second inside the clip's `start`–`end` · the usual timing | the stamp lands and the tally steps there, mapped through the segment's real source start (its cut record: snapped, room included; estimate/preview: the play window's start). The schedule's stamped segment carries `sourceFrom`. Read from the entry that stamps (the last carrying the id). | +| `claim.hold` | 0.5–10 s · `stamp.seconds` | how long the stamp stays from its start (without `at`: comes in `hold` before the segment's out) | +| `claim.stamp` | bool · true | false: counted, not drawn (`drawnStamps`; `stampsDrawn` false when none is drawn) | +| `claim.count` | whole 1–99 · 1 | the tally steps by n (`tallySteps` `step`, `tallyFinals`; each count still its own number element) | +| `claim.label` | ≤ 20 chars · verdict's `stampLabel`, else `label` | the stamp's words | +| `factcheck.stamp.scale` | 0.5–2 · 1 | the stamp region's size (`stampGeometry`), inside the footage box | +| `factcheck.stamp.motion` | slam/pop/fade/none · slam | the entrance, ending at `landed`; slam and pop flash; none leaves at once | +| `factcheck.stamp.opacity` | 0.3–1 · 1 | the whole stamp region's (written only when not 1) | +| `factcheck.verdicts.<V>.stampLabel` | ≤ 24 chars · `label` | validated in factcheck.mjs (common's override rule checks the rest) | +| clip `audio.offset` | −2000–2000 ms · 0 | + = sound later; read from the source again at the shifted window (a last input; `-itsoffset` past the head) | +| clip `audio.gain` | −20–20 dB · 0 | after levelling and room | +| clip `audio.fadeIn`, `fadeOut` | 0–5 s · 0 | at the segment's edges | +| `deck.markers[].align` | auto/left/right/center · auto | the label against its flag; a neighbour reading away lets a label reach up to it | +| `deck.markerLayout` | stagger/truncate · stagger | crowded labels in two rows (every split tried; most labels fitting wins); band +22 px (`MARKER_ROW`); row 1's sticks reach up, row 0 keeps 8 px clear of them; a still-long label ellipsized | +| `render.variants` | ≤ 12 · master, 1080p crf 22, 720p crf 23, fit24 ≤ 24 MiB | `variants.mjs`: crf variants at their height (sound and chapters copied); maxMiB two-pass at the largest of 1080/720/480 keeping 100 kb/s per 480p of pixels, AAC 48 mono under 300 kb/s total (else 96 stereo), retried 6 % lower while over (four tries) | + +The crowded-marker case (9 grey chapter flags + 2 red, the last three within 200 px of the track's end): +one row fits 7 of 11, two rows 9 of 11. Three ~200 px labels on 140 px of track cannot all fit two rows; the +rest are ellipsized. The Huck timeline take's two markers fit one row and lay as before. + +## Exports for K2 + +- `validateClipAudio(audio, where?) → string[]` — `umtool-report-to-video/clip-audio` + (also `validateClipAudioEntries`, `CLIP_AUDIO_LIMITS`, `clipAudioOf`). +- `encodeVariants(outDir, { slug, variants, only, source, onLog })`, `validateVariants`, `variantsOf`, + `DEFAULT_VARIANTS`, `VARIANTS_FILE` — `umtool-report-to-video/variants`. +- `SYNC_FILE`, `writeSyncReport`, `SYNC_WEAK_PEAK` — `umtool-report-to-video/sync-report`. +- `normalizeClaim` accepts and returns the knobs; `CLAIM_KEYS`, `CLAIM_LIMITS`, `STAMP_MOTIONS`, + `FACTCHECK_LIMITS.scale/opacity` — factcheck. +- `MARKER_ALIGNS`, `MARKER_LAYOUTS`, `MARKER_ROW`, `markerLabelWidth`, `markerRowsOf`, + `deckLayout(render, { tally, schedule })` — deck. + +## Left to K2 / open + +- `app/api/report/chrome/preview/route.ts` returns `deckLayout(render, { tally })`: pass `schedule` too, or + a staggered band's geometry differs from the page's. +- `lib/report/manifest.mjs`' claim types (`{ id, verdict }`) and `normalizeClaimsDraft` carry the knobs + only as far as `normalizeClaim` does; the writers are K2's. +- `lib/report/onscreen.mjs` `previewSchedule` places `claim.at` from the built segment's `sourceFrom`, else + the play window's start (a claim given `at` after the build previews up to a snap's distance off until + the next build). +- A montage clip's `audio` is not applied (its graph cuts its own sound); the build says so. +- The real Huck cut has not been re-rendered here (the orchestrator's rollout); the proof above is the + sound re-assembled from its real segments. + +## Files + +`umtool/report-to-video/`: `clip-audio.mjs` (new), `sync-report.mjs` (new), `variants.mjs` (new), +`build-video.mjs`, `factcheck.mjs`, `chrome-stamp.mjs`, `chrome-deck.mjs`, `deck.mjs`, `compose-chrome.mjs`, +`lint.mjs`, `package.json` (exports `./clip-audio`, `./sync-report`, `./variants`; bin `report-variants`); +tests `av-clock`, `sync-report`, `claim-knobs`, `clip-audio`, `deck-markers-layout`, `variants` (new) and +the graph strings in `cut-edits`, `deck-overlay`, `deck-room`, `factcheck`. `umtool/lib/report/onscreen.mjs` +(the preview's source clock for `claim.at`). Docs: `umtool/report-to-video/README.md`, +`umtool/docs/report-video.md`, `editor/CHANGELOG.md`. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -371,6 +371,43 @@ through, with the fact-check block and the other regions (threads, flips, stats, fx), as saved. With the stamps off the preview composes no stamp region (`stampsDrawn`). +### The video's knobs (the pipeline's side) + +Every knob below is a manifest key the build reads; absent, the render is +the one it always was. The pipeline's README has each in full, with its range +and default. + +| where | key | range · default | what | +|---|---|---|---| +| a claimed entry's `claim` | `at` | a source second in the clip's window · the stamp's usual timing | when the stamp lands and the tally steps | +| | `hold` | 0.5–10 s · `factcheck.stamp.seconds` | how long the stamp stays | +| | `stamp` | true/false · true | false: counted, not drawn | +| | `count` | 1–99 · 1 | the tally's step | +| | `label` | ≤ 20 chars · the verdict's stamp label | the stamp's words | +| `render.chrome.factcheck.stamp` | `scale` | 0.5–2 · 1 | the stamp's size | +| | `motion` | slam/pop/fade/none · slam | its entrance | +| | `opacity` | 0.3–1 · 1 | | +| `render.chrome.factcheck.verdicts.<V>` | `stampLabel` | ≤ 24 chars · its `label` | the stamp's word beside the tally's | +| a clip's `audio` | `offset` | −2000–2000 ms · 0 | + = sound later | +| | `gain` | −20–20 dB · 0 | | +| | `fadeIn`, `fadeOut` | 0–5 s · 0 | | +| `render.chrome.deck.markers[]` | `align` | auto/left/right/center · auto | the label against its flag | +| `render.chrome.deck` | `markerLayout` | stagger/truncate · stagger | crowded labels in two rows | +| `render` | `variants` | a ladder · master, 1080p crf 22, 720p crf 23, fit24 ≤ 24 MiB | Make variants | + +Sections: [claim knobs](../report-to-video/README.md#a-claims-own-knobs), +[the stamp's look](../report-to-video/README.md#the-stamps-look), +[clip audio](../report-to-video/README.md#a-clips-audio--sync-nudge-gain-fades), +[markers](../report-to-video/README.md#deckmarkers--flags-on-the-pip-track), +[variants](../report-to-video/README.md#quality-variants-rendervariants-variantsmjs), +[sync](../report-to-video/README.md#every-clips-sound-on-its-own-clock-and-syncjson). + +After every build the take's `out/<variant>/sync.json` says where each clip's +sound landed against its picture (`lagMs`, + = late; `peak`, how well it +matched); the build log names any clip more than a frame off. +`node umtool/report-to-video/variants.mjs <take out dir> [--only …]` makes the +ladder beside the cut (`<slug>.<name>.mp4`, `variants.json`). + ### Preview, before and without a build `POST /api/report/chrome/preview` composes `out/<variant>/chrome/deck-preview/` diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -27,6 +27,7 @@ import { deckText, estimateSchedule, footageMoves, + playWindow, postHolds, postSchedule, postWindows, @@ -239,7 +240,14 @@ export function previewSchedule({ variantManifest, built, draft, metas, postsDra const c = claimOf(patchedEntries[i]); return c ? { ...bare, claim: c } : bare; }); - const stamps = stampSchedule({ segments: claimed, D: built.transition, total, render }); + // A claim stamped at a source second (`claim.at`): the play window's start + // stands in for the cut record's (the build's is exact; snapping moves it). + const stamps = stampSchedule({ + segments: claimed.map((s, i) => (s.claim?.at !== undefined + ? { ...s, sourceFrom: s.sourceFrom ?? playWindow(patchedEntries[i], render).from } + : s)), + D: built.transition, total, render, + }); return { ...rest, ...(feed ? { layout: "feed" } : {}), diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -380,6 +380,31 @@ on the last frame. It is for a cut that ends on a clip; once a finale entry follows the last clip, the ordinary crossfade into it does the job and `endFade` fades the finale instead. +### A clip's `audio` — sync nudge, gain, fades + +```jsonc +{ "type": "clip", "id": "c07", …, + "audio": { "offset": 120, "gain": -3, "fadeIn": 0.5, "fadeOut": 1 } } +``` + +| key | range | default | what | +|---|---|---|---| +| `offset` | −2000…2000 ms | 0 | the sound against the picture; **+ is later** | +| `gain` | −20…20 dB | 0 | after any levelling (`render.loudness`) and room | +| `fadeIn` | 0…5 s | 0 | from the segment's first sample | +| `fadeOut` | 0…5 s | 0 | to its last | + +Applied at the segment encode (`clip-audio.mjs`), so a change rebuilds that +clip's segment. The offset reads the sound from the source again over the +shifted window — one more input, the last — so nothing is cut off the far +end; past the file's head the gap is silence. Every key is optional and a +zero does nothing: a clip without `audio` encodes as it did. The cut record +(`segments/<id>.cut.json`) keeps the knobs it used. `validateClipAudio(audio)` +is the one validator (umtool's `updateClip` calls it); +`validateClipAudioEntries(manifest)` runs in the build and the lint. A +montage cuts its own sound: there the knobs are not applied, and the build +says so. + ### `render.chrome` — the on-screen deck's settings, and per-entry `onscreen` Opt-in (`render.chrome.engine: "hyperframes"`, `layout: "deck"`) — see @@ -476,20 +501,41 @@ timeline itself: next pip — their midpoint; with `pip.spacing: "time"` the second the two segments hand over (the next one's mid-dissolve). After the last clip it stands halfway to the track's end. Its label stands in a band above the - track: with any marker the track moves down 10 px (`MARKER_BAND`) and the + track: with any marker the track moves down 22 px (`MARKER_BAND`) and the body under it with it; without one the deck lays out as it always did. - **When.** Hidden until the fuse burns past the flag, then a short pop (scale and opacity, `MARKER_POP`), lit for the rest of the cut; it slides away and back with the panel. A flag after the last clip pops a second before that clip ends. -- **Labels.** One line, at most 24 characters, uppercased; each label's box - reaches at most halfway to the next flag either side (and 240 px at most), - and a label that does not fit ends in an ellipsis rather than running into - its neighbour. The band is above everything in the body, so a label never - meets the tally or the QR. +- **Labels.** One line, at most 24 characters, uppercased, 18 px; each label's + box reaches at most halfway to the next flag either side (and 360 px at + most), and a label that does not fit ends in an ellipsis rather than running + into its neighbour. The band is above everything in the body, so a label + never meets the tally or the QR. +- **`align`** (per marker, default `"auto"`): `"auto"` centres the label on + its flag when that leaves it the room, else gives it the whole stretch it + may take (a flag near the track's end); `"left"` starts the label at its + flag and reads on to the right; `"right"` ends it at the flag; `"center"` + centres it always. A neighbour whose label reads AWAY from a flag lets the + flag's label reach right up to it (3 px short) instead of stopping halfway. +- **`deck.markerLayout`** (`"stagger"`, the default, or `"truncate"`). When a + label would not fit its box (`markerLabelWidth`: its characters at a bold + sans's advances, a little over Fira Sans Bold's measured ones), "stagger" + splits the flags between two rows — every split is tried and the one where + the most labels fit wins, then the least cut off the rest, then the fewest in + the upper row. The band grows by `MARKER_ROW` (22 px) and the track, the + title, the tally and the QR move down by it (the QR shrinks to the room + left, as under one row). Row 1's flags carry a stick up to their labels, a + row above row 0's; row 0's labels keep 8 px clear of those sticks; neither + row reaches the flags' heads. A label that still does not fit is ellipsized, + as in one row. A row that fits is laid exactly as before, whichever the + setting; "truncate" always keeps one row. `deckLayout(render, { schedule })` + is what knows the band's height — the deck page and `compose-chrome` (for + the QR's size) pass the schedule. - **Refused.** `after` must name a CLIP in the timeline, the label must be non-empty and ≤ 24 characters, at most 12 markers, a colour a hex or a - palette key, and unknown keys are refused. `validateChrome` checks the + palette key, `align` one of the four, `markerLayout` one of the two, and + unknown keys are refused. `validateChrome` checks the shape; `validateDeckMarkers(manifest)` (`deck.mjs`) checks the shape and `after` against the whole timeline — the build, the lint and umtool's writers all call it, so removing a clip a marker follows is refused until @@ -697,6 +743,52 @@ a verdict named without a colour keeps the default's), the stamp's seconds, corner and whether it is drawn, and whether and where the tally is drawn; `validateChrome()` refuses an unknown key there as everywhere in the block. +#### A claim's own knobs + +On the entry that STAMPS the claim — the last carrying its id; the same keys +on an earlier entry are checked and not read: + +```jsonc +"claim": { "id": "k3", "verdict": "CONTRADICTED", + "at": 2593.4, "hold": 4, "stamp": true, "count": 2, "label": "2 seizures" } +``` + +| key | range | default | what | +|---|---|---|---| +| `at` | a source second inside the clip's `start`–`end` | the stamp timing above | when the stamp LANDS and the tally steps | +| `hold` | 0.5…10 s | `factcheck.stamp.seconds` | how long the stamp stays, from its start | +| `stamp` | `true` / `false` | `true` | `false`: counted in the tally, nothing drawn | +| `count` | whole 1…99 | 1 | what the tally steps by ("two seizures" in one clip is 2) | +| `label` | ≤ 20 characters, one line | the verdict's `stampLabel`, else its `label` | the stamp's words for this claim | + +- **`at` is the SOURCE clock**, the clip's own `start`/`end` seconds, so it + survives a re-cut. The build maps it through the second the segment really + starts at — its cut record's `start`, after snapping and room — so the stamp + lands on the word; an estimate (umtool before a build) uses the play + window's start. Kept inside the segment: before its start it lands at the + start, past its outgoing transition at the transition. It slams in over the + `slam` before (`STAMP_MOTION`), stays `hold` (else `stamp.seconds`) from its + start and leaves over as long as the segment's transition — or with the + transition, if that comes first. The stamped segment in `schedule.json` + then carries `sourceFrom` (the source second it starts at), so a preview can + place the stamp again. +- **`count`.** The tally's cell steps by n: the number it was on rolls out + and the one it reaches rolls in (every count up to the last has its own + number in the page; the ones stepped over are never shown). +- **The schedule** carries each knob on its stamp only when set (`count`, + `stamp: false`, `label`), and a claim's `claim` object only the keys it + sets — `stamp: true` and `count: 1` are dropped — so a cut without knobs + writes the schedule and the pages it always did. + +#### The stamp's look + +| key (`render.chrome.factcheck`) | range | default | what | +|---|---|---|---| +| `stamp.scale` | 0.5…2 | 1 | the stamp's region (560×200 at 1920 wide) scaled, inside the footage box; the stamp is drawn to it | +| `stamp.motion` | `"slam"` `"pop"` `"fade"` `"none"` | `"slam"` | the entrance, which still ends at `landed`: slam from 1.7× and −14°; pop from 0.6× with an overshoot; fade in place; none appears at `landed` (and leaves at once). Slam and pop flash | +| `stamp.opacity` | 0.3…1 | 1 | the whole stamp's | +| `verdicts.<V>.stampLabel` | ≤ 24 characters | the verdict's `label` | the stamp's word ("SEIZURE") beside the tally's label ("SEIZURES") | + ### `render.chrome.stats` — a frame scan's running numbers (release 31) A cut seeded from a frame scan (`umtool new <slug> --from <channel>/<id> --seed @@ -1836,6 +1928,39 @@ reason: the band plots the ledger the cut carries, and verifying the whole manifest against one variant's file would report a missing chapter for every entry the other cut has. +### Every clip's sound on its own clock, and `sync.json` + +A segment is in sync by its TIMESTAMPS. Its sound can start late — a cut that +reaches before its window's media begins (the window file's own content +starts seconds in; the segment holds its first frame over silence, and the +build says so) — or have a hole — a source's HLS seam. The joins count +SAMPLES (`apad`, `atrim`'s reset, `acrossfade`, `concat`), so until +2026-10-22 a late start or a hole moved that clip's sound, and every later +clip's in its batch, early by that much: on the Huck cut 469 ms from `rescue` on +(audio start 0.469 s) and 68 ms from `first` to `ten-k` (two gaps, 51 + 17 ms, +near the end of `fed`). `AUDIO_ON_CLOCK` (`clip-audio.mjs`: +`aresample=async=1:min_hard_comp=0.01:first_pts=0`) now lays each sound on its +timestamps — silence where it starts late or a hole opens, samples dropped +where two overlap, whatever is more than 10 ms off — at the segment encode, in +the crossfade's pin, the hard-cut concat filter and the preview's concat. A +sound with neither passes sample for sample. `av-clock.test.mjs` is the guard. + +After every build (and `--chrome-only`), `sync-report.mjs` checks it: +`<out>/<variant>/sync.json` + +```jsonc +{ "at": "…", "fps": 30, "items": [ { "id": "c07", "start": 786.7, "lagMs": 0, "peak": 0.95 } ] } +``` + +Each clip's own sound (its segment file, a window past its joins: up to 6 s +from 3 s in) found in the finished cut's within ±2.5 s of its slot, both mono +at 4 kHz, cross-correlated (coarse at 1 kHz, then fine). `lagMs` > 0 is sound +LATER than its picture; `peak` (about 0…1) how well they matched — a muted or +near-silent clip matches weakly, and a lag under a weak peak means little. +Cards and the rest have no source sound and are not listed; a clip under a +second between its joins reads `null`. The build log says each clip off by +more than a frame. `REPORT_VIDEO_SYNC=0` skips it; it never fails a build. + ### The `ledger` entry type `full`'s answer to the claims no clip covers. One card per **run of consecutive @@ -2720,6 +2845,48 @@ same way: wrap to a column count in JS, write to a file, and use concatenation is a stream copy via the concat demuxer. Mismatched streams are the usual reason a naive concat produces a broken or audio-desynced file. +## Quality variants (`render.variants`, `variants.mjs`) + +```jsonc +"render": { "variants": [ + { "name": "master" }, // the build's own <slug>.mp4, not re-encoded + { "name": "1080p", "height": 1080, "crf": 22 }, + { "name": "720p", "height": 720, "crf": 23 }, + { "name": "fit24", "maxMiB": 24 } // under 24 MiB: a chat app's upload limit +] } // (this list is the default) +``` + +| key | range | default | what | +|---|---|---|---| +| `name` | lower-case letters, digits, dashes, ≤ 24; unique; not `sourced`/`article`/`preview`/`prerail`/`partial` | — | the file is `<slug>.<name>.mp4` | +| `height` | even, 144…2160 | the cut's | never above the cut's; for `maxMiB` a cap | +| `crf` | whole 0…51 | 23 | x264 quality (not with `maxMiB`) | +| `maxMiB` | 0.01…4096 | — | made to fit under this size | +| `preset` | x264's | `medium` | | + +At most 12. `master` takes no settings. A crf variant re-encodes the picture +at its height (lanczos, never up) and copies the sound and the chapters. A +`maxMiB` variant is two-pass x264: its sound AAC 48 kb/s mono when the whole +budget is under 300 kb/s, else 96 kb/s stereo; its height the largest of +1080/720/480 (no taller than the cut) whose picture keeps at least 100 kb/s +per 480p's worth of pixels (225 at 720p, 506 at 1080p) — the 20-minute Huck +cut at 24 MiB is 480p at ~115 kb/s; 2 % of the budget is left for the +container. It is encoded again 6 % lower while it lands over (x264 +overshoots: 24.3 MiB at a 23.1 target, measured), four tries at most. + +``` +node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] +``` + +The slug and the ladder come from the take's `video.manifest.json` beside +its `out/`; the source is `<out>/<slug>.mp4` (the sourced cut) unless +`--source` names another. Each file is written under `.variants/` and renamed +into place. `<out>/variants.json` records `{ at, source, items: [{ name, +path, width, height, bytes, kbps }] }` in ladder order; `--only` remakes the +named ones and keeps the other rows. The CLI takes the heavy slot; +`encodeVariants(outDir, { slug, variants, only, source, onLog })` does not — +umtool's job runner holds it. `validateVariants()` is the one validator. + ## Not done yet - **Narration is on cards only.** A card may carry a synthetic voice (see diff --git a/umtool/report-to-video/av-clock.test.mjs b/umtool/report-to-video/av-clock.test.mjs @@ -0,0 +1,120 @@ +// Every clip's sound lands with its picture, whatever its audio's timestamps say. +// +// A segment is in sync by its TIMESTAMPS: one whose audio starts late (a cut +// that reaches before its window's media begins) or has a hole (a source's HLS +// seam) plays right on its own. The joins count SAMPLES -- apad, atrim's +// reset, acrossfade, concat -- so, unaligned, the late start and the hole moved +// that clip's sound and every later clip's early (469 ms and 68 ms on the Huck +// cut, 2026-10-22). These segments put a tone burst exactly 1.0 s into each by +// its timestamps: the second's audio starts 0.5 s late, the third's has a +// 60 ms hole before its tone. In every join path -- one crossfade pass, a +// batched one, the hard-cut concat filter -- each burst must start within a +// frame of 1.0 s after its segment does. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { buildXfadeBatches, hardCutFilterArgs, xfadeConcatArgs, xfadeGraph } from "./build-video.mjs"; + +const have = spawnSync("ffmpeg", ["-version"]).status === 0; +const FPS = 30; +const RENDER = { width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, transition: 0.5, preset: "ultrafast", palette: { bg: "#12101a" } }; +const SECONDS = 4; + +/** + * A 4 s segment whose sound has a 0.5 s tone burst at TIMESTAMP 1.0 s. + * `late`: the audio stream starts this late (s). `hole`: a gap of this many + * seconds opens in the audio's timestamps at 0.5 s. + */ +function segment(dir, name, { late = 0, hole = 0 } = {}) { + const out = path.join(dir, `${name}.mp4`); + // The tone in SAMPLE time, so that after the shifts it sits at pts 1.0. + const on = 1.0 - late - hole; + const shift = [ + late ? `asetpts=PTS+${late}/TB` : null, + hole ? `asetpts='PTS+gte(T,0.5)*${hole}/TB'` : null, + ].filter(Boolean); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", `color=c=gray:s=320x180:r=${FPS}:d=${SECONDS}`, + "-f", "lavfi", "-i", `sine=f=1000:r=48000:d=${(SECONDS - late - hole - 0.02).toFixed(3)}`, + "-filter_complex", + `[1:a]volume=enable='not(between(t,${on.toFixed(3)},${(on + 0.5).toFixed(3)}))':volume=0,aformat=channel_layouts=stereo${shift.length ? "," + shift.join(",") : ""}[a]`, + "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + return out; +} + +/** The time (s) of the first loud 5 ms window at or after `after`, in a file's decoded sound. */ +function onsetAfter(file, after) { + const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 }); + const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, r.stdout.length / 2); + const w = 40; + for (let i = Math.floor(after * 8000); i + w < pcm.length; i += w) { + let sum = 0; + for (let k = i; k < i + w; k += 1) sum += pcm[k] * pcm[k]; + if (Math.sqrt(sum / w) > 1000) return i / 8000; + } + return null; +} + +function run(args) { + const r = spawnSync("ffmpeg", args, { maxBuffer: 1 << 26 }); + assert.equal(r.status, 0, String(r.stderr)); +} + +/** Each segment's burst, measured in `file` against where its segment starts there. */ +function assertOnsets(file, starts, what) { + starts.forEach((s, i) => { + const got = onsetAfter(file, s + 0.6); + assert.ok(got != null, `${what}: no burst in segment ${i}`); + assert.ok(Math.abs(got - (s + 1.0)) <= 1 / FPS, `${what}: segment ${i}'s burst at ${got.toFixed(3)}, expected ${(s + 1).toFixed(3)}`); + }); +} + +test("the joins lay each clip's sound on its own clock: a late start and a hole stay in sync", { skip: !have && "no ffmpeg" }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "av-clock-")); + try { + const segs = [ + segment(dir, "plain"), + segment(dir, "late", { late: 0.5 }), + segment(dir, "hole", { hole: 0.06 }), + segment(dir, "after"), + ]; + // The fixtures are what they say: the late one's audio starts at 0.5 s. + const st = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", segs[1]]); + assert.ok(Math.abs(Number(String(st.stdout).trim()) - 0.5) < 0.03, `late fixture starts at ${String(st.stdout).trim()}`); + + const D = RENDER.transition; + const durs = segs.map(() => SECONDS); + const xStarts = durs.map((_, i) => i * (SECONDS - D)); + + // One crossfade pass. + const one = path.join(dir, "one.mp4"); + const g = xfadeGraph(durs, D, null, RENDER); + run(["-v", "error", "-y", ...segs.flatMap((s) => ["-i", s]), "-filter_complex", g.parts.join(";"), + "-map", g.vlab, "-map", g.alab, "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", one]); + assertOnsets(one, xStarts, "one pass"); + + // Batched: two batches of two, then the join pass over the batch files. + const batches = await buildXfadeBatches({ + segments: segs, durs, batches: [{ from: 0, to: 2 }, { from: 2, to: 4 }], render: RENDER, dir: path.join(dir, "batches"), + }); + const batched = path.join(dir, "batched.mp4"); + run(xfadeConcatArgs({ segments: segs, durs, render: RENDER, outPath: batched, dip: false, batches })); + assertOnsets(batched, xStarts, "batched"); + + // Hard cuts through the concat filter (a cut with joins). + const hard = path.join(dir, "hard.mp4"); + run(hardCutFilterArgs(segs, [null, null, null, null], RENDER, hard)); + assertOnsets(hard, durs.map((_, i) => i * SECONDS), "hard cut"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -145,7 +145,9 @@ import { } 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 { stampsDrawn, validateClaims } from "./factcheck.mjs"; +import { claimOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; +import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs"; +import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; @@ -750,6 +752,7 @@ export function clipFetchArgs({ url, from, to, fmt, dest, extra = [] }) { // Common's (lib/evidenceClip.mjs) since a report site cuts its evidence clips // with the same arguments: re-exported, never re-spelled. export { cutArgs }; +export { AUDIO_ON_CLOCK }; /** * The span a clip's source is needed over: its extent, widened by the fetch @@ -1256,14 +1259,39 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // poster's waveform also reads it), else nothing and `0:a` as ever. // Room's fades (muted head and tail) after the gain. const roomAf = room ? roomAudioFilter(room.plan) : ""; - const soundChain = [!mont && level != null ? levelFilters(level.gain) : "", roomAf].filter(Boolean).join(","); + // First, the sound laid on its own clock (AUDIO_ON_CLOCK): a cut that starts + // before its source's sound does, or a source with a hole in its sound, + // makes a segment whose audio is continuous from 0 -- in sync by samples, + // not only by timestamps, for every pass after this one. + if (segA < 0) { + EMIT("note", { + message: `${entry.id}: the cut starts ${(-segA).toFixed(2)}s before the media in ${path.basename(raw)} — ` + + `its first frame held, silence under it`, + }); + } + // The clip's own `audio` (clip-audio.mjs): its gain and fades last, in the + // segment's clock; its offset reads the sound from the source again, at + // the shifted window, as one more input (the LAST, so every other index is + // the one a clip without it uses). A montage's sound is its own. + const knobs = mont ? null : clipAudioOf(entry); + if (mont && clipAudioOf(entry)) EMIT("note", { message: `${entry.id}: a montage cuts its own sound — its audio settings are not applied` }); + const shifted = offsetWindow(knobs, segA, segB); + const soundInput = shifted + ? [...(shifted.from < 0 ? ["-itsoffset", (-shifted.from).toFixed(3)] : []), ...cutArgs(raw, Math.max(0, shifted.from), shifted.to)] + : null; + const soundChain = [ + AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf, ...clipAudioFilters(knobs, segB - segA), + ].filter(Boolean).join(","); const leveled = !mont && soundChain !== ""; - const levelParts = (posterParts) => (leveled - ? [ - ...(posterParts ? [`[0:a]asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${soundChain}[al]`] : [`[0:a]${soundChain}[al]`]), - ] - : (posterParts ?? [])); + // `ain`: the sound's input -- `[0:a]`, or the offset's own. + const levelParts = (posterParts, ain = "[0:a]") => { + if (!leveled) return posterParts ?? []; + // An asplit only when the poster reads the sound too (its waveform). + if (!(posterParts ?? []).some((p) => p.includes("[0:a]"))) return [...(posterParts ?? []), `${ain}${soundChain}[al]`]; + return [`${ain}asplit=2[lda][ldw]`, ...posterParts.map((p) => p.replaceAll("[0:a]", "[ldw]")), `[lda]${soundChain}[al]`]; + }; const audioMap = leveled ? "[al]" : "0:a"; + if (knobs) cutRecord.audio = knobs; const quotePath = path.join(outDir, "segments", `${entry.id}.quote.txt`); const attribPath = path.join(outDir, "segments", `${entry.id}.attrib.txt`); @@ -1309,8 +1337,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, "-nostdin", "-v", "error", "-y", ...cutArgs(raw, segA, segB), ...(pst ? pst.input : []), + ...(soundInput ?? []), "-filter_complex", [ - ...levelParts(pst ? pst.parts : null), + ...levelParts(pst ? pst.parts : null, soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"), `${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed" })}[v]`, ].join(";"), "-map", "[v]", "-map", audioMap, @@ -1427,6 +1456,13 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, nextIdx += 1; inputs.push(...pst.input); } + // The clip's offset sound: after everything else. + let ain = "[0:a]"; + if (soundInput) { + ain = `[${nextIdx}:a]`; + nextIdx += 1; + inputs.push(...soundInput); + } // A montage's pieces come first: the picture and the sound of the cut, // re-timed (a stutter), zoomed (a punch-in) and fitted to the box, which the // framing below then leaves as it is. Its sound replaces `0:a`; a poster @@ -1436,7 +1472,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]"); const lead = mg ? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts] - : levelParts(pst ? pst.parts : null); + : levelParts(pst ? pst.parts : null, ain); const parts = hasFooter ? [ @@ -4081,9 +4117,17 @@ export function xfadeGraph(durs, D, joins = null, render = null, { joined = fals // silence and trimmed to exactly `d`, every clip's sound starts with its // picture. `d` is the segment's length in the cut (frames ÷ fps, hold // included), the same number the xfade offsets are summed from. + // + // Before the pin, the sound is laid on its own TIMESTAMPS (AUDIO_ON_CLOCK): + // a segment whose audio starts late (a cut that reaches before its + // window's media begins) or has a hole in it (a source's HLS seam) plays + // in sync by its timestamps, but apad, atrim's reset and acrossfade count + // SAMPLES -- unaligned, the late start and every hole moved this clip's + // sound, and every later clip's, early by that much (measured 469 ms and + // 68 ms on the Huck cut). const len = d.toFixed(6); const a = `[p${i}a]`; - parts.push(`${c.a}apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS${a}`); + parts.push(`${c.a}${AUDIO_ON_CLOCK},apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS${a}`); // A blur slide smears and grains each side of a plain seam (transition.mjs). const special = (k) => !!(joins?.[k]?.dip || (!joined && (joins?.[k]?.wipe || joins?.[k]?.whip))); const edges = blurSlideEdges(d, D, render, { @@ -4134,7 +4178,9 @@ export function hardCutFilterArgs(segments, joins, render, outPath, dips = null) const pairs = segments.map((_, i) => { const c = joinInputChain(i, joins?.[i] ?? null, render); parts.push(...c.parts); - return `${c.v}${c.a}`; + // Each sound on its own clock before concat counts its samples (AUDIO_ON_CLOCK). + parts.push(`${c.a}${AUDIO_ON_CLOCK}[h${i}a]`); + return `${c.v}[h${i}a]`; }); parts.push(`${pairs.join("")}concat=n=${segments.length}:v=1:a=1[vc][ac]`); const dp = dipParts("[vc]", dips, render.fps); @@ -4519,7 +4565,11 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re if (segs.length > 1 && D > 0) { ({ parts, vlab, alab } = xfadeGraph(ds, D, js, render)); } else { - const ins = segs.map((_, i) => joinInputChain(i, js?.[i] ?? null, render)); + const ins = segs.map((_, i) => { + const c = joinInputChain(i, js?.[i] ?? null, render); + // Each sound on its own clock, as the full concat lays it (AUDIO_ON_CLOCK). + return { ...c, parts: [...c.parts, `${c.a}${AUDIO_ON_CLOCK}[w${i}a]`], a: `[w${i}a]` }; + }); for (const c of ins) parts.push(...c.parts); vlab = ins[0].v; alab = ins[0].a; @@ -4863,11 +4913,24 @@ export async function measureChromeSchedule({ manifest, entries, segments, D }) // 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; + // A claim stamped at a source second (`claim.at`): the source second each + // claimed clip's segment really starts at, from its cut record (snapped, + // room included). Read only then. + let clipClock = null; + if (entries.some((e) => claimOf(e)?.at !== undefined)) { + clipClock = new Map(); + for (let i = 0; i < entries.length; i += 1) { + if (claimOf(entries[i])?.at === undefined || !segments[i]) continue; + const rec = await readCutRecord(segments[i]).catch(() => null); + if (Number.isFinite(rec?.start)) clipClock.set(entries[i].id, rec.start); + } + } // 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, ...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}), + ...(clipClock ? { clipClock } : {}), }); } @@ -5037,6 +5100,36 @@ export function concatRecordText(segments, joins = null) { * with them (the deck's holds and moves) the concat filter over each input's * chain, one encode -- the copy cannot host a filtergraph. */ +/** + * The sync report over a finished cut (sync-report.mjs): each clip's own + * sound found in `final`, against its slot in the cut's clock (cutOffsets, + * holds included), written to `<outDir>/sync.json`; a clip off by more than a + * frame is said. Cards, teasers and the rest have no source sound to check. + * `REPORT_VIDEO_SYNC=0` skips it. Never fails a build: a report it cannot + * make is said. + */ +export async function reportSync({ outDir, final, entries, segments, D, render, joins = null, env = process.env }) { + if (env.REPORT_VIDEO_SYNC === "0") return null; + try { + const { starts, durs } = await cutOffsets(segments, D, render.fps, joins); + const items = entries + .map((e, i) => ({ e, i })) + .filter(({ e }) => isClipEntry(e) && e.id !== WALL_ENTRY.id) + // The segment's own length (the hold is silence the file does not carry). + .map(({ e, i }) => ({ id: e.id, segment: segments[i], start: starts[i], seconds: durs[i] - (joins?.[i]?.hold ?? 0) })); + const doc = await writeSyncReport({ + outDir, final, items, fps: render.fps, D, + onLog: (message) => EMIT("note", { message }), + }); + const off = doc.items.filter((it) => it.lagMs != null && Math.abs(it.lagMs) > 1000 / render.fps).length; + EMIT("sync", { file: path.join(outDir, SYNC_FILE), clips: doc.items.length, off }); + return doc; + } catch (err) { + EMIT("note", { message: `sync report not made: ${err?.message ?? err}` }); + return null; + } +} + async function concatHardCut(segments, outDir, outPath, { record = false, joins = null, render = null, dips = null } = {}) { if (joins) { await execFileP(FFMPEG, hardCutFilterArgs(segments, joins, render, outPath, dips), { maxBuffer: 1 << 26 }); @@ -5170,7 +5263,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole), - ...validateLook(whole), + ...validateLook(whole), ...validateClipAudioEntries(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } @@ -5701,6 +5794,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ? null : await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); + await reportSync({ outDir, final: dirs.final, entries, segments: segs, D, render, joins }); await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; @@ -5861,6 +5955,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ? null : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); + await reportSync({ outDir, final, entries, segments, D, render, joins }); // A branded cut with a `thumbnail` gets one beside it. The cut is already // done, so a thumbnail that cannot be made is said, not thrown. diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -37,8 +37,8 @@ // second clock or a label. import { fileURLToPath } from "node:url"; -import { deckChoreography, deckLayout, deckMarkers, pageDuration, pipSegments, pipXs, resolveDeck } from "./deck.mjs"; -import { resolveFactcheck, tallyCues, tallyKey, tallyOf, VERDICT_SHAPES } from "./factcheck.mjs"; +import { deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck } from "./deck.mjs"; +import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyOf, VERDICT_SHAPES } from "./factcheck.mjs"; /** * GSAP, vendored, for every chrome region. @@ -146,7 +146,7 @@ const keyOf = (i, part) => (part === "seg" ? `s${i}` : `s${i}.${part}`); export function deckCues(schedule, render) { const deck = resolveDeck(render); const tally = tallyOf(schedule, render); - const lay = deckLayout(render, { tally }); + const lay = deckLayout(render, { tally, schedule }); const segs = schedule.segments; const ch = deckChoreography(schedule, render); const pipped = pipSegments(schedule); @@ -362,7 +362,7 @@ export function subtitleMarkup(text) { export function deckHtml(schedule, render, opts = {}) { const deck = resolveDeck(render); const tally = tallyOf(schedule, render); - const lay = deckLayout(render, { tally }); + const lay = deckLayout(render, { tally, schedule }); const pal = render.palette; const W = lay.width, H = lay.height; const fonts = opts.fonts ?? {}; @@ -437,16 +437,20 @@ export function deckHtml(schedule, render, opts = {}) { .join(""); // The markers: a flag on the track and its label in the band above it. const band = lay.markerBand ?? null; + // Staggered (deckMarkers `row`): row 1's flags carry a taller stick up to + // their labels, a row above row 0's. A label's `align` sets its text's side. const markerHtml = markers .map((mk, j) => { const left = r4(mk.box[0] - mk.x); + const side = mk.align === "left" || mk.align === "right" ? `; text-align:${mk.align}` : ""; return ( - `<div class="mflag" data-k="mk${j}" data-after="${esc(mk.after)}" style="left:${r4(mk.x)}px; --mc:${esc(mk.color)}">` + + `<div class="mflag${mk.row === 1 ? " up" : ""}" data-k="mk${j}" data-after="${esc(mk.after)}" style="left:${r4(mk.x)}px; --mc:${esc(mk.color)}">` + `<div class="mstick"></div><div class="mhead"></div>` + - `<div class="mlabel" style="left:${left}px; width:${mk.box[1] - mk.box[0]}px">${esc(mk.label)}</div></div>` + `<div class="mlabel" style="left:${left}px; width:${mk.box[1] - mk.box[0]}px${side}">${esc(mk.label)}</div></div>` ); }) .join(""); + const staggered = (band?.rows ?? 1) > 1; // The tally: one cell per verdict the cut stamps, each with every count it // will show stacked in one box (`n0` … `n<final>`), its label under it. const tb = lay.tally ?? null; @@ -460,7 +464,7 @@ export function deckHtml(schedule, render, opts = {}) { ? `<div class="tally">` + tally .map((v, j) => { - const finals = schedule.factcheck.stamps.filter((s) => s.verdict === v).length; + const finals = tallyFinals(schedule.factcheck.stamps)[v]; const color = verdictSet[v].color; const nums = Array.from({ length: finals + 1 }, (_, k) => `<div class="tn" data-k="${tallyKey(v, `n${k}`)}">${k}</div>`).join(""); @@ -615,10 +619,13 @@ export function deckHtml(schedule, render, opts = {}) { .mstick { position: absolute; left: -1.5px; top: -14px; width: 3px; height: 20px; border-radius: 1.5px; background: var(--mc); } .mhead { position: absolute; left: 1.5px; top: -14px; width: 12px; height: 10px; background: var(--mc); clip-path: polygon(0% 0%, 100% 50%, 0% 100%); } - .mlabel { position: absolute; top: ${(band?.y ?? 3) - tr.y}px; height: 20px; text-align: center; white-space: nowrap; - overflow: hidden; text-overflow: ellipsis; font-family: 'DeckSansBold', sans-serif; font-size: 18px; + .mlabel { position: absolute; top: ${(band?.y ?? 3) + (staggered ? MARKER_ROW : 0) - tr.y}px; height: 20px; text-align: center; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; font-family: 'DeckSansBold', sans-serif; font-size: ${MARKER_LABEL_SIZE}px; line-height: 20px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--mc); - text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); }` : ""} + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); }` : ""}${staggered ? ` + /* Staggered labels: row 1 a row above, its flag's stick up to it. */ + .mflag.up .mlabel { top: ${band.y - tr.y}px; } + .mflag.up .mstick { top: ${band.y + 20 - tr.y}px; height: ${tr.y + 6 - (band.y + 20)}px; }` : ""} .deck-qr img { display: block; width: ${qr?.size ?? 0}px; height: ${qr?.size ?? 0}px; border-radius: 6px; image-rendering: pixelated; backface-visibility: hidden; box-shadow: 0 0 0 1px ${rgba(pal.fg, 0.25)}, 0 6px 18px rgba(0, 0, 0, 0.35); } diff --git a/umtool/report-to-video/chrome-stamp.mjs b/umtool/report-to-video/chrome-stamp.mjs @@ -13,7 +13,7 @@ // why at length). The times are factcheck.mjs `stampSchedule`'s, untouched. import { pageDuration, stampGeometry } from "./deck.mjs"; import { mix, rgba } from "./chrome-deck.mjs"; -import { resolveFactcheck, STAMP_MOTION } from "./factcheck.mjs"; +import { drawnStamps, resolveFactcheck, STAMP_MOTION } from "./factcheck.mjs"; /** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */ const INSTANT = 0.001; @@ -28,7 +28,7 @@ const esc = (s) => const r4 = (v) => Math.round(v * 10000) / 10000; /** The stamp's tilt at rest, and how far past it (and how large) it starts its slam. */ -export const STAMP_POSE = Object.freeze({ rest: -6, from: -14, scale: 1.7, leaveScale: 0.96 }); +export const STAMP_POSE = Object.freeze({ rest: -6, from: -14, scale: 1.7, leaveScale: 0.96, popScale: 0.6 }); /** * Everything the stamps' timeline does, as data. Stamp j is `st<j>` (autoAlpha, @@ -37,24 +37,46 @@ export const STAMP_POSE = Object.freeze({ rest: -6, from: -14, scale: 1.7, leave * `landed` -- the second the tally steps -- flashes, holds, and fades over its * `out`. * + * `factcheck.stamp.motion` (the render's; slam without one) changes only the + * entrance, which still ends at `landed`: "pop" grows it from + * `STAMP_POSE.popScale` × with an overshoot, "fade" fades it in, "none" puts + * it there at `landed`. Only slam and pop flash; "none" also leaves at once. + * * @returns {{ init: Record<string, object>, cues: Array<{ k: string, at: number, * dur: number, from: object, to: object, ease: string, why: string }> }} */ -export function stampCues(schedule) { - const stamps = schedule.factcheck?.stamps ?? []; +export function stampCues(schedule, render = null) { + // A claim's `stamp: false` counts in the tally and is not drawn here. + const stamps = drawnStamps(schedule.factcheck?.stamps); + const motion = render ? resolveFactcheck(render).stamp.motion ?? "slam" : "slam"; const P = STAMP_POSE; const m = STAMP_MOTION; const init = {}; const ev = []; const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); stamps.forEach((s, j) => { - init[`st${j}`] = { autoAlpha: 0, scale: P.scale, rotation: P.from }; - init[`fl${j}`] = { opacity: 0 }; const why = `stamp ${s.claim}`; - add(`st${j}`, s.at, s.landed - s.at, { autoAlpha: 1, scale: 1, rotation: P.rest }, "power4.in", `${why} in`); - add(`fl${j}`, s.landed, m.flashUp, { opacity: 1 }, "none", `${why} flash`); - add(`fl${j}`, s.landed + m.flashUp, m.flashDown, { opacity: 0 }, "power2.out", `${why} flash`); - add(`st${j}`, s.out[0], s.out[1] - s.out[0], { autoAlpha: 0, scale: P.leaveScale }, "power1.in", `${why} out`); + const rest = { autoAlpha: 1, scale: 1, rotation: P.rest }; + if (motion === "slam") { + init[`st${j}`] = { autoAlpha: 0, scale: P.scale, rotation: P.from }; + add(`st${j}`, s.at, s.landed - s.at, rest, "power4.in", `${why} in`); + } else if (motion === "pop") { + init[`st${j}`] = { autoAlpha: 0, scale: P.popScale, rotation: P.rest }; + add(`st${j}`, s.at, s.landed - s.at, rest, "back.out(2.2)", `${why} in`); + } else if (motion === "fade") { + init[`st${j}`] = { autoAlpha: 0, scale: 1, rotation: P.rest }; + add(`st${j}`, s.at, s.landed - s.at, { autoAlpha: 1 }, "power1.out", `${why} in`); + } else { + init[`st${j}`] = { autoAlpha: 0, scale: 1, rotation: P.rest }; + add(`st${j}`, s.landed, INSTANT, { autoAlpha: 1 }, "none", `${why} in`); + } + if (motion === "slam" || motion === "pop") { + init[`fl${j}`] = { opacity: 0 }; + add(`fl${j}`, s.landed, m.flashUp, { opacity: 1 }, "none", `${why} flash`); + add(`fl${j}`, s.landed + m.flashUp, m.flashDown, { opacity: 0 }, "power2.out", `${why} flash`); + } + if (motion === "none") add(`st${j}`, s.out[0], INSTANT, { autoAlpha: 0 }, "none", `${why} out`); + else add(`st${j}`, s.out[0], s.out[1] - s.out[0], { autoAlpha: 0, scale: P.leaveScale }, "power1.in", `${why} out`); }); // Order, clamp (a cue never starts before the last on its element ends), // and state every from: the last to on its element, or its init. @@ -90,7 +112,7 @@ export function stampCues(schedule) { * seconds. */ export function stampHtml(schedule, render, opts = {}) { - const stamps = schedule.factcheck?.stamps ?? []; + const stamps = drawnStamps(schedule.factcheck?.stamps); if (!stamps.length) throw new Error("stamp: the schedule stamps no claim"); const geo = stampGeometry(render, { feed: schedule.layout === "feed" }); const fc = resolveFactcheck(render); @@ -103,7 +125,7 @@ export function stampHtml(schedule, render, opts = {}) { const dur = opts.duration != null ? r4(Number(opts.duration)) : r4(total - from); if (!(dur > 0)) throw new Error(`stamp: nothing to render from ${from}s of a ${total}s cut`); const windowed = from > 0 || Math.abs(dur - total) > 1e-6; - const { init, cues } = stampCues(schedule); + const { init, cues } = stampCues(schedule, render); // The stamp's box: inside the region with room for its tilt, so no corner // is clipped at rest (the slam's overscale passes the edges for a moment). @@ -113,10 +135,12 @@ export function stampHtml(schedule, render, opts = {}) { const stampHtmlList = stamps .map((s, j) => { const v = fc.verdicts[s.verdict] ?? { label: s.verdict, color: pal.accent }; + // The words: the claim's own `label`, else the verdict's `stampLabel`, else its label. + const word = s.label ?? v.stampLabel ?? v.label; return ( `<div class="stamp" data-claim="${esc(s.claim)}" data-verdict="${esc(s.verdict)}" data-k="st${j}" ` + `style="--vc:${esc(v.color)}; --vg:${rgba(v.color, 0.6)}; --vb:${rgba(mix(pal.bg, v.color, 0.12), 0.82)}">` + - `<div class="word">${esc(v.label)}</div>` + + `<div class="word">${esc(word)}</div>` + `<div class="flash" data-k="fl${j}"></div></div>` ); }) @@ -152,7 +176,7 @@ export function stampHtml(schedule, render, opts = {}) { body { font-family: 'DeckSansBold', sans-serif; font-synthesis: none; -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; } #root { position: relative; width: ${W}px; height: ${H}px; overflow: hidden; } - #stamp-clip { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px; } + #stamp-clip { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px;${fc.stamp.opacity !== undefined && fc.stamp.opacity !== 1 ? ` opacity: ${fc.stamp.opacity};` : ""} } /* A rubber stamp: a double rule in the verdict's colour round its word, on a dark wash so it reads over any footage. Hidden until its cue. */ .stamp { position: absolute; left: ${Math.round((W - bw) / 2)}px; top: ${Math.round((H - bh) / 2)}px; diff --git a/umtool/report-to-video/claim-knobs.test.mjs b/umtool/report-to-video/claim-knobs.test.mjs @@ -0,0 +1,231 @@ +// The claim's own knobs (factcheck.mjs): `at` (a source second the stamp lands +// and the count steps), `hold`, `stamp: false`, `count`, `label`; and the +// fact-check stamp's `scale`, `motion`, `opacity` and a verdict's `stampLabel`. +// Absent, every one leaves the schedule and the pages as they were. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + CLAIM_LIMITS, drawnStamps, normalizeClaim, resolveFactcheck, STAMP_MOTION, stampSchedule, stampsDrawn, + tallyCues, tallyFinals, tallySteps, validateClaims, validateFactcheck, +} from "./factcheck.mjs"; +import { deckSchedule, stampGeometry } from "./deck.mjs"; +import { deckHtml } from "./chrome-deck.mjs"; +import { stampCues, stampHtml } from "./chrome-stamp.mjs"; + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const CHROME = { engine: "hyperframes", layout: "deck", deck: {} }; +const RENDER = { width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, chrome: CHROME }; +const PROV = { siteOrigin: "https://example.test", channelSlug: "demo-channel" }; +const near = (a, b, msg) => assert.ok(Math.abs(a - b) < 1e-3, `${msg}: ${a} != ${b}`); +const withFc = (factcheck) => ({ ...RENDER, chrome: { ...CHROME, factcheck } }); + +// ---- the claim ---------------------------------------------------------------- + +test("normalizeClaim: the knobs ride along when set, and only then; out-of-range refused in sentences", () => { + assert.deepEqual(normalizeClaim({ id: "k1", verdict: "PARTLY" }), { id: "k1", verdict: "PARTLY" }); + assert.deepEqual( + normalizeClaim({ id: "k1", verdict: "PARTLY", at: 12.5, hold: 2, stamp: false, count: 2, label: " 2 SEIZURES " }), + { id: "k1", verdict: "PARTLY", at: 12.5, hold: 2, stamp: false, count: 2, label: "2 SEIZURES" }, + ); + // The defaults written out are the defaults: dropped. + assert.deepEqual(normalizeClaim({ id: "k1", verdict: "PARTLY", stamp: true, count: 1 }), { id: "k1", verdict: "PARTLY" }); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", at: -1 }), /claim\.at must be a source second/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", hold: 0.2 }), /claim\.hold must be from 0\.5 to 10/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", hold: 11 }), /claim\.hold/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", stamp: "no" }), /claim\.stamp must be true or false/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", count: 0 }), /claim\.count must be a whole number from 1 to 99/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", count: 1.5 }), /claim\.count/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", count: 100 }), /claim\.count/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", label: " " }), /claim\.label must be words/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", label: "x".repeat(CLAIM_LIMITS.label + 1) }), /at most 20/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", label: "a\nb" }), /one line/); + assert.throws(() => normalizeClaim({ id: "k1", verdict: "PARTLY", when: 3 }), /claim\.when is not a claim field/); +}); + +test("validateClaims: `at` must lie in its clip's window (source seconds)", () => { + const at = (v) => ({ timeline: [{ type: "clip", id: "c1", start: 100, end: 130, claim: { id: "k", verdict: "PARTLY", at: v } }] }); + assert.deepEqual(validateClaims(at(100)), []); + assert.deepEqual(validateClaims(at(130)), []); + assert.match(validateClaims(at(99.5))[0], /timeline\[0\] \(c1\)\.claim\.at 99\.5 is outside the clip's window 100–130/); + assert.equal(validateClaims(at(131)).length, 1); +}); + +// ---- the stamp's timing ------------------------------------------------------- + +// Three 10 s segments, D 0.5: starts 0, 9.5, 19; c2's source starts at 200. +const SEGS = (claim) => [ + { id: "c1", start: 0, duration: 10, claim: null }, + { id: "c2", start: 9.5, duration: 10, claim, sourceFrom: 200 }, + { id: "c3", start: 19, duration: 10, claim: null }, +]; +const TOTAL = 29; + +test("stampSchedule: without knobs, the stamp it always placed", () => { + const [s] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY" }), D: 0.5, total: TOTAL, render: RENDER }); + assert.deepEqual(Object.keys(s), ["claim", "verdict", "segment", "at", "landed", "out"]); + near(s.at, 16, "3 s before the out"); + near(s.landed, 16 + STAMP_MOTION.slam, "landed"); + assert.deepEqual(s.out, [19, 19.5]); +}); + +test("stampSchedule: `at` lands the stamp at the source second's place in the cut; it stays `hold`, or stamp.seconds", () => { + // Source 203 is 3 s into c2, which starts at 9.5: lands at 12.5. + const [s] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY", at: 203 }), D: 0.5, total: TOTAL, render: RENDER }); + near(s.landed, 12.5, "landed"); + near(s.at, 12.5 - STAMP_MOTION.slam, "slams in before"); + near(s.out[0], s.at + 3, "stays stamp.seconds from its start"); + near(s.out[1] - s.out[0], 0.5, "leaves over the transition's length"); + // hold: 1.5 + const [h] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY", at: 203, hold: 1.5 }), D: 0.5, total: TOTAL, render: RENDER }); + near(h.out[0], h.at + 1.5, "hold"); + // A hold past the segment's out leaves with the transition, as ever. + const [late] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY", at: 208, hold: 10 }), D: 0.5, total: TOTAL, render: RENDER }); + assert.deepEqual(late.out, [19, 19.5]); + // Kept inside the segment: before its start lands at its start; past its out, at the out. + const [early] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY", at: 150 }), D: 0.5, total: TOTAL, render: RENDER }); + near(early.landed, 9.5, "clamped to the segment's start"); + near(early.at, 9.5, "never before it"); + const [past] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY", at: 260 }), D: 0.5, total: TOTAL, render: RENDER }); + near(past.landed, 19, "clamped to its out"); + // hold without `at`: comes in `hold` before the out. + const [ho] = stampSchedule({ segments: SEGS({ id: "k", verdict: "PARTLY", hold: 5 }), D: 0.5, total: TOTAL, render: RENDER }); + near(ho.at, 14, "hold before the out"); + // No source clock: as if there were no `at`. + const segs = SEGS({ id: "k", verdict: "PARTLY", at: 203 }).map(({ sourceFrom: _s, ...s }) => s); + const [noClock] = stampSchedule({ segments: segs, D: 0.5, total: TOTAL, render: RENDER }); + near(noClock.at, 16, "no clock, default timing"); +}); + +test("stampSchedule: count, stamp:false and label ride on the stamp, and only when set", () => { + const [s] = stampSchedule({ + segments: SEGS({ id: "k", verdict: "PARTLY", count: 2, stamp: false, label: "2 SEIZURES" }), D: 0.5, total: TOTAL, render: RENDER, + }); + assert.equal(s.count, 2); + assert.equal(s.stamp, false); + assert.equal(s.label, "2 SEIZURES"); +}); + +test("deckSchedule: a claim's `at` through the cut record's clock; the segment keeps its sourceFrom; none without `at`", () => { + const entries = [ + { type: "clip", id: "c1", video: "v1", start: 10, end: 20 }, + { type: "clip", id: "c2", video: "v2", start: 200, end: 210, claim: { id: "k", verdict: "PARTLY", at: 203.4 } }, + ]; + const s = deckSchedule({ entries, durs: [10, 10], D: 0.5, render: RENDER, provenance: PROV, clipClock: new Map([["c2", 200.4]]) }); + // 203.4 is 3.0 s past where c2's segment really starts (200.4): 9.5 + 3. + near(s.factcheck.stamps[0].landed, 12.5, "landed"); + assert.equal(s.segments[1].sourceFrom, 200.4); + assert.deepEqual(s.segments[1].claim, { id: "k", verdict: "PARTLY", at: 203.4 }); + // Without the clock: the play window's start (200) stands in. + const est = deckSchedule({ entries, durs: [10, 10], D: 0.5, render: RENDER, provenance: PROV }); + near(est.factcheck.stamps[0].landed, 12.9, "estimated"); + // Without `at`, no sourceFrom key at all. + const plain = deckSchedule({ entries: entries.map((e) => (e.claim ? { ...e, claim: { id: "k", verdict: "PARTLY" } } : e)), durs: [10, 10], D: 0.5, render: RENDER, provenance: PROV }); + assert.equal("sourceFrom" in plain.segments[1], false); +}); + +// ---- the tally ------------------------------------------------------------------ + +const ST = (claim, verdict, landed, extra = {}) => ({ claim, verdict, segment: claim, at: landed - 0.28, landed, out: [landed + 2, landed + 2.5], ...extra }); + +test("tallySteps / tallyFinals: a claim's count steps its verdict by n", () => { + const stamps = [ST("a", "PARTLY", 5), ST("b", "PARTLY", 10, { count: 2 }), ST("c", "CONTRADICTED", 12, { count: 3 })]; + const steps = tallySteps(stamps); + assert.deepEqual(steps.map((s) => [s.verdict, s.count, s.step]), [["PARTLY", 1, 1], ["PARTLY", 3, 2], ["CONTRADICTED", 3, 3]]); + assert.equal(tallyFinals(stamps).PARTLY, 3); + assert.equal(tallyFinals(stamps).CONTRADICTED, 3); +}); + +test("tallyCues: a step of n rolls the number it was on out and the number it reaches in", () => { + const stamps = [ST("a", "PARTLY", 5), ST("b", "PARTLY", 10, { count: 2 })]; + const { init, events } = tallyCues(stamps, ["PARTLY"]); + // Every count up to the final has its element (n2 is passed over, never shown). + assert.deepEqual(Object.keys(init).filter((k) => /\.n\d+$/.test(k)), ["ty.PARTLY.n0", "ty.PARTLY.n1", "ty.PARTLY.n2", "ty.PARTLY.n3"]); + const at10 = events.filter((e) => e.at === 10 && /\.n\d+$/.test(e.k)).map((e) => [e.k, e.to.autoAlpha]); + assert.deepEqual(at10, [["ty.PARTLY.n1", 0], ["ty.PARTLY.n3", 1]]); + // The cell lights at its first step whatever that step's size. + const first = tallyCues([ST("x", "PARTLY", 4, { count: 2 })], ["PARTLY"]).events.filter((e) => e.k === "ty.PARTLY" && e.to.opacity === 1); + assert.equal(first.length, 1); +}); + +test("the deck's tally page carries every number the tally reaches", () => { + const entries = [ + { type: "clip", id: "c1", video: "v1", start: 10, end: 20, claim: { id: "k1", verdict: "PARTLY", count: 2 } }, + { type: "clip", id: "c2", video: "v2", start: 30, end: 40, claim: { id: "k2", verdict: "PARTLY" } }, + ]; + const s = deckSchedule({ entries, durs: [10, 10], D: 0.5, render: RENDER, provenance: PROV }); + const html = deckHtml(s, RENDER, {}); + assert.match(html, /data-k="ty\.PARTLY\.n3">3</); + assert.doesNotMatch(html, /data-k="ty\.PARTLY\.n4"/); +}); + +// ---- drawing ------------------------------------------------------------------ + +test("stamp:false: counted in the tally, not drawn; a cut whose every claim is hidden draws no stamps", () => { + const sched = { total: 30, fps: 30, factcheck: { stamps: [ST("a", "PARTLY", 5, { stamp: false }), ST("b", "PARTLY", 10)] } }; + assert.equal(drawnStamps(sched.factcheck.stamps).length, 1); + const { cues } = stampCues(sched); + assert.ok(cues.every((c) => /st0|fl0/.test(c.k))); + assert.ok(cues.some((c) => c.at === 9.72 && c.k === "st0"), "the drawn one is stamp 0"); + assert.equal(tallySteps(sched.factcheck.stamps).at(-1).count, 2); + assert.equal(stampsDrawn(sched, RENDER), true); + const none = { ...sched, factcheck: { stamps: [ST("a", "PARTLY", 5, { stamp: false })] } }; + assert.equal(stampsDrawn(none, RENDER), false); +}); + +test("the stamp's words: the claim's label, else the verdict's stampLabel, else its label", () => { + const sched = { total: 30, fps: 30, factcheck: { stamps: [ST("a", "PARTLY", 5, { label: "2 Seizures" }), ST("b", "PARTLY", 10), ST("c", "CONTRADICTED", 15)] } }; + const r = withFc({ verdicts: { PARTLY: { label: "Seizures", stampLabel: "Seizure" } } }); + const html = stampHtml(sched, r, {}); + const words = [...html.matchAll(/<div class="word">([^<]*)<\/div>/g)].map((m) => m[1]); + assert.deepEqual(words, ["2 Seizures", "Seizure", "Contradicted"]); +}); + +// ---- the stamp's look ------------------------------------------------------------- + +test("factcheck stamp scale/motion/opacity and verdicts[V].stampLabel: validated, defaulted", () => { + const fc = resolveFactcheck(RENDER); + assert.equal(fc.stamp.scale, 1); + assert.equal(fc.stamp.motion, "slam"); + assert.equal(fc.stamp.opacity, 1); + assert.deepEqual(validateFactcheck({ stamp: { scale: 0.5, motion: "fade", opacity: 0.3 } }), []); + assert.deepEqual(validateFactcheck({ stamp: { scale: 2, motion: "none", opacity: 1 } }), []); + const bad = validateFactcheck({ stamp: { scale: 2.5, motion: "spin", opacity: 0.2 } }); + assert.equal(bad.length, 3); + assert.match(bad[0], /stamp\.scale must be from 0\.5 to 2/); + assert.match(bad[1], /stamp\.motion must be "slam", "pop", "fade", "none"/); + assert.match(bad[2], /stamp\.opacity must be from 0\.3 to 1/); + assert.deepEqual(validateFactcheck({ verdicts: { PARTLY: { label: "Seizures", stampLabel: "Seizure" } } }), []); + assert.match(validateFactcheck({ verdicts: { PARTLY: { stampLabel: "" } } })[0], /stampLabel must be words/); + assert.match(validateFactcheck({ verdicts: { PARTLY: { stampLabel: "x".repeat(25) } } })[0], /stampLabel is 25 characters \(at most 24\)/); + assert.equal(resolveFactcheck(withFc({ verdicts: { PARTLY: { stampLabel: "Seizure" } } })).verdicts.PARTLY.stampLabel, "Seizure"); +}); + +test("stamp motion: slam as ever; pop and fade change the entrance; none appears; scale and opacity on the box", () => { + const sched = { total: 30, fps: 30, factcheck: { stamps: [ST("a", "PARTLY", 5)] } }; + const slam = stampCues(sched, RENDER); + const def = stampCues(sched); + assert.deepEqual(slam, def, "the render's default motion is the motion without one"); + assert.equal(slam.init.st0.scale, 1.7); + const pop = stampCues(sched, withFc({ stamp: { motion: "pop" } })); + assert.ok(pop.init.st0.scale < 1 && pop.init.st0.rotation === -6); + const fade = stampCues(sched, withFc({ stamp: { motion: "fade" } })); + assert.deepEqual(fade.init.st0, { autoAlpha: 0, scale: 1, rotation: -6 }); + const none = stampCues(sched, withFc({ stamp: { motion: "none" } })); + const inCue = none.cues.find((c) => c.k === "st0" && c.to.autoAlpha === 1); + assert.ok(inCue.dur <= 0.002 && Math.abs(inCue.at + inCue.dur - 5) < 0.002, "appears at its landing"); + assert.equal(none.cues.filter((c) => c.k === "fl0").length, 0, "no flash without a slam or a pop"); + // The look: scale sizes the stamp's region (and the stamp with it), kept in + // the footage box; opacity is the whole region's, written only when set. + assert.deepEqual(stampGeometry(RENDER), stampGeometry(withFc({ stamp: { scale: 1 } }))); + const big = stampGeometry(withFc({ stamp: { scale: 1.5 } })); + assert.equal(big.width, 840); + assert.equal(big.height, 300); + assert.equal(stampGeometry(withFc({ stamp: { scale: 0.5 } })).width, 280); + const plain = stampHtml(sched, RENDER, {}); + assert.doesNotMatch(plain, /#stamp-clip \{[^}]*opacity/); + const looked = stampHtml(sched, withFc({ stamp: { opacity: 0.6 } }), {}); + assert.match(looked, /#stamp-clip \{[^}]*opacity: 0\.6;/); +}); diff --git a/umtool/report-to-video/clip-audio.mjs b/umtool/report-to-video/clip-audio.mjs @@ -0,0 +1,116 @@ +// A clip's sound at its segment encode: laid on its own clock, and the +// per-clip `audio` knobs. +// +// timeline entry: "audio": { "offset": 120, "gain": -3, "fadeIn": 0.5, "fadeOut": 1 } +// +// `offset` (ms, −2000…2000) moves the sound against the picture: + is LATER. +// It is read from the source again at the shifted window, so nothing is cut +// off the far end. `gain` (dB, −20…20) after any levelling; `fadeIn` / +// `fadeOut` (s, 0…5) at the segment's edges. Every key optional; absent, +// the segment's sound is what it was. +// +// No imports from build-video.mjs: it imports this file, and so do the sync +// report and umtool's writers (K2's updateClip validates through +// validateClipAudio). + +/** + * A sound laid on its own timestamps from 0: silence where its first sample + * starts late or where a hole opens, samples dropped where two overlap -- + * whatever is more than 10 ms off (a third of a frame); no resampling, and a + * stream with neither passes sample for sample. Every filter after it that + * counts samples (apad, acrossfade, concat) then counts the clock. + */ +export const AUDIO_ON_CLOCK = "aresample=async=1:min_hard_comp=0.01:first_pts=0"; + +/** Each knob's range and unit. */ +export const CLIP_AUDIO_LIMITS = Object.freeze({ + offset: Object.freeze({ min: -2000, max: 2000, unit: "ms" }), + gain: Object.freeze({ min: -20, max: 20, unit: "dB" }), + fadeIn: Object.freeze({ min: 0, max: 5, unit: "s" }), + fadeOut: Object.freeze({ min: 0, max: 5, unit: "s" }), +}); + +export const CLIP_AUDIO_KEYS = Object.freeze(Object.keys(CLIP_AUDIO_LIMITS)); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** + * Every reason a clip's `audio` cannot be used, as sentences naming `where` + * (empty: it can). `undefined` / `null` is none. Unknown keys are refused. + * + * @param {unknown} audio + * @param {string} [where] + * @returns {string[]} + */ +export function validateClipAudio(audio, where = "audio") { + if (audio === undefined || audio === null) return []; + if (!isObj(audio)) return [`${where} must be { offset, gain, fadeIn, fadeOut }`]; + const errors = []; + for (const k of Object.keys(audio)) { + if (!CLIP_AUDIO_KEYS.includes(k)) errors.push(`${where}.${k} is not an audio setting (${CLIP_AUDIO_KEYS.join(", ")})`); + } + for (const [k, { min, max, unit }] of Object.entries(CLIP_AUDIO_LIMITS)) { + const v = audio[k]; + if (v === undefined) continue; + if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max) { + errors.push(`${where}.${k} must be a number from ${min} to ${max} (${unit})`); + } + } + return errors; +} + +/** Every clip's `audio` in a manifest, checked (the build's and the lint's). */ +export function validateClipAudioEntries(manifest) { + const errors = []; + (manifest?.timeline ?? []).forEach((e, i) => { + if (e?.audio === undefined) return; + const where = `timeline[${i}] (${e.id ?? "?"}).audio`; + if (e.type && e.type !== "clip") { errors.push(`${where}: only a clip's sound has these settings`); return; } + errors.push(...validateClipAudio(e.audio, where)); + }); + return errors; +} + +/** The knobs that do anything: an empty object (or none) changes nothing. */ +export function clipAudioOf(entry) { + const a = isObj(entry?.audio) ? entry.audio : null; + if (!a || validateClipAudio(a).length) return null; + const out = {}; + if (a.offset) out.offset = a.offset; + if (a.gain) out.gain = a.gain; + if (a.fadeIn) out.fadeIn = a.fadeIn; + if (a.fadeOut) out.fadeOut = a.fadeOut; + return Object.keys(out).length ? out : null; +} + +const num = (v) => String(Number(v.toFixed(4))); + +/** + * The gain and fades as filters on a segment `seconds` long, in its own clock + * (after AUDIO_ON_CLOCK). Empty without any. + * + * @returns {string[]} + */ +export function clipAudioFilters(audio, seconds) { + if (!audio) return []; + const out = []; + if (audio.gain) out.push(`volume=${num(audio.gain)}dB`); + if (audio.fadeIn) out.push(`afade=t=in:st=0:d=${num(Math.min(audio.fadeIn, seconds))}`); + if (audio.fadeOut) { + const d = Math.min(audio.fadeOut, seconds); + out.push(`afade=t=out:st=${num(Math.max(0, seconds - d))}:d=${num(d)}`); + } + return out; +} + +/** + * Where the sound is read from for a segment cut at [a, b] of its source + * file: [a − offset, b − offset] (seconds), so at the segment's second t the + * source's t + a − offset plays -- the sound `offset` later. Null without an + * offset: the picture's own input carries it. + */ +export function offsetWindow(audio, a, b) { + if (!audio?.offset) return null; + const s = audio.offset / 1000; + return { from: a - s, to: b - s }; +} diff --git a/umtool/report-to-video/clip-audio.test.mjs b/umtool/report-to-video/clip-audio.test.mjs @@ -0,0 +1,141 @@ +// A clip's own `audio` (clip-audio.mjs): validated in sentences, and applied +// at the segment encode -- the offset moves the sound against the picture by +// reading the source again, the gain and fades after. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudio, validateClipAudioEntries, +} from "./clip-audio.mjs"; +import { buildVideo } from "./build-video.mjs"; +import { MONO_FONT_FILE } from "./brand.mjs"; + +test("validateClipAudio: none is fine; each knob in its range; unknown keys refused", () => { + assert.deepEqual(validateClipAudio(undefined), []); + assert.deepEqual(validateClipAudio(null), []); + assert.deepEqual(validateClipAudio({}), []); + assert.deepEqual(validateClipAudio({ offset: -2000, gain: 20, fadeIn: 0, fadeOut: 5 }), []); + assert.deepEqual(validateClipAudio({ offset: 2000, gain: -20 }), []); + assert.deepEqual(validateClipAudio("loud"), ["audio must be { offset, gain, fadeIn, fadeOut }"]); + assert.deepEqual(validateClipAudio({ offset: 2001 }), ["audio.offset must be a number from -2000 to 2000 (ms)"]); + assert.deepEqual(validateClipAudio({ gain: "3" }), ["audio.gain must be a number from -20 to 20 (dB)"]); + assert.deepEqual(validateClipAudio({ fadeIn: -1 }), ["audio.fadeIn must be a number from 0 to 5 (s)"]); + assert.deepEqual(validateClipAudio({ fadeOut: 6 }), ["audio.fadeOut must be a number from 0 to 5 (s)"]); + assert.deepEqual(validateClipAudio({ delay: 1 }), ["audio.delay is not an audio setting (offset, gain, fadeIn, fadeOut)"]); + assert.deepEqual(validateClipAudio({ offset: NaN }, "timeline[2] (c).audio"), ["timeline[2] (c).audio.offset must be a number from -2000 to 2000 (ms)"]); +}); + +test("validateClipAudioEntries: a clip's, named by its place; not on a card", () => { + const m = { + timeline: [ + { id: "a", type: "clip", audio: { offset: 50 } }, + { id: "b", type: "clip", audio: { gain: 40 } }, + { id: "c", type: "card", audio: { gain: 1 } }, + { id: "d", type: "clip" }, + ], + }; + assert.deepEqual(validateClipAudioEntries(m), [ + "timeline[1] (b).audio.gain must be a number from -20 to 20 (dB)", + "timeline[2] (c).audio: only a clip's sound has these settings", + ]); +}); + +test("clipAudioOf / clipAudioFilters / offsetWindow: zeros do nothing; gain, then the fades at the edges", () => { + assert.equal(clipAudioOf({}), null); + assert.equal(clipAudioOf({ audio: { offset: 0, gain: 0, fadeIn: 0, fadeOut: 0 } }), null); + assert.equal(clipAudioOf({ audio: { gain: 99 } }), null, "an invalid one is not applied"); + const a = clipAudioOf({ audio: { offset: -250, gain: -6, fadeIn: 0.5, fadeOut: 1 } }); + assert.deepEqual(a, { offset: -250, gain: -6, fadeIn: 0.5, fadeOut: 1 }); + assert.deepEqual(clipAudioFilters(a, 10), ["volume=-6dB", "afade=t=in:st=0:d=0.5", "afade=t=out:st=9:d=1"]); + assert.deepEqual(clipAudioFilters({ fadeOut: 5 }, 3), ["afade=t=out:st=0:d=3"]); + assert.deepEqual(clipAudioFilters(null, 3), []); + assert.equal(offsetWindow(null, 1, 5), null); + assert.deepEqual(offsetWindow({ offset: 300 }, 1, 5), { from: 0.7, to: 4.7 }); + assert.deepEqual(offsetWindow({ offset: -500 }, 1, 5), { from: 1.5, to: 5.5 }); + assert.match(AUDIO_ON_CLOCK, /^aresample=async=1:min_hard_comp=0\.01:first_pts=0$/); +}); + +// ---- the encode, for real ------------------------------------------------------ + +const have = ["ffmpeg", "ffprobe", "magick"].every((b) => spawnSync(b, ["-version"]).status === 0); +const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" }; +const RENDER = { + width: 320, height: 180, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast", + transition: 0, headerHeight: 24, palette: PALETTE, fontRegular: MONO_FONT_FILE, snapWindow: 0.001, +}; + +/** The first loud 5 ms window's time in a file's sound, and the loudest window's RMS. */ +function onset(file) { + const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 }); + const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, r.stdout.length / 2); + let first = null; + let peak = 0; + for (let i = 0; i + 40 < pcm.length; i += 40) { + let sum = 0; + for (let k = i; k < i + 40; k += 1) sum += pcm[k] * pcm[k]; + const rms = Math.sqrt(sum / 40); + if (rms > 1000 && first === null) first = i / 8000; + peak = Math.max(peak, rms); + } + return { first, peak }; +} + +test("the segment encode: offset moves the burst against the picture, both ways; gain lowers it", { skip: !have && "needs ffmpeg, ffprobe and magick" }, async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "rtv-clip-audio-")); + try { + await mkdir(path.join(root, "media"), { recursive: true }); + // Six seconds of picture; a tone burst from 2.0 to 2.5 s. + const src = path.join(root, "media", "talk.mp4"); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=320x180:r=30:d=6", + "-f", "lavfi", "-i", "sine=f=800:r=48000:d=6", + "-filter_complex", "[1:a]volume=enable='not(between(t,2,2.5))':volume=0[a]", + "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ac", "2", src, + ]); + assert.equal(r.status, 0, String(r.stderr)); + await writeFile(path.join(root, "media", "talk.json"), JSON.stringify({ + duration_seconds: 6, chunk_data: [{ start_time: 1, end_time: 5, text: "A tone." }], + })); + const manifestPath = path.join(root, "video.manifest.json"); + const build = async (audio) => { + await writeFile(manifestPath, JSON.stringify({ + slug: "demo", title: "Demo", render: RENDER, + timeline: [{ + id: "c1", type: "clip", src: "media/talk.mp4", cues: "media/talk.json", start: 1, end: 5, + title: "Talk", channelTitle: "Demo", date: "2026-01-02", ...(audio ? { audio } : {}), + }], + })); + const out = await buildVideo({ manifestPath, only: "c1", opts: { noNetwork: true } }); + assert.equal(out.failures.length, 0); + const rec = JSON.parse(await readFile(path.join(root, "out", "sourced", "segments", "c1.cut.json"), "utf8")); + return { ...onset(out.out), start: rec.start, rec }; + }; + const plain = await build(null); + const want = 2.0 - plain.start; + assert.ok(Math.abs(plain.first - want) <= 0.012, `plain burst at ${plain.first}, expected ${want}`); + assert.equal(plain.rec.audio, undefined); + + const later = await build({ offset: 300 }); + assert.ok(Math.abs(later.first - (want + 0.3)) <= 0.012, `+300 ms burst at ${later.first}, expected ${want + 0.3}`); + assert.deepEqual(later.rec.audio, { offset: 300 }); + + const earlier = await build({ offset: -300 }); + assert.ok(Math.abs(earlier.first - (want - 0.3)) <= 0.012, `-300 ms burst at ${earlier.first}, expected ${want - 0.3}`); + + // An offset past the source's head: silence first, the burst still where it should be. + const past = await build({ offset: 1500 }); + assert.ok(Math.abs(past.first - (want + 1.5)) <= 0.012, `+1500 ms burst at ${past.first}, expected ${want + 1.5}`); + + const quiet = await build({ gain: -6 }); + const ratio = quiet.peak / plain.peak; + assert.ok(ratio > 0.45 && ratio < 0.56, `-6 dB peak ratio ${ratio}`); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -748,7 +748,8 @@ async function regionHtml(region, { manifest, manifestDir, base, projDir, assets if (region === "deck") { const render = manifest.render; const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - const lay = deckLayout(render); + // With the schedule: a staggered marker band moves the QR down and may shrink it. + const lay = deckLayout(render, { schedule }); const qrSrcs = {}; if (lay.qr) { const byUrl = await qrPngsFor(schedule.segments.map((s) => s.qrUrl), render, lay.qr.size, assetsDir); diff --git a/umtool/report-to-video/cut-edits.test.mjs b/umtool/report-to-video/cut-edits.test.mjs @@ -160,8 +160,8 @@ test("withCutEdits: nothing to add leaves the joins as they were (null stays nul test("the graphs: unchanged without edits; the hard cut's record names a mute and a fade, so a changed one is never reused", () => { // No edits: the plain crossfade graph (each sound pinned to its picture). assert.deepEqual(xfadeGraph([10, 12], 0.5, withCutEdits(null, 2), RENDER).parts, [ - "[0:a]apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", - "[1:a]apad=whole_dur=12.000000,atrim=end=12.000000,asetpts=PTS-STARTPTS[p1a]", + "[0:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", + "[1:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=12.000000,atrim=end=12.000000,asetpts=PTS-STARTPTS[p1a]", "[0:v][1:v]xfade=transition=fade:duration=0.5:offset=9.500[v1]", "[p0a][p1a]acrossfade=d=0.5:c1=tri:c2=tri[a1]", ]); @@ -185,9 +185,11 @@ test("the graphs: unchanged without edits; the hard cut's record names a mute an const fc = hardCutFilterArgs(segs, edited, RENDER, "/o.mp4"); assert.equal(fc[fc.indexOf("-filter_complex") + 1], "[0:a]afade=t=out:st=2.96:d=0.04[j0a];" + + "[j0a]aresample=async=1:min_hard_comp=0.01:first_pts=0[h0a];" + "[1:v]tpad=stop_mode=clone:stop_duration=2.5,geq=lum='lum(X,Y)+(31-lum(X,Y))*clip((T-10.9667)/1,0,1)+0.5':cb='cb(X,Y)+(132-cb(X,Y))*clip((T-10.9667)/1,0,1)+0.5':cr='cr(X,Y)+(128-cr(X,Y))*clip((T-10.9667)/1,0,1)+0.5':enable='gte(t,10.9667)'[j1v];" + "[1:a]apad=pad_dur=2.5,afade=t=out:st=10.9667:d=1[j1a];" + - "[0:v][j0a][j1v][j1a]concat=n=2:v=1:a=1[vc][ac]"); + "[j1a]aresample=async=1:min_hard_comp=0.01:first_pts=0[h1a];" + + "[0:v][h0a][j1v][h1a]concat=n=2:v=1:a=1[vc][ac]"); }); // ---- ffmpeg, for real ------------------------------------------------------- diff --git a/umtool/report-to-video/deck-markers-layout.test.mjs b/umtool/report-to-video/deck-markers-layout.test.mjs @@ -0,0 +1,155 @@ +// The deck's marker labels laid against crowding: a marker's `align`, and +// `deck.markerLayout` -- "stagger" (the default: two rows when one would not +// fit) or "truncate" (one row, ellipsized). A row that fits is laid as ever. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + DECK_DEFAULTS, deckLayout, deckMarkers, deckSchedule, MARKER_BAND, MARKER_ROW, markerLabelWidth, markerRowsOf, + pipSegments, pipXs, validateChrome, +} from "./deck.mjs"; +import { deckHtml } from "./chrome-deck.mjs"; + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const CHROME = { engine: "hyperframes", layout: "deck" }; +const BASE = { width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE }; +const renderWith = (deck = {}) => ({ ...BASE, chrome: { ...CHROME, deck } }); +const PROV = { siteOrigin: "https://example.test", channelSlug: "chan" }; + +// 26 clips, evenly pipped, as the Huck story cut. +const N = 26; +const ENTRIES = Array.from({ length: N }, (_, i) => ({ id: `c${i}`, type: "clip", video: `v${i}`, start: 0, end: 30 })); +const DURS = ENTRIES.map(() => 30); + +// The crowded case: nine grey chapter flags along the cut and two red promise +// flags, the last three flags within ~200 px of the track's right end. +const CROWD = [ + ...[1, 4, 7, 10, 13, 16, 19, 22].map((i, n) => ({ after: `c${i}`, label: `Chapter ${n + 1}: the dog`, color: "muted" })), + { after: "c23", label: "“3–5 weeks”: 3 wks on", color: "#e5534b" }, + { after: "c24", label: "Chapter 9: the posts", color: "muted" }, + { after: "c25", label: "“I'll post”: 8 wks on", color: "#e5534b" }, +]; + +function lay(render) { + const s = deckSchedule({ entries: ENTRIES, durs: DURS, D: 0.5, render, provenance: PROV }); + const l = deckLayout(render, { schedule: s }); + const pipped = pipSegments(s); + const xs = pipXs(pipped.length, l.pipTrack.x0, l.pipTrack.x1, "even"); + return { s, l, ms: deckMarkers(s, render, xs, pipped, l) }; +} + +test("align and markerLayout: refused in sentences; the layout defaults to stagger", () => { + assert.equal(DECK_DEFAULTS.markerLayout, "stagger"); + const errs = validateChrome({ ...CHROME, deck: { markerLayout: "wrap", markers: [{ after: "c1", label: "x", align: "middle" }] } }); + assert.ok(errs.includes('render.chrome.deck.markers[0].align must be "auto", "left", "right", "center"'), errs.join("\n")); + assert.ok(errs.includes('render.chrome.deck.markerLayout must be "stagger" or "truncate"'), errs.join("\n")); + assert.deepEqual(validateChrome({ ...CHROME, deck: { markerLayout: "truncate", markers: [{ after: "c1", label: "x", align: "left" }] } }), []); +}); + +test("markerLabelWidth: at least Fira Sans Bold's measured widths at 18 px, upper-cased", () => { + // Measured with fontTools (advances + 0.04 em spacing): 207.5 and 195.7 px. + assert.ok(markerLabelWidth("“3–5 weeks”: 3 wks on") >= 208); + assert.ok(markerLabelWidth("“I'll post”: 8 wks on") >= 196); + assert.ok(markerLabelWidth("“3–5 weeks”: 3 wks on") < 260, "and not wildly over"); + assert.equal(markerLabelWidth("ab"), markerLabelWidth("AB")); +}); + +test("a row that fits is laid as it always was: one row, no row keys, the band unchanged", () => { + const r = renderWith({ markers: [{ after: "c5", label: "Short" }, { after: "c20", label: "Also short" }] }); + const { l, ms } = lay(r); + assert.equal(l.markerBand.height, MARKER_BAND + 6); + assert.equal(l.markerBand.rows, undefined); + for (const m of ms) assert.equal("row" in m, false); + assert.equal(markerRowsOf(lay(r).s, r), 1); +}); + +test("crowded: the labels stagger into two rows; none meets another in its row, a stick or the deck's edge", () => { + const r = renderWith({ markers: CROWD }); + const { s, l, ms } = lay(r); + const W = l.width; + // The last three flags sit within ~200 px of the track's end. + const last3 = [...ms].sort((a, b) => a.x - b.x).slice(-3); + assert.ok(last3.every((m) => l.pipTrack.x1 - m.x <= 200), last3.map((m) => m.x).join(", ")); + // In one row they would not all fit. + const trunc = lay(renderWith({ markers: CROWD, markerLayout: "truncate" })).ms; + const fitting = (list) => list.filter((m) => markerLabelWidth(m.label) <= m.box[1] - m.box[0]).length; + assert.ok(fitting(trunc) < trunc.length, "one row truncates some"); + for (const m of trunc) assert.equal("row" in m, false); + // Staggered: two rows. + assert.equal(markerRowsOf(s, r), 2); + const sorted = [...ms].sort((a, b) => a.x - b.x); + assert.ok(sorted.every((m) => m.row === 0 || m.row === 1)); + assert.ok(sorted.some((m) => m.row === 1)); + for (const row of [0, 1]) { + const inRow = sorted.filter((m) => m.row === row); + for (let j = 1; j < inRow.length; j += 1) { + assert.ok(inRow[j - 1].box[1] < inRow[j].box[0], `row ${row}: ${inRow[j - 1].after} and ${inRow[j].after} meet`); + } + } + // Row 0 keeps clear of the sticks reaching up to row 1. + const sticks = sorted.filter((m) => m.row === 1).map((m) => m.x); + for (const m of sorted.filter((x) => x.row === 0)) { + for (const x of sticks) assert.ok(x < m.box[0] || x > m.box[1], `${m.after}'s label crosses a stick at ${x}`); + } + for (const m of ms) assert.ok(m.box[0] >= 16 && m.box[1] <= W - 16, `${m.after} ${m.box}`); + // More of them fit than in one row -- the last three among them. (Three + // ~200 px labels on 140 px of track cannot all fit two rows: the rest are + // ellipsized, as in one row.) + assert.ok(fitting(ms) > fitting(trunc), `${fitting(ms)} vs ${fitting(trunc)}`); + const lastTrunc = [...trunc].sort((a, b) => a.x - b.x).slice(-3); + assert.ok(fitting(last3) > fitting(lastTrunc), `last three: ${fitting(last3)} vs ${fitting(lastTrunc)}`); + // The band grows by a row; the track and everything under it move down by it. + assert.equal(l.markerBand.height, MARKER_BAND + MARKER_ROW + 6); + assert.equal(l.markerBand.rows, 2); + assert.equal(l.pipTrack.y, 16 + MARKER_BAND + MARKER_ROW); + assert.ok(l.qr.y + l.qr.size <= l.height, `qr ${l.qr.y}+${l.qr.size}`); + assert.ok(l.qr.y >= l.pipTrack.y + 12); + assert.ok(l.text.titleY >= l.pipTrack.y + 14); + // The page: row 1's flags are `up`; their labels a row above; neither row reaches the flags' heads. + const html = deckHtml(s, r, {}); + assert.equal((html.match(/class="mflag up"/g) ?? []).length, ms.filter((m) => m.row === 1).length); + const tr = l.pipTrack.y; + const lowTop = Number(html.match(/\.mlabel \{ position: absolute; top: (-?\d+)px;/)[1]); + const upTop = Number(html.match(/\.mflag\.up \.mlabel \{ top: (-?\d+)px; \}/)[1]); + assert.equal(upTop, l.markerBand.y - tr); + assert.equal(lowTop, l.markerBand.y + MARKER_ROW - tr); + assert.ok(upTop + 20 <= lowTop, "the rows do not overlap"); + assert.ok(lowTop + 20 <= -14, "row 0 ends above the flags' heads (14 px over the track)"); + assert.ok(upTop >= -tr, "row 1 starts inside the deck"); + const stick = html.match(/\.mflag\.up \.mstick \{ top: (-?\d+)px; height: (\d+)px; \}/); + assert.equal(Number(stick[1]), upTop + 20, "the tall stick starts under its label"); + assert.equal(Number(stick[1]) + Number(stick[2]), 6, "and ends where a flag's stick does"); +}); + +test("truncate keeps one row in the crowd: the band as ever", () => { + const r = renderWith({ markers: CROWD, markerLayout: "truncate" }); + const { s, l } = lay(r); + assert.equal(markerRowsOf(s, r), 1); + assert.equal(l.markerBand.height, MARKER_BAND + 6); + assert.doesNotMatch(deckHtml(s, r, {}), /mflag up|\.mflag\.up/); +}); + +test("align: left starts the label at its flag, right ends it there, center centres it; text set to that side", () => { + const markers = [ + { after: "c5", label: "left one", align: "left" }, + { after: "c12", label: "right one", align: "right" }, + { after: "c18", label: "centred", align: "center" }, + ]; + const r = renderWith({ markers }); + const { s, ms } = lay(r); + const [a, b, c] = ms; + assert.equal(a.align, "left"); + assert.equal(a.box[0], Math.round(a.x)); + assert.ok(a.box[1] > a.x + 100); + assert.equal(b.box[1], Math.round(b.x)); + assert.ok(b.box[0] < b.x - 100); + assert.ok(Math.abs((c.box[0] + c.box[1]) / 2 - c.x) <= 1); + const html = deckHtml(s, r, {}); + assert.match(html, /data-after="c5"[^>]*>.*?<div class="mlabel" style="left:[^"]*; text-align:left">LEFT ONE|data-after="c5".*?text-align:left/); + assert.match(html, /data-after="c12".*?text-align:right/); + // A left flag followed by another left one may reach right up to it. + const two = lay(renderWith({ markers: [{ after: "c5", label: "a", align: "left" }, { after: "c7", label: "b", align: "left" }] })).ms; + assert.equal(two[0].box[1], Math.round(two[1].x - 3)); +}); diff --git a/umtool/report-to-video/deck-overlay.test.mjs b/umtool/report-to-video/deck-overlay.test.mjs @@ -86,8 +86,8 @@ test("previewFromSegmentsArgs: the window's segments crossfaded as the full conc assert.equal( args[args.indexOf("-filter_complex") + 1], [ - "[0:a]apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", - "[1:a]apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p1a]", + "[0:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", + "[1:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p1a]", "[0:v][1:v]xfade=transition=fade:duration=0.5:offset=9.500[v1]", "[p0a][p1a]acrossfade=d=0.5:c1=tri:c2=tri[a1]", "[v1]trim=start=2.500:duration=10.000,setpts=PTS-STARTPTS[vw]", @@ -105,12 +105,12 @@ test("previewFromSegmentsArgs: hard cuts concatenate; one segment needs neither" D: 0, at: 8, dur: 4, render: DECK, chromePlan: plan, outPath: "/p.mp4", }); const fc2 = two[two.indexOf("-filter_complex") + 1]; - assert.match(fc2, /^\[0:v\]\[0:a\]\[1:v\]\[1:a\]concat=n=2:v=1:a=1\[vc\]\[ac\];\[vc\]trim=start=8\.000:duration=4\.000/); + assert.match(fc2, /^\[0:a\]aresample=async=1:min_hard_comp=0\.01:first_pts=0\[w0a\];\[1:a\]aresample=[^;]*\[w1a\];\[0:v\]\[w0a\]\[1:v\]\[w1a\]concat=n=2:v=1:a=1\[vc\]\[ac\];\[vc\]trim=start=8\.000:duration=4\.000/); const one = previewFromSegmentsArgs({ segments: ["/s/a.mp4", "/s/b.mp4"], durs: [10, 10], starts: [0, 10], D: 0, at: 1, dur: 4, render: DECK, chromePlan: plan, outPath: "/p.mp4", }); - assert.match(one[one.indexOf("-filter_complex") + 1], /^\[0:v\]trim=start=1\.000:duration=4\.000/); + assert.match(one[one.indexOf("-filter_complex") + 1], /^\[0:a\]aresample=[^;]*\[w0a\];\[0:v\]trim=start=1\.000:duration=4\.000/); }); test("chromeFlags: the three deck flags, one at a time", () => { diff --git a/umtool/report-to-video/deck-room.test.mjs b/umtool/report-to-video/deck-room.test.mjs @@ -184,9 +184,9 @@ test("xfadeGraph: without joins, the graph the crossfade concat always wrote", ( const g = xfadeGraph([10, 12, 4], 0.5, null, RENDER); assert.deepEqual(g.parts, [ // Each input's sound pinned to its picture's length before the crossfade. - "[0:a]apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", - "[1:a]apad=whole_dur=12.000000,atrim=end=12.000000,asetpts=PTS-STARTPTS[p1a]", - "[2:a]apad=whole_dur=4.000000,atrim=end=4.000000,asetpts=PTS-STARTPTS[p2a]", + "[0:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", + "[1:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=12.000000,atrim=end=12.000000,asetpts=PTS-STARTPTS[p1a]", + "[2:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=4.000000,atrim=end=4.000000,asetpts=PTS-STARTPTS[p2a]", "[0:v][1:v]xfade=transition=fade:duration=0.5:offset=9.500[v1]", "[p0a][p1a]acrossfade=d=0.5:c1=tri:c2=tri[a1]", "[v1][2:v]xfade=transition=fade:duration=0.5:offset=21.000[v2]", @@ -203,11 +203,11 @@ test("xfadeGraph: a held input joins through its chain, and the offsets after it const g = xfadeGraph([10, 14.5, 4], 0.5, joins, RENDER); const chain = joinInputChain(1, joins[1], RENDER).parts; assert.deepEqual(g.parts, [ - "[0:a]apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", + "[0:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=10.000000,atrim=end=10.000000,asetpts=PTS-STARTPTS[p0a]", ...chain, // The held input's sound is pinned to its length WITH the hold. - "[j1a]apad=whole_dur=14.500000,atrim=end=14.500000,asetpts=PTS-STARTPTS[p1a]", - "[2:a]apad=whole_dur=4.000000,atrim=end=4.000000,asetpts=PTS-STARTPTS[p2a]", + "[j1a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=14.500000,atrim=end=14.500000,asetpts=PTS-STARTPTS[p1a]", + "[2:a]aresample=async=1:min_hard_comp=0.01:first_pts=0,apad=whole_dur=4.000000,atrim=end=4.000000,asetpts=PTS-STARTPTS[p2a]", "[0:v][j1v]xfade=transition=fade:duration=0.5:offset=9.500[v1]", "[p0a][p1a]acrossfade=d=0.5:c1=tri:c2=tri[a1]", "[v1][2:v]xfade=transition=fade:duration=0.5:offset=23.500[v2]", @@ -221,8 +221,10 @@ test("hardCutFilterArgs: the concat filter over each input's chain, one encode", assert.deepEqual(args.filter((_, i) => args[i - 1] === "-i"), ["/s/a.mp4", "/s/b.mp4", "/s/c.mp4"]); assert.equal( args[args.indexOf("-filter_complex") + 1], - "[1:v]tpad=stop_mode=clone:stop_duration=2.5[j1v];[1:a]apad=pad_dur=2.5[j1a];" + - "[0:v][0:a][j1v][j1a][2:v][2:a]concat=n=3:v=1:a=1[vc][ac]", + "[0:a]aresample=async=1:min_hard_comp=0.01:first_pts=0[h0a];" + + "[1:v]tpad=stop_mode=clone:stop_duration=2.5[j1v];[1:a]apad=pad_dur=2.5[j1a];[j1a]aresample=async=1:min_hard_comp=0.01:first_pts=0[h1a];" + + "[2:a]aresample=async=1:min_hard_comp=0.01:first_pts=0[h2a];" + + "[0:v][h0a][j1v][h1a][2:v][h2a]concat=n=3:v=1:a=1[vc][ac]", ); assert.deepEqual(args.slice(args.indexOf("-map"), args.indexOf("-map") + 4), ["-map", "[vc]", "-map", "[ac]"]); assert.equal(args[args.indexOf("-c:v") + 1], "libx264"); @@ -272,14 +274,14 @@ test("a preview window over a held clip: picked by the cut's lengths, its inputs segments: ["/s/a.mp4", "/s/b.mp4", "/s/c.mp4"], durs, starts, D: 0.5, at: 21.5, dur: 1.5, render: RENDER, chromePlan: plan, outPath: "/p.mp4", joins, }); - assert.match(one[one.indexOf("-filter_complex") + 1], /\[j0v\]trim=start=12\.000:duration=1\.500,setpts=PTS-STARTPTS\[vw\];\[j0a\]atrim=/); + assert.match(one[one.indexOf("-filter_complex") + 1], /\[j0a\]aresample=[^;]*\[w0a\];\[j0v\]trim=start=12\.000:duration=1\.500,setpts=PTS-STARTPTS\[vw\];\[w0a\]atrim=/); const plain = previewFromSegmentsArgs({ segments: ["/s/a.mp4", "/s/b.mp4"], durs: [10, 10], starts: [0, 9.5], D: 0.5, at: 8, dur: 4, render: RENDER, chromePlan: plan, outPath: "/p.mp4", }); // Without joins, the window's graph is the crossfade concat's: each sound // pinned to its picture, then the fades. - assert.match(plain[plain.indexOf("-filter_complex") + 1], /^\[0:a\]apad=whole_dur=10\.000000,atrim=end=10\.000000,asetpts=PTS-STARTPTS\[p0a\];\[1:a\]apad=whole_dur=10\.000000[^;]*\[p1a\];\[0:v\]\[1:v\]xfade=transition=fade:duration=0\.5:offset=9\.500\[v1\];\[p0a\]\[p1a\]acrossfade/); + assert.match(plain[plain.indexOf("-filter_complex") + 1], /^\[0:a\]aresample=async=1:min_hard_comp=0\.01:first_pts=0,apad=whole_dur=10\.000000,atrim=end=10\.000000,asetpts=PTS-STARTPTS\[p0a\];\[1:a\]aresample=[^;]*apad=whole_dur=10\.000000[^;]*\[p1a\];\[0:v\]\[1:v\]xfade=transition=fade:duration=0\.5:offset=9\.500\[v1\];\[p0a\]\[p1a\]acrossfade/); }); // ---- ffmpeg, for real ------------------------------------------------------- diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -78,11 +78,16 @@ export const DECK_DEFAULTS = Object.freeze({ // take the code's width. The clip's own deck QR (`qr`) is untouched. qr: true, }), - // Flags on the pip track: `[{ after, label, color? }]`, each between the pip - // of the clip `after` names and the next, hidden until the fuse reaches it - // (deckMarkers). An empty list is no flags, and the deck lays out as it - // always did. + // Flags on the pip track: `[{ after, label, color?, align? }]`, each between + // the pip of the clip `after` names and the next, hidden until the fuse + // reaches it (deckMarkers). An empty list is no flags, and the deck lays out + // as it always did. markers: Object.freeze([]), + // Crowded labels: "stagger" lays them in two rows when one would not fit in + // a single row (the band grows by MARKER_ROW, the track moves down by it); + // "truncate" keeps one row and ellipsizes. A single row that fits is laid + // the same either way. + markerLayout: "stagger", }); /** The pip's colour when lit (`pip.color`): the deck's accent, or a claimed clip's verdict. */ @@ -91,6 +96,17 @@ export const PIP_COLORS = Object.freeze(["accent", "verdict"]); /** A marker's limits: how many, and a label's characters. */ export const MARKER_LIMITS = Object.freeze({ count: 12, label: 24 }); +/** + * Where a marker's label sits against its flag: "auto" (centred when it has + * the room, else the stretch it may take -- as it always was), "left" (it + * starts at the flag and reads on to the right), "right" (it ends at the + * flag), "center" (centred on it, always). + */ +export const MARKER_ALIGNS = Object.freeze(["auto", "left", "right", "center"]); + +/** `deck.markerLayout`: crowded labels in two rows, or one row ellipsized. */ +export const MARKER_LAYOUTS = Object.freeze(["stagger", "truncate"]); + /** The palette keys a marker's `color` may name (else a `#rgb` / `#rrggbb`). */ export const MARKER_PALETTE_KEYS = Object.freeze(["fg", "muted", "accent", "amber", "dim"]); @@ -303,6 +319,9 @@ export function validateChrome(chrome, render = {}) { if (p.inset !== undefined && !numIn(p.inset, 0, 80)) errors.push(`${w}.posts.inset must be from 0 to 80`); }); errors.push(...markerShapeErrors(d.markers, `${w}.markers`)); + if (d.markerLayout !== undefined && !MARKER_LAYOUTS.includes(d.markerLayout)) { + errors.push(`${w}.markerLayout must be ${MARKER_LAYOUTS.map((l) => `"${l}"`).join(" or ")}`); + } sub("motion", ["out", "in", "pip"], (m) => { for (const k of ["out", "in"]) { if (m[k] !== undefined && !numIn(m[k], 0, 2)) errors.push(`${w}.motion.${k} must be from 0 to 2 seconds`); @@ -356,7 +375,10 @@ function markerShapeErrors(markers, where) { const at = `${where}[${i}]`; if (!isObj(m)) { errors.push(`${at} must be { after, label, color? }`); return; } for (const k of Object.keys(m)) { - if (!["after", "label", "color"].includes(k)) errors.push(`${at}.${k} is not a marker setting (after, label, color)`); + if (!["after", "label", "color", "align"].includes(k)) errors.push(`${at}.${k} is not a marker setting (after, label, color, align)`); + } + if (m.align !== undefined && !MARKER_ALIGNS.includes(m.align)) { + errors.push(`${at}.align must be ${MARKER_ALIGNS.map((a) => `"${a}"`).join(", ")}`); } if (typeof m.after !== "string" || !m.after.trim()) errors.push(`${at}.after must name a clip's id`); const label = typeof m.label === "string" ? m.label.trim() : ""; @@ -492,16 +514,22 @@ export function threadsGeometry(render) { * text column (`factcheck.tally.position`) and the text keeps the rest. * * @param {any} render - * @param {{ tally?: string[] | null }} [opts] + * `schedule`, when given, lets the markers' labels stagger: when they need + * two rows (deckMarkers) the band is MARKER_ROW taller and everything under + * it moves down by that. Without it -- or when one row fits -- one row. + * + * @param {{ tally?: string[] | null, schedule?: any }} [opts] */ -export function deckLayout(render, { tally = null } = {}) { +export function deckLayout(render, { tally = null, schedule = null } = {}) { const { W, deck: rect } = deckGeometry(render); const d = resolveDeck(render); const padX = 48; // The markers' labels (`deck.markers`) stand in a band above the track: the // track moves down by it, and only when there is a marker to label, so a // deck without them lays out as it always did. - const markerBand = Array.isArray(d.markers) && d.markers.length ? MARKER_BAND : 0; + const marked = Array.isArray(d.markers) && d.markers.length > 0; + const rows = marked && schedule ? markerRowsOf(schedule, render) : 1; + const markerBand = marked ? MARKER_BAND + (rows > 1 ? MARKER_ROW : 0) : 0; const trackY = 16 + markerBand; // The body is everything under the pip track: the text block and the QR are // both centred in it, so the title's optical centre and the code's agree @@ -563,13 +591,90 @@ export function deckLayout(render, { tally = null } = {}) { // Only with a tally, so a deck without claims lays out as it always did. ...(tallyBox ? { tally: tallyBox } : {}), // Only with markers, likewise: where their labels stand (deckMarkers). - ...(markerBand ? { markerBand: { y: 3, height: markerBand + 6 } } : {}), + ...(markerBand ? { markerBand: { y: 3, height: markerBand + 6, ...(rows > 1 ? { rows } : {}) } } : {}), }; } /** How far the track moves down to make room for the markers' labels. */ export const MARKER_BAND = 22; +/** How much taller the band is when the labels stagger into a second row. */ +export const MARKER_ROW = 22; + +/** A marker label's font size, px (chrome-deck.mjs draws it at this). */ +export const MARKER_LABEL_SIZE = 18; + +/** + * About how wide a marker's label draws, px: its characters upper-cased (the + * page sets it so), each at a bold sans's advance for its kind plus the + * 0.04 em the page spaces letters by -- a little over Fira Sans Bold's + * measured widths, so a label called fitting does fit. What decides that a + * row of labels is crowded; the page still ellipsizes one that is not. + */ +export function markerLabelWidth(label, size = MARKER_LABEL_SIZE) { + let em = 0; + for (const ch of String(label ?? "").toUpperCase()) { + if (ch === " ") em += 0.25; + else if (/[.,:;'!|’‘]/.test(ch)) em += 0.26; + else if (/[0-9]/.test(ch)) em += 0.56; + else if (/[MW@&]/.test(ch)) em += 0.86; + else if (/[A-Z]/.test(ch)) em += 0.62; + else em += 0.52; + em += 0.04; + } + return Math.ceil(em * size); +} + +/** A flag's stick is kept this clear of a label in the row under its own. */ +const STICK_CLEAR = 8; + +/** + * The label boxes of one row of flags (sorted by x): each up to halfway to + * its neighbours in the row -- or right up to one whose label reads away + * from it ("left"/"right") -- 360 px at most, inside the deck, and clear of + * `walls` (the sticks of the flags labelled in the row above). "auto" is the + * rule it always was: centred when that leaves the label room, else the + * whole stretch it may take. + */ +function labelBoxes(row, W, walls = []) { + return row.map((p, o) => { + const prev = row[o - 1] ?? null; + const next = row[o + 1] ?? null; + const a = p.align ?? "auto"; + const reach = a === "left" ? [p.x, p.x + 360] : a === "right" ? [p.x - 360, p.x] : [p.x - 180, p.x + 180]; + let lo = Math.max(16, reach[0], prev === null ? -Infinity : prev.align === "right" ? prev.x + 3 : (prev.x + p.x) / 2 + 3); + let hi = Math.min(W - 16, reach[1], next === null ? Infinity : next.align === "left" ? next.x - 3 : (p.x + next.x) / 2 - 3); + for (const w of walls) { + if (w < p.x) lo = Math.max(lo, w + STICK_CLEAR); + else if (w > p.x) hi = Math.min(hi, w - STICK_CLEAR); + } + hi = Math.max(lo, hi); + let box; + if (a === "left" || a === "right") box = [lo, hi]; + else { + const half = Math.min(p.x - lo, hi - p.x); + box = a === "center" || half * 2 >= Math.min(140, hi - lo) ? [p.x - half, p.x + half] : [lo, hi]; + } + return box.map((v) => Math.round(v)); + }); +} + +/** + * How many rows the deck's marker labels take for this schedule: 2 when they + * stagger (deckMarkers), else 1. + */ +export function markerRowsOf(schedule, render) { + const d = resolveDeck(render); + if (!Array.isArray(d.markers) || !d.markers.length) return 1; + const lay = deckLayout(render); + const pipped = pipSegments(schedule); + const xs = pipXs( + pipped.length, lay.pipTrack.x0, lay.pipTrack.x1, d.pip.spacing, + d.pip.spacing === "time" ? { total: schedule.total, segments: pipped } : null, + ); + return deckMarkers(schedule, render, xs, pipped, lay).some((m) => m.row === 1) ? 2 : 1; +} + /** * Where each of the deck's markers (`deck.markers`) stands on the pip track, * region-local px: `x` between the pip of the clip it follows and the next @@ -578,11 +683,21 @@ export const MARKER_BAND = 22; * box `[left, right]`: at most 360 px centred on the flag, never past halfway * to the next flag either side nor off the track's ends, so two labels never * meet -- a long one is ellipsized in it. `k` is the pip it follows. A marker - * whose clip has no pip (not in the cut) is left out. + * whose clip has no pip (not in the cut) is left out. A marker's `align` + * places its label against its flag (MARKER_ALIGNS; "auto" as ever). + * + * Crowded: when a label would not fit its box and `deck.markerLayout` is + * "stagger" (the default), the flags alternate between two rows (`row` 0, the + * one over the track, and 1 above it) and each label takes the room to its + * neighbours in its own row; one in row 0 stays clear of the sticks that + * reach up past it to row 1. A label that still does not fit is ellipsized, + * as in one row. `row` and `align` are on a marker only when they say + * something (staggered; not "auto"). * * `xs` are the pips' x (pipXs), `pipped` their segments (pipSegments). * - * @returns {Array<{ after: string, label: string, color: string, k: number, x: number, box: [number, number] }>} + * @returns {Array<{ after: string, label: string, color: string, k: number, x: number, box: [number, number], + * align?: string, row?: number }>} */ export function deckMarkers(schedule, render, xs, pipped, lay = deckLayout(render)) { const d = resolveDeck(render); @@ -609,23 +724,54 @@ export function deckMarkers(schedule, render, xs, pipped, lay = deckLayout(rende x = Math.min(x1, Math.max(x0, x)); const key = m.color ?? MARKER_DEFAULT_COLOR; const color = HEX_RE.test(key) ? key : pal[key] ?? pal.fg ?? "#ffffff"; - placed.push({ after, label: String(m.label ?? "").trim(), color, k, x: Math.round(x * 100) / 100 }); + const align = MARKER_ALIGNS.includes(m.align) && m.align !== "auto" ? m.align : null; + placed.push({ after, label: String(m.label ?? "").trim(), color, k, x: Math.round(x * 100) / 100, ...(align ? { align } : {}) }); } // The label boxes: each up to halfway to its neighbours, 360 px at most. const order = placed.map((p, j) => j).sort((a, b) => placed[a].x - placed[b].x); const W = lay.width; - return placed.map((p, j) => { - const o = order.indexOf(j); - const prev = o > 0 ? placed[order[o - 1]].x : null; - const next = o < order.length - 1 ? placed[order[o + 1]].x : null; - const lo = Math.max(16, p.x - 180, prev === null ? -Infinity : (prev + p.x) / 2 + 3); - const hi = Math.max(lo, Math.min(W - 16, p.x + 180, next === null ? Infinity : (p.x + next) / 2 - 3)); - // Centred on the flag when that leaves the label room; else the whole - // stretch it may take, off-centre (a flag near the track's end). - const half = Math.min(p.x - lo, hi - p.x); - const box = half * 2 >= Math.min(140, hi - lo) ? [p.x - half, p.x + half] : [lo, hi]; - return { ...p, box: box.map((v) => Math.round(v)) }; - }); + const one = labelBoxes(order.map((j) => placed[j]), W); + const boxOf = new Map(order.map((j, o) => [j, one[o]])); + const need = placed.map((p) => markerLabelWidth(p.label)); + const fits = (j, box) => need[j] <= box[1] - box[0]; + if (d.markerLayout === "truncate" || order.every((j) => fits(j, boxOf.get(j)))) { + return placed.map((p, j) => ({ ...p, box: boxOf.get(j) })); + } + // Two rows: row 1's sticks reach up through row 0. Every split of the flags + // between the rows is tried (there are at most MARKER_LIMITS.count) and the + // one where the most labels fit wins -- then the least cut off the rest, + // then the fewest in row 1, then the first in order: alternating flags, + // when nothing tells two splits apart. Past 12 flags, they alternate. + const n = order.length; + const lay2 = (mask) => { + const rows = [order.filter((_, o) => !((mask >> o) & 1)), order.filter((_, o) => (mask >> o) & 1)]; + const up = labelBoxes(rows[1].map((j) => placed[j]), W); + const low = labelBoxes(rows[0].map((j) => placed[j]), W, rows[1].map((j) => placed[j].x)); + const at = new Map([ + ...rows[0].map((j, o) => [j, { box: low[o], row: 0 }]), + ...rows[1].map((j, o) => [j, { box: up[o], row: 1 }]), + ]); + let fit = 0, short = 0; + for (const [j, { box }] of at) { + const over = need[j] - (box[1] - box[0]); + if (over <= 0) fit += 1; + else short += over; + } + return { at, fit, short, ups: rows[1].length }; + }; + let alt = 0; + for (let o = 1; o < n; o += 2) alt |= 1 << o; + let best = lay2(alt); + if (n <= MARKER_LIMITS.count) { + for (let mask = 0; mask < 1 << n; mask += 1) { + if (mask === alt) continue; + const c = lay2(mask); + if (c.fit > best.fit || (c.fit === best.fit && (c.short < best.short || (c.short === best.short && c.ups < best.ups)))) best = c; + } + } + // All in one row is no stagger: the one row as above. + if (best.ups === 0) return placed.map((p, j) => ({ ...p, box: boxOf.get(j) })); + return placed.map((p, j) => ({ ...p, ...best.at.get(j) })); } /** @@ -801,7 +947,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, + fxWords = null, fxClock = null, clipClock = null, }) { const deck = resolveDeck(render); const fps = render.fps ?? 30; @@ -820,7 +966,18 @@ export function deckSchedule({ // the deck alone, and writes the schedule a deck without posts always did. const feed = placed.length > 0 && deck.posts.layout === "feed"; const moves = placed.length && !feed ? footageMoves({ posts: placed, segments: segs, render }) : []; - const stamps = stampSchedule({ segments: segs.map((s, i) => ({ ...s, claim: claimOf(entries[i]) })), D, total, render }); + // A claim stamped at a source second (`claim.at`) needs the source second + // its segment starts at: the cut record's (`clipClock`), else the play + // window's estimate. Only then: a cut without `at` places what it did. + const stamps = stampSchedule({ + segments: segs.map((s, i) => { + const claim = claimOf(entries[i]); + if (claim?.at === undefined) return { ...s, claim }; + const e = entries[i]; + return { ...s, claim, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }; + }), + D, total, render, + }); const threads = threadsOn(render) ? threadSchedule({ segments: segs.map((s, i) => ({ ...s, thread: threadOf(entries[i]) })), D, total, render, moves }) : null; @@ -874,6 +1031,9 @@ export function deckSchedule({ ...(dipOf(e, fps) ? { dip: dipOf(e, fps) } : {}), // Only on an entry that carries a claim (factcheck.mjs), likewise. ...(claimOf(e) ? { claim: claimOf(e) } : {}), + // And on one stamped at a source second, the second its segment starts + // at -- what placed the stamp, kept for a preview to place it again. + ...(claimOf(e)?.at !== undefined ? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) } : {}), }; }), // The fact-check stamps: present only when a claim is stamped. @@ -1448,10 +1608,11 @@ export function stampGeometry(render, { feed = false } = {}) { const { W } = deckGeometry(render); const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage; const k = W / 1920; - const width = Math.min(even(560 * k), even(f.width)); - const height = Math.min(even(200 * k), even(f.height)); + // `stamp.scale` sizes the region (the stamp is drawn to it), still inside the footage. + const { position: pos, scale = 1 } = resolveFactcheck(render).stamp; + const width = Math.min(even(560 * k * scale), even(f.width)); + const height = Math.min(even(200 * k * scale), even(f.height)); const inset = Math.round(28 * k); - const pos = resolveFactcheck(render).stamp.position; const [v, h] = pos === "center" ? ["center", "center"] : pos.split("-"); const x = h === "left" ? f.x + inset : h === "right" ? f.x + f.width - inset - width : f.x + (f.width - width) / 2; const y = v === "top" ? f.y + inset : v === "bottom" ? f.y + f.height - inset - height : f.y + (f.height - height) / 2; diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs @@ -3,8 +3,14 @@ // deck whose counts step up as each stamp lands. // // timeline entry: "claim": { "id": "k3", "verdict": "CONTRADICTED" } -// render.chrome: "factcheck": { "verdicts": { "PARTLY": { "label": "Half true" } }, -// "stamp": { "show": true, "seconds": 3, "position": "top-left" }, +// -- and, each optional, on the entry that stamps (the +// LAST carrying the id): "at" (source seconds the stamp +// lands and the count steps), "hold" (seconds on screen), +// "stamp": false (counts, draws nothing), "count" (steps +// the tally by n), "label" (the stamp's words) +// render.chrome: "factcheck": { "verdicts": { "PARTLY": { "label": "Half true", "stampLabel": "Half" } }, +// "stamp": { "show": true, "seconds": 3, "position": "top-left", +// "scale": 1, "motion": "slam", "opacity": 1 }, // "tally": { "show": true, "position": "right" } } // // `claim` is its own key: an entry's `verdict` is the clip review's @@ -35,6 +41,9 @@ export { VERDICTS }; /** Where the stamp sits in the footage box. */ export const STAMP_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right", "center"]); +/** How a stamp comes in: slammed down (as ever), popped up, faded in, or just there. */ +export const STAMP_MOTIONS = Object.freeze(["slam", "pop", "fade", "none"]); + /** Which end of the deck's text column the tally takes. */ export const TALLY_POSITIONS = Object.freeze(["right", "left"]); @@ -48,12 +57,28 @@ export const FACTCHECK_DEFAULTS = Object.freeze({ verdicts: VERDICT_DEFAULTS, // `show: false` draws no stamp at all -- no composition, no overlay -- and // the tally still counts each claim at the second its stamp would have landed. - stamp: Object.freeze({ show: true, seconds: 3, position: "top-left" }), + // `scale` sizes the stamp's region (and so the stamp), `motion` is how it + // comes in, `opacity` the whole stamp's. + stamp: Object.freeze({ show: true, seconds: 3, position: "top-left", scale: 1, motion: "slam", opacity: 1 }), tally: Object.freeze({ show: true, position: "right" }), }); /** The limits: a stamp's seconds on screen, a label's characters. */ -export const FACTCHECK_LIMITS = Object.freeze({ seconds: Object.freeze([1, 10]), label: VERDICT_LABEL_MAX }); +export const FACTCHECK_LIMITS = Object.freeze({ + seconds: Object.freeze([1, 10]), + label: VERDICT_LABEL_MAX, + scale: Object.freeze([0.5, 2]), + opacity: Object.freeze([0.3, 1]), +}); + +/** + * A claim's own knobs (on the entry that stamps): `hold` seconds on screen, + * `count` the tally's step, `label` the stamp's characters. + */ +export const CLAIM_LIMITS = Object.freeze({ hold: Object.freeze([0.5, 10]), count: Object.freeze([1, 99]), label: 20 }); + +/** The keys a `claim` may carry. */ +export const CLAIM_KEYS = Object.freeze(["id", "verdict", "at", "hold", "stamp", "count", "label"]); /** * The stamp's motion, in seconds: it slams in over `slam` (landing is when the @@ -103,7 +128,19 @@ export function validateFactcheck(f, where = "render.chrome.factcheck") { for (const [k, v] of Object.entries(f.verdicts)) { const w = `${where}.verdicts.${k}`; if (!VERDICTS.includes(k)) { errors.push(`${w} is not a verdict (${VERDICTS.join(", ")})`); continue; } - errors.push(...verdictOverrideProblems(v, w)); + // `stampLabel` is the video's own (the stamp's word beside the tally's + // `label`); the rest is common's override, checked by common's rule. + if (isObj(v) && v.stampLabel !== undefined) { + const { stampLabel, ...rest } = v; + if (typeof stampLabel !== "string" || !stampLabel.trim()) errors.push(`${w}.stampLabel must be words, not empty`); + else if (/[\r\n]/.test(stampLabel)) errors.push(`${w}.stampLabel must be one line`); + else if (stampLabel.trim().length > VERDICT_LABEL_MAX) { + errors.push(`${w}.stampLabel is ${stampLabel.trim().length} characters (at most ${VERDICT_LABEL_MAX})`); + } + errors.push(...verdictOverrideProblems(rest, w)); + } else { + errors.push(...verdictOverrideProblems(v, w)); + } } } } @@ -113,13 +150,20 @@ export function validateFactcheck(f, where = "render.chrome.factcheck") { unknownKeys(f[key], allowed, `${where}.${key}`, errors); check(f[key]); }; - sub("stamp", ["show", "seconds", "position"], (s) => { + sub("stamp", ["show", "seconds", "position", "scale", "motion", "opacity"], (s) => { if (s.show !== undefined && typeof s.show !== "boolean") errors.push(`${where}.stamp.show must be true or false`); const [lo, hi] = FACTCHECK_LIMITS.seconds; if (s.seconds !== undefined && !numIn(s.seconds, lo, hi)) errors.push(`${where}.stamp.seconds must be from ${lo} to ${hi}`); if (s.position !== undefined && !STAMP_POSITIONS.includes(s.position)) { errors.push(`${where}.stamp.position must be ${STAMP_POSITIONS.map((p) => `"${p}"`).join(", ")}`); } + const [slo, shi] = FACTCHECK_LIMITS.scale; + if (s.scale !== undefined && !numIn(s.scale, slo, shi)) errors.push(`${where}.stamp.scale must be from ${slo} to ${shi}`); + if (s.motion !== undefined && !STAMP_MOTIONS.includes(s.motion)) { + errors.push(`${where}.stamp.motion must be ${STAMP_MOTIONS.map((m) => `"${m}"`).join(", ")}`); + } + const [olo, ohi] = FACTCHECK_LIMITS.opacity; + if (s.opacity !== undefined && !numIn(s.opacity, olo, ohi)) errors.push(`${where}.stamp.opacity must be from ${olo} to ${ohi}`); }); sub("tally", ["show", "position"], (t) => { if (t.show !== undefined && typeof t.show !== "boolean") errors.push(`${where}.tally.show must be true or false`); @@ -136,21 +180,59 @@ export function validateFactcheck(f, where = "render.chrome.factcheck") { /** * A `claim` value, normalised: `{ id, verdict }` with the id trimmed, or null - * for none (`undefined`, `null`). Throws a sentence on a shape no writer - * should store. + * for none (`undefined`, `null`), plus each knob it sets -- `at` (source + * seconds), `hold` (seconds), `stamp: false`, `count` (1–99) and `label` + * (trimmed, ≤ 20 characters) -- and nothing it does not, so a claim without + * knobs is the `{ id, verdict }` it always was. `stamp: true` is the default + * and is dropped. Throws a sentence on a shape no writer should store. (That + * `at` lies in its entry's window is validateClaims', which has the entry.) * - * @returns {{ id: string, verdict: string } | null} + * @returns {{ id: string, verdict: string, at?: number, hold?: number, + * stamp?: false, count?: number, label?: string } | null} */ export function normalizeClaim(v) { if (v === undefined || v === null) return null; if (!isObj(v)) throw new Error("claim must be { id, verdict }"); for (const k of Object.keys(v)) { - if (k !== "id" && k !== "verdict") throw new Error(`claim.${k} is not a claim field (id, verdict)`); + if (!CLAIM_KEYS.includes(k)) throw new Error(`claim.${k} is not a claim field (${CLAIM_KEYS.join(", ")})`); } const id = typeof v.id === "string" ? v.id.trim() : ""; if (!CLAIM_ID_RE.test(id)) throw new Error("claim.id must be letters, digits, dots, colons, dashes or underscores (at most 64)"); if (!VERDICTS.includes(v.verdict)) throw new Error(`claim.verdict must be one of ${VERDICTS.join(", ")}`); - return { id, verdict: v.verdict }; + const out = { id, verdict: v.verdict }; + if (v.at !== undefined) { + if (!numIn(v.at, 0, Number.MAX_SAFE_INTEGER)) throw new Error("claim.at must be a source second, 0 or more"); + out.at = v.at; + } + if (v.hold !== undefined) { + const [lo, hi] = CLAIM_LIMITS.hold; + if (!numIn(v.hold, lo, hi)) throw new Error(`claim.hold must be from ${lo} to ${hi} seconds`); + out.hold = v.hold; + } + if (v.stamp !== undefined) { + if (typeof v.stamp !== "boolean") throw new Error("claim.stamp must be true or false"); + if (v.stamp === false) out.stamp = false; + } + if (v.count !== undefined) { + const [lo, hi] = CLAIM_LIMITS.count; + if (!Number.isInteger(v.count) || v.count < lo || v.count > hi) throw new Error(`claim.count must be a whole number from ${lo} to ${hi}`); + if (v.count !== 1) out.count = v.count; + } + if (v.label !== undefined) { + const label = typeof v.label === "string" ? v.label.trim() : ""; + if (!label) throw new Error("claim.label must be words, not empty"); + if (/[\r\n]/.test(label)) throw new Error("claim.label must be one line"); + if (label.length > CLAIM_LIMITS.label) throw new Error(`claim.label is ${label.length} characters (at most ${CLAIM_LIMITS.label})`); + out.label = label; + } + return out; +} + +/** The knobs of a normalised claim (everything but its id and verdict). */ +export function claimKnobs(claim) { + if (!claim) return {}; + const { id: _i, verdict: _v, ...knobs } = claim; + return knobs; } /** An entry's claim when it carries a sound one, else null. Never throws. */ @@ -185,6 +267,10 @@ export function validateClaims(manifest) { errors.push(`${where}.${err.message}`); return; } + // `at` is the entry's own clock: a second of the source inside its window. + if (c.at !== undefined && Number.isFinite(e.start) && Number.isFinite(e.end) && (c.at < e.start || c.at > e.end)) { + errors.push(`${where}.claim.at ${c.at} is outside the clip's window ${e.start}–${e.end} (source seconds)`); + } const seen = verdictOf.get(c.id); if (seen && seen.verdict !== c.verdict) { errors.push(`${where}.claim ${c.id} is ${c.verdict} here and ${seen.verdict} at ${seen.where} -- one claim, one verdict`); @@ -204,15 +290,28 @@ export function validateClaims(manifest) { * The stamp leaves with that segment's outgoing transition -- the next * segment's start to its start + D with a crossfade, the 0.3 s before the cut * on a hard cut, the last 0.3 s of the last segment -- and comes in `seconds` - * before it leaves (`stamp.seconds`), or as the segment's incoming dissolve - * ends when the segment is shorter than that. It has LANDED -- and the tally - * steps -- `STAMP_MOTION.slam` after it starts, never after it starts leaving. + * before it leaves (`stamp.seconds`, or the claim's `hold`), or as the + * segment's incoming dissolve ends when the segment is shorter than that. It + * has LANDED -- and the tally steps -- `STAMP_MOTION.slam` after it starts, + * never after it starts leaving. + * + * A claim with `at` (a SOURCE second) lands then instead: at the segment's + * start plus `at` less the source second the segment starts at (its + * `sourceFrom`, the cut record's: snapped, room included), kept inside the + * segment; it slams in over the `slam` before, stays `hold` (else + * `stamp.seconds`) from its start, and leaves over as long as the segment's + * transition -- or with the transition, if that comes first. A segment with + * no `sourceFrom` stamps the claim as if it had no `at`. + * + * The claim's other knobs ride on its stamp only when set: `count` (the + * tally's step), `stamp: false` (counted, not drawn), `label` (the stamp's + * words). A claim without knobs stamps exactly as it always did. * * `segments` are the schedule's, in order, each `{ id, start, duration, - * claim? }` (`claim` as `claimOf` gives it). + * claim?, sourceFrom? }` (`claim` as `claimOf` gives it). * * @returns {Array<{ claim: string, verdict: string, segment: string, at: number, - * landed: number, out: [number, number] }>} + * landed: number, out: [number, number], count?: number, stamp?: false, label?: string }>} */ export function stampSchedule({ segments, D, total, render }) { const seconds = resolveFactcheck(render).stamp.seconds; @@ -222,24 +321,44 @@ export function stampSchedule({ segments, D, total, render }) { .sort((a, b) => a[1] - b[1]) .map(([claim, i]) => { const seg = segments[i]; + const c = seg.claim; const next = segments[i + 1]; const out = !next ? [total - 0.3, total] : D > 0 ? [next.start, next.start + D] : [next.start - 0.3, next.start]; const from = seg.start + (i > 0 ? D : 0); - const at = Math.min(Math.max(from, out[0] - seconds), out[0]); + const stay = c.hold ?? seconds; + const knobs = { + ...(c.count !== undefined && c.count !== 1 ? { count: c.count } : {}), + ...(c.stamp === false ? { stamp: false } : {}), + ...(c.label !== undefined ? { label: c.label } : {}), + }; + if (c.at !== undefined && Number.isFinite(seg.sourceFrom)) { + // The cut's second the source's `at` plays at, inside the segment + // and before its stamp has to leave. + const want = seg.start + (c.at - seg.sourceFrom); + const landed = Math.min(Math.max(seg.start, want), out[0]); + const at = Math.max(seg.start, landed - STAMP_MOTION.slam); + const leave = Math.min(at + stay, out[0]); + const own = leave < out[0] ? [leave, leave + (out[1] - out[0])] : out; + return { claim, verdict: c.verdict, segment: seg.id, at, landed, out: own, ...knobs }; + } + const at = Math.min(Math.max(from, out[0] - stay), out[0]); const landed = Math.min(at + STAMP_MOTION.slam, out[0]); - return { claim, verdict: seg.claim.verdict, segment: seg.id, at, landed, out }; + return { claim, verdict: c.verdict, segment: seg.id, at, landed, out, ...knobs }; }); } +/** The stamps that are DRAWN: all but a claim's `stamp: false`. */ +export const drawnStamps = (stamps = []) => stamps.filter((s) => s.stamp !== false); + /** * Are the stamps DRAWN: the schedule stamps a claim and `stamp.show` is on. * With it off the schedule still carries its stamps -- the tally counts at * each one's `landed` -- but no stamp composition is rendered or laid. */ export function stampsDrawn(schedule, render) { - return !!schedule?.factcheck?.stamps?.length && resolveFactcheck(render).stamp.show !== false; + return drawnStamps(schedule?.factcheck?.stamps).length > 0 && resolveFactcheck(render).stamp.show !== false; } /** @@ -265,20 +384,30 @@ export function tallyVerdicts(stamps = []) { /** * The tally's steps, in landing order: at each stamp's `landed`, its verdict's - * count goes up by one. `counts` is every verdict's count after the step. + * count goes up by the stamp's `count` (1 unless its claim says). `count` is + * the verdict's count after the step, `step` what it went up by, `counts` + * every verdict's count after it. * - * @returns {Array<{ at: number, verdict: string, count: number, counts: Record<string, number> }>} + * @returns {Array<{ at: number, verdict: string, count: number, step: number, counts: Record<string, number> }>} */ export function tallySteps(stamps = []) { const counts = Object.fromEntries(VERDICTS.map((v) => [v, 0])); return [...stamps] .sort((a, b) => a.landed - b.landed) .map((s) => { - counts[s.verdict] += 1; - return { at: s.landed, verdict: s.verdict, count: counts[s.verdict], counts: { ...counts } }; + const step = s.count ?? 1; + counts[s.verdict] += step; + return { at: s.landed, verdict: s.verdict, count: counts[s.verdict], step, counts: { ...counts } }; }); } +/** Each verdict's count at the end of the cut: the tally's last numbers. */ +export function tallyFinals(stamps = []) { + const finals = Object.fromEntries(VERDICTS.map((v) => [v, 0])); + for (const s of stamps) finals[s.verdict] += s.count ?? 1; + return finals; +} + /** * The verdicts a deck schedule's tally shows, or null for no tally: the * setting is on and the cut stamps at least one claim. @@ -320,8 +449,8 @@ export function tallyCues(stamps, verdicts = tallyVerdicts(stamps)) { const events = []; for (const s of steps) { const why = `tally ${s.verdict} ${s.count}`; - if (s.count === 1) events.push({ k: tallyKey(s.verdict), at: s.at, dur: 0.2, to: { opacity: 1 }, ease: "power1.out", why }); - events.push({ k: tallyKey(s.verdict, `n${s.count - 1}`), at: s.at, dur: m.roll, to: { yPercent: -100, autoAlpha: 0 }, ease: "power2.in", why }); + if (s.count === s.step) events.push({ k: tallyKey(s.verdict), at: s.at, dur: 0.2, to: { opacity: 1 }, ease: "power1.out", why }); + events.push({ k: tallyKey(s.verdict, `n${s.count - s.step}`), at: s.at, dur: m.roll, to: { yPercent: -100, autoAlpha: 0 }, ease: "power2.in", why }); events.push({ k: tallyKey(s.verdict, `n${s.count}`), at: s.at, dur: m.roll, to: { yPercent: 0, autoAlpha: 1 }, ease: "power3.out", why }); events.push({ k: tallyKey(s.verdict, "flash"), at: s.at, dur: m.flashUp, to: { opacity: 1 }, ease: "none", why }); events.push({ k: tallyKey(s.verdict, "flash"), at: s.at + m.flashUp, dur: m.flashDown, to: { opacity: 0 }, ease: "power2.out", why }); diff --git a/umtool/report-to-video/factcheck.test.mjs b/umtool/report-to-video/factcheck.test.mjs @@ -94,12 +94,12 @@ test("validateClaims: shape, never on a teaser, one verdict per claim id; the re test("resolveFactcheck: every default, a verdict's label and colour filled on their own", () => { assert.deepEqual(resolveFactcheck(RENDER), { verdicts: Object.fromEntries(VERDICTS.map((v) => [v, { ...FACTCHECK_DEFAULTS.verdicts[v] }])), - stamp: { show: true, seconds: 3, position: "top-left" }, + stamp: { show: true, seconds: 3, position: "top-left", scale: 1, motion: "slam", opacity: 1 }, tally: { show: true, position: "right" }, }); const f = resolveFactcheck({ chrome: { ...CHROME, factcheck: { verdicts: { PARTLY: { label: "Half true" } }, stamp: { seconds: 5 } } } }); assert.deepEqual(f.verdicts.PARTLY, { label: "Half true", color: FACTCHECK_DEFAULTS.verdicts.PARTLY.color }); - assert.deepEqual(f.stamp, { show: true, seconds: 5, position: "top-left" }); + assert.deepEqual(f.stamp, { show: true, seconds: 5, position: "top-left", scale: 1, motion: "slam", opacity: 1 }); }); test("validateChrome refuses a bad factcheck block in sentences, unknown keys included", () => { diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -81,6 +81,7 @@ import { validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, } from "./deck.mjs"; import { validateClaims } from "./factcheck.mjs"; +import { validateClipAudioEntries } from "./clip-audio.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; @@ -226,7 +227,7 @@ export function imageSrcsOf(manifest, { only = null } = {}) { /** The validators a build runs before it renders, as one list of sentences. */ export function validatorErrors(whole) { const errors = [ - ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), + ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateClipAudioEntries(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), // The podcast's settings: its render refuses them, and `--lint` says so first. ...validatePodcast(whole), diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -13,7 +13,8 @@ "report-check-availability": "./check-availability.mjs", "report-verify-build": "./verify-build.mjs", "report-compose-chrome": "./compose-chrome.mjs", - "report-shoot-page": "./shoot-page.mjs" + "report-shoot-page": "./shoot-page.mjs", + "report-variants": "./variants.mjs" }, "exports": { "./attribution": "./attribution.mjs", @@ -21,6 +22,7 @@ "./brand-ids": "./brand-ids.mjs", "./build-video": "./build-video.mjs", "./check-availability": "./check-availability.mjs", + "./clip-audio": "./clip-audio.mjs", "./compose-chrome": "./compose-chrome.mjs", "./cues": "./cues.mjs", "./deck": "./deck.mjs", @@ -49,7 +51,9 @@ "./shoot-page": "./shoot-page.mjs", "./social": "./social.mjs", "./sources": "./sources.mjs", + "./sync-report": "./sync-report.mjs", "./transition": "./transition.mjs", + "./variants": "./variants.mjs", "./verify-build": "./verify-build.mjs", "./youtube": "./youtube.mjs" } diff --git a/umtool/report-to-video/sync-report.mjs b/umtool/report-to-video/sync-report.mjs @@ -0,0 +1,145 @@ +// The sync report: after a build, where each clip's own sound lands in the +// finished cut against where its picture is scheduled. `<out>/sync.json` +// `{ at, fps, items: [{ id, start, lagMs, peak }] }`. +// +// The method is the one the Huck desync was measured with (lag.py): a few +// seconds of the segment's sound, past its crossfade, cross-correlated against +// the final's sound around the same slot, both mono at 4 kHz. `lagMs` > 0 is +// sound LATER than its picture; `peak` (≈ 0..1) is how well the two matched +// -- a muted or near-silent clip matches weakly and its lag means little. +import { execFile } from "node:child_process"; +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; + +import { AUDIO_ON_CLOCK } from "./clip-audio.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; + +export const SYNC_FILE = "sync.json"; +export const SYNC_RATE = 4000; +/** Below this the match is too weak for a lag to be called a fault. */ +export const SYNC_WEAK_PEAK = 0.3; + +/** `seconds` of `file`'s sound from `from`, mono f32 at `rate`, on its own clock. */ +export async function pcmMono(file, from, seconds, rate = SYNC_RATE) { + const { stdout } = await execFileP(FFMPEG(), [ + "-nostdin", "-v", "error", + "-ss", Math.max(0, from).toFixed(3), "-t", seconds.toFixed(3), "-i", file, + "-vn", "-af", AUDIO_ON_CLOCK, "-ac", "1", "-ar", String(rate), "-f", "f32le", "-", + ], { encoding: "buffer", maxBuffer: 1 << 28 }); + return new Float32Array(stdout.buffer, stdout.byteOffset, Math.floor(stdout.length / 4)); +} + +/** + * Where `a` sits in `b`: the offset (samples) of the best match of `a` inside + * `b`, and that match's strength -- lag.py's normalised correlation peak. + */ +export function bestMatch(a, b, { from = 0, to = Infinity } = {}) { + const n = a.length; + const m = Math.min(b.length - n + 1, to + 1); + if (n < 2 || m < 1) return null; + let mean = 0; + for (let i = 0; i < n; i += 1) mean += a[i]; + mean /= n; + let v = 0; + for (let i = 0; i < n; i += 1) v += (a[i] - mean) ** 2; + const sd = Math.sqrt(v / n) + 1e-9; + const an = new Float32Array(n); + for (let i = 0; i < n; i += 1) an[i] = (a[i] - mean) / sd; + let bm = 0; + for (let i = 0; i < b.length; i += 1) bm += b[i]; + bm /= b.length; + let bv = 0; + const bn = new Float32Array(b.length); + for (let i = 0; i < b.length; i += 1) { + bn[i] = b[i] - bm; + bv += bn[i] * bn[i]; + } + const bsd = Math.sqrt(bv / b.length) + 1e-9; + let best = -Infinity; + let k = Math.max(0, from); + for (let o = Math.max(0, from); o < m; o += 1) { + let c = 0; + for (let j = 0; j < n; j += 1) c += an[j] * bn[o + j]; + if (c > best) { + best = c; + k = o; + } + } + return { offset: k, peak: best / n / bsd }; +} + +/** `x` averaged down by `f`. */ +function decimate(x, f) { + const out = new Float32Array(Math.floor(x.length / f)); + for (let i = 0; i < out.length; i += 1) { + let s = 0; + for (let j = 0; j < f; j += 1) s += x[i * f + j]; + out[i] = s / f; + } + return out; +} + +/** + * bestMatch, found coarse first: at a quarter of the rate over every offset, + * then at the full rate within ±8 samples of the coarse peak -- the same + * answer as the full search on speech, a tenth of the work. + */ +export function bestMatchFast(a, b, f = 4) { + const coarse = bestMatch(decimate(a, f), decimate(b, f)); + if (!coarse) return bestMatch(a, b); + const at = coarse.offset * f; + return bestMatch(a, b, { from: at - 2 * f, to: at + 2 * f }); +} + +/** + * The window of a segment `seconds` long that is measured: past the joins at + * either end (`D`), up to `span` seconds from `lead` in. Null when the segment + * has under a second of its own between them. + */ +export function measureWindow(seconds, D = 0.5, { lead = 3, span = 6 } = {}) { + const from = Math.min(lead, Math.max(D + 0.1, (seconds - span) / 2)); + const len = Math.min(span, seconds - D - 0.1 - from); + return len >= 1 ? { from, len } : null; +} + +/** + * One clip's lag in the final: its segment's sound over `measureWindow`, + * found in the final's within ±`slack` of where its slot puts it. + */ +export async function clipLag({ segment, final, start, seconds, D = 0.5, slack = 2.5, rate = SYNC_RATE }) { + const w = measureWindow(seconds, D); + if (!w) return null; + const a = await pcmMono(segment, w.from, w.len, rate); + const lo = start + w.from - slack; + const b = await pcmMono(final, lo, w.len + 2 * slack, rate); + // A slot near the cut's head cannot look `slack` back: what it can. + const back = Math.min(slack, start + w.from); + if (a.length < rate * 0.9 || b.length < a.length) return null; + const hit = bestMatchFast(a, b); + if (!hit) return null; + return { lagMs: Math.round((hit.offset / rate - back) * 1000), peak: Number(hit.peak.toFixed(2)) }; +} + +/** + * The report for a finished cut: every clip of `items` (`{ id, segment, start, + * seconds }`, starts in the cut's clock) measured, written to `<outDir>/sync.json`. + * `onLog(line)` hears each clip off by more than a frame. + */ +export async function writeSyncReport({ outDir, final, items, fps, D = 0.5, onLog = () => {} }) { + const out = []; + for (const it of items) { + const r = await clipLag({ segment: it.segment, final, start: it.start, seconds: it.seconds, D }).catch(() => null); + const row = { id: it.id, start: Number(it.start.toFixed(3)), lagMs: r?.lagMs ?? null, peak: r?.peak ?? null }; + out.push(row); + if (r && Math.abs(r.lagMs) > 1000 / fps) { + onLog(`sync: ${it.id} sound ${r.lagMs > 0 ? "late" : "early"} by ${Math.abs(r.lagMs)} ms` + + (r.peak < SYNC_WEAK_PEAK ? ` (weak match, peak ${r.peak})` : "")); + } + } + const doc = { at: new Date().toISOString(), fps, items: out }; + await writeFile(path.join(outDir, SYNC_FILE), JSON.stringify(doc, null, 2) + "\n"); + return doc; +} diff --git a/umtool/report-to-video/sync-report.test.mjs b/umtool/report-to-video/sync-report.test.mjs @@ -0,0 +1,78 @@ +// The sync report finds each clip's own sound in the finished cut. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { xfadeGraph } from "./build-video.mjs"; +import { bestMatch, bestMatchFast, measureWindow, SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; + +const have = spawnSync("ffmpeg", ["-version"]).status === 0; +const RENDER = { width: 160, height: 90, fps: 30, audioRate: 48000, audioChannels: 2 }; + +test("measureWindow: past the joins, up to six seconds from three in; none under a second", () => { + assert.deepEqual(measureWindow(30, 0.5), { from: 3, len: 6 }); + assert.deepEqual(measureWindow(8, 0.5), { from: 1, len: 6 }); + const w = measureWindow(4, 0.5); + assert.equal(w.from, 0.6); + assert.ok(Math.abs(w.len - 2.8) < 1e-9); + assert.equal(measureWindow(1.5, 0.5), null); +}); + +test("bestMatch / bestMatchFast: the offset a copy sits at", () => { + let seed = 7; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31) - 0.5; + // Low-passed noise, as speech is to a 4 kHz decode. + const b = new Float32Array(4000); + let y = 0; + for (let i = 0; i < b.length; i += 1) b[i] = y = 0.7 * y + rnd(); + const a = b.slice(1234, 1234 + 1000); + assert.equal(bestMatch(a, b).offset, 1234); + assert.equal(bestMatchFast(a, b).offset, 1234); + assert.ok(bestMatch(a, b).peak > 0.95); +}); + +function segment(dir, name, seed) { + const out = path.join(dir, `${name}.mp4`); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", "color=c=gray:s=160x90:r=30:d=8", + "-f", "lavfi", "-i", `anoisesrc=d=8:c=pink:r=48000:a=0.3:seed=${seed}`, + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ac", "2", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + return out; +} + +test("writeSyncReport: in sync it reads 0; a cut whose sound is 100 ms late reads +100", { skip: !have && "no ffmpeg" }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "sync-report-")); + try { + const segs = [segment(dir, "a", 1), segment(dir, "b", 2), segment(dir, "c", 3)]; + const D = 0.5; + const g = xfadeGraph([8, 8, 8], D, null, RENDER); + const final = path.join(dir, "final.mp4"); + let r = spawnSync("ffmpeg", ["-v", "error", "-y", ...segs.flatMap((s) => ["-i", s]), "-filter_complex", g.parts.join(";"), + "-map", g.vlab, "-map", g.alab, "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", final]); + assert.equal(r.status, 0, String(r.stderr)); + const items = segs.map((s, i) => ({ id: `c${i}`, segment: s, start: i * (8 - D), seconds: 8 })); + const logs = []; + const doc = await writeSyncReport({ outDir: dir, final, items, fps: 30, D, onLog: (l) => logs.push(l) }); + for (const it of doc.items) assert.ok(Math.abs(it.lagMs) <= 2, `${it.id} lag ${it.lagMs}`); + assert.deepEqual(logs, []); + assert.deepEqual(JSON.parse(readFileSync(path.join(dir, SYNC_FILE), "utf8")).items.map((it) => it.id), ["c0", "c1", "c2"]); + + const late = path.join(dir, "late.mp4"); + r = spawnSync("ffmpeg", ["-v", "error", "-y", "-i", final, "-af", "adelay=100:all=1", "-c:v", "copy", "-c:a", "aac", late]); + assert.equal(r.status, 0, String(r.stderr)); + const bad = await writeSyncReport({ outDir: dir, final: late, items, fps: 30, D, onLog: (l) => logs.push(l) }); + for (const it of bad.items) assert.ok(Math.abs(it.lagMs - 100) <= 2, `${it.id} lag ${it.lagMs}`); + assert.equal(logs.length, 3); + assert.match(logs[0], /^sync: c0 sound late by 10\d ms/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/variants.mjs b/umtool/report-to-video/variants.mjs @@ -0,0 +1,301 @@ +#!/usr/bin/env node +// Quality variants of a finished cut: the encode ladder for sharing it +// elsewhere -- the build's own file, smaller re-encodes at a height and a +// quality, and ones made to fit under a size (a chat app's upload limit). +// +// render.variants: [{ name: "master" }, +// { name: "1080p", height: 1080, crf: 22 }, +// { name: "720p", height: 720, crf: 23 }, +// { name: "fit24", maxMiB: 24 }] (the default) +// +// Each is `<take out>/<slug>.<name>.mp4` beside the cut, `master` excepted: +// it IS the build's `<slug>.mp4`, not a copy. `<take out>/variants.json` +// says what was made: `{ at, source, items: [{ name, path, width, height, +// bytes, kbps }] }`. +// +// A `maxMiB` variant is two-pass x264 at the largest of 1080/720/480 (no +// larger than the cut) whose picture keeps at least 100 kb/s per 480p's worth +// of pixels; its sound AAC 48 kb/s mono when the whole is under 300 kb/s, +// else 96 kb/s stereo; and it is encoded again 6 % lower while it lands over +// (x264 overshoots: 24.3 MiB at a 23.1 target, measured). +// +// node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] +// +// The CLI takes the machine's heavy slot (heavy-gate.mjs); encodeVariants +// itself does not -- umtool's job runner holds it for the UI. +import { execFile } from "node:child_process"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { promisify } from "node:util"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; + +/** The ladder when `render.variants` is absent. */ +export const DEFAULT_VARIANTS = Object.freeze([ + Object.freeze({ name: "master" }), + Object.freeze({ name: "1080p", height: 1080, crf: 22 }), + Object.freeze({ name: "720p", height: 720, crf: 23 }), + Object.freeze({ name: "fit24", maxMiB: 24 }), +]); + +export const VARIANTS_FILE = "variants.json"; + +/** The heights a size-capped variant picks from, largest first. */ +export const FIT_HEIGHTS = Object.freeze([1080, 720, 480]); + +/** A size-capped variant's picture floor: kb/s per 480p's worth of pixels. */ +export const FIT_FLOOR_KBPS = 100; + +/** Re-encode this much lower each time a size-capped variant lands over. */ +export const FIT_RETRY_STEP = 0.06; + +const NAME_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; +/** Names a cut variant's final already takes beside the cut (`<slug>.<variant>.mp4`). */ +const RESERVED = new Set(["sourced", "article", "preview", "prerail", "partial"]); + +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; + +/** + * Every reason a `render.variants` list cannot be made, as sentences (empty: + * it can). `undefined` is the default ladder. + * + * @returns {string[]} + */ +export function validateVariants(list, where = "render.variants") { + if (list === undefined) return []; + if (!Array.isArray(list)) return [`${where} must be a list of { name, height?, crf?, maxMiB?, preset? }`]; + const errors = []; + if (list.length > 12) errors.push(`${where} has ${list.length} variants (at most 12)`); + const seen = new Set(); + list.forEach((v, i) => { + const at = `${where}[${i}]`; + if (!isObj(v)) { errors.push(`${at} must be { name, height?, crf?, maxMiB?, preset? }`); return; } + for (const k of Object.keys(v)) { + if (!["name", "height", "crf", "maxMiB", "preset"].includes(k)) errors.push(`${at}.${k} is not a variant setting (name, height, crf, maxMiB, preset)`); + } + if (typeof v.name !== "string" || !NAME_RE.test(v.name)) { + errors.push(`${at}.name must be lower-case letters, digits or dashes (at most 24)`); + } else if (RESERVED.has(v.name)) { + errors.push(`${at}.name "${v.name}" is taken (${[...RESERVED].join(", ")})`); + } else if (seen.has(v.name)) errors.push(`${at}.name "${v.name}" is used twice`); + else seen.add(v.name); + if (v.name === "master" && Object.keys(v).length > 1) errors.push(`${at}: master is the build's own file -- it takes no settings`); + if (v.height !== undefined && !(Number.isInteger(v.height) && v.height % 2 === 0 && numIn(v.height, 144, 2160))) { + errors.push(`${at}.height must be an even whole number of pixels from 144 to 2160`); + } + if (v.crf !== undefined && !(Number.isInteger(v.crf) && numIn(v.crf, 0, 51))) errors.push(`${at}.crf must be a whole number from 0 to 51`); + if (v.maxMiB !== undefined && !numIn(v.maxMiB, 0.01, 4096)) errors.push(`${at}.maxMiB must be from 0.01 to 4096`); + if (v.maxMiB !== undefined && v.crf !== undefined) errors.push(`${at}: a maxMiB variant is sized by its bitrate -- it takes no crf`); + const presets = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"]; + if (v.preset !== undefined && !presets.includes(v.preset)) errors.push(`${at}.preset must be one of ${presets.join(", ")}`); + }); + return errors; +} + +/** The ladder for a render: `render.variants`, else DEFAULT_VARIANTS. */ +export function variantsOf(render) { + return Array.isArray(render?.variants) ? render.variants : DEFAULT_VARIANTS; +} + +/** A file's duration (s), picture size and bytes. */ +export async function probeOut(file) { + const { stdout } = await execFileP(FFPROBE(), [ + "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:format=duration", "-of", "json", file, + ]); + const doc = JSON.parse(stdout); + const v = doc.streams?.[0] ?? {}; + const st = await stat(file); + return { duration: Number(doc.format?.duration), width: Number(v.width), height: Number(v.height), bytes: st.size }; +} + +/** + * A size-capped variant's plan: its height, picture and sound bitrates (kb/s) + * for `maxMiB` over `seconds` of a cut `srcHeight` tall. `scale` < 1 is a + * retry's: the picture's share lowered by that much. + */ +export function fitPlan({ maxMiB, seconds, srcHeight, maxHeight = null, scale = 1 }) { + const totalKbps = (maxMiB * 1024 * 1024 * 8) / seconds / 1000; + const audio = totalKbps < 300 ? { kbps: 48, channels: 1 } : { kbps: 96, channels: 2 }; + // A container's own bytes: about 2 % of the whole at these rates. + const videoKbps = Math.max(1, Math.floor((totalKbps * 0.98 - audio.kbps) * scale)); + const cap = Math.min(srcHeight, maxHeight ?? Infinity); + const heights = FIT_HEIGHTS.filter((h) => h <= cap); + const options = heights.length ? heights : [cap - (cap % 2)]; + const floor = (h) => FIT_FLOOR_KBPS * (h / 480) ** 2; + const height = options.find((h) => videoKbps >= floor(h)) ?? options[options.length - 1]; + return { height, videoKbps, audio, totalKbps }; +} + +const scaleArgs = (height, srcHeight) => (height < srcHeight ? ["-vf", `scale=-2:${height}:flags=lanczos`] : []); + +/** One crf variant's argv: picture re-encoded at its height and quality; the sound copied. */ +export function crfArgs({ source, out, height, srcHeight, crf, preset = "medium" }) { + return [ + "-nostdin", "-v", "error", "-y", "-i", source, + "-map", "0:v:0", "-map", "0:a?", "-map_metadata", "0", "-map_chapters", "0", + ...scaleArgs(height, srcHeight), + "-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p", + "-c:a", "copy", "-movflags", "+faststart", out, + ]; +} + +/** A two-pass variant's argv for `pass` (1 or 2). */ +export function fitArgs({ source, out, plan, srcHeight, pass, logBase, preset = "medium" }) { + const common = [ + "-nostdin", "-v", "error", "-y", "-i", source, + ...scaleArgs(plan.height, srcHeight), + "-c:v", "libx264", "-preset", preset, "-b:v", `${plan.videoKbps}k`, "-pix_fmt", "yuv420p", + "-pass", String(pass), "-passlogfile", logBase, + ]; + if (pass === 1) return [...common, "-map", "0:v:0", "-an", "-f", "null", "-"]; + return [ + ...common, "-map", "0:v:0", "-map", "0:a?", "-map_metadata", "0", "-map_chapters", "0", + "-c:a", "aac", "-b:a", `${plan.audio.kbps}k`, "-ac", String(plan.audio.channels), + "-movflags", "+faststart", out, + ]; +} + +const itemOf = (name, file, p) => ({ + name, path: file, width: p.width, height: p.height, bytes: p.bytes, + kbps: Number.isFinite(p.duration) && p.duration > 0 ? Math.round((p.bytes * 8) / p.duration / 1000) : null, +}); + +/** + * Make the variants of `<outDir>/<slug>.mp4` (or `source`). `variants` is the + * ladder (validated here); `only` names the ones to make now -- the others' + * rows in variants.json are kept. Each is written under a temporary name and + * renamed, so a half-made file is never taken for one. + * + * @param {string} outDir + * @param {{ slug: string, variants?: object[], only?: string[] | null, source?: string | null, + * onLog?: (line: string) => void }} opts + * @returns {Promise<{ at: string, source: string, items: Array<{ name: string, path: string, + * width: number, height: number, bytes: number, kbps: number | null }> }>} + */ +export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS, only = null, source = null, onLog = () => {} } = {}) { + const errors = validateVariants(variants); + if (errors.length) throw new Error(errors.join("; ")); + if (!slug) throw new Error("variants: no slug"); + const src = source ?? path.join(outDir, `${slug}.mp4`); + const sp = await probeOut(src).catch(() => null); + if (!sp) throw new Error(`variants: no cut at ${src} -- build it first`); + if (only?.length) { + const unknown = only.filter((n) => !variants.some((v) => v.name === n)); + if (unknown.length) throw new Error(`variants: no variant named ${unknown.join(", ")} (${variants.map((v) => v.name).join(", ")})`); + } + const todo = variants.filter((v) => !only?.length || only.includes(v.name)); + const made = []; + const work = path.join(outDir, ".variants"); + await mkdir(work, { recursive: true }); + try { + for (const v of todo) { + if (v.name === "master") { + made.push(itemOf("master", src, sp)); + onLog(`variant master: ${path.basename(src)} (${(sp.bytes / 2 ** 20).toFixed(1)} MiB)`); + continue; + } + const out = path.join(outDir, `${slug}.${v.name}.mp4`); + const tmp = path.join(work, `${slug}.${v.name}.partial.mp4`); + if (v.maxMiB === undefined) { + const height = Math.min(v.height ?? sp.height, sp.height); + onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}…`); + await execFileP(FFMPEG(), crfArgs({ source: src, out: tmp, height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset }), { maxBuffer: 1 << 26 }); + } else { + const limit = v.maxMiB * 2 ** 20; + let scale = 1; + for (let tries = 0; ; tries += 1) { + const plan = fitPlan({ maxMiB: v.maxMiB, seconds: sp.duration, srcHeight: sp.height, maxHeight: v.height ?? null, scale }); + onLog(`variant ${v.name}: ${plan.height}p, ${plan.videoKbps} kb/s picture + ${plan.audio.kbps} kb/s ${plan.audio.channels === 1 ? "mono" : "stereo"}, two passes…`); + const logBase = path.join(work, `${slug}.${v.name}.pass`); + for (const pass of [1, 2]) { + await execFileP(FFMPEG(), fitArgs({ source: src, out: tmp, plan, srcHeight: sp.height, pass, logBase, preset: v.preset }), { maxBuffer: 1 << 26, cwd: work }); + } + const got = (await stat(tmp)).size; + if (got <= limit) break; + if (tries >= 3) { + onLog(`variant ${v.name}: still ${(got / 2 ** 20).toFixed(2)} MiB over ${v.maxMiB} after ${tries + 1} tries — kept`); + break; + } + scale *= 1 - FIT_RETRY_STEP; + onLog(`variant ${v.name}: ${(got / 2 ** 20).toFixed(2)} MiB is over ${v.maxMiB} — again ${Math.round(FIT_RETRY_STEP * 100)} % lower`); + } + } + await rename(tmp, out); + const p = await probeOut(out); + made.push(itemOf(v.name, out, p)); + onLog(`variant ${v.name}: ${path.basename(out)} ${p.width}x${p.height}, ${(p.bytes / 2 ** 20).toFixed(2)} MiB`); + } + } finally { + await rm(work, { recursive: true, force: true }); + } + // The record: this run's rows over any earlier ones of the same source, in ladder order. + let prev = null; + try { + prev = JSON.parse(await readFile(path.join(outDir, VARIANTS_FILE), "utf8")); + } catch { + prev = null; + } + const keep = prev?.source === src && Array.isArray(prev.items) ? prev.items.filter((it) => !made.some((m) => m.name === it.name)) : []; + const rank = (n) => { + const i = variants.findIndex((v) => v.name === n); + return i < 0 ? variants.length : i; + }; + const items = [...keep.filter((it) => variants.some((v) => v.name === it.name)), ...made].sort((a, b) => rank(a.name) - rank(b.name)); + const doc = { at: new Date().toISOString(), source: src, items }; + await writeFile(path.join(outDir, VARIANTS_FILE), JSON.stringify(doc, null, 2) + "\n"); + return doc; +} + +// ---- the CLI --------------------------------------------------------------- + +/** argv after the script: `<take out dir> [--slug s] [--only a,b] [--source file]`. */ +export function parseVariantArgs(argv) { + const out = { outDir: null, slug: null, only: null, source: null }; + for (let i = 0; i < argv.length; i += 1) { + const a = argv[i]; + if (a === "--slug") out.slug = argv[++i] ?? null; + else if (a === "--only") out.only = String(argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean); + else if (a === "--source") out.source = argv[++i] ?? null; + else if (a.startsWith("--")) throw new Error(`variants: unknown option ${a}`); + else if (!out.outDir) out.outDir = a; + else throw new Error(`variants: one take out dir, got ${a} too`); + } + if (!out.outDir) throw new Error("usage: variants.mjs <take out dir> [--slug s] [--only name,…] [--source file]"); + return out; +} + +async function main() { + const args = parseVariantArgs(process.argv.slice(2)); + const outDir = path.resolve(args.outDir); + // The take's manifest is beside its out dir: its slug and its ladder. + let manifest = null; + try { + manifest = JSON.parse(await readFile(path.join(path.dirname(outDir), "video.manifest.json"), "utf8")); + } catch { + manifest = null; + } + const slug = args.slug ?? manifest?.slug; + if (!slug) throw new Error(`variants: no --slug and no video.manifest.json beside ${outDir}`); + const variants = variantsOf(manifest?.render); + const run = () => encodeVariants(outDir, { + slug, variants, only: args.only, source: args.source ? path.resolve(args.source) : null, + onLog: (line) => process.stderr.write(`${line}\n`), + }); + // By a URL made from the script's own path at run time, as build-video's + // CLI loads it: never a module the umtool app's bundle traces. + const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href; + const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); + const doc = await withRenderSlot(["variants", outDir], run); + process.stdout.write(JSON.stringify(doc, null, 2) + "\n"); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + main().catch((err) => { + process.stderr.write(`${err?.message ?? err}\n`); + process.exit(1); + }); +} diff --git a/umtool/report-to-video/variants.test.mjs b/umtool/report-to-video/variants.test.mjs @@ -0,0 +1,134 @@ +// Quality variants of a finished cut (variants.mjs): the ladder validated, +// the size-capped plan, and real (tiny) encodes -- master is the build's own +// file, a crf variant is at its height, a maxMiB one lands under its size. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, 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 { + DEFAULT_VARIANTS, encodeVariants, fitPlan, parseVariantArgs, validateVariants, VARIANTS_FILE, variantsOf, +} from "./variants.mjs"; + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); + +test("validateVariants: the default ladder is valid; a bad one is refused in sentences", () => { + assert.deepEqual(validateVariants(undefined), []); + assert.deepEqual(validateVariants(DEFAULT_VARIANTS), []); + assert.deepEqual(variantsOf({}), DEFAULT_VARIANTS); + assert.deepEqual(validateVariants("x"), ["render.variants must be a list of { name, height?, crf?, maxMiB?, preset? }"]); + const errs = validateVariants([ + { name: "Big" }, { name: "article" }, { name: "a", height: 1081 }, { name: "a", crf: 60 }, + { name: "fit", maxMiB: 0 }, { name: "both", maxMiB: 8, crf: 20 }, { name: "master", crf: 20 }, { name: "p", preset: "warp" }, + { name: "q", fps: 60 }, + ]); + for (const want of [ + /\[0\]\.name must be lower-case letters/, /\[1\]\.name "article" is taken/, /\[2\]\.height must be an even whole number/, + /\[3\]\.name "a" is used twice/, /\[3\]\.crf must be a whole number from 0 to 51/, /\[4\]\.maxMiB must be from 0\.01 to 4096/, + /\[5\]: a maxMiB variant is sized by its bitrate/, /\[6\]: master is the build's own file/, /\[7\]\.preset must be one of/, + /\[8\]\.fps is not a variant setting/, + ]) assert.ok(errs.some((e) => want.test(e)), `${want} in ${errs.join("\n")}`); +}); + +test("fitPlan: the Huck cut at 24 MiB is 480p with mono sound; a short cut gets 1080p and stereo", () => { + // 20:10 at 24 MiB: ~166 kb/s in all -- under 300, so 48 kb/s mono; ~115 kb/s picture: 480p. + const huck = fitPlan({ maxMiB: 24, seconds: 1210, srcHeight: 1080 }); + assert.equal(huck.audio.kbps, 48); + assert.equal(huck.audio.channels, 1); + assert.equal(huck.height, 480); + assert.ok(huck.videoKbps > 100 && huck.videoKbps < 125, String(huck.videoKbps)); + // Two minutes at 24 MiB: ~1678 kb/s -- stereo, and enough for 1080p (≥ 506 kb/s). + const short = fitPlan({ maxMiB: 24, seconds: 120, srcHeight: 1080 }); + assert.equal(short.audio.channels, 2); + assert.equal(short.height, 1080); + // 720p when 1080p's floor is missed but 720p's (225) is met. + assert.equal(fitPlan({ maxMiB: 24, seconds: 500, srcHeight: 1080 }).height, 720); + // Never taller than the cut, or than the variant's own height. + assert.equal(fitPlan({ maxMiB: 24, seconds: 60, srcHeight: 720 }).height, 720); + assert.equal(fitPlan({ maxMiB: 24, seconds: 60, srcHeight: 1080, maxHeight: 720 }).height, 720); + assert.equal(fitPlan({ maxMiB: 1, seconds: 2, srcHeight: 180 }).height, 180); + // A retry's scale lowers the picture only. + const r = fitPlan({ maxMiB: 24, seconds: 1210, srcHeight: 1080, scale: 0.94 }); + assert.ok(r.videoKbps < huck.videoKbps && r.audio.kbps === huck.audio.kbps); +}); + +test("parseVariantArgs", () => { + assert.deepEqual(parseVariantArgs(["out", "--slug", "s", "--only", "720p, fit24"]), { outDir: "out", slug: "s", only: ["720p", "fit24"], source: null }); + assert.throws(() => parseVariantArgs([]), /usage/); + assert.throws(() => parseVariantArgs(["a", "--wat"]), /unknown option --wat/); +}); + +function cut(dir, slug) { + const out = path.join(dir, `${slug}.mp4`); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=640x360:r=30:d=3", + "-f", "lavfi", "-i", "sine=f=440:r=48000:d=3", + "-c:v", "libx264", "-preset", "ultrafast", "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ac", "2", "-b:a", "160k", "-shortest", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + return out; +} + +test("encodeVariants: master is the cut itself; a crf variant at its height; a maxMiB one under its size; the record", { skip: !have && "needs ffmpeg" }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "variants-")); + try { + const src = cut(dir, "demo"); + const variants = [ + { name: "master" }, + { name: "small", height: 180, crf: 30, preset: "ultrafast" }, + { name: "fit", maxMiB: 0.06, preset: "ultrafast" }, + ]; + const logs = []; + const doc = await encodeVariants(dir, { slug: "demo", variants, onLog: (l) => logs.push(l) }); + assert.equal(doc.source, src); + assert.deepEqual(doc.items.map((i) => i.name), ["master", "small", "fit"]); + assert.equal(doc.items[0].path, src, "master is the build's own file"); + const small = doc.items[1]; + assert.equal(small.path, path.join(dir, "demo.small.mp4")); + assert.equal(small.height, 180); + assert.equal(small.width, 320); + const fit = doc.items[2]; + assert.ok(fit.bytes <= 0.06 * 2 ** 20, `${fit.bytes} bytes over 0.06 MiB`); + assert.ok(fit.kbps > 0); + // The sound of a size-capped variant at this rate is mono. + const ch = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels", "-of", "csv=p=0", fit.path]); + assert.equal(String(ch.stdout).trim(), "1"); + assert.deepEqual(JSON.parse(readFileSync(path.join(dir, VARIANTS_FILE), "utf8")).items.map((i) => i.name), ["master", "small", "fit"]); + assert.ok(!existsSync(path.join(dir, ".variants")), "the work dir is gone"); + assert.ok(logs.some((l) => /variant fit: \d+p, \d+ kb\/s picture \+ 48 kb\/s mono, two passes/.test(l)), logs.join("\n")); + + // `only`: one remade, the others' rows kept. + const again = await encodeVariants(dir, { slug: "demo", variants, only: ["small"] }); + assert.deepEqual(again.items.map((i) => i.name), ["master", "small", "fit"]); + await assert.rejects(encodeVariants(dir, { slug: "demo", variants, only: ["huge"] }), /no variant named huge/); + await assert.rejects(encodeVariants(dir, { slug: "nope", variants }), /no cut at/); + assert.deepEqual(readdirSync(dir).filter((f) => f.endsWith(".mp4")).sort(), ["demo.fit.mp4", "demo.mp4", "demo.small.mp4"]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the CLI: the take's manifest names the slug and the ladder", { skip: !have && "needs ffmpeg" }, () => { + const take = mkdtempSync(path.join(tmpdir(), "variants-take-")); + try { + const out = path.join(take, "out"); + spawnSync("mkdir", ["-p", out]); + cut(out, "demo"); + writeFileSync(path.join(take, "video.manifest.json"), JSON.stringify({ + slug: "demo", render: { variants: [{ name: "master" }, { name: "tiny", height: 144, crf: 35, preset: "ultrafast" }] }, + })); + const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "variants.mjs"); + const r = spawnSync(process.execPath, [script, out, "--only", "tiny"], { env: { ...process.env, HEAVY: "0" }, encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + const doc = JSON.parse(r.stdout); + assert.deepEqual(doc.items.map((i) => [i.name, i.height]), [["tiny", 144]]); + assert.ok(existsSync(path.join(out, "demo.tiny.mp4"))); + } finally { + rmSync(take, { recursive: true, force: true }); + } +});