// A TRAILER CUT FROM THE MASTER (`umtool trailer`, 2026-10-26). // // A trailer used to be a take of its own: a short cut of a dozen clips, with // its own short rail, so the deck said the video was two minutes long. This // cuts the trailer out of a FINISHED master render instead -- spans of the // master's own frames -- so the rail, the dates, the pips and the running // tallies on screen are the whole video's, and the viewer sees how much more // the full version holds. Nothing is rendered again: it is one ffmpeg pass // over a finished file, in minutes. // // A beat names what plays, in one of two ways: // // { "id": "", "start": , "end": } // source seconds of that clip, as the manifest writes them. Mapped to // master time with the take's own build records: the segment's place // in the cut (`out/sourced/schedule.json`, `segments[{id,start,duration}]`) // and the source second its file really starts at (`segments/.cut.json`, // `start`: snapped to a silence, room included). A segment's frame at // local second τ plays at master second `segment.start + τ`, and its // local second τ is source second `cut.start + τ` -- a hold only // lengthens the segment's END, so it moves nothing before it. // { "at": , "dur": } // raw master time, taken as written. // // THE MASTER'S OWN CROSSFADES. Each join of the master is a dissolve of // `transition` seconds: segment i's first D seconds are blended with the // segment before it (they start at schedule.start, which is already D before // the previous segment's end), its last D with the one after. A clip beat that // reaches into one would put a blend of two clips on screen, so its edge is // pulled in -- but only as far as the TRAILER's own crossfade at that edge // does not hide it: with the trailer dissolving over x seconds, a beat may // start D − x into its segment and the master's blend is under the trailer's. // Pulled-in edges are said, never silent (`notes`). // // EDGES INTO PAUSES (2026-11-02). The trailer's own crossfade overlaps a // beat's last `xfade` seconds with the next beat's first: an edge a tenth of // a second after a word starts fades that word out ("man.", "door is."), and // one before a sentence's last word cuts it ("every [ __ ]" without "type."). // So once the master's crossfades are kept out (above), each clip beat's END // moves forward into the next pause -- through the sentence when one ends // within SNAP_MAX_SHIFT -- far enough that the fade is in the quiet, and its // START back into the pause before it (pauses.mjs snapEdge). The pauses are // the master's own silences over the segment (cut-points.mjs detectSilence, // the build's measure) and the gaps between the recording's timed words; the // words (clip-words.mjs: a words file, a whisper transcript, else the // captions' word starts) say which sentence an edge is in and name the word // it now follows. Never past the segment's own clip (the master's // crossfades, the cut record's end, a gap's join), never more than // SNAP_MAX_SHIFT; each move is a note, and `--no-snap` leaves the edges as // written. A raw beat, the intro and the finale are taken as written. // // The spans are cut frame-accurately (decoded, never stream-copied) in ONE // ffmpeg pass: each run of the master is a `movie` source inside the // filtergraph, decoded only when the chain reaches it (separate `-i` inputs // decode ahead and the waiting frames took 5.6 GB), trimmed by the master's // own timestamps half a frame either side of its frame boundaries (the // picture) and at its first frame (the sound, sample-exact). They are joined // with the master's own encode settings (build-video's encodeArgs over the // take's `render`): crossfaded (xfade + acrossfade, the sound pinned to the // picture's length as build-video's join pins it), or hard-cut through // `concat` when the crossfade is 0. // // The run takes the machine's heavy slot (heavy-gate.mjs) with a declared // memory estimate: the CLI (lib/report/trailerCli.mjs) loads the gate, never // this module, so the umtool app can import it without the gate in its bundle. import { execFile } from "node:child_process"; import { rmSync } from "node:fs"; import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { encodeArgs } from "./build-video.mjs"; import { clipWords } from "./clip-words.mjs"; import { DEFAULT_CHANNELS_DIR } from "./cues.mjs"; import { detectSilence } from "./cut-points.mjs"; import { beatGapsOf, gapFilterParts, offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; import { OUTRO_FADE, outroAdds, outroFilterParts, renderOutroCard } from "./outro.mjs"; import { outroBrand, reelIntroOf, renderReelIntro } from "./reel-intro.mjs"; import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; /** The trailer's crossfade, in seconds, when none is given. */ export const TRAILER_XFADE_DEFAULT = 0.3; /** * The memory the one ffmpeg pass is declared to need in the heavy slot (MB): * measured 3.4 GB peak on the Huck trailer (14 runs of a 1080p master, x264 * `slow`), with room above it. */ export const TRAILER_ESTIMATE_MB = 4000; /** Each run's decoder threads: every source is open at once, so each is kept small. */ export const TRAILER_DECODE_THREADS = 2; /** How far before a run its source seeks (to the keyframe at or before it): the trim cuts on the frame. */ const PRE_ROLL = 1; /** A source second this close to a cut's edge is on it (the records keep three decimals). */ const EPS = 0.02; /** A refusal: said by name, exit 1, nothing written. */ export class TrailerError extends Error {} const r3 = (n) => Number(n.toFixed(3)); const fmt = (n) => n.toFixed(2); /** Seconds as m:ss.s, for the printed plan. */ export function clock(s) { const m = Math.floor(s / 60); const rest = s - m * 60; return `${m}:${rest < 10 ? "0" : ""}${rest.toFixed(1)}`; } /** * The beats, checked: an array, or `{ beats: [...] }`. A clip beat is * `{ id, start, end }`, a raw one `{ at, dur }`; anything else is refused by * its place in the list. An optional `label` is carried through to the record. */ export function parseBeats(value) { const list = Array.isArray(value) ? value : Array.isArray(value?.beats) ? value.beats : null; if (!list) throw new TrailerError("beats: a JSON array of beats, or { \"beats\": [...] }"); if (!list.length) throw new TrailerError("beats: the list is empty"); return list.map((b, i) => { const where = `beat ${i + 1}`; if (!b || typeof b !== "object" || Array.isArray(b)) throw new TrailerError(`${where}: not an object`); const label = typeof b.label === "string" ? b.label : undefined; const num = (k) => typeof b[k] === "number" && Number.isFinite(b[k]); if (b.id !== undefined) { if (typeof b.id !== "string" || !b.id) throw new TrailerError(`${where}: id is a clip id (a string)`); if (!num("start") || !num("end")) throw new TrailerError(`${where} (${b.id}): start and end are source seconds (numbers)`); if (b.end <= b.start) throw new TrailerError(`${where} (${b.id}): end ${b.end} is not after start ${b.start}`); const gaps = beatGaps(b, `${where} (${b.id})`); return { kind: "clip", id: b.id, start: b.start, end: b.end, ...(gaps.length ? { gaps } : {}), ...(label ? { label } : {}) }; } if (b.at !== undefined || b.dur !== undefined) { if (!num("at") || !num("dur")) throw new TrailerError(`${where}: at and dur are master seconds (numbers)`); if (b.at < 0 || b.dur <= 0) throw new TrailerError(`${where}: at ≥ 0 and dur > 0`); return { kind: "raw", at: b.at, dur: b.dur, ...(label ? { label } : {}) }; } throw new TrailerError(`${where}: { "id", "start", "end" } (a clip's source seconds) or { "at", "dur" } (master seconds)`); }); } /** * A clip beat's GAPS (gaps.mjs beatGapsOf: a clip's gap rule, on a beat), * refused as a TrailerError. * * @param {{ start: number, end: number, gaps?: unknown }} b * @param {string} where */ export function beatGaps(b, where = "beat") { try { return beatGapsOf(b, where); } catch (e) { throw new TrailerError(e instanceof Error ? e.message : String(e)); } } /** * Each segment's span in the master, by id: `{ id, type, index, start, end }`. * `end` is the schedule's own (a deck schedule writes it), else start + * duration, else where the next segment's crossfade ends (a rail schedule * writes starts only), else the cut's total. */ export function scheduleSpans(schedule) { const segs = schedule?.segments; if (!Array.isArray(segs) || !segs.length) throw new TrailerError("schedule.json lists no segments"); const D = Number(schedule.transition) || 0; const total = Number(schedule.total); const spans = new Map(); segs.forEach((s, i) => { const next = segs[i + 1]; const end = Number.isFinite(s.end) ? s.end : Number.isFinite(s.duration) ? s.start + s.duration : next ? next.start + D : total; spans.set(s.id, { id: s.id, type: s.type ?? null, index: i, start: s.start, end }); }); return { spans, count: segs.length, D, total, fps: Number(schedule.fps) || 30 }; } /** The brand intro's span: the segment of type "intro" (the build names it brand-intro). */ export function introSpan(spans) { for (const s of spans.values()) if (s.type === "intro" || s.id === "brand-intro") return s; return null; } /** * The trailer's plan, pure: every piece's master span, frame-aligned, with * where it lands in the trailer and the total. * * @param {object} a * @param {object} a.schedule the take's `out/sourced/schedule.json` * @param {Map} a.records each clip segment's cut record, by id * @param {object[]} a.beats parseBeats's * @param {boolean} [a.intro] prepend the master's brand intro * @param {number|null} [a.finale] append the master's last S seconds * @param {number} [a.xfade] the trailer's crossfade (0: hard cuts) * @param {Map, words?: Array<{ start: number, end?: number, text: string }> | null }> | null} [a.pauses] * each clip segment's pauses and words in MASTER seconds (trailerPauses); none: no edge moves to a pause * @param {boolean} [a.snap] move clip beats' edges into pauses (false: `--no-snap`) */ export function planTrailer({ schedule, records, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT, pauses = null, snap = true }) { const { spans, count, D, total, fps } = scheduleSpans(schedule); if (!Number.isFinite(total) || total <= 0) throw new TrailerError("schedule.json has no total"); if (!Number.isFinite(xfade) || xfade < 0) throw new TrailerError(`--xfade ${xfade}: seconds ≥ 0`); const frame = (t) => Math.round(t * fps) / fps; const x = frame(xfade); const notes = []; // The pieces as asked, in trailer order, before any edge is pulled in. const want = []; if (intro) { const s = introSpan(spans); if (!s) throw new TrailerError("--intro: this take's cut has no brand intro (no segment of type \"intro\" in schedule.json)"); want.push({ kind: "intro", id: s.id, seg: s, a: s.start, b: s.end }); } beats.forEach((beat, n) => { if (beat.kind === "raw") { if (beat.at + beat.dur > total + EPS) { throw new TrailerError(`beat ${n + 1}: ${fmt(beat.at)}+${fmt(beat.dur)} s runs past the master's end (${fmt(total)} s)`); } want.push({ kind: "raw", beat, a: beat.at, b: Math.min(total, beat.at + beat.dur) }); return; } const seg = spans.get(beat.id); if (!seg) throw new TrailerError(`beat ${n + 1}: no clip "${beat.id}" in this take's cut (schedule.json)`); const rec = records.get(beat.id); if (!rec || !Number.isFinite(rec.start) || !Number.isFinite(rec.end)) { throw new TrailerError(`beat ${n + 1}: "${beat.id}" has no cut record with source seconds (segments/${beat.id}.cut.json) — a card, or built before records; use { "at", "dur" }`); } if (beat.start < rec.start - EPS || beat.end > rec.end + EPS) { throw new TrailerError( `beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} is outside the source seconds its segment was cut from, ${rec.start}–${rec.end}`, ); } const s = Math.max(beat.start, rec.start); const e = Math.min(beat.end, rec.end); // A clip with gaps (gaps.mjs; the record's, as its segment left them out): // a beat across one plays the master's jump cut, and is that much shorter; // an edge inside one lands on its join. const gaps = recordGaps(rec); const a = seg.start + offsetIn(s, rec.start, gaps); const b = seg.start + offsetIn(e, rec.start, gaps); if (gaps.length && b - a < 0.2) { throw new TrailerError(`beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} lies inside the clip's gaps — nothing of it plays in the master`); } if (gaps.some((g) => g.from < e && g.to > s)) { notes.push(`beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} spans a gap — it plays the master's jump cut (${fmt(b - a)} s)`); } // The beat's OWN gaps (beatGaps), as spans of the master to leave out. The // master runs on across a gap its render already cut, so a beat gap over // one is the master seconds either side of it; one wholly inside it has // nothing left to cut, and is refused. const cuts = (beat.gaps ?? []).map((g) => { const ca = seg.start + offsetIn(Math.max(g.from, s), rec.start, gaps); const cb = seg.start + offsetIn(Math.min(g.to, e), rec.start, gaps); if (cb - ca < 1 / fps) { throw new TrailerError(`beat ${n + 1}: ${beat.id}'s gap ${g.from}–${g.to} lies inside a gap the master already cut out of the clip — nothing of it plays there to cut`); } return { from: ca, to: cb }; }); want.push({ kind: "clip", id: beat.id, beat, n: n + 1, rec, seg, gaps, cuts, a, b }); }); if (finale != null) { if (!Number.isFinite(finale) || finale <= 0) throw new TrailerError(`--finale ${finale}: seconds > 0`); if (finale > total) throw new TrailerError(`--finale ${finale}: the master is ${fmt(total)} s`); want.push({ kind: "finale", a: total - finale, b: total }); } if (!want.length) throw new TrailerError("nothing to cut: no beats, no --intro, no --finale"); // A piece that starts inside the one before it, or where it ends (the brand // intro and the clip after it; a closing beat and the finale), is the same // run of the master: it is joined SEAMLESSLY -- the earlier piece ends on // the frame the later one starts on, no crossfade of the trailer's, and the // master's own dissolve between them plays as it does in the master. The // frames are never shown twice. const n = want.length; const step = 1 / fps; const seam = want.map((w, i) => i > 0 && w.a >= want[i - 1].a - 1e-6 && w.a <= want[i - 1].b + step + 1e-6); for (let i = 1; i < n; i += 1) { if (!seam[i]) continue; if (want[i].b < want[i - 1].b) want[i].b = want[i - 1].b; want[i - 1].b = want[i].a; } // Edges pulled out of the master's own crossfades (see the header), then // put on frames: a start rounded to its frame, the length a whole count. /** The piece before's end in the master, once its edges have moved. */ let prevEnd = null; const pieces = want.map((w, i) => { const joinIn = i > 0 && !seam[i]; const joinOut = i < n - 1 && !seam[i + 1]; const xIn = joinIn ? x : 0; const xOut = joinOut ? x : 0; let { a, b } = w; const moved = {}; if (w.seg) { const lo = Math.max(w.seg.start, w.seg.start + (w.seg.index > 0 ? D : 0) - xIn); const hi = Math.min(w.seg.end, w.seg.end - (w.seg.index < count - 1 ? D : 0) + xOut); if (!seam[i] && a < lo - 1e-6) { moved.start = { from: r3(a), to: r3(lo) }; a = lo; } if (!seam[i + 1] && b > hi + 1e-6) { moved.end = { from: r3(b), to: r3(hi) }; b = hi; } // Into the pauses (the header's "edges into pauses"): bounded by the // master's crossfades (lo, hi), the cut record's own end (a hold after it // is a frozen frame) and the gap joins either side of the edge. const P = snap && w.kind === "clip" ? pauses?.get(w.id) : null; if (P) { const toMaster = (src) => w.seg.start + offsetIn(src, w.rec.start, w.gaps); const joins = w.gaps.map((g) => toMaster(g.from)); const recEnd = toMaster(w.rec.end); const label = (t) => fmt(r3(sourceAtOffset(t - w.seg.start, w.rec.start, w.gaps))); const say = (edge, r, was) => { const where = r.word ? `pause ${edge === "end" ? "after" : "before"} "${r.word}"` : `pause at ${label(r.pause.from)}–${label(r.pause.to)}`; const extra = [r.sentence ? "the sentence's end" : null, r.bounded ? "held at the segment's edge" : null].filter(Boolean).join(", "); notes.push(`beat ${w.n} ${w.id}: ${edge} ${label(was)} → ${label(r.at)} (${where}${extra ? `, ${extra}` : ""})`); }; const kept = (edge, r, was, bound) => { // At the segment's own edge already (the master's crossfade, a // join): nothing to say beyond what the crossfade note says. if (r.reason === "bound" && Math.abs(was - bound) < 1e-3) return; const why = r.reason === "far" ? `the pause is more than ${fmt(SNAP_MAX_SHIFT)} s away` : r.reason === "bound" ? "the pause is past the segment's own clip" : `no pause ${edge === "end" ? "after" : "before"} it`; notes.push(`beat ${w.n} ${w.id}: ${edge} ${label(was)} kept — ${why}`); }; if (!seam[i + 1]) { const room = xOut > 0 ? xOut : SNAP_HARD_ROOM; // Never into the next piece when it plays on from here in the master. const next = want[i + 1]; const nextA = next && next.a >= w.b - 1e-6 ? next.a : Infinity; const hiSnap = Math.min(hi, recEnd, nextA, ...joins.filter((j) => j >= b - 1e-3)); const r = snapEdge(b, "end", { pauses: P.pauses, words: P.words, room, maxShift: SNAP_MAX_SHIFT, hi: hiSnap }); if (r.moved) { // On the frame at or before it: the frame rounding below never carries it past the word after. const at = Math.max(b, Math.floor(r.at * fps + 1e-6) / fps); moved.snapped = { ...(moved.snapped ?? {}), end: { from: r3(b), to: r3(at), ...(r.word ? { after: r.word } : {}) } }; say("end", { ...r, at }, b); b = at; } else if (r.reason !== "fits") kept("end", r, b, hiSnap); } if (!seam[i]) { const room = xIn > 0 ? xIn : SNAP_HARD_ROOM; // Never back into the piece before when it played up to here in the master. const prevB = i > 0 && prevEnd !== null && prevEnd <= w.a + 1e-6 ? prevEnd : -Infinity; const loSnap = Math.max(lo, prevB, ...joins.filter((j) => j <= a + 1e-3)); const r = snapEdge(a, "start", { pauses: P.pauses, words: P.words, room, maxShift: SNAP_MAX_SHIFT, lo: loSnap }); if (r.moved) { // On the frame at or after it, for the same reason. const at = Math.min(a, Math.ceil(r.at * fps - 1e-6) / fps); moved.snapped = { ...(moved.snapped ?? {}), start: { from: r3(a), to: r3(at), ...(r.word ? { before: r.word } : {}) } }; say("start", { ...r, at }, a); a = at; } else if (r.reason !== "fits") kept("start", r, a, loSnap); } } } prevEnd = b; const fa = Math.round(a * fps); const frames = Math.round(b * fps) - fa; const name = w.kind === "clip" ? w.id : w.kind === "intro" ? "intro" : w.kind === "finale" ? "finale" : `beat ${i + 1}`; // The beat's gaps on frames, inside what is left of it: each cut keeps at // least a frame either side, so the beat starts and ends on its own material. const cutFrames = []; for (const c of w.cuts ?? []) { const cs = Math.max(fa + 1, Math.round(c.from * fps)); const ce = Math.min(fa + frames - 1, Math.round(c.to * fps)); if (ce - cs < 1) { notes.push(`${name}: its gap at master ${fmt(c.from)}–${fmt(c.to)} falls outside what is left of the beat — not cut`); continue; } cutFrames.push({ start: cs, count: ce - cs }); } const kept = frames - cutFrames.reduce((n, c) => n + c.count, 0); if (cutFrames.length) { const first = cutFrames[0].start - fa; const lastC = cutFrames[cutFrames.length - 1]; const tail = fa + frames - (lastC.start + lastC.count); if (first / fps <= xIn || tail / fps <= xOut) { throw new TrailerError(`${name}: a gap leaves ${fmt(Math.min(first, tail) / fps)} s at the beat's ${first / fps <= xIn ? "start" : "end"} — too short for the ${fmt(x)} s crossfade`); } } if (frames < 1 || kept / fps <= xIn + xOut) { throw new TrailerError( `${name}: ${fmt(Math.max(0, frames / fps))} s left once it is out of the master's crossfades — too short for ` + `${xIn || xOut ? `a ${fmt(x)} s crossfade either side` : "a cut"}`, ); } const start = fa / fps; const duration = frames / fps; const piece = { kind: w.kind, ...(w.id ? { id: w.id } : {}), ...(w.beat?.label ? { label: w.beat.label } : {}), master: { start: r3(start), end: r3(start + duration), duration: r3(duration) }, frames: { start: fa, count: frames }, // A gapped beat: the master spans it leaves out (each a hard cut, the sound // faded GAP_FADE either side, as a clip's gap renders) and the seconds it plays. ...(cutFrames.length ? { cuts: cutFrames.map((c) => ({ from: r3(c.start / fps), to: r3((c.start + c.count) / fps), frames: c })), seconds: r3(kept / fps), gaps: w.beat.gaps, } : {}), ...(seam[i] ? { seamless: true } : {}), // The source seconds it plays, its gaps counted: a beat after a gap is // that much later in its source than in its segment. ...(w.kind === "clip" ? { source: { start: r3(sourceAtOffset(start - w.seg.start, w.rec.start, w.gaps)), end: r3(sourceAtOffset(start + duration - w.seg.start, w.rec.start, w.gaps)), asked: { start: w.beat.start, end: w.beat.end }, }, segment: { start: r3(w.seg.start), end: r3(w.seg.end), cut: { start: w.rec.start, end: w.rec.end } }, } : {}), ...(w.kind === "raw" ? { asked: { at: w.beat.at, dur: w.beat.dur } } : {}), ...(moved.start || moved.end ? { moved: { ...(moved.start ? { start: moved.start } : {}), ...(moved.end ? { end: moved.end } : {}) } } : {}), ...(moved.snapped ? { snapped: moved.snapped } : {}), }; if (moved.start) { notes.push(`${name}: starts at master ${fmt(moved.start.to)}, not ${fmt(moved.start.from)} — the master's crossfade into it runs until ${fmt(w.seg.start + D)}`); } if (moved.end) { notes.push(`${name}: ends at master ${fmt(moved.end.to)}, not ${fmt(moved.end.from)} — the master's crossfade out of it starts at ${fmt(w.seg.end - D)}`); } if (seam[i]) { notes.push(`${pieceName(want[i - 1], i - 1)} runs straight into ${name} (master ${fmt(start)}): one run of the master, no crossfade`); } return piece; }); // Where each lands in the trailer: each crossfade overlaps its two pieces. let acc = 0; pieces.forEach((p, i) => { const over = i > 0 && !p.seamless ? x : 0; p.at = r3(acc - over); acc = acc + pieceFrames(p) / fps - over; }); // The same master seconds twice: the operator's call, but said. for (let i = 0; i < pieces.length; i += 1) { for (let j = i + 1; j < pieces.length; j += 1) { const lo = Math.max(pieces[i].master.start, pieces[j].master.start); const hi = Math.min(pieces[i].master.end, pieces[j].master.end); if (hi - lo > 1 / fps) { notes.push(`${pieceName(pieces[i], i)} and ${pieceName(pieces[j], j)} share master ${fmt(lo)}–${fmt(hi)} (${fmt(hi - lo)} s): the trailer plays it twice`); } } } return { fps, transition: D, xfade: x, masterSeconds: total, pieces, total: r3(acc), notes }; } /** * A plan with the reel's own pieces added, pure: `intro` (`{ file, seconds, * label? }`, an intro rendered for the reel, as the cut's first piece -- * crossfaded into the first beat like any two pieces) and `outro` (`{ seconds, * fade? }`, the card after the last piece, faded in over `fade`). The pieces' * `at` and the total are placed again. * * @param {ReturnType} plan * @param {{ intro?: { file: string | null, seconds: number, label?: string } | null, outro?: { seconds: number, fade?: number, [k: string]: any } | null }} extras */ export function withReelExtras(plan, { intro = null, outro = null } = {}) { const { fps, xfade: x } = plan; const pieces = [...plan.pieces]; if (intro) { const count = Math.round(intro.seconds * fps); pieces.unshift({ kind: "intro", standalone: true, ...(intro.file ? { file: intro.file } : {}), ...(intro.label ? { label: intro.label } : {}), master: null, frames: { start: 0, count }, }); if (pieces[1]?.seamless) { const { seamless: _s, ...rest } = pieces[1]; pieces[1] = rest; } } let acc = 0; pieces.forEach((p, i) => { const over = i > 0 && !p.seamless ? x : 0; p.at = r3(acc - over); acc = acc + pieceFrames(p) / fps - over; }); const notes = [...plan.notes]; let total = acc; let out = null; if (outro) { const fade = outro.fade ?? OUTRO_FADE; const frames = Math.round(outro.seconds * fps); out = { ...outro, fade, at: r3(Math.max(0, acc - fade)), seconds: r3(frames / fps), frames }; total = acc + outroAdds(frames / fps); } return { ...plan, pieces, total: r3(total), notes, ...(out ? { outro: out } : {}) }; } function pieceName(p, i) { const at = p.master?.start ?? p.a; return p.kind === "clip" ? p.id : p.kind === "raw" ? `beat at ${fmt(at)}` : p.kind ?? `piece ${i + 1}`; } /** The frames a piece plays: its span, less its gaps' cuts. */ export const pieceFrames = (p) => p.frames.count - (p.cuts ?? []).reduce((n, c) => n + c.frames.count, 0); /** * The runs of the master a plan reads: its pieces, a seamless one folded into * the run before it (its frames follow on). `{ start, count }` in frames; a run * holding a gapped beat also carries its `cuts` (`{ start, count }`, master * frames) and the frames it `kept`. */ export function trailerRuns(plan) { const runs = []; for (const p of plan.pieces) { const last = runs[runs.length - 1]; const run = p.seamless && last && !last.file ? last : null; if (run) run.count = p.frames.start + p.frames.count - run.start; else runs.push({ start: p.frames.start, count: p.frames.count, ...(p.file ? { file: p.file } : {}) }); const r = runs[runs.length - 1]; if (p.cuts?.length) r.cuts = [...(r.cuts ?? []), ...p.cuts.map((c) => ({ ...c.frames }))]; if (r.cuts) r.kept = r.count - r.cuts.reduce((n, c) => n + c.count, 0); } return runs; } /** * A file name as a `movie` filter's option inside a filtergraph: escaped for * the option (`\ ' :`), then for the graph (`\ ' [ ] , ;`), as ffmpeg's * filtergraph docs say. */ export function filterPath(file) { const opt = String(file).replace(/[\\':]/g, (c) => `\\${c}`); return opt.replace(/[\\'[\],;]/g, (c) => `\\${c}`); } /** * The ffmpeg argv for a plan: the whole cut in one filtergraph, one `movie` * source of the master per run, the master's encode settings. * * WHY `movie` AND NOT ONE `-i` PER RUN. ffmpeg reads its `-i` inputs on their * own threads, as fast as they decode, and the crossfade chain does not need * the eleventh run for a minute and a half: measured on the Huck trailer * (14 runs), the frames waiting in the graph took 5.6 GB. A `movie` source * inside the graph is decoded only when the filter after it asks for a frame, * so a run is read when the chain reaches it and memory stays flat. * * FRAME-ACCURATE BY TIMESTAMP. `movie` seeks to the keyframe at or before * PRE_ROLL seconds ahead of the run and keeps the master's own timestamps, * so the picture is trimmed half a frame either side of its frame boundaries * (exactly the run's frames, whatever the float rounding) and the sound at * the run's first frame, sample-exact; then both are pinned to the run's * length, as build-video's join pins each segment's. */ export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_DECODE_THREADS, outro = null }) { const { fps, xfade: x } = plan; const runs = trailerRuns(plan); const half = 0.5 / fps; const src = filterPath(master); const parts = []; // A gapped run's concat puts its picture on the default timebase (1/1000000), and // xfade wants both inputs on one: with any gapped run, every run's picture is put there. // So with a run of another file (a reel's own intro): its timebase is not the master's. const tb = runs.some((r) => r.cuts?.length || r.file) ? ",settb=AVTB" : ""; runs.forEach((r, i) => { const a = r.start / fps; const n = r.count; const d = (n / fps).toFixed(6); const seek = Math.max(0, a - PRE_ROLL); // A run of its own file (the reel's intro, rendered for it) is that file's frames from 0, at the master's format. const fmtv = r.file ? `,format=yuv420p,fps=${fps}` : ""; parts.push(`movie=filename=${r.file ? filterPath(r.file) : src}:seek_point=${seek.toFixed(6)}:streams=dv+da:dec_threads=${threads}[m${i}v][m${i}a]`); const cut = r.cuts?.length; parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS${fmtv}${cut ? "" : tb}[${cut ? `r${i}v` : `v${i}`}]`); parts.push( `[m${i}a]atrim=start=${a.toFixed(6)}:end=${(a + n / fps).toFixed(6)},asetpts=PTS-STARTPTS,` + `apad=whole_dur=${d},atrim=end=${d}[${cut ? `r${i}a` : `a${i}`}]`, ); // A gapped beat: its cuts left out of the run as a clip's gaps are of its // segment (gaps.mjs gapFilterParts: hard cuts, the sound faded either side). if (cut) { const gaps = r.cuts.map((c) => ({ from: (c.start - r.start) / fps, to: (c.start + c.count - r.start) / fps })); parts.push(...gapFilterParts({ gaps, seconds: n / fps, vIn: `[r${i}v]`, aIn: `[r${i}a]`, vOut: `[g${i}v]`, aOut: `[a${i}]`, tag: `r${i}` }).parts); parts.push(`[g${i}v]settb=AVTB[v${i}]`); } }); const keptOf = (r) => (r.kept ?? r.count) / fps; let vlab = "[v0]"; let alab = "[a0]"; if (runs.length > 1 && x > 0) { let acc = keptOf(runs[0]); for (let i = 1; i < runs.length; i += 1) { const off = acc - x; parts.push(`${vlab}[v${i}]xfade=transition=fade:duration=${x.toFixed(6)}:offset=${off.toFixed(6)}[xv${i}]`); parts.push(`${alab}[a${i}]acrossfade=d=${x.toFixed(6)}:c1=tri:c2=tri[xa${i}]`); vlab = `[xv${i}]`; alab = `[xa${i}]`; acc = acc + keptOf(runs[i]) - x; } } else if (runs.length > 1) { parts.push(`${runs.map((_, i) => `[v${i}][a${i}]`).join("")}concat=n=${runs.length}:v=1:a=1[cv][ca]`); vlab = "[cv]"; alab = "[ca]"; } // The reel's outro card (outro.mjs): faded in over the cut's last OUTRO_FADE seconds, held to the end. if (outro) { const cutSeconds = runs.reduce((n, r) => n + keptOf(r), 0) - (x > 0 ? x * Math.max(0, runs.length - 1) : 0); const o = outroFilterParts({ png: outro.png, seconds: outro.seconds, fade: outro.fade, fps, cutSeconds, vIn: vlab, aIn: alab, audioRate: render?.audioRate ?? 48000, audioChannels: render?.audioChannels ?? 2, escape: filterPath, }); parts.push(...o.parts); vlab = o.vOut; alab = o.aOut; } return [ "-nostdin", "-v", "error", "-y", "-filter_complex", parts.join(";"), "-map", vlab, "-map", alab, "-map_metadata", "-1", ...encodeArgs(render), outPath, ]; } /** The record beside a trailer: `.trailer.json` for `.trailer.mp4` or `.mp4`. */ export function trailerRecordPath(outPath) { const base = outPath.replace(/\.mp4$/i, "").replace(/\.trailer$/, ""); return `${base}.trailer.json`; } /** * Where the trailer goes: `takes//out/.trailer.mp4`; `--out NAME` * (a bare name) in the same directory, `.mp4` added when missing; `--out` a * path (absolute, or with a slash) exactly there. */ export function trailerOutPath(takeDir, slug, out = null) { const outDir = path.join(takeDir, "out"); if (!out) return path.join(outDir, `${slug}.trailer.mp4`); const file = /\.mp4$/i.test(out) ? out : `${out}.mp4`; if (path.isAbsolute(file) || file.includes("/")) return path.resolve(file); return path.join(outDir, file); } /** * A take's finished build, read: its manifest (slug, render), the master, * the schedule and every segment's cut record. Refused by name when the take * has no build. */ export async function loadTakeBuild(takeDir) { const manifestFile = path.join(takeDir, "video.manifest.json"); const manifest = await readFile(manifestFile, "utf8").then(JSON.parse, () => null); if (!manifest) throw new TrailerError(`${takeDir}: no video.manifest.json — not a take`); const slug = manifest.slug; if (!slug) throw new TrailerError(`${manifestFile}: no slug`); if (!manifest.render?.fps) throw new TrailerError(`${manifestFile}: no render settings`); const master = path.join(takeDir, "out", `${slug}.mp4`); const work = path.join(takeDir, "out", "sourced"); const schedule = await readFile(path.join(work, "schedule.json"), "utf8").then(JSON.parse, () => null); if (!schedule) throw new TrailerError(`${path.basename(takeDir)} has no build: no out/sourced/schedule.json (render the take with the deck first)`); const segDir = path.join(work, "segments"); const records = new Map(); const names = await readdir(segDir).catch(() => []); for (const name of names) { if (!name.endsWith(".cut.json")) continue; const rec = await readFile(path.join(segDir, name), "utf8").then(JSON.parse, () => null); if (rec) records.set(name.slice(0, -".cut.json".length), rec); } return { manifest, slug, render: manifest.render, master, schedule, records }; } /** * Each clip beat's segment's pauses and words, in MASTER seconds, for * planTrailer: the master's silences over the segment (`silences`, the * build's detectSilence with the take's render settings) and the recording's * words over the cut (`words`, clip-words.mjs), mapped onto the master by the * cut record -- a word in one of the clip's gaps is not in the master. Once * per segment, however many beats it plays in. A segment whose measure fails * has no pauses: its edges stay. * * @param {object} a * @param {object} a.build loadTakeBuild's * @param {object[]} a.beats parseBeats's * @param {(file: string, render: object, scan: { from: number, to: number }) => Promise>} [a.silences] * @param {(entry: object, provenance: object, from: number, to: number) => Promise<{ words: Array<{ start: number, end?: number, text: string }>, timed: boolean } | null>} [a.words] */ export async function trailerPauses({ build, beats, silences = (file, render, scan) => detectSilence(file, render, scan), words = (entry, provenance, from, to) => clipWords(entry, provenance, from, to, { channelsDir: DEFAULT_CHANNELS_DIR }), }) { const { spans } = scheduleSpans(build.schedule); const entries = new Map((build.manifest?.timeline ?? []).filter((e) => e?.id).map((e) => [e.id, e])); const out = new Map(); for (const beat of beats) { if (beat.kind !== "clip" || out.has(beat.id)) continue; const seg = spans.get(beat.id); const rec = build.records.get(beat.id); if (!seg || !rec || !Number.isFinite(rec.start) || !Number.isFinite(rec.end)) continue; const gaps = recordGaps(rec); const sil = await silences(build.master, build.render, { from: seg.start, to: seg.end }).catch(() => []); const entry = entries.get(beat.id); const got = entry ? await words(entry, build.manifest?.provenance ?? {}, rec.start - 1, rec.end + 1).catch(() => null) : null; const inGap = (t) => gaps.some((g) => t > g.from && t < g.to); const toMaster = (t) => seg.start + offsetIn(t, rec.start, gaps); const ws = (got?.words ?? []) .filter((w) => !inGap(w.start)) .map((w) => ({ start: toMaster(w.start), ...(got.timed && Number.isFinite(w.end) ? { end: toMaster(w.end) } : {}), text: w.text })); out.set(beat.id, { pauses: pauseSpans({ silences: sil, words: ws }, { from: seg.start, to: seg.end }), words: ws, ...(got ? { wordsFrom: got.from ?? null } : {}), }); } return out; } /** The master's length in seconds (its frames over the fps), or null when it cannot be read. */ export async function probeMasterSeconds(file, fps) { try { const { stdout } = await execFileP(FFPROBE(), [ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=nb_frames:format=duration", "-of", "json", file, ]); const j = JSON.parse(stdout); const n = Number(j.streams?.[0]?.nb_frames); if (Number.isFinite(n) && n > 0 && fps) return n / fps; const d = Number(j.format?.duration); return Number.isFinite(d) ? d : null; } catch { return null; } } /** ffmpeg, run: resolves when it exits 0, rejects with its stderr's tail. */ export async function runFfmpeg(argv) { try { await execFileP(FFMPEG(), argv, { maxBuffer: 1 << 26 }); } catch (err) { const tail = String(err?.stderr ?? err?.message ?? err).trim().split("\n").slice(-6).join("\n"); throw new Error(`ffmpeg failed: ${tail}`); } } /** * Cut a trailer from a take's master. * * @param {object} a * @param {string} a.takeDir `takes//` * @param {object[]} a.beats parseBeats's * @param {boolean} [a.intro] * @param {number|null} [a.finale] * @param {number} [a.xfade] * @param {string|null} [a.out] --out * @param {boolean} [a.dryRun] the plan only: nothing encoded, nothing written * @param {(argv: string[]) => Promise} [a.run] the ffmpeg runner (tests stub it) * @param {(file: string, fps: number) => Promise} [a.probe] * @param {(fn: () => Promise) => Promise} [a.slot] the heavy slot around the encode * @param {() => number} [a.now] * @param {boolean} [a.snap] move clip beats' edges into pauses (false: `--no-snap`) * @param {(build: object, beats: object[]) => Promise>} [a.measure] the pauses (trailerPauses; tests stub it) */ export async function makeTrailer({ takeDir, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT, out = null, dryRun = false, run = runFfmpeg, probe = probeMasterSeconds, slot = (fn) => fn(), now = Date.now, snap = true, measure = (build, list) => trailerPauses({ build, beats: list }), reel = null, introSpec = null, outro = null, makeIntro = renderReelIntro, makeOutro = renderOutroCard, sitesDir = undefined, }) { const build = await loadTakeBuild(takeDir); // The reel's intro (reelIntro.mjs): the master's own when it has one and the // reel names no intro of its own, else one rendered for the reel. let ri = null; if (intro || introSpec) { try { ri = reelIntroOf({ build, introSpec, sitesDir }); } catch (e) { throw new TrailerError(e instanceof Error ? e.message : String(e)); } } const masterIntro = !!ri && ri.from === "master"; const extras = (plan) => withReelExtras(plan, { intro: ri && !masterIntro ? { file: null, seconds: ri.entry.seconds, label: ri.label } : null, outro: outro ? { seconds: outro.seconds, title: outro.title, text: outro.text, image: outro.image ?? null } : null, }); // Checked once without the pauses first: a beat that is refused is refused // before anything is measured. planTrailer({ schedule: build.schedule, records: build.records, beats, intro: masterIntro, finale, xfade, snap: false }); const pauses = snap ? await measure(build, beats) : null; const plan = extras(planTrailer({ schedule: build.schedule, records: build.records, beats, intro: masterIntro, finale, xfade, pauses, snap })); if (ri) plan.notes.unshift(`intro: ${ri.label}`); const masterSeconds = await probe(build.master, plan.fps); if (masterSeconds == null) throw new TrailerError(`${path.basename(takeDir)} has no master: ${build.master} cannot be read`); if (Math.abs(masterSeconds - plan.masterSeconds) > 0.1) { throw new TrailerError( `${build.master} is ${fmt(masterSeconds)} s but its build records describe a ${fmt(plan.masterSeconds)} s cut — ` + "the master is not the build these records are from (rebuilt since, or a window take)", ); } const outPath = trailerOutPath(takeDir, build.slug, out); if (path.resolve(outPath) === path.resolve(build.master)) throw new TrailerError(`--out ${out}: that is the master`); const recordPath = trailerRecordPath(outPath); // What it was cut from, named so a later read can say the cut is stale: the // master by its mtime and the take's build, the reel by its file's version. const masterStat = await stat(build.master).catch(() => null); const takeMeta = await readFile(path.join(takeDir, "take.json"), "utf8").then(JSON.parse, () => null); const record = { version: 1, kind: "trailer", ...(reel ? { reel } : {}), source: { take: path.basename(takeDir), build: typeof takeMeta?.builtAt === "string" ? takeMeta.builtAt : null, master: build.master, masterMtimeMs: masterStat ? Math.round(masterStat.mtimeMs) : null, masterSeconds: r3(masterSeconds), schedule: path.join(takeDir, "out", "sourced", "schedule.json"), }, xfade: plan.xfade, snap, transition: plan.transition, fps: plan.fps, encode: { crf: build.render.crf ?? 20, preset: build.render.preset ?? "medium", audioBitrate: build.render.audioBitrate ?? "160k" }, seconds: plan.total, pieces: plan.pieces, ...(plan.outro ? { outro: { title: plan.outro.title, text: plan.outro.text, image: plan.outro.image, seconds: plan.outro.seconds, fade: plan.outro.fade, at: plan.outro.at } } : {}), notes: plan.notes, }; if (dryRun) return { plan, outPath, recordPath, record, encodeSeconds: null, dryRun: true }; await mkdir(path.dirname(outPath), { recursive: true }); /** The reel's own intro and outro card, made inside the slot (the intro is a HyperFrames render, cached). */ const prepare = async () => { if (ri && !masterIntro) { const file = await makeIntro({ entry: ri.entry, build, takeDir }); plan.pieces[0].file = file; record.pieces[0].file = file; } let card = null; if (outro) { const W = build.render.width ?? 1920; const H = build.render.height ?? 1080; const r = await makeOutro({ width: W, height: H, title: outro.title, text: outro.text, imageFile: outro.imageFile ?? null, brand: await outroBrand(ri?.entry ?? null, { provenance: build.manifest?.provenance ?? null, sitesDir }), dir: path.join(takeDir, "out", "sourced", "outro"), }); card = { png: r.file, seconds: plan.outro.seconds, fade: plan.outro.fade }; record.outro.card = r.file; } return trailerArgs({ plan, master: build.master, render: build.render, outPath: "", outro: card }); }; let argv = null; // Written beside, then renamed: a half-made file never sits at the name. const tmp = tmpPathFor(path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}`), { ext: ".mp4" }); let encodeSeconds = null; // Cancelled (the Trailer page's Cancel signals the job's process group): the // half-made file goes with it. Exits as the signal would when nothing else // here listens for it. const onSignal = ["SIGTERM", "SIGINT", "SIGHUP"].map((sig) => { const alone = process.listenerCount(sig) === 0; const h = () => { try { rmSync(tmp, { force: true }); } catch { // gone already } if (alone) process.exit(128 + (sig === "SIGINT" ? 2 : sig === "SIGHUP" ? 1 : 15)); }; process.once(sig, h); return /** @type {const} */ ([sig, h]); }); try { await slot(async () => { argv = await prepare(); argv[argv.length - 1] = tmp; const t0 = now(); try { await run(argv); await rename(tmp, outPath); } catch (err) { await rm(tmp, { force: true }); throw err; } encodeSeconds = r3((now() - t0) / 1000); }); } finally { for (const [sig, h] of onSignal) process.off(sig, h); } record.builtAt = new Date(now()).toISOString(); record.encodeSeconds = encodeSeconds; record.out = outPath; await writeFile(recordPath, JSON.stringify(record, null, 2) + "\n"); return { plan, outPath, recordPath, record, encodeSeconds, dryRun: false }; } /** The printed plan: one line per piece, then the total. */ export function describePlan(plan) { const lines = plan.pieces.map((p, i) => { const what = p.kind === "clip" ? `${p.id.padEnd(22)} source ${fmt(p.source.start)}–${fmt(p.source.end)}` : p.kind === "raw" ? `${"(master)".padEnd(22)} at ${fmt(p.asked.at)} for ${fmt(p.asked.dur)}` : `${`(${p.kind})`.padEnd(22)}`; const span = p.master ? `master ${clock(p.master.start)}–${clock(p.master.end)}` : `its own render${p.label ? ` (${p.label})` : ""}`; const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}${p.cuts?.length ? ` (${p.cuts.length} gap${p.cuts.length === 1 ? "" : "s"} cut)` : ""}`; return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.seconds ?? p.master?.duration ?? p.frames.count / plan.fps)} s${marks}`; }); if (plan.outro) { lines.push(`${String(plan.pieces.length + 1).padStart(2)}. ${clock(plan.outro.at).padStart(6)} ${"(outro)".padEnd(48)} the card${plan.outro.title ? ` "${plan.outro.title}"` : ""} ${fmt(plan.outro.seconds)} s (fades in over ${fmt(plan.outro.fade)} s)`); } lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces${plan.outro ? " and the outro" : ""}, crossfade ${fmt(plan.xfade)} s`); return lines; }