NetSIDDev.java

package builder.netsiddev;

import builder.netsiddev.commands.Mute;
import builder.netsiddev.commands.TrySetSidModel;
import libsidplay.common.ChipModel;
import libsidplay.common.Emulation;
import libsidplay.common.Engine;
import libsidplay.common.SIDEmu;
import libsidplay.config.IConfig;
import libsidplay.config.IEmulationSection;

import java.util.List;

import static libsidplay.common.SIDChip.REG_COUNT;
import static server.netsiddev.NetworkSIDProtocol.*;

public class NetSIDDev extends SIDEmu {

    /**
     * SID RES/FILT register, containing resonance and voice/external-input filter routing.
     */
    private static final int FILTER_ROUTING_REGISTER = 0x17;
    /**
     * Low four RES/FILT bits route voices and external input through the filter. Clearing them bypasses filtering
     * using ordinary protocol writes while preserving the resonance setting.
     */
    private static final int FILTER_ROUTING_MASK = 0x0f;

    /**
     * FakeStereo mode uses two chips using the same base address. Write commands are routed to both SIDs, while read
     * command can be configured to be processed by a specific SID chip.
     *
     * @author ken
     *
     */
    public static class FakeStereo extends NetSIDDev {
        private final IEmulationSection emulationSection;
        private final int prevNum;
        /**
         * First slot sharing this mirror's C64 base address; never cross into another group.
         */
        private final int firstSidNum;
        private final List<NetSIDDev> sids;

        public FakeStereo(NetSIDClient connection, final int sidNum, final ChipModel model, final IConfig config,
                          final List<NetSIDDev> sids) {
            super(connection, sidNum, model);
            this.emulationSection = config.getEmulationSection();
            this.prevNum = sidNum - 1;
            this.sids = sids;
            NetSIDDev previous = prevNum < sids.size() ? sids.get(prevNum) : null;
            this.firstSidNum = previous instanceof FakeStereo mirror ? mirror.firstSidNum : prevNum;
        }

        /**
         * Standalone unlock can leave holes in a mirror group or trim its tail. Find its nearest surviving predecessor
         * using stable protocol indices.
         */
        private NetSIDDev previousSid() {
            for (int sidNum = Math.min(prevNum, sids.size() - 1); sidNum >= firstSidNum; sidNum--) {
                NetSIDDev previous = sids.get(sidNum);
                if (previous != null) {
                    return previous;
                }
            }
            return null;
        }

        @Override
        public byte read(int addr) {
            NetSIDDev previous = previousSid();
            if (previous != null && (!isActive() || emulationSection.getSidToRead().getSidNum() <= prevNum)) {
                return previous.read(addr);
            }
            return super.read(addr);
        }

        @Override
        public byte readInternalRegister(int addr) {
            NetSIDDev previous = previousSid();
            if (previous != null && (!isActive() || emulationSection.getSidToRead().getSidNum() <= prevNum)) {
                return previous.readInternalRegister(addr);
            }
            return super.readInternalRegister(addr);
        }

        /**
         * Order of writes is important, since SID read flushes the writing queue! (Polly_Rock.sid)
         *
         * @see builder.netsiddev.NetSIDDev#write(int, byte)
         */
        @Override
        public void write(int addr, byte data) {
            NetSIDDev previous = previousSid();
            if (emulationSection.getSidToRead().getSidNum() <= prevNum) {
                if (previous != null) {
                    previous.write(addr, data);
                }
                super.write(addr, data);
            } else {
                super.write(addr, data);
                if (previous != null) {
                    previous.write(addr, data);
                }
            }
        }
    }

    private final byte sidNum;
    private final NetSIDClient client;
    private final ChipModel chipModel;
    private boolean active = true;
    private boolean filterEnabled = true;

    public NetSIDDev(NetSIDClient connection, final int sidNum, final ChipModel model) {
        this.client = connection;
        this.sidNum = (byte) sidNum;
        this.chipModel = model;
    }

    @Override
    public void reset(byte volume) {
        // nothing to do
    }

    @Override
    public byte read(int addr) {
        return active ? client.read(sidNum, (byte) addr) : (byte) 0xff;
    }

    @Override
    public void write(int addr, final byte data) {
        writeRegister(addr, data);
    }

    private void writeRegister(int addr, byte data) {
        if (active) {
            // Keep the tune's unmodified value for feedback, restoration and later re-enabling. Each fake-stereo
            // chip applies its own filter setting only to the physical network write.
            super.write(addr, data);
            if (addr == FILTER_ROUTING_REGISTER && !filterEnabled) {
                data &= ~FILTER_ROUTING_MASK;
            }
            client.write(sidNum, (byte) addr, data);
        }
    }

    /**
     * Replay cached register programming after the remote chip was reset or recreated by a count/model change. This
     * retains frequency, waveform, ADSR, filter and volume settings, but cannot recover oscillator phase or the running
     * envelope state.
     * <p>
     * Read and write this physical chip's own cache: fake-stereo overrides may select another chip on reads and mirror
     * writes into already restored chips. The source can be this same object when only the remote chip was recreated.
     */
    final void restoreRegisters(SIDEmu previous) {
        for (int addr = 0; addr < REG_COUNT; addr++) {
            byte value = previous instanceof NetSIDDev sid ? sid.readOwnRegister(addr)
                    : previous.readInternalRegister(addr);
            writeRegister(addr, value);
        }
    }

    private byte readOwnRegister(int addr) {
        return super.readInternalRegister(addr);
    }

    final boolean isActive() {
        return active;
    }

    final ChipModel getChipModel() {
        return chipModel;
    }

    /**
     * Retire this physical slot while retaining its cache for a later relock. A retired fake-stereo wrapper may still
     * forward to live group members until the C64 bank is remapped, but must never address its removed remote chip.
     */
    final void deactivate() {
        active = false;
    }

    @Override
    public void clock() {
        // nothing to do
    }

    @Override
    public void setChipModel(ChipModel model) {
        // is already configured by setFilter()
    }

    @Override
    public void setClockFrequency(double cpuFrequency) {
        if (active) {
            client.setClockFrequency(cpuFrequency);
        }
    }

    @Override
    public void input(int input) {
        // configured in the JSIDDevice user interface
    }

    @Override
    public void setDigiBoost(boolean digiBoost) {
        // this setting must be changed in the JSIDDevice settings
    }

    @Override
    public void setVoiceMute(int voice, boolean mute) {
        if (active && (client.getVersion() >= DIGI_MUTE_VERSION || voice < DIGI_VOICE)) {
            client.addAndSend(new Mute(sidNum, (byte) voice, mute));
        }
    }

    @Override
    public void setFilter(IConfig config, int sidNum) {
        IEmulationSection emulationSection = config.getEmulationSection();
        String filterName = emulationSection.getFilterName(sidNum, Engine.NETSID, Emulation.DEFAULT, chipModel);
        if (active && client.getVersion() >= CONFIGURATION_VERSION) {
            client.addAndSend(new TrySetSidModel((byte) sidNum, chipModel, filterName));
        }
    }

    /**
     * The shared protocol has no filter-enable command. Bypass routing like the hardware backends and replay this
     * physical chip's original register immediately, without mirroring the toggle or following fake-stereo reads.
     */
    @Override
    public void setFilterEnable(IEmulationSection emulation, int sidNum) {
        boolean enabled = emulation.isFilterEnable(sidNum);
        if (active && filterEnabled != enabled) {
            filterEnabled = enabled;
            writeRegister(FILTER_ROUTING_REGISTER, readOwnRegister(FILTER_ROUTING_REGISTER));
            client.softFlush();
        }
    }

    /**
     * Credits string.
     *
     * @return String of credits.
     */
    public static String credits() {
        String credit = "Network SID Client:\n";
        credit += "\tCopyright (©) 2017 Ken Händel\n";
        credit += "\thttp://sourceforge.net/projects/jsidplay2/\n";
        return credit;
    }

}