Something went wrong. Try again.
A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! A Phasor: Applied Engineering's superset of the Mockingboard.//!//! Where a Mockingboard is two sound chips behind two 6522s, a Phasor is//! *four* — a two-by-two block of AY-3-8913s — behind the same two 6522s, with//! a text-to-speech chip beside them and a stereo amplifier after them (Applied//! Engineering, n.d.; the parts are read off the card's own photograph in the//! brochure, and are four GI `AY-3-8913`s, two Rockwell `R6522`s and an//! `SSI 263AP`).//!//! What makes the extra two chips reachable through the same two 6522s is a//! **mode** the card carries, latched by an access to the card's device//! selects (`$C0nX`). In Mockingboard mode the card is a Mockingboard, one//! sound chip to each 6522 and nothing said to the other two; in Phasor mode//! two more chip-select lines wake up on each 6522's port B, so a 6522 can//! address either of its two chips or — with both selected — write the same//! register to both at once. A third mode, Echo+, is there for compatibility//! with that card and here behaves as Mockingboard mode does for the sound//! path. The mode encoding, the chip-select bits and the read-as-OR-sum of two//! selected chips are taken from AppleWin's model of the card, which is the//! fullest written description of the native-mode register interface there is//! (AppleWin, n.d.); the manuals in the archive document the bundled software//! and the DIP-switch mode selection but not the register interface (Applied//! Engineering, n.d.).//!//! The two 6522s and their sound chips sit in the slot's own ROM page exactly//! as a Mockingboard's do, sixteen registers each at `$Cn00` and `$Cn80`, so//! everything `mockingboard.zig` says about the 6522, the address latch and the//! order a player writes a register in holds here too — this reuses the AY, the//! 6522, the speech chip and the write log from there rather than restating//! them. What is its own is the second pair of chips, the mode, and the//! four-into-two stereo the manual describes: "chips 1 and 3 go to speaker//! channel B, chips 2 and 4 to channel A", and the card "speaks only through//! channel B" (ReActiveMicro.com, 2016).//!//! Like the Mockingboard, none of this has been checked against real software;//! it is checked against the published description of the parts and the sound//! that comes out of them.
const std = @import("std");const testing = std.testing;
const ay3 = @import("ay3.zig");const via = @import("via.zig");const ssi263 = @import("ssi263.zig");const mockingboard = @import("mockingboard.zig");
/// The write log is the Mockingboard's, whose chip field is wide enough for/// four chips: a Phasor writes chips nought to three, a Mockingboard nought to/// one, and the sound is made from the log the same way for both.pub const Log = mockingboard.Log;
/// Where the two 6522s answer in the slot page, as on a Mockingboard: sixteen/// registers at the bottom and sixteen half way up.pub const first_via = 0x00;pub const second_via = 0x80;
/// The SSI 263A speech chip's window, with A6 set and A7 clear — card offsets/// `$40`–`$7F`, the canonical `$Cn40` — its three register-select lines the low/// three address bits, so it mirrors every eight bytes across the range. The/// Phasor populates one speech chip (the second socket on the real card is/// empty and no software ever drove it); it is wired to the first 6522's CA1,/// as the Mockingboard C's is.pub const speech_low = 0x40;pub const speech_high = 0x80;
/// What the three low lines on port B mean, as on a Mockingboard: the low two/// are the sound chip's BC1 and BDIR, the third its reset (low to reset).pub const bus_reset = 0x04;pub const bus_inactive = 0x04;pub const bus_read = 0x05;pub const bus_write = 0x06;pub const bus_latch = 0x07;
/// In Phasor mode two more of port B's lines become active-low chip selects,/// one per sound chip on that 6522: PB4 for the first chip, PB3 for the second./// Pulling both low addresses both at once (AppleWin, n.d.).pub const cs_first = 0x10; // PB4, active low: the 6522's first chippub const cs_second = 0x08; // PB3, active low: the 6522's second chip
/// The card's mode, latched from an access to its device selects. The values/// are the low three bits the card decodes off the address; only three of the/// eight are a mode the card has, and any other is treated as Mockingboard.pub const Mode = enum(u3) { mockingboard = 0, phasor = 5, echo_plus = 7, _,
/// Whether the second chip on each 6522 is awake and the chip-select lines /// are decoded, which is what Phasor mode adds and the other two do not. fn native(self: Mode) bool { return self == .phasor; }};
/// The card itself. As with the Mockingboard, the write log is not here: it/// belongs to the machine, beside the speaker's, because it is somebody/// watching the card rather than part of it, and because at four thousand/// entries it is far larger than the card.pub const Card = struct { const Self = @This();
/// Whether there is a card in the slot at all. fitted: bool = false,
/// The mode, latched from the device selects. A card powers up in /// Mockingboard mode — the mode in which the most software works — and its /// own software selects Phasor mode before using the extra chips. (On the /// real card the power-on mode is a DIP switch; this is the setting that /// keeps Mockingboard-compatible software working, which is the /// configuration people used it in most (Applied Engineering, n.d., p. 4).) mode: Mode = .mockingboard,
/// The two 6522s. vias: [2]via.Via = .{ .{}, .{} },
/// The four sound chips: chips 0 and 1 hang off the first 6522, chips 2 and /// 3 off the second. The card sends chips 0 and 2 to channel B and chips 1 /// and 3 to channel A, which is the four-into-two stereo the manual /// describes (ReActiveMicro.com, 2016). chips: [4]ay3.Chip = .{ .{}, .{}, .{}, .{} },
/// The register each 6522's last address latch pointed its chip or chips /// at, or nothing when the latch held something naming no register — the /// same rule the Mockingboard follows for its one chip per 6522. latched: [2]?u4 = .{ null, null },
/// The speech chip and the level last handed to the first 6522's CA1 from /// its Acknowledge/Request line, so only a change is passed on and the /// 6522's edge detector sees an edge. The Phasor always carries a speech /// chip, so unlike the Mockingboard there is no "is one fitted" to ask. speech: ssi263.Chip = .{}, speech_line: bool = false,
/// The reset line reaches the 6522s and the speech chip, not the whole /// card: the 6522s keep their timer latches and counters through it, the /// same as a Mockingboard, and the mode latch is not disturbed. pub fn reset(self: *Self, cycle: u64) void { for (&self.vias) |*v| v.reset(cycle); self.speech.reset(); self.speech_line = false; }
/// Whether either 6522 is pulling the interrupt line. Asked on every access /// the machine makes, so a slot with no card in it answers false inline. pub inline fn interrupting(self: *Self, cycle: u64) bool { if (!self.fitted) return false; return self.viasInterrupting(cycle); }
fn viasInterrupting(self: *Self, cycle: u64) bool { self.updateSpeechLine(cycle); var asking = false; for (&self.vias) |*v| { v.catchUp(cycle); asking = asking or v.interrupting(); } return asking; }
/// Feeds the speech chip's A/R line to the first 6522's CA1, handing over /// only a change so the edge detector sees an edge. A/R high is the chip /// busy; A/R low is it asking for the next phoneme, and the high-to-low /// edge is the interrupt. fn updateSpeechLine(self: *Self, cycle: u64) void { const high = !self.speech.asking(cycle); if (high != self.speech_line) { self.speech_line = high; self.vias[0].setLine(.ca1, high); } }
/// The card's device selects (`$C0nX`): every access, read or write, latches /// the mode. Bit three of the offset clears the accumulated mode bits; the /// low three bits are OR'd in. So `$C0n8` selects Mockingboard mode, `$C0nD` /// Phasor mode and `$C0nF` Echo+ mode in a single access, which is what the /// card's software does at startup (AppleWin, n.d.). pub fn selectMode(self: *Self, offset: u4) void { const low: u3 = @truncate(offset & 0x07); const bits: u3 = if (offset & 0x08 != 0) low else (@intFromEnum(self.mode) | low); self.mode = @enumFromInt(bits); }
/// What the slot's page answers. The two 6522s are sixteen registers each, /// and everything between them is the first one again, as the card's own /// decoding leaves it; the speech chip answers over the top of the first /// 6522's mirror at `$40`–`$7F`. pub fn access(self: *Self, offset: u8, is_write: bool, value: u8, log: anytype, cycle: u64) u8 { if (offset >= speech_low and offset < speech_high) { const register: ssi263.Register = @enumFromInt(@as(u3, @truncate(offset & 0x07))); const answer = if (is_write) blk: { self.speech.write(register, value, cycle); log.recordSpeech(cycle, @truncate(offset & 0x07), value); break :blk @as(u8, 0); } else self.speech.read(cycle); self.updateSpeechLine(cycle); return answer; }
const which: u1 = if (offset >= second_via) 1 else 0; const v = &self.vias[which]; const register: via.Register = @enumFromInt(@as(u4, @truncate(offset))); if (!is_write) return v.read(register, cycle);
v.write(register, value, cycle); if (register == .orb or register == .ddrb) self.acted(which, log, cycle); return 0; }
/// A 6522 has moved port B, which is the card's orders to the sound chips /// behind it. This is the Mockingboard's `Half.acted`, widened to the two /// chips a Phasor puts behind each 6522 and to the chip-select lines that /// pick between them in Phasor mode. fn acted(self: *Self, which: u1, log: anytype, cycle: u64) void { const v = &self.vias[which]; const driven = v.direction[1]; const lines = v.port[1];
// Reset reaches the chips this 6522 drives, whichever the mode. if (driven & bus_reset != 0 and lines & bus_reset == 0) { for (self.chipsOf(which)) |c| if (c) |i| { self.chips[i].reset(); log.reset(cycle, @intCast(i)); }; self.latched[which] = null; self.release(which); return; }
const data = v.port[0]; switch (lines & driven & 0x03) { // Both function lines high: the address latch. The data is which // register the chips are to be pointed at, if it names one. 0x03 => { self.latched[which] = if (data & 0xf0 == 0) @truncate(data & 0x0f) else null; self.release(which); }, // Write: the value goes to every chip this 6522 has selected. 0x02 => { if (self.latched[which]) |register| { for (self.selected(which, lines)) |c| if (c) |i| { self.chips[i].write(register, data); log.record(cycle, @intCast(i), register, data); }; } self.release(which); }, // Read: the chip drives port A's pins. With two chips selected the // card reads back the OR of them, which is what the wired-together // data lines give (AppleWin, n.d.). 0x01 => if (self.latched[which]) |register| { var byte: u8 = 0; var any = false; for (self.selected(which, lines)) |c| if (c) |i| { byte |= self.chips[i].read(register); any = true; }; if (any) v.setInputs(0, 0xff, byte) else self.release(which); } else self.release(which), else => self.release(which), } }
/// The chips a 6522 owns: one in Mockingboard and Echo+ mode, two in Phasor /// mode. The first 6522 owns chips 0 and 1, the second chips 2 and 3. fn chipsOf(self: *const Self, which: u1) [2]?usize { const base: usize = @as(usize, which) * 2; if (self.mode.native()) return .{ base, base + 1 }; // Mockingboard and Echo+: one chip each, and they are the pair that // renders to opposite channels, so the stereo of a Mockingboard on a // Phasor is the stereo of a Mockingboard. return .{ which, null }; }
/// The chips a 6522 has selected for a write or a read. In Phasor mode the /// two chip-select lines pick, active low, and both low picks both; outside /// it the one chip the 6522 owns is always the target. fn selected(self: *const Self, which: u1, lines: u8) [2]?usize { if (!self.mode.native()) return .{ which, null }; const base: usize = @as(usize, which) * 2; return .{ if (lines & cs_first == 0) base else null, if (lines & cs_second == 0) base + 1 else null, }; }
/// Lets go of a 6522's port A data lines, so a program reading them sees /// the pull-ups — `$ff` — rather than whatever a chip last drove. fn release(self: *Self, which: u1) void { self.vias[which].setInputs(0, 0xff, 0xff); }};
/// Turning the log into sound, four chips into two channels.////// It keeps chips of its own and walks them a sample at a time, applying each/// write as the cycle it happened on goes by, the same as the Mockingboard's/// renderer; what differs is that there are four chips and they are summed two/// to a channel — chips 0 and 2 to the left (the card's channel B, which the/// speech also comes out of), chips 1 and 3 to the right (channel A).pub const Renderer = struct { chips: [4]ay3.Chip = .{ .{}, .{}, .{}, .{} }, at: f64 = 0, cycles_per_sample: f64, owed: f64 = 0,
speech: ssi263.Chip = .{}, voice: ssi263.Voice,
pub fn init(cycles_per_second: f64, sample_rate: f64, start_cycle: u64) Renderer { return .{ .at = @floatFromInt(start_cycle), .cycles_per_sample = cycles_per_second / sample_rate, .voice = .init(@floatCast(sample_rate), @floatCast(cycles_per_second)), }; }
pub fn samplesDue(self: *const Renderer, until: u64) usize { const end: f64 = @floatFromInt(until); if (end <= self.at) return 0; return @intFromFloat((end - self.at) / self.cycles_per_sample); }
pub const Rendered = struct { samples: usize, entries: usize, };
/// Fills as much of `out` as there is sound for, left then right. pub fn render(self: *Renderer, entries: anytype, until: u64, out: []f32) Rendered { var written: usize = 0; var used: usize = 0; const frames = out.len / 2; const end: f64 = @floatFromInt(until);
while (written < frames) { const next = self.at + self.cycles_per_sample; if (next > end) break;
while (used < entries.len and @as(f64, @floatFromInt(entries[used].cycle)) <= next) : (used += 1) { const entry = entries[used]; if (entry.speech) { self.speech.write(@enumFromInt(@as(u3, @truncate(entry.register))), entry.value, entry.cycle); } else if (entry.reset) { self.chips[entry.chip].reset(); } else { self.chips[entry.chip].write(entry.register, entry.value); } }
// The speech rides channel B, which is the card's only speech // output (ReActiveMicro.com, 2016). _ = self.speech.asking(@intFromFloat(next)); const speaking = 0.5 * self.voice.sample(&self.speech);
var sum: [4]f32 = @splat(0); var ticks: usize = 0; self.owed += self.cycles_per_sample; while (self.owed >= ay3.tick_divisor) : (self.owed -= ay3.tick_divisor) { for (&self.chips, 0..) |*chip, i| { chip.step(); sum[i] += chip.level(); } ticks += 1; }
var level: [4]f32 = undefined; for (0..4) |i| level[i] = if (ticks > 0) sum[i] / @as(f32, @floatFromInt(ticks)) else self.chips[i].level();
// Chips 0 and 2 to channel B (left), chips 1 and 3 to channel A // (right); the speech is on channel B. out[written * 2] = level[0] + level[2] + speaking; out[written * 2 + 1] = level[1] + level[3]; written += 1; self.at = next; }
return .{ .samples = written * 2, .entries = used }; }};
// -- tests ------------------------------------------------------------------
/// A card and the log watching it, the pair a test needs.const Watched = struct { card: Card = .{ .fitted = true }, log: Log(true) = .{},
fn access(self: *Watched, offset: u8, is_write: bool, value: u8, cycle: u64) u8 { return self.card.access(offset, is_write, value, &self.log, cycle); }};
/// Turning port A into all outputs and quieting port B, the way a player sets/// up a 6522 before it speaks to the chips.fn ready(card: *Watched, half: u8, cycle: u64) void { const base: u8 = if (half == 0) first_via else second_via; _ = card.access(base + 3, true, 0xff, cycle); // port A all outputs _ = card.access(base + 2, true, 0x1f, cycle); // and five lines of port B _ = card.access(base + 0, true, bus_inactive, cycle);}
/// Writing a register with a chip select on port B's high bits, the way Phasor/// software addresses one of the two chips on a 6522. `cs` is the port B bits.fn playCS(card: *Watched, half: u8, cs: u8, register: u4, value: u8, cycle: u64) void { const base: u8 = if (half == 0) first_via else second_via; _ = card.access(base + 1, true, register, cycle); _ = card.access(base + 0, true, cs | bus_latch, cycle); _ = card.access(base + 0, true, cs | bus_inactive, cycle); _ = card.access(base + 1, true, value, cycle); _ = card.access(base + 0, true, cs | bus_write, cycle); _ = card.access(base + 0, true, cs | bus_inactive, cycle);}
test "the mode latch decodes an access to the device selects" { var card: Card = .{ .fitted = true }; try testing.expectEqual(Mode.mockingboard, card.mode); card.selectMode(0x0d); // $C0nD try testing.expectEqual(Mode.phasor, card.mode); card.selectMode(0x0f); // $C0nF try testing.expectEqual(Mode.echo_plus, card.mode); card.selectMode(0x08); // $C0n8 try testing.expectEqual(Mode.mockingboard, card.mode);}
test "in Phasor mode a 6522 reaches both of its chips, together or apart" { var card: Watched = .{}; card.card.selectMode(0x0d); // Phasor mode ready(&card, 0, 0); ready(&card, 1, 0);
// Select the first chip alone (PB3 high leaves the second unselected) and // write it a period; the second chip is untouched. playCS(&card, 0, cs_second, @intFromEnum(ay3.Register.a_fine), 0x21, 10); try testing.expectEqual(@as(u16, 0x21), card.card.chips[0].period(0)); try testing.expectEqual(@as(u16, 1), card.card.chips[1].period(0));
// Select both (both chip-select lines low) and write: it lands in both. playCS(&card, 0, 0, @intFromEnum(ay3.Register.b_fine), 0x33, 20); try testing.expectEqual(@as(u16, 0x33), card.card.chips[0].period(1)); try testing.expectEqual(@as(u16, 0x33), card.card.chips[1].period(1));
// The second 6522 owns the other two chips: select its first (chip 2) by // pulling that chip's select low and leaving the other's high. playCS(&card, 1, cs_second, @intFromEnum(ay3.Register.c_fine), 0x44, 30); try testing.expectEqual(@as(u16, 0x44), card.card.chips[2].period(2)); try testing.expectEqual(@as(u16, 1), card.card.chips[3].period(2));}
test "in Mockingboard mode each 6522 drives one chip, a stereo pair" { var card: Watched = .{}; // Default mode is Mockingboard. ready(&card, 0, 0); ready(&card, 1, 0); playCS(&card, 0, 0, @intFromEnum(ay3.Register.a_fine), 0x55, 10); playCS(&card, 1, 0, @intFromEnum(ay3.Register.a_fine), 0x66, 20); // The first 6522 drives chip 0 (channel B), the second drives chip 1 // (channel A); the extra two chips stay asleep. try testing.expectEqual(@as(u16, 0x55), card.card.chips[0].period(0)); try testing.expectEqual(@as(u16, 0x66), card.card.chips[1].period(0)); try testing.expectEqual(@as(u16, 1), card.card.chips[2].period(0)); try testing.expectEqual(@as(u16, 1), card.card.chips[3].period(0));}