ImportedApi.java

package client.teavm;

import client.teavm.common.IImportedApi;
import client.teavm.common.parameter.event.IImportEventParameters;
import libsidplay.components.printer.IPaper.Outputs;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSByRef;
import org.teavm.jso.typedarrays.Uint8Array;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

import static java.lang.Short.MIN_VALUE;
import static java.nio.ByteOrder.BIG_ENDIAN;
import static java.nio.ByteOrder.LITTLE_ENDIAN;

/**
 * TeaVM JavaScript Interop (JSO)-based implementation of {@link client.teavm.common.IImportedApi}.
 *
 * <p>
 * This class provides a standard bridge between the TeaVM Web Worker and the browser main thread using TeaVM's
 * {@code @JSBody} mechanism. It is the default implementation for general browser environments.
 * </p>
 *
 * <h2>Data Conversion</h2>
 * <ul>
 * <li><b>Audio samples:</b> Converts 16-bit signed PCM samples (shorts) to
 * 32-bit floats in the range of -1.0 to 1.0. A lookup table is used for high
 * performance.</li>
 * <li><b>Video frame:</b> Transfers RGBA pixel data (4 bytes
 * per pixel).</li>
 * <li><b>Oscilloscope data:</b> Forwards packed SID/OPL
 * snapshots to JavaScript for visualization.</li>
 * </ul>
 *
 * <h2>Oscilloscope Bridges</h2>
 * <p>
 * Each operation has a Java method implementing {@link IImportedApi} and a native {@code ...JS} binding that calls
 * the worker's required JavaScript hooks through {@code @JSBody}:
 * </p>
 * <ul>
 * <li>{@code prepareOscBatch} and {@code processOscBatch}: check capacity and publish batches of numeric SID/OPL
 * snapshots for playback-aligned rendering.</li>
 * <li>{@code processOscSources}: announces source changes and generations.</li>
 * <li>{@code processAudioTiming}: maps audio sample positions to emulated cycles so snapshots follow playback.</li>
 * </ul>
 *
 * <h2>Synchronization</h2>
 * <p>
 * Unlike {@link client.teavm.ImportedApiSAB}, which uses shared memory and
 * atomic operations, this implementation relies on TeaVM's standard JavaScript
 * interop, where data is typically passed via callbacks or message passing
 * (depending on how the JavaScript side is implemented).
 * </p>
 */
public class ImportedApi implements IImportedApi, IImportEventParameters {

    private static final String CALLBACK_PROCESS_WARP = "processWarp";
    private static final String CALLBACK_PROCESS_SAMPLES = "processSamples";
    private static final String CALLBACK_PROCESS_FRAME = "processFrame";
    private static final String CALLBACK_WHATSSID = "whatsSid";
    private static final String CALLBACK_PREPARE_OSC_BATCH = "prepareOscBatch";
    private static final String CALLBACK_PROCESS_OSC_BATCH = "processOscBatch";
    private static final String CALLBACK_PROCESS_AUDIO_TIMING = "processAudioTiming";
    private static final String CALLBACK_PROCESS_OSC_SOURCES = "processOscSources";
    private static final String CALLBACK_PROCESS_SID_WRITE = "processSidWrite";
    private static final String CALLBACK_TIMER_END = "timerEnd";
    private static final String CALLBACK_PROCESS_PRINTER = "processPrinter";
    private static final String CALLBACK_PROCESS_GEORAM_IMAGE = "processGeoRAMImage";

    protected FloatBuffer resultL, resultR;

    @Override
    public boolean supportsWarp() {
        return true;
    }

    @Override
    public void processWarp(boolean enabled) {
        processWarpJS(enabled);
    }

    @Override
    public void processInspection(String json) {
        processInspectionJS(json);
    }

    @Override
    public ByteBuffer initSampleBuffer(int chunkFrames, int channels) {
        ByteBuffer samples = ByteBuffer.allocateDirect(chunkFrames * Short.BYTES * channels).order(LITTLE_ENDIAN);
        resultL = FloatBuffer.wrap(new float[chunkFrames]);
        resultR = FloatBuffer.wrap(new float[chunkFrames]);
        return samples;
    }

    @Override
    public ByteBuffer initFrameBuffer(int maxWidth, int maxHeight) {
        return ByteBuffer.allocateDirect(maxWidth * maxHeight << 2).order(BIG_ENDIAN);
    }

    @Override
    public ByteBuffer initWhatsSidBuffer(int wavLength) {
        return ByteBuffer.allocate(wavLength).order(LITTLE_ENDIAN);
    }

    @Override
    public ByteBuffer initOscBatchBuffer(int length, int slot) {
        return ByteBuffer.allocate(length).order(LITTLE_ENDIAN);
    }

    @Override
    public void processSamples(long absTime, ByteBuffer sampleBuffer, float[] lookupTable) {
        sampleBuffer.flip();
        int remaining = sampleBuffer.remaining() >> 2;
        for (int i = 0; i < remaining; i++) {
            resultL.put(lookupTable[sampleBuffer.getShort() - MIN_VALUE]);
            resultR.put(lookupTable[sampleBuffer.getShort() - MIN_VALUE]);
        }
        processSamplesJS(absTime, resultL.array(), resultR.array(), remaining);
        resultL.clear();
        resultR.clear();
    }

    @Override
    public void prepareFrame(ByteBuffer pixels) {
        pixels.clear();
    }

    @Override
    public void processFrame(long absTime, ByteBuffer pixels) {
        // WASM memory can grow after initialisation; obtain its current view.
        Uint8Array view = Uint8Array.fromJavaBuffer(pixels);
        processFrameJS(absTime, view);
    }

    @Override
    public void whatsSid(ByteBuffer whatsSidBuffer) {
        whatsSidJS(whatsSidBuffer.array(), whatsSidBuffer.capacity());
    }

    @Override
    public int prepareOscBatch() {
        return prepareOscBatchJS();
    }

    @Override
    public void processOscBatch(ByteBuffer frame, int slot) {
        processOscBatchJS(frame.array(), frame.limit());
    }

    @Override
    public void processAudioTiming(ByteBuffer timing) {
        processAudioTimingJS(timing.array(), timing.limit());
    }

    @Override
    public void processOscSources(int type, int generation) {
        processOscSourcesJS(type, generation);
    }

    @Override
    public void processSidWrite(int sidNum, long absTime, int relTime, int addr, int value) {
        processSidWriteJS(sidNum, absTime, relTime, addr, value);
    }

    @Override
    public void processTimerEnd(double end) {
        processTimerEndJS(end);
    }

    @Override
    public void processPrinter(Outputs output) {
        processPrinterJS(output.name());
    }

    @Override
    public void processGeoRAMImage(byte[] contents) {
        processGeoRAMImageJS(contents, contents.length);
    }

    //
    // Imports from JavaScript
    //

    @JSBody(params = {"enabled"}, script = CALLBACK_PROCESS_WARP + "(enabled);")
    public static native void processWarpJS(boolean enabled);

    @JSBody(params = {"json"}, script = "processInspection(json);")
    public static native void processInspectionJS(String json);

    @JSBody(params = {ABS_TIME, LEFT, RIGHT, LENGTH}, script = CALLBACK_PROCESS_SAMPLES + "(" + ABS_TIME + "," + LEFT + "," + RIGHT + "," + LENGTH + ")")
    public static native void processSamplesJS(long absTime, @JSByRef(optional = true) float[] left, @JSByRef(optional = true) float[] right, int length);

    // Own the snapshot independently of WASM memory for transfer or bitmap fallback.
    @JSBody(params = {ABS_TIME, PIXELS}, script = CALLBACK_PROCESS_FRAME + "(" + ABS_TIME + "," + PIXELS + ".slice());")
    public static native void processFrameJS(long absTime, Uint8Array pixels);

    @JSBody(params = {WAV, LENGTH}, script = CALLBACK_WHATSSID + "(" + WAV + "," + LENGTH + ")")
    public static native void whatsSidJS(@JSByRef(optional = true) byte[] wav, int length);

    @JSBody(script = "return " + CALLBACK_PREPARE_OSC_BATCH + "()")
    private static native int prepareOscBatchJS();

    @JSBody(params = {DATA, LENGTH}, script = CALLBACK_PROCESS_OSC_BATCH + "(" + DATA + ", " + LENGTH + ")")
    private static native void processOscBatchJS(@JSByRef(optional = true) byte[] data, int length);

    @JSBody(params = {DATA, LENGTH}, script = CALLBACK_PROCESS_AUDIO_TIMING + "(" + DATA + ", " + LENGTH + ")")
    public static native void processAudioTimingJS(@JSByRef(optional = true) byte[] data, int length);

    @JSBody(params = {OPL_TYPE, GENERATON}, script = CALLBACK_PROCESS_OSC_SOURCES + "(" + OPL_TYPE + ", " + GENERATON + ")")
    public static native void processOscSourcesJS(int type, int generation);

    @JSBody(params = {SID_NUM, ABS_TIME, REL_TIME, ADDR, VALUE}, script = CALLBACK_PROCESS_SID_WRITE + "(" + SID_NUM + "," + ABS_TIME + "," + REL_TIME + "," + ADDR + "," + VALUE + ")")
    public static native void processSidWriteJS(int sidNum, long absTime, int relTime, int addr, int value);

    @JSBody(params = {END}, script = CALLBACK_TIMER_END + "(" + END + ")")
    public static native void processTimerEndJS(double end);

    @JSBody(params = {OUTPUT}, script = CALLBACK_PROCESS_PRINTER + "(" + OUTPUT + ")")
    public static native void processPrinterJS(String output);

    @JSBody(params = {DATA, LENGTH}, script = CALLBACK_PROCESS_GEORAM_IMAGE + "(" + DATA + ", " + LENGTH + ")")
    public static native void processGeoRAMImageJS(@JSByRef(optional = true) byte[] data, int length);

}