Split any YouTube song into stems
TypeScript
feat: processing timer, split duration on songs, review fixes
Daniel Ravinaf466011af48e
diff --git a/README.md b/README.mdindex 5492670..120baa4 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@ Everything runs locally — no accounts, no cloud, no API keys.- Per-stem mute/solo/volume, waveforms with click-to-seek- Parallel background splitting with live progress- Export any stem (or all) as WAV-- Fully offline after setup — separation runs on Apple MPS / CPU, ffmpeg included+- Fully offline after setup — separation runs on Apple Silicon (MPS), NVIDIA GPUs (CUDA) or CPU; ffmpeg included## Download@@ -29,7 +29,7 @@ Grab installers from [Releases](https://github.com/danielravina/stemkit/releases- **macOS** (Apple Silicon): `StemKit-x.y.z-mac-arm64.dmg`- **Windows**: `StemKit-Setup-x.y.z.exe` (installer) or portable `.zip`-First launch creates a private Python environment and downloads the separation engine (~2 GB, one time) plus model weights (~80 MB). ffmpeg is bundled — nothing else to install.+First launch creates a private Python environment and downloads the separation engine (~2 GB, one time) plus model weights (~80 MB). The first split also downloads the neural vocals engine (~913 MB, one time). ffmpeg is bundled — nothing else to install.> **macOS first launch**: builds are signed with a Developer ID but not notarized, so macOS may say it "cannot verify the developer". One-time fix: **System Settings → Privacy & Security → Open Anyway** (or `xattr -cr /Applications/StemKit.app`).>@@ -82,8 +82,11 @@ Without these secrets CI falls back to ad-hoc signing (app runs, but Gatekeeper## How it works```-YouTube URL ──► yt-dlp (+JS runtime) ──► bundled ffmpeg ──► demucs htdemucs ──► stems/*.wav- │+YouTube URL ──► yt-dlp (+JS runtime) ──► bundled ffmpeg ──► mel-band roformer (vocals) ─┐+ │ ├─► stems/*.wav+ └─────────────► demucs htdemucs ────────────────┘+ (drums/bass/other, shift-averaged)+Electron renderer ◄──── IPC events ─────┘video iframe (muted) + Web Audio stem playback · master clock = the audio itself```@@ -99,7 +102,8 @@ video iframe (muted) + Web Audio stem playback · master clock = the audio itselsrc/main Electron main process (pipeline, env bootstrap, library)src/preload IPC bridgesrc/renderer React UI (player, sync engine, waveforms)-python/ separate.py — demucs wrapper with JSON progress output+python/ separate.py (demucs) and roformer.py (neural vocals) with JSON progress output+python/vendor/ patched model code — see python/vendor/README.mdscripts/ node runner, ffmpeg fetchersbuild/ icon sources```diff --git a/python/vendor/README.md b/python/vendor/README.mdnew file mode 100644index 0000000..b9af97f--- /dev/null+++ b/python/vendor/README.md@@ -0,0 +1,16 @@+# Vendored model code++Patched copies of the model definitions from+[Music-Source-Separation-Training](https://github.com/ZFTurbo/Music-Source-Separation-Training)+(MIT), which builds on lucidrains' BS-RoFormer implementation (MIT).++Patches applied for Apple Silicon (MPS) inference:++- complex mask math is done in real/imag components — MPS does not support+ complex `scatter_add_` (mel-band variant) or reliable complex multiply+- `torch.istft` is replaced with a manual overlap-add (it depends on+ `aten::unfold_backward`, which is not implemented on MPS)+- the STFT and band-split run in fp32 (fp16 accumulation overflows on loud+ material); the attention stack runs in fp16 for speed+- the mel filter bank is precomputed (`mel_bank_44100_2048_60.npy`) so librosa+ is not a runtime dependencydiff --git a/src/main/pipeline.ts b/src/main/pipeline.tsindex bd99191..b1df535 100644--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@ -109,6 +109,7 @@ export async function startJob(const job: ActiveJob = { videoId, model, cancelled: false }jobs.set(videoId, job)+ const startedAt = Date.now()const bail = (message: string): never => {throw Object.assign(new Error(message), { videoId })@@ -262,6 +263,9 @@ export async function startJob(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 : 100if (wantsVocals) {if (!(await ensureEngineDeps())) {bail('Could not prepare the engine components for vocal separation')@@ -281,14 +285,16 @@ export async function startJob('--device','auto'],- lineParsers((pct, msg) => (msg ? pct : Math.round(pct * 0.65)))+ lineParsers((pct, msg) =>+ msg ? pct : Math.round((pct / 100) * roformerSpan)+ ))}if (otherStems.length > 0) {progress(job,'separate',- wantsVocals ? 65 : 0,+ wantsVocals ? roformerSpan : 0,`Separating ${otherStems.join(', ')}`)await runProcess(@@ -304,13 +310,13 @@ export async function startJob('htdemucs','--device','auto',- '--shifts',- '2','--only',otherStems.join(',')],lineParsers((pct, msg) =>- wantsVocals && !msg ? 65 + Math.round(pct * 0.35) : pct+ wantsVocals && !msg+ ? roformerSpan + Math.round((pct / 100) * (100 - roformerSpan))+ : pct))}@@ -347,7 +353,8 @@ export async function startJob(duration: meta!.duration,addedAt: existing?.addedAt ?? Date.now(),model: job.model,- stems: producedStems+ stems: producedStems,+ took: Math.round((Date.now() - startedAt) / 1000)})send({ kind: 'done', data: { videoId, song: songs[0] } })} finally {diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 94d0a9e..1048c15 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -84,10 +84,10 @@ export default function App(): React.ReactElement {const startUrl = useCallback(async (url: string, model: string = MODEL_DEFAULT, stems?: string[]): Promise<void> => {- const vid = parseVideoId(url)- if (!vid) return- setActiveId(vid)- setLastUrl(url)+ const vid = parseVideoId(url)+ if (!vid) return+ setActiveId(vid)+ setLastUrl(url)setLastModel(model)setErrors((prev) => withoutKey(prev, vid))setJobs((prev) =>diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsxindex dff7833..6a36e74 100644--- a/src/renderer/src/components/Player.tsx+++ b/src/renderer/src/components/Player.tsx@@ -1,6 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import type { Song, StemId } 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'@@ -325,12 +324,8 @@ export function Player({ song }: Props): React.ReactElement {<div className="min-w-0 flex-1"><h3 className="text-xl font-semibold leading-snug truncate">{song.title}</h3><p className="text-xs text-white/45 mt-1.5 font-mono truncate">- {fmtTime(song.duration)} · added {addedLabel} ·{' '}- {song.model === MODEL_EXTENDED- ? '6-source engine'- : song.model === MODEL_DEFAULT- ? 'roformer engine'- : '4-source engine'}+ {fmtTime(song.duration)} · added {addedLabel}+ {song.took ? ` · split in ${fmtTime(song.took)}` : ''}</p></div><span className="shrink-0 text-xs px-3 py-1.5 rounded-full bg-white/5 text-white/50 font-medium">diff --git a/src/renderer/src/components/Processing.tsx b/src/renderer/src/components/Processing.tsxindex 7b5eebd..bbc2823 100644--- a/src/renderer/src/components/Processing.tsx+++ b/src/renderer/src/components/Processing.tsx@@ -1,4 +1,6 @@+import { useEffect, useRef, useState } from 'react'import type { JobProgress } from '../../../shared/types'+import { fmtTime } from '../lib/format'import { XIcon } from './Icons'const STAGES: { id: JobProgress['stage']; label: string }[] = [@@ -9,6 +11,9 @@ const STAGES: { id: JobProgress['stage']; label: string }[] = [{ id: 'finalize', label: 'Finishing up' }]+const stageOrder = (stage: JobProgress['stage'] | undefined): number =>+ stage ? STAGES.findIndex((s) => s.id === stage) : -1+interface Props {job: JobProgress | nullerror: string | null@@ -28,6 +33,46 @@ export function Processing({}: Props): React.ReactElement {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)+ jobRef.current = job+ const tracker = useRef<{ videoId: string | null; start: number | null; ema: number | null }>({+ videoId: null,+ start: null,+ ema: null+ })++ useEffect(() => {+ const id = window.setInterval(() => {+ const j = jobRef.current+ const t = tracker.current+ // reset on a different job, on a retry (stage regressed), or on error+ if (!j || j.videoId !== t.videoId || stageOrder(j.stage) < stageOrder('separate')) {+ t.videoId = j?.videoId ?? null+ t.start = null+ t.ema = null+ setTiming(null)+ return+ }+ if (j.stage !== 'separate') {+ // finalize and beyond are instant; keep the last reading frozen+ return+ }+ if (t.start === null) t.start = Date.now()+ const elapsed = Math.round((Date.now() - t.start) / 1000)+ let left: number | null = null+ if (j.pct >= 3) {+ // self-calibrating estimate: elapsed over completed fraction,+ // smoothed so phase transitions and chunky updates don't wobble+ const projected = elapsed / (Math.min(j.pct, 99) / 100)+ t.ema = t.ema === null ? projected : t.ema * 0.9 + projected * 0.1+ left = Math.max(0, Math.round(t.ema - elapsed))+ }+ setTiming({ elapsed, left })+ }, 1000)+ return () => window.clearInterval(id)+ }, [])+return (<div className="h-full flex items-center justify-center px-8"><div className="w-full max-w-md glass rounded-2xl p-7 rise-in">@@ -83,6 +128,13 @@ export function Processing({})}</div>+ {timing && !error && (+ <p className="mt-4 text-center text-[11px] font-mono text-white/35">+ elapsed {fmtTime(timing.elapsed)}+ {timing.left !== null ? ` · ~${fmtTime(timing.left)} left` : ' · estimating…'}+ </p>+ )}+{error && (<div className="mt-6 rise-in"><div className="rounded-xl bg-rose-500/10 border border-rose-400/20 px-4 py-3 text-[13px] text-rose-200 break-words">diff --git a/src/shared/types.ts b/src/shared/types.tsindex f79d425..5eee530 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -13,6 +13,7 @@ export interface Song {addedAt: numbermodel?: stringstems?: string[]+ took?: number}export interface EnvStatus {