/*
Copyright (c) 2021 Aaron Giles
Copyright (c) 2022 Rupert Carmichael
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// ======================> fm_engine

// fm_engine represents a set of operators and channels which together
// form a Yamaha FM core; chips that implement other engines (ADPCM, wavetable,
// etc) take this output and combine it with the others externally
// internal state
static uint32_t m_env_counter;          // envelope counter; low 2 bits are sub-counter
static uint8_t m_status;                // current status register
static uint8_t m_clock_prescale;        // prescale factor (2/3/6)
static uint8_t m_irq_mask;              // mask of which bits signal IRQs
static uint8_t m_irq_state;             // current IRQ state
static uint8_t m_timer_running[2];      // current timer running state
static uint8_t m_total_clocks;          // low 8 bits of the total number of clocks processed
static uint32_t m_active_channels;      // mask of active channels (computed by prepare)
static uint32_t m_modified_channels;    // mask of channels that have been modified
static uint32_t m_prepare_count;        // counter to do periodic prepare sweeps
static fm_channel m_channel[CHANNELS];  // channels
static fm_operator m_operator[OPERATORS]; // operators

//*********************************************************
//  GLOBAL TABLE LOOKUPS
//*********************************************************

//-------------------------------------------------
//  abs_sin_attenuation - given a sin (phase) input
//  where the range 0-2*PI is mapped onto 10 bits,
//  return the absolute value of sin(input),
//  logarithmically-adjusted and treated as an
//  attenuation value, in 4.8 fixed point format
//-------------------------------------------------

inline uint32_t abs_sin_attenuation(uint32_t input)
{
	// the values here are stored as 4.8 logarithmic values for 1/4 phase
	// this matches the internal format of the OPN chip, extracted from the die
	static uint16_t const s_sin_table[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
	};

	// if the top bit is set, we're in the second half of the curve
	// which is a mirror image, so invert the index
	if (bitfield(input, 8, 1))
		input = ~input;

	// return the value from the table
	return s_sin_table[input & 0xff];
}


//-------------------------------------------------
//  attenuation_to_volume - given a 5.8 fixed point
//  logarithmic attenuation value, return a 13-bit
//  linear volume
//-------------------------------------------------

inline uint32_t attenuation_to_volume(uint32_t input)
{
	// the values here are 10-bit mantissas with an implied leading bit
	// this matches the internal format of the OPN chip, extracted from the die

	// as a nod to performance, the implicit 0x400 bit is pre-incorporated, and
	// the values are left-shifted by 2 so that a simple right shift is all that
	// is needed; also the order is reversed to save a NOT on the input
#define X(a) (((a) | 0x400) << 2)
	static uint16_t const s_power_table[256] =
	{
		X(0x3fa),X(0x3f5),X(0x3ef),X(0x3ea),X(0x3e4),X(0x3df),X(0x3da),X(0x3d4),
		X(0x3cf),X(0x3c9),X(0x3c4),X(0x3bf),X(0x3b9),X(0x3b4),X(0x3ae),X(0x3a9),
		X(0x3a4),X(0x39f),X(0x399),X(0x394),X(0x38f),X(0x38a),X(0x384),X(0x37f),
		X(0x37a),X(0x375),X(0x370),X(0x36a),X(0x365),X(0x360),X(0x35b),X(0x356),
		X(0x351),X(0x34c),X(0x347),X(0x342),X(0x33d),X(0x338),X(0x333),X(0x32e),
		X(0x329),X(0x324),X(0x31f),X(0x31a),X(0x315),X(0x310),X(0x30b),X(0x306),
		X(0x302),X(0x2fd),X(0x2f8),X(0x2f3),X(0x2ee),X(0x2e9),X(0x2e5),X(0x2e0),
		X(0x2db),X(0x2d6),X(0x2d2),X(0x2cd),X(0x2c8),X(0x2c4),X(0x2bf),X(0x2ba),
		X(0x2b5),X(0x2b1),X(0x2ac),X(0x2a8),X(0x2a3),X(0x29e),X(0x29a),X(0x295),
		X(0x291),X(0x28c),X(0x288),X(0x283),X(0x27f),X(0x27a),X(0x276),X(0x271),
		X(0x26d),X(0x268),X(0x264),X(0x25f),X(0x25b),X(0x257),X(0x252),X(0x24e),
		X(0x249),X(0x245),X(0x241),X(0x23c),X(0x238),X(0x234),X(0x230),X(0x22b),
		X(0x227),X(0x223),X(0x21e),X(0x21a),X(0x216),X(0x212),X(0x20e),X(0x209),
		X(0x205),X(0x201),X(0x1fd),X(0x1f9),X(0x1f5),X(0x1f0),X(0x1ec),X(0x1e8),
		X(0x1e4),X(0x1e0),X(0x1dc),X(0x1d8),X(0x1d4),X(0x1d0),X(0x1cc),X(0x1c8),
		X(0x1c4),X(0x1c0),X(0x1bc),X(0x1b8),X(0x1b4),X(0x1b0),X(0x1ac),X(0x1a8),
		X(0x1a4),X(0x1a0),X(0x19c),X(0x199),X(0x195),X(0x191),X(0x18d),X(0x189),
		X(0x185),X(0x181),X(0x17e),X(0x17a),X(0x176),X(0x172),X(0x16f),X(0x16b),
		X(0x167),X(0x163),X(0x160),X(0x15c),X(0x158),X(0x154),X(0x151),X(0x14d),
		X(0x149),X(0x146),X(0x142),X(0x13e),X(0x13b),X(0x137),X(0x134),X(0x130),
		X(0x12c),X(0x129),X(0x125),X(0x122),X(0x11e),X(0x11b),X(0x117),X(0x114),
		X(0x110),X(0x10c),X(0x109),X(0x106),X(0x102),X(0x0ff),X(0x0fb),X(0x0f8),
		X(0x0f4),X(0x0f1),X(0x0ed),X(0x0ea),X(0x0e7),X(0x0e3),X(0x0e0),X(0x0dc),
		X(0x0d9),X(0x0d6),X(0x0d2),X(0x0cf),X(0x0cc),X(0x0c8),X(0x0c5),X(0x0c2),
		X(0x0be),X(0x0bb),X(0x0b8),X(0x0b5),X(0x0b1),X(0x0ae),X(0x0ab),X(0x0a8),
		X(0x0a4),X(0x0a1),X(0x09e),X(0x09b),X(0x098),X(0x094),X(0x091),X(0x08e),
		X(0x08b),X(0x088),X(0x085),X(0x082),X(0x07e),X(0x07b),X(0x078),X(0x075),
		X(0x072),X(0x06f),X(0x06c),X(0x069),X(0x066),X(0x063),X(0x060),X(0x05d),
		X(0x05a),X(0x057),X(0x054),X(0x051),X(0x04e),X(0x04b),X(0x048),X(0x045),
		X(0x042),X(0x03f),X(0x03c),X(0x039),X(0x036),X(0x033),X(0x030),X(0x02d),
		X(0x02a),X(0x028),X(0x025),X(0x022),X(0x01f),X(0x01c),X(0x019),X(0x016),
		X(0x014),X(0x011),X(0x00e),X(0x00b),X(0x008),X(0x006),X(0x003),X(0x000)
	};
#undef X

	// look up the fractional part, then shift by the whole
	return s_power_table[input & 0xff] >> (input >> 8);
}


//-------------------------------------------------
//  attenuation_increment - given a 6-bit ADSR
//  rate value and a 3-bit stepping index,
//  return a 4-bit increment to the attenutaion
//  for this step (or for the attack case, the
//  fractional scale factor to decrease by)
//-------------------------------------------------

inline uint32_t attenuation_increment(uint32_t rate, uint32_t index)
{
	static uint32_t const s_increment_table[64] =
	{
		0x00000000, 0x00000000, 0x10101010, 0x10101010,  // 0-3    (0x00-0x03)
		0x10101010, 0x10101010, 0x11101110, 0x11101110,  // 4-7    (0x04-0x07)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 8-11   (0x08-0x0B)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 12-15  (0x0C-0x0F)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 16-19  (0x10-0x13)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 20-23  (0x14-0x17)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 24-27  (0x18-0x1B)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 28-31  (0x1C-0x1F)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 32-35  (0x20-0x23)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 36-39  (0x24-0x27)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 40-43  (0x28-0x2B)
		0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 44-47  (0x2C-0x2F)
		0x11111111, 0x21112111, 0x21212121, 0x22212221,  // 48-51  (0x30-0x33)
		0x22222222, 0x42224222, 0x42424242, 0x44424442,  // 52-55  (0x34-0x37)
		0x44444444, 0x84448444, 0x84848484, 0x88848884,  // 56-59  (0x38-0x3B)
		0x88888888, 0x88888888, 0x88888888, 0x88888888   // 60-63  (0x3C-0x3F)
	};
	return bitfield(s_increment_table[rate], 4*index, 4);
}


//-------------------------------------------------
//  detune_adjustment - given a 5-bit key code
//  value and a 3-bit detune parameter, return a
//  6-bit signed phase displacement; this table
//  has been verified against Nuked's equations,
//  but the equations are rather complicated, so
//  we'll keep the simplicity of the table
//-------------------------------------------------

inline int32_t detune_adjustment(uint32_t detune, uint32_t keycode)
{
	static uint8_t const s_detune_adjustment[32][4] =
	{
		{ 0,  0,  1,  2 },  { 0,  0,  1,  2 },  { 0,  0,  1,  2 },  { 0,  0,  1,  2 },
		{ 0,  1,  2,  2 },  { 0,  1,  2,  3 },  { 0,  1,  2,  3 },  { 0,  1,  2,  3 },
		{ 0,  1,  2,  4 },  { 0,  1,  3,  4 },  { 0,  1,  3,  4 },  { 0,  1,  3,  5 },
		{ 0,  2,  4,  5 },  { 0,  2,  4,  6 },  { 0,  2,  4,  6 },  { 0,  2,  5,  7 },
		{ 0,  2,  5,  8 },  { 0,  3,  6,  8 },  { 0,  3,  6,  9 },  { 0,  3,  7, 10 },
		{ 0,  4,  8, 11 },  { 0,  4,  8, 12 },  { 0,  4,  9, 13 },  { 0,  5, 10, 14 },
		{ 0,  5, 11, 16 },  { 0,  6, 12, 17 },  { 0,  6, 13, 19 },  { 0,  7, 14, 20 },
		{ 0,  8, 16, 22 },  { 0,  8, 16, 22 },  { 0,  8, 16, 22 },  { 0,  8, 16, 22 }
	};
	int32_t result = s_detune_adjustment[keycode][detune & 3];
	return bitfield(detune, 2, 1) ? -result : result;
}


//-------------------------------------------------
//  opn_lfo_pm_phase_adjustment - given the 7 most
//  significant frequency number bits, plus a 3-bit
//  PM depth value and a signed 5-bit raw PM value,
//  return a signed PM adjustment to the frequency;
//  algorithm written to match Nuked behavior
//-------------------------------------------------

inline int32_t opn_lfo_pm_phase_adjustment(uint32_t fnum_bits, uint32_t pm_sensitivity, int32_t lfo_raw_pm)
{
	// this table encodes 2 shift values to apply to the top 7 bits
	// of fnum; it is effectively a cheap multiply by a constant
	// value containing 0-2 bits
	static uint8_t const s_lfo_pm_shifts[8][8] =
	{
		{ 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77 },
		{ 0x77, 0x77, 0x77, 0x77, 0x72, 0x72, 0x72, 0x72 },
		{ 0x77, 0x77, 0x77, 0x72, 0x72, 0x72, 0x17, 0x17 },
		{ 0x77, 0x77, 0x72, 0x72, 0x17, 0x17, 0x12, 0x12 },
		{ 0x77, 0x77, 0x72, 0x17, 0x17, 0x17, 0x12, 0x07 },
		{ 0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01 },
		{ 0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01 },
		{ 0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01 }
	};

	// look up the relevant shifts
	int32_t abs_pm = (lfo_raw_pm < 0) ? -lfo_raw_pm : lfo_raw_pm;
	uint32_t const shifts = s_lfo_pm_shifts[pm_sensitivity][bitfield(abs_pm, 0, 3)];

	// compute the adjustment
	int32_t adjust = (fnum_bits >> bitfield(shifts, 0, 4)) + (fnum_bits >> bitfield(shifts, 4, 4));
	if (pm_sensitivity > 5)
		adjust <<= pm_sensitivity - 5;
	adjust >>= 2;

	// every 16 cycles it inverts sign
	return (lfo_raw_pm < 0) ? -adjust : adjust;
}


// map channel number to register offset
static inline uint32_t channel_offset(uint32_t chnum)
{
	assert(chnum < CHANNELS);
	return (chnum % 3) + 0x100 * (chnum / 3);
}

// map operator number to register offset
static inline uint32_t operator_offset(uint32_t opnum)
{
	assert(opnum < OPERATORS);
	return (opnum % 12) + ((opnum % 12) / 3) + 0x100 * (opnum / 12);
}

//*********************************************************
//  FM OPERATOR
//*********************************************************

//-------------------------------------------------
//  fm_operator - init
//-------------------------------------------------

static inline void fm_operator_init(fm_operator *op, uint32_t opoffs)
{
	op->m_choffs = 0;
	op->m_opoffs = opoffs;
	op->m_phase = 0;
	op->m_env_attenuation = 0x3ff;
	op->m_env_state = EG_RELEASE;
	op->m_ssg_inverted = false;
	op->m_key_state = 0;
	op->m_keyon_live = 0;
}


//-------------------------------------------------
//  reset - reset the channel state
//-------------------------------------------------

static inline void fm_operator_reset(fm_operator *op)
{
	// reset our data
	op->m_phase = 0;
	op->m_env_attenuation = 0x3ff;
	op->m_env_state = EG_RELEASE;
	op->m_ssg_inverted = 0;
	op->m_key_state = 0;
	op->m_keyon_live = 0;
}


// set the current channel
static inline void fm_operator_set_choffs(fm_operator *op, uint32_t choffs) {
	op->m_choffs = choffs;
}


static inline uint32_t fm_operator_phase(fm_operator *op) {
	return op->m_phase >> 10;
}


//-------------------------------------------------
//  start_attack - start the attack phase; called
//  when a keyon happens or when an SSG-EG cycle
//  is complete and restarts
//-------------------------------------------------

static inline void fm_operator_start_attack(fm_operator *op, bool is_restart)
{
	// don't change anything if already in attack state
	if (op->m_env_state == EG_ATTACK)
		return;
	op->m_env_state = EG_ATTACK;

	// generally not inverted at start, except if SSG-EG is enabled and
	// one of the inverted modes is specified; leave this alone on a
	// restart, as it is managed by the clock_ssg_eg_state() code
	if (EG_HAS_SSG && !is_restart)
		op->m_ssg_inverted = opn_registers_op_ssg_eg_enable(op->m_opoffs) &
			bitfield(opn_registers_op_ssg_eg_mode(op->m_opoffs), 2, 1);

	// reset the phase when we start an attack due to a key on
	// (but not when due to an SSG-EG restart except in certain cases
	// managed directly by the SSG-EG code)
	if (!is_restart)
		op->m_phase = 0;

	// if the attack rate >= 62 then immediately go to max attenuation
	if (op->m_cache.eg_rate[EG_ATTACK] >= 62)
		op->m_env_attenuation = 0;
}


//-------------------------------------------------
//  start_release - start the release phase;
//  called when a keyoff happens
//-------------------------------------------------

static inline void fm_operator_start_release(fm_operator *op)
{
	// don't change anything if already in release state
	if (op->m_env_state >= EG_RELEASE)
		return;
	op->m_env_state = EG_RELEASE;

	// if attenuation if inverted due to SSG-EG, snap the inverted attenuation
	// as the starting point
	if (EG_HAS_SSG && op->m_ssg_inverted)
	{
		op->m_env_attenuation = (0x200 - op->m_env_attenuation) & 0x3ff;
		op->m_ssg_inverted = false;
	}
}


//-------------------------------------------------
//  clock_keystate - clock the keystate to match
//  the incoming keystate
//-------------------------------------------------

static inline void fm_operator_clock_keystate(fm_operator *op, uint32_t keystate)
{
	assert(keystate == 0 || keystate == 1);

	// has the key changed?
	if ((keystate ^ op->m_key_state) != 0)
	{
		op->m_key_state = keystate;

		// if the key has turned on, start the attack
		if (keystate != 0)
		{
			// OPLL has a DP ("depress"?) state to bring the volume
			// down before starting the attack
			if (EG_HAS_DEPRESS && op->m_env_attenuation < 0x200)
				op->m_env_state = EG_DEPRESS;
			else
				fm_operator_start_attack(op, false);
		}

		// otherwise, start the release
		else
			fm_operator_start_release(op);
	}
}


//-------------------------------------------------
//  prepare - prepare for clocking
//-------------------------------------------------

static inline bool fm_operator_prepare(fm_operator *op)
{
	// cache the data
	opn_registers_cache_operator_data(op->m_choffs, op->m_opoffs, &(op->m_cache));

	// clock the key state
	fm_operator_clock_keystate(op, (uint32_t)(op->m_keyon_live != 0));
	op->m_keyon_live &= ~(1 << KEYON_CSM);

	// we're active until we're quiet after the release
	return (op->m_env_state != (EG_HAS_REVERB ? EG_REVERB : EG_RELEASE) || op->m_env_attenuation < EG_QUIET);
}


//-------------------------------------------------
//  envelope_attenuation - return the effective
//  attenuation of the envelope
//-------------------------------------------------

static inline uint32_t fm_operator_envelope_attenuation(fm_operator *op, uint32_t am_offset)
{
	uint32_t result = op->m_env_attenuation >> op->m_cache.eg_shift;

	// invert if necessary due to SSG-EG
	if (EG_HAS_SSG && op->m_ssg_inverted)
		result = (0x200 - result) & 0x3ff;

	// add in LFO AM modulation
	if (opn_registers_op_lfo_am_enable(op->m_opoffs))
		result += am_offset;

	// add in total level and KSL from the cache
	result += op->m_cache.total_level;

	// clamp to max, apply shift, and return
	return (result < 0x3ff) ? result : 0x3ff;
}


//-------------------------------------------------
//  compute_volume - compute the 14-bit signed
//  volume of this operator, given a phase
//  modulation and an AM LFO offset
//-------------------------------------------------

static inline int32_t fm_operator_compute_volume(fm_operator *op, uint32_t phase, uint32_t am_offset)
{
	// the low 10 bits of phase represents a full 2*PI period over
	// the full sin wave

	// early out if the envelope is effectively off
	if (op->m_env_attenuation > EG_QUIET)
		return 0;

	// get the absolute value of the sin, as attenuation, as a 4.8 fixed point value
	uint32_t sin_attenuation = op->m_cache.waveform[phase & (WAVEFORM_LENGTH - 1)];

	// get the attenuation from the evelope generator as a 4.6 value, shifted up to 4.8
	uint32_t env_attenuation = fm_operator_envelope_attenuation(op, am_offset) << 2;

	// combine into a 5.8 value, then convert from attenuation to 13-bit linear volume
	int32_t result = attenuation_to_volume((sin_attenuation & 0x7fff) + env_attenuation);

	// negate if in the negative part of the sin wave (sign bit gives 14 bits)
	return bitfield(sin_attenuation, 15, 1) ? -result : result;
}


//-------------------------------------------------
//  compute_noise_volume - compute the 14-bit
//  signed noise volume of this operator, given a
//  noise input value and an AM offset
//-------------------------------------------------

static inline int32_t fm_operator_compute_noise_volume(fm_operator *op, uint32_t am_offset)
{
	// application manual says the logarithmic transform is not applied here, so we
	// just use the raw envelope attenuation, inverted (since 0 attenuation should be
	// maximum), and shift it up from a 10-bit value to an 11-bit value
	int32_t result = (fm_operator_envelope_attenuation(op, am_offset) ^ 0x3ff) << 1;

	// QUESTION: is AM applied still?

	// negate based on the noise state
	return bitfield(opn_registers_noise_state(), 0, 1) ? -result : result;
}


//-------------------------------------------------
//  keyonoff - signal a key on/off event
//-------------------------------------------------

static inline void fm_operator_keyonoff(fm_operator *op, uint32_t on, uint32_t type)
{
	op->m_keyon_live = (op->m_keyon_live & ~(1 << (int)(type))) | (bitfield(on, 0, 1) << (int)(type));
}


//-------------------------------------------------
//  clock_ssg_eg_state - clock the SSG-EG state;
//  should only be called if SSG-EG is enabled
//-------------------------------------------------

static inline void fm_operator_clock_ssg_eg_state(fm_operator *op)
{
	// work only happens once the attenuation crosses above 0x200
	if (!bitfield(op->m_env_attenuation, 9, 1))
		return;

	// 8 SSG-EG modes:
	//    000: repeat normally
	//    001: run once, hold low
	//    010: repeat, alternating between inverted/non-inverted
	//    011: run once, hold high
	//    100: inverted repeat normally
	//    101: inverted run once, hold low
	//    110: inverted repeat, alternating between inverted/non-inverted
	//    111: inverted run once, hold high
	uint32_t mode = opn_registers_op_ssg_eg_mode(op->m_opoffs);

	// hold modes (1/3/5/7)
	if (bitfield(mode, 0, 1))
	{
		// set the inverted flag to the end state (0 for modes 1/7, 1 for modes 3/5)
		op->m_ssg_inverted = bitfield(mode, 2, 1) ^ bitfield(mode, 1, 1);

		// if holding, force the attenuation to the expected value once we're
		// past the attack phase
		if (op->m_env_state != EG_ATTACK)
			op->m_env_attenuation = op->m_ssg_inverted ? 0x200 : 0x3ff;
	}

	// continuous modes (0/2/4/6)
	else
	{
		// toggle invert in alternating mode (even in attack state)
		op->m_ssg_inverted ^= bitfield(mode, 1, 1);

		// restart attack if in decay/sustain states
		if (op->m_env_state == EG_DECAY || op->m_env_state == EG_SUSTAIN)
			fm_operator_start_attack(op, true);

		// phase is reset to 0 in modes 0/4
		if (bitfield(mode, 1, 1) == 0)
			op->m_phase = 0;
	}

	// in all modes, once we hit release state, attenuation is forced to maximum
	if (op->m_env_state == EG_RELEASE)
		op->m_env_attenuation = 0x3ff;
}


//-------------------------------------------------
//  clock_envelope - clock the envelope state
//  according to the given count
//-------------------------------------------------

static inline void fm_operator_clock_envelope(fm_operator *op, uint32_t env_counter)
{
	// handle attack->decay transitions
	if (op->m_env_state == EG_ATTACK && op->m_env_attenuation == 0)
		op->m_env_state = EG_DECAY;

	// handle decay->sustain transitions; it is important to do this immediately
	// after the attack->decay transition above in the event that the sustain level
	// is set to 0 (in which case we will skip right to sustain without doing any
	// decay); as an example where this can be heard, check the cymbals sound
	// in channel 0 of shinobi's test mode sound #5
	if (op->m_env_state == EG_DECAY && op->m_env_attenuation >= op->m_cache.eg_sustain)
		op->m_env_state = EG_SUSTAIN;

	// fetch the appropriate 6-bit rate value from the cache
	uint32_t rate = op->m_cache.eg_rate[op->m_env_state];

	// compute the rate shift value; this is the shift needed to
	// apply to the env_counter such that it becomes a 5.11 fixed
	// point number
	uint32_t rate_shift = rate >> 2;
	env_counter <<= rate_shift;

	// see if the fractional part is 0; if not, it's not time to clock
	if (bitfield(env_counter, 0, 11) != 0)
		return;

	// determine the increment based on the non-fractional part of env_counter
	uint32_t relevant_bits = bitfield(env_counter, (rate_shift <= 11) ? 11 : rate_shift, 3);
	uint32_t increment = attenuation_increment(rate, relevant_bits);

	// attack is the only one that increases
	if (op->m_env_state == EG_ATTACK)
	{
		// glitch means that attack rates of 62/63 don't increment if
		// changed after the initial key on (where they are handled
		// specially); nukeykt confirms this happens on OPM, OPN, OPL/OPLL
		// at least so assuming it is true for everyone
		if (rate < 62)
			op->m_env_attenuation += (~op->m_env_attenuation * increment) >> 4;
	}

	// all other cases are similar
	else
	{
		// non-SSG-EG cases just apply the increment
		if (!opn_registers_op_ssg_eg_enable(op->m_opoffs))
			op->m_env_attenuation += increment;

		// SSG-EG only applies if less than mid-point, and then at 4x
		else if (op->m_env_attenuation < 0x200)
			op->m_env_attenuation += 4 * increment;

		// clamp the final attenuation
		if (op->m_env_attenuation >= 0x400)
			op->m_env_attenuation = 0x3ff;

		// transition from depress to attack
		if (EG_HAS_DEPRESS && op->m_env_state == EG_DEPRESS && op->m_env_attenuation >= 0x200)
			fm_operator_start_attack(op, false);

		// transition from release to reverb, should switch at -18dB
		if (EG_HAS_REVERB && op->m_env_state == EG_RELEASE && op->m_env_attenuation >= 0xc0)
			op->m_env_state = EG_REVERB;
	}
}


//-------------------------------------------------
//  clock_phase - clock the 10.10 phase value; the
//  OPN version of the logic has been verified
//  against the Nuked phase generator
//-------------------------------------------------

static inline void fm_operator_clock_phase(fm_operator *op, int32_t lfo_raw_pm)
{
	// read from the cache, or recalculate if PM active
	uint32_t phase_step = op->m_cache.phase_step;
	if (phase_step == PHASE_STEP_DYNAMIC)
		phase_step = opn_registers_compute_phase_step(op->m_choffs, &(op->m_cache), lfo_raw_pm);

	// finally apply the step to the current phase value
	op->m_phase += phase_step;
}


//-------------------------------------------------
//  clock - master clocking function
//-------------------------------------------------

static inline void fm_operator_clock(fm_operator *op, uint32_t env_counter, int32_t lfo_raw_pm)
{
	// clock the SSG-EG state (OPN/OPNA)
	if (opn_registers_op_ssg_eg_enable(op->m_opoffs))
		fm_operator_clock_ssg_eg_state(op);
	else
		op->m_ssg_inverted = false;

	// clock the envelope if on an envelope cycle; env_counter is a x.2 value
	if (bitfield(env_counter, 0, 2) == 0)
		fm_operator_clock_envelope(op, env_counter >> 2);

	// clock the phase
	fm_operator_clock_phase(op, lfo_raw_pm);
}


//*********************************************************
//  FM CHANNEL
//*********************************************************

//-------------------------------------------------
//  fm_channel - init
//-------------------------------------------------

static inline void fm_channel_init(fm_channel *ch, uint32_t choffs)
{
	ch->m_choffs = choffs;
	ch->m_feedback[0] = ch->m_feedback[1] = 0;
	ch->m_feedback_in = 0;
	ch->m_op[0] = ch->m_op[1] = ch->m_op[2] = ch->m_op[3] = NULL;
}


//-------------------------------------------------
//  reset - reset the channel state
//-------------------------------------------------

static inline void fm_channel_reset(fm_channel *ch)
{
	// reset our data
	ch->m_feedback[0] = ch->m_feedback[1] = 0;
	ch->m_feedback_in = 0;
}


// assign operators
static inline void fm_channel_assign(fm_channel *ch, uint32_t index, fm_operator *op) {
	assert(index < 4);
	ch->m_op[index] = op;
	if (op != NULL)
		fm_operator_set_choffs(op, ch->m_choffs);
}


//-------------------------------------------------
//  keyonoff - signal key on/off to our operators
//-------------------------------------------------

static inline void fm_channel_keyonoff(fm_channel *ch, uint32_t states, uint32_t type)
{
	for (uint32_t opnum = 0; opnum < 4; opnum++)
		if (ch->m_op[opnum] != NULL)
			fm_operator_keyonoff(ch->m_op[opnum], bitfield(states, opnum, 1), type);
}


//-------------------------------------------------
//  prepare - prepare for clocking
//-------------------------------------------------

static inline bool fm_channel_prepare(fm_channel *ch)
{
	uint32_t active_mask = 0;

	// prepare all operators and determine if they are active
	for (uint32_t opnum = 0; opnum < 4; opnum++)
		if (ch->m_op[opnum] != NULL)
			if (fm_operator_prepare(ch->m_op[opnum]))
				active_mask |= 1 << opnum;

	return (active_mask != 0);
}


//-------------------------------------------------
//  clock - master clock of all operators
//-------------------------------------------------

static inline void fm_channel_clock(fm_channel *ch, uint32_t env_counter, int32_t lfo_raw_pm)
{
	// clock the feedback through
	ch->m_feedback[0] = ch->m_feedback[1];
	ch->m_feedback[1] = ch->m_feedback_in;

	for (uint32_t opnum = 0; opnum < 4; opnum++)
		if (ch->m_op[opnum] != NULL)
			fm_operator_clock(ch->m_op[opnum], env_counter, lfo_raw_pm);
}


// helper to add values to the outputs based on channel enables
static inline void fm_channel_add_to_output(uint32_t choffs, int32_t *output, int32_t value) {
	int out0_index = 0;
	int out1_index = 1 % OUTPUTS;
	int out2_index = 2 % OUTPUTS;
	int out3_index = 3 % OUTPUTS;

	if (OUTPUTS == 1 || opn_registers_ch_output_0(choffs))
		output[out0_index] += value;
	if (OUTPUTS >= 2 && opn_registers_ch_output_1(choffs))
		output[out1_index] += value;
	if (OUTPUTS >= 3 && opn_registers_ch_output_2(choffs))
		output[out2_index] += value;
	if (OUTPUTS >= 4 && opn_registers_ch_output_3(choffs))
		output[out3_index] += value;
}


//-------------------------------------------------
//  output_2op - combine 4 operators according to
//  the specified algorithm, returning a sum
//  according to the rshift and clipmax parameters,
//  which vary between different implementations
//-------------------------------------------------

static inline void fm_channel_output_2op(fm_channel *ch, int32_t *output, uint32_t rshift, int32_t clipmax)
{
	// The first 2 operators should be populated
	assert(ch->m_op[0] != NULL);
	assert(ch->m_op[1] != NULL);

	// AM amount is the same across all operators; compute it once
	uint32_t am_offset = opn_registers_lfo_am_offset(ch->m_choffs);

	// operator 1 has optional self-feedback
	int32_t opmod = 0;
	uint32_t feedback = opn_registers_ch_feedback(ch->m_choffs);
	if (feedback != 0)
		opmod = (ch->m_feedback[0] + ch->m_feedback[1]) >> (10 - feedback);

	// compute the 14-bit volume/value of operator 1 and update the feedback
	int32_t op1value = ch->m_feedback_in = fm_operator_compute_volume(ch->m_op[0], fm_operator_phase(ch->m_op[0]) + opmod, am_offset);

	// now that the feedback has been computed, skip the rest if all volumes
	// are clear; no need to do all this work for nothing
	if (opn_registers_ch_output_any(ch->m_choffs) == 0)
		return;

	// Algorithms for two-operator case:
	//    0: O1 -> O2 -> out
	//    1: (O1 + O2) -> out
	int32_t result;
	if (bitfield(opn_registers_ch_algorithm(ch->m_choffs), 0, 1) == 0)
	{
		// some OPL chips use the previous sample for modulation instead of
		// the current sample
		opmod = (MODULATOR_DELAY ? ch->m_feedback[1] : op1value) >> 1;
		result = fm_operator_compute_volume(ch->m_op[1], fm_operator_phase(ch->m_op[1]) + opmod, am_offset) >> rshift;
	}
	else
	{
		result = (MODULATOR_DELAY ? ch->m_feedback[1] : op1value) >> rshift;
		result += fm_operator_compute_volume(ch->m_op[1], fm_operator_phase(ch->m_op[1]), am_offset) >> rshift;
		int32_t clipmin = -clipmax - 1;
		result = clamp(result, clipmin, clipmax);
	}

	// add to the output
	fm_channel_add_to_output(ch->m_choffs, output, result);
}


//-------------------------------------------------
//  output_4op - combine 4 operators according to
//  the specified algorithm, returning a sum
//  according to the rshift and clipmax parameters,
//  which vary between different implementations
//-------------------------------------------------

static inline void fm_channel_output_4op(fm_channel *ch, int32_t *output, uint32_t rshift, int32_t clipmax)
{
	// all 4 operators should be populated
	assert(ch->m_op[0] != NULL);
	assert(ch->m_op[1] != NULL);
	assert(ch->m_op[2] != NULL);
	assert(ch->m_op[3] != NULL);

	// AM amount is the same across all operators; compute it once
	uint32_t am_offset = opn_registers_lfo_am_offset(ch->m_choffs);

	// operator 1 has optional self-feedback
	int32_t opmod = 0;
	uint32_t feedback = opn_registers_ch_feedback(ch->m_choffs);
	if (feedback != 0)
		opmod = (ch->m_feedback[0] + ch->m_feedback[1]) >> (10 - feedback);

	// compute the 14-bit volume/value of operator 1 and update the feedback
	int32_t op1value = ch->m_feedback_in = fm_operator_compute_volume(ch->m_op[0], fm_operator_phase(ch->m_op[0]) + opmod, am_offset);

	// now that the feedback has been computed, skip the rest if all volumes
	// are clear; no need to do all this work for nothing
	if (opn_registers_ch_output_any(ch->m_choffs) == 0)
		return;

	// OPM/OPN offer 8 different connection algorithms for 4 operators,
	// and OPL3 offers 4 more, which we designate here as 8-11.
	//
	// The operators are computed in order, with the inputs pulled from
	// an array of values (opout) that is populated as we go:
	//    0 = 0
	//    1 = O1
	//    2 = O2
	//    3 = O3
	//    4 = (O4)
	//    5 = O1+O2
	//    6 = O1+O3
	//    7 = O2+O3
	//
	// The s_algorithm_ops table describes the inputs and outputs of each
	// algorithm as follows:
	//
	//      ---------x use opout[x] as operator 2 input
	//      ------xxx- use opout[x] as operator 3 input
	//      ---xxx---- use opout[x] as operator 4 input
	//      --x------- include opout[1] in final sum
	//      -x-------- include opout[2] in final sum
	//      x--------- include opout[3] in final sum
	#define ALGORITHM(op2in, op3in, op4in, op1out, op2out, op3out) \
		((op2in) | ((op3in) << 1) | ((op4in) << 4) | ((op1out) << 7) | ((op2out) << 8) | ((op3out) << 9))
	static uint16_t const s_algorithm_ops[8+4] =
	{
		ALGORITHM(1,2,3, 0,0,0),    //  0: O1 -> O2 -> O3 -> O4 -> out (O4)
		ALGORITHM(0,5,3, 0,0,0),    //  1: (O1 + O2) -> O3 -> O4 -> out (O4)
		ALGORITHM(0,2,6, 0,0,0),    //  2: (O1 + (O2 -> O3)) -> O4 -> out (O4)
		ALGORITHM(1,0,7, 0,0,0),    //  3: ((O1 -> O2) + O3) -> O4 -> out (O4)
		ALGORITHM(1,0,3, 0,1,0),    //  4: ((O1 -> O2) + (O3 -> O4)) -> out (O2+O4)
		ALGORITHM(1,1,1, 0,1,1),    //  5: ((O1 -> O2) + (O1 -> O3) + (O1 -> O4)) -> out (O2+O3+O4)
		ALGORITHM(1,0,0, 0,1,1),    //  6: ((O1 -> O2) + O3 + O4) -> out (O2+O3+O4)
		ALGORITHM(0,0,0, 1,1,1),    //  7: (O1 + O2 + O3 + O4) -> out (O1+O2+O3+O4)
		ALGORITHM(1,2,3, 0,0,0),    //  8: O1 -> O2 -> O3 -> O4 -> out (O4)         [same as 0]
		ALGORITHM(0,2,3, 1,0,0),    //  9: (O1 + (O2 -> O3 -> O4)) -> out (O1+O4)   [unique]
		ALGORITHM(1,0,3, 0,1,0),    // 10: ((O1 -> O2) + (O3 -> O4)) -> out (O2+O4) [same as 4]
		ALGORITHM(0,2,0, 1,0,1)     // 11: (O1 + (O2 -> O3) + O4) -> out (O1+O3+O4) [unique]
	};
	uint32_t algorithm_ops = s_algorithm_ops[opn_registers_ch_algorithm(ch->m_choffs)];

	// populate the opout table
	int16_t opout[8];
	opout[0] = 0;
	opout[1] = op1value;

	// compute the 14-bit volume/value of operator 2
	opmod = opout[bitfield(algorithm_ops, 0, 1)] >> 1;
	opout[2] = fm_operator_compute_volume(ch->m_op[1], fm_operator_phase(ch->m_op[1]) + opmod, am_offset);
	opout[5] = opout[1] + opout[2];

	// compute the 14-bit volume/value of operator 3
	opmod = opout[bitfield(algorithm_ops, 1, 3)] >> 1;
	opout[3] = fm_operator_compute_volume(ch->m_op[2], fm_operator_phase(ch->m_op[2]) + opmod, am_offset);
	opout[6] = opout[1] + opout[3];
	opout[7] = opout[2] + opout[3];

	// compute the 14-bit volume/value of operator 4; this could be a noise
	// value on the OPM; all algorithms consume OP4 output at a minimum
	int32_t result;
	opmod = opout[bitfield(algorithm_ops, 4, 3)] >> 1;
	result = fm_operator_compute_volume(ch->m_op[3], fm_operator_phase(ch->m_op[3]) + opmod, am_offset);
	result >>= rshift;

	// optionally add OP1, OP2, OP3
	int32_t clipmin = -clipmax - 1;
	if (bitfield(algorithm_ops, 7, 1) != 0)
		result = clamp(result + (opout[1] >> rshift), clipmin, clipmax);
	if (bitfield(algorithm_ops, 8, 1) != 0)
		result = clamp(result + (opout[2] >> rshift), clipmin, clipmax);
	if (bitfield(algorithm_ops, 9, 1) != 0)
		result = clamp(result + (opout[3] >> rshift), clipmin, clipmax);

	// add to the output
	fm_channel_add_to_output(ch->m_choffs, output, result);
}


// are we a 4-operator channel or a 2-operator one?
static inline bool fm_channel_is4op(fm_channel *ch) {
	if (DYNAMIC_OPS)
		return (ch->m_op[2] != NULL);
	return (OPERATORS / CHANNELS == 4);
}


//*********************************************************
//  FM ENGINE BASE
//*********************************************************

//-------------------------------------------------
//  fm_engine - init
//-------------------------------------------------

void fm_engine_init(void)
{
	m_env_counter = 0;
	m_status = 0;
	m_clock_prescale = DEFAULT_PRESCALE;
	m_irq_mask = STATUS_TIMERA | STATUS_TIMERB;
	m_irq_state = 0;
	m_timer_running[0] = m_timer_running[1] = 0;
	m_active_channels = ALL_CHANNELS;
	m_modified_channels = ALL_CHANNELS;
	m_prepare_count = 0;

	opn_registers_init();

	// create the channels
	for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
		fm_channel_init(&m_channel[chnum], channel_offset(chnum));

	// create the operators
	for (uint32_t opnum = 0; opnum < OPERATORS; opnum++)
		fm_operator_init(&m_operator[opnum], operator_offset(opnum));

	// do the initial operator assignment
	fm_engine_assign_operators();
}


//-------------------------------------------------
//  reset - reset the overall state
//-------------------------------------------------

void fm_engine_reset(void)
{
	// reset all status bits
	fm_engine_set_reset_status(0, 0xff);

	// register type-specific initialization
	opn_registers_reset();

	// explicitly write to the mode register since it has side-effects
	// QUESTION: old cores initialize this to 0x30 -- who is right?
	fm_engine_write(REG_MODE, 0);

	// reset the channels
	for (int i = 0; i < CHANNELS; ++i)
		fm_channel_reset(&m_channel[i]);

	// reset the operators
	for (int i = 0; i < OPERATORS; ++i)
		fm_operator_reset(&m_operator[i]);
}


//-------------------------------------------------
//  clock - iterate over all channels, clocking
//  them forward one step
//-------------------------------------------------

uint32_t fm_engine_clock(uint32_t chanmask)
{
	// update the clock counter
	m_total_clocks++;

	// if something was modified, prepare
	// also prepare every 4k samples to catch ending notes
	if (m_modified_channels != 0 || m_prepare_count++ >= 4096)
	{
		// reassign operators to channels if dynamic
		if (DYNAMIC_OPS)
			fm_engine_assign_operators();

		// call each channel to prepare
		m_active_channels = 0;
		for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
			if (bitfield(chanmask, chnum, 1))
				if (fm_channel_prepare(&m_channel[chnum]))
					m_active_channels |= 1 << chnum;

		// reset the modified channels and prepare count
		m_modified_channels = m_prepare_count = 0;
	}

	// if the envelope clock divider is 1, just increment by 4;
	// otherwise, increment by 1 and manually wrap when we reach the divide count
	if (EG_CLOCK_DIVIDER == 1)
		m_env_counter += 4;
	else if (bitfield(++m_env_counter, 0, 2) == EG_CLOCK_DIVIDER)
		m_env_counter += 4 - EG_CLOCK_DIVIDER;

	// clock the noise generator
	int32_t lfo_raw_pm = opn_registers_clock_noise_and_lfo();

	// now update the state of all the channels and operators
	for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
		if (bitfield(chanmask, chnum, 1))
			fm_channel_clock(&m_channel[chnum], m_env_counter, lfo_raw_pm);

	// return the envelope counter as it is used to clock ADPCM-A
	return m_env_counter;
}


//-------------------------------------------------
//  output - compute a sum over the relevant
//  channels
//-------------------------------------------------

void fm_engine_output(int32_t *output, uint32_t rshift, int32_t clipmax, uint32_t chanmask)
{
	// mask out some channels for debug purposes
	chanmask &= 0xffffffff;

	// mask out inactive channels
	chanmask &= m_active_channels;

	// sum over all the desired channels
	for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
		if (bitfield(chanmask, chnum, 1))
		{
			if (fm_channel_is4op(&m_channel[chnum]))
				fm_channel_output_4op(&m_channel[chnum], output, rshift, clipmax);
			else
				fm_channel_output_2op(&m_channel[chnum], output, rshift, clipmax);
		}
}


//-------------------------------------------------
//  write - handle writes to the OPN registers
//-------------------------------------------------

void fm_engine_write(uint16_t regnum, uint8_t data)
{
	// special case: writes to the mode register can impact IRQs;
	// schedule these writes to ensure ordering with timers
	if (regnum == REG_MODE)
	{
		ymfm_sync_mode_write(data);
		return;
	}

	// for now just mark all channels as modified
	m_modified_channels = ALL_CHANNELS;

	// most writes are passive, consumed only when needed
	uint32_t keyon_channel;
	uint32_t keyon_opmask;
	if (opn_registers_write(regnum, data, &keyon_channel, &keyon_opmask))
	{
		// handle writes to the keyon register(s)
		if (keyon_channel < CHANNELS)
		{
			// normal channel on/off
			fm_channel_keyonoff(&m_channel[keyon_channel], keyon_opmask,
				KEYON_NORMAL);
		}
	}
}


//-------------------------------------------------
//  status - return the current state of the
//  status flags
//-------------------------------------------------

uint8_t fm_engine_status(void)
{
	return m_status & ~STATUS_BUSY;
}


// set/reset bits in the status register, updating the IRQ status
uint8_t fm_engine_set_reset_status(uint8_t set, uint8_t reset)
{
	m_status = (m_status | set) & ~(reset | STATUS_BUSY);
	ymfm_sync_check_interrupts();
	return m_status;
}


// set the IRQ mask
void fm_engine_set_irq_mask(uint8_t mask) {
	m_irq_mask = mask;
	ymfm_sync_check_interrupts();
}


// return the current clock prescale
uint32_t fm_engine_clock_prescale(void) {
	return m_clock_prescale;
}


// set prescale factor (2/3/6)
void fm_engine_set_clock_prescale(uint32_t prescale) {
	m_clock_prescale = prescale;
}


// compute sample rate
uint32_t fm_engine_sample_rate(uint32_t baseclock) {
	return baseclock / (m_clock_prescale * OPERATORS);
}


// invalidate any caches
void fm_engine_invalidate_caches(void) {
	m_modified_channels = ALL_CHANNELS;
}


//-------------------------------------------------
//  assign_operators - get the current mapping of
//  operators to channels and assign them all
//-------------------------------------------------

// helper to encode four operator numbers into a 32-bit value in the
// operator maps for each register class
static inline uint32_t operator_list(uint8_t o1, uint8_t o2, uint8_t o3, uint8_t o4)
{
	return o1 | (o2 << 8) | (o3 << 16) | (o4 << 24);
}

void fm_engine_assign_operators(void)
{
	// Note that the channel index order is 0,2,1,3, so we bitswap the index.
	//
	// This is because the order in the map is:
	//    carrier 1, carrier 2, modulator 1, modulator 2
	//
	// But when wiring up the connections, the more natural order is:
	//    carrier 1, modulator 1, carrier 2, modulator 2
	operator_mapping map;

	map.chan[0] = operator_list(  0,  6,  3,  9 );  // Channel 0 operators
	map.chan[1] = operator_list(  1,  7,  4, 10 );  // Channel 1 operators
	map.chan[2] = operator_list(  2,  8,  5, 11 );  // Channel 2 operators
	map.chan[3] = operator_list( 12, 18, 15, 21 );  // Channel 3 operators
	map.chan[4] = operator_list( 13, 19, 16, 22 );  // Channel 4 operators
	map.chan[5] = operator_list( 14, 20, 17, 23 );  // Channel 5 operators

	for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
		for (uint32_t index = 0; index < 4; index++)
		{
			uint32_t opnum = bitfield(map.chan[chnum], 8 * index, 8);
			fm_channel_assign(&m_channel[chnum], index, (opnum == 0xff) ?
				NULL : &m_operator[opnum]);
		}
}


//-------------------------------------------------
//  update_timer - update the state of the given
//  timer
//-------------------------------------------------

void fm_engine_update_timer(uint32_t tnum, uint32_t enable, int32_t delta_clocks)
{
	// if the timer is live, but not currently enabled, set the timer
	if (enable && !m_timer_running[tnum])
	{
		// period comes from the registers, and is different for each
		uint32_t period = (tnum == 0) ? (1024 - opn_registers_timer_a_value()) :
			16 * (256 - opn_registers_timer_b_value());

		// caller can also specify a delta to account for other effects
		period += delta_clocks;

		// reset it
		ymfm_set_timer(tnum, period * OPERATORS * m_clock_prescale);
		m_timer_running[tnum] = 1;
	}

	// if the timer is not live, ensure it is not enabled
	else if (!enable)
	{
		ymfm_set_timer(tnum, -1);
		m_timer_running[tnum] = 0;
	}
}


//-------------------------------------------------
//  engine_timer_expired - timer has expired - signal
//  status and possibly IRQs
//-------------------------------------------------

void fm_engine_timer_expired(uint32_t tnum)
{
	// update status
	if (tnum == 0 && opn_registers_enable_timer_a())
		fm_engine_set_reset_status(STATUS_TIMERA, 0);
	else if (tnum == 1 && opn_registers_enable_timer_b())
		fm_engine_set_reset_status(STATUS_TIMERB, 0);

	// if timer A fired in CSM mode, trigger CSM on all relevant channels
	if (tnum == 0 && opn_registers_csm())
		for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
			if (bitfield(CSM_TRIGGER_MASK, chnum, 1)) {
				fm_channel_keyonoff(&m_channel[chnum], 1, KEYON_CSM);
				m_modified_channels |= 1 << chnum;
			}

	// reset
	m_timer_running[tnum] = false;
	fm_engine_update_timer(tnum, 1, 0);
}


//-------------------------------------------------
//  check_interrupts - check the interrupt sources
//  for interrupts
//-------------------------------------------------

void fm_engine_check_interrupts(void)
{
	// update the state
	uint8_t old_state = m_irq_state;
	m_irq_state = ((m_status & m_irq_mask) != 0);

	// set the IRQ status bit
	if (m_irq_state)
		m_status |= STATUS_IRQ;
	else
		m_status &= ~STATUS_IRQ;

	// if changed, signal the new state
	if (old_state != m_irq_state)
		ymfm_update_irq(m_irq_state ? true : false);
}


//-------------------------------------------------
//  engine_mode_write - handle a mode register write
//  via timer callback
//-------------------------------------------------

void fm_engine_mode_write(uint8_t data)
{
	// mark all channels as modified
	m_modified_channels = ALL_CHANNELS;

	// actually write the mode register now
	uint32_t dummy1, dummy2;
	opn_registers_write(REG_MODE, data, &dummy1, &dummy2);

	// reset IRQ status -- when written, all other bits are ignored
	// QUESTION: should this maybe just reset the IRQ bit and not all the bits?
	//   That is, check_interrupts would only set, this would only clear?
	// reset timer status
	uint8_t reset_mask = 0;
	if (opn_registers_reset_timer_b())
		reset_mask |= STATUS_TIMERB;
	if (opn_registers_reset_timer_a())
		reset_mask |= STATUS_TIMERA;
	fm_engine_set_reset_status(0, reset_mask);

	// load timers; note that timer B gets a small negative adjustment because
	// the *16 multiplier is free-running, so the first tick of the clock
	// is a bit shorter
	fm_engine_update_timer(1, opn_registers_load_timer_b(), -(m_total_clocks & 15));
	fm_engine_update_timer(0, opn_registers_load_timer_a(), 0);
}
