// THE TRAILER'S BEATS, edited (UI notes 2026-10-30, item 11). // // `umtool trailer

--take --beats promo/trailer-beats.json` cuts a // trailer out of a finished master (report-to-video/trailer.mjs). The beats // file was hand JSON: beats went stale after tightening (five fell outside // their clips on the Ember cut), the X limit (under 2:20) was checked after the // encode, and putting the beats in the cut's order needed a script. // // This is that file's ONE writer -- the Trailer page and `umtool trailer-beats` // both go through it -- and its reader, which says, before any encode: // - each beat's length (a clip beat's gaps taken out, as the master plays it) // and the running length against the platform limit, with the trailer's // crossfades and the brand intro counted; // - each beat that falls outside its clip's window, or names a clip that is // no longer in the cut; // - whether the beats are in the cut's order (Order by the cut puts them so). // // The file keeps its shape: a plain array stays an array (what `--beats` has // always read) until a setting is saved, when it becomes `{ limit, xfade, // intro, beats }` -- parseBeats reads `{ beats }` too. Its indent is kept. A // file that does not parse is never written over. The token is its mtime. // // BEAT REELS (2 Nov, lane/beat-reels): a project has more than one reel -- // the X trailer, a teaser, a "Kirsche-first" cut -- each its own file, // `promo/-beats.json` (the reel `trailer` is today's // promo/trailer-beats.json, its path unchanged), with its own limit, // crossfade, intro, title and the take it is cut from. Every function here // takes `{ reel }` (default `trailer`), so a caller that never names one // reads and writes exactly the file it always did. A beat may carry the // walk's `verdict` ("confirmed", or "note": a note was left on it), and every // write leaves an UNDO POINT: the file as it was, kept in // `promo/..undo.json` (newest last, REEL_UNDO_KEEP of them), which // `undoTrailerBeats` puts back. // // Plain ESM: the CLI runs it under bare node. import { createHash } from "node:crypto"; import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { gappedLength, gapsOf } from "umtool-report-to-video/gaps"; import { TRAILER_XFADE_DEFAULT, TrailerError, beatGaps, parseBeats } from "umtool-report-to-video/trailer"; import { normalizeOutro, outroAdds, outroErrors, resolveOutro } from "umtool-report-to-video/outro"; import { INTRO_SECONDS, introErrors } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { indentOf } from "./patchMarkers.mjs"; import { appendReelHistory } from "./reelHistory.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TRAILER_BEATS_FILE = path.join("promo", "trailer-beats.json"); /** The reel a caller that names none reads and writes: promo/trailer-beats.json. */ export const DEFAULT_REEL = "trailer"; /** A reel's name: lower case, digits and dashes (it is in a file name and an output name). */ export const REEL_ID = /^[a-z0-9][a-z0-9-]{0,39}$/; export const isReelId = (v) => typeof v === "string" && REEL_ID.test(v); /** How many undo points a reel keeps. */ export const REEL_UNDO_KEEP = 40; /** What a beat's walk may say of it. */ export const BEAT_VERDICTS = Object.freeze(["confirmed", "note"]); /** A reel's beats file, relative to the project: `promo/-beats.json`. */ export function reelFileOf(reel = DEFAULT_REEL) { const name = reel ?? DEFAULT_REEL; if (!isReelId(name)) throw new Error(`"${name}" is not a reel name (lower case, digits and dashes)`); return path.join("promo", `${name}-beats.json`); } /** The file a reel's cut is written to in its take's out/: `..mp4` (the trailer reel: `.trailer.mp4`, as ever). */ export const reelOutName = (slug, reel = DEFAULT_REEL) => `${slug}.${reel ?? DEFAULT_REEL}.mp4`; /** X's video limit is 2:20; a trailer must be UNDER it. */ export const TRAILER_LIMIT_DEFAULT = 140; /** Platform limits a person picks from (seconds). */ export const TRAILER_LIMITS = Object.freeze([ { id: "x", label: "X (2:20)", seconds: 140 }, { id: "instagram", label: "Instagram reel (1:30)", seconds: 90 }, { id: "shorts", label: "YouTube Short (3:00)", seconds: 180 }, { id: "tiktok", label: "TikTok (10:00)", seconds: 600 }, ]); /** A beat edge this close to its clip's edge is on it (the build records keep 3 dp). */ const EPS = 0.02; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const r2 = (n) => Number(Number(n).toFixed(2)); export class BeatsStale extends Error { constructor(expected, got) { super(`the trailer's beats changed since you read them (${got} vs ${expected})`); this.name = "BeatsStale"; this.stale = true; } } const beatsFile = (dir, reel = DEFAULT_REEL) => path.join(dir, reelFileOf(reel)); const undoFileOf = (dir, reel = DEFAULT_REEL) => { const rel = reelFileOf(reel); return path.join(dir, path.dirname(rel), `.${path.basename(rel)}.undo.json`); }; /** @typedef {{ on: boolean, title?: string, text?: string, image?: string, seconds?: number }} OutroSetting */ /** @typedef {{ limit?: number, xfade?: number, intro?: boolean | Record, outro?: OutroSetting, title?: string, take?: string }} TrailerSettings */ /** @typedef {{ token?: string | null, reel?: string }} BeatsWriteOpts */ /** The file's mtime, the token a writer hands back; null when there is no file. */ export async function beatsToken(dir, reel = DEFAULT_REEL) { const st = await stat(beatsFile(dir, reel)).catch(() => null); return st ? String(Math.round(st.mtimeMs)) : null; } /** * The project's reels: `trailer` always (its file may not exist yet), then * every other `promo/-beats.json`, by name. Each with its beat count, * title and limit when its file reads. * * @param {string} dir */ export async function listReels(dir) { const names = await readdir(path.join(dir, "promo")).catch(() => []); const found = new Set([DEFAULT_REEL]); for (const n of names) { const m = /^([a-z0-9][a-z0-9-]{0,39})-beats\.json$/.exec(n); if (m) found.add(m[1]); } const out = []; for (const name of [DEFAULT_REEL, ...[...found].filter((n) => n !== DEFAULT_REEL).sort()]) { try { const r = await readTrailerBeats(dir, { reel: name }); out.push({ name, file: reelFileOf(name), exists: r.exists, beats: r.beats.length, title: r.settings.title ?? null, limit: r.settings.limit ?? TRAILER_LIMIT_DEFAULT, take: r.settings.take ?? null, error: null }); } catch (e) { out.push({ name, file: reelFileOf(name), exists: true, beats: 0, title: null, limit: TRAILER_LIMIT_DEFAULT, take: null, error: e instanceof Error ? e.message : String(e) }); } } return out; } /** * The beats file, read: `{ exists, shape, beats, settings, indent }`. Missing: * an empty array. Not JSON, or neither an array nor `{ beats }`: an error, * so nothing writes over it. * * @param {string} dir */ export async function readTrailerBeats(dir, { reel = DEFAULT_REEL } = {}) { const rel = reelFileOf(reel); let text; try { text = await readFile(beatsFile(dir, reel), "utf8"); } catch { return { exists: false, shape: /** @type {"array" | "object"} */ ("array"), beats: /** @type {any[]} */ ([]), settings: /** @type {TrailerSettings} */ ({}), indent: 1, token: /** @type {string | null} */ (null), doc: null }; } let doc; try { doc = JSON.parse(text); } catch (e) { throw new Error(`${rel} does not parse; not reading or writing it (${e instanceof Error ? e.message : e})`); } const beats = Array.isArray(doc) ? doc : Array.isArray(doc?.beats) ? doc.beats : null; if (!beats) throw new Error(`${rel} is neither a list of beats nor { "beats": [...] }`); /** @type {TrailerSettings} */ const settings = {}; if (isObj(doc)) { if (typeof doc.limit === "number") settings.limit = doc.limit; if (typeof doc.xfade === "number") settings.xfade = doc.xfade; if (typeof doc.intro === "boolean") settings.intro = doc.intro; // The reel's own intro (render.intro's shape; report-to-video/reel-intro.mjs), when it validates. else if (isObj(doc.intro) && !introErrors(doc.intro).length) settings.intro = doc.intro; // The outro card (report-to-video/outro.mjs), when it validates. if (doc.outro !== undefined && doc.outro !== null && !outroErrors(doc.outro).length) settings.outro = /** @type {OutroSetting} */ (normalizeOutro(doc.outro)); if (typeof doc.title === "string" && doc.title.trim()) settings.title = doc.title; if (typeof doc.take === "string" && TAKE_ID.test(doc.take)) settings.take = doc.take; } return { exists: true, shape: /** @type {"array" | "object"} */ (Array.isArray(doc) ? "array" : "object"), beats, settings, indent: indentOf(text), token: await beatsToken(dir, reel), doc, text }; } const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; const SETTING_KEYS = ["limit", "xfade", "intro", "outro", "title", "take"]; /** The reel's undo points, oldest first: `{ at, what, text }` (`text` null: the file did not exist). */ export async function readReelUndo(dir, { reel = DEFAULT_REEL } = {}) { try { const j = JSON.parse(await readFile(undoFileOf(dir, reel), "utf8")); return Array.isArray(j?.points) ? j.points.filter((p) => p && typeof p.what === "string" && (typeof p.text === "string" || p.text === null)) : []; } catch { return []; } } async function writeUndo(dir, reel, points) { const file = undoFileOf(dir, reel); await mkdir(path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ reel, file: reelFileOf(reel), points: points.slice(-REEL_UNDO_KEEP) }, null, 1) + "\n", "utf8"); await rename(tmp, file); } /** @type {Promise} */ let queue = Promise.resolve(); function withBeatsLock(fn) { const run = queue.then(fn, fn); queue = run.then(() => undefined, () => undefined); return run; } /** * One write: the token, the file re-read inside the lock, `mutate(beats, * settings)` (which throws to refuse), every beat checked by the trailer's own * parseBeats, a `.bak` of the file as it was, then tmp + rename. */ async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an edit", take = null } = {}) { return withBeatsLock(async () => { const current = await beatsToken(dir, reel); if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); const read = await readTrailerBeats(dir, { reel }); const beats = JSON.parse(JSON.stringify(read.beats)); const settings = { ...read.settings }; const result = mutate(beats, settings); if (beats.length) { try { parseBeats(beats); } catch (e) { throw new Error(e instanceof TrailerError ? e.message : String(e)); } } const hasSettings = Object.keys(settings).length > 0; const out = read.shape === "array" && !hasSettings ? beats : { ...(isObj(read.doc) ? read.doc : {}), ...settings, beats }; if (isObj(out)) for (const k of SETTING_KEYS) if (!(k in settings)) delete out[k]; const file = beatsFile(dir, reel); await mkdir(path.dirname(file), { recursive: true }); if (read.exists) await copyFile(file, `${file}.bak`).catch(() => {}); // The undo point: the file as it was, before this write. await writeUndo(dir, reel, [...(await readReelUndo(dir, { reel })), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }]); const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); await rename(tmp, file); // The history (reelHistory.mjs): what moved, old and new, by beat. await appendReelHistory(dir, reelFileOf(reel), { what, take, before: { beats: read.beats, settings: read.settings }, after: { beats, settings } }).catch(() => null); return { ...result, beats, settings, token: await beatsToken(dir, reel) }; }); } /** * Put the reel back as it was before its last write (that write's undo * point, taken off the list). The token guards it like any write. * @param {string} dir * @param {BeatsWriteOpts} [opts] * @returns {Promise<{ undone: string, at: string, left: number, token: string | null }>} */ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL } = {}) { return withBeatsLock(async () => { const current = await beatsToken(dir, reel); if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); const points = await readReelUndo(dir, { reel }); const last = points.pop(); if (!last) throw new Error(`nothing to undo on the reel ${reel}`); const file = beatsFile(dir, reel); const before = await readTrailerBeats(dir, { reel }).catch(() => null); if (last.text === null) await rm(file, { force: true }); else { const tmp = tmpPathFor(file); await writeFile(tmp, last.text, "utf8"); await rename(tmp, file); } await writeUndo(dir, reel, points); const after = await readTrailerBeats(dir, { reel }).catch(() => null); if (before && after) await appendReelHistory(dir, reelFileOf(reel), { what: `undo: ${last.what}`, before, after }).catch(() => null); return { undone: last.what, at: last.at, left: points.length, token: await beatsToken(dir, reel) }; }); } /** * A new reel: `promo/-beats.json`, empty or a copy of another reel's * beats (`from`), with its own title. Refused when the reel exists. * @param {string} dir * @param {string} name * @param {{ from?: string | null, title?: string | null }} [opts] */ export async function createReel(dir, name, { from = null, title = null } = {}) { if (!isReelId(name)) throw new Error(`"${name}" is not a reel name (lower case, digits and dashes, up to 40)`); if (await beatsToken(dir, name)) throw new Error(`the reel ${name} exists (${reelFileOf(name)})`); let beats = []; /** @type {TrailerSettings} */ let settings = {}; if (from) { const src = await readTrailerBeats(dir, { reel: from }); if (!src.exists) throw new Error(`no reel ${from} to copy (${reelFileOf(from)})`); beats = JSON.parse(JSON.stringify(src.beats)).map((b) => { const c = { ...b }; delete c.verdict; return c; }); settings = { ...src.settings }; delete settings.title; } const t = typeof title === "string" ? title.trim().slice(0, 120) : ""; return beatsWrite(dir, null, (list, s) => { list.splice(0, list.length, ...beats); Object.assign(s, settings, t ? { title: t } : {}); return { reel: name, file: reelFileOf(name), copied: from ?? null }; }, { reel: name, what: from ? `new reel ${name}, from ${from}` : `new reel ${name}` }); } /** A beat's anchor (lib/report/reelAnchor.mjs: what it was cut against), carried as written. */ const anchorOf = (b) => (isObj(b.anchor) ? { anchor: b.anchor } : {}); /** A beat as a person writes it: `{ id, start, end, label? }` or `{ at, dur, label? }`, rounded to 2 dp. */ function cleanBeat(b) { if (!isObj(b)) throw new Error("a beat is { id, start, end } or { at, dur }"); const label = typeof b.label === "string" && b.label.trim() ? { label: b.label.trim().slice(0, 120) } : {}; if (b.verdict !== undefined && b.verdict !== null && !BEAT_VERDICTS.includes(b.verdict)) throw new Error(`a beat's verdict is one of ${BEAT_VERDICTS.join(", ")}`); const verdict = BEAT_VERDICTS.includes(b.verdict) ? { verdict: b.verdict } : {}; if (b.id !== undefined) { const start = r2(b.start); const end = r2(b.end); // A beat's gaps (trailer.mjs beatGaps: a clip's gap rule): refused here by the same sentences. let gaps; try { gaps = beatGaps({ start, end, gaps: b.gaps }, `beat ${b.id}`); } catch (e) { throw new Error(e instanceof Error ? e.message : String(e)); } return { id: String(b.id), start, end, ...(gaps.length ? { gaps } : {}), ...label, ...verdict, ...anchorOf(b) }; } return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict, ...anchorOf(b) }; } /** @typedef {((beat: Record) => Record | null) | null} AnchorFor */ /** The take an anchorFor writes against (anchorContext tags it), for the history. */ const anchorTake = (anchorFor) => (anchorFor && typeof anchorFor.take === "string" ? anchorFor.take : null); /** A beat with the anchor of the take it was written against (reelAnchor.mjs anchorContext); none when it does not map there. */ function stamp(b, anchorFor) { if (!anchorFor) return b; const { anchor: _old, ...rest } = b; const a = anchorFor(rest); return a ? { ...rest, anchor: a } : rest; } /** * Anchor beats to a take (reelAnchor.mjs anchorContext's `anchorFor`): all of * them, or the 0-based `only`. A beat that does not map onto the take loses * its anchor (it is said on load). * @param {string} dir * @param {NonNullable} anchorFor * @param {BeatsWriteOpts & { only?: number[] | null, take?: string }} [opts] */ export async function anchorTrailerBeats(dir, anchorFor, { token = null, reel = DEFAULT_REEL, only = null, take = "" } = {}) { return beatsWrite(dir, token, (beats) => { const which = only ?? beats.map((_, k) => k); for (const k of which) beats[indexIn(beats, k)] = stamp(beats[k], anchorFor); return { anchored: which.length }; }, { reel, what: `anchor ${only ? `beat${only.length === 1 ? "" : "s"} ${only.map((k) => k + 1).join(", ")}` : "every beat"}${take ? ` to take ${take}` : ""}`, take: take || null }); } const indexIn = (beats, i, what = "beat") => { const n = Number(i); if (!Number.isInteger(n) || n < 0 || n >= beats.length) throw new Error(`no ${what} ${Number(i) + 1} (1–${beats.length})`); return n; }; /** * Add a beat at index `at` (default: where the cut's order puts it, else the end). * @param {string} dir * @param {Record} beat * @param {{ token?: string | null, at?: number | null, manifest?: Record | null, reel?: string, anchorFor?: AnchorFor }} [opts] */ export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null, reel = DEFAULT_REEL, anchorFor = null } = {}) { return beatsWrite(dir, token, (beats) => { const b = stamp(cleanBeat(beat), anchorFor); let i = beats.length; if (at !== null && at !== undefined) { i = Number(at); if (!Number.isInteger(i) || i < 0 || i > beats.length) throw new Error(`at must be 0–${beats.length}`); } else if (manifest && b.id !== undefined) { // In the cut's order: before the first beat whose clip comes later. const order = cutOrder(manifest); const mine = order.get(b.id); if (mine !== undefined) { const k = beats.findIndex((x) => x.id !== undefined && (order.get(x.id) ?? -1) > mine); if (k >= 0) i = k; } } beats.splice(i, 0, b); return { index: i, beat: b }; }, { reel, what: `add ${beat?.id ?? "a master beat"}`, take: anchorTake(anchorFor) }); } /** * Change beat `i`'s seconds or label (a key given as null removes a label). * @param {string} dir * @param {number} i * @param {Record} patch * @param {BeatsWriteOpts & { anchorFor?: AnchorFor }} [opts] `anchorFor`: the take the edit was made against (its anchor is written) */ export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL, anchorFor = null } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, gaps?, id?, label?, verdict? }"); const b = { ...beats[n] }; for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k]; // Re-pointed to another clip of the cut (a beat whose clip is gone): its seconds go with it. if (patch.id !== undefined) { if (b.id === undefined) throw new Error("a master beat has no clip to re-point"); if (typeof patch.id !== "string" || !patch.id) throw new Error("id is a clip id"); b.id = patch.id; } // The beat's gaps, the whole list ([] or null: none). A clip beat only. if (patch.gaps !== undefined) { if (b.id === undefined) throw new Error("only a clip beat has source seconds to take out; a master beat is { at, dur }"); if (patch.gaps === null || (Array.isArray(patch.gaps) && !patch.gaps.length)) delete b.gaps; else b.gaps = patch.gaps; } for (const k of ["label", "verdict"]) { if (patch[k] === undefined) continue; if (patch[k] === null || patch[k] === "") delete b[k]; else b[k] = patch[k]; } beats[n] = stamp(cleanBeat(b), anchorFor); return { index: n, beat: beats[n] }; }, { reel, what: `beat ${Number(i) + 1}: ${Object.keys(isObj(patch) ? patch : {}).join(", ") || "set"}`, take: anchorTake(anchorFor) }); } /** * Remove beat `i`. * @param {string} dir * @param {number} i * @param {BeatsWriteOpts} [opts] */ export async function removeTrailerBeat(dir, i, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); const [gone] = beats.splice(n, 1); return { index: n, removed: gone }; }, { reel, what: `remove beat ${Number(i) + 1}` }); } /** * Move beat `i` to index `to` (its place after the move). * @param {string} dir * @param {number} i * @param {number} to * @param {BeatsWriteOpts} [opts] */ export async function moveTrailerBeat(dir, i, to, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); const t = Number(to); if (!Number.isInteger(t) || t < 0 || t >= beats.length) throw new Error(`to must be 1–${beats.length}`); const [b] = beats.splice(n, 1); beats.splice(t, 0, b); return { from: n, to: t }; }, { reel, what: `move beat ${Number(i) + 1} to ${Number(to) + 1}` }); } /** * Order the beats as the cut plays them: clip beats by their clip's place in * the timeline (then by start), a raw `{ at, dur }` beat by its master second * among them as best it can -- kept after the clip beat before it. A beat * naming a clip no longer in the cut goes last, and is still flagged. * @param {string} dir * @param {Record} manifest * @param {BeatsWriteOpts} [opts] */ export async function orderTrailerBeats(dir, manifest, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const order = cutOrder(manifest); const keyed = beats.map((b, k) => ({ b, k, key: b.id !== undefined ? order.get(b.id) ?? Infinity : null })); // A raw beat keeps its neighbour: it takes the key of the clip beat before it. let last = -1; for (const x of keyed) { if (x.key === null) x.key = last; else if (Number.isFinite(x.key)) last = x.key; } keyed.sort((a, b) => a.key - b.key || (a.b.id !== undefined && b.b.id !== undefined && a.b.id === b.b.id ? a.b.start - b.b.start : a.k - b.k)); const moved = keyed.some((x, i) => x.k !== i); beats.splice(0, beats.length, ...keyed.map((x) => x.b)); return { moved }; }, { reel, what: "order by the cut" }); } /** * The trailer's settings: `limit` (seconds, the platform's), `xfade` (the * trailer's crossfade), `intro` (opens on the brand intro: `true`, or an * intro of the reel's own, render.intro's shape), `outro` (ends on the card: * `true`/`false` turn it on or off and keep its words, an object merges its * keys -- a key null drops it -- and turns it on), `title` (the * reel's name for a person), `take` (the take it is cut from, pinned). null * removes one (its default again). * @param {string} dir * @param {Record} patch * @param {BeatsWriteOpts} [opts] */ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFAULT_REEL } = {}) { if (isObj(patch) && isObj(patch.outro) && typeof patch.outro.image === "string") { const img = patch.outro.image.trim().replace(/^\.\//, ""); const errors = outroErrors({ image: img }); if (errors.length) throw new Error(errors.join("; ")); if (!(await stat(path.join(dir, img)).then((st) => st.isFile(), () => false))) throw new Error(`outro.image ${img} is not a file of the project`); } return beatsWrite(dir, token, (_beats, settings) => { if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro?, outro?, title?, take? }"); for (const k of ["limit", "xfade"]) { if (patch[k] === undefined) continue; if (patch[k] === null || patch[k] === "") { delete settings[k]; continue; } const v = Number(patch[k]); if (!Number.isFinite(v) || v < 0 || (k === "limit" && v < 5) || (k === "xfade" && v > 3)) { throw new Error(k === "limit" ? "limit is the platform's limit in seconds (5 or more)" : "xfade is the crossfade in seconds (0–3)"); } settings[k] = r2(v); } if (patch.intro !== undefined) { if (patch.intro === null) delete settings.intro; else if (isObj(patch.intro)) { const errors = introErrors(patch.intro); if (errors.length) throw new Error(`the reel's intro: ${errors.join("; ")}`); settings.intro = patch.intro; } else settings.intro = patch.intro === true; } if (patch.outro !== undefined) { if (patch.outro === null) delete settings.outro; else settings.outro = /** @type {OutroSetting} */ (mergeOutro(settings.outro, patch.outro)); } if (patch.title !== undefined) { const t = typeof patch.title === "string" ? patch.title.trim().slice(0, 120) : ""; if (!t) delete settings.title; else settings.title = t; } if (patch.take !== undefined) { if (patch.take === null || patch.take === "") delete settings.take; else if (typeof patch.take !== "string" || !TAKE_ID.test(patch.take)) throw new Error("take is a take id"); else settings.take = patch.take; } return {}; }, { reel, what: `settings: ${Object.keys(isObj(patch) ? patch : {}).join(", ")}` }); } /** * The outro setting after a patch: `true`/`false` turn it on or off (its words * kept), an object merges into it (a key null drops it) and turns it on unless * it says `on: false`. Refused by name (outro.mjs outroErrors). * * @param {OutroSetting | undefined} current * @param {unknown} patch */ export function mergeOutro(current, patch) { const base = isObj(current) ? { ...current } : { on: false }; if (patch === true || patch === false) return normalizeOutro({ ...base, on: patch }); if (!isObj(patch)) throw new Error("outro is on|off or {title?, text?, image?, seconds?}"); /** @type {Record} */ const next = { ...base, on: true }; for (const [k, v] of Object.entries(patch)) { if (v === null || v === "") delete next[k]; else next[k] = v; } if (patch.on === undefined) next.on = true; return normalizeOutro(next); } /** * A reel's VERSION as its cut sees it: a fingerprint of what the cut reads * (each beat's clip and seconds and gaps, the crossfade, the intro) -- not a * verdict, a label or an anchor, which change nothing cut. Named in a cut's * record, so the reel's Play can say the cut is older than the reel. * * @param {{ beats: any[], settings?: Record }} doc */ export function reelVersion(doc) { const beats = (doc?.beats ?? []).map((b) => (isObj(b) ? [b.id ?? null, b.start ?? b.at ?? null, b.end ?? b.dur ?? null, b.gaps ?? null] : b)); const s = doc?.settings ?? {}; // The outro only when it is set: a reel without one keeps the version it had. return createHash("sha256").update(JSON.stringify({ beats, xfade: s.xfade ?? null, intro: s.intro ?? null, ...(s.outro ? { outro: s.outro } : {}) })).digest("hex").slice(0, 16); } /** Spans merged where they touch or overlap, sorted. */ function unionSpans(list) { const out = []; for (const g of [...list].filter((x) => isObj(x) && Number.isFinite(x.from) && Number.isFinite(x.to)).sort((x, y) => x.from - y.from)) { const last = out[out.length - 1]; if (last && g.from <= last.to) last.to = Math.max(last.to, g.to); else out.push({ from: g.from, to: g.to }); } return out; } /** Clip id → its place among the cut's clips. */ function cutOrder(manifest) { const order = new Map(); let n = 0; for (const e of manifest?.timeline ?? []) { if (e?.type !== "clip") continue; if (!order.has(e.id)) order.set(e.id, n); n += 1; } return order; } /** "m:ss.s" */ export function clockOf(s) { if (!Number.isFinite(s)) return "—"; const neg = s < 0; const a = Math.abs(s); const m = Math.floor(a / 60); const r = a - m * 60; return `${neg ? "−" : ""}${m}:${r < 10 ? "0" : ""}${r.toFixed(1)}`; } /** * The beats against the cut, before any encode. Pure. * * @param {Record} manifest the project's manifest * @param {{ beats: any[], settings?: Record }} doc readTrailerBeats's * @param {{ introSeconds?: number | null, reel?: string }} [opts] the brand intro's length in a built take, when known; the reel */ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT_REEL } = {}) { const settings = doc.settings ?? {}; const limit = typeof settings.limit === "number" ? settings.limit : TRAILER_LIMIT_DEFAULT; const xfade = typeof settings.xfade === "number" ? settings.xfade : TRAILER_XFADE_DEFAULT; const intro = settings.intro === true || isObj(settings.intro); // The reel's own intro is its own length; the master's is the built take's (null: not known yet). if (isObj(settings.intro)) introSeconds = Number.isFinite(settings.intro.seconds) ? Number(settings.intro.seconds) : INTRO_SECONDS; const outro = resolveOutro(settings.outro, { reelTitle: typeof settings.title === "string" ? settings.title : null, projectTitle: typeof manifest?.title === "string" ? manifest.title : null }); const tl = manifest?.timeline ?? []; const order = cutOrder(manifest); const model = sectionModel(manifest); let sum = intro && Number.isFinite(introSeconds) ? Number(introSeconds) : 0; let pieces = intro ? 1 : 0; let lastKey = -1; let inOrder = true; const rows = (doc.beats ?? []).map((raw, i) => { const problems = []; let kind = "raw"; let seconds = 0; let clip = null; if (isObj(raw) && raw.id !== undefined) { kind = "clip"; const e = tl.find((x) => x?.id === raw.id); const span = Number(raw.end) - Number(raw.start); if (!e) { problems.push(`${raw.id} is not in the cut any more`); seconds = Math.max(0, span); } else if (e.type !== "clip") { problems.push(`${raw.id} is a ${e.type ?? "non-clip"} entry: use { at, dur } for it`); seconds = Math.max(0, span); } else { const lo = e.cutStart ?? e.start; const hi = e.cutEnd ?? e.end; if (raw.start < lo - EPS) problems.push(`starts ${(lo - raw.start).toFixed(2)} s before ${raw.id}'s window (${lo}–${hi})`); if (raw.end > hi + EPS) problems.push(`ends ${(raw.end - hi).toFixed(2)} s after ${raw.id}'s window (${lo}–${hi})`); const a = Math.max(raw.start, lo); const b = Math.min(raw.end, hi); // What plays: the clip's gaps (its render left them out) and the beat's own, as one list. seconds = b > a ? gappedLength(a, b, unionSpans([...gapsOf(e), ...(Array.isArray(raw.gaps) ? raw.gaps : [])])) : 0; const k = order.get(raw.id); if (k < lastKey) inOrder = false; lastKey = Math.max(lastKey, k); const sec = model.sections[model.sectionOf.get(raw.id) ?? 0]; clip = { start: lo, end: hi, at: k, section: model.sections.length > 1 && sec ? sectionWords(sec) : null, quote: typeof e.quote === "string" ? e.quote : null }; } if (!(span > 0)) problems.push(`end ${raw.end} is not after start ${raw.start}`); } else if (isObj(raw)) { seconds = Math.max(0, Number(raw.dur) || 0); } pieces += 1; sum += seconds; const running = sum - xfade * Math.max(0, pieces - 1); return { n: i + 1, kind, ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end, ...(Array.isArray(raw.gaps) && raw.gaps.length ? { gaps: raw.gaps } : {}) } : { at: raw?.at, dur: raw?.dur }), label: typeof raw?.label === "string" ? raw.label : null, verdict: BEAT_VERDICTS.includes(raw?.verdict) ? raw.verdict : null, seconds: r2(seconds), running: r2(running), over: running > limit, clip, problems, }; }); const total = r2(sum - xfade * Math.max(0, pieces - 1) + (outro ? outroAdds(outro.seconds) : 0)); return { reel: reel ?? DEFAULT_REEL, file: reelFileOf(reel), title: typeof settings.title === "string" ? settings.title : null, take: typeof settings.take === "string" ? settings.take : null, confirmed: rows.filter((r) => r.verdict === "confirmed").length, limit, xfade, intro, introSeconds: intro ? (Number.isFinite(introSeconds) ? Number(introSeconds) : null) : null, introOwn: isObj(settings.intro) ? settings.intro : null, // The card the reel ends on (its words with the defaults), and the setting as stored (off keeps its words). outro, outroSetting: settings.outro ?? null, total, remaining: r2(limit - total), over: total >= limit, inOrder, outside: rows.filter((r) => r.problems.length).length, rows, }; } /** * The brand intro's length, from the newest built take whose schedule has * one (`takes//out/sourced/schedule.json`, a segment of type "intro"), * else null. * * @param {string} dir * @returns {Promise} */ export async function introSecondsOf(dir) { const takes = path.join(dir, "takes"); const names = await readdir(takes).catch(() => []); let best = null; for (const n of names) { const f = path.join(takes, n, "out", "sourced", "schedule.json"); const st = await stat(f).catch(() => null); if (!st || (best && best.mtime >= st.mtimeMs)) continue; try { const s = JSON.parse(await readFile(f, "utf8")); const seg = (s.segments ?? []).find((x) => x?.type === "intro" || x?.id === "brand-intro"); if (!seg) continue; const len = Number.isFinite(seg.duration) ? seg.duration : Number.isFinite(seg.end) ? seg.end - seg.start : null; if (Number.isFinite(len)) best = { mtime: st.mtimeMs, len }; } catch { // a schedule that does not read says nothing about the intro } } return best ? r2(best.len) : null; } /** * The walk's ★ favourites not yet beats: the trailer's candidates -- * lane/ui-cut-integrity's trailerCandidates (a starred clip that will play, * as a beat over what it plays), less the clips already beats. * * @param {Record} manifest * @param {any[]} beats */ export function trailerCandidatesOf(manifest, beats = []) { const used = new Set(beats.filter((b) => isObj(b) && b.id !== undefined).map((b) => b.id)); return trailerCandidates(manifest) .filter((c) => !used.has(c.id)) .map((c) => ({ id: c.id, start: c.start, end: c.end, quote: c.quote ?? null, walkNote: c.walkNote ?? null })); }