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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The SSI 263A phonetic speech synthesizer, the chip on the Mockingboard C,//! the Phasor, the Cricket and the Echo+.//!//! It makes speech by running a glottal (pitched) or noise source through five//! cascaded low-pass filter sections — a model of the vocal tract — and it is//! told what to say through five eight-bit registers: which of sixty-four//! phonemes, how long, how high, how loud, and how fast. When a phoneme is//! done the chip drops its `A/R` line to ask for the next, which on a//! Mockingboard is wired to the 6522's CA1 so the "send me the next phoneme"//! shows up as an interrupt; a program can also poll it, since a read hands//! back the inverted `A/R` in bit seven.//!//! What is faithful here is that interface: the register formats, the phoneme//! and frame timing, and the `A/R` handshake, all from the data sheet (Silicon//! Systems, n.d., the *Register Input Formats* table and the *Operation//! Description*). What is **not** faithful is the voice, because the data sheet//! does not publish the phoneme-to-formant table inside the chip; the voice a//! caller makes from this state is an approximation, kept apart from the//! digital model here so that the part that can be exact is not muddled with//! the part that cannot.//!//! The clock is the machine's own: on a Mockingboard the chip's XCK pin is the//! buffered Ø0 (about 1.02 MHz) with DIV2 tied low, so one of the chip's clock//! cycles is one of the processor's and the timing below is counted in the//! machine's cycles directly (Arnold, 2010).
const std = @import("std");
/// The five attribute registers, addressed by RS2–RS0. The chip decodes only/// these; RS2 high is the filter register whatever RS1 and RS0 are.pub const Register = enum(u3) { duration_phoneme = 0, inflection = 1, rate_inflection = 2, control = 3, filter = 4, _,};
/// The sixty-four phonemes, by the hex code written into the phoneme field,/// with the example word the data sheet gives for each. Kept for reading a/// stream of phonemes back as something legible, and for the voice to look up/// what a code is meant to sound like.pub const phonemes = [64][]const u8{ "PA", "E", "E1", "Y", "YI", "AY", "IE", "I", // 00-07 "A", "AI", "EH", "EH1", "AE", "AE1", "AH", "AH1", // 08-0F "AW", "O", "OU", "OO", "IU", "IU1", "U", "U1", // 10-17 "UH", "UH1", "UH2", "UH3", "ER", "R", "R1", "R2", // 18-1F "L", "L1", "LF", "W", "B", "D", "KV", "P", // 20-27 "T", "K", "HV", "HVC", "HF", "HFC", "HN", "Z", // 28-2F "S", "J", "SCH", "V", "F", "THV", "TH", "M", // 30-37 "N", "NG", ":A", ":OH", ":U", ":UH", "E2", "LB", // 38-3F};
/// A phonetic frame at the chip's slowest rate — 4096 clock cycles times the/// sixteen the rate register can subtract from. Everything the chip times is a/// multiple of this: `frameCycles` and `phonemeCycles` below.////// Frame duration (seconds) = 4096 × (16 − R) / XCK, from the data sheet, and/// XCK is the machine clock here, so the figure is in machine cycles as it/// stands.pub const frame_unit = 4096;
pub const Chip = struct { // The five registers, decoded into their fields. The bit layout is the // data sheet's Register Input Formats table. /// The phoneme, 0–63, indexing `phonemes`. phoneme: u6 = 0, /// The two duration bits, DR1 (high) and DR0 (low). A shorter phoneme is a /// larger value: the phoneme lasts the frame times four less this. duration: u2 = 0, /// The twelve-bit inflection (pitch), split oddly across two registers. inflection: u12 = 0, /// The four-bit speech rate. A larger value is a shorter frame. rate: u4 = 0, /// The three-bit articulation rate — how fast the formants move to a new /// phoneme. Not part of the timing; kept for the voice. articulation: u3 = 0, /// The four-bit amplitude. amplitude: u4 = 0, /// The eight-bit filter frequency. filter: u8 = 0,
/// The control bit. High is a standby/power-down that keeps the registers /// but stops the voice and the `A/R` line; the machine starts it speaking /// by clearing it, and reset and power-up leave it set. control: bool = true,
/// Whether the `A/R` line is low, which is the chip asking for the next /// phoneme — it drops here when a phoneme finishes, and a write of the /// phoneme register raises it again while the new one is produced. The /// interrupt to the 6522 is the high-to-low edge; a read reports the /// inverse in bit seven. requesting: bool = false,
/// The machine cycle the chip has been brought up to date to, and the /// cycle the phoneme now being produced will finish on. Producing while /// `finish_at` is ahead of `now`. now: u64 = 0, finish_at: u64 = 0, producing: bool = false,
/// Puts the chip back the way power-up and the PD/RST pin leave it: the /// control bit set (standby), the voice and the request line quiet, the /// registers as they were. A cold chip has them zeroed by the field /// defaults; this is the warm reset the slot's RES line gives. pub fn reset(self: *Chip) void { self.control = true; self.producing = false; self.requesting = false; }
/// How long a frame lasts at the current rate, in machine cycles. pub fn frameCycles(self: *const Chip) u64 { return frame_unit * (@as(u64, 16) - self.rate); }
/// How long the current phoneme lasts, in machine cycles: a frame times /// four less the duration bits. pub fn phonemeCycles(self: *const Chip) u64 { return self.frameCycles() * (@as(u64, 4) - self.duration); }
/// Writes an attribute register, decoding it into the fields above. A /// write of the phoneme register while the chip is running starts the new /// phoneme: the request line goes back up and the phoneme's own duration is /// timed out from now. pub fn write(self: *Chip, register: Register, value: u8, cycle: u64) void { self.catchUp(cycle); switch (register) { .duration_phoneme => { self.duration = @truncate(value >> 6); self.phoneme = @truncate(value & 0x3f); // A new phoneme is acknowledged and begins, unless the chip is // in standby, in which case it is only loaded. if (!self.control) self.begin(); }, .inflection => { // D7–D0 hold I10–I3. self.inflection = (self.inflection & ~@as(u12, 0x7f8)) | (@as(u12, value) << 3); }, .rate_inflection => { // D7–D4 rate; D3 is I11; D2–D0 are I2–I0. self.rate = @truncate(value >> 4); self.inflection = (self.inflection & 0x7f8) | (@as(u12, value & 0x07)) | (@as(u12, (value >> 3) & 1) << 11); }, .control => { const was = self.control; self.control = value & 0x80 != 0; self.articulation = @truncate(value >> 4); self.amplitude = @truncate(value & 0x0f); // Clearing the control bit is what sets the chip going in the // mode the duration bits chose; a fresh phoneme starts. if (was and !self.control) self.begin(); // Into standby: the voice and the request line stop. if (!was and self.control) { self.producing = false; self.requesting = false; } }, .filter => self.filter = value, _ => {}, } }
/// A register read. The chip drives only bit seven, as the inverse of the /// `A/R` line: a one there is the chip asking for the next phoneme, which /// is the poll a program does instead of taking the interrupt. The rest of /// the byte is the chip's not to drive, and is left to the caller. pub fn read(self: *Chip, cycle: u64) u8 { self.catchUp(cycle); return if (self.requesting) 0x80 else 0x00; }
/// Whether the chip is pulling its `A/R` line low, which the card wires to /// the 6522's CA1. Brings the timing up to date first. pub fn asking(self: *Chip, cycle: u64) bool { self.catchUp(cycle); return self.requesting; }
/// Begins the loaded phoneme: the request is answered, the line goes high, /// and the phoneme is timed to finish a duration from now. fn begin(self: *Chip) void { self.producing = true; self.requesting = false; self.finish_at = self.now + self.phonemeCycles(); }
/// Brings the chip up to the given cycle, dropping the request line when a /// phoneme finishes. fn catchUp(self: *Chip, cycle: u64) void { if (cycle > self.now) self.now = cycle; if (self.producing and self.now >= self.finish_at) { self.producing = false; self.requesting = true; } }};
/// A phoneme's rough sound: whether it is voiced (a pitched glottal source) or/// unvoiced (noise), and the two formant frequencies that place it. These are/// **not** from the data sheet — the chip's own phoneme-to-formant table was/// never published — but standard English formant values assigned to each/// phoneme by the class its example word puts it in. It is what makes the voice/// an approximation: speech-shaped, not the SSI's own voice.const Formant = struct { f1: f32, f2: f32, voiced: bool = true, silent: bool = false };
fn formantOf(phoneme: u6) Formant { return switch (phoneme) { 0x00 => .{ .f1 = 0, .f2 = 0, .silent = true }, // PA, a pause // The front and mid vowels, high F2. 0x01, 0x02, 0x3e => .{ .f1 = 270, .f2 = 2300 }, // E, E1, E2 — "meet" 0x03, 0x04, 0x06, 0x07 => .{ .f1 = 390, .f2 = 2000 }, // Y, YI, IE, I — "six" 0x05, 0x09 => .{ .f1 = 500, .f2 = 1900 }, // AY, AI — "please", "care" 0x08, 0x0c, 0x0d => .{ .f1 = 660, .f2 = 1700 }, // A, AE, AE1 — "made", "dad" 0x0a, 0x0b => .{ .f1 = 530, .f2 = 1840 }, // EH, EH1 — "belt" // The back and low vowels, low F2. 0x0e, 0x0f, 0x10, 0x11 => .{ .f1 = 730, .f2 = 1090 }, // AH, AW, O — "got", "store" 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 => .{ .f1 = 300, .f2 = 870 }, // OU, OO, IU, U — "look", "you" 0x18, 0x19, 0x1a, 0x1b => .{ .f1 = 640, .f2 = 1190 }, // UH — "wonder" 0x3a, 0x3b, 0x3c, 0x3d => .{ .f1 = 620, .f2 = 1200 }, // the accented :A :OH :U :UH // R and L, the liquids: low, close formants. 0x1c, 0x1d, 0x1e, 0x1f => .{ .f1 = 490, .f2 = 1350 }, // ER, R — "bird" 0x20, 0x21, 0x22, 0x3f => .{ .f1 = 360, .f2 = 1300 }, // L, LF, LB — "play" 0x23 => .{ .f1 = 300, .f2 = 610 }, // W — "water" // Voiced consonants: low formants, still pitched. 0x24, 0x25, 0x26 => .{ .f1 = 300, .f2 = 1200 }, // B, D, KV 0x2f => .{ .f1 = 300, .f2 = 1400 }, // Z — "zero" 0x31 => .{ .f1 = 300, .f2 = 1800 }, // J — "measure" 0x33, 0x35 => .{ .f1 = 300, .f2 = 1100 }, // V, THV 0x37, 0x38, 0x39 => .{ .f1 = 300, .f2 = 1000 }, // M, N, NG — nasals 0x2a, 0x2b, 0x2e => .{ .f1 = 500, .f2 = 1500 }, // HV, HVC, HN // Unvoiced consonants: noise through the formants. 0x27, 0x28, 0x29 => .{ .f1 = 500, .f2 = 1700, .voiced = false }, // P, T, K 0x30, 0x32 => .{ .f1 = 400, .f2 = 4000, .voiced = false }, // S, SCH — "same", "ship" 0x34, 0x36 => .{ .f1 = 400, .f2 = 2400, .voiced = false }, // F, TH 0x2c, 0x2d => .{ .f1 = 500, .f2 = 1500, .voiced = false }, // HF, HFC };}
/// A two-pole resonator, the formant filter of the little synthesizer below: a/// pole pair on a circle of radius `r`, which rings at `freq`. The nearer `r`/// is to one the narrower and louder the ring, and `1 - r` on the input keeps/// the gain in bounds.const Resonator = struct { y1: f32 = 0, y2: f32 = 0,
fn run(self: *Resonator, x: f32, freq: f32, rate: f32) f32 { const r = 0.97; const theta = 2.0 * std.math.pi * freq / rate; const y = x * (1.0 - r) + 2.0 * r * @cos(theta) * self.y1 - r * r * self.y2; self.y2 = self.y1; self.y1 = y; return y; }};
/// The SSI's voice, an approximation.////// **Nothing here is from the data sheet.** The chip synthesizes speech from a/// phoneme-to-formant table in its own ROM that was never published, so this/// cannot be the chip's voice; what it is is a small formant synthesizer —/// a glottal buzz or a hiss, at the pitch and amplitude the chip was told,/// through two resonators placed by `formantOf` — which comes out speech-shaped/// and legible as an attempt at the phoneme rather than as the SSI itself. The/// digital model above is exact; this is the honest best that can be done for/// the sound without the table.pub const Voice = struct { phase: f32 = 0, noise: u32 = 0x1234_5678, formants: [2]Resonator = .{ .{}, .{} }, sample_rate: f32, /// The chip's clock, for turning the inflection register into a pitch. xck: f32,
pub fn init(sample_rate: f32, xck: f32) Voice { return .{ .sample_rate = sample_rate, .xck = xck }; }
/// One sample of the voice, given the chip's current state. Zero unless the /// chip is producing a phoneme; the resonators are still run so a note does /// not click off. pub fn sample(self: *Voice, chip: *const Chip) f32 { const shape = formantOf(chip.phoneme); const amplitude = @as(f32, @floatFromInt(chip.amplitude)) / 15.0; const on = chip.producing and !shape.silent;
// The excitation: a sawtooth glottal buzz at the inflection pitch for a // voiced phoneme, white noise for an unvoiced one. var excitation: f32 = 0; if (on) { if (shape.voiced) { // Inflection frequency = XCK / (8 * (4096 - I)), the data // sheet's formula, clamped to a speaking range. const denom = 8.0 * @as(f32, @floatFromInt(4096 - @as(u32, chip.inflection))); const pitch = std.math.clamp(self.xck / denom, 60.0, 400.0); self.phase += pitch / self.sample_rate; if (self.phase >= 1.0) self.phase -= 1.0; excitation = 2.0 * self.phase - 1.0; // a sawtooth, rich in harmonics } else { self.noise = self.noise *% 1664525 +% 1013904223; excitation = @as(f32, @floatFromInt(self.noise >> 9)) / 8_388_608.0 - 1.0; } }
const out = self.formants[0].run(excitation, shape.f1, self.sample_rate) + 0.7 * self.formants[1].run(excitation, shape.f2, self.sample_rate); return out * amplitude * 0.6; }};
const testing = std.testing;
test "the register formats decode the way the data sheet lays them out" { var chip: Chip = .{}; // Duration/Phoneme: DR1 DR0 in the top two bits, phoneme in the low six. chip.write(.duration_phoneme, 0b11_101010, 0); try testing.expectEqual(@as(u2, 0b11), chip.duration); try testing.expectEqual(@as(u6, 0b101010), chip.phoneme);
// Rate/Inflection: rate in the top nibble, I11 in bit 3, I2–I0 in bits 2–0. chip.write(.rate_inflection, 0b1010_1_101, 0); try testing.expectEqual(@as(u4, 0b1010), chip.rate); // Inflection so far: I11 = 1, I2–I0 = 101. try testing.expectEqual(@as(u12, (1 << 11) | 0b101), chip.inflection);
// Inflection register fills I10–I3 without disturbing the rest. chip.write(.inflection, 0xff, 0); try testing.expectEqual(@as(u12, (1 << 11) | (0xff << 3) | 0b101), chip.inflection);
// Control/Articulation/Amplitude. chip.write(.control, 0b1_011_1001, 0); try testing.expect(chip.control); try testing.expectEqual(@as(u3, 0b011), chip.articulation); try testing.expectEqual(@as(u4, 0b1001), chip.amplitude);
chip.write(.filter, 0xc0, 0); try testing.expectEqual(@as(u8, 0xc0), chip.filter);}
test "a phoneme lasts a frame times four less the duration bits" { var chip: Chip = .{}; // Rate 10 leaves 16 - 10 = 6 frame units; duration 0 leaves 4 - 0 = 4. chip.rate = 10; chip.duration = 0; try testing.expectEqual(@as(u64, frame_unit * 6), chip.frameCycles()); try testing.expectEqual(@as(u64, frame_unit * 6 * 4), chip.phonemeCycles());
// A larger duration value is a shorter phoneme. chip.duration = 3; try testing.expectEqual(@as(u64, frame_unit * 6 * 1), chip.phonemeCycles());}
test "A/R drops when a phoneme finishes and a write raises it again" { var chip: Chip = .{}; // Out of standby. chip.write(.control, 0x00, 0); // A short phoneme: rate 15 (one frame unit), duration 3 (times one). chip.write(.rate_inflection, 0xf0, 0); chip.write(.duration_phoneme, 0xc0, 0); // DR = 3, phoneme 0 const length = chip.phonemeCycles(); try testing.expect(length > 0);
// While producing, it is not asking, and bit seven reads back zero. try testing.expect(!chip.asking(length - 1)); try testing.expectEqual(@as(u8, 0x00), chip.read(length - 1));
// Once the phoneme is done it asks for the next: A/R low, bit seven set. try testing.expect(chip.asking(length)); try testing.expectEqual(@as(u8, 0x80), chip.read(length + 100));
// Writing the next phoneme answers the request and starts producing again. chip.write(.duration_phoneme, 0x01, length + 100); try testing.expect(!chip.asking(length + 100));}
test "standby and reset quiet the voice and the request line" { var chip: Chip = .{}; chip.write(.control, 0x00, 0); // running chip.write(.duration_phoneme, 0x00, 0); try testing.expect(chip.producing);
// The control bit going high is standby: nothing produced, nothing asked. chip.write(.control, 0x80, 10); try testing.expect(!chip.producing); try testing.expect(!chip.asking(1_000_000));
// And a reset leaves it in standby with the control bit set. chip.write(.control, 0x00, 0); chip.write(.duration_phoneme, 0x00, 0); chip.reset(); try testing.expect(chip.control); try testing.expect(!chip.producing); try testing.expect(!chip.asking(1_000_000));}
test "every phoneme code has a name" { try testing.expectEqual(@as(usize, 64), phonemes.len); try testing.expectEqualStrings("PA", phonemes[0x00]); try testing.expectEqualStrings("ER", phonemes[0x1c]); try testing.expectEqualStrings("LB", phonemes[0x3f]);}
test "the voice is silent until a phoneme is producing, and every phoneme has a shape" { var chip: Chip = .{}; var voice: Voice = .init(44_100, 1_020_500);
// In standby the voice is silent however many samples are asked for. for (0..1000) |_| try testing.expectEqual(@as(f32, 0), voice.sample(&chip));
// Producing a voiced vowel at full amplitude puts real energy out: not // every sample is zero over a pitch period. chip.write(.control, 0x0f, 0); // out of standby, amplitude 15 chip.write(.rate_inflection, 0x00, 0); chip.write(.duration_phoneme, 0x08, 0); // phoneme "A", a voiced vowel var energy: f32 = 0; for (0..2000) |_| { const s = voice.sample(&chip); energy += s * s; } try testing.expect(energy > 0);
// A pause makes no sound of its own: a fresh voice producing PA stays // silent (a voice that was mid-vowel would ring down rather than click). var quiet: Voice = .init(44_100, 1_020_500); chip.write(.duration_phoneme, 0x00, 0); // PA var pause_energy: f32 = 0; for (0..2000) |_| { const s = quiet.sample(&chip); pause_energy += s * s; } try testing.expectEqual(@as(f32, 0), pause_energy);
// Every phoneme code resolves to a formant shape without tripping. for (0..64) |p| { const shape = formantOf(@intCast(p)); if (!shape.silent) try testing.expect(shape.f1 > 0 and shape.f2 > 0); }}
test "a higher inflection makes a higher pitch" { // The pitch is read off the glottal phase wrapping: count how often the // sawtooth resets over a fixed run, which is the frequency. const cycles = struct { fn count(inflection: u12) usize { var chip: Chip = .{ .control = false, .producing = true, .amplitude = 15, .phoneme = 0x08, .inflection = inflection }; var voice: Voice = .init(44_100, 1_020_500); var last: f32 = 0; var wraps: usize = 0; for (0..8820) |_| { // a fifth of a second _ = voice.sample(&chip); if (voice.phase < last) wraps += 1; last = voice.phase; } return wraps; } }; // A larger inflection is a higher target frequency, so more wraps of the // glottal phase over the same run. try testing.expect(cycles.count(3000) > cycles.count(1000));}