Archilyzer · Source

archilyzer

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

commit 1a113d9c3d75c929900ff9d241f6e6326953f650
parent 833bfa33179f08466a8a57c7168f63758aae5ce7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 20:48:26 -0500

Merge lane/clip-fixes: the clip bench shows its walls -- the cut drawn with draggable edges and Use the whole clip, fetch more reaches on from the drag (a 15-min window, no 120 s cap from the saved edge), gaps anywhere in the drafted extent, every no-cut zone and mark drawn with its reason while dragging, up to 40 gaps; the bench reloads on back/forward (operator, 6 Nov: "the gap tool gets blocked at random invisible walls", "I try to drag a clip and it just doesn't expand beyond a certain point", "I just had to refresh")

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

Diffstat:
Mumtool/app/api/report/clip/route.ts | 9+++++++++
Mumtool/app/api/report/fetch/route.ts | 36++++++++++++++++++++++++++----------
Mumtool/components/projects/ClipBench.tsx | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/components/projects/bench/BenchWave.tsx | 7++++++-
Aumtool/components/projects/bench/CutEdges.tsx | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/GapsZoom.tsx | 131++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/bench/useGapEditor.ts | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/components/projects/reel/ReelBench.tsx | 13+++++++++++--
Mumtool/components/projects/review/ClipEditor.tsx | 25+++++++++++++++++++++++++
Mumtool/docs/clip-bench.md | 20++++++++++++++++++--
Mumtool/docs/knobs.md | 4++--
Mumtool/docs/report-video.md | 2+-
Mumtool/e2e/clip-bench.spec.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 16++++++++++++++++
Mumtool/e2e/gaps-zoom.spec.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/benchData.ts | 8++++++--
Mumtool/lib/report/driver.mjs | 17++++++++++++-----
Mumtool/report-to-video/gaps.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/gaps.test.mjs | 54+++++++++++++++++++++++++++++++++++++++++++++++++++---
19 files changed, 1137 insertions(+), 68 deletions(-)

diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts @@ -3,6 +3,7 @@ import { ensureWindowFile, projectCache, resolveClip, segmentFor, windowVersion, import { takeToken } from "@/lib/report/takeEdit.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { cuesInWindow, readClipDetail, siblingsOf } from "@/lib/projects/report.mjs"; +import { gapWalls } from "umtool-report-to-video/gaps"; export const dynamic = "force-dynamic"; @@ -69,10 +70,18 @@ export async function GET(request: Request) { muteFrom: clip.muteFrom ?? null, // Seconds cut out of its middle (gaps.mjs). gaps: Array.isArray(clip.gaps) ? clip.gaps : [], + // The seconds no gap may cover: each claim mark's or stamp's `at` (gaps.mjs gapWalls). + marks: gapWalls({ ...clip, type: "clip", muteFrom: null }).marks.map((m) => ({ id: m.id, at: m.at })), // What the walk said that is not a verdict, and a deliberate repeat. walkNote: typeof clip.walkNote === "string" ? clip.walkNote : null, star: clip.star === true, repeatOf: typeof clip.repeatOf === "string" ? clip.repeatOf : null, + // The rest of what the bench holds, so a page come back to (the back + // button, lane/clip-fixes) can take the clip as it is now, not as it was. + verdict: clip.verdict === "confirmed" || clip.verdict === "incorrect" || clip.verdict === "rejected" ? clip.verdict : null, + reason: typeof clip.reason === "string" ? clip.reason : null, + rejectNote: typeof clip.rejectNote === "string" ? clip.rejectNote : null, + onscreen: clip.onscreen ?? null, }, view, // `v`: the version of each window's bytes, for the media URLs -- a refetch diff --git a/umtool/app/api/report/fetch/route.ts b/umtool/app/api/report/fetch/route.ts @@ -1,6 +1,6 @@ import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; import { - FETCH_MAX_PAD, + FETCH_MAX_WINDOW, editorFetchSteps, editorFullSourceSteps, fetchSteps, @@ -22,7 +22,8 @@ export const dynamic = "force-dynamic"; // and containing-window reuse then makes this generous fetch BE the build's // cache rather than a second one. -const MAX_PAD = FETCH_MAX_PAD; +/** A fetched window, end to end, is at most this wide (the editor's cap). */ +const MAX_WINDOW = FETCH_MAX_WINDOW; /** Same tolerance the build uses for "this file holds that window". */ const WIN_EPS = 0.02; @@ -33,9 +34,13 @@ export async function POST(request: Request) { // ONE EDGE AT A TIME. `pad` stays the symmetric shorthand; the bench sends // the side it is extending and the side it already has, so a fetch never // quietly re-downloads twenty seconds of lead-in nobody asked for. - const side = (v: unknown, fallback: number) => - Math.max(0, Math.min(MAX_PAD, Number(v ?? fallback))); - const pad = Math.max(1, Math.min(MAX_PAD, Number(body.pad ?? 20))); + // No cap per side: the WINDOW is capped, end to end, below -- an edge dragged + // far from where it was saved needs a pad far bigger than any fixed side cap. + const side = (v: unknown, fallback: number) => { + const n = Number(v ?? fallback); + return Number.isFinite(n) ? Math.max(0, n) : fallback; + }; + const pad = Math.max(1, side(body.pad, 20)); const padBefore = side(body.padBefore, pad); const padAfter = side(body.padAfter, pad); @@ -107,6 +112,20 @@ export async function POST(request: Request) { from: Math.max(0, Number(r.clip.start) - padBefore), to: Number(r.clip.end) + padAfter, }; + // The editor fetches a window of at most MAX_WINDOW seconds (wider is the + // whole recording); say so here, with the numbers, rather than queue a job + // the editor refuses. + if (!wantFull && want.to - want.from > MAX_WINDOW + WIN_EPS) { + return Response.json( + { + error: + `a fetched window is at most ${MAX_WINDOW} s end to end (asked for ${Math.round(want.to - want.from)} s) — ` + + "fetch the whole source for more", + maxWindow: MAX_WINDOW, + }, + { status: 400 }, + ); + } const holds = windows.find((w) => w.from <= want.from + WIN_EPS && w.to >= want.to - WIN_EPS); if (holds) { // What is already there, PER SIDE, in the pads the bench speaks in. @@ -115,15 +134,12 @@ export async function POST(request: Request) { return Response.json( { error: - `already cached to −${haveBefore} s / +${haveAfter} s — ask for more on one side` + - (padBefore >= MAX_PAD || padAfter >= MAX_PAD - ? ` (${MAX_PAD} s is the widest one side goes)` - : ""), + `already cached to −${haveBefore} s / +${haveAfter} s — ask for more on one side`, cachedBefore: haveBefore, cachedAfter: haveAfter, /** The narrower side, for a caller that speaks in one number. */ cachedPad: Math.min(haveBefore, haveAfter), - maxPad: MAX_PAD, + maxWindow: MAX_WINDOW, }, { status: 409 }, ); diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -33,9 +33,10 @@ import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenToo import { attributionLine } from "umtool-report-to-video/attribution"; 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 { gapSpan, gappedLength, validateGaps } from "umtool-report-to-video/gaps"; +import { gapSpan, gapWalls, gappedLength, validateGaps } from "umtool-report-to-video/gaps"; import { useGapEditor } from "./bench/useGapEditor"; import { BenchWaveBox, GapTools } from "./bench/BenchWave"; +import { CutEdges } from "./bench/CutEdges"; import { sourceWindowMedia } from "./bench/benchMedia"; import { useBenchPlayer } from "./bench/useBenchPlayer"; import { usePeaks } from "./bench/usePeaks"; @@ -142,6 +143,12 @@ type Clip = { * not drafted like the edges; every playback here skips them. */ gaps: Span[]; + /** + * The seconds no gap may cover (lane/clip-fixes): each claim mark's or + * stamp's `at` (`claims`, else `claim`; gaps.mjs gapWalls), read so the + * bench's check of a gap is the writer's whole rule, not most of it. + */ + marks: { id: string | null; at: number }[]; /** "confirmed" / "incorrect" / "rejected", or null for "nobody has looked at this yet". */ verdict: "confirmed" | "incorrect" | "rejected" | null; /** An editorial note from the walk -- not a correction (a fact error). Never rendered. */ @@ -212,6 +219,12 @@ const attribValue = (c: Clip, k: AttribKey): string => const emptyDraft = (c: Clip) => Object.fromEntries(ATTRIB.map(([k]) => [k, attribValue(c, k)])) as Record<AttribKey, string>; +/** An entry's claim marks' and stamp's seconds (gapWalls), as the bench holds them. */ +const marksOf = (e: Record<string, unknown>): Clip["marks"] => + gapWalls({ ...e, type: "clip", muteFrom: null }) + .marks.filter((m) => m.kind !== "mute") + .map((m) => ({ id: m.id, at: m.at })); + /** * A saved entry, back into the shape this component holds. * @@ -238,6 +251,7 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({ lockCut: !!e.lockCut, muteFrom: e.muteFrom == null ? null : Number(e.muteFrom), gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [], + marks: Array.isArray(e.marks) ? (e.marks as Clip["marks"]) : marksOf(e), verdict: e.verdict === "confirmed" || e.verdict === "incorrect" || e.verdict === "rejected" ? e.verdict : null, walkNote: (e.walkNote as string) ?? null, star: e.star === true, @@ -294,8 +308,8 @@ export type ClipBenchData = { cues: Cue[]; token: string | null; fetchPad: number; - /** The widest pad `/api/report/fetch` will accept. */ - maxPad: number; + /** The widest window `/api/report/fetch` will ask for, end to end, in seconds (the editor's cap). */ + maxWindow: number; /** A /mix deep link for this clip's cached window, or null. Server-built. */ mixHref: string | null; /** Every other clip in the cut from this same recording, by start. */ @@ -1285,25 +1299,140 @@ export default function ClipBench({ // -- 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 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"); + // + // WHERE A GAP MAY GO (lane/clip-fixes): the cut when the clip has one, else + // the extent AS DRAFTED -- an edge dragged out over a wider fetch is where + // the operator is cutting, and the window patch rides along with the gap's + // write (as it does with a Confirm), so the writer checks the gap against + // the extent it will have. Before, the saved extent was a wall the drag + // stopped at with nothing on screen to say so. + const draftEntry = useMemo( + () => ({ + type: "clip" as const, + id: clip.id, + start: windowMoved ? round2(sel.from) : clip.start, + end: windowMoved ? round2(sel.to) : clip.end, + cutStart: clip.cutStart, + cutEnd: clip.cutEnd, + muteFrom: windowMoved || muteMoved ? mute : clip.muteFrom, + // The marks too: the writer refuses a gap over one, so the check here does. + claims: (clip.marks ?? []).map((m) => (m.id ? { id: m.id, at: m.at } : { at: m.at })), + }), + [clip.id, clip.start, clip.end, clip.cutStart, clip.cutEnd, clip.muteFrom, clip.marks, windowMoved, muteMoved, sel.from, sel.to, mute], + ); + const gapsSpan = gapSpan(draftEntry); + // Every wall a gap stops at, drawn (bench/GapsZoom.tsx GapWallsLayer). + const walls = useMemo(() => gapWalls({ ...draftEntry, gaps: clip.gaps ?? [] }), [draftEntry, clip.gaps]); + const gapRefusalFor = useCallback( + (gaps: Span[], over: Partial<typeof draftEntry> = {}) => { + const errs = validateGaps({ ...draftEntry, ...over, 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], + [draftEntry], ); + const gapRefusal = useCallback((gaps: Span[]) => gapRefusalFor(gaps), [gapRefusalFor]); + /** A cut narrower than the extent: the wall a gap (and the video) stops at. */ + const hasCut = clip.cutStart != null && clip.cutEnd != null; + const cutNarrower = hasCut && (clip.cutStart! > sel.from + 0.05 || clip.cutEnd! < sel.to - 0.05); // bench/useGapEditor.ts, writing through the window writer: `gapAdd` / `gapRemove`, Undo the whole list. const gap = useGapEditor({ key: clip.id, gaps: clip.gaps ?? [], - span: gapSpan(clip), + span: gapsSpan, refusal: gapRefusal, - write: (op, _next) => save("add" in op ? { gapAdd: op.add } : "remove" in op ? { gapRemove: (op.remove.from + op.remove.to) / 2 } : { gaps: op.set }), - said: (next) => `the cut plays ${gappedLength(gapSpan(clip).from, gapSpan(clip).to, next).toFixed(2)} s, one segment`, + write: async (op, _next) => { + // A moved edge rides along: the gap was checked against the extent as drafted. + const win = windowMoved || muteMoved ? windowPatch() : null; + const ok = await save({ + ...(win ?? {}), + ...("add" in op ? { gapAdd: op.add } : "remove" in op ? { gapRemove: (op.remove.from + op.remove.to) / 2 } : { gaps: op.set }), + }); + return ok; + }, + said: (next) => + `the cut plays ${gappedLength(gapsSpan.from, gapsSpan.to, next).toFixed(2)} s, one segment${windowMoved ? " (the window you moved was saved with it)" : ""}`, setNote, fmt: hms, + wall: (side, at) => + hasCut + ? `stopped at the cut's ${side} (${hms(at)}) — gaps go inside the cut: drag its edge on the waveform, or Use the whole clip` + : side === "end" + ? `stopped at the clip's end (${hms(at)}) — drag the clip's end out first${atEndEdge ? ", past the cache: Fetch more" : ""}` + : `stopped at the clip's start (${hms(at)}) — drag the clip's start out first${atStartEdge ? ", past the cache: Fetch more" : ""}`, }); + // ---- the cut's edges, on the waveform ---------------------------------------- + // + // Drawn and dragged there (bench/CutEdges.tsx), written on release through + // the window writer with an Undo -- as are Use the whole clip and Clear cut. + // A gap left outside the new cut is refused here first, with the writer's + // sentence; a moved extent rides along, as with a gap. + const [cutDraft, setCutDraft] = useState<Span | null>(null); + const [cutUndo, setCutUndo] = useState<{ cutStart: number | null; cutEnd: number | null; lockCut: boolean; what: string } | null>(null); + useEffect(() => { + setCutDraft(null); + setCutUndo(null); + }, [clip.id]); + const writeCut = useCallback( + async (next: Span | null, what: string) => { + const before = { cutStart: clip.cutStart, cutEnd: clip.cutEnd, lockCut: clip.lockCut }; + const cutPatch = next ? { cutStart: round2(next.from), cutEnd: round2(next.to) } : { cutStart: "", cutEnd: "", lockCut: false }; + const why = gapRefusalFor(clip.gaps ?? [], next ? { cutStart: round2(next.from), cutEnd: round2(next.to) } : { cutStart: null, cutEnd: null }); + if (why) { + setCutDraft(null); + setNote(`the cut was not moved: ${why}`); + return false; + } + const win = windowMoved || muteMoved ? windowPatch() : null; + const ok = await save({ ...(win ?? {}), ...cutPatch }); + setCutDraft(null); + if (ok) { + setCutUndo({ ...before, what }); + setNote(`${what}${win ? " — the window you moved was saved with it" : ""}`); + } + return ok; + }, + [clip.cutStart, clip.cutEnd, clip.lockCut, clip.gaps, gapRefusalFor, windowMoved, muteMoved, windowPatch, save], + ); + const takeWholeClip = useCallback( + () => void writeCut(null, "the cut cleared — the whole clip plays, and gaps can go anywhere in it"), + [writeCut], + ); + const undoCut = useCallback(async () => { + const u = cutUndo; + if (!u) return; + const ok = await save( + u.cutStart != null && u.cutEnd != null + ? { cutStart: u.cutStart, cutEnd: u.cutEnd, lockCut: u.lockCut } + : { cutStart: "", cutEnd: "", lockCut: false }, + ); + if (ok) { + setCutUndo(null); + setNote(`undone — ${u.what.split(" — ")[0]} is reversed`); + } + }, [cutUndo, save]); + const onCutDrag = useCallback( + (side: "start" | "end", t: number, done: boolean) => { + if (clip.cutStart == null || clip.cutEnd == null) return; + const cur = cutDraft ?? { from: clip.cutStart, to: clip.cutEnd }; + // Inside the extent as drafted, and at least half a second (the writer's rule). + const next = + side === "start" + ? { from: Math.max(sel.from, Math.min(t, cur.to - 0.5)), to: cur.to } + : { from: cur.from, to: Math.min(sel.to, Math.max(t, cur.from + 0.5)) }; + if (!done) { + setCutDraft(next); + return; + } + if (Math.abs(next.from - clip.cutStart) < 0.005 && Math.abs(next.to - clip.cutEnd) < 0.005) { + setCutDraft(null); + return; + } + void writeCut(next, `the cut moved to ${hms(next.from)}–${hms(next.to)}`); + }, + [clip.cutStart, clip.cutEnd, cutDraft, sel.from, sel.to, writeCut], + ); + // ---- 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. @@ -1811,15 +1940,33 @@ export default function ClipBench({ const reachBefore = cached ? clip.start - cached.from : 0; const reachAfter = cached ? cached.to - clip.end : 0; const peekOutside = peek.some((c) => c.start < view.from - 0.02 || c.end > view.to + 0.02); - const nextBefore = Math.min(data.maxPad, Math.round(reachBefore) + 20); - const nextAfter = Math.min(data.maxPad, Math.round(reachAfter) + 20); + // THE NEXT ASK GOES ON FROM WHERE THE EDGE IS NOW -- the cached edge, or an + // unsaved drag out to it -- so every press reaches further. The pads are the + // fetch's, measured from the SAVED edges; the only cap is the WINDOW's, end + // to end (the editor's, data.maxWindow), never a fixed reach per side: a + // cap of 120 s from the saved edge was the wall a long drag stopped at + // (lane/clip-fixes). Twenty seconds a press close in, a minute once the + // edge is already far out. + const clipLen = clip.end - clip.start; + const stepFrom = (reach: number) => (reach < 40 ? 20 : 60); + /** The most one side may ask for with the other kept as it is. */ + const capBefore = Math.max(0, Math.floor(data.maxWindow - clipLen - reachAfter)); + const capAfter = Math.max(0, Math.floor(data.maxWindow - clipLen - reachBefore)); + const edgeBefore = Math.max(reachBefore, clip.start - sel.from); + const edgeAfter = Math.max(reachAfter, sel.to - clip.end); + const nextBefore = Math.min(capBefore, Math.round(edgeBefore) + stepFrom(edgeBefore)); + const nextAfter = Math.min(capAfter, Math.round(edgeAfter) + stepFrom(edgeAfter)); // A side stops being worth offering for two different reasons, and they are - // different sentences: the pad cap, and the end of the recording itself. + // different sentences: the window cap, and the end of the recording itself. const atStartOfSource = !!cached && cached.from <= 0.02; const atEndOfSource = !!cached && sourceDuration != null && cached.to >= sourceDuration - 0.02; - const beforeMaxed = reachBefore >= data.maxPad - 0.5 || atStartOfSource; - const afterMaxed = reachAfter >= data.maxPad - 0.5 || atEndOfSource; + const beforeAtCap = nextBefore <= reachBefore + 0.5; + const afterAtCap = nextAfter <= reachAfter + 0.5; + const beforeMaxed = beforeAtCap || atStartOfSource; + const afterMaxed = afterAtCap || atEndOfSource; + /** What a side at the window cap says: the limit, and the next step. */ + const capSentence = `a fetched window is at most ${Math.round(data.maxWindow / 60)} min end to end — Fetch whole source for more`; const atMaxPad = beforeMaxed && afterMaxed; /** Keep the side that is not being extended exactly where it is. */ const keepBefore = round2(reachBefore); @@ -1846,8 +1993,8 @@ export default function ClipBench({ const padsForCue = (c: Cue) => { const after = c.end > view.to; return { - padBefore: after ? keepBefore : Math.min(data.maxPad, Math.ceil(clip.start - (c.start - 2))), - padAfter: after ? Math.min(data.maxPad, Math.ceil(c.end + 2 - clip.end)) : keepAfter, + padBefore: after ? keepBefore : Math.min(capBefore, Math.ceil(clip.start - (c.start - 2))), + padAfter: after ? Math.min(capAfter, Math.ceil(c.end + 2 - clip.end)) : keepAfter, }; }; const padLabelForCue = (c: Cue) => @@ -1871,6 +2018,80 @@ export default function ClipBench({ // otherwise blank the line the composition was built with. const osTexts: DeckTexts = osAuto ? { [clip.id]: osShown } : {}; const osChanged = !sameOs(os, osDraftOf(clip.onscreen)); + + // ---- coming back to the page ------------------------------------------------ + // + // The back button restores this page as it was shown (the browser's page + // cache: pageshow, persisted; or Next's router cache, which remounts it with + // the payload it had then), and a hidden tab comes back to whatever happened + // meanwhile -- a window fetched, the clip saved from another tab. Operator, + // 6 Nov: "I just had to refresh. Maybe address that so it updates if you + // click the back button." So: read the clip's state again on pageshow + // (persisted), on visibilitychange -> visible and once on mount, through the + // same route a fetch reads -- never while something is in flight or a gap or + // cut edge is being dragged, nor over anything unsaved (an edge, the mark, a + // field): those keep the token they were drafted against, so the writer's + // stale check still guards them. + const returnState = useRef({ busy: false, clean: true }); + returnState.current = { + busy: !!busy || !!gap.sel || gap.pick || cutDraft != null, + clean: !dirty && !muteMoved && !osChanged && ATTRIB.every(([k]) => draft[k] === attribValue(clip, k)), + }; + const windowsRef = useRef(windows); + windowsRef.current = windows; + const clipRef = useRef(clip); + clipRef.current = clip; + const resync = useCallback(async () => { + const ok = () => !returnState.current.busy && returnState.current.clean; + if (!ok()) return; + const r = await fetch( + `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`, + { cache: "no-store" }, + ).catch(() => null); + if (!r?.ok) return; + const j = (await r.json()) as ClipBenchData & { clip: Record<string, unknown> }; + if (!ok()) return; + const wk = (ws: Win[]) => ws.map((w) => `${w.name}|${w.from}|${w.to}|${w.v ?? ""}`).join(","); + if (wk(j.windows) !== wk(windowsRef.current)) { + setWindows(j.windows); + setCues(j.cues); + if (j.windows[0]) setView({ from: j.windows[0].from, to: j.windows[0].to }); + } + setProposed(j.proposed); + setSegment(j.segment); + setSegmentMtime(j.segmentMtime); + if (j.token !== token.current) { + token.current = j.token; + const next = fromEntry(clipRef.current, j.clip); + setClip(next); + setSel({ from: next.start, to: next.end }); + setDirty(false); + setMute(next.muteFrom); + muteRef.current = next.muteFrom; + setDraft(emptyDraft(next)); + setOs(osDraftOf(next.onscreen)); + } + }, [data.project, clip.id, tq]); + const resyncRef = useRef(resync); + resyncRef.current = resync; + useEffect(() => { + const again = () => void resyncRef.current(); + const onShow = (e: PageTransitionEvent) => { + if (e.persisted) again(); + }; + const onVis = () => { + if (document.visibilityState === "visible") again(); + }; + window.addEventListener("pageshow", onShow); + document.addEventListener("visibilitychange", onVis); + // Once on mount: Next's router restores a page gone back to from its own + // cache, with no pageshow -- and a fresh load pays one small request. + again(); + return () => { + window.removeEventListener("pageshow", onShow); + document.removeEventListener("visibilitychange", onVis); + }; + }, [clip.id]); const osOver = osShown.title.length > osMax; // The strip follows the player when the player is inside what the cut // plays, mapped onto the cut's clock; anywhere else it holds mid-segment. @@ -2337,8 +2558,8 @@ export default function ClipBench({ onFetch={(edge, t) => void fetchMore( edge === "end" - ? { padBefore: keepBefore, padAfter: Math.min(data.maxPad, Math.ceil(t + 2 - clip.end)) } - : { padBefore: Math.min(data.maxPad, Math.ceil(clip.start - (t - 2))), padAfter: keepAfter }, + ? { padBefore: keepBefore, padAfter: Math.min(capAfter, Math.ceil(t + 2 - clip.end)) } + : { padBefore: Math.min(capBefore, Math.ceil(clip.start - (t - 2))), padAfter: keepAfter }, ) } /> @@ -2893,11 +3114,23 @@ export default function ClipBench({ data-cut-clear="" className={buttonVariants({ size: "sm" })} disabled={!!busy} - onClick={() => void save({ cutStart: "", cutEnd: "", lockCut: false })} + onClick={takeWholeClip} > Clear cut </button> )} + {cutUndo && ( + <button + type="button" + data-cut-undo="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + title={`undo: ${cutUndo.what}`} + onClick={() => void undoCut()} + > + Undo cut + </button> + )} </span> {/* ---- the MUTE MARK ---- Beside the cut because it is the same kind of decision -- what @@ -2966,7 +3199,35 @@ export default function ClipBench({ {/* ---- 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("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> + <div data-bench-sel={`${sel.from.toFixed(2)}-${sel.to.toFixed(2)}`} className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> + {/* A cut narrower than the clip: the wall a gap -- and the video -- stops + at, said above the waveform it is drawn on, with the way out. */} + {cutNarrower && ( + <div data-cut-limits={`${clip.cutStart}-${clip.cutEnd}`} className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-good)] px-2 py-1 text-[12px]"> + <span className="text-[var(--color-text)]"> + The video plays only the cut{" "} + <span className="num"> + {hms(clip.cutStart!)}–{hms(clip.cutEnd!)} + </span> + , and gaps go inside it{" "} + <span className="text-[var(--color-dim)]"> + (the clip is {hms(sel.from)}–{hms(sel.to)} + {clip.lockCut ? "; the cut is pinned" : ""}) + </span> + </span> + <button + type="button" + data-cut-use-whole="" + className={buttonVariants({ size: "sm" })} + disabled={!!busy} + title="clear the cut: the whole clip plays, and gaps can go anywhere in it (Undo puts the cut back)" + onClick={takeWholeClip} + > + Use the whole clip + </button> + <span className="text-[var(--color-dim)]">or drag the cut&apos;s edges (the green tabs) on the waveform</span> + </div> + )} {/* Zoomed: round ticks over what is shown. */} {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} <BenchWaveBox @@ -2983,6 +3244,7 @@ export default function ClipBench({ words={nearWords?.words ?? null} busy={!!busy} held={mutePick} + walls={walls} > {/* The mute mark over the waveform: a line where the sound stops and a hatch over what is silent to the end of the selection. @@ -3009,6 +3271,17 @@ export default function ClipBench({ </div> </> )} + {/* The cut, when the clip has one: its edges, dragged here (bench/CutEdges.tsx). */} + {hasCut && ( + <CutEdges + vis={zoom.vis} + cut={cutDraft ?? { from: clip.cutStart!, to: clip.cutEnd! }} + extent={sel} + busy={!!busy} + fmt={hms} + onDrag={onCutDrag} + /> + )} {/* Where the render will actually cut: each edge snapped to its silence, faint. */} <RenderGhosts edges={renderEdges} view={zoom.vis} /> {/* Armed: the next click places the mark rather than an edge. */} @@ -3029,7 +3302,7 @@ export default function ClipBench({ {/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */} <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> {/* ---- GAPS inside the clip (bench/BenchWave.tsx GapTools) ---- */} - <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapSpan(clip)} sel={sel} busy={!!busy} fmt={hms} play={play} /> + <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapsSpan} sel={sel} busy={!!busy} fmt={hms} play={play} /> <TightenButtons tools={edgeTools} busy={!!busy} /> <span className="micro max-md:hidden"> <kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "} @@ -3059,7 +3332,7 @@ export default function ClipBench({ <span data-fetch-before-maxed="" className="text-[var(--color-dim)]"> {atStartOfSource ? "the recording starts here" - : `−${data.maxPad} s is the widest one side goes`} + : capSentence} </span> ) : ( <button @@ -3076,7 +3349,7 @@ export default function ClipBench({ <span data-fetch-after-maxed="" className="text-[var(--color-dim)]"> {atEndOfSource ? "the recording ends here" - : `+${data.maxPad} s is the widest one side goes`} + : capSentence} </span> ) : ( <button diff --git a/umtool/components/projects/bench/BenchWave.tsx b/umtool/components/projects/bench/BenchWave.tsx @@ -4,7 +4,7 @@ import { useRef } from "react"; import Waveform, { type Peaks } from "@/components/Waveform"; import { buttonVariants } from "@/components/ui/button"; import { GAP_LIMITS, gappedLength } from "umtool-report-to-video/gaps"; -import { GapLayer, type WaveZoom } from "./GapsZoom"; +import { GapLayer, type GapWallsView, type WaveZoom } from "./GapsZoom"; import type { Span } from "./benchMedia"; import type { GapEditor } from "./useGapEditor"; @@ -34,6 +34,7 @@ export function BenchWaveBox({ words, busy, held = false, + walls = null, children, }: { zoom: WaveZoom; @@ -51,6 +52,8 @@ export function BenchWaveBox({ busy: boolean; /** Another pick is armed (the mute mark's): Alt + drag and the gap pick stand down. */ held?: boolean; + /** Where a gap cannot go, and why (gaps.mjs gapWalls), drawn on the waveform. */ + walls?: GapWallsView | null; children?: React.ReactNode; }) { const altDrag = useRef<{ id: number; at: number } | null>(null); @@ -109,6 +112,8 @@ export function BenchWaveBox({ vis={zoom.vis} gaps={gaps} selection={gap.sel} + live={gap.live} + walls={walls} picking={gap.pick && !held} silences={silences} words={words} diff --git a/umtool/components/projects/bench/CutEdges.tsx b/umtool/components/projects/bench/CutEdges.tsx @@ -0,0 +1,113 @@ +"use client"; + +import { useRef } from "react"; +import type { Span } from "./benchMedia"; + +// --------------------------------------------------------------------------- +// THE CUT ON THE WAVEFORM (lane/clip-fixes). A clip's cut (`cutStart`–`cutEnd`) +// is what the video plays, inside the extent; gaps lie inside it. It used to be +// drawn only on the rail, so a cut narrower than the extent -- a locked clause +// cut kept from an earlier pass, under an extent since widened -- was a wall a +// gap drag stopped at with nothing on the waveform to say why (operator, 6 Nov: +// "I can't add gaps beyond like 9:21"). Here: the seconds of the extent outside +// the cut shaded, each cut edge a line in the cut's colour, and a tab on it +// that drags the edge (written on release, by the caller, with an Undo). The +// line itself never takes a pointer: the waveform's own drag goes on under it. +// --------------------------------------------------------------------------- + +export function CutEdges({ + vis, + cut, + extent, + busy, + fmt, + onDrag, +}: { + /** What the waveform shows. */ + vis: Span; + /** The cut, as saved or as being dragged. */ + cut: Span; + /** The extent the cut lies in (the selection as drafted). */ + extent: Span; + busy: boolean; + fmt: (t: number) => string; + /** An edge dragged to `t`; `done` on release. */ + onDrag: (side: "start" | "end", t: number, 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 drag = useRef<{ id: number; side: "start" | "end" } | null>(null); + const tAt = (el: HTMLElement, clientX: number) => { + const box = (el.closest("[data-wave-box]") as HTMLElement | null) ?? el; + const r = box.getBoundingClientRect(); + return vis.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * span; + }; + const outside: Array<{ side: "start" | "end"; from: number; to: number }> = []; + if (cut.from > extent.from + 0.01) outside.push({ side: "start", from: extent.from, to: cut.from }); + if (cut.to < extent.to - 0.01) outside.push({ side: "end", from: cut.to, to: extent.to }); + const inView = (s: { from: number; to: number }) => s.to > vis.from && s.from < vis.to; + return ( + <> + {outside.filter(inView).map((o) => ( + <div + key={`out-${o.side}`} + data-wave-outside-cut={o.side} + title={`${fmt(o.from)}–${fmt(o.to)} is in the clip but not in its cut: the video does not play it, and no gap can go here`} + className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(-45deg,color-mix(in_srgb,var(--color-good)_16%,transparent)_0_2px,transparent_2px_8px)]" + style={{ left: pct(o.from), width: width(o.from, o.to) }} + /> + ))} + {(["start", "end"] as const).map((side) => { + const t = side === "start" ? cut.from : cut.to; + if (t < vis.from || t > vis.to) return null; + return ( + <div + key={side} + data-wave-cut-edge={side} + data-wave-cut-at={t.toFixed(2)} + className="pointer-events-none absolute top-0 z-[4] h-full border-l-2 border-[var(--color-good)]" + style={{ left: pct(t) }} + > + <button + type="button" + data-wave-cut-grip={side} + disabled={busy} + title={`the cut's ${side}, ${fmt(t)}: the video plays from the cut's start to its end, and gaps go inside it — drag to move it`} + className={ + side === "start" + ? "pointer-events-auto absolute left-0 top-4 cursor-ew-resize touch-none select-none whitespace-nowrap rounded-r bg-[var(--color-good)] px-1 font-mono text-[9px] font-semibold leading-[14px] text-[var(--color-ground)] disabled:cursor-default" + : "pointer-events-auto absolute right-0.5 top-4 cursor-ew-resize touch-none select-none whitespace-nowrap rounded-l bg-[var(--color-good)] px-1 font-mono text-[9px] font-semibold leading-[14px] text-[var(--color-ground)] disabled:cursor-default" + } + onPointerDown={(e) => { + if (busy) return; + e.preventDefault(); + e.stopPropagation(); + e.currentTarget.setPointerCapture(e.pointerId); + drag.current = { id: e.pointerId, side }; + }} + onPointerMove={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + onDrag(d.side, tAt(e.currentTarget, e.clientX), false); + }} + onPointerUp={(e) => { + const d = drag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + drag.current = null; + onDrag(d.side, tAt(e.currentTarget, e.clientX), true); + }} + onPointerCancel={() => { + drag.current = null; + }} + > + {side === "start" ? "cut ▸" : "◂ cut"} + </button> + </div> + ); + })} + </> + ); +} diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx @@ -181,6 +181,15 @@ export function ZoomRuler({ vis }: { vis: Span }) { * 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. */ +/** What GapLayer draws of the walls: gapWalls's shape, the zones' kinds open (a reel adds its master's gaps). */ +export type GapWallsView = { + span: Span; + /** What the span is called in a sentence: "cut", "clip", "beat". */ + whose: string; + zones: Array<{ from: number; to: number; kind: string; why: string }>; + marks: Array<{ at: number; kind: string; why: string }>; +}; + export function GapLayer({ vis, gaps, @@ -191,10 +200,22 @@ export function GapLayer({ busy, onRemove, onSelect, + live = null, + walls = null, }: { vis: Span; gaps: Span[]; selection: Span | null; + /** What the selection would do, checked on every move (useGapEditor's GapLive). */ + live?: { why: string | null; wall: string | null; merged: { from: number; to: number } | null; short: boolean } | null; + /** + * Where a gap cannot go, and why (gaps.mjs gapWalls, or a reel beat's own): + * drawn so no wall a gap drag stops at is invisible -- outside the span and + * the keep bands shaded (a strip along the foot always, the full height + * while a gap is being picked), each mark a gap can't cover ticked, every + * one with its sentence on hover. + */ + walls?: GapWallsView | null; picking: boolean; silences: Span[] | null; /** The recording's words (the clip-editor route's): timed (`end`), or a caption word's start only. */ @@ -258,6 +279,7 @@ export function GapLayer({ {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) }} /> ))} + {walls && <GapWallsLayer walls={walls} vis={vis} pct={pct} width={width} full={picking || !!selection} />} {gaps.filter(inView).map((g) => ( <button key={`gap-${g.from}`} @@ -276,11 +298,37 @@ export function GapLayer({ {selection && inView(selection) && ( <div data-gap-selection={`${selection.from.toFixed(2)}-${selection.to.toFixed(2)}`} + data-gap-selection-state={live?.short ? "short" : live?.why ? "refused" : live?.merged ? "merge" : "ok"} 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)]" + className={ + live?.why && !live.short + ? "pointer-events-none absolute top-0 z-[6] h-full border-x-2 border-solid border-[var(--color-bad)] bg-[color-mix(in_srgb,var(--color-bad)_30%,transparent)]" + : "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) }} /> )} + {/* What the selection would do, said while it is dragged: the writer's + refusal, the wall it stopped at, the gap it would merge into. */} + {selection && live && (live.why || live.wall || live.merged) && ( + <div + data-gap-selection-why={live.short ? "short" : live.why ? "refused" : live.wall ? "wall" : "merge"} + role="status" + className={ + live.why && !live.short + ? "pointer-events-none absolute inset-x-1 bottom-1 z-[9] line-clamp-2 rounded bg-[var(--color-panel-2)] px-1.5 py-0.5 text-[11px] leading-tight text-[var(--color-bad)] shadow" + : "pointer-events-none absolute inset-x-1 bottom-1 z-[9] line-clamp-2 rounded bg-[var(--color-panel-2)] px-1.5 py-0.5 text-[11px] leading-tight text-[var(--color-dim)] shadow" + } + > + {[ + live.why ? (live.short ? live.why : `can't cut: ${live.why}`) : null, + live.merged ? `touches a gap — cutting makes one gap ${live.merged.from.toFixed(2)}–${live.merged.to.toFixed(2)}` : null, + live.wall, + ] + .filter(Boolean) + .join(" · ")} + </div> + )} {picking && ( <div data-gap-pick-layer="" @@ -468,3 +516,84 @@ export function ZoomOverview({ </div> ); } + + +/** The walls (GapLayer's `walls`): no-cut zones and the marks a gap can't cover. */ +function GapWallsLayer({ + walls, + vis, + pct, + width, + full, +}: { + walls: GapWallsView; + vis: Span; + pct: (t: number) => string; + width: (a: number, b: number) => string; + /** A gap is being picked: shade the full height, not just the foot. */ + full: boolean; +}) { + const inView = (a: number, b: number) => b > vis.from && a < vis.to; + const zones: Array<{ from: number; to: number; kind: string; why: string }> = []; + if (walls.span.from > vis.from) zones.push({ from: vis.from, to: walls.span.from, kind: "outside", why: `before the ${walls.whose}'s start: a gap goes inside the ${walls.whose}` }); + if (walls.span.to < vis.to) zones.push({ from: walls.span.to, to: vis.to, kind: "outside", why: `after the ${walls.whose}'s end: a gap goes inside the ${walls.whose}` }); + zones.push(...walls.zones.filter((z) => z.to > z.from)); + return ( + <> + {zones + .filter((z) => inView(z.from, z.to)) + .map((z, k) => ( + <div + key={`nocut-${k}-${z.from}`} + data-gap-nocut={z.kind} + data-gap-nocut-at={`${z.from.toFixed(2)}-${z.to.toFixed(2)}`} + title={`no gap here — ${z.why}`} + className={ + full + ? "pointer-events-none absolute bottom-0 z-[3] h-full [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-bad)_20%,transparent)_0_2px,transparent_2px_6px)]" + : "absolute bottom-0 z-[3] h-1.5 [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-bad)_55%,transparent)_0_2px,transparent_2px_5px)]" + } + style={{ left: pct(z.from), width: width(z.from, z.to) }} + /> + ))} + {/* The cut's own edges, labelled: where the span of gaps starts and ends. */} + {(["start", "end"] as const).map((side) => { + const t = side === "start" ? walls.span.from : walls.span.to; + if (!(t >= vis.from && t <= vis.to)) return null; + return ( + <div + key={`edge-${side}`} + data-gap-span-edge={side} + aria-hidden + className={ + side === "start" + ? "pointer-events-none absolute bottom-1.5 z-[3] translate-x-0.5 whitespace-nowrap font-mono text-[9px] leading-none text-[var(--color-bad)]" + : "pointer-events-none absolute bottom-1.5 z-[3] -translate-x-full whitespace-nowrap pr-0.5 font-mono text-[9px] leading-none text-[var(--color-bad)]" + } + style={{ left: pct(t) }} + > + {side === "start" ? `${walls.whose} ▸` : `◂ ${walls.whose}`} + </div> + ); + })} + {walls.marks + .filter((m) => m.at >= vis.from && m.at <= vis.to) + .map((m) => ( + <div + key={`mark-${m.kind}-${m.at}`} + data-gap-wall-mark={m.at} + data-gap-wall-mark-kind={m.kind} + className="pointer-events-none absolute top-0 z-[6] h-full border-l border-dashed border-[var(--color-bad)]" + style={{ left: pct(m.at) }} + > + <span + title={`a gap can't cover this — ${m.why}`} + className="pointer-events-auto absolute bottom-1.5 -translate-x-1/2 cursor-help rounded-sm bg-[var(--color-bad)] px-0.5 font-mono text-[9px] leading-[11px] text-[var(--color-ground)]" + > + {m.kind === "mute" ? "mute" : m.kind === "stamp" ? "stamp" : "mark"} + </span> + </div> + ))} + </> + ); +} diff --git a/umtool/components/projects/bench/useGapEditor.ts b/umtool/components/projects/bench/useGapEditor.ts @@ -18,6 +18,16 @@ import type { Span } from "./benchMedia"; export type GapOp = { add: Span } | { remove: Span } | { set: Span[] }; +/** + * What the span being dragged for a gap would do, said WHILE it is dragged + * (lane/clip-fixes, operator 6 Nov: "the gap tool gets blocked at random + * invisible walls"): the writer's refusal (`why`, the same sentence the + * writer would answer with), the wall the drag stopped at (`wall`), the + * neighbour a touching span merges into (`merged`, the gap it would make), and + * `short` under the shortest gap. + */ +export type GapLive = { why: string | null; wall: string | null; merged: Span | null; short: boolean }; + const r2 = (n: number) => Number(n.toFixed(2)); export function useGapEditor({ @@ -29,6 +39,7 @@ export function useGapEditor({ said, setNote, fmt, + wall, }: { /** What the gaps belong to: another one starts with nothing selected and nothing to undo. */ key: string; @@ -44,15 +55,22 @@ export function useGapEditor({ said: (next: Span[]) => string; setNote: (s: string | null) => void; fmt: (t: number) => string; + /** The sentence for a drag stopped at `span`'s edge (the clip's cut, a beat's end); a plain one without. */ + wall?: (side: "start" | "end", at: number) => string; }) { - const [sel, setSel] = useState<Span | null>(null); + const [sel, setSelState] = useState<Span | null>(null); + const [live, setLive] = useState<GapLive | null>(null); + const setSel = useCallback((s: Span | null | ((p: Span | null) => Span | null)) => { + setSelState(s); + if (s === null) setLive(null); + }, []); const [pick, setPick] = useState(false); const [undo, setUndo] = useState<{ gaps: Span[]; what: string } | null>(null); useEffect(() => { setSel(null); setPick(false); setUndo(null); - }, [key]); + }, [key, setSel]); const run = useCallback( async (op: GapOp, next: Span[], what: string) => { @@ -83,12 +101,19 @@ export function useGapEditor({ setNote(e instanceof Error ? e.message : String(e)); return; } - const ok = await run({ add: g }, next, `cut ${fmt(g.from)}–${fmt(g.to)} out`); + // A span touching a gap GROWS it (editGaps): say which one it became. + const grown = next.find((x) => x.from <= g.from + 1e-6 && x.to >= g.to - 1e-6); + const merged = grown && (Math.abs(grown.from - g.from) > 0.005 || Math.abs(grown.to - g.to) > 0.005) ? grown : null; + const ok = await run( + { add: g }, + next, + merged ? `cut ${fmt(g.from)}–${fmt(g.to)} out, merged with the gap beside it into ${fmt(merged.from)}–${fmt(merged.to)}` : `cut ${fmt(g.from)}–${fmt(g.to)} out`, + ); if (ok) { setSel(null); setPick(false); } - }, [sel, gaps, run, setNote, fmt]); + }, [sel, gaps, run, setNote, fmt, setSel]); const remove = useCallback( (g: Span) => { @@ -121,28 +146,58 @@ export function useGapEditor({ }); }, [undo, write, setNote]); - /** A span dragged for a gap: kept inside the span; under the shortest gap on release, dropped and said. */ + /** + * A span dragged for a gap: kept inside the span, and checked on EVERY move + * with the writer's own rule (`refusal`, the full validateGaps), so a wall is + * said while the span is being dragged into it, not after release. Under the + * shortest gap on release, dropped and said. + */ const select = useCallback( (s: Span, done: boolean) => { const from = Math.max(span.from, s.from); const to = Math.min(span.to, s.to); + // The clamp biting: the drag went past where a gap may go. + const side = s.from < span.from - 0.01 ? "start" : s.to > span.to + 0.01 ? "end" : null; + const at = side === "start" ? span.from : span.to; + const wallSaid = side ? (wall ? wall(side, at) : `stopped at the ${side} of where a gap may go (${fmt(at)})`) : null; + const short = to - from < GAP_LIMITS.min; + let why: string | null = null; + let merged: Span | null = null; + if (!short) { + const g = { from: r2(from), to: r2(to) }; + try { + const next = editGaps(gaps, { add: g }); + why = refusal(next); + const grown = next.find((x) => x.from <= g.from + 1e-6 && x.to >= g.to - 1e-6); + if (grown && (Math.abs(grown.from - g.from) > 0.005 || Math.abs(grown.to - g.to) > 0.005)) merged = grown; + } catch (e) { + why = e instanceof Error ? e.message : String(e); + } + } if (!done) { - setSel(to > from ? { from, to } : null); + setSelState(to > from ? { from, to } : null); + setLive(to > from ? { why: short ? `a gap is at least ${GAP_LIMITS.min} s` : why, wall: wallSaid, merged, short } : null); return; } - if (to - from < GAP_LIMITS.min) { + if (short) { setSel(null); - if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`); + if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span${wallSaid ? `; ${wallSaid}` : ""}`); + else if (wallSaid) setNote(wallSaid); return; } - setSel({ from, to }); - const why = refusal(editGaps(gaps, { add: { from: r2(from), to: r2(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`); + setSelState({ from, to }); + setLive({ why, wall: wallSaid, merged, short }); + const head = why + ? `this span cannot be cut: ${why}` + : merged + ? `${(to - from).toFixed(2)} s selected — it touches a gap, so Cut gap (g) makes them one: ${fmt(merged.from)}–${fmt(merged.to)}` + : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`; + setNote(wallSaid ? `${head} · ${wallSaid}` : head); }, - [span.from, span.to, gaps, refusal, setNote], + [span.from, span.to, gaps, refusal, setNote, fmt, wall, setSel], ); - return { sel, setSel, pick, setPick, undo, cut, remove, removeAt, undoLast, select }; + return { sel, setSel, live, pick, setPick, undo, cut, remove, removeAt, undoLast, select }; } export type GapEditor = ReturnType<typeof useGapEditor>; diff --git a/umtool/components/projects/reel/ReelBench.tsx b/umtool/components/projects/reel/ReelBench.tsx @@ -12,7 +12,7 @@ import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs"; import { fileSpans } from "@/lib/report/fileMedia.mjs"; import type { ReelBenchData } from "@/lib/report/reelBenchData"; import { cn } from "@/lib/utils"; -import { beatGapsOf, editGaps } from "umtool-report-to-video/gaps"; +import { beatGapsOf, editGaps, gapWalls } from "umtool-report-to-video/gaps"; import { BenchWaveBox, GapTools } from "../bench/BenchWave"; import { renderedFileMedia, type Span } from "../bench/benchMedia"; import { ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom } from "../bench/GapsZoom"; @@ -385,6 +385,14 @@ function BeatEditor({ const fmt = isClip ? sourceClock : clock; const kept = sel.to - sel.from - gaps.reduce((s, g) => s + Math.max(0, Math.min(g.to, sel.to) - Math.max(g.from, sel.from)), 0); const masterGaps = isClip ? m.map.gaps.filter((g) => g.to > span.from && g.from < span.to) : []; + // Where a gap cannot go in the beat, drawn as on the clip bench (lane/clip-fixes): the beat's + // edges and the keep bands, the clip rule's (gaps.mjs gapWalls), said as the beat's. The + // master's own gaps are drawn below, each with its title. + const walls = useMemo(() => { + if (!isClip) return null; + const w = gapWalls({ type: "clip", id: row.id ?? "beat", start: saved.from, end: saved.to, gaps }); + return { ...w, whose: "beat", zones: w.zones.map((z) => ({ ...z, why: z.why.replace("the clip's", "the beat's") })) }; + }, [isClip, row.id, saved.from, saved.to, gaps]); const confirmedCount = (view.rows ?? []).filter((x) => x.verdict === "confirmed").length; return ( @@ -449,13 +457,14 @@ function BeatEditor({ words={nearWords?.words ?? null} busy={busy} held={!isClip} + walls={walls} > {/* What the master already left out of the clip (its render's gaps): nothing plays there. */} {masterGaps.map((g) => ( <div key={`mg-${g.from}`} data-reel-master-gap={`${g.from}-${g.to}`} - title={`${sourceClock(g.from)}–${sourceClock(g.to)}: cut out of ${row.id} in the master (the clip's own gap) — edit it on the clip's walk`} + title={`${sourceClock(g.from)}–${sourceClock(g.to)}: cut out of ${row.id} in the master (the clip's own gap) — nothing plays here, so no beat gap can lie wholly inside it; edit it on the clip's walk`} className="pointer-events-none absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-dim)_25%,transparent)]" style={{ left: zpct(g.from), width: `calc(${zpct(g.to)} - ${zpct(g.from)})` }} /> diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -953,6 +953,31 @@ const Player = forwardRef<PlayerHandle, { clipId: string; targets: Target[]; cut // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, attempt]); + // COMING BACK TO THE PAGE (lane/clip-fixes; operator, 6 Nov: "I just had to + // refresh"): the back button restores this page from the browser's cache + // (pageshow, persisted) or a hidden tab comes back, and what is on disk may + // have changed meanwhile (a window fetched on the bench). Look again -- the + // same file at the same clock keeps playing (settle), so it costs a request. + useEffect(() => { + const again = () => { + const m = media.current; + if (m && !m.paused) return; + setAttempt((a) => a + 1); + }; + const onShow = (e: PageTransitionEvent) => { + if (e.persisted) again(); + }; + const onVis = () => { + if (document.visibilityState === "visible") again(); + }; + window.addEventListener("pageshow", onShow); + document.addEventListener("visibilitychange", onVis); + return () => { + window.removeEventListener("pageshow", onShow); + document.removeEventListener("visibilitychange", onVis); + }; + }, []); + // Another clip on the same file: go to its cut, paused. useEffect(() => { const m = media.current; diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -117,8 +117,24 @@ bench said *"fetched"* over a cache that had not moved. So the button computes its pad from what is on disk right now and **says the number** ("fetch to ±40 s"), the route refuses a window it can already serve (*"already cached to ±N s"*) rather than running a job to prove it, and a job that did run still has -to produce a wider file before the bench claims anything arrived. At -`FETCH_MAX_PAD` it says so instead of offering a press that cannot help. +to produce a wider file before the bench claims anything arrived. **Each press +goes on from where the edge is now** — the cache's edge, or an unsaved drag out +to it — twenty seconds further close in, a minute once the edge is 40 s out. +There is no cap per side (it was 120 s from the SAVED edge, and a long clip's +drag stopped dead there); the only cap is the window's, end to end: +`FETCH_MAX_WINDOW`, the editor's 900 s. At it the side says so — "a fetched +window is at most 15 min end to end — Fetch whole source for more" — and the +route refuses a wider ask with the same next step. + +**A cut narrower than the clip is drawn on the waveform** — its edges in the +cut's green with a `cut ▸` / `◂ cut` tab each, the clip's seconds outside it +hatched — and said above it: *The video plays only the cut …, and gaps go +inside it*. A gap dragged past it stops at it and says so while it is dragged. +The tabs drag the cut's edges (written on release, inside the extent as +drafted, a moved extent saved with it); **Use the whole clip** (and Clear cut) +clears it; **Undo cut** puts back what either did. A gap's span is the cut, +else the extent as DRAFTED: an edge dragged out over a wider fetch can be cut +into at once, and the moved window is saved with the gap. **One edge at a time.** Extending a window is nearly always one-sided — you want the sentence that follows, not another twenty seconds of the lead-in you diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -152,7 +152,7 @@ making two clips (a crossfade, a second rail pip, a second subtitle card). `gaps 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, + inside the clip's cut (`cutStart`–`cutEnd`, else its extent), at least 0.2 s, at most 40 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 @@ -1246,7 +1246,7 @@ Its cut is `takes/<t>/out/<slug>.<name>.mp4` (the trailer reel: `<slug>.trailer. | a reel's title, the take it is cut from | **title** | `trailer-beats <p> --reel R title <text>\|none` · `take <t>\|none` | `{op: "settings", title?, take?}` | | play the reel from a take's master: the crossfades, the clock against the limit, the strip of beats; `M` a note on the beat on screen (anchor `reel`), `E` walk it, `N`/`P` beats, `[`/`]` notes | **Play the reel** → `/projects/<p>/trailer/play?reel=&take=` (the take picker) | `umtool notes <p>` reads the notes | `GET /api/report/reel?project&reel&take` · the master: `GET /api/report/reel/media?project&take&what=master` | | walk a beat: the reel's own editor on the clip bench's parts -- the master's waveform (its envelope, on the clip's source clock) with the zoom (`z`/`Z`/`f`/`F`, Ctrl/⌘ + wheel; ruler, overview, close-in pauses and words), the handles and nudges (`[` `]` in, `,` `.` out, Shift 0.5 s; `I`/`O` at the playhead) held to what the master rendered of the clip (said when a handle hits it), exact playback (`Space`, `-`/`=` speed), tighten to the sentence and snap an edge to a pause; saved in the clip's source seconds (`Enter`), `R` puts back, `B` back to the reel | **Walk it** / `E` → `/projects/<p>/trailer/walk?reel=&take=&beat=n` | `trailer-beats <p> --reel R set <n> <from>-<to> [--take <t>]` | `{op: "set", index, patch: {start, end}, take?}` · the master: `GET /api/report/file?project&path&v` · its envelope `GET /api/report/peaks?project&path&from&to` · its sound `GET /api/report/audio?project&path&from&to` | -| a beat's **gaps**: seconds cut out of its middle, in the clip's source seconds -- two moments of one clip as one beat of jump cuts (the clip gap rule: ≥ 0.2 s each, 0.5 s kept before, between and after, at most 12); cut as the clip's gap renders (hard cuts, the sound faded 0.025 s), never the beat-to-beat crossfade; Play the reel skips them and its clock counts kept seconds; a gap wholly inside one the master already cut out of the clip is refused | the walk: `Alt` + drag on the waveform (or **Select a gap** / `g`), **Cut gap** (`g`), **Hear it**, a click on a gap's band puts it back, `G` the one at the playhead, **Undo** | `trailer-beats <p> --reel R gap <n> add <from>-<to>` · `gap <n> remove <second>` · `gap <n> clear` | `{op: "set", index, patch: {gaps: [{from, to}…]}}` | +| a beat's **gaps**: seconds cut out of its middle, in the clip's source seconds -- two moments of one clip as one beat of jump cuts (the clip gap rule: ≥ 0.2 s each, 0.5 s kept before, between and after, at most 40); cut as the clip's gap renders (hard cuts, the sound faded 0.025 s), never the beat-to-beat crossfade; Play the reel skips them and its clock counts kept seconds; a gap wholly inside one the master already cut out of the clip is refused | the walk: `Alt` + drag on the waveform (or **Select a gap** / `g`), **Cut gap** (`g`), **Hear it**, a click on a gap's band puts it back, `G` the one at the playhead, **Undo** | `trailer-beats <p> --reel R gap <n> add <from>-<to>` · `gap <n> remove <second>` · `gap <n> clear` | `{op: "set", index, patch: {gaps: [{from, to}…]}}` | | a beat's verdict: `confirmed` (Y, and on to the next) or `note` (a note left on it) | the walk's **Confirm (Y)** · **Note (M)** · **Clear verdict** | `trailer-beats <p> --reel R verdict <n> confirmed\|note\|clear` | `{op: "set", index, patch: {verdict}}` | | cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path; its record names the take's build, the master's mtime and the reel's version, so the Cut panel says when the master was re-rendered or the reel edited since | the Trailer page's **Cut the trailer**; its **Options**: close on the master's last S s (`--finale`), a file name (`--out`, a name only), a dry run | `umtool trailer <p> --reel <name> [--take <t>] [--finale S] [--out NAME] [--dry-run]` | `POST /api/report/reel {project, reel, take, finale?, out?, dryRun?}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -183,7 +183,7 @@ the verdict". Play the cut skips it like a fact error; a take does not refuse it `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 +the CUT (the extent when there is none), at least 0.2 s, at most 40, 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 diff --git a/umtool/e2e/clip-bench.spec.ts b/umtool/e2e/clip-bench.spec.ts @@ -1601,3 +1601,129 @@ test("the last attribution field is on screen at a laptop's 1366×768", async ({ await expect(page.locator("[data-reject-menu]")).toBeInViewport(); expect(await reachable()).toBeLessThanOrEqual(0); }); + + +// --------------------------------------------------------------------------- +// Fetch more goes on from where the edge is NOW (lane/clip-fixes; operator, +// 6 Nov: "I try to drag a clip and it just doesn't expand beyond a certain +// point"). The pads were capped at 120 s per side measured from the clip's +// SAVED edges, so an edge dragged (unsaved) to the cache's edge could never be +// given more than 120 s past where it was last saved. Now the only cap is the +// window's, end to end (the editor's 900 s). reach-fixture: r01 reachvid +// 300-306 on a recording 1000 s long, fetched through the editor stub. +// --------------------------------------------------------------------------- + +const REACH = "reports/reach-fixture"; +const REACH_MANIFEST = path.join(FIXTURE, "reports", "reach-fixture", "video.manifest.json"); +const reachClip = () => + (JSON.parse(readFileSync(REACH_MANIFEST, "utf8")) as { timeline: { id: string; start: number; end: number }[] }).timeline.find((e) => e.id === "r01")!; +const reachWindows = async (request: import("@playwright/test").APIRequestContext) => + ((await (await request.get(`/api/report/clip?project=${encodeURIComponent(REACH)}&clip=r01`)).json()) as { windows: { from: number; to: number }[] }).windows; +const waitJob = async (request: import("@playwright/test").APIRequestContext, id: string) => + expect + .poll(async () => ((await (await request.get(`/api/report/fetch?job=${id}`)).json()) as { job: { state: string } | null }).job?.state ?? "gone", { timeout: 120_000 }) + .not.toBe("running"); +/** The end handle dragged out past the waveform's right end: it stops at the cache's edge -- a drag, never a fetch. */ +const endToCacheEdge = async (page: import("@playwright/test").Page) => { + const canvas = page.locator("[data-wave-box] [data-testid=waveform]"); + await canvas.scrollIntoViewIfNeeded(); + const b = (await canvas.boundingBox())!; + const y = b.y + b.height / 2; + await page.mouse.move(b.x + b.width - 4, y); + await page.mouse.down(); + await page.mouse.move(b.x + b.width + 60, y, { steps: 3 }); + await page.mouse.up(); +}; +const selOf = async (page: import("@playwright/test").Page) => + ((await page.locator("[data-bench-sel]").getAttribute("data-bench-sel")) ?? "").split("-").map(Number); + +test("fetch more goes on from the edge as dragged, past 120 s from the saved edge, without saving", async ({ page, request }) => { + test.setTimeout(240_000); + // A window 100 s past the clip's end, as a long clip's first widening leaves it. + const seed = await request.post("/api/report/fetch", { data: { project: REACH, clip: "r01", padBefore: 3, padAfter: 100 } }); + expect(seed.status(), await seed.text()).toBe(202); + await waitJob(request, ((await seed.json()) as { job: { id: string } }).job.id); + expect((await reachWindows(request))[0].to).toBeCloseTo(406, 1); + + const posts: { padBefore: number; padAfter: number }[] = []; + page.on("request", (r) => { + if (r.method() === "POST" && r.url().endsWith("/api/report/fetch")) posts.push(r.postDataJSON()); + }); + await page.goto(urls.clipBenchHref(REACH, "r01")); + await expect(page.locator("[data-bench=r01]")).toBeVisible(); + + for (const [edge, ask] of [ + [406, 160], + [466, 220], + ] as const) { + await endToCacheEdge(page); + await expect.poll(async () => (await selOf(page))[1]).toBeCloseTo(edge, 0); + // From the edge as it is now (100 s, then 160 s out), a minute further: never capped at 120. + const after = page.locator("[data-fetch-after]"); + await expect(after).toHaveAttribute("data-fetch-after", String(ask)); + await after.click(); + await expect(page.locator("[data-bench-note]")).toContainText("fetched later", { timeout: 60_000 }); + } + // The edge drags on into what arrived: 220 s past the saved end, and nothing saved. + await endToCacheEdge(page); + await expect.poll(async () => (await selOf(page))[1]).toBeGreaterThan(306 + 120); + expect(reachClip().end).toBe(306); + // Two presses, two fetches -- the drags downloaded nothing -- each keeping the before side as cached. + expect(posts.map((p) => [p.padBefore, p.padAfter])).toEqual([ + [3, 160], + [3, 220], + ]); +}); + +test("a window wider than the editor's 900 s is refused with the next step, not clamped", async ({ request }) => { + const r = await request.post("/api/report/fetch", { data: { project: REACH, clip: "r01", padBefore: 3, padAfter: 950 } }); + expect(r.status()).toBe(400); + const j = (await r.json()) as { error: string; maxWindow: number }; + expect(j.maxWindow).toBe(900); + expect(j.error).toContain("at most 900 s end to end"); + expect(j.error).toContain("whole source"); +}); + +// --------------------------------------------------------------------------- +// Coming back to the bench (lane/clip-fixes; operator, 6 Nov: "I just had to +// refresh. Maybe address that so it updates if you click the back button"). +// The back button restores the page as it was shown -- Next's router cache, or +// the browser's page cache (pageshow, persisted) -- so a window fetched +// meanwhile did not show. The bench reads its state again on mount, on +// pageshow (persisted) and when the tab comes back; it never fetches to do so. +// --------------------------------------------------------------------------- + +test("back to the bench shows the window fetched meanwhile, and so does a page restored from the page cache -- without a fetch", async ({ page, request }) => { + test.setTimeout(240_000); + const visTo = async () => Number(((await page.locator("[data-wave-box]").getAttribute("data-wave-vis")) ?? "").split("-")[1]); + const widen = async (padAfter: number) => { + const r = await request.post("/api/report/fetch", { data: { project: REACH, clip: "r01", padBefore: 3, padAfter } }); + expect(r.status(), await r.text()).toBe(202); + await waitJob(request, ((await r.json()) as { job: { id: string } }).job.id); + return (await reachWindows(request))[0].to; + }; + const before = (await reachWindows(request))[0]?.to ?? (await widen(30)); + const fetches: string[] = []; + page.on("request", (r) => { + if (r.method() === "POST" && r.url().endsWith("/api/report/fetch")) fetches.push(r.url()); + }); + await page.goto(urls.clipBenchHref(REACH, "r01")); + await expect.poll(visTo).toBeCloseTo(before, 1); + + // Away through the app's own link (a client navigation), a wider window + // fetched meanwhile (another tab, a CLI), and back. + await page.locator("[data-bench-back]").click(); + await expect(page.locator("[data-bench=r01]")).toHaveCount(0); + const wider = await widen(Math.round(before - 306) + 30); + expect(wider).toBeGreaterThan(before + 1); + await page.goBack(); + await expect(page.locator("[data-bench=r01]")).toBeVisible(); + await expect.poll(visTo, { timeout: 15_000 }).toBeCloseTo(wider, 1); + + // A page the browser restored from its page cache says so with pageshow (persisted). + const widest = await widen(Math.round(wider - 306) + 30); + await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))); + await expect.poll(visTo, { timeout: 15_000 }).toBeCloseTo(widest, 1); + // The bench fetched nothing to show any of it. + expect(fetches).toEqual([]); +}); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -821,6 +821,14 @@ CUES.tightvid = CUES.vid1.map((r) => [...r]); // The clip-export spec's Export ▾ source (clip-export.spec.ts): a recording nothing else fetches, so // its full-exchange fetch (through the editor stub) moves no other spec's cache. CUES.exportvid = CUES.vid1.map((r) => [...r]); +// The clip bench's long reach (clip-bench.spec.ts, "fetch more goes on from the edge"): a +// recording a thousand seconds long, so a window can be fetched far past any clip on it -- +// a fetch more is measured from where the edge is NOW, and a window may be 900 s end to end. +CUES.reachvid = [ + [0, 3, "The start of a long recording."], + [300, 306, "The clip sits here, five minutes in."], + [996, 1000, "And the recording ends here."], +]; for (const [vid, rows] of Object.entries(CUES)) { const dir = path.join(CHANNELS, "testchan", "data", vid); mkdirSync(dir, { recursive: true }); @@ -1950,6 +1958,14 @@ makeMediaScenesFixture({ reports, deckManifest }); 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")); } +// Fetch more from where the edge is now (clip-bench.spec.ts): one clip, r01 reachvid 300-306, on a +// recording a thousand seconds long; nothing cached -- the spec fetches through the editor stub. +writeProject( + "reach-fixture", + manifest("reach-fixture", "The Reach Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "r01", video: "reachvid", start: 300, end: 306, cite: 300, section: 0, quote: "the clip sits here" }, + ]), +); // Tighten to the sentence, snap an edge to its pause, and the batch's proposals (tighten.spec.ts), // which WRITES (the spec puts the manifest back before each test): its own project on tightvid // (vid1's cues; sentences 0-3, 3-9, 9-12), the tone window cached as tightvid_0.00-9.00.mp4, and diff --git a/umtool/e2e/gaps-zoom.spec.ts b/umtool/e2e/gaps-zoom.spec.ts @@ -317,3 +317,167 @@ test("Play the cut on a take plays a gapped clip's kept pieces only", async ({ p expect(got.clips.find((c: { id: string }) => c.id === "g01")).toMatchObject({ cutStart: 0.5, cutEnd: 8.5, gaps: [{ from: 3.5, to: 5.5 }], footage: 6 }); await playsJumpCut(page, "gapped"); }); + +// --------------------------------------------------------------------------- +// A cut narrower than the clip (lane/clip-fixes; operator, 6 Nov: "I can't add +// gaps beyond like 9:21"): an extent widened over a cut kept from an earlier +// pass. Gaps lie inside the cut, so every gap stopped at the cut's end with +// nothing on the waveform to say why. Now the cut is drawn there, said above +// it, its edges drag, and Use the whole clip clears it -- each with an Undo. +// --------------------------------------------------------------------------- + +const cutOf = () => { + const e = (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string; cutStart?: number; cutEnd?: number }[] }).timeline.find((x) => x.id === "g01")!; + return { cutStart: e.cutStart ?? null, cutEnd: e.cutEnd ?? null }; +}; +const SHOTS = process.env.E2E_CLIP_FIXES_SHOTS ?? null; +const shot = async (page: Page, name: string) => { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + await page.locator("[data-wave-box]").screenshot({ path: path.join(SHOTS, `${name}.png`) }); +}; + +test("a cut narrower than the clip: drawn on the waveform, said, a gap stops at it with the reason, its edge drags, Use the whole clip", async ({ page, request }) => { + expect((await putWindow(request, { cutStart: 1, cutEnd: 4 })).ok()).toBeTruthy(); + try { + await openBench(page); + await expect(page.locator("[data-cut-limits]")).toContainText("The video plays only the cut"); + await expect(page.locator("[data-cut-limits]")).toContainText("gaps go inside it"); + await expect(page.locator("[data-wave-cut-edge]")).toHaveCount(2); + await expect(page.locator("[data-wave-outside-cut]")).toHaveCount(2); + await shot(page, "cut-narrower"); + + // Alt + drag from inside the cut out past its end: the span stops at the cut's + // end, and -- BEFORE release -- turns red and says why, the clamp included. + await page.keyboard.down("Alt"); + const y = await midY(page); + await page.mouse.move(await xAt(page, 2.5), y); + await page.mouse.down(); + await page.mouse.move(await xAt(page, 6), y, { steps: 4 }); + const live = page.locator("[data-gap-selection-why]"); + await expect(live).toContainText("stopped at the cut's end"); + await expect(live).toContainText("keep at least 0.5 s"); + await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "refused"); + expect(spanOf(await page.locator("[data-gap-selection]").getAttribute("data-gap-selection"))[1]).toBeCloseTo(4, 2); + await shot(page, "gap-at-cut-wall"); + await page.mouse.up(); + await page.keyboard.up("Alt"); + await expect(page.locator("[data-bench-note]")).toContainText("stopped at the cut's end"); + await page.locator("body").press("Escape"); + + // The cut's end tab drags the edge out; written on release, with an Undo. + const grip = page.locator("[data-wave-cut-grip=end]"); + const gb = (await grip.boundingBox())!; + await page.mouse.move(gb.x + gb.width / 2, gb.y + gb.height / 2); + await page.mouse.down(); + await page.mouse.move(await xAt(page, 7), gb.y + gb.height / 2, { steps: 5 }); + await page.mouse.up(); + await expect.poll(() => cutOf().cutEnd ?? 0).toBeGreaterThan(6.5); + expect(cutOf().cutStart).toBe(1); + await expect(page.locator("[data-bench-note]")).toContainText("the cut moved to"); + await page.locator("[data-cut-undo]").click(); + await expect.poll(() => cutOf().cutEnd).toBe(4); + + // Use the whole clip: the cut cleared, the wall gone; Undo puts it back. + await page.locator("[data-cut-use-whole]").click(); + await expect.poll(() => cutOf().cutStart).toBeNull(); + await expect(page.locator("[data-cut-limits]")).toHaveCount(0); + await expect(page.locator("[data-wave-cut-edge]")).toHaveCount(0); + await page.locator("[data-cut-undo]").click(); + await expect.poll(() => cutOf()).toEqual({ cutStart: 1, cutEnd: 4 }); + await expect(page.locator("[data-wave-cut-edge]")).toHaveCount(2); + } finally { + expect((await putWindow(request, { cutStart: "", cutEnd: "", lockCut: false })).ok()).toBeTruthy(); + } +}); + +// --------------------------------------------------------------------------- +// Every wall a gap stops at is drawn and said (lane/clip-fixes; operator, 6 +// Nov: "the gap tool gets blocked at random invisible walls in the clip"): the +// no-cut zones (outside the span, the keep bands at its edges and beside each +// gap), a tick at each second a gap can't cover, and the writer's whole rule +// checked on every move -- the claim marks included, which the bench used to +// leave to the writer, which then refused with a sentence the bench had not +// said. +// --------------------------------------------------------------------------- + +/** Put a claim mark's second on g01 (`claim: {id, verdict, at}`), straight into the manifest; null takes it off. */ +const setStamp = (at: number | null) => { + const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Record<string, unknown>[] }; + const e = m.timeline.find((x) => x.id === "g01")!; + if (at == null) delete e.claim; + else e.claim = { id: "k9", verdict: "CORROBORATED", at }; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); +}; +/** An Alt + drag from a to b, held (not released): what the span says WHILE it is dragged. */ +const altDragHeld = async (page: Page, a: number, b: number) => { + await page.keyboard.down("Alt"); + 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, b), y, { steps: 4 }); +}; +const altRelease = async (page: Page) => { + await page.mouse.up(); + await page.keyboard.up("Alt"); +}; + +test("the walls are drawn: no-cut zones and the marks a gap can't cover; a drag into one turns red with the reason before release; a gap over a claim mark is refused with the writer's sentence", async ({ page, request }) => { + expect((await putWindow(request, { gapAdd: "3.5-5.5" })).ok()).toBeTruthy(); + setStamp(7); + try { + await openBench(page); + // The zones: outside the clip (the view runs 0-9, the clip 0.5-8.5), 0.5 s + // at each of its edges, and 0.5 s either side of the gap. + const kinds = await page.locator("[data-gap-nocut]").evaluateAll((els) => els.map((e) => `${e.getAttribute("data-gap-nocut")} ${e.getAttribute("data-gap-nocut-at")}`)); + expect(kinds).toEqual( + expect.arrayContaining(["outside 0.00-0.50", "outside 8.50-9.00", "keep-start 0.50-1.00", "keep-end 8.00-8.50", "keep-gap 3.00-3.50", "keep-gap 5.50-6.00"]), + ); + await expect(page.locator("[data-gap-nocut='keep-gap']").first()).toHaveAttribute("title", /keep at least 0.5 s between cuts/); + await expect(page.locator("[data-gap-span-edge]")).toHaveCount(2); + // The mark's second, ticked, with what it means on hover. + const tick = page.locator("[data-gap-wall-mark='7']"); + await expect(tick).toHaveAttribute("data-gap-wall-mark-kind", "mark"); + await expect(tick.locator("span")).toHaveAttribute("title", /a gap can't cover this/); + await shot(page, "walls"); + + // Into the keep band beside the gap: red, and why, while still dragging. + await altDragHeld(page, 5.7, 6.6); + await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "refused"); + await expect(page.locator("[data-gap-selection-why]")).toContainText("keep at least 0.5 s"); + await shot(page, "gap-into-keep-band"); + await altRelease(page); + await page.locator("body").press("Escape"); + + // Over the mark's second: refused here, with the writer's own sentence. + await altDragHeld(page, 6.6, 7.6); + await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "refused"); + await expect(page.locator("[data-gap-selection-why]")).toContainText("the mark k9's second (at 7) lies inside the gap"); + await shot(page, "gap-over-mark"); + await altRelease(page); + const [a, b] = spanOf(await page.locator("[data-gap-selection]").getAttribute("data-gap-selection")); + const posts: string[] = []; + page.on("request", (r) => { + if (r.method() === "PUT" && r.url().endsWith("/api/report/window")) posts.push(r.url()); + }); + await page.locator("[data-gap-cut]").click(); + // The writer, asked the same span, says the same thing (less the clip id it starts with). + const r = await putWindow(request, { gapAdd: `${a}-${b}` }); + expect(r.status()).toBe(400); + const said = ((await r.json()) as { error: string }).error.replace(/^g01: /, ""); + expect(said).toContain("the mark k9's second (at 7) lies inside the gap"); + await expect(page.locator("[data-bench-note]")).toContainText(`not cut: ${said}`); + // Refused before anything was sent. + expect(posts).toEqual([]); + expect(clipOf("g01").gaps).toEqual([{ from: 3.5, to: 5.5 }]); + + // Touching the gap: no wall -- it says the two become one. + await page.locator("body").press("Escape"); + await altDragHeld(page, 5.2, 6.4); + await expect(page.locator("[data-gap-selection]")).toHaveAttribute("data-gap-selection-state", "merge"); + await expect(page.locator("[data-gap-selection-why]")).toContainText("touches a gap — cutting makes one gap 3.50–"); + await altRelease(page); + } finally { + setStamp(null); + } +}); diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -11,7 +11,8 @@ import { } from "@/lib/projects/report.mjs"; import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs"; import { projectCache, segmentFor, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; -import { FETCH_MAX_PAD } from "@/lib/report/driver.mjs"; +import { FETCH_MAX_WINDOW } from "@/lib/report/driver.mjs"; +import { gapWalls } from "umtool-report-to-video/gaps"; import { deckOn } from "umtool-report-to-video/deck"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; @@ -132,6 +133,9 @@ export async function clipBenchData( gaps: ((manifest.timeline ?? []) as { id: string; gaps?: { from: number; to: number }[] }[]).find((e) => e.id === clipId) ?.gaps ?? [], + // The seconds no gap may cover (claim marks, a stamp), from the manifest's own entry. + marks: gapWalls({ ...(((manifest.timeline ?? []) as { id: string }[]).find((e) => e.id === clipId) ?? {}), type: "clip", muteFrom: null }) + .marks.map((m) => ({ id: m.id, at: m.at })), verdict: entry.verdict === "confirmed" || entry.verdict === "incorrect" || entry.verdict === "rejected" ? entry.verdict : null, // What the walk said that is not a verdict, and a deliberate repeat. @@ -201,7 +205,7 @@ export async function clipBenchData( // The widest the fetch route will go. The BUTTON has to know it: it names // the pad it will ask for, and "that is as wide as it goes" is a different // sentence from a number the server quietly clamps. - maxPad: FETCH_MAX_PAD, + maxWindow: FETCH_MAX_WINDOW, // The widest cached RAW window: it has no chrome burned in, which is what a // mix is looking at, and it exists as soon as the clip has been fetched // once. start/end are the window minus the file's own start, because a mix diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -285,13 +285,20 @@ export function narrateCardSteps(project, cardId) { } /** - * The widest pad the bench may ask for. + * The widest WINDOW the bench may ask for, in seconds, end to end: the + * editor's own cap on one fetched window (common/lib/clipWindow.ts + * MAX_CLIP_WINDOW_SECONDS; POST /api/media/fetch-window refuses wider). Past it + * the answer is the whole recording. * - * Here rather than in the route, because the BENCH has to know it too: the - * button reads "fetch to ±N s" and has to say "that is as wide as it goes" - * rather than offering a number the server will quietly clamp. + * It replaced a cap of 120 s PER SIDE measured from the clip's SAVED edges + * (lane/clip-fixes, operator 6 Nov: "I try to drag a clip and it just doesn't + * expand beyond a certain point"): an edge dragged out to the cached edge could + * never be given more than 120 s past where it was last saved, and the bench + * went quiet there. Here rather than in the route, because the BENCH has to + * know it too: the button says how far it will ask, and says when this is the + * limit, rather than offering a number the server would refuse. */ -export const FETCH_MAX_PAD = 120; +export const FETCH_MAX_WINDOW = 900; /** * Fetch ONE clip's window, wide. What the bench's "fetch more" runs. diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -6,7 +6,9 @@ // // SOURCE seconds, like `start`/`end`/`cutStart`/`cutEnd`. Each gap lies inside // the clip's CUT (its `cutStart`–`cutEnd`, else its extent), at least -// GAP_LIMITS.min long, at most GAP_LIMITS.max of them, sorted, apart, and with +// GAP_LIMITS.min long, at most GAP_LIMITS.max of them (40: a long clip cut down +// to its sentences; nothing downstream counts them -- gapFilterParts splits into +// as many pieces as there are), sorted, apart, and with // at least GAP_LIMITS.keep seconds of material before the first, between any // two and after the last: a sliver of picture between two jumps reads as a // glitch, not a cut. A `muteFrom` or a claim mark's `at` strictly INSIDE a gap @@ -29,7 +31,7 @@ // `validateGaps`. /** The rules a clip's gaps keep: seconds (min, keep) and a count (max). */ -export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 12, keep: 0.5 }); +export const GAP_LIMITS = Object.freeze({ min: 0.2, max: 40, keep: 0.5 }); /** Each join's fade, in seconds: out over the end of the piece before, in over the start of the piece after -- short enough to keep a word, long enough not to click. */ export const GAP_FADE = 0.025; @@ -173,6 +175,58 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}` } /** + * WHERE A GAP CANNOT GO in a clip, and why -- validateGaps's rules as spans + * and seconds a waveform can draw (lane/clip-fixes; operator, 6 Nov: "the gap + * tool gets blocked at random invisible walls"). Every wall a gap dragged on + * the bench stops at is one of these: + * + * span where gaps lie at all (gapSpan: the cut, else the extent); `whose` + * says which, in the words validateGaps uses + * zones inside the span, the seconds no gap may reach into: GAP_LIMITS.keep + * after the span's start and before its end, and beside each gap + * (a span reaching INTO a gap is not refused -- it grows it, + * editGaps -- but one stopping short in its keep band is) + * marks the seconds no gap may COVER (strictly inside): the mute mark, each + * claim mark's or stamp's `at` + * + * A gap avoiding every zone's interior and covering no mark, at least + * GAP_LIMITS.min long, apart from the rest and under GAP_LIMITS.max of them, is + * one validateGaps accepts (gaps.test.mjs holds the two to each other). + * + * @param {Record<string, any>} entry + * @returns {{ span: { from: number, to: number }, whose: "cut" | "clip", + * zones: Array<{ from: number, to: number, kind: "keep-start" | "keep-end" | "keep-gap", why: string }>, + * marks: Array<{ at: number, kind: "mute" | "mark" | "stamp", id: string | null, why: string }> }} + */ +export function gapWalls(entry) { + const span = gapSpan(entry); + const whose = fin(entry?.cutStart) && fin(entry?.cutEnd) ? "cut" : "clip"; + const keep = GAP_LIMITS.keep; + const zones = []; + if (fin(span.from) && fin(span.to)) { + zones.push({ from: span.from, to: Math.min(span.to, span.from + keep), kind: "keep-start", why: `keep at least ${keep} s after the ${whose}'s start` }); + zones.push({ from: Math.max(span.from, span.to - keep), to: span.to, kind: "keep-end", why: `keep at least ${keep} s before the ${whose}'s end` }); + } + for (const g of gapsOf(entry)) { + const why = `keep at least ${keep} s between cuts — or drag into the gap ${g.from}–${g.to} to grow it`; + zones.push({ from: g.from - keep, to: g.from, kind: "keep-gap", why }); + zones.push({ from: g.to, to: g.to + keep, kind: "keep-gap", why }); + } + const marks = []; + if (fin(entry?.muteFrom)) marks.push({ at: entry.muteFrom, kind: "mute", id: null, why: `the mute mark (${entry.muteFrom}): a gap can't cover it — the cut never plays a second inside a gap` }); + for (const m of marksAt(entry)) { + const id = typeof m.id === "string" && m.id ? m.id : null; + marks.push({ + at: m.at, + kind: id ? "mark" : "stamp", + id, + why: `${id ? `the mark ${id}'s second` : "the stamp's second"} (${m.at}): a gap can't cover it — move it first, or cut around it`, + }); + } + return { span, whose, zones, marks }; +} + +/** * A clip beat's GAPS (lane/reel-bench): source seconds cut out of its middle, * so two moments of one clip play as one beat of jump cuts -- the same shape * and the same rule as a clip's gaps (gaps.mjs): each `{ from, to }` at least diff --git a/umtool/report-to-video/gaps.test.mjs b/umtool/report-to-video/gaps.test.mjs @@ -13,7 +13,7 @@ import path from "node:path"; import test from "node:test"; import { - GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin, + GAP_FADE, GAP_LIMITS, editGaps, gapFilterParts, gapWalls, gapSeconds, gappedLength, gapsOf, gapsOnSegment, gapsText, gapsWithin, inGap, keptSpans, normalizeGaps, offsetIn, parseGapSpec, recordGaps, renderGaps, sourceAtOffset, validateGapEntries, validateGaps, } from "./gaps.mjs"; @@ -44,8 +44,10 @@ test("validateGaps: each refusal names what is wrong", () => { assert.match(one([{ from: 102.3, to: 103 }])[0], /after the cut's start/); assert.match(one([{ from: 117, to: 117.8 }])[0], /before the cut's end/); assert.match(one([{ from: 117, to: 119 }])[0], /outside the clip's cut/); - const many = Array.from({ length: 13 }, (_, k) => ({ from: 100 + k * 1.5, to: 100.3 + k * 1.5 })); - assert.match(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 130, gaps: many })[0], /at most 12 gaps/); + // At most 40 (a long clip cut down to its sentences); 40 is fine, 41 is not. + const many = (n) => Array.from({ length: n }, (_, k) => ({ from: 100 + k * 1.5, to: 100.3 + k * 1.5 })); + assert.deepEqual(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 170, gaps: many(40) }), []); + assert.match(validateGaps({ ...CLIP, start: 0, end: 200, cutStart: 99, cutEnd: 170, gaps: many(41) })[0], /at most 40 gaps/); assert.match(validateGaps({ type: "card", id: "k", gaps: G })[0], /only a clip/); }); @@ -219,3 +221,49 @@ test("fetchPieces: one padded span per kept piece; pieces under a minute apart a [{ from: 0, to: 103 }, { from: 397, to: 413 }, { from: 897, to: 1003 }], ); }); + + +// ---- the walls, drawn (lane/clip-fixes) ------------------------------------- + +test("gapWalls: the span, the keep bands at its edges and beside each gap, and the marks no gap may cover", () => { + const w = gapWalls({ ...CLIP, gaps: G, muteFrom: 116, claims: [{ id: "a", verdict: "FALSE", at: 104 }, { verdict: "FALSE", at: 112 }] }); + assert.deepEqual(w.span, { from: 102, to: 118 }); + assert.equal(w.whose, "cut"); + assert.deepEqual( + w.zones.map((z) => [z.kind, z.from, z.to]), + [["keep-start", 102, 102.5], ["keep-end", 117.5, 118], ["keep-gap", 104.5, 105], ["keep-gap", 107, 107.5], ["keep-gap", 109.5, 110], ["keep-gap", 110.5, 111]], + ); + assert.match(w.zones[0].why, /after the cut's start/); + assert.match(w.zones[2].why, /drag into the gap 105–107 to grow it/); + assert.deepEqual(w.marks.map((m) => [m.kind, m.at, m.id]), [["mute", 116, null], ["mark", 104, "a"], ["stamp", 112, null]]); + assert.match(w.marks[0].why, /can't cover it/); + // No cut: the extent, said as the clip's. + const x = gapWalls({ type: "clip", id: "x", start: 10, end: 20 }); + assert.deepEqual(x.span, { from: 10, to: 20 }); + assert.equal(x.whose, "clip"); + assert.deepEqual(x.marks, []); +}); + +test("gapWalls and validateGaps agree: a new gap clear of every zone and mark is accepted, one reaching into either is refused", () => { + const entry = { ...CLIP, gaps: G, muteFrom: 116, claims: [{ id: "a", verdict: "FALSE", at: 104 }, { verdict: "FALSE", at: 112.6 }] }; + const w = gapWalls(entry); + // A seeded walk: deterministic, many spans, every edge on the writer's 2 dp grid. + let seed = 7; + const rand = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + let checked = 0; + for (let i = 0; i < 4000; i += 1) { + const a = Number((w.span.from + rand() * (w.span.to - w.span.from)).toFixed(2)); + const b = Number((a + 0.2 + rand() * 3).toFixed(2)); + if (b > w.span.to) continue; + // Touching or overlapping a gap is a merge (editGaps), not a wall: not this test's question. + if (G.some((g) => g.to >= a && g.from <= b)) continue; + const hitsZone = w.zones.some((z) => a < z.to - 0.02 && b > z.from + 0.02); + const nearZone = w.zones.some((z) => (Math.abs(a - z.to) <= 0.02 || Math.abs(b - z.from) <= 0.02)); + if (nearZone) continue; // within the writer's 0.02 tolerance of a band's edge + const coversMark = w.marks.some((m) => m.at > a && m.at < b); + const errs = validateGaps({ ...entry, gaps: normalizeGaps([...G, { from: a, to: b }]) }); + assert.equal(errs.length === 0, !hitsZone && !coversMark, `${a}–${b}: ${errs.join("; ") || "accepted"}`); + checked += 1; + } + assert.ok(checked > 500, `checked ${checked}`); +});