PlaybackTimeline.java

package libsidutils.oscilloscope;

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

/**
 * Bounded mapping from absolute PCM sample positions to emulated PHI2 cycles. Chunk boundaries and speed changes
 * provide anchors. Interpolation follows the audio device's played position, rather than jumping to the end of each
 * large emulation buffer. The mixer writes anchors while the display reads them.
 */
public final class PlaybackTimeline {
    private final long[] samplePositions = new long[128], cyclePositions = new long[128];
    private int head, size;

    /**
     * Begin a new live playback epoch after queued samples have been discarded.
     */
    public synchronized void clear() {
        head = size = 0;
    }

    public synchronized void add(long sample, long cycle) {
        if (size > 0 && sample == samplePositions[(head + size - 1) & 127]) {
            cyclePositions[(head + size - 1) & 127] = cycle;
            return;
        }
        if (size == samplePositions.length) {
            head = (head + 1) & 127;
            size--;
        }
        int index = (head + size++) & 127;
        samplePositions[index] = sample;
        cyclePositions[index] = cycle;
    }

    /**
     * Returns Long.MIN_VALUE until playback reaches the first known anchor.
     */
    public synchronized long cycleAt(long sample) {
        if (size == 0) {
            return Long.MIN_VALUE;
        }
        int previous = head;
        if (sample < samplePositions[previous]) {
            return Long.MIN_VALUE;
        }
        for (int i = 1; i < size; i++) {
            int next = (head + i) & 127;
            if (sample <= samplePositions[next]) {
                long span = samplePositions[next] - samplePositions[previous];
                return cyclePositions[previous] + (long) ((sample - samplePositions[previous]) *
                        (double) (cyclePositions[next] - cyclePositions[previous]) / span);
            }
            previous = next;
        }
        return cyclePositions[previous];
    }

    /**
     * Writes one PCM chunk's sample/cycle anchors. Integer-valued doubles remain exact below 2^53 and avoid depending
     * on TeaVM's Java long representation.
     */
    public synchronized void write(ByteBuffer target, long first, long last, int sampleRate) {
        target.clear().order(ByteOrder.LITTLE_ENDIAN);
        target.putInt(1).putInt(sampleRate).putDouble(first).putDouble(last).putInt(0).putInt(0);
        target.putDouble(first).putDouble(cycleAt(first));
        int count = 1;
        for (int i = 0; i < size; i++) {
            int index = (head + i) & 127;
            if (samplePositions[index] > first && samplePositions[index] < last) {
                target.putDouble(samplePositions[index]).putDouble(cyclePositions[index]);
                count++;
            }
        }
        target.putDouble(last).putDouble(cycleAt(last));
        target.putInt(24, count + 1).flip();
    }
}