Archilyzer · Source

archilyzer

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

commit 86f940c37ac697b071412b674618be214ba04f47
parent cfdb5174de5d1b0fbb8eb1ade628dd9e2265cdbb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 17:57:21 -0500

umtool: a reel ends on an outro card, and opens on an intro its master lacks

`umtool trailer-beats <p> --reel <r> outro on|off|none|'{title,text,image,seconds}'`
ends the reel on a card (report-to-video/outro.mjs): the full video's title large
(default the reel's title, else the project's), "Full video on the channel" under
an accent rule, the site's name small in its accent, over an image of the
project's covered, blurred and darkened (else the dark ground); 3.5 s with a
0.5 s fade in from the last beat (its sound fading out), held to the end. The
card is one ImageMagick + Pango still at the take's size, kept by its key in
out/sourced/outro/. `ls` says "· outro 3.5 s" and the length against the limit
counts it (its seconds less the fade); the record names it.

A reel with `intro on` whose master has no brand intro was refused; now the
take's render.intro (else boot-dark, mark chime, site auto) is rendered for the
reel at the take's size and encode (report-to-video/reel-intro.mjs, through the
intro cache), and `intro '<render.intro JSON>'` gives a reel an intro of its
own. A reel with neither is cut exactly as before (no timebase moved, the same
graph), and a reel with no outro keeps its version.

(operator, 5 Nov: "actually I want intro in the trailer too"; "Can X trailer
with outro only be added quickly?")

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/app/api/report/trailer-beats/route.ts | 4++--
Mumtool/docs/cli.md | 4++--
Mumtool/docs/knobs.md | 8+++++---
Mumtool/docs/report-video.md | 21+++++++++++++++++++++
Mumtool/lib/report/trailerBeats.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/report/trailerBeats.test.mjs | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerBeatsCli.mjs | 50++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/report/trailerBeatsCli.test.mjs | 32++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerCli.mjs | 26++++++++++++++++++++++----
Aumtool/report-to-video/outro.mjs | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/outro.test.mjs | 191+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 2++
Aumtool/report-to-video/reel-intro.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/trailer.mjs | 129++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
15 files changed, 967 insertions(+), 39 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool: a reel can end on an outro card, and open on an intro its master does not have.** A trailer stopped on its last beat, and a reel with "open on the brand intro" was refused when the take had been rendered without one (the Mr. Obvious X trailer). `umtool trailer-beats <p> --reel <r> outro '{"title":"…","image":"promo/thumbnail.jpg"}'` (`on`, `off`, `none`) ends the reel on a card: the full video's title large (default the reel's title, else the project's), "Full video on the channel" under it (`text`), the site's name small in its accent, over the image blurred and darkened (or the dark ground), 3.5 s (`seconds`) with a 0.5 s fade in from the last beat while its sound fades out, then held to the end; `ls` says `· outro 3.5 s` and the length against the limit counts it. With `intro on` and no intro in the master, the take's `render.intro` (else the dark boot with the mark on the chime) is rendered for the reel; `intro '{"style":"boot-dark","mark":"chime","site":"anilyzer"}'` gives a reel an intro of its own. `umtool trailer --reel` cuts both in; a reel with neither is cut exactly as before. - **umtool: the background no longer changes shade between post items.** In a render, the page behind a post's card brightened at the cut from a post with a JPEG picture to a plain text post (the Mr. Obvious cut, at 37:00). ffmpeg had encoded the item with the picture in full range, every other item in limited range, and a player reads one range for the whole video. Every post item and combo badge is now encoded in limited range, so the page is the palette's background in every item; the items built full range before are rebuilt on the next render, and nothing else is. - **umtool: a report video can end on a video of the project, full frame, with its own sound.** A meme the subject posted (the Puss in Boots clip of the Mr. Obvious cut) could not be played as itself: `image` is a still and a clip is a corpus window inside the deck. A `video` timeline entry plays a project file's span (`from`, `to`; absent: the file's end) as the whole frame (`fit: contain`, pillarboxed on black, or `cover`), with NOTHING drawn over it -- no deck, header, QR, rail, counters, captions or any overlay layer, in the render and in Play. The item before it (its chrome too) fades to black and the video fades up (`enter`, 0.5 s each; `"cut"` opts out), without shortening the video; as the last entry the cut ends on its final frame (no end fade). Its sound is levelled like a clip's, with an optional bass boost before the level (`audio.bass`, dB). `umtool timeline <p> [--take <t>] add-video <src> --from 32.26 --bass 8` adds one; `set-video <id> key=value` sets its knobs. - **`posts reread --pause "@71.2=0.45"`: a pause at a time of the take.** A read whose word timings drift (a script word said as several -- "45" as "forty-five") put a word-named pause inside the next word. `@<seconds>` names the time instead; the cut is the quietest point within 0.15 s of it, kept on later re-cuts. diff --git a/umtool/app/api/report/trailer-beats/route.ts b/umtool/app/api/report/trailer-beats/route.ts @@ -43,7 +43,7 @@ export const dynamic = "force-dynamic"; // remove { index } // move { index, to } // order {} the cut's order -// settings { limit?, xfade?, intro?, title?, take? } null: the default again +// settings { limit?, xfade?, intro?, outro?, title?, take? } null: the default again (outro: true/false/{…}/null) // undo {} the reel as it was before its last write // anchor { only? } anchor beats (all, or the 0-based `only`) to `take` // `take` on add / set / anchor: the take the edit was made against -- each @@ -123,7 +123,7 @@ export async function POST(request: Request) { await orderTrailerBeats(dir, r.manifest, { token, reel }); break; case "settings": - await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro", "title", "take"].filter((k) => k in body).map((k) => [k, body[k]])), { token, reel }); + await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro", "outro", "title", "take"].filter((k) => k in body).map((k) => [k, body[k]])), { token, reel }); break; case "anchor": { if (!anchorFor) return Response.json({ error: "anchor needs the take to anchor to (take)" }, { status: 400 }); diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -65,8 +65,8 @@ Inbox cannot disagree about what is wrong with one. | `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) | | `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | | `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | -| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade and intro, written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | -| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | +| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | +| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | | `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1154,11 +1154,11 @@ written over. Three kinds (UI notes 2026-10-30, item 12), the bench's and Play's `umtool trailer <p> --take <t> --beats <p>/promo/trailer-beats.json` cuts a trailer from a finished master; the beats file is edited here, through one writer (`lib/report/trailerBeats.mjs`), which says before any encode each beat's length (a clip beat's gaps out, as the master plays it), the **running length against the platform's limit** (X 2:20 by -default; Instagram 1:30, a Short 3:00, TikTok 10:00, or seconds) with the trailer's crossfades and the brand intro -(its length from the newest built take's schedule), every beat **outside its clip's window** or naming a clip no +default; Instagram 1:30, a Short 3:00, TikTok 10:00, or seconds) with the trailer's crossfades, the brand intro +(its length from the newest built take's schedule; a reel's own intro, its own seconds) and the outro card, every beat **outside its clip's window** or naming a clip no longer in the cut, and whether the beats are in the cut's order. A beat is `{id, start, end, label?}` (source seconds of a clip) or `{at, dur}` (master seconds), numbered from 1 as `umtool trailer` numbers them. The file keeps -its shape (an array, until a setting makes it `{limit, xfade, intro, beats}`, which `--beats` reads too) and its +its shape (an array, until a setting makes it `{limit, xfade, intro, outro, beats}`, which `--beats` reads too) and its indent; one that does not parse is never written over; a write over a newer file is a 409. The lengths are the beats as written: `umtool trailer` then moves each clip beat's edges into the nearest pauses (up to 1 s each way, said per edge; `--no-snap` keeps them), so a trailer can come out a few tenths of a second per beat longer than the running @@ -1171,6 +1171,8 @@ length here ([report-video.md](report-video.md#trailer-from-the-master)). | a beat's seconds; pull it inside its clip | the row's from–to; **fit to clip** | `umtool trailer-beats <p> set <n> <from>-<to> [--label L]` | `{op: "set", index, patch}` | | move, remove, the cut's order | ↑ ↓ **remove**; **Order by the cut** | `move <n> --to <m>` · `remove <n>` · `order` | `{op: "move", index, to}` · `{op: "remove", index}` · `{op: "order"}` | | the limit, the crossfade, the intro | **limit** (a platform, or seconds), **crossfade**, **open on the brand intro** | `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok\|default>` · `xfade <s>` · `intro on\|off` | `{op: "settings", limit?, xfade?, intro?}` | +| the reel's own intro (render.intro's shape -- style, mark, seconds, site…): rendered for the reel at the take's size and encode, whatever the master opens on; `intro on` with a master that has no brand intro renders the take's `render.intro` for it, else the default (`boot-dark`, mark `chime`, site `auto`) -- no longer refused | -- | `intro '{"style":"boot-dark","mark":"chime","seconds":4.75,"site":"anilyzer"}'` | `{op: "settings", intro: {…}}` | +| the **outro card** the reel ends on: the full video's title large (default the reel's `title`, else the project's), a call to action (default "Full video on the channel"), an image of the project's under it blurred and darkened (none: the dark ground), the site's name small (the intro's site, else the cut's `siteOrigin`'s, else Archilyzer) in its accent; `seconds` 1.5–10 (3.5), its 0.5 s fade in from the last beat included (the beat's sound fades out under it, silence after); the reel holds the card to its end; counted in the length (its seconds less the fade; `ls` says `· outro 3.5 s`) | -- | `outro on\|off\|none` · `outro '{"title":"…","text":"…","image":"promo/thumb.jpg","seconds":3.5}'` (merges; a key `null` drops it; `off` keeps the words) | `{op: "settings", outro: true\|false\|{…}\|null}` | | the walk's ★ clips | **★ from the walk**: each **Add** | `umtool trailer-beats <p> candidates [--add]` | `GET` (`candidates`) | | undo the last write (every write is an undo point) | **Undo** (the beats); **Undo last write** / `U` (the reel's walk) | `umtool trailer-beats <p> undo` | `{op: "undo"}` | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -2548,6 +2548,27 @@ it uses the reel's pinned take, else the take it was last cut from, else the lat finished master, and says which. `umtool trailer-beats <project> --reel <name> …` edits one, and `reels` / `new-reel <name> [--from <reel>]` list and make them. +**A reel's intro.** With the reel's `intro` on, the cut opens on the master's brand intro when the +master has one. When it has none it is no longer refused: the take's `render.intro` is rendered for +the reel (at the take's size, fps and encode, through the intro's cache -- `report-to-video/reel-intro.mjs`), +else the default `{"style": "boot-dark", "mark": "chime", "site": "auto"}`. The reel's `intro` may also +be an intro of its own, render.intro's shape (`trailer-beats <p> --reel R intro '{"style":"boot-dark", +"mark":"chime","seconds":4.75,"site":"anilyzer"}'`), rendered for it whatever the master opens on. It +joins the first beat with the reel's crossfade; the plan and the record name it (`intro: …`). + +**The outro card** (`report-to-video/outro.mjs`). A reel may end on a card: the full video's title +large, a call to action under an accent rule ("Full video on the channel" by default), the site's name +small at the foot (the intro's site -- "Anilyzer", its lead heavy, in its accent -- else the site of the +cut's `siteOrigin`, else Archilyzer), over the dark ground or over an image of the project's (the +thumbnail art), covered, blurred and darkened so the words read. The setting is the reel's `outro`: +`{on, title?, text?, image?, seconds?}` (`trailer-beats … outro on|off|none|'{…}'`); `title` defaults to +the reel's title, else the project's; `seconds` (1.5–10, 3.5 by default) includes the card's 0.5 s fade +in from the last beat, over which the beat's sound fades out; the reel then holds the card, silent, to +its end. The reel's length counts it (its seconds less the fade). The card is one still drawn by +ImageMagick + Pango in the vendored faces at the take's size, kept in `out/sourced/outro/` by its key +(the words, the size, the image's bytes, the brand); the record names it (`outro`). A reel with no outro +is cut exactly as before. + The Trailer page (`/projects/<p>/trailer?reel=<name>`) plays and walks a reel from a take's rendered master, as the cut's Play and walk do for the cut. Each beat is mapped by the same `planTrailer` the cut uses (`lib/report/reelPlay.mjs`), with the edges as written: the cut then diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -38,6 +38,8 @@ import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from import path from "node:path"; import { gappedLength, gapsOf } from "umtool-report-to-video/gaps"; import { TRAILER_XFADE_DEFAULT, TrailerError, beatGaps, parseBeats } from "umtool-report-to-video/trailer"; +import { normalizeOutro, outroAdds, outroErrors, resolveOutro } from "umtool-report-to-video/outro"; +import { INTRO_SECONDS, introErrors } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { indentOf } from "./patchMarkers.mjs"; import { appendReelHistory } from "./reelHistory.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; @@ -92,7 +94,8 @@ const undoFileOf = (dir, reel = DEFAULT_REEL) => { return path.join(dir, path.dirname(rel), `.${path.basename(rel)}.undo.json`); }; -/** @typedef {{ limit?: number, xfade?: number, intro?: boolean, title?: string, take?: string }} TrailerSettings */ +/** @typedef {{ on: boolean, title?: string, text?: string, image?: string, seconds?: number }} OutroSetting */ +/** @typedef {{ limit?: number, xfade?: number, intro?: boolean | Record<string, any>, outro?: OutroSetting, title?: string, take?: string }} TrailerSettings */ /** @typedef {{ token?: string | null, reel?: string }} BeatsWriteOpts */ /** The file's mtime, the token a writer hands back; null when there is no file. */ @@ -156,6 +159,10 @@ export async function readTrailerBeats(dir, { reel = DEFAULT_REEL } = {}) { if (typeof doc.limit === "number") settings.limit = doc.limit; if (typeof doc.xfade === "number") settings.xfade = doc.xfade; if (typeof doc.intro === "boolean") settings.intro = doc.intro; + // The reel's own intro (render.intro's shape; report-to-video/reel-intro.mjs), when it validates. + else if (isObj(doc.intro) && !introErrors(doc.intro).length) settings.intro = doc.intro; + // The outro card (report-to-video/outro.mjs), when it validates. + if (doc.outro !== undefined && doc.outro !== null && !outroErrors(doc.outro).length) settings.outro = /** @type {OutroSetting} */ (normalizeOutro(doc.outro)); if (typeof doc.title === "string" && doc.title.trim()) settings.title = doc.title; if (typeof doc.take === "string" && TAKE_ID.test(doc.take)) settings.take = doc.take; } @@ -163,7 +170,7 @@ export async function readTrailerBeats(dir, { reel = DEFAULT_REEL } = {}) { } const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; -const SETTING_KEYS = ["limit", "xfade", "intro", "title", "take"]; +const SETTING_KEYS = ["limit", "xfade", "intro", "outro", "title", "take"]; /** The reel's undo points, oldest first: `{ at, what, text }` (`text` null: the file did not exist). */ export async function readReelUndo(dir, { reel = DEFAULT_REEL } = {}) { @@ -470,7 +477,10 @@ export async function orderTrailerBeats(dir, manifest, { token = null, reel = DE /** * The trailer's settings: `limit` (seconds, the platform's), `xfade` (the - * trailer's crossfade), `intro` (opens on the brand intro), `title` (the + * trailer's crossfade), `intro` (opens on the brand intro: `true`, or an + * intro of the reel's own, render.intro's shape), `outro` (ends on the card: + * `true`/`false` turn it on or off and keep its words, an object merges its + * keys -- a key null drops it -- and turns it on), `title` (the * reel's name for a person), `take` (the take it is cut from, pinned). null * removes one (its default again). * @param {string} dir @@ -478,8 +488,14 @@ export async function orderTrailerBeats(dir, manifest, { token = null, reel = DE * @param {BeatsWriteOpts} [opts] */ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFAULT_REEL } = {}) { + if (isObj(patch) && isObj(patch.outro) && typeof patch.outro.image === "string") { + const img = patch.outro.image.trim().replace(/^\.\//, ""); + const errors = outroErrors({ image: img }); + if (errors.length) throw new Error(errors.join("; ")); + if (!(await stat(path.join(dir, img)).then((st) => st.isFile(), () => false))) throw new Error(`outro.image ${img} is not a file of the project`); + } return beatsWrite(dir, token, (_beats, settings) => { - if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro?, title?, take? }"); + if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro?, outro?, title?, take? }"); for (const k of ["limit", "xfade"]) { if (patch[k] === undefined) continue; if (patch[k] === null || patch[k] === "") { @@ -494,7 +510,15 @@ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFA } if (patch.intro !== undefined) { if (patch.intro === null) delete settings.intro; - else settings.intro = patch.intro === true; + else if (isObj(patch.intro)) { + const errors = introErrors(patch.intro); + if (errors.length) throw new Error(`the reel's intro: ${errors.join("; ")}`); + settings.intro = patch.intro; + } else settings.intro = patch.intro === true; + } + if (patch.outro !== undefined) { + if (patch.outro === null) delete settings.outro; + else settings.outro = /** @type {OutroSetting} */ (mergeOutro(settings.outro, patch.outro)); } if (patch.title !== undefined) { const t = typeof patch.title === "string" ? patch.title.trim().slice(0, 120) : ""; @@ -511,6 +535,28 @@ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFA } /** + * The outro setting after a patch: `true`/`false` turn it on or off (its words + * kept), an object merges into it (a key null drops it) and turns it on unless + * it says `on: false`. Refused by name (outro.mjs outroErrors). + * + * @param {OutroSetting | undefined} current + * @param {unknown} patch + */ +export function mergeOutro(current, patch) { + const base = isObj(current) ? { ...current } : { on: false }; + if (patch === true || patch === false) return normalizeOutro({ ...base, on: patch }); + if (!isObj(patch)) throw new Error("outro is on|off or {title?, text?, image?, seconds?}"); + /** @type {Record<string, any>} */ + const next = { ...base, on: true }; + for (const [k, v] of Object.entries(patch)) { + if (v === null || v === "") delete next[k]; + else next[k] = v; + } + if (patch.on === undefined) next.on = true; + return normalizeOutro(next); +} + +/** * A reel's VERSION as its cut sees it: a fingerprint of what the cut reads * (each beat's clip and seconds and gaps, the crossfade, the intro) -- not a * verdict, a label or an anchor, which change nothing cut. Named in a cut's @@ -521,7 +567,8 @@ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFA export function reelVersion(doc) { const beats = (doc?.beats ?? []).map((b) => (isObj(b) ? [b.id ?? null, b.start ?? b.at ?? null, b.end ?? b.dur ?? null, b.gaps ?? null] : b)); const s = doc?.settings ?? {}; - return createHash("sha256").update(JSON.stringify({ beats, xfade: s.xfade ?? null, intro: s.intro ?? null })).digest("hex").slice(0, 16); + // The outro only when it is set: a reel without one keeps the version it had. + return createHash("sha256").update(JSON.stringify({ beats, xfade: s.xfade ?? null, intro: s.intro ?? null, ...(s.outro ? { outro: s.outro } : {}) })).digest("hex").slice(0, 16); } /** Spans merged where they touch or overlap, sorted. */ @@ -568,7 +615,10 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT const settings = doc.settings ?? {}; const limit = typeof settings.limit === "number" ? settings.limit : TRAILER_LIMIT_DEFAULT; const xfade = typeof settings.xfade === "number" ? settings.xfade : TRAILER_XFADE_DEFAULT; - const intro = settings.intro === true; + const intro = settings.intro === true || isObj(settings.intro); + // The reel's own intro is its own length; the master's is the built take's (null: not known yet). + if (isObj(settings.intro)) introSeconds = Number.isFinite(settings.intro.seconds) ? Number(settings.intro.seconds) : INTRO_SECONDS; + const outro = resolveOutro(settings.outro, { reelTitle: typeof settings.title === "string" ? settings.title : null, projectTitle: typeof manifest?.title === "string" ? manifest.title : null }); const tl = manifest?.timeline ?? []; const order = cutOrder(manifest); const model = sectionModel(manifest); @@ -626,7 +676,7 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT problems, }; }); - const total = r2(sum - xfade * Math.max(0, pieces - 1)); + const total = r2(sum - xfade * Math.max(0, pieces - 1) + (outro ? outroAdds(outro.seconds) : 0)); return { reel: reel ?? DEFAULT_REEL, file: reelFileOf(reel), @@ -637,6 +687,10 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT xfade, intro, introSeconds: intro ? (Number.isFinite(introSeconds) ? Number(introSeconds) : null) : null, + introOwn: isObj(settings.intro) ? settings.intro : null, + // The card the reel ends on (its words with the defaults), and the setting as stored (off keeps its words). + outro, + outroSetting: settings.outro ?? null, total, remaining: r2(limit - total), over: total >= limit, diff --git a/umtool/lib/report/trailerBeats.test.mjs b/umtool/lib/report/trailerBeats.test.mjs @@ -249,3 +249,56 @@ test("a beat's gaps (lane/reel-bench): written as a list through the one writer, await rm(dir, { recursive: true, force: true }); } }); + +test("the outro: on/off keeps its words, an object merges (null drops a key), the image must be the project's; the view counts it", async () => { + const dir = await project({ beats: [{ id: "a", start: 12, end: 18 }], limit: 20, title: "Reel" }); + try { + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "promo", "thumb.jpg"), "jpg"); + await setTrailerSettings(dir, { outro: true }); + let doc = await readTrailerBeats(dir); + assert.deepEqual(doc.settings.outro, { on: true }); + await setTrailerSettings(dir, { outro: { title: "Full title", image: "promo/thumb.jpg", seconds: 4 } }); + await setTrailerSettings(dir, { outro: false }); + doc = await readTrailerBeats(dir); + assert.deepEqual(doc.settings.outro, { on: false, title: "Full title", image: "promo/thumb.jpg", seconds: 4 }); + assert.equal(trailerView(manifest(), doc).outro, null); + await setTrailerSettings(dir, { outro: { seconds: null } }); + doc = await readTrailerBeats(dir); + assert.deepEqual(doc.settings.outro, { on: true, title: "Full title", image: "promo/thumb.jpg" }); + const v = trailerView(manifest(), doc); + // 6 s of beat, then the card's 3.5 s less its 0.5 s fade + assert.equal(v.total, 9); + assert.deepEqual(v.outro, { title: "Full title", text: "Full video on the channel", image: "promo/thumb.jpg", seconds: 3.5 }); + await assert.rejects(setTrailerSettings(dir, { outro: { image: "promo/none.jpg" } }), /not a file of the project/); + await assert.rejects(setTrailerSettings(dir, { outro: { seconds: 40 } }), /outro\.seconds/); + await setTrailerSettings(dir, { outro: null }); + doc = await readTrailerBeats(dir); + assert.equal(doc.settings.outro, undefined); + assert.equal(JSON.parse(await fileOf(dir)).outro, undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the reel's own intro: render.intro's shape, its seconds counted; a reel with no outro keeps its version", async () => { + const { reelVersion } = await import("./trailerBeats.mjs"); + const dir = await project([{ id: "a", start: 12, end: 18 }]); + try { + await setTrailerSettings(dir, { intro: { style: "boot-dark", mark: "chime", seconds: 4.75, site: "anilyzer" } }); + const doc = await readTrailerBeats(dir); + assert.deepEqual(doc.settings.intro, { style: "boot-dark", mark: "chime", seconds: 4.75, site: "anilyzer" }); + const v = trailerView(manifest(), doc); + assert.equal(v.introSeconds, 4.75); + assert.equal(v.total, Number((4.75 + 6 - 0.3).toFixed(2))); + await assert.rejects(setTrailerSettings(dir, { intro: { style: "nope" } }), /not an intro style/); + const base = { beats: [{ id: "a", start: 1, end: 2 }], settings: { xfade: 0.3 } }; + // the version as it was computed before the outro: { beats, xfade, intro } only + const { createHash } = await import("node:crypto"); + const before = createHash("sha256").update(JSON.stringify({ beats: [["a", 1, 2, null]], xfade: 0.3, intro: null })).digest("hex").slice(0, 16); + assert.equal(reelVersion(base), before); + assert.notEqual(reelVersion({ ...base, settings: { xfade: 0.3, outro: { on: true } } }), reelVersion(base)); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerBeatsCli.mjs b/umtool/lib/report/trailerBeatsCli.mjs @@ -50,7 +50,13 @@ export const TRAILER_BEATS_USAGE = [ " umtool trailer-beats <project> gap <n> add <from>-<to> | remove <second> | clear", " seconds cut out of beat n's middle (a clip's gap rule): it plays as one beat of jump cuts", " umtool trailer-beats <project> remove <n> | move <n> --to <m> | order (the cut's order)", - ` umtool trailer-beats <project> limit <seconds|m:ss|${TRAILER_LIMITS.map((l) => l.id).join("|")}> | xfade <s> | intro on|off`, + ` umtool trailer-beats <project> limit <seconds|m:ss|${TRAILER_LIMITS.map((l) => l.id).join("|")}> | xfade <s> | intro on|off|'<render.intro JSON>'`, + " intro on: the master's brand intro (one rendered for the reel when the master has none);", + " a JSON intro ({\"style\":\"boot-dark\",\"mark\":\"chime\",\"site\":\"anilyzer\"}): the reel's own, rendered for it", + " umtool trailer-beats <project> outro on|off|none|'{\"title\":…,\"text\":…,\"image\":\"promo/x.jpg\",\"seconds\":3.5}'", + " the card the reel ends on: the title (default the reel's title, else the project's), the call", + " to action (default \"Full video on the channel\"), an image of the project's under it, its seconds", + " (3.5, the fade in from the last beat included); a JSON key null drops it; none removes the outro", " umtool trailer-beats <project> candidates [--add] the walk's ★ clips not yet beats (--add: all of them)", ` umtool trailer-beats <project> verdict <n> ${BEAT_VERDICTS.join("|")}|clear the walk's word on beat n`, " umtool trailer-beats <project> title <text>|none | take <take>|none the reel's name, the take it is cut from", @@ -119,9 +125,12 @@ export function viewLines(v) { const flag = r.problems.length ? ` ! ${r.problems.join("; ")}` : ""; lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${gaps}${flag}`); } + if (v.outro) lines.push(` + outro card ${`${Number(v.outro.seconds).toFixed(2)}s`.padStart(8)} "${v.outro.title || "(no title)"}" · "${v.outro.text}"${v.outro.image ? ` · over ${v.outro.image}` : ""}`); + else if (v.outroSetting) lines.push(" outro off (its words kept: `outro on`)"); lines.push( `${v.rows.length} beat(s): ${clockOf(v.total)} of ${clockOf(v.limit)}${v.over ? ` — OVER by ${(v.total - v.limit).toFixed(1)} s` : ` (${v.remaining.toFixed(1)} s to spare)`}` + - ` · crossfade ${v.xfade} s${v.intro ? ` · intro ${v.introSeconds ?? "?"} s${v.introSeconds === null ? " (unknown until a take is built)" : ""}` : ""}` + + ` · crossfade ${v.xfade} s${v.intro ? ` · intro ${v.introSeconds ?? "?"} s${v.introSeconds === null ? " (unknown until a take is built)" : ""}${v.introOwn ? " (the reel's own)" : ""}` : ""}` + + `${v.outro ? ` · outro ${v.outro.seconds} s` : ""}` + `${v.outside ? ` · ${v.outside} beat(s) to fix` : ""}${v.inOrder ? "" : " · not in the cut's order (`order`)"}`, ); return lines; @@ -234,11 +243,40 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) await setTrailerSettings(project.dir, { xfade: rest[0] === "default" ? null : Number(rest[0]) }, { token, reel }); did = "crossfade set"; break; - case "intro": - if (!["on", "off"].includes(rest[0])) throw new CliError("intro on|off"); - await setTrailerSettings(project.dir, { intro: rest[0] === "on" }, { token, reel }); - did = `intro ${rest[0]}`; + case "intro": { + const arg = rest.join(" ").trim(); + if (arg.startsWith("{")) { + let spec; + try { + spec = JSON.parse(arg); + } catch (e) { + throw new CliError(`intro '<JSON>': ${e instanceof Error ? e.message : e}`); + } + await setTrailerSettings(project.dir, { intro: spec }, { token, reel }); + did = `intro: the reel's own (${spec.style ?? "?"}${spec.site ? `, site ${typeof spec.site === "string" ? spec.site : spec.site?.name}` : ""})`; + break; + } + if (!["on", "off"].includes(arg)) throw new CliError("intro on|off|'<render.intro JSON>'"); + await setTrailerSettings(project.dir, { intro: arg === "on" }, { token, reel }); + did = `intro ${arg}`; + break; + } + case "outro": { + const arg = rest.join(" ").trim(); + let patch; + if (arg === "on" || arg === "off") patch = arg === "on"; + else if (arg === "none") patch = null; + else if (arg.startsWith("{")) { + try { + patch = JSON.parse(arg); + } catch (e) { + throw new CliError(`outro '<JSON>': ${e instanceof Error ? e.message : e}`); + } + } else throw new CliError("outro on|off|none|'{\"title\":…,\"text\":…,\"image\":…,\"seconds\":…}'"); + await setTrailerSettings(project.dir, { outro: patch }, { token, reel }); + did = patch === null ? "outro removed" : patch === false ? "outro off" : "outro on"; break; + } case "title": { const t = rest.join(" ").trim(); if (!t) throw new CliError("title <text>|none"); diff --git a/umtool/lib/report/trailerBeatsCli.test.mjs b/umtool/lib/report/trailerBeatsCli.test.mjs @@ -87,3 +87,35 @@ test("status / anchor / clamp: a reel anchored to one take, read against another await rm(r, { recursive: true, force: true }); } }); + +test("outro on|off|none|JSON and intro JSON: written through the writer; ls says the card and counts it", async () => { + const { r, dir } = await root(); + const out = []; + const err = []; + const run = (...a) => trailerBeatsCommand(["p1", ...a], { root: r, out: (s) => out.push(s), err: (s) => err.push(s) }); + try { + await writeFile(path.join(dir, "promo", "thumb.jpg"), "jpg"); + assert.equal(await run("outro", '{"title":"The Full Title","image":"promo/thumb.jpg"}'), 0, err.join("\n")); + assert.match(out.join("\n"), /outro on/); + assert.match(out.join("\n"), /outro card {4}3\.50s {2}"The Full Title" · "Full video on the channel" · over promo\/thumb\.jpg/); + assert.match(out.join("\n"), /· outro 3\.5 s/); + out.length = 0; + assert.equal(await run("outro", "off"), 0); + assert.match(out.join("\n"), /outro off \(its words kept/); + assert.doesNotMatch(out.join("\n"), /· outro 3\.5 s/); + assert.equal(await run("outro", "on"), 0); + const doc = () => readFile(path.join(dir, "promo", "trailer-beats.json"), "utf8").then(JSON.parse); + assert.deepEqual((await doc()).outro, { on: true, title: "The Full Title", image: "promo/thumb.jpg" }); + assert.equal(await run("outro", "none"), 0); + assert.equal((await doc()).outro, undefined); + assert.equal(await run("outro", "maybe"), 2); + assert.equal(await run("outro", '{"seconds":99}'), 1); + assert.match(err.join("\n"), /outro\.seconds/); + out.length = 0; + assert.equal(await run("intro", '{"style":"boot-dark","mark":"chime","seconds":4.75}'), 0, err.join("\n")); + assert.match(out.join("\n"), /intro 4\.75 s \(the reel's own\)/); + assert.equal((await doc()).intro.style, "boot-dark"); + } finally { + await rm(r, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -6,7 +6,7 @@ // [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json] // umtool trailer <project> --reel <name> [--take <t>] [...] a beat reel (promo/<name>-beats.json) with its own settings // umtool trailer <project> --candidates [--json] the walk's ★ clips as beats -import { readFile } from "node:fs/promises"; +import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; @@ -23,6 +23,9 @@ import { makeTrailer, parseBeats, } from "umtool-report-to-video/trailer"; +import { resolveOutro } from "umtool-report-to-video/outro"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); export const TRAILER_USAGE = [ "usage: umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON)", @@ -41,8 +44,9 @@ export const TRAILER_USAGE = [ "--dry-run prints the mapping and writes nothing.", "", "umtool trailer <project> --reel <name> [--take <t>] [--intro] [--xfade S] [...]: a BEAT REEL -- the beats of", - "promo/<name>-beats.json (the reel `trailer` is promo/trailer-beats.json), with that file's own intro and", - "crossfade unless a flag says otherwise, written to takes/<t>/out/<slug>.<name>.mp4 (the trailer reel:", + "promo/<name>-beats.json (the reel `trailer` is promo/trailer-beats.json), with that file's own intro, outro card", + "and crossfade unless a flag says otherwise (an intro the master lacks, or the reel's own, is rendered for it;", + "the outro card fades in from the last beat and holds), written to takes/<t>/out/<slug>.<name>.mp4 (the trailer reel:", "<slug>.trailer.mp4). With no --take: the reel's pinned take, else the take it was last cut from, else the", "latest take with a finished master (said). The Trailer page's Cut the trailer runs exactly this.", "", @@ -202,11 +206,22 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c } } else beats = await beatsOf(p); const takeDir = path.join(takesDirOf(r.project.dir), take); + // The reel's outro card (report-to-video/outro.mjs): its words with the defaults, its image a file of the project's. + let outro = null; + const o = resolveOutro(reelSettings.outro, { reelTitle: reelSettings.title ?? null, projectTitle: (await readManifest(r.project.dir).catch(() => null))?.title ?? null }); + if (o) { + if (!o.title) throw new CliError(`the reel ${reel}'s outro has no title: give it one (\`umtool trailer-beats ${r.project.id} --reel ${reel} outro '{"title":"…"}'\`)`); + const imageFile = o.image ? path.join(r.project.dir, o.image) : null; + if (imageFile && !(await stat(imageFile).then((st) => st.isFile(), () => false))) throw new CliError(`the reel ${reel}'s outro image ${o.image} is not a file of ${r.project.id}`); + outro = { ...o, imageFile }; + } const slotFor = deps.slot ?? (await realSlot()); const res = await makeTrailer({ takeDir, beats, intro: p.has("--intro") || reelSettings.intro === true, + introSpec: isObj(reelSettings.intro) ? reelSettings.intro : null, + outro, finale: p.has("--finale") ? seconds(p, "--finale", null) : null, xfade: seconds(p, "--xfade", typeof reelSettings.xfade === "number" ? reelSettings.xfade : TRAILER_XFADE_DEFAULT), out: outArg, @@ -216,6 +231,9 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c ...(deps.measure ? { measure: deps.measure } : {}), ...(deps.run ? { run: deps.run } : {}), ...(deps.probe ? { probe: deps.probe } : {}), + ...(deps.makeIntro ? { makeIntro: deps.makeIntro } : {}), + ...(deps.makeOutro ? { makeOutro: deps.makeOutro } : {}), + ...(deps.sitesDir ? { sitesDir: deps.sitesDir } : {}), slot: (fn) => { if (!json) err(`trailer: encoding ${res0(beats)} in the heavy slot …`); return slotFor(["umtool", "trailer", r.project.id, ...(reel ? ["--reel", reel] : []), "--take", take])(fn); @@ -225,7 +243,7 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c log(JSON.stringify({ project: r.project.id, ...(reel ? { reel } : {}), take, out: res.dryRun ? null : res.outPath, record: res.dryRun ? null : res.recordPath, wouldWrite: res.dryRun ? res.outPath : undefined, - seconds: res.plan.total, encodeSeconds: res.encodeSeconds, pieces: res.plan.pieces, notes: res.plan.notes, + seconds: res.plan.total, encodeSeconds: res.encodeSeconds, pieces: res.plan.pieces, ...(res.plan.outro ? { outro: res.record.outro } : {}), notes: res.plan.notes, }, null, 2)); return 0; } diff --git a/umtool/report-to-video/outro.mjs b/umtool/report-to-video/outro.mjs @@ -0,0 +1,303 @@ +// THE REEL'S OUTRO CARD (operator, 5 Nov: "Maybe the trailer gets a bespoke outro?"). +// +// A reel (a beats file, lib/report/trailerBeats.mjs) may end on a card: the +// full video's title large, a short call to action ("Full video on the +// channel"), the site's name small (the intro's site -- "Anilyzer"), over the +// ground or over an image of the project's (the thumbnail art, blurred and +// darkened so the words read). The card fades in from the last beat over +// OUTRO_FADE seconds while the beat's sound fades out; the reel then holds the +// card, in silence, to its end. +// +// The reel's setting (`outro` in promo/<reel>-beats.json): +// +// { "on": true, "title": "…", "text": "…", "image": "promo/thumb.jpg", "seconds": 3.5 } +// +// every key but `on` optional: `title` defaults to the reel's title, else the +// project's; `text` to OUTRO_TEXT_DEFAULT; `image` to none; `seconds` (the +// card's length, its fade-in included) to OUTRO_SECONDS_DEFAULT. +// +// The card is one still, drawn by ImageMagick + Pango in the vendored faces +// (Archivo, IBM Plex Sans; fonts/fonts.conf), at the cut's size: 16:9 or 9:16, +// laid out by outroLayout -- inside the platform's safe area on a vertical +// (Shorts: the top 8 %, the bottom 20 % and the right 12 % carry the player's +// own buttons and text). Drawn once per key, beside the reel's cut. +// +// Plain ESM: the CLI runs it under bare node. + +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { access, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; + +import { FONTCONFIG_FILE } from "./brand.mjs"; + +const execFileP = promisify(execFile); +const exists = (p) => access(p).then(() => true, () => false); + +/** The card's length, its fade-in included. */ +export const OUTRO_SECONDS_DEFAULT = 3.5; +export const OUTRO_SECONDS_MIN = 1.5; +export const OUTRO_SECONDS_MAX = 10; +/** The fade from the last beat into the card (its picture; the beat's sound fades out over it). */ +export const OUTRO_FADE = 0.5; +/** The call to action under the title. */ +export const OUTRO_TEXT_DEFAULT = "Full video on the channel"; +/** The setting's keys. */ +export const OUTRO_KEYS = Object.freeze(["on", "title", "text", "image", "seconds"]); +const TITLE_MAX = 160; +const TEXT_MAX = 120; +const IMAGE_EXT = /\.(jpe?g|png|webp)$/i; + +/** The vertical's safe area, as fractions of the frame (YouTube Shorts' overlays). */ +export const VERTICAL_SAFE = Object.freeze({ top: 0.08, bottom: 0.2, right: 0.12, left: 0.12 }); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** + * Each thing wrong with an outro setting, by name ([] when it is fine). + * `true`/`false` are on/off with every default; an object carries the keys. + * + * @param {unknown} v + * @returns {string[]} + */ +export function outroErrors(v) { + if (v === undefined || v === null || v === true || v === false) return []; + if (!isObj(v)) return [`outro is on|off or {${OUTRO_KEYS.join(", ")}}`]; + const o = /** @type {Record<string, unknown>} */ (v); + const errors = []; + for (const k of Object.keys(o)) if (!OUTRO_KEYS.includes(k)) errors.push(`outro.${k} is not a key (${OUTRO_KEYS.join(", ")})`); + if (o.on !== undefined && typeof o.on !== "boolean") errors.push("outro.on is true or false"); + if (o.title !== undefined && (typeof o.title !== "string" || o.title.length > TITLE_MAX)) errors.push(`outro.title is text (up to ${TITLE_MAX} characters)`); + if (o.text !== undefined && (typeof o.text !== "string" || o.text.length > TEXT_MAX)) errors.push(`outro.text is text (up to ${TEXT_MAX} characters)`); + if (o.image !== undefined) { + const s = o.image; + if (typeof s !== "string" || !s.trim() || path.isAbsolute(s) || s.split(/[\\/]/).includes("..") || !IMAGE_EXT.test(s)) { + errors.push("outro.image is a .jpg, .png or .webp file of the project's, by its path inside the project (e.g. promo/thumbnail.jpg)"); + } + } + if (o.seconds !== undefined && !(typeof o.seconds === "number" && o.seconds >= OUTRO_SECONDS_MIN && o.seconds <= OUTRO_SECONDS_MAX)) { + errors.push(`outro.seconds is ${OUTRO_SECONDS_MIN}–${OUTRO_SECONDS_MAX}`); + } + return errors; +} + +/** + * The setting as stored: `{ on, ...keys }` (a trimmed title or text; an empty + * one dropped). Refused by name when it does not validate. + * @param {unknown} v + * @returns {{ on: boolean, title?: string, text?: string, image?: string, seconds?: number } | null} + */ +export function normalizeOutro(v) { + const errors = outroErrors(v); + if (errors.length) throw new Error(errors.join("; ")); + if (v === undefined || v === null) return null; + if (v === true || v === false) return { on: v }; + const o = /** @type {Record<string, any>} */ (v); + const out = { on: o.on !== false }; + for (const k of ["title", "text"]) if (typeof o[k] === "string" && o[k].trim()) out[k] = o[k].trim().replace(/\s+/g, " "); + if (typeof o.image === "string") out.image = o.image.trim().replace(/^\.\//, ""); + if (typeof o.seconds === "number") out.seconds = Number(o.seconds.toFixed(2)); + return out; +} + +/** Is the outro on? */ +export const outroOn = (v) => v === true || (isObj(v) && /** @type {any} */ (v).on !== false); + +/** + * The card's words and length, with the defaults: null when the outro is off. + * @param {unknown} setting the reel's `outro` + * @param {{ reelTitle?: string | null, projectTitle?: string | null }} [o] + */ +export function resolveOutro(setting, { reelTitle = null, projectTitle = null } = {}) { + if (!outroOn(setting)) return null; + const s = setting === true ? {} : /** @type {Record<string, any>} */ (setting); + const title = (typeof s.title === "string" && s.title.trim()) || (reelTitle && reelTitle.trim()) || (projectTitle && projectTitle.trim()) || ""; + return { + title, + text: typeof s.text === "string" && s.text.trim() ? s.text.trim() : OUTRO_TEXT_DEFAULT, + image: typeof s.image === "string" ? s.image : null, + seconds: typeof s.seconds === "number" ? s.seconds : OUTRO_SECONDS_DEFAULT, + }; +} + +/** What the outro adds to a reel's length: its seconds less the fade it overlaps the last beat by. */ +export function outroAdds(seconds) { + return Number.isFinite(seconds) && seconds > 0 ? Math.max(0, seconds - OUTRO_FADE) : 0; +} + +/** + * Where the card's parts go, in px: the content box (inside the safe area on + * a vertical), the title's wrap width and size, the call to action's size, + * the brand line's size and baseline area. Pure. + * + * @param {{ width: number, height: number }} size + */ +export function outroLayout({ width: W, height: H }) { + const vertical = H > W; + if (vertical) { + const box = { + x0: Math.round(W * VERTICAL_SAFE.left), x1: Math.round(W * (1 - VERTICAL_SAFE.right)), + y0: Math.round(H * VERTICAL_SAFE.top), y1: Math.round(H * (1 - VERTICAL_SAFE.bottom)), + }; + const u = W / 1080; + return { + vertical, box, + titlePx: [92, 80, 70, 62, 54].map((p) => Math.round(p * u)), titleLines: 5, + ctaPx: Math.round(46 * u), brandPx: Math.round(44 * u), + gap: Math.round(44 * u), rule: { w: Math.round(110 * u), h: Math.max(2, Math.round(6 * u)) }, + // The brand sits at the box's foot; the title and the call to action centre in what is above it. + brandRoom: Math.round(150 * u), + }; + } + const u = H / 1080; + const box = { x0: Math.round(W * 0.1), x1: Math.round(W * 0.9), y0: Math.round(H * 0.1), y1: Math.round(H * 0.9) }; + return { + vertical, box, + titlePx: [96, 84, 74, 64].map((p) => Math.round(p * u)), titleLines: 3, + ctaPx: Math.round(44 * u), brandPx: Math.round(40 * u), + gap: Math.round(40 * u), rule: { w: Math.round(120 * u), h: Math.max(2, Math.round(6 * u)) }, + brandRoom: Math.round(120 * u), + }; +} + +function esc(s) { + return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;"); +} +const pt = (px) => px * 0.75; +const span = (text, { px, color, face }) => `<span font_desc="${face}" size="${Math.round(pt(px) * 1024)}" foreground="${color}">${esc(text)}</span>`; + +const magickOpts = { maxBuffer: 1 << 24, env: { ...process.env, FONTCONFIG_FILE } }; + +/** Pango markup -> a transparent PNG centred lines wrapped at `width`; its size. */ +async function textPng(markup, file, width) { + const markupPath = file.replace(/\.png$/, ".pango"); + await writeFile(markupPath, markup, "utf8"); + const args = ["-background", "none", "-define", "pango:align=center"]; + if (width) args.push("-size", `${Math.round(width)}x`, "-define", "pango:wrap=word"); + args.push(`pango:@${markupPath}`, "-trim", "+repage", file); + await execFileP("magick", args, magickOpts); + const { stdout } = await execFileP("magick", [file, "-format", "%w %h", "info:"]); + const [w, h] = stdout.trim().split(" ").map(Number); + return { file, width: w, height: h }; +} + +/** The card's colours: the report videos' dark ground, the brand's paper and the site's accent. */ +export const OUTRO_COLOURS = Object.freeze({ ground: "#151b20", ink: "#f6f1e6", muted: "#a9b4bc" }); + +/** + * The card's key: everything drawn (the words, the size, the image's bytes, the brand). + * @param {object} o + */ +export function outroKey({ width, height, title, text, imageSha = null, brand }) { + return createHash("sha256").update(JSON.stringify({ v: 1, width, height, title, text, imageSha, brand })).digest("hex").slice(0, 20); +} + +/** + * Draw the card: `<dir>/outro-<key>.png` (kept: a second cut with the same + * words is not drawn again). `brand` is the site's name as the intro splits + * it (`lead` heavy, the rest light) in its accent (`ink`). + * + * @param {{ width: number, height: number, title: string, text: string, imageFile?: string | null, + * brand: { name: string, lead?: string, ink: string }, dir: string }} o + * @returns {Promise<{ file: string, key: string, cached: boolean, layout: ReturnType<typeof outroLayout>, placed: Record<string, { x: number, y: number, w: number, h: number }> }>} + */ +export async function renderOutroCard({ width: W, height: H, title, text, imageFile = null, brand, dir }) { + const L = outroLayout({ width: W, height: H }); + const imageBytes = imageFile ? await readFile(imageFile).catch(() => null) : null; + if (imageFile && !imageBytes) throw new Error(`outro.image ${imageFile}: not there`); + const imageSha = imageBytes ? createHash("sha256").update(imageBytes).digest("hex") : null; + const key = outroKey({ width: W, height: H, title, text, imageSha, brand }); + await mkdir(dir, { recursive: true }); + const file = path.join(dir, `outro-${key}.png`); + const placedFile = `${file}.json`; + if ((await exists(file)) && (await exists(placedFile))) { + return { file, key, cached: true, layout: L, placed: JSON.parse(await readFile(placedFile, "utf8")) }; + } + const work = path.join(dir, `.outro-${key}-${process.pid}`); + await mkdir(work, { recursive: true }); + try { + const boxW = L.box.x1 - L.box.x0; + // The title: the largest size whose wrap keeps to its lines. + let t = null; + for (const px of L.titlePx) { + t = await textPng(span(title, { px, color: OUTRO_COLOURS.ink, face: "Archivo @wght=800,wdth=108" }), path.join(work, "title.png"), boxW); + if (t.height <= px * 1.25 * L.titleLines) break; + } + const cta = await textPng(span(text, { px: L.ctaPx, color: brand.ink, face: "IBM Plex Sans @wght=600" }), path.join(work, "cta.png"), boxW); + const lead = brand.lead && brand.name.startsWith(brand.lead) ? brand.lead : ""; + const brandMarkup = `${lead ? span(lead, { px: L.brandPx, color: brand.ink, face: "Archivo @wght=800,wdth=108" }) : ""}${span(brand.name.slice(lead.length), { px: L.brandPx, color: lead ? brand.ink : brand.ink, face: lead ? "Archivo @wght=380,wdth=108" : "Archivo @wght=800,wdth=108" })}`; + const mark = await textPng(brandMarkup, path.join(work, "brand.png"), null); + + // The ground: the image covering the frame, blurred and darkened, else the plain ground. + const ground = path.join(work, "ground.png"); + if (imageFile) { + const blur = Math.round(Math.max(W, H) / 70); + await execFileP("magick", [ + imageFile, "-auto-orient", "-resize", `${W}x${H}^`, "-gravity", "center", "-extent", `${W}x${H}`, + "-blur", `0x${blur}`, "-fill", OUTRO_COLOURS.ground, "-colorize", "55%", "+repage", ground, + ], magickOpts); + } else { + await execFileP("magick", ["-size", `${W}x${H}`, `xc:${OUTRO_COLOURS.ground}`, ground], magickOpts); + } + + // The column: title, the accent rule, the call to action, centred in the box above the brand's room. + const colH = t.height + L.gap + L.rule.h + L.gap + cta.height; + const areaTop = L.box.y0; + const areaBottom = L.box.y1 - L.brandRoom; + let y = Math.round(areaTop + Math.max(0, (areaBottom - areaTop - colH) / 2)); + const cx = (L.box.x0 + L.box.x1) / 2; + const at = (w) => Math.round(cx - w / 2); + /** @type {Record<string, { x: number, y: number, w: number, h: number }>} */ + const placed = {}; + placed.title = { x: at(t.width), y, w: t.width, h: t.height }; + y += t.height + L.gap; + placed.rule = { x: at(L.rule.w), y, w: L.rule.w, h: L.rule.h }; + y += L.rule.h + L.gap; + placed.cta = { x: at(cta.width), y, w: cta.width, h: cta.height }; + placed.brand = { x: at(mark.width), y: L.box.y1 - mark.height, w: mark.width, h: mark.height }; + const tmp = path.join(work, "card.png"); + await execFileP("magick", [ + ground, + t.file, "-geometry", `+${placed.title.x}+${placed.title.y}`, "-composite", + "-fill", brand.ink, "-draw", `rectangle ${placed.rule.x},${placed.rule.y} ${placed.rule.x + placed.rule.w - 1},${placed.rule.y + placed.rule.h - 1}`, + cta.file, "-geometry", `+${placed.cta.x}+${placed.cta.y}`, "-composite", + mark.file, "-geometry", `+${placed.brand.x}+${placed.brand.y}`, "-composite", + "-alpha", "off", "-depth", "8", tmp, + ], magickOpts); + await writeFile(placedFile, JSON.stringify(placed) + "\n"); + await rename(tmp, file); + return { file, key, cached: false, layout: L, placed }; + } finally { + await rm(work, { recursive: true, force: true }); + } +} + +/** + * The filtergraph fragment that appends the card to a cut's `[vIn]`/`[aIn]` + * (`seconds` long, its `fade` overlapping the cut's last seconds): the card + * looped to its frames, the cut's sound faded out over the fade and silence + * after. `cutSeconds` is the cut's length before it. + * + * @param {{ png: string, seconds: number, fade?: number, fps: number, cutSeconds: number, vIn: string, aIn: string, + * audioRate?: number, audioChannels?: number, escape: (f: string) => string }} o + */ +export function outroFilterParts({ png, seconds, fade = OUTRO_FADE, fps, cutSeconds, vIn, aIn, audioRate = 48000, audioChannels = 2, escape }) { + const frames = Math.round(seconds * fps); + const d = (frames / fps).toFixed(6); + const layout = audioChannels === 1 ? "mono" : "stereo"; + const f = fade.toFixed(6); + return { + parts: [ + `movie=filename=${escape(png)},loop=loop=${frames - 1}:size=1:start=0,setpts=N/(${fps}*TB),fps=${fps},format=yuv420p,setsar=1,settb=AVTB[ocv]`, + `aevalsrc=0:channel_layout=${layout}:sample_rate=${audioRate}:duration=${d}[oca]`, + `${vIn}format=yuv420p,settb=AVTB[ocin]`, + `[ocin][ocv]xfade=transition=fade:duration=${f}:offset=${Math.max(0, cutSeconds - fade).toFixed(6)}[ov]`, + `${aIn}aresample=${audioRate},aformat=channel_layouts=${layout}[ocain]`, + `[ocain][oca]acrossfade=d=${f}:c1=tri:c2=tri[oa]`, + ], + vOut: "[ov]", + aOut: "[oa]", + frames, + }; +} diff --git a/umtool/report-to-video/outro.test.mjs b/umtool/report-to-video/outro.test.mjs @@ -0,0 +1,191 @@ +// outro.mjs (the reel's outro card) and the trailer's reel extras: the +// setting's validation and defaults, the card's layout inside the vertical's +// safe area, the plan with a reel's own intro and the card, the graph, and +// the run with both (the renders stubbed). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + OUTRO_FADE, + OUTRO_SECONDS_DEFAULT, + OUTRO_TEXT_DEFAULT, + VERTICAL_SAFE, + normalizeOutro, + outroAdds, + outroErrors, + outroLayout, + outroOn, + resolveOutro, +} from "./outro.mjs"; +import { REEL_INTRO_DEFAULT, outroBrand, reelIntroOf, scheduleHasIntro } from "./reel-intro.mjs"; +import { makeTrailer, parseBeats, planTrailer, trailerArgs, withReelExtras } from "./trailer.mjs"; + +test("outro: on|off or an object of known keys; each wrong key refused by name", () => { + assert.deepEqual(outroErrors(true), []); + assert.deepEqual(outroErrors(false), []); + assert.deepEqual(outroErrors({ title: "T", text: "go", image: "promo/t.jpg", seconds: 3.5 }), []); + assert.match(outroErrors({ colour: "red" }).join(), /outro\.colour is not a key/); + assert.match(outroErrors({ seconds: 0.5 }).join(), /outro\.seconds is 1\.5–10/); + assert.match(outroErrors({ image: "../x.jpg" }).join(), /outro\.image/); + assert.match(outroErrors({ image: "/abs/x.jpg" }).join(), /outro\.image/); + assert.match(outroErrors({ image: "promo/x.gif" }).join(), /outro\.image/); + assert.match(outroErrors("yes").join(), /on\|off/); + assert.throws(() => normalizeOutro({ seconds: 99 }), /outro\.seconds/); + assert.deepEqual(normalizeOutro(true), { on: true }); + assert.deepEqual(normalizeOutro({ title: " The title ", image: "./promo/t.jpg" }), { on: true, title: "The title", image: "promo/t.jpg" }); + assert.equal(outroOn({ on: false, title: "x" }), false); + assert.equal(outroOn({ title: "x" }), true); +}); + +test("outro: the defaults -- the reel's title, else the project's; the call to action; 3.5 s; no image", () => { + assert.equal(resolveOutro(undefined), null); + assert.equal(resolveOutro({ on: false, title: "x" }), null); + assert.deepEqual(resolveOutro(true, { reelTitle: "Reel", projectTitle: "Project" }), { title: "Reel", text: OUTRO_TEXT_DEFAULT, image: null, seconds: OUTRO_SECONDS_DEFAULT }); + assert.equal(resolveOutro({ on: true }, { projectTitle: "Project" }).title, "Project"); + assert.deepEqual(resolveOutro({ on: true, title: "T", text: "Watch it", image: "promo/t.jpg", seconds: 4 }, { reelTitle: "Reel" }), { title: "T", text: "Watch it", image: "promo/t.jpg", seconds: 4 }); + assert.equal(outroAdds(3.5), 3.5 - OUTRO_FADE); + assert.equal(outroAdds(0), 0); +}); + +test("the card's layout: a vertical's content inside the safe area (top 8 %, bottom 20 %, right 12 %); a landscape's centred", () => { + const v = outroLayout({ width: 1080, height: 1920 }); + assert.equal(v.vertical, true); + assert.ok(v.box.y0 >= 1920 * VERTICAL_SAFE.top); + assert.ok(v.box.y1 <= 1920 * (1 - 0.2)); + assert.ok(v.box.x1 <= 1080 * (1 - 0.12)); + assert.ok(v.box.x0 >= 0 && v.box.x0 < v.box.x1); + // the title's wrap is the box's width, and the brand's room sits inside it + assert.ok(v.box.y1 - v.brandRoom > v.box.y0); + const l = outroLayout({ width: 1920, height: 1080 }); + assert.equal(l.vertical, false); + assert.equal(l.box.x0 + l.box.x1, 1920); + assert.equal(l.box.y0 + l.box.y1, 1080); +}); + +// A master of a brand intro and two clips, 30 fps, 0.5 s dissolves. +const SCHEDULE = { + version: 1, kind: "deck", fps: 30, transition: 0.5, total: 26.167, + segments: [ + { id: "c1", type: "clip", start: 0, duration: 12, end: 12 }, + { id: "c2", type: "clip", start: 11.5, duration: 14.667, end: 26.167 }, + ], +}; +const RECORDS = new Map([ + ["c1", { version: 1, id: "c1", start: 100, end: 112 }], + ["c2", { version: 1, id: "c2", start: 500, end: 514.667 }], +]); +const beats = () => parseBeats([{ id: "c1", start: 102, end: 106 }, { id: "c2", start: 503, end: 507 }]); + +test("withReelExtras: a reel's own intro first (crossfaded in), the card after the last beat (faded in over 0.5 s), the total counts both", () => { + const plan = planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: beats(), xfade: 0.3 }); + const bare = plan.total; + const p = withReelExtras(plan, { intro: { file: null, seconds: 4.75 }, outro: { seconds: 3.5, title: "T" } }); + assert.equal(p.pieces[0].kind, "intro"); + assert.equal(p.pieces[0].master, null); + assert.equal(p.pieces[0].frames.count, 143); + assert.equal(p.pieces[1].at, Number((143 / 30 - 0.3).toFixed(3))); + // intro 143 frames, less one crossfade, plus the card less its fade + assert.ok(Math.abs(p.total - (bare + 143 / 30 - 0.3 + 3.5 - OUTRO_FADE)) < 1e-3, `${p.total}`); + assert.equal(p.outro.fade, OUTRO_FADE); + assert.ok(Math.abs(p.outro.at - (bare + 143 / 30 - 0.3 - OUTRO_FADE)) < 1e-3); + // nothing asked: the plan as it was + const same = withReelExtras(plan, {}); + assert.equal(same.total, bare); + assert.equal(same.outro, undefined); +}); + +test("trailerArgs: no outro and no file run is the graph it always was (no timebase moved); with them, the card and the intro's own file", () => { + const plan = planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: beats(), xfade: 0.3 }); + const render = { fps: 30, crf: 20, preset: "medium", audioBitrate: "160k" }; + const bare = trailerArgs({ plan, master: "/m/cut.mp4", render, outPath: "/o.mp4" }); + const graph = bare[bare.indexOf("-filter_complex") + 1]; + assert.doesNotMatch(graph, /settb|outro|aevalsrc/); + const p = withReelExtras(plan, { intro: { file: "/cache/intro.mp4", seconds: 4.75 }, outro: { seconds: 3.5 } }); + p.pieces[0].file = "/cache/intro.mp4"; + const argv = trailerArgs({ plan: p, master: "/m/cut.mp4", render, outPath: "/o.mp4", outro: { png: "/card.png", seconds: 3.5, fade: 0.5 } }); + const g = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(g, /movie=filename=\/cache\/intro\.mp4:seek_point=0\.000000/); + assert.match(g, /movie=filename=\/card\.png,loop=loop=104:size=1/); + assert.match(g, /xfade=transition=fade:duration=0\.500000/); + assert.match(g, /acrossfade=d=0\.500000/); + assert.equal(argv[argv.indexOf("-map") + 1], "[ov]"); +}); + +async function takeFixture({ render = {} } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "outro-")); + const take = path.join(root, "takes", "final"); + const seg = path.join(take, "out", "sourced", "segments"); + await mkdir(seg, { recursive: true }); + await writeFile(path.join(take, "video.manifest.json"), JSON.stringify({ slug: "cut", render: { fps: 30, width: 1920, height: 1080, crf: 21, preset: "slow", audioBitrate: "160k", audioRate: 48000, audioChannels: 2, ...render } })); + await writeFile(path.join(take, "out", "cut.mp4"), "master"); + await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(SCHEDULE)); + for (const [id, rec] of RECORDS) await writeFile(path.join(seg, `${id}.cut.json`), JSON.stringify(rec)); + return { root, take }; +} + +test("reelIntroOf: the reel's own, else the master's, else the take's render.intro, else the default -- rendered for the reel", async () => { + const sitesDir = await mkdtemp(path.join(tmpdir(), "outro-sites-")); + await mkdir(path.join(sitesDir, "anilyzer")); + await writeFile(path.join(sitesDir, "anilyzer", "site.json"), JSON.stringify({ siteTitle: "Anilyzer", wordmarkLead: "Ani", accent: "sakura", siteUrl: "https://anilyzer.pages.dev" })); + try { + const build = { schedule: SCHEDULE, render: { fps: 30 }, manifest: {} }; + const own = reelIntroOf({ build, introSpec: { style: "boot-dark", mark: "chime", site: "anilyzer" }, sitesDir }); + assert.equal(own.from, "reel"); + assert.equal(own.entry.site.name, "Anilyzer"); + assert.equal(reelIntroOf({ build, sitesDir }).from, "default"); + assert.equal(reelIntroOf({ build, sitesDir }).entry.style, REEL_INTRO_DEFAULT.style); + assert.equal(reelIntroOf({ build: { ...build, render: { fps: 30, intro: "boot" } }, sitesDir }).from, "take"); + const withIntro = { ...SCHEDULE, segments: [{ id: "brand-intro", type: "intro", start: 0, duration: 4 }, ...SCHEDULE.segments] }; + assert.equal(scheduleHasIntro(withIntro), true); + assert.equal(reelIntroOf({ build: { ...build, schedule: withIntro }, sitesDir }).from, "master"); + assert.throws(() => reelIntroOf({ build, introSpec: { style: "nope" }, sitesDir }), /not an intro style/); + const brand = await outroBrand(own.entry, { sitesDir }); + assert.equal(brand.name, "Anilyzer"); + assert.equal(brand.lead, "Ani"); + assert.match(brand.ink, /^#[0-9a-f]{6}$/i); + assert.equal((await outroBrand(null, { sitesDir })).name, "Archilyzer"); + } finally { + await rm(sitesDir, { recursive: true, force: true }); + } +}); + +test("makeTrailer: a reel's own intro and the card, made inside the slot; the record names both", async () => { + const { root, take } = await takeFixture(); + try { + let ran = null; + const made = []; + const res = await makeTrailer({ + takeDir: take, + beats: beats(), + introSpec: { style: "boot-dark", mark: "chime" }, + outro: { title: "The Title", text: OUTRO_TEXT_DEFAULT, image: null, imageFile: null, seconds: 3.5 }, + probe: async () => 26.167, + measure: async () => new Map(), + slot: async (fn) => { made.push("slot"); return fn(); }, + makeIntro: async ({ entry }) => { made.push(`intro ${entry.style}`); return "/cache/intro.mp4"; }, + makeOutro: async (o) => { made.push(`outro ${o.width}x${o.height} ${o.brand.name}`); return { file: "/cards/outro.png" }; }, + run: async (argv) => { ran = argv; await writeFile(argv.at(-1), "trailer"); }, + }); + assert.deepEqual(made, ["slot", "intro boot-dark", "outro 1920x1080 Archilyzer"]); + const g = ran[ran.indexOf("-filter_complex") + 1]; + assert.match(g, /\/cache\/intro\.mp4/); + assert.match(g, /\/cards\/outro\.png/); + const rec = JSON.parse(await readFile(res.recordPath, "utf8")); + assert.equal(rec.pieces[0].kind, "intro"); + assert.equal(rec.pieces[0].file, "/cache/intro.mp4"); + assert.equal(rec.outro.title, "The Title"); + assert.equal(rec.outro.card, "/cards/outro.png"); + assert.equal(rec.seconds, res.plan.total); + // intro on with no intro in the master: one rendered for the reel (the default), not refused + const dry = await makeTrailer({ takeDir: take, beats: beats(), intro: true, dryRun: true, probe: async () => 26.167, measure: async () => new Map() }); + assert.equal(dry.plan.pieces[0].kind, "intro"); + assert.match(dry.plan.notes[0], /the default intro/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -105,6 +105,8 @@ "./sources": "./sources.mjs", "./sync-report": "./sync-report.mjs", "./trailer": "./trailer.mjs", + "./outro": "./outro.mjs", + "./reel-intro": "./reel-intro.mjs", "./transition": "./transition.mjs", "./variants": "./variants.mjs", "./verify-build": "./verify-build.mjs", diff --git a/umtool/report-to-video/reel-intro.mjs b/umtool/report-to-video/reel-intro.mjs @@ -0,0 +1,112 @@ +// A REEL'S OWN INTRO, and the site the outro card names (operator, 5 Nov: +// "actually I want intro in the trailer too"). +// +// `umtool trailer --reel <r>` with the reel's `intro` on opened on the +// master's brand intro, and refused a take whose cut had none -- the X +// trailer of a cut rendered without one could not have it. Now: +// +// - the reel's `intro` an OBJECT (render.intro's shape: `{style, mark, +// site, …}`): that intro, rendered for the reel at the take's size, fps +// and encode (intro.mjs renderIntro, through its cache), whatever the +// master opens on; +// - `true` and the master has a brand intro: the master's own frames, as +// before (the cut is byte for byte what it was); +// - `true` and the master has none: the take's `render.intro` rendered for +// the reel, else REEL_INTRO_DEFAULT (the dark boot with the mark on the +// chime, the site found from the cut's siteOrigin). +// +// The outro card's brand line is that intro's site (its name, lead and accent +// on the dark ground), else the site the cut's siteOrigin names, else +// Archilyzer. +// +// Plain ESM: the CLI runs it under bare node. + +import path from "node:path"; + +import { encodeArgs } from "./build-video.mjs"; +import { INTRO_BRAND_DEFAULT, introEntry, introErrors, renderIntro, resolveIntroSite } from "./intro.mjs"; + +/** The intro a reel gets when it asks for one and neither it nor the take names one. */ +export const REEL_INTRO_DEFAULT = Object.freeze({ style: "boot-dark", mark: "chime", site: "auto" }); + +class ReelIntroError extends Error {} + +/** Does the take's cut open on a brand intro (a segment of type "intro" in its schedule)? */ +export function scheduleHasIntro(schedule) { + return (schedule?.segments ?? []).some((s) => s?.type === "intro" || s?.id === "brand-intro"); +} + +const describe = (entry) => `${entry.style}${entry.mark && entry.mark !== "none" ? `, mark ${entry.mark}` : ""}${entry.site ? `, site ${entry.site.name}` : ""}, ${entry.seconds} s`; + +/** + * Which intro the reel opens on: `{ from: "master" | "reel" | "take" | "default", entry, label }`. + * `entry` is intro.mjs introEntry's (for "master", the take's own render.intro, when it reads). + * + * @param {{ build: { schedule: any, render: any, manifest?: any }, introSpec?: unknown, sitesDir?: string }} o + */ +export function reelIntroOf({ build, introSpec = null, sitesDir = undefined }) { + const provenance = build.manifest?.provenance ?? null; + const entryOf = (spec, what) => { + const errors = introErrors(spec); + if (errors.length) throw new ReelIntroError(`${what}: ${errors.join("; ")}`); + const e = introEntry({ ...build.render, intro: spec }, { provenance, ...(sitesDir ? { sitesDir } : {}) }); + if (!e) throw new ReelIntroError(`${what}: not an intro`); + return e; + }; + if (introSpec !== null && introSpec !== undefined && introSpec !== true) { + const entry = entryOf(introSpec, "the reel's intro"); + return { from: /** @type {const} */ ("reel"), entry, label: `the reel's own (${describe(entry)}), rendered for it` }; + } + if (scheduleHasIntro(build.schedule)) { + let entry = null; + try { + entry = build.render?.intro ? entryOf(build.render.intro, "render.intro") : null; + } catch { + entry = null; + } + return { from: /** @type {const} */ ("master"), entry, label: "the master's own brand intro" }; + } + if (build.render?.intro) { + const entry = entryOf(build.render.intro, "the take's render.intro"); + return { from: /** @type {const} */ ("take"), entry, label: `the take's render.intro (${describe(entry)}), rendered for the reel -- the master has none` }; + } + const entry = entryOf({ ...REEL_INTRO_DEFAULT }, "the default intro"); + return { from: /** @type {const} */ ("default"), entry, label: `the default intro (${describe(entry)}), rendered for the reel -- the master has none` }; +} + +/** + * The intro rendered at the take's size, fps and encode: the cached file's path. + * @param {{ entry: any, build: { render: any }, takeDir: string }} o + */ +export async function renderReelIntro({ entry, build, takeDir }) { + const r = await renderIntro({ + entry, render: build.render, encode: encodeArgs(build.render), manifestDir: takeDir, + workDir: path.join(takeDir, "out", "sourced", "chrome"), + }); + return r.path; +} + +/** + * The outro card's brand line: `{ name, lead, ink }` -- the intro's site, else + * the site the cut's siteOrigin names, else Archilyzer; its accent on the dark ground. + * + * @param {any} entry introEntry's, or null + * @param {{ provenance?: any, sitesDir?: string }} [o] + */ +export async function outroBrand(entry, { provenance = null, sitesDir = undefined } = {}) { + let site = entry?.site ?? null; + if (!site) { + try { + site = resolveIntroSite("auto", { siteOrigin: provenance?.siteOrigin ?? null, ...(sitesDir ? { sitesDir } : {}) }); + } catch { + site = null; + } + } + const { introAccent, introPalette } = await import("./chrome-intro.mjs"); + const { brandKit } = await import("./brand.mjs"); + const palette = introPalette("dark", brandKit(entry?.brand ?? INTRO_BRAND_DEFAULT)); + if (!site) return { name: "Archilyzer", lead: "Archi", ink: introAccent("signal", "dark", palette).ink }; + return { name: site.name, ...(site.lead ? { lead: site.lead } : {}), ink: introAccent(site.accent ?? "signal", "dark", palette).ink }; +} + +export { ReelIntroError }; diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -75,6 +75,8 @@ import { clipWords } from "./clip-words.mjs"; import { DEFAULT_CHANNELS_DIR } from "./cues.mjs"; import { detectSilence } from "./cut-points.mjs"; import { beatGapsOf, gapFilterParts, offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; +import { OUTRO_FADE, outroAdds, outroFilterParts, renderOutroCard } from "./outro.mjs"; +import { outroBrand, reelIntroOf, renderReelIntro } from "./reel-intro.mjs"; import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; const execFileP = promisify(execFile); @@ -181,7 +183,7 @@ export function scheduleSpans(schedule) { } /** The brand intro's span: the segment of type "intro" (the build names it brand-intro). */ -function introSpan(spans) { +export function introSpan(spans) { for (const s of spans.values()) if (s.type === "intro" || s.id === "brand-intro") return s; return null; } @@ -459,6 +461,48 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = return { fps, transition: D, xfade: x, masterSeconds: total, pieces, total: r3(acc), notes }; } +/** + * A plan with the reel's own pieces added, pure: `intro` (`{ file, seconds, + * label? }`, an intro rendered for the reel, as the cut's first piece -- + * crossfaded into the first beat like any two pieces) and `outro` (`{ seconds, + * fade? }`, the card after the last piece, faded in over `fade`). The pieces' + * `at` and the total are placed again. + * + * @param {ReturnType<typeof planTrailer>} plan + * @param {{ intro?: { file: string | null, seconds: number, label?: string } | null, outro?: { seconds: number, fade?: number, [k: string]: any } | null }} extras + */ +export function withReelExtras(plan, { intro = null, outro = null } = {}) { + const { fps, xfade: x } = plan; + const pieces = [...plan.pieces]; + if (intro) { + const count = Math.round(intro.seconds * fps); + pieces.unshift({ + kind: "intro", standalone: true, ...(intro.file ? { file: intro.file } : {}), ...(intro.label ? { label: intro.label } : {}), + master: null, frames: { start: 0, count }, + }); + if (pieces[1]?.seamless) { + const { seamless: _s, ...rest } = pieces[1]; + pieces[1] = rest; + } + } + let acc = 0; + pieces.forEach((p, i) => { + const over = i > 0 && !p.seamless ? x : 0; + p.at = r3(acc - over); + acc = acc + pieceFrames(p) / fps - over; + }); + const notes = [...plan.notes]; + let total = acc; + let out = null; + if (outro) { + const fade = outro.fade ?? OUTRO_FADE; + const frames = Math.round(outro.seconds * fps); + out = { ...outro, fade, at: r3(Math.max(0, acc - fade)), seconds: r3(frames / fps), frames }; + total = acc + outroAdds(frames / fps); + } + return { ...plan, pieces, total: r3(total), notes, ...(out ? { outro: out } : {}) }; +} + function pieceName(p, i) { const at = p.master?.start ?? p.a; return p.kind === "clip" ? p.id : p.kind === "raw" ? `beat at ${fmt(at)}` : p.kind ?? `piece ${i + 1}`; @@ -477,9 +521,9 @@ export function trailerRuns(plan) { const runs = []; for (const p of plan.pieces) { const last = runs[runs.length - 1]; - const run = p.seamless && last ? last : null; + const run = p.seamless && last && !last.file ? last : null; if (run) run.count = p.frames.start + p.frames.count - run.start; - else runs.push({ start: p.frames.start, count: p.frames.count }); + else runs.push({ start: p.frames.start, count: p.frames.count, ...(p.file ? { file: p.file } : {}) }); const r = runs[runs.length - 1]; if (p.cuts?.length) r.cuts = [...(r.cuts ?? []), ...p.cuts.map((c) => ({ ...c.frames }))]; if (r.cuts) r.kept = r.count - r.cuts.reduce((n, c) => n + c.count, 0); @@ -515,7 +559,7 @@ export function filterPath(file) { * the run's first frame, sample-exact; then both are pinned to the run's * length, as build-video's join pins each segment's. */ -export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_DECODE_THREADS }) { +export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_DECODE_THREADS, outro = null }) { const { fps, xfade: x } = plan; const runs = trailerRuns(plan); const half = 0.5 / fps; @@ -523,15 +567,18 @@ export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_D const parts = []; // A gapped run's concat puts its picture on the default timebase (1/1000000), and // xfade wants both inputs on one: with any gapped run, every run's picture is put there. - const tb = runs.some((r) => r.cuts?.length) ? ",settb=AVTB" : ""; + // So with a run of another file (a reel's own intro): its timebase is not the master's. + const tb = runs.some((r) => r.cuts?.length || r.file) ? ",settb=AVTB" : ""; runs.forEach((r, i) => { const a = r.start / fps; const n = r.count; const d = (n / fps).toFixed(6); const seek = Math.max(0, a - PRE_ROLL); - parts.push(`movie=filename=${src}:seek_point=${seek.toFixed(6)}:streams=dv+da:dec_threads=${threads}[m${i}v][m${i}a]`); + // A run of its own file (the reel's intro, rendered for it) is that file's frames from 0, at the master's format. + const fmtv = r.file ? `,format=yuv420p,fps=${fps}` : ""; + parts.push(`movie=filename=${r.file ? filterPath(r.file) : src}:seek_point=${seek.toFixed(6)}:streams=dv+da:dec_threads=${threads}[m${i}v][m${i}a]`); const cut = r.cuts?.length; - parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS${cut ? "" : tb}[${cut ? `r${i}v` : `v${i}`}]`); + parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS${fmtv}${cut ? "" : tb}[${cut ? `r${i}v` : `v${i}`}]`); parts.push( `[m${i}a]atrim=start=${a.toFixed(6)}:end=${(a + n / fps).toFixed(6)},asetpts=PTS-STARTPTS,` + `apad=whole_dur=${d},atrim=end=${d}[${cut ? `r${i}a` : `a${i}`}]`, @@ -562,6 +609,17 @@ export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_D vlab = "[cv]"; alab = "[ca]"; } + // The reel's outro card (outro.mjs): faded in over the cut's last OUTRO_FADE seconds, held to the end. + if (outro) { + const cutSeconds = runs.reduce((n, r) => n + keptOf(r), 0) - (x > 0 ? x * Math.max(0, runs.length - 1) : 0); + const o = outroFilterParts({ + png: outro.png, seconds: outro.seconds, fade: outro.fade, fps, cutSeconds, vIn: vlab, aIn: alab, + audioRate: render?.audioRate ?? 48000, audioChannels: render?.audioChannels ?? 2, escape: filterPath, + }); + parts.push(...o.parts); + vlab = o.vOut; + alab = o.aOut; + } return [ "-nostdin", "-v", "error", "-y", "-filter_complex", parts.join(";"), @@ -713,13 +771,30 @@ export async function makeTrailer({ takeDir, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT, out = null, dryRun = false, run = runFfmpeg, probe = probeMasterSeconds, slot = (fn) => fn(), now = Date.now, snap = true, measure = (build, list) => trailerPauses({ build, beats: list }), reel = null, + introSpec = null, outro = null, makeIntro = renderReelIntro, makeOutro = renderOutroCard, sitesDir = undefined, }) { const build = await loadTakeBuild(takeDir); + // The reel's intro (reelIntro.mjs): the master's own when it has one and the + // reel names no intro of its own, else one rendered for the reel. + let ri = null; + if (intro || introSpec) { + try { + ri = reelIntroOf({ build, introSpec, sitesDir }); + } catch (e) { + throw new TrailerError(e instanceof Error ? e.message : String(e)); + } + } + const masterIntro = !!ri && ri.from === "master"; + const extras = (plan) => withReelExtras(plan, { + intro: ri && !masterIntro ? { file: null, seconds: ri.entry.seconds, label: ri.label } : null, + outro: outro ? { seconds: outro.seconds, title: outro.title, text: outro.text, image: outro.image ?? null } : null, + }); // Checked once without the pauses first: a beat that is refused is refused // before anything is measured. - planTrailer({ schedule: build.schedule, records: build.records, beats, intro, finale, xfade, snap: false }); + planTrailer({ schedule: build.schedule, records: build.records, beats, intro: masterIntro, finale, xfade, snap: false }); const pauses = snap ? await measure(build, beats) : null; - const plan = planTrailer({ schedule: build.schedule, records: build.records, beats, intro, finale, xfade, pauses, snap }); + const plan = extras(planTrailer({ schedule: build.schedule, records: build.records, beats, intro: masterIntro, finale, xfade, pauses, snap })); + if (ri) plan.notes.unshift(`intro: ${ri.label}`); const masterSeconds = await probe(build.master, plan.fps); if (masterSeconds == null) throw new TrailerError(`${path.basename(takeDir)} has no master: ${build.master} cannot be read`); if (Math.abs(masterSeconds - plan.masterSeconds) > 0.1) { @@ -754,15 +829,36 @@ export async function makeTrailer({ encode: { crf: build.render.crf ?? 20, preset: build.render.preset ?? "medium", audioBitrate: build.render.audioBitrate ?? "160k" }, seconds: plan.total, pieces: plan.pieces, + ...(plan.outro ? { outro: { title: plan.outro.title, text: plan.outro.text, image: plan.outro.image, seconds: plan.outro.seconds, fade: plan.outro.fade, at: plan.outro.at } } : {}), notes: plan.notes, }; if (dryRun) return { plan, outPath, recordPath, record, encodeSeconds: null, dryRun: true }; - const argv = trailerArgs({ plan, master: build.master, render: build.render, outPath: "" }); await mkdir(path.dirname(outPath), { recursive: true }); + /** The reel's own intro and outro card, made inside the slot (the intro is a HyperFrames render, cached). */ + const prepare = async () => { + if (ri && !masterIntro) { + const file = await makeIntro({ entry: ri.entry, build, takeDir }); + plan.pieces[0].file = file; + record.pieces[0].file = file; + } + let card = null; + if (outro) { + const W = build.render.width ?? 1920; + const H = build.render.height ?? 1080; + const r = await makeOutro({ + width: W, height: H, title: outro.title, text: outro.text, imageFile: outro.imageFile ?? null, + brand: await outroBrand(ri?.entry ?? null, { provenance: build.manifest?.provenance ?? null, sitesDir }), + dir: path.join(takeDir, "out", "sourced", "outro"), + }); + card = { png: r.file, seconds: plan.outro.seconds, fade: plan.outro.fade }; + record.outro.card = r.file; + } + return trailerArgs({ plan, master: build.master, render: build.render, outPath: "", outro: card }); + }; + let argv = null; // Written beside, then renamed: a half-made file never sits at the name. const tmp = path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}.${process.pid}.tmp.mp4`); - argv[argv.length - 1] = tmp; let encodeSeconds = null; // Cancelled (the Trailer page's Cancel signals the job's process group): the // half-made file goes with it. Exits as the signal would when nothing else @@ -782,6 +878,8 @@ export async function makeTrailer({ }); try { await slot(async () => { + argv = await prepare(); + argv[argv.length - 1] = tmp; const t0 = now(); try { await run(argv); @@ -809,10 +907,13 @@ export function describePlan(plan) { ? `${p.id.padEnd(22)} source ${fmt(p.source.start)}–${fmt(p.source.end)}` : p.kind === "raw" ? `${"(master)".padEnd(22)} at ${fmt(p.asked.at)} for ${fmt(p.asked.dur)}` : `${`(${p.kind})`.padEnd(22)}`; - const span = `master ${clock(p.master.start)}–${clock(p.master.end)}`; + const span = p.master ? `master ${clock(p.master.start)}–${clock(p.master.end)}` : `its own render${p.label ? ` (${p.label})` : ""}`; const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}${p.cuts?.length ? ` (${p.cuts.length} gap${p.cuts.length === 1 ? "" : "s"} cut)` : ""}`; - return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.seconds ?? p.master.duration)} s${marks}`; + return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.seconds ?? p.master?.duration ?? p.frames.count / plan.fps)} s${marks}`; }); - lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces, crossfade ${fmt(plan.xfade)} s`); + if (plan.outro) { + lines.push(`${String(plan.pieces.length + 1).padStart(2)}. ${clock(plan.outro.at).padStart(6)} ${"(outro)".padEnd(48)} the card${plan.outro.title ? ` "${plan.outro.title}"` : ""} ${fmt(plan.outro.seconds)} s (fades in over ${fmt(plan.outro.fade)} s)`); + } + lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces${plan.outro ? " and the outro" : ""}, crossfade ${fmt(plan.xfade)} s`); return lines; }