ScopeSnapshot.java

package libsidutils.oscilloscope;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Layout helpers for copied SID traces followed by an optional OPL v1 frame. The header carries source generation and
 * PHI2 time so presentation can reject stale tunes and select the snapshot due at the audio playback position.
 */
public final class ScopeSnapshot {
    public static final int HEADER = 32, REGISTERS = 32;
    public static final int VERSION = 2;

    private ScopeSnapshot() {
    }

    public static int sidBytes(int width) {
        return sidBytes(width, VERSION);
    }

    private static int sidBytes(int width, int version) {
        return REGISTERS + 12 * width * 8 + (version >= 2 ? Integer.BYTES : 0);
    }

    public static int bytes(int width, int sidMask, int oplBytes) {
        return HEADER + Integer.bitCount(sidMask) * sidBytes(width) + oplBytes;
    }

    public static int sidOffset(ByteBuffer frame, int chip) {
        int mask = frame.getInt(16);
        return (mask & 1 << chip) == 0 ? -1 : HEADER + Integer.bitCount(mask & ((1 << chip) - 1))
                * sidBytes(frame.getInt(12), frame.getInt(0));
    }

    /** V1 frames have no applied playback flags. Register and trace offsets remain unchanged. */
    public static int playbackFlags(ByteBuffer frame, int chip) {
        int base = sidOffset(frame, chip);
        return base < 0 || frame.getInt(0) < 2 ? 0
                : frame.getInt(base + REGISTERS + 12 * frame.getInt(12) * 8);
    }

    public static ByteBuffer opl(ByteBuffer frame) {
        int length = frame.getInt(20);
        if (length == 0) {
            return null;
        }
        int offset = HEADER + Integer.bitCount(frame.getInt(16)) * sidBytes(frame.getInt(12), frame.getInt(0));
        return frame.duplicate().position(offset).limit(offset + length).slice().order(ByteOrder.LITTLE_ENDIAN);
    }

    /**
     * Covers queued device audio, one producer chunk and one emulation buffer, plus four display frames. A fixed tiny
     * queue would discard the middle of a 16K audio burst before playback had a chance to display it.
     */
    public static int capacity(double fps, int sampleRate, int deviceFrames, int chunkFrames,
                               int emulationCycles, double cpuFrequency) {
        return Math.max(8, (int) Math.ceil(fps * ((deviceFrames + (double) chunkFrames) /
                sampleRate + emulationCycles / cpuFrequency)) + 4);
    }
}