SIDRenderer.java

package server.netsiddev;

import libsidplay.common.SIDChip;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntConsumer;
import java.util.function.LongSupplier;

/**
 * Renders a bounded slice of the global SID timeline into private chip buffers.
 * Register writes stay on their chip's rendering thread; only the audio thread
 * mixes the completed buffers. There is one barrier per batch, not per write.
 */
final class SIDRenderer implements AutoCloseable {
    /** Roughly 10 ms of PAL/NTSC audio, bounding latency and reconfiguration time. */
    static final int BATCH_CYCLES = 10000;
    /** Also bound a batch containing arbitrarily many same-cycle writes. */
    static final int MAX_BATCH_WRITES = 4096;
    /** An unwritten SID has no samples, delay-line activity or fade progress. */
    private static final int INACTIVE = -1;
    /** Keep mono/stereo on the audio thread; add a participant per further pair. */
    private static final int SIDS_PER_THREAD = 2;
    /** Average over about 100 ms of generated audio to smooth out scheduling jitter. */
    private static final int RENDER_MEASUREMENT_CYCLES = 10 * BATCH_CYCLES;
    /** Leave time for mixing, resampling and PCM delivery. */
    private static final double RENDER_BUDGET = 0.5;
    /** Allow a margin when estimating whether one fewer participant can meet the budget. */
    private static final double REDUCED_RENDER_BUDGET = 0.4;
    private static final AtomicInteger WORKER_NUMBER = new AtomicInteger();

    private final int parallelism;
    private final LongSupplier nanoTime;
    private final SIDWrite[] writes = new SIDWrite[MAX_BATCH_WRITES];
    private final int[] cycles = new int[MAX_BATCH_WRITES];
    private final boolean[] complete = new boolean[MAX_BATCH_WRITES];
    private int size, totalCycles;
    private SIDChip[] sids;
    private boolean[] used;
    private int[][] samples;
    private int[] activeStart, activeSids;
    private int activeCount;
    private ExecutorService workers;
    private int renderParticipants = 1;
    private int measuredCycles;
    private long measuredNanos;

    SIDRenderer(int processors) {
        this(processors, System::nanoTime);
    }

    SIDRenderer(int processors, LongSupplier nanoTime) {
        parallelism = Math.max(1, Math.min(processors,
                (NetworkSIDProtocol.EXTENDED_SID_CAPACITY + SIDS_PER_THREAD - 1) / SIDS_PER_THREAD));
        this.nanoTime = nanoTime;
    }

    void begin(SIDChip[] chips, boolean[] sidUsed) {
        Arrays.fill(writes, 0, size, null);
        size = totalCycles = activeCount = 0;
        if (sids != chips) {
            renderParticipants = 1;
            measuredCycles = 0;
            measuredNanos = 0;
        }
        sids = chips;
        used = sidUsed;
        if (samples == null || samples.length != chips.length) {
            samples = new int[chips.length][BATCH_CYCLES];
            activeStart = new int[chips.length];
            activeSids = new int[chips.length];
        }
        for (int sid = 0; sid < chips.length; sid++) {
            activeStart[sid] = used[sid] ? 0 : INACTIVE;
            if (used[sid]) {
                activeSids[activeCount++] = sid;
            }
        }
    }

    void add(SIDWrite write, int duration, boolean completesWrite) {
        if (write.isSidWrite() && !used[write.getChip()]) {
            int sid = write.getChip();
            // A chip starts before its first write's delay, even when that delay
            // crosses a batch boundary. Never clock a still-unused reserved slot.
            used[sid] = true;
            activeStart[sid] = totalCycles;
            activeSids[activeCount++] = sid;
        }
        writes[size] = write;
        cycles[size] = duration;
        complete[size++] = completesWrite;
        totalCycles += duration;
    }

    boolean isFull() {
        return totalCycles == BATCH_CYCLES || size == MAX_BATCH_WRITES;
    }

    int size() {
        return size;
    }

    int getCycles() {
        return totalCycles;
    }

    int getCycles(int index) {
        return cycles[index];
    }

    SIDWrite getWrite(int index) {
        return writes[index];
    }

    boolean completesWrite(int index) {
        return complete[index];
    }

    int getActiveStart(int sid) {
        return activeStart[sid];
    }

    int[] getSamples(int sid) {
        return samples[sid];
    }

    void render() throws InterruptedException {
        render(maximumParticipants());
    }

    void renderAdaptive(double clockFrequency) throws InterruptedException {
        int maximum = maximumParticipants();
        if (maximum == 1) {
            render(1);
            return;
        }

        // A fast serial batch avoids waking workers and gives the network thread
        // more CPU time for the shadow SIDs it clocks on the same timeline.
        renderParticipants = Math.min(renderParticipants, maximum);
        long start = nanoTime.getAsLong();
        render(renderParticipants);
        measuredNanos += nanoTime.getAsLong() - start;
        measuredCycles += totalCycles;
        if (measuredCycles >= RENDER_MEASUREMENT_CYCLES) {
            double renderShare = measuredNanos * clockFrequency / (measuredCycles * 1e9);
            if (renderShare > RENDER_BUDGET) {
                int needed = (int) Math.ceil(renderParticipants * renderShare / RENDER_BUDGET);
                renderParticipants = Math.min(maximum, needed);
            } else if (renderParticipants > 1
                    && renderShare * renderParticipants < REDUCED_RENDER_BUDGET * (renderParticipants - 1)) {
                renderParticipants--;
            }
            measuredCycles = 0;
            measuredNanos = 0;
        }
    }

    private int maximumParticipants() {
        return activeCount <= SIDS_PER_THREAD || totalCycles == 0 ? 1
                : Math.min(parallelism, (activeCount + SIDS_PER_THREAD - 1) / SIDS_PER_THREAD);
    }

    private void render(int participants) throws InterruptedException {
        if (participants == 1) {
            renderAudioGroup(1);
            return;
        }
        if (workers == null) {
            workers = Executors.newFixedThreadPool(parallelism - 1, task -> {
                Thread worker = new Thread(task, "JSIDDevice-SID-" + WORKER_NUMBER.incrementAndGet());
                worker.setDaemon(true);
                worker.setPriority(Thread.MAX_PRIORITY);
                return worker;
            });
        }
        List<Future<?>> pending = new ArrayList<>(participants - 1);
        boolean finished = false;
        try {
            for (int group = 1; group < participants; group++) {
                final int assignedGroup = group;
                pending.add(workers.submit(() -> renderGroup(assignedGroup, participants)));
            }
            // The audio thread participates, so three SIDs need only one helper.
            renderAudioGroup(participants);
            for (Future<?> task : pending) {
                task.get();
            }
            finished = true;
        } catch (ExecutionException e) {
            throw new IllegalStateException("SID rendering failed", e.getCause());
        } finally {
            if (!finished) {
                for (Future<?> task : pending) {
                    task.cancel(true);
                }
            }
        }
    }

    private void renderAudioGroup(int participants) throws InterruptedException {
        try {
            renderGroup(0, participants);
        } catch (CancellationException e) {
            if (!Thread.currentThread().isInterrupted()) {
                throw e;
            }
            throw new InterruptedException("SID rendering interrupted");
        }
    }

    private void renderGroup(int group, int participants) {
        for (int index = group; index < activeCount; index += participants) {
            renderSid(activeSids[index]);
        }
    }

    private void renderSid(int sid) {
        SIDChip chip = sids[sid];
        // Live mute/digiboost controls use the same per-chip lock. Array/model/
        // clock changes wait until the entire batch has joined on the audio thread.
        synchronized (chip) {
            int[] position = {activeStart[sid]};
            IntConsumer output = sample -> samples[sid][position[0]++] = sample;
            int offset = 0;
            for (int index = 0; index < size; index++) {
                if (Thread.currentThread().isInterrupted()) {
                    throw new CancellationException("SID rendering interrupted");
                }
                if (offset >= activeStart[sid] && cycles[index] != 0) {
                    // Keep every global interval, including other chips' writes:
                    // some cores clean denormals at the end of each clock call.
                    chip.clock(cycles[index], output);
                }
                SIDWrite write = writes[index];
                if (complete[index] && write.isSidWrite() && write.getChip() == sid) {
                    chip.write(write.getRegister(), write.getValue());
                }
                offset += cycles[index];
            }
        }
    }

    @Override
    public void close() {
        if (workers == null) {
            return;
        }
        workers.shutdownNow();
        boolean interrupted = false;
        try {
            // Never let a worker retain an emulator after the audio thread exits.
            while (!workers.isTerminated()) {
                try {
                    workers.awaitTermination(1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    interrupted = true;
                }
            }
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }
}