//! Sentence playback pipeline: synth + play sentences as they complete, //! so voice starts after the first sentence instead of the whole reply. const std = @import("std"); const Io = std.Io; const melo = @import("melo.zig"); var mutex: std.atomic.Mutex = .unlocked; fn lock() void { while (!mutex.tryLock()) std.atomic.spinLoopHint(); } var queue: std.ArrayList([]u8) = .empty; // owned sentences, FIFO var reply_done: bool = true; // current reply fully queued? var alloc: ?std.mem.Allocator = null; var io_ctx: ?Io = null; var thread: ?std.Thread = null; pub fn start(a: std.mem.Allocator, io: Io) void { alloc = a; io_ctx = io; thread = std.Thread.spawn(.{}, run, .{}) catch null; } /// Queue one owned sentence (caller allocates, we free). pub fn push(sentence: []u8) void { lock(); defer mutex.unlock(); queue.append(alloc.?, sentence) catch { alloc.?.free(sentence); return; }; reply_done = false; } /// Mark the current reply as fully queued. pub fn endReply() void { lock(); defer mutex.unlock(); reply_done = true; } /// Free any queued-but-unplayed sentences (quit path). pub fn shutdown() void { const a = alloc orelse return; lock(); defer mutex.unlock(); for (queue.items) |s| a.free(s); queue.clearAndFree(a); } /// Block until every queued sentence has been played. pub fn waitDrained() void { while (true) { lock(); const empty = queue.items.len == 0 and reply_done; mutex.unlock(); if (empty) return; io_ctx.?.sleep(.{ .nanoseconds = 50 * std.time.ns_per_ms }, .real) catch {}; } } fn run() void { const a = alloc orelse return; const io = io_ctx orelse return; while (true) { lock(); const sentence: ?[]u8 = if (queue.items.len > 0) queue.orderedRemove(0) else null; mutex.unlock(); const s = sentence orelse { io.sleep(.{ .nanoseconds = 30 * std.time.ns_per_ms }, .real) catch {}; continue; }; defer a.free(s); if (melo.speakRaw(a, io, s)) |audio| { defer a.free(audio.pcm); playRaw(io, audio.pcm, audio.rate); } else |e| { std.debug.print("inferon/playback: synth failed: {s}\n", .{@errorName(e)}); } } } /// Pipe raw s16le mono PCM straight into pw-play's stdin — no temp files. fn playRaw(io: Io, pcm: []const u8, rate: u32) void { var rate_buf: [16]u8 = undefined; const rate_str = std.fmt.bufPrint(&rate_buf, "{d}", .{rate}) catch return; var child = std.process.spawn(io, .{ .argv = &.{ "pw-play", "--raw", "--format", "s16", "--rate", rate_str, "--channels", "1", "-" }, .stdin = .pipe, .stdout = .ignore, .stderr = .ignore, }) catch |e| { std.debug.print("inferon/playback: pw-play spawn failed: {s}\n", .{@errorName(e)}); return; }; const stdin = child.stdin orelse return; var wbuf: [64 * 1024]u8 = undefined; var writer = stdin.writer(io, &wbuf); writer.interface.writeAll(pcm) catch {}; writer.interface.flush() catch {}; stdin.close(io); // EOF so pw-play finishes child.stdin = null; // already closed — stop wait() from closing again _ = child.wait(io) catch {}; }