GCR.java

/**
 * gcr.c - GCR handling.
 * <p>
 * Written by Andreas Boose <viceteam@t-online.de> Daniel Sladic <sladic@eecg.toronto.edu>
 * <p>
 * This file is part of VICE, the Versatile Commodore Emulator. See README for a copyright notice.
 * <p>
 * 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.
 * <p>
 * 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.
 * <p>
 * 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.
 *
 * @author Ken Händel
 *
 **/
package libsidplay.components.c1541;

import java.util.Arrays;
import java.util.function.BooleanSupplier;

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

/**
 *
 * Group Coded Recording.
 *
 * @author Ken Händel
 *
 */
public final class GCR {
    interface Recording {
        void writeBit(boolean value, int density, long referenceClocks);
        void finish(long referenceClocks);
    }

    /**
     * Number of GCR track slots: two surfaces of up to 42 tracks each.
     */
    public static final int MAX_GCR_TRACKS = 84;
    /**
     * Inline full-track bank size; larger G64 records use separate track buffers.
     */
    public static final int NUM_MAX_BYTES_TRACK = 8192;
    /**
     * Byte size of a whole sector.
     */
    public static final int SECTOR_SIZE = 260;
    /**
     * GCR byte size of a whole sector's data.
     */
    private static final int GCR_SECTOR_SIZE_DATA_ONLY = 325;
    /**
     * Begin of sector block header.
     */
    public static final byte BLOCK_HEADER_START = 0x08;
    /**
     * Begin of sector data header.
     */
    public static final byte DATA_HEADER_START = 0x07;
    /**
     * Convert a nybble to GCR code.
     *
     * <PRE>
     * Nybble Code 0000	  01010 0001	  01011 0010	  10010 0011	  10011 0100	  01110 0101	  01111 0110	  10110 0111 10111
     * 1000	  01001 1001	  11001 1010	  11010 1011	  11011 1100	  01101 1101	  11101 1110	  11110 1111	  10101
     * </PRE>
     */
    private static final byte[] TO_GCR = {0x0a, 0x0b, 0x12, 0x13, 0x0e, 0x0f, 0x16, 0x17, 0x09, 0x19, 0x1a, 0x1b, 0x0d,
            0x1d, 0x1e, 0x15};
    /**
     * GCR to byte table.
     */
    private static final byte[] FROM_GCR = {0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 1, 0, 12, 4, 5, 0, 0, 2, 3, 0, 15, 6, 7,
            0, 9, 10, 11, 0, 13, 14, 0};

    /**
     * Complete disk image as GCR data.
     */
    private final byte[] data = new byte[MAX_GCR_TRACKS * NUM_MAX_BYTES_TRACK];
    /** Oversized full tracks are allocated only for records that need them. */
    private final byte[][] largeTrackData = new byte[MAX_GCR_TRACKS][];
    /** Selected full-track bank or a separately recorded half-track buffer. */
    private byte[] currentTrackData = data;
    /** Aligned NB2 samples, advanced only at a complete physical revolution. */
    private byte[][] currentTrackCycles;
    private int currentTrackCycle;
    /**
     * Offset into the selected buffer, the start of the current GCR track data.
     */
    private int dataPos;
    /**
     * Offset of the R/W head on the current track (bits).
     */
    private int gcrHeadOffset;
    /** Cumulative recorded cell weights at byte boundaries; null denotes evenly spaced bits. */
    private int[] currentTrackTiming;
    /** A missing G64 half-track reads its neighbour until the first recording detaches that fallback. */
    private Runnable writePreparation;

    /**
     * Is a disk attached to the disk drive?
     */
    private boolean isDiskAttached = false;

    /**
     * Get GCR data of a whole track.
     *
     * @param trackPos  track offset
     * @param trackSize track size
     * @return GCR data
     */
    byte[] getTrackData(final int trackPos, final int trackSize) {
        final byte[] trackBytes = new byte[trackSize];
        byte[] large = largeTrackData[trackPos / NUM_MAX_BYTES_TRACK];
        System.arraycopy(large == null ? data : large, large == null ? trackPos : trackPos % NUM_MAX_BYTES_TRACK,
                trackBytes, 0, trackSize);
        return trackBytes;
    }

    /**
     * Set GCR data of a whole track.
     *
     * @param trackPos  track offset
     * @param trackSize track size
     * @param byt       GCR value to be used for the whole track
     */
    void setTrackData(final int trackPos, final int trackSize, final byte byt) {
        if (trackPos % NUM_MAX_BYTES_TRACK == 0) largeTrackData[trackPos / NUM_MAX_BYTES_TRACK] = null;
        Arrays.fill(data, trackPos, trackPos + trackSize, byt);
    }

    /**
     * Set GCR data of a whole track.
     *
     * @param trackBytes GCR data of a whole track
     * @param trackPos   track offset
     * @param trackSize  track size
     */
    void setTrackData(final byte[] trackBytes, final int trackPos, final int trackSize) {
        int track = trackPos / NUM_MAX_BYTES_TRACK;
        if (trackSize > NUM_MAX_BYTES_TRACK) {
            if (trackPos % NUM_MAX_BYTES_TRACK != 0) throw new IllegalArgumentException("Unaligned oversized track");
            byte[] large = new byte[trackSize];
            System.arraycopy(trackBytes, 0, large, 0, trackSize);
            largeTrackData[track] = large;
        } else {
            System.arraycopy(trackBytes, 0, data, trackPos, trackSize);
            if (trackPos % NUM_MAX_BYTES_TRACK == 0) largeTrackData[track] = null;
        }
    }

    /** Bytes available in a full-track surface at its bank offset. */
    int getTrackCapacity(int trackPos) {
        byte[] large = largeTrackData[trackPos / NUM_MAX_BYTES_TRACK];
        return large == null ? NUM_MAX_BYTES_TRACK : large.length;
    }

    /**
     * Attach disk.
     */
    void attach() {
        isDiskAttached = true;
    }

    /**
     * Detach disk, reset GCR data.
     */
    void detach() {
        Arrays.fill(data, (byte) 0);
        currentTrackData = data;
        currentTrackCycles = null;
        currentTrackTiming = null;
        writePreparation = null;
        isDiskAttached = false;
    }

    /**
     * Reset GCR data offset.
     */
    void reset() {
        currentTrackData = data;
        currentTrackCycles = null;
        currentTrackTiming = null;
        writePreparation = null;
        dataPos = 0;
        gcrHeadOffset = 0;
    }

    /**
     * Convert the contents of a disk sector to GCR coded bytes. Input is a pre-formatted sector filled with 0x55 bytes
     * (gap data).
     *
     * @param sectorBytes sector data to convert
     * @param off         position of a result
     * @param track       track, where sector is located in
     * @param sector      sector to convert
     * @param diskID1     first byte of the disk ID
     * @param diskID2     second byte of the disk ID
     * @param errorCode   error code
     */
    void convertSectorToGCR(final byte[] sectorBytes, int off, final int track, final int sector,
                            final byte diskID1, final byte diskID2, final DOSErrorCodes errorCode) {
        byte[] buf = new byte[4];

        /* Sync (5 times 0xff) */
        Arrays.fill(data, off, off + 5, (byte) 0xff);
        off += 5;

        byte headerId1 = (byte) (errorCode == CBMDOS_IPE_DISK_ID_MISMATCH ? diskID1 ^ 0xff : diskID1);

        /* GCR block header */

        // Part1:
        // 8 - $08 begin of block header
        // CKS - checksum
        // S - sector number
        // T - track number
        buf[0] = (byte) (errorCode == CBMDOS_IPE_READ_ERROR_BNF ? 0xff : BLOCK_HEADER_START);
        buf[1] = (byte) (sector ^ track ^ diskID2 ^ headerId1);
        buf[2] = (byte) sector;
        buf[3] = (byte) track;

        if (errorCode == CBMDOS_IPE_READ_ERROR_BCHK) {
            buf[1] ^= 0xff;
        }
        convert4BytesToGCR(buf, 0, data, off);
        off += 5;

        // Part2:
        // ID2 - 2nd ASCII-code of disk ID
        // ID1 - 1st ASCII-code of disk ID
        // 0F - unused
        // 0F - unused
        buf[0] = diskID2;
        buf[1] = headerId1;
        buf[2] = 0x0f;
        buf[3] = 0x0f;
        convert4BytesToGCR(buf, 0, data, off);
        off += 5;

        // gap between header and data (9 GCR bytes on a 1541)
        off += 9;

        /* Sync (5 times 0xff) */
        Arrays.fill(data, off, off + 5, (byte) 0xff);
        off += 5;

        /* GCR data */

        // 7 - $07 begin of data header
        // A soft no-block error must start with a zero GCR bit, preserving framing.
        sectorBytes[0] = (byte) (errorCode == CBMDOS_IPE_READ_ERROR_DATA ? 0x00 : DATA_HEADER_START);
        // CKS - checksum
        int chksum = sectorBytes[1];
        for (int i = 2; i < 257; i++) {
            chksum ^= sectorBytes[i];
        }
        sectorBytes[257] = (byte) (errorCode == CBMDOS_IPE_READ_ERROR_CHK ? chksum ^ 0xff : chksum);
        sectorBytes[258] = sectorBytes[259] = 0; // filler???
        // header + 256 bytes data + checksum
        int sectorBytesPos = 0;
        for (int i = 0; i < GCR_SECTOR_SIZE_DATA_ONLY / 5; i++) {
            convert4BytesToGCR(sectorBytes, sectorBytesPos, data, off);
            sectorBytesPos += 4;
            off += 5;
        }
    }

    /**
     * Convert 4 bytes into the GCR coded form (5 bytes).
     *
     * @param source byte array to convert containing 4 bytes.
     * @param srcPos position of a source
     * @param dest   resulting byte array
     * @param dstPos position of dest
     */
    private void convert4BytesToGCR(final byte[] source, int srcPos, final byte[] dest, int dstPos) {
        int idx = 0;

        for (int i = 2; i < 10; i += 2, srcPos++, dstPos++) {
            /* make room for the upper nybble */
            idx <<= 5;
            idx |= TO_GCR[(source[srcPos] & 0xff) >> 4];

            /* make room for the lower nybble */
            idx <<= 5;
            idx |= TO_GCR[source[srcPos] & 0x0f];

            dest[dstPos] = (byte) (idx >> i);
        }

        dest[dstPos] = (byte) idx;
    }

    /**
     * Convert a GCR coded sector into bytes.
     *
     * @param dest      resulting GCR byte array
     * @param dstPos    position of the GCR data containing the sector
     * @param trackSize the track size
     */
    void convertGCRToSector(final byte[] dest, int dstPos, final int trackSize) {
        byte[] header = new byte[5];
        int bufferPos = 0;
        int trackEnd = dataPos + trackSize;
        for (int i = 0; i < GCR_SECTOR_SIZE_DATA_ONLY / 5; i++) {
            for (int j = 0; j < header.length; j++) {
                header[j] = currentTrackData[dstPos++];
                if (dstPos >= trackEnd) {
                    dstPos = dataPos;
                }
            }
            convertGCRTo4Bytes(header, dest, bufferPos);
            bufferPos += 4;
        }
    }

    /**
     * Search for the sector header of the given track and sector in the GCR data.
     *
     * @param track     track where the sector is contained in
     * @param sector    sector to search for
     * @param trackSize the track size
     * @return offset in the GCR data pointing to the sector or -1 (not found)
     */
    int findSectorHeader(final int track, final int sector, final int trackSize) {
        int offset = dataPos;
        byte[] headerAsGCR = new byte[5], header = new byte[4];
        boolean wrapOver = false;
        int syncCount = 0;
        int trackEnd = dataPos + trackSize;
        while (offset < trackEnd && !wrapOver) {
            while (currentTrackData[offset] != (byte) 0xff) {
                offset++;
                if (offset >= trackEnd) {
                    return -1;
                }
            }
            while (currentTrackData[offset] == (byte) 0xff) {
                offset++;
                if (offset == trackEnd) {
                    offset = dataPos;
                    wrapOver = true;
                }
                /* Check for killer tracks. */
                if (++syncCount >= trackSize) {
                    return -1;
                }
            }

            for (int i = 0; i < 5; i++) {
                headerAsGCR[i] = currentTrackData[offset++];
                if (offset >= trackEnd) {
                    offset = dataPos;
                    wrapOver = true;
                }
            }

            convertGCRTo4Bytes(headerAsGCR, header, 0);

            if (header[0] == BLOCK_HEADER_START) {
                /* FIXME: Add some sanity checks here. */
                if (header[2] == sector && header[3] == track) {
                    return offset;
                }
            }
        }
        return -1;
    }

    /**
     * Find sector GCR data starting at the sector header position.
     *
     * @param sectorHeaderPos search start position
     * @param trackSize       the track size
     * @return offset in the GCR data pointing to the sector data or -1 (not found)
     */
    int findSectorData(final int sectorHeaderPos, final int trackSize) {
        int trackEnd = dataPos + trackSize;
        int header = 0;
        int sectorDataPos = sectorHeaderPos;
        while (currentTrackData[sectorDataPos] != (byte) 0xff) {
            sectorDataPos++;
            if (sectorDataPos >= trackEnd) {
                sectorDataPos = dataPos;
            }
            header++;
            if (header >= 500) {
                return -1;
            }
        }

        while (currentTrackData[sectorDataPos] == (byte) 0xff) {
            sectorDataPos++;
            if (sectorDataPos == trackEnd) {
                sectorDataPos = dataPos;
            }
        }
        return sectorDataPos;
    }

    /**
     * Find a sector header at an arbitrary rotational bit position, including track wraparound.
     *
     * @param track     track number recorded in the header
     * @param sector    sector number recorded in the header
     * @param trackSize raw track length in bytes
     * @return bit position after the matching header, or -1 if absent
     */
    int findSectorHeaderBits(int track, int sector, int trackSize) {
        int limit = trackSize * 8;
        int ones = 0;
        for (int bit = 0; bit < limit * 2; bit++) {
            if (trackBit(bit, trackSize) != 0) { ones++; continue; }
            if (ones >= 10) {
                int start = bit % limit;
                if (decodedByte(start, trackSize) == BLOCK_HEADER_START
                        && decodedByte(start + 20, trackSize) == sector
                        && decodedByte(start + 30, trackSize) == track)
                    return (start + 80) % limit;
            }
            ones = 0;
        }
        return -1;
    }

    /**
     * Locate the next data SYNC mark after a sector header, allowing track wraparound.
     *
     * @param headerEnd bit position following the sector header
     * @param trackSize raw track length in bytes
     * @return first data bit after SYNC, or -1 when no data SYNC is found
     */
    int findSectorDataBits(int headerEnd, int trackSize) {
        int ones = 0;
        for (int bit = 0; bit < Math.min(trackSize * 8, 4000); bit++) {
            int position = headerEnd + bit;
            if (trackBit(position, trackSize) != 0) { ones++; continue; }
            if (ones >= 10) return position % (trackSize * 8);
            ones = 0;
        }
        return -1;
    }

    /**
     * Decode a framed sector from an arbitrary rotational bit position.
     *
     * @param dest      destination for the decoded sector
     * @param start     first encoded data bit
     * @param trackSize raw track length in bytes
     */
    void convertGCRToSectorBits(byte[] dest, int start, int trackSize) {
        for (int i = 0; i < SECTOR_SIZE; i++) dest[i] = (byte) decodedByte(start + i * 10, trackSize);
    }

    private int decodedByte(int start, int trackSize) {
        int high = 0, low = 0;
        for (int bit = 0; bit < 5; bit++) {
            high = (high << 1) | trackBit(start + bit, trackSize);
            low = (low << 1) | trackBit(start + 5 + bit, trackSize);
        }
        return (FROM_GCR[high] << 4) | FROM_GCR[low];
    }

    private int trackBit(int position, int trackSize) {
        int bit = position % (trackSize * 8);
        return currentTrackData[dataPos + (bit >> 3)] >> (7 - (bit & 7)) & 1;
    }

    /**
     * Convert 5-byte GCR code to 4-byte.
     *
     * @param source  source buffer containing the 5-byte GCR code.
     * @param dest    target buffer to hold the result
     * @param destPos off set into the target buffer
     */
    private void convertGCRTo4Bytes(final byte[] source, final byte[] dest, final int destPos) {
        /* at least 24 bits for shifting into bits 16...20 */
        int idx = source[0] & 0xff;
        idx <<= 13;

        int sourcePos = 0;
        int off = destPos;
        for (int i = 5; i < 13; i += 2, off++) {
            sourcePos++;
            idx |= (source[sourcePos] & 0xff) << i;

            dest[off] = (byte) ((FROM_GCR[idx >> 16 & 0x1f] & 0xff) << 4);
            idx <<= 5;

            dest[off] |= FROM_GCR[idx >> 16 & 0x1f];
            idx <<= 5;
        }
    }

    int readNextBit(final int currentTrackSize) {
        if (!isDiskAttached) {
            /* if no image is attached, read 0 */
            return 0;
        }
        int byteOffset = gcrHeadOffset >> 3;
        int bitNumber = ~gcrHeadOffset & 7;
        byte gcrData = currentTrackData[dataPos + byteOffset];
        gcrHeadOffset = (gcrHeadOffset + 1) % (currentTrackSize << 3);
        if (gcrHeadOffset == 0 && currentTrackCycles != null) {
            currentTrackCycle = (currentTrackCycle + 1) % currentTrackCycles.length;
            currentTrackData = currentTrackCycles[currentTrackCycle];
        }
        return gcrData >> bitNumber & 1;
    }

    void writeNextBit(final boolean value, final int currentTrackSize) {
        currentTrackCycles = null;
        if (!isDiskAttached) {
            /* if no image is attached, writes do nothing */
            return;
        }
        if (writePreparation != null) {
            Runnable prepare = writePreparation;
            writePreparation = null;
            prepare.run();
        }
        int byteOffset = gcrHeadOffset >> 3;
        int bitNumber = ~gcrHeadOffset & 7;
        gcrHeadOffset = (gcrHeadOffset + 1) % (currentTrackSize << 3);

        byte gcrData = currentTrackData[dataPos + byteOffset];
        if (value) {
            currentTrackData[dataPos + byteOffset] = (byte) (gcrData | 1 << bitNumber);
        } else {
            currentTrackData[dataPos + byteOffset] = (byte) (gcrData & ~(1 << bitNumber));
        }
    }

    /**
     * Set the current GCR data track position.
     *
     * @param num              half-track to set
     * @param oldTrackSize     old track size
     * @param currentTrackSize current track size
     */
    void setHalfTrack(final int num,
                      final int oldTrackSize,
                      final int currentTrackSize) {
        int track = (num >> 1) - 1;
        byte[] large = largeTrackData[track];
        currentTrackData = large == null ? data : large;
        currentTrackCycles = null;
        currentTrackTiming = null;
        writePreparation = null;
        dataPos = large == null ? track * NUM_MAX_BYTES_TRACK : 0;
        gcrHeadOffset = (int) ((long) gcrHeadOffset * currentTrackSize / oldTrackSize);
    }

    /** Select a recorded half-track without reusing a full track or the second-side bank. */
    void setHalfTrackData(byte[] trackData, int oldTrackSize, int currentTrackSize) {
        currentTrackData = trackData;
        currentTrackCycles = null;
        currentTrackTiming = null;
        writePreparation = null;
        dataPos = 0;
        gcrHeadOffset = (int) ((long) gcrHeadOffset * currentTrackSize / oldTrackSize);
    }

    /** Decode a full-track bank without disturbing the live head, captured pass or recorded timing. */
    boolean readFromFullTrack(int track, BooleanSupplier decoder) {
        byte[] selectedData = currentTrackData;
        int selectedPos = dataPos;
        byte[] large = largeTrackData[track - 1];
        currentTrackData = large == null ? data : large;
        dataPos = large == null ? (track - 1) * NUM_MAX_BYTES_TRACK : 0;
        try {
            return decoder.getAsBoolean();
        } finally {
            currentTrackData = selectedData;
            dataPos = selectedPos;
        }
    }

    void setWritePreparation(Runnable prepare) {
        writePreparation = prepare;
    }

    /** Install validated recorded timing after selecting its associated data surface. */
    void setTrackTiming(int[] timing) {
        currentTrackTiming = timing;
    }

    boolean hasTrackTiming() {
        return currentTrackTiming != null;
    }

    int getRevolutionWeight(int currentTrackSize) {
        return currentTrackTiming != null ? currentTrackTiming[currentTrackSize] : Math.max(1, currentTrackSize << 3);
    }

    int getBitCellWeight() {
        if (currentTrackTiming == null) {
            return 1;
        }
        int offset = gcrHeadOffset >> 3;
        return (currentTrackTiming[offset + 1] - currentTrackTiming[offset]) >> 3;
    }

    int getHeadWeight() {
        return currentTrackTiming != null
                ? currentTrackTiming[gcrHeadOffset >> 3] + (gcrHeadOffset & 7) * getBitCellWeight() : gcrHeadOffset;
    }

    /** Select the cell containing an angular position; return the weight of its starting boundary. */
    int setHeadWeight(int weight) {
        if (currentTrackTiming == null) {
            gcrHeadOffset = weight;
        } else {
            int offset = Arrays.binarySearch(currentTrackTiming, weight);
            if (offset < 0) {
                offset = -offset - 2;
            }
            int cellWeight = (currentTrackTiming[offset + 1] - currentTrackTiming[offset]) >> 3;
            gcrHeadOffset = (offset << 3) + (weight - currentTrackTiming[offset]) / cellWeight;
        }
        return getHeadWeight();
    }

    /** Keep captured variations separate instead of repairing or averaging protected bytes. */
    void setTrackCycles(byte[][] cycles, int oldTrackSize, int currentTrackSize) {
        setHalfTrackData(cycles[0], oldTrackSize, currentTrackSize);
        currentTrackCycles = cycles;
        currentTrackCycle = 0;
    }
}