/** * jsdom has no Web Audio and no media stack, so the player's tests bring their * own — enough of the real semantics to be worth testing against, none of the * audio hardware. * * The parts that are deliberately *not* simplified, because they are where the * bugs live: * - `start()` may be called once per source node (a second call throws), which * is what forces pause/resume to build a new node; * - `stop()` fires `ended`, exactly as browsers do — so a player that advances * the queue from `ended` without filtering its own stops fails here; * - `stop(when)` with a time defers that `ended` until `advance()` carries the * clock past `when`, because that is what a scheduled stop is: a promise to the * audio thread, not an event for whoever asked for it. A fake that reported the * boundary at the moment it was *scheduled* would make every A–B loop look * instantaneous — and, since the engine's `stopped` guard only knows about the * user's `stop()`, would read as the buffer running out, advancing the queue the * instant a loop was armed. A bare `stop()` still fires immediately: that is the * tear-down every existing store test waits on; * - `currentTime` only moves when a test says so, which makes every position * assertion a statement about the audio clock rather than about wall time. * * The fetch stub answers `/rest/stream` with the requested URL as the bytes, so * `decodeAudioData` can decide per container (raw / flac / ogg / mp3) and the * engine never has to know it is being watched. */ import { vi } from "vitest"; import type { AudioBufferLike, AudioContextLike, AudioNodeLike, AudioParamLike, AudioSourceNodeLike, AudioWorkletNodeLike, GainNodeLike, ShifterHandle, } from "../lib/player/engine"; /** * What may be connected to. * * `AudioNodeLike` is structural, so any object carrying `connect`/`disconnect` satisfies it — including * a wrapper *around* a node, which is exactly what a real `BaseAudioContext` refuses to connect * ("Overload resolution failed") and precisely what the shifter's handle once was. A fake graph that * accepts anything therefore lets the whole feature look green while it throws in every browser, which * is not a hypothetical: it is how the pitch control shipped dead. So the fake graph has the same rule * as the real one, and a test that wires a facade into the chain fails here instead. */ const FAKE_AUDIO_NODE = Symbol.for("hackermusic.fakeAudioNode"); export type FakeAudioNode = AudioNodeLike & { readonly [FAKE_AUDIO_NODE]: true }; export function isFakeAudioNode(value: unknown): value is FakeAudioNode { return ( typeof value === "object" && value !== null && (value as Record)[FAKE_AUDIO_NODE] === true ); } function wiredTo(value: unknown, from: string): void { if (!isFakeAudioNode(value)) { throw new TypeError( `${from}: connected to something that is not an audio node — the real graph would throw here too`, ); } } function fakeNode( kind: string, ): FakeAudioNode & { kind: string; connects: number; disconnects: number } { return { [FAKE_AUDIO_NODE]: true, kind, connects: 0, disconnects: 0, connect() { this.connects++; }, disconnect() { this.disconnects++; }, }; } export class FakeSourceNode implements AudioSourceNodeLike { buffer: AudioBufferLike | null = null; /** * The deck's speed, as the engine left it. A plain `{ value }` rather than a param with * automation: the engine writes the rate once at arm time and the store changes speed by * building a new source, so nothing here has to model a ramp — and a test that caught the * engine automating a live node would be reporting a bug, not a feature. */ playbackRate: AudioParamLike = { value: 1 }; onended: (() => void) | null = null; /** one entry per start() — length > 1 is impossible, by design */ started: { when: number; offset: number }[] = []; stopped = false; /** * The `when` a scheduled `stop(when)` was given, until the clock reaches it. * Kept after firing too, because a test asserting *where* a boundary was placed * wants to read the number whether or not it has been heard yet. A second stop() * pulls it earlier, as the browser's does — which is how a pass armed ahead of a * boundary shows up as `stopAt <= startedAt`: taken out of the air before it began. */ stopAt?: number; /** `onended` has been delivered; a second one would be a lie about the browser */ ended = false; connects = 0; disconnects = 0; /** the clock the node's context is running, so a stop due in the past is immediate */ private readonly clock: () => number; constructor(clock: () => number = () => 0) { this.clock = clock; } readonly [FAKE_AUDIO_NODE] = true as const; connect(destination: AudioNodeLike): void { wiredTo(destination, "source"); this.connects++; } disconnect(): void { this.disconnects++; } start(when = 0, offset = 0): void { if (this.started.length > 0) { throw new Error("AudioBufferSourceNode can only be started once — build a new node"); } this.started.push({ when, offset }); } stop(when?: number): void { if (this.ended) return; // Browsers deliver `ended` after a stop() as well as after the buffer runs // out; keeping that here is the point. const at = when === undefined || !Number.isFinite(when) ? this.clock() : when; // A second stop() retargets the first and the earlier of the two wins, which is not // a detail: it is the only way a boundary already scheduled can be cancelled, so the // only way to see a pass armed ahead of one being abandoned rather than left to start. this.stopAt = Math.min(this.stopAt ?? Number.POSITIVE_INFINITY, at); this.stopped = true; // A stop scheduled for a moment the clock has already passed is not waiting for // anything, and the browser says so by firing at once. this.reach(this.clock()); } /** * The context's clock reached `now`: deliver a scheduled stop that is due. Called * from `FakeAudioContext.advance`, never by the code that asked for the stop — * that ordering is the whole difference between testing a boundary and testing a * claim about one. */ reach(now: number): void { if (this.ended || this.stopAt === undefined || now < this.stopAt) return; this.ended = true; this.onended?.(); } /** the buffer reached its end on its own */ finish(): void { if (this.ended) return; this.ended = true; this.onended?.(); } get startedAt(): number | undefined { return this.started[0]?.when; } get startOffset(): number | undefined { return this.started[0]?.offset; } } export interface FakeAudioOptions { /** containers the fake browser cannot decode, e.g. ["raw", "flac"] */ undecodable?: string[]; /** seconds reported for a stream, by substring of its URL (default 240) */ durationFor?: (url: string) => number; /** initial clock, so a test can start from a known position */ currentTime?: number; /** * The samples a stream decodes to, by URL — what the loop detector reads. * * A new option on the same constructor rather than a new fixture, for the same reason * `test/signal.ts` exists at all: what a test needs is *a track with a known answer*, * and a fixture mp3 in the repo could not say "the body repeats at exactly 20 s" as * legibly as a function can. Defaulted to silence, so that the tests which assert what * got *scheduled* keep asserting exactly that and pay for no waveform at all. */ waveformFor?: (url: string) => Float32Array | undefined; /** * Simulate the part of the spec that bites a byte cache: `decodeAudioData` * *takes* the ArrayBuffer it decodes — the browser detaches it, and every later * read of it sees zero bytes. Chrome does this for real; a cache that hands out * its only copy to the decoder therefore poisons itself on first use, which is * the failure this option exists to reproduce. The taking is modelled exactly * (a real transfer, not a zero-fill) because the shape of the bug — `byteLength` * going to 0 forever — is the whole thing under test. */ detaches?: boolean; /** * Hold the decoder open for a test: awaited once the fake knows the URL, before it * returns a buffer. `decodeAudioData` is the one stage of a cached load a synchronous * fake finishes before the test can look, so the state that exists only *while* the * decoder holds bytes already in hand — the prefetch window a warm row must wear as * cached, not as an empty bar — is otherwise impossible to catch. Give a test a promise * it resolves itself and the window stands still until it says otherwise. */ decodeDelay?: (url: string) => Promise; } export interface FakeGainNode extends GainNodeLike { readonly [FAKE_AUDIO_NODE]: true; gain: AudioParamLike & { value: number }; connects: number; disconnects: number; /** every destination it was wired to, in order — the graph shape a test can actually assert on */ readonly connections: string[]; } /** * A `AudioWorkletNode`, as far as the main thread can see one: a name, a parameter map, a port, and * the connect/disconnect counters a wiring assertion reads. `deliver` is how a test speaks *from* the * audio thread — the latency report is the only thing the real node says on its own. */ export class FakeWorkletNode implements AudioWorkletNodeLike { /** every destination it was connected to, in order, by `kind` */ readonly connections: string[] = []; readonly [FAKE_AUDIO_NODE] = true as const; disconnects = 0; /** everything the main thread posted at the audio thread, in order */ readonly sent: unknown[] = []; readonly parameters: { get(name: string): AudioParamLike | undefined }; port: { postMessage(message: unknown): void; onmessage: ((event: { data: unknown }) => void) | null; } = { postMessage: (message: unknown) => { this.sent.push(message); }, onmessage: null, }; // The DOM's shape, argument for argument — (context, name, options) — because the whole reason this // node went missing in every real browser was a fake that accepted a call the platform does not // make. It registers itself with the context the way the real constructor does, so a test reads // `context.worklets` and sees what was built. constructor( context: { worklets: FakeWorkletNode[] }, readonly name: string, readonly options: Record, private readonly params: Record = { ratio: { value: 1 } }, ) { this.parameters = { get: (name) => params[name] }; context.worklets.push(this); } connect(destination: AudioNodeLike & { kind?: string }): void { wiredTo(destination, "worklet node"); this.connections.push(destination.kind ?? "node"); } disconnect(): void { this.disconnects++; } /** what the ratio parameter holds right now */ get ratio(): number { return this.params.ratio?.value ?? Number.NaN; } /** speak from the audio thread */ deliver(data: unknown): void { this.port.onmessage?.({ data }); } } /** A `ShifterHandle` a test can hold: what the engine was asked to do to the pitch, and to the graph. */ export class FakeShifter implements ShifterHandle { connects = 0; disconnects = 0; ratio = 1; quality: string | null = null; disposed = false; /** what the node claims its delay is, in samples */ delay = 4096; /** the node the graph is wired to. The handle itself is deliberately *not* a node: see the brand. */ readonly node = fakeNode("shifter"); connect(destination: AudioNodeLike): void { wiredTo(destination, "shifter"); this.connects++; } disconnect(): void { this.disconnects++; } setRatio(ratio: number): void { this.ratio = ratio; } setQuality(quality: string): void { this.quality = quality; } latency(): number { return this.delay; } dispose(): void { this.disposed = true; } } export class FakeAudioContext implements AudioContextLike { static instances: FakeAudioContext[] = []; /** every context built since the last reset() — the live page has exactly one */ static reset(): void { FakeAudioContext.instances = []; } state: "suspended" | "running" | "closed" = "suspended"; currentTime: number; readonly sampleRate = 44100; readonly destination = fakeNode("destination"); readonly sources: FakeSourceNode[] = []; /** worklet modules the audio thread was asked to fetch, in order */ readonly modules: string[] = []; /** every worklet node built, in order */ readonly worklets: FakeWorkletNode[] = []; /** every gain the engine built: [0] is the master, then one per playback */ readonly gains: FakeGainNode[] = []; /** URLs handed to decodeAudioData, in order — including the refused ones */ readonly decodeRequests: string[] = []; /** URLs whose samples somebody actually asked for — i.e. the tracks the detector looked at */ readonly waveforms: string[] = []; resumes = 0; closes = 0; private readonly undecodable: string[]; private readonly durationFor: (url: string) => number; private readonly waveformFor?: (url: string) => Float32Array | undefined; private readonly detaches: boolean; private readonly decodeDelay?: (url: string) => Promise; constructor(options: FakeAudioOptions = {}) { this.currentTime = options.currentTime ?? 0; this.undecodable = options.undecodable ?? []; this.durationFor = options.durationFor ?? (() => 240); this.waveformFor = options.waveformFor; this.detaches = options.detaches ?? false; this.decodeDelay = options.decodeDelay; FakeAudioContext.instances.push(this); } /** * The audio clock only advances when a test moves it — and moving it is what * delivers scheduled stops, because that is who a schedule was made to. * * The delivery drains rather than making one pass: a browser whose tab was suspended * for a minute does not deliver one `ended` task and wait to be asked again, it queues * every stop that came due and runs them in order, including the ones whose callbacks * arm further sources. Stopping at the pass that is already in hand is the difference * between a fake that models a suspension and one that merely fast-forwards. The bound * is a broken-arm guard, not a policy: a callback that keeps arming nodes whose stops * are already due would otherwise spin here forever, and the loop's arm refuses a start * in the past precisely so that it cannot. */ advance(seconds: number): void { this.currentTime += seconds; for (let pass = 0; pass < 64; pass++) { // A snapshot per pass, not a live view: a boundary callback arms the next pass onto // the end of the list while this loop is running, and the new node must not be // handed a clock it was not armed against. const due = this.sources.filter((s) => !s.ended).slice(0, 1); const next = due.find((s) => s.stopAt !== undefined && s.stopAt <= this.currentTime); if (!next) return; next.reach(this.currentTime); } throw new Error(`advance(${seconds}): stops still coming due after 64 drains`); } resume(): Promise { this.resumes++; this.state = "running"; return Promise.resolve(); } close(): Promise { this.closes++; this.state = "closed"; return Promise.resolve(); } createBufferSource(): FakeSourceNode { const s = new FakeSourceNode(() => this.currentTime); this.sources.push(s); return s; } // a BaseAudioContext is itself an AudioNode in the spec, and the engine type // says so; nothing here connects one connect(): boolean { return true; } disconnect(): void {} createGain(): FakeGainNode { const gain = { value: 1, setTargetAtTime: (target: number) => { gain.value = target; }, }; const node: FakeGainNode = { [FAKE_AUDIO_NODE]: true, gain, connects: 0, disconnects: 0, connections: [], connect: (destination) => { wiredTo(destination, "gain"); node.connections.push((destination as { kind?: string }).kind ?? "node"); node.connects++; }, disconnect: () => { node.disconnects++; }, }; this.gains.push(node); return node; } /** * Present because the engine asks for it before it asks for anything else about the worklet, and * absent-and-ignored is the path a browser without one takes. `addModule` records rather than * fetches: there is no audio thread here, and the point of the record is *how many times* it was * asked. */ readonly audioWorklet = { addModule: async (url: string): Promise => { this.modules.push(url); }, }; async decodeAudioData(data: ArrayBuffer): Promise { // The stream stub hands back the requested URL as the bytes, which is how // the fake knows what container it is being asked to decode. Anything else // (an engine test with an opaque ArrayBuffer) decodes as an ordinary file. const text = new TextDecoder().decode(new Uint8Array(data)); const isStream = /^https?:\/\//.test(text); if (isStream) this.decodeRequests.push(text); const container = isStream ? containerOf(text) : "raw"; if (this.undecodable.includes(container)) { throw new DOMException(`cannot decode ${container}`, "EncodingError"); } // The refused decodes answer immediately — only a decode that will succeed is // worth holding, which is the whole point: to stand still inside a real load. if (isStream && this.decodeDelay) await this.decodeDelay(text); const duration = this.durationFor(isStream ? text : ""); const url = text; if (this.detaches && data.byteLength > 0) { // The taking, modelled with a real transfer rather than a zero-fill: the // point is that the caller's buffer goes to 0 bytes forever, which is // exactly what the warm cache must not hand over. If the environment // cannot transfer, the test asking for this says so loudly instead of // quietly passing on a decoder that never took anything. structuredClone(data, { transfer: [data] }); } // Lazily, and memoised per buffer: a four-minute track is 42 MB of floats, the tests // that ask what got scheduled never look at a sample, and two plays of one track // decode it twice. let waveform: Float32Array | null = null; const samples = () => { if (!waveform) { waveform = this.waveformFor?.(url) ?? silence(Math.round(this.sampleRate * duration)); this.waveforms.push(url); } return waveform; }; // The url rides along on the buffer, because once a boundary is pre-armed a // test can no longer say "the source": two are armed at once, and which one // belongs to which track is exactly the thing being asserted. Named rather // than inline so the extra property is declared, not an excess literal. const buffer: AudioBufferLike & { url: string } = { duration, numberOfChannels: 2, sampleRate: this.sampleRate, url, // Both channels answer with the one waveform, which is all a fake that holds a mono // signal can honestly do: the detector folds the channels by averaging, and a // signal averaged with itself is that signal. The fold is pinned against two // channels that differ, in detect.test.ts. getChannelData: () => samples(), }; return buffer; } /** the source the engine armed most recently */ get lastSource(): FakeSourceNode | undefined { return this.sources[this.sources.length - 1]; } /** * The source armed for one track's stream — the most recent one, if the track * was played twice. With pre-armed boundaries, `lastSource` may be the * *successor*, so tests that mean "the source for track s1" must say so. */ sourceFor(id: string): FakeSourceNode | undefined { const hits = this.sourcesFor(id); return hits[hits.length - 1]; } /** every source ever armed for that track's bytes, in arm order */ sourcesFor(id: string): FakeSourceNode[] { return this.sources.filter((s) => { const url = (s.buffer as { url?: string } | null)?.url ?? ""; if (!url.includes("/rest/stream")) return false; // the query param, not a substring: `id=s1` is inside `id=s12` return new URL(url).searchParams.get("id") === id; }); } } /** "raw" when no format was requested, else the container asked for. */ export function containerOf(url: string): string { const format = new URL(url).searchParams.get("format"); return format ?? "raw"; } /** * The waveform a decode answers with when the test did not bring one. * * Shared per length rather than made per buffer: the default is what the ~40 tests that * only ask what got *scheduled* land on, they all decode 240-second tracks, and 42 MB of * zeroes per decode would be the largest thing in the suite for a signal nobody reads. */ const SILENCE = new Map(); export function silence(samples: number): Float32Array { let hit = SILENCE.get(samples); if (!hit) { hit = new Float32Array(samples); SILENCE.set(samples, hit); } return hit; } export interface StreamFetchStub { /** stream URLs requested, in order */ urls: string[]; /** requests held back until the test releases them (for superseded loads) */ pending: { url: string; release: () => void }[]; /** stream requests whose AbortSignal fired */ aborted: string[]; fetch: typeof globalThis.fetch; } /** * Serve `/rest/stream` from memory; everything else goes to `base` (usually * `navidromeFetch`). Non-2xx for a stream is configurable because the 404 path * is a real one — a song id that has since left the server. */ export function stubStreamFetch( opts: { delay?: boolean; status?: number; /** what answers everything that is not a stream — usually navidromeFetch(...) */ base?: (input: RequestInfo | URL, init?: RequestInit) => Promise; } = {}, ): StreamFetchStub { const urls: string[] = []; const pending: { url: string; release: () => void }[] = []; const aborted: string[] = []; const status = opts.status ?? 200; const impl = async (input: RequestInfo | URL, init?: RequestInit): Promise => { const url = String(input); if (!url.includes("/rest/stream")) { if (!opts.base) throw new Error(`unhandled url ${url}`); return (await opts.base(input, init)) as Response; } urls.push(url); const signal = init?.signal ?? null; if (opts.delay) { await new Promise((resolve, reject) => { pending.push({ url, release: () => { resolve(); const at = pending.findIndex((p) => p.url === url); if (at >= 0) pending.splice(at, 1); }, }); signal?.addEventListener( "abort", () => { aborted.push(url); reject(new DOMException("Aborted", "AbortError")); }, { once: true }, ); }); } if (status !== 200) { return { ok: false, status, headers: new Headers(), arrayBuffer: async () => new ArrayBuffer(0), } as unknown as Response; } // The URL *is* the body, so the fake decoder can see what was asked for. const bytes = new TextEncoder().encode(url); return { ok: true, status: 200, // Headers, because a response without them is a fixture that only half-answers: the // playback trace reads the served type and length off them, and a test that turns the // trace on would otherwise be asserting against a response no server could send. headers: new Headers({ "content-type": "audio/flac", "content-length": String(bytes.byteLength), }), arrayBuffer: async () => bytes.buffer.slice(0), } as unknown as Response; }; return { urls, pending, aborted, fetch: vi.fn(impl) as unknown as typeof globalThis.fetch }; } /** Reset for the next test: no contexts, no leaked position tickers. */ export function resetAudioWorld(): void { FakeAudioContext.reset(); } /** * The passes that were left alone long enough to make a sound: armed on the clock, and not * cut short at or before their own start. A bounded node carries a `stopAt` from the moment * it is armed, so `stopped` says nothing about whether anything was heard — and a pass the * transport abandoned before it began (a region moved, a pause pressed) has a `stopAt` * behind its `startedAt`. Counting one of those as a pass is how a test comes to report a * hole in the seam that nobody heard, or a loop that outlived its own clearing. */ export function soundingPasses(ctx: FakeAudioContext, id: string): FakeSourceNode[] { return ctx .sourcesFor(id) .filter((s) => s.startedAt !== undefined && s.stopAt !== undefined && s.stopAt > s.startedAt); }