1 #define YM2610B_WARNING
2 
3 /*
4 **
5 ** File: fm.c -- software implementation of Yamaha FM sound generator
6 **
7 ** Copyright (C) 2001, 2002, 2003 Jarek Burczynski (bujar at mame dot net)
8 ** Copyright (C) 1998 Tatsuyuki Satoh , MultiArcadeMachineEmulator development
9 **
10 ** Version 1.4 (final beta)
11 **
12 */
13 
14 /*
15 ** History:
16 **
17 ** 03-08-2003 Jarek Burczynski:
18 **  - fixed YM2608 initial values (after the reset)
19 **  - fixed flag and irqmask handling (YM2608)
20 **  - fixed BUFRDY flag handling (YM2608)
21 **
22 ** 14-06-2003 Jarek Burczynski:
23 **  - implemented all of the YM2608 status register flags
24 **  - implemented support for external memory read/write via YM2608
25 **  - implemented support for deltat memory limit register in YM2608 emulation
26 **
27 ** 22-05-2003 Jarek Burczynski:
28 **  - fixed LFO PM calculations (copy&paste bugfix)
29 **
30 ** 08-05-2003 Jarek Burczynski:
31 **  - fixed SSG support
32 **
33 ** 22-04-2003 Jarek Burczynski:
34 **  - implemented 100% correct LFO generator (verified on real YM2610 and YM2608)
35 **
36 ** 15-04-2003 Jarek Burczynski:
37 **  - added support for YM2608's register 0x110 - status mask
38 **
39 ** 01-12-2002 Jarek Burczynski:
40 **  - fixed register addressing in YM2608, YM2610, YM2610B chips. (verified on real YM2608)
41 **    The addressing patch used for early Neo-Geo games can be removed now.
42 **
43 ** 26-11-2002 Jarek Burczynski, Nicola Salmoria:
44 **  - recreated YM2608 ADPCM ROM using data from real YM2608's output which leads to:
45 **  - added emulation of YM2608 drums.
46 **  - output of YM2608 is two times lower now - same as YM2610 (verified on real YM2608)
47 **
48 ** 16-08-2002 Jarek Burczynski:
49 **  - binary exact Envelope Generator (verified on real YM2203);
50 **    identical to YM2151
51 **  - corrected 'off by one' error in feedback calculations (when feedback is off)
52 **  - corrected connection (algorithm) calculation (verified on real YM2203 and YM2610)
53 **
54 ** 18-12-2001 Jarek Burczynski:
55 **  - added SSG-EG support (verified on real YM2203)
56 **
57 ** 12-08-2001 Jarek Burczynski:
58 **  - corrected sin_tab and tl_tab data (verified on real chip)
59 **  - corrected feedback calculations (verified on real chip)
60 **  - corrected phase generator calculations (verified on real chip)
61 **  - corrected envelope generator calculations (verified on real chip)
62 **  - corrected FM volume level (YM2610 and YM2610B).
63 **  - changed YMxxxUpdateOne() functions (YM2203, YM2608, YM2610, YM2610B, YM2612) :
64 **    this was needed to calculate YM2610 FM channels output correctly.
65 **    (Each FM channel is calculated as in other chips, but the output of the channel
66 **    gets shifted right by one *before* sending to accumulator. That was impossible to do
67 **    with previous implementation).
68 **
69 ** 23-07-2001 Jarek Burczynski, Nicola Salmoria:
70 **  - corrected YM2610 ADPCM type A algorithm and tables (verified on real chip)
71 **
72 ** 11-06-2001 Jarek Burczynski:
73 **  - corrected end of sample bug in ADPCMA_calc_cha().
74 **    Real YM2610 checks for equality between current and end addresses (only 20 LSB bits).
75 **
76 ** 08-12-98 hiro-shi:
77 ** rename ADPCMA -> ADPCMB, ADPCMB -> ADPCMA
78 ** move ROM limit check.(CALC_CH? -> 2610Write1/2)
79 ** test program (ADPCMB_TEST)
80 ** move ADPCM A/B end check.
81 ** ADPCMB repeat flag(no check)
82 ** change ADPCM volume rate (8->16) (32->48).
83 **
84 ** 09-12-98 hiro-shi:
85 ** change ADPCM volume. (8->16, 48->64)
86 ** replace ym2610 ch0/3 (YM-2610B)
87 ** init cur_chip (restart bug fix)
88 ** change ADPCM_SHIFT (10->8) missing bank change 0x4000-0xffff.
89 ** add ADPCM_SHIFT_MASK
90 ** change ADPCMA_DECODE_MIN/MAX.
91 */
92 
93 
94 
95 
96 /************************************************************************/
97 /*    comment of hiro-shi(Hiromitsu Shioya)                             */
98 /*    YM2610(B) = OPN-B                                                 */
99 /*    YM2610  : PSG:3ch FM:4ch ADPCM(18.5KHz):6ch DeltaT ADPCM:1ch      */
100 /*    YM2610B : PSG:3ch FM:6ch ADPCM(18.5KHz):6ch DeltaT ADPCM:1ch      */
101 /************************************************************************/
102 
103 #include <stdio.h>
104 #include <stdlib.h>
105 #include <string.h>
106 #include <stdarg.h>
107 #include <math.h>
108 
109 #ifndef __RAINE__
110 #include "driver.h"		/* use M.A.M.E. */
111 #include "state.h"
112 #else
113 #include "deftypes.h"		/* use RAINE */
114 #include "support.h"		/* use RAINE */
115 #endif
116 
117 #define AY8910_CORE
118 #include "ay8910.h"
119 #undef AY8910_CORE
120 #include "fm.h"
121 
122 
123 #ifndef PI
124 #define PI 3.14159265358979323846
125 #endif
126 
127 
128 /* include external DELTA-T unit (when needed) */
129 #if (BUILD_YM2608||BUILD_YM2610||BUILD_YM2610B)
130 	#include "ymdeltat.h"
131 #endif
132 
133 /* shared function building option */
134 #define BUILD_OPN (BUILD_YM2203||BUILD_YM2608||BUILD_YM2610||BUILD_YM2610B||BUILD_YM2612)
135 #define BUILD_OPN_PRESCALER (BUILD_YM2203||BUILD_YM2608)
136 
137 
138 /* globals */
139 #define TYPE_SSG    0x01    /* SSG support          */
140 #define TYPE_LFOPAN 0x02    /* OPN type LFO and PAN */
141 #define TYPE_6CH    0x04    /* FM 6CH / 3CH         */
142 #define TYPE_DAC    0x08    /* YM2612's DAC device  */
143 #define TYPE_ADPCM  0x10    /* two ADPCM units      */
144 #define TYPE_2610   0x20    /* bogus flag to differentiate 2608 from 2610 */
145 
146 #define TYPE_YM2203 (TYPE_SSG)
147 #define TYPE_YM2608 (TYPE_SSG |TYPE_LFOPAN |TYPE_6CH |TYPE_ADPCM)
148 #define TYPE_YM2610 (TYPE_SSG |TYPE_LFOPAN |TYPE_6CH |TYPE_ADPCM |TYPE_2610)
149 #define TYPE_YM2612 (TYPE_DAC |TYPE_LFOPAN |TYPE_6CH)
150 
151 
152 
153 #define FREQ_SH			16  /* 16.16 fixed point (frequency calculations) */
154 #define EG_SH			16  /* 16.16 fixed point (envelope generator timing) */
155 #define LFO_SH			24  /*  8.24 fixed point (LFO calculations)       */
156 #define TIMER_SH		16  /* 16.16 fixed point (timers calculations)    */
157 
158 #define FREQ_MASK		((1<<FREQ_SH)-1)
159 
160 #define ENV_BITS		10
161 #define ENV_LEN			(1<<ENV_BITS)
162 #define ENV_STEP		(128.0/ENV_LEN)
163 
164 #define MAX_ATT_INDEX	(ENV_LEN-1) /* 1023 */
165 #define MIN_ATT_INDEX	(0)			/* 0 */
166 
167 #define EG_ATT			4
168 #define EG_DEC			3
169 #define EG_SUS			2
170 #define EG_REL			1
171 #define EG_OFF			0
172 
173 #define SIN_BITS		10
174 #define SIN_LEN			(1<<SIN_BITS)
175 #define SIN_MASK		(SIN_LEN-1)
176 
177 #define TL_RES_LEN		(256) /* 8 bits addressing (real chip) */
178 
179 
180 #if (FM_SAMPLE_BITS==16)
181 	#define FINAL_SH	(0)
182 	#define MAXOUT		(+32767)
183 	#define MINOUT		(-32768)
184 #else
185 	#define FINAL_SH	(8)
186 	#define MAXOUT		(+127)
187 	#define MINOUT		(-128)
188 #endif
189 
190 
191 /*	TL_TAB_LEN is calculated as:
192 *	13 - sinus amplitude bits     (Y axis)
193 *	2  - sinus sign bit           (Y axis)
194 *	TL_RES_LEN - sinus resolution (X axis)
195 */
196 #define TL_TAB_LEN (13*2*TL_RES_LEN)
197 static signed int tl_tab[TL_TAB_LEN];
198 
199 #define ENV_QUIET		(TL_TAB_LEN>>3)
200 
201 /* sin waveform table in 'decibel' scale */
202 static unsigned int sin_tab[SIN_LEN];
203 
204 /* sustain level table (3dB per step) */
205 /* bit0, bit1, bit2, bit3, bit4, bit5, bit6 */
206 /* 1,    2,    4,    8,    16,   32,   64   (value)*/
207 /* 0.75, 1.5,  3,    6,    12,   24,   48   (dB)*/
208 
209 /* 0 - 15: 0, 3, 6, 9,12,15,18,21,24,27,30,33,36,39,42,93 (dB)*/
210 #define SC(db) (UINT32) ( db * (4.0/ENV_STEP) )
211 static const UINT32 sl_table[16]={
212  SC( 0),SC( 1),SC( 2),SC(3 ),SC(4 ),SC(5 ),SC(6 ),SC( 7),
213  SC( 8),SC( 9),SC(10),SC(11),SC(12),SC(13),SC(14),SC(31)
214 };
215 #undef SC
216 
217 
218 #define RATE_STEPS (8)
219 static const UINT8 eg_inc[19*RATE_STEPS]={
220 
221 /*cycle:0 1  2 3  4 5  6 7*/
222 
223 /* 0 */ 0,1, 0,1, 0,1, 0,1, /* rates 00..11 0 (increment by 0 or 1) */
224 /* 1 */ 0,1, 0,1, 1,1, 0,1, /* rates 00..11 1 */
225 /* 2 */ 0,1, 1,1, 0,1, 1,1, /* rates 00..11 2 */
226 /* 3 */ 0,1, 1,1, 1,1, 1,1, /* rates 00..11 3 */
227 
228 /* 4 */ 1,1, 1,1, 1,1, 1,1, /* rate 12 0 (increment by 1) */
229 /* 5 */ 1,1, 1,2, 1,1, 1,2, /* rate 12 1 */
230 /* 6 */ 1,2, 1,2, 1,2, 1,2, /* rate 12 2 */
231 /* 7 */ 1,2, 2,2, 1,2, 2,2, /* rate 12 3 */
232 
233 /* 8 */ 2,2, 2,2, 2,2, 2,2, /* rate 13 0 (increment by 2) */
234 /* 9 */ 2,2, 2,4, 2,2, 2,4, /* rate 13 1 */
235 /*10 */ 2,4, 2,4, 2,4, 2,4, /* rate 13 2 */
236 /*11 */ 2,4, 4,4, 2,4, 4,4, /* rate 13 3 */
237 
238 /*12 */ 4,4, 4,4, 4,4, 4,4, /* rate 14 0 (increment by 4) */
239 /*13 */ 4,4, 4,8, 4,4, 4,8, /* rate 14 1 */
240 /*14 */ 4,8, 4,8, 4,8, 4,8, /* rate 14 2 */
241 /*15 */ 4,8, 8,8, 4,8, 8,8, /* rate 14 3 */
242 
243 /*16 */ 8,8, 8,8, 8,8, 8,8, /* rates 15 0, 15 1, 15 2, 15 3 (increment by 8) */
244 /*17 */ 16,16,16,16,16,16,16,16, /* rates 15 2, 15 3 for attack */
245 /*18 */ 0,0, 0,0, 0,0, 0,0, /* infinity rates for attack and decay(s) */
246 };
247 
248 
249 #define O(a) (a*RATE_STEPS)
250 
251 /*note that there is no O(17) in this table - it's directly in the code */
252 static const UINT8 eg_rate_select[32+64+32]={	/* Envelope Generator rates (32 + 64 rates + 32 RKS) */
253 /* 32 infinite time rates */
254 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
255 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
256 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
257 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
258 
259 /* rates 00-11 */
260 O( 0),O( 1),O( 2),O( 3),
261 O( 0),O( 1),O( 2),O( 3),
262 O( 0),O( 1),O( 2),O( 3),
263 O( 0),O( 1),O( 2),O( 3),
264 O( 0),O( 1),O( 2),O( 3),
265 O( 0),O( 1),O( 2),O( 3),
266 O( 0),O( 1),O( 2),O( 3),
267 O( 0),O( 1),O( 2),O( 3),
268 O( 0),O( 1),O( 2),O( 3),
269 O( 0),O( 1),O( 2),O( 3),
270 O( 0),O( 1),O( 2),O( 3),
271 O( 0),O( 1),O( 2),O( 3),
272 
273 /* rate 12 */
274 O( 4),O( 5),O( 6),O( 7),
275 
276 /* rate 13 */
277 O( 8),O( 9),O(10),O(11),
278 
279 /* rate 14 */
280 O(12),O(13),O(14),O(15),
281 
282 /* rate 15 */
283 O(16),O(16),O(16),O(16),
284 
285 /* 32 dummy rates (same as 15 3) */
286 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
287 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
288 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
289 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16)
290 
291 };
292 
293 static const UINT8 eg_rate_select2612[32+64+32]={    /* Envelope Generator rates (32 + 64 rates + 32 RKS) */
294 /* 32 infinite time rates */
295 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
296 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
297 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
298 O(18),O(18),O(18),O(18),O(18),O(18),O(18),O(18),
299 
300 /* rates 00-11 */
301 O( 18),O( 18),O( 0),O( 0),
302 O( 0),O( 0),O( 2),O( 2),  // Nemesis's tests
303 
304 O( 0),O( 1),O( 2),O( 3),
305 O( 0),O( 1),O( 2),O( 3),
306 O( 0),O( 1),O( 2),O( 3),
307 O( 0),O( 1),O( 2),O( 3),
308 O( 0),O( 1),O( 2),O( 3),
309 O( 0),O( 1),O( 2),O( 3),
310 O( 0),O( 1),O( 2),O( 3),
311 O( 0),O( 1),O( 2),O( 3),
312 O( 0),O( 1),O( 2),O( 3),
313 O( 0),O( 1),O( 2),O( 3),
314 
315 /* rate 12 */
316 O( 4),O( 5),O( 6),O( 7),
317 
318 /* rate 13 */
319 O( 8),O( 9),O(10),O(11),
320 
321 /* rate 14 */
322 O(12),O(13),O(14),O(15),
323 
324 /* rate 15 */
325 O(16),O(16),O(16),O(16),
326 
327 /* 32 dummy rates (same as 15 3) */
328 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
329 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
330 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16),
331 O(16),O(16),O(16),O(16),O(16),O(16),O(16),O(16)
332 
333 };
334 #undef O
335 
336 /*rate  0,    1,    2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15*/
337 /*shift 11,  10,  9,  8,  7,  6,  5,  4,  3,  2, 1,  0,  0,  0,  0,  0 */
338 /*mask  2047, 1023, 511, 255, 127, 63, 31, 15, 7,  3, 1,  0,  0,  0,  0,  0 */
339 
340 #define O(a) (a*1)
341 static const UINT8 eg_rate_shift[32+64+32]={	/* Envelope Generator counter shifts (32 + 64 rates + 32 RKS) */
342 /* 32 infinite time rates */
343 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
344 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
345 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
346 O(0),O(0),O(0),O(0),O(0),O(0),O(0),O(0),
347 
348 /* rates 00-11 */
349 O(11),O(11),O(11),O(11),
350 O(10),O(10),O(10),O(10),
351 O( 9),O( 9),O( 9),O( 9),
352 O( 8),O( 8),O( 8),O( 8),
353 O( 7),O( 7),O( 7),O( 7),
354 O( 6),O( 6),O( 6),O( 6),
355 O( 5),O( 5),O( 5),O( 5),
356 O( 4),O( 4),O( 4),O( 4),
357 O( 3),O( 3),O( 3),O( 3),
358 O( 2),O( 2),O( 2),O( 2),
359 O( 1),O( 1),O( 1),O( 1),
360 O( 0),O( 0),O( 0),O( 0),
361 
362 /* rate 12 */
363 O( 0),O( 0),O( 0),O( 0),
364 
365 /* rate 13 */
366 O( 0),O( 0),O( 0),O( 0),
367 
368 /* rate 14 */
369 O( 0),O( 0),O( 0),O( 0),
370 
371 /* rate 15 */
372 O( 0),O( 0),O( 0),O( 0),
373 
374 /* 32 dummy rates (same as 15 3) */
375 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
376 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
377 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),
378 O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0),O( 0)
379 
380 };
381 #undef O
382 
383 static const UINT8 dt_tab[4 * 32]={
384 /* this is YM2151 and YM2612 phase increment data (in 10.10 fixed point format)*/
385 /* FD=0 */
386 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
387 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
388 /* FD=1 */
389 	0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
390 	2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
391 /* FD=2 */
392 	1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5,
393 	5, 6, 6, 7, 8, 8, 9,10,11,12,13,14,16,16,16,16,
394 /* FD=3 */
395 	2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7,
396 	8 , 8, 9,10,11,12,13,14,16,17,19,20,22,22,22,22
397 };
398 
399 
400 /* OPN key frequency number -> key code follow table */
401 /* fnum higher 4bit -> keycode lower 2bit */
402 static const UINT8 opn_fktable[16] = {0,0,0,0,0,0,0,1,2,3,3,3,3,3,3,3};
403 
404 
405 /* 8 LFO speed parameters */
406 /* each value represents number of samples that one LFO level will last for */
407 static const UINT32 lfo_samples_per_step[8] = {108, 77, 71, 67, 62, 44, 8, 5};
408 
409 
410 
411 /*There are 4 different LFO AM depths available, they are:
412   0 dB,	1.4 dB,	5.9 dB, 11.8 dB
413   Here is how it is generated (in EG steps):
414 
415   11.8 dB =	0, 2, 4, 6, 8, 10,12,14,16...126,126,124,122,120,118,....4,2,0
416    5.9 dB =	0, 1, 2, 3, 4, 5, 6, 7, 8....63, 63, 62, 61, 60, 59,.....2,1,0
417    1.4 dB =	0, 0, 0, 0, 1, 1, 1, 1, 2,...15, 15, 15, 15, 14, 14,.....0,0,0
418 
419   (1.4 dB is loosing precision as you can see)
420 
421   It's implemented as generator from 0..126 with step 2 then a shift
422   right N times, where N is:
423 	8 for 0 dB
424 	3 for 1.4 dB
425 	1 for 5.9 dB
426 	0 for 11.8 dB
427 */
428 static const UINT8 lfo_ams_depth_shift[4] = {8, 3, 1, 0};
429 
430 
431 
432 /*There are 8 different LFO PM depths available, they are:
433   0, 3.4, 6.7, 10, 14, 20, 40, 80 (cents)
434 
435   Modulation level at each depth depends on F-NUMBER bits: 4,5,6,7,8,9,10
436   (bits 8,9,10 = FNUM MSB from OCT/FNUM register)
437 
438   Here we store only first quarter (positive one) of full waveform.
439   Full table (lfo_pm_table) containing all 128 waveforms is build
440   at run (init) time.
441 
442   One value in table below represents 4 (four) basic LFO steps
443   (1 PM step = 4 AM steps).
444 
445   For example:
446    at LFO SPEED=0 (which is 108 samples per basic LFO step)
447    one value from "lfo_pm_output" table lasts for 432 consecutive
448    samples (4*108=432) and one full LFO waveform cycle lasts for 13824
449    samples (32*432=13824; 32 because we store only a quarter of whole
450             waveform in the table below)
451 */
452 static const UINT8 lfo_pm_output[7*8][8]={ /* 7 bits meaningful (of F-NUMBER), 8 LFO output levels per one depth (out of 32), 8 LFO depths */
453 /* FNUM BIT 4: 000 0001xxxx */
454 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
455 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
456 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   0,   0},
457 /* DEPTH 3 */ {0,   0,   0,   0,   0,   0,   0,   0},
458 /* DEPTH 4 */ {0,   0,   0,   0,   0,   0,   0,   0},
459 /* DEPTH 5 */ {0,   0,   0,   0,   0,   0,   0,   0},
460 /* DEPTH 6 */ {0,   0,   0,   0,   0,   0,   0,   0},
461 /* DEPTH 7 */ {0,   0,   0,   0,   1,   1,   1,   1},
462 
463 /* FNUM BIT 5: 000 0010xxxx */
464 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
465 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
466 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   0,   0},
467 /* DEPTH 3 */ {0,   0,   0,   0,   0,   0,   0,   0},
468 /* DEPTH 4 */ {0,   0,   0,   0,   0,   0,   0,   0},
469 /* DEPTH 5 */ {0,   0,   0,   0,   0,   0,   0,   0},
470 /* DEPTH 6 */ {0,   0,   0,   0,   1,   1,   1,   1},
471 /* DEPTH 7 */ {0,   0,   1,   1,   2,   2,   2,   3},
472 
473 /* FNUM BIT 6: 000 0100xxxx */
474 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
475 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
476 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   0,   0},
477 /* DEPTH 3 */ {0,   0,   0,   0,   0,   0,   0,   0},
478 /* DEPTH 4 */ {0,   0,   0,   0,   0,   0,   0,   1},
479 /* DEPTH 5 */ {0,   0,   0,   0,   1,   1,   1,   1},
480 /* DEPTH 6 */ {0,   0,   1,   1,   2,   2,   2,   3},
481 /* DEPTH 7 */ {0,   0,   2,   3,   4,   4,   5,   6},
482 
483 /* FNUM BIT 7: 000 1000xxxx */
484 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
485 /* DEPTH 1 */ {0,   0,   0,   0,   0,   0,   0,   0},
486 /* DEPTH 2 */ {0,   0,   0,   0,   0,   0,   1,   1},
487 /* DEPTH 3 */ {0,   0,   0,   0,   1,   1,   1,   1},
488 /* DEPTH 4 */ {0,   0,   0,   1,   1,   1,   1,   2},
489 /* DEPTH 5 */ {0,   0,   1,   1,   2,   2,   2,   3},
490 /* DEPTH 6 */ {0,   0,   2,   3,   4,   4,   5,   6},
491 /* DEPTH 7 */ {0,   0,   4,   6,   8,   8, 0xa, 0xc},
492 
493 /* FNUM BIT 8: 001 0000xxxx */
494 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
495 /* DEPTH 1 */ {0,   0,   0,   0,   1,   1,   1,   1},
496 /* DEPTH 2 */ {0,   0,   0,   1,   1,   1,   2,   2},
497 /* DEPTH 3 */ {0,   0,   1,   1,   2,   2,   3,   3},
498 /* DEPTH 4 */ {0,   0,   1,   2,   2,   2,   3,   4},
499 /* DEPTH 5 */ {0,   0,   2,   3,   4,   4,   5,   6},
500 /* DEPTH 6 */ {0,   0,   4,   6,   8,   8, 0xa, 0xc},
501 /* DEPTH 7 */ {0,   0,   8, 0xc,0x10,0x10,0x14,0x18},
502 
503 /* FNUM BIT 9: 010 0000xxxx */
504 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
505 /* DEPTH 1 */ {0,   0,   0,   0,   2,   2,   2,   2},
506 /* DEPTH 2 */ {0,   0,   0,   2,   2,   2,   4,   4},
507 /* DEPTH 3 */ {0,   0,   2,   2,   4,   4,   6,   6},
508 /* DEPTH 4 */ {0,   0,   2,   4,   4,   4,   6,   8},
509 /* DEPTH 5 */ {0,   0,   4,   6,   8,   8, 0xa, 0xc},
510 /* DEPTH 6 */ {0,   0,   8, 0xc,0x10,0x10,0x14,0x18},
511 /* DEPTH 7 */ {0,   0,0x10,0x18,0x20,0x20,0x28,0x30},
512 
513 /* FNUM BIT10: 100 0000xxxx */
514 /* DEPTH 0 */ {0,   0,   0,   0,   0,   0,   0,   0},
515 /* DEPTH 1 */ {0,   0,   0,   0,   4,   4,   4,   4},
516 /* DEPTH 2 */ {0,   0,   0,   4,   4,   4,   8,   8},
517 /* DEPTH 3 */ {0,   0,   4,   4,   8,   8, 0xc, 0xc},
518 /* DEPTH 4 */ {0,   0,   4,   8,   8,   8, 0xc,0x10},
519 /* DEPTH 5 */ {0,   0,   8, 0xc,0x10,0x10,0x14,0x18},
520 /* DEPTH 6 */ {0,   0,0x10,0x18,0x20,0x20,0x28,0x30},
521 /* DEPTH 7 */ {0,   0,0x20,0x30,0x40,0x40,0x50,0x60},
522 
523 };
524 
525 /* all 128 LFO PM waveforms */
526 static INT32 lfo_pm_table[128*8*32]; /* 128 combinations of 7 bits meaningful (of F-NUMBER), 8 LFO depths, 32 LFO output levels per one depth */
527 
528 
529 
530 
531 
532 /* register number to channel number , slot offset */
533 #define OPN_CHAN(N) (N&3)
534 #define OPN_SLOT(N) ((N>>2)&3)
535 
536 /* slot number */
537 #define SLOT1 0
538 #define SLOT2 2
539 #define SLOT3 1
540 #define SLOT4 3
541 
542 /* bit0 = Right enable , bit1 = Left enable */
543 #define OUTD_RIGHT  1
544 #define OUTD_LEFT   2
545 #define OUTD_CENTER 3
546 
547 
548 /* save output as raw 16-bit sample */
549 /* #define SAVE_SAMPLE */
550 
551 #ifdef SAVE_SAMPLE
552 static FILE *sample[1];
553 	#if 1	/*save to MONO file */
554 		#define SAVE_ALL_CHANNELS \
555 		{	signed int pom = lt; \
556 			fputc((unsigned short)pom&0xff,sample[0]); \
557 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
558 		}
559 	#else	/*save to STEREO file */
560 		#define SAVE_ALL_CHANNELS \
561 		{	signed int pom = lt; \
562 			fputc((unsigned short)pom&0xff,sample[0]); \
563 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
564 			pom = rt; \
565 			fputc((unsigned short)pom&0xff,sample[0]); \
566 			fputc(((unsigned short)pom>>8)&0xff,sample[0]); \
567 		}
568 	#endif
569 #endif
570 
571 
572 /* struct describing a single operator (SLOT) */
573 typedef struct
574 {
575 	INT32	*DT;		/* detune          :dt_tab[DT] */
576 	UINT8	KSR;		/* key scale rate  :3-KSR */
577 	UINT32	ar;			/* attack rate  */
578 	UINT32	d1r;		/* decay rate   */
579 	UINT32	d2r;		/* sustain rate */
580 	UINT32	rr;			/* release rate */
581 	UINT8	ksr;		/* key scale rate  :kcode>>(3-KSR) */
582 	UINT32	mul;		/* multiple        :ML_TABLE[ML] */
583 
584 	/* Phase Generator */
585 	UINT32	phase;		/* phase counter */
586 	INT32	Incr;		/* phase step */
587 
588 	/* Envelope Generator */
589 	UINT8	state;		/* phase type */
590 	UINT32	tl;			/* total level: TL << 3	*/
591 	INT32	volume;		/* envelope counter	*/
592 	UINT32	sl;			/* sustain level:sl_table[SL] */
593 	UINT32	vol_out;	/* current output from EG circuit (without AM from LFO) */
594 
595 	UINT8	eg_sh_ar;	/*  (attack state) */
596 	UINT8	eg_sel_ar;	/*  (attack state) */
597 	UINT8	eg_sh_d1r;	/*  (decay state) */
598 	UINT8	eg_sel_d1r;	/*  (decay state) */
599 	UINT8	eg_sh_d2r;	/*  (sustain state) */
600 	UINT8	eg_sel_d2r;	/*  (sustain state) */
601 	UINT8	eg_sh_rr;	/*  (release state) */
602 	UINT8	eg_sel_rr;	/*  (release state) */
603 
604 	UINT8	ssg;		/* SSG-EG waveform */
605 	UINT8	ssgn;		/* SSG-EG negated output */
606 
607 	UINT32	key;		/* 0=last key was KEY OFF, 1=KEY ON	*/
608 
609 	/* LFO */
610 	UINT32	AMmask;		/* AM enable flag */
611 
612 } FM_SLOT;
613 
614 typedef struct
615 {
616 	FM_SLOT	SLOT[4];	/* four SLOTs (operators) */
617 
618 	UINT8	ALGO;		/* algorithm */
619 	UINT8	FB;			/* feedback shift */
620 	INT32	op1_out[2];	/* op1 output for feedback */
621 
622 	INT32	*connect1;	/* SLOT1 output	pointer */
623 	INT32	*connect3;	/* SLOT3 output	pointer */
624 	INT32	*connect2;	/* SLOT2 output	pointer */
625 	INT32	*connect4;	/* SLOT4 output	pointer */
626 
627 	INT32	*mem_connect;/* where to put the delayed sample (MEM) */
628 	INT32	mem_value;	/* delayed sample (MEM) value */
629 
630 	INT32	pms;		/* channel PMS */
631 	UINT8	ams;		/* channel AMS */
632 
633 	UINT32	fc;			/* fnum,blk:adjusted to sample rate	*/
634 	UINT8	kcode;		/* key code:						*/
635 	UINT32	block_fnum;	/* current blk/fnum value for this slot (can be different betweeen slots of one channel in 3slot mode) */
636 } FM_CH;
637 
638 
639 typedef struct
640 {
641 	UINT8	index;		/* this chip index (number of chip)	*/
642 	int		clock;		/* master clock  (Hz)	*/
643 	int		rate;		/* sampling rate (Hz)	*/
644 	double	freqbase;	/* frequency base		*/
645 	double	TimerBase;	/* Timer base time		*/
646 #if FM_BUSY_FLAG_SUPPORT
647 	double	BusyExpire;	/* ExpireTime of Busy clear */
648 #endif
649 	UINT8	address;	/* address register		*/
650 	UINT8	irq;		/* interrupt level		*/
651 	UINT8	irqmask;	/* irq mask				*/
652 	UINT8	status;		/* status flag			*/
653 	UINT32	mode;		/* mode  CSM / 3SLOT	*/
654 	UINT8	prescaler_sel;/* prescaler selector	*/
655 	UINT8	fn_h;		/* freq latch			*/
656 	int		TA;			/* timer a				*/
657 	int		TAC;		/* timer a counter		*/
658 	UINT8	TB;			/* timer b				*/
659 	int		TBC;		/* timer b counter		*/
660 	/* local time tables */
661 	INT32	dt_tab[8][32];/* DeTune table		*/
662 	/* Extention Timer and IRQ handler */
663 	FM_TIMERHANDLER	Timer_Handler;
664 	FM_IRQHANDLER	IRQ_Handler;
665 } FM_ST;
666 
667 
668 
669 /***********************************************************/
670 /* OPN unit                                                */
671 /***********************************************************/
672 
673 /* OPN 3slot struct */
674 typedef struct
675 {
676 	UINT32  fc[3];			/* fnum3,blk3: calculated */
677 	UINT8	fn_h;			/* freq3 latch */
678 	UINT8	kcode[3];		/* key code */
679 	UINT32	block_fnum[3];	/* current fnum value for this slot (can be different betweeen slots of one channel in 3slot mode) */
680 } FM_3SLOT;
681 
682 /* OPN/A/B common state */
683 typedef struct
684 {
685 	UINT8	type;			/* chip type */
686 	FM_ST	ST;				/* general state */
687 	FM_3SLOT SL3;			/* 3 slot mode state */
688 	FM_CH	*P_CH;			/* pointer of CH */
689 	unsigned int pan[6*2];	/* fm channels output masks (0xffffffff = enable) */
690 
691 	UINT32	eg_cnt;			/* global envelope generator counter */
692 	UINT32	eg_timer;		/* global envelope generator counter works at frequency = chipclock/64/3 */
693 	UINT32	eg_timer_add;	/* step of eg_timer */
694 	UINT32	eg_timer_overflow;/* envelope generator timer overlfows every 3 samples (on real chip) */
695 
696 
697 	/* there are 2048 FNUMs that can be generated using FNUM/BLK registers
698 		but LFO works with one more bit of a precision so we really need 4096 elements */
699 
700 	UINT32	fn_table[4096];	/* fnumber->increment counter */
701 	UINT32 fn_max;
702 
703 	/* LFO */
704 	UINT32	lfo_cnt;
705 	UINT32	lfo_inc;
706 
707 	UINT32	lfo_freq[8];	/* LFO FREQ table */
708 } FM_OPN;
709 
710 
711 
712 /* current chip state */
713 static void		*cur_chip = 0;	/* pointer of current chip struct */
714 static FM_ST	*State;			/* basic status */
715 static FM_CH	*cch[8];		/* pointer of FM channels */
716 
717 
718 static INT32	m2,c1,c2;		/* Phase Modulation input for operators 2,3,4 */
719 static INT32	mem;			/* one sample delay memory */
720 
721 static INT32	out_fm[8];		/* outputs of working channels */
722 
723 #if (BUILD_YM2608||BUILD_YM2610||BUILD_YM2610B)
724 static INT32	out_adpcm[4];	/* channel output NONE,LEFT,RIGHT or CENTER for YM2608/YM2610 ADPCM */
725 static INT32	out_delta[4];	/* channel output NONE,LEFT,RIGHT or CENTER for YM2608/YM2610 DELTAT*/
726 #endif
727 
728 static UINT32	LFO_AM;			/* runtime LFO calculations helper */
729 static INT32	LFO_PM;			/* runtime LFO calculations helper */
730 
731 /* log output level */
732 #define LOG_ERR  3      /* ERROR       */
733 #define LOG_WAR  2      /* WARNING     */
734 #define LOG_INF  1      /* INFORMATION */
735 #define LOG_LEVEL LOG_INF
736 
737 #ifndef __RAINE__
738 #define LOG(n,x) if( (n)>=LOG_LEVEL ) logerror x
739 #endif
740 
741 /* limitter */
742 #define Limit(val, max,min) { \
743 	if ( val > max )      val = max; \
744 	else if ( val < min ) val = min; \
745 }
746 
747 
748 /* status set and IRQ handling */
FM_STATUS_SET(FM_ST * ST,int flag)749 INLINE void FM_STATUS_SET(FM_ST *ST,int flag)
750 {
751 	/* set status flag */
752 	ST->status |= flag;
753 	if ( !(ST->irq) && (ST->status & ST->irqmask) )
754 	{
755 		ST->irq = 1;
756 		/* callback user interrupt handler (IRQ is OFF to ON) */
757 		if(ST->IRQ_Handler) (ST->IRQ_Handler)(ST->index,1);
758 	}
759 }
760 
761 /* status reset and IRQ handling */
FM_STATUS_RESET(FM_ST * ST,int flag)762 INLINE void FM_STATUS_RESET(FM_ST *ST,int flag)
763 {
764 	/* reset status flag */
765 	ST->status &=~flag;
766 	if ( (ST->irq) && !(ST->status & ST->irqmask) )
767 	{
768 		ST->irq = 0;
769 		/* callback user interrupt handler (IRQ is ON to OFF) */
770 		if(ST->IRQ_Handler) (ST->IRQ_Handler)(ST->index,0);
771 	}
772 }
773 
774 /* IRQ mask set */
FM_IRQMASK_SET(FM_ST * ST,int flag)775 INLINE void FM_IRQMASK_SET(FM_ST *ST,int flag)
776 {
777 	ST->irqmask = flag;
778 	/* IRQ handling check */
779 	FM_STATUS_SET(ST,0);
780 	FM_STATUS_RESET(ST,0);
781 }
782 
783 /* OPN Mode Register Write */
set_timers(FM_ST * ST,int n,int v)784 INLINE void set_timers( FM_ST *ST, int n, int v )
785 {
786 	/* b7 = CSM MODE */
787 	/* b6 = 3 slot mode */
788 	/* b5 = reset b */
789 	/* b4 = reset a */
790 	/* b3 = timer enable b */
791 	/* b2 = timer enable a */
792 	/* b1 = load b */
793 	/* b0 = load a */
794 	ST->mode = v;
795 
796 	/* reset Timer b flag */
797 	if( v & 0x20 )
798 		FM_STATUS_RESET(ST,0x02);
799 	/* reset Timer a flag */
800 	if( v & 0x10 )
801 		FM_STATUS_RESET(ST,0x01);
802 	/* load b */
803 	if( v & 0x02 )
804 	{
805 		if( ST->TBC == 0 )
806 		{
807 			ST->TBC = ( 256-ST->TB)<<4;
808 			/* External timer handler */
809 			if (ST->Timer_Handler) (ST->Timer_Handler)(n,1,ST->TBC,ST->TimerBase);
810 		}
811 	}
812 	else
813 	{	/* stop timer b */
814 		if( ST->TBC != 0 )
815 		{
816 			ST->TBC = 0;
817 			if (ST->Timer_Handler) (ST->Timer_Handler)(n,1,0,ST->TimerBase);
818 		}
819 	}
820 	/* load a */
821 	if( v & 0x01 )
822 	{
823 		if( ST->TAC == 0 )
824 		{
825 			ST->TAC = (1024-ST->TA);
826 			/* External timer handler */
827 			if (ST->Timer_Handler) (ST->Timer_Handler)(n,0,ST->TAC,ST->TimerBase);
828 		}
829 	}
830 	else
831 	{	/* stop timer a */
832 		if( ST->TAC != 0 )
833 		{
834 			ST->TAC = 0;
835 			if (ST->Timer_Handler) (ST->Timer_Handler)(n,0,0,ST->TimerBase);
836 		}
837 	}
838 }
839 
840 
841 /* Timer A Overflow */
TimerAOver(FM_ST * ST)842 INLINE void TimerAOver(FM_ST *ST)
843 {
844 	/* set status (if enabled) */
845 	if(ST->mode & 0x04) FM_STATUS_SET(ST,0x01);
846 	/* clear or reload the counter */
847 	ST->TAC = (1024-ST->TA);
848 	if (ST->Timer_Handler) (ST->Timer_Handler)(ST->index,0,ST->TAC,ST->TimerBase);
849 }
850 /* Timer B Overflow */
TimerBOver(FM_ST * ST)851 INLINE void TimerBOver(FM_ST *ST)
852 {
853 	/* set status (if enabled) */
854 	if(ST->mode & 0x08) FM_STATUS_SET(ST,0x02);
855 	/* clear or reload the counter */
856 	ST->TBC = ( 256-ST->TB)<<4;
857 	if (ST->Timer_Handler) (ST->Timer_Handler)(ST->index,1,ST->TBC,ST->TimerBase);
858 }
859 
860 
861 #if FM_INTERNAL_TIMER
862 /* ----- internal timer mode , update timer */
863 
864 /* ---------- calculate timer A ---------- */
865 	#define INTERNAL_TIMER_A(ST,CSM_CH)					\
866 	{													\
867 		if( ST->TAC &&  (ST->Timer_Handler==0) )		\
868 			if( (ST->TAC -= (int)(ST->freqbase*4096)) <= 0 )	\
869 			{											\
870 				TimerAOver( ST );						\
871 				/* CSM mode total level latch and auto key on */	\
872 				if( ST->mode & 0x80 )					\
873 					CSMKeyControll( CSM_CH );			\
874 			}											\
875 	}
876 /* ---------- calculate timer B ---------- */
877 	#define INTERNAL_TIMER_B(ST,step)						\
878 	{														\
879 		if( ST->TBC && (ST->Timer_Handler==0) )				\
880 			if( (ST->TBC -= (int)(ST->freqbase*4096*step)) <= 0 )	\
881 				TimerBOver( ST );							\
882 	}
883 #else /* FM_INTERNAL_TIMER */
884 /* external timer mode */
885 #define INTERNAL_TIMER_A(ST,CSM_CH)
886 #define INTERNAL_TIMER_B(ST,step)
887 #endif /* FM_INTERNAL_TIMER */
888 
889 
890 
891 #if FM_BUSY_FLAG_SUPPORT
FM_STATUS_FLAG(FM_ST * ST)892 INLINE UINT8 FM_STATUS_FLAG(FM_ST *ST)
893 {
894 	if( ST->BusyExpire )
895 	{
896 		if( (ST->BusyExpire - FM_GET_TIME_NOW()) > 0)
897 			return ST->status | 0x80;	/* with busy */
898 		/* expire */
899 		ST->BusyExpire = 0;
900 	}
901 	return ST->status;
902 }
FM_BUSY_SET(FM_ST * ST,int busyclock)903 INLINE void FM_BUSY_SET(FM_ST *ST,int busyclock )
904 {
905 	ST->BusyExpire = FM_GET_TIME_NOW() + (ST->TimerBase * busyclock);
906 }
907 #define FM_BUSY_CLEAR(ST) ((ST)->BusyExpire = 0)
908 #else
909 #define FM_STATUS_FLAG(ST) ((ST)->status)
910 #define FM_BUSY_SET(ST,bclock) {}
911 #define FM_BUSY_CLEAR(ST) {}
912 #endif
913 
914 
915 
916 
FM_KEYON(UINT8 type,FM_CH * CH,int s)917 INLINE void FM_KEYON(UINT8 type, FM_CH *CH , int s )
918 {
919 	FM_SLOT *SLOT = &CH->SLOT[s];
920 	if( !SLOT->key )
921 	{
922 		SLOT->key = 1;
923 		SLOT->phase = 0;		/* restart Phase Generator */
924 		SLOT->ssgn = (SLOT->ssg & 0x04) >> 1;
925 
926 		if ((type == TYPE_YM2612) || (type == TYPE_YM2608))
927 		{
928 		        if( (SLOT->ar + SLOT->ksr) < 32+62 )
929 		        {
930 			        SLOT->state = EG_ATT;    /* phase -> Attack */
931 			}
932 			else
933 			{
934 			        /* directly switch to Decay */
935 			        SLOT->volume = MIN_ATT_INDEX;
936 			        SLOT->state = EG_DEC;
937 			}
938 		}
939 		else
940 		{
941 			SLOT->state = EG_ATT;
942 		}
943 	}
944 }
945 
FM_KEYOFF(FM_CH * CH,int s)946 INLINE void FM_KEYOFF(FM_CH *CH , int s )
947 {
948 	FM_SLOT *SLOT = &CH->SLOT[s];
949 	if( SLOT->key )
950 	{
951 		SLOT->key = 0;
952 		if (SLOT->state>EG_REL)
953 			SLOT->state = EG_REL;/* phase -> Release */
954 	}
955 }
956 
957 /* set algorithm connection */
setup_connection(FM_CH * CH,int ch)958 static void setup_connection( FM_CH *CH, int ch )
959 {
960 	INT32 *carrier = &out_fm[ch];
961 
962 	INT32 **om1 = &CH->connect1;
963 	INT32 **om2 = &CH->connect3;
964 	INT32 **oc1 = &CH->connect2;
965 
966 	INT32 **memc = &CH->mem_connect;
967 
968 	switch( CH->ALGO ){
969 	case 0:
970 		/* M1---C1---MEM---M2---C2---OUT */
971 		*om1 = &c1;
972 		*oc1 = &mem;
973 		*om2 = &c2;
974 		*memc= &m2;
975 		break;
976 	case 1:
977 		/* M1------+-MEM---M2---C2---OUT */
978 		/*      C1-+                     */
979 		*om1 = &mem;
980 		*oc1 = &mem;
981 		*om2 = &c2;
982 		*memc= &m2;
983 		break;
984 	case 2:
985 		/* M1-----------------+-C2---OUT */
986 		/*      C1---MEM---M2-+          */
987 		*om1 = &c2;
988 		*oc1 = &mem;
989 		*om2 = &c2;
990 		*memc= &m2;
991 		break;
992 	case 3:
993 		/* M1---C1---MEM------+-C2---OUT */
994 		/*                 M2-+          */
995 		*om1 = &c1;
996 		*oc1 = &mem;
997 		*om2 = &c2;
998 		*memc= &c2;
999 		break;
1000 	case 4:
1001 		/* M1---C1-+-OUT */
1002 		/* M2---C2-+     */
1003 		/* MEM: not used */
1004 		*om1 = &c1;
1005 		*oc1 = carrier;
1006 		*om2 = &c2;
1007 		*memc= &mem;	/* store it anywhere where it will not be used */
1008 		break;
1009 	case 5:
1010 		/*    +----C1----+     */
1011 		/* M1-+-MEM---M2-+-OUT */
1012 		/*    +----C2----+     */
1013 		*om1 = 0;	/* special mark */
1014 		*oc1 = carrier;
1015 		*om2 = carrier;
1016 		*memc= &m2;
1017 		break;
1018 	case 6:
1019 		/* M1---C1-+     */
1020 		/*      M2-+-OUT */
1021 		/*      C2-+     */
1022 		/* MEM: not used */
1023 		*om1 = &c1;
1024 		*oc1 = carrier;
1025 		*om2 = carrier;
1026 		*memc= &mem;	/* store it anywhere where it will not be used */
1027 		break;
1028 	case 7:
1029 		/* M1-+     */
1030 		/* C1-+-OUT */
1031 		/* M2-+     */
1032 		/* C2-+     */
1033 		/* MEM: not used*/
1034 		*om1 = carrier;
1035 		*oc1 = carrier;
1036 		*om2 = carrier;
1037 		*memc= &mem;	/* store it anywhere where it will not be used */
1038 		break;
1039 	}
1040 
1041 	CH->connect4 = carrier;
1042 }
1043 
1044 /* set detune & multiple */
set_det_mul(FM_ST * ST,FM_CH * CH,FM_SLOT * SLOT,int v)1045 INLINE void set_det_mul(FM_ST *ST,FM_CH *CH,FM_SLOT *SLOT,int v)
1046 {
1047 	SLOT->mul = (v&0x0f)? (v&0x0f)*2 : 1;
1048 	SLOT->DT  = ST->dt_tab[(v>>4)&7];
1049 	CH->SLOT[SLOT1].Incr=-1;
1050 }
1051 
1052 /* set total level */
set_tl(FM_CH * CH,FM_SLOT * SLOT,int v)1053 INLINE void set_tl(FM_CH *CH,FM_SLOT *SLOT , int v)
1054 {
1055 	SLOT->tl = (v&0x7f)<<(ENV_BITS-7); /* 7bit TL */
1056 }
1057 
1058 /* set attack rate & key scale  */
set_ar_ksr(UINT8 type,FM_CH * CH,FM_SLOT * SLOT,int v)1059 INLINE void set_ar_ksr(UINT8 type, FM_CH *CH,FM_SLOT *SLOT,int v)
1060 {
1061 	UINT8 old_KSR = SLOT->KSR;
1062 
1063 	SLOT->ar = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1064 
1065 	SLOT->KSR = 3-(v>>6);
1066 	if (SLOT->KSR != old_KSR)
1067 	{
1068 		CH->SLOT[SLOT1].Incr=-1;
1069 	}
1070 
1071 	/* refresh Attack rate */
1072 	if ((SLOT->ar + SLOT->ksr) < 32+62)
1073 	{
1074 		SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar  + SLOT->ksr ];
1075 		if ((type == TYPE_YM2612) || (type == TYPE_YM2608))
1076 		{
1077 			SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar  + SLOT->ksr ];
1078 			SLOT->eg_sel_ar = eg_rate_select2612[SLOT->ar  + SLOT->ksr ];
1079 		}
1080 		else
1081 		{
1082 			SLOT->eg_sel_ar = eg_rate_select[SLOT->ar  + SLOT->ksr ];
1083 		}
1084 	}
1085 	else
1086 	{
1087 		SLOT->eg_sh_ar  = 0;
1088 		SLOT->eg_sel_ar = 17*RATE_STEPS;
1089 	}
1090 }
1091 
1092 /* set decay rate */
set_dr(UINT8 type,FM_SLOT * SLOT,int v)1093 INLINE void set_dr(UINT8 type, FM_SLOT *SLOT,int v)
1094 {
1095 	SLOT->d1r = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1096 
1097 	SLOT->eg_sh_d1r = eg_rate_shift [SLOT->d1r + SLOT->ksr];
1098 	if ((type == TYPE_YM2612) || (type == TYPE_YM2608))
1099 	{
1100 		SLOT->eg_sel_d1r= eg_rate_select2612[SLOT->d1r + SLOT->ksr];
1101 	}
1102 	else
1103 	{
1104 		SLOT->eg_sel_d1r= eg_rate_select[SLOT->d1r + SLOT->ksr];
1105 	}
1106 
1107 }
1108 
1109 /* set sustain rate */
set_sr(UINT8 type,FM_SLOT * SLOT,int v)1110 INLINE void set_sr(UINT8 type, FM_SLOT *SLOT,int v)
1111 {
1112 	SLOT->d2r = (v&0x1f) ? 32 + ((v&0x1f)<<1) : 0;
1113 
1114 	SLOT->eg_sh_d2r = eg_rate_shift [SLOT->d2r + SLOT->ksr];
1115 	if ((type == TYPE_YM2612) || (type == TYPE_YM2608))
1116 	{
1117 		SLOT->eg_sel_d2r= eg_rate_select2612[SLOT->d2r + SLOT->ksr];
1118 	}
1119 	else
1120 	{
1121 		SLOT->eg_sel_d2r= eg_rate_select[SLOT->d2r + SLOT->ksr];
1122 	}
1123 }
1124 
1125 /* set release rate */
set_sl_rr(UINT8 type,FM_SLOT * SLOT,int v)1126 INLINE void set_sl_rr(UINT8 type, FM_SLOT *SLOT,int v)
1127 {
1128 	SLOT->sl = sl_table[ v>>4 ];
1129 
1130 	SLOT->rr  = 34 + ((v&0x0f)<<2);
1131 
1132 	SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr  + SLOT->ksr];
1133 	if ((type == TYPE_YM2612) || (type == TYPE_YM2608))
1134 	{
1135 		SLOT->eg_sel_rr = eg_rate_select2612[SLOT->rr  + SLOT->ksr];
1136 	}
1137 	else
1138 	{
1139 		SLOT->eg_sel_rr = eg_rate_select[SLOT->rr  + SLOT->ksr];
1140 	}
1141 }
1142 
1143 
1144 
op_calc(UINT32 phase,unsigned int env,signed int pm)1145 INLINE signed int op_calc(UINT32 phase, unsigned int env, signed int pm)
1146 {
1147 	UINT32 p;
1148 
1149 	p = (env<<3) + sin_tab[ ( ((signed int)((phase & ~FREQ_MASK) + (pm<<15))) >> FREQ_SH ) & SIN_MASK ];
1150 
1151 	if (p >= TL_TAB_LEN)
1152 		return 0;
1153 	return tl_tab[p];
1154 }
1155 
op_calc1(UINT32 phase,unsigned int env,signed int pm)1156 INLINE signed int op_calc1(UINT32 phase, unsigned int env, signed int pm)
1157 {
1158 	UINT32 p;
1159 
1160 	p = (env<<3) + sin_tab[ ( ((signed int)((phase & ~FREQ_MASK) + pm      )) >> FREQ_SH ) & SIN_MASK ];
1161 
1162 	if (p >= TL_TAB_LEN)
1163 		return 0;
1164 	return tl_tab[p];
1165 }
1166 
1167 /* advance LFO to next sample */
advance_lfo(FM_OPN * OPN)1168 INLINE void advance_lfo(FM_OPN *OPN)
1169 {
1170 	UINT8 pos;
1171 
1172 	if (OPN->lfo_inc)	/* LFO enabled ? */
1173 	{
1174 		OPN->lfo_cnt += OPN->lfo_inc;
1175 
1176 		pos = (OPN->lfo_cnt >> LFO_SH) & 127;
1177 
1178 
1179 		/* update AM when LFO output changes */
1180 
1181 		/* actually I can't optimize is this way without rewritting chan_calc()
1182 		to use chip->lfo_am instead of global lfo_am */
1183 		{
1184 
1185 			/* triangle */
1186 			/* AM: 0 to 126 step +2, 126 to 0 step -2 */
1187 			if (pos<64)
1188 				LFO_AM = (pos&63) * 2;
1189 			else
1190 				LFO_AM = 126 - ((pos&63) * 2);
1191 		}
1192 
1193 		/* PM works with 4 times slower clock */
1194 		pos >>= 2;
1195 		/* update PM when LFO output changes */
1196 		/*if (prev_pos != pos)*/ /* can't use global lfo_pm for this optimization, must be chip->lfo_pm instead*/
1197 		{
1198 			LFO_PM = pos;
1199 		}
1200 
1201 	}
1202 	else
1203 	{
1204 		LFO_AM = 0;
1205 		LFO_PM = 0;
1206 	}
1207 }
1208 
advance_eg_channel(FM_OPN * OPN,FM_SLOT * SLOT)1209 INLINE void advance_eg_channel(FM_OPN *OPN, FM_SLOT *SLOT)
1210 {
1211 	unsigned int out;
1212 	unsigned int swap_flag = 0;
1213 	unsigned int i;
1214 
1215 
1216 	i = 4; /* four operators per channel */
1217 	do
1218 	{
1219 		/* reset SSG-EG swap flag */
1220 		swap_flag = 0;
1221 
1222 		switch(SLOT->state)
1223 		{
1224 		case EG_ATT:		/* attack phase */
1225 			if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_ar)-1) ) )
1226 			{
1227 				SLOT->volume += (~SLOT->volume *
1228                                   (eg_inc[SLOT->eg_sel_ar + ((OPN->eg_cnt>>SLOT->eg_sh_ar)&7)])
1229                                 ) >>4;
1230 
1231 				if (SLOT->volume <= MIN_ATT_INDEX)
1232 				{
1233 					SLOT->volume = MIN_ATT_INDEX;
1234 					SLOT->state = EG_DEC;
1235 				}
1236 			}
1237 		break;
1238 
1239 		case EG_DEC:	/* decay phase */
1240 			if ((OPN->type == TYPE_YM2612) || (OPN->type == TYPE_YM2608))
1241 			{
1242 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d1r)-1) ) )
1243                                 {
1244 					if (SLOT->ssg&0x08)   /* SSG EG type envelope selected */
1245 					{
1246 				       		SLOT->volume += 6 * eg_inc[SLOT->eg_sel_d1r + ((OPN->eg_cnt>>SLOT->eg_sh_d1r)&7)];
1247 					}
1248 					else
1249 					{
1250                                                 SLOT->volume += eg_inc[SLOT->eg_sel_d1r + ((OPN->eg_cnt>>SLOT->eg_sh_d1r)&7)];
1251 					}
1252         			}
1253 
1254         			/* check transition even if no volume update: this fixes the case when SL = MIN_ATT_INDEX */
1255 				if ( SLOT->volume >= (INT32)(SLOT->sl) )
1256 				{
1257 					SLOT->volume = (INT32)(SLOT->sl);
1258 					SLOT->state = EG_SUS;
1259  				}
1260 			}
1261 			else
1262 			{
1263 				if (SLOT->ssg&0x08)	/* SSG EG type envelope selected */
1264 				{
1265 					if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d1r)-1) ) )
1266 					{
1267 						SLOT->volume += 4 * eg_inc[SLOT->eg_sel_d1r + ((OPN->eg_cnt>>SLOT->eg_sh_d1r)&7)];
1268 
1269 						if ( SLOT->volume >= (INT32)(SLOT->sl) )
1270 							SLOT->state = EG_SUS;
1271 					}
1272 				}
1273 				else
1274 				{
1275 					if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d1r)-1) ) )
1276 					{
1277 						SLOT->volume += eg_inc[SLOT->eg_sel_d1r + ((OPN->eg_cnt>>SLOT->eg_sh_d1r)&7)];
1278 
1279 						if ( SLOT->volume >= (INT32)(SLOT->sl) )
1280 							SLOT->state = EG_SUS;
1281 					}
1282 				}
1283 			}
1284 		break;
1285 
1286 		case EG_SUS:	/* sustain phase */
1287 			if (SLOT->ssg&0x08)	/* SSG EG type envelope selected */
1288 			{
1289 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d2r)-1) ) )
1290 				{
1291 					if ((OPN->type == TYPE_YM2612) || (OPN->type == TYPE_YM2608))
1292 					{
1293 						SLOT->volume += 6 * eg_inc[SLOT->eg_sel_d2r + ((OPN->eg_cnt>>SLOT->eg_sh_d2r)&7)];
1294 					}
1295 					else
1296 					{
1297 						SLOT->volume += 4 * eg_inc[SLOT->eg_sel_d2r + ((OPN->eg_cnt>>SLOT->eg_sh_d2r)&7)];
1298 					}
1299 
1300 					if ( SLOT->volume >= ENV_QUIET )
1301 					{
1302 						if ((OPN->type != TYPE_YM2612) && (OPN->type != TYPE_YM2608))
1303 						{
1304 							SLOT->volume = MAX_ATT_INDEX;
1305 						}
1306 
1307 						if (SLOT->ssg&0x01)	/* bit 0 = hold */
1308 						{
1309 							if (SLOT->ssgn&1)	/* have we swapped once ??? */
1310 							{
1311 								/* yes, so do nothing, just hold current level */
1312 							}
1313 							else
1314 								swap_flag = (SLOT->ssg&0x02) | 1 ; /* bit 1 = alternate */
1315 
1316 						}
1317 						else
1318 						{
1319 							/* same as KEY-ON operation */
1320 
1321 							/* restart of the Phase Generator should be here */
1322 							SLOT->phase = 0;
1323 
1324 							if ((OPN->type == TYPE_YM2612) || (OPN->type == TYPE_YM2608))
1325 							{
1326 								if ((SLOT->ar + SLOT->ksr) < 94 /*32+62*/)
1327 								{
1328 									SLOT->state = EG_ATT; /* phase -> Attack */
1329 								}
1330 								else
1331 								{
1332 									/* Attack Rate is maximal: directly switch to Decay (or Substain) */
1333 									SLOT->volume = MIN_ATT_INDEX;
1334 									SLOT->state = (SLOT->sl == MIN_ATT_INDEX) ? EG_SUS : EG_DEC;
1335 								}
1336 							}
1337 							else
1338 							{
1339 								/* phase -> Attack */
1340 								SLOT->volume = 511;
1341 								SLOT->state = EG_ATT;
1342 							}
1343 
1344 							swap_flag = (SLOT->ssg&0x02); /* bit 1 = alternate */
1345 						}
1346 					}
1347 				}
1348 			}
1349 			else
1350 			{
1351 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_d2r)-1) ) )
1352 				{
1353 					SLOT->volume += eg_inc[SLOT->eg_sel_d2r + ((OPN->eg_cnt>>SLOT->eg_sh_d2r)&7)];
1354 
1355 					if ( SLOT->volume >= MAX_ATT_INDEX )
1356 					{
1357 						SLOT->volume = MAX_ATT_INDEX;
1358 						/* do not change SLOT->state (verified on real chip) */
1359 					}
1360 				}
1361 
1362 			}
1363 		break;
1364 
1365 		case EG_REL:	/* release phase */
1366 				if ( !(OPN->eg_cnt & ((1<<SLOT->eg_sh_rr)-1) ) )
1367 				{
1368 					/* SSG-EG affects Release phase also (Nemesis) */
1369 					if ((SLOT->ssg&0x08) && ((OPN->type = TYPE_YM2612) || (OPN->type = TYPE_YM2608)))
1370 					{
1371 						SLOT->volume += 6 * eg_inc[SLOT->eg_sel_rr + ((OPN->eg_cnt>>SLOT->eg_sh_rr)&7)];
1372 					}
1373 					else
1374 					{
1375 						SLOT->volume += eg_inc[SLOT->eg_sel_rr + ((OPN->eg_cnt>>SLOT->eg_sh_rr)&7)];
1376 					}
1377 
1378 					if ( SLOT->volume >= MAX_ATT_INDEX )
1379 					{
1380 						SLOT->volume = MAX_ATT_INDEX;
1381 						SLOT->state = EG_OFF;
1382 					}
1383 				}
1384 		break;
1385 
1386 		}
1387 
1388 		out = ((UINT32)SLOT->volume);
1389 
1390                 /* negate output (changes come from alternate bit, init comes from attack bit) */
1391 		if ((SLOT->ssg&0x08) && (SLOT->ssgn&2) && (SLOT->state > EG_REL))
1392 			out ^= MAX_ATT_INDEX;
1393 
1394 		/* we need to store the result here because we are going to change ssgn
1395 			in next instruction */
1396 		SLOT->vol_out = out + SLOT->tl;
1397 
1398 		/* reverse SLOT inversion flag */
1399 		SLOT->ssgn ^= swap_flag;
1400 
1401 		SLOT++;
1402 		i--;
1403 	}while (i);
1404 
1405 }
1406 
1407 
1408 
1409 #define volume_calc(OP) ((OP)->vol_out + (AM & (OP)->AMmask))
1410 
update_phase_lfo_slot(FM_OPN * OPN,FM_SLOT * SLOT,INT32 pms,UINT32 block_fnum)1411 INLINE void update_phase_lfo_slot(FM_OPN *OPN, FM_SLOT *SLOT, INT32 pms, UINT32 block_fnum)
1412 {
1413 	UINT32 fnum_lfo  = ((block_fnum & 0x7f0) >> 4) * 32 * 8;
1414 	INT32  lfo_fn_table_index_offset = lfo_pm_table[ fnum_lfo + pms + LFO_PM ];
1415 
1416 	if (lfo_fn_table_index_offset)    /* LFO phase modulation active */
1417 	{
1418 		UINT8 blk;
1419 		UINT32 fn;
1420 		int kc, fc;
1421 
1422 		block_fnum = block_fnum*2 + lfo_fn_table_index_offset;
1423 
1424 		blk = (block_fnum&0x7000) >> 12;
1425 		fn  = block_fnum & 0xfff;
1426 
1427 		/* keyscale code */
1428 		kc = (blk<<2) | opn_fktable[fn >> 8];
1429 
1430 		/* phase increment counter */
1431 		fc = (OPN->fn_table[fn]>>(7-blk)) + SLOT->DT[kc];
1432 
1433 		/* detects frequency overflow (credits to Nemesis) */
1434 		if (fc < 0) fc += OPN->fn_max;
1435 
1436 		/* update phase */
1437 		SLOT->phase += (fc * SLOT->mul) >> 1;
1438 	}
1439 	else    /* LFO phase modulation  = zero */
1440 	{
1441 		SLOT->phase += SLOT->Incr;
1442 	}
1443 }
1444 
update_phase_lfo_channel(FM_OPN * OPN,FM_CH * CH)1445 INLINE void update_phase_lfo_channel(FM_OPN *OPN, FM_CH *CH)
1446 {
1447 	UINT32 block_fnum = CH->block_fnum;
1448 
1449 	UINT32 fnum_lfo  = ((block_fnum & 0x7f0) >> 4) * 32 * 8;
1450 	INT32  lfo_fn_table_index_offset = lfo_pm_table[ fnum_lfo + CH->pms + LFO_PM ];
1451 
1452 	if (lfo_fn_table_index_offset)    /* LFO phase modulation active */
1453 	{
1454 	        UINT8 blk;
1455 	        UINT32 fn;
1456 		int kc, fc, finc;
1457 
1458 		block_fnum = block_fnum*2 + lfo_fn_table_index_offset;
1459 
1460 	        blk = (block_fnum&0x7000) >> 12;
1461 	        fn  = block_fnum & 0xfff;
1462 
1463 		/* keyscale code */
1464 	        kc = (blk<<2) | opn_fktable[fn >> 8];
1465 
1466 	        /* phase increment counter */
1467 		fc = (OPN->fn_table[fn]>>(7-blk));
1468 
1469 		/* detects frequency overflow (credits to Nemesis) */
1470 		finc = fc + CH->SLOT[SLOT1].DT[kc];
1471 
1472 		if (finc < 0) finc += OPN->fn_max;
1473 		CH->SLOT[SLOT1].phase += (finc*CH->SLOT[SLOT1].mul) >> 1;
1474 
1475 		finc = fc + CH->SLOT[SLOT2].DT[kc];
1476 		if (finc < 0) finc += OPN->fn_max;
1477 		CH->SLOT[SLOT2].phase += (finc*CH->SLOT[SLOT2].mul) >> 1;
1478 
1479 		finc = fc + CH->SLOT[SLOT3].DT[kc];
1480 		if (finc < 0) finc += OPN->fn_max;
1481 		CH->SLOT[SLOT3].phase += (finc*CH->SLOT[SLOT3].mul) >> 1;
1482 
1483 		finc = fc + CH->SLOT[SLOT4].DT[kc];
1484 		if (finc < 0) finc += OPN->fn_max;
1485 		CH->SLOT[SLOT4].phase += (finc*CH->SLOT[SLOT4].mul) >> 1;
1486 	}
1487 	else    /* LFO phase modulation  = zero */
1488 	{
1489 	        CH->SLOT[SLOT1].phase += CH->SLOT[SLOT1].Incr;
1490 	        CH->SLOT[SLOT2].phase += CH->SLOT[SLOT2].Incr;
1491 	        CH->SLOT[SLOT3].phase += CH->SLOT[SLOT3].Incr;
1492 	        CH->SLOT[SLOT4].phase += CH->SLOT[SLOT4].Incr;
1493 	}
1494 }
1495 
chan_calc(FM_OPN * OPN,FM_CH * CH,int chnum)1496 INLINE void chan_calc(FM_OPN *OPN, FM_CH *CH, int chnum)
1497 {
1498 	unsigned int eg_out;
1499 
1500 	UINT32 AM = LFO_AM >> CH->ams;
1501 
1502 
1503 	m2 = c1 = c2 = mem = 0;
1504 
1505 	*CH->mem_connect = CH->mem_value;	/* restore delayed sample (MEM) value to m2 or c2 */
1506 
1507 	eg_out = volume_calc(&CH->SLOT[SLOT1]);
1508 	{
1509 		INT32 out = CH->op1_out[0] + CH->op1_out[1];
1510 		CH->op1_out[0] = CH->op1_out[1];
1511 
1512 		if( !CH->connect1 ){
1513 			/* algorithm 5  */
1514 			mem = c1 = c2 = CH->op1_out[0];
1515 		}
1516 		else
1517 		{
1518 			/* other algorithms */
1519 			*CH->connect1 += CH->op1_out[0];
1520 		}
1521 
1522 		CH->op1_out[1] = 0;
1523 		if( eg_out < ENV_QUIET )	/* SLOT 1 */
1524 		{
1525 			if (!CH->FB)
1526 				out=0;
1527 
1528 			CH->op1_out[1] = op_calc1(CH->SLOT[SLOT1].phase, eg_out, (out<<CH->FB) );
1529 		}
1530 	}
1531 
1532 	eg_out = volume_calc(&CH->SLOT[SLOT3]);
1533 	if( eg_out < ENV_QUIET )		/* SLOT 3 */
1534 		*CH->connect3 += op_calc(CH->SLOT[SLOT3].phase, eg_out, m2);
1535 
1536 	eg_out = volume_calc(&CH->SLOT[SLOT2]);
1537 	if( eg_out < ENV_QUIET )		/* SLOT 2 */
1538 		*CH->connect2 += op_calc(CH->SLOT[SLOT2].phase, eg_out, c1);
1539 
1540 	eg_out = volume_calc(&CH->SLOT[SLOT4]);
1541 	if( eg_out < ENV_QUIET )		/* SLOT 4 */
1542 		*CH->connect4 += op_calc(CH->SLOT[SLOT4].phase, eg_out, c2);
1543 
1544 
1545 	/* store current MEM */
1546 	CH->mem_value = mem;
1547 
1548 	/* update phase counters AFTER output calculations */
1549 	if(CH->pms)
1550 	{
1551 		/* add support for 3 slot mode */
1552 		if ((OPN->ST.mode & 0xC0) && (chnum == 2))
1553 		{
1554 		        update_phase_lfo_slot(OPN, &CH->SLOT[SLOT1], CH->pms, OPN->SL3.block_fnum[1]);
1555 		        update_phase_lfo_slot(OPN, &CH->SLOT[SLOT2], CH->pms, OPN->SL3.block_fnum[2]);
1556 		        update_phase_lfo_slot(OPN, &CH->SLOT[SLOT3], CH->pms, OPN->SL3.block_fnum[0]);
1557 		        update_phase_lfo_slot(OPN, &CH->SLOT[SLOT4], CH->pms, CH->block_fnum);
1558 		}
1559 		else update_phase_lfo_channel(OPN, CH);
1560 	}
1561 	else	/* no LFO phase modulation */
1562 	{
1563 		CH->SLOT[SLOT1].phase += CH->SLOT[SLOT1].Incr;
1564 		CH->SLOT[SLOT2].phase += CH->SLOT[SLOT2].Incr;
1565 		CH->SLOT[SLOT3].phase += CH->SLOT[SLOT3].Incr;
1566 		CH->SLOT[SLOT4].phase += CH->SLOT[SLOT4].Incr;
1567 	}
1568 }
1569 
1570 /* update phase increment and envelope generator */
refresh_fc_eg_slot(FM_OPN * OPN,FM_SLOT * SLOT,int fc,int kc)1571 INLINE void refresh_fc_eg_slot(FM_OPN *OPN, FM_SLOT *SLOT , int fc , int kc )
1572 {
1573 	int ksr = kc >> SLOT->KSR;
1574 
1575 	fc += SLOT->DT[kc];
1576 
1577 	/* detects frequency overflow (credits to Nemesis) */
1578 	if (fc < 0) fc += OPN->fn_max;
1579 
1580 	/* (frequency) phase increment counter */
1581 	SLOT->Incr = (fc * SLOT->mul) >> 1;
1582 
1583 	if( SLOT->ksr != ksr )
1584 	{
1585 		SLOT->ksr = ksr;
1586 
1587 		/* calculate envelope generator rates */
1588 		if ((SLOT->ar + SLOT->ksr) < 32+62)
1589 		{
1590 			SLOT->eg_sh_ar  = eg_rate_shift [SLOT->ar  + SLOT->ksr ];
1591 			if ((OPN->type == TYPE_YM2612) || (OPN->type == TYPE_YM2608))
1592 			{
1593 				SLOT->eg_sel_ar = eg_rate_select2612[SLOT->ar  + SLOT->ksr ];
1594 			}
1595 			else
1596 			{
1597 				SLOT->eg_sel_ar = eg_rate_select[SLOT->ar  + SLOT->ksr ];
1598 			}
1599 		}
1600 		else
1601 		{
1602 			SLOT->eg_sh_ar  = 0;
1603 			SLOT->eg_sel_ar = 17*RATE_STEPS;
1604 		}
1605 
1606 		SLOT->eg_sh_d1r = eg_rate_shift [SLOT->d1r + SLOT->ksr];
1607 		SLOT->eg_sh_d2r = eg_rate_shift [SLOT->d2r + SLOT->ksr];
1608 		SLOT->eg_sh_rr  = eg_rate_shift [SLOT->rr  + SLOT->ksr];
1609 
1610 		if ((OPN->type == TYPE_YM2612) || (OPN->type == TYPE_YM2608))
1611 		{
1612 			SLOT->eg_sel_d1r= eg_rate_select2612[SLOT->d1r + SLOT->ksr];
1613 			SLOT->eg_sel_d2r= eg_rate_select2612[SLOT->d2r + SLOT->ksr];
1614 			SLOT->eg_sel_rr = eg_rate_select2612[SLOT->rr  + SLOT->ksr];
1615 		}
1616 		else
1617 		{
1618 			SLOT->eg_sel_d1r= eg_rate_select[SLOT->d1r + SLOT->ksr];
1619 			SLOT->eg_sel_d2r= eg_rate_select[SLOT->d2r + SLOT->ksr];
1620 			SLOT->eg_sel_rr = eg_rate_select[SLOT->rr  + SLOT->ksr];
1621 		}
1622 	}
1623 }
1624 
1625 /* update phase increment counters */
1626 /* Changed from INLINE to static to work around gcc 4.2.1 codegen bug */
refresh_fc_eg_chan(FM_OPN * OPN,FM_CH * CH)1627 static void refresh_fc_eg_chan(FM_OPN *OPN, FM_CH *CH )
1628 {
1629 	if( CH->SLOT[SLOT1].Incr==-1){
1630 		int fc = CH->fc;
1631 		int kc = CH->kcode;
1632 		refresh_fc_eg_slot(OPN, &CH->SLOT[SLOT1] , fc , kc );
1633 		refresh_fc_eg_slot(OPN, &CH->SLOT[SLOT2] , fc , kc );
1634 		refresh_fc_eg_slot(OPN, &CH->SLOT[SLOT3] , fc , kc );
1635 		refresh_fc_eg_slot(OPN, &CH->SLOT[SLOT4] , fc , kc );
1636 	}
1637 }
1638 
1639 /* initialize time tables */
init_timetables(FM_ST * ST,const UINT8 * dttable)1640 static void init_timetables( FM_ST *ST , const UINT8 *dttable )
1641 {
1642 	int i,d;
1643 	double rate;
1644 
1645 #if 0
1646 	logerror("FM.C: samplerate=%8i chip clock=%8i  freqbase=%f  \n",
1647 			 ST->rate, ST->clock, ST->freqbase );
1648 #endif
1649 
1650 	/* DeTune table */
1651 	for (d = 0;d <= 3;d++){
1652 		for (i = 0;i <= 31;i++){
1653 			rate = ((double)dttable[d*32 + i]) * SIN_LEN  * ST->freqbase  * (1<<FREQ_SH) / ((double)(1<<20));
1654 			ST->dt_tab[d][i]   = (INT32) rate;
1655 			ST->dt_tab[d+4][i] = -ST->dt_tab[d][i];
1656 #if 0
1657 			logerror("FM.C: DT [%2i %2i] = %8x  \n", d, i, ST->dt_tab[d][i] );
1658 #endif
1659 		}
1660 	}
1661 
1662 }
1663 
1664 
reset_channels(FM_ST * ST,FM_CH * CH,int num)1665 static void reset_channels( FM_ST *ST , FM_CH *CH , int num )
1666 {
1667 	int c,s;
1668 
1669 	ST->mode   = 0;	/* normal mode */
1670 	ST->TA     = 0;
1671 	ST->TAC    = 0;
1672 	ST->TB     = 0;
1673 	ST->TBC    = 0;
1674 
1675 	for( c = 0 ; c < num ; c++ )
1676 	{
1677 		CH[c].fc = 0;
1678 		for(s = 0 ; s < 4 ; s++ )
1679 		{
1680 			CH[c].SLOT[s].ssg = 0;
1681 			CH[c].SLOT[s].ssgn = 0;
1682 			CH[c].SLOT[s].state= EG_OFF;
1683 			CH[c].SLOT[s].volume = MAX_ATT_INDEX;
1684 			CH[c].SLOT[s].vol_out= MAX_ATT_INDEX;
1685 		}
1686 	}
1687 }
1688 
1689 /* initialize generic tables */
init_tables(void)1690 static int init_tables(void)
1691 {
1692 	signed int i,x;
1693 	signed int n;
1694 	double o,m;
1695 
1696 	for (x=0; x<TL_RES_LEN; x++)
1697 	{
1698 		m = (1<<16) / pow(2, (x+1) * (ENV_STEP/4.0) / 8.0);
1699 		m = floor(m);
1700 
1701 		/* we never reach (1<<16) here due to the (x+1) */
1702 		/* result fits within 16 bits at maximum */
1703 
1704 		n = (int)m;		/* 16 bits here */
1705 		n >>= 4;		/* 12 bits here */
1706 		if (n&1)		/* round to nearest */
1707 			n = (n>>1)+1;
1708 		else
1709 			n = n>>1;
1710 						/* 11 bits here (rounded) */
1711 		n <<= 2;		/* 13 bits here (as in real chip) */
1712 		tl_tab[ x*2 + 0 ] = n;
1713 		tl_tab[ x*2 + 1 ] = -tl_tab[ x*2 + 0 ];
1714 
1715 		for (i=1; i<13; i++)
1716 		{
1717 			tl_tab[ x*2+0 + i*2*TL_RES_LEN ] =  tl_tab[ x*2+0 ]>>i;
1718 			tl_tab[ x*2+1 + i*2*TL_RES_LEN ] = -tl_tab[ x*2+0 + i*2*TL_RES_LEN ];
1719 		}
1720 	#if 0
1721 			logerror("tl %04i", x);
1722 			for (i=0; i<13; i++)
1723 				logerror(", [%02i] %4x", i*2, tl_tab[ x*2 /*+1*/ + i*2*TL_RES_LEN ]);
1724 			logerror("\n");
1725 		}
1726 	#endif
1727 	}
1728 	/*logerror("FM.C: TL_TAB_LEN = %i elements (%i bytes)\n",TL_TAB_LEN, (int)sizeof(tl_tab));*/
1729 
1730 
1731 	for (i=0; i<SIN_LEN; i++)
1732 	{
1733 		/* non-standard sinus */
1734 		m = sin( ((i*2)+1) * PI / SIN_LEN ); /* checked against the real chip */
1735 
1736 		/* we never reach zero here due to ((i*2)+1) */
1737 
1738 		if (m>0.0)
1739 			o = 8*log(1.0/m)/log(2.0);	/* convert to 'decibels' */
1740 		else
1741 			o = 8*log(-1.0/m)/log(2.0);	/* convert to 'decibels' */
1742 
1743 		o = o / (ENV_STEP/4);
1744 
1745 		n = (int)(2.0*o);
1746 		if (n&1)						/* round to nearest */
1747 			n = (n>>1)+1;
1748 		else
1749 			n = n>>1;
1750 
1751 		sin_tab[ i ] = n*2 + (m>=0.0? 0: 1 );
1752 		/*logerror("FM.C: sin [%4i]= %4i (tl_tab value=%5i)\n", i, sin_tab[i],tl_tab[sin_tab[i]]);*/
1753 	}
1754 
1755 	/*logerror("FM.C: ENV_QUIET= %08x\n",ENV_QUIET );*/
1756 
1757 
1758 	/* build LFO PM modulation table */
1759 	for(i = 0; i < 8; i++) /* 8 PM depths */
1760 	{
1761 		UINT8 fnum;
1762 		for (fnum=0; fnum<128; fnum++) /* 7 bits meaningful of F-NUMBER */
1763 		{
1764 			UINT8 value;
1765 			UINT8 step;
1766 			UINT32 offset_depth = i;
1767 			UINT32 offset_fnum_bit;
1768 			UINT32 bit_tmp;
1769 
1770 			for (step=0; step<8; step++)
1771 			{
1772 				value = 0;
1773 				for (bit_tmp=0; bit_tmp<7; bit_tmp++) /* 7 bits */
1774 				{
1775 					if (fnum & (1<<bit_tmp)) /* only if bit "bit_tmp" is set */
1776 					{
1777 						offset_fnum_bit = bit_tmp * 8;
1778 						value += lfo_pm_output[offset_fnum_bit + offset_depth][step];
1779 					}
1780 				}
1781 				lfo_pm_table[(fnum*32*8) + (i*32) + step   + 0] = value;
1782 				lfo_pm_table[(fnum*32*8) + (i*32) +(step^7)+ 8] = value;
1783 				lfo_pm_table[(fnum*32*8) + (i*32) + step   +16] = -value;
1784 				lfo_pm_table[(fnum*32*8) + (i*32) +(step^7)+24] = -value;
1785 			}
1786 #if 0
1787 			logerror("LFO depth=%1x FNUM=%04x (<<4=%4x): ", i, fnum, fnum<<4);
1788 			for (step=0; step<16; step++) /* dump only positive part of waveforms */
1789 				logerror("%02x ", lfo_pm_table[(fnum*32*8) + (i*32) + step] );
1790 			logerror("\n");
1791 #endif
1792 
1793 		}
1794 	}
1795 
1796 
1797 
1798 #ifdef SAVE_SAMPLE
1799 	sample[0]=fopen("sampsum.pcm","wb");
1800 #endif
1801 
1802 	return 1;
1803 
1804 }
1805 
1806 
1807 
FMCloseTable(void)1808 static void FMCloseTable( void )
1809 {
1810 #ifdef SAVE_SAMPLE
1811 	fclose(sample[0]);
1812 #endif
1813 	return;
1814 }
1815 
1816 
1817 /* CSM Key Controll */
CSMKeyControll(UINT8 type,FM_CH * CH)1818 INLINE void CSMKeyControll(UINT8 type, FM_CH *CH)
1819 {
1820 	/* all key on then off (only for operators which were OFF!) */
1821 	if (!CH->SLOT[SLOT1].key)
1822 	{
1823 		FM_KEYON(type, CH,SLOT1);
1824 		FM_KEYOFF(CH, SLOT1);
1825 	}
1826 	if (!CH->SLOT[SLOT2].key)
1827 	{
1828 		FM_KEYON(type, CH,SLOT2);
1829 		FM_KEYOFF(CH, SLOT2);
1830 	}
1831 	if (!CH->SLOT[SLOT3].key)
1832 	{
1833 		FM_KEYON(type, CH,SLOT3);
1834 		FM_KEYOFF(CH, SLOT3);
1835 	}
1836 	if (!CH->SLOT[SLOT4].key)
1837 	{
1838 		FM_KEYON(type, CH,SLOT4);
1839 		FM_KEYOFF(CH, SLOT4);
1840 	}
1841 }
1842 
1843 #ifdef _STATE_H
1844 /* FM channel save , internal state only */
FMsave_state_channel(const char * name,int num,FM_CH * CH,int num_ch)1845 static void FMsave_state_channel(const char *name,int num,FM_CH *CH,int num_ch)
1846 {
1847 	int slot , ch;
1848 	char state_name[20];
1849 	const char slot_array[4] = { 1 , 3 , 2 , 4 };
1850 
1851 	for(ch=0;ch<num_ch;ch++,CH++)
1852 	{
1853 		/* channel */
1854 		sprintf(state_name,"%s.CH%d",name,ch);
1855 		state_save_register_INT32(state_name, num, "feedback" , CH->op1_out , 2);
1856 		state_save_register_UINT32(state_name, num, "phasestep"   , &CH->fc , 1);
1857 		/* slots */
1858 		for(slot=0;slot<4;slot++)
1859 		{
1860 			FM_SLOT *SLOT = &CH->SLOT[slot];
1861 
1862 			sprintf(state_name,"%s.CH%d.SLOT%d",name,ch,slot_array[slot]);
1863 			state_save_register_UINT32(state_name, num, "phasecount" , &SLOT->phase, 1);
1864 			state_save_register_UINT8 (state_name, num, "state"      , &SLOT->state, 1);
1865 			state_save_register_INT32 (state_name, num, "volume"     , &SLOT->volume, 1);
1866 		}
1867 	}
1868 }
1869 
FMsave_state_st(const char * state_name,int num,FM_ST * ST)1870 static void FMsave_state_st(const char *state_name,int num,FM_ST *ST)
1871 {
1872 #if FM_BUSY_FLAG_SUPPORT
1873 	state_save_register_double(state_name, num, "BusyExpire", &ST->BusyExpire , 1);
1874 #endif
1875 	state_save_register_UINT8 (state_name, num, "address"   , &ST->address , 1);
1876 	state_save_register_UINT8 (state_name, num, "IRQ"       , &ST->irq     , 1);
1877 	state_save_register_UINT8 (state_name, num, "IRQ MASK"  , &ST->irqmask , 1);
1878 	state_save_register_UINT8 (state_name, num, "status"    , &ST->status  , 1);
1879 	state_save_register_UINT32(state_name, num, "mode"      , &ST->mode    , 1);
1880 	state_save_register_UINT8 (state_name, num, "prescaler" , &ST->prescaler_sel , 1);
1881 	state_save_register_UINT8 (state_name, num, "freq latch", &ST->fn_h , 1);
1882 	state_save_register_int   (state_name, num, "TIMER A"   , &ST->TA   );
1883 	state_save_register_int   (state_name, num, "TIMER Acnt", &ST->TAC  );
1884 	state_save_register_UINT8 (state_name, num, "TIMER B"   , &ST->TB   , 1);
1885 	state_save_register_int   (state_name, num, "TIMER Bcnt", &ST->TBC  );
1886 }
1887 #endif /* _STATE_H */
1888 
1889 #if BUILD_OPN
1890 
1891 
1892 
1893 /* prescaler set (and make time tables) */
OPNSetPres(FM_OPN * OPN,int pres,int TimerPres,int SSGpres)1894 static void OPNSetPres(FM_OPN *OPN , int pres , int TimerPres, int SSGpres)
1895 {
1896 	int i;
1897 
1898 	/* frequency base */
1899 	OPN->ST.freqbase = (OPN->ST.rate) ? ((double)OPN->ST.clock / OPN->ST.rate) / pres : 0;
1900 
1901 #if 0
1902 	OPN->ST.rate = (double)OPN->ST.clock / pres;
1903 	OPN->ST.freqbase = 1.0;
1904 #endif
1905 
1906 	OPN->eg_timer_add  = (1<<EG_SH)  *  OPN->ST.freqbase;
1907 	OPN->eg_timer_overflow = ( 3 ) * (1<<EG_SH);
1908 
1909 
1910 	/* Timer base time */
1911 	OPN->ST.TimerBase = 1.0/((double)OPN->ST.clock / (double)TimerPres);
1912 
1913 	/* SSG part  prescaler set */
1914 	if( SSGpres ) SSGClk( OPN->ST.index, OPN->ST.clock * 2 / SSGpres );
1915 
1916 	/* make time tables */
1917 	init_timetables( &OPN->ST, dt_tab );
1918 
1919 	/* there are 2048 FNUMs that can be generated using FNUM/BLK registers
1920 		but LFO works with one more bit of a precision so we really need 4096 elements */
1921 	/* calculate fnumber -> increment counter table */
1922 	for(i = 0; i < 4096; i++)
1923 	{
1924 		/* freq table for octave 7 */
1925 		/* OPN phase increment counter = 20bit */
1926 		OPN->fn_table[i] = (UINT32)( (double)i * 32 * OPN->ST.freqbase * (1<<(FREQ_SH-10)) ); /* -10 because chip works with 10.10 fixed point, while we use 16.16 */
1927 #if 0
1928 		logerror("FM.C: fn_table[%4i] = %08x (dec=%8i)\n",
1929 				 i, OPN->fn_table[i]>>6,OPN->fn_table[i]>>6 );
1930 #endif
1931 	}
1932 
1933 	/* maximal frequency is required for Phase overflow calculation, register size is 17 bits (Nemesis) */
1934 	OPN->fn_max = (UINT32)( (double)0x20000 * OPN->ST.freqbase * (1<<(FREQ_SH-10)) );
1935 
1936 	/* LFO freq. table */
1937 	for(i = 0; i < 8; i++)
1938 	{
1939 		/* Amplitude modulation: 64 output levels (triangle waveform); 1 level lasts for one of "lfo_samples_per_step" samples */
1940 		/* Phase modulation: one entry from lfo_pm_output lasts for one of 4 * "lfo_samples_per_step" samples  */
1941 		OPN->lfo_freq[i] = (1.0 / lfo_samples_per_step[i]) * (1<<LFO_SH) * OPN->ST.freqbase;
1942 #if 0
1943 		logerror("FM.C: lfo_freq[%i] = %08x (dec=%8i)\n",
1944 				 i, OPN->lfo_freq[i],OPN->lfo_freq[i] );
1945 #endif
1946 	}
1947 }
1948 
1949 
1950 
1951 /* write a OPN mode register 0x20-0x2f */
OPNWriteMode(FM_OPN * OPN,int r,int v)1952 static void OPNWriteMode(FM_OPN *OPN, int r, int v)
1953 {
1954 	UINT8 c;
1955 	FM_CH *CH;
1956 
1957 	switch(r){
1958 	case 0x21:	/* Test */
1959 		break;
1960 	case 0x22:	/* LFO FREQ (YM2608/YM2610/YM2610B/YM2612) */
1961 		if( OPN->type & TYPE_LFOPAN )
1962 		{
1963 			if (v&0x08) /* LFO enabled ? */
1964 			{
1965 				OPN->lfo_inc = OPN->lfo_freq[v&7];
1966 			}
1967 			else
1968 			{
1969 				OPN->lfo_inc = 0;
1970 			}
1971 		}
1972 		break;
1973 	case 0x24:	/* timer A High 8*/
1974 		OPN->ST.TA = (OPN->ST.TA & 0x03)|(((int)v)<<2);
1975 		break;
1976 	case 0x25:	/* timer A Low 2*/
1977 		OPN->ST.TA = (OPN->ST.TA & 0x3fc)|(v&3);
1978 		break;
1979 	case 0x26:	/* timer B */
1980 		OPN->ST.TB = v;
1981 		break;
1982 	case 0x27:	/* mode, timer control */
1983 		set_timers( &(OPN->ST),OPN->ST.index,v );
1984 		break;
1985 	case 0x28:	/* key on / off */
1986 		c = v & 0x03;
1987 		if( c == 3 ) break;
1988 		if( (v&0x04) && (OPN->type & TYPE_6CH) ) c+=3;
1989 		CH = OPN->P_CH;
1990 		CH = &CH[c];
1991 		if(v&0x10) FM_KEYON(OPN->type, CH,SLOT1); else FM_KEYOFF(CH,SLOT1);
1992 		if(v&0x20) FM_KEYON(OPN->type, CH,SLOT2); else FM_KEYOFF(CH,SLOT2);
1993 		if(v&0x40) FM_KEYON(OPN->type, CH,SLOT3); else FM_KEYOFF(CH,SLOT3);
1994 		if(v&0x80) FM_KEYON(OPN->type, CH,SLOT4); else FM_KEYOFF(CH,SLOT4);
1995 		break;
1996 	}
1997 }
1998 
1999 /* write a OPN register (0x30-0xff) */
OPNWriteReg(FM_OPN * OPN,int r,int v)2000 static void OPNWriteReg(FM_OPN *OPN, int r, int v)
2001 {
2002 	FM_CH *CH;
2003 	FM_SLOT *SLOT;
2004 
2005 	UINT8 c = OPN_CHAN(r);
2006 
2007 	if (c == 3) return; /* 0xX3,0xX7,0xXB,0xXF */
2008 
2009 	if (r >= 0x100) c+=3;
2010 
2011 	CH = OPN->P_CH;
2012 	CH = &CH[c];
2013 
2014 	SLOT = &(CH->SLOT[OPN_SLOT(r)]);
2015 
2016 	switch( r & 0xf0 ) {
2017 	case 0x30:	/* DET , MUL */
2018 		set_det_mul(&OPN->ST,CH,SLOT,v);
2019 		break;
2020 
2021 	case 0x40:	/* TL */
2022 		set_tl(CH,SLOT,v);
2023 		break;
2024 
2025 	case 0x50:	/* KS, AR */
2026 		set_ar_ksr(OPN->type, CH,SLOT,v);
2027 		break;
2028 
2029 	case 0x60:	/* bit7 = AM ENABLE, DR */
2030 		set_dr(OPN->type, SLOT,v);
2031 
2032 		if(OPN->type & TYPE_LFOPAN) /* YM2608/2610/2610B/2612 */
2033 		{
2034 			SLOT->AMmask = (v&0x80) ? ~0 : 0;
2035 		}
2036 		break;
2037 
2038 	case 0x70:	/*     SR */
2039 		set_sr(OPN->type, SLOT,v);
2040 		break;
2041 
2042 	case 0x80:	/* SL, RR */
2043 		set_sl_rr(OPN->type, SLOT,v);
2044 		break;
2045 
2046 	case 0x90:	/* SSG-EG */
2047 		SLOT->ssg  =  v&0x0f;
2048 		SLOT->ssgn = (v&0x04)>>1; /* bit 1 in ssgn = attack */
2049 
2050 		/* SSG-EG envelope shapes :
2051 
2052 		E AtAlH
2053 		1 0 0 0  \\\\
2054 
2055 		1 0 0 1  \___
2056 
2057 		1 0 1 0  \/\/
2058 		          ___
2059 		1 0 1 1  \
2060 
2061 		1 1 0 0  ////
2062 		          ___
2063 		1 1 0 1  /
2064 
2065 		1 1 1 0  /\/\
2066 
2067 		1 1 1 1  /___
2068 
2069 
2070 		E = SSG-EG enable
2071 
2072 
2073 		The shapes are generated using Attack, Decay and Sustain phases.
2074 
2075 		Each single character in the diagrams above represents this whole
2076 		sequence:
2077 
2078 		- when KEY-ON = 1, normal Attack phase is generated (*without* any
2079 		  difference when compared to normal mode),
2080 
2081 		- later, when envelope level reaches minimum level (max volume),
2082 		  the EG switches to Decay phase (which works with bigger steps
2083 		  when compared to normal mode - see below),
2084 
2085 		- later when envelope level passes the SL level,
2086 		  the EG swithes to Sustain phase (which works with bigger steps
2087 		  when compared to normal mode - see below),
2088 
2089 		- finally when envelope level reaches maximum level (min volume),
2090 		  the EG switches to Attack phase again (depends on actual waveform).
2091 
2092 		Important is that when switch to Attack phase occurs, the phase counter
2093 		of that operator will be zeroed-out (as in normal KEY-ON) but not always.
2094 		(I havent found the rule for that - perhaps only when the output level is low)
2095 
2096 		The difference (when compared to normal Envelope Generator mode) is
2097 		that the resolution in Decay and Sustain phases is 4 times lower;
2098 		this results in only 256 steps instead of normal 1024.
2099 		In other words:
2100 		when SSG-EG is disabled, the step inside of the EG is one,
2101 		when SSG-EG is enabled, the step is four (in Decay and Sustain phases).
2102 
2103 		Times between the level changes are the same in both modes.
2104 
2105 
2106 		Important:
2107 		Decay 1 Level (so called SL) is compared to actual SSG-EG output, so
2108 		it is the same in both SSG and no-SSG modes, with this exception:
2109 
2110 		when the SSG-EG is enabled and is generating raising levels
2111 		(when the EG output is inverted) the SL will be found at wrong level !!!
2112 		For example, when SL=02:
2113 			0 -6 = -6dB in non-inverted EG output
2114 			96-6 = -90dB in inverted EG output
2115 		Which means that EG compares its level to SL as usual, and that the
2116 		output is simply inverted afterall.
2117 
2118 
2119 		The Yamaha's manuals say that AR should be set to 0x1f (max speed).
2120 		That is not necessary, but then EG will be generating Attack phase.
2121 
2122 		*/
2123 
2124 
2125 		break;
2126 
2127 	case 0xa0:
2128 		switch( OPN_SLOT(r) ){
2129 		case 0:		/* 0xa0-0xa2 : FNUM1 */
2130 			{
2131 				UINT32 fn = (((UINT32)( (OPN->ST.fn_h)&7))<<8) + v;
2132 				UINT8 blk = OPN->ST.fn_h>>3;
2133 				/* keyscale code */
2134 				CH->kcode = (blk<<2) | opn_fktable[fn >> 7];
2135 				/* phase increment counter */
2136 				CH->fc = OPN->fn_table[fn*2]>>(7-blk);
2137 
2138 				/* store fnum in clear form for LFO PM calculations */
2139 				CH->block_fnum = (blk<<11) | fn;
2140 
2141 				CH->SLOT[SLOT1].Incr=-1;
2142 			}
2143 			break;
2144 		case 1:		/* 0xa4-0xa6 : FNUM2,BLK */
2145 			OPN->ST.fn_h = v&0x3f;
2146 			break;
2147 		case 2:		/* 0xa8-0xaa : 3CH FNUM1 */
2148 			if(r < 0x100)
2149 			{
2150 				UINT32 fn = (((UINT32)(OPN->SL3.fn_h&7))<<8) + v;
2151 				UINT8 blk = OPN->SL3.fn_h>>3;
2152 				/* keyscale code */
2153 				OPN->SL3.kcode[c]= (blk<<2) | opn_fktable[fn >> 7];
2154 				/* phase increment counter */
2155 				OPN->SL3.fc[c] = OPN->fn_table[fn*2]>>(7-blk);
2156 				OPN->SL3.block_fnum[c] = (blk<<11) | fn;
2157 				(OPN->P_CH)[2].SLOT[SLOT1].Incr=-1;
2158 			}
2159 			break;
2160 		case 3:		/* 0xac-0xae : 3CH FNUM2,BLK */
2161 			if(r < 0x100)
2162 				OPN->SL3.fn_h = v&0x3f;
2163 			break;
2164 		}
2165 		break;
2166 
2167 	case 0xb0:
2168 		switch( OPN_SLOT(r) ){
2169 		case 0:		/* 0xb0-0xb2 : FB,ALGO */
2170 			{
2171 				int feedback = (v>>3)&7;
2172 				CH->ALGO = v&7;
2173 				CH->FB   = feedback ? feedback+6 : 0;
2174 				setup_connection( CH, c );
2175 			}
2176 			break;
2177 		case 1:		/* 0xb4-0xb6 : L , R , AMS , PMS (YM2612/YM2610B/YM2610/YM2608) */
2178 			if( OPN->type & TYPE_LFOPAN)
2179 			{
2180 				/* b0-2 PMS */
2181 				CH->pms = (v & 7) * 32; /* CH->pms = PM depth * 32 (index in lfo_pm_table) */
2182 
2183 				/* b4-5 AMS */
2184 				CH->ams = lfo_ams_depth_shift[(v>>4) & 0x03];
2185 
2186 				/* PAN :  b7 = L, b6 = R */
2187 				OPN->pan[ c*2   ] = (v & 0x80) ? ~0 : 0;
2188 				OPN->pan[ c*2+1 ] = (v & 0x40) ? ~0 : 0;
2189 
2190 			}
2191 			break;
2192 		}
2193 		break;
2194 	}
2195 }
2196 
2197 #endif /* BUILD_OPN */
2198 
2199 #if BUILD_OPN_PRESCALER
2200 /*
2201   prescaler circuit (best guess to verified chip behaviour)
2202 
2203                +--------------+  +-sel2-+
2204                |              +--|in20  |
2205          +---+ |  +-sel1-+       |      |
2206 M-CLK -+-|1/2|-+--|in10  | +---+ |   out|--INT_CLOCK
2207        | +---+    |   out|-|1/3|-|in21  |
2208        +----------|in11  | +---+ +------+
2209                   +------+
2210 
2211 reg.2d : sel2 = in21 (select sel2)
2212 reg.2e : sel1 = in11 (select sel1)
2213 reg.2f : sel1 = in10 , sel2 = in20 (clear selector)
2214 reset  : sel1 = in11 , sel2 = in21 (clear both)
2215 
2216 */
OPNPrescaler_w(FM_OPN * OPN,int addr,int pre_divider)2217 void OPNPrescaler_w(FM_OPN *OPN , int addr, int pre_divider)
2218 {
2219 	static const int opn_pres[4] = { 2*12 , 2*12 , 6*12 , 3*12 };
2220 	static const int ssg_pres[4] = { 1    ,    1 ,    4 ,    2 };
2221 	int sel;
2222 
2223 	switch(addr)
2224 	{
2225 	case 0:		/* when reset */
2226 		OPN->ST.prescaler_sel = 2;
2227 		break;
2228 	case 1:		/* when postload */
2229 		break;
2230 	case 0x2d:	/* divider sel : select 1/1 for 1/3line    */
2231 		OPN->ST.prescaler_sel |= 0x02;
2232 		break;
2233 	case 0x2e:	/* divider sel , select 1/3line for output */
2234 		OPN->ST.prescaler_sel |= 0x01;
2235 		break;
2236 	case 0x2f:	/* divider sel , clear both selector to 1/2,1/2 */
2237 		OPN->ST.prescaler_sel = 0;
2238 		break;
2239 	}
2240 	sel = OPN->ST.prescaler_sel & 3;
2241 	/* update prescaler */
2242 	OPNSetPres( OPN,	opn_pres[sel]*pre_divider,
2243 						opn_pres[sel]*pre_divider,
2244 						ssg_pres[sel]*pre_divider );
2245 }
2246 #endif /* BUILD_OPN_PRESCALER */
2247 
2248 #if BUILD_YM2203
2249 /*****************************************************************************/
2250 /*		YM2203 local section                                                 */
2251 /*****************************************************************************/
2252 
2253 /* here's the virtual YM2203(OPN) */
2254 typedef struct
2255 {
2256 #ifdef _STATE_H
2257 	UINT8 REGS[256];		/* registers         */
2258 #endif
2259 	FM_OPN OPN;				/* OPN state         */
2260 	FM_CH CH[3];			/* channel state     */
2261 } YM2203;
2262 
2263 static YM2203 *FM2203=NULL;	/* array of YM2203's */
2264 static int YM2203NumChips;	/* number of chips */
2265 
2266 /* Generate samples for one of the YM2203s */
YM2203UpdateOne(int num,INT16 * buffer,int length)2267 void YM2203UpdateOne(int num, INT16 *buffer, int length)
2268 {
2269 	YM2203 *F2203 = &(FM2203[num]);
2270 	FM_OPN *OPN =   &(FM2203[num].OPN);
2271 	int i;
2272 	FMSAMPLE *buf = buffer;
2273 
2274 	cur_chip = (void *)F2203;
2275 	State    = &F2203->OPN.ST;
2276 	cch[0]   = &F2203->CH[0];
2277 	cch[1]   = &F2203->CH[1];
2278 	cch[2]   = &F2203->CH[2];
2279 
2280 
2281 	/* refresh PG and EG */
2282 	refresh_fc_eg_chan( OPN, cch[0] );
2283 	refresh_fc_eg_chan( OPN, cch[1] );
2284 	if( (State->mode & 0xc0) )
2285 	{
2286 		/* 3SLOT MODE */
2287 		if( cch[2]->SLOT[SLOT1].Incr==-1)
2288 		{
2289 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT1] , OPN->SL3.fc[1] , OPN->SL3.kcode[1] );
2290 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT2] , OPN->SL3.fc[2] , OPN->SL3.kcode[2] );
2291 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT3] , OPN->SL3.fc[0] , OPN->SL3.kcode[0] );
2292 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT4] , cch[2]->fc , cch[2]->kcode );
2293 		}
2294 	}else refresh_fc_eg_chan( OPN, cch[2] );
2295 
2296 
2297 	/* YM2203 doesn't have LFO so we must keep these globals at 0 level */
2298 	LFO_AM = 0;
2299 	LFO_PM = 0;
2300 
2301 	/* buffering */
2302 	for (i=0; i < length ; i++)
2303 	{
2304 		/* clear outputs */
2305 		out_fm[0] = 0;
2306 		out_fm[1] = 0;
2307 		out_fm[2] = 0;
2308 
2309 		/* advance envelope generator */
2310 		OPN->eg_timer += OPN->eg_timer_add;
2311 		while (OPN->eg_timer >= OPN->eg_timer_overflow)
2312 		{
2313 			OPN->eg_timer -= OPN->eg_timer_overflow;
2314 			OPN->eg_cnt++;
2315 
2316 			advance_eg_channel(OPN, &cch[0]->SLOT[SLOT1]);
2317 			advance_eg_channel(OPN, &cch[1]->SLOT[SLOT1]);
2318 			advance_eg_channel(OPN, &cch[2]->SLOT[SLOT1]);
2319 		}
2320 
2321 		/* calculate FM */
2322 		chan_calc(OPN, cch[0], 0 );
2323 		chan_calc(OPN, cch[1], 1 );
2324 		chan_calc(OPN, cch[2], 2 );
2325 
2326 		/* buffering */
2327 		{
2328 			int lt;
2329 
2330 			lt = out_fm[0] + out_fm[1] + out_fm[2];
2331 
2332 			lt >>= FINAL_SH;
2333 
2334 			Limit( lt , MAXOUT, MINOUT );
2335 
2336 			#ifdef SAVE_SAMPLE
2337 				SAVE_ALL_CHANNELS
2338 			#endif
2339 
2340 			/* buffering */
2341 			buf[i] = lt;
2342 		}
2343 
2344 		/* timer A control */
2345 		INTERNAL_TIMER_A( State , cch[2] )
2346 	}
2347 	INTERNAL_TIMER_B(State,length)
2348 }
2349 
2350 /* ---------- reset one of chip ---------- */
YM2203ResetChip(int num)2351 void YM2203ResetChip(int num)
2352 {
2353 	int i;
2354 	FM_OPN *OPN = &(FM2203[num].OPN);
2355 
2356 	/* Reset Prescaler */
2357 	OPNPrescaler_w(OPN, 0 , 1 );
2358 	/* reset SSG section */
2359 	SSGReset(OPN->ST.index);
2360 	/* status clear */
2361 	FM_IRQMASK_SET(&OPN->ST,0x03);
2362 	FM_BUSY_CLEAR(&OPN->ST);
2363 	OPNWriteMode(OPN,0x27,0x30); /* mode 0 , timer reset */
2364 
2365 	OPN->eg_timer = 0;
2366 	OPN->eg_cnt   = 0;
2367 
2368 	FM_STATUS_RESET(&OPN->ST, 0xff);
2369 
2370 	reset_channels( &OPN->ST , FM2203[num].CH , 3 );
2371 	/* reset OPerator paramater */
2372 	for(i = 0xb2 ; i >= 0x30 ; i-- ) OPNWriteReg(OPN,i,0);
2373 	for(i = 0x26 ; i >= 0x20 ; i-- ) OPNWriteReg(OPN,i,0);
2374 }
2375 
2376 #ifdef _STATE_H
YM2203_postload(void)2377 static void YM2203_postload(void)
2378 {
2379 	int num , r;
2380 
2381 	for(num=0;num<YM2203NumChips;num++)
2382 	{
2383 		/* prescaler */
2384 		OPNPrescaler_w(&FM2203[num].OPN,1,1);
2385 
2386 		/* SSG registers */
2387 		for(r=0;r<16;r++)
2388 		{
2389 			SSGWrite(num,0,r);
2390 			SSGWrite(num,1,FM2203[num].REGS[r]);
2391 		}
2392 
2393 		/* OPN registers */
2394 		/* DT / MULTI , TL , KS / AR , AMON / DR , SR , SL / RR , SSG-EG */
2395 		for(r=0x30;r<0x9e;r++)
2396 			if((r&3) != 3)
2397 				OPNWriteReg(&FM2203[num].OPN,r,FM2203[num].REGS[r]);
2398 		/* FB / CONNECT , L / R / AMS / PMS */
2399 		for(r=0xb0;r<0xb6;r++)
2400 			if((r&3) != 3)
2401 				OPNWriteReg(&FM2203[num].OPN,r,FM2203[num].REGS[r]);
2402 
2403 		/* channels */
2404 		/*FM_channel_postload(FM2203[num].CH,3);*/
2405 	}
2406 	cur_chip = NULL;
2407 }
2408 
YM2203_save_state(void)2409 static void YM2203_save_state(void)
2410 {
2411 	int num;
2412 	const char statename[] = "YM2203";
2413 
2414 	for(num=0;num<YM2203NumChips;num++)
2415 	{
2416 		state_save_register_UINT8 (statename, num, "regs"   , FM2203[num].REGS   , 256);
2417 		FMsave_state_st(statename,num,&FM2203[num].OPN.ST);
2418 		FMsave_state_channel(statename,num,FM2203[num].CH,3);
2419 		/* 3slots */
2420 		state_save_register_UINT32 (statename, num, "slot3fc" , FM2203[num].OPN.SL3.fc , 3);
2421 		state_save_register_UINT8  (statename, num, "slot3fh" , &FM2203[num].OPN.SL3.fn_h , 1);
2422 		state_save_register_UINT8  (statename, num, "slot3kc" , FM2203[num].OPN.SL3.kcode , 3);
2423 	}
2424 	state_save_register_func_postload(YM2203_postload);
2425 }
2426 #endif /* _STATE_H */
2427 
2428 /* ----------  Initialize YM2203 emulator(s) ----------
2429    'num' is the number of virtual YM2203s to allocate
2430    'clock' is the chip clock in Hz
2431    'rate' is sampling rate
2432 */
YM2203Init(int num,int clock,int rate,FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)2433 int YM2203Init(int num, int clock, int rate,
2434                FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)
2435 {
2436 	int i;
2437 
2438 	if (FM2203) return (-1);	/* duplicate init. */
2439 	cur_chip = NULL;	/* hiro-shi!! */
2440 
2441 	YM2203NumChips = num;
2442 
2443 	/* allocate ym2203 state space */
2444 	if( (FM2203 = (YM2203 *)malloc(sizeof(YM2203) * YM2203NumChips))==NULL)
2445 		return (-1);
2446 	/* clear */
2447 	memset(FM2203,0,sizeof(YM2203) * YM2203NumChips);
2448 
2449 	if( !init_tables() )
2450 	{
2451 		if (FM2203) {
2452 			free( FM2203 );
2453 			FM2203 = NULL;
2454 		}
2455 		return (-1);
2456 	}
2457 	for ( i = 0 ; i < YM2203NumChips; i++ ) {
2458 		FM2203[i].OPN.ST.index = i;
2459 		FM2203[i].OPN.type = TYPE_YM2203;
2460 		FM2203[i].OPN.P_CH = FM2203[i].CH;
2461 		FM2203[i].OPN.ST.clock = clock;
2462 		FM2203[i].OPN.ST.rate = rate;
2463 
2464 		FM2203[i].OPN.ST.Timer_Handler = TimerHandler;
2465 		FM2203[i].OPN.ST.IRQ_Handler   = IRQHandler;
2466 		YM2203ResetChip(i);
2467 	}
2468 #ifdef _STATE_H
2469 	YM2203_save_state();
2470 #endif
2471 	return(0);
2472 }
2473 
2474 /* shut down emulator */
YM2203Shutdown(void)2475 void YM2203Shutdown(void)
2476 {
2477 	if (!FM2203) return;
2478 
2479 	FMCloseTable();
2480 	if (FM2203) {
2481 		free(FM2203);
2482 		FM2203 = NULL;
2483 	}
2484 }
2485 
2486 /* YM2203 I/O interface */
YM2203Write(int n,int a,UINT8 v)2487 int YM2203Write(int n,int a,UINT8 v)
2488 {
2489 	FM_OPN *OPN = &(FM2203[n].OPN);
2490 
2491 	if( !(a&1) )
2492 	{	/* address port */
2493 		OPN->ST.address = (v &= 0xff);
2494 
2495 		/* Write register to SSG emulator */
2496 		if( v < 16 ) SSGWrite(n,0,v);
2497 
2498 		/* prescaler select : 2d,2e,2f  */
2499 		if( v >= 0x2d && v <= 0x2f )
2500 			OPNPrescaler_w(OPN , v , 1);
2501 	}
2502 	else
2503 	{	/* data port */
2504 		int addr = OPN->ST.address;
2505 #ifdef _STATE_H
2506 		FM2203[n].REGS[addr] = v;
2507 #endif
2508 		switch( addr & 0xf0 )
2509 		{
2510 		case 0x00:	/* 0x00-0x0f : SSG section */
2511 			/* Write data to SSG emulator */
2512 			SSGWrite(n,a,v);
2513 			break;
2514 		case 0x20:	/* 0x20-0x2f : Mode section */
2515 			YM2203UpdateReq(n);
2516 			/* write register */
2517 			OPNWriteMode(OPN,addr,v);
2518 			break;
2519 		default:	/* 0x30-0xff : OPN section */
2520 			YM2203UpdateReq(n);
2521 			/* write register */
2522 			OPNWriteReg(OPN,addr,v);
2523 		}
2524 		FM_BUSY_SET(&OPN->ST,1);
2525 	}
2526 	return OPN->ST.irq;
2527 }
2528 
YM2203Read(int n,int a)2529 UINT8 YM2203Read(int n,int a)
2530 {
2531 	YM2203 *F2203 = &(FM2203[n]);
2532 	int addr = F2203->OPN.ST.address;
2533 	UINT8 ret = 0;
2534 
2535 	if( !(a&1) )
2536 	{	/* status port */
2537 		ret = FM_STATUS_FLAG(&F2203->OPN.ST);
2538 	}
2539 	else
2540 	{	/* data port (only SSG) */
2541 		if( addr < 16 ) ret = SSGRead(n);
2542 	}
2543 	return ret;
2544 }
2545 
YM2203TimerOver(int n,int c)2546 int YM2203TimerOver(int n,int c)
2547 {
2548 	YM2203 *F2203 = &(FM2203[n]);
2549 
2550 	if( c )
2551 	{	/* Timer B */
2552 		TimerBOver( &(F2203->OPN.ST) );
2553 	}
2554 	else
2555 	{	/* Timer A */
2556 		YM2203UpdateReq(n);
2557 		/* timer update */
2558 		TimerAOver( &(F2203->OPN.ST) );
2559 		/* CSM mode key,TL control */
2560 		if( F2203->OPN.ST.mode & 0x80 )
2561 		{	/* CSM mode auto key on */
2562 			CSMKeyControll( F2203->OPN.type, &(F2203->CH[2]) );
2563 		}
2564 	}
2565 	return F2203->OPN.ST.irq;
2566 }
2567 #endif /* BUILD_YM2203 */
2568 
2569 
2570 
2571 #if (BUILD_YM2608||BUILD_YM2610||BUILD_YM2610B)
2572 
2573 /* ADPCM type A channel struct */
2574 typedef struct
2575 {
2576 	UINT8		flag;			/* port state				*/
2577 	UINT8		flagMask;		/* arrived flag mask		*/
2578 	UINT8		now_data;		/* current ROM data			*/
2579 	UINT32		now_addr;		/* current ROM address		*/
2580 	UINT32		now_step;
2581 	UINT32		step;
2582 	UINT32		start;			/* sample data start address*/
2583 	UINT32		end;			/* sample data end address	*/
2584 	UINT8		IL;				/* Instrument Level			*/
2585 	INT32		adpcm_acc;		/* accumulator				*/
2586 	INT32		adpcm_step;		/* step						*/
2587 	INT32		adpcm_out;		/* (speedup) hiro-shi!!		*/
2588 	INT8		vol_mul;		/* volume in "0.75dB" steps	*/
2589 	UINT8		vol_shift;		/* volume in "-6dB" steps	*/
2590 	INT32		*pan;			/* &out_adpcm[OPN_xxxx] 	*/
2591 } ADPCM_CH;
2592 
2593 /* here's the virtual YM2610 */
2594 typedef struct
2595 {
2596 #ifdef _STATE_H
2597 	UINT8		REGS[512];			/* registers			*/
2598 #endif
2599 	FM_OPN		OPN;				/* OPN state			*/
2600 	FM_CH		CH[6];				/* channel state		*/
2601 	UINT8		addr_A1;			/* address line A1		*/
2602 
2603 	/* ADPCM-A unit */
2604 	UINT8		*pcmbuf;			/* pcm rom buffer		*/
2605 	UINT32		pcm_size;			/* size of pcm rom		*/
2606 	UINT8		adpcmTL;			/* adpcmA total level	*/
2607 	ADPCM_CH 	adpcm[6];			/* adpcm channels		*/
2608 	UINT32		adpcmreg[0x30];		/* registers			*/
2609 	UINT8		adpcm_arrivedEndAddress;
2610 	YM_DELTAT 	deltaT;				/* Delta-T ADPCM unit	*/
2611 
2612     UINT8		flagmask;			/* YM2608 only */
2613     UINT8		irqmask;			/* YM2608 only */
2614 } YM2610;
2615 
2616 /* here is the virtual YM2608 */
2617 typedef YM2610 YM2608;
2618 
2619 
2620 /**** YM2610 ADPCM defines ****/
2621 static const unsigned ADPCM_SHIFT          = 16;  /* frequency step rate   */
2622 static const unsigned ADPCMA_ADDRESS_SHIFT = 8;   /* adpcm A address shift */
2623 
2624 static UINT8 *pcmbufA;
2625 static UINT32 pcmsizeA;
2626 
2627 
2628 /* Algorithm and tables verified on real YM2608 and YM2610 */
2629 
2630 /* usual ADPCM table (16 * 1.1^N) */
2631 static const int steps[49] =
2632 {
2633 	 16,  17,   19,   21,   23,   25,   28,
2634 	 31,  34,   37,   41,   45,   50,   55,
2635 	 60,  66,   73,   80,   88,   97,  107,
2636 	118, 130,  143,  157,  173,  190,  209,
2637 	230, 253,  279,  307,  337,  371,  408,
2638 	449, 494,  544,  598,  658,  724,  796,
2639 	876, 963, 1060, 1166, 1282, 1411, 1552
2640 };
2641 
2642 /* different from the usual ADPCM table */
2643 static int const step_inc[8] = { -1*16, -1*16, -1*16, -1*16, 2*16, 5*16, 7*16, 9*16 };
2644 
2645 /* speedup purposes only */
2646 static int jedi_table[ 49*16 ];
2647 
2648 
Init_ADPCMATable(void)2649 static void Init_ADPCMATable(void){
2650 
2651 	int step, nib;
2652 
2653 	for (step = 0; step < 49; step++)
2654 	{
2655 		/* loop over all nibbles and compute the difference */
2656 		for (nib = 0; nib < 16; nib++)
2657 		{
2658 			int value = (2*(nib & 0x07) + 1) * steps[step] / 8;
2659 			jedi_table[step*16 + nib] = (nib&0x08) ? -value : value;
2660 		}
2661 	}
2662 }
2663 
2664 /* ADPCM A (Non control type) : calculate one channel output */
ADPCMA_calc_chan(YM2610 * F2610,ADPCM_CH * ch)2665 INLINE void ADPCMA_calc_chan( YM2610 *F2610, ADPCM_CH *ch )
2666 {
2667 	UINT32 step;
2668 	UINT8  data;
2669 
2670 
2671 	ch->now_step += ch->step;
2672 	if ( ch->now_step >= (1<<ADPCM_SHIFT) )
2673 	{
2674 		step = ch->now_step >> ADPCM_SHIFT;
2675 		ch->now_step &= (1<<ADPCM_SHIFT)-1;
2676 		do{
2677 			/* end check */
2678 			/* 11-06-2001 JB: corrected comparison. Was > instead of == */
2679 			/* YM2610 checks lower 20 bits only, the 4 MSB bits are sample bank */
2680 			/* Here we use 1<<21 to compensate for nibble calculations */
2681 
2682 			if (   (ch->now_addr & ((1<<21)-1)) == ((ch->end<<1) & ((1<<21)-1))	   )
2683 			{
2684 				ch->flag = 0;
2685 				F2610->adpcm_arrivedEndAddress |= ch->flagMask;
2686 				return;
2687 			}
2688 #if 0
2689 			if ( ch->now_addr > (pcmsizeA<<1) ) {
2690 				LOG(LOG_WAR,("YM2610: Attempting to play past adpcm rom size!\n" ));
2691 				return;
2692 			}
2693 #endif
2694 			if ( ch->now_addr&1 )
2695 				data = ch->now_data & 0x0f;
2696 			else
2697 			{
2698 				ch->now_data = *(pcmbufA+(ch->now_addr>>1));
2699 				data = (ch->now_data >> 4) & 0x0f;
2700 			}
2701 
2702 			ch->now_addr++;
2703 
2704 			ch->adpcm_acc += jedi_table[ch->adpcm_step + data];
2705 
2706             /* the 12-bit accumulator wraps on the ym2610 and ym2608 (like the msm5205), it does not saturate (like the msm5218) */
2707             ch->adpcm_acc &= 0xfff;
2708 
2709             /* extend 12-bit signed int */
2710 			if (ch->adpcm_acc & 0x800)
2711 				ch->adpcm_acc |= ~0xfff;
2712 
2713 			ch->adpcm_step += step_inc[data & 7];
2714 			Limit( ch->adpcm_step, 48*16, 0*16 );
2715 
2716 		}while(--step);
2717 
2718 		/* calc pcm * volume data */
2719 		ch->adpcm_out = ((ch->adpcm_acc * ch->vol_mul) >> ch->vol_shift) & ~3;	/* multiply, shift and mask out 2 LSB bits */
2720 	}
2721 
2722 	/* output for work of output channels (out_adpcm[OPNxxxx])*/
2723 	*(ch->pan) += ch->adpcm_out;
2724 }
2725 
2726 /* ADPCM type A Write */
FM_ADPCMAWrite(YM2610 * F2610,int r,int v)2727 static void FM_ADPCMAWrite(YM2610 *F2610,int r,int v)
2728 {
2729 	ADPCM_CH *adpcm = F2610->adpcm;
2730 	UINT8 c = r&0x07;
2731 
2732 	F2610->adpcmreg[r] = v&0xff; /* stock data */
2733 	switch( r ){
2734 	case 0x00: /* DM,--,C5,C4,C3,C2,C1,C0 */
2735 		if( !(v&0x80) )
2736 		{
2737 			/* KEY ON */
2738 			for( c = 0; c < 6; c++ )
2739 			{
2740 				if( (v>>c)&1 )
2741 				{
2742 					/**** start adpcm ****/
2743 					adpcm[c].step      = (UINT32)((float)(1<<ADPCM_SHIFT)*((float)F2610->OPN.ST.freqbase)/3.0f);
2744 					adpcm[c].now_addr  = adpcm[c].start<<1;
2745 					adpcm[c].now_step  = 0;
2746 					adpcm[c].adpcm_acc = 0;
2747 					adpcm[c].adpcm_step= 0;
2748 					adpcm[c].adpcm_out = 0;
2749 					adpcm[c].flag      = 1;
2750 
2751 					if(F2610->pcmbuf==NULL){					/* Check ROM Mapped */
2752 						logerror("YM2608-YM2610: ADPCM-A rom not mapped\n");
2753 						adpcm[c].flag = 0;
2754 					} else{
2755 						if(adpcm[c].end >= F2610->pcm_size){	/* Check End in Range */
2756 							logerror("YM2610: ADPCM-A end out of range: $%08x\n",adpcm[c].end);
2757 							/*adpcm[c].end = F2610->pcm_size-1;*/ /* JB: DO NOT uncomment this, otherwise you will break the comparison in the ADPCM_CALC_CHA() */
2758 						}
2759 						if(adpcm[c].start >= F2610->pcm_size)	/* Check Start in Range */
2760 						{
2761 							logerror("YM2608-YM2610: ADPCM-A start out of range: $%08x\n",adpcm[c].start);
2762 							adpcm[c].flag = 0;
2763 						}
2764 					}
2765 				}
2766 			}
2767 		}
2768 		else
2769 		{
2770 			/* KEY OFF */
2771 			for( c = 0; c < 6; c++ )
2772 				if( (v>>c)&1 )
2773 					adpcm[c].flag = 0;
2774 		}
2775 		break;
2776 	case 0x01:	/* B0-5 = TL */
2777 		F2610->adpcmTL = (v & 0x3f) ^ 0x3f;
2778 		for( c = 0; c < 6; c++ )
2779 		{
2780 			int volume = F2610->adpcmTL + adpcm[c].IL;
2781 
2782 			if ( volume >= 63 )	/* This is correct, 63 = quiet */
2783 			{
2784 				adpcm[c].vol_mul   = 0;
2785 				adpcm[c].vol_shift = 0;
2786 			}
2787 			else
2788 			{
2789 				adpcm[c].vol_mul   = 15 - (volume & 7);		/* so called 0.75 dB */
2790 				adpcm[c].vol_shift =  1 + (volume >> 3);	/* Yamaha engineers used the approximation: each -6 dB is close to divide by two (shift right) */
2791 			}
2792 
2793 			/* calc pcm * volume data */
2794 			adpcm[c].adpcm_out = ((adpcm[c].adpcm_acc * adpcm[c].vol_mul) >> adpcm[c].vol_shift) & ~3;	/* multiply, shift and mask out low 2 bits */
2795 		}
2796 		break;
2797 	default:
2798 		c = r&0x07;
2799 		if( c >= 0x06 ) return;
2800 		switch( r&0x38 ){
2801 		case 0x08:	/* B7=L,B6=R, B4-0=IL */
2802 		{
2803 			int volume;
2804 
2805 			adpcm[c].IL = (v & 0x1f) ^ 0x1f;
2806 
2807 			volume = F2610->adpcmTL + adpcm[c].IL;
2808 
2809 			if ( volume >= 63 )	/* This is correct, 63 = quiet */
2810 			{
2811 				adpcm[c].vol_mul   = 0;
2812 				adpcm[c].vol_shift = 0;
2813 			}
2814 			else
2815 			{
2816 				adpcm[c].vol_mul   = 15 - (volume & 7);		/* so called 0.75 dB */
2817 				adpcm[c].vol_shift =  1 + (volume >> 3);	/* Yamaha engineers used the approximation: each -6 dB is close to divide by two (shift right) */
2818 			}
2819 
2820 			adpcm[c].pan    = &out_adpcm[(v>>6)&0x03];
2821 
2822 			/* calc pcm * volume data */
2823 			adpcm[c].adpcm_out = ((adpcm[c].adpcm_acc * adpcm[c].vol_mul) >> adpcm[c].vol_shift) & ~3;	/* multiply, shift and mask out low 2 bits */
2824 		}
2825 			break;
2826 		case 0x10:
2827 		case 0x18:
2828 			adpcm[c].start  = ( (F2610->adpcmreg[0x18 + c]*0x0100 | F2610->adpcmreg[0x10 + c]) << ADPCMA_ADDRESS_SHIFT);
2829 			if ( pcmsizeA > 0x1000000 )         // KOF98AE sample banking support
2830 			{
2831 				if ( F2610->adpcmreg[0x08 + c] >= 0xf0 )
2832 				{
2833 					adpcm[c].start += 0x1000000;
2834 				}
2835 			}
2836 			break;
2837 		case 0x20:
2838 		case 0x28:
2839 			adpcm[c].end    = ( (F2610->adpcmreg[0x28 + c]*0x0100 | F2610->adpcmreg[0x20 + c]) << ADPCMA_ADDRESS_SHIFT);
2840 			adpcm[c].end   += (1<<ADPCMA_ADDRESS_SHIFT) - 1;
2841 			if ( pcmsizeA > 0x1000000 )         // KOF98AE sample banking support
2842 			{
2843 				if ( F2610->adpcmreg[0x08 + c] >= 0xf0 )
2844 				{
2845 					adpcm[c].end += 0x1000000;
2846 				}
2847 			}
2848 			break;
2849 		}
2850 	}
2851 }
2852 
2853 #ifdef _STATE_H
2854 /* FM channel save , internal state only */
FMsave_state_adpcma(const char * name,int num,ADPCM_CH * adpcm)2855 static void FMsave_state_adpcma(const char *name,int num,ADPCM_CH *adpcm)
2856 {
2857 	int ch;
2858 	char state_name[20];
2859 
2860 	for(ch=0;ch<6;ch++,adpcm++)
2861 	{
2862 		sprintf(state_name,"%s.CH%d",name,ch);
2863 
2864 		state_save_register_UINT8 (state_name, num, "flag"    , &adpcm->flag      , 1);
2865 		state_save_register_UINT8 (state_name, num, "data"    , &adpcm->now_data  , 1);
2866 		state_save_register_UINT32(state_name, num, "addr"    , &adpcm->now_addr  , 1);
2867 		state_save_register_UINT32(state_name, num, "step"    , &adpcm->now_step  , 1);
2868 		state_save_register_INT32 (state_name, num, "a_acc"   , &adpcm->adpcm_acc , 1);
2869 		state_save_register_INT32 (state_name, num, "a_step"  , &adpcm->adpcm_step, 1);
2870 		state_save_register_INT32 (state_name, num, "a_out"   , &adpcm->adpcm_out , 1);
2871 	}
2872 }
2873 #endif /* _STATE_H */
2874 
2875 #endif /* (BUILD_YM2608||BUILD_YM2610||BUILD_YM2610B) */
2876 
2877 
2878 #if BUILD_YM2608
2879 /*****************************************************************************/
2880 /*		YM2608 local section                                                 */
2881 /*****************************************************************************/
2882 static YM2608 *FM2608=NULL;	/* array of YM2608's */
2883 static int YM2608NumChips;	/* total chip */
2884 
2885 
2886 
2887 
2888 
2889 static unsigned int YM2608_ADPCM_ROM_addr[2*6] = {
2890 0x0000, 0x01bf, /* bass drum  */
2891 0x01c0, 0x043f, /* snare drum */
2892 0x0440, 0x1b7f, /* top cymbal */
2893 0x1b80, 0x1cff, /* high hat */
2894 0x1d00, 0x1f7f, /* tom tom  */
2895 0x1f80, 0x1fff  /* rim shot */
2896 };
2897 
2898 
2899 /*
2900 	This data is derived from the chip's output - internal ROM can't be read.
2901 	It was verified, using real YM2608, that this ADPCM stream produces 100% correct output signal.
2902 */
2903 
2904 static unsigned char *YM2608_ADPCM_ROM = NULL;
2905 
2906 /* flag enable control 0x110 */
YM2608IRQFlagWrite(FM_OPN * OPN,int n,int v)2907 INLINE void YM2608IRQFlagWrite(FM_OPN *OPN, int n, int v)
2908 {
2909 	YM2608 *F2608 = &(FM2608[n]);
2910 
2911 	if( v & 0x80 )
2912 	{	/* Reset IRQ flag */
2913 		FM_STATUS_RESET(&OPN->ST, 0xf7); /* don't touch BUFRDY flag otherwise we'd have to call ymdeltat module to set the flag back */
2914 	}
2915 	else
2916 	{	/* Set status flag mask */
2917 		F2608->flagmask = (~(v&0x1f));
2918 		FM_IRQMASK_SET(&OPN->ST, (F2608->irqmask & F2608->flagmask) );
2919 	}
2920 }
2921 
2922 /* compatible mode & IRQ enable control 0x29 */
YM2608IRQMaskWrite(FM_OPN * OPN,int n,int v)2923 INLINE void YM2608IRQMaskWrite(FM_OPN *OPN, int n, int v)
2924 {
2925 	YM2608 *F2608 = &(FM2608[n]);
2926 	/* SCH,xx,xxx,EN_ZERO,EN_BRDY,EN_EOS,EN_TB,EN_TA */
2927 
2928 	/* extend 3ch. enable/disable */
2929 	if(v&0x80)
2930 		OPN->type |= TYPE_6CH;	/* OPNA mode - 6 FM channels */
2931 	else
2932 		OPN->type &= ~TYPE_6CH;	/* OPN mode - 3 FM channels */
2933 
2934 	/* IRQ MASK store and set */
2935 	F2608->irqmask = v&0x1f;
2936 	FM_IRQMASK_SET(&OPN->ST, (F2608->irqmask & F2608->flagmask) );
2937 }
2938 
2939 /* Generate samples for one of the YM2608s */
YM2608UpdateOne(int num,INT16 ** buffer,int length)2940 void YM2608UpdateOne(int num, INT16 **buffer, int length)
2941 {
2942 	YM2608 *F2608 = &(FM2608[num]);
2943 	FM_OPN *OPN   = &(FM2608[num].OPN);
2944 	YM_DELTAT *DELTAT = &(F2608[num].deltaT);
2945 	int i,j;
2946 	FMSAMPLE  *bufL,*bufR;
2947 
2948 	/* set bufer */
2949 	bufL = buffer[0];
2950 	bufR = buffer[1];
2951 
2952 	if( (void *)F2608 != cur_chip ){
2953 		cur_chip = (void *)F2608;
2954 
2955 		State = &OPN->ST;
2956 		cch[0]   = &F2608->CH[0];
2957 		cch[1]   = &F2608->CH[1];
2958 		cch[2]   = &F2608->CH[2];
2959 		cch[3]   = &F2608->CH[3];
2960 		cch[4]   = &F2608->CH[4];
2961 		cch[5]   = &F2608->CH[5];
2962 		/* setup adpcm rom address */
2963 		pcmbufA  = F2608->pcmbuf;
2964 		pcmsizeA = F2608->pcm_size;
2965 
2966 	}
2967 
2968 	/* refresh PG and EG */
2969 	refresh_fc_eg_chan( OPN, cch[0] );
2970 	refresh_fc_eg_chan( OPN, cch[1] );
2971 	if( (State->mode & 0xc0) )
2972 	{
2973 		/* 3SLOT MODE */
2974 		if( cch[2]->SLOT[SLOT1].Incr==-1)
2975 		{
2976 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT1] , OPN->SL3.fc[1] , OPN->SL3.kcode[1] );
2977 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT2] , OPN->SL3.fc[2] , OPN->SL3.kcode[2] );
2978 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT3] , OPN->SL3.fc[0] , OPN->SL3.kcode[0] );
2979 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT4] , cch[2]->fc , cch[2]->kcode );
2980 		}
2981 	}else refresh_fc_eg_chan( OPN, cch[2] );
2982 	refresh_fc_eg_chan( OPN, cch[3] );
2983 	refresh_fc_eg_chan( OPN, cch[4] );
2984 	refresh_fc_eg_chan( OPN, cch[5] );
2985 
2986 
2987 	/* buffering */
2988 	for(i=0; i < length ; i++)
2989 	{
2990 
2991 		advance_lfo(OPN);
2992 
2993 		/* clear output acc. */
2994 		out_adpcm[OUTD_LEFT] = out_adpcm[OUTD_RIGHT]= out_adpcm[OUTD_CENTER] = 0;
2995 		out_delta[OUTD_LEFT] = out_delta[OUTD_RIGHT]= out_delta[OUTD_CENTER] = 0;
2996 		/* clear outputs */
2997 		out_fm[0] = 0;
2998 		out_fm[1] = 0;
2999 		out_fm[2] = 0;
3000 		out_fm[3] = 0;
3001 		out_fm[4] = 0;
3002 		out_fm[5] = 0;
3003 
3004 		/* advance envelope generator */
3005 		OPN->eg_timer += OPN->eg_timer_add;
3006 		while (OPN->eg_timer >= OPN->eg_timer_overflow)
3007 		{
3008 			OPN->eg_timer -= OPN->eg_timer_overflow;
3009 			OPN->eg_cnt++;
3010 
3011 			advance_eg_channel(OPN, &cch[0]->SLOT[SLOT1]);
3012 			advance_eg_channel(OPN, &cch[1]->SLOT[SLOT1]);
3013 			advance_eg_channel(OPN, &cch[2]->SLOT[SLOT1]);
3014 			advance_eg_channel(OPN, &cch[3]->SLOT[SLOT1]);
3015 			advance_eg_channel(OPN, &cch[4]->SLOT[SLOT1]);
3016 			advance_eg_channel(OPN, &cch[5]->SLOT[SLOT1]);
3017 		}
3018 
3019 		/* calculate FM */
3020 		chan_calc(OPN, cch[0], 0 );
3021 		chan_calc(OPN, cch[1], 1 );
3022 		chan_calc(OPN, cch[2], 2 );
3023 		chan_calc(OPN, cch[3], 3 );
3024 		chan_calc(OPN, cch[4], 4 );
3025 		chan_calc(OPN, cch[5], 5 );
3026 
3027 		/* deltaT ADPCM */
3028 		if( DELTAT->portstate&0x80 )
3029 			YM_DELTAT_ADPCM_CALC(DELTAT);
3030 
3031 		/* ADPCMA */
3032 		for( j = 0; j < 6; j++ )
3033 		{
3034 			if( F2608->adpcm[j].flag )
3035 				ADPCMA_calc_chan( F2608, &F2608->adpcm[j]);
3036 		}
3037 
3038 		/* buffering */
3039 		{
3040 			int lt,rt;
3041 
3042 			lt =  out_adpcm[OUTD_LEFT]  + out_adpcm[OUTD_CENTER];
3043 			rt =  out_adpcm[OUTD_RIGHT] + out_adpcm[OUTD_CENTER];
3044 			lt += (out_delta[OUTD_LEFT]  + out_delta[OUTD_CENTER])>>9;
3045 			rt += (out_delta[OUTD_RIGHT] + out_delta[OUTD_CENTER])>>9;
3046 			lt += ((out_fm[0]>>1) & OPN->pan[0]);	/* shift right verified on real YM2608 */
3047 			rt += ((out_fm[0]>>1) & OPN->pan[1]);
3048 			lt += ((out_fm[1]>>1) & OPN->pan[2]);
3049 			rt += ((out_fm[1]>>1) & OPN->pan[3]);
3050 			lt += ((out_fm[2]>>1) & OPN->pan[4]);
3051 			rt += ((out_fm[2]>>1) & OPN->pan[5]);
3052 			lt += ((out_fm[3]>>1) & OPN->pan[6]);
3053 			rt += ((out_fm[3]>>1) & OPN->pan[7]);
3054 			lt += ((out_fm[4]>>1) & OPN->pan[8]);
3055 			rt += ((out_fm[4]>>1) & OPN->pan[9]);
3056 			lt += ((out_fm[5]>>1) & OPN->pan[10]);
3057 			rt += ((out_fm[5]>>1) & OPN->pan[11]);
3058 
3059 			lt >>= FINAL_SH;
3060 			rt >>= FINAL_SH;
3061 
3062 			Limit( lt, MAXOUT, MINOUT );
3063 			Limit( rt, MAXOUT, MINOUT );
3064 			/* buffering */
3065 			bufL[i] = lt;
3066 			bufR[i] = rt;
3067 
3068 			#ifdef SAVE_SAMPLE
3069 				SAVE_ALL_CHANNELS
3070 			#endif
3071 
3072 		}
3073 
3074 		/* timer A control */
3075 		INTERNAL_TIMER_A( State , cch[2] )
3076 	}
3077 	INTERNAL_TIMER_B(State,length)
3078 
3079 
3080 	/* check IRQ for DELTA-T EOS */
3081 	FM_STATUS_SET(State, 0);
3082 
3083 }
3084 #ifdef _STATE_H
YM2608_postload(void)3085 static void YM2608_postload(void)
3086 {
3087 	int num , r;
3088 
3089 	for(num=0;num<YM2608NumChips;num++)
3090 	{
3091 		YM2608 *F2608 = &(FM2608[num]);
3092 		/* prescaler */
3093 		OPNPrescaler_w(&F2608->OPN,1,2);
3094 		F2608->deltaT.freqbase = F2608->OPN.ST.freqbase;
3095 		/* IRQ mask / mode */
3096 		YM2608IRQMaskWrite(&F2608->OPN, num, F2608->REGS[0x29]);
3097 		/* SSG registers */
3098 		for(r=0;r<16;r++)
3099 		{
3100 			SSGWrite(num,0,r);
3101 			SSGWrite(num,1,F2608->REGS[r]);
3102 		}
3103 
3104 		/* OPN registers */
3105 		/* DT / MULTI , TL , KS / AR , AMON / DR , SR , SL / RR , SSG-EG */
3106 		for(r=0x30;r<0x9e;r++)
3107 			if((r&3) != 3)
3108 			{
3109 				OPNWriteReg(&F2608->OPN,r,F2608->REGS[r]);
3110 				OPNWriteReg(&F2608->OPN,r|0x100,F2608->REGS[r|0x100]);
3111 			}
3112 		/* FB / CONNECT , L / R / AMS / PMS */
3113 		for(r=0xb0;r<0xb6;r++)
3114 			if((r&3) != 3)
3115 			{
3116 				OPNWriteReg(&F2608->OPN,r,F2608->REGS[r]);
3117 				OPNWriteReg(&F2608->OPN,r|0x100,F2608->REGS[r|0x100]);
3118 			}
3119 		/* FM channels */
3120 		/*FM_channel_postload(F2608->CH,6);*/
3121 		/* rhythm(ADPCMA) */
3122 		FM_ADPCMAWrite(F2608,1,F2608->REGS[0x111]);
3123 		for( r=0x08 ; r<0x0c ; r++)
3124 			FM_ADPCMAWrite(F2608,r,F2608->REGS[r+0x110]);
3125 		/* Delta-T ADPCM unit */
3126 		YM_DELTAT_postload(&F2608->deltaT , &F2608->REGS[0x100] );
3127 	}
3128 	cur_chip = NULL;
3129 }
3130 
YM2608_save_state(void)3131 static void YM2608_save_state(void)
3132 {
3133 	int num;
3134 	const char statename[] = "YM2608";
3135 
3136 	for(num=0;num<YM2608NumChips;num++)
3137 	{
3138 		YM2608 *F2608 = &(FM2608[num]);
3139 
3140 		state_save_register_UINT8 (statename, num, "regs"   , F2608->REGS   , 512);
3141 		FMsave_state_st(statename,num,&FM2608[num].OPN.ST);
3142 		FMsave_state_channel(statename,num,FM2608[num].CH,6);
3143 		/* 3slots */
3144 		state_save_register_UINT32(statename, num, "slot3fc" , F2608->OPN.SL3.fc   , 3);
3145 		state_save_register_UINT8 (statename, num, "slot3fh" , &F2608->OPN.SL3.fn_h, 1);
3146 		state_save_register_UINT8 (statename, num, "slot3kc" , F2608->OPN.SL3.kcode, 3);
3147 		/* address register1 */
3148 		state_save_register_UINT8 (statename, num, "addr_A1" , &F2608->addr_A1 ,1);
3149 		/* rythm(ADPCMA) */
3150 		FMsave_state_adpcma(statename,num,F2608->adpcm);
3151 		/* Delta-T ADPCM unit */
3152 		YM_DELTAT_savestate(statename,num,&FM2608[num].deltaT);
3153 	}
3154 	state_save_register_func_postload(YM2608_postload);
3155 }
3156 #endif /* _STATE_H */
3157 
YM2608_deltat_status_set(UINT8 which,UINT8 changebits)3158 static void YM2608_deltat_status_set(UINT8 which, UINT8 changebits)
3159 {
3160 	FM_STATUS_SET(&(FM2608[which].OPN.ST), changebits);
3161 }
YM2608_deltat_status_reset(UINT8 which,UINT8 changebits)3162 static void YM2608_deltat_status_reset(UINT8 which, UINT8 changebits)
3163 {
3164 	FM_STATUS_RESET(&(FM2608[which].OPN.ST), changebits);
3165 }
3166 /* YM2608(OPNA) */
YM2608Init(int num,int clock,int rate,void ** pcmrom,int * pcmsize,unsigned char * irom,FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)3167 int YM2608Init(int num, int clock, int rate,
3168                void **pcmrom,int *pcmsize, unsigned char *irom,
3169                FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)
3170 {
3171 	int i;
3172 
3173 	if (FM2608) return (-1);	/* duplicate init. */
3174 	cur_chip = NULL;
3175 
3176 	YM2608NumChips = num;
3177 
3178 	YM2608_ADPCM_ROM = irom;
3179 
3180 	/* allocate extend state space */
3181 	if( (FM2608 = (YM2608 *)malloc(sizeof(YM2608) * YM2608NumChips))==NULL)
3182 		return (-1);
3183 	/* clear */
3184 	memset(FM2608,0,sizeof(YM2608) * YM2608NumChips);
3185 	/* allocate total level table (128kb space) */
3186 	if( !init_tables() )
3187 	{
3188 		if (FM2608) {
3189 			free( FM2608 );
3190 			FM2608 = NULL;
3191 		}
3192 		return (-1);
3193 	}
3194 
3195 	for ( i = 0 ; i < YM2608NumChips; i++ ) {
3196 		FM2608[i].OPN.ST.index = i;
3197 		FM2608[i].OPN.type = TYPE_YM2608;
3198 		FM2608[i].OPN.P_CH = FM2608[i].CH;
3199 		FM2608[i].OPN.ST.clock = clock;
3200 		FM2608[i].OPN.ST.rate = rate;
3201 
3202 		/* External handlers */
3203 		FM2608[i].OPN.ST.Timer_Handler = TimerHandler;
3204 		FM2608[i].OPN.ST.IRQ_Handler   = IRQHandler;
3205 
3206 		/* DELTA-T */
3207 		FM2608[i].deltaT.memory = (UINT8 *)(pcmrom[i]);
3208 		FM2608[i].deltaT.memory_size = pcmsize[i];
3209 
3210 		/*FM2608[i].deltaT.write_time = 20.0 / clock;*/	/* a single byte write takes 20 cycles of main clock */
3211 		/*FM2608[i].deltaT.read_time  = 18.0 / clock;*/	/* a single byte read takes 18 cycles of main clock */
3212 
3213 		FM2608[i].deltaT.status_set_handler = YM2608_deltat_status_set;
3214 		FM2608[i].deltaT.status_reset_handler = YM2608_deltat_status_reset;
3215 		FM2608[i].deltaT.status_change_which_chip = i;
3216 		FM2608[i].deltaT.status_change_EOS_bit = 0x04;	/* status flag: set bit2 on End Of Sample */
3217 		FM2608[i].deltaT.status_change_BRDY_bit = 0x08;	/* status flag: set bit3 on BRDY */
3218 		FM2608[i].deltaT.status_change_ZERO_bit = 0x10;	/* status flag: set bit4 if silence continues for more than 290 miliseconds while recording the ADPCM */
3219 
3220 		/* ADPCM Rhythm */
3221 		FM2608[i].pcmbuf   = YM2608_ADPCM_ROM;
3222 		FM2608[i].pcm_size = 0x2000;
3223 
3224 		YM2608ResetChip(i);
3225 	}
3226 
3227 	Init_ADPCMATable();
3228 
3229 #ifdef _STATE_H
3230 	YM2608_save_state();
3231 #endif
3232 	return 0;
3233 }
3234 
3235 /* shut down emulator */
YM2608Shutdown()3236 void YM2608Shutdown()
3237 {
3238 	if (!FM2608) return;
3239 
3240 	FMCloseTable();
3241 	if (FM2608) {
3242 		free(FM2608);
3243 		FM2608 = NULL;
3244 	}
3245 
3246 	YM2608_ADPCM_ROM = NULL;
3247 }
3248 
3249 /* reset one of chips */
YM2608ResetChip(int num)3250 void YM2608ResetChip(int num)
3251 {
3252 	int i;
3253 	YM2608 *F2608 = &(FM2608[num]);
3254 	FM_OPN *OPN   = &(FM2608[num].OPN);
3255 	YM_DELTAT *DELTAT = &(F2608[num].deltaT);
3256 
3257 	/* Reset Prescaler */
3258 	OPNPrescaler_w(OPN , 0 , 2);
3259 	F2608->deltaT.freqbase = OPN->ST.freqbase;
3260 	/* reset SSG section */
3261 	SSGReset(OPN->ST.index);
3262 
3263 	/* status clear */
3264 	FM_BUSY_CLEAR(&OPN->ST);
3265 
3266 	/* register 0x29 - default value after reset is:
3267 		enable only 3 FM channels and enable all the status flags */
3268 	YM2608IRQMaskWrite(OPN, num, 0x1f );	/* default value for D4-D0 is 1 */
3269 
3270 	/* register 0x10, A1=1 - default value is 1 for D4, D3, D2, 0 for the rest */
3271 	YM2608IRQFlagWrite(OPN, num, 0x1c );	/* default: enable timer A and B, disable EOS, BRDY and ZERO */
3272 
3273 	OPNWriteMode(OPN,0x27,0x30);	/* mode 0 , timer reset */
3274 
3275 	OPN->eg_timer = 0;
3276 	OPN->eg_cnt   = 0;
3277 
3278 	FM_STATUS_RESET(&OPN->ST, 0xff);
3279 
3280 	reset_channels( &OPN->ST , F2608->CH , 6 );
3281 	/* reset OPerator paramater */
3282 	for(i = 0xb6 ; i >= 0xb4 ; i-- )
3283 	{
3284 		OPNWriteReg(OPN,i      ,0xc0);
3285 		OPNWriteReg(OPN,i|0x100,0xc0);
3286 	}
3287 	for(i = 0xb2 ; i >= 0x30 ; i-- )
3288 	{
3289 		OPNWriteReg(OPN,i      ,0);
3290 		OPNWriteReg(OPN,i|0x100,0);
3291 	}
3292 	for(i = 0x26 ; i >= 0x20 ; i-- ) OPNWriteReg(OPN,i,0);
3293 
3294 	/* ADPCM - percussion sounds */
3295 	for( i = 0; i < 6; i++ )
3296 	{
3297 		if (i<=3)	/* channels 0,1,2,3 */
3298 			F2608->adpcm[i].step      = (UINT32)((float)(1<<ADPCM_SHIFT)*((float)F2608->OPN.ST.freqbase)/3.0);
3299 		else		/* channels 4 and 5 work with slower clock */
3300 			F2608->adpcm[i].step      = (UINT32)((float)(1<<ADPCM_SHIFT)*((float)F2608->OPN.ST.freqbase)/6.0);
3301 
3302 		F2608->adpcm[i].start     = YM2608_ADPCM_ROM_addr[i*2];
3303 		F2608->adpcm[i].end       = YM2608_ADPCM_ROM_addr[i*2+1];
3304 
3305 		F2608->adpcm[i].now_addr  = 0;
3306 		F2608->adpcm[i].now_step  = 0;
3307 		/* F2608->adpcm[i].delta     = 21866; */
3308 		F2608->adpcm[i].vol_mul   = 0;
3309 		F2608->adpcm[i].pan       = &out_adpcm[OUTD_CENTER]; /* default center */
3310 		F2608->adpcm[i].flagMask  = 0;
3311 		F2608->adpcm[i].flag      = 0;
3312 		F2608->adpcm[i].adpcm_acc = 0;
3313 		F2608->adpcm[i].adpcm_step= 0;
3314 		F2608->adpcm[i].adpcm_out = 0;
3315 	}
3316 	F2608->adpcmTL = 0x3f;
3317 
3318 	F2608->adpcm_arrivedEndAddress = 0; /* not used */
3319 
3320 	/* DELTA-T unit */
3321 	DELTAT->freqbase = OPN->ST.freqbase;
3322 	DELTAT->output_pointer = out_delta;
3323 	DELTAT->portshift = 5;		/* always 5bits shift */ /* ASG */
3324 	DELTAT->output_range = 1<<23;
3325 	YM_DELTAT_ADPCM_Reset(DELTAT,OUTD_CENTER,YM_DELTAT_EMULATION_MODE_NORMAL);
3326 }
3327 
3328 /* YM2608 write */
3329 /* n = number  */
3330 /* a = address */
3331 /* v = value   */
YM2608Write(int n,int a,UINT8 v)3332 int YM2608Write(int n, int a,UINT8 v)
3333 {
3334 	YM2608 *F2608 = &(FM2608[n]);
3335 	FM_OPN *OPN   = &(FM2608[n].OPN);
3336 	int addr;
3337 
3338 	v &= 0xff;	/*adjust to 8 bit bus */
3339 
3340 
3341 	switch(a&3)
3342 	{
3343 	case 0:	/* address port 0 */
3344 		OPN->ST.address = v;
3345 		F2608->addr_A1 = 0;
3346 
3347 		/* Write register to SSG emulator */
3348 		if( v < 16 ) SSGWrite(n,0,v);
3349 		/* prescaler selecter : 2d,2e,2f  */
3350 		if( v >= 0x2d && v <= 0x2f )
3351 		{
3352 			OPNPrescaler_w(OPN , v , 2);
3353 			F2608->deltaT.freqbase = OPN->ST.freqbase;
3354 		}
3355 		break;
3356 
3357 	case 1:	/* data port 0    */
3358 		if (F2608->addr_A1 != 0)
3359 			break;	/* verified on real YM2608 */
3360 
3361 		addr = OPN->ST.address;
3362 #ifdef _STATE_H
3363 		F2608->REGS[addr] = v;
3364 #endif
3365 		switch(addr & 0xf0)
3366 		{
3367 		case 0x00:	/* SSG section */
3368 			/* Write data to SSG emulator */
3369 			SSGWrite(n,a,v);
3370 			break;
3371 		case 0x10:	/* 0x10-0x1f : Rhythm section */
3372 			YM2608UpdateReq(n);
3373 			FM_ADPCMAWrite(F2608,addr-0x10,v);
3374 			break;
3375 		case 0x20:	/* Mode Register */
3376 			switch(addr)
3377 			{
3378 			case 0x29: 	/* SCH,xx,xxx,EN_ZERO,EN_BRDY,EN_EOS,EN_TB,EN_TA */
3379 				YM2608IRQMaskWrite(OPN, n, v);
3380 				break;
3381 			default:
3382 				YM2608UpdateReq(n);
3383 				OPNWriteMode(OPN,addr,v);
3384 			}
3385 			break;
3386 		default:	/* OPN section */
3387 			YM2608UpdateReq(n);
3388 			OPNWriteReg(OPN,addr,v);
3389 		}
3390 		break;
3391 
3392 	case 2:	/* address port 1 */
3393 		OPN->ST.address = v;
3394 		F2608->addr_A1 = 1;
3395 		break;
3396 
3397 	case 3:	/* data port 1    */
3398 		if (F2608->addr_A1 != 1)
3399 			break;	/* verified on real YM2608 */
3400 
3401 		addr = OPN->ST.address;
3402 #ifdef _STATE_H
3403 		F2608->REGS[addr | 0x100] = v;
3404 #endif
3405 		YM2608UpdateReq(n);
3406 		switch( addr & 0xf0 )
3407 		{
3408 		case 0x00:	/* DELTAT PORT */
3409 			switch( addr )
3410 			{
3411 			case 0x0e:	/* DAC data */
3412 				logerror("YM2608: write to DAC data (unimplemented) value=%02x\n",v);
3413 				break;
3414 			default:
3415 				/* 0x00-0x0d */
3416 				YM_DELTAT_ADPCM_Write(&F2608->deltaT,addr,v);
3417 			}
3418 			break;
3419 		case 0x10:	/* IRQ Flag control */
3420 			if( addr == 0x10 )
3421 			{
3422 				YM2608IRQFlagWrite(OPN, n, v);
3423 			}
3424 			break;
3425 		default:
3426 			OPNWriteReg(OPN,addr | 0x100,v);
3427 		}
3428 	}
3429 	return OPN->ST.irq;
3430 }
3431 
YM2608Read(int n,int a)3432 UINT8 YM2608Read(int n,int a)
3433 {
3434 	YM2608 *F2608 = &(FM2608[n]);
3435 	int addr = F2608->OPN.ST.address;
3436 	UINT8 ret = 0;
3437 
3438 	switch( a&3 ){
3439 	case 0:	/* status 0 : YM2203 compatible */
3440 		/* BUSY:x:x:x:x:x:FLAGB:FLAGA */
3441 		ret = FM_STATUS_FLAG(&F2608->OPN.ST) & 0x83;
3442 		break;
3443 
3444 	case 1:	/* status 0, ID  */
3445 		if( addr < 16 ) ret = SSGRead(n);
3446 		else if(addr == 0xff) ret = 0x01; /* ID code */
3447 		break;
3448 
3449 	case 2:	/* status 1 : status 0 + ADPCM status */
3450 		/* BUSY : x : PCMBUSY : ZERO : BRDY : EOS : FLAGB : FLAGA */
3451 		ret = (FM_STATUS_FLAG(&F2608->OPN.ST) & (F2608->flagmask|0x80)) | ((F2608->deltaT.PCM_BSY & 1)<<5) ;
3452 		break;
3453 
3454 	case 3:
3455 		if(addr == 0x08)
3456 		{
3457 			ret = YM_DELTAT_ADPCM_Read(&F2608->deltaT);
3458 		}
3459 		else
3460 		{
3461 			if(addr == 0x0f)
3462 			{
3463 				logerror("YM2608 A/D convertion is accessed but not implemented !\n");
3464 				ret = 0x80; /* 2's complement PCM data - result from A/D convertion */
3465 			}
3466 		}
3467 		break;
3468 	}
3469 	return ret;
3470 }
3471 
YM2608TimerOver(int n,int c)3472 int YM2608TimerOver(int n,int c)
3473 {
3474 	YM2608 *F2608 = &(FM2608[n]);
3475 
3476     switch(c)
3477 	{
3478 #if 0
3479 	case 2:
3480 		{	/* BUFRDY flag */
3481 			YM_DELTAT_BRDY_callback( &F2608->deltaT );
3482 		}
3483 		break;
3484 #endif
3485 	case 1:
3486 		{	/* Timer B */
3487 			TimerBOver( &(F2608->OPN.ST) );
3488 		}
3489 		break;
3490 	case 0:
3491 		{	/* Timer A */
3492 			YM2608UpdateReq(n);
3493 			/* timer update */
3494 			TimerAOver( &(F2608->OPN.ST) );
3495 			/* CSM mode key,TL controll */
3496 			if( F2608->OPN.ST.mode & 0x80 )
3497 			{	/* CSM mode total level latch and auto key on */
3498 				CSMKeyControll( F2608->OPN.type, &(F2608->CH[2]) );
3499 			}
3500 		}
3501 		break;
3502 	default:
3503 		break;
3504     }
3505 
3506 	return FM2608->OPN.ST.irq;
3507 }
3508 
3509 #endif /* BUILD_YM2608 */
3510 
3511 
3512 
3513 #if (BUILD_YM2610||BUILD_YM2610B)
3514 /* YM2610(OPNB) */
3515 static YM2610 *FM2610=NULL;	/* array of YM2610's */
3516 static int YM2610NumChips;
3517 
3518 /* Generate samples for one of the YM2610s */
YM2610UpdateOne(int num,INT16 ** buffer,int length)3519 void YM2610UpdateOne(int num, INT16 **buffer, int length)
3520 {
3521 	YM2610 *F2610 = &(FM2610[num]);
3522 	FM_OPN *OPN   = &(FM2610[num].OPN);
3523 	YM_DELTAT *DELTAT = &(F2610[num].deltaT);
3524 	int i,j;
3525 	FMSAMPLE  *bufL,*bufR;
3526 
3527 	/* buffer setup */
3528 	bufL = buffer[0];
3529 	bufR = buffer[1];
3530 
3531 	if( (void *)F2610 != cur_chip ){
3532 		cur_chip = (void *)F2610;
3533 		State = &OPN->ST;
3534 		cch[0] = &F2610->CH[1];
3535 		cch[1] = &F2610->CH[2];
3536 		cch[2] = &F2610->CH[4];
3537 		cch[3] = &F2610->CH[5];
3538 		/* setup adpcm rom address */
3539 		pcmbufA  = F2610->pcmbuf;
3540 		pcmsizeA = F2610->pcm_size;
3541 
3542 	}
3543 #ifdef YM2610B_WARNING
3544 #define FM_KEY_IS(SLOT) ((SLOT)->key)
3545 #define FM_MSG_YM2610B "YM2610-%d.CH%d is playing,Check whether the type of the chip is YM2610B\n"
3546 	/* Check YM2610B warning message */
3547 	if( FM_KEY_IS(&F2610->CH[0].SLOT[3]) )
3548 		LOG(LOG_WAR,(FM_MSG_YM2610B,num,0));
3549 	if( FM_KEY_IS(&F2610->CH[3].SLOT[3]) )
3550 		LOG(LOG_WAR,(FM_MSG_YM2610B,num,3));
3551 #endif
3552 
3553 	/* refresh PG and EG */
3554 	refresh_fc_eg_chan( OPN, cch[0] );
3555 	if( (State->mode & 0xc0) )
3556 	{
3557 		/* 3SLOT MODE */
3558 		if( cch[1]->SLOT[SLOT1].Incr==-1)
3559 		{
3560 			refresh_fc_eg_slot(OPN, &cch[1]->SLOT[SLOT1] , OPN->SL3.fc[1] , OPN->SL3.kcode[1] );
3561 			refresh_fc_eg_slot(OPN, &cch[1]->SLOT[SLOT2] , OPN->SL3.fc[2] , OPN->SL3.kcode[2] );
3562 			refresh_fc_eg_slot(OPN, &cch[1]->SLOT[SLOT3] , OPN->SL3.fc[0] , OPN->SL3.kcode[0] );
3563 			refresh_fc_eg_slot(OPN, &cch[1]->SLOT[SLOT4] , cch[1]->fc , cch[1]->kcode );
3564 		}
3565 	}else refresh_fc_eg_chan( OPN, cch[1] );
3566 	refresh_fc_eg_chan( OPN, cch[2] );
3567 	refresh_fc_eg_chan( OPN, cch[3] );
3568 
3569 	/* buffering */
3570 	for(i=0; i < length ; i++)
3571 	{
3572 
3573 		advance_lfo(OPN);
3574 
3575 		/* clear output acc. */
3576 		out_adpcm[OUTD_LEFT] = out_adpcm[OUTD_RIGHT]= out_adpcm[OUTD_CENTER] = 0;
3577 		out_delta[OUTD_LEFT] = out_delta[OUTD_RIGHT]= out_delta[OUTD_CENTER] = 0;
3578 		/* clear outputs */
3579 		out_fm[1] = 0;
3580 		out_fm[2] = 0;
3581 		out_fm[4] = 0;
3582 		out_fm[5] = 0;
3583 
3584 		/* advance envelope generator */
3585 		OPN->eg_timer += OPN->eg_timer_add;
3586 		while (OPN->eg_timer >= OPN->eg_timer_overflow)
3587 		{
3588 			OPN->eg_timer -= OPN->eg_timer_overflow;
3589 			OPN->eg_cnt++;
3590 
3591 			advance_eg_channel(OPN, &cch[0]->SLOT[SLOT1]);
3592 			advance_eg_channel(OPN, &cch[1]->SLOT[SLOT1]);
3593 			advance_eg_channel(OPN, &cch[2]->SLOT[SLOT1]);
3594 			advance_eg_channel(OPN, &cch[3]->SLOT[SLOT1]);
3595 		}
3596 
3597 		/* calculate FM */
3598 		chan_calc(OPN, cch[0], 1 );	/*remapped to 1*/
3599 		chan_calc(OPN, cch[1], 2 );	/*remapped to 2*/
3600 		chan_calc(OPN, cch[2], 4 );	/*remapped to 4*/
3601 		chan_calc(OPN, cch[3], 5 );	/*remapped to 5*/
3602 
3603 		/* deltaT ADPCM */
3604 		if( DELTAT->portstate&0x80 )
3605 			YM_DELTAT_ADPCM_CALC(DELTAT);
3606 
3607 		/* ADPCMA */
3608 		for( j = 0; j < 6; j++ )
3609 		{
3610 			if( F2610->adpcm[j].flag )
3611 				ADPCMA_calc_chan( F2610, &F2610->adpcm[j]);
3612 		}
3613 
3614 		/* buffering */
3615 		{
3616 			int lt,rt;
3617 
3618 			lt =  out_adpcm[OUTD_LEFT]  + out_adpcm[OUTD_CENTER];
3619 			rt =  out_adpcm[OUTD_RIGHT] + out_adpcm[OUTD_CENTER];
3620 			lt += (out_delta[OUTD_LEFT]  + out_delta[OUTD_CENTER])>>9;
3621 			rt += (out_delta[OUTD_RIGHT] + out_delta[OUTD_CENTER])>>9;
3622 
3623 
3624 			lt += ((out_fm[1]>>1) & OPN->pan[2]);	/* the shift right was verified on real chip */
3625 			rt += ((out_fm[1]>>1) & OPN->pan[3]);
3626 			lt += ((out_fm[2]>>1) & OPN->pan[4]);
3627 			rt += ((out_fm[2]>>1) & OPN->pan[5]);
3628 
3629 			lt += ((out_fm[4]>>1) & OPN->pan[8]);
3630 			rt += ((out_fm[4]>>1) & OPN->pan[9]);
3631 			lt += ((out_fm[5]>>1) & OPN->pan[10]);
3632 			rt += ((out_fm[5]>>1) & OPN->pan[11]);
3633 
3634 
3635 			lt >>= FINAL_SH;
3636 			rt >>= FINAL_SH;
3637 
3638 			Limit( lt, MAXOUT, MINOUT );
3639 			Limit( rt, MAXOUT, MINOUT );
3640 
3641 			#ifdef SAVE_SAMPLE
3642 				SAVE_ALL_CHANNELS
3643 			#endif
3644 
3645 			/* buffering */
3646 			bufL[i] = lt;
3647 			bufR[i] = rt;
3648 		}
3649 
3650 		/* timer A control */
3651 		INTERNAL_TIMER_A( State , cch[1] )
3652 	}
3653 	INTERNAL_TIMER_B(State,length)
3654 
3655 }
3656 
3657 #if BUILD_YM2610B
3658 /* Generate samples for one of the YM2610Bs */
YM2610BUpdateOne(int num,INT16 ** buffer,int length)3659 void YM2610BUpdateOne(int num, INT16 **buffer, int length)
3660 {
3661 	YM2610 *F2610 = &(FM2610[num]);
3662 	FM_OPN *OPN   = &(FM2610[num].OPN);
3663 	YM_DELTAT *DELTAT = &(FM2610[num].deltaT);
3664 	int i,j;
3665 	FMSAMPLE  *bufL,*bufR;
3666 
3667 	/* buffer setup */
3668 	bufL = buffer[0];
3669 	bufR = buffer[1];
3670 
3671 	if( (void *)F2610 != cur_chip ){
3672 		cur_chip = (void *)F2610;
3673 		State = &OPN->ST;
3674 		cch[0] = &F2610->CH[0];
3675 		cch[1] = &F2610->CH[1];
3676 		cch[2] = &F2610->CH[2];
3677 		cch[3] = &F2610->CH[3];
3678 		cch[4] = &F2610->CH[4];
3679 		cch[5] = &F2610->CH[5];
3680 		/* setup adpcm rom address */
3681 		pcmbufA  = F2610->pcmbuf;
3682 		pcmsizeA = F2610->pcm_size;
3683 
3684 	}
3685 
3686 	/* refresh PG and EG */
3687 	refresh_fc_eg_chan( OPN, cch[0] );
3688 	refresh_fc_eg_chan( OPN, cch[1] );
3689 	if( (State->mode & 0xc0) )
3690 	{
3691 		/* 3SLOT MODE */
3692 		if( cch[2]->SLOT[SLOT1].Incr==-1)
3693 		{
3694 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT1] , OPN->SL3.fc[1] , OPN->SL3.kcode[1] );
3695 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT2] , OPN->SL3.fc[2] , OPN->SL3.kcode[2] );
3696 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT3] , OPN->SL3.fc[0] , OPN->SL3.kcode[0] );
3697 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT4] , cch[2]->fc , cch[2]->kcode );
3698 		}
3699 	}else refresh_fc_eg_chan( OPN, cch[2] );
3700 	refresh_fc_eg_chan( OPN, cch[3] );
3701 	refresh_fc_eg_chan( OPN, cch[4] );
3702 	refresh_fc_eg_chan( OPN, cch[5] );
3703 
3704 	/* buffering */
3705 	for(i=0; i < length ; i++)
3706 	{
3707 
3708 		advance_lfo(OPN);
3709 
3710 		/* clear output acc. */
3711 		out_adpcm[OUTD_LEFT] = out_adpcm[OUTD_RIGHT]= out_adpcm[OUTD_CENTER] = 0;
3712 		out_delta[OUTD_LEFT] = out_delta[OUTD_RIGHT]= out_delta[OUTD_CENTER] = 0;
3713 		/* clear outputs */
3714 		out_fm[0] = 0;
3715 		out_fm[1] = 0;
3716 		out_fm[2] = 0;
3717 		out_fm[3] = 0;
3718 		out_fm[4] = 0;
3719 		out_fm[5] = 0;
3720 
3721 		/* advance envelope generator */
3722 		OPN->eg_timer += OPN->eg_timer_add;
3723 		while (OPN->eg_timer >= OPN->eg_timer_overflow)
3724 		{
3725 			OPN->eg_timer -= OPN->eg_timer_overflow;
3726 			OPN->eg_cnt++;
3727 
3728 			advance_eg_channel(OPN, &cch[0]->SLOT[SLOT1]);
3729 			advance_eg_channel(OPN, &cch[1]->SLOT[SLOT1]);
3730 			advance_eg_channel(OPN, &cch[2]->SLOT[SLOT1]);
3731 			advance_eg_channel(OPN, &cch[3]->SLOT[SLOT1]);
3732 			advance_eg_channel(OPN, &cch[4]->SLOT[SLOT1]);
3733 			advance_eg_channel(OPN, &cch[5]->SLOT[SLOT1]);
3734 		}
3735 
3736 		/* calculate FM */
3737 		chan_calc(OPN, cch[0], 0 );
3738 		chan_calc(OPN, cch[1], 1 );
3739 		chan_calc(OPN, cch[2], 2 );
3740 		chan_calc(OPN, cch[3], 3 );
3741 		chan_calc(OPN, cch[4], 4 );
3742 		chan_calc(OPN, cch[5], 5 );
3743 
3744 		/* deltaT ADPCM */
3745 		if( DELTAT->portstate&0x80 )
3746 			YM_DELTAT_ADPCM_CALC(DELTAT);
3747 
3748 		/* ADPCMA */
3749 		for( j = 0; j < 6; j++ )
3750 		{
3751 			if( F2610->adpcm[j].flag )
3752 				ADPCMA_calc_chan( F2610, &F2610->adpcm[j]);
3753 		}
3754 
3755 		/* buffering */
3756 		{
3757 			int lt,rt;
3758 
3759 			lt =  out_adpcm[OUTD_LEFT]  + out_adpcm[OUTD_CENTER];
3760 			rt =  out_adpcm[OUTD_RIGHT] + out_adpcm[OUTD_CENTER];
3761 			lt += (out_delta[OUTD_LEFT]  + out_delta[OUTD_CENTER])>>9;
3762 			rt += (out_delta[OUTD_RIGHT] + out_delta[OUTD_CENTER])>>9;
3763 
3764 			lt += ((out_fm[0]>>1) & OPN->pan[0]);	/* the shift right is verified on YM2610 */
3765 			rt += ((out_fm[0]>>1) & OPN->pan[1]);
3766 			lt += ((out_fm[1]>>1) & OPN->pan[2]);
3767 			rt += ((out_fm[1]>>1) & OPN->pan[3]);
3768 			lt += ((out_fm[2]>>1) & OPN->pan[4]);
3769 			rt += ((out_fm[2]>>1) & OPN->pan[5]);
3770 			lt += ((out_fm[3]>>1) & OPN->pan[6]);
3771 			rt += ((out_fm[3]>>1) & OPN->pan[7]);
3772 			lt += ((out_fm[4]>>1) & OPN->pan[8]);
3773 			rt += ((out_fm[4]>>1) & OPN->pan[9]);
3774 			lt += ((out_fm[5]>>1) & OPN->pan[10]);
3775 			rt += ((out_fm[5]>>1) & OPN->pan[11]);
3776 
3777 
3778 			lt >>= FINAL_SH;
3779 			rt >>= FINAL_SH;
3780 
3781 			Limit( lt, MAXOUT, MINOUT );
3782 			Limit( rt, MAXOUT, MINOUT );
3783 
3784 			#ifdef SAVE_SAMPLE
3785 				SAVE_ALL_CHANNELS
3786 			#endif
3787 
3788 			/* buffering */
3789 			bufL[i] = lt;
3790 			bufR[i] = rt;
3791 		}
3792 
3793 		/* timer A control */
3794 		INTERNAL_TIMER_A( State , cch[2] )
3795 	}
3796 	INTERNAL_TIMER_B(State,length)
3797 
3798 }
3799 #endif /* BUILD_YM2610B */
3800 
3801 
3802 #ifdef _STATE_H
YM2610_postload(void)3803 static void YM2610_postload(void)
3804 {
3805 	int num , r;
3806 
3807 	for(num=0;num<YM2610NumChips;num++)
3808 	{
3809 		YM2610 *F2610 = &(FM2610[num]);
3810 		/* SSG registers */
3811 		for(r=0;r<16;r++)
3812 		{
3813 			SSGWrite(num,0,r);
3814 			SSGWrite(num,1,F2610->REGS[r]);
3815 		}
3816 
3817 		/* OPN registers */
3818 		/* DT / MULTI , TL , KS / AR , AMON / DR , SR , SL / RR , SSG-EG */
3819 		for(r=0x30;r<0x9e;r++)
3820 			if((r&3) != 3)
3821 			{
3822 				OPNWriteReg(&F2610->OPN,r,F2610->REGS[r]);
3823 				OPNWriteReg(&F2610->OPN,r|0x100,F2610->REGS[r|0x100]);
3824 			}
3825 		/* FB / CONNECT , L / R / AMS / PMS */
3826 		for(r=0xb0;r<0xb6;r++)
3827 			if((r&3) != 3)
3828 			{
3829 				OPNWriteReg(&F2610->OPN,r,F2610->REGS[r]);
3830 				OPNWriteReg(&F2610->OPN,r|0x100,F2610->REGS[r|0x100]);
3831 			}
3832 		/* FM channels */
3833 		/*FM_channel_postload(F2610->CH,6);*/
3834 
3835 		/* rhythm(ADPCMA) */
3836 		FM_ADPCMAWrite(F2610,1,F2610->REGS[0x101]);
3837 		for( r=0 ; r<6 ; r++)
3838 		{
3839 			FM_ADPCMAWrite(F2610,r+0x08,F2610->REGS[r+0x108]);
3840 			FM_ADPCMAWrite(F2610,r+0x10,F2610->REGS[r+0x110]);
3841 			FM_ADPCMAWrite(F2610,r+0x18,F2610->REGS[r+0x118]);
3842 			FM_ADPCMAWrite(F2610,r+0x20,F2610->REGS[r+0x120]);
3843 			FM_ADPCMAWrite(F2610,r+0x28,F2610->REGS[r+0x128]);
3844 		}
3845 		/* Delta-T ADPCM unit */
3846 		YM_DELTAT_postload(&F2610->deltaT , &F2610->REGS[0x010] );
3847 	}
3848 	cur_chip = NULL;
3849 }
3850 
YM2610_save_state(void)3851 static void YM2610_save_state(void)
3852 {
3853 	int num;
3854 	const char statename[] = "YM2610";
3855 
3856 	for(num=0;num<YM2610NumChips;num++)
3857 	{
3858 		YM2610 *F2610 = &(FM2610[num]);
3859 
3860 		state_save_register_UINT8 (statename, num, "regs"   , F2610->REGS   , 512);
3861 		FMsave_state_st(statename,num,&FM2610[num].OPN.ST);
3862 		FMsave_state_channel(statename,num,FM2610[num].CH,6);
3863 		/* 3slots */
3864 		state_save_register_UINT32(statename, num, "slot3fc" , F2610->OPN.SL3.fc   , 3);
3865 		state_save_register_UINT8 (statename, num, "slot3fh" , &F2610->OPN.SL3.fn_h, 1);
3866 		state_save_register_UINT8 (statename, num, "slot3kc" , F2610->OPN.SL3.kcode, 3);
3867 		/* address register1 */
3868 		state_save_register_UINT8 (statename, num, "addr_A1" , &F2610->addr_A1, 1);
3869 
3870 		state_save_register_UINT8 (statename, num, "arrivedFlag", &F2610->adpcm_arrivedEndAddress , 1);
3871 		/* rythm(ADPCMA) */
3872 		FMsave_state_adpcma(statename,num,F2610->adpcm);
3873 		/* Delta-T ADPCM unit */
3874 		YM_DELTAT_savestate(statename,num,&FM2610[num].deltaT);
3875 	}
3876 	state_save_register_func_postload(YM2610_postload);
3877 }
3878 #endif /* _STATE_H */
3879 
YM2610_deltat_status_set(UINT8 which,UINT8 changebits)3880 static void YM2610_deltat_status_set(UINT8 which, UINT8 changebits)
3881 {
3882 	FM2610[which].adpcm_arrivedEndAddress |= changebits;
3883 }
YM2610_deltat_status_reset(UINT8 which,UINT8 changebits)3884 static void YM2610_deltat_status_reset(UINT8 which, UINT8 changebits)
3885 {
3886 	FM2610[which].adpcm_arrivedEndAddress &= (~changebits);
3887 }
3888 
YM2610Init(int num,int clock,int rate,void ** pcmroma,int * pcmsizea,void ** pcmromb,int * pcmsizeb,FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)3889 int YM2610Init(int num, int clock, int rate,
3890                void **pcmroma,int *pcmsizea,void **pcmromb,int *pcmsizeb,
3891                FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)
3892 
3893 {
3894 	int i;
3895 
3896 	if (FM2610) return (-1);	/* duplicate init. */
3897 	cur_chip = NULL;	/* hiro-shi!! */
3898 
3899 	YM2610NumChips = num;
3900 
3901 	/* allocate extend state space */
3902 	if( (FM2610 = (YM2610 *)malloc(sizeof(YM2610) * YM2610NumChips))==NULL)
3903 		return (-1);
3904 	/* clear */
3905 	memset(FM2610,0,sizeof(YM2610) * YM2610NumChips);
3906 	/* allocate total level table (128kb space) */
3907 	if( !init_tables() )
3908 	{
3909 		if (FM2610) {
3910 			free( FM2610 );
3911 			FM2610 = NULL;
3912 		}
3913 		return (-1);
3914 	}
3915 
3916 	for ( i = 0 ; i < YM2610NumChips; i++ ) {
3917 		YM2610 *F2610 = &(FM2610[i]);
3918 		/* FM */
3919 		F2610->OPN.ST.index = i;
3920 		F2610->OPN.type = TYPE_YM2610;
3921 		F2610->OPN.P_CH = FM2610[i].CH;
3922 		F2610->OPN.ST.clock = clock;
3923 		F2610->OPN.ST.rate = rate;
3924 		/* Extend handler */
3925 		F2610->OPN.ST.Timer_Handler = TimerHandler;
3926 		F2610->OPN.ST.IRQ_Handler   = IRQHandler;
3927 		/* ADPCM */
3928 		F2610->pcmbuf   = (UINT8 *)(pcmroma[i]);
3929 		F2610->pcm_size = pcmsizea[i];
3930 		/* DELTA-T */
3931 		F2610->deltaT.memory = (UINT8 *)(pcmromb[i]);
3932 		F2610->deltaT.memory_size = pcmsizeb[i];
3933 
3934 		FM2610[i].deltaT.status_set_handler = YM2610_deltat_status_set;
3935 		FM2610[i].deltaT.status_reset_handler = YM2610_deltat_status_reset;
3936 		FM2610[i].deltaT.status_change_which_chip = i;
3937 		FM2610[i].deltaT.status_change_EOS_bit = 0x80;	/* status flag: set bit7 on End Of Sample */
3938 
3939 		YM2610ResetChip(i);
3940 	}
3941 	Init_ADPCMATable();
3942 #ifdef _STATE_H
3943 	YM2610_save_state();
3944 #endif
3945 	return 0;
3946 }
3947 
3948 /* remap sample memory of chip */
YM2610SetRom(int num,void * pcmroma,int pcmsizea,void * pcmromb,int pcmsizeb)3949 void YM2610SetRom(int num, void *pcmroma,int pcmsizea,void *pcmromb,int pcmsizeb)
3950 {
3951 	YM2610 *F2610 = &(FM2610[num]);
3952 
3953 	/* ADPCM */
3954 	F2610->pcmbuf   = (UINT8 *)pcmroma;
3955 	F2610->pcm_size = pcmsizea;
3956 	/* DELTA-T */
3957 	F2610->deltaT.memory = (UINT8 *)pcmromb;
3958 	F2610->deltaT.memory_size = pcmsizeb;
3959 
3960 	if( (void *)F2610 == cur_chip ){
3961 		pcmbufA  = F2610->pcmbuf;
3962 		pcmsizeA = F2610->pcm_size;
3963 	}
3964 }
3965 
3966 /* shut down emulator */
YM2610Shutdown()3967 void YM2610Shutdown()
3968 {
3969 	if (!FM2610) return;
3970 
3971 	FMCloseTable();
3972 	if (FM2610) {
3973 		free(FM2610);
3974 		FM2610 = NULL;
3975 	}
3976 }
3977 
3978 /* reset one of chip */
YM2610ResetChip(int num)3979 void YM2610ResetChip(int num)
3980 {
3981 	int i;
3982 	YM2610 *F2610 = &(FM2610[num]);
3983 	FM_OPN *OPN   = &(FM2610[num].OPN);
3984 	YM_DELTAT *DELTAT = &(FM2610[num].deltaT);
3985 
3986 	/* Reset Prescaler */
3987 	OPNSetPres( OPN, 6*24, 6*24, 4*2); /* OPN 1/6 , SSG 1/4 */
3988 	/* reset SSG section */
3989 	SSGReset(OPN->ST.index);
3990 	/* status clear */
3991 	FM_IRQMASK_SET(&OPN->ST,0x03);
3992 	FM_BUSY_CLEAR(&OPN->ST);
3993 	OPNWriteMode(OPN,0x27,0x30); /* mode 0 , timer reset */
3994 
3995 	OPN->eg_timer = 0;
3996 	OPN->eg_cnt   = 0;
3997 
3998 	FM_STATUS_RESET(&OPN->ST, 0xff);
3999 
4000 	reset_channels( &OPN->ST , F2610->CH , 6 );
4001 	/* reset OPerator paramater */
4002 	for(i = 0xb6 ; i >= 0xb4 ; i-- )
4003 	{
4004 		OPNWriteReg(OPN,i      ,0xc0);
4005 		OPNWriteReg(OPN,i|0x100,0xc0);
4006 	}
4007 	for(i = 0xb2 ; i >= 0x30 ; i-- )
4008 	{
4009 		OPNWriteReg(OPN,i      ,0);
4010 		OPNWriteReg(OPN,i|0x100,0);
4011 	}
4012 	for(i = 0x26 ; i >= 0x20 ; i-- ) OPNWriteReg(OPN,i,0);
4013 	/**** ADPCM work initial ****/
4014 	for( i = 0; i < 6 ; i++ ){
4015 		F2610->adpcm[i].step      = (UINT32)((float)(1<<ADPCM_SHIFT)*((float)F2610->OPN.ST.freqbase)/3.0f);
4016 		F2610->adpcm[i].now_addr  = 0;
4017 		F2610->adpcm[i].now_step  = 0;
4018 		F2610->adpcm[i].start     = 0;
4019 		F2610->adpcm[i].end       = 0;
4020 		/* F2610->adpcm[i].delta     = 21866; */
4021 		F2610->adpcm[i].vol_mul   = 0;
4022 		F2610->adpcm[i].pan       = &out_adpcm[OUTD_CENTER]; /* default center */
4023 		F2610->adpcm[i].flagMask  = 1<<i;
4024 		F2610->adpcm[i].flag      = 0;
4025 		F2610->adpcm[i].adpcm_acc = 0;
4026 		F2610->adpcm[i].adpcm_step= 0;
4027 		F2610->adpcm[i].adpcm_out = 0;
4028 	}
4029 	F2610->adpcmTL = 0x3f;
4030 
4031 	F2610->adpcm_arrivedEndAddress = 0;
4032 
4033 	/* DELTA-T unit */
4034 	DELTAT->freqbase = OPN->ST.freqbase;
4035 	DELTAT->output_pointer = out_delta;
4036 	DELTAT->portshift = 8;		/* allways 8bits shift */
4037 	DELTAT->output_range = 1<<23;
4038 	YM_DELTAT_ADPCM_Reset(DELTAT,OUTD_CENTER,YM_DELTAT_EMULATION_MODE_YM2610);
4039 }
4040 
4041 /* YM2610 write */
4042 /* n = number  */
4043 /* a = address */
4044 /* v = value   */
YM2610Write(int n,int a,UINT8 v)4045 int YM2610Write(int n, int a, UINT8 v)
4046 {
4047 	YM2610 *F2610 = &(FM2610[n]);
4048 	FM_OPN *OPN   = &(FM2610[n].OPN);
4049 	int addr;
4050 	int ch;
4051 
4052 	v &= 0xff;	/* adjust to 8 bit bus */
4053 
4054 	switch( a&3 ){
4055 	case 0:	/* address port 0 */
4056 		OPN->ST.address = v;
4057 		F2610->addr_A1 = 0;
4058 
4059 		/* Write register to SSG emulator */
4060 		if( v < 16 ) SSGWrite(n,0,v);
4061 		break;
4062 
4063 	case 1:	/* data port 0    */
4064 		if (F2610->addr_A1 != 0)
4065 			break;	/* verified on real YM2608 */
4066 
4067 		addr = OPN->ST.address;
4068 #ifdef _STATE_H
4069 		F2610->REGS[addr] = v;
4070 #endif
4071 		switch(addr & 0xf0)
4072 		{
4073 		case 0x00:	/* SSG section */
4074 			/* Write data to SSG emulator */
4075 			SSGWrite(n,a,v);
4076 			break;
4077 		case 0x10: /* DeltaT ADPCM */
4078 			YM2610UpdateReq(n);
4079 
4080 			switch(addr)
4081 			{
4082 			case 0x10:	/* control 1 */
4083 			case 0x11:	/* control 2 */
4084 			case 0x12:	/* start address L */
4085 			case 0x13:	/* start address H */
4086 			case 0x14:	/* stop address L */
4087 			case 0x15:	/* stop address H */
4088 
4089 			case 0x19:	/* delta-n L */
4090 			case 0x1a:	/* delta-n H */
4091 			case 0x1b:	/* volume */
4092 				{
4093 					YM_DELTAT_ADPCM_Write(&F2610->deltaT,addr-0x10,v);
4094 				}
4095 				break;
4096 
4097 			case 0x1c: /*  FLAG CONTROL : Extend Status Clear/Mask */
4098 				{
4099 					UINT8 statusmask = ~v;
4100 					/* set arrived flag mask */
4101 					for(ch=0;ch<6;ch++)
4102 						F2610->adpcm[ch].flagMask = statusmask&(1<<ch);
4103 
4104 					F2610->deltaT.status_change_EOS_bit = statusmask & 0x80;	/* status flag: set bit7 on End Of Sample */
4105 
4106 					/* clear arrived flag */
4107 					F2610->adpcm_arrivedEndAddress &= statusmask;
4108 				}
4109 				break;
4110 
4111 			default:
4112 				logerror("YM2610: write to unknown deltat register %02x val=%02x\n",addr,v);
4113 				break;
4114 			}
4115 
4116 			break;
4117 		case 0x20:	/* Mode Register */
4118 			YM2610UpdateReq(n);
4119 			OPNWriteMode(OPN,addr,v);
4120 			break;
4121 		default:	/* OPN section */
4122 			YM2610UpdateReq(n);
4123 			/* write register */
4124 			OPNWriteReg(OPN,addr,v);
4125 		}
4126 		break;
4127 
4128 	case 2:	/* address port 1 */
4129 		OPN->ST.address = v;
4130 		F2610->addr_A1 = 1;
4131 		break;
4132 
4133 	case 3:	/* data port 1    */
4134 		if (F2610->addr_A1 != 1)
4135 			break;	/* verified on real YM2608 */
4136 
4137 		YM2610UpdateReq(n);
4138 		addr = OPN->ST.address;
4139 #ifdef _STATE_H
4140 		F2610->REGS[addr | 0x100] = v;
4141 #endif
4142 		if( addr < 0x30 )
4143 			/* 100-12f : ADPCM A section */
4144 			FM_ADPCMAWrite(F2610,addr,v);
4145 		else
4146 			OPNWriteReg(OPN,addr | 0x100,v);
4147 	}
4148 	return OPN->ST.irq;
4149 }
4150 
YM2610Read(int n,int a)4151 UINT8 YM2610Read(int n,int a)
4152 {
4153 	YM2610 *F2610 = &(FM2610[n]);
4154 	int addr = F2610->OPN.ST.address;
4155 	UINT8 ret = 0;
4156 
4157 	switch( a&3){
4158 	case 0:	/* status 0 : YM2203 compatible */
4159 		ret = FM_STATUS_FLAG(&F2610->OPN.ST) & 0x83;
4160 		break;
4161 	case 1:	/* data 0 */
4162 		if( addr < 16 ) ret = SSGRead(n);
4163 		if( addr == 0xff ) ret = 0x01;
4164 		break;
4165 	case 2:	/* status 1 : ADPCM status */
4166 		/* ADPCM STATUS (arrived End Address) */
4167 		/* B,--,A5,A4,A3,A2,A1,A0 */
4168 		/* B     = ADPCM-B(DELTA-T) arrived end address */
4169 		/* A0-A5 = ADPCM-A          arrived end address */
4170 		ret = F2610->adpcm_arrivedEndAddress;
4171 		break;
4172 	case 3:
4173 		ret = 0;
4174 		break;
4175 	}
4176 	return ret;
4177 }
4178 
YM2610TimerOver(int n,int c)4179 int YM2610TimerOver(int n,int c)
4180 {
4181 	YM2610 *F2610 = &(FM2610[n]);
4182 
4183 	if( c )
4184 	{	/* Timer B */
4185 		TimerBOver( &(F2610->OPN.ST) );
4186 	}
4187 	else
4188 	{	/* Timer A */
4189 		YM2610UpdateReq(n);
4190 		/* timer update */
4191 		TimerAOver( &(F2610->OPN.ST) );
4192 		/* CSM mode key,TL controll */
4193 		if( F2610->OPN.ST.mode & 0x80 )
4194 		{	/* CSM mode total level latch and auto key on */
4195 			CSMKeyControll( F2610->OPN.type, &(F2610->CH[2]) );
4196 		}
4197 	}
4198 	return F2610->OPN.ST.irq;
4199 }
4200 
4201 #endif /* (BUILD_YM2610||BUILD_YM2610B) */
4202 
4203 
4204 
4205 #if BUILD_YM2612
4206 /*******************************************************************************/
4207 /*		YM2612 local section                                                   */
4208 /*******************************************************************************/
4209 /* here's the virtual YM2612 */
4210 typedef struct
4211 {
4212 	UINT8		REGS[512];			/* registers			*/
4213 	FM_OPN		OPN;				/* OPN state			*/
4214 	FM_CH		CH[6];				/* channel state		*/
4215 	UINT8		addr_A1;			/* address line A1		*/
4216 
4217 	/* dac output (YM2612) */
4218 	int			dacen;
4219 	INT32		dacout;
4220 } YM2612;
4221 
4222 static int YM2612NumChips;	/* total chip */
4223 static YM2612 *FM2612=NULL;	/* array of YM2612's */
4224 
4225 static int dacen;
4226 
4227 /* Generate samples for one of the YM2612s */
YM2612UpdateOne(int num,INT16 ** buffer,int length)4228 void YM2612UpdateOne(int num, INT16 **buffer, int length)
4229 {
4230 	YM2612 *F2612 = &(FM2612[num]);
4231 	FM_OPN *OPN   = &(FM2612[num].OPN);
4232 	int i;
4233 	FMSAMPLE  *bufL,*bufR;
4234 	INT32 dacout  = F2612->dacout;
4235 
4236 	/* set bufer */
4237 	bufL = buffer[0];
4238 	bufR = buffer[1];
4239 
4240 	if( (void *)F2612 != cur_chip ){
4241 		cur_chip = (void *)F2612;
4242 		State = &OPN->ST;
4243 		cch[0]   = &F2612->CH[0];
4244 		cch[1]   = &F2612->CH[1];
4245 		cch[2]   = &F2612->CH[2];
4246 		cch[3]   = &F2612->CH[3];
4247 		cch[4]   = &F2612->CH[4];
4248 		cch[5]   = &F2612->CH[5];
4249 		/* DAC mode */
4250 		dacen = F2612->dacen;
4251 
4252 	}
4253 
4254 	/* refresh PG and EG */
4255 	refresh_fc_eg_chan( OPN, cch[0] );
4256 	refresh_fc_eg_chan( OPN, cch[1] );
4257 	if( (State->mode & 0xc0) )
4258 	{
4259 		/* 3SLOT MODE */
4260 		if( cch[2]->SLOT[SLOT1].Incr==-1)
4261 		{
4262 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT1] , OPN->SL3.fc[1] , OPN->SL3.kcode[1] );
4263 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT2] , OPN->SL3.fc[2] , OPN->SL3.kcode[2] );
4264 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT3] , OPN->SL3.fc[0] , OPN->SL3.kcode[0] );
4265 			refresh_fc_eg_slot(OPN, &cch[2]->SLOT[SLOT4] , cch[2]->fc , cch[2]->kcode );
4266 		}
4267 	}else refresh_fc_eg_chan( OPN, cch[2] );
4268 	refresh_fc_eg_chan( OPN, cch[3] );
4269 	refresh_fc_eg_chan( OPN, cch[4] );
4270 	refresh_fc_eg_chan( OPN, cch[5] );
4271 
4272 	/* buffering */
4273 	for(i=0; i < length ; i++)
4274 	{
4275 
4276 		advance_lfo(OPN);
4277 
4278 		/* clear outputs */
4279 		out_fm[0] = 0;
4280 		out_fm[1] = 0;
4281 		out_fm[2] = 0;
4282 		out_fm[3] = 0;
4283 		out_fm[4] = 0;
4284 		out_fm[5] = 0;
4285 
4286 		/* calculate FM */
4287 		chan_calc(OPN, cch[0], 0 );
4288 		chan_calc(OPN, cch[1], 1 );
4289 		chan_calc(OPN, cch[2], 2 );
4290 		chan_calc(OPN, cch[3], 3 );
4291 		chan_calc(OPN, cch[4], 4 );
4292 		if( dacen )
4293 			*cch[5]->connect4 += dacout;
4294 		else
4295 			chan_calc(OPN, cch[5], 5 );
4296 
4297 		/* advance envelope generator */
4298 		OPN->eg_timer += OPN->eg_timer_add;
4299 		while (OPN->eg_timer >= OPN->eg_timer_overflow)
4300 		{
4301 			OPN->eg_timer -= OPN->eg_timer_overflow;
4302 			OPN->eg_cnt++;
4303 
4304 			advance_eg_channel(OPN, &cch[0]->SLOT[SLOT1]);
4305 			advance_eg_channel(OPN, &cch[1]->SLOT[SLOT1]);
4306 			advance_eg_channel(OPN, &cch[2]->SLOT[SLOT1]);
4307 			advance_eg_channel(OPN, &cch[3]->SLOT[SLOT1]);
4308 			advance_eg_channel(OPN, &cch[4]->SLOT[SLOT1]);
4309 			advance_eg_channel(OPN, &cch[5]->SLOT[SLOT1]);
4310 		}
4311 
4312 		{
4313 			int lt,rt;
4314 
4315 			lt  = ((out_fm[0]>>0) & OPN->pan[0]);
4316 			rt  = ((out_fm[0]>>0) & OPN->pan[1]);
4317 			lt += ((out_fm[1]>>0) & OPN->pan[2]);
4318 			rt += ((out_fm[1]>>0) & OPN->pan[3]);
4319 			lt += ((out_fm[2]>>0) & OPN->pan[4]);
4320 			rt += ((out_fm[2]>>0) & OPN->pan[5]);
4321 			lt += ((out_fm[3]>>0) & OPN->pan[6]);
4322 			rt += ((out_fm[3]>>0) & OPN->pan[7]);
4323 			lt += ((out_fm[4]>>0) & OPN->pan[8]);
4324 			rt += ((out_fm[4]>>0) & OPN->pan[9]);
4325 			lt += ((out_fm[5]>>0) & OPN->pan[10]);
4326 			rt += ((out_fm[5]>>0) & OPN->pan[11]);
4327 
4328 			lt >>= FINAL_SH;
4329 			rt >>= FINAL_SH;
4330 
4331 			Limit( lt, MAXOUT, MINOUT );
4332 			Limit( rt, MAXOUT, MINOUT );
4333 
4334 			#ifdef SAVE_SAMPLE
4335 				SAVE_ALL_CHANNELS
4336 			#endif
4337 
4338 			/* buffering */
4339 			bufL[i] = lt;
4340 			bufR[i] = rt;
4341 		}
4342 
4343 		/* timer A control */
4344 		INTERNAL_TIMER_A( State , cch[2] )
4345 	}
4346 	INTERNAL_TIMER_B(State,length)
4347 
4348 }
4349 
4350 #ifdef _STATE_H
YM2612_postload(void)4351 static void YM2612_postload(void)
4352 {
4353 	int num , r;
4354 
4355 	for(num=0;num<YM2612NumChips;num++)
4356 	{
4357 		/* DAC data & port */
4358 		FM2612[num].dacout = ((int)FM2612[num].REGS[0x2a] - 0x80) << 6;	/* level unknown */
4359 		FM2612[num].dacen  = FM2612[num].REGS[0x2b] & 0x80;
4360 		/* OPN registers */
4361 		/* DT / MULTI , TL , KS / AR , AMON / DR , SR , SL / RR , SSG-EG */
4362 		for(r=0x30;r<0x9e;r++)
4363 			if((r&3) != 3)
4364 			{
4365 				OPNWriteReg(&FM2612[num].OPN,r,FM2612[num].REGS[r]);
4366 				OPNWriteReg(&FM2612[num].OPN,r|0x100,FM2612[num].REGS[r|0x100]);
4367 			}
4368 		/* FB / CONNECT , L / R / AMS / PMS */
4369 		for(r=0xb0;r<0xb6;r++)
4370 			if((r&3) != 3)
4371 			{
4372 				OPNWriteReg(&FM2612[num].OPN,r,FM2612[num].REGS[r]);
4373 				OPNWriteReg(&FM2612[num].OPN,r|0x100,FM2612[num].REGS[r|0x100]);
4374 			}
4375 		/* channels */
4376 		/*FM_channel_postload(FM2612[num].CH,6);*/
4377 	}
4378 	cur_chip = NULL;
4379 }
4380 
YM2612_save_state(void)4381 static void YM2612_save_state(void)
4382 {
4383 	int num;
4384 	const char statename[] = "YM2612";
4385 
4386 	for(num=0;num<YM2612NumChips;num++)
4387 	{
4388 		state_save_register_UINT8 (statename, num, "regs"   , FM2612[num].REGS   , 512);
4389 		FMsave_state_st(statename,num,&FM2612[num].OPN.ST);
4390 		FMsave_state_channel(statename,num,FM2612[num].CH,6);
4391 		/* 3slots */
4392 		state_save_register_UINT32 (statename, num, "slot3fc" , FM2612[num].OPN.SL3.fc ,   3);
4393 		state_save_register_UINT8  (statename, num, "slot3fh" , &FM2612[num].OPN.SL3.fn_h, 1);
4394 		state_save_register_UINT8  (statename, num, "slot3kc" , FM2612[num].OPN.SL3.kcode, 3);
4395 		/* address register1 */
4396 		state_save_register_UINT8 (statename, num, "addr_A1" , &FM2612[num].addr_A1, 1);
4397 	}
4398 	state_save_register_func_postload(YM2612_postload);
4399 }
4400 #endif /* _STATE_H */
4401 
4402 /* initialize YM2612 emulator(s) */
YM2612Init(int num,int clock,int rate,FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)4403 int YM2612Init(int num, int clock, int rate,
4404                FM_TIMERHANDLER TimerHandler,FM_IRQHANDLER IRQHandler)
4405 {
4406 	int i;
4407 
4408 	if (FM2612) return (-1);	/* duplicate init. */
4409 	cur_chip = NULL;	/* hiro-shi!! */
4410 
4411 	YM2612NumChips = num;
4412 
4413 	/* allocate extend state space */
4414 	if( (FM2612 = (YM2612 *)malloc(sizeof(YM2612) * YM2612NumChips))==NULL)
4415 		return (-1);
4416 	/* clear */
4417 	memset(FM2612,0,sizeof(YM2612) * YM2612NumChips);
4418 	/* allocate total level table (128kb space) */
4419 	if( !init_tables() )
4420 	{
4421 		if (FM2612) {
4422 			free( FM2612 );
4423 			FM2612 = NULL;
4424 		}
4425 		return (-1);
4426 	}
4427 
4428 	for ( i = 0 ; i < YM2612NumChips; i++ ) {
4429 		FM2612[i].OPN.ST.index = i;
4430 		FM2612[i].OPN.type = TYPE_YM2612;
4431 		FM2612[i].OPN.P_CH = FM2612[i].CH;
4432 		FM2612[i].OPN.ST.clock = clock;
4433 		FM2612[i].OPN.ST.rate = rate;
4434 		/* FM2612[i].OPN.ST.irq = 0; */
4435 		/* FM2612[i].OPN.ST.status = 0; */
4436 		/* Extend handler */
4437 		FM2612[i].OPN.ST.Timer_Handler = TimerHandler;
4438 		FM2612[i].OPN.ST.IRQ_Handler   = IRQHandler;
4439 		YM2612ResetChip(i);
4440 	}
4441 #ifdef _STATE_H
4442 	YM2612_save_state();
4443 #endif
4444 	return 0;
4445 }
4446 
4447 /* shut down emulator */
YM2612Shutdown()4448 void YM2612Shutdown()
4449 {
4450 	if (!FM2612) return;
4451 
4452 	FMCloseTable();
4453 	if (FM2612) {
4454 		free(FM2612);
4455 		FM2612 = NULL;
4456 	}
4457 }
4458 
4459 /* reset one of chip */
YM2612ResetChip(int num)4460 void YM2612ResetChip(int num)
4461 {
4462 	int i;
4463 	YM2612 *F2612 = &(FM2612[num]);
4464 	FM_OPN *OPN   = &(FM2612[num].OPN);
4465 
4466 	OPNSetPres( OPN, 6*24, 6*24, 0);
4467 	/* status clear */
4468 	FM_IRQMASK_SET(&OPN->ST,0x03);
4469 	FM_BUSY_CLEAR(&OPN->ST);
4470 	OPNWriteMode(OPN,0x27,0x30); /* mode 0 , timer reset */
4471 
4472 	OPN->eg_timer = 0;
4473 	OPN->eg_cnt   = 0;
4474 
4475 	FM_STATUS_RESET(&OPN->ST, 0xff);
4476 
4477 	reset_channels( &OPN->ST , &F2612->CH[0] , 6 );
4478 	for(i = 0xb6 ; i >= 0xb4 ; i-- )
4479 	{
4480 		OPNWriteReg(OPN,i      ,0xc0);
4481 		OPNWriteReg(OPN,i|0x100,0xc0);
4482 	}
4483 	for(i = 0xb2 ; i >= 0x30 ; i-- )
4484 	{
4485 		OPNWriteReg(OPN,i      ,0);
4486 		OPNWriteReg(OPN,i|0x100,0);
4487 	}
4488 	for(i = 0x26 ; i >= 0x20 ; i-- ) OPNWriteReg(OPN,i,0);
4489 	/* DAC mode clear */
4490 	F2612->dacen = 0;
4491 }
4492 
4493 /* YM2612 write */
4494 /* n = number  */
4495 /* a = address */
4496 /* v = value   */
YM2612Write(int n,int a,UINT8 v)4497 int YM2612Write(int n, int a, UINT8 v)
4498 {
4499 	YM2612 *F2612 = &(FM2612[n]);
4500 	int addr;
4501 
4502 	v &= 0xff;	/* adjust to 8 bit bus */
4503 
4504 	switch( a&3){
4505 	case 0:	/* address port 0 */
4506 		F2612->OPN.ST.address = v;
4507 		F2612->addr_A1 = 0;
4508 		break;
4509 
4510 	case 1:	/* data port 0    */
4511 		if (F2612->addr_A1 != 0)
4512 			break;	/* verified on real YM2608 */
4513 
4514 		addr = F2612->OPN.ST.address;
4515 #ifdef _STATE_H
4516 		F2612->REGS[addr] = v;
4517 #endif
4518 		switch( addr & 0xf0 )
4519 		{
4520 		case 0x20:	/* 0x20-0x2f Mode */
4521 			switch( addr )
4522 			{
4523 			case 0x2a:	/* DAC data (YM2612) */
4524 				YM2612UpdateReq(n);
4525 				F2612->dacout = ((int)v - 0x80) << 6;	/* level unknown */
4526 				break;
4527 			case 0x2b:	/* DAC Sel  (YM2612) */
4528 				/* b7 = dac enable */
4529 				F2612->dacen = v & 0x80;
4530 				cur_chip = NULL;
4531 				break;
4532 			default:	/* OPN section */
4533 				YM2612UpdateReq(n);
4534 				/* write register */
4535 				OPNWriteMode(&(F2612->OPN),addr,v);
4536 			}
4537 			break;
4538 		default:	/* 0x30-0xff OPN section */
4539 			YM2612UpdateReq(n);
4540 			/* write register */
4541 			OPNWriteReg(&(F2612->OPN),addr,v);
4542 		}
4543 		break;
4544 
4545 	case 2:	/* address port 1 */
4546 		F2612->OPN.ST.address = v;
4547 		F2612->addr_A1 = 1;
4548 		break;
4549 
4550 	case 3:	/* data port 1    */
4551 		if (F2612->addr_A1 != 1)
4552 			break;	/* verified on real YM2608 */
4553 
4554 		addr = F2612->OPN.ST.address;
4555 #ifdef _STATE_H
4556 		F2612->REGS[addr | 0x100] = v;
4557 #endif
4558 		YM2612UpdateReq(n);
4559 		OPNWriteReg(&(F2612->OPN),addr | 0x100,v);
4560 		break;
4561 	}
4562 	return F2612->OPN.ST.irq;
4563 }
4564 
YM2612Read(int n,int a)4565 UINT8 YM2612Read(int n,int a)
4566 {
4567 	YM2612 *F2612 = &(FM2612[n]);
4568 
4569 	switch( a&3){
4570 	case 0:	/* status 0 */
4571 		return FM_STATUS_FLAG(&F2612->OPN.ST);
4572 	case 1:
4573 	case 2:
4574 	case 3:
4575 		LOG(LOG_WAR,("YM2612 #%d:A=%d read unmapped area\n",n,a));
4576 		return FM_STATUS_FLAG(&F2612->OPN.ST);
4577 	}
4578 	return 0;
4579 }
4580 
YM2612TimerOver(int n,int c)4581 int YM2612TimerOver(int n,int c)
4582 {
4583 	YM2612 *F2612 = &(FM2612[n]);
4584 
4585 	if( c )
4586 	{	/* Timer B */
4587 		TimerBOver( &(F2612->OPN.ST) );
4588 	}
4589 	else
4590 	{	/* Timer A */
4591 		YM2612UpdateReq(n);
4592 		/* timer update */
4593 		TimerAOver( &(F2612->OPN.ST) );
4594 		/* CSM mode key,TL controll */
4595 		if( F2612->OPN.ST.mode & 0x80 )
4596 		{	/* CSM mode total level latch and auto key on */
4597 			CSMKeyControll( F2612->OPN.type, &(F2612->CH[2]) );
4598 		}
4599 	}
4600 	return F2612->OPN.ST.irq;
4601 }
4602 
4603 #endif /* BUILD_YM2612 */
4604