PSid.java

/**
 * PlaySID one-file format support.
 * <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
 */
package libsidplay.sidtune;

import libsidplay.components.mos6510.MOS6510;
import libsidutils.assembler.KickAssembler;
import libsidutils.assembler.KickAssemblerResult;
import libsidutils.reloc65.Reloc65;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

import static java.util.Objects.requireNonNull;
import static libsidplay.config.ISidPlay2SystemProperties.MAX_SIDS;
import static libsidplay.sidtune.PSidHeader.ISO_8859_1;
import static libsidplay.sidtune.SidTune.Clock.NTSC;
import static libsidplay.sidtune.SidTune.Clock.PAL;
import static libsidplay.sidtune.SidTune.Compatibility.*;
import static libsidplay.sidtune.SidTune.Speed.CIA_1A;
import static libsidplay.sidtune.SidTune.Speed.VBI;

class PSid extends Prg {

    private static final String PSID_DRIVER_ASM = "/libsidplay/sidtune/psiddriver.asm";

    private static final String PSID_DRIVER_BIN = "/libsidplay/sidtune/psiddriver.bin";

    //
    // PSID_SPECIFIC and PSID_BASIC are mutually exclusive
    //

    /**
     * No more supported: MUS specific PSID files
     */
    private static final int PSID_MUS = 1 << 0;

    /**
     * No more supported: PSID specific PSID files
     */
    private static final int PSID_SPECIFIC = 1 << 1;

    /**
     * Compatibility: PSID BASIC files are handled like RSID_BASIC files
     */
    private static final int PSID_BASIC = 1 << 1;
    private static final int V5_SONG_LENGTHS = 1 << 10;
    private static final int V5_FM_OPL = 1 << 11;

    /**
     * PSID file format limit.
     */
    private static final int SIDTUNE_MAX_SONGS = 256;

    private PSidHeader header;

    private final Speed[] songSpeed = new Speed[SIDTUNE_MAX_SONGS];

    private KickAssemblerResult preparedDriver;

    @Override
    public Integer placeProgramInMemory(final byte[] mem) {
        copyProgramToMemory(mem);
        if (info.compatibility == RSID_BASIC) {
            mem[0x30c] = (byte) (info.currentSong - 1);
            return null;
        } else {
            if (USE_KICKASSEMBLER) {
                return assembleAndInstallDriver(mem);
            } else {
                return relocateAndInstallDriver(mem);
            }
        }
    }

    @Override
    public Integer placeProgramInMemory(final byte[] mem, byte[] driver, byte[] musDriver1, byte[] musDriver2) {
        copyProgramToMemory(mem);
        if (info.compatibility == RSID_BASIC) {
            mem[0x30c] = (byte) (info.currentSong - 1);
            return null;
        } else {
            return relocateAndInstallDriver(mem, driver);
        }
    }

    /**
     * Linux ALSA is very sensible for timing: therefore, we assemble before we open AudioLine
     */
    @Override
    public void prepare() {
        if (USE_KICKASSEMBLER) {
            HashMap<String, String> globals = new HashMap<>();
            globals.put("pc", String.valueOf(info.determinedDriverAddr));
            globals.put("songNum", String.valueOf(info.currentSong));
            globals.put("songs", String.valueOf(info.songs));
            globals.put("songSpeed", String.valueOf(getSongSpeed(info.currentSong) == CIA_1A ? 1 : 0));
            globals.put("speed", String.valueOf(getSongSpeedWord()));
            globals.put("loadAddr", String.valueOf(info.loadAddr));
            globals.put("initAddr", String.valueOf(info.initAddr));
            globals.put("playAddr", String.valueOf(info.playAddr));
            globals.put("powerOnDelay", String.valueOf((int) (0x100 + (System.currentTimeMillis() & 0x1ff))));
            globals.put("initIOMap", String.valueOf(info.iomap(info.initAddr)));
            globals.put("playIOMap", String.valueOf(info.iomap(info.playAddr)));
            globals.put("videoMode", String.valueOf(info.clockSpeed == PAL ? 1 : 0));
            if (isRsidMachineCode()) {
                globals.put("flags", String.valueOf(1));
            } else {
                globals.put("flags", String.valueOf(1 << MOS6510.SR_INTERRUPT));
            }
            InputStream asm = PSid.class.getResourceAsStream(PSID_DRIVER_ASM);
            preparedDriver = KickAssembler.assemble(PSID_DRIVER_ASM, asm, globals);
        }
    }

    private int assembleAndInstallDriver(final byte[] mem) {
        if (preparedDriver == null) {
            prepare();
        }
        info.determinedDriverLength = preparedDriver.getData().length - 2;
        System.arraycopy(preparedDriver.getData(), 2, mem, info.determinedDriverAddr, info.determinedDriverLength);
        if (info.determinedDriverLength + 255 >> 8 != 1) {
            throw new RuntimeException("Driver must not be greater than one block! " + PSID_DRIVER_ASM);
        }
        Integer start = preparedDriver.getResolvedSymbols().get("start");
        if (start == null) {
            throw new RuntimeException("Label start not found in " + PSID_DRIVER_ASM);
        }
        return start;
    }

    private int relocateAndInstallDriver(final byte[] ram) {
        byte[] PSID_DRIVER;
        try (DataInputStream is = new DataInputStream(requireNonNull(PSid.class.getResourceAsStream(PSID_DRIVER_BIN)))) {
            URL url = PSid.class.getResource(PSID_DRIVER_BIN);
            PSID_DRIVER = new byte[requireNonNull(url).openConnection().getContentLength()];
            is.readFully(PSID_DRIVER);
            return relocateAndInstallDriver(ram, PSID_DRIVER);
        } catch (IOException e) {
            throw new RuntimeException("Load failed for resource: " + PSID_DRIVER_BIN);
        }
    }

    private int relocateAndInstallDriver(final byte[] ram, byte[] PSID_DRIVER) {
        ByteBuffer relocatedBuffer = new Reloc65().reloc65(PSID_DRIVER, info.determinedDriverAddr - 10);

        if (relocatedBuffer == null) {
            throw new RuntimeException("Failed to relocate driver.");
        }
        info.determinedDriverLength = relocatedBuffer.limit() - 10;

        final byte[] reloc_driver = relocatedBuffer.array();
        final int reloc_driverPos = relocatedBuffer.position();

        if (!(info.playAddr == 0 && info.loadAddr == 0x200)) {
            /*
             * Setting these vectors seems a bit dangerous because we will still run for
             * some time
             */
            ram[0x0314] = reloc_driver[reloc_driverPos + 2]; /* IRQ */
            ram[0x0315] = reloc_driver[reloc_driverPos + 2 + 1];
            if (!isRsidMachineCode()) {
                ram[0x0316] = reloc_driver[reloc_driverPos + 2 + 2]; /* Break */
                ram[0x0317] = reloc_driver[reloc_driverPos + 2 + 3];
                ram[0x0318] = reloc_driver[reloc_driverPos + 2 + 4]; /* NMI */
                ram[0x0319] = reloc_driver[reloc_driverPos + 2 + 5];
            }
        }
        int pos = info.determinedDriverAddr;

        /* Place driver into RAM */
        System.arraycopy(reloc_driver, reloc_driverPos + 10, ram, pos, info.determinedDriverLength);

        // Tell C64 about the song
        ram[pos++] = (byte) (info.currentSong - 1);
        ram[pos++] = (byte) (songSpeed[info.currentSong - 1] == VBI ? 0 : 1);
        ram[pos++] = (byte) (info.initAddr & 0xff);
        ram[pos++] = (byte) (info.initAddr >> 8);
        ram[pos++] = (byte) (info.playAddr & 0xff);
        ram[pos++] = (byte) (info.playAddr >> 8);

        final int powerOnDelay = (int) (0x100 + (System.currentTimeMillis() & 0x1ff));
        ram[pos++] = (byte) (powerOnDelay & 0xff);
        ram[pos++] = (byte) (powerOnDelay >> 8);
        ram[pos++] = (byte) info.iomap(info.initAddr);
        ram[pos++] = (byte) info.iomap(info.playAddr);
        ram[pos++] = ram[0x02a6]; // Flag: TV Standard: $00 = NTSC, $01 = PAL.

        // Add the required tune speed
        switch (info.clockSpeed) {
            case PAL:
                ram[pos++] = 1;
                break;
            case NTSC:
                ram[pos++] = 0;
                break;
            default: // UNKNOWN or ANY? use clock speed of C64 system
                ram[pos++] = ram[0x02a6];
                break;
        }

        // Default processor register flags on calling init
        if (isRsidMachineCode()) {
            ram[pos] = 0;
        } else {
            ram[pos] = 1 << MOS6510.SR_INTERRUPT;
        }

        return reloc_driver[reloc_driverPos] & 0xff | (reloc_driver[reloc_driverPos + 1] & 0xff) << 8;
    }

    /**
     * Common address resolution procedure
     */
    private void resolveAddrs() throws SidTuneError {
        // Originally used as a first attempt at an RSID
        // style format. Now reserved for future use
        if (info.playAddr == 0xffff) {
            info.playAddr = 0;
        }
        // loadAddr = 0 means the address is stored in front of the C64 data.
        if (info.loadAddr == 0) {
            if (info.c64dataLen < 2) {
                throw new SidTuneError("PSID: Song is truncated");
            }
            info.loadAddr = (program[programOffset] & 0xff) + ((program[programOffset + 1] & 0xff) << 8);
            programOffset += 2;
            info.c64dataLen -= 2;
        }
        if (info.compatibility == RSID_BASIC) {
            if (info.initAddr != 0) {
                throw new SidTuneError("PSID: Init address given for a RSID tune with BASIC flag");
            }
        } else if (info.initAddr == 0) {
            info.initAddr = info.loadAddr;
        }
    }

    /**
     * Check for valid relocation information and calculate a place for a driver. The driver is only 1 block long, and
     * we currently make use of this knowledge.
     */
    protected void findPlaceForDriver() throws SidTuneError {
        final short startlp = (short) (info.loadAddr >> 8);
        final short endlp = (short) (info.loadAddr + info.c64dataLen - 1 >> 8);

        // Fix relocation information
        if (info.relocStartPage == 0xFF) {
            info.relocPages = 0;
        } else if (info.relocPages == 0) {
            info.relocStartPage = 0;
        } else {
            // Calculate start/end page
            final short startp = info.relocStartPage;
            final short endp = (short) (startp + info.relocPages - 1 & 0xff);
            if (endp < startp) {
                throw new SidTuneError(String.format(
                        "PSID: Relocation info is invalid: end before start: end=%02x, start=%02x", endp, startp));
            }

            if (startp <= startlp && endp >= startlp || startp <= endlp && endp >= endlp) {
                throw new SidTuneError(String.format(
                        "PSID: Relocation info is invalid: relocation in middle of song tune itself: songstart=%02x, songend=%02x, relocstart=%02x, relocend=%02x",
                        startlp, endlp, startp, endp));
            }

            // Check that the relocation information does not use the following
            // memory areas: 0x0000-0x03FF, 0xA000-0xBFFF and 0xD000-0xFFFF
            if (startp < 0x04 || 0xa0 <= startp && startp <= 0xbf || startp >= 0xd0 || 0xa0 <= endp && endp <= 0xbf
                    || endp >= 0xd0) {
                throw new SidTuneError(String.format(
                        "PSID: Relocation info is invalid: beyond acceptable bounds (kernal, basic, io, < 4th page): %02x-%02x",
                        startp, endp));
            }
        }

        info.determinedDriverAddr = info.relocStartPage << 8;
        if (info.determinedDriverAddr == 0) {
            final int driverLen = 1;
            outer:
            for (int i = 4; i < 0xd0; i++) {
                for (int j = 0; j < driverLen; j++) {
                    if (i + j >= startlp && i + j <= endlp) {
                        continue outer;
                    }
                    if (i + j >= 0xa0 && i + j <= 0xbf) {
                        continue outer;
                    }
                }

                info.determinedDriverAddr = i << 8;
                break;
            }
        }

        if (info.determinedDriverAddr == 0) {
            throw new SidTuneError("PSID: Can't relocate tune: no pages left to store driver.");
        }
    }

    protected static SidTune load(final String name, final byte[] dataBuf) throws SidTuneError {
        if (dataBuf.length < PSidHeader.SIZE) {
            throw new SidTuneError(
                    String.format("PSID: Header too short: %d, expected (%d)", dataBuf.length, PSidHeader.SIZE));
        }
        final PSid psid = new PSid();
        psid.header = new PSidHeader(dataBuf);
        int minimumDataOffset = psid.header.version == 1 ? 0x76 : PSidHeader.SIZE;
        if ((psid.header.data & 0xffff) < minimumDataOffset || (psid.header.data & 0xffff) > dataBuf.length)
            throw new SidTuneError("PSID: invalid data offset");
        if ((psid.header.version & 0xffff) == 5 && (psid.header.flags & 0xf000) != 0) {
            throw new SidTuneError("PSIDv5: reserved flags are set");
        }
        if ((psid.header.flags & PSID_MUS) != 0) {
            throw new SidTuneError("PSID: MUS-specific PSIDs are not supported by this player");
        }

        psid.program = dataBuf;
        psid.programOffset = psid.header.data;

        psid.info.c64dataLen = dataBuf.length - psid.programOffset;
        psid.info.loadAddr = psid.header.load & 0xffff;
        psid.info.initAddr = psid.header.init & 0xffff;
        psid.info.playAddr = psid.header.play & 0xffff;

        psid.info.songs = psid.header.songs & 0xffff;
        if (psid.header.version == 5 && (psid.info.songs < 1 || psid.info.songs > SIDTUNE_MAX_SONGS)) {
            throw new SidTuneError("PSIDv5: invalid song count");
        }
        if (psid.info.songs == 0) {
            psid.info.songs++;
        }
        if (psid.info.songs > SIDTUNE_MAX_SONGS) {
            psid.info.songs = SIDTUNE_MAX_SONGS;
        }
        psid.info.startSong = psid.header.start & 0xffff;
        if (psid.info.startSong > psid.info.songs) {
            psid.info.startSong = 1;
        } else if (psid.info.startSong == 0) {
            psid.info.startSong++;
        }

        if (psid.header.version == 5 && (psid.header.flags & V5_SONG_LENGTHS) != 0) {
            int table = dataBuf.length - psid.info.songs * 4;
            if (table < (psid.header.data & 0xffff)) throw new SidTuneError("PSIDv5: truncated length table");
            psid.info.songLengthsIncluded = true;
            psid.info.songLengths = new long[psid.info.songs];
            psid.info.c64dataLen = table - (psid.header.data & 0xffff);
            for (int i = 0; i < psid.info.songs; i++) {
                int p = table + i * 4;
                int mmss = (dataBuf[p] & 255) << 8 | dataBuf[p + 1] & 255;
                int msec = (dataBuf[p + 2] & 255) << 8 | dataBuf[p + 3] & 255;
                if ((mmss >> 12 & 15) > 9 || (mmss >> 8 & 15) > 9 || (mmss >> 4 & 15) > 5 || (mmss & 15) > 9
                        || (msec >> 12 & 15) != 0 || (msec >> 8 & 15) > 9 || (msec >> 4 & 15) > 9 || (msec & 15) > 9)
                    throw new SidTuneError("PSIDv5: invalid BCD song length");
                int min = (mmss >> 12 & 15) * 10 + (mmss >> 8 & 15);
                int sec = (mmss >> 4 & 15) * 10 + (mmss & 15);
                int ms = (msec >> 8 & 15) * 100 + (msec >> 4 & 15) * 10 + (msec & 15);
                psid.info.songLengths[i] = (min * 60L + sec) * 1000 + ms;
            }
        }

        int speed = psid.header.speed;

        if (Arrays.equals(psid.header.id, "PSID".getBytes(ISO_8859_1))) {
            switch (psid.header.version) {
                case 1:
                    psid.info.compatibility = PSIDv1;
                    break;
                case 2:
                    psid.info.compatibility = PSIDv2;
                    if ((psid.header.flags & PSID_SPECIFIC) != 0) {
                        throw new SidTuneError("PSID: PSID-specific files are not supported by this player");
                    }
                    break;
                case 3:
                    psid.info.compatibility = PSIDv3;
                    break;
                case 4:
                    psid.info.compatibility = PSIDv4;
                    break;
                case 5:
                    psid.info.compatibility = PSIDv5;
                    break;
                case 0x4E:
                    psid.info.compatibility = PSIDv4E;
                    break;
                default:
                    throw new SidTuneError("PSID: PSID version must be 1, 2, 3, 4, 5 or 0x4E, now: " + psid.header.version);
            }
        } else if (Arrays.equals(psid.header.id, "RSID".getBytes(ISO_8859_1))) {
            if ((psid.header.flags & PSID_BASIC) != 0) {
                psid.info.compatibility = RSID_BASIC;
            } else {
                switch (psid.header.version) {
                    case 2:
                        psid.info.compatibility = RSIDv2;
                        break;
                    case 3:
                        psid.info.compatibility = RSIDv3;
                        break;
                    case 4:
                        psid.info.compatibility = RSIDv4;
                        break;
                    case 0x4E:
                        psid.info.compatibility = RSIDv4E;
                        break;
                    case 5:
                        psid.info.compatibility = RSIDv5;
                        break;
                    default:
                        throw new SidTuneError("PSID: RSID version must be 2, 3, 4, 5 or 0x4E, now: " + psid.header.version);
                }
            }
            if (psid.info.loadAddr != 0 || psid.info.playAddr != 0 || speed != 0) {
                throw new SidTuneError("PSID: RSID tune specified load, play or speed information.");
            }
            speed = ~0; /* CIA */
        } else {
            throw new SidTuneError("PSID: Bad PSID header, expected (PSID or RSID)");
        }

        int clock = 0;
        int model1 = 0;
        int model2 = 0;
        int model3 = 0;

        if (psid.header.version == 5) {
            psid.info.panningLayout = psid.header.flags >> 6 & 3;
            psid.info.panningMode = psid.header.flags >> 8 & 3;
            int sidCount = psid.header.multiSidConfig & 15;
            int config = psid.header.multiSidConfig >> 4 & 15;

            psid.info.multiSidConfig = psid.header.multiSidConfig & 255;
            psid.info.sidAddressConfigStart = psid.header.sidAddressConfigStart & 255;
            psid.info.fmOpl = (psid.header.flags & V5_FM_OPL) != 0;
            if (sidCount == 0 && psid.info.multiSidConfig != 0 || sidCount == 1)
                throw new SidTuneError("PSIDv5: invalid SID count configuration");
            if (sidCount > 1) {
                // Values 7 - 15 are reserved
                if (config > 6)
                    throw new SidTuneError("PSIDv5: invalid multi-SID configuration");
                // use the standard start address for the selected configuration or DXX0
                int startConfig = validV5Start(psid.info.sidAddressConfigStart) ? psid.info.sidAddressConfigStart : 0;
                int address = startConfig == 0 ? v5DefaultStart(config)
                        : 0xd000 | startConfig << 4;
                int[] steps;
                if (config < 4) {
                    // single-step configuration
                    steps = new int[]{0x20 << config};
                } else if (config == 4) {
                    // alternating-step-configuration
                    steps = new int[]{0x20, 0x60};
                } else if (config == 5) {
                    // alternating-step-configuration
                    steps = new int[]{0x20, 0xe0};
                } else /* config == 6 */ {
                    // alternating-step-configuration
                    steps = new int[]{0x100, 0x300};
                }
                for (int i = 1; i < sidCount && i < MAX_SIDS; i++) {
                    psid.info.sidChipBase[i] = address;
                    // The first configured step leads from SID #1 to SID #2.
                    // Therefore, the next step (index 1 for alternating configs)
                    // leads from SID #2 to SID #3.
                    address += steps[i % steps.length];
                    if (address > 0xd7e0 && address < 0xde00) {
                        // If a step advances beyond $D7E0, address generation resumes at $DE00, preserving
                        //any remaining offset from the step.
                        address = 0xde00 + address - 0xd800;
                    }
                    if (address > 0xdfe0) {
                        /*
                         * If a step advances beyond $DFE0, no further SID addresses are generated.
                         *<p>
                         * Config  Max SID chips
                         * 0       15
                         * 1       15
                         * 2       12
                         * 3       6
                         * 4       12
                         * 5       12
                         * 6       4
                         */
                        break;
                    }
                }
                if (psid.info.fmOpl) {
                    for (int i = 1; i < MAX_SIDS && psid.info.sidChipBase[i] != 0; i++) {
                        if (psid.info.sidChipBase[i] >= 0xdf00) {
                            throw new SidTuneError("PSIDv5: SID overlaps FM OPL");
                        }
                    }
                }
            }
            applyV5Panning(psid.info, sidCount == 0 ? 1 : sidCount);
            clock = psid.header.flags >> 2 & 3;
            model1 = psid.header.flags >> 4 & 3;
            for (int i = 0; i < MAX_SIDS - 1 && psid.info.sidChipBase[i] != 0; i++) {
                // All SID chips use the SID model specified in bits 4-5
                psid.info.sidModel[1 + i] = Model.values()[model1];
            }
            psid.info.relocStartPage = (short) (psid.header.relocStartPage & 255);
            psid.info.relocPages = (short) (psid.header.relocPages & 255);
        } else if (psid.header.version == 0x4E) {
            clock = psid.header.flags >> 2 & 3;
            model1 = psid.header.flags >> 4 & 3;
            int channel1 = psid.header.flags >> 6 & 1;
            psid.info.channel[0] = channel1;
            if (psid.header.furtherFlags.length + 1 > MAX_SIDS) {
                throw new SidTuneError(String.format("PSIDv4E: Too many SIDs: %d, MAX_SIDS (%d)",
                        (psid.header.furtherFlags.length + 1), MAX_SIDS));
            }
            for (int i = 0; i < psid.header.furtherFlags.length; i++) {
                int modelN = psid.header.furtherFlags[i] >> 4 & 3;
                int channelN = psid.header.furtherFlags[i] >> 6 & 1;
                int addressByte = psid.header.furtherFlags[i] >> 8 & 0xff;
                int sidlocN = 0xd000 | addressByte << 4;
                if ((sidlocN >= 0xd420 && sidlocN < 0xd800 || sidlocN >= 0xde00) && (sidlocN & 0x10) == 0) {
                    psid.info.sidChipBase[1 + i] = sidlocN;
                    if (modelN == 0) {
                        // If Unknown, then SID will be same SID as the first SID
                        modelN = model1;
                    }
                    psid.info.channel[1 + i] = channelN;
                }
                psid.info.sidModel[1 + i] = Model.values()[modelN];
            }
        } else {
            if (psid.header.version >= 2) {
                clock = psid.header.flags >> 2 & 3;
                model1 = psid.header.flags >> 4 & 3;

                psid.info.relocStartPage = (short) (psid.header.relocStartPage & 0xff);
                psid.info.relocPages = (short) (psid.header.relocPages & 0xff);

            }
            if (psid.header.version >= 3) {
                model2 = psid.header.flags >> 6 & 3;

                /* Handle 2nd SID chip location */
                int sid2loc = 0xd000 | (psid.header.sidChip2MiddleNybbles & 0xff) << 4;
                if ((sid2loc >= 0xd420 && sid2loc < 0xd800 || sid2loc >= 0xde00) && (sid2loc & 0x10) == 0) {
                    psid.info.sidChipBase[1] = sid2loc;
                    if (model2 == 0) {
                        // If Unknown, then SID will be same SID as the first SID
                        model2 = model1;
                    }
                }
            }
            if (psid.header.version >= 4) {
                model3 = psid.header.flags >> 8 & 3;

                /* Handle 3rd SID chip location */
                int sid3loc = 0xd000 | (psid.header.sidChip3MiddleNybbles & 0xff) << 4;
                if ((sid3loc >= 0xd420 && sid3loc < 0xd800 || sid3loc >= 0xde00) && (sid3loc & 0x10) == 0) {
                    psid.info.sidChipBase[2] = sid3loc;
                    if (model3 == 0) {
                        // If Unknown, then SID will be same SID as the first SID
                        model3 = model1;
                    }
                }
            }
            psid.info.sidModel[1] = Model.values()[model2];
            psid.info.sidModel[2] = Model.values()[model3];
        }
        psid.info.clockSpeed = Clock.values()[clock];
        psid.info.sidModel[0] = Model.values()[model1];

        // Create the speed/clock setting table.
        psid.convertOldStyleSpeedToTables(speed);

        // Name
        psid.info.infoString.add(psid.header.getName());
        psid.info.infoString.add(psid.header.getAuthor());
        psid.info.infoString.add(psid.header.getReleased());

        psid.resolveAddrs();
        psid.findPlaceForDriver();

        return psid;
    }

    private static boolean validV5Start(int value) {
        return value == 0 || (value >= 0x42 && value <= 0x7e || value >= 0xe0 && value <= 0xfe) && (value & 1) == 0;
    }

    private static int v5DefaultStart(int config) {
        return config == 1 ? 0xd440 : config == 2 ? 0xd480 : config == 3 || config == 6 ? 0xd500 : 0xd420;
    }

    private static void applyV5Panning(SidTuneInfo info, int sidCount) {
        int[] layout = createV5PanningLayout(info.panningLayout, sidCount);
        int[] finalLayout = applyV5PanningMode(layout, info.panningLayout, info.panningMode);
        for (int sid = 0; sid < Math.min(sidCount, MAX_SIDS); sid++) {
            // LEFT, CENTER and RIGHT map to the mixer range 0.0, 0.5 and 1.0.
            info.channel[sid] = finalLayout[sid] / 2f;
        }
    }

    /**
     * BITS 6-7 IN VERSION 5
     * <p>
     * 00 = Standard For one SID, assign the SID to C (mono output). For multiple SIDs, alternate between L and R,
     * starting with L.
     * <p>
     * 01 = L/C/R For one SID, assign the SID to C (mono output). For multiple SIDs, alternate between L, C, and R,
     * starting with L.
     * <p>
     * 10 = Center First Assign the first C-count SIDs to C. Assign the remaining SIDs alternately between L and R,
     * starting with L.
     * <p>
     * C-count = N - floor(N / 3) * 2
     * <p>
     * where N is the number of configured SIDs.
     * <p>
     * 11 = Fully Centered Assign every SID to C (mono output).
     *
     * @param layoutBits panning layout bits
     * @param sidCount   number of SIDs
     * @return generated panning layout
     */
    private static int[] createV5PanningLayout(int layoutBits, int sidCount) {
        final int LEFT = 0, CENTER = 1, RIGHT = 2;
        int[] result = new int[sidCount];
        if (layoutBits == 3 || sidCount == 1) {
            // Layout 11 (Fully Centered) or N=1:
            // All SIDs are assigned to C (mono output).
            // N=1: C, N=2: C-C, N=3: C-C-C, ..., N=15: C-C-C-C-C-C-C-C-C-C-C-C-C-C-C
            java.util.Arrays.fill(result, CENTER);
        } else if (layoutBits == 2) {
            // Layout 10 (Center First):
            // C-count = N - floor(N / 3) * 2 SIDs assigned to C, then alternating L/R starting with L.
            //  1: C                            9: C-C-C-L-R-L-R-L-R
            //  2: C-C                         10: C-C-C-C-L-R-L-R-L-R
            //  3: C-L-R                       11: C-C-C-C-C-L-R-L-R-L-R
            //  4: C-C-L-R                     12: C-C-C-C-L-R-L-R-L-R-L-R
            //  5: C-C-C-L-R                   13: C-C-C-C-C-L-R-L-R-L-R-L-R
            //  6: C-C-L-R-L-R                 14: C-C-C-C-C-C-L-R-L-R-L-R-L-R
            //  7: C-C-C-L-R-L-R               15: C-C-C-C-C-L-R-L-R-L-R-L-R-L-R
            //  8: C-C-C-C-L-R-L-R
            int centeredSids = sidCount - sidCount / 3 * 2;
            for (int sid = 0; sid < sidCount; sid++) {
                result[sid] = sid < centeredSids ? CENTER : (sid - centeredSids) % 2 == 0 ? LEFT : RIGHT;
            }
        } else if (layoutBits == 1) {
            // Layout 01 (L/C/R):
            // Alternate between L, C, and R, starting with L (L-C-R-L-C-R...).
            //  1: C                            9: L-C-R-L-C-R-L-C-R
            //  2: L-C                         10: L-C-R-L-C-R-L-C-R-L
            //  3: L-C-R                       11: L-C-R-L-C-R-L-C-R-L-C
            //  4: L-C-R-L                     12: L-C-R-L-C-R-L-C-R-L-C-R
            //  5: L-C-R-L-C                   13: L-C-R-L-C-R-L-C-R-L-C-R-L
            //  6: L-C-R-L-C-R                 14: L-C-R-L-C-R-L-C-R-L-C-R-L-C
            //  7: L-C-R-L-C-R-L               15: L-C-R-L-C-R-L-C-R-L-C-R-L-C-R
            //  8: L-C-R-L-C-R-L-C
            for (int sid = 0; sid < sidCount; sid++) {
                result[sid] = sid % 3;
            }
        } else /* layout == 0 */ {
            // Layout 00 (Standard):
            // Alternate between L and R, starting with L (L-R-L-R...).
            //  1: C                            9: L-R-L-R-L-R-L-R-L
            //  2: L-R                         10: L-R-L-R-L-R-L-R-L-R
            //  3: L-R-L                       11: L-R-L-R-L-R-L-R-L-R-L
            //  4: L-R-L-R                     12: L-R-L-R-L-R-L-R-L-R-L-R
            //  5: L-R-L-R-L                   13: L-R-L-R-L-R-L-R-L-R-L-R-L
            //  6: L-R-L-R-L-R                 14: L-R-L-R-L-R-L-R-L-R-L-R-L-R
            //  7: L-R-L-R-L-R-L               15: L-R-L-R-L-R-L-R-L-R-L-R-L-R-L
            //  8: L-R-L-R-L-R-L-R
            for (int sid = 0; sid < sidCount; sid++) {
                result[sid] = sid % 2 == 0 ? LEFT : RIGHT;
            }
        }
        return result;
    }

    /**
     * BITS 8-9 IN VERSION 5
     * <p>
     * 00 = Direct (use the SID Panning Layout unchanged) 01 = Reverse (mirror the SID Panning Layout from left to
     * right) 10 = Group (group consecutive panning assignments) 11 = Spread (distribute SIDs across the available
     * panning positions)
     *
     * @param layout     panning layout to apply mode to
     * @param layoutBits panning layout bits
     * @param modeBits   panning mode bits
     * @return final panning layout after applying mode
     */
    private static int[] applyV5PanningMode(int[] layout, int layoutBits, int modeBits) {
        final int LEFT = 0, CENTER = 1, RIGHT = 2;
        // Mode 00 (Direct):
        // Uses the base layout generated from bits 6-7 without modification.
        int[] result = layout.clone();
        int sidCount = result.length;
        if (modeBits == 1) {
            // Mode 01 (Reverse):
            // Mirrors the SID Panning Layout from left to right.
            //
            // Standard (00) [Swap L <-> R]:
            //  1: C                            9: R-L-R-L-R-L-R-L-R
            //  2: R-L                         10: R-L-R-L-R-L-R-L-R-L
            //  3: R-L-R                       11: R-L-R-L-R-L-R-L-R-L-R
            //  4: R-L-R-L                     12: R-L-R-L-R-L-R-L-R-L-R-L
            //  5: R-L-R-L-R                   13: R-L-R-L-R-L-R-L-R-L-R-L-R
            //  6: R-L-R-L-R-L                 14: R-L-R-L-R-L-R-L-R-L-R-L-R-L
            //  7: R-L-R-L-R-L-R               15: R-L-R-L-R-L-R-L-R-L-R-L-R-L-R
            //  8: R-L-R-L-R-L-R-L
            //
            // L/C/R (01) [Swap L <-> R, C unchanged]:
            //  1: C                            9: R-C-L-R-C-L-R-C-L
            //  2: R-C                         10: R-C-L-R-C-L-R-C-L-R
            //  3: R-C-L                       11: R-C-L-R-C-L-R-C-L-R-C
            //  4: R-C-L-R                     12: R-C-L-R-C-L-R-C-L-R-C-L
            //  5: R-C-L-R-C                   13: R-C-L-R-C-L-R-C-L-R-C-L-R
            //  6: R-C-L-R-C-L                 14: R-C-L-R-C-L-R-C-L-R-C-L-R-C
            //  7: R-C-L-R-C-L-R               15: R-C-L-R-C-L-R-C-L-R-C-L-R-C-L
            //  8: R-C-L-R-C-L-R-C
            //
            // Center First (10) [Swap L <-> R, move centered SIDs to end]:
            //  1: C                            9: R-L-R-L-R-L-C-C-C
            //  2: C-C                         10: R-L-R-L-R-L-C-C-C-C
            //  3: R-L-C                       11: R-L-R-L-R-L-C-C-C-C-C
            //  4: R-L-C-C                     12: R-L-R-L-R-L-R-L-C-C-C-C
            //  5: R-L-C-C-C                   13: R-L-R-L-R-L-R-L-C-C-C-C-C
            //  6: R-L-R-L-C-C                 14: R-L-R-L-R-L-R-L-C-C-C-C-C-C
            //  7: R-L-R-L-C-C-C               15: R-L-R-L-R-L-R-L-R-L-C-C-C-C-C
            //  8: R-L-R-L-C-C-C-C
            //
            // Fully Centered (11):
            //  1..15: All SIDs remain C.
            for (int sid = 0; sid < result.length; sid++) {
                // Standard (00) & L/C/R (01): Swaps L <-> R (C unchanged)
                result[sid] = 2 - result[sid];
            }
            if (layoutBits == 2) {
                // Center First (10): Swaps L <-> R and moves centered SIDs to the end.
                int centered = 0;
                while (centered < result.length && result[centered] == CENTER) centered++;
                int[] reversed = new int[result.length];
                System.arraycopy(result, centered, reversed, 0, result.length - centered);
                java.util.Arrays.fill(reversed, result.length - centered, result.length, CENTER);
                result = reversed;
            } else if (layoutBits == 3) {
                // Fully Centered (11): All SIDs remain centered.
                java.util.Arrays.fill(result, CENTER);
            }
        } else if (modeBits == 2) {
            // Mode 10 (Group):
            // Groups consecutive panning assignments.
            if (layoutBits == 3 || sidCount == 1) {
                // Fully Centered (11) or N=1:
                // All SIDs remain C.
                java.util.Arrays.fill(result, CENTER);
            } else if (layoutBits == 0) {
                // Standard (00):
                // For one SID, assign to C. For two SIDs, assign L-R.
                // For >2 SIDs, divide into consecutive pairs alternating L and R, starting with L:
                //  1: C                            9: L-L-R-R-L-L-R-R-L
                //  2: L-R                         10: L-L-R-R-L-L-R-R-L-L
                //  3: L-L-R                       11: L-L-R-R-L-L-R-R-L-L-R
                //  4: L-L-R-R                     12: L-L-R-R-L-L-R-R-L-L-R-R
                //  5: L-L-R-R-L                   13: L-L-R-R-L-L-R-R-L-L-R-R-L
                //  6: L-L-R-R-L-L                 14: L-L-R-R-L-L-R-R-L-L-R-R-L-L
                //  7: L-L-R-R-L-L-R               15: L-L-R-R-L-L-R-R-L-L-R-R-L-L-R
                //  8: L-L-R-R-L-L-R-R
                if (sidCount == 2) {
                    result[0] = LEFT;
                    result[1] = RIGHT;
                } else {
                    for (int sid = 0; sid < sidCount; sid++) {
                        result[sid] = (sid / 2) % 2 == 0 ? LEFT : RIGHT;
                    }
                }
            } else if (layoutBits == 1) {
                // L/C/R (01):
                // 1-9 SIDs: Single group.
                // 10-15 SIDs: Group of 6 SIDs followed by remaining group of 4-9 SIDs.
                // For each group of N SIDs:
                // L-count = floor((N + 1) / 3), R-count = floor((N + 1) / 3), C-count = N - L-count - R-count
                // Output all L, C, and R in order per group:
                //  1: C                            9: L-L-L-C-C-C-R-R-R
                //  2: L-R                         10: L-L-C-C-R-R-L-C-C-R
                //  3: L-C-R                       11: L-L-C-C-R-R-L-L-C-R-R
                //  4: L-C-C-R                     12: L-L-C-C-R-R-L-L-C-C-R-R
                //  5: L-L-C-R-R                   13: L-L-C-C-R-R-L-L-C-C-C-R-R
                //  6: L-L-C-C-R-R                 14: L-L-C-C-R-R-L-L-L-C-C-R-R-R
                //  7: L-L-C-C-C-R-R               15: L-L-C-C-R-R-L-L-L-C-C-C-R-R-R
                //  8: L-L-L-C-C-R-R-R
                int[] groupSizes = sidCount >= 10 ? new int[]{6, sidCount - 6} : new int[]{sidCount};
                int offset = 0;
                for (int gSize : groupSizes) {
                    int lCount = (gSize + 1) / 3;
                    int rCount = (gSize + 1) / 3;
                    int cCount = gSize - lCount - rCount;
                    for (int i = 0; i < lCount; i++) result[offset++] = LEFT;
                    for (int i = 0; i < cCount; i++) result[offset++] = CENTER;
                    for (int i = 0; i < rCount; i++) result[offset++] = RIGHT;
                }
            } else /* layoutType == 2 */ {
                // Center First (10):
                // L-count = floor(N / 3), R-count = floor(N / 3), C-count = N - L-count - R-count
                // Output C exactly C-count times. Append remaining positions according to L-count:
                // 0: Output nothing, 1: Output L-R, Even: Alternate pairs (L-L, R-R, ...),
                // Odd (>1): Output L-L-L and R-R-R first, then alternate remaining pairs (L-L, R-R, ...)
                //  1: C                            9: C-C-C-L-L-L-R-R-R
                //  2: C-C                         10: C-C-C-C-L-L-L-R-R-R
                //  3: C-L-R                       11: C-C-C-C-C-L-L-L-R-R-R
                //  4: C-C-L-R                     12: C-C-C-C-L-L-R-R-L-L-R-R
                //  5: C-C-C-L-R                   13: C-C-C-C-C-L-L-R-R-L-L-R-R
                //  6: C-C-L-L-R-R                 14: C-C-C-C-C-C-L-L-R-R-L-L-R-R
                //  7: C-C-C-L-L-R-R               15: C-C-C-C-C-L-L-L-R-R-R-L-L-R-R
                //  8: C-C-C-C-L-L-R-R
                int lCount = sidCount / 3;
                int rCount = sidCount / 3;
                int cCount = sidCount - lCount - rCount;
                int offset = 0;
                for (int i = 0; i < cCount; i++) {
                    result[offset++] = CENTER;
                }
                if (lCount == 1) {
                    result[offset++] = LEFT;
                    result[offset++] = RIGHT;
                } else if (lCount > 1) {
                    int remainingPairs;
                    if (lCount % 2 != 0) {
                        result[offset++] = LEFT;
                        result[offset++] = LEFT;
                        result[offset++] = LEFT;
                        result[offset++] = RIGHT;
                        result[offset++] = RIGHT;
                        result[offset++] = RIGHT;
                        remainingPairs = (lCount - 3) / 2;
                    } else {
                        remainingPairs = lCount / 2;
                    }
                    for (int p = 0; p < remainingPairs; p++) {
                        result[offset++] = LEFT;
                        result[offset++] = LEFT;
                        result[offset++] = RIGHT;
                        result[offset++] = RIGHT;
                    }
                }
            }
        } else if (modeBits == 3) {
            // Mode 11 (Spread):
            // Distribute SIDs across the available panning positions.
            if (layoutBits == 3 || sidCount == 1) {
                // Fully Centered (11) or N=1:
                // All SIDs remain C.
                java.util.Arrays.fill(result, CENTER);
            } else if (layoutBits == 0) {
                // Standard (00) [L...R]:
                // Split evenly. An odd total count adds 1 to L-count.
                //  1: C                            9: L-L-L-L-L-R-R-R-R
                //  2: L-R                         10: L-L-L-L-L-R-R-R-R-R
                //  3: L-L-R                       11: L-L-L-L-L-L-R-R-R-R-R
                //  4: L-L-R-R                     12: L-L-L-L-L-L-R-R-R-R-R-R
                //  5: L-L-L-R-R                   13: L-L-L-L-L-L-L-R-R-R-R-R-R
                //  6: L-L-L-R-R-R                 14: L-L-L-L-L-L-L-R-R-R-R-R-R-R
                //  7: L-L-L-L-R-R-R               15: L-L-L-L-L-L-L-L-R-R-R-R-R-R-R
                //  8: L-L-L-L-R-R-R-R
                int left = (sidCount + 1) / 2;
                int right = sidCount - left;
                int offset = 0;
                for (int i = 0; i < left; i++) result[offset++] = LEFT;
                for (int i = 0; i < right; i++) result[offset++] = RIGHT;
            } else if (layoutBits == 1) {
                // L/C/R (01) [L...C...R]:
                // L-count = floor(N / 3), R-count = floor(N / 3), C-count = N - L-count - R-count
                //  1: C                            9: L-L-L-C-C-C-R-R-R
                //  2: C-C                         10: L-L-L-C-C-C-C-R-R-R
                //  3: L-C-R                       11: L-L-L-C-C-C-C-C-R-R-R
                //  4: L-C-C-R                     12: L-L-L-L-C-C-C-C-R-R-R-R
                //  5: L-C-C-C-R                   13: L-L-L-L-C-C-C-C-C-R-R-R-R
                //  6: L-L-C-C-R-R                 14: L-L-L-L-C-C-C-C-C-C-R-R-R-R
                //  7: L-L-C-C-C-R-R               15: L-L-L-L-L-C-C-C-C-C-R-R-R-R-R
                //  8: L-L-C-C-C-C-R-R
                int left = sidCount / 3;
                int right = sidCount / 3;
                int centered = sidCount - left - right;
                int offset = 0;
                for (int i = 0; i < left; i++) result[offset++] = LEFT;
                for (int i = 0; i < centered; i++) result[offset++] = CENTER;
                for (int i = 0; i < right; i++) result[offset++] = RIGHT;
            } else /* layoutType == 2 */ {
                // Center First (10) [C...L...R]:
                // C-count = N - L-count - R-count, L-count = floor(N / 3), R-count = floor(N / 3)
                //  1: C                            9: C-C-C-L-L-L-R-R-R
                //  2: C-C                         10: C-C-C-C-L-L-L-R-R-R
                //  3: C-L-R                       11: C-C-C-C-C-L-L-L-R-R-R
                //  4: C-C-L-R                     12: C-C-C-C-L-L-L-L-R-R-R-R
                //  5: C-C-C-L-R                   13: C-C-C-C-C-L-L-L-L-R-R-R-R
                //  6: C-C-L-L-R-R                 14: C-C-C-C-C-C-L-L-L-L-R-R-R-R
                //  7: C-C-C-L-L-R-R               15: C-C-C-C-C-L-L-L-L-L-R-R-R-R-R
                //  8: C-C-C-C-L-L-R-R
                int left = sidCount / 3;
                int right = sidCount / 3;
                int centered = sidCount - left - right;
                int offset = 0;
                for (int i = 0; i < centered; i++) result[offset++] = CENTER;
                for (int i = 0; i < left; i++) result[offset++] = LEFT;
                for (int i = 0; i < right; i++) result[offset++] = RIGHT;
            }
        }
        return result;
    }

    @Override
    public byte[] getPSidHeader() {
        return header.getArray();
    }

    @Override
    public int getPSidVersion() {
        return header == null ? 0 : header.version & 0xffff;
    }

    /**
     * Convert 32-bit PSID-style speed word to internal tables.
     *
     * @param speed The speed to convert.
     */
    protected void convertOldStyleSpeedToTables(long speed) {
        for (int s = 0; s < SIDTUNE_MAX_SONGS; s++) {
            int i = Math.min(s, 31);
            if ((speed & 1 << i) != 0) {
                songSpeed[s] = CIA_1A;
            } else {
                songSpeed[s] = VBI;
            }
        }
    }

    @Override
    public int getSongSpeedWord() {
        int speed = 0;
        for (int i = 0; i < 32; ++i) {
            if (songSpeed[i] != VBI) {
                speed |= 1 << i;
            }
        }
        return speed;
    }

    @Override
    public Speed getSongSpeed(int selected) {
        return songSpeed[selected - 1];
    }

    @Override
    public void save(final String name) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(!name.endsWith(".sid") ? name + ".sid" : name)) {
            final PSidHeader header = new PSidHeader();
            header.id = "PSID".getBytes(ISO_8859_1);
            // Extended routing and metadata belong to the file version, including BASIC and small SID layouts.
            int version = getPSidVersion();
            boolean v5 = version == PSidHeader.VERSION_5;
            boolean v4e = version == PSidHeader.VERSION_4E;
            header.data = PSidHeader.SIZE;
            if (v5 || v4e) {
                header.version = (short) version;
            } else {
                if (info.compatibility == RSIDv4 || info.sidChipBase[2] != 0) {
                    header.version = 4;
                } else if (info.sidChipBase[1] != 0) {
                    header.version = 3;
                } else {
                    header.version = 2;
                }
            }

            header.songs = (short) info.songs;
            header.start = (short) info.startSong;
            header.speed = getSongSpeedWord();

            header.init = (short) info.initAddr;
            header.relocStartPage = (byte) info.relocStartPage;
            header.relocPages = (byte) info.relocPages;

            if (v5) {
                header.multiSidConfig = (byte) info.multiSidConfig;
                header.sidAddressConfigStart = (byte) info.sidAddressConfigStart;
            } else if (v4e) {
                header.furtherFlags = this.header.furtherFlags.clone();
                header.data += (short) (header.furtherFlags.length * Short.BYTES);
            } else {
                if (info.sidChipBase[1] != 0) {
                    header.sidChip2MiddleNybbles = (byte) ((info.sidChipBase[1] & 0x2FFF) >> 4);
                }
                if (info.sidChipBase[2] != 0) {
                    header.sidChip3MiddleNybbles = (byte) ((info.sidChipBase[2] & 0x2FFF) >> 4);
                }
            }

            header.flags = 0;
            switch (info.compatibility) {
                case RSID_BASIC:
                    header.flags |= PSID_BASIC;
                    //$FALL-THROUGH$

                case RSIDv2:
                case RSIDv3:
                case RSIDv4:
                case RSIDv4E:
                case RSIDv5:
                    header.id = "RSID".getBytes(ISO_8859_1);
                    header.speed = 0;
                    break;

                case PSIDv1:
                    throw new IOException("PSID-specific files are not supported by this player");

                default:
                    header.play = (short) info.playAddr;
                    break;
            }

            if (info.infoString.size() == 3) {
                Iterator<String> descriptionIt = info.infoString.iterator();
                String title = descriptionIt.next();
                String author = descriptionIt.next();
                String released = descriptionIt.next();
                if (v5) {
                    header.setV5Strings(title, author, released);
                } else {
                    if (header.version == 2 && (title.length() == 32 || author.length() == 32 || released.length() == 32)) {
                        header.version = 3;
                    }
                    byte[] titleBytes = title.getBytes(ISO_8859_1);
                    System.arraycopy(titleBytes, 0, header.name, 0, titleBytes.length);
                    byte[] authorBytes = author.getBytes(ISO_8859_1);
                    System.arraycopy(authorBytes, 0, header.author, 0, authorBytes.length);
                    byte[] releasedBytes = released.getBytes(ISO_8859_1);
                    System.arraycopy(releasedBytes, 0, header.released, 0, releasedBytes.length);
                }
            }

            header.flags |= info.clockSpeed.ordinal() << 2;
            header.flags |= info.sidModel[0].ordinal() << 4;
            if (v5) {
                header.flags |= info.panningLayout << 6 | info.panningMode << 8;
                if (info.songLengthsIncluded) header.flags |= V5_SONG_LENGTHS;
                if (info.fmOpl) header.flags |= V5_FM_OPL;
            } else if (v4e) {
                header.flags |= (info.channel[0] > .5f ? 1 : 0) << 6;
            } else {
                header.flags |= info.sidModel[1].ordinal() << 6;
                header.flags |= info.sidModel[2].ordinal() << 8;
            }

            fos.write(header.getArray());

            final byte[] saveAddr = new byte[2];
            saveAddr[0] = (byte) (info.loadAddr & 255);
            saveAddr[1] = (byte) (info.loadAddr >> 8);
            fos.write(saveAddr);
            fos.write(program, programOffset, info.c64dataLen);
            if (v5 && info.songLengthsIncluded && info.songLengths != null) {
                for (long value : info.songLengths) {
                    int milliseconds = (int) value;
                    int minutes = milliseconds / 60000;
                    int seconds = milliseconds / 1000 % 60;
                    int millis = milliseconds % 1000;
                    fos.write(minutes / 10 << 4 | minutes % 10);
                    fos.write(seconds / 10 << 4 | seconds % 10);
                    fos.write(millis / 100);
                    fos.write((millis / 10 % 10) << 4 | millis % 10);
                }
            }
        }

    }

    /**
     * Calculate MD5 checksum.
     *
     * @return MD5 checksum as hex string
     */
    @Override
    public String getMD5Digest(MD5Method md5Method) {
        if (md5Method == MD5Method.MD5_PSID_HEADER) {
            final byte[] myMD5 = new byte[info.c64dataLen + 6 + info.songs + (info.clockSpeed == NTSC ? 1 : 0)];
            System.arraycopy(program, programOffset, myMD5, 0, info.c64dataLen);
            int i = info.c64dataLen;
            myMD5[i++] = (byte) (info.initAddr & 0xff);
            myMD5[i++] = (byte) (info.initAddr >> 8);
            myMD5[i++] = (byte) (info.playAddr & 0xff);
            myMD5[i++] = (byte) (info.playAddr >> 8);
            myMD5[i++] = (byte) (info.songs & 0xff);
            myMD5[i++] = (byte) (info.songs >> 8);
            for (int s = 1; s <= info.songs; s++) {
                myMD5[i++] = (byte) getSongSpeed(s).speedValue();
            }
            // Deal with PSID v2NG clock speed flags: Let only NTSC
            // clock speed change the MD5 fingerprint. That way the
            // fingerprint of a PAL-speed sidtune in PSID v1, v2, and
            // PSID v2NG format is the same.
            if (info.clockSpeed == NTSC) {
                myMD5[i] = (byte) info.clockSpeed.ordinal();
                // NB! If the fingerprint is used as an index into a
                // song-lengths database or cache, modify the above code to
                // allow for PSID v2NG files which have clock speed set to
                // SIDTUNE_CLOCK_ANY. If the SID player program fully
                // supports the SIDTUNE_CLOCK_ANY setting, a sidtune could
                // either create two different fingerprints depending on
                // the clock speed chosen by the player, or there could be
                // two different values stored in the database/cache.
            }

            StringBuilder md5 = new StringBuilder();
            try {
                final byte[] encryptMsg = MessageDigest.getInstance("MD5").digest(myMD5);
                for (final byte anEncryptMsg : encryptMsg) {
                    md5.append(Character.forDigit((anEncryptMsg >> 4) & 0xF, 16));
                    md5.append(Character.forDigit((anEncryptMsg & 0xF), 16));
                }
            } catch (final NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
            return md5.toString();
        } else {
            // md5Method == MD5_CONTENTS
            return super.getMD5Digest(md5Method);
        }
    }

    @Override
    public long getInitDelay() {
        // 2.5ms does not always work well (e.g., RSIDs like Synth_sample)!
        return info.compatibility == RSID_BASIC || isRsidMachineCode() ? RESET_INIT_DELAY
                : 2141000L /* PSID Out_Run.sid of Jason Brooks plays too slowly using 2500L */;
    }

    private boolean isRsidMachineCode() {
        return switch (info.compatibility) {
            case RSIDv2, RSIDv3, RSIDv4, RSIDv4E, RSIDv5 -> true;
            default -> false;
        };
    }

}