Skip to content

Split any YouTube song into stems

TypeScript

feat: hybrid separation pipeline with GPU fallback and shift averaging

Daniel Ravinaf7953329a322
diff --git a/src/main/env.ts b/src/main/env.ts
index e45a1bb..5963570 100644
--- a/src/main/env.ts
+++ b/src/main/env.ts
@@ -95,6 +95,79 @@ export function separateScript(): string {
return join(app.getAppPath(), 'python', 'separate.py')
}
+export function roformerScript(): string {
+ if (app.isPackaged) {
+ return join(process.resourcesPath, 'python', 'roformer.py')
+ }
+ return join(app.getAppPath(), 'python', 'roformer.py')
+}
+
+export function modelsDir(): string {
+ return join(userDataDir(), 'models')
+}
+
+const ENGINE_DEPS = ['beartype', 'rotary_embedding_torch', 'einops']
+let engineDepsReady = false
+
+let gpuProbe: Promise<boolean> | null = null
+
+/* true when the venv's torch can run the roformer engine on a GPU
+ (MPS on Apple Silicon, CUDA on NVIDIA). CPU-only machines stay on
+ the demucs engine, which is much faster without GPU acceleration */
+export function hasGpuAcceleration(): Promise<boolean> {
+ if (!gpuProbe) {
+ gpuProbe = runCapture(
+ venvPython(),
+ [
+ '-c',
+ 'import torch;print(1 if (torch.cuda.is_available() or torch.backends.mps.is_available()) else 0)'
+ ],
+ 30000
+ )
+ .then((out) => out.trim().endsWith('1'))
+ .catch(() => false)
+ }
+ return gpuProbe
+}
+
+/* venvs created before the roformer engine lack a few small packages;
+ verify and install them once per session */
+export async function ensureEngineDeps(): Promise<boolean> {
+ if (engineDepsReady) return true
+ try {
+ await runCapture(
+ venvPython(),
+ ['-c', `import ${ENGINE_DEPS.join(', ')}`],
+ 20000
+ )
+ engineDepsReady = true
+ return true
+ } catch {}
+ sendEnvEvent('Preparing engine components…')
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(
+ venvPython(),
+ ['-m', 'pip', 'install', '-q', 'beartype', 'rotary-embedding-torch', 'einops'],
+ { env: { ...process.env } }
+ )
+ child.on('close', (code) =>
+ code === 0 ? resolve() : reject(new Error(`pip install failed (${code})`))
+ )
+ child.on('error', reject)
+ })
+ engineDepsReady = true
+ sendEnvEvent('Engine components ready', 'success')
+ return true
+ } catch (err) {
+ sendEnvEvent(
+ `Engine components failed: ${err instanceof Error ? err.message : String(err)}`,
+ 'error'
+ )
+ return false
+ }
+}
+
function cleanVersion(version: string): string {
return String(version).replace(/^v/, '')
}
@@ -433,6 +506,9 @@ export async function bootstrap(): Promise<boolean> {
'torch==2.5.1',
'torchaudio==2.5.1',
'numpy<2',
+ 'beartype',
+ 'rotary-embedding-torch',
+ 'einops',
'yt-dlp'
])
let buffer = ''
diff --git a/src/main/pipeline.ts b/src/main/pipeline.ts
index 3b02ee6..bd99191 100644
--- a/src/main/pipeline.ts
+++ b/src/main/pipeline.ts
@@ -7,6 +7,10 @@ import {
venvPython,
venvYtDlp,
separateScript,
+ roformerScript,
+ modelsDir,
+ ensureEngineDeps,
+ hasGpuAcceleration,
getStatus,
ytDlpRuntimeArgs
} from './env'
@@ -21,7 +25,7 @@ import {
loadSongs
} from './library'
import type { JobEvent, JobStage } from '../shared/types'
-import { MODEL_FINE, MODEL_EXTENDED } from '../shared/types'
+import { MODEL_DEFAULT, MODEL_EXTENDED } from '../shared/types'
import { parseVideoId } from '../shared/url'
interface ActiveJob {
@@ -81,14 +85,9 @@ export function extractVideoId(url: string): string | null {
export async function startJob(
rawUrl: string,
- requestedModel = 'htdemucs',
+ requestedModel = MODEL_DEFAULT,
stems?: string[]
): Promise<void> {
- // the fine-tuned model has no piano/guitar sources, fall back to the 6s engine
- const model =
- requestedModel === MODEL_FINE && stems?.some((s) => s === 'guitar' || s === 'piano')
- ? MODEL_EXTENDED
- : requestedModel
const url = rawUrl.trim()
const videoId = parseVideoId(url)
if (!videoId) {
@@ -100,6 +99,14 @@ export async function startJob(
return
}
+ // the roformer engine needs GPU acceleration to be practical; without it
+ // the job quietly stays on the demucs engine
+ const wantsVocals = !stems?.length || stems.includes('vocals')
+ let model = requestedModel
+ if (requestedModel === MODEL_DEFAULT && wantsVocals && !(await hasGpuAcceleration())) {
+ model = 'htdemucs'
+ }
+
const job: ActiveJob = { videoId, model, cancelled: false }
jobs.set(videoId, job)
@@ -153,7 +160,7 @@ export async function startJob(
[
...ytDlpRuntimeArgs(),
'-f',
- 'bestaudio[ext=m4a]/bestaudio/best',
+ 'bestaudio/best',
'--no-playlist',
'-o',
rawDownloadPath(videoId),
@@ -188,6 +195,8 @@ export async function startJob(
'-y',
'-i',
rawPath,
+ '-af',
+ 'aresample=44100:resampler=soxr',
'-ar',
'44100',
'-ac',
@@ -201,64 +210,135 @@ export async function startJob(
progress(job, 'convert', 100)
mkdirSync(stemsDir(videoId), { recursive: true })
- progress(
- job,
- 'separate',
- 0,
- job.model === 'htdemucs_6s'
- ? 'Waiting for a free engine slot…'
- : 'Waiting for a free engine slot… (first runs also download models)'
- )
+ progress(job, 'separate', 0, 'Waiting for a free engine slot…')
const release = await acquireSeparation()
try {
if (job.cancelled || !jobs.has(videoId)) return
- progress(job, 'separate', 0, 'Separating stems')
let scriptError: string | null = null
- let producedStems: string[] | null = null
- await runProcess(
- job,
- venvPython(),
- [
- separateScript(),
- '--input',
- mixWavPath(videoId),
- '--out',
- stemsDir(videoId),
- '--model',
- job.model,
- '--device',
- 'auto',
- ...(stems?.length ? ['--only', stems.join(',')] : [])
- ],
- {
- onLine: (line) => {
- let parsed: Record<string, unknown>
- try {
- parsed = JSON.parse(line)
- } catch {
- return
- }
- if (parsed.type === 'progress') {
- progress(
- job,
- 'separate',
- Number(parsed.pct ?? 0),
- typeof parsed.message === 'string' ? parsed.message : undefined
- )
- } else if (parsed.type === 'error') {
- scriptError = `Separation failed: ${String(parsed.message)}`
- } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {
- producedStems = (parsed.stems as unknown[]).map(String)
- }
+ const producedStems: string[] = []
+
+ const lineParsers = (mapPct: (pct: number, msg?: string) => number) => ({
+ 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
+ progress(job, 'separate', mapPct(pct, message), 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 (model === MODEL_EXTENDED) {
+ progress(job, 'separate', 0, 'Separating stems')
+ await runProcess(
+ job,
+ venvPython(),
+ [
+ separateScript(),
+ '--input',
+ mixWavPath(videoId),
+ '--out',
+ stemsDir(videoId),
+ '--model',
+ MODEL_EXTENDED,
+ '--device',
+ 'auto',
+ ...(stems?.length ? ['--only', stems.join(',')] : [])
+ ],
+ lineParsers((pct) => pct)
+ )
+ } else if (model === MODEL_DEFAULT) {
+ const otherStems = (
+ stems?.length ? stems : ['drums', 'bass', 'other', 'vocals']
+ ).filter((s) => s !== 'vocals')
+ if (wantsVocals) {
+ if (!(await ensureEngineDeps())) {
+ bail('Could not prepare the engine components for vocal separation')
+ }
+ progress(job, 'separate', 0, 'Separating vocals (first run downloads a 913MB engine)')
+ await runProcess(
+ job,
+ venvPython(),
+ [
+ roformerScript(),
+ '--input',
+ mixWavPath(videoId),
+ '--out',
+ stemsDir(videoId),
+ '--ckpt-dir',
+ modelsDir(),
+ '--device',
+ 'auto'
+ ],
+ lineParsers((pct, msg) => (msg ? pct : Math.round(pct * 0.65)))
+ )
+ }
+ if (otherStems.length > 0) {
+ progress(
+ job,
+ 'separate',
+ wantsVocals ? 65 : 0,
+ `Separating ${otherStems.join(', ')}`
+ )
+ await runProcess(
+ job,
+ venvPython(),
+ [
+ separateScript(),
+ '--input',
+ mixWavPath(videoId),
+ '--out',
+ stemsDir(videoId),
+ '--model',
+ 'htdemucs',
+ '--device',
+ 'auto',
+ '--shifts',
+ '2',
+ '--only',
+ otherStems.join(',')
+ ],
+ lineParsers((pct, msg) =>
+ wantsVocals && !msg ? 65 + Math.round(pct * 0.35) : pct
+ )
+ )
+ }
+ } else {
+ progress(job, 'separate', 0, 'Separating stems')
+ await runProcess(
+ job,
+ venvPython(),
+ [
+ separateScript(),
+ '--input',
+ mixWavPath(videoId),
+ '--out',
+ stemsDir(videoId),
+ '--model',
+ model,
+ '--device',
+ 'auto',
+ ...(stems?.length ? ['--only', stems.join(',')] : [])
+ ],
+ lineParsers((pct) => pct)
+ )
+ }
+
if (job.cancelled || !jobs.has(videoId)) return
if (scriptError) bail(scriptError)
- const finalStems = producedStems ?? []
- if (!stemsPresent(videoId, finalStems)) bail('Separation finished but stem files are missing')
+ if (!stemsPresent(videoId, producedStems)) bail('Separation finished but stem files are missing')
progress(job, 'finalize', 100, 'Adding to library')
const songs = upsertSong({
@@ -267,7 +347,7 @@ export async function startJob(
duration: meta!.duration,
addedAt: existing?.addedAt ?? Date.now(),
model: job.model,
- stems: finalStems
+ stems: producedStems
})
send({ kind: 'done', data: { videoId, song: songs[0] } })
} finally {
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index f49cd77..94d0a9e 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { EnvStatus, JobProgress, JobStage, Song, UpdateEvent } from '../../shared/types'
+import { MODEL_DEFAULT } from '../../shared/types'
import { parseVideoId } from '../../shared/url'
import { Sidebar } from './components/Sidebar'
import { Home } from './components/Home'
@@ -40,7 +41,7 @@ export default function App(): React.ReactElement {
const [jobs, setJobs] = useState<Record<string, JobProgress>>({})
const [errors, setErrors] = useState<Record<string, string>>({})
const [lastUrl, setLastUrl] = useState('')
- const [lastModel, setLastModel] = useState('htdemucs')
+ const [lastModel, setLastModel] = useState(MODEL_DEFAULT)
const [envLogs, setEnvLogs] = useState<EnvLog[]>([])
const [update, setUpdate] = useState<UpdateEvent | null>(null)
const [appVersion, setAppVersion] = useState<string | undefined>(undefined)
@@ -82,7 +83,7 @@ export default function App(): React.ReactElement {
}, [status?.ready])
const startUrl = useCallback(
- async (url: string, model = 'htdemucs', stems?: string[]): Promise<void> => {
+ async (url: string, model: string = MODEL_DEFAULT, stems?: string[]): Promise<void> => {
const vid = parseVideoId(url)
if (!vid) return
setActiveId(vid)
diff --git a/src/renderer/src/components/Home.tsx b/src/renderer/src/components/Home.tsx
index c6e1e20..383ac2d 100644
--- a/src/renderer/src/components/Home.tsx
+++ b/src/renderer/src/components/Home.tsx
@@ -1,7 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import {
- MODEL_STANDARD,
- MODEL_FINE,
+ MODEL_DEFAULT,
MODEL_EXTENDED,
DEFAULT_STEMS,
type SearchResult,
@@ -25,7 +24,6 @@ const ALL_STEMS = PREFERRED_ORDER
export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props): React.ReactElement {
const [query, setQuery] = useState('')
const [selected, setSelected] = useState<Set<StemId>>(new Set<StemId>(DEFAULT_STEMS as StemId[]))
- const [hq, setHq] = useState(false)
const [results, setResults] = useState<SearchResult[]>([])
const [searching, setSearching] = useState(false)
const [searchError, setSearchError] = useState<string | null>(null)
@@ -34,8 +32,7 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const usesExtended = [...selected].some((id) => id === 'guitar' || id === 'piano')
- const effectiveHq = hq && !usesExtended
- const derivedModel = usesExtended ? MODEL_EXTENDED : effectiveHq ? MODEL_FINE : MODEL_STANDARD
+ const derivedModel = usesExtended ? MODEL_EXTENDED : MODEL_DEFAULT
const orderedSelection = ALL_STEMS.filter((id) => selected.has(id))
const toggleStem = (id: StemId): void => {
@@ -150,9 +147,7 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props
? 'select at least one'
: usesExtended
? `6-source engine · ${selected.size} stems`
- : effectiveHq
- ? `high-quality engine · ${selected.size} stems`
- : `4-source engine · ${selected.size} stems`}
+ : `roformer engine · ${selected.size} stems`}
</span>
</div>
<div className="flex items-center gap-1.5 flex-wrap">
@@ -187,46 +182,6 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props
)
})}
</div>
-
- <div className="mt-3 pt-3 border-t border-white/[0.06] flex items-center justify-between">
- <span className="text-[11px] font-semibold uppercase tracking-widest text-white/30">
- Quality
- </span>
- <div className="flex items-center gap-2">
- {effectiveHq && (
- <span className="text-[11px] text-white/30 font-medium">
- ~4× slower, cleaner stems
- </span>
- )}
- <button
- onClick={() => setHq(false)}
- className={`no-drag rounded-full px-3 py-1 text-[11px] font-medium border transition-all ${
- !effectiveHq
- ? 'bg-white/10 text-white/85 border-white/20'
- : 'border-white/[0.08] bg-white/[0.03] text-white/35 hover:text-white/60 hover:border-white/20'
- }`}
- >
- Standard
- </button>
- <button
- onClick={() => !usesExtended && setHq(true)}
- title={
- usesExtended
- ? 'High quality covers the four main stems — deselect guitar/piano to enable'
- : 'Cleaner separation, roughly 4× the processing time'
- }
- className={`no-drag rounded-full px-3 py-1 text-[11px] font-medium border transition-all ${
- effectiveHq
- ? 'bg-violet-400/15 text-violet-200 border-violet-300/30'
- : usesExtended
- ? 'border-white/[0.06] bg-white/[0.02] text-white/25 cursor-not-allowed'
- : 'border-white/[0.08] bg-white/[0.03] text-white/35 hover:text-white/60 hover:border-white/20'
- }`}
- >
- High
- </button>
- </div>
- </div>
</div>
{(searching || searchError || results.length > 0) && (
@@ -313,7 +268,7 @@ export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props
{!hasSongs && results.length === 0 && !searching && (
<p className="mt-8 text-center text-xs text-white/25 leading-relaxed">
- A 4-minute song takes about {effectiveHq ? 'four minutes' : 'a minute'} to split.
+ A 4-minute song takes about three minutes to split.
</p>
)}
</div>
diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsx
index 6f9beb8..dff7833 100644
--- a/src/renderer/src/components/Player.tsx
+++ b/src/renderer/src/components/Player.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { Song, StemId } from '../../../shared/types'
-import { MODEL_FINE, MODEL_EXTENDED } from '../../../shared/types'
+import { MODEL_DEFAULT, MODEL_EXTENDED } from '../../../shared/types'
import { engine, decodePayload, type BufferMap } from '../lib/engine'
import { buildStemMeta } from '../lib/stems'
import { fmtTime } from '../lib/format'
@@ -328,8 +328,8 @@ export function Player({ song }: Props): React.ReactElement {
{fmtTime(song.duration)} · added {addedLabel} ·{' '}
{song.model === MODEL_EXTENDED
? '6-source engine'
- : song.model === MODEL_FINE
- ? 'high-quality engine'
+ : song.model === MODEL_DEFAULT
+ ? 'roformer engine'
: '4-source engine'}
</p>
</div>
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 2d1fb6e..f79d425 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2,8 +2,8 @@ export type StemId = 'vocals' | 'drums' | 'bass' | 'other' | 'piano' | 'guitar'
export const DEFAULT_STEMS: string[] = ['vocals', 'drums', 'bass', 'other']
-export const MODEL_STANDARD = 'htdemucs'
-export const MODEL_FINE = 'htdemucs_ft'
+// roformer_hybrid = mel-band roformer vocals + htdemucs drums/bass/other
+export const MODEL_DEFAULT = 'roformer_hybrid'
export const MODEL_EXTENDED = 'htdemucs_6s'
export interface Song {