/* opl-shim.c: the WebAssembly face of Nuked OPL3 (nuked-opl3/, unmodified), as the C port's opl_out.c drives it:
 * one chip at its own rate (49716 Hz), OPL2 registers in bank 0, mono output = the left sample of
 * OPL3_Generate (without the OPL3 enable bit both sides carry the OPL2 mix).
 *
 *   opl_reset()             reset the chip
 *   opl_write(reg, val)     write a register (OPL3_WriteReg; reg 100h.. is bank 1)
 *   opl_generate(n)         n <= OPL_BUF mono samples into the buffer at opl_buffer()
 *   opl_generate_stereo(n)  n <= OPL_BUF stereo frames (left, right interleaved) into the buffer at opl_buffer2():
 *                           an OPL3 played as one (the OPL3 enable bit set, each channel's left/right bits), as the
 *                           car radio's chip does
 *
 * No allocator: the chip and the buffer are static. Built by build-opl.sh (clang --target=wasm32 -nostdlib). */
#include <stddef.h>
#include "nuked-opl3/opl3.h"

#define OPL_RATE 49716
#define OPL_BUF 4096

static opl3_chip chip;
static int16_t buffer[OPL_BUF];
static int16_t buffer2[2 * OPL_BUF];

/* the one libc routine opl3.c calls (OPL3_Reset) */
void *memset(void *s, int c, size_t n)
{
    unsigned char *p = s;
    while (n--) *p++ = (unsigned char)c;
    return s;
}

__attribute__((export_name("opl_reset"))) void opl_reset(void) { OPL3_Reset(&chip, OPL_RATE); }

__attribute__((export_name("opl_write"))) void opl_write(uint32_t reg, uint32_t val)
{
    OPL3_WriteReg(&chip, (uint16_t)reg, (uint8_t)val);
}

__attribute__((export_name("opl_buffer"))) int16_t *opl_buffer(void) { return buffer; }

__attribute__((export_name("opl_generate"))) void opl_generate(uint32_t n)
{
    int16_t s[2];
    if (n > OPL_BUF) n = OPL_BUF;
    for (uint32_t i = 0; i < n; i++) {
        OPL3_Generate(&chip, s);
        buffer[i] = s[0];
    }
}

__attribute__((export_name("opl_buffer2"))) int16_t *opl_buffer2(void) { return buffer2; }

__attribute__((export_name("opl_generate_stereo"))) void opl_generate_stereo(uint32_t n)
{
    if (n > OPL_BUF) n = OPL_BUF;
    for (uint32_t i = 0; i < n; i++) OPL3_Generate(&chip, buffer2 + 2 * i);
}
