import { describe, expect, it } from "vitest"; import { clampKey, createShifter, KEY_MAX, KEY_MIN, ratioForSemitones, SHIFT_PRESETS, SHIFT_QUALITIES, type ShifterOptions, } from "./shift"; import { shiftRatio, shiftSemitones } from "./pitch"; import { dftMagnitudes, tone } from "../../test/signal"; /** * The pitch shifter, measured rather than listened to. * * Three claims matter and all three are measurable: the pitch moved by the ratio asked for, the * length did not, and the things that were sudden are still sudden. The first two are a sine wave * and a DFT; the third is an impulse train, because the artefact this algorithm is chosen *for* is * transient preservation, and the only way to know a frame landed on a drum rather than across it * is to ask where the drum came out. * * Everything here is driven through `write`/`read` in 128-sample blocks — the audio thread's quantum * — because a stretcher that is correct when handed the whole file at once and wrong one block at a * time is the failure mode of this genre of code, and the worklet is the only consumer. */ const SR = 44100; const BLOCK = 128; /** The whole signal through the shifter, one audio quantum at a time. */ function through( input: Float32Array, semitones: number, options: ShifterOptions = {}, ): Float32Array { const shifter = createShifter({ channels: 1, ...options }); shifter.setRatio(ratioForSemitones(semitones)); const out = new Float32Array(input.length); const src = new Float32Array(BLOCK); const dst = [new Float32Array(BLOCK)]; for (let i = 0; i < input.length; i += BLOCK) { src.fill(0); src.set(input.subarray(i, Math.min(i + BLOCK, input.length))); shifter.write(0, src); shifter.read(dst); out.set(dst[0]!.subarray(0, Math.min(BLOCK, input.length - i)), i); } return out; } const rms = (x: Float32Array): number => { let sum = 0; for (let i = 0; i < x.length; i++) sum += x[i]! * x[i]!; return Math.sqrt(sum / x.length); }; /** * Where the energy is, to 20 Hz, on the middle of the signal. * * A windowed DFT of 2 205 samples: windowed because a segment that is not a whole number of periods * leaks, and a leak is enough to move a peak when the question is "did this go from 440 to 880". */ function dominantHz(x: Float32Array): number { const n = 2205; const from = Math.max(0, Math.floor(x.length / 2 - n / 2)); const seg = new Float64Array(n); for (let i = 0; i < n; i++) seg[i] = x[from + i]! * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n)); const m = dftMagnitudes(seg, n); let best = 1; let bestMag = -Infinity; for (let b = 1; b < m.length / 2; b++) { if (m[b]! > bestMag) { bestMag = m[b]!; best = b; } } // Parabolic interpolation between the peak bin and its neighbours: the bin grid is 10 Hz and the // question "−24 semitones of 440 Hz" has an answer of 110, which lands exactly on a boundary — // without the interpolation this helper reports whichever side the leakage favoured. const alpha = m[best - 1] ?? 0; const beta = m[best]!; const gamma = m[best + 1] ?? 0; const denom = alpha - 2 * beta + gamma; const tilt = denom === 0 ? 0 : (0.5 * (alpha - gamma)) / denom; return ((best + Math.max(-1, Math.min(1, tilt))) * SR) / n; } const impulseTrain = (seconds: number, everySeconds = 0.5): Float32Array => { const out = new Float32Array(Math.round(SR * seconds)); for (let t = everySeconds; t < seconds - 0.05; t += everySeconds) out[Math.round(t * SR)] = 1; return out; }; /** * Something with a shape and a broadband hiss: what a stretcher actually meets. * * A pure sine is this algorithm's worst adversary — its correlation has an equally good peak at * every period of itself, so the aligner is free to place frames wherever it likes and the overlap * sums add or cancel depending on the luck of the coarse pass. Real material has one peak. So the * level and transient claims below are measured on material that can be measured, and the sine is * kept for the questions it can still answer: where the pitch went. */ function music(seconds: number, seed = 7): Float32Array { const out = new Float32Array(Math.round(SR * seconds)); let state = seed; const rnd = () => { state = (state * 1103515245 + 12345) & 0x7fffffff; return state / 0x7fffffff - 0.5; }; for (let i = 0; i < out.length; i++) { const t = i / SR; const env = 0.6 + 0.4 * Math.sin(2 * Math.PI * 2.1 * t); out[i] = env * 0.25 * (Math.sin(2 * Math.PI * 220 * t) + 0.8 * Math.sin(2 * Math.PI * 440 * t) + 0.6 * Math.sin(2 * Math.PI * 1100 * t) + 0.4 * Math.sin(2 * Math.PI * 2900 * t)) + 0.06 * rnd(); } return out; } /** * A tone with a top end: fundamental plus three harmonics falling away, so the spectrum has an * obvious pitch to find and enough structure for the aligner to have something to line up on. */ function harmonic(hz: number, seconds: number): Float32Array { const out = new Float32Array(Math.round(SR * seconds)); for (let i = 0; i < out.length; i++) { const t = i / SR; let s = 0; for (let k = 1; k <= 4; k++) s += Math.sin(2 * Math.PI * hz * k * t) / k; out[i] = 0.4 * s; } return out; } /** Deterministic white noise: the signal with nothing for an aligner to mistake. */ function noise(seconds: number, seed = 3): Float32Array { const out = new Float32Array(Math.round(SR * seconds)); let state = seed; for (let i = 0; i < out.length; i++) { state = (state * 1103515245 + 12345) & 0x7fffffff; out[i] = 0.5 * (state / 0x7fffffff - 0.5); } return out; } /** Short-term RMS, one number per `hop` samples: where the transients are, as a curve. */ function envelope(x: Float32Array, hop = 256): Float32Array { const n = Math.floor(x.length / hop); const out = new Float32Array(n); for (let k = 0; k < n; k++) { let s = 0; for (let i = 0; i < hop; i++) s += x[k * hop + i]! * x[k * hop + i]!; out[k] = Math.sqrt(s / hop); } return out; } /** * Where the output's envelope best lines up with the input's, searched near `expect`. * * Searched rather than found: the envelope of anything with a beat has a peak at every beat, so an * unbounded search is free to report a delay of zero plus one bar. The question here is never "how * late is it" but "is it late by the delay the module says it is". */ function bestLag(input: Float32Array, out: Float32Array, expectAt: number, hop = 256): number { const a = envelope(input, hop); const b = envelope(out, hop); const centre = Math.round(expectAt / hop); const span = Math.round((0.12 * SR) / hop); let best = centre; let bestScore = -Infinity; for (let lag = Math.max(0, centre - span); lag <= Math.min(b.length - 8, centre + span); lag++) { let dot = 0; for (let i = 0; i + lag < b.length && i < a.length; i++) dot += a[i]! * b[i + lag]!; if (dot > bestScore) { bestScore = dot; best = lag; } } return best * hop; } describe("the ratio", () => { it("is exact at the octaves, because that is where the ear is least forgiving", () => { expect(ratioForSemitones(0)).toBe(1); expect(ratioForSemitones(12)).toBe(2); expect(ratioForSemitones(-12)).toBe(0.5); expect(ratioForSemitones(24)).toBe(4); expect(ratioForSemitones(1)).toBeCloseTo(2 ** (1 / 12), 12); }); it("clamps to the two octaves the control offers, and rounds to the semitone it promises", () => { expect(clampKey(3.2)).toBe(3); expect(clampKey(3.6)).toBe(4); expect(clampKey(-3.6)).toBe(-4); expect(clampKey(1000)).toBe(KEY_MAX); expect(clampKey(-1000)).toBe(KEY_MIN); // Not a number is not a key: it is "do nothing to the pitch", which is the only sane reading of // a value that got here from a NaN somewhere upstream. expect(clampKey(Number.NaN)).toBe(0); expect(clampKey(Number.POSITIVE_INFINITY)).toBe(0); }); }); describe("the presets", () => { it("are three window lengths, and the window is most of the latency", () => { expect(SHIFT_QUALITIES).toEqual(["crisp", "balanced", "smooth"]); expect(SHIFT_PRESETS.crisp.window).toBeLessThan(SHIFT_PRESETS.balanced.window); expect(SHIFT_PRESETS.balanced.window).toBeLessThan(SHIFT_PRESETS.smooth.window); for (const q of SHIFT_QUALITIES) { const p = SHIFT_PRESETS[q]; // The search must fit inside the frame alongside the correlation, or `align` would be free to // pick a frame that has not arrived yet and the whole thing silently stops shifting. expect(p.correlation).toBeLessThanOrEqual(p.window / 2); // More than the window (it needs the frame, the search that hangs off it, and a hop of output // in hand) and less than twice it: the bar compensates this number, so an order-of-magnitude // error in it is a flash a tenth of a second off the beat. const latency = createShifter({ quality: q }).latency(); expect(latency, q).toBeGreaterThan(p.window); expect(latency, q).toBeLessThan(p.window * 2); } }); }); describe("the shifter", () => { it("passes a signal through untouched at zero, apart from the latency", () => { // Noise, deliberately: it is the only signal whose correlation has exactly one peak, so it is // the signal that notices a frame put in the wrong place. Tonal material is ambiguous by // construction — a period of itself looks like itself — and a pass-through measured on it tests // the aligner's patience rather than the reconstruction. const input = noise(2, 11); const shifter = createShifter({ channels: 1, quality: "balanced" }); const out = through(input, 0); // Where the copy actually landed, searched over a quarter of a window either side: the module // promises the delay to within a few milliseconds, which is the accuracy the pulse can use, and // correlating noise at an offset that is 31 samples wrong scores nothing at all. const found = bestLag(input, out, shifter.latency(), 1); expect(Math.abs(found - shifter.latency())).toBeLessThan(128); const w = found; let dot = 0; let inEnergy = 0; let delayed = 0; for (let i = 4096; i < input.length - w - 1024; i++) { dot += input[i]! * out[i + w]!; inEnergy += input[i]! * input[i]!; delayed += out[i + w]! * out[i + w]!; } expect(dot / Math.sqrt(inEnergy * delayed)).toBeGreaterThan(0.98); // Within about 1 dB of the level it was given — which is what makes the engine's decision to // wire this module out entirely at zero shift the right one rather than a precaution. const gain = Math.sqrt(delayed / inEnergy); expect(gain).toBeGreaterThan(0.94); expect(gain).toBeLessThan(1.06); }); it("keeps the length it was given, at every key", () => { const input = music(1.5); for (const key of [-24, -12, -7, -1, 0, 1, 7, 12, 24]) { const out = through(input, key); // The whole reason a loop boundary can stay put under a pitch change: a second of the file in // is a second of the file out, whatever the key. expect(Math.abs(out.length - input.length), `${key} st`).toBeLessThanOrEqual(BLOCK); expect(rms(out) > 0, `${key} st produced silence`).toBe(true); } }); it("doubles the pitch at +12 and halves it at −12, and the level survives both", () => { const input = harmonic(440, 1.5); const up = through(input, 12); const down = through(input, -12); // The fundamental of a harmonic tone, because it is the one frequency claim an artefact cannot // satisfy: the ratio applied to the wrong stage, the two stages half-cancelling, an alignment // drifting a period per hop — all of them put something other than 880 and 220 here. expect(dominantHz(up)).toBeCloseTo(880, -1); expect(dominantHz(down)).toBeCloseTo(220, -1); expect(dominantHz(input)).toBeCloseTo(440, -1); // Within ~2 dB, measured on material with a shape to it: the OLA normalisation, the box filter // above unity and the interpolation below it all have an opinion about level, and any of them // being badly wrong is audible the first time anything with a beat goes through. const shaped = music(1.5); for (const out of [through(shaped, 12), through(shaped, -12)]) { expect(rms(out) / rms(shaped)).toBeGreaterThan(0.75); expect(rms(out) / rms(shaped)).toBeLessThan(1.3); } }); it("holds the pitch at the speeds the deck now runs at, which is the whole point of the lock", () => { // The lock's job is stated once, here, where it can be measured: a record run at 80 % of its own // speed arrives at the shifter 3.86 semitones flat — 12·log₂(1.25), which is not a number anybody // can guess at a prompt and is not a whole number of semitones at any percent but 50, 100 and 200 // — and the shifter is handed the ratio that puts it back. A `toBeCloseTo` on a hand-written // semitone count would pass with the wrong ratio in the store, so the assertion is on the pitch // that comes out the end, on material the aligner can actually line up on. const input = harmonic(440, 1.5); for (const deck of [0.5, 0.8, 1.1, 2]) { // Both numbers are asserted because they are two different chances to be wrong: the semitone // sum lives in `pitch.ts` and the ratio the engine is handed lives with the store. const correction = shiftSemitones(0, true, deck); expect(shiftRatio(0, true, deck), `${deck}x`).toBeCloseTo(ratioForSemitones(correction), 10); // There is no `BufferSource` in this file, so what is measured is the shifter's half of the // transaction — and the half it has to get right is the inverse of what the deck did to the // pitch, which is 440 divided by the deck rate. Put the source back and the two multiply to 440 // exactly, which is the sentence "play it slower, in the same key". expect(dominantHz(through(input, correction)), `${deck}x`).toBeCloseTo(440 / deck, -1); } }); it("reaches two octaves without the aliases a naive decimator would leave behind", () => { // +24 reads every fourth sample of stage A. Without the box average that is a hard decimation // and half the input folds back over the top of the spectrum, which on a sine shows up as a // peak that is not the octave. const input = harmonic(440, 1.5); expect(dominantHz(through(input, 24))).toBeCloseTo(1760, -1); expect(dominantHz(through(input, -24))).toBeCloseTo(110, -1); }); it("keeps a drum where the record had it, in the preset built for drums", () => { // The claim WSOLA is bought with, asked of the one material that can answer it: a kick every // half second through an octave of pitch change. Not "is the click intact sample for sample" — // a stretcher reorders frames and a click inside a reused frame is whatever the overlap says — // but "does the beat still land on the beat", which is what a listener calls tight or sloppy. // A shifter that smeared a transient across a frame, the failure this algorithm exists to avoid, // cannot pass this, and neither can one whose clock drifts. const quality = "crisp"; const shifter = createShifter({ channels: 1, quality }); const input = impulseTrain(4); const out = through(input, 12, { quality }); const every = 0.5 * SR; const latency = shifter.latency(); // Twenty milliseconds: a beat is felt as late past about that, and the alignment is allowed to // move a frame by the search range on its way to the transient. expect(Math.abs(bestLag(input, out, latency) - latency)).toBeLessThan(0.02 * SR); // And the kick is still a kick: a peak that survived within 10 ms of where it belongs, at more // than a third of the original level. Spread the same energy over a 23 ms frame and this is the // assertion that fails. for (let k = 1; k <= 6; k++) { const at = latency + k * every; let peak = 0; for (let i = at - 441; i < at + 441; i++) if (i >= 0 && i < out.length) peak = Math.max(peak, Math.abs(out[i]!)); expect(peak, `kick ${k}`).toBeGreaterThan(0.3); } }); it("reports the delay it actually costs, which is what the pulse is compensated by", () => { // Measured against the envelope of a click track rather than assumed from the window: the delay // is the window plus the search that hangs off it plus a hop of output in hand, and the number // the bar shifts its flash by has to be the one the audio takes, not the one the first draft of // this file guessed. for (const quality of SHIFT_QUALITIES) { const shifter = createShifter({ channels: 1, quality }); const input = impulseTrain(3, 1); const out = through(input, 0, { quality }); expect( Math.abs(bestLag(input, out, shifter.latency()) - shifter.latency()), quality, ).toBeLessThan(SHIFT_PRESETS[quality].window / 4); } }); it("keeps shifting when the key changes mid-stream", () => { // A press during a note: the ratio moves at the next frame boundary, so the second half of the // track is in the new key and the first half is in the old one — which is what a fader does, and // the alternative (recomputing the whole stream) is what a live shifter cannot do. const shifter = createShifter({ channels: 1, quality: "balanced" }); const input = tone(440, 3); const out = new Float32Array(input.length); const src = new Float32Array(BLOCK); const dst = [new Float32Array(BLOCK)]; let flipped = false; for (let i = 0; i < input.length; i += BLOCK) { if (!flipped && i > input.length / 2) { shifter.setRatio(ratioForSemitones(12)); flipped = true; } src.fill(0); src.set(input.subarray(i, Math.min(i + BLOCK, input.length))); shifter.write(0, src); shifter.read(dst); out.set(dst[0]!.subarray(0, Math.min(BLOCK, input.length - i)), i); } expect(flipped).toBe(true); const tail = out.subarray(Math.floor(input.length * 0.8)); const head = out.subarray(SHIFT_PRESETS.balanced.window * 2, Math.floor(input.length * 0.4)); expect(dominantHz(tail)).toBeCloseTo(880, -1); expect(dominantHz(head)).toBeCloseTo(440, -1); }); it("survives a re-tune mid-stream and comes back in the new window", () => { const shifter = createShifter({ channels: 1, quality: "balanced" }); shifter.setRatio(ratioForSemitones(5)); const src = new Float32Array(BLOCK); const dst = [new Float32Array(BLOCK)]; const input = tone(330, 2); for (let i = 0; i < 4000; i += BLOCK) { src.set(input.subarray(i, i + BLOCK)); shifter.write(0, src); shifter.read(dst); } // Re-tuning resizes the rings, so the stream restarts — the engine re-arms the node when it // happens, and what this asserts is that nothing throws and audio comes out the other side. shifter.setQuality("smooth"); expect(shifter.quality()).toBe("smooth"); // The delay is the new window plus the search and hop that hang off it — not the window alone, // and not the number it had before the re-tune either. expect(shifter.latency()).toBeGreaterThan(SHIFT_PRESETS.smooth.window); let energy = 0; for (let i = 0; i < input.length; i += BLOCK) { src.fill(0); src.set(input.subarray(i, Math.min(i + BLOCK, input.length))); shifter.write(0, src); shifter.read(dst); for (let k = 0; k < BLOCK; k++) energy += dst[0]![k]! * dst[0]![k]!; } expect(energy).toBeGreaterThan(0); }); it("shifts each channel by the same amount, from one shared alignment", () => { // One note at two levels, which is what a stereo recording of one thing looks like. Both // channels are placed by the *same* frame positions — that is the decision, and it is the one // that keeps a guitar from swimming between the speakers when the key moves — and the price of // it is that two channels holding unrelated material would be aligned against each other. Measured // on a stereo pair of different notes it fails, loudly, and that failure is the design. const shifter = createShifter({ channels: 2, quality: "balanced" }); shifter.setRatio(ratioForSemitones(12)); const left = harmonic(440, 1.5); const right = harmonic(440, 1.5).map((v) => v * 0.4) as Float32Array; const outs = [new Float32Array(left.length), new Float32Array(right.length)]; const srcL = new Float32Array(BLOCK); const srcR = new Float32Array(BLOCK); const dst = [new Float32Array(BLOCK), new Float32Array(BLOCK)]; for (let i = 0; i < left.length; i += BLOCK) { srcL.set(left.subarray(i, Math.min(i + BLOCK, left.length))); srcR.set(right.subarray(i, Math.min(i + BLOCK, right.length))); shifter.write(0, srcL); shifter.write(1, srcR); shifter.read(dst); outs[0]!.set(dst[0]!.subarray(0, Math.min(BLOCK, left.length - i)), i); outs[1]!.set(dst[1]!.subarray(0, Math.min(BLOCK, right.length - i)), i); } expect(dominantHz(outs[0]!)).toBeCloseTo(880, -1); expect(dominantHz(outs[1]!)).toBeCloseTo(880, -1); // The level difference between the channels survives, which is the way to see that a channel is // read from its own ring and not from its neighbour's. const ratio = rms(outs[1]!) / rms(outs[0]!); expect(ratio).toBeGreaterThan(0.3); expect(ratio).toBeLessThan(0.5); }); it("a ratio changed mid-stream is a slope, not a step in the signal", () => { // The claim that lets the deck stay in the chain at unison. If moving the ratio jumped the output, // the click would only have moved from the rewire to the key press, and the listener would click on // every press of the bracket instead of only on the way home. // // A 220 Hz tone at 0.4 cannot move further than A·2πf/fs between two samples — 0.0125 here — // because that is what a sine is. A re-seeded read position moves it by up to 0.8 in one sample, // which is not a seam anybody needs equipment to find. So this measures the worst consecutive // difference once the pipeline has filled, with the ratio moved eight times through the phrase, and // holds it to the same bound as the run where the ratio was left alone. const input = tone(220, 6, SR, 0.4); const slewLimit = 0.4 * ((2 * Math.PI * 220) / SR); const KEYS = [7, -5, 12, 0, -12, 3, 19, -2]; const worstStep = (moves: number[]): number => { const shifter = createShifter({ channels: 1 }); const out = new Float32Array(input.length); const src = new Float32Array(BLOCK); const dst = [new Float32Array(BLOCK)]; let next = 0; for (let i = 0; i < input.length; i += BLOCK) { if (next < moves.length && i >= moves[next]! * SR) { shifter.setRatio(ratioForSemitones(KEYS[next]!)); next++; } src.fill(0); src.set(input.subarray(i, Math.min(i + BLOCK, input.length))); shifter.write(0, src); shifter.read(dst); out.set(dst[0]!.subarray(0, Math.min(BLOCK, input.length - i)), i); } // The first second is the delay line filling, and is not the thing under test. let worst = 0; for (let i = SR; i < out.length; i++) worst = Math.max(worst, Math.abs(out[i]! - out[i - 1]!)); expect(rms(out.subarray(SR))).toBeGreaterThan(0.1); // and not a jump into silence return worst; }; const still = worstStep([]); const moved = worstStep([1, 1.6, 2.2, 2.8, 3.4, 4, 4.6, 5.2]); // Four times the slew limit is the allowance: a splice between two windowed frames is allowed to be // untidy in a way a re-seed is not. Measured: 0.0125 unstirred — the slew limit exactly — and // 0.0376 with the ratio walked through eight keys, which is three times it and one eleventh of // the smallest jump this feature has ever made. expect(still).toBeLessThan(slewLimit * 4); expect(moved).toBeLessThan(slewLimit * 4); }); });