Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532/** * Pitch without tempo: shift the pitch of a live stream and hand back exactly the same duration. * * This is the half of the feature the browser will not do. `AudioBufferSourceNode` has no * `preservesPitch` (the property is `HTMLMediaElement`-only and the W3C thread declining to move it * here is from 2012), so a rate change moves pitch and pace together and there is nothing to switch * off. Everything in this file exists to undo that coupling: the source keeps playing at whatever * speed the deck is at, and this module shifts the pitch back — or away — while keeping the length * of what it heard. Which is also what makes it work under a loop: the boundary is scheduled on the * audio thread in *file* seconds, and a shifter that preserves duration leaves every one of those * seconds where the loop put them. * * ## How * * The classic two-stage shifter, streamed: * * **stage A — WSOLA time stretch by `ratio`** (`stretch.ts`-style overlap-add). Frames of `W` * samples, hop `W/2`, Hann on the frame as it is read so consecutive frames sum to a constant. Each new * frame's start is chosen by maximising the normalised cross-correlation between its first * `corr` samples and the tail of the frame before it, inside `±search` of the nominal position — * which is why a drum hit stays a drum hit instead of smearing into its neighbours: the frame is * placed *on* the transient, not across it. * * **stage B — resample by `ratio`.** Reading stage A back at step `ratio` shortens the duration * by `ratio` and raises the pitch by `ratio`, exactly undoing stage A's stretch on the clock and * leaving the pitch shifted. When `ratio > 1` this stage is a decimator, so it box-averages over * `ceil(ratio)` input samples first: skipping samples without filtering is how a pitch-up shifter * gets its aliasing. * * Net: duration unchanged, pitch ×`ratio`. Both stages run off the *same* frame positions for every * channel, so a stereo image does not wander between the ears. * * ## What it costs, and what it sounds like * * Latency is one analysis window (see `latency`), 23 ms to 93 ms depending on the preset: a shifter * has to see the frame before it can place it. The artefact is the WSOLA one — a mild warble on * long sustained tones, where consecutive copies of nearly-the-same-waveform are crossfaded with * slightly different alignment — and the presets are three tunings of that trade: a short window * follows transients closely and warbles more, a long window averages the warble away and blurs * transients. Nothing here is a phase vocoder, and the shimmer one of those gets is not the shimmer * the other gets; if the warble is the wrong artefact for this music the answer is a different * algorithm, not a different number in this one. * * At `ratio = 1` the module is a pass-through — Hann² overlap-add over a window that is summed with * its own half, box width 1 — which is transparent within float rounding rather than bit-exact, so * the engine bypasses this entirely whenever the shift is zero. See `player/engine.ts`. */
/** The three tunings the listener can choose, fastest-transient first in feel, longest in window. */export const SHIFT_QUALITIES = ["crisp", "balanced", "smooth"] as const;export type ShiftQuality = (typeof SHIFT_QUALITIES)[number];
export interface ShiftPreset { /** analysis window, samples. Also the latency: a frame has to arrive before it can be placed. */ window: number; /** how far either side of the nominal frame position the alignment may look, samples */ search: number; /** how much of the frame boundary the correlation is scored over, samples */ correlation: number; /** roughly how many coarse candidates the search tries before refining */ candidates: number;}
/** * The window lengths are 44.1 kHz numbers, so the latency each one costs is legible: crisp ≈ 23 ms, * balanced ≈ 46 ms, smooth ≈ 93 ms. The search is kept near a quarter of the window because WSOLA's * error grows with it — a wide search finds a *similar* frame that is not *the* frame, and that is * the warble getting worse rather than the transient getting sharper. */export const SHIFT_PRESETS: Record<ShiftQuality, ShiftPreset> = { // Short frame: a kick stays a kick. Sustained strings get the most warble of the three. crisp: { window: 1024, search: 192, correlation: 256, candidates: 24 }, // The middle of the road, and the one to reach for first on mixed material. balanced: { window: 2048, search: 384, correlation: 384, candidates: 24 }, // Long frame: the warble averages out and held tones go glassy-smooth, at the price of smearing // a transient over half a frame and 93 ms of delay. smooth: { window: 4096, search: 640, correlation: 512, candidates: 32 },};
/** ±24 semitones: two octaves each way, and the ratio range that says. */export const KEY_MIN = -24;export const KEY_MAX = 24;
/** Semitones to a frequency ratio. Exact at the octaves, which is the point of `2 **`. */export function ratioForSemitones(semitones: number): number { return 2 ** (semitones / 12);}
/** * Clamped, finite, and rounded to the semitone the interface promises. * * Rounding here rather than at each caller: this is the one place that knows what a legal shift is, * and a shifter fed 3.7 semitones would be a shifter whose tuning no key on the keyboard asked for. */export function clampKey(semitones: number): number { if (!Number.isFinite(semitones)) return 0; return Math.min(KEY_MAX, Math.max(KEY_MIN, Math.round(semitones)));}
export interface ShifterOptions { channels?: number; quality?: ShiftQuality; /** override the preset; for the tests that want a window small enough to assert against */ preset?: Partial<ShiftPreset>;}
export interface Shifter { /** * The ratio to shift by right now, as a frequency multiple (not semitones — the engine adds the * key, the lock and the speed together and hands over one number). * * Effective from the next frame: a frame already in flight keeps the ratio it started with, so a * change during a sustained note glides across one window instead of stepping inside it. */ setRatio(ratio: number): void; /** re-tune the window, search and correlation. Clears nothing; the stream carries on. */ setQuality(quality: ShiftQuality): void; ratio(): number; quality(): ShiftQuality; /** * Output delay in samples, in the file's own sample rate — to within a few milliseconds, which is * the accuracy anything downstream can use. * * The pulse in the bar reads this: the flash is painted from the playhead, and the playhead is the * audio thread's position, which is now this far ahead of what the listener is hearing. A frame * has to be seen before it can be placed, so the delay is the window, plus the search that hangs * off the end of it, plus a hop of output kept in hand; the exact figure lands a few tens of * samples either side of that, which is a tenth of a millisecond of pulse error and the reason the * number is specified as an approximation rather than promised as one. */ latency(): number; /** one block of input for one channel. `length` must be the same every call, and every channel of * a block must be written before the next `read` — the block is what the clock advances by. */ write(channel: number, samples: Float32Array): void; /** * Fill `out[ch]` with `out[ch].length` output samples, producing whatever the pipeline can. * * Short of that — during the initial window's worth of fill, and only then — the remainder is * silence, which is what makes `latency` the number it is. */ read(out: Float32Array[]): void; /** Put the stream back to empty, as if the track had just started. */ reset(): void;}
const hann = (n: number, window: number): number => 0.5 * (1 - Math.cos((2 * Math.PI * n) / window));
function pow2AtLeast(n: number): number { let p = 1; while (p < n) p <<= 1; return p;}
export function createShifter(options: ShifterOptions = {}): Shifter { const channels = Math.max(1, Math.floor(options.channels ?? 2)); let quality: ShiftQuality = options.quality ?? "balanced"; let preset: ShiftPreset = { ...SHIFT_PRESETS[quality], ...options.preset };
// Ring sizes are powers of two so the wrap is a mask: this runs on the audio thread, and a // modulo per sample is a division per sample there. One size for all three rings, big enough for // the widest gap any stage can have from its neighbour: stage B reads `ratio` samples per output // sample, so at +24 semitones it can be four times as far behind stage A as stage A is behind the // input. const size = pow2AtLeast(preset.window * 16); const mask = size - 1; /** how much un-consumed output the pipeline will hold before it stops producing: the backlog is * the latency, and a backlog with no ceiling is a stall that grows without limit */ const backlog = preset.window * 2;
/** windowed frames of input, one ring per channel, read at stage-A's frame positions */ let input: Float32Array[] = []; /** stage A's overlap-added output, one ring per channel, read by stage B */ let stretched: Float32Array[] = []; /** stage B's output: what `read` consumes, and the reason the delay exists at all */ let produced: Float32Array[] = []; let win = new Float32Array(0); /** * The overlap-add sums to this rather than to 1, because the alignment moves frames by up to the * search range and a window that is exactly COLA at its nominal spacing is not exactly COLA after * being shifted. Measured from the window in use — Hann at a 50 % overlap sums to 1 and the divide * is a no-op, but a future preset with a different hop would not be, and a constant gain nobody * can hear is exactly the kind of bug every later measurement of this module inherits. */ let ola = 1;
let ratio = 1; /** absolute input sample index the next written sample will hold, shared by every channel */ let inAbs = 0; /** * How many channel-writes of the current block have landed. The clock is the block's, not the * channel's — a stereo stream is one timeline with two rows — so `inAbs` advances when the last * row of the block arrives and not before. Counting this wrong is not a subtle bug: it makes the * input arrive twice as fast as the clock believes, and the first you hear of it is a stereo track * a fifth of an octave flat. */ let rows = 0; /** absolute stage-A sample index written so far (= hops × hop) */ let aAbs = 0; /** nominal position of the next stage-A frame, accumulated rather than derived from a hop count: * a ratio change mid-stream then cannot step the frame position, only change its slope */ let nominal = 0; /** integer position of the last frame used, which is what the correlation is aligned to */ let lastFrame = 0; /** absolute stage-A position the next output sample reads at */ let readPos = 0; /** absolute output sample index produced, and the one `read` has handed to the caller */ let outAbs = 0; let outRead = 0;
function build(): void { const w = preset.window; win = new Float32Array(w); for (let n = 0; n < w; n++) win[n] = hann(n, w); // The sum of the window across its own overlap — what an unshifted frame adds up to when the // next frame lands on top of it. let sum = 0; for (let n = 0; n < w / 2; n++) sum += win[n]! + win[n + w / 2]!; ola = sum / (w / 2); input = []; stretched = []; produced = []; for (let c = 0; c < channels; c++) { input.push(new Float32Array(size)); stretched.push(new Float32Array(size)); produced.push(new Float32Array(size)); } } build(); // Not just zeroes: the read position starts behind the head of the stream, which is the delay. reset();
function reset(): void { inAbs = 0; rows = 0; aAbs = 0; nominal = 0; lastFrame = 0; // Stage B starts `lag` output samples *behind* the output stream, which is the delay itself. // // This is the line the whole module hangs on, and the mistake it prevents is the one every // first attempt at this makes: anchoring the output position to the input position makes the // pipeline demand input it has not been given yet — output sample t needing input at t + lag, // which is the future — and the only thing a node built that way can ever return is silence. // Anchoring it behind instead, output t carries the content of t − lag, which is exactly what a // delay is, and every sample the graph asks for is answerable from what has already arrived. readPos = -lag() * ratio; outAbs = 0; outRead = 0; for (let c = 0; c < channels; c++) { input[c]!.fill(0); stretched[c]!.fill(0); produced[c]!.fill(0); } }
/** the ring sample at an absolute index, or 0 for anything the stream has not produced yet */ function at(ring: Float32Array, abs: number): number { return abs < 0 ? 0 : ring[abs & mask]!; }
function inputAvailable(upto: number): boolean { return inAbs >= upto; }
/** * The frame position for this hop: the nominal one, nudged to wherever the waveform agrees with * the frame before it. * * Scored as a normalised cross-correlation rather than a plain one — a plain dot product prefers * *loud* candidates, and a mix is loudest exactly where the transients are, so an unnormalised * search drifts toward the drum rather than toward the match. The tail's energy is constant for * the hop, so only the candidate's cost is paid per candidate. */ function align(from: number): number { const w = preset.window; const hop = w / 2; // Scored over no more than a hop: beyond that the comparison stops being a comparison of the two // halves that actually meet, and the aligner starts scoring regions that will never be summed. const corr = Math.min(preset.correlation, hop); const delta = search(); if (delta <= 1 || !canHop()) return from;
// Channel 0 decides, every channel obeys: two channels searching for themselves would find two // different matches and the image would sway between the speakers. const ref = input[0]!; // The previous frame's *second* half — the part the new frame is about to be summed onto. Not // its last `corr` samples, which is the obvious thing to write and wrong: at unison the new // frame's head lands exactly on that half, so that is the pair whose agreement has to be // measured, and comparing head against tail instead asks a question with no answer. Every // symptom of that one mistake was here at once — a pass-through decorrelated from its own input, // a level a few dB hot, and a pitch that wandered at the extremes. const tailFrom = lastFrame + hop; let tailEnergy = 0; for (let k = 0; k < corr; k++) { const s = at(ref, tailFrom + k); tailEnergy += s * s; } if (tailEnergy === 0) return from; // silence has no opinion; do not let it pick a winner
const score = (p: number): number => { let dot = 0; let energy = 0; for (let k = 0; k < corr; k++) { const s = at(ref, p + k); dot += s * at(ref, tailFrom + k); energy += s * s; } // Squared numerator over the product of energies: the same ranking as the true NCC, one // square root cheaper, and monotone where it matters (both energies are non-negative). // // Minus a pull back toward the nominal position, which is not cosmetic. A pure tone has a // correlation peak at every period of itself — fifty of them inside this search — all with // the same score, and an aligner with no tie-break picks whichever the coarse pass happened // to sample first. The frames then disagree about where the waveform is, the overlap sums add // constructively instead of reconstructing, and a track nobody has shifted comes out two dB // hot with a sine that used to be clean. A genuine match beats the penalty by a wide margin; // an ambiguous one stays where it belongs. const ncc = (dot * dot) / (tailEnergy * (energy || 1e-12)); return ncc - (0.2 * Math.abs(p - from)) / delta; };
const coarse = Math.max(1, Math.round((delta * 2) / Math.max(2, preset.candidates))); // Monotone, whatever the score says: a frame taken from *before* the one already in the overlap // plays the record backwards for a few milliseconds, which is not a stretch, not a shift, and // very audible on anything with a pitch. The nominal advance is positive at every ratio, so this // only ever bites when the correlation prefers a repeat to the truth. const floor = lastFrame + 1; const low = Math.max(from - delta, floor); const high = Math.max(low, from + delta); let best = low; let bestScore = -Infinity; for (let p = low; p <= high; p += coarse) { const s = score(p); if (s > bestScore) { bestScore = s; best = p; } } // Then one sample at a time around the winner: the coarse pass finds the neighbourhood, the // fine pass finds the sample. Two levels because a full-resolution search over ±delta is the // cost that would not fit in an audio quantum. for (let p = Math.max(low, best - coarse); p <= Math.min(high, best + coarse); p++) { const s = score(p); if (s > bestScore) { bestScore = s; best = p; } } return best; }
/** one stage-A frame: find it, window it, and overlap-add it into the stretched ring */ function emitHop(): void { const w = preset.window; const hop = w / 2; const from = align(Math.round(nominal)); lastFrame = from; for (let c = 0; c < channels; c++) { const src = input[c]!; const dst = stretched[c]!; const base = aAbs; for (let n = 0; n < w; n++) { const index = (base + n) & mask; // The first half of the frame lands on the previous frame's tail and adds to it; the second // half lands on ground nothing live covers, and *replaces* it. Adding there would add the // same-shaped write from a frame `size/hop` hops ago — the ring is reused, never zeroed, and // a frame that lands on its own ancestor sums with it. That is how a pass-through came out // a decibel hot with ghost impulses in it, and it is invisible unless you look for the // distance between the ghosts and the real ones: it was exactly the ring size. const held = n < hop ? dst[index]! : 0; dst[index] = held + win[n]! * at(src, from + n); } } aAbs += hop; nominal += hop / ratio; }
/** * How far the alignment may look, which grows with the stretch rather than shrinking with it. * * The reason is worth the paragraph, because it is the part of WSOLA that is not obvious. Frames * are `2·hop` long and are placed `hop` apart in the output, so consecutive frames must agree over * half a frame — but they are taken from input positions `hop/ratio` apart, so over that overlap * they disagree by exactly `hop·(1 − 1/ratio)` samples of input. At unison that is nothing; at +24 * semitones it is three quarters of a frame, and no amount of cleverness in the scoring fixes it: * the two halves are different music. The aligner's job is to *find* that offset — repeat or skip * material until the overlap matches — which is not a correction to the stretch, it is the stretch. * * So the range is the offset the geometry demands, plus the preset's own margin for finding the * peak of the correlation rather than its shoulder. Clamping it to a fraction of the nominal * advance — the intuitive thing, and what this file did first — leaves the frames unable to agree, * and the output is a comb-filtered sum of two different moments of the record at 6 dB hot. */ function search(): number { const hop = preset.window / 2; const required = Math.abs(hop - hop / ratio); const room = preset.window * 2; return Math.max(1, Math.min(room, Math.ceil(required) + preset.search)); }
/** * What the whole module costs, in input samples: the frame it has to see before it can place it, * the search that hangs off the end of that frame, and one hop of output it keeps in hand. * * That last term is not politeness. Hops are produced in bursts — one every `hop` samples of * input — and stage B drains them one sample at a time, so a pipeline allowed to run exactly level * with its input drains the output dry once per hop: eight silences a second, each of them a click. * Producing one hop ahead of the strict minimum is what turns that into a smooth stream, and it is * also why `latency` is larger than the window people expect a windowed shifter to cost. */ function lag(): number { return preset.window + search() + preset.window / 2; }
function canHop(): boolean { return inputAvailable(Math.round(nominal) + preset.window + search()); }
/** * One output sample, appended to the produced ring. * * `ratio > 1` is a decimation, so it averages a box of `ceil(ratio)` input samples around the * read point first: reading every fourth sample of a cymbal and calling it a quarter of the rate * is how an octave-up lands with a tail of aliases behind it. Under unity the read interpolates, * which is all upsampling needs. */ function emitSample(step: number): void { const width = step > 1 ? Math.ceil(step) : 1; const half = (width - 1) / 2; const base = Math.floor(readPos - half); const frac = readPos - half - base; for (let c = 0; c < channels; c++) { const ring = stretched[c]!; let sum = 0; if (width === 1) { const a = at(ring, Math.floor(readPos)); const b = at(ring, Math.floor(readPos) + 1); sum = a + (b - a) * frac; } else { for (let k = 0; k < width; k++) sum += at(ring, base + k); sum /= width; } produced[c]![outAbs & mask] = sum / ola; } outAbs++; readPos += step; }
/** stage B has the stage-A samples the next output sample reads */ function canSample(): boolean { // The `readPos < 0` half is the fill: the head of the stream reads before the beginning of the // track, and silence is the right answer there rather than a stall — see `reset`. return readPos < 0 || aAbs >= Math.floor(readPos + Math.ceil(ratio)) + 2; }
/** * Move the pipeline as far forward as it can go, and no further than the output ring holds. * * The ceiling is not an optimisation: production runs at the input's rate and consumption at the * caller's, and if a caller ever stopped reading (a paused source that still writes, a tab that * slept) an unbounded backlog would be a delay line that grows until it is the only thing in the * worklet's memory. Overflow is a stall, and a stall is a click — which is the same thing a * starved pipeline does, but at least that one is audible once. */ function pump(): void { while (canHop()) emitHop(); while (outAbs - outRead < backlog && canSample()) emitSample(ratio); }
return { setRatio(next) { if (!Number.isFinite(next) || next <= 0) return; // The delay is measured in input samples and stage B walks stage A `ratio` samples at a time, // so the head start the output needs is `lag × ratio` of them. Seeding it in `reset` alone is // wrong for the ordinary case — the engine states the key before the track has produced a // sample — where the ratio changes after the seed and the whole delay is then the wrong size: // the read position reaches the beginning of stage A with nothing behind it, the pipeline runs // exactly level with its input with no hop of slack in it, `canSample` is false forever, and // the shifter answers silence at every pitch except unison. ratio = next; // After the assignment, not before: `lag` is a function of the ratio (a wider shift // needs a wider search, and the search is part of the delay), and seeding the head start from // the ratio the shifter is leaving made the delay two quarters of what it should have been at // −24 semitones. if (outAbs === 0 && outRead === 0) readPos = -lag() * next; }, setQuality(next) { if (SHIFT_QUALITIES.includes(next) && next !== quality) { quality = next; // The window changes, so the rings change size, so the stream has to be restarted: the // absolute indices on both sides of the pipeline are meaningless across a resize. The // engine re-arms the node when it does this, which is why nobody has noticed. preset = { ...SHIFT_PRESETS[next] }; build(); reset(); } }, ratio: () => ratio, quality: () => quality, latency: () => lag(), write(channel, samples) { const ring = input[channel]; if (!ring) return; for (let i = 0; i < samples.length; i++) ring[(inAbs + i) & mask] = samples[i]!; rows++; if (rows >= channels) { inAbs += samples.length; rows = 0; } }, read(out: Float32Array[]) { const frames = out[0]?.length ?? 0; if (frames === 0) return; pump(); for (let i = 0; i < frames; i++) { if (outRead >= outAbs) { // Nothing produced yet — the initial window's worth of fill, and the only silence this // makes. Note the consumer's index advances and the producer's does not: the output comes // out late rather than early, which is what `latency` is the number of. for (let c = 0; c < channels; c++) out[c]![i] = 0; outRead++; continue; } for (let c = 0; c < channels; c++) out[c]![i] = produced[c]![outRead & mask]!; outRead++; } }, reset, };}