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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Sendspin by mDNS: advertising a player or a server, and finding players.//!//! The names are aiosendspin's, which Music Assistant speaks://!//! - a player waiting to be dialed advertises `_sendspin._tcp`, its instance//! named for its client id, with TXT `name` and `path` -- and a server//! finds it there and dials `ws://address:port/path`. aiosendspin ignores//! a player whose TXT has no `path`;//! - a server advertises `_sendspin-server._tcp`, with TXT `name` and `path`.//!//! **Where it is said from.** The system's Avahi daemon, if there is one and//! it lets this user publish, through zig-avahi on the system bus: it holds//! port 5353 and the host's name already, and handles conflicts and changes//! of network. Otherwise -- no daemon, or one with user publishing off, as//! NixOS has it unless `services.avahi.publish.userServices` is on -- an//! mDNS responder of its own, zig-dns-client's, which answers for a host//! name of its own, `<host>.local`. Finding goes the same way: Avahi's//! browser if Avahi is there, zig-dns-client's monitor if not.//!//! A module of its own, so that a player or server that has no use for it//! does not take D-Bus and a DNS library with it.
const std = @import("std");const Io = std.Io;const sendspin = @import("sendspin");const avahi = @import("avahi");const dns_client = @import("dns_client");
const mdns = dns_client.mdns;const log = std.log.scoped(.sendspin_discovery);
/// Where a player waiting to be dialed is advertised.pub const player_type = "_sendspin._tcp";/// Where a server is advertised.pub const server_type = "_sendspin-server._tcp";/// The port a player listens on, by convention; a server's is 8927.pub const player_port = 8928;pub const server_port = 8927;
/// Which does the talking.pub const Backend = enum { /// The system's Avahi daemon. avahi, /// zig-dns-client's own responder or monitor. native,};
/// Whether to try Avahi first, or use only one.pub const Prefer = enum { auto, avahi, native };
fn RunFuture(comptime f: anytype) type { return Io.Future(@typeInfo(@TypeOf(f)).@"fn".return_type.?);}
/// A label that can be a host's name -- letters, digits and hyphens, lower/// case, at most 63 -- made from `text`, into `buf`.pub fn hostLabel(buf: *[63]u8, text: []const u8) []const u8 { var n: usize = 0; var hyphen = true; for (text) |c| { if (n == buf.len) break; if (std.ascii.isAlphanumeric(c)) { buf[n] = std.ascii.toLower(c); n += 1; hyphen = false; } else if (!hyphen) { buf[n] = '-'; n += 1; hyphen = true; } } while (n > 0 and buf[n - 1] == '-') n -= 1; if (n == 0) { @memcpy(buf[0..8], "sendspin"); n = 8; } return buf[0..n];}
/// Something advertised, for as long as it is kept.pub const Advertiser = struct { io: Io, gpa: std.mem.Allocator, state: union(Backend) { avahi: struct { client: *avahi.Client, group: *avahi.Client.EntryGroup, running: RunFuture(avahi.Client.run) }, native: struct { responder: *mdns.Responder, service: *mdns.responder.Service, running: RunFuture(mdns.Responder.run) }, },
pub const Kind = enum { player, server };
pub const Options = struct { kind: Kind, /// The instance's name: a player's client id, a server's name. instance: []const u8, /// The friendly name, for TXT `name`. name: []const u8, port: u16, path: []const u8 = "/sendspin", /// The host label the native responder answers for, `<host>.local`; /// made from `instance` if null. Avahi uses the host's own name. host: ?[]const u8 = null, prefer: Prefer = .auto, };
/// Advertise, through Avahi if it will, else through a responder of its /// own. `environ` is for finding the system bus. pub fn start(io: Io, gpa: std.mem.Allocator, environ: std.process.Environ, options: Options) !*Advertiser { const self = try gpa.create(Advertiser); errdefer gpa.destroy(self); self.* = .{ .io = io, .gpa = gpa, .state = undefined };
var name_buf: [300]u8 = undefined; var path_buf: [300]u8 = undefined; const txt = [_][]const u8{ std.fmt.bufPrint(&name_buf, "name={s}", .{options.name}) catch return error.NameTooLong, std.fmt.bufPrint(&path_buf, "path={s}", .{options.path}) catch return error.PathTooLong, }; const service_type = switch (options.kind) { .player => player_type, .server => server_type, };
if (options.prefer != .native) via_avahi: { const client = avahi.Client.connect(io, gpa, environ) catch |err| { if (options.prefer == .avahi) return err; log.info("no Avahi daemon to advertise through ({t}); answering mDNS here", .{err}); break :via_avahi; }; const group = client.publish(.{ .name = options.instance, .type = service_type, .port = options.port, .txt = &txt }) catch |err| { client.deinit(); if (options.prefer == .avahi) return err; log.info("Avahi will not publish for this user ({t}); answering mDNS here", .{err}); break :via_avahi; }; const running = io.concurrent(avahi.Client.run, .{client}) catch |err| { client.deinit(); return err; }; self.state = .{ .avahi = .{ .client = client, .group = group, .running = running } }; log.info("advertising {s} as {s} through Avahi", .{ service_type, options.instance }); return self; }
var host_buf: [63]u8 = undefined; const host = options.host orelse hostLabel(&host_buf, options.instance); const responder = try mdns.Responder.init(io, gpa, .{ .host = host }); errdefer responder.deinit(); const service = try responder.add(.{ .instance = options.instance, .type = service_type, .port = options.port, .txt = &txt }); const running = try io.concurrent(mdns.Responder.run, .{responder}); self.state = .{ .native = .{ .responder = responder, .service = service, .running = running } }; log.info("advertising {s} as {s} on {s}.local", .{ service_type, options.instance, host }); return self; }
pub fn backend(self: *const Advertiser) Backend { return self.state; }
/// Withdraw it -- goodbyes on the network -- and free everything. pub fn stop(self: *Advertiser) void { switch (self.state) { .avahi => |*a| { a.client.stop(); _ = a.running.await(self.io) catch {}; a.client.deinit(); }, .native => |*n| { n.responder.stop(); _ = n.running.await(self.io) catch {}; n.responder.deinit(); }, } self.gpa.destroy(self); }};
/// A player found: where to dial it. Borrowed for the length of the call.pub const Player = struct { /// Its instance's name: its client id, by convention. instance: []const u8, /// TXT `name`, if it has one. name: ?[]const u8, address: [4]u8, port: u16, /// TXT `path`. path: []const u8,
/// Where `Server.connect` dials it; `buf` holds the address's text. pub fn sessionAddress(self: Player, buf: *[15]u8) sendspin.Session.Address { const host = std.fmt.bufPrint(buf, "{d}.{d}.{d}.{d}", .{ self.address[0], self.address[1], self.address[2], self.address[3] }) catch unreachable; return .{ .hostname = host, .port = self.port, .resource = self.path }; }};
/// What a `Finder` tells the program.pub const Handler = struct { context: *anyopaque, /// A player, resolved -- once, or again for each link and each time it /// changes: the program keeps its own account of whom it has dialed. found: *const fn (context: *anyopaque, player: *const Player) void, /// A player's service gone. A connection to it ends on its own. lost: *const fn (context: *anyopaque, instance: []const u8) void,};
/// Finding players: `_sendspin._tcp`, resolved to IPv4 -- aiosendspin's/// own discovery takes nothing else -- and a player without a `path` left/// out, as aiosendspin leaves it out.pub const Finder = struct { io: Io, gpa: std.mem.Allocator, handler: Handler, state: union(Backend) { avahi: struct { client: *avahi.Client, running: RunFuture(avahi.Client.run) }, native: struct { monitor: *mdns.Monitor, running: RunFuture(mdns.Monitor.run) }, },
pub fn start(io: Io, gpa: std.mem.Allocator, environ: std.process.Environ, handler: Handler, prefer: Prefer) !*Finder { const self = try gpa.create(Finder); errdefer gpa.destroy(self); self.* = .{ .io = io, .gpa = gpa, .handler = handler, .state = undefined };
if (prefer != .native) via_avahi: { const client = avahi.Client.connect(io, gpa, environ) catch |err| { if (prefer == .avahi) return err; log.info("no Avahi daemon to browse through ({t}); asking mDNS here", .{err}); break :via_avahi; }; _ = client.browse(player_type, .{ .address_protocol = .inet }, .{ .context = self, .found = avahiFound, .lost = avahiLost }) catch |err| { client.deinit(); if (prefer == .avahi) return err; log.info("browsing through Avahi failed ({t}); asking mDNS here", .{err}); break :via_avahi; }; const running = io.concurrent(avahi.Client.run, .{client}) catch |err| { client.deinit(); return err; }; self.state = .{ .avahi = .{ .client = client, .running = running } }; return self; }
const monitor = try mdns.Monitor.init(io, gpa, player_type, .{ .context = self, .found = monitorFound, .lost = monitorLost }); errdefer monitor.deinit(); const running = try io.concurrent(mdns.Monitor.run, .{monitor}); self.state = .{ .native = .{ .monitor = monitor, .running = running } }; return self; }
pub fn backend(self: *const Finder) Backend { return self.state; }
pub fn stop(self: *Finder) void { switch (self.state) { .avahi => |*a| { a.client.stop(); _ = a.running.await(self.io) catch {}; a.client.deinit(); }, .native => |*n| { n.monitor.stop(); _ = n.running.await(self.io) catch {}; n.monitor.deinit(); }, } self.gpa.destroy(self); }
fn from(context: *anyopaque) *Finder { return @ptrCast(@alignCast(context)); }
fn avahiFound(context: *anyopaque, r: *const avahi.Resolved) void { const self = from(context); const address = parseIpv4(r.address) orelse return; const path = r.txtValue("path") orelse return; if (path.len == 0 or path[0] != '/') return; self.handler.found(self.handler.context, &.{ .instance = r.name, .name = r.txtValue("name"), .address = address, .port = r.port, .path = path }); }
fn avahiLost(context: *anyopaque, item: *const avahi.Item) void { const self = from(context); self.handler.lost(self.handler.context, item.name); }
fn monitorFound(context: *anyopaque, f: *const mdns.monitor.Found) void { const self = from(context); if (f.addresses.len == 0) return; const path = f.txtValue("path") orelse return; if (path.len == 0 or path[0] != '/') return; self.handler.found(self.handler.context, &.{ .instance = f.instance, .name = f.txtValue("name"), .address = f.addresses[0], .port = f.port, .path = path }); }
fn monitorLost(context: *anyopaque, instance: []const u8) void { const self = from(context); self.handler.lost(self.handler.context, instance); }};
/// `192.168.1.20`, as Avahi gives an address; null for anything else.pub fn parseIpv4(text: []const u8) ?[4]u8 { var out: [4]u8 = undefined; var it = std.mem.splitScalar(u8, text, '.'); for (&out) |*o| { const part = it.next() orelse return null; if (part.len == 0 or part.len > 3) return null; o.* = std.fmt.parseInt(u8, part, 10) catch return null; } if (it.next() != null) return null; return out;}
/// Dialing the players a `Finder` finds: each on a task of its own, for as/// long as the connection lasts, and not again while it does. `connect` is/// the server's -- `Server.connect`, say -- and returns when the connection/// ends.pub const Dialer = struct { io: Io, gpa: std.mem.Allocator, connect: Connect, lock: Io.Mutex = .init, /// The instances being dialed or connected to, owned. active: std.StringHashMapUnmanaged(void) = .empty, tasks: Io.Group = .init,
pub const Connect = struct { context: *anyopaque, connect: *const fn (context: *anyopaque, address: sendspin.Session.Address) anyerror!void, };
pub fn init(io: Io, gpa: std.mem.Allocator, connect: Connect) Dialer { return .{ .io = io, .gpa = gpa, .connect = connect }; }
/// Hang up on everything and free it. pub fn deinit(self: *Dialer) void { self.tasks.cancel(self.io); var it = self.active.keyIterator(); while (it.next()) |k| self.gpa.free(k.*); self.active.deinit(self.gpa); }
/// A `Handler` for a `Finder`, dialing what it finds. pub fn handler(self: *Dialer) Handler { return .{ .context = self, .found = found, .lost = lost }; }
fn found(context: *anyopaque, player: *const Player) void { const self: *Dialer = @ptrCast(@alignCast(context)); const dial = self.gpa.create(Dial) catch return; dial.* = .{ .dialer = self, .instance = undefined, .host = undefined, .path = undefined, .port = player.port }; { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); if (self.active.contains(player.instance)) { self.gpa.destroy(dial); return; } dial.instance = self.gpa.dupe(u8, player.instance) catch { self.gpa.destroy(dial); return; }; self.active.put(self.gpa, dial.instance, {}) catch { self.gpa.free(dial.instance); self.gpa.destroy(dial); return; }; } _ = std.fmt.bufPrint(&dial.host_buf, "{d}.{d}.{d}.{d}", .{ player.address[0], player.address[1], player.address[2], player.address[3] }) catch unreachable; dial.host = std.mem.sliceTo(&dial.host_buf, 0); const path_len = @min(player.path.len, dial.path_buf.len); @memcpy(dial.path_buf[0..path_len], player.path[0..path_len]); dial.path = dial.path_buf[0..path_len]; log.info("found player {s} at {s}:{d}{s}; dialing", .{ player.instance, dial.host, dial.port, dial.path }); self.tasks.concurrent(self.io, Dial.run, .{dial}) catch { dial.finish(); }; }
fn lost(_: *anyopaque, _: []const u8) void {}
const Dial = struct { dialer: *Dialer, instance: []u8, host_buf: [16]u8 = @splat(0), host: []const u8, path_buf: [256]u8 = undefined, path: []const u8, port: u16,
fn run(self: *Dial) void { defer self.finish(); self.dialer.connect.connect(self.dialer.connect.context, .{ .hostname = self.host, .port = self.port, .resource = self.path }) catch |err| { log.info("player {s}: {t}", .{ self.instance, err }); }; }
/// Forget it, so that it is dialed again the next time it is found. fn finish(self: *Dial) void { const d = self.dialer; d.lock.lockUncancelable(d.io); _ = d.active.remove(self.instance); d.lock.unlock(d.io); d.gpa.free(self.instance); d.gpa.destroy(self); } };};
const testing = std.testing;
test "a host label from anything" { var buf: [63]u8 = undefined; try testing.expectEqualStrings("zig-sendspin-server", hostLabel(&buf, "zig-sendspin server")); try testing.expectEqualStrings("pck9paqzwo3injnoqw-csvgldjqwlof1-0ih7p-3dh8", hostLabel(&buf, "pcK9PaqZWO3inJnOqW_cSvGlDJQWLoF1_0Ih7p_3Dh8")); try testing.expectEqualStrings("sendspin", hostLabel(&buf, " ")); try testing.expectEqual(@as(usize, 63), hostLabel(&buf, &@as([100]u8, @splat('x'))).len);}
test "an IPv4 address from Avahi's text" { try testing.expectEqual([4]u8{ 192, 168, 1, 20 }, parseIpv4("192.168.1.20").?); try testing.expect(parseIpv4("fe80::1") == null); try testing.expect(parseIpv4("1.2.3") == null); try testing.expect(parseIpv4("1.2.3.4.5") == null); try testing.expect(parseIpv4("256.1.1.1") == null);}
test "a player's address, to dial" { var buf: [15]u8 = undefined; const p: Player = .{ .instance = "x", .name = null, .address = .{ 10, 0, 0, 7 }, .port = 8928, .path = "/sendspin" }; const a = p.sessionAddress(&buf); try testing.expectEqualStrings("10.0.0.7", a.hostname); try testing.expectEqual(@as(u16, 8928), a.port.?);}