From ceef331eb5305b24a5297a63f10d40dc4ce4e5d5 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Wed, 9 Sep 2026 16:31:42 -0500 Subject: [PATCH] live audio: the machine's sound out of a real speaker Until now the speaker and the Ensoniq only ever went into a .wav. They play live now, on by default, out of the host's own audio: on Linux through PipeWire, the user's zig-pipewire client, which is pure Zig over the daemon's socket and so links no library and wants only a daemon running to make a sound. A machine with no daemon to talk to falls back to silence rather than failing. The seam is `tools/audio.zig`, a shared front-end module beside terminal.zig and config.zig: an `Output` with a volume over it, and a `Backend` chosen for the target at compile time -- Linux is PipeWire, everywhere else is silent until somebody writes one, which is where another platform's audio goes. The front ends own the Output so it survives a machine reset; the library stays about machines and knows nothing of the host's audio. The two rendering paths feed it without being read twice. The eight-bit `Recording` renders the speaker and Mockingboard once and fans the samples out to the file, the live speaker, or both. The IIgs Ensoniq recorder, which lives in the library and must not import the front end, keeps its samples in a plain f32 buffer that gs.zig drains between machine steps. Both take the live graph's rate so the renderers and the file agree with it. .wav in and out is untouched: --audio still records, --cassette-in still reads a tape, --cassette-out still writes one. A file holds the machine to real time as before; live audio does not, dropping what it cannot keep up with, so the speed keys still work when only the speaker is playing. Configurable from the config file (`sound`, `volume`, `mute`) and the command line (--no-audio, --volume N, --mute), and worked from the keyboard behind the alt modifier like every other front-end command: alt+, quieter, alt+. louder, alt+/ mute. The stream shows up in the host's mixer as `zig65`, to be moved or levelled from the usual tools. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01969H4dxMhArn3Co6Dr6k6w --- .ziggy-schema | 6 + README.md | 60 ++++++++-- build.zig | 55 ++++++++- build.zig.zon | 4 + build.zig.zon.nix | 9 ++ completions/zig65.bash | 2 +- completions/zig65.fish | 9 ++ src/ensoniq.zig | 56 +++++++-- src/gs.zig | 88 +++++++++++--- src/main.zig | 124 +++++++++++++++---- src/session16.zig | 2 +- src/session8.zig | 96 +++++++++------ tools/audio.zig | 264 +++++++++++++++++++++++++++++++++++++++++ tools/bootgs.zig | 2 +- tools/config.zig | 15 ++- 15 files changed, 703 insertions(+), 89 deletions(-) create mode 100644 tools/audio.zig diff --git a/.ziggy-schema b/.ziggy-schema index 88dc99b..d0e77fb 100644 --- a/.ziggy-schema +++ b/.ziggy-schema @@ -61,6 +61,12 @@ struct Config { cassette_in: ?bytes, cassette_out: ?bytes, + ///Live audio: whether to play the machine's sound out of a real speaker, + ///how loud it starts (0 to 100), and whether it starts muted. + sound: ?bool, + volume: ?int, + mute: ?bool, + ///How much RAM the machine has, as a size like "1M", "512K" or "48K". memory: ?bytes, ///A IIc's memory expansion, which is a connector inside the case rather diff --git a/README.md b/README.md index 156d8b3..50f2e60 100644 --- a/README.md +++ b/README.md @@ -2522,14 +2522,51 @@ itself out and drifts back. zig build run -- --rom apple2e.rom --audio session.wav ``` -The machine is held at its own 1.0205MHz for as long as it is recording, and -the speed keys are refused: sound played faster or slower is not the sound the -machine made. Nothing stops the file growing — about five megabytes a minute, -until the emulator is closed, which is when the sizes in the header are put -right. - -There is no playback yet. The debugger still rings the terminal bell when the -speaker moves, which is all a terminal can do with it. +The machine is held at its own 1.0205MHz for as long as it is recording to a +file, and the speed keys are refused: sound written faster or slower is not the +sound the machine made. Nothing stops the file growing — about five megabytes a +minute, until the emulator is closed, which is when the sizes in the header are +put right. + +##### Live audio + +The speaker also plays live, out of a real speaker, and this is on by default. +On Linux it goes through PipeWire — [`zig-pipewire`][zig-pipewire], the user's +own client, which is pure Zig talking to the daemon's socket, so it links no +library and wants only a daemon running to make a sound. A machine with no +daemon to talk to falls back to silence rather than failing; sound is not the +reason the machine is running. + +``` +zig build run -- --rom apple2e.rom # plays out loud, on by default +zig build run -- --rom apple2e.rom --no-audio # or keep it quiet +``` + +A file and the speaker are the same samples twice: `--audio PATH` still writes +the WAV whether or not anything is playing, and both are fed from one rendering +of the log, since reading the log consumes it. Live audio does *not* hold the +machine to real time the way a file does — a machine run faster than life plays +choppily rather than at the wrong pitch, the samples it cannot keep up with +dropped rather than the machine held back — so the speed keys still work when +only the speaker is playing, and are refused only while a file is being +written. + +The volume is worked from the keyboard, behind the alt modifier like every +other front-end command: **alt+,** quieter, **alt+.** louder, **alt+/** mute +and unmute. It starts where the config file says — `sound` to turn live audio +off, `volume` a percentage nought to a hundred, `mute` to start silent, or +`--volume N` and `--mute` on the command line — and the platform folds it into +the host's own mixer, where the stream shows up under `zig65` to be moved to +another output or have its level changed from the usual tools. + +**Where a platform is added, its audio is a second backend beside this one.** +`tools/audio.zig` chooses the backend for the target at compile time — Linux is +PipeWire, everything else is silent until somebody writes one — and the rest of +the front end knows only the `Output` it got, not which platform gave it. + +The debugger also rings the terminal bell when the speaker moves, which is all +a terminal itself can do with it whether or not there is a speaker to play +through. #### An Apple IIgs's sound @@ -2567,6 +2604,12 @@ Because a sample's moment is worked out from the machine's own clock, a machine running slower than life still writes a file that plays at the right pitch and the right speed. It only takes longer to write it. +The IIgs plays live as well, on by default and through the same host audio as +the eight-bit speaker: the recorder keeps the samples it makes in a buffer of +its own, and the front end takes them out between machine steps and hands them +to the speaker. The volume keys, the config settings and `--no-audio` are all +the same as above. + ### Printing The parallel printer card is the simplest card the Apple II had, and slot 1 is @@ -7414,6 +7457,7 @@ this does not model. [sst]: https://github.com/SingleStepTests/65x02 [klaus]: https://github.com/Klaus2m5/6502_65C02_functional_tests [aigrette65]: https://git.jcollie.dev/jeff/aigrette65 +[zig-pipewire]: https://git.jcollie.dev/jeff/zig-pipewire [a2audit]: https://github.com/zellyn/a2audit [mb-audit]: https://github.com/tomcw/mb-audit [deadtest]: https://github.com/misterblack1/appleII_deadtest diff --git a/build.zig b/build.zig index 37a06d1..3fe4bb4 100644 --- a/build.zig +++ b/build.zig @@ -75,6 +75,29 @@ pub fn build(b: *std.Build) void { // bag of strings. const ziggy = b.dependency("ziggy", .{}).module("ziggy"); + // Live audio: the machine's sound out of a real speaker rather than only + // into a `.wav`. This is the user's own PipeWire client, pure Zig talking + // to the daemon's socket -- no libpipewire, no C -- so it adds no system + // dependency and only wants a daemon running to make a sound. It is Linux's + // way of doing it; `tools/audio.zig` is shaped so another platform's is a + // second backend beside it. + const pipewire = b.dependency("pipewire", .{ + .target = target, + .optimize = app_optimize, + }); + + // The audio sink both front ends share: turning the samples the library + // renders into live sound, with a volume and mute over the top. Kept out + // of the library proper -- which stays about machines, not about this + // host's audio -- and beside terminal.zig and config.zig, which the front + // ends share for the same reason. + const audio = b.createModule(.{ + .root_source_file = b.path("tools/audio.zig"), + .target = target, + .optimize = app_optimize, + .imports = &.{.{ .name = "pipewire", .module = pipewire.module("pipewire") }}, + }); + // The configuration file, shared by both front ends the way terminal.zig // is: neither the debugger nor gs should have its own idea of what a // machine written down looks like. @@ -129,6 +152,7 @@ pub fn build(b: *std.Build) void { .optimize = app_optimize, .imports = &.{ .{ .name = "zig65", .module = if (mode_was_asked_for) zig65 else zig65_shipped }, + .{ .name = "audio", .module = audio }, }, }); @@ -146,6 +170,7 @@ pub fn build(b: *std.Build) void { .{ .name = "vaxis", .module = vaxis.module("vaxis") }, .{ .name = "terminal", .module = terminal }, .{ .name = "config", .module = config }, + .{ .name = "audio", .module = audio }, }, }); @@ -265,12 +290,21 @@ pub fn build(b: *std.Build) void { .optimize = optimize, .imports = &.{.{ .name = "ziggy", .module = ziggy }}, }); + // The audio sink built the same way, since a module can only be in + // one build at a time and this test build is at `optimize`. + const slow_audio = b.createModule(.{ + .root_source_file = b.path("tools/audio.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "pipewire", .module = pipewire.module("pipewire") }}, + }); const slow_session = b.createModule(.{ .root_source_file = b.path("src/session8.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "zig65", .module = zig65 }, + .{ .name = "audio", .module = slow_audio }, }, }); const slow_terminal = b.addModule("terminal_tests", .{ @@ -304,6 +338,7 @@ pub fn build(b: *std.Build) void { .{ .name = "vaxis", .module = slow_vaxis.module("vaxis") }, .{ .name = "terminal", .module = slow_terminal }, .{ .name = "config", .module = slow_config }, + .{ .name = "audio", .module = slow_audio }, }, }) }, }, @@ -374,7 +409,10 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/session8.zig"), .target = target, .optimize = optimize, - .imports = &.{.{ .name = "zig65", .module = zig65 }}, + .imports = &.{ + .{ .name = "zig65", .module = zig65 }, + .{ .name = "audio", .module = audio }, + }, }), }); const run_session_tests = b.addRunArtifact(session_tests); @@ -411,11 +449,25 @@ pub fn build(b: *std.Build) void { .{ .name = "vaxis", .module = vaxis.module("vaxis") }, .{ .name = "terminal", .module = terminal }, .{ .name = "config", .module = config }, + .{ .name = "audio", .module = audio }, }, }), }); const run_gs_tests = b.addRunArtifact(gs_tests); + // The audio sink's own tests -- the volume steps and the silent fallback. + // Like the others it is compiled when it is a test's root; the pipewire + // dependency is pure Zig and needs no daemon to compile or to test. + const audio_tests = b.addTest(.{ + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/audio.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "pipewire", .module = pipewire.module("pipewire") }}, + }), + }); + const run_audio_tests = b.addRunArtifact(audio_tests); + const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_module_unit_tests.step); test_step.dependOn(&run_exe_unit_tests.step); @@ -424,6 +476,7 @@ pub fn build(b: *std.Build) void { test_step.dependOn(&run_session_tests.step); test_step.dependOn(&run_session16_tests.step); test_step.dependOn(&run_gs_tests.step); + test_step.dependOn(&run_audio_tests.step); const coverage_step = b.step("coverage", "Generate a coverage report with kcov"); const run_kcov = b.addSystemCommand(&.{ diff --git a/build.zig.zon b/build.zig.zon index 10194c7..fb2cf96 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -46,6 +46,10 @@ .url = "git+https://github.com/kristoff-it/ziggy#0b61581980d6905dd4108a618d602f5778593122", .hash = "ziggy-0.1.0-kTg8v0NWBgAyFtS5awtOlKnC7ddvefR_I0Xh3XQyi7p1", }, + .pipewire = .{ + .url = "git+https://git.jcollie.dev/jeff/zig-pipewire.git?ref=main#1af83e5134fb72aeb1e3f583a3bc2f87d587ec22", + .hash = "pipewire-0.1.0-lH35HusiBACjmg25_hcNJOTjMGFfSKyczRK3_6wSG95i", + }, }, .paths = .{ diff --git a/build.zig.zon.nix b/build.zig.zon.nix index b35dee3..7ce04e1 100644 --- a/build.zig.zon.nix +++ b/build.zig.zon.nix @@ -142,6 +142,15 @@ copyFarm name [ unpack = true; }; } + { + name = "pipewire-0.1.0-lH35HusiBACjmg25_hcNJOTjMGFfSKyczRK3_6wSG95i"; + path = fetchZigArtifact { + name = "pipewire"; + url = "git+https://git.jcollie.dev/jeff/zig-pipewire.git?ref=main#1af83e5134fb72aeb1e3f583a3bc2f87d587ec22"; + hash = "sha256-AH6FszefoUscEvO9wmPK1tHVT/9YYc98QkUOy08vBqo="; + unpack = true; + }; + } { name = "uucode-0.2.0-ZZjBPlK5VADj7fdoq7G8LIHzD5o6FSkcBXXrRWr4jnrA"; path = fetchZigArtifact { diff --git a/completions/zig65.bash b/completions/zig65.bash index 1c6e045..176438f 100644 --- a/completions/zig65.bash +++ b/completions/zig65.bash @@ -101,7 +101,7 @@ _zig65() { # line is not offered again. The word under the cursor does not count as # already given: finishing off a flag that is spelled out in full would # otherwise offer nothing at all. - local flags='id --config --machine --processor --memory --revision --rom --video-rom --disk-rom --aci-rom --slot --drives --disk1 --disk2 --unidisk --unidisk2 --hard-disk --scsi-rom --scsi --screenshot --monitor --text --halted --audio --cassette-in --cassette-out --parallel-out --serial-rom --serial-in --serial-out --printer-out --localtalk --localtalk-log --localtalk-interface --appletalk --battery-ram --videx-rom --videx-charset --videx-alternate --ultraterm-rom --ultraterm-charset --mouse --mockingboard --clock --clock-offset --ramfactor-rom --ramfactor --ramcharger --memory-expansion --writable --help' + local flags='id --config --machine --processor --memory --revision --rom --video-rom --disk-rom --aci-rom --slot --drives --disk1 --disk2 --unidisk --unidisk2 --hard-disk --scsi-rom --scsi --screenshot --monitor --text --halted --audio --no-audio --volume --mute --cassette-in --cassette-out --parallel-out --serial-rom --serial-in --serial-out --printer-out --localtalk --localtalk-log --localtalk-interface --appletalk --battery-ram --videx-rom --videx-charset --videx-alternate --ultraterm-rom --ultraterm-charset --mouse --mockingboard --clock --clock-offset --ramfactor-rom --ramfactor --ramcharger --memory-expansion --writable --help' local offered=() flag index seen for flag in $flags; do seen= diff --git a/completions/zig65.fish b/completions/zig65.fish index a773ad5..50968d6 100644 --- a/completions/zig65.fish +++ b/completions/zig65.fish @@ -97,6 +97,15 @@ complete -c zig65 -l halted \ complete -c zig65 -l audio -r \ -n 'not __fish_seen_argument -l audio' \ -d 'Record what the speaker plays to a WAV, holding the machine at 1.0205MHz' +complete -c zig65 -l no-audio \ + -n 'not __fish_seen_argument -l no-audio' \ + -d 'Do not play the machine sound live; it plays out loud by default' +complete -c zig65 -l volume -x \ + -n 'not __fish_seen_argument -l volume' \ + -d 'How loud live audio starts, 0 to 100' +complete -c zig65 -l mute \ + -n 'not __fish_seen_argument -l mute' \ + -d 'Start with live audio muted' complete -c zig65 -l cassette-in -r \ -n 'not __fish_seen_argument -l cassette-in' \ -d 'Play a WAV into the cassette input, as a tape' diff --git a/src/ensoniq.zig b/src/ensoniq.zig index 29a275c..cdf015d 100644 --- a/src/ensoniq.zig +++ b/src/ensoniq.zig @@ -648,16 +648,18 @@ pub const Doc = struct { /// machine running slower than life still writes a file that plays at the /// right pitch and the right speed. It only takes longer to write it. pub const Recorder = struct { - file: *wav.Writer, + /// The file the samples are written to, if one was asked for. Null when the + /// only reason to sample is to play live. + file: ?*wav.Writer = null, /// How many of the machine's cycles make a second, and how many samples a - /// second the file holds. + /// second the recording holds. cycles_per_second: u64, rate: u64, - /// The cycle the recording began at, so that a sample's place in the file - /// is a place in the machine's own time. + /// The cycle the recording began at, so that a sample's place in the + /// recording is a place in the machine's own time. started: u64, /// How many samples have been written. The next one's moment is worked out - /// from this rather than by adding up an interval, so that the file's + /// from this rather than by adding up an interval, so that the recording's /// clock and the machine's cannot drift apart over a long recording. taken: u64 = 0, /// The first thing that went wrong writing the file, if anything did. @@ -668,6 +670,25 @@ pub const Recorder = struct { /// when the machine stops. trouble: ?anyerror = null, + /// Whether to keep the samples for live playback as well, and where. + /// + /// The library does not know what the host's audio is -- that is the front + /// end's business -- so a sample kept for playing is put here as an `f32` + /// and the front end takes it out through `captured` and pushes it to the + /// speaker between machine steps. It is a plain buffer, filled inside the + /// machine and drained outside it, both on the one thread, so it needs no + /// lock. What overruns it when the machine runs ahead of the draining is + /// dropped, which is the right thing for live sound: better a gap than a + /// lag. + capture: bool = false, + live_samples: [live_capacity]f32 = undefined, + live_count: usize = 0, + + /// About a tenth of a second at forty-eight kilohertz, which is more than a + /// frame's worth, so the front end draining once a frame never loses a + /// sample it could have played. + const live_capacity = 4800; + /// When the nth sample of the recording happens. pub fn cycleOf(self: *const Recorder, n: u64) u64 { return self.started + n * self.cycles_per_second / self.rate; @@ -679,18 +700,35 @@ pub const Recorder = struct { /// This is how the chip is brought up to date when anything is being /// recorded, rather than as well as: winding it forward in one go and then /// asking for the samples afterwards would put every pass of a whole step - /// into whichever sample happened to be asked for next, and the file would - /// really be at the rate the machine chose to look rather than the rate it - /// says. Stepping to each sample's own moment is what makes the two agree. + /// into whichever sample happened to be asked for next, and the recording + /// would really be at the rate the machine chose to look rather than the + /// rate it says. Stepping to each sample's own moment is what makes the two + /// agree. pub fn pump(self: *Recorder, doc: *Doc, now: u64) void { while (self.cycleOf(self.taken + 1) <= now) { self.taken += 1; doc.advance(self.cycleOf(self.taken), self.cycles_per_second); - self.file.put(doc.take()) catch |err| { + const sample = doc.take(); + if (self.file) |file| file.put(sample) catch |err| { if (self.trouble == null) self.trouble = err; }; + if (self.capture and self.live_count < live_capacity) { + self.live_samples[self.live_count] = @as(f32, @floatFromInt(sample)) / 32768.0; + self.live_count += 1; + } } } + + /// The samples kept for live playback since the last drain, as `f32` in the + /// range a speaker wants. The front end plays these and then calls + /// `clearCaptured`. + pub fn captured(self: *const Recorder) []const f32 { + return self.live_samples[0..self.live_count]; + } + + pub fn clearCaptured(self: *Recorder) void { + self.live_count = 0; + } }; const testing = std.testing; diff --git a/src/gs.zig b/src/gs.zig index 56159b7..ff154fc 100644 --- a/src/gs.zig +++ b/src/gs.zig @@ -40,6 +40,7 @@ const terminal = @import("terminal"); const config = @import("config"); const vaxis = @import("vaxis"); const zig65 = @import("zig65"); +const audio = @import("audio"); const disk2 = zig65.disk2; const disk35 = zig65.disk35; @@ -130,6 +131,11 @@ const App = struct { /// rest through here; see `session16.zig`. session: session16.Session, + /// The host's live audio: the Ensoniq out of a real speaker. Opened once + /// at startup and kept for the life of the program; the recording captures + /// samples for it and the run loop drains them here. Silent until opened. + audio: audio.Output = .{}, + tty_buffer: [128]u8 = undefined, tty: vaxis.Tty = undefined, writer: *std.Io.Writer = undefined, @@ -360,9 +366,32 @@ const App = struct { self.session.target_hz = session16.cycles_per_second; return true; } + + // The live volume: quieter, louder, or muted. + if (key.matches(',', .{ .alt = true })) { + self.audio.volume.quieter(); + self.announceVolume(); + return true; + } + if (key.matches('.', .{ .alt = true })) { + self.audio.volume.louder(); + self.announceVolume(); + return true; + } + if (key.matches('/', .{ .alt = true })) { + self.audio.volume.toggleMute(); + self.announceVolume(); + return true; + } return false; } + /// Says how loud the live audio is now, after a volume key. + fn announceVolume(self: *App) void { + var buffer: [8]u8 = undefined; + self.session.say("volume {s}", .{self.audio.volume.describe(&buffer)}); + } + fn surface(self: *const App) terminal.Surface { const super = self.session.cpu.memory.superHiRes(); const wide = self.vx.screen.width_pix; @@ -1148,6 +1177,13 @@ const App = struct { while (!self.quit) { self.session.stepDue(); + // Play whatever the Ensoniq made since the last look. The chip is + // sampled inside the machine, into the recording's own buffer; + // here, outside it, is where those samples reach the speaker. + if (self.audio.live()) if (self.session.recording) |*rec| { + self.audio.playMono(rec.captured()); + rec.clearCaptured(); + }; self.session.measureSpeed(); if (self.session.frameDue()) { var arena: std.heap.ArenaAllocator = .init(self.session.gpa); @@ -1190,8 +1226,14 @@ pub const Params = struct { /// Which monitor it is being looked at on, and who draws the text. monitor: terminal.Monitor = .monochrome, text: terminal.TextDrawing = .pixels, - /// Where the Ensoniq's output is written, if anywhere. + /// Where the Ensoniq's output is written, if anywhere. This is the `.wav` + /// file, kept whatever live audio does. audio: ?[]const u8 = null, + /// Live audio: the Ensoniq out of a real speaker, on by default where a + /// daemon answers, and how loud it starts and whether muted. + sound: bool = true, + volume: u8 = 80, + mute: bool = false, /// The two ends of the modem port's wire, which is channel B of the SCC. /// The printer port is channel A of the same chip and is reached the same /// way; nothing here writes to it yet. @@ -1253,7 +1295,7 @@ pub fn run(init: std.process.Init, params: Params) !void { const screenshot = params.screenshot; const monitor = params.monitor; const text = params.text; - const audio = params.audio; + const audio_path = params.audio; const disk_path = params.disk; const hard_disks = params.hard_disks; const machine_rom = params.rom; @@ -1391,23 +1433,38 @@ pub fn run(init: std.process.Init, params: Params) !void { }; }; - if (audio) |path| { - // One channel, because a IIgs has one speaker. The chip has sixteen - // output channels and a stereo card decoded three of the bits that - // name them, but that was a card people bought rather than part of the - // machine, and there is no card here. + // Live audio, on by default: the Ensoniq out of a real speaker. Falls back + // to silence if there is no daemon, and is kept for the life of the program + // -- see the App field. `--audio` still records a file whatever this is. + if (params.sound) { + var volume = audio.Volume.fromPercent(params.volume); + volume.muted = params.mute; + app.audio = audio.Output.open(gpa, "zig65 IIgs", volume); + } + + // A recording that writes a file, plays live, or both. One channel, because + // a IIgs has one speaker: the chip has sixteen output channels and a stereo + // card decoded three of the bits that name them, but that was a card people + // bought rather than part of the machine, and there is none here. The rate + // is the live graph's when there is one, so the two agree, and the file + // takes it too. + if (audio_path != null or app.audio.live()) { + const rate: u64 = if (app.audio.live()) app.audio.rate else sample_rate; + var file: ?*zig65.wav.Writer = null; + if (audio_path) |path| file = zig65.wav.Writer.create(io, gpa, path, @intCast(rate), 1) catch |err| { + std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); + std.process.exit(1); + }; app.session.recording = .{ - .file = zig65.wav.Writer.create(io, gpa, path, sample_rate, 1) catch |err| { - std.debug.print("gs: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); - std.process.exit(1); - }, + .file = file, + .capture = app.audio.live(), .cycles_per_second = cycles_per_second, - .rate = sample_rate, + .rate = rate, .started = cpu.clock.cycles, }; // The machine does the sampling, because the only place the chip can - // be looked at as often as a file wants is where the chip is wound - // forward. + // be looked at as often as the recording wants is where the chip is + // wound forward. cpu.memory.sound = &app.session.recording.?; } if (disk_path) |path| app.session.insert(path, null) catch |err| { @@ -1435,6 +1492,9 @@ pub fn run(init: std.process.Init, params: Params) !void { // recording finished, the ports and the network closed — in one place. The // terminal below is torn down separately. defer app.session.deinit(); + // The live stream is the front end's, not the session's, so it is closed + // here. The recording only ever borrowed samples into a buffer of its own. + defer app.audio.close(); app.tty = try vaxis.Tty.init(io, &app.tty_buffer); defer app.tty.deinit(); app.writer = app.tty.writer(); diff --git a/src/main.zig b/src/main.zig index 26a2ebd..80442b6 100644 --- a/src/main.zig +++ b/src/main.zig @@ -414,6 +414,12 @@ const usage = \\ recording, since sound played faster or slower is \\ the wrong sound. Nothing stops the file growing: \\ about five megabytes a minute, until it is closed. + \\ --no-audio do not play the machine's sound live. It plays out + \\ loud by default, through the host's audio, and + \\ --audio still records a file whatever this is. + \\ --volume N how loud live audio starts, 0 to 100. alt+, and + \\ alt+. change it while it runs, alt+/ mutes it. + \\ --mute start with live audio muted, the volume kept. \\ --cassette-in PATH play a WAV into the cassette input, as a tape. \\ alt+t winds it back and plays it again. \\ --cassette-out PATH write what the cassette output puts out to PATH, @@ -579,6 +585,15 @@ const Options = struct { library: []const config.Disk = &.{}, /// Where to record what the speaker plays, if anywhere. audio: ?[]const u8 = null, + /// Whether to play the machine's sound live, out of a real speaker. On by + /// default where the platform and a running daemon allow it; a machine + /// with no daemon to talk to falls back to silence rather than failing. + /// `--audio` still records a file whatever this is. + sound: bool = true, + /// How loud live audio starts, nought to a hundred, and whether it starts + /// muted. The keys that work the volume move from here. + volume: u8 = 80, + mute: bool = false, /// Where alt+g writes a picture of the machine's screen. screenshot: []const u8 = "screen.png", /// Which monitor the machine is being looked at on, and who draws the @@ -869,6 +884,9 @@ fn applyConfig(options: *Options, rom: *?[]const u8, file: config.Config) void { if (file.screenshot) |path| options.screenshot = path; if (file.halted) |yes| options.halted = yes; if (file.audio) |path| options.audio = path; + if (file.sound) |yes| options.sound = yes; + if (file.volume) |v| options.volume = v; + if (file.mute) |yes| options.mute = yes; if (file.cassette_in) |path| options.cassette_in = path; if (file.cassette_out) |path| options.cassette_out = path; if (file.memory) |text| options.memory = parseMemory(text, &options.memory_hires) orelse { @@ -1013,6 +1031,16 @@ fn parseArgs(args: std.process.Args, io: std.Io, gpa: std.mem.Allocator) ?Option options.unidisks[1] = wants.path(&it, "--unidisk2"); } else if (std.mem.eql(u8, arg, "--audio")) { options.audio = wants.path(&it, "--audio"); + } else if (std.mem.eql(u8, arg, "--no-audio")) { + options.sound = false; + } else if (std.mem.eql(u8, arg, "--volume")) { + const text = wants.path(&it, "--volume"); + options.volume = std.fmt.parseInt(u8, text, 10) catch { + std.debug.print("zig65: --volume wants a number from 0 to 100, not '{s}'\n", .{text}); + std.process.exit(2); + }; + } else if (std.mem.eql(u8, arg, "--mute")) { + options.mute = true; } else if (std.mem.eql(u8, arg, "--screenshot")) { options.screenshot = wants.path(&it, "--screenshot"); } else if (std.mem.eql(u8, arg, "--monitor")) { @@ -1313,6 +1341,12 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { /// it. The terminal debugger is this plus the drawing and the keys. session: SessionT, + /// The host's live audio, opened once at startup and kept for the life + /// of the program: a machine reset makes a fresh recording but the one + /// stream stays open, so the sound does not flicker. The recording + /// borrows this; the volume keys work it. Silent until `init` opens it. + audio: sess.audio.Output = .{}, + io: std.Io, alloc: std.mem.Allocator, should_quit: bool, @@ -1554,24 +1588,42 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { // sess.Recording, if it was asked for. The speed goes with it: sound played // faster or slower than the machine played it is the wrong sound, so // the machine is held at its own rate and the speed keys are refused. - if (options.audio) |path| { - if (comptime !SessionT.hasSpeaker()) { - std.debug.print("zig65: this machine has no speaker to record\n", .{}); - std.process.exit(1); + if (comptime SessionT.hasSpeaker()) { + // Live audio, on by default: open the host's speaker so the + // machine can be heard. It falls back to silence if there is no + // daemon to talk to, and it is kept for the life of the program + // -- a reset makes a fresh recording but not a fresh stream. + if (options.sound) { + var volume = sess.audio.Volume.fromPercent(options.volume); + volume.muted = options.mute; + self.audio = sess.audio.Output.open(alloc, "zig65", volume); } - self.session.target_hz = SessionT.machine_hz; - self.session.recording = sess.Recording.open( - io, - alloc, - path, - SessionT.machine_hz, - self.session.cpu.clock.cycles, - options.mockingboard, - @hasField(CPU.Memory, "dac_log"), - ) catch |err| { - std.debug.print("zig65: cannot record to '{s}': {s}\n", .{ path, @errorName(err) }); - std.process.exit(1); - }; + + // The recording renders the speaker once and hands it to the + // file, the live speaker, or both. A file holds the machine to + // its own rate -- sound played faster than the machine played it + // is the wrong sound -- but live audio does not, and drops what + // it cannot keep up with instead, so the speed keys still work + // when only it is playing. + if (options.audio != null or self.audio.live()) { + if (options.audio != null) self.session.target_hz = SessionT.machine_hz; + self.session.recording = sess.Recording.open( + io, + alloc, + options.audio, + &self.audio, + SessionT.machine_hz, + self.session.cpu.clock.cycles, + options.mockingboard, + @hasField(CPU.Memory, "dac_log"), + ) catch |err| { + std.debug.print("zig65: cannot record to '{s}': {s}\n", .{ options.audio orelse "the speaker", @errorName(err) }); + std.process.exit(1); + }; + } + } else if (options.audio != null) { + std.debug.print("zig65: this machine has no speaker to record\n", .{}); + std.process.exit(1); } // The printer card in slot 1. What is on the end of its cable is @@ -1616,6 +1668,9 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { io, alloc, path, + // The cassette output is a data signal saved to a + // file, not something to play live, so no live output. + null, SessionT.machine_hz, self.session.cpu.clock.cycles, false, @@ -2187,6 +2242,9 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { /// let go of the machine and everything it had open. pub fn deinit(self: *Self) void { self.session.deinit(); + // After the session, which lets go of the recording that borrowed + // this: the stream is the front end's to close. + self.audio.close(); self.display.deinit(self.alloc); self.vx.deinit(self.alloc, self.writer); self.tty.deinit(); @@ -2476,11 +2534,34 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { self.session.cpu.memory.playTape(tape.levels, tape.sample_rate); self.session.say(0, "tape wound back", .{}); }; + + // The live volume: quieter, louder, or muted. Nothing to hear + // on a machine with no speaker, but the keys are harmless there. + if (key.matches(',', .{ .alt = true })) { + self.audio.volume.quieter(); + self.announceVolume(); + } + if (key.matches('.', .{ .alt = true })) { + self.audio.volume.louder(); + self.announceVolume(); + } + if (key.matches('/', .{ .alt = true })) { + self.audio.volume.toggleMute(); + self.announceVolume(); + } } - // Not while recording. What is being written is what the machine - // played, and a machine played faster is playing something else. - if (self.session.recording == null) self.speed(key); + // Not while a file is being written. What is written is what the + // machine played, and a machine played faster is playing something + // else; live audio does not mind -- it just drops what it cannot + // keep up with -- so it does not hold the speed keys back. + if (self.session.recording == null or self.session.recording.?.wav == null) self.speed(key); + } + + /// Says how loud the live audio is now, after a volume key. + fn announceVolume(self: *Self) void { + var buffer: [8]u8 = undefined; + self.session.announce("volume {s}", .{self.audio.volume.describe(&buffer)}); } /// The keys that change how fast the machine runs: double it, halve it, or @@ -3477,6 +3558,9 @@ pub fn main(init: std.process.Init) !void { .monitor = options.monitor, .text = options.text, .audio = options.audio, + .sound = options.sound, + .volume = options.volume, + .mute = options.mute, .memory = options.memory, .serial_in = options.serial_in, .serial_out = options.serial_out, diff --git a/src/session16.zig b/src/session16.zig index d341f45..cc007a2 100644 --- a/src/session16.zig +++ b/src/session16.zig @@ -796,7 +796,7 @@ pub const Session = struct { self.ejectUnidisk(0); self.ejectUnidisk(1); self.unmountAll(); - if (self.recording) |rec| rec.file.finish(self.io, self.gpa); + if (self.recording) |rec| if (rec.file) |file| file.finish(self.io, self.gpa); self.recording = null; if (self.serial_out) |file| file.close(self.io); self.serial_out = null; diff --git a/src/session8.zig b/src/session8.zig index d930ac3..bf37ded 100644 --- a/src/session8.zig +++ b/src/session8.zig @@ -27,6 +27,10 @@ const std = @import("std"); const zig65 = @import("zig65"); +/// The host's live audio, shared with the front ends the way `terminal` is: +/// re-exported so `main.zig` and `gs.zig` reach `audio.Output` and `audio.Volume` +/// through the session rather than importing it a second time. +pub const audio = @import("audio"); const disk2 = zig65.disk2; const disk35 = zig65.disk35; const screen = zig65.screen; @@ -116,19 +120,26 @@ pub const step_budget_ns = 10 * std.time.ns_per_ms; /// instruction costs more than the instruction does. pub const steps_between_clock_checks = 4096; -/// A recording of what the speaker did, written as it happens. +/// Where the sound a machine makes goes: turning the log of the moments the +/// cone moved into samples, and handing those to a `.wav` file, to the host's +/// live audio, or to both. It renders once and fans the samples out, because +/// the log is consumed as it is read and so has one reader. /// -/// The file itself is `zig65.wav`, which both front ends share; what is here -/// is the part that is particular to this machine — turning a log of the -/// moments the cone moved into samples, and mixing a card's two channels -/// around the speaker's one. +/// One or the other end may be absent — a `.wav` with no live audio, or live +/// audio with no file — but not both, in which case there is nothing here to +/// make and `open` returns null. A card's two channels have the speaker mixed +/// down the middle of them; without a card there is the speaker's one. pub const Recording = struct { - /// Compact disc rate, which is more than enough for a machine whose - /// speaker is one bit and whose processor flips it every ten cycles at the - /// very fastest. - const sample_rate = 44_100; - - wav: *zig65.wav.Writer, + /// The compact-disc rate the file used before live audio was a thing, and + /// the fallback when nothing is playing to say what rate the graph wants. + const default_rate = 44_100; + + /// The file, if one was asked for. + wav: ?*zig65.wav.Writer = null, + /// The host's live audio, borrowed from the front end that owns it so that + /// it outlives a machine reset, which makes a fresh recording but keeps the + /// one open stream. Null when nothing is playing. + out: ?*audio.Output = null, renderer: zig65.speaker.Renderer, /// The card, if there is one: it makes two channels of its own, and the /// speaker goes down the middle of them. @@ -138,42 +149,53 @@ pub const Recording = struct { dac: ?zig65.speaker.LevelRenderer = null, samples: [16 * 1024]f32 = undefined, both: [32 * 1024]f32 = undefined, - /// How many samples have been written, which is what the header needs. - written: u32 = 0, + /// Opens a recording for whichever of the two ends is wanted, or returns + /// null when neither is: a `.wav` at `path` if `path` is given, live audio + /// through `out` if it is playing. The rate is the live graph's when there + /// is one, so the renderers match it, and the file takes that rate too; + /// otherwise it is the old compact-disc rate. pub fn open( io: std.Io, alloc: std.mem.Allocator, - path: []const u8, + path: ?[]const u8, + out: ?*audio.Output, cycles_per_second: f64, cycle: u64, with_board: bool, with_dac: bool, - ) !*Recording { - const wav = try zig65.wav.Writer.create( + ) !?*Recording { + const live = if (out) |o| o.live() else false; + if (path == null and !live) return null; + const rate: u32 = if (live) out.?.rate else default_rate; + + var wav: ?*zig65.wav.Writer = null; + if (path) |p| wav = try zig65.wav.Writer.create( io, alloc, - path, - sample_rate, + p, + rate, // A card makes two channels of its own; without one there is only // the speaker, and the speaker is one. if (with_board) 2 else 1, ); - errdefer wav.finish(io, alloc); + errdefer if (wav) |w| w.finish(io, alloc); const self = try alloc.create(Recording); self.* = .{ .wav = wav, - .renderer = .init(cycles_per_second, sample_rate, cycle), - .board = if (with_board) .init(cycles_per_second, sample_rate, cycle) else null, - .dac = if (with_dac) .init(cycles_per_second, sample_rate, cycle) else null, + .out = if (live) out else null, + .renderer = .init(cycles_per_second, @floatFromInt(rate), cycle), + .board = if (with_board) .init(cycles_per_second, @floatFromInt(rate), cycle) else null, + .dac = if (with_dac) .init(cycles_per_second, @floatFromInt(rate), cycle) else null, }; return self; } - /// Writes however much sound the line has made since the last look. The - /// line is the speaker or the cassette output: they are the same hardware - /// twice over, so they are the same recording twice over. + /// Renders however much sound the line has made since the last look and + /// hands it to the file and the speaker. The line is the machine's speaker + /// or its cassette output: the same hardware twice over, so the same + /// recording twice over. fn take(self: *Recording, log: anytype, board_log: anytype, dac_log: anytype, until: u64) !void { while (true) { const flips = log.taken(); @@ -195,22 +217,30 @@ pub const Recording = struct { const made = board.render(board_log.taken(), until, self.both[0 .. done.samples * 2]); board_log.consume(made.entries); const frames = @min(done.samples, made.samples / 2); + // One speaker and two channels, so it goes down the middle of + // them, which is where a machine with a card in it sounds like + // it is coming from. The mix is left in `both` so the file and + // the speaker are handed the very same samples. for (0..frames) |i| { - // One speaker and two channels, so it goes down the middle - // of them, which is where a machine with a card in it - // sounds like it is coming from. - try self.wav.putFloat(self.samples[i] + self.both[i * 2]); - try self.wav.putFloat(self.samples[i] + self.both[i * 2 + 1]); + self.both[i * 2] += self.samples[i]; + self.both[i * 2 + 1] += self.samples[i]; } + if (self.wav) |w| for (0..frames) |i| { + try w.putFloat(self.both[i * 2]); + try w.putFloat(self.both[i * 2 + 1]); + }; + if (self.out) |o| o.playStereo(self.both[0 .. frames * 2]); } else { - for (self.samples[0..done.samples]) |sample| try self.wav.putFloat(sample); + if (self.wav) |w| for (self.samples[0..done.samples]) |sample| try w.putFloat(sample); + if (self.out) |o| o.playMono(self.samples[0..done.samples]); } } } - /// Puts the sizes in the header right and closes the file. + /// Puts the sizes in the file's header right and closes it. The live audio + /// is not touched: the front end owns it and keeps it across a reset. fn close(self: *Recording, io: std.Io, alloc: std.mem.Allocator) void { - self.wav.finish(io, alloc); + if (self.wav) |w| w.finish(io, alloc); alloc.destroy(self); } }; diff --git a/tools/audio.zig b/tools/audio.zig new file mode 100644 index 0000000..28cdaec --- /dev/null +++ b/tools/audio.zig @@ -0,0 +1,264 @@ +// 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(); +} diff --git a/tools/bootgs.zig b/tools/bootgs.zig index 52764a0..bdf9f2c 100644 --- a/tools/bootgs.zig +++ b/tools/bootgs.zig @@ -291,7 +291,7 @@ pub fn main(init: std.process.Init) !void { .rate = sample_rate, .started = cpu.clock.cycles, } else null; - defer if (recorder) |rec| rec.file.finish(io, gpa); + defer if (recorder) |rec| if (rec.file) |f| f.finish(io, gpa); if (recorder) |*rec| cpu.memory.sound = rec; var scc_log: ?std.Io.File = null; diff --git a/tools/config.zig b/tools/config.zig index e5ca067..a8310d0 100644 --- a/tools/config.zig +++ b/tools/config.zig @@ -186,11 +186,24 @@ pub const Config = struct { /// Whether to start stopped rather than running. halted: ?bool = null, - /// Recording what the speaker did, and the tape either way. + /// Recording what the speaker did to a `.wav`, and the tape either way in + /// or out of one. These stay whatever live audio does: `audio` writes a + /// file, `cassette_in` reads one, `cassette_out` writes one. audio: ?[]const u8 = null, cassette_in: ?[]const u8 = null, cassette_out: ?[]const u8 = null, + /// Live audio: the machine's sound out of a real speaker. On where the + /// platform and a running daemon allow it; `false` keeps it quiet. This is + /// separate from `audio` above, which records to a file regardless. + sound: ?bool = null, + /// How loud live audio starts, nought to a hundred. Left unset it is the + /// built-in default; the keys that work the volume move it from here. + volume: ?u8 = null, + /// Whether live audio starts muted, the volume kept for when it is + /// unmuted. + mute: ?bool = null, + /// How much RAM the machine has, as a size like "1M", "512K" or "48K". A /// IIgs counts the Mega II's 128K; an Apple II or II Plus counts its rows /// of chips, in the configurations Apple sold, and "12K-hires" is the -- knotmirror 0.0.1