Archilyzer · Source

archilyzer

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

commit 9518b0b8c8c01a3ddb21935ff199f25dd0d337d9
parent 2472479d18dd84de3d1881cef2e05c4565e978b6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 16:57:32 -0500

umtool reels: a beat may carry gaps -- two moments of one clip as one beat of jump cuts, cut, played and counted as a clip's gap renders

A clip beat takes `gaps: [{ from, to }]` in its clip's source seconds, the
clip gap rule on the beat (gaps.mjs beatGapsOf: at least GAP_LIMITS.min each,
in order, GAP_LIMITS.keep kept before, between and after, at most
GAP_LIMITS.max). The one writer stores and refuses them (updateTrailerBeat's
`gaps`, the list; the edges and the gaps are checked as one rule), the view
counts a beat by what it plays (the clip's own gaps and the beat's, merged),
and `umtool trailer-beats <p> gap <n> add <from>-<to> | remove <s> | clear`
is the terminal's twin.

The cut (trailer.mjs planTrailer): a gapped beat is ONE piece -- its span on
the master, each gap mapped to the master seconds it covers (across a gap the
render already cut, the master runs on, so the span either side; a beat gap
wholly inside one is refused by name), frame-aligned inside what is left of
the beat. Its `cuts` and kept `seconds` ride on the piece; the reel's clock
and the crossfade offsets count kept seconds; the run's cuts leave the graph
through gapFilterParts (hard cuts, the sound faded GAP_FADE either side, as a
clip's gap renders; a `tag` keeps two in one graph) -- never the beat-to-beat
--xfade. One real encode in the tests runs its kept 5 s.

Play the reel (useReelPlayer, reelTypes masterAt/reelAtMaster/cutAt) seeks
over a beat's cuts as the cut leaves them out, its clock kept seconds.

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

Diffstat:
Mumtool/components/projects/reel/ReelPlay.tsx | 10+++++-----
Mumtool/components/projects/reel/reelTypes.ts | 31+++++++++++++++++++++++++++----
Mumtool/components/projects/reel/useReelPlayer.ts | 12++++++++----
Mumtool/lib/report/reelPlay.mjs | 11+++++++++--
Mumtool/lib/report/trailerBeats.mjs | 39++++++++++++++++++++++++++++++++++-----
Mumtool/lib/report/trailerBeats.test.mjs | 29+++++++++++++++++++++++++++++
Mumtool/lib/report/trailerBeatsCli.mjs | 27++++++++++++++++++++++++++-
Aumtool/lib/report/trailerBeatsCli.test.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/gaps.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/trailer-gaps.test.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/trailer.mjs | 101++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
11 files changed, 451 insertions(+), 42 deletions(-)

diff --git a/umtool/components/projects/reel/ReelPlay.tsx b/umtool/components/projects/reel/ReelPlay.tsx @@ -9,7 +9,7 @@ import { NoteThread } from "@/components/notes/NoteThread"; import type { CutAsk, Note } from "@/lib/annotations/types"; import { reelPlayHref, reelWalkHref, takesHref, trailerHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; -import { clock, itemAt, masterOfSource, masterSrc, readReelView, reelItems, sourceClock, sourceOfMaster, type ReelRow, type ReelView } from "./reelTypes"; +import { clock, itemAt, masterAt, masterOfSource, masterSrc, reelAtMaster, readReelView, reelItems, sourceClock, sourceOfMaster, type ReelRow, type ReelView } from "./reelTypes"; import { useReelPlayer } from "./useReelPlayer"; // --------------------------------------------------------------------------- @@ -106,10 +106,10 @@ export default function ReelPlay({ initial, initialBeat = null, initialNote = nu return !!s && a.sourceT! >= s.start - 0.05 && a.sourceT! <= s.end + 0.05; }); const m = it?.row ? masterOfSource(it.row, a.sourceT) : null; - if (it && m !== null) return Math.max(it.at, Math.min(it.at + it.dur, it.at + (m - it.mStart))); + if (it && m !== null) return reelAtMaster(it, m); } const byBeat = items.find((x) => x.n === a.beat); - if (byBeat && a.masterT !== undefined && a.masterT >= byBeat.mStart && a.masterT <= byBeat.mEnd) return byBeat.at + (a.masterT - byBeat.mStart); + if (byBeat && a.masterT !== undefined && a.masterT >= byBeat.mStart && a.masterT <= byBeat.mEnd) return reelAtMaster(byBeat, a.masterT); return byBeat ? byBeat.at : a.t; }, [items], @@ -123,7 +123,7 @@ export default function ReelPlay({ initial, initialBeat = null, initialNote = nu if (!it?.row) return; resume.current = e.playing; if (e.playing) player.setPlaying(false); - const masterT = it.mStart + (e.t - it.at); + const masterT = masterAt(it, e.t); const src = sourceOfMaster(it.row, masterT); setDrafting({ kind: "reel", @@ -236,7 +236,7 @@ export default function ReelPlay({ initial, initialBeat = null, initialNote = nu const mismatch = videoSeconds !== null && view.masterSeconds !== undefined && Math.abs(videoSeconds - view.masterSeconds) > 0.2; const rows = view.rows ?? []; const unplayable = rows.filter((r) => !r.piece); - const masterT = item ? item.mStart + (t - item.at) : 0; + const masterT = item ? masterAt(item, t) : 0; const srcNow = row ? sourceOfMaster(row, masterT) : null; const src = masterSrc(project, take, view.take?.masterMtimeMs); diff --git a/umtool/components/projects/reel/reelTypes.ts b/umtool/components/projects/reel/reelTypes.ts @@ -10,6 +10,9 @@ export type ReelPiece = { seamless: boolean; moved: unknown; source: { start: number; end: number } | null; + /** A gapped beat: the master spans its gaps leave out (hard cuts), and the seconds it plays. */ + cuts?: { from: number; to: number }[]; + seconds?: number; }; export type ReelRow = { @@ -18,7 +21,7 @@ export type ReelRow = { id: string | null; label: string | null; verdict: "confirmed" | "note" | null; - beat: { start?: number; end?: number; at?: number; dur?: number }; + beat: { start?: number; end?: number; at?: number; dur?: number; gaps?: { from: number; to: number }[] }; problem: string | null; piece: ReelPiece | null; asked: { start: number; end: number } | null; @@ -86,15 +89,35 @@ export type ReelView = { }; /** One run of the master the player plays: the intro, or a beat that maps. */ -export type ReelItem = { key: string; n: number; at: number; mStart: number; mEnd: number; dur: number; seamless: boolean; row: ReelRow | null }; +export type ReelItem = { key: string; n: number; at: number; mStart: number; mEnd: number; dur: number; seamless: boolean; row: ReelRow | null; cuts: { from: number; to: number }[] }; + +/** The master second `t` reel seconds into an item plays (its cuts skipped). */ +export function masterAt(it: ReelItem, t: number): number { + let m = it.mStart + Math.max(0, Math.min(it.dur, t - it.at)); + for (const c of it.cuts) if (m >= c.from - 1e-6) m += c.to - c.from; + return Math.min(it.mEnd, m); +} + +/** The reel second a master second inside an item plays at (inside a cut: where the cut joins). */ +export function reelAtMaster(it: ReelItem, m: number): number { + let off = m - it.mStart; + for (const c of it.cuts) { + if (m >= c.to) off -= c.to - c.from; + else if (m > c.from) off -= m - c.from; + } + return it.at + Math.max(0, Math.min(it.dur, off)); +} + +/** The cut a master second is inside, if any. */ +export const cutAt = (it: ReelItem, m: number) => it.cuts.find((c) => m >= c.from - 1e-3 && m < c.to - 1e-3) ?? null; /** The pieces in reel order. */ export function reelItems(view: ReelView): ReelItem[] { const out: ReelItem[] = []; - if (view.intro) out.push({ key: "intro", n: 0, at: view.intro.at, mStart: view.intro.master.start, mEnd: view.intro.master.end, dur: view.intro.master.duration, seamless: false, row: null }); + if (view.intro) out.push({ key: "intro", n: 0, at: view.intro.at, mStart: view.intro.master.start, mEnd: view.intro.master.end, dur: view.intro.master.duration, seamless: false, row: null, cuts: [] }); for (const r of view.rows ?? []) { if (!r.piece) continue; - out.push({ key: `b${r.n}`, n: r.n, at: r.piece.at, mStart: r.piece.master.start, mEnd: r.piece.master.end, dur: r.piece.master.duration, seamless: r.piece.seamless, row: r }); + out.push({ key: `b${r.n}`, n: r.n, at: r.piece.at, mStart: r.piece.master.start, mEnd: r.piece.master.end, dur: r.piece.seconds ?? r.piece.master.duration, seamless: r.piece.seamless, row: r, cuts: r.piece.cuts ?? [] }); } return out; } diff --git a/umtool/components/projects/reel/useReelPlayer.ts b/umtool/components/projects/reel/useReelPlayer.ts @@ -1,7 +1,7 @@ "use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { itemAt, type ReelItem } from "./reelTypes"; +import { cutAt, itemAt, masterAt, reelAtMaster, type ReelItem } from "./reelTypes"; // THE REEL'S PLAYER: a reel's runs of the master played back to back on one // reel clock, the trailer's crossfades previewed. Two <video> elements on the @@ -12,7 +12,8 @@ import { itemAt, type ReelItem } from "./reelTypes"; // before) stays on the same element, so its frames follow with no seek. // // The clock is the active element's currentTime mapped through its run: -// t = item.at + (currentTime − item.mStart). Nothing is decoded here that the +// t = item.at + (currentTime − item.mStart), less a gapped beat's cuts, which +// the player seeks over as the cut leaves them out (reelTypes masterAt). Nothing is decoded here that the // browser does not: it is seeks of one file. export type ReelPlayer = { @@ -72,7 +73,7 @@ export function useReelPlayer(items: ReelItem[], xfade: number, vids: React.RefO const it = items[i]; const v = el(i); if (!it || !v) return; - const want = it.mStart + Math.max(0, Math.min(it.dur, t - it.at)); + const want = masterAt(it, t); if (Math.abs(v.currentTime - want) > 0.04) v.currentTime = want; }, [items, el], @@ -154,7 +155,10 @@ export function useReelPlayer(items: ReelItem[], xfade: number, vids: React.RefO const it = items[i]; const v = el(i); if (!it || !v) return; - let t = it.at + (v.currentTime - it.mStart); + // A gapped beat's cut: on past it, as the cut plays it (a hard cut). + const c = cutAt(it, v.currentTime); + if (c && !v.seeking) v.currentTime = c.to; + let t = reelAtMaster(it, v.currentTime); const nx = items[i + 1]; // Past the run's end (or the element stopped at the file's end): the next run is current. if (v.currentTime >= it.mEnd - 1e-3 || v.ended) { diff --git a/umtool/lib/report/reelPlay.mjs b/umtool/lib/report/reelPlay.mjs @@ -221,10 +221,17 @@ export function reelPlan(build, rawBeats, { intro = false, xfade = TRAILER_XFADE id: isClip ? String(raw.id) : null, label: typeof raw.label === "string" ? raw.label : null, verdict: raw.verdict === "confirmed" || raw.verdict === "note" ? raw.verdict : null, - beat: isClip ? { start: raw.start, end: raw.end } : { at: raw.at, dur: raw.dur }, + beat: isClip ? { start: raw.start, end: raw.end, ...(Array.isArray(raw.gaps) && raw.gaps.length ? { gaps: raw.gaps } : {}) } : { at: raw.at, dur: raw.dur }, problem: r.problem, // Where it plays: the plan's piece (master span after the crossfades are kept out; where it lands in the reel). - piece: p ? { at: p.at, master: p.master, frames: p.frames, seamless: p.seamless === true, moved: p.moved ?? null, source: p.source ?? null } : null, + piece: p + ? { + at: p.at, master: p.master, frames: p.frames, seamless: p.seamless === true, moved: p.moved ?? null, source: p.source ?? null, + // A gapped beat: the master spans it leaves out, and what it plays. + cuts: (p.cuts ?? []).map((c) => ({ from: c.from, to: c.to })), + seconds: p.seconds ?? p.master.duration, + } + : null, asked, limits, map, diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -36,7 +36,7 @@ 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, parseBeats } from "umtool-report-to-video/trailer"; +import { TRAILER_XFADE_DEFAULT, TrailerError, beatGaps, parseBeats } from "umtool-report-to-video/trailer"; import { indentOf } from "./patchMarkers.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; @@ -288,7 +288,18 @@ function cleanBeat(b) { 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) return { id: String(b.id), start: r2(b.start), end: r2(b.end), ...label, ...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 }; + } return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict }; } @@ -335,9 +346,15 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); - if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, label?, verdict? }"); + if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, gaps?, label?, verdict? }"); const b = { ...beats[n] }; for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k]; + // 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]; @@ -448,6 +465,17 @@ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFA }, { reel, what: `settings: ${Object.keys(isObj(patch) ? patch : {}).join(", ")}` }); } +/** 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(); @@ -511,7 +539,8 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT 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); - seconds = b > a ? gappedLength(a, b, gapsOf(e)) : 0; + // 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); @@ -528,7 +557,7 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT return { n: i + 1, kind, - ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end } : { at: raw?.at, dur: raw?.dur }), + ...(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), diff --git a/umtool/lib/report/trailerBeats.test.mjs b/umtool/lib/report/trailerBeats.test.mjs @@ -220,3 +220,32 @@ test("every write is an undo point: undo puts the file back as it was, one write await rm(dir, { recursive: true, force: true }); } }); + +test("a beat's gaps (lane/reel-bench): written as a list through the one writer, refused by the clip gap rule, counted out of its length; undo puts them back", async () => { + const dir = await project([{ id: "a", start: 11, end: 19 }]); + try { + let tok = await beatsToken(dir); + const r = await updateTrailerBeat(dir, 0, { gaps: [{ from: 15.004, to: 17 }, { from: 12, to: 13 }] }, { token: tok }); + assert.deepEqual(r.beat.gaps, [{ from: 12, to: 13 }, { from: 15, to: 17 }]); + assert.deepEqual(JSON.parse(await fileOf(dir))[0], { id: "a", start: 11, end: 19, gaps: [{ from: 12, to: 13 }, { from: 15, to: 17 }] }); + // 8 s of beat, 3 s cut: the view counts 5; and the clip's own gaps with them on another beat. + const v = trailerView(manifest(), await readTrailerBeats(dir)); + assert.equal(v.rows[0].seconds, 5); + assert.deepEqual(v.rows[0].gaps, [{ from: 12, to: 13 }, { from: 15, to: 17 }]); + const both = trailerView(manifest(), { beats: [{ id: "b", start: 30, end: 50, gaps: [{ from: 39, to: 44 }] }] }); + // b's own gap 35–40 and the beat's 39–44: 9 s out of 20. + assert.equal(both.rows[0].seconds, 11); + tok = await beatsToken(dir); + await assert.rejects(updateTrailerBeat(dir, 0, { gaps: [{ from: 11.2, to: 12 }] }, { token: tok }), /keep at least 0.5 s/); + await assert.rejects(updateTrailerBeat(dir, 0, { gaps: [{ from: 14, to: 14.1 }] }, { token: tok }), /under 0.2 s/); + // Moving the edges inside a gap is refused too: the edges and the gaps are one rule. + await assert.rejects(updateTrailerBeat(dir, 0, { end: 17.2 }, { token: tok }), /before the beat's end/); + await updateTrailerBeat(dir, 0, { gaps: [] }, { token: tok }); + assert.deepEqual(JSON.parse(await fileOf(dir))[0], { id: "a", start: 11, end: 19 }); + const { undoTrailerBeats } = await import("./trailerBeats.mjs"); + await undoTrailerBeats(dir); + assert.equal(JSON.parse(await fileOf(dir))[0].gaps.length, 2); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerBeatsCli.mjs b/umtool/lib/report/trailerBeatsCli.mjs @@ -8,6 +8,7 @@ // Beats are numbered from 1, as `umtool trailer`'s refusals number them. // // Plain ESM: the CLI runs under bare node. +import { editGaps } from "umtool-report-to-video/gaps"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { @@ -42,6 +43,8 @@ export const TRAILER_BEATS_USAGE = [ " a clip beat (default: the clip's whole cut), in the cut's order unless --at N", " umtool trailer-beats <project> add-raw <at> <dur> [--at N] [--label L] master seconds", " umtool trailer-beats <project> set <n> <from>-<to> [--label L] beat n's source seconds", + " umtool trailer-beats <project> gap <n> add <from>-<to> | remove <second> | clear", + " seconds cut out of beat n's middle (a clip's gap rule): it plays as one beat of jump cuts", " umtool trailer-beats <project> remove <n> | move <n> --to <m> | order (the cut's order)", ` umtool trailer-beats <project> limit <seconds|m:ss|${TRAILER_LIMITS.map((l) => l.id).join("|")}> | xfade <s> | intro on|off`, " umtool trailer-beats <project> candidates [--add] the walk's ★ clips not yet beats (--add: all of them)", @@ -101,8 +104,9 @@ export function viewLines(v) { const lines = []; for (const r of v.rows) { const what = r.kind === "clip" ? `${r.id.padEnd(8)} ${String(r.start).padStart(9)}–${String(r.end).padEnd(9)}` : `(master) at ${r.at} for ${r.dur}`.padEnd(29); + const gaps = r.gaps?.length ? ` gaps ${r.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : ""; const flag = r.problems.length ? ` ! ${r.problems.join("; ")}` : ""; - lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${flag}`); + lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${gaps}${flag}`); } lines.push( `${v.rows.length} beat(s): ${clockOf(v.total)} of ${clockOf(v.limit)}${v.over ? ` — OVER by ${(v.total - v.limit).toFixed(1)} s` : ` (${v.remaining.toFixed(1)} s to spare)`}` + @@ -165,6 +169,27 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) did = `beat ${i + 1}: ${JSON.stringify(res.beat)}`; break; } + case "gap": { + const i = beatNo(rest[0]); + const op = rest[1]; + const doc = await readTrailerBeats(project.dir, { reel }); + const b = doc.beats[i]; + if (!b) throw new CliError(`no beat ${i + 1}`); + if (b.id === undefined) throw new CliError(`beat ${i + 1} is master seconds ({ at, dur }): only a clip beat has gaps`); + let next; + if (op === "add") { + const sp = spanOf(rest[2]); + next = editGaps(b.gaps ?? [], { add: { from: sp.start, to: sp.end } }); + } else if (op === "remove") { + const t = Number(rest[2]); + if (!Number.isFinite(t)) throw new CliError("gap <n> remove <second>: a source second inside (or at) the gap"); + next = editGaps(b.gaps ?? [], { remove: t }); + } else if (op === "clear") next = []; + else throw new CliError("gap <n> add <from>-<to> | remove <second> | clear"); + const res = await updateTrailerBeat(project.dir, i, { gaps: next }, { token, reel }); + did = `beat ${i + 1}: ${(res.beat.gaps ?? []).length ? `gaps ${res.beat.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps"}`; + break; + } case "remove": { const i = beatNo(rest[0]); const res = await removeTrailerBeat(project.dir, i, { token, reel }); diff --git a/umtool/lib/report/trailerBeatsCli.test.mjs b/umtool/lib/report/trailerBeatsCli.test.mjs @@ -0,0 +1,43 @@ +// `umtool trailer-beats ... gap` (lane/reel-bench): a beat's gaps from a +// terminal, through the beats' one writer -- the page's twin. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { trailerBeatsCommand } from "./trailerBeatsCli.mjs"; + +async function root() { + const r = await mkdtemp(path.join(tmpdir(), "umtool-tbcli-")); + const dir = path.join(r, "p1"); + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "p1", title: "P1", timeline: [{ type: "clip", id: "a", video: "v", start: 10, end: 30 }] })); + await writeFile(path.join(dir, "promo", "trailer-beats.json"), JSON.stringify([{ id: "a", start: 11, end: 29 }, { at: 3, dur: 2 }])); + return { r, dir }; +} + +test("gap <n> add / remove / clear: written through the writer, said, refused by name", async () => { + const { r, dir } = await root(); + const out = []; + const err = []; + const run = (...a) => trailerBeatsCommand(["p1", ...a], { root: r, out: (s) => out.push(s), err: (s) => err.push(s) }); + try { + assert.equal(await run("gap", "1", "add", "14-17"), 0); + assert.match(out.join("\n"), /beat 1: gaps 14–17/); + assert.match(out.join("\n"), /gaps 14–17/); + assert.equal(await run("gap", "1", "add", "20-22"), 0); + const beats = () => readFile(path.join(dir, "promo", "trailer-beats.json"), "utf8").then(JSON.parse); + assert.deepEqual((await beats())[0].gaps, [{ from: 14, to: 17 }, { from: 20, to: 22 }]); + assert.equal(await run("gap", "1", "remove", "15"), 0); + assert.deepEqual((await beats())[0].gaps, [{ from: 20, to: 22 }]); + assert.equal(await run("gap", "1", "clear"), 0); + assert.equal((await beats())[0].gaps, undefined); + assert.equal(await run("gap", "1", "add", "11.1-12"), 1); + assert.match(err.join("\n"), /keep at least 0.5 s/); + assert.equal(await run("gap", "2", "add", "3.5-4"), 2); + assert.match(err.join("\n"), /only a clip beat has gaps/); + } finally { + await rm(r, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -172,6 +172,53 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}` return errors; } +/** + * A clip beat's GAPS (lane/reel-bench): source seconds cut out of its middle, + * so two moments of one clip play as one beat of jump cuts -- the same shape + * and the same rule as a clip's gaps (gaps.mjs): each `{ from, to }` at least + * GAP_LIMITS.min long, in order, inside the beat with at least GAP_LIMITS.keep + * seconds kept before, between and after them, at most GAP_LIMITS.max. + * Returned sorted, each edge at 2 dp; absent or [] is none. Dependency-free, + * like the rest of this module: the reel's walk checks a gap with it before it + * is sent, and trailer.mjs (beatGaps) refuses with it. + * + * @param {{ start: number, end: number, gaps?: unknown }} b + * @param {string} where + * @returns {Array<{ from: number, to: number }>} + */ +export function beatGapsOf(b, where = "beat") { + const v = b?.gaps; + if (v === undefined || v === null) return []; + if (!Array.isArray(v)) throw new Error(`${where}: gaps is a list of { from, to } in source seconds`); + if (v.length > GAP_LIMITS.max) throw new Error(`${where}: at most ${GAP_LIMITS.max} gaps in one beat (it has ${v.length})`); + const r2 = (n) => Number(Number(n).toFixed(2)); + const list = v.map((g, k) => { + if (!g || typeof g !== "object" || !Number.isFinite(g.from) || !Number.isFinite(g.to)) throw new Error(`${where}: gaps[${k}] must be { from, to } in source seconds`); + if (g.to - g.from < GAP_LIMITS.min - 1e-6) throw new Error(`${where}: the gap ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); + return { from: r2(g.from), to: r2(g.to) }; + }).sort((x, y) => x.from - y.from); + let before = b.start; + list.forEach((g, k) => { + if (g.from - before < GAP_LIMITS.keep - WIN_EPS) { + throw new Error( + g.from < before + ? `${where}: the gap ${g.from}–${g.to} ${k ? "overlaps the gap before it — merge them" : `starts before the beat (${b.start})`}` + : `${where}: the gap ${g.from}–${g.to} leaves ${Math.max(0, g.from - before).toFixed(2)} s after ${k ? "the gap before it" : "the beat's start"}; keep at least ${GAP_LIMITS.keep} s`, + ); + } + before = g.to; + }); + if (list.length && b.end - before < GAP_LIMITS.keep - WIN_EPS) { + const g = list[list.length - 1]; + throw new Error( + g.to > b.end + ? `${where}: the gap ${g.from}–${g.to} runs past the beat's end (${b.end})` + : `${where}: the gap ${g.from}–${g.to} leaves ${Math.max(0, b.end - before).toFixed(2)} s before the beat's end; keep at least ${GAP_LIMITS.keep} s`, + ); + } + return list; +} + /** Every clip's gaps in the timeline, checked: the build refuses with these before it fetches. */ export function validateGapEntries(manifest) { const errors = []; @@ -359,24 +406,25 @@ const n3 = (v) => Number(v.toFixed(6)).toString(); * poster stands in; no sound: none). Empty `parts` without gaps. * * @param {{ gaps: Array<{ from: number, to: number }>, seconds: number, vIn?: string | null, aIn?: string | null, - * vOut?: string, aOut?: string, fade?: number }} o + * vOut?: string, aOut?: string, fade?: number, tag?: string }} o + * `tag` goes into the filter's own labels, so two of them sit in one graph (a trailer's runs) * @returns {{ parts: string[], v: string | null, a: string | null }} */ -export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vOut = "[gv]", aOut = "[ga]", fade = GAP_FADE }) { +export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vOut = "[gv]", aOut = "[ga]", fade = GAP_FADE, tag = "" }) { if (!gaps?.length) return { parts: [], v: vIn, a: aIn }; const pieces = keptSpans(0, seconds, gaps); const K = pieces.length; const parts = []; if (vIn) { - const outs = pieces.map((_, k) => `[gvs${k}]`); + const outs = pieces.map((_, k) => `[g${tag}vs${k}]`); parts.push(`${vIn}split=${K}${outs.join("")}`); pieces.forEach((p, k) => { - parts.push(`${outs[k]}trim=start=${n3(p.from)}:end=${n3(p.to)},setpts=PTS-STARTPTS[gvp${k}]`); + parts.push(`${outs[k]}trim=start=${n3(p.from)}:end=${n3(p.to)},setpts=PTS-STARTPTS[g${tag}vp${k}]`); }); - parts.push(`${pieces.map((_, k) => `[gvp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); + parts.push(`${pieces.map((_, k) => `[g${tag}vp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); } if (aIn) { - const outs = pieces.map((_, k) => `[gas${k}]`); + const outs = pieces.map((_, k) => `[g${tag}as${k}]`); parts.push(`${aIn}asplit=${K}${outs.join("")}`); pieces.forEach((p, k) => { const len = p.to - p.from; @@ -385,9 +433,9 @@ export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vO // Only at a join: the segment's own edges are the crossfade's and room's. if (k > 0) f.push(`afade=t=in:st=0:d=${n3(d)}`); if (k < K - 1) f.push(`afade=t=out:st=${n3(Math.max(0, len - d))}:d=${n3(d)}`); - parts.push(`${outs[k]}${f.join(",")}[gap${k}]`); + parts.push(`${outs[k]}${f.join(",")}[g${tag}ap${k}]`); }); - parts.push(`${pieces.map((_, k) => `[gap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); + parts.push(`${pieces.map((_, k) => `[g${tag}ap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); } return { parts, v: vIn ? vOut : null, a: aIn ? aOut : null }; } diff --git a/umtool/report-to-video/trailer-gaps.test.mjs b/umtool/report-to-video/trailer-gaps.test.mjs @@ -0,0 +1,126 @@ +// trailer.mjs: a GAPPED beat (lane/reel-bench) -- two moments of one clip as +// one beat of jump cuts, cut from the master as its kept pieces joined the +// way a clip's gap renders (hard cuts, the sound faded GAP_FADE), not by the +// trailer's beat-to-beat crossfade. The rule, the plan, the graph, and one +// real encode of a synthesized master. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { TrailerError, beatGaps, parseBeats, pieceFrames, planTrailer, trailerArgs, trailerRuns } from "./trailer.mjs"; + +const SCHEDULE = { + version: 1, kind: "deck", fps: 30, transition: 0.5, total: 40.167, + segments: [ + { id: "brand-intro", type: "intro", start: 0, duration: 4.167, end: 4.167 }, + { id: "c1", type: "clip", start: 3.667, duration: 12, end: 15.667 }, + { id: "c2", type: "clip", start: 15.167, duration: 10, end: 25.167 }, + { id: "c3", type: "clip", start: 24.667, duration: 15.5, end: 40.167 }, + ], +}; +const RECORDS = new Map([ + ["c1", { version: 1, id: "c1", start: 100.2, end: 112.2 }], + // c2's render left 504–505 out: its segment plays 500–504 then 505–511. + ["c2", { version: 1, id: "c2", start: 500, end: 511, gaps: [{ from: 504, to: 505 }] }], + ["c3", { version: 1, id: "c3", start: 2000, end: 2015.5 }], +]); +const plan = (beats, o = {}) => planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: parseBeats(beats), snap: false, ...o }); +const close = (a, b, eps = 1 / 60) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b}`); + +test("beatGaps: a clip's gap rule on a beat -- sorted, 2 dp, refused by name", () => { + assert.deepEqual(beatGaps({ start: 1, end: 9, gaps: [{ from: 6.004, to: 7 }, { from: 2, to: 3.5 }] }), [{ from: 2, to: 3.5 }, { from: 6, to: 7 }]); + assert.deepEqual(beatGaps({ start: 1, end: 9 }), []); + const no = (gaps, re) => assert.throws(() => beatGaps({ start: 1, end: 9, gaps }, "beat 2 (c1)"), (e) => e instanceof TrailerError && re.test(e.message)); + no([{ from: 2, to: 2.1 }], /beat 2 \(c1\): the gap 2–2.1 is under 0.2 s/); + no([{ from: 1.2, to: 3 }], /leaves 0.20 s after the beat's start; keep at least 0.5 s/); + no([{ from: 2, to: 4 }, { from: 3, to: 5 }], /overlaps the gap before it/); + no([{ from: 7, to: 8.8 }], /leaves 0.20 s before the beat's end/); + no([{ from: 7, to: 9.5 }], /runs past the beat's end/); + no("2-3", /gaps is a list/); + // parseBeats carries them on a clip beat. + assert.deepEqual(parseBeats([{ id: "c1", start: 1, end: 9, gaps: [{ from: 2, to: 3 }] }])[0].gaps, [{ from: 2, to: 3 }]); +}); + +test("a gapped beat is one piece: its span on the master, the gap's master seconds cut, the kept seconds counted", () => { + const p = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }]); + const [c] = p.pieces; + // 3.667 + (102 − 100.2) = 5.467 → frame 164; 8 s = 240 frames; the gap 104–106 is master 7.467–9.467. + assert.equal(c.frames.start, 164); + assert.equal(c.frames.count, 240); + assert.equal(c.cuts.length, 1); + assert.deepEqual(c.cuts[0].frames, { start: 224, count: 60 }); + close(c.cuts[0].from, 7.467); + assert.equal(c.seconds, 6); + assert.equal(pieceFrames(c), 180); + assert.equal(p.total, 6); + assert.deepEqual(c.gaps, [{ from: 104, to: 106 }]); +}); + +test("one gapped beat runs as long as the two beats it replaces, less their crossfade (within the 0.35 s the brief allows)", () => { + const two = plan([{ id: "c1", start: 102, end: 104 }, { id: "c1", start: 106, end: 110 }], { xfade: 0.3 }); + const one = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }], { xfade: 0.3 }); + assert.equal(two.total, 5.7); + assert.equal(one.total, 6); + assert.ok(Math.abs(one.total - two.total) <= 0.35); + // Among other beats, it lands and is counted by what it plays. + const p = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }, { id: "c3", start: 2001, end: 2004 }], { xfade: 0.3 }); + close(p.pieces[1].at, 6 - 0.3, 1e-6); + close(p.total, 6 + 3 - 0.3, 1e-6); +}); + +test("over a gap the master already cut: the master seconds either side; wholly inside one: refused by name", () => { + // c2's 504–505 is out of the master: a beat gap 503.5–506 cuts master 15.167+3.5 → 15.167+5 (1.5 s, not 2.5). + const p = plan([{ id: "c2", start: 501, end: 509, gaps: [{ from: 503.5, to: 506 }] }]); + const [c] = p.pieces; + close(c.cuts[0].from, 18.667); + close(c.cuts[0].to, 20.167); + // 8 s of source, 1 s already out of the master, 1.5 s more cut: 5.5 s. + close(c.seconds, 5.5, 1e-6); + assert.throws(() => plan([{ id: "c2", start: 501, end: 509, gaps: [{ from: 504.2, to: 504.8 }] }]), /c2's gap 504.2–504.8 lies inside a gap the master already cut out/); +}); + +test("the graph: the gapped run's cuts as a gap filter with its own labels, the crossfade offset on the kept seconds", () => { + const p = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }, { id: "c3", start: 2001, end: 2004 }], { xfade: 0.3 }); + const runs = trailerRuns(p); + assert.deepEqual(runs[0], { start: 164, count: 240, cuts: [{ start: 224, count: 60 }], kept: 180 }); + assert.equal(runs[1].count, 90); + assert.equal(runs[1].cuts, undefined); + const argv = trailerArgs({ plan: p, master: "/m.mp4", render: { fps: 30 }, outPath: "/o.mp4" }); + const graph = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(graph, /\[m0v\]trim=start=[\d.]+:end=[\d.]+,setpts=PTS-STARTPTS\[r0v\]/); + assert.match(graph, /\[r0v\]split=2\[gr0vs0\]\[gr0vs1\]/); + assert.match(graph, /\[gr0vs0\]trim=start=0:end=2,setpts=PTS-STARTPTS\[gr0vp0\]/); + assert.match(graph, /\[gr0vs1\]trim=start=4:end=8,setpts=PTS-STARTPTS\[gr0vp1\]/); + assert.match(graph, /concat=n=2:v=1:a=0\[v0\]/); + assert.match(graph, /afade=t=out:st=1\.975:d=0\.025/); + assert.match(graph, /concat=n=2:v=0:a=1\[a0\]/); + // The crossfade into the next beat starts 0.3 s before the gapped beat's KEPT end (6 s). + assert.match(graph, /\[v0\]\[v1\]xfade=transition=fade:duration=0\.300000:offset=5\.700000\[xv1\]/); +}); + +test("a real encode: a gapped beat cut from a synthesized master runs its kept seconds", { timeout: 60_000 }, async (t) => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + } catch { + t.skip("no ffmpeg"); + return; + } + const dir = await mkdtemp(path.join(tmpdir(), "trailer-gaps-")); + try { + const master = path.join(dir, "m.mp4"); + execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=30:duration=12", "-f", "lavfi", "-i", "sine=frequency=440:duration=12", + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-g", "15", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", master]); + const schedule = { version: 1, kind: "deck", fps: 30, transition: 0, total: 12, segments: [{ id: "c", type: "clip", start: 0, duration: 12, end: 12 }] }; + const records = new Map([["c", { id: "c", start: 10, end: 22 }]]); + const p = planTrailer({ schedule, records, beats: parseBeats([{ id: "c", start: 11, end: 19, gaps: [{ from: 13, to: 16 }] }]), xfade: 0, snap: false }); + const out = path.join(dir, "t.mp4"); + execFileSync("ffmpeg", trailerArgs({ plan: p, master, render: { fps: 30, crf: 35, preset: "ultrafast", audioBitrate: "64k", audioRate: 48000, audioChannels: 2 }, outPath: out })); + const dur = Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", out], { encoding: "utf8" }).trim()); + close(dur, 5, 0.1); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -74,7 +74,7 @@ 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 { offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; +import { beatGapsOf, gapFilterParts, offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; const execFileP = promisify(execFile); @@ -131,7 +131,8 @@ export function parseBeats(value) { if (typeof b.id !== "string" || !b.id) throw new TrailerError(`${where}: id is a clip id (a string)`); if (!num("start") || !num("end")) throw new TrailerError(`${where} (${b.id}): start and end are source seconds (numbers)`); if (b.end <= b.start) throw new TrailerError(`${where} (${b.id}): end ${b.end} is not after start ${b.start}`); - return { kind: "clip", id: b.id, start: b.start, end: b.end, ...(label ? { label } : {}) }; + 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)`); @@ -143,6 +144,21 @@ export function parseBeats(value) { } /** + * 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 @@ -233,7 +249,19 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = 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)`); } - want.push({ kind: "clip", id: beat.id, beat, n: n + 1, rec, seg, gaps, a, b }); + // 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`); @@ -336,7 +364,28 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = const fa = Math.round(a * fps); const frames = Math.round(b * fps) - fa; const name = w.kind === "clip" ? w.id : w.kind === "intro" ? "intro" : w.kind === "finale" ? "finale" : `beat ${i + 1}`; - if (frames < 1 || frames / fps <= xIn + xOut) { + // 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"}`, @@ -350,6 +399,15 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = ...(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. @@ -384,7 +442,7 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = pieces.forEach((p, i) => { const over = i > 0 && !p.seamless ? x : 0; p.at = r3(acc - over); - acc = acc + p.frames.count / fps - over; + acc = acc + pieceFrames(p) / fps - over; }); // The same master seconds twice: the operator's call, but said. @@ -406,16 +464,25 @@ function pieceName(p, i) { 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. + * 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]; - if (p.seamless && last) last.count = p.frames.start + p.frames.count - last.start; + const run = p.seamless && last ? 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 }); + 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; } @@ -460,23 +527,31 @@ export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_D const d = (n / fps).toFixed(6); const seek = Math.max(0, a - PRE_ROLL); parts.push(`movie=filename=${src}:seek_point=${seek.toFixed(6)}:streams=dv+da:dec_threads=${threads}[m${i}v][m${i}a]`); - parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS[v${i}]`); + const cut = r.cuts?.length; + parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS[${cut ? `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}[a${i}]`, + `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: `[v${i}]`, aOut: `[a${i}]`, tag: `r${i}` }).parts); + } }); + const keptOf = (r) => (r.kept ?? r.count) / fps; let vlab = "[v0]"; let alab = "[a0]"; if (runs.length > 1 && x > 0) { - let acc = runs[0].count / fps; + 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 + runs[i].count / fps - x; + 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]`); @@ -724,8 +799,8 @@ export function describePlan(plan) { : p.kind === "raw" ? `${"(master)".padEnd(22)} at ${fmt(p.asked.at)} for ${fmt(p.asked.dur)}` : `${`(${p.kind})`.padEnd(22)}`; const span = `master ${clock(p.master.start)}–${clock(p.master.end)}`; - const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}`; - return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.master.duration)} s${marks}`; + const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}${p.cuts?.length ? ` (${p.cuts.length} gap${p.cuts.length === 1 ? "" : "s"} cut)` : ""}`; + return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.seconds ?? p.master.duration)} s${marks}`; }); lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces, crossfade ${fmt(plan.xfade)} s`); return lines;