Skip to content

Split any YouTube song into stems

TypeScript

local files: split from disk via startLocalJob, listening-list groundwork

Daniel Ravina437ad7db161a
diff --git a/src/main/library.ts b/src/main/library.ts
index 6d53ca7..e7cfe7e 100644
--- a/src/main/library.ts
+++ b/src/main/library.ts
@@ -1,9 +1,26 @@
-import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync } from 'fs'
+import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, openSync, readSync, closeSync } from 'fs'
import { readFile } 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')
}
@@ -67,6 +84,48 @@ export function stemsPresent(videoId: string, stems: string[]): boolean {
return stems.every((name) => existsSync(join(dir, `${name}.wav`)))
}
+// duration of a PCM wav by walking its RIFF chunks — used for local files,
+// which have no yt-dlp metadata to read the length from. Returns 0 when the
+// header can't be parsed (the player recovers from the decoded buffers)
+export function wavDuration(path: string): number {
+ let fd: number | null = null
+ try {
+ fd = openSync(path, 'r')
+ const header = Buffer.alloc(4096)
+ const read = readSync(fd, header, 0, header.length, 0)
+ if (
+ read < 44 ||
+ header.toString('ascii', 0, 4) !== 'RIFF' ||
+ header.toString('ascii', 8, 12) !== 'WAVE'
+ ) {
+ return 0
+ }
+ let sampleRate = 0
+ let channels = 0
+ let bits = 0
+ let off = 12
+ while (off + 8 <= read) {
+ const id = header.toString('ascii', off, off + 4)
+ const size = header.readUInt32LE(off + 4)
+ if (id === 'fmt ' && off + 24 <= read) {
+ channels = header.readUInt16LE(off + 10)
+ sampleRate = header.readUInt32LE(off + 12)
+ bits = header.readUInt16LE(off + 22)
+ } else if (id === 'data') {
+ if (!sampleRate || !channels || !bits || size === 0) return 0
+ return Math.round(size / ((sampleRate * channels * bits) / 8))
+ }
+ if (size === 0) return 0
+ off += 8 + size + (size % 2)
+ }
+ return 0
+ } catch {
+ return 0
+ } finally {
+ if (fd !== null) closeSync(fd)
+ }
+}
+
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)
diff --git a/src/main/pipeline.ts b/src/main/pipeline.ts
index b0a089b..027bf7f 100644
--- a/src/main/pipeline.ts
+++ b/src/main/pipeline.ts
@@ -1,7 +1,7 @@
import { spawn, type ChildProcess } from 'child_process'
import { createInterface } from 'readline'
-import { readdirSync, mkdirSync, rmSync } from 'fs'
-import { join } from 'path'
+import { readdirSync, mkdirSync, rmSync, statSync } from 'fs'
+import { basename, extname, join } from 'path'
import { BrowserWindow } from 'electron'
import {
venvPython,
@@ -25,11 +25,14 @@ import {
mixWavPath,
rawDownloadPath,
upsertSong,
- loadSongs
+ 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 { cacheThumbnail } from './thumbs'
interface ActiveJob {
@@ -87,22 +90,18 @@ export function extractVideoId(url: string): string | null {
return parseVideoId(url)
}
-export async function startJob(
- rawUrl: string,
- requestedModel = MODEL_DEFAULT,
- stems?: string[]
-): Promise<void> {
- const url = rawUrl.trim()
- const videoId = parseVideoId(url)
- if (!videoId) {
- send({ kind: 'failed', data: { videoId: '', message: 'Could not parse a YouTube URL or video id out of that' } })
- return
- }
- if (jobs.has(videoId)) {
- send({ kind: 'failed', data: { videoId, message: 'This song is already being processed' } })
- return
- }
+// everything both entry points (YouTube url / local file) need to know about
+// which engines will run, shared by startJob and startLocalJob
+interface EnginePlan {
+ engine: string
+ modelTag: string
+ settings: ReturnType<typeof loadSettings>
+ useGpu: boolean
+ wantsVocals: boolean
+ deviceArg: () => string
+}
+function resolveEngine(requestedModel: string, stems?: string[]): EnginePlan {
// engine resolution from settings: roformer vocals when opted in (runs on
// CPU too — no GPU fallback by design), otherwise htdemucs / htdemucs_ft.
// The stored model tag encodes the variant so the cache below re-splits
@@ -133,7 +132,100 @@ export async function startJob(
return useGpu ? 'cuda' : 'cpu'
}
- const job: ActiveJob = { videoId, model: modelTag, cancelled: false }
+ return { engine, modelTag, settings, useGpu, wantsVocals, deviceArg }
+}
+
+// library cache check + song dir prep, shared by both entry points. Sends
+// 'done' itself when the existing split already covers the request
+function reuseOrPrepare(
+ videoId: string,
+ modelTag: string,
+ stems?: string[]
+): { covered: boolean; addedAt: number } {
+ const existing = loadSongs().find((s) => s.videoId === videoId)
+ const covered =
+ existing &&
+ existing.model === modelTag &&
+ !!existing.stems?.length &&
+ (stems?.length ? stems.every((s) => existing.stems!.includes(s)) : true)
+ if (covered && stemsPresent(videoId, stemsFor(existing))) {
+ send({ kind: 'done', data: { videoId, song: existing } })
+ return { covered: true, addedAt: existing!.addedAt }
+ }
+ if (existing && (existing.model !== modelTag || !stemsPresent(videoId, stemsFor(existing)))) {
+ rmSync(songDir(videoId), { recursive: true, force: true })
+ }
+
+ mkdirSync(songDir(videoId), { recursive: true })
+ return { covered: false, addedAt: existing?.addedAt ?? Date.now() }
+}
+
+async function convertToWav(job: ActiveJob, inputPath: string): Promise<void> {
+ const videoId = job.videoId
+ progress(job, 'convert', 0, 'Converting to WAV')
+ const ffmpeg = getStatus().ffmpeg.path
+ if (!ffmpeg) {
+ throw Object.assign(
+ new Error('Something went wrong with the built-in audio tools. Try reinstalling StemKit.'),
+ { videoId }
+ )
+ }
+ await runProcess(job, ffmpeg as string, [
+ '-y',
+ '-i',
+ inputPath,
+ '-af',
+ 'aresample=44100:resampler=soxr',
+ '-ar',
+ '44100',
+ '-ac',
+ '2',
+ '-c:a',
+ 'pcm_s16le',
+ mixWavPath(videoId)
+ ])
+ if (job.cancelled || !jobs.has(videoId)) throw new Error('cancelled')
+ progress(job, 'convert', 100)
+}
+
+function finalizeJob(
+ job: ActiveJob,
+ info: { title: string; duration: number; addedAt: number; startedAt: number; source?: 'local' },
+ producedStems: string[]
+): void {
+ progress(job, 'finalize', 100, 'Adding to library')
+ const took = Math.round((Date.now() - info.startedAt) / 1000)
+ const songs = upsertSong({
+ videoId: job.videoId,
+ title: info.title,
+ duration: info.duration,
+ addedAt: info.addedAt,
+ model: job.model,
+ stems: producedStems,
+ took,
+ source: info.source
+ })
+ send({ kind: 'done', data: { videoId: job.videoId, song: songs[0] } })
+}
+
+export async function startJob(
+ rawUrl: string,
+ requestedModel = MODEL_DEFAULT,
+ stems?: string[]
+): Promise<void> {
+ const url = rawUrl.trim()
+ const videoId = parseVideoId(url)
+ if (!videoId) {
+ send({ kind: 'failed', data: { videoId: '', message: 'Could not parse a YouTube URL or video id out of that' } })
+ return
+ }
+ if (jobs.has(videoId)) {
+ send({ kind: 'failed', data: { videoId, message: 'This song is already being processed' } })
+ return
+ }
+
+ const plan = resolveEngine(requestedModel, stems)
+ const job: ActiveJob = { videoId, model: plan.modelTag, cancelled: false }
jobs.set(videoId, job)
const startedAt = Date.now()
@@ -142,21 +234,9 @@ export async function startJob(
}
try {
- const existing = loadSongs().find((s) => s.videoId === videoId)
- const covered =
- existing &&
- existing.model === modelTag &&
- !!existing.stems?.length &&
- (stems?.length ? stems.every((s) => existing.stems!.includes(s)) : true)
- if (covered && stemsPresent(videoId, stemsFor(existing))) {
- send({ kind: 'done', data: { videoId, song: existing } })
- return
- }
- if (existing && (existing.model !== modelTag || !stemsPresent(videoId, stemsFor(existing)))) {
- rmSync(songDir(videoId), { recursive: true, force: true })
- }
+ const { covered, addedAt } = reuseOrPrepare(videoId, plan.modelTag, stems)
+ if (covered) return
- mkdirSync(songDir(videoId), { recursive: true })
progress(job, 'metadata', 0, 'Reading video info')
let raw = ''
@@ -217,203 +297,238 @@ export async function startJob(
if (!rawFile) bail('Download produced no file')
const rawPath = join(dir, rawFile as string)
- progress(job, 'convert', 0, 'Converting to WAV')
- const ffmpeg = getStatus().ffmpeg.path
- if (!ffmpeg) bail('Something went wrong with the built-in audio tools. Try reinstalling StemKit.')
- await runProcess(job, ffmpeg as string, [
- '-y',
- '-i',
- rawPath,
- '-af',
- 'aresample=44100:resampler=soxr',
- '-ar',
- '44100',
- '-ac',
- '2',
- '-c:a',
- 'pcm_s16le',
- mixWavPath(videoId)
- ])
+ await convertToWav(job, rawPath)
rmSync(rawPath, { force: true })
+
+ const producedStems = await runSeparation(job, plan, stems)
if (job.cancelled || !jobs.has(videoId)) return
- progress(job, 'convert', 100)
+ finalizeJob(job, { title: meta!.title, duration: meta!.duration, addedAt, startedAt }, producedStems)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ if (message !== 'cancelled') {
+ send({ kind: 'failed', data: { videoId, message } })
+ }
+ } finally {
+ jobs.delete(videoId)
+ }
+}
- mkdirSync(stemsDir(videoId), { recursive: true })
- progress(job, 'separate', 0, 'Waiting for a free engine slot…')
+export async function startLocalJob(
+ rawPath: string,
+ requestedModel = MODEL_DEFAULT,
+ stems?: string[]
+): Promise<void> {
+ const filePath = String(rawPath ?? '').trim()
+ const ext = extname(filePath).slice(1).toLowerCase()
+ if (!filePath || !AUDIO_EXTENSIONS.includes(ext)) {
+ send({
+ kind: 'failed',
+ data: {
+ videoId: '',
+ message: filePath
+ ? `“${ext || 'that file type'}” is not a supported audio format`
+ : 'No file was selected'
+ }
+ })
+ return
+ }
+ try {
+ if (!statSync(filePath).isFile()) throw new Error('not a file')
+ } catch {
+ send({
+ kind: 'failed',
+ data: { videoId: '', message: 'That file could not be read — it may have been moved or deleted' }
+ })
+ return
+ }
- 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}%`),
- true
- ))
- ) {
- bail('Could not prepare the GPU engine — switch back to CPU in Settings and try again')
- }
+ const videoId = localSongId(filePath)
+ if (jobs.has(videoId)) {
+ send({ kind: 'failed', data: { videoId, message: 'This song is already being processed' } })
+ return
+ }
+
+ const plan = resolveEngine(requestedModel, stems)
+ const title = basename(filePath).replace(/\.[^./\\]+$/, '') || 'Local file'
+ // title goes on the job up front so progress events name the file while
+ // there is still no library entry to read from
+ const job: ActiveJob = { videoId, title, model: plan.modelTag, cancelled: false }
+ jobs.set(videoId, job)
+ const startedAt = Date.now()
+
+ try {
+ const { covered, addedAt } = reuseOrPrepare(videoId, plan.modelTag, stems)
+ if (covered) return
+
+ // no metadata/download stages for local files: ffmpeg reads the source
+ // directly and everything downstream keys off mix.wav as usual
+ await convertToWav(job, filePath)
+ const duration = wavDuration(mixWavPath(videoId))
+
+ const producedStems = await runSeparation(job, plan, stems)
+ if (job.cancelled || !jobs.has(videoId)) return
+ finalizeJob(job, { title, duration, addedAt, startedAt, source: 'local' }, producedStems)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ if (message !== 'cancelled') {
+ send({ kind: 'failed', data: { videoId, message } })
+ }
+ } finally {
+ jobs.delete(videoId)
+ }
+}
+
+async function runSeparation(
+ job: ActiveJob,
+ plan: EnginePlan,
+ stems: string[] | undefined
+): Promise<string[]> {
+ const videoId = job.videoId
+ const { engine, settings, useGpu, wantsVocals, deviceArg } = plan
+ const bail = (message: string): never => {
+ throw Object.assign(new Error(message), { videoId })
+ }
+
+ mkdirSync(stemsDir(videoId), { recursive: true })
+ progress(job, 'separate', 0, 'Waiting for a free engine slot…')
+
+ const release = await acquireSeparation()
+ try {
+ if (job.cancelled || !jobs.has(videoId)) throw new Error('cancelled')
+ // 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}%`),
+ true
+ ))
+ ) {
+ bail('Could not prepare the GPU engine — switch back to CPU in Settings and try again')
}
- let scriptError: string | null = null
- const producedStems: string[] = []
-
- const lineParsers = (mapPct: (pct: number, msg?: string) => number) => {
- // the separate stage must never move backwards: scripts can emit
- // multiple internal sweeps, and message-only events (pct 0) update
- // the status text without touching the bar
- let lastPct = 0
- return {
- onLine: (line: string): void => {
- let parsed: Record<string, unknown>
- try {
- parsed = JSON.parse(line)
- } catch {
+ }
+ let scriptError: string | null = null
+ const producedStems: string[] = []
+
+ const lineParsers = (mapPct: (pct: number, msg?: string) => number) => {
+ // the separate stage must never move backwards: scripts can emit
+ // multiple internal sweeps, and message-only events (pct 0) update
+ // the status text without touching the bar
+ let lastPct = 0
+ return {
+ onLine: (line: string): void => {
+ let parsed: Record<string, unknown>
+ try {
+ parsed = JSON.parse(line)
+ } catch {
+ return
+ }
+ if (parsed.type === 'progress') {
+ const pct = Number(parsed.pct ?? 0)
+ const message =
+ typeof parsed.message === 'string' ? parsed.message : undefined
+ if (message && pct === 0) {
+ progress(job, 'separate', lastPct, message)
return
}
- if (parsed.type === 'progress') {
- const pct = Number(parsed.pct ?? 0)
- const message =
- typeof parsed.message === 'string' ? parsed.message : undefined
- if (message && pct === 0) {
- progress(job, 'separate', lastPct, message)
- return
- }
- const mapped = Math.max(lastPct, mapPct(pct, message))
- lastPct = mapped
- progress(job, 'separate', mapped, message)
- } else if (parsed.type === 'error') {
- scriptError = `Separation failed: ${String(parsed.message)}`
- } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {
- producedStems.push(...(parsed.stems as unknown[]).map(String))
- }
+ const mapped = Math.max(lastPct, mapPct(pct, message))
+ lastPct = mapped
+ progress(job, 'separate', mapped, message)
+ } else if (parsed.type === 'error') {
+ scriptError = `Separation failed: ${String(parsed.message)}`
+ } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {
+ producedStems.push(...(parsed.stems as unknown[]).map(String))
}
}
}
+ }
- if (engine === MODEL_EXTENDED) {
- progress(job, 'separate', 0, 'Separating stems')
+ if (engine === MODEL_EXTENDED) {
+ progress(job, 'separate', 0, 'Separating stems')
+ await runProcess(
+ job,
+ venvPython(),
+ [
+ separateScript(),
+ '--input',
+ mixWavPath(videoId),
+ '--out',
+ stemsDir(videoId),
+ '--model',
+ MODEL_EXTENDED,
+ '--device',
+ deviceArg(),
+ '--shifts',
+ String(settings.shifts),
+ ...(stems?.length ? ['--only', stems.join(',')] : [])
+ ],
+ lineParsers((pct) => pct)
+ )
+ } else if (engine === MODEL_DEFAULT) {
+ const otherStems = (
+ stems?.length ? stems : ['drums', 'bass', 'other', 'vocals']
+ ).filter((s) => s !== 'vocals')
+ // the demucs phase takes roughly twice as long as the vocals pass,
+ // so the bar reflects that split
+ const roformerSpan = otherStems.length > 0 ? 35 : 100
+ // the first slice of the vocals phase is the engine download, when
+ // one is needed; awaiting it here means roformer.py never races
+ // the background fetch on the same checkpoint file
+ const downloadSpan = Math.round(roformerSpan * 0.3)
+ if (wantsVocals) {
+ if (!(await ensureEngineDeps())) {
+ bail('Could not prepare the engine components for vocal separation')
+ }
+ await ensureVocalsEngine((pct) =>
+ progress(
+ job,
+ 'separate',
+ Math.round((pct / 100) * downloadSpan),
+ `Downloading vocals engine (913MB): ${pct}%`
+ )
+ )
+ const vocalsBase = downloadSpan
+ progress(job, 'separate', vocalsBase, 'Separating vocals')
await runProcess(
job,
venvPython(),
[
- separateScript(),
+ roformerScript(),
'--input',
mixWavPath(videoId),
'--out',
stemsDir(videoId),
- '--model',
- MODEL_EXTENDED,
+ '--ckpt-dir',
+ modelsDir(),
'--device',
- deviceArg(),
- '--shifts',
- String(settings.shifts),
- ...(stems?.length ? ['--only', stems.join(',')] : [])
+ deviceArg()
],
- lineParsers((pct) => pct)
- )
- } else if (engine === MODEL_DEFAULT) {
- const otherStems = (
- stems?.length ? stems : ['drums', 'bass', 'other', 'vocals']
- ).filter((s) => s !== 'vocals')
- // the demucs phase takes roughly twice as long as the vocals pass,
- // so the bar reflects that split
- const roformerSpan = otherStems.length > 0 ? 35 : 100
- // the first slice of the vocals phase is the engine download, when
- // one is needed; awaiting it here means roformer.py never races
- // the background fetch on the same checkpoint file
- const downloadSpan = Math.round(roformerSpan * 0.3)
- if (wantsVocals) {
- if (!(await ensureEngineDeps())) {
- bail('Could not prepare the engine components for vocal separation')
- }
- await ensureVocalsEngine((pct) =>
- progress(
- job,
- 'separate',
- Math.round((pct / 100) * downloadSpan),
- `Downloading vocals engine (913MB): ${pct}%`
- )
- )
- const vocalsBase = downloadSpan
- progress(job, 'separate', vocalsBase, 'Separating vocals')
- await runProcess(
- job,
- venvPython(),
- [
- roformerScript(),
- '--input',
- mixWavPath(videoId),
- '--out',
- stemsDir(videoId),
- '--ckpt-dir',
- modelsDir(),
- '--device',
- deviceArg()
- ],
- lineParsers((pct) =>
- vocalsBase + Math.round((pct / 100) * (roformerSpan - vocalsBase))
- )
- )
- }
- if (otherStems.length > 0) {
- if (settings.htdemucsFt) {
- if (
- !(await ensureFtWeights((pct) =>
- progress(
- job,
- 'separate',
- wantsVocals ? roformerSpan : 0,
- `Downloading fine-tuned engine (~320MB): ${pct}%`
- )
- ))
- ) {
- bail('Could not download the fine-tuned engine weights')
- }
- }
- progress(
- job,
- 'separate',
- wantsVocals ? roformerSpan : 0,
- `Separating ${otherStems.join(', ')}`
- )
- await runProcess(
- job,
- venvPython(),
- [
- separateScript(),
- '--input',
- mixWavPath(videoId),
- '--out',
- stemsDir(videoId),
- '--model',
- settings.htdemucsFt ? 'htdemucs_ft' : 'htdemucs',
- '--device',
- deviceArg(),
- '--shifts',
- String(settings.shifts),
- '--only',
- otherStems.join(',')
- ],
- lineParsers((pct, msg) =>
- wantsVocals && !msg
- ? roformerSpan + Math.round((pct / 100) * (100 - roformerSpan))
- : pct
- )
+ lineParsers((pct) =>
+ vocalsBase + Math.round((pct / 100) * (roformerSpan - vocalsBase))
)
- }
- } else {
- progress(job, 'separate', 0, 'Separating stems')
+ )
+ }
+ if (otherStems.length > 0) {
if (settings.htdemucsFt) {
if (
!(await ensureFtWeights((pct) =>
- progress(job, 'separate', 0, `Downloading fine-tuned engine (~320MB): ${pct}%`)
+ progress(
+ job,
+ 'separate',
+ wantsVocals ? roformerSpan : 0,
+ `Downloading fine-tuned engine (~320MB): ${pct}%`
+ )
))
) {
bail('Could not download the fine-tuned engine weights')
}
}
+ progress(
+ job,
+ 'separate',
+ wantsVocals ? roformerSpan : 0,
+ `Separating ${otherStems.join(', ')}`
+ )
await runProcess(
job,
venvPython(),
@@ -424,45 +539,62 @@ export async function startJob(
'--out',
stemsDir(videoId),
'--model',
- engine,
+ settings.htdemucsFt ? 'htdemucs_ft' : 'htdemucs',
'--device',
deviceArg(),
'--shifts',
String(settings.shifts),
- ...(stems?.length ? ['--only', stems.join(',')] : [])
+ '--only',
+ otherStems.join(',')
],
- lineParsers((pct) => pct)
+ lineParsers((pct, msg) =>
+ wantsVocals && !msg
+ ? roformerSpan + Math.round((pct / 100) * (100 - roformerSpan))
+ : pct
+ )
)
}
+ } else {
+ progress(job, 'separate', 0, 'Separating stems')
+ if (settings.htdemucsFt) {
+ if (
+ !(await ensureFtWeights((pct) =>
+ progress(job, 'separate', 0, `Downloading fine-tuned engine (~320MB): ${pct}%`)
+ ))
+ ) {
+ bail('Could not download the fine-tuned engine weights')
+ }
+ }
+ await runProcess(
+ job,
+ venvPython(),
+ [
+ separateScript(),
+ '--input',
+ mixWavPath(videoId),
+ '--out',
+ stemsDir(videoId),
+ '--model',
+ engine,
+ '--device',
+ deviceArg(),
+ '--shifts',
+ String(settings.shifts),
+ ...(stems?.length ? ['--only', stems.join(',')] : [])
+ ],
+ lineParsers((pct) => pct)
+ )
+ }
+
+ if (job.cancelled || !jobs.has(videoId)) throw new Error('cancelled')
+ if (scriptError) bail(scriptError)
- if (job.cancelled || !jobs.has(videoId)) return
- if (scriptError) bail(scriptError)
-
- 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,
- duration: meta!.duration,
- addedAt: existing?.addedAt ?? Date.now(),
- model: job.model,
- stems: producedStems,
- took
- })
- send({ kind: 'done', data: { videoId, song: songs[0] } })
- } finally {
+ if (!stemsPresent(videoId, producedStems)) bail('Separation finished but stem files are missing')
+
+ return producedStems
+ } finally {
release()
}
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err)
- if (message !== 'cancelled') {
- send({ kind: 'failed', data: { videoId, message } })
- }
- } finally {
- jobs.delete(videoId)
- }
}
function runProcess(
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b711641..a0902c8 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -20,6 +20,8 @@ const api: StemKitApi = {
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'),
+ 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),
getAppVersion: () => ipcRenderer.invoke('app:version'),
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 5221300..06b5335 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
import type { AppSettings, EnvStatus, JobProgress, JobStage, Song, UpdateEvent } from '../../shared/types'
import { MODEL_DEFAULT } from '../../shared/types'
import { parseVideoId } from '../../shared/url'
+import { localSongId, isLocalId } from '../../shared/local'
import { Sidebar } from './components/Sidebar'
import { Home } from './components/Home'
import { Processing } from './components/Processing'
@@ -15,6 +16,11 @@ interface EnvLog {
level: string
}
+// what the retry button re-runs: the original url or the picked local file
+type LastStart =
+ | { kind: 'url'; url: string; model: string }
+ | { kind: 'local'; filePath: string; model: string }
+
function stageLabel(stage: JobStage, pct: number): string {
switch (stage) {
case 'metadata':
@@ -41,8 +47,7 @@ export default function App(): React.ReactElement {
const [activeId, setActiveId] = useState<string | null>(null)
const [jobs, setJobs] = useState<Record<string, JobProgress>>({})
const [errors, setErrors] = useState<Record<string, string>>({})
- const [lastUrl, setLastUrl] = useState('')
- const [lastModel, setLastModel] = useState(MODEL_DEFAULT)
+ const [lastStart, setLastStart] = useState<LastStart | null>(null)
const [envLogs, setEnvLogs] = useState<EnvLog[]>([])
const [update, setUpdate] = useState<UpdateEvent | null>(null)
const [appVersion, setAppVersion] = useState<string | undefined>(undefined)
@@ -93,8 +98,7 @@ export default function App(): React.ReactElement {
const vid = parseVideoId(url)
if (!vid) return
setActiveId(vid)
- setLastUrl(url)
- setLastModel(model)
+ setLastStart({ kind: 'url', url, model })
setErrors((prev) => withoutKey(prev, vid))
setJobs((prev) =>
prev[vid]
@@ -106,6 +110,22 @@ export default function App(): React.ReactElement {
[]
)
+ const startLocal = useCallback(
+ async (filePath: string, model: string = MODEL_DEFAULT, stems?: string[]): Promise<void> => {
+ const id = localSongId(filePath)
+ setActiveId(id)
+ setLastStart({ kind: 'local', filePath, model })
+ setErrors((prev) => withoutKey(prev, id))
+ setJobs((prev) =>
+ prev[id]
+ ? prev
+ : { ...prev, [id]: { videoId: id, stage: 'convert', pct: 0, message: 'Starting…', model } }
+ )
+ await window.stemkit.startLocalJob(filePath, model, stems)
+ },
+ []
+ )
+
const cancelSelectedJob = useCallback(
(videoId: string): void => {
void window.stemkit.cancelJob(videoId)
@@ -115,13 +135,15 @@ export default function App(): React.ReactElement {
)
const retryJob = useCallback((): void => {
- if (lastUrl) void startUrl(lastUrl, lastModel)
- }, [lastUrl, lastModel, startUrl])
+ if (!lastStart) return
+ if (lastStart.kind === 'url') void startUrl(lastStart.url, lastStart.model)
+ else void startLocal(lastStart.filePath, lastStart.model)
+ }, [lastStart, startUrl, startLocal])
const updateYtDlp = useCallback(async (): Promise<void> => {
await window.stemkit.envUpdateYtDlp()
- if (lastUrl) void startUrl(lastUrl, lastModel)
- }, [lastUrl, lastModel, startUrl])
+ if (lastStart?.kind === 'url') void startUrl(lastStart.url, lastStart.model)
+ }, [lastStart, startUrl])
const deleteSong = useCallback(
async (videoId: string): Promise<void> => {
@@ -213,6 +235,7 @@ export default function App(): React.ReactElement {
<Processing
job={selectedJob}
error={selectedError}
+ isLocal={activeId ? isLocalId(activeId) : false}
botSuspected={
!!selectedError && /sign in|bot|confirm|unavailable|private/i.test(selectedError)
}
@@ -231,6 +254,7 @@ export default function App(): React.ReactElement {
pending={pendingMap}
settings={settings ?? undefined}
onStart={(u, m, s) => void startUrl(u, m, s)}
+ onStartLocal={(path, m, s) => void startLocal(path, m, s)}
onSelect={(id) => setActiveId(id)}
onOpenSettings={() => {
void window.stemkit.envStatus().then(setStatus)
diff --git a/src/renderer/src/components/Home.tsx b/src/renderer/src/components/Home.tsx
index ef22e30..de7d4cf 100644
--- a/src/renderer/src/components/Home.tsx
+++ b/src/renderer/src/components/Home.tsx
@@ -11,7 +11,7 @@ import {
import { parseVideoId } from '../../../shared/url'
import { STEM_INFO, PREFERRED_ORDER } from '../lib/stems'
import { fmtTime } from '../lib/format'
-import { GearIcon } from './Icons'
+import { GearIcon, FolderIcon } from './Icons'
interface Props {
hasSongs: boolean
@@ -19,6 +19,7 @@ interface Props {
pending?: Record<string, { label: string; error?: boolean }>
settings?: AppSettings
onStart: (url: string, model: string, stems?: string[]) => void
+ onStartLocal: (filePath: string, model: string, stems?: string[]) => void
onSelect: (videoId: string) => void
onOpenSettings: () => void
}
@@ -31,6 +32,7 @@ export function Home({
pending = {},
settings,
onStart,
+ onStartLocal,
onSelect,
onOpenSettings
}: Props): React.ReactElement {
@@ -146,14 +148,20 @@ export function Home({
startWithSelection(r.videoId)
}
+ const pickAndStart = async (): Promise<void> => {
+ if (selected.size === 0) return
+ const filePath = await window.stemkit.pickAudioFile()
+ if (filePath) onStartLocal(filePath, derivedModel, orderedSelection)
+ }
+
return (
<div className="h-full flex flex-col items-center px-8 pt-[8vh] pb-6 overflow-y-auto">
<div className="w-full max-w-2xl">
<h1 className="text-center text-[30px] font-bold tracking-tight leading-tight bg-gradient-to-r from-violet-300 via-white to-emerald-200 bg-clip-text text-transparent">
- Turn any YouTube track into stems.
+ Turn any track into stems.
</h1>
<p className="text-center text-white/45 mt-2.5 text-[14px]">
- Search YouTube or paste a link — separated locally, synced to the video.
+ Search YouTube, paste a link, or split an audio file from your computer — separated locally.
</p>
<div className="mt-6 flex gap-2">
@@ -166,6 +174,14 @@ export function Home({
spellCheck={false}
className="no-drag flex-1 glass rounded-xl px-4 py-3 text-sm outline-none placeholder:text-white/25 focus:ring-2 focus:ring-violet-400/60 transition-shadow"
/>
+ <button
+ onClick={() => void pickAndStart()}
+ disabled={selected.size === 0}
+ title="Split a local audio file (mp3, wav, flac…)"
+ className="no-drag glass rounded-xl w-[52px] flex items-center justify-center text-white/45 hover:text-white hover:bg-white/10 transition-colors disabled:opacity-40"
+ >
+ <FolderIcon className="w-[18px] h-[18px] pointer-events-none" />
+ </button>
<button
onClick={submit}
disabled={!query.trim() || selected.size === 0}
diff --git a/src/renderer/src/components/Icons.tsx b/src/renderer/src/components/Icons.tsx
index a476ab5..e104215 100644
--- a/src/renderer/src/components/Icons.tsx
+++ b/src/renderer/src/components/Icons.tsx
@@ -101,6 +101,24 @@ export function PlusIcon({ className = base }: IconProps) {
)
}
+export function FolderIcon({ className = base }: IconProps) {
+ return (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
+ <path d="M3 7a2 2 0 0 1 2-2h4l2.2 2.6H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" />
+ <path d="M12 11v5M9.5 13.5 12 11l2.5 2.5" />
+ </svg>
+ )
+}
+
+export function SpeakerIcon({ className = base }: IconProps) {
+ return (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
+ <path d="M11 5 6 9H3v6h3l5 4V5Z" />
+ <path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13" />
+ </svg>
+ )
+}
+
export function GearIcon({ className = base }: IconProps) {
return (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsx
index 7bcbee7..e97bd35 100644
--- a/src/renderer/src/components/Player.tsx
+++ b/src/renderer/src/components/Player.tsx
@@ -3,7 +3,7 @@ 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 { SongThumb } from '../lib/thumbs'
import { YouTubeHost, type YTState } from '../lib/youtube'
import { StemLane } from './StemLane'
import { Transport, type PresetId } from './Transport'
@@ -59,10 +59,13 @@ export function Player({ song, settings }: Props): React.ReactElement {
const stemMeta = useMemo(() => buildStemMeta(Object.keys(buffers) as StemId[]), [buffers])
- const youtubeUrl = `https://www.youtube.com/watch?v=${song.videoId}`
+ // local files have no video to sync: the player runs audio-only, with a
+ // placeholder panel where the YouTube iframe would be
+ const isLocal = song.source === 'local'
+ const youtubeUrl = isLocal ? null : `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 showVideo = !(settings?.hideVideo ?? false) && !isLocal
const addedLabel = new Date(song.addedAt).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
@@ -111,7 +114,7 @@ export function Player({ song, settings }: Props): React.ReactElement {
}, [song.videoId])
useEffect(() => {
- if (hideVideo) {
+ if (!showVideo) {
hostRef.current?.destroy()
hostRef.current = null
setYtReady(false)
@@ -141,7 +144,10 @@ export function Player({ song, settings }: Props): React.ReactElement {
return () => {
disposed = true
}
- }, [song.videoId, decoding, decodeError, hideVideo])
+ return () => {
+ disposed = true
+ }
+ }, [song.videoId, decoding, decodeError, showVideo])
useEffect(() => {
engine.applyMix(vols, mutes, solos, master)
@@ -209,7 +215,7 @@ export function Player({ song, settings }: Props): React.ReactElement {
hostRef.current?.play()
setPlaying(true)
}
- }, [decoding, decodeError, hideVideo])
+ }, [decoding, decodeError, showVideo])
const seekTo = useCallback(
(t: number): void => {
@@ -305,7 +311,7 @@ export function Player({ song, settings }: 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]">
- {!hideVideo && (
+ {showVideo && (
<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">
@@ -328,9 +334,10 @@ export function Player({ song, settings }: Props): React.ReactElement {
<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">
- <Thumb
+ <SongThumb
videoId={song.videoId}
className="w-32 h-[72px] rounded-lg object-cover bg-white/5 shrink-0 block"
+ iconClassName="w-7 h-7 text-white/25"
/>
<div className="min-w-0 flex-1">
<h3 className="text-xl font-semibold leading-snug truncate">{song.title}</h3>
@@ -344,7 +351,7 @@ export function Player({ song, settings }: Props): React.ReactElement {
</span>
</div>
- {hideVideo && decodeError && (
+ {!showVideo && 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>
@@ -368,12 +375,14 @@ export function Player({ song, settings }: Props): React.ReactElement {
<DownloadIcon className="w-4 h-4" />
Export everything
</button>
- <button
- onClick={() => window.stemkit.openExternal(youtubeUrl)}
- className="no-drag glass rounded-xl px-5 py-3 text-[13px] font-medium text-white/70 hover:text-white hover:bg-white/10 transition-colors"
- >
- Open on YouTube
- </button>
+ {youtubeUrl && (
+ <button
+ onClick={() => window.stemkit.openExternal(youtubeUrl)}
+ className="no-drag glass rounded-xl px-5 py-3 text-[13px] font-medium text-white/70 hover:text-white hover:bg-white/10 transition-colors"
+ >
+ Open on YouTube
+ </button>
+ )}
</div>
</aside>
</div>
@@ -388,7 +397,7 @@ export function Player({ song, settings }: Props): React.ReactElement {
onPreset={applyPreset}
master={master}
onMaster={setMaster}
- youtubeUrl={youtubeUrl}
+ youtubeUrl={youtubeUrl ?? undefined}
/>
<div className="mt-4 space-y-2">
diff --git a/src/renderer/src/components/Processing.tsx b/src/renderer/src/components/Processing.tsx
index 1fcc15b..dae1afe 100644
--- a/src/renderer/src/components/Processing.tsx
+++ b/src/renderer/src/components/Processing.tsx
@@ -1,7 +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 { SongThumb } from '../lib/thumbs'
import { XIcon } from './Icons'
const STAGES: { id: JobProgress['stage']; label: string }[] = [
@@ -18,6 +18,8 @@ const stageOrder = (stage: JobProgress['stage'] | undefined): number =>
interface Props {
job: JobProgress | null
error: string | null
+ // local-file jobs have no metadata/download stages and no yt-dlp to update
+ isLocal?: boolean
botSuspected: boolean
onCancel: () => void
onRetry: () => void
@@ -27,12 +29,14 @@ interface Props {
export function Processing({
job,
error,
+ isLocal = false,
botSuspected,
onCancel,
onRetry,
onUpdateYtDlp
}: Props): React.ReactElement {
- const stageIndex = job ? STAGES.findIndex((s) => s.id === job.stage) : -1
+ const stages = isLocal ? STAGES.filter((s) => s.id !== 'metadata' && s.id !== 'download') : STAGES
+ const stageIndex = job ? stages.findIndex((s) => s.id === job.stage) : -1
const [timing, setTiming] = useState<{ elapsed: number; left: number | null } | null>(null)
const jobRef = useRef(job)
@@ -79,9 +83,10 @@ 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 ? (
- <Thumb
+ <SongThumb
videoId={job.videoId}
className="w-16 h-9 rounded-lg object-cover bg-white/5 block"
+ iconClassName="w-4 h-4 text-white/25"
/>
) : (
<span className="w-10 h-10 rounded-full border-2 border-white/20 border-t-violet-300 animate-spin" />
@@ -95,7 +100,7 @@ export function Processing({
</div>
<div className="mt-6 space-y-3.5">
- {STAGES.map((stage, i) => {
+ {stages.map((stage, i) => {
const done = !error && i < stageIndex
const active = !error && i === stageIndex
const pct = active && job ? job.pct : done ? 100 : 0
@@ -141,7 +146,7 @@ export function Processing({
{error}
</div>
<div className="mt-4 flex gap-2 justify-end">
- {botSuspected && (
+ {botSuspected && !isLocal && (
<button
onClick={onUpdateYtDlp}
className="px-4 py-2 rounded-lg glass text-[13px] hover:bg-white/10 transition-colors"
diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsx
index 9db1996..d7acc65 100644
--- a/src/renderer/src/components/Sidebar.tsx
+++ b/src/renderer/src/components/Sidebar.tsx
@@ -1,6 +1,6 @@
import type { Song } from '../../../shared/types'
import { fmtTime } from '../lib/format'
-import { Thumb } from '../lib/thumbs'
+import { SongThumb } from '../lib/thumbs'
import { LogoMark, TrashIcon, PlusIcon, GearIcon } from './Icons'
interface Props {
@@ -77,9 +77,10 @@ export function Sidebar({
}`}
>
<span className="relative shrink-0">
- <Thumb
+ <SongThumb
videoId={song.videoId}
className={`w-12 h-[27px] rounded-md object-cover bg-white/5 block ${working ? 'opacity-70' : ''}`}
+ iconClassName="w-3.5 h-3.5 text-white/25"
/>
{working && (
<span className="absolute inset-0 flex items-center justify-center">
diff --git a/src/renderer/src/components/Transport.tsx b/src/renderer/src/components/Transport.tsx
index 5f09333..220f15a 100644
--- a/src/renderer/src/components/Transport.tsx
+++ b/src/renderer/src/components/Transport.tsx
@@ -21,7 +21,8 @@ interface Props {
onPreset: (p: PresetId) => void
master: number
onMaster: (v: number) => void
- youtubeUrl: string
+ // local-file songs have no video to link out to
+ youtubeUrl?: string
}
function SeekBar({
@@ -156,13 +157,15 @@ export function Transport({
/>
</div>
- <button
- onClick={() => window.stemkit.openExternal(youtubeUrl)}
- title="Open on YouTube"
- className="no-drag text-white/40 hover:text-white transition-colors"
- >
- <ExternalIcon />
- </button>
+ {youtubeUrl && (
+ <button
+ onClick={() => window.stemkit.openExternal(youtubeUrl)}
+ title="Open on YouTube"
+ className="no-drag text-white/40 hover:text-white transition-colors"
+ >
+ <ExternalIcon />
+ </button>
+ )}
</div>
</div>
)
diff --git a/src/renderer/src/lib/thumbs.tsx b/src/renderer/src/lib/thumbs.tsx
index 161b326..105eb2c 100644
--- a/src/renderer/src/lib/thumbs.tsx
+++ b/src/renderer/src/lib/thumbs.tsx
@@ -1,4 +1,6 @@
import { useEffect, useState } from 'react'
+import { isLocalId } from '../../../shared/local'
+import { SpeakerIcon } from '../components/Icons'
// library thumbnails resolve through the local cache in the main process
// (userData/thumbs). Setting changes re-resolve: hideVideo on/off changes
@@ -66,3 +68,24 @@ export function Thumb({ videoId, className }: { videoId: string; className: stri
if (!src) return <span className={className} />
return <img src={src} alt="" className={className} draggable={false} />
}
+
+// song artwork slot: YouTube ids resolve through the thumbnail cache, local
+// files get a speaker badge (there is nothing to fetch for them)
+export function SongThumb({
+ videoId,
+ className,
+ iconClassName = 'w-1/2 h-1/2 text-white/25'
+}: {
+ videoId: string
+ className: string
+ iconClassName?: string
+}): React.ReactElement {
+ if (isLocalId(videoId)) {
+ return (
+ <span className={`${className} flex items-center justify-center`}>
+ <SpeakerIcon className={iconClassName} />
+ </span>
+ )
+ }
+ return <Thumb videoId={videoId} className={className} />
+}
diff --git a/src/shared/local.ts b/src/shared/local.ts
new file mode 100644
index 0000000..d025858
--- /dev/null
+++ b/src/shared/local.ts
@@ -0,0 +1,21 @@
+// 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-splitting
+// the same path reuses the cached split, and the renderer and main process
+// always hash the exact same string that came out of the file dialog
+export function localSongId(filePath: string): string {
+ // FNV-1a 32-bit
+ let hash = 0x811c9dc5
+ for (let i = 0; i < filePath.length; i++) {
+ hash ^= filePath.charCodeAt(i)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return `local-${(hash >>> 0).toString(16).padStart(8, '0')}`
+}
+
+// true for synthetic ids minted by localSongId. In-progress jobs only carry
+// the id (no Song record yet), so callers that need "is this local?" during
+// a split must check this instead of Song.source
+export function isLocalId(id: string): boolean {
+ return id.startsWith('local-')
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index bf24faa..fda4534 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -14,6 +14,8 @@ export interface Song {
model?: string
stems?: string[]
took?: number
+ // local audio files carry their own mix; absent means a YouTube source
+ source?: 'local'
}
export interface AppSettings {
@@ -113,6 +115,8 @@ export interface StemKitApi {
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>
+ startLocalJob(filePath: string, model?: string, stems?: string[]): Promise<{ started: boolean }>
cancelJob(videoId?: string): Promise<void>
openExternal(url: string): Promise<void>
getAppVersion(): Promise<string>