OplOscilloscope.java

package libsidutils.oscilloscope;

import libsidplay.components.cart.supported.core.OplObserver;

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

/**
 * Emulator-owned OPL histories and their shared JVM/TeaVM frame format. Samples come from the existing synthesis pass;
 * displaying a second view never synthesizes or accumulates the sound again.
 */
public final class OplOscilloscope extends OplObserver {
    public static final int CHANNELS = 9, ALL_CHANNELS = 511, COLUMNS = 300;
    public static final int VERSION = 1, HEADER_BYTES = 48, CHANNEL_BYTES = 64;
    public static final int DATA_OFFSET = HEADER_BYTES + CHANNELS * CHANNEL_BYTES;
    public static final int MAX_FRAME_BYTES = DATA_OFFSET + CHANNELS * 4 * COLUMNS * 8;
    // The 10-bit F-number spans almost ten octaves; BLOCK adds another seven.
    private static final float PITCH_OCTAVES = 17f;
    private static final float[] PITCH_LOG_OFFSETS = new float[1024];

    static {
        for (int i = 1; i < PITCH_LOG_OFFSETS.length; i++) {
            PITCH_LOG_OFFSETS[i] = (float) (Math.log(i / 1023.0) / Math.log(2) / PITCH_OCTAVES);
        }
    }

    // Four histories per channel: output, OP1 envelope, OP2 envelope, base pitch.
    private final TraceHistory[] traces = new TraceHistory[36];
    private int waveColumnPhase;
    private int historyColumnPhase;

    public OplOscilloscope() {
        for (int i = 0; i < traces.length; i++) {
            traces[i] = new TraceHistory(512);
        }
    }

    @Override
    public void sample() {
        for (int channel = 0; channel < CHANNELS; channel++) {
            int trace = channel * 4;
            traces[trace].accumulate(normalizedOutput(channel));
            if (envelopesUpdated) {
                // The synthesis counter uses 0.1875 dB steps. Show the envelope
                // before total-level attenuation, with silence at the -48 dB floor.
                traces[trace + 1].accumulate(Math.max(0, 1 - envelope[channel * 2] * (0.1875f / 48)));
                traces[trace + 2].accumulate(Math.max(0, 1 - envelope[channel * 2 + 1] * (0.1875f / 48)));
                int blockFnum = fnum[channel];
                traces[trace + 3].accumulate((digi != 0 && channel < 2) || (blockFnum & 1023) == 0 ? 0 :
                        1 + PITCH_LOG_OFFSETS[blockFnum & 1023] + ((blockFnum >> 10) - 7) / PITCH_OCTAVES);
            }
        }
        // Integer phase accumulators keep 300 columns at 12 ms / 1.2 s across
        // sample rates. At low rates, one output sample may span several columns.
        waveColumnPhase += 25000;
        while (waveColumnPhase >= sampleRate) {
            for (int channel = 0; channel < CHANNELS; channel++) {
                traces[channel * 4].advance();
                traces[channel * 4].accumulate(normalizedOutput(channel));
            }
            waveColumnPhase -= sampleRate;
        }
        historyColumnPhase += 250;
        if (historyColumnPhase >= sampleRate) {
            for (int channel = 0; channel < CHANNELS; channel++) {
                for (int gauge = 1; gauge < 4; gauge++) {
                    traces[channel * 4 + gauge].advance();
                }
            }
            historyColumnPhase -= sampleRate;
        }
    }

    private float normalizedOutput(int channel) {
        // Zero is the center of a bipolar trace: 0.5 + output / (2 * peak).
        // Fixed synthesis-mode ranges preserve attenuation; automatic gain would
        // make a quiet instrument look as loud as a full-level instrument.
        // One operator peaks at +/-4096; additive combines two, and rhythm doubles each drum.
        float scale;
        if (digi != 0 && channel < 2) {
            scale = 1 / 16384f; // Signed 8-bit DAC latch * 64.
        } else if ((rhythm & 0x20) != 0 && channel >= 6) {
            scale = channel == 6 ? 1 / 16384f : 1 / 32768f;
        } else {
            scale = algorithm[channel] == 0 ? 1 / 8192f : 1 / 16384f;
        }
        return 0.5f + output[channel] * scale;
    }

    public void reset() {
        for (TraceHistory trace : traces) {
            trace.reset();
        }
        waveColumnPhase = historyColumnPhase = 0;
    }

    public static int frameBytes(int width, int detailMask) {
        return DATA_OFFSET + (CHANNELS + Integer.bitCount(detailMask & ALL_CHANNELS) * 3) * width * 8;
    }

    /**
     * Writes a little-endian frame into caller-owned storage, then flips it for reading. Output is included for all
     * nine channels; the mask adds each selected channel's two envelopes and pitch. The source generation lets a
     * delayed consumer reject frames from a previous tune or cartridge.
     */
    public void writeFrame(ByteBuffer frame, long time, int generation, int sequence, int width, int mask, int type) {
        frame.clear().order(ByteOrder.LITTLE_ENDIAN);
        frame.putInt(VERSION).putInt(generation).putInt(sequence).putInt(width).putInt(mask & ALL_CHANNELS);
        frame.putInt(type).putInt(rhythm).putInt(digi).putLong(time).putInt(clock).putInt(sampleRate);
        for (int channel = 0; channel < CHANNELS; channel++) {
            frame.putInt(fnum[channel]).putInt(algorithm[channel]).putInt(feedback[channel]).putInt(key[channel]);
            for (int operator = 0; operator < 2; operator++) {
                int index = channel * 2 + operator;
                frame.putInt(waveform[index]).putInt(multiplier[index]).putInt(totalLevel[index]).putInt(envelope[index]);
            }
            frame.putLong(0).putLong(0);
        }
        for (int channel = 0; channel < CHANNELS; channel++) {
            for (int gauge = 0; gauge < 4; gauge++) {
                if (gauge != 0 && (mask & 1 << channel) == 0) {
                    continue;
                }
                TraceHistory trace = traces[channel * 4 + gauge];
                for (int x = 0; x < width; x++) {
                    int start = COLUMNS - x * COLUMNS / width, end = COLUMNS - (x + 1) * COLUMNS / width;
                    float minimum = Float.POSITIVE_INFINITY, maximum = Float.NEGATIVE_INFINITY;
                    for (int back = start; back > end; back--) {
                        minimum = Math.min(minimum, trace.minimum(back));
                        maximum = Math.max(maximum, trace.maximum(back));
                    }
                    frame.putFloat(Math.max(0, Math.min(1, minimum))).putFloat(Math.max(0, Math.min(1, maximum)));
                }
            }
        }
        frame.flip();
    }

    /**
     * Base pitch in Hz, before either operator's multiplier or modulation.
     */
    public static double frequency(int blockFnum, int clock) {
        return (blockFnum & 1023) * Math.scalb(clock / 72.0, (blockFnum >> 10) - 20);
    }
}