Archilyzer · Source

archilyzer

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

commit 8f15cabfba387aa98e28c4415d4d7c35af4235aa
parent f72e3355a9f7c99b8842ff72702959fd0b2135f7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 30 Oct 2026 12:13:01 -0400

umtool: gaps inside a clip -- seconds cut out of its middle, one segment of jump cuts

A clip may carry `gaps: [{from, to}]` (source seconds, inside its cut, >= 0.2 s,
at most 12, 0.5 s of material kept between and at the edges). gaps.mjs is the
rule and both clocks; the writer (patchClipEntry: gaps / gapAdd / gapRemove,
an auto-before-gaps undo point), split/merge, the mark writers, `umtool check`
(clip-gap-invalid, blocking) and the build's validators share validateGaps.
A mute mark or claim mark inside a gap is refused (it names a second that
never plays; clamping would move a decision made by ear).

The build cuts the clip as ONE segment: trim + concat of the kept pieces on
the frame grid, a 25 ms fade out/in at each join; the cut record names the
gaps; every source->segment mapping reads them (mute/locked edges at the
join, stamps, deck claims, stats, fx words and punch-ins, captions, blur,
room's tail, the estimate's length, the trailer's beats -- which honour the
jump cut). No edge snaps across a gap. Absent or [] renders byte for byte.

Play the cut: the plan and its source<->cut mapping go through the gaps; a
gapped clip's sound is one span per kept piece with the join fades; the
cut-points route reports the gaps and the footage less them.

CLI: umtool window --gap A-B (repeatable) / --gap-remove S / --gaps 'A-B,..'|'';
umtool set gap.add= gap.remove= gaps=; timeline ls shows them.

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

Diffstat:
Mumtool/app/api/report/window/route.ts | 7+++++++
Mumtool/bin/umtool.mjs | 30++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 4+++-
Mumtool/components/projects/review/playEngine/engine.ts | 10++++++----
Mumtool/lib/inbox/groups.mjs | 1+
Mumtool/lib/inbox/what.mjs | 1+
Mumtool/lib/projects/report.mjs | 12++++++++++++
Mumtool/lib/report/cutPoints.mjs | 16+++++++++++++---
Aumtool/lib/report/gaps-writer.test.mjs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/knobsCli.mjs | 27++++++++++++++++++++++++++-
Mumtool/lib/report/liveClock.mjs | 18+++++++++++++-----
Mumtool/lib/report/manifest.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/playCut.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/lib/report/playSchedule.mjs | 44++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/report/playView.mjs | 2++
Mumtool/lib/report/timelineCli.mjs | 6+++++-
Mumtool/report-to-video/build-video.mjs | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/clip-blur.mjs | 11+++++++----
Mumtool/report-to-video/deck.mjs | 36+++++++++++++++++++++++++-----------
Mumtool/report-to-video/factcheck.mjs | 4+++-
Mumtool/report-to-video/fx.mjs | 18+++++++++++-------
Aumtool/report-to-video/gaps-render.test.mjs | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/gaps.mjs | 424+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/gaps.test.mjs | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/lint.mjs | 3+++
Mumtool/report-to-video/mute.mjs | 11++++++++---
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/snap.mjs | 38+++++++++++++++++++++++++++++---------
Mumtool/report-to-video/stats.mjs | 11+++++++----
Mumtool/report-to-video/trailer.mjs | 15++++++++++++++-
30 files changed, 1484 insertions(+), 99 deletions(-)

diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -59,6 +59,13 @@ export async function PUT(request: Request) { // plays on, in source seconds; empty or null clears it. Checked by the // writer against the clip's window, like the cut. "muteFrom", + // Seconds taken out of the clip's middle (gaps.mjs): the whole list + // (`gaps`, empty clears), one span added (`gapAdd`: {from, to} or + // "12.3-15.1"), or the gap holding a source second removed (`gapRemove`). + // Checked by the writer against the cut and the marks. + "gaps", + "gapAdd", + "gapRemove", // Whether the walk has looked at this clip: "confirmed", or empty to clear // it. A non-empty `correction` is the other answer and needs no value. "verdict", diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -23,6 +23,7 @@ // [--title T] [--date YYYY-MM-DD] [--cite S] [--cite-url U] [--quote Q] // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent +// [--gap FROM-TO]… [--gap-remove S] [--gaps 'A-B,C-D' | ''] seconds cut out of its middle // [--take <id>] a take's clip: the edit goes into the take's patch (walk a take) // umtool walk <project> [--take <id>] [--all] [--json] the walk: clips in walk order, verdicts, fetched // umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label, @@ -115,6 +116,7 @@ import path from "node:path"; import { updateArticleLink, updateClip, updateStorage } from "../lib/report/manifest.mjs"; import { withEditNotes } from "../lib/report/edit-guard.mjs"; import { hms } from "umtool-report-to-video/attribution"; +import { gappedLength, gapSpan, gapsOf, gapsText, parseGapSpec } from "umtool-report-to-video/gaps"; import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs"; import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs"; @@ -735,6 +737,9 @@ function usage() { " --correction TEXT what the REPORT got wrong here (never rendered)", " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --cut-start S --cut-end E --lock-cut the cut the video renders", + " --gap FROM-TO (repeatable) cut those source seconds out of the clip's middle: it plays", + " as ONE segment of jump cuts (gaps.mjs; inside the cut, ≥ 0.2 s, 0.5 s kept between);", + " --gap-remove S the gap holding source second S · --gaps 'A-B,C-D' the whole list ('' clears)", " an empty value (--title '') deletes the field", " --take <id> a take's clip (walk a take): the edit goes into takes/<id>/take.json's", " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched", @@ -999,6 +1004,23 @@ async function cmdWindow() { if (has(`--no-${flag.slice(2)}`)) patch[key] = false; } if (val("--note") !== undefined) patch.note = val("--note"); + // Gaps inside the clip (gaps.mjs): seconds taken out of its middle, so it + // renders as one segment of jump cuts. `--gap` adds one (repeatable), + // `--gap-remove S` takes out the gap holding S, `--gaps` sets the list + // ('' clears it). Applied by the writer to the list as it is now. + const gapAdds = argv.flatMap((a, i) => (a === "--gap" ? [argv[i + 1] ?? ""] : [])); + if (gapAdds.length) { + const bad = gapAdds.find((g) => !parseGapSpec(g)); + if (bad !== undefined) die(`--gap ${bad}: a gap is FROM-TO in source seconds, e.g. --gap 12.3-15.1`); + patch.gapAdd = gapAdds; + } + if (val("--gap-remove") !== undefined) patch.gapRemove = Number(val("--gap-remove")); + if (val("--gaps") !== undefined) { + const list = String(val("--gaps")).split(",").map((s) => s.trim()).filter(Boolean); + const parsed = list.map(parseGapSpec); + if (parsed.some((g) => !g)) die(`--gaps ${val("--gaps")}: a comma-separated list of FROM-TO in source seconds, or '' to clear`); + patch.gaps = parsed; + } // The attribution: what the burned-in header and the QR will say. An empty // value DELETES the field, the same rule the flags keep -- `--title ''` is how // you go back to the archived record's own title. @@ -1028,6 +1050,7 @@ async function cmdWindow() { if (json) return out({ ok: true, take, ...res }); console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`); if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`); + if (gapsText(res.entry)) console.log(` gaps: ${gapsText(res.entry)}`); if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${clipVerdict(res.entry)}`); if (res.entry.correction) console.log(` correction: ${res.entry.correction}`); console.log(` undo point: takes/${take}/${res.revision.rel} (umtool timeline ${p.id} --take ${take} undo)`); @@ -1056,6 +1079,13 @@ async function cmdWindow() { } else if (patch.cutStart !== undefined || patch.cutEnd !== undefined) { console.log(" cut cleared — the build will use the whole extent"); } + if (gapsText(res.entry)) { + const span = gapSpan(res.entry); + const g = gapsOf(res.entry); + console.log(` gaps: ${gapsText(res.entry)} — the cut plays ${gappedLength(span.from, span.to, g).toFixed(2)}s of ${(span.to - span.from).toFixed(2)}s, one segment of jump cuts`); + } else if (patch.gaps !== undefined || patch.gapRemove !== undefined) { + console.log(" no gaps — the cut plays whole"); + } const marks = ["lock", "lockStart", "lockEnd", "lockCut"].filter((k) => res.entry[k]); if (marks.length) console.log(` ${marks.join(", ")}`); // The line the renderer will burn in, printed so an attribution edit is diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -99,6 +99,8 @@ export type PlayEntry = { end?: number; cutStart?: number | null; cutEnd?: number | null; + /** Seconds taken out of its middle (gaps.mjs): one item of jump cuts. */ + gaps?: { from: number; to: number }[]; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; media?: (MediaRef & { from: number; to: number }) | null; /** Ruled incorrect by the walk: its correction (skipped unless "Show clips marked incorrect"). */ @@ -257,7 +259,7 @@ export default function PlayCut({ const segments = schedule?.segments ?? view.segments; const leadIn = doc?.leadIn ?? view.leadIn; // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change. - const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd])), [view.entries]); + const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd, e.gaps ?? null])), [view.entries]); const edges = useRenderCuts(project, take, edgesKey); // Clips ruled incorrect (the walk's verdict) are SKIPPED unless asked for: // the cut the operator means to ship does not hold them (umtool check diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -1,5 +1,5 @@ import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; -import { itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; +import { cutAtSource, itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; import { audioSpans, decodeSpanOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; import { drawFootageLayers, type FootageLayer } from "../footageCanvas"; import { AudioBank, type ClipSound } from "./audioBank"; @@ -180,7 +180,7 @@ export class PlayEngine { this.t = plan.items[same].from; } else if (it?.clip && same >= 0 && plan.items[same].clip) { const src = sourceAt(it, this.now()); - this.t = Math.max(plan.items[same].from, Math.min(plan.items[same].to - 0.001, plan.items[same].start + ((src ?? 0) - plan.items[same].clip!.sourceFrom))); + this.t = Math.max(plan.items[same].from, Math.min(plan.items[same].to - 0.001, cutAtSource(plan.items[same], src ?? 0))); } else this.t = Math.min(this.now(), Math.max(0, plan.total - 0.001)); } else this.t = Math.min(this.t, Math.max(0, plan.total - 0.001)); this.cur = Math.max(0, itemIndexAt(plan, this.t)); @@ -341,8 +341,10 @@ export class PlayEngine { private spanSound(id: string): { media: MediaRef; span: { from: number; to: number } } | null { const e = this.entries.get(id); - const s = this.spans.find((x) => x.id === id); - if (!e?.media || !s) return null; + // A clip with gaps is several spans (one per piece that plays): ONE decode covers them all. + const all = this.spans.filter((x) => x.id === id); + if (!e?.media || !all.length) return null; + const s = { src: Math.min(...all.map((x) => x.src)), srcTo: Math.max(...all.map((x) => x.srcTo)) }; return { media: e.media, span: decodeSpanOf(s) }; } diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -124,6 +124,7 @@ const ACTION_LABEL = { "clip-mid-sentence": "Trim to the sentence", "clip-cue-gap": "Fix the window", "clip-cut-outside": "Fix the cut", + "clip-gap-invalid": "Fix the gaps", "clip-incorrect": "Remove or fix the clip", "window-overlap": "Fix the windows", "no-punctuation": "Check the windows", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -29,6 +29,7 @@ export const WHAT = { "clip-mid-sentence": "clips end mid-sentence", "clip-cue-gap": "clips over a cue gap", "clip-cut-outside": "cuts outside the window", + "clip-gap-invalid": "gaps the build refuses", "clip-incorrect": "clips marked incorrect", "window-overlap": "windows overlap", "no-punctuation": "windows without punctuation", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -39,6 +39,7 @@ const segmentDirs = (outDir) => [ import { adjudicationGaps, ledgerTotals, unadjudicatedOf } from "umtool-report-to-video/ledger-totals"; import { widen } from "umtool-report-to-video/resolve-windows"; import { montageOn } from "umtool-report-to-video/montage"; +import { validateGaps } from "umtool-report-to-video/gaps"; import { fileSig, pathCache } from "../pathCache.mjs"; // widen() and the cache's window naming are IMPORTED, never reimplemented. The @@ -983,6 +984,11 @@ export const REPORT_DECISION_KINDS = [ // written -- silently ignore it and render the whole extent instead. Both // are the render disagreeing with the manifest about what the clip IS. "clip-cut-outside", + // A clip's `gaps` (seconds taken out of its middle, gaps.mjs) that the build + // refuses: outside the cut, overlapping, too short, too close together, or a + // mark inside one. BLOCKING for the same reason: the render would refuse the + // whole manifest, or cut seconds nobody chose. + "clip-gap-invalid", // A clip ruled `incorrect` (the walk's verdict, with its correction) that is // still in the timeline. BLOCKING: the build would render it, the counter // would count its marks, and the video would cite a clip somebody already @@ -1278,6 +1284,12 @@ export async function reportDecisions(ctx, summary) { } } + // GAPS INSIDE A CLIP keep the build's rule (gaps.mjs validateGaps): inside + // the cut, in order, apart, and no mark in one. + for (const e of clips) { + for (const why of validateGaps(e, e.id)) add("clip-gap-invalid", e.id, why, "blocking", { href: clipHref(e.id) }); + } + // A clip with no numeric window cannot be built, widened or benched. The // scaffold's `--seed chapters` writes one when the last chapter has no // duration to end at, and says so; this is where it stays visible. diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -36,6 +36,7 @@ import { loudnessGain, montageOn, parseIntegratedLoudness } from "umtool-report- import { loudnessTargetOf } from "umtool-report-to-video/look"; import { ROOM, clipRoom } from "umtool-report-to-video/room"; import { lockedEdges, soundOnSegment } from "umtool-report-to-video/mute"; +import { gapSeconds, gapsOnSegment, renderGaps } from "umtool-report-to-video/gaps"; import { renderCut, snapKnobs } from "umtool-report-to-video/snap"; import { transitionStyleOf } from "umtool-report-to-video/transition"; import { CACHE_DIR } from "../paths.mjs"; @@ -130,6 +131,9 @@ async function cutContext(project, take) { * snapped { start, end }: which edge moved to a silence * sound [from, to] the sound is heard over, when room mutes * an edge (else the whole segment) + * gaps [{from, to}] the seconds its segment leaves out + * (gaps.mjs; the build's frame-grid edges), absent + * without any -- `footage` is already less them * gainDb render.loudness's gain for the cut (none: absent) * audio the clip's own audio knobs (clip-audio.mjs), absent when none * playFrom / playTo the play window it was snapped from (deck.mjs playWindow) @@ -198,7 +202,9 @@ async function clipCutPoints(entry, ctx) { ); const pw = playWindow(entry, render); const locked = lockedEdges(entry, render); - const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked }); + // A clip's gaps (gaps.mjs): no edge snaps across one, as in the build. None in a montage. + const clipGaps = montage ? [] : renderGaps(entry, render); + const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}) }); const { cutA, cutB } = cut.file; let segA = cutA; let segB = cutB; @@ -228,10 +234,13 @@ async function clipCutPoints(entry, ctx) { // begun counted (the build's cutOffsets sums the probed frames; measured on // the Huck walk, 34 of 51 segments exactly this, the rest one frame more). const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30; + // The gaps as the build applies them: on the segment's frame grid (build-video.mjs buildClipSegment). + const segGaps = clipGaps.length ? gapsOnSegment(clipGaps, fetchStart + segA, segB - segA, fps) : []; + const gaps = segGaps.map((g) => ({ from: r3(fetchStart + segA + g.from), to: r3(fetchStart + segA + g.to) })); const row = { id: entry.id, window: path.basename(src.path), - footage: Number((Math.ceil((segB - segA) * fps - 1e-6) / fps).toFixed(6)), + footage: Number((Math.ceil((segB - segA - gapSeconds(segGaps)) * fps - 1e-6) / fps).toFixed(6)), fetchStart: r3(fetchStart), silences: sil, playFrom: pw.from, @@ -242,6 +251,7 @@ async function clipCutPoints(entry, ctx) { // Which edges are the author's (mute.mjs lockedEdges): the bench snaps a dragged edge with them. ...(locked.start || locked.end ? { locked } : {}), ...(sound ? { sound } : {}), + ...(gaps.length ? { gaps } : {}), ...(montage ? { montage: true } : {}), }; const target = loudnessTargetOf(render); @@ -258,7 +268,7 @@ async function clipCutPoints(entry, ctx) { // Where the sound is heard (mute.mjs soundOnSegment, the build's join rule): // the mute mark (a finale's ending sound), or a locked end the segment // reaches past -- silent from it -- and a locked start it reaches before. - const on = soundOnSegment(entry, render, row.cutStart, row.footage); + const on = soundOnSegment(entry, render, row.cutStart, row.footage, gaps.length ? gaps : null); if (on.mute != null && on.edges.muteFrom != null) row.muteFrom = on.edges.muteFrom; if (on.soundFrom != null && on.edges.soundFrom != null) row.soundFrom = on.edges.soundFrom; return row; diff --git a/umtool/lib/report/gaps-writer.test.mjs b/umtool/lib/report/gaps-writer.test.mjs @@ -0,0 +1,154 @@ +// Gaps inside a clip, written (umtool-report-to-video gaps.mjs; the one writer, +// manifest.mjs patchClipEntry): `gaps` / `gapAdd` / `gapRemove` through +// updateClip, checked against the entry after the patch -- a window, cut or +// mark save that leaves a gap outside, or a mark in one, is refused and the +// file is left as it was; an undo point first; split and merge carry them; +// `umtool set gap.add=…`; `umtool check`'s clip-gap-invalid row. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-gaps-writer-")); +process.env.REPORTS_DIR = ROOT; +const { MANIFEST_NAME, mergeClips, splitClip, updateClip, updateMarks } = await import("./manifest.mjs"); +const { setCommand } = await import("./knobsCli.mjs"); +const { timelineLines, timelineRows } = await import("./timelineCli.mjs"); + +const MANIFEST = { + schemaVersion: 1, + slug: "gaps", + title: "Gaps", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 30, cutStart: 12, cutEnd: 28 }, + { type: "clip", id: "c02", video: "v1", start: 30, end: 40 }, + ], +}; + +let n = 0; +async function project(manifest = MANIFEST) { + const dir = path.join(ROOT, `p${(n += 1)}`); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return dir; +} +const raw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8"); +const read = async (dir) => JSON.parse(await raw(dir)); +const clip = async (dir, id) => (await read(dir)).timeline.find((e) => e.id === id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("updateClip: gapAdd (a span or a list), merged with a gap it touches; gapRemove by a second inside; gaps sets, [] or '' clears", async () => { + const dir = await project(); + let r = await updateClip(dir, "c01", { gapAdd: "15.004-17.333" }); + assert.deepEqual(r.entry.gaps, [{ from: 15, to: 17.33 }]); + r = await updateClip(dir, "c01", { gapAdd: [{ from: 20, to: 21 }, "17-17.6"] }); + assert.deepEqual(r.entry.gaps, [{ from: 15, to: 17.6 }, { from: 20, to: 21 }]); + r = await updateClip(dir, "c01", { gapRemove: 16 }); + assert.deepEqual(r.entry.gaps, [{ from: 20, to: 21 }]); + r = await updateClip(dir, "c01", { gaps: [{ from: 22, to: 23 }, { from: 14, to: 14.5 }] }); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 14, to: 14.5 }, { from: 22, to: 23 }], "sorted on write"); + await updateClip(dir, "c01", { gaps: [] }); + assert.equal("gaps" in (await clip(dir, "c01")), false, "an empty list removes the key"); + await updateClip(dir, "c01", { gapAdd: "15-16" }); + await updateClip(dir, "c01", { gaps: "" }); + assert.equal("gaps" in (await clip(dir, "c01")), false); + // Removing the last gap removes the key too. + await updateClip(dir, "c01", { gapAdd: "15-16" }); + await updateClip(dir, "c01", { gapRemove: 15.5 }); + assert.equal("gaps" in (await clip(dir, "c01")), false); +}); + +test("updateClip: a gap the build would refuse is refused, and the file is left byte for byte", async () => { + const dir = await project(); + await updateClip(dir, "c01", { gapAdd: "15-17" }); + const before = await raw(dir); + const refuses = async (patch, re) => { + await assert.rejects(updateClip(dir, "c01", patch), re); + assert.equal(await raw(dir), before, `${JSON.stringify(patch)} left the file as it was`); + }; + await refuses({ gapAdd: "11-13" }, /outside the clip's cut 12–28/); + await refuses({ gapAdd: "12.2-13" }, /after the cut's start; keep at least 0.5 s/); + await refuses({ gapAdd: "20-20.1" }, /under 0.2 s/); + await refuses({ gapAdd: "17.2-18" }, /merge|keep at least/); + await refuses({ gapAdd: "nonsense" }, /a gap is FROM-TO/); + await refuses({ gapRemove: 25 }, /no gap at 25/); + await refuses({ gaps: "15-17" }, /must be a list/); + // A cut save that leaves the gap outside (or too close to the new edge). + await refuses({ cutStart: 16, cutEnd: 28 }, /outside the clip's cut 16–28/); + await refuses({ cutStart: 14.8 }, /after the cut's start/); + // A mute mark inside the gap. + await refuses({ muteFrom: 16 }, /muteFrom 16 lies inside the gap 15–17, which never plays/); + // On its edge it is fine. + const r = await updateClip(dir, "c01", { muteFrom: 17 }); + assert.equal(r.entry.muteFrom, 17); +}); + +test("updateClip: a gap edit leaves an undo point (auto-before-gaps); another edit does not", async () => { + const dir = await project(); + await updateClip(dir, "c01", { title: "x" }); + const has = async () => (await readdir(path.join(dir, "revisions")).catch(() => [])).some((f) => f.includes("auto-before-gaps")); + assert.equal(await has(), false); + const r = await updateClip(dir, "c01", { gapAdd: "15-17" }); + assert.equal(await has(), true); + assert.ok(r.snapshot, "the answer names it"); +}); + +test("updateMarks: a mark's second inside a gap is refused", async () => { + const dir = await project(); + await updateClip(dir, "c01", { gapAdd: "15-17" }); + const before = await raw(dir); + await assert.rejects(updateMarks(dir, "c01", { add: { verdict: "CONTRADICTED", at: 16 } }), /lies inside the gap 15–17, which never plays.* nothing was written/); + assert.equal(await raw(dir), before); + const r = await updateMarks(dir, "c01", { add: { verdict: "CONTRADICTED", at: 18 } }); + assert.equal(r.marks.length, 1); +}); + +test("splitClip: each half keeps the gaps on its side; a split inside a gap is refused; merge joins them", async () => { + const dir = await project(); + await updateClip(dir, "c01", { gapAdd: ["14-15", "24-25"] }); + await assert.rejects(splitClip(dir, "c01", 14.5), /inside the gap 14–15/); + const s = await splitClip(dir, "c01", 20); + const a = await clip(dir, "c01"); + const b = await clip(dir, s.second); + assert.deepEqual(a.gaps, [{ from: 14, to: 15 }]); + assert.deepEqual(b.gaps, [{ from: 24, to: 25 }]); + // Too close to the new edge: refused, by the gap rule. + const dir2 = await project(); + await updateClip(dir2, "c01", { gapAdd: "18-19.8" }); + await assert.rejects(splitClip(dir2, "c01", 20), /split at 20: .*keep at least 0.5 s/); + // Merge back: both lists, in order. + await mergeClips(dir, "c01"); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 14, to: 15 }, { from: 24, to: 25 }]); +}); + +test("umtool set: gap.add=, gap.remove=, gaps= (a list, JSON, or empty); timeline ls shows them", async () => { + const dir = await project(); + const lines = []; + const run = (...args) => setCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }); + const name = path.basename(dir); + assert.equal(await run(name, "c01", "gap.add=15-17", "gap.add=20-21"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 15, to: 17 }, { from: 20, to: 21 }]); + assert.match(lines.at(-1), /c01: gaps 15–17, 20–21/); + assert.equal(await run(name, "c01", "gap.remove=20.5"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 15, to: 17 }]); + const rows = timelineRows(await read(dir)); + assert.deepEqual(rows[0].gaps, [{ from: 15, to: 17 }]); + assert.equal(rows[0].plays, 14); + assert.match(timelineLines(rows)[0], /gaps −15\.00–17\.00 \(plays 14\.00s\)/); + assert.equal(await run(name, "c01", "gaps=13-14,22-23"), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 13, to: 14 }, { from: 22, to: 23 }]); + assert.equal(await run(name, "c01", 'gaps=[{"from":18,"to":19}]'), 0); + assert.deepEqual((await clip(dir, "c01")).gaps, [{ from: 18, to: 19 }]); + assert.equal(await run(name, "c01", "gaps="), 0); + assert.equal("gaps" in (await clip(dir, "c01")), false); + assert.match(lines.at(-1), /no gaps/); + assert.equal(await run(name, "c01", "gaps=12-zz"), 2); + assert.equal(await run(name, "c01", "gap.add=11-12.5"), 1); + assert.match(lines.at(-1), /^ERR .*outside the clip's cut/); +}); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -39,13 +39,19 @@ import { import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, rawMarksOf, stampingEntryId, variantsOf } from "./knobs.mjs"; import { variantsSteps } from "./driver.mjs"; import { buildFileOf, outDirOf, variantsState } from "./variantsView.mjs"; +import { parseGapSpec } from "umtool-report-to-video/gaps"; export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]); export const BLUR_KNOBS = Object.freeze(["on", "caption", "strength", "from", "to"]); const MARK_KEYS = ["marks", "mark.add", "mark.remove", "mark.verdict"]; /** The walk's verdict, set like a knob: verdict=confirmed|incorrect|wrong-speaker, reason=wrong-speaker, correction=… (`key=` clears). */ const REVIEW_KEYS = ["verdict", "reason", "correction"]; -const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS]; +/** Seconds taken out of the clip's middle (gaps.mjs): the whole list, one added, one removed. */ +const GAP_KEYS = ["gaps", "gap.add", "gap.remove"]; +const SET_KEYS = [ + ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, + ...GAP_KEYS, +]; export const SET_USAGE = [ "usage: umtool set <project> <clip> key=value … [--mark <id>] [--json]", @@ -69,6 +75,9 @@ export const SET_USAGE = [ " seconds inside the clip's window, to blur only that span. render.blur=off (umtool look, or a take's", " --set) renders every clip unblurred: the uncensored variant. layout=finale|clip (the deck's finale", " layout for this clip; clip is the default). `key=` clears it (the default).", + " gap.add=12.3-15.1 cuts those source seconds out of the clip's middle (one segment of jump cuts; inside", + " the cut, ≥ 0.2 s, 0.5 s kept between); gap.remove=<sec> the gap holding it; gaps=12.3-15.1,20-20.6 (or", + " a JSON list of {from,to}) the whole list, `gaps=` none. The same as `umtool window --gap/--gap-remove/--gaps`.", ].join("\n"); export const LOOK_USAGE = [ @@ -172,6 +181,18 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso entryPatch[key] = value === null || value === undefined ? "" : String(value); continue; } + if (GAP_KEYS.includes(key)) { + if (key === "gap.add") (entryPatch.gapAdd ??= []).push(String(value ?? "")); + else if (key === "gap.remove") entryPatch.gapRemove = Number(value); + else if (value === null || (Array.isArray(value) && !value.length)) entryPatch.gaps = []; + else if (Array.isArray(value)) entryPatch.gaps = value; + else { + const list = String(value).split(",").map((s) => s.trim()).filter(Boolean).map(parseGapSpec); + if (list.some((g) => !g)) throw new CliError(`gaps=${value}: a comma-separated list of FROM-TO in source seconds, or a JSON list of {from,to}`); + entryPatch.gaps = list; + } + continue; + } if (MARK_KEYS.includes(key)) { markChanges.push(markChangeOf(key, value, mark)); continue; @@ -207,6 +228,9 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("audio" in entryPatch) results.audio = result.entry.audio ?? null; if ("blur" in entryPatch) results.blur = result.entry.blur ?? null; if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip"; + if ("gaps" in entryPatch || "gapAdd" in entryPatch || "gapRemove" in entryPatch) { + results.gaps = result.entry.gaps ?? []; + } if (REVIEW_KEYS.some((k) => k in entryPatch)) { results.review = { verdict: result.entry.verdict ?? null, reason: result.entry.reason ?? null, correction: result.entry.correction ?? null }; } @@ -227,6 +251,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("audio" in results) out(`${clipId}: audio ${results.audio ? JSON.stringify(results.audio) : "as recorded"}`); if ("blur" in results) out(`${clipId}: blur ${results.blur ? JSON.stringify(results.blur) : "none (the picture as recorded)"}`); if ("layout" in results) out(`${clipId}: layout ${results.layout}`); + if ("gaps" in results) out(`${clipId}: ${results.gaps.length ? `gaps ${results.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps (the cut plays whole)"}`); if (results.review) { const r = results.review; out(`${clipId}: ${r.verdict ?? "not reviewed"}${r.reason ? ` (${r.reason})` : ""}${r.correction ? ` — ${r.correction}` : ""}`); diff --git a/umtool/lib/report/liveClock.mjs b/umtool/lib/report/liveClock.mjs @@ -13,8 +13,14 @@ // does that this does not: it snaps each edge to a nearby silence (up to // `render.snapWindow`), so the deck's handover at a join can land that much // off; the preview says so. +// +// A clip's GAPS (gaps.mjs: source seconds its segment leaves out) are on the +// clock too: the footage is the kept seconds, a source second after a gap +// plays that much earlier, and one inside a gap plays at its join. + +import { gappedLength, gapsWithin, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps"; -/** @typedef {{ start: number, end: number, cutStart?: number | null, cutEnd?: number | null }} ClipSpan */ +/** @typedef {{ start: number, end: number, cutStart?: number | null, cutEnd?: number | null, gaps?: Array<{ from: number, to: number }> | null }} ClipSpan */ /** @typedef {{ id: string, start: number, duration: number, end?: number, hold?: number }} Segment */ /** * @typedef {{ claim: string, verdict: string, segment: string, at: number, landed: number, @@ -59,7 +65,8 @@ export function liveClock(schedule, clip, { leadIn = 0.4 } = {}) { const seg = schedule.segments[i]; const pw = livePlayWindow(clip, leadIn); const hold = fin(seg.hold) && /** @type {number} */ (seg.hold) > 0 ? /** @type {number} */ (seg.hold) : 0; - const playEnd = seg.start + Math.max(0, pw.to - pw.from); + const gaps = gapsWithin(Array.isArray(clip.gaps) ? clip.gaps : [], pw.from, pw.to); + const playEnd = seg.start + Math.max(0, gappedLength(pw.from, pw.to, gaps)); return { id: clip.id, index: i, @@ -70,6 +77,7 @@ export function liveClock(schedule, clip, { leadIn = 0.4 } = {}) { playEnd: round(playEnd), hold, end: round(playEnd + hold), + ...(gaps.length ? { gaps } : {}), }; } @@ -88,7 +96,7 @@ export function cutTimeAt(clock, sourceT) { if (!clock || !fin(sourceT)) return { t: clock?.start ?? 0, where: "before" }; if (sourceT < clock.sourceFrom) return { t: clock.start, where: "before" }; if (sourceT > clock.sourceTo) return { t: clock.playEnd, where: "after" }; - return { t: round(clock.start + (sourceT - clock.sourceFrom)), where: "inside" }; + return { t: round(clock.start + offsetIn(sourceT, clock.sourceFrom, clock.gaps)), where: "inside" }; } /** @@ -100,7 +108,7 @@ export function cutTimeAt(clock, sourceT) { */ export function sourceTimeAt(clock, t) { if (!clock || !fin(t) || t < clock.start || t > clock.playEnd) return null; - return round(clock.sourceFrom + (t - clock.start)); + return round(sourceAtOffset(t - clock.start, clock.sourceFrom, clock.gaps)); } /** @@ -164,7 +172,7 @@ export function clipStamps(schedule, clock) { verdict: s.verdict, drawn: s.stamp !== false && !s.finale, landed: s.landed, - sourceLanded: round(clock.sourceFrom + (s.landed - clock.start)), + sourceLanded: round(sourceAtOffset(s.landed - clock.start, clock.sourceFrom, clock.gaps)), })); } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -47,6 +47,7 @@ import { storyClipErrors } from "umtool-report-to-video/modules/story-settings"; import { counterOrder } from "umtool-report-to-video/counter"; import { validateFinaleEntries } from "umtool-report-to-video/finale"; import { validateClipAudio } from "umtool-report-to-video/clip-audio"; +import { editGaps, parseGapSpec, validateGaps } from "umtool-report-to-video/gaps"; import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH, validateClipBlur, validateClipBlurEntries } from "umtool-report-to-video/clip-blur"; import { CLAIM_KNOBS, CLAIM_MARKS_MAX, claimKnobsOf, claimKnobValue, freshMarkId, marksCopyOf, normalizeClaimKnobPatch, rawMarksOf, setMarks, stampingEntryId, @@ -189,7 +190,7 @@ const WIN_EPS = 0.02; * @param {string} clipId * @param {Record<string, unknown>} patch * @param {{ token?: string | null }} [opts] - * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null }>} + * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null, snapshot?: Record<string, unknown> }>} */ export async function updateClip(dir, clipId, patch, { token = null, edit = "trim", now = null } = {}) { return withManifestLock(async () => { @@ -200,13 +201,19 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri const raw = await readFile(manifestFile(dir), "utf8"); const manifest = JSON.parse(raw); const { entry, before } = patchClipEntry(manifest, clipId, patch, { edit, now, raw }); + // A gap cut or removed (gaps.mjs) changes what the clip IS in the cut, as a + // split does: an undo point first (`umtool timeline <p> undo`, the Cut tab's Undo). + const snapshot = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) ? await autoSnapshot(dir, "gaps") : null; const nextToken = await writeManifestAtomic(dir, manifest); // A moved extent may need a new bench excerpt: queued, never waited for. if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]); - return { entry, before, token: nextToken }; + return { entry, before, token: nextToken, ...(snapshot ? { snapshot } : {}) }; }); } +/** The patch keys that edit a clip's gaps (patchClipEntry, "gaps inside the clip"). */ +export const GAP_PATCH_KEYS = Object.freeze(["gaps", "gapAdd", "gapRemove"]); + /** * updateClip's rules over a manifest held in memory: the ONE place a clip * patch is checked and applied. updateClip runs it on the project's file @@ -404,6 +411,52 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n }); } + // ---- gaps inside the clip (gaps.mjs) ------------------------------------- + // + // `gaps: [{from, to}]` -- source seconds taken out of the middle of the cut; + // the clip then renders as ONE segment of jump cuts. Three ways to write + // them, all applied to the list as it is NOW (inside the lock): `gaps` the + // whole list (null, "" or [] clears it), `gapAdd` a span (`{from, to}` or + // "12.3-15.1", or a list of them; merged with a gap it touches), `gapRemove` + // the gap holding a source second. Then the rule (validateGaps, the build's own check) on the + // entry AFTER the patch, as for the mute mark: a window, cut or mark save + // that leaves a gap outside the cut, or a mark inside a gap, is refused. + if (patch.gaps !== undefined || patch.gapAdd !== undefined || patch.gapRemove !== undefined) { + let list = Array.isArray(entry.gaps) ? entry.gaps : []; + if (patch.gaps !== undefined) { + const v = patch.gaps; + if (v === null || v === "") list = []; + else if (!Array.isArray(v)) throw new Error("gaps must be a list of { from, to } in source seconds, or empty to clear them"); + else { + list = editGaps([], { + set: v.map((g, k) => { + const from = Number(g?.from); + const to = Number(g?.to); + if (!Number.isFinite(from) || !Number.isFinite(to)) throw new Error(`gaps[${k}] must be { from, to } in source seconds`); + return { from, to }; + }), + }); + } + } + if (patch.gapAdd !== undefined) { + for (const one of Array.isArray(patch.gapAdd) ? patch.gapAdd : [patch.gapAdd]) { + const g = typeof one === "string" ? parseGapSpec(one) : one; + if (!isObj(g)) throw new Error(`a gap is FROM-TO in source seconds, e.g. 12.3-15.1 (got ${JSON.stringify(one)})`); + list = editGaps(list, { add: { from: Number(g.from), to: Number(g.to) } }); + } + } + if (patch.gapRemove !== undefined) list = editGaps(list, { remove: Number(patch.gapRemove) }); + if (list.length) entry.gaps = list; + else delete entry.gaps; + } + if ( + entry.gaps !== undefined && + ["start", "end", "cutStart", "cutEnd", "muteFrom", "gaps", "gapAdd", "gapRemove"].some((k) => patch[k] !== undefined) + ) { + const errors = validateGaps(entry, clipId); + if (errors.length) throw new Error(errors.join("; ")); + } + // ---- the clip's sound (video knobs) ------------------------------------- // // `audio: { offset, gain, fadeIn, fadeOut }` -- applied at the segment @@ -685,6 +738,11 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no const from = cutOf(e); const hasCut = e.cutStart != null && e.cutEnd != null; const b = JSON.parse(JSON.stringify(e)); + // Gaps go with the half they are in; a split inside one is refused (the + // second it names never plays -- split at the gap's edge instead). + const gaps = Array.isArray(e.gaps) ? e.gaps : []; + const across = gaps.find((g) => t > g.from && t < g.to); + if (across) throw new Error(`${t} is inside the gap ${across.from}–${across.to}, which never plays — split at its edge`); // The first half: up to the split. e.end = t; if (hasCut) e.cutEnd = t; @@ -700,6 +758,16 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom; delete b.claim; delete b.claims; + const ga = gaps.filter((g) => g.to <= t); + const gb = gaps.filter((g) => g.from >= t); + if (ga.length) e.gaps = ga; + else delete e.gaps; + if (gb.length) b.gaps = gb; + else delete b.gaps; + for (const x of [e, b]) { + const errors = validateGaps(x, x.id); + if (errors.length) throw new Error(`split at ${t}: ${errors.join("; ")}`); + } const qb = textOr(quotes.second, b.quote ?? null); if (qb) b.quote = qb; else delete b.quote; @@ -747,6 +815,14 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null } if (e.muteFrom != null) delete e.muteFrom; if (b.muteFrom != null) e.muteFrom = b.muteFrom; + // Both clips' gaps, in order: the seconds between them now play. + const gaps = [...(Array.isArray(e.gaps) ? e.gaps : []), ...(Array.isArray(b.gaps) ? b.gaps : [])].sort((x, y) => x.from - y.from); + if (gaps.length) e.gaps = gaps; + else delete e.gaps; + { + const errors = validateGaps(e, e.id); + if (errors.length) throw new Error(`merge ${clipId} + ${b.id}: ${errors.join("; ")}`); + } const q = quote !== undefined ? textOr(quote, null) : [e.quote, b.quote].filter((x) => typeof x === "string" && x.trim()).join(" ") || null; if (q) e.quote = q; else delete e.quote; @@ -2224,6 +2300,11 @@ export async function updateClaimKnobs(dir, entryId, patch, { token = null, mark // The renderer's own check -- each knob, `at` inside the entry's window, no two stamps over each other -- on this entry's rows. const bad = validateClaims(manifest).filter((e) => e.includes(`(${entryId})`)); if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + // A mark's second inside one of the clip's gaps never plays (gaps.mjs). + for (const e of entries) { + const g = validateGaps(e, entryId); + if (g.length) throw new Error(`${g.join("; ")} — nothing was written`); + } const nextToken = await writeManifestAtomic(dir, manifest); const claim = pick(entries[0]); const stampsOn = stampingEntryId(manifest, claim.id); @@ -2319,6 +2400,10 @@ export async function updateMarks(dir, entryId, change, { token = null } = {}) { // The renderer's own check: refused when this change adds a problem. const bad = validateClaims(manifest).filter((x) => !before.has(x)); if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + for (const e of entries) { + const g = validateGaps(e, entryId); + if (g.length) throw new Error(`${g.join("; ")} — nothing was written`); + } const nextToken = await writeManifestAtomic(dir, manifest); const stored = marksCopyOf(entries[0]); return { diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -15,6 +15,15 @@ // clip's hold) its last frame holds. import { clockText, livePlayWindow } from "./liveClock.mjs"; +import { gappedLength, gapsOf, gapsWithin, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps"; + +// GAPS INSIDE A CLIP (umtool-report-to-video gaps.mjs): a clip's `gaps` are +// source seconds its segment leaves out, so it plays as one item of jump cuts. +// An item's `clip.gaps` (only when it has any) are those inside its play +// window -- the render's (the cut-points route's `gaps`, on the frame grid) +// with its edges, else the manifest's -- and every cut ↔ source mapping below +// goes through them: the footage is the kept seconds, and a second inside a +// gap plays at its join. // THE RENDER'S EDGES (`cuts`, lib/report/cutPoints.mjs): the build snaps every // clip edge to a silence, so the clip it renders is longer or shorter than @@ -34,7 +43,7 @@ import { clockText, livePlayWindow } from "./liveClock.mjs"; * id: string, index: number, type: string, * start: number, end: number, the segment, in the cut's seconds * from: number, to: number, what the page shows of it: midpoint to midpoint - * clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number }, + * clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number, gaps?: Array<{ from: number, to: number }> }, * est?: { start: number, end: number, from: number, to: number, sourceFrom?: number, sourceTo?: number, playEnd?: number }, * with the render's edges: the item on the estimate's clock * }} PlayItem @@ -45,7 +54,8 @@ const round = (v) => Math.round(v * 1000) / 1000; /** * @typedef {{ cutStart: number, cutEnd: number, footage?: number, snapped?: { start: boolean, end: boolean }, - * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number }} RenderCut + * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number, + * gaps?: Array<{ from: number, to: number }> }} RenderCut */ /** @@ -69,16 +79,15 @@ export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) const before = shift; const c = it.clip ? cutOf(it.id) : null; const ok = !!c && fin(c.cutStart) && fin(c.cutEnd) && c.cutEnd > c.cutStart; - const estAt = { - start: it.start, end: it.end, from: it.from, to: it.to, - ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), - }; + const estAt = estOf(it); if (!ok) { return { ...it, start: round(it.start + before), end: round(it.end + before), from: round(it.from + before), to: round(it.to + before), clip: it.clip ? { ...it.clip, playEnd: round(it.clip.playEnd + before) } : null, est: estAt }; } - // Its length in the cut: the encode's whole frames when the route said (`footage`), else the span. - const foot = fin(c.footage) && /** @type {number} */ (c.footage) > 0 ? /** @type {number} */ (c.footage) : c.cutEnd - c.cutStart; + // Its gaps as the render takes them out (the route's), else none. + const gaps = Array.isArray(c.gaps) ? gapsWithin(c.gaps, c.cutStart, c.cutEnd) : []; + // Its length in the cut: the encode's whole frames when the route said (`footage`), else the span (less its gaps). + const foot = fin(c.footage) && /** @type {number} */ (c.footage) > 0 ? /** @type {number} */ (c.footage) : gappedLength(c.cutStart, c.cutEnd, gaps); // The estimate's segment is its footage (at least a second) and its hold; the render's, its cut and the same hold. const delta = foot + it.clip.hold - (it.end - it.start); shift += delta; @@ -97,6 +106,7 @@ export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) ...(c.snapped ? { snapped: c.snapped } : {}), ...(fin(c.muteFrom) ? { muteFrom: c.muteFrom } : {}), ...(fin(c.soundFrom) ? { soundFrom: c.soundFrom } : {}), + ...(gaps.length ? { gaps } : {}), }, est: estAt, }; @@ -123,7 +133,7 @@ export function chromeTime(plan, t) { if (it.clip && fin(e.sourceFrom)) { if (t > it.clip.playEnd) return clampTo(e.playEnd + (t - it.clip.playEnd), e.from, e.to); const src = /** @type {number} */ (sourceAt(it, t)); - return clampTo(e.start + (src - e.sourceFrom), e.from, it.clip.hold > 0 ? e.playEnd : e.to); + return clampTo(e.start + offsetIn(src, e.sourceFrom, e.gaps), e.from, it.clip.hold > 0 ? e.playEnd : e.to); } return clampTo(e.from + (t - it.from), e.from, e.to); } @@ -150,7 +160,7 @@ export function playTimeOfChrome(plan, tc) { const clampTo = (v) => round(Math.min(it.to, Math.max(it.from, v))); if (it.clip && fin(e.sourceFrom)) { if (tc > e.playEnd) return clampTo(it.clip.playEnd + (tc - e.playEnd)); - return clampTo(cutAtSource(it, e.sourceFrom + (tc - e.start))); + return clampTo(cutAtSource(it, sourceAtOffset(tc - e.start, e.sourceFrom, e.gaps))); } return clampTo(it.from + (tc - e.from)); } @@ -184,10 +194,7 @@ export function skipEntries(plan, ids) { shift += Math.max(0, it.to - it.from); continue; } - const est = it.est ?? { - start: it.start, end: it.end, from: it.from, to: it.to, - ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), - }; + const est = it.est ?? estOf(it); const s = (v) => round(v - shift); items.push({ ...it, @@ -203,6 +210,15 @@ export function skipEntries(plan, ids) { return { ...plan, items, total: items.length ? items[items.length - 1].end : 0, skipped }; } +/** An item's place on the estimate's clock (`est`), its gaps with it when it has any. */ +function estOf(it) { + return { + start: it.start, end: it.end, from: it.from, to: it.to, + ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), + ...(it.clip?.gaps ? { gaps: it.clip.gaps } : {}), + }; +} + /** The plan on the estimate's clock alone (playPlan without the render's edges). */ function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) { const byId = new Map((entries ?? []).map((e) => [e?.id, e])); @@ -219,7 +235,11 @@ function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) { if (e?.type === "clip" && fin(e.start) && fin(e.end)) { const pw = livePlayWindow(/** @type {any} */ (e), leadIn); const hold = fin(s.hold) && /** @type {number} */ (s.hold) > 0 ? /** @type {number} */ (s.hold) : 0; - clip = { sourceFrom: pw.from, sourceTo: pw.to, playEnd: round(s.start + Math.max(0, pw.to - pw.from)), hold }; + const gaps = gapsWithin(gapsOf(e), pw.from, pw.to); + clip = { + sourceFrom: pw.from, sourceTo: pw.to, playEnd: round(s.start + Math.max(0, gappedLength(pw.from, pw.to, gaps))), hold, + ...(gaps.length ? { gaps } : {}), + }; } return { id: s.id, index: i, type: String(e?.type ?? "entry"), start: round(s.start), end: round(end), from: round(from), to: round(to), clip }; }); @@ -247,13 +267,27 @@ export function itemIndexAt(plan, t) { export function sourceAt(item, t) { if (!item?.clip || !fin(t)) return null; const c = item.clip; - return round(Math.min(c.sourceTo, Math.max(c.sourceFrom, c.sourceFrom + (t - item.start)))); + return round(Math.min(c.sourceTo, Math.max(c.sourceFrom, sourceAtOffset(t - item.start, c.sourceFrom, c.gaps)))); } -/** The cut second a clip item's source second plays at (the inverse inside its footage). */ +/** The cut second a clip item's source second plays at (the inverse inside its footage; inside a gap, its join). */ export function cutAtSource(item, src) { if (!item?.clip || !fin(src)) return item?.start ?? 0; - return round(item.start + (src - item.clip.sourceFrom)); + return round(item.start + offsetIn(src, item.clip.sourceFrom, item.clip.gaps)); +} + +/** + * Where a clip item's gaps fall on the cut's clock: one cut second per gap + * (its join), with the source span it leaves out -- the strip's tick and the + * readout's "jump". [] without gaps. + * + * @param {PlayItem} item + * @returns {Array<{ at: number, from: number, to: number }>} + */ +export function gapJoins(item) { + const c = item?.clip; + if (!c?.gaps?.length) return []; + return c.gaps.map((g) => ({ at: cutAtSource(item, g.from), from: g.from, to: g.to })); } /** Is cut second t past the clip's footage, in its hold (its last frame shown)? */ diff --git a/umtool/lib/report/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs @@ -18,6 +18,7 @@ // (cut seconds divided by the speed). import { MUTE_FADE } from "umtool-report-to-video/mute"; +import { GAP_FADE, gappedLength, keptSpans, offsetIn } from "umtool-report-to-video/gaps"; import { ROOM } from "yt-dlp-transcript-common/lib/report/look.mjs"; /** Room's afade at a muted edge (the build's roomAudioFilter): the look's own number. */ @@ -73,9 +74,15 @@ const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : * gain a constant multiplier: the loudness gain and the clip's * own `audio.gain`, in dB, as amplitude * + * A clip with GAPS (`clip.gaps`, gaps.mjs) is several spans, one per piece + * that plays, abutting on the cut's clock: each reads its own source seconds, + * with the build's GAP_FADE out at the end of the piece before a join and in + * at the start of the piece after it -- a jump in the sound with no click. + * * @param {{ items: Array<{ id: string, start: number, end: number, clip: null | { * sourceFrom: number, sourceTo: number, playEnd: number, hold: number, - * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number } }> }} plan + * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number, + * gaps?: Array<{ from: number, to: number }> } }> }} plan * @returns {Array<{ id: string, index: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} */ export function audioSpans(plan) { @@ -86,7 +93,9 @@ export function audioSpans(plan) { if (!c || !(c.playEnd > it.start)) return; const from = it.start; // Its source's length: the encode pads a segment to whole frames with SILENCE (apad), and a hold is silent too. - const to = Math.min(c.playEnd, it.start + Math.max(0, c.sourceTo - c.sourceFrom)); + // Less its gaps: they never play. + const gaps = c.gaps?.length ? c.gaps : null; + const to = Math.min(c.playEnd, it.start + Math.max(0, gaps ? gappedLength(c.sourceFrom, c.sourceTo, gaps) : c.sourceTo - c.sourceFrom)); if (!(to > from)) return; const prev = items[i - 1]; const next = items[i + 1]; @@ -96,7 +105,7 @@ export function audioSpans(plan) { // The crossfades: up over the overlap with the clip before, down over the one after (on the segment, hold included). if (dIn > 0) envs.push(ramp(from, from + dIn)); if (dOut > 0) envs.push(ramp(it.end - dOut, it.end, true)); - const at = (src) => from + (src - c.sourceFrom); + const at = (src) => from + offsetIn(src, c.sourceFrom, gaps); // Room: heard over [sound[0], sound[1]] only -- a fade in ending at its start, a fade out from its end. if (Array.isArray(c.sound) && fin(c.sound[0]) && fin(c.sound[1])) { const [sa, sb] = c.sound; @@ -114,11 +123,30 @@ export function audioSpans(plan) { if (fin(c.soundFrom)) envs.push(ramp(at(/** @type {number} */ (c.soundFrom)), at(/** @type {number} */ (c.soundFrom)) + MUTE_FADE)); const db = (fin(c.gainDb) ? /** @type {number} */ (c.gainDb) : 0) + (fin(a.gain) ? a.gain : 0); const shift = fin(a.offset) ? a.offset / 1000 : 0; - out.push({ - id: it.id, index: i, from, to, - src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), - env: multiply(envs, from, to), - gain: r6(10 ** (db / 20)), + if (!gaps) { + out.push({ + id: it.id, index: i, from, to, + src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), + env: multiply(envs, from, to), + gain: r6(10 ** (db / 20)), + }); + return; + } + // One span per piece that plays; the joins faded out and in (the build's gapFilterParts). + const pieces = keptSpans(c.sourceFrom, c.sourceTo, gaps) + .map((p) => ({ src: p.from, a: at(p.from), b: Math.min(to, at(p.to)) })) + .filter((p) => p.b > p.a + 1e-6); + pieces.forEach((p, k) => { + const d = Math.min(GAP_FADE, (p.b - p.a) / 2); + const joins = []; + if (k > 0) joins.push(ramp(p.a, p.a + d)); + if (k < pieces.length - 1) joins.push(ramp(p.b - d, p.b, true)); + out.push({ + id: it.id, index: i, from: r6(p.a), to: r6(p.b), + src: r6(p.src - shift), srcTo: r6(p.src - shift + (p.b - p.a)), + env: multiply([...envs, ...joins], p.a, p.b), + gain: r6(10 ** (db / 20)), + }); }); }); return out; diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -76,6 +76,8 @@ export async function playView(project, { take = null } = {}) { end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null, + // Seconds taken out of its middle (gaps.mjs): the plan plays it as one item of jump cuts. + ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), blur: e.blur && typeof e.blur === "object" ? e.blur : null, // Ruled incorrect (the walk's verdict): its correction -- Play skips it unless asked to show it. incorrect: clipVerdict(e) === "incorrect" ? text(e.correction) || (e.reason === "wrong-speaker" ? "wrong speaker" : "marked incorrect") : null, diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -39,6 +39,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { isCalendarDate } from "umtool-report-to-video/attribution"; import { deckOn } from "umtool-report-to-video/deck"; +import { gappedLength, gapSpan, gapsOf } from "umtool-report-to-video/gaps"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -150,6 +151,8 @@ export function timelineRows(manifest) { start: e.start ?? null, end: e.end ?? null, ...(e.cutStart != null && e.cutEnd != null ? { cutStart: e.cutStart, cutEnd: e.cutEnd } : {}), + // Seconds taken out of its middle (gaps.mjs), and how long it then plays. + ...(gapsOf(e).length ? { gaps: gapsOf(e), plays: Number(gappedLength(gapSpan(e).from, gapSpan(e).to, gapsOf(e)).toFixed(2)) } : {}), } : {}), date: typeof e.date === "string" ? e.date : null, @@ -164,7 +167,8 @@ export function timelineLines(rows) { return rows.map((r) => { const span = r.type === "clip" - ? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}` + ? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}` + + (r.gaps?.length ? ` gaps ${r.gaps.map((g) => `−${fmt(g.from)}–${fmt(g.to)}`).join(" ")} (plays ${fmt(r.plays)}s)` : "") : "".padEnd(14); const label = [r.date, r.title].filter(Boolean).join(" "); return `${String(r.index).padStart(3)} ${r.id.padEnd(w)} ${r.type.padEnd(tw)} ${span}${label ? ` ${label}` : ""}`; diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -162,6 +162,10 @@ import { marksOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs"; import { blurCaptionLayout, blurPictureFilters, blurProblems, blurRecordOf, blurSpan, clipBlurOf, fittedSize, validateClipBlurEntries } from "./clip-blur.mjs"; import { validateFinaleEntries } from "./finale.mjs"; +// Seconds taken out of a clip's middle (gaps.mjs): pure; the segment's graph is built there too. +import { + gapFilterParts, gapSeconds, gapsOnSegment, inGap, offsetIn, recordGaps, renderGaps, validateGapEntries, +} from "./gaps.mjs"; import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -1298,9 +1302,19 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, entry, mont, raw, fetchStart, M: dirs.montage, render, provenance, sil, wantA, wantB, win, })); } + // GAPS (gaps.mjs): seconds taken out of the clip's middle, so it plays as one + // segment of jump cuts. A montage cuts to its phrase: none there. + const clipGaps = mont ? [] : renderGaps(entry, render); + if (mont && Array.isArray(entry.gaps) && entry.gaps.length) { + EMIT("note", { message: `${entry.id}: a montage cuts to its phrase — its gaps are not applied` }); + } // Snapped, and never inverted or collapsed (snap.mjs snapCut: the cut-points route's own). - // A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges). - const snapped = mont ? null : snapCut({ sil, wantA, wantB, render, locked: lockedEdges(entry, render) }); + // A locked edge snaps only outward, inside the silence it sits in (mute.mjs lockedEdges); + // and no edge snaps across a gap (a gap's edges are exact). + const snapped = mont ? null : snapCut({ + sil, wantA, wantB, render, locked: lockedEdges(entry, render), + ...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), + }); const a = mont ? mont.win.start : snapped.a; const b = mont ? mont.win.end : snapped.b; const cutA = mont ? mont.win.cutA : snapped.cutA; @@ -1314,6 +1328,22 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, : null; const segA = room ? room.plan.picA : cutA; const segB = room ? room.plan.picB : cutB; + // The gaps on the segment's own clock, on the frame grid (gapsOnSegment), and + // in source seconds as applied (the cut record's `gaps`: what every later + // mapping of a source second onto this segment reads). `segSeconds` is what + // the segment lasts: its span less its gaps -- the span itself without any. + const segGaps = clipGaps.length ? gapsOnSegment(clipGaps, fetchStart + segA, segB - segA, render.fps ?? 30) : []; + const gapTotal = gapSeconds(segGaps); + const segSeconds = segGaps.length ? segB - segA - gapTotal : segB - segA; + if (clipGaps.length) { + EMIT("gaps", { + id: entry.id, gaps: segGaps.length, cut: Number(gapTotal.toFixed(3)), seconds: Number(segSeconds.toFixed(3)), + ...(segGaps.length < clipGaps.length ? { dropped: clipGaps.length - segGaps.length } : {}), + }); + const at = entry.cite ?? entry.start; + const g = inGap(at, clipGaps); + if (g) EMIT("note", { message: `${entry.id}: cite ${at} is inside the gap ${g.from}–${g.to}, which never plays — kept as written; move it` }); + } // Where in the SOURCE this segment really starts and ends, snapped: what a // `muteFrom` (source seconds) is measured from at the join, long after this // function is gone (`--chrome-only` rebuilds no segment). With room, the @@ -1323,6 +1353,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, start: Number((fetchStart + segA).toFixed(3)), end: Number((fetchStart + segB).toFixed(3)), snapped: { start: a.snapped, end: b.snapped }, ...(room ? { room: room.record } : {}), + // Only with gaps, so a clip without them records what it always did. + ...(segGaps.length + ? { gaps: segGaps.map((g) => ({ from: Number((fetchStart + segA + g.from).toFixed(3)), to: Number((fetchStart + segA + g.to).toFixed(3)) })) } + : {}), }; // Even loudness for a cut that is not a montage (render.loudness, release // 36): the cut as it will play, measured, one gain toward the target @@ -1336,7 +1370,8 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // The sound's graph: `[0:a]` levelled to `[al]` (an asplit first when a // poster's waveform also reads it), else nothing and `0:a` as ever. // Room's fades (muted head and tail) after the gain. - const roomAf = room ? roomAudioFilter(room.plan) : ""; + // With gaps, the muted tail is that much earlier on the segment's clock (the gaps are inside the cut). + const roomAf = room ? roomAudioFilter(gapTotal ? { ...room.plan, soundB: room.plan.soundB - gapTotal, picB: room.plan.picB - gapTotal } : room.plan) : ""; // First, the sound laid on its own clock (AUDIO_ON_CLOCK): a cut that starts // before its source's sound does, or a source with a hole in its sound, // makes a segment whose audio is continuous from 0 -- in sync by samples, @@ -1358,7 +1393,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ? [...(shifted.from < 0 ? ["-itsoffset", (-shifted.from).toFixed(3)] : []), ...cutArgs(raw, Math.max(0, shifted.from), shifted.to)] : null; const soundChain = [ - AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf, ...clipAudioFilters(knobs, segB - segA), + AUDIO_ON_CLOCK, !mont && level != null ? levelFilters(level.gain) : "", roomAf, ...clipAudioFilters(knobs, segSeconds), ].filter(Boolean).join(","); const leveled = !mont && soundChain !== ""; // `ain`: the sound's input -- `[0:a]`, or the offset's own. @@ -1398,7 +1433,11 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // about it. Same cut, same audio map, same encode as every other segment. // No picture in the source: a poster stands in for `[0:v]` (see above). const media = await probeMedia(raw); - const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(segB, media.duration) : segB) - segA); + const posterSeconds = Math.max(1 / render.fps, (media.duration != null ? Math.min(segB, media.duration) : segB) - segA - gapTotal); + // The gaps taken out first (gaps.mjs gapFilterParts): every later filter + // reads `v` for the picture and `a` for the sound in place of the input's. + // `ain` is the sound's input. Without gaps, the inputs as they always were. + const gapped = (ain) => gapFilterParts({ gaps: segGaps, seconds: segB - segA, vIn: media.hasVideo ? "[0:v]" : null, aIn: ain }); if (!media.hasVideo) EMIT("note", { message: `${entry.id}: no picture in ${path.basename(raw)} — a poster plays under its sound` }); const poster = (box, posterIdx) => media.hasVideo @@ -1413,7 +1452,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // render.blur "off"): every chain below is the one it always was. const blur = clipBlurOf(entry, render); if (blur && !media.hasVideo) EMIT("note", { message: `${entry.id}: no picture to blur in ${path.basename(raw)} — the poster plays as it is` }); - const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segB - segA) : null; + const span = media.hasVideo ? blurSpan(blur, fetchStart + segA, segSeconds, cutRecord.gaps) : null; if (blur) cutRecord.blur = blurRecordOf(blur); /** The blur's filters for a picture fitted into `bw` × `bh` (empty: none). */ const blurPicture = async (bw, bh) => { @@ -1434,6 +1473,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const fr = framing ?? segmentFraming(render); const pst = await poster(fr.box, 1); const picture = await blurPicture(fr.box.width, fr.box.height); + const g = gapped(soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"); // The box it was framed into, so --chrome-only can refuse another layout's. await encodeClipSegment({ seg, outDir, render, opts, id: entry.id, record: { ...cutRecord, framing: fr }, @@ -1443,8 +1483,9 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...(pst ? pst.input : []), ...(soundInput ?? []), "-filter_complex", [ - ...levelParts(pst ? pst.parts : null, soundInput ? `[${pst ? 2 : 1}:a]` : "[0:a]"), - `${pst ? "[pic]" : "[0:v]"}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}[v]`, + ...g.parts, + ...levelParts(pst ? pst.parts : null, g.a), + `${pst ? "[pic]" : g.v}${deckFramingFilter(render, { feed: fr.layout === "feed", picture })}[v]`, ].join(";"), "-map", "[v]", "-map", audioMap, ...encodeArgs(render), @@ -1519,7 +1560,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // the main extends the output, and the fix for that (shortest=1) would instead // truncate the clip to the strip. Ending early is free: overlay's default // eof_action=repeat holds the strip's last frame, which is the parked bar. - const barT = Math.max(0.2, segB - segA - 0.25); + const barT = Math.max(0.2, segSeconds - 0.25); const inputs = cutArgs(raw, segA, segB); let nextIdx = 1; @@ -1564,10 +1605,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // shares it through an asplit. // Even loudness (render.montage.loudness): the cut's sound measured, one gain. const mg = mont ? montageSegmentGraph({ mont, render, box: { w: VW, h: VH }, hasVideo: media.hasVideo, cutA, cutB, gainDb: level?.gain ?? null }) : null; - const pic = mg?.v ?? (pst ? "[pic]" : "[0:v]"); + // The gaps out first (none in a montage: segGaps is empty there). + const g = gapped(ain); + const pic = mg?.v ?? (pst ? "[pic]" : g.v); const lead = mg ? [...(pst ? [`[0:a]asplit=2[mpa][mpw]`, ...pst.parts.map((p) => p.replaceAll("[0:a]", "[mpw]"))] : []), ...mg.parts] - : levelParts(pst ? pst.parts : null, ain); + : [...g.parts, ...levelParts(pst ? pst.parts : null, g.a)]; const parts = hasFooter ? [ @@ -1599,7 +1642,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, if (dirs.look && captionsOn(render)) { const cap = await segmentCaptions({ entry, provenance, look: dirs.look, render, outDir, - from: cutRecord.start, seconds: segB - segA, bottom: FH, + from: cutRecord.start, seconds: segB - segA, bottom: FH, gaps: cutRecord.gaps ?? [], // With room: only the words heard -- none over a muted edge. ...(room ? { audible: { from: fetchStart + cutA, to: fetchStart + room.plan.soundB } } : {}), }); @@ -1680,15 +1723,23 @@ function lookWordsFor(entry, provenance, look, from, to) { * and the filter that burns it in, or null (a note) when the clip has no * words. `from` is the source second the segment starts at. */ -async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom, audible = null }) { +async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, bottom, audible = null, gaps = [] }) { // `audible` (room at the edges): the words of that span only, and no line past its end. const src = await lookWordsFor(entry, provenance, look, audible ? audible.from : from, audible ? audible.to : from + seconds); if (audible) seconds = Math.min(seconds, audible.to - from); + // `gaps` (source seconds, the cut record's): a word said in one is not + // heard, and every later one plays that much earlier. + if (gaps.length) { + seconds = offsetIn(from + seconds, from, gaps); + src.words = src.words.filter((w) => !inGap((w.start + w.end) / 2, gaps)); + } if (!src.words.length) { EMIT("note", { message: `${entry.id}: no words to caption — it plays without captions` }); return null; } - const rel = (x) => ({ ...x, start: x.start - from, end: x.end - from }); + const rel = gaps.length + ? (x) => ({ ...x, start: offsetIn(x.start, from, gaps), end: offsetIn(x.end, from, gaps) }) + : (x) => ({ ...x, start: x.start - from, end: x.end - from }); const size = render.captions?.size ?? "m"; const geo = captionGeometry({ width: render.width, height: render.height, size, bottom }); const lines = captionLines({ @@ -5297,12 +5348,23 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du if (Number.isFinite(rec?.start)) clipClock.set(entries[i].id, rec.start); } } + // A clip with gaps (gaps.mjs): the gaps its segment really left out, from + // its cut record. Read only for those: a cut without gaps measures what it did. + let clipGaps = null; + for (let i = 0; i < entries.length; i += 1) { + if (entries[i].type !== "clip" || !Array.isArray(entries[i].gaps) || !entries[i].gaps.length || !segments[i]) continue; + const rec = await readCutRecord(segments[i]).catch(() => null); + if (!rec) continue; + clipGaps ??= new Map(); + clipGaps.set(entries[i].id, recordGaps(rec)); + } // The variant's posts, placed on the clips this cut plays with their real // upload dates. A manifest without posts writes the schedule it always did. return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null, ...(fx ? { fxWords: fx.words, fxClock: fx.clock } : {}), ...(clipClock ? { clipClock } : {}), + ...(clipGaps ? { clipGaps } : {}), ...(estimated ? { estimated: true } : {}), }); } @@ -5319,12 +5381,16 @@ export async function measureChromeSchedule({ manifest, entries, segments, D, du export async function fxClipWords({ entries, segments, provenance = {}, render }) { const words = new Map(); const clock = new Map(); + const clipGaps = new Map(); for (let i = 0; i < entries.length; i += 1) { const e = entries[i]; if (e.type !== "clip") continue; const rec = segments[i] ? await readCutRecord(segments[i]).catch(() => null) : null; const from = Number.isFinite(rec?.start) ? rec.start : playWindow(e, render).from; clock.set(e.id, from); + // A clip's gaps (the record's as applied, else the manifest's): a word in one is not said in the cut. + const gaps = rec ? recordGaps(rec) : renderGaps(e, render); + if (gaps.length) clipGaps.set(e.id, gaps); const span = fxQuoteSpan(e); let got = null; // The captions first when they mark who speaks (">>", a dash) and the @@ -5342,9 +5408,14 @@ export async function fxClipWords({ entries, segments, provenance = {}, render } } } if (!got?.length) got = cueWords; - if (got.length) words.set(e.id, got.map((w) => ({ text: w.text, start: w.start - from, end: w.end - from, ...(w.turn ? { turn: true } : {}) }))); + if (gaps.length) got = got.filter((w) => !inGap((w.start + w.end) / 2, gaps)); + if (got.length) { + words.set(e.id, got.map((w) => ({ + text: w.text, start: offsetIn(w.start, from, gaps), end: offsetIn(w.end, from, gaps), ...(w.turn ? { turn: true } : {}), + }))); + } } - return { words, clock }; + return { words, clock, ...(clipGaps.size ? { gaps: clipGaps } : {}) }; } /** @@ -5653,6 +5724,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ...validateStatsEntries(whole), ...validateMontage(whole), ...validateAssist(whole), ...validateFxEntries(whole), ...validateTransitionStyle(whole), ...validateLook(whole), ...validateClipAudioEntries(whole), ...validateClipBlurEntries(whole), ...validateFinaleEntries(whole), + ...validateGapEntries(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/clip-blur.mjs b/umtool/report-to-video/clip-blur.mjs @@ -35,6 +35,7 @@ // cut's switch (`render.blur`) is one of the look's keys: its rules are the // common look.mjs's, re-exported here. import { RENDER_BLUR_VALUES, renderBlurOn, validateRenderBlur } from "yt-dlp-transcript-common/lib/report/look.mjs"; +import { offsetIn } from "./gaps.mjs"; export { RENDER_BLUR_VALUES, renderBlurOn, validateRenderBlur }; @@ -139,13 +140,15 @@ const f3 = (n) => String(Number(n.toFixed(3))); /** * Where a blur lands in a segment that starts at source second `segStart` and * runs `seconds`: `{ whole: true }` (all of it), `{ a, b }` (the segment's - * own seconds), or null (the span misses the segment entirely). + * own seconds), or null (the span misses the segment entirely). `gaps` + * (source seconds, gaps.mjs): the segment's left-out seconds, so an edge + * after one lands that much earlier, and an edge inside one at its join. */ -export function blurSpan(blur, segStart, seconds) { +export function blurSpan(blur, segStart, seconds, gaps = null) { if (!blur) return null; if (blur.from === null && blur.to === null) return { whole: true }; - const a = Math.max(0, (blur.from ?? -Infinity) - segStart); - const b = Math.min(seconds, (blur.to ?? Infinity) - segStart); + const a = Math.max(0, blur.from === null || blur.from === undefined ? -Infinity : offsetIn(blur.from, segStart, gaps)); + const b = Math.min(seconds, blur.to === null || blur.to === undefined ? Infinity : offsetIn(blur.to, segStart, gaps)); if (!(b > a)) return null; if (a <= 0 && b >= seconds) return { whole: true }; return { a, b }; diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -16,6 +16,7 @@ // build-video.mjs or compose-chrome.mjs instead. import { createHash } from "node:crypto"; import { playEdges, soundEdges as soundEdgesOf, soundOnSegment } from "./mute.mjs"; +import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; @@ -826,7 +827,8 @@ export function scheduleFrom(durs, D) { export function estimatedDuration(entry, render = {}, D = transitionOf(render)) { if (entry.type === "clip") { const { from, to } = playWindow(entry, render); - return Math.max(1, to - from); + // Less its gaps (gaps.mjs): the seconds taken out of its middle never play. + return Math.max(1, gappedLength(from, to, renderGaps(entry, render))); } if (entry.type === "image") return Number(entry.seconds ?? 4); // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default). @@ -967,9 +969,15 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin */ export function deckSchedule({ entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null, - fxWords = null, fxClock = null, clipClock = null, + fxWords = null, fxClock = null, clipClock = null, clipGaps = null, }) { const deck = resolveDeck(render); + // A clip's gaps (gaps.mjs) on its segment: its cut record's as built + // (`clipGaps`), else its own. A source second after one plays that much + // earlier in the cut; only a segment with any carries `gaps`, so a cut + // without them places everything as it always did. + const gapsFor = (e) => clipGaps?.get(e.id) ?? renderGaps(e, render); + const withGaps = (s, e) => (gapsFor(e).length ? { ...s, gaps: gapsFor(e) } : s); const fps = render.fps ?? 30; // The series a mark may count (counter.mjs): the counter's, else the verdicts. const series = resolveCounter(render).order; @@ -1010,7 +1018,7 @@ export function deckSchedule({ const many = marks.length > 1 ? { claims: marks } : {}; if (!marks.some((c) => c.at !== undefined)) return { ...s, claim, ...many }; const e = entries[i]; - return { ...s, claim, ...many, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }; + return withGaps({ ...s, claim, ...many, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }, e); }), D, total, render, }); @@ -1035,7 +1043,7 @@ export function deckSchedule({ const e = entries[i]; if (!statsWanted(e, render)) return s; const points = overlayPointsOf({ frameScan }, e.id); - return points.length ? { ...s, points, sourceFrom: playWindow(e, render).from } : s; + return points.length ? withGaps({ ...s, points, sourceFrom: playWindow(e, render).from }, e) : s; }), D, total, render, }); @@ -1047,6 +1055,7 @@ export function deckSchedule({ ? fxSchedule({ segments: segs, entries, metas, render, D, total, words: fxWords, fps, sourceFrom: (e) => fxClock?.get(e.id) ?? playWindow(e, render).from, + gapsOf: gapsFor, hidden: (e) => hidesDeck(e, deck), }) : null; @@ -1055,6 +1064,7 @@ export function deckSchedule({ const deckClaims = claimsSchedule({ entries, segments: segs, D, total, metas, render, stamps, sourceFrom: (e) => clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from, + gapsOf: gapsFor, }); const claimClips = deckClaims ? deckClaimClips(render) : new Set(); const doc = { @@ -1155,7 +1165,7 @@ export function deckSchedule({ * * `n` is each item's index in `deck.claims`, for messages. */ -export function claimsSchedule({ entries, segments, D, total, metas = [], render, stamps = [], sourceFrom }) { +export function claimsSchedule({ entries, segments, D, total, metas = [], render, stamps = [], sourceFrom, gapsOf = () => null }) { const list = render?.chrome?.deck?.claims; if (!Array.isArray(list) || !list.length || deckClaimShapeErrors(list).length) return null; const verdicts = resolveFactcheck(render).verdicts; @@ -1170,7 +1180,7 @@ export function claimsSchedule({ entries, segments, D, total, metas = [], render const cutAt = (id, t) => { const i = idx.get(id); const s = segments[i]; - return round(Math.min(s.start + s.duration, Math.max(s.start, s.start + (t - sourceFrom(entries[i]))))); + return round(Math.min(s.start + s.duration, Math.max(s.start, s.start + offsetIn(t, sourceFrom(entries[i]), gapsOf(entries[i]))))); }; const untilOf = (id) => { const i = idx.get(id); @@ -2370,14 +2380,16 @@ export const endFadeOf = (render) => (numIn(render?.endFade, 0, END_FADE_MAX) ? */ export function muteSegmentSeconds({ entry, record = null, render = {}, seconds = null, source = entry.muteFrom }) { const fps = render.fps ?? 30; + // A segment with gaps (gaps.mjs) is its span less them: the record says which it left out. + const recGaps = recordGaps(record); const ok = record && record.video === entry.video && Number.isFinite(record.start) && Number.isFinite(record.end) && - (seconds == null || Math.abs(record.end - record.start - seconds) <= 2 / fps); - const at = (from) => Math.max(0, Math.round((source - from) * 1000) / 1000); - if (ok) return { at: at(record.start), source: "record" }; + (seconds == null || Math.abs(gappedLength(record.start, record.end, recGaps) - seconds) <= 2 / fps); + const at = (from, gaps = null) => Math.max(0, Math.round(offsetIn(source, from, gaps) * 1000) / 1000); + if (ok) return { at: at(record.start, recGaps), source: "record" }; const { from } = playWindow(entry, render); return { - at: at(from), + at: at(from, renderGaps(entry, render)), source: "window", note: `${entry.id}: ${record ? "the cut record does not match the segment" : "no cut record beside the segment"} — ` + @@ -2407,7 +2419,9 @@ export function segmentSoundEdits({ entry, record = null, render = {}, seconds } const probe = muteSegmentSeconds({ entry, record, render, seconds, source: se.muteFrom ?? se.soundFrom }); const fromRecord = probe.source === "record"; if (probe.note && entry.muteFrom != null) out.notes.push(probe.note); - const on = soundOnSegment(entry, render, fromRecord ? record.start : playEdges(entry, render).from, seconds); + const on = fromRecord + ? soundOnSegment(entry, render, record.start, seconds, recordGaps(record)) + : soundOnSegment(entry, render, playEdges(entry, render).from, seconds, renderGaps(entry, render)); if (se.muteFrom != null && !se.implicit) { const from = fromRecord ? "from its cut record" : "from the unsnapped start"; // Validation allows the clip's whole extent, but only the played window is diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs @@ -34,6 +34,7 @@ // verdicts, their default labels and colours and the override rules are one // copy shared with report.json and the export site's report pages. This file // re-exports the list and lays the stamp and tally settings beside the labels. +import { offsetIn } from "./gaps.mjs"; import { isIsoDate } from "./claims.mjs"; import { resolveCounter, VERDICT_SHAPES } from "./counter.mjs"; import { COUNTER_CELL } from "./modules/design.mjs"; @@ -593,7 +594,8 @@ export function stampSchedule({ segments, D, total, render }) { // plays at, inside the segment and before its stamp has to leave. const timed = (c) => { const stay = c.hold ?? seconds; - const want = seg.start + (c.at - seg.sourceFrom); + // A segment with gaps (gaps.mjs `gaps`, source seconds): the seconds that play. + const want = seg.start + offsetIn(c.at, seg.sourceFrom, seg.gaps); const landed = Math.min(Math.max(seg.start, want), out[0]); const at = Math.max(seg.start, landed - STAMP_MOTION.slam); const leave = Math.min(at + stay, out[0]); diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs @@ -32,6 +32,7 @@ // deck.mjs), so the few date and phrase helpers it needs are its own. import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; +import { offsetIn, sourceAtOffset } from "./gaps.mjs"; /** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */ export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]); @@ -537,9 +538,9 @@ export function quotePages(words, max) { * * @param {{ segments: Array<{id: string, start: number, duration: number}>, entries: any[], metas?: any[], * render: any, D: number, total: number, words?: Map<string, Array<{text: string, start: number, end: number}>> | null, - * sourceFrom: (entry: any) => number, hidden: (entry: any) => boolean, fps?: number }} args + * sourceFrom: (entry: any) => number, gapsOf?: (entry: any) => Array<{ from: number, to: number }> | null, hidden: (entry: any) => boolean, fps?: number }} args */ -export function fxSchedule({ segments, entries, metas = [], render, D, total, words = null, sourceFrom, hidden, fps = 30 }) { +export function fxSchedule({ segments, entries, metas = [], render, D, total, words = null, sourceFrom, gapsOf = () => null, hidden, fps = 30 }) { const keys = fxKeysOn(render); if (!keys.length) return null; const out = { keys }; @@ -566,7 +567,8 @@ export function fxSchedule({ segments, entries, metas = [], render, D, total, wo if (!ws || !ws.length) { const fb = fxQuoteFallback(c.entry); const f0 = sourceFrom(c.entry); - ws = fb.map((w) => ({ ...w, start: w.start - f0, end: w.end - f0 })); + const g = gapsOf(c.entry); + ws = fb.map((w) => ({ ...w, start: offsetIn(w.start, f0, g), end: offsetIn(w.end, f0, g) })); } const placed = (ws ?? []) .map((w) => ({ text: w.text, at: r3(c.start + w.start), end: r3(c.start + w.end), ...(w.turn ? { turn: true } : {}) })) @@ -591,7 +593,7 @@ export function fxSchedule({ segments, entries, metas = [], render, D, total, wo const ws = wordsOf(c); if (!ws) continue; const mask = punchMask(ws, fxPunchOf(c.entry)); - const who = style === "kinetic" && cfg.speakers === "auto" ? speakersOf(ws, c, sourceFrom) : null; + const who = style === "kinetic" && cfg.speakers === "auto" ? speakersOf(ws, c, sourceFrom, gapsOf) : null; const marked = ws.map((w, j) => ({ ...w, punch: mask[j], ...(who ? { speaker: who[j] } : {}) })); // A page holds one speaker's words: a turn starts a new page. const runs = []; @@ -730,7 +732,8 @@ export function fxSchedule({ segments, entries, metas = [], render, D, total, wo const rows = []; for (const c of vclips) { const f0 = sourceFrom(c.entry); - const seconds = new Set((Array.isArray(c.entry.fx?.punchIn) ? c.entry.fx.punchIn : []).map((t) => r3(t - f0))); + const g = gapsOf(c.entry); + const seconds = new Set((Array.isArray(c.entry.fx?.punchIn) ? c.entry.fx.punchIn : []).map((t) => r3(offsetIn(t, f0, g)))); // A laugh written in the captions, when `auto`: the word's start. if (pi.auto) for (const w of wordsOf(c) ?? []) if (FX_LAUGH_RE.test(fxNorm(w.text))) seconds.add(r3(w.at - c.start)); // In the segment's clock, inside the clip's clean span; two closer than @@ -846,13 +849,14 @@ export function fxZoomJoins(schedule) { * the line has one voice. It says WHICH of two voices, never whose: the * labels are the manifest's (`kineticQuote.voices`). */ -export function speakersOf(words, c, sourceFrom) { +export function speakersOf(words, c, sourceFrom, gapsOf = () => null) { const marks = Array.isArray(c.entry?.fx?.speakers) ? [...c.entry.fx.speakers].sort((a, b) => a.at - b.at) : null; let who; if (marks?.length) { const f0 = sourceFrom(c.entry); + const g = gapsOf(c.entry); who = words.map((w) => { - const src = w.at - c.start + f0; + const src = g?.length ? sourceAtOffset(w.at - c.start, f0, g) : w.at - c.start + f0; let v = marks[0].who; for (const m of marks) if (m.at <= src + 1e-6) v = m.who; return v; diff --git a/umtool/report-to-video/gaps-render.test.mjs b/umtool/report-to-video/gaps-render.test.mjs @@ -0,0 +1,207 @@ +// Gaps inside a clip (gaps.mjs), rendered for real and on the schedule: a clip +// with a gap is ONE segment, the kept seconds long, with the gap's picture and +// sound gone and its cut record naming what it left out; the cut is the +// segments' sum less the joins, as ever; absent or `[]` the render is byte for +// byte what it was. And every mapping of a source second onto the cut that +// reads the record -- the mute mark at the join, a claim stamped at a source +// second, the estimate's length -- jumps with the gap. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +// The corpus the build reads metadata and cues from: set before build-video +// (cues.mjs) is loaded, so it is this file's own. +const CORPUS = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-corpus-")); +process.env.CHANNELS_DIR = CORPUS; + +const { buildVideo, probeDuration, setProgressMode } = await import("./build-video.mjs"); +const { deckSchedule, estimatedDuration, muteSegmentSeconds, segmentSoundEdits } = await import("./deck.mjs"); +const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs"); +const { renderCut, snapCut } = await import("./snap.mjs"); + +test.after(() => rm(CORPUS, { recursive: true, force: true })); + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const FPS = 30; +const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" }; +const RENDER = { + width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0.4, + headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + fetchPad: 0, snapWindow: 0.05, silenceMinDur: 0.1, +}; +const CHANNEL = "synth"; +{ + const dir = path.join(CORPUS, CHANNEL, "data", "vid1"); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" })); + writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 12, uploadDate: "20240102", cues: [{ start: 0.2, end: 11.8, text: "words" }] })); + writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 12 })); +} + +/** + * A project: c1 1–6 s and c2 7–10 s of one 12 s window in out/clips-raw: a + * grey picture and a tone, BLACK and SILENT over 3–4 s (the gap c1 may take + * out), so what the render kept can be seen and heard. + */ +async function project(c1 = {}) { + const root = mkdtempSync(path.join(os.tmpdir(), "rtv-gaps-")); + mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true }); + const raw = path.join(root, "out", "clips-raw", "vid1_0.00-12.00.mp4"); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=320x180:r=${FPS}:d=12`, + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12", + "-filter_complex", "[0:v]drawbox=c=black:t=fill:enable='between(t,3,3.99)'[v];[1:a]volume=enable='between(t,3,3.99)':volume=0,volume=0.5[a]", + "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const manifestPath = path.join(root, "video.manifest.json"); + await writeFile(manifestPath, JSON.stringify({ + slug: "gaps", title: "Gaps", + provenance: { channelSlug: CHANNEL, channelsDir: CORPUS }, + render: RENDER, + timeline: [ + { type: "clip", id: "c1", channel: CHANNEL, video: "vid1", start: 1, end: 6, cite: 1, quote: "q", ...c1 }, + { type: "clip", id: "c2", channel: CHANNEL, video: "vid1", start: 7, end: 10, cite: 7, quote: "q" }, + ], + })); + return { root, manifestPath, seg: (id) => path.join(root, "out", "sourced", "segments", `${id}.mp4`) }; +} + +const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0]; +const quiet = () => setProgressMode(() => {}); +const record = async (p, id) => JSON.parse(await readFile(p.seg(id).replace(/\.mp4$/, ".cut.json"), "utf8")); +const near = (a, b, tol, what) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +/** Each frame's mean luma. */ +function lumas(file) { + const st = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"], { maxBuffer: 1 << 24 }); + return st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[1])); +} +/** The RMS of a file's sound over [a, b] (s), mono 8 kHz. */ +function rms(file, a, b) { + const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 }); + const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, Math.floor(r.stdout.length / 2)); + let sum = 0; + let n = 0; + for (let i = Math.floor(a * 8000); i < Math.min(pcm.length, Math.floor(b * 8000)); i += 1) { + sum += pcm[i] * pcm[i]; + n += 1; + } + return n ? Math.sqrt(sum / n) : 0; +} + +test("render: without gaps (absent or []) the cut is byte for byte the same, and the record says nothing new", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const ps = [await project({}), await project({ gaps: [] })]; + try { + for (const p of ps) await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + for (const f of ["gaps.mp4", "sourced/segments/c1.mp4", "sourced/segments/c2.mp4", "sourced/segments/c1.cut.json"]) { + const sums = ps.map((p) => md5(path.join(p.root, "out", f))); + assert.equal(new Set(sums).size, 1, `${f}: ${sums.join(" ")}`); + } + assert.equal((await record(ps[0], "c1")).gaps, undefined); + // The black and the silence are in c1 without the gap (2–3 s into it). + assert.ok(Math.min(...lumas(ps[0].seg("c1"))) < 30, "the gap's black plays without gaps"); + } finally { + for (const p of ps) await rm(p.root, { recursive: true, force: true }); + } +}); + +test("render: a gap is taken out of ONE segment -- the kept seconds long, no black, no silence; the record names it; the cut is the sum less the join", { skip: !have && "needs ffmpeg" }, async () => { + quiet(); + const p = await project({ gaps: [{ from: 3, to: 4 }] }); + try { + const r = await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + const rec = await record(p, "c1"); + assert.deepEqual([rec.start, rec.end], [1, 6]); + assert.deepEqual(rec.gaps, [{ from: 3, to: 4 }]); + const d1 = await probeDuration(p.seg("c1"), FPS); + near(d1, 4, 1 / FPS + 1e-6, "c1 is its 5 s less the 1 s gap"); + const y = lumas(p.seg("c1")); + assert.ok(Math.min(...y) > 60, `no black frame left in c1 (min YAVG ${Math.min(...y)})`); + // Heard all through: before the join, across it (its fades are 25 ms), after. + assert.ok(rms(p.seg("c1"), 0.2, 1.9) > 800, "before the join"); + assert.ok(rms(p.seg("c1"), 1.9, 2.1) > 600, "across the join"); + assert.ok(rms(p.seg("c1"), 2.1, 3.8) > 800, "after the join"); + const d2 = await probeDuration(p.seg("c2"), FPS); + near(await probeDuration(r.out, FPS), d1 + d2 - 0.4, 2 / FPS, "the cut's length"); + // A gap changed is that segment re-rendered, and only that one. + const c2Before = md5(p.seg("c2")); + const m = JSON.parse(await readFile(p.manifestPath, "utf8")); + m.timeline[0].gaps = [{ from: 2, to: 2.5 }]; + await writeFile(p.manifestPath, JSON.stringify(m)); + const events = []; + setProgressMode((e) => events.push(e)); + await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true } }); + near(await probeDuration(p.seg("c1"), FPS), 4.5, 1 / FPS + 1e-6, "c1 with the new gap"); + assert.equal(md5(p.seg("c2")), c2Before, "c2 untouched"); + const reused = events.filter((e) => e.ev === "note" && / segment unchanged /.test(e.message)).map((e) => e.message.split(":")[0]); + assert.ok(reused.includes("c2"), `c2 was reused (${JSON.stringify(reused)})`); + assert.ok(!reused.includes("c1"), `c1 was rebuilt (${JSON.stringify(reused)})`); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +// ---- the schedule's mappings, no ffmpeg ------------------------------------------ + +const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 }; +const GAPS = [{ from: 105, to: 107 }]; + +test("estimatedDuration: the play window less its gaps (and none in a montage)", () => { + const r = { leadIn: 0.4 }; + assert.ok(Math.abs(estimatedDuration(CLIP, r) - 16.4) < 1e-9); + assert.ok(Math.abs(estimatedDuration({ ...CLIP, gaps: GAPS }, r) - 14.4) < 1e-9); + assert.ok(Math.abs(estimatedDuration({ ...CLIP, gaps: GAPS }, { ...r, montage: { style: "wall" } }) - 16.4) < 1e-9); +}); + +test("the mute mark on the segment's clock: after a gap, that much earlier (from the record's gaps)", () => { + const e = { ...CLIP, gaps: GAPS, muteFrom: 110 }; + const record = { video: "v", start: 101.6, end: 118, gaps: GAPS }; + // The segment is 16.4 s less 2 s of gap. + const m = muteSegmentSeconds({ entry: e, record, render: { fps: 30 }, seconds: 14.4 }); + assert.equal(m.source, "record"); + assert.equal(m.at, Number((110 - 101.6 - 2).toFixed(3))); + // A record from before the gaps (no `gaps`, the old length) is not believed: the window's estimate, gap-aware. + const old = muteSegmentSeconds({ entry: e, record: { video: "v", start: 101.6, end: 118 }, render: { fps: 30 }, seconds: 14.4 }); + assert.equal(old.source, "window"); + assert.equal(old.at, Number((110 - 101.6 - 2).toFixed(3))); + // The joins' rule agrees. + const ed = segmentSoundEdits({ entry: e, record, render: { fps: 30 }, seconds: 14.4 }); + assert.equal(ed.mute, m.at); +}); + +test("a claim stamped at a source second lands that much earlier after a gap; without gaps exactly where it did", () => { + const render = { fps: 30, transition: 0.5, leadIn: 0.4, chrome: { engine: "hyperframes", layout: "deck" } }; + const claim = { id: "k1", verdict: "CONTRADICTED", at: 110 }; + const entries = [{ ...CLIP, claim }]; + const plain = deckSchedule({ entries, durs: [16.4], D: 0.5, render }); + const gapped = deckSchedule({ entries: [{ ...CLIP, claim, gaps: GAPS }], durs: [14.4], D: 0.5, render }); + const landed = (s) => s.factcheck.stamps[0].landed; + assert.ok(Math.abs(landed(plain) - (110 - 101.6)) < 1e-6, `plain ${landed(plain)}`); + assert.ok(Math.abs(landed(gapped) - (110 - 101.6 - 2)) < 1e-6, `gapped ${landed(gapped)}`); + // The record's gaps win over the manifest's (the frame grid's edges). + const fromRecord = deckSchedule({ + entries: [{ ...CLIP, claim, gaps: GAPS }], durs: [14.4], D: 0.5, render, + clipClock: new Map([["c1", 101.6]]), clipGaps: new Map([["c1", [{ from: 105, to: 106 }]]]), + }); + assert.ok(Math.abs(landed(fromRecord) - (110 - 101.6 - 1)) < 1e-6); +}); + +test("snapCut: no edge snaps across a gap, nor nearer it than half a second", () => { + // A silence right after the start that would pull it inward, past the gap at 1.0 (file seconds). + const sil = [{ s: 0.6, e: 1.4 }]; + const free = snapCut({ sil, wantA: 0.5, wantB: 5, render: { snapWindow: 1.6 } }); + assert.ok(free.a.at > 1, `without the gap it snaps inward (${free.a.at})`); + const held = snapCut({ sil, wantA: 0.5, wantB: 5, render: { snapWindow: 1.6 }, gaps: [{ from: 1.2, to: 2 }] }); + assert.deepEqual(held.a, { at: 0.5, snapped: false }); + // renderCut takes source seconds. + const rc = renderCut({ sil, fetchStart: 100, playFrom: 100.5, playTo: 105, render: { snapWindow: 1.6 }, gaps: [{ from: 101.2, to: 102 }] }); + assert.equal(rc.start, 100.5); +}); diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -0,0 +1,424 @@ +// GAPS INSIDE A CLIP: seconds taken out of the middle of one clip, which then +// plays as ONE segment of jump cuts -- one header, one pip, one subtitle card -- +// rather than as two clips with a crossfade between them. +// +// timeline entry: "gaps": [{ "from": 32988.4, "to": 32990.1 }, ...] +// +// SOURCE seconds, like `start`/`end`/`cutStart`/`cutEnd`. Each gap lies inside +// the clip's CUT (its `cutStart`–`cutEnd`, else its extent), at least +// GAP_LIMITS.min long, at most GAP_LIMITS.max of them, sorted, apart, and with +// at least GAP_LIMITS.keep seconds of material before the first, between any +// two and after the last: a sliver of picture between two jumps reads as a +// glitch, not a cut. A `muteFrom` or a claim mark's `at` strictly INSIDE a gap +// is refused: it names a second the cut never plays, and moving it to the +// join would move a decision somebody made by ear (an `at`, or the mark, on +// a gap's edge is fine -- it lands at the join). +// +// Absent (or empty), every number below is the one a clip without gaps always +// had: `offsetIn(src, from, [])` is `src - from`, byte for byte. +// +// THE CLOCKS. A segment's picture starts at source second `from` (its cut +// record's `start`); the gapped clock counts only the seconds that PLAY. +// `offsetIn` maps a source second onto it (a second inside a gap lands on the +// join, where the gap was), `sourceAtOffset` maps back (the join shows the +// material after the gap). +// +// Dependency-free, so a client bundle (Play the cut, the clip editor, the live +// preview) takes it alone; the writer (umtool lib/report/manifest.mjs), the +// build's validators (lint.mjs, build-video.mjs) and `umtool check` share +// `validateGaps`. + +/** The rules a clip's gaps keep: seconds (min, keep) and a count (max). */ +export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 12, keep: 0.5 }); + +/** Each join's fade, in seconds: out over the end of the piece before, in over the start of the piece after -- short enough to keep a word, long enough not to click. */ +export const GAP_FADE = 0.025; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const EPS = 1e-6; +/** The writer's tolerance for a stored 2 dp edge (manifest.mjs WIN_EPS). */ +const WIN_EPS = 0.02; + +/** + * The span a clip's gaps must lie in: its cut when it has both fields, else + * its extent. + * + * @param {Record<string, any>} entry + * @returns {{ from: number, to: number }} + */ +export function gapSpan(entry) { + const hasCut = fin(entry?.cutStart) && fin(entry?.cutEnd); + return { from: hasCut ? entry.cutStart : entry?.start, to: hasCut ? entry.cutEnd : entry?.end }; +} + +/** + * A clip's gaps as the arithmetic reads them: the well-formed ones, sorted. + * [] for none -- and for anything that is not a list (validateGaps says why; + * the build refuses it before it gets here). + * + * @param {Record<string, any> | null | undefined} entry + * @returns {Array<{ from: number, to: number }>} + */ +export function gapsOf(entry) { + const g = entry?.gaps; + if (!Array.isArray(g) || !g.length) return []; + return g + .filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from) + .map((x) => ({ from: x.from, to: x.to })) + .sort((a, b) => a.from - b.from); +} + +/** Does this clip carry any gap? */ +export const hasGaps = (entry) => gapsOf(entry).length > 0; + +/** + * The gaps a render of this block applies to a clip: its own, except in a + * montage (render.montage), which cuts every clip to its phrase. + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + */ +export function renderGaps(entry, render = {}) { + if (entry?.type !== "clip") return []; + if (render?.montage != null && typeof render.montage === "object" && !Array.isArray(render.montage)) return []; + return gapsOf(entry); +} + +/** + * The marks a clip carries, raw (`claims`, else `claim`) -- what an `at` + * inside a gap is looked for in. + */ +const marksAt = (entry) => (Array.isArray(entry?.claims) ? entry.claims : isObj(entry?.claim) ? [entry.claim] : []) + .filter((m) => isObj(m) && fin(m.at)); + +/** The gap a source second lies strictly inside, or null. */ +export function inGap(src, gaps) { + if (!fin(src)) return null; + for (const g of gaps ?? []) if (src > g.from + EPS && src < g.to - EPS) return g; + return null; +} + +/** + * Every reason a clip's `gaps` cannot be built, as sentences naming `where` + * (empty: it can). Absent or null is none; `[]` is none too (the writer + * removes it). + * + * @param {Record<string, any>} entry + * @param {string} [where] + * @returns {string[]} + */ +export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}`) { + const v = entry?.gaps; + if (v === undefined || v === null) return []; + if (entry.type !== "clip") return [`${where}.gaps: only a clip has seconds to take out`]; + if (!Array.isArray(v)) return [`${where}.gaps must be a list of { from, to } in source seconds`]; + if (!v.length) return []; + const errors = []; + if (v.length > GAP_LIMITS.max) errors.push(`${where}.gaps: at most ${GAP_LIMITS.max} gaps in one clip (it has ${v.length}) — split it into clips`); + const ok = []; + v.forEach((g, k) => { + if (!isObj(g) || !fin(g.from) || !fin(g.to)) { + errors.push(`${where}.gaps[${k}] must be { from, to } in source seconds`); + return; + } + if (g.to - g.from < GAP_LIMITS.min - EPS) { + errors.push(`${where}.gaps[${k}] ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); + return; + } + ok.push({ ...g, k }); + }); + if (errors.length) return errors; + for (let i = 1; i < ok.length; i += 1) { + if (ok[i].from < ok[i - 1].from) { + errors.push(`${where}.gaps must be in order (gaps[${ok[i].k}] ${ok[i].from} starts before gaps[${ok[i - 1].k}] ${ok[i - 1].from})`); + return errors; + } + } + const span = gapSpan(entry); + const keep = GAP_LIMITS.keep; + ok.forEach((g, i) => { + if (fin(span.from) && fin(span.to) && (g.from < span.from - WIN_EPS || g.to > span.to + WIN_EPS)) { + errors.push(`${where}.gaps[${g.k}] ${g.from}–${g.to} lies outside the clip's cut ${span.from}–${span.to} — widen the cut, or remove the gap`); + return; + } + const before = i === 0 ? span.from : ok[i - 1].to; + const what = i === 0 ? "the cut's start" : `gaps[${ok[i - 1].k}]`; + if (fin(before) && g.from - before < keep - WIN_EPS) { + errors.push( + i > 0 && g.from < before + ? `${where}.gaps[${g.k}] ${g.from}–${g.to} overlaps ${what} — merge them into one gap` + : `${where}.gaps[${g.k}] ${g.from}–${g.to} leaves ${Math.max(0, g.from - before).toFixed(2)} s after ${what}; keep at least ${keep} s between cuts`, + ); + } + }); + const last = ok[ok.length - 1]; + if (!errors.length && fin(span.to) && span.to - last.to < keep - WIN_EPS) { + errors.push(`${where}.gaps[${last.k}] ${last.from}–${last.to} leaves ${Math.max(0, span.to - last.to).toFixed(2)} s before the cut's end; keep at least ${keep} s`); + } + if (errors.length) return errors; + // A mark that names a second the cut never plays. + if (fin(entry.muteFrom) && inGap(entry.muteFrom, ok)) { + const g = inGap(entry.muteFrom, ok); + errors.push(`${where}.muteFrom ${entry.muteFrom} lies inside the gap ${g.from}–${g.to}, which never plays — move the mark to the gap's edge, or remove the gap`); + } + for (const m of marksAt(entry)) { + const g = inGap(m.at, ok); + const name = typeof m.id === "string" && m.id ? `the mark ${m.id}'s second` : "the stamp's second"; + if (g) errors.push(`${where}: ${name} (at ${m.at}) lies inside the gap ${g.from}–${g.to}, which never plays — move it, or remove the gap`); + } + return errors; +} + +/** Every clip's gaps in the timeline, checked: the build refuses with these before it fetches. */ +export function validateGapEntries(manifest) { + const errors = []; + (manifest?.timeline ?? []).forEach((e, i) => { + errors.push(...validateGaps(e, `timeline[${i}] (${e?.id ?? "?"})`)); + }); + return errors; +} + +/** + * A list of gaps as the writer stores it: each edge at 2 dp, sorted by its + * start. Not validated (validateGaps on the entry is). + * + * @param {Array<{ from: number, to: number }>} list + */ +export function normalizeGaps(list) { + const r2 = (n) => Number(Number(n).toFixed(2)); + return (list ?? []) + .map((g) => ({ from: r2(g.from), to: r2(g.to) })) + .sort((a, b) => a.from - b.from || a.to - b.to); +} + +/** + * The gaps that fall in [from, to], clipped to it: what a segment cut from + * `from` to `to` actually leaves out. A gap the snapped edge has moved past + * is dropped; one it cuts into is clipped. + * + * @param {Array<{ from: number, to: number }>} gaps + * @param {number} from + * @param {number} to + */ +export function gapsWithin(gaps, from, to) { + const out = []; + for (const g of gaps ?? []) { + const a = Math.max(g.from, from); + const b = Math.min(g.to, to); + if (b - a > EPS) out.push({ from: a, to: b }); + } + return out; +} + +/** How many seconds of [from, to] the gaps take out. */ +export function gapSeconds(gaps, from = -Infinity, to = Infinity) { + let s = 0; + for (const g of gaps ?? []) { + const a = Math.max(g.from, from); + const b = Math.min(g.to, to); + if (b > a) s += b - a; + } + return s; +} + +/** The seconds [from, to] plays with its gaps taken out (`to - from` without any). */ +export function gappedLength(from, to, gaps) { + return gaps?.length ? Math.max(0, to - from - gapSeconds(gaps, from, to)) : to - from; +} + +/** + * Source second `src` on the gapped clock of a segment whose picture starts + * at source second `from`: the seconds that PLAY between them. A second + * inside a gap lands on the join. Without gaps, `src - from`. + * + * @param {number} src + * @param {number} from + * @param {Array<{ from: number, to: number }> | null | undefined} gaps + */ +export function offsetIn(src, from, gaps) { + if (!gaps?.length) return src - from; + return src - from - gapSeconds(gaps, from, Math.max(from, src)); +} + +/** + * The inverse: the source second that plays `off` seconds into a segment + * whose picture starts at source second `from`. A join shows the material + * after its gap. Without gaps, `from + off`. + * + * @param {number} off + * @param {number} from + * @param {Array<{ from: number, to: number }> | null | undefined} gaps + */ +export function sourceAtOffset(off, from, gaps) { + if (!gaps?.length) return from + off; + let s = from + off; + for (const g of gaps) { + if (g.to <= from) continue; + const a = Math.max(g.from, from); + if (s >= a - EPS) s += g.to - a; + else break; + } + return s; +} + +/** + * The pieces of [from, to] that play, in order (the whole span without gaps). + * + * @param {number} from + * @param {number} to + * @param {Array<{ from: number, to: number }> | null | undefined} gaps + * @returns {Array<{ from: number, to: number }>} + */ +export function keptSpans(from, to, gaps) { + if (!gaps?.length) return [{ from, to }]; + const out = []; + let at = from; + for (const g of gapsWithin(gaps, from, to)) { + if (g.from - at > EPS) out.push({ from: at, to: g.from }); + at = Math.max(at, g.to); + } + if (to - at > EPS) out.push({ from: at, to }); + return out; +} + +/** + * A segment's gaps on its OWN clock, for the encode: each gap's edges in + * seconds from the segment's first frame (`segStart`, source seconds), put on + * the render's frame grid -- so the picture's trim and the sound's cut the + * same instants and every piece is whole frames -- and clipped into the + * segment's `seconds`. A gap that rounds to nothing is dropped; two that + * round to touching are one. (One that reaches a snapped edge -- the writer + * keeps GAP_LIMITS.keep from the cut's, and no edge snaps across a gap -- + * simply ends or starts the segment's footage there.) + * + * @param {Array<{ from: number, to: number }>} gaps source seconds + * @param {number} segStart source second of the segment's first frame + * @param {number} seconds the segment's length before the gaps + * @param {number} fps + * @returns {Array<{ from: number, to: number }>} + */ +export function gapsOnSegment(gaps, segStart, seconds, fps) { + const f = fps > 0 ? fps : 30; + const frame = (t) => Math.round(t * f) / f; + const out = []; + for (const g of gaps ?? []) { + const a = frame(Math.max(0, g.from - segStart)); + const b = frame(Math.min(seconds, g.to - segStart)); + if (b - a < 1 / f - EPS) continue; + const last = out[out.length - 1]; + if (last && a - last.to < 1 / f - EPS) { + last.to = Number(Math.max(last.to, b).toFixed(6)); + continue; + } + out.push({ from: Number(a.toFixed(6)), to: Number(b.toFixed(6)) }); + } + // Nothing left to play is not a segment: the gaps do not apply. + return gapSeconds(out) >= seconds - 1 / f + EPS ? [] : out; +} + +const n3 = (v) => Number(v.toFixed(6)).toString(); + +/** + * The filtergraph that takes a segment's gaps out (`gaps` on its own clock, + * gapsOnSegment's): the picture trimmed into its kept pieces and joined with + * hard cuts, the sound cut at the same instants with a GAP_FADE out and in at + * each join, so nothing clicks. Picture and sound come out the same length -- + * the kept seconds -- and every later filter reads `v` / `a` in place of the + * input's streams. Either input may be null (a clip with no picture: the + * 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 + * @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 }) { + 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}]`); + 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(`${pieces.map((_, k) => `[gvp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); + } + if (aIn) { + const outs = pieces.map((_, k) => `[gas${k}]`); + parts.push(`${aIn}asplit=${K}${outs.join("")}`); + pieces.forEach((p, k) => { + const len = p.to - p.from; + const d = Math.min(fade, len / 2); + const f = [`atrim=start=${n3(p.from)}:end=${n3(p.to)}`, "asetpts=PTS-STARTPTS"]; + // 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(`${pieces.map((_, k) => `[gap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); + } + return { parts, v: vIn ? vOut : null, a: aIn ? aOut : null }; +} + +/** + * The gaps of a clip that a cut record (`<id>.cut.json`) says its segment + * left out -- source seconds -- or [] (none, or a record from before gaps). + */ +export function recordGaps(record) { + const g = record?.gaps; + if (!Array.isArray(g)) return []; + return g.filter((x) => isObj(x) && fin(x.from) && fin(x.to) && x.to > x.from); +} + +/** + * Edit a clip's gaps list, as the CLI and the clip editor ask: `add` a span + * (merged with any gap it touches or overlaps), `remove` the gap holding a + * source second (or starting nearest it, within `tolerance`), or `set` the + * whole list (`[]` clears it). Returns the new list, normalized; the caller + * validates it on the entry. + * + * @param {Array<{ from: number, to: number }>} gaps the clip's now + * @param {{ add?: { from: number, to: number }, remove?: number, set?: Array<{ from: number, to: number }> }} op + * @param {{ tolerance?: number }} [opts] + */ +export function editGaps(gaps, op, { tolerance = 0.05 } = {}) { + if (op.set !== undefined) return normalizeGaps(op.set); + let list = [...(gaps ?? [])].sort((a, b) => a.from - b.from); + if (op.add) { + let { from, to } = op.add; + if (!(fin(from) && fin(to)) || to <= from) throw new Error(`a gap needs from < to in source seconds (got ${from}–${to})`); + // A span that touches or overlaps a gap grows it: two gaps a hair apart are one cut. + const keepList = []; + for (const g of list) { + if (g.to >= from - EPS && g.from <= to + EPS) { + from = Math.min(from, g.from); + to = Math.max(to, g.to); + } else keepList.push(g); + } + list = [...keepList, { from, to }]; + } + if (op.remove !== undefined) { + const t = Number(op.remove); + if (!fin(t)) throw new Error(`which gap? a source second inside it (got ${op.remove})`); + const k = list.findIndex((g) => t >= g.from - tolerance && t <= g.to + tolerance); + if (k < 0) throw new Error(`no gap at ${t}${list.length ? ` (gaps: ${list.map((g) => `${g.from}–${g.to}`).join(", ")})` : " — the clip has none"}`); + list = list.filter((_, i) => i !== k); + } + return normalizeGaps(list); +} + +/** `12.3-15.1` (or `12.3–15.1`, `12.3..15.1`) as a gap; null when it is not one. */ +export function parseGapSpec(text) { + const m = String(text ?? "").trim().match(/^(\d+(?:\.\d+)?)\s*(?:-|–|\.\.)\s*(\d+(?:\.\d+)?)$/); + if (!m) return null; + const from = Number(m[1]); + const to = Number(m[2]); + return fin(from) && fin(to) && to > from ? { from, to } : null; +} + +/** A clip's gaps in words, for a listing: `−12.30–15.10, −20.00–20.50` ("" without any). */ +export function gapsText(entry) { + return gapsOf(entry).map((g) => `−${g.from.toFixed(2)}–${g.to.toFixed(2)}`).join(", "); +} diff --git a/umtool/report-to-video/gaps.test.mjs b/umtool/report-to-video/gaps.test.mjs @@ -0,0 +1,209 @@ +// Gaps inside a clip (gaps.mjs): the rule a clip's `gaps` keep, the two clocks +// (source ↔ the gapped segment), the pieces that play, the frame grid, the +// edits the CLI and the bench ask for, and the filtergraph that takes them out +// -- the strings, and a real ffmpeg run on a synthetic clip: the picture and +// the sound come out the kept seconds long, the gap's black and silence gone. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin, + inGap, keptSpans, normalizeGaps, offsetIn, parseGapSpec, recordGaps, renderGaps, sourceAtOffset, validateGapEntries, validateGaps, +} from "./gaps.mjs"; + +const CLIP = { type: "clip", id: "c1", video: "v", start: 100, end: 120, cutStart: 102, cutEnd: 118 }; +const G = [{ from: 105, to: 107 }, { from: 110, to: 110.5 }]; + +// ---- validation ------------------------------------------------------------- + +test("validateGaps: absent, null or [] is none; a list inside the cut, apart and long enough is fine", () => { + assert.deepEqual(validateGaps(CLIP), []); + assert.deepEqual(validateGaps({ ...CLIP, gaps: null }), []); + assert.deepEqual(validateGaps({ ...CLIP, gaps: [] }), []); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G }), []); + // No cut: the extent is the span. + const { cutStart: _a, cutEnd: _b, ...noCut } = CLIP; + assert.deepEqual(validateGaps({ ...noCut, gaps: [{ from: 100.5, to: 101 }] }), []); + assert.match(validateGaps({ ...CLIP, gaps: [{ from: 100.5, to: 101 }] })[0], /outside the clip's cut 102–118/); +}); + +test("validateGaps: each refusal names what is wrong", () => { + const one = (gaps, extra = {}) => validateGaps({ ...CLIP, ...extra, gaps }); + assert.match(one({ from: 105, to: 106 })[0], /must be a list/); + assert.match(one([{ from: 105 }])[0], /gaps\[0\] must be \{ from, to \}/); + assert.match(one([{ from: 105, to: 105.1 }])[0], /under 0.2 s/); + assert.match(one([{ from: 110, to: 111 }, { from: 105, to: 106 }])[0], /in order/); + assert.match(one([{ from: 105, to: 107 }, { from: 106.5, to: 108 }])[0], /overlaps gaps\[0\]/); + assert.match(one([{ from: 105, to: 107 }, { from: 107.2, to: 108 }])[0], /leaves 0.20 s after gaps\[0\]; keep at least 0.5 s/); + assert.match(one([{ from: 102.3, to: 103 }])[0], /after the cut's start/); + assert.match(one([{ from: 117, to: 117.8 }])[0], /before the cut's end/); + assert.match(one([{ from: 117, to: 119 }])[0], /outside the clip's cut/); + const many = Array.from({ length: 13 }, (_, k) => ({ from: 100 + k * 1.5, to: 100.3 + k * 1.5 })); + assert.match(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 130, gaps: many })[0], /at most 12 gaps/); + assert.match(validateGaps({ type: "card", id: "k", gaps: G })[0], /only a clip/); +}); + +test("validateGaps: a mute mark or a claim mark strictly inside a gap is refused; on its edge it is fine", () => { + assert.match(validateGaps({ ...CLIP, gaps: G, muteFrom: 106 })[0], /muteFrom 106 lies inside the gap 105–107/); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G, muteFrom: 107 }), [], "at the gap's end: the join"); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G, muteFrom: 105 }), [], "at its start"); + assert.match(validateGaps({ ...CLIP, gaps: G, claim: { id: "k1", verdict: "FALSE", at: 110.2 } })[0], /the mark k1's second \(at 110.2\) lies inside the gap 110–110.5/); + assert.match(validateGaps({ ...CLIP, gaps: G, claims: [{ id: "a", verdict: "FALSE", at: 103 }, { id: "b", verdict: "FALSE", at: 106 }] })[0], /mark b's/); + assert.deepEqual(validateGaps({ ...CLIP, gaps: G, claim: { id: "k1", verdict: "FALSE", at: 108 } }), []); +}); + +test("validateGapEntries: every clip of the timeline, named by index", () => { + const errs = validateGapEntries({ timeline: [CLIP, { ...CLIP, id: "c2", gaps: [{ from: 1, to: 2 }] }] }); + assert.equal(errs.length, 1); + assert.match(errs[0], /^timeline\[1\] \(c2\)\.gaps\[0\]/); +}); + +// ---- the clocks --------------------------------------------------------------- + +test("offsetIn / sourceAtOffset: the seconds that play; without gaps the subtraction it always was", () => { + // Byte for byte: no gaps is `src - from`, and its inverse `from + off`. + for (const [src, from] of [[105.37, 101.6], [0.1 + 0.2, 0.1], [32989.123, 32986.1]]) { + assert.equal(offsetIn(src, from, []), src - from); + assert.equal(offsetIn(src, from, null), src - from); + assert.equal(sourceAtOffset(src - from, from, undefined), from + (src - from)); + } + const from = 101.6; + assert.equal(offsetIn(104, from, G), 104 - from); + assert.ok(Math.abs(offsetIn(108, from, G) - (108 - from - 2)) < 1e-9, "after the first gap: 2 s earlier"); + assert.ok(Math.abs(offsetIn(106, from, G) - (105 - from)) < 1e-9, "inside a gap: at its join"); + assert.ok(Math.abs(offsetIn(112, from, G) - (112 - from - 2.5)) < 1e-9, "after both"); + // The inverse lands after each gap, and round-trips every second that plays. + assert.ok(Math.abs(sourceAtOffset(105 - from, from, G) - 107) < 1e-9, "the join shows the material after the gap"); + for (const src of [101.6, 103, 104.99, 107, 109.3, 110.5, 115]) { + assert.ok(Math.abs(sourceAtOffset(offsetIn(src, from, G), from, G) - src) < 1e-9, `round trip ${src}`); + } +}); + +test("keptSpans, gappedLength, gapSeconds, gapsWithin", () => { + assert.deepEqual(keptSpans(102, 118, []), [{ from: 102, to: 118 }]); + assert.deepEqual(keptSpans(102, 118, G), [{ from: 102, to: 105 }, { from: 107, to: 110 }, { from: 110.5, to: 118 }]); + assert.equal(gappedLength(102, 118, []), 16); + assert.equal(gappedLength(102, 118, G), 13.5); + assert.equal(gapSeconds(G), 2.5); + assert.equal(gapSeconds(G, 106, 120), 1.5); + // A snapped edge that moved into a gap clips it; one past it drops it. + assert.deepEqual(gapsWithin(G, 106, 110.2), [{ from: 106, to: 107 }, { from: 110, to: 110.2 }]); + assert.deepEqual(gapsWithin(G, 108, 118), [{ from: 110, to: 110.5 }]); + assert.equal(inGap(106, G), G[0]); + assert.equal(inGap(105, G), null); +}); + +test("gapsOf / renderGaps / recordGaps: the well-formed ones, sorted; none in a montage", () => { + assert.deepEqual(gapsOf({ ...CLIP, gaps: [G[1], G[0], { from: 1 }] }), G); + assert.deepEqual(gapsOf(CLIP), []); + assert.deepEqual(renderGaps({ ...CLIP, gaps: G }, {}), G); + assert.deepEqual(renderGaps({ ...CLIP, gaps: G }, { montage: { style: "wall" } }), []); + assert.deepEqual(recordGaps({ start: 1, end: 2 }), []); + assert.deepEqual(recordGaps({ gaps: G }), G); +}); + +test("gapsOnSegment: on the segment's clock, on the frame grid, clipped", () => { + // The segment starts at 101.6 (the lead-in before 102) and runs 16.4 s. + const g = gapsOnSegment(G, 101.6, 16.4, 30); + assert.deepEqual(g.map((x) => [Math.round(x.from * 30), Math.round(x.to * 30)]), [[102, 162], [252, 267]]); + for (const x of g) { + assert.ok(Math.abs(x.from * 30 - Math.round(x.from * 30)) < 1e-6 && Math.abs(x.to * 30 - Math.round(x.to * 30)) < 1e-6, "whole frames"); + } + // A gap past the segment's end is dropped; one cut into is clipped. + assert.deepEqual(gapsOnSegment([{ from: 105, to: 107 }], 101.6, 4, 30).map((x) => [Math.round(x.from * 30), Math.round(x.to * 30)]), [[102, 120]], "cut into by the end: clipped"); + assert.deepEqual(gapsOnSegment([{ from: 105, to: 107 }], 108, 4, 30), []); +}); + +// ---- the edits ---------------------------------------------------------------- + +test("editGaps: add (merging what it touches), remove by a second inside, set; parseGapSpec; gapsText", () => { + assert.deepEqual(editGaps([], { add: { from: 105, to: 106 } }), [{ from: 105, to: 106 }]); + assert.deepEqual(editGaps([{ from: 105, to: 106 }], { add: { from: 105.5, to: 107 } }), [{ from: 105, to: 107 }]); + assert.deepEqual(editGaps([{ from: 110, to: 111 }], { add: { from: 105.004, to: 106.006 } }), [{ from: 105, to: 106.01 }, { from: 110, to: 111 }]); + assert.deepEqual(editGaps(G, { remove: 106.2 }), [G[1]]); + assert.throws(() => editGaps(G, { remove: 108 }), /no gap at 108 \(gaps: 105–107, 110–110.5\)/); + assert.throws(() => editGaps([], { add: { from: 3, to: 2 } }), /from < to/); + assert.deepEqual(editGaps(G, { set: [] }), []); + assert.deepEqual(normalizeGaps([{ from: 110.004, to: 111 }, { from: 105, to: 106.333 }]), [{ from: 105, to: 106.33 }, { from: 110, to: 111 }]); + assert.deepEqual(parseGapSpec("12.3-15.1"), { from: 12.3, to: 15.1 }); + assert.deepEqual(parseGapSpec(" 12.3 – 15.1 "), { from: 12.3, to: 15.1 }); + assert.deepEqual(parseGapSpec("12..13"), { from: 12, to: 13 }); + assert.equal(parseGapSpec("15-12"), null); + assert.equal(parseGapSpec("12"), null); + assert.equal(gapsText({ ...CLIP, gaps: G }), "−105.00–107.00, −110.00–110.50"); + assert.equal(GAP_LIMITS.min, 0.2); +}); + +// ---- the filtergraph ------------------------------------------------------------ + +test("gapFilterParts: nothing without gaps; trim + concat with a fade at each join with", () => { + assert.deepEqual(gapFilterParts({ gaps: [], seconds: 10 }), { parts: [], v: "[0:v]", a: "[0:a]" }); + assert.deepEqual(gapFilterParts({ gaps: [], seconds: 10, aIn: "[2:a]" }), { parts: [], v: "[0:v]", a: "[2:a]" }); + const g = gapFilterParts({ gaps: [{ from: 2, to: 3 }], seconds: 10 }); + assert.equal(g.v, "[gv]"); + assert.equal(g.a, "[ga]"); + assert.deepEqual(g.parts, [ + "[0:v]split=2[gvs0][gvs1]", + "[gvs0]trim=start=0:end=2,setpts=PTS-STARTPTS[gvp0]", + "[gvs1]trim=start=3:end=10,setpts=PTS-STARTPTS[gvp1]", + "[gvp0][gvp1]concat=n=2:v=1:a=0[gv]", + "[0:a]asplit=2[gas0][gas1]", + `[gas0]atrim=start=0:end=2,asetpts=PTS-STARTPTS,afade=t=out:st=${2 - GAP_FADE}:d=${GAP_FADE}[gap0]`, + `[gas1]atrim=start=3:end=10,asetpts=PTS-STARTPTS,afade=t=in:st=0:d=${GAP_FADE}[gap1]`, + "[gap0][gap1]concat=n=2:v=0:a=1[ga]", + ]); + // No picture (a poster stands in): the sound alone. + const a = gapFilterParts({ gaps: [{ from: 2, to: 3 }], seconds: 10, vIn: null }); + assert.equal(a.v, null); + assert.ok(a.parts.every((p) => !p.includes("[0:v]"))); +}); + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); + +test("gapFilterParts on a real clip: the kept seconds, the gap's black and silence gone, picture and sound one length", { skip: !have && "needs ffmpeg" }, () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "gaps-graph-")); + try { + const src = path.join(dir, "src.mp4"); + // 6 s of grey picture and a tone; black and silent over 2-3 s (the gap to take out). + let r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=160x90:r=30:d=6", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=6", + "-filter_complex", "[0:v]drawbox=c=black:t=fill:enable='between(t,2,2.99)'[v];[1:a]volume=enable='between(t,2,2.99)':volume=0[a]", + "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", src, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const out = path.join(dir, "out.mp4"); + const g = gapFilterParts({ gaps: gapsOnSegment([{ from: 2, to: 3 }], 0, 6, 30), seconds: 6 }); + r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-ss", "0", "-to", "6", "-i", src, "-filter_complex", g.parts.join(";"), + "-map", g.v, "-map", g.a, "-c:v", "libx264", "-preset", "ultrafast", "-r", "30", "-c:a", "aac", "-ar", "48000", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + const probe = (sel) => Number(spawnSync("ffprobe", ["-v", "error", "-select_streams", sel, "-show_entries", "stream=duration", "-of", "csv=p=0", out]).stdout.toString().trim()); + assert.ok(Math.abs(probe("v:0") - 5) <= 1 / 30 + 1e-3, `picture ${probe("v:0")}`); + assert.ok(Math.abs(probe("a:0") - 5) <= 0.03, `sound ${probe("a:0")}`); + // No black frame left: the darkest frame is the grey. + const st = spawnSync("ffmpeg", ["-v", "error", "-i", out, "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"]); + const yavg = st.stdout.toString().split("\n").filter((l) => l.includes("YAVG")).map((l) => Number(l.split("=")[1])); + assert.ok(yavg.length >= 149, `frames ${yavg.length}`); + assert.ok(Math.min(...yavg) > 60, `no black frame: min YAVG ${Math.min(...yavg)}`); + // No silence left either: every 100 ms but the join's own fades is loud. + const pcmR = spawnSync("ffmpeg", ["-v", "error", "-i", out, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 24 }); + const pcm = new Int16Array(pcmR.stdout.buffer, pcmR.stdout.byteOffset, Math.floor(pcmR.stdout.length / 2)); + for (let k = 1; k < 48; k += 1) { + const a = k * 800; + let sum = 0; + for (let i = a; i < a + 800 && i < pcm.length; i += 1) sum += pcm[i] * pcm[i]; + const rms = Math.sqrt(sum / 800); + assert.ok(rms > 1000, `loud at ${(k / 10).toFixed(1)} s: ${rms.toFixed(0)}`); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -83,6 +83,7 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateClipAudioEntries } from "./clip-audio.mjs"; import { validateClipBlurEntries } from "./clip-blur.mjs"; +import { validateGapEntries } from "./gaps.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -291,6 +292,8 @@ export function validatorErrors(whole) { ...validateFinaleEntries(whole), // A clip's blurred picture and the cut's render.blur (clip-blur.mjs). ...validateClipBlurEntries(whole), + // Seconds taken out of a clip's middle (gaps.mjs). + ...validateGapEntries(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); diff --git a/umtool/report-to-video/mute.mjs b/umtool/report-to-video/mute.mjs @@ -1,9 +1,11 @@ -// The mute mark's fade, and where a clip's sound is heard, alone: no imports, +// The mute mark's fade, and where a clip's sound is heard, alone: no imports but gaps.mjs (none of its own), // so a client bundle (umtool's clip bench previews the mute as the build makes // it; Play the cut's schedule) can take it without pulling in deck.mjs and // what deck.mjs imports (node:crypto, attribution). deck.mjs re-exports it; // the build, the cut-points route and Play the cut read the same numbers. +import { offsetIn } from "./gaps.mjs"; + /** The fade into a `muteFrom`'s silence, in seconds: long enough not to click, short enough to keep the next word out. */ export const MUTE_FADE = 0.04; @@ -94,15 +96,18 @@ export function soundEdges(entry, render = {}) { * reach before. The clip's own `muteFrom` is placed wherever it falls, as it * always was. The build's joins (deck.mjs segmentSoundEdits, from the cut * record) and the cut-points route (from the cut it computes) both call this. + * `gaps` (source seconds, gaps.mjs): the seconds the segment leaves out, so a + * mark after one lands that much earlier on its clock. * * @param {Record<string, any>} entry * @param {Record<string, any>} render * @param {number} segStart * @param {number} seconds + * @param {Array<{ from: number, to: number }> | null} [gaps] */ -export function soundOnSegment(entry, render, segStart, seconds) { +export function soundOnSegment(entry, render, segStart, seconds, gaps = null) { const se = soundEdges(entry, render); - const at = (src) => Math.max(0, Math.round((src - segStart) * 1000) / 1000); + const at = (src) => Math.max(0, Math.round(offsetIn(src, segStart, gaps) * 1000) / 1000); let mute = null; let soundFrom = null; if (se.muteFrom != null) { diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -36,6 +36,7 @@ "./finale": "./finale.mjs", "./frames-cut": "./frames-cut.mjs", "./fx": "./fx.mjs", + "./gaps": "./gaps.mjs", "./ladder-chunks": "./ladder-chunks.mjs", "./ledger-totals": "./ledger-totals.mjs", "./montage": "./montage.mjs", diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs @@ -12,6 +12,8 @@ // the clock the build snaps on, and the same float arithmetic on the same // clock is what makes the route's edges the build's to the millisecond. +import { GAP_LIMITS } from "./gaps.mjs"; + /** The render's defaults for the snap knobs (render.snapWindow, snapLead, snapTail, silence*). */ export const SNAP_DEFAULTS = Object.freeze({ snapWindow: 1.6, @@ -73,20 +75,35 @@ export function snap(desired, intervals, kind, window, render = {}, { pinned = f } /** + * How close (seconds) a snapped edge may come to a clip's gap: the writer's + * own rule for the material kept beside one (gaps.mjs GAP_LIMITS.keep). + */ +export const GAP_KEEP = GAP_LIMITS.keep; + +/** * A clip's two edges as the render cuts them: each snapped (`snap`), then * never inverted or collapsed -- the start at least a second before the * desired end, the end at least a second after the start. * * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o * `wantA`/`wantB`: the play window's edges in the file's seconds; `locked`: * which of them are the author's, exact (mute.mjs lockedEdges) -- each - * snapped only outward, inside its own silence + * snapped only outward, inside its own silence; `gaps`: the clip's gaps + * (gaps.mjs) in the file's seconds -- a gap's edges are exact, so neither + * edge snaps across one (nor nearer it than GAP_KEEP): such a snap is not + * taken and the edge stays where it was asked */ -export function snapCut({ sil, wantA, wantB, render = {}, locked = null }) { +export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = null }) { const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow; - const a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); - const b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); + let a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); + let b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); + if (gaps?.length) { + const first = gaps.reduce((m, g) => Math.min(m, g.from), Infinity); + const last = gaps.reduce((m, g) => Math.max(m, g.to), -Infinity); + if (a.at > wantA && a.at > first - GAP_KEEP) a = { at: wantA, snapped: false }; + if (b.at < wantB && b.at < last + GAP_KEEP) b = { at: wantB, snapped: false }; + } const cutA = Math.min(a.at, wantB - 1); const cutB = Math.max(b.at, cutA + 1); return { win, a, b, cutA, cutB }; @@ -100,13 +117,16 @@ export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3 * file it is cut from: what `<id>.cut.json` records (`start`, `end`, * `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are * the play window (deck.mjs playWindow); `fetchStart` the file's first - * second in the recording. + * second in the recording; `gaps` the clip's (gaps.mjs), source seconds. * * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o */ -export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null }) { - const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked }); +export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null }) { + const c = snapCut({ + sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked, + ...(gaps?.length ? { gaps: gaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), + }); return { start: recordSecond(fetchStart, c.cutA), end: recordSecond(fetchStart, c.cutB), diff --git a/umtool/report-to-video/stats.mjs b/umtool/report-to-video/stats.mjs @@ -16,6 +16,7 @@ // ffmpeg. deck.mjs imports this file -- never the other way round. import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; +import { offsetIn, sourceAtOffset } from "./gaps.mjs"; /** Where the stats sit in the footage box. */ export const STATS_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]); @@ -171,11 +172,13 @@ export function statsSchedule({ segments, D, total, render }) { const lo = s.start + (i > 0 ? D / 2 : 0); const hi = next ? next.start + D / 2 : total; if (!(hi > lo)) return; - const end = s.sourceFrom + (hi - s.start); - const states = [{ at: r3(lo), values: valuesAt(s.points, s.sourceFrom + (lo - s.start), cfg.fields) }]; + // A segment with gaps (gaps.mjs, source seconds): its clock counts only what plays. + const end = sourceAtOffset(hi - s.start, s.sourceFrom, s.gaps); + const first = sourceAtOffset(lo - s.start, s.sourceFrom, s.gaps); + const states = [{ at: r3(lo), values: valuesAt(s.points, first, cfg.fields) }]; for (const p of s.points) { - if (p.at <= s.sourceFrom + (lo - s.start) || p.at >= end) continue; - const at = r3(s.start + (p.at - s.sourceFrom)); + if (p.at <= first || p.at >= end) continue; + const at = r3(s.start + offsetIn(p.at, s.sourceFrom, s.gaps)); const values = valuesAt(s.points, p.at, cfg.fields); const last = states[states.length - 1]; if (cfg.fields.every((f) => last.values[f] === values[f])) continue; diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -53,6 +53,7 @@ import path from "node:path"; import { promisify } from "node:util"; import { encodeArgs } from "./build-video.mjs"; +import { offsetIn, recordGaps } from "./gaps.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -195,7 +196,19 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = } const s = Math.max(beat.start, rec.start); const e = Math.min(beat.end, rec.end); - want.push({ kind: "clip", id: beat.id, beat, rec, seg, a: seg.start + (s - rec.start), b: seg.start + (e - rec.start) }); + // 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)`); + } + want.push({ kind: "clip", id: beat.id, beat, rec, seg, a, b }); }); if (finale != null) { if (!Number.isFinite(finale) || finale <= 0) throw new TrailerError(`--finale ${finale}: seconds > 0`);