ReSfxSoundExpander.java

package libsidplay.components.cart.supported;

import libsidplay.common.AudioActivity;
import libsidplay.components.cart.MusicCartridgeAudioProcessor;
import libsidplay.components.cart.supported.core.FMOPL_072;
import libsidplay.components.cart.supported.core.OplObserver;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Random;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;

import static java.lang.Short.MAX_VALUE;
import static java.lang.Short.MIN_VALUE;
import static java.nio.ByteOrder.nativeOrder;

public class ReSfxSoundExpander implements ISfxSoundExpander, MusicCartridgeAudioProcessor {
    private static final int OPL_CLOCK = 3579545;

    private final int type;
    private int cpuRate;
    private final IntSupplier ffBitMaskSupplier;
    private final IntSupplier ffFactorSupplier;

    private FMOPL_072.FM_OPL fmOpl;

    private OplObserver observer;

    public int getType() {
        return type;
    }

    public boolean isPrepared() {
        return fmOpl != null;
    }

    public synchronized void setObserver(OplObserver observer) {
        this.observer = observer;
        if (fmOpl != null) {
            FMOPL_072.setObserver(fmOpl, observer);
        }
    }

    public synchronized void copyObserverState() {
        if (fmOpl != null) {
            FMOPL_072.copyObserverState(fmOpl);
        }
    }

    private int sampleRate;
    private long sampleAccumulator;
    private int fastForwardSamples;
    private int sampleSum;
    // Master-clock periods, scaled by cpuRate. Advancing one CPU cycle adds
    // OPL_CLOCK units, retaining sub-cycle timer deadlines without PCM rounding.
    private final long[] timerRemaining = {-1, -1};

    /**
     * Random source for triangular dithering
     */
    private final Random RANDOM = new Random();
    /**
     * State of HP-TPDF.
     */
    private int oldRandomValue;

    private IntBuffer cartAudioBuffer;
    private final AudioActivity audioActivity = new AudioActivity();
    private boolean audioActivityEnabled;
    private static final IntConsumer DISCARD_SAMPLES = sample -> { };
    private final IntConsumer queuedSamples = this::queueSample;
    private final IntConsumer monitoredSamples = sample -> {
        audioActivity.accept(sample);
        queueSample(sample);
    };

    @Override
    public synchronized void setAudioActivityEnabled(boolean enabled) {
        if (audioActivityEnabled != enabled) {
            audioActivityEnabled = enabled;
            audioActivity.reset();
        }
    }

    @Override
    public synchronized boolean pollAudioActivity() {
        return audioActivity.poll();
    }

    public ReSfxSoundExpander(int type, int cpuRate, IntSupplier ffBitMaskSupplier, IntSupplier ffFactorSupplier) {
        if (cpuRate <= 0) throw new IllegalArgumentException("CPU rate must be positive");
        this.type = type;
        this.cpuRate = cpuRate;
        this.ffBitMaskSupplier = ffBitMaskSupplier;
        this.ffFactorSupplier = ffFactorSupplier;
    }

    public synchronized void setCpuRate(int cpuRate) {
        if (cpuRate <= 0) throw new IllegalArgumentException("CPU rate must be positive");
        if (this.cpuRate != cpuRate) {
            for (int i = 0; i < 2; i++) if (timerRemaining[i] >= 0)
                timerRemaining[i] = timerRemaining[i] * cpuRate / this.cpuRate;
            sampleAccumulator = sampleAccumulator * cpuRate / this.cpuRate;
        }
        this.cpuRate = cpuRate;
    }

    @Override
    public synchronized void reset() {
        if (fmOpl != null) {
            FMOPL_072.reset_chip(fmOpl);
        }
        timerRemaining[0] = timerRemaining[1] = -1;
        start();
    }

    @Override
    public synchronized void start() {
        audioActivity.reset();
        sampleAccumulator = 0L;
        sampleSum = 0;
        fastForwardSamples = 0;
        oldRandomValue = 0;
        if (cartAudioBuffer != null) {
            cartAudioBuffer.clear();
        }
    }

    @Override
    public synchronized void prepare(int sampleRate, int bufferSize) {
        if (sampleRate <= 0 || bufferSize <= 0) throw new IllegalArgumentException("Positive audio rate and buffer size required");
        this.sampleRate = sampleRate;
        timerRemaining[0] = timerRemaining[1] = -1;
        fmOpl = FMOPL_072.init(type, OPL_CLOCK, sampleRate);
        FMOPL_072.set_timer_handler(fmOpl, (timer, period) ->
                timerRemaining[timer] = period == 0 ? -1 : Math.round(period * OPL_CLOCK) * cpuRate);
        FMOPL_072.setObserver(fmOpl, observer);

        cartAudioBuffer = ByteBuffer.allocateDirect(Integer.BYTES * bufferSize).order(nativeOrder()).asIntBuffer();
        start();
    }

    /**
     * We mix cartridge audio samples into the audio buffer here.
     *
     * @param buffer stereo audio buffer of samples at the target frequency rate.
     */
    public synchronized void process(ByteBuffer buffer) {
        if (cartAudioBuffer == null) return;
        ((Buffer) cartAudioBuffer).flip();

        int len = buffer.position() >> 2;
        ((Buffer) buffer).flip();
        for (int i = 0; i < len && cartAudioBuffer.hasRemaining(); i++) {
            int dither = triangularDithering();
            int sample = (short) Math.max(Math.min(cartAudioBuffer.get() + dither, MAX_VALUE), MIN_VALUE);
            int origSampleL = buffer.getShort(buffer.position());
            buffer.putShort((short) Math.max(Math.min(origSampleL + sample, MAX_VALUE), MIN_VALUE));
            int origSampleR = buffer.getShort(buffer.position());
            buffer.putShort((short) Math.max(Math.min(origSampleR + sample, MAX_VALUE), MIN_VALUE));
        }
        ((Buffer) buffer).position(len << 2);
        cartAudioBuffer.compact();
    }

    /**
     * Triangularly shaped noise source for audio applications. Output of this PRNG is between ]-1, 1[.
     *
     * @return triangular noise sample
     */
    private int triangularDithering() {
        int prevValue = oldRandomValue;
        oldRandomValue = RANDOM.nextInt(2);
        return oldRandomValue - prevValue;
    }

    @Override
    public synchronized byte read(int addr) {
        return fmOpl == null ? (byte) 0xff : (byte) FMOPL_072.read(fmOpl, 0);
    }

    @Override
    public synchronized void write(int addr, byte val) {
        if (fmOpl != null) FMOPL_072.write(fmOpl, (addr & 0x7f) == 0x40 ? 0 : 1, val & 0xff);
    }

    @Override
    public synchronized void clock(int cycles) {
        clock(cycles, true);
    }

    synchronized void clock(int cycles, boolean queueAudio) {
        if (fmOpl == null || cycles <= 0) return;
        // Bound the multiplication by sampleRate even for a long idle interval.
        while (cycles > 0) {
            int piece = Math.min(cycles, 32768);
            long remaining = (long) piece * OPL_CLOCK;
            while (remaining > 0) {
                long step = remaining;
                for (long timer : timerRemaining) if (timer >= 0) step = Math.min(step, timer);
                render(step, queueAudio);
                remaining -= step;
                for (int i = 0; i < 2; i++) if (timerRemaining[i] >= 0) timerRemaining[i] -= step;
                for (int i = 0; i < 2; i++) if (timerRemaining[i] == 0) {
                    timerRemaining[i] = -1;
                    FMOPL_072.timer_over(fmOpl, i); // Also reloads through the timer handler.
                }
            }
            cycles -= piece;
        }
    }

    private void render(long clocks, boolean queueAudio) {
        long denominator = (long) cpuRate * OPL_CLOCK;
        sampleAccumulator += clocks * sampleRate;
        int samples = (int) (sampleAccumulator / denominator);
        sampleAccumulator %= denominator;

        FMOPL_072.update_one(fmOpl, !queueAudio ? DISCARD_SAMPLES
                : audioActivityEnabled ? monitoredSamples : queuedSamples, samples);
    }

    private void queueSample(int sample) {
        sampleSum += sample;
        int fastForwardBitMask = ffBitMaskSupplier.getAsInt();
        if ((fastForwardSamples++ & fastForwardBitMask) == fastForwardBitMask) {
            if (!cartAudioBuffer.hasRemaining()) {
                IntBuffer larger = ByteBuffer.allocateDirect(Math.multiplyExact(cartAudioBuffer.capacity(), Integer.BYTES * 2))
                        .order(nativeOrder()).asIntBuffer();
                cartAudioBuffer.flip(); larger.put(cartAudioBuffer); cartAudioBuffer = larger;
            }
            cartAudioBuffer.put(sampleSum >> ffFactorSupplier.getAsInt());
            sampleSum = 0;
        }
    }

}