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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Clients that play together: what one is sent, all are, in step.//!//! Every client is in exactly one group. A server starts with one, which//! every client joins; a program makes more with `Server.createGroup` and//! moves clients between them with `Server.move`.
const Group = @This();
const std = @import("std");const Io = std.Io;const sendspin = @import("sendspin");
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.id: []const u8,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,
/// What is playing, for the metadata role, its strings in/// `metadata_arena`; null for nothing. Under the server's lock.metadata: ?message.Metadata = null,metadata_arena: std.heap.ArenaAllocator,/// The program's side of the controller's state: the commands it carries/// out, repeat, shuffle and how far a seek may go. Volume and mute are the/// players', and added when the state is sent. Under the server's lock.controller: message.ControllerState = .{},controller_arena: std.heap.ArenaAllocator,/// Whether there is an album's and an artist's picture to show.artwork: [2]bool = .{ false, false },
/// Every member, retained, so that they can be sent to without the/// server's lock held; `releaseAll` when done. Under the server's lock.pub fn snapshotLocked(self: *Group, gpa: std.mem.Allocator) ![]*Connection { const out = try gpa.dupe(*Connection, self.members.items); for (out) |c| c.retain(); return out;}
pub fn releaseAll(gpa: std.mem.Allocator, conns: []*Connection) void { for (conns) |c| c.release(); gpa.free(conns);}
/// The playback state, told to every member. Under the server's lock.pub fn setPlaybackLocked(self: *Group, state: message.PlaybackState) void { self.playback = state; for (self.members.items) |c| self.sendUpdate(c);}
/// Tell `c` which group it is in and how it is playing.pub fn sendUpdate(self: *Group, c: *Connection) void { var buf: [512]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); server_message.writeGroupUpdate(&w, .{ .playback_state = self.playback, .group_id = self.id, .group_name = self.name }) catch return; c.send(w.buffered()) catch {};}
/// Add `c`; under the server's lock.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.pub fn removeLocked(self: *Group, c: *Connection) void { for (self.members.items, 0..) |m, i| if (m == c) { _ = self.members.orderedRemove(i); 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 cleared and/// ended first, at once: what it had sent ahead is not waited out. To let it/// finish, `end` it before starting the next.pub fn start(self: *Group, source: Stream.Source) !void { if (self.stream) |s| { s.clear(); try 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 once it has been heard: see/// `Stream.end`, which this waits on. `clear` first to stop at once.pub fn end(self: *Group) Io.Cancelable!void { const s = self.stream orelse return; defer s.destroy(); const ended = s.end(); const io = self.server.io; self.server.lock.lockUncancelable(io); self.stream = null; self.setPlaybackLocked(.stopped); self.server.lock.unlock(io); return ended;}
pub fn deinit(self: *Group) void { if (self.stream) |s| s.destroy(); self.members.deinit(self.server.gpa); self.metadata_arena.deinit(); self.controller_arena.deinit();}
// --- metadata, controller, artwork -----------------------------------------
/// What is playing now, or null for nothing: sent whole to every client with/// the metadata role, and to each that joins later. Copied.pub fn setMetadata(self: *Group, metadata: ?message.Metadata) !void { const io = self.server.io; self.server.lock.lockUncancelable(io); defer self.server.lock.unlock(io); _ = self.metadata_arena.reset(.retain_capacity); self.metadata = if (metadata) |m| try copyMetadata(self.metadata_arena.allocator(), m) else null; for (self.members.items) |c| if (c.roles.metadata) self.sendMetadataLocked(c);}
fn copyMetadata(a: std.mem.Allocator, m: message.Metadata) !message.Metadata { var out = m; inline for (.{ "title", "artist", "album_artist", "album", "artwork_url" }) |f| { if (@field(m, f)) |t| @field(out, f) = try a.dupe(u8, t); } return out;}
fn sendMetadataLocked(self: *Group, c: *Connection) void { var buf: [4096]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); server_message.writeState(&w, if (self.metadata) |m| .{ .set = m } else .clear, null) catch return; c.send(w.buffered()) catch {};}
/// The program's side of the controller's state -- the commands it will/// carry out, repeat, shuffle, how far a seek may go -- sent to every client/// with the controller role, with the group's volume and mute added. Copied.pub fn setController(self: *Group, state: message.ControllerState) !void { const io = self.server.io; self.server.lock.lockUncancelable(io); defer self.server.lock.unlock(io); _ = self.controller_arena.reset(.retain_capacity); const a = self.controller_arena.allocator(); var s = state; const commands = try a.alloc([]const u8, state.supported_commands.len); for (commands, state.supported_commands) |*o, n| o.* = try a.dupe(u8, n); s.supported_commands = commands; self.controller = s; self.sendControllerLocked();}
/// The controller's state as clients see it: the program's, with volume and/// mute from the players -- volume the average of those that take it, mute/// only if all that take it are muted -- and those commands offered only if/// some player takes them.fn controllerStateLocked(self: *Group, commands: *std.ArrayList([]const u8), a: std.mem.Allocator) !message.ControllerState { var s = self.controller; var sum: u32 = 0; var volumes: u32 = 0; var mutes: u32 = 0; var muted: u32 = 0; for (self.members.items) |c| { const p = c.hello.player orelse continue; if (!c.roles.player) continue; if (p.volume) { sum += c.state.volume; volumes += 1; } if (p.mute) { mutes += 1; if (c.state.muted) muted += 1; } } s.volume = if (volumes > 0) @intCast(sum / volumes) else 100; s.muted = mutes > 0 and muted == mutes; for (self.controller.supported_commands) |n| { if (std.mem.eql(u8, n, "volume") or std.mem.eql(u8, n, "mute")) continue; try commands.append(a, n); } if (volumes > 0) try commands.append(a, "volume"); if (mutes > 0) try commands.append(a, "mute"); s.supported_commands = commands.items; return s;}
/// Tell every controller in the group how it stands. Under the lock.pub fn sendControllerLocked(self: *Group) void { for (self.members.items) |c| if (c.roles.controller) self.sendControllerToLocked(c);}
fn sendControllerToLocked(self: *Group, c: *Connection) void { var scratch: [2048]u8 = undefined; var fba: std.heap.FixedBufferAllocator = .init(&scratch); var commands: std.ArrayList([]const u8) = .empty; const state = self.controllerStateLocked(&commands, fba.allocator()) catch return; var buf: [2048]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); server_message.writeState(&w, .absent, state) catch return; c.send(w.buffered()) catch {};}
/// The group's volume, as a controller sets it: the difference from the/// players' average applied to each that takes a volume, what a clamp to/// 0 or 100 loses shared among the rest, until it is all applied or every/// player is at a limit -- relative levels kept. Each player is sent its/// own. Under the lock.pub fn setVolumeLocked(self: *Group, volume: u8) void { var players: [64]*Connection = undefined; var levels: [64]f64 = undefined; var n: usize = 0; for (self.members.items) |c| { const p = c.hello.player orelse continue; if (!c.roles.player or !p.volume or n == players.len) continue; players[n] = c; levels[n] = @floatFromInt(c.state.volume); n += 1; } if (n == 0) return; var sum: f64 = 0; for (levels[0..n]) |l| sum += l; var delta = @as(f64, @floatFromInt(volume)) - sum / @as(f64, @floatFromInt(n)); var free: [64]bool = @splat(true); var rounds: usize = 0; while (@abs(delta) > 1e-9 and rounds < n + 1) : (rounds += 1) { var open: usize = 0; for (free[0..n]) |f| open += @intFromBool(f); if (open == 0) break; const share = delta * @as(f64, @floatFromInt(n)) / @as(f64, @floatFromInt(open)); var lost: f64 = 0; for (levels[0..n], free[0..n]) |*l, *f| { if (!f.*) continue; const proposed = l.* + share; const clamped = std.math.clamp(proposed, 0, 100); if (clamped != proposed) f.* = false; lost += proposed - clamped; l.* = clamped; } delta = lost / @as(f64, @floatFromInt(n)); } for (players[0..n], levels[0..n]) |c, l| { const v: u8 = @intFromFloat(@round(l)); if (v == c.state.volume) continue; c.state.volume = v; sendCommand(c, .{ .volume = v }); } self.sendControllerLocked();}
/// The group's mute, set on every player that takes it. Under the lock.pub fn setMuteLocked(self: *Group, muted: bool) void { for (self.members.items) |c| { const p = c.hello.player orelse continue; if (!c.roles.player or !p.mute) continue; c.state.muted = muted; sendCommand(c, .{ .mute = muted }); } self.sendControllerLocked();}
fn sendCommand(c: *Connection, command: message.Command) void { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); server_message.writeCommand(&w, command) catch return; c.send(w.buffered()) catch {};}
/// Whether there is an album's or an artist's picture now: every client with/// a channel for it is sent one, rendered by `Server.Options.artwork` at its/// size and in its format, or an empty image to clear it.pub fn setArtwork(self: *Group, source: message.ArtworkSource, present: bool) !void { const io = self.server.io; const gpa = self.server.gpa; const conns = blk: { self.server.lock.lockUncancelable(io); defer self.server.lock.unlock(io); if (source != .none) self.artwork[@backingInt(source)] = present; var list: std.ArrayList(*Connection) = .empty; errdefer list.deinit(gpa); for (self.members.items) |c| if (c.roles.artwork) { try list.append(gpa, c); c.retain(); }; break :blk try list.toOwnedSlice(gpa); }; defer releaseAll(gpa, conns); var cache: Renders = .{ .gpa = gpa }; defer cache.deinit(); for (conns) |c| self.sendArtwork(c, source, present, &cache);}
/// Images already rendered, by configuration, so that clients asking for/// the same one share it.const Renders = struct { gpa: std.mem.Allocator, list: std.ArrayList(struct { channel: message.ArtworkChannel, bytes: ?[]u8 }) = .empty,
fn deinit(r: *Renders) void { for (r.list.items) |e| if (e.bytes) |b| r.gpa.free(b); r.list.deinit(r.gpa); }};
/// `c`'s channels showing `source`, sent the picture, or cleared. Not/// under the lock: rendering is the program's, and may take a while.fn sendArtwork(self: *Group, c: *Connection, source: message.ArtworkSource, present: bool, cache: *Renders) void { const channels = c.hello.artwork orelse return; for (channels, 0..) |ch, i| { if (ch.source != source) continue; const bytes: []const u8 = if (!present) &.{} else self.render(ch, cache) orelse continue; c.sendBinaryParts(&server_message.binaryHeader(server_message.artworkType(@intCast(i)), Server.now()), bytes) catch {}; }}
fn render(self: *Group, ch: message.ArtworkChannel, cache: *Renders) ?[]const u8 { for (cache.list.items) |e| if (std.meta.eql(e.channel, ch)) return e.bytes; const renderer = self.server.options.artwork orelse return null; var out: std.Io.Writer.Allocating = .init(self.server.gpa); const bytes: ?[]u8 = if (renderer.render(renderer.context, self, ch.source, ch.format, ch.width, ch.height, &out.writer)) |_| out.toOwnedSlice() catch null else |_| blk: { out.deinit(); break :blk null; }; cache.list.append(self.server.gpa, .{ .channel = ch, .bytes = bytes }) catch { if (bytes) |b| self.server.gpa.free(b); return null; }; return bytes;}
/// Everything a client that has just joined should know of the group: its/// metadata, its controller state, the artwork stream and pictures. Not/// under the lock.pub fn welcome(self: *Group, c: *Connection) void { const io = self.server.io; { self.server.lock.lockUncancelable(io); defer self.server.lock.unlock(io); if (c.group != self) return; if (c.roles.metadata) self.sendMetadataLocked(c); if (c.roles.controller) self.sendControllerToLocked(c); } if (!c.roles.artwork) return; const channels = c.hello.artwork orelse return; var buf: [1024]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); server_message.writeStreamStart(&w, Server.now(), .{ .artwork = channels }) catch return; c.send(w.buffered()) catch {}; var cache: Renders = .{ .gpa = self.server.gpa }; defer cache.deinit(); for ([_]message.ArtworkSource{ .album, .artist }) |source| { if (self.artwork[@backingInt(source)]) self.sendArtwork(c, source, true, &cache); }}