diff --git a/README.md b/README.md index 63229f2..93b392c 100644 --- a/README.md +++ b/README.md @@ -170,11 +170,22 @@ then want hardware that is not there. | 341-0445-A, with memory expansion | 32768 | `48318d174d7df008c12efe7a26e9c83147499141933b8041d94639fb767466c1` | | 341-0445-B, the last of them | 32768 | `8ad5e6c4ed15d09b62183965b6c04762610d4b26510afc1896bdb4ecc55da883` | +Nothing else needs a ROM. The block device in slot 7, the clock card, the +mouse card and the Mockingboard all answer with firmware written for this +project, which is possible because what each of those cards has to do is +published and none of it is Apple's code. + +``` +zig65 --rom APPLE2E.ROM --disk-rom 341-0027-a.p5 --disk1 game.dsk +zig build -Dmachine=iic -Dprocessor=65C02 && zig65 --rom "Apple IIc ROM FF - 342-0272-A.bin" --disk1 game.dsk +zig build gs -- "Apple IIGS ROM 01 - 342-0077-B.bin" --hard-disk system.2mg +``` + #### The Apple IIgs ROMs -Nothing loads these yet — `src/cpu16/` is a processor and there is no machine -to put it in — but identifying them turned out to be the first real piece of -work in that direction, and the answer is not what you would guess. +`gs` loads one of these and boots it, and `zig build bootgs` runs the same ROM +without a screen to see how far it gets. Which one you have matters more than +it should, though, because identifying a IIgs ROM is not what you would guess. A IIgs system ROM covers the top banks of the address space: two of them for the 128K ROM 00 and ROM 01, four for a 256K ROM 3. **The banks are not always @@ -194,7 +205,9 @@ at fixed addresses will not turn up together by accident. Whichever end of the image has them is bank `$ff`, and the rest run in order from there. `iigsrom.identify` does that, and is checked against all fifteen IIgs images to -hand — including the swapped pairs and the 256K ones. +hand — including the swapped pairs and the 256K ones. So `gs` takes whichever +of them you have and works out the arrangement itself; there is no switch for +it and nothing to get wrong. | what it is | bytes | order in the file | sha256 | | --- | --- | --- | --- | @@ -205,16 +218,6 @@ hand — including the swapped pairs and the 256K ones. | **ROM 3, 341-0728.** Its other half, banks `$fc` and `$fd`. No firmware in it, so the test above does not apply and `identify` refuses it — correctly: it is half a ROM. | 131072 | `$fc` then `$fd` | `b327c945a15a11b4a54ca1fb30f5974dc10f6322e280579e1cce51f775cfa588` | | **ROM 4, the Mark Twain.** The machine Apple did not ship, and a whole 256K in one file. | 262144 | `$fc` up to `$ff` | `565d8ca073e5c46367ca56d4b12827020e76e6a0bf6c2300da0989161aa34ad9` | -Nothing else needs a ROM. The block device in slot 7, the clock card, the -mouse card and the Mockingboard all answer with firmware written for this -project, which is possible because what each of those cards has to do is -published and none of it is Apple's code. - -``` -zig65 --rom APPLE2E.ROM --disk-rom 341-0027-a.p5 --disk1 game.dsk -zig build -Dmachine=iic -Dprocessor=65C02 && zig65 --rom "Apple IIc ROM FF - 342-0272-A.bin" --disk1 game.dsk -``` - ### Writing the machine down A machine that gets used often is a long line of switches, and most of them do @@ -1221,11 +1224,12 @@ machine around them is not. block device above in slot 7 answering ProDOS and SmartPort both. Every IIgs ROM to hand boots it: ROM 00 and ROM 01, both ROM 3 dumps, the ROM 4 out of a Mark Twain, the 1986 beta, the Alpha ROM and a prototype. -- **What a IIgs has not got.** The Ensoniq's thirty-two oscillators are four - registers and nothing behind them: the interface is exact and the synthesis - is not written, so the chip remembers a waveform and never plays it. Memory - stops at 256K, so the banks a card would add answer as nothing. There is no - SCC, no AppleTalk and no memory expansion. +- **What a IIgs has not got.** The Ensoniq's thirty-two oscillators run — they + walk their wavetables, halt and swap and interrupt as the chip does — but + nothing carries what they add up to out of the machine, so the sound is + worked out and never heard. Memory stops at 256K, so the banks a card would + add answer as nothing. There is no SCC, no AppleTalk and no memory + expansion. ## Building @@ -1820,9 +1824,47 @@ eleven times and throws the first away. Without that every byte comes back shifted by one, which a memory test reports as every location being wrong: a correct model of working RAM would look like broken RAM. -The chip's registers are storage and behave as storage. What an oscillator -would *do* with a frequency written to it is synthesis, and that is not -modelled: nothing here makes a sound. +Behind those registers the oscillators run. 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 are an address +into the sound RAM, and the byte there is the signal. *Which* bits is Figure +5-7's business — the wavetable size decides how the sixteen address lines are +shared between an oscillator's pointer and its accumulator, and the address bus +resolution slides the accumulator's share up and down — and the figure is what +`addressOf` is written from, corner by corner, in a test. + +What happens at the end of a wavetable is the difference between the four +modes, and it is also where two things had to be got right that a plain reading +would miss. The first is when the interrupt happens. The Hardware Reference +says an oscillator interrupts when it "reaches the end of its wavetable", not +when it halts, and that distinction carries weight: Technical Note #23 +describes the machine's own note synthesiser running a *free-running* +oscillator over the first page of the sound RAM at zero volume purely as a +clock — an oscillator that by definition never halts — so a model that +interrupted only on halting would leave every envelope in the machine frozen. +The second is how the interrupt is let go, which nothing published says at all. +The machine's own handler settles it: at `$ffb8f6` it points the chip at the +interrupt register, reads the data register twice — once for the lag and once +for the value — tests bit 7, puts the pointer and the control register back and +writes nothing to the chip. If reading it were not the acknowledgement, the +line would never drop and the machine would spend the rest of its life in that +handler. + +The behaviour worth pointing at, though, is one that is not written down here +at all. Technical Note #11 records that the DOC falls silent for no more than a +single sample "whenever a swap occurs from a higher-numbered oscillator to a +lower-numbered one", and that it does not do so swapping the other way. Nothing +in `src/ensoniq.zig` arranges that. It falls out of scanning the oscillators in +order, lowest first, as the chip does: an even oscillator woken by its odd mate +has already been passed over this time round and cannot play until the next, +and an odd one woken by its even mate has not been reached yet and plays +immediately. The test for it asserts the anomaly rather than the tidy +behaviour, because reproducing the anomaly is the evidence that the scan order +is right. + +What is missing is the last step. Nothing carries the mix out of the machine: +`gs` has no audio output, so the oscillators are summed and the sum is thrown +away. That took the list to 128 accesses across seven switches, touched once or twice each — the disk interface register, the slot ROM select, the serial chip, @@ -3110,6 +3152,25 @@ half of this project rather than the finished half. [archive.org](https://archive.org/details/Apple_IIgs_Firmware_Reference_HiRes) · [text](https://archive.org/download/Apple_IIgs_Firmware_Reference_HiRes/Apple_IIgs_Firmware_Reference_HiRes_djvu.txt) +- **Apple IIgs Technical Notes, numbers 11 to 25.** Apple Computer, Developer + Technical Support, 1987 to 1990. Short notes issued between editions of the + books above, and three of these fifteen bear directly on the sound chip. + #11, "Ensoniq DOC Swap-Mode Anomaly", records that the output falls to the + zero-crossing level for no longer than one sample period "whenever a swap + occurs from a higher-numbered oscillator to a lower-numbered one", and not + the other way about — which `src/ensoniq.zig` reproduces without being told + to, by scanning its oscillators in the order the chip scans them. #23, + "Toolbox Use of DOC RAM", explains that the Note Synthesizer runs a + free-running oscillator over the first page of the sound RAM at zero volume + purely as a clock, which is what settles that an oscillator interrupts at the + end of its wavetable rather than when it halts. And #19, "Multichannel Output + with the Apple IIgs Note Synthesizer", says what the top four bits of an + Oscillator Control register are for: a stereo card decodes three of them, + even channels to the right and odd to the left. The other twelve are toolbox + and firmware matters, of which #25 is a correction list for the Firmware + Reference above and #13 a bug in ROM 1.0's modem firmware. + [PDF at mirrors.apple2.org.za](https://mirrors.apple2.org.za/Apple%20II%20Documentation%20Project/Computers/Apple%20II/Apple%20IIGS/Documentation/Apple%20IIGS%20Technical%20Notes%2011-25.pdf) + - **The Cortland documentation set.** Apple Computer, 1985–86, under the machine's codename and before it had its name. Thirty-odd documents, of which three bear on this: the Cortland Hardware Reference, which is the earlier diff --git a/src/ensoniq.zig b/src/ensoniq.zig index 109e880..d697df2 100644 --- a/src/ensoniq.zig +++ b/src/ensoniq.zig @@ -27,14 +27,100 @@ //! An emulator without that returns everything shifted by one byte, which a //! memory test would report as every location being wrong. //! -//! What is not here is the synthesis. The chip's registers are storage and -//! behave as storage: a byte written to an oscillator's frequency comes back. -//! What an oscillator would *do* with it — walk a wavetable, sum thirty-two of -//! them, put the result out of the speaker — is not modelled, and nothing here -//! makes a sound. +//! 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"); +/// 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: whether one has happened, and +/// which oscillator it was. The number sits in bits 5 to 1, which is the +/// oscillator's own number doubled — the same doubling the enable register +/// counts in. +pub const interrupt_happened: u8 = 0x80; + /// The sound chip and its glue. pub const Doc = struct { /// Sixty-four kilobytes of waveform storage, owned by whoever built this: @@ -63,6 +149,25 @@ pub const Doc = struct { /// This is the one-cycle lag, and it is the whole reason reads are odd. latch: u8 = 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, + + /// 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 @@ -93,11 +198,28 @@ pub const Doc = struct { self.latch = if (self.ram_access) self.ram[self.pointer] else - self.registers[@as(u8, @truncate(self.pointer))]; + 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 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; the machine's own handler settles it. At `$ffb8f6` 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 { + const value = self.registers[which]; + if (which == interrupt_register) self.registers[which] = 0; + return value; + } + /// 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 { @@ -128,6 +250,228 @@ pub const Doc = struct { 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 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 it holds the first until + /// something reads it. Nothing here says what the real chip does with a + /// second one in the meantime. + fn reached(self: *Doc, osc: u5) void { + if (self.reg(.control, osc) & control_interrupt == 0) return; + if (self.registers[interrupt_register] & interrupt_happened != 0) return; + // The register carries the oscillator's number doubled, in the same + // units the enable register counts in. + self.registers[interrupt_register] = interrupt_happened | (@as(u8, osc) << 1); + } + + /// 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.registers[interrupt_register] & interrupt_happened != 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 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 0; + 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; + return @intCast(std.math.clamp(average, -32768, 32767)); + } + /// 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 { @@ -137,6 +481,10 @@ pub const Doc = struct { self.auto_increment = false; self.volume = 0; self.latch = 0; + self.accumulators = @splat(0); + self.mixed = 0; + self.passes = 0; + self.left_over = 0; } }; @@ -239,3 +587,291 @@ test "a whole pass over the sound RAM comes back byte for byte" { 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()); + // The register carries the oscillator's number doubled, in the same units + // the enable register counts in. + try testing.expectEqual( + @as(u8, interrupt_happened | (3 << 1)), + doc.registers[interrupt_register], + ); + + // And one that was not asked to interrupt does not. + doc.registers[interrupt_register] = 0; + playing(&doc, 2, 0x2000, .one_shot, &.{ 0x11, 0x00 }); + doc.onePass(); + try testing.expect(!doc.interrupting()); +} + +test "a swap from an odd oscillator to its even mate loses a sample" { + // Technical Note #11, "Ensoniq DOC Swap-Mode Anomaly": 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: 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_happened | (0 << 1)), + doc.registers[interrupt_register], + ); + + // And it keeps time: acknowledged, it comes round again. + doc.registers[interrupt_register] = 0; + 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_happened | (5 << 1)), answer); + try testing.expect(!doc.interrupting()); +} diff --git a/src/memory16/apple2gs.zig b/src/memory16/apple2gs.zig index c09cdd9..42fd19f 100644 --- a/src/memory16/apple2gs.zig +++ b/src/memory16/apple2gs.zig @@ -493,7 +493,7 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { // The machine's own idea of a second, which is // what the one-second interrupt counts in too, so // that the two agree about how fast time goes. - .cycles_per_second = cycles_per_frame * frames_per_second, + .cycles_per_second = cycles_per_second, }, .iwm = .{ .drives = .{ @@ -603,6 +603,11 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { const frames_per_quarter_second = 16; const frames_per_second = 60; + /// How many of the machine's cycles make a second, which is + /// what anything measuring real time against the clock needs: + /// the real-time clock, and the sound chip's scan rate. + pub const cycles_per_second = cycles_per_frame * frames_per_second; + /// Whether the video is in the vertical blanking interval. /// /// There is one notion of where the beam is rather than two @@ -662,6 +667,21 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { if (superhires.interruptsOn(&self.mega2, y)) self.vgc.scan_line = true; } } + // And the sound chip, brought up to date on the same + // count. A frame would be too coarse a tick for it: the + // machine's own note synthesiser runs an oscillator round + // a 256-byte buffer as a clock, which at eight oscillators + // is an interrupt every three milliseconds or so, and the + // interrupt register can only hold one at a time — caught + // up once a frame, five of them would arrive as one and + // every envelope in the machine would move six times too + // slowly. A line is 64 microseconds, which is finer than + // anything the chip does, and this is the hot path, so it + // is done on the line boundaries the video has counted + // already rather than on every access. + if (reached != self.scan_lines) { + self.doc.advance(now, cycles_per_second); + } self.scan_lines = reached; const begun = (now + blanking_cycles) / cycles_per_frame; @@ -697,6 +717,7 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { inline fn updateInterrupt(self: *Self) void { self.getCPU().irq = self.interrupts.asking() or self.vgc.interrupting() or + self.doc.interrupting() or self.adb.interrupting(self.mega2.keyWaiting()); }