SampleMixer.java

package builder.resid;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.function.IntConsumer;

import static builder.resid.SIDMixer.VOLUME_SCALER;

/**
 * Sound sample consumer consuming sample data while a SID is being clock'ed. A sample value is added to the audio
 * buffer to mix the output of several SIDs.
 * <BR>
 * <B>Note:</B> To mix several SIDs, all SampleMixer's IntBuffers must wrap the
 * same audio buffer. Additionally, the buffer must be cleared, before the next mixing starts.
 *
 * @author ken
 *
 */
public interface SampleMixer extends IntConsumer {

    class LogFadeTable {

        private static final float FADE_DB = -60.0f;

        /**
         * LOG fade table: x = [0..1], attenuation = -60 dB ... 0 dB.
         */
        private final int[] table;

        public LogFadeTable(int steps, int maxVolume) {
            this.table = new int[steps + 1];
            for (int i = 0; i <= steps; i++) {
                float x = (float) i / steps;
                float fade = (float) Math.pow(
                        10.0,
                        (FADE_DB * (1.0f - x)) / 20.0f
                );
                table[i] = Math.round(fade * maxVolume);
            }
        }

        public int get(int index) {
            return table[index];
        }

        public int size() {
            return table.length;
        }
    }

    /**
     *
     * Extends SampleMixer with a logarithmic fade-in/fade-out feature to smoothly increase/decrease volume.
     *
     * @author ken
     *
     */
    class LogFadingSampleMixer extends NoFadingSampleMixer {

        private static final int FADE_RESOLUTION = 1000; // clocks per fade table step
        private static final int MAX_FADE_STEPS = 200_000; // max entries for safety

        private int maxVolL, maxVolR;

        private LogFadeTable fadeInTableL, fadeInTableR;
        private LogFadeTable fadeOutTableL, fadeOutTableR;

        private int fadeInIndex = -1;
        private int fadeOutIndex = -1;

        private long fadeClockCounter = 0;

        public LogFadingSampleMixer(IntBuffer audioBufferL, IntBuffer audioBufferR) {
            super(audioBufferL, audioBufferR);
        }

        /**
         * Build a fade table using downsampled steps.
         */
        private LogFadeTable buildTable(long fadeClocks, int maxVolume) {
            if (fadeClocks <= 0)
                return null;

            long stepsLong = fadeClocks / FADE_RESOLUTION;
            int steps = (int) Math.min(stepsLong, MAX_FADE_STEPS);
            if (steps == 0)
                steps = 1;

            return new LogFadeTable(steps, maxVolume);
        }

        @Override
        public void setFadeIn(long fadeInClocks) {
            super.setVolume(0, 0);
            fadeInTableL = buildTable(fadeInClocks, maxVolL);
            fadeInTableR = buildTable(fadeInClocks, maxVolR);

            fadeInIndex = (fadeInTableL != null ? 0 : -1);
            fadeOutIndex = -1;
            fadeClockCounter = 0;
        }

        @Override
        public void setFadeOut(long fadeOutClocks) {
            super.setVolume(maxVolL, maxVolR);
            fadeOutTableL = buildTable(fadeOutClocks, maxVolL);
            fadeOutTableR = buildTable(fadeOutClocks, maxVolR);

            fadeOutIndex = (fadeOutTableL != null ? 0 : -1);
            fadeInIndex = -1;
            fadeClockCounter = 0;
        }

        @Override
        public void setVolume(int volumeL, int volumeR) {
            super.setVolume(volumeL, volumeR);
            this.maxVolL = volumeL;
            this.maxVolR = volumeR;
        }

        @Override
        public void accept(int sample) {
            if (fadeInIndex >= 0 && fadeInTableL != null) {
                fadeClockCounter++;
                if (fadeClockCounter >= FADE_RESOLUTION) {
                    fadeClockCounter = 0;

                    fadeInIndex++;
                    if (fadeInIndex >= fadeInTableL.size()) {
                        // Fade-in complete
                        fadeInIndex = -1;
                        fadeInTableL = fadeInTableR = null;
                        volumeL = maxVolL;
                        volumeR = maxVolR;
                    } else {
                        volumeL = fadeInTableL.get(fadeInIndex);
                        volumeR = fadeInTableR.get(fadeInIndex);
                    }
                }
            } else if (fadeOutIndex >= 0 && fadeOutTableL != null) {
                fadeClockCounter++;
                if (fadeClockCounter >= FADE_RESOLUTION) {
                    fadeClockCounter = 0;

                    fadeOutIndex++;
                    if (fadeOutIndex >= fadeOutTableL.size()) {
                        // Fade-out complete
                        fadeOutIndex = -1;
                        fadeOutTableL = fadeOutTableR = null;
                        volumeL = 0;
                        volumeR = 0;
                    } else {
                        int idx = fadeOutTableL.size() - 1 - fadeOutIndex;
                        volumeL = fadeOutTableL.get(idx);
                        volumeR = fadeOutTableR.get(idx);
                    }
                }
            }
            super.accept(sample);
        }

    }

    /**
     *
     * Extends SampleMixer with a linear fade-in/fade-out feature to smoothly increase/decrease volume.
     *
     * @author ken
     *
     */
    class LinearFadingSampleMixer extends NoFadingSampleMixer {
        /**
         * Fade-in/fade-out time in clock ticks.
         */
        private long fadeInClocks, fadeOutClocks;

        /**
         * Currently configured volume level.
         */
        private int maxVolL, maxVolR;

        /**
         * Fade-in/fade-out clock steps until the next volume change and current fade-in and fade-out counters for the
         * left and right speaker.
         */
        private long fadeInStepL, fadeInStepR, fadeOutStepL, fadeOutStepR, fadeInValL, fadeInValR, fadeOutValL,
                fadeOutValR;

        LinearFadingSampleMixer(IntBuffer audioBufferL, IntBuffer audioBufferR) {
            super(audioBufferL, audioBufferR);
        }

        /**
         * Set fade-in time. Increase volume from zero to the maximum.
         *
         * @param fadeIn fade-in time in clock ticks
         */
        public void setFadeIn(long fadeIn) {
            this.fadeInClocks = fadeIn;
            super.setVolume(0, 0);
            fadeInValL = fadeInStepL = maxVolL != 0 ? fadeInClocks / maxVolL : 0;
            fadeInValR = fadeInStepR = maxVolR != 0 ? fadeInClocks / maxVolR : 0;
        }

        /**
         * Set fade-out time. Decrease volume from the maximum to zero.
         *
         * @param fadeOut fade-out time in clock ticks
         */
        public void setFadeOut(long fadeOut) {
            this.fadeOutClocks = fadeOut;
            super.setVolume(maxVolL, maxVolR);
            fadeOutValL = fadeOutStepL = maxVolL != 0 ? fadeOutClocks / maxVolL : 0;
            fadeOutValR = fadeOutStepR = maxVolR != 0 ? fadeOutClocks / maxVolR : 0;
        }

        @Override
        public void setVolume(int volumeL, int volumeR) {
            super.setVolume(volumeL, volumeR);
            this.maxVolL = volumeL;
            this.maxVolR = volumeR;
        }

        @Override
        public void accept(int sample) {
            if (fadeInClocks > 0) {
                fadeInClocks--;
                if (--fadeInValL == 0) {
                    fadeInValL = fadeInStepL;
                    volumeL++;
                }
                if (--fadeInValR == 0) {
                    fadeInValR = fadeInStepR;
                    volumeR++;
                }
            } else if (fadeOutClocks > 0) {
                fadeOutClocks--;
                if (--fadeOutValL == 0) {
                    fadeOutValL = fadeOutStepL;
                    volumeL--;
                }
                if (--fadeOutValR == 0) {
                    fadeOutValR = fadeOutStepR;
                    volumeR--;
                }
            }
            super.accept(sample);
        }

    }

    class NoFadingSampleMixer implements SampleMixer {

        /**
         * Buffers of mixed sample values for the left/right speaker.
         */
        private final IntBuffer bufferL;
        private final IntBuffer bufferR;

        /**
         * Audibility of mixed sample values for the left/right speaker.
         */
        protected int volumeL, volumeR;

        /**
         * Sample buffer for delay effect.
         */
        private IntBuffer delayedSamples;

        private boolean delayedSamplesEnabled;

        NoFadingSampleMixer(IntBuffer audioBufferL, IntBuffer audioBufferR) {
            this.bufferL = audioBufferL;
            this.bufferR = audioBufferR;
            this.delayedSamplesEnabled = false;
            setVolume(1 << VOLUME_SCALER, 1 << VOLUME_SCALER);
            setDelay(0);
        }

        @Override
        public void setFadeIn(long fadeIn) {
        }

        @Override
        public void setFadeOut(long fadeOut) {
        }

        @Override
        public void setVolume(int volumeL, int volumeR) {
            this.volumeL = volumeL;
            this.volumeR = volumeR;
        }

        @Override
        public void setDelay(int delayedSamples) {
            this.delayedSamplesEnabled = delayedSamples != 0;
            this.delayedSamples = ByteBuffer
                    .allocate/* Direct: OutOfMemory for TeaVM WASM_GC_SAB */(Integer.BYTES * (delayedSamples + 1))
                    .order(ByteOrder.nativeOrder()).asIntBuffer().put(new int[delayedSamples + 1]);
            this.delayedSamples.flip();
        }

        @Override
        public void accept(int sample) {
            if (this.delayedSamplesEnabled) {
                if (!delayedSamples.put(sample).hasRemaining()) {
                    this.delayedSamples.flip();
                }
                sample = delayedSamples.get(delayedSamples.position());
            }
            bufferL.put(bufferL.get(bufferL.position()) + sample * volumeL);
            bufferR.put(bufferR.get(bufferR.position()) + sample * volumeR);
        }

        @Override
        public void clear() {
            bufferL.clear();
            bufferR.clear();
        }
    }

    class NoOpSampleMixer implements SampleMixer {

        @Override
        public void setFadeIn(long fadeIn) {
        }

        @Override
        public void setFadeOut(long fadeOut) {
        }

        @Override
        public void setVolume(int volumeL, int volumeR) {
        }

        @Override
        public void setDelay(int delayedSamples) {
        }

        @Override
        public void accept(int sample) {
        }

        @Override
        public void clear() {
        }
    }

    void setFadeIn(long fadeIn);

    void setFadeOut(long fadeOut);

    void setVolume(int volumeL, int volumeR);

    void setDelay(int delayedSamples);

    void clear();

}