Skip to content

Split any YouTube song into stems

TypeScript

feat: add wav encoder and export render helpers

David Navia1707b8356a93
diff --git a/scripts/run.cjs b/scripts/run.cjs
index afa3b90..d382814 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']],
+ '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']],
// 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/lib/render-math.ts b/src/renderer/src/lib/render-math.ts
new file mode 100644
index 0000000..ddac689
--- /dev/null
+++ b/src/renderer/src/lib/render-math.ts
@@ -0,0 +1,28 @@
+// Pure helpers for offline export rendering. No DOM types, so node:test can import it.
+
+export function renderLength(durations: number[], sampleRate: number): number {
+ return Math.ceil(Math.max(...durations) * sampleRate)
+}
+
+// Drops the shifter's start-up latency and pads with silence if the render ran short.
+export function trimLatency(
+ channels: Float32Array[],
+ latencySamples: number,
+ length: number
+): Float32Array[] {
+ return channels.map((ch) => {
+ const out = new Float32Array(length)
+ out.set(ch.subarray(latencySamples, latencySamples + length))
+ return out
+ })
+}
+
+// Scales in place only when the mix would clip; returns the gain applied.
+export function limitPeak(channels: Float32Array[], ceiling = 0.98855): number {
+ let peak = 0
+ for (const ch of channels) for (let i = 0; i < ch.length; i++) peak = Math.max(peak, Math.abs(ch[i]))
+ if (peak <= 1) return 1
+ const gain = ceiling / peak
+ for (const ch of channels) for (let i = 0; i < ch.length; i++) ch[i] *= gain
+ return gain
+}
diff --git a/src/shared/wav.ts b/src/shared/wav.ts
new file mode 100644
index 0000000..36accab
--- /dev/null
+++ b/src/shared/wav.ts
@@ -0,0 +1,33 @@
+// Same layout as save_wav_f32 in python/separate.py: 32-bit float PCM
+// (format tag 3), little-endian, interleaved.
+export function encodeWavF32(channels: Float32Array[], sampleRate: number): Uint8Array {
+ const nch = channels.length
+ const frames = nch ? channels[0].length : 0
+ const dataBytes = frames * nch * 4
+ const out = new Uint8Array(44 + dataBytes)
+ const view = new DataView(out.buffer)
+ const tag = (off: number, s: string): void => {
+ for (let i = 0; i < 4; i++) out[off + i] = s.charCodeAt(i)
+ }
+ tag(0, 'RIFF')
+ view.setUint32(4, 36 + dataBytes, true)
+ tag(8, 'WAVE')
+ tag(12, 'fmt ')
+ view.setUint32(16, 16, true)
+ view.setUint16(20, 3, true)
+ view.setUint16(22, nch, true)
+ view.setUint32(24, sampleRate, true)
+ view.setUint32(28, sampleRate * nch * 4, true)
+ view.setUint16(32, nch * 4, true)
+ view.setUint16(34, 32, true)
+ tag(36, 'data')
+ view.setUint32(40, dataBytes, true)
+ let off = 44
+ for (let i = 0; i < frames; i++) {
+ for (let c = 0; c < nch; c++) {
+ view.setFloat32(off, channels[c][i], true)
+ off += 4
+ }
+ }
+ return out
+}
diff --git a/tests/export-audio.test.mjs b/tests/export-audio.test.mjs
new file mode 100644
index 0000000..afa4336
--- /dev/null
+++ b/tests/export-audio.test.mjs
@@ -0,0 +1,64 @@
+import { test, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { registerTsHooks } from './helpers/ts-resolve.mjs'
+import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+const root = mkdtempSync(join(tmpdir(), 'stemkit-export-'))
+after(() => rmSync(root, { recursive: true, force: true }))
+const hooks = registerTsHooks({ stubEnv: `export const userDataDir = () => ${JSON.stringify(root)}` })
+const { wavDuration } = await import(new URL('../src/main/library.ts', import.meta.url).href)
+const { encodeWavF32 } = await import(new URL('../src/shared/wav.ts', import.meta.url).href)
+const { renderLength, trimLatency, limitPeak } = await import(
+ new URL('../src/renderer/src/lib/render-math.ts', import.meta.url).href
+)
+hooks.deregister()
+
+test('encodeWavF32 writes a float32 RIFF file that wavDuration and a reader accept', () => {
+ const left = Float32Array.from([0.25, -0.5, 1])
+ const right = Float32Array.from([0, 0.5, -1])
+ const bytes = encodeWavF32([left, right], 44100)
+ assert.equal(bytes.length, 44 + 24)
+ const file = join(root, 'a.wav')
+ writeFileSync(file, bytes)
+ // wavDuration returns whole seconds, so check it on a 2 s file rather than the 3-sample one
+ const long = join(root, 'long.wav')
+ writeFileSync(long, encodeWavF32([new Float32Array(88200), new Float32Array(88200)], 44100))
+ assert.equal(wavDuration(long), 2)
+ const buf = readFileSync(file)
+ assert.equal(buf.toString('ascii', 0, 4), 'RIFF')
+ assert.equal(buf.readUInt32LE(4), buf.length - 8)
+ assert.equal(buf.readUInt32LE(16), 16)
+ assert.equal(buf.readUInt16LE(20), 3)
+ assert.equal(buf.readUInt16LE(22), 2)
+ assert.equal(buf.readUInt32LE(24), 44100)
+ assert.equal(buf.readUInt32LE(28), 44100 * 8)
+ assert.equal(buf.readUInt16LE(32), 8)
+ assert.equal(buf.readUInt16LE(34), 32)
+ assert.equal(buf.toString('ascii', 36, 40), 'data')
+ assert.equal(buf.readUInt32LE(40), 24)
+ const got = []
+ for (let i = 0; i < 6; i++) got.push(buf.readFloatLE(44 + i * 4))
+ assert.deepEqual(got, [0.25, 0, -0.5, 0.5, 1, -1])
+})
+
+test('renderLength rounds the longest duration up to whole samples', () => {
+ assert.equal(renderLength([10, 10.02], 44100), 441882)
+})
+
+test('trimLatency drops leading latency and zero-pads a short tail', () => {
+ const ch = [Float32Array.from([0, 0, 1, 2, 3, 4])]
+ assert.deepEqual(Array.from(trimLatency(ch, 2, 3)[0]), [1, 2, 3])
+ assert.deepEqual(Array.from(trimLatency(ch, 2, 5)[0]), [1, 2, 3, 4, 0])
+})
+
+test('limitPeak scales only when the peak exceeds 1', () => {
+ const loud = [Float32Array.from([2, -1]), Float32Array.from([0.5, 0])]
+ const gain = limitPeak(loud)
+ assert.ok(Math.abs(gain - 0.98855 / 2) < 1e-6)
+ assert.ok(Math.abs(loud[0][0] - 0.98855) < 1e-6)
+ const quiet = [Float32Array.from([0.5, -0.25])]
+ assert.equal(limitPeak(quiet), 1)
+ assert.deepEqual(Array.from(quiet[0]), [0.5, -0.25])
+})