// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A group's audio, from the program to every player in it, in step. //! //! The program writes interleaved `f32` in its own format -- the source -- //! and each player is sent it in a format of its own, from those its hello //! offered: the source's rate and channels if it takes them, else its first //! choice, resampled with zig-resample and its channels mixed to fit. //! Players that chose the same format share one encoding of it: //! //! - PCM at 16, 24 or 32 bits, little-endian; //! - FLAC, a frame a chunk, the signature and the streaminfo sent as the //! stream's `codec_header`; //! - Opus, a 20 ms packet a chunk, stamped back by the encoder's lookahead //! so that what the decoder gives is heard from the stamp. //! //! Every chunk is 20 ms and stamped with the moment its first sample is to //! be heard, on the server's clock. The first sample is set, when the first //! write after a start or a clear arrives, as far ahead of now as the //! slowest player in the group needs -- its `min_buffer_ms` and //! `static_delay_ms`, or its `required_lead_time_ms` if longer -- and the //! rest follow from it sample for sample. An encoding started later -- a //! player joining, or asking for another format -- is stamped from where the //! source had got to, so it plays in step with the rest. //! //! `write` waits while it is further ahead of the clock than the players //! can hold: `max_ahead_us`, or less if a player's `buffer_capacity` would //! not hold that much PCM. A player whose queue is full misses the chunk //! rather than holding the group up. const Stream = @This(); const std = @import("std"); const Io = std.Io; const sendspin = @import("sendspin"); const resample = @import("resample"); const flac = @import("flac"); const opus = @import("opus"); const message = sendspin.message; const server_message = sendspin.server_message; const Server = @import("Server.zig"); const Connection = @import("Connection.zig"); const log = std.log.scoped(.sendspin_server); /// The program's audio: what `write` is handed. pub const Source = struct { sample_rate: u32, channels: u8, }; /// How far ahead of the clock audio is sent, at most: time for a player to /// ride out a hiccup in the network, and little enough that a skip takes /// effect soon. pub const default_max_ahead_us = 5 * std.time.us_per_s; /// The shortest lead the first chunk is given, whatever the players say. const min_lead_us = 200 * std.time.us_per_ms; const chunk_ms = 20; server: *Server, source: Source, max_ahead_us: i64, /// Held over the encodings and the timeline; taken after the server's lock, /// never before it. lock: Io.Mutex = .init, encodings: std.ArrayList(*Encoding) = .empty, /// When source frame 0 is to be heard, on the server's clock; set by the /// first write after a start or a clear. t0: ?i64 = null, /// Source frames written since. source_pos: u64 = 0, /// Whether `end` has been: the encoders are flushed and finished, and /// nothing more goes through them. ended: bool = false, /// One format, and the players that chose it. const Encoding = struct { stream: *Stream, format: message.Format, /// Retained. members: std.ArrayList(*Connection) = .empty, resampler: ?resample.Resampler = null, codec: Codec, /// The codec header, base64, for FLAC. header: ?[]u8 = null, flac_out: Io.Writer.Allocating, /// When this encoding's first frame is to be heard, and how many frames /// it has made since; the source frame it began at. base_us: i64 = 0, out_frames: u64 = 0, start_source: u64 = 0, /// Frames at the format's rate and channels, waiting for a whole chunk. pending: std.ArrayList(f32) = .empty, /// Scratch: the source mapped to the format's channels, and resampled. mapped: std.ArrayList(f32) = .empty, resampled: std.ArrayList(f32) = .empty, chunk_frames: usize, const Codec = union(enum) { pcm, flac: flac.Encoder, opus: struct { encoder: opus.Encoder, lookahead_us: i64 }, }; fn channels(e: *const Encoding) usize { return e.format.channels; } }; pub fn create(server: *Server, source: Source, max_ahead_us: i64) !*Stream { const s = try server.gpa.create(Stream); s.* = .{ .server = server, .source = source, .max_ahead_us = max_ahead_us }; return s; } pub fn destroy(self: *Stream) void { const gpa = self.server.gpa; for (self.encodings.items) |e| self.freeEncoding(e); self.encodings.deinit(gpa); gpa.destroy(self); } fn freeEncoding(self: *Stream, e: *Encoding) void { const gpa = self.server.gpa; for (e.members.items) |c| c.release(); e.members.deinit(gpa); if (e.resampler) |*r| r.deinit(); switch (e.codec) { .flac => |*f| f.deinit(), else => {}, } if (e.header) |h| gpa.free(h); e.flac_out.deinit(); e.pending.deinit(gpa); e.mapped.deinit(gpa); e.resampled.deinit(gpa); gpa.destroy(e); } /// The format `offered` would play the source in: its first that is at /// the source's rate and channels, else its first at the source's rate, /// else its first -- resampled. pub fn choose(source: Source, offered: []const message.Format) ?message.Format { for (offered) |f| if (f.sample_rate == source.sample_rate and f.channels == source.channels) return f; for (offered) |f| if (f.sample_rate == source.sample_rate) return f; return if (offered.len > 0) offered[0] else null; } /// Start sending to `conn`, in the format it prefers of those it offered, /// or `format` if given. Under the server's lock. pub fn addMember(self: *Stream, conn: *Connection, format: ?message.Format) !void { const player = conn.hello.player orelse return; const want = format orelse choose(self.source, player.formats) orelse return; self.lock.lockUncancelable(self.server.io); defer self.lock.unlock(self.server.io); if (self.ended) return; self.removeMemberLocked(conn); const e = try self.encodingFor(want); try e.members.append(self.server.gpa, conn); conn.retain(); self.sendStart(e, conn); } /// Stop sending to `conn`. Under the server's lock. pub fn removeMember(self: *Stream, conn: *Connection) void { self.lock.lockUncancelable(self.server.io); defer self.lock.unlock(self.server.io); self.removeMemberLocked(conn); } fn removeMemberLocked(self: *Stream, conn: *Connection) void { for (self.encodings.items, 0..) |e, i| { for (e.members.items, 0..) |m, j| if (m == conn) { _ = e.members.swapRemove(j); conn.release(); if (e.members.items.len == 0) { _ = self.encodings.swapRemove(i); self.freeEncoding(e); } return; }; } } /// `conn`'s request for another format: the first it offered that meets /// every field it names. A request nothing meets is ignored. Under the /// server's lock. pub fn requestFormat(self: *Stream, conn: *Connection, request: message.FormatRequest) !void { const player = conn.hello.player orelse return; const f = for (player.formats) |f| { if (request.codec) |c| if (c != f.codec) continue; if (request.channels) |c| if (c != f.channels) continue; if (request.sample_rate) |c| if (c != f.sample_rate) continue; if (request.bit_depth) |c| if (c != f.bit_depth) continue; break f; } else { log.info("{s} asked for a format it did not offer", .{conn.hello.name}); return; }; try self.addMember(conn, f); } /// The encoding of `format`, made if there is none yet. Under the lock. fn encodingFor(self: *Stream, format: message.Format) !*Encoding { for (self.encodings.items) |e| if (std.meta.eql(e.format, format)) return e; const gpa = self.server.gpa; const e = try gpa.create(Encoding); e.* = .{ .stream = self, .format = format, .codec = .pcm, .flac_out = .init(gpa), .chunk_frames = @max(1, format.sample_rate * chunk_ms / 1000), .start_source = self.source_pos, }; errdefer { e.flac_out.deinit(); gpa.destroy(e); } if (format.sample_rate != self.source.sample_rate) e.resampler = try .init(gpa, .{ .in_rate = self.source.sample_rate, .out_rate = format.sample_rate, .channels = format.channels, }); errdefer if (e.resampler) |*r| r.deinit(); switch (format.codec) { .pcm => {}, .flac => { e.codec = .{ .flac = try flac.Encoder.init(gpa, &e.flac_out.writer, .{ .sample_rate = format.sample_rate, .channels = format.channels, .bits_per_sample = format.bit_depth, }, .{ .block_size = @intCast(e.chunk_frames) }) }; // The signature and the streaminfo, marked the last block, as // the decoders expect; then only frames are written. const written = e.flac_out.written(); var head: [4 + 4 + 34]u8 = undefined; @memcpy(head[0..4], "fLaC"); head[4] = 0x80; std.mem.writeInt(u24, head[5..8], 34, .big); @memcpy(head[8..], written[flac.Encoder.streaminfo_body_offset..][0..34]); e.header = try gpa.alloc(u8, std.base64.standard.Encoder.calcSize(head.len)); _ = std.base64.standard.Encoder.encode(e.header.?, &head); e.flac_out.clearRetainingCapacity(); }, .opus => { var encoder = try opus.Encoder.init(format.sample_rate, format.channels, .audio); try encoder.setBitrate(.{ .bps = 64_000 * @as(i32, format.channels) }); e.codec = .{ .opus = .{ .encoder = encoder, .lookahead_us = @divFloor(@as(i64, encoder.lookahead()) * std.time.us_per_s, format.sample_rate), } }; }, } if (self.t0) |t0| self.setBase(e, t0); try self.encodings.append(gpa, e); return e; } /// When `e`'s first frame is heard: where the source had got to when it /// began, on the timeline that starts at `t0`. fn setBase(self: *Stream, e: *Encoding, t0: i64) void { e.base_us = t0 + @as(i64, @intCast(e.start_source * std.time.us_per_s / self.source.sample_rate)); e.out_frames = 0; } fn sendStart(self: *Stream, e: *Encoding, conn: *Connection) void { _ = self; var buf: [512]u8 = undefined; var w: Io.Writer = .fixed(&buf); const start: message.StreamStart = .{ .codec = e.format.codec, .sample_rate = e.format.sample_rate, .channels = e.format.channels, .bit_depth = e.format.bit_depth, .codec_header = e.header, }; server_message.writeStreamStart(&w, Server.now(), .{ .player = start }) catch return; conn.send(w.buffered()) catch {}; if (conn.server.options.observer) |o| o.onStart(o.context, conn, start); } /// The lead the first chunk needs: the longest any player in the group /// asks for. Under the server's lock. pub fn leadLocked(members: []const *Connection) i64 { var lead: i64 = min_lead_us; for (members) |c| { if (!c.roles.player) continue; const st = c.state; const needs = @max(@as(i64, st.required_lead_time_ms), @as(i64, st.min_buffer_ms) + st.static_delay_ms) * std.time.us_per_ms; lead = @max(lead, needs); } return lead; } /// Frames of the source, interleaved, sent to every player in its format. /// `lead_us` is for the first write after a start or a clear, from /// `leadLocked`. Waits while the stream is as far ahead of the clock as it /// may go. pub fn write(self: *Stream, frames: []const f32, lead_us: i64) !void { const io = self.server.io; const ch = self.source.channels; if (frames.len % ch != 0) return error.RaggedInput; const n = frames.len / ch; try self.lock.lock(io); defer self.lock.unlock(io); if (self.ended) return error.Ended; const t0 = self.t0 orelse blk: { const t = Server.now() + lead_us; self.t0 = t; for (self.encodings.items) |e| self.setBase(e, t); break :blk t; }; // Not further ahead than the players hold. const window = self.windowLocked(); while (true) { const at = t0 + @as(i64, @intCast(self.source_pos * std.time.us_per_s / self.source.sample_rate)); const ahead = at - Server.now(); if (ahead <= window) break; self.lock.unlock(io); const nap = @min(ahead - window, 50 * std.time.us_per_ms); io.sleep(.fromMicroseconds(nap), .awake) catch |err| { self.lock.lockUncancelable(io); return err; }; self.lock.lockUncancelable(io); } for (self.encodings.items) |e| try self.feed(e, frames); self.source_pos += n; } /// How far ahead audio may go: `max_ahead_us`, or less if a player's /// buffer would not hold that much of its format as PCM, which bounds any /// codec's bytes. fn windowLocked(self: *Stream) i64 { var window = self.max_ahead_us; for (self.encodings.items) |e| { const bytes_per_second: u64 = @as(u64, e.format.sample_rate) * e.format.channels * (@max(e.format.bit_depth, 8) / 8); for (e.members.items) |c| { const capacity = (c.hello.player orelse continue).buffer_capacity; const holds: i64 = @intCast(@as(u64, capacity) * std.time.us_per_s / @max(bytes_per_second, 1)); window = @min(window, @divFloor(holds * 3, 4)); } } return @max(window, min_lead_us); } /// The source's frames into `e`: channels mapped, resampled, and encoded /// and sent a chunk at a time. fn feed(self: *Stream, e: *Encoding, frames: []const f32) !void { const gpa = self.server.gpa; const in_ch: usize = self.source.channels; const out_ch = e.channels(); const n = frames.len / in_ch; e.mapped.clearRetainingCapacity(); try e.mapped.resize(gpa, n * out_ch); mapChannels(frames, in_ch, e.mapped.items, out_ch); if (e.resampler) |*r| { var consumed: usize = 0; while (consumed < n) { const room = 1024; try e.resampled.resize(gpa, room * out_ch); const d = r.process(e.mapped.items[consumed * out_ch ..], e.resampled.items); consumed += d.consumed; try e.pending.appendSlice(gpa, e.resampled.items[0 .. d.produced * out_ch]); } } else try e.pending.appendSlice(gpa, e.mapped.items); const chunk = e.chunk_frames * out_ch; var at: usize = 0; while (e.pending.items.len - at >= chunk) : (at += chunk) try self.emit(e, e.pending.items[at..][0..chunk]); std.mem.copyForwards(f32, e.pending.items, e.pending.items[at..]); e.pending.shrinkRetainingCapacity(e.pending.items.len - at); } /// Mix `in` (`in_ch` channels) into `out` (`out_ch`): the same, averaged to /// mono, mono spread to all, or the first channels kept and the rest silent. fn mapChannels(in: []const f32, in_ch: usize, out: []f32, out_ch: usize) void { const n = in.len / in_ch; if (in_ch == out_ch) return @memcpy(out[0 .. n * out_ch], in[0 .. n * in_ch]); for (0..n) |i| { const frame = in[i * in_ch ..][0..in_ch]; const dest = out[i * out_ch ..][0..out_ch]; if (out_ch == 1) { var sum: f32 = 0; for (frame) |s| sum += s; dest[0] = sum / @as(f32, @floatFromInt(in_ch)); } else if (in_ch == 1) { @memset(dest, frame[0]); } else { @memset(dest, 0); const k = @min(in_ch, out_ch); @memcpy(dest[0..k], frame[0..k]); } } } /// One chunk, encoded, stamped and sent to every player in `e`. fn emit(self: *Stream, e: *Encoding, samples: []const f32) !void { const gpa = self.server.gpa; const frames = samples.len / e.channels(); var stamp = e.base_us + @as(i64, @intCast(e.out_frames * std.time.us_per_s / e.format.sample_rate)); e.out_frames += frames; var bytes: []const u8 = undefined; var owned: ?[]u8 = null; defer if (owned) |o| gpa.free(o); var packet: [4000]u8 = undefined; switch (e.codec) { .pcm => { const width: usize = @max(e.format.bit_depth, 8) / 8; const out = try gpa.alloc(u8, samples.len * width); owned = out; for (samples, 0..) |s, i| writeSample(out[i * width ..][0..width], s, e.format.bit_depth); bytes = out; }, .flac => |*enc| { const ints = try gpa.alloc(i32, samples.len); defer gpa.free(ints); for (ints, samples) |*d, s| d.* = quantize(s, e.format.bit_depth); try enc.writeInterleaved(ints); owned = try gpa.dupe(u8, e.flac_out.written()); e.flac_out.clearRetainingCapacity(); bytes = owned.?; }, .opus => |*o| { const len = try o.encoder.encodeFloat(samples, @intCast(frames), &packet); bytes = packet[0..len]; stamp -= o.lookahead_us; }, } if (bytes.len == 0) return; if (self.server.options.observer) |o| o.onChunk(o.context, e.format, stamp, bytes); const header = server_message.binaryHeader(.audio, stamp); for (e.members.items) |c| { // Not before its first state, which says the timing it needs, nor // while it says it is taken up with something else. if (!c.state_seen.load(.acquire) or !c.state.available) continue; const out = try gpa.alloc(u8, header.len + bytes.len); @memcpy(out[0..header.len], &header); @memcpy(out[header.len..], bytes); if (!c.putNow(.{ .binary = out })) log.debug("{s} is behind; a chunk dropped", .{c.hello.name}); } } /// A sample as a `bits`-bit integer: rounded, clamped to the range, and /// silence for a NaN. In `f64`, which holds 2³¹ − 1 exactly where `f32` /// would round it up past the top. fn quantize(s: f32, bits: u8) i32 { if (std.math.isNan(s)) return 0; const full: f64 = @floatFromInt(@as(i64, 1) << @intCast(bits - 1)); return @intFromFloat(std.math.clamp(@round(@as(f64, s) * full), -full, full - 1)); } fn writeSample(out: []u8, s: f32, bits: u8) void { switch (bits) { 16 => std.mem.writeInt(i16, out[0..2], @intCast(quantize(s, 16)), .little), 24 => std.mem.writeInt(i24, out[0..3], @intCast(quantize(s, 24)), .little), 32 => std.mem.writeInt(i32, out[0..4], quantize(s, 32), .little), else => @memset(out, 0), } } /// Drop what is buffered, on the players too: what comes next is from /// somewhere else. The next write sets a new timeline. pub fn clear(self: *Stream) void { self.lock.lockUncancelable(self.server.io); defer self.lock.unlock(self.server.io); if (self.ended) return; self.t0 = null; self.source_pos = 0; for (self.encodings.items) |e| { e.pending.clearRetainingCapacity(); if (e.resampler) |*r| r.reset(); e.start_source = 0; e.out_frames = 0; var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); server_message.writeStreamClear(&w, Server.now(), .{ .player = true }) catch continue; for (e.members.items) |c| c.send(w.buffered()) catch {}; } } /// The last of the audio -- what the resamplers and a short last chunk /// hold -- and then, once it has all been heard, `stream/end`. Final: a /// stream that has ended takes no more writes, and a new one is started for /// more audio. /// /// `stream/end` says playback is over, and a player takes it at its word: /// by default it stops and drops what it holds. So it waits for the last /// chunk's moment to pass -- up to the send-ahead window -- rather than /// cutting off what the players were sent ahead. To stop at once instead, /// `clear` first: then nothing is left to be heard, and nothing is waited /// for. Canceled while it waits, it ends the stream there and then, and /// returns the cancelation. pub fn end(self: *Stream) Io.Cancelable!void { const io = self.server.io; const until = self.finish() orelse return; while (true) { const left = until - Server.now(); if (left <= 0) break; io.sleep(.fromMicroseconds(@min(left, 50 * std.time.us_per_ms)), .awake) catch |err| { self.sendEnd(); return err; }; } self.sendEnd(); } /// The flushing half of `end`: marks the stream ended, sends what the /// resamplers and a short last chunk hold, and says when the last of it is /// to be heard -- or null if it has already ended. fn finish(self: *Stream) ?i64 { const gpa = self.server.gpa; self.lock.lockUncancelable(self.server.io); defer self.lock.unlock(self.server.io); if (self.ended) return null; self.ended = true; var until = Server.now(); if (self.t0 == null) return until; for (self.encodings.items) |e| { if (e.resampler) |*r| { var tail: [1024 * 8]f32 = undefined; while (true) { const room = tail.len / e.channels() * e.channels(); const produced = r.flush(tail[0..room]); if (produced == 0) break; e.pending.appendSlice(gpa, tail[0 .. produced * e.channels()]) catch break; } } const chunk = e.chunk_frames * e.channels(); var at: usize = 0; while (e.pending.items.len - at >= chunk) : (at += chunk) self.emit(e, e.pending.items[at..][0..chunk]) catch break; const rest = e.pending.items[at..]; if (rest.len > 0) { // Opus codes only whole frames: the last one padded with // silence. The others may end short. if (e.codec == .opus) { var padded: [48000 / 50 * 8]f32 = @splat(0); @memcpy(padded[0..rest.len], rest); self.emit(e, padded[0..chunk]) catch {}; } else self.emit(e, rest) catch {}; } e.pending.clearRetainingCapacity(); until = @max(until, e.base_us + @as(i64, @intCast(e.out_frames * std.time.us_per_s / e.format.sample_rate))); } return until; } fn sendEnd(self: *Stream) void { self.lock.lockUncancelable(self.server.io); defer self.lock.unlock(self.server.io); for (self.encodings.items) |e| { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); server_message.writeStreamEnd(&w, Server.now(), .{ .player = true }) catch continue; for (e.members.items) |c| c.send(w.buffered()) catch {}; } } test "a format for every source" { const offered = [_]message.Format{ .{ .codec = .opus, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }, .{ .codec = .flac, .channels = 2, .sample_rate = 44100, .bit_depth = 16 }, .{ .codec = .pcm, .channels = 1, .sample_rate = 44100, .bit_depth = 24 }, }; try std.testing.expectEqual(offered[1], choose(.{ .sample_rate = 44100, .channels = 2 }, &offered).?); try std.testing.expectEqual(offered[2], choose(.{ .sample_rate = 44100, .channels = 1 }, &offered).?); try std.testing.expectEqual(offered[1], choose(.{ .sample_rate = 44100, .channels = 6 }, &offered).?); try std.testing.expectEqual(offered[0], choose(.{ .sample_rate = 96000, .channels = 2 }, &offered).?); try std.testing.expect(choose(.{ .sample_rate = 48000, .channels = 2 }, &.{}) == null); } test "samples quantized, clamped, and NaN silent" { try std.testing.expectEqual(@as(i32, 16384), quantize(0.5, 16)); try std.testing.expectEqual(@as(i32, 32767), quantize(2.0, 16)); try std.testing.expectEqual(@as(i32, -32768), quantize(-1.0, 16)); try std.testing.expectEqual(@as(i32, -8388608), quantize(-5.0, 24)); try std.testing.expectEqual(@as(i32, 0), quantize(std.math.nan(f32), 16)); var four: [4]u8 = undefined; writeSample(&four, 1.0, 32); try std.testing.expectEqual(@as(i32, std.math.maxInt(i32)), std.mem.readInt(i32, &four, .little)); } test "channels mapped" { var out: [4]f32 = undefined; mapChannels(&.{ 0.2, 0.4, -0.2, 0.6 }, 2, out[0..2], 1); try std.testing.expectApproxEqAbs(@as(f32, 0.3), out[0], 1e-6); try std.testing.expectApproxEqAbs(@as(f32, 0.2), out[1], 1e-6); mapChannels(&.{ 0.5, -0.5 }, 1, &out, 2); try std.testing.expectEqualSlices(f32, &.{ 0.5, 0.5, -0.5, -0.5 }, &out); }