GCRDiskImage.java

package libsidplay.components.c1541;

import java.io.RandomAccessFile;

/**
 * Sector decoding for the GCR media used by the 1541 and 1571.
 */
public abstract class GCRDiskImage extends DiskImage {
    /**
     * Create a disk image backed by GCR surface data.
     *
     * @param gcr      GCR surface data
     * @param name     image file name
     * @param fd       open image file
     * @param readOnly true for a read-only attachment
     */
    protected GCRDiskImage(GCR gcr, String name, RandomAccessFile fd, boolean readOnly) {
        super(gcr, name, fd, readOnly);
    }

    /**
     * Map a logical image track to its GCR surface bank.
     *
     * @param track logical track (1-based)
     * @return GCR track (1-based), including the second surface's bank offset
     */
    protected int gcrTrack(int track) {
        return track;
    }

    /**
     * Get the track number recorded in the sector header.
     *
     * @param track logical track (1-based)
     * @return track number used to locate the sector header
     */
    protected int headerTrack(int track) {
        return track;
    }

    @Override
    public byte[] copyTrackData(int track) {
        if (track < 1 || track > tracks) throw new IllegalArgumentException("Unsupported track: " + track);
        int index = gcrTrack(track) - 1;
        return gcr.getTrackData(index * GCR.NUM_MAX_BYTES_TRACK, trackSize[index]);
    }

    @Override
    public boolean getDiskSector(int track, int sector, byte[] currSector) {
        // check if the track is within range
        if (track < 1 || track > tracks) {
            return false;
        }
        return gcr.readFromFullTrack(gcrTrack(track), () -> {
            int gcrDataPos = gcr.findSectorHeaderBits(headerTrack(track), sector, trackSize[gcrTrack(track) - 1]);
            if (gcrDataPos == -1) {
                // A missing sector header makes the read fail below.
            } 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);
                    return false;
                } else {
                    gcr.convertGCRToSectorBits(currSector, gcrDataPos, trackSize[gcrTrack(track) - 1]);
                    if (currSector[0] != GCR.DATA_HEADER_START) {
                        System.err.printf("Could not find data block id of T:%d S:%d.\n", track, sector);
                        return false;
                    } else {
                        return true;
                    }
                }
            }
            return false;
        });
    }

}