// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Raw PCM as Sendspin sends it, to 32-bit float. //! //! Samples are little-endian, signed and interleaved. 24-bit samples are //! packed into three bytes each rather than padded out to four -- which is //! what aiosendspin writes, and what a 24-bit format means on this wire. const std = @import("std"); pub const Error = error{ /// A bit depth this does not decode: only 16, 24 and 32 are sent. UnsupportedBitDepth, }; pub fn bytesPerSample(bit_depth: u8) Error!u8 { return switch (bit_depth) { 16 => 2, 24 => 3, 32 => 4, else => error.UnsupportedBitDepth, }; } /// Decode as many whole samples of `in` as fit in `out`, and return how many /// that was. A trailing partial sample is ignored. pub fn decode(bit_depth: u8, in: []const u8, out: []f32) Error!usize { const width = try bytesPerSample(bit_depth); const n = @min(in.len / width, out.len); switch (bit_depth) { 16 => for (out[0..n], 0..) |*o, i| { const s = std.mem.readInt(i16, in[i * 2 ..][0..2], .little); o.* = @as(f32, @floatFromInt(s)) / 32768.0; }, 24 => for (out[0..n], 0..) |*o, i| { const s = std.mem.readInt(i24, in[i * 3 ..][0..3], .little); o.* = @as(f32, @floatFromInt(s)) / 8388608.0; }, 32 => for (out[0..n], 0..) |*o, i| { const s = std.mem.readInt(i32, in[i * 4 ..][0..4], .little); o.* = @floatCast(@as(f64, @floatFromInt(s)) / 2147483648.0); }, else => unreachable, } return n; } const testing = std.testing; test "the three widths, at their extremes" { var out: [2]f32 = undefined; try testing.expectEqual(@as(usize, 2), try decode(16, &.{ 0x00, 0x80, 0xff, 0x7f }, &out)); try testing.expectEqual(@as(f32, -1.0), out[0]); try testing.expectApproxEqAbs(@as(f32, 1.0), out[1], 1e-4); try testing.expectEqual(@as(usize, 2), try decode(24, &.{ 0x00, 0x00, 0x80, 0x00, 0x00, 0x40 }, &out)); try testing.expectEqual(@as(f32, -1.0), out[0]); try testing.expectEqual(@as(f32, 0.5), out[1]); try testing.expectEqual(@as(usize, 1), try decode(32, &.{ 0x00, 0x00, 0x00, 0xc0, 0x01 }, &out)); try testing.expectEqual(@as(f32, -0.5), out[0]); try testing.expectError(error.UnsupportedBitDepth, decode(8, &.{0}, &out)); }