Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
881ccca
cuda: a process-wide cap on DeviceBuffer and pinned HostBuffer bytes
plotarmordev Oct 16, 2026
b00dd4e
drama: the temporal codebook tower
plotarmordev Oct 16, 2026
c8af505
drama: the speech codec, with codec.pth read without Python
plotarmordev Oct 16, 2026
e192c0f
engine_api: speech requests, speech info and a submit_speech hook
plotarmordev Oct 16, 2026
ab45904
native: Drama 3 (fish_omni) on CUDA
plotarmordev Oct 16, 2026
7553d00
server: POST /v1/audio/speech
plotarmordev Oct 16, 2026
8ba4307
tests: Drama 3 backbone and tower oracles, replays and stage traces
plotarmordev Oct 16, 2026
20249e9
drama: incremental codec decode, bit-identical to the whole decode
plotarmordev Oct 16, 2026
93fcaab
tests: Drama 3 codec oracle, replays and stage trace
plotarmordev Oct 16, 2026
d84284d
engine_api: audio events, so a speech engine can publish PCM while it…
plotarmordev Oct 16, 2026
71c31a9
build: Drama 3 backbone and tower kernels, the drama module, the nati…
plotarmordev Oct 16, 2026
588f1f1
server: stream: true on /v1/audio/speech sends raw PCM chunks as they…
plotarmordev Oct 16, 2026
d8c6a47
drama: the backbone's one-row GEMM stages its weights through shared …
plotarmordev Oct 16, 2026
10796d4
build: the Drama 3 codec kernels and the codec tool steps
plotarmordev Oct 16, 2026
8bc6814
tests: tf-drama-codec-stream-oracle, whole against chunked codec decodes
plotarmordev Oct 16, 2026
40c7c87
core: a direct read the file system refuses goes through the page cache
plotarmordev Oct 16, 2026
23a7fcc
cuda: Module.holds, whether a loaded image defines a device global
plotarmordev Oct 16, 2026
6f85731
drama: the Drama 3 text backbone on CUDA
plotarmordev Oct 16, 2026
05a715f
drama: one-row backbone GEMVs stream weights through a swizzled cp.as…
plotarmordev Oct 16, 2026
9dc8202
drama: add-norm fused with the routed experts' FP8 activation quantiz…
plotarmordev Oct 16, 2026
705541c
drama: one SwiGLU launch for the routed and shared experts
plotarmordev Oct 16, 2026
08291b5
drama: MoE combine on 8-wide vectors
plotarmordev Oct 16, 2026
641b18b
drama: decode attention keeps the next keys' loads in flight
plotarmordev Oct 16, 2026
01b7f3b
drama: the tower's one decode row attends as a thread-block cluster
plotarmordev Oct 16, 2026
b89dc67
drama: checkpoint weights stream onto the GPU with direct I/O in file…
plotarmordev Oct 16, 2026
0f9345e
speech: a Drama 3 reply that reaches max_frames returns its clipped a…
plotarmordev Oct 16, 2026
9b3934c
drama: one-row attention runs its Q/K norm and RoPE prologue in the s…
plotarmordev Oct 16, 2026
ea06b8b
drama: the tower samples with a stable radix sort
plotarmordev Oct 16, 2026
68aeb3e
drama: the codec builds its weights on its own thread while the backb…
plotarmordev Oct 16, 2026
2757724
drama: the tower's one-row projections on drama_tower_gemv, in cuBLAS…
plotarmordev Oct 16, 2026
bef432b
drama: the backbone chain launches with programmatic dependent launch
plotarmordev Oct 16, 2026
fdee05c
Merge upstream main (6ee828c2) into feat/drama3-cuda
plotarmordev Oct 17, 2026
0f81a2b
Merge align/920-merge-main (upstream main 6ee828c2) into feat/drama3-…
plotarmordev Oct 17, 2026
15bceca
Merge align/921-merge-main (upstream main 6ee828c2) into fix/drama3-c…
plotarmordev Oct 17, 2026
64e8ff8
Merge align/922-merge-main (upstream main 6ee828c2) into perf/drama3-…
plotarmordev Oct 17, 2026
2d9232a
Merge align/923-merge-main (upstream main 6ee828c2) into perf/drama3-…
plotarmordev Oct 17, 2026
42c548c
Merge align/924-merge-main (upstream main 6ee828c2) into perf/drama3-…
plotarmordev Oct 17, 2026
96f2b38
Merge align/925-merge-main (upstream main 6ee828c2) into perf/drama3-…
plotarmordev Oct 17, 2026
7c9fd59
Merge align/926-merge-main (upstream main 6ee828c2) into perf/drama3-pdl
plotarmordev Oct 17, 2026
b56fc8c
drama: below sm_90 the tower's decode row runs drama_attention, and i…
plotarmordev Oct 17, 2026
996637c
Merge align/924-merge-main into perf/drama3-load: the tower's sm_90 c…
plotarmordev Oct 17, 2026
bc31ec2
Merge align/926-merge-main into perf/drama3-pdl: the tower's sm_90 cl…
plotarmordev Oct 17, 2026
4d3c4f5
Merge align/925-merge-main into perf/drama3-tower-gemv: the tower's s…
plotarmordev Oct 17, 2026
2d62476
CHANGELOG: the tower's cluster decode attention runs from sm_90 on, t…
plotarmordev Oct 17, 2026
65cd256
engine_api and native/cuda.zig back under 600 lines: speech and visio…
plotarmordev Oct 17, 2026
f5aa7a5
Merge align/920-merge-main into feat/drama3-streaming: speech and vis…
plotarmordev Oct 17, 2026
fd87532
Merge align/921-merge-main into fix/drama3-clipped-replies: speech an…
plotarmordev Oct 17, 2026
572afe3
Merge align/922-merge-main into perf/drama3-backbone-one-row: speech …
plotarmordev Oct 17, 2026
1ecf53b
Merge align/923-merge-main into perf/drama3-tower-decode: speech and …
plotarmordev Oct 17, 2026
bd11ba4
Merge align/924-merge-main into perf/drama3-load: speech and vision t…
plotarmordev Oct 17, 2026
f495030
Merge align/925-merge-main into perf/drama3-tower-gemv: speech and vi…
plotarmordev Oct 17, 2026
f64f02d
Merge align/926-merge-main into perf/drama3-pdl: speech and vision ty…
plotarmordev Oct 17, 2026
118086a
core: lane tests ignore the speech audio event
plotarmordev Oct 17, 2026
4d41f5a
Merge align/921-merge-main into fix/drama3-clipped-replies: lane test…
plotarmordev Oct 17, 2026
2b27b19
Merge align/922-merge-main into perf/drama3-backbone-one-row: lane te…
plotarmordev Oct 17, 2026
e45d71b
Merge align/923-merge-main into perf/drama3-tower-decode: lane tests …
plotarmordev Oct 17, 2026
809e103
Merge align/924-merge-main into perf/drama3-load: lane tests ignore t…
plotarmordev Oct 17, 2026
0ed8946
Merge align/925-merge-main into perf/drama3-tower-gemv: lane tests ig…
plotarmordev Oct 17, 2026
d986914
Merge align/926-merge-main into perf/drama3-pdl: lane tests ignore th…
plotarmordev Oct 17, 2026
9d6a54c
drama: backbone attention runs the reference's 64-key softmax tiles
plotarmordev Oct 17, 2026
d2734fd
Merge align/927-merge-main into align/attention-tiles: lane tests ign…
plotarmordev Oct 17, 2026
391c64c
changelog: drop the attention tiles' speed sentence, no change measur…
plotarmordev Oct 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
server: stream: true on /v1/audio/speech sends raw PCM chunks as they…
… are decoded

With stream: true and response_format pcm, the route sends HTTP/1.1 chunks as the engine publishes audio. A stream
that fails after its first chunk ends without a terminator, so a client cannot mistake it for complete audio.
  • Loading branch information
plotarmordev committed Oct 16, 2026
commit 588f1f1d4df80b27a26d2a0da322427957018f03
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](RELEASE-NOTES-1.0.0.md) for the native binary's supported models and migration details.

## Unreleased

- speech: `stream: true` with `response_format: pcm` streams HTTP/1.1 chunks while Drama 3 generates; incremental codec decode bit-identical to the whole decode (oracle-gated)

## 1.0.11

- `--cortheon`'s instruction filter keeps reading past a long word. A word longer than the filter's scan buffer ended the scan early, so an order written after one was never checked; each word now keeps at most 16 bytes, so a long word can no longer end the scan (#829). Thanks to @joeynyc.
Expand Down
1 change: 1 addition & 0 deletions zig/src/server/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ test {
_ = @import("chunk_plan.zig");
_ = @import("status_routes.zig");
_ = @import("speech.zig");
_ = @import("speech_stream_test.zig");
_ = @import("drama_prompt.zig");
_ = @import("memory_routes.zig");
_ = @import("process_memory.zig");
Expand Down
165 changes: 132 additions & 33 deletions zig/src/server/speech.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! POST /v1/audio/speech: synthesized whole and sent as WAV or raw PCM; anything but complete audio is an error.
//! POST /v1/audio/speech: WAV or raw PCM whole, or raw PCM chunks with stream; only complete synthesis is audio.
const std = @import("std");
const api = @import("engine_api");
const json = @import("json.zig");
Expand All @@ -22,11 +22,11 @@ const Allocator = std.mem.Allocator;
/// ``MAX_SPEECH_INPUT_CHARS``: the most characters (code points) one input may hold.
pub const max_input_chars = 4096;

/// The request fields served: the OpenAI ones (``speaker`` is ``voice``'s alias).
/// The request fields served: the OpenAI ones (``speaker`` is ``voice``'s alias); ``stream*`` are checked apart.
const served_fields = [_][]const u8{ "model", "input", "voice", "speaker", "response_format" };

/// The rest of the speech protocol's fields: synthesis modifiers, references and streaming this route does not honor.
const modifier_fields = [_][]const u8{ "speed", "stream", "stream_format", "task_type", "language", "instructions", "ref_audio", "ref_text", "references", "x_vector_only_mode", "stream_codec_output", "suppress_bootstrap_silence", "token_count", "duration_tokens", "initial_codec_chunk_frames", "max_new_tokens", "temperature", "top_p", "top_k", "repetition_penalty", "seed", "stage_params" };
/// The rest of the speech protocol's fields: synthesis modifiers and references this route does not honor.
const modifier_fields = [_][]const u8{ "speed", "task_type", "language", "instructions", "ref_audio", "ref_text", "references", "x_vector_only_mode", "stream_codec_output", "suppress_bootstrap_silence", "token_count", "duration_tokens", "initial_codec_chunk_frames", "max_new_tokens", "temperature", "top_p", "top_k", "repetition_penalty", "seed", "stage_params" };

pub const Format = enum {
wav,
Expand All @@ -40,7 +40,7 @@ pub const Format = enum {
}
};

const Plan = struct { prompt: []const u32, seed: u64, format: Format };
const Plan = struct { prompt: []const u32, seed: u64, format: Format, stream: bool };

pub fn post(srv: *Server, c: *Conn, a: Allocator) !void {
const sp = srv.info.speech orelse {
Expand All @@ -52,6 +52,8 @@ pub fn post(srv: *Server, c: *Conn, a: Allocator) !void {
const received = clock.nowNs(srv.io);
const raw = http_body.readJson(c, &cx) catch |e| return refuse(c, &cx, id, e);
const plan = prepare(srv, &cx, sp, raw) catch |e| return refuse(c, &cx, id, e);
// only chunked framing tells a client that a stream which ends early is incomplete
if (plan.stream and !std.mem.eql(u8, c.version, "HTTP/1.1")) return fail(c, &cx, id, .request, "stream=true requires HTTP/1.1");
synthesize(srv, c, &cx, id, sp, plan, received);
}

Expand All @@ -60,11 +62,17 @@ fn listed(names: []const []const u8, key: []const u8) bool {
return false;
}

/// Refuses what the route would drop: unknown fields even when null, set modifiers, non-string served fields.
/// Refuses what this route would drop: unknown fields, set modifiers, non-strings, a bad ``stream``/``stream_format``.
fn checkFields(cx: *Cx, body: Value) errors.Refused!void {
for (body.object.keys(), body.object.values()) |key, value| {
if (listed(&served_fields, key)) {
if (value != .string) return cx.fail(.request, "{s} must be a string", .{key});
} else if (std.mem.eql(u8, key, "stream")) {
if (value != .bool and value != .null) return cx.refuse("stream must be a boolean");
} else if (std.mem.eql(u8, key, "stream_format")) {
if (value == .null or (value == .string and std.mem.eql(u8, value.string, "audio"))) continue;
if (value == .string and std.mem.eql(u8, value.string, "sse")) return cx.refuse("stream_format sse is not supported by this model");
return cx.refuse("stream_format must be one of: audio, sse");
} else if (listed(&modifier_fields, key)) {
if (value != .null) return cx.fail(.request, "{s} is not supported by this model", .{key});
} else return cx.fail(.request, "unknown speech request field: {s}", .{key});
Expand Down Expand Up @@ -92,6 +100,8 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused
if ((std.unicode.utf8CountCodepoints(input) catch unreachable) > max_input_chars)
return cx.fail(.request, "input must be at most {d} characters", .{max_input_chars});
const format = try responseFormat(cx, raw.strField("response_format") orelse "wav");
const stream = if (raw.get("stream")) |s| s == .bool and s.bool else false;
if (stream and format != .pcm) return cx.refuse("stream=true requires response_format='pcm'");
const voice = raw.strField("voice") orelse raw.strField("speaker") orelse "default";
if (voice.len > 0 and !std.ascii.eqlIgnoreCase(voice, "default"))
return cx.fail(.request, drama_prompt.error_prefix ++ " unknown voice {s}; only the default voice is supported", .{try pyrepr.repr(cx.a, .{ .string = voice })});
Expand All @@ -102,10 +112,10 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused
};
if (prompt.len > sp.max_prompt_tokens)
return cx.fail(.request, drama_prompt.error_prefix ++ " a prompt of {d} rows exceeds the maximum allowed length of {d} rows", .{ prompt.len, sp.max_prompt_tokens });
return .{ .prompt = prompt, .seed = api.seedFor(prompt, srv.config.seed_salt), .format = format };
return .{ .prompt = prompt, .seed = api.seedFor(prompt, srv.config.seed_salt), .format = format, .stream = stream };
}

/// One synthesis: submit, wait for the engine's finished event, then send the whole audio or the reason there is none.
/// One synthesis: submit, then send the whole audio after the finished event, or stream it as the engine publishes it.
fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInfo, plan: Plan, received: i96) void {
const pcm_len = std.math.mul(usize, sp.max_frames, sp.frame_length) catch 0;
if (pcm_len == 0 or sp.sample_rate == 0 or sp.sample_rate > std.math.maxInt(u32) / 2)
Expand All @@ -122,6 +132,7 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf
.temperature = drama_prompt.temperature,
.top_p = drama_prompt.top_p,
.top_k = drama_prompt.top_k,
.stream = plan.stream,
};
var box: Mailbox = .{ .io = srv.io, .gpa = srv.gpa };
defer box.deinit();
Expand All @@ -135,21 +146,10 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf
error.Unsupported => fail(c, cx, id, .request, "this model does not support speech synthesis"),
};
// The engine holds request, prompt, pcm and result until finished; no path below returns before that.
if (!settle(srv, c, &box, engine_id)) {
c.close = true;
srv.metrics.disconnected(srv.io);
var buf: [1024]u8 = undefined;
log.line("{s}", .{log.ended(&buf, id, null, plan.prompt.len, 0, clock.seconds(clock.nowNs(srv.io) - received))});
return;
}
if (plan.stream) return streamReply(srv, c, cx, id, sp, plan, received, &box, engine_id, pcm, &result);
if (settle(srv, c, &box, engine_id, null) == null) return left(srv, c, id, plan.prompt.len, received);
const samples = result.samples;
const why: ?[]const u8 = switch (box.reason) {
.stop => if (samples == 0 or samples > pcm.len) "the engine finished without complete audio" else null,
.length => "speech reached the frame limit without ending; truncated audio is not returned",
.cancelled => "speech synthesis was cancelled",
.failed => if (box.message.len > 0) box.message else "speech synthesis failed",
};
if (why) |message| return fail(c, cx, id, .server, message);
if (why(&box, samples, pcm.len)) |message| return fail(c, cx, id, .server, message);
const data = quantizeInPlace(pcm[0..samples]) catch return fail(c, cx, id, .server, "the synthesized audio has non-finite samples");
if (data.len > std.math.maxInt(u32) - 36) return fail(c, cx, id, .server, "the synthesized audio is too long for one reply");
sendAudio(c, plan.format, sp.sample_rate, data) catch {
Expand All @@ -159,24 +159,119 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf
log.line("speech {s} prompt={d} samples={d} format={s} seconds={d:.2}", .{ id, plan.prompt.len, samples, @tagName(plan.format), clock.seconds(clock.nowNs(srv.io) - received) });
}

/// Waits for the engine's finished event; a client that leaves cancels the synthesis first. False: the client left.
fn settle(srv: *Server, c: *Conn, box: *Mailbox, engine_id: api.Id) bool {
/// The client left before the reply ended; the synthesis was cancelled and waited out.
fn left(srv: *Server, c: *Conn, id: []const u8, prompt_len: usize, received: i96) void {
c.close = true;
srv.metrics.disconnected(srv.io);
var buf: [1024]u8 = undefined;
log.line("{s}", .{log.ended(&buf, id, null, prompt_len, 0, clock.seconds(clock.nowNs(srv.io) - received))});
}

/// Why a finished synthesis has no complete audio, or null.
fn why(box: *const Mailbox, samples: usize, capacity: usize) ?[]const u8 {
return switch (box.reason) {
.stop => if (samples == 0 or samples > capacity) "the engine finished without complete audio" else null,
.length => "speech reached the frame limit without ending; truncated audio is not returned",
.cancelled => "speech synthesis was cancelled",
.failed => if (box.message.len > 0) box.message else "speech synthesis failed",
};
}

/// An error reply when synthesis ends before any audio; else the chunks, and the terminator only after a complete one.
fn streamReply(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInfo, plan: Plan, received: i96, box: *Mailbox, engine_id: api.Id, pcm: []f32, result: *const api.SpeechResult) void {
const sent = streamAudio(srv, c, sp, box, engine_id, pcm) orelse return left(srv, c, id, plan.prompt.len, received);
const mismatch: ?[]const u8 = if (result.samples != sent.samples) "the finished synthesis does not match the audio it published" else null;
const problem = why(box, result.samples, pcm.len) orelse mismatch;
if (sent.samples == 0) return fail(c, cx, id, .server, problem orelse "the engine finished without publishing audio");
if (problem) |message| {
c.close = true; // no terminating chunk: the client's HTTP/1.1 parser reports an incomplete body
log.line("speech {s} stream ended incomplete after samples={d}: {s}", .{ id, sent.samples, message });
return;
}
c.writeAll(last_chunk) catch {
c.close = true;
return;
};
log.line("speech {s} prompt={d} samples={d} format=pcm stream=true first_audio_ready_seconds={d:.3} first_frame_written_seconds={d:.3} seconds={d:.2}", .{
id, plan.prompt.len, sent.samples, clock.seconds(sent.first_ready - received), clock.seconds(sent.first_written - received), clock.seconds(clock.nowNs(srv.io) - received),
});
}

/// What a stream sent, when this thread first saw published audio, and when frame 0's own bytes reached the socket.
const Sent = struct { samples: usize = 0, first_ready: i96 = 0, first_written: i96 = 0 };

/// Sends everything published since the last send as one chunk, converted in place; null: the client left.
fn streamAudio(srv: *Server, c: *Conn, sp: api.SpeechInfo, box: *Mailbox, engine_id: api.Id, pcm: []f32) ?Sent {
var sent: Sent = .{};
var size: [20]u8 = undefined;
while (true) {
const now = settle(srv, c, box, engine_id, sent.samples) orelse return null;
if (now == sent.samples) return sent; // finished, and everything published is sent
const first = sent.samples == 0;
if (first) {
sent.first_ready = clock.nowNs(srv.io);
startStream(c, sp.sample_rate) catch return abandon(srv, box, engine_id);
}
// the audio event made pcm[..now] final: this thread converts it in place
const bytes = quantizeInPlace(pcm[sent.samples..now]) catch return abandon(srv, box, engine_id);
// frame 0's bytes go apart, so their hand-off time does not depend on the chunk's size
const split: usize = if (first) @min(2 * sp.frame_length, bytes.len) else 0;
c.writeAll(std.fmt.bufPrint(&size, "{x}\r\n", .{bytes.len}) catch unreachable) catch return abandon(srv, box, engine_id);
c.writeAll(bytes[0..split]) catch return abandon(srv, box, engine_id);
if (first) sent.first_written = clock.nowNs(srv.io);
c.writeAll(bytes[split..]) catch return abandon(srv, box, engine_id);
c.writeAll("\r\n") catch return abandon(srv, box, engine_id);
sent.samples = now;
}
}

/// Cancels a synthesis whose client is gone, then waits for its finished event; null, for the callers' `return`.
fn abandon(srv: *Server, box: *Mailbox, engine_id: api.Id) ?Sent {
srv.engine.cancel(engine_id);
box.mutex.lockUncancelable(box.io);
defer box.mutex.unlock(box.io);
while (!box.finished) box.cond.waitUncancelable(box.io, &box.mutex);
return null;
}

/// Waits for `finished` or (with `sent`) samples past it, cancelling if the client leaves; samples so far, or null.
fn settle(srv: *Server, c: *Conn, box: *Mailbox, engine_id: api.Id, sent: ?usize) ?usize {
while (true) {
box.mutex.lockUncancelable(box.io);
if (!box.finished) box.cond.waitTimeout(box.io, &box.mutex, .{ .duration = .{ .raw = .fromMilliseconds(50), .clock = .awake } }) catch {};
const done = box.finished;
const idle = if (sent) |n| box.audio == n else true;
if (!box.finished and idle) box.cond.waitTimeout(box.io, &box.mutex, .{ .duration = .{ .raw = .fromMilliseconds(50), .clock = .awake } }) catch {};
const finished = box.finished;
const published = box.audio;
box.mutex.unlock(box.io);
if (done) return true;
if (finished or (if (sent) |n| published > n else false)) return published;
if (c.peerGone()) {
srv.engine.cancel(engine_id);
box.mutex.lockUncancelable(box.io);
defer box.mutex.unlock(box.io);
while (!box.finished) box.cond.waitUncancelable(box.io, &box.mutex);
return false;
_ = abandon(srv, box, engine_id);
return null;
}
}
}

/// 200 with raw PCM16LE in HTTP/1.1 chunks, under the reference's sample-format headers.
fn startStream(c: *Conn, sample_rate: u32) error{Closed}!void {
c.startResponse(200, null) catch return error.Closed;
c.addHeader("Content-Type", Format.pcm.contentType()) catch return error.Closed;
c.addHeader("Transfer-Encoding", "chunked") catch return error.Closed;
var rate: [16]u8 = undefined;
c.addHeader("X-Sample-Rate", std.fmt.bufPrint(&rate, "{d}", .{sample_rate}) catch unreachable) catch return error.Closed;
c.addHeader("X-Channels", "1") catch return error.Closed;
c.addHeader("X-Bit-Depth", "16") catch return error.Closed;
if (c.close) c.addHeader("Connection", "close") catch return error.Closed;
// each chunk leaves at once rather than waiting on the client's acknowledgement of the last (no effect off TCP)
std.posix.setsockopt(c.fd, std.posix.IPPROTO.TCP, std.posix.TCP.NODELAY, &std.mem.toBytes(@as(c_int, 1))) catch {};
// a blocking write into a full socket returns after the stall limit, so writeAll's poll can end a stalled stream
const stall: std.posix.timeval = .{ .sec = @divTrunc(c.timeouts.write_ms, 1000), .usec = @rem(c.timeouts.write_ms, 1000) * 1000 };
std.posix.setsockopt(c.fd, std.posix.SOL.SOCKET, std.posix.SO.SNDTIMEO, std.mem.asBytes(&stall)) catch {};
return c.finish("");
}

/// The terminating chunk: sent only after a complete synthesis's last samples.
const last_chunk = "0\r\n\r\n";

fn refuse(c: *Conn, cx: *Cx, id: []const u8, e: errors.Refused) void {
if (e == error.OutOfMemory) {
cx.kind = .server;
Expand Down Expand Up @@ -288,7 +383,11 @@ test "fields: unknown ones are refused even when null, modifiers when set" {
.{ "{\"model\": \"m\", \"input\": \"hi\", \"voice\": \"default\", \"response_format\": \"wav\", \"speed\": null, \"references\": null}", "" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream_audio\": null}", "unknown speech request field: stream_audio" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"speed\": 1.0}", "speed is not supported by this model" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": false}", "stream is not supported by this model" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": false, \"stream_format\": \"audio\"}", "" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": null, \"stream_format\": null}", "" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": \"yes\"}", "stream must be a boolean" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream_format\": \"sse\"}", "stream_format sse is not supported by this model" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"stream_format\": \"mp3\"}", "stream_format must be one of: audio, sse" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"temperature\": 0.7}", "temperature is not supported by this model" },
.{ "{\"model\": \"m\", \"input\": \"hi\", \"ref_audio\": \"x.wav\"}", "ref_audio is not supported by this model" },
.{ "{\"model\": \"m\", \"input\": 3}", "input must be a string" },
Expand Down
Loading