Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179/** * The main thread's half of the pitch shifter: build the worklet node, feed it, and know its delay. * * Split from `shift.processor.ts` because the two halves live on different threads and only one of * them can be imported by anything that also wants to be a test: the processor runs where jsdom has * never been, and the DOM's `AudioWorkletNode` runs where a worklet has never been asked for. What * is between them — the URL of the module, the name it registered itself under, the one parameter and * the two messages — is this file, and it is deliberately too dumb to be wrong. * * Importing the processor with `?worker&url` is what makes this work in a build: Vite bundles that * module together with its imports (this file's `./shift` import included, which is the whole point — * the shifter's DSP ships once and runs on either side of the thread boundary) and hands back a URL * the audio thread can fetch. A plain `new URL("./x.ts", import.meta.url)` would copy the file and * leave its import specifier pointing at nothing. */import type { AudioContextLike, AudioParamLike, AudioWorkletNodeLike, ShifterHandle,} from "./engine";import type { ShiftQuality } from "./shift";import processorUrl from "./shift.processor.ts?worker&url";
/** The name `shift.processor.ts` called `registerProcessor` with. Both sides have to agree. */export const SHIFTER_PROCESSOR = "hackermusic-pitch";
interface LatencyReport { type?: string; samples?: number;}
/** * The script the audio thread is handed, as one self-contained file. * * `addModule` evaluates its argument **in the audio thread's own global scope**, which has no module * loader worth the name and no `document` to hand one. So the script has to be alone in the world: * one file, no imports. The build already gives us that — the bundler inlines the DSP into the * emitted worker chunk and wraps it in an IIFE — and the check below passes it straight through. * * The dev server does not. It serves worker files as ES modules, and not merely ours: it puts an * `import` of its own HMR client first, a module that reaches for a `document` the audio thread does * not have, and puts an `import` of `./shift.ts` second. Evaluated where a worklet is evaluated, the * file throws before it registers anything, and until the module arrives the pitch control is simply * absent — the deck still plays, the readout still moves, and nothing says so. That is what this is * for. It fetches the entry, resolves the handful of same-origin imports the dev server emitted, and * hands over their concatenation with the `export` keywords removed: one script, no imports, which * is correct whichever way a given browser happens to evaluate a worklet module. * * Only root-relative specifiers are followed, and anything under `node_modules` is dropped: that is * the dev server's own client, and there is nothing in it a thread without a DOM can use. * * Exported for the test, which is the one place the two shapes it has to survive can be shown side by * side. Nothing in the app imports it; `createShifterNode` is the only caller. */export async function workletScript(entry: string): Promise<string> { const seen = new Set<string>(); const load = async (at: string): Promise<string> => { const key = new URL(at, location.href).href; if (seen.has(key)) return ""; seen.add(key); const deps: string[] = []; const body = (await (await fetch(key)).text()) // One import statement, matched to its specifier: named, default, namespace or bare, on one // line or several. Everything the dev server puts in front of a worker file is one of these. .replace(/^[ \t]*import\b[\s\S]*?["']([^"']+)["'];?[ \t]*$/gm, (_all, spec: string) => { if (!/^\/(?!\/)/.test(spec) || spec.includes("/node_modules/")) return ""; deps.push(spec); return ""; }) .replace(/^[ \t]*export[ \t]+default[ \t]+/gm, "const __worklet_default = ") .replace(/^[ \t]*export[ \t]+/gm, ""); const resolved = (await Promise.all(deps.map(load))).filter(Boolean).join("\n"); // Dependencies first: the entry references what they declare, and a script is read top to bottom. return resolved === "" ? body : `${resolved}\n${body}`; }; return load(entry);}
/** * The one place the delay is turned into a number the interface can use. * * The node reports it rather than the main thread computing it from the preset, because the DSP can * change it from under us: a wider search is part of the delay, and how wide the search has to be * depends on how far the pitch has moved. Anything that guessed from the window length would be a * few milliseconds wrong at the extremes, which is the amount of pulse error a listener does notice. */export async function createShifterNode( context: AudioContextLike, quality: ShiftQuality,): Promise<ShifterHandle | null> { const worklet = context.audioWorklet; // The constructor, not a factory: `AudioContext` has no `createWorkletNode`, and asking for one is // how this file used to decide — quietly, in every browser, on every attempt — that there was no // worklet here. Read off `globalThis` rather than as a bare name because the environments that have // to answer this question without a DOM (a test, a server render) need a way to say no. const Construct = globalThis.AudioWorkletNode; if (!worklet || typeof Construct !== "function") return null; // One module per context: `addModule` is not free, and a context outlives every shift the page // will ever make. The URL is fetched rather than handed over, for the reason on `workletScript`. const source = await workletScript(processorUrl); const moduleUrl = URL.createObjectURL(new Blob([source], { type: "text/javascript" })); try { await worklet.addModule(moduleUrl); } finally { // `addModule` has finished fetching by the time it settles, in either direction it settles, and a // blob URL outlives the page that made it otherwise. URL.revokeObjectURL(moduleUrl); } // Built the way the platform builds one: the context is the first argument, not the receiver of a // method. The double cast is the engine's structural `AudioContextLike` meeting the DOM's nominal // `BaseAudioContext` — the object that arrives here *is* the context the engine made, whatever // shape it happened to be described in. const node = new (Construct as unknown as new ( ctx: BaseAudioContext, name: string, options: AudioWorkletNodeOptions, ) => AudioWorkletNodeLike)(context as unknown as BaseAudioContext, SHIFTER_PROCESSOR, { numberOfInputs: 1, numberOfOutputs: 1, channelCount: 2, channelCountMode: "explicit", outputChannelCount: [2], processorOptions: { quality }, });
const ratio = node.parameters.get("ratio"); let samples = 0; node.port.onmessage = (event: { data: unknown }) => { const report = event.data as LatencyReport | null; // Negative and non-numeric reports are refused rather than clamped: a delay of zero is a pulse // painted ahead of the sound, which is the exact wrongness this number exists to prevent, and a // thread that says something impossible is better answered by the last thing it said that was // not impossible. if ( report?.type === "latency" && typeof report.samples === "number" && Number.isFinite(report.samples) && report.samples >= 0 ) { samples = report.samples; } }; // The ratio travels both ways on purpose: the parameter is the route that lands on the audio clock, // and the message is the route that still works on an engine that came up without the descriptor. // The delay is not asked for at all — the node announces it from inside its own render loop, because // until it is wired into a graph there is no thread running to answer a request. See // `reportIfChanged` in the processor. node.port.postMessage({ type: "ratio", value: ratio?.value ?? 1 });
return { // The node, for the input side of the graph: the engine puts *this* into the master, and asks the // handle to reach the destination with `connect` below. A wrapper is not an AudioNode, and the // browser is right to say so. node, connect: (destination) => node.connect(destination), disconnect: () => node.disconnect(), setRatio(next: number) { if (!Number.isFinite(next) || next <= 0) return; if (ratio) ratio.value = next; // Both routes, always. The parameter is the one that lands on the audio clock; the message is // the one that works when the node came up without the descriptor — and posting both is cheaper // than a test for which browser this is, which is the kind of thing that rots. node.port.postMessage({ type: "ratio", value: next }); }, setQuality(next: ShiftQuality) { node.port.postMessage({ type: "quality", quality: next }); }, latency: () => samples, dispose() { node.port.onmessage = null; node.disconnect(); }, };}
/** Re-exported so a test can name the parameter without reaching into the processor. */export type { AudioParamLike };