commit 74b1806b9fb5c83e2b6e41895d9b9f2d05282099
parent 7fa0c551f949ceed803661bf77ea02b4808b3e6f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 16:49:07 -0500
umtool bench: the walk's editing primitives as shared parts -- a media adapter, the playback engine, the gap editor, the waveform box and its gap tools
ClipBench's playback engine (decoded audio on the audio clock, the element
fallback, time-stretch, the mute ramp, the gap joins), its gap editor and its
waveform box (Alt + drag, GapLayer, the bench's overlays) and the gaps' tool
row move out into components/projects/bench/: useBenchPlayer.ts, usePeaks.ts,
useGapEditor.ts, BenchWave.tsx. They speak SOURCE seconds and take a media
adapter (benchMedia.ts): the clip's cached raw window (sourceWindowMedia, the
bench as it was) or a rendered file of the project with its map onto the
clip's source (renderedFileMedia; lib/report/fileMedia.mjs) -- what the
reel's walk will play. The gap editor takes its writer, so a clip's window
writer and a reel's beat writer both drive it.
ClipBench keeps every behaviour, attribute and label; it is 830 lines shorter.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 1209 insertions(+), 903 deletions(-)
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -10,7 +10,6 @@ import { LatestLine, type WorkingCut } from "./review/WhatPlays";
import { createPortal } from "react-dom";
import Link from "next/link";
import { useRouter } from "next/navigation";
-import Waveform, { type Peaks } from "@/components/Waveform";
import { badgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { StoredUrlCheckbox, useStoredUrlOffered } from "@/components/clips/StoredUrlOption";
@@ -24,27 +23,21 @@ import CopyCitation from "./bench/CopyCitation";
import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport";
import EdgeStrip from "./bench/EdgeStrip";
import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts";
-import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom";
+import { ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom";
import TakeWalkStrip from "./bench/TakeWalkStrip";
import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenTools";
// 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
// would only find out twenty minutes into a build.
import { attributionLine } from "umtool-report-to-video/attribution";
-import {
- MUTE_FADE,
- START_LEAD,
- bufferSchedule,
- covers,
- decodeSpan,
- elementShouldStop,
- muteRamp,
- 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 { gapSpan, gappedLength, validateGaps } from "umtool-report-to-video/gaps";
+import { useGapEditor } from "./bench/useGapEditor";
+import { BenchWaveBox, GapTools } from "./bench/BenchWave";
+import { sourceWindowMedia } from "./bench/benchMedia";
+import { useBenchPlayer } from "./bench/useBenchPlayer";
+import { usePeaks } from "./bench/usePeaks";
import {
DeckFrame,
NeutralFrame,
@@ -474,63 +467,6 @@ type WindowPatch = {
muteFrom?: number | string;
};
-/**
- * A decoded span of the cached window, placed on the source clock. `name` is
- * the window's name and the version of its bytes (`<name>|<v>`).
- */
-type Decoded = { name: string; span: { from: number; to: number }; buf: AudioBuffer };
-
-/**
- * What is playing, and what the last playback measured.
- *
- * On the page as data attributes (`data-play-*`), because "did it stop where
- * the selection ends" is the claim this bench now makes, and a spec has to be
- * able to check it against the audio clock rather than against a feeling.
- */
-type PlayInfo = {
- engine: "webaudio" | "element";
- state: "playing" | "stopped";
- from: number;
- /** The scheduled end, in source seconds. */
- to: number;
- rate: number;
- /**
- * Web Audio at a speed but 1x: the range was time-stretched and played at
- * 1x, so it keeps its pitch as the element does (`preservesPitch`). False at
- * 1x, and for the element, which keeps the pitch by itself.
- */
- stretched: boolean;
- /** Context clock: when the source starts and when it is told to stop. */
- ctxStart: number | null;
- ctxStop: number | null;
- /**
- * Where the playback had reached, in source seconds, when the page heard it
- * end: the element's own position at its pause, or the context clock at
- * `ended` -- which reaches the page a task later than the sound stopped, so
- * for Web Audio it is an upper bound and `ctxStop` is the stop itself.
- */
- endedAt: number | null;
-};
-
-/** The playback in flight. One at a time: a new one stops the last. */
-type Session = {
- gen: number;
- engine: "webaudio" | "element";
- node: AudioBufferSourceNode | null;
- gain: GainNode | null;
- raf: number;
- timers: number[];
- from: number;
- to: number;
- rate: number;
- t0: number;
- 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,
navigate,
@@ -571,7 +507,6 @@ export default function ClipBench({
// Armed: the next click on the waveform places the mark instead of moving
// an edge.
const [mutePick, setMutePick] = useState(false);
- const [peaks, setPeaks] = useState<Peaks | null>(null);
// The cues AROUND the cached window: what is coming, read before paying for
// the media. One request, widened only when somebody asks.
const [peek, setPeek] = useState<Cue[]>([]);
@@ -579,11 +514,6 @@ export default function ClipBench({
// manifest: it is a fact about a matching run, not about the cut.
const [cutScore, setCutScore] = useState<number | null>(null);
const [peekPad, setPeekPad] = useState(PEEK_STEP);
- const [playhead, setPlayhead] = useState<number | null>(null);
- const playheadRef = useRef<number | null>(null);
- useEffect(() => {
- playheadRef.current = playhead;
- }, [playhead]);
const [note, setNote] = useState<string | null>(null);
// A window save refused because a stamp's second (or the mute mark) would fall outside the new
// window (manifest.mjs MarksOutside): the refused patch, kept to retry with the fix the
@@ -736,27 +666,36 @@ export default function ClipBench({
// The widest cached file is the one the bench draws from: it is how much room
// there is to drag before anything has to be fetched.
const cached = windows[0] ?? null;
- // The version of its bytes in every media URL: a refetch under the same name is a new URL.
- const vq = cached?.v ? `&v=${encodeURIComponent(cached.v)}` : "";
const fetchStart = cached?.from ?? 0;
const cachedTo = cached?.to ?? 0;
- // ---- peaks --------------------------------------------------------------
+ // What plays (bench/benchMedia.ts): the widest cached window, on the source clock.
+ const media = useMemo(
+ () => sourceWindowMedia({ project: data.project, clip: clip.id, take: takeId, win: cached }),
+ // The window by its name and the version of its bytes: a refresh returning the same one is the same media.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [data.project, clip.id, takeId, cached?.name, cached?.v, cached?.from, cached?.to],
+ );
+ // 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 ?? [];
+ // The playback engine (bench/useBenchPlayer.ts): every bounded range from decoded audio, the picture following.
+ const { play, stopPlayback, playhead, playInfo, audio, retargetMute } = useBenchPlayer({
+ media,
+ video,
+ rate: playback.rate,
+ gapsRef,
+ muteRef,
+ warm: { from: clip.start, to: clip.end },
+ });
+ const playheadRef = useRef<number | null>(null);
useEffect(() => {
- if (!cached) return;
- let live = true;
- void (async () => {
- const r = await fetch(
- `/api/report/peaks?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}${vq}`,
- { cache: "no-store" },
- );
- if (!r.ok || !live) return;
- setPeaks((await r.json()) as Peaks);
- })();
- return () => {
- live = false;
- };
- }, [cached, data.project, clip.id, tq]);
+ playheadRef.current = playhead;
+ }, [playhead]);
+ const peaks = usePeaks(media);
// Follow the playhead in the reading pane, and ONLY while something is
// playing: scrolling the words out from under somebody who is reading ahead
@@ -904,524 +843,6 @@ export default function ClipBench({
return () => el.removeEventListener("loadedmetadata", again);
}, [playback, segment, cached, renderedOpen, deckPreview]);
- // ---- audition -----------------------------------------------------------
- //
- // EVERY BOUNDED RANGE PLAYS FROM DECODED AUDIO. A selection, an edge, a line
- // of the transcript, the auto-audition: each is an AudioBufferSourceNode
- // started at an exact offset and stopped at an exact time on the audio
- // clock, so what you hear ends where the selection ends, to the sample. The
- // <video> used to play these itself and was stopped from `timeupdate`, which
- // fires every 15-250 ms -- the stop overran by up to a quarter of a second,
- // and by a different amount every time, which is exactly what makes a cut
- // between two words impossible to judge by ear. (The old HTML chooser had
- // this right; it is the same technique.)
- //
- // The picture FOLLOWS, muted, and the playhead is read off the audio clock.
- // When the decode fails the element plays instead, stopped per animation
- // frame by remaining time, and the bench says so.
-
- /** The decoded audio for the cached window: one decode per window. */
- const decoded = useRef<Decoded | null>(null);
- const decoding = useRef<{ key: string; p: Promise<Decoded> } | null>(null);
- // The last few time-stretched ranges: a replay at the same speed, and the
- // clip's selection stretched ahead of the first play, cost nothing.
- const stretchedRanges = useRef<{ key: string; buf: AudioBuffer }[]>([]);
- const actx = useRef<AudioContext | null>(null);
- const session = useRef<Session | null>(null);
- const playGen = useRef(0);
- // Pauses the bench asked for itself and has not yet heard the event of. A
- // `pause` event is a task, so it arrives AFTER the next playback has started:
- // without the count, stopping one playback to start the next would read as
- // somebody pausing the picture, and stop the new one.
- const selfPauses = useRef(0);
- const pauseVideo = useCallback((el: HTMLVideoElement) => {
- if (el.paused) return;
- selfPauses.current += 1;
- el.pause();
- }, []);
- // 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",
- });
- const [playInfo, setPlayInfo] = useState<PlayInfo | null>(null);
-
- /**
- * The cached window's sound over (at least) `want`, decoded once.
- *
- * Through /api/report/audio -- ffmpeg's decode of the same file the player
- * loads, as PCM -- and decoded here on an OfflineAudioContext, so no audio
- * output is opened before somebody asks to hear something. A buffer belongs
- * to no context and plays in the real one.
- */
- const ensureDecoded = useCallback(
- async (want: { from: number; to: number }): Promise<Decoded> => {
- if (!cached) throw new Error("nothing is cached for this clip");
- const have = decoded.current;
- if (have && have.name === `${cached.name}|${cached.v ?? ""}` && covers(have.span, want.from, want.to)) return have;
- const span = decodeSpan({ from: cached.from, to: cached.to }, want);
- const key = `${cached.name}|${cached.v ?? ""}|${span.from}|${span.to}`;
- if (decoding.current?.key === key) return decoding.current.p;
- const p = (async () => {
- setAudio({ state: "loading" });
- const r = await fetch(
- `/api/report/audio?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` +
- `&file=${encodeURIComponent(cached.name)}&from=${span.from}&to=${span.to}${tq}${vq}`,
- );
- if (!r.ok) {
- const j = (await r.json().catch(() => null)) as { error?: string } | null;
- throw new Error(j?.error ?? `the audio route answered ${r.status}`);
- }
- const from = Number(r.headers.get("x-audio-from") ?? span.from);
- const bytes = await r.arrayBuffer();
- const Offline =
- typeof window !== "undefined" ? (window.OfflineAudioContext ?? null) : null;
- if (!Offline) throw new Error("this browser has no Web Audio");
- const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes);
- const d: Decoded = { name: `${cached.name}|${cached.v ?? ""}`, span: { from, to: from + buf.duration }, buf };
- decoded.current = d;
- setAudio({ state: "ready" });
- return d;
- })();
- decoding.current = { key, p };
- p.catch((e: unknown) => {
- if (decoding.current?.p === p) decoding.current = null;
- setAudio({ state: "failed", why: e instanceof Error ? e.message : String(e) });
- });
- return p;
- },
- [cached, data.project, clip.id],
- );
-
- // A different window -- a wider one after "fetch more", or the first after a
- // fetch -- is different audio: drop the old decode and start the new one
- // now, so the first play after it does not wait.
- // (Its name and the version of its bytes: a refetch under the same name is different audio too.)
- const cachedName = cached ? `${cached.name}|${cached.v ?? ""}` : null;
- useEffect(() => {
- decoded.current = null;
- decoding.current = null;
- setAudio({ state: "idle" });
- if (!cachedName) return;
- ensureDecoded({ from: clip.start, to: clip.end }).catch(() => {
- /* said in the bench; play() falls back to the element */
- });
- // ensureDecoded changes identity with `cached`, which is this effect's
- // whole subject; keying on the NAME is what stops a refresh() that returns
- // the same window from decoding it again.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [cachedName]);
-
- /**
- * The range [offset, offset + duration) of a decoded buffer, time-stretched
- * to `rate` at its own pitch (timeStretch.mjs): played at 1x it lasts
- * duration / rate -- the wall length bufferSchedule computed -- and starts
- * and ends on the range's own samples.
- */
- const stretchFor = useCallback((d: Decoded, offset: number, duration: number, rate: number): AudioBuffer => {
- const key = `${d.name}|${d.span.from}|${offset.toFixed(5)}|${duration.toFixed(5)}|${rate}`;
- const hit = stretchedRanges.current.find((r) => r.key === key);
- if (hit) return hit.buf;
- const sr = d.buf.sampleRate;
- const a = Math.max(0, Math.min(d.buf.length, Math.round(offset * sr)));
- const b = Math.max(a, Math.min(d.buf.length, a + Math.round(duration * sr)));
- const channels: Float32Array[] = [];
- for (let c = 0; c < d.buf.numberOfChannels; c++) channels.push(d.buf.getChannelData(c).subarray(a, b));
- const out = timeStretch(channels, sr, rate);
- const buf = new AudioBuffer({
- length: Math.max(1, out[0]?.length ?? 0),
- numberOfChannels: Math.max(1, out.length),
- sampleRate: sr,
- });
- out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array<ArrayBuffer>, c));
- stretchedRanges.current = [{ key, buf }, ...stretchedRanges.current.filter((r) => r.key !== key)].slice(0, 4);
- return buf;
- }, []);
-
- // At a speed but 1x, the clip's selection is stretched while the bench is
- // idle, so "play the clip" does not wait for it (a minute of stereo is a
- // few hundred ms).
- useEffect(() => {
- const rate = playback.rate;
- if (audio.state !== "ready" || !wantsStretch(rate)) return;
- const d = decoded.current;
- if (!d) return;
- const sch = bufferSchedule(d.span, d.buf.duration, clip.start, clip.end, rate);
- if (!sch) return;
- const w = window as Window & {
- requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number;
- cancelIdleCallback?: (id: number) => void;
- };
- const run = () => {
- if (decoded.current === d) stretchFor(d, sch.offset, sch.duration, rate);
- };
- if (w.requestIdleCallback) {
- const id = w.requestIdleCallback(run, { timeout: 2000 });
- return () => w.cancelIdleCallback?.(id);
- }
- const id = window.setTimeout(run, 250);
- return () => window.clearTimeout(id);
- }, [audio.state, playback.rate, clip.start, clip.end, stretchFor]);
-
- /** Stop whatever is playing, Web Audio or element, and let go of it. */
- const stopPlayback = useCallback(() => {
- const s = session.current;
- if (!s) return;
- session.current = null;
- cancelAnimationFrame(s.raf);
- for (const t of s.timers) clearTimeout(t);
- for (const node of [s.node, ...(s.more ?? [])]) {
- if (!node) continue;
- node.onended = null;
- try {
- node.stop();
- } catch {
- /* never started, or already stopped */
- }
- node.disconnect();
- }
- s.gain?.disconnect();
- const el = video.current;
- if (el) {
- pauseVideo(el);
- el.muted = s.mutedBefore;
- }
- setPlayInfo((pi) => (pi && pi.state === "playing" ? { ...pi, state: "stopped" } : pi));
- }, [pauseVideo]);
-
- /**
- * The fallback: the element, stopped per animation frame by REMAINING TIME.
- *
- * `timeupdate` was the old stop and is the overrun this replaces; a frame
- * tick that stops once the end is under half a frame away is the best the
- * element can do, and the bench says that this is what is playing.
- */
- const playElement = useCallback(
- (from: number, to: number, gen: number, gaps: Span[] = []) => {
- const el = video.current;
- if (!el || !cached) return;
- const rate = playback.rate;
- el.currentTime = Math.max(0, from - fetchStart);
- el.playbackRate = rate;
- const s: Session = {
- gen,
- engine: "element",
- node: null,
- gain: null,
- raf: 0,
- timers: [],
- from,
- to,
- rate,
- t0: 0,
- ctxStop: 0,
- mutedBefore: el.muted,
- };
- session.current = s;
- setPlayInfo({
- engine: "element",
- state: "playing",
- from,
- to,
- rate,
- stretched: false,
- ctxStart: null,
- ctxStop: null,
- endedAt: null,
- });
- const stopNow = () => {
- if (session.current !== s) return;
- pauseVideo(el);
- session.current = null;
- cancelAnimationFrame(s.raf);
- for (const t of s.timers) clearTimeout(t);
- el.muted = s.mutedBefore;
- setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: el.currentTime + fetchStart } : pi));
- };
- const tick = () => {
- 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);
- if (!el.paused && elementShouldStop(t, to, rate)) {
- stopNow();
- return;
- }
- // Inside the last few frames, a timer for the REMAINING time: it lands
- // between frames, where the next tick would land up to a frame late.
- const remaining = (to - t) / rate;
- if (!el.paused && remaining < 0.1 && !s.timers.length) {
- s.timers.push(window.setTimeout(stopNow, remaining * 1000));
- }
- s.raf = requestAnimationFrame(tick);
- };
- s.raf = requestAnimationFrame(tick);
- // A rejected play() is normal, not a bug: Chrome refuses unmuted audio on
- // a document nobody has interacted with (a typed URL, a fresh tab), and
- // an unhandled rejection in that case would be noise. The seek has
- // already happened either way.
- void el.play().catch(() => {});
- },
- [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, { 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.
- let ac = actx.current;
- if (!ac && typeof window !== "undefined" && window.AudioContext) {
- ac = new window.AudioContext();
- actx.current = ac;
- }
- const resumed = ac && ac.state !== "running" ? ac.resume().catch(() => {}) : null;
- let d: Decoded;
- try {
- 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, 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, gaps);
- return;
- }
- if (resumed) await Promise.race([resumed, new Promise((res) => setTimeout(res, 300))]);
- // No gesture has ever reached this document, so the context may not
- // start: the same refusal a muted-autoplay policy gives the element, and
- // just as silent.
- if (gen !== playGen.current || ac!.state !== "running") return;
- const ctx = ac!;
- // 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 bufs = pieces.map(({ sch }) => (stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf));
- if (gen !== playGen.current) return;
-
- const gain = ctx.createGain();
- 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;
- // 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);
- }
- const node = nodes[0];
-
- const el = video.current;
- const s: Session = {
- gen,
- engine: "webaudio",
- node,
- gain,
- raf: 0,
- timers: [],
- from,
- to: end,
- rate,
- t0,
- ctxStop,
- mutedBefore: el?.muted ?? false,
- ...(nodes.length > 1 ? { more: nodes.slice(1) } : {}),
- };
- session.current = s;
- setPlayInfo({
- engine: "webaudio",
- state: "playing",
- from,
- to: s.to,
- rate,
- stretched,
- ctxStart: t0,
- 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.
- if (el) {
- el.muted = true;
- el.playbackRate = rate;
- el.currentTime = Math.max(0, from - fetchStart);
- s.timers.push(
- window.setTimeout(() => {
- 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),
- );
- }
- }
-
- 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.
- const late = ctx.currentTime - ctxStop;
- session.current = null;
- cancelAnimationFrame(s.raf);
- for (const t of s.timers) clearTimeout(t);
- for (const n of nodes) n.disconnect();
- gain.disconnect();
- if (el) {
- pauseVideo(el);
- el.muted = s.mutedBefore;
- }
- setPlayhead(s.to);
- setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: s.to + Math.max(0, late) * rate } : pi));
- };
-
- // The playhead at ~30 Hz, not every frame: each update re-renders the
- // bench, and the line moving smoothly is not worth that at 60.
- //
- // And the picture is pulled back to the sound when it drifts by more
- // than a quarter second -- which it does after a seek into a file that
- // is only partly loaded, where the element starts late by however long
- // the bytes took.
- let painted = -1;
- let checked = t0;
- const tick = () => {
- if (session.current !== s) return;
- const now = ctx.currentTime;
- 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);
- }
- if (el && now - checked >= 0.5 && now > t0) {
- checked = now;
- const want = pos - fetchStart;
- if (!el.seeking && Math.abs(el.currentTime - want) > 0.25) el.currentTime = want;
- }
- s.raf = requestAnimationFrame(tick);
- };
- s.raf = requestAnimationFrame(tick);
- },
- [cached, fetchStart, playback.rate, ensureDecoded, playElement, stopPlayback, pauseVideo, stretchFor],
- );
-
- // A speed change mid-playback would leave the picture and the sound at two
- // rates: stop, and the next play is at the new one.
- useEffect(() => {
- stopPlayback();
- }, [playback.rate, stopPlayback]);
-
- // Let go of the audio output with the bench.
- useEffect(
- () => () => {
- stopPlayback();
- void actx.current?.close().catch(() => {});
- actx.current = null;
- },
- [stopPlayback],
- );
-
// ---- auto-audition -------------------------------------------------------
//
// Off by default, and when it is on it waits for the element rather than
@@ -1453,41 +874,6 @@ export default function ClipBench({
};
}, [playback.auto, cached, clip.id, clip.start, clip.end, play]);
- // The element's own controls: unbounded "play from here", which stays on the
- // element. Its clock moves the playhead only while nothing bounded is
- // playing -- during a Web Audio playback the muted picture would otherwise
- // fight the audio clock for it. Pausing the picture by hand stops the sound
- // it is following.
- useEffect(() => {
- const el = video.current;
- if (!el) return;
- // While it plays by itself. A paused element's `timeupdate` is the one its
- // own pause fires -- after a Web Audio playback, that is the muted picture
- // stopping wherever it had got to, which is not where the sound stopped.
- const tick = () => {
- if (!session.current && !el.paused) setPlayhead(el.currentTime + fetchStart);
- };
- // A scrub on the paused element's own bar.
- const seeked = () => {
- if (!session.current) setPlayhead(el.currentTime + fetchStart);
- };
- const paused = () => {
- if (selfPauses.current > 0) {
- selfPauses.current -= 1;
- return;
- }
- if (session.current) stopPlayback();
- };
- el.addEventListener("timeupdate", tick);
- el.addEventListener("seeked", seeked);
- el.addEventListener("pause", paused);
- return () => {
- el.removeEventListener("timeupdate", tick);
- el.removeEventListener("seeked", seeked);
- el.removeEventListener("pause", paused);
- };
- }, [fetchStart, stopPlayback, cachedName]);
-
// ---- the selection ------------------------------------------------------
//
// Clamped to the cached file. Past its edge the handle stops and the "fetch
@@ -1851,31 +1237,6 @@ export default function ClipBench({
// waveform, by a nudge -- and every playback here mutes at it, so a mark is
// heard before it is saved.
- /** Re-aim the playback in flight at a new mark, from now. */
- const retargetMute = useCallback((t: number | null) => {
- const s = session.current;
- const ctx = actx.current;
- if (!s || s.engine !== "webaudio" || !s.gain || !ctx) return;
- const now = ctx.currentTime;
- const g = s.gain.gain;
- g.cancelScheduledValues(now);
- const pos = playheadAt(s.from, s.t0, now, s.rate, s.to - s.from);
- const m = t == null ? null : muteRamp(t, pos, s.to, s.rate);
- if (!m) {
- g.setValueAtTime(1, now);
- return;
- }
- if (m.at <= 0) {
- // Already past the mark: fade out from here.
- g.setValueAtTime(g.value, now);
- g.linearRampToValueAtTime(0, now + MUTE_FADE / s.rate);
- return;
- }
- g.setValueAtTime(1, now);
- g.setValueAtTime(1, now + m.at);
- g.linearRampToValueAtTime(0, now + m.at + m.fade);
- }, []);
-
/**
* Put the mark at `t`, inside the selection. `audition` plays across it --
* three seconds of sound and two of what should now be silence -- the way a
@@ -1923,16 +1284,6 @@ 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 [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");
@@ -1940,91 +1291,17 @@ export default function ClipBench({
},
[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);
+ // 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),
+ 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`,
+ setNote,
+ fmt: hms,
+ });
// ---- the zoom ----------------------------------------------------------------
// What the waveform shows of the cached window (bench/GapsZoom.tsx). Fit -- the
@@ -2166,15 +1443,15 @@ export default function ClipBench({
zoom.fit();
break;
case "F":
- zoom.to(gapSel ?? sel);
+ zoom.to(gap.sel ?? 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);
+ if (gap.sel) void gap.cut();
+ else gap.setPick((v) => !v);
break;
case "G":
- removeGapAt(playheadRef.current);
+ gap.removeAt(playheadRef.current);
break;
case "Escape":
// Reject ▾'s reasons are up: the Escape closes them (RejectClip), nothing else.
@@ -2182,9 +1459,9 @@ export default function ClipBench({
// (React flushes that discrete update in a microtask between the two window
// listeners, so isOpen() is false by now) and marked the event handled.
if (e.defaultPrevented || rejectCtl.current?.isOpen()) return;
- if (gapPick || gapSel) {
- setGapPick(false);
- setGapSel(null);
+ if (gap.pick || gap.sel) {
+ gap.setPick(false);
+ gap.setSel(null);
break;
}
if (!mutePick) return;
@@ -2219,10 +1496,10 @@ export default function ClipBench({
clearMute,
placeMute,
zoom,
- gapSel,
- gapPick,
- cutGap,
- removeGapAt,
+ gap.sel,
+ gap.pick,
+ gap.cut,
+ gap.removeAt,
]);
const refresh = useCallback(async (): Promise<ClipBenchData | null> => {
@@ -3427,7 +2704,7 @@ export default function ClipBench({
<video
ref={video}
data-testid="clip-video"
- src={`/api/report/raw?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}${vq}`}
+ src={media.src ?? undefined}
// object-contain, because the height is now whatever is left
// rather than whatever 16:9 asks for.
// The picture and the words SHARE what is left, 3:2, rather
@@ -3691,69 +2968,25 @@ export default function ClipBench({
<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);
- }}
+ <BenchWaveBox
+ zoom={zoom}
+ sel={sel}
+ cand={{ from: clip.start, to: clip.end }}
+ cues={cues}
+ peaks={peaks}
+ playhead={playhead}
+ onSel={onSel}
+ gap={gap}
+ gaps={clip.gaps ?? []}
+ silences={renderEdges?.silences ?? null}
+ words={nearWords?.words ?? null}
+ busy={!!busy}
+ held={mutePick}
>
- <Waveform
- 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) }))}
- peaks={peaks}
- playhead={playhead}
- height={104}
- onSel={onSel}
- onReachEdge={() => {
- /* widening is a FETCH here, not a redraw -- see the button below */
- }}
- />
{/* 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.
In the interaction colour, like the handles -- it is an edit,
not a reading -- and never in the way of a drag. */}
- {/* 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
@@ -3789,81 +3022,19 @@ export default function ClipBench({
}}
/>
)}
- </div>
+ </BenchWaveBox>
{/* Zoomed: the whole cached window, what is shown of it -- drag to pan. */}
{zoom.zoomed && <ZoomOverview zoom={zoom} whole={view} peaks={peaks} sel={sel} gaps={clip.gaps ?? []} />}
{/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */}
<div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]">
- {/* ---- GAPS inside the clip ----
- Seconds cut out of its middle: it renders as one segment of
- jump cuts. Written at once (not drafted like the edges), and
- every playback here skips them, as the cut will. */}
- <span data-gaps={(clip.gaps ?? []).map((g) => `${g.from}-${g.to}`).join(",")} className="flex flex-wrap items-center gap-1.5">
- {(clip.gaps ?? []).length ? (
- <span data-gaps-summary="" className="num text-[var(--color-text)]">
- {(clip.gaps ?? []).length} gap{(clip.gaps ?? []).length === 1 ? "" : "s"}{" "}
- <span className="text-[var(--color-dim)]">
- (the cut plays {gappedLength(gapSpan(clip).from, gapSpan(clip).to, clip.gaps ?? []).toFixed(2)} s of{" "}
- {(gapSpan(clip).to - gapSpan(clip).from).toFixed(2)} s, one segment)
- </span>
- </span>
- ) : (
- <span className="text-[var(--color-dim)]">no gaps — the cut plays whole</span>
- )}
- <button
- type="button"
- data-gap-pick={gapPick ? "armed" : ""}
- aria-pressed={gapPick}
- className={`${buttonVariants({ variant: "outline", size: "sm" })}${gapPick ? " bg-panel-2 border-muted" : ""}`}
- title="drag on the waveform to select seconds to cut out of the clip (g; or hold Alt and drag; Esc cancels)"
- onClick={() => setGapPick((v) => !v)}
- >
- {gapPick ? "Drag on the waveform…" : "Select a gap"}
- </button>
- {gapSel && (
- <>
- <button
- type="button"
- data-gap-cut=""
- className={buttonVariants({ size: "sm" })}
- disabled={!!busy || gapSel.to - gapSel.from < GAP_LIMITS.min}
- title="cut the selected seconds out of the clip (g)"
- onClick={() => void cutGap()}
- >
- Cut gap {hms(gapSel.from)}–{hms(gapSel.to)} ({(gapSel.to - gapSel.from).toFixed(2)} s)
- </button>
- <button
- type="button"
- data-gap-hear=""
- className={buttonVariants({ variant: "outline", size: "sm" })}
- title="two seconds either side, the selection skipped: the jump as the cut will play it"
- onClick={() => void play(Math.max(sel.from, gapSel.from - 2), Math.min(sel.to, gapSel.to + 2), { extra: gapSel })}
- >
- Hear it
- </button>
- <button
- type="button"
- data-gap-play-span=""
- className={buttonVariants({ variant: "outline", size: "sm" })}
- title="play what the selection would take out"
- onClick={() => void play(gapSel.from, gapSel.to, { through: true })}
- >
- Play the span
- </button>
- </>
- )}
- {gapUndo && (
- <button type="button" data-gap-undo="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={!!busy} onClick={undoGap} title={`undo: ${gapUndo.what}`}>
- Undo
- </button>
- )}
- </span>
+ {/* ---- 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} />
<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 ·{" "}
<kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead
</span>
- <ZoomControls zoom={zoom} whole={view} selection={gapSel ?? sel} playhead={playhead} />
+ <ZoomControls zoom={zoom} whole={view} selection={gap.sel ?? sel} playhead={playhead} />
</div>
</div>
diff --git a/umtool/components/projects/bench/BenchWave.tsx b/umtool/components/projects/bench/BenchWave.tsx
@@ -0,0 +1,214 @@
+"use client";
+
+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 type { Span } from "./benchMedia";
+import type { GapEditor } from "./useGapEditor";
+
+// ---------------------------------------------------------------------------
+// THE BENCH'S WAVEFORM AND ITS GAPS (lifted out of ClipBench.tsx; shared with
+// the reel's walk, lane/reel-bench): the zoomed waveform with its handles,
+// Alt + drag selecting a span for a gap (the waveform's own drag held off),
+// the gaps' bands and close-in pauses and words (GapLayer), any marks the
+// bench draws over it (`children`), and the gaps' row of tools under it.
+// Source seconds throughout; what plays is the bench's media's business.
+// ---------------------------------------------------------------------------
+
+type Cue = { start: number; end: number; text: string };
+
+/** The waveform box: Waveform, GapLayer and the bench's own overlays, with Alt + drag for a gap. */
+export function BenchWaveBox({
+ zoom,
+ sel,
+ cand,
+ cues,
+ peaks,
+ playhead,
+ onSel,
+ gap,
+ gaps,
+ silences,
+ words,
+ busy,
+ held = false,
+ children,
+}: {
+ zoom: WaveZoom;
+ sel: Span;
+ /** The saved extent, drawn behind the selection. */
+ cand: Span;
+ cues: Cue[];
+ peaks: Peaks | null;
+ playhead: number | null;
+ onSel: (next: Span, dragging: boolean, edge?: "start" | "end" | null) => void;
+ gap: GapEditor;
+ gaps: Span[];
+ silences: Span[] | null;
+ words: { start: number; end?: number; w?: string }[] | null;
+ busy: boolean;
+ /** Another pick is armed (the mute mark's): Alt + drag and the gap pick stand down. */
+ held?: boolean;
+ children?: React.ReactNode;
+}) {
+ const altDrag = useRef<{ id: number; at: number } | null>(null);
+ const zspan = Math.max(1e-6, zoom.vis.to - zoom.vis.from);
+ const tAt = (e: React.PointerEvent<HTMLDivElement>) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ return zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan;
+ };
+ return (
+ <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 || gap.pick || held) return;
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ const at = tAt(e);
+ altDrag.current = { id: e.pointerId, at };
+ gap.select({ from: at, to: at }, false);
+ }}
+ onPointerMoveCapture={(e) => {
+ const d = altDrag.current;
+ if (!d || d.id !== e.pointerId) return;
+ e.stopPropagation();
+ const t = tAt(e);
+ gap.select({ 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 t = tAt(e);
+ gap.select({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true);
+ }}
+ >
+ <Waveform
+ view={zoom.vis}
+ sel={sel}
+ cand={cand}
+ words={cues.map((c) => ({ start: c.start, end: c.end, w: c.text.slice(0, 24) }))}
+ peaks={peaks}
+ playhead={playhead}
+ height={104}
+ onSel={onSel}
+ onReachEdge={() => {
+ /* widening is the bench's own button, never a redraw */
+ }}
+ />
+ {/* The gaps, the span being selected for one, and close in the silences and the pauses between words. */}
+ <GapLayer
+ vis={zoom.vis}
+ gaps={gaps}
+ selection={gap.sel}
+ picking={gap.pick && !held}
+ silences={silences}
+ words={words}
+ busy={busy}
+ onRemove={gap.remove}
+ onSelect={gap.select}
+ />
+ {children}
+ </div>
+ );
+}
+
+/**
+ * The gaps' tools under the waveform: what they leave, Select a gap, Cut gap,
+ * Hear it, Play the span, Undo. `span` is what the gaps are inside (the
+ * clip's cut, a beat), `noun` what plays as one ("the cut", "the beat").
+ */
+export function GapTools({
+ gap,
+ gaps,
+ span,
+ sel,
+ busy,
+ fmt,
+ play,
+ noun = "the cut",
+ of = "the clip",
+}: {
+ gap: GapEditor;
+ gaps: Span[];
+ span: Span;
+ sel: Span;
+ busy: boolean;
+ fmt: (t: number) => string;
+ play: (from: number, to: number, o?: { through?: boolean; extra?: Span | null }) => unknown;
+ noun?: string;
+ of?: string;
+}) {
+ const g = gap.sel;
+ return (
+ // Seconds cut out of its middle: it plays as one run of jump cuts. Written
+ // at once (not drafted like the edges), and every playback here skips them.
+ <span data-gaps={gaps.map((x) => `${x.from}-${x.to}`).join(",")} className="flex flex-wrap items-center gap-1.5">
+ {gaps.length ? (
+ <span data-gaps-summary="" className="num text-[var(--color-text)]">
+ {gaps.length} gap{gaps.length === 1 ? "" : "s"}{" "}
+ <span className="text-[var(--color-dim)]">
+ ({noun} plays {gappedLength(span.from, span.to, gaps).toFixed(2)} s of {(span.to - span.from).toFixed(2)} s, one segment)
+ </span>
+ </span>
+ ) : (
+ <span className="text-[var(--color-dim)]">no gaps — {noun} plays whole</span>
+ )}
+ <button
+ type="button"
+ data-gap-pick={gap.pick ? "armed" : ""}
+ aria-pressed={gap.pick}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })}${gap.pick ? " bg-panel-2 border-muted" : ""}`}
+ title={`drag on the waveform to select seconds to cut out of ${of} (g; or hold Alt and drag; Esc cancels)`}
+ onClick={() => gap.setPick((v) => !v)}
+ >
+ {gap.pick ? "Drag on the waveform…" : "Select a gap"}
+ </button>
+ {g && (
+ <>
+ <button
+ type="button"
+ data-gap-cut=""
+ className={buttonVariants({ size: "sm" })}
+ disabled={busy || g.to - g.from < GAP_LIMITS.min}
+ title={`cut the selected seconds out of ${of} (g)`}
+ onClick={() => void gap.cut()}
+ >
+ Cut gap {fmt(g.from)}–{fmt(g.to)} ({(g.to - g.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, g.from - 2), Math.min(sel.to, g.to + 2), { extra: g })}
+ >
+ 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(g.from, g.to, { through: true })}
+ >
+ Play the span
+ </button>
+ </>
+ )}
+ {gap.undo && (
+ <button type="button" data-gap-undo="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={busy} onClick={gap.undoLast} title={`undo: ${gap.undo.what}`}>
+ Undo
+ </button>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/bench/benchMedia.ts b/umtool/components/projects/bench/benchMedia.ts
@@ -0,0 +1,125 @@
+import type { Peaks } from "@/components/Waveform";
+import { fileAt, fileSpans, peaksOnSource, sourceAt, type FileMap } from "@/lib/report/fileMedia.mjs";
+
+// ---------------------------------------------------------------------------
+// WHAT A BENCH PLAYS, behind one shape (lane/reel-bench): the bench's own
+// work -- edges, gaps, cues, words, the mute mark -- is always in SOURCE
+// seconds; a media adapter says where those seconds are in the picture and
+// the sound.
+//
+// sourceWindow the clip's cached raw window (the clip bench): the decode
+// clock IS the source clock, the element is offset by the
+// window's start (`fetchStart`), and a clip's gaps are still
+// in the file -- playback skips them.
+// renderedFile a rendered file in the project (a take's master, the
+// reel's walk) with its map onto the clip's source
+// (lib/report/fileMedia.mjs): the decode clock and the
+// element are the FILE's clock, and the render's own gaps
+// are already out of it.
+//
+// The playback engine (useBenchPlayer.ts) schedules on the decode clock and
+// reports the playhead back in source seconds; the waveform's peaks come
+// back on the source clock either way.
+// ---------------------------------------------------------------------------
+
+export type Span = { from: number; to: number };
+
+export type BenchMedia = {
+ kind: "source" | "file";
+ /** What is playing, for the decode cache: a new key is new audio. Null: nothing to play. */
+ key: string | null;
+ /** The <video>'s src. */
+ src: string | null;
+ /** The source seconds it holds: how far an edge may go. */
+ span: Span | null;
+ /** The decode clock's bounds (decodeSpan picks inside them). */
+ clock: Span | null;
+ /** A source second on the decode clock, and back. */
+ clockOf: (src: number) => number;
+ sourceOfClock: (c: number) => number;
+ /** A decode-clock second as the element's currentTime, and back. */
+ elOf: (c: number) => number;
+ clockOfEl: (t: number) => number;
+ /** Source-second spans to leave out, as decode-clock spans (the render's own gaps are already out of a file). */
+ clockGaps: (gaps: Span[]) => Span[];
+ /** The decoded sound of a decode-clock span: a WAV, `x-audio-from` its first second on that clock. */
+ audioUrl: (span: Span) => string;
+ /** The waveform's envelope, and how to put it on the source clock. */
+ peaksUrl: string | null;
+ peaksOnSource: (p: Peaks) => Peaks;
+};
+
+const enc = encodeURIComponent;
+
+/** The clip bench's media: the widest cached window of the clip, its bytes' version in every URL. */
+export function sourceWindowMedia({
+ project,
+ clip,
+ take,
+ win,
+}: {
+ project: string;
+ clip: string;
+ take: string | null;
+ win: { name: string; from: number; to: number; v?: string | null } | null;
+}): BenchMedia {
+ const tq = take ? `&take=${enc(take)}` : "";
+ const vq = win?.v ? `&v=${enc(win.v)}` : "";
+ const fetchStart = win?.from ?? 0;
+ const id = (t: number) => t;
+ return {
+ kind: "source",
+ key: win ? `${win.name}|${win.v ?? ""}` : null,
+ src: win ? `/api/report/raw?project=${enc(project)}&clip=${enc(clip)}&file=${enc(win.name)}${tq}${vq}` : null,
+ span: win ? { from: win.from, to: win.to } : null,
+ clock: win ? { from: win.from, to: win.to } : null,
+ clockOf: id,
+ sourceOfClock: id,
+ elOf: (c) => c - fetchStart,
+ clockOfEl: (t) => t + fetchStart,
+ clockGaps: (gaps) => gaps,
+ audioUrl: (s) =>
+ win
+ ? `/api/report/audio?project=${enc(project)}&clip=${enc(clip)}&file=${enc(win.name)}&from=${s.from}&to=${s.to}${tq}${vq}`
+ : "",
+ peaksUrl: win ? `/api/report/peaks?project=${enc(project)}&clip=${enc(clip)}&file=${enc(win.name)}${tq}${vq}` : null,
+ peaksOnSource: (p) => p,
+ };
+}
+
+/**
+ * A rendered file of the project (`path`, project-relative) over the source
+ * seconds `span` of one clip, through `map`. `v` the file's version (its mtime).
+ */
+export function renderedFileMedia({
+ project,
+ path,
+ v,
+ map,
+ span,
+}: {
+ project: string;
+ path: string;
+ v: string | number | null;
+ map: FileMap;
+ span: Span;
+}): BenchMedia {
+ const q = `project=${enc(project)}&path=${enc(path)}${v ? `&v=${enc(String(v))}` : ""}`;
+ const clock = { from: fileAt(map, span.from), to: fileAt(map, span.to) };
+ const id = (t: number) => t;
+ return {
+ kind: "file",
+ key: `${path}|${v ?? ""}`,
+ src: `/api/report/file?${q}`,
+ span,
+ clock,
+ clockOf: (s) => fileAt(map, s),
+ sourceOfClock: (c) => sourceAt(map, c),
+ elOf: id,
+ clockOfEl: id,
+ clockGaps: (gaps) => fileSpans(map, gaps),
+ audioUrl: (s) => `/api/report/audio?${q}&from=${s.from}&to=${s.to}`,
+ peaksUrl: `/api/report/peaks?${q}&from=${clock.from}&to=${clock.to}`,
+ peaksOnSource: (p) => peaksOnSource(p, span, map),
+ };
+}
diff --git a/umtool/components/projects/bench/useBenchPlayer.ts b/umtool/components/projects/bench/useBenchPlayer.ts
@@ -0,0 +1,539 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ MUTE_FADE,
+ START_LEAD,
+ bufferSchedule,
+ covers,
+ decodeSpan,
+ elementShouldStop,
+ muteRamp,
+ playheadAt,
+} from "@/lib/report/playback.mjs";
+import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs";
+import { GAP_FADE, gapsWithin, inGap, keptSpans } from "umtool-report-to-video/gaps";
+import type { BenchMedia, Span } from "./benchMedia";
+
+// ---------------------------------------------------------------------------
+// THE BENCH'S PLAYBACK ENGINE, shared by the clip bench and the reel's walk
+// (lifted out of ClipBench.tsx unchanged in behaviour; lane/reel-bench).
+//
+// EVERY BOUNDED RANGE PLAYS FROM DECODED AUDIO. A selection, an edge, a line
+// of the transcript, the auto-audition: each is an AudioBufferSourceNode
+// started at an exact offset and stopped at an exact time on the audio
+// clock, so what you hear ends where the selection ends, to the sample. The
+// <video> used to play these itself and was stopped from `timeupdate`, which
+// fires every 15-250 ms -- the stop overran by up to a quarter of a second,
+// and by a different amount every time, which is exactly what makes a cut
+// between two words impossible to judge by ear.
+//
+// The picture FOLLOWS, muted, and the playhead is read off the audio clock.
+// When the decode fails the element plays instead, stopped per animation
+// frame by remaining time, and the bench says so.
+//
+// Callers speak SOURCE seconds; the media adapter (benchMedia.ts) puts them
+// on the decode clock -- the source clock for a raw window, the file's for a
+// render -- and the playhead comes back in source seconds.
+// ---------------------------------------------------------------------------
+
+/** A decoded span of the media, on the decode clock. `name` is the media's key. */
+type Decoded = { name: string; span: Span; buf: AudioBuffer };
+
+/** What is playing, and what the last playback measured (the bench's `data-play-*`). */
+export type PlayInfo = {
+ engine: "webaudio" | "element";
+ state: "playing" | "stopped";
+ from: number;
+ /** The scheduled end, in source seconds. */
+ to: number;
+ rate: number;
+ /** Web Audio at a speed but 1x: time-stretched at its own pitch, played at 1x. */
+ stretched: boolean;
+ /** Context clock: when the source starts and when it is told to stop. */
+ ctxStart: number | null;
+ ctxStop: number | null;
+ /** Where the playback had reached, in source seconds, when the page heard it end. */
+ endedAt: number | null;
+};
+
+type Session = {
+ gen: number;
+ engine: "webaudio" | "element";
+ node: AudioBufferSourceNode | null;
+ gain: GainNode | null;
+ raf: number;
+ timers: number[];
+ /** On the decode clock. */
+ from: number;
+ to: number;
+ rate: number;
+ t0: number;
+ ctxStop: number;
+ mutedBefore: boolean;
+ more?: AudioBufferSourceNode[];
+};
+
+export type AudioState = { state: "idle" | "loading" | "ready" | "failed"; why?: string };
+
+export function useBenchPlayer({
+ media,
+ video,
+ rate,
+ gapsRef,
+ muteRef,
+ warm,
+}: {
+ media: BenchMedia;
+ video: React.RefObject<HTMLVideoElement | null>;
+ rate: number;
+ /** The gaps every playback skips (source seconds), read at the moment it schedules. */
+ gapsRef: React.RefObject<Span[]>;
+ /** The mute mark (source seconds) every playback fades out at, read when it schedules. */
+ muteRef: React.RefObject<number | null>;
+ /** The span decoded (and, at a speed, stretched) ahead of the first play: the clip's or the beat's. */
+ warm: Span;
+}) {
+ const [playhead, setPlayhead] = useState<number | null>(null);
+ const decoded = useRef<Decoded | null>(null);
+ const decoding = useRef<{ key: string; p: Promise<Decoded> } | null>(null);
+ const stretchedRanges = useRef<{ key: string; buf: AudioBuffer }[]>([]);
+ const actx = useRef<AudioContext | null>(null);
+ const session = useRef<Session | null>(null);
+ const playGen = useRef(0);
+ // Pauses the bench asked for itself and has not yet heard the event of: a
+ // `pause` event is a task, so it arrives AFTER the next playback has started.
+ const selfPauses = useRef(0);
+ const pauseVideo = useCallback((el: HTMLVideoElement) => {
+ if (el.paused) return;
+ selfPauses.current += 1;
+ el.pause();
+ }, []);
+ const [audio, setAudio] = useState<AudioState>({ state: "idle" });
+ const [playInfo, setPlayInfo] = useState<PlayInfo | null>(null);
+ const m = media;
+
+ /** The media's sound over (at least) `want` -- decode-clock seconds -- decoded once. */
+ const ensureDecoded = useCallback(
+ async (want: Span): Promise<Decoded> => {
+ if (!m.key || !m.clock) throw new Error("nothing is cached for this clip");
+ const have = decoded.current;
+ if (have && have.name === m.key && covers(have.span, want.from, want.to)) return have;
+ const span = decodeSpan(m.clock, want);
+ const key = `${m.key}|${span.from}|${span.to}`;
+ if (decoding.current?.key === key) return decoding.current.p;
+ const name = m.key;
+ const p = (async () => {
+ setAudio({ state: "loading" });
+ const r = await fetch(m.audioUrl(span));
+ if (!r.ok) {
+ const j = (await r.json().catch(() => null)) as { error?: string } | null;
+ throw new Error(j?.error ?? `the audio route answered ${r.status}`);
+ }
+ const from = Number(r.headers.get("x-audio-from") ?? span.from);
+ const bytes = await r.arrayBuffer();
+ const Offline = typeof window !== "undefined" ? (window.OfflineAudioContext ?? null) : null;
+ if (!Offline) throw new Error("this browser has no Web Audio");
+ const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes);
+ const d: Decoded = { name, span: { from, to: from + buf.duration }, buf };
+ decoded.current = d;
+ setAudio({ state: "ready" });
+ return d;
+ })();
+ decoding.current = { key, p };
+ p.catch((e: unknown) => {
+ if (decoding.current?.p === p) decoding.current = null;
+ setAudio({ state: "failed", why: e instanceof Error ? e.message : String(e) });
+ });
+ return p;
+ },
+ [m],
+ );
+
+ // Different media -- a wider window after a fetch, a re-rendered master -- is
+ // different audio: drop the old decode and start the new one now.
+ useEffect(() => {
+ decoded.current = null;
+ decoding.current = null;
+ setAudio({ state: "idle" });
+ if (!m.key) return;
+ ensureDecoded({ from: m.clockOf(warm.from), to: m.clockOf(warm.to) }).catch(() => {
+ /* said in the bench; play() falls back to the element */
+ });
+ // Keyed on the media's NAME: a refresh that returns the same window does not decode it again.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [m.key]);
+
+ /** [offset, offset + duration) of a decoded buffer, time-stretched to `rate` at its own pitch. */
+ const stretchFor = useCallback((d: Decoded, offset: number, duration: number, r: number): AudioBuffer => {
+ const key = `${d.name}|${d.span.from}|${offset.toFixed(5)}|${duration.toFixed(5)}|${r}`;
+ const hit = stretchedRanges.current.find((x) => x.key === key);
+ if (hit) return hit.buf;
+ const sr = d.buf.sampleRate;
+ const a = Math.max(0, Math.min(d.buf.length, Math.round(offset * sr)));
+ const b = Math.max(a, Math.min(d.buf.length, a + Math.round(duration * sr)));
+ const channels: Float32Array[] = [];
+ for (let c = 0; c < d.buf.numberOfChannels; c++) channels.push(d.buf.getChannelData(c).subarray(a, b));
+ const out = timeStretch(channels, sr, r);
+ const buf = new AudioBuffer({ length: Math.max(1, out[0]?.length ?? 0), numberOfChannels: Math.max(1, out.length), sampleRate: sr });
+ out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array<ArrayBuffer>, c));
+ stretchedRanges.current = [{ key, buf }, ...stretchedRanges.current.filter((x) => x.key !== key)].slice(0, 4);
+ return buf;
+ }, []);
+
+ // At a speed but 1x, the warm span is stretched while the bench is idle.
+ useEffect(() => {
+ if (audio.state !== "ready" || !wantsStretch(rate)) return;
+ const d = decoded.current;
+ if (!d) return;
+ const sch = bufferSchedule(d.span, d.buf.duration, m.clockOf(warm.from), m.clockOf(warm.to), rate);
+ if (!sch) return;
+ const w = window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number; cancelIdleCallback?: (id: number) => void };
+ const run = () => {
+ if (decoded.current === d) stretchFor(d, sch.offset, sch.duration, rate);
+ };
+ if (w.requestIdleCallback) {
+ const id = w.requestIdleCallback(run, { timeout: 2000 });
+ return () => w.cancelIdleCallback?.(id);
+ }
+ const id = window.setTimeout(run, 250);
+ return () => window.clearTimeout(id);
+ }, [audio.state, rate, warm.from, warm.to, stretchFor, m]);
+
+ /** Stop whatever is playing, Web Audio or element, and let go of it. */
+ const stopPlayback = useCallback(() => {
+ const s = session.current;
+ if (!s) return;
+ session.current = null;
+ cancelAnimationFrame(s.raf);
+ for (const t of s.timers) clearTimeout(t);
+ for (const node of [s.node, ...(s.more ?? [])]) {
+ if (!node) continue;
+ node.onended = null;
+ try {
+ node.stop();
+ } catch {
+ /* never started, or already stopped */
+ }
+ node.disconnect();
+ }
+ s.gain?.disconnect();
+ const el = video.current;
+ if (el) {
+ pauseVideo(el);
+ el.muted = s.mutedBefore;
+ }
+ setPlayInfo((pi) => (pi && pi.state === "playing" ? { ...pi, state: "stopped" } : pi));
+ }, [pauseVideo, video]);
+
+ /** The fallback: the element, stopped per animation frame by REMAINING TIME. Decode-clock seconds. */
+ const playElement = useCallback(
+ (from: number, to: number, gen: number, gaps: Span[] = []) => {
+ const el = video.current;
+ if (!el || !m.key) return;
+ el.currentTime = Math.max(0, m.elOf(from));
+ el.playbackRate = rate;
+ const s: Session = { gen, engine: "element", node: null, gain: null, raf: 0, timers: [], from, to, rate, t0: 0, ctxStop: 0, mutedBefore: el.muted };
+ session.current = s;
+ setPlayInfo({ engine: "element", state: "playing", from: m.sourceOfClock(from), to: m.sourceOfClock(to), rate, stretched: false, ctxStart: null, ctxStop: null, endedAt: null });
+ const stopNow = () => {
+ if (session.current !== s) return;
+ pauseVideo(el);
+ session.current = null;
+ cancelAnimationFrame(s.raf);
+ for (const t of s.timers) clearTimeout(t);
+ el.muted = s.mutedBefore;
+ setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: m.sourceOfClock(m.clockOfEl(el.currentTime)) } : pi));
+ };
+ const tick = () => {
+ if (session.current !== s) return;
+ const t = m.clockOfEl(el.currentTime);
+ setPlayhead(m.sourceOfClock(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 = m.elOf(g.to);
+ // The mark, as near as a frame tick gets it.
+ const mk = muteRef.current;
+ el.muted = s.mutedBefore || (mk != null && t >= m.clockOf(mk));
+ if (!el.paused && elementShouldStop(t, to, rate)) {
+ stopNow();
+ return;
+ }
+ // Inside the last few frames, a timer for the REMAINING time.
+ const remaining = (to - t) / rate;
+ if (!el.paused && remaining < 0.1 && !s.timers.length) s.timers.push(window.setTimeout(stopNow, remaining * 1000));
+ s.raf = requestAnimationFrame(tick);
+ };
+ s.raf = requestAnimationFrame(tick);
+ // A rejected play() is normal (no gesture yet): the seek has happened either way.
+ void el.play().catch(() => {});
+ },
+ [m, rate, pauseVideo, video, muteRef],
+ );
+
+ /**
+ * Play [from, to] (source seconds), skipping the gaps as the cut will: 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).
+ */
+ const play = useCallback(
+ async (srcFrom: number, srcTo: number, { through = false, extra = null }: { through?: boolean; extra?: Span | null } = {}) => {
+ const gen = (playGen.current += 1);
+ stopPlayback();
+ if (!m.key || !(srcTo > srcFrom)) return;
+ const srcGaps = through ? [] : gapsWithin([...(gapsRef.current ?? []), ...(extra ? [extra] : [])].sort((a, b) => a.from - b.from), srcFrom, srcTo);
+ // On the decode clock from here on.
+ const from = m.clockOf(srcFrom);
+ const to = m.clockOf(srcTo);
+ const gaps = gapsWithin(m.clockGaps(srcGaps), from, to);
+ const mark = muteRef.current == null ? null : m.clockOf(muteRef.current);
+ let ac = actx.current;
+ if (!ac && typeof window !== "undefined" && window.AudioContext) {
+ ac = new window.AudioContext();
+ actx.current = ac;
+ }
+ const resumed = ac && ac.state !== "running" ? ac.resume().catch(() => {}) : null;
+ let d: Decoded;
+ try {
+ 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, gaps);
+ return;
+ }
+ if (gen !== playGen.current) return;
+ if (!covers(d.span, from, to)) {
+ playElement(from, to, gen, gaps);
+ return;
+ }
+ if (resumed) await Promise.race([resumed, new Promise((res) => setTimeout(res, 300))]);
+ if (gen !== playGen.current || ac!.state !== "running") return;
+ const ctx = ac!;
+ 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;
+ const stretched = wantsStretch(rate);
+ const bufs = pieces.map(({ sch }) => (stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf));
+ if (gen !== playGen.current) return;
+
+ const gain = ctx.createGain();
+ gain.connect(ctx.destination);
+ const t0 = ctx.currentTime + START_LEAD;
+ 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);
+ node.start(t0 + w0, stretched ? 0 : sch.offset);
+ node.stop(t0 + w0 + sch.wall);
+ return node;
+ });
+ if (placed.length === 1) {
+ const mr = muteRamp(mark, from, from + placed[0].sch.duration, rate);
+ if (mr) {
+ if (mr.at <= 0) gain.gain.setValueAtTime(0, t0);
+ else {
+ gain.gain.setValueAtTime(1, t0 + mr.at);
+ gain.gain.linearRampToValueAtTime(0, t0 + mr.at + mr.fade);
+ }
+ }
+ } else {
+ // Across gaps: the joins' fades and the mute mark, as one level on the wall clock.
+ const fadeW = GAP_FADE / rate;
+ 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);
+ }
+
+ const el = video.current;
+ const s: Session = {
+ gen, engine: "webaudio", node: nodes[0], gain, raf: 0, timers: [], from, to: end, rate, t0, ctxStop,
+ mutedBefore: el?.muted ?? false,
+ ...(nodes.length > 1 ? { more: nodes.slice(1) } : {}),
+ };
+ session.current = s;
+ setPlayInfo({ engine: "webaudio", state: "playing", from: m.sourceOfClock(from), to: m.sourceOfClock(end), rate, stretched, ctxStart: t0, ctxStop, endedAt: null });
+ /** The decode-clock second playing `w` wall seconds in. */
+ 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.
+ if (el) {
+ el.muted = true;
+ el.playbackRate = rate;
+ el.currentTime = Math.max(0, m.elOf(from));
+ s.timers.push(window.setTimeout(() => {
+ if (session.current === s) void el.play().catch(() => {});
+ }, START_LEAD * 1000));
+ for (const x of placed.slice(1)) {
+ s.timers.push(window.setTimeout(() => {
+ if (session.current === s) el.currentTime = Math.max(0, m.elOf(x.p.from));
+ }, (START_LEAD + x.w0) * 1000));
+ }
+ }
+
+ const last = nodes[nodes.length - 1];
+ last.onended = () => {
+ if (session.current !== s) return;
+ const late = ctx.currentTime - ctxStop;
+ session.current = null;
+ cancelAnimationFrame(s.raf);
+ for (const t of s.timers) clearTimeout(t);
+ for (const n of nodes) n.disconnect();
+ gain.disconnect();
+ if (el) {
+ pauseVideo(el);
+ el.muted = s.mutedBefore;
+ }
+ setPlayhead(m.sourceOfClock(s.to));
+ setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: m.sourceOfClock(s.to + Math.max(0, late) * rate) } : pi));
+ };
+
+ // The playhead at ~30 Hz; the picture pulled back to the sound past a quarter second of drift.
+ let painted = -1;
+ let checked = t0;
+ const tick = () => {
+ if (session.current !== s) return;
+ const now = ctx.currentTime;
+ 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(m.sourceOfClock(pos));
+ }
+ if (el && now - checked >= 0.5 && now > t0) {
+ checked = now;
+ const want = m.elOf(pos);
+ if (!el.seeking && Math.abs(el.currentTime - want) > 0.25) el.currentTime = want;
+ }
+ s.raf = requestAnimationFrame(tick);
+ };
+ s.raf = requestAnimationFrame(tick);
+ },
+ [m, rate, ensureDecoded, playElement, stopPlayback, pauseVideo, stretchFor, video, gapsRef, muteRef],
+ );
+
+ // A speed change mid-playback would leave the picture and the sound at two rates.
+ useEffect(() => {
+ stopPlayback();
+ }, [rate, stopPlayback]);
+
+ // Let go of the audio output with the bench.
+ useEffect(
+ () => () => {
+ stopPlayback();
+ void actx.current?.close().catch(() => {});
+ actx.current = null;
+ },
+ [stopPlayback],
+ );
+
+ // The element's own controls: unbounded "play from here", which stays on the
+ // element. Its clock moves the playhead only while nothing bounded plays;
+ // pausing the picture by hand stops the sound it follows.
+ useEffect(() => {
+ const el = video.current;
+ if (!el) return;
+ const tick = () => {
+ if (!session.current && !el.paused) setPlayhead(m.sourceOfClock(m.clockOfEl(el.currentTime)));
+ };
+ const seeked = () => {
+ if (!session.current) setPlayhead(m.sourceOfClock(m.clockOfEl(el.currentTime)));
+ };
+ const paused = () => {
+ if (selfPauses.current > 0) {
+ selfPauses.current -= 1;
+ return;
+ }
+ if (session.current) stopPlayback();
+ };
+ el.addEventListener("timeupdate", tick);
+ el.addEventListener("seeked", seeked);
+ el.addEventListener("pause", paused);
+ return () => {
+ el.removeEventListener("timeupdate", tick);
+ el.removeEventListener("seeked", seeked);
+ el.removeEventListener("pause", paused);
+ };
+ // The element is the same one while the media is.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [m.key, stopPlayback]);
+
+ /** Re-aim the playback in flight at a new mute mark (source seconds), from now. */
+ const retargetMute = useCallback((t: number | null) => {
+ const s = session.current;
+ const ctx = actx.current;
+ if (!s || s.engine !== "webaudio" || !s.gain || !ctx) return;
+ const now = ctx.currentTime;
+ const g = s.gain.gain;
+ g.cancelScheduledValues(now);
+ const pos = playheadAt(s.from, s.t0, now, s.rate, s.to - s.from);
+ const mr = t == null ? null : muteRamp(m.clockOf(t), pos, s.to, s.rate);
+ if (!mr) {
+ g.setValueAtTime(1, now);
+ return;
+ }
+ if (mr.at <= 0) {
+ g.setValueAtTime(g.value, now);
+ g.linearRampToValueAtTime(0, now + MUTE_FADE / s.rate);
+ return;
+ }
+ g.setValueAtTime(1, now);
+ g.setValueAtTime(1, now + mr.at);
+ g.linearRampToValueAtTime(0, now + mr.at + mr.fade);
+ }, [m]);
+
+ /** Show the picture at a source second, paused (a click on the waveform, a handle let go). */
+ const showAt = useCallback(
+ (src: number) => {
+ const el = video.current;
+ if (!el || !m.key) return;
+ stopPlayback();
+ el.currentTime = Math.max(0, m.elOf(m.clockOf(src)));
+ setPlayhead(src);
+ },
+ [m, stopPlayback, video],
+ );
+
+ return { play, stopPlayback, playhead, setPlayhead, playInfo, audio, retargetMute, showAt, playing: playInfo?.state === "playing" };
+}
diff --git a/umtool/components/projects/bench/useGapEditor.ts b/umtool/components/projects/bench/useGapEditor.ts
@@ -0,0 +1,148 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { GAP_LIMITS, editGaps } from "umtool-report-to-video/gaps";
+import type { Span } from "./benchMedia";
+
+// ---------------------------------------------------------------------------
+// GAPS, EDITED (lifted out of ClipBench.tsx; lane/reel-bench): seconds cut
+// out of the middle of a span (umtool-report-to-video gaps.mjs), so it plays
+// as one run of jump cuts. 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; Undo writes the list back as it was. Written AT
+// ONCE, through the caller's writer -- a clip's window writer (`gapAdd` /
+// `gapRemove`) or a reel's beat writer -- which refuses what the build would;
+// the rule is checked here first (`refusal`), with the same sentences, so a
+// refusal is said before anything is sent.
+// ---------------------------------------------------------------------------
+
+export type GapOp = { add: Span } | { remove: Span } | { set: Span[] };
+
+const r2 = (n: number) => Number(n.toFixed(2));
+
+export function useGapEditor({
+ key,
+ gaps,
+ span,
+ refusal,
+ write,
+ said,
+ setNote,
+ fmt,
+}: {
+ /** What the gaps belong to: another one starts with nothing selected and nothing to undo. */
+ key: string;
+ /** The gaps as saved. */
+ gaps: Span[];
+ /** Where a gap may go (the clip's cut or extent; a beat's span). */
+ span: Span;
+ /** Why `next` cannot be written, or null. */
+ refusal: (next: Span[]) => string | null;
+ /** Write the op (`next` the list it makes); resolves whether it was written. */
+ write: (op: GapOp, next: Span[]) => Promise<boolean>;
+ /** The sentence after a write, with the list it made ("the cut plays 6.20 s, one segment"). */
+ said: (next: Span[]) => string;
+ setNote: (s: string | null) => void;
+ fmt: (t: number) => string;
+}) {
+ const [sel, setSel] = useState<Span | null>(null);
+ const [pick, setPick] = useState(false);
+ const [undo, setUndo] = useState<{ gaps: Span[]; what: string } | null>(null);
+ useEffect(() => {
+ setSel(null);
+ setPick(false);
+ setUndo(null);
+ }, [key]);
+
+ const run = useCallback(
+ async (op: GapOp, next: Span[], what: string) => {
+ const why = refusal(next);
+ if (why) {
+ setNote(`not cut: ${why}`);
+ return false;
+ }
+ const before = gaps;
+ const ok = await write(op, next);
+ if (ok) {
+ setUndo({ gaps: before, what });
+ setNote(`${what} — ${said(next)}`);
+ }
+ return ok;
+ },
+ [refusal, write, said, setNote, gaps],
+ );
+
+ const cut = useCallback(async () => {
+ const s = sel;
+ if (!s) return;
+ const g = { from: r2(s.from), to: r2(s.to) };
+ let next: Span[];
+ try {
+ next = editGaps(gaps, { add: g });
+ } catch (e) {
+ setNote(e instanceof Error ? e.message : String(e));
+ return;
+ }
+ const ok = await run({ add: g }, next, `cut ${fmt(g.from)}–${fmt(g.to)} out`);
+ if (ok) {
+ setSel(null);
+ setPick(false);
+ }
+ }, [sel, gaps, run, setNote, fmt]);
+
+ const remove = useCallback(
+ (g: Span) => {
+ const next = gaps.filter((x) => x.from !== g.from || x.to !== g.to);
+ void run({ remove: g }, next, `put ${fmt(g.from)}–${fmt(g.to)} back`);
+ },
+ [gaps, run, fmt],
+ );
+
+ /** `G`: the gap the playhead is in (or at the edge of). */
+ const removeAt = useCallback(
+ (t: number | null) => {
+ const g = t == null ? null : 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;
+ }
+ remove(g);
+ },
+ [gaps, remove, setNote],
+ );
+
+ const undoLast = useCallback(() => {
+ const u = undo;
+ if (!u) return;
+ void write({ set: u.gaps }, u.gaps).then((ok) => {
+ if (!ok) return;
+ setUndo(null);
+ setNote(`undone — ${u.what} is reversed`);
+ });
+ }, [undo, write, setNote]);
+
+ /** A span dragged for a gap: kept inside the span; 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);
+ if (!done) {
+ setSel(to > from ? { from, to } : null);
+ return;
+ }
+ if (to - from < GAP_LIMITS.min) {
+ setSel(null);
+ if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`);
+ 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`);
+ },
+ [span.from, span.to, gaps, refusal, setNote],
+ );
+
+ return { sel, setSel, pick, setPick, undo, cut, remove, removeAt, undoLast, select };
+}
+
+export type GapEditor = ReturnType<typeof useGapEditor>;
diff --git a/umtool/components/projects/bench/usePeaks.ts b/umtool/components/projects/bench/usePeaks.ts
@@ -0,0 +1,29 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import type { Peaks } from "@/components/Waveform";
+import type { BenchMedia } from "./benchMedia";
+
+/** The waveform's envelope for a bench's media, on the source clock (benchMedia.ts). One request per media. */
+export function usePeaks(media: BenchMedia): Peaks | null {
+ const [got, setGot] = useState<{ url: string; peaks: Peaks } | null>(null);
+ const url = media.peaksUrl;
+ const toSource = media.peaksOnSource;
+ useEffect(() => {
+ if (!url) return;
+ let live = true;
+ void (async () => {
+ const r = await fetch(url, { cache: "no-store" });
+ if (!r.ok || !live) return;
+ const p = (await r.json()) as Peaks;
+ if (live) setGot({ url, peaks: toSource(p) });
+ })();
+ return () => {
+ live = false;
+ };
+ // The URL names the media; its mapping comes with it.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [url]);
+ // Until the new media's envelope arrives, the last one stays drawn (as the bench always did).
+ return got?.peaks ?? null;
+}
diff --git a/umtool/lib/report/fileMedia.mjs b/umtool/lib/report/fileMedia.mjs
@@ -0,0 +1,80 @@
+// A RENDERED FILE AS A BENCH'S MEDIA (lane/reel-bench, 2 Nov).
+//
+// The clip bench plays a clip's cached RAW window, on the source clock. A
+// reel's walk plays a take's rendered MASTER -- the final frames, the chrome
+// burned in -- and works on the same source seconds: a beat is written in its
+// clip's source seconds, the cues and words are the clip's. Between the two
+// clocks is the build record's map: the file second the clip's segment
+// starts at (`segStart`), the source second its picture starts at
+// (`recStart`), and the source seconds the render cut out of it (`gaps`,
+// gaps.mjs). Within a kept piece the map is a shift; across a gap the file
+// goes straight on while the source jumps.
+//
+// Plain ESM: the bench's media adapter (components/projects/bench/benchMedia.ts)
+// and the tests read it.
+import { inGap, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps";
+
+/**
+ * @typedef {{ segStart: number, recStart: number, gaps: Array<{ from: number, to: number }> }} FileMap
+ */
+
+/**
+ * The file second a source second plays at (a second inside a gap the render
+ * cut out: the join).
+ *
+ * @param {FileMap} map
+ * @param {number} src
+ */
+export const fileAt = (map, src) => map.segStart + offsetIn(src, map.recStart, map.gaps ?? []);
+
+/**
+ * The source second a file second shows; at a join, the material after the gap.
+ *
+ * @param {FileMap} map
+ * @param {number} t
+ */
+export const sourceAt = (map, t) => sourceAtOffset(t - map.segStart, map.recStart, map.gaps ?? []);
+
+/**
+ * Source-second spans as spans of the file's clock: what is left of each once
+ * the render's own gaps are out (a span wholly inside one is nothing, and
+ * dropped).
+ *
+ * @param {FileMap} map
+ * @param {Array<{ from: number, to: number }>} spans
+ * @param {number} [min] shorter than this on the file's clock is dropped
+ */
+export function fileSpans(map, spans, min = 1e-3) {
+ const out = [];
+ for (const s of spans ?? []) {
+ const a = fileAt(map, s.from);
+ const b = fileAt(map, s.to);
+ if (b - a > min) out.push({ from: a, to: b });
+ }
+ return out;
+}
+
+/**
+ * A file's peaks (uniform over a span of the FILE's clock) as peaks over a
+ * span of SOURCE seconds -- what the bench's waveform draws. A source second
+ * inside a gap the render cut out is silence.
+ *
+ * @param {{ from: number, to: number, min: number[], max: number[] }} peaks on the file's clock
+ * @param {{ from: number, to: number }} span source seconds
+ * @param {FileMap} map
+ * @param {number} [n] buckets out
+ */
+export function peaksOnSource(peaks, span, map, n = peaks.max.length) {
+ const k = peaks.max.length;
+ const pSpan = Math.max(1e-9, peaks.to - peaks.from);
+ const width = Math.max(1e-9, span.to - span.from);
+ const min = [];
+ const max = [];
+ for (let b = 0; b < n; b += 1) {
+ const t = span.from + ((b + 0.5) / n) * width;
+ const i = inGap(t, map.gaps) ? -1 : Math.floor(((fileAt(map, t) - peaks.from) / pSpan) * k);
+ min.push(i >= 0 && i < k ? peaks.min[i] : 0);
+ max.push(i >= 0 && i < k ? peaks.max[i] : 0);
+ }
+ return { from: span.from, to: span.to, min, max };
+}