Skip to content

Split any YouTube song into stems

TypeScript

feat: detect and store song key after separation

David Naviaffe8978638cb
diff --git a/scripts/run.cjs b/scripts/run.cjs
index 7e3376d..28a1b9a 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']],
+ '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']],
dev: [['electron-vite', 'dev']],
build: [['electron-vite', 'build']],
typecheck: [
diff --git a/src/main/env.ts b/src/main/env.ts
index 3c80bd7..ca4da4f 100644
--- a/src/main/env.ts
+++ b/src/main/env.ts
@@ -114,6 +114,13 @@ export function separateScript(): string {
return join(app.getAppPath(), 'python', 'separate.py')
}
+export function keyScript(): string {
+ if (app.isPackaged) {
+ return join(process.resourcesPath, 'python', 'key.py')
+ }
+ return join(app.getAppPath(), 'python', 'key.py')
+}
+
export function roformerScript(): string {
if (app.isPackaged) {
return join(process.resourcesPath, 'python', 'roformer.py')
diff --git a/src/main/index.ts b/src/main/index.ts
index deff363..806f888 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -31,9 +31,10 @@ import {
import { loadSettings, saveSettings } from './settings'
import {
loadSongs, removeSong, clearLibrary, stemBuffers, stemsDir, stemsFor, sanitizeName,
- exportStems, transcodeToAac, loadStemPan, saveStemPan
+ exportStems, transcodeToAac, loadStemPan, saveStemPan, setKeyOverride
} from './library'
import { AUDIO_EXTENSIONS } from '../shared/local'
+import { detectOnce } from './keydetect'
import { startJob, startLocalJob, cancelJob, searchYouTube } from './pipeline'
import { initUpdater } from './updater'
import { runSmoke } from './smoke'
@@ -234,6 +235,10 @@ app.whenReady().then(async () => {
ipcMain.handle('library:list', () => loadSongs())
ipcMain.handle('song:pan:get', (_e, videoId: string) => loadStemPan(videoId))
ipcMain.handle('song:pan:set', (_e, videoId: string, pans: unknown) => saveStemPan(videoId, pans))
+ ipcMain.handle('song:key:detect', (_e, videoId: string) => detectOnce(videoId))
+ ipcMain.handle('song:key:set', (_e, videoId: string, override: string | null) =>
+ setKeyOverride(videoId, override)
+ )
ipcMain.handle('library:delete', (_e, videoId: string) => removeSong(videoId))
ipcMain.handle('library:clear', () => {
// cancel first: a running job would keep writing into the folder we are
diff --git a/src/main/keydetect.ts b/src/main/keydetect.ts
new file mode 100644
index 0000000..53e7ad6
--- /dev/null
+++ b/src/main/keydetect.ts
@@ -0,0 +1,95 @@
+import { spawn } from 'child_process'
+import { existsSync } from 'fs'
+import { join } from 'path'
+import { venvPython, keyScript } from './env'
+import { stemsDir, stemsFor, mixWavPath, loadSongs, patchSongKey } from './library'
+import { acquireSeparation } from './separation-slots'
+import { keyName, type KeyMode } from '../shared/keys'
+import type { SongKey } from '../shared/types'
+
+const TIMEOUT_MS = 120_000
+
+// drums carry no pitch and only blur the chroma, so they are left out; with
+// nothing else on disk the full mix is the fallback
+export function keyInputs(videoId: string, stems: string[]): string[] {
+ const files = stems
+ .filter((s) => s !== 'drums')
+ .map((s) => join(stemsDir(videoId), `${s}.wav`))
+ .filter((f) => existsSync(f))
+ return files.length ? files : [mixWavPath(videoId)]
+}
+
+export function runKeyScript(inputs: string[]): Promise<SongKey> {
+ return new Promise((resolve) => {
+ let settled = false
+ const done = (key: SongKey): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ resolve(key)
+ }
+ let child: ReturnType<typeof spawn> | undefined
+ const timer = setTimeout(() => {
+ child?.kill()
+ done({ detected: null })
+ }, TIMEOUT_MS)
+ try {
+ child = spawn(venvPython(), [keyScript(), ...inputs.flatMap((i) => ['--input', i])], {
+ stdio: ['ignore', 'pipe', 'ignore']
+ })
+ } catch {
+ return done({ detected: null })
+ }
+ let out = ''
+ child.stdout?.on('data', (d: Buffer) => (out += d.toString()))
+ child.on('error', () => done({ detected: null }))
+ child.on('close', (code) => {
+ if (code !== 0) return done({ detected: null })
+ for (const line of out.split('\n')) {
+ try {
+ const msg = JSON.parse(line)
+ if (
+ msg?.type === 'key' &&
+ Number.isInteger(msg.tonic) &&
+ (msg.mode === 'major' || msg.mode === 'minor')
+ ) {
+ return done({
+ detected: keyName(msg.tonic, msg.mode as KeyMode),
+ confidence: Number(msg.confidence)
+ })
+ }
+ } catch {
+ // not a JSON line: ignore
+ }
+ }
+ done({ detected: null })
+ })
+ })
+}
+
+const inflight = new Map<string, Promise<SongKey>>()
+
+export function detectOnce(videoId: string, run = runKeyScript): Promise<SongKey> {
+ const existing = inflight.get(videoId)
+ if (existing) return existing
+ const song = loadSongs().find((s) => s.videoId === videoId)
+ if (!song) return Promise.resolve({ detected: null })
+ // a stored result is final; a stored override-only entry still needs detecting
+ if (song.key?.detected) return Promise.resolve(song.key)
+ const job = (async (): Promise<SongKey> => {
+ const release = await acquireSeparation()
+ try {
+ const result = await run(keyInputs(videoId, stemsFor(song)))
+ if (!result.detected) return song.key ?? result
+ // keep a user override that was set before detection finished
+ const current = loadSongs().find((s) => s.videoId === videoId)?.key
+ const key: SongKey = current?.override ? { ...result, override: current.override } : result
+ patchSongKey(videoId, key)
+ return key
+ } finally {
+ release()
+ }
+ })().finally(() => inflight.delete(videoId))
+ inflight.set(videoId, job)
+ return job
+}
diff --git a/src/main/library.ts b/src/main/library.ts
index 1f8268f..b9a12fa 100644
--- a/src/main/library.ts
+++ b/src/main/library.ts
@@ -3,7 +3,8 @@ import { readFile, cp } from 'fs/promises'
import { spawn } from 'child_process'
import { join } from 'path'
import { userDataDir } from './env'
-import { DEFAULT_STEMS, type Song, type StemPanMap, type StemId } from '../shared/types'
+import { KEY_NAMES } from '../shared/keys'
+import { DEFAULT_STEMS, type Song, type SongKey, type StemPanMap, type StemId } from '../shared/types'
function libraryFile(): string {
return join(userDataDir(), 'library.json')
@@ -51,6 +52,27 @@ export function upsertSong(song: Song): Song[] {
return songs
}
+// rewrites only this song's entry, keeping its place in the list; a song
+// removed while detection ran must not be resurrected, hence null + no write
+export function patchSongKey(videoId: string, key: SongKey): Song | null {
+ const songs = loadSongs()
+ const song = songs.find((s) => s.videoId === videoId)
+ if (!song) return null
+ song.key = key
+ saveSongs(songs)
+ return song
+}
+
+export function setKeyOverride(videoId: string, override: string | null): SongKey {
+ if (override !== null && !KEY_NAMES.includes(override)) throw new Error('Unknown key')
+ const song = loadSongs().find((s) => s.videoId === videoId)
+ if (!song) throw new Error('Unknown song')
+ const { override: _old, ...rest } = song.key ?? { detected: null }
+ const key: SongKey = override === null ? rest : { ...rest, override }
+ patchSongKey(videoId, key)
+ return key
+}
+
export function removeSong(videoId: string): Song[] {
const songs = loadSongs().filter((s) => s.videoId !== videoId)
saveSongs(songs)
diff --git a/src/main/pipeline.ts b/src/main/pipeline.ts
index 4dc05b0..f18994f 100644
--- a/src/main/pipeline.ts
+++ b/src/main/pipeline.ts
@@ -2,7 +2,6 @@ import { spawn, type ChildProcess } from 'child_process'
import { createInterface } from 'readline'
import { readdirSync, mkdirSync, rmSync, statSync } from 'fs'
import { basename, join } from 'path'
-import { totalmem } from 'os'
import { BrowserWindow } from 'electron'
import {
venvPython,
@@ -31,11 +30,13 @@ import {
loadSongs,
wavDuration
} from './library'
-import type { JobEvent, JobStage } from '../shared/types'
+import type { JobEvent, JobStage, SongKey } from '../shared/types'
import { MODEL_DEFAULT, MODEL_EXTENDED } from '../shared/types'
import { parseVideoId } from '../shared/url'
import { AUDIO_EXTENSIONS, audioExtension, localSongId } from '../shared/local'
import { cacheThumbnail } from './thumbs'
+import { acquireSeparation } from './separation-slots'
+import { keyInputs, runKeyScript } from './keydetect'
interface ActiveJob {
videoId: string
@@ -47,33 +48,6 @@ interface ActiveJob {
const jobs = new Map<string, ActiveJob>()
-/* One engine process peaks at a few GB (weights + the whole song on the
- device), so two at once needs real headroom: below 16GB of RAM a second
- concurrent split is what gets the pair killed, which looks like a random
- failure on the second song. Machines with less run one at a time and the
- rest queue. */
-const MAX_CONCURRENT_SEPARATIONS = totalmem() >= 16 * 1024 ** 3 ? 2 : 1
-let activeSeparations = 0
-const separationWaiters: Array<() => void> = []
-
-function acquireSeparation(): Promise<() => void> {
- if (activeSeparations < MAX_CONCURRENT_SEPARATIONS) {
- activeSeparations++
- return Promise.resolve(releaseSeparation)
- }
- return new Promise((resolve) => {
- separationWaiters.push(() => {
- activeSeparations++
- resolve(releaseSeparation)
- })
- })
-}
-
-function releaseSeparation(): void {
- activeSeparations--
- separationWaiters.shift()?.()
-}
-
function send(ev: JobEvent): void {
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send('job:event', ev)
@@ -197,10 +171,22 @@ async function convertToWav(job: ActiveJob, inputPath: string): Promise<void> {
progress(job, 'convert', 100)
}
+// runKeyScript never throws: a failed detection just leaves the song keyless
+async function detectKey(job: ActiveJob, producedStems: string[]): Promise<SongKey> {
+ progress(job, 'finalize', 100, 'Detecting key')
+ const release = await acquireSeparation()
+ try {
+ return await runKeyScript(keyInputs(job.videoId, producedStems))
+ } finally {
+ release()
+ }
+}
+
function finalizeJob(
job: ActiveJob,
info: { title: string; duration: number; addedAt: number; startedAt: number; source?: 'local' },
- producedStems: string[]
+ producedStems: string[],
+ key: SongKey
): void {
progress(job, 'finalize', 100, 'Adding to library')
const took = Math.round((Date.now() - info.startedAt) / 1000)
@@ -212,7 +198,8 @@ function finalizeJob(
model: job.model,
stems: producedStems,
took,
- source: info.source
+ source: info.source,
+ key
})
send({ kind: 'done', data: { videoId: job.videoId, song: songs[0] } })
@@ -334,7 +321,9 @@ export async function startJob(
const producedStems = await runSeparation(job, plan, stems)
if (job.cancelled || !jobs.has(videoId)) return
- finalizeJob(job, { title: meta!.title, duration: meta!.duration, addedAt, startedAt }, producedStems)
+ const key = await detectKey(job, producedStems)
+ if (job.cancelled || !jobs.has(videoId)) return
+ finalizeJob(job, { title: meta!.title, duration: meta!.duration, addedAt, startedAt }, producedStems, key)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
if (message !== 'cancelled') {
@@ -399,7 +388,9 @@ export async function startLocalJob(
const producedStems = await runSeparation(job, plan, stems)
if (job.cancelled || !jobs.has(videoId)) return
- finalizeJob(job, { title, duration, addedAt, startedAt, source: 'local' }, producedStems)
+ const key = await detectKey(job, producedStems)
+ if (job.cancelled || !jobs.has(videoId)) return
+ finalizeJob(job, { title, duration, addedAt, startedAt, source: 'local' }, producedStems, key)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
if (message !== 'cancelled') {
diff --git a/src/main/separation-slots.ts b/src/main/separation-slots.ts
new file mode 100644
index 0000000..a14ad66
--- /dev/null
+++ b/src/main/separation-slots.ts
@@ -0,0 +1,29 @@
+import { totalmem } from 'os'
+
+/* One engine process peaks at a few GB (weights + the whole song on the
+ device), so two at once needs real headroom: below 16GB of RAM a second
+ concurrent split is what gets the pair killed, which looks like a random
+ failure on the second song. Machines with less run one at a time and the
+ rest queue. Lives apart from pipeline.ts so key detection can share the
+ slots without importing electron. */
+const MAX_CONCURRENT_SEPARATIONS = totalmem() >= 16 * 1024 ** 3 ? 2 : 1
+let activeSeparations = 0
+const separationWaiters: Array<() => void> = []
+
+export function acquireSeparation(): Promise<() => void> {
+ if (activeSeparations < MAX_CONCURRENT_SEPARATIONS) {
+ activeSeparations++
+ return Promise.resolve(releaseSeparation)
+ }
+ return new Promise((resolve) => {
+ separationWaiters.push(() => {
+ activeSeparations++
+ resolve(releaseSeparation)
+ })
+ })
+}
+
+function releaseSeparation(): void {
+ activeSeparations--
+ separationWaiters.shift()?.()
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ede7a29..e03a34f 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -18,6 +18,8 @@ const api: StemKitApi = {
clearLibrary: () => ipcRenderer.invoke('library:clear'),
getBuffers: (videoId) => ipcRenderer.invoke('song:buffers', videoId),
getStemPan: (videoId) => ipcRenderer.invoke('song:pan:get', videoId),
+ detectKey: (videoId) => ipcRenderer.invoke('song:key:detect', videoId),
+ setKeyOverride: (videoId, override) => ipcRenderer.invoke('song:key:set', videoId, override),
setStemPan: (videoId, pans) => ipcRenderer.invoke('song:pan:set', videoId, pans),
exportStem: (videoId, stem) => ipcRenderer.invoke('stem:export', videoId, stem),
exportAllStems: (videoId) => ipcRenderer.invoke('stems:export-all', videoId),
diff --git a/src/shared/types.ts b/src/shared/types.ts
index b5ed129..a83a466 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -11,6 +11,12 @@ export const DEFAULT_STEMS: string[] = ['vocals', 'drums', 'bass', 'other']
export const MODEL_DEFAULT = 'roformer_hybrid'
export const MODEL_EXTENDED = 'htdemucs_6s'
+export interface SongKey {
+ detected: string | null
+ override?: string
+ confidence?: number
+}
+
export interface Song {
videoId: string
title: string
@@ -21,6 +27,7 @@ export interface Song {
took?: number
// local audio files carry their own mix; absent means a YouTube source
source?: 'local'
+ key?: SongKey
}
export interface AppSettings {
@@ -130,6 +137,8 @@ export interface StemKitApi {
clearLibrary(): Promise<void>
getBuffers(videoId: string): Promise<Record<string, Uint8Array>>
getStemPan(videoId: string): Promise<StemPanMap>
+ detectKey(videoId: string): Promise<SongKey>
+ setKeyOverride(videoId: string, override: string | null): Promise<SongKey>
setStemPan(videoId: string, pans: StemPanMap): Promise<void>
exportStem(videoId: string, stem: string): Promise<{ saved: boolean; path?: string }>
exportAllStems(videoId: string): Promise<{ saved: boolean; path?: string; count?: number }>
diff --git a/tests/key-storage.test.mjs b/tests/key-storage.test.mjs
new file mode 100644
index 0000000..e6c48cf
--- /dev/null
+++ b/tests/key-storage.test.mjs
@@ -0,0 +1,92 @@
+import { test, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { registerHooks } from 'node:module'
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+const root = mkdtempSync(join(tmpdir(), 'stemkit-key-'))
+after(() => rmSync(root, { recursive: true, force: true }))
+const src = (f) => new URL(`../src/main/${f}`, import.meta.url).href
+const parents = new Set([src('library.ts'), src('keydetect.ts')])
+const envStub = `export const userDataDir = () => ${JSON.stringify(root)}
+export const venvPython = () => 'python3'
+export const keyScript = () => 'key.py'`
+const hooks = registerHooks({
+ resolve(specifier, context, next) {
+ if (parents.has(context.parentURL) && specifier === './env') {
+ return { shortCircuit: true, url: `data:text/javascript,${encodeURIComponent(envStub)}` }
+ }
+ if (parents.has(context.parentURL) && specifier === '../shared/types') {
+ return { shortCircuit: true, url: new URL('../src/shared/types.ts', import.meta.url).href }
+ }
+ if (parents.has(context.parentURL) && specifier === '../shared/keys') {
+ return { shortCircuit: true, url: new URL('../src/shared/keys.ts', import.meta.url).href }
+ }
+ if (context.parentURL === src('keydetect.ts') && specifier === './library') {
+ return { shortCircuit: true, url: src('library.ts') }
+ }
+ if (context.parentURL === src('keydetect.ts') && specifier === './separation-slots') {
+ return { shortCircuit: true, url: src('separation-slots.ts') }
+ }
+ return next(specifier, context)
+ }
+})
+const { saveSongs, loadSongs, patchSongKey, setKeyOverride } = await import(src('library.ts'))
+const { keyInputs, detectOnce } = await import(src('keydetect.ts'))
+hooks.deregister()
+
+const mk = (id) => ({ videoId: id, stems: ['vocals', 'drums', 'bass'], title: id, duration: 10, addedAt: 1 })
+const libPath = join(root, 'library.json')
+
+test('patchSongKey rewrites only that song; missing song is a no-op', () => {
+ saveSongs([mk('a'), mk('b')])
+ const key = { detected: 'Am', confidence: 0.8 }
+ const out = patchSongKey('b', key)
+ assert.deepEqual(out.key, key)
+ const songs = loadSongs()
+ assert.deepEqual(songs.find((s) => s.videoId === 'b').key, key)
+ assert.equal(songs.find((s) => s.videoId === 'a').key, undefined)
+ const before = readFileSync(libPath, 'utf8')
+ assert.equal(patchSongKey('missing', key), null)
+ assert.equal(readFileSync(libPath, 'utf8'), before)
+})
+
+test('setKeyOverride validates, stores and clears while keeping detected', () => {
+ saveSongs([{ ...mk('a'), key: { detected: 'Am', confidence: 0.5 } }])
+ assert.deepEqual(setKeyOverride('a', 'F♯m'), { detected: 'Am', confidence: 0.5, override: 'F♯m' })
+ assert.equal(loadSongs()[0].key.override, 'F♯m')
+ assert.throws(() => setKeyOverride('a', 'Zm'), /Unknown key/)
+ const cleared = setKeyOverride('a', null)
+ assert.equal('override' in cleared, false)
+ assert.equal(loadSongs()[0].key.detected, 'Am')
+})
+
+test('keyInputs skips drums and falls back to the mix', () => {
+ mkdirSync(join(root, 'songs', 'k', 'stems'), { recursive: true })
+ for (const s of ['vocals', 'drums', 'bass']) writeFileSync(join(root, 'songs', 'k', 'stems', `${s}.wav`), '')
+ assert.deepEqual(keyInputs('k', ['vocals', 'drums', 'bass']), [
+ join(root, 'songs', 'k', 'stems', 'vocals.wav'),
+ join(root, 'songs', 'k', 'stems', 'bass.wav')
+ ])
+ assert.deepEqual(keyInputs('k', ['drums']), [join(root, 'songs', 'k', 'mix.wav')])
+})
+
+test('detectOnce dedupes concurrent calls, caches, and skips unknown songs', async () => {
+ saveSongs([mk('c')])
+ mkdirSync(join(root, 'songs', 'c'), { recursive: true })
+ let calls = 0
+ const run = async () => {
+ calls++
+ await new Promise((r) => setTimeout(r, 20))
+ return { detected: 'C', confidence: 0.9 }
+ }
+ const [x, y] = await Promise.all([detectOnce('c', run), detectOnce('c', run)])
+ assert.equal(calls, 1)
+ assert.deepEqual(x, { detected: 'C', confidence: 0.9 })
+ assert.deepEqual(y, x)
+ assert.deepEqual(await detectOnce('c', run), x)
+ assert.equal(calls, 1)
+ assert.deepEqual(await detectOnce('nope', run), { detected: null })
+ assert.equal(calls, 1)
+})
diff --git a/tests/pan-storage.test.mjs b/tests/pan-storage.test.mjs
index 9d2657d..f37a6fe 100644
--- a/tests/pan-storage.test.mjs
+++ b/tests/pan-storage.test.mjs
@@ -16,6 +16,9 @@ const hooks = registerHooks({
if (context.parentURL === libraryUrl && specifier === '../shared/types') {
return { shortCircuit: true, url: new URL('../src/shared/types.ts', import.meta.url).href }
}
+ if (context.parentURL === libraryUrl && specifier === '../shared/keys') {
+ return { shortCircuit: true, url: new URL('../src/shared/keys.ts', import.meta.url).href }
+ }
return next(specifier, context)
}
})