D64.java

/**
 * D64 disk images.
 *
 * @author Ken Händel
 */
package libsidplay.components.c1541;

import java.io.IOException;
import java.io.RandomAccessFile;

import static libsidplay.components.c1541.DOSErrorCodes.CBMDOS_IPE_READ_ERROR_SYNC;

/**
 * @author Ken Händel
 *
 */
public class D64 extends GCRDiskImage {
    @Override public Format getFormat() { return Format.D64; }

    /**
     * D64 image byte size (35 tracks).
     */
    private static final int D64_FILE_SIZE_35 = 174848;
    /**
     * D64 sector byte size.
     */
    private static final int D64_SECTOR_SIZE = 256;
    /**
     * GCR byte size of a whole sector.
     */
    private static final int GCR_SECTOR_SIZE_WITH_HEADER = 354;
    /**
     * Number of gap bytes between sectors of the speedzones 0-3.
     */
    private static final int[] GAPS_BETWEEN_SECTORS = {9, 12, 17, 8};
    /**
     * Number of sectors per track of the speedzones 0-3.
     */
    private static final int[] SECTOR_MAP_D64 = {17, 18, 19, 21};
    /**
     * Error information for each logical sector of a D64 or D71 image.
     */
    protected byte[] errorInfo;
    /**
     * Whether an error map was present in the attached sector image.
     */
    private boolean errorMapPresent;
    /**
     * Whether the D71 image contains two independently formatted single-sided surfaces.
     */
    protected boolean twoSingleSides;
    /**
     * Disk ID bytes from the second surface of a two-single-sided D71 image.
     */
    protected byte secondId1, secondId2;

    public D64(final GCR gcr, final String fileName, final RandomAccessFile fd, final boolean readOnly) {
        super(gcr, fileName, fd, readOnly);
    }

    /**
     * Detect a 35..42 track D64 or a 70-track D71 image, read optional sector errors, and synthesize its GCR surfaces.
     *
     * @throws IOException disk image file read error
     */
    @Override
    protected void attach() throws IOException {
        long imageFilesize = fd.length();
        int imageBlocks;
        boolean hasErrorinfo;
        if (getFormat() == Format.D71) {
            tracks = 70;
            imageBlocks = 1366;
            if (imageFilesize != 1366L * 256 && imageFilesize != 1366L * 257)
                throw new IOException("Invalid D71 image size");
            hasErrorinfo = imageFilesize == 1366L * 257;
        } else {
            tracks = MIN_TRACKS_1541;
            imageBlocks = D64_FILE_SIZE_35 >> 8;
            while (imageFilesize != imageBlocks * 256L && imageFilesize != imageBlocks * 257L) {
                if (tracks == MAX_TRACKS_1541) throw new IOException("Invalid D64 image size");
                imageBlocks += 17;
                tracks++;
            }
            hasErrorinfo = imageFilesize == imageBlocks * 257L;
        }

        // Optional error bytes follow all logical sector payloads.
        errorMapPresent = hasErrorinfo;
        errorInfo = new byte[imageBlocks];
        if (hasErrorinfo) {
            fd.seek((long) imageBlocks << 8);
            fd.readFully(errorInfo, 0, imageBlocks);
        }

        // set Disk ID
        byte[] sectorBytes = new byte[D64_SECTOR_SIZE];
        readSector(sectorBytes, 0, DIR_TRACK_1541, 0);
        /*
         * Disk ID.
         */
        byte diskID1 = sectorBytes[0xa2];
        byte diskID2 = sectorBytes[0xa3];

        if (getFormat() == Format.D71) {
            twoSingleSides = (sectorBytes[3] & 0x80) == 0;
            readSector(sectorBytes, 0, 53, 0);
            secondId1 = sectorBytes[0xa2];
            secondId2 = sectorBytes[0xa3];
        }

        // Initialize track size and speed zone for all tracks.
        // D64 does not contain speed zone info, therefore, assume common
        // defaults
        for (int track = 1; track <= (getFormat() == Format.D71 ? 70 : MAX_TRACKS_1541); track++) {
            trackSize[gcrTrack(track) - 1] = RAW_TRACK_SIZE[speedZone(track)];
        }

        final byte[] gcrSectorBytes = new byte[GCR.SECTOR_SIZE];
        int trackOffset = 0;
        for (int track = 1; track <= tracks; track++) {
            // Point to the GCR data where the track is located
            final int trackStart = (gcrTrack(track) - 1) * GCR.NUM_MAX_BYTES_TRACK;
            int gcrDataPos = trackStart;

            // Clear the whole track to avoid read errors
            gcr.setTrackData(gcrDataPos, GCR.NUM_MAX_BYTES_TRACK, (byte) 0x55);

            final int speedZone = speedZone(track);
            final int sectorPerTrack = SECTOR_MAP_D64[speedZone];
            final int gap = GAPS_BETWEEN_SECTORS[speedZone];

            for (int sector = 0; sector < sectorPerTrack; sector++) {
                final DOSErrorCodes errorCode = readSector(gcrSectorBytes, 1, track, sector);
                if (errorCode == CBMDOS_IPE_READ_ERROR_SYNC) {
                    // If the data block is not found, the whole track gets
                    // zeroed
                    gcr.setTrackData(trackStart, GCR.NUM_MAX_BYTES_TRACK, (byte) 0x00);
                    break;
                }
                gcr.convertSectorToGCR(gcrSectorBytes, gcrDataPos, headerTrack(track), sector,
                        twoSingleSides && track > 35 ? secondId1 : diskID1,
                        twoSingleSides && track > 35 ? secondId2 : diskID2, errorCode);

                // Point to the GCR data where the next sector is located
                gcrDataPos += gap + GCR_SECTOR_SIZE_WITH_HEADER;
            }

            /*
             * A D64 contains sectors, but no physical angular position for the
             * individual tracks. A real 1541 keeps rotating while the head steps,
             * so consecutively formatted tracks are not perfectly aligned.
             *
             * Match VICE's Dxx-to-GCR conversion: advance by the amount of GCR
             * occupied by the formatted track, excluding the final gap, then add
             * an approximation of the head-step time.
             */
            final int currentTrackSize = trackSize[gcrTrack(track) - 1];
            final int bytesWritten = sectorPerTrack * (GCR_SECTOR_SIZE_WITH_HEADER + gap);

            trackOffset += bytesWritten - gap;
            trackOffset += currentTrackSize * 100 / 270;
            trackOffset %= currentTrackSize;

            /*
             * Circularly rotate the generated track. This changes only its angular
             * position; sector spacing and track length remain unchanged.
             */
            final byte[] trackBytes = gcr.getTrackData(trackStart, currentTrackSize);
            final byte[] skewedTrack = new byte[currentTrackSize];

            System.arraycopy(trackBytes, 0, skewedTrack, trackOffset,
                    currentTrackSize - trackOffset);
            System.arraycopy(trackBytes, currentTrackSize - trackOffset,
                    skewedTrack, 0, trackOffset);

            gcr.setTrackData(skewedTrack, trackStart, currentTrackSize);
        }
    }

    /**
     * Read the sector of the disk image.
     *
     * @param sectorBytes    sector bytes read from track
     * @param sectorBytesPos offset with the start of the sector bytes
     * @param track          track
     * @param sector         sector
     * @return DOS error code of the sector to read
     * @throws IOException error reading disk image
     */
    private DOSErrorCodes readSector(final byte[] sectorBytes, final int sectorBytesPos, final int track,
                                     final int sector) throws IOException {
        int sectorCount = getSectorCount(track, sector);
        fd.seek((long) sectorCount << 8);
        fd.readFully(sectorBytes, sectorBytesPos, D64_SECTOR_SIZE);
        return DOSErrorCodes.valueOf(errorInfo[sectorCount]);
    }

    /**
     * Count sectors up to the given location.
     *
     * @param track  track
     * @param sector sector
     * @return sector number
     */
    protected int getSectorCount(final int track, final int sector) {
        int sectorCount = sector;
        for (int i = 1; i < track; i++) {
            sectorCount += getSectorsPerTrack(i);
        }
        return sectorCount;
    }

    /**
     * Get the recording speed zone for a logical track.
     *
     * @param track logical track (1-based)
     * @return speed zone (0-3)
     */
    protected int speedZone(int track) { return SPEED_MAP_1541[track - 1]; }

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

    @Override
    public void gcrDataWriteback(final int track) throws IOException {
        if (isReadOnly() || track < 1 || track > (getFormat() == Format.D71 ? 70 : EXT_TRACKS_1541)) {
            // D64 tracks 41-42 are read-only; D71 writeback is limited to its 70 logical tracks.
            return;
        }
        int sectorsPerTrack = SECTOR_MAP_D64[speedZone(track)];
        if (track > tracks) {
            // Allowed to extend the disk image to 40 tracks?
            // No one to ask for means yes.
            if (extendImageListener == null || extendImageListener.isAllowed()) {
                driveExtendDiskImage();
            } else {
                // Forbidden by policy
                return;
            }
        }

        // Write back each sector of the track
        for (int sector = 0; sector < sectorsPerTrack; sector++) {
            int gcrDataPos = gcr.findSectorHeaderBits(headerTrack(track), sector, trackSize[gcrTrack(track) - 1]);
            if (gcrDataPos == -1) {
                // Keep the backing sector unchanged when its GCR header is missing.
            } else {
                gcrDataPos = gcr.findSectorDataBits(gcrDataPos, trackSize[gcrTrack(track) - 1]);
                if (gcrDataPos == -1) {
                    System.err.printf("Could not find data sync of T:%d S:%d.\n", track, sector);
                } else {
                    gcrDataWritebackSector(gcrDataPos, track, sector);
                }
            }
        }
    }

    /**
     * Extend disk image to 40 tracks.
     *
     * @throws IOException disk image write error
     */
    private void driveExtendDiskImage() throws IOException {
        int oldBlocks = errorInfo.length;
        tracks = EXT_TRACKS_1541;
        int blocks = getSectorCapacity();
        errorInfo = java.util.Arrays.copyOf(errorInfo, blocks);
        java.util.Arrays.fill(errorInfo, oldBlocks, blocks, (byte) 1);
        fd.seek(oldBlocks * 256L);
        fd.write(new byte[(blocks - oldBlocks) * 256]);
        if (errorMapPresent) {
            fd.seek(blocks * 256L);
            fd.write(errorInfo);
        }
        fd.setLength(blocks * (errorMapPresent ? 257L : 256L));
    }

    /**
     * Write back the dirty sector into the disk image.
     *
     * @param offset offset of the GCR data
     * @param track  track
     * @param sector sector
     * @throws IOException disk image write error
     */
    private void gcrDataWritebackSector(final int offset, final int track, final int sector) throws IOException {
        byte[] sectorBytes = new byte[GCR.SECTOR_SIZE];
        gcr.convertGCRToSectorBits(sectorBytes, offset, trackSize[gcrTrack(track) - 1]);
        if (sectorBytes[0] != GCR.DATA_HEADER_START) {
            System.err.printf("Could not find data block id of T:%d S:%d.\n", track, sector);
        } else {
            writeSector(sectorBytes, 1, track, sector);
        }
    }

    /**
     * Write a sector.
     *
     * @param sectorBytes    sector bytes to write
     * @param sectorBytesPos offset of the sector bytes
     * @param track          track
     * @param sector         sector
     * @throws IOException disk image write error
     */
    private void writeSector(final byte[] sectorBytes, final int sectorBytesPos, final int track, final int sector)
            throws IOException {
        int sectorCount = getSectorCount(track, sector);
        fd.seek((long) sectorCount << 8);
        fd.write(sectorBytes, sectorBytesPos, D64_SECTOR_SIZE);
        if (errorMapPresent && errorInfo[sectorCount] != 1) {
            errorInfo[sectorCount] = 1;
            fd.seek(errorInfo.length * 256L + sectorCount);
            fd.write(1);
        }
    }

}