// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The server adapter for the Sendspin conformance harness //! (): zig-sendspin's server as one //! side of the harness's matrix, against every client the harness has. //! //! It listens on `--port` whatever the scenario, as the harness's own server //! adapter does, and writes `--ready`. Then, as the scenario says: //! //! - **the client connects**: its URL is put under `--server-name` in the //! `--registry` file, and the client that dials it is served; //! - **the server connects**: the client's URL is read from under //! `--client-name` in the registry, and dialed with `Server.connect`. //! //! Once the client named `--client-name` has joined, the scenario runs on //! the server's default group: //! //! - the audio scenarios stream the first `--clip-seconds` of `--fixture`, //! decoded with zig-flac to 16-bit PCM as the harness decodes it, to the //! client in whatever format it chose -- in 100 ms pieces, and in real time //! for the scenarios in which the client asks for another format midway -- //! then end the stream, which waits for it to have been heard, and //! disconnect; //! - the metadata scenario sets the metadata the harness names; //! - the controller scenario offers the command the harness names, with its //! repeat and shuffle, and waits for the client to send it; //! - the artwork scenario sends the harness's reference picture, drawn with //! z2d at the channel's size and letterboxed, and encoded with z2dimg. //! //! and writes `--summary` with what the harness compares: the source PCM's //! hash, what was sent -- the stream's format and codec header, and every //! chunk -- the client's hello as `peer_hello`, and the protocol evidence //! from the server's side of the trace. //! //! The server's identity and the client's long-term PSK are derived from //! `--server-id` and `--client-id`, as the harness's own adapters derive //! them, so a sealing client is paired from the first handshake. //! `--allow-unencrypted true` speaks aiosendspin 4.4's protocol to a client //! that opens with it. const std = @import("std"); const Io = std.Io; const sendspin = @import("sendspin"); const server_mod = @import("sendspin_server"); const noise = @import("noise"); const flac = @import("flac"); const z2d = @import("z2d"); const z2dimg = @import("z2dimg"); const common = @import("conformance_common.zig"); const Server = server_mod.Server; const Connection = server_mod.Connection; const Group = server_mod.Group; const Listener = server_mod.Listener; const message = sendspin.message; const Sha256 = std.crypto.hash.sha2.Sha256; const log = std.log.scoped(.conformance_server); const Scenario = enum { client_initiated_pcm, server_initiated_pcm, server_initiated_pcm_24bit, server_initiated_flac, server_initiated_opus, server_initiated_protocol_baseline_v1, server_initiated_legacy_unencrypted, client_initiated_request_format_pcm, client_initiated_request_format_flac, server_initiated_metadata, server_initiated_controller, server_initiated_artwork, fn parse(id: []const u8) ?Scenario { var buf: [64]u8 = undefined; if (id.len > buf.len) return null; const name = buf[0..id.len]; for (name, id) |*o, c| o.* = if (c == '-') '_' else c; return std.meta.stringToEnum(Scenario, name); } fn serverConnects(s: Scenario) bool { return std.mem.startsWith(u8, @tagName(s), "server_initiated"); } fn streams(s: Scenario) bool { return switch (s) { .server_initiated_metadata, .server_initiated_controller, .server_initiated_artwork => false, else => true, }; } /// Whether the audio goes in real time, so that a client asking for /// another format midway has audio still to come in it. fn realtime(s: Scenario) bool { return s == .client_initiated_request_format_pcm or s == .client_initiated_request_format_flac; } }; const Args = struct { summary: []const u8 = "", ready: []const u8 = "", registry: []const u8 = "", fixture: []const u8 = "", scenario_id: []const u8 = "", initiator_role: []const u8 = "server", preferred_codec: []const u8 = "pcm", timeout_seconds: f64 = 30, port: []const u8 = "8927", host: []const u8 = "127.0.0.1", server_id: []const u8 = "conformance-server", client_id: []const u8 = "conformance-client-id", server_name: []const u8 = "Sendspin Conformance Server", client_name: []const u8 = "", allow_unencrypted: []const u8 = "false", clip_seconds: f64 = 5, metadata_title: []const u8 = "Almost Silent", metadata_artist: []const u8 = "Sendspin Conformance", metadata_album_artist: []const u8 = "Sendspin", metadata_album: []const u8 = "Protocol Fixtures", metadata_artwork_url: []const u8 = "https://example.invalid/almost-silent.jpg", metadata_year: []const u8 = "2026", metadata_track: []const u8 = "1", metadata_track_progress: []const u8 = "12000", metadata_track_duration: []const u8 = "180000", metadata_playback_speed: []const u8 = "1000", controller_command: []const u8 = "next", controller_repeat: []const u8 = "all", controller_shuffle: []const u8 = "false", artwork_format: []const u8 = "jpeg", artwork_width: []const u8 = "256", artwork_height: []const u8 = "256", }; pub fn main(init: std.process.Init) !u8 { const io = init.io; const gpa = init.gpa; var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); var it = try init.minimal.args.iterateAllocator(gpa); defer it.deinit(); _ = it.skip(); const args = common.parseArgs(Args, &it) catch null; if (args == null or args.?.summary.len == 0 or args.?.ready.len == 0 or args.?.registry.len == 0) { std.debug.print("usage: sendspin-conformance-server --summary PATH --ready PATH --registry PATH --fixture PATH [--name value]...\n", .{}); return 2; } const a = args.?; const failure = struct { fn write(i: Io, al: std.mem.Allocator, x: Args, comptime fmt: []const u8, fa: anytype) !u8 { const reason = try std.fmt.allocPrint(al, fmt, fa); try common.writeJson(i, x.summary, .{ .status = "error", .implementation = "zig-sendspin", .role = "server", .scenario_id = x.scenario_id, .reason = reason }); return 1; } }.write; const scenario = Scenario.parse(a.scenario_id) orelse return failure(io, arena, a, "zig-sendspin's server does not run {s}", .{a.scenario_id}); return run(io, gpa, arena, a, scenario) catch |err| failure(io, arena, a, "{t}", .{err}); } fn parseInt(s: []const u8) !i64 { return std.fmt.parseInt(i64, s, 10); } fn run(io: Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, args: Args, scenario: Scenario) !u8 { const deadline: Io.Clock.Timestamp = .fromNow(io, .{ .raw = .fromNanoseconds(@intFromFloat(args.timeout_seconds * std.time.ns_per_s)), .clock = .awake, }); const identity = noise.KeyPair.fromSecret(try common.identity("server", args.server_id)); const client_key = noise.KeyPair.fromSecret(try common.identity("client", args.client_id)); var store: Store = .{ .client_id = sendspin.secure.peerId(client_key.public), .psk = common.psk(args.server_id, args.client_id) }; var watch: Watch = .{ .io = io, .arena = arena, .client_name = args.client_name }; var painter: Painter = .{ .gpa = gpa, .arena = arena }; var server: Server = undefined; try server.init(io, gpa, .{ .name = args.server_name, .identity = identity, .psks = .{ .context = &store, .lookup = Store.lookup }, .allow_unencrypted = std.mem.eql(u8, args.allow_unencrypted, "true"), .trace = .{ .context = &watch, .event = Watch.onTrace }, .observer = .{ .context = &watch, .onStart = Watch.onStart, .onChunk = Watch.onChunk }, .artwork = .{ .context = &painter, .render = Painter.render }, }, watch.sink()); defer server.deinit(); const port = try std.fmt.parseInt(u16, args.port, 10); var listener: Listener = undefined; try listener.init(io, gpa, &server, .{ .address = try .parse(args.host, port) }); defer listener.deinit(); var serving = try io.concurrent(runListener, .{&listener}); defer serving.cancel(io) catch {}; const url = try std.fmt.allocPrint(arena, "ws://127.0.0.1:{d}/sendspin", .{port}); const server_id = sendspin.secure.peerId(identity.public); if (!scenario.serverConnects()) try common.register(io, arena, args.registry, args.server_name, url); try common.writeJson(io, args.ready, .{ .status = "ready", .server_id = &server_id, .server_name = args.server_name, .scenario_id = args.scenario_id, .initiator_role = args.initiator_role, .url = url, }); var dialing: ?Io.Future(@typeInfo(@TypeOf(Server.connect)).@"fn".return_type.?) = null; defer if (dialing) |*d| d.cancel(io) catch {}; if (scenario.serverConnects()) { const client_url = try common.lookup(io, arena, args.registry, args.client_name, deadline); dialing = try io.concurrent(Server.connect, .{ &server, try common.addressOf(arena, client_url) }); } const conn = try watch.waitForClient(deadline); defer conn.release(); const group = server.default_group; var payload: Payload = .{}; if (scenario.streams()) { payload.audio = try streamFixture(io, gpa, arena, args, scenario, group, &watch); payload.stream = watch.stream; } else switch (scenario) { .server_initiated_metadata => { const m: message.Metadata = .{ .timestamp = Server.now(), .title = args.metadata_title, .artist = args.metadata_artist, .album_artist = args.metadata_album_artist, .album = args.metadata_album, .artwork_url = args.metadata_artwork_url, .year = try parseInt(args.metadata_year), .track = try parseInt(args.metadata_track), .progress = .{ .track_progress = try parseInt(args.metadata_track_progress), .track_duration = try parseInt(args.metadata_track_duration), .playback_speed = try parseInt(args.metadata_playback_speed), }, }; try group.setMetadata(m); payload.metadata = .{ .expected = common.snapshotOf(m).? }; try io.sleep(.fromMilliseconds(500), .awake); }, .server_initiated_controller => { const command = try common.commandOf(args.controller_command); const repeat = std.meta.stringToEnum(message.RepeatMode, args.controller_repeat) orelse return error.UnknownRepeat; const shuffle = std.mem.eql(u8, args.controller_shuffle, "true"); try group.setController(.{ .supported_commands = &.{args.controller_command}, .repeat = repeat, .shuffle = shuffle }); const received = try watch.waitForCommand(deadline); payload.controller = .{ .expected_command = .{ .command = command.name() }, .received_command = .{ .command = received.name() }, .supported_commands = &.{args.controller_command}, .repeat = @tagName(repeat), .shuffle = shuffle, }; try io.sleep(.fromMilliseconds(200), .awake); }, .server_initiated_artwork => { const format = std.meta.stringToEnum(message.PictureFormat, args.artwork_format) orelse return error.UnknownArtworkFormat; try group.setArtwork(.album, true); const sent = painter.last orelse return error.NothingRendered; payload.artwork = .{ .channel = 0, .source = "album", .format = @tagName(format), .width = try std.fmt.parseInt(u32, args.artwork_width, 10), .height = try std.fmt.parseInt(u32, args.artwork_height, 10), .encoded_sha256 = &std.fmt.bytesToHex(sent.sha256, .lower), .byte_count = sent.len, }; try io.sleep(.fromMilliseconds(500), .awake); }, else => unreachable, } conn.disconnect(); watch.waitForLeave(Io.Clock.Timestamp.fromNow(io, .{ .raw = .fromSeconds(5), .clock = .awake })); // The client's hello, as it sent it. const hello = try std.json.parseFromSliceLeaky(std.json.Value, arena, conn.hello_text, .{}); const hello_payload = if (hello == .object) hello.object.get("payload") orelse .null else .null; var offered_buf: [4][]const u8 = undefined; var granted_buf: [4][]const u8 = undefined; const summary: Summary = .{ .server_id = &server_id, .server_name = args.server_name, .scenario_id = args.scenario_id, .initiator_role = args.initiator_role, .preferred_codec = args.preferred_codec, .discovery_method = if (scenario.serverConnects()) "registry" else "registry_advertised", .peer_hello = .{ .payload = hello_payload }, .client = .{ .client_id = conn.client_id, .name = conn.hello.name }, .stream = payload.stream, .audio = payload.audio, .metadata = payload.metadata, .controller = payload.controller, .artwork = payload.artwork, .protocol = if (scenario == .server_initiated_protocol_baseline_v1) try common.evidence(arena, .{ .side = .server, .events = watch.events.items, .complete = watch.events.items.len < Watch.max_events, .activations = &.{conn.roles.names(&granted_buf)}, .offered_roles = conn.hello.roles(&offered_buf), .stream = if (watch.stream) |st| st.format() else null, .advertised = if (conn.hello.player) |p| p.formats else &.{}, }) else null, }; try common.writeJson(io, args.summary, summary); try common.print(io, summary); return 0; } fn runListener(l: *Listener) anyerror!void { return l.run(); } const Payload = struct { stream: ?Watch.Stream = null, audio: ?Audio = null, metadata: ?Expected = null, controller: ?Controller = null, artwork: ?Artwork = null, }; const Expected = struct { expected: common.MetadataSnapshot }; const Audio = struct { fixture: []const u8, source_pcm_sha256: []const u8, sent_codec_header_sha256: ?[]const u8, sent_encoded_sha256: ?[]const u8, sent_audio_chunk_count: u64, sent_encoded_byte_count: u64, clip_seconds: f64, sample_rate: u32, channels: u8, bit_depth: u8, frame_count: u64, duration_seconds: f64, }; const Controller = struct { expected_command: struct { command: []const u8 }, received_command: struct { command: []const u8 }, supported_commands: []const []const u8, repeat: []const u8, shuffle: bool, }; const Artwork = struct { channel: u8, source: []const u8, format: []const u8, width: u32, height: u32, encoded_sha256: []const u8, byte_count: usize, }; const Summary = struct { status: []const u8 = "ok", implementation: []const u8 = "zig-sendspin", role: []const u8 = "server", server_id: []const u8, server_name: []const u8, scenario_id: []const u8, initiator_role: []const u8, preferred_codec: []const u8, discovery_method: []const u8, peer_hello: struct { type: []const u8 = "client/hello", payload: std.json.Value }, client: struct { client_id: []const u8, name: []const u8 }, stream: ?Watch.Stream, audio: ?Audio, metadata: ?Expected, controller: ?Controller, artwork: ?Artwork, protocol: ?common.Protocol, }; /// The first `clip_seconds` of the fixture, played to the group; ended, and /// waited out until it has been heard. fn streamFixture(io: Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, args: Args, scenario: Scenario, group: *Group, watch: *Watch) !Audio { const fixture = try decodeFixture(io, gpa, arena, args.fixture, args.clip_seconds); try group.start(.{ .sample_rate = fixture.rate, .channels = fixture.channels }); // A moment between `stream/start` and the first audio. The order on the // wire is right either way; but sendspin-go's client adapter takes the // two from separate Go channels in one `select`, which picks at random // between those ready, and fails the case if it takes a chunk first. try io.sleep(.fromMilliseconds(200), .awake); const block = fixture.rate / 10 * fixture.channels; const floats = try gpa.alloc(f32, block); defer gpa.free(floats); var at: usize = 0; while (at < fixture.samples.len) : (at += block) { const piece = fixture.samples[at..@min(at + block, fixture.samples.len)]; for (floats[0..piece.len], piece) |*f, s| f.* = @as(f32, @floatFromInt(s)) / 32768; try group.write(floats[0..piece.len]); if (scenario.realtime()) try io.sleep(.fromMilliseconds(100), .awake); } // Once it has been heard: a player may drop what it holds on // `stream/end`, as sendspin-dotnet's does. Then a moment for the player // to finish with it before the connection goes, as the harness's own // server allows. try group.end(); try io.sleep(.fromMilliseconds(500), .awake); var source: Sha256 = .init(.{}); for (fixture.samples) |s| { var le: [4]u8 = undefined; std.mem.writeInt(u32, &le, @bitCast(@as(f32, @floatFromInt(s)) / 32768), .little); source.update(&le); } var sent: [32]u8 = undefined; watch.sent_hash.final(&sent); const frames = fixture.samples.len / fixture.channels; return .{ .fixture = args.fixture, .source_pcm_sha256 = try arena.dupe(u8, &std.fmt.bytesToHex(source.finalResult(), .lower)), .sent_codec_header_sha256 = if (watch.stream) |st| st.codec_header_sha256 else null, .sent_encoded_sha256 = if (watch.chunks > 0) try arena.dupe(u8, &std.fmt.bytesToHex(sent, .lower)) else null, .sent_audio_chunk_count = watch.chunks, .sent_encoded_byte_count = watch.sent_bytes, .clip_seconds = args.clip_seconds, .sample_rate = fixture.rate, .channels = fixture.channels, .bit_depth = if (watch.stream) |st| st.bit_depth else 16, .frame_count = frames, .duration_seconds = @as(f64, @floatFromInt(frames)) / @as(f64, @floatFromInt(fixture.rate)), }; } const Fixture = struct { rate: u32, channels: u8, /// 16-bit, interleaved: as the harness decodes it, a wider sample's /// top sixteen bits. samples: []const i16, }; fn decodeFixture(io: Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, path: []const u8, clip_seconds: f64) !Fixture { const bytes = try Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)); var reader: Io.Reader = .fixed(bytes); var decoder = try flac.Decoder.init(gpa, &reader, .{ .verify_md5 = false }); defer decoder.deinit(); const info = decoder.streaminfo; const bits = info.bits_per_sample; const max_frames: usize = @intFromFloat(@as(f64, @floatFromInt(info.sample_rate)) * clip_seconds); var samples: std.ArrayList(i16) = .empty; var frames: usize = 0; while (frames < max_frames) { const frame = (try decoder.decodeFrame(&reader, 0)) orelse break; const n = @min(frame.header.block_size, max_frames - frames); for (0..n) |i| for (frame.channels) |plane| { const v = plane[i]; const s: i32 = if (bits > 16) v >> @intCast(bits - 16) else v << @intCast(16 - bits); try samples.append(arena, @intCast(s)); }; frames += n; } return .{ .rate = info.sample_rate, .channels = @intCast(info.channels), .samples = samples.items }; } /// The client's long-term PSK, as the harness pairs it. const Store = struct { client_id: sendspin.secure.PeerId, psk: [32]u8, fn lookup(context: *anyopaque, client_id: []const u8) ?[32]u8 { const self: *Store = @ptrCast(@alignCast(context)); return if (std.mem.eql(u8, client_id, &self.client_id)) self.psk else null; } }; /// Everything the server says it did: the client joining and leaving, the /// trace, the stream's format and every chunk sent. const Watch = struct { io: Io, arena: std.mem.Allocator, client_name: []const u8, lock: Io.Mutex = .init, client: std.atomic.Value(?*Connection) = .init(null), left: std.atomic.Value(bool) = .init(false), /// The command a controller sent, once `commanded` says there is one. command: message.ControllerCommand = undefined, commanded: std.atomic.Value(bool) = .init(false), events: std.ArrayList(common.Event) = .empty, stream: ?Stream = null, chunks: u64 = 0, sent_bytes: u64 = 0, sent_hash: Sha256 = .init(.{}), const max_events = 1 << 16; const Stream = struct { codec: []const u8, sample_rate: u32, channels: u8, bit_depth: u8, codec_header: ?[]const u8, codec_header_sha256: ?[]const u8, fn format(s: Stream) message.Format { return .{ .codec = std.meta.stringToEnum(message.Codec, s.codec).?, .channels = s.channels, .sample_rate = s.sample_rate, .bit_depth = s.bit_depth, }; } }; fn sink(self: *Watch) Server.Sink { return .{ .context = self, .onJoin = onJoin, .onLeave = onLeave, .onCommand = onCommand }; } fn onJoin(context: *anyopaque, c: *Connection) void { const self: *Watch = @ptrCast(@alignCast(context)); if (!std.mem.eql(u8, c.hello.name, self.client_name)) return; c.retain(); self.client.store(c, .release); } fn onLeave(context: *anyopaque, c: *Connection) void { const self: *Watch = @ptrCast(@alignCast(context)); if (self.client.load(.acquire) == c) self.left.store(true, .release); } fn onCommand(context: *anyopaque, _: *Connection, c: message.ControllerCommand) void { const self: *Watch = @ptrCast(@alignCast(context)); self.command = c; self.commanded.store(true, .release); } fn onTrace(context: *anyopaque, event: sendspin.Client.TraceEvent) void { const self: *Watch = @ptrCast(@alignCast(context)); self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); if (self.events.items.len >= max_events) return; const e = common.Event.of(self.arena, event) catch return; self.events.append(self.arena, e) catch {}; } fn onStart(context: *anyopaque, _: *Connection, start: message.StreamStart) void { const self: *Watch = @ptrCast(@alignCast(context)); self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); var header_sha: ?[]const u8 = null; if (start.codec_header) |h| blk: { const raw = self.arena.alloc(u8, std.base64.standard.Decoder.calcSizeForSlice(h) catch break :blk) catch break :blk; std.base64.standard.Decoder.decode(raw, h) catch break :blk; var digest: [32]u8 = undefined; Sha256.hash(raw, &digest, .{}); header_sha = self.arena.dupe(u8, &std.fmt.bytesToHex(digest, .lower)) catch null; } self.stream = .{ .codec = @tagName(start.codec), .sample_rate = start.sample_rate, .channels = start.channels, .bit_depth = start.bit_depth, .codec_header = if (start.codec_header) |h| self.arena.dupe(u8, h) catch null else null, .codec_header_sha256 = header_sha, }; } fn onChunk(context: *anyopaque, _: message.Format, _: i64, bytes: []const u8) void { const self: *Watch = @ptrCast(@alignCast(context)); self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); self.chunks += 1; self.sent_bytes += bytes.len; self.sent_hash.update(bytes); } fn waitForClient(self: *Watch, deadline: Io.Clock.Timestamp) !*Connection { while (true) { if (self.client.load(.acquire)) |c| return c; if (deadline.durationFromNow(self.io).raw.nanoseconds <= 0) return error.TimedOutWaitingForClient; try self.io.sleep(.fromMilliseconds(20), .awake); } } fn waitForCommand(self: *Watch, deadline: Io.Clock.Timestamp) !message.ControllerCommand { while (true) { if (self.commanded.load(.acquire)) return self.command; if (deadline.durationFromNow(self.io).raw.nanoseconds <= 0) return error.TimedOutWaitingForCommand; try self.io.sleep(.fromMilliseconds(20), .awake); } } fn waitForLeave(self: *Watch, deadline: Io.Clock.Timestamp) void { while (!self.left.load(.acquire)) { if (deadline.durationFromNow(self.io).raw.nanoseconds <= 0) return; self.io.sleep(.fromMilliseconds(20), .awake) catch return; } } }; /// The harness's reference picture -- three bands, a disc, four bars and a /// rule -- drawn at a channel's size, scaled to fit and letterboxed in /// black, and encoded. What it last sent, for the summary. const Painter = struct { gpa: std.mem.Allocator, arena: std.mem.Allocator, last: ?struct { sha256: [32]u8, len: usize } = null, const width = 320; const height = 200; fn render(context: *anyopaque, _: *Group, _: message.ArtworkSource, format: message.PictureFormat, w: u32, h: u32, out: *Io.Writer) anyerror!void { const self: *Painter = @ptrCast(@alignCast(context)); if (w == 0 or h == 0) return error.NoSize; var sfc = try z2d.Surface.init(.image_surface_rgb, self.gpa, @intCast(w), @intCast(h)); defer sfc.deinit(self.gpa); // Fit, as the harness's server fits: by the wider aspect. const scale = @min(@as(f64, @floatFromInt(w)) / width, @as(f64, @floatFromInt(h)) / height); const drawn_w: u32 = @intFromFloat(@floor(width * scale)); const drawn_h: u32 = @intFromFloat(@floor(height * scale)); const x0 = (w - drawn_w) / 2; const y0 = (h - drawn_h) / 2; for (0..drawn_h) |y| for (0..drawn_w) |x| { const sx = (@as(f64, @floatFromInt(x)) + 0.5) / scale; const sy = (@as(f64, @floatFromInt(y)) + 0.5) / scale; sfc.putPixel(@intCast(x0 + x), @intCast(y0 + y), .{ .rgb = colourAt(sx, sy) }); }; var bytes: Io.Writer.Allocating = .init(self.gpa); defer bytes.deinit(); switch (format) { .jpeg => try z2dimg.jpeg.encode(self.gpa, &sfc, &bytes.writer, .{ .quality = 85 }), .png => try z2dimg.png.encode(self.gpa, &sfc, &bytes.writer, .{}), } var digest: [32]u8 = undefined; Sha256.hash(bytes.written(), &digest, .{}); self.last = .{ .sha256 = digest, .len = bytes.written().len }; try out.writeAll(bytes.written()); } fn rgb(hex: u24) z2d.pixel.RGB { return .{ .r = @truncate(hex >> 16), .g = @truncate(hex >> 8), .b = @truncate(hex) }; } /// The reference picture's colour at (`x`, `y`), in its own 320 by 200. fn colourAt(x: f64, y: f64) z2d.pixel.RGB { const in = struct { fn rect(px: f64, py: f64, x1: f64, y1: f64, x2: f64, y2: f64) bool { return px >= x1 and px <= x2 and py >= y1 and py <= y2; } }.rect; // The disc, its outline four wide. const dx = (x - 69) / 45; const dy = (y - 67) / 45; const d = dx * dx + dy * dy; if (d <= 1) return if (d >= 0.83) rgb(0x4b2f1b) else rgb(0xf3e5cf); if (in(x, y, 152, 151.5, 292, 154.5)) return rgb(0x4b2f1b); if (in(x, y, 150, 36, 280, 54)) return rgb(0xf3e5cf); if (in(x, y, 150, 74, 252, 88)) return rgb(0xe7c49f); if (in(x, y, 150, 102, 264, 116)) return rgb(0xe7c49f); if (in(x, y, 150, 140, 296, 166)) return rgb(0xd7a16d); if (y < 60) return rgb(0xc9783b); if (y < 130) return rgb(0x935228); return rgb(0x4b2f1b); } }; test { _ = common; } test "scenarios" { try std.testing.expectEqual(Scenario.server_initiated_artwork, Scenario.parse("server-initiated-artwork").?); try std.testing.expect(Scenario.parse("client-initiated-artwork") == null); try std.testing.expect(!Scenario.server_initiated_controller.streams()); try std.testing.expect(Scenario.client_initiated_request_format_pcm.realtime()); try std.testing.expect(!Scenario.client_initiated_pcm.serverConnects()); } test "the reference picture, letterboxed, encodes" { var painter: Painter = .{ .gpa = std.testing.allocator, .arena = std.testing.allocator }; var out: Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); try Painter.render(&painter, undefined, .album, .png, 64, 64, &out.writer); try std.testing.expectEqualSlices(u8, "\x89PNG", out.written()[0..4]); out.clearRetainingCapacity(); try Painter.render(&painter, undefined, .album, .jpeg, 256, 256, &out.writer); try std.testing.expectEqualSlices(u8, "\xff\xd8", out.written()[0..2]); try std.testing.expectEqual(out.written().len, painter.last.?.len); }