NetSIDClient.java

package builder.netsiddev;

import builder.netsiddev.commands.*;
import libsidplay.common.*;
import libsidplay.config.IEmulationSection;
import server.netsiddev.Command;
import server.netsiddev.Response;

import java.io.EOFException;
import java.io.IOException;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.List;

import static libsidplay.config.ISidPlay2SystemProperties.MAX_SIDS;
import static server.netsiddev.NetworkSIDProtocol.*;
import static server.netsiddev.Response.BUSY;

public class NetSIDClient {
    /**
     * Approximate C64 cycles per millisecond, used only to pace BUSY retries.
     */
    private static final int CYCLES_TO_MILLIS = 1000;
    /**
     * Flush a batch after about four milliseconds of emulated C64 time.
     */
    private static final int MAX_WRITE_CYCLES = 4096;
    /**
     * Bound the number of locally queued commands, including untimed controls.
     */
    private static final int MAX_BUFFER_SIZE = 4096;
    /**
     * Keep write payloads near 1 KiB even when all event delays are zero.
     */
    private static final int MAX_WRITE_BYTES = 1024 - HEADER_SIZE;
    /**
     * Send idle-time progress four times per maximum-duration write batch.
     */
    private static final int REGULAR_DELAY = MAX_WRITE_CYCLES >> 2;
    /**
     * Retry slightly before an estimated batch drain to avoid adding latency.
     */
    private static final int BUSY_RETRY_MARGIN_MILLIS = 3;
    /**
     * Minimum retry wait, including for commands without cycle information.
     */
    private static final int MIN_BUSY_RETRY_MILLIS = 1;
    /**
     * Largest right-shift factor whose corresponding int speed remains positive.
     */
    private static final int MAX_FAST_FORWARD_FACTOR = Integer.SIZE - 2;

    private final NetSIDDevConnection connection = NetSIDDevConnection.getInstance();

    private static int version = LEGACY_VERSION;
    private final EventScheduler context;
    private final List<NetSIDPkg> commands = new ArrayList<>(MAX_BUFFER_SIZE);
    private TryWriteBase tryWrite;
    private int readResult;
    private String configName;
    private long lastSIDWriteTime;
    private int fastForwardFactor;
    private int sidCount;
    private int legacyConfiguration;

    private final Event event;

    /**
     * Establish a connection and discover the server's available configurations.
     */
    public NetSIDClient(EventScheduler context, IEmulationSection emulationSection) {
        this.context = context;
        this.event = Event.of("JSIDDevice Delay",
                event -> context.schedule(event, eventuallyDelay(), Event.Phase.PHI2));
        boolean wasNotConnectedYet = connection.isDisconnected();
        try {
            connection.open(emulationSection.getNetSIDDevHost(), emulationSection.getNetSIDDevPort());
            if (TrySetSidModel.getFilterToSidModel().isEmpty() || wasNotConnectedYet) {
                version = sendReceive(new GetVersion());
                if (version < LEGACY_VERSION) {
                    throw new IOException("Unsupported Network SID protocol version: " + version);
                }
                TrySetSidModel.getFilterToSidModel().clear();
                if (version == LEGACY_VERSION) {
                    TrySetSidModel.getFilterToSidModel().put(
                            new SimpleImmutableEntry<>(ChipModel.MOS6581, "FilterDefault6581"), (byte) 0);
                    TrySetSidModel.getFilterToSidModel().put(
                            new SimpleImmutableEntry<>(ChipModel.MOS8580, "FilterDefault8580"), (byte) 1);
                } else {
                    int configurations = sendReceive(new GetConfigCount());
                    if (configurations == 0) {
                        throw new IOException("Network SID device has no SID configurations");
                    }
                    for (int configuration = 0; configuration < configurations; configuration++) {
                        SimpleImmutableEntry<ChipModel, String> filter = sendReceiveConfig(
                                new GetConfigInfo((byte) configuration));
                        TrySetSidModel.getFilterToSidModel().put(filter, (byte) configuration);
                    }
                }
            }
        } catch (IOException | RuntimeException e) {
            connection.close();
            throw new RuntimeException("Cannot initialize Network SID device: " + e.getMessage(), e);
        }
    }

    public int getVersion() {
        return version;
    }

    public int getSidCount() {
        return Math.max(1, sidCount);
    }

    public void configureSids(int count) {
        int maximum = Math.min(MAX_SIDS, sidCapacity(version));
        if (count < 1 || count > maximum) {
            throw new IllegalArgumentException("Network SID protocol version " + version
                    + " supports at most " + maximum + " SID chips; requested " + count);
        }
        if (count != sidCount) {
            if (version >= CONFIGURATION_VERSION) {
                addAndSend(new TrySetSidCount((byte) count));
                // Older servers leave new slots uninitialized until a model is assigned.
                for (int sid = 0; sid < count; sid++) {
                    add(new TrySetSidModel((byte) sid, (byte) 0));
                }
                softFlush();
            }
            sidCount = count;
        }
    }

    /**
     * Protocol version 1 carries model, sampling and clock flags in header byte 1. Flush earlier packets before
     * changing those flags. Version 2 and later use separate configuration commands and leave this compatibility path
     * unused.
     */
    void configureProtocolV1(ChipModel model, SamplingMethod sampling, CPUClock clock) {
        if (version == LEGACY_VERSION) {
            softFlush();
            legacyConfiguration = (model == ChipModel.MOS8580 ? LEGACY_MODEL_8580 : 0)
                    | (clock == CPUClock.NTSC ? LEGACY_CLOCK_NTSC : 0)
                    | (sampling == SamplingMethod.DECIMATE ? LEGACY_SAMPLING_DECIMATE : 0);
        }
    }

    /**
     * Update the shared clock using the command or header bits supported by the server.
     */
    void setClockFrequency(double cpuFrequency) {
        if (version == LEGACY_VERSION) {
            softFlush();
            legacyConfiguration = legacyConfiguration & ~LEGACY_CLOCK_NTSC
                    | (cpuFrequency == CPUClock.PAL.getCpuFrequency() ? 0 : LEGACY_CLOCK_NTSC);
        } else {
            addAndSend(new SetClocking(cpuFrequency));
        }
    }

    public void init(byte volume) {
        clocksSinceLastAccess();
        commands.clear();
        tryWrite = null;
        add(new Flush());
        add(new TryReset(volume));
    }

    public byte read(byte sidNum, byte addr) {
        int chip = validateSid(sidNum);
        int cycles = splitDelay(clocksSinceLastAccess() >> fastForwardFactor);
        return (byte) tryRead(sidNum, cycles, chip << SID_REGISTER_BITS | addr & SID_REGISTER_MASK);
    }

    public void write(byte sidNum, byte addr, byte data) {
        int chip = validateSid(sidNum);
        int cycles = splitDelay(clocksSinceLastAccess() >> fastForwardFactor);
        write(cycles, chip << SID_REGISTER_BITS | addr & SID_REGISTER_MASK, data);
    }

    public void write(int addr, byte data) {
        if (getVersion() < EXTENDED_ADDRESS_VERSION) {
            return;
        }
        if (!isFmAddress(addr)) {
            throw new IllegalArgumentException("FM address must be in 0xdf00..0xdfff: " + addr);
        }
        int cycles = splitDelay(clocksSinceLastAccess() >> fastForwardFactor);
        write(cycles, addr, data);
    }

    private int validateSid(byte sid) {
        int chip = sid & 0xff;
        int maximum = sidCapacity(version);
        if (chip >= maximum || chip >= getSidCount()) {
            throw new IllegalArgumentException("Unconfigured or unsupported SID index: " + chip);
        }
        return chip;
    }

    private void write(int cycles, int address, byte data) {
        if (commands.isEmpty() || commands.getLast() != tryWrite) {
            tryWrite = createTryWrite();
            commands.add(tryWrite);
        }
        tryWrite.addWrite(cycles, address, data);
        int writeSize = version >= EXTENDED_ADDRESS_VERSION ? EXTENDED_WRITE_SIZE : LEGACY_WRITE_SIZE;
        if (commands.size() >= MAX_BUFFER_SIZE || tryWrite.getCyclesSendToServer() >= MAX_WRITE_CYCLES
                || tryWrite.getWriteCount() * writeSize >= MAX_WRITE_BYTES) {
            softFlush();
        }
    }

    private int splitDelay(long cycles) {
        while (cycles > MAX_CYCLE_DELAY) {
            addAndSend(new TryDelay((byte) 0, MAX_CYCLE_DELAY));
            cycles -= MAX_CYCLE_DELAY;
        }
        return (int) cycles;
    }

    private SimpleImmutableEntry<ChipModel, String> sendReceiveConfig(NetSIDPkg cmd) {
        addAndSend(cmd);
        return new SimpleImmutableEntry<>(readResult == 1 ? ChipModel.MOS8580 : ChipModel.MOS6581,
                "Filter" + configName);
    }

    private int sendReceive(NetSIDPkg cmd) {
        addAndSend(cmd);
        return readResult;
    }

    final void addAndSend(NetSIDPkg cmd) {
        softFlush();
        add(cmd);
        softFlush();
    }

    final void add(NetSIDPkg cmd) {
        commands.add(cmd);
    }

    void softFlush() {
        try {
            flush();
        } catch (IOException e) {
            connection.close();
            throw new RuntimeException(e.getMessage(), e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            connection.close();
            throw new RuntimeException(e);
        }
    }

    private int tryRead(byte sidNum, int cycles, int address) {
        if (!commands.isEmpty() && commands.getLast() == tryWrite) {
            commands.removeLast();
            tryWrite = version >= EXTENDED_ADDRESS_VERSION ? new TryReadExt((TryWriteExt) tryWrite, cycles, address)
                    : new TryRead((TryWrite) tryWrite, sidNum, cycles, (byte) address);
        } else {
            tryWrite = version >= EXTENDED_ADDRESS_VERSION ? new TryReadExt(cycles, address)
                    : new TryRead(sidNum, cycles, (byte) address);
        }
        return sendReceive(tryWrite);
    }

    private void flush() throws IOException, InterruptedException {
        while (!commands.isEmpty()) {
            NetSIDPkg command = commands.getFirst();
            byte[] packet = command.toByteArrayWithLength();
            Command commandType = Command.values()[packet[0] & 0xff];
            if (!commandType.isSupportedBy(version)) {
                throw new IOException("Command " + commandType + " is unsupported by protocol version " + version);
            }
            if (version == LEGACY_VERSION && commandType != Command.GET_VERSION) {
                packet[1] = (byte) legacyConfiguration;
            }
            connection.send(packet);
            int responseCode = readResponse();
            if (responseCode >= Response.values().length) {
                throw new IOException("Unknown Network SID response: " + responseCode);
            }
            Response response = Response.values()[responseCode];
            if (response == BUSY) {
                int cycles = command instanceof TryWriteBase writes ? writes.getCyclesSendToServer() : 0;
                Thread.sleep(Math.max(MIN_BUSY_RETRY_MILLIS,
                        cycles / CYCLES_TO_MILLIS - BUSY_RETRY_MARGIN_MILLIS));
                continue;
            }
            if (response == Response.ERR) {
                throw new IOException("Network SID device rejected command " + commandType);
            }
            Response expected = commandType.getResponse();
            if (response != expected) {
                throw new IOException("Unexpected Network SID response " + responseCode + " for command " + commandType);
            }
            if (response.hasByteValue()) {
                readResult = readResponse();
            } else if (response == Response.INFO) {
                readResult = readResponse();
                if (readResult > 1) {
                    throw new IOException("Unknown SID model in INFO response: " + readResult);
                }
                configName = connection.receiveString();
            }
            commands.removeFirst();
        }
    }

    private int readResponse() throws IOException {
        int result = connection.receive();
        if (result == -1) {
            throw new EOFException("Network SID device closed the connection");
        }
        return result;
    }

    private TryWriteBase createTryWrite() {
        return getVersion() >= EXTENDED_ADDRESS_VERSION ? new TryWriteExt() : new TryWrite();
    }

    private long clocksSinceLastAccess() {
        long now = context.getTime(Event.Phase.PHI2);
        long difference = Math.max(0, now - lastSIDWriteTime);
        lastSIDWriteTime = now;
        return difference;
    }

    private long eventuallyDelay() {
        long difference = context.getTime(Event.Phase.PHI2) - lastSIDWriteTime;
        if (difference >= REGULAR_DELAY) {
            lastSIDWriteTime += REGULAR_DELAY;
            int cycles = REGULAR_DELAY >> fastForwardFactor;
            if (cycles > 0) {
                addAndSend(new TryDelay((byte) 0, cycles));
            }
        }
        return REGULAR_DELAY;
    }

    public void start() {
        context.schedule(event, 0, Event.Phase.PHI2);
    }

    public void fastForward() {
        fastForwardFactor = Math.min(fastForwardFactor + 1, MAX_FAST_FORWARD_FACTOR);
    }

    public void normalSpeed() {
        fastForwardFactor = 0;
    }

    public boolean isFastForward() {
        return fastForwardFactor != 0;
    }

    public int getFastForwardFactor() {
        return fastForwardFactor;
    }

    public int getFastForwardBitMask() {
        return (1 << fastForwardFactor) - 1;
    }
}