DiskImage.java

/*
 * driveimage.c
 *
 * Written by
 *  Andreas Boose <viceteam@t-online.de>
 *
 * This file is part of VICE, the Versatile Commodore Emulator.
 * See README for copyright notice.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307  USA.
 *
 */
package libsidplay.components.c1541;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Support of disk images.
 *
 * @author Ken Händel
 *
 */
public abstract class DiskImage implements AutoCloseable {
    /**
     * Supported disk image encodings.
     */
    public enum Format {D64, D71, D81, G64, NIB, NBZ, NB2}

    /**
     * Size of a logical disk sector, excluding GCR framing.
     */
    public static final int SECTOR_BYTES = 256;
    /**
     * Track containing the directory.
     */
    public static final int DIR_TRACK_1541 = 18;
    /**
     * Minimum tracks of a disk.
     */
    public static final int MIN_TRACKS_1541 = 35;
    /**
     * Maximum tracks of a D64 disk that can be written.
     */
    protected static final int EXT_TRACKS_1541 = 40;
    /**
     * Maximum tracks of a disk that can be accessed.
     */
    protected static final int MAX_TRACKS_1541 = 42;

    /**
     * Standard settings: Number of bytes per track in the speedzones 0-3.
     */
    protected static final int[] RAW_TRACK_SIZE = {6250, 6666, 7142, 7692};
    /**
     * Standard settings: Track (1-42) to a speedzone (0-3) map.
     */
    protected static final int[] SPEED_MAP_1541 = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2,
            2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    /**
     * Size of the GCR data of each track.
     */
    protected int[] trackSize = new int[GCR.MAX_GCR_TRACKS];
    /**
     * Recently attached file handle.
     */
    protected RandomAccessFile fd;
    /**
     * Recently attached file name.
     */
    protected String fileName;
    /**
     * Attach mode read-only.
     */
    protected boolean readOnly;

    /**
     * Media protection flag independent of the file attachment mode.
     */
    private volatile boolean writeProtected;
    /**
     * Track count of this image.
     */
    protected int tracks;
    /**
     * Group Code Recording support.
     */
    protected GCR gcr;
    /**
     * 40 tracks disk image extension policy.
     */
    protected IExtendImageListener extendImageListener;

    /**
     * Create an image owning the supplied file handle.
     *
     * @param gcr      GCR surface data, or null for a logical MFM image
     * @param fileName image file name
     * @param fd       open image file, closed with this image
     * @param readOnly true for a read-only attachment
     */
    protected DiskImage(final GCR gcr, final String fileName, final RandomAccessFile fd, final boolean readOnly) {
        this.gcr = gcr;
        this.fileName = fileName;
        this.fd = fd;
        this.readOnly = readOnly;
    }

    /**
     * Attach a disk image file to the drive.
     *
     * @param gcr  group code recording support
     * @param file file of the image
     * @return disk image
     * @throws IOException disk image file could not be attached
     */
    public static DiskImage attach(final GCR gcr, final File file) throws IOException {
        return open(gcr, file, !file.canWrite());
    }

    /**
     * Open a disk image for host-side readers without requesting write access.
     *
     * @param file disk image file
     * @return image owning an open file handle; close it after use
     * @throws IOException image could not be opened or attached
     */
    public static DiskImage openReadOnly(File file) throws IOException {
        return open(new GCR(), file, true);
    }

    /**
     * Detect an image format from its signature or supported sector-image size.
     *
     * @param file disk image file
     * @return detected image format
     * @throws IOException image cannot be read or its format is unsupported
     */
    public static Format detect(File file) throws IOException {
        try (RandomAccessFile fileData = new RandomAccessFile(file, "r")) {
            return detect(fileData);
        }
    }

    /**
     * Detect the image format and rewind the file after reading its signature.
     *
     * @param fileData open image file
     * @return detected format
     * @throws IOException image cannot be read or its format is unsupported
     */
    private static Format detect(RandomAccessFile fileData) throws IOException {
        byte[] header = new byte[16];
        int count = fileData.read(header);
        fileData.seek(0);
        String magic = new String(header, 0, Math.max(0, count), StandardCharsets.ISO_8859_1);
        if (magic.startsWith(G64.IMAGE_HEADER)) return Format.G64;
        if (magic.startsWith(NIB.IMAGE_HEADER)) return count > 13 && header[13] == 2 ? Format.NB2 : Format.NIB;
        if (NBZ.matches(fileData)) return Format.NBZ;
        long length = fileData.length();
        if (length == 1366L * 256 || length == 1366L * 257) return Format.D71;
        for (int tracks = 80; tracks <= 83; tracks++) {
            if (length == tracks * 40L * 256 || length == tracks * 40L * 257) return Format.D81;
        }
        int sectors = 683;
        for (int track = 35; track <= 42; track++, sectors += 17) {
            if (length == sectors * 256L || length == sectors * 257L) return Format.D64;
        }
        throw new IOException("Unsupported or corrupt disk image (" + length + " bytes)");
    }

    private static DiskImage open(GCR gcr, File file, boolean readOnly) throws IOException {
        RandomAccessFile fd = new RandomAccessFile(file, readOnly ? "r" : "rw");
        try {
            DiskImage image = switch (detect(fd)) {
                case G64 -> new G64(gcr, file.getName(), fd, readOnly);
                case NIB -> new NIB(gcr, file.getName(), fd, readOnly);
                case NBZ -> new NBZ(gcr, file.getName(), fd, readOnly);
                case NB2 -> new NB2(gcr, file.getName(), fd, readOnly);
                case D64 -> new D64(gcr, file.getName(), fd, readOnly);
                case D71 -> new D71(gcr, file.getName(), fd, readOnly);
                case D81 -> new D81(file.getName(), fd, readOnly);
            };
            image.attach();
            return image;
        } catch (IOException | RuntimeException | Error failure) {
            try {
                fd.close();
            } catch (IOException close) {
                failure.addSuppressed(close);
            }
            throw failure;
        }
    }

    /**
     * Attach disk image to drive.
     *
     * @throws IOException error reading disk image
     */
    protected abstract void attach() throws IOException;

    /**
     * Detach disk image from drive.
     *
     * @throws IOException disk image file write error
     */
    public final void detach() throws IOException {
        close();
    }

    @Override
    public void close() throws IOException {
        fd.close();
    }

    /**
     * Get the logical track count.
     *
     * @return number of tracks
     */
    public int getTracks() {
        return tracks;
    }

    /**
     * Get the logical sector count for a track.
     *
     * @param track logical track (1-based)
     * @return sector count, or 0 for a track outside the image
     */
    public int getSectorsPerTrack(int track) {
        return track >= 1 && track <= tracks ? new int[]{17, 18, 19, 21}[SPEED_MAP_1541[track - 1]] : 0;
    }

    /**
     * Check a logical sector against this image's geometry.
     *
     * @param track  logical track (1-based)
     * @param sector logical sector (0-based)
     * @return true if the sector exists
     */
    public boolean isValidSector(int track, int sector) {
        return sector >= 0 && sector < getSectorsPerTrack(track);
    }

    /**
     * Get the logical capacity of all tracks.
     *
     * @return total number of sectors
     */
    public int getSectorCapacity() {
        int total = 0;
        for (int track = 1; track <= tracks; track++) total += getSectorsPerTrack(track);
        return total;
    }

    /**
     * Get the image encoding.
     *
     * @return disk image format
     */
    public abstract Format getFormat();

    /**
     * Read a logical sector without GCR framing bytes.
     *
     * @param track   logical track (1-based)
     * @param sector  logical sector (0-based)
     * @param payload destination for the 256-byte payload
     * @return true if the sector was read
     * @throws IOException image data could not be read
     */
    public boolean readSector(int track, int sector, byte[] payload) throws IOException {
        byte[] framed = new byte[GCR.SECTOR_SIZE];
        if (!isValidSector(track, sector) || !getDiskSector(track, sector, framed)) return false;
        System.arraycopy(framed, 1, payload, 0, SECTOR_BYTES);
        return true;
    }

    /**
     * Write a logical sector to an image that supports direct sector writes.
     *
     * @param track   logical track (1-based)
     * @param sector  logical sector (0-based)
     * @param payload sector data; at least 256 bytes
     * @throws IOException image requires GCR controller writeback, is protected, or cannot be written
     */
    public void writeSector(int track, int sector, byte[] payload) throws IOException {
        throw new IOException("Sector writes require the GCR controller for " + getFormat());
    }

    /**
     * Set policy how to deal with disks up to 40 tracks.
     *
     * @param listener listener to ask about the policy
     */
    public final void setExtendImagePolicy(final IExtendImageListener listener) {
        this.extendImageListener = listener;
    }

    /**
     * Write back unsaved disk image data.
     *
     * @param track dirty track
     * @throws IOException disk image write error
     */
    public void gcrDataWriteback(final int track) throws IOException {
        throw new IOException("Image is not GCR encoded");
    }

    /**
     * Is the image protected by its read-only attachment or explicit media flag?
     *
     * @return true if recording and writeback are inhibited
     */
    public final boolean isReadOnly() {
        return readOnly || writeProtected;
    }

    /**
     * Set media protection independently of the backing file permissions.
     *
     * @param protectedMedia true to inhibit recording and writeback
     */
    public final void setWriteProtected(final boolean protectedMedia) {
        writeProtected = protectedMedia;
    }

    /**
     * Copy a raw full track within the image geometry. Call on the emulation thread or while the drive is stopped so
     * the snapshot is consistent.
     *
     * @param track logical track (1-based)
     * @return copy of the raw GCR track data
     * @throws UnsupportedOperationException image does not provide GCR track data
     */
    public byte[] copyTrackData(int track) {
        throw new UnsupportedOperationException("Image is not GCR encoded");
    }

    /** Size of the GCR surface under the selected physical head. */
    int getHalfTrackSize(int halfTrack, int side) {
        int track = (halfTrack >> 1) - 1;
        int size = trackSize[track + side * 42];
        return size > 0 ? size : RAW_TRACK_SIZE[SPEED_MAP_1541[track]];
    }

    /** Select the ordinary full-track bank, retaining angular position across a seek. */
    void selectHalfTrack(int halfTrack, int side, int oldSize, int newSize) {
        gcr.setHalfTrack(halfTrack + side * 84, oldSize, newSize);
    }

    /** Optional recording support that retains encoder timing rather than overwriting a fixed number of cells. */
    GCR.Recording beginGCRRecording(int halfTrack, int side, long phase) {
        return null;
    }

    boolean hasPendingGCRWrites() {
        return false;
    }

    void flushPendingGCRWrites() throws IOException {
    }

    /** Write the surface under the physical head using this image's supported recording geometry. */
    void gcrHalfTrackWriteback(int halfTrack, int side) throws IOException {
        gcrDataWriteback((halfTrack >> 1) + side * 35);
    }

    /**
     * Legacy upper bound for logical sector counts.
     *
     * @deprecated Use {@link #getSectorCapacity()} and the image geometry instead.
     */
    @Deprecated
    public static final int MAX_OVERALL_SECTORS = 83 * 40;

    /**
     * Read a logical sector with a leading GCR data-block marker.
     *
     * @param track  logical track (1-based)
     * @param sector logical sector (0-based)
     * @param framed destination for the marker and 256-byte payload; at least {@link GCR#SECTOR_SIZE} bytes
     * @return true if the sector was read
     */
    public abstract boolean getDiskSector(int track, int sector, byte[] framed);

    /**
     * Extract a linked file-sector chain, rejecting invalid sectors and cycles.
     *
     * @param file        destination file
     * @param startTrack  first logical track, interpreted as unsigned
     * @param startSector first logical sector, interpreted as unsigned
     * @return true if the complete chain was saved
     * @throws IOException image data could not be read or the destination could not be written
     */
    public final boolean save(File file, byte startTrack, byte startSector) throws IOException {
        boolean[][] visited = new boolean[tracks + 1][];
        for (int t = 1; t <= tracks; t++) visited[t] = new boolean[getSectorsPerTrack(t)];
        try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
            byte[] sector = new byte[SECTOR_BYTES];
            int track = startTrack & 255, number = startSector & 255;
            while (isValidSector(track, number) && !visited[track][number]) {
                visited[track][number] = true;
                if (!readSector(track, number, sector)) return false;
                int nextTrack = sector[0] & 255, nextSector = sector[1] & 255;
                if (nextTrack == 0) {
                    if (nextSector == 0) return false;
                    out.write(sector, 2, nextSector - 1);
                    return true;
                }
                out.write(sector, 2, 254);
                track = nextTrack;
                number = nextSector;
            }
            return false;
        }
    }
}