Split any YouTube song into stems
TypeScript
Merge upstream main: keep AAC export and export-folder working together
Anton Sychevdde01c91aa6b
diff --cc src/main/index.tsindex 45ba716,6d3341c..18adb8d--- a/src/main/index.ts+++ b/src/main/index.ts@@@ -1,6 -1,15 +1,14 @@@- import { app, BrowserWindow, ipcMain, shell, dialog } from 'electron'+ import {+ app,+ BrowserWindow,+ ipcMain,+ shell,+ dialog,+ Menu,+ type MenuItemConstructorOptions+ } from 'electron'import { join, normalize, extname } from 'path'-import { existsSync, copyFileSync, mkdirSync, createReadStream, statSync } from 'fs'-import { spawn } from 'child_process'+import { existsSync, copyFileSync, createReadStream, statSync } from 'fs'import { createServer, type Server } from 'http'import type { AddressInfo } from 'net'import type { AppSettings } from '../shared/types'@@@ -21,8 -30,7 +29,8 @@@ importgetStatus} from './env'import { loadSettings, saveSettings } from './settings'- import { loadSongs, removeSong, clearLibrary, stemBuffers, stemsDir, stemsFor, sanitizeName, exportStems } from './library'-import { loadSongs, removeSong, stemBuffers, stemsDir, stemsFor, mixWavPath, AUDIO_EXTENSIONS } from './library'++import { loadSongs, removeSong, clearLibrary, stemBuffers, stemsDir, stemsFor, sanitizeName, exportStems, transcodeToAac } from './library'+import { AUDIO_EXTENSIONS } from '../shared/local'import { startJob, startLocalJob, cancelJob, searchYouTube } from './pipeline'import { initUpdater } from './updater'import { runSmoke } from './smoke'@@@ -76,6 -84,80 +84,65 @@@ function startRendererServer(): Promise})}-function sanitizeName(name: string): string {- const clean = name.replace(/[\\/:*?"<>|]/g, '-').trim()- return clean.length > 0 ? clean.slice(0, 120) : 'stems'-}-+ function showAboutWindow(): void {+ if (!mainWindow) return+ if (mainWindow.isMinimized()) mainWindow.restore()+ mainWindow.show()+ mainWindow.focus()+ mainWindow.webContents.send('app:show-about')+ }++ function installApplicationMenu(): void {+ const aboutItem: MenuItemConstructorOptions = {+ label: 'About StemKit',+ click: showAboutWindow+ }+ const template: MenuItemConstructorOptions[] =+ process.platform === 'darwin'+ ? [+ {+ label: app.name,+ submenu: [+ aboutItem,+ { type: 'separator' },+ { role: 'services', submenu: [] },+ { type: 'separator' },+ { role: 'hide' },+ { role: 'hideOthers' },+ { role: 'unhide' },+ { type: 'separator' },+ { role: 'quit' }+ ]+ },+ {+ label: 'Edit',+ submenu: [+ { role: 'undo' },+ { role: 'redo' },+ { type: 'separator' },+ { role: 'cut' },+ { role: 'copy' },+ { role: 'paste' },+ { role: 'selectAll' }+ ]+ },+ { label: 'Window', submenu: [{ role: 'minimize' }, { role: 'zoom' }, { role: 'front' }] }+ ]+ : [+ { label: 'File', submenu: [{ role: 'quit' }] },+ { label: 'Help', submenu: [aboutItem] }+ ]+ Menu.setApplicationMenu(Menu.buildFromTemplate(template))+ }++ function requireExportFfmpeg(): string {+ const ffmpeg = getStatus().ffmpeg.path+ if (!ffmpeg) {+ throw new Error('Something went wrong with the built-in audio tools. Try reinstalling StemKit.')+ }+ return ffmpeg+ }+-// the bundled ffmpeg is a minimal static build without libmp3lame, so mp3-// isn't an option — aac is a native encoder, no extra library needed-function transcodeToAac(ffmpeg: string, input: string, output: string): Promise<void> {- return new Promise((resolve, reject) => {- const child = spawn(ffmpeg, ['-y', '-i', input, '-c:a', 'aac', '-b:a', '256k', output])- child.on('error', reject)- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`ffmpeg exited ${code}`))))- })-}-async function createWindow(): Promise<void> {mainWindow = new BrowserWindow({width: 1360,@@@ -228,8 -306,26 +306,17 @@@ app.whenReady().then(async () =>properties: ['openDirectory', 'createDirectory']})if (result.canceled || !result.filePaths[0]) return { saved: false }- const { path, count } = await exportStems(videoId, song?.title ?? videoId, list, result.filePaths[0])- const target = join(result.filePaths[0], sanitizeName(song?.title ?? videoId))- mkdirSync(target, { recursive: true })+ const format = loadSettings().exportFormat- const ext = format === 'aac' ? 'm4a' : 'wav'+ const ffmpeg = format === 'aac' ? requireExportFfmpeg() : null- for (const name of list) {- const src = join(dir, `${name}.wav`)- const dest = join(target, `${name}.${ext}`)- if (ffmpeg) await transcodeToAac(ffmpeg, src, dest)- else copyFileSync(src, dest)- }- let count = list.length- const mix = mixWavPath(videoId)- if (existsSync(mix)) {- const mixDest = join(target, `${sanitizeName(song?.title ?? 'full track')}.${ext}`)- if (ffmpeg) await transcodeToAac(ffmpeg, mix, mixDest)- else copyFileSync(mix, mixDest)- count += 1- }- return { saved: true, path: target, count }++ const { path, count } = await exportStems(++ videoId,++ song?.title ?? videoId,++ list,++ result.filePaths[0],++ format,++ ffmpeg++ )+ return { saved: true, path, count }})ipcMain.handle('search:youtube', (_e, query: string) => searchYouTube(query))diff --cc src/main/library.tsindex 004b40a,e7cfe7e..b13b505--- a/src/main/library.ts+++ b/src/main/library.ts@@@ -1,5 -1,5 +1,6 @@@import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, openSync, readSync, closeSync } from 'fs'-import { readFile } from 'fs/promises'+import { readFile, cp } from 'fs/promises'++import { spawn } from 'child_process'import { join } from 'path'import { userDataDir } from './env'import { DEFAULT_STEMS, type Song } from '../shared/types'@@@ -61,36 -74,6 +62,64 @@@ export function removeSong(videoId: strreturn songs}+// wipes the whole library off the disk; running jobs are cancelled by the+// caller first, otherwise they would keep writing into a deleted folder+export function clearLibrary(): void {+ saveSongs([])+ rmSync(songsRoot(), { recursive: true, force: true })+}++export function sanitizeName(name: string): string {+ const clean = name.replace(/[\\/:*?"<>|]/g, '-').trim()+ return clean.length > 0 ? clean.slice(0, 120) : 'stems'+}+++// the bundled ffmpeg is a minimal static build without libmp3lame, so mp3 isn't++// an option — aac is a native encoder that needs no extra library++export function transcodeToAac(ffmpeg: string, input: string, output: string): Promise<void> {++ return new Promise((resolve, reject) => {++ const child = spawn(ffmpeg, ['-y', '-i', input, '-c:a', 'aac', '-b:a', '256k', output])++ child.on('error', reject)++ child.on('close', (code) =>++ code === 0 ? resolve() : reject(new Error(`ffmpeg exited ${code} writing ${output}`))++ )++ })++}++++// aac needs the bundled ffmpeg passed in; a null ffmpeg copies the lossless wav++async function writeTo(++ src: string,++ dest: string,++ format: 'wav' | 'aac',++ ffmpeg: string | null++): Promise<void> {++ if (format === 'wav' || !ffmpeg) await cp(src, dest)++ else await transcodeToAac(ffmpeg, src, dest)++}+++export async function exportStems(+ videoId: string,+ title: string,+ stems: string[],- root: string++ root: string,++ format: 'wav' | 'aac' = 'wav',++ ffmpeg: string | null = null+): Promise<{ path: string; count: number }> {+ const dir = stemsDir(videoId)++ const ext = format === 'aac' ? 'm4a' : 'wav'+ const target = join(root, sanitizeName(title || videoId))+ mkdirSync(target, { recursive: true })+ const names = stems.filter((name) => existsSync(join(dir, `${name}.wav`)))- await Promise.all(names.map((name) => cp(join(dir, `${name}.wav`), join(target, `${name}.wav`))))++ await Promise.all(++ names.map((name) => writeTo(join(dir, `${name}.wav`), join(target, `${name}.${ext}`), format, ffmpeg))++ )+ const mix = mixWavPath(videoId)+ if (existsSync(mix)) {- await cp(mix, join(target, `${sanitizeName(title || 'full track')}.wav`))++ await writeTo(mix, join(target, `${sanitizeName(title || 'full track')}.${ext}`), format, ffmpeg)+ }+ return { path: target, count: names.length + (existsSync(mix) ? 1 : 0) }+}+export function stemsFor(song?: Song | null): string[] {return song?.stems?.length ? song.stems : DEFAULT_STEMS}diff --cc src/main/pipeline.tsindex 527c4f6,151e26d..3026ee0--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@@ -215,21 -207,6 +215,29 @@@ function finalizeJobsource: info.source})send({ kind: 'done', data: { videoId: job.videoId, song: songs[0] } })+- const folder = loadSettings().exportFolder- if (folder) {++ const { exportFolder, exportFormat } = loadSettings()++ if (exportFolder) {++ const ffmpeg = exportFormat === 'aac' ? (getStatus().ffmpeg.path ?? null) : null+ // not awaited: a slow or full target volume must not hold up the library+ // entry the player is already waiting on- void exportStems(job.videoId, info.title, producedStems, folder).catch((err: unknown) =>++ void exportStems(++ job.videoId,++ info.title,++ producedStems,++ exportFolder,++ exportFormat,++ ffmpeg++ ).catch((err: unknown) =>+ send({+ kind: 'failed',+ data: {+ videoId: '',- message: `Export to ${folder} failed: ${err instanceof Error ? err.message : String(err)}`++ message: `Export to ${exportFolder} failed: ${err instanceof Error ? err.message : String(err)}`+ }+ })+ )+ }}export async function startJob(diff --cc src/main/settings.tsindex 9c5189e,6ca8aee..d9ff62d--- a/src/main/settings.ts+++ b/src/main/settings.ts@@@ -25,7 -25,7 +25,8 @@@ export function saveSettings(patch: ParroformerVocals: !!merged.roformerVocals,gpuSplit: !!merged.gpuSplit,hideVideo: !!merged.hideVideo,- exportFormat: merged.exportFormat === 'aac' ? 'aac' : 'wav'++ exportFormat: merged.exportFormat === 'aac' ? 'aac' : 'wav',+ exportFolder: typeof merged.exportFolder === 'string' ? merged.exportFolder.trim() : ''}writeFileSync(settingsFile(), JSON.stringify(next, null, 2))for (const win of BrowserWindow.getAllWindows()) {diff --cc src/renderer/src/App.tsxindex 70d318b,3cdea8d..cf78675--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@@ -6,9 -6,10 +6,10 @@@ import { isAudioPath, isLocalId, localSimport { Sidebar } from './components/Sidebar'import { Home } from './components/Home'import { Processing } from './components/Processing'-import { Player } from './components/Player'+import { Player, releaseBufferCache } from './components/Player'import { Setup } from './components/Setup'import { Settings } from './components/Settings'+ import { About } from './components/About'import { LogoMark } from './components/Icons'interface EnvLog {@@@ -53,15 -54,7 +54,16 @@@ export default function App(): React.Reconst [appVersion, setAppVersion] = useState<string | undefined>(undefined)const [settings, setSettings] = useState<AppSettings | null>(null)const [settingsOpen, setSettingsOpen] = useState(false)+ const [aboutOpen, setAboutOpen] = useState(false)+ const [dropping, setDropping] = useState(false)+ const [notice, setNotice] = useState<string | null>(null)+ // what a dropped file should be split with: Home pushes its current engine+ // and instrument selection down, so a drop honours the same toggles the+ // buttons use without owning that state here+ const startOpts = useRef<{ model: string; stems: string[] }>({+ model: MODEL_DEFAULT,+ stems: [...DEFAULT_STEMS]+ })useEffect(() => {void window.stemkit.envStatus().then(setStatus)@@@ -428,25 -301,7 +438,26 @@@onClose={() => setSettingsOpen(false)}/>)}+ {/* pointer-events-none: the drop has to land on the window listeners,+ not on the hint itself, or enter/leave would flicker over it */}+ {dropping && (+ <div className="fixed inset-0 z-50 p-6 pointer-events-none">+ <div className="h-full w-full rounded-3xl border-2 border-dashed border-violet-300/70 bg-violet-500/[0.12] flex flex-col items-center justify-center gap-2">+ <p className="text-lg font-semibold text-violet-100">Drop to split</p>+ <p className="text-[13px] text-white/60">+ audio files (mp3, wav, flac, m4a…) or a YouTube link+ </p>+ </div>+ </div>+ )}+ {notice && (+ <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 max-w-[720px] rise-in">+ <div className="rounded-xl border border-rose-400/25 bg-rose-500/10 px-4 py-2.5 text-[13px] text-rose-200 break-words">+ {notice}+ </div>+ </div>+ )}+ {aboutOpen && <About version={appVersion} onClose={() => setAboutOpen(false)} />}</div>)}diff --cc src/renderer/src/components/Settings.tsxindex 51e1d53,8ccfb81..fab39da--- a/src/renderer/src/components/Settings.tsx+++ b/src/renderer/src/components/Settings.tsx@@@ -342,55 -336,52 +342,82 @@@ export function Settings({ settings, gp</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>- </section>-<section className="pt-5 border-t border-white/[0.06] space-y-5"><SectionHeader label="Export" />+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-[13px] font-medium">Export format</p>+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">+ AAC (.m4a) is transcoded on export with the built-in ffmpeg — much smaller+ files, small quality loss.+ </p>+ </div>+ <div className="flex shrink-0 rounded-lg bg-white/[0.06] p-0.5 border border-white/[0.08]">+ {([+ { v: 'wav' as const, label: 'WAV' },+ { v: 'aac' as const, label: 'AAC' }+ ]).map((opt) => (+ <button+ key={opt.v}+ onClick={() => onChange({ exportFormat: opt.v })}+ className={`no-drag px-2.5 h-6 rounded-md text-[12px] font-semibold transition-colors ${+ settings.exportFormat === opt.v+ ? 'bg-white text-black'+ : 'text-white/45 hover:text-white/80'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div>+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <p className="text-[13px] font-medium">Export folder</p>+ <p className="text-[11.5px] text-white/40 leading-relaxed mt-0.5">+ Copy the stems of every finished split straight into this folder, in a subfolder+ per song. They stay in the library either way.+ </p>+ {settings.exportFolder && (+ <p className="mt-1.5 text-[11px] font-mono text-white/45 break-all leading-relaxed">+ {settings.exportFolder}+ </p>+ )}+ </div>+ <div className="shrink-0 flex flex-col items-end gap-1.5">+ <button+ onClick={pickFolder}+ className="no-drag px-3 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/[0.08] text-[12px] text-white/75 hover:text-white transition-colors"+ >+ {settings.exportFolder ? 'Change' : 'Choose…'}+ </button>+ {settings.exportFolder && (+ <button+ onClick={() => onChange({ exportFolder: '' })}+ className="no-drag text-[11px] text-white/35 hover:text-white/70 transition-colors"+ >+ Stop exporting+ </button>+ )}+ </div>+ </div>+ </section>++ <section className="pt-5 border-t border-white/[0.06] space-y-5">+ <SectionHeader label="Playback" />+ <div className="flex items-start justify-between gap-4">+ <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></section></div></div>diff --cc src/shared/types.tsindex 40c7d1b,b446aed..7825730--- a/src/shared/types.ts+++ b/src/shared/types.ts@@@ -34,10 -34,10 +34,14 @@@ export interface AppSettings// hide the YouTube video while playing: stems are always played locally,// this stops streaming the video and falls back to cached thumbnailshideVideo: boolean+ // format used when exporting stems: wav is the lossless source format,+ // aac (.m4a) is transcoded on export via the bundled ffmpeg. mp3 isn't an+ // option — the bundled ffmpeg is a minimal static build without libmp3lame+ exportFormat: 'wav' | 'aac'+ // absolute path: every finished split is copied out of the app's own storage+ // into a <exportFolder>/<song>/ folder as soon as it lands in the library.+ // Empty means "stay in the library only"+ exportFolder: string}export const DEFAULT_SETTINGS: AppSettings = {@@@ -46,7 -46,7 +50,8 @@@roformerVocals: false,gpuSplit: false,hideVideo: false,- exportFormat: 'wav'++ exportFormat: 'wav',+ exportFolder: ''}export interface EngineStatus {