TR
games/alis / src / Alis / fn / emu8950.php · commit 9c722cf
<?phpnamespace App\Alis;// Port of alis/src/emu8950/emu8950.c (emu8950 v1.1.4, MIT, Mitsutaka Okazaki), used by the ALIS port// (MIT, Olivier Huguenot, Vadim Kindl).// PORT: the static functions update_output() / mix_output() are named opl_update_output() / opl_mix_output()// (emu2149.c has functions of the same name). The ADPCM unit (emuadpcm.c) is not ported: it only exists on// the Y8950 and ALIS always selects the YM3812 (sys_init_opl), so opl->adpcm stays NULL.// PORT: OPL_calc() renders through OPL_calc_block(), a fast version of n successive OPL_calc() calls with the// state in local variables; the faithful per-sample functions below (opl_update_output(), OPL_calc_ref())// are the reference it was checked against and the fallback for the features the fast path does not// handle (rhythm mode, CSM, test register, channel masks).const OPL_ATTACK = 0;const OPL_DECAY = 1;const OPL_SUSTAIN = 2;const OPL_RELEASE = 3;const OPL_UNKNOWN = 4;const OPL_TYPE_Y8950 = 0;const OPL_TYPE_YM3526 = 1;const OPL_TYPE_YM3812 = 2;const OPL_TYPE_MAX = 3;/* phase increment counter */const OPL_DP_BITS = 20;const OPL_DP_WIDTH = 1 << OPL_DP_BITS;const OPL_PG_BITS = 10;const OPL_PG_WIDTH = 1 << OPL_PG_BITS;const OPL_DP_BASE_BITS = OPL_DP_BITS - OPL_PG_BITS;/* dynamic range of envelope output */const OPL_EG_STEP = 0.1875;const OPL_EG_BITS = 9;const OPL_EG_MUTE = (1 << OPL_EG_BITS) - 1;const OPL_EG_MAX = 0x1f0; // 93dBconst OPL_TL_BITS = 6;/* pitch modulator */const OPL_PM_PG_BITS = 3;const OPL_PM_DP_BITS = 22;const OPL_PM_DP_WIDTH = 1 << OPL_PM_DP_BITS;const OPL_LW = 16;const OPL_SINC_RESO = 256;const OPL_SINC_AMP_BITS = 12;const OPL_SLOT_BD1 = 12;const OPL_SLOT_BD2 = 13;const OPL_SLOT_HH = 14;const OPL_SLOT_SD = 15;const OPL_SLOT_TOM = 16;const OPL_SLOT_CYM = 17;const OPL_UPDATE_WS = 1;const OPL_UPDATE_TLL = 2;const OPL_UPDATE_RKS = 4;const OPL_UPDATE_EG = 8;const OPL_UPDATE_ALL = 255;const OPL_MASK_HH = 1 << 9;const OPL_MASK_CYM = 1 << 10;const OPL_MASK_TOM = 1 << 11;const OPL_MASK_SD = 1 << 12;const OPL_MASK_BD = 1 << 13;const OPL_MASK_ADPCM = 1 << 14;/***************************************************           Internal Sample Rate Converter****************************************************/function blackman(float $x): float{    return 0.42 - 0.5 * cos(2 * M_PI * $x) + 0.08 * cos(4 * M_PI * $x);}function sinc(float $x): float{    return $x == 0.0 ? 1.0 : sin(M_PI * $x) / (M_PI * $x);}function windowed_sinc(float $x): float{    return blackman(0.5 + 0.5 * $x / intdiv(OPL_LW, 2)) * sinc($x);}/* f_inp: input frequency. f_out: output frequencey, ch: number of channels */function OPL_RateConv_new(float $f_inp, float $f_out, int $ch): OPL_RateConv{    $conv = new OPL_RateConv();    $conv->ch = $ch;    $conv->f_ratio = $f_inp / $f_out;    $conv->buf = [];    for ($i = 0; $i < $ch; $i++) {        $conv->buf[$i] = array_fill(0, OPL_LW, 0);    }    /* create sinc_table for positive 0 <= x < LW/2 */    $conv->sinc_table = [];    for ($i = 0; $i < OPL_SINC_RESO * OPL_LW / 2; $i++) {        $x = (float) $i / OPL_SINC_RESO;        if ($f_out < $f_inp) {            /* for downsampling */            $v = (int) ((1 << OPL_SINC_AMP_BITS) * windowed_sinc($x / $conv->f_ratio) / $conv->f_ratio);        } else {            /* for upsampling */            $v = (int) ((1 << OPL_SINC_AMP_BITS) * windowed_sinc($x));        }        $conv->sinc_table[$i] = s16($v);    }    // PORT (speed): the taps for every dn in ]fd/256, (fd+1)/256[ (see OPL_RateConv_getData)    $conv->coef = [];    for ($fd = 0; $fd < 256; $fd++) {        $dn = ($fd + 0.5) / 256.0;        $c = [];        for ($k = 0; $k < OPL_LW; $k++) {            $c[$k] = lookup_sinc_table($conv->sinc_table, ((float) $k - (OPL_LW / 2 - 1)) - $dn);        }        $conv->coef[$fd] = $c;    }    return $conv;}function lookup_sinc_table(array $table, float $x): int{    $index = s16((int) ($x * OPL_SINC_RESO));    if ($index < 0) {        $index = -$index;    }    return $table[\min(intdiv(OPL_SINC_RESO * OPL_LW, 2) - 1, $index)];}function OPL_RateConv_reset(OPL_RateConv $conv): void{    $conv->timer = 0.0;    for ($i = 0; $i < $conv->ch; $i++) {        $conv->buf[$i] = array_fill(0, OPL_LW, 0);    }}/* put original data to this converter at f_inp. */function OPL_RateConv_putData(OPL_RateConv $conv, int $ch, int $data): void{    $buf = $conv->buf[$ch];    array_shift($buf);    $buf[] = $data;    $conv->buf[$ch] = $buf;}/* get resampled data from this converter at f_out. */function OPL_RateConv_getData(OPL_RateConv $conv, int $ch): int{    $buf = $conv->buf[$ch];    $sum = 0;    $conv->timer += $conv->f_ratio;    $dn = $conv->timer - floor($conv->timer);    $conv->timer = $dn;    for ($k = 0; $k < OPL_LW; $k++) {        $x = ((float) $k - (OPL_LW / 2 - 1)) - $dn;        $sum += $buf[$k] * lookup_sinc_table($conv->sinc_table, $x);    }    return s16(s32($sum) >> OPL_SINC_AMP_BITS);}function OPL_RateConv_delete(OPL_RateConv $conv): void{}/***************************************************                  Create tables****************************************************/function makeSinTable(): void{    $logsin = Emu8950Vars::logsin_table;    $w = array_fill(0, 4, array_fill(0, OPL_PG_WIDTH, 0));    for ($x = 0; $x < OPL_PG_WIDTH; $x++) {        if ($x < OPL_PG_WIDTH / 4) {            $w[0][$x] = $logsin[$x];        } elseif ($x < OPL_PG_WIDTH / 2) {            $w[0][$x] = $logsin[OPL_PG_WIDTH / 2 - $x - 1];        } else {            $w[0][$x] = 0x8000 | $w[0][OPL_PG_WIDTH - $x - 1];        }    }    for ($x = 0; $x < OPL_PG_WIDTH; $x++) {        $w[1][$x] = $x < OPL_PG_WIDTH / 2 ? $w[0][$x] : 0xfff;    }    for ($x = 0; $x < OPL_PG_WIDTH; $x++) {        $w[2][$x] = $x < OPL_PG_WIDTH / 2 ? $w[0][$x] : $w[0][$x - OPL_PG_WIDTH / 2];    }    for ($x = 0; $x < OPL_PG_WIDTH; $x++) {        if ($x < OPL_PG_WIDTH / 4) {            $w[3][$x] = $w[0][$x];        } elseif ($x < OPL_PG_WIDTH / 2) {            $w[3][$x] = 0xfff;        } elseif ($x < OPL_PG_WIDTH * 3 / 4) {            $w[3][$x] = $w[0][$x - OPL_PG_WIDTH / 2];        } else {            $w[3][$x] = 0xfff;        }    }    Emu8950Vars::$wave_table_map = $w;    // PORT (speed): sign bit 0x8000 -> 0x2000 (values are <= 0xfff, attenuations <= 0xff8: no carry into it)    $f = [];    for ($t = 0; $t < 4; $t++) {        foreach ($w[$t] as $x => $h) {            $f[$t][$x] = ($h & 0x7fff) | (($h & 0x8000) ? 0x2000 : 0);        }    }    Emu8950Vars::$wave_fast = $f;    $lin = [];    for ($j = 0; $j < 0x4000; $j++) {        $lin[$j] = lookup_exp_table((($j & 0x2000) ? 0x8000 : 0) | ($j & 0x1fff));    }    Emu8950Vars::$lin = $lin;}function makeTllTable(): void{    $t = [];    for ($fnum = 0; $fnum < 16; $fnum++) {        for ($block = 0; $block < 8; $block++) {            for ($TL = 0; $TL < 64; $TL++) {                for ($KL = 0; $KL < 4; $KL++) {                    $kx = (($KL & 1) << 1) | (($KL >> 1) & 1);                    $i = (((($block << 4) | $fnum) << 6 | $TL) << 2) | $KL;                    if ($KL == 0) {                        $t[$i] = $TL << 2;                    } else {                        $tmp = (int) (Emu8950Vars::kl_table[$fnum] - 3.000 * 2 * (7 - $block));                        if ($tmp <= 0) {                            $t[$i] = $TL << 2;                        } else {                            $t[$i] = (int) (($tmp >> (3 - $kx)) / OPL_EG_STEP) + ($TL << 2);                        }                    }                }            }        }    }    ksort($t);    Emu8950Vars::$tll_table = array_values($t);}function makeRksTable(): void{    $r = array_fill(0, 2 * 32 * 2, 0);    for ($fnum8 = 0; $fnum8 < 2; $fnum8++) {        for ($fnum9 = 0; $fnum9 < 2; $fnum9++) {            for ($blk = 0; $blk < 8; $blk++) {                $blk_fnum98 = ($blk << 2) | ($fnum9 << 1) | $fnum8;                $r[(0 << 6) | ($blk_fnum98 << 1) | 1] = ($blk << 1) + $fnum9;                $r[(0 << 6) | ($blk_fnum98 << 1) | 0] = $blk >> 1;                $r[(1 << 6) | ($blk_fnum98 << 1) | 1] = ($blk << 1) + ($fnum9 & $fnum8);                $r[(1 << 6) | ($blk_fnum98 << 1) | 0] = $blk >> 1;            }        }    }    Emu8950Vars::$rks_table = $r;}/** PORT (speed): the noise LFSR (linear over GF(2)) advanced by 18, 14 and 2 steps, by byte of the state. */function makeNoiseJumpTables(): void{    $tables = [];    foreach ([18, 14, 2] as $steps) {        for ($b = 0; $b < 3; $b++) {            for ($v = 0; $v < 256; $v++) {                $n = $v << ($b * 8);                for ($i = 0; $i < $steps; $i++) {                    if ($n & 1) {                        $n ^= 0x800200;                    }                    $n >>= 1;                }                $tables[$steps][$b][$v] = $n;            }        }    }    Emu8950Vars::$noise_jump = $tables;}function initializeTables(): void{    makeTllTable();    makeRksTable();    makeSinTable();    makeNoiseJumpTables();    Emu8950Vars::$table_initialized = 1;}/*********************************************************                      Synthesizing*********************************************************/function get_parameter_rate(OPL $o, int $s): int{    switch ($o->eg_state[$s]) {        case OPL_ATTACK:            return $o->AR[$s];        case OPL_DECAY:            return $o->DR[$s];        case OPL_SUSTAIN:            return $o->EG[$s] ? 0 : $o->RR[$s];        case OPL_RELEASE:            return $o->RR[$s];        default:            return 0;    }}function request_update(OPL $o, int $s, int $flag): void{    $o->update_requests[$s] |= $flag;}function commit_slot_update(OPL $o, int $s, int $notesel): void{    $req = $o->update_requests[$s];    if ($req & OPL_UPDATE_WS) {        $o->wave_table[$s] = $o->WS[$s] & 3;    }    if ($req & OPL_UPDATE_TLL) {        $o->tll[$s] = Emu8950Vars::$tll_table[(($o->blk_fnum[$s] >> 6) << 8) | ($o->TL[$s] << 2) | $o->KL[$s]];    }    if ($req & OPL_UPDATE_RKS) {        $o->rks[$s] = Emu8950Vars::$rks_table[($notesel << 6) | (($o->blk_fnum[$s] >> 8) << 1) | $o->KR[$s]];    }    if ($req & (OPL_UPDATE_RKS | OPL_UPDATE_EG)) {        $p_rate = get_parameter_rate($o, $s);        if ($p_rate == 0) {            $o->eg_shift[$s] = 0;            $o->eg_rate_h[$s] = 0;            $o->eg_rate_l[$s] = 0;        } else {            $rh = \min(15, $p_rate + ($o->rks[$s] >> 2));            $o->eg_rate_h[$s] = $rh;            $o->eg_rate_l[$s] = $o->rks[$s] & 3;            if ($o->eg_state[$s] == OPL_ATTACK) {                $o->eg_shift[$s] = (0 < $rh && $rh < 12) ? (12 - $rh) : 0;            } else {                $o->eg_shift[$s] = ($rh < 12) ? (12 - $rh) : 0;            }        }    }    $o->update_requests[$s] = 0;}function reset_slot(OPL $o, int $s, int $number): void{    foreach (['TL', 'FB', 'EG', 'ML', 'AR', 'DR', 'SL', 'RR', 'KR', 'KL', 'AM', 'PM', 'WS'] as $f) {        $o->$f[$s] = 0;    }    $o->number[$s] = $number;    $o->type[$s] = $number % 2;    $o->pg_keep[$s] = 0;    $o->wave_table[$s] = 0;    $o->pg_phase[$s] = 0;    $o->output0[$s] = 0;    $o->output1[$s] = 0;    $o->eg_state[$s] = OPL_RELEASE;    $o->eg_shift[$s] = 0;    $o->rks[$s] = 0;    $o->tll[$s] = 0;    $o->blk_fnum[$s] = 0;    $o->blk[$s] = 0;    $o->fnum[$s] = 0;    $o->pg_out[$s] = 0;    $o->eg_out[$s] = OPL_EG_MUTE;    // (update_requests is not reset by the C either: calloc'ed at creation)}function slotOn(OPL $o, int $i): void{    $o->rks[$i] = Emu8950Vars::$rks_table[($o->notesel << 6) | (($o->blk_fnum[$i] >> 8) << 1) | $o->KR[$i]];    if (\min(15, $o->AR[$i] + ($o->rks[$i] >> 2)) == 15) {        $o->eg_state[$i] = OPL_DECAY;        $o->eg_out[$i] = 0;    } else {        $o->eg_state[$i] = OPL_ATTACK;    }    if (!$o->pg_keep[$i]) {        $o->pg_phase[$i] = 0;    }    request_update($o, $i, OPL_UPDATE_EG);}function slotOff(OPL $o, int $i): void{    $o->eg_state[$i] = OPL_RELEASE;    request_update($o, $i, OPL_UPDATE_EG);}function update_key_status(OPL $o): void{    $r14 = $o->reg[0xbd];    $rhythm_mode = ($r14 >> 5) & 1;    $new_slot_key_status = 0;    if ($o->csm_mode && $o->csm_key_count) {        $new_slot_key_status = 0x3ffff;    }    for ($ch = 0; $ch < 9; $ch++) {        if ($o->reg[0xB0 + $ch] & 0x20) {            $new_slot_key_status |= 3 << ($ch * 2);        }    }    if ($rhythm_mode) {        if ($r14 & 0x10) {            $new_slot_key_status |= 3 << OPL_SLOT_BD1;        }        if ($r14 & 0x01) {            $new_slot_key_status |= 1 << OPL_SLOT_HH;        }        if ($r14 & 0x08) {            $new_slot_key_status |= 1 << OPL_SLOT_SD;        }        if ($r14 & 0x04) {            $new_slot_key_status |= 1 << OPL_SLOT_TOM;        }        if ($r14 & 0x02) {            $new_slot_key_status |= 1 << OPL_SLOT_CYM;        }    }    $updated_status = $o->slot_key_status ^ $new_slot_key_status;    if ($updated_status) {        for ($i = 0; $i < 18; $i++) {            if (($updated_status >> $i) & 1) {                if (($new_slot_key_status >> $i) & 1) {                    slotOn($o, $i);                } else {                    slotOff($o, $i);                }            }        }    }    $o->slot_key_status = $new_slot_key_status;}/* set f-Nnmber ( fnum : 10bit ) */function set_fnumber(OPL $o, int $ch, int $fnum): void{    $car = ($ch << 1) | 1;    $mod = $ch << 1;    $o->fnum[$car] = $fnum & 0xffff;    $o->blk_fnum[$car] = ($o->blk_fnum[$car] & 0x1c00) | ($fnum & 0x3ff);    $o->fnum[$mod] = $fnum & 0xffff;    $o->blk_fnum[$mod] = ($o->blk_fnum[$mod] & 0x1c00) | ($fnum & 0x3ff);    request_update($o, $car, OPL_UPDATE_EG | OPL_UPDATE_RKS | OPL_UPDATE_TLL);    request_update($o, $mod, OPL_UPDATE_EG | OPL_UPDATE_RKS | OPL_UPDATE_TLL);}/* set block data (blk : 3bit ) */function set_block(OPL $o, int $ch, int $blk): void{    $car = ($ch << 1) | 1;    $mod = $ch << 1;    $o->blk[$car] = $blk & 0xff;    $o->blk_fnum[$car] = (($blk & 7) << 10) | ($o->blk_fnum[$car] & 0x3ff);    $o->blk[$mod] = $blk & 0xff;    $o->blk_fnum[$mod] = (($blk & 7) << 10) | ($o->blk_fnum[$mod] & 0x3ff);    request_update($o, $car, OPL_UPDATE_EG | OPL_UPDATE_RKS | OPL_UPDATE_TLL);    request_update($o, $mod, OPL_UPDATE_EG | OPL_UPDATE_RKS | OPL_UPDATE_TLL);}function update_rhythm_mode(OPL $o): void{    $new_rhythm_mode = ($o->reg[0xbd] >> 5) & 1;    if ($o->rhythm_mode != $new_rhythm_mode) {        if ($new_rhythm_mode) {            $o->type[OPL_SLOT_HH] = 3;            $o->pg_keep[OPL_SLOT_HH] = 1;            $o->type[OPL_SLOT_SD] = 3;            $o->type[OPL_SLOT_TOM] = 3;            $o->type[OPL_SLOT_CYM] = 3;            $o->pg_keep[OPL_SLOT_CYM] = 1;        } else {            $o->type[OPL_SLOT_HH] = 0;            $o->pg_keep[OPL_SLOT_HH] = 0;            $o->type[OPL_SLOT_SD] = 1;            $o->type[OPL_SLOT_TOM] = 0;            $o->type[OPL_SLOT_CYM] = 1;            $o->pg_keep[OPL_SLOT_CYM] = 0;        }    }    $o->rhythm_mode = $new_rhythm_mode;}function update_ampm(OPL $o): void{    $pm_inc = ($o->test_flag & 8) ? $o->pm_dphase << 10 : $o->pm_dphase;    $am_inc = ($o->test_flag & 8) ? 64 : 1;    if ($o->test_flag & 2) {        $o->pm_phase = 0;        $o->am_phase = 0;    } else {        $o->pm_phase = ($o->pm_phase + $pm_inc) & (OPL_PM_DP_WIDTH - 1);        $o->am_phase = s32($o->am_phase + $am_inc);    }    $o->lfo_am = Emu8950Vars::am_table[(($o->am_phase >> 6) % 210 + 210) % 210] >> ($o->am_mode ? 0 : 2);}function update_noise(OPL $o, int $cycle): void{    for ($i = 0; $i < $cycle; $i++) {        if ($o->noise & 1) {            $o->noise ^= 0x800200;        }        $o->noise >>= 1;    }}function update_short_noise(OPL $o): void{    $pg_hh = $o->pg_out[OPL_SLOT_HH];    $pg_cym = $o->pg_out[OPL_SLOT_CYM];    $h_bit2 = ($pg_hh >> (OPL_PG_BITS - 8)) & 1;    $h_bit7 = ($pg_hh >> (OPL_PG_BITS - 3)) & 1;    $h_bit3 = ($pg_hh >> (OPL_PG_BITS - 7)) & 1;    $c_bit3 = ($pg_cym >> (OPL_PG_BITS - 7)) & 1;    $c_bit5 = ($pg_cym >> (OPL_PG_BITS - 5)) & 1;    $o->short_noise = ($h_bit2 ^ $h_bit7) | ($h_bit3 ^ $c_bit5) | ($c_bit3 ^ $c_bit5);}function calc_phase(OPL $o, int $s, int $pm_phase, int $pm_mode, int $reset): void{    $pm = 0;    if ($o->PM[$s]) {        $pm = Emu8950Vars::pm_table[($o->fnum[$s] >> 7) & 7][$pm_phase >> (OPL_PM_DP_BITS - OPL_PM_PG_BITS)];        $pm >>= ($pm_mode ? 0 : 1);    }    if ($reset) {        $o->pg_phase[$s] = 0;    }    // uint32 arithmetic: only the low 20 bits are kept    $o->pg_phase[$s] = ($o->pg_phase[$s] + (((((($o->fnum[$s] & 0x3ff) + $pm) * Emu8950Vars::ml_table[$o->ML[$s]]) << $o->blk[$s]) >> 1) & (OPL_DP_WIDTH - 1))) & (OPL_DP_WIDTH - 1);    $o->pg_out[$s] = $o->pg_phase[$s] >> OPL_DP_BASE_BITS;}function lookup_attack_step(OPL $o, int $s, int $counter): int{    $index = ($counter >> $o->eg_shift[$s]) & 7;    switch ($o->eg_rate_h[$s]) {        case 13:            return Emu8950Vars::eg_step_tables_fast[$o->eg_rate_l[$s]][$index];        case 14:            return Emu8950Vars::eg_step_tables_fast[$o->eg_rate_l[$s]][$index] << 1;        case 0:        case 15:            return 0;        default:            return Emu8950Vars::eg_step_tables[$o->eg_rate_l[$s]][$index];    }}function lookup_decay_step(OPL $o, int $s, int $counter): int{    $index = ($counter >> $o->eg_shift[$s]) & 7;    switch ($o->eg_rate_h[$s]) {        case 0:            return 0;        case 13:            return Emu8950Vars::eg_step_tables_fast[$o->eg_rate_l[$s]][$index];        case 14:            return Emu8950Vars::eg_step_tables_fast[$o->eg_rate_l[$s]][$index] << 1;        case 15:            return 4;        default:            return Emu8950Vars::eg_step_tables[$o->eg_rate_l[$s]][$index];    }}function calc_envelope(OPL $o, int $s, int $eg_counter, int $test): void{    $eg_counter &= 0xffff;    $mask = ((1 << $o->eg_shift[$s]) - 1) & 0xffff;    if ($o->eg_state[$s] == OPL_ATTACK) {        if (0 < $o->eg_out[$s] && $o->eg_rate_h[$s] > 0 && ($eg_counter & $mask) == 0) {            $st = lookup_attack_step($o, $s, $eg_counter);            $o->eg_out[$s] = s16($o->eg_out[$s] + ((~$o->eg_out[$s] * $st) >> 3));        }    } else {        if ($o->eg_rate_h[$s] > 0 && ($eg_counter & $mask) == 0) {            $o->eg_out[$s] = \min(OPL_EG_MUTE, $o->eg_out[$s] + lookup_decay_step($o, $s, $eg_counter));        }    }    switch ($o->eg_state[$s]) {        case OPL_ATTACK:            if ($o->eg_out[$s] == 0) {                $o->eg_state[$s] = OPL_DECAY;                request_update($o, $s, OPL_UPDATE_EG);            }            break;        case OPL_DECAY:            if (($o->SL[$s] != 15) && ($o->eg_out[$s] >> 4) == $o->SL[$s]) {                $o->eg_state[$s] = OPL_SUSTAIN;                request_update($o, $s, OPL_UPDATE_EG);            }            break;        default:            break;    }    if ($test) {        $o->eg_out[$s] = 0;    }}function update_slots(OPL $o): void{    $o->eg_counter = s32($o->eg_counter + 1);    for ($i = 0; $i < 18; $i++) {        if ($o->update_requests[$i]) {            commit_slot_update($o, $i, $o->notesel);        }        calc_envelope($o, $i, $o->eg_counter, $o->test_flag & 1);        calc_phase($o, $i, $o->pm_phase, $o->pm_mode, $o->test_flag & 4);    }}/* input: 0..8191 output: -4095..4095 */function lookup_exp_table(int $i): int{    /* from andete's expressoin */    $t = Emu8950Vars::exp_table[($i & 0xff) ^ 0xff] + 1024;    $res = $t >> (($i & 0x7f00) >> 8);    return s16((($i & 0x8000) ? ~$res : $res) << 1);}function to_linear(int $h, OPL $o, int $s, int $am): int{    if ($o->eg_out[$s] >= OPL_EG_MAX) {        return 0;    }    $att = (\min(OPL_EG_MUTE, ($o->eg_out[$s] + $o->tll[$s] + $am)) << 3) & 0xffff;    return lookup_exp_table(($h + $att) & 0xffff);}function calc_slot_car(OPL $o, int $ch, int $fm): int{    $s = ($ch << 1) | 1;    $am = $o->AM[$s] ? $o->lfo_am : 0;    $o->output1[$s] = $o->output0[$s];    $o->output0[$s] = to_linear(Emu8950Vars::$wave_table_map[$o->wave_table[$s]][($o->pg_out[$s] + 2 * ($fm >> 1)) & (OPL_PG_WIDTH - 1)], $o, $s, $am);    return $o->output0[$s];}function calc_slot_mod(OPL $o, int $ch): int{    $s = $ch << 1;    $fm = $o->FB[$s] > 0 ? s16(($o->output1[$s] + $o->output0[$s]) >> (9 - $o->FB[$s])) : 0;    $am = $o->AM[$s] ? $o->lfo_am : 0;    $o->output1[$s] = $o->output0[$s];    $o->output0[$s] = to_linear(Emu8950Vars::$wave_table_map[$o->wave_table[$s]][($o->pg_out[$s] + $fm) & (OPL_PG_WIDTH - 1)], $o, $s, $am);    return $o->output0[$s];}function calc_slot_tom(OPL $o): int{    $s = OPL_SLOT_TOM;    return to_linear(Emu8950Vars::$wave_table_map[$o->wave_table[$s]][$o->pg_out[$s]], $o, $s, 0);}function calc_slot_snare(OPL $o): int{    $s = OPL_SLOT_SD;    if (($o->pg_out[OPL_SLOT_HH] >> (OPL_PG_BITS - 2)) & 1) {        $phase = ($o->noise & 1) ? 0x300 : 0x200;    } else {        $phase = ($o->noise & 1) ? 0x0 : 0x100;    }    return to_linear(Emu8950Vars::$wave_table_map[$o->wave_table[$s]][$phase], $o, $s, 0);}function calc_slot_cym(OPL $o): int{    $s = OPL_SLOT_CYM;    $phase = $o->short_noise ? 0x300 : 0x100;    return to_linear(Emu8950Vars::$wave_table_map[$o->wave_table[$s]][$phase], $o, $s, 0);}function calc_slot_hat(OPL $o): int{    $s = OPL_SLOT_HH;    if ($o->short_noise) {        $phase = ($o->noise & 1) ? 0x2d0 : 0x234;    } else {        $phase = ($o->noise & 1) ? 0x34 : 0xd0;    }    return to_linear(Emu8950Vars::$wave_table_map[$o->wave_table[$s]][$phase], $o, $s, 0);}function calc_fm(OPL $o, int $ch): int{    if ($o->ch_alg[$ch]) {        return s16(calc_slot_car($o, $ch, 0) + calc_slot_mod($o, $ch));    }    return calc_slot_car($o, $ch, calc_slot_mod($o, $ch));}function latch_timer1(OPL $o): void{    $o->timer1_counter = $o->reg[0x02] << 2;}function latch_timer2(OPL $o): void{    $o->timer2_counter = $o->reg[0x03] << 4;}function csm_key_on(OPL $o): void{    $o->csm_key_count = 1;    update_key_status($o);}function csm_key_off(OPL $o): void{    $o->csm_key_count = 0;    update_key_status($o);}function update_timer(OPL $o): void{    if ($o->csm_mode && 0 < $o->csm_key_count) {        csm_key_off($o);    }    if ($o->reg[0x04] & 0x01) {        $o->timer1_counter++;        if ($o->timer1_counter >> 10) {            $o->status |= 0x40; // timer1 overflow            if ($o->csm_mode) {                csm_key_on($o);            }            latch_timer1($o);        }    }    if ($o->reg[0x04] & 0x02) {        $o->timer2_counter++;        if ($o->timer2_counter >> 12) {            $o->status |= 0x20; // timer2 overflow            latch_timer2($o);        }    }}/** C static update_output() */function opl_update_output(OPL $o): void{    update_timer($o);    update_ampm($o);    update_short_noise($o);    update_slots($o);    /* CH1-6 */    for ($i = 0; $i < 6; $i++) {        if (!($o->mask & (1 << $i))) {            $o->ch_out[$i] = s16((-calc_fm($o, $i)) >> 1);        }    }    /* CH7 */    if (!$o->rhythm_mode) {        if (!($o->mask & (1 << 6))) {            $o->ch_out[6] = s16((-calc_fm($o, 6)) >> 1);        }    } else {        if (!($o->mask & OPL_MASK_BD)) {            $o->ch_out[9] = calc_fm($o, 6);        }    }    update_noise($o, 14);    /* CH8 */    if (!$o->rhythm_mode) {        if (!($o->mask & (1 << 7))) {            $o->ch_out[7] = s16((-calc_fm($o, 7)) >> 1);        }    } else {        if (!($o->mask & OPL_MASK_HH)) {            $o->ch_out[10] = calc_slot_hat($o);        }        if (!($o->mask & OPL_MASK_SD)) {            $o->ch_out[11] = calc_slot_snare($o);        }    }    update_noise($o, 2);    /* CH9 */    if (!$o->rhythm_mode) {        if (!($o->mask & (1 << 8))) {            $o->ch_out[8] = s16((-calc_fm($o, 8)) >> 1);        }    } else {        if (!($o->mask & OPL_MASK_TOM)) {            $o->ch_out[12] = calc_slot_tom($o);        }        if (!($o->mask & OPL_MASK_CYM)) {            $o->ch_out[13] = calc_slot_cym($o);        }    }    update_noise($o, 2);    /* ADPCM: opl->adpcm is always NULL (see the file header) */}/** C static mix_output() */function opl_mix_output(OPL $o): void{    $out = 0;    for ($i = 0; $i < 15; $i++) {        $out += $o->ch_out[$i];    }    $out = s16($out);    if ($o->conv) {        OPL_RateConv_putData($o->conv, 0, $out);    } else {        $o->mix_out[0] = $out;    }}/** C static mix_output_stereo() */function opl_mix_output_stereo(OPL $o): void{    $out0 = 0;    $out1 = 0;    for ($i = 0; $i < 15; $i++) {        if ($o->pan[$i] & 2) {            $out0 = s16($out0 + (int) ($o->ch_out[$i] * $o->pan_fine[$i][0]));        }        if ($o->pan[$i] & 1) {            $out1 = s16($out1 + (int) ($o->ch_out[$i] * $o->pan_fine[$i][1]));        }    }    $o->mix_out = [$out0, $out1];    if ($o->conv) {        OPL_RateConv_putData($o->conv, 0, $out0);        OPL_RateConv_putData($o->conv, 1, $out1);    }}/***********************************************************                   External Interfaces***********************************************************/function OPL_new(int $clk, int $rate): OPL{    if (!Emu8950Vars::$table_initialized) {        initializeTables();    }    $o = new OPL();    $o->adpcm = null;    $o->clk = $clk;    $o->rate = $rate;    $o->mask = 0;    $o->conv = null;    $o->mix_out = [0, 0];    OPL_reset($o);    return $o;}function OPL_delete(OPL $o): void{    $o->conv = null;    $o->adpcm = null;}function reset_rate_conversion_params(OPL $o): void{    $f_out = (float) $o->rate;    $f_inp = (float) intdiv($o->clk, 72);    $o->out_time = 0;    $o->out_step = ((int) $f_inp) << 8;    $o->inp_step = ((int) $f_out) << 8;    $o->conv = null;    if (floor($f_inp) != $f_out && floor($f_inp + 0.5) != $f_out) {        $o->conv = OPL_RateConv_new($f_inp, $f_out, 2);    }    if ($o->conv) {        OPL_RateConv_reset($o->conv);    }}function refresh_adpcm_object(OPL $o): void{    // PORT: the Y8950 ADPCM unit is not ported (see the file header): opl->adpcm stays NULL.    $o->adpcm = null;}function OPL_reset(?OPL $o): void{    if (!$o) {        return;    }    $o->adr = 0;    $o->csm_mode = 0;    $o->csm_key_count = 0;    $o->notesel = 0;    $o->status = 0;    $o->timer1_counter = 0;    $o->timer2_counter = 0;    $o->pm_phase = 0;    $o->am_phase = 0;    $o->noise = 1;    $o->mask = 0;    $o->rhythm_mode = 0;    $o->slot_key_status = 0;    $o->eg_counter = 0;    reset_rate_conversion_params($o);    for ($i = 0; $i < 18; $i++) {        reset_slot($o, $i, $i);    }    for ($i = 0; $i < 9; $i++) {        $o->ch_alg[$i] = 0;    }    for ($i = 0; $i < 0x100; $i++) {        $o->reg[$i] = 0;    }    $o->reg[0x04] = 0x18; // MASK_EOS | MASK_BUF_RDY    $o->pm_dphase = intdiv(OPL_PM_DP_WIDTH, 1024 * 8);    for ($i = 0; $i < 15; $i++) {        $o->pan[$i] = 3;        $o->pan_fine[$i] = [1.0, 1.0];    }    for ($i = 0; $i < 15; $i++) {        $o->ch_out[$i] = 0;    }    refresh_adpcm_object($o);}function OPL_setRate(OPL $o, int $rate): void{    $o->rate = $rate;    reset_rate_conversion_params($o);}function OPL_setQuality(OPL $o, int $q): void{}function OPL_setChipType(OPL $o, int $type): void{    if ($type < OPL_TYPE_MAX) {        $o->chip_type = $type;        refresh_adpcm_object($o);    }}function OPL_writeIO(OPL $o, int $adr, int $val): void{    if ($adr & 1) {        OPL_writeReg($o, $o->adr, $val);    } else {        $o->adr = $val & 0xff;    }}function OPL_setPan(OPL $o, int $ch, int $pan): void{    $o->pan[$ch & 15] = $pan & 0xff;}function OPL_setPanFine(OPL $o, int $ch, array $pan): void{    $o->pan_fine[$ch & 15] = [(float) $pan[0], (float) $pan[1]];}/** The faithful C OPL_calc() (one output sample): reference of OPL_calc_block(). */function OPL_calc_ref(OPL $o): int{    while ($o->out_step > $o->out_time) {        $o->out_time += $o->inp_step;        opl_update_output($o);        opl_mix_output($o);    }    $o->out_time -= $o->out_step;    if ($o->conv) {        $o->mix_out[0] = OPL_RateConv_getData($o->conv, 0);    }    return $o->mix_out[0];}function OPL_calc(OPL $o): int{    return OPL_calc_block($o, 1)[0];}function OPL_calcStereo(OPL $o, array &$out): void{    while ($o->out_step > $o->out_time) {        $o->out_time += $o->inp_step;        opl_update_output($o);        opl_mix_output_stereo($o);    }    $o->out_time -= $o->out_step;    if ($o->conv) {        $out[0] = OPL_RateConv_getData($o->conv, 0);        $out[1] = OPL_RateConv_getData($o->conv, 1);    } else {        $out[0] = $o->mix_out[0];        $out[1] = $o->mix_out[1];    }}function OPL_setMask(?OPL $o, int $mask): int{    if ($o) {        $ret = $o->mask;        $o->mask = $mask;        return $ret;    }    return 0;}function OPL_toggleMask(?OPL $o, int $mask): int{    if ($o) {        $ret = $o->mask;        $o->mask ^= $mask;        return $ret;    }    return 0;}function OPL_writeReg(OPL $o, int $reg, int $data): void{    $reg = $reg & 0xff;    $data &= 0xff;    if (($reg == 0x04) && ($data & 0x80)) {        // IRQ RESET        $o->status = 0;        $o->reg[0x04] &= 0x7f;        return;    }    $o->reg[$reg] = $data;    if ($reg == 0x01) {        $o->test_flag = $data;    } elseif ($reg == 0x04) {        if ($data & 0x01) {            latch_timer1($o);        }        if ($data & 0x02) {            latch_timer2($o);        }    } elseif (0x07 <= $reg && $reg <= 0x12) {        if ($reg == 0x08) {            $o->csm_mode = ($data >> 7) & 1;            $o->notesel = ($data >> 6) & 1;        }        // (ADPCM registers: no ADPCM unit)    } elseif (0x20 <= $reg && $reg < 0x40) {        $s = Emu8950Vars::stbl[$reg - 0x20];        if ($s >= 0) {            $o->AM[$s] = ($data >> 7) & 1;            $o->PM[$s] = ($data >> 6) & 1;            $o->EG[$s] = ($data >> 5) & 1;            $o->KR[$s] = ($data >> 4) & 1;            $o->ML[$s] = ($data) & 15;            request_update($o, $s, OPL_UPDATE_ALL);        }    } elseif (0x40 <= $reg && $reg < 0x60) {        $s = Emu8950Vars::stbl[$reg - 0x40];        if ($s >= 0) {            $o->KL[$s] = ($data >> 6) & 3;            $o->TL[$s] = ($data) & 63;            request_update($o, $s, OPL_UPDATE_ALL);        }    } elseif (0x60 <= $reg && $reg < 0x80) {        $s = Emu8950Vars::stbl[$reg - 0x60];        if ($s >= 0) {            $o->AR[$s] = ($data >> 4) & 15;            $o->DR[$s] = ($data) & 15;            request_update($o, $s, OPL_UPDATE_EG);        }    } elseif (0x80 <= $reg && $reg < 0xa0) {        $s = Emu8950Vars::stbl[$reg - 0x80];        if ($s >= 0) {            $o->SL[$s] = ($data >> 4) & 15;            $o->RR[$s] = ($data) & 15;            request_update($o, $s, OPL_UPDATE_EG);        }    } elseif (0xa0 <= $reg && $reg < 0xa9) {        $c = $reg - 0xa0;        set_fnumber($o, $c, $data + (($o->reg[$reg + 0x10] & 3) << 8));    } elseif (0xb0 <= $reg && $reg < 0xb9) {        $c = $reg - 0xb0;        set_fnumber($o, $c, (($data & 3) << 8) + $o->reg[$reg - 0x10]);        set_block($o, $c, ($data >> 2) & 7);        update_key_status($o);    } elseif (0xc0 <= $reg && $reg < 0xc9) {        $c = $reg - 0xc0;        $o->FB[$c * 2] = ($data >> 1) & 7;        $o->ch_alg[$c] = $data & 1;    } elseif ($reg == 0xbd) {        update_rhythm_mode($o);        update_key_status($o);        $o->am_mode = ($data >> 7) & 1;        $o->pm_mode = ($data >> 6) & 1;    } elseif (0xe0 <= $reg && $reg < 0x100) {        if ($o->chip_type == OPL_TYPE_YM3812 && ($o->reg[0x01] & 0x20)) {            $s = Emu8950Vars::stbl[$reg - 0xe0];            if ($s >= 0) {                $o->WS[$s] = $data & 3;                request_update($o, $s, OPL_UPDATE_WS);            }        }    }}function OPL_readIO(OPL $o): int{    return $o->reg[$o->adr];}function OPL_status(OPL $o): int{    $status = $o->status;    $status &= ~($o->reg[0x04] & 0x78) & 0xff; // IRQ MASK    if ($status & 0x78) {        return $status | 0x80; // IRQ=1    }    return $status & 0x7f; // IRQ = 0}function OPL_writeADPCMData(OPL $o, int $type, int $start, int $length, int $data): void{    // no ADPCM unit (see the file header)}/** * PORT (speed): $n successive OPL_calc() results in one call, bit-exact with OPL_calc_ref(). * * The chip state lives in local variables during the block. What makes it exact: * - the slot updates requested by register writes (made between two calls) are committed first: the C commits *   them at the next internal step, before anything reads them; * - the envelope parameters (rate_h, rate_l, shift, step table) of the 4 envelope states are precomputed per slot: *   a state change inside the block (attack -> decay -> sustain) just switches to the next set, as the C's *   request_update(UPDATE_EG) + commit at the next step does; * - a slot at the end of its release (eg_out = EG_MUTE, not attacking, both outputs 0, phase not kept) stays *   silent and unchanged until the next key-on (which resets its phase): it is skipped; * - the noise LFSR advances by tables (it is linear), the AM phase is kept modulo its period (13440); * - the sinc resampler taps come from a table per 1/256 of the fractional position (exact recomputation when *   the position is within 1e-9 of a table boundary). * Rhythm mode, CSM, the test register and channel masks fall back to the reference functions. */function OPL_calc_block(OPL $opl, int $n): array{    if ($n <= 0) {        return [];    }    if ($opl->rhythm_mode || $opl->csm_mode || $opl->test_flag || $opl->mask || $opl->adpcm !== null) {        $res = [];        for ($k = 0; $k < $n; $k++) {            $res[] = OPL_calc_ref($opl);        }        return $res;    }    // commit pending slot updates    $notesel = $opl->notesel;    for ($s = 0; $s < 18; $s++) {        if ($opl->update_requests[$s]) {            commit_slot_update($opl, $s, $notesel);        }    }    $fastT = Emu8950Vars::eg_step_tables_fast;    $normT = Emu8950Vars::eg_step_tables;    $zero8 = [0, 0, 0, 0, 0, 0, 0, 0];    $four8 = [4, 4, 4, 4, 4, 4, 4, 4];    $waves = Emu8950Vars::$wave_fast;    $mlT = Emu8950Vars::ml_table;    // per slot: envelope parameters of the 4 states [rate_h, mask, shift, steps] (envP), of the current state    // (cur), phase increment without PM (dph), wave table (wt), silent-until-key-on flag (dead)    $envP = [];    $cur = [];    $egState = $opl->eg_state;    $wt = [];    $dph = [];    $mlv = [];    $dead = [];    for ($s = 0; $s < 18; $s++) {        $rks = $opl->rks[$s];        for ($st = 0; $st < 4; $st++) {            switch ($st) {                case OPL_ATTACK: $p = $opl->AR[$s]; break;                case OPL_DECAY: $p = $opl->DR[$s]; break;                case OPL_SUSTAIN: $p = $opl->EG[$s] ? 0 : $opl->RR[$s]; break;                default: $p = $opl->RR[$s]; break;            }            if ($p == 0) {                $h = 0; $l = 0; $shf = 0;            } else {                $h = \min(15, $p + ($rks >> 2));                $l = $rks & 3;                if ($st == OPL_ATTACK) {                    $shf = (0 < $h && $h < 12) ? (12 - $h) : 0;                } else {                    $shf = ($h < 12) ? (12 - $h) : 0;                }            }            if ($st == OPL_ATTACK) {                $steps = match (true) {                    $h == 13 => $fastT[$l],                    $h == 14 => array_map(fn ($v) => $v << 1, $fastT[$l]),                    $h == 0 || $h == 15 => $zero8,                    default => $normT[$l],                };            } else {                $steps = match (true) {                    $h == 0 => $zero8,                    $h == 13 => $fastT[$l],                    $h == 14 => array_map(fn ($v) => $v << 1, $fastT[$l]),                    $h == 15 => $four8,                    default => $normT[$l],                };            }            $envP[$s][$st] = [$h, ((1 << $shf) - 1) & 0xffff, $shf, $steps];        }        $cur[$s] = $envP[$s][$egState[$s]];        $wt[$s] = $waves[$opl->wave_table[$s]];        $mlv[$s] = $mlT[$opl->ML[$s]];        $dph[$s] = (((($opl->fnum[$s] & 0x3ff) * $mlv[$s]) << $opl->blk[$s]) >> 1) & 0xfffff;        // (never the HH / CYM slots: their phase is kept at key-on once rhythm mode is turned on)        $dead[$s] = $opl->eg_out[$s] == OPL_EG_MUTE && $egState[$s] != OPL_ATTACK && !$opl->pg_keep[$s]            && $opl->output0[$s] == 0 && $opl->output1[$s] == 0 && $s != OPL_SLOT_HH && $s != OPL_SLOT_CYM;    }    // ch_out[9..14] (rhythm / ADPCM outputs) do not change outside rhythm mode    $chOut = $opl->ch_out;    $rest = $chOut[9] + $chOut[10] + $chOut[11] + $chOut[12] + $chOut[13] + $chOut[14];    return opl_calc_block_melodic($opl, $n, $envP, $cur, $dead, $mlv, $dph, $wt, $rest);}