// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The Ensoniq 5503 and the glue between it and the processor. //! //! An Apple IIgs makes its sound with a synthesiser chip that has thirty-two //! independent oscillators and sixty-four kilobytes of RAM of its own to keep //! waveforms in. The processor cannot reach either directly: it goes through //! four registers, and those four are what is here. //! //! - `$c03c` is the control register. Bit 7 is the chip's busy flag, bit 6 //! chooses whether the data register reaches the sound RAM or the chip's //! own registers, bit 5 turns on auto-incrementing, and the low four bits //! are the volume. //! - `$c03d` is the data register: one byte in or out of whichever of those //! two the control register selected, at wherever the pointer points. //! - `$c03e` and `$c03f` are that pointer, low byte and high. Reaching the //! chip's own registers uses only the low byte, there being 256 of them. //! //! Two details of the interface are worth having exactly, and both are in the //! manual rather than guessed at. Bit 6 set means the *RAM* and clear means the //! chip, which is the opposite way round from what the bit's name suggests and //! is stated twice. And **reading lags by one**: the data register hands back //! the byte from the *previous* read while fetching the one asked for now, so //! a program wanting ten bytes reads eleven times and throws the first away. //! An emulator without that returns everything shifted by one byte, which a //! memory test would report as every location being wrong. //! //! The oscillators are here too. Each is an address generator rather than a //! tone generator, which is the whole idea of the part: a 24-bit accumulator //! that a frequency is added to, some of whose bits become an address into the //! sound RAM, and the byte there is the signal. Thirty-two of them run at once //! and what comes out is their sum. const std = @import("std"); const wav = @import("wav.zig"); /// How fast the chip services its oscillators, one at a time: 894.886 kHz, a /// quarter of the machine's 3.58 MHz colour clock. Each oscillator is scanned /// at that divided by the number running plus two. pub const master_hz = 894_886; /// How many scans this will walk in one catching-up. A machine that has been /// left alone has no sound to catch up on, only silence, and walking every /// scan of an hour of it would take an hour. const catch_up_limit = 1 << 16; /// How many oscillators the chip has, and how many its Oscillator Enable /// register counts in: that register holds twice the number that are to run, /// so the two go together. pub const oscillators = 32; /// Where each oscillator's registers live. Thirty-two of each, one after /// another, and the number of the oscillator indexes into them. pub const Register = enum(u8) { frequency_low = 0x00, frequency_high = 0x20, volume = 0x40, data = 0x60, pointer = 0x80, control = 0xa0, size = 0xc0, _, /// Which of one oscillator's registers, and which oscillator. pub fn of(self: Register, which: u5) u8 { return @intFromEnum(self) + which; } }; /// The three the oscillators share. pub const interrupt_register = 0xe0; pub const enable_register = 0xe1; pub const converter_register = 0xe2; /// What an oscillator is doing, out of bits 2 and 1 of its control register. /// /// The manual's own words, since the difference between them is exactly what /// happens at the end of the wavetable: /// /// - free run: "begins at the beginning of the wavetable and repeats the /// wavetable. The oscillator will halt when the halt bit is set or when a /// zero is encountered in the table." /// - one shot: "stepping through it only once, and stopping at the end of /// the table." /// - sync: "when the even-numbered oscillator begins its wavetable, the /// odd-mate oscillator will synchronize and begin its wavetable /// simultaneously." /// - swap: "the enabled oscillator pair runs in one shot mode. When it /// reaches the end of its wavetable, it resets its accumulator to 0, sets /// its halt bit, and clears the halt bit of its mate." /// /// So a zero byte stops any of them, and running off the end of the table /// stops only the two that say so — the other two go round again, one of them /// dragging its mate back to the start with it. pub const Mode = enum(u2) { free_run = 0, one_shot = 1, sync = 2, swap = 3, }; /// Bits of an Oscillator Control register. The top four are the channel a /// demultiplexer would send this oscillator to, which this machine has none /// of and keeps anyway. pub const control_halt: u8 = 0x01; pub const control_mode: u8 = 0x06; pub const control_interrupt: u8 = 0x08; /// The top four bits of the same register: which of the chip's sixteen output /// channels this oscillator goes to. This machine has one speaker and sums /// them all, so nothing here reads it, but it is not decorative — Technical /// Note #19 says a stereo card decodes the low three bits of it, with even /// channels going to the right and odd to the left, and the convention is /// channel zero for right and channel one for left. pub const control_channel: u8 = 0xf0; /// Bits of the Oscillator Interrupt register at `$e0`. /// /// Bit 7 is the interrupt line, and the line is active low, so the bit reads /// **one when nothing has interrupted** and zero when something has. The /// Hardware Reference's Table 5-3 (Apple Computer, Inc., 1989a) gives it as /// "1: No oscillator has generated an interrupt. 0: One of the 32 DOC /// oscillators has generated an interrupt; this bit reflects the status of /// the IRQ line", and Apple's own specification for the chip says the same /// from the other side: "The OIR will force the IRQ line low indicating an /// interrupt, bit 7 will be set to a zero" (Apple Computer, Inc., 1986). /// /// This was the other way about for a long time, with bit 7 set meaning an /// interrupt had happened, and the machine's own interrupt manager at /// `$ff/b8f6` is what found it. It reads this register and takes `BMI` past /// the sound check when bit 7 is set; with an idle register reading `$00` /// every interrupt in the machine looked like a sound interrupt, was handed to /// the sound vector, and never got as far as the vertical blanking check /// below it — so GS/OS enabled vertical blanking and the ROM printed /// "Unclaimed Sound Interrupt" once a frame for ever. pub const interrupt_none: u8 = 0x80; /// Bits 6 and 0 of the same register "are always read back as 1's" (Apple /// Computer, Inc., 1986); the Hardware Reference has them as reserved. pub const interrupt_always_set: u8 = 0x41; /// Bits 5 to 1: which oscillator it was. The number sits there doubled, the /// same doubling the enable register counts in. pub const interrupt_oscillator: u8 = 0x3e; /// The sound chip and its glue. pub const Doc = struct { /// Sixty-four kilobytes of waveform storage, owned by whoever built this: /// it is too much to carry inside a struct that lives on a stack. ram: []u8, /// The chip's own registers. Thirty-two oscillators with six registers /// each, and three more shared between them — the oscillator interrupt and /// enable registers, and the analogue-to-digital converter. registers: [256]u8 = @splat(0), /// Where the next byte goes or comes from. Only the low byte is used when /// the chip's own registers are being reached. pointer: u16 = 0, /// Bit 6 of the control register: set for the sound RAM, clear for the /// chip's registers. ram_access: bool = false, /// Bit 5: whether the pointer moves on by itself after each access. auto_increment: bool = false, /// Bits 3 to 0: nothing here listens, but a program setting the volume can /// read back what it set. volume: u4 = 0, /// What the last read fetched, waiting to be handed over on the next one. /// This is the one-cycle lag, and it is the whole reason reads are odd. latch: u8 = 0, /// The oscillators that have interrupted and not yet been read, in the /// order they did it. The Oscillator Interrupt register can only name one, /// and Apple's specification says what the chip does with the rest: "if /// more than one oscillator is generating an interrupt, unprocessed /// interrupts will be put into an interrupt stack. After the processor /// reads the OIR, the DOC will clear the appropriate interrupt request and /// the next pending interrupt, if any, will be pulled off of the interrupt /// stack and put in the OIR" — served, despite the name, "in a first in /// first out order" (Apple Computer, Inc., 1986). The front of this is what /// the register reports. waiting: [oscillators]u5 = @splat(0), waiting_count: u6 = 0, /// The interrupt table: which oscillators finished a cycle while their own /// interrupt was disabled, one bit each. /// /// "If the IE bit is a zero, then when the oscillator completes its cycle /// the oscillator status will be passed to the an interrupt table, but /// will not be passed to the OIR. However if the IE bit is changed to a /// one then the interrupt will be sent to the OIR" (Ensoniq, 1986, p. 5). /// So a completion is not lost by nobody listening -- it is kept, and /// turning the bit on afterwards is what delivers it. /// /// A bitmask rather than a queue because the table has no order in it: it /// is a *table*, one place per oscillator, and an oscillator that finished /// twice while disabled has one thing to say. The order they reach the /// register in when several are released at once is the order the /// oscillators are numbered, which is the only order there is to take. table: u32 = 0, /// Each oscillator's phase accumulator: twenty-four bits, added to by the /// frequency once per scan, and some of whose bits are the address the /// oscillator is pointing at. Figure 5-7 says which bits. accumulators: [oscillators]u32 = @splat(0), /// Where the sum of every oscillator's output has got to since the last /// time anything asked for it, and how many times round the oscillators /// went into it. A caller wanting sound divides the one by the other; a /// caller wanting none can ignore both, and they cost a multiply and an /// add per oscillator scanned. mixed: i64 = 0, passes: u32 = 0, /// What was last handed out, held for anyone who asks again before the /// oscillators have been round once more. /// /// Not tidiness: with all thirty-two running the chip goes round them /// 26,320 times a second, which is slower than anything is likely to be /// asking, so most asks land between two passes. A converter holds its /// last level until it is given a new one, and answering nought instead /// would put a click in the sound at every one of them. held: i16 = 0, /// When the oscillators were last brought up to date, and the remainder /// of a scan left over from doing it. Keeping the remainder is what stops /// the sound drifting slowly out of tune against the machine's clock. stepped_at: u64 = 0, left_over: u64 = 0, /// What the control register reads. /// /// The busy flag is always clear. A real chip raises it while it is /// getting to a register between its own accesses to the sound RAM, and a /// program is told to loop until it clears; this one is never busy, so the /// loop goes round once. pub fn control(self: *const Doc) u8 { var value: u8 = self.volume; if (self.ram_access) value |= 0x40; if (self.auto_increment) value |= 0x20; return value; } pub fn setControl(self: *Doc, value: u8) void { self.ram_access = value & 0x40 != 0; self.auto_increment = value & 0x20 != 0; self.volume = @truncate(value); } /// Reads a byte, one behind. /// /// What comes back is what the *previous* read went and fetched; this read /// fetches the byte at the pointer and leaves it for the next one. The /// manual is explicit: to read ten bytes, read eleven times and discard the /// first. pub fn readData(self: *Doc) u8 { const handing_over = self.latch; self.latch = if (self.ram_access) self.ram[self.pointer] else self.readRegister(@truncate(self.pointer)); self.step(); return handing_over; } /// One of the chip's own registers, and the acknowledging of an interrupt. /// /// Reading the Oscillator Interrupt register is what clears it. The /// Hardware Reference (Apple Computer, Inc., 1989a) says how the register /// is set and never says how it is let go, and there is no clear register /// for the DOC as there is for the VGC. Apple's specification for the chip /// does say: "After the processor reads the OIR, the DOC will clear the /// appropriate interrupt request" (Apple Computer, Inc., 1986), and the /// machine's own interrupt manager relies on it. At `$ff/b8f6` it points /// the chip at `$e0`, reads the data register twice — the first for the /// lag and the second for the value — tests bit 7, and puts the pointer /// and the control register back without writing anything to the chip. If /// the read did not clear it, the line would never let go and the machine /// would spend the rest of its life in that handler. fn readRegister(self: *Doc, which: u8) u8 { if (which != interrupt_register) return self.registers[which]; const value = self.interruptRegister(); self.acknowledge(); return value; } /// What the Oscillator Interrupt register reads, without reading it: the /// oscillator at the front of the queue with bit 7 low, or bit 7 high and /// no oscillator when nothing is waiting. Bits 6 and 0 are set either way. pub fn interruptRegister(self: *const Doc) u8 { if (self.waiting_count == 0) return interrupt_none | interrupt_always_set; return interrupt_always_set | (@as(u8, self.waiting[0]) << 1); } /// Takes the front oscillator off the queue, which is what a read does. fn acknowledge(self: *Doc) void { if (self.waiting_count == 0) return; const rest = self.waiting_count - 1; std.mem.copyForwards(u5, self.waiting[0..rest], self.waiting[1..self.waiting_count]); self.waiting_count = rest; } /// Writes a byte, which does not lag: it goes where the pointer points and /// the pointer moves on. pub fn writeData(self: *Doc, value: u8) void { if (self.ram_access) { self.ram[self.pointer] = value; } else { const at: u8 = @truncate(self.pointer); self.registers[at] = value; // Enabling an oscillator's interrupt hands it whatever the // interrupt table has been keeping for it. The control registers // are the thirty-two from $a0, so this is which one was written // rather than a search. if (at >= @intFromEnum(Register.control) and at < @intFromEnum(Register.control) + oscillators) { self.release(@truncate(at - @intFromEnum(Register.control))); } } self.step(); } fn step(self: *Doc) void { if (self.auto_increment) self.pointer +%= 1; } pub fn pointerLow(self: *const Doc) u8 { return @truncate(self.pointer); } pub fn pointerHigh(self: *const Doc) u8 { return @truncate(self.pointer >> 8); } pub fn setPointerLow(self: *Doc, value: u8) void { self.pointer = (self.pointer & 0xff00) | value; } pub fn setPointerHigh(self: *Doc, value: u8) void { self.pointer = (@as(u16, value) << 8) | (self.pointer & 0x00ff); } /// One oscillator's register, and setting one. pub fn reg(self: *const Doc, which: Register, osc: u5) u8 { return self.registers[which.of(osc)]; } fn setReg(self: *Doc, which: Register, osc: u5, value: u8) void { self.registers[which.of(osc)] = value; } /// How many oscillators are running. /// /// The Oscillator Enable register holds twice the number wanted, and the /// manual is firm that at least one is always enabled — which is also what /// keeps the scan rate from dividing by nothing. pub fn running(self: *const Doc) u6 { const asked = self.registers[enable_register] >> 1; return @intCast(@max(1, @min(oscillators, asked))); } /// Where an oscillator is pointing, out of Figure 5-7. /// /// The final address is sixteen bits, and it is the wavetable pointer and /// the accumulator concatenated in a ratio that the table size decides: /// a 256-byte table takes all eight pointer bits and eight of the /// accumulator's, a 32K one takes a single pointer bit and fifteen. Which /// eight, or fifteen, is the address bus resolution: at seven they are the /// accumulator's top bits, `A23` down, and every step down the resolution /// takes them one bit lower, so the same frequency walks the table half as /// fast. The bottom of the run is `A(9 + resolution - size)`, which is /// where the figure's rows meet. pub fn addressOf(self: *const Doc, osc: u5) u16 { const layout = self.reg(.size, osc); const size: u3 = @truncate(layout >> 3); const resolution: u3 = @truncate(layout); const pointer = self.reg(.pointer, osc); const width: u4 = @as(u4, 8) + size; const shift: u5 = @as(u5, 9) + resolution - size; const from_accumulator: u16 = @truncate( (self.accumulators[osc] >> shift) & (@as(u32, 1) << width) - 1, ); const from_pointer: u16 = @as(u16, pointer >> size) << width; return from_pointer | from_accumulator; } /// Sets an oscillator going from the start of its wavetable, which is what /// a swap does to its mate and what an even oscillator in sync mode does /// to its odd one. fn start(self: *Doc, osc: u5) void { self.accumulators[osc] = 0; self.setReg(.control, osc, self.reg(.control, osc) & ~control_halt); } /// Says an oscillator has reached the end of its wavetable, if it was /// asked to say so. /// /// The condition is the end of the table and not the halting: "when an /// oscillator reaches the end of its wavetable and the enable interrupt /// bit for that oscillator has previously been set, the IRQ line and bit 7 /// of the Oscillator Interrupt register are then set, and the register /// number is placed in bits 1 through 5." /// /// That distinction is the whole of how the machine's own sound software /// keeps time. Technical Note #23 (Apple Computer, Inc., 1987-1990) /// describes the Note Synthesizer setting an oscillator free-running over /// the first page of the sound RAM at zero volume purely as a clock: "once /// it scans through the entire waveform buffer, the oscillator generates an /// interrupt". A free-running oscillator never halts, so an emulator that /// interrupted only on halting would leave every envelope in the machine /// frozen. /// /// The register can only name one oscillator, so the rest queue behind it /// in the order they arrived, and a read brings the next one forward. An /// oscillator already waiting is not queued a second time. /// /// And one whose interrupt is *disabled* is not simply dropped: it goes in /// the interrupt table instead, and enabling the bit afterwards delivers /// it. See `table`. fn reached(self: *Doc, osc: u5) void { if (self.reg(.control, osc) & control_interrupt == 0) { // Not delivered, but not lost either: it goes in the table and // waits for somebody to enable the interrupt. self.table |= @as(u32, 1) << osc; return; } self.queue(osc); } /// Puts an oscillator on the stack behind whatever is already there. /// /// "If more than one oscillator has generated an interrupt, the /// consecutive interrupts will be put on the interrupt stack to be /// processed in a first in first out order" (Ensoniq, 1986, p. 5). One /// already waiting is not queued a second time: the register can say one /// thing about one oscillator. fn queue(self: *Doc, osc: u5) void { for (self.waiting[0..self.waiting_count]) |already| if (already == osc) return; if (self.waiting_count >= self.waiting.len) return; self.waiting[self.waiting_count] = osc; self.waiting_count += 1; } /// Hands over whatever the table has been keeping for an oscillator whose /// interrupt has just been enabled. /// /// Called on every write to a control register rather than on a detected /// edge, because a write that leaves the bit set with something in the /// table is the same situation as one that sets it: the sentence is "if /// the IE bit is changed to a one then the interrupt will be sent", and /// the state it describes is the bit being one with a table entry behind /// it. fn release(self: *Doc, osc: u5) void { const bit = @as(u32, 1) << osc; if (self.table & bit == 0) return; if (self.reg(.control, osc) & control_interrupt == 0) return; self.table &= ~bit; self.queue(osc); } /// Halts an oscillator. /// /// One way to the end of the table is a zero byte: "unused portions within /// a wavetable should begin with a minimum of eight zeros. Otherwise, the /// oscillator will not halt when it encounters these bytes and will /// interpret them as data." fn halt(self: *Doc, osc: u5) void { self.setReg(.control, osc, self.reg(.control, osc) | control_halt); self.accumulators[osc] = 0; } /// Whether the chip is asking for the processor's attention. pub fn interrupting(self: *const Doc) bool { return self.waiting_count != 0; } /// What the end of the wavetable does, whether it was reached by stepping /// off the end or by reading a zero. fn finish(self: *Doc, osc: u5, mode: Mode) void { self.halt(osc); self.reached(osc); // "clears the halt bit of its mate" — the even and odd of a pair. if (mode == .swap) self.start(osc ^ 1); } /// One scan of one oscillator: add the frequency, look at what the /// accumulator now points at, and stop if that is the end of the table. fn scan(self: *Doc, osc: u5) void { const settings = self.reg(.control, osc); if (settings & control_halt != 0) return; const mode: Mode = @enumFromInt(@as(u2, @truncate(settings >> 1))); const frequency: u32 = @as(u32, self.reg(.frequency_low, osc)) | (@as(u32, self.reg(.frequency_high, osc)) << 8); // The wavetable fills the accumulator up to bit 17 plus the address // bus resolution — that is where Figure 5-7's address runs out — so // carrying past there is what "the end of the table" means. const span: u5 = 17 + @as(u5, @as(u3, @truncate(self.reg(.size, osc)))); const limit = @as(u32, 1) << span; const stepped = self.accumulators[osc] + frequency; self.accumulators[osc] = stepped & (limit - 1); if (stepped >= limit) switch (mode) { // Round again, and take the odd one back to the start with it. // Either way the end of the table has been reached, which is what // the interrupt is about. .free_run => self.reached(osc), .sync => { self.reached(osc); if (osc & 1 == 0) self.start(osc ^ 1); }, .one_shot, .swap => return self.finish(osc, mode), }; const sample = self.ram[self.addressOf(osc)]; self.setReg(.data, osc, sample); // A zero stops any of them. It is not a sample either: an oscillator // that has stopped puts out the zero-crossing level, not the most // negative one its byte could have meant. if (sample == 0) return self.finish(osc, mode); // A wavetable byte is unsigned with the zero crossing in the middle, // so the middle comes off before the volume is applied. self.mixed += (@as(i64, sample) - 128) * @as(i64, self.reg(.volume, osc)); } /// One time round every running oscillator, lowest first. /// /// The order is not a detail. It is the whole of why a swap from an odd /// oscillator to its even mate loses a sample and a swap the other way does /// not: an even oscillator woken by its mate has already been passed over /// this time round and does not play until the next. Technical Note #11 /// (Apple Computer, Inc., 1987-1990) describes exactly that, as an anomaly /// of the real part, and here it falls out of scanning in the right order /// rather than being arranged. fn onePass(self: *Doc) void { const count = self.running(); var i: u6 = 0; while (i < count) : (i += 1) self.scan(@intCast(i)); self.passes +|= 1; } /// Brings the oscillators up to date. /// /// The chip services one oscillator at a time, round and round however /// many are running, at 894.886 kHz — so each of them is scanned at that /// rate divided by the number running plus two, which is the scan rate the /// manual's frequency formula divides by. `per_second` is how many of the /// machine's cycles make a second, since that is the only thing here that /// knows. pub fn advance(self: *Doc, cycles: u64, per_second: u64) void { // No dividing to get a whole number of cycles per scan: at 2.8 MHz // with eight oscillators running that is 31.29, and calling it 31 // plays the machine about one per cent sharp, which is a sixth of a // semitone and audible. The division is done once, against the scan // rate, and its remainder is kept in the same units — so what is // carried over is good however many oscillators are running next // time. const gap = @min(cycles -| self.stepped_at, per_second); self.stepped_at = cycles; const slots: u64 = @as(u64, self.running()) + 2; const per_scan = per_second * slots; if (per_scan == 0) return; const elapsed = gap * master_hz + self.left_over; var scans = elapsed / per_scan; self.left_over = elapsed % per_scan; // A machine left alone for a long time has no sound to catch up on, // only silence, and walking every scan of it would take as long as the // silence did. if (scans > catch_up_limit) scans = catch_up_limit; while (scans > 0) : (scans -= 1) self.onePass(); } /// What the oscillators have come to since this was last asked, and /// nothing said twice: asking clears what was gathered. /// /// One time round all of them is what the chip puts out in one sample /// period, so this is the average of the passes that have gone by, shared /// out among the oscillators that were running. An oscillator that was not /// scanned — halted, or waiting for its turn to come round again after a /// swap — contributes nothing to the pass it missed, and that silence is /// the point rather than an omission. /// /// Sharing it out is the one liberty taken. The real machine sums its /// channels in analogue at a fixed gain, so a program using two /// oscillators is quieter than one using thirty; dividing by how many are /// enabled instead keeps a two-voice program audible, at the cost of being /// approximate when that number changes mid-window. pub fn take(self: *Doc) i16 { if (self.passes == 0) return self.held; const per_pass = @divTrunc(self.mixed, @as(i64, self.passes)); const average = @divTrunc(per_pass, @as(i64, self.running())); self.mixed = 0; self.passes = 0; self.held = @intCast(std.math.clamp(average, -32768, 32767)); return self.held; } /// What the reset line does. The sound RAM keeps what it held, as RAM /// does; the registers and the pointer do not. pub fn reset(self: *Doc) void { self.registers = @splat(0); self.pointer = 0; self.ram_access = false; self.auto_increment = false; self.volume = 0; self.latch = 0; self.waiting_count = 0; self.accumulators = @splat(0); self.mixed = 0; self.passes = 0; self.held = 0; self.left_over = 0; } }; /// The chip written down as it plays, since neither front end has a speaker. /// /// The awkward part of recording this chip is that its own rate moves. It /// services one oscillator at a time at 894.886 kHz, so how often any of them /// is looked at depends on how many are enabled: with all thirty-two running /// it goes round them 26,320 times a second, and with eight it is 89,489. A /// file has one rate and cannot move, so the two have to be reconciled, and /// this reconciles them in the direction that is always right — it winds the /// oscillators forward to each sample's own moment and then asks what they /// came to. /// /// That makes the asking the filter as well. `Doc.take` averages every time /// the chip went round its oscillators since it was last asked, so going from /// the faster rate to the slower one is a box average over exactly the right /// window rather than a value plucked out of the middle of it; and going from /// the slower rate to the faster one holds the last level, which is what the /// converter does anyway. /// /// Because the sample's moment is worked out from the machine's 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. pub const Recorder = struct { /// 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 recording holds. cycles_per_second: u64, rate: u64, /// 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 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. /// /// Kept rather than returned because the pumping happens deep inside the /// machine, on a path that has nowhere to put an error and no business /// stopping the emulator over one. Whoever owns the file looks at this /// 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; } /// Writes every sample whose moment has now passed, and winds the /// oscillators forward to it on the way. /// /// 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 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); 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; fn withRam(ram: []u8) Doc { @memset(ram, 0); return .{ .ram = ram }; } test "the control register says which of the two the data register reaches" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); // Bit 6 set is the RAM, and clear is the chip — the opposite way round // from what the name suggests, and stated twice in the manual. doc.setControl(0x60); // RAM, auto-incrementing try testing.expect(doc.ram_access); doc.setControl(0x20); // the chip's own registers try testing.expect(!doc.ram_access); // The volume reads back, and so does everything else that is writable. doc.setControl(0x6a); try testing.expectEqual(@as(u8, 0x6a), doc.control()); // And the busy flag is never set, so a program looping until it clears // goes round once. try testing.expectEqual(@as(u8, 0x00), doc.control() & 0x80); } test "reading the sound RAM lags by one byte" { // The manual's own example: to read ten bytes, read eleven times and throw // the first away. Without this every byte comes back shifted by one, which // a memory test reports as every location being wrong — and which would // look like a broken model of working RAM. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); for (0..10) |i| ram[0x1000 + i] = @intCast(0xa0 + i); doc.setControl(0x60); // the RAM, auto-incrementing doc.setPointerLow(0x00); doc.setPointerHigh(0x10); _ = doc.readData(); // the one that is thrown away for (0..10) |i| { try testing.expectEqual(@as(u8, @intCast(0xa0 + i)), doc.readData()); } } test "writing does not lag, and the pointer moves on" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.setControl(0x60); doc.setPointerHigh(0x20); doc.setPointerLow(0x00); for ([_]u8{ 1, 2, 3, 4 }) |b| doc.writeData(b); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, ram[0x2000..0x2004]); try testing.expectEqual(@as(u16, 0x2004), doc.pointer); // And with auto-incrementing off it stays put. doc.setControl(0x40); doc.setPointerHigh(0x30); doc.setPointerLow(0x00); doc.writeData(0x11); doc.writeData(0x22); try testing.expectEqual(@as(u8, 0x22), ram[0x3000]); try testing.expectEqual(@as(u16, 0x3000), doc.pointer); } test "the chip's own registers are reached with the low byte alone" { // There are 256 of them, so the high byte of the pointer has nothing to // say and the manual says the chip ignores it. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.setControl(0x20); // the chip, auto-incrementing doc.setPointerHigh(0xff); // ignored doc.setPointerLow(0xa0); // the first oscillator's control register doc.writeData(0x5a); try testing.expectEqual(@as(u8, 0x5a), doc.registers[0xa0]); // Nothing was written to the RAM at $ffa0. try testing.expectEqual(@as(u8, 0x00), ram[0xffa0]); } test "a whole pass over the sound RAM comes back byte for byte" { // Which is what the machine's self-test does: sixty-five thousand five // hundred accesses to the data register, a byte at a time. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.setControl(0x60); doc.setPointerLow(0); doc.setPointerHigh(0); for (0..0x10000) |i| doc.writeData(@truncate(i *% 7)); doc.setPointerLow(0); doc.setPointerHigh(0); _ = doc.readData(); for (0..0x10000 - 1) |i| { try testing.expectEqual(@as(u8, @truncate(i *% 7)), doc.readData()); } } test "an oscillator points where Figure 5-7 says it does" { // The figure is a table of five rows, one per wavetable size, each showing // how the sixteen address lines are shared between the wavetable pointer // and the accumulator, and how the address bus resolution slides the // accumulator's share up and down. These are its corners, read off it. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.accumulators[0] = 0xab_cdef; const size_shift = 3; // A 256-byte table: all eight pointer bits, and eight of the // accumulator's. At resolution 7 those are its top eight, A23 to A16. doc.registers[Register.pointer.of(0)] = 0x34; doc.registers[Register.size.of(0)] = (0 << size_shift) | 7; try testing.expectEqual(@as(u16, 0x34ab), doc.addressOf(0)); // At resolution 0 they are A16 to A9, which is the same table walked at a // hundred and twenty-eight times the frequency for the same pitch. doc.registers[Register.size.of(0)] = (0 << size_shift) | 0; try testing.expectEqual(@as(u16, 0x34e6), doc.addressOf(0)); // A 32K table: one pointer bit, P7, and fifteen of the accumulator's. doc.registers[Register.pointer.of(0)] = 0xc0; doc.registers[Register.size.of(0)] = (7 << size_shift) | 7; try testing.expectEqual(@as(u16, 0xd5e6), doc.addressOf(0)); doc.registers[Register.size.of(0)] = (7 << size_shift) | 0; try testing.expectEqual(@as(u16, 0xf37b), doc.addressOf(0)); // And a row from the middle of the figure, to catch anything that only // works at the ends: 2K, so five pointer bits and eleven of the other. doc.registers[Register.pointer.of(0)] = 0x5a; doc.registers[Register.size.of(0)] = (3 << size_shift) | 4; try testing.expectEqual(@as(u16, 0x5af3), doc.addressOf(0)); } /// Sets oscillator `osc` playing `table` at `at`, one byte per scan. /// /// A 256-byte table at address bus resolution 0 takes the accumulator's bits /// A16 to A9, so adding 512 to the accumulator moves the address on by one and /// the wavetable is walked a byte at a time — which is what a test wants to /// watch. fn playing(doc: *Doc, osc: u5, at: u16, mode: Mode, table: []const u8) void { @memcpy(doc.ram[at..][0..table.len], table); doc.registers[Register.pointer.of(osc)] = @truncate(at >> 8); doc.registers[Register.size.of(osc)] = 0; // 256 bytes, resolution 0 doc.registers[Register.frequency_low.of(osc)] = 0x00; doc.registers[Register.frequency_high.of(osc)] = 0x02; // 512 doc.registers[Register.volume.of(osc)] = 0xff; doc.registers[Register.control.of(osc)] = @as(u8, @intFromEnum(mode)) << 1; } test "an oscillator walks its wavetable and stops at a zero" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 1 << 1; // one oscillator running // The frequency is added before the byte is read, so the first scan reads // the second byte of the table rather than the first. playing(&doc, 0, 0x1000, .free_run, &.{ 0x11, 0x22, 0x33, 0x44, 0x00, 0x66 }); for ([_]u8{ 0x22, 0x33, 0x44 }) |expected| { doc.onePass(); try testing.expectEqual(expected, doc.reg(.data, 0)); try testing.expectEqual(@as(u8, 0), doc.reg(.control, 0) & control_halt); } // The zero halts it, and the accumulator goes back to the start. doc.onePass(); try testing.expectEqual(@as(u8, control_halt), doc.reg(.control, 0) & control_halt); try testing.expectEqual(@as(u32, 0), doc.accumulators[0]); // And a halted oscillator stays halted and reads nothing more, so the // byte after the zero is never heard. doc.onePass(); try testing.expectEqual(@as(u8, 0x00), doc.reg(.data, 0)); } test "free run goes round the table and one shot does not" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 2 << 1; // A table with no zero in it, so the only end is the end of the table. var table: [256]u8 = @splat(0x40); playing(&doc, 0, 0x1000, .free_run, &table); playing(&doc, 1, 0x2000, .one_shot, &table); // Round the table once and one byte over. for (0..257) |_| doc.onePass(); // The free-running one came round the end and is a byte past the start, // still going; the one shot stopped at the end of the table, as the // manual says. try testing.expectEqual(@as(u8, 0), doc.reg(.control, 0) & control_halt); try testing.expectEqual(@as(u16, 0x1001), doc.addressOf(0)); try testing.expectEqual(@as(u8, control_halt), doc.reg(.control, 1) & control_halt); } test "an oscillator can be told to interrupt when it stops" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 4 << 1; playing(&doc, 3, 0x1000, .one_shot, &.{ 0x11, 0x00 }); doc.registers[Register.control.of(3)] |= control_interrupt; try testing.expect(!doc.interrupting()); doc.onePass(); try testing.expect(doc.interrupting()); // Bit 7 low for the line, the oscillator's number doubled in bits 5 to 1 // — the same units the enable register counts in — and bits 6 and 0 set. try testing.expectEqual( @as(u8, interrupt_always_set | (3 << 1)), doc.interruptRegister(), ); // And one that was not asked to interrupt does not. _ = doc.readRegister(interrupt_register); playing(&doc, 2, 0x2000, .one_shot, &.{ 0x11, 0x00 }); doc.onePass(); try testing.expect(!doc.interrupting()); } test "the interrupt register reads idle with bit 7 set, which is what the ROM tests" { // Table 5-3 of the Hardware Reference (Apple Computer, Inc., 1989a): "1: // No oscillator has generated an interrupt", and bits 6 and 0 "are always // read back as 1's" (Apple Computer, Inc., 1986). The machine's interrupt // manager at $ff/b8f6 reads this and takes BMI past the sound check when // the bit is set; a chip that read $00 while idle made every interrupt in // the machine a sound interrupt. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); try testing.expectEqual(@as(u8, 0xc1), doc.interruptRegister()); doc.setControl(0x00); doc.setPointerLow(interrupt_register); _ = doc.readData(); // the lag try testing.expectEqual(@as(u8, 0xc1), doc.readData()); try testing.expect(!doc.interrupting()); } test "a second oscillator interrupting waits its turn behind the first" { // "If more than one oscillator is generating an interrupt, unprocessed // interrupts will be put into an interrupt stack. After the processor // reads the OIR, the DOC will clear the appropriate interrupt request and // the next pending interrupt, if any, will be pulled off of the interrupt // stack and put in the OIR" — first in, first out (Apple Computer, Inc., // 1986). var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 6 << 1; playing(&doc, 2, 0x1000, .one_shot, &.{ 0x11, 0x00 }); playing(&doc, 5, 0x2000, .one_shot, &.{ 0x11, 0x00 }); doc.registers[Register.control.of(2)] |= control_interrupt; doc.registers[Register.control.of(5)] |= control_interrupt; doc.onePass(); try testing.expect(doc.interrupting()); // Two arrived in one scan, lowest first. Each read hands over one and // brings the next forward, and the line stays down until both are gone. try testing.expectEqual(@as(u8, interrupt_always_set | (2 << 1)), doc.readRegister(interrupt_register)); try testing.expect(doc.interrupting()); try testing.expectEqual(@as(u8, interrupt_always_set | (5 << 1)), doc.readRegister(interrupt_register)); try testing.expect(!doc.interrupting()); try testing.expectEqual(@as(u8, 0xc1), doc.readRegister(interrupt_register)); } test "a swap from an odd oscillator to its even mate loses a sample" { // Technical Note #11, "Ensoniq DOC Swap-Mode Anomaly" (Apple Computer, // Inc., 1987-1990): the output "falls to the zero-crossing level (silence) // whenever a swap occurs from a higher-numbered oscillator to a // lower-numbered one; this anomaly does not occur during swaps from // lower-numbered oscillators to higher-numbered ones", and lasts no longer // than a single sample period. // // Nothing here arranges that. It falls out of the chip scanning its // oscillators in order, lowest first: an even oscillator woken by its mate // has already been passed over this time round, and an odd one woken by // its mate has not. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 2 << 1; // Two samples each, then the zero that ends the table. The frequency is // added before the byte is read, so the first byte of each is stepped // over. playing(&doc, 0, 0x1000, .swap, &.{ 0x40, 0x40, 0x40, 0x00 }); playing(&doc, 1, 0x2000, .swap, &.{ 0x40, 0x40, 0x40, 0x00 }); doc.registers[Register.control.of(1)] |= control_halt; // the even one starts // The even oscillator plays its two. for (0..2) |_| { doc.onePass(); try testing.expect(doc.take() != 0); } // Low to high: oscillator 0 reads its zero and wakes oscillator 1, which // comes after it in the scan and so plays in this very pass. No gap. doc.onePass(); try testing.expectEqual(@as(u8, control_halt), doc.reg(.control, 0) & control_halt); try testing.expectEqual(@as(u8, 0), doc.reg(.control, 1) & control_halt); try testing.expect(doc.take() != 0); // The odd oscillator plays its second. doc.onePass(); try testing.expect(doc.take() != 0); // High to low: oscillator 1 reads its zero and wakes oscillator 0 — which // was scanned first this pass, while it was still halted. Nothing played // at all: the zero-crossing level, for exactly one sample period. doc.onePass(); try testing.expectEqual(@as(u8, 0), doc.reg(.control, 0) & control_halt); try testing.expectEqual(@as(u8, control_halt), doc.reg(.control, 1) & control_halt); try testing.expectEqual(@as(i16, 0), doc.take()); // And it is over by the next pass, which is what "lasts no longer than a // single sample period" means. doc.onePass(); try testing.expect(doc.take() != 0); } test "the enable register counts in twos and never reaches nothing" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); try testing.expectEqual(@as(u6, 1), doc.running()); doc.registers[enable_register] = 8 << 1; try testing.expectEqual(@as(u6, 8), doc.running()); // The manual is firm that at least one is always enabled, and it is also // what keeps the scan rate from dividing by nothing. doc.registers[enable_register] = 0; try testing.expectEqual(@as(u6, 1), doc.running()); doc.registers[enable_register] = 0xff; try testing.expectEqual(@as(u6, oscillators), doc.running()); } test "the oscillators keep pace with the machine's clock" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); // Eight oscillators running are scanned at 894.886 kHz over eight plus // two, which is 89.4886 kHz each. A second of a 2.8 MHz machine, caught up // a frame at a time as the machine does it, should come to that many // passes — and to within a tenth of a per cent, since a whole per cent is // already a sixth of a semitone out. doc.registers[enable_register] = 8 << 1; var table: [256]u8 = @splat(0x40); playing(&doc, 0, 0x1000, .free_run, &table); const per_second: u64 = 2_800_000; const expected = master_hz / 10; var at: u64 = 0; while (at < per_second) : (at += per_second / 60) doc.advance(at, per_second); doc.advance(per_second, per_second); try testing.expect(doc.passes > expected * 999 / 1000); try testing.expect(doc.passes < expected * 1001 / 1000); // And a hundred cycles at a time comes to the same, because the remainder // is kept: without it every step would round down and the chip would run // slowly flat. _ = doc.take(); doc.stepped_at = 0; doc.left_over = 0; at = 0; while (at < per_second) : (at += 100) doc.advance(at, per_second); doc.advance(per_second, per_second); try testing.expect(doc.passes > expected * 999 / 1000); try testing.expect(doc.passes < expected * 1001 / 1000); } test "a free-running oscillator interrupts without ever halting" { // Which is how the machine keeps musical time. Technical Note #23 (Apple // Computer, Inc., 1987-1990): the Note Synthesizer sets an oscillator // free-running over the first page of the sound RAM at zero volume purely // as a clock, and "once it scans through the entire waveform buffer, the // oscillator generates an interrupt". Interrupting only on a halt would // freeze every envelope in the machine. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 1 << 1; // A whole page with no zero anywhere in it, so nothing can halt. var table: [256]u8 = @splat(0x80); playing(&doc, 0, 0x0000, .free_run, &table); doc.registers[Register.control.of(0)] |= control_interrupt; doc.registers[Register.volume.of(0)] = 0; // a timer, not a voice // Round the page once. It comes back to the beginning, still running, and // has said so. for (0..256) |_| doc.onePass(); try testing.expectEqual(@as(u8, 0), doc.reg(.control, 0) & control_halt); try testing.expect(doc.interrupting()); try testing.expectEqual( @as(u8, interrupt_always_set | (0 << 1)), doc.interruptRegister(), ); // And it keeps time: acknowledged, it comes round again. _ = doc.readRegister(interrupt_register); for (0..255) |_| doc.onePass(); try testing.expect(!doc.interrupting()); doc.onePass(); try testing.expect(doc.interrupting()); } test "reading the interrupt register is what acknowledges it" { // There is no clear register for the DOC, and the machine's own handler at // $ffb8f6 points the chip at $e0, reads the data register twice — once for // the lag and once for the value — tests bit 7 and writes nothing back. So // the read has to be what lets the line go. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.registers[enable_register] = 1 << 1; playing(&doc, 5, 0x1000, .one_shot, &.{ 0x40, 0x00 }); doc.registers[Register.control.of(5)] |= control_interrupt; doc.registers[enable_register] = 6 << 1; doc.onePass(); try testing.expect(doc.interrupting()); // The handler's own sequence: point at $e0 with the registers selected and // no auto-incrementing, then read twice. doc.setControl(0x00); doc.setPointerLow(interrupt_register); _ = doc.readData(); // the lag const answer = doc.readData(); try testing.expectEqual(@as(u8, interrupt_always_set | (5 << 1)), answer); try testing.expect(!doc.interrupting()); } test "a wavetable played and sampled comes out at the pitch it was asked for" { // The whole chain the recording uses, end to end: a waveform in the sound // RAM, an oscillator walking it, the machine's clock winding the chip // forward, and one sample taken per moment the file wants one. What comes // out should be a tone of the frequency the manual's formula says. var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); // One cycle of a sine over a 256-byte table, kept well away from zero so // that nothing in it can be mistaken for the end of the table. var table: [256]u8 = undefined; for (&table, 0..) |*byte, i| { const turn = 2.0 * std.math.pi * @as(f64, @floatFromInt(i)) / 256.0; byte.* = @intFromFloat(128.0 + 100.0 * @sin(turn)); } doc.registers[enable_register] = 1 << 1; // one oscillator, so a scan is a pass playing(&doc, 0, 0x1000, .free_run, &table); // 256 bytes at resolution 0 is 512 of accumulator to the byte, so the // table takes 256 * 512 / frequency passes to go round once. const frequency = 193; doc.registers[Register.frequency_low.of(0)] = frequency & 0xff; doc.registers[Register.frequency_high.of(0)] = frequency >> 8; // Which comes to 439 Hz and a bit: the chip services one oscillator at // 894886/(1 + 2) passes a second, and a cycle of the table is 131072/193 // of them. const passes_per_second = @as(f64, master_hz) / 3.0; const expected = passes_per_second / (131072.0 / @as(f64, frequency)); const per_second: u64 = 2_800_000; const rate: u64 = 44_100; // A whole second of it. Counting whole cycles is the measurement, so the // length of the window is the precision: a tenth of a second can only tell // the frequency to about two per cent, which is not enough to catch // anything worth catching. const wanted = rate; var samples: [44_100]i16 = undefined; for (&samples, 1..) |*sample, n| { doc.advance(n * per_second / rate, per_second); sample.* = doc.take(); } // It is a tone: it swings both ways and reaches most of the amplitude the // table has at full volume. var loudest: i16 = 0; for (samples) |sample| loudest = @max(loudest, @as(i16, @intCast(@abs(sample)))); try testing.expect(loudest > 20_000); // And it is the right tone. Counting the upward zero crossings over a // known stretch of time is the frequency, and nothing in the middle of the // chain can be wrong without moving it. var crossings: usize = 0; for (samples[1..], 0..) |sample, i| { if (samples[i] <= 0 and sample > 0) crossings += 1; } const measured = @as(f64, @floatFromInt(crossings)) / (@as(f64, @floatFromInt(wanted)) / @as(f64, @floatFromInt(rate))); try testing.expect(measured > expected * 0.99); try testing.expect(measured < expected * 1.01); } test "a recording's samples are placed by the machine's clock" { // The nth sample's moment is worked out from n rather than by adding an // interval to the last one, which is what keeps a long recording from // drifting against the machine it is a recording of. var recorder: Recorder = .{ .file = undefined, // not touched: this is the arithmetic, not the file .cycles_per_second = 2_800_000, .rate = 44_100, .started = 1_000, }; try testing.expectEqual(@as(u64, 1_000), recorder.cycleOf(0)); try testing.expectEqual(@as(u64, 1_000 + 63), recorder.cycleOf(1)); // A second in is a second's worth of cycles in, exactly, however many // samples that took. try testing.expectEqual(@as(u64, 1_000 + 2_800_000), recorder.cycleOf(44_100)); // And there is no accumulated rounding: the millionth sample is where the // ratio says it is and not sixty thousand cycles adrift. try testing.expectEqual( @as(u64, 1_000 + 1_000_000 * 2_800_000 / 44_100), recorder.cycleOf(1_000_000), ); } test "an oscillator that finishes with its interrupt off is remembered, not lost" { // "If the IE bit is a zero, then when the oscillator completes its cycle // the oscillator status will be passed to the an interrupt table, but will // not be passed to the OIR. However if the IE bit is changed to a one then // the interrupt will be sent to the OIR" (Ensoniq, 1986, p. 5). var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); // Oscillator 3 finishes with nobody listening. Nothing is waiting, so the // register still says so -- but it has not been thrown away. doc.reached(3); try testing.expectEqual(@as(u6, 0), doc.waiting_count); try testing.expect(doc.interruptRegister() & interrupt_none != 0); try testing.expect(doc.table & (1 << 3) != 0); // Enabling it afterwards is what delivers it, and the register names the // oscillator that had finished rather than nothing. doc.setPointerLow(Register.control.of(3)); doc.setPointerHigh(0); doc.writeData(control_interrupt); try testing.expectEqual(@as(u6, 1), doc.waiting_count); try testing.expectEqual(@as(u8, 3), (doc.interruptRegister() >> 1) & 0x1f); try testing.expect(doc.interruptRegister() & interrupt_none == 0); // And the table has let go of it, so enabling it again says nothing new. try testing.expectEqual(@as(u32, 0), doc.table); } test "the table keeps one thing per oscillator, and several come out in order" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); // Two finish with their interrupts off, and one of them twice: a table has // one place per oscillator, so finishing twice is one thing to say. doc.reached(5); doc.reached(2); doc.reached(5); try testing.expectEqual(@as(u6, 0), doc.waiting_count); // Released one at a time, each arriving when its own bit is set. There is // no order in a table, so what decides theirs is the order they are // enabled in. doc.setPointerHigh(0); doc.setPointerLow(Register.control.of(5)); doc.writeData(control_interrupt); doc.setPointerLow(Register.control.of(2)); doc.writeData(control_interrupt); try testing.expectEqual(@as(u6, 2), doc.waiting_count); // First in, first out, which is what the specification says of the stack. try testing.expectEqual(@as(u8, 5), (doc.interruptRegister() >> 1) & 0x1f); _ = doc.readRegister(interrupt_register); try testing.expectEqual(@as(u8, 2), (doc.interruptRegister() >> 1) & 0x1f); _ = doc.readRegister(interrupt_register); try testing.expect(doc.interruptRegister() & interrupt_none != 0); } test "writing a control register with the interrupt already off keeps the table" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); doc.reached(7); try testing.expect(doc.table & (1 << 7) != 0); // A write that leaves the bit clear is not the sentence's "changed to a // one", so nothing is delivered and nothing is forgotten: the oscillator // is still owed an interrupt whenever somebody enables it. doc.setPointerHigh(0); doc.setPointerLow(Register.control.of(7)); doc.writeData(0x00); try testing.expectEqual(@as(u6, 0), doc.waiting_count); try testing.expect(doc.table & (1 << 7) != 0); doc.writeData(control_interrupt); try testing.expectEqual(@as(u6, 1), doc.waiting_count); } test "an oscillator whose interrupt is on goes straight to the register" { var ram: [0x10000]u8 = undefined; var doc = withRam(&ram); // The ordinary path, which the table must not have changed: with the bit // already set a completion is delivered and the table stays empty. doc.registers[Register.control.of(1)] |= control_interrupt; doc.reached(1); try testing.expectEqual(@as(u6, 1), doc.waiting_count); try testing.expectEqual(@as(u32, 0), doc.table); try testing.expectEqual(@as(u8, 1), (doc.interruptRegister() >> 1) & 0x1f); }