Skip to content

Split any YouTube song into stems

TypeScript

feat: nvidia gpu split on windows + gpu smoke coverage

Daniel Ravinade750278a101
diff --git a/.github/workflows/windows-smoke.yml b/.github/workflows/windows-smoke.yml
index 6ea7a51..21fa647 100644
--- a/.github/workflows/windows-smoke.yml
+++ b/.github/workflows/windows-smoke.yml
@@ -1,8 +1,11 @@
name: windows-smoke
# installs the NSIS build silently, then runs the app's self-test mode
-# (STEMKIT_SMOKE=1): full bootstrap on a python-less runner + separating a
-# generated tone through both engines. Run manually before cutting a release
+# (STEMKIT_SMOKE=1): full bootstrap on a python-less runner, separating a
+# generated tone through both engines on CPU, then the GPU plumbing: the
+# cuda fail-fast paths plus the CUDA engine install (torch.version.cuda set,
+# cuda.is_available() still false with no NVIDIA driver). Run manually before
+# cutting a release
on:
workflow_dispatch:
workflow_call:
@@ -10,7 +13,9 @@ on:
jobs:
smoke:
runs-on: windows-latest
- timeout-minutes: 45
+ # the GPU section adds a ~2.5GB CUDA torch install (skippable via
+ # STEMKIT_SMOKE_SKIP_GPU=1); real CUDA execution needs NVIDIA hardware
+ timeout-minutes: 60
steps:
- uses: actions/checkout@v4
diff --git a/.gitignore b/.gitignore
index b9d55b3..deae81e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,4 @@ listening-list.md
__pycache__/
*.pyc
.plans/
+.env
diff --git a/electron.vite.config.ts b/electron.vite.config.ts
index 96f3aaf..9139bae 100644
--- a/electron.vite.config.ts
+++ b/electron.vite.config.ts
@@ -1,11 +1,20 @@
-import { defineConfig } from 'electron-vite'
+import { defineConfig, loadEnv } from 'electron-vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
-export default defineConfig({
- main: {},
- preload: {},
- renderer: {
- plugins: [react(), tailwindcss()]
+export default defineConfig(({ mode }) => {
+ // .env values (and shell overrides) bake into the main bundle at build time
+ const env = loadEnv(mode ?? 'production', process.cwd(), '')
+ return {
+ main: {
+ define: {
+ __STEMKIT_GA_ID__: JSON.stringify(env.STEMKIT_GA_ID ?? ''),
+ __STEMKIT_GA_SECRET__: JSON.stringify(env.STEMKIT_GA_SECRET ?? '')
+ }
+ },
+ preload: {},
+ renderer: {
+ plugins: [react(), tailwindcss()]
+ }
}
})
diff --git a/python/roformer.py b/python/roformer.py
index af0028b..b901720 100644
--- a/python/roformer.py
+++ b/python/roformer.py
@@ -222,6 +222,10 @@ def main():
vendor = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vendor")
sys.path.insert(0, vendor)
+ # fail fast before the ~913MB checkpoint download on GPU-less machines
+ if args.device == "cuda" and not torch.cuda.is_available():
+ fail("GPU engine not available (no NVIDIA GPU, or the CUDA build of torch is not installed)")
+
ckpt_path = os.path.join(args.ckpt_dir, CKPT_NAME)
if not os.path.exists(ckpt_path):
emit(type="progress", stage="separate", pct=0, message="Downloading vocals engine (913MB, one time)")
diff --git a/python/separate.py b/python/separate.py
index b0d655e..c86ddb2 100644
--- a/python/separate.py
+++ b/python/separate.py
@@ -118,6 +118,8 @@ def main():
device = "mps" if torch.backends.mps.is_available() else "cpu"
else:
device = args.device
+ if device == "cuda" and not torch.cuda.is_available():
+ fail("GPU engine not available (no NVIDIA GPU, or the CUDA build of torch is not installed)")
emit(type="progress", stage="model", pct=0, message=f"loading {args.model} on {device}")
from demucs.apply import apply_model
diff --git a/src/main/analytics.ts b/src/main/analytics.ts
new file mode 100644
index 0000000..43209fc
--- /dev/null
+++ b/src/main/analytics.ts
@@ -0,0 +1,134 @@
+import { randomUUID } from 'crypto'
+import { readFileSync, writeFileSync, mkdirSync } from 'fs'
+import { release } from 'os'
+import { join } from 'path'
+import { app, net } from 'electron'
+import { userDataDir } from './env'
+import { loadSettings } from './settings'
+
+/* GA4 Measurement Protocol (server-side from the main process — the renderer
+ stays CSP-isolated and nothing google ever runs in the app). Fill these in
+ to enable reporting: GA4 property Measurement ID + a Measurement Protocol
+ API secret (GA Admin → Data streams → stream → Measurement Protocol API
+ secrets). Values are baked in at build time via STEMKIT_GA_ID /
+ STEMKIT_GA_SECRET (see electron.vite.config.ts), with runtime env vars as a
+ fallback. With either value missing, track() is a no-op. */
+const MEASUREMENT_ID = __STEMKIT_GA_ID__ || process.env.STEMKIT_GA_ID || ''
+const API_SECRET = __STEMKIT_GA_SECRET__ || process.env.STEMKIT_GA_SECRET || ''
+
+const OS_NAMES: Record<string, string> = {
+ darwin: 'macOS',
+ win32: 'Windows',
+ linux: 'Linux'
+}
+
+let sessionStart = 0
+let sessionId: string | null = null
+let clientId: string | null = null
+
+function clientFile(): string {
+ return join(userDataDir(), 'analytics-client.json')
+}
+
+function ensureClientId(): string {
+ if (clientId) return clientId
+ try {
+ const raw = readFileSync(clientFile(), 'utf8')
+ const data = JSON.parse(raw)
+ if (typeof data.clientId === 'string' && data.clientId) clientId = data.clientId
+ } catch {}
+ if (!clientId) {
+ clientId = randomUUID()
+ try {
+ mkdirSync(userDataDir(), { recursive: true })
+ writeFileSync(clientFile(), JSON.stringify({ clientId }, null, 2))
+ } catch {}
+ }
+ return clientId
+}
+
+function ensureSessionId(): string {
+ // roll a new session when the app has been idle long enough to count as a
+ // new visit (GA's default 30 min timeout)
+ if (!sessionId || Date.now() - sessionStart > 30 * 60 * 1000) {
+ sessionId = randomUUID()
+ }
+ sessionStart = Date.now()
+ return sessionId
+}
+
+export function track(
+ name: string,
+ params: Record<string, string | number | boolean> = {},
+ engagementMs = 100
+): void {
+ if (!MEASUREMENT_ID || !API_SECRET) return
+ if (!app.isReady()) return
+ // consent is checked at send time so opting out takes effect immediately
+ if (!loadSettings().analytics) return
+
+ const flat: Record<string, string | number> = {
+ session_id: ensureSessionId(),
+ engagement_time_msec: engagementMs,
+ app_version: app.getVersion(),
+ os: OS_NAMES[process.platform] ?? process.platform,
+ os_version: release(),
+ arch: process.arch
+ }
+ for (const [k, v] of Object.entries(params)) {
+ if (k.length > 40) continue
+ flat[k] = typeof v === 'boolean' ? (v ? 'true' : 'false') : v
+ }
+
+ const body = {
+ client_id: ensureClientId(),
+ // user properties need a one-time registration in GA (Admin → Custom
+ // definitions) before they show up as report dimensions
+ user_properties: {
+ app_version: { value: app.getVersion() },
+ os: { value: OS_NAMES[process.platform] ?? process.platform },
+ os_version: { value: release() },
+ arch: { value: process.arch }
+ },
+ events: [{ name: name.slice(0, 40), params: flat }]
+ }
+
+ void net
+ .fetch(
+ `https://www.google-analytics.com/mp/collect?measurement_id=${encodeURIComponent(MEASUREMENT_ID)}&api_secret=${encodeURIComponent(API_SECRET)}`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(8000)
+ }
+ )
+ .catch(() => {})
+}
+
+/* engagement beacon: GA infers session length from the timestamps between
+ events, which for a desktop app with sparse events reads as ~instant. A
+ 5-minute heartbeat carrying its own interval as engagement time makes
+ session duration and average engagement meaningful (heartbeats also keep
+ the session alive for long-running windows). track() no-ops without
+ credentials or consent, so the timer is effectively free when disabled. */
+const HEARTBEAT_MS = 5 * 60 * 1000
+setInterval(() => {
+ track('session_heartbeat', {}, HEARTBEAT_MS)
+}, HEARTBEAT_MS).unref()
+
+const VALID_NAME = /^[a-z][a-z0-9_]{0,39}$/
+
+// events coming from the renderer go through a strict shape check
+export function trackFromRenderer(
+ name: unknown,
+ params: unknown
+): void {
+ if (typeof name !== 'string' || !VALID_NAME.test(name)) return
+ if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params))) return
+ const flat: Record<string, string | number | boolean> = {}
+ for (const [k, v] of Object.entries(params ?? {})) {
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') flat[k] = v
+ }
+ track(name, flat)
+}
\ No newline at end of file
diff --git a/src/main/env.ts b/src/main/env.ts
index a01ca73..27b2604 100644
--- a/src/main/env.ts
+++ b/src/main/env.ts
@@ -146,6 +146,38 @@ export function gpuAccelerationInfo(): boolean | undefined {
return gpuInfo
}
+let nvidiaProbe: Promise<boolean> | null = null
+let nvidiaInfo: boolean | undefined
+
+/* windows only: whether an NVIDIA GPU is present (nvidia-smi ships with the
+ driver). Gates the GPU-acceleration toggle in Settings */
+export function detectNvidiaGpu(): Promise<boolean> {
+ if (!IS_WIN) {
+ nvidiaInfo = false
+ return Promise.resolve(false)
+ }
+ if (!nvidiaProbe) {
+ nvidiaProbe = runCapture(
+ 'nvidia-smi',
+ ['--query-gpu=name,memory.total', '--format=csv,noheader'],
+ 10000
+ )
+ .then((out) => {
+ nvidiaInfo = /nvidia/i.test(out)
+ return nvidiaInfo
+ })
+ .catch(() => {
+ nvidiaInfo = false
+ return false
+ })
+ }
+ return nvidiaProbe
+}
+
+export function nvidiaGpuInfo(): boolean | undefined {
+ return nvidiaInfo
+}
+
/* venvs created before the roformer engine lack a few small packages;
verify and install them once per session */
export async function ensureEngineDeps(): Promise<boolean> {
@@ -609,12 +641,120 @@ export function ensureFtWeights(onProgress?: (pct: number) => void): Promise<boo
return ftWeightsPromise.then(detach)
}
+/* CUDA build of torch (windows + nvidia). The default bootstrap installs the
+ CPU wheel from PyPI; this swaps in the cu121 build (~2.5GB download) on
+ demand when the GPU-acceleration toggle is enabled. It stays installed when
+ the toggle goes back off — CUDA torch handles cpu devices fine */
+const GPU_TORCH_VERSION = '2.5.1'
+const GPU_TORCH_INDEX = 'https://download.pytorch.org/whl/cu121'
+
+let gpuEnginePromise: Promise<boolean> | null = null
+const gpuProgressListeners = new Set<(pct: number) => void>()
+
+export function ensureGpuEngine(onProgress?: (pct: number) => void): Promise<boolean> {
+ if (onProgress) gpuProgressListeners.add(onProgress)
+ const detach = (): boolean => {
+ if (onProgress) gpuProgressListeners.delete(onProgress)
+ return true
+ }
+ if (!IS_WIN) {
+ detach()
+ return Promise.resolve(false)
+ }
+ if (!gpuEnginePromise) {
+ gpuEnginePromise = (async () => {
+ // already swapped in: the venv's torch speaks CUDA, nothing to install
+ if (await hasGpuAcceleration()) return true
+ sendEnvEvent('Downloading the GPU engine (~2.5GB, one time)')
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(
+ venvPython(),
+ [
+ '-m',
+ 'pip',
+ 'install',
+ '--no-cache-dir',
+ `torch==${GPU_TORCH_VERSION}`,
+ `torchaudio==${GPU_TORCH_VERSION}`,
+ '--index-url',
+ GPU_TORCH_INDEX
+ ],
+ { env: { ...process.env } }
+ )
+ let lastPct = 0
+ let stderrTail = ''
+ child.stdout?.on('data', (chunk: Buffer) => {
+ const t = chunk.toString().trim()
+ if (/^(Collecting|Downloading|Installing)/i.test(t)) sendEnvEvent(t.slice(0, 200))
+ })
+ child.stderr?.on('data', (chunk: Buffer) => {
+ stderrTail = (stderrTail + chunk.toString()).slice(-1000)
+ for (const piece of chunk.toString().split(/[\r\n]/)) {
+ const pct = pipProgressPct(piece)
+ if (pct === null || pct <= lastPct) continue
+ lastPct = Math.min(99, pct)
+ sendEnvEvent(`GPU engine: ${lastPct}%`)
+ for (const listener of gpuProgressListeners) listener(lastPct)
+ }
+ })
+ child.on('error', reject)
+ child.on('close', (code) => {
+ if (code === 0) {
+ resolve()
+ return
+ }
+ reject(
+ new Error(
+ stderrTail.split('\n').filter(Boolean).slice(-1).join('') ||
+ `GPU engine install exited ${code}`
+ )
+ )
+ })
+ })
+ // refresh the cached cuda probe so Settings' status lines update
+ gpuProbe = null
+ gpuInfo = undefined
+ void hasGpuAcceleration()
+ sendEnvEvent('GPU engine ready', 'success')
+ return true
+ })()
+ .catch((err) => {
+ sendEnvEvent(
+ `GPU engine install failed: ${err instanceof Error ? err.message : String(err)}`,
+ 'error'
+ )
+ return false
+ })
+ .finally(() => {
+ gpuEnginePromise = null
+ })
+ }
+ return gpuEnginePromise.then(detach)
+}
+
+/* pip progress bars report absolute sizes ("45.2/2450.0 MB") rather than
+ percentages; tqdm-style output reports "%" directly */
+function pipProgressPct(line: string): number | null {
+ const pct = line.match(/(\d{1,3})%/)
+ if (pct) return parseInt(pct[1], 10)
+ const sizes = line.match(/([\d.]+)\s*\/\s*([\d.]+)\s*(GB|MB)/i)
+ if (sizes) {
+ const scale = sizes[3].toUpperCase() === 'GB' ? 1024 : 1
+ const done = parseFloat(sizes[1]) * scale
+ const total = parseFloat(sizes[2]) * scale
+ if (total > 0) return Math.round((done / total) * 100)
+ }
+ return null
+}
+
export function engineStatus(): EngineStatus {
return {
vocalsDownloading: vocalsEnginePromise !== null,
vocalsReady: existsSync(vocalsEnginePath()),
ftDownloading: ftWeightsPromise !== null,
- ftVerified
+ ftVerified,
+ gpuDownloading: gpuEnginePromise !== null,
+ gpuReady: IS_WIN && gpuInfo === true
}
}
diff --git a/src/main/globals.d.ts b/src/main/globals.d.ts
new file mode 100644
index 0000000..4fae1a9
--- /dev/null
+++ b/src/main/globals.d.ts
@@ -0,0 +1,3 @@
+// build-time constants injected by electron.vite.config.ts (main.define)
+declare const __STEMKIT_GA_ID__: string
+declare const __STEMKIT_GA_SECRET__: string
\ No newline at end of file
diff --git a/src/main/index.ts b/src/main/index.ts
index efd1414..cdb94af 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -11,6 +11,9 @@ import {
refreshReady,
ensureVocalsEngine,
ensureFtWeights,
+ ensureGpuEngine,
+ detectNvidiaGpu,
+ nvidiaGpuInfo,
hasGpuAcceleration,
gpuAccelerationInfo,
engineStatus,
@@ -21,6 +24,8 @@ import { loadSongs, removeSong, stemBuffers, stemsDir, stemsFor, mixWavPath } fr
import { startJob, cancelJob, searchYouTube } from './pipeline'
import { initUpdater } from './updater'
import { runSmoke } from './smoke'
+import { track, trackFromRenderer } from './analytics'
+import { getThumb, clearThumbMemo } from './thumbs'
let mainWindow: BrowserWindow | null = null
let staticServer: Server | null = null
@@ -111,7 +116,8 @@ async function createWindow(): Promise<void> {
app.whenReady().then(async () => {
// self-test mode for the windows-smoke CI job: bootstrap, separate a
- // generated tone through both engines, exit 0/1 without opening a window
+ // generated tone through both engines, exercise the GPU plumbing
+ // (cuda fail-fast paths + CUDA engine install), exit 0/1 without a window
if (process.env.STEMKIT_SMOKE === '1') {
const ok = await runSmoke()
app.exit(ok ? 0 : 1)
@@ -126,14 +132,20 @@ app.whenReady().then(async () => {
const settings = loadSettings()
if (settings.roformerVocals) void ensureVocalsEngine()
if (settings.htdemucsFt) void ensureFtWeights()
+ if (settings.gpuSplit) void ensureGpuEngine()
// warm the informational GPU probe so Settings can show it right away
void hasGpuAcceleration()
}
ipcMain.handle('env:status', async () => {
await detectTools()
- const status = { ...getStatus(), gpu: gpuAccelerationInfo() }
- // the probe result lands on a later status call; never blocks ready
+ void detectNvidiaGpu()
+ const status = {
+ ...getStatus(),
+ gpu: gpuAccelerationInfo(),
+ nvidiaGpu: nvidiaGpuInfo()
+ }
+ // the probe results land on a later status call; never blocks ready
if (status.ready) void hasGpuAcceleration()
return status
})
@@ -169,6 +181,7 @@ app.whenReady().then(async () => {
})
if (result.canceled || !result.filePath) return { saved: false }
copyFileSync(file, result.filePath)
+ track('export', { kind: 'stem', stem })
return { saved: true, path: result.filePath }
})
@@ -196,19 +209,38 @@ app.whenReady().then(async () => {
copyFileSync(mix, join(target, `${sanitizeName(song?.title ?? 'full track')}.wav`))
count += 1
}
+ track('export', { kind: 'all', stems: count })
return { saved: true, path: target, count }
})
ipcMain.handle('search:youtube', (_e, query: string) => searchYouTube(query))
ipcMain.handle('app:version', () => app.getVersion())
ipcMain.handle('settings:get', () => loadSettings())
- ipcMain.handle('settings:set', (_e, patch: Partial<AppSettings>) => saveSettings(patch))
+ ipcMain.handle('settings:set', (_e, patch: Partial<AppSettings>) => {
+ const prev = loadSettings()
+ const next = saveSettings(patch)
+ // hideVideo flips the thumbnail source, so cached lookups must retry
+ clearThumbMemo()
+ for (const key of Object.keys(patch) as (keyof AppSettings)[]) {
+ if (prev[key] !== next[key]) track('settings_changed', { setting: key })
+ }
+ return next
+ })
+ ipcMain.handle('thumb:get', (_e, videoId: string) => getThumb(videoId))
+ ipcMain.on('analytics:track', (_e, name: unknown, params: unknown) => {
+ trackFromRenderer(name, params)
+ })
// the renderer confirms optional-engine downloads explicitly; nothing
// starts as a side effect of flipping a toggle
- ipcMain.handle('engines:status', () => engineStatus())
- ipcMain.handle('engines:fetch', (_e, which: 'vocals' | 'ft') => {
+ ipcMain.handle('engines:status', () => {
+ // warm the cuda probe so gpuReady flips without waiting for a split
+ if (getStatus().ready) void hasGpuAcceleration()
+ return engineStatus()
+ })
+ ipcMain.handle('engines:fetch', (_e, which: 'vocals' | 'ft' | 'gpu') => {
if (which === 'vocals') void ensureVocalsEngine()
- else void ensureFtWeights()
+ else if (which === 'ft') void ensureFtWeights()
+ else void ensureGpuEngine()
})
initUpdater()
ipcMain.handle('open-external', (_e, url: string) => {
@@ -219,6 +251,7 @@ app.whenReady().then(async () => {
await detectTools()
await createWindow()
+ track('app_launch')
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) void createWindow()
diff --git a/src/main/library.ts b/src/main/library.ts
index c3fa12e..6d53ca7 100644
--- a/src/main/library.ts
+++ b/src/main/library.ts
@@ -1,4 +1,5 @@
import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync } from 'fs'
+import { readFile } from 'fs/promises'
import { join } from 'path'
import { userDataDir } from './env'
import { DEFAULT_STEMS, type Song } from '../shared/types'
@@ -66,14 +67,17 @@ export function stemsPresent(videoId: string, stems: string[]): boolean {
return stems.every((name) => existsSync(join(dir, `${name}.wav`)))
}
-export function stemBuffers(videoId: string, stems?: string[]): Record<string, Uint8Array> {
+export async function stemBuffers(videoId: string, stems?: string[]): Promise<Record<string, Uint8Array>> {
const list = stems ?? stemsFor(loadSongs().find((s) => s.videoId === videoId))
const dir = stemsDir(videoId)
const out: Record<string, Uint8Array> = {}
- for (const name of list) {
- const file = join(dir, `${name}.wav`)
- if (!existsSync(file)) throw new Error(`Missing stem ${name} for ${videoId}`)
- out[name] = new Uint8Array(readFileSync(file))
- }
+ // async parallel reads so ~400MB of WAV doesn't block the main process
+ await Promise.all(
+ list.map(async (name) => {
+ const file = join(dir, `${name}.wav`)
+ if (!existsSync(file)) throw new Error(`Missing stem ${name} for ${videoId}`)
+ out[name] = new Uint8Array(await readFile(file))
+ })
+ )
return out
}
diff --git a/src/main/pipeline.ts b/src/main/pipeline.ts
index 28dde91..e285970 100644
--- a/src/main/pipeline.ts
+++ b/src/main/pipeline.ts
@@ -12,6 +12,7 @@ import {
ensureEngineDeps,
ensureVocalsEngine,
ensureFtWeights,
+ ensureGpuEngine,
getStatus,
ytDlpRuntimeArgs
} from './env'
@@ -27,8 +28,10 @@ import {
loadSongs
} from './library'
import type { JobEvent, JobStage } from '../shared/types'
-import { MODEL_DEFAULT, MODEL_EXTENDED } from '../shared/types'
+import { MODEL_DEFAULT, MODEL_EXTENDED, DEFAULT_STEMS } from '../shared/types'
import { parseVideoId } from '../shared/url'
+import { track } from './analytics'
+import { cacheThumbnail } from './thumbs'
interface ActiveJob {
videoId: string
@@ -121,6 +124,15 @@ export async function startJob(
(settings.htdemucsFt && engine !== MODEL_EXTENDED ? '-ft' : '') +
(settings.shifts === 2 ? '@s2' : '')
+ // windows honors the GPU toggle: 'cpu' is passed explicitly because
+ // roformer.py's 'auto' prefers CUDA whenever the venv's torch supports it.
+ // macOS keeps 'auto' (MPS when available)
+ const useGpu = settings.gpuSplit && process.platform === 'win32'
+ const deviceArg = (): string => {
+ if (process.platform === 'win32') return useGpu ? 'cuda' : 'cpu'
+ return 'auto'
+ }
+
const job: ActiveJob = { videoId, model: modelTag, cancelled: false }
jobs.set(videoId, job)
const startedAt = Date.now()
@@ -144,6 +156,11 @@ export async function startJob(
rmSync(songDir(videoId), { recursive: true, force: true })
}
+ track('split_started', {
+ model: modelTag,
+ stems: stems?.length ?? DEFAULT_STEMS.length,
+ gpu: useGpu
+ })
mkdirSync(songDir(videoId), { recursive: true })
progress(job, 'metadata', 0, 'Reading video info')
@@ -160,6 +177,8 @@ export async function startJob(
title: typeof parsed.title === 'string' ? parsed.title : 'Unknown title',
duration: typeof parsed.duration === 'number' ? Math.round(parsed.duration) : 0
}
+ // warm the thumbnail cache for offline library browsing
+ void cacheThumbnail(videoId, typeof parsed.thumbnail === 'string' ? parsed.thumbnail : undefined)
} catch {
bail('Could not read video metadata')
}
@@ -230,6 +249,17 @@ export async function startJob(
const release = await acquireSeparation()
try {
if (job.cancelled || !jobs.has(videoId)) return
+ // self-heal the GPU engine: the toggle may be on before the CUDA torch
+ // download has run (fresh setting, or a failed earlier attempt)
+ if (useGpu) {
+ if (
+ !(await ensureGpuEngine((pct) =>
+ progress(job, 'separate', 0, `Downloading GPU engine: ${pct}%`)
+ ))
+ ) {
+ bail('Could not prepare the GPU engine — switch back to CPU in Settings and try again')
+ }
+ }
let scriptError: string | null = null
const producedStems: string[] = []
@@ -280,7 +310,7 @@ export async function startJob(
'--model',
MODEL_EXTENDED,
'--device',
- 'auto',
+ deviceArg(),
'--shifts',
String(settings.shifts),
...(stems?.length ? ['--only', stems.join(',')] : [])
@@ -324,7 +354,7 @@ export async function startJob(
'--ckpt-dir',
modelsDir(),
'--device',
- 'auto'
+ deviceArg()
],
lineParsers((pct, msg) => {
if (!msg) return vocalsBase + Math.round((pct / 100) * (roformerSpan - vocalsBase))
@@ -367,7 +397,7 @@ export async function startJob(
'--model',
settings.htdemucsFt ? 'htdemucs_ft' : 'htdemucs',
'--device',
- 'auto',
+ deviceArg(),
'--shifts',
String(settings.shifts),
'--only',
@@ -403,7 +433,7 @@ export async function startJob(
'--model',
engine,
'--device',
- 'auto',
+ deviceArg(),
'--shifts',
String(settings.shifts),
...(stems?.length ? ['--only', stems.join(',')] : [])
@@ -418,6 +448,7 @@ export async function startJob(
if (!stemsPresent(videoId, producedStems)) bail('Separation finished but stem files are missing')
progress(job, 'finalize', 100, 'Adding to library')
+ const took = Math.round((Date.now() - startedAt) / 1000)
const songs = upsertSong({
videoId,
title: meta!.title,
@@ -425,8 +456,9 @@ export async function startJob(
addedAt: existing?.addedAt ?? Date.now(),
model: job.model,
stems: producedStems,
- took: Math.round((Date.now() - startedAt) / 1000)
+ took
})
+ track('split_completed', { model: job.model, stems: producedStems.length, took })
send({ kind: 'done', data: { videoId, song: songs[0] } })
} finally {
release()
@@ -434,6 +466,7 @@ export async function startJob(
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
if (message !== 'cancelled') {
+ track('split_failed', { model: job.model })
send({ kind: 'failed', data: { videoId, message } })
}
} finally {
@@ -533,7 +566,7 @@ export async function searchYouTube(query: string): Promise<
try {
const data = JSON.parse(results)
const entries = Array.isArray(data.entries) ? data.entries : []
- return entries
+ const mapped = entries
.filter((e: Record<string, unknown>) => typeof e.id === 'string' && typeof e.title === 'string')
.map((e: Record<string, unknown>) => ({
videoId: e.id as string,
@@ -546,6 +579,8 @@ export async function searchYouTube(query: string): Promise<
: undefined,
duration: typeof e.duration === 'number' ? Math.round(e.duration) : undefined
}))
+ track('search', { results: mapped.length })
+ return mapped
} catch {
return []
}
diff --git a/src/main/settings.ts b/src/main/settings.ts
index ec2b4d6..302b862 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -22,7 +22,10 @@ export function saveSettings(patch: Partial<AppSettings>): AppSettings {
const next: AppSettings = {
shifts: merged.shifts === 2 ? 2 : 1,
htdemucsFt: !!merged.htdemucsFt,
- roformerVocals: !!merged.roformerVocals
+ roformerVocals: !!merged.roformerVocals,
+ gpuSplit: !!merged.gpuSplit,
+ hideVideo: !!merged.hideVideo,
+ analytics: !!merged.analytics
}
writeFileSync(settingsFile(), JSON.stringify(next, null, 2))
for (const win of BrowserWindow.getAllWindows()) {
diff --git a/src/main/smoke.ts b/src/main/smoke.ts
index 4a4f8d9..9567028 100644
--- a/src/main/smoke.ts
+++ b/src/main/smoke.ts
@@ -12,7 +12,9 @@ import {
roformerScript,
modelsDir,
bundledFfmpeg,
- ensureEngineDeps
+ ensureEngineDeps,
+ ensureGpuEngine,
+ detectNvidiaGpu
} from './env'
/* self-test mode, driven by STEMKIT_SMOKE=1 (used by the windows-smoke CI
@@ -95,6 +97,37 @@ function generateMix(dest: string): Promise<void> {
})
}
+function runCapture(cmd: string, args: string[]): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(cmd, args, { env: { ...process.env } })
+ let out = ''
+ let err = ''
+ child.stdout?.on('data', (c: Buffer) => {
+ out += c.toString()
+ })
+ child.stderr?.on('data', (c: Buffer) => {
+ err += c.toString()
+ })
+ child.on('error', reject)
+ child.on('close', (code) =>
+ code === 0 ? resolve(out) : reject(new Error(err.slice(-300) || `exit ${code}`))
+ )
+ })
+}
+
+/* the friendly cuda failure is expected on every GPU-less machine: a split
+ asked to run on cuda must exit non-zero with the actionable message rather
+ than a cryptic torch crash */
+async function expectCudaFailure(label: string, args: string[]): Promise<boolean> {
+ const result = await runScript(venvPython(), args)
+ if (result.ok || !(result.error ?? '').includes('GPU engine not available')) {
+ log(`FAIL: ${label}: expected "GPU engine not available", got ok=${result.ok} error=${result.error}`)
+ return false
+ }
+ log(`${label}: fail-fast ok`)
+ return true
+}
+
/* our float32 WAVs are standard 44-byte headers: format 3 (IEEE float), 32 bits */
function isFloat32Wav(path: string): boolean {
try {
@@ -179,6 +212,60 @@ export async function runSmoke(): Promise<boolean> {
}
log('roformer vocals ok')
+ // GPU plumbing on this GPU-less runner: --device cuda must fail fast
+ // with the friendly message (on the default cpu torch, before any big
+ // downloads), and the CUDA wheel swap must install cleanly while
+ // torch.cuda.is_available() stays false (no NVIDIA driver here). The
+ // real CUDA execution path still needs a machine with an NVIDIA GPU
+ const nvidia = await detectNvidiaGpu()
+ log(`nvidia gpu detected: ${nvidia}`)
+
+ if (
+ !(await expectCudaFailure('cuda on cpu torch', [
+ separateScript(),
+ '--input', mix,
+ '--out', join(dir, 'stems-cuda-demucs'),
+ '--model', 'htdemucs',
+ '--device', 'cuda'
+ ]))
+ ) {
+ return false
+ }
+
+ if (process.env.STEMKIT_SMOKE_SKIP_GPU === '1') {
+ log('skipping GPU engine install (STEMKIT_SMOKE_SKIP_GPU=1)')
+ } else {
+ if (!(await ensureGpuEngine((pct) => log(`gpu engine install: ${pct}%`)))) {
+ log('FAIL: GPU engine (cuda torch) did not install')
+ return false
+ }
+ try {
+ const info = await runCapture(venvPython(), [
+ '-c', 'import torch;print("cuda", torch.version.cuda, int(torch.cuda.is_available()))'
+ ])
+ const [, ver, avail] = info.trim().split(/\s+/)
+ if (!ver || ver === 'None' || avail !== '0') {
+ log(`FAIL: unexpected torch cuda state: "${info.trim()}"`)
+ return false
+ }
+ log(`cuda torch ok (version.cuda=${ver}, available=0)`)
+ } catch (e) {
+ log(`FAIL: could not probe torch cuda state: ${e instanceof Error ? e.message : String(e)}`)
+ return false
+ }
+ if (
+ !(await expectCudaFailure('cuda on cuda torch without nvidia driver', [
+ roformerScript(),
+ '--input', mix,
+ '--out', join(dir, 'stems-cuda-roformer'),
+ '--ckpt-dir', modelsDir(),
+ '--device', 'cuda'
+ ]))
+ ) {
+ return false
+ }
+ }
+
log('SMOKE RESULT: PASS')
return true
} catch (err) {
diff --git a/src/main/thumbs.ts b/src/main/thumbs.ts
new file mode 100644
index 0000000..2bbe407
--- /dev/null
+++ b/src/main/thumbs.ts
@@ -0,0 +1,82 @@
+import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'
+import { join } from 'path'
+import { net } from 'electron'
+import { userDataDir } from './env'
+import { loadSettings } from './settings'
+
+// mqdefault (320x180) covers every thumbnail slot in the app; library
+// thumbnails come from this local cache instead of i.ytimg.com once the
+// "hide video" setting is on
+const YT_THUMB_URL = 'https://i.ytimg.com/vi/'
+
+const memo = new Map<string, Promise<string | null>>()
+
+function thumbsDir(): string {
+ return join(userDataDir(), 'thumbs')
+}
+
+function thumbPath(videoId: string): string {
+ return join(thumbsDir(), `${videoId}.jpg`)
+}
+
+const VALID_ID = /^[\w-]{11}$/
+
+function toDataUrl(buf: Buffer): string {
+ return `data:image/jpeg;base64,${buf.toString('base64')}`
+}
+
+// called from the split pipeline (metadata stage) so the cache is warm
+// before the song ever shows up in the library
+export async function cacheThumbnail(videoId: string, url?: string): Promise<void> {
+ if (!VALID_ID.test(videoId)) return
+ const file = thumbPath(videoId)
+ if (existsSync(file)) return
+ const source = typeof url === 'string' && /^https:\/\//.test(url) ? url : `${YT_THUMB_URL}${videoId}/mqdefault.jpg`
+ try {
+ const res = await net.fetch(source, { signal: AbortSignal.timeout(10000) })
+ if (!res.ok) return
+ const buf = Buffer.from(await res.arrayBuffer())
+ if (buf.length === 0) return
+ mkdirSync(thumbsDir(), { recursive: true })
+ writeFileSync(file, buf)
+ memo.delete(videoId)
+ } catch {}
+}
+
+// resolves to a data URL from the local cache. When the "hide video" setting
+// is on, nothing is fetched online — missing thumbs just stay placeholders
+export function getThumb(videoId: string): Promise<string | null> {
+ if (!VALID_ID.test(videoId)) return Promise.resolve(null)
+ let p = memo.get(videoId)
+ if (p) return p
+ p = (async (): Promise<string | null> => {
+ const file = thumbPath(videoId)
+ if (existsSync(file)) {
+ try {
+ return toDataUrl(readFileSync(file))
+ } catch {}
+ }
+ if (loadSettings().hideVideo) return null
+ try {
+ const res = await net.fetch(`${YT_THUMB_URL}${videoId}/mqdefault.jpg`, {
+ signal: AbortSignal.timeout(10000)
+ })
+ if (!res.ok) return null
+ const buf = Buffer.from(await res.arrayBuffer())
+ if (buf.length === 0) return null
+ mkdirSync(thumbsDir(), { recursive: true })
+ writeFileSync(file, buf)
+ return toDataUrl(buf)
+ } catch {
+ return null
+ }
+ })()
+ memo.set(videoId, p)
+ return p
+}
+
+// hideVideo flipped: previously-returned nulls may now be servable and the
+// other way around, so drop every cached resolution
+export function clearThumbMemo(): void {
+ memo.clear()
+}
\ No newline at end of file
diff --git a/src/main/updater.ts b/src/main/updater.ts
index d26f100..253e7be 100644
--- a/src/main/updater.ts
+++ b/src/main/updater.ts
@@ -1,5 +1,6 @@
import { app, BrowserWindow, ipcMain } from 'electron'
import { autoUpdater } from 'electron-updater'
+import { track } from './analytics'
function send(status: string, payload?: Record<string, unknown>): void {
for (const win of BrowserWindow.getAllWindows()) {
@@ -14,13 +15,20 @@ export function initUpdater(): void {
autoUpdater.autoInstallOnAppQuit = true
autoUpdater.on('checking-for-update', () => send('checking'))
- autoUpdater.on('update-available', (info) => send('available', { version: info.version }))
+ autoUpdater.on('update-available', (info) => {
+ track('update_available', { version: info.version })
+ send('available', { version: info.version })
+ })
autoUpdater.on('update-not-available', (info) => send('none', { version: info.version }))
autoUpdater.on('download-progress', (p) => send('progress', { pct: Math.round(p.percent) }))
- autoUpdater.on('update-downloaded', (info) => send('downloaded', { version: info.version }))
+ autoUpdater.on('update-downloaded', (info) => {
+ track('update_downloaded', { version: info.version })
+ send('downloaded', { version: info.version })
+ })
autoUpdater.on('error', () => send('error'))
ipcMain.handle('update:install', () => {
+ track('update_installed')
autoUpdater.quitAndInstall()
})
ipcMain.handle('update:check', async () => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b2c7026..b1a36ad 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -26,6 +26,8 @@ const api: StemKitApi = {
installUpdate: () => ipcRenderer.invoke('update:install'),
getSettings: () => ipcRenderer.invoke('settings:get'),
setSettings: (patch) => ipcRenderer.invoke('settings:set', patch),
+ trackEvent: (name, params) => ipcRenderer.send('analytics:track', name, params),
+ getThumb: (videoId) => ipcRenderer.invoke('thumb:get', videoId),
enginesStatus: () => ipcRenderer.invoke('engines:status'),
fetchEngine: (which) => ipcRenderer.invoke('engines:fetch', which),
onUpdateEvent: (cb) => subscribe<UpdateEvent>('update:event', cb),
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 9e28dd3..5221300 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -222,7 +222,7 @@ export default function App(): React.ReactElement {
/>
)
} else if (activeSong) {
- main = <Player key={activeSong.videoId} song={activeSong} />
+ main = <Player key={activeSong.videoId} song={activeSong} settings={settings ?? undefined} />
} else {
main = (
<Home
@@ -262,6 +262,7 @@ export default function App(): React.ReactElement {
<Settings
settings={settings}
gpu={status.gpu}
+ nvidiaGpu={status.nvidiaGpu}
onChange={(patch) => void window.stemkit.setSettings(patch)}
onClose={() => setSettingsOpen(false)}
/>
diff --git a/src/renderer/src/components/Home.tsx b/src/renderer/src/components/Home.tsx
index 64f78e8..ef22e30 100644
--- a/src/renderer/src/components/Home.tsx
+++ b/src/renderer/src/components/Home.tsx
@@ -188,7 +188,7 @@ export function Home({
</span>
<button
onClick={onOpenSettings}
- title="Quality settings"
+ title="Settings"
className="no-drag w-5 h-5 rounded-md hover:bg-white/10 text-white/35 hover:text-white flex items-center justify-center transition-colors"
>
<GearIcon className="w-3 h-3" />
diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsx
index 6a36e74..9e652e8 100644
--- a/src/renderer/src/components/Player.tsx
+++ b/src/renderer/src/components/Player.tsx
@@ -1,8 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import type { Song, StemId } from '../../../shared/types'
+import type { AppSettings, Song, StemId } from '../../../shared/types'
import { engine, decodePayload, type BufferMap } from '../lib/engine'
import { buildStemMeta } from '../lib/stems'
import { fmtTime } from '../lib/format'
+import { Thumb } from '../lib/thumbs'
import { YouTubeHost, type YTState } from '../lib/youtube'
import { StemLane } from './StemLane'
import { Transport, type PresetId } from './Transport'
@@ -29,9 +30,10 @@ function getDecoded(videoId: string): Promise<BufferCacheMap> {
interface Props {
song: Song
+ settings?: AppSettings
}
-export function Player({ song }: Props): React.ReactElement {
+export function Player({ song, settings }: Props): React.ReactElement {
const containerRef = useRef<HTMLDivElement>(null)
const hostRef = useRef<YouTubeHost | null>(null)
const posRef = useRef(0)
@@ -58,6 +60,9 @@ export function Player({ song }: Props): React.ReactElement {
const stemMeta = useMemo(() => buildStemMeta(Object.keys(buffers) as StemId[]), [buffers])
const youtubeUrl = `https://www.youtube.com/watch?v=${song.videoId}`
+ // stems always play locally from the library; hiding the video just stops
+ // streaming it from YouTube (and switches thumbnails to the local cache)
+ const hideVideo = settings?.hideVideo ?? false
const addedLabel = new Date(song.addedAt).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
@@ -106,6 +111,12 @@ export function Player({ song }: Props): React.ReactElement {
}, [song.videoId])
useEffect(() => {
+ if (hideVideo) {
+ hostRef.current?.destroy()
+ hostRef.current = null
+ setYtReady(false)
+ return
+ }
if (decoding || decodeError || hostRef.current) return
let disposed = false
const container = containerRef.current
@@ -130,7 +141,7 @@ export function Player({ song }: Props): React.ReactElement {
return () => {
disposed = true
}
- }, [song.videoId, decoding, decodeError])
+ }, [song.videoId, decoding, decodeError, hideVideo])
useEffect(() => {
engine.applyMix(vols, mutes, solos, master)
@@ -197,8 +208,9 @@ export function Player({ song }: Props): React.ReactElement {
engine.setPlaying(true, posRef.current)
hostRef.current?.play()
setPlaying(true)
+ window.stemkit.trackEvent('playback_started', { video_hidden: hideVideo })
}
- }, [decoding, decodeError])
+ }, [decoding, decodeError, hideVideo])
const seekTo = useCallback(
(t: number): void => {
@@ -294,32 +306,32 @@ export function Player({ song }: Props): React.ReactElement {
<div className="flex-1 min-h-0 overflow-y-auto px-6 pb-6">
<div className="max-w-6xl mx-auto">
<div className="flex items-stretch gap-4 h-[220px]">
- <div className="relative w-[391px] shrink-0">
- <div className="absolute -inset-4 bg-violet-500/10 blur-3xl rounded-full pointer-events-none" />
- <div className="absolute inset-0 rounded-xl overflow-hidden ring-1 ring-white/10 bg-black shadow-2xl shadow-black/60">
- <div ref={containerRef} className="absolute inset-0 [&_iframe]:w-full [&_iframe]:h-full" />
- {!ytReady && (
- <div className="absolute inset-0 flex items-center justify-center animate-pulse">
- <span className="text-[10px] text-white/40 tracking-widest uppercase">loading…</span>
- </div>
- )}
- {decodeError && (
- <div className="absolute inset-x-3 bottom-3 flex justify-center rise-in">
- <div className="glass rounded-lg px-3 py-1.5 text-xs text-rose-300 break-words">
- {decodeError}
+ {!hideVideo && (
+ <div className="relative w-[391px] shrink-0">
+ <div className="absolute -inset-4 bg-violet-500/10 blur-3xl rounded-full pointer-events-none" />
+ <div className="absolute inset-0 rounded-xl overflow-hidden ring-1 ring-white/10 bg-black shadow-2xl shadow-black/60">
+ <div ref={containerRef} className="absolute inset-0 [&_iframe]:w-full [&_iframe]:h-full" />
+ {!ytReady && (
+ <div className="absolute inset-0 flex items-center justify-center animate-pulse">
+ <span className="text-[10px] text-white/40 tracking-widest uppercase">loading…</span>
+ </div>
+ )}
+ {decodeError && (
+ <div className="absolute inset-x-3 bottom-3 flex justify-center rise-in">
+ <div className="glass rounded-lg px-3 py-1.5 text-xs text-rose-300 break-words">
+ {decodeError}
+ </div>
</div>
- </div>
- )}
+ )}
+ </div>
</div>
- </div>
+ )}
<aside className="flex-1 min-w-0 glass rounded-2xl px-6 py-5 rise-in flex flex-col justify-between">
<div className="flex items-center gap-4">
- <img
- src={`https://i.ytimg.com/vi/${song.videoId}/mqdefault.jpg`}
- alt=""
- className="w-32 h-[72px] rounded-lg object-cover bg-white/5 shrink-0"
- draggable={false}
+ <Thumb
+ videoId={song.videoId}
+ className="w-32 h-[72px] rounded-lg object-cover bg-white/5 shrink-0 block"
/>
<div className="min-w-0 flex-1">
<h3 className="text-xl font-semibold leading-snug truncate">{song.title}</h3>
@@ -333,6 +345,12 @@ export function Player({ song }: Props): React.ReactElement {
</span>
</div>
+ {hideVideo && decodeError && (
+ <div className="rounded-xl bg-rose-500/10 border border-rose-400/20 px-3 py-2 text-xs text-rose-200 break-words">
+ {decodeError}
+ </div>
+ )}
+
<div className="flex items-center gap-x-6 gap-y-2 flex-wrap">
{stemMeta.map((meta) => (
<span key={meta.id} className="flex items-center gap-2 text-[14px] text-white/75">
@@ -375,7 +393,15 @@ export function Player({ song }: Props): React.ReactElement {
/>
<div className="mt-4 space-y-2">
- {stemMeta.map((meta) => (
+ {decoding
+ ? [...Array(4)].map((_, i) => (
+ <div
+ key={i}
+ className="glass rounded-xl h-16 animate-pulse"
+ style={{ animationDelay: `${i * 120}ms` }}
+ />
+ ))
+ : stemMeta.map((meta) => (
<StemLane
key={meta.id}
meta={meta}
diff --git a/src/renderer/src/components/Processing.tsx b/src/renderer/src/components/Processing.tsx
index bbc2823..1fcc15b 100644
--- a/src/renderer/src/components/Processing.tsx
+++ b/src/renderer/src/components/Processing.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import type { JobProgress } from '../../../shared/types'
import { fmtTime } from '../lib/format'
+import { Thumb } from '../lib/thumbs'
import { XIcon } from './Icons'
const STAGES: { id: JobProgress['stage']; label: string }[] = [
@@ -78,10 +79,9 @@ export function Processing({
<div className="w-full max-w-md glass rounded-2xl p-7 rise-in">
<div className="flex items-center gap-3.5">
{job?.videoId ? (
- <img
- src={`https://i.ytimg.com/vi/${job.videoId}/default.jpg`}
- alt=""
- className="w-16 h-9 rounded-lg object-cover bg-white/5"
+ <Thumb
+ videoId={job.videoId}
+ className="w-16 h-9 rounded-lg object-cover bg-white/5 block"
/>
) : (
<span className="w-10 h-10 rounded-full border-2 border-white/20 border-t-violet-300 animate-spin" />
diff --git a/src/renderer/src/components/Settings.tsx b/src/renderer/src/components/Settings.tsx
index 68da31b..ff9e2da 100644
--- a/src/renderer/src/components/Settings.tsx
+++ b/src/renderer/src/components/Settings.tsx
@@ -5,6 +5,7 @@ import { XIcon } from './Icons'
interface Props {
settings: AppSettings
gpu?: boolean
+ nvidiaGpu?: boolean
onChange: (patch: Partial<AppSettings>) => void
onClose: () => void
}
@@ -101,14 +102,23 @@ function ConfirmButton({ label, onClick }: { label: string; onClick: () => void
)
}
-export function Settings({ settings, gpu, onChange, onClose }: Props): React.ReactElement {
+function SectionHeader({ label }: { label: string }): React.ReactElement {
+ return (
+ <h3 className="text-[11px] font-semibold uppercase tracking-widest text-white/30">{label}</h3>
+ )
+}
+
+export function Settings({ settings, gpu, nvidiaGpu, onChange, onClose }: Props): React.ReactElement {
const [engines, setEngines] = useState<EngineStatus | null>(null)
const [vocalsPct, setVocalsPct] = useState<number | null>(null)
const [ftPct, setFtPct] = useState<number | null>(null)
+ const [gpuPct, setGpuPct] = useState<number | null>(null)
const [vocalsError, setVocalsError] = useState<string | null>(null)
const [ftError, setFtError] = useState<string | null>(null)
+ const [gpuError, setGpuError] = useState<string | null>(null)
const [vocalsStarting, setVocalsStarting] = useState(false)
const [ftStarting, setFtStarting] = useState(false)
+ const [gpuStarting, setGpuStarting] = useState(false)
useEffect(() => {
const off = window.stemkit.onEnvEvent((e) => {
@@ -127,6 +137,14 @@ export function Settings({ settings, gpu, onChange, onClose }: Props): React.Rea
}
if (/Fine-tuned engine ready/.test(e.message)) setFtPct(100)
if (/Fine-tuned engine download failed/.test(e.message)) setFtError(e.message)
+
+ const gpuEngine = e.message.match(/GPU engine: (\d+)%/)
+ if (gpuEngine) {
+ setGpuPct(parseInt(gpuEngine[1], 10))
+ setGpuError(null)
+ }
+ if (/GPU engine ready/.test(e.message)) setGpuPct(100)
+ if (/GPU engine install failed/.test(e.message)) setGpuError(e.message)
})
return off
}, [])
@@ -141,6 +159,7 @@ export function Settings({ settings, gpu, onChange, onClose }: Props): React.Rea
setEngines(s)
if (s.vocalsDownloading || s.vocalsReady) setVocalsStarting(false)
if (s.ftDownloading || s.ftVerified) setFtStarting(false)
+ if (s.gpuDownloading || s.gpuReady) setGpuStarting(false)
})
}
tick()
@@ -162,15 +181,20 @@ export function Settings({ settings, gpu, onChange, onClose }: Props): React.Rea
const gpuLine =
gpu === true
? 'Uses your GPU — fast'
- : gpu === false
- ? 'No GPU found — expect ~20-35 min per song on CPU'
- : null
+ : gpu === false && nvidiaGpu
+ ? 'Running on CPU — enable GPU acceleration below for much faster splits'
+ : gpu === false
+ ? 'No GPU found — expect ~20-35 min per song on CPU'
+ : null
const vocalsBusy = vocalsStarting || (engines?.vocalsDownloading ?? false)
const ftBusy = ftStarting || (engines?.ftDownloading ?? false)
+ const gpuBusy = gpuStarting || (engines?.gpuDownloading ?? false)
const showVocalsConfirm =
!!engines && settings.roformerVocals && !engines.vocalsReady && !vocalsBusy
const showFtConfirm = !!engines && settings.htdemucsFt && !engines.ftVerified && !ftBusy
+ const showGpuConfirm =
+ !!engines && settings.gpuSplit && nvidiaGpu && !engines.gpuReady && !gpuBusy
const startVocals = (): void => {
setVocalsStarting(true)
@@ -186,6 +210,13 @@ export function Settings({ settings, gpu, onChange, onClose }: Props): React.Rea
void window.stemkit.fetchEngine('ft')
}
+ const startGpu = (): void => {
+ setGpuStarting(true)
+ setGpuPct(null)
+ setGpuError(null)
+ void window.stemkit.fetchEngine('gpu')
+ }
+
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
@@ -196,7 +227,7 @@ export function Settings({ settings, gpu, onChange, onClose }: Props): React.Rea
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/[0.07]">
- <h2 className="text-[14px] font-semibold tracking-tight">Quality settings</h2>
+ <h2 className="text-[14px] font-semibold tracking-tight">Settings</h2>
<button
onClick={onClose}
title="Close"
@@ -206,80 +237,136 @@ export function Settings({ settings, gpu, onChange, onClose }: Props): React.Rea
</button>
</div>
- <div className="px-5 py-4 space-y-5">
- <div className="flex items-start justify-between gap-4">
- <div className="min-w-0">
- <p className="text-[13px] font-medium">Studio-quality vocals</p>
- <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
- Cleaner, more natural vocal separation.
- </p>
- {gpuLine && <p className="text-[11px] text-white/30 mt-1">{gpuLine}</p>}
- <DownloadBar pct={vocalsPct} starting={vocalsBusy && vocalsPct === null} error={vocalsError} />
- {showVocalsConfirm && (
- <ConfirmButton label="Download now · 913 MB" onClick={startVocals} />
- )}
+ <div className="px-5 py-4 space-y-6 max-h-[70vh] overflow-y-auto">
+ <section className="space-y-5">
+ <SectionHeader label="Separation" />
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">Studio-quality vocals</p>
+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
+ Cleaner, more natural vocal separation.
+ </p>
+ {gpuLine && <p className="text-[11px] text-white/30 mt-1">{gpuLine}</p>}
+ <DownloadBar pct={vocalsPct} starting={vocalsBusy && vocalsPct === null} error={vocalsError} />
+ {showVocalsConfirm && (
+ <ConfirmButton label="Download now · 913 MB" onClick={startVocals} />
+ )}
+ </div>
+ <Toggle
+ on={settings.roformerVocals}
+ disabled={vocalsBusy}
+ loading={vocalsBusy}
+ onClick={() => onChange({ roformerVocals: !settings.roformerVocals })}
+ />
</div>
- <Toggle
- on={settings.roformerVocals}
- disabled={vocalsBusy}
- loading={vocalsBusy}
- onClick={() => onChange({ roformerVocals: !settings.roformerVocals })}
- />
- </div>
- <div className="flex items-start justify-between gap-4">
- <div className="min-w-0">
- <p className="text-[13px] font-medium">Cleaner instruments</p>
- <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
- Extra polish for drums, bass and other. Up to 4× slower.
- </p>
- <DownloadBar pct={ftPct} starting={ftBusy && ftPct === null} error={ftError} />
- {showFtConfirm && (
- <ConfirmButton label="Download now · ~320 MB" onClick={startFt} />
- )}
+ {nvidiaGpu && (
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">GPU acceleration</p>
+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
+ Use your NVIDIA GPU for much faster splits.
+ </p>
+ <DownloadBar pct={gpuPct} starting={gpuBusy && gpuPct === null} error={gpuError} />
+ {showGpuConfirm && (
+ <ConfirmButton label="Download now · ~2.5 GB" onClick={startGpu} />
+ )}
+ </div>
+ <Toggle
+ on={settings.gpuSplit}
+ disabled={gpuBusy}
+ loading={gpuBusy}
+ onClick={() => onChange({ gpuSplit: !settings.gpuSplit })}
+ />
+ </div>
+ )}
+
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">Cleaner instruments</p>
+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
+ Extra polish for drums, bass and other. Up to 4× slower.
+ </p>
+ <DownloadBar pct={ftPct} starting={ftBusy && ftPct === null} error={ftError} />
+ {showFtConfirm && (
+ <ConfirmButton label="Download now · ~320 MB" onClick={startFt} />
+ )}
+ </div>
+ <Toggle
+ on={settings.htdemucsFt}
+ disabled={ftBusy}
+ loading={ftBusy}
+ onClick={() => onChange({ htdemucsFt: !settings.htdemucsFt })}
+ />
</div>
- <Toggle
- on={settings.htdemucsFt}
- disabled={ftBusy}
- loading={ftBusy}
- onClick={() => onChange({ htdemucsFt: !settings.htdemucsFt })}
- />
- </div>
- <div className="flex items-start justify-between gap-4">
- <div className="min-w-0">
- <p className="text-[13px] font-medium">Extra quality pass</p>
- <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
- Separates the song twice and blends the takes for cleaner results. Up to 3×
- slower.
- </p>
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">Extra quality pass</p>
+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
+ Separates the song twice and blends the takes for cleaner results. Up to 3×
+ slower.
+ </p>
+ </div>
+ <div className="flex shrink-0 rounded-lg bg-white/[0.06] p-0.5 border border-white/[0.08]">
+ {([
+ { v: 1 as const, label: 'Fast' },
+ { v: 2 as const, label: 'Best' }
+ ]).map((opt) => (
+ <button
+ key={opt.v}
+ onClick={() => onChange({ shifts: opt.v })}
+ className={`no-drag px-2.5 h-6 rounded-md text-[12px] font-semibold transition-colors ${
+ settings.shifts === opt.v
+ ? 'bg-white text-black'
+ : 'text-white/45 hover:text-white/80'
+ }`}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
</div>
- <div className="flex shrink-0 rounded-lg bg-white/[0.06] p-0.5 border border-white/[0.08]">
- {([
- { v: 1 as const, label: 'Fast' },
- { v: 2 as const, label: 'Best' }
- ]).map((opt) => (
- <button
- key={opt.v}
- onClick={() => onChange({ shifts: opt.v })}
- className={`no-drag px-2.5 h-6 rounded-md text-[12px] font-semibold transition-colors ${
- settings.shifts === opt.v
- ? 'bg-white text-black'
- : 'text-white/45 hover:text-white/80'
- }`}
- >
- {opt.label}
- </button>
- ))}
+
+ <p className="text-[11px] text-white/30 leading-relaxed">
+ Changes apply to future splits. Songs you already split keep their current sound —
+ split them again to use the new settings.
+ </p>
+ </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">
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">Hide YouTube video</p>
+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
+ Stems always play locally from your library. This stops streaming the video
+ while you play and uses cached thumbnails instead.
+ </p>
+ </div>
+ <Toggle
+ on={settings.hideVideo}
+ onClick={() => onChange({ hideVideo: !settings.hideVideo })}
+ />
</div>
- </div>
- </div>
+ </section>
- <div className="px-5 py-3 border-t border-white/[0.07]">
- <p className="text-[11px] text-white/30 leading-relaxed">
- Changes apply to future splits. Songs you already split keep their current sound —
- split them again to use the new settings.
- </p>
+ <section className="pt-5 border-t border-white/[0.06] space-y-5">
+ <SectionHeader label="Privacy" />
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-[13px] font-medium">Anonymous usage stats</p>
+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">
+ On by default. Helps improve StemKit with anonymous events (app version, OS,
+ actions). Song titles, links and audio never leave your machine.
+ </p>
+ </div>
+ <Toggle
+ on={settings.analytics}
+ onClick={() => onChange({ analytics: !settings.analytics })}
+ />
+ </div>
+ </section>
</div>
</div>
</div>
diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsx
index 3b4e6c1..9db1996 100644
--- a/src/renderer/src/components/Sidebar.tsx
+++ b/src/renderer/src/components/Sidebar.tsx
@@ -1,5 +1,6 @@
import type { Song } from '../../../shared/types'
import { fmtTime } from '../lib/format'
+import { Thumb } from '../lib/thumbs'
import { LogoMark, TrashIcon, PlusIcon, GearIcon } from './Icons'
interface Props {
@@ -34,7 +35,7 @@ export function Sidebar({
<span className="font-semibold tracking-tight text-[15px]">StemKit</span>
<button
onClick={onOpenSettings}
- title="Quality settings"
+ title="Settings"
className="no-drag ml-auto w-7 h-7 rounded-lg bg-white/5 hover:bg-white/10 text-white/50 hover:text-white flex items-center justify-center transition-colors"
>
<GearIcon className="w-3.5 h-3.5" />
@@ -76,11 +77,9 @@ export function Sidebar({
}`}
>
<span className="relative shrink-0">
- <img
- src={`https://i.ytimg.com/vi/${song.videoId}/default.jpg`}
- alt=""
- className={`w-12 h-[27px] rounded-md object-cover bg-white/5 ${working ? 'opacity-70' : ''}`}
- draggable={false}
+ <Thumb
+ videoId={song.videoId}
+ className={`w-12 h-[27px] rounded-md object-cover bg-white/5 block ${working ? 'opacity-70' : ''}`}
/>
{working && (
<span className="absolute inset-0 flex items-center justify-center">
diff --git a/src/renderer/src/lib/engine.ts b/src/renderer/src/lib/engine.ts
index 4d6907e..bfd2e2f 100644
--- a/src/renderer/src/lib/engine.ts
+++ b/src/renderer/src/lib/engine.ts
@@ -7,11 +7,16 @@ export async function decodePayload(
): Promise<BufferMap> {
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 = {}
- for (const id of Object.keys(payload)) {
- const copy = payload[id].slice()
- out[id as StemId] = await ctx.decodeAudioData(copy.buffer as ArrayBuffer)
- }
+ ids.forEach((id, i) => {
+ out[id as StemId] = decoded[i]
+ })
return out
}
diff --git a/src/renderer/src/lib/thumbs.tsx b/src/renderer/src/lib/thumbs.tsx
new file mode 100644
index 0000000..18690c4
--- /dev/null
+++ b/src/renderer/src/lib/thumbs.tsx
@@ -0,0 +1,42 @@
+import { useEffect, useState } from 'react'
+
+// library thumbnails resolve through the local cache in the main process
+// (userData/thumbs). Setting changes re-resolve: hideVideo on/off changes
+// whether missing thumbs may still be fetched online
+const memo = new Map<string, Promise<string | null>>()
+
+function getThumbCached(videoId: string): Promise<string | null> {
+ let p = memo.get(videoId)
+ if (!p) {
+ p = window.stemkit.getThumb(videoId).catch(() => null)
+ memo.set(videoId, p)
+ }
+ return p
+}
+
+export function useThumb(videoId: string): string | null {
+ const [src, setSrc] = useState<string | null>(null)
+ useEffect(() => {
+ let alive = true
+ void getThumbCached(videoId).then((url) => {
+ if (alive) setSrc(url)
+ })
+ const off = window.stemkit.onSettingsChange(() => {
+ memo.clear()
+ void getThumbCached(videoId).then((url) => {
+ if (alive) setSrc(url)
+ })
+ })
+ return () => {
+ alive = false
+ off()
+ }
+ }, [videoId])
+ return src
+}
+
+export function Thumb({ videoId, className }: { videoId: string; className: string }): React.ReactElement {
+ const src = useThumb(videoId)
+ if (!src) return <span className={className} />
+ return <img src={src} alt="" className={className} draggable={false} />
+}
\ No newline at end of file
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 819d970..56ad6cd 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -20,12 +20,24 @@ export interface AppSettings {
shifts: 1 | 2
htdemucsFt: boolean
roformerVocals: boolean
+ // windows + nvidia: separate on the GPU instead of the CPU. The toggle is
+ // only rendered when an NVIDIA GPU is detected; enabling it downloads the
+ // CUDA build of torch (~2.5GB) on first use
+ gpuSplit: boolean
+ // hide the YouTube video while playing: stems are always played locally,
+ // this stops streaming the video and falls back to cached thumbnails
+ hideVideo: boolean
+ // anonymous usage analytics (GA4 Measurement Protocol); on by default
+ analytics: boolean
}
export const DEFAULT_SETTINGS: AppSettings = {
shifts: 1,
htdemucsFt: false,
- roformerVocals: false
+ roformerVocals: false,
+ gpuSplit: false,
+ hideVideo: false,
+ analytics: true
}
export interface EngineStatus {
@@ -33,6 +45,9 @@ export interface EngineStatus {
vocalsReady: boolean
ftDownloading: boolean
ftVerified: boolean
+ // cuda torch engine (windows + nvidia only)
+ gpuDownloading: boolean
+ gpuReady: boolean
}
export interface EnvStatus {
@@ -42,6 +57,8 @@ export interface EnvStatus {
bootstrapping: boolean
updating: boolean
gpu?: boolean
+ // windows only: an NVIDIA GPU was detected (gates the GPU toggle in Settings)
+ nvidiaGpu?: boolean
}
export interface EnvEvent {
@@ -105,8 +122,10 @@ export interface StemKitApi {
installUpdate(): void
getSettings(): Promise<AppSettings>
setSettings(patch: Partial<AppSettings>): Promise<AppSettings>
+ trackEvent(name: string, params?: Record<string, string | number | boolean>): void
+ getThumb(videoId: string): Promise<string | null>
enginesStatus(): Promise<EngineStatus>
- fetchEngine(which: 'vocals' | 'ft'): Promise<void>
+ fetchEngine(which: 'vocals' | 'ft' | 'gpu'): Promise<void>
onUpdateEvent(cb: (ev: UpdateEvent) => void): () => void
onJobEvent(cb: (ev: JobEvent) => void): () => void
onEnvEvent(cb: (ev: EnvEvent) => void): () => void