Split any YouTube song into stems
TypeScript
feat: drag-and-drop splitting, steady memory across songs, library wipe and auto-export
Anton Sychev5243e23bc617
diff --git a/python/roformer.py b/python/roformer.pyindex b7270ea..52e1bdd 100644--- a/python/roformer.py+++ b/python/roformer.py@@ -1,4 +1,5 @@import argparse+import gcimport jsonimport osimport struct@@ -10,6 +11,22 @@ import waveimport numpy as npimport torch++def release_device_memory(device):+ """torch's caching allocators keep blocks that refcounts already dropped,+ so a fallback that loads a second copy of the engine gets charged for the+ same ram twice — which is how one gpu failure turns into an out-of-memory+ on the retry"""+ try:+ if device == "cuda" and torch.cuda.is_available():+ torch.cuda.empty_cache()+ elif device == "mps" and getattr(torch.backends, "mps", None):+ if torch.backends.mps.is_available():+ torch.mps.empty_cache()+ except Exception:+ pass++CKPT_NAME = "MelBandRoformer.ckpt"CKPT_URL = "https://huggingface.co/KimberleyJSN/melbandroformer/resolve/main/MelBandRoformer.ckpt"@@ -92,16 +109,19 @@ def load_wav(path):def save_wav_f32(path, data, sr):"""write a 32-bit float wav (fmt tag 3); values above 1.0 are preserved"""channels, _ = data.shape- payload = data.T.astype("<f4").tobytes()+ # one transposed contiguous copy written straight from memory: building a+ # bytes payload first would hold a second full copy of the stem in ram+ block = np.ascontiguousarray(data.T, dtype="<f4")+ size = block.nbytesblock_align = channels * 4- header = b"RIFF" + struct.pack("<I", 36 + len(payload)) + b"WAVE"+ header = b"RIFF" + struct.pack("<I", 36 + size) + b"WAVE"header += b"fmt " + struct.pack("<IHHIIHH", 16, 3, channels, sr, sr * block_align, block_align, 32)- header += b"data" + struct.pack("<I", len(payload))+ header += b"data" + struct.pack("<I", size)with open(path, "wb") as f:f.write(header)- f.write(payload)+ block.tofile(f)def download_checkpoint(dest):@@ -163,6 +183,12 @@ def load_model(ckpt_path, device, use_half):if isinstance(ckpt, dict) and "state_dict" in ckpt:ckpt = ckpt["state_dict"]model.load_state_dict(ckpt, strict=True)+ # the checkpoint is a second full copy of the weights sitting next to the+ # model that just consumed them: ~900MB of ram held for nothing through+ # the whole separation, which is often the difference between a split and+ # a kill+ del ckpt+ gc.collect()model.to(device)if use_half:model.half()@@ -261,6 +287,7 @@ def main():if audio.shape[0] == 1:audio = np.repeat(audio, 2, axis=0)mix = torch.from_numpy(audio).to(device)+ del audiolast_emit = 0.0@@ -277,18 +304,31 @@ def main():except Exception as e:if device == "mps":emit(type="progress", stage="separate", pct=0, message=f"gpu failed ({e}), falling back to cpu")+ # drop the gpu copies first: reloading the engine on top of a+ # full cache is how the fallback dies of out-of-memory after a+ # gpu error that was already recoverable+ model = None+ gc.collect()+ mix = mix.to("cpu")+ release_device_memory("mps")device = "cpu"use_half = Falsetry:model = load_model(ckpt_path, device, use_half)except Exception as e2:fail(f"vocals engine load failed on cpu: {e2}")- mix = mix.to("cpu").float()est = separate(model, mix, device, use_half, on_progress)else:fail(f"separation failed: {e}")vocals = est.cpu().numpy()+ # nothing left to compute: hand the engine and the device copies back+ # before spending ram on the wav+ model = None+ mix = None+ est = None+ gc.collect()+ release_device_memory(device)if np.isnan(vocals).any():fail("separation produced invalid audio")os.makedirs(args.out, exist_ok=True)diff --git a/python/separate.py b/python/separate.pyindex 75b44c4..62efde9 100644--- a/python/separate.py+++ b/python/separate.py@@ -1,4 +1,5 @@import argparse+import gcimport jsonimport structimport sys@@ -54,16 +55,19 @@ def load_wav(path):def save_wav_f32(path, data, sr):"""write a 32-bit float wav (fmt tag 3); values above 1.0 are preserved"""channels, _ = data.shape- payload = data.T.astype("<f4").tobytes()+ # one transposed contiguous copy written straight from memory: building a+ # bytes payload first would hold a second full copy of the stem in ram+ block = np.ascontiguousarray(data.T, dtype="<f4")+ size = block.nbytesblock_align = channels * 4- header = b"RIFF" + struct.pack("<I", 36 + len(payload)) + b"WAVE"+ header = b"RIFF" + struct.pack("<I", 36 + size) + b"WAVE"header += b"fmt " + struct.pack("<IHHIIHH", 16, 3, channels, sr, sr * block_align, block_align, 32)- header += b"data" + struct.pack("<I", len(payload))+ header += b"data" + struct.pack("<I", size)with open(path, "wb") as f:f.write(header)- f.write(payload)+ block.tofile(f)def main():@@ -80,6 +84,20 @@ def main():import torchimport types+ def release_device_memory(device):+ """torch's caching allocators keep blocks that refcounts already+ dropped, so a cpu fallback that rebuilds the model gets charged for the+ same ram twice — which is how one device failure turns into an+ out-of-memory on the retry"""+ try:+ if device == "cuda" and torch.cuda.is_available():+ torch.cuda.empty_cache()+ elif device == "mps" and getattr(torch.backends, "mps", None):+ if torch.backends.mps.is_available():+ torch.mps.empty_cache()+ except Exception:+ pass+# torch>=2.6 defaults torch.load(weights_only=True), which rejects demucs's# pickled full-model checkpoints (htdemucs.th / htdemucs_ft.th); restore# the legacy behavior — the weights come from the official demucs releases@@ -175,6 +193,7 @@ def main():audio = np.repeat(audio, 2, axis=0)mix = torch.from_numpy(audio).to(device)[None]+ del audioemit(type="progress", stage="separate", pct=0, message="separating")try:@@ -195,9 +214,14 @@ def main():pct=0,message=f"mps failed ({e}), falling back to cpu",)+ # both rebinds drop the device copies; without the collector and+ # the empty_cache the retry is still charged for them, so a+ # recoverable mps error comes back as an out-of-memorymodel = model.cpu()mix = mix.cpu()device = "cpu"+ gc.collect()+ release_device_memory("mps")sources = apply_model(model,mix,@@ -210,6 +234,8 @@ def main():else:fail(f"separation failed: {e}")+ del mix+import oswanted = None@@ -222,10 +248,18 @@ def main():fail("no valid stems requested")emit(type="progress", stage="separate", pct=0, message=f"writing {len(wanted)} stems")+ names = list(model.sources)os.makedirs(args.out, exist_ok=True)+ # the host copy below is song-length per stem, so the weights and the+ # device-side sources go first: keeping them through the write phase+ # doubles the peak for nothing+ del modelout_cpu = sources[0].cpu().numpy()+ del sources+ gc.collect()+ release_device_memory(device)written = []- for i, name in enumerate(model.sources):+ for i, name in enumerate(names):if wanted is not None and name not in wanted:continuepath = os.path.join(args.out, f"{name}.wav")diff --git a/src/main/env.ts b/src/main/env.tsindex 8ecd392..f188da2 100644--- a/src/main/env.ts+++ b/src/main/env.ts@@ -13,7 +13,10 @@ export interface ToolInfo {export interface EnvState {python: ToolInfo- ffmpeg: ToolInfo+ // ffmpeg builds without libsoxr (some homebrew/conda installs) reject+ // aresample's resampler=soxr with a bare EINVAL, so the pipeline needs to+ // know whether it may ask for it+ ffmpeg: ToolInfo & { soxr?: boolean }jsRuntime?: { kind: 'deno' | 'node'; path: string }ready: booleanbootstrapping: boolean@@ -553,8 +556,12 @@ export async function detectTools(): Promise<void> {for (const candidate of ffProbes) {if (!existsSync(candidate)) continuetry {- await runCapture(candidate, ['-version'])- state.ffmpeg = { found: true, path: candidate }+ const version = await runCapture(candidate, ['-version'])+ // --enable-libsoxr shows up in the configuration line; conda and some+ // homebrew builds omit it, and aresample then fails with "Invalid+ // argument" after the output file is already open+ const soxr = /libsoxr/.test(version)+ state.ffmpeg = { found: true, path: candidate, soxr }break} catch {continuediff --git a/src/main/index.ts b/src/main/index.tsindex 7a85de1..45ba716 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,6 +1,6 @@import { app, BrowserWindow, ipcMain, shell, dialog } from 'electron'import { join, normalize, extname } from 'path'-import { existsSync, copyFileSync, mkdirSync, createReadStream, statSync } from 'fs'+import { existsSync, copyFileSync, createReadStream, statSync } from 'fs'import { createServer, type Server } from 'http'import type { AddressInfo } from 'net'import type { AppSettings } from '../shared/types'@@ -21,7 +21,8 @@ import {getStatus} from './env'import { loadSettings, saveSettings } from './settings'-import { loadSongs, removeSong, stemBuffers, stemsDir, stemsFor, mixWavPath, AUDIO_EXTENSIONS } from './library'+import { loadSongs, removeSong, clearLibrary, stemBuffers, stemsDir, stemsFor, sanitizeName, exportStems } from './library'+import { AUDIO_EXTENSIONS } from '../shared/local'import { startJob, startLocalJob, cancelJob, searchYouTube } from './pipeline'import { initUpdater } from './updater'import { runSmoke } from './smoke'@@ -75,11 +76,6 @@ function startRendererServer(): Promise<string> {})}-function sanitizeName(name: string): string {- const clean = name.replace(/[\\/:*?"<>|]/g, '-').trim()- return clean.length > 0 ? clean.slice(0, 120) : 'stems'-}-async function createWindow(): Promise<void> {mainWindow = new BrowserWindow({width: 1360,@@ -165,6 +161,12 @@ app.whenReady().then(async () => {ipcMain.handle('library:list', () => loadSongs())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+ // about to delete and land a half-split song back in the library+ cancelJob()+ clearLibrary()+ })ipcMain.handle('song:buffers', (_e, videoId: string) => {const song = loadSongs().find((s) => s.videoId === videoId)return stemBuffers(videoId, song?.stems)@@ -188,6 +190,15 @@ app.whenReady().then(async () => {if (result.canceled || !result.filePaths[0]) return nullreturn result.filePaths[0]})+ ipcMain.handle('files:pick-folder', async () => {+ const result = await dialog.showOpenDialog({+ title: 'Choose the export folder',+ buttonLabel: 'Export here',+ properties: ['openDirectory', 'createDirectory']+ })+ if (result.canceled || !result.filePaths[0]) return null+ return result.filePaths[0]+ })ipcMain.handle('jobs:cancel', (_e, videoId?: string) => cancelJob(videoId))ipcMain.handle('stem:export', async (_e, videoId: string, stem: string) => {@@ -217,18 +228,8 @@ app.whenReady().then(async () => {properties: ['openDirectory', 'createDirectory']})if (result.canceled || !result.filePaths[0]) return { saved: false }- const target = join(result.filePaths[0], sanitizeName(song?.title ?? videoId))- mkdirSync(target, { recursive: true })- for (const name of list) {- copyFileSync(join(dir, `${name}.wav`), join(target, `${name}.wav`))- }- let count = list.length- const mix = mixWavPath(videoId)- if (existsSync(mix)) {- copyFileSync(mix, join(target, `${sanitizeName(song?.title ?? 'full track')}.wav`))- count += 1- }- return { saved: true, path: target, count }+ const { path, count } = await exportStems(videoId, song?.title ?? videoId, list, result.filePaths[0])+ return { saved: true, path, count }})ipcMain.handle('search:youtube', (_e, query: string) => searchYouTube(query))diff --git a/src/main/library.ts b/src/main/library.tsindex e7cfe7e..004b40a 100644--- a/src/main/library.ts+++ b/src/main/library.ts@@ -1,26 +1,9 @@import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, openSync, readSync, closeSync } from 'fs'-import { readFile } from 'fs/promises'+import { readFile, cp } from 'fs/promises'import { join } from 'path'import { userDataDir } from './env'import { DEFAULT_STEMS, type Song } from '../shared/types'-// drives both the file-dialog filter and the pre-flight extension check in-// startLocalJob; anything here is fair game for ffmpeg to decode-export const AUDIO_EXTENSIONS = [- 'mp3',- 'wav',- 'm4a',- 'aac',- 'flac',- 'ogg',- 'opus',- 'wma',- 'aiff',- 'aif',- 'alac',- 'webm'-]-function libraryFile(): string {return join(userDataDir(), 'library.json')}@@ -70,10 +53,44 @@ export function upsertSong(song: Song): Song[] {export function removeSong(videoId: string): Song[] {const songs = loadSongs().filter((s) => s.videoId !== videoId)saveSongs(songs)- rmSync(songDir(videoId), { recursive: true, force: true })+ // songDir('') would point at the songs root itself and take every other+ // song with it, so only ever delete a real single-segment id+ if (videoId && !videoId.includes('/') && !videoId.includes('\\') && videoId !== '.') {+ rmSync(songDir(videoId), { recursive: true, force: true })+ }return songs}+// wipes the whole library off the disk; running jobs are cancelled by the+// caller first, otherwise they would keep writing into a deleted folder+export function clearLibrary(): void {+ saveSongs([])+ rmSync(songsRoot(), { recursive: true, force: true })+}++export function sanitizeName(name: string): string {+ const clean = name.replace(/[\\/:*?"<>|]/g, '-').trim()+ return clean.length > 0 ? clean.slice(0, 120) : 'stems'+}++export async function exportStems(+ videoId: string,+ title: string,+ stems: string[],+ root: string+): Promise<{ path: string; count: number }> {+ const dir = stemsDir(videoId)+ const target = join(root, sanitizeName(title || videoId))+ mkdirSync(target, { recursive: true })+ const names = stems.filter((name) => existsSync(join(dir, `${name}.wav`)))+ await Promise.all(names.map((name) => cp(join(dir, `${name}.wav`), join(target, `${name}.wav`))))+ const mix = mixWavPath(videoId)+ if (existsSync(mix)) {+ await cp(mix, join(target, `${sanitizeName(title || 'full track')}.wav`))+ }+ return { path: target, count: names.length + (existsSync(mix) ? 1 : 0) }+}+export function stemsFor(song?: Song | null): string[] {return song?.stems?.length ? song.stems : DEFAULT_STEMS}diff --git a/src/main/pipeline.ts b/src/main/pipeline.tsindex 151e26d..527c4f6 100644--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@ -1,7 +1,8 @@import { spawn, type ChildProcess } from 'child_process'import { createInterface } from 'readline'import { readdirSync, mkdirSync, rmSync, statSync } from 'fs'-import { basename, extname, join } from 'path'+import { basename, join } from 'path'+import { totalmem } from 'os'import { BrowserWindow } from 'electron'import {venvPython,@@ -24,16 +25,16 @@ import {stemsPresent,stemsFor,mixWavPath,+ exportStems,rawDownloadPath,upsertSong,loadSongs,- AUDIO_EXTENSIONS,wavDuration} from './library'import type { JobEvent, JobStage } from '../shared/types'import { MODEL_DEFAULT, MODEL_EXTENDED } from '../shared/types'import { parseVideoId } from '../shared/url'-import { localSongId } from '../shared/local'+import { AUDIO_EXTENSIONS, audioExtension, localSongId } from '../shared/local'import { cacheThumbnail } from './thumbs'interface ActiveJob {@@ -46,7 +47,12 @@ interface ActiveJob {const jobs = new Map<string, ActiveJob>()-const MAX_CONCURRENT_SEPARATIONS = 2+/* 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 : 1let activeSeparations = 0const separationWaiters: Array<() => void> = []@@ -164,19 +170,21 @@ function reuseOrPrepare(async function convertToWav(job: ActiveJob, inputPath: string): Promise<void> {const videoId = job.videoIdprogress(job, 'convert', 0, 'Converting to WAV')- const ffmpeg = getStatus().ffmpeg.path- if (!ffmpeg) {+ const ffmpeg = getStatus().ffmpeg+ if (!ffmpeg.path) {throw Object.assign(new Error('Something went wrong with the built-in audio tools. Try reinstalling StemKit.'),{ videoId })}- await runProcess(job, ffmpeg as string, [+ await runProcess(job, ffmpeg.path as string, ['-y','-i',inputPath,'-af',- 'aresample=44100:resampler=soxr',+ // swr sounds marginally worse on odd sample rates, but a build without+ // libsoxr hard-fails the whole job on the soxr resampler+ ffmpeg.soxr === false ? 'aresample=44100' : 'aresample=44100:resampler=soxr','-ar','44100','-ac',@@ -207,6 +215,21 @@ function finalizeJob(source: info.source})send({ kind: 'done', data: { videoId: job.videoId, song: songs[0] } })++ const folder = loadSettings().exportFolder+ if (folder) {+ // not awaited: a slow or full target volume must not hold up the library+ // entry the player is already waiting on+ void exportStems(job.videoId, info.title, producedStems, folder).catch((err: unknown) =>+ send({+ kind: 'failed',+ data: {+ videoId: '',+ message: `Export to ${folder} failed: ${err instanceof Error ? err.message : String(err)}`+ }+ })+ )+ }}export async function startJob(@@ -320,7 +343,7 @@ export async function startLocalJob(stems?: string[]): Promise<void> {const filePath = String(rawPath ?? '').trim()- const ext = extname(filePath).slice(1).toLowerCase()+ const ext = audioExtension(filePath)if (!filePath || !AUDIO_EXTENSIONS.includes(ext)) {send({kind: 'failed',@@ -634,23 +657,48 @@ function runProcess(stderrTail = (stderrTail + chunk.toString()).slice(-2000)})+ let rl: ReturnType<typeof createInterface> | null = nullif (opts.onLine && child.stdout) {- const rl = createInterface({ input: child.stdout })+ rl = createInterface({ input: child.stdout })rl.on('line', (line) => opts.onLine?.(line))}+ // an open readline interface keeps the pipe and its buffered tail alive+ // for the lifetime of the app, one per spawned engine process+ const stopReading = (): void => rl?.close()- child.on('error', (err) => reject(friendlySpawnError(err)))- child.on('close', (code) => {+ child.on('error', (err) => {+ stopReading()+ reject(friendlySpawnError(err))+ })+ child.on('close', (code, signal) => {+ stopReading()if (job.cancelled || !jobs.has(job.videoId)) return reject(new Error('cancelled'))if (code === 0) return resolve()const detail =stderrTail.split('\n').filter(Boolean).slice(-2).join(' — ') ||stdoutTail.split('\n').filter(Boolean).slice(-1).join('')+ const tool = cmd.split('/').pop()+ /* memory is the failure that looks random: an out-of-memory kill leaves+ no output behind (code null + SIGKILL), and a torch allocation failure+ only says "CUDA out of memory". Say what it was, or the retry loop+ never ends */+ if (+ (code === null && signal === 'SIGKILL' && !detail) ||+ /out of memory|cannot allocate|std::bad_alloc|insufficient memory/i.test(detail)+ ) {+ reject(+ new Error(+ 'Ran out of memory while splitting. Try again on its own (only one song at a time), ' ++ 'close other heavy apps, or turn off GPU acceleration in Settings.'+ )+ )+ return+ }reject(new Error(detail- ? `${cmd.split('/').pop()} exited (${code}): ${detail}`- : `${cmd.split('/').pop()} exited with code ${code}`+ ? `${tool} exited (${code ?? signal}): ${detail}`+ : `${tool} exited (${code ?? signal})`))})diff --git a/src/main/settings.ts b/src/main/settings.tsindex 64b83a9..9c5189e 100644--- a/src/main/settings.ts+++ b/src/main/settings.ts@@ -24,7 +24,8 @@ export function saveSettings(patch: Partial<AppSettings>): AppSettings {htdemucsFt: !!merged.htdemucsFt,roformerVocals: !!merged.roformerVocals,gpuSplit: !!merged.gpuSplit,- hideVideo: !!merged.hideVideo+ hideVideo: !!merged.hideVideo,+ exportFolder: typeof merged.exportFolder === 'string' ? merged.exportFolder.trim() : ''}writeFileSync(settingsFile(), JSON.stringify(next, null, 2))for (const win of BrowserWindow.getAllWindows()) {diff --git a/src/preload/index.ts b/src/preload/index.tsindex a0902c8..f84615a 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,4 +1,4 @@-import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'+import { contextBridge, ipcRenderer, webUtils, type IpcRendererEvent } from 'electron'import type { JobEvent, EnvEvent, UpdateEvent, AppSettings, StemKitApi } from '../shared/types'function subscribe<T>(channel: string, cb: (data: T) => void): () => void {@@ -15,12 +15,17 @@ const api: StemKitApi = {envUpdateYtDlp: () => ipcRenderer.invoke('env:update-ytdlp'),listSongs: () => ipcRenderer.invoke('library:list'),deleteSong: (videoId) => ipcRenderer.invoke('library:delete', videoId),+ clearLibrary: () => ipcRenderer.invoke('library:clear'),getBuffers: (videoId) => ipcRenderer.invoke('song:buffers', videoId),exportStem: (videoId, stem) => ipcRenderer.invoke('stem:export', videoId, stem),exportAllStems: (videoId) => ipcRenderer.invoke('stems:export-all', videoId),searchYouTube: (query) => ipcRenderer.invoke('search:youtube', query),startJob: (url, model, stems) => ipcRenderer.invoke('jobs:start', url, model, stems),pickAudioFile: () => ipcRenderer.invoke('files:pick-audio'),+ pickFolder: () => ipcRenderer.invoke('files:pick-folder'),+ // Electron 32 dropped the File.path augmentation, so a dropped file's path+ // on disk has to be resolved here — it is the only place with node access+ getPathForFile: (file) => webUtils.getPathForFile(file),startLocalJob: (filePath, model, stems) => ipcRenderer.invoke('jobs:start-local', filePath, model, stems),cancelJob: (videoId?: string) => ipcRenderer.invoke('jobs:cancel', videoId),openExternal: (url) => ipcRenderer.invoke('open-external', url),diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex e106542..70d318b 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -1,12 +1,12 @@-import { useCallback, useEffect, useMemo, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import type { AppSettings, EnvStatus, JobProgress, JobStage, Song, UpdateEvent } from '../../shared/types'-import { MODEL_DEFAULT } from '../../shared/types'+import { DEFAULT_STEMS, MODEL_DEFAULT } from '../../shared/types'import { parseVideoId } from '../../shared/url'-import { localSongId, isLocalId } from '../../shared/local'+import { isAudioPath, isLocalId, localSongId } from '../../shared/local'import { Sidebar } from './components/Sidebar'import { Home } from './components/Home'import { Processing } from './components/Processing'-import { Player } from './components/Player'+import { Player, releaseBufferCache } from './components/Player'import { Setup } from './components/Setup'import { Settings } from './components/Settings'import { LogoMark } from './components/Icons'@@ -53,6 +53,15 @@ export default function App(): React.ReactElement {const [appVersion, setAppVersion] = useState<string | undefined>(undefined)const [settings, setSettings] = useState<AppSettings | null>(null)const [settingsOpen, setSettingsOpen] = useState(false)+ const [dropping, setDropping] = useState(false)+ const [notice, setNotice] = useState<string | null>(null)+ // what a dropped file should be split with: Home pushes its current engine+ // and instrument selection down, so a drop honours the same toggles the+ // buttons use without owning that state here+ const startOpts = useRef<{ model: string; stems: string[] }>({+ model: MODEL_DEFAULT,+ stems: [...DEFAULT_STEMS]+ })useEffect(() => {void window.stemkit.envStatus().then(setStatus)@@ -69,6 +78,10 @@ export default function App(): React.ReactElement {void window.stemkit.listSongs().then(setSongs)} else if (ev.data.message === 'Cancelled') {setJobs((prev) => withoutKey(prev, ev.data.videoId))+ } else if (!ev.data.videoId) {+ // rejections that have no song to attach to (unplayable drop, missing+ // file): a toast, since an empty id would key a blank library row+ setNotice(ev.data.message)} else {setJobs((prev) => withoutKey(prev, ev.data.videoId))setErrors((prev) => ({ ...prev, [ev.data.videoId]: ev.data.message }))@@ -97,6 +110,7 @@ export default function App(): React.ReactElement {async (url: string, model: string = MODEL_DEFAULT, stems?: string[]): Promise<void> => {const vid = parseVideoId(url)if (!vid) return+ releaseBufferCache()setActiveId(vid)setLastStart({ kind: 'url', url, model })setErrors((prev) => withoutKey(prev, vid))@@ -111,9 +125,16 @@ export default function App(): React.ReactElement {)const startLocal = useCallback(- async (filePath: string, model: string = MODEL_DEFAULT, stems?: string[]): Promise<void> => {+ async (+ filePath: string,+ model: string = MODEL_DEFAULT,+ stems?: string[],+ // a multi-file drop queues every file but only the first takes the view+ focus = true+ ): Promise<void> => {const id = localSongId(filePath)- setActiveId(id)+ releaseBufferCache()+ if (focus) setActiveId(id)setLastStart({ kind: 'local', filePath, model })setErrors((prev) => withoutKey(prev, id))setJobs((prev) =>@@ -126,6 +147,107 @@ export default function App(): React.ReactElement {[])+ const setStartOptions = useCallback((model: string, stems: string[]): void => {+ startOpts.current = { model, stems }+ }, [])++ const ready = !!status?.ready++ useEffect(() => {+ if (!notice) return+ const timer = setTimeout(() => setNotice(null), 6000)+ return () => clearTimeout(timer)+ }, [notice])++ useEffect(() => {+ let depth = 0+ // Files = something off disk, text/uri-list = a dragged link. A plain+ // text/plain drag is a selection inside the app, which stays untouched+ const droppable = (e: DragEvent): boolean => {+ const types = e.dataTransfer ? Array.from(e.dataTransfer.types) : []+ return types.includes('Files') || types.includes('text/uri-list')+ }++ /* dropping without preventDefault navigates the window to file:///… and+ takes the whole app down with it, so every handler here claims the+ event first and only then decides what to do with it */+ const onDragEnter = (e: DragEvent): void => {+ if (!droppable(e)) return+ e.preventDefault()+ depth += 1+ setDropping(true)+ }+ const onDragOver = (e: DragEvent): void => {+ if (!droppable(e)) return+ e.preventDefault()+ if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'+ }+ const onDragLeave = (): void => {+ depth = Math.max(0, depth - 1)+ if (depth === 0) setDropping(false)+ }+ const onDrop = (e: DragEvent): void => {+ e.preventDefault()+ depth = 0+ setDropping(false)+ const dt = e.dataTransfer+ if (!dt) return+ // dropping into the search field is an edit, not a request to split+ if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return+ if (!ready) {+ setNotice('StemKit is still getting ready — try again once setup finishes')+ return+ }+ const { model, stems } = startOpts.current+ const files = Array.from(dt.files)+ if (files.length === 0) {+ const link = (dt.getData('text/uri-list') || '').split(/[\r\n]/)[0]+ if (link && parseVideoId(link)) void startUrl(link, model, stems)+ else setNotice('Drop audio files or a YouTube link')+ return+ }+ const paths: string[] = []+ const skipped: string[] = []+ for (const file of files) {+ let path = ''+ try {+ path = window.stemkit.getPathForFile(file)+ } catch {+ path = ''+ }+ if (path && isAudioPath(path)) paths.push(path)+ else skipped.push(file.name || 'that file')+ }+ if (paths.length === 0) {+ setNotice(+ skipped.length+ ? `Can’t split ${skipped.join(', ')} — use mp3, wav, flac, m4a, ogg or opus`+ : 'Drop audio files (mp3, wav, flac, m4a…)'+ )+ return+ }+ if (stems.length === 0) {+ setNotice('Pick at least one instrument first')+ return+ }+ if (skipped.length > 0) setNotice(`Skipped ${skipped.join(', ')} — not audio`)+ paths.forEach((path, i) => {+ void startLocal(path, model, stems, i === 0)+ })+ }++ window.addEventListener('dragenter', onDragEnter)+ window.addEventListener('dragover', onDragOver)+ window.addEventListener('dragleave', onDragLeave)+ window.addEventListener('drop', onDrop)+ return () => {+ window.removeEventListener('dragenter', onDragEnter)+ window.removeEventListener('dragover', onDragOver)+ window.removeEventListener('dragleave', onDragLeave)+ window.removeEventListener('drop', onDrop)+ }+ }, [ready, startLocal, startUrl])+const cancelSelectedJob = useCallback((videoId: string): void => {void window.stemkit.cancelJob(videoId)@@ -156,6 +278,19 @@ export default function App(): React.ReactElement {[jobs])+ const clearAll = useCallback(async (): Promise<void> => {+ if (!songs.length) return+ // main cancels anything mid-split before wiping the folders+ if (!window.confirm(`Remove all ${songs.length} songs and delete their stems from this computer?`))+ return+ releaseBufferCache()+ setJobs({})+ setErrors({})+ setActiveId(null)+ await window.stemkit.clearLibrary()+ setSongs(await window.stemkit.listSongs())+ }, [songs.length])+const activeSong = useMemo(() => songs.find((s) => s.videoId === activeId) ?? null,[songs, activeId]@@ -255,6 +390,7 @@ export default function App(): React.ReactElement {settings={settings ?? undefined}onStart={(u, m, s) => void startUrl(u, m, s)}onStartLocal={(path, m, s) => void startLocal(path, m, s)}+ onOptions={setStartOptions}onSelect={(id) => setActiveId(id)}onOpenSettings={() => {void window.stemkit.envStatus().then(setStatus)@@ -274,6 +410,7 @@ export default function App(): React.ReactElement {appVersion={appVersion}onSelect={(id) => setActiveId(id)}onDelete={(id) => void deleteSong(id)}+ onClearAll={() => void clearAll()}onAdd={() => setActiveId(null)}onInstallUpdate={() => window.stemkit.installUpdate()}onOpenSettings={() => {@@ -291,6 +428,25 @@ export default function App(): React.ReactElement {onClose={() => setSettingsOpen(false)}/>)}+ {/* pointer-events-none: the drop has to land on the window listeners,+ not on the hint itself, or enter/leave would flicker over it */}+ {dropping && (+ <div className="fixed inset-0 z-50 p-6 pointer-events-none">+ <div className="h-full w-full rounded-3xl border-2 border-dashed border-violet-300/70 bg-violet-500/[0.12] flex flex-col items-center justify-center gap-2">+ <p className="text-lg font-semibold text-violet-100">Drop to split</p>+ <p className="text-[13px] text-white/60">+ audio files (mp3, wav, flac, m4a…) or a YouTube link+ </p>+ </div>+ </div>+ )}+ {notice && (+ <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 max-w-[720px] rise-in">+ <div className="rounded-xl border border-rose-400/25 bg-rose-500/10 px-4 py-2.5 text-[13px] text-rose-200 break-words">+ {notice}+ </div>+ </div>+ )}</div>)}diff --git a/src/renderer/src/components/Home.tsx b/src/renderer/src/components/Home.tsxindex de7d4cf..02fe5e1 100644--- a/src/renderer/src/components/Home.tsx+++ b/src/renderer/src/components/Home.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import {MODEL_DEFAULT,MODEL_EXTENDED,@@ -20,6 +20,9 @@ interface Props {settings?: AppSettingsonStart: (url: string, model: string, stems?: string[]) => voidonStartLocal: (filePath: string, model: string, stems?: string[]) => void+ // mirrors the engine + instrument toggles out to App, which owns the+ // window-wide drop target and has no selection state of its own+ onOptions: (model: string, stems: string[]) => voidonSelect: (videoId: string) => voidonOpenSettings: () => void}@@ -33,6 +36,7 @@ export function Home({settings,onStart,onStartLocal,+ onOptions,onSelect,onOpenSettings}: Props): React.ReactElement {@@ -47,7 +51,13 @@ export function Home({const usesExtended = [...selected].some((id) => id === 'guitar' || id === 'piano')const derivedModel = usesExtended ? MODEL_EXTENDED : MODEL_DEFAULT- const orderedSelection = ALL_STEMS.filter((id) => selected.has(id))+ const orderedSelection = useMemo(+ () => ALL_STEMS.filter((id) => selected.has(id)),+ [selected]+ )+ useEffect(() => {+ onOptions(derivedModel, orderedSelection)+ }, [derivedModel, orderedSelection, onOptions])// the fine-tuned engine only covers the standard 4-stem split; guitar and// piano always run through the 6-source engine, so they're unavailable// while it's on@@ -161,7 +171,7 @@ export function Home({Turn any track into stems.</h1><p className="text-center text-white/45 mt-2.5 text-[14px]">- Search YouTube, paste a link, or split an audio file from your computer — separated locally.+ Search YouTube, paste a link, or drag audio files in from your computer — separated locally.</p><div className="mt-6 flex gap-2">diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsxindex e97bd35..3cb3d62 100644--- a/src/renderer/src/components/Player.tsx+++ b/src/renderer/src/components/Player.tsx@@ -13,21 +13,43 @@ type BufferCacheMap = BufferMapconst bufferCache = new Map<string, Promise<BufferCacheMap>>()+// one decoded song is a few hundred MB of Float32 PCM sitting in the renderer,+// so this is a small LRU rather than an accumulating one: it keeps a jump back+// to the previous song free without holding a copy of everything ever opened+const CACHE_LIMIT = 2+function getDecoded(videoId: string): Promise<BufferCacheMap> {- let entry = bufferCache.get(videoId)- if (!entry) {- entry = window.stemkit- .getBuffers(videoId)- .then((payload) => decodePayload(payload))- .catch((err) => {- bufferCache.delete(videoId)- throw err- })- bufferCache.set(videoId, entry)+ const cached = bufferCache.get(videoId)+ if (cached) {+ // re-insert so the entry is last again (Map iterates in insertion order)+ bufferCache.delete(videoId)+ bufferCache.set(videoId, cached)+ return cached+ }+ const entry = window.stemkit+ .getBuffers(videoId)+ .then((payload) => decodePayload(payload))+ .catch((err) => {+ bufferCache.delete(videoId)+ throw err+ })+ bufferCache.set(videoId, entry)+ while (bufferCache.size > CACHE_LIMIT) {+ const oldest = bufferCache.keys().next()+ if (oldest.done) break+ bufferCache.delete(oldest.value)}return entry}+/* A split peaks at several GB in the engine process, so whatever is left over+ from browsing has to go when one starts — otherwise the song you last played+ is what gets the next separation killed. */+export function releaseBufferCache(): void {+ bufferCache.clear()+ engine.release()+}+interface Props {song: Songsettings?: AppSettingsdiff --git a/src/renderer/src/components/Settings.tsx b/src/renderer/src/components/Settings.tsxindex 853a74b..51e1d53 100644--- a/src/renderer/src/components/Settings.tsx+++ b/src/renderer/src/components/Settings.tsx@@ -217,6 +217,12 @@ export function Settings({ settings, gpu, gpuVendor, onChange, onClose }: Props)void window.stemkit.fetchEngine('gpu')}+ const pickFolder = (): void => {+ void window.stemkit.pickFolder().then((path) => {+ if (path) onChange({ exportFolder: path })+ })+ }+return (<divclassName="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"@@ -336,6 +342,40 @@ export function Settings({ settings, gpu, gpuVendor, onChange, onClose }: Props)</p></section>+ <section className="pt-5 border-t border-white/[0.06] space-y-5">+ <SectionHeader label="Export" />+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-[13px] font-medium">Export folder</p>+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">+ Copy the stems of every finished split straight into this folder, in a subfolder+ per song. They stay in the library either way.+ </p>+ {settings.exportFolder && (+ <p className="mt-1.5 text-[11px] font-mono text-white/45 break-all leading-relaxed">+ {settings.exportFolder}+ </p>+ )}+ </div>+ <div className="shrink-0 flex flex-col items-end gap-1.5">+ <button+ onClick={pickFolder}+ className="no-drag px-3 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/[0.08] text-[12px] text-white/75 hover:text-white transition-colors"+ >+ {settings.exportFolder ? 'Change' : 'Choose…'}+ </button>+ {settings.exportFolder && (+ <button+ onClick={() => onChange({ exportFolder: '' })}+ className="no-drag text-[11px] text-white/35 hover:text-white/70 transition-colors"+ >+ Stop exporting+ </button>+ )}+ </div>+ </div>+ </section>+<section className="pt-5 border-t border-white/[0.06] space-y-5"><SectionHeader label="Playback" /><div className="flex items-start justify-between gap-4">diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex d7acc65..fdb13d7 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -12,6 +12,7 @@ interface Props {onSelect: (videoId: string) => voidonDelete: (videoId: string) => voidonAdd: () => void+ onClearAll: () => voidonInstallUpdate: () => voidonOpenSettings: () => void}@@ -25,6 +26,7 @@ export function Sidebar({onSelect,onDelete,onAdd,+ onClearAll,onInstallUpdate,onOpenSettings}: Props): React.ReactElement {@@ -46,13 +48,24 @@ export function Sidebar({<span className="text-[11px] font-semibold uppercase tracking-widest text-white/30">Library</span>- <button- onClick={onAdd}- title="Add song"- className="no-drag w-6 h-6 rounded-md bg-white/5 hover:bg-white/10 text-white/50 hover:text-white flex items-center justify-center transition-colors"- >- <PlusIcon className="w-3.5 h-3.5" />- </button>+ <span className="flex items-center gap-1">+ {songs.length > 0 && (+ <button+ onClick={onClearAll}+ title="Remove every song and its stems"+ className="no-drag w-6 h-6 rounded-md bg-white/5 hover:bg-white/10 text-white/40 hover:text-rose-300 flex items-center justify-center transition-colors"+ >+ <TrashIcon className="w-3.5 h-3.5" />+ </button>+ )}+ <button+ onClick={onAdd}+ title="Add song"+ className="no-drag w-6 h-6 rounded-md bg-white/5 hover:bg-white/10 text-white/50 hover:text-white flex items-center justify-center transition-colors"+ >+ <PlusIcon className="w-3.5 h-3.5" />+ </button>+ </span></div><div className="flex-1 overflow-y-auto px-3 pb-3 space-y-0.5">diff --git a/src/renderer/src/lib/engine.ts b/src/renderer/src/lib/engine.tsindex bfd2e2f..23706eb 100644--- a/src/renderer/src/lib/engine.ts+++ b/src/renderer/src/lib/engine.ts@@ -8,16 +8,24 @@ export async function decodePayload(const ctx = new AudioContext()void ctx.resume()const ids = Object.keys(payload)- // decodeAudioData detaches the source buffer — the IPC payload is throwaway,- // so hand it over as-is (skips a full copy per stem)- const decoded = await Promise.all(- ids.map((id) => ctx.decodeAudioData(payload[id].buffer as ArrayBuffer))- )- const out: BufferMap = {}- ids.forEach((id, i) => {- out[id as StemId] = decoded[i]- })- return out+ try {+ // decodeAudioData detaches the source buffer — the IPC payload is throwaway,+ // so hand it over as-is (skips a full copy per stem)+ const decoded = await Promise.all(+ ids.map((id) => ctx.decodeAudioData(payload[id].buffer as ArrayBuffer))+ )+ const out: BufferMap = {}+ ids.forEach((id, i) => {+ out[id as StemId] = decoded[i]+ })+ return out+ } finally {+ // this context exists only to decode, and every open one holds an audio+ // stream + engine of its own: leaving it running leaks one per song+ // visited. AudioBuffers outlive the context that made them, so the+ // playback engine (a separate context) still uses them+ void ctx.close()+ }}export class StemEngine {@@ -129,6 +137,13 @@ export class StemEngine {this.stopSources()}+ // hand back the decoded audio: the singleton engine would otherwise pin the+ // last viewed song for the rest of the session+ release(): void {+ this.stopAll()+ this.buffers = {}+ }+private stopSources(): void {for (const s of this.sources) {try {diff --git a/src/shared/local.ts b/src/shared/local.tsindex d025858..1c58b10 100644--- a/src/shared/local.ts+++ b/src/shared/local.ts@@ -1,3 +1,33 @@+// drives the file-dialog filter and the pre-flight extension check for both+// the picker and drag-and-drop; anything here is fair game for ffmpeg to+// decode. Lives in shared/ because the renderer has to reject unsupported+// drops before it starts a job (a failed job keys an empty song id into the+// library list)+export const AUDIO_EXTENSIONS = [+ 'mp3',+ 'wav',+ 'm4a',+ 'aac',+ 'flac',+ 'ogg',+ 'opus',+ 'wma',+ 'aiff',+ 'aif',+ 'alac',+ 'webm'+]++export function audioExtension(filePath: string): string {+ const base = filePath.split(/[\\/]/).pop() ?? ''+ const dot = base.lastIndexOf('.')+ return dot <= 0 ? '' : base.slice(dot + 1).toLowerCase()+}++export function isAudioPath(filePath: string): boolean {+ return AUDIO_EXTENSIONS.includes(audioExtension(filePath))+}+// local audio files get a synthetic id derived from their absolute path, so// they flow through the same library/jobs/player plumbing as YouTube songs// (which key everything off the 11-char video id). Deterministic: re-splittingdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 961d728..40c7d1b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -34,6 +34,10 @@ export interface AppSettings {// hide the YouTube video while playing: stems are always played locally,// this stops streaming the video and falls back to cached thumbnailshideVideo: boolean+ // absolute path: every finished split is copied out of the app's own storage+ // into a <exportFolder>/<song>/ folder as soon as it lands in the library.+ // Empty means "stay in the library only"+ exportFolder: string}export const DEFAULT_SETTINGS: AppSettings = {@@ -41,7 +45,8 @@ export const DEFAULT_SETTINGS: AppSettings = {htdemucsFt: false,roformerVocals: false,gpuSplit: false,- hideVideo: false+ hideVideo: false,+ exportFolder: ''}export interface EngineStatus {@@ -116,12 +121,16 @@ export interface StemKitApi {envUpdateYtDlp(): Promise<boolean>listSongs(): Promise<Song[]>deleteSong(videoId: string): Promise<void>+ clearLibrary(): Promise<void>getBuffers(videoId: string): Promise<Record<string, Uint8Array>>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[]>startJob(url: string, model?: string, stems?: string[]): Promise<{ started: boolean }>pickAudioFile(): Promise<string | null>+ pickFolder(): Promise<string | null>+ // absolute path of a File dropped into the window (preload-side webUtils)+ getPathForFile(file: File): stringstartLocalJob(filePath: string, model?: string, stems?: string[]): Promise<{ started: boolean }>cancelJob(videoId?: string): Promise<void>openExternal(url: string): Promise<void>