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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The glue between a `Client` and a `Scheduler`: a `Client.Sink` that//! decodes what arrives and queues it to be played on time.//!//! It decodes FLAC, Opus and PCM. `formats` offers FLAC first unless asked//! for Opus: FLAC is lossless, so it sounds exactly as PCM does at around//! half the bytes on the network, where Opus is lossy and a tenth of that//! again. The audio device reads from `scheduler` on its own thread://!//! ```zig//! var scheduler: sendspin.Scheduler = .init(gpa, .{});//! var player: sendspin.Player = .init(gpa, &scheduler);//! defer player.deinit();//! const formats = sendspin.Player.formats(48000, .lossless);//! var client: sendspin.Client = .init(io, gpa, .{ ..., .hello = .{//! ...//! .formats = formats.slice(),//! } }, player.sink());//! ```//!//! ## FLAC on the wire//!//! `stream/start` carries the stream header in `codec_header`, base64: the//! `fLaC` signature and a single metadata block, the streaminfo, marked as//! the last. Every audio message is then one FLAC frame as the encoder wrote//! it, stamped with the moment its first sample is to be heard. That is how//! aiosendspin's encoder sends it, which is Music Assistant's.//!//! ## Opus on the wire//!//! No header at all: every audio message is one Opus packet as RFC 6716//! defines it, with no Ogg around it, 20 ms long as libopus's encoder makes//! them. The server has already moved the timestamps back by the encoder's//! pre-skip, so a packet's samples are played from its timestamp as they//! come out of the decoder.
const Player = @This();
const std = @import("std");const flac = @import("flac");const opus = @import("opus");
const Client = @import("Client.zig");const message = @import("message.zig");const pcm = @import("pcm.zig");const Scheduler = @import("Scheduler.zig");const TimeFilter = @import("TimeFilter.zig");
const log = std.log.scoped(.sendspin);
gpa: std.mem.Allocator,scheduler: *Scheduler,/// What the stream playing is coded as, and what it takes to decode it.codec: Codec = .none,/// Where each chunk is decoded to, interleaved, grown to the largest seen.decoded: []f32 = &.{},/// Told whatever the client is told, after the player has dealt with it./// Optional; for a program that wants to show what is happening.observer: ?Client.Sink = null,/// What the server last set, which the scheduler plays at.volume: u8 = 100,muted: bool = false,
const Codec = union(enum) { /// No stream, or one in a format this cannot decode. none, /// PCM of this many bits. pcm: u8, flac: Flac, opus: Opus,};
const Opus = struct { decoder: opus.Decoder,};
const Flac = struct { decoder: flac.Decoder, rate: u32, /// 1 / 2^(bits - 1): what takes a sample to the range -1 to 1. scale: f32,};
pub fn init(gpa: std.mem.Allocator, scheduler: *Scheduler) Player { return .{ .gpa = gpa, .scheduler = scheduler };}
pub fn deinit(self: *Player) void { self.dropCodec(); self.gpa.free(self.decoded);}
/// Which of the codecs to ask for first.pub const Preference = enum { /// FLAC, then PCM, then Opus: nothing lost, for a local network. lossless, /// Opus, then the rest: a tenth of FLAC's bytes, for a slow link. opus,};
/// The formats `formats` offers, in order.pub const Formats = struct { buffer: [6]message.Format, len: usize,
pub fn slice(f: *const Formats) []const message.Format { return f.buffer[0..f.len]; }
fn add(f: *Formats, format: message.Format) void { f.buffer[f.len] = format; f.len += 1; }};
/// What to offer in `client/hello` for a device running at `rate`: stereo,/// at the device's own rate, so that the server does the resampling and the/// samples can go straight out. FLAC at the depths Music Assistant's encoder/// writes -- its FLAC encoder stops at 24 bits -- then PCM, deepest first.////// Opus goes first or last as `preference` says, and only if `rate` is one/// Opus codes at -- 48, 24, 16, 12 or 8 kHz -- since the server refuses it at/// any other. It is offered at 16 bits, the only depth the server accepts for/// it; the depth means nothing to a lossy codec, and the samples come out as/// floating point regardless.pub fn formats(rate: u32, preference: Preference) Formats { var f: Formats = .{ .buffer = undefined, .len = 0 }; const offer_opus = switch (rate) { 8000, 12000, 16000, 24000, 48000 => true, else => false, }; const opus_format: message.Format = .{ .codec = .opus, .channels = 2, .sample_rate = rate, .bit_depth = 16 }; if (offer_opus and preference == .opus) f.add(opus_format); f.add(.{ .codec = .flac, .channels = 2, .sample_rate = rate, .bit_depth = 24 }); f.add(.{ .codec = .flac, .channels = 2, .sample_rate = rate, .bit_depth = 16 }); f.add(.{ .codec = .pcm, .channels = 2, .sample_rate = rate, .bit_depth = 24 }); f.add(.{ .codec = .pcm, .channels = 2, .sample_rate = rate, .bit_depth = 16 }); f.add(.{ .codec = .pcm, .channels = 2, .sample_rate = rate, .bit_depth = 32 }); if (offer_opus and preference == .lossless) f.add(opus_format); return f;}
pub fn sink(self: *Player) Client.Sink { return .{ .context = self, .onConnected = onConnected, .onStreamStart = onStreamStart, .onAudio = onAudio, .onStreamClear = onStreamClear, .onStreamEnd = onStreamEnd, .onCommand = onCommand, .onClock = onClock, .onPlayback = onPlayback, .onDisconnected = onDisconnected, };}
fn from(context: *anyopaque) *Player { return @ptrCast(@alignCast(context));}
fn dropCodec(self: *Player) void { switch (self.codec) { .flac => |*f| f.decoder.deinit(), .none, .pcm, .opus => {}, } self.codec = .none;}
fn onConnected(context: *anyopaque, hello: message.ServerHello) void { const self = from(context); if (self.observer) |o| o.onConnected(o.context, hello);}
fn onStreamStart(context: *anyopaque, format: message.StreamStart) void { const self = from(context); self.dropCodec(); self.start(format) catch |err| { log.warn("cannot play the {t} stream the server started ({d} Hz, {d} bit, {d} channels): {t}", .{ format.codec, format.sample_rate, format.bit_depth, format.channels, err, }); self.dropCodec(); self.scheduler.stop(); }; if (self.observer) |o| o.onStreamStart(o.context, format);}
fn start(self: *Player, format: message.StreamStart) !void { switch (format.codec) { .pcm => { _ = try pcm.bytesPerSample(format.bit_depth); try self.scheduler.start(format.channels, format.sample_rate); self.codec = .{ .pcm = format.bit_depth }; }, .flac => { const encoded = format.codec_header orelse return error.NoCodecHeader; const header = try self.gpa.alloc(u8, try std.base64.standard.Decoder.calcSizeForSlice(encoded)); defer self.gpa.free(header); try std.base64.standard.Decoder.decode(header, encoded); var reader: std.Io.Reader = .fixed(header); // The frames arrive one at a time and the stream never ends, so // there is no whole to check an MD5 against. const decoder = try flac.Decoder.init(self.gpa, &reader, .{ .verify_md5 = false }); self.codec = .{ .flac = .{ .decoder = decoder, .rate = decoder.streaminfo.sample_rate, .scale = std.math.ldexp(@as(f32, 1), -@as(i32, decoder.streaminfo.bits_per_sample - 1)), } }; const info = decoder.streaminfo; if (info.channels != format.channels or info.sample_rate != format.sample_rate) return error.HeaderDisagrees; try self.scheduler.start(info.channels, info.sample_rate); }, .opus => { const decoder = try opus.Decoder.init(format.sample_rate, format.channels); try self.scheduler.start(format.channels, format.sample_rate); self.codec = .{ .opus = .{ .decoder = decoder } }; }, }}
fn onAudio(context: *anyopaque, timestamp_us: i64, data: []const u8) void { const self = from(context); switch (self.codec) { .none => {}, .pcm => |depth| self.playPcm(depth, timestamp_us, data), .flac => |*f| self.playFlac(f, timestamp_us, data) catch |err| { // A damaged frame is a moment of silence, not the end of the // stream: the next one starts afresh. log.warn("could not decode a FLAC frame: {t}", .{err}); }, .opus => |*o| self.playOpus(o, timestamp_us, data), }}
fn playPcm(self: *Player, depth: u8, timestamp_us: i64, data: []const u8) void { const width = pcm.bytesPerSample(depth) catch unreachable; const out = self.room(data.len / width) orelse return; const got = pcm.decode(depth, data, out) catch unreachable; _ = self.scheduler.push(timestamp_us, out[0..got]);}
/// Every frame in the chunk -- one, as Music Assistant sends it, but nothing/// here depends on that -- each stamped from the chunk's time and the/// samples before it.fn playFlac(self: *Player, f: *Flac, timestamp_us: i64, data: []const u8) !void { var reader: std.Io.Reader = .fixed(data); var played: u64 = 0; while (try f.decoder.decodeFrame(&reader, 0)) |frame| { const channels = frame.channels; const n = frame.header.block_size; const out = self.room(@as(usize, n) * channels.len) orelse return; for (0..n) |i| for (channels, 0..) |plane, c| { out[i * channels.len + c] = @as(f32, @floatFromInt(plane[i])) * f.scale; }; const at = timestamp_us +| @as(i64, @intCast(played * std.time.us_per_s / f.rate)); _ = self.scheduler.push(at, out); played += n; }}
fn playOpus(self: *Player, o: *Opus, timestamp_us: i64, data: []const u8) void { const d = &o.decoder; const out = self.room(opus.Decoder.max_frame_samples * d.sample_rate / 48000 * d.channels) orelse return; const got = d.decode(data, out) catch |err| blk: { log.warn("could not decode an Opus packet: {t}", .{err}); // A packet that cannot be decoded is concealed, as a lost one would // be, for as long as its table of contents says, so that what // follows still lines up. const parsed = opus.packet.parse(data) catch return; const n = @as(usize, parsed.samples()) * d.sample_rate / 48000; if (n * d.channels > out.len) return; break :blk d.decode(null, out[0 .. n * d.channels]) catch return; }; _ = self.scheduler.push(timestamp_us, out[0 .. got * d.channels]);}
/// `n` samples of `decoded`, grown if need be; null if it cannot be.fn room(self: *Player, n: usize) ?[]f32 { if (self.decoded.len < n) { self.decoded = self.gpa.realloc(self.decoded, n) catch { log.warn("out of memory for a chunk of {d} samples", .{n}); return null; }; } return self.decoded[0..n];}
fn onStreamClear(context: *anyopaque) void { const self = from(context); self.scheduler.clear(); if (self.observer) |o| o.onStreamClear(o.context);}
fn onStreamEnd(context: *anyopaque) void { const self = from(context); self.dropCodec(); self.scheduler.stop(); if (self.observer) |o| o.onStreamEnd(o.context);}
fn onCommand(context: *anyopaque, command: message.Command) void { const self = from(context); switch (command) { .volume => |v| self.volume = v, .mute => |m| self.muted = m, } self.scheduler.setVolume(self.volume, self.muted); if (self.observer) |o| o.onCommand(o.context, command);}
fn onClock(context: *anyopaque, clock: TimeFilter) void { const self = from(context); self.scheduler.setClock(clock); if (self.observer) |o| o.onClock(o.context, clock);}
fn onPlayback(context: *anyopaque, state: ?message.PlaybackState) void { const self = from(context); if (self.observer) |o| o.onPlayback(o.context, state);}
fn onDisconnected(context: *anyopaque, reason: anyerror) void { const self = from(context); self.dropCodec(); self.scheduler.stop(); if (self.observer) |o| o.onDisconnected(o.context, reason);}
const testing = std.testing;
/// A FLAC stream as Music Assistant would send it: the header, base64, and/// the frames one by one.const Sent = struct { header: []u8, frames: [][]const u8, bytes: []u8,
fn deinit(s: Sent) void { testing.allocator.free(s.header); testing.allocator.free(s.frames); testing.allocator.free(s.bytes); }};
fn encodeFlac(samples: []const i32, rate: u32, bits: u8, block_size: u32) !Sent { var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var encoder = try flac.Encoder.init(testing.allocator, &out.writer, .{ .sample_rate = rate, .channels = 2, .bits_per_sample = bits, }, .{ .block_size = block_size }); defer encoder.deinit(); try encoder.writeInterleaved(samples); try encoder.finish(); const bytes = try out.toOwnedSlice(); errdefer testing.allocator.free(bytes);
// Where each frame starts, as a decoder finds them. var reader: std.Io.Reader = .fixed(bytes); var decoder = try flac.Decoder.init(testing.allocator, &reader, .{}); defer decoder.deinit(); const audio: usize = @intCast(decoder.audioOffset()); var starts: std.ArrayList(usize) = .empty; defer starts.deinit(testing.allocator); while (try decoder.next()) |frame| try starts.append(testing.allocator, audio + @as(usize, @intCast(frame.offset)));
const frames = try testing.allocator.alloc([]const u8, starts.items.len); errdefer testing.allocator.free(frames); for (frames, 0..) |*f, i| { const end = if (i + 1 < starts.items.len) starts.items[i + 1] else bytes.len; f.* = bytes[starts.items[i]..end]; }
// The signature and the streaminfo alone, marked as the last block, as // aiosendspin builds it from ffmpeg's. var head: [4 + 4 + 34]u8 = undefined; @memcpy(head[0..4], "fLaC"); head[4] = 0x80; std.mem.writeInt(u24, head[5..8], 34, .big); @memcpy(head[8..], bytes[8..][0..34]); const header = try testing.allocator.alloc(u8, std.base64.standard.Encoder.calcSize(head.len)); _ = std.base64.standard.Encoder.encode(header, &head); return .{ .header = header, .frames = frames, .bytes = bytes };}
test "FLAC frames are decoded into the scheduler, each at its moment" { // Two channels counting up and down in 16 bits, so that any sample out of // place or out of scale shows. const rate = 1000; var samples: [2 * 300]i32 = undefined; for (0..300) |i| { samples[2 * i] = @intCast(i * 100); samples[2 * i + 1] = -@as(i32, @intCast(i * 100)); } const sent = try encodeFlac(&samples, rate, 16, 100); defer sent.deinit(); try testing.expectEqual(@as(usize, 3), sent.frames.len);
var scheduler: Scheduler = .init(testing.allocator, .{ .capacity_us = 1_000_000 }); defer scheduler.deinit(); var player: Player = .init(testing.allocator, &scheduler); defer player.deinit(); const s = player.sink(); s.onStreamStart(s.context, .{ .codec = .flac, .sample_rate = rate, .channels = 2, .bit_depth = 16, .codec_header = sent.header }); try testing.expect(player.codec == .flac);
// A chunk a frame, stamped a tenth of a second apart; then all three in // one chunk after a gap, which the samples before each frame place. for (sent.frames, 0..) |frame, i| s.onAudio(s.context, @intCast(i * 100_000), frame); try testing.expectEqual(@as(i64, 300_000), scheduler.bufferedUs()); try testing.expectEqual(@as(usize, 1), scheduler.segment_count); const all = sent.frames[0].ptr[0 .. sent.frames[0].len + sent.frames[1].len + sent.frames[2].len]; s.onAudio(s.context, 1_000_000, all); // One new run, not three: had the later frames been stamped with the // chunk's time rather than their own, each would have started another. try testing.expectEqual(@as(usize, 2), scheduler.segment_count); const second = scheduler.segments[(scheduler.segment_head + 1) % scheduler.segments.len]; try testing.expectEqual(@as(u64, 300), second.frame); try testing.expectEqual(@as(i64, 1_000_000), second.timestamp_us);
var clock: TimeFilter = .init(); clock.update(0, 100, 1_000_000); clock.update(0, 100, 2_000_000); scheduler.setClock(clock); var left: [300]f32 = undefined; var right: [300]f32 = undefined; _ = scheduler.fill(&.{ &left, &right }, 300, 0); for (0..300) |i| { const want: f32 = @as(f32, @floatFromInt(i * 100)) / 32768; try testing.expectEqual(want, left[i]); try testing.expectEqual(-want, right[i]); }}
test "a FLAC stream with no header is refused, and plays nothing" { var scheduler: Scheduler = .init(testing.allocator, .{ .capacity_us = 100_000 }); defer scheduler.deinit(); var player: Player = .init(testing.allocator, &scheduler); defer player.deinit(); const s = player.sink(); s.onStreamStart(s.context, .{ .codec = .flac, .sample_rate = 48000, .channels = 2, .bit_depth = 16 }); try testing.expect(player.codec == .none); s.onAudio(s.context, 0, "not a frame"); try testing.expectEqual(@as(i64, 0), scheduler.bufferedUs());}
test "FLAC is offered first, and Opus last" { const f = formats(48000, .lossless).slice(); try testing.expectEqual(message.Codec.flac, f[0].codec); try testing.expectEqual(@as(u8, 24), f[0].bit_depth); try testing.expectEqual(message.Codec.opus, f[f.len - 1].codec); try testing.expectEqual(@as(u8, 16), f[f.len - 1].bit_depth);}
test "Opus first when preferred, and never at a rate it cannot code" { const f = formats(48000, .opus).slice(); try testing.expectEqual(message.Codec.opus, f[0].codec); try testing.expectEqual(@as(usize, 6), f.len); for (formats(44100, .opus).slice()) |g| try testing.expect(g.codec != .opus); try testing.expectEqual(@as(usize, 5), formats(44100, .lossless).len);}
/// A CELT-only Opus packet of 20 ms, stereo, fullband, as libopus's encoder/// made it from a sine. Its first byte is the table of contents: config 31/// (CELT, fullband, 20 ms), stereo, one frame.fn celtPacket(buf: []u8) []const u8 { // Any bytes after a valid table of contents decode, since the range // decoder reads anything as some symbol; a fixed pattern keeps it // repeatable. buf[0] = (31 << 3) | 0x4; for (buf[1..], 1..) |*b, i| b.* = @truncate(i *% 97 +% 13); return buf;}
test "Opus packets are decoded into the scheduler, each at its moment" { var scheduler: Scheduler = .init(testing.allocator, .{ .capacity_us = 1_000_000 }); defer scheduler.deinit(); var player: Player = .init(testing.allocator, &scheduler); defer player.deinit(); const s = player.sink(); s.onStreamStart(s.context, .{ .codec = .opus, .sample_rate = 48000, .channels = 2, .bit_depth = 16 }); try testing.expect(player.codec == .opus);
var buf: [120]u8 = undefined; const p = celtPacket(&buf); for (0..5) |i| s.onAudio(s.context, @intCast(i * 20_000), p); try testing.expectEqual(@as(i64, 100_000), scheduler.bufferedUs()); try testing.expectEqual(@as(usize, 1), scheduler.segment_count);}
test "Opus packets in SILK mode are decoded too" { var scheduler: Scheduler = .init(testing.allocator, .{ .capacity_us = 1_000_000 }); defer scheduler.deinit(); var player: Player = .init(testing.allocator, &scheduler); defer player.deinit(); const s = player.sink(); s.onStreamStart(s.context, .{ .codec = .opus, .sample_rate = 48000, .channels = 2, .bit_depth = 16 });
// Config 1: SILK, narrowband, 20 ms. const silk = [_]u8{ (1 << 3) | 0x4, 0x55, 0xaa, 0x55 }; s.onAudio(s.context, 0, &silk); s.onAudio(s.context, 20_000, &silk); try testing.expectEqual(@as(i64, 40_000), scheduler.bufferedUs()); try testing.expectEqual(@as(usize, 1), scheduler.segment_count);}
test "Opus at a rate it cannot code is refused" { var scheduler: Scheduler = .init(testing.allocator, .{ .capacity_us = 100_000 }); defer scheduler.deinit(); var player: Player = .init(testing.allocator, &scheduler); defer player.deinit(); const s = player.sink(); s.onStreamStart(s.context, .{ .codec = .opus, .sample_rate = 44100, .channels = 2, .bit_depth = 16 }); try testing.expect(player.codec == .none);}