import { coveringSlot, keysToTrim } from "@/lib/report/bankTrim.mjs"; import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; import type { MediaRef } from "./engine"; // THE PLAY VIEW'S DECODED SOUND (the engine's, engine.ts): each clip's sound, // 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'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 // rule, so a voice at 1.5x sounds the same in both. /** 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; sound: ClipSound | null; why: string | null; bytes: number; used: number; }; /** About 3 minutes of 48 kHz stereo as 32-bit floats. */ const DEFAULT_BUDGET = 72 * 1024 * 1024; /** Stretched copies kept (the clip playing and the next few). */ const STRETCHED_KEPT = 6; export class AudioBank { private slots = new Map(); private stretched: { key: string; buf: AudioBuffer }[] = []; private clock = 0; /** The keys the engine asked for last (touch): the clips around the playhead, on the edges in force. */ private wanted: Set | null = null; constructor( private urlOf: (id: string, media: MediaRef, from: number, to: number) => string, private budget = DEFAULT_BUDGET, ) {} 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 ?? ""}|`; } /** 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 } { 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 { 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, 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)); 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"); // Decoded on an offline context: a buffer belongs to no context and // plays in the real one, which need not exist yet. const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes); slot.sound = { key, from, buf }; slot.bytes = buf.length * buf.numberOfChannels * 4; slot.state = "ready"; this.trim(); return slot.sound; } catch (e) { slot.state = "failed"; slot.why = e instanceof Error ? e.message : String(e); return null; } })(); this.slots.set(key, slot); return slot.p; } /** 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 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. */ touch(keys: Iterable) { this.wanted = new Set(keys); for (const k of this.wanted) { const s = this.slots.get(k); if (s) s.used = ++this.clock; } this.trim(); } /** The sound at `rate`: itself at 1x, else a stretched copy (made once, kept for the clips near the playhead). */ atRate(sound: ClipSound, rate: number): AudioBuffer { if (!wantsStretch(rate)) return sound.buf; const key = `${sound.key}|${rate}`; const hit = this.stretched.find((x) => x.key === key); if (hit) return hit.buf; const d = sound.buf; const channels: Float32Array[] = []; for (let c = 0; c < d.numberOfChannels; c++) channels.push(d.getChannelData(c)); const out = timeStretch(channels, d.sampleRate, rate) as Float32Array[]; const buf = new AudioBuffer({ length: Math.max(1, out[0]?.length ?? 0), numberOfChannels: Math.max(1, out.length), sampleRate: d.sampleRate }); out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array, c)); this.stretched = [{ key, buf }, ...this.stretched.filter((x) => x.key !== key)].slice(0, STRETCHED_KEPT); return buf; } hasRate(sound: ClipSound, rate: number) { return !wantsStretch(rate) || this.stretched.some((x) => x.key === `${sound.key}|${rate}`); } /** Decoded bytes held now (the budget's measure). */ get bytes() { let n = 0; for (const s of this.slots.values()) n += s.bytes; return n; } get size() { 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); } clear() { this.slots.clear(); this.wanted = null; this.stretched = []; } }