// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Live audio: the samples the library renders sent to a real speaker rather //! than only to a `.wav`. //! //! The library turns what a machine's speaker, Mockingboard or Ensoniq did into //! a stream of `f32` samples (see `speaker.Renderer` and the rest); this hands //! that stream to the host's audio. It is kept out of the library proper, which //! is about machines and not about this host, and lives beside `terminal.zig` //! and `config.zig`, which the two front ends share for the same reason. //! //! **Which host is a compile-time choice, so another one is a second backend //! beside this one.** `Backend` is selected for the target: Linux plays through //! PipeWire — the user's own pure-Zig client, which talks to the daemon's //! socket and wants no library linked — and everywhere else is silent until //! somebody writes a backend for it. `Output` is the same either way: it opens //! the backend, and if that does not come up (no daemon, or no backend for the //! platform) it stays quiet rather than failing, since sound is not the reason //! the machine is running. //! //! A stream plays at the graph's own rate, not necessarily the one asked for, //! so `Output.rate` is read back after opening and the renderers are built to //! match it. Writes are non-blocking: a machine that has run ahead of real time //! hands over more than the ring will take, and the excess is dropped rather //! than stalling the machine to the speed of the sound. const std = @import("std"); const builtin = @import("builtin"); /// A volume control over the samples on their way out: a gain and a mute, /// stepped so that a keystroke can nudge it and a number in a config file can /// set it. pub const Volume = struct { /// Nought (silent) to `steps` (unity), in even steps of loudness. step: u8 = default_step, muted: bool = false, /// Ten steps, so each is ten per cent and the numbers a person says — /// "half", "eighty per cent" — land on one. pub const steps: u8 = 10; pub const default_step: u8 = 8; /// A volume from a percentage nought to a hundred, rounded to the nearest /// step, which is what a config file gives. pub fn fromPercent(percent: u8) Volume { const p = @min(percent, 100); return .{ .step = @intCast((@as(u16, p) * steps + 50) / 100) }; } /// The multiplier to apply, which is nothing at all when muted. pub fn gain(self: Volume) f32 { if (self.muted) return 0; return @as(f32, @floatFromInt(self.step)) / @as(f32, @floatFromInt(steps)); } /// What to show a person: "70%", or "muted" whatever the step. pub fn describe(self: Volume, buffer: []u8) []const u8 { if (self.muted) return "muted"; return std.fmt.bufPrint(buffer, "{d}%", .{@as(u16, self.step) * 100 / steps}) catch "?"; } pub fn louder(self: *Volume) void { if (self.step < steps) self.step += 1; self.muted = false; } pub fn quieter(self: *Volume) void { if (self.step > 0) self.step -= 1; } pub fn toggleMute(self: *Volume) void { self.muted = !self.muted; } }; /// Where the samples go once the library has made them: the platform's live /// audio, if it opened, with the volume over the top. /// /// The renderers must run at `rate`, which is the rate the backend settled on /// rather than the one asked for — zero when nothing opened, in which case the /// caller uses its own default and nothing is played. `open` never fails: a /// backend that does not come up leaves a silent `Output` that still carries a /// volume, so the keystrokes that work it are there whether or not there is a /// daemon listening. pub const Output = struct { backend: Backend = .{}, volume: Volume = .{}, rate: u32 = 0, /// Gain is applied into this on the way out, a chunk at a time, so the /// caller's samples — which also go to a `.wav` unscaled — are left alone. scratch: [2 * chunk_frames]f32 = undefined, /// Two channels always, so the one speaker plays through both and a card's /// pair keeps its sides. The graph folds it down to a mono sink itself. pub const channels = 2; /// The rate asked for when nothing better is known: compact disc, which is /// what the `.wav` used and more than a one-bit speaker needs. pub const default_rate = 44_100; const chunk_frames = 2048; /// Brings the platform's audio up, or leaves it silent. `name` is what the /// stream is called in the host's mixer. pub fn open(gpa: std.mem.Allocator, name: []const u8, volume: Volume) Output { var self: Output = .{ .volume = volume }; self.backend.start(gpa, name) catch return self; self.rate = self.backend.rate(); return self; } pub fn close(self: *Output) void { self.backend.close(); } /// Whether anything is actually playing, as against a silent fallback. pub fn live(self: *const Output) bool { return self.rate != 0; } /// One channel played through both, the speaker's own case. pub fn playMono(self: *Output, mono: []const f32) void { if (self.rate == 0) return; const g = self.volume.gain(); var at: usize = 0; while (at < mono.len) { const take = @min(chunk_frames, mono.len - at); for (0..take) |i| { const s = mono[at + i] * g; self.scratch[i * 2] = s; self.scratch[i * 2 + 1] = s; } self.backend.write(self.scratch[0 .. take * 2]); at += take; } } /// Interleaved stereo played as it stands, a card's two channels. pub fn playStereo(self: *Output, interleaved: []const f32) void { if (self.rate == 0) return; const g = self.volume.gain(); const frames = interleaved.len / 2; var at: usize = 0; while (at < frames) { const take = @min(chunk_frames, frames - at); for (0..take * 2) |i| self.scratch[i] = interleaved[at * 2 + i] * g; self.backend.write(self.scratch[0 .. take * 2]); at += take; } } }; /// The backend for the target platform. Adding another platform is adding a /// struct with these five methods and a case here; nothing above this line /// knows which one it got. const Backend = switch (builtin.os.tag) { .linux => PipeWire, else => Silent, }; /// Linux, through the PipeWire daemon. The client is `zig-pipewire`, pure Zig /// over the daemon's socket, so this links no library and needs only a daemon /// running to make a sound. const PipeWire = struct { stream: ?*pw.Stream = null, negotiated: u32 = 0, const pw = @import("pipewire"); /// Long enough for the session manager to link the stream and the graph to /// turn over once, so that `rate` has the graph's rate to report; short /// enough that a machine with no daemon is not held up at startup. const wait_ms = 1500; fn start(self: *PipeWire, gpa: std.mem.Allocator, name: []const u8) !void { const stream = try pw.Stream.open(gpa, .{ .name = name, .channels = Output.channels, .rate = Output.default_rate, .role = .game, }); errdefer stream.close(); if (!stream.waitStreaming(wait_ms)) return error.NotConnected; self.stream = stream; // Zero before the first cycle; the rate asked for is the honest guess // until the graph says otherwise. self.negotiated = if (stream.rate() != 0) stream.rate() else Output.default_rate; } fn rate(self: *const PipeWire) u32 { return self.negotiated; } fn write(self: *PipeWire, interleaved: []const f32) void { // Non-blocking: what the ring will not take is dropped rather than // holding the machine back. A short write is the ring full, which is a // machine running ahead of the sound, not an error. if (self.stream) |stream| _ = stream.write(interleaved); } fn close(self: *PipeWire) void { if (self.stream) |stream| stream.close(); self.stream = null; } }; /// Every other platform, until one has a backend of its own: opening it does /// nothing and it plays nothing, so `Output` falls back to silence. const Silent = struct { fn start(_: *Silent, _: std.mem.Allocator, _: []const u8) !void { return error.NoBackend; } fn rate(_: *const Silent) u32 { return 0; } fn write(_: *Silent, _: []const f32) void {} fn close(_: *Silent) void {} }; const testing = std.testing; test "a volume steps between silence and unity, and mute overrides it" { var v: Volume = .{ .step = Volume.steps }; try testing.expectEqual(@as(f32, 1.0), v.gain()); v.quieter(); try testing.expectApproxEqAbs(@as(f32, 0.9), v.gain(), 0.001); v.toggleMute(); try testing.expectEqual(@as(f32, 0.0), v.gain()); // Turning it up unmutes, the way a person reaching for the volume expects. v.louder(); try testing.expect(!v.muted); // It stops at the ends rather than wrapping. v.step = 0; v.quieter(); try testing.expectEqual(@as(u8, 0), v.step); v.step = Volume.steps; v.louder(); try testing.expectEqual(Volume.steps, v.step); } test "a percentage becomes the nearest step" { try testing.expectEqual(@as(u8, 0), Volume.fromPercent(0).step); try testing.expectEqual(@as(u8, 5), Volume.fromPercent(50).step); try testing.expectEqual(@as(u8, 10), Volume.fromPercent(100).step); try testing.expectEqual(@as(u8, 7), Volume.fromPercent(66).step); // Over a hundred is held at full rather than overflowing the step. try testing.expectEqual(@as(u8, 10), Volume.fromPercent(200).step); } test "a describe says the percentage, or that it is muted" { var buffer: [8]u8 = undefined; try testing.expectEqualStrings("80%", (Volume{ .step = 8 }).describe(&buffer)); try testing.expectEqualStrings("muted", (Volume{ .step = 8, .muted = true }).describe(&buffer)); } test "a silent output plays nothing and never claims to be live" { // Whatever the platform, an output nobody opened is silent and safe to // push samples at. var out: Output = .{}; try testing.expect(!out.live()); out.playMono(&[_]f32{ 0.1, -0.1, 0.2 }); out.playStereo(&[_]f32{ 0.1, 0.1, -0.2, -0.2 }); out.close(); }