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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Where a Sendspin server connects to this player: the protocol's other way//! of starting, in which the player listens -- on 8928 at `/sendspin` by//! convention, found by mDNS as `_sendspin._tcp` -- and the server dials it.//!//! An HTTP server, zig-http's, with one resource: a WebSocket at the path,//! each connection to which is handed to `Client.serve`. The handshake on it//! is the one `Client.run` does, the client still speaking first. One//! connection at a time, since a client has one: a server that dials while//! another is connected is answered `503 Service Unavailable`.//!//! Advertising the player by mDNS is not done here.//!//! A module of its own, `sendspin_listener`, whose root this is, so that a//! player that only dials out does not take an HTTP server with it.//!//! ```zig//! const Listener = @import("sendspin_listener");//! var listener: Listener = undefined;//! try listener.init(io, gpa, &client, .{ .address = try .parse("0.0.0.0", 8928) });//! defer listener.deinit();//! try listener.run(); // until canceled//! ```
const Listener = @This();
const std = @import("std");const Io = std.Io;const http = @import("http");const http_io = @import("http_io");const wss = @import("websocket_server");
const sendspin = @import("sendspin");const Client = sendspin.Client;const Session = sendspin.Session;
const log = std.log.scoped(.sendspin);
pub const Options = struct { /// Where to listen. Port zero has the kernel choose one, which /// `localAddress` then reports. address: Io.net.IpAddress, /// The resource the WebSocket is at. path: []const u8 = "/sendspin", /// The largest message accepted, as `Client.Options.max_message`. max_message: usize = 1 << 20,};
io: Io,gpa: std.mem.Allocator,client: *Client,options: Options,tcp: http_io.tcp.Listener,server: http.server.Server,/// Held while a connection is being served.busy: Io.Mutex = .init,
/// Start listening. `self` must already be where it will stay, since the/// server points back at it; `client` and `options.path` are borrowed and/// must outlive it.pub fn init(self: *Listener, io: Io, gpa: std.mem.Allocator, client: *Client, options: Options) !void { self.* = .{ .io = io, .gpa = gpa, .client = client, .options = options, .tcp = try http_io.tcp.Listener.listen(io, options.address, .{}), .server = undefined, }; // HTTP/2 needs a task for each stream; a player's server never speaks // it, and one WebSocket at a time needs no more than HTTP/1.1. self.server = .init(io, gpa, self.tcp.listener(), .init(self, handle), .{ .http2 = null });}
pub fn deinit(self: *Listener) void { self.tcp.deinit(self.io);}
/// Where it is listening; after binding port zero, with the port chosen.pub fn localAddress(self: *const Listener) Io.net.IpAddress { return self.tcp.localAddress();}
/// Serve connections until canceled.pub fn run(self: *Listener) !void { try self.server.serve();}
fn handle(self: *Listener, req: *http.server.Request, res: *http.server.Response) anyerror!void { if (!std.mem.eql(u8, req.target.path, self.options.path)) return res.sendStatus(.not_found); if (!self.busy.tryLock()) { log.info("a Sendspin server connected while another is; refused", .{}); return res.sendStatus(.service_unavailable); } defer self.busy.unlock(self.io);
const buffer = try self.gpa.alloc(u8, self.options.max_message); defer self.gpa.free(buffer); var session: Session = undefined; session.write_mutex = .init; const ws = wss.accept(req, res, .{ .buffer = buffer, .connection = .{ .write_lock = .{ .io = self.io, .mutex = &session.write_mutex } }, }) catch |err| return wss.refuse(res, err); session.accepted(self.gpa, ws); log.info("a Sendspin server connected", .{}); self.client.serve(&session) catch |err| switch (err) { error.Canceled => return error.Canceled, else => {}, };}
const testing = std.testing;const message = sendspin.message;const websocket = @import("websocket");
/// What the client under test hands its sink, counted.const Recorder = struct { starts: std.atomic.Value(u32) = .init(0), chunks: std.atomic.Value(u32) = .init(0), ended: std.atomic.Value(bool) = .init(false),
fn sink(self: *Recorder) Client.Sink { return .{ .context = self, .onStreamStart = onStreamStart, .onAudio = onAudio, .onStreamClear = ignore, .onStreamEnd = ignore, .onClock = onClock, .onDisconnected = onDisconnected, }; } fn onStreamStart(context: *anyopaque, _: message.StreamStart) void { const self: *Recorder = @ptrCast(@alignCast(context)); _ = self.starts.fetchAdd(1, .monotonic); } fn onAudio(context: *anyopaque, timestamp_us: i64, data: []const u8) void { const self: *Recorder = @ptrCast(@alignCast(context)); if (timestamp_us == 1_000_000 and data.len == 4) _ = self.chunks.fetchAdd(1, .monotonic); } fn ignore(_: *anyopaque) void {} fn onClock(_: *anyopaque, _: sendspin.TimeFilter) void {} fn onDisconnected(context: *anyopaque, _: anyerror) void { const self: *Recorder = @ptrCast(@alignCast(context)); self.ended.store(true, .monotonic); }};
/// The next text message's type, from the server's end.fn nextType(session: *Session) ![]const u8 { while (try session.receive()) |m| { if (m.kind == .text) return message.typeOf(m.data) orelse ""; } return error.ConnectionClosed;}
fn waitFor(io: Io, flag: anytype, want: anytype) !void { for (0..500) |_| { if (flag.load(.monotonic) == want) return; try io.sleep(.fromMilliseconds(10), .awake); } return error.TimedOut;}
test "a server connects to the player, and the client speaks first" { const gpa = testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
const formats = [_]message.Format{.{ .codec = .pcm, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }}; var recorder: Recorder = .{}; // No identity, so unsealed: what goes by can be read here. A token, // which is for a proxy the client dials through and so never sent on a // connection the server opened: the hello comes first regardless. var client: Client = .init(io, gpa, .{ .address = .{ .hostname = "unused" }, .token = "for-the-proxy", .hello = .{ .client_id = "player", .name = "Player", .formats = &formats, .buffer_capacity = 1 << 16 }, }, recorder.sink());
var listener: Listener = undefined; try listener.init(io, gpa, &client, .{ .address = try .parse("127.0.0.1", 0) }); defer listener.deinit(); var serving = try io.concurrent(Listener.run, .{&listener}); defer serving.cancel(io) catch {};
// The server's end, dialing the player. var server: Session = undefined; try Session.open(io, gpa, &server, .{ .hostname = "127.0.0.1", .port = listener.localAddress().getPort(), }, 1 << 16); defer server.close(io);
try testing.expectEqualStrings("client/hello", try nextType(&server)); try server.sendText( \\{"type":"server/hello","payload":{"server_id":"s","name":"Server","version":1,"active_roles":["player@v1"]}} ); try testing.expectEqualStrings("client/state", try nextType(&server));
try server.sendText( \\{"type":"stream/start","payload":{"player":{"codec":"pcm","sample_rate":48000,"channels":2,"bit_depth":16}}} ); var frame: [message.binary_header_len + 4]u8 = undefined; frame[0] = @intFromEnum(message.BinaryType.audio); std.mem.writeInt(i64, frame[1..9], 1_000_000, .big); @memcpy(frame[9..], &[_]u8{ 1, 2, 3, 4 }); try server.sendBinary(&frame); try waitFor(io, &recorder.chunks, 1); try testing.expectEqual(1, recorder.starts.load(.monotonic));
// A second server, while the first is connected, is turned away. { const address = listener.localAddress(); const stream = try address.connect(io, .{ .mode = .stream }); defer stream.close(io); var read_buf: [4096]u8 = undefined; var write_buf: [4096]u8 = undefined; var reader = stream.reader(io, &read_buf); var writer = stream.writer(io, &write_buf); var buffer: [1024]u8 = undefined; var random: std.Random.IoSource = .{ .io = io }; var status: u16 = 0; try testing.expectError(error.NotSwitchingProtocols, websocket.connect(&reader.interface, &writer.interface, .{ .resource = "/sendspin", .host = "127.0.0.1", .buffer = &buffer, .random = random.interface(), .status = &status, })); try testing.expectEqual(503, status); }
// The server goes, and so does the connection. server.shutdown(io); try waitFor(io, &recorder.ended, true);}