ImportedApiWav.java

package client.teavm;

import client.teavm.common.IImportedApi;
import libsidplay.components.printer.IPaper.Outputs;

import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import static java.nio.ByteOrder.LITTLE_ENDIAN;

/**
 * WAV file implementation of {@link client.teavm.common.IImportedApi}.
 *
 * <p>
 * This class implements audio output to a {@link java.io.DataOutputStream} in the standard RIFF/WAVE format. It is used
 * for capturing high-quality PCM audio streams during playback.
 * </p>
 *
 * <h2>Audio Output</h2>
 * <ul>
 * <li><b>Format:</b> 16-bit signed PCM, 2 channels (stereo).</li>
 * <li><b>Sampling rate:</b> Configurable during initialization.</li>
 * <li><b>Direct output:</b> Audio samples are written directly to the provided
 * output stream with correct little-endian byte ordering for WAV files.</li>
 * </ul>
 *
 * <h2>Limitations</h2>
 * <p>
 * This implementation only supports audio sample processing. Other
 * functionality like video frame, oscilloscope, and printer output are
 * ignored.
 * </p>
 */
public class ImportedApiWav implements IImportedApi {

    private final DataOutputStream out;

    public ImportedApiWav(DataOutputStream out, int sampleRate, int numSamples) {
        try {
            this.out = out;
            int numChannels = 2;
            int bitsPerSample = 16;
            int byteRate = sampleRate * numChannels * bitsPerSample / 8;
            int blockAlign = numChannels * bitsPerSample / 8;
            int dataSize = numSamples * blockAlign;

            // RIFF header
            out.writeBytes("RIFF");
            out.writeInt(Integer.reverseBytes(36 + dataSize)); // Chunk size
            out.writeBytes("WAVE");

            // fmt subchunk
            out.writeBytes("fmt ");
            out.writeInt(Integer.reverseBytes(16)); // Subchunk1Size (16 for PCM)
            out.writeShort(Short.reverseBytes((short) 1)); // AudioFormat (1 = PCM)
            out.writeShort(Short.reverseBytes((short) numChannels));
            out.writeInt(Integer.reverseBytes(sampleRate));
            out.writeInt(Integer.reverseBytes(byteRate));
            out.writeShort(Short.reverseBytes((short) blockAlign));
            out.writeShort(Short.reverseBytes((short) bitsPerSample));

            // data subchunk
            out.writeBytes("data");
            out.writeInt(Integer.reverseBytes(dataSize));
        } catch (final IOException e) {
            throw new RuntimeException("Error writing WAV audio stream", e);
        }

    }

    @Override
    public ByteBuffer initSampleBuffer(int chunkFrames, int channels) {
        return ByteBuffer.allocate(chunkFrames * Short.BYTES * channels).order(LITTLE_ENDIAN);
    }

    @Override
    public ByteBuffer initFrameBuffer(int maxWidth, int maxHeight) {
        // Only required for video output!
        return null;
    }

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

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

    @Override
    public ByteBuffer initWhatsSidBuffer(int wavLength) {
        // Only required for WhatsSid!
        return null;
    }

    @Override
    public void processSamples(long absTime, ByteBuffer sampleBuffer, float[] lookupTable) {
        try {
            sampleBuffer.flip();
            int remaining = sampleBuffer.remaining() >> 2;
            for (int i = 0; i < remaining; i++) {
                out.writeShort(Short.reverseBytes(sampleBuffer.getShort()));
                out.writeShort(Short.reverseBytes(sampleBuffer.getShort()));
            }
        } catch (final IOException e) {
            throw new RuntimeException("Error writing WAV audio stream", e);
        }
    }

    @Override
    public void prepareFrame(ByteBuffer pixels) {
    }

    @Override
    public void processFrame(long absTime, ByteBuffer pixels) {
    }

    @Override
    public void whatsSid(ByteBuffer whatsSidBuffer) {
    }

    @Override
    public void processOscBatch(ByteBuffer batch, int slot) {
    }

    @Override
    public void processAudioTiming(ByteBuffer timing) {
    }

    @Override
    public void processOscSources(int oplType, int generation) {
    }

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

    @Override
    public void processTimerEnd(double end) {
    }

    @Override
    public void processPrinter(Outputs output) {
    }

    @Override
    public void processGeoRAMImage(byte[] contents) {
    }

}