JSIDPlay2TeaVMc.java

package client.teavm;

import client.teavm.common.ExportedApi;
import client.teavm.common.IExportedApi;
import libsidplay.common.SamplingRate;

import java.io.*;

import static java.lang.Integer.parseInt;
import static libsidutils.IOUtils.readAllBytes;

/**
 * The main entry point for the TeaVM-based implementation of JSIDPlay2, designed to generate C code.
 *
 * <p>
 * This class provides a command-line interface for SID playback and WAV recording. When compiled to C using TeaVM, it
 * can be run as a standalone executable.
 * </p>
 *
 * <h2>Building</h2>
 * <p>
 * To build the C version, use the following commands:
 * </p>
 *
 * <pre>
 * mvn -Djavafx.platform=linux clean install
 * cd target/classes/server/restful/webapp/teavm/c
 * cmake .
 * make
 * </pre>
 *
 * <h2>Usage</h2>
 * <p>
 * Run the generated executable with the following arguments:
 * </p>
 *
 * <pre>
 * ./build/dist/jsidplay2 &lt;sidFilename&gt; &lt;wavFilename&gt; &lt;recordingTimeInSeconds&gt;
 * </pre>
 *
 * <p>
 * Example:
 * </p>
 *
 * <pre>
 * ./build/dist/jsidplay2 ../sid/Turrican_2-The_Final_Fight.sid ./out.wav 180
 * play ./out.wav
 * </pre>
 */
public final class JSIDPlay2TeaVMc {

    private static final String[] DEBUG_ARGS = new String[]{"--debug", "false"};

    //
    // Exports
    //

    public static void main(String[] args) throws IOException {
        if (args.length < 3) {
            System.err.println("Missing arguments: <sidFilename> <wavFilename> <recordingTimeInSeconds>");
        } else {
            File tuneFile = new File(args[0]);
            File outFile = new File(args[1]);
            int seconds = parseInt(args[2]);

            try (InputStream is = new FileInputStream(tuneFile);
                 DataOutputStream os = new DataOutputStream(new FileOutputStream(outFile))) {
                SamplingRate samplingRate = SamplingRate.MEDIUM;
                int frequency = samplingRate.getFrequency();
                int numSamples = seconds * frequency;

                IExportedApi jsidplay2 = new ExportedApi(new ImportedApiWav(os, frequency, numSamples), DEBUG_ARGS);
                jsidplay2.bufferSize(65536);
                jsidplay2.audioBufferSize(16384);
                jsidplay2.samplingRate(samplingRate);
                jsidplay2.whatsSID(false, 0, 0, 0, 0);
                jsidplay2.open(readAllBytes(is), tuneFile.getName(), 0, 0, false, null, null, null, 0, false, 0, null, null);

                while (os.size() >> 2 < numSamples) {
                    jsidplay2.clock();
                }
            }
        }
    }

}