// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What goes over a Sendspin connection. Nothing here does I/O. //! //! Two kinds of message share the one WebSocket: //! //! - **text**: JSON, always `{"type": "...", "payload": {...}}`, for //! everything but audio -- the hello each side sends, clock exchanges, //! state, commands, and a stream starting, being cleared and ending; //! - **binary**: a byte saying what it is, eight bytes of big-endian server //! time in microseconds saying when it is to be heard, and the data -- //! for the player role, encoded audio; for the artwork role, a whole //! image. //! //! Four roles are spoken: the player, which plays the stream; metadata, //! which is told what is playing and where it has got to; the controller, //! which is told how the group stands and can command it; and artwork, //! which is sent the pictures. `Hello.roles` says which a client offers. //! //! Both generations of the protocol are here: aiosendspin 4.4's, which //! Music Assistant 2.8 serves, unencrypted; and aiosendspin 9.1's, which //! Music Assistant 2.10 serves, whose messages travel sealed (see //! `secure`) and whose hello, state and activation differ where noted. const std = @import("std"); pub const player_role = "player@v1"; pub const metadata_role = "metadata@v1"; pub const controller_role = "controller@v1"; pub const artwork_role = "artwork@v1"; /// Which roles a client offers, and what each needs said about it. pub const Roles = struct { player: bool = true, metadata: bool = false, controller: bool = false, /// The artwork channels, one to four, the index of each its channel /// number; none means no artwork role. artwork: []const ArtworkChannel = &.{}, }; pub const ArtworkSource = enum { album, artist, none }; pub const PictureFormat = enum { jpeg, png }; /// What one artwork channel shows, and how: the server scales the image to /// fit `width` by `height`, and sends it encoded as `format`. pub const ArtworkChannel = struct { source: ArtworkSource, format: PictureFormat = .jpeg, width: u32 = 0, height: u32 = 0, }; pub const Codec = enum { pcm, flac, opus }; pub const Format = struct { codec: Codec, channels: u8, sample_rate: u32, bit_depth: u8, }; pub const DeviceInfo = struct { product_name: ?[]const u8 = null, manufacturer: ?[]const u8 = null, software_version: ?[]const u8 = null, }; pub const Hello = struct { /// Stable across restarts: the server keeps a player's settings under /// it, and a new id is a new player. client_id: []const u8, /// What the player is called in the server's list. name: []const u8, device_info: ?DeviceInfo = null, /// The formats this player can play, the one it prefers first. formats: []const Format, /// How many bytes of encoded audio it can hold ahead of time; the server /// sends no further ahead than this. buffer_capacity: u32, /// The roles offered: the player's alone, unless said otherwise. Without /// the player, `formats` and `buffer_capacity` go unsaid. roles: Roles = .{}, }; /// Which generation of the protocol a message is written for. pub const Generation = union(enum) { /// aiosendspin 4.4, unencrypted. legacy, /// aiosendspin 9.1, sealed: the client's id and version travel in /// `client/init` instead of the hello, and the hello asks for guest /// access -- playback without pairing, which the server may grant. encrypted: Sealed, pub const Sealed = struct { /// The shortest dynamic PIN this player accepts, if it offers to /// pair with one: it shows the PIN, so its channel is the display. dynamic_pin: ?u8 = null, /// Whether this connection is on a long-term PSK: the player trusts /// the server as one it paired with. paired: bool = false, }; }; // --- client to server ------------------------------------------------------ /// Music Assistant's proxy wants a token before anything else, and names the /// client with it so the player is the user's. pub fn writeAuth(w: *std.Io.Writer, token: []const u8, client_id: []const u8) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "auth", .token = token, .client_id = client_id }, .{}, w); } pub fn writeHello(w: *std.Io.Writer, hello: Hello, generation: Generation) std.Io.Writer.Error!void { var s: std.json.Stringify = .{ .writer = w, .options = .{ .emit_null_optional_fields = false } }; try s.beginObject(); try s.objectField("type"); try s.write("client/hello"); try s.objectField("payload"); try s.beginObject(); if (generation == .legacy) { try s.objectField("client_id"); try s.write(hello.client_id); } try s.objectField("name"); try s.write(hello.name); if (generation == .legacy) { try s.objectField("version"); try s.write(1); } else { const sealed = generation.encrypted; try s.objectField("unpaired_access"); try s.write(.{ .enabled = true }); if (sealed.paired) { try s.objectField("trust_level"); try s.write("user"); } if (sealed.dynamic_pin) |min| { try s.objectField("supported_pair_methods"); try s.write(.{.{ .method = "dynamic_pin", .out_channels = .{"display"}, .min_pin_length = min }}); } } const roles = hello.roles; try s.objectField("supported_roles"); try s.beginArray(); if (roles.player) try s.write(player_role); if (roles.metadata) try s.write(metadata_role); if (roles.controller) try s.write(controller_role); if (roles.artwork.len > 0) try s.write(artwork_role); try s.endArray(); if (hello.device_info) |d| { try s.objectField("device_info"); try s.write(d); } if (roles.player) { try s.objectField(player_role ++ "_support"); try s.beginObject(); try s.objectField("supported_formats"); try s.write(hello.formats); try s.objectField("buffer_capacity"); try s.write(hello.buffer_capacity); try s.objectField("supported_commands"); try s.write(&[_][]const u8{ "volume", "mute" }); try s.endObject(); } if (roles.artwork.len > 0) { // As aiosendspin 9.1 has it, in the hello and with `media_` sizes; // the specification since moves it to `client/state`. try s.objectField(artwork_role ++ "_support"); try s.beginObject(); try s.objectField("channels"); try s.beginArray(); for (roles.artwork[0..@min(roles.artwork.len, max_artwork_channels)]) |ch| { try s.write(.{ .source = ch.source, .format = ch.format, .media_width = ch.width, .media_height = ch.height }); } try s.endArray(); try s.endObject(); } try s.endObject(); try s.endObject(); } pub const max_artwork_channels = 4; /// A command for the group, from a controller: what `server/state`'s /// controller object lists in `supported_commands`, which the server /// ignores any other of. pub const ControllerCommand = union(enum) { play, pause, stop, next, previous, /// The group's volume, 0 to 100. volume: u8, mute: bool, repeat_off, repeat_one, repeat_all, shuffle, unshuffle, /// Move to the next group in the server's cycle. @"switch", /// To a position, in milliseconds, up to `ControllerState.seek_max_ms`. seek: u64, /// By an offset, in milliseconds, forward or back. seek_relative: i64, pub fn name(c: ControllerCommand) []const u8 { return @tagName(c); } }; pub fn writeCommand(w: *std.Io.Writer, command: ControllerCommand) std.Io.Writer.Error!void { var s: std.json.Stringify = .{ .writer = w }; try s.beginObject(); try s.objectField("type"); try s.write("client/command"); try s.objectField("payload"); try s.beginObject(); try s.objectField("controller"); try s.beginObject(); try s.objectField("command"); try s.write(command.name()); switch (command) { .volume => |v| { try s.objectField("volume"); try s.write(@min(v, 100)); }, .mute => |m| { try s.objectField("mute"); try s.write(m); }, .seek => |ms| { try s.objectField("position_ms"); try s.write(ms); }, .seek_relative => |ms| { try s.objectField("offset_ms"); try s.write(ms); }, else => {}, } try s.endObject(); try s.endObject(); try s.endObject(); } /// A client without the player role's state: that it is available. pub fn writeAvailable(w: *std.Io.Writer, available: bool) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "client/state", .payload = .{ .available = available } }, .{}, w); } pub fn writeTime(w: *std.Io.Writer, client_transmitted: i64) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "client/time", .payload = .{ .client_transmitted = client_transmitted }, }, .{}, w); } pub const PlayerState = enum { synchronized, @"error", external_source }; /// The player's state, volume (0 to 100) and mute, as the server should /// show them. pub fn writeState(w: *std.Io.Writer, state: PlayerState, volume: u8, muted: bool) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "client/state", .payload = .{ .player = .{ .state = state, .volume = volume, .muted = muted } }, }, .{}, w); } /// What a sealed connection's `client/state` says of the player: whether it /// is available, its volume and mute, and the timing the server schedules /// its audio by -- all in milliseconds. pub const PlayerStatus = struct { available: bool = true, volume: u8, muted: bool, /// How far behind the audio the device plays it: the server sends this /// much earlier, so that grouped players sound together. static_delay_ms: u32 = 0, /// How long, from a stream's start or clear, before the first audio can /// be heard: the server leaves this much lead. required_lead_time_ms: u32 = 250, /// How much buffer to keep during playback, against jitter. min_buffer_ms: u32 = 250, }; pub fn writeStatus(w: *std.Io.Writer, status: PlayerStatus) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "client/state", .payload = .{ .available = status.available, .player = .{ .volume = status.volume, .muted = status.muted, .static_delay_ms = status.static_delay_ms, .required_lead_time_ms = status.required_lead_time_ms, .min_buffer_ms = status.min_buffer_ms, }, }, }, .{}, w); } /// A different stream format, asked of the server mid-stream: any field /// left null keeps what the stream has. The server answers with a new /// `stream/start`, and must pick from the formats the hello offered. pub const FormatRequest = struct { codec: ?Codec = null, channels: ?u8 = null, sample_rate: ?u32 = null, bit_depth: ?u8 = null, }; pub fn writeRequestFormat(w: *std.Io.Writer, request: FormatRequest) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "stream/request-format", .payload = .{ .player = request }, }, .{ .emit_null_optional_fields = false }, w); } pub const GoodbyeReason = enum { another_server, shutdown, restart, user_request }; pub fn writeGoodbye(w: *std.Io.Writer, reason: GoodbyeReason) std.Io.Writer.Error!void { try std.json.Stringify.value(.{ .type = "client/goodbye", .payload = .{ .reason = reason } }, .{}, w); } // --- server to client ------------------------------------------------------ pub const ServerHello = struct { /// In a sealed connection the server's id comes from the handshake, /// and the hello carries only its name. server_id: []const u8 = "", name: []const u8, version: i64 = 1, active_roles: []const []const u8 = &.{}, /// Not the server's: whether the connection is on a long-term PSK, /// which the client fills in. paired: bool = false, }; pub const ServerTime = struct { client_transmitted: i64, server_received: i64, server_transmitted: i64, }; pub const StreamStart = struct { codec: Codec, sample_rate: u32, channels: u8, bit_depth: u8, /// Base64 of what a decoder needs before the first frame: FLAC's /// STREAMINFO, Opus's header. codec_header: ?[]const u8 = null, }; pub const Command = union(enum) { volume: u8, mute: bool, }; /// A `stream/start`: the parts for the roles it starts. Either may be /// absent, and one for a role this client does not have is. pub const StreamStarts = struct { player: ?StreamStart = null, /// The artwork channels as the server will send them, index for index. artwork: ?[]const ArtworkChannel = null, }; /// Which roles a `stream/clear` or `stream/end` is for: every one, if it /// names none. pub const StreamRoles = struct { player: bool = false, artwork: bool = false, }; /// Where a track has got to, as of `Metadata.timestamp`. pub const Progress = struct { /// Milliseconds into the track. track_progress: i64, /// Its length in milliseconds; 0 for one with no end, a radio station's. track_duration: i64, /// Speed times 1000: 1000 playing, 0 paused. playback_speed: i64, }; /// What is playing, as the metadata role is told: the whole of it, each /// `server/state` merged into the last. Null is unknown or cleared. pub const Metadata = struct { /// Server time, in microseconds, at which this took effect -- or, in /// the future, will. timestamp: i64 = 0, title: ?[]const u8 = null, artist: ?[]const u8 = null, album_artist: ?[]const u8 = null, album: ?[]const u8 = null, artwork_url: ?[]const u8 = null, year: ?i64 = null, track: ?i64 = null, progress: ?Progress = null, /// Where the track has got to at server time `now_us`, in milliseconds, /// as the specification reckons it from `timestamp` and the speed. pub fn position(m: Metadata, now_us: i64) ?i64 { const p = m.progress orelse return null; const elapsed_us = std.math.sub(i64, now_us, m.timestamp) catch return null; const moved = std.math.mul(i128, elapsed_us, p.playback_speed) catch return null; const at = @as(i128, p.track_progress) + @divFloor(moved, 1_000_000); // No end to hold it to, for a duration of 0 -- a radio station's -- // and for one no server should send, below it. const top: i128 = if (p.track_duration > 0) p.track_duration else std.math.maxInt(i64); return @intCast(std.math.clamp(at, 0, top)); } /// `update`, a `server/state` metadata object, over `m`: a field it /// leaves out stays, a null one is cleared. aiosendspin 9.1 sends only /// what changed; the specification sends the whole, which this takes /// the same way. The strings are copied into `arena`. pub fn merge(m: Metadata, arena: std.mem.Allocator, update: std.json.ObjectMap) !Metadata { var out = m; inline for (.{ "title", "artist", "album_artist", "album", "artwork_url" }) |f| { if (update.get(f)) |v| @field(out, f) = switch (v) { .string => |t| try arena.dupe(u8, t), else => null, } else if (@field(out, f)) |old| { @field(out, f) = try arena.dupe(u8, old); } } inline for (.{ "year", "track" }) |f| { if (update.get(f)) |v| @field(out, f) = switch (v) { .integer => |i| i, else => null, }; } if (update.get("timestamp")) |v| if (v == .integer) { out.timestamp = v.integer; }; if (update.get("progress")) |v| out.progress = if (v == .object) blk: { const Parsed = struct { track_progress: i64 = 0, track_duration: i64 = 0, playback_speed: i64 = 1000 }; const pr = std.json.parseFromValueLeaky(Parsed, arena, v, .{ .ignore_unknown_fields = true }) catch break :blk null; break :blk .{ .track_progress = pr.track_progress, .track_duration = pr.track_duration, .playback_speed = pr.playback_speed }; } else null; return out; } }; pub const RepeatMode = enum { off, one, all }; /// How the group stands, as the controller role is told. pub const ControllerState = struct { /// The commands the server will act on; any other it ignores. supported_commands: []const []const u8 = &.{}, volume: u8 = 100, muted: bool = false, repeat: RepeatMode = .off, shuffle: bool = false, /// How far a `seek` may go, when the server allows one. seek_max_ms: ?i64 = null, pub fn supports(self: ControllerState, command: ControllerCommand) bool { for (self.supported_commands) |c| if (std.mem.eql(u8, c, command.name())) return true; return false; } fn parse(arena: std.mem.Allocator, v: std.json.Value) ?ControllerState { const Parsed = struct { supported_commands: []const []const u8 = &.{}, volume: i64 = 100, muted: bool = false, repeat: ?[]const u8 = null, shuffle: bool = false, seek_max_ms: ?i64 = null, }; const p = std.json.parseFromValueLeaky(Parsed, arena, v, .{ .ignore_unknown_fields = true }) catch return null; return .{ .supported_commands = p.supported_commands, .volume = @intCast(std.math.clamp(p.volume, 0, 100)), .muted = p.muted, .repeat = if (p.repeat) |r| std.meta.stringToEnum(RepeatMode, r) orelse .off else .off, .shuffle = p.shuffle, .seek_max_ms = p.seek_max_ms, }; } }; /// A `server/state`: what changed for the metadata and controller roles. pub const ServerState = struct { /// The metadata object as sent, to merge (see `Metadata.merge`); null /// when there was none, or it was null -- which clears it. metadata: MetadataUpdate = .absent, controller: ?ControllerState = null, pub const MetadataUpdate = union(enum) { absent, clear, update: std.json.ObjectMap, }; }; pub const PlaybackState = enum { playing, paused, stopped }; pub const Activate = struct { /// Whether playback is among the connection's activities. playback: bool, /// Whether the player role is active; null when the message does not /// say, which leaves it as it was. player: ?bool, /// Whether the server wants to pair: `pairing` among the activities, /// and the method it chose. pairing: ?Pairing = null, /// Every activity it names, whether this knows them or not, for the /// admission rules: `pairing` must come alone. activity_count: usize = 0, /// The roles the server activated, when it says: every one of them /// should be a role the hello offered. Borrowed, as the message is. active_roles: ?[]const []const u8 = null, pub const Pairing = struct { method: PairMethod, /// For a dynamic PIN, how many digits. pin_length: ?i64 = null, }; pub const PairMethod = enum { dynamic_pin, static_pin, pairing_psk, unknown }; }; /// One text message from the server, as much of it as a player uses. The /// strings point into the JSON it was parsed from. pub const Incoming = union(enum) { /// Music Assistant's proxy has accepted the token. auth_ok, hello: ServerHello, time: ServerTime, stream_start: StreamStarts, /// Drop whatever is buffered: the server is about to send audio from /// somewhere else -- a seek, a skip. stream_clear: StreamRoles, stream_end: StreamRoles, command: Command, /// For the metadata and controller roles. state: ServerState, group: ?PlaybackState, /// `server/activate`, on a sealed connection: what the server means the /// connection for now. activate: Activate, /// Anything else, which no role here needs: whatever later versions /// add. other, }; /// A text message's `type`, without parsing the rest: for saying what went /// by, not for acting on it. Null if the message has no plain string type /// at its top level. pub fn typeOf(text: []const u8) ?[]const u8 { // The scanner keeps a bit a level of nesting; this is room for deeper // than any message goes, without an allocation a message. var stack: [256]u8 = undefined; var fba: std.heap.FixedBufferAllocator = .init(&stack); var scanner: std.json.Scanner = .initCompleteInput(fba.allocator(), text); defer scanner.deinit(); if ((scanner.next() catch return null) != .object_begin) return null; var depth: usize = 1; while (depth > 0) { const token = scanner.next() catch return null; switch (token) { .object_begin, .array_begin => depth += 1, .object_end, .array_end => depth -= 1, .string => |key| if (depth == 1 and std.mem.eql(u8, key, "type")) { return switch (scanner.next() catch return null) { .string => |value| value, else => null, }; } else if (depth == 1) { // A key at the top: skip its value whole. scanner.skipValue() catch return null; }, .end_of_document => return null, else => {}, } } return null; } /// What kind of message `v` -- the parsed JSON -- is, and its payload. pub fn classify(arena: std.mem.Allocator, v: std.json.Value) !Incoming { if (v != .object) return .other; const type_value = v.object.get("type") orelse return .other; if (type_value != .string) return .other; const t = type_value.string; const payload = v.object.get("payload") orelse .null; const opts: std.json.ParseOptions = .{ .ignore_unknown_fields = true }; if (std.mem.eql(u8, t, "auth_ok")) return .auth_ok; if (std.mem.eql(u8, t, "server/hello")) return .{ .hello = try std.json.parseFromValueLeaky(ServerHello, arena, payload, opts) }; if (std.mem.eql(u8, t, "server/time")) return .{ .time = try std.json.parseFromValueLeaky(ServerTime, arena, payload, opts) }; if (std.mem.eql(u8, t, "stream/start")) { const Channel = struct { source: ArtworkSource, format: PictureFormat = .jpeg, width: u32 = 0, height: u32 = 0 }; const Payload = struct { player: ?StreamStart = null, artwork: ?struct { channels: []const Channel = &.{} } = null }; const p = try std.json.parseFromValueLeaky(Payload, arena, payload, opts); var out: StreamStarts = .{ .player = p.player }; if (p.artwork) |art| { const channels = try arena.alloc(ArtworkChannel, @min(art.channels.len, max_artwork_channels)); for (channels, art.channels[0..channels.len]) |*o, c| o.* = .{ .source = c.source, .format = c.format, .width = c.width, .height = c.height }; out.artwork = channels; } // One with no part this client knows is for roles it does not have. return if (out.player != null or out.artwork != null) .{ .stream_start = out } else .other; } if (std.mem.eql(u8, t, "stream/clear")) return .{ .stream_clear = streamRoles(payload) }; if (std.mem.eql(u8, t, "stream/end")) return .{ .stream_end = streamRoles(payload) }; if (std.mem.eql(u8, t, "server/state")) { if (payload != .object) return .other; var out: ServerState = .{}; if (payload.object.get("metadata")) |m| out.metadata = switch (m) { .object => |o| .{ .update = o }, else => .clear, }; if (payload.object.get("controller")) |c| out.controller = ControllerState.parse(arena, c); return .{ .state = out }; } if (std.mem.eql(u8, t, "server/command")) { const Payload = struct { player: ?struct { command: []const u8, volume: ?i64 = null, mute: ?bool = null } = null }; const p = try std.json.parseFromValueLeaky(Payload, arena, payload, opts); const c = p.player orelse return .other; if (std.mem.eql(u8, c.command, "volume")) { return .{ .command = .{ .volume = @intCast(std.math.clamp(c.volume orelse return .other, 0, 100)) } }; } if (std.mem.eql(u8, c.command, "mute")) return .{ .command = .{ .mute = c.mute orelse return .other } }; return .other; } if (std.mem.eql(u8, t, "server/activate")) { const Payload = struct { activities: []const []const u8 = &.{}, active_roles: ?[]const []const u8 = null, pairing: ?struct { method: []const u8, pin_length: ?i64 = null } = null, }; const p = std.json.parseFromValueLeaky(Payload, arena, payload, opts) catch return .other; var out: Activate = .{ .playback = false, .player = null, .activity_count = p.activities.len }; var pairing = false; for (p.activities) |act| { if (std.mem.eql(u8, act, "playback")) out.playback = true; if (std.mem.eql(u8, act, "pairing")) pairing = true; } if (pairing) out.pairing = .{ .method = if (p.pairing) |pr| std.meta.stringToEnum(Activate.PairMethod, pr.method) orelse .unknown else .unknown, .pin_length = if (p.pairing) |pr| pr.pin_length else null, }; if (p.active_roles) |roles| { out.active_roles = roles; out.player = false; for (roles) |r| if (std.mem.eql(u8, r, player_role)) { out.player = true; }; } return .{ .activate = out }; } if (std.mem.eql(u8, t, "group/update")) { const Payload = struct { playback_state: ?PlaybackState = null }; const p = std.json.parseFromValueLeaky(Payload, arena, payload, opts) catch return .{ .group = null }; return .{ .group = p.playback_state }; } return .other; } /// Which roles a `stream/clear` or `stream/end` is for: those it names, or /// every one if it names none. Roles are named without their version. fn streamRoles(payload: std.json.Value) StreamRoles { const every: StreamRoles = .{ .player = true, .artwork = true }; if (payload != .object) return every; const roles = payload.object.get("roles") orelse return every; if (roles != .array) return every; var out: StreamRoles = .{}; for (roles.array.items) |r| if (r == .string) { if (std.mem.eql(u8, r.string, "player")) out.player = true; if (std.mem.eql(u8, r.string, "artwork")) out.artwork = true; }; return out; } /// The binary message types, from the first byte. pub const BinaryType = enum(u8) { audio = 4, /// A whole image for artwork channel 0; channels 1 to 3 follow. artwork_0 = 8, artwork_1 = 9, artwork_2 = 10, artwork_3 = 11, _, /// The artwork channel this carries, if it is artwork. pub fn artworkChannel(t: BinaryType) ?u2 { const n = @backingInt(t); return if (n >= 8 and n <= 11) @intCast(n - 8) else null; } }; pub const binary_header_len = 9; pub const Binary = struct { type: BinaryType, /// When to be heard, in server microseconds. timestamp_us: i64, data: []const u8, }; pub fn parseBinary(bytes: []const u8) error{Truncated}!Binary { if (bytes.len < binary_header_len) return error.Truncated; return .{ .type = @fromBackingInt(@intCast(bytes[0])), .timestamp_us = std.mem.readInt(i64, bytes[1..9], .big), .data = bytes[binary_header_len..], }; } const testing = std.testing; test "a client hello is what the server expects" { var buf: [1024]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeHello(&w, .{ .client_id = "pipit-1", .name = "Pipit", .device_info = .{ .product_name = "Pipit" }, .formats = &.{.{ .codec = .pcm, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }}, .buffer_capacity = 1048576, }, .legacy); try testing.expectEqualStrings( \\{"type":"client/hello","payload":{"client_id":"pipit-1","name":"Pipit","version":1,"supported_roles":["player@v1"],"device_info":{"product_name":"Pipit"},"player@v1_support":{"supported_formats":[{"codec":"pcm","channels":2,"sample_rate":48000,"bit_depth":16}],"buffer_capacity":1048576,"supported_commands":["volume","mute"]}}} , w.buffered()); } test "state, time and auth" { var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeState(&w, .synchronized, 80, false); try testing.expectEqualStrings( \\{"type":"client/state","payload":{"player":{"state":"synchronized","volume":80,"muted":false}}} , w.buffered()); w = .fixed(&buf); try writeTime(&w, 1234); try testing.expectEqualStrings( \\{"type":"client/time","payload":{"client_transmitted":1234}} , w.buffered()); w = .fixed(&buf); try writeAuth(&w, "tok", "pipit-1"); try testing.expectEqualStrings( \\{"type":"auth","token":"tok","client_id":"pipit-1"} , w.buffered()); } fn classifyText(arena: std.mem.Allocator, json: []const u8) !Incoming { const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}); return classify(arena, v); } test "what the server says, sorted" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); try testing.expectEqual(Incoming.auth_ok, try classifyText(a, \\{"type": "auth_ok"} )); const hello = (try classifyText(a, \\{"type":"server/hello","payload":{"server_id":"s","name":"Music Assistant","version":1,"active_roles":["player@v1"],"connection_reason":"playback"}} )).hello; try testing.expectEqualStrings("Music Assistant", hello.name); const t = (try classifyText(a, \\{"type":"server/time","payload":{"client_transmitted":1,"server_received":2,"server_transmitted":3}} )).time; try testing.expectEqual(@as(i64, 3), t.server_transmitted); const start = (try classifyText(a, \\{"type":"stream/start","payload":{"player":{"codec":"pcm","sample_rate":44100,"channels":2,"bit_depth":24}}} )).stream_start.player.?; try testing.expectEqual(Codec.pcm, start.codec); try testing.expectEqual(@as(u8, 24), start.bit_depth); try testing.expectEqual(StreamRoles{ .player = true }, (try classifyText(a, \\{"type":"stream/clear","payload":{"roles":["player"]}} )).stream_clear); try testing.expectEqual(StreamRoles{}, (try classifyText(a, \\{"type":"stream/clear","payload":{"roles":["visualizer"]}} )).stream_clear); try testing.expectEqual(StreamRoles{ .player = true, .artwork = true }, (try classifyText(a, \\{"type":"stream/end","payload":{}} )).stream_end); try testing.expectEqual(@as(u8, 42), (try classifyText(a, \\{"type":"server/command","payload":{"player":{"command":"volume","volume":42}}} )).command.volume); try testing.expect((try classifyText(a, \\{"type":"server/command","payload":{"player":{"command":"mute","mute":true}}} )).command.mute); try testing.expectEqual(@as(i64, 1), (try classifyText(a, \\{"type":"server/state","payload":{"metadata":{"timestamp":1}}} )).state.metadata.update.get("timestamp").?.integer); } test "the hello offers the roles asked for, and only their support objects" { var buf: [1024]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeHello(&w, .{ .client_id = "c", .name = "Display", .formats = &.{}, .buffer_capacity = 0, .roles = .{ .player = false, .metadata = true, .controller = true, .artwork = &.{.{ .source = .album, .format = .png, .width = 256, .height = 128 }}, }, }, .{ .encrypted = .{} }); try testing.expectEqualStrings( \\{"type":"client/hello","payload":{"name":"Display","unpaired_access":{"enabled":true},"supported_roles":["metadata@v1","controller@v1","artwork@v1"],"artwork@v1_support":{"channels":[{"source":"album","format":"png","media_width":256,"media_height":128}]}}} , w.buffered()); } test "controller commands" { var buf: [256]u8 = undefined; const cases = .{ .{ ControllerCommand.next, "{\"type\":\"client/command\",\"payload\":{\"controller\":{\"command\":\"next\"}}}" }, .{ ControllerCommand{ .volume = 140 }, "{\"type\":\"client/command\",\"payload\":{\"controller\":{\"command\":\"volume\",\"volume\":100}}}" }, .{ ControllerCommand{ .seek = 90_000 }, "{\"type\":\"client/command\",\"payload\":{\"controller\":{\"command\":\"seek\",\"position_ms\":90000}}}" }, .{ ControllerCommand{ .seek_relative = -5000 }, "{\"type\":\"client/command\",\"payload\":{\"controller\":{\"command\":\"seek_relative\",\"offset_ms\":-5000}}}" }, .{ ControllerCommand.@"switch", "{\"type\":\"client/command\",\"payload\":{\"controller\":{\"command\":\"switch\"}}}" }, }; inline for (cases) |c| { var w: std.Io.Writer = .fixed(&buf); try writeCommand(&w, c[0]); try testing.expectEqualStrings(c[1], w.buffered()); } } test "server/state: metadata merged, a field left out kept and a null one cleared" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const a = arena_state.allocator(); const first = (try classifyText(a, \\{"type":"server/state","payload":{"metadata":{"timestamp":1000000,"title":"Overture","artist":"Rush","year":1976,"track":1, \\ "progress":{"track_progress":60000,"track_duration":1233000,"playback_speed":1000}}, \\ "controller":{"supported_commands":["play","next"],"volume":55,"muted":false,"repeat":"all","shuffle":true}}} )).state; var m = try Metadata.merge(.{}, a, first.metadata.update); try testing.expectEqualStrings("Overture", m.title.?); try testing.expectEqual(@as(?i64, 1976), m.year); // Two seconds on at full speed; then paused, where it stays. try testing.expectEqual(@as(?i64, 62000), m.position(3_000_000)); const ctl = first.controller.?; try testing.expectEqual(RepeatMode.all, ctl.repeat); try testing.expect(ctl.shuffle); try testing.expect(ctl.supports(.next)); try testing.expect(!ctl.supports(.{ .volume = 1 })); const second = (try classifyText(a, \\{"type":"server/state","payload":{"metadata":{"timestamp":5000000,"artist":null,"progress":{"track_progress":64000,"track_duration":1233000,"playback_speed":0}}}} )).state; m = try Metadata.merge(m, a, second.metadata.update); try testing.expectEqualStrings("Overture", m.title.?); try testing.expect(m.artist == null); // A duration no server should send is no end at all, not a panic. const odd: Metadata = .{ .progress = .{ .track_progress = 5, .track_duration = -3, .playback_speed = 1000 } }; try testing.expectEqual(@as(?i64, 5), odd.position(0)); try testing.expectEqual(@as(?i64, 64000), m.position(9_000_000)); try testing.expect(second.controller == null); try testing.expectEqual(ServerState.MetadataUpdate.clear, (try classifyText(a, \\{"type":"server/state","payload":{"metadata":null}} )).state.metadata); } test "stream/start for artwork" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const starts = (try classifyText(arena_state.allocator(), \\{"type":"stream/start","payload":{"artwork":{"channels":[{"source":"album","format":"jpeg","width":256,"height":256}]}}} )).stream_start; try testing.expect(starts.player == null); try testing.expectEqual(@as(u32, 256), starts.artwork.?[0].width); try testing.expectEqual(@as(?u2, 0), BinaryType.artwork_0.artworkChannel()); try testing.expectEqual(@as(?u2, 3), @as(BinaryType, @fromBackingInt(@intCast(11))).artworkChannel()); try testing.expect(BinaryType.audio.artworkChannel() == null); } test "an audio frame's header" { var frame: [13]u8 = undefined; frame[0] = 4; std.mem.writeInt(i64, frame[1..9], 123_456_789, .big); @memcpy(frame[9..], "abcd"); const b = try parseBinary(&frame); try testing.expectEqual(BinaryType.audio, b.type); try testing.expectEqual(@as(i64, 123_456_789), b.timestamp_us); try testing.expectEqualStrings("abcd", b.data); try testing.expectError(error.Truncated, parseBinary(frame[0..5])); } test "the sealed generation's hello, state and activation" { var buf: [1024]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeHello(&w, .{ .client_id = "ignored", .name = "Pipit", .formats = &.{.{ .codec = .flac, .channels = 2, .sample_rate = 48000, .bit_depth = 24 }}, .buffer_capacity = 1000, }, .{ .encrypted = .{} }); try testing.expectEqualStrings( \\{"type":"client/hello","payload":{"name":"Pipit","unpaired_access":{"enabled":true},"supported_roles":["player@v1"],"player@v1_support":{"supported_formats":[{"codec":"flac","channels":2,"sample_rate":48000,"bit_depth":24}],"buffer_capacity":1000,"supported_commands":["volume","mute"]}}} , w.buffered()); w = .fixed(&buf); try writeStatus(&w, .{ .volume = 40, .muted = false, .required_lead_time_ms = 300 }); try testing.expectEqualStrings( \\{"type":"client/state","payload":{"available":true,"player":{"volume":40,"muted":false,"static_delay_ms":0,"required_lead_time_ms":300,"min_buffer_ms":250}}} , w.buffered()); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const act = (try classifyText(a, \\{"type":"server/activate","payload":{"activities":["playback"],"active_roles":["player@v1"]}} )).activate; try testing.expect(act.playback and act.player.?); const none = (try classifyText(a, \\{"type":"server/activate","payload":{"activities":[]}} )).activate; try testing.expect(!none.playback and none.player == null and none.pairing == null); const pair = (try classifyText(a, \\{"type":"server/activate","payload":{"activities":["pairing"],"pairing":{"method":"dynamic_pin","pin_length":6}}} )).activate; try testing.expectEqual(Activate.PairMethod.dynamic_pin, pair.pairing.?.method); try testing.expectEqual(@as(?i64, 6), pair.pairing.?.pin_length); const hello = (try classifyText(a, \\{"type":"server/hello","payload":{"name":"Music Assistant (media01)"}} )).hello; try testing.expectEqualStrings("Music Assistant (media01)", hello.name); } test "typeOf" { try testing.expectEqualStrings("server/hello", typeOf( \\{"payload":{"type":"inner","list":[{"type":"x"}]},"type":"server/hello"} ).?); try testing.expectEqualStrings("client/time", typeOf( \\{"type":"client/time","payload":{"client_transmitted":1}} ).?); try testing.expect(typeOf("[1,2]") == null); try testing.expect(typeOf("{\"type\":1}") == null); try testing.expect(typeOf("{\"type\":\"a\\u0062\"}") == null); try testing.expect(typeOf("not json") == null); } test "stream/request-format" { var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeRequestFormat(&w, .{ .codec = .flac, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }); try testing.expectEqualStrings( \\{"type":"stream/request-format","payload":{"player":{"codec":"flac","channels":1,"sample_rate":8000,"bit_depth":16}}} , w.buffered()); w = .fixed(&buf); try writeRequestFormat(&w, .{ .bit_depth = 16 }); try testing.expectEqualStrings( \\{"type":"stream/request-format","payload":{"player":{"bit_depth":16}}} , w.buffered()); }