YM2151.java
     1: //========================================================================================
     2: //  YM2151.java
     3: //    en:YM2151
     4: //    ja:YM2151
     5: //  Copyright (C) 2003-2022 Makoto Kamada
     6: //
     7: //  This file is part of the XEiJ (X68000 Emulator in Java).
     8: //  You can use, modify and redistribute the XEiJ if the conditions are met.
     9: //  Read the XEiJ License for more details.
    10: //  https://stdkmd.net/xeij/
    11: //========================================================================================
    12: 
    13: //--------------------------------------------------------------------------------
    14: //  This program is based on ymfm developed by Aaron Giles.
    15: //  https://github.com/aaronsgiles/ymfm
    16: //--------------------------------------------------------------------------------
    17: 
    18: //--------------------------------------------------------------------------------
    19: //ymfm License
    20: //--------------------------------------------------------------------------------
    21: // BSD 3-Clause License
    22: //
    23: // Copyright (c) 2021, Aaron Giles
    24: // All rights reserved.
    25: //
    26: // Redistribution and use in source and binary forms, with or without
    27: // modification, are permitted provided that the following conditions are met:
    28: //
    29: // 1. Redistributions of source code must retain the above copyright notice, this
    30: //    list of conditions and the following disclaimer.
    31: //
    32: // 2. Redistributions in binary form must reproduce the above copyright notice,
    33: //    this list of conditions and the following disclaimer in the documentation
    34: //    and/or other materials provided with the distribution.
    35: //
    36: // 3. Neither the name of the copyright holder nor the names of its
    37: //    contributors may be used to endorse or promote products derived from
    38: //    this software without specific prior written permission.
    39: //
    40: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    41: // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    42: // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    43: // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    44: // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    45: // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    46: // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    47: // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    48: // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    49: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    50: //--------------------------------------------------------------------------------
    51: 
    52: package xeij;
    53: 
    54: import java.io.*;  //FileOutputStream
    55: import java.nio.*;  //ByteBuffer
    56: import java.util.*;  //Arrays
    57: 
    58: public class YM2151 {
    59: 
    60: 
    61: 
    62:   public static int sint8 (int x) {
    63:     return (byte) x;
    64:   }
    65:   public static int sint16 (int x) {
    66:     return (short) x;
    67:   }
    68:   public static int uint8 (int x) {
    69:     return 0xff & x;
    70:   }
    71:   public static int uint16 (int x) {
    72:     return (char) x;
    73:   }
    74:   public static int umin32 (int x, int y) {
    75:     return Integer.compareUnsigned (x, y) < 0 ? x : y;
    76:   }
    77: 
    78: 
    79: 
    80:   //-------------------------------------------------
    81:   //  bitfield - extract a bitfield from the given
    82:   //  value, starting at bit 'start' for a length of
    83:   //  'length' bits
    84:   //-------------------------------------------------
    85:   public static /*uint32*/ int bitfield (/*uint32*/ int value, int start) {
    86:     return (value >>> start) & 1;
    87:   }
    88:   public static /*uint32*/ int bitfield (/*uint32*/ int value, int start, int length) {
    89:     return (value >>> start) & ((1 << length) - 1);
    90:   }
    91: 
    92:   //-------------------------------------------------
    93:   //  clamp - clamp between the minimum and maximum
    94:   //  values provided
    95:   //-------------------------------------------------
    96:   public static /*sint32*/ int clamp (/*sint32*/ int value, /*sint32*/ int minval, /*sint32*/ int maxval) {
    97:     //return Math.max (minval, Math.min (maxval, value));
    98:     if (value < minval) {
    99:       return minval;
   100:     }
   101:     if (value > maxval) {
   102:       return maxval;
   103:     }
   104:     return value;
   105:   }
   106: 
   107:   //-------------------------------------------------
   108:   //  count_leading_zeros - return the number of
   109:   //  leading zeros in a 32-bit value; CPU-optimized
   110:   //  versions for various architectures are included
   111:   //  below
   112:   //-------------------------------------------------
   113:   public static /*uint8*/ int count_leading_zeros (/*uint32*/ int value) {
   114:     //return uint8 (Integer.numberOfLeadingZeros (value));
   115:     if (value == 0) {
   116:       return 32;
   117:     }
   118:     /*uint8*/ int count;
   119:     for (count = 0; /*sint32*/ value >= 0; count++) {
   120:       value <<= 1;
   121:     }
   122:     return count;
   123:   }
   124: 
   125:   // Many of the Yamaha FM chips emit a floating-point value, which is sent to
   126:   // a DAC for processing. The exact format of this floating-point value is
   127:   // documented below. This description only makes sense if the "internal"
   128:   // format treats sign as 1=positive and 0=negative, so the helpers below
   129:   // presume that.
   130:   //
   131:   // Internal OPx data      16-bit signed data     Exp Sign Mantissa
   132:   // =================      =================      === ==== ========
   133:   // 1 1xxxxxxxx------  ->  0 1xxxxxxxx------  ->  111   1  1xxxxxxx
   134:   // 1 01xxxxxxxx-----  ->  0 01xxxxxxxx-----  ->  110   1  1xxxxxxx
   135:   // 1 001xxxxxxxx----  ->  0 001xxxxxxxx----  ->  101   1  1xxxxxxx
   136:   // 1 0001xxxxxxxx---  ->  0 0001xxxxxxxx---  ->  100   1  1xxxxxxx
   137:   // 1 00001xxxxxxxx--  ->  0 00001xxxxxxxx--  ->  011   1  1xxxxxxx
   138:   // 1 000001xxxxxxxx-  ->  0 000001xxxxxxxx-  ->  010   1  1xxxxxxx
   139:   // 1 000000xxxxxxxxx  ->  0 000000xxxxxxxxx  ->  001   1  xxxxxxxx
   140:   // 0 111111xxxxxxxxx  ->  1 111111xxxxxxxxx  ->  001   0  xxxxxxxx
   141:   // 0 111110xxxxxxxx-  ->  1 111110xxxxxxxx-  ->  010   0  0xxxxxxx
   142:   // 0 11110xxxxxxxx--  ->  1 11110xxxxxxxx--  ->  011   0  0xxxxxxx
   143:   // 0 1110xxxxxxxx---  ->  1 1110xxxxxxxx---  ->  100   0  0xxxxxxx
   144:   // 0 110xxxxxxxx----  ->  1 110xxxxxxxx----  ->  101   0  0xxxxxxx
   145:   // 0 10xxxxxxxx-----  ->  1 10xxxxxxxx-----  ->  110   0  0xxxxxxx
   146:   // 0 0xxxxxxxx------  ->  1 0xxxxxxxx------  ->  111   0  0xxxxxxx
   147: 
   148:   //-------------------------------------------------
   149:   //  roundtrip_fp - compute the result of a round
   150:   //  trip through the encode/decode process above
   151:   //-------------------------------------------------
   152:   public static /*sint16*/ int roundtrip_fp (/*sint32*/ int value) {
   153:     // handle overflows first
   154:     if (value < -32768) {
   155:       return sint16 (-32768);
   156:     }
   157:     if (value > 32767) {
   158:       return sint16 (32767);
   159:     }
   160: 
   161:     // we need to count the number of leading sign bits after the sign
   162:     // we can use count_leading_zeros if we invert negative values
   163:     /*sint32*/ int scanvalue = value ^ (value >> 31);
   164: 
   165:     // exponent is related to the number of leading bits starting from bit 14
   166:     int exponent = 7 - count_leading_zeros (scanvalue << 17);
   167: 
   168:     // smallest exponent value allowed is 1
   169:     exponent = Math.max (exponent, 1);
   170: 
   171:     // apply the shift back and forth to zero out bits that are lost
   172:     exponent -= 1;
   173:     return sint16 ((value >> exponent) << exponent);
   174:   }
   175: 
   176: 
   177: 
   178:   // variants
   179:   // the YM2164 is almost 100% functionally identical to the YM2151, except
   180:   // it apparently has some mystery registers in the 00-07 range, and timer
   181:   // B's frequency is half that of the 2151
   182: 
   183:   // constants
   184:   // the following constants need to be defined per family:
   185:   //          uint OUTPUTS: The number of outputs exposed (1-4)
   186:   //         uint CHANNELS: The number of channels on the chip
   187:   //     uint ALL_CHANNELS: A bitmask of all channels
   188:   //        uint OPERATORS: The number of operators on the chip
   189:   //        uint WAVEFORMS: The number of waveforms offered
   190:   //        uint REGISTERS: The number of 8-bit registers allocated
   191:   // uint DEFAULT_PRESCALE: The starting clock prescale
   192:   // uint EG_CLOCK_DIVIDER: The clock divider of the envelope generator
   193:   // uint CSM_TRIGGER_MASK: Mask of channels to trigger in CSM mode
   194:   //         uint REG_MODE: The address of the "mode" register controlling timers
   195:   //     uint8_t STATUS_TIMERA: Status bit to set when timer A fires
   196:   //     uint8_t STATUS_TIMERB: Status bit to set when tiemr B fires
   197:   //       uint8_t STATUS_BUSY: Status bit to set when the chip is busy
   198:   //        uint8_t STATUS_IRQ: Status bit to set when an IRQ is signalled
   199:   public static final /*uint32*/ int OUTPUTS = 2;
   200:   public static final /*uint32*/ int CHANNELS = 8;
   201:   public static final /*uint32*/ int ALL_CHANNELS = (1 << CHANNELS) - 1;
   202:   public static final /*uint32*/ int OPERATORS = CHANNELS * 4;
   203:   public static final /*uint32*/ int WAVEFORMS = 1;
   204:   public static final /*uint32*/ int REGISTERS = 0x100;
   205:   public static final /*uint32*/ int DEFAULT_PRESCALE = 2;
   206:   public static final /*uint32*/ int EG_CLOCK_DIVIDER = 3;
   207:   public static final /*uint32*/ int CSM_TRIGGER_MASK = ALL_CHANNELS;
   208:   public static final /*uint32*/ int REG_MODE = 0x14;
   209:   public static final /*uint8*/ int STATUS_TIMERA = 0x01;
   210:   public static final /*uint8*/ int STATUS_TIMERB = 0x02;
   211:   public static final /*uint8*/ int STATUS_BUSY = 0x80;
   212:   public static final /*uint8*/ int STATUS_IRQ = 0;
   213: 
   214:   // various envelope states
   215:   //envelope_state
   216:   public static final int EG_ATTACK = 1;
   217:   public static final int EG_DECAY = 2;
   218:   public static final int EG_SUSTAIN = 3;
   219:   public static final int EG_RELEASE = 4;
   220:   public static final int EG_STATES = 6;
   221: 
   222:   // external I/O access classes
   223:   //access_class
   224: 
   225:   // this value is returned from the write() function for rhythm channels
   226: 
   227:   // this is the size of a full sin waveform
   228:   public static final /*uint32*/ int WAVEFORM_LENGTH = 0x400;
   229: 
   230:   //struct opdata_cache
   231:   // set phase_step to this value to recalculate it each sample; needed
   232:   // in the case of PM LFO changes
   233:   public static final /*uint32*/ int PHASE_STEP_DYNAMIC = 1;
   234: 
   235:   // "quiet" value, used to optimize when we can skip doing work
   236:   public static final /*uint32*/ int EG_QUIET = 0x380;
   237: 
   238:   // the values here are stored as 4.8 logarithmic values for 1/4 phase
   239:   // this matches the internal format of the OPN chip, extracted from the die
   240:   public static final /*uint16*/ int[] s_sin_table = {
   241:     0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365,
   242:     0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, 0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261,
   243:     0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f, 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd,
   244:     0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195, 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166,
   245:     0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118,
   246:     0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, 0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db,
   247:     0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9,
   248:     0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094, 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081,
   249:     0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060,
   250:     0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, 0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045,
   251:     0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, 0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f,
   252:     0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026, 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e,
   253:     0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017, 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011,
   254:     0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, 0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007,
   255:     0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, 0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002,
   256:     0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000,
   257:   };
   258: 
   259:   private static int X (int a) {
   260:     return (a | 0x400) << 2;
   261:   }
   262:   public static final /*uint16*/ int[] s_power_table = {
   263:     X (0x3fa), X (0x3f5), X (0x3ef), X (0x3ea), X (0x3e4), X (0x3df), X (0x3da), X (0x3d4),
   264:     X (0x3cf), X (0x3c9), X (0x3c4), X (0x3bf), X (0x3b9), X (0x3b4), X (0x3ae), X (0x3a9),
   265:     X (0x3a4), X (0x39f), X (0x399), X (0x394), X (0x38f), X (0x38a), X (0x384), X (0x37f),
   266:     X (0x37a), X (0x375), X (0x370), X (0x36a), X (0x365), X (0x360), X (0x35b), X (0x356),
   267:     X (0x351), X (0x34c), X (0x347), X (0x342), X (0x33d), X (0x338), X (0x333), X (0x32e),
   268:     X (0x329), X (0x324), X (0x31f), X (0x31a), X (0x315), X (0x310), X (0x30b), X (0x306),
   269:     X (0x302), X (0x2fd), X (0x2f8), X (0x2f3), X (0x2ee), X (0x2e9), X (0x2e5), X (0x2e0),
   270:     X (0x2db), X (0x2d6), X (0x2d2), X (0x2cd), X (0x2c8), X (0x2c4), X (0x2bf), X (0x2ba),
   271:     X (0x2b5), X (0x2b1), X (0x2ac), X (0x2a8), X (0x2a3), X (0x29e), X (0x29a), X (0x295),
   272:     X (0x291), X (0x28c), X (0x288), X (0x283), X (0x27f), X (0x27a), X (0x276), X (0x271),
   273:     X (0x26d), X (0x268), X (0x264), X (0x25f), X (0x25b), X (0x257), X (0x252), X (0x24e),
   274:     X (0x249), X (0x245), X (0x241), X (0x23c), X (0x238), X (0x234), X (0x230), X (0x22b),
   275:     X (0x227), X (0x223), X (0x21e), X (0x21a), X (0x216), X (0x212), X (0x20e), X (0x209),
   276:     X (0x205), X (0x201), X (0x1fd), X (0x1f9), X (0x1f5), X (0x1f0), X (0x1ec), X (0x1e8),
   277:     X (0x1e4), X (0x1e0), X (0x1dc), X (0x1d8), X (0x1d4), X (0x1d0), X (0x1cc), X (0x1c8),
   278:     X (0x1c4), X (0x1c0), X (0x1bc), X (0x1b8), X (0x1b4), X (0x1b0), X (0x1ac), X (0x1a8),
   279:     X (0x1a4), X (0x1a0), X (0x19c), X (0x199), X (0x195), X (0x191), X (0x18d), X (0x189),
   280:     X (0x185), X (0x181), X (0x17e), X (0x17a), X (0x176), X (0x172), X (0x16f), X (0x16b),
   281:     X (0x167), X (0x163), X (0x160), X (0x15c), X (0x158), X (0x154), X (0x151), X (0x14d),
   282:     X (0x149), X (0x146), X (0x142), X (0x13e), X (0x13b), X (0x137), X (0x134), X (0x130),
   283:     X (0x12c), X (0x129), X (0x125), X (0x122), X (0x11e), X (0x11b), X (0x117), X (0x114),
   284:     X (0x110), X (0x10c), X (0x109), X (0x106), X (0x102), X (0x0ff), X (0x0fb), X (0x0f8),
   285:     X (0x0f4), X (0x0f1), X (0x0ed), X (0x0ea), X (0x0e7), X (0x0e3), X (0x0e0), X (0x0dc),
   286:     X (0x0d9), X (0x0d6), X (0x0d2), X (0x0cf), X (0x0cc), X (0x0c8), X (0x0c5), X (0x0c2),
   287:     X (0x0be), X (0x0bb), X (0x0b8), X (0x0b5), X (0x0b1), X (0x0ae), X (0x0ab), X (0x0a8),
   288:     X (0x0a4), X (0x0a1), X (0x09e), X (0x09b), X (0x098), X (0x094), X (0x091), X (0x08e),
   289:     X (0x08b), X (0x088), X (0x085), X (0x082), X (0x07e), X (0x07b), X (0x078), X (0x075),
   290:     X (0x072), X (0x06f), X (0x06c), X (0x069), X (0x066), X (0x063), X (0x060), X (0x05d),
   291:     X (0x05a), X (0x057), X (0x054), X (0x051), X (0x04e), X (0x04b), X (0x048), X (0x045),
   292:     X (0x042), X (0x03f), X (0x03c), X (0x039), X (0x036), X (0x033), X (0x030), X (0x02d),
   293:     X (0x02a), X (0x028), X (0x025), X (0x022), X (0x01f), X (0x01c), X (0x019), X (0x016),
   294:     X (0x014), X (0x011), X (0x00e), X (0x00b), X (0x008), X (0x006), X (0x003), X (0x000),
   295:   };
   296: 
   297:   public static final /*uint32*/ int[] s_increment_table = {
   298:     0x00000000, 0x00000000, 0x10101010, 0x10101010,  // 0-3    (0x00-0x03)
   299:     0x10101010, 0x10101010, 0x11101110, 0x11101110,  // 4-7    (0x04-0x07)
   300:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 8-11   (0x08-0x0B)
   301:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 12-15  (0x0C-0x0F)
   302:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 16-19  (0x10-0x13)
   303:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 20-23  (0x14-0x17)
   304:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 24-27  (0x18-0x1B)
   305:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 28-31  (0x1C-0x1F)
   306:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 32-35  (0x20-0x23)
   307:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 36-39  (0x24-0x27)
   308:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 40-43  (0x28-0x2B)
   309:     0x10101010, 0x10111010, 0x11101110, 0x11111110,  // 44-47  (0x2C-0x2F)
   310:     0x11111111, 0x21112111, 0x21212121, 0x22212221,  // 48-51  (0x30-0x33)
   311:     0x22222222, 0x42224222, 0x42424242, 0x44424442,  // 52-55  (0x34-0x37)
   312:     0x44444444, 0x84448444, 0x84848484, 0x88848884,  // 56-59  (0x38-0x3B)
   313:     0x88888888, 0x88888888, 0x88888888, 0x88888888,  // 60-63  (0x3C-0x3F)
   314:   };
   315: 
   316:   public static final /*uint8*/ int[] s_detune_adjustment = {
   317:     0,  0,  1,  2,  0,  0,  1,  2,  0,  0,  1,  2,  0,  0,  1,  2,
   318:     0,  1,  2,  2,  0,  1,  2,  3,  0,  1,  2,  3,  0,  1,  2,  3,
   319:     0,  1,  2,  4,  0,  1,  3,  4,  0,  1,  3,  4,  0,  1,  3,  5,
   320:     0,  2,  4,  5,  0,  2,  4,  6,  0,  2,  4,  6,  0,  2,  5,  7,
   321:     0,  2,  5,  8,  0,  3,  6,  8,  0,  3,  6,  9,  0,  3,  7, 10,
   322:     0,  4,  8, 11,  0,  4,  8, 12,  0,  4,  9, 13,  0,  5, 10, 14,
   323:     0,  5, 11, 16,  0,  6, 12, 17,  0,  6, 13, 19,  0,  7, 14, 20,
   324:     0,  8, 16, 22,  0,  8, 16, 22,  0,  8, 16, 22,  0,  8, 16, 22,
   325:   };
   326: 
   327:   public static final /*uint32*/ int[] s_phase_step = {
   328:     41568, 41600, 41632, 41664, 41696, 41728, 41760, 41792, 41856, 41888, 41920, 41952, 42016, 42048, 42080, 42112,
   329:     42176, 42208, 42240, 42272, 42304, 42336, 42368, 42400, 42464, 42496, 42528, 42560, 42624, 42656, 42688, 42720,
   330:     42784, 42816, 42848, 42880, 42912, 42944, 42976, 43008, 43072, 43104, 43136, 43168, 43232, 43264, 43296, 43328,
   331:     43392, 43424, 43456, 43488, 43552, 43584, 43616, 43648, 43712, 43744, 43776, 43808, 43872, 43904, 43936, 43968,
   332:     44032, 44064, 44096, 44128, 44192, 44224, 44256, 44288, 44352, 44384, 44416, 44448, 44512, 44544, 44576, 44608,
   333:     44672, 44704, 44736, 44768, 44832, 44864, 44896, 44928, 44992, 45024, 45056, 45088, 45152, 45184, 45216, 45248,
   334:     45312, 45344, 45376, 45408, 45472, 45504, 45536, 45568, 45632, 45664, 45728, 45760, 45792, 45824, 45888, 45920,
   335:     45984, 46016, 46048, 46080, 46144, 46176, 46208, 46240, 46304, 46336, 46368, 46400, 46464, 46496, 46528, 46560,
   336:     46656, 46688, 46720, 46752, 46816, 46848, 46880, 46912, 46976, 47008, 47072, 47104, 47136, 47168, 47232, 47264,
   337:     47328, 47360, 47392, 47424, 47488, 47520, 47552, 47584, 47648, 47680, 47744, 47776, 47808, 47840, 47904, 47936,
   338:     48032, 48064, 48096, 48128, 48192, 48224, 48288, 48320, 48384, 48416, 48448, 48480, 48544, 48576, 48640, 48672,
   339:     48736, 48768, 48800, 48832, 48896, 48928, 48992, 49024, 49088, 49120, 49152, 49184, 49248, 49280, 49344, 49376,
   340:     49440, 49472, 49504, 49536, 49600, 49632, 49696, 49728, 49792, 49824, 49856, 49888, 49952, 49984, 50048, 50080,
   341:     50144, 50176, 50208, 50240, 50304, 50336, 50400, 50432, 50496, 50528, 50560, 50592, 50656, 50688, 50752, 50784,
   342:     50880, 50912, 50944, 50976, 51040, 51072, 51136, 51168, 51232, 51264, 51328, 51360, 51424, 51456, 51488, 51520,
   343:     51616, 51648, 51680, 51712, 51776, 51808, 51872, 51904, 51968, 52000, 52064, 52096, 52160, 52192, 52224, 52256,
   344:     52384, 52416, 52448, 52480, 52544, 52576, 52640, 52672, 52736, 52768, 52832, 52864, 52928, 52960, 52992, 53024,
   345:     53120, 53152, 53216, 53248, 53312, 53344, 53408, 53440, 53504, 53536, 53600, 53632, 53696, 53728, 53792, 53824,
   346:     53920, 53952, 54016, 54048, 54112, 54144, 54208, 54240, 54304, 54336, 54400, 54432, 54496, 54528, 54592, 54624,
   347:     54688, 54720, 54784, 54816, 54880, 54912, 54976, 55008, 55072, 55104, 55168, 55200, 55264, 55296, 55360, 55392,
   348:     55488, 55520, 55584, 55616, 55680, 55712, 55776, 55808, 55872, 55936, 55968, 56032, 56064, 56128, 56160, 56224,
   349:     56288, 56320, 56384, 56416, 56480, 56512, 56576, 56608, 56672, 56736, 56768, 56832, 56864, 56928, 56960, 57024,
   350:     57120, 57152, 57216, 57248, 57312, 57376, 57408, 57472, 57536, 57568, 57632, 57664, 57728, 57792, 57824, 57888,
   351:     57952, 57984, 58048, 58080, 58144, 58208, 58240, 58304, 58368, 58400, 58464, 58496, 58560, 58624, 58656, 58720,
   352:     58784, 58816, 58880, 58912, 58976, 59040, 59072, 59136, 59200, 59232, 59296, 59328, 59392, 59456, 59488, 59552,
   353:     59648, 59680, 59744, 59776, 59840, 59904, 59936, 60000, 60064, 60128, 60160, 60224, 60288, 60320, 60384, 60416,
   354:     60512, 60544, 60608, 60640, 60704, 60768, 60800, 60864, 60928, 60992, 61024, 61088, 61152, 61184, 61248, 61280,
   355:     61376, 61408, 61472, 61536, 61600, 61632, 61696, 61760, 61824, 61856, 61920, 61984, 62048, 62080, 62144, 62208,
   356:     62272, 62304, 62368, 62432, 62496, 62528, 62592, 62656, 62720, 62752, 62816, 62880, 62944, 62976, 63040, 63104,
   357:     63200, 63232, 63296, 63360, 63424, 63456, 63520, 63584, 63648, 63680, 63744, 63808, 63872, 63904, 63968, 64032,
   358:     64096, 64128, 64192, 64256, 64320, 64352, 64416, 64480, 64544, 64608, 64672, 64704, 64768, 64832, 64896, 64928,
   359:     65024, 65056, 65120, 65184, 65248, 65312, 65376, 65408, 65504, 65536, 65600, 65664, 65728, 65792, 65856, 65888,
   360:     65984, 66016, 66080, 66144, 66208, 66272, 66336, 66368, 66464, 66496, 66560, 66624, 66688, 66752, 66816, 66848,
   361:     66944, 66976, 67040, 67104, 67168, 67232, 67296, 67328, 67424, 67456, 67520, 67584, 67648, 67712, 67776, 67808,
   362:     67904, 67936, 68000, 68064, 68128, 68192, 68256, 68288, 68384, 68448, 68512, 68544, 68640, 68672, 68736, 68800,
   363:     68896, 68928, 68992, 69056, 69120, 69184, 69248, 69280, 69376, 69440, 69504, 69536, 69632, 69664, 69728, 69792,
   364:     69920, 69952, 70016, 70080, 70144, 70208, 70272, 70304, 70400, 70464, 70528, 70560, 70656, 70688, 70752, 70816,
   365:     70912, 70976, 71040, 71104, 71136, 71232, 71264, 71360, 71424, 71488, 71552, 71616, 71648, 71744, 71776, 71872,
   366:     71968, 72032, 72096, 72160, 72192, 72288, 72320, 72416, 72480, 72544, 72608, 72672, 72704, 72800, 72832, 72928,
   367:     72992, 73056, 73120, 73184, 73216, 73312, 73344, 73440, 73504, 73568, 73632, 73696, 73728, 73824, 73856, 73952,
   368:     74080, 74144, 74208, 74272, 74304, 74400, 74432, 74528, 74592, 74656, 74720, 74784, 74816, 74912, 74944, 75040,
   369:     75136, 75200, 75264, 75328, 75360, 75456, 75488, 75584, 75648, 75712, 75776, 75840, 75872, 75968, 76000, 76096,
   370:     76224, 76288, 76352, 76416, 76448, 76544, 76576, 76672, 76736, 76800, 76864, 76928, 77024, 77120, 77152, 77248,
   371:     77344, 77408, 77472, 77536, 77568, 77664, 77696, 77792, 77856, 77920, 77984, 78048, 78144, 78240, 78272, 78368,
   372:     78464, 78528, 78592, 78656, 78688, 78784, 78816, 78912, 78976, 79040, 79104, 79168, 79264, 79360, 79392, 79488,
   373:     79616, 79680, 79744, 79808, 79840, 79936, 79968, 80064, 80128, 80192, 80256, 80320, 80416, 80512, 80544, 80640,
   374:     80768, 80832, 80896, 80960, 80992, 81088, 81120, 81216, 81280, 81344, 81408, 81472, 81568, 81664, 81696, 81792,
   375:     81952, 82016, 82080, 82144, 82176, 82272, 82304, 82400, 82464, 82528, 82592, 82656, 82752, 82848, 82880, 82976,
   376:   };
   377: 
   378:   // this table encodes 2 shift values to apply to the top 7 bits
   379:   // of fnum; it is effectively a cheap multiply by a constant
   380:   // value containing 0-2 bits
   381:   public static final /*uint8*/ int[] s_lfo_pm_shifts = {
   382:     0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
   383:     0x77, 0x77, 0x77, 0x77, 0x72, 0x72, 0x72, 0x72,
   384:     0x77, 0x77, 0x77, 0x72, 0x72, 0x72, 0x17, 0x17,
   385:     0x77, 0x77, 0x72, 0x72, 0x17, 0x17, 0x12, 0x12,
   386:     0x77, 0x77, 0x72, 0x17, 0x17, 0x17, 0x12, 0x07,
   387:     0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01,
   388:     0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01,
   389:     0x77, 0x77, 0x17, 0x12, 0x07, 0x07, 0x02, 0x01,
   390:   };
   391: 
   392:   // LFO waveforms are 256 entries long
   393:   public static final /*uint32*/ int LFO_WAVEFORM_LENGTH = 256;
   394: 
   395:   // helper to encode four operator numbers into a 32-bit value in the
   396:   // operator maps for each register class
   397:   //fm_registers_base::operator_list
   398:   private static /*uint32*/ int operator_list (/*uint8*/ int o1, /*uint8*/ int o2, /*uint8*/ int o3, /*uint8*/ int o4) {
   399:     return o1 | (o2 << 8) | (o3 << 16) | (o4 << 24);
   400:   }
   401: 
   402:   // Note that the channel index order is 0,2,1,3, so we bitswap the index.
   403:   //
   404:   // This is because the order in the map is:
   405:   //    carrier 1, carrier 2, modulator 1, modulator 2
   406:   //
   407:   // But when wiring up the connections, the more natural order is:
   408:   //    carrier 1, modulator 1, carrier 2, modulator 2
   409:   //opm_registers::operator_map
   410:   public static final /*operator_mapping*/ int[] s_fixed_map = {
   411:     operator_list (  0, 16,  8, 24 ),  // Channel 0 operators
   412:     operator_list (  1, 17,  9, 25 ),  // Channel 1 operators
   413:     operator_list (  2, 18, 10, 26 ),  // Channel 2 operators
   414:     operator_list (  3, 19, 11, 27 ),  // Channel 3 operators
   415:     operator_list (  4, 20, 12, 28 ),  // Channel 4 operators
   416:     operator_list (  5, 21, 13, 29 ),  // Channel 5 operators
   417:     operator_list (  6, 22, 14, 30 ),  // Channel 6 operators
   418:     operator_list (  7, 23, 15, 31 ),  // Channel 7 operators
   419:   };
   420: 
   421:   //fm_channel::output_4op
   422:   private static int ALGORITHM (int op2in, int op3in, int op4in, int op1out, int op2out, int op3out) {
   423:     return op2in | (op3in << 1) | (op4in << 4) | (op1out << 7) | (op2out << 8) | (op3out << 9);
   424:   }
   425:   public static final /*uint16*/ int[] s_algorithm_ops = {
   426:     ALGORITHM (1,2,3, 0,0,0),  //  0: O1 -> O2 -> O3 -> O4 -> out (O4)
   427:     ALGORITHM (0,5,3, 0,0,0),  //  1: (O1 + O2) -> O3 -> O4 -> out (O4)
   428:     ALGORITHM (0,2,6, 0,0,0),  //  2: (O1 + (O2 -> O3)) -> O4 -> out (O4)
   429:     ALGORITHM (1,0,7, 0,0,0),  //  3: ((O1 -> O2) + O3) -> O4 -> out (O4)
   430:     ALGORITHM (1,0,3, 0,1,0),  //  4: ((O1 -> O2) + (O3 -> O4)) -> out (O2+O4)
   431:     ALGORITHM (1,1,1, 0,1,1),  //  5: ((O1 -> O2) + (O1 -> O3) + (O1 -> O4)) -> out (O2+O3+O4)
   432:     ALGORITHM (1,0,0, 0,1,1),  //  6: ((O1 -> O2) + O3 + O4) -> out (O2+O3+O4)
   433:     ALGORITHM (0,0,0, 1,1,1),  //  7: (O1 + O2 + O3 + O4) -> out (O1+O2+O3+O4)
   434:     ALGORITHM (1,2,3, 0,0,0),  //  8: O1 -> O2 -> O3 -> O4 -> out (O4)         [same as 0]
   435:     ALGORITHM (0,2,3, 1,0,0),  //  9: (O1 + (O2 -> O3 -> O4)) -> out (O1+O4)   [unique]
   436:     ALGORITHM (1,0,3, 0,1,0),  // 10: ((O1 -> O2) + (O3 -> O4)) -> out (O2+O4) [same as 4]
   437:     ALGORITHM (0,2,0, 1,0,1),  // 11: (O1 + (O2 -> O3) + O4) -> out (O1+O3+O4) [unique]
   438:   };
   439: 
   440:   public static final /*sint16*/ int[] s_detune2_delta = { 0, (600*64+50)/100, (781*64+50)/100, (950*64+50)/100 };
   441: 
   442:   // three different keyon sources; actual keyon is an OR over all of these
   443:   //keyon_type
   444:   public static final int KEYON_NORMAL = 0;
   445:   public static final int KEYON_RHYTHM = 1;
   446:   public static final int KEYON_CSM = 2;
   447: 
   448: 
   449: 
   450:   //-------------------------------------------------
   451:   //  abs_sin_attenuation - given a sin (phase) input
   452:   //  where the range 0-2*PI is mapped onto 10 bits,
   453:   //  return the absolute value of sin(input),
   454:   //  logarithmically-adjusted and treated as an
   455:   //  attenuation value, in 4.8 fixed point format
   456:   //-------------------------------------------------
   457:   public static /*uint32*/ int abs_sin_attenuation (/*uint32*/ int input) {
   458:     // if the top bit is set, we're in the second half of the curve
   459:     // which is a mirror image, so invert the index
   460:     if (bitfield (input, 8) != 0) {
   461:       input = ~input;
   462:     }
   463:     // return the value from the table
   464:     return s_sin_table[input & 0xff];
   465:   }
   466: 
   467:   //-------------------------------------------------
   468:   //  attenuation_to_volume - given a 5.8 fixed point
   469:   //  logarithmic attenuation value, return a 13-bit
   470:   //  linear volume
   471:   //-------------------------------------------------
   472:   public static /*uint32*/ int attenuation_to_volume (/*uint32*/ int input) {
   473:     // the values here are 10-bit mantissas with an implied leading bit
   474:     // this matches the internal format of the OPN chip, extracted from the die
   475: 
   476:     // as a nod to performance, the implicit 0x400 bit is pre-incorporated, and
   477:     // the values are left-shifted by 2 so that a simple right shift is all that
   478:     // is needed; also the order is reversed to save a NOT on the input
   479: 
   480:     // look up the fractional part, then shift by the whole
   481:     return s_power_table[input & 0xff] >>> (input >>> 8);
   482:   }
   483: 
   484:   //-------------------------------------------------
   485:   //  attenuation_increment - given a 6-bit ADSR
   486:   //  rate value and a 3-bit stepping index,
   487:   //  return a 4-bit increment to the attenutaion
   488:   //  for this step (or for the attack case, the
   489:   //  fractional scale factor to decrease by)
   490:   //-------------------------------------------------
   491:   public static /*uint32*/ int attenuation_increment (/*uint32*/ int rate, /*uint32*/ int index) {
   492:     return bitfield (s_increment_table[rate], 4 * index, 4);
   493:   }
   494: 
   495:   //-------------------------------------------------
   496:   //  detune_adjustment - given a 5-bit key code
   497:   //  value and a 3-bit detune parameter, return a
   498:   //  6-bit signed phase displacement; this table
   499:   //  has been verified against Nuked's equations,
   500:   //  but the equations are rather complicated, so
   501:   //  we'll keep the simplicity of the table
   502:   //-------------------------------------------------
   503:   public static /*sint32*/ int detune_adjustment (/*uint32*/ int detune, /*uint32*/ int keycode) {
   504:     /*sint32*/ int result = s_detune_adjustment[4 * keycode + (detune & 3)];
   505:     return bitfield (detune, 2) != 0 ? -result : result;
   506:   }
   507: 
   508:   //-------------------------------------------------
   509:   //  opm_key_code_to_phase_step - converts an
   510:   //  OPM concatenated block (3 bits), keycode
   511:   //  (4 bits) and key fraction (6 bits) to a 0.10
   512:   //  phase step, after applying the given delta;
   513:   //  this applies to OPM and OPZ, so it lives here
   514:   //  in a central location
   515:   //-------------------------------------------------
   516:   public static /*uint32*/ int opm_key_code_to_phase_step (/*uint32*/ int block_freq, /*sint32*/ int delta) {
   517:     // The phase step is essentially the fnum in OPN-speak. To compute this table,
   518:     // we used the standard formula for computing the frequency of a note, and
   519:     // then converted that frequency to fnum using the formula documented in the
   520:     // YM2608 manual.
   521:     //
   522:     // However, the YM2608 manual describes everything in terms of a nominal 8MHz
   523:     // clock, which produces an FM clock of:
   524:     //
   525:     //    8000000 / 24(operators) / 6(prescale) = 55555Hz FM clock
   526:     //
   527:     // Whereas the descriptions for the YM2151 use a nominal 3.579545MHz clock:
   528:     //
   529:     //    3579545 / 32(operators) / 2(prescale) = 55930Hz FM clock
   530:     //
   531:     // To correct for this, the YM2608 formula was adjusted to use a clock of
   532:     // 8053920Hz, giving this equation for the fnum:
   533:     //
   534:     //    fnum = (double(144) * freq * (1 << 20)) / double(8053920) / 4;
   535:     //
   536:     // Unfortunately, the computed table differs in a few spots from the data
   537:     // verified from an actual chip. The table below comes from David Viens'
   538:     // analysis, used with his permission.
   539: 
   540:     // extract the block (octave) first
   541:     /*uint32*/ int block = bitfield (block_freq, 10, 3);
   542: 
   543:     // the keycode (bits 6-9) is "gappy", mapping 12 values over 16 in each
   544:     // octave; to correct for this, we multiply the 4-bit value by 3/4 (or
   545:     // rather subtract 1/4); note that a (invalid) value of 15 will bleed into
   546:     // the next octave -- this is confirmed
   547:     /*uint32*/ int adjusted_code = bitfield (block_freq, 6, 4) - bitfield (block_freq, 8, 2);
   548: 
   549:     // now re-insert the 6-bit fraction
   550:     /*sint32*/ int eff_freq = (adjusted_code << 6) | bitfield (block_freq, 0, 6);
   551: 
   552:     // now that the gaps are removed, add the delta
   553:     eff_freq += delta;
   554: 
   555:     // handle over/underflow by adjusting the block:
   556:     if (Integer.compareUnsigned (eff_freq, 768) >= 0) {
   557:       // minimum delta is -512 (PM), so we can only underflow by 1 octave
   558:       if (eff_freq < 0) {
   559:         eff_freq += 768;
   560:         if (block-- == 0) {
   561:           return s_phase_step[0] >>> 7;
   562:         }
   563:       }
   564: 
   565:       // maximum delta is +512+608 (PM+detune), so we can overflow by up to 2 octaves
   566:       else {
   567:         eff_freq -= 768;
   568:         if (eff_freq >= 768) {
   569:           block++;
   570:           eff_freq -= 768;
   571:         }
   572:         if (block++ >= 7) {
   573:           return s_phase_step[767];
   574:         }
   575:       }
   576:     }
   577: 
   578:     // look up the phase shift for the key code, then shift by octave
   579:     return s_phase_step[eff_freq] >>> (block ^ 7);
   580:   }
   581: 
   582:   //-------------------------------------------------
   583:   //  opn_lfo_pm_phase_adjustment - given the 7 most
   584:   //  significant frequency number bits, plus a 3-bit
   585:   //  PM depth value and a signed 5-bit raw PM value,
   586:   //  return a signed PM adjustment to the frequency;
   587:   //  algorithm written to match Nuked behavior
   588:   //-------------------------------------------------
   589:   public static /*sint32*/ int opn_lfo_pm_phase_adjustment (/*uint32*/ int fnum_bits, /*uint32*/ int pm_sensitivity, /*sint32*/ int lfo_raw_pm) {
   590:     // look up the relevant shifts
   591:     /*sint32*/ int abs_pm = (lfo_raw_pm < 0) ? -lfo_raw_pm : lfo_raw_pm;
   592:     /*uint32*/ int shifts = s_lfo_pm_shifts[8 * pm_sensitivity + bitfield (abs_pm, 0, 3)];
   593: 
   594:     // compute the adjustment
   595:     /*sint32*/ int adjust = (fnum_bits >>> bitfield (shifts, 0, 4)) + (fnum_bits >>> bitfield (shifts, 4, 4));
   596:     if (pm_sensitivity > 5) {
   597:       adjust <<= pm_sensitivity - 5;
   598:     }
   599:     adjust >>= 2;
   600: 
   601:     // every 16 cycles it inverts sign
   602:     return (lfo_raw_pm < 0) ? -adjust : adjust;
   603:   }
   604: 
   605: 
   606: 
   607:   // this class holds data that is computed once at the start of clocking
   608:   // and remains static during subsequent sound generation
   609:   //struct opdata_cache
   610:   class opdata_cache {
   611:     /*uint16*/ int[] waveform;  // base of sine table
   612:     /*uint32*/ int phase_step;  // phase step, or PHASE_STEP_DYNAMIC if PM is active
   613:     /*uint32*/ int total_level;  // total level * 8 + KSL
   614:     /*uint32*/ int block_freq;  // raw block frequency value (used to compute phase_step)
   615:     /*sint32*/ int detune;  // detuning value (used to compute phase_step)
   616:     /*uint32*/ int multiple;  // multiple value (x.1, used to compute phase_step)
   617:     /*uint32*/ int eg_sustain;  // sustain level, shifted up to envelope values
   618:     /*uint8*/ int[] eg_rate;  // envelope rate, including KSR
   619:     /*uint8*/ int eg_shift;  // envelope shift amount
   620:     public opdata_cache () {
   621:       eg_rate = new /*uint8*/ int[EG_STATES];
   622:       eg_shift = 0;
   623:     }
   624:   }
   625: 
   626: 
   627: 
   628:   //class fm_registers_base
   629: 
   630:   // helper to apply KSR to the raw ADSR rate, ignoring ksr if the
   631:   // raw value is 0, and clamping to 63
   632:   protected static /*uint32*/ int effective_rate (/*uint32*/ int rawrate, /*uint32*/ int ksr) {
   633:     return (rawrate == 0) ? 0 : umin32 (rawrate + ksr, 63);
   634:   }
   635: 
   636: 
   637: 
   638:   // fm_operator represents an FM operator (or "slot" in FM parlance), which
   639:   // produces an output sine wave modulated by an envelope
   640:   class fm_operator {
   641: 
   642:     // internal state
   643:     private /*uint32*/ int m_choffs;  // channel offset in registers
   644:     private /*uint32*/ int m_opoffs;  // operator offset in registers
   645:     private /*uint32*/ int m_phase;  // current phase value (10.10 format)
   646:     public /*uint16*/ int m_env_attenuation;  // computed envelope attenuation (4.6 format)
   647:     public /*envelope_state*/ int m_env_state;  // current envelope state
   648:     private /*uint8*/ int m_key_state;  // current key state: on or off (bit 0)
   649:     private /*uint8*/ int m_keyon_live;  // live key on state (bit 0 = direct, bit 1 = rhythm, bit 2 = CSM)
   650:     private opdata_cache m_cache;  // cached values for performance
   651: 
   652:     // constructor
   653:     //-------------------------------------------------
   654:     //  fm_operator - constructor
   655:     //-------------------------------------------------
   656:     public fm_operator (/*uint32*/ int opoffs) {
   657:       m_choffs = 0;
   658:       m_opoffs = opoffs;
   659:       m_phase = 0;
   660:       m_env_attenuation = uint16 (0x3ff);
   661:       m_env_state = EG_RELEASE;
   662:       m_key_state = uint8 (0);
   663:       m_keyon_live = uint8 (0);
   664:       m_cache = new opdata_cache ();
   665:     }
   666: 
   667:     // reset the operator state
   668:     //-------------------------------------------------
   669:     //  reset - reset the channel state
   670:     //-------------------------------------------------
   671:     public void reset () {
   672:       // reset our data
   673:       m_phase = 0;
   674:       m_env_attenuation = uint16 (0x3ff);
   675:       m_env_state = EG_RELEASE;
   676:       m_key_state = uint8 (0);
   677:       m_keyon_live = uint8 (0);
   678:     }
   679: 
   680:     // set the current channel
   681:     public void set_choffs (/*uint32*/ int choffs) {
   682:       m_choffs = choffs;
   683:     }
   684: 
   685:     // prepare prior to clocking
   686:     //-------------------------------------------------
   687:     //  prepare - prepare for clocking
   688:     //-------------------------------------------------
   689:     public boolean prepare () {
   690:       // cache the data
   691:       cache_operator_data (m_choffs, m_opoffs, m_cache);
   692: 
   693:       // clock the key state
   694:       clock_keystate (m_keyon_live != 0 ? 1 : 0);
   695:       //m_keyon_live &= ~(1 << KEYON_CSM);
   696:       m_keyon_live = uint8 (m_keyon_live & (~(1 << KEYON_CSM)));
   697: 
   698:       // we're active until we're quiet after the release
   699:       return (m_env_state != EG_RELEASE || Integer.compareUnsigned (m_env_attenuation, EG_QUIET) < 0);
   700:     }
   701: 
   702:     // master clocking function
   703:     //-------------------------------------------------
   704:     //  clock - master clocking function
   705:     //-------------------------------------------------
   706:     public void clock (/*uint32*/ int env_counter, /*sint32*/ int lfo_raw_pm) {
   707:       // clock the envelope if on an envelope cycle; env_counter is a x.2 value
   708:       if (bitfield (env_counter, 0, 2) == 0) {
   709:         clock_envelope (env_counter >>> 2);
   710:       }
   711: 
   712:       // clock the phase
   713:       //-------------------------------------------------
   714:       //  clock_phase - clock the 10.10 phase value; the
   715:       //  OPN version of the logic has been verified
   716:       //  against the Nuked phase generator
   717:       //-------------------------------------------------
   718:       //fm_operator::clock_phase
   719:       // read from the cache, or recalculate if PM active
   720:       /*uint32*/ int phase_step = m_cache.phase_step;
   721:       if (phase_step == PHASE_STEP_DYNAMIC) {
   722:         phase_step = compute_phase_step (m_choffs, m_opoffs, m_cache, lfo_raw_pm);
   723:       }
   724: 
   725:       // finally apply the step to the current phase value
   726:       m_phase += phase_step;
   727:     }
   728: 
   729:     //fm_operator::phase
   730:     // return the current phase value
   731:     public /*uint32*/ int phase () {
   732:       return m_phase >>> 10;
   733:     }
   734: 
   735:     // compute operator volume
   736:     //-------------------------------------------------
   737:     //  compute_volume - compute the 14-bit signed
   738:     //  volume of this operator, given a phase
   739:     //  modulation and an AM LFO offset
   740:     //-------------------------------------------------
   741:     //fm_operator::compute_volume
   742:     public /*sint32*/ int compute_volume (/*uint32*/ int phase, /*uint32*/ int am_offset) {
   743:       // the low 10 bits of phase represents a full 2*PI period over
   744:       // the full sin wave
   745: 
   746:       // early out if the envelope is effectively off
   747:       if (Integer.compareUnsigned (m_env_attenuation, EG_QUIET) > 0) {
   748:         return 0;
   749:       }
   750: 
   751:       // get the absolute value of the sin, as attenuation, as a 4.8 fixed point value
   752:       /*uint32*/ int sin_attenuation = m_cache.waveform[phase & (WAVEFORM_LENGTH - 1)];
   753: 
   754:       // get the attenuation from the evelope generator as a 4.6 value, shifted up to 4.8
   755:       /*uint32*/ int env_attenuation = envelope_attenuation (am_offset) << 2;
   756: 
   757:       // combine into a 5.8 value, then convert from attenuation to 13-bit linear volume
   758:       /*sint32*/ int result = attenuation_to_volume ((sin_attenuation & 0x7fff) + env_attenuation);
   759: 
   760:       // negate if in the negative part of the sin wave (sign bit gives 14 bits)
   761:       return bitfield (sin_attenuation, 15) != 0 ? -result : result;
   762:     }
   763: 
   764:     // compute volume for the OPM noise channel
   765:     //-------------------------------------------------
   766:     //  compute_noise_volume - compute the 14-bit
   767:     //  signed noise volume of this operator, given a
   768:     //  noise input value and an AM offset
   769:     //-------------------------------------------------
   770:     //fm_operator::compute_noise_volume
   771:     public int compute_noise_volume (/*uint32*/ int am_offset) {
   772:       // application manual says the logarithmic transform is not applied here, so we
   773:       // just use the raw envelope attenuation, inverted (since 0 attenuation should be
   774:       // maximum), and shift it up from a 10-bit value to an 11-bit value
   775:       /*sint32*/ int result = (envelope_attenuation (am_offset) ^ 0x3ff) << 1;
   776: 
   777:       // QUESTION: is AM applied still?
   778: 
   779:       // negate based on the noise state
   780:       return bitfield (noise_state (), 0) != 0 ? -result : result;
   781:     }
   782: 
   783:     // key state control
   784:     //-------------------------------------------------
   785:     //  keyonoff - signal a key on/off event
   786:     //-------------------------------------------------
   787:     //fm_operator::keyonoff
   788:     public void keyonoff (/*uint32*/ int on, /*keyon_type*/ int type) {
   789:       m_keyon_live = uint8 ((m_keyon_live & ~(1 << type)) | (bitfield (on, 0) << type));
   790:     }
   791: 
   792:     // start the attack phase
   793:     //-------------------------------------------------
   794:     //  start_attack - start the attack phase; called
   795:     //  when a keyon happens or when an SSG-EG cycle
   796:     //  is complete and restarts
   797:     //-------------------------------------------------
   798:     //fm_operator::start_attack
   799:     private void start_attack () {
   800:       start_attack (false);
   801:     }
   802:     private void start_attack (boolean is_restart) {
   803:       // don't change anything if already in attack state
   804:       if (m_env_state == EG_ATTACK) {
   805:         return;
   806:       }
   807:       m_env_state = EG_ATTACK;
   808: 
   809:       // generally not inverted at start, except if SSG-EG is enabled and
   810:       // one of the inverted modes is specified; leave this alone on a
   811:       // restart, as it is managed by the clock_ssg_eg_state() code
   812: 
   813:       // reset the phase when we start an attack due to a key on
   814:       // (but not when due to an SSG-EG restart except in certain cases
   815:       // managed directly by the SSG-EG code)
   816:       if (!is_restart) {
   817:         m_phase = 0;
   818:       }
   819: 
   820:       // if the attack rate >= 62 then immediately go to max attenuation
   821:       if (Integer.compareUnsigned (m_cache.eg_rate[EG_ATTACK], 62) >= 0) {
   822:         m_env_attenuation = uint16 (0);
   823:       }
   824:     }
   825: 
   826:     // start the release phase
   827:     //-------------------------------------------------
   828:     //  start_release - start the release phase;
   829:     //  called when a keyoff happens
   830:     //-------------------------------------------------
   831:     //fm_operator::start_release
   832:     private void start_release () {
   833:       // don't change anything if already in release state
   834:       if (m_env_state >= EG_RELEASE) {
   835:         return;
   836:       }
   837:       m_env_state = EG_RELEASE;
   838: 
   839:       // if attenuation if inverted due to SSG-EG, snap the inverted attenuation
   840:       // as the starting point
   841:     }
   842: 
   843:     // clock phases
   844:     //-------------------------------------------------
   845:     //  clock_keystate - clock the keystate to match
   846:     //  the incoming keystate
   847:     //-------------------------------------------------
   848:     //fm_operator::clock_keystate
   849:     private void clock_keystate (/*uint32*/ int keystate) {
   850: 
   851:       // has the key changed?
   852:       if ((keystate ^ m_key_state) != 0) {
   853:         m_key_state = uint8 (keystate);
   854: 
   855:         // if the key has turned on, start the attack
   856:         if (keystate != 0) {
   857:           // OPLL has a DP ("depress"?) state to bring the volume
   858:           // down before starting the attack
   859:           start_attack ();
   860:         }
   861: 
   862:         // otherwise, start the release
   863:         else {
   864:           start_release ();
   865:         }
   866:       }
   867:     }
   868: 
   869:     //-------------------------------------------------
   870:     //  clock_ssg_eg_state - clock the SSG-EG state;
   871:     //  should only be called if SSG-EG is enabled
   872:     //-------------------------------------------------
   873:     //fm_operator::clock_ssg_eg_state
   874: 
   875:     //-------------------------------------------------
   876:     //  clock_envelope - clock the envelope state
   877:     //  according to the given count
   878:     //-------------------------------------------------
   879:     //fm_operator::clock_envelope
   880:     private void clock_envelope (/*uint32*/ int env_counter) {
   881:       // handle attack->decay transitions
   882:       if (m_env_state == EG_ATTACK && m_env_attenuation == 0) {
   883:         m_env_state = EG_DECAY;
   884:       }
   885: 
   886:       // handle decay->sustain transitions; it is important to do this immediately
   887:       // after the attack->decay transition above in the event that the sustain level
   888:       // is set to 0 (in which case we will skip right to sustain without doing any
   889:       // decay); as an example where this can be heard, check the cymbals sound
   890:       // in channel 0 of shinobi's test mode sound #5
   891:       if (m_env_state == EG_DECAY && Integer.compareUnsigned (m_env_attenuation, m_cache.eg_sustain) >= 0) {
   892:         m_env_state = EG_SUSTAIN;
   893:       }
   894: 
   895:       // fetch the appropriate 6-bit rate value from the cache
   896:       /*uint32*/ int rate = m_cache.eg_rate[m_env_state];
   897: 
   898:       // compute the rate shift value; this is the shift needed to
   899:       // apply to the env_counter such that it becomes a 5.11 fixed
   900:       // point number
   901:       /*uint32*/ int rate_shift = rate >>> 2;
   902:       env_counter <<= rate_shift;
   903: 
   904:       // see if the fractional part is 0; if not, it's not time to clock
   905:       if (bitfield (env_counter, 0, 11) != 0) {
   906:         return;
   907:       }
   908: 
   909:       // determine the increment based on the non-fractional part of env_counter
   910:       /*uint32*/ int relevant_bits = bitfield (env_counter, (rate_shift <= 11) ? 11 : rate_shift, 3);
   911:       /*uint32*/ int increment = attenuation_increment (rate, relevant_bits);
   912: 
   913:       // attack is the only one that increases
   914:       if (m_env_state == EG_ATTACK) {
   915:         // glitch means that attack rates of 62/63 don't increment if
   916:         // changed after the initial key on (where they are handled
   917:         // specially); nukeykt confirms this happens on OPM, OPN, OPL/OPLL
   918:         // at least so assuming it is true for everyone
   919:         if (rate < 62) {
   920:           //m_env_attenuation += (~m_env_attenuation * increment) >>> 4;
   921:           m_env_attenuation = uint16 (m_env_attenuation + ((~m_env_attenuation * increment) >>> 4));
   922:         }
   923:       }
   924: 
   925:       // all other cases are similar
   926:       else {
   927:         // non-SSG-EG cases just apply the increment
   928:         //m_env_attenuation += increment;
   929:         m_env_attenuation = uint16 (m_env_attenuation + increment);
   930: 
   931:         // SSG-EG only applies if less than mid-point, and then at 4x
   932: 
   933:         // clamp the final attenuation
   934:         if (Integer.compareUnsigned (m_env_attenuation, 0x400) >= 0) {
   935:           m_env_attenuation = uint16 (0x3ff);
   936:         }
   937: 
   938:         // transition from depress to attack
   939: 
   940:         // transition from release to reverb, should switch at -18dB
   941: 
   942:       }
   943:     }
   944: 
   945:     //fm_operator::clock_phase
   946: 
   947:     // return effective attenuation of the envelope
   948:     //-------------------------------------------------
   949:     //  envelope_attenuation - return the effective
   950:     //  attenuation of the envelope
   951:     //-------------------------------------------------
   952:     //fm_operator::envelope_attenuation
   953:     private /*uint32*/ int envelope_attenuation (/*uint32*/ int am_offset) {
   954:       /*uint32*/ int result = m_env_attenuation >>> m_cache.eg_shift;
   955: 
   956:       // invert if necessary due to SSG-EG
   957: 
   958:       // add in LFO AM modulation
   959:       if (op_lfo_am_enable (m_opoffs) != 0) {
   960:         result += am_offset;
   961:       }
   962: 
   963:       // add in total level and KSL from the cache
   964:       result += m_cache.total_level;
   965: 
   966:       // clamp to max, apply shift, and return
   967:       return umin32 (result, 0x3ff);
   968:     }
   969: 
   970:   }  //class fm_operator
   971: 
   972: 
   973: 
   974:   // fm_channel represents an FM channel which combines the output of 2 or 4
   975:   // operators into a final result
   976:   class fm_channel {
   977: 
   978:     // internal state
   979:     private /*uint32*/ int m_choffs;  // channel offset in registers
   980:     private /*sint16*/ int m_feedback_0, m_feedback_1;  // feedback memory for operator 1
   981:     private /*sint16*/ int m_feedback_in;  // next input value for op 1 feedback (set in output)
   982:     public fm_operator[] m_op;  // up to 4 operators
   983: 
   984:     // constructor
   985:     //-------------------------------------------------
   986:     //  fm_channel - constructor
   987:     //-------------------------------------------------
   988:     //fm_channel::fm_channel
   989:     public fm_channel (/*uint32*/ int choffs) {
   990:       m_choffs = choffs;
   991:       m_feedback_0 = m_feedback_1 = sint16 (0);
   992:       m_feedback_in = sint16 (0);
   993:       m_op = new fm_operator[4];
   994:     }
   995: 
   996:     // reset the channel state
   997:     //-------------------------------------------------
   998:     //  reset - reset the channel state
   999:     //-------------------------------------------------
  1000:     //fm_channel::reset
  1001:     public void reset () {
  1002:       // reset our data
  1003:       m_feedback_0 = m_feedback_1 = sint16 (0);
  1004:       m_feedback_in = sint16 (0);
  1005:     }
  1006: 
  1007:     //fm_channel::save_restore
  1008: 
  1009:     // assign operators
  1010:     public void assign (/*uint32*/ int index, fm_operator op) {
  1011:       m_op[index] = op;
  1012:       op.set_choffs (m_choffs);
  1013:     }
  1014: 
  1015:     // signal key on/off to our operators
  1016:     //-------------------------------------------------
  1017:     //  keyonoff - signal key on/off to our operators
  1018:     //-------------------------------------------------
  1019:     //fm_channel::keyonoff
  1020:     public void keyonoff (/*uint32*/ int states, /*keyon_type*/ int type, /*uint32*/ int chnum) {
  1021:       for (/*uint32*/ int opnum = 0; opnum < 4; opnum++) {
  1022:         m_op[opnum].keyonoff (bitfield (states, opnum), type);
  1023:       }
  1024:     }
  1025: 
  1026:     // prepare prior to clocking
  1027:     //-------------------------------------------------
  1028:     //  prepare - prepare for clocking
  1029:     //-------------------------------------------------
  1030:     //fm_channel::prepare
  1031:     public boolean prepare () {
  1032:       /*uint32*/ int active_mask = 0;
  1033: 
  1034:       // prepare all operators and determine if they are active
  1035:       for (/*uint32*/ int opnum = 0; opnum < 4; opnum++) {
  1036:         if (m_op[opnum].prepare ())  {
  1037:           active_mask |= 1 << opnum;
  1038:         }
  1039:       }
  1040: 
  1041:       return (active_mask != 0);
  1042:     }
  1043: 
  1044:     // master clocking function
  1045:     //-------------------------------------------------
  1046:     //  clock - master clock of all operators
  1047:     //-------------------------------------------------
  1048:     //fm_channel::clock
  1049:     public void clock (/*uint32*/ int env_counter, /*sint32*/ int lfo_raw_pm) {
  1050:       // clock the feedback through
  1051:       m_feedback_0 = sint16 (m_feedback_1);
  1052:       m_feedback_1 = sint16 (m_feedback_in);
  1053: 
  1054:       for (/*uint32*/ int opnum = 0; opnum < 4; opnum++) {
  1055:         m_op[opnum].clock (env_counter, lfo_raw_pm);
  1056:       }
  1057:     }
  1058: 
  1059:     //-------------------------------------------------
  1060:     //  output_2op - combine 4 operators according to
  1061:     //  the specified algorithm, returning a sum
  1062:     //  according to the rshift and clipmax parameters,
  1063:     //  which vary between different implementations
  1064:     //-------------------------------------------------
  1065:     //fm_channel::output_2op
  1066: 
  1067:     //-------------------------------------------------
  1068:     //  output_4op - combine 4 operators according to
  1069:     //  the specified algorithm, returning a sum
  1070:     //  according to the rshift and clipmax parameters,
  1071:     //  which vary between different implementations
  1072:     //-------------------------------------------------
  1073:     //fm_channel::output_4op
  1074:     public void output_4op (/*uint32*/ int rshift, /*sint32*/ int clipmax) {
  1075:       // all 4 operators should be populated
  1076: 
  1077:       // AM amount is the same across all operators; compute it once
  1078:       /*uint32*/ int am_offset = lfo_am_offset (m_choffs);
  1079: 
  1080:       // operator 1 has optional self-feedback
  1081:       /*sint32*/ int opmod = 0;
  1082:       /*uint32*/ int feedback = ch_feedback (m_choffs);
  1083:       if (feedback != 0) {
  1084:         opmod = (m_feedback_0 + m_feedback_1) >> (10 - feedback);
  1085:       }
  1086: 
  1087:       // compute the 14-bit volume/value of operator 1 and update the feedback
  1088:       /*sint32*/ int op1value = m_feedback_in = sint16 (m_op[0].compute_volume (m_op[0].phase () + opmod, am_offset));
  1089: 
  1090:       // now that the feedback has been computed, skip the rest if all volumes
  1091:       // are clear; no need to do all this work for nothing
  1092:       if (ch_output_any (m_choffs) == 0) {
  1093:         return;
  1094:       }
  1095: 
  1096:       // OPM/OPN offer 8 different connection algorithms for 4 operators,
  1097:       // and OPL3 offers 4 more, which we designate here as 8-11.
  1098:       //
  1099:       // The operators are computed in order, with the inputs pulled from
  1100:       // an array of values (opout) that is populated as we go:
  1101:       //    0 = 0
  1102:       //    1 = O1
  1103:       //    2 = O2
  1104:       //    3 = O3
  1105:       //    4 = (O4)
  1106:       //    5 = O1+O2
  1107:       //    6 = O1+O3
  1108:       //    7 = O2+O3
  1109:       //
  1110:       // The s_algorithm_ops table describes the inputs and outputs of each
  1111:       // algorithm as follows:
  1112:       //
  1113:       //      ---------x use opout[x] as operator 2 input
  1114:       //      ------xxx- use opout[x] as operator 3 input
  1115:       //      ---xxx---- use opout[x] as operator 4 input
  1116:       //      --x------- include opout[1] in final sum
  1117:       //      -x-------- include opout[2] in final sum
  1118:       //      x--------- include opout[3] in final sum
  1119:       /*uint32*/ int algorithm_ops = s_algorithm_ops[ch_algorithm (m_choffs)];
  1120: 
  1121:       // populate the opout table
  1122:       /*sint16*/ int[] opout = new int[8];
  1123:       opout[0] = sint16 (0);
  1124:       opout[1] = sint16 (op1value);
  1125: 
  1126:       // compute the 14-bit volume/value of operator 2
  1127:       opmod = opout[bitfield (algorithm_ops, 0, 1)] >> 1;
  1128:       opout[2] = sint16 (m_op[1].compute_volume (m_op[1].phase () + opmod, am_offset));
  1129:       opout[5] = sint16 (opout[1] + opout[2]);
  1130: 
  1131:       // compute the 14-bit volume/value of operator 3
  1132:       opmod = opout[bitfield (algorithm_ops, 1, 3)] >> 1;
  1133:       opout[3] = sint16 (m_op[2].compute_volume (m_op[2].phase () + opmod, am_offset));
  1134:       opout[6] = sint16 (opout[1] + opout[3]);
  1135:       opout[7] = sint16 (opout[2] + opout[3]);
  1136: 
  1137:       // compute the 14-bit volume/value of operator 4; this could be a noise
  1138:       // value on the OPM; all algorithms consume OP4 output at a minimum
  1139:       /*sint32*/ int result;
  1140:       if (noise_enable () != 0 && m_choffs == 7) {
  1141:         result = m_op[3].compute_noise_volume (am_offset);
  1142:       } else {
  1143:         opmod = opout[bitfield (algorithm_ops, 4, 3)] >> 1;
  1144:         result = m_op[3].compute_volume (m_op[3].phase () + opmod, am_offset);
  1145:       }
  1146:       result >>= rshift;
  1147: 
  1148:       // optionally add OP1, OP2, OP3
  1149:       /*sint32*/ int clipmin = -clipmax - 1;
  1150:       if (bitfield (algorithm_ops, 7) != 0) {
  1151:         result = clamp (result + (opout[1] >> rshift), clipmin, clipmax);
  1152:       }
  1153:       if (bitfield (algorithm_ops, 8) != 0) {
  1154:         result = clamp (result + (opout[2] >> rshift), clipmin, clipmax);
  1155:       }
  1156:       if (bitfield (algorithm_ops, 9) != 0) {
  1157:         result = clamp (result + (opout[3] >> rshift), clipmin, clipmax);
  1158:       }
  1159: 
  1160:       // add to the output
  1161:       if (ch_output_0 (m_choffs) != 0) {
  1162:         buffer[pointer    ] += result;
  1163:       }
  1164:       if (ch_output_1 (m_choffs) != 0) {
  1165:         buffer[pointer + 1] += result;
  1166:       }
  1167:     }
  1168: 
  1169:   }  //class fm_channel
  1170: 
  1171: 
  1172: 
  1173:   //ym2151
  1174:   // internal state
  1175:   private /*uint8*/ int m_address;  // address register
  1176: 
  1177:   // fm_engine_base represents a set of operators and channels which together
  1178:   // form a Yamaha FM core; chips that implement other engines (ADPCM, wavetable,
  1179:   // etc) take this output and combine it with the others externally
  1180:   //fm_engine_base implements ymfm_engine_callbacks
  1181: 
  1182:   //fm_engine_base
  1183:   // internal state
  1184:   //private ymfm_interface m_intf;  // reference to the system interface
  1185:   private /*uint32*/ int m_env_counter;  // envelope counter; low 2 bits are sub-counter
  1186:   private /*uint8*/ int m_status;  // current status register
  1187:   private /*uint8*/ int m_clock_prescale;  // prescale factor (2/3/6)
  1188:   private /*uint8*/ int m_irq_mask;  // mask of which bits signal IRQs
  1189:   private /*uint8*/ boolean m_irq_state;  // current IRQ state
  1190:   private /*uint8*/ boolean[] m_timer_running;  // current timer running state
  1191:   private /*uint8*/ int m_total_clocks;  // low 8 bits of the total number of clocks processed
  1192:   private /*uint32*/ int m_active_channels;  // mask of active channels (computed by prepare)
  1193:   private /*uint32*/ int m_modified_channels;  // mask of channels that have been modified
  1194:   private /*uint32*/ int m_prepare_count;  // counter to do periodic prepare sweeps
  1195:   public fm_channel[] m_channel = new fm_channel[CHANNELS];  // channel pointers
  1196:   private fm_operator[] m_operator = new fm_operator[OPERATORS];  // operator pointers
  1197: 
  1198:   //opm_registers
  1199:   // OPM register map:
  1200:   //
  1201:   //      System-wide registers:
  1202:   //           01 xxxxxx-x Test register
  1203:   //              ------x- LFO reset
  1204:   //           08 -x------ Key on/off operator 4
  1205:   //              --x----- Key on/off operator 3
  1206:   //              ---x---- Key on/off operator 2
  1207:   //              ----x--- Key on/off operator 1
  1208:   //              -----xxx Channel select
  1209:   //           0F x------- Noise enable
  1210:   //              ---xxxxx Noise frequency
  1211:   //           10 xxxxxxxx Timer A value (upper 8 bits)
  1212:   //           11 ------xx Timer A value (lower 2 bits)
  1213:   //           12 xxxxxxxx Timer B value
  1214:   //           14 x------- CSM mode
  1215:   //              --x----- Reset timer B
  1216:   //              ---x---- Reset timer A
  1217:   //              ----x--- Enable timer B
  1218:   //              -----x-- Enable timer A
  1219:   //              ------x- Load timer B
  1220:   //              -------x Load timer A
  1221:   //           18 xxxxxxxx LFO frequency
  1222:   //           19 0xxxxxxx AM LFO depth
  1223:   //              1xxxxxxx PM LFO depth
  1224:   //           1B xx------ CT (2 output data lines)
  1225:   //              ------xx LFO waveform
  1226:   //
  1227:   //     Per-channel registers (channel in address bits 0-2)
  1228:   //        20-27 x------- Pan right
  1229:   //              -x------ Pan left
  1230:   //              --xxx--- Feedback level for operator 1 (0-7)
  1231:   //              -----xxx Operator connection algorithm (0-7)
  1232:   //        28-2F -xxxxxxx Key code
  1233:   //        30-37 xxxxxx-- Key fraction
  1234:   //        38-3F -xxx---- LFO PM sensitivity
  1235:   //              ------xx LFO AM shift
  1236:   //
  1237:   //     Per-operator registers (channel in address bits 0-2, operator in bits 3-4)
  1238:   //        40-5F -xxx---- Detune value (0-7)
  1239:   //              ----xxxx Multiple value (0-15)
  1240:   //        60-7F -xxxxxxx Total level (0-127)
  1241:   //        80-9F xx------ Key scale rate (0-3)
  1242:   //              ---xxxxx Attack rate (0-31)
  1243:   //        A0-BF x------- LFO AM enable
  1244:   //              ---xxxxx Decay rate (0-31)
  1245:   //        C0-DF xx------ Detune 2 value (0-3)
  1246:   //              ---xxxxx Sustain rate (0-31)
  1247:   //        E0-FF xxxx---- Sustain level (0-15)
  1248:   //              ----xxxx Release rate (0-15)
  1249:   //
  1250:   //     Internal (fake) registers:
  1251:   //           1A -xxxxxxx PM depth
  1252:   // internal state
  1253:   protected /*uint32*/ int m_lfo_counter;  // LFO counter
  1254:   protected /*uint32*/ int m_noise_lfsr;  // noise LFSR state
  1255:   protected /*uint8*/ int m_noise_counter;  // noise counter
  1256:   protected /*uint8*/ int m_noise_state;  // latched noise state
  1257:   protected /*uint8*/ int m_noise_lfo;  // latched LFO noise value
  1258:   protected /*uint8*/ int m_lfo_am;  // current LFO AM value
  1259:   protected /*uint8*/ int[] m_regdata;  // register data
  1260:   protected /*sint16*/ int[] m_lfo_waveform;  // LFO waveforms; AM in low 8, PM in upper 8
  1261:   protected /*uint16*/ int[] m_waveform;  // waveforms
  1262: 
  1263: 
  1264: 
  1265:   public YM2151 () {
  1266: 
  1267:     //-------------------------------------------------
  1268:     //  ym2151 - constructor
  1269:     //-------------------------------------------------
  1270:     m_address = uint8 (0);
  1271: 
  1272:     //-------------------------------------------------
  1273:     //  fm_engine_base - constructor
  1274:     //-------------------------------------------------
  1275:     //m_intf = intf;
  1276:     m_env_counter = 0;
  1277:     m_status = uint8 (0);
  1278:     m_clock_prescale = uint8 (DEFAULT_PRESCALE);
  1279:     m_irq_mask = uint8 (STATUS_TIMERA | STATUS_TIMERB);
  1280:     m_irq_state = false;
  1281:     m_timer_running = new boolean[] { false, false };
  1282:     m_active_channels = ALL_CHANNELS;
  1283:     m_modified_channels = ALL_CHANNELS;
  1284:     m_prepare_count = 0;
  1285: 
  1286:     // inform the interface of their engine
  1287:     //m_intf.m_engine = this;
  1288: 
  1289:     // create the channels
  1290:     for (/*uint32*/ int chnum = 0; chnum < CHANNELS; chnum++) {
  1291:       m_channel[chnum] = new fm_channel (channel_offset (chnum));
  1292:     }
  1293: 
  1294:     // create the operators
  1295:     for (/*uint32*/ int opnum = 0; opnum < OPERATORS; opnum++) {
  1296:       m_operator[opnum] = new fm_operator (operator_offset (opnum));
  1297:     }
  1298: 
  1299:     // do the initial operator assignment
  1300:     //-------------------------------------------------
  1301:     //  assign_operators - get the current mapping of
  1302:     //  operators to channels and assign them all
  1303:     //-------------------------------------------------
  1304:     //fm_engine_base::assign_operators
  1305:     for (/*uint32*/ int chnum = 0; chnum < CHANNELS; chnum++) {
  1306:       for (/*uint32*/ int index = 0; index < 4; index++) {
  1307:         /*uint32*/ int opnum = bitfield (s_fixed_map[chnum], 8 * index, 8);
  1308:         m_channel[chnum].assign (index, m_operator[opnum]);
  1309:       }
  1310:     }
  1311: 
  1312:     //-------------------------------------------------
  1313:     //  opm_registers - constructor
  1314:     //-------------------------------------------------
  1315:     m_lfo_counter = 0;
  1316:     m_noise_lfsr = 1;
  1317:     m_noise_counter = uint8 (0);
  1318:     m_noise_state = uint8 (0);
  1319:     m_noise_lfo = uint8 (0);
  1320:     m_lfo_am = uint8 (0);
  1321: 
  1322:     m_regdata = new /*uint8*/ int[REGISTERS];
  1323:     m_lfo_waveform = new /*sint16*/ int[LFO_WAVEFORM_LENGTH * 4];
  1324:     m_waveform = new /*uint16*/ int[WAVEFORM_LENGTH * WAVEFORMS];
  1325: 
  1326:     // create the waveforms
  1327:     for (/*uint32*/ int index = 0; index < WAVEFORM_LENGTH; index++) {
  1328:       m_waveform[WAVEFORM_LENGTH * 0 + index] = uint16 (abs_sin_attenuation (index) | (bitfield (index, 9) << 15));
  1329:     }
  1330: 
  1331:     // create the LFO waveforms; AM in the low 8 bits, PM in the upper 8
  1332:     // waveforms are adjusted to match the pictures in the application manual
  1333:     for (/*uint32*/ int index = 0; index < LFO_WAVEFORM_LENGTH; index++) {
  1334:       // waveform 0 is a sawtooth
  1335:       /*uint8*/ int am = uint8 (index ^ 0xff);
  1336:       /*sint8*/ int pm = sint8 (index);
  1337:       m_lfo_waveform[LFO_WAVEFORM_LENGTH * 0 + index] = sint16 (am | (pm << 8));
  1338: 
  1339:       // waveform 1 is a square wave
  1340:       am = uint8 (bitfield (index, 7) != 0 ? 0 : 0xff);
  1341:       pm = sint8 (am ^ 0x80);
  1342:       m_lfo_waveform[LFO_WAVEFORM_LENGTH * 1 + index] = sint16 (am | (pm << 8));
  1343: 
  1344:       // waveform 2 is a triangle wave
  1345:       am = uint8 (bitfield (index, 7) != 0 ? (index << 1) : ((index ^ 0xff) << 1));
  1346:       pm = sint8 (bitfield (index, 6) != 0 ? am : ~am);
  1347:       m_lfo_waveform[LFO_WAVEFORM_LENGTH * 2 + index] = sint16 (am | (pm << 8));
  1348: 
  1349:       // waveform 3 is noise; it is filled in dynamically
  1350:       m_lfo_waveform[LFO_WAVEFORM_LENGTH * 3 + index] = sint16 (0);
  1351:     }
  1352: 
  1353:     init2 ();
  1354:   }
  1355: 
  1356:   // reset
  1357:   //-------------------------------------------------
  1358:   //  reset - reset the system
  1359:   //-------------------------------------------------
  1360:   // reset the overall state
  1361:   //-------------------------------------------------
  1362:   //  reset - reset the overall state
  1363:   //-------------------------------------------------
  1364:   public void reset () {
  1365:     // reset the engines
  1366:     // reset all status bits
  1367:     set_reset_status (0, 0xff);
  1368: 
  1369:     // register type-specific initialization
  1370:     // reset to initial state
  1371:     //-------------------------------------------------
  1372:     //  reset - reset to initial state
  1373:     //-------------------------------------------------
  1374:     Arrays.fill (m_regdata, 0, REGISTERS, uint8 (0));
  1375: 
  1376:     // enable output on both channels by default
  1377:     m_regdata[0x20] = m_regdata[0x21] = m_regdata[0x22] = m_regdata[0x23] = uint8 (0xc0);
  1378:     m_regdata[0x24] = m_regdata[0x25] = m_regdata[0x26] = m_regdata[0x27] = uint8 (0xc0);
  1379: 
  1380:     // explicitly write to the mode register since it has side-effects
  1381:     // QUESTION: old cores initialize this to 0x30 -- who is right?
  1382:     writeAddress (REG_MODE);
  1383:     writeData (0);
  1384: 
  1385:     // reset the channels
  1386:     for (fm_channel chan : m_channel) {
  1387:       chan.reset ();
  1388:     }
  1389: 
  1390:     // reset the operators
  1391:     for (fm_operator op : m_operator) {
  1392:       op.reset ();
  1393:     }
  1394:   }
  1395: 
  1396:   //-------------------------------------------------
  1397:   //  read_status - read the status register
  1398:   //-------------------------------------------------
  1399:   //public /*uint8*/ int read_status () {
  1400:   public int readStatus () {
  1401:     /*uint8*/ int result = uint8 (status ());
  1402:     //if (m_intf.ymfm_is_busy ()) {
  1403:     if (listener != null && listener.isBusy ()) {
  1404:       //result |= STATUS_BUSY;
  1405:       result = uint8 (result | STATUS_BUSY);
  1406:     }
  1407:     return uint8 (result);
  1408:   }
  1409: 
  1410:   //-------------------------------------------------
  1411:   //  writeAddress - handle a write to the address
  1412:   //  register
  1413:   //-------------------------------------------------
  1414:   public void writeAddress (int address) {
  1415:     address &= 0xff;
  1416: 
  1417:     // just set the address
  1418:     m_address = address;
  1419:   }
  1420: 
  1421:   //-------------------------------------------------
  1422:   //  write - handle a write to the register
  1423:   //  interface
  1424:   //-------------------------------------------------
  1425:   public void writeData (int data) {
  1426:     data &= 0xff;
  1427:     if (listener != null) {
  1428:       listener.written (pointer, m_address, data);
  1429:     }
  1430: 
  1431:     // write the FM register
  1432:     // special case: writes to the mode register can impact IRQs;
  1433:     // schedule these writes to ensure ordering with timers
  1434:     if (m_address == REG_MODE) {
  1435:       //m_intf.ymfm_sync_mode_write (data);
  1436:       engine_mode_write (data);
  1437:       return;
  1438:     }
  1439: 
  1440:     // for now just mark all channels as modified
  1441:     m_modified_channels = ALL_CHANNELS;
  1442: 
  1443:     // most writes are passive, consumed only when needed
  1444:     regs_write (m_address, data);
  1445:     // handle writes to the key on index
  1446:     if (m_address == 0x08) {
  1447:       /*uint32*/ int keyon_channel = bitfield (data, 0, 3);
  1448:       /*uint32*/ int keyon_opmask = bitfield (data, 3, 4);
  1449:       // handle writes to the keyon register(s)
  1450:       if (keyon_channel < CHANNELS) {
  1451:         // normal channel on/off
  1452:         m_channel[keyon_channel].keyonoff (keyon_opmask, KEYON_NORMAL, keyon_channel);
  1453:       }
  1454:     }
  1455: 
  1456:     // special cases
  1457:     if (m_address == 0x1b) {
  1458:       // writes to register 0x1B send the upper 2 bits to the output lines
  1459:       //m_intf.ymfm_external_write (0, data >>> 6);
  1460:       if (listener != null) {
  1461:         listener.control ((data >>> 6) & 3);
  1462:       }
  1463:     }
  1464: 
  1465:     // mark busy for a bit
  1466:     //m_intf.ymfm_set_busy_end (32 * clock_prescale ());
  1467:     listener.busy (32 * clock_prescale ());
  1468:   }
  1469: 
  1470:   // generate one sample of sound
  1471:   //-------------------------------------------------
  1472:   //  generate - generate one sample of sound
  1473:   //-------------------------------------------------
  1474:   //ym2151::generate
  1475:   public void generate (int limit) {
  1476:     for (; pointer < limit; pointer += 2) {
  1477: 
  1478:       // clock the system
  1479: 
  1480:       //-------------------------------------------------
  1481:       //  clock - iterate over all channels, clocking
  1482:       //  them forward one step
  1483:       //-------------------------------------------------
  1484:       //fm_engine_base::clock
  1485: 
  1486:       // update the clock counter
  1487:       //m_total_clocks++;
  1488:       m_total_clocks = uint8 (m_total_clocks + 1);
  1489: 
  1490:       // if something was modified, prepare
  1491:       // also prepare every 4k samples to catch ending notes
  1492:       if (m_modified_channels != 0 || Integer.compareUnsigned (m_prepare_count++, 4096) >= 0) {
  1493: 
  1494:         // call each channel to prepare
  1495:         m_active_channels = 0;
  1496:         for (/*uint32*/ int chnum = 0; chnum < CHANNELS; chnum++) {
  1497:           if (m_channel[chnum].prepare ()) {
  1498:             m_active_channels |= 1 << chnum;
  1499:           }
  1500:         }
  1501: 
  1502:         // reset the modified channels and prepare count
  1503:         m_modified_channels = m_prepare_count = 0;
  1504:       }
  1505: 
  1506:       // if the envelope clock divider is 1, just increment by 4;
  1507:       // otherwise, increment by 1 and manually wrap when we reach the divide count
  1508:       if (EG_CLOCK_DIVIDER == 1) {
  1509:         m_env_counter += 4;
  1510:       } else if (bitfield (++m_env_counter, 0, 2) == EG_CLOCK_DIVIDER) {
  1511:         m_env_counter += 4 - EG_CLOCK_DIVIDER;
  1512:       }
  1513: 
  1514:       // clock the noise generator
  1515:       /*sint32*/ int lfo_raw_pm = clock_noise_and_lfo ();
  1516: 
  1517:       // now update the state of all the channels and operators
  1518:       for (/*uint32*/ int chnum = 0; chnum < CHANNELS; chnum++) {
  1519:         m_channel[chnum].clock (m_env_counter, lfo_raw_pm);
  1520:       }
  1521: 
  1522:       //ym2151::generate
  1523: 
  1524:       // update the FM content; OPM is full 14-bit with no intermediate clipping
  1525:       buffer[pointer    ] = 0;
  1526:       buffer[pointer + 1] = 0;
  1527:       /*uint32*/ int chanmask = channelMask;  //ALL_CHANNELS
  1528: 
  1529:       //fm_engine_base::output
  1530: 
  1531:       // mask out inactive channels
  1532:       chanmask &= m_active_channels;
  1533: 
  1534:       // sum over all the desired channels
  1535:       for (/*uint32*/ int chnum = 0; chnum < CHANNELS; chnum++) {
  1536:         if (bitfield (chanmask, chnum) != 0) {
  1537:           m_channel[chnum].output_4op (0, 32767);
  1538:         }
  1539:       }
  1540: 
  1541:       //ym2151::generate
  1542: 
  1543:       // YM2151 uses an external DAC (YM3012) with mantissa/exponent format
  1544:       // convert to 10.3 floating point value and back to simulate truncation
  1545:       buffer[pointer    ] = roundtrip_fp (buffer[pointer    ]);
  1546:       buffer[pointer + 1] = roundtrip_fp (buffer[pointer + 1]);
  1547: 
  1548:     }  //for pointer
  1549:   }
  1550: 
  1551: 
  1552: 
  1553:   //class fm_engine_base
  1554: 
  1555:   // return the current status
  1556:   //-------------------------------------------------
  1557:   //  status - return the current state of the
  1558:   //  status flags
  1559:   //-------------------------------------------------
  1560:   public /*uint8*/ int status () {
  1561:     return uint8 (m_status & ~STATUS_BUSY);
  1562:   }
  1563: 
  1564:   // set/reset bits in the status register, updating the IRQ status
  1565:   public /*uint8*/ int set_reset_status (/*uint8*/ int set, /*uint8*/ int reset) {
  1566:     m_status = uint8 ((m_status | set) & ~(reset | STATUS_BUSY));
  1567:     //m_intf.ymfm_sync_check_interrupts ();
  1568:     engine_check_interrupts ();
  1569:     return uint8 (m_status);
  1570:   }
  1571: 
  1572:   // set the IRQ mask
  1573:   public void set_irq_mask (/*uint8*/ int mask) {
  1574:     m_irq_mask = uint8 (mask);
  1575:     //m_intf.ymfm_sync_check_interrupts ();
  1576:     engine_check_interrupts ();
  1577:   }
  1578: 
  1579:   // return the current clock prescale
  1580:   public /*uint32*/ int clock_prescale () {
  1581:     return m_clock_prescale;
  1582:   }
  1583: 
  1584:   // set prescale factor (2/3/6)
  1585:   public void set_clock_prescale (/*uint32*/ int prescale) {
  1586:     m_clock_prescale = uint8 (prescale);
  1587:   }
  1588: 
  1589:   // timer callback; called by the interface when a timer fires
  1590:   //-------------------------------------------------
  1591:   //  engine_timer_expired - timer has expired - signal
  1592:   //  status and possibly IRQs
  1593:   //-------------------------------------------------
  1594:   public void engine_timer_expired (/*uint32*/ int tnum) {
  1595:     // update status
  1596:     if (tnum == 0 && enable_timer_a () != 0) {
  1597:       set_reset_status (STATUS_TIMERA, 0);
  1598:     } else if (tnum == 1 && enable_timer_b () != 0) {
  1599:       set_reset_status (STATUS_TIMERB, 0);
  1600:     }
  1601: 
  1602:     // if timer A fired in CSM mode, trigger CSM on all relevant channels
  1603:     if (tnum == 0 && csm () != 0) {
  1604:       for (/*uint32*/ int chnum = 0; chnum < CHANNELS; chnum++) {
  1605:         if (bitfield (CSM_TRIGGER_MASK, chnum) != 0) {
  1606:           m_channel[chnum].keyonoff (1, KEYON_CSM, chnum);
  1607:           m_modified_channels |= 1 << chnum;
  1608:         }
  1609:       }
  1610:     }
  1611: 
  1612:     // reset
  1613:     m_timer_running[tnum] = false;
  1614:     update_timer (tnum, 1, 0);
  1615:   }
  1616: 
  1617:   // check interrupts; called by the interface after synchronization
  1618:   //-------------------------------------------------
  1619:   //  check_interrupts - check the interrupt sources
  1620:   //  for interrupts
  1621:   //-------------------------------------------------
  1622:   public void engine_check_interrupts () {
  1623:     // update the state
  1624:     /*uint8*/ boolean old_state = m_irq_state;
  1625:     m_irq_state = (m_status & m_irq_mask) != 0;
  1626: 
  1627:     // set the IRQ status bit
  1628:     if (m_irq_state) {
  1629:       //m_status |= STATUS_IRQ;
  1630:       m_status = uint8 (m_status | STATUS_IRQ);
  1631:     } else {
  1632:       //m_status &= ~STATUS_IRQ;
  1633:       m_status = uint8 (m_status & (~STATUS_IRQ));
  1634:     }
  1635: 
  1636:     // if changed, signal the new state
  1637:     if (old_state != m_irq_state) {
  1638:       //m_intf.ymfm_update_irq (m_irq_state);
  1639:       listener.irq (m_irq_state);
  1640:     }
  1641:   }
  1642: 
  1643:   // mode register write; called by the interface after synchronization
  1644:   //-------------------------------------------------
  1645:   //  engine_mode_write - handle a mode register write
  1646:   //  via timer callback
  1647:   //-------------------------------------------------
  1648:   public void engine_mode_write (/*uint8*/ int data) {
  1649:     // mark all channels as modified
  1650:     m_modified_channels = ALL_CHANNELS;
  1651: 
  1652:     // actually write the mode register now
  1653:     regs_write (REG_MODE, data);
  1654: 
  1655:     // reset IRQ status -- when written, all other bits are ignored
  1656:     // QUESTION: should this maybe just reset the IRQ bit and not all the bits?
  1657:     //   That is, check_interrupts would only set, this would only clear?
  1658: 
  1659:     // reset timer status
  1660:     /*uint8*/ int reset_mask = 0;
  1661:     if (reset_timer_b () != 0) {
  1662:       //reset_mask |= STATUS_TIMERB;
  1663:       reset_mask = uint8 (reset_mask | STATUS_TIMERB);
  1664:     }
  1665:     if (reset_timer_a () != 0) {
  1666:       //reset_mask |= STATUS_TIMERA;
  1667:       reset_mask = uint8 (reset_mask | STATUS_TIMERA);
  1668:     }
  1669:     set_reset_status (0, reset_mask);
  1670: 
  1671:     // load timers; note that timer B gets a small negative adjustment because
  1672:     // the *16 multiplier is free-running, so the first tick of the clock
  1673:     // is a bit shorter
  1674:     updateTimerB (load_timer_b (), -(m_total_clocks & 15));
  1675:     updateTimerA (load_timer_a (), 0);
  1676:   }
  1677: 
  1678:   protected void updateTimerA (int enable, int delta_clocks) {
  1679:     update_timer (0, enable, delta_clocks);
  1680:   }
  1681:   protected void updateTimerB (int enable, int delta_clocks) {
  1682:     update_timer (1, enable, delta_clocks);
  1683:   }
  1684: 
  1685:   // update the state of the given timer
  1686:   //-------------------------------------------------
  1687:   //  update_timer - update the state of the given
  1688:   //  timer
  1689:   //-------------------------------------------------
  1690:   protected void update_timer (/*uint32*/ int tnum, /*uint32*/ int enable, /*sint32*/ int delta_clocks) {
  1691:     // if the timer is live, but not currently enabled, set the timer
  1692:     if (enable != 0 && !m_timer_running[tnum]) {
  1693:       // period comes from the registers, and is different for each
  1694:       /*uint32*/ int period = (tnum == 0) ? (1024 - timer_a_value ()) : 16 * (256 - timer_b_value ());
  1695: 
  1696:       // caller can also specify a delta to account for other effects
  1697:       period += delta_clocks;
  1698: 
  1699:       // reset it
  1700:       //m_intf.ymfm_set_timer (tnum, period * OPERATORS * m_clock_prescale);
  1701:       if (tnum == 0) {
  1702:         listener.timerA (period * OPERATORS * m_clock_prescale);
  1703:       } else {
  1704:         listener.timerB (period * OPERATORS * m_clock_prescale);
  1705:       }
  1706:       m_timer_running[tnum] = true;
  1707:     }
  1708: 
  1709:     // if the timer is not live, ensure it is not enabled
  1710:     else if (enable == 0) {
  1711:       //m_intf.ymfm_set_timer (tnum, -1);
  1712:       if (tnum == 0) {
  1713:         listener.timerA (-1);
  1714:       } else {
  1715:         listener.timerB (-1);
  1716:       }
  1717:       m_timer_running[tnum] = false;
  1718:     }
  1719:   }
  1720: 
  1721: 
  1722: 
  1723:   //class opm_registers
  1724: 
  1725:   // map channel number to register offset
  1726:   public static /*uint32*/ int channel_offset (/*uint32*/ int chnum) {
  1727:     return chnum;
  1728:   }
  1729: 
  1730:   // map operator number to register offset
  1731:   public static /*uint32*/ int operator_offset (/*uint32*/ int opnum) {
  1732:     return opnum;
  1733:   }
  1734: 
  1735:   // handle writes to the register array
  1736:   //-------------------------------------------------
  1737:   //  write - handle writes to the register array
  1738:   //-------------------------------------------------
  1739:   public void regs_write (/*uint16*/ int index, /*uint8*/ int data) {
  1740:     // LFO AM/PM depth are written to the same register (0x19);
  1741:     // redirect the PM depth to an unused neighbor (0x1a)
  1742:     if (index == 0x19) {
  1743:       m_regdata[index + bitfield (data, 7)] = uint8 (data);
  1744:     } else if (index != 0x1a) {
  1745:       m_regdata[index] = uint8 (data);
  1746:     }
  1747:   }
  1748: 
  1749:   // clock the noise and LFO, if present, returning LFO PM value
  1750:   //-------------------------------------------------
  1751:   //  clock_noise_and_lfo - clock the noise and LFO,
  1752:   //  handling clock division, depth, and waveform
  1753:   //  computations
  1754:   //-------------------------------------------------
  1755:   public int clock_noise_and_lfo () {
  1756:     // base noise frequency is measured at 2x 1/2 FM frequency; this
  1757:     // means each tick counts as two steps against the noise counter
  1758:     /*uint32*/ int freq = noise_frequency ();
  1759:     for (int rep = 0; rep < 2; rep++) {
  1760:       // evidence seems to suggest the LFSR is clocked continually and just
  1761:       // sampled at the noise frequency for output purposes; note that the
  1762:       // low 8 bits are the most recent 8 bits of history while bits 8-24
  1763:       // contain the 17 bit LFSR state
  1764:       m_noise_lfsr <<= 1;
  1765:       m_noise_lfsr |= bitfield (m_noise_lfsr, 17) ^ bitfield (m_noise_lfsr, 14) ^ 1;
  1766: 
  1767:       // compare against the frequency and latch when we exceed it
  1768:       //if (m_noise_counter++ >= freq) {
  1769:       if (Integer.compareUnsigned ((m_noise_counter = uint8 (m_noise_counter + 1)), freq) >= 0) {
  1770:         m_noise_counter = uint8 (0);
  1771:         m_noise_state = uint8 (bitfield (m_noise_lfsr, 17));
  1772:       }
  1773:     }
  1774: 
  1775:     // treat the rate as a 4.4 floating-point step value with implied
  1776:     // leading 1; this matches exactly the frequencies in the application
  1777:     // manual, though it might not be implemented exactly this way on chip
  1778:     /*uint32*/ int rate = lfo_rate ();
  1779:     m_lfo_counter += (0x10 | bitfield (rate, 0, 4)) << bitfield (rate, 4, 4);
  1780: 
  1781:     // bit 1 of the test register is officially undocumented but has been
  1782:     // discovered to hold the LFO in reset while active
  1783:     if (lfo_reset () != 0) {
  1784:       m_lfo_counter = 0;
  1785:     }
  1786: 
  1787:     // now pull out the non-fractional LFO value
  1788:     /*uint32*/ int lfo = bitfield (m_lfo_counter, 22, 8);
  1789: 
  1790:     // fill in the noise entry 1 ahead of our current position; this
  1791:     // ensures the current value remains stable for a full LFO clock
  1792:     // and effectively latches the running value when the LFO advances
  1793:     /*uint32*/ int lfo_noise = bitfield (m_noise_lfsr, 17, 8);
  1794:     m_lfo_waveform[LFO_WAVEFORM_LENGTH * 3 + ((lfo + 1) & 0xff)] = sint16 (lfo_noise | (lfo_noise << 8));
  1795: 
  1796:     // fetch the AM/PM values based on the waveform; AM is unsigned and
  1797:     // encoded in the low 8 bits, while PM signed and encoded in the upper
  1798:     // 8 bits
  1799:     /*sint32*/ int ampm = m_lfo_waveform[LFO_WAVEFORM_LENGTH * lfo_waveform () + lfo];
  1800: 
  1801:     // apply depth to the AM value and store for later
  1802:     m_lfo_am = uint8 (((ampm & 0xff) * lfo_am_depth ()) >>> 7);
  1803: 
  1804:     // apply depth to the PM value and return it
  1805:     return ((ampm >> 8) * lfo_pm_depth ()) >> 7;
  1806:   }
  1807: 
  1808:   // return the AM offset from LFO for the given channel
  1809:   //-------------------------------------------------
  1810:   //  lfo_am_offset - return the AM offset from LFO
  1811:   //  for the given channel
  1812:   //-------------------------------------------------
  1813:   public /*uint32*/ int lfo_am_offset (/*uint32*/ int choffs) {
  1814:     // OPM maps AM quite differently from OPN
  1815: 
  1816:     // shift value for AM sensitivity is [*, 0, 1, 2],
  1817:     // mapping to values of [0, 23.9, 47.8, and 95.6dB]
  1818:     /*uint32*/ int am_sensitivity = ch_lfo_am_sens (choffs);
  1819:     if (am_sensitivity == 0) {
  1820:       return 0;
  1821:     }
  1822: 
  1823:     // QUESTION: see OPN note below for the dB range mapping; it applies
  1824:     // here as well
  1825: 
  1826:     // raw LFO AM value on OPM is 0-FF, which is already a factor of 2
  1827:     // larger than the OPN below, putting our staring point at 2x theirs;
  1828:     // this works out since our minimum is 2x their maximum
  1829:     return m_lfo_am << (am_sensitivity - 1);
  1830:   }
  1831: 
  1832:   // return the current noise state, gated by the noise clock
  1833:   public /*uint32*/ int noise_state () {
  1834:     return m_noise_state;
  1835:   }
  1836: 
  1837:   // caching helpers
  1838:   //-------------------------------------------------
  1839:   //  cache_operator_data - fill the operator cache
  1840:   //  with prefetched data
  1841:   //-------------------------------------------------
  1842:   public void cache_operator_data (/*uint32*/ int choffs, /*uint32*/ int opoffs, opdata_cache cache) {
  1843:     // set up the easy stuff
  1844:     cache.waveform = m_waveform;
  1845: 
  1846:     // get frequency from the channel
  1847:     /*uint32*/ int block_freq = cache.block_freq = ch_block_freq (choffs);
  1848: 
  1849:     // compute the keycode: block_freq is:
  1850:     //
  1851:     //     BBBCCCCFFFFFF
  1852:     //     ^^^^^
  1853:     //
  1854:     // the 5-bit keycode is just the top 5 bits (block + top 2 bits
  1855:     // of the key code)
  1856:     /*uint32*/ int keycode = bitfield (block_freq, 8, 5);
  1857: 
  1858:     // detune adjustment
  1859:     cache.detune = detune_adjustment (op_detune (opoffs), keycode);
  1860: 
  1861:     // multiple value, as an x.1 value (0 means 0.5)
  1862:     cache.multiple = op_multiple (opoffs) * 2;
  1863:     if (cache.multiple == 0) {
  1864:       cache.multiple = 1;
  1865:     }
  1866: 
  1867:     // phase step, or PHASE_STEP_DYNAMIC if PM is active; this depends on
  1868:     // block_freq, detune, and multiple, so compute it after we've done those
  1869:     if (lfo_pm_depth () == 0 || ch_lfo_pm_sens (choffs) == 0){
  1870:       cache.phase_step = compute_phase_step (choffs, opoffs, cache, 0);
  1871:     } else {
  1872:       cache.phase_step = PHASE_STEP_DYNAMIC;
  1873:     }
  1874: 
  1875:     // total level, scaled by 8
  1876:     cache.total_level = op_total_level (opoffs) << 3;
  1877: 
  1878:     // 4-bit sustain level, but 15 means 31 so effectively 5 bits
  1879:     cache.eg_sustain = op_sustain_level (opoffs);
  1880:     cache.eg_sustain |= (cache.eg_sustain + 1) & 0x10;
  1881:     cache.eg_sustain <<= 5;
  1882: 
  1883:     // determine KSR adjustment for enevlope rates
  1884:     /*uint32*/ int ksrval = keycode >>> (op_ksr (opoffs) ^ 3);
  1885:     cache.eg_rate[EG_ATTACK] = uint8 (effective_rate (op_attack_rate (opoffs) * 2, ksrval));
  1886:     cache.eg_rate[EG_DECAY] = uint8 (effective_rate (op_decay_rate (opoffs) * 2, ksrval));
  1887:     cache.eg_rate[EG_SUSTAIN] = uint8 (effective_rate (op_sustain_rate (opoffs) * 2, ksrval));
  1888:     cache.eg_rate[EG_RELEASE] = uint8 (effective_rate (op_release_rate (opoffs) * 4 + 2, ksrval));
  1889:   }
  1890: 
  1891:   // compute the phase step, given a PM value
  1892:   //-------------------------------------------------
  1893:   //  compute_phase_step - compute the phase step
  1894:   //-------------------------------------------------
  1895:   public /*uint32*/ int compute_phase_step (/*uint32*/ int choffs, /*uint32*/ int opoffs, opdata_cache cache, /*sint32*/ int lfo_raw_pm) {
  1896:     // OPM logic is rather unique here, due to extra detune
  1897:     // and the use of key codes (not to be confused with keycode)
  1898: 
  1899:     // start with coarse detune delta; table uses cents value from
  1900:     // manual, converted into 1/64ths
  1901:     /*sint32*/ int delta = s_detune2_delta[op_detune2 (opoffs)];
  1902: 
  1903:     // add in the PM delta
  1904:     /*uint32*/ int pm_sensitivity = ch_lfo_pm_sens (choffs);
  1905:     if (pm_sensitivity != 0) {
  1906:       // raw PM value is -127..128 which is +/- 200 cents
  1907:       // manual gives these magnitudes in cents:
  1908:       //    0, +/-5, +/-10, +/-20, +/-50, +/-100, +/-400, +/-700
  1909:       // this roughly corresponds to shifting the 200-cent value:
  1910:       //    0  >> 5,  >> 4,  >> 3,  >> 2,  >> 1,   << 1,   << 2
  1911:       if (pm_sensitivity < 6) {
  1912:         delta += lfo_raw_pm >> (6 - pm_sensitivity);
  1913:       } else {
  1914:         delta += lfo_raw_pm << (pm_sensitivity - 5);
  1915:       }
  1916:     }
  1917: 
  1918:     // apply delta and convert to a frequency number
  1919:     /*uint32*/ int phase_step = opm_key_code_to_phase_step (cache.block_freq, delta);
  1920: 
  1921:     // apply detune based on the keycode
  1922:     phase_step += cache.detune;
  1923: 
  1924:     // apply frequency multiplier (which is cached as an x.1 value)
  1925:     return (phase_step * cache.multiple) >>> 1;
  1926:   }
  1927: 
  1928:   // return a bitfield extracted from a byte
  1929:   private /*uint32*/ int regbyte (/*uint32*/ int offset, /*uint32*/ int start, /*uint32*/ int count) {
  1930:     return bitfield (m_regdata[offset + 0], start, count);
  1931:   }
  1932:   private /*uint32*/ int regbyte (/*uint32*/ int offset, /*uint32*/ int start, /*uint32*/ int count, /*uint32*/ int extra_offset) {
  1933:     return bitfield (m_regdata[offset + extra_offset], start, count);
  1934:   }
  1935: 
  1936:   // return a bitfield extracted from a pair of bytes, MSBs listed first
  1937:   private /*uint32*/ int regword (/*uint32*/ int offset1, /*uint32*/ int start1, /*uint32*/ int count1, /*uint32*/ int offset2, /*uint32*/ int start2, /*uint32*/ int count2) {
  1938:     return (regbyte (offset1, start1, count1, 0) << count2) | regbyte (offset2, start2, count2, 0);
  1939:   }
  1940:   private /*uint32*/ int regword (/*uint32*/ int offset1, /*uint32*/ int start1, /*uint32*/ int count1, /*uint32*/ int offset2, /*uint32*/ int start2, /*uint32*/ int count2, /*uint32*/ int extra_offset) {
  1941:     return (regbyte (offset1, start1, count1, extra_offset) << count2) | regbyte (offset2, start2, count2, extra_offset);
  1942:   }
  1943: 
  1944:   // system-wide registers
  1945:   public /*uint32*/ int test () {
  1946:     return regbyte (0x01, 0, 8);
  1947:   }
  1948:   public /*uint32*/ int lfo_reset () {
  1949:     return regbyte (0x01, 1, 1);
  1950:   }
  1951:   public /*uint32*/ int noise_frequency () {
  1952:     return regbyte (0x0f, 0, 5) ^ 0x1f;
  1953:   }
  1954:   public /*uint32*/ int noise_enable () {
  1955:     return regbyte (0x0f, 7, 1);
  1956:   }
  1957:   public /*uint32*/ int timer_a_value () {
  1958:     return regword (0x10, 0, 8, 0x11, 0, 2);
  1959:   }
  1960:   public /*uint32*/ int timer_b_value () {
  1961:     return regbyte (0x12, 0, 8);
  1962:   }
  1963:   public /*uint32*/ int csm () {
  1964:     return regbyte (0x14, 7, 1);
  1965:   }
  1966:   public /*uint32*/ int reset_timer_b () {
  1967:     return regbyte (0x14, 5, 1);
  1968:   }
  1969:   public /*uint32*/ int reset_timer_a () {
  1970:     return regbyte (0x14, 4, 1);
  1971:   }
  1972:   public /*uint32*/ int enable_timer_b () {
  1973:     return regbyte (0x14, 3, 1);
  1974:   }
  1975:   public /*uint32*/ int enable_timer_a () {
  1976:     return regbyte (0x14, 2, 1);
  1977:   }
  1978:   public /*uint32*/ int load_timer_b () {
  1979:     return regbyte (0x14, 1, 1);
  1980:   }
  1981:   public /*uint32*/ int load_timer_a () {
  1982:     return regbyte (0x14, 0, 1);
  1983:   }
  1984:   public /*uint32*/ int lfo_rate () {
  1985:     return regbyte (0x18, 0, 8);
  1986:   }
  1987:   public /*uint32*/ int lfo_am_depth () {
  1988:     return regbyte (0x19, 0, 7);
  1989:   }
  1990:   public /*uint32*/ int lfo_pm_depth () {
  1991:     return regbyte (0x1a, 0, 7);
  1992:   }
  1993:   public /*uint32*/ int output_bits () {
  1994:     return regbyte (0x1b, 6, 2);
  1995:   }
  1996:   public /*uint32*/ int lfo_waveform () {
  1997:     return regbyte (0x1b, 0, 2);
  1998:   }
  1999: 
  2000:   // per-channel registers
  2001:   public /*uint32*/ int ch_output_any (/*uint32*/ int choffs) {
  2002:     return regbyte (0x20, 6, 2, choffs);
  2003:   }
  2004:   public /*uint32*/ int ch_output_0 (/*uint32*/ int choffs) {
  2005:     return regbyte (0x20, 6, 1, choffs);
  2006:   }
  2007:   public /*uint32*/ int ch_output_1 (/*uint32*/ int choffs) {
  2008:     return regbyte (0x20, 7, 1, choffs);
  2009:   }
  2010:   public /*uint32*/ int ch_feedback (/*uint32*/ int choffs) {
  2011:     return regbyte (0x20, 3, 3, choffs);
  2012:   }
  2013:   public /*uint32*/ int ch_algorithm (/*uint32*/ int choffs) {
  2014:     return regbyte (0x20, 0, 3, choffs);
  2015:   }
  2016:   public /*uint32*/ int ch_block_freq (/*uint32*/ int choffs) {
  2017:     return regword (0x28, 0, 7, 0x30, 2, 6, choffs);
  2018:   }
  2019:   public /*uint32*/ int ch_lfo_pm_sens (/*uint32*/ int choffs) {
  2020:     return regbyte (0x38, 4, 3, choffs);
  2021:   }
  2022:   public /*uint32*/ int ch_lfo_am_sens (/*uint32*/ int choffs) {
  2023:     return regbyte (0x38, 0, 2, choffs);
  2024:   }
  2025: 
  2026:   // per-operator registers
  2027:   public /*uint32*/ int op_detune (/*uint32*/ int opoffs) {
  2028:     return regbyte (0x40, 4, 3, opoffs);
  2029:   }
  2030:   public /*uint32*/ int op_multiple (/*uint32*/ int opoffs) {
  2031:     return regbyte (0x40, 0, 4, opoffs);
  2032:   }
  2033:   public /*uint32*/ int op_total_level (/*uint32*/ int opoffs) {
  2034:     return regbyte (0x60, 0, 7, opoffs);
  2035:   }
  2036:   public /*uint32*/ int op_ksr (/*uint32*/ int opoffs) {
  2037:     return regbyte (0x80, 6, 2, opoffs);
  2038:   }
  2039:   public /*uint32*/ int op_attack_rate (/*uint32*/ int opoffs) {
  2040:     return regbyte (0x80, 0, 5, opoffs);
  2041:   }
  2042:   public /*uint32*/ int op_lfo_am_enable (/*uint32*/ int opoffs) {
  2043:     return regbyte (0xa0, 7, 1, opoffs);
  2044:   }
  2045:   public /*uint32*/ int op_decay_rate (/*uint32*/ int opoffs) {
  2046:     return regbyte (0xa0, 0, 5, opoffs);
  2047:   }
  2048:   public /*uint32*/ int op_detune2 (/*uint32*/ int opoffs) {
  2049:     return regbyte (0xc0, 6, 2, opoffs);
  2050:   }
  2051:   public /*uint32*/ int op_sustain_rate (/*uint32*/ int opoffs) {
  2052:     return regbyte (0xc0, 0, 5, opoffs);
  2053:   }
  2054:   public /*uint32*/ int op_sustain_level (/*uint32*/ int opoffs) {
  2055:     return regbyte (0xe0, 4, 4, opoffs);
  2056:   }
  2057:   public /*uint32*/ int op_release_rate (/*uint32*/ int opoffs) {
  2058:     return regbyte (0xe0, 0, 4, opoffs);
  2059:   }
  2060: 
  2061: 
  2062: 
  2063:   // this class represents the interface between the fm_engine and the outside
  2064:   // world; it provides hooks for timers, synchronization, and I/O
  2065:   //class ymfm_interface
  2066:   static interface Listener {
  2067: 
  2068:     // the following functions must be implemented by any derived classes; the
  2069:     // default implementations are sufficient for some minimal operation, but will
  2070:     // likely need to be overridden to integrate with the outside world; they are
  2071:     // all prefixed with ymfm_ to reduce the likelihood of namespace collisions
  2072: 
  2073:     //
  2074:     // timing and synchronizaton
  2075:     //
  2076: 
  2077:     // the chip implementation calls this when a write happens to the mode
  2078:     // register, which could affect timers and interrupts; our responsibility
  2079:     // is to ensure the system is up to date before calling the engine's
  2080:     // engine_mode_write() method
  2081:     //public void ymfm_sync_mode_write (/*uint8*/ int data);
  2082: 
  2083:     // the chip implementation calls this when the chip's status has changed,
  2084:     // which may affect the interrupt state; our responsibility is to ensure
  2085:     // the system is up to date before calling the engine's
  2086:     // engine_check_interrupts() method
  2087:     //public void ymfm_sync_check_interrupts ();
  2088: 
  2089:     // the chip implementation calls this when one of the two internal timers
  2090:     // has changed state; our responsibility is to arrange to call the engine's
  2091:     // engine_timer_expired() method after the provided number of clocks; if
  2092:     // duration_in_clocks is negative, we should cancel any outstanding timers
  2093:     //public void ymfm_set_timer (/*uint32*/ int tnum, int duration_in_clocks);
  2094: 
  2095:     //timerA (clocks)
  2096:     //  タイマーAが始動または停止した
  2097:     //  clocks  -1以外  始動。タイマーAがオーバーフローするまでの時間
  2098:     //          -1      停止
  2099:     public void timerA (int clocks);
  2100: 
  2101:     //timerB (clocks)
  2102:     //  タイマーBが始動または停止した
  2103:     //  clocks  -1以外  始動。タイマーBがオーバーフローするまでの時間
  2104:     //          -1      停止
  2105:     public void timerB (int clocks);
  2106: 
  2107:     // the chip implementation calls this to indicate that the chip should be
  2108:     // considered in a busy state until the given number of clocks has passed;
  2109:     // our responsibility is to compute and remember the ending time based on
  2110:     // the chip's clock for later checking
  2111:     //public void ymfm_set_busy_end (/*uint32*/ int clocks);
  2112: 
  2113:     //busy (clocks)
  2114:     //  BUSYがセットされた
  2115:     //  clocks  BUSYがクリアされるまでの時間
  2116:     public void busy (int clocks);
  2117: 
  2118:     // the chip implementation calls this to see if the chip is still currently
  2119:     // is a busy state, as specified by a previous call to ymfm_set_busy_end();
  2120:     // our responsibility is to compare the current time against the previously
  2121:     // noted busy end time and return true if we haven't yet passed it
  2122:     //public boolean ymfm_is_busy ();
  2123: 
  2124:     //busy = isBusy ()
  2125:     //  busy  true   BUSYがセットされている
  2126:     //        false  BUSYがセットされていない
  2127:     public boolean isBusy ();
  2128: 
  2129:     //
  2130:     // I/O functions
  2131:     //
  2132: 
  2133:     // the chip implementation calls this when the state of the IRQ signal has
  2134:     // changed due to a status change; our responsibility is to respond as
  2135:     // needed to the change in IRQ state, signaling any consumers
  2136:     //public void ymfm_update_irq (boolean asserted);
  2137: 
  2138:     //irq (asserted)
  2139:     //  IRQが変化した
  2140:     //  asserted  false  IRQがネゲートされた
  2141:     //            true   IRQがアサートされた
  2142:     public void irq (boolean asserted);
  2143: 
  2144:     // the chip implementation calls this whenever data is read from outside
  2145:     // of the chip; our responsibility is to provide the data requested
  2146:     //public /*uint8*/ int ymfm_external_read (/*access_class*/ int type, /*uint32*/ int address);
  2147: 
  2148:     // the chip implementation calls this whenever data is written outside
  2149:     // of the chip; our responsibility is to pass the written data on to any consumers
  2150:     //public void ymfm_external_write (/*uint32*/ int address, /*uint8*/ int data);
  2151: 
  2152:     //control (data)
  2153:     //  コントロール
  2154:     //  data  CT1<<1|CT2
  2155:     public void control (int data);
  2156: 
  2157:     //written (pointer, address, data)
  2158:     //  データレジスタへ書き込まれた
  2159:     public void written (int pointer, int address, int data);
  2160: 
  2161:   }  //interface Listener
  2162: 
  2163: 
  2164: 
  2165:   private Listener listener;  //リスナー
  2166:   private int[] buffer;  //バッファ
  2167:   private int pointer;  //バッファのポインタ
  2168:   private int channelMask;  //チャンネルマスク
  2169: 
  2170:   //init2 ()
  2171:   private void init2 () {
  2172:     listener = null;
  2173:     buffer = new int[2 * 62500 * 5];  //5s
  2174:     pointer = 0;
  2175:     channelMask = ALL_CHANNELS;
  2176:   }
  2177: 
  2178:   //setListener (listener)
  2179:   //  リスナーを設定する
  2180:   public void setListener (Listener listener) {
  2181:     this.listener = listener;
  2182:   }
  2183: 
  2184:   //allocate (size)
  2185:   //  バッファを確保する
  2186:   //  バッファはクリアされる
  2187:   //  ポインタは先頭に戻る
  2188:   public void allocate (int size) {
  2189:     buffer = new int[size];
  2190:     Arrays.fill (buffer, 0);
  2191:     pointer = 0;
  2192:   }
  2193: 
  2194:   //clear ()
  2195:   //  バッファをクリアする
  2196:   //  ポインタは先頭に戻る
  2197:   //  チップは変化しない
  2198:   public void clear () {
  2199:     Arrays.fill (buffer, 0);
  2200:     pointer = 0;
  2201:   }
  2202: 
  2203:   //buffer = getBuffer ()
  2204:   //  バッファを返す
  2205:   public int[] getBuffer () {
  2206:     return buffer;
  2207:   }
  2208: 
  2209:   //pointer = getPointer ()
  2210:   //  ポインタを返す
  2211:   public int getPointer () {
  2212:     return pointer;
  2213:   }
  2214: 
  2215:   //reset ()
  2216:   //  チップをリセットする
  2217:   //  バッファは変化しない
  2218:   //public void reset () {
  2219:   //}
  2220: 
  2221:   //generate (limit)
  2222:   //  バッファを構築する
  2223:   //public void generate (int limit) {
  2224:   //}
  2225: 
  2226:   //fill ()
  2227:   //  バッファを最後まで構築する
  2228:   public void fill () {
  2229:     generate (buffer.length);
  2230:   }
  2231: 
  2232:   //readStatus ()
  2233:   //  ステータスレジスタから読み出す
  2234:   //public int readStatus () {
  2235:   //}
  2236: 
  2237:   //writeAddress (address)
  2238:   //  アドレスレジスタへ書き込む
  2239:   //public void writeAddress (int address) {
  2240:   //}
  2241: 
  2242:   //writeData (data)
  2243:   //  データレジスタへ書き込む
  2244:   //public void writeData (int data) {
  2245:   //}
  2246: 
  2247:   //setChannelMask (mask)
  2248:   //  チャンネルマスクを設定する
  2249:   public void setChannelMask (int mask) {
  2250:     channelMask = mask;
  2251:   }
  2252: 
  2253:   //timerAExpired ()
  2254:   //  タイマーAがオーバーフローした
  2255:   public void timerAExpired () {
  2256:     engine_timer_expired (0);
  2257:   }
  2258: 
  2259:   //timerBExpired ()
  2260:   //  タイマーBがオーバーフローした
  2261:   public void timerBExpired () {
  2262:     engine_timer_expired (1);
  2263:   }
  2264: 
  2265: 
  2266: 
  2267: }  //class YM2151