import { createPortal } from 'react-dom' import { useEffect, useMemo, useState, type ReactNode } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type JobStatus, type PlaylistNode, type StemConvertOptions, type StemEngineStatus, type StemTarget, } from '../api' import { FolderPicker } from './FolderPicker' /** * Convert to Stems — one dialog (decided, see the stem-conversion discussion * log): where the files go, what the collection does, a live preview, Convert. * * Every option is REMEMBERED (`stemConvert` in prefs) — unlike Add Files' * ask-every-time — so Replace may be the preselected mode; that is why its * consequence is stated in the option itself, not only at Save. * * When the engine is missing the dialog downloads it inline; closing it lets * the download carry on (App shows it in the status bar via `onDownloading`). */ interface Remembered { mode: 'replace' | 'destination' destination: string collection: 'repoint' | 'add' playlist: 'none' | 'existing' | 'new' playlistId: string playlistName: string } const DEFAULTS: Remembered = { mode: 'replace', destination: '~/Music/Stems', collection: 'repoint', playlist: 'new', playlistId: '', playlistName: 'Stems', } /** Real-time factors (seconds of audio per second of work), measured on an M3 * Pro for MPS and CPU; the Windows figures are estimates until measured. */ const SPEED: Record = { 'macos-arm64:gpu': 5.4, 'macos-arm64:cpu': 1.2, 'windows-x64-cuda:gpu': 8, 'windows-x64-cuda:cpu': 0.8, 'windows-x64-cpu:cpu': 0.8, } export function size(bytes: number): string { if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB` if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB` return `${Math.max(1, Math.round(bytes / 1e3))} kB` } function duration(seconds: number): string { const m = Math.round(seconds / 60) if (m < 1) return 'under a minute' if (m < 90) return `${m} min` return `${(seconds / 3600).toFixed(1)} h` } function flatten(nodes: PlaylistNode[], path = ''): { id: string; label: string }[] { return nodes.flatMap((n) => [ ...(n.can_add_tracks && n.kind === 'playlist' ? [{ id: n.id, label: path + n.name }] : []), ...flatten(n.children ?? [], `${path}${n.name} / `), ]) } interface Props { trackIds: string[] onClose: () => void /** The conversion job started — App tracks it in the status bar. */ onStarted: (job: JobStatus) => void /** An engine download started — App shows it in the status bar. */ onDownloading: (job: JobStatus) => void onError: (msg: string) => void } export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading, onError }: Props) { const qc = useQueryClient() const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const [opts, setOpts] = useState(null) const [browsing, setBrowsing] = useState(false) const [showSkipped, setShowSkipped] = useState(false) const [starting, setStarting] = useState(false) const [target, setTarget] = useState(null) useEffect(() => { if (opts || !prefs.isSuccess) return const saved = (prefs.data as { stemConvert?: Partial }).stemConvert setOpts({ ...DEFAULTS, ...(saved ?? {}) }) }, [prefs.isSuccess, prefs.data, opts]) const engine = useQuery({ queryKey: ['stem-engine'], queryFn: api.stemEngine }) const installJobId = engine.data?.install_job ?? null const install = useQuery({ queryKey: ['job', installJobId], queryFn: () => api.job(installJobId!), enabled: !!installJobId, refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400), }) useEffect(() => { if (install.data && install.data.state !== 'running') { if (install.data.state === 'failed') onError(install.data.error || 'The download failed') qc.invalidateQueries({ queryKey: ['stem-engine'] }) } }, [install.data, qc, onError]) const playlists = useQuery({ queryKey: ['playlists'], queryFn: api.playlists }) const choices = useMemo(() => flatten(playlists.data ?? []), [playlists.data]) const body: StemConvertOptions | null = opts && { mode: opts.mode, destination: opts.mode === 'destination' ? opts.destination : null, collection: opts.mode === 'replace' ? 'repoint' : opts.collection, playlist_id: opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'existing' ? opts.playlistId || null : null, new_playlist: opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'new' ? opts.playlistName.trim() || 'Stems' : null, } const preview = useQuery({ queryKey: ['stem-preview', trackIds, body], queryFn: () => api.stemPreview(trackIds, body!), enabled: !!body, staleTime: 0, gcTime: 0, }) const set = (patch: Partial) => setOpts((o) => (o ? { ...o, ...patch } : o)) const st: StemEngineStatus | undefined = engine.data const ready = !!st?.installed && !!st?.weights.installed const downloading = install.data?.state === 'running' const offered = st?.offered_targets ?? [] const chosenTarget = target ?? (offered.includes('windows-x64-cuda') ? 'windows-x64-cuda' : offered[0]) const needBytes = (st?.installed ? 0 : (chosenTarget && st?.download_sizes[chosenTarget]) || 0) + (st?.weights.installed ? 0 : st?.weights.size ?? 0) const plan = preview.data const n = plan?.convert.length ?? 0 const allReused = !!plan && plan.convert.every((c) => c.reuse) const device = (st?.device ?? 'auto') === 'cpu' ? 'cpu' : 'gpu' const rtf = st?.installed ? SPEED[`${st.installed.target}:${device}`] ?? SPEED[`${st.installed.target}:cpu`] : null const canConvert = !!plan && n > 0 && !plan.blocked && (ready || allReused) && !starting // With nothing to convert the reasons ARE the answer: show them without a click. const skippedOpen = showSkipped || (!!plan && n === 0 && plan.skipped.length > 0) const whyNot = !plan ? undefined : n === 0 ? 'Nothing to convert — see why each track is skipped' : plan.blocked ? plan.blocked : !ready && !allReused ? 'The stem engine is not installed yet' : undefined const download = async () => { try { const job = await api.stemEngineInstall(chosenTarget ?? null) onDownloading(job) qc.invalidateQueries({ queryKey: ['stem-engine'] }) } catch (e) { onError((e as Error).message) } } const convert = async () => { if (!body || !opts) return setStarting(true) try { api.patchPrefs({ stemConvert: opts }).then((p) => qc.setQueryData(['prefs'], p)).catch(() => {}) onStarted(await api.stemConvert(trackIds, body)) onClose() } catch (e) { onError((e as Error).message) setStarting(false) } } const radio = ( name: string, checked: boolean, onPick: () => void, label: string, detail: ReactNode, disabled = false, ) => ( ) const count = trackIds.length return createPortal( <> {browsing && opts && ( set({ destination: path })} onClose={() => setBrowsing(false)} /> )}
e.key === 'Escape' && !starting && onClose()} >

Convert {count} track{count === 1 ? '' : 's'} to stems

{!opts ? (
Loading…
) : (
Where
{radio( 'stem-mode', opts.mode === 'replace', () => set({ mode: 'replace' }), 'Replace the originals', <> Track.mp3 becomes Track.stem.m4a, in the same folder. {opts.mode === 'replace' && ( Saving deletes the {n || ''} original file{n === 1 ? '' : 's'} {plan?.original_bytes ? ` (${size(plan.original_bytes)})` : ''} for good — and any other app or older collection version using them loses them. Discard keeps them. )} , )} {radio( 'stem-mode', opts.mode === 'destination', () => set({ mode: 'destination' }), 'Save to a folder', {`‎${opts.destination}‎`} , )}
{opts.mode === 'destination' && (
In the collection
{radio( 'stem-collection', opts.collection === 'repoint', () => set({ collection: 'repoint' }), 'Point each track at its stem file', 'The track keeps its playlists, cues and history. The original file stays where it is.', )} {radio( 'stem-collection', opts.collection === 'add', () => set({ collection: 'add' }), 'Add the stem files as new tracks', 'With the same cues, grid and tags. The original tracks stay as they are.', )} {opts.collection === 'add' && (
{opts.playlist === 'new' && ( set({ playlistName: e.target.value })} className="well min-w-0 flex-1 rounded-md px-2 py-1 text-text" placeholder="Playlist name" /> )}
)}
)} {!ready && st && (
{!st.supported ? (
There is no stem engine for this computer.
) : downloading && install.data ? (
{install.data.message || 'Downloading…'}
{size(install.data.done)} of {size(install.data.total || needBytes)} · closing this keeps it going
) : !st.manifest_available && !st.installed ? (
The stem engine is a one-time download, and it cannot be reached right now. Check the internet connection — or install it from a file in Settings → Stems.
) : (
The stem engine is a one-time download ({size(needBytes)}).
{offered.length > 1 && !st.installed && (
{offered.map((t) => ( ))}
)}
)}
)} {preview.isError &&
{(preview.error as Error).message}
} {plan && (
{n} to convert {plan.skipped.length > 0 && ( <> {' · '} )}
{skippedOpen && (
    {plan.skipped.map((s) => (
  • {s.title} {s.reason}
  • ))}
)} {n > 0 && (
{plan.seconds > 0 && rtf ? `About ${duration(plan.seconds / rtf)} on this computer · ` : ''} {plan.seconds === 0 && allReused ? 'Already converted earlier — nothing to separate · ' : ''} {size(plan.bytes)} of stem files
)} {plan.blocked &&
{plan.blocked}
}
)}
)}
, document.body, ) }