// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The messages from the server's side: everything a server writes, and a //! reading of everything a client sends. Nothing here does I/O. //! //! The mirror of `message`, which is the client's side, and written against //! it: the types a message carries -- formats, metadata, the controller's //! state, artwork channels -- are `message`'s, so that what one side writes //! the other reads as the same value. The dialect is aiosendspin 9.1's, //! which is what Music Assistant 2.10 and the clients that meet it speak, //! with aiosendspin 4.4's unencrypted hello beside it; where the //! specification has since moved on, this follows the implementations. const std = @import("std"); const message = @import("message.zig"); const Format = message.Format; const Metadata = message.Metadata; const ControllerState = message.ControllerState; const ControllerCommand = message.ControllerCommand; const ArtworkChannel = message.ArtworkChannel; const Writer = std.Io.Writer; const WriteError = Writer.Error; // --- server to client ---------------------------------------------------- /// `server/hello` on a sealed connection: only the server's name, its id /// having come with the handshake. pub fn writeHello(w: *Writer, name: []const u8) WriteError!void { try std.json.Stringify.value(.{ .type = "server/hello", .payload = .{ .name = name } }, .{}, w); } /// `server/hello` in aiosendspin 4.4's unencrypted protocol, which has no /// activation: the roles it grants are here. pub fn writeLegacyHello(w: *Writer, hello: struct { server_id: []const u8, name: []const u8, active_roles: []const []const u8, connection_reason: ConnectionReason = .playback, }) WriteError!void { try std.json.Stringify.value(.{ .type = "server/hello", .payload = .{ .server_id = hello.server_id, .name = hello.name, .version = 1, .connection_reason = hello.connection_reason, .active_roles = hello.active_roles, }, }, .{}, w); } pub const ConnectionReason = enum { discovery, playback }; pub fn writeTime(w: *Writer, time: message.ServerTime) WriteError!void { try std.json.Stringify.value(.{ .type = "server/time", .payload = time }, .{}, w); } pub const Activity = enum { playback, pairing }; /// `server/activate`: what the connection is for now, the roles it may /// use, and -- to pair -- how. pub const Activate = struct { activities: []const Activity, /// Required on the first; left out after it keeps what was. active_roles: ?[]const []const u8 = null, /// When pairing is among the activities. pairing: ?struct { method: []const u8 = "dynamic_pin", pin_length: u8 } = null, }; pub fn writeActivate(w: *Writer, activate: Activate) WriteError!void { try std.json.Stringify.value(.{ .type = "server/activate", .payload = activate }, .{ .emit_null_optional_fields = false }, w); } /// What a `stream/start` starts: the player's stream, the artwork's, or /// both. pub const StreamStart = struct { player: ?message.StreamStart = null, artwork: ?[]const ArtworkChannel = null, }; /// `stream/start`, stamped with when it was sent on the server's clock. pub fn writeStreamStart(w: *Writer, server_transmitted: i64, start: StreamStart) WriteError!void { var s: std.json.Stringify = .{ .writer = w, .options = .{ .emit_null_optional_fields = false } }; try s.beginObject(); try s.objectField("type"); try s.write("stream/start"); try s.objectField("payload"); try s.beginObject(); try s.objectField("server_transmitted"); try s.write(server_transmitted); if (start.player) |p| { try s.objectField("player"); try s.write(p); } if (start.artwork) |channels| { try s.objectField("artwork"); try s.beginObject(); try s.objectField("channels"); try s.write(channels); try s.endObject(); } try s.endObject(); try s.endObject(); } /// `stream/clear` for `roles`, by their names without versions. pub fn writeStreamClear(w: *Writer, server_transmitted: i64, roles: message.StreamRoles) WriteError!void { try writeStreamRoles(w, "stream/clear", server_transmitted, roles); } pub fn writeStreamEnd(w: *Writer, server_transmitted: i64, roles: message.StreamRoles) WriteError!void { try writeStreamRoles(w, "stream/end", server_transmitted, roles); } fn writeStreamRoles(w: *Writer, comptime kind: []const u8, server_transmitted: i64, roles: message.StreamRoles) WriteError!void { var names: [2][]const u8 = undefined; var n: usize = 0; if (roles.player) { names[n] = "player"; n += 1; } if (roles.artwork) { names[n] = "artwork"; n += 1; } try std.json.Stringify.value(.{ .type = kind, .payload = .{ .server_transmitted = server_transmitted, .roles = names[0..n] }, }, .{}, w); } /// What a `server/state` says of the metadata: nothing, that there is none, /// or all of it. pub const MetadataState = union(enum) { absent, clear, /// Every field is written, null where unknown: whole for the /// specification's clients, and a clearing of what is not there for /// aiosendspin 9.1's, which merge. set: Metadata, }; pub fn writeState(w: *Writer, metadata: MetadataState, controller: ?ControllerState) WriteError!void { var s: std.json.Stringify = .{ .writer = w }; try s.beginObject(); try s.objectField("type"); try s.write("server/state"); try s.objectField("payload"); try s.beginObject(); switch (metadata) { .absent => {}, .clear => { try s.objectField("metadata"); try s.write(null); }, .set => |m| { try s.objectField("metadata"); try s.write(.{ .timestamp = m.timestamp, .title = m.title, .artist = m.artist, .album_artist = m.album_artist, .album = m.album, .artwork_url = m.artwork_url, .year = m.year, .track = m.track, .progress = m.progress, }); }, } if (controller) |c| { try s.objectField("controller"); try s.beginObject(); try s.objectField("supported_commands"); try s.write(c.supported_commands); try s.objectField("volume"); try s.write(c.volume); try s.objectField("muted"); try s.write(c.muted); try s.objectField("repeat"); try s.write(c.repeat); try s.objectField("shuffle"); try s.write(c.shuffle); if (c.seek_max_ms) |max| { try s.objectField("seek_max_ms"); try s.write(max); } try s.endObject(); } try s.endObject(); try s.endObject(); } /// `server/command` for a player: its volume or mute, as the group's were /// set. pub fn writeCommand(w: *Writer, command: message.Command) WriteError!void { switch (command) { .volume => |v| try std.json.Stringify.value(.{ .type = "server/command", .payload = .{ .player = .{ .command = "volume", .volume = @min(v, 100) } }, }, .{}, w), .mute => |m| try std.json.Stringify.value(.{ .type = "server/command", .payload = .{ .player = .{ .command = "mute", .mute = m } }, }, .{}, w), } } pub fn writeGroupUpdate(w: *Writer, update: struct { playback_state: ?message.PlaybackState = null, group_id: ?[]const u8 = null, group_name: ?[]const u8 = null, }) WriteError!void { try std.json.Stringify.value(.{ .type = "group/update", .payload = update }, .{ .emit_null_optional_fields = false }, w); } /// A binary message's header: its type and when it is for, on the server's /// clock. pub fn binaryHeader(kind: message.BinaryType, timestamp_us: i64) [message.binary_header_len]u8 { var out: [message.binary_header_len]u8 = undefined; out[0] = @backingInt(kind); std.mem.writeInt(i64, out[1..9], timestamp_us, .big); return out; } /// The binary type artwork on `channel` travels as. pub fn artworkType(channel: u2) message.BinaryType { return @fromBackingInt(@intCast(@as(u8, 8) + channel)); } // --- client to server ---------------------------------------------------- /// What a client offers in its hello. pub const ClientHello = struct { /// Only in aiosendspin 4.4's unencrypted hello: on a sealed connection /// the id is the key the handshake proved. client_id: ?[]const u8 = null, name: []const u8, /// 1 in the unencrypted hello; absent from the sealed one. version: ?i64 = null, device_info: ?message.DeviceInfo = null, player: ?PlayerSupport = null, metadata: bool = false, controller: bool = false, /// The artwork channels, if it offers the role; at most four. artwork: ?[]const ArtworkChannel = null, /// Whether it offers pairing with a dynamic PIN, and the shortest PIN /// it accepts. dynamic_pin: ?u8 = null, /// Whether it will play for a server it has not paired with. unpaired_access: bool = false, /// Whether it says, on the long-term PSK, that it trusts the server as /// one it paired with. paired: bool = false, pub const PlayerSupport = struct { /// The formats it plays, the one it prefers first; any it names /// that are not PCM, FLAC or Opus are left out. formats: []const Format, buffer_capacity: u32, /// `volume` and `mute`, if it takes them. volume: bool = false, mute: bool = false, }; /// The roles, versioned, it offers and this server speaks. pub fn roles(h: ClientHello, buf: *[4][]const u8) []const []const u8 { var n: usize = 0; if (h.player != null) { buf[n] = message.player_role; n += 1; } if (h.metadata) { buf[n] = message.metadata_role; n += 1; } if (h.controller) { buf[n] = message.controller_role; n += 1; } if (h.artwork != null) { buf[n] = message.artwork_role; n += 1; } return buf[0..n]; } }; /// What a client says of itself in `client/state`. pub const ClientState = struct { /// Whether it is there to play; unsaid, it stays as it was. available: ?bool = null, player: ?struct { volume: ?u8 = null, muted: ?bool = null, static_delay_ms: ?u32 = null, required_lead_time_ms: ?u32 = null, min_buffer_ms: ?u32 = null, } = null, }; /// One message from a client, as much of it as a server uses. Strings /// point into the JSON it was parsed from. pub const ClientIncoming = union(enum) { hello: ClientHello, time: i64, state: ClientState, command: ControllerCommand, request_format: message.FormatRequest, goodbye: []const u8, /// Anything else: pairing's messages, which `pairing` reads, and /// whatever later versions add. other, }; /// What kind of message `v` -- a client's, parsed -- is, and its payload. pub fn classifyClient(arena: std.mem.Allocator, v: std.json.Value) !ClientIncoming { 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, "client/hello")) return .{ .hello = try parseHello(arena, payload) }; if (std.mem.eql(u8, t, "client/time")) { const P = struct { client_transmitted: i64 }; return .{ .time = (try std.json.parseFromValueLeaky(P, arena, payload, opts)).client_transmitted }; } if (std.mem.eql(u8, t, "client/state")) return .{ .state = parseState(arena, payload) }; if (std.mem.eql(u8, t, "client/command")) { const P = struct { controller: ?struct { command: []const u8, volume: ?i64 = null, mute: ?bool = null, position_ms: ?i64 = null, offset_ms: ?i64 = null, } = null }; const p = std.json.parseFromValueLeaky(P, arena, payload, opts) catch return .other; const c = p.controller orelse return .other; return if (commandOf(c.command, c.volume, c.mute, c.position_ms, c.offset_ms)) |cmd| .{ .command = cmd } else .other; } if (std.mem.eql(u8, t, "stream/request-format")) { const P = struct { player: ?struct { codec: ?[]const u8 = null, channels: ?i64 = null, sample_rate: ?i64 = null, bit_depth: ?i64 = null, } = null }; const p = std.json.parseFromValueLeaky(P, arena, payload, opts) catch return .other; const r = p.player orelse return .other; return .{ .request_format = .{ .codec = if (r.codec) |c| std.meta.stringToEnum(message.Codec, c) orelse return .other else null, .channels = if (r.channels) |c| std.math.cast(u8, c) orelse return .other else null, .sample_rate = if (r.sample_rate) |c| std.math.cast(u32, c) orelse return .other else null, .bit_depth = if (r.bit_depth) |c| std.math.cast(u8, c) orelse return .other else null, } }; } if (std.mem.eql(u8, t, "client/goodbye")) { const P = struct { reason: []const u8 = "" }; const p = std.json.parseFromValueLeaky(P, arena, payload, opts) catch return .{ .goodbye = "" }; return .{ .goodbye = p.reason }; } return .other; } fn commandOf(name: []const u8, volume: ?i64, mute: ?bool, position_ms: ?i64, offset_ms: ?i64) ?ControllerCommand { const Tag = std.meta.Tag(ControllerCommand); const tag = std.meta.stringToEnum(Tag, name) orelse return null; return switch (tag) { .volume => .{ .volume = @intCast(std.math.clamp(volume orelse return null, 0, 100)) }, .mute => .{ .mute = mute orelse return null }, .seek => .{ .seek = std.math.cast(u64, position_ms orelse return null) orelse return null }, .seek_relative => .{ .seek_relative = offset_ms orelse return null }, inline else => |t| @unionInit(ControllerCommand, @tagName(t), {}), }; } fn parseHello(arena: std.mem.Allocator, payload: std.json.Value) !ClientHello { if (payload != .object) return error.UnexpectedMessage; const o = payload.object; const name = stringField(o, "name") orelse return error.UnexpectedMessage; var out: ClientHello = .{ .name = name, .client_id = stringField(o, "client_id"), .version = if (o.get("version")) |v| if (v == .integer) v.integer else null else null, }; if (o.get("device_info")) |d| out.device_info = std.json.parseFromValueLeaky(message.DeviceInfo, arena, d, .{ .ignore_unknown_fields = true }) catch null; if (o.get("unpaired_access")) |u| if (u == .object) if (u.object.get("enabled")) |e| if (e == .bool) { out.unpaired_access = e.bool; }; if (stringField(o, "trust_level")) |t| out.paired = std.mem.eql(u8, t, "user"); const roles = o.get("supported_roles") orelse return out; if (roles != .array) return out; for (roles.array.items) |r| { if (r != .string) continue; if (std.mem.eql(u8, r.string, message.player_role)) { const support = supportObject(o, "player") orelse continue; out.player = parsePlayerSupport(arena, support) catch continue; } else if (std.mem.eql(u8, r.string, message.metadata_role)) { out.metadata = true; } else if (std.mem.eql(u8, r.string, message.controller_role)) { out.controller = true; } else if (std.mem.eql(u8, r.string, message.artwork_role)) { const support = supportObject(o, "artwork") orelse continue; out.artwork = parseArtworkSupport(arena, support) catch continue; } } if (o.get("supported_pair_methods")) |methods| if (methods == .array) for (methods.array.items) |m| { if (m != .object) continue; const method = stringField(m.object, "method") orelse continue; if (!std.mem.eql(u8, method, "dynamic_pin")) continue; const min = if (m.object.get("min_pin_length")) |l| if (l == .integer) l.integer else 6 else 6; out.dynamic_pin = std.math.cast(u8, min) orelse continue; }; return out; } /// A role's support object: `@v1_support`, or the unversioned /// `_support` older clients send. fn supportObject(o: std.json.ObjectMap, comptime role: []const u8) ?std.json.Value { const v = o.get(role ++ "@v1_support") orelse o.get(role ++ "_support") orelse return null; return if (v == .object) v else null; } /// Whether the server can send `f`: one to eight channels, as a player /// plays; a rate from 8 to 384 kHz; PCM and FLAC at 16, 24 or 32 bits; and /// Opus at one of its own rates, in mono or stereo. A client may offer /// anything, and a format outside these is dropped from its offer rather /// than handed to an encoder that would divide by its rate or loop on its /// channels. pub fn servable(f: Format) bool { if (f.channels == 0 or f.channels > max_channels) return false; if (f.sample_rate < 8000 or f.sample_rate > 384000) return false; return switch (f.codec) { .pcm, .flac => f.bit_depth == 16 or f.bit_depth == 24 or f.bit_depth == 32, .opus => f.channels <= 2 and switch (f.sample_rate) { 8000, 12000, 16000, 24000, 48000 => true, else => false, }, }; } /// As many channels as the player plays. const max_channels = 8; fn parsePlayerSupport(arena: std.mem.Allocator, v: std.json.Value) !ClientHello.PlayerSupport { const Raw = struct { supported_formats: []const struct { codec: []const u8, channels: i64, sample_rate: i64, bit_depth: i64 = 16 } = &.{}, buffer_capacity: i64 = 0, supported_commands: []const []const u8 = &.{}, }; const raw = try std.json.parseFromValueLeaky(Raw, arena, v, .{ .ignore_unknown_fields = true }); var formats: std.ArrayList(Format) = .empty; for (raw.supported_formats) |f| { const format: Format = .{ .codec = std.meta.stringToEnum(message.Codec, f.codec) orelse continue, .channels = std.math.cast(u8, f.channels) orelse continue, .sample_rate = std.math.cast(u32, f.sample_rate) orelse continue, .bit_depth = std.math.cast(u8, f.bit_depth) orelse continue, }; if (servable(format)) try formats.append(arena, format); } var out: ClientHello.PlayerSupport = .{ .formats = formats.items, .buffer_capacity = std.math.cast(u32, raw.buffer_capacity) orelse std.math.maxInt(u32), }; for (raw.supported_commands) |c| { if (std.mem.eql(u8, c, "volume")) out.volume = true; if (std.mem.eql(u8, c, "mute")) out.mute = true; } return out; } fn parseArtworkSupport(arena: std.mem.Allocator, v: std.json.Value) ![]const ArtworkChannel { const Raw = struct { channels: []const struct { source: message.ArtworkSource, format: message.PictureFormat = .jpeg, media_width: ?u32 = null, media_height: ?u32 = null, width: ?u32 = null, height: ?u32 = null, } = &.{} }; const raw = try std.json.parseFromValueLeaky(Raw, arena, v, .{ .ignore_unknown_fields = true }); const n = @min(raw.channels.len, message.max_artwork_channels); const out = try arena.alloc(ArtworkChannel, n); for (out, raw.channels[0..n]) |*o, c| o.* = .{ .source = c.source, .format = c.format, .width = c.media_width orelse c.width orelse 0, .height = c.media_height orelse c.height orelse 0, }; return out; } fn parseState(arena: std.mem.Allocator, payload: std.json.Value) ClientState { if (payload != .object) return .{}; const o = payload.object; var out: ClientState = .{}; if (o.get("available")) |a| if (a == .bool) { out.available = a.bool; }; // aiosendspin 4.4 says `state` instead: anything but an external source // is there to play. if (out.available == null) if (stringField(o, "state")) |s| { out.available = !std.mem.eql(u8, s, "external_source"); }; if (o.get("player")) |p| if (p == .object) { const Raw = struct { volume: ?i64 = null, muted: ?bool = null, static_delay_ms: ?i64 = null, required_lead_time_ms: ?i64 = null, min_buffer_ms: ?i64 = null, state: ?[]const u8 = null, }; if (std.json.parseFromValueLeaky(Raw, arena, p, .{ .ignore_unknown_fields = true })) |raw| { out.player = .{ .volume = if (raw.volume) |v| @intCast(std.math.clamp(v, 0, 100)) else null, .muted = raw.muted, .static_delay_ms = if (raw.static_delay_ms) |v| std.math.cast(u32, v) else null, .required_lead_time_ms = if (raw.required_lead_time_ms) |v| std.math.cast(u32, v) else null, .min_buffer_ms = if (raw.min_buffer_ms) |v| std.math.cast(u32, v) else null, }; if (out.available == null) if (raw.state) |s| { out.available = !std.mem.eql(u8, s, "external_source"); }; } else |_| {} }; return out; } fn stringField(o: std.json.ObjectMap, name: []const u8) ?[]const u8 { const v = o.get(name) orelse return null; return if (v == .string) v.string else null; } // --- tests: each side against the other ----------------------------------- const testing = std.testing; fn parseText(arena: std.mem.Allocator, text: []const u8) !std.json.Value { return std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}); } fn clientSees(arena: std.mem.Allocator, text: []const u8) !message.Incoming { return message.classify(arena, try parseText(arena, text)); } fn serverSees(arena: std.mem.Allocator, text: []const u8) !ClientIncoming { return classifyClient(arena, try parseText(arena, text)); } test "what a client writes, the server reads" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const a = arena_state.allocator(); var buf: [2048]u8 = undefined; const formats = [_]Format{ .{ .codec = .flac, .channels = 2, .sample_rate = 48000, .bit_depth = 24 }, .{ .codec = .opus, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }, }; const art = [_]ArtworkChannel{.{ .source = .album, .format = .png, .width = 300, .height = 300 }}; var w: Writer = .fixed(&buf); try message.writeHello(&w, .{ .client_id = "c", .name = "Kitchen", .device_info = .{ .product_name = "Pipit" }, .formats = &formats, .buffer_capacity = 1 << 20, .roles = .{ .metadata = true, .controller = true, .artwork = &art }, }, .{ .encrypted = .{ .dynamic_pin = 6, .paired = true } }); const hello = (try serverSees(a, w.buffered())).hello; try testing.expectEqualStrings("Kitchen", hello.name); try testing.expect(hello.client_id == null); try testing.expectEqualStrings("Pipit", hello.device_info.?.product_name.?); try testing.expectEqualSlices(Format, &formats, hello.player.?.formats); try testing.expectEqual(@as(u32, 1 << 20), hello.player.?.buffer_capacity); try testing.expect(hello.player.?.volume and hello.player.?.mute); try testing.expect(hello.metadata and hello.controller); try testing.expectEqualSlices(ArtworkChannel, &art, hello.artwork.?); try testing.expectEqual(@as(?u8, 6), hello.dynamic_pin); try testing.expect(hello.unpaired_access and hello.paired); var roles: [4][]const u8 = undefined; try testing.expectEqual(@as(usize, 4), hello.roles(&roles).len); w = .fixed(&buf); try message.writeHello(&w, .{ .client_id = "legacy-1", .name = "Old", .formats = &formats, .buffer_capacity = 100 }, .legacy); const legacy = (try serverSees(a, w.buffered())).hello; try testing.expectEqualStrings("legacy-1", legacy.client_id.?); try testing.expectEqual(@as(?i64, 1), legacy.version); w = .fixed(&buf); try message.writeTime(&w, 123456); try testing.expectEqual(@as(i64, 123456), (try serverSees(a, w.buffered())).time); w = .fixed(&buf); try message.writeStatus(&w, .{ .volume = 30, .muted = true, .static_delay_ms = 5, .required_lead_time_ms = 400, .min_buffer_ms = 150 }); const state = (try serverSees(a, w.buffered())).state; try testing.expectEqual(@as(?bool, true), state.available); try testing.expectEqual(@as(?u8, 30), state.player.?.volume); try testing.expectEqual(@as(?u32, 400), state.player.?.required_lead_time_ms); try testing.expectEqual(@as(?u32, 150), state.player.?.min_buffer_ms); w = .fixed(&buf); try message.writeState(&w, .external_source, 70, false); try testing.expectEqual(@as(?bool, false), (try serverSees(a, w.buffered())).state.available); w = .fixed(&buf); try message.writeAvailable(&w, true); try testing.expectEqual(@as(?bool, true), (try serverSees(a, w.buffered())).state.available); inline for (.{ ControllerCommand.next, ControllerCommand{ .volume = 40 }, ControllerCommand{ .mute = true }, ControllerCommand{ .seek = 12_000 }, ControllerCommand{ .seek_relative = -3000 }, ControllerCommand.@"switch" }) |cmd| { w = .fixed(&buf); try message.writeCommand(&w, cmd); try testing.expectEqual(cmd, (try serverSees(a, w.buffered())).command); } w = .fixed(&buf); try message.writeRequestFormat(&w, .{ .codec = .flac, .bit_depth = 16 }); const req = (try serverSees(a, w.buffered())).request_format; try testing.expectEqual(@as(?message.Codec, .flac), req.codec); try testing.expectEqual(@as(?u8, 16), req.bit_depth); try testing.expect(req.sample_rate == null); w = .fixed(&buf); try message.writeGoodbye(&w, .restart); try testing.expectEqualStrings("restart", (try serverSees(a, w.buffered())).goodbye); } test "what the server writes, a client reads" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const a = arena_state.allocator(); var buf: [2048]u8 = undefined; var w: Writer = .fixed(&buf); try writeHello(&w, "Living Room"); try testing.expectEqualStrings("Living Room", (try clientSees(a, w.buffered())).hello.name); w = .fixed(&buf); try writeLegacyHello(&w, .{ .server_id = "srv", .name = "Old", .active_roles = &.{message.player_role} }); const legacy = (try clientSees(a, w.buffered())).hello; try testing.expectEqualStrings("srv", legacy.server_id); try testing.expectEqualStrings(message.player_role, legacy.active_roles[0]); w = .fixed(&buf); try writeTime(&w, .{ .client_transmitted = 1, .server_received = 2, .server_transmitted = 3 }); try testing.expectEqual(@as(i64, 2), (try clientSees(a, w.buffered())).time.server_received); w = .fixed(&buf); try writeActivate(&w, .{ .activities = &.{.playback}, .active_roles = &.{ message.player_role, message.metadata_role } }); const act = (try clientSees(a, w.buffered())).activate; try testing.expect(act.playback and act.player.? and act.pairing == null); try testing.expectEqual(@as(usize, 2), act.active_roles.?.len); w = .fixed(&buf); try writeActivate(&w, .{ .activities = &.{.pairing}, .active_roles = &.{}, .pairing = .{ .pin_length = 6 } }); const pair = (try clientSees(a, w.buffered())).activate; try testing.expectEqual(message.Activate.PairMethod.dynamic_pin, pair.pairing.?.method); try testing.expectEqual(@as(?i64, 6), pair.pairing.?.pin_length); const art = [_]ArtworkChannel{.{ .source = .artist, .format = .jpeg, .width = 64, .height = 48 }}; w = .fixed(&buf); try writeStreamStart(&w, 99, .{ .player = .{ .codec = .flac, .sample_rate = 44100, .channels = 2, .bit_depth = 16, .codec_header = "ZkxhQw==" }, .artwork = &art, }); const starts = (try clientSees(a, w.buffered())).stream_start; try testing.expectEqual(message.Codec.flac, starts.player.?.codec); try testing.expectEqualStrings("ZkxhQw==", starts.player.?.codec_header.?); try testing.expectEqualSlices(ArtworkChannel, &art, starts.artwork.?); w = .fixed(&buf); try writeStreamClear(&w, 5, .{ .player = true }); try testing.expectEqual(message.StreamRoles{ .player = true }, (try clientSees(a, w.buffered())).stream_clear); w = .fixed(&buf); try writeStreamEnd(&w, 5, .{ .player = true, .artwork = true }); try testing.expectEqual(message.StreamRoles{ .player = true, .artwork = true }, (try clientSees(a, w.buffered())).stream_end); // Metadata goes whole, and a client merging it into an older one ends // with exactly what was sent: what is unknown now is cleared. const now: Metadata = .{ .timestamp = 7, .title = "Tom Sawyer", .artist = "Rush", .year = 1981, .progress = .{ .track_progress = 1000, .track_duration = 276000, .playback_speed = 1000 }, }; const controller: ControllerState = .{ .supported_commands = &.{ "play", "next" }, .volume = 80, .repeat = .one, .shuffle = true, .seek_max_ms = 276000 }; w = .fixed(&buf); try writeState(&w, .{ .set = now }, controller); const state = (try clientSees(a, w.buffered())).state; const before: Metadata = .{ .title = "Old", .album = "Moving Pictures", .track = 2 }; const merged = try before.merge(a, state.metadata.update); try testing.expectEqualStrings("Tom Sawyer", merged.title.?); try testing.expect(merged.album == null and merged.track == null); try testing.expectEqual(@as(?i64, 1981), merged.year); try testing.expectEqual(now.progress, merged.progress); const c = state.controller.?; try testing.expectEqual(RepeatOf.one, c.repeat); try testing.expect(c.shuffle and c.supports(.next) and !c.supports(.pause)); try testing.expectEqual(@as(?i64, 276000), c.seek_max_ms); w = .fixed(&buf); try writeState(&w, .clear, null); try testing.expectEqual(message.ServerState.MetadataUpdate.clear, (try clientSees(a, w.buffered())).state.metadata); w = .fixed(&buf); try writeCommand(&w, .{ .volume = 250 }); try testing.expectEqual(@as(u8, 100), (try clientSees(a, w.buffered())).command.volume); w = .fixed(&buf); try writeCommand(&w, .{ .mute = true }); try testing.expect((try clientSees(a, w.buffered())).command.mute); w = .fixed(&buf); try writeGroupUpdate(&w, .{ .playback_state = .paused, .group_id = "g" }); try testing.expectEqual(@as(?message.PlaybackState, .paused), (try clientSees(a, w.buffered())).group); var frame: [message.binary_header_len + 3]u8 = undefined; frame[0..message.binary_header_len].* = binaryHeader(artworkType(2), -5); @memcpy(frame[message.binary_header_len..], "img"); const b = try message.parseBinary(&frame); try testing.expectEqual(@as(?u2, 2), b.type.artworkChannel()); try testing.expectEqual(@as(i64, -5), b.timestamp_us); try testing.expectEqualStrings("img", b.data); } const RepeatOf = message.RepeatMode; test "a client's messages that do not hold together are other, not errors" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const a = arena_state.allocator(); const cases = [_][]const u8{ \\{"type":"client/command","payload":{"controller":{"command":"volume"}}} , \\{"type":"client/command","payload":{"controller":{"command":"seek","position_ms":-4}}} , \\{"type":"client/command","payload":{"controller":{"command":"dance"}}} , \\{"type":"stream/request-format","payload":{"player":{"codec":"mp3"}}} , \\{"type":"stream/request-format","payload":{"player":{"channels":300}}} , \\{"type":"client/pair-init","payload":{}} , }; for (cases) |text| try testing.expectEqual(ClientIncoming.other, try serverSees(a, text)); // A hello with no name is no hello. try testing.expectError(error.UnexpectedMessage, serverSees(a, \\{"type":"client/hello","payload":{"supported_roles":["player@v1"]}} )); // A role offered without its support object is not offered. const bare = (try serverSees(a, \\{"type":"client/hello","payload":{"name":"x","supported_roles":["player@v1","artwork@v1"],"player_support":{"supported_formats":[{"codec":"mp3","channels":2,"sample_rate":44100,"bit_depth":16},{"codec":"pcm","channels":2,"sample_rate":44100,"bit_depth":16}],"buffer_capacity":-1}}} )).hello; try testing.expect(bare.artwork == null); try testing.expectEqual(@as(usize, 1), bare.player.?.formats.len); try testing.expectEqual(@as(u32, std.math.maxInt(u32)), bare.player.?.buffer_capacity); // Formats no encoder here can make are dropped from the offer: no // channels, a rate of nothing, a depth PCM has no layout for, Opus at a // rate or in channels it does not code. const odd = (try serverSees(a, \\{"type":"client/hello","payload":{"name":"x","supported_roles":["player@v1"],"player_support":{"supported_formats":[ \\{"codec":"pcm","channels":0,"sample_rate":48000,"bit_depth":16}, \\{"codec":"pcm","channels":2,"sample_rate":0,"bit_depth":16}, \\{"codec":"pcm","channels":2,"sample_rate":48000,"bit_depth":12}, \\{"codec":"flac","channels":9,"sample_rate":48000,"bit_depth":16}, \\{"codec":"opus","channels":2,"sample_rate":44100,"bit_depth":16}, \\{"codec":"opus","channels":6,"sample_rate":48000,"bit_depth":16}, \\{"codec":"opus","channels":2,"sample_rate":48000,"bit_depth":16}],"buffer_capacity":1000}}} )).hello; try testing.expectEqual(@as(usize, 1), odd.player.?.formats.len); try testing.expectEqual(message.Codec.opus, odd.player.?.formats[0].codec); }