// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The speaker, and turning what it did into sound. //! //! There is one bit of speaker on an Apple II. Every access to $c030 flips the //! cone, and that is the whole of the hardware: no volume, no waveform, no //! timer. Everything a program plays it makes by choosing when to flip, so the //! only thing that carries any sound at all is the timing, measured in //! processor cycles. //! //! That is why this keeps the cycle each flip happened on rather than telling //! anybody a click occurred. A tone is a steady rate of flipping; the two voice //! music people wrote for these machines is an artfully uneven one; and a good //! deal of what games do is pulses a few cycles wide. Told only that the cone //! moved, none of that can be told apart or reproduced. const std = @import("std"); /// How many flips a log holds before it starts dropping them. /// /// A tight toggle loop flips the cone about every ten cycles, so something like /// a hundred thousand times a second, and a caller draining once a frame needs /// a couple of thousand. This is room for a good deal more than that, and what /// does not fit is counted rather than quietly lost. pub const capacity = 8192; /// A record of when the cone moved, or nothing at all. /// /// Keeping it costs a compare and a store on every access to the speaker, so /// whether to keep it is a decision the caller makes when it chooses a memory /// model. The disabled version has the same shape and does nothing, so a model /// needs no conditionals of its own. pub fn Log(comptime enabled: bool) type { return if (enabled) struct { const Self = @This(); cycles: [capacity]u64 = undefined, len: usize = 0, /// Flips there was no room for. Nothing here goes wrong when this is /// not zero; the sound does, and silently, which is worth being able /// to notice. dropped: u64 = 0, pub fn record(self: *Self, cycle: u64) void { if (self.len == capacity) { self.dropped += 1; return; } self.cycles[self.len] = cycle; self.len += 1; } /// The flips since the last clearing, in the order they happened. /// /// Read these and be done with them before letting the machine run /// again: what they point at is where the next ones will be written. pub fn taken(self: *const Self) []const u64 { return self.cycles[0..self.len]; } pub fn clear(self: *Self) void { self.len = 0; } /// Drops the first `count` flips and keeps the rest. /// /// What renders is whole samples, so a flip that falls in the sample /// after the last one rendered has not been used yet and has to wait /// for it. Dropping it instead would leave the cone the wrong way /// round from then on, which is a click rather than a nothing. pub fn consume(self: *Self, count: usize) void { const taking = @min(count, self.len); std.mem.copyForwards(u64, self.cycles[0 .. self.len - taking], self.cycles[taking..self.len]); self.len -= taking; } } else struct { const Self = @This(); pub fn record(_: *Self, _: u64) void {} pub fn taken(_: *const Self) []const u64 { return &.{}; } pub fn clear(_: *Self) void {} pub fn consume(_: *Self, _: usize) void {} }; } /// Turns the times the cone moved into sound. /// /// A sample is not the state of the cone at an instant. It is where the cone /// was over the whole of that sample's worth of time, so this adds up how long /// the cone spent each way round inside the sample and divides. That matters /// more than it sounds: a sample at 44.1kHz is about twenty-three cycles, and a /// good deal of what these machines play is pulses shorter than that. Looking /// at the state once a sample would miss them completely and play silence where /// there was a click; adding up the time puts the same energy in the sample /// wherever inside it the pulse fell. pub const Renderer = struct { /// How many processor cycles one output sample lasts. cycles_per_sample: f64, /// Where the sample being built starts, in cycles. at: f64, /// Which way the cone is, as the value it contributes. level: f32 = -1, /// How loud, with room left over for what the filter below does at a step. amplitude: f32 = 0.6, /// The state of the filter that takes the constant part out. A square wave /// sitting one way round is a direct current, and a cone cannot hold itself /// out: it drifts back, and so does this. /// /// What the filter last saw starts at where the cone is rather than at /// zero. A cone that has not moved is a cone at rest, and starting the /// filter at zero instead makes the machine's first moment of silence a /// full sized thump that takes a second to die away. decay: f32, last_in: f32 = -1, last_out: f32 = 0, /// The rate is the machine's, in cycles a second: a IIe runs at 1020500. pub fn init(cycles_per_second: f64, sample_rate: f64, start_cycle: u64) Renderer { return .{ .cycles_per_sample = cycles_per_second / sample_rate, .at = @floatFromInt(start_cycle), // A twenty hertz corner, which is below anything a person hears // and well below anything this machine plays. .decay = 1.0 - (2.0 * std.math.pi * 20.0 / @as(f32, @floatCast(sample_rate))), }; } /// How many samples are owed for the time up to this cycle. Size a buffer /// with this: what does not fit is not rendered, and the sound has a hole /// in it rather than a delay. pub fn samplesDue(self: *const Renderer, until: u64) usize { const ahead = @as(f64, @floatFromInt(until)) - self.at; if (ahead < self.cycles_per_sample) return 0; return @intFromFloat(ahead / self.cycles_per_sample); } /// What one go at rendering came to. pub const Rendered = struct { /// Samples written. samples: usize, /// Flips used up, so that a caller whose buffer filled before the /// machine's time ran out knows where to carry on from rather than /// losing what is left. flips: usize, }; /// Renders the sound made up to `until`, given the flips that happened up /// to it. /// /// Stops when the buffer is full or when it runs out of machine time, /// whichever comes first, and says how far it got either way. pub fn render(self: *Renderer, flips: []const u64, until: u64, out: []f32) Rendered { const limit: f64 = @floatFromInt(until); var written: usize = 0; var next: usize = 0; while (written < out.len) { const ends = self.at + self.cycles_per_sample; if (ends > limit) break; // How long the cone spent each way round inside this sample. var span: f64 = 0; var position = self.at; while (next < flips.len) : (next += 1) { const flip: f64 = @floatFromInt(flips[next]); if (flip >= ends) break; // A flip from before this sample belongs at its start: the // machine may have run on before anybody asked for sound. const when = @max(flip, position); span += (when - position) * self.level; position = when; self.level = -self.level; } span += (ends - position) * self.level; out[written] = self.settle(@floatCast(span / self.cycles_per_sample)) * self.amplitude; written += 1; self.at = ends; } return .{ .samples = written, .flips = next }; } /// One pole of high pass, which is what takes the constant part out. fn settle(self: *Renderer, in: f32) f32 { const out = in - self.last_in + self.decay * self.last_out; self.last_in = in; self.last_out = out; return out; } }; /// One level a leveled line was driven to, and the cycle it happened on. pub const LevelEntry = struct { cycle: u64, level: f32 }; /// A record of a leveled sound line, such as the Apple III's six-bit DAC: /// the level it was set to and the cycle it was set on. Where the speaker /// above keeps the moments a one-bit cone flipped, this keeps the value a /// many-bit one was driven to, since that is what a program chooses. pub fn LevelLog(comptime enabled: bool) type { return if (enabled) struct { const Self = @This(); pub const Entry = LevelEntry; entries: [capacity]Entry = undefined, len: usize = 0, dropped: u64 = 0, /// The level the line is at, so a write that does not change it is /// not logged and a full log does not lose where the line stands. level: f32 = 0, /// Records a new level for the line, in [-1, 1], if it has changed. pub fn record(self: *Self, cycle: u64, level: f32) void { if (level == self.level) return; self.level = level; if (self.len == capacity) { self.dropped += 1; return; } self.entries[self.len] = .{ .cycle = cycle, .level = level }; self.len += 1; } pub fn taken(self: *const Self) []const Entry { return self.entries[0..self.len]; } pub fn clear(self: *Self) void { self.len = 0; } pub fn consume(self: *Self, count: usize) void { const keep = self.len - count; std.mem.copyForwards(Entry, self.entries[0..keep], self.entries[count..self.len]); self.len = keep; } } else struct { const Self = @This(); pub const Entry = LevelEntry; pub fn record(_: *Self, _: u64, _: f32) void {} pub fn taken(_: *const Self) []const Entry { return &.{}; } pub fn clear(_: *Self) void {} pub fn consume(_: *Self, _: usize) void {} }; } /// Turns a leveled log into samples, and adds them to what is there: the /// six-bit DAC and the one-bit speaker share the one cone, so the DAC is /// mixed into the speaker's channel rather than given one of its own. Same /// high-pass as the speaker, since it is the same cone that cannot hold a /// constant, and a quieter amplitude, the DAC being the softer of the two. pub const LevelRenderer = struct { cycles_per_sample: f64, at: f64, level: f32 = 0, amplitude: f32 = 0.3, decay: f32, last_in: f32 = 0, last_out: f32 = 0, pub fn init(cycles_per_second: f64, sample_rate: f64, start_cycle: u64) LevelRenderer { return .{ .cycles_per_sample = cycles_per_second / sample_rate, .at = @floatFromInt(start_cycle), .decay = 1.0 - (2.0 * std.math.pi * 20.0 / @as(f32, @floatCast(sample_rate))), }; } pub const Rendered = struct { samples: usize, entries: usize }; /// Renders up to `until`, mixing into `out` — each sample is added, not /// stored — and says how far it got. Stops at the buffer's end or the /// machine's time, whichever comes first. pub fn render(self: *LevelRenderer, entries: []const Entry, until: u64, out: []f32) Rendered { const limit: f64 = @floatFromInt(until); var written: usize = 0; var next: usize = 0; while (written < out.len) { const ends = self.at + self.cycles_per_sample; if (ends > limit) break; var span: f64 = 0; var position = self.at; while (next < entries.len) : (next += 1) { const when_cycle: f64 = @floatFromInt(entries[next].cycle); if (when_cycle >= ends) break; const when = @max(when_cycle, position); span += (when - position) * self.level; position = when; self.level = entries[next].level; } span += (ends - position) * self.level; out[written] += self.settle(@floatCast(span / self.cycles_per_sample)) * self.amplitude; written += 1; self.at = ends; } return .{ .samples = written, .entries = next }; } const Entry = LevelEntry; fn settle(self: *LevelRenderer, in: f32) f32 { const out = in - self.last_in + self.decay * self.last_out; self.last_in = in; self.last_out = out; return out; } }; const testing = std.testing; test "a log keeps when the cone moved, and says when it could not" { var log: Log(true) = .{}; try testing.expectEqual(@as(usize, 0), log.taken().len); log.record(10); log.record(3000); try testing.expectEqualSlices(u64, &.{ 10, 3000 }, log.taken()); log.clear(); try testing.expectEqual(@as(usize, 0), log.taken().len); // Full, and then honest about it. for (0..capacity + 5) |cycle| log.record(cycle); try testing.expectEqual(capacity, log.taken().len); try testing.expectEqual(@as(u64, 5), log.dropped); } test "a log that is not kept costs nothing and has nothing" { var log: Log(false) = .{}; log.record(10); try testing.expectEqual(@as(usize, 0), log.taken().len); try testing.expectEqual(@as(usize, 0), @sizeOf(Log(false))); } test "a steady flipping comes out as a tone of that frequency" { const rate = 1_020_500.0; const sample_rate = 44_100.0; // A thousand hertz is two thousand flips a second. const cycles_between = rate / 2000.0; var flips: [2000]u64 = undefined; for (&flips, 0..) |*flip, i| flip.* = @intFromFloat(@as(f64, @floatFromInt(i)) * cycles_between); var renderer: Renderer = .init(rate, sample_rate, 0); var samples: [44_100]f32 = undefined; const written = renderer.render(&flips, @intFromFloat(rate), &samples).samples; try testing.expect(written > 44_000); // Count the times it crosses zero: a thousand hertz crosses two thousand // times a second, and the filter takes a moment to settle, so allow a // little either way. var crossings: usize = 0; for (samples[100..written], samples[99 .. written - 1]) |now, before| { if ((now > 0) != (before > 0)) crossings += 1; } try testing.expect(crossings > 1950 and crossings < 2050); } test "a pulse far shorter than a sample still makes a sound" { const pulse = struct { /// How loud one pulse of a given width comes out. fn loudness(width: u64) f32 { var renderer: Renderer = .init(1_020_500.0, 44_100.0, 0); var samples: [64]f32 = undefined; const flips = [_]u64{ 100, 100 + width }; const written = renderer.render(&flips, 20_000, &samples).samples; var loudest: f32 = 0; for (samples[0..written]) |sample| loudest = @max(loudest, @abs(sample)); return loudest; } }; // Four cycles out and back is a sixth of one sample at 44.1kHz, and would // be missed altogether by looking at the cone once a sample. const narrow = pulse.loudness(4); try testing.expect(narrow > 0.01); // And a wider pulse is louder than a narrow one, which is the whole point // of adding up the time rather than taking a look. try testing.expect(pulse.loudness(12) > narrow); try testing.expect(pulse.loudness(20) > pulse.loudness(12)); } test "silence is silent" { var renderer: Renderer = .init(1_020_500.0, 44_100.0, 0); var samples: [1000]f32 = undefined; const written = renderer.render(&.{}, 100_000, &samples).samples; try testing.expect(written > 0); // The cone is not moving, so there is nothing to hear, from the first // sample rather than after something has died away. for (samples[0..written]) |sample| try testing.expectEqual(@as(f32, 0), sample); } test "rendering in pieces sounds the same as rendering in one go" { const rate = 1_020_500.0; var flips: [500]u64 = undefined; for (&flips, 0..) |*flip, i| flip.* = 37 * i + (i % 7) * 11; var whole: Renderer = .init(rate, 44_100.0, 0); var all: [2000]f32 = undefined; const written = whole.render(&flips, 20_000, &all).samples; // The same flips handed over in two goes, which is what anything draining // once a frame does. A join that is not seamless is a click every frame. var piecemeal: Renderer = .init(rate, 44_100.0, 0); var parts: [2000]f32 = undefined; var split: usize = 0; while (flips[split] < 10_000) split += 1; const first = piecemeal.render(flips[0..split], 10_000, &parts).samples; const second = piecemeal.render(flips[split..], 20_000, parts[first..]).samples; try testing.expectEqual(written, first + second); for (all[0..written], parts[0..written]) |one, other| { try testing.expectApproxEqAbs(one, other, 1e-6); } } test "how many samples are owed" { var renderer: Renderer = .init(1_020_500.0, 44_100.0, 0); try testing.expectEqual(@as(usize, 0), renderer.samplesDue(0)); try testing.expectEqual(@as(usize, 0), renderer.samplesDue(10)); // A second of machine time is a second of sound. try testing.expectEqual(@as(usize, 44_100), renderer.samplesDue(1_020_500)); } test "a buffer that fills early says where to carry on from" { var flips: [400]u64 = undefined; for (&flips, 0..) |*flip, i| flip.* = 50 * (i + 1); var renderer: Renderer = .init(1_020_500.0, 44_100.0, 0); // Room for four samples, against machine time enough for far more. var samples: [4]f32 = undefined; const first = renderer.render(&flips, 20_000, &samples); try testing.expectEqual(@as(usize, 4), first.samples); try testing.expect(first.flips > 0 and first.flips < flips.len); // Carrying on from where it said leaves nothing out: the rest of the // flips render into the samples that follow. var rest: [1024]f32 = undefined; const second = renderer.render(flips[first.flips..], 20_000, &rest); try testing.expect(second.samples > 0); // All but the one sitting exactly where the machine's time ran out. That // flip belongs to the sample after the last one rendered, so it waits for // it, and turns up once there is time enough to render that sample. try testing.expectEqual(flips.len - 1, first.flips + second.flips); const last = renderer.render(flips[first.flips + second.flips ..], 40_000, &rest); try testing.expectEqual(@as(usize, 1), last.flips); } test "a log gives up only what was used" { var log: Log(true) = .{}; for (0..5) |cycle| log.record(cycle * 100); log.consume(2); try testing.expectEqualSlices(u64, &.{ 200, 300, 400 }, log.taken()); log.consume(0); try testing.expectEqualSlices(u64, &.{ 200, 300, 400 }, log.taken()); // Asking for more than there is takes what there is. log.consume(99); try testing.expectEqual(@as(usize, 0), log.taken().len); } test "a leveled log keeps only the changes, and the renderer mixes a ramp into the samples" { var log: LevelLog(true) = .{}; log.record(0, 0.0); log.record(0, 0.0); // no change, not logged log.record(100, 0.5); log.record(200, 0.5); // no change log.record(300, 1.0); try testing.expectEqual(@as(usize, 2), log.taken().len); var out: [64]f32 = @splat(1.0); var renderer: LevelRenderer = .init(44_100, 44_100, 0); // One sample a cycle here is absurd, but it lets a level land in a sample. renderer.cycles_per_sample = 50; const done = renderer.render(log.taken(), 1600, &out); log.consume(done.entries); try testing.expect(done.samples > 0); // The samples were added to the ones already there, not overwritten: // the first, over the level-zero stretch, is still one. try testing.expectEqual(@as(f32, 1.0), out[0]); // And a later one, where the level has risen, is above one. try testing.expect(out[10] > 1.0); }