Skip to content

Split any YouTube song into stems

TypeScript

fix: keep video in sync across pitch re-routes and preload the shifter

David Navia2f757ec4f0de
diff --git a/src/renderer/src/lib/engine.ts b/src/renderer/src/lib/engine.ts
index 81a1570..d632ae9 100644
--- a/src/renderer/src/lib/engine.ts
+++ b/src/renderer/src/lib/engine.ts
@@ -4,6 +4,9 @@ import type { PitchShifter, ShifterFactory } from './pitch'
export type BufferMap = Partial<Record<StemId, AudioBuffer>>
+// headroom between scheduling the sources and their first sample
+const START_DELAY = 0.04
+
export async function decodePayload(
payload: Record<string, Uint8Array>
): Promise<BufferMap> {
@@ -49,10 +52,11 @@ export class StemEngine {
private anchorCtx = 0
rate = 1
// the latest requested pitch; may differ from the applied one while the
- // shifter loads or before the AudioContext exists
+ // shifter loads
private wantedPitch = 0
private appliedPitch = 0
- // created once and reused: building a worklet per change is slow and leaks
+ // created once and reused: building a worklet per change is slow and leaks.
+ // The node lives for the app session by design (never disposed here)
private shifterLoad: Promise<PitchShifter> | null = null
// the shifter master currently feeds, or null when bypassed
private routed: PitchShifter | null = null
@@ -70,8 +74,6 @@ export class StemEngine {
this.master = this.ctx.createGain()
this.master.gain.value = this.mix.master
this.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
}
@@ -82,8 +84,16 @@ export class StemEngine {
async setPitch(semitones: number): Promise<void> {
this.wantedPitch = clampPitch(semitones)
- // no context yet (nothing played): ensureCtx applies it later
- if (!this.ctx) return
+ // a failed load is only relevant while a shift is wanted
+ if (this.wantedPitch === 0) this.pitchError = null
+ if (!this.ctx) {
+ // nothing to bypass before the first play
+ if (this.wantedPitch === 0) return
+ // load the shifter now, while paused, so the first play is routed
+ // through it from the start instead of re-routing mid-song once it
+ // lands (decodePayload also opens a context without a gesture)
+ this.ensureCtx()
+ }
await this.applyPitch()
}
@@ -132,9 +142,14 @@ export class StemEngine {
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())
+ // the path latency changed: restart the sources from where the video
+ // will be once the new path is audible. Re-aligning at expected() would
+ // stall the clock for the start delay plus the latency while the video
+ // keeps running, and that lead would add up on every toggle
+ if (this.playing) {
+ const latency = next ? next.latency : 0
+ this.align(this.expected() + (START_DELAY + latency) * this.rate)
+ }
}
private getGain(id: StemId): GainNode {
@@ -192,7 +207,7 @@ export class StemEngine {
this.anchorYt = time
if (!this.ctx || !this.playing || !this.hasBuffers()) return
const ctx = this.ctx
- const startAt = ctx.currentTime + 0.04
+ const startAt = ctx.currentTime + START_DELAY
for (const id of Object.keys(this.buffers) as StemId[]) {
const buf = this.buffers[id]
if (!buf) continue
@@ -210,11 +225,11 @@ export class StemEngine {
}
// 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 threshold
+ // context clock. A re-route aligns ahead by the start delay plus the new
+ // path's latency, so once the new path is audible the clock is exactly where
+ // it would have been without the re-route: it never stalls or goes back,
+ // and the video keeps no lead. The price is a short skip in the audio
+ // (about the start delay plus the latency), not a sync error
expected(): number {
if (!this.ctx || !this.playing) return this.anchorYt
const now = this.ctx.currentTime
diff --git a/tests/engine.test.mjs b/tests/engine.test.mjs
index e656707..d58d5ac 100644
--- a/tests/engine.test.mjs
+++ b/tests/engine.test.mjs
@@ -25,7 +25,8 @@ class Context {
createStereoPanner() { return Object.assign(new AudioNode(), { pan: new Param() }) }
createBufferSource() {
const node = Object.assign(new AudioNode(), {
- playbackRate: new Param(), stopped: false, start() {}, stop() { this.stopped = true }
+ playbackRate: new Param(), stopped: false, started: null,
+ start(...args) { this.started = args }, stop() { this.stopped = true }
})
this.sources.push(node)
return node
@@ -117,9 +118,12 @@ test('pitch 0 keeps master wired straight to destination', () => {
assert.equal(engine.pitch(), 0)
})
-test('non-zero pitch routes master through the shifter and offsets the clock', async () => {
+test('non-zero pitch routes master through the shifter and jumps the clock ahead', async () => {
const { calls, factory } = instant()
const { engine, ctx, master } = playing(factory)
+ // mid-playback: 1 s after the first sample became audible
+ ctx.currentTime = 1.04 + 1
+ assert.ok(Math.abs(engine.expected() - 6) < 1e-9)
await engine.setPitch(-3)
const { shifter } = calls[0]
assert.equal(master.outputs.length, 1)
@@ -127,14 +131,27 @@ test('non-zero pitch routes master through the shifter and offsets the clock', a
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)
+ // re-aligned ahead by the start delay plus the shifter's latency, so the
+ // position is where the video will be once the new path is audible
+ const audibleAt = ctx.currentTime + 0.04 + 0.05
+ assert.ok(Math.abs(engine.expected() - (6 + 0.09)) < 1e-9)
+ const [src] = ctx.sources.slice(-2)
+ assert.ok(src.started && Math.abs(src.started[1] - 6.09) < 1e-9, 'sources resume ahead')
+ ctx.currentTime = audibleAt + 1
+ assert.ok(Math.abs(engine.expected() - 7.09) < 1e-9)
+})
+
+test('a 0 -> n -> 0 round trip while playing does not leave the clock behind the wall clock', async () => {
+ const { factory } = instant()
+ const { engine, ctx } = playing(factory)
+ const audibleAt = ctx.currentTime + 0.04
+ ctx.currentTime = 2
+ await engine.setPitch(3)
+ ctx.currentTime = 3
+ await engine.setPitch(0)
+ ctx.currentTime = 4
+ const wall = 5 + (ctx.currentTime - audibleAt)
+ assert.ok(Math.abs(engine.expected() - wall) < 0.005, `expected ${engine.expected()} ~ ${wall}`)
})
test('back to 0 restores bypass', async () => {
@@ -186,18 +203,33 @@ test('factory failure leaves audio in bypass', async () => {
assert.equal(engine.pitchError, 'Pitch shifter failed to load')
})
-test('pitch set before the audio context exists applies once playback starts', async () => {
+test('pitch set before the audio context exists loads the shifter while paused', async () => {
const { calls, factory } = instant()
const engine = new StemEngine(factory)
engine.setBuffers(buffers)
await engine.setPitch(-2)
- assert.equal(calls.length, 0)
+ assert.equal(calls.length, 1, 'the shifter loads before the first play')
+ assert.equal(engine.pitch(), -2)
+ const ctx = Context.last
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)
+ // routed from the first align: no re-route restarted the sources
+ assert.equal(ctx.sources.length, 2)
+ assert.ok(ctx.sources.every((s) => !s.stopped))
+ const master = nodes(ctx.sources[0]).master
+ assert.deepEqual(master.outputs, [calls[0].shifter.input])
+ assert.equal(calls.length, 1)
+})
+
+test('returning to 0 clears a previous load error', async () => {
+ const { calls, factory } = fakeFactory()
+ const { engine } = playing(factory)
+ const first = engine.setPitch(2)
+ calls[0].reject(new Error('Pitch shifter failed to load'))
+ await first
+ assert.equal(engine.pitchError, 'Pitch shifter failed to load')
+ await engine.setPitch(0)
+ assert.equal(engine.pitchError, null)
})
test('a failed load can be retried by pressing again', async () => {