ExportedApi.java

package client.teavm.common;

import builder.jexsid.JExSIDMapping;
import builder.jhardsid.JHardSIDMapping;
import builder.jusbsid.JUSBSIDMapping;
import builder.resid.ReSIDBase;
import builder.resid.ReSIDBuilder;
import client.teavm.common.audio.AudioDriverTeaVM;
import client.teavm.common.autoplay.KeyEventType;
import client.teavm.common.config.ConfigurationTeaVM;
import client.teavm.common.config.FilterSectionTeaVM;
import client.teavm.common.oscilloscope.Oscilloscope;
import client.teavm.common.video.PALEmulationTeaVM;
import client.teavm.common.video.VicePALEmulationTeaVM;
import libsidplay.C64;
import libsidplay.HardwareEnsemble;
import libsidplay.common.*;
import libsidplay.components.c1530.Datasette.Control;
import libsidplay.components.c1541.FloppyType;
import libsidplay.components.cart.CartridgeType;
import libsidplay.components.cart.supported.GeoRAM;
import libsidplay.components.keyboard.KeyTableEntry;
import libsidplay.components.printer.PrinterConnection;
import libsidplay.components.printer.PrinterModel;
import libsidplay.config.*;
import libsidplay.sidtune.SidTune;
import libsidplay.sidtune.SidTuneError;
import libsidutils.debug.InspectionService;
import libsidutils.debug.InspectionTimeline;
import libsidutils.prg2tap.PRG2TAP;
import libsidutils.prg2tap.PRG2TAPProgram;
import libsidutils.sidid.SidIdInfo.PlayerInfoSection;
import libsidutils.status.Status;
import sidplay.consoleplayer.ConsoleIO;
import sidplay.player.*;
import sidplay.player.Timer;
import ui.common.util.SidTuneInfoDetails;
import ui.entities.collection.HVSCEntry;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.function.Function;

import static client.teavm.JsonUtilitiesTeaVM.stringify;
import static client.teavm.JsonUtilitiesTeaVM.toJSObject;
import static com.fasterxml.jackson.databind.EnumNamingStrategies.LOWER_CASE;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.Map.of;
import static java.util.stream.Collectors.joining;
import static libsidplay.common.ChipModel.getChipModel;
import static libsidplay.common.Emulation.getEmulation;
import static libsidplay.common.Engine.EMULATION;
import static libsidplay.common.Engine.getEngine;
import static libsidplay.common.SIDEmu.NONE;
import static libsidplay.config.ISidPlay2SystemProperties.MAX_SIDS;
import static libsidplay.sidtune.SidTune.*;
import static libsidplay.sidtune.SidTune.Model.UNKNOWN;
import static libsidutils.IOUtils.*;
import static ui.musiccollection.SearchCriteria.getText;

/**
 * The {@code ExportedApi} class provides the external API that allows interaction with the C64 SID chip emulator and
 * audio playback. It acts as a bridge between the client-side application and the emulator, handling the loading,
 * configuration, and playback of SID tunes, while also managing the emulation of hardware components like the CPU, VIC,
 * and SID chips.
 *
 * <p>
 * Key responsibilities of this class include:
 * </p>
 * <ul>
 * <li>Initializing and configuring the emulator environment, including loading
 * SID tunes, setting up the audio driver, and managing hardware components like
 * C64, SID, and VIC.</li>
 * <li>Handling playback parameters such as song selection, loop settings, and
 * play length.</li>
 * <li>Providing a mechanism for interacting with external modules, like the
 * sound expander cartridge or loading custom cartridge files.</li>
 * <li>Exposing methods for event scheduling, audio playback, and emulation
 * control.</li>
 * <li>Validating and logging critical operations to ensure the emulator runs
 * smoothly.</li>
 * </ul>
 *
 * <p>
 * This class interfaces directly with lower-level components like the event
 * scheduler, SID chip emulator, and audio driver to ensure that the emulator
 * works efficiently. It also supports various features such as detecting PSID64
 * files, interacting with a playlist, and supporting integration with external
 * APIs.
 * </p>
 *
 * <p>
 * Usage Example:
 * </p>
 *
 * <pre>
 * // Initialize the ExportedApi with necessary parameters
 * exportedApi = new ExportedApi(importedApiInstance, args);
 *
 * // Open a SID tune file for playback
 * exportedApi.open(sidContents, sidContentsName, songIndex, nthFrame, addSidListener, cartContents, cartContentsName,
 * 		command, songLength, sfxSoundExpander, sfxSoundExpanderType, companionContents, companionName);
 *
 * // Trigger clock ticks to advance the emulation state and emit samples and frames
 * exportedApi.clock();
 * </pre>
 *
 * <p>
 * The {@code ExportedApi} class also provides methods for customizing the
 * behavior of the emulator, such as adjusting the default play length and
 * enabling or disabling looped playback of SID tunes.
 * </p>
 *
 * <p>
 * Methods are available for controlling playback, managing hardware emulation,
 * and integrating with external modules such as sound expanders or cartridge
 * files.
 * </p>
 *
 * @see client.teavm.common.audio.AudioDriverTeaVM
 * @see libsidplay.sidtune.SidTune
 * @see libsidplay.common.EventScheduler
 * @see libsidplay.config.IConfig
 * @see sidplay.consoleplayer.ConsoleIO
 */
public final class ExportedApi implements IExportedApi {

    private static final String RUN = "RUN\r", SYS = "SYS%d\r", LOAD = "LOAD\r";
    private static final String HEADING = "Java SIDPlay2 - Music Player & C64 SID Chip Emulator";
    private static final String HVSC_ENTRY = "HVSCEntry";
    private static final Function<String, String> RESOURCE_BUNDLE = LOWER_CASE::convertEnumToExternalName;

    private final IImportedApi importedApi;
    private final ILogger LOG;
    private final MainArgs mainArgs;

    private final IConfig config;
    private final ISidPlay2Section sidplay2Section;
    private final IAudioSection audioSection;
    private final IEmulationSection emulationSection;
    private final List<? extends IFilterSection> filterSections;
    private final IC1541Section c1541Section;
    private final IPrinterSection printerSection;
    private final IWhatsSidSection whatsSidSection;
    private final WarpControl startupWarp = new WarpControl(System::nanoTime, this::applyStartupWarp);

    private EventScheduler context;
    private SidTune tune;
    private HVSCEntry hvscEntry;
    private double databaseSongLength;
    private PlayList playList;
    private HardwareEnsemble hardwareEnsemble;
    private C64 c64;

    private boolean starTreuWorkaround;
    private ReSIDBuilder sidBuilder;
    private AudioDriverTeaVM audioDriver;
    private boolean forceCheckSongLength;
    private Timer timer;
    private Status status;
    private String command;
    private Collection<String> playerIds;
    private String playerId;
    private Autodetection autodetection;
    private Oscilloscope oscilloscope;
    private boolean soundSetupRequested;
    private int fastForwardWhatsSIDRequests;
    private int bufferSize;
    private AutostartControl autostartControl;
    private InspectionService.Subscription inspectionSubscription;
    private InspectionService.VideoSubscription inspectionVideoSubscription;

    public ExportedApi(IImportedApi importedApi, String[] args) {
        this.importedApi = importedApi;
        LOG = mainArgs = new MainArgs(args);

        config = new ConfigurationTeaVM();
        sidplay2Section = config.getSidplay2Section();
        audioSection = config.getAudioSection();
        emulationSection = config.getEmulationSection();
        filterSections = config.getFilterSection();
        c1541Section = config.getC1541Section();
        printerSection = config.getPrinterSection();
        whatsSidSection = config.getWhatsSidSection();
    }

    @Override
    public void open(byte[] sidContents, String sidContentsName, int song, int nthFrame, boolean addSidListener,
                     byte[] cartContents, String cartContentsName, String command, double songLength, boolean sfxSoundExpander,
                     int sfxSoundExpanderType, byte[] companionContents, String companionName) {
        try {
            if (inspectionSubscription != null) {
                inspectionSubscription.close();
                inspectionSubscription = null;
            }
            if (inspectionVideoSubscription != null) {
                inspectionVideoSubscription.close();
                inspectionVideoSubscription = null;
            }
            if (oscilloscope != null) {
                oscilloscope.stop();
                oscilloscope = null;
            }
            if (autostartControl != null) {
                autostartControl.cancel();
            }
            startupWarp.setManual(false);
            this.command = command;

            doLog(sidplay2Section, audioSection, emulationSection, c1541Section);

            if (sidContents != null || (sidContentsName != null && getBuiltIn(sidContentsName) != null)) {
                if (sidContents == null) {
                    sidContents = getBuiltIn(sidContentsName);
                    sidContentsName += ".prg";
                }
                LOG.fine("Load Tune, length=" + sidContents.length);
                LOG.fine("Tune name: " + sidContentsName);
                tune = SidTune.load(sidContentsName, sidContents, companionName, companionContents);
                tune.getInfo().setSelectedSong(song == 0 ? null : song);
                LOG.fine("Song: " + tune.getInfo().getSelectedSong());
                LOG.fine("SongLength: " + songLength);

                playerIds = tune.identify(SID_ID_CFG_BIN);
                playerId = String.join(",", playerIds);

                hvscEntry = new HVSCEntry(() -> songLength, sidContentsName, "", sidContents.length, 0, tune, playerId);
                databaseSongLength = songLength;
            } else {
                LOG.fine("RESET");
                tune = RESET;
                hvscEntry = null;
                databaseSongLength = 0;
            }
            LOG.fine("nthFrame: " + nthFrame);
            LOG.fine("addSidListener: " + addSidListener);
            LOG.fine("sfxSoundExpander: " + sfxSoundExpander);
            LOG.fine("sfxSoundExpanderType: " + sfxSoundExpanderType);
            if (cartContentsName != null) {
                LOG.fine("Cart, length=: " + cartContents.length);
                LOG.fine("Cart name: : " + cartContentsName);
            }
            doLog(emulationSection, tune);

            // propagate control buffer, only required using SharedArrayBuffers!
            importedApi.initControlBuffer();

            hardwareEnsemble = new HardwareEnsemble(config, CHAR_ROM, BASIC_ROM, KERNAL_ROM,
                    JIFFY_DOS_C64_ROM, JIFFY_DOS_C1541_ROM, JIFFY_DOS_C1571_ROM, JIFFY_DOS_C1581_ROM,
                    C1541_ROM, C1541_II_ROM, C1571_ROM, C1581_ROM, MPS803_ROM);
            CPUClock cpuClock = CPUClock.getCPUClock(emulationSection, tune);
            hardwareEnsemble.setClock(cpuClock);
            hardwareEnsemble.getPrinter().setPaper(importedApi::processPrinter);
            c64 = hardwareEnsemble.getC64();
            c64.setStarTreuWorkaround(starTreuWorkaround);
            c64.getVIC().setPalEmulation(nthFrame > 0 ?
                    cpuClock == CPUClock.PAL && sidplay2Section.getPalEmulationMode() == PalEmulationMode.VICE
                            ? new VicePALEmulationTeaVM(importedApi, nthFrame)
                            : new PALEmulationTeaVM(importedApi, nthFrame, cpuClock, COMBINED_LINES_EVEN, COMBINED_LINES_ODD,
                            LINE_PALETTE_EVEN, LINE_PALETTE_ODD) : null);
            context = c64.getEventScheduler();

            boolean fmOpl = isFMOpl(config.getEmulationSection(), tune);
            if (fmOpl || sfxSoundExpander) {
                insertCart(CartridgeType.SOUNDEXPANDER, fmOpl ? 1 : sfxSoundExpanderType);
            } else if (cartContents != null) {
                insertCart(cartContents, cartContentsName);
            }
            hardwareEnsemble.reset();
            boolean cartridgeBoot = AutostartControl.isCartridgeBoot(c64, tune == RESET, this.command);
            autostartControl = new AutostartControl(c64, this::typeInCommand, startupWarp::finishStartup);
            sidBuilder = new ReSIDBuilder(context, config, cpuClock, c64.getCartridge());
            sidBuilder.setScreenRefresh(c64.getScreenRefresh());
            ByteBuffer wavBuffer = importedApi.initWhatsSidBuffer(sidBuilder.getWhatsSidSupport().getWavBufferSize());

            context.schedule(Event.of("Auto-start", event -> {
                if (tune != RESET) {
                    // for tunes: Install player into RAM
                    Integer driverAddress = tune.placeProgramInMemory(c64.getRAM(), PSID_DRIVER_BIN, MUS_DRIVER1_BIN, MUS_DRIVER2_BIN);
                    if (driverAddress != null) {
                        // Set play address to feedback call frames counter.
                        c64.setPlayAddr(tune.getInfo().getPlayAddr());
                        // Start SID player driver
                        c64.getCPU().forcedJump(driverAddress);
                    } else {
                        // No player: Start a basic program or assembler code
                        final int loadAddr = tune.getInfo().getLoadAddr();
                        this.command = loadAddr == 0x0801 ? RUN : loadAddr >= 0x0801 ? format(SYS, loadAddr) : null;
                    }
                }
                if (this.command != null) {
                    if (this.command.startsWith(LOAD)) {
                        // Load from tape needs someone to press play
                        hardwareEnsemble.getDatasette().control(Control.START);
                    }
                    // Enter basic command
                    if (tune != RESET || !autostartControl.start(this.command)) {
                        startupWarp.finishStartup();
                        typeInCommand(this.command);
                    }
                }
                if (tune != RESET || this.command == null || !AutostartControl.isLoadCommand(this.command)) {
                    startupWarp.finishStartup();
                }
                autodetection.start(tune);
            }), cartridgeBoot ? 0 : SidTune.getInitDelay(tune));

            boolean usb = emulationSection.getEngine().isHardwareBased();
            audioDriver = new AudioDriverTeaVM(importedApi, AUD_LOOKUP_TABLE, sidBuilder, usb, nthFrame);
            audioDriver.open(audioSection, null, cpuClock, context);
            sidBuilder.setAudioDriver(audioDriver);

            updateSIDChipConfiguration();
            if (nthFrame > 0) {
                c64.configureVICs(vic -> vic.setVideoDriver(audioDriver));
            }
            if (emulationSection.getEngine() != EMULATION || addSidListener) {
                c64.setSIDListener(audioDriver);
            }

            timer = new Timer(sidplay2Section, context, () -> songLength) {

                @Override
                protected long getInitDelay(SidTune tune) {
                    return cartridgeBoot ? 0 : super.getInitDelay(tune);
                }

                @Override
                public void start() {
                }

                @Override
                public void end() {
                    bufferSize = 0;
                    try {
                        try {
                            sidBuilder.flushAudio();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new IllegalStateException(e);
                        }
                    } finally {
                        importedApi.processTimerEnd(timer.getEnd());
                    }
                }

                @Override
                public void fadeInStart(final double fadeIn) {
                    sidBuilder.fadeIn(fadeIn);
                }

                @Override
                public void fadeOutStart(final double fadeOut) {
                    sidBuilder.fadeOut(fadeOut);
                }

            };
            timer.setStart(0);
            timer.setDefaultLength(sidplay2Section.getDefaultPlayLength());
            timer.setForceCheckSongLength(forceCheckSongLength);
            timer.reset(tune);

            playList = new PlayList(sidplay2Section, tune, true);

            autodetection = new Autodetection(emulationSection, c64, timer) {
                @Override
                protected AudioActivitySource getAudioActivitySource() {
                    return sidBuilder;
                }

                @Override
                protected void updateSids() {
                    updateSIDChipConfiguration();
                }
            };

            status = new Status(hardwareEnsemble, tune, sidBuilder, audioDriver, tune -> null, timer,
                    () -> autodetection.isPsid64Detected(), () -> autodetection.isStereoSniffed(), RESOURCE_BUNDLE);

            if (whatsSidSection.isEnable()) {
                int matchStartTimeInSeconds = whatsSidSection.getMatchStartTime();
                if (songLength > 0 && songLength < matchStartTimeInSeconds) {
                    // song is too short? start at 90%
                    matchStartTimeInSeconds = Math.min((int) (songLength * 0.9), matchStartTimeInSeconds);
                }
                context.schedule(Event.of("WhatsSID?", event -> {
                    int fastForwardBitMask = sidBuilder.getFastForwardBitMask();
                    if ((fastForwardWhatsSIDRequests++ & fastForwardBitMask) == fastForwardBitMask) {
                        wavBuffer.clear();
                        wavBuffer.put(sidBuilder.getWhatsSidSupport().createWAV());
                        importedApi.whatsSid(wavBuffer);
                    }
                    int matchRetryTimeInSeconds = whatsSidSection.getMatchRetryTime();
                    context.schedule(event, (long) (matchRetryTimeInSeconds * context.getCyclesPerSecond()));

                }), (long) (matchStartTimeInSeconds * context.getCyclesPerSecond()));

                sidBuilder.getWhatsSidSupport().reset();
            }
            if (emulationSection.getEngine() == EMULATION && audioDriver.supportsWarp()
                    && sidplay2Section.isWarpOnStartup() && !cartridgeBoot) {
                startupWarp.start(sidplay2Section.getWarpStartupTimeout());
            }
            sidBuilder.start();
            bufferSize = audioSection.getBufferSize();

            if (tune != RESET) {
                ConsoleIO consoleIO = new ConsoleIO(config, sidContentsName, key -> key.equals("HEADING") ? HEADING
                        : LOWER_CASE.convertEnumToExternalName(key));
                consoleIO.menu(tune, playList, timer, mainArgs.getVerbose(), mainArgs.isQuiet(), false, System.out);
            }
        } catch (Exception e) {
            cancelStartup();
            LOG.severe(e.getMessage());
            throw new IllegalStateException(format("Cannot open tune '%s'.", sidContentsName != null ? sidContentsName : "RESET"), e);
        }
    }

    @Override
    public void clock() {
        try {
            pollStartupWarp();
            InspectionService inspection = c64.peekInspection();
            if (inspection != null && (inspection.isArmed() || inspection.isPaused())) {
                inspection.clock(bufferSize);
            } else {
                // Preserve the original loop when no breakpoint can stop this batch.
                for (int i = 0; i < bufferSize; i++) {
                    context.clock();
                }
            }
            flushOscilloscope();
        } catch (Exception e) {
            cancelStartup();
            LOG.severe(e.getMessage());
            throw new IllegalStateException("Cannot clock.", e);
        }
    }

    @Override
    public void inspection(String action, int channels, String type, int target, int value, int mask, boolean oneShot) {
        if (c64 == null) throw new IllegalStateException("Start playback before using inspection");
        InspectionService service = c64.getInspection();
        service.setPauseHandler(snapshot -> importedApi.processInspection(snapshot.toJson()));
        switch (action) {
            case "SHOW" -> {
                if (inspectionVideoSubscription == null) inspectionVideoSubscription = service.watchVideo();
                if (service.timeline() != null) sendTimeline(service.timeline());
            }
            case "HIDE" -> {
                if (inspectionVideoSubscription != null) inspectionVideoSubscription.close();
                inspectionVideoSubscription = null;
            }
            case "LIVE" -> {
                if (inspectionSubscription != null) inspectionSubscription.close();
                inspectionSubscription = service.subscribe(channels, snapshot -> {
                    if (!snapshot.paused()) importedApi.processInspection(snapshot.toJson());
                });
            }
            case "OFF" -> {
                if (inspectionSubscription != null) inspectionSubscription.close();
                inspectionSubscription = null;
            }
            case "SNAPSHOT" -> {
                importedApi.processInspection(service.snapshot(channels).toJson());
                return;
            }
            case "FREEZE" -> {
                service.freeze(channels);
                return;
            }
            case "RESUME" -> service.resume();
            case "ARM" -> service.arm(new InspectionService.Breakpoint(
                    InspectionService.BreakpointType.valueOf(type), target, value, mask, oneShot));
            case "DISARM" -> service.disarm();
            case "REMOVE" -> service.removeBreakpoint(target);
            case "RECORD_TIMELINE" -> {
                service.recordTimeline(this::sendTimeline);
                return;
            }
            case "CANCEL_TIMELINE" -> {
                if (service.isRecordingTimeline()) service.cancelTimeline();
                else sendTimeline(service.timeline());
                return;
            }
            case "CLEAR_TIMELINE" -> {
                service.clearTimeline();
                sendTimeline(null);
                return;
            }
            case "GET_TIMELINE" -> {
                sendTimeline(service.timeline());
                return;
            }
            default -> throw new IllegalArgumentException("Unknown inspection action");
        }
        importedApi.processInspection((service.isPaused() && service.latest() != null && !action.equals("SNAPSHOT")
                ? service.latest().withArmed(service.breakpointCount())
                : service.snapshot(channels & ~InspectionService.VIDEO)).toJson());
    }

    private void sendTimeline(InspectionTimeline timeline) {
        importedApi.processInspection(timeline == null ? InspectionTimeline.clearedMessageJson() : timeline.messageJson());
    }

    private void cancelStartup() {
        bufferSize = 0;
        if (autostartControl != null) {
            autostartControl.cancel();
        }
        startupWarp.finishStartup();
    }

    @Override
    public void pollStartupWarp() {
        startupWarp.poll();
    }

    private void applyStartupWarp(boolean enabled) {
        sidBuilder.setWarp(enabled);
        importedApi.processWarp(enabled);
        if (oscilloscope != null) {
            c64.getOscilloscope().sidConfigurationChanged();
        }
    }

    //
    // ISidplay2Section methods
    //

    @Override
    public void defaultPlayLength(double defaultPlayLength) {
        LOG.fine(format("defaultPlayLength: %f", defaultPlayLength));

        sidplay2Section.setDefaultPlayLength(defaultPlayLength);

        if (isOpen()) {
            timer.setDefaultLength(defaultPlayLength);
            timer.updateEnd(tune);
        }
    }

    @Override
    public void loop(boolean loop) {
        LOG.fine(format("loop: %b", loop));

        sidplay2Section.setLoop(loop);
    }

    @Override
    public void single(boolean single) {
        LOG.fine(format("single: %b", single));

        sidplay2Section.setSingle(single);
    }

    @Override
    public void palEmulationEnable(boolean palEmulationEnable, PalEmulationMode palEmulationMode) {
        LOG.fine(format("palEmulationEnable: %b, palEmulationMode: %s", palEmulationEnable, palEmulationMode));

        sidplay2Section.setPalEmulation(palEmulationEnable);
        sidplay2Section.setPalEmulationMode(palEmulationMode);

        if (isOpen()) {
            Optional.ofNullable(c64.getVIC().getPalEmulation())
                    .ifPresent(palEmu -> palEmu.setPalEmulationEnable(palEmulationEnable));
        }
    }

    @Override
    public void turboTape(boolean turboTape) {
        LOG.fine(format("turboTape: %b", turboTape));

        sidplay2Section.setTurboTape(turboTape);
    }

    @Override
    public void startupWarp(boolean warpOnStartup, int warpStartupTimeout) {
        WarpControl.validateTimeout(warpStartupTimeout);
        sidplay2Section.setWarpOnStartup(warpOnStartup);
        sidplay2Section.setWarpStartupTimeout(warpStartupTimeout);
        if (!warpOnStartup) {
            startupWarp.finishStartup();
        }
    }

    @Override
    public void fade(double fadeInTime, double fadeOutTime) {
        LOG.fine(format("fadeInTime: %f, fadeOutTime: %f", fadeInTime, fadeOutTime));

        sidplay2Section.setFadeInTime(fadeInTime);
        sidplay2Section.setFadeOutTime(fadeOutTime);
    }

    //
    // IAudioSection methods
    //

    @Override
    public void samplingRate(SamplingRate samplingRate) {
        LOG.fine(format("samplingRate: %s", samplingRate));

        audioSection.setSamplingRate(samplingRate);
    }

    @Override
    public void sampling(SamplingMethod sampling) {
        LOG.fine(format("samplingMethod: %s", sampling));

        audioSection.setSampling(sampling);
    }

    @Override
    public void volumeLevels(float mainVolume, float secondVolume, float thirdVolume, float mainBalance,
                             float secondBalance, float thirdBalance, int mainDelay, int secondDelay, int thirdDelay) {
        LOG.fine(format("mainVolume: %f, secondVolume: %f, thirdVolume: %f", mainVolume, secondVolume, thirdVolume));
        LOG.fine(format("mainBalance: %f, secondBalance: %f, thirdBalance: %f", mainBalance, secondBalance,
                thirdBalance));
        LOG.fine(format("mainDelay: %d, secondDelay: %d, thirdDelay: %d", mainDelay, secondDelay, thirdDelay));

        audioSection.setVolume(0, mainVolume);
        audioSection.setVolume(1, secondVolume);
        audioSection.setVolume(2, thirdVolume);
        audioSection.setBalance(0, mainBalance);
        audioSection.setBalance(1, secondBalance);
        audioSection.setBalance(2, thirdBalance);
        audioSection.setDelay(0, mainDelay);
        audioSection.setDelay(1, secondDelay);
        audioSection.setDelay(2, thirdDelay);

        if (isOpen()) {
            sidBuilder.setVolume(0, mainVolume);
            sidBuilder.setVolume(1, secondVolume);
            sidBuilder.setVolume(2, thirdVolume);
            sidBuilder.setBalance(0, mainBalance);
            sidBuilder.setBalance(1, secondBalance);
            sidBuilder.setBalance(2, thirdBalance);
            sidBuilder.setDelay(0, mainDelay);
            sidBuilder.setDelay(1, secondDelay);
            sidBuilder.setDelay(2, thirdDelay);
        }
    }

    @Override
    public void bufferSize(int bufferSize) {
        LOG.fine(format("bufferSize: %s", bufferSize));

        audioSection.setBufferSize(bufferSize);

        if (isOpen()) {
            this.bufferSize = bufferSize;
        }
    }

    @Override
    public void audioBufferSize(int audioBufferSize) {
        LOG.fine(format("audioBufferSize: %s", audioBufferSize));

        audioSection.setAudioBufferSize(audioBufferSize);
    }

    @Override
    public void delay(boolean delayBypass, int delay, int delayWetLevel, int delayDryLevel, int delayFeedbackLevel) {
        LOG.fine(format("delayBypass: %b, delay: %d, delayWetLevel: %d, delayDryLevel: %d, delayFeedbackLevel: %d",
                delayBypass, delay, delayWetLevel, delayDryLevel, delayFeedbackLevel));

        audioSection.setDelayBypass(delayBypass);
        audioSection.setDelay(delay);
        audioSection.setDelayWetLevel(delayWetLevel);
        audioSection.setDelayDryLevel(delayDryLevel);
        audioSection.setDelayFeedbackLevel(delayFeedbackLevel);
    }

    @Override
    public void reverb(boolean reverbBypass, float reverbComb1Delay, float reverbComb2Delay, float reverbComb3Delay,
                       float reverbComb4Delay, float reverbAllPass1Delay, float reverbAllPass2Delay, float reverbSustainDelay,
                       float reverbDryWetMix) {
        LOG.fine(format(
                "reverbBypass: %b, reverbComb1Delay: %f, reverbComb2Delay: %f, reverbComb3Delay: %f, reverbComb4Delay: %f",
                reverbBypass, reverbComb1Delay, reverbComb2Delay, reverbComb3Delay, reverbComb4Delay));
        LOG.fine(format("reverbAllPass1Delay: %f, reverbAllPass2Delay: %f, reverbSustainDelay: %f, reverbDryWetMix: %f",
                reverbAllPass1Delay, reverbAllPass2Delay, reverbSustainDelay, reverbDryWetMix));

        audioSection.setReverbBypass(reverbBypass);
        audioSection.setReverbComb1Delay(reverbComb1Delay);
        audioSection.setReverbComb2Delay(reverbComb2Delay);
        audioSection.setReverbComb3Delay(reverbComb3Delay);
        audioSection.setReverbComb4Delay(reverbComb4Delay);
        audioSection.setReverbAllPass1Delay(reverbAllPass1Delay);
        audioSection.setReverbAllPass2Delay(reverbAllPass2Delay);
        audioSection.setReverbSustainDelay(reverbSustainDelay);
        audioSection.setReverbDryWetMix(reverbDryWetMix);
    }

    //
    // IEmulationSection methods
    //

    @Override
    public void engine(Engine engine) {
        LOG.fine(format("engine: %s", engine));

        emulationSection.setEngine(engine);

    }

    @Override
    public void defaultEmulation(Emulation emulation) {
        LOG.fine(format("defaultEmulation: %s", emulation));

        emulationSection.setDefaultEmulation(emulation);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void userEmulation(Emulation userEmulation, Emulation stereoEmulation, Emulation thirdEmulation) {
        LOG.fine(format("userEmulation: %s, stereoEmulation: %s, thirdEmulation: %s", userEmulation, stereoEmulation,
                thirdEmulation));

        emulationSection.setForcedEmulation(0, userEmulation);
        emulationSection.setForcedEmulation(1, stereoEmulation);
        emulationSection.setForcedEmulation(2, thirdEmulation);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void defaultClockSpeed(CPUClock defaultClockSpeed) {
        LOG.fine(format("defaultClockSpeed: %s", defaultClockSpeed));

        emulationSection.setDefaultClockSpeed(defaultClockSpeed);
    }

    @Override
    public void userClockSpeed(CPUClock userClockSpeed) {
        LOG.fine(format("userClockSpeed: %s", userClockSpeed));

        emulationSection.setUserClockSpeed(userClockSpeed);
    }

    @Override
    public void defaultChipModel(ChipModel chipModel) {
        LOG.fine(format("defaultChipModel: %s", chipModel));

        emulationSection.setDefaultSidModel(chipModel);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void userChipModel(ChipModel userSidModel, ChipModel stereoSidModel, ChipModel thirdSIDModel) {
        LOG.fine(format("userSidModel: %s, stereoSidModel: %s, thirdSIDModel: %s", userSidModel, stereoSidModel,
                thirdSIDModel));

        emulationSection.setForcedSidModel(0, userSidModel);
        emulationSection.setForcedSidModel(1, stereoSidModel);
        emulationSection.setForcedSidModel(2, thirdSIDModel);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void overrideChipModel(ChipModel chipModel) {
        LOG.fine(format("overrideChipModel: %s", chipModel));

        boolean update = false;
        for (int sidNum = 0; sidNum < MAX_SIDS; sidNum++) {
            Model tuneSidModel = tune != RESET ? tune.getInfo().getSIDModel(0) : UNKNOWN;
            if (tuneSidModel == UNKNOWN) {
                update |= !chipModel.equals(emulationSection.getOverrideSection().getSidModel()[sidNum]);
                emulationSection.getOverrideSection().getSidModel()[sidNum] = chipModel;
            }
        }

        if (isOpen() && update) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public String hardSidMapping(int chipCount, int hardsid6581, int hardsid8580) {
        LOG.fine(format("hardSidMapping, chipCount: %d, hardsid6581: %d, hardsid8580: %d", chipCount, hardsid6581 + 1,
                hardsid8580 + 1));

        emulationSection.setHardsid6581(hardsid6581);
        emulationSection.setHardsid8580(hardsid8580);

        if (isOpen()) {
            return stringify(toJSObject(JHardSIDMapping.mapping(emulationSection, tune, chipCount)));
        }
        return null;
    }

    @Override
    public String exSidMapping() {
        LOG.fine("exSidMapping");

        if (isOpen()) {
            return stringify(toJSObject(JExSIDMapping.mapping(emulationSection, tune)));
        }
        return null;
    }

    @Override
    public String usbSidMapping() {
        LOG.fine("usbSidMapping");

        if (isOpen()) {
            return stringify(toJSObject(JUSBSIDMapping.mapping(emulationSection, tune)));
        }
        return null;
    }

    @Override
    public void filterEnable(int sidNum, boolean filterEnable) {
        LOG.fine(format("filterEnable %d, %b", sidNum, filterEnable));

        emulationSection.setFilterEnable(sidNum, filterEnable);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void filterName(Emulation emulation, ChipModel chipModel, int sidNum, String filterName) {
        LOG.fine(format("filterName %s, %s, %s", emulation, chipModel, getFilterName(sidNum, filterName)));

        emulationSection.setFilterName(sidNum, EMULATION, emulation, chipModel, filterName);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void filter(FilterSectionTeaVM filter) {
        LOG.fine(format("filter %s: " +
                        "attenuation=%f, nonlinearity=%f, " +
                        "baseResistance=%f, offset=%f, steepness=%f, minFetResistance=%f, " +
                        "k=%f, b=%f, " +
                        "filter6581CurvePosition=%f, " +
                        "filter8580CurvePosition=%f, " +
                        "voiceNonlinearity=%f, resonanceFactor=%f, ",
                filter.getName(),
                filter.getAttenuation(), filter.getNonlinearity(),
                filter.getBaseresistance(), filter.getOffset(), filter.getSteepness(), filter.getMinimumfetresistance(),
                filter.getK(), filter.getB(),
                filter.getFilter6581CurvePosition(),
                filter.getFilter8580CurvePosition(),
                filter.getVoiceNonlinearity(),
                filter.getResonanceFactor()
        ));

        Optional<? extends IFilterSection> foundFilterSection = filterSections.stream()
                .filter(f -> f.getName().equals(filter.getName()))
                .findFirst();
        if (foundFilterSection.isPresent()) {
            IFilterSection filterSection = foundFilterSection.get();

            filterSection.setAttenuation(filter.getAttenuation());
            filterSection.setNonlinearity(filter.getNonlinearity());
            filterSection.setVoiceNonlinearity(filter.getVoiceNonlinearity());
            filterSection.setBaseresistance(filter.getBaseresistance());
            filterSection.setOffset(filter.getOffset());
            filterSection.setSteepness(filter.getSteepness());
            filterSection.setMinimumfetresistance(filter.getMinimumfetresistance());
            filterSection.setK(filter.getK());
            filterSection.setB(filter.getB());
            filterSection.setFilter6581CurvePosition(filter.getFilter6581CurvePosition());
            filterSection.setFilter8580CurvePosition(filter.getFilter8580CurvePosition());
            filterSection.setVoiceNonlinearity(filter.getVoiceNonlinearity());
            filterSection.setResonanceFactor(filter.getResonanceFactor());
            if (filter.getCircuitModel() != ChipModel.AUTO) {
                filterSection.setCircuitModel(filter.getCircuitModel());
                filterSection.setCircuitCurve(filter.getCircuitCurve());
                filterSection.setCircuitRange(filter.getCircuitRange());
                filterSection.setCircuitCapacitance(filter.getCircuitCapacitance());
            }
        }

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void digiBoosted8580(boolean boost) {
        LOG.fine(format("digiBoosted8580: %b", boost));

        emulationSection.setDigiBoosted8580(boost);

        if (isOpen()) {
            c64.configureSIDs((num, sid) -> sid.setDigiBoost(boost));
        }
    }

    @Override
    public void stereo(StereoMode stereoMode, int dualSidBase, int thirdSIDBase, boolean fakeStereo,
                       SidReads sidToRead) {
        LOG.fine(format("stereoMode: %s, dualSidBase: %d, thirdSIDBase: %d", stereoMode, dualSidBase, thirdSIDBase));
        LOG.fine(format("fakeStereo: %b, sidToRead: %s", fakeStereo, sidToRead));

        emulationSection.setStereoMode(stereoMode);
        emulationSection.setDualSidBase(dualSidBase);
        emulationSection.setThirdSIDBase(thirdSIDBase);
        emulationSection.setFakeStereo(fakeStereo);
        emulationSection.setSidToRead(sidToRead);

        if (isOpen()) {
            updateSIDChipConfiguration();
        }
    }

    @Override
    public void mute(int sidNum, int voice, boolean value) {
        LOG.fine(format("mute SID%d, voice%d: %b", sidNum, voice, value));

        emulationSection.setMuteVoice(sidNum, voice, value);

        if (isOpen()) {
            c64.configureSID(sidNum, sid -> sid.setVoiceMute(voice, value));
        }
    }

    @Override
    public void detectPSID64ChipModel(boolean detectPSID64ChipModel) {
        LOG.fine("detectPSID64ChipModel: " + detectPSID64ChipModel);

        emulationSection.setDetectPSID64ChipModel(detectPSID64ChipModel);
    }

    @Override
    public void stereoSniffer(boolean stereoSniffer) {
        LOG.fine("stereoSniffer: " + stereoSniffer);

        emulationSection.setStereoSniffer(stereoSniffer);
    }

    @Override
    public void silenceTimeout(int silenceTimeout) {
        LOG.fine("silenceTimeout: " + silenceTimeout);

        emulationSection.setSilenceTimeout(silenceTimeout);
    }

    @Override
    public void c64Model(C64Model c64Model) {
        LOG.fine(format("c64Model: %s", c64Model));

        emulationSection.setC64Model(c64Model);
    }

    @Override
    public void vicModel(VICModel vicModel) {
        LOG.fine(format("vicModel: %s", vicModel));

        emulationSection.setVicModel(vicModel);
    }

    //
    // IC1541Section methods
    //

    @Override
    public void turnDriveOn(boolean driveOn) {
        LOG.fine(format("turnDriveOn: %b", driveOn));

        c1541Section.setDriveOn(driveOn);

        if (isOpen()) {
            hardwareEnsemble.enableFloppyDiskDrives(driveOn);
        }
    }

    @Override
    public void parallelCable(boolean parallelCable) {
        LOG.fine(format("parallelCable: %b", parallelCable));

        c1541Section.setParallelCable(parallelCable);
    }

    @Override
    public void jiffyDosInstalled(boolean jiffyDosInstalled) {
        LOG.fine(format("jiffyDosInstalled: %b", jiffyDosInstalled));

        c1541Section.setJiffyDosInstalled(jiffyDosInstalled);
    }

    @Override
    public void ramExpansion(boolean ramExpansion0, boolean ramExpansion1, boolean ramExpansion2, boolean ramExpansion3,
                             boolean ramExpansion4) {
        LOG.fine(format(
                "ramExpansion, ramExpansion0X2000: %b, ramExpansion0X4000: %b, ramExpansion0X6000: %b, ramExpansion0X8000: %b, ramExpansion0XA000: %b",
                ramExpansion0, ramExpansion1, ramExpansion2, ramExpansion3, ramExpansion4));

        c1541Section.setRamExpansionEnabled0(ramExpansion0);
        c1541Section.setRamExpansionEnabled1(ramExpansion1);
        c1541Section.setRamExpansionEnabled2(ramExpansion2);
        c1541Section.setRamExpansionEnabled3(ramExpansion3);
        c1541Section.setRamExpansionEnabled4(ramExpansion4);
    }

    @Override
    public void floppyType(FloppyType floppyType) {
        try {
            LOG.fine(format("floppyType: %s", floppyType));

            if (isOpen()) {
                hardwareEnsemble.setFloppyType(floppyType);
            } else {
                c1541Section.setFloppyType(floppyType);
            }
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot set floppy type '%s'.", floppyType));
        }
    }

    //
    // IPrinterSection methods
    //

    @Override
    public void printerOn(boolean printerOn) {
        LOG.fine(format("printerOn: %b", printerOn));

        printerSection.setPrinterOn(printerOn);
        if (isOpen()) {
            hardwareEnsemble.enablePrinter(printerOn);
        }
    }

    @Override
    public void printerSettings(PrinterModel model, PrinterConnection connection) {
        LOG.fine(format("printerSettings, model: %s, connection: %s", model, connection));

        printerSection.setPrinterModel(model);
        printerSection.setPrinterConnection(connection);

        if (isOpen()) {
            hardwareEnsemble.enablePrinter(printerSection.isPrinterOn());
        }
    }

    @Override
    public void flushPrinter() {
        LOG.fine("flushPrinter");

        if (isOpen()) {
            hardwareEnsemble.getPrinter().flush();
        }
    }

    //
    // IWhatsSidSection methods
    //

    @Override
    public void whatsSID(boolean enable, int captureTime, int matchStartTime, int matchRetryTime,
                         float minimumRelativeConfidence) {
        LOG.fine(format(
                "whatsSID enable: %b, captureTime: %d, matchStartTime: %d, matchRetryTime: %d, minimumRelativeConfidence: %f",
                enable, captureTime, matchStartTime, matchRetryTime, minimumRelativeConfidence));

        whatsSidSection.setEnable(enable);
        whatsSidSection.setCaptureTime(captureTime);
        whatsSidSection.setMatchStartTime(matchStartTime);
        whatsSidSection.setMatchRetryTime(matchRetryTime);
        whatsSidSection.setMinimumRelativeConfidence(minimumRelativeConfidence);
    }

    //
    // Business methods
    //

    @Override
    public void typeInCommand(String multiLineCommand) {
        LOG.fine(format("typeInCommand: %s", multiLineCommand));

        if (isOpen()) {
            hardwareEnsemble.typeInCommand(multiLineCommand);
        }
    }

    @Override
    public void typeKey(KeyTableEntry key) {
        LOG.fine(format("typeKey: %s", key));

        if (isOpen()) {
            if (key == KeyTableEntry.RESTORE) {
                c64.getKeyboard().restore();
            } else {
                c64.getKeyboard().keyPressed(key);

                context.schedule(
                        Event.of("Wait Until Virtual Keyboard Released", (e) -> c64.getKeyboard().keyReleased(key)),
                        (long) c64.getCyclesPerFrame() << 2);
            }
        }
    }

    @Override
    public void pressKey(KeyTableEntry key) {
        LOG.fine(format("pressKey: %s", key));

        if (isOpen()) {
            if (key == KeyTableEntry.RESTORE) {
                c64.getKeyboard().restore();
            } else {
                c64.getKeyboard().keyPressed(key);
            }
        }
    }

    @Override
    public void releaseKey(KeyTableEntry key) {
        LOG.fine(format("releaseKey: %s", key));

        if (isOpen()) {
            c64.getKeyboard().keyReleased(key);
        }
    }

    @Override
    public void joystick(int number, int value) {
        LOG.fine(format("joystick P%d: %d", (number + 1), value));

        if (isOpen()) {
            c64.setJoystick(number, () -> (byte) (0xff ^ value));
        }
    }

    @Override
    public void fastForward() {
        LOG.fine("fastForward");

        if (isOpen()) {
            sidBuilder.fastForward();
        }
    }

    @Override
    public void normalSpeed() {
        LOG.fine("normalSpeed");

        if (isOpen()) {
            sidBuilder.normalSpeed();
        }
    }

    @Override
    public String tuneInfo() {
        LOG.fine("tuneInfo");

        if (isOpen()) {
            return stringify(toJSObject(createTuneInfo()));
        }
        return null;
    }

    @Override
    public String playerInfo() {
        LOG.fine("playerInfo");

        if (isOpen()) {
            return stringify(toJSObject(createPlayerInfo()));
        }
        return null;
    }

    @Override
    public String playList() {
        LOG.fine("playList");

        if (isOpen()) {
            Map<String, Object> mapping = new HashMap<>();
            mapping.put("current", playList.getCurrent());
            mapping.put("length", playList.getLength());
            mapping.put("hasPrevious", playList.hasPrevious());
            mapping.put("hasNext", playList.hasNext());
            mapping.put("previous", playList.getPrevious());
            mapping.put("next", playList.getNext());
            return stringify(toJSObject(mapping));
        }
        return null;
    }

    @Override
    public String status() {
        LOG.finest("status");

        if (isOpen()) {
            return status.createStatusLine(true, playerId != null && !playerId.isEmpty() ? ", " + playerId : "");
        }
        return null;
    }

    @Override
    public String activeSettings() {
        LOG.finest("activeSettings");

        if (isOpen()) {
            return stringify(toJSObject(createActiveSettings()));
        }
        return null;
    }

    @Override
    public void insertDisk(byte[] diskContents, String diskContentsName) {
        try {
            LOG.fine(format("insertDisk: %s(%d)", diskContentsName, diskContents.length));

            if (isOpen()) {
                File diskFile = createReadOnlyFile(diskContents, diskContentsName);
                hardwareEnsemble.setExtendImagePolicy(() -> true);
                hardwareEnsemble.insertLocalDisk(diskFile);
            }
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot insert media file '%s'.", diskContentsName));
        }
    }

    @Override
    public void ejectDisk() {
        try {
            LOG.fine("ejectDisk");

            if (isOpen()) {
                hardwareEnsemble.ejectDisk();
            }
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe("Cannot eject disk.");
        }
    }

    @Override
    public void insertTape(byte[] tapeContents, String tapeContentsName) {
        try {
            LOG.fine(format("insertTape: %s(%d)", tapeContentsName, tapeContents.length));

            if (isOpen()) {
                if (!tapeContentsName.toLowerCase(Locale.US).endsWith(".tap")) {
                    // All that is not tape convert to tape, first

                    SidTune prg = SidTune.load(tapeContentsName, new ByteArrayInputStream(tapeContents));

                    PRG2TAPProgram program = new PRG2TAPProgram(prg, getFilenameWithoutSuffix(tapeContentsName),
                            PSID_DRIVER_BIN, MUS_DRIVER1_BIN, MUS_DRIVER2_BIN);

                    PRG2TAP prg2tap = new PRG2TAP();
                    prg2tap.setTurboTape(sidplay2Section.isTurboTape());
                    prg2tap.open();
                    prg2tap.addBin(program, TURBO_HEADER_ROM, TURBO_DATA_ROM, SLOW_HEADER_ROM);
                    prg2tap.close();

                    File convertedTapeFile = createReadOnlyFile(prg2tap.getResult(), tapeContentsName + ".tap");
                    hardwareEnsemble.getDatasette().insertTape(convertedTapeFile);
                } else {
                    File tapeFile = createReadOnlyFile(tapeContents, tapeContentsName);
                    hardwareEnsemble.getDatasette().insertTape(tapeFile);
                }
            }
        } catch (IOException | SidTuneError e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot insert media file '%s'.", tapeContentsName));
        }
    }

    @Override
    public void ejectTape() {
        try {
            LOG.fine("ejectTape");

            if (isOpen()) {
                hardwareEnsemble.getDatasette().ejectTape();
            }
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe("Cannot eject tape.");
        }
    }

    @Override
    public void controlDatasette(Control control) {
        LOG.fine(format("controlDatasette: %s", control));

        if (isOpen()) {
            hardwareEnsemble.getDatasette().control(control);
        }
    }

    @Override
    public void insertREUfile(byte[] cartContents, String cartContentsName) {
        try {
            LOG.fine(format("insertREU file: %s(%d)", cartContentsName, cartContents.length));

            if (isOpen()) {
                File cartFile = createReadOnlyFile(cartContents, cartContentsName);
                c64.setREU(cartFile);
                LOG.fine("REU: image attached: " + cartContentsName);
            }
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot insert media file '%s'.", cartContentsName));
        }
    }

    @Override
    public void starTreuWorkaround(boolean enable) {
        starTreuWorkaround = enable;
        if (c64 != null) c64.setStarTreuWorkaround(enable);
    }

    @Override
    public void insertREU(int sizeKb) {
        try {
            LOG.fine(format("insertREU: %d", sizeKb));

            if (isOpen()) {
                c64.setREU(sizeKb);
                LOG.fine(format("REU: sizeKb=%d", sizeKb));
            }
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot insert media sizeKb=%d.", sizeKb));
        }
    }

    @Override
    public boolean insertGeoRAMfile(byte[] contents, String name) {
        if (contents == null) return false;
        try {
            LOG.fine(format("insertGeoRAMfile file: %s(%d)", name, contents.length));

            if (isOpen()) {
                GeoRAM.imageSizeKB(contents.length);
                c64.setCartridge(CartridgeType.GEORAM, createReadOnlyFile(contents, name == null ? "georam.img" : name));
                return true;
            }
        } catch (IOException error) {
            LOG.severe(error.getMessage());
        }
        return false;
    }

    @Override
    public boolean insertGeoRAM(int sizeKb) {
        try {
            if (isOpen()) {
                LOG.fine(format("insertGeoRAM: %d", sizeKb));

                if (sizeKb == 0) {
                    if (c64.getCartridge() instanceof GeoRAM) c64.ejectCartridge();
                } else if (!(c64.getCartridge() instanceof GeoRAM geo) || geo.getSizeKB() != sizeKb) {
                    c64.setCartridge(CartridgeType.GEORAM, sizeKb);
                }
                return true;
            }
        } catch (IOException error) {
            LOG.severe(error.getMessage());
        }
        return false;
    }

    @Override
    public void getGeoRAMImage() {
        LOG.fine("getGeoRAMImage");

        importedApi.processGeoRAMImage(isOpen() && c64.getCartridge() instanceof GeoRAM geo ? geo.copyRAM() : new byte[0]);
    }

    @Override
    public void freezeCartridge() {
        LOG.fine("freezeCartridge");

        if (isOpen()) {
            c64.getCartridge().freeze();
        }
    }

    @Override
    public void oscilloscope(boolean enable, int width, int height) {
        LOG.fine(format("oscilloscope enable: %b, width: %d, height: %d", enable, width, height));

        soundSetupRequested = enable;
        if (isOpen()) {
            if (!enable && oscilloscope == null) {
                return;
            }
            if (oscilloscope == null) {
                oscilloscope = new Oscilloscope(importedApi, c64, sidBuilder, width);
            }
            if (enable) {
                oscilloscope.start();
            } else {
                oscilloscope.stop();
            }
        }
    }

    @Override
    public void oplOscilloscope(int detailMask) {
        LOG.fine(format("oplOscilloscope detailMask: %d", detailMask));

        if (oscilloscope != null) {
            oscilloscope.setDetailMask(detailMask);
        }
    }

    @Override
    public void flushOscilloscope() {
        if (oscilloscope != null) {
            oscilloscope.flush();
        }
    }

    @Override
    public void forceCheckSongLength(boolean forceCheckSongLength) {
        LOG.fine(format("forceCheckSongLength: %b", forceCheckSongLength));

        this.forceCheckSongLength = forceCheckSongLength;

        if (isOpen()) {
            timer.setForceCheckSongLength(forceCheckSongLength);
        }
    }

    @Override
    public void sidListenerEnable(boolean sidListenerEnable) {
        LOG.fine(format("sidListenerEnable: %b", sidListenerEnable));

        if (isOpen()) {
            c64.setSIDListener(emulationSection.getEngine() != EMULATION || sidListenerEnable ? audioDriver : null);
        }
    }

    @Override
    public void autoDiskChange(byte[] diskContents, String diskContentsName, long ticks) {
        LOG.fine(format("autoDiskChange: %s (%d) in %d", diskContentsName, diskContents.length, ticks));

        if (isOpen()) {
            context.schedule(Event.of("Auto swap-disk", event -> insertDisk(diskContents, diskContentsName)), ticks);
        }
    }

    @Override
    public void autoKeyType(KeyEventType keyEventType, KeyTableEntry key, long ticks) {
        LOG.fine(format("autoKeyType: %s %s in %d", keyEventType, key, ticks));

        if (isOpen()) {
            context.schedule(Event.of("Auto key-type", event -> {
                switch (keyEventType) {
                    case KEY_TYPED:
                        if (key == KeyTableEntry.RESTORE) {
                            c64.getKeyboard().restore();
                        } else {
                            c64.getKeyboard().keyPressed(key);

                            context.schedule(
                                    Event.of("Wait Until Virtual Keyboard Released", (e) -> c64.getKeyboard().keyReleased(key)),
                                    (long) c64.getCyclesPerFrame() << 2);
                        }
                        break;
                    case KEY_PRESSED:
                        if (key == KeyTableEntry.RESTORE) {
                            c64.getKeyboard().restore();
                        } else {
                            c64.getKeyboard().keyPressed(key);
                        }
                        break;
                    case KEY_RELEASED:
                        c64.getKeyboard().keyReleased(key);
                        break;
                }
            }), ticks);
        }
    }

    //
    // Private methods
    //

    private void doLog(ISidPlay2Section sidplay2Section, IAudioSection audioSection, IEmulationSection emulationSection,
                       IC1541Section c1541Section) {
        LOG.fine("defaultPlayLength: " + sidplay2Section.getDefaultPlayLength());
        LOG.fine("loop: " + sidplay2Section.isLoop());
        LOG.fine("single: " + sidplay2Section.isSingle());
        LOG.fine("palEmulation: " + sidplay2Section.isPalEmulation());
        LOG.fine("fadeInTime: " + sidplay2Section.getFadeInTime());
        LOG.fine("fadeOutTime: " + sidplay2Section.getFadeOutTime());

        LOG.fine("samplingRate: " + audioSection.getSamplingRate());
        LOG.fine("sampling: " + audioSection.getSampling());
        LOG.fine("bufferSize: " + audioSection.getBufferSize());
        LOG.fine("audioBufferSize: " + audioSection.getAudioBufferSize());
        LOG.fine("reverbBypass: " + audioSection.getReverbBypass());

        LOG.fine("engine: " + emulationSection.getEngine());
        LOG.fine("detectPSID64ChipModel: " + emulationSection.isDetectPSID64ChipModel());

        LOG.fine("isJiffyDosInstalled: " + c1541Section.isJiffyDosInstalled());
    }

    private void doLog(IEmulationSection emulationSection, SidTune tune) {
        doLogFilterNames(emulationSection, tune);
        doLogCPUClock(emulationSection, tune);
        doLogEmulation(emulationSection, tune);
        doLogChipModel(emulationSection, tune);
    }

    private void doLogFilterNames(final IEmulationSection emulationSection, SidTune tune) {
        for (int sidNum = 0; sidNum < MAX_SIDS && isSIDUsed(emulationSection, tune, sidNum); sidNum++) {
            Engine engine = getEngine(emulationSection, tune);
            Emulation emulation = getEmulation(emulationSection, sidNum);
            ChipModel chipModel = getChipModel(emulationSection, tune, sidNum);
            String filterName = emulationSection.getFilterName(sidNum, engine, emulation, chipModel);

            LOG.fine(getFilterName(sidNum, filterName));
        }
    }

    private void doLogCPUClock(final IEmulationSection emulationSection, SidTune tune) {
        CPUClock cpuClock = CPUClock.getCPUClock(emulationSection, tune);

        LOG.fine("cpuClock: " + cpuClock);
    }

    private void doLogEmulation(IEmulationSection emulationSection, SidTune tune) {
        StringBuilder result = new StringBuilder();
        for (int sidNum = 0; sidNum < MAX_SIDS && isSIDUsed(emulationSection, tune, sidNum); sidNum++) {
            Emulation emulation = getEmulation(emulationSection, sidNum);
            if (sidNum > 0) {
                result.append("+");
            }
            result.append(emulation);
        }
        LOG.fine("Emulation: " + result);
    }

    private void doLogChipModel(IEmulationSection emulationSection, SidTune tune) {
        StringBuilder result = new StringBuilder();
        for (int sidNum = 0; sidNum < MAX_SIDS && isSIDUsed(emulationSection, tune, sidNum); sidNum++) {
            ChipModel chipModel = getChipModel(emulationSection, tune, sidNum);
            int sidBase = getSIDAddress(emulationSection, tune, sidNum);
            if (sidNum > 0) {
                result.append("+");
            }
            determineChipModel(result, chipModel, sidBase);
        }
        LOG.fine("ChipModel: " + result);
    }

    private String getFilterName(int sidNum, String filterName) {
        return switch (sidNum) {
            default -> "Filter: " + filterName;
            case 1 -> "Stereo Filter: " + filterName;
            case 2 -> "3-SID Filter: " + filterName;
        };
    }

    private void determineChipModel(StringBuilder result, ChipModel chipModel, int sidBase) {
        if (sidBase != SIDChip.DEF_BASE_ADDRESS) {
            result.append(format("%s(at 0x%04x)", chipModel, sidBase));
        } else {
            result.append(chipModel);
        }
    }

    private boolean isOpen() {
        return c64 != null;
    }

    private void insertCart(byte[] cartContents, String cartContentsName) {
        try {
            File cartFile = createReadOnlyFile(cartContents, cartContentsName);
            CartridgeType type = cartContentsName.toLowerCase(Locale.ROOT).endsWith(".reu")
                    ? CartridgeType.REU : CartridgeType.CRT;
            c64.setCartridge(type, cartFile);
            LOG.fine("Cartridge: media attached: " + cartContentsName);
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot insert media file '%s'.", cartContentsName));
        }
    }

    private void insertCart(CartridgeType cartType, int size) {
        try {
            c64.setCartridge(cartType, size);
            LOG.fine("Cartridge: media attached: " + cartType.name());
        } catch (IOException e) {
            LOG.severe(e.getMessage());
            LOG.severe(format("Cannot insert media type '%s' sizeKb=%d", cartType.name(), size));
        }
    }

    private void updateSIDChipConfiguration() {
        c64.insertSIDChips((sidNum, sidEmu) -> {
            if (isSIDUsed(emulationSection, tune, sidNum)) {
                return sidBuilder.lock(sidEmu, sidNum, tune);
            } else if (sidEmu != NONE) {
                sidBuilder.unlock(sidEmu);
            }
            return NONE;
        }, sidNum -> getSIDAddress(emulationSection, tune, sidNum));
    }

    private File createReadOnlyFile(byte[] fileContents, String fileContentsUrl)
            throws IOException {
        StringBuilder filenamePrefix = new StringBuilder(getFilenameWithoutSuffix(fileContentsUrl));
        while (filenamePrefix.length() < 3) {
            filenamePrefix.append(" ");
        }
        File tmp = File.createTempFile(filenamePrefix.toString(), getFilenameSuffix(fileContentsUrl));
        try (OutputStream os = new FileOutputStream(tmp)) {
            os.write(fileContents);
        }
        ioWrap(() -> tmp.setWritable(false));
        return tmp;
    }

    private List<Map<?, ?>> createTuneInfo() {
        List<Map<?, ?>> result = new ArrayList<>();
        if (hvscEntry != null) {
            result.add(of(
                    "Name", HVSC_ENTRY + ".name",
                    "Value", getText(hvscEntry.getName())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".title",
                    "Value", getText(hvscEntry.getTitle())));
            if (hvscEntry.getAuthor() != null && !hvscEntry.getAuthor().isEmpty()) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".author",
                        "Value", getText(hvscEntry.getAuthor())));
            }
            if (hvscEntry.getReleased() != null && !hvscEntry.getReleased().isEmpty()) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".released",
                        "Value", getText(hvscEntry.getReleased())));
            }
            result.add(of(
                    "Name", HVSC_ENTRY + ".audio",
                    "Value", getText(hvscEntry.getAudio())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".format",
                    "Value", getText(hvscEntry.getFormat())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".compatibility",
                    "Value", getText(hvscEntry.getCompatibility())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".speed",
                    "Value", getText(hvscEntry.getSpeed())));
            if (hvscEntry.getPlayerId() != null && !hvscEntry.getPlayerId().isEmpty()) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".playerId",
                        "Value", getText(hvscEntry.getPlayerId())));
            }
            if (hvscEntry.getNoOfSongs() != 1) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".noOfSongs",
                        "Value", getText(hvscEntry.getNoOfSongs())));
                result.add(of(
                        "Name", HVSC_ENTRY + ".startSong",
                        "Value", getText(hvscEntry.getStartSong())));
            }
            if (hvscEntry.getTuneLength() != 0.) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".tuneLength",
                        "Value", getText(hvscEntry.getTuneLength())));
            }
            result.add(of(
                    "Name", HVSC_ENTRY + ".clockFreq",
                    "Value", getText(hvscEntry.getClockFreq())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".sidModel1",
                    "Value", getText(hvscEntry.getSidModel1())));
            if (hvscEntry.getSidModel2() != Model.UNKNOWN) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".sidModel2",
                        "Value", getText(hvscEntry.getSidModel2())));
            }
            if (hvscEntry.getSidModel3() != Model.UNKNOWN) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".sidModel3",
                        "Value", getText(hvscEntry.getSidModel3())));
            }
            result.add(of(
                    "Name", HVSC_ENTRY + ".sidChipBase1",
                    "Value", getText(hvscEntry.getSidChipBase1())));
            if (hvscEntry.getSidChipBase2() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".sidChipBase2",
                        "Value", getText(hvscEntry.getSidChipBase2())));
            }
            if (hvscEntry.getSidChipBase3() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".sidChipBase3",
                        "Value", getText(hvscEntry.getSidChipBase3())));
            }
            if (hvscEntry.getDriverAddress() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".driverAddress",
                        "Value", getText(hvscEntry.getDriverAddress())));
            }
            result.add(of(
                    "Name", HVSC_ENTRY + ".loadAddress",
                    "Value", getText(hvscEntry.getLoadAddress())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".loadLength",
                    "Value", getText(hvscEntry.getLoadLength())));
            if (hvscEntry.getInitAddress() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".initAddress",
                        "Value", getText(hvscEntry.getInitAddress())));
            }
            if (hvscEntry.getPlayerAddress() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".playerAddress",
                        "Value", getText(hvscEntry.getPlayerAddress())));
            }
            if (hvscEntry.getFileDate() != null) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".fileDate",
                        "Value", getText(hvscEntry.getFileDate())));
            }
            result.add(of(
                    "Name", HVSC_ENTRY + ".fileSizeKb",
                    "Value", getText(hvscEntry.getFileSizeKb())));
            result.add(of(
                    "Name", HVSC_ENTRY + ".tuneSizeB",
                    "Value", getText(hvscEntry.getTuneSizeB())));
            if (hvscEntry.getRelocStartPage() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".relocStartPage",
                        "Value", getText(hvscEntry.getRelocStartPage())));
            }
            if (hvscEntry.getRelocNoPages() != 0) {
                result.add(of(
                        "Name", HVSC_ENTRY + ".relocNoPages",
                        "Value", getText(hvscEntry.getRelocNoPages())));
            }
            SidTuneInfoDetails details = new SidTuneInfoDetails(tune,
                    sidplay2Section.isEnableDatabase() ? databaseSongLength : 0,
                    sidplay2Section.getDefaultPlayLength(), Function.identity());
            details.getValues().forEach((name, value) -> result.add(of("Name", name, "Value", value)));
        }
        return result;
    }

    private List<Map<String, Object>> createPlayerInfo() {
        List<Map<String, Object>> result = new ArrayList<>();

        if (playerIds != null) {
            for (final String playerId : playerIds) {
                PlayerInfoSection playerIdInfo = tune.getPlayerInfo(playerId, SID_ID_INFO_CFG_BIN);
                if (playerIdInfo != null) {
                    List<Map<String, String>> playerIdMap = new ArrayList<>();
                    result.add(of(
                            "Id", playerId,
                            "Properties", playerIdMap));

                    if (playerIdInfo.getName() != null) {
                        playerIdMap.add(of(
                                "Name", "NAME",
                                "Value", playerIdInfo.getName()));
                    }
                    if (playerIdInfo.getAuthor() != null) {
                        playerIdMap.add(of(
                                "Name", "AUTHOR",
                                "Value", playerIdInfo.getAuthor()));
                    }
                    if (playerIdInfo.getReleased() != null) {
                        playerIdMap.add(of(
                                "Name", "RELEASED",
                                "Value", playerIdInfo.getReleased()));
                    }
                    if (playerIdInfo.getReference() != null) {
                        playerIdMap.add(of(
                                "Name", "REFERENCE",
                                "Value", playerIdInfo.getReference()));
                    }
                    if (playerIdInfo.getComment() != null) {
                        playerIdMap.add(of(
                                "Name", "COMMENT",
                                "Value", playerIdInfo.getComment()));
                    }
                }
            }
        }
        return result;
    }

    private List<Map<?, ?>> createActiveSettings() {
        List<Map<?, ?>> result = new ArrayList<>();

        Engine[] engines = new Engine[MAX_SIDS];
        Emulation[] emulations = new Emulation[MAX_SIDS];
        ChipModel[] chipModels = new ChipModel[MAX_SIDS];
        Integer[] sidBases = new Integer[MAX_SIDS];
        String[] filterNames = new String[MAX_SIDS];
        int sidNum = 0;
        for (; sidNum < MAX_SIDS && isSIDUsed(emulationSection, tune, sidNum); sidNum++) {
            engines[sidNum] = getEngine(emulationSection, tune);
            emulations[sidNum] = getEmulation(emulationSection, sidNum);
            chipModels[sidNum] = getChipModel(emulationSection, tune, sidNum);
            sidBases[sidNum] = getSIDAddress(emulationSection, tune, sidNum);
            filterNames[sidNum] = emulationSection.getFilterName(sidNum,
                    engines[sidNum], emulations[sidNum], chipModels[sidNum]);
        }
        result.add(of(
                "Name", "C64_MODEL",
                "Value", hardwareEnsemble.getC64().getModel().name()));
        result.add(of(
                "Name", "FLOPPY_TYPE",
                "Value", hardwareEnsemble.getFloppyType().name()));
        result.add(of(
                "Name", "VIC_MODEL",
                "Value", hardwareEnsemble.getC64().getConfiguredVicModel().name()));
        result.add(of(
                "Name", "CPU_CLOCK",
                "Value", hardwareEnsemble.getC64().getClock().name()));
        result.add(of(
                "Name", "CYCLES_PER_FRAME",
                "Value", hardwareEnsemble.getC64().getCyclesPerFrame()));
        result.add(of(
                "Name", "SCREEN_REFRESH",
                "Value", hardwareEnsemble.getC64().getScreenRefresh()));
        result.add(of(
                "Name", "PAL_EMULATION_MODE",
                "Value", (c64.getVIC().getPalEmulation() instanceof VicePALEmulationTeaVM
                        ? PalEmulationMode.VICE : PalEmulationMode.JSIDPLAY2).name()));
        result.add(of(
                "Name", "ENGINES",
                "Value", stream(engines, 0, sidNum)
                        .map(Enum::name).collect(joining(","))));
        result.add(of(
                "Name", "EMULATIONS",
                "Value", stream(emulations, 0, sidNum)
                        .map(Enum::name).collect(joining(","))));
        result.add(of(
                "Name", "CHIP_MODELS",
                "Value", stream(chipModels, 0, sidNum)
                        .map(Enum::name).collect(joining(","))));
        result.add(of(
                "Name", "SID_BASES",
                "Value", stream(sidBases, 0, sidNum)
                        .map(Object::toString).collect(joining(","))));
        result.add(of(
                "Name", "FILTER_NAMES",
                "Value", stream(filterNames, 0, sidNum)
                        .collect(joining(","))));
        if (soundSetupRequested) {
            List<Map<String, Object>> setups = new ArrayList<>();
            c64.configureSIDs((chip, sid) -> {
                if (sid instanceof ReSIDBase software && sidBuilder.getSoundSetup(chip) != null) {
                    Map<String, Object> setup = sidBuilder.getSoundSetup(chip)
                            .toMap(libsidutils.sound.SoundSetup.playbackFlags(software));
                    libsidutils.sound.OutputSettings output = chip < 3 ? sidBuilder.getOutputSettings(chip) : null;
                    if (output != null) {
                        setup.put("output", output.toMap());
                    }
                    setups.add(setup);
                }
            });
            result.add(of("Name", "SOUND_SETUPS", "Value", setups));
            result.add(of("Name", "OUTPUT_EFFECTS", "Value", sidBuilder.getOutputEffects().toMap()));
        }
        return result;
    }


}