Skip to content

Split any YouTube song into stems

TypeScript

feat(export): put the original mix first and show real progress

David Navia690c19fe5289
diff --git a/src/renderer/src/components/ExportDialog.tsx b/src/renderer/src/components/ExportDialog.tsx
index 8603ef3..43fe44f 100644
--- a/src/renderer/src/components/ExportDialog.tsx
+++ b/src/renderer/src/components/ExportDialog.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { MIX_ID, canExport, type ExportMode } from '../../../shared/export-rules'
import { formatShift, transposeKey } from '../../../shared/keys'
+import type { ExportProgress, OnProgress } from '../lib/exporter'
import type { StemMeta } from '../lib/stems'
import { XIcon } from './Icons'
@@ -11,7 +12,12 @@ interface Props {
originalKey: string | null
onClose(): void
// resolves false when the user cancelled the save/folder picker
- onExport(mode: ExportMode, selected: Set<string>, shifted: boolean): Promise<boolean>
+ onExport(
+ mode: ExportMode,
+ selected: Set<string>,
+ shifted: boolean,
+ onProgress: OnProgress
+ ): Promise<boolean>
}
export function ExportDialog({
@@ -26,8 +32,10 @@ export function ExportDialog({
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 [progress, setProgress] = useState<ExportProgress | null>(null)
+ // the stems checked right before "Original mix", given back when it is unchecked
+ const [stemsBeforeMix, setStemsBeforeMix] = useState<Set<string>>(() => new Set())
+ const mixChecked = selected.has(MIX_ID)
const dialogRef = useRef<HTMLDivElement>(null)
// a render can take a while and the session must reach exportEnd, so the
@@ -57,17 +65,31 @@ export function ExportDialog({
})
}
+ // the original mix already holds every stem, so it is exported on its own
+ const toggleMix = (): void => {
+ if (mixChecked) {
+ setSelected(new Set(stemsBeforeMix))
+ } else {
+ setStemsBeforeMix(selected)
+ setSelected(new Set([MIX_ID]))
+ }
+ }
+
const run = async (mode: ExportMode): Promise<void> => {
setBusy(mode)
setError(null)
+ setProgress(null)
try {
// a cancelled picker keeps the dialog and its checkboxes for another try
- if (await onExport(mode, selected, semitones !== 0 && shifted)) onClose()
- else setBusy(null)
+ if (await onExport(mode, selected, semitones !== 0 && shifted, setProgress)) {
+ onClose()
+ return
+ }
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
- setBusy(null)
}
+ setBusy(null)
+ setProgress(null)
}
const shiftedKey = originalKey ? transposeKey(originalKey, semitones) : null
@@ -75,10 +97,12 @@ export function ExportDialog({
const shiftedLabel = shiftedKey
? `Shifted (${shiftedKey} ${formatShift(semitones)})`
: `Shifted (${formatShift(semitones)})`
- const mixDimmed = mixedHover || busy === 'mixed'
+ const percent = progress ? Math.round(progress.fraction * 100) : 0
- 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 rowClass = (off: boolean): string =>
+ `flex items-center gap-3 rounded-lg px-3 py-2 text-[13px] transition-colors ${
+ off ? 'opacity-40 cursor-not-allowed' : 'hover:bg-white/[0.04] 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'
@@ -114,31 +138,38 @@ export function ExportDialog({
<div className="px-5 py-4 space-y-4">
<fieldset disabled={busy !== null} className="space-y-0.5">
<legend className="sr-only">Tracks</legend>
+ <label className={rowClass(false)}>
+ <input
+ type="checkbox"
+ checked={mixChecked}
+ onChange={toggleMix}
+ aria-describedby={mixChecked ? 'export-mix-note' : undefined}
+ 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>
+ </label>
+ {mixChecked && (
+ <p id="export-mix-note" className="pl-10 pb-1 text-[11px] text-white/50">
+ Contains every stem
+ </p>
+ )}
+ <div role="separator" className="py-1.5">
+ <div className="border-t border-white/[0.07]" />
+ </div>
{stems.map((meta) => (
- <label key={meta.id} className={rowClass}>
+ <label key={meta.id} className={rowClass(mixChecked)}>
<input
type="checkbox"
checked={selected.has(meta.id)}
onChange={() => toggle(meta.id)}
- className="w-4 h-4 accent-violet-500"
+ disabled={mixChecked}
+ className="w-4 h-4 accent-violet-500 disabled:cursor-not-allowed"
/>
<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 && (
@@ -177,24 +208,40 @@ export function ExportDialog({
</p>
)}
+ {busy !== null && progress && (
+ <div className="space-y-1.5" aria-live="polite">
+ <div className="flex items-baseline justify-between gap-3 text-[11.5px] text-white/60">
+ <span className="truncate">{progress.label}</span>
+ {progress.steps > 1 && (
+ <span className="shrink-0 tabular-nums text-white/40">
+ {progress.step} of {progress.steps}
+ </span>
+ )}
+ </div>
+ <div
+ role="progressbar"
+ aria-label="Export progress"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={percent}
+ className="h-1 rounded-full bg-white/[0.08] overflow-hidden"
+ >
+ <div
+ className="h-full rounded-full bg-violet-500 transition-[width] duration-150 ease-out"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ </div>
+ )}
+
<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')}
+ disabled={busy !== null || !canExport(selected, 'mixed')}
+ className={`${buttonClass} bg-violet-500 text-white hover:bg-violet-400`}
>
- <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>
+ {busy === 'mixed' ? 'Exporting…' : 'Export mixed'}
+ </button>
<button
onClick={() => void run('separate')}
disabled={busy !== null || !canExport(selected, 'separate')}
diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsx
index bbba194..7a167f4 100644
--- a/src/renderer/src/components/Player.tsx
+++ b/src/renderer/src/components/Player.tsx
@@ -9,7 +9,7 @@ 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 { exportMixed, exportOriginal, exportSeparate, type OnProgress } 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 bottom
@@ -369,7 +369,8 @@ export function Player({ song, settings }: Props): React.ReactElement {
const runExport = async (
mode: ExportMode,
selected: Set<string>,
- shifted: boolean
+ shifted: boolean,
+ onProgress: OnProgress
): Promise<boolean> => {
const opts = {
videoId: song.videoId,
@@ -380,14 +381,17 @@ export function Player({ song, settings }: Props): React.ReactElement {
pans,
semitones: shifted ? semitones : 0
}
- // null means the user cancelled the picker
- if (mode === 'mixed') {
- const path = await exportMixed(opts)
+ // null means the user cancelled the picker. The original mix is exclusive
+ // in the dialog, so either button exports just that one file.
+ if (mode === 'mixed' || selected.has(MIX_ID)) {
+ const path = selected.has(MIX_ID)
+ ? await exportOriginal(opts, onProgress)
+ : await exportMixed(opts, onProgress)
if (path === null) return false
setExportNotice({ text: `Exported to ${path}`, path })
return true
}
- const result = await exportSeparate({ ...opts, includeMix: selected.has(MIX_ID) })
+ const result = await exportSeparate(opts, onProgress)
if (result === null) return false
const files = result.count === 1 ? '1 file' : `${result.count} files`
setExportNotice({ text: `Exported ${files} to ${result.path}`, path: result.path })
diff --git a/src/renderer/src/lib/exporter.ts b/src/renderer/src/lib/exporter.ts
index 8e6eeaa..4bef6ea 100644
--- a/src/renderer/src/lib/exporter.ts
+++ b/src/renderer/src/lib/exporter.ts
@@ -1,6 +1,6 @@
import type { StemId, StemPanMap } from '../../../shared/types'
import { encodeWavF32 } from '../../../shared/wav'
-import { MIX_ID, mixedBaseName, separateFolderName } from '../../../shared/export-rules'
+import { MIX_ID, mixedBaseName, originalMixName, separateFolderName } from '../../../shared/export-rules'
import { limitPeak, renderLength, trimLatency } from './render-math'
import { createPitchShifter } from './pitch'
import type { PitchShifter, ShifterFactory } from './pitch'
@@ -17,13 +17,47 @@ export interface RenderSource {
// gets a fixed pad longer than any latency signalsmith reports (~0.12 s)
const SHIFT_PAD = SAMPLE_RATE
+// startRendering gives no progress of its own; suspending at fixed points and
+// resuming right away does, without touching the rendered samples
+const CHECKPOINTS = 20
+const RENDER_QUANTUM = 128
+
+function scheduleCheckpoints(ctx: OfflineAudioContext, onRender: (fraction: number) => void): void {
+ let last = 0
+ for (let k = 1; k < CHECKPOINTS; k++) {
+ // Chromium rounds suspend times to a render quantum and rejects two in the
+ // same quantum (or one at the end), so short renders get fewer checkpoints
+ const frame = Math.floor((ctx.length * k) / CHECKPOINTS / RENDER_QUANTUM) * RENDER_QUANTUM
+ if (frame <= last || frame + RENDER_QUANTUM > ctx.length) continue
+ last = frame
+ // aim mid-quantum: frame / sampleRate can round just below the boundary
+ // and land in the previous quantum, which may already be taken
+ const at = (frame + RENDER_QUANTUM / 2) / ctx.sampleRate
+ ctx.suspend(at).then(
+ () => {
+ // progress is cosmetic: a failing callback must neither stall the
+ // render (no resume) nor surface as an unhandled rejection
+ try {
+ onRender(frame / ctx.length)
+ } catch {
+ // ignored on purpose
+ }
+ void ctx.resume()
+ },
+ // a rejected checkpoint only means one progress tick fewer
+ () => {}
+ )
+ }
+}
+
// 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
+ factory: ShifterFactory = createPitchShifter,
+ onRender?: (fraction: number) => void
): Promise<Float32Array[]> {
if (sources.length === 0) throw new Error('Nothing to export')
const length = renderLength(
@@ -55,7 +89,10 @@ export async function renderOffline(
src.connect(gain).connect(pan).connect(target)
src.start(0)
}
+ // every suspend has to be scheduled before rendering starts
+ if (onRender) scheduleCheckpoints(ctx, onRender)
const rendered = await ctx.startRendering()
+ onRender?.(1)
const out = trimLatency(
[rendered.getChannelData(0), rendered.getChannelData(1)],
latencySamples,
@@ -105,12 +142,59 @@ async function stemSource(
}
}
-// stems in display order; the original mix is handled separately (or ignored)
+// stems in display order; the original mix has its own export
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> {
+export interface ExportProgress {
+ // what is happening now, e.g. "Rendering drums"
+ label: string
+ // 1-based file index and file count
+ step: number
+ steps: number
+ // overall progress across every file, 0..1
+ fraction: number
+}
+
+export type OnProgress = (p: ExportProgress) => void
+
+// Each file weighs the same: decoding 10%, rendering 80%, writing 10%. Decoding
+// is fast but the render is what the user waits for.
+const DECODE = 0.1
+const RENDER = 0.8
+
+function progress(steps: number, onProgress?: OnProgress) {
+ return (step: number, label: string, within: number): void => {
+ onProgress?.({ label, step, steps, fraction: Math.min(1, (step - 1 + within) / steps) })
+ }
+}
+
+// one output file from sources decoded one by one, reporting as it goes
+async function renderFile(
+ step: number,
+ name: string,
+ report: ReturnType<typeof progress>,
+ decode: Array<() => Promise<RenderSource>>,
+ semitones: number
+): Promise<Uint8Array> {
+ const rendering = `Rendering ${name}`
+ const sources: RenderSource[] = []
+ for (const next of decode) {
+ sources.push(await next())
+ report(step, rendering, (DECODE * sources.length) / decode.length)
+ }
+ const channels = await renderOffline(sources, semitones, undefined, (f) =>
+ report(step, rendering, DECODE + RENDER * f)
+ )
+ report(step, `Saving ${name}`, DECODE + RENDER)
+ return encodeWavF32(channels, SAMPLE_RATE)
+}
+
+export async function exportMixed(
+ opts: ExportOptions,
+ onProgress?: OnProgress
+): 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(
@@ -118,46 +202,78 @@ export async function exportMixed(opts: ExportOptions): Promise<string | null> {
mixedBaseName(opts.title, ids, opts.stems, opts.semitones)
)
if (!session) return null
+ const report = progress(1, onProgress)
try {
+ report(1, 'Preparing', 0)
const payload = await window.stemkit.getBuffers(opts.videoId, ids)
- const sources: RenderSource[] = []
- for (const id of ids) sources.push(await stemSource(opts, payload, id))
- const channels = await renderOffline(sources, opts.semitones)
- return await window.stemkit.exportWrite(session.token, null, encodeWavF32(channels, SAMPLE_RATE))
+ const wav = await renderFile(
+ 1,
+ 'mix',
+ report,
+ ids.map((id) => () => stemSource(opts, payload, id)),
+ opts.semitones
+ )
+ const path = await window.stemkit.exportWrite(session.token, null, wav)
+ report(1, 'Saving mix', 1)
+ return path
+ } finally {
+ await window.stemkit.exportEnd(session.token)
+ }
+}
+
+// The original song as one file: pitch only, at full volume, ignoring the mixer.
+export async function exportOriginal(
+ opts: ExportOptions,
+ onProgress?: OnProgress
+): Promise<string | null> {
+ // checked before the picker, so a song without a mix never opens a save dialog
+ const mix = await window.stemkit.getMix(opts.videoId)
+ if (!mix) throw new Error('This song has no original mix to export')
+ const session = await window.stemkit.exportBegin(
+ 'file',
+ originalMixName(opts.title, opts.semitones)
+ )
+ if (!session) return null
+ const report = progress(1, onProgress)
+ try {
+ report(1, 'Preparing', 0)
+ const wav = await renderFile(
+ 1,
+ 'original mix',
+ report,
+ [async () => ({ buffer: await decodeAtExportRate(mix), gain: 1, pan: 0 })],
+ opts.semitones
+ )
+ const path = await window.stemkit.exportWrite(session.token, null, wav)
+ report(1, 'Saving original mix', 1)
+ return path
} finally {
await window.stemkit.exportEnd(session.token)
}
}
export async function exportSeparate(
- opts: ExportOptions & { includeMix: boolean }
+ opts: ExportOptions,
+ onProgress?: OnProgress
): Promise<{ path: string; count: number } | null> {
const ids = chosenStems(opts)
- if (ids.length === 0 && !opts.includeMix) throw new Error('Select at least one stem')
- // checked before the picker: a missing mix found after the stems would
- // leave a half-finished folder behind
- const mix = opts.includeMix ? await window.stemkit.getMix(opts.videoId) : null
- if (opts.includeMix && !mix) throw new Error('This song has no original mix to export')
+ if (ids.length === 0) throw new Error('Select at least one stem')
const session = await window.stemkit.exportBegin(
'folder',
separateFolderName(opts.title, opts.semitones)
)
if (!session) return null
+ const report = progress(ids.length, onProgress)
let count = 0
try {
- const payload = ids.length > 0 ? await window.stemkit.getBuffers(opts.videoId, ids) : {}
+ report(1, 'Preparing', 0)
+ const payload = await window.stemkit.getBuffers(opts.videoId, ids)
// one at a time: every decode and render holds a full-length stereo copy in memory
- for (const id of ids) {
- const channels = await renderOffline([await stemSource(opts, payload, id)], opts.semitones)
- await window.stemkit.exportWrite(session.token, id, encodeWavF32(channels, SAMPLE_RATE))
- count++
- }
- if (mix) {
- // the original mix ignores the mixer: pitch only, at full volume
- const buffer = await decodeAtExportRate(mix)
- const channels = await renderOffline([{ buffer, gain: 1, pan: 0 }], opts.semitones)
- await window.stemkit.exportWrite(session.token, opts.title, encodeWavF32(channels, SAMPLE_RATE))
+ for (const [i, id] of ids.entries()) {
+ const wav = await renderFile(i + 1, id, report, [() => stemSource(opts, payload, id)], opts.semitones)
+ await window.stemkit.exportWrite(session.token, id, wav)
count++
+ report(i + 1, `Saving ${id}`, 1)
}
} finally {
await window.stemkit.exportEnd(session.token)
diff --git a/src/shared/export-rules.ts b/src/shared/export-rules.ts
index 65ac988..72013ca 100644
--- a/src/shared/export-rules.ts
+++ b/src/shared/export-rules.ts
@@ -18,9 +18,9 @@ export function initialSelection(
)
}
-export function canExport(selected: Set<string>, mode: ExportMode): boolean {
- // a mixed file is built from stems only, so the original mix does not count there
- if (mode === 'mixed') return [...selected].some((id) => id !== MIX_ID)
+// The original mix is exclusive: when it is checked, both modes export that one
+// file, so the mode no longer changes what counts.
+export function canExport(selected: Set<string>, _mode: ExportMode): boolean {
return selected.size > 0
}
@@ -58,3 +58,8 @@ export function mixedBaseName(
export function separateFolderName(title: string, semitones: number): string {
return withSuffix(title, shiftSuffix(semitones))
}
+
+// the original song as one file: nothing to list, only the shift tells two exports apart
+export function originalMixName(title: string, semitones: number): string {
+ return withSuffix(title, shiftSuffix(semitones))
+}
diff --git a/tests/export-rules.test.mjs b/tests/export-rules.test.mjs
index 5370989..ab52c1d 100644
--- a/tests/export-rules.test.mjs
+++ b/tests/export-rules.test.mjs
@@ -5,7 +5,8 @@ import {
initialSelection,
canExport,
mixedBaseName,
- separateFolderName
+ separateFolderName,
+ originalMixName
} from '../src/shared/export-rules.ts'
const ALL = ['vocals', 'drums', 'bass', 'other']
@@ -24,11 +25,12 @@ test('initialSelection never includes the mix id', () => {
assert.equal(initialSelection([...ALL, MIX_ID], new Set(), new Set()).has(MIX_ID), false)
})
-test('canExport needs at least one stem; the mix only counts when separate', () => {
- assert.equal(canExport(new Set(), 'mixed'), false)
- assert.equal(canExport(new Set([MIX_ID]), 'mixed'), false)
- assert.equal(canExport(new Set([MIX_ID]), 'separate'), true)
- assert.equal(canExport(new Set(['drums']), 'mixed'), true)
+test('canExport needs the original mix or at least one stem, in either mode', () => {
+ for (const mode of ['mixed', 'separate']) {
+ assert.equal(canExport(new Set(), mode), false)
+ assert.equal(canExport(new Set([MIX_ID]), mode), true)
+ assert.equal(canExport(new Set(['drums']), mode), true)
+ }
})
test('mixedBaseName calls everything-but-vocals "instrumental"', () => {
@@ -68,3 +70,14 @@ test('the suffix survives even with every stem of a 6-stem song checked and a sh
assert.ok(name.length <= 120, `length ${name.length}`)
assert.ok(name.endsWith(' - vocals+drums+bass+guitar+piano+other (-6)'))
})
+
+test('originalMixName is the title plus the shift suffix', () => {
+ assert.equal(originalMixName('Song', 0), 'Song')
+ assert.equal(originalMixName('Song', -3), 'Song (-3)')
+ assert.equal(originalMixName('Song', 2), 'Song (+2)')
+})
+
+test('originalMixName cuts long titles so the shift suffix survives', () => {
+ assert.equal(originalMixName('z'.repeat(200), -3), `${'z'.repeat(115)} (-3)`)
+ assert.equal(originalMixName('z'.repeat(200), 0), 'z'.repeat(120))
+})
diff --git a/tests/exporter.test.mjs b/tests/exporter.test.mjs
index 39bb445..5da02b6 100644
--- a/tests/exporter.test.mjs
+++ b/tests/exporter.test.mjs
@@ -3,14 +3,18 @@ import assert from 'node:assert/strict'
import { registerTsHooks } from './helpers/ts-resolve.mjs'
const hooks = registerTsHooks()
-const { exportMixed, exportSeparate } = await import('../src/renderer/src/lib/exporter.ts')
+const { exportMixed, exportSeparate, exportOriginal, renderOffline } = await import('../src/renderer/src/lib/exporter.ts')
hooks.deregister()
// A minimal Web Audio stand-in: enough for renderOffline at 0 semitones and for
-// decodeAudioData, recording the sample rate each decode ran at.
+// decodeAudioData, recording the sample rate each decode ran at. suspend/resume
+// follow Chromium: one suspend per render quantum, before the end, and the
+// render only goes on after resume().
let log = []
let decoding = 0
let maxConcurrentDecodes = 0
+let lastContext = null
+const QUANTUM = 128
class Node {
connect(n) { return n }
@@ -20,6 +24,24 @@ class FakeOfflineContext {
this.length = length
this.sampleRate = sampleRate
this.destination = new Node()
+ this.suspends = []
+ this.resumes = 0
+ this.rendering = false
+ lastContext = this
+ }
+ suspend(t) {
+ const frame = Math.floor((t * this.sampleRate) / QUANTUM) * QUANTUM
+ if (this.rendering) return Promise.reject(new Error('suspend after start'))
+ if (frame >= this.length) return Promise.reject(new Error('suspend past the end'))
+ if (this.suspends.some((s) => s.frame === frame)) return Promise.reject(new Error('duplicate suspend'))
+ return new Promise((res) => this.suspends.push({ frame, res }))
+ }
+ resume() {
+ this.resumes++
+ const go = this.waiting
+ this.waiting = null
+ go?.()
+ return Promise.resolve()
}
async decodeAudioData(ab) {
const tag = new TextDecoder().decode(new Uint8Array(ab))
@@ -28,12 +50,19 @@ class FakeOfflineContext {
log.push(`decode:${tag}@${this.sampleRate}`)
await new Promise((r) => setTimeout(r, 1))
decoding--
- return { duration: 0.001, tag }
+ // 0.1 s: long enough for the 5% suspend checkpoints to land on distinct quanta
+ return { duration: 0.1, tag }
}
createBufferSource() { return Object.assign(new Node(), { start() {} }) }
createGain() { return Object.assign(new Node(), { gain: { value: 1 } }) }
createStereoPanner() { return Object.assign(new Node(), { pan: { value: 0 } }) }
async startRendering() {
+ this.rendering = true
+ for (const s of [...this.suspends].sort((a, b) => a.frame - b.frame)) {
+ const resumed = new Promise((r) => { this.waiting = r })
+ s.res()
+ await resumed
+ }
const data = [new Float32Array(this.length), new Float32Array(this.length)]
return { getChannelData: (c) => data[c] }
}
@@ -57,8 +86,8 @@ beforeEach(() => {
log.push('getMix')
return mixPayload
},
- exportBegin: async (kind) => {
- log.push(`begin:${kind}`)
+ exportBegin: async (kind, name) => {
+ log.push(`begin:${kind}:${name}`)
return { token: 't', path: '/out' }
},
exportWrite: async (_t, name) => {
@@ -87,29 +116,131 @@ test('exportMixed decodes only the checked stems from the raw payload at 44.1 kH
})
test('exportSeparate decodes one stem at a time, each written before the next decode', async () => {
- await exportSeparate({ ...base, selected: ['drums', 'bass', 'mix'], includeMix: true })
+ await exportSeparate({ ...base, selected: ['drums', 'bass'] })
assert.equal(maxConcurrentDecodes, 1)
const steps = log.filter((l) => l.startsWith('decode:') || l.startsWith('write:'))
assert.deepEqual(steps, [
'decode:drums@44100', 'write:drums',
- 'decode:bass@44100', 'write:bass',
- 'decode:mix@44100', 'write:Song'
+ 'decode:bass@44100', 'write:bass'
+ ])
+})
+
+test('exportSeparate never adds the original mix to the folder', async () => {
+ const result = await exportSeparate({ ...base, selected: ['drums', 'mix'] })
+ assert.equal(log.includes('getMix'), false)
+ assert.deepEqual(log.filter((l) => l.startsWith('write:')), ['write:drums'])
+ assert.equal(result.count, 1)
+})
+
+test('exportOriginal writes the original mix as one file named after the song', async () => {
+ const path = await exportOriginal({ ...base, selected: ['mix'] })
+ assert.equal(path, '/out/x.wav')
+ assert.ok(log.includes('begin:file:Song'), log.join(' '))
+ assert.deepEqual(log.filter((l) => l.startsWith('decode:') || l.startsWith('write:')), [
+ 'decode:mix@44100', 'write:null'
])
+ // the stems are never fetched for the original mix
+ assert.equal(log.some((l) => l.startsWith('getBuffers')), false)
})
-test('exportSeparate with a missing original mix fails before opening a session or writing', async () => {
+test('exportOriginal with a missing original mix fails before opening a session or writing', async () => {
mixPayload = null
- await assert.rejects(
- exportSeparate({ ...base, selected: ['drums', 'mix'], includeMix: true }),
- /no original mix/i
- )
+ await assert.rejects(exportOriginal({ ...base, selected: ['mix'] }), /no original mix/i)
assert.equal(log.some((l) => l.startsWith('begin') || l.startsWith('write')), false)
})
+test('exportOriginal checks the mix before the picker', async () => {
+ await exportOriginal({ ...base, selected: ['mix'] })
+ assert.ok(log.indexOf('getMix') < log.findIndex((l) => l.startsWith('begin')), log.join(' '))
+})
+
test('exports only fetch the raw bytes of the checked stems', async () => {
await exportMixed({ ...base, selected: ['bass', 'drums'] })
assert.ok(log.includes('getBuffers:bass,drums'), log.join(' '))
log = []
- await exportSeparate({ ...base, selected: ['other'], includeMix: false })
+ await exportSeparate({ ...base, selected: ['other'] })
assert.ok(log.includes('getBuffers:other'), log.join(' '))
})
+
+const isMonotonic = (xs) => xs.every((x, i) => i === 0 || x >= xs[i - 1])
+
+test('renderOffline reports render progress from suspend checkpoints, ending at 1', async () => {
+ const fractions = []
+ const buffer = { duration: 1 }
+ await renderOffline([{ buffer, gain: 1, pan: 0 }], 0, undefined, (f) => fractions.push(f))
+ // 19 checkpoints (5%..95%) plus the end
+ assert.equal(lastContext.suspends.length, 19)
+ assert.equal(lastContext.resumes, 19)
+ assert.ok(lastContext.suspends.every((s) => s.frame % QUANTUM === 0 && s.frame > 0))
+ assert.equal(fractions.length, 20)
+ assert.ok(isMonotonic(fractions), fractions.join(' '))
+ assert.ok(fractions[0] > 0.04 && fractions[0] <= 0.05, String(fractions[0]))
+ assert.equal(fractions.at(-1), 1)
+})
+
+test('renderOffline skips checkpoints that would share a render quantum', async () => {
+ const fractions = []
+ // 300 frames: 5% steps of 15 frames collapse onto quanta 128 and 256, and
+ // 256 is dropped because its quantum runs past the end
+ await renderOffline([{ buffer: { duration: 300 / 44100 }, gain: 1, pan: 0 }], 0, undefined, (f) => fractions.push(f))
+ assert.deepEqual(lastContext.suspends.map((s) => s.frame), [128])
+ assert.ok(isMonotonic(fractions))
+ assert.equal(fractions.at(-1), 1)
+})
+
+test('renderOffline still finishes when the progress callback throws', async () => {
+ const out = await renderOffline([{ buffer: { duration: 0.1 }, gain: 1, pan: 0 }], 0, undefined, (f) => {
+ if (f < 1) throw new Error('boom')
+ })
+ assert.equal(out[0].length, 4410)
+ assert.equal(lastContext.resumes, lastContext.suspends.length)
+})
+
+test('renderOffline without a progress callback schedules no suspends', async () => {
+ await renderOffline([{ buffer: { duration: 1 }, gain: 1, pan: 0 }], 0)
+ assert.equal(lastContext.suspends.length, 0)
+})
+
+test('exportMixed reports one step whose fraction climbs to 1', async () => {
+ const events = []
+ await exportMixed({ ...base, selected: ['bass', 'drums'] }, (p) => events.push(p))
+ assert.ok(events.length > 5, String(events.length))
+ assert.ok(events.every((p) => p.step === 1 && p.steps === 1))
+ assert.ok(isMonotonic(events.map((p) => p.fraction)))
+ assert.equal(events.at(-1).fraction, 1)
+ const labels = new Set(events.map((p) => p.label))
+ assert.ok(labels.has('Rendering mix') && labels.has('Saving mix'), [...labels].join(','))
+ // rendering spans 10%..90% of the file
+ const rendering = events.filter((p) => p.label === 'Rendering mix').map((p) => p.fraction)
+ assert.ok(Math.max(...rendering) <= 0.9 + 1e-9 && rendering.some((f) => f > 0.5))
+})
+
+test('exportSeparate reports one step per stem, split evenly across the total', async () => {
+ const events = []
+ await exportSeparate({ ...base, selected: ['drums', 'bass'] }, (p) => events.push(p))
+ assert.ok(events.every((p) => p.steps === 2))
+ assert.ok(isMonotonic(events.map((p) => p.fraction)))
+ assert.ok(isMonotonic(events.map((p) => p.step)))
+ assert.equal(events.at(-1).fraction, 1)
+ const firstBass = events.find((p) => p.label === 'Rendering bass')
+ assert.equal(firstBass.step, 2)
+ assert.ok(firstBass.fraction >= 0.5, String(firstBass.fraction))
+ const order = [...new Set(events.map((p) => p.label))].filter((l) => l !== 'Preparing')
+ assert.deepEqual(order, ['Rendering drums', 'Saving drums', 'Rendering bass', 'Saving bass'])
+})
+
+test('exportOriginal reports the original mix as one step', async () => {
+ const events = []
+ await exportOriginal({ ...base, selected: ['mix'] }, (p) => events.push(p))
+ assert.ok(events.every((p) => p.step === 1 && p.steps === 1))
+ assert.ok(events.some((p) => p.label === 'Rendering original mix'))
+ assert.ok(isMonotonic(events.map((p) => p.fraction)))
+ assert.equal(events.at(-1).fraction, 1)
+})
+
+test('a cancelled picker reports no progress', async () => {
+ window.stemkit.exportBegin = async () => null
+ const events = []
+ assert.equal(await exportMixed({ ...base, selected: ['drums'] }, (p) => events.push(p)), null)
+ assert.equal(events.length, 0)
+})