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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Join a server as a player, and say what arrives.//!//! ```console//! $ SENDSPIN_TOKEN=... sendspin-probe media01 [seconds]//! ```//!//! It connects through Music Assistant's proxy with the token (or directly,//! without one), registers as a player called "sendspin-probe", and plays//! into nothing: a pretend audio device takes 20 ms of samples from the//! scheduler every 20 ms, which is enough to see whether the audio arrives,//! how far ahead, and whether it stays in step. Once a second it prints the//! clock estimate, what is buffered, the scheduler's counters and the level//! of what was "played".//!//! With `SENDSPIN_IDENTITY_FILE` naming a file, the connection is sealed, as//! aiosendspin 9 expects: the probe's key is kept in that file, made the//! first time, so that the server sees the same player each run. Without//! it, the probe speaks the unencrypted protocol.//!//! With `SENDSPIN_OPUS` set, to anything, it asks for Opus first rather//! than FLAC.//!//! With `SENDSPIN_PAIRINGS` naming a file as well, it offers to pair with a//! dynamic PIN, prints the PIN when a server asks (`pin: 123456`), and keeps//! the long-term PSKs it makes there, one line per server.//!//! With `SENDSPIN_RATE_FILE` naming a file, it looks there once a second for//! a sample rate, and when one appears it behaves as a sound card that has//! changed rate: its pretend device runs at the new rate, and it offers the//! server formats at it, which takes a new connection.//!//! With `SENDSPIN_LISTEN` naming a port, it does not dial: it waits there to//! be dialed, and advertises itself by mDNS as `_sendspin._tcp` for a server//! to find -- through Avahi if Avahi will, or answering mDNS itself -- which//! is how Music Assistant finds a player nobody told it about. The server//! argument is then ignored.
const std = @import("std");const Io = std.Io;const sendspin = @import("sendspin");const Listener = @import("sendspin_listener");const discovery = @import("sendspin_discovery");const noise = @import("noise");
const rate = 48000;const max_rate = 192000;
pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa;
var args = try init.minimal.args.iterateAllocator(gpa); defer args.deinit(); _ = args.skip(); const server = args.next() orelse { std.debug.print("usage: sendspin-probe HOST[:PORT] [SECONDS]\n", .{}); return error.Usage; }; const seconds = if (args.next()) |s| try std.fmt.parseInt(u32, s, 10) else 60;
var address: sendspin.Client.Address = .{ .hostname = server }; if (std.mem.lastIndexOfScalar(u8, server, ':')) |i| { address.hostname = server[0..i]; address.port = try std.fmt.parseInt(u16, server[i + 1 ..], 10); }
var scheduler: sendspin.Scheduler = .init(gpa, .{}); defer scheduler.deinit(); var player: sendspin.Player = .init(gpa, &scheduler); defer player.deinit(); var report: Report = .{}; player.observer = report.sink();
const identity: ?noise.KeyPair = if (init.environ_map.get("SENDSPIN_IDENTITY_FILE")) |path| try loadIdentity(io, path) else null; if (identity) |i| std.debug.print("encrypted, as {s}\n", .{&sendspin.secure.peerId(i.public)});
var pairings: Pairings = .{ .io = io, .gpa = gpa, .path = init.environ_map.get("SENDSPIN_PAIRINGS") orelse "" }; const pairing: ?sendspin.Client.Pairing = if (pairings.path.len > 0 and identity != null) .{ .context = &pairings, .lookup = Pairings.lookup, .save = Pairings.save, .show_pin = Pairings.showPin, } else null;
const formats = sendspin.Player.formats(rate, if (init.environ_map.get("SENDSPIN_OPUS") != null) .opus else .lossless); var client: sendspin.Client = .init(io, gpa, .{ .address = address, .token = init.environ_map.get("SENDSPIN_TOKEN"), .hello = .{ .client_id = "sendspin-probe", .name = "sendspin-probe", .device_info = .{ .product_name = "sendspin-probe", .software_version = "0.0.0" }, .formats = formats.slice(), .buffer_capacity = rate * 2 * 3 * 5, }, .identity = identity, .pairing = pairing, }, player.sink());
// Dialing out, or dialed: listening, and advertised by mDNS for a // server to find. const listen_port: ?u16 = if (init.environ_map.get("SENDSPIN_LISTEN")) |p| try std.fmt.parseInt(u16, p, 10) else null; // Torn down in the reverse of this order: the task first, then the // listener it was serving, then the advertisement. var advertiser: ?*discovery.Advertiser = null; defer if (advertiser) |a| a.stop(); var listener: Listener = undefined; if (listen_port) |port| try listener.init(io, gpa, &client, .{ .address = try .parse("0.0.0.0", port) }); defer if (listen_port != null) listener.deinit(); if (listen_port) |port| { const id = if (identity) |i| &sendspin.secure.peerId(i.public) else "sendspin-probe"; advertiser = try discovery.Advertiser.start(io, gpa, init.minimal.environ, .{ .kind = .player, .instance = id, .name = "sendspin-probe", .port = port }); std.debug.print("listening on {d}, advertised through {t}\n", .{ port, advertiser.?.backend() }); } var runner = if (listen_port != null) try io.concurrent(runListener, .{&listener}) else try io.concurrent(runClient, .{&client}); defer runner.cancel(io) catch {};
// Room for a period at the highest rate a rate file may ask for. var left_buf: [max_rate / 50]f32 = undefined; var right_buf: [max_rate / 50]f32 = undefined; var device_rate: u32 = rate; var changed_formats: sendspin.Player.Formats = undefined; const rate_file = init.environ_map.get("SENDSPIN_RATE_FILE"); var sum_squares: f64 = 0; var samples: u64 = 0; var tick: u32 = 0; // Cycles on an absolute schedule, as a sound card's clock would run: // sleeping 20 ms at a time would overshoot a little every cycle, and the // scheduler would spend its time correcting for a device that runs slow. const start = sendspin.Scheduler.now(); for (0..seconds * 50) |cycle| { const due = start + @as(i64, @intCast(cycle + 1)) * 20_000; const wait = due - sendspin.Scheduler.now(); if (wait > 0) try io.sleep(.fromMicroseconds(wait), .awake); const period = device_rate / 50; const left = left_buf[0..period]; const planes = [_][]f32{ left, right_buf[0..period] }; _ = scheduler.fill(&planes, period, due); for (left) |s| sum_squares += s * s; samples += left.len; tick += 1; if (tick == 50) { tick = 0; if (rate_file) |path| if (readRate(io, path)) |new_rate| if (new_rate != device_rate) { device_rate = new_rate; changed_formats = sendspin.Player.formats(new_rate, if (init.environ_map.get("SENDSPIN_OPUS") != null) .opus else .lossless); std.debug.print("device rate now {d} Hz\n", .{new_rate}); client.setFormats(changed_formats.slice()) catch |err| std.debug.print("could not change formats: {t}\n", .{err}); }; const rms = @sqrt(sum_squares / @as(f64, @floatFromInt(samples))); sum_squares = 0; samples = 0; const c = scheduler.stats(); std.debug.print( "clock ±{d} µs buffered {d} ms level {d:.3} locks {d} underruns {d} late {d} corrections {d}\n", .{ client.clock.errorUs(), @divTrunc(scheduler.bufferedUs(), 1000), rms, c.locks, c.underruns, c.late_frames, c.corrections, }, ); } }}
fn runClient(client: *sendspin.Client) anyerror!void { return client.run();}
fn runListener(listener: *Listener) anyerror!void { return listener.run();}
/// The long-term PSKs, in a file: a line for each server, its id and the/// PSK in base64url.const Pairings = struct { io: Io, gpa: std.mem.Allocator, path: []const u8,
const b64 = std.base64.url_safe_no_pad;
fn from(context: *anyopaque) *Pairings { return @ptrCast(@alignCast(context)); }
fn read(self: *Pairings, buf: []u8) []const u8 { return Io.Dir.cwd().readFile(self.io, self.path, buf) catch ""; }
fn lookup(context: *anyopaque, psk_id: []const u8, server_id: []const u8) ?[32]u8 { const self = from(context); var buf: [4096]u8 = undefined; var lines = std.mem.tokenizeScalar(u8, self.read(&buf), '\n'); while (lines.next()) |line| { var fields = std.mem.tokenizeScalar(u8, line, ' '); const server = fields.next() orelse continue; const encoded = fields.next() orelse continue; if (!std.mem.eql(u8, server, server_id)) continue; var psk: [32]u8 = undefined; b64.Decoder.decode(&psk, encoded) catch continue; if (std.mem.eql(u8, &sendspin.secure.pskId(psk), psk_id)) return psk; } return null; }
fn save(context: *anyopaque, server_id: []const u8, psk: [32]u8) anyerror!void { const self = from(context); var buf: [4096]u8 = undefined; var out: std.Io.Writer.Allocating = .init(self.gpa); defer out.deinit(); var lines = std.mem.tokenizeScalar(u8, self.read(&buf), '\n'); while (lines.next()) |line| { if (std.mem.startsWith(u8, line, server_id) and line.len > server_id.len and line[server_id.len] == ' ') continue; try out.writer.print("{s}\n", .{line}); } var encoded: [43]u8 = undefined; try out.writer.print("{s} {s}\n", .{ server_id, b64.Encoder.encode(&encoded, &psk) }); try Io.Dir.cwd().writeFile(self.io, .{ .sub_path = self.path, .data = out.written(), .flags = .{ .permissions = .fromMode(0o600) } }); std.debug.print("paired with {s}\n", .{server_id}); }
fn showPin(_: *anyopaque, pin: ?[]const u8) void { if (pin) |p| std.debug.print("pin: {s}\n", .{p}) else std.debug.print("pin gone\n", .{}); }};
/// A rate asked for in `path`, if there is one there it can run at.fn readRate(io: Io, path: []const u8) ?u32 { var buf: [16]u8 = undefined; const text = Io.Dir.cwd().readFile(io, path, &buf) catch return null; const r = std.fmt.parseInt(u32, std.mem.trim(u8, text, " \n"), 10) catch return null; return if (r >= 8000 and r <= max_rate) r else null;}
/// The key kept at `path`, as base64url of the secret; made and written the/// first time.fn loadIdentity(io: Io, path: []const u8) !noise.KeyPair { const b64 = std.base64.url_safe_no_pad; var buf: [128]u8 = undefined; if (Io.Dir.cwd().readFile(io, path, &buf)) |text| { var secret: [32]u8 = undefined; try b64.Decoder.decode(&secret, std.mem.trim(u8, text, " \n")); return noise.KeyPair.fromSecret(secret); } else |err| if (err != error.FileNotFound) return err; var source: std.Random.IoSource = .{ .io = io }; const pair = noise.KeyPair.generate(source.interface()); var out: [43]u8 = undefined; _ = b64.Encoder.encode(&out, &pair.secret); try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = &out, .flags = .{ .permissions = .fromMode(0o600) } }); return pair;}
/// Prints what happens, as it happens.const Report = struct { fn sink(self: *Report) sendspin.Client.Sink { return .{ .context = self, .onConnected = onConnected, .onStreamStart = onStreamStart, .onAudio = onAudio, .onStreamClear = onStreamClear, .onStreamEnd = onStreamEnd, .onCommand = onCommand, .onClock = onClock, .onPlayback = onPlayback, .onDisconnected = onDisconnected, }; }
fn onConnected(_: *anyopaque, hello: sendspin.message.ServerHello) void { std.debug.print("connected to {s} ({s}){s}\n", .{ hello.name, hello.server_id, if (hello.paired) ", paired" else "" }); } fn onStreamStart(_: *anyopaque, f: sendspin.message.StreamStart) void { std.debug.print("stream: {t} {d} Hz, {d} bit, {d} channels\n", .{ f.codec, f.sample_rate, f.bit_depth, f.channels }); } fn onAudio(_: *anyopaque, _: i64, _: []const u8) void {} fn onStreamClear(_: *anyopaque) void { std.debug.print("stream cleared\n", .{}); } fn onStreamEnd(_: *anyopaque) void { std.debug.print("stream ended\n", .{}); } fn onCommand(_: *anyopaque, c: sendspin.message.Command) void { switch (c) { .volume => |v| std.debug.print("volume {d}\n", .{v}), .mute => |m| std.debug.print("mute {}\n", .{m}), } } fn onClock(_: *anyopaque, _: sendspin.TimeFilter) void {} fn onPlayback(_: *anyopaque, s: ?sendspin.message.PlaybackState) void { if (s) |state| std.debug.print("group {t}\n", .{state}); } fn onDisconnected(_: *anyopaque, reason: anyerror) void { std.debug.print("disconnected: {t}\n", .{reason}); }};