ClientContext.java

package server.netsiddev;

import libsidplay.common.CPUClock;
import libsidplay.common.ChipModel;
import libsidplay.common.SIDChip;
import libsidplay.common.SamplingMethod;
import libsidplay.sidtune.PSidHeader;
import libsidutils.fingerprinting.IFingerprintMatcher;
import libsidutils.fingerprinting.rest.beans.MusicInfoWithConfidenceBean;
import server.netsiddev.ini.IniJSIDDeviceAudioSection;
import server.netsiddev.ini.JSIDDeviceConfig;
import sidplay.audio.AudioConfig;
import sidplay.fingerprinting.FingerprintJsonClient;
import sidplay.fingerprinting.WhatsSidSupport;

import javax.sound.sampled.Mixer;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static libsidplay.sidtune.PSidHeader.*;
import static server.netsiddev.NetworkSIDProtocol.*;

/**
 * Container for client-specific data.
 *
 * @author Ken Händel
 * @author Antti Lankila
 * @author Wilfred Bos
 * @see NetworkSIDDevice
 */
class ClientContext {
    /**
     * String encoding
     */
    private static final Charset ISO_8859 = StandardCharsets.ISO_8859_1;

    /**
     * See netsiddev.adoc for version information about the protocol.
     */
    private static final byte SID_NETWORK_PROTOCOL_VERSION = EXTENDED_ADDRESS_VERSION;

    /**
     * Maximum time to wait for the queue in milliseconds.
     */
    private static final long MAX_TIME_TO_WAIT_FOR_QUEUE = 50;

    /** Extra socket read capacity beyond one maximum-size protocol request. */
    private static final int SOCKET_READ_SLACK = 16384;

    // A sound device can block a flush behind a PCM write. Give each waiting client its own worker.
    private static final Executor FLUSH_EXECUTOR = Executors.newCachedThreadPool(
            Thread.ofPlatform().daemon().name("JSIDDevice FLUSH-", 1).factory());

    /**
     * Expected buffer fill rate
     */
    private final int latency;

    /**
     * Cached commands because values() returns a new array each time.
     */
    private final Command[] commands = Command.values();

    /**
     * Our back-end thread
     */
    private final AudioGeneratorThread eventConsumerThread;

    /**
     * Shadow SID clocked with a client to read from
     */
    private SIDChip[] sidRead;

    /**
     * Allocate one maximum-size request plus room for socket read-ahead.
     */
    private final ByteBuffer dataRead = ByteBuffer.allocateDirect(HEADER_SIZE + MAX_PAYLOAD_LENGTH + SOCKET_READ_SLACK);

    /**
     * Largest response: INFO code, model byte, 255 name bytes and NUL terminator.
     */
    private final ByteBuffer dataWrite = ByteBuffer.allocateDirect(2 + MAX_INFO_NAME_LENGTH + 1);

    /**
     * A selectable channel for stream-oriented listening sockets.
     */
    private static ServerSocketChannel ssc = null;

    /**
     * The selector which is registered to the server socket channel.
     */
    private static volatile Selector selector;

    /**
     * Current command.
     */
    private Command command;

    /**
     * Current sid number in command.
     */
    private int sidNumber;

    /**
     * Length of a data packet associated with command.
     */
    private int dataLength;

    /**
     * Current clock value in input.
     */
    private long inputClock;

    private CompletableFuture<Long> pendingFlush;

    private PSidHeader tuneHeader;

    private CPUClock sidClocking = CPUClock.PAL;

    /**
     * Indicates if a new connection should be opened in case of connection settings changes.
     */
    private static volatile boolean openNewConnection = true;

    /**
     * Map which holds all instances of each client connection.
     */
    private static final Map<SocketChannel, ClientContext> clientContextMap = new ConcurrentHashMap<>();

    private MusicInfoWithConfidenceBean whatsSidResult;

    private static int clientContextNumToCheck;

    public static String getRecognizedTunes() {
        return clientContextMap.values().stream().map(ClientContext::toWhatsSidAnswer).collect(Collectors.joining("\n"));
    }

    private static String toWhatsSidAnswer(ClientContext cc) {
        StringBuilder result = new StringBuilder();
        if (cc.whatsSidResult != null) {
            result.append(cc.whatsSidResult);
        }
        cc.whatsSidResult = null;
        return result.toString();
    }

    /**
     * Construct a new audio player for a connected client
     */
    private ClientContext(AudioConfig config, int latency) {
        this(new AudioGeneratorThread(config), latency);
        setDefaultSidConfiguration();
        eventConsumerThread.start();
    }

    ClientContext(AudioGeneratorThread eventConsumerThread, int latency) {
        this.latency = latency;
        dataWrite.position(dataWrite.capacity());
        this.eventConsumerThread = eventConsumerThread;
        dataRead.limit(HEADER_SIZE);
    }

    private void setDefaultSidConfiguration() {
        sidRead = new SIDChip[]{NetworkSIDDevice.getSidConfig(0)};
        sidRead[0].setClockFrequency(sidClocking.getCpuFrequency());
        eventConsumerThread.setSidArray(new SIDChip[]{NetworkSIDDevice.getSidConfig(0)});
    }

    /**
     * Callback to handle protocol after new data has been received.
     */
    private void processReadBuffer() {
        if (dataRead.position() < dataRead.limit()) {
            return;
        }
        if (command == null) {
            int commandByte = dataRead.get(0) & 0xff;
            command = commandByte < commands.length ? commands[commandByte] : null;
            sidNumber = dataRead.get(1) & 0xff;
            dataLength = dataRead.getShort(2) & 0xffff;
            dataRead.limit(HEADER_SIZE + dataLength);
            if (dataRead.position() < dataRead.limit()) {
                return;
            }
        }

        dataWrite.clear();
        try {
            validateCommand();
            processCommand();
        } catch (InvalidCommandException e) {
            dataWrite.clear();
            dataWrite.put((byte) Response.ERR.ordinal());
        }
        dataWrite.flip();
        dataRead.position(HEADER_SIZE + dataLength);
        dataRead.compact();
        command = null;
        dataRead.limit(HEADER_SIZE);
    }

    /** Validate the whole frame before queuing any writes, including writes preceding a read. */
    private void validateCommand() throws InvalidCommandException {
        if (command == null) {
            throw new InvalidCommandException("Unknown command number: " + (dataRead.get(0) & 0xff));
        }
        int expectedLength = switch (command) {
            case FLUSH, TRY_SET_SID_COUNT, GET_VERSION -> 0;
            case MUTE, TRY_DELAY -> 2;
            case TRY_RESET, TRY_SET_SAMPLING, TRY_SET_CLOCKING, SET_SID_POSITION, SET_SID_LEVEL,
                    TRY_SET_SID_MODEL, SET_DELAY, TRY_SET_FM_OPL -> 1;
            case SET_FADE_IN, SET_FADE_OUT -> 4;
            default -> -1;
        };
        if (expectedLength >= 0 && dataLength != expectedLength) {
            throw new InvalidCommandException(command + " needs " + expectedLength + " data bytes", dataLength);
        }
        switch (command) {
            case TRY_SET_SID_COUNT:
                if (sidNumber < 1 || sidNumber > EXTENDED_SID_CAPACITY) {
                    throw new InvalidCommandException("SID count must be between 1 and 16");
                }
                break;
            case MUTE:
                validateSidNumber();
                if ((dataRead.get(HEADER_SIZE) & 0xff) > DIGI_VOICE || (dataRead.get(HEADER_SIZE + 1) & 0xff) > 1) {
                    throw new InvalidCommandException("MUTE needs voice 0..3 and mute flag 0 or 1");
                }
                break;
            case TRY_DELAY:
                if (dataRead.getShort(HEADER_SIZE) == 0) {
                    throw new InvalidCommandException("TRY_DELAY must advance at least one cycle");
                }
                break;
            case TRY_WRITE:
            case TRY_READ:
            case TRY_WRITE_EX:
            case TRY_READ_EX:
                int writeSize = command.getWriteSize();
                int readSize = command.getReadSize();
                if (dataLength < readSize || (dataLength - readSize) % writeSize != 0) {
                    throw new InvalidCommandException("Invalid " + command + " data length", dataLength);
                }
                if (command.isExtended()) {
                    for (int i = 0; i < dataLength - readSize; i += writeSize) {
                        int address = dataRead.getShort(HEADER_SIZE + i + 2) & 0xffff;
                        if (address > MAX_EXTENDED_SID_ADDRESS && !isFmAddress(address)) {
                            throw new InvalidCommandException("Invalid extended write address: " + address);
                        }
                    }
                    if (command.isRead()
                            && (dataRead.getShort(HEADER_SIZE + dataLength - 2) & 0xffff) > MAX_EXTENDED_SID_ADDRESS) {
                        throw new InvalidCommandException("Extended reads require a SID address in 0x0000..0x01ff");
                    }
                }
                break;
            case TRY_SET_SAMPLING:
            case TRY_SET_CLOCKING:
            case TRY_SET_FM_OPL:
                if ((dataRead.get(HEADER_SIZE) & 0xff) > 1) {
                    throw new InvalidCommandException(command + " needs value 0 or 1");
                }
                break;
            case SET_SID_POSITION:
                validateSidNumber();
                if (dataRead.get(HEADER_SIZE) < POSITION_LEFT || dataRead.get(HEADER_SIZE) > POSITION_RIGHT) {
                    throw new InvalidCommandException("Position must be between -100 and 100");
                }
                break;
            case SET_SID_LEVEL:
            case SET_DELAY:
                validateSidNumber();
                break;
            case TRY_SET_SID_MODEL:
                validateSidNumber();
                validateConfiguration(dataRead.get(HEADER_SIZE) & 0xff);
                break;
            case GET_CONFIG_INFO:
                validateConfiguration(sidNumber);
                break;
            default:
                break;
        }
    }

    private void validateSidNumber() throws InvalidCommandException {
        if (sidNumber >= sidRead.length) {
            throw new InvalidCommandException("Unconfigured SID number: " + sidNumber);
        }
    }

    private void validateConfiguration(int configuration) throws InvalidCommandException {
        if (configuration >= (NetworkSIDDevice.getSidCount() & 0xff)) {
            throw new InvalidCommandException("Unknown SID configuration: " + configuration);
        }
    }

    private void processCommand() throws InvalidCommandException {
        long clientTimeDifference = inputClock - eventConsumerThread.getPlaybackClock();
        boolean isBufferFull = clientTimeDifference > latency;
        boolean isBufferHalfFull = clientTimeDifference > latency / 2;
        switch (command) {
            case FLUSH:
                pendingFlush = CompletableFuture.supplyAsync(eventConsumerThread::flush, FLUSH_EXECUTOR);
                break;
            case TRY_SET_SID_COUNT:
                if (!queueReady()) {
                    break;
                }
                SIDChip[] sid = new SIDChip[sidNumber];
                SIDChip[] read = new SIDChip[sidNumber];
                for (int i = 0; i < sidNumber; i++) {
                    sid[i] = NetworkSIDDevice.getSidConfig(0);
                    read[i] = NetworkSIDDevice.getSidConfig(0);
                    read[i].setClockFrequency(CPUClock.PAL.getCpuFrequency());
                }
                sidClocking = CPUClock.PAL;
                sidRead = read;
                eventConsumerThread.setSidArray(sid);
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case MUTE:
                eventConsumerThread.mute(sidNumber, dataRead.get(HEADER_SIZE), dataRead.get(HEADER_SIZE + 1) == 1);
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case TRY_RESET:
                if (!queueReady()) {
                    break;
                }
                byte volume = dataRead.get(HEADER_SIZE);
                tuneHeader = null;
                for (int i = 0; i < sidRead.length; i++) {
                    eventConsumerThread.reset(i, volume);
                    sidRead[i].reset();
                    sidRead[i].write(0x18, volume);
                }
                eventConsumerThread.reopen();
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case TRY_DELAY:
            case TRY_WRITE:
            case TRY_READ:
            case TRY_WRITE_EX:
            case TRY_READ_EX:
                if (isBufferHalfFull) {
                    eventConsumerThread.ensureDraining();
                }
                if (isBufferFull) {
                    dataWrite.put((byte) Response.BUSY.ordinal());
                    break;
                }
                if (command == Command.TRY_DELAY) {
                    handleDelayPacket(dataRead.getShort(HEADER_SIZE) & 0xffff);
                    dataWrite.put((byte) Response.OK.ordinal());
                    break;
                }
                boolean extended = command.isExtended();
                int readSize = command.getReadSize();
                handleWritePacket(dataLength - readSize, command);
                if (!command.isRead()) {
                    dataWrite.put((byte) Response.OK.ordinal());
                } else {
                    int offset = HEADER_SIZE + dataLength - readSize;
                    int cycles = dataRead.getShort(offset) & 0xffff;
                    int register = extended ? dataRead.getShort(offset + Short.BYTES) & 0xffff
                            : dataRead.get(offset + Short.BYTES) & 0xff;
                    handleDelayPacket(cycles);
                    int chip = register >> SID_REGISTER_BITS;
                    dataWrite.put((byte) Response.READ.ordinal());
                    dataWrite.put(chip < sidRead.length ? sidRead[chip].read(register & SID_REGISTER_MASK) : (byte) 0);
                }
                break;
            case TRY_SET_FM_OPL:
                boolean enabled = dataRead.get(HEADER_SIZE) == 1;
                if (eventConsumerThread.isSfxEnabled() != enabled && !queueReady()) {
                    break;
                }
                eventConsumerThread.setSfxEnable(enabled);
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case GET_VERSION:
                dataWrite.put((byte) Response.VERSION.ordinal());
                dataWrite.put(SID_NETWORK_PROTOCOL_VERSION);
                break;
            case TRY_SET_SAMPLING:
                if (!queueReady()) {
                    break;
                }
                eventConsumerThread.setSampling(SamplingMethod.values()[dataRead.get(HEADER_SIZE)]);
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case TRY_SET_CLOCKING:
                if (!queueReady()) {
                    break;
                }
                sidClocking = dataRead.get(HEADER_SIZE) == 0 ? CPUClock.PAL : CPUClock.NTSC;
                eventConsumerThread.setClocking(sidClocking);
                for (SIDChip chip : sidRead) {
                    chip.setClockFrequency(sidClocking.getCpuFrequency());
                }
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case GET_CONFIG_COUNT:
                dataWrite.put((byte) Response.COUNT.ordinal());
                dataWrite.put(NetworkSIDDevice.getSidCount());
                break;
            case GET_CONFIG_INFO:
                dataWrite.put((byte) Response.INFO.ordinal());
                dataWrite.put((byte) (NetworkSIDDevice.getSidModel(sidNumber) == ChipModel.MOS8580 ? 1 : 0));
                byte[] name = NetworkSIDDevice.getSidName(sidNumber).getBytes(ISO_8859);
                int length = 0;
                while (length < Math.min(name.length, MAX_INFO_NAME_LENGTH) && name[length] != 0) {
                    length++;
                }
                dataWrite.put(name, 0, length);
                dataWrite.put((byte) 0);
                break;
            case SET_SID_POSITION:
                eventConsumerThread.setPosition(sidNumber, dataRead.get(HEADER_SIZE));
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case SET_SID_LEVEL:
                eventConsumerThread.setLevelAdjustment(sidNumber, dataRead.get(HEADER_SIZE));
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case TRY_SET_SID_MODEL:
                if (!queueReady()) {
                    break;
                }
                int configuration = dataRead.get(HEADER_SIZE) & 0xff;
                SIDChip readChip = NetworkSIDDevice.getSidConfig(configuration);
                readChip.setClockFrequency(sidClocking.getCpuFrequency());
                sidRead[sidNumber] = readChip;
                eventConsumerThread.setSID(sidNumber, NetworkSIDDevice.getSidConfig(configuration));
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case SET_DELAY:
                eventConsumerThread.setDelay(sidNumber, dataRead.get(HEADER_SIZE) & 0xff);
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case SET_FADE_IN:
            case SET_FADE_OUT:
                if (!queueReady()) {
                    break;
                }
                double seconds = Integer.toUnsignedLong(dataRead.getInt(HEADER_SIZE)) / (double) MILLIS_PER_SECOND;
                if (command == Command.SET_FADE_IN) {
                    eventConsumerThread.setFadeIn(seconds);
                } else {
                    eventConsumerThread.setFadeOut(seconds);
                }
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            case SET_SID_HEADER:
                tuneHeader = readSidHeader();
                dataWrite.put((byte) Response.OK.ordinal());
                break;
            default:
                throw new InvalidCommandException("Unsupported command: " + command);
        }
    }

    private boolean queueReady() {
        if (!eventConsumerThread.waitUntilQueueReady(MAX_TIME_TO_WAIT_FOR_QUEUE)) {
            dataWrite.put((byte) Response.BUSY.ordinal());
            return false;
        }
        return true;
    }

    private PSidHeader readSidHeader() throws InvalidCommandException {
        if (dataLength < SIZE_V1) {
            throw new InvalidCommandException("SET_SID_HEADER needs a complete PSID or RSID header", dataLength);
        }
        int magic = dataRead.getInt(HEADER_SIZE);
        int version = dataRead.getShort(HEADER_SIZE + VERSION_FIELD) & 0xffff;
        int offset = dataRead.getShort(HEADER_SIZE + PSidHeader.DATA_OFFSET_FIELD) & 0xffff;
        int minimumSize = version == 1 ? SIZE_V1 : PSidHeader.SIZE;
        if ((magic != MAGIC_PSID && magic != MAGIC_RSID)
                || (version < 1 || version > 5) && version != VERSION_4E
                || magic == MAGIC_RSID && version == 1
                || dataLength < minimumSize || offset < minimumSize || offset > dataLength
                || version == VERSION_4E && (offset - PSidHeader.SIZE) % 2 != 0) {
            throw new InvalidCommandException("Invalid PSID or RSID metadata header", dataLength);
        }
        byte[] bytes = new byte[dataLength];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = dataRead.get(HEADER_SIZE + i);
        }
        try {
            return new PSidHeader(bytes);
        } catch (RuntimeException e) {
            throw new InvalidCommandException("Invalid PSID or RSID metadata header: " + e.getMessage());
        }
    }

    /** All shadow chips share the C64 timeline, even when an event targets FM or an unused slot. */
    private void clockReadSids(int cycles) {
        inputClock += cycles;
        if (cycles > 0) {
            for (SIDChip chip : sidRead) {
                chip.clock(cycles, sample -> {
                });
            }
        }
    }

    private void handleDelayPacket(int cycles) throws InvalidCommandException {
        clockReadSids(cycles);
        if (cycles > 0) {
            eventConsumerThread.getSidCommandQueue().add(SIDWrite.makePureDelay(0, cycles));
        }
    }

    private void handleWritePacket(int length, Command command) throws InvalidCommandException {
        boolean extended = command.isExtended();
        Queue<SIDWrite> queue = eventConsumerThread.getSidCommandQueue();
        for (int i = 0; i < length; i += command.getWriteSize()) {
            int cycles = dataRead.getShort(HEADER_SIZE + i) & 0xffff;
            int address = extended ? dataRead.getShort(HEADER_SIZE + i + Short.BYTES) & 0xffff
                    : dataRead.get(HEADER_SIZE + i + Short.BYTES) & 0xff;
            byte value = dataRead.get(HEADER_SIZE + i + command.getWriteSize() - 1);
            clockReadSids(cycles);
            if (isFmAddress(address)) {
                if (eventConsumerThread.isSfxEnabled()) {
                    queue.add(new SIDWrite(0, address, value, cycles));
                    continue;
                }
            } else {
                int chip = address >> SID_REGISTER_BITS;
                if (chip < sidRead.length) {
                    queue.add(new SIDWrite(chip, address & SID_REGISTER_MASK, value, cycles));
                    sidRead[chip].write(address & SID_REGISTER_MASK, value);
                    continue;
                }
            }
            if (cycles > 0) {
                queue.add(SIDWrite.makePureDelay(0, cycles));
            }
        }
    }

    protected void dispose() {
        if (pendingFlush != null) {
            // A flush already in progress could clear an end marker queued here.
            pendingFlush.cancel(false);
            eventConsumerThread.interrupt();
            return;
        }
        eventConsumerThread.getSidCommandQueue().add(SIDWrite.makeEnd());

        if (!eventConsumerThread.waitUntilQueueReady(MAX_TIME_TO_WAIT_FOR_QUEUE)) {
            eventConsumerThread.interrupt();
            return;
        }

        eventConsumerThread.ensureDraining();
    }

    protected void disposeWait() {
        try {
            eventConsumerThread.join();
        } catch (InterruptedException ignored) {
        }
    }

    void processReady(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        if (key.isReadable()) {
            if (channel.read(dataRead) == -1) {
                throw new EOFException();
            }
            processReadBuffer();
            if (pendingFlush != null) {
                // Keep later packets on this connection behind the flush acknowledgement.
                key.interestOps(0);
                pendingFlush.whenComplete((clock, failure) -> {
                    try {
                        key.interestOps(SelectionKey.OP_WRITE);
                        key.selector().wakeup();
                    } catch (CancelledKeyException ignored) {
                        // The connection was closed while the flush was pending.
                    }
                });
            } else if (dataWrite.hasRemaining()) {
                key.interestOps(SelectionKey.OP_WRITE);
            }
        } else if (key.isWritable()) {
            if (pendingFlush != null) {
                // The completion callback enables write interest only after the PCM flush.
                inputClock = pendingFlush.join();
                pendingFlush = null;
                dataWrite.clear();
                dataWrite.put((byte) Response.OK.ordinal()).flip();
            }
            channel.write(dataWrite);
            if (!dataWrite.hasRemaining()) {
                key.interestOps(SelectionKey.OP_READ);
            }
        }
    }

    public PSidHeader getTuneHeader() {
        return tuneHeader;
    }

    /**
     * changeDevice will change the device to the specified device for all connected client contexts
     *
     * @param deviceInfo the device that should be used
     */
    public static void changeDevice(final Mixer.Info deviceInfo) {
        for (ClientContext clientContext : clientContextMap.values()) {
            clientContext.eventConsumerThread.changeDevice(deviceInfo);
        }
    }

    /**
     * setDigiBoost will change the digiboost setting for each device 8580 for all connected client contexts
     *
     * @param enabled specifies if the digiboost feature is turned on
     */
    public static void setDigiBoost(final boolean enabled) {
        for (ClientContext clientContext : clientContextMap.values()) {
            clientContext.eventConsumerThread.setDigiBoost(enabled);
        }
    }

    /**
     * setAudioBufferSize will change the size of the audio buffer for all connected client contexts
     *
     * @param audioBufferSize specifies the size of the audio buffer (1024-16384 as a power of two)
     */
    public static void setAudioBufferSize(final Integer audioBufferSize) {
        for (ClientContext clientContext : clientContextMap.values()) {
            clientContext.eventConsumerThread.setAudioBufferSize(audioBufferSize);
        }
    }

    public static Collection<PSidHeader> getTuneHeaders() {
        return clientContextMap.values().stream().map(ClientContext::getTuneHeader)
                .collect(Collectors.toList());
    }

    public static int getClientsConnectedCount() {
        return clientContextMap.size();
    }

    /**
     * applyConnectionConfigChanges will close all current connections and apply the new configuration which is stored
     * in the SIDDeviceSettings.
     */
    public static void applyConnectionConfigChanges() {
        openNewConnection = true;
        if (selector != null) {
            selector.wakeup();
        }
    }

    public static void listenForClients(final JSIDDeviceConfig config) {
        DetectionThread detectionThread = null;
        try {
            /* check for new connections. */
            openNewConnection = true;

            SIDDeviceSettings settings = SIDDeviceSettings.getInstance();
            startWhatsSidThread(settings);

            while (openNewConnection) {

                ssc = ServerSocketChannel.open();
                ssc.configureBlocking(false);

                boolean allowExternalIpConnections = settings.getAllowExternalConnections();

                String ipAddress = allowExternalIpConnections ? "0.0.0.0" : config.jsiddevice().getHostname();
                ssc.socket().bind(new InetSocketAddress(ipAddress, config.jsiddevice().getPort()));

                // Advertise exactly the endpoint TCP can accept. Recreate both
                // listeners together when external-connections settings change.
                detectionThread = new DetectionThread((InetSocketAddress) ssc.getLocalAddress(),
                        () -> allowExternalIpConnections);
                detectionThread.start();

                System.out.println("Opening listening socket on ip address " + ipAddress);

                selector = Selector.open();
                ssc.register(selector, SelectionKey.OP_ACCEPT);

                clientContextMap.clear();

                openNewConnection = false;
                while (!openNewConnection && !Thread.currentThread().isInterrupted()) {
                    // A flush completion can wake the selector before any key is ready.
                    selector.select();
                    if (openNewConnection) {
                        break;
                    }

                    for (SelectionKey sk : selector.selectedKeys()) {
                        if (sk.isAcceptable()) {
                            SocketChannel sc = ((ServerSocketChannel) sk.channel()).accept();
                            sc.socket().setReceiveBufferSize(16384);
                            sc.socket().setSendBufferSize(1024);
                            sc.configureBlocking(false);

                            sc.register(selector, SelectionKey.OP_READ);
                            IniJSIDDeviceAudioSection audio = config.audio();
                            AudioConfig audioConfig = new AudioConfig(audio.getSamplingRate().getFrequency(), 2,
                                    audio.getAudioBufferSize());
                            ClientContext cc = new ClientContext(audioConfig, config.jsiddevice().getLatency());
                            clientContextMap.put(sc, cc);
                            System.out.println("New client: " + cc);
                            continue;
                        }

                        SocketChannel sc = (SocketChannel) sk.channel();
                        ClientContext cc = clientContextMap.get(sc);
                        try {
                            cc.processReady(sk);
                        } catch (Exception e) {
                            System.out.println("Closing client " + cc + " due to exception: " + e);
                            clientContextMap.remove(sc);
                            sk.cancel();
                            sc.close();
                            cc.dispose();

                            if (!(e instanceof IOException)) {
                                e.printStackTrace();
                            }
                        }
                    }

                    selector.selectedKeys().clear();
                }

                detectionThread.close();
                closeClientConnections();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (detectionThread != null) {
                detectionThread.close();
            }
        }
    }

    private static void startWhatsSidThread(SIDDeviceSettings settings) {
        clientContextNumToCheck = 0;
        // server not available? silently ignore!
        Thread whatsSidThread = new Thread(() -> {
            do {
                try {
                    Thread.sleep(settings.getWhatsSidMatchRetryTime() * 1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (settings.isWhatsSidEnable()) {
                    Collection<ClientContext> clientContexts = clientContextMap.values();
                    Optional<ClientContext> clientContextToCheck = clientContexts.stream().skip(clientContextNumToCheck)
                            .findFirst();
                    if (++clientContextNumToCheck >= clientContexts.size()) {
                        clientContextNumToCheck = 0;
                    }
                    if (clientContextToCheck.isPresent()) {
                        ClientContext clientContext = clientContextToCheck.get();
                        WhatsSidSupport whatsSidSupport = clientContext.eventConsumerThread.getWhatsSidSupport();
                        if (whatsSidSupport != null) {
                            try {
                                IFingerprintMatcher fingerprintMatcher = new FingerprintJsonClient(
                                        settings.getWhatsSidUrl(), settings.getWhatsSidUsername(),
                                        settings.getWhatsSidPassword(), settings.getWhatsSidConnectionTimeout());
                                MusicInfoWithConfidenceBean result = whatsSidSupport.match(fingerprintMatcher);
                                if (result != null) {
                                    clientContext.whatsSidResult = result;
                                }
                            } catch (Throwable e) {
                                // server not available? silently ignore!
                            }
                        }
                    }
                }
            } while (true);
        });
        whatsSidThread.setPriority(Thread.MIN_PRIORITY);
        whatsSidThread.start();
    }

    private static void closeClientConnections() throws IOException {
        for (ClientContext cc : clientContextMap.values()) {
            System.out.println("Cleaning up client: " + cc);
            cc.dispose();
        }

        for (SocketChannel sc : clientContextMap.keySet()) {
            sc.close();
        }

        for (ClientContext cc : clientContextMap.values()) {
            cc.disposeWait();
        }

        if (ssc.socket().isBound()) {
            ssc.socket().close();
        }

        if (selector.isOpen()) {
            selector.close();
        }

        ssc.close();
        System.out.println("Listening socket closed.");
    }
}