Archilyzer · Source

archilyzer

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

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

umtool bench: cut gaps on the waveform, and zoom it

The clip bench (Edit this clip) draws a clip's gaps as hatched bands on its
waveform and the cue rail. A span is dragged with Alt held (or after g /
Select a gap) and cut by Cut gap (g), heard first by Hear it; a click on a
band puts it back (G: the one at the playhead); Undo writes the list back.
Writes go through the window writer at once, refused here first with its own
sentences. Every bench playback skips the gaps as the cut will (one node per
kept piece, the join faded, the picture seeked at each join).

The waveform zooms: Ctrl/Cmd + wheel (and a trackpad pinch) at the pointer,
- / + / Fit / Zoom to selection, z Z f F; zoomed, the wheel pans, an overview
strip shows the whole window (drag to pan, two-finger pinch), a ruler of round
ticks, and at 20 s or closer the measured silences and the pauses between
words. At fit it is the waveform it always was.

Play the cut draws a jump tick on the reel strip, and never draws a frame from
inside a gap while the decoder crosses one. The clip editor's live preview
clock takes the clip's gaps.

e2e: gaps-zoom.spec.ts (gaps-fixture). Docs: knobs.md (a clip's row, "Gaps
inside a clip", the zoom), report-video.md, cli.md.

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/components/projects/ClipBench.tsx | 484++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
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/ReelStrip.tsx | 16+++++++++++++++-
Mumtool/components/projects/review/playEngine/engine.ts | 10+++++++++-
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 | 287+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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++
Aumtool/lib/report/playGaps.test.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/gaps.mjs | 8+++++---
20 files changed, 1557 insertions(+), 56 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/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( { @@ -3194,11 +3466,78 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { </button> )} </span> + {/* ---- 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> + <ZoomControls zoom={zoom} whole={view} selection={gapSel ?? sel} playhead={playhead} /> <span className="micro max-md:hidden"> <kbd>[</kbd> <kbd>]</kbd> start · <kbd>,</kbd> <kbd>.</kbd> end — each plays the edge it moved · <kbd>space</kbd> the whole selection · <kbd>R</kbd> reset · <kbd>-</kbd>{" "} <kbd>=</kbd> speed · <kbd>a</kbd> auto · <kbd>m</kbd> mute from the playhead,{" "} - <kbd>;</kbd> <kbd>&apos;</kbd> move it, <kbd>M</kbd> clear — shift for 0.5s + <kbd>;</kbd> <kbd>&apos;</kbd> move it, <kbd>M</kbd> clear — shift for 0.5s ·{" "} + <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> {busy && <span className="text-[var(--color-meter)]">{busy}</span>} {note && ( @@ -3211,9 +3550,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 +3604,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 +3638,23 @@ 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 ?? []} />} + </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 +3773,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/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,4 +1,5 @@ import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; +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"; @@ -641,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 @@ -30,6 +30,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 @@ -37,6 +38,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,287 @@ +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) => { + 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 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/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/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/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -137,13 +137,15 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}` } 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 cut ${span.from}–${span.to} — widen the cut, or remove the gap`); + 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 cut's start" : `gaps[${ok[i - 1].k}]`; + 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 @@ -154,7 +156,7 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}` }); const last = ok[ok.length - 1]; if (!errors.length && fin(span.to) && span.to - last.to < keep - WIN_EPS) { - errors.push(`${where}.gaps[${last.k}] ${last.from}–${last.to} leaves ${Math.max(0, span.to - last.to).toFixed(2)} s before the cut's end; keep at least ${keep} s`); + 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.