Archilyzer · Source

archilyzer

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

commit 48937b9be5612ebe52e8b83e0727491a2ece9f64
parent 2a32bd0a66321a05af66cff618bbcb04dee8dac8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 30 Oct 2026 14:46:54 -0400

Merge lane/clip-gaps-zoom: gaps inside a clip (seconds cut out of its middle, one segment of jump cuts) and the bench waveform's gap tools and zoom

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

Diffstat:
Mumtool/app/api/report/clip-editor/route.ts | 3+++
Mumtool/app/api/report/clip/route.ts | 2++
Mumtool/app/api/report/window/route.ts | 7+++++++
Mumtool/bin/umtool.mjs | 30++++++++++++++++++++++++++++++
Mumtool/components/projects/ClipBench.tsx | 487++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/components/projects/ClipBenchPage.tsx | 4++++
Aumtool/components/projects/bench/GapsZoom.tsx | 392+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/RenderGhosts.tsx | 11++++++++---
Mumtool/components/projects/review/LiveDeckPreview.tsx | 4++--
Mumtool/components/projects/review/PlayCut.tsx | 4+++-
Mumtool/components/projects/review/ReelStrip.tsx | 16+++++++++++++++-
Mumtool/components/projects/review/playEngine/engine.ts | 20+++++++++++++++-----
Mumtool/docs/cli.md | 12++++++++++++
Mumtool/docs/knobs.md | 44++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 12++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 16++++++++++++++++
Aumtool/e2e/gaps-zoom.spec.ts | 289++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/groups.mjs | 1+
Mumtool/lib/inbox/what.mjs | 1+
Mumtool/lib/projects/report.mjs | 12++++++++++++
Aumtool/lib/report/benchZoom.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/benchZoom.test.mjs | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/clipEditor.mjs | 16++++++++++++----
Mumtool/lib/report/clipEditorTypes.ts | 2++
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++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Aumtool/lib/report/playGaps.test.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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 | 426+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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++++++++++++++-
48 files changed, 3044 insertions(+), 151 deletions(-)

diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts @@ -12,6 +12,7 @@ export const dynamic = "force-dynamic"; // // GET ?project=<id> the view: clips, token, speakers, unused proposals // GET ?project=<id>&clip=<id>&from=<s>&to=<s> the strip for a span: turns, laughs, words | cues +// [&video=<id>] words only when they are that recording's (the bench's zoom) // POST { project, op, token?, … } one operation (clipEditor.mjs runClipEditorOp): // trim | restore | split | merge | add | bring-in | ruling | role | … | audio | blur // -> { op, result, carried, view }; 409 on a stale token (reload), 400 with @@ -35,6 +36,8 @@ export async function GET(request: Request) { clip: url.searchParams.get("clip"), from: Number(url.searchParams.get("from")), to: Number(url.searchParams.get("to")), + // The clip bench, zoomed in: that recording's words only. + video: url.searchParams.get("video") || null, }); return Response.json(n, { headers }); } diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts @@ -67,6 +67,8 @@ export async function GET(request: Request) { cutEnd: clip.cutEnd ?? null, lockCut: !!clip.lockCut, muteFrom: clip.muteFrom ?? null, + // Seconds cut out of its middle (gaps.mjs). + gaps: Array.isArray(clip.gaps) ? clip.gaps : [], }, view, // `v`: the version of each window's bytes, for the media URLs -- a refetch diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -62,6 +62,13 @@ export async function PUT(request: Request) { // The clip this one re-plays on purpose (a callback, a flash-forward), so // their overlap is not flagged or trimmed; empty or null clears it. "repeatOf", + // 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"; @@ -736,6 +738,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", @@ -1000,6 +1005,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. @@ -1032,6 +1054,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)`); @@ -1060,6 +1083,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/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -20,6 +20,7 @@ import { BenchBody, VerdictBar } from "./bench/BenchShell"; import CopyCitation from "./bench/CopyCitation"; import EdgeStrip from "./bench/EdgeStrip"; import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts"; +import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom"; import TakeWalkStrip from "./bench/TakeWalkStrip"; // The renderer's own line, imported rather than re-written. A preview that // disagrees with the header by a character is worth less than no preview: you @@ -36,6 +37,9 @@ import { playheadAt, } from "@/lib/report/playback.mjs"; import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; +import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs"; +// Gaps inside a clip: the rule (the writer's and the build's) and the pieces that play. +import { GAP_FADE, GAP_LIMITS, editGaps, gapSpan, gappedLength, gapsWithin, inGap, keptSpans, validateGaps } from "umtool-report-to-video/gaps"; import { DeckFrame, NeutralFrame, @@ -133,6 +137,12 @@ type Clip = { * before a finale's ending sound. Absent means the clip plays with its sound. */ muteFrom: number | null; + /** + * GAPS: source seconds cut out of the clip's middle (gaps.mjs), so it plays + * as one segment of jump cuts. Written at once (Cut gap, a click on a band), + * not drafted like the edges; every playback here skips them. + */ + gaps: Span[]; /** "confirmed" / "incorrect", or null for "nobody has looked at this yet". */ verdict: "confirmed" | "incorrect" | null; /** What the on-screen panel says over this clip. Absent means the auto text. */ @@ -214,6 +224,7 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({ cutEnd: e.cutEnd == null ? null : Number(e.cutEnd), lockCut: !!e.lockCut, muteFrom: e.muteFrom == null ? null : Number(e.muteFrom), + gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [], verdict: e.verdict === "confirmed" || e.verdict === "incorrect" ? e.verdict : null, onscreen: (e.onscreen as Onscreen | undefined) ?? null, }); @@ -487,6 +498,8 @@ type Session = { ctxStop: number; /** The element's own mute, put back when the picture stops following. */ mutedBefore: boolean; + /** A playback across gaps: the later pieces' nodes (the first is `node`). */ + more?: AudioBufferSourceNode[]; }; export default function ClipBench({ data }: { data: ClipBenchData }) { @@ -883,6 +896,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // Read by play() at the moment it schedules, so a mark moved since the last // render is the one you hear -- without re-creating play() on every nudge. const muteRef = useRef<number | null>(data.clip.muteFrom); + // The gaps as SAVED: what every playback skips. Read at the moment it schedules, like the mark. + const gapsRef = useRef<Span[]>(data.clip.gaps ?? []); + gapsRef.current = clip.gaps ?? []; const [audio, setAudio] = useState<{ state: "idle" | "loading" | "ready" | "failed"; why?: string }>({ state: "idle", }); @@ -1012,16 +1028,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { session.current = null; cancelAnimationFrame(s.raf); for (const t of s.timers) clearTimeout(t); - if (s.node) { - s.node.onended = null; + for (const node of [s.node, ...(s.more ?? [])]) { + if (!node) continue; + node.onended = null; try { - s.node.stop(); + node.stop(); } catch { /* never started, or already stopped */ } - s.node.disconnect(); - s.gain?.disconnect(); + node.disconnect(); } + s.gain?.disconnect(); const el = video.current; if (el) { pauseVideo(el); @@ -1038,7 +1055,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { * element can do, and the bench says that this is what is playing. */ const playElement = useCallback( - (from: number, to: number, gen: number) => { + (from: number, to: number, gen: number, gaps: Span[] = []) => { const el = video.current; if (!el || !cached) return; const rate = playback.rate; @@ -1083,6 +1100,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { if (session.current !== s) return; const t = el.currentTime + fetchStart; setPlayhead(t); + // A gap: on past it, as near as a frame tick gets it. + const g = inGap(t, gaps); + if (g && !el.seeking) el.currentTime = g.to - fetchStart; // The mark, as near as a frame tick gets it. const m = muteRef.current; el.muted = s.mutedBefore || (m != null && t >= m); @@ -1108,11 +1128,20 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { [cached, fetchStart, playback.rate, pauseVideo], ); + /** + * Play [from, to], skipping the clip's GAPS as the cut will (gaps.mjs): each + * piece that plays is its own node, abutting the next on the context's + * clock, the join faded out and in by the build's GAP_FADE; the picture is + * seeked at each join. `through` plays the gaps too (a span being chosen for + * one is heard as it is); `extra` is one more span to skip (Hear it: a + * selection heard as cut, before it is written). + */ const play = useCallback( - async (from: number, to: number) => { + async (from: number, to: number, { through = false, extra = null }: { through?: boolean; extra?: Span | null } = {}) => { const gen = (playGen.current += 1); stopPlayback(); if (!cached || !(to > from)) return; + const gaps = through ? [] : gapsWithin([...gapsRef.current, ...(extra ? [extra] : [])].sort((a, b) => a.from - b.from), from, to); const rate = playback.rate; // The context is opened HERE, inside the click or the key that asked: // that gesture is what lets it start. @@ -1127,14 +1156,14 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { if (!ac) throw new Error("this browser has no Web Audio"); d = await ensureDecoded({ from, to }); } catch { - if (gen === playGen.current) playElement(from, to, gen); + if (gen === playGen.current) playElement(from, to, gen, gaps); return; } if (gen !== playGen.current) return; // Longer than one decode: the element, rather than a second decode in // the middle of a click. if (!covers(d.span, from, to)) { - playElement(from, to, gen); + playElement(from, to, gen, gaps); return; } if (resumed) await Promise.race([resumed, new Promise((res) => setTimeout(res, 300))]); @@ -1143,38 +1172,90 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { // just as silent. if (gen !== playGen.current || ac!.state !== "running") return; const ctx = ac!; - const sch = bufferSchedule(d.span, d.buf.duration, from, to, rate); - if (!sch) return; + // The pieces that play: the whole range without gaps. + const pieces = keptSpans(from, to, gaps) + .map((p) => ({ p, sch: bufferSchedule(d.span, d.buf.duration, p.from, p.to, rate) })) + .filter((x): x is { p: Span; sch: NonNullable<ReturnType<typeof bufferSchedule>> } => !!x.sch); + if (!pieces.length) return; // At a speed but 1x the range is stretched at its own pitch and played // at 1x; a buffer's playbackRate is tape speed, an octave up at 2x. const stretched = wantsStretch(rate); - const buf = stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf; + const bufs = pieces.map(({ sch }) => (stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf)); if (gen !== playGen.current) return; - const node = ctx.createBufferSource(); - node.buffer = buf; - node.playbackRate.value = stretched ? 1 : rate; const gain = ctx.createGain(); - node.connect(gain); gain.connect(ctx.destination); // Ahead of now, so start and stop stay on the clock they were computed // on: a start in the past begins late at the SAME offset. const t0 = ctx.currentTime + START_LEAD; - const ctxStop = t0 + sch.wall; - const m = muteRamp(muteRef.current, from, from + sch.duration, rate); - if (m) { - if (m.at <= 0) gain.gain.setValueAtTime(0, t0); - else { - gain.gain.setValueAtTime(1, t0 + m.at); - gain.gain.linearRampToValueAtTime(0, t0 + m.at + m.fade); + // Each piece's place on the wall clock, from t0. + let acc = 0; + const placed = pieces.map(({ p, sch }) => { + const w0 = acc; + acc += sch.wall; + return { p, sch, w0, w1: acc }; + }); + const ctxStop = t0 + acc; + const end = placed[placed.length - 1].p.from + placed[placed.length - 1].sch.duration; + const nodes = placed.map(({ sch, w0 }, k) => { + const node = ctx.createBufferSource(); + node.buffer = bufs[k]; + node.playbackRate.value = stretched ? 1 : rate; + node.connect(gain); + // The stop is a TIME on the context's clock, not start()'s duration + // argument: that one is buffer content, and a clock time means the same + // thing at every speed. + node.start(t0 + w0, stretched ? 0 : sch.offset); + node.stop(t0 + w0 + sch.wall); + return node; + }); + if (placed.length === 1) { + const m = muteRamp(muteRef.current, from, from + placed[0].sch.duration, rate); + if (m) { + if (m.at <= 0) gain.gain.setValueAtTime(0, t0); + else { + gain.gain.setValueAtTime(1, t0 + m.at); + gain.gain.linearRampToValueAtTime(0, t0 + m.at + m.fade); + } + } + } else { + // Across gaps: the joins' fades and the mute mark, as one level on the wall clock. + const fadeW = GAP_FADE / rate; + const mark = muteRef.current; + let markW: number | null = null; + if (mark != null) { + if (mark <= from) markW = 0; + else { + const k = placed.findIndex((x) => mark <= x.p.from + x.sch.duration); + if (k >= 0) markW = placed[k].w0 + Math.max(0, mark - placed[k].p.from) / rate; + } } + const muteFadeW = MUTE_FADE / rate; + const level = (w: number) => { + let v = 1; + placed.forEach((x, k) => { + if (w < x.w0 || w > x.w1) return; + if (k > 0 && w < x.w0 + fadeW) v = Math.min(v, (w - x.w0) / fadeW); + if (k < placed.length - 1 && w > x.w1 - fadeW) v = Math.min(v, (x.w1 - w) / fadeW); + }); + if (markW != null) { + if (w >= markW) v = 0; + else if (w > markW - muteFadeW) v = Math.min(v, (markW - w) / muteFadeW); + } + return Math.max(0, Math.min(1, v)); + }; + const pts = new Set<number>([0, acc]); + placed.forEach((x, k) => { + if (k > 0) [x.w0, x.w0 + fadeW].forEach((w) => pts.add(w)); + if (k < placed.length - 1) [x.w1 - fadeW, x.w1 - 1e-4].forEach((w) => pts.add(w)); + }); + if (markW != null) [markW - muteFadeW, markW].forEach((w) => pts.add(Math.max(0, w))); + const ws = [...pts].filter((w) => w >= 0 && w <= acc).sort((a, b) => a - b); + gain.gain.setValueAtTime(level(ws[0]), t0 + ws[0]); + for (const w of ws.slice(1)) gain.gain.linearRampToValueAtTime(level(w), t0 + w); } - // The stop is a TIME on the context's clock, not start()'s duration - // argument: that one is buffer content, and a clock time means the same - // thing at every speed. - node.start(t0, stretched ? 0 : sch.offset); - node.stop(ctxStop); + const node = nodes[0]; const el = video.current; const s: Session = { @@ -1185,11 +1266,12 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { raf: 0, timers: [], from, - to: from + sch.duration, + to: end, rate, t0, ctxStop, mutedBefore: el?.muted ?? false, + ...(nodes.length > 1 ? { more: nodes.slice(1) } : {}), }; session.current = s; setPlayInfo({ @@ -1203,6 +1285,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { ctxStop, endedAt: null, }); + /** The source second playing `w` wall seconds in: its piece's, from its first. */ + const posAt = (w: number) => { + const x = placed.find((q) => w <= q.w1) ?? placed[placed.length - 1]; + return Math.min(x.p.from + x.sch.duration, x.p.from + Math.max(0, w - x.w0) * rate); + }; // The picture follows, muted. It is not what is being judged; a few // milliseconds of drift between the two is not worth a sync loop. @@ -1215,9 +1302,18 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { if (session.current === s) void el.play().catch(() => {}); }, START_LEAD * 1000), ); + // Each join: the picture jumps with the sound. + for (const x of placed.slice(1)) { + s.timers.push( + window.setTimeout(() => { + if (session.current === s) el.currentTime = Math.max(0, x.p.from - fetchStart); + }, (START_LEAD + x.w0) * 1000), + ); + } } - node.onended = () => { + const last = nodes[nodes.length - 1]; + last.onended = () => { if (session.current !== s) return; // How late the context clock reads at `ended`, mapped back onto the // source: what the playback measured, for the bench's own record. @@ -1225,7 +1321,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { session.current = null; cancelAnimationFrame(s.raf); for (const t of s.timers) clearTimeout(t); - node.disconnect(); + for (const n of nodes) n.disconnect(); gain.disconnect(); if (el) { pauseVideo(el); @@ -1247,7 +1343,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const tick = () => { if (session.current !== s) return; const now = ctx.currentTime; - const pos = playheadAt(from, t0, now, rate, sch.duration); + const pos = placed.length === 1 ? playheadAt(from, t0, now, rate, placed[0].sch.duration) : posAt(Math.max(0, now - t0)); if (now - painted >= 1 / 30) { painted = now; setPlayhead(pos); @@ -1747,6 +1843,146 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { placeMute(at, false); }, [sel.from, sel.to, placeMute]); + // ---- gaps inside the clip -------------------------------------------------- + // + // Seconds cut out of the clip's middle (gaps.mjs): it renders as ONE segment + // of jump cuts rather than as two clips with a crossfade, a second pip and a + // second card. A span is dragged on the waveform with Alt held (or after `g` + // / Select a gap) and written by Cut gap (or `g`); a click on a gap's band + // puts it back. Unlike the edges these are WRITTEN AT ONCE, through the one + // window writer (`gapAdd` / `gapRemove`), which refuses what the build would + // -- and leaves an undo point (auto-before-gaps) -- and Undo here writes the + // list back as it was. The rule is checked here first, with the same + // sentences, so a refusal is said before anything is sent. + const [gapSel, setGapSel] = useState<Span | null>(null); + const [gapPick, setGapPick] = useState(false); + const [gapUndo, setGapUndo] = useState<{ gaps: Span[]; what: string } | null>(null); + // A different clip: nothing selected, nothing to undo. + useEffect(() => { + setGapSel(null); + setGapPick(false); + setGapUndo(null); + }, [clip.id]); + /** Why `gaps` cannot be written on this clip as saved (the writer's own check), or null. */ + const gapRefusal = useCallback( + (gaps: Span[]) => { + const errs = validateGaps({ type: "clip", id: clip.id, start: clip.start, end: clip.end, cutStart: clip.cutStart, cutEnd: clip.cutEnd, muteFrom: clip.muteFrom, gaps }, "gap"); + return errs.length ? errs[0].replace(/^gap\.gaps\[\d+\] /, "the gap ").replace(/^gap\.muteFrom/, "the mute mark").replace(/^gap: /, "") : null; + }, + [clip.id, clip.start, clip.end, clip.cutStart, clip.cutEnd, clip.muteFrom], + ); + const writeGaps = useCallback( + async (patch: Record<string, unknown>, next: Span[], what: string) => { + const why = gapRefusal(next); + if (why) { + setNote(`not cut: ${why}`); + return false; + } + const before = clip.gaps ?? []; + const ok = await save(patch); + if (ok) { + setGapUndo({ gaps: before, what }); + setNote(`${what} — the cut plays ${gappedLength(gapSpan(clip).from, gapSpan(clip).to, next).toFixed(2)} s, one segment`); + } + return ok; + }, + [gapRefusal, save, clip], + ); + const cutGap = useCallback(async () => { + const s = gapSel; + if (!s) return; + const g = { from: round2(s.from), to: round2(s.to) }; + let next: Span[]; + try { + next = editGaps(clip.gaps ?? [], { add: g }); + } catch (e) { + setNote(e instanceof Error ? e.message : String(e)); + return; + } + const ok = await writeGaps({ gapAdd: g }, next, `cut ${hms(g.from)}–${hms(g.to)} out`); + if (ok) { + setGapSel(null); + setGapPick(false); + } + }, [gapSel, clip.gaps, writeGaps]); + const removeGap = useCallback( + (g: Span) => { + const next = (clip.gaps ?? []).filter((x) => x.from !== g.from || x.to !== g.to); + void writeGaps({ gapRemove: (g.from + g.to) / 2 }, next, `put ${hms(g.from)}–${hms(g.to)} back`); + }, + [clip.gaps, writeGaps], + ); + /** `G`: the gap the playhead is in (or at the edge of). */ + const removeGapAt = useCallback( + (t: number | null) => { + const g = t == null ? null : (clip.gaps ?? []).find((x) => t >= x.from - 0.05 && t <= x.to + 0.05); + if (!g) { + setNote("the playhead is not on a gap — play to it, or click its band"); + return; + } + removeGap(g); + }, + [clip.gaps, removeGap], + ); + const undoGap = useCallback(() => { + const u = gapUndo; + if (!u) return; + void save({ gaps: u.gaps }).then((ok) => { + if (!ok) return; + setGapUndo(null); + setNote(`undone — ${u.what} is reversed`); + }); + }, [gapUndo, save]); + /** A span dragged for a gap: kept inside the cut; under the shortest gap on release, dropped and said. */ + const selectGap = useCallback( + (s: Span, done: boolean) => { + const span = gapSpan(clip); + const from = Math.max(span.from, s.from); + const to = Math.min(span.to, s.to); + if (!done) { + setGapSel(to > from ? { from, to } : null); + return; + } + if (to - from < GAP_LIMITS.min) { + setGapSel(null); + if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`); + return; + } + setGapSel({ from, to }); + const why = gapRefusal(editGaps(clip.gaps ?? [], { add: { from: round2(from), to: round2(to) } })); + setNote(why ? `this span cannot be cut: ${why}` : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`); + }, + [clip, gapRefusal], + ); + // Alt + drag on the waveform selects a gap's span without arming anything. + const altDrag = useRef<{ id: number; at: number } | null>(null); + + // ---- the zoom ---------------------------------------------------------------- + // What the waveform shows of the cached window (bench/GapsZoom.tsx). Fit -- the + // whole window, today's view -- on every clip's arrival. + const zoom = useWaveZoom(view); + // Close in: the pauses between words, when the project has its words for this recording (the clip editor's). + const [nearWords, setNearWords] = useState<{ key: string; words: { start: number; end: number }[] | null } | null>(null); + const close = zoom.vis.to - zoom.vis.from <= DETAIL_SPAN; + const wordsKey = close ? `${clip.id}|${Math.floor(zoom.vis.from / 10) * 10}|${Math.ceil(zoom.vis.to / 10) * 10}` : null; + useEffect(() => { + if (!wordsKey || nearWords?.key === wordsKey) return; + let live = true; + const [, a, b] = wordsKey.split("|"); + const q = new URLSearchParams({ project: data.project, clip: clip.id, from: a, to: b, video: clip.video }); + fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" }) + .then((r) => (r.ok ? (r.json() as Promise<{ words?: { start: number; end: number }[] | null }>) : null)) + .then((j) => { + if (live) setNearWords({ key: wordsKey, words: j?.words ?? null }); + }) + .catch(() => { + if (live) setNearWords({ key: wordsKey, words: null }); + }); + return () => { + live = false; + }; + }, [wordsKey, nearWords?.key, data.project, clip.id, clip.video]); + // ---- keyboard ----------------------------------------------------------- useEffect(() => { const nudge = (which: "from" | "to", by: number) => @@ -1766,6 +2002,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const el = e.target as HTMLElement | null; if (el && /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return; const step = e.shiftKey ? 0.5 : 0.05; + // The zoom's and the gaps' keys leave the browser's own (Ctrl+F, Ctrl+Z …) alone. + if ((e.ctrlKey || e.metaKey || e.altKey) && "zZfFgG".includes(e.key)) return; switch (e.key) { // The SHIFTED character too, on every edge key. `e.shiftKey` selects // the 0.5 s step, but shift also changes what the key IS -- `Shift+.` @@ -1843,7 +2081,33 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { } placeMute(mute + (e.key === ";" || e.key === ":" ? -step : step), true); break; + // The waveform's zoom: z in, Z out (at the playhead when it is in view), f fit, F to the selection. + case "z": + zoom.zoomIn(playheadRef.current != null && playheadRef.current >= zoom.vis.from && playheadRef.current <= zoom.vis.to ? playheadRef.current : null); + break; + case "Z": + zoom.zoomOut(playheadRef.current != null && playheadRef.current >= zoom.vis.from && playheadRef.current <= zoom.vis.to ? playheadRef.current : null); + break; + case "f": + zoom.fit(); + break; + case "F": + zoom.to(gapSel ?? sel); + break; + // Gaps: g cuts the selected span (or starts selecting one), G puts back the gap at the playhead. + case "g": + if (gapSel) void cutGap(); + else setGapPick((v) => !v); + break; + case "G": + removeGapAt(playheadRef.current); + break; case "Escape": + if (gapPick || gapSel) { + setGapPick(false); + setGapSel(null); + break; + } if (!mutePick) return; setMutePick(false); break; @@ -1874,6 +2138,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { muteAtPlayhead, clearMute, placeMute, + zoom, + gapSel, + gapPick, + cutGap, + removeGapAt, ]); const refresh = useCallback(async (): Promise<ClipBenchData | null> => { @@ -2139,6 +2408,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { const span = Math.max(1e-6, view.to - view.from); const pct = (t: number) => `${((t - view.from) / span) * 100}%`; + // What the waveform shows (the zoom's), for everything drawn over it. + const zspan = Math.max(1e-6, zoom.vis.to - zoom.vis.from); + const zpct = (t: number) => `${((t - zoom.vis.from) / zspan) * 100}%`; const previewLine = attributionLine( { @@ -3211,9 +3483,45 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { {/* ---- the instrument ---- On a phone the edge strip is the instrument; this one is still there, folded under Window, for the mute mark. */} - <div className={cn("relative", secBody("window", "max-md:order-[52]"))}> + <div className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> + {/* Zoomed: round ticks over what is shown. */} + {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} + <div + ref={zoom.ref} + data-wave-box="" + data-wave-vis={`${zoom.vis.from}-${zoom.vis.to}`} + className="relative" + // Alt + drag: a span for a gap, never an edge (the waveform's own drag is held off). + onPointerDownCapture={(e) => { + if (!e.altKey || gapPick || mutePick) return; + e.preventDefault(); + e.stopPropagation(); + e.currentTarget.setPointerCapture(e.pointerId); + const r = e.currentTarget.getBoundingClientRect(); + const at = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + altDrag.current = { id: e.pointerId, at }; + selectGap({ from: at, to: at }, false); + }} + onPointerMoveCapture={(e) => { + const d = altDrag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + const r = e.currentTarget.getBoundingClientRect(); + const t = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + selectGap({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); + }} + onPointerUpCapture={(e) => { + const d = altDrag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + altDrag.current = null; + const r = e.currentTarget.getBoundingClientRect(); + const t = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + selectGap({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); + }} + > <Waveform - view={view} + view={zoom.vis} sel={sel} cand={{ from: clip.start, to: clip.end }} words={cues.map((c) => ({ start: c.start, end: c.end, w: c.text.slice(0, 24) }))} @@ -3229,20 +3537,32 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { and a hatch over what is silent to the end of the selection. In the interaction colour, like the handles -- it is an edit, not a reading -- and never in the way of a drag. */} - {mute != null && mute >= view.from && mute <= view.to && ( + {/* The gaps, the span being selected for one, and close in the silences and the pauses between words. */} + <GapLayer + vis={zoom.vis} + gaps={clip.gaps ?? []} + selection={gapSel} + picking={gapPick && !mutePick} + silences={renderEdges?.silences ?? null} + words={nearWords?.words ?? null} + busy={!!busy} + onRemove={removeGap} + onSelect={selectGap} + /> + {mute != null && mute >= zoom.vis.from && mute <= zoom.vis.to && ( <> <div data-mute-span="" className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-dim)_22%,transparent)_0_3px,transparent_3px_7px)]" style={{ - left: pct(mute), - width: `calc(${pct(Math.max(mute, sel.to))} - ${pct(mute)})`, + left: zpct(mute), + width: `calc(${zpct(Math.max(mute, Math.min(sel.to, zoom.vis.to)))} - ${zpct(mute)})`, }} /> <div data-mute-marker={mute} className="pointer-events-none absolute top-0 h-full border-l-2 border-dashed border-[var(--color-sel)]" - style={{ left: pct(mute) }} + style={{ left: zpct(mute) }} > <span className="absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-sel)]"> mute @@ -3251,20 +3571,95 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </> )} {/* Where the render will actually cut: each edge snapped to its silence, faint. */} - <RenderGhosts edges={renderEdges} view={view} /> + <RenderGhosts edges={renderEdges} view={zoom.vis} /> {/* Armed: the next click places the mark rather than an edge. */} {mutePick && ( <div data-mute-pick-layer="" - className="absolute inset-0 cursor-crosshair rounded-md outline outline-1 outline-[var(--color-sel)]" + className="absolute inset-0 z-[8] cursor-crosshair rounded-md outline outline-1 outline-[var(--color-sel)]" onPointerDown={(e) => { const r = e.currentTarget.getBoundingClientRect(); const frac = Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))); - placeMute(view.from + frac * span, true); + placeMute(zoom.vis.from + frac * zspan, true); }} /> )} </div> + {/* Zoomed: the whole cached window, what is shown of it -- drag to pan. */} + {zoom.zoomed && <ZoomOverview zoom={zoom} whole={view} peaks={peaks} sel={sel} gaps={clip.gaps ?? []} />} + {/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */} + <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> + {/* ---- GAPS inside the clip ---- + Seconds cut out of its middle: it renders as one segment of + jump cuts. Written at once (not drafted like the edges), and + every playback here skips them, as the cut will. */} + <span data-gaps={(clip.gaps ?? []).map((g) => `${g.from}-${g.to}`).join(",")} className="flex flex-wrap items-center gap-1.5"> + {(clip.gaps ?? []).length ? ( + <span data-gaps-summary="" className="num text-[var(--color-text)]"> + {(clip.gaps ?? []).length} gap{(clip.gaps ?? []).length === 1 ? "" : "s"}{" "} + <span className="text-[var(--color-dim)]"> + (the cut plays {gappedLength(gapSpan(clip).from, gapSpan(clip).to, clip.gaps ?? []).toFixed(2)} s of{" "} + {(gapSpan(clip).to - gapSpan(clip).from).toFixed(2)} s, one segment) + </span> + </span> + ) : ( + <span className="text-[var(--color-dim)]">no gaps — the cut plays whole</span> + )} + <button + type="button" + data-gap-pick={gapPick ? "armed" : ""} + aria-pressed={gapPick} + className={`${buttonVariants({ variant: "outline", size: "sm" })}${gapPick ? " bg-panel-2 border-muted" : ""}`} + title="drag on the waveform to select seconds to cut out of the clip (g; or hold Alt and drag; Esc cancels)" + onClick={() => setGapPick((v) => !v)} + > + {gapPick ? "Drag on the waveform…" : "Select a gap"} + </button> + {gapSel && ( + <> + <button + type="button" + data-gap-cut="" + className={buttonVariants({ size: "sm" })} + disabled={!!busy || gapSel.to - gapSel.from < GAP_LIMITS.min} + title="cut the selected seconds out of the clip (g)" + onClick={() => void cutGap()} + > + Cut gap {hms(gapSel.from)}–{hms(gapSel.to)} ({(gapSel.to - gapSel.from).toFixed(2)} s) + </button> + <button + type="button" + data-gap-hear="" + className={buttonVariants({ variant: "outline", size: "sm" })} + title="two seconds either side, the selection skipped: the jump as the cut will play it" + onClick={() => void play(Math.max(sel.from, gapSel.from - 2), Math.min(sel.to, gapSel.to + 2), { extra: gapSel })} + > + Hear it + </button> + <button + type="button" + data-gap-play-span="" + className={buttonVariants({ variant: "outline", size: "sm" })} + title="play what the selection would take out" + onClick={() => void play(gapSel.from, gapSel.to, { through: true })} + > + Play the span + </button> + </> + )} + {gapUndo && ( + <button type="button" data-gap-undo="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={!!busy} onClick={undoGap} title={`undo: ${gapUndo.what}`}> + Undo + </button> + )} + </span> + <span className="micro max-md:hidden"> + <kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "} + <kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead + </span> + <ZoomControls zoom={zoom} whole={view} selection={gapSel ?? sel} playhead={playhead} /> + </div> + </div> {/* Offered at the edge of the cache, as always -- and also whenever the rail has something to read past it. Having just read the next @@ -3383,6 +3778,16 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </div> ); })} + {/* The GAPS: cut out of the clip's middle. */} + {(clip.gaps ?? []).map((g) => ( + <div + key={`rail-gap-${g.from}`} + data-rail-gap={`${g.from}-${g.to}`} + aria-hidden + className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-dirty)_26%,transparent)_0_4px,transparent_4px_8px)]" + style={{ left: rpct(g.from), width: `calc(${rpct(g.to)} - ${rpct(g.from)})` }} + /> + ))} {/* The CUT, as an inner pair of markers: what plays, inside what was reviewed. */} {clip.cutStart != null && clip.cutEnd != null && ( diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -108,6 +108,10 @@ export default async function ClipBenchPage({ muteFrom: ((manifest.timeline ?? []) as { id: string; muteFrom?: number }[]).find((e) => e.id === clipId) ?.muteFrom ?? null, + // Seconds cut out of its middle (gaps.mjs), likewise from the manifest's own entry. + gaps: + ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) + ?.gaps ?? [], verdict: entry.verdict === "confirmed" || entry.verdict === "incorrect" ? entry.verdict : null, // From the manifest's own entry: what the on-screen panel says over this diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx @@ -0,0 +1,392 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import type { Peaks } from "@/components/Waveform"; +import { buttonVariants } from "@/components/ui/button"; +import { alpha, usePalette } from "@/components/ui/use-palette"; +import { cn } from "@/lib/utils"; +import { + DETAIL_SPAN, ZOOM_STEP, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo, +} from "@/lib/report/benchZoom.mjs"; + +// --------------------------------------------------------------------------- +// THE BENCH WAVEFORM, CLOSER (ClipBench.tsx's desk): a zoom on the waveform +// where edges, the mute mark and a clip's GAPS (umtool-report-to-video +// gaps.mjs: seconds cut out of its middle) are set. +// +// zoom Ctrl/⌘ + wheel (a trackpad's pinch is one) at the pointer, the +// second under it staying there; − / + / Fit / Zoom to selection; +// z in, Z out, f fit, F to the selection. The waveform, every mark +// over it and the handles' drags all work on what is shown. +// pan the wheel (either axis) while zoomed; a drag on the overview +// strip under it, which shows the whole cached window, what is +// shown in it, the selection and the gaps; a two-finger pinch on it. +// closer a ruler of round ticks, and at DETAIL_SPAN seconds or less the +// measured silences (the cut-points route's, the build's own) and +// the pauses between words, so a gap's edge goes between two words. +// gaps each a hatched band over the waveform, `cut` on it; a click on +// one removes it. A span for a new one is dragged with Alt held +// (or after `g` / Select a gap); Cut gap (or `g`) writes it. +// +// At fit -- the default, and on every clip's arrival -- the waveform is exactly +// what it was: no ruler, no overview, nothing moved. +// --------------------------------------------------------------------------- + +export type Span = { from: number; to: number }; + +/** + * What the waveform shows (`vis`) and the zoom's moves, over `whole` (the + * cached window). Null state is fit. `ref` goes on the element the wheel is + * read over. + */ +export function useWaveZoom(whole: Span) { + const [zv, setZv] = useState<Span | null>(null); + // A different window (a fetch widened it, the next clip): what was shown, kept inside it. + const wholeKey = `${whole.from}|${whole.to}`; + const lastWhole = useRef(wholeKey); + useEffect(() => { + if (lastWhole.current === wholeKey) return; + lastWhole.current = wholeKey; + setZv((v) => (v ? (isFit(clampVis(v, whole), whole) ? null : clampVis(v, whole)) : null)); + // `whole` is read through its key. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [wholeKey]); + const vis = zv ?? whole; + const zoomed = !isFit(zv, whole); + const set = useCallback((v: Span) => setZv(isFit(v, whole) ? null : v), [whole]); + const zoomIn = useCallback((at?: number | null) => set(zoomAt(zv, whole, at ?? (vis.from + vis.to) / 2, ZOOM_STEP)), [zv, whole, vis.from, vis.to, set]); + const zoomOut = useCallback((at?: number | null) => set(zoomAt(zv, whole, at ?? (vis.from + vis.to) / 2, 1 / ZOOM_STEP)), [zv, whole, vis.from, vis.to, set]); + const fit = useCallback(() => setZv(null), []); + const to = useCallback((range: Span) => set(zoomTo(range, whole)), [whole, set]); + const pan = useCallback((dt: number) => set(panBy(zv, whole, dt)), [zv, whole, set]); + const centre = useCallback((t: number) => set(centreOn(zv, whole, t)), [zv, whole, set]); + + // The wheel, read natively: React's is passive, and a zoom must not also scroll the page. + const el = useRef<HTMLDivElement | null>(null); + const state = useRef({ zv, whole, vis, zoomed, set }); + state.current = { zv, whole, vis, zoomed, set }; + // Attached as the element mounts (a callback ref: the waveform is not on the page at the first render). + const detach = useRef<(() => void) | null>(null); + const ref = useCallback((node: HTMLDivElement | null) => { + detach.current?.(); + detach.current = null; + el.current = node; + if (!node) return; + const on = (e: WheelEvent) => { + const s = state.current; + const r = node.getBoundingClientRect(); + const at = s.vis.from + ((e.clientX - r.left) / Math.max(1, r.width)) * (s.vis.to - s.vis.from); + if (e.ctrlKey || e.metaKey) { + e.preventDefault(); + s.set(zoomAt(s.zv, s.whole, at, wheelFactor(e.deltaY, e.deltaMode))); + return; + } + if (!s.zoomed) return; + // Zoomed: the wheel pans, either axis (shift turns a vertical wheel sideways on most systems already). + const d = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY; + if (!d) return; + e.preventDefault(); + const px = e.deltaMode === 1 ? d * 16 : e.deltaMode === 2 ? d * 400 : d; + s.set(panBy(s.zv, s.whole, (px / Math.max(1, r.width)) * (s.vis.to - s.vis.from))); + }; + node.addEventListener("wheel", on, { passive: false }); + detach.current = () => node.removeEventListener("wheel", on); + }, []); + + return { vis, zoomed, ref, zoomIn, zoomOut, fit, to, pan, centre, set }; +} + +export type WaveZoom = ReturnType<typeof useWaveZoom>; + +const btn = buttonVariants({ variant: "outline", size: "sm" }); + +/** − / + / Fit / Zoom to selection, and how much is shown. */ +export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZoom; whole: Span; selection: Span | null; playhead: number | null }) { + const at = playhead != null && playhead >= zoom.vis.from && playhead <= zoom.vis.to ? playhead : null; + const shown = zoom.vis.to - zoom.vis.from; + return ( + <span data-wave-zoom={zoom.zoomed ? `${zoom.vis.from.toFixed(2)}-${zoom.vis.to.toFixed(2)}` : "fit"} className="flex flex-wrap items-center gap-1"> + <span className="micro">zoom</span> + <button type="button" data-zoom-out="" className={btn} disabled={!zoom.zoomed} title="zoom out (Z; Ctrl/⌘ + wheel)" onClick={() => zoom.zoomOut(at)}> + − + </button> + <button type="button" data-zoom-in="" className={btn} title="zoom in at the playhead, else the middle (z; Ctrl/⌘ + wheel at the pointer)" onClick={() => zoom.zoomIn(at)}> + + + </button> + <button type="button" data-zoom-fit="" className={btn} disabled={!zoom.zoomed} title="the whole cached window (f)" onClick={zoom.fit}> + Fit + </button> + <button + type="button" + data-zoom-selection="" + className={btn} + disabled={!selection} + title="zoom to the gap you are selecting, else the selection (F)" + onClick={() => selection && zoom.to(selection)} + > + Zoom to selection + </button> + <span className="num text-[11px] text-[var(--color-dim)]" data-zoom-shown={shown.toFixed(2)}> + {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : "whole window"} + </span> + </span> + ); +} + +/** The ruler over the zoomed waveform: round ticks, labelled. */ +export function ZoomRuler({ vis }: { vis: Span }) { + const { step, ticks } = rulerFor(vis); + const span = Math.max(1e-6, vis.to - vis.from); + return ( + <div data-zoom-ruler={step} aria-hidden className="relative h-4 w-full select-none overflow-hidden font-mono text-[9.5px] leading-4 text-[var(--color-dim)]"> + {ticks.map((t) => ( + <span key={t} className="absolute top-0 h-full border-l border-[var(--color-line)] pl-0.5" style={{ left: `${((t - vis.from) / span) * 100}%` }}> + {tickLabel(t, step)} + </span> + ))} + </div> + ); +} + +/** + * Over the waveform (absolutely placed, the waveform's box): the gaps, the + * span being selected for one, and -- close in -- the silences and the pauses + * between words. `onRemove` on a gap's click; while `picking` (or with Alt + * held over the waveform, the caller's capture handler) a drag selects a span. + */ +export function GapLayer({ + vis, + gaps, + selection, + picking, + silences, + words, + busy, + onRemove, + onSelect, +}: { + vis: Span; + gaps: Span[]; + selection: Span | null; + picking: boolean; + silences: Span[] | null; + words: { start: number; end: number }[] | null; + busy: boolean; + onRemove: (g: Span) => void; + onSelect: (s: Span, done: boolean) => void; +}) { + const span = Math.max(1e-6, vis.to - vis.from); + const pct = (t: number) => `${((Math.min(vis.to, Math.max(vis.from, t)) - vis.from) / span) * 100}%`; + const width = (a: number, b: number) => `calc(${pct(b)} - ${pct(a)})`; + const inView = (s: Span) => s.to > vis.from && s.from < vis.to; + const close = vis.to - vis.from <= DETAIL_SPAN; + const quiet = close ? quietPoints({ words, silences }, vis.from, vis.to) : []; + const drag = useRef<{ id: number; at: number } | null>(null); + const tAt = (el: HTMLElement, clientX: number) => { + const r = el.getBoundingClientRect(); + return vis.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * span; + }; + return ( + <> + {close && + (silences ?? []).filter(inView).map((s) => ( + <div + key={`sil-${s.from}`} + data-wave-silence={`${s.from.toFixed(2)}-${s.to.toFixed(2)}`} + aria-hidden + className="pointer-events-none absolute bottom-0 h-2 rounded-sm bg-[color-mix(in_srgb,var(--color-meter)_35%,transparent)]" + style={{ left: pct(s.from), width: width(s.from, s.to) }} + /> + ))} + {quiet.map((t) => ( + <div key={`q-${t}`} data-wave-quiet={t} aria-hidden className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-meter)_55%,transparent)]" style={{ left: pct(t) }} /> + ))} + {gaps.filter(inView).map((g) => ( + <button + key={`gap-${g.from}`} + type="button" + data-gap-band={`${g.from}-${g.to}`} + disabled={busy} + title={`a gap: ${g.from.toFixed(2)}–${g.to.toFixed(2)} (${(g.to - g.from).toFixed(2)} s) is cut out of the clip — click to put it back`} + onPointerDown={(e) => e.stopPropagation()} + onClick={() => onRemove(g)} + className="absolute top-0 z-[5] h-full cursor-pointer overflow-hidden border-x border-[var(--color-dirty)] p-0 text-left [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-ground)_70%,transparent)_0_5px,color-mix(in_srgb,var(--color-dirty)_22%,transparent)_5px_9px)]" + style={{ left: pct(g.from), width: width(g.from, g.to) }} + > + <span className="pointer-events-none absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-dirty)]">cut</span> + </button> + ))} + {selection && inView(selection) && ( + <div + data-gap-selection={`${selection.from.toFixed(2)}-${selection.to.toFixed(2)}`} + aria-hidden + className="pointer-events-none absolute top-0 z-[6] h-full border-x-2 border-dashed border-[var(--color-dirty)] bg-[color-mix(in_srgb,var(--color-dirty)_14%,transparent)]" + style={{ left: pct(selection.from), width: width(selection.from, selection.to) }} + /> + )} + {picking && ( + <div + data-gap-pick-layer="" + className="absolute inset-0 z-[7] cursor-crosshair rounded-md outline outline-1 outline-[var(--color-dirty)]" + onPointerDown={(e) => { + e.currentTarget.setPointerCapture(e.pointerId); + const at = tAt(e.currentTarget, e.clientX); + drag.current = { id: e.pointerId, at }; + onSelect({ from: at, to: at }, false); + }} + onPointerMove={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId) return; + const t = tAt(e.currentTarget, e.clientX); + onSelect({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); + }} + onPointerUp={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId) return; + drag.current = null; + const t = tAt(e.currentTarget, e.clientX); + onSelect({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); + }} + onPointerCancel={() => { + drag.current = null; + }} + /> + )} + </> + ); +} + +const OVERVIEW_H = 22; + +/** + * The whole cached window under a zoomed waveform: its peaks small, the + * selection, the gaps, and the stretch shown -- dragged to pan, clicked + * elsewhere to centre there, pinched (two fingers) to zoom. + */ +export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom; whole: Span; peaks: Peaks | null; sel: Span; gaps: Span[] }) { + const pal = usePalette(); + const box = useRef<HTMLDivElement | null>(null); + const canvas = useRef<HTMLCanvasElement | null>(null); + const [width, setWidth] = useState(600); + useEffect(() => { + const el = box.current; + if (!el) return; + const ro = new ResizeObserver(() => setWidth(el.clientWidth || 600)); + ro.observe(el); + setWidth(el.clientWidth || 600); + return () => ro.disconnect(); + }, []); + const W = Math.max(1e-6, whole.to - whole.from); + const pct = (t: number) => `${((Math.min(whole.to, Math.max(whole.from, t)) - whole.from) / W) * 100}%`; + useEffect(() => { + const cv = canvas.current; + if (!cv) return; + const dpr = window.devicePixelRatio || 1; + cv.width = Math.max(1, Math.floor(width * dpr)); + cv.height = Math.floor(OVERVIEW_H * dpr); + const g = cv.getContext("2d"); + if (!g) return; + g.setTransform(dpr, 0, 0, dpr, 0, 0); + g.clearRect(0, 0, width, OVERVIEW_H); + const mid = OVERVIEW_H / 2; + const toX = (t: number) => ((t - whole.from) / W) * width; + g.fillStyle = alpha(pal.signal, 0.12); + g.fillRect(toX(sel.from), 0, Math.max(1, toX(sel.to) - toX(sel.from)), OVERVIEW_H); + if (peaks && peaks.max.length) { + const n = peaks.max.length; + const pSpan = Math.max(1e-6, peaks.to - peaks.from); + g.fillStyle = pal["seam-2"]; + for (let i = 0; i < n; i += 1) { + const t0 = peaks.from + (i / n) * pSpan; + const x = toX(t0); + if (x < -1 || x > width + 1) continue; + const y0 = mid - peaks.max[i] * (mid - 2); + const y1 = mid - peaks.min[i] * (mid - 2); + g.fillRect(x, Math.min(y0, y1), Math.max(1, width / n), Math.max(1, Math.abs(y1 - y0))); + } + } + g.fillStyle = alpha(pal.reject, 0.45); + for (const gp of gaps) g.fillRect(toX(gp.from), 0, Math.max(1, toX(gp.to) - toX(gp.from)), OVERVIEW_H); + }, [peaks, width, whole.from, W, sel.from, sel.to, gaps, pal]); + + const drag = useRef<{ id: number; grab: number } | null>(null); + const tAt = (clientX: number) => { + const r = box.current?.getBoundingClientRect(); + if (!r) return whole.from; + return whole.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * W; + }; + // Two fingers: the distance between them is the zoom, about their middle. + const pinch = useRef<{ d: number; mid: number } | null>(null); + useEffect(() => { + const el = box.current; + if (!el) return; + const dist = (e: TouchEvent) => Math.abs(e.touches[0].clientX - e.touches[1].clientX); + const midOf = (e: TouchEvent) => (e.touches[0].clientX + e.touches[1].clientX) / 2; + const start = (e: TouchEvent) => { + if (e.touches.length !== 2) return; + e.preventDefault(); + drag.current = null; + pinch.current = { d: Math.max(8, dist(e)), mid: midOf(e) }; + }; + const move = (e: TouchEvent) => { + const p = pinch.current; + if (!p || e.touches.length !== 2) return; + e.preventDefault(); + const d = Math.max(8, dist(e)); + const r = el.getBoundingClientRect(); + const at = whole.from + ((midOf(e) - r.left) / Math.max(1, r.width)) * W; + zoom.set(zoomAt(zoom.vis, whole, at, d / p.d)); + pinch.current = { d, mid: midOf(e) }; + }; + const end = () => { + pinch.current = null; + }; + el.addEventListener("touchstart", start, { passive: false }); + el.addEventListener("touchmove", move, { passive: false }); + el.addEventListener("touchend", end); + return () => { + el.removeEventListener("touchstart", start); + el.removeEventListener("touchmove", move); + el.removeEventListener("touchend", end); + }; + }, [zoom, whole, W]); + + return ( + <div + ref={box} + data-zoom-overview="" + className="relative w-full touch-none select-none overflow-hidden rounded border border-[var(--color-line)] bg-[var(--color-panel-2)]" + style={{ height: OVERVIEW_H }} + onPointerDown={(e) => { + if (pinch.current) return; + e.currentTarget.setPointerCapture(e.pointerId); + const t = tAt(e.clientX); + const inside = t >= zoom.vis.from && t <= zoom.vis.to; + // On the shown stretch: grab it where it was taken. Elsewhere: centre there, then drag. + if (!inside) zoom.centre(t); + const from = inside ? zoom.vis.from : t - (zoom.vis.to - zoom.vis.from) / 2; + drag.current = { id: e.pointerId, grab: t - from }; + }} + onPointerMove={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId || pinch.current) return; + const span = zoom.vis.to - zoom.vis.from; + zoom.set(clampVis({ from: tAt(e.clientX) - d.grab, to: tAt(e.clientX) - d.grab + span }, whole)); + }} + onPointerUp={() => { + drag.current = null; + }} + onPointerCancel={() => { + drag.current = null; + }} + > + <canvas ref={canvas} aria-hidden className="absolute inset-0 h-full w-full" /> + <div + data-zoom-window={`${zoom.vis.from.toFixed(2)}-${zoom.vis.to.toFixed(2)}`} + aria-hidden + className={cn("pointer-events-none absolute top-0 h-full rounded-sm border-2 border-[var(--color-sel)] bg-[color-mix(in_srgb,var(--color-sel)_12%,transparent)]")} + style={{ left: pct(zoom.vis.from), width: `calc(${pct(zoom.vis.to)} - ${pct(zoom.vis.from)})` }} + /> + </div> + ); +} diff --git a/umtool/components/projects/bench/RenderGhosts.tsx b/umtool/components/projects/bench/RenderGhosts.tsx @@ -38,7 +38,8 @@ function playWindowOf(sel: { from: number; to: number }, cut: { cutStart: number /** One edge as the render will cut it: where (source s), how far from the edge drawn, and whether a silence moved it. */ export type GhostEdge = { at: number; offset: number; snapped: boolean }; -export type RenderEdges = { start: GhostEdge; end: GhostEdge } | null; +/** The two edges, and the silences they were snapped to (source seconds: the zoomed waveform draws them). */ +export type RenderEdges = { start: GhostEdge; end: GhostEdge; silences: { from: number; to: number }[] } | null; /** "render: +0.52 s" (or "render: here"): a ghost's words. */ export const ghostLabel = (g: GhostEdge) => @@ -52,7 +53,7 @@ export const ghostLabel = (g: GhostEdge) => */ export function useRenderEdges( project: string, - clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null }, + clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null; gaps?: { from: number; to: number }[] }, sel: { from: number; to: number }, /** Walking a take: the clip is the take's (the cut-points route reads its manifest). */ take: string | null = null, @@ -81,10 +82,14 @@ export function useRenderEdges( snapLead: got.knobs.snapLead ?? undefined, snapTail: got.knobs.snapTail ?? undefined, }; - const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render, locked: row.locked ?? null }); + // The clip's gaps: no edge snaps across one (snap.mjs, as the build). + const gaps = clip.gaps?.length ? clip.gaps : null; + const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render, locked: row.locked ?? null, gaps }); + const fs = row.fetchStart; return { start: { at: cut.start, offset: Number((cut.start - pw.from).toFixed(3)), snapped: cut.snapped.start }, end: { at: cut.end, offset: Number((cut.end - pw.to).toFixed(3)), snapped: cut.snapped.end }, + silences: row.silences.map((x) => ({ from: fs + x.s, to: fs + x.e })), }; } diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx @@ -155,8 +155,8 @@ export default function LiveDeckPreview({ // ---- the clock --------------------------------------------------------------- const schedule = doc?.schedule ?? null; const clock = useMemo( - () => (schedule ? liveClock(schedule, { id: clip.id, start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd }, { leadIn: doc?.leadIn ?? 0.4 }) : null), - [schedule, clip.id, clip.start, clip.end, cut.cutStart, cut.cutEnd, doc?.leadIn], + () => (schedule ? liveClock(schedule, { id: clip.id, start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd, gaps: clip.gaps ?? null }, { leadIn: doc?.leadIn ?? 0.4 }) : null), + [schedule, clip.id, clip.start, clip.end, cut.cutStart, cut.cutEnd, clip.gaps, doc?.leadIn], ); const clockRef = useRef(clock); clockRef.current = clock; 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/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -2,7 +2,7 @@ import { useMemo, useRef, useState } from "react"; import { cn } from "@/lib/utils"; -import { counterAt, dateRamp, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; +import { counterAt, dateRamp, gapJoins, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; type PlayItem = ReturnType<typeof playPlan>["items"][number]; @@ -198,6 +198,20 @@ export default function ReelStrip({ ); })} + {/* a clip's gaps (gaps.mjs): a jump cut inside its cell, where the seconds it leaves out were */} + {items.flatMap((it) => + gapJoins(it).map((g) => ( + <span + key={`gap:${it.id}:${g.from}`} + data-play-gap={`${it.id}@${g.at}`} + title={`${it.id}: ${(g.to - g.from).toFixed(2)} s cut out (${g.from.toFixed(2)}–${g.to.toFixed(2)}) — a jump cut`} + aria-hidden + className="pointer-events-none absolute top-0 z-[1] h-full w-0 border-l border-dashed border-[var(--color-dirty)]" + style={{ left: pctOf(g.at, total) }} + /> + )), + )} + {/* the entries skipped (ruled incorrect): a greyed, struck-through tag where they would play */} {skipped.map((x) => ( <span diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -1,5 +1,6 @@ import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; -import { itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; +import { inGap } from "umtool-report-to-video/gaps"; +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 +181,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 +342,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) }; } @@ -639,9 +642,16 @@ export class PlayEngine { missing = true; continue; } - drawn.push({ i: l.i, mediaTime: l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp / 1e6 }); + const mediaTime = l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp / 1e6; const it = items[l.i]; const e = this.entries.get(it.id); + // A clip's gap (gaps.mjs) never plays: the frames a decoder (or a seeking element) passes + // on its way across one are not drawn -- the last picture holds until the far side's is here. + if (it.clip?.gaps?.length && inGap(mediaTime + (e?.media?.from ?? 0), it.clip.gaps)) { + missing = true; + continue; + } + drawn.push({ i: l.i, mediaTime }); const src = sourceAt(it, t); const b = e?.blur && this.blurRendered ? e.blur : null; const blur = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity) diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -152,6 +152,18 @@ c01: 43.12–61.48 -> 43.12–61.48 `--no-lock-end` **removes** the key rather than writing `false`: these manifests are read by humans, and `"lockEnd": false` reads like a decision. +Gaps — seconds cut out of a clip's middle, so it renders as one segment of jump cuts +(knobs.md, "Gaps inside a clip") — go through the same writer, applied to the list as +it is when the write lands, each an undo point (`umtool timeline <p> undo`): + +``` +$ umtool window ferret-rescue c01 --gap 50.2-52.9 --gap 57.1-57.8 +c01: 43.12–61.48 -> 43.12–61.48 + gaps: −50.20–52.90, −57.10–57.80 — the cut plays 14.96s of 18.36s, one segment of jump cuts +``` + +`--gap-remove 51` takes out the gap holding that second; `--gaps ''` clears them all. + ## `link` names the article a project is the video of An article links to a project its iterations made, to one whose manifest names it diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -31,6 +31,7 @@ that generates it ([notes.md](notes.md)). | `blur.strength` — the blur's radius, % of the picture's height as it plays (2–15; default 5) | Blur, **strength** | `blur.strength=8` | same | | `blur.from`, `blur.to` — source seconds inside the clip's window: blur only that span (either alone runs to the clip's edge; default the whole clip) | Blur, **From playhead** / **To playhead**, **Whole clip** | `blur.from=231.5 blur.to=262` | same | | `layout` — `finale`: the deck's finale layout for this clip (`render.chrome.deck.finale`); `clip` is the default | — | `umtool set <p> <clip> layout=finale` | — | +| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band puts it back (`G`: the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps}` | `key=` (nothing after the `=`) clears a knob; in umtool, **Clear** beside a field (Audio: **Clear all**). A claim's knobs are read from the clip that **stamps** it — the last clip carrying the claim id; the box on any other @@ -38,6 +39,49 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +## Gaps inside a clip + +A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than +making two clips (a crossfade, a second rail pip, a second subtitle card). `gaps: [{from, to}]` on the clip, in SOURCE +seconds (`report-to-video/gaps.mjs` is the rule and both clocks). + +- **The rule** (the writer's, the build's validators' and `umtool check`'s `clip-gap-invalid`, blocking): each gap + inside the clip's cut (`cutStart`–`cutEnd`, else its extent), at least 0.2 s, at most 12 of them, in order, apart, + and at least 0.5 s of material before the first, between any two and after the last. A window, cut or mark save that + would leave a gap outside the cut is refused, as the mute mark's is. **A `muteFrom` or a claim mark's `at` strictly + inside a gap is refused** (on its edge is fine: it lands at the join) — it names a second the cut never plays, and + clamping it to the join would move a decision made by ear. A split inside a gap is refused (split at its edge); a + split gives each half the gaps on its side; a merge keeps both lists. +- **The render**: one segment whose footage is the kept pieces joined with hard cuts — the picture trimmed on the frame + grid, the sound cut at the same instants with a 25 ms fade out and in at each join so nothing clicks. Its length is + the kept seconds. The cut record (`segments/<id>.cut.json`) names the `gaps` it left out, and everything that maps a + source second onto the cut reads them: the mute mark and a locked edge's silence, a claim stamped at a source second, + a deck claim check, the stats region, the effects' words and punch-ins, captions, a partial blur, room's muted tail, + the estimate's length, a trailer's beats (a beat across a gap plays the master's jump cut). The QR, the pip and the + header are the clip's, unchanged; the subtitle's clock part is the clip's `cite` — a fixed second, so it does not + move (a `cite` inside a gap is noted at build). No edge snaps across a gap, nor nearer one than 0.5 s. Loudness is + measured over the whole cut, gaps included. A gap changed re-renders that clip's segment only. A montage cuts to its + phrase: gaps are not applied there (noted). Absent or `[]`, the render is byte for byte what it was. +- **The bench** draws each gap as a hatched band on the waveform (and on the cue rail); every playback there skips + them as the cut will. Gap writes go through the one window writer at once (not drafted like the edges), each an undo + point (`auto-before-gaps`: `umtool timeline <p> undo`), and **Undo** beside them writes the list back. +- **Play the cut** plays the clip as one item: its sound one span per kept piece on the cut's clock with the same + fades, the picture past the gap at the join, the clock and the scrub bar in cut seconds, a dashed tick on the reel + strip at each jump. +- **`umtool timeline <p> ls`** shows a clip's gaps and what it then plays. + +### The bench waveform's zoom + +Where edges, the mute mark and gaps are set. **Ctrl/⌘ + wheel** (a trackpad pinch is one) zooms at the pointer — the +second under it stays there; **−** / **+** / **Fit** / **Zoom to selection** (the gap being selected, else the +selection); keys `z` in, `Z` out, `f` fit, `F` to the selection. Zoomed, the wheel pans (either axis), and an +**overview** strip under the waveform shows the whole cached window with what is shown, the selection and the gaps: +drag it to pan, click elsewhere to centre, pinch it with two fingers. A ruler of round ticks sits over a zoomed +waveform; at 20 s across or closer it also draws the measured silences (the cut-points route's, the build's own) and +the pauses between words (when the project's words file is this recording's), so a gap's edge goes between two words. +At fit — the default, on every clip — the waveform is what it always was. (Play the cut's reel strip is a scrubber; +nothing is trimmed there, so it has no zoom.) + ## A clip's picture, blurred For footage a platform's graphic-content rules would refuse (the operator's case: a clip showing a dog having a diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -42,6 +42,7 @@ travel. umtool never reorders as a side effect of a window edit. "start": 32980.24, "end": 32994.19, // the reviewed EXTENT, absolute source seconds, 2 dp "cutStart": 32986.1, "cutEnd": 32992.4, // the CUT that plays, inside the extent "lockCut": true, // the cut is deliberate; the resolver leaves it + "gaps": [{ "from": 32988.4, "to": 32990.1 }], // optional: seconds cut out of the cut's middle -- one segment of jump cuts "cite": 32989, // the second shown in the attribution line "citeUrl": "https://…", // optional: overrides the derived QR target "quote": "…", // the words this clip exists for @@ -159,6 +160,17 @@ incorrect** is ticked. - **`lock` is about the extent; `lockCut` is about the cut.** The resolver honours both, and never overwrites existing cut fields without `--force-cut`. +### Gaps — seconds cut out of the cut's middle + +`gaps: [{from, to}]` (source seconds) takes seconds out of the middle of a clip, which then renders as ONE segment of +jump cuts — one header, one pip, one subtitle card — rather than as two clips with a crossfade. Each gap lies inside +the CUT (the extent when there is none), at least 0.2 s, at most 12, apart, with 0.5 s kept at the edges and between +them; a mute mark or claim mark inside one is refused. `umtool check` reports a malformed gap as `clip-gap-invalid`, +**blocking**, as it does `clip-cut-outside`. The build trims the kept pieces on the frame grid and joins them with a +25 ms sound fade at each join; the cut record names the gaps, and every source-to-cut mapping reads it. Written by the +bench (a span dragged on its waveform), `umtool window --gap/--gap-remove/--gaps` and `umtool set gap.add=…`; the +whole of it is in [knobs.md, "Gaps inside a clip"](knobs.md#gaps-inside-a-clip). + The matcher is deliberately loose, because a quote is prose a human wrote about speech a machine transcribed: case and punctuation are dropped, `[bracketed]` editorial words and `[Speaker]` markers are dropped, and an **ellipsis splits diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1865,6 +1865,22 @@ makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "cl makeLivePreviewFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // The Play view: the whole cut (and a take) played with no render, notes at the playhead (play-cut.spec.ts). makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut, +// undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1 +// window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it). +// g01 gapvid 0.5-8.5 (locked: its edges are where they are written, in the tone) +// g02 gapvid 1.0-3.0 (locked) +// No deck: Play the cut plays it on the estimate's clock and the render's edges. +{ + const g = manifest("gaps-fixture", "The Gaps Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "g01", video: "gapvid", start: 0.5, end: 8.5, cite: 1, section: 0, lock: true, quote: "a clip with a gap" }, + { type: "clip", id: "g02", video: "gapvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "the clip after it" }, + ]); + g.render.fetchPad = 0; + const dir = writeProject("gaps-fixture", g); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4")); +} // The same cut for Play → Edit this clip → Back (phone-walk.spec.ts), which WRITES // an edge: its own copy, so play-cut.spec's clock is never moved. makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-edit-fixture", title: "The Play Edit Fixture", video: "vid1" }); diff --git a/umtool/e2e/gaps-zoom.spec.ts b/umtool/e2e/gaps-zoom.spec.ts @@ -0,0 +1,289 @@ +import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Gaps inside a clip (umtool-report-to-video gaps.mjs) and the bench +// waveform's zoom (components/projects/bench/GapsZoom.tsx): +// +// - the waveform zooms (+ / − / Fit, Ctrl + wheel at the pointer, the keys) +// and pans (the wheel, the overview strip); close in it draws the measured +// silences; at fit it is what it always was +// - a span selected on the waveform (Select a gap, or Alt + drag) is cut out +// of the clip through the window writer; Undo puts the list back; a click +// on a gap's band removes it; a span the build would refuse is refused here +// - the bench's playback skips a gap, as the cut will +// - Play the cut plays the clip as ONE item of jump cuts: the render's +// footage less the gap, one sound node per kept piece, the picture past +// the gap at the join, a tick on the reel strip +// +// Fixture: gaps-fixture (make-fixture.mjs), which this spec WRITES: g01 +// gapvid 0.5-8.5 and g02 1.0-3.0, both locked, on the fixture's tone window +// (silences 2.9-3.1, 5.9-6.1) cached as gapvid_0.00-9.00.mp4; 15 fps. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PROJECT = "reports/gaps-fixture"; +const MANIFEST = path.join(HERE, "..", ".e2e-song", "reports", "gaps-fixture", "video.manifest.json"); +type Gap = { from: number; to: number }; +const clipOf = (id: string) => + (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string; start: number; end: number; gaps?: Gap[] }[] }).timeline.find((e) => e.id === id)!; + +const token = async (request: APIRequestContext, clip = "g01") => + ((await (await request.get(`/api/report/clip?project=${encodeURIComponent(PROJECT)}&clip=${clip}`)).json()) as { token: string }).token; +const putWindow = async (request: APIRequestContext, data: Record<string, unknown>, clip = "g01") => + request.put("/api/report/window", { data: { project: PROJECT, clip, token: await token(request, clip), ...data } }); + +/** The bench, with its waveform scrolled on screen (the mouse only reaches what is in the viewport). */ +const openBench = async (page: Page, clip = "g01") => { + await page.goto(urls.clipBenchHref(PROJECT, clip)); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(page.locator("[data-wave-box]")).toBeInViewport(); +}; + +/** The waveform's shown span, [from, to] (data-wave-vis). */ +const visOf = async (page: Page) => { + const v = (await page.locator("[data-wave-box]").getAttribute("data-wave-vis"))!; + const [a, b] = v.split("-").map(Number); + return { from: a, to: b }; +}; +/** A source second's x on the waveform, as shown now. */ +const xAt = async (page: Page, t: number) => { + const b = (await page.locator("[data-wave-box]").boundingBox())!; + const v = await visOf(page); + return b.x + ((t - v.from) / (v.to - v.from)) * b.width; +}; +const tAtX = async (page: Page, x: number) => { + const b = (await page.locator("[data-wave-box]").boundingBox())!; + const v = await visOf(page); + return v.from + ((x - b.x) / b.width) * (v.to - v.from); +}; +const midY = async (page: Page) => { + const b = (await page.locator("[data-wave-box]").boundingBox())!; + return b.y + b.height / 2; +}; +/** Drag on the waveform from source second a to b. */ +const dragSpan = async (page: Page, a: number, b: number) => { + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + const y = await midY(page); + await page.mouse.move(await xAt(page, a), y); + await page.mouse.down(); + await page.mouse.move((await xAt(page, a) + (await xAt(page, b))) / 2, y, { steps: 3 }); + await page.mouse.move(await xAt(page, b), y, { steps: 3 }); + await page.mouse.up(); +}; +const spanOf = (s: string | null) => (s ?? "").split("-").map(Number); + +/** The bench's keyboard is attached on hydration: prove it with `x` (focuses the correction box, writes nothing). */ +const keyboardLive = async (page: Page) => { + const box = page.locator("[data-attrib-field=correction]"); + await expect(async () => { + await page.locator("body").press("x"); + await expect(box).toBeFocused({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + await box.blur(); +}; + +test.beforeEach(async ({ request }) => { + test.setTimeout(120_000); + // Every test starts from no gaps. + const r = await putWindow(request, { gaps: [] }); + expect(r.ok(), await r.text()).toBeTruthy(); +}); + +test("the bench waveform zooms at the pointer, pans, and fits back to what it always was", async ({ page }) => { + await openBench(page); + const zoom = page.locator("[data-wave-zoom]"); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); + await expect(page.locator("[data-zoom-ruler]")).toHaveCount(0); + await expect(page.locator("[data-zoom-overview]")).toHaveCount(0); + const whole = await visOf(page); + + // + zooms in (about the playhead, else the middle): a ruler and the overview appear. + await page.locator("[data-zoom-in]").click(); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(zoom).not.toHaveAttribute("data-wave-zoom", "fit"); + await expect(page.locator("[data-zoom-ruler]")).toBeVisible(); + await expect(page.locator("[data-zoom-overview]")).toBeVisible(); + let v = await visOf(page); + expect(v.to - v.from).toBeCloseTo((whole.to - whole.from) / 1.6, 2); + + // Ctrl + wheel at the pointer: the second under it stays under it. + const x3 = await xAt(page, 3); + await page.mouse.move(x3, await midY(page)); + await page.keyboard.down("Control"); + await page.mouse.wheel(0, -240); + await page.keyboard.up("Control"); + await expect.poll(async () => (await visOf(page)).to - (await visOf(page)).from).toBeLessThan(v.to - v.from - 0.5); + expect(await tAtX(page, x3)).toBeCloseTo(3, 1); + v = await visOf(page); + + // The wheel alone pans while zoomed. + await page.mouse.wheel(0, 120); + await expect.poll(async () => (await visOf(page)).from).toBeGreaterThan(v.from + 0.05); + const panned = await visOf(page); + expect(panned.to - panned.from).toBeCloseTo(v.to - v.from, 2); + + // The overview: its window is what is shown; dragging it pans back. + await page.locator("[data-zoom-overview]").scrollIntoViewIfNeeded(); + const win = page.locator("[data-zoom-window]"); + const wb = (await win.boundingBox())!; + await page.mouse.move(wb.x + wb.width / 2, wb.y + wb.height / 2); + await page.mouse.down(); + await page.mouse.move(wb.x + wb.width / 2 - 60, wb.y + wb.height / 2, { steps: 4 }); + await page.mouse.up(); + await expect.poll(async () => (await visOf(page)).from).toBeLessThan(panned.from - 0.1); + + // Close in, the measured silences are drawn (the cut-points route's: 2.9-3.1 on this window). + await page.locator("[data-zoom-fit]").click(); + await page.locator("[data-wave-box]").scrollIntoViewIfNeeded(); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); + await page.mouse.move(await xAt(page, 3), await midY(page)); + await page.keyboard.down("Control"); + for (let i = 0; i < 3; i += 1) await page.mouse.wheel(0, -300); + await page.keyboard.up("Control"); + await expect.poll(async () => (await visOf(page)).to - (await visOf(page)).from).toBeLessThan(3); + await expect(page.locator("[data-wave-silence]").first()).toBeVisible({ timeout: 30_000 }); + const sil = spanOf(await page.locator("[data-wave-silence]").first().getAttribute("data-wave-silence")); + expect(sil[0]).toBeGreaterThan(2.8); + expect(sil[1]).toBeLessThan(3.2); + // Finer ticks: under a second apart. + expect(Number(await page.locator("[data-zoom-ruler]").getAttribute("data-zoom-ruler"))).toBeLessThan(1); + + // The keys: f fits, z zooms in, Z out. + await keyboardLive(page); + await page.locator("body").press("f"); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); + await page.locator("body").press("z"); + await expect(zoom).not.toHaveAttribute("data-wave-zoom", "fit"); + await page.locator("body").press("Shift+Z"); + await expect(zoom).toHaveAttribute("data-wave-zoom", "fit"); +}); + +test("a gap: selected on the waveform, cut, undone; Alt + drag and g; a click on its band puts it back; refusals", async ({ page, request }) => { + await openBench(page); + await expect(page.locator("[data-gaps]")).toHaveAttribute("data-gaps", ""); + const before = clipOf("g01"); + + // Select a gap, drag 3.5 → 5.5 on the waveform. + await page.locator("[data-gap-pick]").click(); + await expect(page.locator("[data-gap-pick=armed]")).toBeVisible(); + await dragSpan(page, 3.5, 5.5); + const sel = spanOf(await page.locator("[data-gap-selection]").getAttribute("data-gap-selection")); + expect(sel[0]).toBeCloseTo(3.5, 1); + expect(sel[1]).toBeCloseTo(5.5, 1); + await expect(page.locator("[data-bench-note]")).toContainText("selected"); + await page.locator("[data-gap-cut]").click(); + await expect.poll(() => clipOf("g01").gaps?.length ?? 0).toBe(1); + const g = clipOf("g01").gaps![0]; + expect(g.from).toBeCloseTo(3.5, 1); + expect(g.to).toBeCloseTo(5.5, 1); + // The edges did not move; the band is drawn; the summary says what plays. + expect([clipOf("g01").start, clipOf("g01").end]).toEqual([before.start, before.end]); + await expect(page.locator("[data-gap-band]")).toHaveCount(1); + await expect(page.locator("[data-gaps-summary]")).toContainText(/the cut plays \d\.\d\d s of 8\.00 s, one segment/); + await expect(page.locator("[data-rail-gap]")).toHaveCount(1); + + // Undo writes the list back as it was. + await page.locator("[data-gap-undo]").click(); + await expect.poll(() => clipOf("g01").gaps).toBeUndefined(); + await expect(page.locator("[data-gap-band]")).toHaveCount(0); + + // Alt + drag selects without arming, and never moves an edge; `g` cuts it. + await page.keyboard.down("Alt"); + await dragSpan(page, 4, 5); + await page.keyboard.up("Alt"); + await expect(page.locator("[data-gap-selection]")).toBeVisible(); + expect([clipOf("g01").start, clipOf("g01").end]).toEqual([before.start, before.end]); + await expect(page.locator("[data-save-window]")).toBeDisabled(); + await keyboardLive(page); + await page.locator("body").press("g"); + await expect.poll(() => clipOf("g01").gaps?.length ?? 0).toBe(1); + expect(clipOf("g01").gaps![0].from).toBeCloseTo(4, 1); + + // A click on the band puts the seconds back. + await page.locator("[data-gap-band]").click(); + await expect.poll(() => clipOf("g01").gaps).toBeUndefined(); + + // Too close to the clip's start: said, and nothing written. + await page.locator("[data-gap-pick]").click(); + await dragSpan(page, 0.7, 1.4); + await expect(page.locator("[data-bench-note]")).toContainText("cannot be cut"); + await page.locator("[data-gap-cut]").click(); + await expect(page.locator("[data-bench-note]")).toContainText("keep at least 0.5 s"); + expect(clipOf("g01").gaps).toBeUndefined(); + + // The writer's own refusals, through the route. + let r = await putWindow(request, { gapAdd: "0.6-1" }); + expect(r.status()).toBe(400); + expect(((await r.json()) as { error: string }).error).toMatch(/keep at least 0.5 s/); + r = await putWindow(request, { gapAdd: "3.5-5.5" }); + expect(r.ok()).toBeTruthy(); + r = await putWindow(request, { muteFrom: 4 }); + expect(r.status()).toBe(400); + expect(((await r.json()) as { error: string }).error).toMatch(/inside the gap 3\.5–5\.5, which never plays/); +}); + +test("the bench plays across a gap the way the cut will: the gap is skipped", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + await page.goto(urls.clipBenchHref(PROJECT, "g01")); + const playback = page.locator("[data-playback]"); + await expect(playback).toHaveAttribute("data-audio-state", "ready", { timeout: 15_000 }); + await expect(page.locator("[data-gap-band]")).toHaveCount(1); + await keyboardLive(page); + await page.locator("body").press(" "); + await expect(playback).toHaveAttribute("data-play-state", "playing", { timeout: 10_000 }); + expect(await playback.getAttribute("data-play-engine")).toBe("webaudio"); + const a = Number(await playback.getAttribute("data-play-ctx-start")); + const b = Number(await playback.getAttribute("data-play-ctx-stop")); + // 0.5-8.5 less the 2 s gap: six seconds of sound, not eight. + expect(b - a).toBeCloseTo(6, 2); + expect(Number(await playback.getAttribute("data-play-to"))).toBeCloseTo(8.5, 2); + await page.locator("body").press(" "); +}); + +test("Play the cut plays a gapped clip as one item of jump cuts", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + // The render's cut: the gap on the frame grid, the footage the kept seconds. + const got = await (await request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}`)).json(); + const g01 = got.clips.find((c: { id: string }) => c.id === "g01"); + expect(g01).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 }); + + await page.goto(urls.playHref(PROJECT)); + const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(root).toHaveAttribute("data-play-item", "g01"); + // The jump cut on the reel strip, 3 s into the clip. + await expect(page.locator("[data-play-gap]")).toHaveAttribute("data-play-gap", "g01@3"); + await page.locator("[data-play-toggle]").click(); + await expect(root).toHaveAttribute("data-play-sound", "webaudio", { timeout: 15_000 }); + // Past the join: the picture is the material after the gap (5.5 on), never 3.5-5.5. Every + // frame drawn while g01 plays is said (data-play-drawn): none from inside the gap. + const seen: string[] = []; + await expect + .poll(async () => { + const t = Number(await root.getAttribute("data-play-t")); + const d = (await page.locator("[data-play-footage]").getAttribute("data-play-drawn")) ?? ""; + seen.push(`${t.toFixed(2)}=${d}`); + const [id, at] = d.split(":"); + return id === "g01" && t > 3.2 ? Number(at) : -1; + }, { timeout: 20_000, intervals: [100] }) + .toBeGreaterThan(5.5); + console.log(`gaps-zoom: drawn ${seen.join(" ")}`); + const inGap = seen.map((x) => x.split("=")[1]).filter((d) => d.startsWith("g01:")).map((d) => Number(d.split(":")[1])).filter((at) => at > 3.6 && at < 5.4); + expect(inGap, "no frame from inside the gap").toEqual([]); + // Two sound nodes for g01, abutting at the join (cut second 3), and g02 after its six seconds. + const s = await page.evaluate( + () => (window as unknown as { __umtoolPlayEngine: { stats: { scheduled: { id: string; from: number; to: number; run: number }[] } } }).__umtoolPlayEngine.stats, + ); + const mine = s.scheduled.filter((n) => n.id === "g01"); + const run = mine[mine.length - 1].run; + const pieces = mine.filter((n) => n.run === run).sort((x, y) => x.from - y.from); + expect(pieces.length).toBe(2); + expect(pieces[0].to).toBeCloseTo(3, 2); + expect(pieces[1].from).toBeCloseTo(3, 2); + expect(pieces[1].to).toBeCloseTo(6, 2); + await page.keyboard.press("k"); +}); 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 @@ -1281,6 +1287,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/benchZoom.mjs b/umtool/lib/report/benchZoom.mjs @@ -0,0 +1,120 @@ +// THE BENCH WAVEFORM'S ZOOM, as arithmetic (ClipBench.tsx, bench/GapsZoom.tsx): +// which stretch of the cached window the waveform shows, moved by a zoom at a +// point (the pointer's second stays under the pointer), a pan, a fit and a +// zoom to a span; the ruler's ticks for what is shown; and the pauses between +// words, drawn once the waveform is close enough to place a gap (or an edge) +// in one. Pure: no DOM, no React, so it is unit-tested (benchZoom.test.mjs) +// and the component only applies it. +// +// EVERYTHING IS IN ABSOLUTE SOURCE SECONDS, like the bench. `whole` is the +// cached window (what the waveform shows at fit -- today's view); `vis` the +// stretch of it shown now. + +/** The closest the waveform zooms: a quarter of a second across its width. */ +export const MIN_ZOOM_SPAN = 0.25; +/** One step of + / − (and of a wheel notch, scaled by its delta). */ +export const ZOOM_STEP = 1.6; +/** At or under this many seconds shown, the measured silences and the words' boundaries are drawn. */ +export const DETAIL_SPAN = 20; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const round4 = (v) => Math.round(v * 10000) / 10000; + +/** `vis` kept inside `whole`, at least MIN_ZOOM_SPAN (or the whole) wide. */ +export function clampVis(vis, whole) { + const W = Math.max(1e-6, whole.to - whole.from); + const span = Math.min(W, Math.max(Math.min(MIN_ZOOM_SPAN, W), vis.to - vis.from)); + let from = Math.max(whole.from, Math.min(vis.from, whole.to - span)); + if (!fin(from)) from = whole.from; + return { from: round4(from), to: round4(Math.min(whole.to, from + span)) }; +} + +/** Is `vis` the whole window (no zoom)? */ +export const isFit = (vis, whole) => !vis || (vis.from <= whole.from + 1e-3 && vis.to >= whole.to - 1e-3); + +/** + * Zoom by `factor` (> 1 in, < 1 out) about source second `at`: the second + * under the pointer stays under it. At fit and zooming out, fit. + */ +export function zoomAt(vis, whole, at, factor) { + const v = vis ?? whole; + const span = v.to - v.from; + const next = Math.min(whole.to - whole.from, Math.max(MIN_ZOOM_SPAN, span / (factor > 0 ? factor : 1))); + const a = fin(at) ? Math.min(v.to, Math.max(v.from, at)) : (v.from + v.to) / 2; + const frac = span > 0 ? (a - v.from) / span : 0.5; + return clampVis({ from: a - frac * next, to: a - frac * next + next }, whole); +} + +/** Move what is shown by `dt` seconds (clamped to the window). */ +export function panBy(vis, whole, dt) { + const v = vis ?? whole; + return clampVis({ from: v.from + dt, to: v.to + dt }, whole); +} + +/** Show `range` with `margin` of its length either side (at least MIN_ZOOM_SPAN). */ +export function zoomTo(range, whole, margin = 0.15) { + const len = Math.max(MIN_ZOOM_SPAN, range.to - range.from); + const pad = len * margin; + return clampVis({ from: range.from - pad, to: range.to + pad }, whole); +} + +/** Centre what is shown on `t`, keeping its width. */ +export function centreOn(vis, whole, t) { + const v = vis ?? whole; + const span = v.to - v.from; + return clampVis({ from: t - span / 2, to: t + span / 2 }, whole); +} + +/** A wheel notch as a zoom factor: deltaY < 0 zooms in; a trackpad's small deltas zoom a little. */ +export function wheelFactor(deltaY, deltaMode = 0) { + const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 400 : deltaY; + return Math.exp(-px * 0.0025); +} + +const STEPS = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600]; + +/** + * The ruler for what is shown: a round step that gives at most `maxTicks` + * ticks, and each tick's second (a multiple of the step). + */ +export function rulerFor(vis, maxTicks = 10) { + const span = Math.max(1e-6, vis.to - vis.from); + const step = STEPS.find((s) => span / s <= maxTicks) ?? STEPS[STEPS.length - 1]; + const ticks = []; + for (let k = Math.ceil(vis.from / step - 1e-9); k * step <= vis.to + 1e-9; k += 1) ticks.push(round4(k * step) + 0); + return { step, ticks }; +} + +/** A tick's label: `m:ss` for a step of a second or more, else `m:ss.s` / `m:ss.ss`. */ +export function tickLabel(t, step) { + const s = Math.max(0, t); + const m = Math.floor(s / 60); + const sec = s - m * 60; + const dp = step >= 1 ? 0 : step >= 0.1 ? 1 : 2; + const text = sec.toFixed(dp).padStart(dp ? 3 + dp : 2, "0"); + const h = Math.floor(m / 60); + return h ? `${h}:${String(m % 60).padStart(2, "0")}:${text}` : `${m}:${text}`; +} + +/** + * The gaps between words, as places an edge or a gap's edge can go: for each + * pause between consecutive words (or cues), its middle; and every measured + * silence's middle. Sorted, deduplicated within 20 ms. In [from, to]. + * + * @param {{ words?: Array<{ start: number, end: number }> | null, silences?: Array<{ from: number, to: number }> | null }} o + * @param {number} from + * @param {number} to + */ +export function quietPoints({ words = null, silences = null }, from, to) { + const pts = []; + const ws = (words ?? []).filter((w) => fin(w.start) && fin(w.end)).sort((a, b) => a.start - b.start); + for (let i = 1; i < ws.length; i += 1) { + if (ws[i].start >= ws[i - 1].end) pts.push((ws[i - 1].end + ws[i].start) / 2); + } + for (const s of silences ?? []) if (fin(s.from) && fin(s.to)) pts.push((s.from + s.to) / 2); + const out = []; + for (const p of pts.filter((x) => x >= from && x <= to).sort((a, b) => a - b)) { + if (!out.length || p - out[out.length - 1] > 0.02) out.push(round4(p)); + } + return out; +} diff --git a/umtool/lib/report/benchZoom.test.mjs b/umtool/lib/report/benchZoom.test.mjs @@ -0,0 +1,68 @@ +// The bench waveform's zoom (benchZoom.mjs): a zoom keeps the pointer's second +// under the pointer, never past the window or closer than MIN_ZOOM_SPAN; a pan +// stops at the window's edges; fit is the whole; the ruler's round ticks; the +// pauses between words. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { MIN_ZOOM_SPAN, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo } from "./benchZoom.mjs"; + +const W = { from: 10, to: 40 }; +const near = (a, b, what, tol = 1e-3) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +test("zoomAt: the second under the pointer stays there; never closer than MIN_ZOOM_SPAN, never wider than the window", () => { + const v = zoomAt(null, W, 16, 2); + near(v.to - v.from, 15, "half the window"); + near((16 - v.from) / (v.to - v.from), (16 - 10) / 30, "the pointer's fraction"); + const out = zoomAt(v, W, 16, 1 / 4); + assert.deepEqual(out, W, "out past the whole: the whole"); + assert.equal(isFit(out, W), true); + let z = W; + for (let i = 0; i < 40; i += 1) z = zoomAt(z, W, 25, 3); + near(z.to - z.from, MIN_ZOOM_SPAN, "the closest"); + assert.ok(z.from <= 25 && z.to >= 25); + // Near an edge: kept inside the window. + const e = zoomAt({ from: 10, to: 12 }, W, 10, 1 / 2); + assert.ok(e.from >= 10 && e.to <= 40); +}); + +test("panBy, centreOn, zoomTo, clampVis: inside the window, the width kept", () => { + assert.deepEqual(panBy({ from: 20, to: 25 }, W, 3), { from: 23, to: 28 }); + assert.deepEqual(panBy({ from: 20, to: 25 }, W, 100), { from: 35, to: 40 }); + assert.deepEqual(panBy({ from: 20, to: 25 }, W, -100), { from: 10, to: 15 }); + assert.deepEqual(centreOn({ from: 20, to: 24 }, W, 30), { from: 28, to: 32 }); + assert.deepEqual(zoomTo({ from: 20, to: 30 }, W), { from: 18.5, to: 31.5 }); + assert.deepEqual(clampVis({ from: 5, to: 5.01 }, W), { from: 10, to: 10.25 }); + assert.equal(isFit(null, W), true); + assert.equal(isFit({ from: 10, to: 39 }, W), false); +}); + +test("wheelFactor: a notch up zooms in, down out; a trackpad's small delta a little", () => { + assert.ok(wheelFactor(-100) > 1); + assert.ok(wheelFactor(100) < 1); + near(wheelFactor(-100) * wheelFactor(100), 1, "symmetric"); + assert.ok(Math.abs(wheelFactor(-4) - 1) < 0.02); + assert.ok(wheelFactor(-3, 1) > 1.1, "a line-mode notch"); +}); + +test("rulerFor / tickLabel: round steps, finer as it zooms; labels to the step's precision", () => { + assert.deepEqual(rulerFor({ from: 0, to: 9 }), { step: 1, ticks: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] }); + const r = rulerFor({ from: 2.53, to: 3.4 }); + assert.equal(r.step, 0.1); + assert.deepEqual(r.ticks, [2.6, 2.7, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4]); + assert.equal(rulerFor({ from: 0, to: 600 }).step, 60); + assert.equal(tickLabel(65, 5), "1:05"); + assert.equal(tickLabel(65.25, 0.05), "1:05.25"); + assert.equal(tickLabel(3.5, 0.5), "0:03.5"); + assert.equal(tickLabel(3725, 60), "1:02:05"); +}); + +test("quietPoints: the middle of each pause between words, and of each silence, in the span, once", () => { + const words = [{ start: 1, end: 1.4 }, { start: 1.6, end: 2 }, { start: 2, end: 2.5 }, { start: 3.1, end: 3.3 }]; + assert.deepEqual(quietPoints({ words }, 0, 10), [1.5, 2, 2.8]); + assert.deepEqual(quietPoints({ words, silences: [{ from: 2.7, to: 2.91 }, { from: 5, to: 6 }] }, 0, 5.4), [1.5, 2, 2.8]); + assert.deepEqual(quietPoints({ silences: [{ from: 5, to: 6 }] }, 0, 10), [5.5]); + assert.deepEqual(quietPoints({}, 0, 10), []); +}); diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -94,7 +94,8 @@ export async function readWords(dir, reactions = null) { * cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null, * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean, * vertical: { crop: number[], aspect?: number } | null, - * room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null }} EditorClip + * room: false | { tail?: boolean, head?: boolean } | null, roomEdges: { tail: boolean, head: boolean } | null, + * gaps?: Array<{ from: number, to: number }> }} EditorClip */ /** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ @@ -115,6 +116,8 @@ export async function clipEditorView(project) { end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null, + // Seconds cut out of its middle (gaps.mjs): the live preview's clock jumps with them. + ...(Array.isArray(e.gaps) && e.gaps.length ? { gaps: e.gaps } : {}), quote: typeof e.quote === "string" ? e.quote : null, title: typeof e.title === "string" ? e.title : typeof e.onscreen?.title === "string" ? e.onscreen.title : null, assist: isObj(e.assist) ? e.assist : null, @@ -249,12 +252,17 @@ const overlapping = (list, from, to) => /** * What the strip draws for [from, to] around one clip: turns, laughs, words * (or cues when the project has no word timings), and the source's length - * when known. + * when known. `video` (the clip bench, zoomed in): the words only when they + * are THAT recording's (`reactions.source.video`) -- a project's words file + * is one recording's, and another's words would be drawn in the wrong places. + * + * @param {{ id: string, dir: string }} project + * @param {{ clip?: string | null, from: number, to: number, video?: string | null }} opts */ -export async function clipNeighbourhood(project, { clip, from, to }) { +export async function clipNeighbourhood(project, { clip, from, to, video = null }) { if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to"); const { doc } = await readReactions(project.dir); - const words = await readWords(project.dir, doc); + const words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc); const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker })); const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null })); let cues = null; diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -25,6 +25,8 @@ export type EditorClip = { key: string | null; ruling: string | null; montage: boolean; + /** Seconds cut out of its middle (gaps.mjs), when it has any. */ + gaps?: { from: number; to: number }[]; /** A short's framing (release 36): `crop` = [x, y, w, h], fractions of the source picture. */ vertical: { crop: number[]; aspect?: number } | null; /** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */ 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 @@ -422,6 +429,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 @@ -703,6 +756,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; @@ -718,6 +776,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; @@ -765,6 +833,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; @@ -2242,6 +2318,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); @@ -2337,6 +2418,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/playGaps.test.mjs b/umtool/lib/report/playGaps.test.mjs @@ -0,0 +1,102 @@ +// Play the cut with gaps inside a clip (gaps.mjs): the plan plays the kept +// seconds as one item -- its footage the cut less its gaps, the cut ↔ source +// mapping jumping at each join (on the estimate's clock and on the render's, +// from the cut-points route's `gaps`), the chrome seeked by source second +// through them; the sound is one span per kept piece, abutting on the cut's +// clock, with the build's join fades; the clip editor's live clock agrees. +// Without gaps every number is the one it was. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { estimateSchedule } from "umtool-report-to-video/deck"; +import { GAP_FADE } from "umtool-report-to-video/gaps"; +import { chromeTime, cutAtSource, gapJoins, playPlan, playTimeOfChrome, skipEntries, sourceAt } from "./playCut.mjs"; +import { audioSpans, levelAt, scheduleFrom } from "./playSchedule.mjs"; +import { cutTimeAt, liveClock, sourceTimeAt } from "./liveClock.mjs"; + +const GAPS = [{ from: 12, to: 13 }, { from: 15, to: 15.5 }]; +const manifest = (gaps) => ({ + slug: "t", + render: { width: 1920, height: 1080, fps: 30, transition: 0 }, + timeline: [ + { type: "clip", id: "a", video: "v1", start: 10, end: 18, ...(gaps ? { gaps } : {}) }, + { type: "clip", id: "b", video: "v2", start: 100, end: 103 }, + ], +}); +const planOf = (gaps, cuts = null) => { + const m = manifest(gaps); + return playPlan(estimateSchedule(m).segments, m.timeline, { cuts }); +}; +const near = (a, b, what, tol = 1e-6) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`); + +test("the estimate: a gapped clip is one item, its footage the kept seconds; b moves up by the gaps", () => { + const plain = planOf(null); + const p = planOf(GAPS); + assert.equal(plain.items[0].clip.playEnd, 8); + assert.equal(p.items[0].clip.playEnd, 6.5); + assert.deepEqual(p.items[0].clip.gaps, GAPS); + assert.equal("gaps" in plain.items[0].clip, false, "no key without gaps"); + assert.equal(p.items[1].start, 6.5); + assert.equal(p.total, 9.5); +}); + +test("sourceAt / cutAtSource jump at each join; a second inside a gap plays at its join", () => { + const it = planOf(GAPS).items[0]; + assert.equal(sourceAt(it, 1.9), 11.9); + assert.equal(sourceAt(it, 2), 13, "the join shows the material after the gap"); + assert.equal(sourceAt(it, 3.5), 14.5); + assert.equal(sourceAt(it, 4.2), 15.7); + assert.equal(sourceAt(it, 6.5), 18); + assert.equal(cutAtSource(it, 12.5), 2, "inside the first gap: its join"); + assert.equal(cutAtSource(it, 14), 3); + assert.equal(cutAtSource(it, 16), 4.5); + assert.deepEqual(gapJoins(it), [{ at: 2, from: 12, to: 13 }, { at: 4, from: 15, to: 15.5 }]); + // Without gaps: the subtraction it always was. + const plain = planOf(null).items[0]; + assert.equal(sourceAt(plain, 2.5), 12.5); + assert.equal(cutAtSource(plain, 12.5), 2.5); + assert.deepEqual(gapJoins(plain), []); +}); + +test("the render's edges: the route's gaps and footage; the chrome (on the estimate's clock) is seeked by source second", () => { + const cuts = { a: { cutStart: 9.9, cutEnd: 18.1, footage: 6.7, gaps: [{ from: 12, to: 13 }, { from: 15, to: 15.5 }] }, b: { cutStart: 100, cutEnd: 103 } }; + const p = planOf(GAPS, cuts); + const it = p.items[0]; + assert.equal(it.clip.sourceFrom, 9.9); + assert.equal(it.clip.playEnd, 6.7); + assert.equal(sourceAt(it, 2.1), 13, "9.9 + 2.1 is the first gap's start: the join"); + // Source 14 plays at Play 3.1 (render) and at estimate 3 -- the chrome is seeked there. + near(chromeTime(p, cutAtSource(it, 14)), 3, "chromeTime"); + near(playTimeOfChrome(p, 3), 3.1, "and back"); + // Skipping b keeps a's gaps on its estimate. + const s = skipEntries(p, ["b"]); + assert.deepEqual(s.items[0].est.gaps, GAPS); +}); + +test("the sound: one span per kept piece, abutting; the join fades; a seek into a later piece reads its own source", () => { + const spans = audioSpans(planOf(GAPS)).filter((s) => s.id === "a"); + assert.deepEqual(spans.map((s) => [s.from, s.to, s.src, s.srcTo]), [[0, 2, 10, 12], [2, 4, 13, 15], [4, 6.5, 15.5, 18]]); + // The fades: out over the last GAP_FADE of a piece before a join, in over the first after it; full level between. + near(levelAt(spans[0].env, 2 - GAP_FADE / 2), 0.5, "fading out into the first join", 1e-3); + near(levelAt(spans[1].env, 2 + GAP_FADE / 2), 0.5, "fading in out of it", 1e-3); + assert.equal(levelAt(spans[1].env, 3), 1); + assert.equal(levelAt(spans[0].env, 0), 1, "the clip's own first sample is not faded"); + const sch = scheduleFrom(audioSpans(planOf(GAPS)), 3); + assert.deepEqual(sch.slice(0, 2).map((x) => [x.atWall, x.src]), [[0, 14], [1, 15.5]]); + // Without gaps: one span, as ever. + assert.deepEqual(audioSpans(planOf(null)).filter((s) => s.id === "a").map((s) => [s.from, s.to, s.src]), [[0, 8, 10]]); +}); + +test("the clip editor's live clock: the footage less the gaps, the jump at each join", () => { + const sched = estimateSchedule(manifest(GAPS)); + const clock = liveClock(sched, { id: "a", start: 10, end: 18, gaps: GAPS }); + assert.equal(clock.playEnd, 6.5); + assert.deepEqual(cutTimeAt(clock, 14), { t: 3, where: "inside" }); + assert.deepEqual(cutTimeAt(clock, 12.4), { t: 2, where: "inside" }); + assert.equal(sourceTimeAt(clock, 4.5), 16); + const plain = liveClock(estimateSchedule(manifest(null)), { id: "a", start: 10, end: 18 }); + assert.equal(plain.playEnd, 8); + assert.equal("gaps" in plain, false); +}); 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,426 @@ +// 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; + // The span is the cut when the clip has one, else its extent: say which. + const whose = fin(entry.cutStart) && fin(entry.cutEnd) ? "cut" : "clip"; + 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 ${whose} ${span.from}–${span.to} — widen the ${whose}, or remove the gap`); + return; + } + const before = i === 0 ? span.from : ok[i - 1].to; + const what = i === 0 ? `the ${whose}'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 ${whose}'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`);