D81.java

package libsidplay.components.c1541;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Objects;

/**
 * 1581 image of logical 256-byte sectors. The drive controller supplies physical MFM framing.
 */
public final class D81 extends DiskImage {
    /**
     * Number of logical 256-byte sectors per track, across both heads.
     */
    public static final int SECTORS_PER_TRACK = 40;
    /**
     * Maximum supported logical track number, including extended tracks.
     */
    public static final int MAX_TRACKS = 83;
    /**
     * Cached logical sector payloads in image-file order.
     */
    private byte[] sectors;
    /**
     * Optional error-map byte for each logical sector; null when the image has no error map.
     */
    private byte[] errors;

    /**
     * Create an image of 1581 logical sectors. Physical MFM framing is supplied by the controller.
     *
     * @param name     image file name
     * @param file     open image file
     * @param readOnly true for a read-only attachment
     */
    public D81(String name, RandomAccessFile file, boolean readOnly) {
        super(null, name, file, readOnly);
    }

    @Override
    public Format getFormat() {
        return Format.D81;
    }

    @Override
    public int getSectorsPerTrack(int track) {
        return track >= 1 && track <= tracks ? SECTORS_PER_TRACK : 0;
    }

    @Override
    protected void attach() throws IOException {
        long length = fd.length();
        for (tracks = 80; tracks <= MAX_TRACKS; tracks++) {
            int blocks = tracks * SECTORS_PER_TRACK;
            if (length == blocks * 256L || length == blocks * 257L) {
                sectors = new byte[blocks * 256];
                fd.seek(0);
                fd.readFully(sectors);
                if (length == blocks * 257L) {
                    errors = new byte[blocks];
                    fd.readFully(errors);
                }
                return;
            }
        }
        throw new IOException("Invalid D81 image size: " + length);
    }

    @Override
    public boolean readSector(int track, int sector, byte[] payload) {
        if (!isValidSector(track, sector)) return false;
        System.arraycopy(sectors, ((track - 1) * 40 + sector) * 256, payload, 0, 256);
        return true;
    }

    @Override
    public boolean getDiskSector(int track, int sector, byte[] framed) {
        byte[] payload = new byte[256];
        if (!readSector(track, sector, payload)) return false;
        framed[0] = GCR.DATA_HEADER_START;
        System.arraycopy(payload, 0, framed, 1, 256);
        return true;
    }

    /**
     * Get the image's native error-map value. The controller decides which errors it can represent.
     *
     * @param track  logical track (1-based)
     * @param sector logical sector (0-based)
     * @return error-map value, 1 when no error map is present, or 15 for an invalid sector
     */
    public int sectorError(int track, int sector) {
        if (!isValidSector(track, sector)) return 0x0f;
        return errors == null ? 1 : errors[(track - 1) * 40 + sector] & 255;
    }

    @Override
    public void writeSector(int track, int sector, byte[] payload) throws IOException {
        if (isReadOnly()) throw new IOException("Disk is write protected");
        if (track < 1 || track > MAX_TRACKS || sector < 0 || sector >= 40)
            throw new IOException("Invalid D81 sector: " + track + "/" + sector);
        Objects.checkFromIndexSize(0, SECTOR_BYTES, payload.length);
        int block = (track - 1) * 40 + sector;
        if (track > tracks) {
            byte[] nextSectors = Arrays.copyOf(sectors, track * 40 * 256);
            byte[] nextErrors = errors;
            if (errors != null) {
                nextErrors = Arrays.copyOf(errors, track * 40);
                Arrays.fill(nextErrors, errors.length, nextErrors.length, (byte) 1);
            }
            System.arraycopy(payload, 0, nextSectors, block * 256, 256);
            fd.seek(0);
            fd.write(nextSectors);
            if (nextErrors != null) fd.write(nextErrors);
            fd.setLength(nextSectors.length + (nextErrors == null ? 0 : nextErrors.length));
            // Publish geometry and caches only after every host operation succeeds.
            sectors = nextSectors;
            errors = nextErrors;
            tracks = track;
            return;
        }
        fd.seek(block * 256L);
        fd.write(payload, 0, 256);
        if (errors != null && errors[block] != 1) {
            fd.seek(sectors.length + block);
            fd.write(1);
        }
        System.arraycopy(payload, 0, sectors, block * 256, 256);
        if (errors != null) errors[block] = 1;
    }
}