Viewing File: <root>/src/emu/sound/fmopl.c

    1  /*
    2  **
    3  ** File: fmopl.c - software implementation of FM sound generator
    4  **                                            types OPL and OPL2
    5  **
    6  ** Copyright Jarek Burczynski (bujar at mame dot net)
    7  ** Copyright Tatsuyuki Satoh , MultiArcadeMachineEmulator development
    8  **
    9  ** Version 0.72
   10  **
   11  
   12  Revision History:
   13  
   14  04-08-2003 Jarek Burczynski:
   15   - removed BFRDY hack. BFRDY is busy flag, and it should be 0 only when the chip
   16     handles memory read/write or during the adpcm synthesis when the chip
   17     requests another byte of ADPCM data.
   18  
   19  24-07-2003 Jarek Burczynski:
   20   - added a small hack for Y8950 status BFRDY flag (bit 3 should be set after
   21     some (unknown) delay). Right now it's always set.
   22  
   23  14-06-2003 Jarek Burczynski:
   24   - implemented all of the status register flags in Y8950 emulation
   25   - renamed y8950_set_delta_t_memory() parameters from _rom_ to _mem_ since
   26     they can be either RAM or ROM
   27  
   28  08-10-2002 Jarek Burczynski (thanks to Dox for the YM3526 chip)
   29   - corrected ym3526_read() to always set bit 2 and bit 1
   30     to HIGH state - identical to ym3812_read (verified on real YM3526)
   31  
   32  04-28-2002 Jarek Burczynski:
   33   - binary exact Envelope Generator (verified on real YM3812);
   34     compared to YM2151: the EG clock is equal to internal_clock,
   35     rates are 2 times slower and volume resolution is one bit less
   36   - modified interface functions (they no longer return pointer -
   37     that's internal to the emulator now):
   38      - new wrapper functions for OPLCreate: ym3526_init(), ym3812_init() and y8950_init()
   39   - corrected 'off by one' error in feedback calculations (when feedback is off)
   40   - enabled waveform usage (credit goes to Vlad Romascanu and zazzal22)
   41   - speeded up noise generator calculations (Nicola Salmoria)
   42  
   43  03-24-2002 Jarek Burczynski (thanks to Dox for the YM3812 chip)
   44   Complete rewrite (all verified on real YM3812):
   45   - corrected sin_tab and tl_tab data
   46   - corrected operator output calculations
   47   - corrected waveform_select_enable register;
   48     simply: ignore all writes to waveform_select register when
   49     waveform_select_enable == 0 and do not change the waveform previously selected.
   50   - corrected KSR handling
   51   - corrected Envelope Generator: attack shape, Sustain mode and
   52     Percussive/Non-percussive modes handling
   53   - Envelope Generator rates are two times slower now
   54   - LFO amplitude (tremolo) and phase modulation (vibrato)
   55   - rhythm sounds phase generation
   56   - white noise generator (big thanks to Olivier Galibert for mentioning Berlekamp-Massey algorithm)
   57   - corrected key on/off handling (the 'key' signal is ORed from three sources: FM, rhythm and CSM)
   58   - funky details (like ignoring output of operator 1 in BD rhythm sound when connect == 1)
   59  
   60  12-28-2001 Acho A. Tang
   61   - reflected Delta-T EOS status on Y8950 status port.
   62   - fixed subscription range of attack/decay tables
   63  
   64  
   65      To do:
   66          add delay before key off in CSM mode (see CSMKeyControll)
   67          verify volume of the FM part on the Y8950
   68  */
   69  
   70  #include "emu.h"
   71  #include "ymdeltat.h"
   72  #include "fmopl.h"
   73  
   74  
   75  
   76  /* output final shift */
   77  #if (OPL_SAMPLE_BITS==16)
   78      #define FINAL_SH    (0)
   79      #define MAXOUT      (+32767)
   80      #define MINOUT      (-32768)
   81  #else
   82      #define FINAL_SH    (8)
   83      #define MAXOUT      (+127)
   84      #define MINOUT      (-128)
   85  #endif
   86  
   87  
   88  #define FREQ_SH         16  /* 16.16 fixed point (frequency calculations) */
   89  #define EG_SH           16  /* 16.16 fixed point (EG timing)              */
   90  #define LFO_SH          24  /*  8.24 fixed point (LFO calculations)       */
   91  #define TIMER_SH        16  /* 16.16 fixed point (timers calculations)    */
   92  
   93  #define FREQ_MASK       ((1<<FREQ_SH)-1)
   94  
   95  /* envelope output entries */
   96  #define ENV_BITS        10
   97  #define ENV_LEN         (1<<ENV_BITS)
   98  #define ENV_STEP        (128.0/ENV_LEN)
   99  
  100  #define MAX_ATT_INDEX   ((1<<(ENV_BITS-1))-1) /*511*/
  101  #define MIN_ATT_INDEX   (0)
  102  
  103  /* sinwave entries */
  104  #define SIN_BITS        10
  105  #define SIN_LEN         (1<<SIN_BITS)
  106  #define SIN_MASK        (SIN_LEN-1)
  107  
  108  #define TL_RES_LEN      (256)   /* 8 bits addressing (real chip) */
  109  
  110  
  111  
  112  /* register number to channel number , slot offset */
  113  #define SLOT1 0
  114  #define SLOT2 1
  115  
  116  /* Envelope Generator phases */
  117  
  118  #define EG_ATT          4
  119  #define EG_DEC          3
  120  #define EG_SUS          2
  121  #define EG_REL          1
  122  #define EG_OFF          0
  123  
  124  
  125  /* save output as raw 16-bit sample */
  126  
  127  /*#define SAVE_SAMPLE*/
  128  
  129  #ifdef SAVE_SAMPLE
  130  INLINE signed int acc_calc(signed int value)
  131  {
  132      if (value>=0)
  133      {
  134          if (value < 0x0200)
  135              return (value & ~0);
  136          if (value < 0x0400)
  137              return (value & ~1);
  138          if (value < 0x0800)
  139              return (value & ~3);
  140          if (value < 0x1000)
  141              return (value & ~7);
  142          if (value < 0x2000)
  143              return (value & ~15);
  144          if (value < 0x4000)
  145              return (value & ~31);
  146          return (value & ~63);
  147      }
  148      /*else value < 0*/
  149      if (value > -0x0200)
  150          return (~abs(value) & ~0);
  151      if (value > -0x0400)
  152          return (~abs(value) & ~1);
  153      if (value > -0x0800)
  154          return (~abs(value) & ~3);
  155      if (value > -0x1000)
  156          return (~abs(value) & ~7);
  157      if (value > -0x2000)
  158          return (~abs(value) & ~15);
  159      if (value > -0x4000)
  160          return (~abs(value) & ~31);
  161      return (~abs(value) & ~63);
  162  }
  163  
  164  
  165  static FILE *sample[1];
  166      #if 1   /*save to MONO file */
  167          #define SAVE_ALL_CHANNELS \
  168          {   signed int pom = acc_calc(lt); \
  169              fputc((unsigned short)pom&0xff,sample[0]); \
  170              fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
  171          }
  172      #else   /*save to STEREO file */
  173          #define SAVE_ALL_CHANNELS \
  174          {   signed int pom = lt; \
  175              fputc((unsigned short)pom&0xff,sample[0]); \
  176              fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
  177              pom = rt; \
  178              fputc((unsigned short)pom&0xff,sample[0]); \
  179              fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
  180          }
  181      #endif
  182  #endif
  183  
  184  #define LOG_CYM_FILE 0
  185  static FILE * cymfile = NULL;
  186  
  187  
  188  
  189  #define OPL_TYPE_WAVESEL   0x01  /* waveform select     */
  190  #define OPL_TYPE_ADPCM     0x02  /* DELTA-T ADPCM unit  */
  191  #define OPL_TYPE_KEYBOARD  0x04  /* keyboard interface  */
  192  #define OPL_TYPE_IO        0x08  /* I/O port            */
  193  
  194  /* ---------- Generic interface section ---------- */
  195  #define OPL_TYPE_YM3526 (0)
  196  #define OPL_TYPE_YM3812 (OPL_TYPE_WAVESEL)
  197  #define OPL_TYPE_Y8950  (OPL_TYPE_ADPCM|OPL_TYPE_KEYBOARD|OPL_TYPE_IO)
  198  
  199  
  200  
  201  struct OPL_SLOT
  202  {
  203      UINT32  ar;         /* attack rate: AR<<2           */
  204      UINT32  dr;         /* decay rate:  DR<<2           */
  205      UINT32  rr;         /* release rate:RR<<2           */
  206      UINT8   KSR;        /* key scale rate               */
  207      UINT8   ksl;        /* keyscale level               */
  208      UINT8   ksr;        /* key scale rate: kcode>>KSR   */
  209      UINT8   mul;        /* multiple: mul_tab[ML]        */
  210  
  211      /* Phase Generator */
  212      UINT32  Cnt;        /* frequency counter            */
  213      UINT32  Incr;       /* frequency counter step       */
  214      UINT8   FB;         /* feedback shift value         */
  215      INT32   *connect1;  /* slot1 output pointer         */
  216      INT32   op1_out[2]; /* slot1 output for feedback    */
  217      UINT8   CON;        /* connection (algorithm) type  */
  218  
  219      /* Envelope Generator */
  220      UINT8   eg_type;    /* percussive/non-percussive mode */
  221      UINT8   state;      /* phase type                   */
  222      UINT32  TL;         /* total level: TL << 2         */
  223      INT32   TLL;        /* adjusted now TL              */
  224      INT32   volume;     /* envelope counter             */
  225      UINT32  sl;         /* sustain level: sl_tab[SL]    */
  226      UINT8   eg_sh_ar;   /* (attack state)               */
  227      UINT8   eg_sel_ar;  /* (attack state)               */
  228      UINT8   eg_sh_dr;   /* (decay state)                */
  229      UINT8   eg_sel_dr;  /* (decay state)                */
  230      UINT8   eg_sh_rr;   /* (release state)              */
  231      UINT8   eg_sel_rr;  /* (release state)              */
  232      UINT32  key;        /* 0 = KEY OFF, >0 = KEY ON     */
  233  
  234      /* LFO */
  235      UINT32  AMmask;     /* LFO Amplitude Modulation enable mask */
  236      UINT8   vib;        /* LFO Phase Modulation enable flag (active high)*/
  237  
  238      /* waveform select */
  239      UINT16  wavetable;
  240  };
  241  
  242  struct OPL_CH
  243  {
  244      OPL_SLOT SLOT[2];
  245      /* phase generator state */
  246      UINT32  block_fnum; /* block+fnum                   */
  247      UINT32  fc;         /* Freq. Increment base         */
  248      UINT32  ksl_base;   /* KeyScaleLevel Base step      */
  249      UINT8   kcode;      /* key code (for key scaling)   */
  250  };
  251  
  252  /* OPL state */
  253  struct FM_OPL
  254  {
  255      /* FM channel slots */
  256      OPL_CH  P_CH[9];                /* OPL/OPL2 chips have 9 channels*/
  257  
  258      UINT32  eg_cnt;                 /* global envelope generator counter    */
  259      UINT32  eg_timer;               /* global envelope generator counter works at frequency = chipclock/72 */
  260      UINT32  eg_timer_add;           /* step of eg_timer                     */
  261      UINT32  eg_timer_overflow;      /* envelope generator timer overlfows every 1 sample (on real chip) */
  262  
  263      UINT8   rhythm;                 /* Rhythm mode                  */
  264  
  265      UINT32  fn_tab[1024];           /* fnumber->increment counter   */
  266  
  267      /* LFO */
  268      UINT32  LFO_AM;
  269      INT32   LFO_PM;
  270  
  271      UINT8   lfo_am_depth;
  272      UINT8   lfo_pm_depth_range;
  273      UINT32  lfo_am_cnt;
  274      UINT32  lfo_am_inc;
  275      UINT32  lfo_pm_cnt;
  276      UINT32  lfo_pm_inc;
  277  
  278      UINT32  noise_rng;              /* 23 bit noise shift register  */
  279      UINT32  noise_p;                /* current noise 'phase'        */
  280      UINT32  noise_f;                /* current noise period         */
  281  
  282      UINT8   wavesel;                /* waveform select enable flag  */
  283  
  284      UINT32  T[2];                   /* timer counters               */
  285      UINT8   st[2];                  /* timer enable                 */
  286  
  287  #if BUILD_Y8950
  288      /* Delta-T ADPCM unit (Y8950) */
  289  
  290      YM_DELTAT *deltat;
  291  
  292      /* Keyboard and I/O ports interface */
  293      UINT8   portDirection;
  294      UINT8   portLatch;
  295      OPL_PORTHANDLER_R porthandler_r;
  296      OPL_PORTHANDLER_W porthandler_w;
  297      void *  port_param;
  298      OPL_PORTHANDLER_R keyboardhandler_r;
  299      OPL_PORTHANDLER_W keyboardhandler_w;
  300      void *  keyboard_param;
  301  #endif
  302  
  303      /* external event callback handlers */
  304      OPL_TIMERHANDLER  timer_handler;    /* TIMER handler                */
  305      void *TimerParam;                   /* TIMER parameter              */
  306      OPL_IRQHANDLER    IRQHandler;   /* IRQ handler                  */
  307      void *IRQParam;                 /* IRQ parameter                */
  308      OPL_UPDATEHANDLER UpdateHandler;/* stream update handler        */
  309      void *UpdateParam;              /* stream update parameter      */
  310  
  311      UINT8 type;                     /* chip type                    */
  312      UINT8 address;                  /* address register             */
  313      UINT8 status;                   /* status flag                  */
  314      UINT8 statusmask;               /* status mask                  */
  315      UINT8 mode;                     /* Reg.08 : CSM,notesel,etc.    */
  316  
  317      UINT32 clock;                   /* master clock  (Hz)           */
  318      UINT32 rate;                    /* sampling rate (Hz)           */
  319      double freqbase;                /* frequency base               */
  320      attotime TimerBase;         /* Timer base time (==sampling time)*/
  321      device_t *device;
  322  
  323      signed int phase_modulation;    /* phase modulation input (SLOT 2) */
  324      signed int output[1];
  325  #if BUILD_Y8950
  326      INT32 output_deltat[4];     /* for Y8950 DELTA-T, chip is mono, that 4 here is just for safety */
  327  #endif
  328  };
  329  
  330  
  331  
  332  /* mapping of register number (offset) to slot number used by the emulator */
  333  static const int slot_array[32]=
  334  {
  335          0, 2, 4, 1, 3, 5,-1,-1,
  336          6, 8,10, 7, 9,11,-1,-1,
  337      12,14,16,13,15,17,-1,-1,
  338      -1,-1,-1,-1,-1,-1,-1,-1
  339  };
  340  
  341  /* key scale level */
  342  /* table is 3dB/octave , DV converts this into 6dB/octave */
  343  /* 0.1875 is bit 0 weight of the envelope counter (volume) expressed in the 'decibel' scale */
  344  #define DV (0.1875/2.0)
  345  static const UINT32 ksl_tab[8*16]=
  346  {
  347      /* OCT 0 */
  348          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  349          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  350          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  351          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  352      /* OCT 1 */
  353          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  354          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  355          0.000/DV, 0.750/DV, 1.125/DV, 1.500/DV,
  356          1.875/DV, 2.250/DV, 2.625/DV, 3.000/DV,
  357      /* OCT 2 */
  358          0.000/DV, 0.000/DV, 0.000/DV, 0.000/DV,
  359          0.000/DV, 1.125/DV, 1.875/DV, 2.625/DV,
  360          3.000/DV, 3.750/DV, 4.125/DV, 4.500/DV,
  361          4.875/DV, 5.250/DV, 5.625/DV, 6.000/DV,
  362      /* OCT 3 */
  363          0.000/DV, 0.000/DV, 0.000/DV, 1.875/DV,
  364          3.000/DV, 4.125/DV, 4.875/DV, 5.625/DV,
  365          6.000/DV, 6.750/DV, 7.125/DV, 7.500/DV,
  366          7.875/DV, 8.250/DV, 8.625/DV, 9.000/DV,
  367      /* OCT 4 */
  368          0.000/DV, 0.000/DV, 3.000/DV, 4.875/DV,
  369          6.000/DV, 7.125/DV, 7.875/DV, 8.625/DV,
  370          9.000/DV, 9.750/DV,10.125/DV,10.500/DV,
  371      10.875/DV,11.250/DV,11.625/DV,12.000/DV,
  372      /* OCT 5 */
  373          0.000/DV, 3.000/DV, 6.000/DV, 7.875/DV,
  374          9.000/DV,10.125/DV,10.875/DV,11.625/DV,
  375      12.000/DV,12.750/DV,13.125/DV,13.500/DV,
  376      13.875/DV,14.250/DV,14.625/DV,15.000/DV,
  377      /* OCT 6 */
  378          0.000/DV, 6.000/DV, 9.000/DV,10.875/DV,
  379      12.000/DV,13.125/DV,13.875/DV,14.625/DV,
  380      15.000/DV,15.750/DV,16.125/DV,16.500/DV,
  381      16.875/DV,17.250/DV,17.625/DV,18.000/DV,
  382      /* OCT 7 */
  383          0.000/DV, 9.000/DV,12.000/DV,13.875/DV,
  384      15.000/DV,16.125/DV,16.875/DV,17.625/DV,
  385      18.000/DV,18.750/DV,19.125/DV,19.500/DV,
  386      19.875/DV,20.250/DV,20.625/DV,21.000/DV
  387  };
  388  #undef DV
  389  
  390  /* sustain level table (3dB per step) */
  391  /* 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,93 (dB)*/
  392  #define SC(db) (UINT32) ( db * (2.0/ENV_STEP) )
  393  static const UINT32 sl_tab[16]={
  394      SC( 0),SC( 1),SC( 2),SC(3 ),SC(4 ),SC(5 ),SC(6 ),SC( 7),
  395      SC( 8),SC( 9),SC(10),SC(11),SC(12),SC(13),SC(14),SC(31)
  396  };
  397  #undef SC
  398  
  399  
  400  #define RATE_STEPS (8)
  401  static const unsigned char eg_inc[15*RATE_STEPS]={
  402  /*cycle:0 1  2 3  4 5  6 7*/
  403  
  404  /* 0 */ 0,1, 0,1, 0,1, 0,1, /* rates 00..12 0 (increment by 0 or 1) */
  405  /* 1 */ 0,1, 0,1, 1,1, 0,1, /* rates 00..12 1 */
  406  /* 2 */ 0,1, 1,1, 0,1, 1,1, /* rates 00..12 2 */
  407  /* 3 */ 0,1, 1,1, 1,1, 1,1, /* rates 00..12 3 */
  408  
  409  /* 4 */ 1,1, 1,1, 1,1, 1,1, /* rate 13 0 (increment by 1) */
  410  /* 5 */ 1,1, 1,2, 1,1, 1,2, /* rate 13 1 */
  411  /* 6 */ 1,2, 1,2, 1,2, 1,2, /* rate 13 2 */
  412  /* 7 */ 1,2, 2,2, 1,2, 2,2, /* rate 13 3 */
  413  
  414  /* 8 */ 2,2, 2,2, 2,2, 2,2, /* rate 14 0 (increment by 2) */
  415  /* 9 */ 2,2, 2,4, 2,2, 2,4, /* rate 14 1 */
  416  /*10 */ 2,4, 2,4, 2,4, 2,4, /* rate 14 2 */
  417  /*11 */ 2,4, 4,4, 2,4, 4,4, /* rate 14 3 */
  418  
  419  /*12 */ 4,4, 4,4, 4,4, 4,4, /* rates 15 0, 15 1, 15 2, 15 3 (increment by 4) */
  420  /*13 */ 8,8, 8,8, 8,8, 8,8, /* rates 15 2, 15 3 for attack */
  421  /*14 */ 0,0, 0,0, 0,0, 0,0, /* infinity rates for attack and decay(s) */
  422  };
  423  
  424  
  425  #define O(a) (a*RATE_STEPS)
  426  
  427  /*note that there is no O(13) in this table - it's directly in the code */
  428  static const unsigned char eg_rate_select[16+64+16]={   /* Envelope Generator rates (16 + 64 rates + 16 RKS) */
  429  /* 16 infinite time rates */
  430  O(14),O(14),O(14),O(14),O(14),O(14),O(14),O(14),
  431  O(14),O(14),O(14),O(14),O(14),O(14),O(14),O(14),
  432  
  433  /* rates 00-12 */
  434  O( 0),O( 1),O( 2),O( 3),
  435  O( 0),O( 1),O( 2),O( 3),
  436  O( 0),O( 1),O( 2),O( 3),
  437  O( 0),O( 1),O( 2),O( 3),
  438  O( 0),O( 1),O( 2),O( 3),
  439  O( 0),O( 1),O( 2),O( 3),
  440  O( 0),O( 1),O( 2),O( 3),
  441  O( 0),O( 1),O( 2),O( 3),
  442  O( 0),O( 1),O( 2),O( 3),
  443  O( 0),O( 1),O( 2),O( 3),
  444  O( 0),O( 1),O( 2),O( 3),
  445  O( 0),O( 1),O( 2),O( 3),
  446  O( 0),O( 1),O( 2),O( 3),
  447  
  448  /* rate 13 */
  449  O( 4),O( 5),O( 6),O( 7),
  450  
  451  /* rate 14 */
  452  O( 8),O( 9),O(10),O(11),
  453  
  454  /* rate 15 */
  455  O(12),O(12),O(12),O(12),
  456  
  457  /* 16 dummy rates (same as 15 3) */
  458  O(12),O(12),O(12),O(12),O(12),O(12),O(12),O(12),
  459  O(12),O(12),O(12),O(12),O(12),O(12),O(12),O(12),
  460  
  461  };
  462  #undef O
  463  
  464  /*rate  0,    1,    2,    3,   4,   5,   6,  7,  8,  9,  10, 11, 12, 13, 14, 15 */
  465  /*shift 12,   11,   10,   9,   8,   7,   6,  5,  4,  3,  2,  1,  0,  0,  0,  0  */
  466  /*mask  4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7,  3,  1,  0,  0,  0,  0  */
  467  
  468  #define O(a) (a*1)
  469  static const unsigned char eg_rate_shift[16+64+16]={    /* Envelope Generator counter shifts (16 + 64 rates + 16 RKS) */
  470  /* 16 infinite time rates */
  471  O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
  472  O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
  473  
  474  /* rates 00-12 */
  475  O(12),O(12),O(12),O(12),
  476  O(11),O(11),O(11),O(11),
  477  O(10),O(10),O(10),O(10),
  478  O( 9),O( 9),O( 9),O( 9),
  479  O( 8),O( 8),O( 8),O( 8),
  480  O( 7),O( 7),O( 7),O( 7),
  481  O( 6),O( 6),O( 6),O( 6),
  482  O( 5),O( 5),O( 5),O( 5),
  483  O( 4),O( 4),O( 4),O( 4),
  484  O( 3),O( 3),O( 3),O( 3),
  485  O( 2),O( 2),O( 2),O( 2),
  486  O( 1),O( 1),O( 1),O( 1),
  487  O( 0),O( 0),O( 0),O( 0),
  488  
  489  /* rate 13 */
  490  O( 0),O( 0),O( 0),O( 0),
  491  
  492  /* rate 14 */
  493  O( 0),O( 0),O( 0),O( 0),
  494  
  495  /* rate 15 */
  496  O( 0),O( 0),O( 0),O( 0),
  497  
  498  /* 16 dummy rates (same as 15 3) */
  499  O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
  500  O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
  501  
  502  };
  503  #undef O
  504  
  505  
  506  /* multiple table */
  507  #define ML 2
  508  static const UINT8 mul_tab[16]= {
  509  /* 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,10,12,12,15,15 */
  510      0.50*ML, 1.00*ML, 2.00*ML, 3.00*ML, 4.00*ML, 5.00*ML, 6.00*ML, 7.00*ML,
  511      8.00*ML, 9.00*ML,10.00*ML,10.00*ML,12.00*ML,12.00*ML,15.00*ML,15.00*ML
  512  };
  513  #undef ML
  514  
  515  /*  TL_TAB_LEN is calculated as:
  516  *   12 - sinus amplitude bits     (Y axis)
  517  *   2  - sinus sign bit           (Y axis)
  518  *   TL_RES_LEN - sinus resolution (X axis)
  519  */
  520  #define TL_TAB_LEN (12*2*TL_RES_LEN)
  521  static signed int tl_tab[TL_TAB_LEN];
  522  
  523  #define ENV_QUIET       (TL_TAB_LEN>>4)
  524  
  525  /* sin waveform table in 'decibel' scale */
  526  /* four waveforms on OPL2 type chips */
  527  static unsigned int sin_tab[SIN_LEN * 4];
  528  
  529  
  530  /* LFO Amplitude Modulation table (verified on real YM3812)
  531     27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples
  532  
  533     Length: 210 elements.
  534  
  535      Each of the elements has to be repeated
  536      exactly 64 times (on 64 consecutive samples).
  537      The whole table takes: 64 * 210 = 13440 samples.
  538  
  539      When AM = 1 data is used directly
  540      When AM = 0 data is divided by 4 before being used (losing precision is important)
  541  */
  542  
  543  #define LFO_AM_TAB_ELEMENTS 210
  544  
  545  static const UINT8 lfo_am_table[LFO_AM_TAB_ELEMENTS] = {
  546  0,0,0,0,0,0,0,
  547  1,1,1,1,
  548  2,2,2,2,
  549  3,3,3,3,
  550  4,4,4,4,
  551  5,5,5,5,
  552  6,6,6,6,
  553  7,7,7,7,
  554  8,8,8,8,
  555  9,9,9,9,
  556  10,10,10,10,
  557  11,11,11,11,
  558  12,12,12,12,
  559  13,13,13,13,
  560  14,14,14,14,
  561  15,15,15,15,
  562  16,16,16,16,
  563  17,17,17,17,
  564  18,18,18,18,
  565  19,19,19,19,
  566  20,20,20,20,
  567  21,21,21,21,
  568  22,22,22,22,
  569  23,23,23,23,
  570  24,24,24,24,
  571  25,25,25,25,
  572  26,26,26,
  573  25,25,25,25,
  574  24,24,24,24,
  575  23,23,23,23,
  576  22,22,22,22,
  577  21,21,21,21,
  578  20,20,20,20,
  579  19,19,19,19,
  580  18,18,18,18,
  581  17,17,17,17,
  582  16,16,16,16,
  583  15,15,15,15,
  584  14,14,14,14,
  585  13,13,13,13,
  586  12,12,12,12,
  587  11,11,11,11,
  588  10,10,10,10,
  589  9,9,9,9,
  590  8,8,8,8,
  591  7,7,7,7,
  592  6,6,6,6,
  593  5,5,5,5,
  594  4,4,4,4,
  595  3,3,3,3,
  596  2,2,2,2,
  597  1,1,1,1
  598  };
  599  
  600  /* LFO Phase Modulation table (verified on real YM3812) */
  601  static const INT8 lfo_pm_table[8*8*2] = {
  602  /* FNUM2/FNUM = 00 0xxxxxxx (0x0000) */
  603  0, 0, 0, 0, 0, 0, 0, 0, /*LFO PM depth = 0*/
  604  0, 0, 0, 0, 0, 0, 0, 0, /*LFO PM depth = 1*/
  605  
  606  /* FNUM2/FNUM = 00 1xxxxxxx (0x0080) */
  607  0, 0, 0, 0, 0, 0, 0, 0, /*LFO PM depth = 0*/
  608  1, 0, 0, 0,-1, 0, 0, 0, /*LFO PM depth = 1*/
  609  
  610  /* FNUM2/FNUM = 01 0xxxxxxx (0x0100) */
  611  1, 0, 0, 0,-1, 0, 0, 0, /*LFO PM depth = 0*/
  612  2, 1, 0,-1,-2,-1, 0, 1, /*LFO PM depth = 1*/
  613  
  614  /* FNUM2/FNUM = 01 1xxxxxxx (0x0180) */
  615  1, 0, 0, 0,-1, 0, 0, 0, /*LFO PM depth = 0*/
  616  3, 1, 0,-1,-3,-1, 0, 1, /*LFO PM depth = 1*/
  617  
  618  /* FNUM2/FNUM = 10 0xxxxxxx (0x0200) */
  619  2, 1, 0,-1,-2,-1, 0, 1, /*LFO PM depth = 0*/
  620  4, 2, 0,-2,-4,-2, 0, 2, /*LFO PM depth = 1*/
  621  
  622  /* FNUM2/FNUM = 10 1xxxxxxx (0x0280) */
  623  2, 1, 0,-1,-2,-1, 0, 1, /*LFO PM depth = 0*/
  624  5, 2, 0,-2,-5,-2, 0, 2, /*LFO PM depth = 1*/
  625  
  626  /* FNUM2/FNUM = 11 0xxxxxxx (0x0300) */
  627  3, 1, 0,-1,-3,-1, 0, 1, /*LFO PM depth = 0*/
  628  6, 3, 0,-3,-6,-3, 0, 3, /*LFO PM depth = 1*/
  629  
  630  /* FNUM2/FNUM = 11 1xxxxxxx (0x0380) */
  631  3, 1, 0,-1,-3,-1, 0, 1, /*LFO PM depth = 0*/
  632  7, 3, 0,-3,-7,-3, 0, 3  /*LFO PM depth = 1*/
  633  };
  634  
  635  
  636  /* lock level of common table */
  637  static int num_lock = 0;
  638  
  639  
  640  #define SLOT7_1 (&OPL->P_CH[7].SLOT[SLOT1])
  641  #define SLOT7_2 (&OPL->P_CH[7].SLOT[SLOT2])
  642  #define SLOT8_1 (&OPL->P_CH[8].SLOT[SLOT1])
  643  #define SLOT8_2 (&OPL->P_CH[8].SLOT[SLOT2])
  644  
  645  
  646  
  647  
  648  INLINE int limit( int val, int max, int min ) {
  649      if ( val > max )
  650          val = max;
  651      else if ( val < min )
  652          val = min;
  653  
  654      return val;
  655  }
  656  
  657  
  658  /* status set and IRQ handling */
  659  INLINE void OPL_STATUS_SET(FM_OPL *OPL,int flag)
  660  {
  661      /* set status flag */
  662      OPL->status |= flag;
  663      if(!(OPL->status & 0x80))
  664      {
  665          if(OPL->status & OPL->statusmask)
  666          {   /* IRQ on */
  667              OPL->status |= 0x80;
  668              /* callback user interrupt handler (IRQ is OFF to ON) */
  669              if(OPL->IRQHandler) (OPL->IRQHandler)(OPL->IRQParam,1);
  670          }
  671      }
  672  }
  673  
  674  /* status reset and IRQ handling */
  675  INLINE void OPL_STATUS_RESET(FM_OPL *OPL,int flag)
  676  {
  677      /* reset status flag */
  678      OPL->status &=~flag;
  679      if((OPL->status & 0x80))
  680      {
  681          if (!(OPL->status & OPL->statusmask) )
  682          {
  683              OPL->status &= 0x7f;
  684              /* callback user interrupt handler (IRQ is ON to OFF) */
  685              if(OPL->IRQHandler) (OPL->IRQHandler)(OPL->IRQParam,0);
  686          }
  687      }
  688  }
  689  
  690  /* IRQ mask set */
  691  INLINE void OPL_STATUSMASK_SET(FM_OPL *OPL,int flag)
  692  {
  693      OPL->statusmask = flag;
  694      /* IRQ handling check */
  695      OPL_STATUS_SET(OPL,0);
  696      OPL_STATUS_RESET(OPL,0);
  697  }
  698  
  699  
  700  /* advance LFO to next sample */
  701  INLINE void advance_lfo(FM_OPL *OPL)
  702  {
  703      UINT8 tmp;
  704  
  705      /* LFO */
  706      OPL->lfo_am_cnt += OPL->lfo_am_inc;
  707      if (OPL->lfo_am_cnt >= ((UINT32)LFO_AM_TAB_ELEMENTS<<LFO_SH) )  /* lfo_am_table is 210 elements long */
  708          OPL->lfo_am_cnt -= ((UINT32)LFO_AM_TAB_ELEMENTS<<LFO_SH);
  709  
  710      tmp = lfo_am_table[ OPL->lfo_am_cnt >> LFO_SH ];
  711  
  712      if (OPL->lfo_am_depth)
  713          OPL->LFO_AM = tmp;
  714      else
  715          OPL->LFO_AM = tmp>>2;
  716  
  717      OPL->lfo_pm_cnt += OPL->lfo_pm_inc;
  718      OPL->LFO_PM = ((OPL->lfo_pm_cnt>>LFO_SH) & 7) | OPL->lfo_pm_depth_range;
  719  }
  720  
  721  /* advance to next sample */
  722  INLINE void advance(FM_OPL *OPL)
  723  {
  724      OPL_CH *CH;
  725      OPL_SLOT *op;
  726      int i;
  727  
  728      OPL->eg_timer += OPL->eg_timer_add;
  729  
  730      while (OPL->eg_timer >= OPL->eg_timer_overflow)
  731      {
  732          OPL->eg_timer -= OPL->eg_timer_overflow;
  733  
  734          OPL->eg_cnt++;
  735  
  736          for (i=0; i<9*2; i++)
  737          {
  738              CH  = &OPL->P_CH[i/2];
  739              op  = &CH->SLOT[i&1];
  740  
  741              /* Envelope Generator */
  742              switch(op->state)
  743              {
  744              case EG_ATT:        /* attack phase */
  745                  if ( !(OPL->eg_cnt & ((1<<op->eg_sh_ar)-1) ) )
  746                  {
  747                      op->volume += (~op->volume *
  748                                                  (eg_inc[op->eg_sel_ar + ((OPL->eg_cnt>>op->eg_sh_ar)&7)])
  749                                                  ) >>3;
  750  
  751                      if (op->volume <= MIN_ATT_INDEX)
  752                      {
  753                          op->volume = MIN_ATT_INDEX;
  754                          op->state = EG_DEC;
  755                      }
  756  
  757                  }
  758              break;
  759  
  760              case EG_DEC:    /* decay phase */
  761                  if ( !(OPL->eg_cnt & ((1<<op->eg_sh_dr)-1) ) )
  762                  {
  763                      op->volume += eg_inc[op->eg_sel_dr + ((OPL->eg_cnt>>op->eg_sh_dr)&7)];
  764  
  765                      if ( op->volume >= op->sl )
  766                          op->state = EG_SUS;
  767  
  768                  }
  769              break;
  770  
  771              case EG_SUS:    /* sustain phase */
  772  
  773                  /* this is important behaviour:
  774                  one can change percusive/non-percussive modes on the fly and
  775                  the chip will remain in sustain phase - verified on real YM3812 */
  776  
  777                  if(op->eg_type)     /* non-percussive mode */
  778                  {
  779                                      /* do nothing */
  780                  }
  781                  else                /* percussive mode */
  782                  {
  783                      /* during sustain phase chip adds Release Rate (in percussive mode) */
  784                      if ( !(OPL->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
  785                      {
  786                          op->volume += eg_inc[op->eg_sel_rr + ((OPL->eg_cnt>>op->eg_sh_rr)&7)];
  787  
  788                          if ( op->volume >= MAX_ATT_INDEX )
  789                              op->volume = MAX_ATT_INDEX;
  790                      }
  791                      /* else do nothing in sustain phase */
  792                  }
  793              break;
  794  
  795              case EG_REL:    /* release phase */
  796                  if ( !(OPL->eg_cnt & ((1<<op->eg_sh_rr)-1) ) )
  797                  {
  798                      op->volume += eg_inc[op->eg_sel_rr + ((OPL->eg_cnt>>op->eg_sh_rr)&7)];
  799  
  800                      if ( op->volume >= MAX_ATT_INDEX )
  801                      {
  802                          op->volume = MAX_ATT_INDEX;
  803                          op->state = EG_OFF;
  804                      }
  805  
  806                  }
  807              break;
  808  
  809              default:
  810              break;
  811              }
  812          }
  813      }
  814  
  815      for (i=0; i<9*2; i++)
  816      {
  817          CH  = &OPL->P_CH[i/2];
  818          op  = &CH->SLOT[i&1];
  819  
  820          /* Phase Generator */
  821          if(op->vib)
  822          {
  823              UINT8 block;
  824              unsigned int block_fnum = CH->block_fnum;
  825  
  826              unsigned int fnum_lfo   = (block_fnum&0x0380) >> 7;
  827  
  828              signed int lfo_fn_table_index_offset = lfo_pm_table[OPL->LFO_PM + 16*fnum_lfo ];
  829  
  830              if (lfo_fn_table_index_offset)  /* LFO phase modulation active */
  831              {
  832                  block_fnum += lfo_fn_table_index_offset;
  833                  block = (block_fnum&0x1c00) >> 10;
  834                  op->Cnt += (OPL->fn_tab[block_fnum&0x03ff] >> (7-block)) * op->mul;
  835              }
  836              else    /* LFO phase modulation  = zero */
  837              {
  838                  op->Cnt += op->Incr;
  839              }
  840          }
  841          else    /* LFO phase modulation disabled for this operator */
  842          {
  843              op->Cnt += op->Incr;
  844          }
  845      }
  846  
  847      /*  The Noise Generator of the YM3812 is 23-bit shift register.
  848      *   Period is equal to 2^23-2 samples.
  849      *   Register works at sampling frequency of the chip, so output
  850      *   can change on every sample.
  851      *
  852      *   Output of the register and input to the bit 22 is:
  853      *   bit0 XOR bit14 XOR bit15 XOR bit22
  854      *
  855      *   Simply use bit 22 as the noise output.
  856      */
  857  
  858      OPL->noise_p += OPL->noise_f;
  859      i = OPL->noise_p >> FREQ_SH;        /* number of events (shifts of the shift register) */
  860      OPL->noise_p &= FREQ_MASK;
  861      while (i)
  862      {
  863          /*
  864          UINT32 j;
  865          j = ( (OPL->noise_rng) ^ (OPL->noise_rng>>14) ^ (OPL->noise_rng>>15) ^ (OPL->noise_rng>>22) ) & 1;
  866          OPL->noise_rng = (j<<22) | (OPL->noise_rng>>1);
  867          */
  868  
  869          /*
  870              Instead of doing all the logic operations above, we
  871              use a trick here (and use bit 0 as the noise output).
  872              The difference is only that the noise bit changes one
  873              step ahead. This doesn't matter since we don't know
  874              what is real state of the noise_rng after the reset.
  875          */
  876  
  877          if (OPL->noise_rng & 1) OPL->noise_rng ^= 0x800302;
  878          OPL->noise_rng >>= 1;
  879  
  880          i--;
  881      }
  882  }
  883  
  884  
  885  INLINE signed int op_calc(UINT32 phase, unsigned int env, signed int pm, unsigned int wave_tab)
  886  {
  887      UINT32 p;
  888  
  889      p = (env<<4) + sin_tab[wave_tab + ((((signed int)((phase & ~FREQ_MASK) + (pm<<16))) >> FREQ_SH ) & SIN_MASK) ];
  890  
  891      if (p >= TL_TAB_LEN)
  892          return 0;
  893      return tl_tab[p];
  894  }
  895  
  896  INLINE signed int op_calc1(UINT32 phase, unsigned int env, signed int pm, unsigned int wave_tab)
  897  {
  898      UINT32 p;
  899  
  900      p = (env<<4) + sin_tab[wave_tab + ((((signed int)((phase & ~FREQ_MASK) + pm      )) >> FREQ_SH ) & SIN_MASK) ];
  901  
  902      if (p >= TL_TAB_LEN)
  903          return 0;
  904      return tl_tab[p];
  905  }
  906  
  907  
  908  #define volume_calc(OP) ((OP)->TLL + ((UINT32)(OP)->volume) + (OPL->LFO_AM & (OP)->AMmask))
  909  
  910  /* calculate output */
  911  INLINE void OPL_CALC_CH( FM_OPL *OPL, OPL_CH *CH )
  912  {
  913      OPL_SLOT *SLOT;
  914      unsigned int env;
  915      signed int out;
  916  
  917      OPL->phase_modulation = 0;
  918  
  919      /* SLOT 1 */
  920      SLOT = &CH->SLOT[SLOT1];
  921      env  = volume_calc(SLOT);
  922      out  = SLOT->op1_out[0] + SLOT->op1_out[1];
  923      SLOT->op1_out[0] = SLOT->op1_out[1];
  924      *SLOT->connect1 += SLOT->op1_out[0];
  925      SLOT->op1_out[1] = 0;
  926      if( env < ENV_QUIET )
  927      {
  928          if (!SLOT->FB)
  929              out = 0;
  930          SLOT->op1_out[1] = op_calc1(SLOT->Cnt, env, (out<<SLOT->FB), SLOT->wavetable );
  931      }
  932  
  933      /* SLOT 2 */
  934      SLOT++;
  935      env = volume_calc(SLOT);
  936      if( env < ENV_QUIET )
  937          OPL->output[0] += op_calc(SLOT->Cnt, env, OPL->phase_modulation, SLOT->wavetable);
  938  }
  939  
  940  /*
  941      operators used in the rhythm sounds generation process:
  942  
  943      Envelope Generator:
  944  
  945  channel  operator  register number   Bass  High  Snare Tom  Top
  946  / slot   number    TL ARDR SLRR Wave Drum  Hat   Drum  Tom  Cymbal
  947   6 / 0   12        50  70   90   f0  +
  948   6 / 1   15        53  73   93   f3  +
  949   7 / 0   13        51  71   91   f1        +
  950   7 / 1   16        54  74   94   f4              +
  951   8 / 0   14        52  72   92   f2                    +
  952   8 / 1   17        55  75   95   f5                          +
  953  
  954      Phase Generator:
  955  
  956  channel  operator  register number   Bass  High  Snare Tom  Top
  957  / slot   number    MULTIPLE          Drum  Hat   Drum  Tom  Cymbal
  958   6 / 0   12        30                +
  959   6 / 1   15        33                +
  960   7 / 0   13        31                      +     +           +
  961   7 / 1   16        34                -----  n o t  u s e d -----
  962   8 / 0   14        32                                  +
  963   8 / 1   17        35                      +                 +
  964  
  965  channel  operator  register number   Bass  High  Snare Tom  Top
  966  number   number    BLK/FNUM2 FNUM    Drum  Hat   Drum  Tom  Cymbal
  967     6     12,15     B6        A6      +
  968  
  969     7     13,16     B7        A7            +     +           +
  970  
  971     8     14,17     B8        A8            +           +     +
  972  
  973  */
  974  
  975  /* calculate rhythm */
  976  
  977  INLINE void OPL_CALC_RH( FM_OPL *OPL, OPL_CH *CH, unsigned int noise )
  978  {
  979      OPL_SLOT *SLOT;
  980      signed int out;
  981      unsigned int env;
  982  
  983  
  984      /* Bass Drum (verified on real YM3812):
  985        - depends on the channel 6 'connect' register:
  986            when connect = 0 it works the same as in normal (non-rhythm) mode (op1->op2->out)
  987            when connect = 1 _only_ operator 2 is present on output (op2->out), operator 1 is ignored
  988        - output sample always is multiplied by 2
  989      */
  990  
  991      OPL->phase_modulation = 0;
  992      /* SLOT 1 */
  993      SLOT = &CH[6].SLOT[SLOT1];
  994      env = volume_calc(SLOT);
  995  
  996      out = SLOT->op1_out[0] + SLOT->op1_out[1];
  997      SLOT->op1_out[0] = SLOT->op1_out[1];
  998  
  999      if (!SLOT->CON)
 1000          OPL->phase_modulation = SLOT->op1_out[0];
 1001      /* else ignore output of operator 1 */
 1002  
 1003      SLOT->op1_out[1] = 0;
 1004      if( env < ENV_QUIET )
 1005      {
 1006          if (!SLOT->FB)
 1007              out = 0;
 1008          SLOT->op1_out[1] = op_calc1(SLOT->Cnt, env, (out<<SLOT->FB), SLOT->wavetable );
 1009      }
 1010  
 1011      /* SLOT 2 */
 1012      SLOT++;
 1013      env = volume_calc(SLOT);
 1014      if( env < ENV_QUIET )
 1015          OPL->output[0] += op_calc(SLOT->Cnt, env, OPL->phase_modulation, SLOT->wavetable) * 2;
 1016  
 1017  
 1018      /* Phase generation is based on: */
 1019      /* HH  (13) channel 7->slot 1 combined with channel 8->slot 2 (same combination as TOP CYMBAL but different output phases) */
 1020      /* SD  (16) channel 7->slot 1 */
 1021      /* TOM (14) channel 8->slot 1 */
 1022      /* TOP (17) channel 7->slot 1 combined with channel 8->slot 2 (same combination as HIGH HAT but different output phases) */
 1023  
 1024      /* Envelope generation based on: */
 1025      /* HH  channel 7->slot1 */
 1026      /* SD  channel 7->slot2 */
 1027      /* TOM channel 8->slot1 */
 1028      /* TOP channel 8->slot2 */
 1029  
 1030  
 1031      /* The following formulas can be well optimized.
 1032         I leave them in direct form for now (in case I've missed something).
 1033      */
 1034  
 1035      /* High Hat (verified on real YM3812) */
 1036      env = volume_calc(SLOT7_1);
 1037      if( env < ENV_QUIET )
 1038      {
 1039          /* high hat phase generation:
 1040              phase = d0 or 234 (based on frequency only)
 1041              phase = 34 or 2d0 (based on noise)
 1042          */
 1043  
 1044          /* base frequency derived from operator 1 in channel 7 */
 1045          unsigned char bit7 = ((SLOT7_1->Cnt>>FREQ_SH)>>7)&1;
 1046          unsigned char bit3 = ((SLOT7_1->Cnt>>FREQ_SH)>>3)&1;
 1047          unsigned char bit2 = ((SLOT7_1->Cnt>>FREQ_SH)>>2)&1;
 1048  
 1049          unsigned char res1 = (bit2 ^ bit7) | bit3;
 1050  
 1051          /* when res1 = 0 phase = 0x000 | 0xd0; */
 1052          /* when res1 = 1 phase = 0x200 | (0xd0>>2); */
 1053          UINT32 phase = res1 ? (0x200|(0xd0>>2)) : 0xd0;
 1054  
 1055          /* enable gate based on frequency of operator 2 in channel 8 */
 1056          unsigned char bit5e= ((SLOT8_2->Cnt>>FREQ_SH)>>5)&1;
 1057          unsigned char bit3e= ((SLOT8_2->Cnt>>FREQ_SH)>>3)&1;
 1058  
 1059          unsigned char res2 = (bit3e ^ bit5e);
 1060  
 1061          /* when res2 = 0 pass the phase from calculation above (res1); */
 1062          /* when res2 = 1 phase = 0x200 | (0xd0>>2); */
 1063          if (res2)
 1064              phase = (0x200|(0xd0>>2));
 1065  
 1066  
 1067          /* when phase & 0x200 is set and noise=1 then phase = 0x200|0xd0 */
 1068          /* when phase & 0x200 is set and noise=0 then phase = 0x200|(0xd0>>2), ie no change */
 1069          if (phase&0x200)
 1070          {
 1071              if (noise)
 1072                  phase = 0x200|0xd0;
 1073          }
 1074          else
 1075          /* when phase & 0x200 is clear and noise=1 then phase = 0xd0>>2 */
 1076          /* when phase & 0x200 is clear and noise=0 then phase = 0xd0, ie no change */
 1077          {
 1078              if (noise)
 1079                  phase = 0xd0>>2;
 1080          }
 1081  
 1082          OPL->output[0] += op_calc(phase<<FREQ_SH, env, 0, SLOT7_1->wavetable) * 2;
 1083      }
 1084  
 1085      /* Snare Drum (verified on real YM3812) */
 1086      env = volume_calc(SLOT7_2);
 1087      if( env < ENV_QUIET )
 1088      {
 1089          /* base frequency derived from operator 1 in channel 7 */
 1090          unsigned char bit8 = ((SLOT7_1->Cnt>>FREQ_SH)>>8)&1;
 1091  
 1092          /* when bit8 = 0 phase = 0x100; */
 1093          /* when bit8 = 1 phase = 0x200; */
 1094          UINT32 phase = bit8 ? 0x200 : 0x100;
 1095  
 1096          /* Noise bit XOR'es phase by 0x100 */
 1097          /* when noisebit = 0 pass the phase from calculation above */
 1098          /* when noisebit = 1 phase ^= 0x100; */
 1099          /* in other words: phase ^= (noisebit<<8); */
 1100          if (noise)
 1101              phase ^= 0x100;
 1102  
 1103          OPL->output[0] += op_calc(phase<<FREQ_SH, env, 0, SLOT7_2->wavetable) * 2;
 1104      }
 1105  
 1106      /* Tom Tom (verified on real YM3812) */
 1107      env = volume_calc(SLOT8_1);
 1108      if( env < ENV_QUIET )
 1109          OPL->output[0] += op_calc(SLOT8_1->Cnt, env, 0, SLOT8_1->wavetable) * 2;
 1110  
 1111      /* Top Cymbal (verified on real YM3812) */
 1112      env = volume_calc(SLOT8_2);
 1113      if( env < ENV_QUIET )
 1114      {
 1115          /* base frequency derived from operator 1 in channel 7 */
 1116          unsigned char bit7 = ((SLOT7_1->Cnt>>FREQ_SH)>>7)&1;
 1117          unsigned char bit3 = ((SLOT7_1->Cnt>>FREQ_SH)>>3)&1;
 1118          unsigned char bit2 = ((SLOT7_1->Cnt>>FREQ_SH)>>2)&1;
 1119  
 1120          unsigned char res1 = (bit2 ^ bit7) | bit3;
 1121  
 1122          /* when res1 = 0 phase = 0x000 | 0x100; */
 1123          /* when res1 = 1 phase = 0x200 | 0x100; */
 1124          UINT32 phase = res1 ? 0x300 : 0x100;
 1125  
 1126          /* enable gate based on frequency of operator 2 in channel 8 */
 1127          unsigned char bit5e= ((SLOT8_2->Cnt>>FREQ_SH)>>5)&1;
 1128          unsigned char bit3e= ((SLOT8_2->Cnt>>FREQ_SH)>>3)&1;
 1129  
 1130          unsigned char res2 = (bit3e ^ bit5e);
 1131          /* when res2 = 0 pass the phase from calculation above (res1); */
 1132          /* when res2 = 1 phase = 0x200 | 0x100; */
 1133          if (res2)
 1134              phase = 0x300;
 1135  
 1136          OPL->output[0] += op_calc(phase<<FREQ_SH, env, 0, SLOT8_2->wavetable) * 2;
 1137      }
 1138  }
 1139  
 1140  
 1141  /* generic table initialize */
 1142  static int init_tables(void)
 1143  {
 1144      signed int i,x;
 1145      signed int n;
 1146      double o,m;
 1147  
 1148  
 1149      for (x=0; x<TL_RES_LEN; x++)
 1150      {
 1151          m = (1<<16) / pow(2, (x+1) * (ENV_STEP/4.0) / 8.0);
 1152          m = floor(m);
 1153  
 1154          /* we never reach (1<<16) here due to the (x+1) */
 1155          /* result fits within 16 bits at maximum */
 1156  
 1157          n = (int)m;     /* 16 bits here */
 1158          n >>= 4;        /* 12 bits here */
 1159          if (n&1)        /* round to nearest */
 1160              n = (n>>1)+1;
 1161          else
 1162              n = n>>1;
 1163                          /* 11 bits here (rounded) */
 1164          n <<= 1;        /* 12 bits here (as in real chip) */
 1165          tl_tab[ x*2 + 0 ] = n;
 1166          tl_tab[ x*2 + 1 ] = -tl_tab[ x*2 + 0 ];
 1167  
 1168          for (i=1; i<12; i++)
 1169          {
 1170              tl_tab[ x*2+0 + i*2*TL_RES_LEN ] =  tl_tab[ x*2+0 ]>>i;
 1171              tl_tab[ x*2+1 + i*2*TL_RES_LEN ] = -tl_tab[ x*2+0 + i*2*TL_RES_LEN ];
 1172          }
 1173      #if 0
 1174              logerror("tl %04i", x*2);
 1175              for (i=0; i<12; i++)
 1176                  logerror(", [%02i] %5i", i*2, tl_tab[ x*2 /*+1*/ + i*2*TL_RES_LEN ] );
 1177              logerror("\n");
 1178      #endif
 1179      }
 1180      /*logerror("FMOPL.C: TL_TAB_LEN = %i elements (%i bytes)\n",TL_TAB_LEN, (int)sizeof(tl_tab));*/
 1181  
 1182  
 1183      for (i=0; i<SIN_LEN; i++)
 1184      {
 1185          /* non-standard sinus */
 1186          m = sin( ((i*2)+1) * M_PI / SIN_LEN ); /* checked against the real chip */
 1187  
 1188          /* we never reach zero here due to ((i*2)+1) */
 1189  
 1190          if (m>0.0)
 1191              o = 8*log(1.0/m)/log(2.0);  /* convert to 'decibels' */
 1192          else
 1193              o = 8*log(-1.0/m)/log(2.0); /* convert to 'decibels' */
 1194  
 1195          o = o / (ENV_STEP/4);
 1196  
 1197          n = (int)(2.0*o);
 1198          if (n&1)                        /* round to nearest */
 1199              n = (n>>1)+1;
 1200          else
 1201              n = n>>1;
 1202  
 1203          sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
 1204  
 1205          /*logerror("FMOPL.C: sin [%4i (hex=%03x)]= %4i (tl_tab value=%5i)\n", i, i, sin_tab[i], tl_tab[sin_tab[i]] );*/
 1206      }
 1207  
 1208      for (i=0; i<SIN_LEN; i++)
 1209      {
 1210          /* waveform 1:  __      __     */
 1211          /*             /  \____/  \____*/
 1212          /* output only first half of the sinus waveform (positive one) */
 1213  
 1214          if (i & (1<<(SIN_BITS-1)) )
 1215              sin_tab[1*SIN_LEN+i] = TL_TAB_LEN;
 1216          else
 1217              sin_tab[1*SIN_LEN+i] = sin_tab[i];
 1218  
 1219          /* waveform 2:  __  __  __  __ */
 1220          /*             /  \/  \/  \/  \*/
 1221          /* abs(sin) */
 1222  
 1223          sin_tab[2*SIN_LEN+i] = sin_tab[i & (SIN_MASK>>1) ];
 1224  
 1225          /* waveform 3:  _   _   _   _  */
 1226          /*             / |_/ |_/ |_/ |_*/
 1227          /* abs(output only first quarter of the sinus waveform) */
 1228  
 1229          if (i & (1<<(SIN_BITS-2)) )
 1230              sin_tab[3*SIN_LEN+i] = TL_TAB_LEN;
 1231          else
 1232              sin_tab[3*SIN_LEN+i] = sin_tab[i & (SIN_MASK>>2)];
 1233  
 1234          /*logerror("FMOPL.C: sin1[%4i]= %4i (tl_tab value=%5i)\n", i, sin_tab[1*SIN_LEN+i], tl_tab[sin_tab[1*SIN_LEN+i]] );
 1235          logerror("FMOPL.C: sin2[%4i]= %4i (tl_tab value=%5i)\n", i, sin_tab[2*SIN_LEN+i], tl_tab[sin_tab[2*SIN_LEN+i]] );
 1236          logerror("FMOPL.C: sin3[%4i]= %4i (tl_tab value=%5i)\n", i, sin_tab[3*SIN_LEN+i], tl_tab[sin_tab[3*SIN_LEN+i]] );*/
 1237      }
 1238      /*logerror("FMOPL.C: ENV_QUIET= %08x (dec*8=%i)\n", ENV_QUIET, ENV_QUIET*8 );*/
 1239  
 1240  
 1241  #ifdef SAVE_SAMPLE
 1242      sample[0]=fopen("sampsum.pcm","wb");
 1243  #endif
 1244  
 1245      return 1;
 1246  }
 1247  
 1248  static void OPLCloseTable( void )
 1249  {
 1250  #ifdef SAVE_SAMPLE
 1251      fclose(sample[0]);
 1252  #endif
 1253  }
 1254  
 1255  
 1256  
 1257  static void OPL_initalize(FM_OPL *OPL)
 1258  {
 1259      int i;
 1260  
 1261      /* frequency base */
 1262      OPL->freqbase  = (OPL->rate) ? ((double)OPL->clock / 72.0) / OPL->rate  : 0;
 1263  #if 0
 1264      OPL->rate = (double)OPL->clock / 72.0;
 1265      OPL->freqbase  = 1.0;
 1266  #endif
 1267  
 1268      /*logerror("freqbase=%f\n", OPL->freqbase);*/
 1269  
 1270      /* Timer base time */
 1271      OPL->TimerBase = attotime::from_hz(OPL->clock) * 72;
 1272  
 1273      /* make fnumber -> increment counter table */
 1274      for( i=0 ; i < 1024 ; i++ )
 1275      {
 1276          /* opn phase increment counter = 20bit */
 1277          OPL->fn_tab[i] = (UINT32)( (double)i * 64 * OPL->freqbase * (1<<(FREQ_SH-10)) ); /* -10 because chip works with 10.10 fixed point, while we use 16.16 */
 1278  #if 0
 1279          logerror("FMOPL.C: fn_tab[%4i] = %08x (dec=%8i)\n",
 1280                      i, OPL->fn_tab[i]>>6, OPL->fn_tab[i]>>6 );
 1281  #endif
 1282      }
 1283  
 1284  #if 0
 1285      for( i=0 ; i < 16 ; i++ )
 1286      {
 1287          logerror("FMOPL.C: sl_tab[%i] = %08x\n",
 1288              i, sl_tab[i] );
 1289      }
 1290      for( i=0 ; i < 8 ; i++ )
 1291      {
 1292          int j;
 1293          logerror("FMOPL.C: ksl_tab[oct=%2i] =",i);
 1294          for (j=0; j<16; j++)
 1295          {
 1296              logerror("%08x ", ksl_tab[i*16+j] );
 1297          }
 1298          logerror("\n");
 1299      }
 1300  #endif
 1301  
 1302  
 1303      /* Amplitude modulation: 27 output levels (triangle waveform); 1 level takes one of: 192, 256 or 448 samples */
 1304      /* One entry from LFO_AM_TABLE lasts for 64 samples */
 1305      OPL->lfo_am_inc = (1.0 / 64.0 ) * (1<<LFO_SH) * OPL->freqbase;
 1306  
 1307      /* Vibrato: 8 output levels (triangle waveform); 1 level takes 1024 samples */
 1308      OPL->lfo_pm_inc = (1.0 / 1024.0) * (1<<LFO_SH) * OPL->freqbase;
 1309  
 1310      /*logerror ("OPL->lfo_am_inc = %8x ; OPL->lfo_pm_inc = %8x\n", OPL->lfo_am_inc, OPL->lfo_pm_inc);*/
 1311  
 1312      /* Noise generator: a step takes 1 sample */
 1313      OPL->noise_f = (1.0 / 1.0) * (1<<FREQ_SH) * OPL->freqbase;
 1314  
 1315      OPL->eg_timer_add  = (1<<EG_SH)  * OPL->freqbase;
 1316      OPL->eg_timer_overflow = ( 1 ) * (1<<EG_SH);
 1317      /*logerror("OPLinit eg_timer_add=%8x eg_timer_overflow=%8x\n", OPL->eg_timer_add, OPL->eg_timer_overflow);*/
 1318  
 1319  }
 1320  
 1321  INLINE void FM_KEYON(OPL_SLOT *SLOT, UINT32 key_set)
 1322  {
 1323      if( !SLOT->key )
 1324      {
 1325          /* restart Phase Generator */
 1326          SLOT->Cnt = 0;
 1327          /* phase -> Attack */
 1328          SLOT->state = EG_ATT;
 1329      }
 1330      SLOT->key |= key_set;
 1331  }
 1332  
 1333  INLINE void FM_KEYOFF(OPL_SLOT *SLOT, UINT32 key_clr)
 1334  {
 1335      if( SLOT->key )
 1336      {
 1337          SLOT->key &= key_clr;
 1338  
 1339          if( !SLOT->key )
 1340          {
 1341              /* phase -> Release */
 1342              if (SLOT->state>EG_REL)
 1343                  SLOT->state = EG_REL;
 1344          }
 1345      }
 1346  }
 1347  
 1348  /* update phase increment counter of operator (also update the EG rates if necessary) */
 1349  INLINE void CALC_FCSLOT(OPL_CH *CH,OPL_SLOT *SLOT)
 1350  {
 1351      int ksr;
 1352  
 1353      /* (frequency) phase increment counter */
 1354      SLOT->Incr = CH->fc * SLOT->mul;
 1355      ksr = CH->kcode >> SLOT->KSR;
 1356  
 1357      if( SLOT->ksr != ksr )
 1358      {
 1359          SLOT->ksr = ksr;
 1360  
 1361          /* calculate envelope generator rates */
 1362          if ((SLOT->ar + SLOT->ksr) < 16+62)
 1363          {
 1364              SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
 1365              SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
 1366          }
 1367          else
 1368          {
 1369              SLOT->eg_sh_ar  = 0;
 1370              SLOT->eg_sel_ar = 13*RATE_STEPS;
 1371          }
 1372          SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
 1373          SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
 1374          SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
 1375          SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
 1376      }
 1377  }
 1378  
 1379  /* set multi,am,vib,EG-TYP,KSR,mul */
 1380  INLINE void set_mul(FM_OPL *OPL,int slot,int v)
 1381  {
 1382      OPL_CH   *CH   = &OPL->P_CH[slot/2];
 1383      OPL_SLOT *SLOT = &CH->SLOT[slot&1];
 1384  
 1385      SLOT->mul     = mul_tab[v&0x0f];
 1386      SLOT->KSR     = (v&0x10) ? 0 : 2;
 1387      SLOT->eg_type = (v&0x20);
 1388      SLOT->vib     = (v&0x40);
 1389      SLOT->AMmask  = (v&0x80) ? ~0 : 0;
 1390      CALC_FCSLOT(CH,SLOT);
 1391  }
 1392  
 1393  /* set ksl & tl */
 1394  INLINE void set_ksl_tl(FM_OPL *OPL,int slot,int v)
 1395  {
 1396      OPL_CH   *CH   = &OPL->P_CH[slot/2];
 1397      OPL_SLOT *SLOT = &CH->SLOT[slot&1];
 1398      int ksl = v>>6; /* 0 / 1.5 / 3.0 / 6.0 dB/OCT */
 1399  
 1400      SLOT->ksl = ksl ? 3-ksl : 31;
 1401      SLOT->TL  = (v&0x3f)<<(ENV_BITS-1-7); /* 7 bits TL (bit 6 = always 0) */
 1402  
 1403      SLOT->TLL = SLOT->TL + (CH->ksl_base>>SLOT->ksl);
 1404  }
 1405  
 1406  /* set attack rate & decay rate  */
 1407  INLINE void set_ar_dr(FM_OPL *OPL,int slot,int v)
 1408  {
 1409      OPL_CH   *CH   = &OPL->P_CH[slot/2];
 1410      OPL_SLOT *SLOT = &CH->SLOT[slot&1];
 1411  
 1412      SLOT->ar = (v>>4)  ? 16 + ((v>>4)  <<2) : 0;
 1413  
 1414      if ((SLOT->ar + SLOT->ksr) < 16+62)
 1415      {
 1416          SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
 1417          SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
 1418      }
 1419      else
 1420      {
 1421          SLOT->eg_sh_ar  = 0;
 1422          SLOT->eg_sel_ar = 13*RATE_STEPS;
 1423      }
 1424  
 1425      SLOT->dr    = (v&0x0f)? 16 + ((v&0x0f)<<2) : 0;
 1426      SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
 1427      SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
 1428  }
 1429  
 1430  /* set sustain level & release rate */
 1431  INLINE void set_sl_rr(FM_OPL *OPL,int slot,int v)
 1432  {
 1433      OPL_CH   *CH   = &OPL->P_CH[slot/2];
 1434      OPL_SLOT *SLOT = &CH->SLOT[slot&1];
 1435  
 1436      SLOT->sl  = sl_tab[ v>>4 ];
 1437  
 1438      SLOT->rr  = (v&0x0f)? 16 + ((v&0x0f)<<2) : 0;
 1439      SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
 1440      SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
 1441  }
 1442  
 1443  
 1444  /* write a value v to register r on OPL chip */
 1445  static void OPLWriteReg(FM_OPL *OPL, int r, int v)
 1446  {
 1447      OPL_CH *CH;
 1448      int slot;
 1449      int block_fnum;
 1450  
 1451  
 1452      /* adjust bus to 8 bits */
 1453      r &= 0xff;
 1454      v &= 0xff;
 1455  
 1456      if (LOG_CYM_FILE && (cymfile) && (r!=0) )
 1457      {
 1458          fputc( (unsigned char)r, cymfile );
 1459          fputc( (unsigned char)v, cymfile );
 1460      }
 1461  
 1462  
 1463      switch(r&0xe0)
 1464      {
 1465      case 0x00:  /* 00-1f:control */
 1466          switch(r&0x1f)
 1467          {
 1468          case 0x01:  /* waveform select enable */
 1469              if(OPL->type&OPL_TYPE_WAVESEL)
 1470              {
 1471                  OPL->wavesel = v&0x20;
 1472                  /* do not change the waveform previously selected */
 1473              }
 1474              break;
 1475          case 0x02:  /* Timer 1 */
 1476              OPL->T[0] = (256-v)*4;
 1477              break;
 1478          case 0x03:  /* Timer 2 */
 1479              OPL->T[1] = (256-v)*16;
 1480              break;
 1481          case 0x04:  /* IRQ clear / mask and Timer enable */
 1482              if(v&0x80)
 1483              {   /* IRQ flag clear */
 1484                  OPL_STATUS_RESET(OPL,0x7f-0x08); /* don't reset BFRDY flag or we will have to call deltat module to set the flag */
 1485              }
 1486              else
 1487              {   /* set IRQ mask ,timer enable*/
 1488                  UINT8 st1 = v&1;
 1489                  UINT8 st2 = (v>>1)&1;
 1490  
 1491                  /* IRQRST,T1MSK,t2MSK,EOSMSK,BRMSK,x,ST2,ST1 */
 1492                  OPL_STATUS_RESET(OPL, v & (0x78-0x08) );
 1493                  OPL_STATUSMASK_SET(OPL, (~v) & 0x78 );
 1494  
 1495                  /* timer 2 */
 1496                  if(OPL->st[1] != st2)
 1497                  {
 1498                      attotime period = st2 ? (OPL->TimerBase * OPL->T[1]) : attotime::zero;
 1499                      OPL->st[1] = st2;
 1500                      if (OPL->timer_handler) (OPL->timer_handler)(OPL->TimerParam,1,period);
 1501                  }
 1502                  /* timer 1 */
 1503                  if(OPL->st[0] != st1)
 1504                  {
 1505                      attotime period = st1 ? (OPL->TimerBase * OPL->T[0]) : attotime::zero;
 1506                      OPL->st[0] = st1;
 1507                      if (OPL->timer_handler) (OPL->timer_handler)(OPL->TimerParam,0,period);
 1508                  }
 1509              }
 1510              break;
 1511  #if BUILD_Y8950
 1512          case 0x06:      /* Key Board OUT */
 1513              if(OPL->type&OPL_TYPE_KEYBOARD)
 1514              {
 1515                  if(OPL->keyboardhandler_w)
 1516                      OPL->keyboardhandler_w(OPL->keyboard_param,v);
 1517                  else
 1518                      logerror("Y8950: write unmapped KEYBOARD port\n");
 1519              }
 1520              break;
 1521          case 0x07:  /* DELTA-T control 1 : START,REC,MEMDATA,REPT,SPOFF,x,x,RST */
 1522              if(OPL->type&OPL_TYPE_ADPCM)
 1523                  YM_DELTAT_ADPCM_Write(OPL->deltat,r-0x07,v);
 1524              break;
 1525  #endif
 1526          case 0x08:  /* MODE,DELTA-T control 2 : CSM,NOTESEL,x,x,smpl,da/ad,64k,rom */
 1527              OPL->mode = v;
 1528  #if BUILD_Y8950
 1529              if(OPL->type&OPL_TYPE_ADPCM)
 1530                  YM_DELTAT_ADPCM_Write(OPL->deltat,r-0x07,v&0x0f); /* mask 4 LSBs in register 08 for DELTA-T unit */
 1531  #endif
 1532              break;
 1533  
 1534  #if BUILD_Y8950
 1535          case 0x09:      /* START ADD */
 1536          case 0x0a:
 1537          case 0x0b:      /* STOP ADD  */
 1538          case 0x0c:
 1539          case 0x0d:      /* PRESCALE   */
 1540          case 0x0e:
 1541          case 0x0f:      /* ADPCM data write */
 1542          case 0x10:      /* DELTA-N    */
 1543          case 0x11:      /* DELTA-N    */
 1544          case 0x12:      /* ADPCM volume */
 1545              if(OPL->type&OPL_TYPE_ADPCM)
 1546                  YM_DELTAT_ADPCM_Write(OPL->deltat,r-0x07,v);
 1547              break;
 1548  
 1549          case 0x15:      /* DAC data high 8 bits (F7,F6...F2) */
 1550          case 0x16:      /* DAC data low 2 bits (F1, F0 in bits 7,6) */
 1551          case 0x17:      /* DAC data shift (S2,S1,S0 in bits 2,1,0) */
 1552              logerror("FMOPL.C: DAC data register written, but not implemented reg=%02x val=%02x\n",r,v);
 1553              break;
 1554  
 1555          case 0x18:      /* I/O CTRL (Direction) */
 1556              if(OPL->type&OPL_TYPE_IO)
 1557                  OPL->portDirection = v&0x0f;
 1558              break;
 1559          case 0x19:      /* I/O DATA */
 1560              if(OPL->type&OPL_TYPE_IO)
 1561              {
 1562                  OPL->portLatch = v;
 1563                  if(OPL->porthandler_w)
 1564                      OPL->porthandler_w(OPL->port_param,v&OPL->portDirection);
 1565              }
 1566              break;
 1567  #endif
 1568          default:
 1569              logerror("FMOPL.C: write to unknown register: %02x\n",r);
 1570              break;
 1571          }
 1572          break;
 1573      case 0x20:  /* am ON, vib ON, ksr, eg_type, mul */
 1574          slot = slot_array[r&0x1f];
 1575          if(slot < 0) return;
 1576          set_mul(OPL,slot,v);
 1577          break;
 1578      case 0x40:
 1579          slot = slot_array[r&0x1f];
 1580          if(slot < 0) return;
 1581          set_ksl_tl(OPL,slot,v);
 1582          break;
 1583      case 0x60:
 1584          slot = slot_array[r&0x1f];
 1585          if(slot < 0) return;
 1586          set_ar_dr(OPL,slot,v);
 1587          break;
 1588      case 0x80:
 1589          slot = slot_array[r&0x1f];
 1590          if(slot < 0) return;
 1591          set_sl_rr(OPL,slot,v);
 1592          break;
 1593      case 0xa0:
 1594          if (r == 0xbd)          /* am depth, vibrato depth, r,bd,sd,tom,tc,hh */
 1595          {
 1596              OPL->lfo_am_depth = v & 0x80;
 1597              OPL->lfo_pm_depth_range = (v&0x40) ? 8 : 0;
 1598  
 1599              OPL->rhythm  = v&0x3f;
 1600  
 1601              if(OPL->rhythm&0x20)
 1602              {
 1603                  /* BD key on/off */
 1604                  if(v&0x10)
 1605                  {
 1606                      FM_KEYON (&OPL->P_CH[6].SLOT[SLOT1], 2);
 1607                      FM_KEYON (&OPL->P_CH[6].SLOT[SLOT2], 2);
 1608                  }
 1609                  else
 1610                  {
 1611                      FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT1],~2);
 1612                      FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT2],~2);
 1613                  }
 1614                  /* HH key on/off */
 1615                  if(v&0x01) FM_KEYON (&OPL->P_CH[7].SLOT[SLOT1], 2);
 1616                  else       FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT1],~2);
 1617                  /* SD key on/off */
 1618                  if(v&0x08) FM_KEYON (&OPL->P_CH[7].SLOT[SLOT2], 2);
 1619                  else       FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT2],~2);
 1620                  /* TOM key on/off */
 1621                  if(v&0x04) FM_KEYON (&OPL->P_CH[8].SLOT[SLOT1], 2);
 1622                  else       FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT1],~2);
 1623                  /* TOP-CY key on/off */
 1624                  if(v&0x02) FM_KEYON (&OPL->P_CH[8].SLOT[SLOT2], 2);
 1625                  else       FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT2],~2);
 1626              }
 1627              else
 1628              {
 1629                  /* BD key off */
 1630                  FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT1],~2);
 1631                  FM_KEYOFF(&OPL->P_CH[6].SLOT[SLOT2],~2);
 1632                  /* HH key off */
 1633                  FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT1],~2);
 1634                  /* SD key off */
 1635                  FM_KEYOFF(&OPL->P_CH[7].SLOT[SLOT2],~2);
 1636                  /* TOM key off */
 1637                  FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT1],~2);
 1638                  /* TOP-CY off */
 1639                  FM_KEYOFF(&OPL->P_CH[8].SLOT[SLOT2],~2);
 1640              }
 1641              return;
 1642          }
 1643          /* keyon,block,fnum */
 1644          if( (r&0x0f) > 8) return;
 1645          CH = &OPL->P_CH[r&0x0f];
 1646          if(!(r&0x10))
 1647          {   /* a0-a8 */
 1648              block_fnum  = (CH->block_fnum&0x1f00) | v;
 1649          }
 1650          else
 1651          {   /* b0-b8 */
 1652              block_fnum = ((v&0x1f)<<8) | (CH->block_fnum&0xff);
 1653  
 1654              if(v&0x20)
 1655              {
 1656                  FM_KEYON (&CH->SLOT[SLOT1], 1);
 1657                  FM_KEYON (&CH->SLOT[SLOT2], 1);
 1658              }
 1659              else
 1660              {
 1661                  FM_KEYOFF(&CH->SLOT[SLOT1],~1);
 1662                  FM_KEYOFF(&CH->SLOT[SLOT2],~1);
 1663              }
 1664          }
 1665          /* update */
 1666          if(CH->block_fnum != block_fnum)
 1667          {
 1668              UINT8 block  = block_fnum >> 10;
 1669  
 1670              CH->block_fnum = block_fnum;
 1671  
 1672              CH->ksl_base = ksl_tab[block_fnum>>6];
 1673              CH->fc       = OPL->fn_tab[block_fnum&0x03ff] >> (7-block);
 1674  
 1675              /* BLK 2,1,0 bits -> bits 3,2,1 of kcode */
 1676              CH->kcode    = (CH->block_fnum&0x1c00)>>9;
 1677  
 1678                  /* the info below is actually opposite to what is stated in the Manuals (verifed on real YM3812) */
 1679              /* if notesel == 0 -> lsb of kcode is bit 10 (MSB) of fnum  */
 1680              /* if notesel == 1 -> lsb of kcode is bit 9 (MSB-1) of fnum */
 1681              if (OPL->mode&0x40)
 1682                  CH->kcode |= (CH->block_fnum&0x100)>>8; /* notesel == 1 */
 1683              else
 1684                  CH->kcode |= (CH->block_fnum&0x200)>>9; /* notesel == 0 */
 1685  
 1686              /* refresh Total Level in both SLOTs of this channel */
 1687              CH->SLOT[SLOT1].TLL = CH->SLOT[SLOT1].TL + (CH->ksl_base>>CH->SLOT[SLOT1].ksl);
 1688              CH->SLOT[SLOT2].TLL = CH->SLOT[SLOT2].TL + (CH->ksl_base>>CH->SLOT[SLOT2].ksl);
 1689  
 1690              /* refresh frequency counter in both SLOTs of this channel */
 1691              CALC_FCSLOT(CH,&CH->SLOT[SLOT1]);
 1692              CALC_FCSLOT(CH,&CH->SLOT[SLOT2]);
 1693          }
 1694          break;
 1695      case 0xc0:
 1696          /* FB,C */
 1697          if( (r&0x0f) > 8) return;
 1698          CH = &OPL->P_CH[r&0x0f];
 1699          CH->SLOT[SLOT1].FB  = (v>>1)&7 ? ((v>>1)&7) + 7 : 0;
 1700          CH->SLOT[SLOT1].CON = v&1;
 1701          CH->SLOT[SLOT1].connect1 = CH->SLOT[SLOT1].CON ? &OPL->output[0] : &OPL->phase_modulation;
 1702          break;
 1703      case 0xe0: /* waveform select */
 1704          /* simply ignore write to the waveform select register if selecting not enabled in test register */
 1705          if(OPL->wavesel)
 1706          {
 1707              slot = slot_array[r&0x1f];
 1708              if(slot < 0) return;
 1709              CH = &OPL->P_CH[slot/2];
 1710  
 1711              CH->SLOT[slot&1].wavetable = (v&0x03)*SIN_LEN;
 1712          }
 1713          break;
 1714      }
 1715  }
 1716  
 1717  static TIMER_CALLBACK( cymfile_callback )
 1718  {
 1719      if (cymfile)
 1720      {
 1721          fputc( (unsigned char)0, cymfile );
 1722      }
 1723  }
 1724  
 1725  /* lock/unlock for common table */
 1726  static int OPL_LockTable(device_t *device)
 1727  {
 1728      num_lock++;
 1729      if(num_lock>1) return 0;
 1730  
 1731      /* first time */
 1732  
 1733      /* allocate total level table (128kb space) */
 1734      if( !init_tables() )
 1735      {
 1736          num_lock--;
 1737          return -1;
 1738      }
 1739  
 1740      if (LOG_CYM_FILE)
 1741      {
 1742          cymfile = fopen("3812_.cym","wb");
 1743          if (cymfile)
 1744              device->machine().scheduler().timer_pulse ( attotime::from_hz(110), FUNC(cymfile_callback)); /*110 Hz pulse timer*/
 1745          else
 1746              logerror("Could not create file 3812_.cym\n");
 1747      }
 1748  
 1749      return 0;
 1750  }
 1751  
 1752  static void OPL_UnLockTable(void)
 1753  {
 1754      if(num_lock) num_lock--;
 1755      if(num_lock) return;
 1756  
 1757      /* last time */
 1758  
 1759      OPLCloseTable();
 1760  
 1761      if (cymfile)
 1762          fclose (cymfile);
 1763      cymfile = NULL;
 1764  }
 1765  
 1766  static void OPLResetChip(FM_OPL *OPL)
 1767  {
 1768      int c,s;
 1769      int i;
 1770  
 1771      OPL->eg_timer = 0;
 1772      OPL->eg_cnt   = 0;
 1773  
 1774      OPL->noise_rng = 1; /* noise shift register */
 1775      OPL->mode   = 0;    /* normal mode */
 1776      OPL_STATUS_RESET(OPL,0x7f);
 1777  
 1778      /* reset with register write */
 1779      OPLWriteReg(OPL,0x01,0); /* wavesel disable */
 1780      OPLWriteReg(OPL,0x02,0); /* Timer1 */
 1781      OPLWriteReg(OPL,0x03,0); /* Timer2 */
 1782      OPLWriteReg(OPL,0x04,0); /* IRQ mask clear */
 1783      for(i = 0xff ; i >= 0x20 ; i-- ) OPLWriteReg(OPL,i,0);
 1784  
 1785      /* reset operator parameters */
 1786      for( c = 0 ; c < 9 ; c++ )
 1787      {
 1788          OPL_CH *CH = &OPL->P_CH[c];
 1789          for(s = 0 ; s < 2 ; s++ )
 1790          {
 1791              /* wave table */
 1792              CH->SLOT[s].wavetable = 0;
 1793              CH->SLOT[s].state     = EG_OFF;
 1794              CH->SLOT[s].volume    = MAX_ATT_INDEX;
 1795          }
 1796      }
 1797  #if BUILD_Y8950
 1798      if(OPL->type&OPL_TYPE_ADPCM)
 1799      {
 1800          YM_DELTAT *DELTAT = OPL->deltat;
 1801  
 1802          DELTAT->freqbase = OPL->freqbase;
 1803          DELTAT->output_pointer = &OPL->output_deltat[0];
 1804          DELTAT->portshift = 5;
 1805          DELTAT->output_range = 1<<23;
 1806          YM_DELTAT_ADPCM_Reset(DELTAT,0,YM_DELTAT_EMULATION_MODE_NORMAL);
 1807      }
 1808  #endif
 1809  }
 1810  
 1811  
 1812  static void OPL_postload(FM_OPL *OPL)
 1813  {
 1814      int slot, ch;
 1815  
 1816      for( ch=0 ; ch < 9 ; ch++ )
 1817      {
 1818          OPL_CH *CH = &OPL->P_CH[ch];
 1819  
 1820          /* Look up key scale level */
 1821          UINT32 block_fnum = CH->block_fnum;
 1822          CH->ksl_base = ksl_tab[block_fnum >> 6];
 1823          CH->fc       = OPL->fn_tab[block_fnum & 0x03ff] >> (7 - (block_fnum >> 10));
 1824  
 1825          for( slot=0 ; slot < 2 ; slot++ )
 1826          {
 1827              OPL_SLOT *SLOT = &CH->SLOT[slot];
 1828  
 1829              /* Calculate key scale rate */
 1830              SLOT->ksr = CH->kcode >> SLOT->KSR;
 1831  
 1832              /* Calculate attack, decay and release rates */
 1833              if ((SLOT->ar + SLOT->ksr) < 16+62)
 1834              {
 1835                  SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar + SLOT->ksr ];
 1836                  SLOT->eg_sel_ar = eg_rate_select[SLOT->ar + SLOT->ksr ];
 1837              }
 1838              else
 1839              {
 1840                  SLOT->eg_sh_ar  = 0;
 1841                  SLOT->eg_sel_ar = 13*RATE_STEPS;
 1842              }
 1843              SLOT->eg_sh_dr  = eg_rate_shift [SLOT->dr + SLOT->ksr ];
 1844              SLOT->eg_sel_dr = eg_rate_select[SLOT->dr + SLOT->ksr ];
 1845              SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr + SLOT->ksr ];
 1846              SLOT->eg_sel_rr = eg_rate_select[SLOT->rr + SLOT->ksr ];
 1847  
 1848              /* Calculate phase increment */
 1849              SLOT->Incr = CH->fc * SLOT->mul;
 1850  
 1851              /* Total level */
 1852              SLOT->TLL = SLOT->TL + (CH->ksl_base >> SLOT->ksl);
 1853  
 1854              /* Connect output */
 1855              SLOT->connect1 = SLOT->CON ? &OPL->output[0] : &OPL->phase_modulation;
 1856          }
 1857      }
 1858  #if BUILD_Y8950
 1859      if ( (OPL->type & OPL_TYPE_ADPCM) && (OPL->deltat) )
 1860      {
 1861          // We really should call the postlod function for the YM_DELTAT, but it's hard without registers
 1862          // (see the way the YM2610 does it)
 1863          //YM_DELTAT_postload(OPL->deltat, REGS);
 1864      }
 1865  #endif
 1866  }
 1867  
 1868  
 1869  static void OPLsave_state_channel(device_t *device, OPL_CH *CH)
 1870  {
 1871      int slot, ch;
 1872  
 1873      for( ch=0 ; ch < 9 ; ch++, CH++ )
 1874      {
 1875          /* channel */
 1876          device->save_item(NAME(CH->block_fnum), ch);
 1877          device->save_item(NAME(CH->kcode), ch);
 1878          /* slots */
 1879          for( slot=0 ; slot < 2 ; slot++ )
 1880          {
 1881              OPL_SLOT *SLOT = &CH->SLOT[slot];
 1882  
 1883              device->save_item(NAME(SLOT->ar), ch * 2 + slot);
 1884              device->save_item(NAME(SLOT->dr), ch * 2 + slot);
 1885              device->save_item(NAME(SLOT->rr), ch * 2 + slot);
 1886              device->save_item(NAME(SLOT->KSR), ch * 2 + slot);
 1887              device->save_item(NAME(SLOT->ksl), ch * 2 + slot);
 1888              device->save_item(NAME(SLOT->mul), ch * 2 + slot);
 1889  
 1890              device->save_item(NAME(SLOT->Cnt), ch * 2 + slot);
 1891              device->save_item(NAME(SLOT->FB), ch * 2 + slot);
 1892              device->save_item(NAME(SLOT->op1_out), ch * 2 + slot);
 1893              device->save_item(NAME(SLOT->CON), ch * 2 + slot);
 1894  
 1895              device->save_item(NAME(SLOT->eg_type), ch * 2 + slot);
 1896              device->save_item(NAME(SLOT->state), ch * 2 + slot);
 1897              device->save_item(NAME(SLOT->TL), ch * 2 + slot);
 1898              device->save_item(NAME(SLOT->volume), ch * 2 + slot);
 1899              device->save_item(NAME(SLOT->sl), ch * 2 + slot);
 1900              device->save_item(NAME(SLOT->key), ch * 2 + slot);
 1901  
 1902              device->save_item(NAME(SLOT->AMmask), ch * 2 + slot);
 1903              device->save_item(NAME(SLOT->vib), ch * 2 + slot);
 1904  
 1905              device->save_item(NAME(SLOT->wavetable), ch * 2 + slot);
 1906          }
 1907      }
 1908  }
 1909  
 1910  
 1911  /* Register savestate for a virtual YM3812/YM3526Y8950 */
 1912  
 1913  static void OPL_save_state(FM_OPL *OPL, device_t *device)
 1914  {
 1915      OPLsave_state_channel(device, OPL->P_CH);
 1916  
 1917      device->save_item(NAME(OPL->eg_cnt));
 1918      device->save_item(NAME(OPL->eg_timer));
 1919  
 1920      device->save_item(NAME(OPL->rhythm));
 1921  
 1922      device->save_item(NAME(OPL->lfo_am_depth));
 1923      device->save_item(NAME(OPL->lfo_pm_depth_range));
 1924      device->save_item(NAME(OPL->lfo_am_cnt));
 1925      device->save_item(NAME(OPL->lfo_pm_cnt));
 1926  
 1927      device->save_item(NAME(OPL->noise_rng));
 1928      device->save_item(NAME(OPL->noise_p));
 1929  
 1930      if( OPL->type & OPL_TYPE_WAVESEL )
 1931      {
 1932          device->save_item(NAME(OPL->wavesel));
 1933      }
 1934  
 1935      device->save_item(NAME(OPL->T));
 1936      device->save_item(NAME(OPL->st));
 1937  
 1938  #if BUILD_Y8950
 1939      if ( (OPL->type & OPL_TYPE_ADPCM) && (OPL->deltat) )
 1940      {
 1941          YM_DELTAT_savestate(device, OPL->deltat);
 1942      }
 1943  
 1944      if ( OPL->type & OPL_TYPE_IO )
 1945      {
 1946          device->save_item(NAME(OPL->portDirection));
 1947          device->save_item(NAME(OPL->portLatch));
 1948      }
 1949  #endif
 1950  
 1951      device->save_item(NAME(OPL->address));
 1952      device->save_item(NAME(OPL->status));
 1953      device->save_item(NAME(OPL->statusmask));
 1954      device->save_item(NAME(OPL->mode));
 1955  
 1956      device->machine().save().register_postload(save_prepost_delegate(FUNC(OPL_postload), OPL));
 1957  }
 1958  
 1959  
 1960  /* Create one of virtual YM3812/YM3526/Y8950 */
 1961  /* 'clock' is chip clock in Hz  */
 1962  /* 'rate'  is sampling rate  */
 1963  static FM_OPL *OPLCreate(device_t *device, UINT32 clock, UINT32 rate, int type)
 1964  {
 1965      char *ptr;
 1966      FM_OPL *OPL;
 1967      int state_size;
 1968  
 1969      if (OPL_LockTable(device) == -1) return NULL;
 1970  
 1971      /* calculate OPL state size */
 1972      state_size  = sizeof(FM_OPL);
 1973  
 1974  #if BUILD_Y8950
 1975      if (type&OPL_TYPE_ADPCM) state_size+= sizeof(YM_DELTAT);
 1976  #endif
 1977  
 1978      /* allocate memory block */
 1979      ptr = (char *)auto_alloc_array_clear(device->machine(), UINT8, state_size);
 1980  
 1981      OPL  = (FM_OPL *)ptr;
 1982  
 1983      ptr += sizeof(FM_OPL);
 1984  
 1985  #if BUILD_Y8950
 1986      if (type&OPL_TYPE_ADPCM)
 1987      {
 1988          OPL->deltat = (YM_DELTAT *)ptr;
 1989      }
 1990      ptr += sizeof(YM_DELTAT);
 1991  #endif
 1992  
 1993      OPL->device = device;
 1994      OPL->type  = type;
 1995      OPL->clock = clock;
 1996      OPL->rate  = rate;
 1997  
 1998      /* init global tables */
 1999      OPL_initalize(OPL);
 2000  
 2001      return OPL;
 2002  }
 2003  
 2004  /* Destroy one of virtual YM3812 */
 2005  static void OPLDestroy(FM_OPL *OPL)
 2006  {
 2007      OPL_UnLockTable();
 2008      auto_free(OPL->device->machine(), OPL);
 2009  }
 2010  
 2011  /* Optional handlers */
 2012  
 2013  static void OPLSetTimerHandler(FM_OPL *OPL,OPL_TIMERHANDLER timer_handler,void *param)
 2014  {
 2015      OPL->timer_handler   = timer_handler;
 2016      OPL->TimerParam = param;
 2017  }
 2018  static void OPLSetIRQHandler(FM_OPL *OPL,OPL_IRQHANDLER IRQHandler,void *param)
 2019  {
 2020      OPL->IRQHandler     = IRQHandler;
 2021      OPL->IRQParam = param;
 2022  }
 2023  static void OPLSetUpdateHandler(FM_OPL *OPL,OPL_UPDATEHANDLER UpdateHandler,void *param)
 2024  {
 2025      OPL->UpdateHandler = UpdateHandler;
 2026      OPL->UpdateParam = param;
 2027  }
 2028  
 2029  static int OPLWrite(FM_OPL *OPL,int a,int v)
 2030  {
 2031      if( !(a&1) )
 2032      {   /* address port */
 2033          OPL->address = v & 0xff;
 2034      }
 2035      else
 2036      {   /* data port */
 2037          if(OPL->UpdateHandler) OPL->UpdateHandler(OPL->UpdateParam,0);
 2038          OPLWriteReg(OPL,OPL->address,v);
 2039      }
 2040      return OPL->status>>7;
 2041  }
 2042  
 2043  static unsigned char OPLRead(FM_OPL *OPL,int a)
 2044  {
 2045      if( !(a&1) )
 2046      {
 2047          /* status port */
 2048  
 2049          #if BUILD_Y8950
 2050  
 2051          if(OPL->type&OPL_TYPE_ADPCM)    /* Y8950 */
 2052          {
 2053              return (OPL->status & (OPL->statusmask|0x80)) | (OPL->deltat->PCM_BSY&1);
 2054          }
 2055  
 2056          #endif
 2057  
 2058          /* OPL and OPL2 */
 2059          return OPL->status & (OPL->statusmask|0x80);
 2060      }
 2061  
 2062  #if BUILD_Y8950
 2063      /* data port */
 2064      switch(OPL->address)
 2065      {
 2066      case 0x05: /* KeyBoard IN */
 2067          if(OPL->type&OPL_TYPE_KEYBOARD)
 2068          {
 2069              if(OPL->keyboardhandler_r)
 2070                  return OPL->keyboardhandler_r(OPL->keyboard_param);
 2071              else
 2072                  logerror("Y8950: read unmapped KEYBOARD port\n");
 2073          }
 2074          return 0;
 2075  
 2076      case 0x0f: /* ADPCM-DATA  */
 2077          if(OPL->type&OPL_TYPE_ADPCM)
 2078          {
 2079              UINT8 val;
 2080  
 2081              val = YM_DELTAT_ADPCM_Read(OPL->deltat);
 2082              /*logerror("Y8950: read ADPCM value read=%02x\n",val);*/
 2083              return val;
 2084          }
 2085          return 0;
 2086  
 2087      case 0x19: /* I/O DATA    */
 2088          if(OPL->type&OPL_TYPE_IO)
 2089          {
 2090              if(OPL->porthandler_r)
 2091                  return OPL->porthandler_r(OPL->port_param);
 2092              else
 2093                  logerror("Y8950:read unmapped I/O port\n");
 2094          }
 2095          return 0;
 2096      case 0x1a: /* PCM-DATA    */
 2097          if(OPL->type&OPL_TYPE_ADPCM)
 2098          {
 2099              logerror("Y8950 A/D convertion is accessed but not implemented !\n");
 2100              return 0x80; /* 2's complement PCM data - result from A/D convertion */
 2101          }
 2102          return 0;
 2103      }
 2104  #endif
 2105  
 2106      return 0xff;
 2107  }
 2108  
 2109  /* CSM Key Controll */
 2110  INLINE void CSMKeyControll(OPL_CH *CH)
 2111  {
 2112      FM_KEYON (&CH->SLOT[SLOT1], 4);
 2113      FM_KEYON (&CH->SLOT[SLOT2], 4);
 2114  
 2115      /* The key off should happen exactly one sample later - not implemented correctly yet */
 2116  
 2117      FM_KEYOFF(&CH->SLOT[SLOT1], ~4);
 2118      FM_KEYOFF(&CH->SLOT[SLOT2], ~4);
 2119  }
 2120  
 2121  
 2122  static int OPLTimerOver(FM_OPL *OPL,int c)
 2123  {
 2124      if( c )
 2125      {   /* Timer B */
 2126          OPL_STATUS_SET(OPL,0x20);
 2127      }
 2128      else
 2129      {   /* Timer A */
 2130          OPL_STATUS_SET(OPL,0x40);
 2131          /* CSM mode key,TL controll */
 2132          if( OPL->mode & 0x80 )
 2133          {   /* CSM mode total level latch and auto key on */
 2134              int ch;
 2135              if(OPL->UpdateHandler) OPL->UpdateHandler(OPL->UpdateParam,0);
 2136              for(ch=0; ch<9; ch++)
 2137                  CSMKeyControll( &OPL->P_CH[ch] );
 2138          }
 2139      }
 2140      /* reload timer */
 2141      if (OPL->timer_handler) (OPL->timer_handler)(OPL->TimerParam,c,OPL->TimerBase * OPL->T[c]);
 2142      return OPL->status>>7;
 2143  }
 2144  
 2145  
 2146  #define MAX_OPL_CHIPS 2
 2147  
 2148  
 2149  #if (BUILD_YM3812)
 2150  
 2151  void * ym3812_init(device_t *device, UINT32 clock, UINT32 rate)
 2152  {
 2153      /* emulator create */
 2154      FM_OPL *YM3812 = OPLCreate(device,clock,rate,OPL_TYPE_YM3812);
 2155      if (YM3812)
 2156      {
 2157          OPL_save_state(YM3812, device);
 2158          ym3812_reset_chip(YM3812);
 2159      }
 2160      return YM3812;
 2161  }
 2162  
 2163  void ym3812_shutdown(void *chip)
 2164  {
 2165      FM_OPL *YM3812 = (FM_OPL *)chip;
 2166  
 2167      /* emulator shutdown */
 2168      OPLDestroy(YM3812);
 2169  }
 2170  void ym3812_reset_chip(void *chip)
 2171  {
 2172      FM_OPL *YM3812 = (FM_OPL *)chip;
 2173      OPLResetChip(YM3812);
 2174  }
 2175  
 2176  int ym3812_write(void *chip, int a, int v)
 2177  {
 2178      FM_OPL *YM3812 = (FM_OPL *)chip;
 2179      return OPLWrite(YM3812, a, v);
 2180  }
 2181  
 2182  unsigned char ym3812_read(void *chip, int a)
 2183  {
 2184      FM_OPL *YM3812 = (FM_OPL *)chip;
 2185      /* YM3812 always returns bit2 and bit1 in HIGH state */
 2186      return OPLRead(YM3812, a) | 0x06 ;
 2187  }
 2188  int ym3812_timer_over(void *chip, int c)
 2189  {
 2190      FM_OPL *YM3812 = (FM_OPL *)chip;
 2191      return OPLTimerOver(YM3812, c);
 2192  }
 2193  
 2194  void ym3812_set_timer_handler(void *chip, OPL_TIMERHANDLER timer_handler, void *param)
 2195  {
 2196      FM_OPL *YM3812 = (FM_OPL *)chip;
 2197      OPLSetTimerHandler(YM3812, timer_handler, param);
 2198  }
 2199  void ym3812_set_irq_handler(void *chip,OPL_IRQHANDLER IRQHandler,void *param)
 2200  {
 2201      FM_OPL *YM3812 = (FM_OPL *)chip;
 2202      OPLSetIRQHandler(YM3812, IRQHandler, param);
 2203  }
 2204  void ym3812_set_update_handler(void *chip,OPL_UPDATEHANDLER UpdateHandler,void *param)
 2205  {
 2206      FM_OPL *YM3812 = (FM_OPL *)chip;
 2207      OPLSetUpdateHandler(YM3812, UpdateHandler, param);
 2208  }
 2209  
 2210  
 2211  /*
 2212  ** Generate samples for one of the YM3812's
 2213  **
 2214  ** 'which' is the virtual YM3812 number
 2215  ** '*buffer' is the output buffer pointer
 2216  ** 'length' is the number of samples that should be generated
 2217  */
 2218  void ym3812_update_one(void *chip, OPLSAMPLE *buffer, int length)
 2219  {
 2220      FM_OPL      *OPL = (FM_OPL *)chip;
 2221      UINT8       rhythm = OPL->rhythm&0x20;
 2222      OPLSAMPLE   *buf = buffer;
 2223      int i;
 2224  
 2225      for( i=0; i < length ; i++ )
 2226      {
 2227          int lt;
 2228  
 2229          OPL->output[0] = 0;
 2230  
 2231          advance_lfo(OPL);
 2232  
 2233          /* FM part */
 2234          OPL_CALC_CH(OPL, &OPL->P_CH[0]);
 2235          OPL_CALC_CH(OPL, &OPL->P_CH[1]);
 2236          OPL_CALC_CH(OPL, &OPL->P_CH[2]);
 2237          OPL_CALC_CH(OPL, &OPL->P_CH[3]);
 2238          OPL_CALC_CH(OPL, &OPL->P_CH[4]);
 2239          OPL_CALC_CH(OPL, &OPL->P_CH[5]);
 2240  
 2241          if(!rhythm)
 2242          {
 2243              OPL_CALC_CH(OPL, &OPL->P_CH[6]);
 2244              OPL_CALC_CH(OPL, &OPL->P_CH[7]);
 2245              OPL_CALC_CH(OPL, &OPL->P_CH[8]);
 2246          }
 2247          else        /* Rhythm part */
 2248          {
 2249              OPL_CALC_RH(OPL, &OPL->P_CH[0], (OPL->noise_rng>>0)&1 );
 2250          }
 2251  
 2252          lt = OPL->output[0];
 2253  
 2254          lt >>= FINAL_SH;
 2255  
 2256          /* limit check */
 2257          lt = limit( lt , MAXOUT, MINOUT );
 2258  
 2259          #ifdef SAVE_SAMPLE
 2260          if (which==0)
 2261          {
 2262              SAVE_ALL_CHANNELS
 2263          }
 2264          #endif
 2265  
 2266          /* store to sound buffer */
 2267          buf[i] = lt;
 2268  
 2269          advance(OPL);
 2270      }
 2271  
 2272  }
 2273  #endif /* BUILD_YM3812 */
 2274  
 2275  
 2276  
 2277  #if (BUILD_YM3526)
 2278  
 2279  void *ym3526_init(device_t *device, UINT32 clock, UINT32 rate)
 2280  {
 2281      /* emulator create */
 2282      FM_OPL *YM3526 = OPLCreate(device,clock,rate,OPL_TYPE_YM3526);
 2283      if (YM3526)
 2284      {
 2285          OPL_save_state(YM3526, device);
 2286          ym3526_reset_chip(YM3526);
 2287      }
 2288      return YM3526;
 2289  }
 2290  
 2291  void ym3526_shutdown(void *chip)
 2292  {
 2293      FM_OPL *YM3526 = (FM_OPL *)chip;
 2294      /* emulator shutdown */
 2295      OPLDestroy(YM3526);
 2296  }
 2297  void ym3526_reset_chip(void *chip)
 2298  {
 2299      FM_OPL *YM3526 = (FM_OPL *)chip;
 2300      OPLResetChip(YM3526);
 2301  }
 2302  
 2303  int ym3526_write(void *chip, int a, int v)
 2304  {
 2305      FM_OPL *YM3526 = (FM_OPL *)chip;
 2306      return OPLWrite(YM3526, a, v);
 2307  }
 2308  
 2309  unsigned char ym3526_read(void *chip, int a)
 2310  {
 2311      FM_OPL *YM3526 = (FM_OPL *)chip;
 2312      /* YM3526 always returns bit2 and bit1 in HIGH state */
 2313      return OPLRead(YM3526, a) | 0x06 ;
 2314  }
 2315  int ym3526_timer_over(void *chip, int c)
 2316  {
 2317      FM_OPL *YM3526 = (FM_OPL *)chip;
 2318      return OPLTimerOver(YM3526, c);
 2319  }
 2320  
 2321  void ym3526_set_timer_handler(void *chip, OPL_TIMERHANDLER timer_handler, void *param)
 2322  {
 2323      FM_OPL *YM3526 = (FM_OPL *)chip;
 2324      OPLSetTimerHandler(YM3526, timer_handler, param);
 2325  }
 2326  void ym3526_set_irq_handler(void *chip,OPL_IRQHANDLER IRQHandler,void *param)
 2327  {
 2328      FM_OPL *YM3526 = (FM_OPL *)chip;
 2329      OPLSetIRQHandler(YM3526, IRQHandler, param);
 2330  }
 2331  void ym3526_set_update_handler(void *chip,OPL_UPDATEHANDLER UpdateHandler,void *param)
 2332  {
 2333      FM_OPL *YM3526 = (FM_OPL *)chip;
 2334      OPLSetUpdateHandler(YM3526, UpdateHandler, param);
 2335  }
 2336  
 2337  
 2338  /*
 2339  ** Generate samples for one of the YM3526's
 2340  **
 2341  ** 'which' is the virtual YM3526 number
 2342  ** '*buffer' is the output buffer pointer
 2343  ** 'length' is the number of samples that should be generated
 2344  */
 2345  void ym3526_update_one(void *chip, OPLSAMPLE *buffer, int length)
 2346  {
 2347      FM_OPL      *OPL = (FM_OPL *)chip;
 2348      UINT8       rhythm = OPL->rhythm&0x20;
 2349      OPLSAMPLE   *buf = buffer;
 2350      int i;
 2351  
 2352      for( i=0; i < length ; i++ )
 2353      {
 2354          int lt;
 2355  
 2356          OPL->output[0] = 0;
 2357  
 2358          advance_lfo(OPL);
 2359  
 2360          /* FM part */
 2361          OPL_CALC_CH(OPL, &OPL->P_CH[0]);
 2362          OPL_CALC_CH(OPL, &OPL->P_CH[1]);
 2363          OPL_CALC_CH(OPL, &OPL->P_CH[2]);
 2364          OPL_CALC_CH(OPL, &OPL->P_CH[3]);
 2365          OPL_CALC_CH(OPL, &OPL->P_CH[4]);
 2366          OPL_CALC_CH(OPL, &OPL->P_CH[5]);
 2367  
 2368          if(!rhythm)
 2369          {
 2370              OPL_CALC_CH(OPL, &OPL->P_CH[6]);
 2371              OPL_CALC_CH(OPL, &OPL->P_CH[7]);
 2372              OPL_CALC_CH(OPL, &OPL->P_CH[8]);
 2373          }
 2374          else        /* Rhythm part */
 2375          {
 2376              OPL_CALC_RH(OPL, &OPL->P_CH[0], (OPL->noise_rng>>0)&1 );
 2377          }
 2378  
 2379          lt = OPL->output[0];
 2380  
 2381          lt >>= FINAL_SH;
 2382  
 2383          /* limit check */
 2384          lt = limit( lt , MAXOUT, MINOUT );
 2385  
 2386          #ifdef SAVE_SAMPLE
 2387          if (which==0)
 2388          {
 2389              SAVE_ALL_CHANNELS
 2390          }
 2391          #endif
 2392  
 2393          /* store to sound buffer */
 2394          buf[i] = lt;
 2395  
 2396          advance(OPL);
 2397      }
 2398  
 2399  }
 2400  #endif /* BUILD_YM3526 */
 2401  
 2402  
 2403  
 2404  
 2405  #if BUILD_Y8950
 2406  
 2407  static void Y8950_deltat_status_set(void *chip, UINT8 changebits)
 2408  {
 2409      FM_OPL *Y8950 = (FM_OPL *)chip;
 2410      OPL_STATUS_SET(Y8950, changebits);
 2411  }
 2412  static void Y8950_deltat_status_reset(void *chip, UINT8 changebits)
 2413  {
 2414      FM_OPL *Y8950 = (FM_OPL *)chip;
 2415      OPL_STATUS_RESET(Y8950, changebits);
 2416  }
 2417  
 2418  void *y8950_init(device_t *device, UINT32 clock, UINT32 rate)
 2419  {
 2420      /* emulator create */
 2421      FM_OPL *Y8950 = OPLCreate(device,clock,rate,OPL_TYPE_Y8950);
 2422      if (Y8950)
 2423      {
 2424          Y8950->deltat->status_set_handler = Y8950_deltat_status_set;
 2425          Y8950->deltat->status_reset_handler = Y8950_deltat_status_reset;
 2426          Y8950->deltat->status_change_which_chip = Y8950;
 2427          Y8950->deltat->status_change_EOS_bit = 0x10;        /* status flag: set bit4 on End Of Sample */
 2428          Y8950->deltat->status_change_BRDY_bit = 0x08;   /* status flag: set bit3 on BRDY (End Of: ADPCM analysis/synthesis, memory reading/writing) */
 2429  
 2430          /*Y8950->deltat->write_time = 10.0 / clock;*/       /* a single byte write takes 10 cycles of main clock */
 2431          /*Y8950->deltat->read_time  = 8.0 / clock;*/        /* a single byte read takes 8 cycles of main clock */
 2432          /* reset */
 2433          OPL_save_state(Y8950, device);
 2434          y8950_reset_chip(Y8950);
 2435      }
 2436  
 2437      return Y8950;
 2438  }
 2439  
 2440  void y8950_shutdown(void *chip)
 2441  {
 2442      FM_OPL *Y8950 = (FM_OPL *)chip;
 2443      /* emulator shutdown */
 2444      OPLDestroy(Y8950);
 2445  }
 2446  void y8950_reset_chip(void *chip)
 2447  {
 2448      FM_OPL *Y8950 = (FM_OPL *)chip;
 2449      OPLResetChip(Y8950);
 2450  }
 2451  
 2452  int y8950_write(void *chip, int a, int v)
 2453  {
 2454      FM_OPL *Y8950 = (FM_OPL *)chip;
 2455      return OPLWrite(Y8950, a, v);
 2456  }
 2457  
 2458  unsigned char y8950_read(void *chip, int a)
 2459  {
 2460      FM_OPL *Y8950 = (FM_OPL *)chip;
 2461      return OPLRead(Y8950, a);
 2462  }
 2463  int y8950_timer_over(void *chip, int c)
 2464  {
 2465      FM_OPL *Y8950 = (FM_OPL *)chip;
 2466      return OPLTimerOver(Y8950, c);
 2467  }
 2468  
 2469  void y8950_set_timer_handler(void *chip, OPL_TIMERHANDLER timer_handler, void *param)
 2470  {
 2471      FM_OPL *Y8950 = (FM_OPL *)chip;
 2472      OPLSetTimerHandler(Y8950, timer_handler, param);
 2473  }
 2474  void y8950_set_irq_handler(void *chip,OPL_IRQHANDLER IRQHandler,void *param)
 2475  {
 2476      FM_OPL *Y8950 = (FM_OPL *)chip;
 2477      OPLSetIRQHandler(Y8950, IRQHandler, param);
 2478  }
 2479  void y8950_set_update_handler(void *chip,OPL_UPDATEHANDLER UpdateHandler,void *param)
 2480  {
 2481      FM_OPL *Y8950 = (FM_OPL *)chip;
 2482      OPLSetUpdateHandler(Y8950, UpdateHandler, param);
 2483  }
 2484  
 2485  void y8950_set_delta_t_memory(void *chip, void * deltat_mem_ptr, int deltat_mem_size )
 2486  {
 2487      FM_OPL      *OPL = (FM_OPL *)chip;
 2488      OPL->deltat->memory = (UINT8 *)(deltat_mem_ptr);
 2489      OPL->deltat->memory_size = deltat_mem_size;
 2490  }
 2491  
 2492  /*
 2493  ** Generate samples for one of the Y8950's
 2494  **
 2495  ** 'which' is the virtual Y8950 number
 2496  ** '*buffer' is the output buffer pointer
 2497  ** 'length' is the number of samples that should be generated
 2498  */
 2499  void y8950_update_one(void *chip, OPLSAMPLE *buffer, int length)
 2500  {
 2501      int i;
 2502      FM_OPL      *OPL = (FM_OPL *)chip;
 2503      UINT8       rhythm  = OPL->rhythm&0x20;
 2504      YM_DELTAT   *DELTAT = OPL->deltat;
 2505      OPLSAMPLE   *buf    = buffer;
 2506  
 2507      for( i=0; i < length ; i++ )
 2508      {
 2509          int lt;
 2510  
 2511          OPL->output[0] = 0;
 2512          OPL->output_deltat[0] = 0;
 2513  
 2514          advance_lfo(OPL);
 2515  
 2516          /* deltaT ADPCM */
 2517          if( DELTAT->portstate&0x80 )
 2518              YM_DELTAT_ADPCM_CALC(DELTAT);
 2519  
 2520          /* FM part */
 2521          OPL_CALC_CH(OPL, &OPL->P_CH[0]);
 2522          OPL_CALC_CH(OPL, &OPL->P_CH[1]);
 2523          OPL_CALC_CH(OPL, &OPL->P_CH[2]);
 2524          OPL_CALC_CH(OPL, &OPL->P_CH[3]);
 2525          OPL_CALC_CH(OPL, &OPL->P_CH[4]);
 2526          OPL_CALC_CH(OPL, &OPL->P_CH[5]);
 2527  
 2528          if(!rhythm)
 2529          {
 2530              OPL_CALC_CH(OPL, &OPL->P_CH[6]);
 2531              OPL_CALC_CH(OPL, &OPL->P_CH[7]);
 2532              OPL_CALC_CH(OPL, &OPL->P_CH[8]);
 2533          }
 2534          else        /* Rhythm part */
 2535          {
 2536              OPL_CALC_RH(OPL, &OPL->P_CH[0], (OPL->noise_rng>>0)&1 );
 2537          }
 2538  
 2539          lt = OPL->output[0] + (OPL->output_deltat[0]>>11);
 2540  
 2541          lt >>= FINAL_SH;
 2542  
 2543          /* limit check */
 2544          lt = limit( lt , MAXOUT, MINOUT );
 2545  
 2546          #ifdef SAVE_SAMPLE
 2547          if (which==0)
 2548          {
 2549              SAVE_ALL_CHANNELS
 2550          }
 2551          #endif
 2552  
 2553          /* store to sound buffer */
 2554          buf[i] = lt;
 2555  
 2556          advance(OPL);
 2557      }
 2558  
 2559  }
 2560  
 2561  void y8950_set_port_handler(void *chip,OPL_PORTHANDLER_W PortHandler_w,OPL_PORTHANDLER_R PortHandler_r,void * param)
 2562  {
 2563      FM_OPL      *OPL = (FM_OPL *)chip;
 2564      OPL->porthandler_w = PortHandler_w;
 2565      OPL->porthandler_r = PortHandler_r;
 2566      OPL->port_param = param;
 2567  }
 2568  
 2569  void y8950_set_keyboard_handler(void *chip,OPL_PORTHANDLER_W KeyboardHandler_w,OPL_PORTHANDLER_R KeyboardHandler_r,void * param)
 2570  {
 2571      FM_OPL      *OPL = (FM_OPL *)chip;
 2572      OPL->keyboardhandler_w = KeyboardHandler_w;
 2573      OPL->keyboardhandler_r = KeyboardHandler_r;
 2574      OPL->keyboard_param = param;
 2575  }
 2576  
 2577  #endif