Split any YouTube song into stems
TypeScript
fix(export): decode export sources at 44.1 kHz from the stored files
David Navia1705de2e9770
diff --git a/scripts/run.cjs b/scripts/run.cjsindex c04d842..3765f01 100644--- a/scripts/run.cjs+++ b/scripts/run.cjs@@ -73,7 +73,7 @@ function findNode(requiredMajor) {}const STEPS = {- 'test:audio': [['node', '--experimental-strip-types', '--test', 'tests/engine.test.mjs', 'tests/pan-storage.test.mjs', 'tests/keys.test.mjs', 'tests/key-storage.test.mjs', 'tests/pitch.test.mjs', 'tests/pitch-storage.test.mjs', 'tests/export-audio.test.mjs', 'tests/export-rules.test.mjs', 'tests/export-session.test.mjs']],+ 'test:audio': [['node', '--experimental-strip-types', '--test', 'tests/engine.test.mjs', 'tests/pan-storage.test.mjs', 'tests/keys.test.mjs', 'tests/key-storage.test.mjs', 'tests/pitch.test.mjs', 'tests/pitch-storage.test.mjs', 'tests/export-audio.test.mjs', 'tests/export-rules.test.mjs', 'tests/export-session.test.mjs', 'tests/exporter.test.mjs']],// STEMKIT_PY points at an interpreter that has numpy (e.g. the dev venv)'test:py': [[process.env.STEMKIT_PY || (IS_WIN ? 'python' : 'python3'), '-m', 'unittest', 'discover', '-s', 'python/tests', '-v']],dev: [['electron-vite', 'dev']],diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsxindex 14ce2d6..7d4641c 100644--- a/src/renderer/src/components/Player.tsx+++ b/src/renderer/src/components/Player.tsx@@ -373,7 +373,6 @@ export function Player({ song, settings }: Props): React.ReactElement {title: song.title,stems: stemMeta.map((s) => s.id),selected: [...selected],- buffers,vols,pans,semitones: shifted ? semitones : 0diff --git a/src/renderer/src/lib/exporter.ts b/src/renderer/src/lib/exporter.tsindex 5df3308..f11d124 100644--- a/src/renderer/src/lib/exporter.ts+++ b/src/renderer/src/lib/exporter.ts@@ -4,7 +4,6 @@ import { MIX_ID, mixedBaseName, separateFolderName } from '../../../shared/exporimport { limitPeak, renderLength, trimLatency } from './render-math'import { createPitchShifter } from './pitch'import type { PitchShifter, ShifterFactory } from './pitch'-import { decodePayload, type BufferMap } from './engine'const SAMPLE_RATE = 44100@@ -76,18 +75,31 @@ export interface ExportOptions {// every stem id of the song, in display order (never MIX_ID)stems: string[]selected: string[]- buffers: BufferMapvols: Partial<Record<StemId, number>>pans: StemPanMap// 0 exports at the original pitchsemitones: number}-function stemSource(opts: ExportOptions, id: string): RenderSource {- const buffer = opts.buffers[id as StemId]- if (!buffer) throw new Error(`Missing audio for ${id}`)+// The player's buffers come from an AudioContext at the device rate (often+// 48 kHz), so rendering those at 44.1 kHz would resample twice. Stems are+// stored at 44.1 kHz: decoding the raw file at that rate keeps every sample.+function decodeAtExportRate(bytes: Uint8Array): Promise<AudioBuffer> {+ // decodeAudioData detaches the bytes, which are a throwaway IPC copy+ return new OfflineAudioContext(2, 1, SAMPLE_RATE).decodeAudioData(bytes.buffer as ArrayBuffer)+}++async function stemSource(+ opts: ExportOptions,+ payload: Record<string, Uint8Array>,+ id: string+): Promise<RenderSource> {+ const bytes = payload[id]+ if (!bytes) throw new Error(`Missing audio for ${id}`)+ // drop the reference so the bytes can go once decoded+ delete payload[id]return {- buffer,+ buffer: await decodeAtExportRate(bytes),gain: opts.vols[id as StemId] ?? 1,pan: opts.pans[id as StemId] ?? 0}@@ -107,10 +119,10 @@ export async function exportMixed(opts: ExportOptions): Promise<string | null> {)if (!session) return nulltry {- const channels = await renderOffline(- ids.map((id) => stemSource(opts, id)),- opts.semitones- )+ const payload = await window.stemkit.getBuffers(opts.videoId)+ const sources: RenderSource[] = []+ for (const id of ids) sources.push(await stemSource(opts, payload, id))+ const channels = await renderOffline(sources, opts.semitones)return await window.stemkit.exportWrite(session.token, null, encodeWavF32(channels, SAMPLE_RATE))} finally {await window.stemkit.exportEnd(session.token)@@ -122,6 +134,10 @@ export async function exportSeparate(): Promise<{ path: string; count: number } | null> {const ids = chosenStems(opts)if (ids.length === 0 && !opts.includeMix) throw new Error('Select at least one stem')+ // checked before the picker: a missing mix found after the stems would+ // leave a half-finished folder behind+ const mix = opts.includeMix ? await window.stemkit.getMix(opts.videoId) : null+ if (opts.includeMix && !mix) throw new Error('This song has no original mix to export')const session = await window.stemkit.exportBegin('folder',separateFolderName(opts.title, opts.semitones)@@ -129,19 +145,16 @@ export async function exportSeparate(if (!session) return nulllet count = 0try {- // one at a time: every render holds a full-length stereo copy in memory+ const payload = ids.length > 0 ? await window.stemkit.getBuffers(opts.videoId) : {}+ // one at a time: every decode and render holds a full-length stereo copy in memoryfor (const id of ids) {- const channels = await renderOffline([stemSource(opts, id)], opts.semitones)+ const channels = await renderOffline([await stemSource(opts, payload, id)], opts.semitones)await window.stemkit.exportWrite(session.token, id, encodeWavF32(channels, SAMPLE_RATE))count++}- if (opts.includeMix) {- const payload = await window.stemkit.getMix(opts.videoId)- if (!payload) throw new Error('This song has no original mix to export')- const decoded = await decodePayload({ [MIX_ID]: payload })- const buffer = decoded[MIX_ID as StemId]- if (!buffer) throw new Error('Could not decode the original mix')+ if (mix) {// the original mix ignores the mixer: pitch only, at full volume+ const buffer = await decodeAtExportRate(mix)const channels = await renderOffline([{ buffer, gain: 1, pan: 0 }], opts.semitones)await window.stemkit.exportWrite(session.token, opts.title, encodeWavF32(channels, SAMPLE_RATE))count++diff --git a/tests/exporter.test.mjs b/tests/exporter.test.mjsnew file mode 100644index 0000000..7d6f94b--- /dev/null+++ b/tests/exporter.test.mjs@@ -0,0 +1,107 @@+import { test, beforeEach } from 'node:test'+import assert from 'node:assert/strict'+import { registerTsHooks } from './helpers/ts-resolve.mjs'++const hooks = registerTsHooks()+const { exportMixed, exportSeparate } = await import('../src/renderer/src/lib/exporter.ts')+hooks.deregister()++// A minimal Web Audio stand-in: enough for renderOffline at 0 semitones and for+// decodeAudioData, recording the sample rate each decode ran at.+let log = []+let decoding = 0+let maxConcurrentDecodes = 0++class Node {+ connect(n) { return n }+}+class FakeOfflineContext {+ constructor(channels, length, sampleRate) {+ this.length = length+ this.sampleRate = sampleRate+ this.destination = new Node()+ }+ async decodeAudioData(ab) {+ const tag = new TextDecoder().decode(new Uint8Array(ab))+ decoding+++ maxConcurrentDecodes = Math.max(maxConcurrentDecodes, decoding)+ log.push(`decode:${tag}@${this.sampleRate}`)+ await new Promise((r) => setTimeout(r, 1))+ decoding--+ return { duration: 0.001, tag }+ }+ createBufferSource() { return Object.assign(new Node(), { start() {} }) }+ createGain() { return Object.assign(new Node(), { gain: { value: 1 } }) }+ createStereoPanner() { return Object.assign(new Node(), { pan: { value: 0 } }) }+ async startRendering() {+ const data = [new Float32Array(this.length), new Float32Array(this.length)]+ return { getChannelData: (c) => data[c] }+ }+}+globalThis.OfflineAudioContext = FakeOfflineContext++const bytes = (s) => new TextEncoder().encode(s)+let mixPayload = bytes('mix')++beforeEach(() => {+ log = []+ maxConcurrentDecodes = 0+ mixPayload = bytes('mix')+ globalThis.window = {+ stemkit: {+ getBuffers: async () => {+ log.push('getBuffers')+ return { vocals: bytes('vocals'), drums: bytes('drums'), bass: bytes('bass'), other: bytes('other') }+ },+ getMix: async () => {+ log.push('getMix')+ return mixPayload+ },+ exportBegin: async (kind) => {+ log.push(`begin:${kind}`)+ return { token: 't', path: '/out' }+ },+ exportWrite: async (_t, name) => {+ log.push(`write:${name}`)+ return '/out/x.wav'+ },+ exportEnd: async () => { log.push('end') }+ }+ }+})++const base = {+ videoId: 'v',+ title: 'Song',+ stems: ['vocals', 'drums', 'bass', 'other'],+ vols: {},+ pans: {},+ semitones: 0+}++test('exportMixed decodes only the checked stems from the raw payload at 44.1 kHz', async () => {+ await exportMixed({ ...base, selected: ['bass', 'drums'] })+ const decodes = log.filter((l) => l.startsWith('decode:'))+ assert.deepEqual(decodes.sort(), ['decode:bass@44100', 'decode:drums@44100'])+ assert.deepEqual(log.filter((l) => l.startsWith('write:')), ['write:null'])+})++test('exportSeparate decodes one stem at a time, each written before the next decode', async () => {+ await exportSeparate({ ...base, selected: ['drums', 'bass', 'mix'], includeMix: true })+ assert.equal(maxConcurrentDecodes, 1)+ const steps = log.filter((l) => l.startsWith('decode:') || l.startsWith('write:'))+ assert.deepEqual(steps, [+ 'decode:drums@44100', 'write:drums',+ 'decode:bass@44100', 'write:bass',+ 'decode:mix@44100', 'write:Song'+ ])+})++test('exportSeparate with a missing original mix fails before opening a session or writing', async () => {+ mixPayload = null+ await assert.rejects(+ exportSeparate({ ...base, selected: ['drums', 'mix'], includeMix: true }),+ /no original mix/i+ )+ assert.equal(log.some((l) => l.startsWith('begin') || l.startsWith('write')), false)+})