Something went wrong. Try again.
Sendspin in Zig, both sides: a player client for Music Assistant, and a server streaming to players in sync
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The client adapter for the Sendspin conformance harness//! (<https://github.com/Sendspin/conformance>): zig-sendspin as one side of//! the harness's matrix, against every server the harness has.//!//! The harness starts the server's adapter, then this, each with the same//! command line of `--name value` pairs, and each writes a JSON summary that//! the harness compares. This one writes `--ready` once it has started, and//! then, as the scenario says://!//! - **the client connects**: it waits for the server to put its URL under//! `--server-name` in the `--registry` file, and connects with//! `Client.run`;//! - **the server connects**: it listens with `Listener` on `--port` and//! `--path`, puts its own URL under `--client-name` in the registry, and//! serves the connection that comes.//!//! Either way it records what arrives until the server closes the//! connection, and writes `--summary`://!//! - PCM is hashed as the harness does, every sample as a little-endian//! `f32` -- through `pcm.decode`, so that the hash is of zig-sendspin's own//! decoding;//! - FLAC and Opus are hashed as they arrive, chunk after chunk, with the//! stream's codec header beside them;//! - the `request-format` scenarios offer two formats, and ask for the//! second with `Client.requestFormat` once the server starts on the first;//! - the protocol scenario builds its evidence from `Client`'s trace -- the//! direction, frame and type of every message, in order -- rather than//! from having got to the end, and checks each assertion against it.//!//! - the metadata scenario offers only the metadata role, and reports what//! `Client` merged the server's states into;//! - the controller scenario offers only the controller role, reports the//! last controller state, and sends the command the harness names once a//! state says the server will take it;//! - the artwork scenario offers only the artwork role, one channel in the//! format and size the harness names, and hashes the images as they//! arrive.//!//! A scenario it does not know it writes a summary saying so for, and//! exits 1, which is what the harness asks of a client that cannot run one.//!//! The harness pairs the two sides beforehand, with nothing passed between//! them but the ids: each derives the client's key pair and a long-term PSK//! from `--client-id` and `--server-id`, as its `_aiosendspin_pairing.py`//! does. So against a server that seals connections, this one is on the//! long-term PSK from the first handshake. Against one that does not seal,//! a `Client` that dialed falls back to the unsealed protocol, as it would//! with any server.//!//! `--unsealed true`, which the harness never passes, leaves the identity//! out, so that the client speaks only aiosendspin 4's unencrypted protocol,//! as it does to Music Assistant 2.8. It is for a server that cannot be//! fallen back to: sendspin-go's adapter takes one connection, unsealed, and//! gives up when that connection starts with `client/init`; and it is what//! the legacy-unencrypted scenario asks for.
const std = @import("std");const Io = std.Io;const sendspin = @import("sendspin");const Listener = @import("sendspin_listener");const noise = @import("noise");const common = @import("conformance_common.zig");
const Sha256 = std.crypto.hash.sha2.Sha256;const Format = sendspin.message.Format;const FormatRequest = sendspin.message.FormatRequest;
const log = std.log.scoped(.conformance);
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"); }
/// The formats offered, the one wanted first. The harness's own clients /// offer the fixture's own 8 kHz mono first, so that the server has no /// reason to resample it. /// The roles offered: the player's, but for the scenarios about the /// others, which offer that one alone. fn roles(s: Scenario, args: Args, artwork: *[1]sendspin.message.ArtworkChannel) !sendspin.message.Roles { return switch (s) { .server_initiated_metadata => .{ .player = false, .metadata = true }, .server_initiated_controller => .{ .player = false, .controller = true }, .server_initiated_artwork => blk: { artwork[0] = .{ .source = .album, .format = std.meta.stringToEnum(sendspin.message.PictureFormat, args.artwork_format) orelse return error.UnknownArtworkFormat, .width = try std.fmt.parseInt(u32, args.artwork_width, 10), .height = try std.fmt.parseInt(u32, args.artwork_height, 10), }; break :blk .{ .player = false, .artwork = artwork }; }, else => .{}, }; }
fn formats(s: Scenario) []const Format { const pcm = [_]Format{ .{ .codec = .pcm, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }, .{ .codec = .pcm, .channels = 2, .sample_rate = 44100, .bit_depth = 16 }, .{ .codec = .pcm, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }, }; const flac = [_]Format{ .{ .codec = .flac, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }, .{ .codec = .flac, .channels = 2, .sample_rate = 44100, .bit_depth = 16 }, .{ .codec = .flac, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }, }; // Opus codes at 48 kHz, and the server resamples to it. const opus = [_]Format{ .{ .codec = .opus, .channels = 1, .sample_rate = 48000, .bit_depth = 16 }, .{ .codec = .opus, .channels = 2, .sample_rate = 48000, .bit_depth = 16 }, }; return switch (s) { .client_initiated_pcm, .server_initiated_pcm, .server_initiated_protocol_baseline_v1, .server_initiated_legacy_unencrypted, => &pcm, .server_initiated_pcm_24bit => &.{.{ .codec = .pcm, .channels = 1, .sample_rate = 8000, .bit_depth = 24 }}, .server_initiated_flac => &flac, .server_initiated_opus => &opus, .client_initiated_request_format_pcm => &.{ .{ .codec = .pcm, .channels = 1, .sample_rate = 8000, .bit_depth = 24 }, .{ .codec = .pcm, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }, }, .client_initiated_request_format_flac => &.{ .{ .codec = .pcm, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }, .{ .codec = .flac, .channels = 1, .sample_rate = 8000, .bit_depth = 16 }, }, .server_initiated_metadata, .server_initiated_controller, .server_initiated_artwork => &.{}, }; }
/// What to ask for once the stream has started, for the scenarios that /// renegotiate: the second of the formats offered. fn request(s: Scenario) ?FormatRequest { return switch (s) { .client_initiated_request_format_pcm, .client_initiated_request_format_flac, => blk: { const f = s.formats()[1]; break :blk .{ .codec = f.codec, .channels = f.channels, .sample_rate = f.sample_rate, .bit_depth = f.bit_depth }; }, else => null, }; }};
/// What the harness passes; everything else it passes is accepted and/// ignored, since each scenario adds its own.const Args = struct { summary: []const u8 = "", ready: []const u8 = "", registry: []const u8 = "", scenario_id: []const u8 = "", initiator_role: []const u8 = "client", preferred_codec: []const u8 = "pcm", client_name: []const u8 = "zig-sendspin-client", client_id: []const u8 = "zig-sendspin-client-id", server_name: []const u8 = "", server_id: []const u8 = "", timeout_seconds: f64 = 30, port: []const u8 = "8928", path: []const u8 = "/sendspin", unsealed: []const u8 = "false", controller_command: []const u8 = "next", artwork_format: []const u8 = "jpeg", artwork_width: []const u8 = "256", artwork_height: []const u8 = "256",};
fn parseArgs(it: *std.process.Args.Iterator) !Args { const args = try common.parseArgs(Args, it); if (args.summary.len == 0 or args.ready.len == 0 or args.registry.len == 0) return error.Usage; return args;}
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 = parseArgs(&it) catch { std.debug.print("usage: sendspin-conformance --summary PATH --ready PATH --registry PATH [--name value]...\n", .{}); return 2; };
const scenario = Scenario.parse(args.scenario_id) orelse { const reason = try std.fmt.allocPrint(arena, "zig-sendspin has the player role alone, and does not run {s}", .{args.scenario_id}); try common.writeJson(io, args.ready, .{ .status = "error" }); try common.writeJson(io, args.summary, .{ .status = "error", .reason = reason }); return 1; };
return run(io, gpa, arena, args, scenario) catch |err| { const reason = try std.fmt.allocPrint(arena, "{t}", .{err}); try common.writeJson(io, args.summary, .{ .status = "error", .reason = reason }); return 1; };}
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 unsealed = std.mem.eql(u8, args.unsealed, "true"); const identity = noise.KeyPair.fromSecret(try common.identity("client", args.client_id)); var psk: Psk = .{ .psk = common.psk(args.server_id, args.client_id) }; psk.psk_id = sendspin.secure.pskId(psk.psk);
const formats = scenario.formats(); var artwork_channels: [1]sendspin.message.ArtworkChannel = undefined; var recorder: Recorder = .{ .io = io, .arena = arena, .request = scenario.request(), .command = if (scenario == .server_initiated_controller) try common.commandOf(args.controller_command) else null, }; var options: sendspin.Client.Options = .{ .address = .{ .hostname = "" }, .hello = .{ .client_id = args.client_id, .name = args.client_name, .formats = formats, .buffer_capacity = 2_000_000, .roles = try scenario.roles(args, &artwork_channels), }, .identity = if (unsealed) null else identity, .pairing = if (unsealed) null else .{ .context = &psk, .lookup = Psk.lookup, .save = Psk.save, .show_pin = Psk.showPin, }, .trace = .{ .context = &recorder, .event = Recorder.onTrace }, };
if (scenario.serverConnects()) { var client: sendspin.Client = .init(io, gpa, options, recorder.sink()); recorder.client = &client; const port = try std.fmt.parseInt(u16, args.port, 10); var listener: Listener = undefined; try listener.init(io, gpa, &client, .{ .address = try .parse("127.0.0.1", port), .path = args.path, .max_message = 1 << 20, }); defer listener.deinit(); var serving = try io.concurrent(Listener.run, .{&listener}); defer serving.cancel(io) catch {};
const url = try std.fmt.allocPrint(arena, "ws://127.0.0.1:{d}{s}", .{ port, args.path }); try common.register(io, arena, args.registry, args.client_name, url); try common.writeJson(io, args.ready, .{ .status = "ready", .scenario_id = args.scenario_id, .initiator_role = args.initiator_role, .url = url, }); try recorder.wait(deadline); // Stopped before the recorder is read: it is the connection's task // that writes it. serving.cancel(io) catch {}; } else { try common.writeJson(io, args.ready, .{ .status = "ready", .scenario_id = args.scenario_id, .initiator_role = args.initiator_role, }); const url = try common.lookup(io, arena, args.registry, args.server_name, deadline); options.address = try common.addressOf(arena, url); var client: sendspin.Client = .init(io, gpa, options, recorder.sink()); recorder.client = &client; var runner = try io.concurrent(sendspin.Client.run, .{&client}); defer runner.cancel(io) catch {}; try recorder.wait(deadline); runner.cancel(io) catch {}; }
const hello = recorder.hello orelse return error.NeverConnected; const stream = recorder.lastStream(); var pcm_digest: [32]u8 = undefined; recorder.pcm_hash.final(&pcm_digest); var encoded_digest: [32]u8 = undefined; recorder.encoded_hash.final(&encoded_digest); var artwork_digest: [32]u8 = undefined; recorder.artwork_hash.final(&artwork_digest); const is_pcm = if (stream) |s| std.mem.eql(u8, s.codec, "pcm") else false;
const summary: Summary = .{ .client_name = args.client_name, .client_id = if (unsealed) args.client_id else &sendspin.secure.peerId(identity.public), .scenario_id = args.scenario_id, .initiator_role = args.initiator_role, .preferred_codec = args.preferred_codec, .peer_hello = .{ .payload = .{ .server_id = hello.server_id, .name = hello.name, .version = hello.version, .active_roles = hello.active_roles, } }, .sealed = recorder.sealed, .paired = hello.paired, .stream = stream, .artwork_stream = if (recorder.artwork_channels) |c| .{ .channels = c } else null, .audio = .{ .audio_chunk_count = recorder.chunks, .received_encoded_sha256 = &std.fmt.bytesToHex(encoded_digest, .lower), .received_pcm_sha256 = if (is_pcm) &std.fmt.bytesToHex(pcm_digest, .lower) else null, .received_sample_count = if (is_pcm) recorder.samples else null, }, .renegotiation = if (scenario.request()) |r| .{ .stream_start_count = recorder.streams.items.len, .requested = r, .initial_format = if (recorder.streams.items.len > 0) recorder.streams.items[0].format() else null, .final_format = if (recorder.streams.items.len > 1) recorder.streams.items[recorder.streams.items.len - 1].format() else null, } else null, .protocol = if (scenario == .server_initiated_protocol_baseline_v1) try common.evidence(arena, .{ .side = .client, .events = recorder.events.items, .complete = recorder.events.items.len < Recorder.max_events, .activations = try recorder.activatedRoles(arena), .offered_roles = &.{sendspin.message.player_role}, .stream = if (recorder.lastStream()) |st| st.format() else null, .advertised = formats, }) else null, .metadata = if (scenario == .server_initiated_metadata) .{ .update_count = recorder.metadata_updates, .received = common.snapshotOf(recorder.metadata), } else null, .controller = if (scenario == .server_initiated_controller) .{ .received_state = if (recorder.controller) |c| .{ .supported_commands = c.supported_commands, .volume = c.volume, .muted = c.muted, .repeat = @tagName(c.repeat), .shuffle = c.shuffle, } else null, .sent_command = if (recorder.sent) |c| .{ .command = c.name() } else null, } else null, .artwork = if (scenario == .server_initiated_artwork) .{ .channel = recorder.artwork_channel, .received_count = recorder.artwork_count, .received_sha256 = if (recorder.artwork_count > 0) &std.fmt.bytesToHex(artwork_digest, .lower) else null, .byte_count = recorder.artwork_bytes, } else null, }; try common.writeJson(io, args.summary, summary);
try common.print(io, summary); return 0;}
const Summary = struct { status: []const u8 = "ok", implementation: []const u8 = "zig-sendspin", role: []const u8 = "client", client_name: []const u8, client_id: []const u8, scenario_id: []const u8, initiator_role: []const u8, preferred_codec: []const u8, peer_hello: struct { type: []const u8 = "server/hello", payload: struct { server_id: []const u8, name: []const u8, version: i64, active_roles: []const []const u8, }, }, sealed: bool, paired: bool, stream: ?Recorder.Stream, artwork_stream: ?struct { channels: []const sendspin.message.ArtworkChannel } = null, audio: struct { audio_chunk_count: u64, received_encoded_sha256: []const u8, received_pcm_sha256: ?[]const u8, received_sample_count: ?u64, }, renegotiation: ?struct { stream_start_count: usize, requested: FormatRequest, initial_format: ?Format, final_format: ?Format, }, protocol: ?common.Protocol, metadata: ?struct { update_count: u64, received: ?common.MetadataSnapshot, }, controller: ?struct { received_state: ?struct { supported_commands: []const []const u8, volume: u8, muted: bool, repeat: []const u8, shuffle: bool, }, sent_command: ?struct { command: []const u8 }, }, artwork: ?struct { channel: ?u2, received_count: u64, received_sha256: ?[]const u8, byte_count: u64, },};
/// The one long-term PSK the harness shares with its server, handed to the/// handshake whenever the server names it.const Psk = struct { psk: [32]u8, psk_id: sendspin.secure.PeerId = undefined,
fn lookup(context: *anyopaque, psk_id: []const u8, _: []const u8) ?[32]u8 { const self: *Psk = @ptrCast(@alignCast(context)); return if (std.mem.eql(u8, psk_id, &self.psk_id)) self.psk else null; }
fn save(_: *anyopaque, _: []const u8, _: [32]u8) anyerror!void {}
fn showPin(_: *anyopaque, _: ?[]const u8) void {}};
/// What the server sends, and every message that goes by, reduced to what/// the harness compares.const Recorder = struct { io: Io, arena: std.mem.Allocator, client: ?*sendspin.Client = null, /// The format to ask for once the first stream starts, if any. request: ?FormatRequest, requested: bool = false, /// The command to send once a controller state says the server takes /// it, and whether it has been. command: ?sendspin.message.ControllerCommand = null, sent: ?sendspin.message.ControllerCommand = null,
metadata: ?sendspin.message.Metadata = null, metadata_updates: u64 = 0, controller: ?sendspin.message.ControllerState = null, artwork_channels: ?[]const sendspin.message.ArtworkChannel = null, artwork_channel: ?u2 = null, artwork_count: u64 = 0, artwork_bytes: u64 = 0, artwork_hash: Sha256 = .init(.{}),
hello: ?sendspin.message.ServerHello = null, sealed: bool = false, streams: std.ArrayList(Stream) = .empty, chunks: u64 = 0, samples: u64 = 0, pcm_hash: Sha256 = .init(.{}), encoded_hash: Sha256 = .init(.{}),
/// Every message, in order, from the trace; and every activation. Both /// are written from more than one task -- the clock sends from its own /// -- so under the lock. lock: Io.Mutex = .init, events: std.ArrayList(common.Event) = .empty, activations: std.ArrayList(?[]const []const u8) = .empty,
/// Set once a connection that got as far as the hellos has ended: the /// server's end of the scenario. done: std.atomic.Value(bool) = .init(false),
/// Enough for any scenario's whole session, audio and all; past it the /// trace is not kept, which the evidence would fail on as incomplete. const max_events = 1 << 16;
const Stream = struct { codec: []const u8, sample_rate: u32, channels: u8, bit_depth: u8, codec_header: ?[]const u8,
fn format(s: Stream) Format { return .{ .codec = std.meta.stringToEnum(sendspin.message.Codec, s.codec).?, .channels = s.channels, .sample_rate = s.sample_rate, .bit_depth = s.bit_depth, }; } };
fn sink(self: *Recorder) sendspin.Client.Sink { return .{ .context = self, .onConnected = onConnected, .onStreamStart = onStreamStart, .onAudio = onAudio, .onStreamClear = onStreamClear, .onStreamEnd = onStreamEnd, .onClock = onClock, .onActivate = onActivate, .onMetadata = onMetadata, .onController = onController, .onArtworkStart = onArtworkStart, .onArtwork = onArtwork, .onDisconnected = onDisconnected, }; }
fn onMetadata(context: *anyopaque, metadata: sendspin.message.Metadata) void { const self: *Recorder = @ptrCast(@alignCast(context)); const a = self.arena; var m = metadata; // Copied: the client's copy goes with the next. inline for (.{ "title", "artist", "album_artist", "album", "artwork_url" }) |f| { if (@field(m, f)) |t| @field(m, f) = a.dupe(u8, t) catch null; } self.metadata = m; self.metadata_updates += 1; }
fn onController(context: *anyopaque, state: sendspin.message.ControllerState) void { const self: *Recorder = @ptrCast(@alignCast(context)); var c = state; const commands = self.arena.alloc([]const u8, c.supported_commands.len) catch return; for (commands, c.supported_commands) |*o, n| o.* = self.arena.dupe(u8, n) catch return; c.supported_commands = commands; self.controller = c; if (self.command) |cmd| if (self.sent == null and c.supports(cmd)) { if (self.client) |client| client.command(cmd) catch |err| { log.err("could not send {s}: {t}", .{ cmd.name(), err }); return; }; self.sent = cmd; }; }
fn onArtworkStart(context: *anyopaque, channels: []const sendspin.message.ArtworkChannel) void { const self: *Recorder = @ptrCast(@alignCast(context)); self.artwork_channels = self.arena.dupe(sendspin.message.ArtworkChannel, channels) catch null; }
fn onArtwork(context: *anyopaque, channel: u2, _: i64, image: []const u8) void { const self: *Recorder = @ptrCast(@alignCast(context)); self.artwork_channel = channel; self.artwork_count += 1; self.artwork_bytes += image.len; self.artwork_hash.update(image); }
/// Every activation's roles; one that named none, none. fn activatedRoles(self: *const Recorder, a: std.mem.Allocator) ![]const []const []const u8 { const out = try a.alloc([]const []const u8, self.activations.items.len); for (out, self.activations.items) |*o, r| o.* = r orelse &.{}; return out; }
fn lastStream(self: *const Recorder) ?Stream { const items = self.streams.items; return if (items.len > 0) items[items.len - 1] else null; }
fn wait(self: *Recorder, deadline: Io.Clock.Timestamp) !void { while (!self.done.load(.acquire)) { if (deadline.durationFromNow(self.io).raw.nanoseconds <= 0) return error.TimedOutWaitingForDisconnect; try self.io.sleep(.fromMilliseconds(20), .awake); } }
fn onTrace(context: *anyopaque, event: sendspin.Client.TraceEvent) void { const self: *Recorder = @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 onActivate(context: *anyopaque, activate: sendspin.message.Activate) void { const self: *Recorder = @ptrCast(@alignCast(context)); const roles: ?[]const []const u8 = if (activate.active_roles) |r| blk: { const out = self.arena.alloc([]const u8, r.len) catch return; for (out, r) |*o, s| o.* = self.arena.dupe(u8, s) catch return; break :blk out; } else null; self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); self.activations.append(self.arena, roles) catch {}; }
fn onConnected(context: *anyopaque, hello: sendspin.message.ServerHello) void { const self: *Recorder = @ptrCast(@alignCast(context)); const a = self.arena; const roles = a.alloc([]const u8, hello.active_roles.len) catch return; for (roles, hello.active_roles) |*r, s| r.* = a.dupe(u8, s) catch return; self.hello = .{ .server_id = a.dupe(u8, hello.server_id) catch return, .name = a.dupe(u8, hello.name) catch return, .version = hello.version, .active_roles = roles, .paired = hello.paired, }; if (self.client) |c| self.sealed = c.sealed.load(.monotonic); log.info("connected to {s}{s}", .{ hello.name, if (hello.paired) ", paired" else "" }); }
fn onStreamStart(context: *anyopaque, format: sendspin.message.StreamStart) void { const self: *Recorder = @ptrCast(@alignCast(context)); self.streams.append(self.arena, .{ .codec = @tagName(format.codec), .sample_rate = format.sample_rate, .channels = format.channels, .bit_depth = format.bit_depth, .codec_header = if (format.codec_header) |h| self.arena.dupe(u8, h) catch null else null, }) catch {}; if (self.request) |r| if (!self.requested) { self.requested = true; if (self.client) |c| c.requestFormat(r) catch |err| log.err("could not ask for another format: {t}", .{err}); }; }
fn onAudio(context: *anyopaque, _: i64, data: []const u8) void { const self: *Recorder = @ptrCast(@alignCast(context)); self.chunks += 1; self.encoded_hash.update(data); const stream = self.lastStream() orelse return; if (!std.mem.eql(u8, stream.codec, "pcm")) return; var samples: [1024]f32 = undefined; var rest = data; const width = sendspin.pcm.bytesPerSample(stream.bit_depth) catch return; while (rest.len >= width) { const n = sendspin.pcm.decode(stream.bit_depth, rest, &samples) catch return; for (samples[0..n]) |s| { var le: [4]u8 = undefined; std.mem.writeInt(u32, &le, @bitCast(s), .little); self.pcm_hash.update(&le); } self.samples += n; rest = rest[n * width ..]; } }
fn onStreamClear(_: *anyopaque) void {} fn onStreamEnd(_: *anyopaque) void {} fn onClock(_: *anyopaque, _: sendspin.TimeFilter) void {}
fn onDisconnected(context: *anyopaque, reason: anyerror) void { const self: *Recorder = @ptrCast(@alignCast(context)); log.info("disconnected: {t}", .{reason}); if (self.hello != null) self.done.store(true, .release); }};
test "scenarios" { try std.testing.expectEqual(Scenario.server_initiated_pcm_24bit, Scenario.parse("server-initiated-pcm-24bit").?); try std.testing.expectEqual(Scenario.server_initiated_metadata, Scenario.parse("server-initiated-metadata").?); try std.testing.expect(Scenario.parse("client-initiated-metadata") == null); try std.testing.expect(Scenario.server_initiated_opus.serverConnects()); try std.testing.expect(!Scenario.client_initiated_request_format_flac.serverConnects()); const r = Scenario.client_initiated_request_format_flac.request().?; try std.testing.expectEqual(sendspin.message.Codec.flac, r.codec.?); try std.testing.expect(Scenario.server_initiated_flac.request() == null);}
test { _ = common;}