SnapshotQueue.java

package libsidutils.oscilloscope;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 * Reusable snapshots between emulation and presentation/transport threads. Synchronization covers slot reuse and
 * copying: a consumer never retains a view into a producer slot. Overflow discards the oldest snapshot rather than
 * blocking synthesis or growing memory without a bound.
 */
public final class SnapshotQueue {
    private final ByteBuffer[] slots;
    private int head, size;
    private ByteBuffer presentation;

    public SnapshotQueue(int capacity) {
        if (capacity < 1) {
            throw new IllegalArgumentException("Positive capacity required");
        }
        slots = new ByteBuffer[capacity];
    }

    public int capacity() {
        return slots.length;
    }

    public synchronized int size() {
        return size;
    }

    public synchronized void clear() {
        head = size = 0;
        Arrays.fill(slots, null);
        presentation = null;
    }

    public synchronized void capture(OscilloscopeService source, long time, int generation,
                                     int sequence, int width, int detailMask) {
        if (size == slots.length) {
            head = (head + 1) % slots.length;
            size--;
        }
        int slot = (head + size++) % slots.length;
        int bytes = source.snapshotBytes(width, detailMask);
        if (slots[slot] == null || slots[slot].capacity() < bytes) {
            slots[slot] = ByteBuffer.allocate(bytes).order(ByteOrder.LITTLE_ENDIAN);
        }
        source.writeSnapshot(slots[slot], time, generation, sequence, width, detailMask);
    }

    /**
     * Also useful for received packets and deterministic playback tests.
     */
    public synchronized void offer(ByteBuffer frame) {
        if (size == slots.length) {
            head = (head + 1) % slots.length;
            size--;
        }
        int slot = (head + size++) % slots.length;
        if (slots[slot] == null || slots[slot].capacity() < frame.remaining()) {
            slots[slot] = ByteBuffer.allocate(frame.remaining()).order(ByteOrder.LITTLE_ENDIAN);
        }
        slots[slot].clear().put(frame.duplicate()).flip();
    }

    /**
     * Coalesces obsolete due frames, retaining future frames until audio reaches them. The returned presentation buffer
     * is valid until the next poll/clear.
     */
    public synchronized ByteBuffer pollDue(long cycle) {
        ByteBuffer selected = null;
        while (size > 0 && slots[head].getLong(24) <= cycle) {
            selected = slots[head];
            head = (head + 1) % slots.length;
            size--;
        }
        if (selected == null) {
            return null;
        }
        // Presentation owns this copy; the producer may immediately reuse its ring slot.
        if (presentation == null || presentation.capacity() < selected.limit()) {
            presentation = ByteBuffer.allocate(selected.limit()).order(ByteOrder.LITTLE_ENDIAN);
        }
        presentation.clear().put(selected.duplicate().rewind()).flip();
        return presentation;
    }

    /**
     * Counts only snapshots covered by audio that the mixer has submitted.
     */
    public synchronized int batchBytes(long through) {
        int bytes = 16;
        for (int i = 0; i < size; i++) {
            ByteBuffer frame = slots[(head + i) % slots.length];
            if (frame.getLong(24) > through) {
                break;
            }
            bytes += 4 + frame.limit();
        }
        return bytes;
    }

    /**
     * Copies due records into a reserved transport slot; drawing does not hold it.
     */
    public synchronized void writeBatch(ByteBuffer target, long through, int generation) {
        target.clear().order(ByteOrder.LITTLE_ENDIAN);
        target.putInt(1).putInt(generation).putInt(0).putInt(slots.length);
        int count = 0;
        while (size > 0) {
            ByteBuffer frame = slots[head];
            if (frame.getLong(24) > through || target.remaining() < frame.limit() + 4) {
                break;
            }
            target.putInt(frame.limit()).put(frame.duplicate().rewind());
            head = (head + 1) % slots.length;
            size--;
            count++;
        }
        target.putInt(8, count).flip();
    }
}