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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! The AY-3-8910, which is the chip that makes the noise on a Mockingboard.//!//! Three square waves, a noise source and one envelope between them, driven by//! sixteen registers and nothing else. Unlike the Apple's own speaker, which//! has no volume and no waveform and must be told when to move, this is told//! what to play and plays it until it is told otherwise: a program writes a//! period and a level and goes away.//!//! Everything counts down from the chip's clock. The tone and noise counters//! tick at a sixteenth of it and the envelope at a two hundred and fifty sixth,//! so a tone comes out at clock over sixteen times its period, which is why the//! periods are the numbers they are in a tune.
const std = @import("std");const testing = std.testing;
/// A Mockingboard runs its chips at the machine's own rate.pub const cycles_per_second = 1_020_500;
/// What the counters tick at.////// The chip's own numbers are that a tone comes out at the clock over sixteen/// times its period, that the noise does the same, and that the envelope runs/// at the clock over two hundred and fifty six times its period. A tone is a/// square, so it turns over twice in each of its periods, while the noise/// shifts once: the two can only both be the clock over sixteen if the tone/// counters tick twice as often as the noise counter does. So the tick/// everything is counted in is the clock over eight, the noise takes every/// second one, and the envelope every thirty-second.pub const tick_divisor = 8;pub const noise_ticks = 2;pub const envelope_ticks = 32;
pub const channels = 3;
/// Which register is which.pub const Register = enum(u4) { a_fine = 0, a_coarse = 1, b_fine = 2, b_coarse = 3, c_fine = 4, c_coarse = 5, noise_period = 6, mixer = 7, a_level = 8, b_level = 9, c_level = 10, envelope_fine = 11, envelope_coarse = 12, envelope_shape = 13, port_a = 14, port_b = 15,};
/// The mixer register turns a channel's tone and noise on by holding its bit/// low, which is the other way round from everything else on the chip.pub const mixer_tone_off = 0x01;pub const mixer_noise_off = 0x08;
/// A level of sixteen means the envelope decides it rather than the register.pub const level_envelope = 0x10;
/// The sixteen steps of the volume control, which are not evenly spaced: each/// is about two decibels above the one below, so that the ear hears them as/// even. These are the measured ratios rather than a formula, since the ladder/// on the chip is a ladder of resistors and not a calculation.pub const levels = [16]f32{ 0.0000, 0.0137, 0.0205, 0.0291, 0.0423, 0.0618, 0.0847, 0.1369, 0.1691, 0.2647, 0.3527, 0.4499, 0.5704, 0.6873, 0.8482, 1.0000,};
/// What the envelope does when it reaches the end of a run: the four bits are/// hold, alternate, attack and continue, and between them they make the eight/// shapes that are worth having out of the sixteen that can be written.pub const envelope_hold = 0x01;pub const envelope_alternate = 0x02;pub const envelope_attack = 0x04;pub const envelope_continue = 0x08;
pub const Chip = struct { registers: [16]u8 = @splat(0),
/// Where each tone counter has got to, and which way its square is. counter: [channels]u16 = @splat(0), high: [channels]bool = @splat(false),
/// The noise counter, and the shift register that makes the noise. The /// chip uses seventeen bits with taps at the third and the last, which is /// what makes it hiss rather than repeat audibly. noise_counter: u16 = 0, noise_shift: u17 = 1,
/// Where the slower counters have got to within a tick. prescale: u8 = 0,
/// The envelope: where its counter has got to, which of the thirty-two /// steps it is on, and whether it has stopped. envelope_counter: u16 = 0, envelope_step: u5 = 0, envelope_holding: bool = false,
pub fn reset(self: *Chip) void { self.* = .{}; }
/// The period a channel is counting, which is twelve bits across two /// registers. A period of nought behaves as one: the counter is reloaded /// with it and a nought would never count down. pub fn period(self: *const Chip, channel: u2) u16 { const at: usize = @as(usize, channel) * 2; const value = @as(u16, self.registers[at]) | @as(u16, self.registers[at + 1] & 0x0f) << 8; return @max(1, value); }
pub fn noisePeriod(self: *const Chip) u16 { return @max(1, self.registers[@intFromEnum(Register.noise_period)] & 0x1f); }
pub fn envelopePeriod(self: *const Chip) u16 { const value = @as(u16, self.registers[@intFromEnum(Register.envelope_fine)]) | @as(u16, self.registers[@intFromEnum(Register.envelope_coarse)]) << 8; return @max(1, value); }
pub fn write(self: *Chip, register: u4, value: u8) void { self.registers[register] = value; // Writing the shape starts the envelope again, whatever was written, // which is how a program retriggers a note. if (register == @intFromEnum(Register.envelope_shape)) { self.envelope_step = 0; self.envelope_counter = 0; self.envelope_holding = false; } }
pub fn read(self: *const Chip, register: u4) u8 { return self.registers[register]; }
/// One tick, which is an eighth of the chip's clock. The tone counters /// move on every one of them, the noise on every second and the envelope /// on every thirty-second, which is what makes their three frequencies /// come out as the chip's own numbers say they should. pub fn step(self: *Chip) void { self.prescale +%= 1; for (0..channels) |i| { const channel: u2 = @intCast(i); if (self.counter[i] > 0) { self.counter[i] -= 1; continue; } self.counter[i] = self.period(channel) - 1; self.high[i] = !self.high[i]; }
if (self.prescale % noise_ticks == 0) self.stepNoise(); if (self.prescale % envelope_ticks == 0) self.stepEnvelope(); }
fn stepNoise(self: *Chip) void { if (self.noise_counter > 0) { self.noise_counter -= 1; } else { self.noise_counter = self.noisePeriod() - 1; // The taps that make it noise rather than a tune: bit nought and // bit three, fed back into the top. const bit: u1 = @truncate((self.noise_shift ^ (self.noise_shift >> 3)) & 1); self.noise_shift = @as(u17, bit) << 16 | self.noise_shift >> 1; } }
fn stepEnvelope(self: *Chip) void { if (self.envelope_holding) return; self.envelope_counter += 1; if (self.envelope_counter < self.envelopePeriod()) return; self.envelope_counter = 0;
if (self.envelope_step < 31) { self.envelope_step += 1; return; } // The end of a run. What happens next is the four bits: carry on, and // if so whether to hold where it stopped and whether to turn round. const shape = self.registers[@intFromEnum(Register.envelope_shape)]; if (shape & envelope_continue == 0) { self.envelope_holding = true; self.envelope_step = 31; return; } if (shape & envelope_hold != 0) { self.envelope_holding = true; // Alternating and holding stops at the end it started from. if (shape & envelope_alternate != 0) self.envelope_step = 0; return; } self.envelope_step = 0; }
/// Where the envelope is now, as one of the sixteen levels. pub fn envelopeLevel(self: *const Chip) u4 { const shape = self.registers[@intFromEnum(Register.envelope_shape)]; const attack = shape & envelope_attack != 0; // Half way through, an alternating envelope turns round. const turned = shape & envelope_continue != 0 and shape & envelope_alternate != 0 and self.envelope_step >= 16 and !self.envelope_holding; const rising = if (turned) !attack else attack;
var reached: u5 = self.envelope_step; if (shape & envelope_continue != 0 and shape & envelope_alternate != 0) reached %= 16; const within: u4 = @truncate(@min(reached, 15)); return if (rising) within else 15 - within; }
/// Whether a channel is being let through. /// /// A channel carries whichever of its tone and its noise the mixer has /// switched on, and both of them are switched on by holding a bit low. A /// channel with both switched off is not silent: it sits at whatever its /// level says, which is what a program playing a recording through one of /// these relies on. It switches everything off and writes the sample into /// the level register, and the ladder of resistors is the converter. pub fn open(self: *const Chip, channel: u2) bool { const mixer = self.registers[@intFromEnum(Register.mixer)]; const shift: u3 = channel; const tone_on = mixer & (@as(u8, mixer_tone_off) << shift) == 0; const noise_on = mixer & (@as(u8, mixer_noise_off) << shift) == 0; const tone = self.high[channel] or !tone_on; const noise = (self.noise_shift & 1) != 0 or !noise_on; return tone and noise; }
/// A channel's level now, which is the register's or the envelope's. pub fn channelLevel(self: *const Chip, channel: u2) f32 { if (!self.open(channel)) return 0; const register = self.registers[@intFromEnum(Register.a_level) + @as(usize, channel)]; const which: u4 = if (register & level_envelope != 0) self.envelopeLevel() else @truncate(register & 0x0f); return levels[which]; }
/// The three channels together, which is what one chip puts out. They are /// summed rather than averaged, as three voices on one wire are, and the /// result is divided by three so that a chip at full tilt comes to one. pub fn level(self: *const Chip) f32 { var sum: f32 = 0; for (0..channels) |i| sum += self.channelLevel(@intCast(i)); return sum / @as(f32, channels); }};
/// How many ticks it takes a channel to turn its square over, counted rather/// than worked out, so that the counting is what is being checked.fn ticksBetweenTurns(chip: *Chip, channel: u2, ticks: usize) usize { var turns: usize = 0; var was = chip.high[channel]; for (0..ticks) |_| { chip.step(); if (chip.high[channel] != was) turns += 1; was = chip.high[channel]; } return turns;}
test "a tone comes out at the frequency its period asks for" { var chip: Chip = .{}; // A period of a hundred, which at a sixteenth of a megahertz or so is // about 638 hertz: the counter turns the square over every hundred ticks. chip.write(@intFromEnum(Register.a_fine), 100); chip.write(@intFromEnum(Register.a_coarse), 0); const ticks = 100_000; const turns = ticksBetweenTurns(&chip, 0, ticks); try testing.expectEqual(@as(usize, ticks / 100), turns);
// Twice the period is half the frequency, which is the whole of how a // tune is written for one of these. var slower: Chip = .{}; slower.write(@intFromEnum(Register.a_fine), 200); try testing.expectEqual(@as(usize, ticks / 200), ticksBetweenTurns(&slower, 0, ticks));
// The period is twelve bits, so the coarse register is the top four. var lowest: Chip = .{}; lowest.write(@intFromEnum(Register.a_fine), 0x00); lowest.write(@intFromEnum(Register.a_coarse), 0x0f); try testing.expectEqual(@as(u16, 0x0f00), lowest.period(0));
// And a period of nought is a period of one: the counter would never // count down otherwise. var fastest: Chip = .{}; fastest.write(@intFromEnum(Register.a_fine), 0); try testing.expectEqual(@as(u16, 1), fastest.period(0));}
test "the mixer decides what a channel carries" { var chip: Chip = .{}; chip.write(@intFromEnum(Register.a_level), 15); // Every bit set is both the tone and the noise switched off, which is not // silence: the channel sits at its level, which is what a program playing // a recording writes samples into. chip.write(@intFromEnum(Register.mixer), 0xff); for (0..100) |_| { chip.step(); try testing.expectEqual(levels[15], chip.channelLevel(0)); } // Silence is the level, not the mixer. chip.write(@intFromEnum(Register.a_level), 0); try testing.expectEqual(@as(f32, 0), chip.channelLevel(0)); chip.write(@intFromEnum(Register.a_level), 15);
// The tone let through, and nothing else: the level follows the square, // so over a run of ticks it is sometimes loud and sometimes nothing. chip.write(@intFromEnum(Register.mixer), 0xff & ~@as(u8, mixer_tone_off)); chip.write(@intFromEnum(Register.a_fine), 4); var loud: usize = 0; var quiet: usize = 0; for (0..1000) |_| { chip.step(); if (chip.channelLevel(0) > 0) loud += 1 else quiet += 1; } try testing.expect(loud > 100 and quiet > 100);
// The other two channels are their own: switching one on leaves the rest. try testing.expectEqual(@as(f32, 0), chip.channelLevel(1)); try testing.expectEqual(@as(f32, 0), chip.channelLevel(2));}
test "the levels are the ladder the chip has, not a straight line" { // Sixteen of them, rising, the top one being everything and the bottom // nothing, and each about two decibels above the one below rather than a // sixteenth more. try testing.expectEqual(@as(f32, 0), levels[0]); try testing.expectEqual(@as(f32, 1), levels[15]); for (1..16) |i| try testing.expect(levels[i] > levels[i - 1]); // Half way up the numbers is nowhere near half the loudness. try testing.expect(levels[8] < 0.25);}
test "an envelope runs, and stops or repeats as its shape says" { var chip: Chip = .{}; chip.write(@intFromEnum(Register.a_level), level_envelope); chip.write(@intFromEnum(Register.mixer), 0xff & ~@as(u8, mixer_tone_off)); // A period of one, so the envelope moves a step every thirty-two ticks. chip.write(@intFromEnum(Register.envelope_fine), 1); chip.write(@intFromEnum(Register.envelope_coarse), 0);
// Decay: down from the top and then silence, which is the one every // twanged note uses. chip.write(@intFromEnum(Register.envelope_shape), 0x00); try testing.expectEqual(@as(u4, 15), chip.envelopeLevel()); for (0..envelope_ticks * 8) |_| chip.step(); try testing.expect(chip.envelopeLevel() < 15); for (0..envelope_ticks * 40) |_| chip.step(); try testing.expectEqual(@as(u4, 0), chip.envelopeLevel()); try testing.expect(chip.envelope_holding);
// Attack and hold: up from nothing and stay there. chip.write(@intFromEnum(Register.envelope_shape), envelope_continue | envelope_attack | envelope_hold); try testing.expectEqual(@as(u4, 0), chip.envelopeLevel()); for (0..envelope_ticks * 40) |_| chip.step(); try testing.expectEqual(@as(u4, 15), chip.envelopeLevel()); try testing.expect(chip.envelope_holding);
// Attack and continue: up from nothing, over and over. chip.write(@intFromEnum(Register.envelope_shape), envelope_continue | envelope_attack); for (0..envelope_ticks * 40) |_| chip.step(); try testing.expect(!chip.envelope_holding);
// And writing the shape again starts it from the beginning, which is how // a note is struck again. chip.write(@intFromEnum(Register.envelope_shape), envelope_continue | envelope_attack); try testing.expectEqual(@as(u4, 0), chip.envelopeLevel());}
test "the noise is noise rather than a tune" { var chip: Chip = .{}; chip.write(@intFromEnum(Register.a_level), 15); chip.write(@intFromEnum(Register.mixer), 0xff & ~@as(u8, mixer_noise_off)); chip.write(@intFromEnum(Register.noise_period), 1);
// Both values come up, and the run is not a short one repeating: the // shift register is seventeen bits, so it takes 131,071 ticks to come // round, which is two seconds of hiss. var high: usize = 0; var runs: usize = 0; var was = chip.noise_shift & 1; for (0..20_000) |_| { chip.step(); const now = chip.noise_shift & 1; if (now == 1) high += 1; if (now != was) runs += 1; was = now; } try testing.expect(high > 5_000 and high < 15_000); try testing.expect(runs > 1_000);}
test "a period is the number the chip's own formula asks for" { // The data sheet's arithmetic (General Instrument, n.d.), which is what // every tune written for one of these assumes: the frequency is the clock // over sixteen times the period. A square turns over twice in a period, and // the counters tick at an eighth of the clock, so that is what turning over // every `period` ticks comes to. const period = 254; var chip: Chip = .{}; chip.write(@intFromEnum(Register.a_fine), period & 0xff); chip.write(@intFromEnum(Register.a_coarse), period >> 8);
const ticks = 254_000; const turns = ticksBetweenTurns(&chip, 0, ticks); try testing.expectEqual(@as(usize, ticks / period), turns);
const seconds = @as(f64, ticks) * tick_divisor / @as(f64, cycles_per_second); const hertz = @as(f64, @floatFromInt(turns)) / 2.0 / seconds; const wanted = @as(f64, cycles_per_second) / (16.0 * period); try testing.expect(@abs(hertz - wanted) < 1.0); // Which for this period on a Mockingboard is a bit above middle C. try testing.expect(hertz > 250 and hertz < 255);}