diff --git a/build.zig b/build.zig index 06abc81..783ca1f 100644 --- a/build.zig +++ b/build.zig @@ -14,6 +14,7 @@ pub fn build(b: *std.Build) void { const noise = b.dependency("noise", .{ .target = target, .optimize = optimize }); const opus = b.dependency("opus", .{ .target = target, .optimize = optimize }); const std_crypto_ext = b.dependency("std_crypto_ext", .{ .target = target, .optimize = optimize }); + const resample = b.dependency("resample", .{ .target = target, .optimize = optimize }); const mod = b.addModule("sendspin", .{ .root_source_file = b.path("src/root.zig"), @@ -66,6 +67,9 @@ pub fn build(b: *std.Build) void { .{ .name = "websocket_server", .module = websocket.module("websocket_server") }, .{ .name = "http", .module = http.module("http") }, .{ .name = "http_io", .module = http.module("http_io") }, + .{ .name = "flac", .module = flac.module("flac") }, + .{ .name = "opus", .module = opus.module("opus") }, + .{ .name = "resample", .module = resample.module("resample") }, }, }); // Its tests meet the client, dialing and dialed. @@ -81,6 +85,9 @@ pub fn build(b: *std.Build) void { .{ .name = "websocket_server", .module = websocket.module("websocket_server") }, .{ .name = "http", .module = http.module("http") }, .{ .name = "http_io", .module = http.module("http_io") }, + .{ .name = "flac", .module = flac.module("flac") }, + .{ .name = "opus", .module = opus.module("opus") }, + .{ .name = "resample", .module = resample.module("resample") }, }, }); _ = server_mod; diff --git a/build.zig.zon b/build.zig.zon index fd75cc3..72a3487 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -32,6 +32,10 @@ .url = "git+https://git.jcollie.dev/jeff/zig-uri.git#c472509ef662a1528f24e283799280bebbeb2777", .hash = "uri-0.1.0-yCrwNNH2EwBMp75OiyjnW1w5FMiFdI0gWghu4QMEVWtU", }, + .resample = .{ + .url = "git+https://git.jcollie.dev/jeff/zig-resample.git#8a336b8dd1630b3c61e0a14632a4207256b3836c", + .hash = "resample-0.0.0-to7yt-ceAQD8ZlIgHarJQeoHtxuARLgRrFOyZKTutmAb", + }, }, .paths = .{ "build.zig", diff --git a/build.zig.zon.nix b/build.zig.zon.nix index dd8720e..648197c 100644 --- a/build.zig.zon.nix +++ b/build.zig.zon.nix @@ -219,6 +219,15 @@ copyFarm name unpack = true; }; } + { + name = "resample-0.0.0-to7yt-ceAQD8ZlIgHarJQeoHtxuARLgRrFOyZKTutmAb"; + path = fetchZigArtifact { + name = "resample"; + url = "git+https://git.jcollie.dev/jeff/zig-resample.git#8a336b8dd1630b3c61e0a14632a4207256b3836c"; + hash = "sha256-+FG7Y2Aoki4zhw97v751UFrv1Te9q55jzdG0jZqdxD0="; + unpack = true; + }; + } { name = "std_crypto_ext-0.0.0-zmlw4UC9BQAAw8f8c14lGEbZ2bih0gDWr7NpmCZZJMyh"; path = fetchZigArtifact { diff --git a/src/server/Connection.zig b/src/server/Connection.zig index bc08d98..658bade 100644 --- a/src/server/Connection.zig +++ b/src/server/Connection.zig @@ -150,6 +150,18 @@ pub fn sendBinaryParts(self: *Connection, header: []const u8, body: []const u8) return self.put(.{ .binary = out }); } +/// Queue `out` if there is room, and say whether there was; never waits. +/// For audio, which a client too far behind can miss. +pub fn putNow(self: *Connection, out: Out) bool { + if (self.closed.load(.acquire)) { + freeOut(self.server.gpa, out); + return false; + } + const n = self.queue.put(self.server.io, &.{out}, 0) catch 0; + if (n == 0) freeOut(self.server.gpa, out); + return n == 1; +} + pub fn put(self: *Connection, out: Out) !void { if (self.closed.load(.acquire)) { freeOut(self.server.gpa, out); diff --git a/src/server/Group.zig b/src/server/Group.zig index 02cd932..7f763c6 100644 --- a/src/server/Group.zig +++ b/src/server/Group.zig @@ -16,6 +16,7 @@ const message = sendspin.message; const server_message = sendspin.server_message; const Server = @import("Server.zig"); const Connection = @import("Connection.zig"); +const Stream = @import("Stream.zig"); server: *Server, /// The group's id and name, as `group/update` says them. @@ -24,6 +25,8 @@ name: []const u8, /// Its clients, under the server's lock. members: std.ArrayList(*Connection) = .empty, playback: message.PlaybackState = .stopped, +/// The audio being played to it, between `start` and `end`. +stream: ?*Stream = null, /// Every member, retained, so that they can be sent to without the /// server's lock held; `releaseAll` when done. Under the server's lock. @@ -57,6 +60,7 @@ pub fn addLocked(self: *Group, c: *Connection) !void { try self.members.append(self.server.gpa, c); c.group = self; self.sendUpdate(c); + if (self.stream) |s| if (c.roles.player) try s.addMember(c, null); } /// Take `c` out; under the server's lock. @@ -66,8 +70,59 @@ pub fn removeLocked(self: *Group, c: *Connection) void { break; }; if (c.group == self) c.group = null; + if (self.stream) |s| s.removeMember(c); +} + +// --- the audio --------------------------------------------------------------- +// +// `start`, `write`, `clear` and `end` are the program's, from one task: the +// one producing the audio. + +/// Start playing audio in `source`'s format: every player in the group is +/// told the format it will get. A stream already started is ended first. +pub fn start(self: *Group, source: Stream.Source) !void { + if (self.stream != null) self.end(); + const s = try Stream.create(self.server, source, Stream.default_max_ahead_us); + const io = self.server.io; + self.server.lock.lockUncancelable(io); + defer self.server.lock.unlock(io); + self.stream = s; + for (self.members.items) |c| if (c.roles.player) s.addMember(c, null) catch {}; + self.setPlaybackLocked(.playing); +} + +/// Frames of audio, interleaved, in the format `start` was given. Waits +/// while the group is as far ahead of the clock as its players can hold. +pub fn write(self: *Group, frames: []const f32) !void { + const s = self.stream orelse return error.NotStarted; + const lead = blk: { + if (s.t0 != null) break :blk 0; + self.server.lock.lockUncancelable(self.server.io); + defer self.server.lock.unlock(self.server.io); + break :blk Stream.leadLocked(self.members.items); + }; + try s.write(frames, lead); +} + +/// Drop what the players have buffered: what comes next -- a seek, a skip +/// -- is from somewhere else. +pub fn clear(self: *Group) void { + if (self.stream) |s| s.clear(); +} + +/// The last of the audio, and the stream's end. +pub fn end(self: *Group) void { + const s = self.stream orelse return; + s.end(); + const io = self.server.io; + self.server.lock.lockUncancelable(io); + self.stream = null; + self.setPlaybackLocked(.stopped); + self.server.lock.unlock(io); + s.destroy(); } pub fn deinit(self: *Group) void { + if (self.stream) |s| s.destroy(); self.members.deinit(self.server.gpa); } diff --git a/src/server/Server.zig b/src/server/Server.zig index 157ef0f..c5b6eb1 100644 --- a/src/server/Server.zig +++ b/src/server/Server.zig @@ -295,7 +295,13 @@ fn readLoop(self: *Server, conn: *Connection) !void { self.sink.onState(self.sink.context, conn); }, .command => |c| self.sink.onCommand(self.sink.context, conn, c), - .request_format => {}, + .request_format => |r| { + self.lock.lockUncancelable(self.io); + defer self.lock.unlock(self.io); + if (conn.group) |g| if (g.stream) |s| s.requestFormat(conn, r) catch |err| { + log.warn("could not change {s}'s format: {t}", .{ conn.hello.name, err }); + }; + }, .goodbye => |reason| { log.info("{s} said goodbye: {s}", .{ conn.hello.name, reason }); return; diff --git a/src/server/Stream.zig b/src/server/Stream.zig new file mode 100644 index 0000000..5ff81dc --- /dev/null +++ b/src/server/Stream.zig @@ -0,0 +1,551 @@ +// 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, + +/// 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); + 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); + server_message.writeStreamStart(&w, Server.now(), .{ .player = .{ + .codec = e.format.codec, + .sample_rate = e.format.sample_rate, + .channels = e.format.channels, + .bit_depth = e.format.bit_depth, + .codec_header = e.header, + } }) catch return; + conn.send(w.buffered()) catch {}; +} + +/// 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); + 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; + const header = server_message.binaryHeader(.audio, stamp); + for (e.members.items) |c| { + if (!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); + 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 `stream/end`. +pub fn end(self: *Stream) void { + const gpa = self.server.gpa; + self.lock.lockUncancelable(self.server.io); + defer self.lock.unlock(self.server.io); + for (self.encodings.items) |e| { + if (self.t0 != null) { + 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 {}; + } + } + 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); +} diff --git a/src/server/root.zig b/src/server/root.zig index 4de459e..456f6cb 100644 --- a/src/server/root.zig +++ b/src/server/root.zig @@ -11,6 +11,7 @@ pub const Server = @import("Server.zig"); pub const Connection = @import("Connection.zig"); pub const Group = @import("Group.zig"); pub const Listener = @import("Listener.zig"); +pub const Stream = @import("Stream.zig"); test { std.testing.refAllDecls(@This()); diff --git a/src/server/tests.zig b/src/server/tests.zig index 7397e3d..710b343 100644 --- a/src/server/tests.zig +++ b/src/server/tests.zig @@ -258,3 +258,197 @@ test "the server dials a client that listens" { try testing.expectEqual(@as(u32, 1), seen.joins.load(.acquire)); dialing.cancel(io) catch {}; } + +// --- streaming ----------------------------------------------------------------- + +const flac = @import("flac"); +const opus = @import("opus"); +const Stream = @import("Stream.zig"); + +/// A client's view of a stream: its format, and every chunk with its stamp. +/// Written by the client's task alone; read after `ended`, which is stored +/// with release and loaded with acquire. +const Received = struct { + format: ?message.StreamStart = null, + header: ?[]u8 = null, + chunks: std.ArrayList(Chunk) = .empty, + ended: std.atomic.Value(bool) = .init(false), + player_active: std.atomic.Value(bool) = .init(false), + + const Chunk = struct { stamp: i64, data: []u8 }; + + fn deinit(self: *Received) void { + for (self.chunks.items) |c| testing.allocator.free(c.data); + self.chunks.deinit(testing.allocator); + if (self.header) |h| testing.allocator.free(h); + } + + fn sink(self: *Received) sendspin.Client.Sink { + return .{ + .context = self, + .onStreamStart = onStart, + .onAudio = onAudio, + .onStreamClear = ignore, + .onStreamEnd = onEnd, + .onClock = ignoreClock, + .onActivate = onActivate, + }; + } + fn onActivate(context: *anyopaque, a: message.Activate) void { + const self: *Received = @ptrCast(@alignCast(context)); + if (a.player orelse false) self.player_active.store(true, .release); + } + fn onStart(context: *anyopaque, f: message.StreamStart) void { + const self: *Received = @ptrCast(@alignCast(context)); + self.format = f; + if (f.codec_header) |h| self.header = testing.allocator.dupe(u8, h) catch null; + } + fn onAudio(context: *anyopaque, stamp: i64, data: []const u8) void { + const self: *Received = @ptrCast(@alignCast(context)); + const copy = testing.allocator.dupe(u8, data) catch return; + self.chunks.append(testing.allocator, .{ .stamp = stamp, .data = copy }) catch testing.allocator.free(copy); + } + fn onEnd(context: *anyopaque) void { + const self: *Received = @ptrCast(@alignCast(context)); + self.ended.store(true, .release); + } + fn ignore(_: *anyopaque) void {} + fn ignoreClock(_: *anyopaque, _: sendspin.TimeFilter) void {} +}; + +fn ended(r: *Received) bool { + return r.ended.load(.acquire); +} +fn active(r: *Received) bool { + return r.player_active.load(.acquire); +} +fn fourJoined(h: *Harness) bool { + return h.seen.joins.load(.acquire) >= 4; +} + +fn tone(i: usize, channel: usize, rate: f64) f32 { + const freq: f64 = if (channel == 0) 440 else 1000; + return @floatCast(0.5 * @sin(2 * std.math.pi * freq * @as(f64, @floatFromInt(i)) / rate)); +} + +test "one stream to four players: PCM exact, FLAC exact, Opus whole, and PCM resampled, all in step" { + var prng: std.Random.DefaultPrng = .init(31); + var h: Harness = undefined; + try h.start(.{ .name = "Streaming Server", .identity = noise.KeyPair.generate(prng.random()) }); + defer h.stop(); + const io = h.io(); + + const offers = [_][]const message.Format{ + &.{.{ .codec = .pcm, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }}, + &.{.{ .codec = .flac, .channels = 2, .sample_rate = 48000, .bit_depth = 24 }}, + &.{.{ .codec = .opus, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }}, + &.{.{ .codec = .pcm, .channels = 2, .sample_rate = 44100, .bit_depth = 16 }}, + }; + var received: [4]Received = @splat(.{}); + defer for (&received) |*r| r.deinit(); + var clients: [4]sendspin.Client = undefined; + var runners: [4]Io.Future(@typeInfo(@TypeOf(sendspin.Client.run)).@"fn".return_type.?) = undefined; + for (&clients, &runners, &received, offers) |*c, *run, *r, offer| { + var options = clientOptions(h.port(), noise.KeyPair.generate(prng.random())); + options.hello.formats = offer; + c.* = .init(io, testing.allocator, options, r.sink()); + run.* = try io.concurrent(sendspin.Client.run, .{c}); + } + defer for (&runners) |*run| run.cancel(io) catch {}; + try waitUntil(io, "four players", &h, fourJoined); + for (&received) |*r| try waitUntil(io, "a player's activation", r, active); + + const rate = 48000; + const frames = rate; + const group = h.server.default_group; + try group.start(.{ .sample_rate = rate, .channels = 2 }); + var piece: [2 * 480]f32 = undefined; + var at: usize = 0; + while (at < frames) : (at += 480) { + for (0..480) |i| { + piece[2 * i] = tone(at + i, 0, rate); + piece[2 * i + 1] = tone(at + i, 1, rate); + } + try group.write(&piece); + } + group.end(); + for (&received) |*r| try waitUntil(io, "the stream's end", r, ended); + + // PCM, as it went: every sample, every chunk 20 ms after the last. + const pcm = &received[0]; + try testing.expectEqual(message.Codec.pcm, pcm.format.?.codec); + try testing.expectEqual(@as(usize, 50), pcm.chunks.items.len); + var n: usize = 0; + for (pcm.chunks.items, 0..) |c, k| { + try testing.expectEqual(pcm.chunks.items[0].stamp + @as(i64, @intCast(k)) * 20_000, c.stamp); + var i: usize = 0; + while (i + 4 <= c.data.len) : (i += 4) { + const l = std.mem.readInt(i16, c.data[i..][0..2], .little); + const r = std.mem.readInt(i16, c.data[i + 2 ..][0..2], .little); + try testing.expectEqual(@as(i16, @intFromFloat(@round(tone(n, 0, rate) * 32768))), l); + try testing.expectEqual(@as(i16, @intFromFloat(@round(tone(n, 1, rate) * 32768))), r); + n += 1; + } + } + try testing.expectEqual(@as(usize, frames), n); + + // FLAC, decoded against its header: lossless, so exact at 24 bits. + const fl = &received[1]; + const header = try testing.allocator.alloc(u8, try std.base64.standard.Decoder.calcSizeForSlice(fl.header.?)); + defer testing.allocator.free(header); + try std.base64.standard.Decoder.decode(header, fl.header.?); + var header_reader: std.Io.Reader = .fixed(header); + var decoder = try flac.Decoder.init(testing.allocator, &header_reader, .{ .verify_md5 = false }); + defer decoder.deinit(); + try testing.expectEqual(@as(u32, rate), decoder.streaminfo.sample_rate); + n = 0; + for (fl.chunks.items) |c| { + var reader: std.Io.Reader = .fixed(c.data); + while (try decoder.decodeFrame(&reader, 0)) |frame| { + for (0..frame.header.block_size) |i| { + try testing.expectEqual(@as(i32, @intFromFloat(@round(@as(f64, tone(n, 0, rate)) * 8388608))), frame.channels[0][i]); + try testing.expectEqual(@as(i32, @intFromFloat(@round(@as(f64, tone(n, 1, rate)) * 8388608))), frame.channels[1][i]); + n += 1; + } + } + } + try testing.expectEqual(@as(usize, frames), n); + try testing.expectEqual(pcm.chunks.items[0].stamp, fl.chunks.items[0].stamp); + + // Opus: 50 packets, stamped back by the lookahead, and the tone there. + const op = &received[2]; + try testing.expectEqual(@as(usize, 50), op.chunks.items.len); + var od = try opus.Decoder.init(rate, 2); + var energy: f64 = 0; + var decoded: usize = 0; + var out: [2 * 960]f32 = undefined; + for (op.chunks.items) |c| { + const got = try od.decode(c.data, &out); + for (out[0 .. 2 * got]) |s| energy += s * s; + decoded += got; + } + try testing.expectEqual(@as(usize, frames), decoded); + // Each channel's tone is 0.5 in amplitude: mean square 0.125. + const mean_square = energy / @as(f64, @floatFromInt(2 * decoded)); + try testing.expect(@abs(10 * std.math.log10(mean_square / 0.125)) < 1.0); + try testing.expect(op.chunks.items[0].stamp < pcm.chunks.items[0].stamp); + try testing.expect(pcm.chunks.items[0].stamp - op.chunks.items[0].stamp < 20_000); + + // Resampled to 44.1 kHz: exactly as long, the same moment, the same tone. + const rs = &received[3]; + try testing.expectEqual(pcm.chunks.items[0].stamp, rs.chunks.items[0].stamp); + var samples: std.ArrayList(f32) = .empty; + defer samples.deinit(testing.allocator); + for (rs.chunks.items) |c| { + var i: usize = 0; + while (i + 4 <= c.data.len) : (i += 4) try samples.append(testing.allocator, @as(f32, @floatFromInt(std.mem.readInt(i16, c.data[i..][0..2], .little))) / 32768); + } + try testing.expectEqual(@as(usize, 44100), samples.items.len); + var err: f64 = 0; + for (samples.items[4410 .. 44100 - 4410], 4410..) |s, i| { + const want = tone(i, 0, 44100); + err += (s - want) * (s - want); + } + const rms = @sqrt(err / @as(f64, @floatFromInt(44100 - 2 * 4410))); + try testing.expect(20 * std.math.log10(rms / (0.5 / std.math.sqrt2)) < -60); +}