C64.java

package libsidplay;

import libsidplay.common.*;
import libsidplay.common.Event.Phase;
import libsidplay.components.c1530.DatasetteEnvironment;
import libsidplay.components.c1541.C1541Environment;
import libsidplay.components.c1541.IParallelCable;
import libsidplay.components.cart.Cartridge;
import libsidplay.components.cart.CartridgeType;
import libsidplay.components.cart.CartridgeWithREU;
import libsidplay.components.cart.MusicCartridge;
import libsidplay.components.cart.supported.GeoRAM;
import libsidplay.components.cart.supported.MagicDesk;
import libsidplay.components.cart.supported.REU;
import libsidplay.components.cart.supported.SFXSoundExpander;
import libsidplay.components.joystick.IJoystick;
import libsidplay.components.keyboard.Keyboard;
import libsidplay.components.mos6510.IMOS6510Extension;
import libsidplay.components.mos6510.MOS6510;
import libsidplay.components.mos6526.MOS6526;
import libsidplay.components.mos656x.MOS6567;
import libsidplay.components.mos656x.MOS6567R56A;
import libsidplay.components.mos656x.MOS6569;
import libsidplay.components.mos656x.PALEmulation;
import libsidplay.components.mos656x.VIC;
import libsidplay.components.pla.Bank;
import libsidplay.components.pla.PLA;
import libsidplay.components.printer.UserportPrinterEnvironment;
import libsidplay.components.ram.SystemRAMBank;
import libsidutils.debug.InspectionService;
import libsidutils.oscilloscope.OscilloscopeService;
import sidplay.player.StereoSnifferDetectedTuneInfo;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;

import static java.nio.charset.StandardCharsets.US_ASCII;
import static libsidplay.common.SIDEmu.NONE;
import static libsidplay.config.ISidPlay2SystemProperties.MAX_SIDS;
import static libsidutils.CBMCodeUtils.petsciiToScreenRam;

/**
 * Commodore 64 emulation core.
 * <p>
 * It consists of the following chips: PLA, MOS6510, MOS6526(a), VIC 6569(PAL)/6567(NTSC), RAM/ROM.<BR> Some connectors
 * exist additionally: Keyboard, two Joysticks, parallel cable and some memory expansions and other cartridges can be
 * plugged in.
 *
 * @author Antti Lankila
 * @author Ken Händel
 *
 */
public abstract class C64 implements DatasetteEnvironment, C1541Environment, UserportPrinterEnvironment {

    private OscilloscopeService oscilloscope;
    private InspectionService inspection;

    /** Lazily created tooling; unused machines have no inspection events or collection. */
    public InspectionService getInspection() {
        if (inspection == null) {
            inspection = new InspectionService(this);
        }
        return inspection;
    }

    public InspectionService peekInspection() {
        return inspection;
    }

    /**
     * One lazily created collector per emulator, shared by all view subscriptions.
     */
    public synchronized OscilloscopeService getOscilloscope() {
        if (oscilloscope == null) {
            oscilloscope = new OscilloscopeService(this);
        }
        return oscilloscope;
    }

    /**
     * RAM screen address for a user typed-in command.
     */
    private static final int RAM_COMMAND_SCREEN_ADDRESS = 1024 + 6 * 40;
    /**
     * RAM location for a user typed-in command.
     */
    private static final int RAM_COMMAND = 0x277;
    /**
     * RAM location for a user typed-in command length.
     */
    private static final int RAM_COMMAND_LEN = 0xc6;
    /**
     * Maximum length for a user typed-in command.
     */
    private static final int MAX_COMMAND_LEN = 16;

    /**
     * System clock
     */
    protected CPUClock clock = CPUClock.PAL;

    /**
     * MMU chip
     */
    private final PLA pla;

    /**
     * CPU
     */
    private final MOS6510 cpu;

    private IntConsumer cpuExecutionObserver;

    /**
     * CIA1
     */
    protected final MOS6526 cia1;

    /**
     * CIA2
     */
    protected final MOS6526 cia2;

    /**
     * Keyboard
     */
    protected final Keyboard keyboard;

    /**
     * Attached parallel cable
     */
    protected IParallelCable parallelCable;

    /**
     * Specific VIC used for PAL.
     */
    protected final VIC palVic;

    /**
     * Specific VIC used for NTSC.
     */
    protected final VIC ntscVic;

    /**
     * System memory array
     */
    protected final SystemRAMBank ramBank = new SystemRAMBank();

    /**
     * System event context
     */
    protected final EventScheduler context;

    /**
     * C64 hardware model.
     */
    private final C64Model model;

    /**
     * Immutable configuration targets, not yet applied to VIC behavior.
     */
    private final VICConfiguration vicConfiguration;

    private final VICModel vicModel;

    /**
     * Glue logic between CIA2 and the VIC bank lines.
     */
    private final C64GlueLogic glueLogic;

    /**
     * Number of entrances to play routine to determine tune speed
     */
    protected int callsToPlayRoutine;
    /**
     * Last time tune speed has been measured
     */
    private long lastUpdate;
    /**
     * detected tune speed
     */
    private double tuneSpeed;

    /**
     * The interested party for playroutine entrances.
     */
    protected IMOS6510Extension playRoutineObserver;

    /**
     * Joystick port devices
     */
    protected final IJoystick[] joystickPort = new IJoystick[2];

    /**
     * Implementation of a disconnected Joystick
     */
    private final IJoystick disconnectedJoystick = () -> (byte) 0xff;

    /**
     * Area backed by RAM, including cpu port addresses 0 and 1.
     * <p>
     * This is a bit of a fake. We know that the CPU port is an internal detail of the CPU, and therefore CPU should
     * simply pay the price for reading/writing to 0/1.
     * <p>
     * However, that would slow down all accesses, which is suboptimal. Therefore, we install this little hook to the 4k
     * 0 region to deal with this.
     *
     * @author Antti Lankila
     */
    protected class ZeroRAMBank extends Bank {
        /**
         * Value written to processor port.
         */
        private byte dir;
        private byte data;

        /**
         * Value read from the processor port.
         */
        private byte dataRead;

        /**
         * State of processor port pins.
         */
        private byte dataOut;

        /**
         * $01 bits 6 and 7 fall-off cycles (1-&gt;0), average is about 350 msec
         */
        private static final long C64_CPU_DATA_PORT_FALL_OFF_CYCLES = 350000;

        /**
         * cycle that should invalidate the unused bits of the data port.
         */
        private long dataSetClkBit6;
        private long dataSetClkBit7;

        /**
         * indicates if the unused bits of the data port are still valid or should be read as 0, 1 = unused bits valid,
         * 0 = unused bits should be 0
         */
        private boolean dataSetBit6;
        private boolean dataSetBit7;

        /**
         * indicated if the unused bits are in the process of falling off.
         */
        private boolean dataFalloffBit6;
        private boolean dataFalloffBit7;

        /**
         * Tape motor status.
         */
        private byte oldPortDataOut;
        /**
         * Tape write line status.
         */
        private byte oldPortWriteBit;

        public void reset() {
            oldPortDataOut = (byte) 0xff;
            oldPortWriteBit = (byte) 0xff;
            // Reset clears the latch and pins; input pull-ups are applied by updateCpuPort().
            data = 0;
            dataOut = 0;
            dataRead = 0;
            dir = 0;
            dataSetBit6 = false;
            dataSetBit7 = false;
            dataFalloffBit6 = false;
            dataFalloffBit7 = false;
            updateCpuPort();
        }

        private void updateCpuPort() {
            dataOut = (byte) (dataOut & ~dir | data & dir);
            dataRead = (byte) ((data | ~dir) & (dataOut | 0x17));
            // Output pins actively drive their latch value, including after a
            // DATA preload while input. Each floating bit then retains its own charge.
            if ((dir & 0x40) != 0) {
                dataSetBit6 = (data & 0x40) != 0;
                dataFalloffBit6 = false;
            }
            if ((dir & 0x80) != 0) {
                dataSetBit7 = (data & 0x80) != 0;
                dataFalloffBit7 = false;
            }
            pla.setCpuPort(dataRead);

            if (0 == (dir & 0x20)) {
                dataRead &= 0xdf;
            }
            if (0 == (dir & 0x10) && C64.this.getTapeSense()) {
                dataRead &= 0xef;
            }

            if ((dir & data & 0x20) != oldPortDataOut) {
                oldPortDataOut = (byte) (dir & data & 0x20);
                C64.this.setMotor(0 == oldPortDataOut);
            }

            if (((~dir | data) & 0x8) != oldPortWriteBit) {
                oldPortWriteBit = (byte) ((~dir | data) & 0x8);
                C64.this.toggleWriteBit(((~dir | data) & 0x8) != 0);
            }
        }

        @Override
        public byte read(final int address) {
            if (address == 0) {
                return dir;
            } else if (address == 1) {
                if (dataFalloffBit6 || dataFalloffBit7) {
                    if (dataFalloffBit6 && dataSetClkBit6 < context.getTime(Phase.PHI2)) {
                        dataFalloffBit6 = false;
                        dataSetBit6 = false;
                    }

                    if (dataFalloffBit7 && dataSetClkBit7 < context.getTime(Phase.PHI2)) {
                        dataSetBit7 = false;
                        dataFalloffBit7 = false;
                    }
                }
                return (byte) (dataRead & 0xff - (((!dataSetBit6 ? 1 : 0) << 6) + ((!dataSetBit7 ? 1 : 0) << 7)));
            } else {
                return ramBank.read(address);
            }
        }

        @Override
        public void write(final int address, byte value) {
            if (address == 0) {
                if (dataSetBit7 && (value & 0x80) == 0 && !dataFalloffBit7) {
                    dataFalloffBit7 = true;
                    dataSetClkBit7 = context.getTime(Phase.PHI2) + C64_CPU_DATA_PORT_FALL_OFF_CYCLES;
                }
                if (dataSetBit6 && (value & 0x40) == 0 && !dataFalloffBit6) {
                    dataFalloffBit6 = true;
                    dataSetClkBit6 = context.getTime(Phase.PHI2) + C64_CPU_DATA_PORT_FALL_OFF_CYCLES;
                }
                dir = value;
                updateCpuPort();
                value = pla.getDisconnectedBusBank().read(address);
            } else if (address == 1) {
                data = value;
                updateCpuPort();
                value = pla.getDisconnectedBusBank().read(address);
            }
            ramBank.write(address, value);
        }
    }

    /**
     * Zero-page memory bank
     */
    private final ZeroRAMBank zeroRAMBank = new ZeroRAMBank();

    /**
     * Set the play routine address to watch by CPU emulation.
     *
     * @param playAddr Observe calls of SID player (JSR $PlayAddr).
     */
    public void setPlayAddr(final int playAddr) {
        cpu.setJmpJsrHandler(Register_ProgramCounter -> {
            if (Register_ProgramCounter == playAddr) {
                if (playRoutineObserver != null) {
                    playRoutineObserver.jmpJsr();
                }
                callsToPlayRoutine++;
            }
        });
    }

    /**
     * Determine tune speed (calls of play routine per frame).
     *
     * @return current tune speed
     */
    public final double determineTuneSpeed() {
        final double cpuFreq = clock.getCpuFrequency();
        final long now = context.getTime(Event.Phase.PHI1);
        final double interval = now - lastUpdate;
        if (interval >= cpuFreq) {
            lastUpdate = now;
            tuneSpeed = callsToPlayRoutine * cpuFreq / (interval * getScreenRefresh());
            callsToPlayRoutine = 0;
        }
        return tuneSpeed;
    }

    public final void setParallelCable(final IParallelCable parallelCable) {
        this.parallelCable = parallelCable;
    }

    private final class C64GlueLogic {

        private int oldVicBank;

        private final Event vicBankSwitch = Event.of("C64C VIC bank switch",
                event -> pla.setVicMemBase(oldVicBank << 14));

        private void reset() {
            context.cancel(vicBankSwitch);
            oldVicBank = 0;
            pla.setVicMemBase(0);
        }

        private void setVicBank(final int vicBank, final boolean ddrChange) {
            // A newer request supersedes any transition still waiting to settle.
            context.cancel(vicBankSwitch);
            int newVicBank = vicBank;
            if (model.hasCustomGlueLogic() && !ddrChange
                    && (oldVicBank ^ vicBank) == 3
                    && vicBank != 0
                    && (vicBank & (vicBank - 1)) == 0) {
                // PRA transitions 1 <-> 2 briefly expose bank 3. DDRA changes
                // take effect immediately in fetchsplit's common/M7 hardware
                // profile; other measured machines vary with temperature.
                newVicBank = 3;
                context.schedule(vicBankSwitch, 1);
            }
            pla.setVicMemBase(newVicBank << 14);

            /*
             * This is the requested bank, not necessarily the bank currently
             * visible to VIC while the custom-glue transition is pending.
             */
            oldVicBank = vicBank;
        }
    }

    public C64(byte[] charBin, byte[] basicBin, byte[] kernalBin) {
        this(C64Model.C64C, charBin, basicBin, kernalBin);
    }

    public C64(final C64Model model, byte[] charBin, byte[] basicBin, byte[] kernalBin) {
        this(model, VICModel.DEFAULT, charBin, basicBin, kernalBin);
    }

    /**
     * Construct a machine with an independent VIC override. A new machine is required to apply a different selection;
     * CIA and glue logic continue to follow the C64 model. Existing palette output is preserved.
     */
    public C64(final C64Model model, final VICModel vicModel,
                byte[] charBin, byte[] basicBin, byte[] kernalBin) {
        this.model = model;
        this.vicModel = java.util.Objects.requireNonNull(vicModel, "vicModel");
        this.vicConfiguration = vicModel.resolve(model);
        context = new EventScheduler();

        cpu = new MOS6510(context) {
            @Override
            protected void fetchNextOpcode() {
                if (cpuExecutionObserver != null) {
                    cpuExecutionObserver.accept(Register_ProgramCounter);
                }
                super.fetchNextOpcode();
            }

            @Override
            protected byte cpuRead(int address) {
                return pla.cpuRead(address);
            }

            @Override
            protected void cpuWrite(int address, byte data) {
                pla.cpuWrite(address, data);
            }

            @Override
            protected void nmiAcknowledged() {
                getCartridge().nmiAcknowledged();
            }
        };

        pla = new PLA(context, zeroRAMBank, ramBank, charBin, basicBin, kernalBin, model == C64Model.C64C);

        glueLogic = new C64GlueLogic();

        pla.setCpu(cpu);

        palVic = new MOS6569(pla, context);
        // Bind implemented PAL timing rules to the selected chip, independently of the palette.
        palVic.setGreyDotBugEnabled(vicConfiguration.getPalModel() == VICChipModel.MOS8565);
        palVic.setLightpenTiming(vicConfiguration.getPalModel());
        palVic.setVideoModeTiming(vicConfiguration.getPalModel());
        palVic.setPalEmulation(new PALEmulation(VICChipModel.MOS6567R8));

        ntscVic = vicConfiguration.getNtscModel() == VICChipModel.MOS6567R56A
                ? new MOS6567R56A(pla, context) : new MOS6567(pla, context);
        ntscVic.setGreyDotBugEnabled(vicConfiguration.getNtscModel() == VICChipModel.MOS8562);
        ntscVic.setLightpenTiming(vicConfiguration.getNtscModel());
        ntscVic.setVideoModeTiming(vicConfiguration.getNtscModel());
        ntscVic.setPalEmulation(new PALEmulation(VICChipModel.MOS6567R8));

        pla.setVic(palVic);

        cia1 = new MOS6526(context, model.getCiaModel()) {
            @Override
            public void interrupt(final boolean state) {
                pla.setIRQ(state);
            }

            @Override
            public void writePRA(final byte data, final boolean ddrChange) {
            }

            @Override
            public void writePRB(final byte data) {
                if ((data & 0x10) == 0) {
                    getVIC().triggerLightpen();
                } else {
                    getVIC().clearLightpen();
                }
            }

            @Override
            public byte readPRA() {
                final byte joyB = joystickPort[0].getValue();
                final byte joyA = joystickPort[1].getValue();
                final byte paPins = (byte) ((regs[PRA] | ~regs[DDRA]) & joyA);
                final byte pbPins = (byte) ((regs[PRB] | ~regs[DDRB]) & joyB);
                // An input pulled high is not equivalent to an actively-high PB
                // output when an indirect keyboard path is scanned in reverse.
                final byte pbOutputHigh = (byte) (regs[PRB] & regs[DDRB]);
                return (byte) (keyboard.readColumn(paPins, pbPins, pbOutputHigh) & joyA);
            }

            @Override
            public byte readPRB() {
                final byte joyA = joystickPort[1].getValue();
                final byte joyB = joystickPort[0].getValue();
                final byte paPins = (byte) ((regs[PRA] | ~regs[DDRA]) & joyA);
                final byte pbPins = (byte) ((regs[PRB] | ~regs[DDRB]) & joyB);
                final byte paOutputLow = (byte) (regs[DDRA] & ~regs[PRA]);
                final byte pbOutputHigh = (byte) (regs[PRB] & regs[DDRB]);
                return (byte) (keyboard.readRow(paPins, pbPins, paOutputLow, pbOutputHigh) & joyB);
            }

            @Override
            public void pulse() {
                /* Nobody home */
            }
        };
        pla.setCia1(cia1);

        cia2 = new MOS6526(context, model.getCiaModel()) {
            @Override
            public void interrupt(final boolean state) {
                pla.setNMI(state);
            }

            @Override
            public void writePRA(final byte data, final boolean ddrChange) {
                glueLogic.setVicBank(~data & 3, ddrChange);
                C64.this.writeToIECBus((byte) ~data);
                C64.this.printerUserportWriteStrobe((data & 0x04) != 0);

            }

            @Override
            public void writePRB(final byte data) {
                parallelCable.c64Write(data);
                C64.this.printerUserportWriteData(data);
            }

            @Override
            public byte readPRA() {
                return (byte) (C64.this.readFromIECBus() | 0x3f);
            }

            @Override
            public byte readPRB() {
                return parallelCable.c64Read();
            }

            @Override
            public void pulse() {
                parallelCable.pulse();
            }
        };
        pla.setCia2(cia2);

        keyboard = new Keyboard() {
            @Override
            public void restore() {
                /*
                 * in reality, the PLA chip has a RESTORE line, and it pulls the NMI low. We're
                 * modeling the overall NMI and IRQ state in the PLA, so we can't really do
                 * that. We just pulse NMI instead.
                 */
                pla.setNMI(true);
                pla.setNMI(false);
            }
        };

        setJoystick(0, null);
        setJoystick(1, null);
        if (vicModel != VICModel.DEFAULT) setClock(vicModel.getClock());
    }

    /**
     * Perform the equivalent of full power-on reset of C64, re-initializing everything.
     */
    public void reset() {
        context.reset();
        keyboard.reset();
        pla.reset();
        glueLogic.reset();
        cpuExecutionObserver = null;
        cpu.setJmpJsrHandler(null);
        cpu.triggerRST();
        cia1.reset();
        cia2.reset();
        getVIC().reset();
        zeroRAMBank.reset();
        ramBank.reset();

        callsToPlayRoutine = 0;
        lastUpdate = 0;
        tuneSpeed = 0;
        if (oscilloscope != null) {
            oscilloscope.reset();
        }
        if (inspection != null) {
            inspection.reset();
        }
    }

    /**
     * Return the array backing C64 RAM
     *
     * @return the RAM
     */
    public byte[] getRAM() {
        return ramBank.array();
    }

    /**
     * Return CPU emulator
     *
     * @return the cpu
     */
    public MOS6510 getCPU() {
        return cpu;
    }

    /**
     * Observe instruction fetch addresses without reading memory or changing CPU execution.
     * Set on the emulation thread; null removes the observer. Reset also removes it.
     */
    public void setCpuExecutionObserver(IntConsumer observer) {
        cpuExecutionObserver = observer;
    }

    /**
     * Inspect the active CPU read mapping without a bus access.
     */
    public boolean isCpuReadFromRam(int address) {
        return pla.isCpuReadFromRam(address);
    }

    /**
     * Install a play routine observer to hook the JSR command of the CPU. It gets called if the player address gets
     * called.
     *
     * @param observer play routine observer
     */
    public void setPlayRoutineObserver(final IMOS6510Extension observer) {
        playRoutineObserver = observer;
    }

    /**
     * Get VIC chip emulator (PAL/NTSC).
     *
     * @return VIC chip
     */
    public VIC getVIC() {
        return clock == CPUClock.NTSC ? ntscVic : palVic;
    }

    public int getVicMemBase() {
        return pla.getVicMemBase();
    }

    /**
     * Insert SID chips to be used.
     *
     * @param sidCreator Responsible to decide which SID chips we need (SIDEmu) and which we don't need (NONE). SID
     *                   number and old SID are mapped to new SID.
     * @param sidLocator Responsible to determine the base address of the SID chips we need
     */
    public final void insertSIDChips(BiFunction<Integer, SIDEmu, SIDEmu> sidCreator, IntFunction<Integer> sidLocator) {
        for (int sidNum = 0; sidNum < MAX_SIDS; sidNum++) {
            SIDEmu oldSid = pla.getSIDBank().getSID(sidNum);
            if (oldSid != NONE) {
                pla.getSIDBank().unplugSID(sidNum, oldSid, sidLocator.apply(sidNum));
            }
            SIDEmu newSid = sidCreator.apply(sidNum, oldSid);
            if (newSid != NONE) {
                pla.getSIDBank().plugInSID(sidNum, newSid, sidLocator.apply(sidNum));
            }
        }
        if (oscilloscope != null) {
            oscilloscope.sidConfigurationChanged();
        }
    }

    /**
     * Configure PAL and NTSC VIC.
     *
     * @param action VIC consumer
     */
    public void configureVICs(Consumer<VIC> action) {
        action.accept(palVic);
        action.accept(ntscVic);
    }

    /**
     * Configure all available SIDs.
     *
     * @param action SID chip consumer
     */
    public final void configureSIDs(BiConsumer<Integer, SIDEmu> action) {
        for (int chipNum = 0; chipNum < MAX_SIDS; chipNum++) {
            final SIDEmu sid = pla.getSIDBank().getSID(chipNum);
            if (sid != NONE) {
                action.accept(chipNum, sid);
            }
        }
    }

    /**
     * Configure one specific SID.
     *
     * @param chipNum SID chip number
     * @param action  SID chip consumer
     */
    public final void configureSID(int chipNum, Consumer<SIDEmu> action) {
        final SIDEmu sid = pla.getSIDBank().getSID(chipNum);
        if (sid != NONE) {
            action.accept(sid);
        }
    }

    /**
     * Get SID register write notifications.
     */
    public void setSIDListener(SIDListener listener) {
        pla.getSIDBank().setSIDListener(listener);
    }

    /**
     * Set the system clock (PAL/NTSC).
     *
     * @param clock system clock (PAL/NTSC)
     */
    protected void setClock(CPUClock clock) {
        if (vicModel != VICModel.DEFAULT) clock = vicModel.getClock();
        this.clock = clock;

        context.setCyclesPerSecond(clock.getCpuFrequency());

        final int powerFrequency =
                clock == CPUClock.NTSC ? 60 : 50;

        cia1.setDayOfTimeRate(
                clock.getCpuFrequency(),
                powerFrequency);

        cia2.setDayOfTimeRate(
                clock.getCpuFrequency(),
                powerFrequency);

        pla.setVic(getVIC());
    }

    /**
     * Get system clock (PAL/NTSC).
     *
     * @return system clock (PAL/NTSC)
     */
    public CPUClock getClock() {
        return clock;
    }

    /** Frame length of the active VIC, including the 64-cycle early NTSC model. */
    public final int getCyclesPerFrame() {
        return getVIC().getCyclesPerFrame();
    }

    public final double getScreenRefresh() {
        return clock.getCpuFrequency() / getCyclesPerFrame();
    }

    public C64Model getModel() {
        return model;
    }

    /**
     * Return the immutable targets selected at construction time.
     */
    public final VICModel getVicModel() {
        return vicModel;
    }

    public final VICConfiguration getVicConfiguration() {
        return vicConfiguration;
    }

    /**
     * Return the chip identity for the active clock, with the currently implemented revision-specific behavior.
     */
    public final VICChipModel getConfiguredVicModel() {
        return vicConfiguration.getModel(clock);
    }

    /**
     * Get C64's event scheduler
     *
     * @return the scheduler
     */
    public EventScheduler getEventScheduler() {
        return context;
    }

    /**
     * Installs a custom Kernal ROM.
     *
     * @param kernalRom Kernal ROM replacement (null means original Kernal)
     */
    public void setCustomKernal(final byte[] kernalRom) {
        if (kernalRom == null) {
            pla.setCustomKernalRomBank(null);
        } else {
            pla.setCustomKernalRomBank(new Bank() {
                @Override
                public byte read(final int address) {
                    return kernalRom[address & 0x1fff];
                }

                @Override
                public void write(final int address, final byte value) {
                    throw new RuntimeException("This bank should never be mapped to W mode");
                }
            });
        }
    }

    /**
     * Get current keyboard emulation.
     *
     * @return current keyboard emulation
     */
    public Keyboard getKeyboard() {
        return keyboard;
    }

    /**
     * Set joystick implementation.
     *
     * @param portNumber     joystick port (0-1)
     * @param joystickReader joystick implementation or null (disconnected)
     */
    public final void setJoystick(final int portNumber, final IJoystick joystickReader) {
        joystickPort[portNumber] = joystickReader == null ? disconnectedJoystick : joystickReader;
    }

    /**
     * Is joystick connected?
     *
     * @param portNumber joystick port (0-1)
     * @return joystick connected?
     */
    public final boolean isJoystickConnected(final int portNumber) {
        return !joystickPort[portNumber].equals(disconnectedJoystick);
    }

    /**
     * Insert a cartridge of a given size with empty contents.
     *
     * @param type   cartridge type
     * @param sizeKB size in KB
     * @throws IOException never thrown here
     */
    public final void setCartridge(final CartridgeType type, final int sizeKB) throws IOException {
        pla.setCartridge(configuredCartridge(Cartridge.create(pla, type, sizeKB)));
    }

    /**
     * Insert a cartridge loading an image file.
     *
     * @param type cartridge type
     * @param file file to load the RAM contents
     * @throws IOException image read error
     */
    public final void setCartridge(final CartridgeType type, final File file) throws IOException {
        pla.setCartridge(configuredCartridge(Cartridge.read(pla, type, file)));
    }

    /**
     * Insert a cartridge of type CRT loading an image.
     *
     * @param is input stream to load the RAM contents
     * @throws IOException image read error
     */
    public final void setCartridgeCRT(final InputStream is) throws IOException {
        setCartridgeCRT(is, false);
    }

    /** Load a CRT, optionally retaining an explicitly prepared REU. */
    public final void setCartridgeCRT(final InputStream is, final boolean withREU) throws IOException {
        Cartridge cart = Cartridge.readCRT(pla, new DataInputStream(is));
        Cartridge current = getCartridge();
        REU reu = current instanceof CartridgeWithREU bundle ? bundle.getREU()
                : current instanceof REU expansion ? expansion : null;
        pla.setCartridge(configuredCartridge(withREU && reu != null ? new CartridgeWithREU(cart, reu) : cart));
    }

    private boolean starTreuWorkaround;

    /** Enable the optional StarTreu compatibility fixes for a recognised cartridge. */
    public final void setStarTreuWorkaround(boolean enable) {
        starTreuWorkaround = enable;
        configuredCartridge(getCartridge());
    }

    private Cartridge configuredCartridge(Cartridge cartridge) {
        Cartridge primary = cartridge instanceof CartridgeWithREU bundle ? bundle.getCartridge() : cartridge;
        boolean active = primary instanceof MagicDesk magicDesk && magicDesk.setStarTreuWorkaround(starTreuWorkaround);
        if (cartridge instanceof CartridgeWithREU bundle) bundle.getREU().setStarTreuWorkaround(active);
        return cartridge;
    }

    /** Explicitly select a REU alongside the current CRT; zero removes only the REU. */
    public final void setREU(final int sizeKB) throws IOException {
        if (sizeKB == 0) {
            Cartridge current = getCartridge();
            if (current instanceof CartridgeWithREU bundle) pla.setCartridge(bundle.getCartridge());
            else if (current instanceof REU) ejectCartridge();
        } else {
            attachREU((REU) Cartridge.create(pla, CartridgeType.REU, sizeKB));
        }
    }

    /** Select an image-backed REU without replacing the current CRT. */
    public final void setREU(final File image) throws IOException {
        attachREU((REU) Cartridge.read(pla, CartridgeType.REU, image));
    }

    private void attachREU(REU reu) {
        Cartridge current = getCartridge();
        if (current instanceof CartridgeWithREU bundle) current = bundle.getCartridge();
        // GeoRAM, Sound Expander and the internal music cartridge remain exclusive devices.
        boolean bundle = isCartridge() && !(current instanceof REU) && !(current instanceof GeoRAM)
                && !(current instanceof SFXSoundExpander) && !(current instanceof MusicCartridge);
        pla.setCartridge(configuredCartridge(bundle ? new CartridgeWithREU(current, reu) : reu));
    }

    /**
     * Get the current multipurpose cartridge of the expansion port of the C64.
     *
     * @return multipurpose cartridge
     */
    public final Cartridge getCartridge() {
        return pla.getCartridge();
    }

    /**
     * @return is a multipurpose cartridge inserted into the expansion port of the C64?
     */
    public boolean isCartridge() {
        return pla.isCartridge();
    }

    /**
     * Eject multipurpose cartridge from the expansion port of the C64.
     */
    public final void ejectCartridge() {
        pla.setCartridge(null);
    }

    /**
     * Inject a prepared command. Command preparation is owned by
     * {@link HardwareEnsemble#typeInCommand(String)}.
     *
     * @param multiLineCommand command to type-in (PETSCII)
     */
    final void typeInCommand(final String multiLineCommand) {
        String command;
        if (multiLineCommand.length() > MAX_COMMAND_LEN) {
            String[] lines = multiLineCommand.split("\r");
            for (String line : lines) {
                byte[] screenRam = petsciiToScreenRam(line);
                if (screenRam.length > 80) throw new IllegalArgumentException("BASIC command exceeds 80 columns");
                System.arraycopy(screenRam, 0, getRAM(), RAM_COMMAND_SCREEN_ADDRESS, screenRam.length);
                // The editor follows logical lines, not contiguous screen bytes. Link
                // the second physical row for the 1571 mode command plus LOAD.
                int row = (RAM_COMMAND_SCREEN_ADDRESS - 1024) / 40;
                getRAM()[0xd9 + row] |= (byte) 0x80;
                if (screenRam.length > 40) getRAM()[0xd9 + row + 1] &= 0x7f;
                else getRAM()[0xd9 + row + 1] |= (byte) 0x80;
                getRAM()[0xd5] = (byte) (screenRam.length > 40 ? 79 : 39);
                break;
            }
            int indexOf = multiLineCommand.indexOf('\r');
            command = indexOf != -1 ? multiLineCommand.substring(indexOf) : "\r";
        } else {
            command = multiLineCommand;
        }
        final int length = Math.min(command.length(), MAX_COMMAND_LEN);
        System.arraycopy(command.getBytes(US_ASCII), 0, getRAM(), RAM_COMMAND, length);
        getRAM()[RAM_COMMAND_LEN] = (byte) length;
    }

    /** Enable detailed sniffer evidence; raw writes and register caches are always retained. */
    public void setStereoSnifferEnabled(boolean enabled) {
        pla.setStereoSnifferEnabled(enabled);
    }

    public StereoSnifferDetectedTuneInfo getStereoSnifferDetectedTuneInfo() {
        var activity = pla.getSidWriteActivity();
        return new StereoSnifferDetectedTuneInfo(activity.getActiveSidBases(), activity.sidWriteOccurred());
    }

}