Skip to content

Suno-style web UI for a self-hosted MiniMax-Music3 inference server

feat: real progress on every render when the server streams; audio windows only with Play-while-rendering

Adam Benhassen8f4a8f0a56aa
diff --git a/README.md b/README.md
index 1a8bf9e..7a9d174 100644
--- a/README.md
+++ b/README.md
@@ -25,7 +25,7 @@
- **Create panel** — Simple or Custom mode, song title (random name like “Velvet Horizon” if left empty), style description, lyrics editor with `[Verse]` / `[Chorus]` / … tag chips, instrumental toggle, duration 5–360 s, 1–4 takes per submit (each take gets `seed + i`), advanced seed. Output is WAV, as the official route documents.
- **Templates** — a built-in default plus your own saved templates (style, lyrics, duration), stored server-side.
- **Render queue** — the UI server renders one track at a time against the blocking `/v1/audio/speech` route and shows queued / rendering / done with elapsed time and an estimated bar (~3× realtime — the official API reports no progress). Cancel while queued or rendering, retry on error.
-- **Live progress + play while rendering** — when the server is the bundled `inference/server.py` (it advertises `capabilities: ["stream"]` on `/health`), the UI streams real progress (Generating → Rendering, seconds rendered, ETA from the measured rate) and lets you press play on a track that is still rendering; the player buffers when it catches up with the renderer and swaps to the final file seamlessly. Stock `sgl-omni` keeps the estimated bar.
+- **Live progress + play while rendering** — when the server is the bundled `inference/server.py` (it advertises `capabilities: ["stream"]` on `/health`), progress is real for every render (Generating → Rendering, ETA from the measured rate). Tick *Play while rendering* under Advanced and the audio is streamed as it's rendered too: press play on a track that is still rendering, the player buffers when it catches up with the renderer and swaps to the final file seamlessly. Stock `sgl-omni` keeps the estimated bar.
- **Library** — every finished render is saved into `data/tracks/` with its metadata (prompt, lyrics, seed, format). Search, download, delete, "reuse settings".
- **Player** — sticky bottom bar with waveform (decoded client-side), seek, prev/next, keyboard space to play/pause.
- **Health pill** — offline / loading model / idle (· live progress) / rendering · N queued (probes `GET /v1/models` and the optional `GET /health`).
diff --git a/inference/README.md b/inference/README.md
index 2c1580a..43bd98a 100644
--- a/inference/README.md
+++ b/inference/README.md
@@ -24,7 +24,7 @@ If the Hub asks you to accept the model's terms, do that on the model page and l
| Route | |
|---|---|
| `POST /v1/audio/speech` | `{model, input (lyrics), instructions (style), response_format: "wav", seed?, max_new_tokens (25 fps frames, ≤ 9000), stream: false}` → 44.1 kHz stereo 16-bit WAV, seed used in `X-Seed` |
-| `POST /v1/audio/speech` + `stream: true` | *this server only* — `text/event-stream`: `progress {stage: semantic\|denoise, done, total, secondsRendered}`, `audio {pcm (base64 int16 stereo), samples, sampleRate, channels}` per denoised ~8 s window, then `done {seed}` or `error {message}`; disconnecting cancels the render |
+| `POST /v1/audio/speech` + `stream: true` | *this server only* — `text/event-stream`: `progress {stage: semantic\|denoise, done, total, secondsRendered}`, `audio {pcm (base64 int16 stereo), samples, sampleRate, channels}` per denoised ~8 s window (add `stream_audio: false` for progress only — the clip then arrives in one `audio` event at the end), then `done {seed}` or `error {message}`; disconnecting cancels the render |
| `GET /v1/models` | the one model (`minimax_ttm`) |
| `GET /health` | `200 {"status":"ready","capabilities":["stream"]}` once loaded, 503 while loading |
diff --git a/inference/server.py b/inference/server.py
index 8c19151..25739a6 100644
--- a/inference/server.py
+++ b/inference/server.py
@@ -16,8 +16,9 @@ which fits on one card (~24 GB), so a client written against either works agains
POST /v1/audio/speech with "stream": true (this server only; upstream rejects it)
-> text/event-stream: `progress` {stage: semantic|denoise, done, total, secondsRendered},
- `audio` {pcm: base64 int16 stereo, samples, sampleRate, channels} per denoised window,
- then `done` {seed, sampleRate, channels} or `error` {message}. Disconnecting cancels the job.
+ `audio` {pcm: base64 int16 stereo, samples, sampleRate, channels} per denoised window
+ (or once at the end when "stream_audio": false), then `done` {seed, sampleRate, channels}
+ or `error` {message}. Disconnecting cancels the job.
GET /v1/models -> the one model
GET /health -> 200 {"status":"ready","capabilities":["stream"]} once loaded, 503 while loading
@@ -120,7 +121,7 @@ def _install_progress_hooks(pipe):
job = CURRENT["job"]
_check_cancel(job)
components, block_state = orig_loop_step(self, components, block_state, k=k)
- if job is not None and job["events"] is not None:
+ if job is not None and job["events"] is not None and job["stream_audio"]:
latents = block_state.latent_chunks[-1]
last = k == len(block_state.chunk_starts) - 1
hop = components.latent_hop_length
@@ -152,6 +153,7 @@ class SpeechRequest(BaseModel):
None, description="Length in 25 fps frames: 750 = 30 s, cap 9000 = 360 s. Default 1500 = 60 s."
)
stream: bool = Field(False, description="true (this server only) streams SSE progress + PCM windows; upstream accepts only false.")
+ stream_audio: bool = Field(True, description="With stream=true: false skips per-window audio events (progress only; the clip arrives in one `audio` event at the end).")
def _worker():
@@ -199,7 +201,7 @@ def _worker():
)[0]
if hasattr(audio, "cpu"): # some builds return a tensor, others a numpy array
audio = audio.float().cpu().numpy()
- if job["events"] is not None and not job["pcm"]: # hooks missing: ship the whole clip in one event
+ if job["events"] is not None and not job["pcm"]: # progress-only stream, or hooks missing: whole clip in one event
pcm = (audio.T * 32767.0).astype("<i2").tobytes()
_emit(job, "audio", {"pcm": base64.b64encode(pcm).decode("ascii"), "samples": int(audio.shape[-1]),
"sampleRate": int(PIPE.sampling_rate), "channels": int(audio.shape[0])})
@@ -267,6 +269,7 @@ def speech(req: SpeechRequest, authorization: str = Header(None), x_api_key: str
"error": None,
"event": threading.Event(),
"events": queue.Queue() if req.stream else None,
+ "stream_audio": bool(req.stream_audio),
"cancelled": False,
"frames": 0,
"max_frames": frames,
diff --git a/server/src/upstream.ts b/server/src/upstream.ts
index b6b7d34..8ac198f 100644
--- a/server/src/upstream.ts
+++ b/server/src/upstream.ts
@@ -129,7 +129,7 @@ export class UpstreamClient {
}
}
- private async post(body: SpeechBody, stream: boolean, signal?: AbortSignal): Promise<Response> {
+ private async post(body: SpeechBody, stream: boolean, signal?: AbortSignal, extra: Record<string, unknown> = {}): Promise<Response> {
await this.ensureProbed();
const payload = {
model: this.model,
@@ -139,6 +139,7 @@ export class UpstreamClient {
max_new_tokens: Math.min(MAX_FRAMES, Math.max(1, Math.round(body.duration * FRAMES_PER_SECOND))),
stream,
...(body.seed !== null ? { seed: body.seed } : {}),
+ ...extra,
};
let res: Response;
try {
@@ -173,9 +174,12 @@ export class UpstreamClient {
return { seed: UpstreamClient.seedOf(res) };
}
- /** stream:true variant (only when `canStream`): SSE with progress + PCM windows, assembled into a WAV at `dest`. */
- async speechStream(body: SpeechBody, dest: string, onEvent: (e: StreamEvent) => void, signal?: AbortSignal): Promise<{ seed: number | null }> {
- const res = await this.post(body, true, signal);
+ /**
+ * stream:true variant (only when `canStream`): SSE with progress + PCM windows, assembled into a WAV at `dest`.
+ * `audio: false` asks for progress only (`stream_audio: false`); the clip then arrives in one event at the end.
+ */
+ async speechStream(body: SpeechBody, dest: string, onEvent: (e: StreamEvent) => void, signal?: AbortSignal, opts: { audio?: boolean } = {}): Promise<{ seed: number | null }> {
+ const res = await this.post(body, true, signal, opts.audio === false ? { stream_audio: false } : {});
if (!(res.headers.get('content-type') ?? '').includes('text/event-stream') || !res.body) {
throw new UpstreamError(`upstream did not stream (content-type ${res.headers.get('content-type') ?? 'none'})`, res.status);
}
@@ -270,8 +274,9 @@ export class RenderQueue {
const startedAt = Date.now();
const est = Math.max(5, track.duration * REALTIME_FACTOR);
await this.client.ensureProbed();
- const streaming = track.stream && this.client.canStream;
- await this.library.update(id, { status: 'running', stage: streaming ? 'semantic' : 'rendering', progress: 0, eta: est, elapsed: 0, renderedSeconds: streaming ? 0 : null });
+ const streaming = this.client.canStream; // real progress whenever the upstream offers it
+ const audioWindows = streaming && track.stream; // early playback is opt-in per track
+ await this.library.update(id, { status: 'running', stage: streaming ? 'semantic' : 'rendering', progress: 0, eta: est, elapsed: 0, renderedSeconds: audioWindows ? 0 : null });
const rel = `${id}.${extFor(track.format)}`;
const dest = path.join(this.tracksDir, rel);
@@ -282,9 +287,10 @@ export class RenderQueue {
const onEvent = (e: StreamEvent) => {
if (e.type === 'progress') {
const part = e.total > 0 ? Math.min(1, e.done / e.total) : 0;
+ const stageChanged = e.stage !== stage;
stage = e.stage;
frac = stage === 'semantic' ? 0.35 * part : 0.35 + 0.65 * part;
- if (Date.now() - lastWrite < 250) return; // throttle store writes; audio events always write
+ if (!stageChanged && Date.now() - lastWrite < 250) return; // throttle store writes; stage changes and audio always write
} else {
rendered = e.secondsRendered;
}
@@ -292,7 +298,8 @@ export class RenderQueue {
const elapsed = elapsedS();
const eta = frac > 0.02 ? Math.max(0, elapsed / frac - elapsed) : Math.max(0, est - elapsed);
const patch: Partial<Track> = { stage, progress: Math.min(0.99, frac), eta, elapsed, renderedSeconds: rendered };
- if (rendered > 0 && !fileKnown) { fileKnown = true; patch.file = rel; }
+ if (!audioWindows) patch.renderedSeconds = null; // whole clip arrives at the end; nothing to play early
+ else if (rendered > 0 && !fileKnown) { fileKnown = true; patch.file = rel; }
void this.library.update(id, patch);
};
@@ -305,7 +312,7 @@ export class RenderQueue {
try {
const body = { prompt: track.prompt, lyrics: track.lyrics, duration: track.duration, seed: track.seed, format: track.format };
const { seed } = streaming
- ? await this.client.speechStream(body, dest, onEvent, ac.signal)
+ ? await this.client.speechStream(body, dest, onEvent, ac.signal, { audio: audioWindows })
: await this.client.speechToFile(body, dest, ac.signal);
clearInterval(timer);
await this.library.update(id, {
@@ -313,7 +320,7 @@ export class RenderQueue {
elapsed: elapsedS(),
seed: seed ?? track.seed,
file: rel,
- renderedSeconds: streaming ? rendered : null,
+ renderedSeconds: audioWindows ? rendered : null,
finishedAt: new Date().toISOString(),
});
} catch (err) {
diff --git a/server/test/app.test.ts b/server/test/app.test.ts
index 2e1423b..50f5f99 100644
--- a/server/test/app.test.ts
+++ b/server/test/app.test.ts
@@ -245,12 +245,21 @@ describe('app', () => {
expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: true });
});
- it('streaming is opt-in: without stream:true the blocking path is used even when advertised', async () => {
- const { app, lib } = await setup({ stream: { windows: 2 } });
+ it('without the per-track stream flag: progress is still real over SSE (stream_audio:false), no early audio, valid WAV', async () => {
+ const { app, lib, tracksDir } = await setup({ stream: { windows: 3, secondsPerWindow: 0.1, windowMs: 40 } });
const res = await request(app).post('/api/generate').send({ prompt: 'x' });
- await until(() => lib.get(res.body[0].id)?.status === 'done');
- expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: false });
- expect(lib.get(res.body[0].id)?.renderedSeconds).toBeNull();
+ const id = res.body[0].id as string;
+ await until(() => lib.get(id)?.stage === 'denoise');
+ expect(lib.get(id)?.renderedSeconds).toBeNull();
+ expect(lib.get(id)?.file).toBeNull();
+ await until(() => lib.get(id)?.status === 'done');
+ const t = lib.get(id)!;
+ expect(t.renderedSeconds).toBeNull();
+ expect(t.progress).toBe(1);
+ const wav = await fs.readFile(path.join(tracksDir, t.file!));
+ expect(wav.length).toBe(44 + Math.round(0.1 * 44100) * 4 * 3);
+ expect(wav.readUInt32LE(40)).toBe(wav.length - 44);
+ expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: true, stream_audio: false });
});
it('never sends stream:true to servers that do not advertise it', async () => {
diff --git a/server/test/fakeUpstream.ts b/server/test/fakeUpstream.ts
index f37fa29..4545a9e 100644
--- a/server/test/fakeUpstream.ts
+++ b/server/test/fakeUpstream.ts
@@ -69,6 +69,7 @@ export async function startFakeUpstream(opts: FakeUpstreamOptions = {}): Promise
res.flushHeaders();
entry.stream = true;
const frames = Number(b.max_new_tokens ?? 1500);
+ const audioWindows = b.stream_audio !== false;
let step = 0; let seconds = 0;
const timer = setInterval(() => {
if (res.destroyed) return clearInterval(timer);
@@ -76,10 +77,16 @@ export async function startFakeUpstream(opts: FakeUpstreamOptions = {}): Promise
else if (step - 2 < s.windows) {
const k = step - 2;
send('progress', { stage: 'denoise', done: k * 30 + 30, total: s.windows * 30, secondsRendered: seconds });
- const pcm = sinePcm(per, sr, 220 * (k + 1));
seconds += per;
- send('audio', { pcm: pcm.toString('base64'), samples: pcm.length / 4, sampleRate: sr, channels: 2 });
+ if (audioWindows) {
+ const pcm = sinePcm(per, sr, 220 * (k + 1));
+ send('audio', { pcm: pcm.toString('base64'), samples: pcm.length / 4, sampleRate: sr, channels: 2 });
+ }
} else {
+ if (!audioWindows) {
+ const pcm = Buffer.concat(Array.from({ length: s.windows }, (_, k) => sinePcm(per, sr, 220 * (k + 1))));
+ send('audio', { pcm: pcm.toString('base64'), samples: pcm.length / 4, sampleRate: sr, channels: 2 });
+ }
send('done', { seed: Number(b.seed ?? 4242), sampleRate: sr, channels: 2 });
clearInterval(timer);
res.end();
diff --git a/web/src/components/CreatePanel.tsx b/web/src/components/CreatePanel.tsx
index c258d0f..d3eac4b 100644
--- a/web/src/components/CreatePanel.tsx
+++ b/web/src/components/CreatePanel.tsx
@@ -29,7 +29,7 @@ export interface FormState {
takes: number;
seed: string;
format: string;
- /** stream live progress + audio while rendering (needs a server that advertises it) */
+ /** stream audio while rendering so the track can be played before it finishes (needs a server that advertises it) */
stream: boolean;
}
@@ -207,11 +207,11 @@ export function CreatePanel({ health, form, onFormChange, onSubmit }: Props) {
{FORMAT_OPTIONS.map((f) => <option key={f.value} value={f.value} disabled={f.disabled}>{f.label}</option>)}
</select>
</div>
- <label className={`col-span-2 flex items-start gap-2 text-xs ${canStream ? 'text-zinc-300 cursor-pointer' : 'text-zinc-500'}`} title={canStream ? undefined : 'This server does not advertise streaming (stock sgl-omni); progress will be estimated'}>
+ <label className={`col-span-2 flex items-start gap-2 text-xs ${canStream ? 'text-zinc-300 cursor-pointer' : 'text-zinc-500'}`} title={canStream ? undefined : 'This server does not advertise streaming (stock sgl-omni)'}>
<input type="checkbox" className="mt-0.5 accent-accent" checked={form.stream && canStream} disabled={!canStream} onChange={(e) => set('stream', e.target.checked)} />
<span>
- Stream while rendering
- <span className="block text-[10px] text-zinc-500">Live progress and play-before-finished{canStream ? '' : ' — not offered by this server'}</span>
+ Play while rendering
+ <span className="block text-[10px] text-zinc-500">Streams audio as it's rendered so you can listen early; costs a little extra GPU time{canStream ? '' : ' — not offered by this server'}</span>
</span>
</label>
</div>
diff --git a/web/src/types.ts b/web/src/types.ts
index 1216ffb..9cae868 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -16,7 +16,7 @@ export interface Track {
stage: string;
eta: number | null;
elapsed?: number | null;
- /** opt-in per track: stream live progress + audio when the server supports it */
+ /** opt-in per track: stream audio windows for play-while-rendering (progress is live regardless when the server supports it) */
stream: boolean;
/** seconds of audio on disk while a streamed render is running; null when the server can't stream */
renderedSeconds: number | null;
@@ -74,5 +74,5 @@ export interface SettingsTestResult {
}
export const isInflight = (t: Track) => t.status === 'queued' || t.status === 'running';
-/** done, or rendering — pressing play on a rendering track arms it and playback starts when audio arrives */
-export const isPlayable = (t: Track) => t.status === 'done' || t.status === 'running';
+/** done, or rendering with early audio enabled — play arms it and playback starts when audio arrives */
+export const isPlayable = (t: Track) => t.status === 'done' || (t.status === 'running' && t.stream);