Split any YouTube song into stems
TypeScript
feat: route playback through pitch shifter with latency compensation
David Navia7a7afda07a0f
diff --git a/src/renderer/src/lib/engine.ts b/src/renderer/src/lib/engine.tsindex ea42a13..82d6b62 100644--- a/src/renderer/src/lib/engine.ts+++ b/src/renderer/src/lib/engine.ts@@ -1,4 +1,6 @@import type { StemId, StemPanMap } from '../../../shared/types'+import { clampPitch, createPitchShifter } from './pitch'+import type { PitchShifter, ShifterFactory } from './pitch'export type BufferMap = Partial<Record<StemId, AudioBuffer>>@@ -46,6 +48,21 @@ export class StemEngine {private anchorYt = 0private anchorCtx = 0rate = 1+ // the latest requested pitch; may differ from the applied one while the+ // shifter loads or before the AudioContext exists+ private wantedPitch = 0+ private appliedPitch = 0+ // created once and reused: building a worklet per change is slow and leaks+ private shifterLoad: Promise<PitchShifter> | null = null+ // the shifter master currently feeds, or null when bypassed+ private routed: PitchShifter | null = null+ pitchError: string | null = null++ private readonly shifterFactory: ShifterFactory++ constructor(factory: ShifterFactory = createPitchShifter) {+ this.shifterFactory = factory+ }private ensureCtx(): AudioContext {if (!this.ctx) {@@ -53,10 +70,69 @@ export class StemEngine {this.master = this.ctx.createGain()this.master.gain.value = this.mix.masterthis.master.connect(this.ctx.destination)+ // a pitch chosen before the first play is applied now+ if (this.wantedPitch !== 0) void this.applyPitch()}return this.ctx}+ pitch(): number {+ return this.appliedPitch+ }++ async setPitch(semitones: number): Promise<void> {+ this.wantedPitch = clampPitch(semitones)+ // no context yet (nothing played): ensureCtx applies it later+ if (!this.ctx) return+ await this.applyPitch()+ }++ private async applyPitch(): Promise<void> {+ if (this.wantedPitch === 0) {+ // exact bypass: the shifter is never perfectly transparent+ this.appliedPitch = 0+ this.route(null)+ return+ }+ let shifter: PitchShifter+ try {+ shifter = await (this.shifterLoad ??= this.shifterFactory(this.ctx!))+ } catch (err) {+ this.pitchError = err instanceof Error ? err.message : String(err)+ this.appliedPitch = 0+ this.route(null)+ return+ }+ this.pitchError = null+ // calls overlapping the load all land here: read the value again so the+ // last press wins (and a return to 0 meanwhile stays in bypass)+ const want = this.wantedPitch+ if (want === 0) return this.route(null)+ shifter.setSemitones(want)+ this.appliedPitch = want+ this.route(shifter)+ }++ private route(next: PitchShifter | null): void {+ if (next === this.routed) return+ const ctx = this.ctx!+ const master = this.master!+ master.disconnect()+ // a bypassed shifter stays alive with no input (it just processes+ // silence) so the next non-zero pitch does not rebuild it+ this.routed?.output.disconnect()+ if (next) {+ master.connect(next.input)+ next.output.connect(ctx.destination)+ } else {+ master.connect(ctx.destination)+ }+ this.routed = next+ // the path latency changed: restart the sources from where the listener+ // is now so the clock and the video stay in step+ if (this.playing) this.align(this.expected())+ }+private getGain(id: StemId): GainNode {const ctx = this.ensureCtx()let g = this.gains[id]@@ -124,12 +200,22 @@ export class StemEngine {src.start(startAt, Math.min(Math.max(0, time), Math.max(0, buf.duration - 0.01)))this.sources.push(src)}- this.anchorCtx = startAt+ // anchorCtx is when anchorYt becomes audible: the shifter delays the+ // sound by its latency, so the clock starts that much later+ this.anchorCtx = startAt + (this.routed ? this.routed.latency : 0)}+ // Held at anchorYt until the first sample is audible, then advances with the+ // context clock. A re-route calls align(expected()), so the new anchorYt is+ // the value expected() had just before: the clock pauses for the start delay+ // plus the new path's latency and never goes backwards. The price is that+ // the listener hears up to one old-path latency (≈0.12 s) of audio again or+ // skipped, far below Player's 0.4 s re-seek thresholdexpected(): number {if (!this.ctx || !this.playing) return this.anchorYt- return this.anchorYt + (this.ctx.currentTime - this.anchorCtx) * this.rate+ const now = this.ctx.currentTime+ if (now < this.anchorCtx) return this.anchorYt+ return this.anchorYt + (now - this.anchorCtx) * this.rate}trackDuration(): number {diff --git a/tests/engine.test.mjs b/tests/engine.test.mjsindex 4689af5..a16c744 100644--- a/tests/engine.test.mjs+++ b/tests/engine.test.mjs@@ -1,6 +1,20 @@import { test } from 'node:test'import assert from 'node:assert/strict'-import { StemEngine } from '../src/renderer/src/lib/engine.ts'+import { registerHooks } from 'node:module'++// renderer modules use extensionless relative imports (bundler resolution);+// node needs the .ts spelled out+const srcRoot = new URL('../src/', import.meta.url).href+const hooks = registerHooks({+ resolve(specifier, context, next) {+ if (context.parentURL?.startsWith(srcRoot) && specifier.startsWith('.') && !/\.\w+$/.test(specifier)) {+ return { shortCircuit: true, url: new URL(`${specifier}.ts`, context.parentURL).href }+ }+ return next(specifier, context)+ }+})+const { StemEngine } = await import('../src/renderer/src/lib/engine.ts')+hooks.deregister()class Param {value = 0@@ -20,7 +34,9 @@ class Context {createGain() { return Object.assign(new AudioNode(), { gain: new Param() }) }createStereoPanner() { return Object.assign(new AudioNode(), { pan: new Param() }) }createBufferSource() {- const node = Object.assign(new AudioNode(), { playbackRate: new Param(), start() {}, stop() {} })+ const node = Object.assign(new AudioNode(), {+ playbackRate: new Param(), stopped: false, start() {}, stop() { this.stopped = true }+ })this.sources.push(node)return node}@@ -68,3 +84,128 @@ test('seeking and resume preserve pan; switching songs disconnects and resets itengine.setPlaying(true, 0)assert.equal(nodes(Context.last.sources[6]).pan.pan.value, 0)})++// controllable fake: each factory call returns a pending promise the test settles+const fakeFactory = () => {+ const calls = []+ const factory = (ctx) => new Promise((resolve, reject) => {+ const shifter = {+ input: new AudioNode(),+ output: new AudioNode(),+ latency: 0.05,+ semitones: [],+ setSemitones(n) { this.semitones.push(n) },+ dispose() {}+ }+ calls.push({ ctx, shifter, resolve: () => resolve(shifter), reject })+ })+ return { factory, calls }+}+const instant = () => {+ const fake = fakeFactory()+ return {+ calls: fake.calls,+ factory: (ctx) => {+ const p = fake.factory(ctx)+ fake.calls.at(-1).resolve()+ return p+ }+ }+}+const playing = (factory) => {+ const engine = new StemEngine(factory)+ engine.setBuffers(buffers)+ engine.setPlaying(true, 5)+ return { engine, ctx: Context.last, master: nodes(Context.last.sources[0]).master }+}++test('pitch 0 keeps master wired straight to destination', () => {+ const { calls, factory } = instant()+ const { engine, ctx, master } = playing(factory)+ assert.deepEqual(master.outputs, [ctx.destination])+ assert.equal(calls.length, 0)+ assert.equal(engine.pitch(), 0)+})++test('non-zero pitch routes master through the shifter and offsets the clock', async () => {+ const { calls, factory } = instant()+ const { engine, ctx, master } = playing(factory)+ await engine.setPitch(-3)+ const { shifter } = calls[0]+ assert.equal(master.outputs.length, 1)+ assert.equal(master.outputs[0], shifter.input)+ assert.deepEqual(shifter.output.outputs, [ctx.destination])+ assert.equal(shifter.semitones.at(-1), -3)+ assert.equal(engine.pitch(), -3)+ // re-aligned at the same position: the clock holds while the shifter's+ // latency drains, then advances in step with currentTime+ const startAt = ctx.currentTime + 0.04+ assert.equal(engine.expected(), 5)+ ctx.currentTime = startAt + 0.05 - 0.01+ assert.equal(engine.expected(), 5)+ ctx.currentTime = startAt + 0.05 + 1+ assert.ok(Math.abs(engine.expected() - 6) < 1e-9)+})++test('back to 0 restores bypass', async () => {+ const { calls, factory } = instant()+ const { engine, ctx, master } = playing(factory)+ await engine.setPitch(2)+ const routed = Context.last.sources.slice()+ await engine.setPitch(0)+ assert.deepEqual(master.outputs, [ctx.destination])+ assert.deepEqual(calls[0].shifter.output.outputs, [])+ assert.ok(routed.every((s) => s.stopped))+ assert.equal(engine.pitch(), 0)+ await engine.setPitch(4)+ assert.equal(calls.length, 1, 'the shifter is created once and reused')+ assert.equal(master.outputs[0], calls[0].shifter.input)+})++test('rapid presses while the factory is pending create one shifter and end at the last value', async () => {+ const { calls, factory } = fakeFactory()+ const { engine, master } = playing(factory)+ const pending = [engine.setPitch(1), engine.setPitch(2), engine.setPitch(3)]+ assert.equal(calls.length, 1)+ calls[0].resolve()+ await Promise.all(pending)+ assert.equal(calls.length, 1)+ assert.equal(engine.pitch(), 3)+ assert.equal(calls[0].shifter.semitones.at(-1), 3)+ assert.deepEqual(master.outputs, [calls[0].shifter.input])+})++test('returning to 0 while the factory is pending stays in bypass', async () => {+ const { calls, factory } = fakeFactory()+ const { engine, ctx, master } = playing(factory)+ const pending = [engine.setPitch(2), engine.setPitch(0)]+ calls[0].resolve()+ await Promise.all(pending)+ assert.equal(engine.pitch(), 0)+ assert.deepEqual(master.outputs, [ctx.destination])+})++test('factory failure leaves audio in bypass', async () => {+ const { calls, factory } = fakeFactory()+ const { engine, ctx, master } = playing(factory)+ const pending = engine.setPitch(2)+ calls[0].reject(new Error('Pitch shifter failed to load'))+ await assert.doesNotReject(pending)+ assert.deepEqual(master.outputs, [ctx.destination])+ assert.equal(engine.pitch(), 0)+ assert.equal(engine.pitchError, 'Pitch shifter failed to load')+})++test('pitch set before the audio context exists applies once playback starts', async () => {+ const { calls, factory } = instant()+ const engine = new StemEngine(factory)+ engine.setBuffers(buffers)+ await engine.setPitch(-2)+ assert.equal(calls.length, 0)+ engine.setPlaying(true, 0)+ await new Promise((r) => setTimeout(r, 0))+ // the re-route restarted the sources: read the graph from the live ones+ const master = nodes(Context.last.sources.at(-1)).master+ assert.equal(master.outputs[0], calls[0].shifter.input)+ assert.equal(engine.pitch(), -2)+})