PSidHeader.java

package libsidplay.sidtune;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Header has been extended for 'RSID' format<BR>
 * <p>
 * The following changes are present:
 * <UL>
 * <LI>id = 'RSID'
 * <LI>version = 2, 3, 4, 5 or 0x4E
 * <LI>play, load and speed reserved 0
 * <LI>psid specific flag reserved 0
 * <LI>init cannot be under ROMS/IO
 * <LI>load cannot be less than 0x0801 (start of basic)
 * </UL>
 * all values big-endian
 *
 * @author Ken Händel
 *
 */
public class PSidHeader {
    private static final int METADATA_OFFSET = 0x16;
    private static final int METADATA_LENGTH = 0x60;
    static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1;
    // PSIDv5 uses Windows-1252. TeaVM has ISO-8859-1 but lacks this charset,
    // so map the only differing byte range explicitly. Undefined bytes round-trip as controls.
    private static final String WINDOWS_1252_EXTENSIONS =
            "\u20ac\u0081\u201a\u0192\u201e\u2026\u2020\u2021\u02c6\u2030\u0160\u2039\u0152\u008d\u017d\u008f"
            + "\u0090\u2018\u2019\u201c\u201d\u2022\u2013\u2014\u02dc\u2122\u0161\u203a\u0153\u009d\u017e\u0178";

    /**
     * ASCII PSID signature, interpreted as a big-endian integer.
     */
    public static final int MAGIC_PSID = 0x50534944;
    /**
     * ASCII RSID signature, interpreted as a big-endian integer.
     */
    public static final int MAGIC_RSID = 0x52534944;
    /**
     * Size of a version-1 PSID header, before the version-2 flags extension.
     */
    public static final int SIZE_V1 = 118;
    /**
     * Size of the standard version-2 and later header.
     */
    public static final int SIZE = 124;
    /**
     * Offset of the unsigned big-endian version field.
     */
    public static final int VERSION_FIELD = 4;
    /**
     * Offset of the unsigned big-endian C64 program-data offset field.
     */
    public static final int DATA_OFFSET_FIELD = 6;
    /**
     * Extended multi-SID header version with per-chip address, model and panning flags.
     */
    public static final int VERSION_4E = 0x4e;
    /**
     * Header version with multi-SID address layouts and configurable panning layouts/modes.
     */
    public static final int VERSION_5 = 5;

    public PSidHeader(final byte[] header) {
        final ByteBuffer buffer = ByteBuffer.wrap(header);

        buffer.get(id);
        version = buffer.getShort();
        data = buffer.getShort();
        load = buffer.getShort();
        init = buffer.getShort();
        play = buffer.getShort();
        songs = buffer.getShort();
        start = buffer.getShort();
        speed = buffer.getInt();
        if (version == 5) {
            parseV5Strings(header);
            buffer.position(METADATA_OFFSET + METADATA_LENGTH);
        } else {
            buffer.get(name, 0, 32);
            buffer.get(author, 0, 32);
            buffer.get(released, 0, 32);
        }
        if (version >= 2) {
            flags = buffer.getShort();
            /* 2B */
            relocStartPage = buffer.get();
            relocPages = buffer.get();
        }
        if (version == VERSION_4E) {
            furtherFlags = new short[((data & 0xffff) - SIZE) >> 1];
            for (int i = 0; i < furtherFlags.length; i++) {
                furtherFlags[i] = buffer.getShort();
            }
        } else {
            if (version == 5) {
                multiSidConfig = buffer.get();
                sidAddressConfigStart = buffer.get();
            } else {
                if (version >= 3) {
                    /* 2SID */
                    sidChip2MiddleNybbles = buffer.get();
                }
                if (version >= 4) {
                    /* 3SID */
                    sidChip3MiddleNybbles = buffer.get();
                }
            }
        }
    }

    private void parseV5Strings(byte[] data) {
        byte[] shared = Arrays.copyOfRange(data, METADATA_OFFSET, METADATA_OFFSET + METADATA_LENGTH);
        int pos = 0;
        boolean valid = true;
        byte[][] fields = {name, author, released};
        for (int i = 0; i < 3; i++) {
            int end = pos;
            while (end < METADATA_LENGTH && shared[end] != 0) end++;
            if (end == pos || end == METADATA_LENGTH && i < 2 || end - pos > METADATA_LENGTH) {
                valid = false;
                break;
            }
            System.arraycopy(shared, pos, fields[i], 0, end - pos);
            fields[i][end - pos] = 0;
            pos = end + 1;
            while (pos < METADATA_LENGTH && shared[pos] == 0) pos++;
        }
        if (!valid) {
            // v5 readers must support the old fixed 32-byte layout as a fallback.
            for (int i = 0; i < fields.length; i++) {
                Arrays.fill(fields[i], (byte) 0);
                System.arraycopy(shared, i * 32, fields[i], 0, 32);
            }
        }
    }

    PSidHeader() {
    }

    public byte[] getArray() {
        final ByteBuffer buffer = ByteBuffer.allocate(version == VERSION_4E ? data & 0xffff : SIZE);
        buffer.put(id);
        buffer.putShort(version);
        buffer.putShort(data);
        buffer.putShort(load);
        buffer.putShort(init);
        buffer.putShort(play);
        buffer.putShort(songs);
        buffer.putShort(start);
        buffer.putInt(speed);
        if (version == 5) {
            buffer.put(formatV5Metadata(name, author, released));
        } else {
            buffer.put(name, 0, 32);
            buffer.put(author, 0, 32);
            buffer.put(released, 0, 32);
        }
        if (version >= 2) {
            buffer.putShort(flags);
            buffer.put(relocStartPage);
            buffer.put(relocPages);
        }
        if (version == VERSION_4E) {
            for (short furtherFlag : furtherFlags) {
                buffer.putShort(furtherFlag);
            }
        } else {
            if (version == 5) {
                buffer.put(multiSidConfig);
                buffer.put(sidAddressConfigStart);
            } else {
                if (version >= 3) {
                    buffer.put(sidChip2MiddleNybbles);
                }
                if (version >= 4) {
                    buffer.put(sidChip3MiddleNybbles);
                }
            }
        }
        return buffer.array();
    }

    static byte[] formatV5Metadata(byte[] name, byte[] author, byte[] released) {
        int N = getStringByteLength(name);
        int A = getStringByteLength(author);
        int R = getStringByteLength(released);

        int authorOffset;
        int releasedOffset;

        if (N <= 32 && A <= 32 && R <= 32) {
            authorOffset = 32;
            releasedOffset = 64;
        } else if (N + A + R + 2 > 96) {
            throw new IllegalArgumentException("SIDv5 metadata exceeds " + METADATA_LENGTH + " bytes");
        } else if (R <= 32 && N + A + 2 <= 64) {
            int padding = (64 - N - A - 2) / 2;
            authorOffset = N + 1 + padding;
            releasedOffset = 64;
        } else if (N < 32 && A + R + 1 <= 64) {
            authorOffset = 32;
            releasedOffset = 96 - R;
        } else {
            int padding = (96 - N - A - R - 2) / 2;
            authorOffset = N + 1 + padding;
            releasedOffset = 96 - R;
        }

        byte[] metadata = new byte[METADATA_LENGTH];
        System.arraycopy(name, 0, metadata, 0, N);
        System.arraycopy(author, 0, metadata, authorOffset, A);
        System.arraycopy(released, 0, metadata, releasedOffset, R);
        return metadata;
    }

    private static int getStringByteLength(byte[] bytes) {
        int len = 0;
        while (len < bytes.length && bytes[len] != 0) {
            len++;
        }
        return len;
    }

    void setV5Strings(String title, String authorName, String releasedName) {
        setV5String(title, name);
        setV5String(authorName, author);
        setV5String(releasedName, released);
    }

    private static void setV5String(String value, byte[] destination) {
        int size = 0;
        for (int offset = 0; offset < value.length() && size < destination.length; ) {
            int codePoint = value.codePointAt(offset);
            offset += Character.charCount(codePoint);
            if (codePoint < 0x80 || codePoint >= 0xa0 && codePoint <= 0xff) {
                destination[size++] = (byte) codePoint;
            } else {
                int index = WINDOWS_1252_EXTENSIONS.indexOf(codePoint);
                destination[size++] = (byte) (index >= 0 ? 0x80 + index : '?');
            }
        }
        Arrays.fill(destination, size, destination.length, (byte) 0);
    }

    /**
     * Magic (PSID or RSID)
     */
    byte[] id = new byte[4];

    /**
     * Standard versions 1–5 and the extended version 0x4E.
     */
    short version;

    /**
     * 16-bit offset to binary data in a file
     */
    short data;

    /**
     * 16-bit C64 address to load a file to
     */
    short load;

    /**
     * 16-bit C64 address of init subroutine
     */
    short init;

    /**
     * 16-bit C64 address of play subroutine
     */
    short play;

    /**
     * number of songs
     */
    short songs;

    /**
     * start song out of [1..256]
     */
    short start;

    /**
     * 32-bit speed info:<BR>
     * <p>
     * bit: 0 = 50 Hz, 1 = CIA 1 Timer A (default: 60 Hz)
     */
    int speed;

    /**
     * ASCII strings, 31 characters long and terminated by a trailing zero For version 0x0003, all 32 chars can be used
     * without zero termination. if less than 32 chars are used, then it should be terminated with a trailing zero
     */
    byte[] name = new byte[METADATA_LENGTH];

    /**
     * ASCII strings, 31 characters long and terminated by a trailing zero For version 0x0003, all 32 chars can be used
     * without zero termination. if less than 32 chars are used, then it should be terminated with a trailing zero
     */
    byte[] author = new byte[METADATA_LENGTH];

    /**
     * ASCII strings, 31 characters long and terminated by a trailing zero For version 0x0003, all 32 chars can be used
     * without zero termination. if less than 32 chars are used, then it should be terminated with a trailing zero
     */
    byte[] released = new byte[METADATA_LENGTH];

    /**
     * only version 0x0002+
     */
    short flags;

    /**
     * only version 0x0002+
     */
    byte relocStartPage;

    /**
     * only version 0x0002+
     */
    byte relocPages;

    /**
     * only version 0x0003 to indicate the second SID chip address
     */
    byte sidChip2MiddleNybbles;

    /**
     * only version 0x0004 to indicate third SID chip address
     */
    byte sidChip3MiddleNybbles;

    /**
     * v5 multi-SID configuration field (replacement of sidChip2MiddleNybbles).
     */
    byte multiSidConfig;

    /**
     * v5 multi-SID configuration field (replacement of sidChip3MiddleNybbles).
     */
    byte sidAddressConfigStart;

    short[] furtherFlags;

    private String getString(byte[] info) {
        StringBuilder result = new StringBuilder();
        for (byte encoded : info) {
            int value = encoded & 0xff;
            if (value == 0) {
                break;
            }
            char decoded = version == VERSION_5 && value >= 0x80 && value < 0xa0
                    ? WINDOWS_1252_EXTENSIONS.charAt(value - 0x80) : (char) value;
            result.append(decoded);
        }
        return result.length() == 0 ? "<?>" : result.toString();
    }

    public String getName() {
        return getString(name);
    }

    public String getAuthor() {
        return getString(author);
    }

    public String getReleased() {
        return getString(released);
    }

}