Archilyzer · Source

archilyzer

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

commit 15b28673b49b6eb91e70888b38e1849a392c05bc
parent a4e30bb49d3464525aa933922da92812f8b680af
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 14:47:21 -0500

umtool Play: each clip's sound is decoded once, and a gapped clip per kept piece -- never its gaps

Two wastes on the operator's cut (nt1 81 s, lw1 88 s, og1: ~180 MB of PCM in one neighbourhood against the bank's 72 MB):

- Every clip was decoded TWICE: on the manifest's edges while the render's were measured, then again on the render's once they landed. A decode is now found by what it covers (bankTrim.mjs coveringSlot, audioBank.ts resolve/lookup): a node plays from any decode of its clip's window whose span holds the seconds it reads. While the render's edges are measured (useRenderCuts `measuring`, handed to the engine as edgesPending) a clip's two outer ends are decoded EDGE_SLACK (2 s: snapWindow's 1.6 default and the snap's tail) wider, so the render's edges play from that decode; one that snaps further (a wider snapWindow, a montage's phrase) asks only for what nothing covers.
- A gapped clip decoded its whole span, gaps included (lw1: 88 s to play ~25 s). playSchedule.mjs decodesOf decodes per kept piece -- pieces under MERGE_GAP (1 s) apart as one -- each padded a quarter second, inside the cached window (the route clamps to it). audioSpans/scheduleFrom carry each span's `piece`, which the engine looks its decode up by. The joins are unchanged: each piece was already its own node with GAP_FADE out and in, so a node reading its own buffer instead of an offset into the clip's one is the same samples at the same start.

The bank's budget and keysToTrim are as they were: the keys touched are the decodes resolved for the clips around the playhead (now the one playing first, then ahead, then behind), so a wanted piece is never let go. The engine's stats add decodedSeconds and held (each decode's clip, span and state) for a probe.

codecPicture.ts BLOCK = 120 is a sample count, not seconds (two seconds at 60 fps): more round trips there, never a wrong frame -- the comment says so; the value is unchanged.

Tests: playDecodes.test.mjs (per piece, merging, the window clamp, measuring -> render reuse for a plain and a gapped clip, without the slack a second decode, a montage's cut); bankTrim.test.mjs coveringSlot. knobs.md "Play the cut" says it.

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

Diffstat:
Mumtool/components/projects/review/PlayCut.tsx | 4+++-
Mumtool/components/projects/review/playEngine/audioBank.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/components/projects/review/playEngine/codecPicture.ts | 4+++-
Mumtool/components/projects/review/playEngine/engine.ts | 86++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mumtool/components/projects/review/playEngine/usePlayEngine.ts | 14++++++++------
Mumtool/docs/knobs.md | 4+++-
Mumtool/lib/report/bankTrim.mjs | 31+++++++++++++++++++++++++++++--
Mumtool/lib/report/bankTrim.test.mjs | 12+++++++++++-
Aumtool/lib/report/playDecodes.test.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playSchedule.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
10 files changed, 374 insertions(+), 60 deletions(-)

diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -361,7 +361,9 @@ export default function PlayCut({ }).toString()}`, [project, take], ); - const engine = usePlayEngine({ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style }); + const engine = usePlayEngine({ + plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", + }); const { ui, rate, failed, seekTo, setPlaying, now } = engine; const setRate = engine.setRate; diff --git a/umtool/components/projects/review/playEngine/audioBank.ts b/umtool/components/projects/review/playEngine/audioBank.ts @@ -1,4 +1,4 @@ -import { keysToTrim } from "@/lib/report/bankTrim.mjs"; +import { coveringSlot, keysToTrim } from "@/lib/report/bankTrim.mjs"; import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; import type { MediaRef } from "./engine"; @@ -6,13 +6,20 @@ import type { MediaRef } from "./engine"; // fetched as PCM from the bench's /api/report/audio -- ffmpeg's decode of the // same cached window the picture comes from, so the samples are the ones the // build cuts, with no browser AAC priming to argue about -- and decoded once -// into an AudioBuffer. One buffer per CLIP (its sound and a quarter second -// either side, playSchedule.mjs decodeSpanOf), never a window: a window can be -// a two-minute excerpt and a cut has fifty clips, so the bank holds the clips -// around the playhead and lets the rest go, oldest use first, past a budget -// of decoded bytes (a 20-minute cut never holds 20 minutes of PCM). The clips -// the engine last asked for (touch) are never let go, even over the budget: -// one let go is asked for again at once, and the clock holds on it (bankTrim.mjs). +// into an AudioBuffer. One buffer per clip's SOUND, never a window: a window +// can be a two-minute excerpt and a cut has fifty clips. A clip with gaps is +// one buffer per kept piece (pieces under a second apart share one), never +// its gaps (playSchedule.mjs decodesOf). The bank holds the clips around the +// playhead and lets the rest go, oldest use first, past a budget of decoded +// bytes (a 20-minute cut never holds 20 minutes of PCM). The decodes the +// engine last asked for (touch) are never let go, even over the budget: one +// let go is asked for again at once, and the clock holds on it (bankTrim.mjs). +// +// A DECODE IS FOUND BY WHAT IT COVERS (`resolve`, bankTrim.mjs coveringSlot): +// a node plays from any decode of its clip's window whose span holds the +// seconds it reads, so the decode made on the manifest's edges (wider at the +// ends while the render's are measured) is the one the render's edges play +// from -- each clip's sound is asked for once, not once per set of edges. // // At a speed but 1x a clip is time-stretched at its own pitch (the bench's // timeStretch.mjs, WSOLA) and the stretched copy played at 1x -- the bench's @@ -21,8 +28,12 @@ import type { MediaRef } from "./engine"; /** A clip's decoded sound: its buffer and the source second of its first sample. */ export type ClipSound = { key: string; from: number; buf: AudioBuffer }; +type Span = { from: number; to: number }; + type Slot = { key: string; + /** The source seconds asked for (inside the window: the route clamps to it). */ + span: Span; state: "loading" | "ready" | "failed"; p: Promise<ClipSound | null>; sound: ClipSound | null; @@ -48,19 +59,44 @@ export class AudioBank { private budget = DEFAULT_BUDGET, ) {} - static keyOf(id: string, media: MediaRef, span: { from: number; to: number }) { - return `${id}|${media.name}|${media.v ?? ""}|${span.from}|${span.to}`; + static keyOf(id: string, media: MediaRef, span: Span) { + return `${AudioBank.prefixOf(id, media)}${span.from}|${span.to}`; + } + + /** Every decode of one clip's window (these bytes) starts with this. */ + static prefixOf(id: string, media: MediaRef) { + return `${id}|${media.name}|${media.v ?? ""}|`; } - /** The decode of a clip's span: started once, shared by every caller. */ - request(id: string, media: MediaRef, span: { from: number; to: number }): Promise<ClipSound | null> { + /** A decode held (or under way) that covers `need`, without asking for anything: its key, or null. */ + lookup(id: string, media: MediaRef, need: Span): string | null { + return coveringSlot([...this.slots.values()], AudioBank.prefixOf(id, media), need); + } + + /** + * The decode a span plays from: one held that covers `need` if there is + * one, else `ask` decoded (started once, shared by every caller). Its key, + * for peek and touch, and its promise. + */ + resolve(id: string, media: MediaRef, need: Span, ask: Span): { key: string; p: Promise<ClipSound | null> } { + const have = this.lookup(id, media, need); + if (have) { + const s = this.slots.get(have)!; + s.used = ++this.clock; + return { key: have, p: s.p }; + } + return { key: AudioBank.keyOf(id, media, ask), p: this.request(id, media, ask) }; + } + + /** The decode of exactly this span: started once, shared by every caller. */ + request(id: string, media: MediaRef, span: Span): Promise<ClipSound | null> { const key = AudioBank.keyOf(id, media, span); const have = this.slots.get(key); if (have) { have.used = ++this.clock; return have.p; } - const slot: Slot = { key, state: "loading", p: Promise.resolve(null), sound: null, why: null, bytes: 0, used: ++this.clock }; + const slot: Slot = { key, span: { from: span.from, to: span.to }, state: "loading", p: Promise.resolve(null), sound: null, why: null, bytes: 0, used: ++this.clock }; slot.p = (async () => { try { const r = await fetch(this.urlOf(id, media, span.from, span.to)); @@ -90,17 +126,17 @@ export class AudioBank { return slot.p; } - /** What the bank has for a clip now, without waiting: the sound, "loading", or "failed". */ - peek(id: string, media: MediaRef, span: { from: number; to: number }): ClipSound | "loading" | "failed" | null { - const s = this.slots.get(AudioBank.keyOf(id, media, span)); + /** What the bank has under a key now, without waiting: the sound, "loading", or "failed". */ + peek(key: string | null): ClipSound | "loading" | "failed" | null { + const s = key ? this.slots.get(key) : undefined; if (!s) return null; s.used = ++this.clock; return s.state === "ready" ? s.sound : s.state; } - /** Why a clip's sound did not decode (said in the Approximate line). */ - why(id: string, media: MediaRef, span: { from: number; to: number }) { - return this.slots.get(AudioBank.keyOf(id, media, span))?.why ?? null; + /** Why a decode failed (said in the Approximate line). */ + why(key: string) { + return this.slots.get(key)?.why ?? null; } /** These are the clips wanted now: marked in use, and kept by every trim until the next touch. */ @@ -144,6 +180,18 @@ export class AudioBank { return this.slots.size; } + /** Seconds of sound decoded and held now. */ + get seconds() { + let n = 0; + for (const s of this.slots.values()) n += s.sound?.buf.duration ?? 0; + return Math.round(n * 1000) / 1000; + } + + /** Each decode held: its clip, the span asked for and its state (the engine's stats, for the e2e and a probe). */ + get held() { + return [...this.slots.values()].map((s) => ({ id: s.key.split("|")[0], from: s.span.from, to: s.span.to, state: s.state })); + } + /** Over the budget: the least recently used decodes not wanted now go (a failure is kept, it is small and says why). */ private trim() { for (const k of keysToTrim([...this.slots.values()], this.wanted, this.budget)) this.slots.delete(k); diff --git a/umtool/components/projects/review/playEngine/codecPicture.ts b/umtool/components/projects/review/playEngine/codecPicture.ts @@ -30,7 +30,9 @@ const AHEAD_S = 0.6; /** * A byte-range read: up to this many samples (four seconds at 30 fps) or * bytes, whichever comes first -- few round trips, since a busy server answers - * each in a few hundred ms -- and the blocks a clip keeps. + * each in a few hundred ms -- and the blocks a clip keeps. A count of SAMPLES + * (frames), not seconds: two seconds at 60 fps, which is only more round + * trips (a block is found by sample index, never by time), not a wrong frame. */ const BLOCK = 120; const BLOCK_BYTES = 2 * 1024 * 1024; diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -1,7 +1,7 @@ import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; import { inGap } from "umtool-report-to-video/gaps"; import { cutAtSource, itemIndexAt, pieceWants, playPlan, sourceAt } from "@/lib/report/playCut.mjs"; -import { audioSpans, decodeSpanOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; +import { EDGE_SLACK, audioSpans, decodesOf, scheduleFrom } from "@/lib/report/playSchedule.mjs"; import { drawFootageLayers, type FootageLayer } from "../footageCanvas"; import { AudioBank, type ClipSound } from "./audioBank"; import { CodecPicture, codecsAvailable } from "./codecPicture"; @@ -96,6 +96,10 @@ export class PlayEngine { plan: Plan = { items: [], total: 0, edges: "estimate" }; private entries = new Map<string, EngineEntry>(); private spans: ReturnType<typeof audioSpans> = []; + /** Each clip's decodes, one per span (its piece), from the plan and the entry's window (decodesOf). */ + private decodes = new Map<string, ReturnType<typeof decodesOf>>(); + /** The plan's edges are the manifest's until the render's are measured: decode wider at a clip's ends. */ + private edgesPending = false; private failed = new Set<string>(); private silent: Record<string, string> = {}; @@ -168,11 +172,19 @@ export class PlayEngine { // ---- what plays ----------------------------------------------------------- - setPlan(plan: Plan, entries: Map<string, EngineEntry>) { + setPlan(plan: Plan, entries: Map<string, EngineEntry>, { edgesPending = false }: { edgesPending?: boolean } = {}) { const was = this.plan; + if (plan === was && entries === this.entries) { + // Only the edges' state moved (measuring, then an estimate after all): the decodes, not the clock. + this.edgesPending = edgesPending; + this.decodes = this.decodePlan(); + return; + } this.plan = plan; this.entries = entries; + this.edgesPending = edgesPending; this.spans = audioSpans(plan as never); + this.decodes = this.decodePlan(); if (was.items.length && plan.items.length) { // The same moment of the same clip after a re-plan (the render's edges // arriving, a reload): by its source second when it is a clip. @@ -342,29 +354,54 @@ export class PlayEngine { // ---- the sound ------------------------------------------------------------------ - private spanSound(id: string): { media: MediaRef; span: { from: number; to: number } } | null { + /** + * What each clip's sound is decoded as: per kept piece of a gapped clip + * (never its gaps), padded, and while the render's edges are measured + * EDGE_SLACK wider at its two ends -- so the render's edges play from the + * same decode (audioBank.ts resolve) and nothing is asked for twice. + */ + private decodePlan() { + const byId = new Map<string, ReturnType<typeof audioSpans>>(); + for (const s of this.spans) byId.set(s.id, [...(byId.get(s.id) ?? []), s]); + const out = new Map<string, ReturnType<typeof decodesOf>>(); + for (const [id, spans] of byId) { + const m = this.entries.get(id)?.media; + if (!m) continue; + out.set(id, decodesOf(spans, { slack: this.edgesPending ? EDGE_SLACK : 0, within: { from: m.from, to: m.to } })); + } + return out; + } + + /** The decode a span of a clip plays from (its piece): the window, what it reads, and what to ask for. */ + private spanSound(id: string, piece: number) { const e = this.entries.get(id); - // A clip with gaps is several spans (one per piece that plays): ONE decode covers them all. - const all = this.spans.filter((x) => x.id === id); - if (!e?.media || !all.length) return null; - const s = { src: Math.min(...all.map((x) => x.src)), srcTo: Math.max(...all.map((x) => x.srcTo)) }; - return { media: e.media, span: decodeSpanOf(s) }; + const d = this.decodes.get(id)?.[piece]; + if (!e?.media || !d) return null; + return { media: e.media, need: d.need, ask: d.ask }; } - /** Decode the clips around the playhead; the bank lets the far ones go. */ + /** Decode the clips around the playhead -- the one playing first, then those ahead, then behind; the bank lets the far ones go. */ private prefetch() { const keys: string[] = []; - for (let i = Math.max(0, this.cur - DECODE_BEHIND); i <= Math.min(this.plan.items.length - 1, this.cur + DECODE_AHEAD); i += 1) { + const last = this.plan.items.length - 1; + const order: number[] = []; + for (let i = this.cur; i <= Math.min(last, this.cur + DECODE_AHEAD); i += 1) order.push(i); + for (let i = this.cur - 1; i >= Math.max(0, this.cur - DECODE_BEHIND); i -= 1) order.push(i); + for (const i of order) { const it = this.plan.items[i]; - if (!it.clip) continue; - const ss = this.spanSound(it.id); - if (!ss) continue; - keys.push(AudioBank.keyOf(it.id, ss.media, ss.span)); - void this.bank.request(it.id, ss.media, ss.span).then((got) => { - if (!got && !this.silent[it.id]) { - this.silent = { ...this.silent, [it.id]: this.bank.why(it.id, ss.media, ss.span) ?? "no sound" }; - } - }); + if (!it?.clip) continue; + const ds = this.decodes.get(it.id); + const media = this.entries.get(it.id)?.media; + if (!ds || !media) continue; + for (const d of ds) { + const got = this.bank.resolve(it.id, media, d.need, d.ask); + keys.push(got.key); + void got.p.then((sound) => { + if (!sound && !this.silent[it.id]) { + this.silent = { ...this.silent, [it.id]: this.bank.why(got.key) ?? "no sound" }; + } + }); + } } this.bank.touch(keys); } @@ -382,8 +419,8 @@ export class PlayEngine { this.started.add(key); continue; } - const ss = this.spanSound(p.id); - const got = ss ? this.bank.peek(p.id, ss.media, ss.span) : "failed"; + const ss = this.spanSound(p.id, p.piece); + const got = ss ? this.bank.peek(this.bank.lookup(p.id, ss.media, ss.need)) : "failed"; // (A clip whose PICTURE failed still sounds: its sound is decoded on the server, not by the element.) if (got === "failed" || !ss) { this.started.add(key); // silent: the clock goes on @@ -464,10 +501,9 @@ export class PlayEngine { if (this.playing && this.waiting) { // Held: start again once what was due is decoded. const p = this.plannedFrom.find((x) => !this.started.has(`${x.id}|${x.atWall}`) && this.t0 + (x.atWall + x.durWall) * this.rate > this.t); - const ss = p ? this.spanSound(p.id) : null; + const ss = p ? this.spanSound(p.id, p.piece) : null; // Asked for here too: a hold far from where the prefetch looks (a seek) must not wait on nothing. - if (p && ss) void this.bank.request(p.id, ss.media, ss.span); - const got = p && ss ? this.bank.peek(p.id, ss.media, ss.span) : null; + const got = p && ss ? this.bank.peek(this.bank.resolve(p.id, ss.media, ss.need, ss.ask).key) : null; if (!p || !ss || got === "failed" || (got && got !== "loading" && this.bank.hasRate(got as ClipSound, this.rate))) { this.restart(this.t); } else if (got && got !== "loading") this.bank.atRate(got as ClipSound, this.rate); @@ -716,7 +752,7 @@ export class PlayEngine { /** How many clips' sound is decoded now, and the decoders open (read by the e2e through a data attribute). */ get stats() { return { - decoded: this.bank.size, bytes: this.bank.bytes, decoders: this.codecs?.open ?? 0, nodes: this.nodes.length, + decoded: this.bank.size, bytes: this.bank.bytes, decodedSeconds: this.bank.seconds, held: this.bank.held, decoders: this.codecs?.open ?? 0, nodes: this.nodes.length, scheduled: this.measured.nodes, framesDrawn: this.measured.drawn, framesOff: this.measured.off, worstFrames: this.measured.worst, offFrames: this.measured.late, contextTime: this.ctx?.currentTime ?? null, sound: this.sound, }; diff --git a/umtool/components/projects/review/playEngine/usePlayEngine.ts b/umtool/components/projects/review/playEngine/usePlayEngine.ts @@ -19,9 +19,11 @@ type Args = { bg: string; /** render.transitionStyle: how a crossfade is drawn (a dissolve, or a dip through the ground). */ style: string; + /** The plan's edges are the manifest's until the render's are measured (useRenderCuts `measuring`). */ + edgesPending?: boolean; }; -export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style }: Args) { +export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style, edgesPending = false }: Args) { const [ui, setUi] = useState<EngineUi>({ t: 0, cur: 0, playing: false, ended: false, waiting: false }); const [failed, setFailed] = useState<Record<string, string>>({}); const [info, setInfo] = useState<EngineInfo | null>(null); @@ -29,8 +31,8 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, const eng = useRef<PlayEngine | null>(null); const fns = useRef({ srcOf, audioOf }); fns.current = { srcOf, audioOf }; - const latest = useRef({ plan, entries }); - latest.current = { plan, entries }; + const latest = useRef({ plan, entries, edgesPending }); + latest.current = { plan, entries, edgesPending }; // Elements attach before the engine exists (refs before effects): held here and handed over. const els = useRef<{ canvas: HTMLCanvasElement | null; slots: (HTMLVideoElement | null)[] }>({ canvas: null, slots: [null, null] }); @@ -53,7 +55,7 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, }); e.attachCanvas(els.current.canvas); els.current.slots.forEach((el, k) => e.attachSlot(k, el)); - e.setPlan(latest.current.plan, latest.current.entries); + e.setPlan(latest.current.plan, latest.current.entries, { edgesPending: latest.current.edgesPending }); eng.current = e; // A handle for a console and the e2e (play-engine.spec.ts): the engine's own clock and its measurements. (window as Window & { __umtoolPlayEngine?: PlayEngine }).__umtoolPlayEngine = e; @@ -66,8 +68,8 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, }, []); useEffect(() => { - eng.current?.setPlan(plan, entries); - }, [plan, entries]); + eng.current?.setPlan(plan, entries, { edgesPending }); + }, [plan, entries, edgesPending]); useEffect(() => { eng.current?.setRate(rate); }, [rate]); diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -458,7 +458,9 @@ draws the same edges over its waveform as faint ghosts with their offset (**rend the measured silences as an edge is dragged. **The sound is on one Web Audio clock.** Each clip's sound is decoded (ffmpeg's decode of the cached window, the -bench's `/api/report/audio`; only the clips around the playhead are held) and scheduled back to back on one +bench's `/api/report/audio`; only the clips around the playhead are held) ONCE — while the render's edges are +measured, two seconds wider at the clip's ends, so the render's edges play from the same decode — and a clip with +gaps per kept piece, never its gaps (pieces under a second apart as one); it is scheduled back to back on one AudioContext, sample-exact at the render's edges: a crossfade is the build's two linear ramps over the overlap, the loudness gain, room's muted edges, the clip's own `audio` knobs and the mute mark are gain automation, and a speed time-stretches at the voice's pitch as the bench does. The clock of the whole view — the rail, the tally, the diff --git a/umtool/lib/report/bankTrim.mjs b/umtool/lib/report/bankTrim.mjs @@ -6,8 +6,10 @@ // budget. Letting a wanted decode go is a thrash, not a saving: the engine // asks for it again on its next tick, the clock holds on it ("loading…"), and // the next decode to land lets it go again. A neighbourhood of long gapped -// clips (each decoded whole, its gaps too) is past three minutes of PCM -// together, which is what kept nt1, lw1 and lj1 loading forever. +// clips (each decoded whole, its gaps too, as they were then) is past three +// minutes of PCM together, which is what kept nt1, lw1 and lj1 loading +// forever. (A gapped clip is decoded per kept piece now, and each clip once +// across the two sets of edges: `coveringSlot`, below.) /** * @param {{ key: string, state: string, bytes: number, used: number }[]} slots @@ -27,3 +29,28 @@ export function keysToTrim(slots, wanted, budget) { } return out; } + +/** + * The decode a node can play from: one of a clip's slots (same clip, same + * window, same bytes -- `prefix`) whose span covers the source seconds it + * reads. A decode is never asked for twice to play a span inside one already + * held: the manifest's edges and the render's (playSchedule.mjs decodesOf, + * EDGE_SLACK), a seek, a re-plan. Ready first, then one under way, then a + * failed one (so the node plays silent rather than holding the clock); the + * last used among equals. null: none covers it. + * + * @param {{ key: string, state: string, used: number, span: { from: number, to: number } }[]} slots + * @param {string} prefix + * @param {{ from: number, to: number }} need + */ +export function coveringSlot(slots, prefix, need) { + const rank = { ready: 0, loading: 1, failed: 2 }; + let best = null; + for (const s of slots) { + if (!s.key.startsWith(prefix)) continue; + if (!(s.span.from <= need.from + 1e-6 && s.span.to >= need.to - 1e-6)) continue; + const r = rank[/** @type {"ready" | "loading" | "failed"} */ (s.state)] ?? 3; + if (!best || r < best.r || (r === best.r && s.used > best.s.used)) best = { s, r }; + } + return best ? best.s.key : null; +} diff --git a/umtool/lib/report/bankTrim.test.mjs b/umtool/lib/report/bankTrim.test.mjs @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { keysToTrim } from "./bankTrim.mjs"; +import { coveringSlot, keysToTrim } from "./bankTrim.mjs"; const MB = 1024 * 1024; const slot = (key, mb, used, state = "ready") => ({ key, state, bytes: mb * MB, used }); @@ -37,3 +37,13 @@ test("stale-edge and out-of-window decodes go first, wanted ones stay", () => { test("a decode still loading is not trimmed (it has no bytes to give back)", () => { assert.deepEqual(keysToTrim([slot("a", 0, 1, "loading"), slot("b", 80, 2)], new Set(["b"]), 72 * MB), []); }); + +test("coveringSlot: a decode of the clip's window that holds the seconds; ready before loading before failed", () => { + const s = (key, state, from, to, used = 1) => ({ key, state, used, span: { from, to } }); + const slots = [s("a|w|1|9|20", "loading", 9, 20, 5), s("a|w|1|9.5|15", "ready", 9.5, 15, 1), s("b|w|1|0|100", "ready", 0, 100, 9)]; + assert.equal(coveringSlot(slots, "a|w|1|", { from: 10, to: 14 }), "a|w|1|9.5|15", "the ready one"); + assert.equal(coveringSlot(slots, "a|w|1|", { from: 10, to: 19 }), "a|w|1|9|20", "only the one under way covers it"); + assert.equal(coveringSlot(slots, "a|w|1|", { from: 8, to: 14 }), null, "none: another clip's never counts"); + assert.equal(coveringSlot([s("a|w|1|0|9", "failed", 0, 9)], "a|w|1|", { from: 1, to: 2 }), "a|w|1|0|9", "a failure plays silent, not held"); + assert.equal(coveringSlot([s("a|w|2|0|9", "ready", 0, 9)], "a|w|1|", { from: 1, to: 2 }), null, "the window's bytes replaced: another version"); +}); diff --git a/umtool/lib/report/playDecodes.test.mjs b/umtool/lib/report/playDecodes.test.mjs @@ -0,0 +1,120 @@ +// What the Play view decodes of each clip's sound (playSchedule.mjs decodesOf, +// bankTrim.mjs coveringSlot): a gapped clip per kept piece, never its gaps; +// pieces under a second apart as one; and one decode per clip across the +// manifest's edges and the render's -- the render's play from the decode made +// while they were measured, found by what it covers. +// +// Run with: node --test lib/report/playDecodes.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; + +import { coveringSlot } from "./bankTrim.mjs"; +import { playPlan } from "./playCut.mjs"; +import { EDGE_SLACK, MERGE_GAP, audioSpans, decodesOf, scheduleFrom } from "./playSchedule.mjs"; + +const WIN = { from: 0, to: 600 }; + +/** The engine's prefetch, as arithmetic: each span's decode found by what it covers, else asked for (a new slot). */ +function resolveAll(slots, id, decodes) { + const asked = []; + const keys = decodes.map((d) => { + const have = coveringSlot(slots, `${id}|`, d.need); + if (have) return have; + const key = `${id}|${d.ask.from}|${d.ask.to}`; + if (!slots.some((s) => s.key === key)) { + slots.push({ key, state: "loading", used: slots.length, span: d.ask }); + asked.push(d.ask); + } + return key; + }); + return { keys, asked }; +} +const secondsOf = (asks) => Math.round(asks.reduce((n, a) => n + (a.to - a.from), 0) * 1000) / 1000; +const spansOf = (plan, id) => audioSpans(plan).filter((s) => s.id === id); + +// lw1's shape: an 88 s span of which about 25 s plays (three gaps). +const lw1 = { id: "lw1", type: "clip", video: "v", start: 100, end: 188, gaps: [{ from: 106, to: 130 }, { from: 138, to: 160 }, { from: 166, to: 183 }] }; +const lw1Plan = (cuts = null) => playPlan([{ id: "lw1", start: 0, duration: 25 }], [lw1], { leadIn: 0, cuts }); + +test("a gapped clip is decoded per kept piece: the 25 s it plays and the pads, never its 63 s of gaps", () => { + const spans = spansOf(lw1Plan(), "lw1"); + assert.deepEqual(spans.map((s) => s.piece), [0, 1, 2, 3], "one span per piece, each carrying its piece"); + const ds = decodesOf(spans, { within: WIN }); + const { asked } = resolveAll([], "lw1", ds); + assert.equal(asked.length, 4, "four pieces, four decodes"); + assert.deepEqual(asked, [{ from: 99.75, to: 106.25 }, { from: 129.75, to: 138.25 }, { from: 159.75, to: 166.25 }, { from: 182.75, to: 188.25 }]); + assert.equal(secondsOf(asked), 25 + 4 * 0.5, "the kept seconds and a quarter second either side of each"); + // Each node reads inside its own decode. + for (const d of ds) assert.ok(d.ask.from <= d.need.from && d.ask.to >= d.need.to); +}); + +test("pieces under MERGE_GAP apart share one decode; further apart they do not", () => { + const spans = [{ src: 10, srcTo: 14 }, { src: 14.6, srcTo: 18 }, { src: 25, srcTo: 30 }]; + const ds = decodesOf(spans, { within: WIN }); + assert.ok(MERGE_GAP > 0.6 && MERGE_GAP < 7); + assert.deepEqual(ds.map((d) => d.ask), [{ from: 9.75, to: 18.25 }, { from: 9.75, to: 18.25 }, { from: 24.75, to: 30.25 }]); + assert.equal(resolveAll([], "x", ds).asked.length, 2, "two requests for three pieces"); +}); + +test("a decode stays inside the cached window (the route clamps to it), and a node's seconds with it", () => { + const ds = decodesOf([{ src: 0.1, srcTo: 5 }], { within: { from: 0.05, to: 4.9 }, slack: EDGE_SLACK }); + assert.deepEqual(ds[0].ask, { from: 0.05, to: 4.9 }); + assert.deepEqual(ds[0].need, { from: 0.1, to: 4.9 }); + assert.equal(coveringSlot([{ key: "x|a", state: "ready", used: 1, span: ds[0].ask }], "x|", ds[0].need), "x|a", "covered: never asked again"); +}); + +// The render snaps each clip's edges to a silence: up to a second or so either way (cutPoints.mjs). +const plain = { id: "nt1", type: "clip", video: "v", start: 200, end: 281 }; +const plainPlan = (cuts = null) => playPlan([{ id: "nt1", start: 0, duration: 81 }], [plain], { leadIn: 0, cuts }); + +test("measuring, then the render's edges: ONE decode of a plain clip -- the render's play from the wide one", () => { + const slots = []; + // While the render's edges are measured: the manifest's, EDGE_SLACK wider at both ends. + const first = resolveAll(slots, "nt1", decodesOf(spansOf(plainPlan(), "nt1"), { slack: EDGE_SLACK, within: WIN })); + assert.equal(first.asked.length, 1); + assert.deepEqual(first.asked[0], { from: 200 - 0.25 - EDGE_SLACK, to: 281 + 0.25 + EDGE_SLACK }); + slots[0].state = "ready"; + // The render's land: the start 1.1 s earlier, the end 1.4 s later. + const render = plainPlan(new Map([["nt1", { cutStart: 198.9, cutEnd: 282.4 }]])); + const second = resolveAll(slots, "nt1", decodesOf(spansOf(render, "nt1"), { within: WIN })); + assert.equal(second.asked.length, 0, "nothing asked for again"); + assert.deepEqual(second.keys, [slots[0].key], "the render's span plays from the manifest's decode"); + // A node from any second of it reads inside that decode (offset src − its first second, as the engine starts it). + for (const p of scheduleFrom(audioSpans(render), 30)) { + assert.ok(p.src >= slots[0].span.from && p.srcTo <= slots[0].span.to); + } +}); + +test("without the slack the render's wider edges would be a second decode (why it is there)", () => { + const slots = []; + resolveAll(slots, "nt1", decodesOf(spansOf(plainPlan(), "nt1"), { within: WIN })); + const render = plainPlan(new Map([["nt1", { cutStart: 198.9, cutEnd: 282.4 }]])); + assert.equal(resolveAll(slots, "nt1", decodesOf(spansOf(render, "nt1"), { within: WIN })).asked.length, 1); +}); + +test("a gapped clip across the two sets of edges: its pieces decoded once, the outer ones wide", () => { + const slots = []; + const first = resolveAll(slots, "lw1", decodesOf(spansOf(lw1Plan(), "lw1"), { slack: EDGE_SLACK, within: WIN })); + assert.equal(first.asked.length, 4); + assert.equal(first.asked[0].from, 100 - 0.25 - EDGE_SLACK, "the first piece wide at the clip's start"); + assert.equal(first.asked[3].to, 188 + 0.25 + EDGE_SLACK, "the last piece wide at its end"); + assert.equal(first.asked[1].from, 129.75, "an inner piece only padded: a gap's edges are exact"); + // The render's: its edges snapped, its gaps on the frame grid (within a frame of the manifest's). + const render = lw1Plan(new Map([["lw1", { + cutStart: 99.2, cutEnd: 189.1, + gaps: [{ from: 106.0, to: 130.033 }, { from: 137.967, to: 160.0 }, { from: 166.033, to: 183.0 }], + }]])); + const second = resolveAll(slots, "lw1", decodesOf(spansOf(render, "lw1"), { within: WIN })); + assert.equal(second.asked.length, 0, "every render piece inside a decode already made"); + assert.deepEqual(second.keys, first.keys); + assert.ok(secondsOf(first.asked) < 25 + 4 * 0.5 + 2 * EDGE_SLACK + 1e-9, "the kept seconds, the pads and the slack: not the 88 s span"); +}); + +test("a render that cuts differently (a montage's phrase: no gaps) asks only for what nothing covers", () => { + const slots = []; + resolveAll(slots, "lw1", decodesOf(spansOf(lw1Plan(), "lw1"), { slack: EDGE_SLACK, within: WIN })); + const render = lw1Plan(new Map([["lw1", { cutStart: 101, cutEnd: 105.5 }]])); + assert.equal(resolveAll(slots, "lw1", decodesOf(spansOf(render, "lw1"), { within: WIN })).asked.length, 0, "inside the first piece's decode"); + const wide = lw1Plan(new Map([["lw1", { cutStart: 101, cutEnd: 140 }]])); + assert.equal(resolveAll(slots, "lw1", decodesOf(spansOf(wide, "lw1"), { within: WIN })).asked.length, 1, "across a gap no piece covers: asked once"); +}); diff --git a/umtool/lib/report/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs @@ -83,7 +83,10 @@ const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : * sourceFrom: number, sourceTo: number, playEnd: number, hold: number, * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number, soundFrom?: number, * gaps?: Array<{ from: number, to: number }> } }> }} plan - * @returns {Array<{ id: string, index: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} + * `piece` is the span's place among its clip's (0 for a clip with no gaps): + * what its decode is looked up by (decodesOf). + * + * @returns {Array<{ id: string, index: number, piece: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} */ export function audioSpans(plan) { const items = plan?.items ?? []; @@ -125,7 +128,7 @@ export function audioSpans(plan) { const shift = fin(a.offset) ? a.offset / 1000 : 0; if (!gaps) { out.push({ - id: it.id, index: i, from, to, + id: it.id, index: i, piece: 0, from, to, src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), env: multiply(envs, from, to), gain: r6(10 ** (db / 20)), @@ -142,7 +145,7 @@ export function audioSpans(plan) { if (k > 0) joins.push(ramp(p.a, p.a + d)); if (k < pieces.length - 1) joins.push(ramp(p.b - d, p.b, true)); out.push({ - id: it.id, index: i, from: r6(p.a), to: r6(p.b), + id: it.id, index: i, piece: k, from: r6(p.a), to: r6(p.b), src: r6(p.src - shift), srcTo: r6(p.src - shift + (p.b - p.a)), env: multiply([...envs, ...joins], p.a, p.b), gain: r6(10 ** (db / 20)), @@ -175,6 +178,7 @@ export function scheduleFrom(spans, t, rate = 1, { until = Infinity } = {}) { out.push({ id: s.id, index: s.index, + piece: s.piece ?? 0, atWall: r6((begin - t) / r), durWall: r6((s.to - begin) / r), src: r6(s.src + (begin - s.from)), @@ -190,7 +194,8 @@ export function scheduleFrom(spans, t, rate = 1, { until = Infinity } = {}) { export const cutTimeAtCtx = (t0, ctxStart, now, rate = 1) => t0 + Math.max(0, now - ctxStart) * (rate > 0 ? rate : 1); /** - * Which span of a clip's source to decode for Play: its whole sound + * One span's decode (the engine's are decodesOf, below: per kept piece, and + * found by what they cover). Which span of a clip's source to decode for Play: its whole sound * (offset included) and a little either side, so a seek and a crossfade read * inside one buffer. Bounded: a clip is seconds, never a recording. * @@ -201,3 +206,63 @@ export function decodeSpanOf(span, { pad = 0.25, max = 120 } = {}) { const from = Math.max(0, span.src - pad); return { from: Math.round(from * 1000) / 1000, to: Math.round(Math.min(span.srcTo + pad, from + max) * 1000) / 1000 }; } + +/** + * How far the render may move a clip's OUTER edge from the manifest's (s): + * render.snapWindow's default (1.6, snap.mjs SNAP_DEFAULTS) and the snap's + * tail (0.18), rounded up. While the render's edges are being measured + * (useRenderCuts `measuring`) a clip's sound is decoded this much wider at + * its two ends, so the decode on the manifest's edges is the one the render's + * play from too -- found by what it covers (bankTrim.mjs coveringSlot), not + * asked for again. A cut that snaps further (a wider `snapWindow`, a montage's + * phrase cut) asks again for what it does not cover. + */ +export const EDGE_SLACK = 2; +/** Kept pieces of a gapped clip less than this far apart (source s) are decoded as one. */ +export const MERGE_GAP = 1; + +const msDown = (v) => Math.floor(v * 1000 + 1e-6) / 1000; +const msUp = (v) => Math.ceil(v * 1000 - 1e-6) / 1000; + +/** + * WHAT TO DECODE FOR ONE CLIP'S SOUND: for each of its spans (audioSpans, one + * per kept piece, in order), the source seconds its node reads (`need`) and + * the span to ask the audio route for when no decode held covers them + * (`ask`). A clip with gaps is decoded PER PIECE -- never its gaps: a clip + * that keeps 25 s of an 88 s span decodes 25 s and the pads -- except that + * pieces under `merge` apart share one decode (one request, not several + * for a few hundred ms saved). Each decode is the pieces' sound and `pad` + * either side (a seek and a crossfade read inside it), the clip's outer two + * edges `slack` more (EDGE_SLACK while the render's edges are measured, else + * 0); all of it inside the cached window (`within`: the route clamps to it + * too), at most `max` long. + * + * @param {Array<{ src: number, srcTo: number }>} spans the clip's, in order + * @param {{ pad?: number, slack?: number, merge?: number, max?: number, within?: { from: number, to: number } | null }} [opts] + * @returns {Array<{ need: { from: number, to: number }, ask: { from: number, to: number } }>} one per span + */ +export function decodesOf(spans, { pad = 0.25, slack = 0, merge = MERGE_GAP, max = 120, within = null } = {}) { + const lo = within && fin(within.from) ? within.from : 0; + const hi = within && fin(within.to) ? within.to : Infinity; + const clamp = (v) => Math.min(hi, Math.max(lo, v)); + /** @type {number[][]} */ + const groups = []; + spans.forEach((s, k) => { + const g = groups[groups.length - 1]; + if (g && s.src - spans[g[g.length - 1]].srcTo < merge) g.push(k); + else groups.push([k]); + }); + const out = new Array(spans.length); + groups.forEach((g, n) => { + const a = spans[g[0]]; + const b = spans[g[g.length - 1]]; + const from = msDown(clamp(Math.max(0, a.src - pad - (n === 0 ? slack : 0)))); + const to = msUp(Math.min(clamp(b.srcTo + pad + (n === groups.length - 1 ? slack : 0)), from + max)); + for (const k of g) { + const s = spans[k]; + const nf = clamp(s.src); + out[k] = { need: { from: r6(nf), to: r6(Math.max(nf, clamp(s.srcTo))) }, ask: { from, to } }; + } + }); + return out; +}