/* Nuked OPL3
 *
 * Copyright (C) 2013-2020 Nuke.YKT
 * Copyright (C) 2026 Tony Gies (Nuked-OPL3-fast modifications)
 *
 * This file is part of Nuked OPL3.
 *
 * Nuked OPL3 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 2.1
 * of the License, or (at your option) any later version.
 *
 * Nuked OPL3 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Nuked OPL3. If not, see <https://www.gnu.org/licenses/>.
 *
 *  Nuked OPL3 emulator.
 *  Thanks:
 *      MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh):
 *          Feedback and Rhythm part calculation information.
 *      forums.submarine.org.uk(carbon14, opl3):
 *          Tremolo and phase generator calculation information.
 *      OPLx decapsulated(Matthew Gambrell, Olli Niemitalo):
 *          OPL2 ROMs.
 *      siliconpr0n.org(John McMaster, digshadow):
 *          YMF262 and VRC VII decaps and die shots.
 *
 * Upstream version: 1.8 (commit cfedb09)
 * Fork version:    1.8-fast.3
 * Fork home:       https://github.com/tgies/Nuked-OPL3-fast
 *
 * Nuked-OPL3-fast is a bit-exact performance-optimized fork of Nuked-OPL3.
 * Audio output is identical to upstream for the same register stream.
 *
 * Modifications vs. upstream:
 *
 *   - Replaced 8 runtime waveform math functions with a unified 8x1024
 *     logsin lookup table (logsin_wf, in nukedopl_wf_rom.h). With
 *     OPL_WF_TABLE_RUNTIME=1 the table is instead built from the base
 *     logsinrom[256] at the first OPL3_Reset and nukedopl_wf_rom.h is not used.
 *   - Pre-shifted the exprom table at compile time to eliminate a runtime
 *     shift in OPL3_SlotGenerate.
 *   - Hoisted per-sample envelope rate resolution out of OPL3_EnvelopeCalc
 *     into OPL3_EnvelopeUpdateRate (eg_rate_hi[4], eg_rate_lo[4]).
 *   - Added write-time caches on opl3_slot: eg_tl_ksl (TL + KSL sum),
 *     eg_ks (envelope key-scale shift), pg_inc (non-vibrato phase
 *     increment).
 *   - Added fast paths in OPL3_ProcessSlot for fully-attenuated key-off
 *     non-rhythm slots, permanently-dead uninitialized slots, and
 *     sustain-with-rate-zero slots.
 *   - Added OPL3_SlotGenerateSilent: when eg_out >= 0x180 the exprom
 *     result is provably zero, so output reduces to the waveform sign bit.
 *     Used by the key-off fast path.
 *   - Unrolled both 18-channel mix loops in OPL3_Generate4Ch using a
 *     per-channel out_cnt, skipping dummy reads for muted/2-op voices.
 *   - All 36 slots are processed (channel-grouped modulator/carrier pairs,
 *     with channel->fb loaded once per pair) before either mix pass; the
 *     CHANNELSAMPLEDELAY snapshots come from per-channel out_left/out_right
 *     pointer lists that read delayed slots through prout, and the right
 *     mix is its own function (OPL3_MixRight).
 *   - Fused the rhythm-mode special cases in OPL3_PhaseGenerate into a
 *     single switch indexed by slot_num for jump-table dispatch.
 *   - Reordered opl3_slot to put hot per-sample fields in the first cache
 *     line; struct size reduced from 96 to 88 bytes.
 *   - Per-slot pg_inc_vib[8] (phase increment per vibrato position) replaces
 *     the per-sample vibrato recomputation; rebuilt on the writes that affect
 *     it (f_num/block/mult/vibshift).
 *   - Hoisted the noise LFSR out of slot processing into a word-parallel
 *     36-step advance at the top of OPL3_Generate4Ch.
 *   - Minor: __builtin_ctz for the envelope timer on GCC/Clang with a
 *     portable fallback; replaced the tremolo-position modulo with an
 *     explicit wrap.
 *   - Compile-time rhythm specialization: OPL3_ProcessSlot and
 *     OPL3_PhaseGenerate are cloned on a maybe_rhythm flag; only channels
 *     7 and 8 (slots 13/16/17) take the rhythm-aware clone; every other
 *     channel's clone omits the slot_num checks and the rhythm switch.
 *   - Mix-eligibility lists: the per-sample mix passes iterate precomputed
 *     lists of channels with active outputs routed to that side, rebuilt
 *     (mix_dirty) only when register writes change routing or algorithms.
 *   - Dormant-slot generation gate: a slot proven inert (fully attenuated,
 *     key off, zero phase/output state, mod/trem frozen) is tagged with the
 *     chip's write generation and skipped with a single compare per sample
 *     until the next register write.
 *   - Compatibility switches OPL_COMPAT_OLD_EG (pre-2024 envelope stepping)
 *     and OPL_COMPAT_DEFERRED_4OP_ALG (pre-Nov-2022 4-op routing update),
 *     both default-off; see opl3.h.
 */

// Synced from Nuked-OPL3-fast https://github.com/tgies/Nuked-OPL3-fast @ 5d30ee9
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nukedopl.h"

#if OPL_WF_TABLE_RUNTIME

/* Base logsin quarter-wave table from upstream Nuked-OPL3. logsin_wf is
 * derived from it at the first OPL3_Reset and holds the same data as
 * nukedopl_wf_rom.h (gen_logsin.py documents the derivation). */
static const uint16_t logsinrom[256] = {
    0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471,
    0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365,
    0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd,
    0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261,
    0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f,
    0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd,
    0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195,
    0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166,
    0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c,
    0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118,
    0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8,
    0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db,
    0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1,
    0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9,
    0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094,
    0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081,
    0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070,
    0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060,
    0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052,
    0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045,
    0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039,
    0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f,
    0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026,
    0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e,
    0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017,
    0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011,
    0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c,
    0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007,
    0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004,
    0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002,
    0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001,
    0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000
};

static uint16_t logsin_wf[8][1024];
static uint8_t logsin_wf_built = 0;

static void OPL3_BuildWfTable(void)
{
    uint32_t p;
    for (p = 0; p < 1024; p++)
    {
        uint16_t c2 = (p & 0x100) ? logsinrom[(p & 0xff) ^ 0xff]
                                  : logsinrom[p & 0xff];
        uint16_t c6 = (p & 0x200) ? 0x8000 : 0;
        uint16_t c5 = c6 ? 0x1000
                         : ((p & 0x80) ? logsinrom[((p ^ 0xff) << 1) & 0xff]
                                       : logsinrom[(p << 1) & 0xff]);
        logsin_wf[0][p] = c6 | c2;
        logsin_wf[1][p] = c6 ? 0x1000 : c2;
        logsin_wf[2][p] = c2;
        logsin_wf[3][p] = (p & 0x100) ? 0x1000 : logsinrom[p & 0xff];
        logsin_wf[4][p] = (uint16_t)((((p & 0x300) == 0x100) ? 0x8000 : 0) | c5);
        logsin_wf[5][p] = c5;
        logsin_wf[6][p] = c6;
        logsin_wf[7][p] = (uint16_t)(c6 | ((c6 ? ((p & 0x1ff) ^ 0x1ff) : p) << 3));
    }
    logsin_wf_built = 1;
}

#else /* OPL_WF_TABLE_RUNTIME */
#include "nukedopl_wf_rom.h"
#endif

#if OPL_ENABLE_STEREOEXT && !defined OPL_SIN
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES 1
#endif
#include <math.h>
/* input: [0, 256), output: [0, 65536] */
#define OPL_SIN(x) ((int32_t)(sin((x) * M_PI / 512.0) * 65536.0))
#endif

#define RSM_FRAC    10

/* Channel types */

enum {
    ch_2op = 0,
    ch_4op = 1,
    ch_4op2 = 2,
    ch_drum = 3
};

/* Envelope key types */

enum {
    egk_norm = 0x01,
    egk_drum = 0x02
};

/*
    exp table
*/

static const uint16_t exprom[256] = {
    0xff4, 0xfea, 0xfde, 0xfd4, 0xfc8, 0xfbe, 0xfb4, 0xfa8,
    0xf9e, 0xf92, 0xf88, 0xf7e, 0xf72, 0xf68, 0xf5c, 0xf52,
    0xf48, 0xf3e, 0xf32, 0xf28, 0xf1e, 0xf14, 0xf08, 0xefe,
    0xef4, 0xeea, 0xee0, 0xed4, 0xeca, 0xec0, 0xeb6, 0xeac,
    0xea2, 0xe98, 0xe8e, 0xe84, 0xe7a, 0xe70, 0xe66, 0xe5c,
    0xe52, 0xe48, 0xe3e, 0xe34, 0xe2a, 0xe20, 0xe16, 0xe0c,
    0xe04, 0xdfa, 0xdf0, 0xde6, 0xddc, 0xdd2, 0xdca, 0xdc0,
    0xdb6, 0xdac, 0xda4, 0xd9a, 0xd90, 0xd88, 0xd7e, 0xd74,
    0xd6a, 0xd62, 0xd58, 0xd50, 0xd46, 0xd3c, 0xd34, 0xd2a,
    0xd22, 0xd18, 0xd10, 0xd06, 0xcfe, 0xcf4, 0xcec, 0xce2,
    0xcda, 0xcd0, 0xcc8, 0xcbe, 0xcb6, 0xcae, 0xca4, 0xc9c,
    0xc92, 0xc8a, 0xc82, 0xc78, 0xc70, 0xc68, 0xc60, 0xc56,
    0xc4e, 0xc46, 0xc3c, 0xc34, 0xc2c, 0xc24, 0xc1c, 0xc12,
    0xc0a, 0xc02, 0xbfa, 0xbf2, 0xbea, 0xbe0, 0xbd8, 0xbd0,
    0xbc8, 0xbc0, 0xbb8, 0xbb0, 0xba8, 0xba0, 0xb98, 0xb90,
    0xb88, 0xb80, 0xb78, 0xb70, 0xb68, 0xb60, 0xb58, 0xb50,
    0xb48, 0xb40, 0xb38, 0xb32, 0xb2a, 0xb22, 0xb1a, 0xb12,
    0xb0a, 0xb02, 0xafc, 0xaf4, 0xaec, 0xae4, 0xade, 0xad6,
    0xace, 0xac6, 0xac0, 0xab8, 0xab0, 0xaa8, 0xaa2, 0xa9a,
    0xa92, 0xa8c, 0xa84, 0xa7c, 0xa76, 0xa6e, 0xa68, 0xa60,
    0xa58, 0xa52, 0xa4a, 0xa44, 0xa3c, 0xa36, 0xa2e, 0xa28,
    0xa20, 0xa18, 0xa12, 0xa0c, 0xa04, 0x9fe, 0x9f6, 0x9f0,
    0x9e8, 0x9e2, 0x9da, 0x9d4, 0x9ce, 0x9c6, 0x9c0, 0x9b8,
    0x9b2, 0x9ac, 0x9a4, 0x99e, 0x998, 0x990, 0x98a, 0x984,
    0x97c, 0x976, 0x970, 0x96a, 0x962, 0x95c, 0x956, 0x950,
    0x948, 0x942, 0x93c, 0x936, 0x930, 0x928, 0x922, 0x91c,
    0x916, 0x910, 0x90a, 0x904, 0x8fc, 0x8f6, 0x8f0, 0x8ea,
    0x8e4, 0x8de, 0x8d8, 0x8d2, 0x8cc, 0x8c6, 0x8c0, 0x8ba,
    0x8b4, 0x8ae, 0x8a8, 0x8a2, 0x89c, 0x896, 0x890, 0x88a,
    0x884, 0x87e, 0x878, 0x872, 0x86c, 0x866, 0x860, 0x85a,
    0x854, 0x850, 0x84a, 0x844, 0x83e, 0x838, 0x832, 0x82c,
    0x828, 0x822, 0x81c, 0x816, 0x810, 0x80c, 0x806, 0x800,
};

/*
    freq mult table multiplied by 2

    1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15
*/

static const uint8_t mt[16] = {
    1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30
};

/*
    ksl table
*/

static const uint8_t kslrom[16] = {
    0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64
};

static const uint8_t kslshift[4] = {
    8, 1, 2, 0
};

/*
    envelope generator constants
*/

static const uint8_t eg_incstep[4][4] = {
    { 0, 0, 0, 0 },
    { 1, 0, 0, 0 },
    { 1, 0, 1, 0 },
    { 1, 1, 1, 0 }
};

/*
    address decoding
*/

static const int8_t ad_slot[0x20] = {
    0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1,
    12, 13, 14, 15, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};

static const uint8_t ch_slot[18] = {
    0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32
};

#if OPL_ENABLE_STEREOEXT
/*
    stereo extension panning table
*/

static int32_t panpot_lut[256];
static uint8_t panpot_lut_build = 0;
#endif

/*
    Envelope generator
*/

enum envelope_gen_num
{
    envelope_gen_num_attack = 0,
    envelope_gen_num_decay = 1,
    envelope_gen_num_sustain = 2,
    envelope_gen_num_release = 3
};

static void OPL3_EnvelopeUpdateKSL(opl3_slot *slot)
{
    int16_t ksl = (kslrom[slot->channel->f_num >> 6u] << 2)
               - ((0x08 - slot->channel->block) << 5);
    if (ksl < 0)
    {
        ksl = 0;
    }
    slot->eg_ksl = (uint8_t)ksl;
    /* Refresh the cached (reg_tl << 2) + (eg_ksl >> kslshift[reg_ksl])
     * sum used by OPL3_EnvelopeCalc. Both reg_tl/reg_ksl-driven changes
     * (via SlotWrite40, which calls this function) and eg_ksl-driven
     * changes (f_num/block updates via Channel{A0,B0}) flow through
     * here, so this covers all dirty cases. */
    slot->eg_tl_ksl = (uint16_t)((slot->reg_tl << 2)
                              + (slot->eg_ksl >> kslshift[slot->reg_ksl]));
}

static void OPL3_EnvelopeUpdateRate(opl3_slot *slot)
{
    uint8_t ii;

    slot->eg_ks = slot->channel->ksv >> ((slot->reg_ksr ^ 1) << 1);
    for (ii = 0; ii < 4; ii++)
    {
        uint8_t rate = slot->eg_ks + (slot->eg_rates[ii] << 2);
        uint8_t rate_hi = rate >> 2;
        if (rate_hi & 0x10)
        {
            rate_hi = 0x0f;
        }
        slot->eg_rate_hi[ii] = rate_hi;
        slot->eg_rate_lo[ii] = rate & 0x03;
    }
}

static void OPL3_EnvelopeCalc(opl3_slot *slot)
{
    uint8_t nonzero;
    uint8_t rate_hi;
    uint8_t rate_lo;
    uint8_t reg_rate = 0;
    uint8_t eg_shift, shift;
    uint16_t eg_rout;
    int16_t eg_inc;
    uint8_t eg_off;
    uint8_t reset = 0;

    slot->eg_out = slot->eg_rout + slot->eg_tl_ksl + *slot->trem;
    if (slot->key && slot->eg_gen == envelope_gen_num_release)
    {
        reset = 1;
        reg_rate = slot->eg_rates[0];
    }
    else
    {
        reg_rate = slot->eg_rates[slot->eg_gen];
    }
    slot->pg_reset = reset;
    nonzero = (reg_rate != 0);
    if (reset)
    {
        rate_hi = slot->eg_rate_hi[0];
        rate_lo = slot->eg_rate_lo[0];
    }
    else
    {
        rate_hi = slot->eg_rate_hi[slot->eg_gen];
        rate_lo = slot->eg_rate_lo[slot->eg_gen];
    }
    eg_shift = rate_hi + slot->chip->eg_add;
    shift = 0;
    if (nonzero)
    {
        if (rate_hi < 12)
        {
            if (slot->chip->eg_state)
            {
                switch (eg_shift)
                {
                case 12:
                    shift = 1;
                    break;
                case 13:
                    shift = (rate_lo >> 1) & 0x01;
                    break;
                case 14:
                    shift = rate_lo & 0x01;
                    break;
                default:
                    break;
                }
            }
        }
        else
        {
#if OPL_COMPAT_OLD_EG
            shift = (rate_hi & 0x03) + eg_incstep[rate_lo][slot->chip->timer & 0x03u];
#else
            shift = (rate_hi & 0x03) + eg_incstep[rate_lo][slot->chip->eg_timer_lo];
#endif
            if (shift & 0x04)
            {
                shift = 0x03;
            }
            if (!shift)
            {
                shift = slot->chip->eg_state;
            }
        }
    }
    eg_rout = slot->eg_rout;
    eg_inc = 0;
    eg_off = 0;
    /* Instant attack */
    if (reset && rate_hi == 0x0f)
    {
        eg_rout = 0x00;
    }
    /* Envelope off */
    if ((slot->eg_rout & 0x1f8) == 0x1f8)
    {
        eg_off = 1;
    }
    if (slot->eg_gen != envelope_gen_num_attack && !reset && eg_off)
    {
        eg_rout = 0x1ff;
    }
    switch (slot->eg_gen)
    {
    case envelope_gen_num_attack:
        if (!slot->eg_rout)
        {
            slot->eg_gen = envelope_gen_num_decay;
        }
        else if (slot->key && shift > 0 && rate_hi != 0x0f)
        {
            eg_inc = ~slot->eg_rout >> (4 - shift);
        }
        break;
    case envelope_gen_num_decay:
        if ((slot->eg_rout >> 4) == slot->reg_sl)
        {
            slot->eg_gen = envelope_gen_num_sustain;
        }
        else if (!eg_off && !reset && shift > 0)
        {
            eg_inc = 1 << (shift - 1);
        }
        break;
    case envelope_gen_num_sustain:
    case envelope_gen_num_release:
        if (!eg_off && !reset && shift > 0)
        {
            eg_inc = 1 << (shift - 1);
        }
        break;
    }
    slot->eg_rout = (eg_rout + eg_inc) & 0x1ff;
    /* Key off */
    if (reset)
    {
        slot->eg_gen = envelope_gen_num_attack;
    }
    if (!slot->key)
    {
        slot->eg_gen = envelope_gen_num_release;
    }
}

static void OPL3_EnvelopeKeyOn(opl3_slot *slot, uint8_t type)
{
    slot->key |= type;
}

static void OPL3_EnvelopeKeyOff(opl3_slot *slot, uint8_t type)
{
    slot->key &= ~type;
}

/*
    Phase Generator
*/

static void OPL3_PhaseUpdateInc(opl3_slot *slot)
{
    uint32_t basefreq = ((uint32_t)slot->channel->f_num << slot->channel->block) >> 1;
    uint8_t vibpos;
    slot->pg_inc = (basefreq * mt[slot->reg_mult]) >> 1;
    /* Per-vibpos increments (exact replica of the vibrato f_num adjustment
     * the phase generator applies per sample), so vib slots resolve their
     * increment with one load. Rebuilt when vibshift changes */
    for (vibpos = 0; vibpos < 8; vibpos++)
    {
        uint16_t f_num = slot->channel->f_num;
        int8_t range = (f_num >> 7) & 7;
        if (!(vibpos & 3))
        {
            range = 0;
        }
        else if (vibpos & 1)
        {
            range >>= 1;
        }
        range >>= slot->chip->vibshift;
        if (vibpos & 4)
        {
            range = -range;
        }
        f_num += range;
        slot->pg_inc_vib[vibpos] =
            ((((uint32_t)f_num << slot->channel->block) >> 1) * mt[slot->reg_mult]) >> 1;
    }
}

/* maybe_rhythm is a compile-time constant at every call site: channels 7 and
 * 8 are the only ones whose slots (13, 16, 17) have rhythm-special phase
 * handling. Every other channel's clone omits the switch. */
static inline void OPL3_PhaseGenerateImpl(opl3_slot *slot, int maybe_rhythm)
{
    opl3_chip *chip;
    uint32_t phaseinc;
    uint8_t rm_xor;
    uint16_t phase;

    chip = slot->chip;
    if (slot->reg_vib)
    {
        phaseinc = slot->pg_inc_vib[chip->vibpos];
    }
    else
    {
        phaseinc = slot->pg_inc;
    }
    phase = (uint16_t)(slot->pg_phase >> 9);
    if (slot->pg_reset)
    {
        slot->pg_phase = 0;
    }
    slot->pg_phase += phaseinc;
    /* Rhythm mode: dispatch on slot_num via a single switch so non-rhythm
     * slots (33 of 36) hit the default case and skip everything. The
     * fused switch also lets gcc emit a jump table instead of branches. */
    slot->pg_phase_out = phase;
    if (!maybe_rhythm)
    {
        return;
    }
    switch (slot->slot_num)
    {
    case 13: /* hh */
        chip->rm_hh_bit2 = (phase >> 2) & 1;
        chip->rm_hh_bit3 = (phase >> 3) & 1;
        chip->rm_hh_bit7 = (phase >> 7) & 1;
        chip->rm_hh_bit8 = (phase >> 8) & 1;
        if (chip->rhy & 0x20)
        {
            rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7)
                   | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5)
                   | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5);
            slot->pg_phase_out = rm_xor << 9;
            if (rm_xor ^ (chip->noise_hh & 1))
            {
                slot->pg_phase_out |= 0xd0;
            }
            else
            {
                slot->pg_phase_out |= 0x34;
            }
        }
        break;
    case 16: /* sd */
        if (chip->rhy & 0x20)
        {
            slot->pg_phase_out = (chip->rm_hh_bit8 << 9)
                               | ((chip->rm_hh_bit8 ^ (chip->noise_sd & 1)) << 8);
        }
        break;
    case 17: /* tc */
        if (chip->rhy & 0x20)
        {
            chip->rm_tc_bit3 = (phase >> 3) & 1;
            chip->rm_tc_bit5 = (phase >> 5) & 1;
            rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7)
                   | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5)
                   | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5);
            slot->pg_phase_out = (rm_xor << 9) | 0x80;
        }
        break;
    default:
        break;
    }
}

/*
    Slot
*/

static void OPL3_SlotWrite20(opl3_slot *slot, uint8_t data)
{
    if ((data >> 7) & 0x01)
    {
        slot->trem = &slot->chip->tremolo;
    }
    else
    {
        slot->trem = (uint8_t*)&slot->chip->zeromod;
    }
    slot->reg_vib = (data >> 6) & 0x01;
    slot->reg_type = (data >> 5) & 0x01;
    slot->eg_rates[2] = slot->reg_type ? 0 : slot->reg_rr;
    slot->reg_ksr = (data >> 4) & 0x01;
    slot->reg_mult = data & 0x0f;
    OPL3_EnvelopeUpdateRate(slot);
    OPL3_PhaseUpdateInc(slot);
}

static void OPL3_SlotWrite40(opl3_slot *slot, uint8_t data)
{
    slot->reg_ksl = (data >> 6) & 0x03;
    slot->reg_tl = data & 0x3f;
    OPL3_EnvelopeUpdateKSL(slot);
}

static void OPL3_SlotWrite60(opl3_slot *slot, uint8_t data)
{
    slot->reg_ar = (data >> 4) & 0x0f;
    slot->reg_dr = data & 0x0f;
    slot->eg_rates[0] = slot->reg_ar;
    slot->eg_rates[1] = slot->reg_dr;
    OPL3_EnvelopeUpdateRate(slot);
}

static void OPL3_SlotWrite80(opl3_slot *slot, uint8_t data)
{
    slot->reg_sl = (data >> 4) & 0x0f;
    if (slot->reg_sl == 0x0f)
    {
        slot->reg_sl = 0x1f;
    }
    slot->reg_rr = data & 0x0f;
    slot->eg_rates[2] = slot->reg_type ? 0 : slot->reg_rr;
    slot->eg_rates[3] = slot->reg_rr;
    OPL3_EnvelopeUpdateRate(slot);
}

static void OPL3_SlotWriteE0(opl3_slot *slot, uint8_t data)
{
    slot->reg_wf = data & 0x07;
    if (slot->chip->newm == 0x00)
    {
        slot->reg_wf &= 0x03;
    }
}

static inline void OPL3_SlotGenerate(opl3_slot *slot)
{
    uint16_t phase = slot->pg_phase_out + *slot->mod;
    uint16_t envelope = slot->eg_out;
    uint16_t wf_data = logsin_wf[slot->reg_wf][phase & 0x3ff];
    uint16_t neg = (uint16_t)(((int16_t)wf_data) >> 15);
    uint32_t level = (wf_data & 0x7fff) + (envelope << 3);
    if (level > 0x1fff)
    {
        level = 0x1fff;
    }
    slot->out = ((exprom[level & 0xffu] >> (level >> 8)) ^ neg);
}

/* Silent-regime variant: when the caller has proven eg_out >= 0x180, the
 * exprom lookup always reads through to zero (max exprom value 0xff4 >> 12
 * = 0), so the final out reduces to just the sign bit of wf_data. Skips a
 * load, an add, a clamp, a shift, and a xor. */
static inline void OPL3_SlotGenerateSilent(opl3_slot *slot)
{
    uint16_t phase = slot->pg_phase_out + *slot->mod;
    uint16_t wf_data = logsin_wf[slot->reg_wf][phase & 0x3ff];
    slot->out = (int16_t)wf_data >> 15;
}

/* fb is the slot's channel->fb, loaded once per channel pair by the caller
 * (slot processing cannot change it, only register writes can). */
static inline void OPL3_SlotCalcFB(opl3_slot *slot, uint8_t fb)
{
    if (fb != 0x00)
    {
        slot->fbmod = (slot->prout + slot->out) >> (0x09 - fb);
    }
    else
    {
        slot->fbmod = 0;
    }
    slot->prout = slot->out;
}

/*
    Channel
*/

static void OPL3_ChannelSetupAlg(opl3_channel *channel);

static void OPL3_ChannelUpdateRhythm(opl3_chip *chip, uint8_t data)
{
    opl3_channel *channel6;
    opl3_channel *channel7;
    opl3_channel *channel8;
    uint8_t chnum;

    chip->rhy = data & 0x3f;
    if (chip->rhy & 0x20)
    {
        channel6 = &chip->channel[6];
        channel7 = &chip->channel[7];
        channel8 = &chip->channel[8];
        channel6->out[0] = &channel6->slotz[1]->out;
        channel6->out[1] = &channel6->slotz[1]->out;
        channel6->out[2] = &chip->zeromod;
        channel6->out[3] = &chip->zeromod;
        channel6->out_cnt = 2;
        channel7->out[0] = &channel7->slotz[0]->out;
        channel7->out[1] = &channel7->slotz[0]->out;
        channel7->out[2] = &channel7->slotz[1]->out;
        channel7->out[3] = &channel7->slotz[1]->out;
        channel7->out_cnt = 4;
        channel8->out[0] = &channel8->slotz[0]->out;
        channel8->out[1] = &channel8->slotz[0]->out;
        channel8->out[2] = &channel8->slotz[1]->out;
        channel8->out[3] = &channel8->slotz[1]->out;
        channel8->out_cnt = 4;
        for (chnum = 6; chnum < 9; chnum++)
        {
            chip->channel[chnum].chtype = ch_drum;
        }
        OPL3_ChannelSetupAlg(channel6);
        OPL3_ChannelSetupAlg(channel7);
        OPL3_ChannelSetupAlg(channel8);
        /* hh */
        if (chip->rhy & 0x01)
        {
            OPL3_EnvelopeKeyOn(channel7->slotz[0], egk_drum);
        }
        else
        {
            OPL3_EnvelopeKeyOff(channel7->slotz[0], egk_drum);
        }
        /* tc */
        if (chip->rhy & 0x02)
        {
            OPL3_EnvelopeKeyOn(channel8->slotz[1], egk_drum);
        }
        else
        {
            OPL3_EnvelopeKeyOff(channel8->slotz[1], egk_drum);
        }
        /* tom */
        if (chip->rhy & 0x04)
        {
            OPL3_EnvelopeKeyOn(channel8->slotz[0], egk_drum);
        }
        else
        {
            OPL3_EnvelopeKeyOff(channel8->slotz[0], egk_drum);
        }
        /* sd */
        if (chip->rhy & 0x08)
        {
            OPL3_EnvelopeKeyOn(channel7->slotz[1], egk_drum);
        }
        else
        {
            OPL3_EnvelopeKeyOff(channel7->slotz[1], egk_drum);
        }
        /* bd */
        if (chip->rhy & 0x10)
        {
            OPL3_EnvelopeKeyOn(channel6->slotz[0], egk_drum);
            OPL3_EnvelopeKeyOn(channel6->slotz[1], egk_drum);
        }
        else
        {
            OPL3_EnvelopeKeyOff(channel6->slotz[0], egk_drum);
            OPL3_EnvelopeKeyOff(channel6->slotz[1], egk_drum);
        }
    }
    else
    {
        for (chnum = 6; chnum < 9; chnum++)
        {
            chip->channel[chnum].chtype = ch_2op;
            OPL3_ChannelSetupAlg(&chip->channel[chnum]);
            OPL3_EnvelopeKeyOff(chip->channel[chnum].slotz[0], egk_drum);
            OPL3_EnvelopeKeyOff(chip->channel[chnum].slotz[1], egk_drum);
        }
    }
}

static void OPL3_ChannelWriteA0(opl3_channel *channel, uint8_t data)
{
    if (channel->chip->newm && channel->chtype == ch_4op2)
    {
        return;
    }
    channel->f_num = (channel->f_num & 0x300) | data;
    channel->ksv = (channel->block << 1)
                 | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01);
    OPL3_EnvelopeUpdateKSL(channel->slotz[0]);
    OPL3_EnvelopeUpdateKSL(channel->slotz[1]);
    OPL3_EnvelopeUpdateRate(channel->slotz[0]);
    OPL3_EnvelopeUpdateRate(channel->slotz[1]);
    OPL3_PhaseUpdateInc(channel->slotz[0]);
    OPL3_PhaseUpdateInc(channel->slotz[1]);
    if (channel->chip->newm && channel->chtype == ch_4op)
    {
        channel->pair->f_num = channel->f_num;
        channel->pair->ksv = channel->ksv;
        OPL3_EnvelopeUpdateKSL(channel->pair->slotz[0]);
        OPL3_EnvelopeUpdateKSL(channel->pair->slotz[1]);
        OPL3_EnvelopeUpdateRate(channel->pair->slotz[0]);
        OPL3_EnvelopeUpdateRate(channel->pair->slotz[1]);
        OPL3_PhaseUpdateInc(channel->pair->slotz[0]);
        OPL3_PhaseUpdateInc(channel->pair->slotz[1]);
    }
}

static void OPL3_ChannelWriteB0(opl3_channel *channel, uint8_t data)
{
    if (channel->chip->newm && channel->chtype == ch_4op2)
    {
        return;
    }
    channel->f_num = (channel->f_num & 0xff) | ((data & 0x03) << 8);
    channel->block = (data >> 2) & 0x07;
    channel->ksv = (channel->block << 1)
                 | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01);
    OPL3_EnvelopeUpdateKSL(channel->slotz[0]);
    OPL3_EnvelopeUpdateKSL(channel->slotz[1]);
    OPL3_EnvelopeUpdateRate(channel->slotz[0]);
    OPL3_EnvelopeUpdateRate(channel->slotz[1]);
    OPL3_PhaseUpdateInc(channel->slotz[0]);
    OPL3_PhaseUpdateInc(channel->slotz[1]);
    if (channel->chip->newm && channel->chtype == ch_4op)
    {
        channel->pair->f_num = channel->f_num;
        channel->pair->block = channel->block;
        channel->pair->ksv = channel->ksv;
        OPL3_EnvelopeUpdateKSL(channel->pair->slotz[0]);
        OPL3_EnvelopeUpdateKSL(channel->pair->slotz[1]);
        OPL3_EnvelopeUpdateRate(channel->pair->slotz[0]);
        OPL3_EnvelopeUpdateRate(channel->pair->slotz[1]);
        OPL3_PhaseUpdateInc(channel->pair->slotz[0]);
        OPL3_PhaseUpdateInc(channel->pair->slotz[1]);
    }
}

static void OPL3_ChannelSetupAlgBody(opl3_channel *channel)
{
    if (channel->chtype == ch_drum)
    {
        if (channel->ch_num == 7 || channel->ch_num == 8)
        {
            channel->slotz[0]->mod = &channel->chip->zeromod;
            channel->slotz[1]->mod = &channel->chip->zeromod;
            return;
        }
        switch (channel->alg & 0x01)
        {
        case 0x00:
            channel->slotz[0]->mod = &channel->slotz[0]->fbmod;
            channel->slotz[1]->mod = &channel->slotz[0]->out;
            break;
        case 0x01:
            channel->slotz[0]->mod = &channel->slotz[0]->fbmod;
            channel->slotz[1]->mod = &channel->chip->zeromod;
            break;
        }
        return;
    }
    if (channel->alg & 0x08)
    {
        return;
    }
    if (channel->alg & 0x04)
    {
        channel->pair->out[0] = &channel->chip->zeromod;
        channel->pair->out[1] = &channel->chip->zeromod;
        channel->pair->out[2] = &channel->chip->zeromod;
        channel->pair->out[3] = &channel->chip->zeromod;
        channel->pair->out_cnt = 0;
        switch (channel->alg & 0x03)
        {
        case 0x00:
            channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod;
            channel->pair->slotz[1]->mod = &channel->pair->slotz[0]->out;
            channel->slotz[0]->mod = &channel->pair->slotz[1]->out;
            channel->slotz[1]->mod = &channel->slotz[0]->out;
            channel->out[0] = &channel->slotz[1]->out;
            channel->out[1] = &channel->chip->zeromod;
            channel->out[2] = &channel->chip->zeromod;
            channel->out[3] = &channel->chip->zeromod;
            channel->out_cnt = 1;
            break;
        case 0x01:
            channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod;
            channel->pair->slotz[1]->mod = &channel->pair->slotz[0]->out;
            channel->slotz[0]->mod = &channel->chip->zeromod;
            channel->slotz[1]->mod = &channel->slotz[0]->out;
            channel->out[0] = &channel->pair->slotz[1]->out;
            channel->out[1] = &channel->slotz[1]->out;
            channel->out[2] = &channel->chip->zeromod;
            channel->out[3] = &channel->chip->zeromod;
            channel->out_cnt = 2;
            break;
        case 0x02:
            channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod;
            channel->pair->slotz[1]->mod = &channel->chip->zeromod;
            channel->slotz[0]->mod = &channel->pair->slotz[1]->out;
            channel->slotz[1]->mod = &channel->slotz[0]->out;
            channel->out[0] = &channel->pair->slotz[0]->out;
            channel->out[1] = &channel->slotz[1]->out;
            channel->out[2] = &channel->chip->zeromod;
            channel->out[3] = &channel->chip->zeromod;
            channel->out_cnt = 2;
            break;
        case 0x03:
            channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod;
            channel->pair->slotz[1]->mod = &channel->chip->zeromod;
            channel->slotz[0]->mod = &channel->pair->slotz[1]->out;
            channel->slotz[1]->mod = &channel->chip->zeromod;
            channel->out[0] = &channel->pair->slotz[0]->out;
            channel->out[1] = &channel->slotz[0]->out;
            channel->out[2] = &channel->slotz[1]->out;
            channel->out[3] = &channel->chip->zeromod;
            channel->out_cnt = 3;
            break;
        }
    }
    else
    {
        switch (channel->alg & 0x01)
        {
        case 0x00:
            channel->slotz[0]->mod = &channel->slotz[0]->fbmod;
            channel->slotz[1]->mod = &channel->slotz[0]->out;
            channel->out[0] = &channel->slotz[1]->out;
            channel->out[1] = &channel->chip->zeromod;
            channel->out[2] = &channel->chip->zeromod;
            channel->out[3] = &channel->chip->zeromod;
            channel->out_cnt = 1;
            break;
        case 0x01:
            channel->slotz[0]->mod = &channel->slotz[0]->fbmod;
            channel->slotz[1]->mod = &channel->chip->zeromod;
            channel->out[0] = &channel->slotz[0]->out;
            channel->out[1] = &channel->slotz[1]->out;
            channel->out[2] = &channel->chip->zeromod;
            channel->out[3] = &channel->chip->zeromod;
            channel->out_cnt = 2;
            break;
        }
    }
}

#if OPL_QUIRK_CHANNELSAMPLEDELAY
/* Rebuild out_left/out_right from out[]: entries pointing at a delayed
 * slot's out (15-35 for the left mix, 33-35 for the right) are redirected to
 * that slot's prout. zeromod entries, and the transient NULLs while
 * OPL3_Reset is wiring channels up, pass through unchanged. */
static void OPL3_ChannelUpdateDelayedOuts(opl3_channel *channel)
{
    opl3_chip *chip = channel->chip;
    uint8_t k;
    for (k = 0; k < 4; k++)
    {
        int16_t *p = channel->out[k];
        int16_t *pl = p;
        int16_t *pr = p;
        if (p != NULL && p != &chip->zeromod)
        {
            /* p is always &chip->slot[sn].out here; recover containing slot */
            opl3_slot *sp = (opl3_slot *)((char *)p - offsetof(opl3_slot, out));
            uint8_t sn = (uint8_t)(sp - &chip->slot[0]);
            if (sn >= 15)
            {
                pl = &chip->slot[sn].prout;
            }
            if (sn >= 33)
            {
                pr = &chip->slot[sn].prout;
            }
        }
        channel->out_left[k] = pl;
        channel->out_right[k] = pr;
    }
}
#endif

/* Every out[] mutation goes through here (directly, or via
 * OPL3_ChannelUpdateRhythm which rewrites out[] before calling this), so the
 * mix pointer lists are rebuilt for the channel and its pair. */
static void OPL3_ChannelSetupAlg(opl3_channel *channel)
{
    OPL3_ChannelSetupAlgBody(channel);
#if OPL_QUIRK_CHANNELSAMPLEDELAY
    OPL3_ChannelUpdateDelayedOuts(channel);
    if (channel->pair)
    {
        OPL3_ChannelUpdateDelayedOuts(channel->pair);
    }
#endif
    channel->chip->mix_dirty = 1;
}

/* Rebuild the per-side lists of mix-eligible channels. A channel is
 * eligible when it has active slot outputs and at least one of the side's
 * two output routes enabled. Skipping an ineligible channel is
 * output-identical: its contribution to that side's mix is zero (both
 * route masks/pans are zero) and accm has no side effects. */
static void OPL3_RebuildMixLists(opl3_chip *chip)
{
    uint8_t ii;
    uint8_t nl = 0;
    uint8_t nr = 0;
    for (ii = 0; ii < 18; ii++)
    {
        opl3_channel *channel = &chip->channel[ii];
        if (!channel->out_cnt)
        {
            continue;
        }
#if OPL_ENABLE_STEREOEXT
        if (channel->leftpan | channel->chc)
        {
            chip->mix_left[nl++] = channel;
        }
        if (channel->rightpan | channel->chd)
        {
            chip->mix_right[nr++] = channel;
        }
#else
        if (channel->cha | channel->chc)
        {
            chip->mix_left[nl++] = channel;
        }
        if (channel->chb | channel->chd)
        {
            chip->mix_right[nr++] = channel;
        }
#endif
    }
    chip->nmix_left = nl;
    chip->nmix_right = nr;
    chip->mix_dirty = 0;
}

static void OPL3_ChannelUpdateAlg(opl3_channel *channel)
{
    channel->alg = channel->con;
    if (channel->chip->newm)
    {
        if (channel->chtype == ch_4op)
        {
            channel->pair->alg = 0x04 | (channel->con << 1) | (channel->pair->con);
            channel->alg = 0x08;
            OPL3_ChannelSetupAlg(channel->pair);
        }
        else if (channel->chtype == ch_4op2)
        {
            channel->alg = 0x04 | (channel->pair->con << 1) | (channel->con);
            channel->pair->alg = 0x08;
            OPL3_ChannelSetupAlg(channel);
        }
        else
        {
            OPL3_ChannelSetupAlg(channel);
        }
    }
    else
    {
        OPL3_ChannelSetupAlg(channel);
    }
}

static void OPL3_ChannelWriteC0(opl3_channel *channel, uint8_t data)
{
    channel->fb = (data & 0x0e) >> 1;
    channel->con = data & 0x01;
    OPL3_ChannelUpdateAlg(channel);
    if (channel->chip->newm)
    {
        channel->cha = ((data >> 4) & 0x01) ? ~0 : 0;
        channel->chb = ((data >> 5) & 0x01) ? ~0 : 0;
        channel->chc = ((data >> 6) & 0x01) ? ~0 : 0;
        channel->chd = ((data >> 7) & 0x01) ? ~0 : 0;
    }
    else
    {
        channel->cha = channel->chb = (uint16_t)~0;
        // TODO: Verify on real chip if DAC2 output is disabled in compat mode
        channel->chc = channel->chd = 0;
    }
#if OPL_ENABLE_STEREOEXT
    if (!channel->chip->stereoext)
    {
        channel->leftpan = channel->cha << 16;
        channel->rightpan = channel->chb << 16;
    }
#endif
}

#if OPL_ENABLE_STEREOEXT
static void OPL3_ChannelWriteD0(opl3_channel* channel, uint8_t data)
{
    if (channel->chip->stereoext)
    {
        channel->leftpan = panpot_lut[data ^ 0xffu];
        channel->rightpan = panpot_lut[data];
        channel->chip->mix_dirty = 1;
    }
}
#endif

static void OPL3_ChannelKeyOn(opl3_channel *channel)
{
    if (channel->chip->newm)
    {
        if (channel->chtype == ch_4op)
        {
            OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm);
            OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm);
            OPL3_EnvelopeKeyOn(channel->pair->slotz[0], egk_norm);
            OPL3_EnvelopeKeyOn(channel->pair->slotz[1], egk_norm);
        }
        else if (channel->chtype == ch_2op || channel->chtype == ch_drum)
        {
            OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm);
            OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm);
        }
    }
    else
    {
        OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm);
        OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm);
    }
}

static void OPL3_ChannelKeyOff(opl3_channel *channel)
{
    if (channel->chip->newm)
    {
        if (channel->chtype == ch_4op)
        {
            OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm);
            OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm);
            OPL3_EnvelopeKeyOff(channel->pair->slotz[0], egk_norm);
            OPL3_EnvelopeKeyOff(channel->pair->slotz[1], egk_norm);
        }
        else if (channel->chtype == ch_2op || channel->chtype == ch_drum)
        {
            OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm);
            OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm);
        }
    }
    else
    {
        OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm);
        OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm);
    }
}

static void OPL3_ChannelSet4Op(opl3_chip *chip, uint8_t data)
{
    uint8_t bit;
    uint8_t chnum;
    for (bit = 0; bit < 6; bit++)
    {
        chnum = bit;
        if (bit >= 3)
        {
            chnum += 9 - 3;
        }
        if ((data >> bit) & 0x01)
        {
            chip->channel[chnum].chtype = ch_4op;
            chip->channel[chnum + 3u].chtype = ch_4op2;
#if !OPL_COMPAT_DEFERRED_4OP_ALG
            OPL3_ChannelUpdateAlg(&chip->channel[chnum]);
#endif
        }
        else
        {
            chip->channel[chnum].chtype = ch_2op;
            chip->channel[chnum + 3u].chtype = ch_2op;
#if !OPL_COMPAT_DEFERRED_4OP_ALG
            OPL3_ChannelUpdateAlg(&chip->channel[chnum]);
            OPL3_ChannelUpdateAlg(&chip->channel[chnum + 3u]);
#endif
        }
    }
}

static int16_t OPL3_ClipSample(int32_t sample)
{
    if (sample > 32767)
    {
        sample = 32767;
    }
    else if (sample < -32768)
    {
        sample = -32768;
    }
    return (int16_t)sample;
}

static inline void OPL3_ProcessSlotImpl(opl3_slot *slot, uint8_t fb, int maybe_rhythm)
{
    /* Fast path for fully-attenuated key-off non-rhythm slots. The envelope
     * rate machine cannot change eg_rout here, but the full path still updates
     * feedback history, eg_out/eg_gen/pg_reset, phase output, noise, and out. */
    if (!slot->key && slot->eg_rout == 0x1ff
        && (!maybe_rhythm
            || (slot->slot_num != 13 && slot->slot_num != 16 && slot->slot_num != 17)))
    {
        opl3_chip *chip = slot->chip;
        uint32_t phaseinc;
        uint16_t phase;

        if (fb == 0 && slot->pg_inc == 0 && slot->out == 0
            && *slot->mod == 0 && slot->eg_tl_ksl == 0 && *slot->trem == 0
            && slot->pg_phase == 0 && slot->reg_vib == 0 && slot->reg_wf == 0)
        {
            slot->fbmod = 0;
            slot->prout = 0;
            slot->eg_out = 0x1ff;
            slot->pg_reset = 0;
            slot->eg_gen = envelope_gen_num_release;
            slot->pg_phase_out = 0;
            return;
        }

        OPL3_SlotCalcFB(slot, fb);

        slot->eg_out = slot->eg_rout + slot->eg_tl_ksl + *slot->trem;
        slot->pg_reset = 0;
        slot->eg_gen = envelope_gen_num_release;

        if (slot->reg_vib)
        {
            phaseinc = slot->pg_inc_vib[chip->vibpos];
        }
        else
        {
            phaseinc = slot->pg_inc;
        }

        phase = (uint16_t)(slot->pg_phase >> 9);
        slot->pg_phase += phaseinc;
        slot->pg_phase_out = phase;

        /* eg_out = eg_rout + eg_tl_ksl + *trem >= 0x1ff here, so the
         * silent-regime shortcut is always valid. */
        OPL3_SlotGenerateSilent(slot);
        return;
    }
    if (slot->eg_gen == envelope_gen_num_sustain && slot->key
        && slot->eg_rates[envelope_gen_num_sustain] == 0)
    {
        OPL3_SlotCalcFB(slot, fb);
        slot->eg_out = slot->eg_rout + slot->eg_tl_ksl + *slot->trem;
        slot->pg_reset = 0;
        if ((slot->eg_rout & 0x1f8) == 0x1f8)
        {
            slot->eg_rout = 0x1ff;
        }

        if (!slot->reg_vib
            && (!maybe_rhythm
                || (slot->slot_num != 13 && slot->slot_num != 16 && slot->slot_num != 17)))
        {
            uint16_t phase = (uint16_t)(slot->pg_phase >> 9);

            slot->pg_phase += slot->pg_inc;
            slot->pg_phase_out = phase;
        }
        else
        {
            OPL3_PhaseGenerateImpl(slot, maybe_rhythm);
        }

        OPL3_SlotGenerate(slot);
        return;
    }
    OPL3_SlotCalcFB(slot, fb);
    OPL3_EnvelopeCalc(slot);
    OPL3_PhaseGenerateImpl(slot, maybe_rhythm);
    OPL3_SlotGenerate(slot);
}

/* Out-of-line clones of OPL3_ProcessSlotImpl. Norm is for the 16 channels
 * that can never contain a rhythm-special slot (everything except channels
 * 7 and 8, which hold slots 13/16 and 14/17). */
static void OPL3_ProcessSlotNorm(opl3_slot *slot, uint8_t fb)
{
    OPL3_ProcessSlotImpl(slot, fb, 0);
}

static void OPL3_ProcessSlotRhythm(opl3_slot *slot, uint8_t fb)
{
    OPL3_ProcessSlotImpl(slot, fb, 1);
}

/* Inlined pre-check skipping the ProcessSlot call for trivially-silent slots.
 * The prout == 0 and eg_gen == release conditions are critical because their
 * silence values are not implied by the other conditions (a key-on pulse with
 * AR=0 parks eg_gen in attack; prout can hold the last pre-silence output),
 * so the transition sample runs the trivial path inside ProcessSlot, which
 * writes both. The remaining fields the trivial path writes (fbmod, eg_out,
 * pg_reset, pg_phase_out) are recomputed by every ProcessSlot tier. */
static inline void OPL3_ProcessSlotMaybeInline(opl3_slot *slot, uint8_t fb, int maybe_rhythm,
                                               uint32_t write_gen)
{
    if (slot->dormant_gen == write_gen)
    {
        return;
    }
    if (!slot->key && slot->eg_rout == 0x1ff
        && slot->eg_gen == envelope_gen_num_release
        && (!maybe_rhythm
            || (slot->slot_num != 13 && slot->slot_num != 16 && slot->slot_num != 17))
        && fb == 0 && slot->pg_inc == 0 && slot->out == 0
        && slot->prout == 0
        && *slot->mod == 0 && slot->eg_tl_ksl == 0 && *slot->trem == 0
        && slot->pg_phase == 0 && slot->reg_vib == 0 && slot->reg_wf == 0)
    {
        /* Try to mark the slot dormant, which requires that *mod and *trem
         * stay zero without reprocessing. trem must be frozen at zeromod.
         * mod may be zeromod, the slot's own fbmod (unchanged while the slot
         * is skipped), or another slot's out; that slot is always earlier in
         * processing order, so if it is dormant now, its out stays 0 for
         * exactly as long as this slot's own gate holds (any register write
         * invalidates both). */
        opl3_chip *chip = slot->chip;
        if (slot->trem == (uint8_t*)&chip->zeromod)
        {
            int16_t *m = slot->mod;
            if (m == &chip->zeromod || m == &slot->fbmod)
            {
                slot->dormant_gen = write_gen;
            }
            else
            {
                /* m is &src->out for some slot src */
                opl3_slot *src = (opl3_slot *)((char *)m - offsetof(opl3_slot, out));
                if (src->dormant_gen == write_gen)
                {
                    slot->dormant_gen = write_gen;
                }
            }
        }
        return;
    }
    if (maybe_rhythm)
    {
        OPL3_ProcessSlotRhythm(slot, fb);
    }
    else
    {
        OPL3_ProcessSlotNorm(slot, fb);
    }
}

/* Process a channel's slot pair (modulator then carrier). */
static inline void OPL3_ProcessChannelSlots(opl3_channel *channel, int maybe_rhythm,
                                            uint32_t write_gen)
{
    uint8_t fb = channel->fb;
    OPL3_ProcessSlotMaybeInline(channel->slotz[0], fb, maybe_rhythm, write_gen);
    OPL3_ProcessSlotMaybeInline(channel->slotz[1], fb, maybe_rhythm, write_gen);
}

/* Right-channel mix over the out_right pointer lists, into mixbuff[1] and
 * mixbuff[3]. */
static void OPL3_MixRight(opl3_chip *chip)
{
    int32_t mix0 = 0;
    int32_t mix1 = 0;
    uint8_t ii;
    for (ii = 0; ii < chip->nmix_right; ii++)
    {
        opl3_channel *channel = chip->mix_right[ii];
        int16_t **out;
        int16_t accm;
#if OPL_QUIRK_CHANNELSAMPLEDELAY
        out = channel->out_right;
#else
        out = channel->out;
#endif
        accm = *out[0];
        if (channel->out_cnt > 1)
        {
            accm += *out[1];
            if (channel->out_cnt > 2)
            {
                accm += *out[2];
                if (channel->out_cnt > 3)
                {
                    accm += *out[3];
                }
            }
        }
#if OPL_ENABLE_STEREOEXT
        mix0 += (int16_t)((accm * channel->rightpan) >> 16);
#else
        mix0 += (int16_t)(accm & channel->chb);
#endif
        mix1 += (int16_t)(accm & channel->chd);
    }
    chip->mixbuff[1] = mix0;
    chip->mixbuff[3] = mix1;
}

inline void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4)
{
    opl3_channel *channel;
    opl3_writebuf *writebuf;
    int16_t **out;
    int32_t mix[2];
    uint8_t ii;
    int16_t accm;
    uint8_t shift = 0;
    uint8_t update_tremolo;

    buf4[1] = OPL3_ClipSample(chip->mixbuff[1]);
    buf4[3] = OPL3_ClipSample(chip->mixbuff[3]);

    if (chip->mix_dirty)
    {
        OPL3_RebuildMixLists(chip);
    }

    /* Advance the noise LFSR for the whole sample up front (36 steps, one per
     * slot), capturing the bits the hh (slot 13) and sd (slot 16) operators
     * read. This way slot processing does not touch the LFSR so it doesn't need
     * to run in strict slot order.
     *
     * The 36 feedback bits are computable word-parallel as:
     * fb_i = s_i ^ s_{i+14} for i in [0,8],
     * fb_i = s_i ^ fb_{i-9} for i in [9,22],
     * fb_i = fb_{i-23} ^ fb_{i-9} for i >= 23,
     * and the state after 36 steps is fb_13..fb_35. The hh/sd taps only read
     * bit 0 of the intermediate state, which is s_13 / s_16. */
    {
        uint32_t s = chip->noise;
        uint32_t f0_8   = (s ^ (s >> 14)) & 0x1ffu;          /* fb 0..8   */
        uint32_t f9_17  = ((s >> 9) ^ f0_8) & 0x1ffu;        /* fb 9..17  */
        uint32_t f18_22 = ((s >> 18) ^ f9_17) & 0x1fu;       /* fb 18..22 */
        uint32_t f23_31 = f0_8 ^ ((f9_17 >> 5) | (f18_22 << 4)); /* fb 23..31 */
        uint32_t f32_35 = (f9_17 ^ f23_31) & 0x0fu;          /* fb 32..35 */
        chip->noise_hh = (s >> 13) & 1u;
        chip->noise_sd = (s >> 16) & 1u;
        chip->noise = ((f9_17 >> 4) & 0x1fu)
                    | (f18_22 << 5)
                    | (f23_31 << 10)
                    | (f32_35 << 19);
    }

    /* Process all 36 slots (channel-grouped pairs) before either mix pass.
     * The mixes read the delayed slots' previous-sample out through prout
     * via the out_left/out_right pointer lists. */
    {
        uint32_t write_gen = chip->write_gen;
        for (ii = 0; ii < 7; ii++)
        {
            OPL3_ProcessChannelSlots(&chip->channel[ii], 0, write_gen);
        }
        OPL3_ProcessChannelSlots(&chip->channel[7], 1, write_gen);
        OPL3_ProcessChannelSlots(&chip->channel[8], 1, write_gen);
        for (ii = 9; ii < 18; ii++)
        {
            OPL3_ProcessChannelSlots(&chip->channel[ii], 0, write_gen);
        }
    }

    mix[0] = mix[1] = 0;
    for (ii = 0; ii < chip->nmix_left; ii++)
    {
        channel = chip->mix_left[ii];
#if OPL_QUIRK_CHANNELSAMPLEDELAY
        out = channel->out_left;
#else
        out = channel->out;
#endif
        accm = *out[0];
        if (channel->out_cnt > 1)
        {
            accm += *out[1];
            if (channel->out_cnt > 2)
            {
                accm += *out[2];
                if (channel->out_cnt > 3) accm += *out[3];
            }
        }
#if OPL_ENABLE_STEREOEXT
        mix[0] += (int16_t)((accm * channel->leftpan) >> 16);
#else
        mix[0] += (int16_t)(accm & channel->cha);
#endif
        mix[1] += (int16_t)(accm & channel->chc);
    }
    chip->mixbuff[0] = mix[0];
    chip->mixbuff[2] = mix[1];

    buf4[0] = OPL3_ClipSample(chip->mixbuff[0]);
    buf4[2] = OPL3_ClipSample(chip->mixbuff[2]);

    /* The right mix (OPL3_MixRight) runs after the housekeeping below */

    update_tremolo = chip->tremolo_dirty;
    if ((chip->timer & 0x3f) == 0x3f)
    {
        chip->tremolopos++;
        if (chip->tremolopos == 210)
        {
            chip->tremolopos = 0;
        }
        update_tremolo = 1;
    }
    if (update_tremolo)
    {
        if (chip->tremolopos < 105)
        {
            chip->tremolo = chip->tremolopos >> chip->tremoloshift;
        }
        else
        {
            chip->tremolo = (210 - chip->tremolopos) >> chip->tremoloshift;
        }
        chip->tremolo_dirty = 0;
    }

    if ((chip->timer & 0x3ff) == 0x3ff)
    {
        chip->vibpos = (chip->vibpos + 1) & 7;
    }

    chip->timer++;

#if OPL_COMPAT_OLD_EG
    /* Pre-2024 envelope stepping (upstream 730f8c2 and earlier): eg_add is
     * recomputed from the raw envelope timer every sample instead of only
     * on eg_state cycles, and OPL3_EnvelopeCalc indexes eg_incstep with the
     * live low bits of chip->timer instead of the latched eg_timer_lo. */
    {
        uint32_t eg_timer_low = (uint32_t)chip->eg_timer & 0x1fffu;
        if (!eg_timer_low)
        {
            chip->eg_add = 0;
        }
        else
        {
#if defined(__GNUC__) || defined(__clang__)
            shift = (uint8_t)__builtin_ctz(eg_timer_low);
#else
            while (((eg_timer_low >> shift) & 1) == 0)
            {
                shift++;
            }
#endif
            chip->eg_add = shift + 1;
        }
    }
#else
    if (chip->eg_state)
    {
        uint32_t eg_timer_low = (uint32_t)chip->eg_timer & 0x1fffu;
        if (!eg_timer_low)
        {
            chip->eg_add = 0;
        }
        else
        {
#if defined(__GNUC__) || defined(__clang__)
            shift = (uint8_t)__builtin_ctz(eg_timer_low);
#else
            while (((eg_timer_low >> shift) & 1) == 0)
            {
                shift++;
            }
#endif
            chip->eg_add = shift + 1;
        }
        chip->eg_timer_lo = (uint8_t)(chip->eg_timer & 0x3u);
    }
#endif

    if (chip->eg_timerrem || chip->eg_state)
    {
        if (chip->eg_timer == UINT64_C(0xfffffffff))
        {
            chip->eg_timer = 0;
            chip->eg_timerrem = 1;
        }
        else
        {
            chip->eg_timer++;
            chip->eg_timerrem = 0;
        }
    }

    chip->eg_state ^= 1;

    /* The right mix reads channel state the register writes below may
     * mutate, so it must complete first. */
    OPL3_MixRight(chip);

    while ((writebuf = &chip->writebuf[chip->writebuf_cur]), writebuf->time <= chip->writebuf_samplecnt)
    {
        if (!(writebuf->reg & 0x200))
        {
            break;
        }
        writebuf->reg &= 0x1ff;
        OPL3_WriteReg(chip, writebuf->reg, writebuf->data);
        chip->writebuf_cur = (chip->writebuf_cur + 1) % OPL_WRITEBUF_SIZE;
    }
    chip->writebuf_samplecnt++;
}

void OPL3_Generate(opl3_chip *chip, int16_t *buf)
{
    int16_t samples[4];
    OPL3_Generate4Ch(chip, samples);
    buf[0] = samples[0];
    buf[1] = samples[1];
}

void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4)
{
    while (chip->samplecnt >= chip->rateratio)
    {
        chip->oldsamples[0] = chip->samples[0];
        chip->oldsamples[1] = chip->samples[1];
        chip->oldsamples[2] = chip->samples[2];
        chip->oldsamples[3] = chip->samples[3];
        OPL3_Generate4Ch(chip, chip->samples);
        chip->samplecnt -= chip->rateratio;
    }
    buf4[0] = (int16_t)((chip->oldsamples[0] * (chip->rateratio - chip->samplecnt)
                        + chip->samples[0] * chip->samplecnt) / chip->rateratio);
    buf4[1] = (int16_t)((chip->oldsamples[1] * (chip->rateratio - chip->samplecnt)
                        + chip->samples[1] * chip->samplecnt) / chip->rateratio);
    buf4[2] = (int16_t)((chip->oldsamples[2] * (chip->rateratio - chip->samplecnt)
                        + chip->samples[2] * chip->samplecnt) / chip->rateratio);
    buf4[3] = (int16_t)((chip->oldsamples[3] * (chip->rateratio - chip->samplecnt)
                        + chip->samples[3] * chip->samplecnt) / chip->rateratio);
    chip->samplecnt += 1 << RSM_FRAC;
}

void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf)
{
    int16_t samples[4];
    OPL3_Generate4ChResampled(chip, samples);
    buf[0] = samples[0];
    buf[1] = samples[1];
}

void OPL3_Reset(opl3_chip *chip, uint32_t samplerate)
{
    opl3_slot *slot;
    opl3_channel *channel;
    uint8_t slotnum;
    uint8_t channum;
    uint8_t local_ch_slot;

#if OPL_WF_TABLE_RUNTIME
    if (!logsin_wf_built)
    {
        OPL3_BuildWfTable();
    }
#endif
    memset(chip, 0, sizeof(opl3_chip));
    for (slotnum = 0; slotnum < 36; slotnum++)
    {
        slot = &chip->slot[slotnum];
        slot->chip = chip;
        slot->mod = &chip->zeromod;
        slot->eg_rout = 0x1ff;
        slot->eg_out = 0x1ff;
        slot->eg_gen = envelope_gen_num_release;
        slot->trem = (uint8_t*)&chip->zeromod;
        slot->eg_rates[0] = slot->eg_rates[1] = slot->eg_rates[2] = slot->eg_rates[3] = 0;
        slot->slot_num = slotnum;
    }
    for (channum = 0; channum < 18; channum++)
    {
        channel = &chip->channel[channum];
        local_ch_slot = ch_slot[channum];
        channel->slotz[0] = &chip->slot[local_ch_slot];
        channel->slotz[1] = &chip->slot[local_ch_slot + 3u];
        chip->slot[local_ch_slot].channel = channel;
        chip->slot[local_ch_slot + 3u].channel = channel;
        if ((channum % 9) < 3)
        {
            channel->pair = &chip->channel[channum + 3u];
        }
        else if ((channum % 9) < 6)
        {
            channel->pair = &chip->channel[channum - 3u];
        }
        channel->chip = chip;
        channel->out[0] = &chip->zeromod;
        channel->out[1] = &chip->zeromod;
        channel->out[2] = &chip->zeromod;
        channel->out[3] = &chip->zeromod;
        channel->out_cnt = 0;
        channel->chtype = ch_2op;
        channel->cha = 0xffff;
        channel->chb = 0xffff;
#if OPL_ENABLE_STEREOEXT
        channel->leftpan = 0x10000;
        channel->rightpan = 0x10000;
#endif
        channel->ch_num = channum;
        OPL3_ChannelSetupAlg(channel);
    }
    chip->noise = 1;
    chip->mix_dirty = 1;
    chip->write_gen = 1;
    chip->rateratio = (samplerate << RSM_FRAC) / 49716;
    chip->tremoloshift = 4;
    chip->vibshift = 1;

#if OPL_ENABLE_STEREOEXT
    if (!panpot_lut_build)
    {
        int32_t i;
        for (i = 0; i < 256; i++)
        {
            panpot_lut[i] = OPL_SIN(i);
        }
        panpot_lut_build = 1;
    }
#endif
}

void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v)
{
    uint8_t high = (reg >> 8) & 0x01;
    uint8_t regm = reg & 0xff;
    if (++chip->write_gen == 0)
    {
        uint8_t ii;
        for (ii = 0; ii < 36; ii++)
        {
            chip->slot[ii].dormant_gen = 0;
        }
        chip->write_gen = 1;
    }
    switch (regm & 0xf0)
    {
    case 0x00:
        if (high)
        {
            switch (regm & 0x0f)
            {
            case 0x04:
                OPL3_ChannelSet4Op(chip, v);
                break;
            case 0x05:
                chip->newm = v & 0x01;
#if OPL_ENABLE_STEREOEXT
                chip->stereoext = (v >> 1) & 0x01;
#endif
                break;
            }
        }
        else
        {
            switch (regm & 0x0f)
            {
            case 0x08:
                chip->nts = (v >> 6) & 0x01;
                break;
            }
        }
        break;
    case 0x20:
    case 0x30:
        if (ad_slot[regm & 0x1fu] >= 0)
        {
            OPL3_SlotWrite20(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v);
        }
        break;
    case 0x40:
    case 0x50:
        if (ad_slot[regm & 0x1fu] >= 0)
        {
            OPL3_SlotWrite40(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v);
        }
        break;
    case 0x60:
    case 0x70:
        if (ad_slot[regm & 0x1fu] >= 0)
        {
            OPL3_SlotWrite60(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v);
        }
        break;
    case 0x80:
    case 0x90:
        if (ad_slot[regm & 0x1fu] >= 0)
        {
            OPL3_SlotWrite80(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v);
        }
        break;
    case 0xe0:
    case 0xf0:
        if (ad_slot[regm & 0x1fu] >= 0)
        {
            OPL3_SlotWriteE0(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], v);
        }
        break;
    case 0xa0:
        if ((regm & 0x0f) < 9)
        {
            OPL3_ChannelWriteA0(&chip->channel[9u * high + (regm & 0x0fu)], v);
        }
        break;
    case 0xb0:
        if (regm == 0xbd && !high)
        {
            uint8_t tremoloshift = (((v >> 7) ^ 1) << 1) + 2;
            uint8_t vibshift = ((v >> 6) & 0x01) ^ 1;
            if (chip->tremoloshift != tremoloshift)
            {
                chip->tremolo_dirty = 1;
            }
            chip->tremoloshift = tremoloshift;
            if (chip->vibshift != vibshift)
            {
                uint8_t ii;
                chip->vibshift = vibshift;
                for (ii = 0; ii < 36; ii++)
                {
                    OPL3_PhaseUpdateInc(&chip->slot[ii]);
                }
            }
            OPL3_ChannelUpdateRhythm(chip, v);
        }
        else if ((regm & 0x0f) < 9)
        {
            OPL3_ChannelWriteB0(&chip->channel[9u * high + (regm & 0x0fu)], v);
            if (v & 0x20)
            {
                OPL3_ChannelKeyOn(&chip->channel[9u * high + (regm & 0x0fu)]);
            }
            else
            {
                OPL3_ChannelKeyOff(&chip->channel[9u * high + (regm & 0x0fu)]);
            }
        }
        break;
    case 0xc0:
        if ((regm & 0x0f) < 9)
        {
            OPL3_ChannelWriteC0(&chip->channel[9u * high + (regm & 0x0fu)], v);
        }
        break;
#if OPL_ENABLE_STEREOEXT
    case 0xd0:
        if ((regm & 0x0f) < 9)
        {
            OPL3_ChannelWriteD0(&chip->channel[9u * high + (regm & 0x0fu)], v);
        }
        break;
#endif
    }
}

void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v)
{
    uint64_t time1, time2;
    opl3_writebuf *writebuf;
    uint32_t writebuf_last;

    writebuf_last = chip->writebuf_last;
    writebuf = &chip->writebuf[writebuf_last];

    if (writebuf->reg & 0x200)
    {
        OPL3_WriteReg(chip, writebuf->reg & 0x1ff, writebuf->data);

        chip->writebuf_cur = (writebuf_last + 1) % OPL_WRITEBUF_SIZE;
        chip->writebuf_samplecnt = writebuf->time;
    }

    writebuf->reg = reg | 0x200;
    writebuf->data = v;
    time1 = chip->writebuf_lasttime + OPL_WRITEBUF_DELAY;
    time2 = chip->writebuf_samplecnt;

    if (time1 < time2)
    {
        time1 = time2;
    }

    writebuf->time = time1;
    chip->writebuf_lasttime = time1;
    chip->writebuf_last = (writebuf_last + 1) % OPL_WRITEBUF_SIZE;
}

void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples)
{
    uint_fast32_t i;
    int16_t samples[4];

    for(i = 0; i < numsamples; i++)
    {
        OPL3_Generate4ChResampled(chip, samples);
        sndptr1[0] = samples[0];
        sndptr1[1] = samples[1];
        sndptr2[0] = samples[2];
        sndptr2[1] = samples[3];
        sndptr1 += 2;
        sndptr2 += 2;
    }
}

void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples)
{
    uint_fast32_t i;

    for(i = 0; i < numsamples; i++)
    {
        OPL3_GenerateResampled(chip, sndptr);
        sndptr += 2;
    }
}
