MFMTrack.java

/*
 * Port of VICE fdd.c, written by Kajtar Zsolt <soci@c64.rulez.org>.
 * Copyright (C) the VICE project. GNU GPL version 2 or later.
 * Reference: VICE d928b850b7ef4c1b1826a6efd175d8eaa80344d8.
 */
package libsidplay.components.c1541;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;

/**
 * Rotating 250 kbit/s MFM surface, with VICE's 1581 head inversion and sector pairing.
 */
final class MFMTrack {
    /**
     * Number of byte cells in one revolution at 250 kbit/s and 300 RPM.
     */
    private static final int TRACK_BYTES = 6250;
    /**
     * Cached MFM byte cells; bit 8 marks a byte with a missing clock bit.
     */
    private final int[] raw = new int[TRACK_BYTES];
    /**
     * Mounted logical sector image, or null when no disk is attached.
     */
    private D81 image;
    /**
     * Physical cylinder, head and byte position (all 0-based), followed by the cached cylinder/head key. A cache key of
     * -1 forces synthesis of the selected surface.
     */
    private int track, head, position, trackHead = -1;
    /**
     * Number of revolutions since the controller last reset the index counter.
     */
    private long indexCount;
    /**
     * Motor state, pending cache writeback and the disk-change latch.
     */
    private boolean motor, dirty, changed = true;

    /**
     * Update the controller's CRC-16-CCITT value with one byte.
     *
     * @param crc   current CRC
     * @param value next byte
     * @return updated unsigned 16-bit CRC
     */
    static int crc(int crc, int value) {
        int result = crc ^ ((value & 255) << 8);
        for (int bit = 0; bit < 8; bit++) result = (result << 1) ^ ((result & 0x8000) != 0 ? 0x1021 : 0);
        return result & 65535;
    }

    /**
     * Attach a logical image and invalidate the synthesized track cache.
     *
     * @param image mounted D81 image
     */
    void attach(D81 image) {
        this.image = image;
        trackHead = -1;
        position = 0;
        dirty = false;
        changed = true;
    }

    /**
     * Flush the cached surface, close the image and latch a disk change.
     *
     * @throws IOException image data could not be written or the file could not be closed
     */
    void detach() throws IOException {
        flush();
        if (image != null) image.close();
        image = null;
        trackHead = -1;
        changed = true;
    }

    int getTrack() {
        return track;
    }

    int getHead() {
        return head;
    }

    boolean isMotorOn() {
        return motor;
    }

    /**
     * Get the disk-change latch, cleared by a seek with media present.
     *
     * @return 1 after a disk change, otherwise 0
     */
    int diskChange() {
        return changed ? 1 : 0;
    }

    /**
     * Read the track-zero sensor.
     *
     * @return 1 at cylinder 0, otherwise 0
     */
    int track0() {
        return track == 0 ? 1 : 0;
    }

    /**
     * Read write protection, including an empty drive.
     *
     * @return 1 when writing is inhibited, otherwise 0
     */
    int writeProtect() {
        return image == null || image.isReadOnly() ? 1 : 0;
    }

    /**
     * Read the index pulse at the start of a revolution.
     *
     * @return 1 during the first 16 byte cells, otherwise 0
     */
    int index() {
        return position < 16 ? 1 : 0;
    }

    long indexCount() {
        return indexCount;
    }

    void resetIndexCount() {
        indexCount = 0;
    }

    /**
     * Select the physical head.
     *
     * @param value head selection; only bit 0 is used
     */
    void selectHead(int value) {
        head = value & 1;
    }

    void setMotor(boolean on) {
        motor = on;
    }

    /**
     * Step the physical head when the motor is running and acknowledge an inserted disk.
     *
     * @param direction zero to step out, nonzero to step in
     */
    void seek(int direction) {
        if (motor) track = Math.max(0, Math.min(83, track + (direction != 0 ? 1 : -1)));
        if (image != null) changed = false;
    }

    /**
     * Advance rotational position when the motor is running. Controller time also advances with the motor off.
     *
     * @param bytes elapsed byte cells
     * @return nonnegative elapsed byte cells consumed by the controller
     */
    long rotate(long bytes) {
        if (bytes <= 0) return 0;
        if (motor) {
            indexCount += (position + bytes) / TRACK_BYTES;
            position = (int) ((position + bytes) % TRACK_BYTES);
        }
        return bytes;
    }

    /**
     * Read one cell from the selected surface and advance rotation.
     *
     * @return byte cell, including its missing-clock marker, or 0 without a running motor or media
     */
    int read() {
        if (!motor) return 0;
        update();
        int result = image == null ? 0 : raw[position];
        rotate(1);
        return result;
    }

    /**
     * Write one cell when the surface is writable and advance rotation.
     *
     * @param value byte cell, including its missing-clock marker
     * @return -1 when the motor is off, otherwise 0
     */
    int write(int value) {
        if (!motor) return -1;
        update();
        if (writeProtect() == 0) {
            raw[position] = value & 511;
            dirty = true;
        }
        rotate(1);
        return 0;
    }

    /**
     * Flush the previous cached surface and synthesize the selected cylinder and head. Each physical 512-byte sector
     * combines two logical 256-byte sectors; head numbering is inverted.
     *
     * @throws UncheckedIOException pending surface data could not be written
     */
    private void update() {
        int selected = track * 2 + head;
        if (selected == trackHead) return;
        try {
            flush();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        trackHead = selected;
        Arrays.fill(raw, 0x4e);
        if (image == null || track >= image.getTracks()) return;
        int p = 32;
        byte[] payload = new byte[256];
        for (int sector = 0; sector < 10; sector++) {
            for (int i = 0; i < 12; i++) raw[p++] = 0;
            for (int i = 0; i < 3; i++) raw[p++] = 0x1a1;
            raw[p++] = 0xfe;
            int c = 0xb230;
            int[] header = {track, head ^ 1, sector + 1, 2};
            for (int b : header) {
                raw[p++] = b;
                c = crc(c, b);
            }
            raw[p++] = c >>> 8;
            raw[p++] = c & 255;
            p += 22;
            for (int i = 0; i < 12; i++) raw[p++] = 0;
            for (int i = 0; i < 3; i++) raw[p++] = 0x1a1;
            raw[p++] = 0xfb;
            c = 0xe295;
            for (int half = 0; half < 2; half++) {
                int logicalSector = (head ^ 1) * 20 + sector * 2 + half;
                image.readSector(track + 1, logicalSector, payload);
                // VICE's FDD synthesizer does not translate D81 error-map bytes into bad MFM CRCs.
                for (byte b : payload) {
                    raw[p++] = b & 255;
                    c = crc(c, b);
                }
            }
            raw[p++] = c >>> 8;
            raw[p++] = c & 255;
            p += 35;
        }
    }

    /**
     * Decode the cached surface, including tracks written by WRITE TRACK, and write logical sectors back.
     *
     * @throws IOException sector data could not be written
     */
    void flush() throws IOException {
        if (!dirty) return;
        if (image == null || image.isReadOnly()) return;
        int cachedTrack = trackHead / 2;
        if (cachedTrack >= D81.MAX_TRACKS) return;
        for (int sector = 0; sector < 10; sector++) {
            int step = 0, d = 0, p = 0;
            byte[] data = new byte[512];
            scan:
            for (int i = 0; i < TRACK_BYTES * 2; i++) {
                int w = raw[p];
                p = (p + 1) % TRACK_BYTES;
                switch (step) {
                    case 0:
                        if (w == 0) step++;
                        continue;
                    case 1:
                        if (w == 0) continue;
                        if (w == 0x1a1) {
                            step++;
                            continue;
                        }
                        break;
                    case 2:
                        if (w == 0x1a1) continue;
                        if (w == 0xfe) {
                            step++;
                            continue;
                        }
                        break;
                    case 3:
                        if (w == cachedTrack) {
                            step++;
                            continue;
                        }
                        break;
                    case 4:
                        if (w == ((trackHead & 1) ^ 1)) {
                            step++;
                            continue;
                        }
                        break;
                    case 5:
                        if (w == sector + 1) {
                            step++;
                            continue;
                        }
                        break;
                    case 6:
                        if (w == 2) {
                            step++;
                            continue;
                        }
                        break;
                    case 7:
                    case 8:
                        step++;
                        continue;
                    case 9:
                        if (w == 0) step++;
                        continue;
                    case 10:
                        if (w == 0) continue;
                        if (w == 0x1a1) {
                            step++;
                            continue;
                        }
                        step = 9;
                        continue;
                    case 11:
                        if (w == 0x1a1) continue;
                        if (w == 0xfb) {
                            step++;
                            continue;
                        }
                        break;
                    case 12:
                        data[d++] = (byte) w;
                        if (d == 512) step++;
                        continue;
                    case 13:
                        step++;
                        continue;
                    case 14:
                        int logical = ((trackHead & 1) ^ 1) * 20 + sector * 2;
                        image.writeSector(cachedTrack + 1, logical, data);
                        image.writeSector(cachedTrack + 1, logical + 1, Arrays.copyOfRange(data, 256, 512));
                        break scan;
                    default:
                        break;
                }
                step = 0;
            }
        }
        dirty = false;
    }
}