Archilyzer · Source

archilyzer

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

commit 11c4cf79a0dc5766a5b80bcd8a77993934b134b6
parent 54223690f744686233212369a203cb4fdfe6c4d8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 26 Oct 2026 15:57:11 -0400

Merge lane/trailer: umtool trailer cuts a trailer from a finished take's master (the full video's rail and tallies), beats mapped through the schedule and cut records

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

# Conflicts:
#	editor/CHANGELOG.md

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/bin/umtool.mjs | 6++++++
Mumtool/docs/cli.md | 1+
Mumtool/docs/report-video.md | 40++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/trailerCli.mjs | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/trailerCli.test.mjs | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/trailer.mjs | 561+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/trailer.test.mjs | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 1187 insertions(+), 0 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,6 +3,7 @@ ## [Unreleased] - **A report video's fact-check counter never cuts its label short.** The deck's count box showed the verdict's label and cut what did not fit with "…", so the Huck cut's count read "HUCK'S BLEND …". A verdict can now carry a `tallyLabel` (`render.chrome.factcheck.verdicts.<V>.tallyLabel`), a short word for the count box alone, and the Huck cut's says "Pitches"; the finale's totals and stats keep the full "Huck's Blend pitches". Without one, the box shows the label if it fits, else the longest run of the label's last words that fits. A `tallyLabel` that does not fit, or a label with no last words that fit, is refused by name when the manifest is checked, not found in the render. Labels that already fit draw exactly as before. - **A post screenshot alone in the posts feed fills the card's width.** The feed only let a tall screenshot grow into the room beside the card under it, and it kept that room even when the card under it was about to be pushed out of the column, so the Huck video's 21 October "new kind of seizure" post stood alone at 345 px wide in a 556 px card with the column empty under it. A screenshot whose card arrives alone, or pushes the one under it out, now takes the card's full width, its height following the picture, up to the column's height (larger than the screenshot itself if the width needs it). With a card under it that stays on screen, the feed draws exactly as before, and a feed with no screenshots builds the same page, so its cached render is reused. +- **A report video's trailer can be cut from the finished video, so it shows the whole timeline.** The Huck trailer was a short take of its own: 14 clips with their own rail, so the on-screen timeline, dates and tallies said the video was two minutes long. `umtool trailer <project> --take <take> --beats beats.json --intro --finale 8` now cuts the trailer from the take's finished master instead. Each beat is a clip's source seconds (or master seconds), and the take's own build records find where those seconds play in the master. The rail on screen is the full video's, so a viewer can see there is more. Nothing is rendered again: it is one ffmpeg pass, crossfaded and encoded with the take's own settings. It writes `<slug>.trailer.mp4` beside the master and a `.trailer.json` record of what was cut. A beat that reaches into one of the master's own crossfades is moved in, and the command says so. A beat that runs into the next piece (the intro into the first clip, the last beat into the finale) plays straight on, so no moment is shown twice. Unknown clips, beats outside what was cut, and takes with no build are refused by name. - **A twin of a finished report-video take renders in a fraction of the time.** A full build of the Huck cut took about 1 h 45 m, and its uncensored twin — the same cut with `render.blur` off — took as long again, because every build encoded all 66 clips again (about 8 minutes), which in turn redid every crossfade batch, and captured the on-screen chrome again (about 47 minutes) once the first build had pruned its frames. Now a clip's segment is encoded again only when something that makes its picture or sound changed (its cut, snap, room, blur, framing, captions, loudness, encode settings or source file); otherwise the one on disk is reused untouched, and so are the crossfade batches over it. `umtool take <project> --id <id> --from <other take> …` starts a take from another take's render: it hard-links that take's clip segments, chrome frames and crossfade batches in (no copies, and the other take's files never change) and renders, rebuilding only what differs — for the uncensored twin, the blurred clip and the batch it sits in, then the final overlay. Make the first take with `--keep-frames` so its chrome frames are still there for the twin (they are 1–3 GB a layer; without it they are pruned after the render as before). `--from` refuses a take that does not exist, the take itself, or a take never rendered. Needs a restart of umtool for the Takes page's jobs; the CLI has it at once. - **A report video's fact-check counter can stay off screen until it first counts.** The deck's tally drew every verdict's cell from the first frame, so in the Huck cut the "Huck's Blend pitches" cell read 0 for about 23 of its 29 minutes. With `render.chrome.factcheck.tally.showAt: "first"` a cell is hidden until the stamp that gives it its first count lands; then it pops in already reading that count, flashes, and stays to the end. `{ "PARTLY": "first" }` sets it for one verdict's cell only. The default, `"always"`, is the tally as before. A hidden cell keeps its place in the row, and the finale's totals still show every verdict. Set it in the On-screen tab's fact-check labels (**pop in**, per verdict), with `umtool look <project> factcheck.tally.showAt=first` (or `factcheck.tally.showAt.PARTLY=first`; `factcheck.tally.showAt=` clears it), or in a take (`--set render.chrome.factcheck.tally.showAt=first`). An unknown value is refused by name. The clip editor's live preview and the Play view show the same deck page as the render, so the cell pops in at the same moment there. Needs a restart of umtool and a rebuild of the video. - **A report video's finale timeline no longer prints words over words.** In the Huck cut's finale the claim checks' words all stood on one line over the rail (`“less than ten” a year`, `19 seizures on camera`, `12 in a day · 4 in a week`, both pill-test goalposts), the `12 IN A DAY`/`4 IN A WEEK` labels ran into the markers' flags, and the turned dates under the rail overlapped. Now the claim checks take turns (`deck.finale.claims`: `rotate`, the default — one claim at a time for an even share of the finale's time, at least 6 s each, with a short crossfade; `all` stacks them), every claim's words, span label and marker label is laid in its own place in rows over the rail, with its stick kept inside its bracket and clear of the words under it, and a crowded rail says each date once and fans the turned labels out on thin leaders so no two meet. The timeline takes the height its rows need (`deck.finale.timelineShare`: `auto`, up to just over half the frame, its words set larger when there is room; or a share 0.38–0.6), and the clip, the totals and the stats shrink to fit under it. A finale without claim checks and with room for its labels renders as before. Re-render a take to see it. diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -57,6 +57,8 @@ // umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] // [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] +// umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] +// [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] // the clip deck's montage rulings (release 34) // umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of @@ -768,6 +770,9 @@ function usage() { " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force;", " --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", + " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]", + " a trailer cut from the take's finished master: the master's own frames, so the deck shows the", + " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)", " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>", " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]", @@ -838,6 +843,7 @@ const COMMANDS = { // The take maker (release 33): lib/report/takeCli.mjs. take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))), takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), + trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // The clip deck's rulings (release 34): lib/report/rulingsCli.mjs. rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), // Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs. diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -46,6 +46,7 @@ Inbox cannot disagree about what is wrong with one. | `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) | | `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | | `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | +| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--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, 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)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. Every run is recorded in `<project>/fetch-runs.json`. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | | `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -934,6 +934,46 @@ the one the take was made from (its `baseHash`), the card says **The project cha take was made** and the pick waits for **Use anyway**. A take that does not record its base asks the same. +### Trailer from the master + +`umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) [--intro] [--finale S] +[--xfade 0.3] [--out NAME] [--dry-run] [--json]` cuts a trailer out of a finished take's master +(`takes/<t>/out/<slug>.mp4`). The trailer is the master's own frames, so the deck's rail, dates, +pips and running tallies show the whole video's timeline, and a viewer can see the full version +has more. Nothing is rendered again: it is one ffmpeg pass over the finished file. + +A beat is either: + +``` +{ "id": "<clip id>", "start": <source s>, "end": <source s> } a clip's source seconds, as in the manifest +{ "at": <master s>, "dur": <s> } master seconds, as written +``` + +A clip beat is mapped with the take's build records. `out/sourced/schedule.json` gives the +segment's start in the cut. `out/sourced/segments/<id>.cut.json` gives the source second the +segment really starts at (snapped to a silence, room included). Source second *s* plays at master +second `segment.start + (s − cut.start)`. `--intro` opens on the master's brand intro. +`--finale S` closes on the master's last *S* seconds, where the finale's timeline is. + +- **The master's own crossfades.** Each join of the master is a `render.transition`-second + dissolve. If a beat's edge falls inside one, the edge is moved in, but only until the trailer's + own crossfade hides what is left. Each moved edge is printed as a note. +- **Seamless runs.** If a piece starts inside the piece before it, or where it ends, the two are + one run of the master with no crossfade, and no frame plays twice. This happens with the intro + and a first beat in the first clip, and with a last beat and the finale. +- **What it refuses.** A clip the take's cut does not have, a beat outside the source seconds + its segment was cut from, a take with no build, and a master whose length is not the cut its + records describe (rebuilt since, or a window take). + +The pieces are joined with `--xfade` crossfades (picture and sound, 0.3 s by default; `0` gives +hard cuts). They are cut on exact frames (decoded, never stream-copied) and encoded with the +take's `render.crf`, `render.preset` and `render.audioBitrate`. The run takes the heavy slot with +a declared memory estimate. The output is `takes/<t>/out/<slug>.trailer.mp4` (`--out NAME` puts +that name in the same folder; a path puts it exactly there). Beside it, `<name>.trailer.json` +records each piece's master span, its source seconds (as asked and as cut), the edges moved, the +master it came from and the encode time. The command prints the mapped spans and the total +length; `--dry-run` prints them and writes nothing, and `--json` is for agents. + ## Montages (`render.montage`) A cut of one phrase said many times — every "slow news day" — is a montage, and diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -0,0 +1,157 @@ +// `umtool trailer` (2026-10-26): a trailer cut from a finished take's master, +// so the deck on screen shows the whole video's timeline. The cutting is +// report-to-video/trailer.mjs; this is the command line around it. +// +// umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) +// [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json] +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { takesDirOf } from "./takes.mjs"; +import { + TRAILER_ESTIMATE_MB, + TRAILER_XFADE_DEFAULT, + TrailerError, + describePlan, + makeTrailer, + parseBeats, +} from "umtool-report-to-video/trailer"; + +export const TRAILER_USAGE = [ + "usage: umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON)", + ` [--intro] [--finale S] [--xfade ${TRAILER_XFADE_DEFAULT}] [--out NAME] [--dry-run] [--json]`, + "", + "A trailer cut from the take's finished master (takes/<t>/out/<slug>.mp4): spans of the master's own", + "frames, so the deck's rail, dates and tallies show the whole video's timeline. Nothing is rendered again.", + "A beat is { \"id\": \"<clip>\", \"start\": <source s>, \"end\": <source s> } (mapped to the master by the", + "take's build records) or { \"at\": <master s>, \"dur\": <s> }. --intro opens on the master's brand intro;", + "--finale S closes on its last S seconds. Joined with S-second crossfades (--xfade 0: hard cuts),", + "encoded with the take's render settings, in the heavy slot. Writes takes/<t>/out/<slug>.trailer.mp4", + "(--out NAME: that name there; a path: exactly there) and <name>.trailer.json beside it, what was cut.", + "--dry-run prints the mapping and writes nothing.", +].join("\n"); + +class CliError extends Error {} + +function parse(args) { + const valued = new Set(["--take", "--beats", "--beats-json", "--finale", "--xfade", "--out"]); + /** @type {Record<string, string>} */ + const flags = {}; + const positional = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a.startsWith("--")) { + if (valued.has(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags[a] = args[++i]; + } else if (["--intro", "--json", "--dry-run", "--help"].includes(a)) flags[a] = ""; + else throw new CliError(`unknown flag ${a}`); + } else positional.push(a); + } + return { flags, positional, has: (n) => n in flags }; +} + +async function beatsOf(p) { + if (p.has("--beats") && p.has("--beats-json")) throw new CliError("--beats or --beats-json, not both"); + let value; + if (p.has("--beats")) { + const file = p.flags["--beats"]; + try { + value = JSON.parse(await readFile(path.resolve(file), "utf8")); + } catch (err) { + throw new CliError(`--beats ${file}: ${err instanceof Error ? err.message : err}`); + } + } else if (p.has("--beats-json")) { + try { + value = JSON.parse(p.flags["--beats-json"]); + } catch (err) { + throw new CliError(`--beats-json: ${err instanceof Error ? err.message : err}`); + } + } else if (p.has("--intro") || p.has("--finale")) { + value = { beats: [] }; + } else throw new CliError("--beats FILE or --beats-json JSON: the trailer's beats"); + if (Array.isArray(value?.beats ?? value) && !(value?.beats ?? value).length) return []; + return parseBeats(value); +} + +function seconds(p, flag, fallback) { + if (!p.has(flag)) return fallback; + const n = Number(p.flags[flag]); + if (!Number.isFinite(n) || n < 0) throw new CliError(`${flag} ${p.flags[flag]}: seconds ≥ 0`); + return n; +} + +/** + * The heavy slot, loaded at run time from the report-to-video package (never + * a module the umtool app bundles): `withRenderSlot` with the trailer's + * declared estimate. An older gate ignores the estimate and runs it alone. + */ +async function realSlot() { + const gate = new URL("./heavy-gate.mjs", import.meta.resolve("umtool-report-to-video/package.json")).href; + const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); + return (cmd) => (fn) => withRenderSlot(cmd, fn, { estimateMb: TRAILER_ESTIMATE_MB }); +} + +/** + * `umtool trailer …` + * @param {string[]} args everything after `trailer` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, any> }} [opts] + * @returns {Promise<number>} + */ +export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps = {} } = {}) { + try { + const p = parse(args); + if (p.has("--help") || !p.positional.length) { + log(TRAILER_USAGE); + return p.has("--help") ? 0 : 2; + } + const r = await resolveProject(p.positional[0], reportsRoot); + if (r.ambiguous) throw new CliError(`"${p.positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${p.positional[0]}"`); + if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + const take = p.flags["--take"]; + if (!take) throw new CliError("--take <t>: the finished take to cut the trailer from"); + if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); + const beats = await beatsOf(p); + const takeDir = path.join(takesDirOf(r.project.dir), take); + const json = p.has("--json"); + const slotFor = deps.slot ?? (await realSlot()); + const res = await makeTrailer({ + takeDir, + beats, + intro: p.has("--intro"), + finale: p.has("--finale") ? seconds(p, "--finale", null) : null, + xfade: seconds(p, "--xfade", TRAILER_XFADE_DEFAULT), + out: p.flags["--out"] ?? null, + dryRun: p.has("--dry-run"), + ...(deps.run ? { run: deps.run } : {}), + ...(deps.probe ? { probe: deps.probe } : {}), + slot: (fn) => { + if (!json) err(`trailer: encoding ${res0(beats)} in the heavy slot …`); + return slotFor(["umtool", "trailer", r.project.id, "--take", take])(fn); + }, + }); + if (json) { + log(JSON.stringify({ + project: r.project.id, 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, + }, null, 2)); + return 0; + } + for (const line of describePlan(res.plan)) log(line); + for (const n of res.plan.notes) log(`note: ${n}`); + if (res.dryRun) log(`dry run: would write ${res.outPath}`); + else log(`wrote ${res.outPath} (${res.encodeSeconds} s to encode) and ${path.basename(res.recordPath)}`); + return 0; + } catch (e) { + if (e instanceof CliError || e instanceof TrailerError) { + err(`umtool trailer: ${e.message}`); + return e instanceof CliError ? 2 : 1; + } + throw e; + } +} + +const res0 = (beats) => `${beats.length} beat${beats.length === 1 ? "" : "s"}`; diff --git a/umtool/lib/report/trailerCli.test.mjs b/umtool/lib/report/trailerCli.test.mjs @@ -0,0 +1,115 @@ +// `umtool trailer`: the command line over report-to-video/trailer.mjs, on a +// fixture project (the encode and the slot stubbed). +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 { PROJECT_KINDS } from "../projects/kinds.mjs"; +import { trailerCommand } from "./trailerCli.mjs"; + +const TAKES_KIND = PROJECT_KINDS.find((k) => k.makesTakes).id; +const SCHEDULE = { + fps: 30, transition: 0.5, total: 20.167, + segments: [ + { id: "brand-intro", type: "intro", start: 0, duration: 4.167 }, + { id: "c1", type: "clip", start: 3.667, duration: 16.5 }, + ], +}; + +async function project() { + const root = await mkdtemp(path.join(tmpdir(), "trailercli-")); + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "proj"); + const take = path.join(dir, "takes", "final"); + await mkdir(path.join(take, "out", "sourced", "segments"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "cut", render: { fps: 30 }, timeline: [] })); + await writeFile(path.join(dir, "project.json"), JSON.stringify({ kind: TAKES_KIND, title: "Proj" })); + await writeFile(path.join(take, "video.manifest.json"), JSON.stringify({ slug: "cut", render: { fps: 30, crf: 21, preset: "slow" } })); + await writeFile(path.join(take, "out", "cut.mp4"), "master"); + await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(SCHEDULE)); + await writeFile(path.join(take, "out", "sourced", "segments", "c1.cut.json"), JSON.stringify({ id: "c1", start: 50, end: 66.5 })); + return { root, reportsRoot, take }; +} + +function io() { + const out = []; + const errs = []; + return { out, errs, log: (s) => out.push(s), err: (s) => errs.push(s) }; +} + +const deps = (ran) => ({ + slot: () => (fn) => fn(), + probe: async () => 20.167, + run: async (argv) => { ran.push(argv); await writeFile(argv.at(-1), "trailer"); }, +}); + +test("umtool trailer: cuts, prints the mapping and the total, writes the record", async () => { + const { root, reportsRoot, take } = await project(); + try { + const ran = []; + const o = io(); + const code = await trailerCommand( + ["proj", "--take", "final", "--beats-json", JSON.stringify([{ id: "c1", start: 55, end: 60 }]), "--intro", "--finale", "2"], + { reportsRoot, log: o.log, err: o.err, deps: deps(ran) }, + ); + assert.equal(code, 0, o.errs.join("\n")); + assert.equal(ran.length, 1); + assert.match(o.out.join("\n"), /c1 +source 55\.00–60\.00/); + assert.match(o.out.join("\n"), /^total 0:/m); + assert.match(o.out.join("\n"), /wrote .*cut\.trailer\.mp4/); + const rec = JSON.parse(await readFile(path.join(take, "out", "cut.trailer.json"), "utf8")); + assert.equal(rec.pieces.length, 3); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("umtool trailer --beats FILE --json --dry-run: the plan for an agent, nothing encoded", async () => { + const { root, reportsRoot } = await project(); + try { + const file = path.join(root, "beats.json"); + await writeFile(file, JSON.stringify([{ id: "c1", start: 55, end: 60 }, { at: 15, dur: 2 }])); + const ran = []; + const o = io(); + const code = await trailerCommand(["proj", "--take", "final", "--beats", file, "--json", "--dry-run"], { reportsRoot, log: o.log, err: o.err, deps: deps(ran) }); + assert.equal(code, 0, o.errs.join("\n")); + assert.equal(ran.length, 0); + const doc = JSON.parse(o.out.join("\n")); + assert.equal(doc.out, null); + assert.match(doc.wouldWrite, /cut\.trailer\.mp4$/); + assert.deepEqual(doc.pieces.map((p) => p.kind), ["clip", "raw"]); + assert.ok(doc.seconds > 6.5 && doc.seconds < 7); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("umtool trailer: refusals exit 1 by name; usage mistakes exit 2", async () => { + const { root, reportsRoot } = await project(); + try { + const run = (args) => { + const o = io(); + return trailerCommand(args, { reportsRoot, log: o.log, err: o.err, deps: deps([]) }).then((code) => ({ code, err: o.errs.join("\n") })); + }; + let r = await run(["proj", "--take", "final", "--beats-json", JSON.stringify([{ id: "zz", start: 1, end: 2 }])]); + assert.equal(r.code, 1); + assert.match(r.err, /no clip "zz"/); + r = await run(["proj", "--take", "nope", "--beats-json", JSON.stringify([{ id: "c1", start: 55, end: 56 }])]); + assert.equal(r.code, 1); + assert.match(r.err, /not a take/); + r = await run(["proj", "--beats-json", "[]"]); + assert.equal(r.code, 2); + assert.match(r.err, /--take <t>/); + r = await run(["proj", "--take", "final"]); + assert.equal(r.code, 2); + assert.match(r.err, /--beats FILE or --beats-json/); + r = await run(["proj", "--take", "final", "--beats", path.join(root, "missing.json")]); + assert.equal(r.code, 2); + r = await run(["proj", "--take", "final", "--bogus"]); + assert.equal(r.code, 2); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -58,6 +58,7 @@ "./social": "./social.mjs", "./sources": "./sources.mjs", "./sync-report": "./sync-report.mjs", + "./trailer": "./trailer.mjs", "./transition": "./transition.mjs", "./variants": "./variants.mjs", "./verify-build": "./verify-build.mjs", diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -0,0 +1,561 @@ +// A TRAILER CUT FROM THE MASTER (`umtool trailer`, 2026-10-26). +// +// A trailer used to be a take of its own: a short cut of a dozen clips, with +// its own short rail, so the deck said the video was two minutes long. This +// cuts the trailer out of a FINISHED master render instead -- spans of the +// master's own frames -- so the rail, the dates, the pips and the running +// tallies on screen are the whole video's, and the viewer sees how much more +// the full version holds. Nothing is rendered again: it is one ffmpeg pass +// over a finished file, in minutes. +// +// A beat names what plays, in one of two ways: +// +// { "id": "<clip id>", "start": <source s>, "end": <source s> } +// source seconds of that clip, as the manifest writes them. Mapped to +// master time with the take's own build records: the segment's place +// in the cut (`out/sourced/schedule.json`, `segments[{id,start,duration}]`) +// and the source second its file really starts at (`segments/<id>.cut.json`, +// `start`: snapped to a silence, room included). A segment's frame at +// local second τ plays at master second `segment.start + τ`, and its +// local second τ is source second `cut.start + τ` -- a hold only +// lengthens the segment's END, so it moves nothing before it. +// { "at": <master s>, "dur": <s> } +// raw master time, taken as written. +// +// THE MASTER'S OWN CROSSFADES. Each join of the master is a dissolve of +// `transition` seconds: segment i's first D seconds are blended with the +// segment before it (they start at schedule.start, which is already D before +// the previous segment's end), its last D with the one after. A clip beat that +// reaches into one would put a blend of two clips on screen, so its edge is +// pulled in -- but only as far as the TRAILER's own crossfade at that edge +// does not hide it: with the trailer dissolving over x seconds, a beat may +// start D − x into its segment and the master's blend is under the trailer's. +// Pulled-in edges are said, never silent (`notes`). +// +// The spans are cut frame-accurately (decoded, never stream-copied) in ONE +// ffmpeg pass: each run of the master is a `movie` source inside the +// filtergraph, decoded only when the chain reaches it (separate `-i` inputs +// decode ahead and the waiting frames took 5.6 GB), trimmed by the master's +// own timestamps half a frame either side of its frame boundaries (the +// picture) and at its first frame (the sound, sample-exact). They are joined +// with the master's own encode settings (build-video's encodeArgs over the +// take's `render`): crossfaded (xfade + acrossfade, the sound pinned to the +// picture's length as build-video's join pins it), or hard-cut through +// `concat` when the crossfade is 0. +// +// The run takes the machine's heavy slot (heavy-gate.mjs) with a declared +// memory estimate: the CLI (lib/report/trailerCli.mjs) loads the gate, never +// this module, so the umtool app can import it without the gate in its bundle. + +import { execFile } from "node:child_process"; +import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; + +import { encodeArgs } from "./build-video.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; + +/** The trailer's crossfade, in seconds, when none is given. */ +export const TRAILER_XFADE_DEFAULT = 0.3; + +/** + * The memory the one ffmpeg pass is declared to need in the heavy slot (MB): + * measured 3.4 GB peak on the Huck trailer (14 runs of a 1080p master, x264 + * `slow`), with room above it. + */ +export const TRAILER_ESTIMATE_MB = 4000; + +/** Each run's decoder threads: every source is open at once, so each is kept small. */ +export const TRAILER_DECODE_THREADS = 2; + +/** How far before a run its source seeks (to the keyframe at or before it): the trim cuts on the frame. */ +const PRE_ROLL = 1; + +/** A source second this close to a cut's edge is on it (the records keep three decimals). */ +const EPS = 0.02; + +/** A refusal: said by name, exit 1, nothing written. */ +export class TrailerError extends Error {} + +const r3 = (n) => Number(n.toFixed(3)); +const fmt = (n) => n.toFixed(2); + +/** Seconds as m:ss.s, for the printed plan. */ +export function clock(s) { + const m = Math.floor(s / 60); + const rest = s - m * 60; + return `${m}:${rest < 10 ? "0" : ""}${rest.toFixed(1)}`; +} + +/** + * The beats, checked: an array, or `{ beats: [...] }`. A clip beat is + * `{ id, start, end }`, a raw one `{ at, dur }`; anything else is refused by + * its place in the list. An optional `label` is carried through to the record. + */ +export function parseBeats(value) { + const list = Array.isArray(value) ? value : Array.isArray(value?.beats) ? value.beats : null; + if (!list) throw new TrailerError("beats: a JSON array of beats, or { \"beats\": [...] }"); + if (!list.length) throw new TrailerError("beats: the list is empty"); + return list.map((b, i) => { + const where = `beat ${i + 1}`; + if (!b || typeof b !== "object" || Array.isArray(b)) throw new TrailerError(`${where}: not an object`); + const label = typeof b.label === "string" ? b.label : undefined; + const num = (k) => typeof b[k] === "number" && Number.isFinite(b[k]); + if (b.id !== undefined) { + if (typeof b.id !== "string" || !b.id) throw new TrailerError(`${where}: id is a clip id (a string)`); + if (!num("start") || !num("end")) throw new TrailerError(`${where} (${b.id}): start and end are source seconds (numbers)`); + if (b.end <= b.start) throw new TrailerError(`${where} (${b.id}): end ${b.end} is not after start ${b.start}`); + return { kind: "clip", id: b.id, start: b.start, end: b.end, ...(label ? { label } : {}) }; + } + if (b.at !== undefined || b.dur !== undefined) { + if (!num("at") || !num("dur")) throw new TrailerError(`${where}: at and dur are master seconds (numbers)`); + if (b.at < 0 || b.dur <= 0) throw new TrailerError(`${where}: at ≥ 0 and dur > 0`); + return { kind: "raw", at: b.at, dur: b.dur, ...(label ? { label } : {}) }; + } + throw new TrailerError(`${where}: { "id", "start", "end" } (a clip's source seconds) or { "at", "dur" } (master seconds)`); + }); +} + +/** + * Each segment's span in the master, by id: `{ id, type, index, start, end }`. + * `end` is the schedule's own (a deck schedule writes it), else start + + * duration, else where the next segment's crossfade ends (a rail schedule + * writes starts only), else the cut's total. + */ +export function scheduleSpans(schedule) { + const segs = schedule?.segments; + if (!Array.isArray(segs) || !segs.length) throw new TrailerError("schedule.json lists no segments"); + const D = Number(schedule.transition) || 0; + const total = Number(schedule.total); + const spans = new Map(); + segs.forEach((s, i) => { + const next = segs[i + 1]; + const end = Number.isFinite(s.end) ? s.end + : Number.isFinite(s.duration) ? s.start + s.duration + : next ? next.start + D : total; + spans.set(s.id, { id: s.id, type: s.type ?? null, index: i, start: s.start, end }); + }); + return { spans, count: segs.length, D, total, fps: Number(schedule.fps) || 30 }; +} + +/** The brand intro's span: the segment of type "intro" (the build names it brand-intro). */ +function introSpan(spans) { + for (const s of spans.values()) if (s.type === "intro" || s.id === "brand-intro") return s; + return null; +} + +/** + * The trailer's plan, pure: every piece's master span, frame-aligned, with + * where it lands in the trailer and the total. + * + * @param {object} a + * @param {object} a.schedule the take's `out/sourced/schedule.json` + * @param {Map<string, object>} a.records each clip segment's cut record, by id + * @param {object[]} a.beats parseBeats's + * @param {boolean} [a.intro] prepend the master's brand intro + * @param {number|null} [a.finale] append the master's last S seconds + * @param {number} [a.xfade] the trailer's crossfade (0: hard cuts) + */ +export function planTrailer({ schedule, records, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT }) { + const { spans, count, D, total, fps } = scheduleSpans(schedule); + if (!Number.isFinite(total) || total <= 0) throw new TrailerError("schedule.json has no total"); + if (!Number.isFinite(xfade) || xfade < 0) throw new TrailerError(`--xfade ${xfade}: seconds ≥ 0`); + const frame = (t) => Math.round(t * fps) / fps; + const x = frame(xfade); + const notes = []; + + // The pieces as asked, in trailer order, before any edge is pulled in. + const want = []; + if (intro) { + const s = introSpan(spans); + if (!s) throw new TrailerError("--intro: this take's cut has no brand intro (no segment of type \"intro\" in schedule.json)"); + want.push({ kind: "intro", id: s.id, seg: s, a: s.start, b: s.end }); + } + beats.forEach((beat, n) => { + if (beat.kind === "raw") { + if (beat.at + beat.dur > total + EPS) { + throw new TrailerError(`beat ${n + 1}: ${fmt(beat.at)}+${fmt(beat.dur)} s runs past the master's end (${fmt(total)} s)`); + } + want.push({ kind: "raw", beat, a: beat.at, b: Math.min(total, beat.at + beat.dur) }); + return; + } + const seg = spans.get(beat.id); + if (!seg) throw new TrailerError(`beat ${n + 1}: no clip "${beat.id}" in this take's cut (schedule.json)`); + const rec = records.get(beat.id); + if (!rec || !Number.isFinite(rec.start) || !Number.isFinite(rec.end)) { + throw new TrailerError(`beat ${n + 1}: "${beat.id}" has no cut record with source seconds (segments/${beat.id}.cut.json) — a card, or built before records; use { "at", "dur" }`); + } + if (beat.start < rec.start - EPS || beat.end > rec.end + EPS) { + throw new TrailerError( + `beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} is outside the source seconds its segment was cut from, ${rec.start}–${rec.end}`, + ); + } + const s = Math.max(beat.start, rec.start); + const e = Math.min(beat.end, rec.end); + want.push({ kind: "clip", id: beat.id, beat, rec, seg, a: seg.start + (s - rec.start), b: seg.start + (e - rec.start) }); + }); + if (finale != null) { + if (!Number.isFinite(finale) || finale <= 0) throw new TrailerError(`--finale ${finale}: seconds > 0`); + if (finale > total) throw new TrailerError(`--finale ${finale}: the master is ${fmt(total)} s`); + want.push({ kind: "finale", a: total - finale, b: total }); + } + if (!want.length) throw new TrailerError("nothing to cut: no beats, no --intro, no --finale"); + + // A piece that starts inside the one before it, or where it ends (the brand + // intro and the clip after it; a closing beat and the finale), is the same + // run of the master: it is joined SEAMLESSLY -- the earlier piece ends on + // the frame the later one starts on, no crossfade of the trailer's, and the + // master's own dissolve between them plays as it does in the master. The + // frames are never shown twice. + const n = want.length; + const step = 1 / fps; + const seam = want.map((w, i) => i > 0 && w.a >= want[i - 1].a - 1e-6 && w.a <= want[i - 1].b + step + 1e-6); + for (let i = 1; i < n; i += 1) { + if (!seam[i]) continue; + if (want[i].b < want[i - 1].b) want[i].b = want[i - 1].b; + want[i - 1].b = want[i].a; + } + + // Edges pulled out of the master's own crossfades (see the header), then + // put on frames: a start rounded to its frame, the length a whole count. + const pieces = want.map((w, i) => { + const joinIn = i > 0 && !seam[i]; + const joinOut = i < n - 1 && !seam[i + 1]; + const xIn = joinIn ? x : 0; + const xOut = joinOut ? x : 0; + let { a, b } = w; + const moved = {}; + if (w.seg) { + const lo = Math.max(w.seg.start, w.seg.start + (w.seg.index > 0 ? D : 0) - xIn); + const hi = Math.min(w.seg.end, w.seg.end - (w.seg.index < count - 1 ? D : 0) + xOut); + if (!seam[i] && a < lo - 1e-6) { + moved.start = { from: r3(a), to: r3(lo) }; + a = lo; + } + if (!seam[i + 1] && b > hi + 1e-6) { + moved.end = { from: r3(b), to: r3(hi) }; + b = hi; + } + } + const fa = Math.round(a * fps); + const frames = Math.round(b * fps) - fa; + const name = w.kind === "clip" ? w.id : w.kind === "intro" ? "intro" : w.kind === "finale" ? "finale" : `beat ${i + 1}`; + if (frames < 1 || frames / fps <= xIn + xOut) { + throw new TrailerError( + `${name}: ${fmt(Math.max(0, frames / fps))} s left once it is out of the master's crossfades — too short for ` + + `${xIn || xOut ? `a ${fmt(x)} s crossfade either side` : "a cut"}`, + ); + } + const start = fa / fps; + const duration = frames / fps; + const piece = { + kind: w.kind, + ...(w.id ? { id: w.id } : {}), + ...(w.beat?.label ? { label: w.beat.label } : {}), + master: { start: r3(start), end: r3(start + duration), duration: r3(duration) }, + frames: { start: fa, count: frames }, + ...(seam[i] ? { seamless: true } : {}), + ...(w.kind === "clip" + ? { + source: { + start: r3(w.rec.start + (start - w.seg.start)), + end: r3(w.rec.start + (start + duration - w.seg.start)), + asked: { start: w.beat.start, end: w.beat.end }, + }, + segment: { start: r3(w.seg.start), end: r3(w.seg.end), cut: { start: w.rec.start, end: w.rec.end } }, + } + : {}), + ...(w.kind === "raw" ? { asked: { at: w.beat.at, dur: w.beat.dur } } : {}), + ...(moved.start || moved.end ? { moved } : {}), + }; + if (moved.start) { + notes.push(`${name}: starts at master ${fmt(moved.start.to)}, not ${fmt(moved.start.from)} — the master's crossfade into it runs until ${fmt(w.seg.start + D)}`); + } + if (moved.end) { + notes.push(`${name}: ends at master ${fmt(moved.end.to)}, not ${fmt(moved.end.from)} — the master's crossfade out of it starts at ${fmt(w.seg.end - D)}`); + } + if (seam[i]) { + notes.push(`${pieceName(want[i - 1], i - 1)} runs straight into ${name} (master ${fmt(start)}): one run of the master, no crossfade`); + } + return piece; + }); + + // Where each lands in the trailer: each crossfade overlaps its two pieces. + let acc = 0; + pieces.forEach((p, i) => { + const over = i > 0 && !p.seamless ? x : 0; + p.at = r3(acc - over); + acc = acc + p.frames.count / fps - over; + }); + + // The same master seconds twice: the operator's call, but said. + for (let i = 0; i < pieces.length; i += 1) { + for (let j = i + 1; j < pieces.length; j += 1) { + const lo = Math.max(pieces[i].master.start, pieces[j].master.start); + const hi = Math.min(pieces[i].master.end, pieces[j].master.end); + if (hi - lo > 1 / fps) { + notes.push(`${pieceName(pieces[i], i)} and ${pieceName(pieces[j], j)} share master ${fmt(lo)}–${fmt(hi)} (${fmt(hi - lo)} s): the trailer plays it twice`); + } + } + } + + return { fps, transition: D, xfade: x, masterSeconds: total, pieces, total: r3(acc), notes }; +} + +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}`; +} + +/** + * The runs of the master a plan reads: its pieces, a seamless one folded into + * the run before it (its frames follow on). `{ start, count }` in frames. + */ +export function trailerRuns(plan) { + const runs = []; + for (const p of plan.pieces) { + const last = runs[runs.length - 1]; + if (p.seamless && last) last.count = p.frames.start + p.frames.count - last.start; + else runs.push({ start: p.frames.start, count: p.frames.count }); + } + return runs; +} + +/** + * A file name as a `movie` filter's option inside a filtergraph: escaped for + * the option (`\ ' :`), then for the graph (`\ ' [ ] , ;`), as ffmpeg's + * filtergraph docs say. + */ +export function filterPath(file) { + const opt = String(file).replace(/[\\':]/g, (c) => `\\${c}`); + return opt.replace(/[\\'[\],;]/g, (c) => `\\${c}`); +} + +/** + * The ffmpeg argv for a plan: the whole cut in one filtergraph, one `movie` + * source of the master per run, the master's encode settings. + * + * WHY `movie` AND NOT ONE `-i` PER RUN. ffmpeg reads its `-i` inputs on their + * own threads, as fast as they decode, and the crossfade chain does not need + * the eleventh run for a minute and a half: measured on the Huck trailer + * (14 runs), the frames waiting in the graph took 5.6 GB. A `movie` source + * inside the graph is decoded only when the filter after it asks for a frame, + * so a run is read when the chain reaches it and memory stays flat. + * + * FRAME-ACCURATE BY TIMESTAMP. `movie` seeks to the keyframe at or before + * PRE_ROLL seconds ahead of the run and keeps the master's own timestamps, + * so the picture is trimmed half a frame either side of its frame boundaries + * (exactly the run's frames, whatever the float rounding) and the sound at + * 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 }) { + const { fps, xfade: x } = plan; + const runs = trailerRuns(plan); + const half = 0.5 / fps; + const src = filterPath(master); + const parts = []; + 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]`); + parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS[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}[a${i}]`, + ); + }); + let vlab = "[v0]"; + let alab = "[a0]"; + if (runs.length > 1 && x > 0) { + let acc = runs[0].count / fps; + for (let i = 1; i < runs.length; i += 1) { + const off = acc - x; + parts.push(`${vlab}[v${i}]xfade=transition=fade:duration=${x.toFixed(6)}:offset=${off.toFixed(6)}[xv${i}]`); + parts.push(`${alab}[a${i}]acrossfade=d=${x.toFixed(6)}:c1=tri:c2=tri[xa${i}]`); + vlab = `[xv${i}]`; + alab = `[xa${i}]`; + acc = acc + runs[i].count / fps - x; + } + } else if (runs.length > 1) { + parts.push(`${runs.map((_, i) => `[v${i}][a${i}]`).join("")}concat=n=${runs.length}:v=1:a=1[cv][ca]`); + vlab = "[cv]"; + alab = "[ca]"; + } + return [ + "-nostdin", "-v", "error", "-y", + "-filter_complex", parts.join(";"), + "-map", vlab, "-map", alab, + "-map_metadata", "-1", + ...encodeArgs(render), + outPath, + ]; +} + +/** The record beside a trailer: `<name>.trailer.json` for `<name>.trailer.mp4` or `<name>.mp4`. */ +export function trailerRecordPath(outPath) { + const base = outPath.replace(/\.mp4$/i, "").replace(/\.trailer$/, ""); + return `${base}.trailer.json`; +} + +/** + * Where the trailer goes: `takes/<t>/out/<slug>.trailer.mp4`; `--out NAME` + * (a bare name) in the same directory, `.mp4` added when missing; `--out` a + * path (absolute, or with a slash) exactly there. + */ +export function trailerOutPath(takeDir, slug, out = null) { + const outDir = path.join(takeDir, "out"); + if (!out) return path.join(outDir, `${slug}.trailer.mp4`); + const file = /\.mp4$/i.test(out) ? out : `${out}.mp4`; + if (path.isAbsolute(file) || file.includes("/")) return path.resolve(file); + return path.join(outDir, file); +} + +/** + * A take's finished build, read: its manifest (slug, render), the master, + * the schedule and every segment's cut record. Refused by name when the take + * has no build. + */ +export async function loadTakeBuild(takeDir) { + const manifestFile = path.join(takeDir, "video.manifest.json"); + const manifest = await readFile(manifestFile, "utf8").then(JSON.parse, () => null); + if (!manifest) throw new TrailerError(`${takeDir}: no video.manifest.json — not a take`); + const slug = manifest.slug; + if (!slug) throw new TrailerError(`${manifestFile}: no slug`); + if (!manifest.render?.fps) throw new TrailerError(`${manifestFile}: no render settings`); + const master = path.join(takeDir, "out", `${slug}.mp4`); + const work = path.join(takeDir, "out", "sourced"); + const schedule = await readFile(path.join(work, "schedule.json"), "utf8").then(JSON.parse, () => null); + if (!schedule) throw new TrailerError(`${path.basename(takeDir)} has no build: no out/sourced/schedule.json (render the take with the deck first)`); + const segDir = path.join(work, "segments"); + const records = new Map(); + const names = await readdir(segDir).catch(() => []); + for (const name of names) { + if (!name.endsWith(".cut.json")) continue; + const rec = await readFile(path.join(segDir, name), "utf8").then(JSON.parse, () => null); + if (rec) records.set(name.slice(0, -".cut.json".length), rec); + } + return { manifest, slug, render: manifest.render, master, schedule, records }; +} + +/** The master's length in seconds (its frames over the fps), or null when it cannot be read. */ +export async function probeMasterSeconds(file, fps) { + try { + const { stdout } = await execFileP(FFPROBE(), [ + "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=nb_frames:format=duration", + "-of", "json", file, + ]); + const j = JSON.parse(stdout); + const n = Number(j.streams?.[0]?.nb_frames); + if (Number.isFinite(n) && n > 0 && fps) return n / fps; + const d = Number(j.format?.duration); + return Number.isFinite(d) ? d : null; + } catch { + return null; + } +} + +/** ffmpeg, run: resolves when it exits 0, rejects with its stderr's tail. */ +export async function runFfmpeg(argv) { + try { + await execFileP(FFMPEG(), argv, { maxBuffer: 1 << 26 }); + } catch (err) { + const tail = String(err?.stderr ?? err?.message ?? err).trim().split("\n").slice(-6).join("\n"); + throw new Error(`ffmpeg failed: ${tail}`); + } +} + +/** + * Cut a trailer from a take's master. + * + * @param {object} a + * @param {string} a.takeDir `takes/<t>/` + * @param {object[]} a.beats parseBeats's + * @param {boolean} [a.intro] + * @param {number|null} [a.finale] + * @param {number} [a.xfade] + * @param {string|null} [a.out] --out + * @param {boolean} [a.dryRun] the plan only: nothing encoded, nothing written + * @param {(argv: string[]) => Promise<void>} [a.run] the ffmpeg runner (tests stub it) + * @param {(file: string, fps: number) => Promise<number|null>} [a.probe] + * @param {(fn: () => Promise<any>) => Promise<any>} [a.slot] the heavy slot around the encode + * @param {() => number} [a.now] + */ +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, +}) { + const build = await loadTakeBuild(takeDir); + const plan = planTrailer({ schedule: build.schedule, records: build.records, beats, intro, finale, xfade }); + 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) { + throw new TrailerError( + `${build.master} is ${fmt(masterSeconds)} s but its build records describe a ${fmt(plan.masterSeconds)} s cut — ` + + "the master is not the build these records are from (rebuilt since, or a window take)", + ); + } + const outPath = trailerOutPath(takeDir, build.slug, out); + if (path.resolve(outPath) === path.resolve(build.master)) throw new TrailerError(`--out ${out}: that is the master`); + const recordPath = trailerRecordPath(outPath); + const record = { + version: 1, + kind: "trailer", + source: { + take: path.basename(takeDir), + master: build.master, + masterSeconds: r3(masterSeconds), + schedule: path.join(takeDir, "out", "sourced", "schedule.json"), + }, + xfade: plan.xfade, + transition: plan.transition, + fps: plan.fps, + encode: { crf: build.render.crf ?? 20, preset: build.render.preset ?? "medium", audioBitrate: build.render.audioBitrate ?? "160k" }, + seconds: plan.total, + pieces: plan.pieces, + 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 }); + // 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; + await slot(async () => { + const t0 = now(); + try { + await run(argv); + await rename(tmp, outPath); + } catch (err) { + await rm(tmp, { force: true }); + throw err; + } + encodeSeconds = r3((now() - t0) / 1000); + }); + record.builtAt = new Date(now()).toISOString(); + record.encodeSeconds = encodeSeconds; + record.out = outPath; + await writeFile(recordPath, JSON.stringify(record, null, 2) + "\n"); + return { plan, outPath, recordPath, record, encodeSeconds, dryRun: false }; +} + +/** The printed plan: one line per piece, then the total. */ +export function describePlan(plan) { + const lines = plan.pieces.map((p, i) => { + const what = p.kind === "clip" + ? `${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)}`; + return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.master.duration)} s${p.moved ? " (edge moved)" : ""}`; + }); + lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces, crossfade ${fmt(plan.xfade)} s`); + return lines; +} diff --git a/umtool/report-to-video/trailer.test.mjs b/umtool/report-to-video/trailer.test.mjs @@ -0,0 +1,305 @@ +// trailer.mjs: a trailer cut from a finished master. The mapping (a clip's +// source seconds → master seconds by the take's own records), the edges kept +// out of the master's crossfades, the seamless runs, the refusals, the +// ffmpeg graph's shape, and the run (the runner stubbed). +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + TrailerError, + filterPath, + loadTakeBuild, + makeTrailer, + parseBeats, + planTrailer, + scheduleSpans, + trailerArgs, + trailerOutPath, + trailerRecordPath, + trailerRuns, +} from "./trailer.mjs"; + +// A master of four segments, 30 fps, 0.5 s dissolves: the brand intro, then +// three clips. Each starts where the last one's dissolve begins. +const SCHEDULE = { + version: 1, kind: "deck", fps: 30, transition: 0.5, total: 40.167, + segments: [ + { id: "brand-intro", type: "intro", start: 0, duration: 4.167, end: 4.167 }, + { id: "c1", type: "clip", start: 3.667, duration: 12, end: 15.667 }, + { id: "c2", type: "clip", start: 15.167, duration: 10, end: 25.167 }, + { id: "c3", type: "clip", start: 24.667, duration: 15.5, end: 40.167 }, + ], +}; +// c1 was cut from source 100.2 (snapped), c2 from 500, c3 from 2000. +const RECORDS = new Map([ + ["c1", { version: 1, id: "c1", start: 100.2, end: 112.2, snapped: { start: true, end: true } }], + ["c2", { version: 1, id: "c2", start: 500, end: 510 }], + ["c3", { version: 1, id: "c3", start: 2000, end: 2015.5 }], +]); +const plan = (beats, o = {}) => planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: parseBeats(beats), ...o }); +const close = (a, b, eps = 1 / 60) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b}`); + +test("a clip beat lands at segment.start + (source − the cut record's snapped start), on a frame", () => { + const p = plan([{ id: "c1", start: 104.2, end: 108.2 }]); + const [c] = p.pieces; + // 3.667 + (104.2 − 100.2) = 7.667: frame 230. + assert.equal(c.frames.start, 230); + assert.equal(c.frames.count, 120); + close(c.master.start, 7.667); + close(c.master.end, 11.667); + close(c.source.start, 104.2); + assert.equal(c.at, 0); + assert.equal(p.total, 4); + assert.deepEqual(p.notes, []); +}); + +test("the snapped start is what counts, not the manifest's: the same beat moves with the record", () => { + const records = new Map(RECORDS); + records.set("c1", { ...RECORDS.get("c1"), start: 100.5 }); + const p = planTrailer({ schedule: SCHEDULE, records, beats: parseBeats([{ id: "c1", start: 104.2, end: 108.2 }]) }); + close(p.pieces[0].master.start, 3.667 + 3.7); +}); + +test("an edge inside the master's crossfade is pulled in only as far as the trailer's crossfade hides it", () => { + // c2's first 0.5 s (15.167–15.667) is the master's dissolve from c1. Second + // piece, so a 0.3 s trailer crossfade covers its first 0.3 s: it may start + // at 15.167 + 0.5 − 0.3 = 15.367 (source 500.2), not before. + const p = plan([{ id: "c1", start: 104, end: 106 }, { id: "c2", start: 500.05, end: 505 }], { xfade: 0.3 }); + const c2 = p.pieces[1]; + close(c2.master.start, 15.367); + close(c2.source.start, 500.2); + assert.ok(c2.moved?.start); + assert.match(p.notes.join("\n"), /c2: starts at master 15\.37, not 15\.22/); + // Hard cuts: nothing hides the dissolve, so all of it is skipped. + const hard = plan([{ id: "c1", start: 104, end: 106 }, { id: "c2", start: 500.05, end: 505 }], { xfade: 0 }); + close(hard.pieces[1].master.start, 15.667); + // The FIRST piece has no crossfade in: the whole dissolve is skipped. + const first = plan([{ id: "c2", start: 500.05, end: 505 }]); + close(first.pieces[0].master.start, 15.667); +}); + +test("the end is kept out of the master's dissolve into the next segment the same way", () => { + // c1's last 0.5 s (15.167–15.667) dissolves into c2; a middle piece may end 0.3 s into it. + const p = plan([{ id: "c1", start: 110, end: 112.2 }, { id: "c3", start: 2001, end: 2003 }]); + close(p.pieces[0].master.end, 15.467); + assert.ok(p.pieces[0].moved?.end); + // The last piece has no crossfade out. + const last = plan([{ id: "c1", start: 110, end: 112.2 }]); + close(last.pieces[0].master.end, 15.167); +}); + +test("pieces overlap by the crossfade: each lands at the running total less one crossfade", () => { + const p = plan([{ id: "c1", start: 104, end: 108 }, { id: "c3", start: 2001, end: 2004 }, { id: "c2", start: 502, end: 504 }]); + assert.deepEqual(p.pieces.map((x) => x.at), [0, 3.7, 6.4]); + close(p.total, 4 + 3 + 2 - 0.6, 1e-6); +}); + +test("--intro opens on the brand intro and runs SEAMLESSLY into a beat that starts inside it", () => { + const p = plan([{ id: "c1", start: 100.3, end: 104 }], { intro: true }); + const [intro, c1] = p.pieces; + assert.equal(intro.kind, "intro"); + assert.equal(intro.master.start, 0); + // c1's beat starts at master 3.767, inside the intro (0–4.167): one run of the master. + assert.equal(c1.seamless, true); + assert.equal(intro.frames.start + intro.frames.count, c1.frames.start); + assert.equal(c1.at, intro.master.duration); + assert.equal(c1.moved, undefined, "a seam pulls no edge in: the master's own dissolve plays"); + assert.deepEqual(trailerRuns(p), [{ start: 0, count: c1.frames.start + c1.frames.count }]); + assert.match(p.notes.join("\n"), /intro runs straight into c1/); +}); + +test("--intro before a beat elsewhere ends where the master's dissolve out of it is hidden", () => { + const p = plan([{ id: "c3", start: 2002, end: 2005 }], { intro: true }); + close(p.pieces[0].master.end, 4.167 - 0.5 + 0.3); + assert.equal(p.pieces[1].seamless, undefined); +}); + +test("--finale S closes on the master's last S seconds; a beat it starts inside runs on into it, never twice", () => { + const p = plan([{ id: "c1", start: 104, end: 106 }], { finale: 5 }); + const fin = p.pieces.at(-1); + assert.equal(fin.kind, "finale"); + close(fin.master.start, 35.167); + close(fin.master.end, 40.167); + // c3 2010–2014 is master 34.667–38.667; the finale starts at 35.167, inside it. + const q = plan([{ id: "c3", start: 2010, end: 2014 }], { finale: 5 }); + assert.equal(q.pieces[1].seamless, true); + close(q.pieces[0].master.end, 35.167); + assert.equal(trailerRuns(q).length, 1); + assert.ok(!q.notes.some((n) => /twice/.test(n))); +}); + +test("the same master seconds twice, not adjacent, are said", () => { + const p = plan([{ id: "c1", start: 104, end: 108 }, { id: "c3", start: 2001, end: 2004 }, { id: "c1", start: 106, end: 109 }]); + assert.match(p.notes.join("\n"), /c1 and c1 share master .*twice/); +}); + +test("a raw beat is master seconds as written", () => { + const p = plan([{ at: 20, dur: 3 }]); + assert.equal(p.pieces[0].kind, "raw"); + close(p.pieces[0].master.start, 20); + assert.equal(p.pieces[0].frames.count, 90); +}); + +test("refusals, by name", () => { + assert.throws(() => plan([{ id: "nope", start: 1, end: 2 }]), (e) => e instanceof TrailerError && /no clip "nope"/.test(e.message)); + assert.throws(() => plan([{ id: "c1", start: 99, end: 104 }]), /c1 99–104 is outside the source seconds its segment was cut from, 100\.2–112\.2/); + assert.throws(() => plan([{ id: "c1", start: 110, end: 113 }]), /outside the source seconds/); + assert.throws( + () => planTrailer({ schedule: SCHEDULE, records: new Map(), beats: parseBeats([{ id: "c1", start: 104, end: 105 }]) }), + /"c1" has no cut record with source seconds/, + ); + assert.throws(() => plan([{ at: 39, dur: 3 }]), /runs past the master's end/); + assert.throws(() => plan([{ id: "c1", start: 104, end: 106 }, { id: "c2", start: 503, end: 503.5 }, { id: "c3", start: 2001, end: 2003 }]), /c2: 0\.50 s left .* too short for a 0\.30 s crossfade either side/); + assert.throws(() => plan([{ id: "c1", start: 104, end: 106 }], { finale: 99 }), /--finale 99: the master is 40\.17 s/); + const noIntro = { ...SCHEDULE, segments: SCHEDULE.segments.slice(1) }; + assert.throws(() => planTrailer({ schedule: noIntro, records: RECORDS, beats: [], intro: true }), /no brand intro/); + assert.throws(() => planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: [] }), /nothing to cut/); +}); + +test("parseBeats: a list or { beats }, each a clip beat or a raw one, refused by place", () => { + assert.equal(parseBeats({ beats: [{ at: 1, dur: 2 }] })[0].kind, "raw"); + assert.equal(parseBeats([{ id: "x", start: 1, end: 2, label: "L" }])[0].label, "L"); + assert.throws(() => parseBeats("x"), /a JSON array of beats/); + assert.throws(() => parseBeats([]), /empty/); + assert.throws(() => parseBeats([{ id: "x", start: 2, end: 1 }]), /beat 1 \(x\): end 1 is not after start 2/); + assert.throws(() => parseBeats([{ at: 1, dur: 1 }, { id: "x", start: "1", end: 2 }]), /beat 2 \(x\): start and end are source seconds/); + assert.throws(() => parseBeats([{ start: 1 }]), /beat 1: \{ "id", "start", "end" \}/); +}); + +test("scheduleSpans: a rail schedule (starts only) ends each segment where the next one's dissolve ends", () => { + const { spans } = scheduleSpans({ fps: 30, transition: 0.5, total: 20, segments: [{ id: "a", start: 0 }, { id: "b", start: 9.5 }] }); + assert.equal(spans.get("a").end, 10); + assert.equal(spans.get("b").end, 20); +}); + +test("the ffmpeg graph: one movie source per run, trimmed by the master's timestamps, crossfaded, the master's encode", () => { + const p = plan([{ id: "c1", start: 104.2, end: 108.2 }, { id: "c3", start: 2001, end: 2004 }], { intro: false, finale: 2 }); + const render = { fps: 30, crf: 21, preset: "slow", audioBitrate: "160k", audioRate: 48000, audioChannels: 2 }; + const argv = trailerArgs({ plan: p, master: "/m/master.mp4", render, outPath: "/o/t.mp4" }); + assert.ok(!argv.includes("-i"), "no -i inputs: the sources are in the graph, read when the chain asks"); + const graph = argv[argv.indexOf("-filter_complex") + 1]; + assert.equal(graph.match(/movie=filename=\/m\/master\.mp4:/g).length, 3); + // The first run: frame 230 (7.667 s) for 120 frames, the source seeked a second ahead. + assert.match(graph, /movie=filename=\/m\/master\.mp4:seek_point=6\.666667:streams=dv\+da:dec_threads=2\[m0v\]\[m0a\]/); + assert.match(graph, /\[m0v\]trim=start=7\.650000:end=11\.650000,setpts=PTS-STARTPTS\[v0\]/); + assert.match(graph, /\[m0a\]atrim=start=7\.666667:end=11\.666667,asetpts=PTS-STARTPTS,apad=whole_dur=4\.000000,atrim=end=4\.000000\[a0\]/); + assert.match(graph, /\[v0\]\[v1\]xfade=transition=fade:duration=0\.300000:offset=3\.700000\[xv1\]/); + assert.match(graph, /\[a0\]\[a1\]acrossfade=d=0\.300000:c1=tri:c2=tri\[xa1\]/); + assert.match(graph, /\[xv1\]\[v2\]xfade=.*offset=6\.400000\[xv2\]/); + assert.deepEqual(argv.slice(argv.indexOf("-map"), argv.indexOf("-map") + 4), ["-map", "[xv2]", "-map", "[xa2]"]); + assert.equal(argv[argv.indexOf("-crf") + 1], "21"); + assert.equal(argv[argv.indexOf("-preset") + 1], "slow"); + assert.equal(argv[argv.indexOf("-b:a") + 1], "160k"); + assert.equal(argv.at(-1), "/o/t.mp4"); +}); + +test("the ffmpeg graph: --xfade 0 is a concat; a run at the master's start seeks to 0", () => { + const p = plan([{ id: "c3", start: 2001, end: 2004 }], { intro: true, xfade: 0 }); + const argv = trailerArgs({ plan: p, master: "/m.mp4", render: { fps: 30 }, outPath: "/o.mp4" }); + const graph = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(graph, /\[v0\]\[a0\]\[v1\]\[a1\]concat=n=2:v=1:a=1\[cv\]\[ca\]/); + assert.doesNotMatch(graph, /xfade/); + assert.match(graph, /seek_point=0\.000000:.*\[m0v\]trim=start=0\.000000:/); +}); + +test("the ffmpeg graph: a seamless pair is one source, one run", () => { + const p = plan([{ id: "c1", start: 100.3, end: 104 }], { intro: true }); + const argv = trailerArgs({ plan: p, master: "/m.mp4", render: { fps: 30 }, outPath: "/o.mp4" }); + const graph = argv[argv.indexOf("-filter_complex") + 1]; + assert.equal(graph.match(/movie=/g).length, 1); + assert.deepEqual(argv.slice(argv.indexOf("-map"), argv.indexOf("-map") + 2), ["-map", "[v0]"]); +}); + +test("filterPath: a file name escaped for the movie option, then for the graph", () => { + assert.equal(filterPath("/a/b.mp4"), "/a/b.mp4"); + assert.equal(filterPath("/x/it's:a,[b];c.mp4"), "/x/it\\\\\\'s\\\\:a\\,\\[b\\]\\;c.mp4"); +}); + +test("output paths: the default, a bare --out name, a path; the record beside", () => { + assert.equal(trailerOutPath("/r/takes/t", "slug"), "/r/takes/t/out/slug.trailer.mp4"); + assert.equal(trailerOutPath("/r/takes/t", "slug", "teaser"), "/r/takes/t/out/teaser.mp4"); + assert.equal(trailerOutPath("/r/takes/t", "slug", "/tmp/x/y.mp4"), "/tmp/x/y.mp4"); + assert.equal(trailerRecordPath("/a/slug.trailer.mp4"), "/a/slug.trailer.json"); + assert.equal(trailerRecordPath("/a/teaser.mp4"), "/a/teaser.trailer.json"); +}); + +async function takeFixture({ schedule = SCHEDULE } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "trailer-")); + 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, crf: 21, preset: "slow", audioBitrate: "160k", audioRate: 48000, audioChannels: 2 } })); + await writeFile(path.join(take, "out", "cut.mp4"), "master"); + if (schedule) 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("a take with no build is refused by name; a master that is not the build's is refused", async () => { + const { root, take } = await takeFixture({ schedule: null }); + try { + await assert.rejects(loadTakeBuild(take), /final has no build: no out\/sourced\/schedule\.json/); + await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(SCHEDULE)); + const beats = parseBeats([{ id: "c1", start: 104, end: 106 }]); + await assert.rejects(makeTrailer({ takeDir: take, beats, probe: async () => 12, run: async () => {} }), /is 12\.00 s but its build records describe a 40\.17 s cut/); + await assert.rejects(makeTrailer({ takeDir: take, beats, probe: async () => null, run: async () => {} }), /has no master/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("makeTrailer: the encode runs in the slot, the file lands by rename, the record says what was cut", async () => { + const { root, take } = await takeFixture(); + try { + let slotted = 0; + let ran = null; + const res = await makeTrailer({ + takeDir: take, + beats: parseBeats([{ id: "c1", start: 100.3, end: 104 }, { id: "c3", start: 2001, end: 2004 }]), + intro: true, + finale: 2, + probe: async () => 40.167, + slot: async (fn) => { slotted += 1; return fn(); }, + run: async (argv) => { ran = argv; await writeFile(argv.at(-1), "trailer"); }, + now: (() => { let t = 0; return () => (t += 1500); })(), + }); + assert.equal(slotted, 1); + assert.equal(res.outPath, path.join(take, "out", "cut.trailer.mp4")); + assert.match(path.basename(ran.at(-1)), /^\.cut\.trailer\.\d+\.tmp\.mp4$/); + assert.equal(await readFile(res.outPath, "utf8"), "trailer"); + const rec = JSON.parse(await readFile(path.join(take, "out", "cut.trailer.json"), "utf8")); + assert.equal(rec.kind, "trailer"); + assert.equal(rec.source.take, "final"); + assert.deepEqual(rec.pieces.map((p) => p.kind), ["intro", "clip", "clip", "finale"]); + assert.equal(rec.pieces[1].source.asked.start, 100.3); + assert.equal(rec.encode.crf, 21); + assert.equal(rec.encodeSeconds, 1.5); + assert.equal(rec.seconds, res.plan.total); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("makeTrailer: a failed encode leaves nothing at the name; --dry-run encodes and writes nothing", async () => { + const { root, take } = await takeFixture(); + try { + const beats = parseBeats([{ id: "c1", start: 104, end: 106 }]); + let tmp = null; + await assert.rejects( + makeTrailer({ takeDir: take, beats, probe: async () => 40.167, run: async (argv) => { tmp = argv.at(-1); await writeFile(tmp, "half"); throw new Error("ffmpeg failed: boom"); } }), + /boom/, + ); + await assert.rejects(stat(tmp), { code: "ENOENT" }); + await assert.rejects(stat(path.join(take, "out", "cut.trailer.mp4")), { code: "ENOENT" }); + let ran = false; + const res = await makeTrailer({ takeDir: take, beats, dryRun: true, probe: async () => 40.167, run: async () => { ran = true; } }); + assert.equal(ran, false); + assert.equal(res.dryRun, true); + await assert.rejects(stat(res.recordPath), { code: "ENOENT" }); + } finally { + await rm(root, { recursive: true, force: true }); + } +});