// 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 (Morris, 2018). 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, /// Writing a track back found it a different length than it was read as, /// which a drive's own writes cannot cause and so is a bug. LengthChanged, }; /// 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, /// The same again for tracks recorded as flux rather than as bits, which /// arrived with version 2.1. Empty when the file has none, which is almost /// all of them. flux: []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; } /// Which flux-recorded track the head finds at a position, or nothing. /// /// The format asks for this to be looked at first: "if a WOZ file hasn't /// been created properly and a single track has valid entries in both the /// 'TMAP' and 'FLUX' maps, the 'FLUX' one should be used." pub fn fluxAt(self: Image, position: u8) ?u8 { if (position >= self.flux.len) return null; const which = self.flux[position]; return if (which == no_track) null else which; } /// One recorded track. /// /// For a track named by the flux map rather than the track map, `count` is /// a count of bytes rather than of bits: the format says so, and says the /// TRKS chunk is otherwise unchanged. `fluxToBits` turns those bytes into /// the bits a drive would have read. 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 any track is recorded as flux rather than as bits. Write-back /// cannot put flux back — a drive reads it as bits and there is no encoder /// the other way — so a file with any is refused rather than half-written. pub fn hasFlux(self: Image) bool { for (self.flux) |which| if (which != no_track) return true; return false; } /// Writes a recorded track's bits back into a mutable copy of the file /// this image was opened from. /// /// `into` is that copy, the same bytes `open` was given; the track's stored /// bits are found by where `track` pointed into them. A drive cannot have /// changed a track's length — its head steps modulo the bit count — so a /// `bits` of a different length than the track holds is a bug and refused /// rather than written as a resize this format's in-place slot cannot take. /// A position with nothing recorded, or a track of no bits, is left alone. pub fn patch(self: Image, into: []u8, position: u8, bits: []const u8) Error!void { const which = self.at(position) orelse return; const found = try self.track(which); if (found.count == 0) return; if (bits.len != (found.count + 7) / 8) return error.LengthChanged; const offset = @intFromPtr(found.bits.ptr) - @intFromPtr(self.bytes.ptr); @memcpy(into[offset..][0..bits.len], bits); } }; /// Recomputes the header CRC over everything after it, for a file whose chunks /// have been edited in place. The CRC covers all the bytes past the twelve-byte /// header (WozIO Reference, "The Header"). pub fn reChecksum(bytes: []u8) void { std.mem.writeInt(u32, bytes[8..12], std.hash.Crc32.hash(bytes[header_size..]), .little); } /// 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; } else if (std.mem.eql(u8, id, "FLUX")) { // "Structured and functions identically to the 'TMAP' chunk", and // a file that says it has one but has not room for it is broken in // the same way a short TMAP is. if (size < positions) return error.Truncated; image.flux = bytes[from..][0..positions]; } // Anything else — META, WRIT — 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; } /// A tick of the flux clock, in nanoseconds. Everything in a flux stream is /// counted in these. pub const tick_nanoseconds = 125; /// Turns a flux stream into the bits a drive would have read off it. /// /// A flux stream is what the head actually saw rather than what a drive made /// of it: "each byte represents a single flux transition and its value is the /// number of ticks since the previous flux transition. A single tick is 125 /// nanoseconds." A byte cannot hold a long gap, so `$ff` means carry on /// counting — "255, 255, 10 should be treated as 255 + 255 + 10 = 520 ticks". /// /// Turning that back into bit cells is what a drive's data separator does, and /// the arithmetic is the same: each gap is however many cells long it comes /// nearest to, the transition falls in the last of them, and the ones before /// it held nothing. Four microseconds is thirty-two ticks, so the format's own /// examples — "101 and 1001 bit sequences at approximately 64 and 96 ticks" — /// come out as one zero then a one, and two zeroes then a one. /// /// Each gap is measured from the transition before it rather than from the /// start of the track, so a drive that was running a little fast or a little /// slow puts every cell slightly out and none of it accumulates. That is why /// this needs no phase-locked loop to chase: the stream re-states where it is /// at every transition. /// /// Returns how many bits were written, which is the track's length. A stream /// that asks for more room than the track has is `error.Truncated` rather than /// a track quietly one lap short, which would read as a disk with a piece /// missing out of the middle of it. pub fn fluxToBits(stream: []const u8, cell: u8, into: []u8) Error!u32 { @memset(into, 0); if (cell == 0) return 0; const capacity: u32 = @intCast(into.len * 8); var bits: u32 = 0; var ticks: u32 = 0; for (stream) |byte| { ticks += byte; // Not a transition yet, just more time. if (byte == 0xff) continue; var cells = (ticks + cell / 2) / cell; // Two transitions closer together than a cell is the surface being // read faster than it was written, and there is still a bit there. if (cells == 0) cells = 1; ticks = 0; if (bits + cells > capacity) return error.Truncated; // Everything up to the last cell held nothing, and the buffer is // already zero. bits += cells - 1; into[bits / 8] |= @as(u8, 0x80) >> @intCast(bits % 8); bits += 1; } return bits; } const testing = std.testing; test "a flux stream becomes the bits a drive would have read" { var bits: [64]u8 = undefined; // The format's own examples. A gap of about thirty-two ticks is one cell // and the transition is in it; sixty-four is a zero and then a one; and // ninety-six is two zeroes and then a one. const stream = [_]u8{ 32, 32, 64, 96, 31, 33 }; const count = try fluxToBits(&stream, 32, &bits); try testing.expectEqual(@as(u32, 1 + 1 + 2 + 3 + 1 + 1), count); var out: [16]u1 = undefined; for (0..count) |i| out[i] = @intCast((bits[i / 8] >> @intCast(7 - i % 8)) & 1); try testing.expectEqualSlices(u1, &.{ 1, 1, 0, 1, 0, 0, 1, 1, 1 }, out[0..count]); } test "a long gap in a flux stream is spelled out in $ff" { var bits: [64]u8 = undefined; // "255, 255, 10 should be treated as 255 + 255 + 10 = 520 ticks", which at // thirty-two ticks to the cell is sixteen cells: fifteen with nothing in // them and then the transition. const stream = [_]u8{ 0xff, 0xff, 10 }; const count = try fluxToBits(&stream, 32, &bits); try testing.expectEqual(@as(u32, 16), count); for (0..15) |i| try testing.expectEqual(@as(u8, 0), (bits[i / 8] >> @intCast(7 - i % 8)) & 1); try testing.expectEqual(@as(u8, 1), (bits[15 / 8] >> @intCast(7 - 15 % 8)) & 1); } test "a flux stream too long for the track says so rather than stopping short" { var bits: [2]u8 = undefined; const stream = [_]u8{32} ** 100; // Sixteen bits of room and a hundred transitions asking to be written. A // track that stopped where the room ran out would read as a disk with a // piece missing out of the middle of it. try testing.expectError(error.Truncated, fluxToBits(&stream, 32, &bits)); } /// 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; reChecksum(into[0..length]); 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; reChecksum(file); try testing.expectError(error.Unsupported, open(file)); } test "a track written back goes into the file it came from, and the CRC follows" { var buffer: [4096]u8 = undefined; const file = testImage(&buffer, 4096, 0xaa); // Overwrite recorded track 0 (at position 0) with a different pattern of // the same length, the way a drive that had rewritten the track would. var fresh: [512]u8 = @splat(0x99); { const image = try open(file); try testing.expect(!image.hasFlux()); try image.patch(file, 0, &fresh); // A position with nothing recorded is left alone rather than refused. try image.patch(file, 1, &fresh); reChecksum(file); } // It re-opens -- so the CRC was made to match -- and reads back the new // bits, with the untouched positions still empty. const image = try open(file); try testing.expectEqual(@as(?u8, 0), image.at(0)); try testing.expectEqual(@as(?u8, null), image.at(1)); const track = try image.track(0); try testing.expectEqual(@as(u32, 4096), track.count); try testing.expectEqual(@as(u8, 0x99), track.bits[0]); try testing.expectEqual(@as(u8, 0x99), track.bits[511]); // A length that does not match the track is refused rather than written. var wrong: [256]u8 = @splat(0); try testing.expectError(error.LengthChanged, image.patch(file, 0, &wrong)); }