Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { FakeAudioContext, FakeWorkletNode } from "../../test/audio";import { createShifterNode, SHIFTER_PROCESSOR, workletScript } from "./shift-node";
/** * The text the bundler and the dev server hand back for `?worker&url`, faked to the two shapes that * exist. `workletScript` is the part of this file that could be wrong without anything thrown, so it * gets the assertions: whatever comes out of it has to be one script with nothing left to fetch, and * the dev server's shape — an ES module, with its own HMR client as the first import — is the case * that was silently killing the feature. */const DSP = `export const SHIFT_QUALITIES = ["crisp"];export function createShifter() { return { setRatio() {}, setQuality() {}, reset() {}, latency() { return 4096; } }; };`;const ENTRY_AS_BUILT = `(function(){ class P {} registerProcessor("hackermusic-pitch", P); })();\n`;const ENTRY_AS_SERVED = `import "/node_modules/.pnpm/vite@8/dist/client/env.mjs";import { createShifter } from "/src/lib/player/shift.ts";class P { constructor() { this.shifter = createShifter(); }}registerProcessor("hackermusic-pitch", P);`;
/** Serve `?worker&url` (and anything it imports) out of the page rather than out of a server. */function stubSource(table: Record<string, string>) { const blobs: Blob[] = []; vi.stubGlobal("fetch", async (input: unknown) => { const at = String(input); const hit = Object.keys(table).find((key) => at.includes(key)); if (!hit) throw new Error(`the test has no source for ${at}`); return { text: async () => table[hit]! }; }); void blobs; return table;}
beforeEach(() => { stubSource({ "shift.processor": ENTRY_AS_BUILT, "player/shift.ts": DSP }); // The node is constructed, not manufactured by the context — the only way this file can be run at // all outside a DOM, and the reason the fake takes (context, name, options) like the real thing. vi.stubGlobal("AudioWorkletNode", FakeWorkletNode);});
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks();});
/** * The main thread's half of the worklet, against a fake that records instead of rendering. * * There is no audio thread in jsdom, so nothing here can say the DSP arrived and started: that claim * belongs to `shift.test.ts`, which runs the DSP itself, and to the browser. What is under test is * the *contract across the boundary* — that the module is fetched once, that the ratio travels as a * parameter rather than a message, that the delay the node reports is the delay the handle reports, * and that letting go of the handle lets go of the node. * * Those four are exactly the things that fail in a way nobody hears until a week later: a module * fetched per press, a shift that only takes effect on the next play, a pulse a frame late. */
it("fetches the processor once per context and asks for it by the name it registered", async () => { const ctx = new FakeAudioContext(); const handle = await createShifterNode(ctx, "balanced"); expect(handle).not.toBeNull(); expect(ctx.modules).toHaveLength(1); // A blob URL and not the bundler's: `addModule` evaluates in the audio thread's global scope, and // what it is handed has to be one self-contained script — see `workletScript`. expect(ctx.modules[0]).toMatch(/^blob:/); expect(ctx.worklets[0]!.name).toBe(SHIFTER_PROCESSOR);});
it("hands the audio thread one script, whatever the bundler's answer looked like", async () => { // The dev server's shape, which is the one that broke: a module, importing Vite's HMR client (a // module that wants a `document` the audio thread does not have) and importing our DSP from a // root-relative URL nothing on the audio thread can resolve. Handed over as it came, the file // threw before it registered anything, the load was caught, and the pitch control vanished without // a word — which is the failure mode this test exists to keep visible. stubSource({ "shift.processor": ENTRY_AS_SERVED, "player/shift.ts": DSP }); const script = await workletScript("/src/lib/player/shift.processor.ts?worker&url"); // One script, nothing left to fetch: no imports of any kind, and no `export` for a classic script // to trip over — while the code those exports were attached to is still there, undeclared and // reachable, which is the whole point of stripping the keyword rather than the line. expect(script).not.toMatch(/^\s*(import|export)\b/m); expect(script).not.toContain("node_modules"); expect(script).toContain("function createShifter"); expect(script).toContain("registerProcessor"); // And it is a script, in the sense that the thread can compile it. expect(() => new Function(script)).not.toThrow();});
it("takes the built bundle as it stands, and lets go of the blob either way", async () => { stubSource({ "shift.processor": ENTRY_AS_BUILT }); expect(await workletScript("/src/lib/player/shift.processor.ts?worker&url")).toBe(ENTRY_AS_BUILT); // pass-through: the built chunk has nothing to resolve, and rewriting it would be the risk with no // reward — the production path is the one a listener is on. const ctx = new FakeAudioContext(); await createShifterNode(ctx, "balanced"); expect(ctx.modules[0]).toMatch(/^blob:/);});
it("hands the ratio to the parameter, and everything else to the port", async () => { const ctx = new FakeAudioContext(); const handle = (await createShifterNode(ctx, "balanced"))!; const node: FakeWorkletNode = ctx.worklets[0]!;
handle.setRatio(2); // The parameter is the route that lands on the audio clock, and that is the claim worth making: a // shift that reached the thread only by message would take effect a block late at best and a whole // scheduling round-trip at worst. expect(node.ratio).toBe(2); // The port carries the same number beside it, on purpose: an engine that came up without the // parameter descriptor needs that route, and posting to both is cheaper than detecting which // browser this is — the kind of test that outlives the browser it was written against. expect(node.sent).toContainEqual({ type: "ratio", value: 2 });
handle.setQuality("smooth"); expect(node.sent).toContainEqual({ type: "quality", quality: "smooth" });
// Junk is refused rather than passed on: a ratio of 0 is not silence, it is a stream that stops // arriving at the other end of a delay line, and the DSP's own clamp would only hide the ask. const before = node.ratio; handle.setRatio(0); handle.setRatio(Number.NaN); expect(node.ratio).toBe(before);});
it("reports the delay the node claimed, and nothing at all before it claims one", async () => { const ctx = new FakeAudioContext(); const handle = (await createShifterNode(ctx, "balanced"))!; const node: FakeWorkletNode = ctx.worklets[0]!;
// Nothing is asked for at construction — a node that is not wired into a graph has no thread to // answer, which is the ordering this used to get wrong — and the handle is 0 until the thread says // otherwise. expect(node.sent).not.toContainEqual({ type: "latency" }); expect(handle.latency()).toBe(0); node.deliver({ type: "latency", samples: 4096 }); expect(handle.latency()).toBe(4096);
// The re-tune moves the delay, and the node gets to say by how much — a window length guessed at // on this side would be wrong by the search range at the extremes. node.deliver({ type: "latency", samples: 8192 }); expect(handle.latency()).toBe(8192);
// Junk from the thread is refused rather than trusted: a negative delay would be the pulse painted // ahead of the sound, which is the failure this number exists to prevent. node.deliver({ type: "latency", samples: -5 }); // ^ refused, not clamped to zero: an uncompensated pulse is the wrongness being guarded against. node.deliver({ type: "latency", samples: "lots" }); node.deliver({ type: "unrelated" }); expect(handle.latency()).toBe(8192);});
it("letting go of the handle takes the node out of the graph", async () => { const ctx = new FakeAudioContext(); const handle = (await createShifterNode(ctx, "balanced"))!; const node: FakeWorkletNode = ctx.worklets[0]!; handle.connect(ctx.destination); expect(node.connections).toEqual(["destination"]);
handle.dispose(); expect(node.disconnects).toBeGreaterThan(0); // Nothing is left listening on a port whose thread may still be running: a handler kept alive holds // the closure, and the closure holds whatever the graph asked it to remember. expect(node.port.onmessage).toBeNull();});
it("a browser with no worklet in it gets no shifter, and no exception", async () => { // The two ways this can be missing, separated, because they are different stories: a context that // never got an audio worklet, and a DOM with no node constructor to ask. Both have to answer "no // pitch control" rather than throw, and neither is allowed to look like the other in a log. const ctx = new FakeAudioContext(); delete (ctx as unknown as { audioWorklet?: unknown }).audioWorklet; await expect(createShifterNode(ctx, "balanced")).resolves.toBeNull();
const other = new FakeAudioContext(); vi.stubGlobal("AudioWorkletNode", undefined); await expect(createShifterNode(other, "balanced")).resolves.toBeNull(); expect(other.modules).toHaveLength(0); // refused before fetching anything});