/** * The audio thread's half of the pitch shifter. * * Loaded with `audioWorklet.addModule`, so it runs on the rendering thread beside the graph rather * than on the main thread beside the reactive system: a shift that dropouts when the page is busy * scrolling a library is worse than no shift, and this is the only place in the app where the * distinction is not cosmetic. * * It is a wrapper and nothing more. Every decision about *how* to shift lives in `shift.ts`, which * is pure, runs on either side, and is measured in `shift.test.ts` — a worklet cannot be tested * from jsdom, which is precisely why no DSP lives here. What this file owns is the plumbing a * worklet needs and a pure module cannot have: the quantum-shaped handshake with the graph, the one * parameter that crosses the thread boundary, and the report of what the delay turned out to be. * * It is bundled, so the import of `shift.ts` is allowed — Vite inlines it into this file when the * module is asked for with `?worker&url`, and the worklet never sees a second request. See * `shift-node.ts`, which is the main-thread half that knows the URL. */ import { createShifter, type ShiftQuality } from "./shift"; /** What the main thread is allowed to say to us. */ interface Command { type: "quality" | "reset" | "ratio"; quality?: ShiftQuality; value?: number; } class PitchShifterProcessor extends AudioWorkletProcessor { /** * The shift, as a frequency ratio, at k-rate. * * K-rate rather than a-rate because the shifter applies a ratio per *frame*, not per sample: an * a-rate param would be read once per quantum anyway, and asking for 44 100 automation points a * second to be ignored is not a cheaper lie, just a different one. A key change therefore lands * at the next frame boundary, which is what a fader being released sounds like, and what a * difference of one semitone between two quanta would not be. */ static get parameterDescriptors(): AudioParamDescriptor[] { return [ { name: "ratio", defaultValue: 1, minValue: 0.05, maxValue: 20, automationRate: "k-rate" }, ]; } private readonly shifter; private readonly scratch: Float32Array[]; private lastRatio = 1; constructor(options?: AudioWorkletNodeOptions) { super(); const channels = Math.max(1, options?.outputChannelCount?.[0] ?? options?.numberOfOutputs ?? 2); this.shifter = createShifter({ channels, quality: options?.processorOptions?.quality }); this.scratch = []; for (let c = 0; c < channels; c++) this.scratch.push(new Float32Array(128)); this.port.onmessage = (event: MessageEvent) => { const message = event.data; if (!message || typeof message !== "object") return; if (message.type === "quality" && message.quality) this.shifter.setQuality(message.quality); else if (message.type === "reset") this.shifter.reset(); // The ratio, by the other route: see `process`, which explains why there are two. else if (message.type === "ratio" && typeof message.value === "number") this.shifter.setRatio(message.value); }; } /** The delay the interface is told about, and `-1` for "not told yet" — no real delay is negative. */ private reported = -1; /** * The delay is the module's business, but the *interface* has to know it: the bar moves its pulse * by this number, and the only entity that can measure it is the thing holding the rings. * * Announced from `process` rather than sent on request, and that ordering is the whole point. A * node that exists but is not yet wired into the graph is not pulled, and a node that is not pulled * has no audio-thread event loop running to answer a message — so a report asked for at construction * is a reply that arrives never, or whenever the graph is eventually built, which in this app is a * few awaits later. Reporting on change from inside `process` costs one integer comparison a quantum * and cannot be missed: the first moment the node is rendering is the first moment anybody is owed a * number, and every re-tune changes the number and so re-announces itself. */ private reportIfChanged(): void { const latency = this.shifter.latency(); if (latency === this.reported) return; this.reported = latency; this.port.postMessage({ type: "latency", samples: latency }); } process( inputs: Float32Array[][], outputs: Float32Array[][], parameters: Record, ): boolean { const input = inputs[0]; const output = outputs[0]; if (!output || output.length === 0) return true; this.reportIfChanged(); // The parameter, if this browser gave us one. `parameters` is keyed by the names in // `parameterDescriptors`, and an engine that failed to build them hands back an empty object — // which is why the fallback below exists and why this reads as "if there is a param" rather than // "read the param, default 1": defaulting a missing parameter to 1 every quantum would undo the // ratio the port just set, and the feature would be silent in exactly the browser that needs the // other route. const param = parameters.ratio; if (param && param.length > 0) { const ratio = param[0]!; if (ratio !== this.lastRatio) { this.shifter.setRatio(ratio); this.lastRatio = ratio; } } const frames = output[0]!.length; // Time outside, channels inside, in that order: the shifter's clock advances by a *block* — one // timeline with a row per channel — so a quantum bigger than the render quantum has to be fed as // several complete blocks rather than as one channel finished before the next begins. // // The buffers are reused for the life of the node, because this runs every quantum and an // allocation per quantum is how an audio thread earns its glitches. 128 is the render quantum in // every browser that implements this API; the loop simply takes more passes over it if a bigger // one ever arrives. const quantum = this.scratch[0]!.length; for (let at = 0; at < frames; at += quantum) { const take = Math.min(quantum, frames - at); for (let c = 0; c < this.scratch.length; c++) { const row = this.scratch[c]!; const source = input?.[c]; for (let i = 0; i < take; i++) row[i] = source?.[at + i] ?? 0; this.shifter.write(c, row.subarray(0, take)); } const out = this.scratch.map((row) => row.subarray(0, take)); this.shifter.read(out); for (let c = 0; c < output.length; c++) { const row = output[c]; const from = this.scratch[c]; if (!row || !from) continue; row.set(from, at); } } return true; } } registerProcessor("hackermusic-pitch", PitchShifterProcessor);