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