Archilyzer · Source

archilyzer

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

commit 46641414709bc523a2564dcd1abdc80abc45f2a0
parent 36e6766e1ff06d4fb9bc849f749b2da1e5c99a37
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 20:51:51 -0500

clip kit A: umtool shorts -- a batch of shorts through the one builder

`umtool shorts <p> --take <t> (--items a,b | --all | --again) --formats vertical,landscape`
builds each clip in each format through buildShort (the builder `umtool vertical` now calls),
into the project's shorts-<take>/ (a deliverable family beside clips/ and share-*), as
<name>.<format>.mp4 with records and batch.json.

Stable names: a pinned `name`, else the title's slug, else the id; a clash gets -<id>; a name
once in batch.json is kept. A file there is kept unless --replace (set aside). Each clip's row
keeps the knobs and the snapshot of its project keys (vertical-plan PROJECT_KEYS) it was built
with; --again rebuilds from them. Length caps are notes (180 s vertical, 140 s landscape).

verticalCli: the command's body moved into buildShort() with no change of what it builds;
vertical-plan: PROJECT_KEYS and withOverrides (null overrides: the entries as they were).
The vertical form offers --landscape.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 13+++++++++++++
Mumtool/bin/umtool.mjs | 2++
Mumtool/docs/cli.md | 32+++++++++++++++++++++++++++++++-
Mumtool/docs/knobs.md | 1+
Mumtool/lib/cli/groups.mjs | 13++++++++++++-
Mumtool/lib/cli/verbs.mjs | 10+++++++++-
Mumtool/lib/report/deliverables.test.mjs | 4+++-
Aumtool/lib/report/shortsBatch.mjs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/shortsBatch.test.mjs | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/shortsCli.mjs | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/storage.mjs | 6++++--
Mumtool/lib/report/verticalCli.mjs | 339+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mumtool/report-to-video/vertical-plan.mjs | 29+++++++++++++++++++++++++++--
13 files changed, 856 insertions(+), 152 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,19 @@ # Changelog ## [Unreleased] +- **umtool: a batch of shorts in one command, `umtool shorts`.** `umtool shorts <p> --take <t> (--items a,b | --all) + --formats vertical,landscape` builds each clip in each format through the builder `umtool vertical` uses (the same + layouts and flags), into the project's `shorts-<take>/`, as `<name>.<format>.mp4`. Each file gets its record, and the + folder gets `batch.json`. + - A clip's name is its pinned `name`, else its title's slug, else its id. A clash gets `-<clip id>`, and a name once + given is kept. + - A file already there is kept unless `--replace`, which sets it aside first. + - `--again` builds the folder again from its record: each clip with the knobs and framing it was built with. + - A vertical over 180 s or a landscape over 140 s (X's 2:20) gets a note, never a refusal. + - A clip that fails is recorded and the rest go on. The command exits 1 at the end. + - It is a ⌘K form and runs as one queued job. `shorts-<take>` is a deliverable: `umtool storage deliverables` moves it + with `clips/`. + - `umtool vertical`'s form now offers `--landscape`. - **Clip windows can be asked for taller than 720, and the 720 window stays.** A `maxHeight` above 720 on fetch-windows, fetch-window or `fetch_clip` asks for a taller window, up to the new setting `clips.windowMaxHeight` (default 1080; a taller ask is held to it and the answer says so). With no `maxHeight` a diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -954,6 +954,8 @@ const COMMANDS = { trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // A vertical short (1080x1920) of a take's items, natively or reframed: lib/report/verticalCli.mjs. vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))), + // A batch of shorts: a take's clips in each format, into shorts-<take>/ (lane clip-kit): lib/report/shortsCli.mjs. + shorts: async () => process.exit(await (await import("../lib/report/shortsCli.mjs")).shortsCommand(argv.slice(argv.indexOf("shorts") + 1))), // Quick clip (lane output-modes): one moment to a basic-mode mp4 and its share line: lib/report/quickClip.mjs. clip: async () => process.exit(await (await import("../lib/report/quickClip.mjs")).quickClipCommand(argv.slice(argv.indexOf("clip") + 1))), // The inspector's twins (umtool redesign L6): provenance, title, a still at second N -- lib/report/inspectorCli.mjs. diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -274,7 +274,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* | | `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* | | `trailer <project> [--take TAKE] [--reel REEL] [--beats BEATS] [--beats-json JSON] [--intro] [--finale N] [--xfade N] [--no-snap] [--out OUT] [--dry-run] [--candidates] [--vertical] [--layout reframe]` | a trailer or beat reel cut from a take's master | form · queued · *project* | -| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro] [--deck stacked\|bare]` | a vertical short (1080x1920) of a take's items | form · queued · *project* | +| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--landscape] [--dry-run] [--intro] [--no-intro] [--no-outro] [--deck stacked\|bare]` | a vertical short (1080x1920) of a take's items | form · queued · *project* | +| `shorts <project> --take TAKE [--items ITEMS] [--all] [--again] [--formats FORMATS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max-vertical N] [--max-landscape N] [--deck stacked\|bare] [--replace] [--dry-run]` | a batch of shorts: each clip of a take in each format, into shorts-<take>/ | form · queued · *project* | | `trailer-beats <project> ls [--reel REEL]` | a reel's beats against its limit | form · *project* | | `trailer-beats <project> add <clip> [<span>] [--at N] [--label LABEL] [--take TAKE] [--reel REEL]` | a clip beat | form · *project* | | `trailer-beats <project> add-raw <at> <dur> [--at N] [--label LABEL] [--reel REEL]` | a beat of master seconds | form · *project* | @@ -548,6 +549,7 @@ $U vertical emberparadox/mr-obvious --take mid-14 --reel short-die --reframe --j - **The cut itself vertical**: `umtool look <p> format='"vertical"' vertical='{"clip":"framed","post":"card"}'` (or the same keys in a take's patch) renders the whole timeline 9:16 -- `umtool take` as ever. - `--landscape` builds the same items in the take's 16:9 look, to compare (a side post is a panel at the right). +- **Many clips, both formats, one command:** `umtool shorts` ([below](#make-promo-clips-a-batch-of-shorts)). - **The intro and the outro card.** `--intro` opens the short on the brand intro re-laid 9:16 -- the same style, sound, timing and site swap, the drawing centred in the safe area -- from the take's `render.intro`, else `boot-dark` with the mark on the chime; a reel whose `intro` is on opens on it too (its own intro when it has one; @@ -556,6 +558,34 @@ $U vertical emberparadox/mr-obvious --take mid-14 --reel short-die --reframe --j record names them (`intro`, `outro`). - Hooks only ever say the cut's own words: a clip's title, its section's title (the deck's marker), or a line you give. +## Make promo clips (a batch of shorts) + +The clipping job as one command: each listed clip of a take, in each format, through the same builder as +`umtool vertical`, into the project's `shorts-<take>/`. One queued job, one log, one record. + +```sh +U="node umtool/bin/umtool.mjs" +$U shorts my-clips --take kit --items w01,w03,w05 --formats vertical,landscape --clip framed --hook title +$U shorts my-clips --take kit --all --dry-run # the names and files it would write +$U shorts my-clips --take kit --again # the folder's batch.json made again +``` + +- **Formats.** `vertical` is `umtool vertical`'s 9:16 short (its layouts and flags: `--clip`, `--hook`, `--captions`, …); + `landscape` is the same clip in the take's own 16:9 look (`umtool vertical --landscape`). +- **Names.** `<name>.<format>.mp4`, each with its record (`.json`): the clip's `name` when it pins one, else its + title's slug, else its id. A name another clip of the folder holds gets `-<clip id>` (two clips of one cut often share + a title). Once a clip has a name in `batch.json` it keeps it, whatever its title becomes. +- **A file there is kept** unless `--replace`, which sets the old one aside as `<name>.<format>.<stamp>.mp4`. +- **`batch.json`** names each clip's files, lengths, notes and errors, the knobs it was last built with and its + **snapshot** (its framing, `vertical` and `side`, as read). `--again` builds every clip of the folder again with its + own formats, knobs and snapshot, so a later edit of the project does not silently change a rebuild. +- **Length.** A vertical over 180 s (`--max-vertical`, Shorts' 3 minutes) or a landscape over 140 s (`--max-landscape`, + X's 2:20) is said so in the record: a note, never a refusal. +- Each build runs in the heavy slot as `umtool vertical`'s does (another job may run between two clips). A clip that + fails is recorded with its error and the rest go on; the command exits 1 at the end. +- Not `shorts/`: that folder is the clip editor's **Make a short**, whose every mp4 the Deliver tab reads as a clip's. + `shorts-<take>` is a deliverable, moved with `clips/` and `share-*` by `umtool storage deliverables`. + ## `check` is the one to run before every build ``` diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -2184,6 +2184,7 @@ byte what it was. | the brand intro 9:16 first (centred in the safe area); the reel's outro card 9:16 last | `umtool vertical <p> --take <t> --reel <r> --intro` (a reel with `intro` on: by itself; `--no-intro`) · the reel's `outro` on: by itself (`--no-outro`) | | R, recomposed from the master | `umtool vertical <p> --take <t> --reel <r> --reframe` (each item's footage box, card and attachment, the deck's date line; nothing cut again) | | the same items 16:9, to compare | `umtool vertical <p> --take <t> --reel <r> --landscape` | +| each clip of a take in each format, into `shorts-<take>/` (a batch, its record, stable names) | `umtool shorts <p> --take <t> (--items a,b \| --all \| --again) [--formats vertical,landscape] [the vertical flags]` ([cli.md](cli.md#make-promo-clips-a-batch-of-shorts)) | A clip's `vertical` and `side` are read from the PROJECT's manifest over the take's (they are set after the take was made). The side card is drawn by the post card's own page with the cut's redaction and the authors' pictures; its diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -693,7 +693,7 @@ export const GROUPS = [ usage: [ " umtool vertical <project> --take <t> (--reel R | --beats F | --items a,b) [--clip full|framed|quote]", " [--post card|stack|media] [--side split|overlay] [--hook title|section|<copy>] [--deck stacked|bare]", - " [--reframe] [--json]", + " [--reframe | --landscape] [--json]", " a vertical short (1080x1920, -14 LUFS) of the take's items: each clip cut again in its layout,", " each post drawn in a portrait box; --reframe recomposes the finished 16:9 master instead", ], @@ -701,6 +701,17 @@ export const GROUPS = [ ], }, { + cmd: "shorts", + usage: [ + " umtool shorts <project> --take <t> (--items a,b | --all | --again) [--formats vertical,landscape]", + " [the vertical flags] [--max-vertical 180] [--max-landscape 140] [--replace] [--dry-run] [--json]", + " a batch of shorts: each clip in each format through `umtool vertical`'s builder, into the", + " project's shorts-<take>/ as <name>.<format>.mp4 (the title's slug) with batch.json", + ], + docs: [ + ], + }, + { cmd: "trailer-beats", usage: [ " umtool trailer-beats <project> [ls] | add <clip> [<from>-<to>] [--at N] [--label L] | add-raw <at> <dur> | set <n> <from>-<to>", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -322,9 +322,17 @@ export const VERBS = Object.freeze([ form("vertical", "project", "a vertical short (1080x1920) of a take's items", [ project(), takeOpt({ required: true, help: "the take" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--items", { help: "id,id" }), pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]), pick("--side", ["split", "overlay"]), opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"), num("--max"), - name("--name"), bool("--reframe", "recompose the finished 16:9 master"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"), + name("--name"), bool("--reframe", "recompose the finished 16:9 master"), bool("--landscape", "the same items in the take's 16:9 look"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"), pick("--deck", ["stacked", "bare"]), ], Q), + form("shorts", "project", "a batch of shorts: each clip of a take in each format, into shorts-<take>/", [ + project(), takeOpt({ required: true, help: "the take" }), opt("--items", { help: "id,id" }), bool("--all", "every clip of the take"), + bool("--again", "the folder's batch.json made again"), opt("--formats", { help: "vertical,landscape (default vertical)" }), + pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]), pick("--side", ["split", "overlay"]), + opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"), + num("--max-vertical", { help: "s (180): over it, a note" }), num("--max-landscape", { help: "s (140): over it, a note" }), pick("--deck", ["stacked", "bare"]), + bool("--replace", "set a file there aside and make it again"), dry(), + ], Q), // ---- the trailer's beats ---- ...trailerBeats(), diff --git a/umtool/lib/report/deliverables.test.mjs b/umtool/lib/report/deliverables.test.mjs @@ -99,7 +99,9 @@ test("updateStorage writes the switch, keeps the rest, and does not rewrite a no test("deliverable names: clips and share-*, never a leftover, a file or another directory", async () => { assert.ok(isDeliverableName("clips") && isDeliverableName("share-first") && isDeliverableName("share-batch-2026.10.01")); - for (const no of ["out", "share-", "shares", "clips.moved-20261001T000000Z", "share-x.incoming", "../clips", "share-a/b"]) { + // A take's batch of shorts (lane clip-kit): shorts-<take>, never the clip editor's own shorts/. + assert.ok(isDeliverableName("shorts-kit") && isDeliverableName("shorts-x-2")); + for (const no of ["out", "share-", "shares", "clips.moved-20261001T000000Z", "share-x.incoming", "../clips", "share-a/b", "shorts", "shorts-", "shorts-a/b", "shorts-kit.incoming"]) { assert.equal(isDeliverableName(no), false, no); } const w = await world(); diff --git a/umtool/lib/report/shortsBatch.mjs b/umtool/lib/report/shortsBatch.mjs @@ -0,0 +1,163 @@ +// A BATCH OF SHORTS (lane clip-kit, slice A): the clipping job as one command. `umtool shorts <project> --take <t> +// (--items a,b | --all) --formats vertical,landscape` builds every listed clip in every format through the ONE +// builder behind `umtool vertical` (lib/report/verticalCli.mjs buildShort), into one folder of the project, +// `shorts-<take>/` -- a deliverable (storage.mjs isDeliverableName), never `shorts/`, which the clip editor's Make a +// short owns and whose every mp4 the Deliver tab reads as `<clipId>.mp4`. +// +// shorts-<take>/<name>.<format>.mp4 each with its record (<name>.<format>.json, the vertical-short record) +// shorts-<take>/batch.json the batch: what was asked, each clip's name, files, notes and snapshot +// +// NAMES are stable: a clip's `name` when it pins one, else its title's slug, else its id. A name another clip of the +// folder already holds gets `-<clipId>` (two clips of one cut often share a title). Once a clip has a name in the +// folder's batch.json it keeps it on every later run, whatever its title becomes or whatever else the batch holds. +// +// THE SNAPSHOT: each clip's PROJECT keys (vertical-plan.mjs PROJECT_KEYS -- set after the take was made, read over +// it) as the batch read them. `--again` rebuilds from the record: the same items, formats and knobs, each clip +// framed by its snapshot, so a later edit of the project does not silently change a rebuild. +// +// PURE: no fs. The command is lib/report/shortsCli.mjs. + +/** The formats a batch builds, each the builder's options and its length note's cap (s; a note, never a refusal). */ +export const BATCH_FORMATS = Object.freeze({ + vertical: Object.freeze({ landscape: false, maxSeconds: 180 }), + landscape: Object.freeze({ landscape: true, maxSeconds: 140 }), +}); +export const FORMAT_NAMES = Object.freeze(Object.keys(BATCH_FORMATS)); + +/** The folder a take's batch lands in. */ +export const BATCH_PREFIX = "shorts-"; +export const batchDirName = (take) => `${BATCH_PREFIX}${take}`; +export const BATCH_FILE = "batch.json"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** A title as a file name: lower case, letters and digits, words joined by "-" (apostrophes dropped), ≤ 60. */ +export function slugOf(text) { + const s = String(text ?? "") + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/['’‘`]/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return s.slice(0, 60).replace(/-+$/, ""); +} + +/** A clip's own name, a pinned `name` or its title's slug or its id: what its files are called before a tiebreak. */ +export function baseNameOf(entry) { + const pinned = typeof entry?.name === "string" ? slugOf(entry.name) : ""; + if (pinned) return pinned; + const title = typeof entry?.title === "string" ? slugOf(entry.title) : ""; + return title || slugOf(entry?.id) || "clip"; +} + +/** + * Each clip's name in the folder: `prior` ({<clip id>: name}, the folder's batch.json) kept as it is; a new clip its + * base name, or `<base>-<id>` when another clip holds that already. In the order given; returns {<clip id>: name}. + * + * @param {Array<{ id: string, name?: string, title?: string }>} entries + * @param {Record<string, string>} [prior] + */ +export function assignNames(entries, prior = {}) { + const names = { ...(isObj(prior) ? prior : {}) }; + const taken = new Map(Object.entries(names).map(([id, n]) => [n, id])); + for (const e of entries) { + if (typeof names[e.id] === "string") continue; + const base = baseNameOf(e); + let n = base; + if (taken.has(n) && taken.get(n) !== e.id) n = `${base}-${slugOf(e.id) || "clip"}`; + for (let k = 2; taken.has(n) && taken.get(n) !== e.id; k += 1) n = `${base}-${slugOf(e.id)}-${k}`; + names[e.id] = n; + taken.set(n, e.id); + } + return names; +} + +/** `--formats a,b` read: known names, each once, in the order given. Throws naming an unknown one. */ +export function parseFormats(text) { + const list = String(text ?? "vertical").split(",").map((s) => s.trim()).filter(Boolean); + const bad = list.filter((f) => !FORMAT_NAMES.includes(f)); + if (bad.length) throw new Error(`--formats ${bad.join(", ")}: not a format (${FORMAT_NAMES.join(", ")})`); + if (!list.length) throw new Error(`--formats: one or more of ${FORMAT_NAMES.join(", ")}`); + return [...new Set(list)]; +} + +/** The keys of a clip a batch snapshots (vertical-plan.mjs PROJECT_KEYS): each set one, null for one it lacks. */ +export function snapshotOf(entry, keys) { + /** @type {Record<string, unknown>} */ + const out = {}; + for (const k of keys) out[k] = entry?.[k] === undefined ? null : entry[k]; + return out; +} + +/** A file set aside before it is made again: `<name>.<format>.<stamp>.mp4`. */ +export function asideName(file, now = new Date()) { + const p = (n) => String(n).padStart(2, "0"); + const stamp = `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`; + return file.replace(/\.mp4$/, `.${stamp}.mp4`); +} + +/** + * What `--again` builds from a record: each clip of it, in its order, with the formats it has a file (or an error) + * in, the knobs it was last built with and its snapshot. `[{id, formats, knobs, snapshot}]`. + */ +export function againOf(record) { + if (!isObj(record) || record.kind !== "shorts-batch" || !Array.isArray(record.clips)) throw new Error("not a batch record (batch.json, kind shorts-batch)"); + return record.clips + .filter((c) => isObj(c) && typeof c.id === "string") + .map((c) => ({ + id: c.id, + formats: FORMAT_NAMES.filter((f) => (isObj(c.files) && c.files[f]) || (isObj(c.errors) && c.errors[f])), + knobs: isObj(c.knobs) ? c.knobs : {}, + snapshot: isObj(c.snapshot) ? c.snapshot : null, + })) + .filter((c) => c.formats.length); +} + +/** + * A clip's row after one format's build: `prior` (its row, or null) with this run's name and title, and the format's + * file, length and notes -- or its error, the file dropped when it is no longer there (`exists`). The knobs and the + * snapshot are the last SUCCESSFUL build's. Pure. + * + * @param {Record<string, any> | null} prior + * @param {{ id: string, name: string, title: string | null, format: string, knobs: Record<string, any>, snapshot: Record<string, any>, + * file?: string, seconds?: number | null, notes?: string[], error?: string, exists?: boolean }} r + */ +export function rowAfter(prior, r) { + const row = { id: r.id, name: r.name, title: r.title, knobs: {}, snapshot: null, files: {}, seconds: {}, notes: {}, errors: {}, ...(isObj(prior) ? prior : {}) }; + row.name = r.name; + row.title = r.title; + row.files = { ...row.files }; + row.seconds = { ...row.seconds }; + row.notes = isObj(row.notes) ? { ...row.notes } : {}; + row.errors = { ...row.errors }; + if (r.error) { + row.errors[r.format] = r.error; + if (!r.exists) { + delete row.files[r.format]; + delete row.seconds[r.format]; + delete row.notes[r.format]; + } + return row; + } + delete row.errors[r.format]; + row.files[r.format] = r.file; + row.seconds[r.format] = r.seconds ?? null; + row.notes[r.format] = r.notes ?? []; + row.knobs = r.knobs; + row.snapshot = r.snapshot; + return row; +} + +/** The clips a batch builds: `items` (each must be a clip of the take), else with `all` every clip of the take. */ +export function batchItems(timeline, { items = null, all = false } = {}) { + const clips = (timeline ?? []).filter((e) => e?.type === "clip" && typeof e.id === "string"); + if (items?.length) { + const byId = new Map(clips.map((e) => [e.id, e])); + const missing = items.filter((id) => !byId.has(id)); + if (missing.length) throw new Error(`${missing.join(", ")}: not ${missing.length > 1 ? "clips" : "a clip"} of the take`); + return [...new Set(items)].map((id) => byId.get(id)); + } + if (all) return clips; + throw new Error("--items <id>,… or --all: which clips"); +} diff --git a/umtool/lib/report/shortsBatch.test.mjs b/umtool/lib/report/shortsBatch.test.mjs @@ -0,0 +1,183 @@ +// A batch of shorts (lane clip-kit, slice A): names, formats, the snapshot, and `umtool shorts` driving the one +// builder (a stand-in here: nothing is rendered) into shorts-<take>/ with its batch.json. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { againOf, asideName, assignNames, baseNameOf, batchItems, parseFormats, rowAfter, slugOf, snapshotOf } from "./shortsBatch.mjs"; +import { shortsCommand } from "./shortsCli.mjs"; +import { PROJECT_KEYS, planVerticalCut, withOverrides } from "umtool-report-to-video/vertical-plan"; + +test("a title's slug: lower case, apostrophes dropped, words joined", () => { + assert.equal(slugOf("A clip about Tom's toast"), "a-clip-about-toms-toast"); + assert.equal(slugOf(" Rye or sourdough?! "), "rye-or-sourdough"); + assert.equal(slugOf("Café — déjà vu"), "cafe-deja-vu"); + assert.equal(slugOf("x".repeat(80)).length, 60); + assert.equal(baseNameOf({ id: "w01", title: "A great break", name: "Pinned Name" }), "pinned-name"); + assert.equal(baseNameOf({ id: "w01" }), "w01"); +}); + +test("names: two clips sharing a title, the second gets -<id>; a name once given is kept", () => { + const clips = [ + { id: "m01", title: "A clip about Tom's toast" }, + { id: "w01", title: "A clip about Tom's toast" }, + { id: "w05", title: "Rye loaf" }, + ]; + assert.deepEqual(assignNames(clips), { + m01: "a-clip-about-toms-toast", + w01: "a-clip-about-toms-toast-w01", + w05: "rye-loaf", + }); + // A later run that holds only w01 keeps its name; a retitled clip keeps its name too. + const prior = { w01: "a-clip-about-toms-toast-w01", w05: "rye-loaf" }; + assert.deepEqual(assignNames([{ id: "w01", title: "x" }, { id: "w05", title: "Retitled" }], prior), prior); + // A new clip whose slug a prior clip holds takes the tiebreak. + assert.equal(assignNames([{ id: "m05", title: "Rye loaf" }], prior).m05, "rye-loaf-m05"); +}); + +test("formats, items and the record's again", () => { + assert.deepEqual(parseFormats("vertical,landscape,vertical"), ["vertical", "landscape"]); + assert.deepEqual(parseFormats(undefined), ["vertical"]); + assert.throws(() => parseFormats("square"), /square: not a format/); + const tl = [{ type: "clip", id: "a" }, { type: "post", id: "p" }, { type: "clip", id: "b" }]; + assert.deepEqual(batchItems(tl, { all: true }).map((e) => e.id), ["a", "b"]); + assert.deepEqual(batchItems(tl, { items: ["b", "a", "b"] }).map((e) => e.id), ["b", "a"]); + assert.throws(() => batchItems(tl, { items: ["p"] }), /p: not a clip of the take/); + assert.throws(() => batchItems(tl, {}), /--items <id>,… or --all/); + const again = againOf({ kind: "shorts-batch", clips: [ + { id: "a", knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, files: { landscape: "a.landscape.mp4" }, errors: { vertical: "failed" } }, + { id: "b", files: {}, errors: {} }, + ] }); + assert.deepEqual(again, [{ id: "a", formats: ["vertical", "landscape"], knobs: { clip: "framed" }, snapshot: { vertical: null, side: null } }]); + // A row: a success records the file, the knobs and the snapshot; a failure keeps a file still there, drops one gone. + const ok = rowAfter(null, { id: "a", name: "n", title: "T", format: "vertical", knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, file: "n.vertical.mp4", seconds: 9, notes: ["x"] }); + assert.deepEqual(ok, { id: "a", name: "n", title: "T", knobs: { clip: "framed" }, snapshot: { vertical: null, side: null }, files: { vertical: "n.vertical.mp4" }, seconds: { vertical: 9 }, notes: { vertical: ["x"] }, errors: {} }); + const refused = rowAfter(ok, { id: "a", name: "n", title: "T", format: "vertical", knobs: {}, snapshot: {}, error: "is there", exists: true }); + assert.deepEqual([refused.files, refused.errors, refused.knobs], [{ vertical: "n.vertical.mp4" }, { vertical: "is there" }, { clip: "framed" }]); + assert.deepEqual(rowAfter(ok, { id: "a", name: "n", title: "T", format: "vertical", knobs: {}, snapshot: {}, error: "crashed", exists: false }).files, {}); + assert.throws(() => againOf({ kind: "vertical-short" }), /not a batch record/); + assert.match(asideName("/x/a.vertical.mp4", new Date(2026, 10, 13, 9, 5, 7)), /\/x\/a\.vertical\.20261113-090507\.mp4$/); +}); + +test("the snapshot: the project keys a clip has, null for one it lacks; laid over the project's entries", () => { + const e = { type: "clip", id: "a", vertical: { crop: [0.6, 0, 0.3164, 1] } }; + assert.deepEqual(snapshotOf(e, PROJECT_KEYS), { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null }); + const project = [{ type: "clip", id: "a", vertical: { crop: [0.1, 0, 0.3164, 1] }, side: { item: "p", from: 0, to: 3 } }]; + const laid = withOverrides(project, { a: { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null, title: "ignored" } }); + assert.deepEqual(laid[0], { type: "clip", id: "a", vertical: { crop: [0.6, 0, 0.3164, 1] } }); + // The plan reads the snapshot's framing over the take's own entry. + const plan = planVerticalCut({ timeline: [{ type: "clip", id: "a", start: 1, end: 5 }], items: ["a"], project: laid }); + assert.deepEqual(plan.timeline[0].vertical, { crop: [0.6, 0, 0.3164, 1] }); + // No snapshot: the entries as they are (byte for byte the plan it always made). + assert.equal(withOverrides(project, null), project); +}); + +async function world() { + const root = await mkdtemp(path.join(tmpdir(), "shortsbatch-")); + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "proj"); + await mkdir(path.join(dir, "takes", "kit"), { recursive: true }); + const timeline = [ + { type: "clip", id: "m01", video: "v", start: 1, end: 5, title: "Tom's toast" }, + { type: "clip", id: "w01", video: "v", start: 0, end: 8, title: "Tom's toast", vertical: { crop: [0.6, 0, 0.3164, 1] } }, + ]; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "cut", title: "Cut", render: { fps: 30 }, timeline })); + await writeFile(path.join(dir, "takes", "kit", "take.json"), JSON.stringify({ id: "kit", group: "takes", order: 1, label: "kit", kind: "reference", preview: "preview.mp4", patch: null, draft: true, window: "full", style: null })); + return { root, reportsRoot, dir }; +} + +/** A builder that writes a file where it is asked and records what it was asked. */ +function standIn(calls, { fail = () => false } = {}) { + return async (o) => { + calls.push(o); + if (fail(o)) throw new Error(`stand-in refused ${o.items[0]}`); + await mkdir(path.dirname(o.out), { recursive: true }); + await writeFile(o.out, `mp4 of ${o.items[0]}`); + return { record: { seconds: 150, notes: o.knobs.maxSeconds < 150 ? [`this short runs 150.0 s, over its ${o.knobs.maxSeconds} s`] : [], out: o.out } }; + }; +} + +const sink = () => { + const logs = []; + const errs = []; + return { logs, errs, log: (s) => logs.push(s), err: (s) => errs.push(s) }; +}; + +test("umtool shorts: each clip in each format into shorts-<take>/, named, recorded; a file there kept unless --replace", async () => { + const w = await world(); + try { + const calls = []; + const o = sink(); + const code = await shortsCommand(["proj", "--take", "kit", "--all", "--formats", "vertical,landscape", "--clip", "framed", "--hook", "title"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn(calls) }); + assert.equal(code, 0, o.errs.join("\n")); + const folder = path.join(w.dir, "shorts-kit"); + const files = (await readdir(folder)).sort(); + assert.deepEqual(files, ["batch.json", "toms-toast-w01.landscape.mp4", "toms-toast-w01.vertical.mp4", "toms-toast.landscape.mp4", "toms-toast.vertical.mp4"]); + // The builder was asked one clip at a time, with the flags' knobs and each format's cap. + assert.deepEqual(calls.map((c) => [c.items[0], c.landscape, c.knobs.maxSeconds, c.knobs.clip]), [["m01", false, 180, "framed"], ["m01", true, 140, "framed"], ["w01", false, 180, "framed"], ["w01", true, 140, "framed"]]); + assert.deepEqual(calls[2].overrides, { w01: { vertical: { crop: [0.6, 0, 0.3164, 1] }, side: null } }); + const rec = JSON.parse(await readFile(path.join(folder, "batch.json"), "utf8")); + assert.equal(rec.kind, "shorts-batch"); + assert.deepEqual(rec.last.argv, ["shorts", "proj", "--take", "kit", "--items", "m01,w01", "--formats", "vertical,landscape"]); + assert.deepEqual(rec.clips.map((c) => [c.id, c.name, c.files.vertical, c.knobs.clip]), [["m01", "toms-toast", "toms-toast.vertical.mp4", "framed"], ["w01", "toms-toast-w01", "toms-toast-w01.vertical.mp4", "framed"]]); + assert.deepEqual(rec.clips[0].notes, { vertical: [], landscape: ["this short runs 150.0 s, over its 140 s"] }); + + // Again without --replace: refused per file, recorded, exit 1; the files are untouched. + const o2 = sink(); + assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01"], { reportsRoot: w.reportsRoot, log: o2.log, err: o2.err, build: standIn([]) }), 1); + assert.match(o2.errs.join("\n"), /toms-toast-w01\.vertical\.mp4 is there — --replace/); + const rec2 = JSON.parse(await readFile(path.join(folder, "batch.json"), "utf8")); + assert.deepEqual(rec2.clips.map((c) => c.id), ["m01", "w01"], "a clip of the folder this run did not build keeps its row"); + assert.equal(rec2.clips[1].knobs.clip, "framed", "a refused run keeps the knobs the file was made with"); + assert.equal(rec2.clips[1].files.landscape, "toms-toast-w01.landscape.mp4"); + + // --again: the record's clips, formats and knobs, framed by its snapshot, the old files set aside. + await writeFile(path.join(w.dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "cut", render: { fps: 30 }, timeline: [{ type: "clip", id: "m01", video: "v", start: 1, end: 5, title: "Renamed" }, { type: "clip", id: "w01", video: "v", start: 0, end: 8, vertical: { crop: [0, 0, 0.3164, 1] } }] })); + const calls3 = []; + const o3 = sink(); + assert.equal(await shortsCommand(["proj", "--take", "kit", "--again"], { reportsRoot: w.reportsRoot, log: o3.log, err: o3.err, build: standIn(calls3) }), 0, o3.errs.join("\n")); + assert.deepEqual(calls3.map((c) => [c.items[0], c.landscape, c.knobs.clip]), [["m01", false, "framed"], ["m01", true, "framed"], ["w01", false, "framed"], ["w01", true, "framed"]]); + assert.deepEqual(calls3[2].overrides.w01.vertical, { crop: [0.6, 0, 0.3164, 1] }, "the snapshot, not the project's new crop"); + const after = await readdir(folder); + assert.ok(after.includes("toms-toast.vertical.mp4"), "the name kept though the title changed"); + assert.equal(after.filter((f) => /\.\d{8}-\d{6}\.mp4$/.test(f)).length, 4, "each old file set aside"); + } finally { + await rm(w.root, { recursive: true, force: true }); + } +}); + +test("umtool shorts: a failing clip is recorded and the rest go on; --dry-run writes nothing; refusals say why", async () => { + const w = await world(); + try { + const o = sink(); + const code = await shortsCommand(["proj", "--take", "kit", "--all"], { reportsRoot: w.reportsRoot, log: o.log, err: o.err, build: standIn([], { fail: (x) => x.items[0] === "m01" }) }); + assert.equal(code, 1); + const rec = JSON.parse(await readFile(path.join(w.dir, "shorts-kit", "batch.json"), "utf8")); + assert.match(rec.clips[0].errors.vertical, /stand-in refused m01/); + assert.deepEqual(rec.clips[0].files, {}); + assert.deepEqual(rec.clips[1].files, { vertical: "toms-toast-w01.vertical.mp4" }); + + await rm(path.join(w.dir, "shorts-kit"), { recursive: true }); + const d = sink(); + assert.equal(await shortsCommand(["proj", "--take", "kit", "--items", "w01", "--formats", "landscape", "--dry-run", "--json"], { reportsRoot: w.reportsRoot, log: d.log, err: d.err, build: standIn([]) }), 0); + assert.deepEqual(JSON.parse(d.logs.join("\n")).clips[0].files, { landscape: "toms-toast.landscape.mp4" }, "alone in a new folder, w01 takes its plain name"); + assert.equal(existsSync(path.join(w.dir, "shorts-kit")), false); + + const say = async (args, re) => { + const x = sink(); + assert.equal(await shortsCommand(args, { reportsRoot: w.reportsRoot, log: x.log, err: x.err, build: standIn([]) }), 2, args.join(" ")); + assert.match(x.errs.join("\n"), re); + }; + await say(["proj", "--all"], /--take <t>/); + await say(["proj", "--take", "kit"], /--items <id>,… or --all/); + await say(["proj", "--take", "kit", "--items", "nope"], /nope: not a clip of the take/); + await say(["proj", "--take", "kit", "--all", "--formats", "square"], /square: not a format/); + await say(["proj", "--take", "kit", "--again"], /batch\.json is not there/); + await say(["proj", "--take", "kit", "--all", "--max-vertical", "2"], /--max-vertical is 5 to 600/); + } finally { + await rm(w.root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/shortsCli.mjs b/umtool/lib/report/shortsCli.mjs @@ -0,0 +1,213 @@ +// `umtool shorts` (lane clip-kit, slice A): every listed clip of a take, in every listed format, into the project's +// `shorts-<take>/`, through the ONE builder behind `umtool vertical` (verticalCli.mjs buildShort). The rules -- the +// names, the formats, the snapshot -- are lib/report/shortsBatch.mjs's. +// +// umtool shorts <project> --take <t> (--items a,b | --all | --again) [--formats vertical,landscape] +// [--clip full|framed|quote] [--hook title|section|"<copy>"] [--captions l|xl] [--lines 1|2] +// [--loudness -14] [--max-vertical 180] [--max-landscape 140] [--deck stacked|bare] +// [--replace] [--dry-run] [--json] +// +// One command, one record: each build takes the heavy slot as `umtool vertical` does (another job may run between +// two clips); a clip that fails is recorded with its error, the rest go on, and the command exits 1 at the end. +import { existsSync } from "node:fs"; +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { deliverableDir } from "./storage.mjs"; +import { BATCH_FILE, BATCH_FORMATS, FORMAT_NAMES, againOf, asideName, assignNames, batchDirName, batchItems, parseFormats, rowAfter, snapshotOf } from "./shortsBatch.mjs"; +import { CliError, buildShort, isRefusal, knobsOfFlags, takeManifestOf } from "./verticalCli.mjs"; + +export const SHORTS_USAGE = [ + "usage: umtool shorts <project> --take <t> (--items <id>,<id>… | --all | --again) [--formats vertical,landscape]", + " [--clip full|framed|quote] [--post card|stack|media] [--side split|overlay]", + " [--hook title|section|\"<a line of the cut's own copy>\"] [--captions l|xl] [--lines 1|2]", + " [--loudness -14] [--max-vertical 180] [--max-landscape 140] [--deck stacked|bare]", + " [--replace] [--dry-run] [--json]", + "", + "A batch of shorts: each clip (--items, or --all of the take's) in each format -- vertical (1080x1920, the", + "`umtool vertical` layouts and flags) and landscape (the take's own 16:9 look) -- into the project's", + "shorts-<take>/ as <name>.<format>.mp4, each with its record, and batch.json. A clip's name is its own `name`, else", + "its title's slug, else its id; one another clip holds already gets -<clip id>; once given, it is kept. A file", + "there is not replaced unless --replace (the old one set aside as <name>.<format>.<stamp>.mp4). --again builds the", + "folder's batch.json again: its clips, formats and knobs, each clip framed as the record saw it. Over its length", + "(--max-vertical 180 s, --max-landscape 140 s) a short is said so: a note, never a refusal. Each build runs in the", + "heavy slot, as `umtool vertical`'s does; a clip that fails is recorded and the rest go on (exit 1 at the end).", +].join("\n"); + +const VALUED = new Set(["--take", "--items", "--formats", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max-vertical", "--max-landscape", "--deck"]); +const BOOL = new Set(["--all", "--again", "--replace", "--dry-run", "--json", "--help"]); + +function parse(args) { + /** @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 (BOOL.has(a)) flags[a] = ""; + else throw new CliError(`unknown flag ${a}`); + } else positional.push(a); + } + return { flags, positional, has: (n) => n in flags }; +} + +const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** Write a file through a rename (a reader never sees half of it). */ +async function writeJson(file, doc) { + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, file); +} + +/** + * `umtool shorts …` + * @param {string[]} args everything after `shorts` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, build?: typeof buildShort }} [opts] + * `build` the builder (tests stand one in). + * @returns {Promise<number>} + */ +export async function shortsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, build = buildShort } = {}) { + try { + const p = parse(args); + if (p.has("--help") || !p.positional.length) { + log(SHORTS_USAGE); + return p.has("--help") ? 0 : 2; + } + const json = p.has("--json"); + const say = json ? err : log; + const take = p.flags["--take"] ?? null; + if (!take) throw new CliError("--take <t>: the take whose clips the shorts are cut from"); + if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); + 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 dir = r.project.dir; + const folder = path.join(dir, batchDirName(take)); + const prior = await readJson(path.join(folder, BATCH_FILE)); + + // What is asked: the flags, or (--again) the folder's record -- each clip with its own formats, knobs and snapshot. + /** @type {Array<{ id: string, formats: string[], knobs: Record<string, any>, snapshot: Record<string, any> | null }> | null} */ + let again = null; + const replace = p.has("--replace") || p.has("--again"); + if (p.has("--again")) { + if (!prior) throw new CliError(`--again: ${batchDirName(take)}/${BATCH_FILE} is not there — make the batch first`); + try { + again = againOf(prior); + } catch (e) { + throw new CliError(`--again: ${e instanceof Error ? e.message : e}`); + } + if (!again.length) throw new CliError(`--again: ${batchDirName(take)}/${BATCH_FILE} names no clip with a file`); + } + let formats; + try { + formats = parseFormats(p.flags["--formats"] ?? "vertical"); + } catch (e) { + throw new CliError(e instanceof Error ? e.message : String(e)); + } + const knobs = knobsOfFlags(p.flags); + const takeManifest = await takeManifestOf(dir, take); + let entries; + try { + entries = batchItems(takeManifest.timeline ?? [], { items: again ? again.map((c) => c.id) : p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null, all: p.has("--all") }); + } catch (e) { + throw new CliError(e instanceof Error ? e.message : String(e)); + } + const projectManifest = await readJson(path.join(dir, "video.manifest.json")); + const projectById = new Map((projectManifest?.timeline ?? []).filter((e) => typeof e?.id === "string").map((e) => [e.id, e])); + const priorRows = new Map((Array.isArray(prior?.clips) ? prior.clips : []).filter((c) => isObj(c) && typeof c.id === "string").map((c) => [c.id, c])); + const priorNames = Object.fromEntries([...priorRows.values()].filter((c) => typeof c.name === "string").map((c) => [c.id, c.name])); + // A clip's name reads its PROJECT entry (a pinned `name`, a title set after the take), over the take's. + const names = assignNames(entries.map((e) => ({ ...e, ...(projectById.get(e.id) ?? {}) })), priorNames); + const caps = { + vertical: p.flags["--max-vertical"] !== undefined ? Number(p.flags["--max-vertical"]) : BATCH_FORMATS.vertical.maxSeconds, + landscape: p.flags["--max-landscape"] !== undefined ? Number(p.flags["--max-landscape"]) : BATCH_FORMATS.landscape.maxSeconds, + }; + for (const [f, n] of Object.entries(caps)) if (!(Number.isFinite(n) && n >= 5 && n <= 600)) throw new CliError(`--max-${f} is 5 to 600 seconds`); + + const { PROJECT_KEYS } = await import("umtool-report-to-video/vertical-plan"); + const againById = new Map((again ?? []).map((c) => [c.id, c])); + const plan = entries.map((e) => { + const ag = againById.get(e.id) ?? null; + const fs = ag ? ag.formats : formats; + return { + id: e.id, name: names[e.id], title: projectById.get(e.id)?.title ?? e.title ?? null, + knobs: ag ? ag.knobs : knobs, + snapshot: ag?.snapshot ?? snapshotOf(projectById.get(e.id) ?? e, PROJECT_KEYS), + files: Object.fromEntries(fs.map((f) => [f, `${names[e.id]}.${f}.mp4`])), + }; + }); + if (p.has("--dry-run")) { + const out = { project: r.project.id, take, folder, clips: plan.map((c) => ({ id: c.id, name: c.name, title: c.title, knobs: c.knobs, files: c.files, exists: Object.values(c.files).filter((f) => existsSync(path.join(folder, f))) })) }; + log(json ? JSON.stringify(out, null, 2) : [`would write into ${folder}`, ...out.clips.map((c) => ` ${c.id} ${Object.values(c.files).join(" ")}${c.exists.length ? ` (there: ${c.exists.join(", ")}${replace ? ", set aside" : " — --replace to make again"})` : ""}`)].join("\n")); + return 0; + } + const outDir = await deliverableDir(dir, batchDirName(take)); + const started = Date.now(); + const record = { + version: 1, kind: "shorts-batch", project: r.project.id, take, + // The last run: what it was asked. Each clip's row says what IT was last built with. + last: { argv: ["shorts", r.project.id, "--take", take, ...(again ? ["--again"] : ["--items", entries.map((e) => e.id).join(","), "--formats", formats.join(",")])], caps, madeAt: new Date().toISOString(), buildSeconds: 0 }, + clips: /** @type {any[]} */ ([...priorRows.values()]), + }; + const put = (row) => { + const i = record.clips.findIndex((x) => x.id === row.id); + if (i >= 0) record.clips[i] = row; + else record.clips.push(row); + }; + let failed = 0; + for (const c of plan) { + for (const f of Object.keys(c.files)) { + const file = path.join(outDir, c.files[f]); + const base = { id: c.id, name: c.name, title: c.title, format: f, knobs: c.knobs, snapshot: c.snapshot }; + let row; + try { + if (existsSync(file)) { + if (!replace) throw new CliError(`${c.files[f]} is there — --replace to make it again (the old one set aside)`); + const aside = asideName(file); + await rename(file, aside); + await rename(file.replace(/\.mp4$/, ".json"), aside.replace(/\.mp4$/, ".json")).catch(() => {}); + } + say(`shorts: ${c.id} (${c.name}) ${f} …`); + const done = await build( + { project: r.project.id, take, items: [c.id], knobs: { ...c.knobs, maxSeconds: caps[f] }, name: "shorts", out: file, landscape: BATCH_FORMATS[f].landscape, overrides: { [c.id]: c.snapshot } }, + { reportsRoot, say }, + ); + const rec = "record" in done ? done.record : null; + row = rowAfter(record.clips.find((x) => x.id === c.id) ?? null, { ...base, file: c.files[f], seconds: rec?.seconds ?? null, notes: rec?.notes ?? [] }); + } catch (e) { + if (!(e instanceof Error)) throw e; + failed += 1; + err(`shorts: ${c.id} ${f}: ${e.message}`); + row = rowAfter(record.clips.find((x) => x.id === c.id) ?? null, { ...base, error: e.message, exists: existsSync(file) }); + } + put(row); + record.last.buildSeconds = Math.round((Date.now() - started) / 1000); + await writeJson(path.join(outDir, BATCH_FILE), record); + } + } + if (json) log(JSON.stringify(record, null, 2)); + else { + for (const c of record.clips.filter((x) => entries.some((e) => e.id === x.id))) { + for (const [f, ns] of Object.entries(c.notes ?? {})) for (const n of ns) log(`note: ${c.id} ${f}: ${n}`); + log(`${c.id} ${Object.values(c.files).join(" ") || "(nothing made)"}`); + } + log(`wrote ${path.join(outDir, BATCH_FILE)}${failed ? ` — ${failed} failed` : ""}`); + } + return failed ? 1 : 0; + } catch (e) { + if (isRefusal(e)) { + err(`umtool shorts: ${e.message}`); + return 2; + } + throw e; + } +} + +export { FORMAT_NAMES }; diff --git a/umtool/lib/report/storage.mjs b/umtool/lib/report/storage.mjs @@ -608,6 +608,8 @@ export const DELIVERABLES_MODES = ["local", "media"]; const CLIPS = "clips"; /** A share batch's directory prefix (lib/report/deliver.mjs's SHARE_PREFIX). */ const SHARE = "share-"; +/** A take's batch of shorts (lib/report/shortsBatch.mjs's BATCH_PREFIX): `shorts-<take>`. */ +const SHORTS = "shorts-"; /** What a cut move leaves beside a deliverable: `<name>.moved-<stamp>` or `<name>.incoming`. */ const LEFTOVER = /^(.+)\.(moved-[^/]*|incoming)$/; @@ -616,7 +618,7 @@ const LEFTOVER = /^(.+)\.(moved-[^/]*|incoming)$/; export const isDeliverableName = (name) => typeof name === "string" && !LEFTOVER.test(name) && - (name === CLIPS || (name.startsWith(SHARE) && name.length > SHARE.length && !/[\/\\\0]/.test(name))); + (name === CLIPS || ([SHARE, SHORTS].some((x) => name.startsWith(x) && name.length > x.length) && !/[\/\\\0]/.test(name))); /** * `storage.deliverables` of a parsed manifest. @@ -692,7 +694,7 @@ export async function deliverableDir(projectDir, name, opts = {}) { } /** - * Every deliverable a project has, by name: `clips` and each `share-*` that is + * Every deliverable a project has, by name: `clips` and each `share-*` (and `shorts-*`) that is * a directory or a link -- and the name of any whose cut move left only a * leftover (`clips.moved-<ts>` with no `clips`), so a move finishes it. * `clips` first, then the batches by name. diff --git a/umtool/lib/report/verticalCli.mjs b/umtool/lib/report/verticalCli.mjs @@ -27,7 +27,7 @@ export const VERTICAL_USAGE = [ "usage: umtool vertical <project> --take <t> (--reel <r> | --beats FILE | --items <id>,<id>…)", " [--clip full|framed|quote] [--post card|stack|media] [--side split|overlay]", " [--hook title|section|\"<a line of the cut's own copy>\"] [--captions l|xl] [--lines 1|2]", - " [--loudness -14] [--max 60] [--name N] [--out FILE] [--reframe] [--dry-run] [--json]", + " [--loudness -14] [--max 60] [--name N] [--out FILE] [--reframe | --landscape] [--dry-run] [--json]", " [--intro | --no-intro] [--no-outro] [--deck stacked|bare]", "", "A vertical short (1080x1920, the take's fps) of a take's items: a reel's beats (promo/<r>-beats.json, as", @@ -42,6 +42,7 @@ export const VERTICAL_USAGE = [ "60 s (--max) is said so. A clip's vertical crop and layout and its side post are read from the PROJECT's", "manifest over the take's. The hook only ever says the cut's own words: a clip's title, its section's title,", "or a line you give it from the cut's copy.", + "--landscape builds the same items in the take's own 16:9 look instead (its header, QR and deck), to compare.", "--reframe recomposes the take's finished 16:9 master instead (each item's region -- the footage, the post's", "card and attachment, the deck's date line -- laid out 9:16): nothing is cut again, any finished take.", "Writes takes/<t>/out/<slug>.<name>.<layout>.vertical.mp4 (--out: that file) and a .json beside it. The build", @@ -55,12 +56,12 @@ export const VERTICAL_USAGE = [ "source line and its QR above the bottom band; --deck bare is the vertical with no deck, as it first shipped.", ].join("\n"); -class CliError extends Error {} +export class CliError extends Error {} const VALUED = new Set(["--take", "--reel", "--beats", "--items", "--clip", "--post", "--side", "--hook", "--captions", "--lines", "--loudness", "--max", "--name", "--out", "--deck"]); const BOOL = new Set(["--reframe", "--landscape", "--dry-run", "--json", "--help", "--intro", "--no-intro", "--no-outro"]); -function parse(args) { +export function parse(args) { /** @type {Record<string, string>} */ const flags = {}; const positional = []; @@ -133,6 +134,188 @@ function run(argv, { cwd, log }) { }); } +/** The options `umtool vertical`'s flags ask for (buildShort's), read from its parsed flags. */ +export function shortOptionsOf(p) { + return { + project: p.positional[0], + take: p.flags["--take"] ?? null, + reel: p.flags["--reel"] ?? null, + beats: p.has("--beats") ? p.flags["--beats"] : null, + items: p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null, + knobs: knobsOfFlags(p.flags), + name: p.flags["--name"] ?? null, + out: p.flags["--out"] ?? null, + reframe: p.has("--reframe"), + landscape: p.has("--landscape"), + dryRun: p.has("--dry-run"), + intro: p.has("--intro"), + noIntro: p.has("--no-intro"), + noOutro: p.has("--no-outro"), + }; +} + +/** + * ONE SHORT, BUILT (the builder behind `umtool vertical` and `umtool shorts`): a take's items -- a reel's beats, a + * beats file or a list of items -- natively in a 9:16 layout, recomposed from the master (`reframe`), or in the + * take's 16:9 look (`landscape`). Writes the mp4 and its record beside it and returns the record; `dryRun` returns + * what it would do instead. Throws a CliError (or the plan's VerticalPlanError) for a refusal. + * + * `overrides` (`{<clip id>: {<key>: value}}`, a batch's snapshot): laid over the PROJECT's own entries before the + * plan reads them, so a rebuild from a record frames each clip as it was then. + * + * @param {{ project: string, take?: string | null, reel?: string | null, beats?: string | null, items?: string[] | null, + * knobs?: Record<string, any>, name?: string | null, out?: string | null, reframe?: boolean, landscape?: boolean, + * dryRun?: boolean, intro?: boolean, noIntro?: boolean, noOutro?: boolean, overrides?: Record<string, Record<string, any>> | null }} o + * @param {{ reportsRoot?: string, say?: (s: string) => void }} [ctx] + * @returns {Promise<{ dryRun: Record<string, any> } | { record: Record<string, any> }>} + */ +export async function buildShort(o, { reportsRoot = REPORTS_ROOT, say = () => {} } = {}) { + const V = await import("umtool-report-to-video/vertical"); + const P = await import("umtool-report-to-video/vertical-plan"); + const r = await resolveProject(o.project, reportsRoot); + if (r.ambiguous) throw new CliError(`"${o.project}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${o.project}"`); + if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + const dir = r.project.dir; + const reel = o.reel ?? null; + let take = o.take ?? null; + let beats = null; + /** The reel's settings (its intro, outro and crossfade), when the short is a reel. */ + let reelSettings = /** @type {Record<string, any>} */ ({}); + if (reel) { + const doc = await readTrailerBeats(dir, { reel }); + if (!doc.exists) throw new CliError(`no reel ${reel}: ${reelFileOf(reel)} is not there`); + beats = P.beatsOf(doc.beats); + reelSettings = doc.settings ?? {}; + take ??= doc.settings?.take ?? null; + } else if (o.beats) { + const doc = await readJson(path.resolve(o.beats)); + if (!doc) throw new CliError(`--beats ${o.beats}: not a JSON file`); + beats = P.beatsOf(doc); + } + const items = o.items?.length ? o.items : null; + if (!beats && !items) throw new CliError("--reel <r>, --beats FILE or --items <id>,…: what the short is made of"); + if (!take) throw new CliError("--take <t>: the take whose items the short is cut from"); + if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); + const takeDir = path.join(takesDirOf(dir), take); + const takeManifest = await takeManifestOf(dir, take); + const projectManifest = await readJson(path.join(dir, "video.manifest.json")); + const outDir = path.join(takeDir, "out"); + const sourced = path.join(outDir, "sourced"); + const schedule = await readJson(path.join(sourced, "schedule.json")); + const knobs = o.knobs ?? {}; + const errors = V.validateVerticalRender({ render: { format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } } }); + if (errors.length) throw new CliError(errors.join("; ")); + const name = P.shortName({ reel, name: o.name ?? null }); + const reframe = !!o.reframe; + // `landscape`: the same items in the take's own 16:9 look (a side post as a panel), for comparison. + const landscape = !!o.landscape; + if (landscape && reframe) throw new CliError("--landscape or --reframe, not both"); + const tag = landscape ? "landscape" : P.layoutTag(knobs, { reframe }); + const slug = takeManifest.slug ?? r.project.id.split("/").pop(); + const outFile = o.out ? path.resolve(o.out) : path.join(outDir, `${slug}.${name}.${tag}${landscape ? "" : ".vertical"}.mp4`); + const cuts = new Map(); + for (const e of takeManifest.timeline ?? []) { + if (e?.type !== "clip") continue; + const c = await readJson(path.join(sourced, "segments", `${e.id}.cut.json`)); + if (c) cuts.set(e.id, c); + } + // The brand intro (9:16) and the reel's outro card (outro.mjs), added after the short is made. + const introSpec = o.noIntro ? null : isObj(reelSettings.intro) ? reelSettings.intro : (o.intro || reelSettings.intro === true) ? true : null; + let outro = null; + const ro = o.noOutro ? null : resolveOutro(reelSettings.outro, { reelTitle: reelSettings.title ?? null, projectTitle: projectManifest?.title ?? null }); + if (ro) { + if (!ro.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 = ro.image ? path.join(dir, ro.image) : null; + if (imageFile && !existsSync(imageFile)) throw new CliError(`the reel ${reel}'s outro image ${ro.image} is not a file of ${r.project.id}`); + outro = { ...ro, imageFile }; + } + const project = P.withOverrides(projectManifest?.timeline ?? [], o.overrides ?? null); + const plan = P.planVerticalCut({ timeline: takeManifest.timeline ?? [], beats, items, schedule, cuts, project }); + if (o.dryRun) { + return { dryRun: { project: r.project.id, take, name, layout: tag, wouldWrite: outFile, intro: introSpec ? (introSpec === true ? "the take's render.intro, else the default" : introSpec) : null, outro: outro ? { title: outro.title, text: outro.text, image: outro.image, seconds: outro.seconds } : null, pieces: plan.pieces, items: plan.timeline.map((e) => ({ id: e.id, type: e.type, start: e.start, end: e.end })) } }; + } + const started = Date.now(); + let made; + if (reframe) { + const RF = await import("umtool-report-to-video/reframe"); + made = await RF.reframeTake({ takeDir, outDir, slug, beats, items, plan, render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, outFile, log: say }); + } else if (landscape) { + const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`); + await writeFile(renderPath, JSON.stringify({ ...takeManifest, render: P.renderForPart(takeManifest.render, plan.timeline), timeline: plan.timeline }, null, 2) + "\n", "utf8"); + const own = path.join(takeDir, `out-landscape-${name}`); + const argv = [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", own, "--skip-fetch", "--no-chapters"]; + say(`vertical --landscape: building ${plan.timeline.length} item(s) 16:9 in the heavy slot …`); + const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true })); + if (code !== 0) throw new CliError(`the landscape build exited ${code}`); + const RF = await import("umtool-report-to-video/reframe"); + await mkdir(path.dirname(outFile), { recursive: true }); + await writeFile(outFile, await readFile(path.join(own, `${slug}.mp4`))); + made = { seconds: await RF.probeSeconds(outFile), loudness: null }; + } else { + // The build's manifest: the take's render, the planned items; beside the project's manifest, so its files resolve. + const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`); + const doc = { ...takeManifest, timeline: plan.timeline }; + await writeFile(renderPath, JSON.stringify(doc, null, 2) + "\n", "utf8"); + const work = `vertical-${name}-${tag}`; + const sections = V.sectionTitlesOf(takeManifest); + const built = path.join(outDir, `${slug}.${name}.${tag}.vertical-build.mp4`); + const argv = [ + process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", outDir, + "--skip-fetch", "--no-chapters", "--vertical", "--vertical-knobs", JSON.stringify(knobs), "--vertical-work", work, "--vertical-out", built, + // The hook "section" names a clip's section in the WHOLE take (each planned entry under its source's id). + "--vertical-sections", JSON.stringify(Object.fromEntries(plan.timeline.map((e) => [e.id, sections.get(e.id.replace(/~\d+$/, "")) ?? null]))), + ]; + say(`vertical: building ${plan.timeline.length} item(s) 9:16 in the heavy slot …`); + const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true })); + if (code !== 0) throw new CliError(`the vertical build exited ${code}`); + const RF = await import("umtool-report-to-video/reframe"); + made = await RF.assembleShort({ + pieces: plan.pieces, segmentsDir: path.join(outDir, work, "segments"), built, outFile, + // A stacked vertical deck's pieces are cut from the built cut (its deck laid over it), at the build's places. + schedule: V.stackedDeckWanted({ ...(takeManifest.render ?? {}), format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }) + ? await readJson(path.join(outDir, work, "schedule.json")) + : null, + render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, log: say, + }); + } + // The intro before and the card after, in one pass, in the heavy slot (the intro is a HyperFrames render, cached). + let wrapped = { intro: null, outro: null }; + if ((introSpec || outro) && !landscape) { + const { wrapShort } = await import("umtool-report-to-video/reel-intro"); + const RF = await import("umtool-report-to-video/reframe"); + const slot = await heavySlot(); + // The 9:16 end card (outro.mjs) -- the stacked deck's only: a bare short's outro is the card it always was. + const endCard = await endCardOf({ + render: takeManifest.render ?? {}, knobs, provenance: takeManifest.provenance ?? {}, timeline: plan.timeline, + schedule: reframe || landscape ? null : await readJson(path.join(outDir, `vertical-${name}-${tag}`, "schedule.json")), + }); + wrapped = await slot(["umtool", "vertical", r.project.id, "--take", take, ...(reel ? ["--reel", reel] : []), "(intro/outro)"], () => wrapShort({ + file: outFile, takeDir, render: takeManifest.render ?? {}, manifest: takeManifest, introSpec, outro, + xfade: typeof reelSettings.xfade === "number" ? reelSettings.xfade : 0.3, log: say, endCard, + })); + made = { ...made, seconds: await RF.probeSeconds(outFile) }; + } + const record = { + version: 1, kind: "vertical-short", project: r.project.id, take, name, layout: tag, reframe, + knobs, pieces: plan.pieces, ...(wrapped.intro ? { intro: wrapped.intro } : {}), ...(wrapped.outro ? { outro: wrapped.outro } : {}), seconds: made.seconds, loudness: made.loudness ?? null, + notes: V.verticalNotes({ format: "vertical", vertical: knobs }, made.seconds), out: outFile, + madeAt: new Date().toISOString(), buildSeconds: Math.round((Date.now() - started) / 1000), + }; + await writeFile(outFile.replace(/\.mp4$/, ".json"), JSON.stringify(record, null, 2) + "\n", "utf8"); + return { record }; +} + +/** A take's manifest as rendered, else (a draft, never rendered) the project's with the take's patch laid on. */ +export async function takeManifestOf(dir, take) { + const rendered = await readJson(path.join(takesDirOf(dir), take, "video.manifest.json")); + if (rendered) return rendered; + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + return resolveTakeManifest(dir, take).then((x) => x.manifest, (e) => { + throw new CliError(`take ${take}: ${e instanceof Error ? e.message : e}`); + }); +} + /** * `umtool vertical …` * @param {string[]} args everything after `vertical` @@ -140,8 +323,6 @@ function run(argv, { cwd, log }) { * @returns {Promise<number>} */ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) { - const V = await import("umtool-report-to-video/vertical"); - const P = await import("umtool-report-to-video/vertical-plan"); try { const p = parse(args); if (p.has("--help") || !p.positional.length) { @@ -150,153 +331,21 @@ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log = } const json = p.has("--json"); const say = json ? err : log; - 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 dir = r.project.dir; - const reel = p.flags["--reel"] ?? null; - let take = p.flags["--take"] ?? null; - let beats = null; - /** The reel's settings (its intro, outro and crossfade), when the short is a reel. */ - let reelSettings = /** @type {Record<string, any>} */ ({}); - if (reel) { - const doc = await readTrailerBeats(dir, { reel }); - if (!doc.exists) throw new CliError(`no reel ${reel}: ${reelFileOf(reel)} is not there`); - beats = P.beatsOf(doc.beats); - reelSettings = doc.settings ?? {}; - take ??= doc.settings?.take ?? null; - } else if (p.has("--beats")) { - const doc = await readJson(path.resolve(p.flags["--beats"])); - if (!doc) throw new CliError(`--beats ${p.flags["--beats"]}: not a JSON file`); - beats = P.beatsOf(doc); - } - const items = p.has("--items") ? p.flags["--items"].split(",").map((s) => s.trim()).filter(Boolean) : null; - if (!beats && !items) throw new CliError("--reel <r>, --beats FILE or --items <id>,…: what the short is made of"); - if (!take) throw new CliError("--take <t>: the take whose items the short is cut from"); - if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); - const takeDir = path.join(takesDirOf(dir), take); - // The take's manifest as rendered, else (a draft, never rendered) the project's with the take's patch laid on. - let takeManifest = await readJson(path.join(takeDir, "video.manifest.json")); - if (!takeManifest) { - const { resolveTakeManifest } = await import("./takeManifest.mjs"); - takeManifest = await resolveTakeManifest(dir, take).then((x) => x.manifest, (e) => { - throw new CliError(`take ${take}: ${e instanceof Error ? e.message : e}`); - }); - } - const projectManifest = await readJson(path.join(dir, "video.manifest.json")); - const outDir = path.join(takeDir, "out"); - const sourced = path.join(outDir, "sourced"); - const schedule = await readJson(path.join(sourced, "schedule.json")); - const knobs = knobsOfFlags(p.flags); - const errors = V.validateVerticalRender({ render: { format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } } }); - if (errors.length) throw new CliError(errors.join("; ")); - const name = P.shortName({ reel, name: p.flags["--name"] ?? null }); - const reframe = p.has("--reframe"); - // `--landscape`: the same items in the take's own 16:9 look (a side post as a panel), for comparison. - const landscape = p.has("--landscape"); - if (landscape && reframe) throw new CliError("--landscape or --reframe, not both"); - const tag = landscape ? "landscape" : P.layoutTag(knobs, { reframe }); - const slug = takeManifest.slug ?? r.project.id.split("/").pop(); - const outFile = p.flags["--out"] ? path.resolve(p.flags["--out"]) : path.join(outDir, `${slug}.${name}.${tag}${landscape ? "" : ".vertical"}.mp4`); - const cuts = new Map(); - for (const e of takeManifest.timeline ?? []) { - if (e?.type !== "clip") continue; - const c = await readJson(path.join(sourced, "segments", `${e.id}.cut.json`)); - if (c) cuts.set(e.id, c); - } - // The brand intro (9:16) and the reel's outro card (outro.mjs), added after the short is made. - const introSpec = p.has("--no-intro") ? null : isObj(reelSettings.intro) ? reelSettings.intro : (p.has("--intro") || reelSettings.intro === true) ? true : null; - let outro = null; - const o = p.has("--no-outro") ? null : resolveOutro(reelSettings.outro, { reelTitle: reelSettings.title ?? null, projectTitle: projectManifest?.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(dir, o.image) : null; - if (imageFile && !existsSync(imageFile)) throw new CliError(`the reel ${reel}'s outro image ${o.image} is not a file of ${r.project.id}`); - outro = { ...o, imageFile }; - } - const plan = P.planVerticalCut({ timeline: takeManifest.timeline ?? [], beats, items, schedule, cuts, project: projectManifest?.timeline ?? [] }); - if (p.has("--dry-run")) { - const out = { project: r.project.id, take, name, layout: tag, wouldWrite: outFile, intro: introSpec ? (introSpec === true ? "the take's render.intro, else the default" : introSpec) : null, outro: outro ? { title: outro.title, text: outro.text, image: outro.image, seconds: outro.seconds } : null, pieces: plan.pieces, items: plan.timeline.map((e) => ({ id: e.id, type: e.type, start: e.start, end: e.end })) }; - log(json ? JSON.stringify(out, null, 2) : [`would write ${outFile}`, ...(introSpec ? [" (intro, 9:16)"] : []), ...plan.pieces.map((x) => ` ${x.id}${x.to === null ? "" : ` ${x.from}–${x.to}`}`), ...(outro ? [` (outro card "${outro.title}", ${outro.seconds} s)`] : [])].join("\n")); + const done = await buildShort(shortOptionsOf(p), { reportsRoot, say }); + if ("dryRun" in done) { + const out = done.dryRun; + log(json ? JSON.stringify(out, null, 2) : [`would write ${out.wouldWrite}`, ...(out.intro ? [" (intro, 9:16)"] : []), ...out.pieces.map((x) => ` ${x.id}${x.to === null ? "" : ` ${x.from}–${x.to}`}`), ...(out.outro ? [` (outro card "${out.outro.title}", ${out.outro.seconds} s)`] : [])].join("\n")); return 0; } - const started = Date.now(); - let made; - if (reframe) { - const RF = await import("umtool-report-to-video/reframe"); - made = await RF.reframeTake({ takeDir, outDir, slug, beats, items, plan, render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, outFile, log: say }); - } else if (landscape) { - const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`); - await writeFile(renderPath, JSON.stringify({ ...takeManifest, render: P.renderForPart(takeManifest.render, plan.timeline), timeline: plan.timeline }, null, 2) + "\n", "utf8"); - const own = path.join(takeDir, `out-landscape-${name}`); - const argv = [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", own, "--skip-fetch", "--no-chapters"]; - say(`vertical --landscape: building ${plan.timeline.length} item(s) 16:9 in the heavy slot …`); - const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true })); - if (code !== 0) throw new CliError(`the landscape build exited ${code}`); - const RF = await import("umtool-report-to-video/reframe"); - await mkdir(path.dirname(outFile), { recursive: true }); - await writeFile(outFile, await readFile(path.join(own, `${slug}.mp4`))); - made = { seconds: await RF.probeSeconds(outFile), loudness: null }; - } else { - // The build's manifest: the take's render, the planned items; beside the project's manifest, so its files resolve. - const renderPath = path.join(dir, `.vertical-${take}-${name}.render.json`); - const doc = { ...takeManifest, timeline: plan.timeline }; - await writeFile(renderPath, JSON.stringify(doc, null, 2) + "\n", "utf8"); - const work = `vertical-${name}-${tag}`; - const sections = V.sectionTitlesOf(takeManifest); - const built = path.join(outDir, `${slug}.${name}.${tag}.vertical-build.mp4`); - const argv = [ - process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), renderPath, "--out", outDir, - "--skip-fetch", "--no-chapters", "--vertical", "--vertical-knobs", JSON.stringify(knobs), "--vertical-work", work, "--vertical-out", built, - // The hook "section" names a clip's section in the WHOLE take (each planned entry under its source's id). - "--vertical-sections", JSON.stringify(Object.fromEntries(plan.timeline.map((e) => [e.id, sections.get(e.id.replace(/~\d+$/, "")) ?? null]))), - ]; - say(`vertical: building ${plan.timeline.length} item(s) 9:16 in the heavy slot …`); - const code = await run(argv, { cwd: path.join(UMTOOL_DIR, ".."), log: say }).finally(() => rm(renderPath, { force: true })); - if (code !== 0) throw new CliError(`the vertical build exited ${code}`); - const RF = await import("umtool-report-to-video/reframe"); - made = await RF.assembleShort({ - pieces: plan.pieces, segmentsDir: path.join(outDir, work, "segments"), built, outFile, - // A stacked vertical deck's pieces are cut from the built cut (its deck laid over it), at the build's places. - schedule: V.stackedDeckWanted({ ...(takeManifest.render ?? {}), format: "vertical", vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }) - ? await readJson(path.join(outDir, work, "schedule.json")) - : null, - render: { ...takeManifest.render, vertical: { ...(takeManifest.render?.vertical ?? {}), ...knobs } }, log: say, - }); - } - // The intro before and the card after, in one pass, in the heavy slot (the intro is a HyperFrames render, cached). - let wrapped = { intro: null, outro: null }; - if ((introSpec || outro) && !landscape) { - const { wrapShort } = await import("umtool-report-to-video/reel-intro"); - const RF = await import("umtool-report-to-video/reframe"); - const slot = await heavySlot(); - // The 9:16 end card (outro.mjs) -- the stacked deck's only: a bare short's outro is the card it always was. - const endCard = await endCardOf({ - render: takeManifest.render ?? {}, knobs, provenance: takeManifest.provenance ?? {}, timeline: plan.timeline, - schedule: reframe || landscape ? null : await readJson(path.join(outDir, `vertical-${name}-${tag}`, "schedule.json")), - }); - wrapped = await slot(["umtool", "vertical", r.project.id, "--take", take, ...(reel ? ["--reel", reel] : []), "(intro/outro)"], () => wrapShort({ - file: outFile, takeDir, render: takeManifest.render ?? {}, manifest: takeManifest, introSpec, outro, - xfade: typeof reelSettings.xfade === "number" ? reelSettings.xfade : 0.3, log: say, endCard, - })); - made = { ...made, seconds: await RF.probeSeconds(outFile) }; - } - const record = { - version: 1, kind: "vertical-short", project: r.project.id, take, name, layout: tag, reframe, - knobs, pieces: plan.pieces, ...(wrapped.intro ? { intro: wrapped.intro } : {}), ...(wrapped.outro ? { outro: wrapped.outro } : {}), seconds: made.seconds, loudness: made.loudness ?? null, - notes: V.verticalNotes({ format: "vertical", vertical: knobs }, made.seconds), out: outFile, - madeAt: new Date().toISOString(), buildSeconds: Math.round((Date.now() - started) / 1000), - }; - await writeFile(outFile.replace(/\.mp4$/, ".json"), JSON.stringify(record, null, 2) + "\n", "utf8"); + const record = done.record; if (json) log(JSON.stringify(record, null, 2)); else { for (const n of record.notes) log(`note: ${n}`); - log(`wrote ${outFile} (${made.seconds.toFixed(1)} s, 1080x1920)`); + log(`wrote ${record.out} (${record.seconds.toFixed(1)} s, ${record.layout === "landscape" ? "1920x1080" : "1080x1920"})`); } return 0; } catch (e) { - if (e instanceof CliError || e?.name === "VerticalPlanError") { + if (isRefusal(e)) { err(`umtool vertical: ${e.message}`); return 2; } @@ -304,3 +353,5 @@ export async function verticalCommand(args, { reportsRoot = REPORTS_ROOT, log = } } +/** A refusal (said, exit 2) rather than a crash. */ +export const isRefusal = (e) => e instanceof CliError || e?.name === "VerticalPlanError"; diff --git a/umtool/report-to-video/vertical-plan.mjs b/umtool/report-to-video/vertical-plan.mjs @@ -35,15 +35,40 @@ export function beatsOf(doc) { }); } -/** The project's per-clip framing (vertical, side) laid over a take's entry. */ +/** + * The keys of a clip a short reads from the PROJECT over the take's: set with `umtool set` after the take was made + * (its framing, its side post, the clip kit's keys). A batch's record snapshots them (lib/report/shortsBatch.mjs). + */ +export const PROJECT_KEYS = Object.freeze(["vertical", "side"]); + +/** The project's per-clip framing (PROJECT_KEYS) laid over a take's entry. */ export function withProjectFraming(entry, projectById) { const own = projectById?.get?.(entry?.id); if (!own || entry?.type !== "clip") return entry; const out = { ...entry }; - for (const k of ["vertical", "side"]) if (own[k] !== undefined) out[k] = own[k]; + for (const k of PROJECT_KEYS) if (own[k] !== undefined) out[k] = own[k]; return out; } +/** + * The project's entries with a snapshot laid over them (`{<id>: {<key>: value | null}}`, a batch record's): each + * named key set (null: removed), so a rebuild reads each clip as the record saw it. Null: the entries as they are. + */ +export function withOverrides(timeline, overrides) { + if (!isObj(overrides)) return timeline; + return (timeline ?? []).map((e) => { + const o = typeof e?.id === "string" && isObj(overrides[e.id]) ? overrides[e.id] : null; + if (!o) return e; + const out = { ...e }; + for (const [k, v] of Object.entries(o)) { + if (!PROJECT_KEYS.includes(k)) continue; + if (v === null) delete out[k]; + else out[k] = v; + } + return out; + }); +} + /** A clip entry cut to the source span [a, b]: its gaps inside kept, its own cut points dropped. */ export function cutClip(entry, a, b, id = entry.id) { const { cutStart: _a, cutEnd: _b, ...rest } = entry;