Split any YouTube song into stems
TypeScript
feat: export selected stems mixed or separately
David Navia03d543885cdd
diff --git a/src/renderer/src/components/ExportDialog.tsx b/src/renderer/src/components/ExportDialog.tsxnew file mode 100644index 0000000..3780fb0--- /dev/null+++ b/src/renderer/src/components/ExportDialog.tsx@@ -0,0 +1,208 @@+import { useEffect, useRef, useState } from 'react'+import { MIX_ID, canExport, type ExportMode } from '../../../shared/export-rules'+import { formatShift, transposeKey } from '../../../shared/keys'+import type { StemMeta } from '../lib/stems'+import { XIcon } from './Icons'++interface Props {+ stems: StemMeta[]+ initial: Set<string>+ semitones: number+ originalKey: string | null+ onClose(): void+ onExport(mode: ExportMode, selected: Set<string>, shifted: boolean): Promise<void>+}++export function ExportDialog({+ stems,+ initial,+ semitones,+ originalKey,+ onClose,+ onExport+}: Props): React.ReactElement {+ const [selected, setSelected] = useState<Set<string>>(() => new Set(initial))+ const [shifted, setShifted] = useState(true)+ const [busy, setBusy] = useState<ExportMode | null>(null)+ const [error, setError] = useState<string | null>(null)+ // hovering or focusing "Export mixed" previews that the original mix is left out+ const [mixedHover, setMixedHover] = useState(false)+ const dialogRef = useRef<HTMLDivElement>(null)++ // a render can take a while and the session must reach exportEnd, so the+ // dialog stays up until the export settles+ const close = (): void => {+ if (!busy) onClose()+ }++ useEffect(() => {+ dialogRef.current?.focus()+ }, [])++ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ if (e.key === 'Escape' && !busy) onClose()+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [busy, onClose])++ const toggle = (id: string): void => {+ setSelected((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }++ const run = async (mode: ExportMode): Promise<void> => {+ setBusy(mode)+ setError(null)+ try {+ await onExport(mode, selected, semitones !== 0 && shifted)+ onClose()+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ setBusy(null)+ }+ }++ const shiftedKey = originalKey ? transposeKey(originalKey, semitones) : null+ const originalLabel = shiftedKey ? `Original (${originalKey})` : 'Original'+ const shiftedLabel = shiftedKey+ ? `Shifted (${shiftedKey} ${formatShift(semitones)})`+ : `Shifted (${formatShift(semitones)})`+ const mixDimmed = mixedHover || busy === 'mixed'++ const rowClass =+ 'flex items-center gap-3 rounded-lg px-3 py-2 text-[13px] hover:bg-white/[0.04] transition-colors cursor-pointer'+ const buttonClass =+ 'no-drag flex-1 rounded-xl px-4 py-2.5 text-[13px] font-medium transition-colors disabled:opacity-40 disabled:cursor-not-allowed'++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"+ onClick={close}+ >+ <div+ ref={dialogRef}+ role="dialog"+ aria-modal="true"+ aria-labelledby="export-title"+ aria-busy={busy !== null}+ tabIndex={-1}+ className="w-full max-w-sm mx-4 rounded-2xl border border-white/[0.08] bg-[#16151d] shadow-2xl rise-in outline-none"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/[0.07]">+ <h2 id="export-title" className="text-[14px] font-semibold tracking-tight">+ Export+ </h2>+ <button+ onClick={close}+ disabled={busy !== null}+ title="Close"+ className="no-drag w-7 h-7 rounded-lg hover:bg-white/10 text-white/50 hover:text-white flex items-center justify-center transition-colors disabled:opacity-40"+ >+ <XIcon className="w-3.5 h-3.5" />+ </button>+ </div>++ <div className="px-5 py-4 space-y-4">+ <fieldset disabled={busy !== null} className="space-y-0.5">+ <legend className="sr-only">Tracks</legend>+ {stems.map((meta) => (+ <label key={meta.id} className={rowClass}>+ <input+ type="checkbox"+ checked={selected.has(meta.id)}+ onChange={() => toggle(meta.id)}+ className="w-4 h-4 accent-violet-500"+ />+ <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: meta.color }} />+ <span className="capitalize text-white/80">{meta.label}</span>+ </label>+ ))}+ <label className={`${rowClass} ${mixDimmed ? 'opacity-40' : ''}`}>+ <input+ type="checkbox"+ checked={selected.has(MIX_ID)}+ onChange={() => toggle(MIX_ID)}+ className="w-4 h-4 accent-violet-500"+ />+ <span className="w-2.5 h-2.5 rounded-full shrink-0 bg-white/40" />+ <span className="text-white/80">Original mix</span>+ {mixDimmed && (+ <span className="ml-auto text-[11px] text-white/50">already contains every stem</span>+ )}+ </label>+ </fieldset>++ {semitones !== 0 && (+ <fieldset disabled={busy !== null} className="space-y-1">+ <legend className="text-[11px] uppercase tracking-wider text-white/40 mb-1.5">Pitch</legend>+ <div className="flex gap-2">+ {[+ { value: false, label: originalLabel },+ { value: true, label: shiftedLabel }+ ].map((opt) => (+ <label+ key={opt.label}+ className={`flex-1 flex items-center gap-2 rounded-lg px-3 py-2 text-[12.5px] cursor-pointer border transition-colors ${+ shifted === opt.value+ ? 'border-violet-400/50 bg-violet-500/10 text-white'+ : 'border-white/[0.08] text-white/60 hover:bg-white/[0.04]'+ }`}+ >+ <input+ type="radio"+ name="export-pitch"+ checked={shifted === opt.value}+ onChange={() => setShifted(opt.value)}+ className="accent-violet-500"+ />+ <span className="truncate">{opt.label}</span>+ </label>+ ))}+ </div>+ </fieldset>+ )}++ {error && (+ <p role="alert" className="rounded-lg bg-rose-500/10 border border-rose-400/20 px-3 py-2 text-xs text-rose-200 break-words">+ {error}+ </p>+ )}++ <div className="flex gap-2 pt-1">+ {/* hover lives on a wrapper: disabled buttons get no mouse events,+ and that is exactly when the hint explains why */}+ <span+ className="flex-1 flex"+ onMouseEnter={() => setMixedHover(true)}+ onMouseLeave={() => setMixedHover(false)}+ >+ <button+ onClick={() => void run('mixed')}+ onFocus={() => setMixedHover(true)}+ onBlur={() => setMixedHover(false)}+ disabled={busy !== null || !canExport(selected, 'mixed')}+ className={`${buttonClass} bg-violet-500 text-white hover:bg-violet-400`}+ >+ {busy === 'mixed' ? 'Exporting…' : 'Export mixed'}+ </button>+ </span>+ <button+ onClick={() => void run('separate')}+ disabled={busy !== null || !canExport(selected, 'separate')}+ className={`${buttonClass} glass text-white/80 hover:text-white hover:bg-white/10`}+ >+ {busy === 'separate' ? 'Exporting…' : 'Export separately'}+ </button>+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsxindex 7db1745..df0cf99 100644--- a/src/renderer/src/components/Player.tsx+++ b/src/renderer/src/components/Player.tsx@@ -8,6 +8,9 @@ import { YouTubeHost, type YTState } from '../lib/youtube'import { StemLane } from './StemLane'import { Transport, type PresetId } from './Transport'import { DownloadIcon } from './Icons'+import { ExportDialog } from './ExportDialog'+import { exportMixed, exportSeparate } from '../lib/exporter'+import { MIX_ID, initialSelection, type ExportMode } from '../../../shared/export-rules'// number keys 1-6 mute the lane shown in that position, top to bottomconst STEM_KEYS = ['1', '2', '3', '4', '5', '6']@@ -93,6 +96,7 @@ export function Player({ song, settings }: Props): React.ReactElement {const [semitones, setSemitones] = useState(0)const [pitchError, setPitchError] = useState<string | null>(null)const [preset, setPreset] = useState<PresetId | 'custom'>('all')+ const [exportOpen, setExportOpen] = useState(false)const stemMeta = useMemo(() => buildStemMeta(Object.keys(buffers) as StemId[]), [buffers])@@ -126,6 +130,7 @@ export function Player({ song, settings }: Props): React.ReactElement {setMutes(new Set())setSolos(new Set())setPreset('all')+ setExportOpen(false)engine.stopAll()// the engine applies pitch lazily, so the UI keeps its own valuesetSemitones(0)@@ -358,7 +363,24 @@ export function Player({ song, settings }: Props): React.ReactElement {[song.videoId])-+ const runExport = async (+ mode: ExportMode,+ selected: Set<string>,+ shifted: boolean+ ): Promise<void> => {+ const opts = {+ videoId: song.videoId,+ title: song.title,+ stems: stemMeta.map((s) => s.id),+ selected: [...selected],+ buffers,+ vols,+ pans,+ semitones: shifted ? semitones : 0+ }+ if (mode === 'mixed') await exportMixed(opts)+ else await exportSeparate({ ...opts, includeMix: selected.has(MIX_ID) })+ }const applyPreset = (p: PresetId): void => {setPreset(p)@@ -393,6 +415,8 @@ export function Player({ song, settings }: Props): React.ReactElement {useEffect(() => {const onKey = (e: KeyboardEvent): void => {+ // the dialog's buttons and checkboxes own Space and the number keys+ if (exportOpen) returnif (e.target instanceof HTMLInputElement) returnif (e.code === 'Space') {e.preventDefault()@@ -411,7 +435,7 @@ export function Player({ song, settings }: Props): React.ReactElement {}window.addEventListener('keydown', onKey)return () => window.removeEventListener('keydown', onKey)- }, [togglePlay, toggleMute, stemMeta, seekTo, decoding, decodeError])+ }, [togglePlay, toggleMute, stemMeta, seekTo, decoding, decodeError, exportOpen])const toggleSolo = (id: StemId): void => {setPreset('custom')@@ -497,12 +521,12 @@ export function Player({ song, settings }: Props): React.ReactElement {<div className="flex items-center gap-3"><button- // temporary: Task 4 replaces this with the Export dialog- disabled+ onClick={() => setExportOpen(true)}+ disabled={decoding || !!decodeError || stemMeta.length === 0}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 flex items-center gap-2 disabled:opacity-40"><DownloadIcon className="w-4 h-4" />- Export everything+ Export</button>{youtubeUrl && (<button@@ -599,6 +623,16 @@ export function Player({ song, settings }: Props): React.ReactElement {</div></div></div>+ {exportOpen && (+ <ExportDialog+ stems={stemMeta}+ initial={initialSelection(stemMeta.map((s) => s.id), mutes, solos)}+ semitones={semitones}+ originalKey={songKey?.override ?? songKey?.detected ?? null}+ onClose={() => setExportOpen(false)}+ onExport={runExport}+ />+ )}</div>)}diff --git a/src/renderer/src/lib/exporter.ts b/src/renderer/src/lib/exporter.tsnew file mode 100644index 0000000..d866ca7--- /dev/null+++ b/src/renderer/src/lib/exporter.ts@@ -0,0 +1,157 @@+import type { StemId, StemPanMap } from '../../../shared/types'+import { encodeWavF32 } from '../../../shared/wav'+import { MIX_ID, mixedBaseName, separateFolderName } from '../../../shared/export-rules'+import { limitPeak, renderLength, trimLatency } from './render-math'+import { createPitchShifter } from './pitch'+import type { PitchShifter, ShifterFactory } from './pitch'+import { decodePayload, type BufferMap } from './engine'++const SAMPLE_RATE = 44100++export interface RenderSource {+ buffer: AudioBuffer+ gain: number+ pan: number+}++// The context length depends on the shifter's latency, and the shifter needs a+// context to exist, so a tiny context that never renders is used to read it+async function shifterLatency(factory: ShifterFactory): Promise<number> {+ const probe = await factory(new OfflineAudioContext(2, 1, SAMPLE_RATE))+ try {+ return probe.latency+ } finally {+ probe.dispose()+ }+}++// Renders the sources through the same per-stem gain → pan chain as the live+// engine, without the master volume, at 44.1 kHz stereo. The output has the+// length of the longest source: the shifter delay is trimmed off the front.+export async function renderOffline(+ sources: RenderSource[],+ semitones: number,+ factory: ShifterFactory = createPitchShifter+): Promise<Float32Array[]> {+ if (sources.length === 0) throw new Error('Nothing to export')+ const length = renderLength(+ sources.map((s) => s.buffer.duration),+ SAMPLE_RATE+ )+ const latencySamples =+ semitones !== 0 ? Math.ceil((await shifterLatency(factory)) * SAMPLE_RATE) : 0+ const ctx = new OfflineAudioContext(2, length + latencySamples, SAMPLE_RATE)+ let shifter: PitchShifter | null = null+ try {+ let target: AudioNode = ctx.destination+ if (semitones !== 0) {+ shifter = await factory(ctx)+ shifter.setSemitones(semitones)+ shifter.output.connect(ctx.destination)+ target = shifter.input+ }+ for (const s of sources) {+ const src = ctx.createBufferSource()+ src.buffer = s.buffer+ const gain = ctx.createGain()+ gain.gain.value = s.gain+ const pan = ctx.createStereoPanner()+ pan.pan.value = s.pan+ src.connect(gain).connect(pan).connect(target)+ src.start(0)+ }+ const rendered = await ctx.startRendering()+ const out = trimLatency(+ [rendered.getChannelData(0), rendered.getChannelData(1)],+ latencySamples,+ length+ )+ limitPeak(out)+ return out+ } finally {+ // a fresh worklet per render: keeping it would hold the WASM instance alive+ shifter?.dispose()+ }+}++export interface ExportOptions {+ videoId: string+ title: string+ // every stem id of the song, in display order (never MIX_ID)+ stems: string[]+ selected: string[]+ buffers: BufferMap+ vols: Partial<Record<StemId, number>>+ pans: StemPanMap+ // 0 exports at the original pitch+ semitones: number+}++function stemSource(opts: ExportOptions, id: string): RenderSource {+ const buffer = opts.buffers[id as StemId]+ if (!buffer) throw new Error(`Missing audio for ${id}`)+ return {+ buffer,+ gain: opts.vols[id as StemId] ?? 1,+ pan: opts.pans[id as StemId] ?? 0+ }+}++// stems in display order; the original mix is handled separately (or ignored)+function chosenStems(opts: ExportOptions): string[] {+ return opts.stems.filter((id) => id !== MIX_ID && opts.selected.includes(id))+}++export async function exportMixed(opts: ExportOptions): Promise<string | null> {+ const ids = chosenStems(opts)+ if (ids.length === 0) throw new Error('Select at least one stem')+ const session = await window.stemkit.exportBegin(+ 'file',+ mixedBaseName(opts.title, ids, opts.stems, opts.semitones)+ )+ if (!session) return null+ try {+ const channels = await renderOffline(+ ids.map((id) => stemSource(opts, id)),+ opts.semitones+ )+ return await window.stemkit.exportWrite(session.token, null, encodeWavF32(channels, SAMPLE_RATE))+ } finally {+ await window.stemkit.exportEnd(session.token)+ }+}++export async function exportSeparate(+ opts: ExportOptions & { includeMix: boolean }+): Promise<{ path: string; count: number } | null> {+ const ids = chosenStems(opts)+ if (ids.length === 0 && !opts.includeMix) throw new Error('Select at least one stem')+ const session = await window.stemkit.exportBegin(+ 'folder',+ separateFolderName(opts.title, opts.semitones)+ )+ if (!session) return null+ let count = 0+ try {+ // one at a time: every render holds a full-length stereo copy in memory+ for (const id of ids) {+ const channels = await renderOffline([stemSource(opts, id)], opts.semitones)+ await window.stemkit.exportWrite(session.token, id, encodeWavF32(channels, SAMPLE_RATE))+ count+++ }+ if (opts.includeMix) {+ const payload = await window.stemkit.getMix(opts.videoId)+ if (!payload) throw new Error('This song has no original mix to export')+ const decoded = await decodePayload({ [MIX_ID]: payload })+ const buffer = decoded[MIX_ID as StemId]+ if (!buffer) throw new Error('Could not decode the original mix')+ // the original mix ignores the mixer: pitch only, at full volume+ const channels = await renderOffline([{ buffer, gain: 1, pan: 0 }], opts.semitones)+ await window.stemkit.exportWrite(session.token, opts.title, encodeWavF32(channels, SAMPLE_RATE))+ count+++ }+ } finally {+ await window.stemkit.exportEnd(session.token)+ }+ return { path: session.path, count }+}