diff --git a/README.md b/README.md index 4289d1e..f6295dc 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,66 @@ and the header comes along unchanged. The header is believed over the name, which is the entire point of the format — a DOS-order image called `.po` reads correctly, and this is tested by making exactly that file and booting it. +#### Recordings of the surface + +A `.dsk` says what sectors are on a disk. A `.nib` says what the drive's head +*saw*, which is not the same thing: address fields with the wrong prologue, +sectors with no address field, a thirteenth sector hidden in the gaps, a track +carrying two sector 3s that read differently. It is thirty-five tracks of 6,656 +nibbles and nothing else — 232,960 bytes, and no header, so the size is what +says a file is one. Writing works and saves back as nibbles. + +#### WOZ: the bits themselves + +**WOZ** goes one further and writes down what is actually on the surface: the +bit cells, in order, as many of them as that track happens to hold. It came out +of the Applesauce project in 2018, and it exists because everything above it +throws away what copy protection was built on. + +``` +zig65 --rom apple2e.rom --disk-rom disk2.rom --disk1 "DOS 3.3 System Master.woz" +``` + +What the other formats throw away is timing and shape. A track is not a fixed +number of bytes — it is however many bit cells went past in one revolution, +which depends on how fast the disk was turning. A self-sync byte is *ten* bits +long rather than eight. Some disks have a track between two tracks, or a track +two tracks wide, or a run of bits that reads differently every time because +nothing is recorded there and the drive's amplifier is listening to its own +noise. None of that fits in a file of sectors, and a file of nibbles keeps only +the second-hand version of it. + +Reading it properly meant the drive had to change. It used to hold a disk as +thirty-five tracks of 6,656 bytes and hand one over per read; it now holds each +track as the bits it is, with its own length, and the controller assembles them +the way the real one does — a shift register that takes a bit every four +microseconds and says a byte is ready when its top bit comes round. That is a +better model of the hardware for every disk, not only for WOZ, and it made +something visible that had been quietly wrong all along. + +**The gaps had to become real self-sync bytes.** A gap written as plain `$ff` +is eight bits, so a reader that starts mid-byte stays mid-byte for ever and +every field on the disk reads as a smear of two. Real formatters write `$ff` +followed by two extra zero bits, and those two bits are what push a lost reader +back into step within a byte or two. The old byte-at-a-time drive could not +tell the difference and did not need to; the moment the shifter became real, +disks laid out here stopped being readable until the encoder wrote proper +self-sync. That is the sort of thing only the bit-level model can show you. + +A head that has just been put down is *not* in step with the disk, so the first +bytes it assembles are two neighbours smeared together. That is correct, and +the tests now say so: what they check is not that every byte is a legal nibble +— it should not be — but that the marks a sector begins with turn up, which is +what the ROM is looking for too. + +Verified against the WOZ reference images, which the format's authors publish +for exactly this, following the order their readme recommends: the DOS 3.3 +System Master, then "The Apple at Play", then the protected titles the readme +calls "your reward for getting this far". + +WOZ disks are read only. Writing one back means the WRIT chunk and an account +of where the write splice falls, and this only reads. + #### ShrinkIt archives Most of what is on the Apple II archives is not a disk image at all. It is a @@ -1390,15 +1450,19 @@ machine around them is not. motor, four magnets that walk the head a half track at a time, and a stream of bytes going past. `.dsk`, `.do` and `.po` images are encoded into six and two exactly as a real disk is written, so the machine's own ROM and DOS read - them the way they read a disk; a `.2mg` says which order its sectors are in + them the way they read a disk; a `.nib` is a recording of the nibbles rather + than a description of the sectors and goes in as it stands; a `.woz` is a + recording of the *bits*, which is what a copy-protected disk needs and what + the drive reads natively; a `.2mg` says which order its sectors are in and is believed; and a ShrinkIt archive — `.shk` or `.sdk`, which is what most Apple II software is distributed as — is unpacked and the disk inside it used. Writing works and is saved back to the file when asked for — as nibbles for a `.nib`, which is the only file that can hold a track the machine laid out itself — except for a disk that came out of an archive, which is read - only because putting one back would mean writing a ShrinkIt archive. Quarter - tracking and bit-level timing are not modelled, so a disk whose protection - counts on either still will not load, `.nib` or not. + only because putting one back would mean writing a ShrinkIt archive, and a + `.woz`, which this only reads. Quarter tracking is not modelled — the head + moves in half tracks — so a disk whose protection depends on putting it + between two of those will not load. - **Text video.** Forty columns, and on a IIe eighty, drawn out of both halves of memory the way the hardware reads them, with the alternate character set and both text pages. The switches that move the processor's window about are @@ -3195,6 +3259,7 @@ being redrawn because a screen hole moved. | `src/disk2.zig` | the Disk II: the card, its drives, and six and two | | `src/iwm.zig` | the IWM: an Apple IIgs's disk port, and which drives it reaches | | `src/disk35.zig` | the Apple 3.5-inch drive: its fifteen registers, and 800K of zoned six and two | +| `src/woz.zig` | WOZ: a disk as the bits that go past the head | | `src/shrinkit.zig` | ShrinkIt archives: the NuFX format and both of its compressors | | `src/diskfile.zig` | a disk out of whatever file was named, whichever of the three kinds it is | | `src/dos33.zig` | DOS 3.3 on the disk: making an image, and the files on it | @@ -3351,6 +3416,26 @@ half of this project rather than the finished half. comes off, and the card adds the line feed the Apple does not send. [Internet Archive](https://archive.org/details/Apple_II_Parallel_Printer_Interface_Card_Installation_and_Operating_Manual) +- **WOZ Disk Image Reference 2.1.** John K. Morris and the Applesauce + project, 2018 onward. The format that writes a disk down as its bits, and + the reference is unusually good: it gives the chunks exactly, and then goes + further and tells an emulator author what to *do* with them — the four-bit + window that puts back the noise a cleaned image had taken out of it, the + rule for scaling the head's position when it moves to a track of a different + length, and what an empty quarter track should read as. `src/woz.zig` and the + drive in `src/disk2.zig` are written from it. + [Reference 2.1](https://applesaucefdc.com/woz/reference2/) + · [Reference 1.0](https://applesaucefdc.com/woz/reference1/) + +- **The WOZ test images.** John K. Morris, v1.4, 2021. Forty-five 5.25-inch + images "intended to assist Apple ][ emulator developers in testing their + implementations of floppy drives and drive controller cards", with a readme + that puts them in order of difficulty: start with the System Masters, then + the ordinary copy protections, then the cross-track checks. It is the closest + thing a drive has to the processor's corpus, and it is what this was built + against. + [woz_images.zip](http://evolutioninteractive.com/applesauce/woz_images.zip) + - **The 2IMG (2MG) disk image format.** Written by the Apple II community rather than by Apple, in the middle nineteen-nineties, and the only image format in the family that says what it is: a sixty-four byte header giving diff --git a/completions/zig65.bash b/completions/zig65.bash index b7888df..39e65f5 100644 --- a/completions/zig65.bash +++ b/completions/zig65.bash @@ -57,7 +57,7 @@ _zig65() { ;; --disk1 | --disk2) _zig65_files "$current" '*.[dD][sS][kK]' '*.[dD][oO]' '*.[pP][oO]' \ - '*.2[mM][gG]' '*.[sS][hH][kK]' '*.[sS][dD][kK]' '*.[nN][iI][bB]' + '*.2[mM][gG]' '*.[sS][hH][kK]' '*.[sS][dD][kK]' '*.[nN][iI][bB]' '*.[wW][oO][zZ]' return ;; --drives) diff --git a/completions/zig65.fish b/completions/zig65.fish index 23a0dde..6900d3a 100644 --- a/completions/zig65.fish +++ b/completions/zig65.fish @@ -52,10 +52,10 @@ complete -c zig65 -l drives -x \ -d 'How many drives are on the card, 0 to 2 (default 2)' complete -c zig65 -l disk1 -r \ -n 'not __fish_seen_argument -l disk1' \ - -d 'Disk to put in the first drive: .dsk, .do, .po, .nib, .2mg, .shk or .sdk' + -d 'Disk to put in the first drive: .dsk, .po, .nib, .woz, .2mg, .shk or .sdk' complete -c zig65 -l disk2 -r \ -n 'not __fish_seen_argument -l disk2' \ - -d 'Disk to put in the second drive: .dsk, .do, .po, .nib, .2mg, .shk or .sdk' + -d 'Disk to put in the second drive: .dsk, .po, .nib, .woz, .2mg, .shk or .sdk' complete -c zig65 -l screenshot -r \ -n 'not __fish_seen_argument -l screenshot' \ -d 'Where alt+g writes a picture of the screen, as a PNG' diff --git a/src/disk2.zig b/src/disk2.zig index ee09008..cdc7f1f 100644 --- a/src/disk2.zig +++ b/src/disk2.zig @@ -30,6 +30,8 @@ //! addresses. const std = @import("std"); + +const woz = @import("woz.zig"); const testing = std.testing; /// A 5.25 inch disk as the Apple wrote it: 35 tracks of 16 sectors of 256 @@ -61,6 +63,41 @@ pub const nibbles_per_track = 6656; /// same name on the controller below. pub const cycles_per_nibble = 32; +/// How many cycles one *bit* takes to pass the head, which is what the drive +/// actually deals in: four microseconds, and eight of them to a byte. +/// +/// The byte figure above is this times eight, and both are here because the +/// controller counts bits and everything that talks to it counts bytes. +pub const cycles_per_bit = cycles_per_nibble / 8; + +/// How many quarter-track positions a head can be put at. +/// +/// The four magnets place it in half tracks, and a real drive can be coaxed +/// between two of those by leaving two magnets on at once, which some copy +/// protection uses. A disk is stored at this resolution whether or not the head +/// can be put there, because a WOZ says what is at each of them. +pub const quarter_tracks = 160; + +/// How many distinct tracks a disk can hold. +/// +/// Thirty-five for anything laid out here, and up to thirty-six in the WOZ +/// reference images — a disk with a half track on it. Forty-eight is room to +/// spare without making a floppy larger than it needs to be. +pub const max_tracks = 48; + +/// How long a track can be, in bytes of bit stream. A 5.25-inch track is about +/// fifty thousand bits, and the longest in the reference images is 51,483. +pub const max_track_bytes = 14 * 512; + +/// How many bits a track laid out here comes to, which is the nibble count +/// times eight. A real track is a little shorter, because a real disk is not +/// turning at exactly 300rpm and the number of bits is whatever went past. +pub const bits_per_track = nibbles_per_track * 8; + +/// What a quarter-track position holds when it holds no track at all, which is +/// the ordinary state of the gap between two tracks. +pub const nothing_there: u8 = 0xff; + /// Which order the sectors of a track appear in inside the file. /// /// Sectors are not laid down one after another on the track. Reading is much @@ -129,18 +166,39 @@ const epilogue = [_]u8{ 0xde, 0xaa, 0xeb }; /// start of a byte, and this hands over whole bytes already. const sync = 0xff; -/// How the gaps are sized. The fixed parts of a sector come to 369 bytes, so -/// sixteen of them and the gaps have to add up to a track exactly. +/// How long a self-sync byte is, in bits. +/// +/// Ten rather than eight, and this is the one thing about a track that a file +/// of bytes cannot hold. A gap is written as `$ff` with two extra zero bits +/// after it, so a reader that has lost its place — which every reader has, at +/// the start — collects nonsense for a byte or two and is then back in step +/// with the disk, because the extra zeros push its shifter along by less than +/// a whole byte each time. Without them nothing would ever line up: a shifter +/// that started mid-byte would stay mid-byte for ever, and every field on the +/// disk would read as a smear of two. +const self_sync_bits = 10; + +/// How the gaps are sized. The fixed parts of a sector come to 363 bytes of +/// data and 2,904 bits, so sixteen of them and the gaps have to come to about +/// a track: fifty-odd thousand bits, which is what goes past the head in one +/// revolution. const leading_sync = 48; const address_to_data_sync = 6; -const sector_fixed = address_prologue.len + 8 + epilogue.len + - address_to_data_sync + data_prologue.len + 343 + epilogue.len; -const trailing_sync = (nibbles_per_track - leading_sync - sectors_per_track * sector_fixed) / sectors_per_track; +const fixed_bytes = address_prologue.len + 8 + epilogue.len + + data_prologue.len + 343 + epilogue.len; +const sector_fixed = fixed_bytes + address_to_data_sync; +const trailing_sync = (bits_per_track - leading_sync * self_sync_bits - + sectors_per_track * (fixed_bytes * 8 + address_to_data_sync * self_sync_bits)) / + (sectors_per_track * self_sync_bits); + +/// How long a track laid out here comes to, in bits. +const laid_out_bits = leading_sync * self_sync_bits + + sectors_per_track * (fixed_bytes * 8 + (address_to_data_sync + trailing_sync) * self_sync_bits); comptime { - // Whatever is left over after dividing the gaps evenly is padding at the - // end of the track, and there has to be room for it to be non-negative. - std.debug.assert(leading_sync + sectors_per_track * (sector_fixed + trailing_sync) <= nibbles_per_track); + // It has to fit in a track, with the self-sync bytes costing a quarter + // more than they would as plain bytes. + std.debug.assert(laid_out_bits <= max_track_bytes * 8); } /// The volume number written into every address field. DOS puts 254 on a disk @@ -235,14 +293,61 @@ pub fn reorder(image: []const u8, into: []u8, from: Order, to: Order) Floppy.Loa } } +/// Whether a byte is one the surface can carry. +/// +/// The high bit set, and no two zero bits in a row: that is the whole of the +/// rule, and it is why there are only sixty-four of them rather than 256. A +/// drive reading a disk that was laid out properly sees nothing else. +pub fn legal(value: u8) bool { + for (write_table) |pattern| { + if (pattern == value) return true; + } + return false; +} + /// A floppy, held the way the drive sees it rather than the way the file does. /// /// This is deliberately large — a third of a megabyte — and deliberately not /// part of the machine: whoever owns the emulator allocates it and hands it /// over, so that a machine with no drives costs nothing and swapping a disk is /// a matter of handing over a different one. +/// One track, as the bits that go past the head. +/// +/// Bits and not bytes, because a track is not a whole number of bytes and the +/// difference is what copy protection is made of. A self-sync byte is ten bits +/// long, so a reader that has lost its place finds it again a byte or two +/// later; a track holds however many bits went past in one revolution, which +/// depends on how fast the disk was turning; and a disk laid out by hand has +/// nothing to say about any of that. Storing bytes throws all of it away. +pub const Track = struct { + /// Packed high bit first, which is the order they go past the head. + bits: [max_track_bytes]u8 = @splat(0), + /// How many of those bits are the track. Zero means nothing is recorded + /// here, which is not the same as a track of zeroes. + count: u32 = 0, + + /// The bit at `at`, counting round the track. + pub fn bit(self: *const Track, at: u32) u1 { + if (self.count == 0) return 0; + const which = at % self.count; + return @truncate(self.bits[which / 8] >> @intCast(7 - (which % 8))); + } + + pub fn setBit(self: *Track, at: u32, value: u1) void { + if (self.count == 0) return; + const which = at % self.count; + const mask = @as(u8, 0x80) >> @intCast(which % 8); + if (value == 1) self.bits[which / 8] |= mask else self.bits[which / 8] &= ~mask; + } +}; + pub const Floppy = struct { - tracks: [tracks_per_disk][nibbles_per_track]u8 = undefined, + /// Which recorded track the head finds at each quarter-track position, or + /// `nothing_there`. A disk laid out here puts the same track at all four + /// quarters of its position, which is what the drive used to do when it + /// simply divided by two; a WOZ brings its own map and is more particular. + map: [quarter_tracks]u8 = @splat(nothing_there), + tracks: [max_tracks]Track = @splat(.{}), /// Whether the tab is over the notch. A drive can tell, and DOS asks /// before it writes. write_protected: bool = true, @@ -259,12 +364,106 @@ pub const Floppy = struct { if (image.len != image_size) return error.WrongSize; self.order = order; self.dirty = false; + self.describe(tracks_per_disk); for (0..tracks_per_disk) |track| { const from = image[track * bytes_per_track ..][0..bytes_per_track]; encodeTrack(from, &self.tracks[track], @intCast(track), order); } } + /// Lays out the quarter-track map for a disk of `count` whole tracks. + /// + /// All four quarters of a position read the same track, which is what the + /// drive did when it simply divided the half-track count by two. It is not + /// what a real disk does — the gap between two tracks holds nothing — but + /// it is what a disk described rather than recorded can honestly say, and + /// changing it would make a half-track step read silence on disks that have + /// always worked. + fn describe(self: *Floppy, count: u8) void { + self.map = @splat(nothing_there); + for (0..count) |track| { + for (0..4) |quarter| { + const at = track * 4 + quarter; + if (at < quarter_tracks) self.map[at] = @intCast(track); + } + } + } + + /// Writes a track's worth of nibbles into it, eight bits to the nibble. + /// + /// Everything laid out here is nibble aligned, so this is the whole of the + /// difference between what the encoder produces and what the head sees. + fn putNibbles(self: *Floppy, track: u8, nibbles: *const [nibbles_per_track]u8) void { + const into = &self.tracks[track]; + @memcpy(into.bits[0..nibbles_per_track], nibbles); + into.count = bits_per_track; + } + + /// Reads a track back as nibbles, by running the shifter over it the way + /// the controller does. + /// + /// For a disk laid out here this gives back exactly what went in. For one + /// that was recorded it gives what a drive would read on one pass, which + /// is the best a file of nibbles can hold. + fn takeNibbles(self: *const Floppy, track: u8, nibbles: *[nibbles_per_track]u8) void { + self.readTrack(track, nibbles, null); + } + + /// The same, and where each nibble began. + /// + /// The second half of that is what anything wanting to put a nibble back + /// needs. A nibble is not at a fixed place in a track: a self-sync byte is + /// ten bits long, so everything after one is pushed along by two, and the + /// nth nibble is simply wherever the shifter had got to. + pub fn readTrack( + self: *const Floppy, + track: u8, + nibbles: *[nibbles_per_track]u8, + offsets: ?*[nibbles_per_track]u32, + ) void { + const from = &self.tracks[track]; + if (from.count == 0) { + @memset(nibbles, sync); + return; + } + var latch: u8 = 0; + var at: u32 = 0; + var out: usize = 0; + // One revolution and no more. A file of nibbles holds a track once, + // and going round twice would put the beginning of it in the buffer a + // second time — which anything reading the file would see as a + // seventeenth sector that stops in the middle. + var began: u32 = 0; + while (out < nibbles.len and at < from.count) : (at += 1) { + if (latch == 0) began = at; + latch = (latch << 1) | from.bit(at); + if (latch & 0x80 != 0) { + nibbles[out] = latch; + if (offsets) |where| where[out] = began; + out += 1; + latch = 0; + } + } + while (out < nibbles.len) : (out += 1) { + nibbles[out] = sync; + if (offsets) |where| where[out] = 0; + } + } + + /// One nibble of a track whose bytes are byte aligned, which is what a + /// disk read out of a file of nibbles is. A track laid out here is not: + /// its gaps are ten bits long. + pub fn nibbleAt(self: *const Floppy, track: u8, at: usize) u8 { + return self.tracks[track].bits[at % nibbles_per_track]; + } + + /// Lays a byte down at a bit position, high bit first, which is what the + /// machine does when it writes. + pub fn writeNibbleAt(self: *Floppy, track: u8, at: u32, value: u8) void { + const into = &self.tracks[track]; + for (0..8) |i| into.setBit(at + @as(u32, @intCast(i)), @truncate(value >> @intCast(7 - i))); + } + /// How big a file of raw nibbles is: every track as the drive holds it, /// one after another and nothing else. pub const nibble_size = tracks_per_disk * nibbles_per_track; @@ -295,9 +494,51 @@ pub const Floppy = struct { // back into a sectored file anyway. Recorded, not described. self.order = .prodos; self.dirty = false; + self.describe(tracks_per_disk); for (0..tracks_per_disk) |track| { - @memcpy(&self.tracks[track], image[track * nibbles_per_track ..][0..nibbles_per_track]); + self.putNibbles( + @intCast(track), + image[track * nibbles_per_track ..][0..nibbles_per_track], + ); + } + } + + /// Takes a disk recorded as the bits that went past the head. + /// + /// This is the one format that keeps a track's own length and its own + /// alignment, so it is the one that goes in without being turned into + /// anything: the bits are copied and the map comes along with them. + pub fn loadWoz(self: *Floppy, image: woz.Image) !void { + self.order = .prodos; + self.dirty = false; + self.write_protected = image.info.write_protected; + self.map = @splat(nothing_there); + self.tracks = @splat(.{}); + + // The file's own map, position for position. Which recorded track is + // at each quarter is the file's business and not this one's: that is + // where a track between two tracks, or one track two tracks wide, + // lives. + var mapping: [woz.positions]u8 = @splat(nothing_there); + var used: u8 = 0; + for (0..@min(quarter_tracks, woz.positions)) |position| { + const which = image.at(@intCast(position)) orelse continue; + if (mapping[which] == nothing_there) { + if (used >= max_tracks) return error.TooManyTracks; + const track = try image.track(which); + if (track.count == 0) continue; + if ((track.count + 7) / 8 > max_track_bytes) return error.TrackTooLong; + mapping[which] = used; + self.tracks[used].count = track.count; + @memcpy( + self.tracks[used].bits[0 .. (track.count + 7) / 8], + track.bits[0 .. (track.count + 7) / 8], + ); + used += 1; + } + self.map[position] = mapping[which]; } + if (used == 0) return error.NoTracks; } /// Writes the disk out as raw nibbles, which is the one form that can hold @@ -306,7 +547,7 @@ pub const Floppy = struct { pub fn saveNibbles(self: *const Floppy, image: []u8) LoadError!void { if (image.len != nibble_size) return error.WrongSize; for (0..tracks_per_disk) |track| { - @memcpy(image[track * nibbles_per_track ..][0..nibbles_per_track], &self.tracks[track]); + self.takeNibbles(@intCast(track), image[track * nibbles_per_track ..][0..nibbles_per_track]); } } @@ -319,8 +560,10 @@ pub const Floppy = struct { /// disk being saved over itself means it keeps what it had. pub fn save(self: *const Floppy, image: []u8) LoadError!void { if (image.len != image_size) return error.WrongSize; + var nibbles: [nibbles_per_track]u8 = undefined; for (0..tracks_per_disk) |track| { - decodeTrack(&self.tracks[track], image[track * bytes_per_track ..][0..bytes_per_track], self.order); + self.takeNibbles(@intCast(track), &nibbles); + decodeTrack(&nibbles, image[track * bytes_per_track ..][0..bytes_per_track], self.order); } } }; @@ -329,41 +572,67 @@ pub const Floppy = struct { /// field saying where it is and a data field holding it. fn encodeTrack( from: *const [bytes_per_track]u8, - into: *[nibbles_per_track]u8, + into: *Track, track: u8, order: Order, ) void { - @memset(into, sync); - var at: usize = leading_sync; + var head: Layer = .{ .track = into }; + into.count = laid_out_bits; + @memset(&into.bits, 0); + + head.sync(leading_sync); + var field: [343]u8 = undefined; for (0..sectors_per_track) |physical| { const sector: u8 = @intCast(physical); - @memcpy(into[at..][0..3], &address_prologue); - at += 3; - writeFourAndFour(into[at..][0..2], default_volume); - writeFourAndFour(into[at + 2 ..][0..2], track); - writeFourAndFour(into[at + 4 ..][0..2], sector); - writeFourAndFour(into[at + 6 ..][0..2], default_volume ^ track ^ sector); - at += 8; - @memcpy(into[at..][0..3], &epilogue); - at += 3; - - @memset(into[at..][0..address_to_data_sync], sync); - at += address_to_data_sync; + head.all(&address_prologue); + var four: [2]u8 = undefined; + for ([_]u8{ default_volume, track, sector, default_volume ^ track ^ sector }) |value| { + writeFourAndFour(&four, value); + head.all(&four); + } + head.all(&epilogue); + head.sync(address_to_data_sync); - @memcpy(into[at..][0..3], &data_prologue); - at += 3; + head.all(&data_prologue); const logical: usize = order.logical(sector); - encodeSector(from[logical * bytes_per_sector ..][0..bytes_per_sector], into[at..][0..343]); - at += 343; - @memcpy(into[at..][0..3], &epilogue); - at += 3; + encodeSector(from[logical * bytes_per_sector ..][0..bytes_per_sector], &field); + head.all(&field); + head.all(&epilogue); - @memset(into[at..][0..trailing_sync], sync); - at += trailing_sync; + head.sync(trailing_sync); } } +/// Lays bytes down on a track, high bit first, as the head would. +const Layer = struct { + track: *Track, + at: u32 = 0, + + fn bit(self: *Layer, value: u1) void { + if (value == 1) self.track.bits[self.at / 8] |= @as(u8, 0x80) >> @intCast(self.at % 8); + self.at += 1; + } + + fn byte(self: *Layer, value: u8) void { + for (0..8) |i| self.bit(@truncate(value >> @intCast(7 - i))); + } + + fn all(self: *Layer, values: []const u8) void { + for (values) |value| self.byte(value); + } + + /// A gap: `$ff` and then two bits of nothing, which is what puts a reader + /// back in step. + fn sync(self: *Layer, count: usize) void { + for (0..count) |_| { + self.byte(0xff); + self.bit(0); + self.bit(0); + } + } +}; + /// Reads a track back, by going round it looking for the marks. fn decodeTrack(from: *const [nibbles_per_track]u8, into: *[bytes_per_track]u8, order: Order) void { var at: usize = 0; @@ -423,13 +692,54 @@ pub const Drive = struct { /// Which magnets are energised. Which one comes on next is what says /// whether the head is going in or out. phases: [4]bool = @splat(false), - /// How far round the disk has turned, as a position in the encoded track. - position: u16 = 0, + /// How far round the disk has turned, as a bit position in the track under + /// the head. Bits, because that is what goes past it. + position: u32 = 0, + /// The read shifter: bits go in at the bottom and a byte is ready when the + /// top one is set, which is the whole of how a nibble is recognised. A + /// self-sync byte's two extra zero bits are absorbed here rather than + /// becoming part of anything, which is what lets a reader find its place. + latch: u8 = 0, + /// The last four bits off the surface, for spotting the runs of nothing a + /// cleaned image leaves behind. + window: u8 = 0, + /// Where the random bits over unrecorded surface come from. Seeded from + /// nothing in particular, because what matters is that they are not the + /// same every revolution. + noise: u32 = 0x2545f491, pub fn track(self: *const Drive) u8 { return self.half_track / 2; } + /// Which quarter-track position the head is at. + pub fn quarter(self: *const Drive) u8 { + return @min(quarter_tracks - 1, @as(u16, self.half_track) * 2); + } + + /// The track under the head, or nothing if there is none there. + pub fn under(self: *const Drive) ?*Track { + const floppy = self.floppy orelse return null; + const which = floppy.map[self.quarter()]; + if (which == nothing_there) return null; + return &floppy.tracks[which]; + } + + /// One bit off the surface. + /// + /// A cleaned image has had the noise a drive makes over unrecorded surface + /// taken out and left as a run of zero bits, and a reader has to put it + /// back or the disk reads as something no drive ever saw. The WOZ reference + /// gives the rule outright: keep the last four bits, and if all four are + /// zero — which is to say more than two zeroes in a row, which no real + /// recording contains — hand back noise instead, about three times in ten. + fn nextBit(self: *Drive, from: *const Track) u1 { + self.window = (self.window << 1) | from.bit(self.position); + if (self.window & 0x0f != 0) return @truncate(self.window >> 1); + self.noise = self.noise *% 1664525 +% 1013904223; + return if ((self.noise >> 16) % 10 < 3) 1 else 0; + } + /// Energises or releases one magnet, and moves the head if the one coming /// on is next door to where the head already is. Turning one off never /// moves anything. @@ -437,16 +747,49 @@ pub const Drive = struct { self.phases[phase] = on; if (!on) return; const at: u2 = @truncate(self.half_track); + const before: u32 = if (self.under()) |t| t.count else 0; if (phase == at +% 1 and self.half_track < (tracks_per_disk - 1) * 2) { self.half_track += 1; } else if (phase == at -% 1 and self.half_track > 0) { self.half_track -= 1; + } else return; + + // The head moves; the disk does not stop turning. Where it now is on + // the new track is where it would have been had it always been there, + // which matters because a track is not the same length as its + // neighbour and a disk written in one pass has the two lined up. That + // alignment is what a cross-track check looks at. + const after: u32 = if (self.under()) |t| t.count else 0; + if (before != 0 and after != 0) { + self.position = @intCast(@as(u64, self.position) * after / before); + } else if (after != 0) { + self.position %= after; } + self.latch = 0; } - /// Turns the disk on by however many bytes have gone past. - fn turn(self: *Drive, nibbles: usize) void { - self.position = @intCast((self.position + nibbles) % nibbles_per_track); + /// Turns the disk by however many bits have gone past, shifting each one + /// into the read shifter on its way. + /// + /// The shifter stops taking bits once it holds a whole byte: the disk goes + /// on turning, and what goes past while the processor has not collected the + /// last byte is gone. That is what a drive does, and it is why the firmware + /// has to come back for each byte inside thirty-two cycles. + fn turn(self: *Drive, bits: usize) void { + const from = self.under() orelse { + // Between two tracks, or over a track that was never recorded. + // A real head hears the amplifier's own noise, and firmware + // looking for an address field there finds nothing for ever. + self.position +%= @intCast(bits); + self.latch = 0; + return; + }; + for (0..bits) |_| { + const value = self.nextBit(from); + self.position = (self.position + 1) % @max(1, from.count); + if (self.latch & 0x80 != 0) continue; + self.latch = (self.latch << 1) | value; + } } }; @@ -615,9 +958,15 @@ pub const Controller = struct { pub fn readNibble(self: *Controller, cycles: u64) u8 { self.spin(cycles); const disk = self.current(); - const floppy = disk.floppy orelse return 0; - self.latch = floppy.tracks[disk.track()][disk.position]; - return self.latch; + if (disk.floppy == null) return 0; + const value = disk.latch; + // A byte the processor has taken is a byte the shifter starts again + // after. One it has not finished assembling is handed over as it + // stands, high bit clear, which is exactly what the firmware's read + // loop is waiting to not see. + if (value & 0x80 != 0) disk.latch = 0; + self.latch = value; + return value; } /// One byte past the head, writing. What is written goes down where the @@ -627,7 +976,18 @@ pub const Controller = struct { const disk = self.current(); const floppy = disk.floppy orelse return; if (floppy.write_protected) return; - floppy.tracks[disk.track()][disk.position] = value; + const at = disk.quarter(); + const which = floppy.map[at]; + if (which == nothing_there) return; + const into = &floppy.tracks[which]; + // Eight bits, high one first, laid down where the head is — and the + // head keeps moving while they go down, which is why the position + // advances with them. + for (0..8) |i| { + into.setBit(disk.position, @truncate(value >> @intCast(7 - i))); + disk.position = (disk.position + 1) % @max(1, into.count); + } + disk.latch = 0; floppy.dirty = true; } @@ -648,7 +1008,10 @@ pub const Controller = struct { fn spin(self: *Controller, cycles: u64) void { const elapsed = cycles -| self.turned_at; self.turned_at = cycles; - if (self.motor) self.current().turn(@max(1, elapsed / self.turning)); + // A bit rather than a byte, and never nothing: a processor that reads + // the data register twice in a row still sees the disk move, which is + // what its read loop is counting on. + if (self.motor) self.current().turn(@max(1, elapsed * 8 / self.turning)); } }; @@ -751,15 +1114,17 @@ test "the sector order is the one the file was written in" { // Read the track back by hand: the sector the address field names is a // place on the track, and what is in it is the file's sector. + var laid: [nibbles_per_track]u8 = undefined; + floppy.takeNibbles(0, &laid); var at: usize = 0; var found: usize = 0; while (at < nibbles_per_track) : (at += 1) { - if (!matches(&floppy.tracks[0], at, &address_prologue)) continue; - const physical = readFourAndFour(peek(&floppy.tracks[0], at + 7), peek(&floppy.tracks[0], at + 8)); + if (!matches(&laid, at, &address_prologue)) continue; + const physical = readFourAndFour(peek(&laid, at + 7), peek(&laid, at + 8)); var search = at + 11; - while (!matches(&floppy.tracks[0], search, &data_prologue)) search += 1; + while (!matches(&laid, search, &data_prologue)) search += 1; var field: [343]u8 = undefined; - for (&field, 0..) |*byte, i| byte.* = peek(&floppy.tracks[0], search + 3 + i); + for (&field, 0..) |*byte, i| byte.* = peek(&laid, search + 3 + i); var sector: [bytes_per_sector]u8 = undefined; try decodeSector(&field, §or); try testing.expectEqual(Order.dos.logical(physical), sector[0]); @@ -852,11 +1217,14 @@ test "the write protect tab is what decides whether writing lands" { try testing.expectEqual(@as(u8, 0x80), controller.access(0xe, false, 0, 0)); // Protected, so what is written goes nowhere at all. - const before = floppy.tracks[0]; + var before: [nibbles_per_track]u8 = undefined; + floppy.takeNibbles(0, &before); _ = controller.access(0xf, false, 0, 0); // write mode _ = controller.access(0xd, true, 0x96, 0); // load the latch _ = controller.access(0xc, false, 0, 0); // put it down - try testing.expectEqualSlices(u8, &before, &floppy.tracks[0]); + var after: [nibbles_per_track]u8 = undefined; + floppy.takeNibbles(0, &after); + try testing.expectEqualSlices(u8, &before, &after); try testing.expect(!floppy.dirty); // With the tab off the notch it lands, and the disk is marked as changed @@ -870,8 +1238,16 @@ test "the write protect tab is what decides whether writing lands" { _ = controller.access(0xd, true, 0x96, 0); _ = controller.access(0xc, false, 0, 0); // The disk turned under the head on the way, so the byte is wherever it - // had got to rather than wherever it was. - try testing.expectEqual(@as(u8, 0x96), floppy.tracks[0][controller.drive(0).position]); + // had got to rather than wherever it was — and the head has moved on over + // the eight bits it just laid down, so they are the eight behind it. + const drive = controller.drive(0); + const track = drive.under().?; + var written: u8 = 0; + for (0..8) |i| { + const at = (drive.position + track.count - 8 + @as(u32, @intCast(i))) % track.count; + written = (written << 1) | track.bit(at); + } + try testing.expectEqual(@as(u8, 0x96), written); try testing.expect(floppy.dirty); } @@ -908,17 +1284,20 @@ test "a sector written on the disk turns up in the right place in the file" { var replacement: [bytes_per_sector]u8 = undefined; for (&replacement, 0..) |*byte, i| byte.* = @truncate(0xa0 + i); + var three: [nibbles_per_track]u8 = undefined; + var where: [nibbles_per_track]u32 = undefined; + floppy.readTrack(3, &three, &where); var at: usize = 0; const found = while (at < nibbles_per_track) : (at += 1) { - if (!matches(&floppy.tracks[3], at, &address_prologue)) continue; - if (readFourAndFour(peek(&floppy.tracks[3], at + 7), peek(&floppy.tracks[3], at + 8)) != physical) continue; + if (!matches(&three, at, &address_prologue)) continue; + if (readFourAndFour(peek(&three, at + 7), peek(&three, at + 8)) != physical) continue; var search = at + 11; - while (!matches(&floppy.tracks[3], search, &data_prologue)) search += 1; + while (!matches(&three, search, &data_prologue)) search += 1; break search + data_prologue.len; } else null; var field: [343]u8 = undefined; encodeSector(&replacement, &field); - for (field, 0..) |nibble, i| floppy.tracks[3][(found.? + i) % nibbles_per_track] = nibble; + for (field, 0..) |nibble, i| floppy.writeNibbleAt(3, where[found.? + i], nibble); // Saving reads the surface back, so the new bytes land in the file at the // sector the skew says that place on the track belongs to. @@ -948,7 +1327,7 @@ test "a track the machine has scribbled over keeps what could still be read" { try floppy.load(image, .dos); // Wipe a stretch of the track, as a half finished write would. - @memset(floppy.tracks[7][0..2000], 0xff); + @memset(floppy.tracks[7].bits[0..2000], 0xff); const saved = try testing.allocator.alloc(u8, image_size); defer testing.allocator.free(saved); @@ -1024,10 +1403,10 @@ test "a recording of the surface goes in as it stands and comes back the same" { } try floppy.loadNibbles(&image); - try testing.expectEqual(image[0], floppy.tracks[0][0]); + try testing.expectEqual(image[0], floppy.nibbleAt(0, 0)); try testing.expectEqual( image[nibbles_per_track * 34 + 100], - floppy.tracks[34][100], + floppy.nibbleAt(34, 100), ); var back: [Floppy.nibble_size]u8 = undefined; @@ -1050,7 +1429,11 @@ test "a nibble image a drive can actually read" { var recorded: Floppy = .{}; try recorded.loadNibbles(&nibbles); - try testing.expectEqualSlices(u8, &described.tracks[17], &recorded.tracks[17]); + var a: [nibbles_per_track]u8 = undefined; + var b: [nibbles_per_track]u8 = undefined; + described.takeNibbles(17, &a); + recorded.takeNibbles(17, &b); + try testing.expectEqualSlices(u8, &a, &b); // And it decodes back to the sectors it started as, which is the drive's // own decoder finding the address and data fields in what came off the @@ -1074,3 +1457,121 @@ test "a file that is not a whole recording is refused" { try testing.expectEqual(@as(usize, 35 * 6656), Floppy.nibble_size); try testing.expectEqual(@as(usize, 232_960), Floppy.nibble_size); } + +test "a track laid out here is longer in bits than its bytes would suggest" { + // Because the gaps are self-sync: `$ff` and two bits of nothing, ten bits + // to the byte. A track of the same bytes written eight bits each would be + // shorter, and would be unreadable by anything that had lost its place. + const image = try testing.allocator.alloc(u8, image_size); + defer testing.allocator.free(image); + @memset(image, 0); + const floppy = try testing.allocator.create(Floppy); + defer testing.allocator.destroy(floppy); + floppy.* = .{}; + try floppy.load(image, .dos); + + const track = &floppy.tracks[0]; + var nibbles: [nibbles_per_track]u8 = undefined; + floppy.takeNibbles(0, &nibbles); + + // Count the bytes the shifter got back, and compare with the bits it took + // to deliver them. More than eight bits apiece means self-sync is there. + var real: usize = nibbles_per_track; + while (real > 0 and nibbles[real - 1] == sync) real -= 1; + try testing.expect(track.count > real * 8); +} + +test "a reader that has lost its place is put back by the gaps" { + // The whole point of a self-sync byte. Start the shifter one bit late — + // which is what a head being put down in the middle of a byte does — and + // it should come back into step, because the extra zero bits in a gap + // push it along by less than a whole byte at a time. + const image = try testing.allocator.alloc(u8, image_size); + defer testing.allocator.free(image); + @memset(image, 0); + const floppy = try testing.allocator.create(Floppy); + defer testing.allocator.destroy(floppy); + floppy.* = .{}; + try floppy.load(image, .dos); + const track = &floppy.tracks[0]; + + var latch: u8 = 0; + var recent: [3]u8 = @splat(0); + var marks: usize = 0; + // Deliberately off by one bit, and round twice so that the first sector + // comes past after the head has had a gap to find itself in. + var at: u32 = 1; + while (at < track.count * 2 + 1) : (at += 1) { + latch = (latch << 1) | track.bit(at); + if (latch & 0x80 == 0) continue; + recent = .{ recent[1], recent[2], latch }; + latch = 0; + if (std.mem.eql(u8, &recent, &address_prologue)) marks += 1; + } + // All sixteen sectors turn up, which they could not if the reader had + // stayed a bit out of step. + try testing.expect(marks >= sectors_per_track); +} + +test "a WOZ keeps its own track lengths and its own map" { + // Which is the whole reason for the format: a track is however many bits + // went past in one revolution, and what is at a quarter-track position is + // the file's business rather than a matter of dividing by two. + var file: [4096]u8 = undefined; + @memset(&file, 0); + @memcpy(file[0..8], &woz.woz2_magic); + @memcpy(file[12..16], "INFO"); + std.mem.writeInt(u32, file[16..20], 60, .little); + file[20] = 2; + file[21] = 1; // 5.25-inch + @memcpy(file[80..84], "TMAP"); + std.mem.writeInt(u32, file[84..88], woz.positions, .little); + @memset(file[88..][0..woz.positions], woz.no_track); + file[88] = 0; // track 0.00 only; everything else is empty + @memcpy(file[248..252], "TRKS"); + std.mem.writeInt(u32, file[252..256], 1280 + 512, .little); + std.mem.writeInt(u16, file[256..258], 3, .little); + std.mem.writeInt(u16, file[258..260], 1, .little); + std.mem.writeInt(u32, file[260..264], 3000, .little); // an odd length on purpose + @memset(file[1536..][0..512], 0xa5); + std.mem.writeInt(u32, file[8..12], std.hash.Crc32.hash(file[woz.header_size..2048]), .little); + + const floppy = try testing.allocator.create(Floppy); + defer testing.allocator.destroy(floppy); + floppy.* = .{}; + try floppy.loadWoz(try woz.open(file[0..2048])); + + // The track is three thousand bits, not a round number of bytes and not + // padded out to one. + try testing.expectEqual(@as(u32, 3000), floppy.tracks[0].count); + try testing.expectEqual(@as(u8, 0), floppy.map[0]); + // And the gap between tracks is empty, which is what the file says and + // what a described disk cannot say at all. + try testing.expectEqual(nothing_there, floppy.map[2]); + try testing.expectEqual(nothing_there, floppy.map[4]); +} + +test "a head over nothing reads nothing a drive could use" { + // Between two tracks there is no recording, and the amplifier hears its + // own noise. Firmware looking for an address field there finds none, which + // is how a disk that checks for an empty half track knows it is genuine. + var floppy: Floppy = .{}; + floppy.map = @splat(nothing_there); + + var controller: Controller = .{}; + controller.fitted = 1; + controller.insert(0, &floppy); + controller.motor = true; + + var recent: [3]u8 = @splat(0); + var marks: usize = 0; + var cycles: u64 = 0; + for (0..20_000) |_| { + cycles += 4; + const value = controller.readNibble(cycles); + if (value & 0x80 == 0) continue; + recent = .{ recent[1], recent[2], value }; + if (std.mem.eql(u8, &recent, &address_prologue)) marks += 1; + } + try testing.expectEqual(@as(usize, 0), marks); +} diff --git a/src/diskfile.zig b/src/diskfile.zig index 572cf15..39e5388 100644 --- a/src/diskfile.zig +++ b/src/diskfile.zig @@ -21,10 +21,11 @@ const std = @import("std"); const disk2 = @import("disk2.zig"); +const wozfmt = @import("woz.zig"); const shrinkit = @import("shrinkit.zig"); const twomg = @import("twomg.zig"); -pub const Error = twomg.Error || shrinkit.Error || std.mem.Allocator.Error; +pub const Error = twomg.Error || shrinkit.Error || wozfmt.Error || std.mem.Allocator.Error; /// A disk, and whatever had to be allocated to get at it. pub const Opened = struct { @@ -45,6 +46,19 @@ pub const Opened = struct { /// used, unless the file was an archive — in which case the disk is somewhere /// else and `owned` says so. pub fn open(gpa: std.mem.Allocator, bytes: []u8, path: []const u8) Error!Opened { + if (wozfmt.looksLike(bytes)) { + // Checked here rather than taken on trust: what comes back points into + // the caller's bytes, so anything wrong with them is wrong with the + // disk, and a WOZ says outright whether it survived the journey. + _ = try wozfmt.open(bytes); + return .{ .image = .{ + .data = bytes, + .format = .woz, + .write_protected = false, + .volume_number = null, + .blocks = 0, + } }; + } if (!shrinkit.looksLike(bytes)) { var image = try twomg.openOrBare(bytes, path); // A bare file the size of a drive's own idea of a disk is a recording @@ -93,6 +107,8 @@ pub fn explain(err: anyerror) []const u8 { error.Corrupt => "that archive does not make sense partway through", error.NotTwoImg, error.NotAnArchive => "that file is not a disk image", error.Truncated => "that file stops in the middle", + error.NotAWoz => "that file is not a disk image", + error.Mangled => "that WOZ has been through something that thought it was text", error.NibbleImage => "that is a recording of a disk's surface, and only a 5.25-inch drive takes one", else => @errorName(err), }; diff --git a/src/iwm.zig b/src/iwm.zig index 8546717..8df8e4c 100644 --- a/src/iwm.zig +++ b/src/iwm.zig @@ -427,8 +427,11 @@ test "the disk port reads what is going past the head" { // data register, and read until something recognisable goes by. var iwm: Iwm = .{}; var floppy: disk2.Floppy = .{}; - @memset(&floppy.tracks[0], 0xff); - floppy.tracks[0][100] = 0xd5; + var laid: [disk2.nibbles_per_track]u8 = @splat(0xff); + laid[100] = 0xd5; + var whole: [disk2.Floppy.nibble_size]u8 = @splat(0xff); + @memcpy(whole[0..laid.len], &laid); + try floppy.loadNibbles(&whole); iwm.drives.insert(0, &floppy); _ = iwm.access(0xe, false, 0, 0); // Q7 low diff --git a/src/main.zig b/src/main.zig index 20351ab..f8e7e41 100644 --- a/src/main.zig +++ b/src/main.zig @@ -568,6 +568,18 @@ fn parseArgs(args: std.process.Args, io: std.Io, gpa: std.mem.Allocator) ?Option /// The clock the run mode paces itself against. Monotonic, so that changing /// the system time does not make the processor lurch. +/// How big a file naming a disk may be. +/// +/// Sized by the largest of the four kinds rather than by the smallest, which +/// is a WOZ: a recording of the bits is bigger than a description of the +/// sectors, and a limit that fitted a `.dsk` turned a perfectly good WOZ into +/// "stream too long". +const disk_file_limit = @max( + disk2.image_size, + disk2.Floppy.nibble_size, + zig65.woz.max_file_size, +) + zig65.twomg.header_size + 1; + const pacing_clock: std.Io.Clock = .awake; /// What a byte on the text page means. It is not ASCII: the Apple II keeps @@ -1602,7 +1614,7 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { // than the disk in it only by luck; the limit is the archive's // and the disk that comes out is checked against its own size // by the drive. - const file = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.alloc, .limited(disk2.image_size + zig65.twomg.header_size + 1)); + const file = try std.Io.Dir.cwd().readFileAlloc(self.io, path, self.alloc, .limited(disk_file_limit)); defer self.alloc.free(file); const opened = try zig65.diskfile.open(self.alloc, file, path); defer opened.deinit(self.alloc); @@ -1610,7 +1622,12 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { const floppy = try self.alloc.create(disk2.Floppy); errdefer self.alloc.destroy(floppy); floppy.* = .{}; - if (image.isNibble()) { + if (image.isWoz()) { + // The bits themselves, track lengths and all, which is the + // only form that keeps what the timing-based protections + // are made of. + try floppy.loadWoz(try zig65.woz.open(image.data)); + } else if (image.isNibble()) { // A recording of the surface rather than a description of // the sectors on it, which is how a disk that was // protected survives at all: it goes in as it stands and @@ -1669,9 +1686,7 @@ fn Debugger(comptime machine: Machine, comptime processor: Processor) type { const path = self.disk_paths[drive] orelse return; if (!floppy.dirty or floppy.write_protected) return; - const limit = @max(disk2.image_size, disk2.Floppy.nibble_size) + - zig65.twomg.header_size + 1; - const file = std.Io.Dir.cwd().readFileAlloc(self.io, path, self.alloc, .limited(limit)) catch { + const file = std.Io.Dir.cwd().readFileAlloc(self.io, path, self.alloc, .limited(disk_file_limit)) catch { self.say(drive, "cannot re-read {s}", .{std.fs.path.basename(path)}); return; }; diff --git a/src/memory/apple2e.zig b/src/memory/apple2e.zig index 5cd9f1c..f254819 100644 --- a/src/memory/apple2e.zig +++ b/src/memory/apple2e.zig @@ -2083,13 +2083,28 @@ test "the card's switches are the sixteen at $c0e0" { } try testing.expectEqual(@as(u8, 4), cpu.memory.disk.drive(0).track()); - // Reading the data register hands back what is going past the head, which - // on a formatted disk is only ever a byte the surface can hold. + // Reading the data register hands back the shifter, which holds a whole + // byte only once the top bit has come round. Until then it is a partial + // byte with that bit clear, which is precisely what the ROM's read loop + // waits to stop seeing: `LDA $C08C,X` and `BPL` back to itself. + // + // What comes out is not all legal nibbles, and should not be. A head that + // has just been put down is not in step with the disk, so the first bytes + // it assembles are two neighbours smeared together — and then it meets a + // gap, whose self-sync bytes are ten bits long, and the extra bits push it + // back into step. So the thing to look for is not that every byte is + // clean; it is that the marks a sector begins with turn up, which is what + // the ROM is looking for too. _ = cpu.memory.read(u8, 0xc0ee); - for (0..64) |_| { + var recent: [3]u8 = @splat(0); + var marks: usize = 0; + for (0..200_000) |_| { const nibble = cpu.memory.read(u8, 0xc0ec); - try testing.expect(nibble & 0x80 != 0); + if (nibble & 0x80 == 0) continue; + recent = .{ recent[1], recent[2], nibble }; + if (std.mem.eql(u8, &recent, &[_]u8{ 0xd5, 0xaa, 0x96 })) marks += 1; } + try testing.expect(marks > 0); // And the write protect answer comes back the way the ROM asks for it. _ = cpu.memory.read(u8, 0xc0ed); diff --git a/src/memory/apple2plus.zig b/src/memory/apple2plus.zig index a7afd18..90b1949 100644 --- a/src/memory/apple2plus.zig +++ b/src/memory/apple2plus.zig @@ -1243,8 +1243,28 @@ test "a II Plus has nothing of its own in the slot pages" { _ = cpu.memory.read(u8, 0xc0e9); try testing.expect(cpu.memory.disk.motor); + // Reading the data register hands back the shifter, which holds a whole + // byte only once the top bit has come round. Until then it is a partial + // byte with that bit clear, which is precisely what the ROM's read loop + // waits to stop seeing: `LDA $C08C,X` and `BPL` back to itself. + // + // What comes out is not all legal nibbles, and should not be. A head that + // has just been put down is not in step with the disk, so the first bytes + // it assembles are two neighbours smeared together — and then it meets a + // gap, whose self-sync bytes are ten bits long, and the extra bits push it + // back into step. So the thing to look for is not that every byte is + // clean; it is that the marks a sector begins with turn up, which is what + // the ROM is looking for too. _ = cpu.memory.read(u8, 0xc0ee); - for (0..64) |_| try testing.expect(cpu.memory.read(u8, 0xc0ec) & 0x80 != 0); + var recent: [3]u8 = @splat(0); + var marks: usize = 0; + for (0..200_000) |_| { + const nibble = cpu.memory.read(u8, 0xc0ec); + if (nibble & 0x80 == 0) continue; + recent = .{ recent[1], recent[2], nibble }; + if (std.mem.eql(u8, &recent, &[_]u8{ 0xd5, 0xaa, 0x96 })) marks += 1; + } + try testing.expect(marks > 0); } test "a II Plus reads back forty columns and knows only three modes" { diff --git a/src/root.zig b/src/root.zig index c03da6c..bb24227 100644 --- a/src/root.zig +++ b/src/root.zig @@ -47,6 +47,9 @@ pub const parallel = @import("parallel.zig"); /// Sound written to a file, which is how either front end is listened to. pub const wav = @import("wav.zig"); +/// WOZ: a disk written down as the bits that go past the head. +pub const woz = @import("woz.zig"); + /// ShrinkIt archives, which is how an Apple II disk usually arrives. pub const shrinkit = @import("shrinkit.zig"); @@ -227,6 +230,7 @@ test { _ = parallel; _ = wav; _ = shrinkit; + _ = woz; _ = diskfile; _ = cassette; _ = serial; diff --git a/src/twomg.zig b/src/twomg.zig index e8e5fd3..0832cdb 100644 --- a/src/twomg.zig +++ b/src/twomg.zig @@ -52,6 +52,10 @@ pub const Format = enum(u32) { /// The nibbles as they come off the head, already encoded. A drive takes /// these as they are: see `disk2.Floppy.loadNibbles`. nibble = 2, + /// Not a 2IMG format at all: what `diskfile` marks a WOZ with, since a + /// recording of the bits is a fourth kind of thing and the enum is where + /// the kinds are named. + woz = 3, _, }; @@ -85,6 +89,11 @@ pub const Image = struct { return self.format == .nibble; } + /// Whether this is a recording of the bits themselves. + pub fn isWoz(self: Image) bool { + return self.format == .woz; + } + /// Which sector order to read the data in, for anything that wants one. /// A nibble image is neither, and says so. pub fn order(self: Image) ?disk2.Order { diff --git a/src/woz.zig b/src/woz.zig new file mode 100644 index 0000000..b9a7e35 --- /dev/null +++ b/src/woz.zig @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! WOZ, which is a disk written down as the bits that go past the head. +//! +//! Every other disk format here describes a disk. A `.dsk` says what sectors +//! are on it; a `.nib` says what nibbles the drive would read. WOZ says what is +//! actually *on the surface*: the bit cells, in order, as many of them as that +//! track happens to hold. It came out of the Applesauce project in 2018, and it +//! exists because the formats above it all throw away the thing copy protection +//! was built on. +//! +//! What they throw away is timing and shape. A track is not a fixed number of +//! bytes — it is however many bit cells go past in one revolution, which +//! depends on how fast the disk was spinning when it was written. Self-sync +//! bytes are ten bits long rather than eight, so a reader that has lost its +//! place finds it again. Some disks have a track between two tracks, or one +//! track that is two tracks wide, or a run of bits that reads differently every +//! time because there is nothing recorded there at all and the drive's +//! amplifier is listening to noise. None of that can be written in a file of +//! sectors, and all of it is what a protected disk is made of. +//! +//! ## The file +//! +//! Twelve bytes of header — `WOZ1` or `WOZ2`, then `$ff` and a line ending, so +//! that a file mangled by a text-mode transfer says so — a CRC of everything +//! after it, and then chunks: four characters, a length, and that many bytes. +//! Three matter. +//! +//! **INFO** says what kind of disk it is, whether it was write protected, and +//! from version 2 how long a bit cell is. **TMAP** is a hundred and sixty +//! bytes, one per quarter track, saying which recorded track the head finds at +//! that position — or `$ff`, meaning nothing is there, which is what the gap +//! between two tracks reads as. **TRKS** holds the tracks themselves, and is +//! the one place the two versions differ: version 1 gives every track a fixed +//! 6,656 bytes, and version 2 gives each one a run of 512-byte blocks and says +//! where it starts. +//! +//! Both say how many *bits* the track is, which is the number that matters. The +//! bytes are only how the bits are carried. + +const std = @import("std"); + +/// The twelve bytes at the front. The `$ff` and the line ending are a check +/// that the file has not been through anything that thought it was text: a +/// transfer that stripped the high bit or turned `\n` into `\r\n` shows up +/// here rather than as a disk that almost works. +pub const header_size = 12; +pub const woz1_magic = [_]u8{ 'W', 'O', 'Z', '1', 0xff, 0x0a, 0x0d, 0x0a }; +pub const woz2_magic = [_]u8{ 'W', 'O', 'Z', '2', 0xff, 0x0a, 0x0d, 0x0a }; + +/// How many quarter-track positions the map has. A 5.25-inch drive can put its +/// head at any of them; what it finds there is the map's business. +pub const positions = 160; + +/// What a position holds when it holds nothing, which is the ordinary state of +/// the gap between two tracks. +pub const no_track: u8 = 0xff; + +/// How long a track can be, in bytes of bit stream. +/// +/// A 5.25-inch track is about 50,000 bits — six and a quarter kilobytes — and +/// the longest in the reference images is 51,483. Fourteen blocks is generous +/// and is what version 2 would allocate for anything longer than thirteen. +pub const max_track_bytes = 14 * 512; + +/// The largest a WOZ worth reading can be: every quarter-track position +/// holding a track of its own, and room over for the chunks around them. +/// Nothing real comes close — a 5.25-inch image is a quarter of a megabyte — +/// but a limit has to be somewhere and this is where the format's own numbers +/// put it. +pub const max_file_size = positions * max_track_bytes + 64 * 1024; + +pub const Version = enum { woz1, woz2 }; + +pub const DiskType = enum(u8) { + five_and_a_quarter = 1, + three_and_a_half = 2, + _, +}; + +pub const Error = error{ + /// Not a WOZ at all. + NotAWoz, + /// A WOZ whose header says it has been through something that thought it + /// was text. + Mangled, + /// It stops in the middle of something. + Truncated, + /// The CRC in the header does not match what follows it. + BadCrc, + /// A WOZ this cannot use: a 3.5-inch disk, or a track longer than a + /// 5.25-inch drive could hold. + Unsupported, +}; + +/// One track: the bits, and how many of them are the track. +/// +/// The byte count is not the track length. A track of 51,483 bits is 6,436 +/// bytes of which the last one is half used, and reading past the bit count +/// into the rest of that byte would put four bits of nothing into the middle of +/// the stream every revolution. +pub const Track = struct { + bits: []const u8, + count: u32, +}; + +/// What the INFO chunk says. +pub const Info = struct { + version: u8 = 1, + disk_type: DiskType = .five_and_a_quarter, + write_protected: bool = false, + /// Whether the tracks were written in one pass with the head timing kept, + /// which is what makes a cross-track check work. + synchronized: bool = false, + /// Whether the noise a drive makes over unrecorded surface was taken out + /// and left as a run of zero bits, which is what a reader has to put back. + cleaned: bool = false, + creator: []const u8 = "", + /// How long a bit cell is, in units of 125 nanoseconds. Thirty-two is four + /// microseconds, which is what a 5.25-inch drive does; version 1 does not + /// say and is always that. + bit_timing: u8 = 32, + /// 0 unknown, 1 sixteen sectors, 2 thirteen, 3 both. + boot_format: u8 = 0, +}; + +/// An opened WOZ, which is the caller's bytes with the chunks found in them. +pub const Image = struct { + bytes: []const u8, + version: Version, + info: Info, + /// A hundred and sixty bytes, one per quarter track. + map: []const u8, + /// Where the TRKS chunk's data begins. + trks: usize, + trks_size: usize, + + /// Which recorded track the head finds at a quarter-track position, or + /// nothing. + pub fn at(self: Image, position: u8) ?u8 { + if (position >= self.map.len) return null; + const which = self.map[position]; + return if (which == no_track) null else which; + } + + /// One recorded track. + pub fn track(self: Image, which: u8) Error!Track { + switch (self.version) { + // Every track a fixed 6,656 bytes: 6,646 of bit stream and then + // how much of it was used, how many bits it is, and where the + // write splice fell. + .woz1 => { + const slot = 6656; + const at_track = self.trks + @as(usize, which) * slot; + if (at_track + slot > self.bytes.len) return error.Truncated; + const count = std.mem.readInt(u16, self.bytes[at_track + 6648 ..][0..2], .little); + return .{ .bits = self.bytes[at_track..][0..6646], .count = count }; + }, + // An eight byte entry apiece saying where the track is, and the + // bits themselves in whole blocks somewhere after them. + .woz2 => { + const entry = self.trks + @as(usize, which) * 8; + if (entry + 8 > self.bytes.len) return error.Truncated; + const block = std.mem.readInt(u16, self.bytes[entry..][0..2], .little); + const blocks = std.mem.readInt(u16, self.bytes[entry + 2 ..][0..2], .little); + const count = std.mem.readInt(u32, self.bytes[entry + 4 ..][0..4], .little); + if (count == 0) return .{ .bits = &.{}, .count = 0 }; + const from = @as(usize, block) * 512; + const length = @as(usize, blocks) * 512; + if (from + length > self.bytes.len) return error.Truncated; + return .{ .bits = self.bytes[from..][0..length], .count = count }; + }, + } + } +}; + +/// Whether this looks like a WOZ, without committing to it. +pub fn looksLike(bytes: []const u8) bool { + if (bytes.len < header_size) return false; + return std.mem.eql(u8, bytes[0..4], "WOZ1") or std.mem.eql(u8, bytes[0..4], "WOZ2"); +} + +/// Opens a WOZ and finds its chunks. +/// +/// The CRC covers everything after the first twelve bytes, and a zero means the +/// writer did not compute one — which is allowed and which some writers do. A +/// wrong one is refused: a disk image that has been damaged in transit will +/// usually still boot for a while and then do something inexplicable, and that +/// is a far worse afternoon than being told the file is broken. +pub fn open(bytes: []const u8) Error!Image { + if (bytes.len < header_size) return error.NotAWoz; + const version: Version = if (std.mem.eql(u8, bytes[0..4], "WOZ1")) + .woz1 + else if (std.mem.eql(u8, bytes[0..4], "WOZ2")) + .woz2 + else + return error.NotAWoz; + + const expected = switch (version) { + .woz1 => woz1_magic, + .woz2 => woz2_magic, + }; + if (!std.mem.eql(u8, bytes[0..8], &expected)) return error.Mangled; + + const stated = std.mem.readInt(u32, bytes[8..12], .little); + if (stated != 0 and std.hash.Crc32.hash(bytes[header_size..]) != stated) return error.BadCrc; + + var image: Image = .{ + .bytes = bytes, + .version = version, + .info = .{}, + .map = &.{}, + .trks = 0, + .trks_size = 0, + }; + var found_map = false; + + var at: usize = header_size; + while (at + 8 <= bytes.len) { + const id = bytes[at..][0..4]; + const size = std.mem.readInt(u32, bytes[at + 4 ..][0..4], .little); + const from = at + 8; + if (size > bytes.len or from + size > bytes.len) return error.Truncated; + + if (std.mem.eql(u8, id, "INFO")) { + if (size < 37) return error.Truncated; + image.info = .{ + .version = bytes[from], + .disk_type = @enumFromInt(bytes[from + 1]), + .write_protected = bytes[from + 2] == 1, + .synchronized = bytes[from + 3] == 1, + .cleaned = bytes[from + 4] == 1, + // Space padded by the format, and zero padded by at least one + // writer that did not read that part. + .creator = std.mem.trimEnd(u8, bytes[from + 5 ..][0..32], " \x00"), + }; + // Everything from the disk sides onward arrived with version 2 of + // the chunk, and a version 1 file simply does not have it. + if (bytes[from] >= 2 and size >= 40) { + image.info.boot_format = bytes[from + 38]; + image.info.bit_timing = bytes[from + 39]; + } + } else if (std.mem.eql(u8, id, "TMAP")) { + if (size < positions) return error.Truncated; + image.map = bytes[from..][0..positions]; + found_map = true; + } else if (std.mem.eql(u8, id, "TRKS")) { + image.trks = from; + image.trks_size = size; + } + // Anything else — META, WRIT, FLUX — is skipped by its length, which + // is what the format asks a reader to do with what it does not know. + at = from + size; + } + + if (!found_map or image.trks_size == 0) return error.Truncated; + if (image.info.disk_type != .five_and_a_quarter) return error.Unsupported; + return image; +} + +const testing = std.testing; + +/// Builds a WOZ 2 around one track, for the tests that want a whole file. +fn testImage(into: []u8, bit_count: u32, pattern: u8) []u8 { + @memset(into, 0); + @memcpy(into[0..8], &woz2_magic); + + @memcpy(into[12..16], "INFO"); + std.mem.writeInt(u32, into[16..20], 60, .little); + into[20] = 2; // chunk version + into[21] = 1; // 5.25-inch + into[20 + 39] = 32; // four microseconds a bit + @memset(into[25..][0..32], ' '); + @memcpy(into[25..][0..7], "testing"); + + @memcpy(into[80..84], "TMAP"); + std.mem.writeInt(u32, into[84..88], positions, .little); + @memset(into[88..][0..positions], no_track); + into[88] = 0; // track 0.00 is recorded track 0 + + @memcpy(into[248..252], "TRKS"); + std.mem.writeInt(u32, into[252..256], 1280 + 512, .little); + // The first entry: one block, starting at block 3, which is byte 1536. + std.mem.writeInt(u16, into[256..258], 3, .little); + std.mem.writeInt(u16, into[258..260], 1, .little); + std.mem.writeInt(u32, into[260..264], bit_count, .little); + @memset(into[1536..][0..512], pattern); + + const length = 1536 + 512; + std.mem.writeInt(u32, into[8..12], std.hash.Crc32.hash(into[header_size..length]), .little); + return into[0..length]; +} + +test "a WOZ says which of its tracks the head is over" { + var buffer: [4096]u8 = undefined; + const file = testImage(&buffer, 4096, 0xaa); + + const image = try open(file); + try testing.expectEqual(Version.woz2, image.version); + try testing.expectEqual(DiskType.five_and_a_quarter, image.info.disk_type); + try testing.expectEqual(@as(u8, 32), image.info.bit_timing); + try testing.expectEqualStrings("testing", image.info.creator); + + // Track 0.00 is recorded track 0, and every other position is empty — + // which is what the gap between two tracks reads as. + try testing.expectEqual(@as(?u8, 0), image.at(0)); + try testing.expectEqual(@as(?u8, null), image.at(1)); + try testing.expectEqual(@as(?u8, null), image.at(positions - 1)); + + const track = try image.track(0); + try testing.expectEqual(@as(u32, 4096), track.count); + try testing.expectEqual(@as(usize, 512), track.bits.len); + try testing.expectEqual(@as(u8, 0xaa), track.bits[0]); +} + +test "a file that is not a WOZ, and one that has been through a text transfer" { + var bare: [64]u8 = @splat(0); + try testing.expectError(error.NotAWoz, open(&bare)); + try testing.expect(!looksLike(&bare)); + + // The magic is there and the guard bytes are not, which is exactly what a + // transfer that stripped the high bit or fixed up the line endings leaves + // behind. Saying so beats a disk that almost works. + var mangled: [4096]u8 = undefined; + const file = testImage(&mangled, 4096, 0x55); + try testing.expect(looksLike(file)); + file[4] = 0x7f; + try testing.expectError(error.Mangled, open(file)); +} + +test "a damaged WOZ is refused rather than half read" { + var buffer: [4096]u8 = undefined; + const file = testImage(&buffer, 4096, 0x55); + file[2000] ^= 0xff; + try testing.expectError(error.BadCrc, open(file)); + + // A CRC of zero means the writer did not compute one, which is allowed. + std.mem.writeInt(u32, file[8..12], 0, .little); + _ = try open(file); +} + +test "a 3.5-inch WOZ is refused by name" { + // The format covers both drives and this is a Disk II. A IIgs's 800K drive + // is a different mechanism with a different encoding, and quietly reading + // one as a 5.25 would produce a disk that is nothing but noise. + var buffer: [4096]u8 = undefined; + const file = testImage(&buffer, 4096, 0x55); + file[21] = 2; + std.mem.writeInt(u32, file[8..12], std.hash.Crc32.hash(file[header_size..]), .little); + try testing.expectError(error.Unsupported, open(file)); +} diff --git a/tools/gs.zig b/tools/gs.zig index 7a10a00..1730bfe 100644 --- a/tools/gs.zig +++ b/tools/gs.zig @@ -212,8 +212,11 @@ const App = struct { // A recording of a surface is a 5.25-inch disk and nothing else: the // format is thirty-five tracks of what a Disk II's head saw, and an // 800K drive's head sees something else entirely. - if (image.isNibble()) { - try self.floppy.loadNibbles(image.data); + if (image.isWoz() or image.isNibble()) { + if (image.isWoz()) + try self.floppy.loadWoz(try zig65.woz.open(image.data)) + else + try self.floppy.loadNibbles(image.data); self.floppy.write_protected = image.write_protected; self.cpu.memory.iwm.drives.insert(0, self.floppy); self.slots[1].set(path);