Split any YouTube song into stems
TypeScript
feat: persist pitch shift per song
David Naviafb6d11b9ec31
diff --git a/scripts/run.cjs b/scripts/run.cjsindex 6f15a64..afa3b90 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']],+ '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']],// 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/main/index.ts b/src/main/index.tsindex 40e9380..adba98f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -31,7 +31,7 @@ import {import { loadSettings, saveSettings } from './settings'import {loadSongs, removeSong, clearLibrary, stemBuffers, stemsDir, stemsFor, sanitizeName,- exportStems, transcodeToAac, loadStemPan, saveStemPan, setKeyOverride+ exportStems, transcodeToAac, loadStemPan, saveStemPan, loadPitch, savePitch, setKeyOverride} from './library'import { AUDIO_EXTENSIONS } from '../shared/local'import { detectOnce } from './keydetect'@@ -235,6 +235,8 @@ 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:pitch:get', (_e, videoId: string) => loadPitch(videoId))+ ipcMain.handle('song:pitch:set', (_e, videoId: string, semitones: unknown) => savePitch(videoId, semitones))ipcMain.handle('song:key:detect', (_e, videoId: string, force?: unknown) =>detectOnce(videoId, undefined, { force: force === true }))diff --git a/src/main/library.ts b/src/main/library.tsindex b9a12fa..eb15cc2 100644--- a/src/main/library.ts+++ b/src/main/library.ts@@ -4,6 +4,7 @@ import { spawn } from 'child_process'import { join } from 'path'import { userDataDir } from './env'import { KEY_NAMES } from '../shared/keys'+import { clampPitch } from '../shared/pitch-range'import { DEFAULT_STEMS, type Song, type SongKey, type StemPanMap, type StemId } from '../shared/types'function libraryFile(): string {@@ -185,6 +186,21 @@ export function saveStemPan(videoId: string, pans: unknown): void {writeFileSync(join(songDir(videoId), 'pan.json'), JSON.stringify(normalizePan(song, pans), null, 2))}+export function loadPitch(videoId: string): number {+ panSong(videoId)+ try {+ return clampPitch(JSON.parse(readFileSync(join(songDir(videoId), 'pitch.json'), 'utf8')).semitones)+ } catch {+ return 0+ }+}++export function savePitch(videoId: string, semitones: unknown): void {+ panSong(videoId)+ // Do not recreate a deleted song directory for a late player save.+ writeFileSync(join(songDir(videoId), 'pitch.json'), JSON.stringify({ semitones: clampPitch(semitones) }, null, 2))+}+export function stemsPresent(videoId: string, stems: string[]): boolean {const dir = stemsDir(videoId)if (!existsSync(dir)) return falsediff --git a/src/preload/index.ts b/src/preload/index.tsindex be6bbb9..6035e23 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -21,6 +21,8 @@ const api: StemKitApi = {detectKey: (videoId, force) => ipcRenderer.invoke('song:key:detect', videoId, force === true),setKeyOverride: (videoId, override) => ipcRenderer.invoke('song:key:set', videoId, override),setStemPan: (videoId, pans) => ipcRenderer.invoke('song:pan:set', videoId, pans),+ getPitch: (videoId) => ipcRenderer.invoke('song:pitch:get', videoId),+ setPitch: (videoId, semitones) => ipcRenderer.invoke('song:pitch:set', videoId, semitones),exportStem: (videoId, stem) => ipcRenderer.invoke('stem:export', videoId, stem),exportAllStems: (videoId) => ipcRenderer.invoke('stems:export-all', videoId),searchYouTube: (query) => ipcRenderer.invoke('search:youtube', query),diff --git a/src/shared/types.ts b/src/shared/types.tsindex f89c72d..70a3047 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -140,6 +140,8 @@ export interface StemKitApi {detectKey(videoId: string, force?: boolean): Promise<SongKey>setKeyOverride(videoId: string, override: string | null): Promise<SongKey>setStemPan(videoId: string, pans: StemPanMap): Promise<void>+ getPitch(videoId: string): Promise<number>+ setPitch(videoId: string, semitones: number): Promise<void>exportStem(videoId: string, stem: string): Promise<{ saved: boolean; path?: string }>exportAllStems(videoId: string): Promise<{ saved: boolean; path?: string; count?: number }>searchYouTube(query: string): Promise<SearchResult[]>diff --git a/tests/key-storage.test.mjs b/tests/key-storage.test.mjsindex bda2d43..90d06a2 100644--- a/tests/key-storage.test.mjs+++ b/tests/key-storage.test.mjs@@ -29,6 +29,9 @@ const hooks = registerHooks({if (context.parentURL === src('keydetect.ts') && specifier === './separation-slots') {return { shortCircuit: true, url: src('separation-slots.ts') }}+ if (parents.has(context.parentURL) && specifier === '../shared/pitch-range') {+ return { shortCircuit: true, url: new URL('../src/shared/pitch-range.ts', import.meta.url).href }+ }return next(specifier, context)}})diff --git a/tests/pan-storage.test.mjs b/tests/pan-storage.test.mjsindex f37a6fe..14c4809 100644--- a/tests/pan-storage.test.mjs+++ b/tests/pan-storage.test.mjs@@ -19,6 +19,9 @@ const hooks = registerHooks({if (context.parentURL === libraryUrl && specifier === '../shared/keys') {return { shortCircuit: true, url: new URL('../src/shared/keys.ts', import.meta.url).href }}+ if (context.parentURL === libraryUrl && specifier === '../shared/pitch-range') {+ return { shortCircuit: true, url: new URL('../src/shared/pitch-range.ts', import.meta.url).href }+ }return next(specifier, context)}})diff --git a/tests/pitch-storage.test.mjs b/tests/pitch-storage.test.mjsnew file mode 100644index 0000000..efdd665--- /dev/null+++ b/tests/pitch-storage.test.mjs@@ -0,0 +1,49 @@+import { test, after } from 'node:test'+import assert from 'node:assert/strict'+import { registerHooks } from 'node:module'+import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++const root = mkdtempSync(join(tmpdir(), 'stemkit-pitch-'))+after(() => rmSync(root, { recursive: true, force: true }))+const libraryUrl = new URL('../src/main/library.ts', import.meta.url).href+const hooks = registerHooks({+ resolve(specifier, context, next) {+ if (context.parentURL === libraryUrl && specifier === './env') {+ return { shortCircuit: true, url: `data:text/javascript,${encodeURIComponent(`export const userDataDir = () => ${JSON.stringify(root)}`)}` }+ }+ 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 }+ }+ if (context.parentURL === libraryUrl && specifier === '../shared/pitch-range') {+ return { shortCircuit: true, url: new URL('../src/shared/pitch-range.ts', import.meta.url).href }+ }+ return next(specifier, context)+ }+})+const { saveSongs, loadPitch, savePitch, removeSong } = await import(libraryUrl)+hooks.deregister()+const song = { videoId: 'song-one', stems: ['vocals', 'drums'], title: 'Test', duration: 10, addedAt: 1 }++test('pitch persists per song, clamps, tolerates missing/corrupt files, deletes with song', () => {+ saveSongs([song, { ...song, videoId: 'song-two' }])+ mkdirSync(join(root, 'songs', song.videoId), { recursive: true })+ assert.equal(loadPitch(song.videoId), 0)+ savePitch(song.videoId, -3)+ assert.equal(loadPitch(song.videoId), -3)+ assert.equal(loadPitch('song-two'), 0)+ writeFileSync(join(root, 'songs', song.videoId, 'pitch.json'), '{"semitones":40}')+ assert.equal(loadPitch(song.videoId), 6)+ writeFileSync(join(root, 'songs', song.videoId, 'pitch.json'), '{broken')+ assert.equal(loadPitch(song.videoId), 0)+ assert.throws(() => savePitch('../escape', 1), /Unknown song/)+ assert.throws(() => loadPitch('../escape'), /Unknown song/)+ removeSong(song.videoId)+ assert.equal(existsSync(join(root, 'songs', song.videoId)), false)+ assert.throws(() => savePitch(song.videoId, 2), /Unknown song/)+ assert.equal(existsSync(join(root, 'songs', song.videoId)), false)+})