Something went wrong. Try again.
Sendspin in Zig, both sides: a player client for Music Assistant, and a server streaming to players in sync
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A Sendspin server: clients connect -- or are connected to -- and are//! served, in groups, whatever the program has for them.//!//! `serve` is one connection's life, on the task that calls it: the//! handshake, the hellos, the activation, and then everything the client//! says until it goes. `Listener` calls it for each client that dials in,//! and `connect` dials a client that listens and calls it too. The//! handshake is the same either way, the client speaking first://!//! - `client/init`, and the sealed protocol of aiosendspin 9.1, which Music//! Assistant 2.10 serves: the Noise handshake (see `secure`), with the//! server as its initiator, on the client's long-term PSK if the program's//! store has one for it, the sentinel if not; then `server/hello`,//! `client/hello` and `server/activate`, sealed;//! - or `client/hello`, and aiosendspin 4.4's unencrypted protocol, if//! `Options.allow_unencrypted`: `server/hello` grants the roles, and there//! is no activation.//!//! A client the handshake left on the sentinel -- never paired -- plays only//! as a guest: if it offers unpaired access and `Options.allow_guests`. One//! that does not is activated for nothing, and waits.//!//! A client joins the default group, and the program is told `onJoin`, once//! it is activated -- or, for a player, once its first `client/state` has//! come, which says the lead its audio needs. Until then there is nothing//! to stamp its audio by, and a stream started for it would only miss it.//!//! The clock is the server's own, `now`: `CLOCK_MONOTONIC` in microseconds.//! Each `client/time` is stamped as it arrives and answered through the//! connection's queue, stamped again as it goes.
const Server = @This();
const std = @import("std");const Io = std.Io;const noise = @import("noise");const sendspin = @import("sendspin");
const message = sendspin.message;const server_message = sendspin.server_message;const secure = sendspin.secure;const Session = sendspin.Session;const Client = sendspin.Client;const Connection = @import("Connection.zig");const Group = @import("Group.zig");
const log = std.log.scoped(.sendspin_server);
io: Io,gpa: std.mem.Allocator,options: Options,sink: Sink,
/// Held over the connections, the groups, and every connection's state and/// group; never while sending, which only queues.lock: Io.Mutex = .init,connections: std.ArrayList(*Connection) = .empty,groups: std.ArrayList(*Group) = .empty,/// Where every client starts.default_group: *Group = undefined,next_id: u64 = 1,
pub const Options = struct { /// What clients are told the server is called. name: []const u8, /// The server's identity: with one, it seals connections, and its /// public key is its id. Without one, only `allow_unencrypted` clients /// can connect. identity: ?noise.KeyPair = null, /// The long-term PSKs of the clients paired with the server. psks: ?secure.ServerPskStore = null, /// Whether a client never paired may play, if it offers to. allow_guests: bool = true, /// Whether to speak aiosendspin 4.4's unencrypted protocol to a client /// that opens with `client/hello`. allow_unencrypted: bool = false, /// The roles the server grants, of those a client offers. roles: Connection.Roles = .{ .player = true, .metadata = true, .controller = true, .artwork = true }, /// The largest message accepted. max_message: usize = 1 << 20, /// Told of every message as it goes by, as `Client.Options.trace` is. trace: ?Client.Trace = null, /// Where artwork comes from: the program renders it for each client's /// channel. artwork: ?ArtworkRenderer = null, /// Pairing with a dynamic PIN: with this, a sealed client not yet paired /// that offers it is asked to pair before anything else. pairing: ?Pairing = null, /// Told of every stream started and every chunk sent, for a program /// that watches what goes out. observer: ?Observer = null,};
/// What the streams send, as it goes: on the task writing the audio, or/// the connection's for a start made when a player joins or asks for/// another format.pub const Observer = struct { context: *anyopaque, /// `client` was told the format of its stream. onStart: *const fn (context: *anyopaque, client: *Connection, start: message.StreamStart) void = ignoreStart, /// A chunk, encoded in `format`, stamped `timestamp_us`, was sent to /// every player of that format. onChunk: *const fn (context: *anyopaque, format: message.Format, timestamp_us: i64, bytes: []const u8) void = ignoreChunk,
fn ignoreStart(_: *anyopaque, _: *Connection, _: message.StreamStart) void {} fn ignoreChunk(_: *anyopaque, _: message.Format, _: i64, _: []const u8) void {}};
/// What pairing needs of the program, on the connection's task.pub const Pairing = struct { context: *anyopaque, /// The PIN the player is showing, `digits` long, as a person types it /// in; null to give up. May wait as long as it takes. pin: *const fn (context: *anyopaque, client: *Connection, digits: u8) ?[]const u8, /// Keep `psk` as the long-term PSK for `client_id`, for good: the next /// handshake with that client is on it, through `Options.psks`. save: *const fn (context: *anyopaque, client_id: []const u8, psk: [32]u8) anyerror!void, /// Attempts before the connection goes on unpaired. attempts: u8 = 3,};
/// The program's pictures, at the size and in the format a client's channel/// asks for: scaled to fit `width` by `height`, what is left padded with/// black, never cropped, and encoded. An error sends nothing.pub const ArtworkRenderer = struct { context: *anyopaque, render: *const fn (context: *anyopaque, group: *Group, source: message.ArtworkSource, format: message.PictureFormat, width: u32, height: u32, out: *Io.Writer) anyerror!void,};
/// What the server tells the program, on the connection's task.pub const Sink = struct { context: *anyopaque, /// A client has connected and been activated, and is in the default /// group: a player once its first `client/state` has come. onJoin: *const fn (context: *anyopaque, client: *Connection) void = ignoreConnection, /// A client that joined has gone; this is the last of it. onLeave: *const fn (context: *anyopaque, client: *Connection) void = ignoreConnection, /// A client has said something new of itself: `client.state`. onState: *const fn (context: *anyopaque, client: *Connection) void = ignoreConnection, /// A controller has commanded its group. Volume and mute the server /// has already applied; the rest are the program's to carry out. onCommand: *const fn (context: *anyopaque, client: *Connection, command: message.ControllerCommand) void = ignoreCommand,
fn ignoreConnection(_: *anyopaque, _: *Connection) void {} fn ignoreCommand(_: *anyopaque, _: *Connection, _: message.ControllerCommand) void {}};
pub const Error = error{ /// A client opened with something other than `client/init` or, when /// allowed, `client/hello`. UnexpectedMessage, /// A client asked for a sealed connection and the server has no /// identity to seal it with. NoIdentity, /// An unsealed hello with no client id. NoClientId,};
/// The server's clock, in microseconds, as every timestamp it sends is.pub fn now() i64 { return sendspin.Scheduler.now();}
/// `self` must already be where it will stay: its groups point back at it.pub fn init(self: *Server, io: Io, gpa: std.mem.Allocator, options: Options, sink: Sink) !void { self.* = .{ .io = io, .gpa = gpa, .options = options, .sink = sink }; self.default_group = try self.createGroup("default", options.name);}
pub fn deinit(self: *Server) void { for (self.groups.items) |g| { g.deinit(); self.gpa.destroy(g); } self.groups.deinit(self.gpa); self.connections.deinit(self.gpa);}
/// A new group, with no clients yet. `id` and `name` are borrowed.pub fn createGroup(self: *Server, id: []const u8, name: []const u8) !*Group { const g = try self.gpa.create(Group); errdefer self.gpa.destroy(g); g.* = .{ .server = self, .id = id, .name = name, .metadata_arena = .init(self.gpa), .controller_arena = .init(self.gpa), }; self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); try self.groups.append(self.gpa, g); return g;}
/// Move `client` to `group`.pub fn move(self: *Server, client: *Connection, group: *Group) !void { { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); if (client.group) |from| { if (from == group) return; from.removeLocked(client); from.sendControllerLocked(); } try group.addLocked(client); group.sendControllerLocked(); } group.welcome(client);}
/// Dial a client that listens -- the protocol's other way of starting, the/// server connecting -- and serve it until it goes.pub fn connect(self: *Server, address: Session.Address) !void { const session = try self.gpa.create(Session); defer self.gpa.destroy(session); try Session.open(self.io, self.gpa, session, address, self.options.max_message); return self.serve(session);}
/// One connection, from its first message to its end, on the calling/// task. `session` is closed on return.pub fn serve(self: *Server, session: *Session) !void { const io = self.io; const gpa = self.gpa; var session_open = true; defer if (session_open) session.close(io);
const first = try receiveText(self, session); const kind = message.typeOf(first) orelse return error.UnexpectedMessage;
const conn = try gpa.create(Connection); var conn_owned = true; defer if (conn_owned) gpa.destroy(conn); conn.* = .{ .server = self, .session = session, .id = 0, .channel = null, .hello = undefined, .client_id = "", .paired = false, .arena = .init(gpa), .roles = .{}, .queue = undefined, }; var arena_owned = true; defer if (arena_owned) { if (conn.channel) |*ch| ch.deinit(); conn.arena.deinit(); }; const a = conn.arena.allocator();
if (std.mem.eql(u8, kind, "client/init")) { const identity = self.options.identity orelse return error.NoIdentity; var source: std.Random.IoSource = .{ .io = io }; var hs: secure.ServerHandshake = .init(gpa, identity, source.interface(), self.options.psks); defer hs.deinit(); const reply = try hs.clientInit(first); self.traceText(.outbound, false, reply.server_init); try session.sendText(reply.server_init); self.traceText(.outbound, false, reply.message_1); try session.sendText(reply.message_1); try hs.message2(try receiveText(self, session)); conn.channel = try secure.Channel.init(gpa, try hs.transport()); conn.paired = hs.category == .long_term; conn.client_id = try a.dupe(u8, &hs.client_id); conn.handshake_hash = hs.handshakeHash();
var buf: [512]u8 = undefined; var w: Io.Writer = .fixed(&buf); try server_message.writeHello(&w, self.options.name); try conn.writeText(w.buffered()); const hello_text = try receiveSealed(self, conn); conn.hello_text = try a.dupe(u8, hello_text); conn.hello = try parseHello(a, conn.hello_text); if (!conn.paired and conn.hello.dynamic_pin != null) if (self.options.pairing) |p| { conn.paired = try self.pair(conn, p, identity); }; } else if (std.mem.eql(u8, kind, "client/hello") and self.options.allow_unencrypted) { conn.hello_text = try a.dupe(u8, first); conn.hello = try parseHello(a, conn.hello_text); conn.client_id = conn.hello.client_id orelse return error.NoClientId; } else return error.UnexpectedMessage;
// What the client offers, and the server grants. const offered = conn.hello; const allowed = self.options.roles; const may_play = conn.channel == null or conn.paired or (offered.unpaired_access and self.options.allow_guests); if (may_play) conn.roles = .{ .player = allowed.player and offered.player != null, .metadata = allowed.metadata and offered.metadata, .controller = allowed.controller and offered.controller, .artwork = allowed.artwork and offered.artwork != null, };
conn.queue = .init(&conn.queue_buf); conn.writer = io.concurrent(Connection.writeLoop, .{conn}) catch |err| { log.err("could not start writing to {s}: {t}", .{ offered.name, err }); return err; }; // From here the connection is counted, and frees itself. conn_owned = false; arena_owned = false; session_open = false; defer self.finish(conn);
var roles_buf: [4][]const u8 = undefined; const roles = conn.roles.names(&roles_buf); var buf: [512]u8 = undefined; var w: Io.Writer = .fixed(&buf); if (conn.channel != null) { try server_message.writeActivate(&w, .{ .activities = if (may_play) &.{.playback} else &.{}, .active_roles = roles, }); } else { const id = if (self.options.identity) |i| &secure.peerId(i.public) else "sendspin-server"; try server_message.writeLegacyHello(&w, .{ .server_id = id, .name = self.options.name, .active_roles = roles }); } try conn.send(w.buffered());
{ self.lock.lockUncancelable(io); defer self.lock.unlock(io); conn.id = self.next_id; self.next_id += 1; try self.connections.append(gpa, conn); } log.info("{s} connected, {s}{s}", .{ offered.name, if (conn.channel != null) "sealed" else "unsealed", if (conn.paired) ", paired" else "" }); if (!conn.roles.player) try self.join(conn);
try self.readLoop(conn);}
/// Into the default group, and the program told. On `conn`'s task.fn join(self: *Server, conn: *Connection) !void { { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); try self.default_group.addLocked(conn); } conn.joined = true; self.default_group.welcome(conn); self.sink.onJoin(self.sink.context, conn);}
/// Pair `conn` with a dynamic PIN, attempt after attempt, before it is/// activated for anything else: the activation that asks, the PIN the/// program gets typed in, CPace, the client's new PSK kept, and the/// handshake run again on it with the hellos after. Whether it paired./// Everything is sent here, before the connection's writer starts: the/// re-handshake changes the keys between two messages.fn pair(self: *Server, conn: *Connection, p: Pairing, identity: noise.KeyPair) !bool { const gpa = self.gpa; var source: std.Random.IoSource = .{ .io = self.io }; const random = source.interface(); const digits: u8 = @max(conn.hello.dynamic_pin.?, sendspin.pairing.default_min_pin_digits); var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit();
var attempts: u8 = 0; attempt: while (attempts < p.attempts) : (attempts += 1) { out.clearRetainingCapacity(); try server_message.writeActivate(&out.writer, .{ .activities = &.{.pairing}, .active_roles = &.{}, .pairing = .{ .pin_length = digits } }); try conn.writeText(out.written()); var verifier: ?sendspin.pairing.Verifier = null; while (true) { const text = try receiveSealed(self, conn); _ = arena.reset(.retain_capacity); const v = std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), text, .{}) catch continue; const m = sendspin.pairing.parseClient(v) catch { try self.abortPairing(conn, .pin_mismatch); continue :attempt; } orelse continue; out.clearRetainingCapacity(); switch (m) { .init => |i| { verifier = try .start(random, &conn.handshake_hash, i.index, i.commit, digits, &out.writer); try conn.writeText(out.written()); log.info("pairing with {s}: waiting for the PIN", .{conn.hello.name}); const pin = p.pin(p.context, conn, digits) orelse { try self.abortPairing(conn, .user_cancelled); return false; }; out.clearRetainingCapacity(); try verifier.?.auth(random, pin, &out.writer); try conn.writeText(out.written()); }, .auth => |share| { const vf = &(verifier orelse continue :attempt); vf.onAuth(share, &out.writer) catch { try self.abortPairing(conn, .pin_mismatch); continue :attempt; }; try conn.writeText(out.written()); }, .confirm => |c| { const vf = &(verifier orelse continue :attempt); vf.onConfirm(c.tag, c.nonce_b) catch |err| { log.info("pairing with {s}: {t}", .{ conn.hello.name, err }); try self.abortPairing(conn, .pin_mismatch); continue :attempt; }; }, .finalize => |wrapped| { const vf = &(verifier orelse continue :attempt); const psk = vf.onFinalize(wrapped, &out.writer) catch { try self.abortPairing(conn, .pin_mismatch); continue :attempt; }; try p.save(p.context, conn.client_id, psk); try conn.writeText(out.written()); try self.rehandshake(conn, identity, psk); log.info("paired with {s}", .{conn.hello.name}); return true; }, // Waiting for a gesture on the player, or given up: this // attempt is over, and the next activation says what next. .pending => { try self.abortPairing(conn, .attempt_timeout); continue :attempt; }, .abort => |reason| { log.info("pairing with {s}: the client abandoned it, {?t}", .{ conn.hello.name, reason }); continue :attempt; }, } } } return false;}
fn abortPairing(self: *Server, conn: *Connection, reason: sendspin.pairing.AbortReason) !void { _ = self; var buf: [96]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sendspin.pairing.writeAbort(&w, reason); try conn.writeText(w.buffered());}
/// The handshake again, inside the channel, on the PSK pairing made: message/// 1 sealed under the old keys, message 2 opened with them, then the new/// keys both ways, and the hellos again under them.fn rehandshake(self: *Server, conn: *Connection, identity: noise.KeyPair, psk: [32]u8) !void { var source: std.Random.IoSource = .{ .io = self.io }; var hs: secure.ServerHandshake = try .initRehandshake(self.gpa, identity, source.interface(), conn.client_id[0..secure.peer_id_len].*, &conn.handshake_hash, psk); defer hs.deinit(); try conn.writeText(hs.message1Sealed()); try hs.message2(try receiveSealed(self, conn)); conn.channel.?.transport = try hs.transport(); conn.handshake_hash = hs.handshakeHash();
var buf: [512]u8 = undefined; var w: Io.Writer = .fixed(&buf); try server_message.writeHello(&w, self.options.name); try conn.writeText(w.buffered()); conn.hello_text = try conn.arena.allocator().dupe(u8, try receiveSealed(self, conn)); conn.hello = try parseHello(conn.arena.allocator(), conn.hello_text);}
/// Everything the client says until it goes.fn readLoop(self: *Server, conn: *Connection) !void { var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); while (true) { const text = receiveSealed(self, conn) catch |err| switch (err) { error.ConnectionClosed => return, else => return err, }; const received = now(); _ = arena.reset(.retain_capacity); const a = arena.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch continue; const incoming = server_message.classifyClient(a, v) catch continue; switch (incoming) { .time => |t| conn.put(.{ .time = .{ .client_transmitted = t, .server_received = received } }) catch return, .state => |s| { { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); applyState(&conn.state, s); conn.state_seen.store(true, .release); // A player's volume is part of the group's. if (s.player != null) if (conn.group) |g| g.sendControllerLocked(); } if (!conn.joined) try self.join(conn); self.sink.onState(self.sink.context, conn); }, .command => |c| { if (!conn.roles.controller) continue; try self.command(conn, c); self.sink.onCommand(self.sink.context, conn, c); }, .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; }, .hello, .other => {}, } }}
/// What the server does of a controller's command itself: the group's/// volume and mute, and moving to the next group.fn command(self: *Server, conn: *Connection, c: message.ControllerCommand) !void { var next: ?*Group = null; { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); const g = conn.group orelse return; switch (c) { .volume => |v| g.setVolumeLocked(v), .mute => |m| g.setMuteLocked(m), .@"switch" => { // The next group in the order they were made, round. const at = std.mem.findScalar(*Group, self.groups.items, g) orelse return; if (self.groups.items.len > 1) next = self.groups.items[(at + 1) % self.groups.items.len]; }, else => {}, } } if (next) |g| try self.move(conn, g);}
fn applyState(state: *Connection.State, s: server_message.ClientState) void { if (s.available) |av| state.available = av; const p = s.player orelse return; if (p.volume) |v| state.volume = v; if (p.muted) |m| state.muted = m; if (p.static_delay_ms) |d| state.static_delay_ms = d; if (p.required_lead_time_ms) |d| state.required_lead_time_ms = d; if (p.min_buffer_ms) |d| state.min_buffer_ms = d;}
/// The end of a connection: out of its group and the list, the program/// told, the writer finished, and the server's count of it dropped.fn finish(self: *Server, conn: *Connection) void { { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); if (conn.group) |g| g.removeLocked(conn); for (self.connections.items, 0..) |c, i| if (c == conn) { _ = self.connections.swapRemove(i); break; }; } if (conn.id != 0) log.info("{s} disconnected", .{conn.hello.name}); if (conn.joined) self.sink.onLeave(self.sink.context, conn); conn.close(); // A writer blocked on a client that stopped reading is woken by the // socket going; one that is not finishes what was queued first. conn.session.shutdown(self.io); if (conn.writer) |*f| f.cancel(self.io); conn.session.close(self.io); conn.release();}
fn parseHello(a: std.mem.Allocator, text: []const u8) !server_message.ClientHello { const v = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch return error.UnexpectedMessage; return switch (try server_message.classifyClient(a, v)) { .hello => |h| h, else => error.UnexpectedMessage, };}
/// The next text frame, before any sealing; the handshake's.fn receiveText(self: *Server, session: *Session) ![]const u8 { const m = (try session.receive()) orelse return error.ConnectionClosed; if (m.kind != .text) return error.UnexpectedMessage; self.traceText(.inbound, false, m.data); return m.data;}
/// The next text message, opened from the channel on a sealed connection;/// binary messages -- a source role's audio -- are passed over.fn receiveSealed(self: *Server, conn: *Connection) ![]const u8 { while (try conn.session.receive()) |m| { if (conn.channel) |*ch| { if (m.kind != .binary) return error.UnexpectedMessage; const opened = (try ch.open(m.data)) orelse continue; switch (opened) { .text => |t| { self.traceText(.inbound, true, t); return t; }, .binary => |b| self.traceBinary(.inbound, true, b), } } else switch (m.kind) { .text => { self.traceText(.inbound, false, m.data); return m.data; }, .binary => self.traceBinary(.inbound, false, m.data), } } return error.ConnectionClosed;}
pub fn traceText(self: *Server, direction: Client.Direction, sealed: bool, text: []const u8) void { const t = self.options.trace orelse return; t.event(t.context, .{ .direction = direction, .frame = if (sealed) .binary else .text, .sealed = sealed, .type = message.typeOf(text) orelse "", });}
pub fn traceBinary(self: *Server, direction: Client.Direction, sealed: bool, data: []const u8) void { const t = self.options.trace orelse return; t.event(t.context, .{ .direction = direction, .frame = .binary, .sealed = sealed, .type = "", .binary_type = if (data.len > 0) data[0] else null, .timestamp_us = if (message.parseBinary(data)) |b| b.timestamp_us else |_| null, });}